summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--Demo/embed/demo.c64
-rw-r--r--Demo/embed/loop.c38
-rw-r--r--Demo/pysvr/pysvr.c498
-rw-r--r--Include/abstract.h948
-rw-r--r--Include/ceval.h56
-rw-r--r--Include/datetime.h118
-rw-r--r--Include/descrobject.h60
-rw-r--r--Include/dictobject.h64
-rw-r--r--Include/fileobject.h44
-rw-r--r--Include/object.h566
-rw-r--r--Include/objimpl.h152
-rw-r--r--Include/pyerrors.h68
-rw-r--r--Include/pymacconfig.h76
-rw-r--r--Include/pyport.h240
-rw-r--r--Include/pythonrun.h42
-rw-r--r--Include/setobject.h62
-rw-r--r--Include/structmember.h68
-rw-r--r--Include/symtable.h66
-rw-r--r--Include/unicodeobject.h480
-rw-r--r--Mac/Modules/ColorPickermodule.c76
-rw-r--r--Mac/Modules/MacOS.c994
-rw-r--r--Mac/Modules/Nav.c1288
-rw-r--r--Mac/Modules/OSATerminology.c122
-rw-r--r--Mac/Modules/_scproxy.c374
-rw-r--r--Mac/Modules/ae/_AEmodule.c2092
-rw-r--r--Mac/Modules/ah/_AHmodule.c178
-rw-r--r--Mac/Modules/app/_Appmodule.c2718
-rw-r--r--Mac/Modules/autoGIL.c196
-rwxr-xr-xMac/Modules/carbonevt/_CarbonEvtmodule.c2936
-rw-r--r--Mac/Modules/cf/_CFmodule.c6772
-rw-r--r--Mac/Modules/cf/pycfbridge.c466
-rwxr-xr-xMac/Modules/cg/CFMLateImport.c2376
-rwxr-xr-xMac/Modules/cg/CFMLateImport.h462
-rwxr-xr-xMac/Modules/cg/_CGmodule.c1882
-rw-r--r--Mac/Modules/cm/_Cmmodule.c1220
-rw-r--r--Mac/Modules/ctl/_Ctlmodule.c8516
-rw-r--r--Mac/Modules/dlg/_Dlgmodule.c2188
-rw-r--r--Mac/Modules/drag/_Dragmodule.c1578
-rw-r--r--Mac/Modules/evt/_Evtmodule.c706
-rw-r--r--Mac/Modules/file/_Filemodule.c4752
-rw-r--r--Mac/Modules/fm/_Fmmodule.c432
-rw-r--r--Mac/Modules/folder/_Foldermodule.c510
-rw-r--r--Mac/Modules/gestaltmodule.c30
-rw-r--r--Mac/Modules/help/_Helpmodule.c242
-rw-r--r--Mac/Modules/ibcarbon/_IBCarbon.c318
-rw-r--r--Mac/Modules/icgluemodule.c498
-rw-r--r--Mac/Modules/icn/_Icnmodule.c2384
-rw-r--r--Mac/Modules/launch/_Launchmodule.c702
-rw-r--r--Mac/Modules/list/_Listmodule.c1618
-rw-r--r--Mac/Modules/menu/_Menumodule.c4914
-rw-r--r--Mac/Modules/mlte/_Mltemodule.c2272
-rw-r--r--Mac/Modules/osa/_OSAmodule.c1268
-rw-r--r--Mac/Modules/qd/_Qdmodule.c9856
-rw-r--r--Mac/Modules/qdoffs/_Qdoffsmodule.c922
-rw-r--r--Mac/Modules/qt/_Qtmodule.c41936
-rw-r--r--Mac/Modules/res/_Resmodule.c2504
-rw-r--r--Mac/Modules/scrap/_Scrapmodule.c474
-rw-r--r--Mac/Modules/snd/_Sndihooks.c578
-rw-r--r--Mac/Modules/snd/_Sndmodule.c1640
-rw-r--r--Mac/Modules/te/_TEmodule.c1646
-rw-r--r--Mac/Modules/win/_Winmodule.c4564
-rw-r--r--Mac/Tools/pythonw.c170
-rw-r--r--Misc/setuid-prog.c152
-rw-r--r--Modules/_bisectmodule.c284
-rw-r--r--Modules/_bsddb.c346
-rw-r--r--Modules/_codecsmodule.c680
-rw-r--r--Modules/_collectionsmodule.c2360
-rw-r--r--Modules/_csv.c2188
-rw-r--r--Modules/_ctypes/_ctypes.c8610
-rw-r--r--Modules/_ctypes/_ctypes_test.c434
-rw-r--r--Modules/_ctypes/callbacks.c964
-rw-r--r--Modules/_ctypes/callproc.c2522
-rw-r--r--Modules/_ctypes/cfield.c2030
-rw-r--r--Modules/_ctypes/ctypes.h332
-rw-r--r--Modules/_ctypes/darwin/dlfcn_simple.c282
-rw-r--r--Modules/_ctypes/malloc_closure.c98
-rw-r--r--Modules/_ctypes/stgdict.c952
-rw-r--r--Modules/_curses_panel.c180
-rw-r--r--Modules/_functoolsmodule.c574
-rw-r--r--Modules/_hashopenssl.c60
-rw-r--r--Modules/_heapqmodule.c892
-rw-r--r--Modules/_hotshot.c186
-rw-r--r--Modules/_localemodule.c156
-rw-r--r--Modules/_lsprof.c1152
-rw-r--r--Modules/_math.c206
-rw-r--r--Modules/_multiprocessing/connection.h738
-rw-r--r--Modules/_multiprocessing/multiprocessing.c396
-rw-r--r--Modules/_multiprocessing/multiprocessing.h30
-rw-r--r--Modules/_multiprocessing/pipe_connection.c194
-rw-r--r--Modules/_multiprocessing/semaphore.c892
-rw-r--r--Modules/_multiprocessing/socket_connection.c258
-rw-r--r--Modules/_multiprocessing/win32_functions.c342
-rw-r--r--Modules/_randommodule.c774
-rw-r--r--Modules/_struct.c2518
-rw-r--r--Modules/_testcapimodule.c2802
-rw-r--r--Modules/_tkinter.c4204
-rw-r--r--Modules/addrinfo.h106
-rw-r--r--Modules/almodule.c4122
-rw-r--r--Modules/arraymodule.c3030
-rw-r--r--Modules/audioop.c2452
-rw-r--r--Modules/binascii.c2262
-rw-r--r--Modules/bsddbmodule.c1294
-rw-r--r--Modules/bz2module.c3320
-rw-r--r--Modules/cPickle.c9002
-rw-r--r--Modules/cStringIO.c736
-rw-r--r--Modules/cdmodule.c1048
-rw-r--r--Modules/cgensupport.c454
-rw-r--r--Modules/cgensupport.h28
-rw-r--r--Modules/cjkcodecs/_codecs_cn.c634
-rw-r--r--Modules/cjkcodecs/_codecs_hk.c256
-rw-r--r--Modules/cjkcodecs/_codecs_iso2022.c1622
-rw-r--r--Modules/cjkcodecs/_codecs_jp.c1204
-rw-r--r--Modules/cjkcodecs/_codecs_kr.c602
-rw-r--r--Modules/cjkcodecs/_codecs_tw.c140
-rw-r--r--Modules/cjkcodecs/alg_jisx0201.h46
-rw-r--r--Modules/cjkcodecs/cjkcodecs.h550
-rw-r--r--Modules/cjkcodecs/emu_jisx0213_2000.h58
-rw-r--r--Modules/cjkcodecs/multibytecodec.c2824
-rw-r--r--Modules/cjkcodecs/multibytecodec.h132
-rw-r--r--Modules/clmodule.c3450
-rw-r--r--Modules/cmathmodule.c1600
-rw-r--r--Modules/cryptmodule.c22
-rw-r--r--Modules/datetimemodule.c6722
-rw-r--r--Modules/dbmmodule.c532
-rw-r--r--Modules/dlmodule.c344
-rw-r--r--Modules/errnomodule.c504
-rw-r--r--Modules/fcntlmodule.c680
-rw-r--r--Modules/flmodule.c1950
-rw-r--r--Modules/fmmodule.c268
-rw-r--r--Modules/fpectlmodule.c66
-rw-r--r--Modules/future_builtins.c56
-rw-r--r--Modules/gcmodule.c1762
-rw-r--r--Modules/getaddrinfo.c884
-rw-r--r--Modules/getbuildinfo.c26
-rw-r--r--Modules/getnameinfo.c254
-rw-r--r--Modules/getpath.c102
-rw-r--r--Modules/glmodule.c8980
-rw-r--r--Modules/imageop.c1264
-rw-r--r--Modules/imgfile.c776
-rw-r--r--Modules/itertoolsmodule.c6084
-rw-r--r--Modules/linuxaudiodev.c202
-rw-r--r--Modules/main.c948
-rw-r--r--Modules/mathmodule.c1870
-rw-r--r--Modules/md5.c130
-rw-r--r--Modules/md5module.c232
-rw-r--r--Modules/mmapmodule.c2112
-rw-r--r--Modules/nismodule.c546
-rw-r--r--Modules/operator.c796
-rw-r--r--Modules/parsermodule.c198
-rw-r--r--Modules/puremodule.c596
-rw-r--r--Modules/pwdmodule.c182
-rw-r--r--Modules/pyexpat.c352
-rw-r--r--Modules/readline.c1018
-rw-r--r--Modules/resource.c372
-rw-r--r--Modules/rotatingtree.c160
-rw-r--r--Modules/selectmodule.c2438
-rw-r--r--Modules/sgimodule.c52
-rw-r--r--Modules/sha256module.c118
-rw-r--r--Modules/sha512module.c138
-rw-r--r--Modules/shamodule.c120
-rw-r--r--Modules/signalmodule.c840
-rw-r--r--Modules/socketmodule.c6234
-rw-r--r--Modules/socketmodule.h104
-rw-r--r--Modules/spwdmodule.c150
-rw-r--r--Modules/stropmodule.c1822
-rw-r--r--Modules/sunaudiodev.c570
-rw-r--r--Modules/svmodule.c1232
-rw-r--r--Modules/symtablemodule.c114
-rw-r--r--Modules/syslogmodule.c378
-rw-r--r--Modules/termios.c886
-rw-r--r--Modules/testcapi_long.h348
-rw-r--r--Modules/threadmodule.c930
-rw-r--r--Modules/timemodule.c1188
-rw-r--r--Modules/timingmodule.c36
-rw-r--r--Modules/tkappinit.c188
-rw-r--r--Modules/unicodedata.c266
-rw-r--r--Modules/xxmodule.c496
-rw-r--r--Modules/xxsubtype.c394
-rw-r--r--Modules/yuv.h86
-rw-r--r--Modules/yuvconvert.c184
-rw-r--r--Modules/zipimport.c1720
-rw-r--r--Modules/zlibmodule.c474
-rw-r--r--Objects/abstract.c4496
-rw-r--r--Objects/boolobject.c248
-rw-r--r--Objects/bufferobject.c1346
-rw-r--r--Objects/bytes_methods.c246
-rw-r--r--Objects/cellobject.c176
-rw-r--r--Objects/classobject.c4144
-rw-r--r--Objects/codeobject.c944
-rw-r--r--Objects/complexobject.c1942
-rw-r--r--Objects/descrobject.c1788
-rw-r--r--Objects/dictobject.c4412
-rw-r--r--Objects/enumobject.c590
-rw-r--r--Objects/exceptions.c48
-rw-r--r--Objects/fileobject.c4004
-rw-r--r--Objects/floatobject.c4158
-rw-r--r--Objects/frameobject.c1462
-rw-r--r--Objects/funcobject.c1186
-rw-r--r--Objects/genobject.c600
-rw-r--r--Objects/intobject.c2152
-rw-r--r--Objects/iterobject.c328
-rw-r--r--Objects/listobject.c4498
-rw-r--r--Objects/longobject.c6748
-rw-r--r--Objects/methodobject.c564
-rw-r--r--Objects/moduleobject.c368
-rw-r--r--Objects/object.c3226
-rw-r--r--Objects/obmalloc.c2142
-rw-r--r--Objects/rangeobject.c420
-rw-r--r--Objects/setobject.c3646
-rw-r--r--Objects/sliceobject.c470
-rw-r--r--Objects/stringlib/string_format.h178
-rw-r--r--Objects/stringobject.c6612
-rw-r--r--Objects/structseq.c822
-rw-r--r--Objects/tupleobject.c1508
-rw-r--r--Objects/typeobject.c10212
-rw-r--r--Objects/weakrefobject.c110
-rw-r--r--PC/VS7.1/make_buildinfo.c126
-rw-r--r--PC/VS8.0/make_buildinfo.c128
-rw-r--r--PC/_msi.c752
-rw-r--r--PC/_subprocess.c748
-rw-r--r--PC/_winreg.c2144
-rw-r--r--PC/bdist_wininst/archive.h94
-rw-r--r--PC/bdist_wininst/extract.c534
-rw-r--r--PC/bdist_wininst/install.c4160
-rw-r--r--PC/config.c144
-rw-r--r--PC/dl_nt.c90
-rw-r--r--PC/errmap.h148
-rw-r--r--PC/frozen_dllmain.c116
-rw-r--r--PC/generrmap.c24
-rw-r--r--PC/getpathp.c952
-rw-r--r--PC/import_nt.c122
-rw-r--r--PC/make_versioninfo.c26
-rwxr-xr-xPC/msvcrtmodule.c358
-rw-r--r--PC/os2emx/config.c130
-rw-r--r--PC/os2emx/dlfcn.c286
-rw-r--r--PC/os2emx/dllentry.c44
-rw-r--r--PC/os2emx/getpathp.c480
-rw-r--r--PC/os2emx/pythonpm.c144
-rw-r--r--PC/os2vacpp/getpathp.c636
-rw-r--r--PC/winsound.c122
-rw-r--r--PCbuild/make_buildinfo.c128
-rw-r--r--Parser/acceler.c168
-rw-r--r--Parser/bitset.c58
-rw-r--r--Parser/firstsets.c180
-rw-r--r--Parser/grammar.c380
-rw-r--r--Parser/grammar1.c70
-rw-r--r--Parser/intrcheck.c72
-rw-r--r--Parser/listnode.c78
-rw-r--r--Parser/metagrammar.c170
-rw-r--r--Parser/myreadline.c246
-rw-r--r--Parser/node.c122
-rw-r--r--Parser/parser.c534
-rw-r--r--Parser/parsetok.c362
-rw-r--r--Parser/pgen.c964
-rw-r--r--Parser/pgenmain.c194
-rw-r--r--Parser/printgrammar.c152
-rw-r--r--Parser/tokenizer.c2740
-rw-r--r--Parser/tokenizer.h82
-rw-r--r--Python/asdl.c88
-rw-r--r--Python/atof.c74
-rw-r--r--Python/bltinmodule.c4340
-rw-r--r--Python/ceval.c7928
-rw-r--r--Python/codecs.c804
-rw-r--r--Python/compile.c6256
-rw-r--r--Python/dynload_aix.c280
-rw-r--r--Python/dynload_atheos.c62
-rw-r--r--Python/dynload_beos.c302
-rw-r--r--Python/dynload_hpux.c74
-rw-r--r--Python/dynload_next.c150
-rw-r--r--Python/dynload_os2.c58
-rw-r--r--Python/dynload_shlib.c152
-rw-r--r--Python/dynload_win.c412
-rw-r--r--Python/errors.c1112
-rw-r--r--Python/frozen.c26
-rw-r--r--Python/frozenmain.c72
-rw-r--r--Python/future.c228
-rw-r--r--Python/getargs.c3112
-rw-r--r--Python/getcwd.c74
-rw-r--r--Python/getopt.c150
-rw-r--r--Python/import.c4788
-rw-r--r--Python/importdl.c100
-rw-r--r--Python/importdl.h28
-rw-r--r--Python/mactoolboxglue.c332
-rw-r--r--Python/marshal.c2178
-rw-r--r--Python/modsupport.c964
-rw-r--r--Python/mysnprintf.c112
-rw-r--r--Python/mystrtoul.c466
-rw-r--r--Python/peephole.c1182
-rw-r--r--Python/pyarena.c300
-rw-r--r--Python/pymath.c48
-rw-r--r--Python/pystate.c722
-rw-r--r--Python/pystrcmp.c24
-rw-r--r--Python/pystrtod.c1966
-rw-r--r--Python/pythonrun.c2650
-rw-r--r--Python/strtod.c206
-rw-r--r--Python/structmember.c642
-rw-r--r--Python/symtable.c2440
-rw-r--r--Python/sysmodule.c1938
-rw-r--r--Python/thread.c264
-rw-r--r--Python/thread_atheos.h242
-rw-r--r--Python/thread_beos.h310
-rw-r--r--Python/thread_cthread.h94
-rw-r--r--Python/thread_foobar.h44
-rw-r--r--Python/thread_lwp.h122
-rw-r--r--Python/thread_nt.h328
-rw-r--r--Python/thread_os2.h280
-rw-r--r--Python/thread_pth.h192
-rw-r--r--Python/thread_pthread.h438
-rw-r--r--Python/thread_sgi.h358
-rw-r--r--Python/thread_solaris.h142
-rw-r--r--Python/thread_wince.h70
-rw-r--r--Python/traceback.c424
-rw-r--r--RISCOS/Modules/config.c28
-rw-r--r--RISCOS/Modules/getpath_riscos.c60
-rw-r--r--RISCOS/Modules/riscosmodule.c530
-rw-r--r--RISCOS/Python/dynload_riscos.c26
-rw-r--r--RISCOS/sleep.c50
-rw-r--r--Tools/msi/msisupport.c112
318 files changed, 206646 insertions, 206646 deletions
diff --git a/Demo/embed/demo.c b/Demo/embed/demo.c
index 6005f13..55bc808 100644
--- a/Demo/embed/demo.c
+++ b/Demo/embed/demo.c
@@ -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);
}
diff --git a/Demo/embed/loop.c b/Demo/embed/loop.c
index d5af829..2f7fe62 100644
--- a/Demo/embed/loop.c
+++ b/Demo/embed/loop.c
@@ -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;
}
diff --git a/Demo/pysvr/pysvr.c b/Demo/pysvr/pysvr.c
index cced6da..706cd2a 100644
--- a/Demo/pysvr/pysvr.c
+++ b/Demo/pysvr/pysvr.c
@@ -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;
-
- 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();
- }
- }
-
- 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);
-
- fprintf(stderr, "Bye.\n");
-
- exit(0);
+ int port = PORT;
+ int c;
+
+ 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();
+ }
+ }
+
+ 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);
+
+ fprintf(stderr, "Bye.\n");
+
+ 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);
- }
-
- if (listen(sock, 5) < 0) {
- oprogname();
- perror("can't listen on socket");
- exit(1);
- }
-
- 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);
- }
-
- 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);
-
- 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);
+ 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);
+ }
+
+ 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);
+ }
+
+ 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);
+
+ 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;
-
- 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();
-
- 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");
- }
+ 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;
+
+ init_python();
+
+ 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");
+ }
}
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;
-
- 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);
-
- 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);
-
- 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;
-
- 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;
-
- end = run_command(buffer, globals);
- if (end < 0)
- PyErr_Print();
-
- if (end)
- break;
- }
-
- Py_XDECREF(globals);
- Py_XDECREF(new_stdin);
- Py_XDECREF(new_stdout);
-
- Py_EndInterpreter(tstate);
- PyEval_ReleaseLock();
-
- fprintf(output, "Goodbye!\n");
+ 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;
+ }
+
+ 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);
+
+ 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
+
+ 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';
+ }
+
+ while (*p && isspace(*p))
+ p++;
+ if (p[0] == '#' || p[0] == '\0')
+ continue;
+
+ end = run_command(buffer, globals);
+ if (end < 0)
+ PyErr_Print();
+
+ if (end)
+ break;
+ }
+
+ Py_XDECREF(globals);
+ Py_XDECREF(new_stdin);
+ Py_XDECREF(new_stdout);
+
+ Py_EndInterpreter(tstate);
+ PyEval_ReleaseLock();
+
+ 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);
}
diff --git a/Include/abstract.h b/Include/abstract.h
index fc9c6b5..6ca4988 100644
--- a/Include/abstract.h
+++ b/Include/abstract.h
@@ -32,7 +32,7 @@ Problem
If the programmer wants to get an item from another type of object
that provides sequence behavior, there is no clear way to do it
- correctly.
+ correctly.
The persistent programmer may peruse object.h and find that the
_typeobject structure provides a means of invoking up to (currently
@@ -44,7 +44,7 @@ Problem
Also, certain semantics, especially memory management semantics, may
differ by the type of object being used. Unfortunately, these
semantics are not clearly described in the current include files.
- An abstract interface providing more consistent semantics is needed.
+ An abstract interface providing more consistent semantics is needed.
Proposal
@@ -77,7 +77,7 @@ Proposal
Python distributions.
From the point of view of Python accessing services provided by C
- modules:
+ modules:
- "Python module interface": this interface consist of the basic
routines used to define modules and their members. Most of the
@@ -133,11 +133,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_Print(PyObject *o, FILE *fp, int flags);
- Print an object, o, on file, fp. Returns -1 on
- error. The flags argument is used to enable certain printing
- options. The only option currently supported is Py_Print_RAW.
+ Print an object, o, on file, fp. Returns -1 on
+ error. The flags argument is used to enable certain printing
+ options. The only option currently supported is Py_Print_RAW.
- (What should be said about Py_Print_RAW?)
+ (What should be said about Py_Print_RAW?)
*/
@@ -145,11 +145,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_HasAttrString(PyObject *o, char *attr_name);
- Returns 1 if o has the attribute attr_name, and 0 otherwise.
- This is equivalent to the Python expression:
- hasattr(o,attr_name).
+ Returns 1 if o has the attribute attr_name, and 0 otherwise.
+ This is equivalent to the Python expression:
+ hasattr(o,attr_name).
- This function always succeeds.
+ This function always succeeds.
*/
@@ -157,9 +157,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject* PyObject_GetAttrString(PyObject *o, char *attr_name);
- Retrieve an attributed named attr_name form object o.
- Returns the attribute value on success, or NULL on failure.
- This is the equivalent of the Python expression: o.attr_name.
+ Retrieve an attributed named attr_name form object o.
+ Returns the attribute value on success, or NULL on failure.
+ This is the equivalent of the Python expression: o.attr_name.
*/
@@ -167,11 +167,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_HasAttr(PyObject *o, PyObject *attr_name);
- Returns 1 if o has the attribute attr_name, and 0 otherwise.
- This is equivalent to the Python expression:
- hasattr(o,attr_name).
+ Returns 1 if o has the attribute attr_name, and 0 otherwise.
+ This is equivalent to the Python expression:
+ hasattr(o,attr_name).
- This function always succeeds.
+ This function always succeeds.
*/
@@ -179,9 +179,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject* PyObject_GetAttr(PyObject *o, PyObject *attr_name);
- Retrieve an attributed named attr_name form object o.
- Returns the attribute value on success, or NULL on failure.
- This is the equivalent of the Python expression: o.attr_name.
+ Retrieve an attributed named attr_name form object o.
+ Returns the attribute value on success, or NULL on failure.
+ This is the equivalent of the Python expression: o.attr_name.
*/
@@ -190,9 +190,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_SetAttrString(PyObject *o, char *attr_name, PyObject *v);
- Set the value of the attribute named attr_name, for object o,
- to the value, v. Returns -1 on failure. This is
- the equivalent of the Python statement: o.attr_name=v.
+ Set the value of the attribute named attr_name, for object o,
+ to the value, v. Returns -1 on failure. This is
+ the equivalent of the Python statement: o.attr_name=v.
*/
@@ -200,9 +200,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v);
- Set the value of the attribute named attr_name, for object o,
- to the value, v. Returns -1 on failure. This is
- the equivalent of the Python statement: o.attr_name=v.
+ Set the value of the attribute named attr_name, for object o,
+ to the value, v. Returns -1 on failure. This is
+ the equivalent of the Python statement: o.attr_name=v.
*/
@@ -210,9 +210,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_DelAttrString(PyObject *o, char *attr_name);
- Delete attribute named attr_name, for object o. Returns
- -1 on failure. This is the equivalent of the Python
- statement: del o.attr_name.
+ Delete attribute named attr_name, for object o. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: del o.attr_name.
*/
#define PyObject_DelAttrString(O,A) PyObject_SetAttrString((O),(A),NULL)
@@ -221,9 +221,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_DelAttr(PyObject *o, PyObject *attr_name);
- Delete attribute named attr_name, for object o. Returns -1
- on failure. This is the equivalent of the Python
- statement: del o.attr_name.
+ Delete attribute named attr_name, for object o. Returns -1
+ on failure. This is the equivalent of the Python
+ statement: del o.attr_name.
*/
#define PyObject_DelAttr(O,A) PyObject_SetAttr((O),(A),NULL)
@@ -231,11 +231,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(int) PyObject_Cmp(PyObject *o1, PyObject *o2, int *result);
/*
- Compare the values of o1 and o2 using a routine provided by
- o1, if one exists, otherwise with a routine provided by o2.
- The result of the comparison is returned in result. Returns
- -1 on failure. This is the equivalent of the Python
- statement: result=cmp(o1,o2).
+ Compare the values of o1 and o2 using a routine provided by
+ o1, if one exists, otherwise with a routine provided by o2.
+ The result of the comparison is returned in result. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: result=cmp(o1,o2).
*/
@@ -243,11 +243,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_Compare(PyObject *o1, PyObject *o2);
- Compare the values of o1 and o2 using a routine provided by
- o1, if one exists, otherwise with a routine provided by o2.
- Returns the result of the comparison on success. On error,
- the value returned is undefined. This is equivalent to the
- Python expression: cmp(o1,o2).
+ Compare the values of o1 and o2 using a routine provided by
+ o1, if one exists, otherwise with a routine provided by o2.
+ Returns the result of the comparison on success. On error,
+ the value returned is undefined. This is equivalent to the
+ Python expression: cmp(o1,o2).
*/
@@ -255,11 +255,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *PyObject_Repr(PyObject *o);
- Compute the string representation of object, o. Returns the
- string representation on success, NULL on failure. This is
- the equivalent of the Python expression: repr(o).
+ Compute the string representation of object, o. Returns the
+ string representation on success, NULL on failure. This is
+ the equivalent of the Python expression: repr(o).
- Called by the repr() built-in function and by reverse quotes.
+ Called by the repr() built-in function and by reverse quotes.
*/
@@ -267,12 +267,12 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *PyObject_Str(PyObject *o);
- Compute the string representation of object, o. Returns the
- string representation on success, NULL on failure. This is
- the equivalent of the Python expression: str(o).)
+ Compute the string representation of object, o. Returns the
+ string representation on success, NULL on failure. This is
+ the equivalent of the Python expression: str(o).)
- Called by the str() built-in function and by the print
- statement.
+ Called by the str() built-in function and by the print
+ statement.
*/
@@ -280,11 +280,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *PyObject_Unicode(PyObject *o);
- Compute the unicode representation of object, o. Returns the
- unicode representation on success, NULL on failure. This is
- the equivalent of the Python expression: unistr(o).)
+ Compute the unicode representation of object, o. Returns the
+ unicode representation on success, NULL on failure. This is
+ the equivalent of the Python expression: unistr(o).)
- Called by the unistr() built-in function.
+ Called by the unistr() built-in function.
*/
@@ -292,34 +292,34 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(int) PyCallable_Check(PyObject *o);
- Determine if the object, o, is callable. Return 1 if the
- object is callable and 0 otherwise.
+ Determine if the object, o, is callable. Return 1 if the
+ object is callable and 0 otherwise.
- This function always succeeds.
+ This function always succeeds.
*/
PyAPI_FUNC(PyObject *) PyObject_Call(PyObject *callable_object,
- PyObject *args, PyObject *kw);
+ PyObject *args, PyObject *kw);
/*
- Call a callable Python object, callable_object, with
- arguments and keywords arguments. The 'args' argument can not be
- NULL, but the 'kw' argument can be NULL.
+ Call a callable Python object, callable_object, with
+ arguments and keywords arguments. The 'args' argument can not be
+ NULL, but the 'kw' argument can be NULL.
*/
-
+
PyAPI_FUNC(PyObject *) PyObject_CallObject(PyObject *callable_object,
PyObject *args);
/*
- Call a callable Python object, callable_object, with
- arguments given by the tuple, args. If no arguments are
- needed, then args may be NULL. Returns the result of the
- call on success, or NULL on failure. This is the equivalent
- of the Python expression: apply(o,args).
+ Call a callable Python object, callable_object, with
+ arguments given by the tuple, args. If no arguments are
+ needed, then args may be NULL. Returns the result of the
+ call on success, or NULL on failure. This is the equivalent
+ of the Python expression: apply(o,args).
*/
@@ -327,12 +327,12 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
char *format, ...);
/*
- Call a callable Python object, callable_object, with a
- variable number of C arguments. The C arguments are described
- using a mkvalue-style format string. The format may be NULL,
- indicating that no arguments are provided. Returns the
- result of the call on success, or NULL on failure. This is
- the equivalent of the Python expression: apply(o,args).
+ Call a callable Python object, callable_object, with a
+ variable number of C arguments. The C arguments are described
+ using a mkvalue-style format string. The format may be NULL,
+ indicating that no arguments are provided. Returns the
+ result of the call on success, or NULL on failure. This is
+ the equivalent of the Python expression: apply(o,args).
*/
@@ -341,29 +341,29 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
char *format, ...);
/*
- Call the method named m of object o with a variable number of
- C arguments. The C arguments are described by a mkvalue
- format string. The format may be NULL, indicating that no
- arguments are provided. Returns the result of the call on
- success, or NULL on failure. This is the equivalent of the
- Python expression: o.method(args).
+ Call the method named m of object o with a variable number of
+ C arguments. The C arguments are described by a mkvalue
+ format string. The format may be NULL, indicating that no
+ arguments are provided. Returns the result of the call on
+ success, or NULL on failure. This is the equivalent of the
+ Python expression: o.method(args).
*/
PyAPI_FUNC(PyObject *) _PyObject_CallFunction_SizeT(PyObject *callable,
- char *format, ...);
+ char *format, ...);
PyAPI_FUNC(PyObject *) _PyObject_CallMethod_SizeT(PyObject *o,
- char *name,
- char *format, ...);
+ char *name,
+ char *format, ...);
PyAPI_FUNC(PyObject *) PyObject_CallFunctionObjArgs(PyObject *callable,
...);
/*
- Call a callable Python object, callable_object, with a
- variable number of C arguments. The C arguments are provided
- as PyObject * values, terminated by a NULL. Returns the
- result of the call on success, or NULL on failure. This is
- the equivalent of the Python expression: apply(o,args).
+ Call a callable Python object, callable_object, with a
+ variable number of C arguments. The C arguments are provided
+ as PyObject * values, terminated by a NULL. Returns the
+ result of the call on success, or NULL on failure. This is
+ the equivalent of the Python expression: apply(o,args).
*/
@@ -371,11 +371,11 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *m, ...);
/*
- Call the method named m of object o with a variable number of
- C arguments. The C arguments are provided as PyObject *
- values, terminated by NULL. Returns the result of the call
- on success, or NULL on failure. This is the equivalent of
- the Python expression: o.method(args).
+ Call the method named m of object o with a variable number of
+ C arguments. The C arguments are provided as PyObject *
+ values, terminated by NULL. Returns the result of the call
+ on success, or NULL on failure. This is the equivalent of
+ the Python expression: o.method(args).
*/
@@ -383,9 +383,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
long PyObject_Hash(PyObject *o);
- Compute and return the hash, hash_value, of an object, o. On
- failure, return -1. This is the equivalent of the Python
- expression: hash(o).
+ Compute and return the hash, hash_value, of an object, o. On
+ failure, return -1. This is the equivalent of the Python
+ expression: hash(o).
*/
@@ -394,9 +394,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_IsTrue(PyObject *o);
- Returns 1 if the object, o, is considered to be true, 0 if o is
- considered to be false and -1 on failure. This is equivalent to the
- Python expression: not not o
+ Returns 1 if the object, o, is considered to be true, 0 if o is
+ considered to be false and -1 on failure. This is equivalent to the
+ Python expression: not not o
*/
@@ -404,27 +404,27 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyObject_Not(PyObject *o);
- Returns 0 if the object, o, is considered to be true, 1 if o is
- considered to be false and -1 on failure. This is equivalent to the
- Python expression: not o
+ Returns 0 if the object, o, is considered to be true, 1 if o is
+ considered to be false and -1 on failure. This is equivalent to the
+ Python expression: not o
*/
PyAPI_FUNC(PyObject *) PyObject_Type(PyObject *o);
/*
- On success, returns a type object corresponding to the object
- type of object o. On failure, returns NULL. This is
- equivalent to the Python expression: type(o).
+ On success, returns a type object corresponding to the object
+ type of object o. On failure, returns NULL. This is
+ equivalent to the Python expression: type(o).
*/
PyAPI_FUNC(Py_ssize_t) PyObject_Size(PyObject *o);
/*
- Return the size of object o. If the object, o, provides
- both sequence and mapping protocols, the sequence size is
- returned. On error, -1 is returned. This is the equivalent
- to the Python expression: len(o).
+ Return the size of object o. If the object, o, provides
+ both sequence and mapping protocols, the sequence size is
+ returned. On error, -1 is returned. This is the equivalent
+ to the Python expression: len(o).
*/
@@ -436,203 +436,203 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(Py_ssize_t) _PyObject_LengthHint(PyObject *o, Py_ssize_t);
/*
- Guess the size of object o using len(o) or o.__length_hint__().
- If neither of those return a non-negative value, then return the
- default value. If one of the calls fails, this function returns -1.
+ Guess the size of object o using len(o) or o.__length_hint__().
+ If neither of those return a non-negative value, then return the
+ default value. If one of the calls fails, this function returns -1.
*/
PyAPI_FUNC(PyObject *) PyObject_GetItem(PyObject *o, PyObject *key);
/*
- Return element of o corresponding to the object, key, or NULL
- on failure. This is the equivalent of the Python expression:
- o[key].
+ Return element of o corresponding to the object, key, or NULL
+ on failure. This is the equivalent of the Python expression:
+ o[key].
*/
PyAPI_FUNC(int) PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v);
/*
- Map the object, key, to the value, v. Returns
- -1 on failure. This is the equivalent of the Python
- statement: o[key]=v.
+ Map the object, key, to the value, v. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: o[key]=v.
*/
PyAPI_FUNC(int) PyObject_DelItemString(PyObject *o, char *key);
/*
- Remove the mapping for object, key, from the object *o.
- Returns -1 on failure. This is equivalent to
- the Python statement: del o[key].
+ Remove the mapping for object, key, from the object *o.
+ Returns -1 on failure. This is equivalent to
+ the Python statement: del o[key].
*/
PyAPI_FUNC(int) PyObject_DelItem(PyObject *o, PyObject *key);
/*
- Delete the mapping for key from *o. Returns -1 on failure.
- This is the equivalent of the Python statement: del o[key].
+ Delete the mapping for key from *o. Returns -1 on failure.
+ This is the equivalent of the Python statement: del o[key].
*/
PyAPI_FUNC(int) PyObject_AsCharBuffer(PyObject *obj,
- const char **buffer,
- Py_ssize_t *buffer_len);
+ const char **buffer,
+ Py_ssize_t *buffer_len);
- /*
- Takes an arbitrary object which must support the (character,
- single segment) buffer interface and returns a pointer to a
- read-only memory location useable as character based input
- for subsequent processing.
+ /*
+ Takes an arbitrary object which must support the (character,
+ single segment) buffer interface and returns a pointer to a
+ read-only memory location useable as character based input
+ for subsequent processing.
- 0 is returned on success. buffer and buffer_len are only
- set in case no error occurs. Otherwise, -1 is returned and
- an exception set.
+ 0 is returned on success. buffer and buffer_len are only
+ set in case no error occurs. Otherwise, -1 is returned and
+ an exception set.
*/
PyAPI_FUNC(int) PyObject_CheckReadBuffer(PyObject *obj);
- /*
- Checks whether an arbitrary object supports the (character,
- single segment) buffer interface. Returns 1 on success, 0
- on failure.
+ /*
+ Checks whether an arbitrary object supports the (character,
+ single segment) buffer interface. Returns 1 on success, 0
+ on failure.
*/
PyAPI_FUNC(int) PyObject_AsReadBuffer(PyObject *obj,
- const void **buffer,
- Py_ssize_t *buffer_len);
+ const void **buffer,
+ Py_ssize_t *buffer_len);
- /*
- Same as PyObject_AsCharBuffer() except that this API expects
- (readable, single segment) buffer interface and returns a
- pointer to a read-only memory location which can contain
- arbitrary data.
+ /*
+ Same as PyObject_AsCharBuffer() except that this API expects
+ (readable, single segment) buffer interface and returns a
+ pointer to a read-only memory location which can contain
+ arbitrary data.
- 0 is returned on success. buffer and buffer_len are only
- set in case no error occurrs. Otherwise, -1 is returned and
- an exception set.
+ 0 is returned on success. buffer and buffer_len are only
+ set in case no error occurrs. Otherwise, -1 is returned and
+ an exception set.
*/
PyAPI_FUNC(int) PyObject_AsWriteBuffer(PyObject *obj,
- void **buffer,
- Py_ssize_t *buffer_len);
+ void **buffer,
+ Py_ssize_t *buffer_len);
- /*
- Takes an arbitrary object which must support the (writeable,
- single segment) buffer interface and returns a pointer to a
- writeable memory location in buffer of size buffer_len.
+ /*
+ Takes an arbitrary object which must support the (writeable,
+ single segment) buffer interface and returns a pointer to a
+ writeable memory location in buffer of size buffer_len.
- 0 is returned on success. buffer and buffer_len are only
- set in case no error occurrs. Otherwise, -1 is returned and
- an exception set.
+ 0 is returned on success. buffer and buffer_len are only
+ set in case no error occurrs. Otherwise, -1 is returned and
+ an exception set.
*/
- /* new buffer API */
+ /* new buffer API */
#define PyObject_CheckBuffer(obj) \
- (((obj)->ob_type->tp_as_buffer != NULL) && \
- (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_NEWBUFFER)) && \
- ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL))
-
- /* Return 1 if the getbuffer function is available, otherwise
- return 0 */
+ (((obj)->ob_type->tp_as_buffer != NULL) && \
+ (PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_NEWBUFFER)) && \
+ ((obj)->ob_type->tp_as_buffer->bf_getbuffer != NULL))
- PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
- int flags);
+ /* Return 1 if the getbuffer function is available, otherwise
+ return 0 */
- /* This is a C-API version of the getbuffer function call. It checks
- to make sure object has the required function pointer and issues the
- call. Returns -1 and raises an error on failure and returns 0 on
- success
- */
+ PyAPI_FUNC(int) PyObject_GetBuffer(PyObject *obj, Py_buffer *view,
+ int flags);
+
+ /* This is a C-API version of the getbuffer function call. It checks
+ to make sure object has the required function pointer and issues the
+ call. Returns -1 and raises an error on failure and returns 0 on
+ success
+ */
PyAPI_FUNC(void *) PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices);
-
- /* Get the memory area pointed to by the indices for the buffer given.
- Note that view->ndim is the assumed size of indices
- */
+
+ /* Get the memory area pointed to by the indices for the buffer given.
+ Note that view->ndim is the assumed size of indices
+ */
PyAPI_FUNC(int) PyBuffer_SizeFromFormat(const char *);
-
- /* Return the implied itemsize of the data-format area from a
- struct-style description */
-
-
+ /* Return the implied itemsize of the data-format area from a
+ struct-style description */
+
+
+
PyAPI_FUNC(int) PyBuffer_ToContiguous(void *buf, Py_buffer *view,
- Py_ssize_t len, char fort);
+ Py_ssize_t len, char fort);
- PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf,
- Py_ssize_t len, char fort);
+ PyAPI_FUNC(int) PyBuffer_FromContiguous(Py_buffer *view, void *buf,
+ Py_ssize_t len, char fort);
- /* Copy len bytes of data from the contiguous chunk of memory
- pointed to by buf into the buffer exported by obj. Return
- 0 on success and return -1 and raise a PyBuffer_Error on
- error (i.e. the object does not have a buffer interface or
- it is not working).
+ /* Copy len bytes of data from the contiguous chunk of memory
+ pointed to by buf into the buffer exported by obj. Return
+ 0 on success and return -1 and raise a PyBuffer_Error on
+ error (i.e. the object does not have a buffer interface or
+ it is not working).
- If fort is 'F' and the object is multi-dimensional,
- then the data will be copied into the array in
- Fortran-style (first dimension varies the fastest). If
- fort is 'C', then the data will be copied into the array
- in C-style (last dimension varies the fastest). If fort
- is 'A', then it does not matter and the copy will be made
- in whatever way is more efficient.
+ If fort is 'F' and the object is multi-dimensional,
+ then the data will be copied into the array in
+ Fortran-style (first dimension varies the fastest). If
+ fort is 'C', then the data will be copied into the array
+ in C-style (last dimension varies the fastest). If fort
+ is 'A', then it does not matter and the copy will be made
+ in whatever way is more efficient.
- */
+ */
PyAPI_FUNC(int) PyObject_CopyData(PyObject *dest, PyObject *src);
-
- /* Copy the data from the src buffer to the buffer of destination
- */
+
+ /* Copy the data from the src buffer to the buffer of destination
+ */
PyAPI_FUNC(int) PyBuffer_IsContiguous(Py_buffer *view, char fort);
- PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims,
- Py_ssize_t *shape,
- Py_ssize_t *strides,
- int itemsize,
- char fort);
+ PyAPI_FUNC(void) PyBuffer_FillContiguousStrides(int ndims,
+ Py_ssize_t *shape,
+ Py_ssize_t *strides,
+ int itemsize,
+ char fort);
- /* Fill the strides array with byte-strides of a contiguous
- (Fortran-style if fort is 'F' or C-style otherwise)
- array of the given shape with the given number of bytes
- per element.
- */
+ /* Fill the strides array with byte-strides of a contiguous
+ (Fortran-style if fort is 'F' or C-style otherwise)
+ array of the given shape with the given number of bytes
+ per element.
+ */
PyAPI_FUNC(int) PyBuffer_FillInfo(Py_buffer *view, PyObject *o, void *buf,
- Py_ssize_t len, int readonly,
- int flags);
+ Py_ssize_t len, int readonly,
+ int flags);
- /* Fills in a buffer-info structure correctly for an exporter
- that can only share a contiguous chunk of memory of
- "unsigned bytes" of the given length. Returns 0 on success
- and -1 (with raising an error) on error.
- */
+ /* Fills in a buffer-info structure correctly for an exporter
+ that can only share a contiguous chunk of memory of
+ "unsigned bytes" of the given length. Returns 0 on success
+ and -1 (with raising an error) on error.
+ */
PyAPI_FUNC(void) PyBuffer_Release(Py_buffer *view);
/* Releases a Py_buffer obtained from getbuffer ParseTuple's s*.
- */
+ */
PyAPI_FUNC(PyObject *) PyObject_Format(PyObject* obj,
- PyObject *format_spec);
+ PyObject *format_spec);
/*
- Takes an arbitrary object and returns the result of
- calling obj.__format__(format_spec).
+ Takes an arbitrary object and returns the result of
+ calling obj.__format__(format_spec).
*/
/* Iterators */
PyAPI_FUNC(PyObject *) PyObject_GetIter(PyObject *);
/* Takes an object and returns an iterator for it.
- This is typically a new iterator but if the argument
- is an iterator, this returns itself. */
+ This is typically a new iterator but if the argument
+ is an iterator, this returns itself. */
#define PyIter_Check(obj) \
(PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_ITER) && \
@@ -641,27 +641,27 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyIter_Next(PyObject *);
/* Takes an iterator object and calls its tp_iternext slot,
- returning the next value. If the iterator is exhausted,
- this returns NULL without setting an exception.
- NULL with an exception means an error occurred. */
+ returning the next value. If the iterator is exhausted,
+ this returns NULL without setting an exception.
+ NULL with an exception means an error occurred. */
/* Number Protocol:*/
PyAPI_FUNC(int) PyNumber_Check(PyObject *o);
/*
- Returns 1 if the object, o, provides numeric protocols, and
- false otherwise.
+ Returns 1 if the object, o, provides numeric protocols, and
+ false otherwise.
- This function always succeeds.
+ This function always succeeds.
*/
PyAPI_FUNC(PyObject *) PyNumber_Add(PyObject *o1, PyObject *o2);
/*
- Returns the result of adding o1 and o2, or null on failure.
- This is the equivalent of the Python expression: o1+o2.
+ Returns the result of adding o1 and o2, or null on failure.
+ This is the equivalent of the Python expression: o1+o2.
*/
@@ -669,18 +669,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Subtract(PyObject *o1, PyObject *o2);
/*
- Returns the result of subtracting o2 from o1, or null on
- failure. This is the equivalent of the Python expression:
- o1-o2.
+ Returns the result of subtracting o2 from o1, or null on
+ failure. This is the equivalent of the Python expression:
+ o1-o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_Multiply(PyObject *o1, PyObject *o2);
/*
- Returns the result of multiplying o1 and o2, or null on
- failure. This is the equivalent of the Python expression:
- o1*o2.
+ Returns the result of multiplying o1 and o2, or null on
+ failure. This is the equivalent of the Python expression:
+ o1*o2.
*/
@@ -688,8 +688,8 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Divide(PyObject *o1, PyObject *o2);
/*
- Returns the result of dividing o1 by o2, or null on failure.
- This is the equivalent of the Python expression: o1/o2.
+ Returns the result of dividing o1 by o2, or null on failure.
+ This is the equivalent of the Python expression: o1/o2.
*/
@@ -697,9 +697,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_FloorDivide(PyObject *o1, PyObject *o2);
/*
- Returns the result of dividing o1 by o2 giving an integral result,
- or null on failure.
- This is the equivalent of the Python expression: o1//o2.
+ Returns the result of dividing o1 by o2 giving an integral result,
+ or null on failure.
+ This is the equivalent of the Python expression: o1//o2.
*/
@@ -707,9 +707,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_TrueDivide(PyObject *o1, PyObject *o2);
/*
- Returns the result of dividing o1 by o2 giving a float result,
- or null on failure.
- This is the equivalent of the Python expression: o1/o2.
+ Returns the result of dividing o1 by o2 giving a float result,
+ or null on failure.
+ This is the equivalent of the Python expression: o1/o2.
*/
@@ -717,9 +717,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Remainder(PyObject *o1, PyObject *o2);
/*
- Returns the remainder of dividing o1 by o2, or null on
- failure. This is the equivalent of the Python expression:
- o1%o2.
+ Returns the remainder of dividing o1 by o2, or null on
+ failure. This is the equivalent of the Python expression:
+ o1%o2.
*/
@@ -727,9 +727,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Divmod(PyObject *o1, PyObject *o2);
/*
- See the built-in function divmod. Returns NULL on failure.
- This is the equivalent of the Python expression:
- divmod(o1,o2).
+ See the built-in function divmod. Returns NULL on failure.
+ This is the equivalent of the Python expression:
+ divmod(o1,o2).
*/
@@ -738,42 +738,42 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *o3);
/*
- See the built-in function pow. Returns NULL on failure.
- This is the equivalent of the Python expression:
- pow(o1,o2,o3), where o3 is optional.
+ See the built-in function pow. Returns NULL on failure.
+ This is the equivalent of the Python expression:
+ pow(o1,o2,o3), where o3 is optional.
*/
PyAPI_FUNC(PyObject *) PyNumber_Negative(PyObject *o);
/*
- Returns the negation of o on success, or null on failure.
- This is the equivalent of the Python expression: -o.
+ Returns the negation of o on success, or null on failure.
+ This is the equivalent of the Python expression: -o.
*/
PyAPI_FUNC(PyObject *) PyNumber_Positive(PyObject *o);
/*
- Returns the (what?) of o on success, or NULL on failure.
- This is the equivalent of the Python expression: +o.
+ Returns the (what?) of o on success, or NULL on failure.
+ This is the equivalent of the Python expression: +o.
*/
PyAPI_FUNC(PyObject *) PyNumber_Absolute(PyObject *o);
/*
- Returns the absolute value of o, or null on failure. This is
- the equivalent of the Python expression: abs(o).
+ Returns the absolute value of o, or null on failure. This is
+ the equivalent of the Python expression: abs(o).
*/
PyAPI_FUNC(PyObject *) PyNumber_Invert(PyObject *o);
/*
- Returns the bitwise negation of o on success, or NULL on
- failure. This is the equivalent of the Python expression:
- ~o.
+ Returns the bitwise negation of o on success, or NULL on
+ failure. This is the equivalent of the Python expression:
+ ~o.
*/
@@ -781,9 +781,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Lshift(PyObject *o1, PyObject *o2);
/*
- Returns the result of left shifting o1 by o2 on success, or
- NULL on failure. This is the equivalent of the Python
- expression: o1 << o2.
+ Returns the result of left shifting o1 by o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1 << o2.
*/
@@ -791,18 +791,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Rshift(PyObject *o1, PyObject *o2);
/*
- Returns the result of right shifting o1 by o2 on success, or
- NULL on failure. This is the equivalent of the Python
- expression: o1 >> o2.
+ Returns the result of right shifting o1 by o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1 >> o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_And(PyObject *o1, PyObject *o2);
/*
- Returns the result of bitwise and of o1 and o2 on success, or
- NULL on failure. This is the equivalent of the Python
- expression: o1&o2.
+ Returns the result of bitwise and of o1 and o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1&o2.
*/
@@ -810,9 +810,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Xor(PyObject *o1, PyObject *o2);
/*
- Returns the bitwise exclusive or of o1 by o2 on success, or
- NULL on failure. This is the equivalent of the Python
- expression: o1^o2.
+ Returns the bitwise exclusive or of o1 by o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1^o2.
*/
@@ -820,9 +820,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_Or(PyObject *o1, PyObject *o2);
/*
- Returns the result of bitwise or on o1 and o2 on success, or
- NULL on failure. This is the equivalent of the Python
- expression: o1|o2.
+ Returns the result of bitwise or on o1 and o2 on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o1|o2.
*/
@@ -830,18 +830,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyNumber_Coerce(PyObject **p1, PyObject **p2);
- This function takes the addresses of two variables of type
- PyObject*.
+ This function takes the addresses of two variables of type
+ PyObject*.
- If the objects pointed to by *p1 and *p2 have the same type,
- increment their reference count and return 0 (success).
- If the objects can be converted to a common numeric type,
- replace *p1 and *p2 by their converted value (with 'new'
- reference counts), and return 0.
- If no conversion is possible, or if some other error occurs,
- return -1 (failure) and don't increment the reference counts.
- The call PyNumber_Coerce(&o1, &o2) is equivalent to the Python
- statement o1, o2 = coerce(o1, o2).
+ If the objects pointed to by *p1 and *p2 have the same type,
+ increment their reference count and return 0 (success).
+ If the objects can be converted to a common numeric type,
+ replace *p1 and *p2 by their converted value (with 'new'
+ reference counts), and return 0.
+ If no conversion is possible, or if some other error occurs,
+ return -1 (failure) and don't increment the reference counts.
+ The call PyNumber_Coerce(&o1, &o2) is equivalent to the Python
+ statement o1, o2 = coerce(o1, o2).
*/
@@ -849,184 +849,184 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
((obj)->ob_type->tp_as_number != NULL && \
PyType_HasFeature((obj)->ob_type, Py_TPFLAGS_HAVE_INDEX) && \
(obj)->ob_type->tp_as_number->nb_index != NULL)
-
+
PyAPI_FUNC(PyObject *) PyNumber_Index(PyObject *o);
/*
- Returns the object converted to a Python long or int
- or NULL with an error raised on failure.
+ Returns the object converted to a Python long or int
+ or NULL with an error raised on failure.
*/
PyAPI_FUNC(Py_ssize_t) PyNumber_AsSsize_t(PyObject *o, PyObject *exc);
/*
- Returns the Integral instance converted to an int. The
- instance is expected to be int or long or have an __int__
- method. Steals integral's reference. error_format will be
- used to create the TypeError if integral isn't actually an
- Integral instance. error_format should be a format string
- that can accept a char* naming integral's type.
+ Returns the Integral instance converted to an int. The
+ instance is expected to be int or long or have an __int__
+ method. Steals integral's reference. error_format will be
+ used to create the TypeError if integral isn't actually an
+ Integral instance. error_format should be a format string
+ that can accept a char* naming integral's type.
*/
PyAPI_FUNC(PyObject *) _PyNumber_ConvertIntegralToInt(
- PyObject *integral,
- const char* error_format);
+ PyObject *integral,
+ const char* error_format);
/*
- Returns the object converted to Py_ssize_t by going through
- PyNumber_Index first. If an overflow error occurs while
- converting the int-or-long to Py_ssize_t, then the second argument
- is the error-type to return. If it is NULL, then the overflow error
- is cleared and the value is clipped.
+ Returns the object converted to Py_ssize_t by going through
+ PyNumber_Index first. If an overflow error occurs while
+ converting the int-or-long to Py_ssize_t, then the second argument
+ is the error-type to return. If it is NULL, then the overflow error
+ is cleared and the value is clipped.
*/
PyAPI_FUNC(PyObject *) PyNumber_Int(PyObject *o);
/*
- Returns the o converted to an integer object on success, or
- NULL on failure. This is the equivalent of the Python
- expression: int(o).
+ Returns the o converted to an integer object on success, or
+ NULL on failure. This is the equivalent of the Python
+ expression: int(o).
*/
PyAPI_FUNC(PyObject *) PyNumber_Long(PyObject *o);
/*
- Returns the o converted to a long integer object on success,
- or NULL on failure. This is the equivalent of the Python
- expression: long(o).
+ Returns the o converted to a long integer object on success,
+ or NULL on failure. This is the equivalent of the Python
+ expression: long(o).
*/
PyAPI_FUNC(PyObject *) PyNumber_Float(PyObject *o);
/*
- Returns the o converted to a float object on success, or NULL
- on failure. This is the equivalent of the Python expression:
- float(o).
+ Returns the o converted to a float object on success, or NULL
+ on failure. This is the equivalent of the Python expression:
+ float(o).
*/
-
+
/* In-place variants of (some of) the above number protocol functions */
PyAPI_FUNC(PyObject *) PyNumber_InPlaceAdd(PyObject *o1, PyObject *o2);
/*
- Returns the result of adding o2 to o1, possibly in-place, or null
- on failure. This is the equivalent of the Python expression:
- o1 += o2.
+ Returns the result of adding o2 to o1, possibly in-place, or null
+ on failure. This is the equivalent of the Python expression:
+ o1 += o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceSubtract(PyObject *o1, PyObject *o2);
/*
- Returns the result of subtracting o2 from o1, possibly in-place or
- null on failure. This is the equivalent of the Python expression:
- o1 -= o2.
+ Returns the result of subtracting o2 from o1, possibly in-place or
+ null on failure. This is the equivalent of the Python expression:
+ o1 -= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceMultiply(PyObject *o1, PyObject *o2);
/*
- Returns the result of multiplying o1 by o2, possibly in-place, or
- null on failure. This is the equivalent of the Python expression:
- o1 *= o2.
+ Returns the result of multiplying o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 *= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceDivide(PyObject *o1, PyObject *o2);
/*
- Returns the result of dividing o1 by o2, possibly in-place, or null
- on failure. This is the equivalent of the Python expression:
- o1 /= o2.
+ Returns the result of dividing o1 by o2, possibly in-place, or null
+ on failure. This is the equivalent of the Python expression:
+ o1 /= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceFloorDivide(PyObject *o1,
- PyObject *o2);
+ PyObject *o2);
/*
- Returns the result of dividing o1 by o2 giving an integral result,
- possibly in-place, or null on failure.
- This is the equivalent of the Python expression:
- o1 /= o2.
+ Returns the result of dividing o1 by o2 giving an integral result,
+ possibly in-place, or null on failure.
+ This is the equivalent of the Python expression:
+ o1 /= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceTrueDivide(PyObject *o1,
- PyObject *o2);
+ PyObject *o2);
/*
- Returns the result of dividing o1 by o2 giving a float result,
- possibly in-place, or null on failure.
- This is the equivalent of the Python expression:
- o1 /= o2.
+ Returns the result of dividing o1 by o2 giving a float result,
+ possibly in-place, or null on failure.
+ This is the equivalent of the Python expression:
+ o1 /= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceRemainder(PyObject *o1, PyObject *o2);
/*
- Returns the remainder of dividing o1 by o2, possibly in-place, or
- null on failure. This is the equivalent of the Python expression:
- o1 %= o2.
+ Returns the remainder of dividing o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 %= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlacePower(PyObject *o1, PyObject *o2,
- PyObject *o3);
+ PyObject *o3);
/*
- Returns the result of raising o1 to the power of o2, possibly
- in-place, or null on failure. This is the equivalent of the Python
- expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present.
+ Returns the result of raising o1 to the power of o2, possibly
+ in-place, or null on failure. This is the equivalent of the Python
+ expression: o1 **= o2, or pow(o1, o2, o3) if o3 is present.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceLshift(PyObject *o1, PyObject *o2);
/*
- Returns the result of left shifting o1 by o2, possibly in-place, or
- null on failure. This is the equivalent of the Python expression:
- o1 <<= o2.
+ Returns the result of left shifting o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 <<= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceRshift(PyObject *o1, PyObject *o2);
/*
- Returns the result of right shifting o1 by o2, possibly in-place or
- null on failure. This is the equivalent of the Python expression:
- o1 >>= o2.
+ Returns the result of right shifting o1 by o2, possibly in-place or
+ null on failure. This is the equivalent of the Python expression:
+ o1 >>= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceAnd(PyObject *o1, PyObject *o2);
/*
- Returns the result of bitwise and of o1 and o2, possibly in-place,
- or null on failure. This is the equivalent of the Python
- expression: o1 &= o2.
+ Returns the result of bitwise and of o1 and o2, possibly in-place,
+ or null on failure. This is the equivalent of the Python
+ expression: o1 &= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceXor(PyObject *o1, PyObject *o2);
/*
- Returns the bitwise exclusive or of o1 by o2, possibly in-place, or
- null on failure. This is the equivalent of the Python expression:
- o1 ^= o2.
+ Returns the bitwise exclusive or of o1 by o2, possibly in-place, or
+ null on failure. This is the equivalent of the Python expression:
+ o1 ^= o2.
*/
PyAPI_FUNC(PyObject *) PyNumber_InPlaceOr(PyObject *o1, PyObject *o2);
/*
- Returns the result of bitwise or of o1 and o2, possibly in-place,
- or null on failure. This is the equivalent of the Python
- expression: o1 |= o2.
+ Returns the result of bitwise or of o1 and o2, possibly in-place,
+ or null on failure. This is the equivalent of the Python
+ expression: o1 |= o2.
*/
@@ -1034,9 +1034,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyNumber_ToBase(PyObject *n, int base);
/*
- Returns the integer n converted to a string with a base, with a base
- marker of 0b, 0o or 0x prefixed if applicable.
- If n is not an int object, it is converted with PyNumber_Index first.
+ Returns the integer n converted to a string with a base, with a base
+ marker of 0b, 0o or 0x prefixed if applicable.
+ If n is not an int object, it is converted with PyNumber_Index first.
*/
@@ -1045,17 +1045,17 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(int) PySequence_Check(PyObject *o);
/*
- Return 1 if the object provides sequence protocol, and zero
- otherwise.
+ Return 1 if the object provides sequence protocol, and zero
+ otherwise.
- This function always succeeds.
+ This function always succeeds.
*/
PyAPI_FUNC(Py_ssize_t) PySequence_Size(PyObject *o);
/*
- Return the size of sequence object o, or -1 on failure.
+ Return the size of sequence object o, or -1 on failure.
*/
@@ -1068,151 +1068,151 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PySequence_Concat(PyObject *o1, PyObject *o2);
/*
- Return the concatenation of o1 and o2 on success, and NULL on
- failure. This is the equivalent of the Python
- expression: o1+o2.
+ Return the concatenation of o1 and o2 on success, and NULL on
+ failure. This is the equivalent of the Python
+ expression: o1+o2.
*/
PyAPI_FUNC(PyObject *) PySequence_Repeat(PyObject *o, Py_ssize_t count);
/*
- Return the result of repeating sequence object o count times,
- or NULL on failure. This is the equivalent of the Python
- expression: o1*count.
+ Return the result of repeating sequence object o count times,
+ or NULL on failure. This is the equivalent of the Python
+ expression: o1*count.
*/
PyAPI_FUNC(PyObject *) PySequence_GetItem(PyObject *o, Py_ssize_t i);
/*
- Return the ith element of o, or NULL on failure. This is the
- equivalent of the Python expression: o[i].
+ Return the ith element of o, or NULL on failure. This is the
+ equivalent of the Python expression: o[i].
*/
PyAPI_FUNC(PyObject *) PySequence_GetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
/*
- Return the slice of sequence object o between i1 and i2, or
- NULL on failure. This is the equivalent of the Python
- expression: o[i1:i2].
+ Return the slice of sequence object o between i1 and i2, or
+ NULL on failure. This is the equivalent of the Python
+ expression: o[i1:i2].
*/
PyAPI_FUNC(int) PySequence_SetItem(PyObject *o, Py_ssize_t i, PyObject *v);
/*
- Assign object v to the ith element of o. Returns
- -1 on failure. This is the equivalent of the Python
- statement: o[i]=v.
+ Assign object v to the ith element of o. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: o[i]=v.
*/
PyAPI_FUNC(int) PySequence_DelItem(PyObject *o, Py_ssize_t i);
/*
- Delete the ith element of object v. Returns
- -1 on failure. This is the equivalent of the Python
- statement: del o[i].
+ Delete the ith element of object v. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: del o[i].
*/
PyAPI_FUNC(int) PySequence_SetSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2,
PyObject *v);
/*
- Assign the sequence object, v, to the slice in sequence
- object, o, from i1 to i2. Returns -1 on failure. This is the
- equivalent of the Python statement: o[i1:i2]=v.
+ Assign the sequence object, v, to the slice in sequence
+ object, o, from i1 to i2. Returns -1 on failure. This is the
+ equivalent of the Python statement: o[i1:i2]=v.
*/
PyAPI_FUNC(int) PySequence_DelSlice(PyObject *o, Py_ssize_t i1, Py_ssize_t i2);
/*
- Delete the slice in sequence object, o, from i1 to i2.
- Returns -1 on failure. This is the equivalent of the Python
- statement: del o[i1:i2].
+ Delete the slice in sequence object, o, from i1 to i2.
+ Returns -1 on failure. This is the equivalent of the Python
+ statement: del o[i1:i2].
*/
PyAPI_FUNC(PyObject *) PySequence_Tuple(PyObject *o);
/*
- Returns the sequence, o, as a tuple on success, and NULL on failure.
- This is equivalent to the Python expression: tuple(o)
+ Returns the sequence, o, as a tuple on success, and NULL on failure.
+ This is equivalent to the Python expression: tuple(o)
*/
PyAPI_FUNC(PyObject *) PySequence_List(PyObject *o);
/*
- Returns the sequence, o, as a list on success, and NULL on failure.
- This is equivalent to the Python expression: list(o)
+ Returns the sequence, o, as a list on success, and NULL on failure.
+ This is equivalent to the Python expression: list(o)
*/
PyAPI_FUNC(PyObject *) PySequence_Fast(PyObject *o, const char* m);
/*
- Returns the sequence, o, as a tuple, unless it's already a
- tuple or list. Use PySequence_Fast_GET_ITEM to access the
- members of this list, and PySequence_Fast_GET_SIZE to get its length.
+ Returns the sequence, o, as a tuple, unless it's already a
+ tuple or list. Use PySequence_Fast_GET_ITEM to access the
+ members of this list, and PySequence_Fast_GET_SIZE to get its length.
- Returns NULL on failure. If the object does not support iteration,
- raises a TypeError exception with m as the message text.
+ Returns NULL on failure. If the object does not support iteration,
+ raises a TypeError exception with m as the message text.
*/
#define PySequence_Fast_GET_SIZE(o) \
- (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o))
+ (PyList_Check(o) ? PyList_GET_SIZE(o) : PyTuple_GET_SIZE(o))
/*
- Return the size of o, assuming that o was returned by
- PySequence_Fast and is not NULL.
+ Return the size of o, assuming that o was returned by
+ PySequence_Fast and is not NULL.
*/
#define PySequence_Fast_GET_ITEM(o, i)\
(PyList_Check(o) ? PyList_GET_ITEM(o, i) : PyTuple_GET_ITEM(o, i))
/*
- Return the ith element of o, assuming that o was returned by
- PySequence_Fast, and that i is within bounds.
+ Return the ith element of o, assuming that o was returned by
+ PySequence_Fast, and that i is within bounds.
*/
#define PySequence_ITEM(o, i)\
- ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
+ ( Py_TYPE(o)->tp_as_sequence->sq_item(o, i) )
/* Assume tp_as_sequence and sq_item exist and that i does not
- need to be corrected for a negative index
- */
+ need to be corrected for a negative index
+ */
#define PySequence_Fast_ITEMS(sf) \
- (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \
- : ((PyTupleObject *)(sf))->ob_item)
- /* Return a pointer to the underlying item array for
- an object retured by PySequence_Fast */
+ (PyList_Check(sf) ? ((PyListObject *)(sf))->ob_item \
+ : ((PyTupleObject *)(sf))->ob_item)
+ /* Return a pointer to the underlying item array for
+ an object retured by PySequence_Fast */
PyAPI_FUNC(Py_ssize_t) PySequence_Count(PyObject *o, PyObject *value);
/*
- Return the number of occurrences on value on o, that is,
- return the number of keys for which o[key]==value. On
- failure, return -1. This is equivalent to the Python
- expression: o.count(value).
+ Return the number of occurrences on value on o, that is,
+ return the number of keys for which o[key]==value. On
+ failure, return -1. This is equivalent to the Python
+ expression: o.count(value).
*/
PyAPI_FUNC(int) PySequence_Contains(PyObject *seq, PyObject *ob);
/*
- Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
- Use __contains__ if possible, else _PySequence_IterSearch().
+ Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
+ Use __contains__ if possible, else _PySequence_IterSearch().
*/
#define PY_ITERSEARCH_COUNT 1
#define PY_ITERSEARCH_INDEX 2
#define PY_ITERSEARCH_CONTAINS 3
PyAPI_FUNC(Py_ssize_t) _PySequence_IterSearch(PyObject *seq,
- PyObject *obj, int operation);
- /*
- Iterate over seq. Result depends on the operation:
- PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if
- error.
- PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of
- obj in seq; set ValueError and return -1 if none found;
- also return -1 on error.
- PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on
- error.
- */
+ PyObject *obj, int operation);
+ /*
+ Iterate over seq. Result depends on the operation:
+ PY_ITERSEARCH_COUNT: return # of times obj appears in seq; -1 if
+ error.
+ PY_ITERSEARCH_INDEX: return 0-based index of first occurrence of
+ obj in seq; set ValueError and return -1 if none found;
+ also return -1 on error.
+ PY_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on
+ error.
+ */
/* For DLL-level backwards compatibility */
#undef PySequence_In
@@ -1222,17 +1222,17 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
#define PySequence_In PySequence_Contains
/*
- Determine if o contains value. If an item in o is equal to
- X, return 1, otherwise return 0. On error, return -1. This
- is equivalent to the Python expression: value in o.
+ Determine if o contains value. If an item in o is equal to
+ X, return 1, otherwise return 0. On error, return -1. This
+ is equivalent to the Python expression: value in o.
*/
PyAPI_FUNC(Py_ssize_t) PySequence_Index(PyObject *o, PyObject *value);
/*
- Return the first index for which o[i]=value. On error,
- return -1. This is equivalent to the Python
- expression: o.index(value).
+ Return the first index for which o[i]=value. On error,
+ return -1. This is equivalent to the Python
+ expression: o.index(value).
*/
/* In-place versions of some of the above Sequence functions. */
@@ -1240,18 +1240,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PySequence_InPlaceConcat(PyObject *o1, PyObject *o2);
/*
- Append o2 to o1, in-place when possible. Return the resulting
- object, which could be o1, or NULL on failure. This is the
- equivalent of the Python expression: o1 += o2.
+ Append o2 to o1, in-place when possible. Return the resulting
+ object, which could be o1, or NULL on failure. This is the
+ equivalent of the Python expression: o1 += o2.
*/
PyAPI_FUNC(PyObject *) PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count);
/*
- Repeat o1 by count, in-place when possible. Return the resulting
- object, which could be o1, or NULL on failure. This is the
- equivalent of the Python expression: o1 *= count.
+ Repeat o1 by count, in-place when possible. Return the resulting
+ object, which could be o1, or NULL on failure. This is the
+ equivalent of the Python expression: o1 *= count.
*/
@@ -1260,18 +1260,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(int) PyMapping_Check(PyObject *o);
/*
- Return 1 if the object provides mapping protocol, and zero
- otherwise.
+ Return 1 if the object provides mapping protocol, and zero
+ otherwise.
- This function always succeeds.
+ This function always succeeds.
*/
PyAPI_FUNC(Py_ssize_t) PyMapping_Size(PyObject *o);
/*
- Returns the number of keys in object o on success, and -1 on
- failure. For objects that do not provide sequence protocol,
- this is equivalent to the Python expression: len(o).
+ Returns the number of keys in object o on success, and -1 on
+ failure. For objects that do not provide sequence protocol,
+ this is equivalent to the Python expression: len(o).
*/
/* For DLL compatibility */
@@ -1284,9 +1284,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyMapping_DelItemString(PyObject *o, char *key);
- Remove the mapping for object, key, from the object *o.
- Returns -1 on failure. This is equivalent to
- the Python statement: del o[key].
+ Remove the mapping for object, key, from the object *o.
+ Returns -1 on failure. This is equivalent to
+ the Python statement: del o[key].
*/
#define PyMapping_DelItemString(O,K) PyObject_DelItemString((O),(K))
@@ -1294,30 +1294,30 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
int PyMapping_DelItem(PyObject *o, PyObject *key);
- Remove the mapping for object, key, from the object *o.
- Returns -1 on failure. This is equivalent to
- the Python statement: del o[key].
+ Remove the mapping for object, key, from the object *o.
+ Returns -1 on failure. This is equivalent to
+ the Python statement: del o[key].
*/
#define PyMapping_DelItem(O,K) PyObject_DelItem((O),(K))
PyAPI_FUNC(int) PyMapping_HasKeyString(PyObject *o, char *key);
/*
- On success, return 1 if the mapping object has the key, key,
- and 0 otherwise. This is equivalent to the Python expression:
- o.has_key(key).
+ On success, return 1 if the mapping object has the key, key,
+ and 0 otherwise. This is equivalent to the Python expression:
+ o.has_key(key).
- This function always succeeds.
+ This function always succeeds.
*/
PyAPI_FUNC(int) PyMapping_HasKey(PyObject *o, PyObject *key);
/*
- Return 1 if the mapping object has the key, key,
- and 0 otherwise. This is equivalent to the Python expression:
- o.has_key(key).
+ Return 1 if the mapping object has the key, key,
+ and 0 otherwise. This is equivalent to the Python expression:
+ o.has_key(key).
- This function always succeeds.
+ This function always succeeds.
*/
@@ -1325,9 +1325,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *PyMapping_Keys(PyObject *o);
- On success, return a list of the keys in object o. On
- failure, return NULL. This is equivalent to the Python
- expression: o.keys().
+ On success, return a list of the keys in object o. On
+ failure, return NULL. This is equivalent to the Python
+ expression: o.keys().
*/
#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL)
@@ -1335,9 +1335,9 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *PyMapping_Values(PyObject *o);
- On success, return a list of the values in object o. On
- failure, return NULL. This is equivalent to the Python
- expression: o.values().
+ On success, return a list of the values in object o. On
+ failure, return NULL. This is equivalent to the Python
+ expression: o.values().
*/
#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL)
@@ -1345,10 +1345,10 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyObject *PyMapping_Items(PyObject *o);
- On success, return a list of the items in object o, where
- each item is a tuple containing a key-value pair. On
- failure, return NULL. This is equivalent to the Python
- expression: o.items().
+ On success, return a list of the items in object o, where
+ each item is a tuple containing a key-value pair. On
+ failure, return NULL. This is equivalent to the Python
+ expression: o.items().
*/
#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL)
@@ -1356,18 +1356,18 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key);
/*
- Return element of o corresponding to the object, key, or NULL
- on failure. This is the equivalent of the Python expression:
- o[key].
+ Return element of o corresponding to the object, key, or NULL
+ on failure. This is the equivalent of the Python expression:
+ o[key].
*/
PyAPI_FUNC(int) PyMapping_SetItemString(PyObject *o, char *key,
PyObject *value);
/*
- Map the object, key, to the value, v. Returns
- -1 on failure. This is the equivalent of the Python
- statement: o[key]=v.
+ Map the object, key, to the value, v. Returns
+ -1 on failure. This is the equivalent of the Python
+ statement: o[key]=v.
*/
diff --git a/Include/ceval.h b/Include/ceval.h
index a3b3dcf..0e8bd2a 100644
--- a/Include/ceval.h
+++ b/Include/ceval.h
@@ -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 */
diff --git a/Include/datetime.h b/Include/datetime.h
index e017299..47abe5c 100644
--- a/Include/datetime.h
+++ b/Include/datetime.h
@@ -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
}
diff --git a/Include/descrobject.h b/Include/descrobject.h
index 718f9d5..b542732 100644
--- a/Include/descrobject.h
+++ b/Include/descrobject.h
@@ -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 *);
diff --git a/Include/dictobject.h b/Include/dictobject.h
index dfd42dc..ece01c6 100644
--- a/Include/dictobject.h
+++ b/Include/dictobject.h
@@ -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 */
-
- /* 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];
+ 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;
+
+ /* 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);
diff --git a/Include/fileobject.h b/Include/fileobject.h
index 83e9c25..ba506ec 100644
--- a/Include/fileobject.h
+++ b/Include/fileobject.h
@@ -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;
diff --git a/Include/object.h b/Include/object.h
index 12e0c46..dffe0f8 100644
--- a/Include/object.h
+++ b/Include/object.h
@@ -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. */
-
- 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.5 */
- unaryfunc nb_index;
+ /* 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;
+
+ /* 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;
} 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 */
-
- /* Methods to implement standard operations */
-
- destructor tp_dealloc;
- printfunc tp_print;
- getattrfunc tp_getattr;
- setattrfunc tp_setattr;
- cmpfunc tp_compare;
- reprfunc tp_repr;
-
- /* Method suites for standard classes */
-
- PyNumberMethods *tp_as_number;
- PySequenceMethods *tp_as_sequence;
- PyMappingMethods *tp_as_mapping;
-
- /* More standard operations (here for binary compatibility) */
-
- 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;
-
- /* Flags to define presence of optional/expanded features */
- long tp_flags;
-
- const char *tp_doc; /* Documentation string */
-
- /* Assigned meaning in release 2.0 */
- /* call function for all accessible objects */
- traverseproc tp_traverse;
-
- /* delete references to contained objects */
- inquiry tp_clear;
-
- /* Assigned meaning in release 2.1 */
- /* rich comparisons */
- richcmpfunc tp_richcompare;
-
- /* weak reference enabler */
- Py_ssize_t tp_weaklistoffset;
-
- /* 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;
-
- /* Type attribute cache version tag. Added in version 2.6 */
- unsigned int tp_version_tag;
+ 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 */
+
+ destructor tp_dealloc;
+ printfunc tp_print;
+ getattrfunc tp_getattr;
+ setattrfunc tp_setattr;
+ cmpfunc tp_compare;
+ reprfunc tp_repr;
+
+ /* Method suites for standard classes */
+
+ PyNumberMethods *tp_as_number;
+ PySequenceMethods *tp_as_sequence;
+ PyMappingMethods *tp_as_mapping;
+
+ /* More standard operations (here for binary compatibility) */
+
+ 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;
+
+ /* Flags to define presence of optional/expanded features */
+ long tp_flags;
+
+ const char *tp_doc; /* Documentation string */
+
+ /* Assigned meaning in release 2.0 */
+ /* call function for all accessible objects */
+ traverseproc tp_traverse;
+
+ /* delete references to contained objects */
+ inquiry tp_clear;
+
+ /* Assigned meaning in release 2.1 */
+ /* rich comparisons */
+ richcmpfunc tp_richcompare;
+
+ /* weak reference enabler */
+ Py_ssize_t tp_weaklistoffset;
+
+ /* 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;
+
+ /* 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
}
diff --git a/Include/objimpl.h b/Include/objimpl.h
index 4176c6b..55e83ec 100644
--- a/Include/objimpl.h
+++ b/Include/objimpl.h
@@ -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
-
-#else /* WITH_PYMALLOC && ! PYMALLOC_DEBUG */
-#define PyObject_MALLOC PyObject_Malloc
-#define PyObject_REALLOC PyObject_Realloc
-#define PyObject_FREE PyObject_Free
+#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
#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
}
diff --git a/Include/pyerrors.h b/Include/pyerrors.h
index 432004a..dbe3bfa 100644
--- a/Include/pyerrors.h
+++ b/Include/pyerrors.h
@@ -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
}
diff --git a/Include/pymacconfig.h b/Include/pymacconfig.h
index 813a617..6d4a971 100644
--- a/Include/pymacconfig.h
+++ b/Include/pymacconfig.h
@@ -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__) */
diff --git a/Include/pyport.h b/Include/pyport.h
index e02a5fd..7c2dab0 100644
--- a/Include/pyport.h
+++ b/Include/pyport.h
@@ -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_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_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)
/* 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 */
diff --git a/Include/pythonrun.h b/Include/pythonrun.h
index 4ce0536..f8ed718 100644
--- a/Include/pythonrun.h
+++ b/Include/pythonrun.h
@@ -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);
diff --git a/Include/setobject.h b/Include/setobject.h
index 92adf52..52b07d5 100644
--- a/Include/setobject.h
+++ b/Include/setobject.h
@@ -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
-
- 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;
-
- /* 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 */
+ PyObject_HEAD
+
+ 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;
+
+ /* 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 */
};
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 *);
diff --git a/Include/structmember.h b/Include/structmember.h
index 1f26b42..fe5b44e 100644
--- a/Include/structmember.h
+++ b/Include/structmember.h
@@ -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 */
diff --git a/Include/symtable.h b/Include/symtable.h
index 081fd3b..e0a0be4 100644
--- a/Include/symtable.h
+++ b/Include/symtable.h
@@ -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
diff --git a/Include/unicodeobject.h b/Include/unicodeobject.h
index b3fe2f7..9ab724a 100644
--- a/Include/unicodeobject.h
+++ b/Include/unicodeobject.h
@@ -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
diff --git a/Mac/Modules/ColorPickermodule.c b/Mac/Modules/ColorPickermodule.c
index 51d7c37..688c468 100644
--- a/Mac/Modules/ColorPickermodule.c
+++ b/Mac/Modules/ColorPickermodule.c
@@ -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;
-
- /* 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");
+ PyObject *m;
+
+ if (PyErr_WarnPy3k("In 3.x, the ColorPicker module is removed.", 1) < 0)
+ return;
+
+ /* 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");
}
diff --git a/Mac/Modules/MacOS.c b/Mac/Modules/MacOS.c
index 19deb44..28de4f5 100644
--- a/Mac/Modules/MacOS.c
+++ b/Mac/Modules/MacOS.c
@@ -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.
@@ -34,7 +34,7 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#ifndef HAVE_OSX105_SDK
-typedef SInt16 FSIORefNum;
+typedef SInt16 FSIORefNum;
#endif
static PyObject *MacOS_Error; /* Exception MacOS.Error */
@@ -46,9 +46,9 @@ static PyObject *MacOS_Error; /* Exception MacOS.Error */
/* Declarations for objects of type Resource fork */
typedef struct {
- PyObject_HEAD
- FSIORefNum fRefNum;
- int isclosed;
+ PyObject_HEAD
+ FSIORefNum fRefNum;
+ int isclosed;
} rfobject;
static PyTypeObject Rftype;
@@ -60,166 +60,166 @@ static PyTypeObject Rftype;
static void
do_close(rfobject *self)
{
- if (self->isclosed ) return;
- (void)FSCloseFork(self->fRefNum);
- self->isclosed = 1;
+ if (self->isclosed ) return;
+ (void)FSCloseFork(self->fRefNum);
+ self->isclosed = 1;
}
-static char rf_read__doc__[] =
+static char rf_read__doc__[] =
"Read data from resource fork"
;
static PyObject *
rf_read(rfobject *self, PyObject *args)
{
- long n;
- PyObject *v;
- OSErr err;
- ByteCount n2;
-
- if (self->isclosed) {
- PyErr_SetString(PyExc_ValueError, "Operation on closed file");
- return NULL;
- }
-
- if (!PyArg_ParseTuple(args, "l", &n))
- return NULL;
-
- v = PyBytes_FromStringAndSize((char *)NULL, n);
- if (v == NULL)
- return NULL;
-
- err = FSReadFork(self->fRefNum, fsAtMark, 0, n, PyString_AsString(v), &n2);
- if (err && err != eofErr) {
- PyMac_Error(err);
- Py_DECREF(v);
- return NULL;
- }
- _PyString_Resize(&v, n2);
- return v;
+ long n;
+ PyObject *v;
+ OSErr err;
+ ByteCount n2;
+
+ if (self->isclosed) {
+ PyErr_SetString(PyExc_ValueError, "Operation on closed file");
+ return NULL;
+ }
+
+ if (!PyArg_ParseTuple(args, "l", &n))
+ return NULL;
+
+ v = PyBytes_FromStringAndSize((char *)NULL, n);
+ if (v == NULL)
+ return NULL;
+
+ err = FSReadFork(self->fRefNum, fsAtMark, 0, n, PyString_AsString(v), &n2);
+ if (err && err != eofErr) {
+ PyMac_Error(err);
+ Py_DECREF(v);
+ return NULL;
+ }
+ _PyString_Resize(&v, n2);
+ return v;
}
-static char rf_write__doc__[] =
+static char rf_write__doc__[] =
"Write to resource fork"
;
static PyObject *
rf_write(rfobject *self, PyObject *args)
{
- char *buffer;
- long size;
- OSErr err;
-
- if (self->isclosed) {
- PyErr_SetString(PyExc_ValueError, "Operation on closed file");
- return NULL;
- }
- if (!PyArg_ParseTuple(args, "s#", &buffer, &size))
- return NULL;
- err = FSWriteFork(self->fRefNum, fsAtMark, 0, size, buffer, NULL);
- if (err) {
- PyMac_Error(err);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ char *buffer;
+ long size;
+ OSErr err;
+
+ if (self->isclosed) {
+ PyErr_SetString(PyExc_ValueError, "Operation on closed file");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(args, "s#", &buffer, &size))
+ return NULL;
+ err = FSWriteFork(self->fRefNum, fsAtMark, 0, size, buffer, NULL);
+ if (err) {
+ PyMac_Error(err);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static char rf_seek__doc__[] =
+static char rf_seek__doc__[] =
"Set file position"
;
static PyObject *
rf_seek(rfobject *self, PyObject *args)
{
- long amount;
- int whence = SEEK_SET;
- int mode;
- OSErr err;
-
- if (self->isclosed) {
- PyErr_SetString(PyExc_ValueError, "Operation on closed file");
- return NULL;
- }
- if (!PyArg_ParseTuple(args, "l|i", &amount, &whence)) {
- return NULL;
- }
-
- switch (whence) {
- case SEEK_CUR:
- mode = fsFromMark;
- break;
- case SEEK_END:
- mode = fsFromLEOF;
- break;
- case SEEK_SET:
- mode = fsFromStart;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- err = FSSetForkPosition(self->fRefNum, mode, amount);
- if (err != noErr) {
- PyMac_Error(err);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ long amount;
+ int whence = SEEK_SET;
+ int mode;
+ OSErr err;
+
+ if (self->isclosed) {
+ PyErr_SetString(PyExc_ValueError, "Operation on closed file");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(args, "l|i", &amount, &whence)) {
+ return NULL;
+ }
+
+ switch (whence) {
+ case SEEK_CUR:
+ mode = fsFromMark;
+ break;
+ case SEEK_END:
+ mode = fsFromLEOF;
+ break;
+ case SEEK_SET:
+ mode = fsFromStart;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ err = FSSetForkPosition(self->fRefNum, mode, amount);
+ if (err != noErr) {
+ PyMac_Error(err);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static char rf_tell__doc__[] =
+static char rf_tell__doc__[] =
"Get file position"
;
static PyObject *
rf_tell(rfobject *self, PyObject *args)
{
- long long where;
- OSErr err;
-
- if (self->isclosed) {
- PyErr_SetString(PyExc_ValueError, "Operation on closed file");
- return NULL;
- }
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
-
- err = FSGetForkPosition(self->fRefNum, &where);
- if (err != noErr) {
- PyMac_Error(err);
- return NULL;
- }
- return PyLong_FromLongLong(where);
+ long long where;
+ OSErr err;
+
+ if (self->isclosed) {
+ PyErr_SetString(PyExc_ValueError, "Operation on closed file");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+
+ err = FSGetForkPosition(self->fRefNum, &where);
+ if (err != noErr) {
+ PyMac_Error(err);
+ return NULL;
+ }
+ return PyLong_FromLongLong(where);
}
-static char rf_close__doc__[] =
+static char rf_close__doc__[] =
"Close resource fork"
;
static PyObject *
rf_close(rfobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- do_close(self);
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ do_close(self);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef rf_methods[] = {
- {"read", (PyCFunction)rf_read, 1, rf_read__doc__},
- {"write", (PyCFunction)rf_write, 1, rf_write__doc__},
- {"seek", (PyCFunction)rf_seek, 1, rf_seek__doc__},
- {"tell", (PyCFunction)rf_tell, 1, rf_tell__doc__},
- {"close", (PyCFunction)rf_close, 1, rf_close__doc__},
-
- {NULL, NULL} /* sentinel */
+ {"read", (PyCFunction)rf_read, 1, rf_read__doc__},
+ {"write", (PyCFunction)rf_write, 1, rf_write__doc__},
+ {"seek", (PyCFunction)rf_seek, 1, rf_seek__doc__},
+ {"tell", (PyCFunction)rf_tell, 1, rf_tell__doc__},
+ {"close", (PyCFunction)rf_close, 1, rf_close__doc__},
+
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -228,56 +228,56 @@ static struct PyMethodDef rf_methods[] = {
static rfobject *
newrfobject(void)
{
- rfobject *self;
-
- self = PyObject_NEW(rfobject, &Rftype);
- if (self == NULL)
- return NULL;
- self->isclosed = 1;
- return self;
+ rfobject *self;
+
+ self = PyObject_NEW(rfobject, &Rftype);
+ if (self == NULL)
+ return NULL;
+ self->isclosed = 1;
+ return self;
}
static void
rf_dealloc(rfobject *self)
{
- do_close(self);
- PyObject_DEL(self);
+ do_close(self);
+ PyObject_DEL(self);
}
static PyObject *
rf_getattr(rfobject *self, char *name)
{
- return Py_FindMethod(rf_methods, (PyObject *)self, name);
+ return Py_FindMethod(rf_methods, (PyObject *)self, name);
}
-static char Rftype__doc__[] =
+static char Rftype__doc__[] =
"Resource fork file object"
;
static PyTypeObject Rftype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "MacOS.ResourceFork", /*tp_name*/
- sizeof(rfobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)rf_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)rf_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,
- Rftype__doc__ /* Documentation string */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "MacOS.ResourceFork", /*tp_name*/
+ sizeof(rfobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)rf_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)rf_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,
+ Rftype__doc__ /* Documentation string */
};
@@ -292,71 +292,71 @@ static char getcrtp_doc[] = "Get MacOS 4-char creator and type for a file";
static PyObject *
MacOS_GetCreatorAndType(PyObject *self, PyObject *args)
{
- PyObject *creator, *type, *res;
- OSErr err;
- FSRef ref;
- FSCatalogInfo cataloginfo;
- FileInfo* finfo;
+ PyObject *creator, *type, *res;
+ OSErr err;
+ FSRef ref;
+ FSCatalogInfo cataloginfo;
+ FileInfo* finfo;
- if (!PyArg_ParseTuple(args, "O&", PyMac_GetFSRef, &ref)) {
+ if (!PyArg_ParseTuple(args, "O&", PyMac_GetFSRef, &ref)) {
#ifndef __LP64__
- /* This function is documented to take an FSSpec as well,
- * which only works in 32-bit mode.
- */
- PyErr_Clear();
- FSSpec fss;
- FInfo info;
-
- if (!PyArg_ParseTuple(args, "O&", PyMac_GetFSSpec, &fss))
- return NULL;
-
- if ((err = FSpGetFInfo(&fss, &info)) != noErr) {
- return PyErr_Mac(MacOS_Error, err);
- }
-
- info.fdCreator = ntohl(info.fdCreator);
- info.fdType = ntohl(info.fdType);
-
- creator = PyString_FromStringAndSize(
- (char *)&info.fdCreator, 4);
- type = PyString_FromStringAndSize((char *)&info.fdType, 4);
- res = Py_BuildValue("OO", creator, type);
- Py_DECREF(creator);
- Py_DECREF(type);
- return res;
-#else /* __LP64__ */
- return NULL;
-#endif /* __LP64__ */
- }
-
- err = FSGetCatalogInfo(&ref,
- kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
- NULL, NULL, NULL);
- if (err != noErr) {
- PyErr_Mac(MacOS_Error, err);
- return NULL;
- }
-
- if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
- /* Directory: doesn't have type/creator info.
- *
- * The specific error code is for backward compatibility with
- * earlier versions.
- */
- PyErr_Mac(MacOS_Error, fnfErr);
- return NULL;
-
- }
- finfo = (FileInfo*)&(cataloginfo.finderInfo);
- finfo->fileCreator = ntohl(finfo->fileCreator);
- finfo->fileType = ntohl(finfo->fileType);
- creator = PyString_FromStringAndSize((char*)&(finfo->fileCreator), 4);
- type = PyString_FromStringAndSize((char*)&(finfo->fileType), 4);
-
- res = Py_BuildValue("OO", creator, type);
- Py_DECREF(creator);
- Py_DECREF(type);
- return res;
+ /* This function is documented to take an FSSpec as well,
+ * which only works in 32-bit mode.
+ */
+ PyErr_Clear();
+ FSSpec fss;
+ FInfo info;
+
+ if (!PyArg_ParseTuple(args, "O&", PyMac_GetFSSpec, &fss))
+ return NULL;
+
+ if ((err = FSpGetFInfo(&fss, &info)) != noErr) {
+ return PyErr_Mac(MacOS_Error, err);
+ }
+
+ info.fdCreator = ntohl(info.fdCreator);
+ info.fdType = ntohl(info.fdType);
+
+ creator = PyString_FromStringAndSize(
+ (char *)&info.fdCreator, 4);
+ type = PyString_FromStringAndSize((char *)&info.fdType, 4);
+ res = Py_BuildValue("OO", creator, type);
+ Py_DECREF(creator);
+ Py_DECREF(type);
+ return res;
+#else /* __LP64__ */
+ return NULL;
+#endif /* __LP64__ */
+ }
+
+ err = FSGetCatalogInfo(&ref,
+ kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
+ NULL, NULL, NULL);
+ if (err != noErr) {
+ PyErr_Mac(MacOS_Error, err);
+ return NULL;
+ }
+
+ if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
+ /* Directory: doesn't have type/creator info.
+ *
+ * The specific error code is for backward compatibility with
+ * earlier versions.
+ */
+ PyErr_Mac(MacOS_Error, fnfErr);
+ return NULL;
+
+ }
+ finfo = (FileInfo*)&(cataloginfo.finderInfo);
+ finfo->fileCreator = ntohl(finfo->fileCreator);
+ finfo->fileType = ntohl(finfo->fileType);
+ creator = PyString_FromStringAndSize((char*)&(finfo->fileCreator), 4);
+ type = PyString_FromStringAndSize((char*)&(finfo->fileType), 4);
+
+ res = Py_BuildValue("OO", creator, type);
+ Py_DECREF(creator);
+ Py_DECREF(type);
+ return res;
}
static char setcrtp_doc[] = "Set MacOS 4-char creator and type for a file";
@@ -364,68 +364,68 @@ static char setcrtp_doc[] = "Set MacOS 4-char creator and type for a file";
static PyObject *
MacOS_SetCreatorAndType(PyObject *self, PyObject *args)
{
- ResType creator, type;
- FSRef ref;
- FileInfo* finfo;
- OSErr err;
- FSCatalogInfo cataloginfo;
-
- if (!PyArg_ParseTuple(args, "O&O&O&",
- PyMac_GetFSRef, &ref, PyMac_GetOSType, &creator, PyMac_GetOSType, &type)) {
+ ResType creator, type;
+ FSRef ref;
+ FileInfo* finfo;
+ OSErr err;
+ FSCatalogInfo cataloginfo;
+
+ if (!PyArg_ParseTuple(args, "O&O&O&",
+ PyMac_GetFSRef, &ref, PyMac_GetOSType, &creator, PyMac_GetOSType, &type)) {
#ifndef __LP64__
- /* Try to handle FSSpec arguments, for backward compatibility */
- FSSpec fss;
- FInfo info;
+ /* Try to handle FSSpec arguments, for backward compatibility */
+ FSSpec fss;
+ FInfo info;
- if (!PyArg_ParseTuple(args, "O&O&O&",
- PyMac_GetFSSpec, &fss, PyMac_GetOSType, &creator, PyMac_GetOSType, &type))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O&O&O&",
+ PyMac_GetFSSpec, &fss, PyMac_GetOSType, &creator, PyMac_GetOSType, &type))
+ return NULL;
- if ((err = FSpGetFInfo(&fss, &info)) != noErr)
- return PyErr_Mac(MacOS_Error, err);
+ if ((err = FSpGetFInfo(&fss, &info)) != noErr)
+ return PyErr_Mac(MacOS_Error, err);
- info.fdCreator = creator;
- info.fdType = type;
+ info.fdCreator = creator;
+ info.fdType = type;
- if ((err = FSpSetFInfo(&fss, &info)) != noErr)
- return PyErr_Mac(MacOS_Error, err);
- Py_INCREF(Py_None);
- return Py_None;
+ if ((err = FSpSetFInfo(&fss, &info)) != noErr)
+ return PyErr_Mac(MacOS_Error, err);
+ Py_INCREF(Py_None);
+ return Py_None;
#else /* __LP64__ */
- return NULL;
+ return NULL;
#endif /* __LP64__ */
- }
-
- err = FSGetCatalogInfo(&ref,
- kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
- NULL, NULL, NULL);
- if (err != noErr) {
- PyErr_Mac(MacOS_Error, err);
- return NULL;
- }
-
- if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
- /* Directory: doesn't have type/creator info.
- *
- * The specific error code is for backward compatibility with
- * earlier versions.
- */
- PyErr_Mac(MacOS_Error, fnfErr);
- return NULL;
-
- }
- finfo = (FileInfo*)&(cataloginfo.finderInfo);
- finfo->fileCreator = creator;
- finfo->fileType = type;
-
- err = FSSetCatalogInfo(&ref, kFSCatInfoFinderInfo, &cataloginfo);
- if (err != noErr) {
- PyErr_Mac(MacOS_Error, fnfErr);
- return NULL;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ }
+
+ err = FSGetCatalogInfo(&ref,
+ kFSCatInfoFinderInfo|kFSCatInfoNodeFlags, &cataloginfo,
+ NULL, NULL, NULL);
+ if (err != noErr) {
+ PyErr_Mac(MacOS_Error, err);
+ return NULL;
+ }
+
+ if ((cataloginfo.nodeFlags & kFSNodeIsDirectoryMask) != 0) {
+ /* Directory: doesn't have type/creator info.
+ *
+ * The specific error code is for backward compatibility with
+ * earlier versions.
+ */
+ PyErr_Mac(MacOS_Error, fnfErr);
+ return NULL;
+
+ }
+ finfo = (FileInfo*)&(cataloginfo.finderInfo);
+ finfo->fileCreator = creator;
+ finfo->fileType = type;
+
+ err = FSSetCatalogInfo(&ref, kFSCatInfoFinderInfo, &cataloginfo);
+ if (err != noErr) {
+ PyErr_Mac(MacOS_Error, fnfErr);
+ return NULL;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -434,65 +434,65 @@ static char geterr_doc[] = "Convert OSErr number to string";
static PyObject *
MacOS_GetErrorString(PyObject *self, PyObject *args)
{
- int err;
- char buf[256];
- Handle h;
- char *str;
- static int errors_loaded;
-
- if (!PyArg_ParseTuple(args, "i", &err))
- return NULL;
-
- h = GetResource('Estr', err);
- if (!h && !errors_loaded) {
- /*
- ** Attempt to open the resource file containing the
- ** Estr resources. We ignore all errors. We also try
- ** this only once.
- */
- PyObject *m, *rv;
- errors_loaded = 1;
-
- m = PyImport_ImportModuleNoBlock("macresource");
- if (!m) {
- if (Py_VerboseFlag)
- PyErr_Print();
- PyErr_Clear();
- }
- else {
- rv = PyObject_CallMethod(m, "open_error_resource", "");
- if (!rv) {
- if (Py_VerboseFlag)
- PyErr_Print();
- PyErr_Clear();
- }
- else {
- Py_DECREF(rv);
- /* And try again... */
- h = GetResource('Estr', err);
- }
- Py_DECREF(m);
- }
- }
- /*
- ** Whether the code above succeeded or not, we won't try
- ** again.
- */
- errors_loaded = 1;
-
- if (h) {
- HLock(h);
- str = (char *)*h;
- memcpy(buf, str+1, (unsigned char)str[0]);
- buf[(unsigned char)str[0]] = '\0';
- HUnlock(h);
- ReleaseResource(h);
- }
- else {
- PyOS_snprintf(buf, sizeof(buf), "Mac OS error code %d", err);
- }
-
- return Py_BuildValue("s", buf);
+ int err;
+ char buf[256];
+ Handle h;
+ char *str;
+ static int errors_loaded;
+
+ if (!PyArg_ParseTuple(args, "i", &err))
+ return NULL;
+
+ h = GetResource('Estr', err);
+ if (!h && !errors_loaded) {
+ /*
+ ** Attempt to open the resource file containing the
+ ** Estr resources. We ignore all errors. We also try
+ ** this only once.
+ */
+ PyObject *m, *rv;
+ errors_loaded = 1;
+
+ m = PyImport_ImportModuleNoBlock("macresource");
+ if (!m) {
+ if (Py_VerboseFlag)
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ else {
+ rv = PyObject_CallMethod(m, "open_error_resource", "");
+ if (!rv) {
+ if (Py_VerboseFlag)
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ else {
+ Py_DECREF(rv);
+ /* And try again... */
+ h = GetResource('Estr', err);
+ }
+ Py_DECREF(m);
+ }
+ }
+ /*
+ ** Whether the code above succeeded or not, we won't try
+ ** again.
+ */
+ errors_loaded = 1;
+
+ if (h) {
+ HLock(h);
+ str = (char *)*h;
+ memcpy(buf, str+1, (unsigned char)str[0]);
+ buf[(unsigned char)str[0]] = '\0';
+ HUnlock(h);
+ ReleaseResource(h);
+ }
+ else {
+ PyOS_snprintf(buf, sizeof(buf), "Mac OS error code %d", err);
+ }
+
+ return Py_BuildValue("s", buf);
}
@@ -503,42 +503,42 @@ static char splash_doc[] = "Open a splash-screen dialog by resource-id (0=close)
static PyObject *
MacOS_splash(PyObject *self, PyObject *args)
{
- int resid = -1;
- static DialogPtr curdialog = NULL;
- DialogPtr olddialog;
- WindowRef theWindow;
- CGrafPtr thePort;
+ int resid = -1;
+ static DialogPtr curdialog = NULL;
+ DialogPtr olddialog;
+ WindowRef theWindow;
+ CGrafPtr thePort;
#if 0
- short xpos, ypos, width, height, swidth, sheight;
+ short xpos, ypos, width, height, swidth, sheight;
#endif
-
- if (!PyArg_ParseTuple(args, "|i", &resid))
- return NULL;
- olddialog = curdialog;
- curdialog = NULL;
-
- if ( resid != -1 ) {
- curdialog = GetNewDialog(resid, NULL, (WindowPtr)-1);
- if ( curdialog ) {
- theWindow = GetDialogWindow(curdialog);
- thePort = GetWindowPort(theWindow);
+
+ if (!PyArg_ParseTuple(args, "|i", &resid))
+ return NULL;
+ olddialog = curdialog;
+ curdialog = NULL;
+
+ if ( resid != -1 ) {
+ curdialog = GetNewDialog(resid, NULL, (WindowPtr)-1);
+ if ( curdialog ) {
+ theWindow = GetDialogWindow(curdialog);
+ thePort = GetWindowPort(theWindow);
#if 0
- width = thePort->portRect.right - thePort->portRect.left;
- height = thePort->portRect.bottom - thePort->portRect.top;
- swidth = qd.screenBits.bounds.right - qd.screenBits.bounds.left;
- sheight = qd.screenBits.bounds.bottom - qd.screenBits.bounds.top - LMGetMBarHeight();
- xpos = (swidth-width)/2;
- ypos = (sheight-height)/5 + LMGetMBarHeight();
- MoveWindow(theWindow, xpos, ypos, 0);
- ShowWindow(theWindow);
+ width = thePort->portRect.right - thePort->portRect.left;
+ height = thePort->portRect.bottom - thePort->portRect.top;
+ swidth = qd.screenBits.bounds.right - qd.screenBits.bounds.left;
+ sheight = qd.screenBits.bounds.bottom - qd.screenBits.bounds.top - LMGetMBarHeight();
+ xpos = (swidth-width)/2;
+ ypos = (sheight-height)/5 + LMGetMBarHeight();
+ MoveWindow(theWindow, xpos, ypos, 0);
+ ShowWindow(theWindow);
#endif
- DrawDialog(curdialog);
- }
- }
- if (olddialog)
- DisposeDialog(olddialog);
- Py_INCREF(Py_None);
- return Py_None;
+ DrawDialog(curdialog);
+ }
+ }
+ if (olddialog)
+ DisposeDialog(olddialog);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static char DebugStr_doc[] = "Switch to low-level debugger with a message";
@@ -546,15 +546,15 @@ static char DebugStr_doc[] = "Switch to low-level debugger with a message";
static PyObject *
MacOS_DebugStr(PyObject *self, PyObject *args)
{
- Str255 message;
- PyObject *object = 0;
-
- if (!PyArg_ParseTuple(args, "O&|O", PyMac_GetStr255, message, &object))
- return NULL;
-
- DebugStr(message);
- Py_INCREF(Py_None);
- return Py_None;
+ Str255 message;
+ PyObject *object = 0;
+
+ if (!PyArg_ParseTuple(args, "O&|O", PyMac_GetStr255, message, &object))
+ return NULL;
+
+ DebugStr(message);
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -563,59 +563,59 @@ static char SysBeep_doc[] = "BEEEEEP!!!";
static PyObject *
MacOS_SysBeep(PyObject *self, PyObject *args)
{
- int duration = 6;
-
- if (!PyArg_ParseTuple(args, "|i", &duration))
- return NULL;
- SysBeep(duration);
- Py_INCREF(Py_None);
- return Py_None;
+ int duration = 6;
+
+ if (!PyArg_ParseTuple(args, "|i", &duration))
+ return NULL;
+ SysBeep(duration);
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* __LP64__ */
-static char WMAvailable_doc[] =
- "True if this process can interact with the display."
- "Will foreground the application on the first call as a side-effect."
- ;
+static char WMAvailable_doc[] =
+ "True if this process can interact with the display."
+ "Will foreground the application on the first call as a side-effect."
+ ;
static PyObject *
MacOS_WMAvailable(PyObject *self, PyObject *args)
{
- static PyObject *rv = NULL;
-
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- if (!rv) {
- ProcessSerialNumber psn;
-
- /*
- ** This is a fairly innocuous call to make if we don't have a window
- ** manager, or if we have no permission to talk to it. It will print
- ** a message on stderr, but at least it won't abort the process.
- ** It appears the function caches the result itself, and it's cheap, so
- ** no need for us to cache.
- */
+ static PyObject *rv = NULL;
+
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ if (!rv) {
+ ProcessSerialNumber psn;
+
+ /*
+ ** This is a fairly innocuous call to make if we don't have a window
+ ** manager, or if we have no permission to talk to it. It will print
+ ** a message on stderr, but at least it won't abort the process.
+ ** It appears the function caches the result itself, and it's cheap, so
+ ** no need for us to cache.
+ */
#ifdef kCGNullDirectDisplay
- /* On 10.1 CGMainDisplayID() isn't available, and
- ** kCGNullDirectDisplay isn't defined.
- */
- if (CGMainDisplayID() == 0) {
- rv = Py_False;
- } else {
+ /* On 10.1 CGMainDisplayID() isn't available, and
+ ** kCGNullDirectDisplay isn't defined.
+ */
+ if (CGMainDisplayID() == 0) {
+ rv = Py_False;
+ } else {
#else
- {
+ {
#endif
- if (GetCurrentProcess(&psn) < 0 ||
- SetFrontProcess(&psn) < 0) {
- rv = Py_False;
- } else {
- rv = Py_True;
- }
- }
- }
- Py_INCREF(rv);
- return rv;
+ if (GetCurrentProcess(&psn) < 0 ||
+ SetFrontProcess(&psn) < 0) {
+ rv = Py_False;
+ } else {
+ rv = Py_True;
+ }
+ }
+ }
+ Py_INCREF(rv);
+ return rv;
}
static char GetTicks_doc[] = "Return number of ticks since bootup";
@@ -623,7 +623,7 @@ static char GetTicks_doc[] = "Return number of ticks since bootup";
static PyObject *
MacOS_GetTicks(PyObject *self, PyObject *args)
{
- return Py_BuildValue("i", (int)TickCount());
+ return Py_BuildValue("i", (int)TickCount());
}
static char openrf_doc[] = "Open resource fork of a file";
@@ -631,100 +631,100 @@ static char openrf_doc[] = "Open resource fork of a file";
static PyObject *
MacOS_openrf(PyObject *self, PyObject *args)
{
- OSErr err;
- char *mode = "r";
- FSRef ref;
- SInt8 permission = fsRdPerm;
- rfobject *fp;
- HFSUniStr255 name;
-
- if (!PyArg_ParseTuple(args, "O&|s", PyMac_GetFSRef, &ref, &mode))
- return NULL;
- while (*mode) {
- switch (*mode++) {
- case '*': break;
- case 'r': permission = fsRdPerm; break;
- case 'w': permission = fsWrPerm; break;
- case 'b': break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
- }
-
- err = FSGetResourceForkName(&name);
- if (err != noErr) {
- PyMac_Error(err);
- return NULL;
- }
-
- if ( (fp = newrfobject()) == NULL )
- return NULL;
-
-
- err = FSOpenFork(&ref, name.length, name.unicode, permission, &fp->fRefNum);
- if (err != noErr) {
- Py_DECREF(fp);
- PyMac_Error(err);
- return NULL;
- }
- fp->isclosed = 0;
- return (PyObject *)fp;
+ OSErr err;
+ char *mode = "r";
+ FSRef ref;
+ SInt8 permission = fsRdPerm;
+ rfobject *fp;
+ HFSUniStr255 name;
+
+ if (!PyArg_ParseTuple(args, "O&|s", PyMac_GetFSRef, &ref, &mode))
+ return NULL;
+ while (*mode) {
+ switch (*mode++) {
+ case '*': break;
+ case 'r': permission = fsRdPerm; break;
+ case 'w': permission = fsWrPerm; break;
+ case 'b': break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+ }
+
+ err = FSGetResourceForkName(&name);
+ if (err != noErr) {
+ PyMac_Error(err);
+ return NULL;
+ }
+
+ if ( (fp = newrfobject()) == NULL )
+ return NULL;
+
+
+ err = FSOpenFork(&ref, name.length, name.unicode, permission, &fp->fRefNum);
+ if (err != noErr) {
+ Py_DECREF(fp);
+ PyMac_Error(err);
+ return NULL;
+ }
+ fp->isclosed = 0;
+ return (PyObject *)fp;
}
static PyMethodDef MacOS_Methods[] = {
- {"GetCreatorAndType", MacOS_GetCreatorAndType, 1, getcrtp_doc},
- {"SetCreatorAndType", MacOS_SetCreatorAndType, 1, setcrtp_doc},
- {"GetErrorString", MacOS_GetErrorString, 1, geterr_doc},
- {"openrf", MacOS_openrf, 1, openrf_doc},
+ {"GetCreatorAndType", MacOS_GetCreatorAndType, 1, getcrtp_doc},
+ {"SetCreatorAndType", MacOS_SetCreatorAndType, 1, setcrtp_doc},
+ {"GetErrorString", MacOS_GetErrorString, 1, geterr_doc},
+ {"openrf", MacOS_openrf, 1, openrf_doc},
#ifndef __LP64__
- {"splash", MacOS_splash, 1, splash_doc},
- {"DebugStr", MacOS_DebugStr, 1, DebugStr_doc},
- {"SysBeep", MacOS_SysBeep, 1, SysBeep_doc},
+ {"splash", MacOS_splash, 1, splash_doc},
+ {"DebugStr", MacOS_DebugStr, 1, DebugStr_doc},
+ {"SysBeep", MacOS_SysBeep, 1, SysBeep_doc},
#endif /* __LP64__ */
- {"GetTicks", MacOS_GetTicks, 1, GetTicks_doc},
- {"WMAvailable", MacOS_WMAvailable, 1, WMAvailable_doc},
- {NULL, NULL} /* Sentinel */
+ {"GetTicks", MacOS_GetTicks, 1, GetTicks_doc},
+ {"WMAvailable", MacOS_WMAvailable, 1, WMAvailable_doc},
+ {NULL, NULL} /* Sentinel */
};
void
initMacOS(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("In 3.x, the MacOS module is removed.", 1))
- return;
-
- m = Py_InitModule("MacOS", MacOS_Methods);
- d = PyModule_GetDict(m);
-
- /* Initialize MacOS.Error exception */
- MacOS_Error = PyMac_GetOSErrException();
- if (MacOS_Error == NULL || PyDict_SetItemString(d, "Error", MacOS_Error) != 0)
- return;
- Rftype.ob_type = &PyType_Type;
- Py_INCREF(&Rftype);
- if (PyDict_SetItemString(d, "ResourceForkType", (PyObject *)&Rftype) != 0)
- return;
- /*
- ** This is a hack: the following constant added to the id() of a string
- ** object gives you the address of the data. Unfortunately, it is needed for
- ** some of the image and sound processing interfaces on the mac:-(
- */
- {
- PyStringObject *p = 0;
- long off = (long)&(p->ob_sval[0]);
-
- if( PyDict_SetItemString(d, "string_id_to_buffer", Py_BuildValue("i", off)) != 0)
- return;
- }
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("In 3.x, the MacOS module is removed.", 1))
+ return;
+
+ m = Py_InitModule("MacOS", MacOS_Methods);
+ d = PyModule_GetDict(m);
+
+ /* Initialize MacOS.Error exception */
+ MacOS_Error = PyMac_GetOSErrException();
+ if (MacOS_Error == NULL || PyDict_SetItemString(d, "Error", MacOS_Error) != 0)
+ return;
+ Rftype.ob_type = &PyType_Type;
+ Py_INCREF(&Rftype);
+ if (PyDict_SetItemString(d, "ResourceForkType", (PyObject *)&Rftype) != 0)
+ return;
+ /*
+ ** This is a hack: the following constant added to the id() of a string
+ ** object gives you the address of the data. Unfortunately, it is needed for
+ ** some of the image and sound processing interfaces on the mac:-(
+ */
+ {
+ PyStringObject *p = 0;
+ long off = (long)&(p->ob_sval[0]);
+
+ if( PyDict_SetItemString(d, "string_id_to_buffer", Py_BuildValue("i", off)) != 0)
+ return;
+ }
#define PY_RUNTIMEMODEL "macho"
- if (PyDict_SetItemString(d, "runtimemodel",
- Py_BuildValue("s", PY_RUNTIMEMODEL)) != 0)
- return;
+ if (PyDict_SetItemString(d, "runtimemodel",
+ Py_BuildValue("s", PY_RUNTIMEMODEL)) != 0)
+ return;
#if defined(WITH_NEXT_FRAMEWORK)
#define PY_LINKMODEL "framework"
#elif defined(Py_ENABLE_SHARED)
@@ -732,8 +732,8 @@ initMacOS(void)
#else
#define PY_LINKMODEL "static"
#endif
- if (PyDict_SetItemString(d, "linkmodel",
- Py_BuildValue("s", PY_LINKMODEL)) != 0)
- return;
+ if (PyDict_SetItemString(d, "linkmodel",
+ Py_BuildValue("s", PY_LINKMODEL)) != 0)
+ return;
}
diff --git a/Mac/Modules/Nav.c b/Mac/Modules/Nav.c
index f7b19b9..7118d43 100644
--- a/Mac/Modules/Nav.c
+++ b/Mac/Modules/Nav.c
@@ -44,172 +44,172 @@ static NavObjectFilterUPP my_filterProcUPP;
/* Callback functions */
static pascal void
my_eventProc(NavEventCallbackMessage callBackSelector,
- NavCBRecPtr callBackParms,
- NavCallBackUserData callbackUD)
+ NavCBRecPtr callBackParms,
+ NavCallBackUserData callbackUD)
{
- PyObject *dict = (PyObject *)callbackUD;
- PyObject *pyfunc;
- PyObject *rv;
-
- if (!dict) return;
- if ( (pyfunc = PyDict_GetItemString(dict, "eventProc")) == NULL ) {
- PyErr_Print();
- return;
- }
- if ( pyfunc == Py_None ) {
- return;
- }
- rv = PyObject_CallFunction(pyfunc, "ls#", (long)callBackSelector,
- (void *)callBackParms, sizeof(NavCBRec));
- if ( rv )
- Py_DECREF(rv);
- else {
- PySys_WriteStderr("Nav: exception in eventProc callback\n");
- PyErr_Print();
- }
+ PyObject *dict = (PyObject *)callbackUD;
+ PyObject *pyfunc;
+ PyObject *rv;
+
+ if (!dict) return;
+ if ( (pyfunc = PyDict_GetItemString(dict, "eventProc")) == NULL ) {
+ PyErr_Print();
+ return;
+ }
+ if ( pyfunc == Py_None ) {
+ return;
+ }
+ rv = PyObject_CallFunction(pyfunc, "ls#", (long)callBackSelector,
+ (void *)callBackParms, sizeof(NavCBRec));
+ if ( rv )
+ Py_DECREF(rv);
+ else {
+ PySys_WriteStderr("Nav: exception in eventProc callback\n");
+ PyErr_Print();
+ }
}
static pascal Boolean
my_previewProc(NavCBRecPtr callBackParms,
- NavCallBackUserData callbackUD)
+ NavCallBackUserData callbackUD)
{
- PyObject *dict = (PyObject *)callbackUD;
- PyObject *pyfunc;
- PyObject *rv;
- Boolean c_rv = false;
-
- if (!dict) return false;
- if ( (pyfunc = PyDict_GetItemString(dict, "previewProc")) == NULL ) {
- PyErr_Print();
- return false;
- }
- rv = PyObject_CallFunction(pyfunc, "s#", (void *)callBackParms, sizeof(NavCBRec));
- if ( rv ) {
- c_rv = PyObject_IsTrue(rv);
- Py_DECREF(rv);
- } else {
- PySys_WriteStderr("Nav: exception in previewProc callback\n");
- PyErr_Print();
- }
- return c_rv;
+ PyObject *dict = (PyObject *)callbackUD;
+ PyObject *pyfunc;
+ PyObject *rv;
+ Boolean c_rv = false;
+
+ if (!dict) return false;
+ if ( (pyfunc = PyDict_GetItemString(dict, "previewProc")) == NULL ) {
+ PyErr_Print();
+ return false;
+ }
+ rv = PyObject_CallFunction(pyfunc, "s#", (void *)callBackParms, sizeof(NavCBRec));
+ if ( rv ) {
+ c_rv = PyObject_IsTrue(rv);
+ Py_DECREF(rv);
+ } else {
+ PySys_WriteStderr("Nav: exception in previewProc callback\n");
+ PyErr_Print();
+ }
+ return c_rv;
}
static pascal Boolean
my_filterProc(AEDesc *theItem, void *info,
- NavCallBackUserData callbackUD,
- NavFilterModes filterMode)
+ NavCallBackUserData callbackUD,
+ NavFilterModes filterMode)
{
- PyObject *dict = (PyObject *)callbackUD;
- PyObject *pyfunc;
- PyObject *rv;
- Boolean c_rv = false;
-
- if (!dict) return false;
- if ( (pyfunc = PyDict_GetItemString(dict, "filterProc")) == NULL ) {
- PyErr_Print();
- return false;
- }
- rv = PyObject_CallFunction(pyfunc, "O&s#h",
- AEDesc_NewBorrowed, theItem, info, sizeof(NavFileOrFolderInfo), (short)filterMode);
- if ( rv ) {
- c_rv = PyObject_IsTrue(rv);
- Py_DECREF(rv);
- } else {
- PySys_WriteStderr("Nav: exception in filterProc callback\n");
- PyErr_Print();
- }
- return c_rv;
+ PyObject *dict = (PyObject *)callbackUD;
+ PyObject *pyfunc;
+ PyObject *rv;
+ Boolean c_rv = false;
+
+ if (!dict) return false;
+ if ( (pyfunc = PyDict_GetItemString(dict, "filterProc")) == NULL ) {
+ PyErr_Print();
+ return false;
+ }
+ rv = PyObject_CallFunction(pyfunc, "O&s#h",
+ AEDesc_NewBorrowed, theItem, info, sizeof(NavFileOrFolderInfo), (short)filterMode);
+ if ( rv ) {
+ c_rv = PyObject_IsTrue(rv);
+ Py_DECREF(rv);
+ } else {
+ PySys_WriteStderr("Nav: exception in filterProc callback\n");
+ PyErr_Print();
+ }
+ return c_rv;
}
/* ----------------------------------------------------- */
static int
filldialogoptions(PyObject *d,
- AEDesc **defaultLocationP,
- NavDialogOptions *opt,
- NavEventUPP *eventProcP,
- NavPreviewUPP *previewProcP,
- NavObjectFilterUPP *filterProcP,
- NavTypeListHandle *typeListP,
- OSType *fileTypeP,
- OSType *fileCreatorP)
+ AEDesc **defaultLocationP,
+ NavDialogOptions *opt,
+ NavEventUPP *eventProcP,
+ NavPreviewUPP *previewProcP,
+ NavObjectFilterUPP *filterProcP,
+ NavTypeListHandle *typeListP,
+ OSType *fileTypeP,
+ OSType *fileCreatorP)
{
- Py_ssize_t pos = 0;
- PyObject *key, *value;
- char *keystr;
- AEDesc *defaultLocation_storage;
-
- NavGetDefaultDialogOptions(opt);
-
- while ( PyDict_Next(d, &pos, &key, &value) ) {
- if ( !key || !value || !PyString_Check(key) ) {
- PyErr_SetString(ErrorObject, "DialogOption has non-string key");
- return 0;
- }
- keystr = PyString_AsString(key);
- if( strcmp(keystr, "defaultLocation") == 0 ) {
- if ( (defaultLocation_storage = PyMem_NEW(AEDesc, 1)) == NULL ) {
- PyErr_NoMemory();
- return 0;
- }
- if ( !PyArg_Parse(value, "O&", AEDesc_Convert, defaultLocation_storage) ) {
- PyMem_DEL(defaultLocation_storage);
- return 0;
- }
- *defaultLocationP = defaultLocation_storage;
- } else if( strcmp(keystr, "version") == 0 ) {
- if ( !PyArg_Parse(value, "H", &opt->version) )
- return 0;
- } else if( strcmp(keystr, "dialogOptionFlags") == 0 ) {
- if ( !PyArg_Parse(value, "k", &opt->dialogOptionFlags) )
- return 0;
- } else if( strcmp(keystr, "location") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetPoint, &opt->location) )
- return 0;
- } else if( strcmp(keystr, "clientName") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->clientName) )
- return 0;
- } else if( strcmp(keystr, "windowTitle") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->windowTitle) )
- return 0;
- } else if( strcmp(keystr, "actionButtonLabel") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->actionButtonLabel) )
- return 0;
- } else if( strcmp(keystr, "cancelButtonLabel") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->cancelButtonLabel) )
- return 0;
- } else if( strcmp(keystr, "savedFileName") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->savedFileName) )
- return 0;
- } else if( strcmp(keystr, "message") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->message) )
- return 0;
- } else if( strcmp(keystr, "preferenceKey") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetOSType, &opt->preferenceKey) )
- return 0;
- } else if( strcmp(keystr, "popupExtension") == 0 ) {
- if ( !PyArg_Parse(value, "O&", ResObj_Convert, &opt->popupExtension) )
- return 0;
- } else if( eventProcP && strcmp(keystr, "eventProc") == 0 ) {
- *eventProcP = my_eventProcUPP;
- } else if( previewProcP && strcmp(keystr, "previewProc") == 0 ) {
- *previewProcP = my_previewProcUPP;
- } else if( filterProcP && strcmp(keystr, "filterProc") == 0 ) {
- *filterProcP = my_filterProcUPP;
- } else if( typeListP && strcmp(keystr, "typeList") == 0 ) {
- if ( !PyArg_Parse(value, "O&", ResObj_Convert, typeListP) )
- return 0;
- } else if( fileTypeP && strcmp(keystr, "fileType") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetOSType, fileTypeP) )
- return 0;
- } else if( fileCreatorP && strcmp(keystr, "fileCreator") == 0 ) {
- if ( !PyArg_Parse(value, "O&", PyMac_GetOSType, fileCreatorP) )
- return 0;
- } else {
- PyErr_Format(ErrorObject, "Unknown DialogOption key: %s", keystr);
- return 0;
- }
- }
- return 1;
+ Py_ssize_t pos = 0;
+ PyObject *key, *value;
+ char *keystr;
+ AEDesc *defaultLocation_storage;
+
+ NavGetDefaultDialogOptions(opt);
+
+ while ( PyDict_Next(d, &pos, &key, &value) ) {
+ if ( !key || !value || !PyString_Check(key) ) {
+ PyErr_SetString(ErrorObject, "DialogOption has non-string key");
+ return 0;
+ }
+ keystr = PyString_AsString(key);
+ if( strcmp(keystr, "defaultLocation") == 0 ) {
+ if ( (defaultLocation_storage = PyMem_NEW(AEDesc, 1)) == NULL ) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ if ( !PyArg_Parse(value, "O&", AEDesc_Convert, defaultLocation_storage) ) {
+ PyMem_DEL(defaultLocation_storage);
+ return 0;
+ }
+ *defaultLocationP = defaultLocation_storage;
+ } else if( strcmp(keystr, "version") == 0 ) {
+ if ( !PyArg_Parse(value, "H", &opt->version) )
+ return 0;
+ } else if( strcmp(keystr, "dialogOptionFlags") == 0 ) {
+ if ( !PyArg_Parse(value, "k", &opt->dialogOptionFlags) )
+ return 0;
+ } else if( strcmp(keystr, "location") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetPoint, &opt->location) )
+ return 0;
+ } else if( strcmp(keystr, "clientName") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->clientName) )
+ return 0;
+ } else if( strcmp(keystr, "windowTitle") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->windowTitle) )
+ return 0;
+ } else if( strcmp(keystr, "actionButtonLabel") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->actionButtonLabel) )
+ return 0;
+ } else if( strcmp(keystr, "cancelButtonLabel") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->cancelButtonLabel) )
+ return 0;
+ } else if( strcmp(keystr, "savedFileName") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->savedFileName) )
+ return 0;
+ } else if( strcmp(keystr, "message") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetStr255, &opt->message) )
+ return 0;
+ } else if( strcmp(keystr, "preferenceKey") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetOSType, &opt->preferenceKey) )
+ return 0;
+ } else if( strcmp(keystr, "popupExtension") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", ResObj_Convert, &opt->popupExtension) )
+ return 0;
+ } else if( eventProcP && strcmp(keystr, "eventProc") == 0 ) {
+ *eventProcP = my_eventProcUPP;
+ } else if( previewProcP && strcmp(keystr, "previewProc") == 0 ) {
+ *previewProcP = my_previewProcUPP;
+ } else if( filterProcP && strcmp(keystr, "filterProc") == 0 ) {
+ *filterProcP = my_filterProcUPP;
+ } else if( typeListP && strcmp(keystr, "typeList") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", ResObj_Convert, typeListP) )
+ return 0;
+ } else if( fileTypeP && strcmp(keystr, "fileType") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetOSType, fileTypeP) )
+ return 0;
+ } else if( fileCreatorP && strcmp(keystr, "fileCreator") == 0 ) {
+ if ( !PyArg_Parse(value, "O&", PyMac_GetOSType, fileCreatorP) )
+ return 0;
+ } else {
+ PyErr_Format(ErrorObject, "Unknown DialogOption key: %s", keystr);
+ return 0;
+ }
+ }
+ return 1;
}
/* ----------------------------------------------------- */
@@ -217,8 +217,8 @@ filldialogoptions(PyObject *d,
/* Declarations for objects of type NavReplyRecord */
typedef struct {
- PyObject_HEAD
- NavReplyRecord itself;
+ PyObject_HEAD
+ NavReplyRecord itself;
} navrrobject;
static PyTypeObject Navrrtype;
@@ -234,18 +234,18 @@ static char nav_NavTranslateFile__doc__[] =
static PyObject *
nav_NavTranslateFile(navrrobject *self, PyObject *args)
{
- NavTranslationOptions howToTranslate;
- OSErr err;
-
- if (!PyArg_ParseTuple(args, "k", &howToTranslate))
- return NULL;
- err = NavTranslateFile(&self->itself, howToTranslate);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ NavTranslationOptions howToTranslate;
+ OSErr err;
+
+ if (!PyArg_ParseTuple(args, "k", &howToTranslate))
+ return NULL;
+ err = NavTranslateFile(&self->itself, howToTranslate);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static char nav_NavCompleteSave__doc__[] =
@@ -255,26 +255,26 @@ static char nav_NavCompleteSave__doc__[] =
static PyObject *
nav_NavCompleteSave(navrrobject *self, PyObject *args)
{
- NavTranslationOptions howToTranslate;
- OSErr err;
-
- if (!PyArg_ParseTuple(args, "k", &howToTranslate))
- return NULL;
- err = NavCompleteSave(&self->itself, howToTranslate);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ NavTranslationOptions howToTranslate;
+ OSErr err;
+
+ if (!PyArg_ParseTuple(args, "k", &howToTranslate))
+ return NULL;
+ err = NavCompleteSave(&self->itself, howToTranslate);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef navrr_methods[] = {
- {"NavTranslateFile", (PyCFunction)nav_NavTranslateFile, METH_VARARGS, nav_NavTranslateFile__doc__},
- {"NavCompleteSave", (PyCFunction)nav_NavCompleteSave, METH_VARARGS, nav_NavCompleteSave__doc__},
-
- {NULL, NULL} /* sentinel */
+ {"NavTranslateFile", (PyCFunction)nav_NavTranslateFile, METH_VARARGS, nav_NavTranslateFile__doc__},
+ {"NavCompleteSave", (PyCFunction)nav_NavCompleteSave, METH_VARARGS, nav_NavCompleteSave__doc__},
+
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -283,161 +283,161 @@ static struct PyMethodDef navrr_methods[] = {
static navrrobject *
newnavrrobject(NavReplyRecord *itself)
{
- navrrobject *self;
-
- self = PyObject_NEW(navrrobject, &Navrrtype);
- if (self == NULL)
- return NULL;
- self->itself = *itself;
- return self;
+ navrrobject *self;
+
+ self = PyObject_NEW(navrrobject, &Navrrtype);
+ if (self == NULL)
+ return NULL;
+ self->itself = *itself;
+ return self;
}
static void
navrr_dealloc(navrrobject *self)
{
- NavDisposeReply(&self->itself);
- PyObject_DEL(self);
+ NavDisposeReply(&self->itself);
+ PyObject_DEL(self);
}
static PyObject *
navrr_getattr(navrrobject *self, char *name)
{
- FSRef fsr;
- FSSpec fss;
-
- if( strcmp(name, "__members__") == 0 )
- return Py_BuildValue(
- "ssssssssss",
- "version", "validRecord", "replacing",
- "isStationery", "translationNeeded",
- "selection",
- "selection_fsr",
- "fileTranslation", "keyScript", "saveFileName");
-
- if( strcmp(name, "version") == 0 )
- return Py_BuildValue("h", self->itself.version);
- if( strcmp(name, "validRecord") == 0 )
- return Py_BuildValue("l", (long)self->itself.validRecord);
- if( strcmp(name, "replacing") == 0 )
- return Py_BuildValue("l", (long)self->itself.replacing);
- if( strcmp(name, "isStationery") == 0 )
- return Py_BuildValue("l", (long)self->itself.isStationery);
- if( strcmp(name, "translationNeeded") == 0 )
- return Py_BuildValue("l", (long)self->itself.translationNeeded);
- if( strcmp(name, "selection") == 0 ) {
- SInt32 i;
- long count;
- OSErr err;
- PyObject *rv, *rvitem;
- AEDesc desc;
-
- if ((err=AECountItems(&self->itself.selection, &count))) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- if ( (rv=PyList_New(count)) == NULL )
- return NULL;
- for(i=0; i<count; i++) {
- desc.dataHandle = NULL;
- if ((err=AEGetNthDesc(&self->itself.selection, i+1, typeFSS, NULL, &desc))) {
- Py_DECREF(rv);
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- if ((err=AEGetDescData(&desc, &fss, sizeof(FSSpec)))) {
- Py_DECREF(rv);
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- rvitem = PyMac_BuildFSSpec(&fss);
- PyList_SetItem(rv, i, rvitem);
- AEDisposeDesc(&desc);
- }
- return rv;
- }
- if( strcmp(name, "selection_fsr") == 0 ) {
- SInt32 i;
- long count;
- OSErr err;
- PyObject *rv, *rvitem;
- AEDesc desc;
-
- if ((err=AECountItems(&self->itself.selection, &count))) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- if ( (rv=PyList_New(count)) == NULL )
- return NULL;
- for(i=0; i<count; i++) {
- desc.dataHandle = NULL;
- if ((err=AEGetNthDesc(&self->itself.selection, i+1, typeFSRef, NULL, &desc))) {
- Py_DECREF(rv);
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- if ((err=AEGetDescData(&desc, &fsr, sizeof(FSRef)))) {
- Py_DECREF(rv);
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- rvitem = PyMac_BuildFSRef(&fsr);
- PyList_SetItem(rv, i, rvitem);
- AEDisposeDesc(&desc);
- }
- return rv;
- }
- if( strcmp(name, "fileTranslation") == 0 )
- return ResObj_New((Handle)self->itself.fileTranslation);
- if( strcmp(name, "keyScript") == 0 )
- return Py_BuildValue("h", (short)self->itself.keyScript);
- if( strcmp(name, "saveFileName") == 0 )
- return Py_BuildValue("O&", CFStringRefObj_New, self->itself.saveFileName);
-
-
- return Py_FindMethod(navrr_methods, (PyObject *)self, name);
+ FSRef fsr;
+ FSSpec fss;
+
+ if( strcmp(name, "__members__") == 0 )
+ return Py_BuildValue(
+ "ssssssssss",
+ "version", "validRecord", "replacing",
+ "isStationery", "translationNeeded",
+ "selection",
+ "selection_fsr",
+ "fileTranslation", "keyScript", "saveFileName");
+
+ if( strcmp(name, "version") == 0 )
+ return Py_BuildValue("h", self->itself.version);
+ if( strcmp(name, "validRecord") == 0 )
+ return Py_BuildValue("l", (long)self->itself.validRecord);
+ if( strcmp(name, "replacing") == 0 )
+ return Py_BuildValue("l", (long)self->itself.replacing);
+ if( strcmp(name, "isStationery") == 0 )
+ return Py_BuildValue("l", (long)self->itself.isStationery);
+ if( strcmp(name, "translationNeeded") == 0 )
+ return Py_BuildValue("l", (long)self->itself.translationNeeded);
+ if( strcmp(name, "selection") == 0 ) {
+ SInt32 i;
+ long count;
+ OSErr err;
+ PyObject *rv, *rvitem;
+ AEDesc desc;
+
+ if ((err=AECountItems(&self->itself.selection, &count))) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ if ( (rv=PyList_New(count)) == NULL )
+ return NULL;
+ for(i=0; i<count; i++) {
+ desc.dataHandle = NULL;
+ if ((err=AEGetNthDesc(&self->itself.selection, i+1, typeFSS, NULL, &desc))) {
+ Py_DECREF(rv);
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ if ((err=AEGetDescData(&desc, &fss, sizeof(FSSpec)))) {
+ Py_DECREF(rv);
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ rvitem = PyMac_BuildFSSpec(&fss);
+ PyList_SetItem(rv, i, rvitem);
+ AEDisposeDesc(&desc);
+ }
+ return rv;
+ }
+ if( strcmp(name, "selection_fsr") == 0 ) {
+ SInt32 i;
+ long count;
+ OSErr err;
+ PyObject *rv, *rvitem;
+ AEDesc desc;
+
+ if ((err=AECountItems(&self->itself.selection, &count))) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ if ( (rv=PyList_New(count)) == NULL )
+ return NULL;
+ for(i=0; i<count; i++) {
+ desc.dataHandle = NULL;
+ if ((err=AEGetNthDesc(&self->itself.selection, i+1, typeFSRef, NULL, &desc))) {
+ Py_DECREF(rv);
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ if ((err=AEGetDescData(&desc, &fsr, sizeof(FSRef)))) {
+ Py_DECREF(rv);
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ rvitem = PyMac_BuildFSRef(&fsr);
+ PyList_SetItem(rv, i, rvitem);
+ AEDisposeDesc(&desc);
+ }
+ return rv;
+ }
+ if( strcmp(name, "fileTranslation") == 0 )
+ return ResObj_New((Handle)self->itself.fileTranslation);
+ if( strcmp(name, "keyScript") == 0 )
+ return Py_BuildValue("h", (short)self->itself.keyScript);
+ if( strcmp(name, "saveFileName") == 0 )
+ return Py_BuildValue("O&", CFStringRefObj_New, self->itself.saveFileName);
+
+
+ return Py_FindMethod(navrr_methods, (PyObject *)self, name);
}
static int
navrr_setattr(navrrobject *self, char *name, PyObject *v)
{
- /* Set attribute 'name' to value 'v'. v==NULL means delete */
-
- /* XXXX Add your own setattr code here */
- return -1;
+ /* Set attribute 'name' to value 'v'. v==NULL means delete */
+
+ /* XXXX Add your own setattr code here */
+ return -1;
}
-static char Navrrtype__doc__[] =
+static char Navrrtype__doc__[] =
"Record containing result of a Nav file selection call. Use dir() for member names."
;
static PyTypeObject Navrrtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "Nav.NavReplyRecord", /*tp_name*/
- sizeof(navrrobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)navrr_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)navrr_getattr, /*tp_getattr*/
- (setattrfunc)navrr_setattr, /*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,
- Navrrtype__doc__ /* Documentation string */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "Nav.NavReplyRecord", /*tp_name*/
+ sizeof(navrrobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)navrr_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)navrr_getattr, /*tp_getattr*/
+ (setattrfunc)navrr_setattr, /*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,
+ Navrrtype__doc__ /* Documentation string */
};
/* End of code for NavReplyRecord objects */
-
+
/* ----------------------------------------------------- */
static char nav_NavGetFile__doc__[] =
@@ -447,32 +447,32 @@ static char nav_NavGetFile__doc__[] =
static PyObject *
nav_NavGetFile(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- NavPreviewUPP previewProc = NULL;
- NavObjectFilterUPP filterProc = NULL;
- NavTypeListHandle typeList = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, &previewProc, &filterProc, &typeList, NULL, NULL))
- return NULL;
- err = NavGetFile(defaultLocation, &reply, &dialogOptions,
- eventProc, previewProc, filterProc, typeList, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ NavPreviewUPP previewProc = NULL;
+ NavObjectFilterUPP filterProc = NULL;
+ NavTypeListHandle typeList = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, &previewProc, &filterProc, &typeList, NULL, NULL))
+ return NULL;
+ err = NavGetFile(defaultLocation, &reply, &dialogOptions,
+ eventProc, previewProc, filterProc, typeList, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
static char nav_NavPutFile__doc__[] =
@@ -482,31 +482,31 @@ static char nav_NavPutFile__doc__[] =
static PyObject *
nav_NavPutFile(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- OSType fileType;
- OSType fileCreator;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, NULL, NULL, &fileType, &fileCreator))
- return NULL;
- err = NavPutFile(defaultLocation, &reply, &dialogOptions,
- eventProc, fileType, fileCreator, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ OSType fileType;
+ OSType fileCreator;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, NULL, NULL, &fileType, &fileCreator))
+ return NULL;
+ err = NavPutFile(defaultLocation, &reply, &dialogOptions,
+ eventProc, fileType, fileCreator, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
static char nav_NavAskSaveChanges__doc__[] =
@@ -517,27 +517,27 @@ static char nav_NavAskSaveChanges__doc__[] =
static PyObject *
nav_NavAskSaveChanges(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- NavDialogOptions dialogOptions;
- NavAskSaveChangesAction action;
- NavAskSaveChangesResult reply;
- NavEventUPP eventProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, "k", &action))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "lO!", &action, &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, NULL, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
- return NULL;
- err = NavAskSaveChanges(&dialogOptions, action, &reply, eventProc, (void *)dict);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return Py_BuildValue("l", (long)reply);
+ PyObject *dict;
+ NavDialogOptions dialogOptions;
+ NavAskSaveChangesAction action;
+ NavAskSaveChangesResult reply;
+ NavEventUPP eventProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, "k", &action))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "lO!", &action, &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, NULL, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
+ return NULL;
+ err = NavAskSaveChanges(&dialogOptions, action, &reply, eventProc, (void *)dict);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return Py_BuildValue("l", (long)reply);
}
static char nav_NavCustomAskSaveChanges__doc__[] =
@@ -547,26 +547,26 @@ static char nav_NavCustomAskSaveChanges__doc__[] =
static PyObject *
nav_NavCustomAskSaveChanges(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- NavDialogOptions dialogOptions;
- NavAskSaveChangesResult reply;
- NavEventUPP eventProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, NULL, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
- return NULL;
- err = NavCustomAskSaveChanges(&dialogOptions, &reply, eventProc, (void *)dict);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return Py_BuildValue("l", (long)reply);
+ PyObject *dict;
+ NavDialogOptions dialogOptions;
+ NavAskSaveChangesResult reply;
+ NavEventUPP eventProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, NULL, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
+ return NULL;
+ err = NavCustomAskSaveChanges(&dialogOptions, &reply, eventProc, (void *)dict);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return Py_BuildValue("l", (long)reply);
}
static char nav_NavAskDiscardChanges__doc__[] =
@@ -576,26 +576,26 @@ static char nav_NavAskDiscardChanges__doc__[] =
static PyObject *
nav_NavAskDiscardChanges(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- NavDialogOptions dialogOptions;
- NavAskSaveChangesResult reply;
- NavEventUPP eventProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, NULL, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
- return NULL;
- err = NavAskDiscardChanges(&dialogOptions, &reply, eventProc, (void *)dict);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return Py_BuildValue("l", (long)reply);
+ PyObject *dict;
+ NavDialogOptions dialogOptions;
+ NavAskSaveChangesResult reply;
+ NavEventUPP eventProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, NULL, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
+ return NULL;
+ err = NavAskDiscardChanges(&dialogOptions, &reply, eventProc, (void *)dict);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return Py_BuildValue("l", (long)reply);
}
static char nav_NavChooseFile__doc__[] =
@@ -605,32 +605,32 @@ static char nav_NavChooseFile__doc__[] =
static PyObject *
nav_NavChooseFile(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- NavPreviewUPP previewProc = NULL;
- NavObjectFilterUPP filterProc = NULL;
- NavTypeListHandle typeList = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, &previewProc, &filterProc, &typeList, NULL, NULL))
- return NULL;
- err = NavChooseFile(defaultLocation, &reply, &dialogOptions,
- eventProc, previewProc, filterProc, typeList, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ NavPreviewUPP previewProc = NULL;
+ NavObjectFilterUPP filterProc = NULL;
+ NavTypeListHandle typeList = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, &previewProc, &filterProc, &typeList, NULL, NULL))
+ return NULL;
+ err = NavChooseFile(defaultLocation, &reply, &dialogOptions,
+ eventProc, previewProc, filterProc, typeList, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
static char nav_NavChooseFolder__doc__[] =
@@ -640,30 +640,30 @@ static char nav_NavChooseFolder__doc__[] =
static PyObject *
nav_NavChooseFolder(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- NavObjectFilterUPP filterProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, &filterProc, NULL, NULL, NULL))
- return NULL;
- err = NavChooseFolder(defaultLocation, &reply, &dialogOptions,
- eventProc, filterProc, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ NavObjectFilterUPP filterProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, &filterProc, NULL, NULL, NULL))
+ return NULL;
+ err = NavChooseFolder(defaultLocation, &reply, &dialogOptions,
+ eventProc, filterProc, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
static char nav_NavChooseVolume__doc__[] =
@@ -673,30 +673,30 @@ static char nav_NavChooseVolume__doc__[] =
static PyObject *
nav_NavChooseVolume(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- NavObjectFilterUPP filterProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, &filterProc, NULL, NULL, NULL))
- return NULL;
- err = NavChooseVolume(defaultLocation, &reply, &dialogOptions,
- eventProc, filterProc, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ NavObjectFilterUPP filterProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, &filterProc, NULL, NULL, NULL))
+ return NULL;
+ err = NavChooseVolume(defaultLocation, &reply, &dialogOptions,
+ eventProc, filterProc, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
static char nav_NavChooseObject__doc__[] =
@@ -706,30 +706,30 @@ static char nav_NavChooseObject__doc__[] =
static PyObject *
nav_NavChooseObject(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- NavObjectFilterUPP filterProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, &filterProc, NULL, NULL, NULL))
- return NULL;
- err = NavChooseObject(defaultLocation, &reply, &dialogOptions,
- eventProc, filterProc, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ NavObjectFilterUPP filterProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, &filterProc, NULL, NULL, NULL))
+ return NULL;
+ err = NavChooseObject(defaultLocation, &reply, &dialogOptions,
+ eventProc, filterProc, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
static char nav_NavNewFolder__doc__[] =
@@ -739,28 +739,28 @@ static char nav_NavNewFolder__doc__[] =
static PyObject *
nav_NavNewFolder(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *dict;
- AEDesc *defaultLocation = NULL;
- NavReplyRecord reply;
- NavDialogOptions dialogOptions;
- NavEventUPP eventProc = NULL;
- OSErr err;
-
- if ( kw && PyObject_IsTrue(kw) ) {
- if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
- return NULL;
- dict = kw;
- } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
- return NULL;
- if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
- return NULL;
- err = NavNewFolder(defaultLocation, &reply, &dialogOptions, eventProc, (void *)dict);
- PyMem_DEL(defaultLocation);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return (PyObject *)newnavrrobject(&reply);
+ PyObject *dict;
+ AEDesc *defaultLocation = NULL;
+ NavReplyRecord reply;
+ NavDialogOptions dialogOptions;
+ NavEventUPP eventProc = NULL;
+ OSErr err;
+
+ if ( kw && PyObject_IsTrue(kw) ) {
+ if (!PyArg_ParseTuple(args, ";either keyword arguments or dictionary expected"))
+ return NULL;
+ dict = kw;
+ } else if (!PyArg_ParseTuple(args, "O!", &PyDict_Type, &dict))
+ return NULL;
+ if (!filldialogoptions(dict, &defaultLocation, &dialogOptions, &eventProc, NULL, NULL, NULL, NULL, NULL))
+ return NULL;
+ err = NavNewFolder(defaultLocation, &reply, &dialogOptions, eventProc, (void *)dict);
+ PyMem_DEL(defaultLocation);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return (PyObject *)newnavrrobject(&reply);
}
#if 0
@@ -774,10 +774,10 @@ static PyObject *
nav_NavCustomControl(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -788,11 +788,11 @@ static char nav_NavServicesCanRun__doc__[] =
static PyObject *
nav_NavServicesCanRun(PyObject *self, PyObject *args)
{
- Boolean rv;
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- rv = NavServicesCanRun();
- return Py_BuildValue("l", (long)rv);
+ Boolean rv;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ rv = NavServicesCanRun();
+ return Py_BuildValue("l", (long)rv);
}
static char nav_NavServicesAvailable__doc__[] =
@@ -802,12 +802,12 @@ static char nav_NavServicesAvailable__doc__[] =
static PyObject *
nav_NavServicesAvailable(PyObject *self, PyObject *args)
{
- Boolean rv;
-
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- rv = NavServicesAvailable();
- return Py_BuildValue("l", (long)rv);
+ Boolean rv;
+
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ rv = NavServicesAvailable();
+ return Py_BuildValue("l", (long)rv);
}
/* XX */
static char nav_NavLoad__doc__[] =
@@ -818,11 +818,11 @@ static PyObject *
nav_NavLoad(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- NavLoad();
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ NavLoad();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static char nav_NavUnload__doc__[] =
@@ -833,11 +833,11 @@ static PyObject *
nav_NavUnload(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- NavUnload();
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ NavUnload();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static char nav_NavLibraryVersion__doc__[] =
@@ -847,12 +847,12 @@ static char nav_NavLibraryVersion__doc__[] =
static PyObject *
nav_NavLibraryVersion(PyObject *self, PyObject *args)
{
- UInt32 rv;
-
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
- rv = NavLibraryVersion();
- return Py_BuildValue("l", (long)rv);
+ UInt32 rv;
+
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
+ rv = NavLibraryVersion();
+ return Py_BuildValue("l", (long)rv);
}
static char nav_NavGetDefaultDialogOptions__doc__[] =
@@ -862,59 +862,59 @@ static char nav_NavGetDefaultDialogOptions__doc__[] =
static PyObject *
nav_NavGetDefaultDialogOptions(PyObject *self, PyObject *args)
{
- NavDialogOptions dialogOptions;
- OSErr err;
-
- err = NavGetDefaultDialogOptions(&dialogOptions);
- if ( err ) {
- PyErr_Mac(ErrorObject, err);
- return NULL;
- }
- return Py_BuildValue(
- "{s:h,s:l,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&}",
- "version", dialogOptions.version,
- "dialogOptionFlags", dialogOptions.dialogOptionFlags,
- "location", PyMac_BuildPoint, dialogOptions.location,
- "clientName", PyMac_BuildStr255, &dialogOptions.clientName,
- "windowTitle", PyMac_BuildStr255, &dialogOptions.windowTitle,
- "actionButtonLabel", PyMac_BuildStr255, &dialogOptions.actionButtonLabel,
- "cancelButtonLabel", PyMac_BuildStr255, &dialogOptions.cancelButtonLabel,
- "savedFileName", PyMac_BuildStr255, &dialogOptions.savedFileName,
- "message", PyMac_BuildStr255, &dialogOptions.message,
- "preferenceKey", PyMac_BuildOSType, dialogOptions.preferenceKey
- ,"popupExtension", OptResObj_New, dialogOptions.popupExtension
- );
+ NavDialogOptions dialogOptions;
+ OSErr err;
+
+ err = NavGetDefaultDialogOptions(&dialogOptions);
+ if ( err ) {
+ PyErr_Mac(ErrorObject, err);
+ return NULL;
+ }
+ return Py_BuildValue(
+ "{s:h,s:l,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&,s:O&}",
+ "version", dialogOptions.version,
+ "dialogOptionFlags", dialogOptions.dialogOptionFlags,
+ "location", PyMac_BuildPoint, dialogOptions.location,
+ "clientName", PyMac_BuildStr255, &dialogOptions.clientName,
+ "windowTitle", PyMac_BuildStr255, &dialogOptions.windowTitle,
+ "actionButtonLabel", PyMac_BuildStr255, &dialogOptions.actionButtonLabel,
+ "cancelButtonLabel", PyMac_BuildStr255, &dialogOptions.cancelButtonLabel,
+ "savedFileName", PyMac_BuildStr255, &dialogOptions.savedFileName,
+ "message", PyMac_BuildStr255, &dialogOptions.message,
+ "preferenceKey", PyMac_BuildOSType, dialogOptions.preferenceKey
+ ,"popupExtension", OptResObj_New, dialogOptions.popupExtension
+ );
}
/* List of methods defined in the module */
static struct PyMethodDef nav_methods[] = {
- {"NavGetFile", (PyCFunction)nav_NavGetFile, METH_VARARGS|METH_KEYWORDS, nav_NavGetFile__doc__},
- {"NavPutFile", (PyCFunction)nav_NavPutFile, METH_VARARGS|METH_KEYWORDS, nav_NavPutFile__doc__},
- {"NavAskSaveChanges", (PyCFunction)nav_NavAskSaveChanges, METH_VARARGS|METH_KEYWORDS, nav_NavAskSaveChanges__doc__},
- {"NavCustomAskSaveChanges", (PyCFunction)nav_NavCustomAskSaveChanges, METH_VARARGS|METH_KEYWORDS, nav_NavCustomAskSaveChanges__doc__},
- {"NavAskDiscardChanges", (PyCFunction)nav_NavAskDiscardChanges, METH_VARARGS|METH_KEYWORDS, nav_NavAskDiscardChanges__doc__},
- {"NavChooseFile", (PyCFunction)nav_NavChooseFile, METH_VARARGS|METH_KEYWORDS, nav_NavChooseFile__doc__},
- {"NavChooseFolder", (PyCFunction)nav_NavChooseFolder, METH_VARARGS|METH_KEYWORDS, nav_NavChooseFolder__doc__},
- {"NavChooseVolume", (PyCFunction)nav_NavChooseVolume, METH_VARARGS|METH_KEYWORDS, nav_NavChooseVolume__doc__},
- {"NavChooseObject", (PyCFunction)nav_NavChooseObject, METH_VARARGS|METH_KEYWORDS, nav_NavChooseObject__doc__},
- {"NavNewFolder", (PyCFunction)nav_NavNewFolder, METH_VARARGS|METH_KEYWORDS, nav_NavNewFolder__doc__},
+ {"NavGetFile", (PyCFunction)nav_NavGetFile, METH_VARARGS|METH_KEYWORDS, nav_NavGetFile__doc__},
+ {"NavPutFile", (PyCFunction)nav_NavPutFile, METH_VARARGS|METH_KEYWORDS, nav_NavPutFile__doc__},
+ {"NavAskSaveChanges", (PyCFunction)nav_NavAskSaveChanges, METH_VARARGS|METH_KEYWORDS, nav_NavAskSaveChanges__doc__},
+ {"NavCustomAskSaveChanges", (PyCFunction)nav_NavCustomAskSaveChanges, METH_VARARGS|METH_KEYWORDS, nav_NavCustomAskSaveChanges__doc__},
+ {"NavAskDiscardChanges", (PyCFunction)nav_NavAskDiscardChanges, METH_VARARGS|METH_KEYWORDS, nav_NavAskDiscardChanges__doc__},
+ {"NavChooseFile", (PyCFunction)nav_NavChooseFile, METH_VARARGS|METH_KEYWORDS, nav_NavChooseFile__doc__},
+ {"NavChooseFolder", (PyCFunction)nav_NavChooseFolder, METH_VARARGS|METH_KEYWORDS, nav_NavChooseFolder__doc__},
+ {"NavChooseVolume", (PyCFunction)nav_NavChooseVolume, METH_VARARGS|METH_KEYWORDS, nav_NavChooseVolume__doc__},
+ {"NavChooseObject", (PyCFunction)nav_NavChooseObject, METH_VARARGS|METH_KEYWORDS, nav_NavChooseObject__doc__},
+ {"NavNewFolder", (PyCFunction)nav_NavNewFolder, METH_VARARGS|METH_KEYWORDS, nav_NavNewFolder__doc__},
#if 0
- {"NavCustomControl", (PyCFunction)nav_NavCustomControl, METH_VARARGS, nav_NavCustomControl__doc__},
+ {"NavCustomControl", (PyCFunction)nav_NavCustomControl, METH_VARARGS, nav_NavCustomControl__doc__},
#endif
- {"NavServicesCanRun", (PyCFunction)nav_NavServicesCanRun, METH_VARARGS, nav_NavServicesCanRun__doc__},
- {"NavServicesAvailable", (PyCFunction)nav_NavServicesAvailable, METH_VARARGS, nav_NavServicesAvailable__doc__},
- {"NavLoad", (PyCFunction)nav_NavLoad, METH_VARARGS, nav_NavLoad__doc__},
- {"NavUnload", (PyCFunction)nav_NavUnload, METH_VARARGS, nav_NavUnload__doc__},
- {"NavLibraryVersion", (PyCFunction)nav_NavLibraryVersion, METH_VARARGS, nav_NavLibraryVersion__doc__},
- {"NavGetDefaultDialogOptions", (PyCFunction)nav_NavGetDefaultDialogOptions, METH_VARARGS, nav_NavGetDefaultDialogOptions__doc__},
- {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
+ {"NavServicesCanRun", (PyCFunction)nav_NavServicesCanRun, METH_VARARGS, nav_NavServicesCanRun__doc__},
+ {"NavServicesAvailable", (PyCFunction)nav_NavServicesAvailable, METH_VARARGS, nav_NavServicesAvailable__doc__},
+ {"NavLoad", (PyCFunction)nav_NavLoad, METH_VARARGS, nav_NavLoad__doc__},
+ {"NavUnload", (PyCFunction)nav_NavUnload, METH_VARARGS, nav_NavUnload__doc__},
+ {"NavLibraryVersion", (PyCFunction)nav_NavLibraryVersion, METH_VARARGS, nav_NavLibraryVersion__doc__},
+ {"NavGetDefaultDialogOptions", (PyCFunction)nav_NavGetDefaultDialogOptions, METH_VARARGS, nav_NavGetDefaultDialogOptions__doc__},
+ {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Initialization function for the module (*must* be called initNav) */
-static char Nav_module_documentation[] =
+static char Nav_module_documentation[] =
"Interface to Navigation Services\n"
"Most calls accept a NavDialogOptions dictionary or keywords with the same names, pass {}\n"
"if you want the default options.\n"
@@ -930,39 +930,39 @@ static char Nav_module_documentation[] =
void
initNav(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("In 3.x, the Nav module is removed.", 1))
- return;
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("In 3.x, the Nav module is removed.", 1))
+ return;
#ifdef __LP64__
- PyErr_SetString(PyExc_ImportError, "Navigation Services not available in 64-bit mode");
- return;
-
-#else /* !__LP64__ */
-
- /* Test that we have NavServices */
- if ( !NavServicesAvailable() ) {
- PyErr_SetString(PyExc_ImportError, "Navigation Services not available");
- return;
- }
- /* Create the module and add the functions */
- m = Py_InitModule4("Nav", nav_methods,
- Nav_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
-
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- ErrorObject = PyString_FromString("Nav.error");
- PyDict_SetItemString(d, "error", ErrorObject);
-
- /* XXXX Add constants here */
-
- /* Set UPPs */
- my_eventProcUPP = NewNavEventUPP(my_eventProc);
- my_previewProcUPP = NewNavPreviewUPP(my_previewProc);
- my_filterProcUPP = NewNavObjectFilterUPP(my_filterProc);
+ PyErr_SetString(PyExc_ImportError, "Navigation Services not available in 64-bit mode");
+ return;
+
+#else /* !__LP64__ */
+
+ /* Test that we have NavServices */
+ if ( !NavServicesAvailable() ) {
+ PyErr_SetString(PyExc_ImportError, "Navigation Services not available");
+ return;
+ }
+ /* Create the module and add the functions */
+ m = Py_InitModule4("Nav", nav_methods,
+ Nav_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
+
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ ErrorObject = PyString_FromString("Nav.error");
+ PyDict_SetItemString(d, "error", ErrorObject);
+
+ /* XXXX Add constants here */
+
+ /* Set UPPs */
+ my_eventProcUPP = NewNavEventUPP(my_eventProc);
+ my_previewProcUPP = NewNavPreviewUPP(my_previewProc);
+ my_filterProcUPP = NewNavObjectFilterUPP(my_filterProc);
#endif /* !__LP64__ */
-
+
}
diff --git a/Mac/Modules/OSATerminology.c b/Mac/Modules/OSATerminology.c
index a7becf7..2114d07 100644
--- a/Mac/Modules/OSATerminology.c
+++ b/Mac/Modules/OSATerminology.c
@@ -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);
}
diff --git a/Mac/Modules/_scproxy.c b/Mac/Modules/_scproxy.c
index 9f4c1a4..dd5a293 100644
--- a/Mac/Modules/_scproxy.c
+++ b/Mac/Modules/_scproxy.c
@@ -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;
-
- 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);
-
- 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;
- }
+ const char* 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);
+
+ 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;
-
- proxyDict = SCDynamicStoreCopyProxies(NULL);
- if (!proxyDict) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- 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 (v == NULL) 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;
-
- r = PyDict_SetItemString(result, "exceptions", v);
- Py_DECREF(v);
- if (r == -1) goto error;
-
- 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);
- }
- }
- }
- }
-
- CFRelease(proxyDict);
- return result;
+ 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;
+ }
+
+ 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 (v == NULL) 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;
+
+ r = PyDict_SetItemString(result, "exceptions", v);
+ Py_DECREF(v);
+ if (r == -1) goto error;
+
+ 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);
+ }
+ }
+ }
+ }
+
+ 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;
-
- aNum = CFDictionaryGetValue(proxyDict, enabledKey);
- if (aNum && cfnum_to_int32(aNum)) {
- CFStringRef hostString;
-
- 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;
- }
- }
-
- }
- return 0;
+ CFNumberRef aNum;
+
+ aNum = CFDictionaryGetValue(proxyDict, enabledKey);
+ if (aNum && cfnum_to_int32(aNum)) {
+ CFStringRef hostString;
+
+ 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;
+ }
+ }
+
+ }
+ 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;
-
- proxyDict = SCDynamicStoreCopyProxies(NULL);
- if (proxyDict == NULL) {
- return PyDict_New();
- }
-
- 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;
-
- CFRelease(proxyDict);
- return result;
+ PyObject* result = NULL;
+ int r;
+ CFDictionaryRef proxyDict = NULL;
+
+ proxyDict = SCDynamicStoreCopyProxies(NULL);
+ if (proxyDict == NULL) {
+ return PyDict_New();
+ }
+
+ 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;
+
+ 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);
}
diff --git a/Mac/Modules/ae/_AEmodule.c b/Mac/Modules/ae/_AEmodule.c
index 09105a5..21a2d40 100644
--- a/Mac/Modules/ae/_AEmodule.c
+++ b/Mac/Modules/ae/_AEmodule.c
@@ -13,9 +13,9 @@ typedef SInt32 SRefCon;
/* 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)
@@ -38,9 +38,9 @@ AEEventHandlerUPP upp_GenericEventHandler;
static pascal Boolean AEIdleProc(EventRecord *theEvent, long *sleepTime, RgnHandle *mouseRgn)
{
- if ( PyOS_InterruptOccurred() )
- return 1;
- return 0;
+ if ( PyOS_InterruptOccurred() )
+ return 1;
+ return 0;
}
AEIdleUPP upp_AEIdleProc;
@@ -54,807 +54,807 @@ PyTypeObject AEDesc_Type;
#define AEDesc_Check(x) ((x)->ob_type == &AEDesc_Type || PyObject_TypeCheck((x), &AEDesc_Type))
typedef struct AEDescObject {
- PyObject_HEAD
- AEDesc ob_itself;
- int ob_owned;
+ PyObject_HEAD
+ AEDesc ob_itself;
+ int ob_owned;
} AEDescObject;
PyObject *AEDesc_New(AEDesc *itself)
{
- AEDescObject *it;
- it = PyObject_NEW(AEDescObject, &AEDesc_Type);
- if (it == NULL) return NULL;
- it->ob_itself = *itself;
- it->ob_owned = 1;
- return (PyObject *)it;
+ AEDescObject *it;
+ it = PyObject_NEW(AEDescObject, &AEDesc_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = *itself;
+ it->ob_owned = 1;
+ return (PyObject *)it;
}
int AEDesc_Convert(PyObject *v, AEDesc *p_itself)
{
- if (!AEDesc_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "AEDesc required");
- return 0;
- }
- *p_itself = ((AEDescObject *)v)->ob_itself;
- return 1;
+ if (!AEDesc_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "AEDesc required");
+ return 0;
+ }
+ *p_itself = ((AEDescObject *)v)->ob_itself;
+ return 1;
}
static void AEDesc_dealloc(AEDescObject *self)
{
- if (self->ob_owned) AEDisposeDesc(&self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_owned) AEDisposeDesc(&self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *AEDesc_AECoerceDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DescType toType;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DescType toType;
+ AEDesc result;
#ifndef AECoerceDesc
- PyMac_PRECHECK(AECoerceDesc);
+ PyMac_PRECHECK(AECoerceDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &toType))
- return NULL;
- _err = AECoerceDesc(&_self->ob_itself,
- toType,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &toType))
+ return NULL;
+ _err = AECoerceDesc(&_self->ob_itself,
+ toType,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AEDesc_AEDuplicateDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEDesc result;
#ifndef AEDuplicateDesc
- PyMac_PRECHECK(AEDuplicateDesc);
+ PyMac_PRECHECK(AEDuplicateDesc);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AEDuplicateDesc(&_self->ob_itself,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AEDuplicateDesc(&_self->ob_itself,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AEDesc_AECountItems(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long theCount;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long theCount;
#ifndef AECountItems
- PyMac_PRECHECK(AECountItems);
+ PyMac_PRECHECK(AECountItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AECountItems(&_self->ob_itself,
- &theCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- theCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AECountItems(&_self->ob_itself,
+ &theCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ theCount);
+ return _res;
}
static PyObject *AEDesc_AEPutPtr(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
- DescType typeCode;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
+ DescType typeCode;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
#ifndef AEPutPtr
- PyMac_PRECHECK(AEPutPtr);
+ PyMac_PRECHECK(AEPutPtr);
#endif
- if (!PyArg_ParseTuple(_args, "lO&s#",
- &index,
- PyMac_GetOSType, &typeCode,
- &dataPtr__in__, &dataPtr__in_len__))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEPutPtr(&_self->ob_itself,
- index,
- typeCode,
- dataPtr__in__, dataPtr__len__);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&s#",
+ &index,
+ PyMac_GetOSType, &typeCode,
+ &dataPtr__in__, &dataPtr__in_len__))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEPutPtr(&_self->ob_itself,
+ index,
+ typeCode,
+ dataPtr__in__, dataPtr__len__);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEPutDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
- AEDesc theAEDesc;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
+ AEDesc theAEDesc;
#ifndef AEPutDesc
- PyMac_PRECHECK(AEPutDesc);
+ PyMac_PRECHECK(AEPutDesc);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &index,
- AEDesc_Convert, &theAEDesc))
- return NULL;
- _err = AEPutDesc(&_self->ob_itself,
- index,
- &theAEDesc);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &index,
+ AEDesc_Convert, &theAEDesc))
+ return NULL;
+ _err = AEPutDesc(&_self->ob_itself,
+ index,
+ &theAEDesc);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEGetNthPtr(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
- DescType desiredType;
- AEKeyword theAEKeyword;
- DescType typeCode;
- char *dataPtr__out__;
- long dataPtr__len__;
- int dataPtr__in_len__;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
+ DescType desiredType;
+ AEKeyword theAEKeyword;
+ DescType typeCode;
+ char *dataPtr__out__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
#ifndef AEGetNthPtr
- PyMac_PRECHECK(AEGetNthPtr);
+ PyMac_PRECHECK(AEGetNthPtr);
#endif
- if (!PyArg_ParseTuple(_args, "lO&i",
- &index,
- PyMac_GetOSType, &desiredType,
- &dataPtr__in_len__))
- return NULL;
- if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
- {
- PyErr_NoMemory();
- goto dataPtr__error__;
- }
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEGetNthPtr(&_self->ob_itself,
- index,
- desiredType,
- &theAEKeyword,
- &typeCode,
- dataPtr__out__, dataPtr__len__, &dataPtr__len__);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&s#",
- PyMac_BuildOSType, theAEKeyword,
- PyMac_BuildOSType, typeCode,
- dataPtr__out__, (int)dataPtr__len__);
- free(dataPtr__out__);
+ if (!PyArg_ParseTuple(_args, "lO&i",
+ &index,
+ PyMac_GetOSType, &desiredType,
+ &dataPtr__in_len__))
+ return NULL;
+ if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
+ {
+ PyErr_NoMemory();
+ goto dataPtr__error__;
+ }
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEGetNthPtr(&_self->ob_itself,
+ index,
+ desiredType,
+ &theAEKeyword,
+ &typeCode,
+ dataPtr__out__, dataPtr__len__, &dataPtr__len__);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&s#",
+ PyMac_BuildOSType, theAEKeyword,
+ PyMac_BuildOSType, typeCode,
+ dataPtr__out__, (int)dataPtr__len__);
+ free(dataPtr__out__);
dataPtr__error__: ;
- return _res;
+ return _res;
}
static PyObject *AEDesc_AEGetNthDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
- DescType desiredType;
- AEKeyword theAEKeyword;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
+ DescType desiredType;
+ AEKeyword theAEKeyword;
+ AEDesc result;
#ifndef AEGetNthDesc
- PyMac_PRECHECK(AEGetNthDesc);
+ PyMac_PRECHECK(AEGetNthDesc);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &index,
- PyMac_GetOSType, &desiredType))
- return NULL;
- _err = AEGetNthDesc(&_self->ob_itself,
- index,
- desiredType,
- &theAEKeyword,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildOSType, theAEKeyword,
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &index,
+ PyMac_GetOSType, &desiredType))
+ return NULL;
+ _err = AEGetNthDesc(&_self->ob_itself,
+ index,
+ desiredType,
+ &theAEKeyword,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildOSType, theAEKeyword,
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AEDesc_AESizeOfNthItem(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
- DescType typeCode;
- Size dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
+ DescType typeCode;
+ Size dataSize;
#ifndef AESizeOfNthItem
- PyMac_PRECHECK(AESizeOfNthItem);
+ PyMac_PRECHECK(AESizeOfNthItem);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &index))
- return NULL;
- _err = AESizeOfNthItem(&_self->ob_itself,
- index,
- &typeCode,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&l",
- PyMac_BuildOSType, typeCode,
- dataSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &index))
+ return NULL;
+ _err = AESizeOfNthItem(&_self->ob_itself,
+ index,
+ &typeCode,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&l",
+ PyMac_BuildOSType, typeCode,
+ dataSize);
+ return _res;
}
static PyObject *AEDesc_AEDeleteItem(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
#ifndef AEDeleteItem
- PyMac_PRECHECK(AEDeleteItem);
+ PyMac_PRECHECK(AEDeleteItem);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &index))
- return NULL;
- _err = AEDeleteItem(&_self->ob_itself,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &index))
+ return NULL;
+ _err = AEDeleteItem(&_self->ob_itself,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEPutParamPtr(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType typeCode;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType typeCode;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
#ifndef AEPutParamPtr
- PyMac_PRECHECK(AEPutParamPtr);
+ PyMac_PRECHECK(AEPutParamPtr);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&s#",
- PyMac_GetOSType, &theAEKeyword,
- PyMac_GetOSType, &typeCode,
- &dataPtr__in__, &dataPtr__in_len__))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEPutParamPtr(&_self->ob_itself,
- theAEKeyword,
- typeCode,
- dataPtr__in__, dataPtr__len__);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&s#",
+ PyMac_GetOSType, &theAEKeyword,
+ PyMac_GetOSType, &typeCode,
+ &dataPtr__in__, &dataPtr__in_len__))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEPutParamPtr(&_self->ob_itself,
+ theAEKeyword,
+ typeCode,
+ dataPtr__in__, dataPtr__len__);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEPutParamDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- AEDesc theAEDesc;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ AEDesc theAEDesc;
#ifndef AEPutParamDesc
- PyMac_PRECHECK(AEPutParamDesc);
+ PyMac_PRECHECK(AEPutParamDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theAEKeyword,
- AEDesc_Convert, &theAEDesc))
- return NULL;
- _err = AEPutParamDesc(&_self->ob_itself,
- theAEKeyword,
- &theAEDesc);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theAEKeyword,
+ AEDesc_Convert, &theAEDesc))
+ return NULL;
+ _err = AEPutParamDesc(&_self->ob_itself,
+ theAEKeyword,
+ &theAEDesc);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEGetParamPtr(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType desiredType;
- DescType typeCode;
- char *dataPtr__out__;
- long dataPtr__len__;
- int dataPtr__in_len__;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType desiredType;
+ DescType typeCode;
+ char *dataPtr__out__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
#ifndef AEGetParamPtr
- PyMac_PRECHECK(AEGetParamPtr);
+ PyMac_PRECHECK(AEGetParamPtr);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&i",
- PyMac_GetOSType, &theAEKeyword,
- PyMac_GetOSType, &desiredType,
- &dataPtr__in_len__))
- return NULL;
- if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
- {
- PyErr_NoMemory();
- goto dataPtr__error__;
- }
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEGetParamPtr(&_self->ob_itself,
- theAEKeyword,
- desiredType,
- &typeCode,
- dataPtr__out__, dataPtr__len__, &dataPtr__len__);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&s#",
- PyMac_BuildOSType, typeCode,
- dataPtr__out__, (int)dataPtr__len__);
- free(dataPtr__out__);
+ if (!PyArg_ParseTuple(_args, "O&O&i",
+ PyMac_GetOSType, &theAEKeyword,
+ PyMac_GetOSType, &desiredType,
+ &dataPtr__in_len__))
+ return NULL;
+ if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
+ {
+ PyErr_NoMemory();
+ goto dataPtr__error__;
+ }
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEGetParamPtr(&_self->ob_itself,
+ theAEKeyword,
+ desiredType,
+ &typeCode,
+ dataPtr__out__, dataPtr__len__, &dataPtr__len__);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&s#",
+ PyMac_BuildOSType, typeCode,
+ dataPtr__out__, (int)dataPtr__len__);
+ free(dataPtr__out__);
dataPtr__error__: ;
- return _res;
+ return _res;
}
static PyObject *AEDesc_AEGetParamDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType desiredType;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType desiredType;
+ AEDesc result;
#ifndef AEGetParamDesc
- PyMac_PRECHECK(AEGetParamDesc);
+ PyMac_PRECHECK(AEGetParamDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theAEKeyword,
- PyMac_GetOSType, &desiredType))
- return NULL;
- _err = AEGetParamDesc(&_self->ob_itself,
- theAEKeyword,
- desiredType,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theAEKeyword,
+ PyMac_GetOSType, &desiredType))
+ return NULL;
+ _err = AEGetParamDesc(&_self->ob_itself,
+ theAEKeyword,
+ desiredType,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AEDesc_AESizeOfParam(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType typeCode;
- Size dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType typeCode;
+ Size dataSize;
#ifndef AESizeOfParam
- PyMac_PRECHECK(AESizeOfParam);
+ PyMac_PRECHECK(AESizeOfParam);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theAEKeyword))
- return NULL;
- _err = AESizeOfParam(&_self->ob_itself,
- theAEKeyword,
- &typeCode,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&l",
- PyMac_BuildOSType, typeCode,
- dataSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theAEKeyword))
+ return NULL;
+ _err = AESizeOfParam(&_self->ob_itself,
+ theAEKeyword,
+ &typeCode,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&l",
+ PyMac_BuildOSType, typeCode,
+ dataSize);
+ return _res;
}
static PyObject *AEDesc_AEDeleteParam(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
#ifndef AEDeleteParam
- PyMac_PRECHECK(AEDeleteParam);
+ PyMac_PRECHECK(AEDeleteParam);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theAEKeyword))
- return NULL;
- _err = AEDeleteParam(&_self->ob_itself,
- theAEKeyword);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theAEKeyword))
+ return NULL;
+ _err = AEDeleteParam(&_self->ob_itself,
+ theAEKeyword);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEGetAttributePtr(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType desiredType;
- DescType typeCode;
- char *dataPtr__out__;
- long dataPtr__len__;
- int dataPtr__in_len__;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType desiredType;
+ DescType typeCode;
+ char *dataPtr__out__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
#ifndef AEGetAttributePtr
- PyMac_PRECHECK(AEGetAttributePtr);
+ PyMac_PRECHECK(AEGetAttributePtr);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&i",
- PyMac_GetOSType, &theAEKeyword,
- PyMac_GetOSType, &desiredType,
- &dataPtr__in_len__))
- return NULL;
- if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
- {
- PyErr_NoMemory();
- goto dataPtr__error__;
- }
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEGetAttributePtr(&_self->ob_itself,
- theAEKeyword,
- desiredType,
- &typeCode,
- dataPtr__out__, dataPtr__len__, &dataPtr__len__);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&s#",
- PyMac_BuildOSType, typeCode,
- dataPtr__out__, (int)dataPtr__len__);
- free(dataPtr__out__);
+ if (!PyArg_ParseTuple(_args, "O&O&i",
+ PyMac_GetOSType, &theAEKeyword,
+ PyMac_GetOSType, &desiredType,
+ &dataPtr__in_len__))
+ return NULL;
+ if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
+ {
+ PyErr_NoMemory();
+ goto dataPtr__error__;
+ }
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEGetAttributePtr(&_self->ob_itself,
+ theAEKeyword,
+ desiredType,
+ &typeCode,
+ dataPtr__out__, dataPtr__len__, &dataPtr__len__);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&s#",
+ PyMac_BuildOSType, typeCode,
+ dataPtr__out__, (int)dataPtr__len__);
+ free(dataPtr__out__);
dataPtr__error__: ;
- return _res;
+ return _res;
}
static PyObject *AEDesc_AEGetAttributeDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType desiredType;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType desiredType;
+ AEDesc result;
#ifndef AEGetAttributeDesc
- PyMac_PRECHECK(AEGetAttributeDesc);
+ PyMac_PRECHECK(AEGetAttributeDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theAEKeyword,
- PyMac_GetOSType, &desiredType))
- return NULL;
- _err = AEGetAttributeDesc(&_self->ob_itself,
- theAEKeyword,
- desiredType,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theAEKeyword,
+ PyMac_GetOSType, &desiredType))
+ return NULL;
+ _err = AEGetAttributeDesc(&_self->ob_itself,
+ theAEKeyword,
+ desiredType,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AEDesc_AESizeOfAttribute(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType typeCode;
- Size dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType typeCode;
+ Size dataSize;
#ifndef AESizeOfAttribute
- PyMac_PRECHECK(AESizeOfAttribute);
+ PyMac_PRECHECK(AESizeOfAttribute);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theAEKeyword))
- return NULL;
- _err = AESizeOfAttribute(&_self->ob_itself,
- theAEKeyword,
- &typeCode,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&l",
- PyMac_BuildOSType, typeCode,
- dataSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theAEKeyword))
+ return NULL;
+ _err = AESizeOfAttribute(&_self->ob_itself,
+ theAEKeyword,
+ &typeCode,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&l",
+ PyMac_BuildOSType, typeCode,
+ dataSize);
+ return _res;
}
static PyObject *AEDesc_AEPutAttributePtr(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- DescType typeCode;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ DescType typeCode;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
#ifndef AEPutAttributePtr
- PyMac_PRECHECK(AEPutAttributePtr);
+ PyMac_PRECHECK(AEPutAttributePtr);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&s#",
- PyMac_GetOSType, &theAEKeyword,
- PyMac_GetOSType, &typeCode,
- &dataPtr__in__, &dataPtr__in_len__))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEPutAttributePtr(&_self->ob_itself,
- theAEKeyword,
- typeCode,
- dataPtr__in__, dataPtr__len__);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&s#",
+ PyMac_GetOSType, &theAEKeyword,
+ PyMac_GetOSType, &typeCode,
+ &dataPtr__in__, &dataPtr__in_len__))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEPutAttributePtr(&_self->ob_itself,
+ theAEKeyword,
+ typeCode,
+ dataPtr__in__, dataPtr__len__);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEPutAttributeDesc(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword theAEKeyword;
- AEDesc theAEDesc;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword theAEKeyword;
+ AEDesc theAEDesc;
#ifndef AEPutAttributeDesc
- PyMac_PRECHECK(AEPutAttributeDesc);
+ PyMac_PRECHECK(AEPutAttributeDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theAEKeyword,
- AEDesc_Convert, &theAEDesc))
- return NULL;
- _err = AEPutAttributeDesc(&_self->ob_itself,
- theAEKeyword,
- &theAEDesc);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theAEKeyword,
+ AEDesc_Convert, &theAEDesc))
+ return NULL;
+ _err = AEPutAttributeDesc(&_self->ob_itself,
+ theAEKeyword,
+ &theAEDesc);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEGetDescDataSize(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Size _rv;
+ PyObject *_res = NULL;
+ Size _rv;
#ifndef AEGetDescDataSize
- PyMac_PRECHECK(AEGetDescDataSize);
+ PyMac_PRECHECK(AEGetDescDataSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = AEGetDescDataSize(&_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = AEGetDescDataSize(&_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *AEDesc_AESend(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AppleEvent reply;
- AESendMode sendMode;
- AESendPriority sendPriority;
- long timeOutInTicks;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AppleEvent reply;
+ AESendMode sendMode;
+ AESendPriority sendPriority;
+ long timeOutInTicks;
#ifndef AESend
- PyMac_PRECHECK(AESend);
+ PyMac_PRECHECK(AESend);
#endif
- if (!PyArg_ParseTuple(_args, "lhl",
- &sendMode,
- &sendPriority,
- &timeOutInTicks))
- return NULL;
- _err = AESend(&_self->ob_itself,
- &reply,
- sendMode,
- sendPriority,
- timeOutInTicks,
- upp_AEIdleProc,
- (AEFilterUPP)0);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &reply);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lhl",
+ &sendMode,
+ &sendPriority,
+ &timeOutInTicks))
+ return NULL;
+ _err = AESend(&_self->ob_itself,
+ &reply,
+ sendMode,
+ sendPriority,
+ timeOutInTicks,
+ upp_AEIdleProc,
+ (AEFilterUPP)0);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &reply);
+ return _res;
}
static PyObject *AEDesc_AEResetTimer(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef AEResetTimer
- PyMac_PRECHECK(AEResetTimer);
+ PyMac_PRECHECK(AEResetTimer);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AEResetTimer(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AEResetTimer(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AESuspendTheCurrentEvent(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef AESuspendTheCurrentEvent
- PyMac_PRECHECK(AESuspendTheCurrentEvent);
+ PyMac_PRECHECK(AESuspendTheCurrentEvent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AESuspendTheCurrentEvent(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AESuspendTheCurrentEvent(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEResumeTheCurrentEvent(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AppleEvent reply;
- AEEventHandlerUPP dispatcher__proc__ = upp_GenericEventHandler;
- PyObject *dispatcher;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AppleEvent reply;
+ AEEventHandlerUPP dispatcher__proc__ = upp_GenericEventHandler;
+ PyObject *dispatcher;
#ifndef AEResumeTheCurrentEvent
- PyMac_PRECHECK(AEResumeTheCurrentEvent);
+ PyMac_PRECHECK(AEResumeTheCurrentEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O",
- AEDesc_Convert, &reply,
- &dispatcher))
- return NULL;
- _err = AEResumeTheCurrentEvent(&_self->ob_itself,
- &reply,
- dispatcher__proc__,
- (SRefCon)dispatcher);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- Py_INCREF(dispatcher); /* XXX leak, but needed */
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O",
+ AEDesc_Convert, &reply,
+ &dispatcher))
+ return NULL;
+ _err = AEResumeTheCurrentEvent(&_self->ob_itself,
+ &reply,
+ dispatcher__proc__,
+ (SRefCon)dispatcher);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ Py_INCREF(dispatcher); /* XXX leak, but needed */
+ return _res;
}
static PyObject *AEDesc_AEGetTheCurrentEvent(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef AEGetTheCurrentEvent
- PyMac_PRECHECK(AEGetTheCurrentEvent);
+ PyMac_PRECHECK(AEGetTheCurrentEvent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AEGetTheCurrentEvent(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AEGetTheCurrentEvent(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AESetTheCurrentEvent(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef AESetTheCurrentEvent
- PyMac_PRECHECK(AESetTheCurrentEvent);
+ PyMac_PRECHECK(AESetTheCurrentEvent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AESetTheCurrentEvent(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AESetTheCurrentEvent(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AEDesc_AEResolve(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short callbackFlags;
- AEDesc theToken;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short callbackFlags;
+ AEDesc theToken;
#ifndef AEResolve
- PyMac_PRECHECK(AEResolve);
+ PyMac_PRECHECK(AEResolve);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &callbackFlags))
- return NULL;
- _err = AEResolve(&_self->ob_itself,
- callbackFlags,
- &theToken);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &theToken);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &callbackFlags))
+ return NULL;
+ _err = AEResolve(&_self->ob_itself,
+ callbackFlags,
+ &theToken);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &theToken);
+ return _res;
}
static PyObject *AEDesc_AutoDispose(AEDescObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int onoff, old;
- if (!PyArg_ParseTuple(_args, "i", &onoff))
- return NULL;
- old = _self->ob_owned;
- _self->ob_owned = onoff;
- _res = Py_BuildValue("i", old);
- return _res;
+ int onoff, old;
+ if (!PyArg_ParseTuple(_args, "i", &onoff))
+ return NULL;
+ old = _self->ob_owned;
+ _self->ob_owned = onoff;
+ _res = Py_BuildValue("i", old);
+ return _res;
}
static PyMethodDef AEDesc_methods[] = {
- {"AECoerceDesc", (PyCFunction)AEDesc_AECoerceDesc, 1,
- PyDoc_STR("(DescType toType) -> (AEDesc result)")},
- {"AEDuplicateDesc", (PyCFunction)AEDesc_AEDuplicateDesc, 1,
- PyDoc_STR("() -> (AEDesc result)")},
- {"AECountItems", (PyCFunction)AEDesc_AECountItems, 1,
- PyDoc_STR("() -> (long theCount)")},
- {"AEPutPtr", (PyCFunction)AEDesc_AEPutPtr, 1,
- PyDoc_STR("(long index, DescType typeCode, Buffer dataPtr) -> None")},
- {"AEPutDesc", (PyCFunction)AEDesc_AEPutDesc, 1,
- PyDoc_STR("(long index, AEDesc theAEDesc) -> None")},
- {"AEGetNthPtr", (PyCFunction)AEDesc_AEGetNthPtr, 1,
- PyDoc_STR("(long index, DescType desiredType, Buffer dataPtr) -> (AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr)")},
- {"AEGetNthDesc", (PyCFunction)AEDesc_AEGetNthDesc, 1,
- PyDoc_STR("(long index, DescType desiredType) -> (AEKeyword theAEKeyword, AEDesc result)")},
- {"AESizeOfNthItem", (PyCFunction)AEDesc_AESizeOfNthItem, 1,
- PyDoc_STR("(long index) -> (DescType typeCode, Size dataSize)")},
- {"AEDeleteItem", (PyCFunction)AEDesc_AEDeleteItem, 1,
- PyDoc_STR("(long index) -> None")},
- {"AEPutParamPtr", (PyCFunction)AEDesc_AEPutParamPtr, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr) -> None")},
- {"AEPutParamDesc", (PyCFunction)AEDesc_AEPutParamDesc, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, AEDesc theAEDesc) -> None")},
- {"AEGetParamPtr", (PyCFunction)AEDesc_AEGetParamPtr, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType, Buffer dataPtr) -> (DescType typeCode, Buffer dataPtr)")},
- {"AEGetParamDesc", (PyCFunction)AEDesc_AEGetParamDesc, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType) -> (AEDesc result)")},
- {"AESizeOfParam", (PyCFunction)AEDesc_AESizeOfParam, 1,
- PyDoc_STR("(AEKeyword theAEKeyword) -> (DescType typeCode, Size dataSize)")},
- {"AEDeleteParam", (PyCFunction)AEDesc_AEDeleteParam, 1,
- PyDoc_STR("(AEKeyword theAEKeyword) -> None")},
- {"AEGetAttributePtr", (PyCFunction)AEDesc_AEGetAttributePtr, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType, Buffer dataPtr) -> (DescType typeCode, Buffer dataPtr)")},
- {"AEGetAttributeDesc", (PyCFunction)AEDesc_AEGetAttributeDesc, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType) -> (AEDesc result)")},
- {"AESizeOfAttribute", (PyCFunction)AEDesc_AESizeOfAttribute, 1,
- PyDoc_STR("(AEKeyword theAEKeyword) -> (DescType typeCode, Size dataSize)")},
- {"AEPutAttributePtr", (PyCFunction)AEDesc_AEPutAttributePtr, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr) -> None")},
- {"AEPutAttributeDesc", (PyCFunction)AEDesc_AEPutAttributeDesc, 1,
- PyDoc_STR("(AEKeyword theAEKeyword, AEDesc theAEDesc) -> None")},
- {"AEGetDescDataSize", (PyCFunction)AEDesc_AEGetDescDataSize, 1,
- PyDoc_STR("() -> (Size _rv)")},
- {"AESend", (PyCFunction)AEDesc_AESend, 1,
- PyDoc_STR("(AESendMode sendMode, AESendPriority sendPriority, long timeOutInTicks) -> (AppleEvent reply)")},
- {"AEResetTimer", (PyCFunction)AEDesc_AEResetTimer, 1,
- PyDoc_STR("() -> None")},
- {"AESuspendTheCurrentEvent", (PyCFunction)AEDesc_AESuspendTheCurrentEvent, 1,
- PyDoc_STR("() -> None")},
- {"AEResumeTheCurrentEvent", (PyCFunction)AEDesc_AEResumeTheCurrentEvent, 1,
- PyDoc_STR("(AppleEvent reply, EventHandler dispatcher) -> None")},
- {"AEGetTheCurrentEvent", (PyCFunction)AEDesc_AEGetTheCurrentEvent, 1,
- PyDoc_STR("() -> None")},
- {"AESetTheCurrentEvent", (PyCFunction)AEDesc_AESetTheCurrentEvent, 1,
- PyDoc_STR("() -> None")},
- {"AEResolve", (PyCFunction)AEDesc_AEResolve, 1,
- PyDoc_STR("(short callbackFlags) -> (AEDesc theToken)")},
- {"AutoDispose", (PyCFunction)AEDesc_AutoDispose, 1,
- PyDoc_STR("(int)->int. Automatically AEDisposeDesc the object on Python object cleanup")},
- {NULL, NULL, 0}
+ {"AECoerceDesc", (PyCFunction)AEDesc_AECoerceDesc, 1,
+ PyDoc_STR("(DescType toType) -> (AEDesc result)")},
+ {"AEDuplicateDesc", (PyCFunction)AEDesc_AEDuplicateDesc, 1,
+ PyDoc_STR("() -> (AEDesc result)")},
+ {"AECountItems", (PyCFunction)AEDesc_AECountItems, 1,
+ PyDoc_STR("() -> (long theCount)")},
+ {"AEPutPtr", (PyCFunction)AEDesc_AEPutPtr, 1,
+ PyDoc_STR("(long index, DescType typeCode, Buffer dataPtr) -> None")},
+ {"AEPutDesc", (PyCFunction)AEDesc_AEPutDesc, 1,
+ PyDoc_STR("(long index, AEDesc theAEDesc) -> None")},
+ {"AEGetNthPtr", (PyCFunction)AEDesc_AEGetNthPtr, 1,
+ PyDoc_STR("(long index, DescType desiredType, Buffer dataPtr) -> (AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr)")},
+ {"AEGetNthDesc", (PyCFunction)AEDesc_AEGetNthDesc, 1,
+ PyDoc_STR("(long index, DescType desiredType) -> (AEKeyword theAEKeyword, AEDesc result)")},
+ {"AESizeOfNthItem", (PyCFunction)AEDesc_AESizeOfNthItem, 1,
+ PyDoc_STR("(long index) -> (DescType typeCode, Size dataSize)")},
+ {"AEDeleteItem", (PyCFunction)AEDesc_AEDeleteItem, 1,
+ PyDoc_STR("(long index) -> None")},
+ {"AEPutParamPtr", (PyCFunction)AEDesc_AEPutParamPtr, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr) -> None")},
+ {"AEPutParamDesc", (PyCFunction)AEDesc_AEPutParamDesc, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, AEDesc theAEDesc) -> None")},
+ {"AEGetParamPtr", (PyCFunction)AEDesc_AEGetParamPtr, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType, Buffer dataPtr) -> (DescType typeCode, Buffer dataPtr)")},
+ {"AEGetParamDesc", (PyCFunction)AEDesc_AEGetParamDesc, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType) -> (AEDesc result)")},
+ {"AESizeOfParam", (PyCFunction)AEDesc_AESizeOfParam, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword) -> (DescType typeCode, Size dataSize)")},
+ {"AEDeleteParam", (PyCFunction)AEDesc_AEDeleteParam, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword) -> None")},
+ {"AEGetAttributePtr", (PyCFunction)AEDesc_AEGetAttributePtr, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType, Buffer dataPtr) -> (DescType typeCode, Buffer dataPtr)")},
+ {"AEGetAttributeDesc", (PyCFunction)AEDesc_AEGetAttributeDesc, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, DescType desiredType) -> (AEDesc result)")},
+ {"AESizeOfAttribute", (PyCFunction)AEDesc_AESizeOfAttribute, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword) -> (DescType typeCode, Size dataSize)")},
+ {"AEPutAttributePtr", (PyCFunction)AEDesc_AEPutAttributePtr, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, DescType typeCode, Buffer dataPtr) -> None")},
+ {"AEPutAttributeDesc", (PyCFunction)AEDesc_AEPutAttributeDesc, 1,
+ PyDoc_STR("(AEKeyword theAEKeyword, AEDesc theAEDesc) -> None")},
+ {"AEGetDescDataSize", (PyCFunction)AEDesc_AEGetDescDataSize, 1,
+ PyDoc_STR("() -> (Size _rv)")},
+ {"AESend", (PyCFunction)AEDesc_AESend, 1,
+ PyDoc_STR("(AESendMode sendMode, AESendPriority sendPriority, long timeOutInTicks) -> (AppleEvent reply)")},
+ {"AEResetTimer", (PyCFunction)AEDesc_AEResetTimer, 1,
+ PyDoc_STR("() -> None")},
+ {"AESuspendTheCurrentEvent", (PyCFunction)AEDesc_AESuspendTheCurrentEvent, 1,
+ PyDoc_STR("() -> None")},
+ {"AEResumeTheCurrentEvent", (PyCFunction)AEDesc_AEResumeTheCurrentEvent, 1,
+ PyDoc_STR("(AppleEvent reply, EventHandler dispatcher) -> None")},
+ {"AEGetTheCurrentEvent", (PyCFunction)AEDesc_AEGetTheCurrentEvent, 1,
+ PyDoc_STR("() -> None")},
+ {"AESetTheCurrentEvent", (PyCFunction)AEDesc_AESetTheCurrentEvent, 1,
+ PyDoc_STR("() -> None")},
+ {"AEResolve", (PyCFunction)AEDesc_AEResolve, 1,
+ PyDoc_STR("(short callbackFlags) -> (AEDesc theToken)")},
+ {"AutoDispose", (PyCFunction)AEDesc_AutoDispose, 1,
+ PyDoc_STR("(int)->int. Automatically AEDisposeDesc the object on Python object cleanup")},
+ {NULL, NULL, 0}
};
static PyObject *AEDesc_get_type(AEDescObject *self, void *closure)
{
- return PyMac_BuildOSType(self->ob_itself.descriptorType);
+ return PyMac_BuildOSType(self->ob_itself.descriptorType);
}
#define AEDesc_set_type NULL
static PyObject *AEDesc_get_data(AEDescObject *self, void *closure)
{
- PyObject *res;
- Size size;
- char *ptr;
- OSErr err;
-
- size = AEGetDescDataSize(&self->ob_itself);
- if ( (res = PyString_FromStringAndSize(NULL, size)) == NULL )
- return NULL;
- if ( (ptr = PyString_AsString(res)) == NULL )
- return NULL;
- if ( (err=AEGetDescData(&self->ob_itself, ptr, size)) < 0 )
- return PyMac_Error(err);
- return res;
+ PyObject *res;
+ Size size;
+ char *ptr;
+ OSErr err;
+
+ size = AEGetDescDataSize(&self->ob_itself);
+ if ( (res = PyString_FromStringAndSize(NULL, size)) == NULL )
+ return NULL;
+ if ( (ptr = PyString_AsString(res)) == NULL )
+ return NULL;
+ if ( (err=AEGetDescData(&self->ob_itself, ptr, size)) < 0 )
+ return PyMac_Error(err);
+ return res;
}
#define AEDesc_set_data NULL
static PyGetSetDef AEDesc_getsetlist[] = {
- {"type", (getter)AEDesc_get_type, (setter)AEDesc_set_type, "Type of this AEDesc"},
- {"data", (getter)AEDesc_get_data, (setter)AEDesc_set_data, "The raw data in this AEDesc"},
- {NULL, NULL, NULL, NULL},
+ {"type", (getter)AEDesc_get_type, (setter)AEDesc_set_type, "Type of this AEDesc"},
+ {"data", (getter)AEDesc_get_data, (setter)AEDesc_set_data, "The raw data in this AEDesc"},
+ {NULL, NULL, NULL, NULL},
};
@@ -869,61 +869,61 @@ static PyGetSetDef AEDesc_getsetlist[] = {
static PyObject *AEDesc_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- AEDesc itself;
- char *kw[] = {"itself", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, AEDesc_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((AEDescObject *)_self)->ob_itself = itself;
- return _self;
+ PyObject *_self;
+ AEDesc itself;
+ char *kw[] = {"itself", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, AEDesc_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((AEDescObject *)_self)->ob_itself = itself;
+ return _self;
}
#define AEDesc_tp_free PyObject_Del
PyTypeObject AEDesc_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_AE.AEDesc", /*tp_name*/
- sizeof(AEDescObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) AEDesc_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) AEDesc_compare, /*tp_compare*/
- (reprfunc) AEDesc_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) AEDesc_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*/
- AEDesc_methods, /* tp_methods */
- 0, /*tp_members*/
- AEDesc_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- AEDesc_tp_init, /* tp_init */
- AEDesc_tp_alloc, /* tp_alloc */
- AEDesc_tp_new, /* tp_new */
- AEDesc_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_AE.AEDesc", /*tp_name*/
+ sizeof(AEDescObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) AEDesc_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) AEDesc_compare, /*tp_compare*/
+ (reprfunc) AEDesc_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) AEDesc_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*/
+ AEDesc_methods, /* tp_methods */
+ 0, /*tp_members*/
+ AEDesc_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ AEDesc_tp_init, /* tp_init */
+ AEDesc_tp_alloc, /* tp_alloc */
+ AEDesc_tp_new, /* tp_new */
+ AEDesc_tp_free, /* tp_free */
};
/* --------------------- End object type AEDesc --------------------- */
@@ -931,455 +931,455 @@ PyTypeObject AEDesc_Type = {
static PyObject *AE_AECoercePtr(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DescType typeCode;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
- DescType toType;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DescType typeCode;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
+ DescType toType;
+ AEDesc result;
#ifndef AECoercePtr
- PyMac_PRECHECK(AECoercePtr);
+ PyMac_PRECHECK(AECoercePtr);
#endif
- if (!PyArg_ParseTuple(_args, "O&s#O&",
- PyMac_GetOSType, &typeCode,
- &dataPtr__in__, &dataPtr__in_len__,
- PyMac_GetOSType, &toType))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AECoercePtr(typeCode,
- dataPtr__in__, dataPtr__len__,
- toType,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s#O&",
+ PyMac_GetOSType, &typeCode,
+ &dataPtr__in__, &dataPtr__in_len__,
+ PyMac_GetOSType, &toType))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AECoercePtr(typeCode,
+ dataPtr__in__, dataPtr__len__,
+ toType,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AE_AECreateDesc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DescType typeCode;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DescType typeCode;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
+ AEDesc result;
#ifndef AECreateDesc
- PyMac_PRECHECK(AECreateDesc);
+ PyMac_PRECHECK(AECreateDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- PyMac_GetOSType, &typeCode,
- &dataPtr__in__, &dataPtr__in_len__))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AECreateDesc(typeCode,
- dataPtr__in__, dataPtr__len__,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ PyMac_GetOSType, &typeCode,
+ &dataPtr__in__, &dataPtr__in_len__))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AECreateDesc(typeCode,
+ dataPtr__in__, dataPtr__len__,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AE_AECreateList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- char *factoringPtr__in__;
- long factoringPtr__len__;
- int factoringPtr__in_len__;
- Boolean isRecord;
- AEDescList resultList;
+ PyObject *_res = NULL;
+ OSErr _err;
+ char *factoringPtr__in__;
+ long factoringPtr__len__;
+ int factoringPtr__in_len__;
+ Boolean isRecord;
+ AEDescList resultList;
#ifndef AECreateList
- PyMac_PRECHECK(AECreateList);
+ PyMac_PRECHECK(AECreateList);
#endif
- if (!PyArg_ParseTuple(_args, "s#b",
- &factoringPtr__in__, &factoringPtr__in_len__,
- &isRecord))
- return NULL;
- factoringPtr__len__ = factoringPtr__in_len__;
- _err = AECreateList(factoringPtr__in__, factoringPtr__len__,
- isRecord,
- &resultList);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultList);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#b",
+ &factoringPtr__in__, &factoringPtr__in_len__,
+ &isRecord))
+ return NULL;
+ factoringPtr__len__ = factoringPtr__in_len__;
+ _err = AECreateList(factoringPtr__in__, factoringPtr__len__,
+ isRecord,
+ &resultList);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultList);
+ return _res;
}
static PyObject *AE_AECreateAppleEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEEventClass theAEEventClass;
- AEEventID theAEEventID;
- AEAddressDesc target;
- AEReturnID returnID;
- AETransactionID transactionID;
- AppleEvent result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEEventClass theAEEventClass;
+ AEEventID theAEEventID;
+ AEAddressDesc target;
+ AEReturnID returnID;
+ AETransactionID transactionID;
+ AppleEvent result;
#ifndef AECreateAppleEvent
- PyMac_PRECHECK(AECreateAppleEvent);
+ PyMac_PRECHECK(AECreateAppleEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&hl",
- PyMac_GetOSType, &theAEEventClass,
- PyMac_GetOSType, &theAEEventID,
- AEDesc_Convert, &target,
- &returnID,
- &transactionID))
- return NULL;
- _err = AECreateAppleEvent(theAEEventClass,
- theAEEventID,
- &target,
- returnID,
- transactionID,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&hl",
+ PyMac_GetOSType, &theAEEventClass,
+ PyMac_GetOSType, &theAEEventID,
+ AEDesc_Convert, &target,
+ &returnID,
+ &transactionID))
+ return NULL;
+ _err = AECreateAppleEvent(theAEEventClass,
+ theAEEventID,
+ &target,
+ returnID,
+ transactionID,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *AE_AEReplaceDescData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DescType typeCode;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
- AEDesc theAEDesc;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DescType typeCode;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
+ AEDesc theAEDesc;
#ifndef AEReplaceDescData
- PyMac_PRECHECK(AEReplaceDescData);
+ PyMac_PRECHECK(AEReplaceDescData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- PyMac_GetOSType, &typeCode,
- &dataPtr__in__, &dataPtr__in_len__))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AEReplaceDescData(typeCode,
- dataPtr__in__, dataPtr__len__,
- &theAEDesc);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &theAEDesc);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ PyMac_GetOSType, &typeCode,
+ &dataPtr__in__, &dataPtr__in_len__))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AEReplaceDescData(typeCode,
+ dataPtr__in__, dataPtr__len__,
+ &theAEDesc);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &theAEDesc);
+ return _res;
}
static PyObject *AE_AEProcessAppleEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- EventRecord theEventRecord;
+ PyObject *_res = NULL;
+ OSErr _err;
+ EventRecord theEventRecord;
#ifndef AEProcessAppleEvent
- PyMac_PRECHECK(AEProcessAppleEvent);
+ PyMac_PRECHECK(AEProcessAppleEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &theEventRecord))
- return NULL;
- _err = AEProcessAppleEvent(&theEventRecord);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &theEventRecord))
+ return NULL;
+ _err = AEProcessAppleEvent(&theEventRecord);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AEGetInteractionAllowed(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEInteractAllowed level;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEInteractAllowed level;
#ifndef AEGetInteractionAllowed
- PyMac_PRECHECK(AEGetInteractionAllowed);
+ PyMac_PRECHECK(AEGetInteractionAllowed);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AEGetInteractionAllowed(&level);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- level);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AEGetInteractionAllowed(&level);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ level);
+ return _res;
}
static PyObject *AE_AESetInteractionAllowed(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEInteractAllowed level;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEInteractAllowed level;
#ifndef AESetInteractionAllowed
- PyMac_PRECHECK(AESetInteractionAllowed);
+ PyMac_PRECHECK(AESetInteractionAllowed);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &level))
- return NULL;
- _err = AESetInteractionAllowed(level);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &level))
+ return NULL;
+ _err = AESetInteractionAllowed(level);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AEInteractWithUser(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long timeOutInTicks;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long timeOutInTicks;
#ifndef AEInteractWithUser
- PyMac_PRECHECK(AEInteractWithUser);
+ PyMac_PRECHECK(AEInteractWithUser);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &timeOutInTicks))
- return NULL;
- _err = AEInteractWithUser(timeOutInTicks,
- (NMRecPtr)0,
- upp_AEIdleProc);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &timeOutInTicks))
+ return NULL;
+ _err = AEInteractWithUser(timeOutInTicks,
+ (NMRecPtr)0,
+ upp_AEIdleProc);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AEInstallEventHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEEventClass theAEEventClass;
- AEEventID theAEEventID;
- AEEventHandlerUPP handler__proc__ = upp_GenericEventHandler;
- PyObject *handler;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEEventClass theAEEventClass;
+ AEEventID theAEEventID;
+ AEEventHandlerUPP handler__proc__ = upp_GenericEventHandler;
+ PyObject *handler;
#ifndef AEInstallEventHandler
- PyMac_PRECHECK(AEInstallEventHandler);
+ PyMac_PRECHECK(AEInstallEventHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O",
- PyMac_GetOSType, &theAEEventClass,
- PyMac_GetOSType, &theAEEventID,
- &handler))
- return NULL;
- _err = AEInstallEventHandler(theAEEventClass,
- theAEEventID,
- handler__proc__, (SRefCon)handler,
- 0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- Py_INCREF(handler); /* XXX leak, but needed */
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O",
+ PyMac_GetOSType, &theAEEventClass,
+ PyMac_GetOSType, &theAEEventID,
+ &handler))
+ return NULL;
+ _err = AEInstallEventHandler(theAEEventClass,
+ theAEEventID,
+ handler__proc__, (SRefCon)handler,
+ 0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ Py_INCREF(handler); /* XXX leak, but needed */
+ return _res;
}
static PyObject *AE_AERemoveEventHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEEventClass theAEEventClass;
- AEEventID theAEEventID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEEventClass theAEEventClass;
+ AEEventID theAEEventID;
#ifndef AERemoveEventHandler
- PyMac_PRECHECK(AERemoveEventHandler);
+ PyMac_PRECHECK(AERemoveEventHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theAEEventClass,
- PyMac_GetOSType, &theAEEventID))
- return NULL;
- _err = AERemoveEventHandler(theAEEventClass,
- theAEEventID,
- upp_GenericEventHandler,
- 0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theAEEventClass,
+ PyMac_GetOSType, &theAEEventID))
+ return NULL;
+ _err = AERemoveEventHandler(theAEEventClass,
+ theAEEventID,
+ upp_GenericEventHandler,
+ 0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AEGetEventHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEEventClass theAEEventClass;
- AEEventID theAEEventID;
- AEEventHandlerUPP handler__proc__ = upp_GenericEventHandler;
- PyObject *handler;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEEventClass theAEEventClass;
+ AEEventID theAEEventID;
+ AEEventHandlerUPP handler__proc__ = upp_GenericEventHandler;
+ PyObject *handler;
#ifndef AEGetEventHandler
- PyMac_PRECHECK(AEGetEventHandler);
+ PyMac_PRECHECK(AEGetEventHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theAEEventClass,
- PyMac_GetOSType, &theAEEventID))
- return NULL;
- _err = AEGetEventHandler(theAEEventClass,
- theAEEventID,
- &handler__proc__, (SRefCon *)&handler,
- 0);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O",
- handler);
- Py_INCREF(handler); /* XXX leak, but needed */
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theAEEventClass,
+ PyMac_GetOSType, &theAEEventID))
+ return NULL;
+ _err = AEGetEventHandler(theAEEventClass,
+ theAEEventID,
+ &handler__proc__, (SRefCon *)&handler,
+ 0);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O",
+ handler);
+ Py_INCREF(handler); /* XXX leak, but needed */
+ return _res;
}
static PyObject *AE_AEInstallSpecialHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword functionClass;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword functionClass;
#ifndef AEInstallSpecialHandler
- PyMac_PRECHECK(AEInstallSpecialHandler);
+ PyMac_PRECHECK(AEInstallSpecialHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &functionClass))
- return NULL;
- _err = AEInstallSpecialHandler(functionClass,
- upp_GenericEventHandler,
- 0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &functionClass))
+ return NULL;
+ _err = AEInstallSpecialHandler(functionClass,
+ upp_GenericEventHandler,
+ 0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AERemoveSpecialHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword functionClass;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword functionClass;
#ifndef AERemoveSpecialHandler
- PyMac_PRECHECK(AERemoveSpecialHandler);
+ PyMac_PRECHECK(AERemoveSpecialHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &functionClass))
- return NULL;
- _err = AERemoveSpecialHandler(functionClass,
- upp_GenericEventHandler,
- 0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &functionClass))
+ return NULL;
+ _err = AERemoveSpecialHandler(functionClass,
+ upp_GenericEventHandler,
+ 0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AEManagerInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEKeyword keyWord;
- long result;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEKeyword keyWord;
+ long result;
#ifndef AEManagerInfo
- PyMac_PRECHECK(AEManagerInfo);
+ PyMac_PRECHECK(AEManagerInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &keyWord))
- return NULL;
- _err = AEManagerInfo(keyWord,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &keyWord))
+ return NULL;
+ _err = AEManagerInfo(keyWord,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ result);
+ return _res;
}
static PyObject *AE_AEObjectInit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef AEObjectInit
- PyMac_PRECHECK(AEObjectInit);
+ PyMac_PRECHECK(AEObjectInit);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AEObjectInit();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AEObjectInit();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *AE_AEDisposeToken(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEDesc theToken;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEDesc theToken;
#ifndef AEDisposeToken
- PyMac_PRECHECK(AEDisposeToken);
+ PyMac_PRECHECK(AEDisposeToken);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AEDisposeToken(&theToken);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &theToken);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AEDisposeToken(&theToken);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &theToken);
+ return _res;
}
static PyObject *AE_AECallObjectAccessor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DescType desiredClass;
- AEDesc containerToken;
- DescType containerClass;
- DescType keyForm;
- AEDesc keyData;
- AEDesc token;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DescType desiredClass;
+ AEDesc containerToken;
+ DescType containerClass;
+ DescType keyForm;
+ AEDesc keyData;
+ AEDesc token;
#ifndef AECallObjectAccessor
- PyMac_PRECHECK(AECallObjectAccessor);
+ PyMac_PRECHECK(AECallObjectAccessor);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
- PyMac_GetOSType, &desiredClass,
- AEDesc_Convert, &containerToken,
- PyMac_GetOSType, &containerClass,
- PyMac_GetOSType, &keyForm,
- AEDesc_Convert, &keyData))
- return NULL;
- _err = AECallObjectAccessor(desiredClass,
- &containerToken,
- containerClass,
- keyForm,
- &keyData,
- &token);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &token);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
+ PyMac_GetOSType, &desiredClass,
+ AEDesc_Convert, &containerToken,
+ PyMac_GetOSType, &containerClass,
+ PyMac_GetOSType, &keyForm,
+ AEDesc_Convert, &keyData))
+ return NULL;
+ _err = AECallObjectAccessor(desiredClass,
+ &containerToken,
+ containerClass,
+ keyForm,
+ &keyData,
+ &token);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &token);
+ return _res;
}
static PyMethodDef AE_methods[] = {
- {"AECoercePtr", (PyCFunction)AE_AECoercePtr, 1,
- PyDoc_STR("(DescType typeCode, Buffer dataPtr, DescType toType) -> (AEDesc result)")},
- {"AECreateDesc", (PyCFunction)AE_AECreateDesc, 1,
- PyDoc_STR("(DescType typeCode, Buffer dataPtr) -> (AEDesc result)")},
- {"AECreateList", (PyCFunction)AE_AECreateList, 1,
- PyDoc_STR("(Buffer factoringPtr, Boolean isRecord) -> (AEDescList resultList)")},
- {"AECreateAppleEvent", (PyCFunction)AE_AECreateAppleEvent, 1,
- PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID, AEAddressDesc target, AEReturnID returnID, AETransactionID transactionID) -> (AppleEvent result)")},
- {"AEReplaceDescData", (PyCFunction)AE_AEReplaceDescData, 1,
- PyDoc_STR("(DescType typeCode, Buffer dataPtr) -> (AEDesc theAEDesc)")},
- {"AEProcessAppleEvent", (PyCFunction)AE_AEProcessAppleEvent, 1,
- PyDoc_STR("(EventRecord theEventRecord) -> None")},
- {"AEGetInteractionAllowed", (PyCFunction)AE_AEGetInteractionAllowed, 1,
- PyDoc_STR("() -> (AEInteractAllowed level)")},
- {"AESetInteractionAllowed", (PyCFunction)AE_AESetInteractionAllowed, 1,
- PyDoc_STR("(AEInteractAllowed level) -> None")},
- {"AEInteractWithUser", (PyCFunction)AE_AEInteractWithUser, 1,
- PyDoc_STR("(long timeOutInTicks) -> None")},
- {"AEInstallEventHandler", (PyCFunction)AE_AEInstallEventHandler, 1,
- PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID, EventHandler handler) -> None")},
- {"AERemoveEventHandler", (PyCFunction)AE_AERemoveEventHandler, 1,
- PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID) -> None")},
- {"AEGetEventHandler", (PyCFunction)AE_AEGetEventHandler, 1,
- PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID) -> (EventHandler handler)")},
- {"AEInstallSpecialHandler", (PyCFunction)AE_AEInstallSpecialHandler, 1,
- PyDoc_STR("(AEKeyword functionClass) -> None")},
- {"AERemoveSpecialHandler", (PyCFunction)AE_AERemoveSpecialHandler, 1,
- PyDoc_STR("(AEKeyword functionClass) -> None")},
- {"AEManagerInfo", (PyCFunction)AE_AEManagerInfo, 1,
- PyDoc_STR("(AEKeyword keyWord) -> (long result)")},
- {"AEObjectInit", (PyCFunction)AE_AEObjectInit, 1,
- PyDoc_STR("() -> None")},
- {"AEDisposeToken", (PyCFunction)AE_AEDisposeToken, 1,
- PyDoc_STR("() -> (AEDesc theToken)")},
- {"AECallObjectAccessor", (PyCFunction)AE_AECallObjectAccessor, 1,
- PyDoc_STR("(DescType desiredClass, AEDesc containerToken, DescType containerClass, DescType keyForm, AEDesc keyData) -> (AEDesc token)")},
- {NULL, NULL, 0}
+ {"AECoercePtr", (PyCFunction)AE_AECoercePtr, 1,
+ PyDoc_STR("(DescType typeCode, Buffer dataPtr, DescType toType) -> (AEDesc result)")},
+ {"AECreateDesc", (PyCFunction)AE_AECreateDesc, 1,
+ PyDoc_STR("(DescType typeCode, Buffer dataPtr) -> (AEDesc result)")},
+ {"AECreateList", (PyCFunction)AE_AECreateList, 1,
+ PyDoc_STR("(Buffer factoringPtr, Boolean isRecord) -> (AEDescList resultList)")},
+ {"AECreateAppleEvent", (PyCFunction)AE_AECreateAppleEvent, 1,
+ PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID, AEAddressDesc target, AEReturnID returnID, AETransactionID transactionID) -> (AppleEvent result)")},
+ {"AEReplaceDescData", (PyCFunction)AE_AEReplaceDescData, 1,
+ PyDoc_STR("(DescType typeCode, Buffer dataPtr) -> (AEDesc theAEDesc)")},
+ {"AEProcessAppleEvent", (PyCFunction)AE_AEProcessAppleEvent, 1,
+ PyDoc_STR("(EventRecord theEventRecord) -> None")},
+ {"AEGetInteractionAllowed", (PyCFunction)AE_AEGetInteractionAllowed, 1,
+ PyDoc_STR("() -> (AEInteractAllowed level)")},
+ {"AESetInteractionAllowed", (PyCFunction)AE_AESetInteractionAllowed, 1,
+ PyDoc_STR("(AEInteractAllowed level) -> None")},
+ {"AEInteractWithUser", (PyCFunction)AE_AEInteractWithUser, 1,
+ PyDoc_STR("(long timeOutInTicks) -> None")},
+ {"AEInstallEventHandler", (PyCFunction)AE_AEInstallEventHandler, 1,
+ PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID, EventHandler handler) -> None")},
+ {"AERemoveEventHandler", (PyCFunction)AE_AERemoveEventHandler, 1,
+ PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID) -> None")},
+ {"AEGetEventHandler", (PyCFunction)AE_AEGetEventHandler, 1,
+ PyDoc_STR("(AEEventClass theAEEventClass, AEEventID theAEEventID) -> (EventHandler handler)")},
+ {"AEInstallSpecialHandler", (PyCFunction)AE_AEInstallSpecialHandler, 1,
+ PyDoc_STR("(AEKeyword functionClass) -> None")},
+ {"AERemoveSpecialHandler", (PyCFunction)AE_AERemoveSpecialHandler, 1,
+ PyDoc_STR("(AEKeyword functionClass) -> None")},
+ {"AEManagerInfo", (PyCFunction)AE_AEManagerInfo, 1,
+ PyDoc_STR("(AEKeyword keyWord) -> (long result)")},
+ {"AEObjectInit", (PyCFunction)AE_AEObjectInit, 1,
+ PyDoc_STR("() -> None")},
+ {"AEDisposeToken", (PyCFunction)AE_AEDisposeToken, 1,
+ PyDoc_STR("() -> (AEDesc theToken)")},
+ {"AECallObjectAccessor", (PyCFunction)AE_AECallObjectAccessor, 1,
+ PyDoc_STR("(DescType desiredClass, AEDesc containerToken, DescType containerClass, DescType keyForm, AEDesc keyData) -> (AEDesc token)")},
+ {NULL, NULL, 0}
};
@@ -1387,72 +1387,72 @@ static PyMethodDef AE_methods[] = {
static pascal OSErr
GenericEventHandler(const AppleEvent *request, AppleEvent *reply, refcontype refcon)
{
- PyObject *handler = (PyObject *)refcon;
- AEDescObject *requestObject, *replyObject;
- PyObject *args, *res;
- if ((requestObject = (AEDescObject *)AEDesc_New((AppleEvent *)request)) == NULL) {
- return -1;
- }
- if ((replyObject = (AEDescObject *)AEDesc_New(reply)) == NULL) {
- Py_DECREF(requestObject);
- return -1;
- }
- if ((args = Py_BuildValue("OO", requestObject, replyObject)) == NULL) {
- Py_DECREF(requestObject);
- Py_DECREF(replyObject);
- return -1;
- }
- res = PyEval_CallObject(handler, args);
- requestObject->ob_itself.descriptorType = 'null';
- requestObject->ob_itself.dataHandle = NULL;
- replyObject->ob_itself.descriptorType = 'null';
- replyObject->ob_itself.dataHandle = NULL;
- Py_DECREF(args);
- if (res == NULL) {
- PySys_WriteStderr("Exception in AE event handler function\n");
- PyErr_Print();
- return -1;
- }
- Py_DECREF(res);
- return noErr;
+ PyObject *handler = (PyObject *)refcon;
+ AEDescObject *requestObject, *replyObject;
+ PyObject *args, *res;
+ if ((requestObject = (AEDescObject *)AEDesc_New((AppleEvent *)request)) == NULL) {
+ return -1;
+ }
+ if ((replyObject = (AEDescObject *)AEDesc_New(reply)) == NULL) {
+ Py_DECREF(requestObject);
+ return -1;
+ }
+ if ((args = Py_BuildValue("OO", requestObject, replyObject)) == NULL) {
+ Py_DECREF(requestObject);
+ Py_DECREF(replyObject);
+ return -1;
+ }
+ res = PyEval_CallObject(handler, args);
+ requestObject->ob_itself.descriptorType = 'null';
+ requestObject->ob_itself.dataHandle = NULL;
+ replyObject->ob_itself.descriptorType = 'null';
+ replyObject->ob_itself.dataHandle = NULL;
+ Py_DECREF(args);
+ if (res == NULL) {
+ PySys_WriteStderr("Exception in AE event handler function\n");
+ PyErr_Print();
+ return -1;
+ }
+ Py_DECREF(res);
+ return noErr;
}
PyObject *AEDesc_NewBorrowed(AEDesc *itself)
{
- PyObject *it;
+ PyObject *it;
- it = AEDesc_New(itself);
- if (it)
- ((AEDescObject *)it)->ob_owned = 0;
- return (PyObject *)it;
+ it = AEDesc_New(itself);
+ if (it)
+ ((AEDescObject *)it)->ob_owned = 0;
+ return (PyObject *)it;
}
void init_AE(void)
{
- PyObject *m;
- PyObject *d;
-
- upp_AEIdleProc = NewAEIdleUPP(AEIdleProc);
- upp_GenericEventHandler = NewAEEventHandlerUPP(GenericEventHandler);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_New);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_NewBorrowed);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(AEDesc, AEDesc_Convert);
-
- m = Py_InitModule("_AE", AE_methods);
- d = PyModule_GetDict(m);
- AE_Error = PyMac_GetOSErrException();
- if (AE_Error == NULL ||
- PyDict_SetItemString(d, "Error", AE_Error) != 0)
- return;
- AEDesc_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&AEDesc_Type) < 0) return;
- Py_INCREF(&AEDesc_Type);
- PyModule_AddObject(m, "AEDesc", (PyObject *)&AEDesc_Type);
- /* Backward-compatible name */
- Py_INCREF(&AEDesc_Type);
- PyModule_AddObject(m, "AEDescType", (PyObject *)&AEDesc_Type);
+ PyObject *m;
+ PyObject *d;
+
+ upp_AEIdleProc = NewAEIdleUPP(AEIdleProc);
+ upp_GenericEventHandler = NewAEEventHandlerUPP(GenericEventHandler);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_New);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(AEDesc *, AEDesc_NewBorrowed);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(AEDesc, AEDesc_Convert);
+
+ m = Py_InitModule("_AE", AE_methods);
+ d = PyModule_GetDict(m);
+ AE_Error = PyMac_GetOSErrException();
+ if (AE_Error == NULL ||
+ PyDict_SetItemString(d, "Error", AE_Error) != 0)
+ return;
+ AEDesc_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&AEDesc_Type) < 0) return;
+ Py_INCREF(&AEDesc_Type);
+ PyModule_AddObject(m, "AEDesc", (PyObject *)&AEDesc_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&AEDesc_Type);
+ PyModule_AddObject(m, "AEDescType", (PyObject *)&AEDesc_Type);
}
/* ========================= End module _AE ========================= */
diff --git a/Mac/Modules/ah/_AHmodule.c b/Mac/Modules/ah/_AHmodule.c
index 160a845..73ab437 100644
--- a/Mac/Modules/ah/_AHmodule.c
+++ b/Mac/Modules/ah/_AHmodule.c
@@ -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 ========================= */
diff --git a/Mac/Modules/app/_Appmodule.c b/Mac/Modules/app/_Appmodule.c
index 52d17f5..c791807 100644
--- a/Mac/Modules/app/_Appmodule.c
+++ b/Mac/Modules/app/_Appmodule.c
@@ -4,16 +4,16 @@
#include "Python.h"
#ifndef __LP64__
- /* Carbon GUI stuff, not available in 64-bit mode */
+ /* Carbon GUI stuff, not available in 64-bit mode */
#include "pymactoolbox.h"
/* 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,7 +22,7 @@
static int ThemeButtonDrawInfo_Convert(PyObject *v, ThemeButtonDrawInfo *p_itself)
{
- return PyArg_Parse(v, "(iHH)", &p_itself->state, &p_itself->value, &p_itself->adornment);
+ return PyArg_Parse(v, "(iHH)", &p_itself->state, &p_itself->value, &p_itself->adornment);
}
@@ -35,75 +35,75 @@ PyTypeObject ThemeDrawingState_Type;
#define ThemeDrawingStateObj_Check(x) ((x)->ob_type == &ThemeDrawingState_Type || PyObject_TypeCheck((x), &ThemeDrawingState_Type))
typedef struct ThemeDrawingStateObject {
- PyObject_HEAD
- ThemeDrawingState ob_itself;
+ PyObject_HEAD
+ ThemeDrawingState ob_itself;
} ThemeDrawingStateObject;
PyObject *ThemeDrawingStateObj_New(ThemeDrawingState itself)
{
- ThemeDrawingStateObject *it;
- it = PyObject_NEW(ThemeDrawingStateObject, &ThemeDrawingState_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ ThemeDrawingStateObject *it;
+ it = PyObject_NEW(ThemeDrawingStateObject, &ThemeDrawingState_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int ThemeDrawingStateObj_Convert(PyObject *v, ThemeDrawingState *p_itself)
{
- if (!ThemeDrawingStateObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "ThemeDrawingState required");
- return 0;
- }
- *p_itself = ((ThemeDrawingStateObject *)v)->ob_itself;
- return 1;
+ if (!ThemeDrawingStateObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "ThemeDrawingState required");
+ return 0;
+ }
+ *p_itself = ((ThemeDrawingStateObject *)v)->ob_itself;
+ return 1;
}
static void ThemeDrawingStateObj_dealloc(ThemeDrawingStateObject *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 *ThemeDrawingStateObj_SetThemeDrawingState(ThemeDrawingStateObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _rv;
- Boolean inDisposeNow;
+ PyObject *_res = NULL;
+ OSStatus _rv;
+ Boolean inDisposeNow;
#ifndef SetThemeDrawingState
- PyMac_PRECHECK(SetThemeDrawingState);
+ PyMac_PRECHECK(SetThemeDrawingState);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &inDisposeNow))
- return NULL;
- _rv = SetThemeDrawingState(_self->ob_itself,
- inDisposeNow);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &inDisposeNow))
+ return NULL;
+ _rv = SetThemeDrawingState(_self->ob_itself,
+ inDisposeNow);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ThemeDrawingStateObj_DisposeThemeDrawingState(ThemeDrawingStateObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _rv;
+ PyObject *_res = NULL;
+ OSStatus _rv;
#ifndef DisposeThemeDrawingState
- PyMac_PRECHECK(DisposeThemeDrawingState);
+ PyMac_PRECHECK(DisposeThemeDrawingState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = DisposeThemeDrawingState(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = DisposeThemeDrawingState(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyMethodDef ThemeDrawingStateObj_methods[] = {
- {"SetThemeDrawingState", (PyCFunction)ThemeDrawingStateObj_SetThemeDrawingState, 1,
- PyDoc_STR("(Boolean inDisposeNow) -> (OSStatus _rv)")},
- {"DisposeThemeDrawingState", (PyCFunction)ThemeDrawingStateObj_DisposeThemeDrawingState, 1,
- PyDoc_STR("() -> (OSStatus _rv)")},
- {NULL, NULL, 0}
+ {"SetThemeDrawingState", (PyCFunction)ThemeDrawingStateObj_SetThemeDrawingState, 1,
+ PyDoc_STR("(Boolean inDisposeNow) -> (OSStatus _rv)")},
+ {"DisposeThemeDrawingState", (PyCFunction)ThemeDrawingStateObj_DisposeThemeDrawingState, 1,
+ PyDoc_STR("() -> (OSStatus _rv)")},
+ {NULL, NULL, 0}
};
#define ThemeDrawingStateObj_getsetlist NULL
@@ -120,61 +120,61 @@ static PyMethodDef ThemeDrawingStateObj_methods[] = {
static PyObject *ThemeDrawingStateObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- ThemeDrawingState itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ ThemeDrawingState itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, ThemeDrawingStateObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((ThemeDrawingStateObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, ThemeDrawingStateObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((ThemeDrawingStateObject *)_self)->ob_itself = itself;
+ return _self;
}
#define ThemeDrawingStateObj_tp_free PyObject_Del
PyTypeObject ThemeDrawingState_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_App.ThemeDrawingState", /*tp_name*/
- sizeof(ThemeDrawingStateObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) ThemeDrawingStateObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) ThemeDrawingStateObj_compare, /*tp_compare*/
- (reprfunc) ThemeDrawingStateObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) ThemeDrawingStateObj_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*/
- ThemeDrawingStateObj_methods, /* tp_methods */
- 0, /*tp_members*/
- ThemeDrawingStateObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- ThemeDrawingStateObj_tp_init, /* tp_init */
- ThemeDrawingStateObj_tp_alloc, /* tp_alloc */
- ThemeDrawingStateObj_tp_new, /* tp_new */
- ThemeDrawingStateObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_App.ThemeDrawingState", /*tp_name*/
+ sizeof(ThemeDrawingStateObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) ThemeDrawingStateObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) ThemeDrawingStateObj_compare, /*tp_compare*/
+ (reprfunc) ThemeDrawingStateObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) ThemeDrawingStateObj_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*/
+ ThemeDrawingStateObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ ThemeDrawingStateObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ ThemeDrawingStateObj_tp_init, /* tp_init */
+ ThemeDrawingStateObj_tp_alloc, /* tp_alloc */
+ ThemeDrawingStateObj_tp_new, /* tp_new */
+ ThemeDrawingStateObj_tp_free, /* tp_free */
};
/* --------------- End object type ThemeDrawingState ---------------- */
@@ -182,1622 +182,1622 @@ PyTypeObject ThemeDrawingState_Type = {
static PyObject *App_RegisterAppearanceClient(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef RegisterAppearanceClient
- PyMac_PRECHECK(RegisterAppearanceClient);
+ PyMac_PRECHECK(RegisterAppearanceClient);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = RegisterAppearanceClient();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = RegisterAppearanceClient();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_UnregisterAppearanceClient(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef UnregisterAppearanceClient
- PyMac_PRECHECK(UnregisterAppearanceClient);
+ PyMac_PRECHECK(UnregisterAppearanceClient);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UnregisterAppearanceClient();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = UnregisterAppearanceClient();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetThemePen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeBrush inBrush;
- SInt16 inDepth;
- Boolean inIsColorDevice;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeBrush inBrush;
+ SInt16 inDepth;
+ Boolean inIsColorDevice;
#ifndef SetThemePen
- PyMac_PRECHECK(SetThemePen);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &inBrush,
- &inDepth,
- &inIsColorDevice))
- return NULL;
- _err = SetThemePen(inBrush,
- inDepth,
- inIsColorDevice);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetThemePen);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &inBrush,
+ &inDepth,
+ &inIsColorDevice))
+ return NULL;
+ _err = SetThemePen(inBrush,
+ inDepth,
+ inIsColorDevice);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetThemeBackground(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeBrush inBrush;
- SInt16 inDepth;
- Boolean inIsColorDevice;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeBrush inBrush;
+ SInt16 inDepth;
+ Boolean inIsColorDevice;
#ifndef SetThemeBackground
- PyMac_PRECHECK(SetThemeBackground);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &inBrush,
- &inDepth,
- &inIsColorDevice))
- return NULL;
- _err = SetThemeBackground(inBrush,
- inDepth,
- inIsColorDevice);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetThemeBackground);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &inBrush,
+ &inDepth,
+ &inIsColorDevice))
+ return NULL;
+ _err = SetThemeBackground(inBrush,
+ inDepth,
+ inIsColorDevice);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetThemeTextColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeTextColor inColor;
- SInt16 inDepth;
- Boolean inIsColorDevice;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeTextColor inColor;
+ SInt16 inDepth;
+ Boolean inIsColorDevice;
#ifndef SetThemeTextColor
- PyMac_PRECHECK(SetThemeTextColor);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &inColor,
- &inDepth,
- &inIsColorDevice))
- return NULL;
- _err = SetThemeTextColor(inColor,
- inDepth,
- inIsColorDevice);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetThemeTextColor);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &inColor,
+ &inDepth,
+ &inIsColorDevice))
+ return NULL;
+ _err = SetThemeTextColor(inColor,
+ inDepth,
+ inIsColorDevice);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetThemeWindowBackground(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- ThemeBrush inBrush;
- Boolean inUpdate;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ ThemeBrush inBrush;
+ Boolean inUpdate;
#ifndef SetThemeWindowBackground
- PyMac_PRECHECK(SetThemeWindowBackground);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hb",
- WinObj_Convert, &inWindow,
- &inBrush,
- &inUpdate))
- return NULL;
- _err = SetThemeWindowBackground(inWindow,
- inBrush,
- inUpdate);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetThemeWindowBackground);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hb",
+ WinObj_Convert, &inWindow,
+ &inBrush,
+ &inUpdate))
+ return NULL;
+ _err = SetThemeWindowBackground(inWindow,
+ inBrush,
+ inUpdate);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeWindowHeader(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeWindowHeader
- PyMac_PRECHECK(DrawThemeWindowHeader);
+ PyMac_PRECHECK(DrawThemeWindowHeader);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeWindowHeader(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeWindowHeader(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeWindowListViewHeader(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeWindowListViewHeader
- PyMac_PRECHECK(DrawThemeWindowListViewHeader);
+ PyMac_PRECHECK(DrawThemeWindowListViewHeader);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeWindowListViewHeader(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeWindowListViewHeader(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemePlacard(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemePlacard
- PyMac_PRECHECK(DrawThemePlacard);
+ PyMac_PRECHECK(DrawThemePlacard);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemePlacard(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemePlacard(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeEditTextFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeEditTextFrame
- PyMac_PRECHECK(DrawThemeEditTextFrame);
+ PyMac_PRECHECK(DrawThemeEditTextFrame);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeEditTextFrame(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeEditTextFrame(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeListBoxFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeListBoxFrame
- PyMac_PRECHECK(DrawThemeListBoxFrame);
+ PyMac_PRECHECK(DrawThemeListBoxFrame);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeListBoxFrame(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeListBoxFrame(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeFocusRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- Boolean inHasFocus;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ Boolean inHasFocus;
#ifndef DrawThemeFocusRect
- PyMac_PRECHECK(DrawThemeFocusRect);
+ PyMac_PRECHECK(DrawThemeFocusRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetRect, &inRect,
- &inHasFocus))
- return NULL;
- _err = DrawThemeFocusRect(&inRect,
- inHasFocus);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetRect, &inRect,
+ &inHasFocus))
+ return NULL;
+ _err = DrawThemeFocusRect(&inRect,
+ inHasFocus);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemePrimaryGroup(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemePrimaryGroup
- PyMac_PRECHECK(DrawThemePrimaryGroup);
+ PyMac_PRECHECK(DrawThemePrimaryGroup);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemePrimaryGroup(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemePrimaryGroup(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeSecondaryGroup(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeSecondaryGroup
- PyMac_PRECHECK(DrawThemeSecondaryGroup);
+ PyMac_PRECHECK(DrawThemeSecondaryGroup);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeSecondaryGroup(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeSecondaryGroup(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeSeparator(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeSeparator
- PyMac_PRECHECK(DrawThemeSeparator);
+ PyMac_PRECHECK(DrawThemeSeparator);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeSeparator(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeSeparator(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeModelessDialogFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeModelessDialogFrame
- PyMac_PRECHECK(DrawThemeModelessDialogFrame);
+ PyMac_PRECHECK(DrawThemeModelessDialogFrame);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeModelessDialogFrame(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeModelessDialogFrame(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeGenericWell(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
- Boolean inFillCenter;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
+ Boolean inFillCenter;
#ifndef DrawThemeGenericWell
- PyMac_PRECHECK(DrawThemeGenericWell);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lb",
- PyMac_GetRect, &inRect,
- &inState,
- &inFillCenter))
- return NULL;
- _err = DrawThemeGenericWell(&inRect,
- inState,
- inFillCenter);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeGenericWell);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lb",
+ PyMac_GetRect, &inRect,
+ &inState,
+ &inFillCenter))
+ return NULL;
+ _err = DrawThemeGenericWell(&inRect,
+ inState,
+ inFillCenter);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeFocusRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean inHasFocus;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean inHasFocus;
#ifndef DrawThemeFocusRegion
- PyMac_PRECHECK(DrawThemeFocusRegion);
+ PyMac_PRECHECK(DrawThemeFocusRegion);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &inHasFocus))
- return NULL;
- _err = DrawThemeFocusRegion((RgnHandle)0,
- inHasFocus);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &inHasFocus))
+ return NULL;
+ _err = DrawThemeFocusRegion((RgnHandle)0,
+ inHasFocus);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_IsThemeInColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- SInt16 inDepth;
- Boolean inIsColorDevice;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ SInt16 inDepth;
+ Boolean inIsColorDevice;
#ifndef IsThemeInColor
- PyMac_PRECHECK(IsThemeInColor);
+ PyMac_PRECHECK(IsThemeInColor);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &inDepth,
- &inIsColorDevice))
- return NULL;
- _rv = IsThemeInColor(inDepth,
- inIsColorDevice);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &inDepth,
+ &inIsColorDevice))
+ return NULL;
+ _rv = IsThemeInColor(inDepth,
+ inIsColorDevice);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *App_GetThemeAccentColors(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CTabHandle outColors;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CTabHandle outColors;
#ifndef GetThemeAccentColors
- PyMac_PRECHECK(GetThemeAccentColors);
+ PyMac_PRECHECK(GetThemeAccentColors);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeAccentColors(&outColors);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, outColors);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeAccentColors(&outColors);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, outColors);
+ return _res;
}
static PyObject *App_DrawThemeMenuBarBackground(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inBounds;
- ThemeMenuBarState inState;
- UInt32 inAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inBounds;
+ ThemeMenuBarState inState;
+ UInt32 inAttributes;
#ifndef DrawThemeMenuBarBackground
- PyMac_PRECHECK(DrawThemeMenuBarBackground);
-#endif
- if (!PyArg_ParseTuple(_args, "O&Hl",
- PyMac_GetRect, &inBounds,
- &inState,
- &inAttributes))
- return NULL;
- _err = DrawThemeMenuBarBackground(&inBounds,
- inState,
- inAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeMenuBarBackground);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&Hl",
+ PyMac_GetRect, &inBounds,
+ &inState,
+ &inAttributes))
+ return NULL;
+ _err = DrawThemeMenuBarBackground(&inBounds,
+ inState,
+ inAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeMenuBarHeight(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 outHeight;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 outHeight;
#ifndef GetThemeMenuBarHeight
- PyMac_PRECHECK(GetThemeMenuBarHeight);
+ PyMac_PRECHECK(GetThemeMenuBarHeight);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeMenuBarHeight(&outHeight);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outHeight);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeMenuBarHeight(&outHeight);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outHeight);
+ return _res;
}
static PyObject *App_DrawThemeMenuBackground(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inMenuRect;
- ThemeMenuType inMenuType;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inMenuRect;
+ ThemeMenuType inMenuType;
#ifndef DrawThemeMenuBackground
- PyMac_PRECHECK(DrawThemeMenuBackground);
+ PyMac_PRECHECK(DrawThemeMenuBackground);
#endif
- if (!PyArg_ParseTuple(_args, "O&H",
- PyMac_GetRect, &inMenuRect,
- &inMenuType))
- return NULL;
- _err = DrawThemeMenuBackground(&inMenuRect,
- inMenuType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&H",
+ PyMac_GetRect, &inMenuRect,
+ &inMenuType))
+ return NULL;
+ _err = DrawThemeMenuBackground(&inMenuRect,
+ inMenuType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeMenuBackgroundRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inMenuRect;
- ThemeMenuType menuType;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inMenuRect;
+ ThemeMenuType menuType;
#ifndef GetThemeMenuBackgroundRegion
- PyMac_PRECHECK(GetThemeMenuBackgroundRegion);
+ PyMac_PRECHECK(GetThemeMenuBackgroundRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&H",
- PyMac_GetRect, &inMenuRect,
- &menuType))
- return NULL;
- _err = GetThemeMenuBackgroundRegion(&inMenuRect,
- menuType,
- (RgnHandle)0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&H",
+ PyMac_GetRect, &inMenuRect,
+ &menuType))
+ return NULL;
+ _err = GetThemeMenuBackgroundRegion(&inMenuRect,
+ menuType,
+ (RgnHandle)0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeMenuSeparator(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inItemRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inItemRect;
#ifndef DrawThemeMenuSeparator
- PyMac_PRECHECK(DrawThemeMenuSeparator);
+ PyMac_PRECHECK(DrawThemeMenuSeparator);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &inItemRect))
- return NULL;
- _err = DrawThemeMenuSeparator(&inItemRect);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &inItemRect))
+ return NULL;
+ _err = DrawThemeMenuSeparator(&inItemRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeMenuSeparatorHeight(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 outHeight;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 outHeight;
#ifndef GetThemeMenuSeparatorHeight
- PyMac_PRECHECK(GetThemeMenuSeparatorHeight);
+ PyMac_PRECHECK(GetThemeMenuSeparatorHeight);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeMenuSeparatorHeight(&outHeight);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outHeight);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeMenuSeparatorHeight(&outHeight);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outHeight);
+ return _res;
}
static PyObject *App_GetThemeMenuItemExtra(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeMenuItemType inItemType;
- SInt16 outHeight;
- SInt16 outWidth;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeMenuItemType inItemType;
+ SInt16 outHeight;
+ SInt16 outWidth;
#ifndef GetThemeMenuItemExtra
- PyMac_PRECHECK(GetThemeMenuItemExtra);
+ PyMac_PRECHECK(GetThemeMenuItemExtra);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &inItemType))
- return NULL;
- _err = GetThemeMenuItemExtra(inItemType,
- &outHeight,
- &outWidth);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hh",
- outHeight,
- outWidth);
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &inItemType))
+ return NULL;
+ _err = GetThemeMenuItemExtra(inItemType,
+ &outHeight,
+ &outWidth);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hh",
+ outHeight,
+ outWidth);
+ return _res;
}
static PyObject *App_GetThemeMenuTitleExtra(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 outWidth;
- Boolean inIsSquished;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 outWidth;
+ Boolean inIsSquished;
#ifndef GetThemeMenuTitleExtra
- PyMac_PRECHECK(GetThemeMenuTitleExtra);
+ PyMac_PRECHECK(GetThemeMenuTitleExtra);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &inIsSquished))
- return NULL;
- _err = GetThemeMenuTitleExtra(&outWidth,
- inIsSquished);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outWidth);
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &inIsSquished))
+ return NULL;
+ _err = GetThemeMenuTitleExtra(&outWidth,
+ inIsSquished);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outWidth);
+ return _res;
}
static PyObject *App_DrawThemeTabPane(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeDrawState inState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeDrawState inState;
#ifndef DrawThemeTabPane
- PyMac_PRECHECK(DrawThemeTabPane);
+ PyMac_PRECHECK(DrawThemeTabPane);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &inRect,
- &inState))
- return NULL;
- _err = DrawThemeTabPane(&inRect,
- inState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &inRect,
+ &inState))
+ return NULL;
+ _err = DrawThemeTabPane(&inRect,
+ inState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeTabRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inRect;
- ThemeTabStyle inStyle;
- ThemeTabDirection inDirection;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inRect;
+ ThemeTabStyle inStyle;
+ ThemeTabDirection inDirection;
#ifndef GetThemeTabRegion
- PyMac_PRECHECK(GetThemeTabRegion);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HH",
- PyMac_GetRect, &inRect,
- &inStyle,
- &inDirection))
- return NULL;
- _err = GetThemeTabRegion(&inRect,
- inStyle,
- inDirection,
- (RgnHandle)0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(GetThemeTabRegion);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HH",
+ PyMac_GetRect, &inRect,
+ &inStyle,
+ &inDirection))
+ return NULL;
+ _err = GetThemeTabRegion(&inRect,
+ inStyle,
+ inDirection,
+ (RgnHandle)0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetThemeCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeCursor inCursor;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeCursor inCursor;
#ifndef SetThemeCursor
- PyMac_PRECHECK(SetThemeCursor);
+ PyMac_PRECHECK(SetThemeCursor);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCursor))
- return NULL;
- _err = SetThemeCursor(inCursor);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCursor))
+ return NULL;
+ _err = SetThemeCursor(inCursor);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetAnimatedThemeCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeCursor inCursor;
- UInt32 inAnimationStep;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeCursor inCursor;
+ UInt32 inAnimationStep;
#ifndef SetAnimatedThemeCursor
- PyMac_PRECHECK(SetAnimatedThemeCursor);
+ PyMac_PRECHECK(SetAnimatedThemeCursor);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &inCursor,
- &inAnimationStep))
- return NULL;
- _err = SetAnimatedThemeCursor(inCursor,
- inAnimationStep);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &inCursor,
+ &inAnimationStep))
+ return NULL;
+ _err = SetAnimatedThemeCursor(inCursor,
+ inAnimationStep);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeScrollBarThumbStyle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeScrollBarThumbStyle outStyle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeScrollBarThumbStyle outStyle;
#ifndef GetThemeScrollBarThumbStyle
- PyMac_PRECHECK(GetThemeScrollBarThumbStyle);
+ PyMac_PRECHECK(GetThemeScrollBarThumbStyle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeScrollBarThumbStyle(&outStyle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeScrollBarThumbStyle(&outStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outStyle);
+ return _res;
}
static PyObject *App_GetThemeScrollBarArrowStyle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeScrollBarArrowStyle outStyle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeScrollBarArrowStyle outStyle;
#ifndef GetThemeScrollBarArrowStyle
- PyMac_PRECHECK(GetThemeScrollBarArrowStyle);
+ PyMac_PRECHECK(GetThemeScrollBarArrowStyle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeScrollBarArrowStyle(&outStyle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeScrollBarArrowStyle(&outStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outStyle);
+ return _res;
}
static PyObject *App_GetThemeCheckBoxStyle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeCheckBoxStyle outStyle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeCheckBoxStyle outStyle;
#ifndef GetThemeCheckBoxStyle
- PyMac_PRECHECK(GetThemeCheckBoxStyle);
+ PyMac_PRECHECK(GetThemeCheckBoxStyle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeCheckBoxStyle(&outStyle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeCheckBoxStyle(&outStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outStyle);
+ return _res;
}
static PyObject *App_UseThemeFont(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeFontID inFontID;
- ScriptCode inScript;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeFontID inFontID;
+ ScriptCode inScript;
#ifndef UseThemeFont
- PyMac_PRECHECK(UseThemeFont);
+ PyMac_PRECHECK(UseThemeFont);
#endif
- if (!PyArg_ParseTuple(_args, "Hh",
- &inFontID,
- &inScript))
- return NULL;
- _err = UseThemeFont(inFontID,
- inScript);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "Hh",
+ &inFontID,
+ &inScript))
+ return NULL;
+ _err = UseThemeFont(inFontID,
+ inScript);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeTextBox(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
- ThemeFontID inFontID;
- ThemeDrawState inState;
- Boolean inWrapToWidth;
- Rect inBoundingBox;
- SInt16 inJust;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
+ ThemeFontID inFontID;
+ ThemeDrawState inState;
+ Boolean inWrapToWidth;
+ Rect inBoundingBox;
+ SInt16 inJust;
#ifndef DrawThemeTextBox
- PyMac_PRECHECK(DrawThemeTextBox);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HlbO&h",
- CFStringRefObj_Convert, &inString,
- &inFontID,
- &inState,
- &inWrapToWidth,
- PyMac_GetRect, &inBoundingBox,
- &inJust))
- return NULL;
- _err = DrawThemeTextBox(inString,
- inFontID,
- inState,
- inWrapToWidth,
- &inBoundingBox,
- inJust,
- NULL);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeTextBox);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HlbO&h",
+ CFStringRefObj_Convert, &inString,
+ &inFontID,
+ &inState,
+ &inWrapToWidth,
+ PyMac_GetRect, &inBoundingBox,
+ &inJust))
+ return NULL;
+ _err = DrawThemeTextBox(inString,
+ inFontID,
+ inState,
+ inWrapToWidth,
+ &inBoundingBox,
+ inJust,
+ NULL);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_TruncateThemeText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFMutableStringRef inString;
- ThemeFontID inFontID;
- ThemeDrawState inState;
- SInt16 inPixelWidthLimit;
- TruncCode inTruncWhere;
- Boolean outTruncated;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFMutableStringRef inString;
+ ThemeFontID inFontID;
+ ThemeDrawState inState;
+ SInt16 inPixelWidthLimit;
+ TruncCode inTruncWhere;
+ Boolean outTruncated;
#ifndef TruncateThemeText
- PyMac_PRECHECK(TruncateThemeText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&Hlhh",
- CFMutableStringRefObj_Convert, &inString,
- &inFontID,
- &inState,
- &inPixelWidthLimit,
- &inTruncWhere))
- return NULL;
- _err = TruncateThemeText(inString,
- inFontID,
- inState,
- inPixelWidthLimit,
- inTruncWhere,
- &outTruncated);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- outTruncated);
- return _res;
+ PyMac_PRECHECK(TruncateThemeText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&Hlhh",
+ CFMutableStringRefObj_Convert, &inString,
+ &inFontID,
+ &inState,
+ &inPixelWidthLimit,
+ &inTruncWhere))
+ return NULL;
+ _err = TruncateThemeText(inString,
+ inFontID,
+ inState,
+ inPixelWidthLimit,
+ inTruncWhere,
+ &outTruncated);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ outTruncated);
+ return _res;
}
static PyObject *App_GetThemeTextDimensions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
- ThemeFontID inFontID;
- ThemeDrawState inState;
- Boolean inWrapToWidth;
- Point ioBounds;
- SInt16 outBaseline;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
+ ThemeFontID inFontID;
+ ThemeDrawState inState;
+ Boolean inWrapToWidth;
+ Point ioBounds;
+ SInt16 outBaseline;
#ifndef GetThemeTextDimensions
- PyMac_PRECHECK(GetThemeTextDimensions);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HlbO&",
- CFStringRefObj_Convert, &inString,
- &inFontID,
- &inState,
- &inWrapToWidth,
- PyMac_GetPoint, &ioBounds))
- return NULL;
- _err = GetThemeTextDimensions(inString,
- inFontID,
- inState,
- inWrapToWidth,
- &ioBounds,
- &outBaseline);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- PyMac_BuildPoint, ioBounds,
- outBaseline);
- return _res;
+ PyMac_PRECHECK(GetThemeTextDimensions);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HlbO&",
+ CFStringRefObj_Convert, &inString,
+ &inFontID,
+ &inState,
+ &inWrapToWidth,
+ PyMac_GetPoint, &ioBounds))
+ return NULL;
+ _err = GetThemeTextDimensions(inString,
+ inFontID,
+ inState,
+ inWrapToWidth,
+ &ioBounds,
+ &outBaseline);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ PyMac_BuildPoint, ioBounds,
+ outBaseline);
+ return _res;
}
static PyObject *App_GetThemeTextShadowOutset(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeFontID inFontID;
- ThemeDrawState inState;
- Rect outOutset;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeFontID inFontID;
+ ThemeDrawState inState;
+ Rect outOutset;
#ifndef GetThemeTextShadowOutset
- PyMac_PRECHECK(GetThemeTextShadowOutset);
+ PyMac_PRECHECK(GetThemeTextShadowOutset);
#endif
- if (!PyArg_ParseTuple(_args, "Hl",
- &inFontID,
- &inState))
- return NULL;
- _err = GetThemeTextShadowOutset(inFontID,
- inState,
- &outOutset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outOutset);
- return _res;
+ if (!PyArg_ParseTuple(_args, "Hl",
+ &inFontID,
+ &inState))
+ return NULL;
+ _err = GetThemeTextShadowOutset(inFontID,
+ inState,
+ &outOutset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outOutset);
+ return _res;
}
static PyObject *App_DrawThemeScrollBarArrows(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
- ThemeTrackEnableState enableState;
- ThemeTrackPressState pressState;
- Boolean isHoriz;
- Rect trackBounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
+ ThemeTrackEnableState enableState;
+ ThemeTrackPressState pressState;
+ Boolean isHoriz;
+ Rect trackBounds;
#ifndef DrawThemeScrollBarArrows
- PyMac_PRECHECK(DrawThemeScrollBarArrows);
-#endif
- if (!PyArg_ParseTuple(_args, "O&bbb",
- PyMac_GetRect, &bounds,
- &enableState,
- &pressState,
- &isHoriz))
- return NULL;
- _err = DrawThemeScrollBarArrows(&bounds,
- enableState,
- pressState,
- isHoriz,
- &trackBounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &trackBounds);
- return _res;
+ PyMac_PRECHECK(DrawThemeScrollBarArrows);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&bbb",
+ PyMac_GetRect, &bounds,
+ &enableState,
+ &pressState,
+ &isHoriz))
+ return NULL;
+ _err = DrawThemeScrollBarArrows(&bounds,
+ enableState,
+ pressState,
+ isHoriz,
+ &trackBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &trackBounds);
+ return _res;
}
static PyObject *App_GetThemeScrollBarTrackRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
- ThemeTrackEnableState enableState;
- ThemeTrackPressState pressState;
- Boolean isHoriz;
- Rect trackBounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
+ ThemeTrackEnableState enableState;
+ ThemeTrackPressState pressState;
+ Boolean isHoriz;
+ Rect trackBounds;
#ifndef GetThemeScrollBarTrackRect
- PyMac_PRECHECK(GetThemeScrollBarTrackRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&bbb",
- PyMac_GetRect, &bounds,
- &enableState,
- &pressState,
- &isHoriz))
- return NULL;
- _err = GetThemeScrollBarTrackRect(&bounds,
- enableState,
- pressState,
- isHoriz,
- &trackBounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &trackBounds);
- return _res;
+ PyMac_PRECHECK(GetThemeScrollBarTrackRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&bbb",
+ PyMac_GetRect, &bounds,
+ &enableState,
+ &pressState,
+ &isHoriz))
+ return NULL;
+ _err = GetThemeScrollBarTrackRect(&bounds,
+ enableState,
+ pressState,
+ isHoriz,
+ &trackBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &trackBounds);
+ return _res;
}
static PyObject *App_HitTestThemeScrollBarArrows(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect scrollBarBounds;
- ThemeTrackEnableState enableState;
- ThemeTrackPressState pressState;
- Boolean isHoriz;
- Point ptHit;
- Rect trackBounds;
- ControlPartCode partcode;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect scrollBarBounds;
+ ThemeTrackEnableState enableState;
+ ThemeTrackPressState pressState;
+ Boolean isHoriz;
+ Point ptHit;
+ Rect trackBounds;
+ ControlPartCode partcode;
#ifndef HitTestThemeScrollBarArrows
- PyMac_PRECHECK(HitTestThemeScrollBarArrows);
-#endif
- if (!PyArg_ParseTuple(_args, "O&bbbO&",
- PyMac_GetRect, &scrollBarBounds,
- &enableState,
- &pressState,
- &isHoriz,
- PyMac_GetPoint, &ptHit))
- return NULL;
- _rv = HitTestThemeScrollBarArrows(&scrollBarBounds,
- enableState,
- pressState,
- isHoriz,
- ptHit,
- &trackBounds,
- &partcode);
- _res = Py_BuildValue("bO&h",
- _rv,
- PyMac_BuildRect, &trackBounds,
- partcode);
- return _res;
+ PyMac_PRECHECK(HitTestThemeScrollBarArrows);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&bbbO&",
+ PyMac_GetRect, &scrollBarBounds,
+ &enableState,
+ &pressState,
+ &isHoriz,
+ PyMac_GetPoint, &ptHit))
+ return NULL;
+ _rv = HitTestThemeScrollBarArrows(&scrollBarBounds,
+ enableState,
+ pressState,
+ isHoriz,
+ ptHit,
+ &trackBounds,
+ &partcode);
+ _res = Py_BuildValue("bO&h",
+ _rv,
+ PyMac_BuildRect, &trackBounds,
+ partcode);
+ return _res;
}
static PyObject *App_DrawThemeScrollBarDelimiters(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeWindowType flavor;
- Rect inContRect;
- ThemeDrawState state;
- ThemeWindowAttributes attributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeWindowType flavor;
+ Rect inContRect;
+ ThemeDrawState state;
+ ThemeWindowAttributes attributes;
#ifndef DrawThemeScrollBarDelimiters
- PyMac_PRECHECK(DrawThemeScrollBarDelimiters);
-#endif
- if (!PyArg_ParseTuple(_args, "HO&ll",
- &flavor,
- PyMac_GetRect, &inContRect,
- &state,
- &attributes))
- return NULL;
- _err = DrawThemeScrollBarDelimiters(flavor,
- &inContRect,
- state,
- attributes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeScrollBarDelimiters);
+#endif
+ if (!PyArg_ParseTuple(_args, "HO&ll",
+ &flavor,
+ PyMac_GetRect, &inContRect,
+ &state,
+ &attributes))
+ return NULL;
+ _err = DrawThemeScrollBarDelimiters(flavor,
+ &inContRect,
+ state,
+ attributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeButton(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inBounds;
- UInt16 inKind;
- ThemeButtonDrawInfo inNewInfo;
- ThemeButtonDrawInfo inPrevInfo;
- UInt32 inUserData;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inBounds;
+ UInt16 inKind;
+ ThemeButtonDrawInfo inNewInfo;
+ ThemeButtonDrawInfo inPrevInfo;
+ UInt32 inUserData;
#ifndef DrawThemeButton
- PyMac_PRECHECK(DrawThemeButton);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HO&O&l",
- PyMac_GetRect, &inBounds,
- &inKind,
- ThemeButtonDrawInfo_Convert, &inNewInfo,
- ThemeButtonDrawInfo_Convert, &inPrevInfo,
- &inUserData))
- return NULL;
- _err = DrawThemeButton(&inBounds,
- inKind,
- &inNewInfo,
- &inPrevInfo,
- NULL,
- NULL,
- inUserData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeButton);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HO&O&l",
+ PyMac_GetRect, &inBounds,
+ &inKind,
+ ThemeButtonDrawInfo_Convert, &inNewInfo,
+ ThemeButtonDrawInfo_Convert, &inPrevInfo,
+ &inUserData))
+ return NULL;
+ _err = DrawThemeButton(&inBounds,
+ inKind,
+ &inNewInfo,
+ &inPrevInfo,
+ NULL,
+ NULL,
+ inUserData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeButtonRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inBounds;
- UInt16 inKind;
- ThemeButtonDrawInfo inNewInfo;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inBounds;
+ UInt16 inKind;
+ ThemeButtonDrawInfo inNewInfo;
#ifndef GetThemeButtonRegion
- PyMac_PRECHECK(GetThemeButtonRegion);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HO&",
- PyMac_GetRect, &inBounds,
- &inKind,
- ThemeButtonDrawInfo_Convert, &inNewInfo))
- return NULL;
- _err = GetThemeButtonRegion(&inBounds,
- inKind,
- &inNewInfo,
- (RgnHandle)0);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(GetThemeButtonRegion);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HO&",
+ PyMac_GetRect, &inBounds,
+ &inKind,
+ ThemeButtonDrawInfo_Convert, &inNewInfo))
+ return NULL;
+ _err = GetThemeButtonRegion(&inBounds,
+ inKind,
+ &inNewInfo,
+ (RgnHandle)0);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeButtonContentBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inBounds;
- UInt16 inKind;
- ThemeButtonDrawInfo inDrawInfo;
- Rect outBounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inBounds;
+ UInt16 inKind;
+ ThemeButtonDrawInfo inDrawInfo;
+ Rect outBounds;
#ifndef GetThemeButtonContentBounds
- PyMac_PRECHECK(GetThemeButtonContentBounds);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HO&",
- PyMac_GetRect, &inBounds,
- &inKind,
- ThemeButtonDrawInfo_Convert, &inDrawInfo))
- return NULL;
- _err = GetThemeButtonContentBounds(&inBounds,
- inKind,
- &inDrawInfo,
- &outBounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outBounds);
- return _res;
+ PyMac_PRECHECK(GetThemeButtonContentBounds);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HO&",
+ PyMac_GetRect, &inBounds,
+ &inKind,
+ ThemeButtonDrawInfo_Convert, &inDrawInfo))
+ return NULL;
+ _err = GetThemeButtonContentBounds(&inBounds,
+ inKind,
+ &inDrawInfo,
+ &outBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outBounds);
+ return _res;
}
static PyObject *App_GetThemeButtonBackgroundBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inBounds;
- UInt16 inKind;
- ThemeButtonDrawInfo inDrawInfo;
- Rect outBounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inBounds;
+ UInt16 inKind;
+ ThemeButtonDrawInfo inDrawInfo;
+ Rect outBounds;
#ifndef GetThemeButtonBackgroundBounds
- PyMac_PRECHECK(GetThemeButtonBackgroundBounds);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HO&",
- PyMac_GetRect, &inBounds,
- &inKind,
- ThemeButtonDrawInfo_Convert, &inDrawInfo))
- return NULL;
- _err = GetThemeButtonBackgroundBounds(&inBounds,
- inKind,
- &inDrawInfo,
- &outBounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outBounds);
- return _res;
+ PyMac_PRECHECK(GetThemeButtonBackgroundBounds);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HO&",
+ PyMac_GetRect, &inBounds,
+ &inKind,
+ ThemeButtonDrawInfo_Convert, &inDrawInfo))
+ return NULL;
+ _err = GetThemeButtonBackgroundBounds(&inBounds,
+ inKind,
+ &inDrawInfo,
+ &outBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outBounds);
+ return _res;
}
static PyObject *App_PlayThemeSound(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeSoundKind kind;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeSoundKind kind;
#ifndef PlayThemeSound
- PyMac_PRECHECK(PlayThemeSound);
+ PyMac_PRECHECK(PlayThemeSound);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &kind))
- return NULL;
- _err = PlayThemeSound(kind);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &kind))
+ return NULL;
+ _err = PlayThemeSound(kind);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_BeginThemeDragSound(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeDragSoundKind kind;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeDragSoundKind kind;
#ifndef BeginThemeDragSound
- PyMac_PRECHECK(BeginThemeDragSound);
+ PyMac_PRECHECK(BeginThemeDragSound);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &kind))
- return NULL;
- _err = BeginThemeDragSound(kind);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &kind))
+ return NULL;
+ _err = BeginThemeDragSound(kind);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_EndThemeDragSound(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef EndThemeDragSound
- PyMac_PRECHECK(EndThemeDragSound);
+ PyMac_PRECHECK(EndThemeDragSound);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = EndThemeDragSound();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = EndThemeDragSound();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeTickMark(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
- ThemeDrawState state;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
+ ThemeDrawState state;
#ifndef DrawThemeTickMark
- PyMac_PRECHECK(DrawThemeTickMark);
+ PyMac_PRECHECK(DrawThemeTickMark);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &bounds,
- &state))
- return NULL;
- _err = DrawThemeTickMark(&bounds,
- state);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &bounds,
+ &state))
+ return NULL;
+ _err = DrawThemeTickMark(&bounds,
+ state);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeChasingArrows(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
- UInt32 index;
- ThemeDrawState state;
- UInt32 eraseData;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
+ UInt32 index;
+ ThemeDrawState state;
+ UInt32 eraseData;
#ifndef DrawThemeChasingArrows
- PyMac_PRECHECK(DrawThemeChasingArrows);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- PyMac_GetRect, &bounds,
- &index,
- &state,
- &eraseData))
- return NULL;
- _err = DrawThemeChasingArrows(&bounds,
- index,
- state,
- NULL,
- eraseData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeChasingArrows);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ PyMac_GetRect, &bounds,
+ &index,
+ &state,
+ &eraseData))
+ return NULL;
+ _err = DrawThemeChasingArrows(&bounds,
+ index,
+ state,
+ NULL,
+ eraseData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemePopupArrow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
- ThemeArrowOrientation orientation;
- ThemePopupArrowSize size;
- ThemeDrawState state;
- UInt32 eraseData;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
+ ThemeArrowOrientation orientation;
+ ThemePopupArrowSize size;
+ ThemeDrawState state;
+ UInt32 eraseData;
#ifndef DrawThemePopupArrow
- PyMac_PRECHECK(DrawThemePopupArrow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&HHll",
- PyMac_GetRect, &bounds,
- &orientation,
- &size,
- &state,
- &eraseData))
- return NULL;
- _err = DrawThemePopupArrow(&bounds,
- orientation,
- size,
- state,
- NULL,
- eraseData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemePopupArrow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&HHll",
+ PyMac_GetRect, &bounds,
+ &orientation,
+ &size,
+ &state,
+ &eraseData))
+ return NULL;
+ _err = DrawThemePopupArrow(&bounds,
+ orientation,
+ size,
+ state,
+ NULL,
+ eraseData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeStandaloneGrowBox(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point origin;
- ThemeGrowDirection growDirection;
- Boolean isSmall;
- ThemeDrawState state;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point origin;
+ ThemeGrowDirection growDirection;
+ Boolean isSmall;
+ ThemeDrawState state;
#ifndef DrawThemeStandaloneGrowBox
- PyMac_PRECHECK(DrawThemeStandaloneGrowBox);
-#endif
- if (!PyArg_ParseTuple(_args, "O&Hbl",
- PyMac_GetPoint, &origin,
- &growDirection,
- &isSmall,
- &state))
- return NULL;
- _err = DrawThemeStandaloneGrowBox(origin,
- growDirection,
- isSmall,
- state);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeStandaloneGrowBox);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&Hbl",
+ PyMac_GetPoint, &origin,
+ &growDirection,
+ &isSmall,
+ &state))
+ return NULL;
+ _err = DrawThemeStandaloneGrowBox(origin,
+ growDirection,
+ isSmall,
+ state);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_DrawThemeStandaloneNoGrowBox(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point origin;
- ThemeGrowDirection growDirection;
- Boolean isSmall;
- ThemeDrawState state;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point origin;
+ ThemeGrowDirection growDirection;
+ Boolean isSmall;
+ ThemeDrawState state;
#ifndef DrawThemeStandaloneNoGrowBox
- PyMac_PRECHECK(DrawThemeStandaloneNoGrowBox);
-#endif
- if (!PyArg_ParseTuple(_args, "O&Hbl",
- PyMac_GetPoint, &origin,
- &growDirection,
- &isSmall,
- &state))
- return NULL;
- _err = DrawThemeStandaloneNoGrowBox(origin,
- growDirection,
- isSmall,
- state);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawThemeStandaloneNoGrowBox);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&Hbl",
+ PyMac_GetPoint, &origin,
+ &growDirection,
+ &isSmall,
+ &state))
+ return NULL;
+ _err = DrawThemeStandaloneNoGrowBox(origin,
+ growDirection,
+ isSmall,
+ state);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeStandaloneGrowBoxBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point origin;
- ThemeGrowDirection growDirection;
- Boolean isSmall;
- Rect bounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point origin;
+ ThemeGrowDirection growDirection;
+ Boolean isSmall;
+ Rect bounds;
#ifndef GetThemeStandaloneGrowBoxBounds
- PyMac_PRECHECK(GetThemeStandaloneGrowBoxBounds);
-#endif
- if (!PyArg_ParseTuple(_args, "O&Hb",
- PyMac_GetPoint, &origin,
- &growDirection,
- &isSmall))
- return NULL;
- _err = GetThemeStandaloneGrowBoxBounds(origin,
- growDirection,
- isSmall,
- &bounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ PyMac_PRECHECK(GetThemeStandaloneGrowBoxBounds);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&Hb",
+ PyMac_GetPoint, &origin,
+ &growDirection,
+ &isSmall))
+ return NULL;
+ _err = GetThemeStandaloneGrowBoxBounds(origin,
+ growDirection,
+ isSmall,
+ &bounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *App_NormalizeThemeDrawingState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef NormalizeThemeDrawingState
- PyMac_PRECHECK(NormalizeThemeDrawingState);
+ PyMac_PRECHECK(NormalizeThemeDrawingState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = NormalizeThemeDrawingState();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = NormalizeThemeDrawingState();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_GetThemeDrawingState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeDrawingState outState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeDrawingState outState;
#ifndef GetThemeDrawingState
- PyMac_PRECHECK(GetThemeDrawingState);
+ PyMac_PRECHECK(GetThemeDrawingState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetThemeDrawingState(&outState);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ThemeDrawingStateObj_New, outState);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetThemeDrawingState(&outState);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ThemeDrawingStateObj_New, outState);
+ return _res;
}
static PyObject *App_ApplyThemeBackground(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeBackgroundKind inKind;
- Rect bounds;
- ThemeDrawState inState;
- SInt16 inDepth;
- Boolean inColorDev;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeBackgroundKind inKind;
+ Rect bounds;
+ ThemeDrawState inState;
+ SInt16 inDepth;
+ Boolean inColorDev;
#ifndef ApplyThemeBackground
- PyMac_PRECHECK(ApplyThemeBackground);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&lhb",
- &inKind,
- PyMac_GetRect, &bounds,
- &inState,
- &inDepth,
- &inColorDev))
- return NULL;
- _err = ApplyThemeBackground(inKind,
- &bounds,
- inState,
- inDepth,
- inColorDev);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ApplyThemeBackground);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&lhb",
+ &inKind,
+ PyMac_GetRect, &bounds,
+ &inState,
+ &inDepth,
+ &inColorDev))
+ return NULL;
+ _err = ApplyThemeBackground(inKind,
+ &bounds,
+ inState,
+ inDepth,
+ inColorDev);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_SetThemeTextColorForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Boolean isActive;
- SInt16 depth;
- Boolean isColorDev;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Boolean isActive;
+ SInt16 depth;
+ Boolean isColorDev;
#ifndef SetThemeTextColorForWindow
- PyMac_PRECHECK(SetThemeTextColorForWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&bhb",
- WinObj_Convert, &window,
- &isActive,
- &depth,
- &isColorDev))
- return NULL;
- _err = SetThemeTextColorForWindow(window,
- isActive,
- depth,
- isColorDev);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetThemeTextColorForWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&bhb",
+ WinObj_Convert, &window,
+ &isActive,
+ &depth,
+ &isColorDev))
+ return NULL;
+ _err = SetThemeTextColorForWindow(window,
+ isActive,
+ depth,
+ isColorDev);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *App_IsValidAppearanceFileType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- OSType fileType;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ OSType fileType;
#ifndef IsValidAppearanceFileType
- PyMac_PRECHECK(IsValidAppearanceFileType);
+ PyMac_PRECHECK(IsValidAppearanceFileType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &fileType))
- return NULL;
- _rv = IsValidAppearanceFileType(fileType);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &fileType))
+ return NULL;
+ _rv = IsValidAppearanceFileType(fileType);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *App_GetThemeBrushAsColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeBrush inBrush;
- SInt16 inDepth;
- Boolean inColorDev;
- RGBColor outColor;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeBrush inBrush;
+ SInt16 inDepth;
+ Boolean inColorDev;
+ RGBColor outColor;
#ifndef GetThemeBrushAsColor
- PyMac_PRECHECK(GetThemeBrushAsColor);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &inBrush,
- &inDepth,
- &inColorDev))
- return NULL;
- _err = GetThemeBrushAsColor(inBrush,
- inDepth,
- inColorDev,
- &outColor);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- QdRGB_New, &outColor);
- return _res;
+ PyMac_PRECHECK(GetThemeBrushAsColor);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &inBrush,
+ &inDepth,
+ &inColorDev))
+ return NULL;
+ _err = GetThemeBrushAsColor(inBrush,
+ inDepth,
+ inColorDev,
+ &outColor);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &outColor);
+ return _res;
}
static PyObject *App_GetThemeTextColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeTextColor inColor;
- SInt16 inDepth;
- Boolean inColorDev;
- RGBColor outColor;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeTextColor inColor;
+ SInt16 inDepth;
+ Boolean inColorDev;
+ RGBColor outColor;
#ifndef GetThemeTextColor
- PyMac_PRECHECK(GetThemeTextColor);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &inColor,
- &inDepth,
- &inColorDev))
- return NULL;
- _err = GetThemeTextColor(inColor,
- inDepth,
- inColorDev,
- &outColor);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- QdRGB_New, &outColor);
- return _res;
+ PyMac_PRECHECK(GetThemeTextColor);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &inColor,
+ &inDepth,
+ &inColorDev))
+ return NULL;
+ _err = GetThemeTextColor(inColor,
+ inDepth,
+ inColorDev,
+ &outColor);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &outColor);
+ return _res;
}
static PyObject *App_GetThemeMetric(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ThemeMetric inMetric;
- SInt32 outMetric;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ThemeMetric inMetric;
+ SInt32 outMetric;
#ifndef GetThemeMetric
- PyMac_PRECHECK(GetThemeMetric);
+ PyMac_PRECHECK(GetThemeMetric);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inMetric))
- return NULL;
- _err = GetThemeMetric(inMetric,
- &outMetric);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outMetric);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inMetric))
+ return NULL;
+ _err = GetThemeMetric(inMetric,
+ &outMetric);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outMetric);
+ return _res;
}
static PyMethodDef App_methods[] = {
- {"RegisterAppearanceClient", (PyCFunction)App_RegisterAppearanceClient, 1,
- PyDoc_STR("() -> None")},
- {"UnregisterAppearanceClient", (PyCFunction)App_UnregisterAppearanceClient, 1,
- PyDoc_STR("() -> None")},
- {"SetThemePen", (PyCFunction)App_SetThemePen, 1,
- PyDoc_STR("(ThemeBrush inBrush, SInt16 inDepth, Boolean inIsColorDevice) -> None")},
- {"SetThemeBackground", (PyCFunction)App_SetThemeBackground, 1,
- PyDoc_STR("(ThemeBrush inBrush, SInt16 inDepth, Boolean inIsColorDevice) -> None")},
- {"SetThemeTextColor", (PyCFunction)App_SetThemeTextColor, 1,
- PyDoc_STR("(ThemeTextColor inColor, SInt16 inDepth, Boolean inIsColorDevice) -> None")},
- {"SetThemeWindowBackground", (PyCFunction)App_SetThemeWindowBackground, 1,
- PyDoc_STR("(WindowPtr inWindow, ThemeBrush inBrush, Boolean inUpdate) -> None")},
- {"DrawThemeWindowHeader", (PyCFunction)App_DrawThemeWindowHeader, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeWindowListViewHeader", (PyCFunction)App_DrawThemeWindowListViewHeader, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemePlacard", (PyCFunction)App_DrawThemePlacard, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeEditTextFrame", (PyCFunction)App_DrawThemeEditTextFrame, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeListBoxFrame", (PyCFunction)App_DrawThemeListBoxFrame, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeFocusRect", (PyCFunction)App_DrawThemeFocusRect, 1,
- PyDoc_STR("(Rect inRect, Boolean inHasFocus) -> None")},
- {"DrawThemePrimaryGroup", (PyCFunction)App_DrawThemePrimaryGroup, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeSecondaryGroup", (PyCFunction)App_DrawThemeSecondaryGroup, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeSeparator", (PyCFunction)App_DrawThemeSeparator, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeModelessDialogFrame", (PyCFunction)App_DrawThemeModelessDialogFrame, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"DrawThemeGenericWell", (PyCFunction)App_DrawThemeGenericWell, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState, Boolean inFillCenter) -> None")},
- {"DrawThemeFocusRegion", (PyCFunction)App_DrawThemeFocusRegion, 1,
- PyDoc_STR("(Boolean inHasFocus) -> None")},
- {"IsThemeInColor", (PyCFunction)App_IsThemeInColor, 1,
- PyDoc_STR("(SInt16 inDepth, Boolean inIsColorDevice) -> (Boolean _rv)")},
- {"GetThemeAccentColors", (PyCFunction)App_GetThemeAccentColors, 1,
- PyDoc_STR("() -> (CTabHandle outColors)")},
- {"DrawThemeMenuBarBackground", (PyCFunction)App_DrawThemeMenuBarBackground, 1,
- PyDoc_STR("(Rect inBounds, ThemeMenuBarState inState, UInt32 inAttributes) -> None")},
- {"GetThemeMenuBarHeight", (PyCFunction)App_GetThemeMenuBarHeight, 1,
- PyDoc_STR("() -> (SInt16 outHeight)")},
- {"DrawThemeMenuBackground", (PyCFunction)App_DrawThemeMenuBackground, 1,
- PyDoc_STR("(Rect inMenuRect, ThemeMenuType inMenuType) -> None")},
- {"GetThemeMenuBackgroundRegion", (PyCFunction)App_GetThemeMenuBackgroundRegion, 1,
- PyDoc_STR("(Rect inMenuRect, ThemeMenuType menuType) -> None")},
- {"DrawThemeMenuSeparator", (PyCFunction)App_DrawThemeMenuSeparator, 1,
- PyDoc_STR("(Rect inItemRect) -> None")},
- {"GetThemeMenuSeparatorHeight", (PyCFunction)App_GetThemeMenuSeparatorHeight, 1,
- PyDoc_STR("() -> (SInt16 outHeight)")},
- {"GetThemeMenuItemExtra", (PyCFunction)App_GetThemeMenuItemExtra, 1,
- PyDoc_STR("(ThemeMenuItemType inItemType) -> (SInt16 outHeight, SInt16 outWidth)")},
- {"GetThemeMenuTitleExtra", (PyCFunction)App_GetThemeMenuTitleExtra, 1,
- PyDoc_STR("(Boolean inIsSquished) -> (SInt16 outWidth)")},
- {"DrawThemeTabPane", (PyCFunction)App_DrawThemeTabPane, 1,
- PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
- {"GetThemeTabRegion", (PyCFunction)App_GetThemeTabRegion, 1,
- PyDoc_STR("(Rect inRect, ThemeTabStyle inStyle, ThemeTabDirection inDirection) -> None")},
- {"SetThemeCursor", (PyCFunction)App_SetThemeCursor, 1,
- PyDoc_STR("(ThemeCursor inCursor) -> None")},
- {"SetAnimatedThemeCursor", (PyCFunction)App_SetAnimatedThemeCursor, 1,
- PyDoc_STR("(ThemeCursor inCursor, UInt32 inAnimationStep) -> None")},
- {"GetThemeScrollBarThumbStyle", (PyCFunction)App_GetThemeScrollBarThumbStyle, 1,
- PyDoc_STR("() -> (ThemeScrollBarThumbStyle outStyle)")},
- {"GetThemeScrollBarArrowStyle", (PyCFunction)App_GetThemeScrollBarArrowStyle, 1,
- PyDoc_STR("() -> (ThemeScrollBarArrowStyle outStyle)")},
- {"GetThemeCheckBoxStyle", (PyCFunction)App_GetThemeCheckBoxStyle, 1,
- PyDoc_STR("() -> (ThemeCheckBoxStyle outStyle)")},
- {"UseThemeFont", (PyCFunction)App_UseThemeFont, 1,
- PyDoc_STR("(ThemeFontID inFontID, ScriptCode inScript) -> None")},
- {"DrawThemeTextBox", (PyCFunction)App_DrawThemeTextBox, 1,
- PyDoc_STR("(CFStringRef inString, ThemeFontID inFontID, ThemeDrawState inState, Boolean inWrapToWidth, Rect inBoundingBox, SInt16 inJust) -> None")},
- {"TruncateThemeText", (PyCFunction)App_TruncateThemeText, 1,
- PyDoc_STR("(CFMutableStringRef inString, ThemeFontID inFontID, ThemeDrawState inState, SInt16 inPixelWidthLimit, TruncCode inTruncWhere) -> (Boolean outTruncated)")},
- {"GetThemeTextDimensions", (PyCFunction)App_GetThemeTextDimensions, 1,
- PyDoc_STR("(CFStringRef inString, ThemeFontID inFontID, ThemeDrawState inState, Boolean inWrapToWidth, Point ioBounds) -> (Point ioBounds, SInt16 outBaseline)")},
- {"GetThemeTextShadowOutset", (PyCFunction)App_GetThemeTextShadowOutset, 1,
- PyDoc_STR("(ThemeFontID inFontID, ThemeDrawState inState) -> (Rect outOutset)")},
- {"DrawThemeScrollBarArrows", (PyCFunction)App_DrawThemeScrollBarArrows, 1,
- PyDoc_STR("(Rect bounds, ThemeTrackEnableState enableState, ThemeTrackPressState pressState, Boolean isHoriz) -> (Rect trackBounds)")},
- {"GetThemeScrollBarTrackRect", (PyCFunction)App_GetThemeScrollBarTrackRect, 1,
- PyDoc_STR("(Rect bounds, ThemeTrackEnableState enableState, ThemeTrackPressState pressState, Boolean isHoriz) -> (Rect trackBounds)")},
- {"HitTestThemeScrollBarArrows", (PyCFunction)App_HitTestThemeScrollBarArrows, 1,
- PyDoc_STR("(Rect scrollBarBounds, ThemeTrackEnableState enableState, ThemeTrackPressState pressState, Boolean isHoriz, Point ptHit) -> (Boolean _rv, Rect trackBounds, ControlPartCode partcode)")},
- {"DrawThemeScrollBarDelimiters", (PyCFunction)App_DrawThemeScrollBarDelimiters, 1,
- PyDoc_STR("(ThemeWindowType flavor, Rect inContRect, ThemeDrawState state, ThemeWindowAttributes attributes) -> None")},
- {"DrawThemeButton", (PyCFunction)App_DrawThemeButton, 1,
- PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inNewInfo, ThemeButtonDrawInfo inPrevInfo, UInt32 inUserData) -> None")},
- {"GetThemeButtonRegion", (PyCFunction)App_GetThemeButtonRegion, 1,
- PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inNewInfo) -> None")},
- {"GetThemeButtonContentBounds", (PyCFunction)App_GetThemeButtonContentBounds, 1,
- PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inDrawInfo) -> (Rect outBounds)")},
- {"GetThemeButtonBackgroundBounds", (PyCFunction)App_GetThemeButtonBackgroundBounds, 1,
- PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inDrawInfo) -> (Rect outBounds)")},
- {"PlayThemeSound", (PyCFunction)App_PlayThemeSound, 1,
- PyDoc_STR("(ThemeSoundKind kind) -> None")},
- {"BeginThemeDragSound", (PyCFunction)App_BeginThemeDragSound, 1,
- PyDoc_STR("(ThemeDragSoundKind kind) -> None")},
- {"EndThemeDragSound", (PyCFunction)App_EndThemeDragSound, 1,
- PyDoc_STR("() -> None")},
- {"DrawThemeTickMark", (PyCFunction)App_DrawThemeTickMark, 1,
- PyDoc_STR("(Rect bounds, ThemeDrawState state) -> None")},
- {"DrawThemeChasingArrows", (PyCFunction)App_DrawThemeChasingArrows, 1,
- PyDoc_STR("(Rect bounds, UInt32 index, ThemeDrawState state, UInt32 eraseData) -> None")},
- {"DrawThemePopupArrow", (PyCFunction)App_DrawThemePopupArrow, 1,
- PyDoc_STR("(Rect bounds, ThemeArrowOrientation orientation, ThemePopupArrowSize size, ThemeDrawState state, UInt32 eraseData) -> None")},
- {"DrawThemeStandaloneGrowBox", (PyCFunction)App_DrawThemeStandaloneGrowBox, 1,
- PyDoc_STR("(Point origin, ThemeGrowDirection growDirection, Boolean isSmall, ThemeDrawState state) -> None")},
- {"DrawThemeStandaloneNoGrowBox", (PyCFunction)App_DrawThemeStandaloneNoGrowBox, 1,
- PyDoc_STR("(Point origin, ThemeGrowDirection growDirection, Boolean isSmall, ThemeDrawState state) -> None")},
- {"GetThemeStandaloneGrowBoxBounds", (PyCFunction)App_GetThemeStandaloneGrowBoxBounds, 1,
- PyDoc_STR("(Point origin, ThemeGrowDirection growDirection, Boolean isSmall) -> (Rect bounds)")},
- {"NormalizeThemeDrawingState", (PyCFunction)App_NormalizeThemeDrawingState, 1,
- PyDoc_STR("() -> None")},
- {"GetThemeDrawingState", (PyCFunction)App_GetThemeDrawingState, 1,
- PyDoc_STR("() -> (ThemeDrawingState outState)")},
- {"ApplyThemeBackground", (PyCFunction)App_ApplyThemeBackground, 1,
- PyDoc_STR("(ThemeBackgroundKind inKind, Rect bounds, ThemeDrawState inState, SInt16 inDepth, Boolean inColorDev) -> None")},
- {"SetThemeTextColorForWindow", (PyCFunction)App_SetThemeTextColorForWindow, 1,
- PyDoc_STR("(WindowPtr window, Boolean isActive, SInt16 depth, Boolean isColorDev) -> None")},
- {"IsValidAppearanceFileType", (PyCFunction)App_IsValidAppearanceFileType, 1,
- PyDoc_STR("(OSType fileType) -> (Boolean _rv)")},
- {"GetThemeBrushAsColor", (PyCFunction)App_GetThemeBrushAsColor, 1,
- PyDoc_STR("(ThemeBrush inBrush, SInt16 inDepth, Boolean inColorDev) -> (RGBColor outColor)")},
- {"GetThemeTextColor", (PyCFunction)App_GetThemeTextColor, 1,
- PyDoc_STR("(ThemeTextColor inColor, SInt16 inDepth, Boolean inColorDev) -> (RGBColor outColor)")},
- {"GetThemeMetric", (PyCFunction)App_GetThemeMetric, 1,
- PyDoc_STR("(ThemeMetric inMetric) -> (SInt32 outMetric)")},
- {NULL, NULL, 0}
+ {"RegisterAppearanceClient", (PyCFunction)App_RegisterAppearanceClient, 1,
+ PyDoc_STR("() -> None")},
+ {"UnregisterAppearanceClient", (PyCFunction)App_UnregisterAppearanceClient, 1,
+ PyDoc_STR("() -> None")},
+ {"SetThemePen", (PyCFunction)App_SetThemePen, 1,
+ PyDoc_STR("(ThemeBrush inBrush, SInt16 inDepth, Boolean inIsColorDevice) -> None")},
+ {"SetThemeBackground", (PyCFunction)App_SetThemeBackground, 1,
+ PyDoc_STR("(ThemeBrush inBrush, SInt16 inDepth, Boolean inIsColorDevice) -> None")},
+ {"SetThemeTextColor", (PyCFunction)App_SetThemeTextColor, 1,
+ PyDoc_STR("(ThemeTextColor inColor, SInt16 inDepth, Boolean inIsColorDevice) -> None")},
+ {"SetThemeWindowBackground", (PyCFunction)App_SetThemeWindowBackground, 1,
+ PyDoc_STR("(WindowPtr inWindow, ThemeBrush inBrush, Boolean inUpdate) -> None")},
+ {"DrawThemeWindowHeader", (PyCFunction)App_DrawThemeWindowHeader, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeWindowListViewHeader", (PyCFunction)App_DrawThemeWindowListViewHeader, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemePlacard", (PyCFunction)App_DrawThemePlacard, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeEditTextFrame", (PyCFunction)App_DrawThemeEditTextFrame, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeListBoxFrame", (PyCFunction)App_DrawThemeListBoxFrame, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeFocusRect", (PyCFunction)App_DrawThemeFocusRect, 1,
+ PyDoc_STR("(Rect inRect, Boolean inHasFocus) -> None")},
+ {"DrawThemePrimaryGroup", (PyCFunction)App_DrawThemePrimaryGroup, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeSecondaryGroup", (PyCFunction)App_DrawThemeSecondaryGroup, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeSeparator", (PyCFunction)App_DrawThemeSeparator, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeModelessDialogFrame", (PyCFunction)App_DrawThemeModelessDialogFrame, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"DrawThemeGenericWell", (PyCFunction)App_DrawThemeGenericWell, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState, Boolean inFillCenter) -> None")},
+ {"DrawThemeFocusRegion", (PyCFunction)App_DrawThemeFocusRegion, 1,
+ PyDoc_STR("(Boolean inHasFocus) -> None")},
+ {"IsThemeInColor", (PyCFunction)App_IsThemeInColor, 1,
+ PyDoc_STR("(SInt16 inDepth, Boolean inIsColorDevice) -> (Boolean _rv)")},
+ {"GetThemeAccentColors", (PyCFunction)App_GetThemeAccentColors, 1,
+ PyDoc_STR("() -> (CTabHandle outColors)")},
+ {"DrawThemeMenuBarBackground", (PyCFunction)App_DrawThemeMenuBarBackground, 1,
+ PyDoc_STR("(Rect inBounds, ThemeMenuBarState inState, UInt32 inAttributes) -> None")},
+ {"GetThemeMenuBarHeight", (PyCFunction)App_GetThemeMenuBarHeight, 1,
+ PyDoc_STR("() -> (SInt16 outHeight)")},
+ {"DrawThemeMenuBackground", (PyCFunction)App_DrawThemeMenuBackground, 1,
+ PyDoc_STR("(Rect inMenuRect, ThemeMenuType inMenuType) -> None")},
+ {"GetThemeMenuBackgroundRegion", (PyCFunction)App_GetThemeMenuBackgroundRegion, 1,
+ PyDoc_STR("(Rect inMenuRect, ThemeMenuType menuType) -> None")},
+ {"DrawThemeMenuSeparator", (PyCFunction)App_DrawThemeMenuSeparator, 1,
+ PyDoc_STR("(Rect inItemRect) -> None")},
+ {"GetThemeMenuSeparatorHeight", (PyCFunction)App_GetThemeMenuSeparatorHeight, 1,
+ PyDoc_STR("() -> (SInt16 outHeight)")},
+ {"GetThemeMenuItemExtra", (PyCFunction)App_GetThemeMenuItemExtra, 1,
+ PyDoc_STR("(ThemeMenuItemType inItemType) -> (SInt16 outHeight, SInt16 outWidth)")},
+ {"GetThemeMenuTitleExtra", (PyCFunction)App_GetThemeMenuTitleExtra, 1,
+ PyDoc_STR("(Boolean inIsSquished) -> (SInt16 outWidth)")},
+ {"DrawThemeTabPane", (PyCFunction)App_DrawThemeTabPane, 1,
+ PyDoc_STR("(Rect inRect, ThemeDrawState inState) -> None")},
+ {"GetThemeTabRegion", (PyCFunction)App_GetThemeTabRegion, 1,
+ PyDoc_STR("(Rect inRect, ThemeTabStyle inStyle, ThemeTabDirection inDirection) -> None")},
+ {"SetThemeCursor", (PyCFunction)App_SetThemeCursor, 1,
+ PyDoc_STR("(ThemeCursor inCursor) -> None")},
+ {"SetAnimatedThemeCursor", (PyCFunction)App_SetAnimatedThemeCursor, 1,
+ PyDoc_STR("(ThemeCursor inCursor, UInt32 inAnimationStep) -> None")},
+ {"GetThemeScrollBarThumbStyle", (PyCFunction)App_GetThemeScrollBarThumbStyle, 1,
+ PyDoc_STR("() -> (ThemeScrollBarThumbStyle outStyle)")},
+ {"GetThemeScrollBarArrowStyle", (PyCFunction)App_GetThemeScrollBarArrowStyle, 1,
+ PyDoc_STR("() -> (ThemeScrollBarArrowStyle outStyle)")},
+ {"GetThemeCheckBoxStyle", (PyCFunction)App_GetThemeCheckBoxStyle, 1,
+ PyDoc_STR("() -> (ThemeCheckBoxStyle outStyle)")},
+ {"UseThemeFont", (PyCFunction)App_UseThemeFont, 1,
+ PyDoc_STR("(ThemeFontID inFontID, ScriptCode inScript) -> None")},
+ {"DrawThemeTextBox", (PyCFunction)App_DrawThemeTextBox, 1,
+ PyDoc_STR("(CFStringRef inString, ThemeFontID inFontID, ThemeDrawState inState, Boolean inWrapToWidth, Rect inBoundingBox, SInt16 inJust) -> None")},
+ {"TruncateThemeText", (PyCFunction)App_TruncateThemeText, 1,
+ PyDoc_STR("(CFMutableStringRef inString, ThemeFontID inFontID, ThemeDrawState inState, SInt16 inPixelWidthLimit, TruncCode inTruncWhere) -> (Boolean outTruncated)")},
+ {"GetThemeTextDimensions", (PyCFunction)App_GetThemeTextDimensions, 1,
+ PyDoc_STR("(CFStringRef inString, ThemeFontID inFontID, ThemeDrawState inState, Boolean inWrapToWidth, Point ioBounds) -> (Point ioBounds, SInt16 outBaseline)")},
+ {"GetThemeTextShadowOutset", (PyCFunction)App_GetThemeTextShadowOutset, 1,
+ PyDoc_STR("(ThemeFontID inFontID, ThemeDrawState inState) -> (Rect outOutset)")},
+ {"DrawThemeScrollBarArrows", (PyCFunction)App_DrawThemeScrollBarArrows, 1,
+ PyDoc_STR("(Rect bounds, ThemeTrackEnableState enableState, ThemeTrackPressState pressState, Boolean isHoriz) -> (Rect trackBounds)")},
+ {"GetThemeScrollBarTrackRect", (PyCFunction)App_GetThemeScrollBarTrackRect, 1,
+ PyDoc_STR("(Rect bounds, ThemeTrackEnableState enableState, ThemeTrackPressState pressState, Boolean isHoriz) -> (Rect trackBounds)")},
+ {"HitTestThemeScrollBarArrows", (PyCFunction)App_HitTestThemeScrollBarArrows, 1,
+ PyDoc_STR("(Rect scrollBarBounds, ThemeTrackEnableState enableState, ThemeTrackPressState pressState, Boolean isHoriz, Point ptHit) -> (Boolean _rv, Rect trackBounds, ControlPartCode partcode)")},
+ {"DrawThemeScrollBarDelimiters", (PyCFunction)App_DrawThemeScrollBarDelimiters, 1,
+ PyDoc_STR("(ThemeWindowType flavor, Rect inContRect, ThemeDrawState state, ThemeWindowAttributes attributes) -> None")},
+ {"DrawThemeButton", (PyCFunction)App_DrawThemeButton, 1,
+ PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inNewInfo, ThemeButtonDrawInfo inPrevInfo, UInt32 inUserData) -> None")},
+ {"GetThemeButtonRegion", (PyCFunction)App_GetThemeButtonRegion, 1,
+ PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inNewInfo) -> None")},
+ {"GetThemeButtonContentBounds", (PyCFunction)App_GetThemeButtonContentBounds, 1,
+ PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inDrawInfo) -> (Rect outBounds)")},
+ {"GetThemeButtonBackgroundBounds", (PyCFunction)App_GetThemeButtonBackgroundBounds, 1,
+ PyDoc_STR("(Rect inBounds, UInt16 inKind, ThemeButtonDrawInfo inDrawInfo) -> (Rect outBounds)")},
+ {"PlayThemeSound", (PyCFunction)App_PlayThemeSound, 1,
+ PyDoc_STR("(ThemeSoundKind kind) -> None")},
+ {"BeginThemeDragSound", (PyCFunction)App_BeginThemeDragSound, 1,
+ PyDoc_STR("(ThemeDragSoundKind kind) -> None")},
+ {"EndThemeDragSound", (PyCFunction)App_EndThemeDragSound, 1,
+ PyDoc_STR("() -> None")},
+ {"DrawThemeTickMark", (PyCFunction)App_DrawThemeTickMark, 1,
+ PyDoc_STR("(Rect bounds, ThemeDrawState state) -> None")},
+ {"DrawThemeChasingArrows", (PyCFunction)App_DrawThemeChasingArrows, 1,
+ PyDoc_STR("(Rect bounds, UInt32 index, ThemeDrawState state, UInt32 eraseData) -> None")},
+ {"DrawThemePopupArrow", (PyCFunction)App_DrawThemePopupArrow, 1,
+ PyDoc_STR("(Rect bounds, ThemeArrowOrientation orientation, ThemePopupArrowSize size, ThemeDrawState state, UInt32 eraseData) -> None")},
+ {"DrawThemeStandaloneGrowBox", (PyCFunction)App_DrawThemeStandaloneGrowBox, 1,
+ PyDoc_STR("(Point origin, ThemeGrowDirection growDirection, Boolean isSmall, ThemeDrawState state) -> None")},
+ {"DrawThemeStandaloneNoGrowBox", (PyCFunction)App_DrawThemeStandaloneNoGrowBox, 1,
+ PyDoc_STR("(Point origin, ThemeGrowDirection growDirection, Boolean isSmall, ThemeDrawState state) -> None")},
+ {"GetThemeStandaloneGrowBoxBounds", (PyCFunction)App_GetThemeStandaloneGrowBoxBounds, 1,
+ PyDoc_STR("(Point origin, ThemeGrowDirection growDirection, Boolean isSmall) -> (Rect bounds)")},
+ {"NormalizeThemeDrawingState", (PyCFunction)App_NormalizeThemeDrawingState, 1,
+ PyDoc_STR("() -> None")},
+ {"GetThemeDrawingState", (PyCFunction)App_GetThemeDrawingState, 1,
+ PyDoc_STR("() -> (ThemeDrawingState outState)")},
+ {"ApplyThemeBackground", (PyCFunction)App_ApplyThemeBackground, 1,
+ PyDoc_STR("(ThemeBackgroundKind inKind, Rect bounds, ThemeDrawState inState, SInt16 inDepth, Boolean inColorDev) -> None")},
+ {"SetThemeTextColorForWindow", (PyCFunction)App_SetThemeTextColorForWindow, 1,
+ PyDoc_STR("(WindowPtr window, Boolean isActive, SInt16 depth, Boolean isColorDev) -> None")},
+ {"IsValidAppearanceFileType", (PyCFunction)App_IsValidAppearanceFileType, 1,
+ PyDoc_STR("(OSType fileType) -> (Boolean _rv)")},
+ {"GetThemeBrushAsColor", (PyCFunction)App_GetThemeBrushAsColor, 1,
+ PyDoc_STR("(ThemeBrush inBrush, SInt16 inDepth, Boolean inColorDev) -> (RGBColor outColor)")},
+ {"GetThemeTextColor", (PyCFunction)App_GetThemeTextColor, 1,
+ PyDoc_STR("(ThemeTextColor inColor, SInt16 inDepth, Boolean inColorDev) -> (RGBColor outColor)")},
+ {"GetThemeMetric", (PyCFunction)App_GetThemeMetric, 1,
+ PyDoc_STR("(ThemeMetric inMetric) -> (SInt32 outMetric)")},
+ {NULL, NULL, 0}
};
-#else /* __LP64__ */
+#else /* __LP64__ */
static PyMethodDef App_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#endif /* __LP64__ */
@@ -1805,26 +1805,26 @@ static PyMethodDef App_methods[] = {
void init_App(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
#endif /* !__LP64__ */
- m = Py_InitModule("_App", App_methods);
+ m = Py_InitModule("_App", App_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- App_Error = PyMac_GetOSErrException();
- if (App_Error == NULL ||
- PyDict_SetItemString(d, "Error", App_Error) != 0)
- return;
- ThemeDrawingState_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&ThemeDrawingState_Type) < 0) return;
- Py_INCREF(&ThemeDrawingState_Type);
- PyModule_AddObject(m, "ThemeDrawingState", (PyObject *)&ThemeDrawingState_Type);
- /* Backward-compatible name */
- Py_INCREF(&ThemeDrawingState_Type);
- PyModule_AddObject(m, "ThemeDrawingStateType", (PyObject *)&ThemeDrawingState_Type);
+ d = PyModule_GetDict(m);
+ App_Error = PyMac_GetOSErrException();
+ if (App_Error == NULL ||
+ PyDict_SetItemString(d, "Error", App_Error) != 0)
+ return;
+ ThemeDrawingState_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&ThemeDrawingState_Type) < 0) return;
+ Py_INCREF(&ThemeDrawingState_Type);
+ PyModule_AddObject(m, "ThemeDrawingState", (PyObject *)&ThemeDrawingState_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&ThemeDrawingState_Type);
+ PyModule_AddObject(m, "ThemeDrawingStateType", (PyObject *)&ThemeDrawingState_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/autoGIL.c b/Mac/Modules/autoGIL.c
index af2e699..3bc1593 100644
--- a/Mac/Modules/autoGIL.c
+++ b/Mac/Modules/autoGIL.c
@@ -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;
-
- 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;
- }
-
- 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? */
-
- /* 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;
+ 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;
+ }
+
+ 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;
+
+ 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;
+
+ 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;
-
- 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;
+ PyObject *mod;
+
+ 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;
}
diff --git a/Mac/Modules/carbonevt/_CarbonEvtmodule.c b/Mac/Modules/carbonevt/_CarbonEvtmodule.c
index 893beec..623a3e5 100755
--- a/Mac/Modules/carbonevt/_CarbonEvtmodule.c
+++ b/Mac/Modules/carbonevt/_CarbonEvtmodule.c
@@ -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)
@@ -30,11 +30,11 @@ PyObject *EventRef_New(EventRef itself);
static int
EventTypeSpec_Convert(PyObject *v, EventTypeSpec *out)
{
- if (PyArg_Parse(v, "(O&l)",
- PyMac_GetOSType, &(out->eventClass),
- &(out->eventKind)))
- return 1;
- return 0;
+ if (PyArg_Parse(v, "(O&l)",
+ PyMac_GetOSType, &(out->eventClass),
+ &(out->eventKind)))
+ return 1;
+ return 0;
}
/********** end EventTypeSpec *******/
@@ -45,15 +45,15 @@ EventTypeSpec_Convert(PyObject *v, EventTypeSpec *out)
static PyObject*
HIPoint_New(HIPoint *in)
{
- return Py_BuildValue("ff", in->x, in->y);
+ return Py_BuildValue("ff", in->x, in->y);
}
static int
HIPoint_Convert(PyObject *v, HIPoint *out)
{
- if (PyArg_ParseTuple(v, "ff", &(out->x), &(out->y)))
- return 1;
- return NULL;
+ if (PyArg_ParseTuple(v, "ff", &(out->x), &(out->y)))
+ return 1;
+ return NULL;
}
#endif
@@ -64,9 +64,9 @@ HIPoint_Convert(PyObject *v, HIPoint *out)
static int
EventHotKeyID_Convert(PyObject *v, EventHotKeyID *out)
{
- if (PyArg_ParseTuple(v, "ll", &out->signature, &out->id))
- return 1;
- return 0;
+ if (PyArg_ParseTuple(v, "ll", &out->signature, &out->id))
+ return 1;
+ return 0;
}
/********** end EventHotKeyID *******/
@@ -77,27 +77,27 @@ static EventHandlerUPP myEventHandlerUPP;
static pascal OSStatus
myEventHandler(EventHandlerCallRef handlerRef, EventRef event, void *outPyObject) {
- PyObject *retValue;
- int status;
-
- retValue = PyObject_CallFunction((PyObject *)outPyObject, "O&O&",
- EventHandlerCallRef_New, handlerRef,
- EventRef_New, event);
- if (retValue == NULL) {
- PySys_WriteStderr("Error in event handler callback:\n");
- PyErr_Print(); /* this also clears the error */
- status = noErr; /* complain? how? */
- } else {
- if (retValue == Py_None)
- status = noErr;
- else if (PyInt_Check(retValue)) {
- status = PyInt_AsLong(retValue);
- } else
- status = noErr; /* wrong object type, complain? */
- Py_DECREF(retValue);
- }
-
- return status;
+ PyObject *retValue;
+ int status;
+
+ retValue = PyObject_CallFunction((PyObject *)outPyObject, "O&O&",
+ EventHandlerCallRef_New, handlerRef,
+ EventRef_New, event);
+ if (retValue == NULL) {
+ PySys_WriteStderr("Error in event handler callback:\n");
+ PyErr_Print(); /* this also clears the error */
+ status = noErr; /* complain? how? */
+ } else {
+ if (retValue == Py_None)
+ status = noErr;
+ else if (PyInt_Check(retValue)) {
+ status = PyInt_AsLong(retValue);
+ } else
+ status = noErr; /* wrong object type, complain? */
+ Py_DECREF(retValue);
+ }
+
+ return status;
}
/******** end myEventHandler ***********/
@@ -112,268 +112,268 @@ PyTypeObject EventRef_Type;
#define EventRef_Check(x) ((x)->ob_type == &EventRef_Type || PyObject_TypeCheck((x), &EventRef_Type))
typedef struct EventRefObject {
- PyObject_HEAD
- EventRef ob_itself;
+ PyObject_HEAD
+ EventRef ob_itself;
} EventRefObject;
PyObject *EventRef_New(EventRef itself)
{
- EventRefObject *it;
- it = PyObject_NEW(EventRefObject, &EventRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventRefObject *it;
+ it = PyObject_NEW(EventRefObject, &EventRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventRef_Convert(PyObject *v, EventRef *p_itself)
{
- if (!EventRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventRef required");
- return 0;
- }
- *p_itself = ((EventRefObject *)v)->ob_itself;
- return 1;
+ if (!EventRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventRef required");
+ return 0;
+ }
+ *p_itself = ((EventRefObject *)v)->ob_itself;
+ return 1;
}
static void EventRef_dealloc(EventRefObject *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 *EventRef_RetainEvent(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = RetainEvent(_self->ob_itself);
- _res = Py_BuildValue("O&",
- EventRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = RetainEvent(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ EventRef_New, _rv);
+ return _res;
}
static PyObject *EventRef_GetEventRetainCount(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetEventRetainCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetEventRetainCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *EventRef_ReleaseEvent(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ReleaseEvent(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ReleaseEvent(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventRef_SetEventParameter(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType inName;
- OSType inType;
- char *inDataPtr__in__;
- long inDataPtr__len__;
- int inDataPtr__in_len__;
- if (!PyArg_ParseTuple(_args, "O&O&s#",
- PyMac_GetOSType, &inName,
- PyMac_GetOSType, &inType,
- &inDataPtr__in__, &inDataPtr__in_len__))
- return NULL;
- inDataPtr__len__ = inDataPtr__in_len__;
- _err = SetEventParameter(_self->ob_itself,
- inName,
- inType,
- inDataPtr__len__, inDataPtr__in__);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType inName;
+ OSType inType;
+ char *inDataPtr__in__;
+ long inDataPtr__len__;
+ int inDataPtr__in_len__;
+ if (!PyArg_ParseTuple(_args, "O&O&s#",
+ PyMac_GetOSType, &inName,
+ PyMac_GetOSType, &inType,
+ &inDataPtr__in__, &inDataPtr__in_len__))
+ return NULL;
+ inDataPtr__len__ = inDataPtr__in_len__;
+ _err = SetEventParameter(_self->ob_itself,
+ inName,
+ inType,
+ inDataPtr__len__, inDataPtr__in__);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventRef_GetEventClass(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetEventClass(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetEventClass(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *EventRef_GetEventKind(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetEventKind(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetEventKind(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *EventRef_GetEventTime(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- double _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetEventTime(_self->ob_itself);
- _res = Py_BuildValue("d",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ double _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetEventTime(_self->ob_itself);
+ _res = Py_BuildValue("d",
+ _rv);
+ return _res;
}
static PyObject *EventRef_SetEventTime(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- double inTime;
- if (!PyArg_ParseTuple(_args, "d",
- &inTime))
- return NULL;
- _err = SetEventTime(_self->ob_itself,
- inTime);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ double inTime;
+ if (!PyArg_ParseTuple(_args, "d",
+ &inTime))
+ return NULL;
+ _err = SetEventTime(_self->ob_itself,
+ inTime);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventRef_IsUserCancelEventRef(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsUserCancelEventRef(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsUserCancelEventRef(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *EventRef_ConvertEventRefToEventRecord(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord outEvent;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = ConvertEventRefToEventRecord(_self->ob_itself,
- &outEvent);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildEventRecord, &outEvent);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord outEvent;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = ConvertEventRefToEventRecord(_self->ob_itself,
+ &outEvent);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildEventRecord, &outEvent);
+ return _res;
}
static PyObject *EventRef_IsEventInMask(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- UInt16 inMask;
- if (!PyArg_ParseTuple(_args, "H",
- &inMask))
- return NULL;
- _rv = IsEventInMask(_self->ob_itself,
- inMask);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ UInt16 inMask;
+ if (!PyArg_ParseTuple(_args, "H",
+ &inMask))
+ return NULL;
+ _rv = IsEventInMask(_self->ob_itself,
+ inMask);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *EventRef_SendEventToEventTarget(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- EventTargetRef inTarget;
- if (!PyArg_ParseTuple(_args, "O&",
- EventTargetRef_Convert, &inTarget))
- return NULL;
- _err = SendEventToEventTarget(_self->ob_itself,
- inTarget);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ EventTargetRef inTarget;
+ if (!PyArg_ParseTuple(_args, "O&",
+ EventTargetRef_Convert, &inTarget))
+ return NULL;
+ _err = SendEventToEventTarget(_self->ob_itself,
+ inTarget);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventRef_GetEventParameter(EventRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- UInt32 bufferSize;
- EventParamName inName;
- EventParamType inType;
- OSErr _err;
- void * buffer;
+ UInt32 bufferSize;
+ EventParamName inName;
+ EventParamType inType;
+ OSErr _err;
+ void * buffer;
- if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &inName, PyMac_GetOSType, &inType))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "O&O&", PyMac_GetOSType, &inName, PyMac_GetOSType, &inType))
+ return NULL;
- /* Figure out the size by passing a null buffer to GetEventParameter */
- _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, 0, &bufferSize, NULL);
+ /* Figure out the size by passing a null buffer to GetEventParameter */
+ _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, 0, &bufferSize, NULL);
- if (_err != noErr)
- return PyMac_Error(_err);
- buffer = PyMem_NEW(char, bufferSize);
- if (buffer == NULL)
- return PyErr_NoMemory();
+ if (_err != noErr)
+ return PyMac_Error(_err);
+ buffer = PyMem_NEW(char, bufferSize);
+ if (buffer == NULL)
+ return PyErr_NoMemory();
- _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, bufferSize, NULL, buffer);
+ _err = GetEventParameter(_self->ob_itself, inName, inType, NULL, bufferSize, NULL, buffer);
- if (_err != noErr) {
- PyMem_DEL(buffer);
- return PyMac_Error(_err);
- }
- _res = Py_BuildValue("s#", buffer, bufferSize);
- PyMem_DEL(buffer);
- return _res;
+ if (_err != noErr) {
+ PyMem_DEL(buffer);
+ return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("s#", buffer, bufferSize);
+ PyMem_DEL(buffer);
+ return _res;
}
static PyMethodDef EventRef_methods[] = {
- {"RetainEvent", (PyCFunction)EventRef_RetainEvent, 1,
- PyDoc_STR("() -> (EventRef _rv)")},
- {"GetEventRetainCount", (PyCFunction)EventRef_GetEventRetainCount, 1,
- PyDoc_STR("() -> (UInt32 _rv)")},
- {"ReleaseEvent", (PyCFunction)EventRef_ReleaseEvent, 1,
- PyDoc_STR("() -> None")},
- {"SetEventParameter", (PyCFunction)EventRef_SetEventParameter, 1,
- PyDoc_STR("(OSType inName, OSType inType, Buffer inDataPtr) -> None")},
- {"GetEventClass", (PyCFunction)EventRef_GetEventClass, 1,
- PyDoc_STR("() -> (UInt32 _rv)")},
- {"GetEventKind", (PyCFunction)EventRef_GetEventKind, 1,
- PyDoc_STR("() -> (UInt32 _rv)")},
- {"GetEventTime", (PyCFunction)EventRef_GetEventTime, 1,
- PyDoc_STR("() -> (double _rv)")},
- {"SetEventTime", (PyCFunction)EventRef_SetEventTime, 1,
- PyDoc_STR("(double inTime) -> None")},
- {"IsUserCancelEventRef", (PyCFunction)EventRef_IsUserCancelEventRef, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"ConvertEventRefToEventRecord", (PyCFunction)EventRef_ConvertEventRefToEventRecord, 1,
- PyDoc_STR("() -> (Boolean _rv, EventRecord outEvent)")},
- {"IsEventInMask", (PyCFunction)EventRef_IsEventInMask, 1,
- PyDoc_STR("(UInt16 inMask) -> (Boolean _rv)")},
- {"SendEventToEventTarget", (PyCFunction)EventRef_SendEventToEventTarget, 1,
- PyDoc_STR("(EventTargetRef inTarget) -> None")},
- {"GetEventParameter", (PyCFunction)EventRef_GetEventParameter, 1,
- PyDoc_STR("(EventParamName eventName, EventParamType eventType) -> (String eventParamData)")},
- {NULL, NULL, 0}
+ {"RetainEvent", (PyCFunction)EventRef_RetainEvent, 1,
+ PyDoc_STR("() -> (EventRef _rv)")},
+ {"GetEventRetainCount", (PyCFunction)EventRef_GetEventRetainCount, 1,
+ PyDoc_STR("() -> (UInt32 _rv)")},
+ {"ReleaseEvent", (PyCFunction)EventRef_ReleaseEvent, 1,
+ PyDoc_STR("() -> None")},
+ {"SetEventParameter", (PyCFunction)EventRef_SetEventParameter, 1,
+ PyDoc_STR("(OSType inName, OSType inType, Buffer inDataPtr) -> None")},
+ {"GetEventClass", (PyCFunction)EventRef_GetEventClass, 1,
+ PyDoc_STR("() -> (UInt32 _rv)")},
+ {"GetEventKind", (PyCFunction)EventRef_GetEventKind, 1,
+ PyDoc_STR("() -> (UInt32 _rv)")},
+ {"GetEventTime", (PyCFunction)EventRef_GetEventTime, 1,
+ PyDoc_STR("() -> (double _rv)")},
+ {"SetEventTime", (PyCFunction)EventRef_SetEventTime, 1,
+ PyDoc_STR("(double inTime) -> None")},
+ {"IsUserCancelEventRef", (PyCFunction)EventRef_IsUserCancelEventRef, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"ConvertEventRefToEventRecord", (PyCFunction)EventRef_ConvertEventRefToEventRecord, 1,
+ PyDoc_STR("() -> (Boolean _rv, EventRecord outEvent)")},
+ {"IsEventInMask", (PyCFunction)EventRef_IsEventInMask, 1,
+ PyDoc_STR("(UInt16 inMask) -> (Boolean _rv)")},
+ {"SendEventToEventTarget", (PyCFunction)EventRef_SendEventToEventTarget, 1,
+ PyDoc_STR("(EventTargetRef inTarget) -> None")},
+ {"GetEventParameter", (PyCFunction)EventRef_GetEventParameter, 1,
+ PyDoc_STR("(EventParamName eventName, EventParamType eventType) -> (String eventParamData)")},
+ {NULL, NULL, 0}
};
#define EventRef_getsetlist NULL
@@ -390,61 +390,61 @@ static PyMethodDef EventRef_methods[] = {
static PyObject *EventRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventRef_tp_free PyObject_Del
PyTypeObject EventRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventRef", /*tp_name*/
- sizeof(EventRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventRef_compare, /*tp_compare*/
- (reprfunc) EventRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventRef_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*/
- EventRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventRef_tp_init, /* tp_init */
- EventRef_tp_alloc, /* tp_alloc */
- EventRef_tp_new, /* tp_new */
- EventRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventRef", /*tp_name*/
+ sizeof(EventRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventRef_compare, /*tp_compare*/
+ (reprfunc) EventRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventRef_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*/
+ EventRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventRef_tp_init, /* tp_init */
+ EventRef_tp_alloc, /* tp_alloc */
+ EventRef_tp_new, /* tp_new */
+ EventRef_tp_free, /* tp_free */
};
/* -------------------- End object type EventRef -------------------- */
@@ -457,144 +457,144 @@ PyTypeObject EventQueueRef_Type;
#define EventQueueRef_Check(x) ((x)->ob_type == &EventQueueRef_Type || PyObject_TypeCheck((x), &EventQueueRef_Type))
typedef struct EventQueueRefObject {
- PyObject_HEAD
- EventQueueRef ob_itself;
+ PyObject_HEAD
+ EventQueueRef ob_itself;
} EventQueueRefObject;
PyObject *EventQueueRef_New(EventQueueRef itself)
{
- EventQueueRefObject *it;
- it = PyObject_NEW(EventQueueRefObject, &EventQueueRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventQueueRefObject *it;
+ it = PyObject_NEW(EventQueueRefObject, &EventQueueRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventQueueRef_Convert(PyObject *v, EventQueueRef *p_itself)
{
- if (!EventQueueRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventQueueRef required");
- return 0;
- }
- *p_itself = ((EventQueueRefObject *)v)->ob_itself;
- return 1;
+ if (!EventQueueRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventQueueRef required");
+ return 0;
+ }
+ *p_itself = ((EventQueueRefObject *)v)->ob_itself;
+ return 1;
}
static void EventQueueRef_dealloc(EventQueueRefObject *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 *EventQueueRef_PostEventToQueue(EventQueueRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- EventRef inEvent;
- SInt16 inPriority;
- if (!PyArg_ParseTuple(_args, "O&h",
- EventRef_Convert, &inEvent,
- &inPriority))
- return NULL;
- _err = PostEventToQueue(_self->ob_itself,
- inEvent,
- inPriority);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ EventRef inEvent;
+ SInt16 inPriority;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ EventRef_Convert, &inEvent,
+ &inPriority))
+ return NULL;
+ _err = PostEventToQueue(_self->ob_itself,
+ inEvent,
+ inPriority);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventQueueRef_FlushEventsMatchingListFromQueue(EventQueueRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 inNumTypes;
- EventTypeSpec inList;
- if (!PyArg_ParseTuple(_args, "lO&",
- &inNumTypes,
- EventTypeSpec_Convert, &inList))
- return NULL;
- _err = FlushEventsMatchingListFromQueue(_self->ob_itself,
- inNumTypes,
- &inList);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 inNumTypes;
+ EventTypeSpec inList;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &inNumTypes,
+ EventTypeSpec_Convert, &inList))
+ return NULL;
+ _err = FlushEventsMatchingListFromQueue(_self->ob_itself,
+ inNumTypes,
+ &inList);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventQueueRef_FlushEventQueue(EventQueueRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FlushEventQueue(_self->ob_itself);
- 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 = FlushEventQueue(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventQueueRef_GetNumEventsInQueue(EventQueueRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetNumEventsInQueue(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetNumEventsInQueue(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *EventQueueRef_RemoveEventFromQueue(EventQueueRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- EventRef inEvent;
- if (!PyArg_ParseTuple(_args, "O&",
- EventRef_Convert, &inEvent))
- return NULL;
- _err = RemoveEventFromQueue(_self->ob_itself,
- inEvent);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ EventRef inEvent;
+ if (!PyArg_ParseTuple(_args, "O&",
+ EventRef_Convert, &inEvent))
+ return NULL;
+ _err = RemoveEventFromQueue(_self->ob_itself,
+ inEvent);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventQueueRef_IsEventInQueue(EventQueueRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRef inEvent;
- if (!PyArg_ParseTuple(_args, "O&",
- EventRef_Convert, &inEvent))
- return NULL;
- _rv = IsEventInQueue(_self->ob_itself,
- inEvent);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRef inEvent;
+ if (!PyArg_ParseTuple(_args, "O&",
+ EventRef_Convert, &inEvent))
+ return NULL;
+ _rv = IsEventInQueue(_self->ob_itself,
+ inEvent);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyMethodDef EventQueueRef_methods[] = {
- {"PostEventToQueue", (PyCFunction)EventQueueRef_PostEventToQueue, 1,
- PyDoc_STR("(EventRef inEvent, SInt16 inPriority) -> None")},
- {"FlushEventsMatchingListFromQueue", (PyCFunction)EventQueueRef_FlushEventsMatchingListFromQueue, 1,
- PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList) -> None")},
- {"FlushEventQueue", (PyCFunction)EventQueueRef_FlushEventQueue, 1,
- PyDoc_STR("() -> None")},
- {"GetNumEventsInQueue", (PyCFunction)EventQueueRef_GetNumEventsInQueue, 1,
- PyDoc_STR("() -> (UInt32 _rv)")},
- {"RemoveEventFromQueue", (PyCFunction)EventQueueRef_RemoveEventFromQueue, 1,
- PyDoc_STR("(EventRef inEvent) -> None")},
- {"IsEventInQueue", (PyCFunction)EventQueueRef_IsEventInQueue, 1,
- PyDoc_STR("(EventRef inEvent) -> (Boolean _rv)")},
- {NULL, NULL, 0}
+ {"PostEventToQueue", (PyCFunction)EventQueueRef_PostEventToQueue, 1,
+ PyDoc_STR("(EventRef inEvent, SInt16 inPriority) -> None")},
+ {"FlushEventsMatchingListFromQueue", (PyCFunction)EventQueueRef_FlushEventsMatchingListFromQueue, 1,
+ PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList) -> None")},
+ {"FlushEventQueue", (PyCFunction)EventQueueRef_FlushEventQueue, 1,
+ PyDoc_STR("() -> None")},
+ {"GetNumEventsInQueue", (PyCFunction)EventQueueRef_GetNumEventsInQueue, 1,
+ PyDoc_STR("() -> (UInt32 _rv)")},
+ {"RemoveEventFromQueue", (PyCFunction)EventQueueRef_RemoveEventFromQueue, 1,
+ PyDoc_STR("(EventRef inEvent) -> None")},
+ {"IsEventInQueue", (PyCFunction)EventQueueRef_IsEventInQueue, 1,
+ PyDoc_STR("(EventRef inEvent) -> (Boolean _rv)")},
+ {NULL, NULL, 0}
};
#define EventQueueRef_getsetlist NULL
@@ -611,61 +611,61 @@ static PyMethodDef EventQueueRef_methods[] = {
static PyObject *EventQueueRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventQueueRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventQueueRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventQueueRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventQueueRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventQueueRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventQueueRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventQueueRef_tp_free PyObject_Del
PyTypeObject EventQueueRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventQueueRef", /*tp_name*/
- sizeof(EventQueueRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventQueueRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventQueueRef_compare, /*tp_compare*/
- (reprfunc) EventQueueRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventQueueRef_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*/
- EventQueueRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventQueueRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventQueueRef_tp_init, /* tp_init */
- EventQueueRef_tp_alloc, /* tp_alloc */
- EventQueueRef_tp_new, /* tp_new */
- EventQueueRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventQueueRef", /*tp_name*/
+ sizeof(EventQueueRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventQueueRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventQueueRef_compare, /*tp_compare*/
+ (reprfunc) EventQueueRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventQueueRef_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*/
+ EventQueueRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventQueueRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventQueueRef_tp_init, /* tp_init */
+ EventQueueRef_tp_alloc, /* tp_alloc */
+ EventQueueRef_tp_new, /* tp_new */
+ EventQueueRef_tp_free, /* tp_free */
};
/* ----------------- End object type EventQueueRef ------------------ */
@@ -678,53 +678,53 @@ PyTypeObject EventLoopRef_Type;
#define EventLoopRef_Check(x) ((x)->ob_type == &EventLoopRef_Type || PyObject_TypeCheck((x), &EventLoopRef_Type))
typedef struct EventLoopRefObject {
- PyObject_HEAD
- EventLoopRef ob_itself;
+ PyObject_HEAD
+ EventLoopRef ob_itself;
} EventLoopRefObject;
PyObject *EventLoopRef_New(EventLoopRef itself)
{
- EventLoopRefObject *it;
- it = PyObject_NEW(EventLoopRefObject, &EventLoopRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventLoopRefObject *it;
+ it = PyObject_NEW(EventLoopRefObject, &EventLoopRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventLoopRef_Convert(PyObject *v, EventLoopRef *p_itself)
{
- if (!EventLoopRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventLoopRef required");
- return 0;
- }
- *p_itself = ((EventLoopRefObject *)v)->ob_itself;
- return 1;
+ if (!EventLoopRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventLoopRef required");
+ return 0;
+ }
+ *p_itself = ((EventLoopRefObject *)v)->ob_itself;
+ return 1;
}
static void EventLoopRef_dealloc(EventLoopRefObject *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 *EventLoopRef_QuitEventLoop(EventLoopRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = QuitEventLoop(_self->ob_itself);
- 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 = QuitEventLoop(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef EventLoopRef_methods[] = {
- {"QuitEventLoop", (PyCFunction)EventLoopRef_QuitEventLoop, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"QuitEventLoop", (PyCFunction)EventLoopRef_QuitEventLoop, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define EventLoopRef_getsetlist NULL
@@ -741,61 +741,61 @@ static PyMethodDef EventLoopRef_methods[] = {
static PyObject *EventLoopRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventLoopRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventLoopRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventLoopRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventLoopRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventLoopRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventLoopRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventLoopRef_tp_free PyObject_Del
PyTypeObject EventLoopRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventLoopRef", /*tp_name*/
- sizeof(EventLoopRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventLoopRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventLoopRef_compare, /*tp_compare*/
- (reprfunc) EventLoopRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventLoopRef_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*/
- EventLoopRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventLoopRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventLoopRef_tp_init, /* tp_init */
- EventLoopRef_tp_alloc, /* tp_alloc */
- EventLoopRef_tp_new, /* tp_new */
- EventLoopRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventLoopRef", /*tp_name*/
+ sizeof(EventLoopRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventLoopRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventLoopRef_compare, /*tp_compare*/
+ (reprfunc) EventLoopRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventLoopRef_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*/
+ EventLoopRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventLoopRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventLoopRef_tp_init, /* tp_init */
+ EventLoopRef_tp_alloc, /* tp_alloc */
+ EventLoopRef_tp_new, /* tp_new */
+ EventLoopRef_tp_free, /* tp_free */
};
/* ------------------ End object type EventLoopRef ------------------ */
@@ -808,71 +808,71 @@ PyTypeObject EventLoopTimerRef_Type;
#define EventLoopTimerRef_Check(x) ((x)->ob_type == &EventLoopTimerRef_Type || PyObject_TypeCheck((x), &EventLoopTimerRef_Type))
typedef struct EventLoopTimerRefObject {
- PyObject_HEAD
- EventLoopTimerRef ob_itself;
+ PyObject_HEAD
+ EventLoopTimerRef ob_itself;
} EventLoopTimerRefObject;
PyObject *EventLoopTimerRef_New(EventLoopTimerRef itself)
{
- EventLoopTimerRefObject *it;
- it = PyObject_NEW(EventLoopTimerRefObject, &EventLoopTimerRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventLoopTimerRefObject *it;
+ it = PyObject_NEW(EventLoopTimerRefObject, &EventLoopTimerRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventLoopTimerRef_Convert(PyObject *v, EventLoopTimerRef *p_itself)
{
- if (!EventLoopTimerRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventLoopTimerRef required");
- return 0;
- }
- *p_itself = ((EventLoopTimerRefObject *)v)->ob_itself;
- return 1;
+ if (!EventLoopTimerRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventLoopTimerRef required");
+ return 0;
+ }
+ *p_itself = ((EventLoopTimerRefObject *)v)->ob_itself;
+ return 1;
}
static void EventLoopTimerRef_dealloc(EventLoopTimerRefObject *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 *EventLoopTimerRef_RemoveEventLoopTimer(EventLoopTimerRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = RemoveEventLoopTimer(_self->ob_itself);
- 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 = RemoveEventLoopTimer(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventLoopTimerRef_SetEventLoopTimerNextFireTime(EventLoopTimerRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- double inNextFire;
- if (!PyArg_ParseTuple(_args, "d",
- &inNextFire))
- return NULL;
- _err = SetEventLoopTimerNextFireTime(_self->ob_itself,
- inNextFire);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ double inNextFire;
+ if (!PyArg_ParseTuple(_args, "d",
+ &inNextFire))
+ return NULL;
+ _err = SetEventLoopTimerNextFireTime(_self->ob_itself,
+ inNextFire);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef EventLoopTimerRef_methods[] = {
- {"RemoveEventLoopTimer", (PyCFunction)EventLoopTimerRef_RemoveEventLoopTimer, 1,
- PyDoc_STR("() -> None")},
- {"SetEventLoopTimerNextFireTime", (PyCFunction)EventLoopTimerRef_SetEventLoopTimerNextFireTime, 1,
- PyDoc_STR("(double inNextFire) -> None")},
- {NULL, NULL, 0}
+ {"RemoveEventLoopTimer", (PyCFunction)EventLoopTimerRef_RemoveEventLoopTimer, 1,
+ PyDoc_STR("() -> None")},
+ {"SetEventLoopTimerNextFireTime", (PyCFunction)EventLoopTimerRef_SetEventLoopTimerNextFireTime, 1,
+ PyDoc_STR("(double inNextFire) -> None")},
+ {NULL, NULL, 0}
};
#define EventLoopTimerRef_getsetlist NULL
@@ -889,61 +889,61 @@ static PyMethodDef EventLoopTimerRef_methods[] = {
static PyObject *EventLoopTimerRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventLoopTimerRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventLoopTimerRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventLoopTimerRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventLoopTimerRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventLoopTimerRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventLoopTimerRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventLoopTimerRef_tp_free PyObject_Del
PyTypeObject EventLoopTimerRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventLoopTimerRef", /*tp_name*/
- sizeof(EventLoopTimerRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventLoopTimerRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventLoopTimerRef_compare, /*tp_compare*/
- (reprfunc) EventLoopTimerRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventLoopTimerRef_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*/
- EventLoopTimerRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventLoopTimerRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventLoopTimerRef_tp_init, /* tp_init */
- EventLoopTimerRef_tp_alloc, /* tp_alloc */
- EventLoopTimerRef_tp_new, /* tp_new */
- EventLoopTimerRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventLoopTimerRef", /*tp_name*/
+ sizeof(EventLoopTimerRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventLoopTimerRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventLoopTimerRef_compare, /*tp_compare*/
+ (reprfunc) EventLoopTimerRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventLoopTimerRef_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*/
+ EventLoopTimerRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventLoopTimerRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventLoopTimerRef_tp_init, /* tp_init */
+ EventLoopTimerRef_tp_alloc, /* tp_alloc */
+ EventLoopTimerRef_tp_new, /* tp_new */
+ EventLoopTimerRef_tp_free, /* tp_free */
};
/* --------------- End object type EventLoopTimerRef ---------------- */
@@ -956,116 +956,116 @@ PyTypeObject EventHandlerRef_Type;
#define EventHandlerRef_Check(x) ((x)->ob_type == &EventHandlerRef_Type || PyObject_TypeCheck((x), &EventHandlerRef_Type))
typedef struct EventHandlerRefObject {
- PyObject_HEAD
- EventHandlerRef ob_itself;
- PyObject *ob_callback;
+ PyObject_HEAD
+ EventHandlerRef ob_itself;
+ PyObject *ob_callback;
} EventHandlerRefObject;
PyObject *EventHandlerRef_New(EventHandlerRef itself)
{
- EventHandlerRefObject *it;
- it = PyObject_NEW(EventHandlerRefObject, &EventHandlerRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_callback = NULL;
- return (PyObject *)it;
+ EventHandlerRefObject *it;
+ it = PyObject_NEW(EventHandlerRefObject, &EventHandlerRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_callback = NULL;
+ return (PyObject *)it;
}
int EventHandlerRef_Convert(PyObject *v, EventHandlerRef *p_itself)
{
- if (!EventHandlerRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventHandlerRef required");
- return 0;
- }
- *p_itself = ((EventHandlerRefObject *)v)->ob_itself;
- return 1;
+ if (!EventHandlerRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventHandlerRef required");
+ return 0;
+ }
+ *p_itself = ((EventHandlerRefObject *)v)->ob_itself;
+ return 1;
}
static void EventHandlerRef_dealloc(EventHandlerRefObject *self)
{
- if (self->ob_itself != NULL) {
- RemoveEventHandler(self->ob_itself);
- Py_DECREF(self->ob_callback);
- }
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_itself != NULL) {
+ RemoveEventHandler(self->ob_itself);
+ Py_DECREF(self->ob_callback);
+ }
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *EventHandlerRef_AddEventTypesToHandler(EventHandlerRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 inNumTypes;
- EventTypeSpec inList;
- if (_self->ob_itself == NULL) {
- PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
- return NULL;
- }
- if (!PyArg_ParseTuple(_args, "lO&",
- &inNumTypes,
- EventTypeSpec_Convert, &inList))
- return NULL;
- _err = AddEventTypesToHandler(_self->ob_itself,
- inNumTypes,
- &inList);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 inNumTypes;
+ EventTypeSpec inList;
+ if (_self->ob_itself == NULL) {
+ PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &inNumTypes,
+ EventTypeSpec_Convert, &inList))
+ return NULL;
+ _err = AddEventTypesToHandler(_self->ob_itself,
+ inNumTypes,
+ &inList);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventHandlerRef_RemoveEventTypesFromHandler(EventHandlerRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 inNumTypes;
- EventTypeSpec inList;
- if (_self->ob_itself == NULL) {
- PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
- return NULL;
- }
- if (!PyArg_ParseTuple(_args, "lO&",
- &inNumTypes,
- EventTypeSpec_Convert, &inList))
- return NULL;
- _err = RemoveEventTypesFromHandler(_self->ob_itself,
- inNumTypes,
- &inList);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 inNumTypes;
+ EventTypeSpec inList;
+ if (_self->ob_itself == NULL) {
+ PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &inNumTypes,
+ EventTypeSpec_Convert, &inList))
+ return NULL;
+ _err = RemoveEventTypesFromHandler(_self->ob_itself,
+ inNumTypes,
+ &inList);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventHandlerRef_RemoveEventHandler(EventHandlerRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- OSStatus _err;
- if (_self->ob_itself == NULL) {
- PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
- return NULL;
- }
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = RemoveEventHandler(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- _self->ob_itself = NULL;
- Py_DECREF(_self->ob_callback);
- _self->ob_callback = NULL;
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+
+ OSStatus _err;
+ if (_self->ob_itself == NULL) {
+ PyErr_SetString(CarbonEvents_Error, "Handler has been removed");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = RemoveEventHandler(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ _self->ob_itself = NULL;
+ Py_DECREF(_self->ob_callback);
+ _self->ob_callback = NULL;
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef EventHandlerRef_methods[] = {
- {"AddEventTypesToHandler", (PyCFunction)EventHandlerRef_AddEventTypesToHandler, 1,
- PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList) -> None")},
- {"RemoveEventTypesFromHandler", (PyCFunction)EventHandlerRef_RemoveEventTypesFromHandler, 1,
- PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList) -> None")},
- {"RemoveEventHandler", (PyCFunction)EventHandlerRef_RemoveEventHandler, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"AddEventTypesToHandler", (PyCFunction)EventHandlerRef_AddEventTypesToHandler, 1,
+ PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList) -> None")},
+ {"RemoveEventTypesFromHandler", (PyCFunction)EventHandlerRef_RemoveEventTypesFromHandler, 1,
+ PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList) -> None")},
+ {"RemoveEventHandler", (PyCFunction)EventHandlerRef_RemoveEventHandler, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define EventHandlerRef_getsetlist NULL
@@ -1082,61 +1082,61 @@ static PyMethodDef EventHandlerRef_methods[] = {
static PyObject *EventHandlerRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventHandlerRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventHandlerRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventHandlerRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventHandlerRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventHandlerRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventHandlerRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventHandlerRef_tp_free PyObject_Del
PyTypeObject EventHandlerRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventHandlerRef", /*tp_name*/
- sizeof(EventHandlerRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventHandlerRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventHandlerRef_compare, /*tp_compare*/
- (reprfunc) EventHandlerRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventHandlerRef_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*/
- EventHandlerRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventHandlerRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventHandlerRef_tp_init, /* tp_init */
- EventHandlerRef_tp_alloc, /* tp_alloc */
- EventHandlerRef_tp_new, /* tp_new */
- EventHandlerRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventHandlerRef", /*tp_name*/
+ sizeof(EventHandlerRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventHandlerRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventHandlerRef_compare, /*tp_compare*/
+ (reprfunc) EventHandlerRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventHandlerRef_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*/
+ EventHandlerRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventHandlerRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventHandlerRef_tp_init, /* tp_init */
+ EventHandlerRef_tp_alloc, /* tp_alloc */
+ EventHandlerRef_tp_new, /* tp_new */
+ EventHandlerRef_tp_free, /* tp_free */
};
/* ---------------- End object type EventHandlerRef ----------------- */
@@ -1149,56 +1149,56 @@ PyTypeObject EventHandlerCallRef_Type;
#define EventHandlerCallRef_Check(x) ((x)->ob_type == &EventHandlerCallRef_Type || PyObject_TypeCheck((x), &EventHandlerCallRef_Type))
typedef struct EventHandlerCallRefObject {
- PyObject_HEAD
- EventHandlerCallRef ob_itself;
+ PyObject_HEAD
+ EventHandlerCallRef ob_itself;
} EventHandlerCallRefObject;
PyObject *EventHandlerCallRef_New(EventHandlerCallRef itself)
{
- EventHandlerCallRefObject *it;
- it = PyObject_NEW(EventHandlerCallRefObject, &EventHandlerCallRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventHandlerCallRefObject *it;
+ it = PyObject_NEW(EventHandlerCallRefObject, &EventHandlerCallRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventHandlerCallRef_Convert(PyObject *v, EventHandlerCallRef *p_itself)
{
- if (!EventHandlerCallRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventHandlerCallRef required");
- return 0;
- }
- *p_itself = ((EventHandlerCallRefObject *)v)->ob_itself;
- return 1;
+ if (!EventHandlerCallRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventHandlerCallRef required");
+ return 0;
+ }
+ *p_itself = ((EventHandlerCallRefObject *)v)->ob_itself;
+ return 1;
}
static void EventHandlerCallRef_dealloc(EventHandlerCallRefObject *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 *EventHandlerCallRef_CallNextEventHandler(EventHandlerCallRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- EventRef inEvent;
- if (!PyArg_ParseTuple(_args, "O&",
- EventRef_Convert, &inEvent))
- return NULL;
- _err = CallNextEventHandler(_self->ob_itself,
- inEvent);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ EventRef inEvent;
+ if (!PyArg_ParseTuple(_args, "O&",
+ EventRef_Convert, &inEvent))
+ return NULL;
+ _err = CallNextEventHandler(_self->ob_itself,
+ inEvent);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef EventHandlerCallRef_methods[] = {
- {"CallNextEventHandler", (PyCFunction)EventHandlerCallRef_CallNextEventHandler, 1,
- PyDoc_STR("(EventRef inEvent) -> None")},
- {NULL, NULL, 0}
+ {"CallNextEventHandler", (PyCFunction)EventHandlerCallRef_CallNextEventHandler, 1,
+ PyDoc_STR("(EventRef inEvent) -> None")},
+ {NULL, NULL, 0}
};
#define EventHandlerCallRef_getsetlist NULL
@@ -1215,61 +1215,61 @@ static PyMethodDef EventHandlerCallRef_methods[] = {
static PyObject *EventHandlerCallRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventHandlerCallRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventHandlerCallRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventHandlerCallRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventHandlerCallRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventHandlerCallRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventHandlerCallRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventHandlerCallRef_tp_free PyObject_Del
PyTypeObject EventHandlerCallRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventHandlerCallRef", /*tp_name*/
- sizeof(EventHandlerCallRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventHandlerCallRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventHandlerCallRef_compare, /*tp_compare*/
- (reprfunc) EventHandlerCallRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventHandlerCallRef_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*/
- EventHandlerCallRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventHandlerCallRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventHandlerCallRef_tp_init, /* tp_init */
- EventHandlerCallRef_tp_alloc, /* tp_alloc */
- EventHandlerCallRef_tp_new, /* tp_new */
- EventHandlerCallRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventHandlerCallRef", /*tp_name*/
+ sizeof(EventHandlerCallRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventHandlerCallRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventHandlerCallRef_compare, /*tp_compare*/
+ (reprfunc) EventHandlerCallRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventHandlerCallRef_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*/
+ EventHandlerCallRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventHandlerCallRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventHandlerCallRef_tp_init, /* tp_init */
+ EventHandlerCallRef_tp_alloc, /* tp_alloc */
+ EventHandlerCallRef_tp_new, /* tp_new */
+ EventHandlerCallRef_tp_free, /* tp_free */
};
/* -------------- End object type EventHandlerCallRef --------------- */
@@ -1282,78 +1282,78 @@ PyTypeObject EventTargetRef_Type;
#define EventTargetRef_Check(x) ((x)->ob_type == &EventTargetRef_Type || PyObject_TypeCheck((x), &EventTargetRef_Type))
typedef struct EventTargetRefObject {
- PyObject_HEAD
- EventTargetRef ob_itself;
+ PyObject_HEAD
+ EventTargetRef ob_itself;
} EventTargetRefObject;
PyObject *EventTargetRef_New(EventTargetRef itself)
{
- EventTargetRefObject *it;
- it = PyObject_NEW(EventTargetRefObject, &EventTargetRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventTargetRefObject *it;
+ it = PyObject_NEW(EventTargetRefObject, &EventTargetRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventTargetRef_Convert(PyObject *v, EventTargetRef *p_itself)
{
- if (!EventTargetRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventTargetRef required");
- return 0;
- }
- *p_itself = ((EventTargetRefObject *)v)->ob_itself;
- return 1;
+ if (!EventTargetRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventTargetRef required");
+ return 0;
+ }
+ *p_itself = ((EventTargetRefObject *)v)->ob_itself;
+ return 1;
}
static void EventTargetRef_dealloc(EventTargetRefObject *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 *EventTargetRef_InstallStandardEventHandler(EventTargetRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = InstallStandardEventHandler(_self->ob_itself);
- 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 = InstallStandardEventHandler(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *EventTargetRef_InstallEventHandler(EventTargetRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- EventTypeSpec inSpec;
- PyObject *callback;
- EventHandlerRef outRef;
- OSStatus _err;
+ EventTypeSpec inSpec;
+ PyObject *callback;
+ EventHandlerRef outRef;
+ OSStatus _err;
- if (!PyArg_ParseTuple(_args, "O&O", EventTypeSpec_Convert, &inSpec, &callback))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "O&O", EventTypeSpec_Convert, &inSpec, &callback))
+ return NULL;
- _err = InstallEventHandler(_self->ob_itself, myEventHandlerUPP, 1, &inSpec, (void *)callback, &outRef);
- if (_err != noErr) return PyMac_Error(_err);
+ _err = InstallEventHandler(_self->ob_itself, myEventHandlerUPP, 1, &inSpec, (void *)callback, &outRef);
+ if (_err != noErr) return PyMac_Error(_err);
- _res = EventHandlerRef_New(outRef);
- if (_res != NULL) {
- ((EventHandlerRefObject*)_res)->ob_callback = callback;
- Py_INCREF(callback);
- }
- return _res;
+ _res = EventHandlerRef_New(outRef);
+ if (_res != NULL) {
+ ((EventHandlerRefObject*)_res)->ob_callback = callback;
+ Py_INCREF(callback);
+ }
+ return _res;
}
static PyMethodDef EventTargetRef_methods[] = {
- {"InstallStandardEventHandler", (PyCFunction)EventTargetRef_InstallStandardEventHandler, 1,
- PyDoc_STR("() -> None")},
- {"InstallEventHandler", (PyCFunction)EventTargetRef_InstallEventHandler, 1,
- PyDoc_STR("(EventTypeSpec inSpec, Method callback) -> (EventHandlerRef outRef)")},
- {NULL, NULL, 0}
+ {"InstallStandardEventHandler", (PyCFunction)EventTargetRef_InstallStandardEventHandler, 1,
+ PyDoc_STR("() -> None")},
+ {"InstallEventHandler", (PyCFunction)EventTargetRef_InstallEventHandler, 1,
+ PyDoc_STR("(EventTypeSpec inSpec, Method callback) -> (EventHandlerRef outRef)")},
+ {NULL, NULL, 0}
};
#define EventTargetRef_getsetlist NULL
@@ -1370,61 +1370,61 @@ static PyMethodDef EventTargetRef_methods[] = {
static PyObject *EventTargetRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventTargetRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventTargetRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventTargetRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventTargetRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventTargetRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventTargetRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventTargetRef_tp_free PyObject_Del
PyTypeObject EventTargetRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventTargetRef", /*tp_name*/
- sizeof(EventTargetRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventTargetRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventTargetRef_compare, /*tp_compare*/
- (reprfunc) EventTargetRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventTargetRef_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*/
- EventTargetRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventTargetRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventTargetRef_tp_init, /* tp_init */
- EventTargetRef_tp_alloc, /* tp_alloc */
- EventTargetRef_tp_new, /* tp_new */
- EventTargetRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventTargetRef", /*tp_name*/
+ sizeof(EventTargetRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventTargetRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventTargetRef_compare, /*tp_compare*/
+ (reprfunc) EventTargetRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventTargetRef_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*/
+ EventTargetRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventTargetRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventTargetRef_tp_init, /* tp_init */
+ EventTargetRef_tp_alloc, /* tp_alloc */
+ EventTargetRef_tp_new, /* tp_new */
+ EventTargetRef_tp_free, /* tp_free */
};
/* ----------------- End object type EventTargetRef ----------------- */
@@ -1437,53 +1437,53 @@ PyTypeObject EventHotKeyRef_Type;
#define EventHotKeyRef_Check(x) ((x)->ob_type == &EventHotKeyRef_Type || PyObject_TypeCheck((x), &EventHotKeyRef_Type))
typedef struct EventHotKeyRefObject {
- PyObject_HEAD
- EventHotKeyRef ob_itself;
+ PyObject_HEAD
+ EventHotKeyRef ob_itself;
} EventHotKeyRefObject;
PyObject *EventHotKeyRef_New(EventHotKeyRef itself)
{
- EventHotKeyRefObject *it;
- it = PyObject_NEW(EventHotKeyRefObject, &EventHotKeyRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ EventHotKeyRefObject *it;
+ it = PyObject_NEW(EventHotKeyRefObject, &EventHotKeyRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int EventHotKeyRef_Convert(PyObject *v, EventHotKeyRef *p_itself)
{
- if (!EventHotKeyRef_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "EventHotKeyRef required");
- return 0;
- }
- *p_itself = ((EventHotKeyRefObject *)v)->ob_itself;
- return 1;
+ if (!EventHotKeyRef_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "EventHotKeyRef required");
+ return 0;
+ }
+ *p_itself = ((EventHotKeyRefObject *)v)->ob_itself;
+ return 1;
}
static void EventHotKeyRef_dealloc(EventHotKeyRefObject *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 *EventHotKeyRef_UnregisterEventHotKey(EventHotKeyRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UnregisterEventHotKey(_self->ob_itself);
- 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 = UnregisterEventHotKey(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef EventHotKeyRef_methods[] = {
- {"UnregisterEventHotKey", (PyCFunction)EventHotKeyRef_UnregisterEventHotKey, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"UnregisterEventHotKey", (PyCFunction)EventHotKeyRef_UnregisterEventHotKey, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define EventHotKeyRef_getsetlist NULL
@@ -1500,61 +1500,61 @@ static PyMethodDef EventHotKeyRef_methods[] = {
static PyObject *EventHotKeyRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- EventHotKeyRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ EventHotKeyRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventHotKeyRef_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((EventHotKeyRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, EventHotKeyRef_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((EventHotKeyRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define EventHotKeyRef_tp_free PyObject_Del
PyTypeObject EventHotKeyRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CarbonEvt.EventHotKeyRef", /*tp_name*/
- sizeof(EventHotKeyRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) EventHotKeyRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) EventHotKeyRef_compare, /*tp_compare*/
- (reprfunc) EventHotKeyRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) EventHotKeyRef_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*/
- EventHotKeyRef_methods, /* tp_methods */
- 0, /*tp_members*/
- EventHotKeyRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- EventHotKeyRef_tp_init, /* tp_init */
- EventHotKeyRef_tp_alloc, /* tp_alloc */
- EventHotKeyRef_tp_new, /* tp_new */
- EventHotKeyRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CarbonEvt.EventHotKeyRef", /*tp_name*/
+ sizeof(EventHotKeyRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) EventHotKeyRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) EventHotKeyRef_compare, /*tp_compare*/
+ (reprfunc) EventHotKeyRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) EventHotKeyRef_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*/
+ EventHotKeyRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ EventHotKeyRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ EventHotKeyRef_tp_init, /* tp_init */
+ EventHotKeyRef_tp_alloc, /* tp_alloc */
+ EventHotKeyRef_tp_new, /* tp_new */
+ EventHotKeyRef_tp_free, /* tp_free */
};
/* ----------------- End object type EventHotKeyRef ----------------- */
@@ -1562,577 +1562,577 @@ PyTypeObject EventHotKeyRef_Type = {
static PyObject *CarbonEvents_GetCurrentEventLoop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventLoopRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetCurrentEventLoop();
- _res = Py_BuildValue("O&",
- EventLoopRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventLoopRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetCurrentEventLoop();
+ _res = Py_BuildValue("O&",
+ EventLoopRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetMainEventLoop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventLoopRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMainEventLoop();
- _res = Py_BuildValue("O&",
- EventLoopRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventLoopRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMainEventLoop();
+ _res = Py_BuildValue("O&",
+ EventLoopRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_RunCurrentEventLoop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- double inTimeout;
- if (!PyArg_ParseTuple(_args, "d",
- &inTimeout))
- return NULL;
- _err = RunCurrentEventLoop(inTimeout);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ double inTimeout;
+ if (!PyArg_ParseTuple(_args, "d",
+ &inTimeout))
+ return NULL;
+ _err = RunCurrentEventLoop(inTimeout);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_ReceiveNextEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 inNumTypes;
- EventTypeSpec inList;
- double inTimeout;
- Boolean inPullEvent;
- EventRef outEvent;
- if (!PyArg_ParseTuple(_args, "lO&db",
- &inNumTypes,
- EventTypeSpec_Convert, &inList,
- &inTimeout,
- &inPullEvent))
- return NULL;
- _err = ReceiveNextEvent(inNumTypes,
- &inList,
- inTimeout,
- inPullEvent,
- &outEvent);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- EventRef_New, outEvent);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 inNumTypes;
+ EventTypeSpec inList;
+ double inTimeout;
+ Boolean inPullEvent;
+ EventRef outEvent;
+ if (!PyArg_ParseTuple(_args, "lO&db",
+ &inNumTypes,
+ EventTypeSpec_Convert, &inList,
+ &inTimeout,
+ &inPullEvent))
+ return NULL;
+ _err = ReceiveNextEvent(inNumTypes,
+ &inList,
+ inTimeout,
+ inPullEvent,
+ &outEvent);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ EventRef_New, outEvent);
+ return _res;
}
static PyObject *CarbonEvents_GetCurrentEventQueue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventQueueRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetCurrentEventQueue();
- _res = Py_BuildValue("O&",
- EventQueueRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventQueueRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetCurrentEventQueue();
+ _res = Py_BuildValue("O&",
+ EventQueueRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetMainEventQueue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventQueueRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMainEventQueue();
- _res = Py_BuildValue("O&",
- EventQueueRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventQueueRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMainEventQueue();
+ _res = Py_BuildValue("O&",
+ EventQueueRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetCurrentEventTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- double _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetCurrentEventTime();
- _res = Py_BuildValue("d",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ double _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetCurrentEventTime();
+ _res = Py_BuildValue("d",
+ _rv);
+ return _res;
}
static PyObject *CarbonEvents_TrackMouseLocation(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- GrafPtr inPort;
- Point outPt;
- UInt16 outResult;
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &inPort))
- return NULL;
- _err = TrackMouseLocation(inPort,
- &outPt,
- &outResult);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&H",
- PyMac_BuildPoint, outPt,
- outResult);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ GrafPtr inPort;
+ Point outPt;
+ UInt16 outResult;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &inPort))
+ return NULL;
+ _err = TrackMouseLocation(inPort,
+ &outPt,
+ &outResult);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&H",
+ PyMac_BuildPoint, outPt,
+ outResult);
+ return _res;
}
static PyObject *CarbonEvents_TrackMouseLocationWithOptions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- GrafPtr inPort;
- OptionBits inOptions;
- double inTimeout;
- Point outPt;
- UInt32 outModifiers;
- UInt16 outResult;
- if (!PyArg_ParseTuple(_args, "O&ld",
- GrafObj_Convert, &inPort,
- &inOptions,
- &inTimeout))
- return NULL;
- _err = TrackMouseLocationWithOptions(inPort,
- inOptions,
- inTimeout,
- &outPt,
- &outModifiers,
- &outResult);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&lH",
- PyMac_BuildPoint, outPt,
- outModifiers,
- outResult);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ GrafPtr inPort;
+ OptionBits inOptions;
+ double inTimeout;
+ Point outPt;
+ UInt32 outModifiers;
+ UInt16 outResult;
+ if (!PyArg_ParseTuple(_args, "O&ld",
+ GrafObj_Convert, &inPort,
+ &inOptions,
+ &inTimeout))
+ return NULL;
+ _err = TrackMouseLocationWithOptions(inPort,
+ inOptions,
+ inTimeout,
+ &outPt,
+ &outModifiers,
+ &outResult);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&lH",
+ PyMac_BuildPoint, outPt,
+ outModifiers,
+ outResult);
+ return _res;
}
static PyObject *CarbonEvents_TrackMouseRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- GrafPtr inPort;
- RgnHandle inRegion;
- Boolean ioWasInRgn;
- UInt16 outResult;
- if (!PyArg_ParseTuple(_args, "O&O&b",
- GrafObj_Convert, &inPort,
- ResObj_Convert, &inRegion,
- &ioWasInRgn))
- return NULL;
- _err = TrackMouseRegion(inPort,
- inRegion,
- &ioWasInRgn,
- &outResult);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bH",
- ioWasInRgn,
- outResult);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ GrafPtr inPort;
+ RgnHandle inRegion;
+ Boolean ioWasInRgn;
+ UInt16 outResult;
+ if (!PyArg_ParseTuple(_args, "O&O&b",
+ GrafObj_Convert, &inPort,
+ ResObj_Convert, &inRegion,
+ &ioWasInRgn))
+ return NULL;
+ _err = TrackMouseRegion(inPort,
+ inRegion,
+ &ioWasInRgn,
+ &outResult);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bH",
+ ioWasInRgn,
+ outResult);
+ return _res;
}
static PyObject *CarbonEvents_GetLastUserEventTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- double _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetLastUserEventTime();
- _res = Py_BuildValue("d",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ double _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetLastUserEventTime();
+ _res = Py_BuildValue("d",
+ _rv);
+ return _res;
}
static PyObject *CarbonEvents_IsMouseCoalescingEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsMouseCoalescingEnabled();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsMouseCoalescingEnabled();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CarbonEvents_SetMouseCoalescingEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean inNewState;
- Boolean outOldState;
- if (!PyArg_ParseTuple(_args, "b",
- &inNewState))
- return NULL;
- _err = SetMouseCoalescingEnabled(inNewState,
- &outOldState);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- outOldState);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean inNewState;
+ Boolean outOldState;
+ if (!PyArg_ParseTuple(_args, "b",
+ &inNewState))
+ return NULL;
+ _err = SetMouseCoalescingEnabled(inNewState,
+ &outOldState);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ outOldState);
+ return _res;
}
static PyObject *CarbonEvents_GetWindowEventTarget(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventTargetRef _rv;
- WindowPtr inWindow;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _rv = GetWindowEventTarget(inWindow);
- _res = Py_BuildValue("O&",
- EventTargetRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventTargetRef _rv;
+ WindowPtr inWindow;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _rv = GetWindowEventTarget(inWindow);
+ _res = Py_BuildValue("O&",
+ EventTargetRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetControlEventTarget(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventTargetRef _rv;
- ControlHandle inControl;
- if (!PyArg_ParseTuple(_args, "O&",
- CtlObj_Convert, &inControl))
- return NULL;
- _rv = GetControlEventTarget(inControl);
- _res = Py_BuildValue("O&",
- EventTargetRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventTargetRef _rv;
+ ControlHandle inControl;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CtlObj_Convert, &inControl))
+ return NULL;
+ _rv = GetControlEventTarget(inControl);
+ _res = Py_BuildValue("O&",
+ EventTargetRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetMenuEventTarget(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventTargetRef _rv;
- MenuHandle inMenu;
- if (!PyArg_ParseTuple(_args, "O&",
- MenuObj_Convert, &inMenu))
- return NULL;
- _rv = GetMenuEventTarget(inMenu);
- _res = Py_BuildValue("O&",
- EventTargetRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventTargetRef _rv;
+ MenuHandle inMenu;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MenuObj_Convert, &inMenu))
+ return NULL;
+ _rv = GetMenuEventTarget(inMenu);
+ _res = Py_BuildValue("O&",
+ EventTargetRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetApplicationEventTarget(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventTargetRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetApplicationEventTarget();
- _res = Py_BuildValue("O&",
- EventTargetRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventTargetRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetApplicationEventTarget();
+ _res = Py_BuildValue("O&",
+ EventTargetRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetUserFocusEventTarget(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventTargetRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetUserFocusEventTarget();
- _res = Py_BuildValue("O&",
- EventTargetRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventTargetRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetUserFocusEventTarget();
+ _res = Py_BuildValue("O&",
+ EventTargetRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_GetEventDispatcherTarget(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventTargetRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetEventDispatcherTarget();
- _res = Py_BuildValue("O&",
- EventTargetRef_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ EventTargetRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetEventDispatcherTarget();
+ _res = Py_BuildValue("O&",
+ EventTargetRef_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_RunApplicationEventLoop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- RunApplicationEventLoop();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ RunApplicationEventLoop();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_QuitApplicationEventLoop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- QuitApplicationEventLoop();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ QuitApplicationEventLoop();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_RunAppModalLoopForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = RunAppModalLoopForWindow(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = RunAppModalLoopForWindow(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_QuitAppModalLoopForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = QuitAppModalLoopForWindow(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = QuitAppModalLoopForWindow(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_BeginAppModalStateForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = BeginAppModalStateForWindow(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = BeginAppModalStateForWindow(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_EndAppModalStateForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = EndAppModalStateForWindow(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = EndAppModalStateForWindow(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_SetUserFocusWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = SetUserFocusWindow(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = SetUserFocusWindow(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_GetUserFocusWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetUserFocusWindow();
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetUserFocusWindow();
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *CarbonEvents_SetWindowDefaultButton(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- ControlHandle inControl;
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &inWindow,
- CtlObj_Convert, &inControl))
- return NULL;
- _err = SetWindowDefaultButton(inWindow,
- inControl);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ ControlHandle inControl;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &inWindow,
+ CtlObj_Convert, &inControl))
+ return NULL;
+ _err = SetWindowDefaultButton(inWindow,
+ inControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_SetWindowCancelButton(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- ControlHandle inControl;
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &inWindow,
- CtlObj_Convert, &inControl))
- return NULL;
- _err = SetWindowCancelButton(inWindow,
- inControl);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ ControlHandle inControl;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &inWindow,
+ CtlObj_Convert, &inControl))
+ return NULL;
+ _err = SetWindowCancelButton(inWindow,
+ inControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CarbonEvents_GetWindowDefaultButton(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- ControlHandle outControl;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = GetWindowDefaultButton(inWindow,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ ControlHandle outControl;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = GetWindowDefaultButton(inWindow,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *CarbonEvents_GetWindowCancelButton(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- ControlHandle outControl;
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = GetWindowCancelButton(inWindow,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ ControlHandle outControl;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = GetWindowCancelButton(inWindow,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *CarbonEvents_RegisterEventHotKey(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 inHotKeyCode;
- UInt32 inHotKeyModifiers;
- EventHotKeyID inHotKeyID;
- EventTargetRef inTarget;
- OptionBits inOptions;
- EventHotKeyRef outRef;
- if (!PyArg_ParseTuple(_args, "llO&O&l",
- &inHotKeyCode,
- &inHotKeyModifiers,
- EventHotKeyID_Convert, &inHotKeyID,
- EventTargetRef_Convert, &inTarget,
- &inOptions))
- return NULL;
- _err = RegisterEventHotKey(inHotKeyCode,
- inHotKeyModifiers,
- inHotKeyID,
- inTarget,
- inOptions,
- &outRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- EventHotKeyRef_New, outRef);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 inHotKeyCode;
+ UInt32 inHotKeyModifiers;
+ EventHotKeyID inHotKeyID;
+ EventTargetRef inTarget;
+ OptionBits inOptions;
+ EventHotKeyRef outRef;
+ if (!PyArg_ParseTuple(_args, "llO&O&l",
+ &inHotKeyCode,
+ &inHotKeyModifiers,
+ EventHotKeyID_Convert, &inHotKeyID,
+ EventTargetRef_Convert, &inTarget,
+ &inOptions))
+ return NULL;
+ _err = RegisterEventHotKey(inHotKeyCode,
+ inHotKeyModifiers,
+ inHotKeyID,
+ inTarget,
+ inOptions,
+ &outRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ EventHotKeyRef_New, outRef);
+ return _res;
}
static PyMethodDef CarbonEvents_methods[] = {
- {"GetCurrentEventLoop", (PyCFunction)CarbonEvents_GetCurrentEventLoop, 1,
- PyDoc_STR("() -> (EventLoopRef _rv)")},
- {"GetMainEventLoop", (PyCFunction)CarbonEvents_GetMainEventLoop, 1,
- PyDoc_STR("() -> (EventLoopRef _rv)")},
- {"RunCurrentEventLoop", (PyCFunction)CarbonEvents_RunCurrentEventLoop, 1,
- PyDoc_STR("(double inTimeout) -> None")},
- {"ReceiveNextEvent", (PyCFunction)CarbonEvents_ReceiveNextEvent, 1,
- PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList, double inTimeout, Boolean inPullEvent) -> (EventRef outEvent)")},
- {"GetCurrentEventQueue", (PyCFunction)CarbonEvents_GetCurrentEventQueue, 1,
- PyDoc_STR("() -> (EventQueueRef _rv)")},
- {"GetMainEventQueue", (PyCFunction)CarbonEvents_GetMainEventQueue, 1,
- PyDoc_STR("() -> (EventQueueRef _rv)")},
- {"GetCurrentEventTime", (PyCFunction)CarbonEvents_GetCurrentEventTime, 1,
- PyDoc_STR("() -> (double _rv)")},
- {"TrackMouseLocation", (PyCFunction)CarbonEvents_TrackMouseLocation, 1,
- PyDoc_STR("(GrafPtr inPort) -> (Point outPt, UInt16 outResult)")},
- {"TrackMouseLocationWithOptions", (PyCFunction)CarbonEvents_TrackMouseLocationWithOptions, 1,
- PyDoc_STR("(GrafPtr inPort, OptionBits inOptions, double inTimeout) -> (Point outPt, UInt32 outModifiers, UInt16 outResult)")},
- {"TrackMouseRegion", (PyCFunction)CarbonEvents_TrackMouseRegion, 1,
- PyDoc_STR("(GrafPtr inPort, RgnHandle inRegion, Boolean ioWasInRgn) -> (Boolean ioWasInRgn, UInt16 outResult)")},
- {"GetLastUserEventTime", (PyCFunction)CarbonEvents_GetLastUserEventTime, 1,
- PyDoc_STR("() -> (double _rv)")},
- {"IsMouseCoalescingEnabled", (PyCFunction)CarbonEvents_IsMouseCoalescingEnabled, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SetMouseCoalescingEnabled", (PyCFunction)CarbonEvents_SetMouseCoalescingEnabled, 1,
- PyDoc_STR("(Boolean inNewState) -> (Boolean outOldState)")},
- {"GetWindowEventTarget", (PyCFunction)CarbonEvents_GetWindowEventTarget, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (EventTargetRef _rv)")},
- {"GetControlEventTarget", (PyCFunction)CarbonEvents_GetControlEventTarget, 1,
- PyDoc_STR("(ControlHandle inControl) -> (EventTargetRef _rv)")},
- {"GetMenuEventTarget", (PyCFunction)CarbonEvents_GetMenuEventTarget, 1,
- PyDoc_STR("(MenuHandle inMenu) -> (EventTargetRef _rv)")},
- {"GetApplicationEventTarget", (PyCFunction)CarbonEvents_GetApplicationEventTarget, 1,
- PyDoc_STR("() -> (EventTargetRef _rv)")},
- {"GetUserFocusEventTarget", (PyCFunction)CarbonEvents_GetUserFocusEventTarget, 1,
- PyDoc_STR("() -> (EventTargetRef _rv)")},
- {"GetEventDispatcherTarget", (PyCFunction)CarbonEvents_GetEventDispatcherTarget, 1,
- PyDoc_STR("() -> (EventTargetRef _rv)")},
- {"RunApplicationEventLoop", (PyCFunction)CarbonEvents_RunApplicationEventLoop, 1,
- PyDoc_STR("() -> None")},
- {"QuitApplicationEventLoop", (PyCFunction)CarbonEvents_QuitApplicationEventLoop, 1,
- PyDoc_STR("() -> None")},
- {"RunAppModalLoopForWindow", (PyCFunction)CarbonEvents_RunAppModalLoopForWindow, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"QuitAppModalLoopForWindow", (PyCFunction)CarbonEvents_QuitAppModalLoopForWindow, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"BeginAppModalStateForWindow", (PyCFunction)CarbonEvents_BeginAppModalStateForWindow, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"EndAppModalStateForWindow", (PyCFunction)CarbonEvents_EndAppModalStateForWindow, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"SetUserFocusWindow", (PyCFunction)CarbonEvents_SetUserFocusWindow, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"GetUserFocusWindow", (PyCFunction)CarbonEvents_GetUserFocusWindow, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"SetWindowDefaultButton", (PyCFunction)CarbonEvents_SetWindowDefaultButton, 1,
- PyDoc_STR("(WindowPtr inWindow, ControlHandle inControl) -> None")},
- {"SetWindowCancelButton", (PyCFunction)CarbonEvents_SetWindowCancelButton, 1,
- PyDoc_STR("(WindowPtr inWindow, ControlHandle inControl) -> None")},
- {"GetWindowDefaultButton", (PyCFunction)CarbonEvents_GetWindowDefaultButton, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
- {"GetWindowCancelButton", (PyCFunction)CarbonEvents_GetWindowCancelButton, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
- {"RegisterEventHotKey", (PyCFunction)CarbonEvents_RegisterEventHotKey, 1,
- PyDoc_STR("(UInt32 inHotKeyCode, UInt32 inHotKeyModifiers, EventHotKeyID inHotKeyID, EventTargetRef inTarget, OptionBits inOptions) -> (EventHotKeyRef outRef)")},
- {NULL, NULL, 0}
+ {"GetCurrentEventLoop", (PyCFunction)CarbonEvents_GetCurrentEventLoop, 1,
+ PyDoc_STR("() -> (EventLoopRef _rv)")},
+ {"GetMainEventLoop", (PyCFunction)CarbonEvents_GetMainEventLoop, 1,
+ PyDoc_STR("() -> (EventLoopRef _rv)")},
+ {"RunCurrentEventLoop", (PyCFunction)CarbonEvents_RunCurrentEventLoop, 1,
+ PyDoc_STR("(double inTimeout) -> None")},
+ {"ReceiveNextEvent", (PyCFunction)CarbonEvents_ReceiveNextEvent, 1,
+ PyDoc_STR("(UInt32 inNumTypes, EventTypeSpec inList, double inTimeout, Boolean inPullEvent) -> (EventRef outEvent)")},
+ {"GetCurrentEventQueue", (PyCFunction)CarbonEvents_GetCurrentEventQueue, 1,
+ PyDoc_STR("() -> (EventQueueRef _rv)")},
+ {"GetMainEventQueue", (PyCFunction)CarbonEvents_GetMainEventQueue, 1,
+ PyDoc_STR("() -> (EventQueueRef _rv)")},
+ {"GetCurrentEventTime", (PyCFunction)CarbonEvents_GetCurrentEventTime, 1,
+ PyDoc_STR("() -> (double _rv)")},
+ {"TrackMouseLocation", (PyCFunction)CarbonEvents_TrackMouseLocation, 1,
+ PyDoc_STR("(GrafPtr inPort) -> (Point outPt, UInt16 outResult)")},
+ {"TrackMouseLocationWithOptions", (PyCFunction)CarbonEvents_TrackMouseLocationWithOptions, 1,
+ PyDoc_STR("(GrafPtr inPort, OptionBits inOptions, double inTimeout) -> (Point outPt, UInt32 outModifiers, UInt16 outResult)")},
+ {"TrackMouseRegion", (PyCFunction)CarbonEvents_TrackMouseRegion, 1,
+ PyDoc_STR("(GrafPtr inPort, RgnHandle inRegion, Boolean ioWasInRgn) -> (Boolean ioWasInRgn, UInt16 outResult)")},
+ {"GetLastUserEventTime", (PyCFunction)CarbonEvents_GetLastUserEventTime, 1,
+ PyDoc_STR("() -> (double _rv)")},
+ {"IsMouseCoalescingEnabled", (PyCFunction)CarbonEvents_IsMouseCoalescingEnabled, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SetMouseCoalescingEnabled", (PyCFunction)CarbonEvents_SetMouseCoalescingEnabled, 1,
+ PyDoc_STR("(Boolean inNewState) -> (Boolean outOldState)")},
+ {"GetWindowEventTarget", (PyCFunction)CarbonEvents_GetWindowEventTarget, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (EventTargetRef _rv)")},
+ {"GetControlEventTarget", (PyCFunction)CarbonEvents_GetControlEventTarget, 1,
+ PyDoc_STR("(ControlHandle inControl) -> (EventTargetRef _rv)")},
+ {"GetMenuEventTarget", (PyCFunction)CarbonEvents_GetMenuEventTarget, 1,
+ PyDoc_STR("(MenuHandle inMenu) -> (EventTargetRef _rv)")},
+ {"GetApplicationEventTarget", (PyCFunction)CarbonEvents_GetApplicationEventTarget, 1,
+ PyDoc_STR("() -> (EventTargetRef _rv)")},
+ {"GetUserFocusEventTarget", (PyCFunction)CarbonEvents_GetUserFocusEventTarget, 1,
+ PyDoc_STR("() -> (EventTargetRef _rv)")},
+ {"GetEventDispatcherTarget", (PyCFunction)CarbonEvents_GetEventDispatcherTarget, 1,
+ PyDoc_STR("() -> (EventTargetRef _rv)")},
+ {"RunApplicationEventLoop", (PyCFunction)CarbonEvents_RunApplicationEventLoop, 1,
+ PyDoc_STR("() -> None")},
+ {"QuitApplicationEventLoop", (PyCFunction)CarbonEvents_QuitApplicationEventLoop, 1,
+ PyDoc_STR("() -> None")},
+ {"RunAppModalLoopForWindow", (PyCFunction)CarbonEvents_RunAppModalLoopForWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"QuitAppModalLoopForWindow", (PyCFunction)CarbonEvents_QuitAppModalLoopForWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"BeginAppModalStateForWindow", (PyCFunction)CarbonEvents_BeginAppModalStateForWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"EndAppModalStateForWindow", (PyCFunction)CarbonEvents_EndAppModalStateForWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"SetUserFocusWindow", (PyCFunction)CarbonEvents_SetUserFocusWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"GetUserFocusWindow", (PyCFunction)CarbonEvents_GetUserFocusWindow, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"SetWindowDefaultButton", (PyCFunction)CarbonEvents_SetWindowDefaultButton, 1,
+ PyDoc_STR("(WindowPtr inWindow, ControlHandle inControl) -> None")},
+ {"SetWindowCancelButton", (PyCFunction)CarbonEvents_SetWindowCancelButton, 1,
+ PyDoc_STR("(WindowPtr inWindow, ControlHandle inControl) -> None")},
+ {"GetWindowDefaultButton", (PyCFunction)CarbonEvents_GetWindowDefaultButton, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
+ {"GetWindowCancelButton", (PyCFunction)CarbonEvents_GetWindowCancelButton, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
+ {"RegisterEventHotKey", (PyCFunction)CarbonEvents_RegisterEventHotKey, 1,
+ PyDoc_STR("(UInt32 inHotKeyCode, UInt32 inHotKeyModifiers, EventHotKeyID inHotKeyID, EventTargetRef inTarget, OptionBits inOptions) -> (EventHotKeyRef outRef)")},
+ {NULL, NULL, 0}
};
#else /* __LP64__ */
static PyMethodDef CarbonEvents_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#endif /* __LP64__ */
@@ -2141,77 +2141,77 @@ static PyMethodDef CarbonEvents_methods[] = {
void init_CarbonEvt(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
#endif /* !__LP64__ */
- m = Py_InitModule("_CarbonEvt", CarbonEvents_methods);
+ m = Py_InitModule("_CarbonEvt", CarbonEvents_methods);
#ifndef __LP64__
- myEventHandlerUPP = NewEventHandlerUPP(myEventHandler);
- d = PyModule_GetDict(m);
- CarbonEvents_Error = PyMac_GetOSErrException();
- if (CarbonEvents_Error == NULL ||
- PyDict_SetItemString(d, "Error", CarbonEvents_Error) != 0)
- return;
- EventRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventRef_Type) < 0) return;
- Py_INCREF(&EventRef_Type);
- PyModule_AddObject(m, "EventRef", (PyObject *)&EventRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventRef_Type);
- PyModule_AddObject(m, "EventRefType", (PyObject *)&EventRef_Type);
- EventQueueRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventQueueRef_Type) < 0) return;
- Py_INCREF(&EventQueueRef_Type);
- PyModule_AddObject(m, "EventQueueRef", (PyObject *)&EventQueueRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventQueueRef_Type);
- PyModule_AddObject(m, "EventQueueRefType", (PyObject *)&EventQueueRef_Type);
- EventLoopRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventLoopRef_Type) < 0) return;
- Py_INCREF(&EventLoopRef_Type);
- PyModule_AddObject(m, "EventLoopRef", (PyObject *)&EventLoopRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventLoopRef_Type);
- PyModule_AddObject(m, "EventLoopRefType", (PyObject *)&EventLoopRef_Type);
- EventLoopTimerRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventLoopTimerRef_Type) < 0) return;
- Py_INCREF(&EventLoopTimerRef_Type);
- PyModule_AddObject(m, "EventLoopTimerRef", (PyObject *)&EventLoopTimerRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventLoopTimerRef_Type);
- PyModule_AddObject(m, "EventLoopTimerRefType", (PyObject *)&EventLoopTimerRef_Type);
- EventHandlerRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventHandlerRef_Type) < 0) return;
- Py_INCREF(&EventHandlerRef_Type);
- PyModule_AddObject(m, "EventHandlerRef", (PyObject *)&EventHandlerRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventHandlerRef_Type);
- PyModule_AddObject(m, "EventHandlerRefType", (PyObject *)&EventHandlerRef_Type);
- EventHandlerCallRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventHandlerCallRef_Type) < 0) return;
- Py_INCREF(&EventHandlerCallRef_Type);
- PyModule_AddObject(m, "EventHandlerCallRef", (PyObject *)&EventHandlerCallRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventHandlerCallRef_Type);
- PyModule_AddObject(m, "EventHandlerCallRefType", (PyObject *)&EventHandlerCallRef_Type);
- EventTargetRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventTargetRef_Type) < 0) return;
- Py_INCREF(&EventTargetRef_Type);
- PyModule_AddObject(m, "EventTargetRef", (PyObject *)&EventTargetRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventTargetRef_Type);
- PyModule_AddObject(m, "EventTargetRefType", (PyObject *)&EventTargetRef_Type);
- EventHotKeyRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&EventHotKeyRef_Type) < 0) return;
- Py_INCREF(&EventHotKeyRef_Type);
- PyModule_AddObject(m, "EventHotKeyRef", (PyObject *)&EventHotKeyRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&EventHotKeyRef_Type);
- PyModule_AddObject(m, "EventHotKeyRefType", (PyObject *)&EventHotKeyRef_Type);
+ myEventHandlerUPP = NewEventHandlerUPP(myEventHandler);
+ d = PyModule_GetDict(m);
+ CarbonEvents_Error = PyMac_GetOSErrException();
+ if (CarbonEvents_Error == NULL ||
+ PyDict_SetItemString(d, "Error", CarbonEvents_Error) != 0)
+ return;
+ EventRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventRef_Type) < 0) return;
+ Py_INCREF(&EventRef_Type);
+ PyModule_AddObject(m, "EventRef", (PyObject *)&EventRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventRef_Type);
+ PyModule_AddObject(m, "EventRefType", (PyObject *)&EventRef_Type);
+ EventQueueRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventQueueRef_Type) < 0) return;
+ Py_INCREF(&EventQueueRef_Type);
+ PyModule_AddObject(m, "EventQueueRef", (PyObject *)&EventQueueRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventQueueRef_Type);
+ PyModule_AddObject(m, "EventQueueRefType", (PyObject *)&EventQueueRef_Type);
+ EventLoopRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventLoopRef_Type) < 0) return;
+ Py_INCREF(&EventLoopRef_Type);
+ PyModule_AddObject(m, "EventLoopRef", (PyObject *)&EventLoopRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventLoopRef_Type);
+ PyModule_AddObject(m, "EventLoopRefType", (PyObject *)&EventLoopRef_Type);
+ EventLoopTimerRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventLoopTimerRef_Type) < 0) return;
+ Py_INCREF(&EventLoopTimerRef_Type);
+ PyModule_AddObject(m, "EventLoopTimerRef", (PyObject *)&EventLoopTimerRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventLoopTimerRef_Type);
+ PyModule_AddObject(m, "EventLoopTimerRefType", (PyObject *)&EventLoopTimerRef_Type);
+ EventHandlerRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventHandlerRef_Type) < 0) return;
+ Py_INCREF(&EventHandlerRef_Type);
+ PyModule_AddObject(m, "EventHandlerRef", (PyObject *)&EventHandlerRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventHandlerRef_Type);
+ PyModule_AddObject(m, "EventHandlerRefType", (PyObject *)&EventHandlerRef_Type);
+ EventHandlerCallRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventHandlerCallRef_Type) < 0) return;
+ Py_INCREF(&EventHandlerCallRef_Type);
+ PyModule_AddObject(m, "EventHandlerCallRef", (PyObject *)&EventHandlerCallRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventHandlerCallRef_Type);
+ PyModule_AddObject(m, "EventHandlerCallRefType", (PyObject *)&EventHandlerCallRef_Type);
+ EventTargetRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventTargetRef_Type) < 0) return;
+ Py_INCREF(&EventTargetRef_Type);
+ PyModule_AddObject(m, "EventTargetRef", (PyObject *)&EventTargetRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventTargetRef_Type);
+ PyModule_AddObject(m, "EventTargetRefType", (PyObject *)&EventTargetRef_Type);
+ EventHotKeyRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&EventHotKeyRef_Type) < 0) return;
+ Py_INCREF(&EventHotKeyRef_Type);
+ PyModule_AddObject(m, "EventHotKeyRef", (PyObject *)&EventHotKeyRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&EventHotKeyRef_Type);
+ PyModule_AddObject(m, "EventHotKeyRefType", (PyObject *)&EventHotKeyRef_Type);
#endif /* !__LP64__ */
}
diff --git a/Mac/Modules/cf/_CFmodule.c b/Mac/Modules/cf/_CFmodule.c
index 0904ae1..ee67c70 100644
--- a/Mac/Modules/cf/_CFmodule.c
+++ b/Mac/Modules/cf/_CFmodule.c
@@ -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)
@@ -84,19 +84,19 @@ extern int _OptionalCFURLRefObj_Convert(PyObject *, CFURLRef *);
PyObject *CFRange_New(CFRange *itself)
{
- return Py_BuildValue("ll", (long)itself->location, (long)itself->length);
+ return Py_BuildValue("ll", (long)itself->location, (long)itself->length);
}
int
CFRange_Convert(PyObject *v, CFRange *p_itself)
{
- long location, length;
+ long location, length;
- if( !PyArg_ParseTuple(v, "ll", &location, &length) )
- return 0;
- p_itself->location = (CFIndex)location;
- p_itself->length = (CFIndex)length;
- return 1;
+ if( !PyArg_ParseTuple(v, "ll", &location, &length) )
+ return 0;
+ p_itself->location = (CFIndex)location;
+ p_itself->length = (CFIndex)length;
+ return 1;
}
/* Optional CFURL argument or None (passed as NULL) */
@@ -104,8 +104,8 @@ int
OptionalCFURLRefObj_Convert(PyObject *v, CFURLRef *p_itself)
{
if ( v == Py_None ) {
- p_itself = NULL;
- return 1;
+ p_itself = NULL;
+ return 1;
}
return CFURLRefObj_Convert(v, p_itself);
}
@@ -119,262 +119,262 @@ PyTypeObject CFTypeRef_Type;
#define CFTypeRefObj_Check(x) ((x)->ob_type == &CFTypeRef_Type || PyObject_TypeCheck((x), &CFTypeRef_Type))
typedef struct CFTypeRefObject {
- PyObject_HEAD
- CFTypeRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFTypeRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFTypeRefObject;
PyObject *CFTypeRefObj_New(CFTypeRef itself)
{
- CFTypeRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFTypeRefObject, &CFTypeRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFTypeRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFTypeRefObject, &CFTypeRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFTypeRefObj_Convert(PyObject *v, CFTypeRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFTypeRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFTypeRef required");
- return 0;
- }
- *p_itself = ((CFTypeRefObject *)v)->ob_itself;
- return 1;
+ if (!CFTypeRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFTypeRef required");
+ return 0;
+ }
+ *p_itself = ((CFTypeRefObject *)v)->ob_itself;
+ return 1;
}
static void CFTypeRefObj_dealloc(CFTypeRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *CFTypeRefObj_CFGetTypeID(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFGetTypeID
- PyMac_PRECHECK(CFGetTypeID);
+ PyMac_PRECHECK(CFGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFGetTypeID(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFGetTypeID(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFRetain(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeRef _rv;
+ PyObject *_res = NULL;
+ CFTypeRef _rv;
#ifndef CFRetain
- PyMac_PRECHECK(CFRetain);
+ PyMac_PRECHECK(CFRetain);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFRetain(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFTypeRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFRetain(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFTypeRefObj_New, _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFRelease(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CFRelease
- PyMac_PRECHECK(CFRelease);
+ PyMac_PRECHECK(CFRelease);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CFRelease(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CFRelease(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFTypeRefObj_CFGetRetainCount(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
+ PyObject *_res = NULL;
+ CFIndex _rv;
#ifndef CFGetRetainCount
- PyMac_PRECHECK(CFGetRetainCount);
+ PyMac_PRECHECK(CFGetRetainCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFGetRetainCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFGetRetainCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFEqual(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFTypeRef cf2;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFTypeRef cf2;
#ifndef CFEqual
- PyMac_PRECHECK(CFEqual);
+ PyMac_PRECHECK(CFEqual);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFTypeRefObj_Convert, &cf2))
- return NULL;
- _rv = CFEqual(_self->ob_itself,
- cf2);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFTypeRefObj_Convert, &cf2))
+ return NULL;
+ _rv = CFEqual(_self->ob_itself,
+ cf2);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFHash(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFHashCode _rv;
+ PyObject *_res = NULL;
+ CFHashCode _rv;
#ifndef CFHash
- PyMac_PRECHECK(CFHash);
+ PyMac_PRECHECK(CFHash);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFHash(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFHash(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFCopyDescription(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFCopyDescription
- PyMac_PRECHECK(CFCopyDescription);
+ PyMac_PRECHECK(CFCopyDescription);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFCopyDescription(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFCopyDescription(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFPropertyListCreateXMLData(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDataRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFPropertyListCreateXMLData((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFDataRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFDataRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFPropertyListCreateXMLData((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFPropertyListCreateDeepCopy(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeRef _rv;
- CFOptionFlags mutabilityOption;
- if (!PyArg_ParseTuple(_args, "l",
- &mutabilityOption))
- return NULL;
- _rv = CFPropertyListCreateDeepCopy((CFAllocatorRef)NULL,
- _self->ob_itself,
- mutabilityOption);
- _res = Py_BuildValue("O&",
- CFTypeRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFTypeRef _rv;
+ CFOptionFlags mutabilityOption;
+ if (!PyArg_ParseTuple(_args, "l",
+ &mutabilityOption))
+ return NULL;
+ _rv = CFPropertyListCreateDeepCopy((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ mutabilityOption);
+ _res = Py_BuildValue("O&",
+ CFTypeRefObj_New, _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_CFShow(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CFShow
- PyMac_PRECHECK(CFShow);
+ PyMac_PRECHECK(CFShow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CFShow(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CFShow(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFTypeRefObj_CFPropertyListCreateFromXMLData(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- CFTypeRef _rv;
- CFOptionFlags mutabilityOption;
- CFStringRef errorString;
- if (!PyArg_ParseTuple(_args, "l",
- &mutabilityOption))
- return NULL;
- _rv = CFPropertyListCreateFromXMLData((CFAllocatorRef)NULL,
- _self->ob_itself,
- mutabilityOption,
- &errorString);
- if (errorString)
- CFRelease(errorString);
- if (_rv == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "Parse error in XML data");
- return NULL;
- }
- _res = Py_BuildValue("O&",
- CFTypeRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+
+ CFTypeRef _rv;
+ CFOptionFlags mutabilityOption;
+ CFStringRef errorString;
+ if (!PyArg_ParseTuple(_args, "l",
+ &mutabilityOption))
+ return NULL;
+ _rv = CFPropertyListCreateFromXMLData((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ mutabilityOption,
+ &errorString);
+ if (errorString)
+ CFRelease(errorString);
+ if (_rv == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "Parse error in XML data");
+ return NULL;
+ }
+ _res = Py_BuildValue("O&",
+ CFTypeRefObj_New, _rv);
+ return _res;
}
static PyObject *CFTypeRefObj_toPython(CFTypeRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- _res = PyCF_CF2Python(_self->ob_itself);
- return _res;
+ _res = PyCF_CF2Python(_self->ob_itself);
+ return _res;
}
static PyMethodDef CFTypeRefObj_methods[] = {
- {"CFGetTypeID", (PyCFunction)CFTypeRefObj_CFGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFRetain", (PyCFunction)CFTypeRefObj_CFRetain, 1,
- PyDoc_STR("() -> (CFTypeRef _rv)")},
- {"CFRelease", (PyCFunction)CFTypeRefObj_CFRelease, 1,
- PyDoc_STR("() -> None")},
- {"CFGetRetainCount", (PyCFunction)CFTypeRefObj_CFGetRetainCount, 1,
- PyDoc_STR("() -> (CFIndex _rv)")},
- {"CFEqual", (PyCFunction)CFTypeRefObj_CFEqual, 1,
- PyDoc_STR("(CFTypeRef cf2) -> (Boolean _rv)")},
- {"CFHash", (PyCFunction)CFTypeRefObj_CFHash, 1,
- PyDoc_STR("() -> (CFHashCode _rv)")},
- {"CFCopyDescription", (PyCFunction)CFTypeRefObj_CFCopyDescription, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFPropertyListCreateXMLData", (PyCFunction)CFTypeRefObj_CFPropertyListCreateXMLData, 1,
- PyDoc_STR("() -> (CFDataRef _rv)")},
- {"CFPropertyListCreateDeepCopy", (PyCFunction)CFTypeRefObj_CFPropertyListCreateDeepCopy, 1,
- PyDoc_STR("(CFOptionFlags mutabilityOption) -> (CFTypeRef _rv)")},
- {"CFShow", (PyCFunction)CFTypeRefObj_CFShow, 1,
- PyDoc_STR("() -> None")},
- {"CFPropertyListCreateFromXMLData", (PyCFunction)CFTypeRefObj_CFPropertyListCreateFromXMLData, 1,
- PyDoc_STR("(CFOptionFlags mutabilityOption) -> (CFTypeRefObj)")},
- {"toPython", (PyCFunction)CFTypeRefObj_toPython, 1,
- PyDoc_STR("() -> (python_object)")},
- {NULL, NULL, 0}
+ {"CFGetTypeID", (PyCFunction)CFTypeRefObj_CFGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFRetain", (PyCFunction)CFTypeRefObj_CFRetain, 1,
+ PyDoc_STR("() -> (CFTypeRef _rv)")},
+ {"CFRelease", (PyCFunction)CFTypeRefObj_CFRelease, 1,
+ PyDoc_STR("() -> None")},
+ {"CFGetRetainCount", (PyCFunction)CFTypeRefObj_CFGetRetainCount, 1,
+ PyDoc_STR("() -> (CFIndex _rv)")},
+ {"CFEqual", (PyCFunction)CFTypeRefObj_CFEqual, 1,
+ PyDoc_STR("(CFTypeRef cf2) -> (Boolean _rv)")},
+ {"CFHash", (PyCFunction)CFTypeRefObj_CFHash, 1,
+ PyDoc_STR("() -> (CFHashCode _rv)")},
+ {"CFCopyDescription", (PyCFunction)CFTypeRefObj_CFCopyDescription, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFPropertyListCreateXMLData", (PyCFunction)CFTypeRefObj_CFPropertyListCreateXMLData, 1,
+ PyDoc_STR("() -> (CFDataRef _rv)")},
+ {"CFPropertyListCreateDeepCopy", (PyCFunction)CFTypeRefObj_CFPropertyListCreateDeepCopy, 1,
+ PyDoc_STR("(CFOptionFlags mutabilityOption) -> (CFTypeRef _rv)")},
+ {"CFShow", (PyCFunction)CFTypeRefObj_CFShow, 1,
+ PyDoc_STR("() -> None")},
+ {"CFPropertyListCreateFromXMLData", (PyCFunction)CFTypeRefObj_CFPropertyListCreateFromXMLData, 1,
+ PyDoc_STR("(CFOptionFlags mutabilityOption) -> (CFTypeRefObj)")},
+ {"toPython", (PyCFunction)CFTypeRefObj_toPython, 1,
+ PyDoc_STR("() -> (python_object)")},
+ {NULL, NULL, 0}
};
#define CFTypeRefObj_getsetlist NULL
@@ -382,93 +382,93 @@ static PyMethodDef CFTypeRefObj_methods[] = {
static int CFTypeRefObj_compare(CFTypeRefObject *self, CFTypeRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFTypeRefObj_repr(CFTypeRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFTypeRef type-%d object at 0x%8.8x for 0x%8.8x>", (int)CFGetTypeID(self->ob_itself), (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFTypeRef type-%d object at 0x%8.8x for 0x%8.8x>", (int)CFGetTypeID(self->ob_itself), (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFTypeRefObj_hash(CFTypeRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFTypeRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFTypeRef itself;
- char *kw[] = {"itself", 0};
+ CFTypeRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFTypeRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFTypeRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFTypeRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFTypeRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFTypeRefObject *)self)->ob_itself = NULL;
- ((CFTypeRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFTypeRefObject *)self)->ob_itself = NULL;
+ ((CFTypeRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFTypeRefObj_tp_free PyObject_Del
PyTypeObject CFTypeRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFTypeRef", /*tp_name*/
- sizeof(CFTypeRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFTypeRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFTypeRefObj_compare, /*tp_compare*/
- (reprfunc) CFTypeRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFTypeRefObj_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*/
- CFTypeRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFTypeRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFTypeRefObj_tp_init, /* tp_init */
- CFTypeRefObj_tp_alloc, /* tp_alloc */
- CFTypeRefObj_tp_new, /* tp_new */
- CFTypeRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFTypeRef", /*tp_name*/
+ sizeof(CFTypeRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFTypeRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFTypeRefObj_compare, /*tp_compare*/
+ (reprfunc) CFTypeRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFTypeRefObj_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*/
+ CFTypeRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFTypeRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFTypeRefObj_tp_init, /* tp_init */
+ CFTypeRefObj_tp_alloc, /* tp_alloc */
+ CFTypeRefObj_tp_new, /* tp_new */
+ CFTypeRefObj_tp_free, /* tp_free */
};
/* ------------------- End object type CFTypeRef -------------------- */
@@ -481,104 +481,104 @@ PyTypeObject CFArrayRef_Type;
#define CFArrayRefObj_Check(x) ((x)->ob_type == &CFArrayRef_Type || PyObject_TypeCheck((x), &CFArrayRef_Type))
typedef struct CFArrayRefObject {
- PyObject_HEAD
- CFArrayRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFArrayRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFArrayRefObject;
PyObject *CFArrayRefObj_New(CFArrayRef itself)
{
- CFArrayRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFArrayRefObject, &CFArrayRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFArrayRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFArrayRefObject, &CFArrayRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFArrayRefObj_Convert(PyObject *v, CFArrayRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFArrayRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFArrayRef required");
- return 0;
- }
- *p_itself = ((CFArrayRefObject *)v)->ob_itself;
- return 1;
+ if (!CFArrayRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFArrayRef required");
+ return 0;
+ }
+ *p_itself = ((CFArrayRefObject *)v)->ob_itself;
+ return 1;
}
static void CFArrayRefObj_dealloc(CFArrayRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFTypeRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFTypeRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFArrayRefObj_CFArrayCreateCopy(CFArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFArrayRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFArrayCreateCopy((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFArrayRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFArrayRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFArrayCreateCopy((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CFArrayRefObj_CFArrayGetCount(CFArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
+ PyObject *_res = NULL;
+ CFIndex _rv;
#ifndef CFArrayGetCount
- PyMac_PRECHECK(CFArrayGetCount);
+ PyMac_PRECHECK(CFArrayGetCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFArrayGetCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFArrayGetCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFArrayRefObj_CFStringCreateByCombiningStrings(CFArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringRef separatorString;
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &separatorString))
- return NULL;
- _rv = CFStringCreateByCombiningStrings((CFAllocatorRef)NULL,
- _self->ob_itself,
- separatorString);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringRef separatorString;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &separatorString))
+ return NULL;
+ _rv = CFStringCreateByCombiningStrings((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ separatorString);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyMethodDef CFArrayRefObj_methods[] = {
- {"CFArrayCreateCopy", (PyCFunction)CFArrayRefObj_CFArrayCreateCopy, 1,
- PyDoc_STR("() -> (CFArrayRef _rv)")},
- {"CFArrayGetCount", (PyCFunction)CFArrayRefObj_CFArrayGetCount, 1,
- PyDoc_STR("() -> (CFIndex _rv)")},
- {"CFStringCreateByCombiningStrings", (PyCFunction)CFArrayRefObj_CFStringCreateByCombiningStrings, 1,
- PyDoc_STR("(CFStringRef separatorString) -> (CFStringRef _rv)")},
- {NULL, NULL, 0}
+ {"CFArrayCreateCopy", (PyCFunction)CFArrayRefObj_CFArrayCreateCopy, 1,
+ PyDoc_STR("() -> (CFArrayRef _rv)")},
+ {"CFArrayGetCount", (PyCFunction)CFArrayRefObj_CFArrayGetCount, 1,
+ PyDoc_STR("() -> (CFIndex _rv)")},
+ {"CFStringCreateByCombiningStrings", (PyCFunction)CFArrayRefObj_CFStringCreateByCombiningStrings, 1,
+ PyDoc_STR("(CFStringRef separatorString) -> (CFStringRef _rv)")},
+ {NULL, NULL, 0}
};
#define CFArrayRefObj_getsetlist NULL
@@ -586,100 +586,100 @@ static PyMethodDef CFArrayRefObj_methods[] = {
static int CFArrayRefObj_compare(CFArrayRefObject *self, CFArrayRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFArrayRefObj_repr(CFArrayRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFArrayRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFArrayRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFArrayRefObj_hash(CFArrayRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFArrayRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFArrayRef itself;
- char *kw[] = {"itself", 0};
+ CFArrayRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFArrayRefObj_Convert, &itself))
- {
- ((CFArrayRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFArrayRefObj_Convert, &itself))
+ {
+ ((CFArrayRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFArrayRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFArrayRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFArrayRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFArrayRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFArrayRefObject *)self)->ob_itself = NULL;
- ((CFArrayRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFArrayRefObject *)self)->ob_itself = NULL;
+ ((CFArrayRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFArrayRefObj_tp_free PyObject_Del
PyTypeObject CFArrayRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFArrayRef", /*tp_name*/
- sizeof(CFArrayRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFArrayRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFArrayRefObj_compare, /*tp_compare*/
- (reprfunc) CFArrayRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFArrayRefObj_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*/
- CFArrayRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFArrayRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFArrayRefObj_tp_init, /* tp_init */
- CFArrayRefObj_tp_alloc, /* tp_alloc */
- CFArrayRefObj_tp_new, /* tp_new */
- CFArrayRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFArrayRef", /*tp_name*/
+ sizeof(CFArrayRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFArrayRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFArrayRefObj_compare, /*tp_compare*/
+ (reprfunc) CFArrayRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFArrayRefObj_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*/
+ CFArrayRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFArrayRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFArrayRefObj_tp_init, /* tp_init */
+ CFArrayRefObj_tp_alloc, /* tp_alloc */
+ CFArrayRefObj_tp_new, /* tp_new */
+ CFArrayRefObj_tp_free, /* tp_free */
};
/* ------------------- End object type CFArrayRef ------------------- */
@@ -692,133 +692,133 @@ PyTypeObject CFMutableArrayRef_Type;
#define CFMutableArrayRefObj_Check(x) ((x)->ob_type == &CFMutableArrayRef_Type || PyObject_TypeCheck((x), &CFMutableArrayRef_Type))
typedef struct CFMutableArrayRefObject {
- PyObject_HEAD
- CFMutableArrayRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFMutableArrayRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFMutableArrayRefObject;
PyObject *CFMutableArrayRefObj_New(CFMutableArrayRef itself)
{
- CFMutableArrayRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFMutableArrayRefObject, &CFMutableArrayRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFMutableArrayRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFMutableArrayRefObject, &CFMutableArrayRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFMutableArrayRefObj_Convert(PyObject *v, CFMutableArrayRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFMutableArrayRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFMutableArrayRef required");
- return 0;
- }
- *p_itself = ((CFMutableArrayRefObject *)v)->ob_itself;
- return 1;
+ if (!CFMutableArrayRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFMutableArrayRef required");
+ return 0;
+ }
+ *p_itself = ((CFMutableArrayRefObject *)v)->ob_itself;
+ return 1;
}
static void CFMutableArrayRefObj_dealloc(CFMutableArrayRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFArrayRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFArrayRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFMutableArrayRefObj_CFArrayRemoveValueAtIndex(CFMutableArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex idx;
+ PyObject *_res = NULL;
+ CFIndex idx;
#ifndef CFArrayRemoveValueAtIndex
- PyMac_PRECHECK(CFArrayRemoveValueAtIndex);
+ PyMac_PRECHECK(CFArrayRemoveValueAtIndex);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &idx))
- return NULL;
- CFArrayRemoveValueAtIndex(_self->ob_itself,
- idx);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &idx))
+ return NULL;
+ CFArrayRemoveValueAtIndex(_self->ob_itself,
+ idx);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableArrayRefObj_CFArrayRemoveAllValues(CFMutableArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CFArrayRemoveAllValues
- PyMac_PRECHECK(CFArrayRemoveAllValues);
+ PyMac_PRECHECK(CFArrayRemoveAllValues);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CFArrayRemoveAllValues(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CFArrayRemoveAllValues(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableArrayRefObj_CFArrayExchangeValuesAtIndices(CFMutableArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex idx1;
- CFIndex idx2;
+ PyObject *_res = NULL;
+ CFIndex idx1;
+ CFIndex idx2;
#ifndef CFArrayExchangeValuesAtIndices
- PyMac_PRECHECK(CFArrayExchangeValuesAtIndices);
+ PyMac_PRECHECK(CFArrayExchangeValuesAtIndices);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &idx1,
- &idx2))
- return NULL;
- CFArrayExchangeValuesAtIndices(_self->ob_itself,
- idx1,
- idx2);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &idx1,
+ &idx2))
+ return NULL;
+ CFArrayExchangeValuesAtIndices(_self->ob_itself,
+ idx1,
+ idx2);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableArrayRefObj_CFArrayAppendArray(CFMutableArrayRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFArrayRef otherArray;
- CFRange otherRange;
+ PyObject *_res = NULL;
+ CFArrayRef otherArray;
+ CFRange otherRange;
#ifndef CFArrayAppendArray
- PyMac_PRECHECK(CFArrayAppendArray);
+ PyMac_PRECHECK(CFArrayAppendArray);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFArrayRefObj_Convert, &otherArray,
- CFRange_Convert, &otherRange))
- return NULL;
- CFArrayAppendArray(_self->ob_itself,
- otherArray,
- otherRange);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFArrayRefObj_Convert, &otherArray,
+ CFRange_Convert, &otherRange))
+ return NULL;
+ CFArrayAppendArray(_self->ob_itself,
+ otherArray,
+ otherRange);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef CFMutableArrayRefObj_methods[] = {
- {"CFArrayRemoveValueAtIndex", (PyCFunction)CFMutableArrayRefObj_CFArrayRemoveValueAtIndex, 1,
- PyDoc_STR("(CFIndex idx) -> None")},
- {"CFArrayRemoveAllValues", (PyCFunction)CFMutableArrayRefObj_CFArrayRemoveAllValues, 1,
- PyDoc_STR("() -> None")},
- {"CFArrayExchangeValuesAtIndices", (PyCFunction)CFMutableArrayRefObj_CFArrayExchangeValuesAtIndices, 1,
- PyDoc_STR("(CFIndex idx1, CFIndex idx2) -> None")},
- {"CFArrayAppendArray", (PyCFunction)CFMutableArrayRefObj_CFArrayAppendArray, 1,
- PyDoc_STR("(CFArrayRef otherArray, CFRange otherRange) -> None")},
- {NULL, NULL, 0}
+ {"CFArrayRemoveValueAtIndex", (PyCFunction)CFMutableArrayRefObj_CFArrayRemoveValueAtIndex, 1,
+ PyDoc_STR("(CFIndex idx) -> None")},
+ {"CFArrayRemoveAllValues", (PyCFunction)CFMutableArrayRefObj_CFArrayRemoveAllValues, 1,
+ PyDoc_STR("() -> None")},
+ {"CFArrayExchangeValuesAtIndices", (PyCFunction)CFMutableArrayRefObj_CFArrayExchangeValuesAtIndices, 1,
+ PyDoc_STR("(CFIndex idx1, CFIndex idx2) -> None")},
+ {"CFArrayAppendArray", (PyCFunction)CFMutableArrayRefObj_CFArrayAppendArray, 1,
+ PyDoc_STR("(CFArrayRef otherArray, CFRange otherRange) -> None")},
+ {NULL, NULL, 0}
};
#define CFMutableArrayRefObj_getsetlist NULL
@@ -826,100 +826,100 @@ static PyMethodDef CFMutableArrayRefObj_methods[] = {
static int CFMutableArrayRefObj_compare(CFMutableArrayRefObject *self, CFMutableArrayRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFMutableArrayRefObj_repr(CFMutableArrayRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFMutableArrayRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFMutableArrayRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFMutableArrayRefObj_hash(CFMutableArrayRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFMutableArrayRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFMutableArrayRef itself;
- char *kw[] = {"itself", 0};
+ CFMutableArrayRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableArrayRefObj_Convert, &itself))
- {
- ((CFMutableArrayRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableArrayRefObj_Convert, &itself))
+ {
+ ((CFMutableArrayRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFMutableArrayRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFMutableArrayRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFMutableArrayRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFMutableArrayRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFMutableArrayRefObject *)self)->ob_itself = NULL;
- ((CFMutableArrayRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFMutableArrayRefObject *)self)->ob_itself = NULL;
+ ((CFMutableArrayRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFMutableArrayRefObj_tp_free PyObject_Del
PyTypeObject CFMutableArrayRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFMutableArrayRef", /*tp_name*/
- sizeof(CFMutableArrayRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFMutableArrayRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFMutableArrayRefObj_compare, /*tp_compare*/
- (reprfunc) CFMutableArrayRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFMutableArrayRefObj_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*/
- CFMutableArrayRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFMutableArrayRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFMutableArrayRefObj_tp_init, /* tp_init */
- CFMutableArrayRefObj_tp_alloc, /* tp_alloc */
- CFMutableArrayRefObj_tp_new, /* tp_new */
- CFMutableArrayRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFMutableArrayRef", /*tp_name*/
+ sizeof(CFMutableArrayRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFMutableArrayRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFMutableArrayRefObj_compare, /*tp_compare*/
+ (reprfunc) CFMutableArrayRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFMutableArrayRefObj_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*/
+ CFMutableArrayRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFMutableArrayRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFMutableArrayRefObj_tp_init, /* tp_init */
+ CFMutableArrayRefObj_tp_alloc, /* tp_alloc */
+ CFMutableArrayRefObj_tp_new, /* tp_new */
+ CFMutableArrayRefObj_tp_free, /* tp_free */
};
/* --------------- End object type CFMutableArrayRef ---------------- */
@@ -932,86 +932,86 @@ PyTypeObject CFDictionaryRef_Type;
#define CFDictionaryRefObj_Check(x) ((x)->ob_type == &CFDictionaryRef_Type || PyObject_TypeCheck((x), &CFDictionaryRef_Type))
typedef struct CFDictionaryRefObject {
- PyObject_HEAD
- CFDictionaryRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFDictionaryRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFDictionaryRefObject;
PyObject *CFDictionaryRefObj_New(CFDictionaryRef itself)
{
- CFDictionaryRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFDictionaryRefObject, &CFDictionaryRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFDictionaryRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFDictionaryRefObject, &CFDictionaryRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFDictionaryRefObj_Convert(PyObject *v, CFDictionaryRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFDictionaryRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFDictionaryRef required");
- return 0;
- }
- *p_itself = ((CFDictionaryRefObject *)v)->ob_itself;
- return 1;
+ if (!CFDictionaryRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFDictionaryRef required");
+ return 0;
+ }
+ *p_itself = ((CFDictionaryRefObject *)v)->ob_itself;
+ return 1;
}
static void CFDictionaryRefObj_dealloc(CFDictionaryRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFTypeRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFTypeRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFDictionaryRefObj_CFDictionaryCreateCopy(CFDictionaryRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDictionaryRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFDictionaryCreateCopy((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFDictionaryRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFDictionaryRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFDictionaryCreateCopy((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFDictionaryRefObj_New, _rv);
+ return _res;
}
static PyObject *CFDictionaryRefObj_CFDictionaryGetCount(CFDictionaryRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
+ PyObject *_res = NULL;
+ CFIndex _rv;
#ifndef CFDictionaryGetCount
- PyMac_PRECHECK(CFDictionaryGetCount);
+ PyMac_PRECHECK(CFDictionaryGetCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFDictionaryGetCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFDictionaryGetCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyMethodDef CFDictionaryRefObj_methods[] = {
- {"CFDictionaryCreateCopy", (PyCFunction)CFDictionaryRefObj_CFDictionaryCreateCopy, 1,
- PyDoc_STR("() -> (CFDictionaryRef _rv)")},
- {"CFDictionaryGetCount", (PyCFunction)CFDictionaryRefObj_CFDictionaryGetCount, 1,
- PyDoc_STR("() -> (CFIndex _rv)")},
- {NULL, NULL, 0}
+ {"CFDictionaryCreateCopy", (PyCFunction)CFDictionaryRefObj_CFDictionaryCreateCopy, 1,
+ PyDoc_STR("() -> (CFDictionaryRef _rv)")},
+ {"CFDictionaryGetCount", (PyCFunction)CFDictionaryRefObj_CFDictionaryGetCount, 1,
+ PyDoc_STR("() -> (CFIndex _rv)")},
+ {NULL, NULL, 0}
};
#define CFDictionaryRefObj_getsetlist NULL
@@ -1019,100 +1019,100 @@ static PyMethodDef CFDictionaryRefObj_methods[] = {
static int CFDictionaryRefObj_compare(CFDictionaryRefObject *self, CFDictionaryRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFDictionaryRefObj_repr(CFDictionaryRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFDictionaryRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFDictionaryRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFDictionaryRefObj_hash(CFDictionaryRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFDictionaryRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFDictionaryRef itself;
- char *kw[] = {"itself", 0};
+ CFDictionaryRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFDictionaryRefObj_Convert, &itself))
- {
- ((CFDictionaryRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFDictionaryRefObj_Convert, &itself))
+ {
+ ((CFDictionaryRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFDictionaryRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFDictionaryRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFDictionaryRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFDictionaryRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFDictionaryRefObject *)self)->ob_itself = NULL;
- ((CFDictionaryRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFDictionaryRefObject *)self)->ob_itself = NULL;
+ ((CFDictionaryRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFDictionaryRefObj_tp_free PyObject_Del
PyTypeObject CFDictionaryRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFDictionaryRef", /*tp_name*/
- sizeof(CFDictionaryRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFDictionaryRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFDictionaryRefObj_compare, /*tp_compare*/
- (reprfunc) CFDictionaryRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFDictionaryRefObj_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*/
- CFDictionaryRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFDictionaryRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFDictionaryRefObj_tp_init, /* tp_init */
- CFDictionaryRefObj_tp_alloc, /* tp_alloc */
- CFDictionaryRefObj_tp_new, /* tp_new */
- CFDictionaryRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFDictionaryRef", /*tp_name*/
+ sizeof(CFDictionaryRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFDictionaryRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFDictionaryRefObj_compare, /*tp_compare*/
+ (reprfunc) CFDictionaryRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFDictionaryRefObj_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*/
+ CFDictionaryRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFDictionaryRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFDictionaryRefObj_tp_init, /* tp_init */
+ CFDictionaryRefObj_tp_alloc, /* tp_alloc */
+ CFDictionaryRefObj_tp_new, /* tp_new */
+ CFDictionaryRefObj_tp_free, /* tp_free */
};
/* ---------------- End object type CFDictionaryRef ----------------- */
@@ -1125,70 +1125,70 @@ PyTypeObject CFMutableDictionaryRef_Type;
#define CFMutableDictionaryRefObj_Check(x) ((x)->ob_type == &CFMutableDictionaryRef_Type || PyObject_TypeCheck((x), &CFMutableDictionaryRef_Type))
typedef struct CFMutableDictionaryRefObject {
- PyObject_HEAD
- CFMutableDictionaryRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFMutableDictionaryRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFMutableDictionaryRefObject;
PyObject *CFMutableDictionaryRefObj_New(CFMutableDictionaryRef itself)
{
- CFMutableDictionaryRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFMutableDictionaryRefObject, &CFMutableDictionaryRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFMutableDictionaryRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFMutableDictionaryRefObject, &CFMutableDictionaryRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFMutableDictionaryRefObj_Convert(PyObject *v, CFMutableDictionaryRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFMutableDictionaryRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFMutableDictionaryRef required");
- return 0;
- }
- *p_itself = ((CFMutableDictionaryRefObject *)v)->ob_itself;
- return 1;
+ if (!CFMutableDictionaryRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFMutableDictionaryRef required");
+ return 0;
+ }
+ *p_itself = ((CFMutableDictionaryRefObject *)v)->ob_itself;
+ return 1;
}
static void CFMutableDictionaryRefObj_dealloc(CFMutableDictionaryRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFDictionaryRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFDictionaryRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFMutableDictionaryRefObj_CFDictionaryRemoveAllValues(CFMutableDictionaryRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CFDictionaryRemoveAllValues
- PyMac_PRECHECK(CFDictionaryRemoveAllValues);
+ PyMac_PRECHECK(CFDictionaryRemoveAllValues);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CFDictionaryRemoveAllValues(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CFDictionaryRemoveAllValues(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef CFMutableDictionaryRefObj_methods[] = {
- {"CFDictionaryRemoveAllValues", (PyCFunction)CFMutableDictionaryRefObj_CFDictionaryRemoveAllValues, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"CFDictionaryRemoveAllValues", (PyCFunction)CFMutableDictionaryRefObj_CFDictionaryRemoveAllValues, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define CFMutableDictionaryRefObj_getsetlist NULL
@@ -1196,100 +1196,100 @@ static PyMethodDef CFMutableDictionaryRefObj_methods[] = {
static int CFMutableDictionaryRefObj_compare(CFMutableDictionaryRefObject *self, CFMutableDictionaryRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFMutableDictionaryRefObj_repr(CFMutableDictionaryRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFMutableDictionaryRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFMutableDictionaryRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFMutableDictionaryRefObj_hash(CFMutableDictionaryRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFMutableDictionaryRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFMutableDictionaryRef itself;
- char *kw[] = {"itself", 0};
+ CFMutableDictionaryRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableDictionaryRefObj_Convert, &itself))
- {
- ((CFMutableDictionaryRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableDictionaryRefObj_Convert, &itself))
+ {
+ ((CFMutableDictionaryRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFMutableDictionaryRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFMutableDictionaryRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFMutableDictionaryRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFMutableDictionaryRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFMutableDictionaryRefObject *)self)->ob_itself = NULL;
- ((CFMutableDictionaryRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFMutableDictionaryRefObject *)self)->ob_itself = NULL;
+ ((CFMutableDictionaryRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFMutableDictionaryRefObj_tp_free PyObject_Del
PyTypeObject CFMutableDictionaryRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFMutableDictionaryRef", /*tp_name*/
- sizeof(CFMutableDictionaryRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFMutableDictionaryRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFMutableDictionaryRefObj_compare, /*tp_compare*/
- (reprfunc) CFMutableDictionaryRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFMutableDictionaryRefObj_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*/
- CFMutableDictionaryRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFMutableDictionaryRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFMutableDictionaryRefObj_tp_init, /* tp_init */
- CFMutableDictionaryRefObj_tp_alloc, /* tp_alloc */
- CFMutableDictionaryRefObj_tp_new, /* tp_new */
- CFMutableDictionaryRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFMutableDictionaryRef", /*tp_name*/
+ sizeof(CFMutableDictionaryRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFMutableDictionaryRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFMutableDictionaryRefObj_compare, /*tp_compare*/
+ (reprfunc) CFMutableDictionaryRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFMutableDictionaryRefObj_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*/
+ CFMutableDictionaryRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFMutableDictionaryRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFMutableDictionaryRefObj_tp_init, /* tp_init */
+ CFMutableDictionaryRefObj_tp_alloc, /* tp_alloc */
+ CFMutableDictionaryRefObj_tp_new, /* tp_new */
+ CFMutableDictionaryRefObj_tp_free, /* tp_free */
};
/* ------------- End object type CFMutableDictionaryRef ------------- */
@@ -1302,124 +1302,124 @@ PyTypeObject CFDataRef_Type;
#define CFDataRefObj_Check(x) ((x)->ob_type == &CFDataRef_Type || PyObject_TypeCheck((x), &CFDataRef_Type))
typedef struct CFDataRefObject {
- PyObject_HEAD
- CFDataRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFDataRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFDataRefObject;
PyObject *CFDataRefObj_New(CFDataRef itself)
{
- CFDataRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFDataRefObject, &CFDataRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFDataRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFDataRefObject, &CFDataRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFDataRefObj_Convert(PyObject *v, CFDataRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- if (PyString_Check(v)) {
- char *cStr;
- Py_ssize_t cLen;
- if( PyString_AsStringAndSize(v, &cStr, &cLen) < 0 ) return 0;
- *p_itself = CFDataCreate((CFAllocatorRef)NULL, (unsigned char *)cStr, cLen);
- return 1;
- }
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ if (PyString_Check(v)) {
+ char *cStr;
+ Py_ssize_t cLen;
+ if( PyString_AsStringAndSize(v, &cStr, &cLen) < 0 ) return 0;
+ *p_itself = CFDataCreate((CFAllocatorRef)NULL, (unsigned char *)cStr, cLen);
+ return 1;
+ }
- if (!CFDataRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFDataRef required");
- return 0;
- }
- *p_itself = ((CFDataRefObject *)v)->ob_itself;
- return 1;
+ if (!CFDataRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFDataRef required");
+ return 0;
+ }
+ *p_itself = ((CFDataRefObject *)v)->ob_itself;
+ return 1;
}
static void CFDataRefObj_dealloc(CFDataRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFTypeRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFTypeRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFDataRefObj_CFDataCreateCopy(CFDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDataRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFDataCreateCopy((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFDataRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFDataRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFDataCreateCopy((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CFDataRefObj_CFDataGetLength(CFDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
+ PyObject *_res = NULL;
+ CFIndex _rv;
#ifndef CFDataGetLength
- PyMac_PRECHECK(CFDataGetLength);
+ PyMac_PRECHECK(CFDataGetLength);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFDataGetLength(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFDataGetLength(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFDataRefObj_CFStringCreateFromExternalRepresentation(CFDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringEncoding encoding;
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringCreateFromExternalRepresentation((CFAllocatorRef)NULL,
- _self->ob_itself,
- encoding);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringEncoding encoding;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringCreateFromExternalRepresentation((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ encoding);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFDataRefObj_CFDataGetData(CFDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int size = CFDataGetLength(_self->ob_itself);
- char *data = (char *)CFDataGetBytePtr(_self->ob_itself);
+ int size = CFDataGetLength(_self->ob_itself);
+ char *data = (char *)CFDataGetBytePtr(_self->ob_itself);
- _res = (PyObject *)PyString_FromStringAndSize(data, size);
- return _res;
+ _res = (PyObject *)PyString_FromStringAndSize(data, size);
+ return _res;
}
static PyMethodDef CFDataRefObj_methods[] = {
- {"CFDataCreateCopy", (PyCFunction)CFDataRefObj_CFDataCreateCopy, 1,
- PyDoc_STR("() -> (CFDataRef _rv)")},
- {"CFDataGetLength", (PyCFunction)CFDataRefObj_CFDataGetLength, 1,
- PyDoc_STR("() -> (CFIndex _rv)")},
- {"CFStringCreateFromExternalRepresentation", (PyCFunction)CFDataRefObj_CFStringCreateFromExternalRepresentation, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFDataGetData", (PyCFunction)CFDataRefObj_CFDataGetData, 1,
- PyDoc_STR("() -> (string _rv)")},
- {NULL, NULL, 0}
+ {"CFDataCreateCopy", (PyCFunction)CFDataRefObj_CFDataCreateCopy, 1,
+ PyDoc_STR("() -> (CFDataRef _rv)")},
+ {"CFDataGetLength", (PyCFunction)CFDataRefObj_CFDataGetLength, 1,
+ PyDoc_STR("() -> (CFIndex _rv)")},
+ {"CFStringCreateFromExternalRepresentation", (PyCFunction)CFDataRefObj_CFStringCreateFromExternalRepresentation, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFDataGetData", (PyCFunction)CFDataRefObj_CFDataGetData, 1,
+ PyDoc_STR("() -> (string _rv)")},
+ {NULL, NULL, 0}
};
#define CFDataRefObj_getsetlist NULL
@@ -1427,100 +1427,100 @@ static PyMethodDef CFDataRefObj_methods[] = {
static int CFDataRefObj_compare(CFDataRefObject *self, CFDataRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFDataRefObj_repr(CFDataRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFDataRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFDataRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFDataRefObj_hash(CFDataRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFDataRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFDataRef itself;
- char *kw[] = {"itself", 0};
+ CFDataRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFDataRefObj_Convert, &itself))
- {
- ((CFDataRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFDataRefObj_Convert, &itself))
+ {
+ ((CFDataRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFDataRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFDataRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFDataRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFDataRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFDataRefObject *)self)->ob_itself = NULL;
- ((CFDataRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFDataRefObject *)self)->ob_itself = NULL;
+ ((CFDataRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFDataRefObj_tp_free PyObject_Del
PyTypeObject CFDataRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFDataRef", /*tp_name*/
- sizeof(CFDataRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFDataRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFDataRefObj_compare, /*tp_compare*/
- (reprfunc) CFDataRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFDataRefObj_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*/
- CFDataRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFDataRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFDataRefObj_tp_init, /* tp_init */
- CFDataRefObj_tp_alloc, /* tp_alloc */
- CFDataRefObj_tp_new, /* tp_new */
- CFDataRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFDataRef", /*tp_name*/
+ sizeof(CFDataRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFDataRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFDataRefObj_compare, /*tp_compare*/
+ (reprfunc) CFDataRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFDataRefObj_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*/
+ CFDataRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFDataRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFDataRefObj_tp_init, /* tp_init */
+ CFDataRefObj_tp_alloc, /* tp_alloc */
+ CFDataRefObj_tp_new, /* tp_new */
+ CFDataRefObj_tp_free, /* tp_free */
};
/* ------------------- End object type CFDataRef -------------------- */
@@ -1533,158 +1533,158 @@ PyTypeObject CFMutableDataRef_Type;
#define CFMutableDataRefObj_Check(x) ((x)->ob_type == &CFMutableDataRef_Type || PyObject_TypeCheck((x), &CFMutableDataRef_Type))
typedef struct CFMutableDataRefObject {
- PyObject_HEAD
- CFMutableDataRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFMutableDataRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFMutableDataRefObject;
PyObject *CFMutableDataRefObj_New(CFMutableDataRef itself)
{
- CFMutableDataRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFMutableDataRefObject, &CFMutableDataRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFMutableDataRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFMutableDataRefObject, &CFMutableDataRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFMutableDataRefObj_Convert(PyObject *v, CFMutableDataRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFMutableDataRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFMutableDataRef required");
- return 0;
- }
- *p_itself = ((CFMutableDataRefObject *)v)->ob_itself;
- return 1;
+ if (!CFMutableDataRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFMutableDataRef required");
+ return 0;
+ }
+ *p_itself = ((CFMutableDataRefObject *)v)->ob_itself;
+ return 1;
}
static void CFMutableDataRefObj_dealloc(CFMutableDataRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFDataRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFDataRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFMutableDataRefObj_CFDataSetLength(CFMutableDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex length;
+ PyObject *_res = NULL;
+ CFIndex length;
#ifndef CFDataSetLength
- PyMac_PRECHECK(CFDataSetLength);
+ PyMac_PRECHECK(CFDataSetLength);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &length))
- return NULL;
- CFDataSetLength(_self->ob_itself,
- length);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &length))
+ return NULL;
+ CFDataSetLength(_self->ob_itself,
+ length);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableDataRefObj_CFDataIncreaseLength(CFMutableDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex extraLength;
+ PyObject *_res = NULL;
+ CFIndex extraLength;
#ifndef CFDataIncreaseLength
- PyMac_PRECHECK(CFDataIncreaseLength);
+ PyMac_PRECHECK(CFDataIncreaseLength);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &extraLength))
- return NULL;
- CFDataIncreaseLength(_self->ob_itself,
- extraLength);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &extraLength))
+ return NULL;
+ CFDataIncreaseLength(_self->ob_itself,
+ extraLength);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableDataRefObj_CFDataAppendBytes(CFMutableDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned char *bytes__in__;
- long bytes__len__;
- int bytes__in_len__;
+ PyObject *_res = NULL;
+ unsigned char *bytes__in__;
+ long bytes__len__;
+ int bytes__in_len__;
#ifndef CFDataAppendBytes
- PyMac_PRECHECK(CFDataAppendBytes);
+ PyMac_PRECHECK(CFDataAppendBytes);
#endif
- if (!PyArg_ParseTuple(_args, "s#",
- &bytes__in__, &bytes__in_len__))
- return NULL;
- bytes__len__ = bytes__in_len__;
- CFDataAppendBytes(_self->ob_itself,
- bytes__in__, bytes__len__);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#",
+ &bytes__in__, &bytes__in_len__))
+ return NULL;
+ bytes__len__ = bytes__in_len__;
+ CFDataAppendBytes(_self->ob_itself,
+ bytes__in__, bytes__len__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableDataRefObj_CFDataReplaceBytes(CFMutableDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange range;
- unsigned char *newBytes__in__;
- long newBytes__len__;
- int newBytes__in_len__;
+ PyObject *_res = NULL;
+ CFRange range;
+ unsigned char *newBytes__in__;
+ long newBytes__len__;
+ int newBytes__in_len__;
#ifndef CFDataReplaceBytes
- PyMac_PRECHECK(CFDataReplaceBytes);
+ PyMac_PRECHECK(CFDataReplaceBytes);
#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- CFRange_Convert, &range,
- &newBytes__in__, &newBytes__in_len__))
- return NULL;
- newBytes__len__ = newBytes__in_len__;
- CFDataReplaceBytes(_self->ob_itself,
- range,
- newBytes__in__, newBytes__len__);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ CFRange_Convert, &range,
+ &newBytes__in__, &newBytes__in_len__))
+ return NULL;
+ newBytes__len__ = newBytes__in_len__;
+ CFDataReplaceBytes(_self->ob_itself,
+ range,
+ newBytes__in__, newBytes__len__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableDataRefObj_CFDataDeleteBytes(CFMutableDataRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange range;
+ PyObject *_res = NULL;
+ CFRange range;
#ifndef CFDataDeleteBytes
- PyMac_PRECHECK(CFDataDeleteBytes);
+ PyMac_PRECHECK(CFDataDeleteBytes);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFRange_Convert, &range))
- return NULL;
- CFDataDeleteBytes(_self->ob_itself,
- range);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFRange_Convert, &range))
+ return NULL;
+ CFDataDeleteBytes(_self->ob_itself,
+ range);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef CFMutableDataRefObj_methods[] = {
- {"CFDataSetLength", (PyCFunction)CFMutableDataRefObj_CFDataSetLength, 1,
- PyDoc_STR("(CFIndex length) -> None")},
- {"CFDataIncreaseLength", (PyCFunction)CFMutableDataRefObj_CFDataIncreaseLength, 1,
- PyDoc_STR("(CFIndex extraLength) -> None")},
- {"CFDataAppendBytes", (PyCFunction)CFMutableDataRefObj_CFDataAppendBytes, 1,
- PyDoc_STR("(Buffer bytes) -> None")},
- {"CFDataReplaceBytes", (PyCFunction)CFMutableDataRefObj_CFDataReplaceBytes, 1,
- PyDoc_STR("(CFRange range, Buffer newBytes) -> None")},
- {"CFDataDeleteBytes", (PyCFunction)CFMutableDataRefObj_CFDataDeleteBytes, 1,
- PyDoc_STR("(CFRange range) -> None")},
- {NULL, NULL, 0}
+ {"CFDataSetLength", (PyCFunction)CFMutableDataRefObj_CFDataSetLength, 1,
+ PyDoc_STR("(CFIndex length) -> None")},
+ {"CFDataIncreaseLength", (PyCFunction)CFMutableDataRefObj_CFDataIncreaseLength, 1,
+ PyDoc_STR("(CFIndex extraLength) -> None")},
+ {"CFDataAppendBytes", (PyCFunction)CFMutableDataRefObj_CFDataAppendBytes, 1,
+ PyDoc_STR("(Buffer bytes) -> None")},
+ {"CFDataReplaceBytes", (PyCFunction)CFMutableDataRefObj_CFDataReplaceBytes, 1,
+ PyDoc_STR("(CFRange range, Buffer newBytes) -> None")},
+ {"CFDataDeleteBytes", (PyCFunction)CFMutableDataRefObj_CFDataDeleteBytes, 1,
+ PyDoc_STR("(CFRange range) -> None")},
+ {NULL, NULL, 0}
};
#define CFMutableDataRefObj_getsetlist NULL
@@ -1692,100 +1692,100 @@ static PyMethodDef CFMutableDataRefObj_methods[] = {
static int CFMutableDataRefObj_compare(CFMutableDataRefObject *self, CFMutableDataRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFMutableDataRefObj_repr(CFMutableDataRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFMutableDataRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFMutableDataRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFMutableDataRefObj_hash(CFMutableDataRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFMutableDataRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFMutableDataRef itself;
- char *kw[] = {"itself", 0};
+ CFMutableDataRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableDataRefObj_Convert, &itself))
- {
- ((CFMutableDataRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableDataRefObj_Convert, &itself))
+ {
+ ((CFMutableDataRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFMutableDataRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFMutableDataRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFMutableDataRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFMutableDataRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFMutableDataRefObject *)self)->ob_itself = NULL;
- ((CFMutableDataRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFMutableDataRefObject *)self)->ob_itself = NULL;
+ ((CFMutableDataRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFMutableDataRefObj_tp_free PyObject_Del
PyTypeObject CFMutableDataRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFMutableDataRef", /*tp_name*/
- sizeof(CFMutableDataRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFMutableDataRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFMutableDataRefObj_compare, /*tp_compare*/
- (reprfunc) CFMutableDataRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFMutableDataRefObj_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*/
- CFMutableDataRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFMutableDataRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFMutableDataRefObj_tp_init, /* tp_init */
- CFMutableDataRefObj_tp_alloc, /* tp_alloc */
- CFMutableDataRefObj_tp_new, /* tp_new */
- CFMutableDataRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFMutableDataRef", /*tp_name*/
+ sizeof(CFMutableDataRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFMutableDataRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFMutableDataRefObj_compare, /*tp_compare*/
+ (reprfunc) CFMutableDataRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFMutableDataRefObj_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*/
+ CFMutableDataRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFMutableDataRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFMutableDataRefObj_tp_init, /* tp_init */
+ CFMutableDataRefObj_tp_alloc, /* tp_alloc */
+ CFMutableDataRefObj_tp_new, /* tp_new */
+ CFMutableDataRefObj_tp_free, /* tp_free */
};
/* ---------------- End object type CFMutableDataRef ---------------- */
@@ -1798,636 +1798,636 @@ PyTypeObject CFStringRef_Type;
#define CFStringRefObj_Check(x) ((x)->ob_type == &CFStringRef_Type || PyObject_TypeCheck((x), &CFStringRef_Type))
typedef struct CFStringRefObject {
- PyObject_HEAD
- CFStringRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFStringRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFStringRefObject;
PyObject *CFStringRefObj_New(CFStringRef itself)
{
- CFStringRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFStringRefObject, &CFStringRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFStringRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFStringRefObject, &CFStringRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFStringRefObj_Convert(PyObject *v, CFStringRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- if (PyString_Check(v)) {
- char *cStr;
- if (!PyArg_Parse(v, "es", "ascii", &cStr))
- return 0;
- *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII);
- PyMem_Free(cStr);
- return 1;
- }
- if (PyUnicode_Check(v)) {
- /* We use the CF types here, if Python was configured differently that will give an error */
- CFIndex size = PyUnicode_GetSize(v);
- UniChar *unichars = PyUnicode_AsUnicode(v);
- if (!unichars) return 0;
- *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size);
- return 1;
- }
-
-
- if (!CFStringRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFStringRef required");
- return 0;
- }
- *p_itself = ((CFStringRefObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ if (PyString_Check(v)) {
+ char *cStr;
+ if (!PyArg_Parse(v, "es", "ascii", &cStr))
+ return 0;
+ *p_itself = CFStringCreateWithCString((CFAllocatorRef)NULL, cStr, kCFStringEncodingASCII);
+ PyMem_Free(cStr);
+ return 1;
+ }
+ if (PyUnicode_Check(v)) {
+ /* We use the CF types here, if Python was configured differently that will give an error */
+ CFIndex size = PyUnicode_GetSize(v);
+ UniChar *unichars = PyUnicode_AsUnicode(v);
+ if (!unichars) return 0;
+ *p_itself = CFStringCreateWithCharacters((CFAllocatorRef)NULL, unichars, size);
+ return 1;
+ }
+
+
+ if (!CFStringRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFStringRef required");
+ return 0;
+ }
+ *p_itself = ((CFStringRefObject *)v)->ob_itself;
+ return 1;
}
static void CFStringRefObj_dealloc(CFStringRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFTypeRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFTypeRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFStringRefObj_CFStringCreateWithSubstring(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFRange range;
- if (!PyArg_ParseTuple(_args, "O&",
- CFRange_Convert, &range))
- return NULL;
- _rv = CFStringCreateWithSubstring((CFAllocatorRef)NULL,
- _self->ob_itself,
- range);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFRange range;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFRange_Convert, &range))
+ return NULL;
+ _rv = CFStringCreateWithSubstring((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ range);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringCreateCopy(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringCreateCopy((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringCreateCopy((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetLength(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
+ PyObject *_res = NULL;
+ CFIndex _rv;
#ifndef CFStringGetLength
- PyMac_PRECHECK(CFStringGetLength);
+ PyMac_PRECHECK(CFStringGetLength);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetLength(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetLength(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetBytes(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
- CFRange range;
- CFStringEncoding encoding;
- UInt8 lossByte;
- Boolean isExternalRepresentation;
- UInt8 buffer;
- CFIndex maxBufLen;
- CFIndex usedBufLen;
+ PyObject *_res = NULL;
+ CFIndex _rv;
+ CFRange range;
+ CFStringEncoding encoding;
+ UInt8 lossByte;
+ Boolean isExternalRepresentation;
+ UInt8 buffer;
+ CFIndex maxBufLen;
+ CFIndex usedBufLen;
#ifndef CFStringGetBytes
- PyMac_PRECHECK(CFStringGetBytes);
+ PyMac_PRECHECK(CFStringGetBytes);
#endif
- if (!PyArg_ParseTuple(_args, "O&lbll",
- CFRange_Convert, &range,
- &encoding,
- &lossByte,
- &isExternalRepresentation,
- &maxBufLen))
- return NULL;
- _rv = CFStringGetBytes(_self->ob_itself,
- range,
- encoding,
- lossByte,
- isExternalRepresentation,
- &buffer,
- maxBufLen,
- &usedBufLen);
- _res = Py_BuildValue("lbl",
- _rv,
- buffer,
- usedBufLen);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lbll",
+ CFRange_Convert, &range,
+ &encoding,
+ &lossByte,
+ &isExternalRepresentation,
+ &maxBufLen))
+ return NULL;
+ _rv = CFStringGetBytes(_self->ob_itself,
+ range,
+ encoding,
+ lossByte,
+ isExternalRepresentation,
+ &buffer,
+ maxBufLen,
+ &usedBufLen);
+ _res = Py_BuildValue("lbl",
+ _rv,
+ buffer,
+ usedBufLen);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringCreateExternalRepresentation(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDataRef _rv;
- CFStringEncoding encoding;
- UInt8 lossByte;
- if (!PyArg_ParseTuple(_args, "lb",
- &encoding,
- &lossByte))
- return NULL;
- _rv = CFStringCreateExternalRepresentation((CFAllocatorRef)NULL,
- _self->ob_itself,
- encoding,
- lossByte);
- _res = Py_BuildValue("O&",
- CFDataRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFDataRef _rv;
+ CFStringEncoding encoding;
+ UInt8 lossByte;
+ if (!PyArg_ParseTuple(_args, "lb",
+ &encoding,
+ &lossByte))
+ return NULL;
+ _rv = CFStringCreateExternalRepresentation((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ encoding,
+ lossByte);
+ _res = Py_BuildValue("O&",
+ CFDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetSmallestEncoding(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
#ifndef CFStringGetSmallestEncoding
- PyMac_PRECHECK(CFStringGetSmallestEncoding);
+ PyMac_PRECHECK(CFStringGetSmallestEncoding);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetSmallestEncoding(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetSmallestEncoding(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetFastestEncoding(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
#ifndef CFStringGetFastestEncoding
- PyMac_PRECHECK(CFStringGetFastestEncoding);
+ PyMac_PRECHECK(CFStringGetFastestEncoding);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetFastestEncoding(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetFastestEncoding(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringCompareWithOptions(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFComparisonResult _rv;
- CFStringRef theString2;
- CFRange rangeToCompare;
- CFOptionFlags compareOptions;
+ PyObject *_res = NULL;
+ CFComparisonResult _rv;
+ CFStringRef theString2;
+ CFRange rangeToCompare;
+ CFOptionFlags compareOptions;
#ifndef CFStringCompareWithOptions
- PyMac_PRECHECK(CFStringCompareWithOptions);
+ PyMac_PRECHECK(CFStringCompareWithOptions);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CFStringRefObj_Convert, &theString2,
- CFRange_Convert, &rangeToCompare,
- &compareOptions))
- return NULL;
- _rv = CFStringCompareWithOptions(_self->ob_itself,
- theString2,
- rangeToCompare,
- compareOptions);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CFStringRefObj_Convert, &theString2,
+ CFRange_Convert, &rangeToCompare,
+ &compareOptions))
+ return NULL;
+ _rv = CFStringCompareWithOptions(_self->ob_itself,
+ theString2,
+ rangeToCompare,
+ compareOptions);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringCompare(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFComparisonResult _rv;
- CFStringRef theString2;
- CFOptionFlags compareOptions;
+ PyObject *_res = NULL;
+ CFComparisonResult _rv;
+ CFStringRef theString2;
+ CFOptionFlags compareOptions;
#ifndef CFStringCompare
- PyMac_PRECHECK(CFStringCompare);
+ PyMac_PRECHECK(CFStringCompare);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CFStringRefObj_Convert, &theString2,
- &compareOptions))
- return NULL;
- _rv = CFStringCompare(_self->ob_itself,
- theString2,
- compareOptions);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CFStringRefObj_Convert, &theString2,
+ &compareOptions))
+ return NULL;
+ _rv = CFStringCompare(_self->ob_itself,
+ theString2,
+ compareOptions);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringFindWithOptions(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringRef stringToFind;
- CFRange rangeToSearch;
- CFOptionFlags searchOptions;
- CFRange result;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringRef stringToFind;
+ CFRange rangeToSearch;
+ CFOptionFlags searchOptions;
+ CFRange result;
#ifndef CFStringFindWithOptions
- PyMac_PRECHECK(CFStringFindWithOptions);
+ PyMac_PRECHECK(CFStringFindWithOptions);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CFStringRefObj_Convert, &stringToFind,
- CFRange_Convert, &rangeToSearch,
- &searchOptions))
- return NULL;
- _rv = CFStringFindWithOptions(_self->ob_itself,
- stringToFind,
- rangeToSearch,
- searchOptions,
- &result);
- _res = Py_BuildValue("lO&",
- _rv,
- CFRange_New, result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CFStringRefObj_Convert, &stringToFind,
+ CFRange_Convert, &rangeToSearch,
+ &searchOptions))
+ return NULL;
+ _rv = CFStringFindWithOptions(_self->ob_itself,
+ stringToFind,
+ rangeToSearch,
+ searchOptions,
+ &result);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CFRange_New, result);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringCreateArrayWithFindResults(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFArrayRef _rv;
- CFStringRef stringToFind;
- CFRange rangeToSearch;
- CFOptionFlags compareOptions;
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CFStringRefObj_Convert, &stringToFind,
- CFRange_Convert, &rangeToSearch,
- &compareOptions))
- return NULL;
- _rv = CFStringCreateArrayWithFindResults((CFAllocatorRef)NULL,
- _self->ob_itself,
- stringToFind,
- rangeToSearch,
- compareOptions);
- _res = Py_BuildValue("O&",
- CFArrayRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFArrayRef _rv;
+ CFStringRef stringToFind;
+ CFRange rangeToSearch;
+ CFOptionFlags compareOptions;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CFStringRefObj_Convert, &stringToFind,
+ CFRange_Convert, &rangeToSearch,
+ &compareOptions))
+ return NULL;
+ _rv = CFStringCreateArrayWithFindResults((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ stringToFind,
+ rangeToSearch,
+ compareOptions);
+ _res = Py_BuildValue("O&",
+ CFArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringFind(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange _rv;
- CFStringRef stringToFind;
- CFOptionFlags compareOptions;
+ PyObject *_res = NULL;
+ CFRange _rv;
+ CFStringRef stringToFind;
+ CFOptionFlags compareOptions;
#ifndef CFStringFind
- PyMac_PRECHECK(CFStringFind);
+ PyMac_PRECHECK(CFStringFind);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CFStringRefObj_Convert, &stringToFind,
- &compareOptions))
- return NULL;
- _rv = CFStringFind(_self->ob_itself,
- stringToFind,
- compareOptions);
- _res = Py_BuildValue("O&",
- CFRange_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CFStringRefObj_Convert, &stringToFind,
+ &compareOptions))
+ return NULL;
+ _rv = CFStringFind(_self->ob_itself,
+ stringToFind,
+ compareOptions);
+ _res = Py_BuildValue("O&",
+ CFRange_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringHasPrefix(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringRef prefix;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringRef prefix;
#ifndef CFStringHasPrefix
- PyMac_PRECHECK(CFStringHasPrefix);
+ PyMac_PRECHECK(CFStringHasPrefix);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &prefix))
- return NULL;
- _rv = CFStringHasPrefix(_self->ob_itself,
- prefix);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &prefix))
+ return NULL;
+ _rv = CFStringHasPrefix(_self->ob_itself,
+ prefix);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringHasSuffix(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringRef suffix;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringRef suffix;
#ifndef CFStringHasSuffix
- PyMac_PRECHECK(CFStringHasSuffix);
+ PyMac_PRECHECK(CFStringHasSuffix);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &suffix))
- return NULL;
- _rv = CFStringHasSuffix(_self->ob_itself,
- suffix);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &suffix))
+ return NULL;
+ _rv = CFStringHasSuffix(_self->ob_itself,
+ suffix);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetLineBounds(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange range;
- CFIndex lineBeginIndex;
- CFIndex lineEndIndex;
- CFIndex contentsEndIndex;
+ PyObject *_res = NULL;
+ CFRange range;
+ CFIndex lineBeginIndex;
+ CFIndex lineEndIndex;
+ CFIndex contentsEndIndex;
#ifndef CFStringGetLineBounds
- PyMac_PRECHECK(CFStringGetLineBounds);
+ PyMac_PRECHECK(CFStringGetLineBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFRange_Convert, &range))
- return NULL;
- CFStringGetLineBounds(_self->ob_itself,
- range,
- &lineBeginIndex,
- &lineEndIndex,
- &contentsEndIndex);
- _res = Py_BuildValue("lll",
- lineBeginIndex,
- lineEndIndex,
- contentsEndIndex);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFRange_Convert, &range))
+ return NULL;
+ CFStringGetLineBounds(_self->ob_itself,
+ range,
+ &lineBeginIndex,
+ &lineEndIndex,
+ &contentsEndIndex);
+ _res = Py_BuildValue("lll",
+ lineBeginIndex,
+ lineEndIndex,
+ contentsEndIndex);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringCreateArrayBySeparatingStrings(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFArrayRef _rv;
- CFStringRef separatorString;
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &separatorString))
- return NULL;
- _rv = CFStringCreateArrayBySeparatingStrings((CFAllocatorRef)NULL,
- _self->ob_itself,
- separatorString);
- _res = Py_BuildValue("O&",
- CFArrayRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFArrayRef _rv;
+ CFStringRef separatorString;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &separatorString))
+ return NULL;
+ _rv = CFStringCreateArrayBySeparatingStrings((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ separatorString);
+ _res = Py_BuildValue("O&",
+ CFArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetIntValue(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef CFStringGetIntValue
- PyMac_PRECHECK(CFStringGetIntValue);
+ PyMac_PRECHECK(CFStringGetIntValue);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetIntValue(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetIntValue(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetDoubleValue(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- double _rv;
+ PyObject *_res = NULL;
+ double _rv;
#ifndef CFStringGetDoubleValue
- PyMac_PRECHECK(CFStringGetDoubleValue);
+ PyMac_PRECHECK(CFStringGetDoubleValue);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetDoubleValue(_self->ob_itself);
- _res = Py_BuildValue("d",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetDoubleValue(_self->ob_itself);
+ _res = Py_BuildValue("d",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringConvertIANACharSetNameToEncoding(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
#ifndef CFStringConvertIANACharSetNameToEncoding
- PyMac_PRECHECK(CFStringConvertIANACharSetNameToEncoding);
+ PyMac_PRECHECK(CFStringConvertIANACharSetNameToEncoding);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringConvertIANACharSetNameToEncoding(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringConvertIANACharSetNameToEncoding(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFShowStr(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CFShowStr
- PyMac_PRECHECK(CFShowStr);
+ PyMac_PRECHECK(CFShowStr);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CFShowStr(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CFShowStr(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFStringRefObj_CFURLCreateWithString(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- CFURLRef baseURL;
- if (!PyArg_ParseTuple(_args, "O&",
- OptionalCFURLRefObj_Convert, &baseURL))
- return NULL;
- _rv = CFURLCreateWithString((CFAllocatorRef)NULL,
- _self->ob_itself,
- baseURL);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ CFURLRef baseURL;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptionalCFURLRefObj_Convert, &baseURL))
+ return NULL;
+ _rv = CFURLCreateWithString((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ baseURL);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFURLCreateWithFileSystemPath(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- CFURLPathStyle pathStyle;
- Boolean isDirectory;
- if (!PyArg_ParseTuple(_args, "ll",
- &pathStyle,
- &isDirectory))
- return NULL;
- _rv = CFURLCreateWithFileSystemPath((CFAllocatorRef)NULL,
- _self->ob_itself,
- pathStyle,
- isDirectory);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ CFURLPathStyle pathStyle;
+ Boolean isDirectory;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &pathStyle,
+ &isDirectory))
+ return NULL;
+ _rv = CFURLCreateWithFileSystemPath((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ pathStyle,
+ isDirectory);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFURLCreateWithFileSystemPathRelativeToBase(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- CFURLPathStyle pathStyle;
- Boolean isDirectory;
- CFURLRef baseURL;
- if (!PyArg_ParseTuple(_args, "llO&",
- &pathStyle,
- &isDirectory,
- OptionalCFURLRefObj_Convert, &baseURL))
- return NULL;
- _rv = CFURLCreateWithFileSystemPathRelativeToBase((CFAllocatorRef)NULL,
- _self->ob_itself,
- pathStyle,
- isDirectory,
- baseURL);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ CFURLPathStyle pathStyle;
+ Boolean isDirectory;
+ CFURLRef baseURL;
+ if (!PyArg_ParseTuple(_args, "llO&",
+ &pathStyle,
+ &isDirectory,
+ OptionalCFURLRefObj_Convert, &baseURL))
+ return NULL;
+ _rv = CFURLCreateWithFileSystemPathRelativeToBase((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ pathStyle,
+ isDirectory,
+ baseURL);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFURLCreateStringByReplacingPercentEscapes(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringRef charactersToLeaveEscaped;
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &charactersToLeaveEscaped))
- return NULL;
- _rv = CFURLCreateStringByReplacingPercentEscapes((CFAllocatorRef)NULL,
- _self->ob_itself,
- charactersToLeaveEscaped);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringRef charactersToLeaveEscaped;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &charactersToLeaveEscaped))
+ return NULL;
+ _rv = CFURLCreateStringByReplacingPercentEscapes((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ charactersToLeaveEscaped);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFURLCreateStringByAddingPercentEscapes(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringRef charactersToLeaveUnescaped;
- CFStringRef legalURLCharactersToBeEscaped;
- CFStringEncoding encoding;
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CFStringRefObj_Convert, &charactersToLeaveUnescaped,
- CFStringRefObj_Convert, &legalURLCharactersToBeEscaped,
- &encoding))
- return NULL;
- _rv = CFURLCreateStringByAddingPercentEscapes((CFAllocatorRef)NULL,
- _self->ob_itself,
- charactersToLeaveUnescaped,
- legalURLCharactersToBeEscaped,
- encoding);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringRef charactersToLeaveUnescaped;
+ CFStringRef legalURLCharactersToBeEscaped;
+ CFStringEncoding encoding;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CFStringRefObj_Convert, &charactersToLeaveUnescaped,
+ CFStringRefObj_Convert, &legalURLCharactersToBeEscaped,
+ &encoding))
+ return NULL;
+ _rv = CFURLCreateStringByAddingPercentEscapes((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ charactersToLeaveUnescaped,
+ legalURLCharactersToBeEscaped,
+ encoding);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetString(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int size = CFStringGetLength(_self->ob_itself)+1;
- char *data = malloc(size);
+ int size = CFStringGetLength(_self->ob_itself)+1;
+ char *data = malloc(size);
- if( data == NULL ) return PyErr_NoMemory();
- if ( CFStringGetCString(_self->ob_itself, data, size, 0) ) {
- _res = (PyObject *)PyString_FromString(data);
- } else {
- PyErr_SetString(PyExc_RuntimeError, "CFStringGetCString could not fit the string");
- _res = NULL;
- }
- free(data);
- return _res;
+ if( data == NULL ) return PyErr_NoMemory();
+ if ( CFStringGetCString(_self->ob_itself, data, size, 0) ) {
+ _res = (PyObject *)PyString_FromString(data);
+ } else {
+ PyErr_SetString(PyExc_RuntimeError, "CFStringGetCString could not fit the string");
+ _res = NULL;
+ }
+ free(data);
+ return _res;
}
static PyObject *CFStringRefObj_CFStringGetUnicode(CFStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int size = CFStringGetLength(_self->ob_itself)+1;
- Py_UNICODE *data = malloc(size*sizeof(Py_UNICODE));
- CFRange range;
+ int size = CFStringGetLength(_self->ob_itself)+1;
+ Py_UNICODE *data = malloc(size*sizeof(Py_UNICODE));
+ CFRange range;
- range.location = 0;
- range.length = size;
- if( data == NULL ) return PyErr_NoMemory();
- CFStringGetCharacters(_self->ob_itself, range, data);
- _res = (PyObject *)PyUnicode_FromUnicode(data, size-1);
- free(data);
- return _res;
+ range.location = 0;
+ range.length = size;
+ if( data == NULL ) return PyErr_NoMemory();
+ CFStringGetCharacters(_self->ob_itself, range, data);
+ _res = (PyObject *)PyUnicode_FromUnicode(data, size-1);
+ free(data);
+ return _res;
}
static PyMethodDef CFStringRefObj_methods[] = {
- {"CFStringCreateWithSubstring", (PyCFunction)CFStringRefObj_CFStringCreateWithSubstring, 1,
- PyDoc_STR("(CFRange range) -> (CFStringRef _rv)")},
- {"CFStringCreateCopy", (PyCFunction)CFStringRefObj_CFStringCreateCopy, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFStringGetLength", (PyCFunction)CFStringRefObj_CFStringGetLength, 1,
- PyDoc_STR("() -> (CFIndex _rv)")},
- {"CFStringGetBytes", (PyCFunction)CFStringRefObj_CFStringGetBytes, 1,
- PyDoc_STR("(CFRange range, CFStringEncoding encoding, UInt8 lossByte, Boolean isExternalRepresentation, CFIndex maxBufLen) -> (CFIndex _rv, UInt8 buffer, CFIndex usedBufLen)")},
- {"CFStringCreateExternalRepresentation", (PyCFunction)CFStringRefObj_CFStringCreateExternalRepresentation, 1,
- PyDoc_STR("(CFStringEncoding encoding, UInt8 lossByte) -> (CFDataRef _rv)")},
- {"CFStringGetSmallestEncoding", (PyCFunction)CFStringRefObj_CFStringGetSmallestEncoding, 1,
- PyDoc_STR("() -> (CFStringEncoding _rv)")},
- {"CFStringGetFastestEncoding", (PyCFunction)CFStringRefObj_CFStringGetFastestEncoding, 1,
- PyDoc_STR("() -> (CFStringEncoding _rv)")},
- {"CFStringCompareWithOptions", (PyCFunction)CFStringRefObj_CFStringCompareWithOptions, 1,
- PyDoc_STR("(CFStringRef theString2, CFRange rangeToCompare, CFOptionFlags compareOptions) -> (CFComparisonResult _rv)")},
- {"CFStringCompare", (PyCFunction)CFStringRefObj_CFStringCompare, 1,
- PyDoc_STR("(CFStringRef theString2, CFOptionFlags compareOptions) -> (CFComparisonResult _rv)")},
- {"CFStringFindWithOptions", (PyCFunction)CFStringRefObj_CFStringFindWithOptions, 1,
- PyDoc_STR("(CFStringRef stringToFind, CFRange rangeToSearch, CFOptionFlags searchOptions) -> (Boolean _rv, CFRange result)")},
- {"CFStringCreateArrayWithFindResults", (PyCFunction)CFStringRefObj_CFStringCreateArrayWithFindResults, 1,
- PyDoc_STR("(CFStringRef stringToFind, CFRange rangeToSearch, CFOptionFlags compareOptions) -> (CFArrayRef _rv)")},
- {"CFStringFind", (PyCFunction)CFStringRefObj_CFStringFind, 1,
- PyDoc_STR("(CFStringRef stringToFind, CFOptionFlags compareOptions) -> (CFRange _rv)")},
- {"CFStringHasPrefix", (PyCFunction)CFStringRefObj_CFStringHasPrefix, 1,
- PyDoc_STR("(CFStringRef prefix) -> (Boolean _rv)")},
- {"CFStringHasSuffix", (PyCFunction)CFStringRefObj_CFStringHasSuffix, 1,
- PyDoc_STR("(CFStringRef suffix) -> (Boolean _rv)")},
- {"CFStringGetLineBounds", (PyCFunction)CFStringRefObj_CFStringGetLineBounds, 1,
- PyDoc_STR("(CFRange range) -> (CFIndex lineBeginIndex, CFIndex lineEndIndex, CFIndex contentsEndIndex)")},
- {"CFStringCreateArrayBySeparatingStrings", (PyCFunction)CFStringRefObj_CFStringCreateArrayBySeparatingStrings, 1,
- PyDoc_STR("(CFStringRef separatorString) -> (CFArrayRef _rv)")},
- {"CFStringGetIntValue", (PyCFunction)CFStringRefObj_CFStringGetIntValue, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"CFStringGetDoubleValue", (PyCFunction)CFStringRefObj_CFStringGetDoubleValue, 1,
- PyDoc_STR("() -> (double _rv)")},
- {"CFStringConvertIANACharSetNameToEncoding", (PyCFunction)CFStringRefObj_CFStringConvertIANACharSetNameToEncoding, 1,
- PyDoc_STR("() -> (CFStringEncoding _rv)")},
- {"CFShowStr", (PyCFunction)CFStringRefObj_CFShowStr, 1,
- PyDoc_STR("() -> None")},
- {"CFURLCreateWithString", (PyCFunction)CFStringRefObj_CFURLCreateWithString, 1,
- PyDoc_STR("(CFURLRef baseURL) -> (CFURLRef _rv)")},
- {"CFURLCreateWithFileSystemPath", (PyCFunction)CFStringRefObj_CFURLCreateWithFileSystemPath, 1,
- PyDoc_STR("(CFURLPathStyle pathStyle, Boolean isDirectory) -> (CFURLRef _rv)")},
- {"CFURLCreateWithFileSystemPathRelativeToBase", (PyCFunction)CFStringRefObj_CFURLCreateWithFileSystemPathRelativeToBase, 1,
- PyDoc_STR("(CFURLPathStyle pathStyle, Boolean isDirectory, CFURLRef baseURL) -> (CFURLRef _rv)")},
- {"CFURLCreateStringByReplacingPercentEscapes", (PyCFunction)CFStringRefObj_CFURLCreateStringByReplacingPercentEscapes, 1,
- PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
- {"CFURLCreateStringByAddingPercentEscapes", (PyCFunction)CFStringRefObj_CFURLCreateStringByAddingPercentEscapes, 1,
- PyDoc_STR("(CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringGetString", (PyCFunction)CFStringRefObj_CFStringGetString, 1,
- PyDoc_STR("() -> (string _rv)")},
- {"CFStringGetUnicode", (PyCFunction)CFStringRefObj_CFStringGetUnicode, 1,
- PyDoc_STR("() -> (unicode _rv)")},
- {NULL, NULL, 0}
+ {"CFStringCreateWithSubstring", (PyCFunction)CFStringRefObj_CFStringCreateWithSubstring, 1,
+ PyDoc_STR("(CFRange range) -> (CFStringRef _rv)")},
+ {"CFStringCreateCopy", (PyCFunction)CFStringRefObj_CFStringCreateCopy, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFStringGetLength", (PyCFunction)CFStringRefObj_CFStringGetLength, 1,
+ PyDoc_STR("() -> (CFIndex _rv)")},
+ {"CFStringGetBytes", (PyCFunction)CFStringRefObj_CFStringGetBytes, 1,
+ PyDoc_STR("(CFRange range, CFStringEncoding encoding, UInt8 lossByte, Boolean isExternalRepresentation, CFIndex maxBufLen) -> (CFIndex _rv, UInt8 buffer, CFIndex usedBufLen)")},
+ {"CFStringCreateExternalRepresentation", (PyCFunction)CFStringRefObj_CFStringCreateExternalRepresentation, 1,
+ PyDoc_STR("(CFStringEncoding encoding, UInt8 lossByte) -> (CFDataRef _rv)")},
+ {"CFStringGetSmallestEncoding", (PyCFunction)CFStringRefObj_CFStringGetSmallestEncoding, 1,
+ PyDoc_STR("() -> (CFStringEncoding _rv)")},
+ {"CFStringGetFastestEncoding", (PyCFunction)CFStringRefObj_CFStringGetFastestEncoding, 1,
+ PyDoc_STR("() -> (CFStringEncoding _rv)")},
+ {"CFStringCompareWithOptions", (PyCFunction)CFStringRefObj_CFStringCompareWithOptions, 1,
+ PyDoc_STR("(CFStringRef theString2, CFRange rangeToCompare, CFOptionFlags compareOptions) -> (CFComparisonResult _rv)")},
+ {"CFStringCompare", (PyCFunction)CFStringRefObj_CFStringCompare, 1,
+ PyDoc_STR("(CFStringRef theString2, CFOptionFlags compareOptions) -> (CFComparisonResult _rv)")},
+ {"CFStringFindWithOptions", (PyCFunction)CFStringRefObj_CFStringFindWithOptions, 1,
+ PyDoc_STR("(CFStringRef stringToFind, CFRange rangeToSearch, CFOptionFlags searchOptions) -> (Boolean _rv, CFRange result)")},
+ {"CFStringCreateArrayWithFindResults", (PyCFunction)CFStringRefObj_CFStringCreateArrayWithFindResults, 1,
+ PyDoc_STR("(CFStringRef stringToFind, CFRange rangeToSearch, CFOptionFlags compareOptions) -> (CFArrayRef _rv)")},
+ {"CFStringFind", (PyCFunction)CFStringRefObj_CFStringFind, 1,
+ PyDoc_STR("(CFStringRef stringToFind, CFOptionFlags compareOptions) -> (CFRange _rv)")},
+ {"CFStringHasPrefix", (PyCFunction)CFStringRefObj_CFStringHasPrefix, 1,
+ PyDoc_STR("(CFStringRef prefix) -> (Boolean _rv)")},
+ {"CFStringHasSuffix", (PyCFunction)CFStringRefObj_CFStringHasSuffix, 1,
+ PyDoc_STR("(CFStringRef suffix) -> (Boolean _rv)")},
+ {"CFStringGetLineBounds", (PyCFunction)CFStringRefObj_CFStringGetLineBounds, 1,
+ PyDoc_STR("(CFRange range) -> (CFIndex lineBeginIndex, CFIndex lineEndIndex, CFIndex contentsEndIndex)")},
+ {"CFStringCreateArrayBySeparatingStrings", (PyCFunction)CFStringRefObj_CFStringCreateArrayBySeparatingStrings, 1,
+ PyDoc_STR("(CFStringRef separatorString) -> (CFArrayRef _rv)")},
+ {"CFStringGetIntValue", (PyCFunction)CFStringRefObj_CFStringGetIntValue, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"CFStringGetDoubleValue", (PyCFunction)CFStringRefObj_CFStringGetDoubleValue, 1,
+ PyDoc_STR("() -> (double _rv)")},
+ {"CFStringConvertIANACharSetNameToEncoding", (PyCFunction)CFStringRefObj_CFStringConvertIANACharSetNameToEncoding, 1,
+ PyDoc_STR("() -> (CFStringEncoding _rv)")},
+ {"CFShowStr", (PyCFunction)CFStringRefObj_CFShowStr, 1,
+ PyDoc_STR("() -> None")},
+ {"CFURLCreateWithString", (PyCFunction)CFStringRefObj_CFURLCreateWithString, 1,
+ PyDoc_STR("(CFURLRef baseURL) -> (CFURLRef _rv)")},
+ {"CFURLCreateWithFileSystemPath", (PyCFunction)CFStringRefObj_CFURLCreateWithFileSystemPath, 1,
+ PyDoc_STR("(CFURLPathStyle pathStyle, Boolean isDirectory) -> (CFURLRef _rv)")},
+ {"CFURLCreateWithFileSystemPathRelativeToBase", (PyCFunction)CFStringRefObj_CFURLCreateWithFileSystemPathRelativeToBase, 1,
+ PyDoc_STR("(CFURLPathStyle pathStyle, Boolean isDirectory, CFURLRef baseURL) -> (CFURLRef _rv)")},
+ {"CFURLCreateStringByReplacingPercentEscapes", (PyCFunction)CFStringRefObj_CFURLCreateStringByReplacingPercentEscapes, 1,
+ PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
+ {"CFURLCreateStringByAddingPercentEscapes", (PyCFunction)CFStringRefObj_CFURLCreateStringByAddingPercentEscapes, 1,
+ PyDoc_STR("(CFStringRef charactersToLeaveUnescaped, CFStringRef legalURLCharactersToBeEscaped, CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringGetString", (PyCFunction)CFStringRefObj_CFStringGetString, 1,
+ PyDoc_STR("() -> (string _rv)")},
+ {"CFStringGetUnicode", (PyCFunction)CFStringRefObj_CFStringGetUnicode, 1,
+ PyDoc_STR("() -> (unicode _rv)")},
+ {NULL, NULL, 0}
};
#define CFStringRefObj_getsetlist NULL
@@ -2435,100 +2435,100 @@ static PyMethodDef CFStringRefObj_methods[] = {
static int CFStringRefObj_compare(CFStringRefObject *self, CFStringRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFStringRefObj_repr(CFStringRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFStringRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFStringRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFStringRefObj_hash(CFStringRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFStringRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFStringRef itself;
- char *kw[] = {"itself", 0};
+ CFStringRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFStringRefObj_Convert, &itself))
- {
- ((CFStringRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFStringRefObj_Convert, &itself))
+ {
+ ((CFStringRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFStringRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFStringRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFStringRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFStringRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFStringRefObject *)self)->ob_itself = NULL;
- ((CFStringRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFStringRefObject *)self)->ob_itself = NULL;
+ ((CFStringRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFStringRefObj_tp_free PyObject_Del
PyTypeObject CFStringRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFStringRef", /*tp_name*/
- sizeof(CFStringRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFStringRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFStringRefObj_compare, /*tp_compare*/
- (reprfunc) CFStringRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFStringRefObj_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*/
- CFStringRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFStringRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFStringRefObj_tp_init, /* tp_init */
- CFStringRefObj_tp_alloc, /* tp_alloc */
- CFStringRefObj_tp_new, /* tp_new */
- CFStringRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFStringRef", /*tp_name*/
+ sizeof(CFStringRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFStringRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFStringRefObj_compare, /*tp_compare*/
+ (reprfunc) CFStringRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFStringRefObj_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*/
+ CFStringRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFStringRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFStringRefObj_tp_init, /* tp_init */
+ CFStringRefObj_tp_alloc, /* tp_alloc */
+ CFStringRefObj_tp_new, /* tp_new */
+ CFStringRefObj_tp_free, /* tp_free */
};
/* ------------------ End object type CFStringRef ------------------- */
@@ -2541,281 +2541,281 @@ PyTypeObject CFMutableStringRef_Type;
#define CFMutableStringRefObj_Check(x) ((x)->ob_type == &CFMutableStringRef_Type || PyObject_TypeCheck((x), &CFMutableStringRef_Type))
typedef struct CFMutableStringRefObject {
- PyObject_HEAD
- CFMutableStringRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFMutableStringRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFMutableStringRefObject;
PyObject *CFMutableStringRefObj_New(CFMutableStringRef itself)
{
- CFMutableStringRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFMutableStringRefObject, &CFMutableStringRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFMutableStringRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFMutableStringRefObject, &CFMutableStringRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFMutableStringRefObj_Convert(PyObject *v, CFMutableStringRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFMutableStringRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFMutableStringRef required");
- return 0;
- }
- *p_itself = ((CFMutableStringRefObject *)v)->ob_itself;
- return 1;
+ if (!CFMutableStringRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFMutableStringRef required");
+ return 0;
+ }
+ *p_itself = ((CFMutableStringRefObject *)v)->ob_itself;
+ return 1;
}
static void CFMutableStringRefObj_dealloc(CFMutableStringRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFStringRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFStringRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFMutableStringRefObj_CFStringAppend(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef appendedString;
+ PyObject *_res = NULL;
+ CFStringRef appendedString;
#ifndef CFStringAppend
- PyMac_PRECHECK(CFStringAppend);
+ PyMac_PRECHECK(CFStringAppend);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &appendedString))
- return NULL;
- CFStringAppend(_self->ob_itself,
- appendedString);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &appendedString))
+ return NULL;
+ CFStringAppend(_self->ob_itself,
+ appendedString);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringAppendCharacters(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UniChar *chars__in__;
- UniCharCount chars__len__;
- int chars__in_len__;
+ PyObject *_res = NULL;
+ UniChar *chars__in__;
+ UniCharCount chars__len__;
+ int chars__in_len__;
#ifndef CFStringAppendCharacters
- PyMac_PRECHECK(CFStringAppendCharacters);
+ PyMac_PRECHECK(CFStringAppendCharacters);
#endif
- if (!PyArg_ParseTuple(_args, "u#",
- &chars__in__, &chars__in_len__))
- return NULL;
- chars__len__ = chars__in_len__;
- CFStringAppendCharacters(_self->ob_itself,
- chars__in__, chars__len__);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "u#",
+ &chars__in__, &chars__in_len__))
+ return NULL;
+ chars__len__ = chars__in_len__;
+ CFStringAppendCharacters(_self->ob_itself,
+ chars__in__, chars__len__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringAppendPascalString(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 pStr;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ Str255 pStr;
+ CFStringEncoding encoding;
#ifndef CFStringAppendPascalString
- PyMac_PRECHECK(CFStringAppendPascalString);
+ PyMac_PRECHECK(CFStringAppendPascalString);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetStr255, pStr,
- &encoding))
- return NULL;
- CFStringAppendPascalString(_self->ob_itself,
- pStr,
- encoding);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetStr255, pStr,
+ &encoding))
+ return NULL;
+ CFStringAppendPascalString(_self->ob_itself,
+ pStr,
+ encoding);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringAppendCString(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char* cStr;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ char* cStr;
+ CFStringEncoding encoding;
#ifndef CFStringAppendCString
- PyMac_PRECHECK(CFStringAppendCString);
+ PyMac_PRECHECK(CFStringAppendCString);
#endif
- if (!PyArg_ParseTuple(_args, "sl",
- &cStr,
- &encoding))
- return NULL;
- CFStringAppendCString(_self->ob_itself,
- cStr,
- encoding);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "sl",
+ &cStr,
+ &encoding))
+ return NULL;
+ CFStringAppendCString(_self->ob_itself,
+ cStr,
+ encoding);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringInsert(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex idx;
- CFStringRef insertedStr;
+ PyObject *_res = NULL;
+ CFIndex idx;
+ CFStringRef insertedStr;
#ifndef CFStringInsert
- PyMac_PRECHECK(CFStringInsert);
+ PyMac_PRECHECK(CFStringInsert);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &idx,
- CFStringRefObj_Convert, &insertedStr))
- return NULL;
- CFStringInsert(_self->ob_itself,
- idx,
- insertedStr);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &idx,
+ CFStringRefObj_Convert, &insertedStr))
+ return NULL;
+ CFStringInsert(_self->ob_itself,
+ idx,
+ insertedStr);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringDelete(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange range;
+ PyObject *_res = NULL;
+ CFRange range;
#ifndef CFStringDelete
- PyMac_PRECHECK(CFStringDelete);
+ PyMac_PRECHECK(CFStringDelete);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFRange_Convert, &range))
- return NULL;
- CFStringDelete(_self->ob_itself,
- range);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFRange_Convert, &range))
+ return NULL;
+ CFStringDelete(_self->ob_itself,
+ range);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringReplace(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange range;
- CFStringRef replacement;
+ PyObject *_res = NULL;
+ CFRange range;
+ CFStringRef replacement;
#ifndef CFStringReplace
- PyMac_PRECHECK(CFStringReplace);
+ PyMac_PRECHECK(CFStringReplace);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFRange_Convert, &range,
- CFStringRefObj_Convert, &replacement))
- return NULL;
- CFStringReplace(_self->ob_itself,
- range,
- replacement);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFRange_Convert, &range,
+ CFStringRefObj_Convert, &replacement))
+ return NULL;
+ CFStringReplace(_self->ob_itself,
+ range,
+ replacement);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringReplaceAll(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef replacement;
+ PyObject *_res = NULL;
+ CFStringRef replacement;
#ifndef CFStringReplaceAll
- PyMac_PRECHECK(CFStringReplaceAll);
+ PyMac_PRECHECK(CFStringReplaceAll);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &replacement))
- return NULL;
- CFStringReplaceAll(_self->ob_itself,
- replacement);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &replacement))
+ return NULL;
+ CFStringReplaceAll(_self->ob_itself,
+ replacement);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringPad(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef padString;
- CFIndex length;
- CFIndex indexIntoPad;
+ PyObject *_res = NULL;
+ CFStringRef padString;
+ CFIndex length;
+ CFIndex indexIntoPad;
#ifndef CFStringPad
- PyMac_PRECHECK(CFStringPad);
+ PyMac_PRECHECK(CFStringPad);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CFStringRefObj_Convert, &padString,
- &length,
- &indexIntoPad))
- return NULL;
- CFStringPad(_self->ob_itself,
- padString,
- length,
- indexIntoPad);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CFStringRefObj_Convert, &padString,
+ &length,
+ &indexIntoPad))
+ return NULL;
+ CFStringPad(_self->ob_itself,
+ padString,
+ length,
+ indexIntoPad);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringTrim(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef trimString;
+ PyObject *_res = NULL;
+ CFStringRef trimString;
#ifndef CFStringTrim
- PyMac_PRECHECK(CFStringTrim);
+ PyMac_PRECHECK(CFStringTrim);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &trimString))
- return NULL;
- CFStringTrim(_self->ob_itself,
- trimString);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &trimString))
+ return NULL;
+ CFStringTrim(_self->ob_itself,
+ trimString);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CFMutableStringRefObj_CFStringTrimWhitespace(CFMutableStringRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CFStringTrimWhitespace
- PyMac_PRECHECK(CFStringTrimWhitespace);
+ PyMac_PRECHECK(CFStringTrimWhitespace);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CFStringTrimWhitespace(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CFStringTrimWhitespace(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef CFMutableStringRefObj_methods[] = {
- {"CFStringAppend", (PyCFunction)CFMutableStringRefObj_CFStringAppend, 1,
- PyDoc_STR("(CFStringRef appendedString) -> None")},
- {"CFStringAppendCharacters", (PyCFunction)CFMutableStringRefObj_CFStringAppendCharacters, 1,
- PyDoc_STR("(Buffer chars) -> None")},
- {"CFStringAppendPascalString", (PyCFunction)CFMutableStringRefObj_CFStringAppendPascalString, 1,
- PyDoc_STR("(Str255 pStr, CFStringEncoding encoding) -> None")},
- {"CFStringAppendCString", (PyCFunction)CFMutableStringRefObj_CFStringAppendCString, 1,
- PyDoc_STR("(char* cStr, CFStringEncoding encoding) -> None")},
- {"CFStringInsert", (PyCFunction)CFMutableStringRefObj_CFStringInsert, 1,
- PyDoc_STR("(CFIndex idx, CFStringRef insertedStr) -> None")},
- {"CFStringDelete", (PyCFunction)CFMutableStringRefObj_CFStringDelete, 1,
- PyDoc_STR("(CFRange range) -> None")},
- {"CFStringReplace", (PyCFunction)CFMutableStringRefObj_CFStringReplace, 1,
- PyDoc_STR("(CFRange range, CFStringRef replacement) -> None")},
- {"CFStringReplaceAll", (PyCFunction)CFMutableStringRefObj_CFStringReplaceAll, 1,
- PyDoc_STR("(CFStringRef replacement) -> None")},
- {"CFStringPad", (PyCFunction)CFMutableStringRefObj_CFStringPad, 1,
- PyDoc_STR("(CFStringRef padString, CFIndex length, CFIndex indexIntoPad) -> None")},
- {"CFStringTrim", (PyCFunction)CFMutableStringRefObj_CFStringTrim, 1,
- PyDoc_STR("(CFStringRef trimString) -> None")},
- {"CFStringTrimWhitespace", (PyCFunction)CFMutableStringRefObj_CFStringTrimWhitespace, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"CFStringAppend", (PyCFunction)CFMutableStringRefObj_CFStringAppend, 1,
+ PyDoc_STR("(CFStringRef appendedString) -> None")},
+ {"CFStringAppendCharacters", (PyCFunction)CFMutableStringRefObj_CFStringAppendCharacters, 1,
+ PyDoc_STR("(Buffer chars) -> None")},
+ {"CFStringAppendPascalString", (PyCFunction)CFMutableStringRefObj_CFStringAppendPascalString, 1,
+ PyDoc_STR("(Str255 pStr, CFStringEncoding encoding) -> None")},
+ {"CFStringAppendCString", (PyCFunction)CFMutableStringRefObj_CFStringAppendCString, 1,
+ PyDoc_STR("(char* cStr, CFStringEncoding encoding) -> None")},
+ {"CFStringInsert", (PyCFunction)CFMutableStringRefObj_CFStringInsert, 1,
+ PyDoc_STR("(CFIndex idx, CFStringRef insertedStr) -> None")},
+ {"CFStringDelete", (PyCFunction)CFMutableStringRefObj_CFStringDelete, 1,
+ PyDoc_STR("(CFRange range) -> None")},
+ {"CFStringReplace", (PyCFunction)CFMutableStringRefObj_CFStringReplace, 1,
+ PyDoc_STR("(CFRange range, CFStringRef replacement) -> None")},
+ {"CFStringReplaceAll", (PyCFunction)CFMutableStringRefObj_CFStringReplaceAll, 1,
+ PyDoc_STR("(CFStringRef replacement) -> None")},
+ {"CFStringPad", (PyCFunction)CFMutableStringRefObj_CFStringPad, 1,
+ PyDoc_STR("(CFStringRef padString, CFIndex length, CFIndex indexIntoPad) -> None")},
+ {"CFStringTrim", (PyCFunction)CFMutableStringRefObj_CFStringTrim, 1,
+ PyDoc_STR("(CFStringRef trimString) -> None")},
+ {"CFStringTrimWhitespace", (PyCFunction)CFMutableStringRefObj_CFStringTrimWhitespace, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define CFMutableStringRefObj_getsetlist NULL
@@ -2823,100 +2823,100 @@ static PyMethodDef CFMutableStringRefObj_methods[] = {
static int CFMutableStringRefObj_compare(CFMutableStringRefObject *self, CFMutableStringRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFMutableStringRefObj_repr(CFMutableStringRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFMutableStringRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFMutableStringRef object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFMutableStringRefObj_hash(CFMutableStringRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFMutableStringRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFMutableStringRef itself;
- char *kw[] = {"itself", 0};
+ CFMutableStringRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableStringRefObj_Convert, &itself))
- {
- ((CFMutableStringRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFMutableStringRefObj_Convert, &itself))
+ {
+ ((CFMutableStringRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFMutableStringRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFMutableStringRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFMutableStringRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFMutableStringRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFMutableStringRefObject *)self)->ob_itself = NULL;
- ((CFMutableStringRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFMutableStringRefObject *)self)->ob_itself = NULL;
+ ((CFMutableStringRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFMutableStringRefObj_tp_free PyObject_Del
PyTypeObject CFMutableStringRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFMutableStringRef", /*tp_name*/
- sizeof(CFMutableStringRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFMutableStringRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFMutableStringRefObj_compare, /*tp_compare*/
- (reprfunc) CFMutableStringRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFMutableStringRefObj_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*/
- CFMutableStringRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFMutableStringRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFMutableStringRefObj_tp_init, /* tp_init */
- CFMutableStringRefObj_tp_alloc, /* tp_alloc */
- CFMutableStringRefObj_tp_new, /* tp_new */
- CFMutableStringRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFMutableStringRef", /*tp_name*/
+ sizeof(CFMutableStringRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFMutableStringRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFMutableStringRefObj_compare, /*tp_compare*/
+ (reprfunc) CFMutableStringRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFMutableStringRefObj_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*/
+ CFMutableStringRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFMutableStringRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFMutableStringRefObj_tp_init, /* tp_init */
+ CFMutableStringRefObj_tp_alloc, /* tp_alloc */
+ CFMutableStringRefObj_tp_new, /* tp_new */
+ CFMutableStringRefObj_tp_free, /* tp_free */
};
/* --------------- End object type CFMutableStringRef --------------- */
@@ -2929,545 +2929,545 @@ PyTypeObject CFURLRef_Type;
#define CFURLRefObj_Check(x) ((x)->ob_type == &CFURLRef_Type || PyObject_TypeCheck((x), &CFURLRef_Type))
typedef struct CFURLRefObject {
- PyObject_HEAD
- CFURLRef ob_itself;
- void (*ob_freeit)(CFTypeRef ptr);
+ PyObject_HEAD
+ CFURLRef ob_itself;
+ void (*ob_freeit)(CFTypeRef ptr);
} CFURLRefObject;
PyObject *CFURLRefObj_New(CFURLRef itself)
{
- CFURLRefObject *it;
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- it = PyObject_NEW(CFURLRefObject, &CFURLRef_Type);
- if (it == NULL) return NULL;
- /* XXXX Should we tp_init or tp_new our basetype? */
- it->ob_itself = itself;
- it->ob_freeit = CFRelease;
- return (PyObject *)it;
+ CFURLRefObject *it;
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ it = PyObject_NEW(CFURLRefObject, &CFURLRef_Type);
+ if (it == NULL) return NULL;
+ /* XXXX Should we tp_init or tp_new our basetype? */
+ it->ob_itself = itself;
+ it->ob_freeit = CFRelease;
+ return (PyObject *)it;
}
int CFURLRefObj_Convert(PyObject *v, CFURLRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
- if (!CFURLRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CFURLRef required");
- return 0;
- }
- *p_itself = ((CFURLRefObject *)v)->ob_itself;
- return 1;
+ if (!CFURLRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CFURLRef required");
+ return 0;
+ }
+ *p_itself = ((CFURLRefObject *)v)->ob_itself;
+ return 1;
}
static void CFURLRefObj_dealloc(CFURLRefObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit((CFTypeRef)self->ob_itself);
- self->ob_itself = NULL;
- }
- CFTypeRef_Type.tp_dealloc((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit((CFTypeRef)self->ob_itself);
+ self->ob_itself = NULL;
+ }
+ CFTypeRef_Type.tp_dealloc((PyObject *)self);
}
static PyObject *CFURLRefObj_CFURLCreateData(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDataRef _rv;
- CFStringEncoding encoding;
- Boolean escapeWhitespace;
- if (!PyArg_ParseTuple(_args, "ll",
- &encoding,
- &escapeWhitespace))
- return NULL;
- _rv = CFURLCreateData((CFAllocatorRef)NULL,
- _self->ob_itself,
- encoding,
- escapeWhitespace);
- _res = Py_BuildValue("O&",
- CFDataRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFDataRef _rv;
+ CFStringEncoding encoding;
+ Boolean escapeWhitespace;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &encoding,
+ &escapeWhitespace))
+ return NULL;
+ _rv = CFURLCreateData((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ encoding,
+ escapeWhitespace);
+ _res = Py_BuildValue("O&",
+ CFDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLGetFileSystemRepresentation(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Boolean resolveAgainstBase;
- UInt8 buffer;
- CFIndex maxBufLen;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Boolean resolveAgainstBase;
+ UInt8 buffer;
+ CFIndex maxBufLen;
#ifndef CFURLGetFileSystemRepresentation
- PyMac_PRECHECK(CFURLGetFileSystemRepresentation);
+ PyMac_PRECHECK(CFURLGetFileSystemRepresentation);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &resolveAgainstBase,
- &maxBufLen))
- return NULL;
- _rv = CFURLGetFileSystemRepresentation(_self->ob_itself,
- resolveAgainstBase,
- &buffer,
- maxBufLen);
- _res = Py_BuildValue("lb",
- _rv,
- buffer);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &resolveAgainstBase,
+ &maxBufLen))
+ return NULL;
+ _rv = CFURLGetFileSystemRepresentation(_self->ob_itself,
+ resolveAgainstBase,
+ &buffer,
+ maxBufLen);
+ _res = Py_BuildValue("lb",
+ _rv,
+ buffer);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyAbsoluteURL(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
#ifndef CFURLCopyAbsoluteURL
- PyMac_PRECHECK(CFURLCopyAbsoluteURL);
+ PyMac_PRECHECK(CFURLCopyAbsoluteURL);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyAbsoluteURL(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyAbsoluteURL(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLGetString(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLGetString
- PyMac_PRECHECK(CFURLGetString);
+ PyMac_PRECHECK(CFURLGetString);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLGetString(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLGetString(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLGetBaseURL(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
#ifndef CFURLGetBaseURL
- PyMac_PRECHECK(CFURLGetBaseURL);
+ PyMac_PRECHECK(CFURLGetBaseURL);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLGetBaseURL(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLGetBaseURL(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCanBeDecomposed(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef CFURLCanBeDecomposed
- PyMac_PRECHECK(CFURLCanBeDecomposed);
+ PyMac_PRECHECK(CFURLCanBeDecomposed);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCanBeDecomposed(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCanBeDecomposed(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyScheme(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyScheme
- PyMac_PRECHECK(CFURLCopyScheme);
+ PyMac_PRECHECK(CFURLCopyScheme);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyScheme(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyScheme(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyNetLocation(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyNetLocation
- PyMac_PRECHECK(CFURLCopyNetLocation);
+ PyMac_PRECHECK(CFURLCopyNetLocation);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyNetLocation(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyNetLocation(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyPath(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyPath
- PyMac_PRECHECK(CFURLCopyPath);
+ PyMac_PRECHECK(CFURLCopyPath);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyPath(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyPath(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyStrictPath(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- Boolean isAbsolute;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ Boolean isAbsolute;
#ifndef CFURLCopyStrictPath
- PyMac_PRECHECK(CFURLCopyStrictPath);
+ PyMac_PRECHECK(CFURLCopyStrictPath);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyStrictPath(_self->ob_itself,
- &isAbsolute);
- _res = Py_BuildValue("O&l",
- CFStringRefObj_New, _rv,
- isAbsolute);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyStrictPath(_self->ob_itself,
+ &isAbsolute);
+ _res = Py_BuildValue("O&l",
+ CFStringRefObj_New, _rv,
+ isAbsolute);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyFileSystemPath(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFURLPathStyle pathStyle;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFURLPathStyle pathStyle;
#ifndef CFURLCopyFileSystemPath
- PyMac_PRECHECK(CFURLCopyFileSystemPath);
+ PyMac_PRECHECK(CFURLCopyFileSystemPath);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &pathStyle))
- return NULL;
- _rv = CFURLCopyFileSystemPath(_self->ob_itself,
- pathStyle);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &pathStyle))
+ return NULL;
+ _rv = CFURLCopyFileSystemPath(_self->ob_itself,
+ pathStyle);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLHasDirectoryPath(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef CFURLHasDirectoryPath
- PyMac_PRECHECK(CFURLHasDirectoryPath);
+ PyMac_PRECHECK(CFURLHasDirectoryPath);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLHasDirectoryPath(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLHasDirectoryPath(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyResourceSpecifier(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyResourceSpecifier
- PyMac_PRECHECK(CFURLCopyResourceSpecifier);
+ PyMac_PRECHECK(CFURLCopyResourceSpecifier);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyResourceSpecifier(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyResourceSpecifier(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyHostName(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyHostName
- PyMac_PRECHECK(CFURLCopyHostName);
+ PyMac_PRECHECK(CFURLCopyHostName);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyHostName(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyHostName(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLGetPortNumber(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef CFURLGetPortNumber
- PyMac_PRECHECK(CFURLGetPortNumber);
+ PyMac_PRECHECK(CFURLGetPortNumber);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLGetPortNumber(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLGetPortNumber(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyUserName(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyUserName
- PyMac_PRECHECK(CFURLCopyUserName);
+ PyMac_PRECHECK(CFURLCopyUserName);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyUserName(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyUserName(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyPassword(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyPassword
- PyMac_PRECHECK(CFURLCopyPassword);
+ PyMac_PRECHECK(CFURLCopyPassword);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyPassword(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyPassword(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyParameterString(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringRef charactersToLeaveEscaped;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringRef charactersToLeaveEscaped;
#ifndef CFURLCopyParameterString
- PyMac_PRECHECK(CFURLCopyParameterString);
+ PyMac_PRECHECK(CFURLCopyParameterString);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &charactersToLeaveEscaped))
- return NULL;
- _rv = CFURLCopyParameterString(_self->ob_itself,
- charactersToLeaveEscaped);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &charactersToLeaveEscaped))
+ return NULL;
+ _rv = CFURLCopyParameterString(_self->ob_itself,
+ charactersToLeaveEscaped);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyQueryString(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringRef charactersToLeaveEscaped;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringRef charactersToLeaveEscaped;
#ifndef CFURLCopyQueryString
- PyMac_PRECHECK(CFURLCopyQueryString);
+ PyMac_PRECHECK(CFURLCopyQueryString);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &charactersToLeaveEscaped))
- return NULL;
- _rv = CFURLCopyQueryString(_self->ob_itself,
- charactersToLeaveEscaped);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &charactersToLeaveEscaped))
+ return NULL;
+ _rv = CFURLCopyQueryString(_self->ob_itself,
+ charactersToLeaveEscaped);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyFragment(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringRef charactersToLeaveEscaped;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringRef charactersToLeaveEscaped;
#ifndef CFURLCopyFragment
- PyMac_PRECHECK(CFURLCopyFragment);
+ PyMac_PRECHECK(CFURLCopyFragment);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &charactersToLeaveEscaped))
- return NULL;
- _rv = CFURLCopyFragment(_self->ob_itself,
- charactersToLeaveEscaped);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &charactersToLeaveEscaped))
+ return NULL;
+ _rv = CFURLCopyFragment(_self->ob_itself,
+ charactersToLeaveEscaped);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyLastPathComponent(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyLastPathComponent
- PyMac_PRECHECK(CFURLCopyLastPathComponent);
+ PyMac_PRECHECK(CFURLCopyLastPathComponent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyLastPathComponent(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyLastPathComponent(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCopyPathExtension(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
#ifndef CFURLCopyPathExtension
- PyMac_PRECHECK(CFURLCopyPathExtension);
+ PyMac_PRECHECK(CFURLCopyPathExtension);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCopyPathExtension(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCopyPathExtension(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCreateCopyAppendingPathComponent(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- CFStringRef pathComponent;
- Boolean isDirectory;
- if (!PyArg_ParseTuple(_args, "O&l",
- CFStringRefObj_Convert, &pathComponent,
- &isDirectory))
- return NULL;
- _rv = CFURLCreateCopyAppendingPathComponent((CFAllocatorRef)NULL,
- _self->ob_itself,
- pathComponent,
- isDirectory);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ CFStringRef pathComponent;
+ Boolean isDirectory;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CFStringRefObj_Convert, &pathComponent,
+ &isDirectory))
+ return NULL;
+ _rv = CFURLCreateCopyAppendingPathComponent((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ pathComponent,
+ isDirectory);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCreateCopyDeletingLastPathComponent(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCreateCopyDeletingLastPathComponent((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCreateCopyDeletingLastPathComponent((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCreateCopyAppendingPathExtension(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- CFStringRef extension;
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &extension))
- return NULL;
- _rv = CFURLCreateCopyAppendingPathExtension((CFAllocatorRef)NULL,
- _self->ob_itself,
- extension);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ CFStringRef extension;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &extension))
+ return NULL;
+ _rv = CFURLCreateCopyAppendingPathExtension((CFAllocatorRef)NULL,
+ _self->ob_itself,
+ extension);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLCreateCopyDeletingPathExtension(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLCreateCopyDeletingPathExtension((CFAllocatorRef)NULL,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLCreateCopyDeletingPathExtension((CFAllocatorRef)NULL,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CFURLRefObj_CFURLGetFSRef(CFURLRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- FSRef fsRef;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ FSRef fsRef;
#ifndef CFURLGetFSRef
- PyMac_PRECHECK(CFURLGetFSRef);
+ PyMac_PRECHECK(CFURLGetFSRef);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLGetFSRef(_self->ob_itself,
- &fsRef);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildFSRef, &fsRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLGetFSRef(_self->ob_itself,
+ &fsRef);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildFSRef, &fsRef);
+ return _res;
}
static PyMethodDef CFURLRefObj_methods[] = {
- {"CFURLCreateData", (PyCFunction)CFURLRefObj_CFURLCreateData, 1,
- PyDoc_STR("(CFStringEncoding encoding, Boolean escapeWhitespace) -> (CFDataRef _rv)")},
- {"CFURLGetFileSystemRepresentation", (PyCFunction)CFURLRefObj_CFURLGetFileSystemRepresentation, 1,
- PyDoc_STR("(Boolean resolveAgainstBase, CFIndex maxBufLen) -> (Boolean _rv, UInt8 buffer)")},
- {"CFURLCopyAbsoluteURL", (PyCFunction)CFURLRefObj_CFURLCopyAbsoluteURL, 1,
- PyDoc_STR("() -> (CFURLRef _rv)")},
- {"CFURLGetString", (PyCFunction)CFURLRefObj_CFURLGetString, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLGetBaseURL", (PyCFunction)CFURLRefObj_CFURLGetBaseURL, 1,
- PyDoc_STR("() -> (CFURLRef _rv)")},
- {"CFURLCanBeDecomposed", (PyCFunction)CFURLRefObj_CFURLCanBeDecomposed, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"CFURLCopyScheme", (PyCFunction)CFURLRefObj_CFURLCopyScheme, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyNetLocation", (PyCFunction)CFURLRefObj_CFURLCopyNetLocation, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyPath", (PyCFunction)CFURLRefObj_CFURLCopyPath, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyStrictPath", (PyCFunction)CFURLRefObj_CFURLCopyStrictPath, 1,
- PyDoc_STR("() -> (CFStringRef _rv, Boolean isAbsolute)")},
- {"CFURLCopyFileSystemPath", (PyCFunction)CFURLRefObj_CFURLCopyFileSystemPath, 1,
- PyDoc_STR("(CFURLPathStyle pathStyle) -> (CFStringRef _rv)")},
- {"CFURLHasDirectoryPath", (PyCFunction)CFURLRefObj_CFURLHasDirectoryPath, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"CFURLCopyResourceSpecifier", (PyCFunction)CFURLRefObj_CFURLCopyResourceSpecifier, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyHostName", (PyCFunction)CFURLRefObj_CFURLCopyHostName, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLGetPortNumber", (PyCFunction)CFURLRefObj_CFURLGetPortNumber, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"CFURLCopyUserName", (PyCFunction)CFURLRefObj_CFURLCopyUserName, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyPassword", (PyCFunction)CFURLRefObj_CFURLCopyPassword, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyParameterString", (PyCFunction)CFURLRefObj_CFURLCopyParameterString, 1,
- PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
- {"CFURLCopyQueryString", (PyCFunction)CFURLRefObj_CFURLCopyQueryString, 1,
- PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
- {"CFURLCopyFragment", (PyCFunction)CFURLRefObj_CFURLCopyFragment, 1,
- PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
- {"CFURLCopyLastPathComponent", (PyCFunction)CFURLRefObj_CFURLCopyLastPathComponent, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCopyPathExtension", (PyCFunction)CFURLRefObj_CFURLCopyPathExtension, 1,
- PyDoc_STR("() -> (CFStringRef _rv)")},
- {"CFURLCreateCopyAppendingPathComponent", (PyCFunction)CFURLRefObj_CFURLCreateCopyAppendingPathComponent, 1,
- PyDoc_STR("(CFStringRef pathComponent, Boolean isDirectory) -> (CFURLRef _rv)")},
- {"CFURLCreateCopyDeletingLastPathComponent", (PyCFunction)CFURLRefObj_CFURLCreateCopyDeletingLastPathComponent, 1,
- PyDoc_STR("() -> (CFURLRef _rv)")},
- {"CFURLCreateCopyAppendingPathExtension", (PyCFunction)CFURLRefObj_CFURLCreateCopyAppendingPathExtension, 1,
- PyDoc_STR("(CFStringRef extension) -> (CFURLRef _rv)")},
- {"CFURLCreateCopyDeletingPathExtension", (PyCFunction)CFURLRefObj_CFURLCreateCopyDeletingPathExtension, 1,
- PyDoc_STR("() -> (CFURLRef _rv)")},
- {"CFURLGetFSRef", (PyCFunction)CFURLRefObj_CFURLGetFSRef, 1,
- PyDoc_STR("() -> (Boolean _rv, FSRef fsRef)")},
- {NULL, NULL, 0}
+ {"CFURLCreateData", (PyCFunction)CFURLRefObj_CFURLCreateData, 1,
+ PyDoc_STR("(CFStringEncoding encoding, Boolean escapeWhitespace) -> (CFDataRef _rv)")},
+ {"CFURLGetFileSystemRepresentation", (PyCFunction)CFURLRefObj_CFURLGetFileSystemRepresentation, 1,
+ PyDoc_STR("(Boolean resolveAgainstBase, CFIndex maxBufLen) -> (Boolean _rv, UInt8 buffer)")},
+ {"CFURLCopyAbsoluteURL", (PyCFunction)CFURLRefObj_CFURLCopyAbsoluteURL, 1,
+ PyDoc_STR("() -> (CFURLRef _rv)")},
+ {"CFURLGetString", (PyCFunction)CFURLRefObj_CFURLGetString, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLGetBaseURL", (PyCFunction)CFURLRefObj_CFURLGetBaseURL, 1,
+ PyDoc_STR("() -> (CFURLRef _rv)")},
+ {"CFURLCanBeDecomposed", (PyCFunction)CFURLRefObj_CFURLCanBeDecomposed, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"CFURLCopyScheme", (PyCFunction)CFURLRefObj_CFURLCopyScheme, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyNetLocation", (PyCFunction)CFURLRefObj_CFURLCopyNetLocation, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyPath", (PyCFunction)CFURLRefObj_CFURLCopyPath, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyStrictPath", (PyCFunction)CFURLRefObj_CFURLCopyStrictPath, 1,
+ PyDoc_STR("() -> (CFStringRef _rv, Boolean isAbsolute)")},
+ {"CFURLCopyFileSystemPath", (PyCFunction)CFURLRefObj_CFURLCopyFileSystemPath, 1,
+ PyDoc_STR("(CFURLPathStyle pathStyle) -> (CFStringRef _rv)")},
+ {"CFURLHasDirectoryPath", (PyCFunction)CFURLRefObj_CFURLHasDirectoryPath, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"CFURLCopyResourceSpecifier", (PyCFunction)CFURLRefObj_CFURLCopyResourceSpecifier, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyHostName", (PyCFunction)CFURLRefObj_CFURLCopyHostName, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLGetPortNumber", (PyCFunction)CFURLRefObj_CFURLGetPortNumber, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"CFURLCopyUserName", (PyCFunction)CFURLRefObj_CFURLCopyUserName, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyPassword", (PyCFunction)CFURLRefObj_CFURLCopyPassword, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyParameterString", (PyCFunction)CFURLRefObj_CFURLCopyParameterString, 1,
+ PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
+ {"CFURLCopyQueryString", (PyCFunction)CFURLRefObj_CFURLCopyQueryString, 1,
+ PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
+ {"CFURLCopyFragment", (PyCFunction)CFURLRefObj_CFURLCopyFragment, 1,
+ PyDoc_STR("(CFStringRef charactersToLeaveEscaped) -> (CFStringRef _rv)")},
+ {"CFURLCopyLastPathComponent", (PyCFunction)CFURLRefObj_CFURLCopyLastPathComponent, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCopyPathExtension", (PyCFunction)CFURLRefObj_CFURLCopyPathExtension, 1,
+ PyDoc_STR("() -> (CFStringRef _rv)")},
+ {"CFURLCreateCopyAppendingPathComponent", (PyCFunction)CFURLRefObj_CFURLCreateCopyAppendingPathComponent, 1,
+ PyDoc_STR("(CFStringRef pathComponent, Boolean isDirectory) -> (CFURLRef _rv)")},
+ {"CFURLCreateCopyDeletingLastPathComponent", (PyCFunction)CFURLRefObj_CFURLCreateCopyDeletingLastPathComponent, 1,
+ PyDoc_STR("() -> (CFURLRef _rv)")},
+ {"CFURLCreateCopyAppendingPathExtension", (PyCFunction)CFURLRefObj_CFURLCreateCopyAppendingPathExtension, 1,
+ PyDoc_STR("(CFStringRef extension) -> (CFURLRef _rv)")},
+ {"CFURLCreateCopyDeletingPathExtension", (PyCFunction)CFURLRefObj_CFURLCreateCopyDeletingPathExtension, 1,
+ PyDoc_STR("() -> (CFURLRef _rv)")},
+ {"CFURLGetFSRef", (PyCFunction)CFURLRefObj_CFURLGetFSRef, 1,
+ PyDoc_STR("() -> (Boolean _rv, FSRef fsRef)")},
+ {NULL, NULL, 0}
};
#define CFURLRefObj_getsetlist NULL
@@ -3475,100 +3475,100 @@ static PyMethodDef CFURLRefObj_methods[] = {
static int CFURLRefObj_compare(CFURLRefObject *self, CFURLRefObject *other)
{
- /* XXXX Or should we use CFEqual?? */
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ /* XXXX Or should we use CFEqual?? */
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * CFURLRefObj_repr(CFURLRefObject *self)
{
- char buf[100];
- sprintf(buf, "<CFURL object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<CFURL object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int CFURLRefObj_hash(CFURLRefObject *self)
{
- /* XXXX Or should we use CFHash?? */
- return (int)self->ob_itself;
+ /* XXXX Or should we use CFHash?? */
+ return (int)self->ob_itself;
}
static int CFURLRefObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- CFURLRef itself;
- char *kw[] = {"itself", 0};
+ CFURLRef itself;
+ char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFURLRefObj_Convert, &itself))
- {
- ((CFURLRefObject *)_self)->ob_itself = itself;
- return 0;
- }
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFURLRefObj_Convert, &itself))
+ {
+ ((CFURLRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
- /* Any CFTypeRef descendent is allowed as initializer too */
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
- {
- ((CFURLRefObject *)_self)->ob_itself = itself;
- return 0;
- }
- return -1;
+ /* Any CFTypeRef descendent is allowed as initializer too */
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CFTypeRefObj_Convert, &itself))
+ {
+ ((CFURLRefObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ return -1;
}
#define CFURLRefObj_tp_alloc PyType_GenericAlloc
static PyObject *CFURLRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CFURLRefObject *)self)->ob_itself = NULL;
- ((CFURLRefObject *)self)->ob_freeit = CFRelease;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CFURLRefObject *)self)->ob_itself = NULL;
+ ((CFURLRefObject *)self)->ob_freeit = CFRelease;
+ return self;
}
#define CFURLRefObj_tp_free PyObject_Del
PyTypeObject CFURLRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CF.CFURLRef", /*tp_name*/
- sizeof(CFURLRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CFURLRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CFURLRefObj_compare, /*tp_compare*/
- (reprfunc) CFURLRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CFURLRefObj_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*/
- CFURLRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CFURLRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CFURLRefObj_tp_init, /* tp_init */
- CFURLRefObj_tp_alloc, /* tp_alloc */
- CFURLRefObj_tp_new, /* tp_new */
- CFURLRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CF.CFURLRef", /*tp_name*/
+ sizeof(CFURLRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CFURLRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CFURLRefObj_compare, /*tp_compare*/
+ (reprfunc) CFURLRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CFURLRefObj_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*/
+ CFURLRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CFURLRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CFURLRefObj_tp_init, /* tp_init */
+ CFURLRefObj_tp_alloc, /* tp_alloc */
+ CFURLRefObj_tp_new, /* tp_new */
+ CFURLRefObj_tp_free, /* tp_free */
};
/* -------------------- End object type CFURLRef -------------------- */
@@ -3576,1250 +3576,1250 @@ PyTypeObject CFURLRef_Type = {
static PyObject *CF___CFRangeMake(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFRange _rv;
- CFIndex loc;
- CFIndex len;
+ PyObject *_res = NULL;
+ CFRange _rv;
+ CFIndex loc;
+ CFIndex len;
#ifndef __CFRangeMake
- PyMac_PRECHECK(__CFRangeMake);
+ PyMac_PRECHECK(__CFRangeMake);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &loc,
- &len))
- return NULL;
- _rv = __CFRangeMake(loc,
- len);
- _res = Py_BuildValue("O&",
- CFRange_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &loc,
+ &len))
+ return NULL;
+ _rv = __CFRangeMake(loc,
+ len);
+ _res = Py_BuildValue("O&",
+ CFRange_New, _rv);
+ return _res;
}
static PyObject *CF_CFAllocatorGetTypeID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFAllocatorGetTypeID
- PyMac_PRECHECK(CFAllocatorGetTypeID);
+ PyMac_PRECHECK(CFAllocatorGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFAllocatorGetTypeID();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFAllocatorGetTypeID();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFAllocatorGetPreferredSizeForSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
- CFIndex size;
- CFOptionFlags hint;
+ PyObject *_res = NULL;
+ CFIndex _rv;
+ CFIndex size;
+ CFOptionFlags hint;
#ifndef CFAllocatorGetPreferredSizeForSize
- PyMac_PRECHECK(CFAllocatorGetPreferredSizeForSize);
+ PyMac_PRECHECK(CFAllocatorGetPreferredSizeForSize);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &size,
- &hint))
- return NULL;
- _rv = CFAllocatorGetPreferredSizeForSize((CFAllocatorRef)NULL,
- size,
- hint);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &size,
+ &hint))
+ return NULL;
+ _rv = CFAllocatorGetPreferredSizeForSize((CFAllocatorRef)NULL,
+ size,
+ hint);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFCopyTypeIDDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFTypeID type_id;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFTypeID type_id;
#ifndef CFCopyTypeIDDescription
- PyMac_PRECHECK(CFCopyTypeIDDescription);
+ PyMac_PRECHECK(CFCopyTypeIDDescription);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &type_id))
- return NULL;
- _rv = CFCopyTypeIDDescription(type_id);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &type_id))
+ return NULL;
+ _rv = CFCopyTypeIDDescription(type_id);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFArrayGetTypeID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFArrayGetTypeID
- PyMac_PRECHECK(CFArrayGetTypeID);
+ PyMac_PRECHECK(CFArrayGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFArrayGetTypeID();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFArrayGetTypeID();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFArrayCreateMutable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableArrayRef _rv;
- CFIndex capacity;
+ PyObject *_res = NULL;
+ CFMutableArrayRef _rv;
+ CFIndex capacity;
#ifndef CFArrayCreateMutable
- PyMac_PRECHECK(CFArrayCreateMutable);
+ PyMac_PRECHECK(CFArrayCreateMutable);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &capacity))
- return NULL;
- _rv = CFArrayCreateMutable((CFAllocatorRef)NULL,
- capacity,
- &kCFTypeArrayCallBacks);
- _res = Py_BuildValue("O&",
- CFMutableArrayRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &capacity))
+ return NULL;
+ _rv = CFArrayCreateMutable((CFAllocatorRef)NULL,
+ capacity,
+ &kCFTypeArrayCallBacks);
+ _res = Py_BuildValue("O&",
+ CFMutableArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFArrayCreateMutableCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableArrayRef _rv;
- CFIndex capacity;
- CFArrayRef theArray;
+ PyObject *_res = NULL;
+ CFMutableArrayRef _rv;
+ CFIndex capacity;
+ CFArrayRef theArray;
#ifndef CFArrayCreateMutableCopy
- PyMac_PRECHECK(CFArrayCreateMutableCopy);
+ PyMac_PRECHECK(CFArrayCreateMutableCopy);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &capacity,
- CFArrayRefObj_Convert, &theArray))
- return NULL;
- _rv = CFArrayCreateMutableCopy((CFAllocatorRef)NULL,
- capacity,
- theArray);
- _res = Py_BuildValue("O&",
- CFMutableArrayRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &capacity,
+ CFArrayRefObj_Convert, &theArray))
+ return NULL;
+ _rv = CFArrayCreateMutableCopy((CFAllocatorRef)NULL,
+ capacity,
+ theArray);
+ _res = Py_BuildValue("O&",
+ CFMutableArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFDataGetTypeID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFDataGetTypeID
- PyMac_PRECHECK(CFDataGetTypeID);
+ PyMac_PRECHECK(CFDataGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFDataGetTypeID();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFDataGetTypeID();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFDataCreate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDataRef _rv;
- unsigned char *bytes__in__;
- long bytes__len__;
- int bytes__in_len__;
+ PyObject *_res = NULL;
+ CFDataRef _rv;
+ unsigned char *bytes__in__;
+ long bytes__len__;
+ int bytes__in_len__;
#ifndef CFDataCreate
- PyMac_PRECHECK(CFDataCreate);
+ PyMac_PRECHECK(CFDataCreate);
#endif
- if (!PyArg_ParseTuple(_args, "s#",
- &bytes__in__, &bytes__in_len__))
- return NULL;
- bytes__len__ = bytes__in_len__;
- _rv = CFDataCreate((CFAllocatorRef)NULL,
- bytes__in__, bytes__len__);
- _res = Py_BuildValue("O&",
- CFDataRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#",
+ &bytes__in__, &bytes__in_len__))
+ return NULL;
+ bytes__len__ = bytes__in_len__;
+ _rv = CFDataCreate((CFAllocatorRef)NULL,
+ bytes__in__, bytes__len__);
+ _res = Py_BuildValue("O&",
+ CFDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFDataCreateWithBytesNoCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDataRef _rv;
- unsigned char *bytes__in__;
- long bytes__len__;
- int bytes__in_len__;
+ PyObject *_res = NULL;
+ CFDataRef _rv;
+ unsigned char *bytes__in__;
+ long bytes__len__;
+ int bytes__in_len__;
#ifndef CFDataCreateWithBytesNoCopy
- PyMac_PRECHECK(CFDataCreateWithBytesNoCopy);
+ PyMac_PRECHECK(CFDataCreateWithBytesNoCopy);
#endif
- if (!PyArg_ParseTuple(_args, "s#",
- &bytes__in__, &bytes__in_len__))
- return NULL;
- bytes__len__ = bytes__in_len__;
- _rv = CFDataCreateWithBytesNoCopy((CFAllocatorRef)NULL,
- bytes__in__, bytes__len__,
- (CFAllocatorRef)NULL);
- _res = Py_BuildValue("O&",
- CFDataRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#",
+ &bytes__in__, &bytes__in_len__))
+ return NULL;
+ bytes__len__ = bytes__in_len__;
+ _rv = CFDataCreateWithBytesNoCopy((CFAllocatorRef)NULL,
+ bytes__in__, bytes__len__,
+ (CFAllocatorRef)NULL);
+ _res = Py_BuildValue("O&",
+ CFDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFDataCreateMutable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableDataRef _rv;
- CFIndex capacity;
+ PyObject *_res = NULL;
+ CFMutableDataRef _rv;
+ CFIndex capacity;
#ifndef CFDataCreateMutable
- PyMac_PRECHECK(CFDataCreateMutable);
+ PyMac_PRECHECK(CFDataCreateMutable);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &capacity))
- return NULL;
- _rv = CFDataCreateMutable((CFAllocatorRef)NULL,
- capacity);
- _res = Py_BuildValue("O&",
- CFMutableDataRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &capacity))
+ return NULL;
+ _rv = CFDataCreateMutable((CFAllocatorRef)NULL,
+ capacity);
+ _res = Py_BuildValue("O&",
+ CFMutableDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFDataCreateMutableCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableDataRef _rv;
- CFIndex capacity;
- CFDataRef theData;
+ PyObject *_res = NULL;
+ CFMutableDataRef _rv;
+ CFIndex capacity;
+ CFDataRef theData;
#ifndef CFDataCreateMutableCopy
- PyMac_PRECHECK(CFDataCreateMutableCopy);
+ PyMac_PRECHECK(CFDataCreateMutableCopy);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &capacity,
- CFDataRefObj_Convert, &theData))
- return NULL;
- _rv = CFDataCreateMutableCopy((CFAllocatorRef)NULL,
- capacity,
- theData);
- _res = Py_BuildValue("O&",
- CFMutableDataRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &capacity,
+ CFDataRefObj_Convert, &theData))
+ return NULL;
+ _rv = CFDataCreateMutableCopy((CFAllocatorRef)NULL,
+ capacity,
+ theData);
+ _res = Py_BuildValue("O&",
+ CFMutableDataRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFDictionaryGetTypeID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFDictionaryGetTypeID
- PyMac_PRECHECK(CFDictionaryGetTypeID);
+ PyMac_PRECHECK(CFDictionaryGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFDictionaryGetTypeID();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFDictionaryGetTypeID();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFDictionaryCreateMutable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableDictionaryRef _rv;
- CFIndex capacity;
+ PyObject *_res = NULL;
+ CFMutableDictionaryRef _rv;
+ CFIndex capacity;
#ifndef CFDictionaryCreateMutable
- PyMac_PRECHECK(CFDictionaryCreateMutable);
+ PyMac_PRECHECK(CFDictionaryCreateMutable);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &capacity))
- return NULL;
- _rv = CFDictionaryCreateMutable((CFAllocatorRef)NULL,
- capacity,
- &kCFTypeDictionaryKeyCallBacks,
- &kCFTypeDictionaryValueCallBacks);
- _res = Py_BuildValue("O&",
- CFMutableDictionaryRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &capacity))
+ return NULL;
+ _rv = CFDictionaryCreateMutable((CFAllocatorRef)NULL,
+ capacity,
+ &kCFTypeDictionaryKeyCallBacks,
+ &kCFTypeDictionaryValueCallBacks);
+ _res = Py_BuildValue("O&",
+ CFMutableDictionaryRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFDictionaryCreateMutableCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableDictionaryRef _rv;
- CFIndex capacity;
- CFDictionaryRef theDict;
+ PyObject *_res = NULL;
+ CFMutableDictionaryRef _rv;
+ CFIndex capacity;
+ CFDictionaryRef theDict;
#ifndef CFDictionaryCreateMutableCopy
- PyMac_PRECHECK(CFDictionaryCreateMutableCopy);
+ PyMac_PRECHECK(CFDictionaryCreateMutableCopy);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &capacity,
- CFDictionaryRefObj_Convert, &theDict))
- return NULL;
- _rv = CFDictionaryCreateMutableCopy((CFAllocatorRef)NULL,
- capacity,
- theDict);
- _res = Py_BuildValue("O&",
- CFMutableDictionaryRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &capacity,
+ CFDictionaryRefObj_Convert, &theDict))
+ return NULL;
+ _rv = CFDictionaryCreateMutableCopy((CFAllocatorRef)NULL,
+ capacity,
+ theDict);
+ _res = Py_BuildValue("O&",
+ CFMutableDictionaryRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesCopyAppValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeRef _rv;
- CFStringRef key;
- CFStringRef applicationID;
+ PyObject *_res = NULL;
+ CFTypeRef _rv;
+ CFStringRef key;
+ CFStringRef applicationID;
#ifndef CFPreferencesCopyAppValue
- PyMac_PRECHECK(CFPreferencesCopyAppValue);
+ PyMac_PRECHECK(CFPreferencesCopyAppValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFStringRefObj_Convert, &key,
- CFStringRefObj_Convert, &applicationID))
- return NULL;
- _rv = CFPreferencesCopyAppValue(key,
- applicationID);
- _res = Py_BuildValue("O&",
- CFTypeRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFStringRefObj_Convert, &key,
+ CFStringRefObj_Convert, &applicationID))
+ return NULL;
+ _rv = CFPreferencesCopyAppValue(key,
+ applicationID);
+ _res = Py_BuildValue("O&",
+ CFTypeRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesGetAppBooleanValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringRef key;
- CFStringRef applicationID;
- Boolean keyExistsAndHasValidFormat;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringRef key;
+ CFStringRef applicationID;
+ Boolean keyExistsAndHasValidFormat;
#ifndef CFPreferencesGetAppBooleanValue
- PyMac_PRECHECK(CFPreferencesGetAppBooleanValue);
+ PyMac_PRECHECK(CFPreferencesGetAppBooleanValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFStringRefObj_Convert, &key,
- CFStringRefObj_Convert, &applicationID))
- return NULL;
- _rv = CFPreferencesGetAppBooleanValue(key,
- applicationID,
- &keyExistsAndHasValidFormat);
- _res = Py_BuildValue("ll",
- _rv,
- keyExistsAndHasValidFormat);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFStringRefObj_Convert, &key,
+ CFStringRefObj_Convert, &applicationID))
+ return NULL;
+ _rv = CFPreferencesGetAppBooleanValue(key,
+ applicationID,
+ &keyExistsAndHasValidFormat);
+ _res = Py_BuildValue("ll",
+ _rv,
+ keyExistsAndHasValidFormat);
+ return _res;
}
static PyObject *CF_CFPreferencesGetAppIntegerValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
- CFStringRef key;
- CFStringRef applicationID;
- Boolean keyExistsAndHasValidFormat;
+ PyObject *_res = NULL;
+ CFIndex _rv;
+ CFStringRef key;
+ CFStringRef applicationID;
+ Boolean keyExistsAndHasValidFormat;
#ifndef CFPreferencesGetAppIntegerValue
- PyMac_PRECHECK(CFPreferencesGetAppIntegerValue);
+ PyMac_PRECHECK(CFPreferencesGetAppIntegerValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFStringRefObj_Convert, &key,
- CFStringRefObj_Convert, &applicationID))
- return NULL;
- _rv = CFPreferencesGetAppIntegerValue(key,
- applicationID,
- &keyExistsAndHasValidFormat);
- _res = Py_BuildValue("ll",
- _rv,
- keyExistsAndHasValidFormat);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFStringRefObj_Convert, &key,
+ CFStringRefObj_Convert, &applicationID))
+ return NULL;
+ _rv = CFPreferencesGetAppIntegerValue(key,
+ applicationID,
+ &keyExistsAndHasValidFormat);
+ _res = Py_BuildValue("ll",
+ _rv,
+ keyExistsAndHasValidFormat);
+ return _res;
}
static PyObject *CF_CFPreferencesSetAppValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef key;
- CFTypeRef value;
- CFStringRef applicationID;
+ PyObject *_res = NULL;
+ CFStringRef key;
+ CFTypeRef value;
+ CFStringRef applicationID;
#ifndef CFPreferencesSetAppValue
- PyMac_PRECHECK(CFPreferencesSetAppValue);
+ PyMac_PRECHECK(CFPreferencesSetAppValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CFStringRefObj_Convert, &key,
- CFTypeRefObj_Convert, &value,
- CFStringRefObj_Convert, &applicationID))
- return NULL;
- CFPreferencesSetAppValue(key,
- value,
- applicationID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CFStringRefObj_Convert, &key,
+ CFTypeRefObj_Convert, &value,
+ CFStringRefObj_Convert, &applicationID))
+ return NULL;
+ CFPreferencesSetAppValue(key,
+ value,
+ applicationID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CF_CFPreferencesAddSuitePreferencesToApp(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef applicationID;
- CFStringRef suiteID;
+ PyObject *_res = NULL;
+ CFStringRef applicationID;
+ CFStringRef suiteID;
#ifndef CFPreferencesAddSuitePreferencesToApp
- PyMac_PRECHECK(CFPreferencesAddSuitePreferencesToApp);
+ PyMac_PRECHECK(CFPreferencesAddSuitePreferencesToApp);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &suiteID))
- return NULL;
- CFPreferencesAddSuitePreferencesToApp(applicationID,
- suiteID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &suiteID))
+ return NULL;
+ CFPreferencesAddSuitePreferencesToApp(applicationID,
+ suiteID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CF_CFPreferencesRemoveSuitePreferencesFromApp(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef applicationID;
- CFStringRef suiteID;
+ PyObject *_res = NULL;
+ CFStringRef applicationID;
+ CFStringRef suiteID;
#ifndef CFPreferencesRemoveSuitePreferencesFromApp
- PyMac_PRECHECK(CFPreferencesRemoveSuitePreferencesFromApp);
+ PyMac_PRECHECK(CFPreferencesRemoveSuitePreferencesFromApp);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &suiteID))
- return NULL;
- CFPreferencesRemoveSuitePreferencesFromApp(applicationID,
- suiteID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &suiteID))
+ return NULL;
+ CFPreferencesRemoveSuitePreferencesFromApp(applicationID,
+ suiteID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CF_CFPreferencesAppSynchronize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringRef applicationID;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringRef applicationID;
#ifndef CFPreferencesAppSynchronize
- PyMac_PRECHECK(CFPreferencesAppSynchronize);
+ PyMac_PRECHECK(CFPreferencesAppSynchronize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &applicationID))
- return NULL;
- _rv = CFPreferencesAppSynchronize(applicationID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &applicationID))
+ return NULL;
+ _rv = CFPreferencesAppSynchronize(applicationID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesCopyValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeRef _rv;
- CFStringRef key;
- CFStringRef applicationID;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ CFTypeRef _rv;
+ CFStringRef key;
+ CFStringRef applicationID;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesCopyValue
- PyMac_PRECHECK(CFPreferencesCopyValue);
+ PyMac_PRECHECK(CFPreferencesCopyValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CFStringRefObj_Convert, &key,
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- _rv = CFPreferencesCopyValue(key,
- applicationID,
- userName,
- hostName);
- _res = Py_BuildValue("O&",
- CFTypeRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CFStringRefObj_Convert, &key,
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ _rv = CFPreferencesCopyValue(key,
+ applicationID,
+ userName,
+ hostName);
+ _res = Py_BuildValue("O&",
+ CFTypeRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesCopyMultiple(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDictionaryRef _rv;
- CFArrayRef keysToFetch;
- CFStringRef applicationID;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ CFDictionaryRef _rv;
+ CFArrayRef keysToFetch;
+ CFStringRef applicationID;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesCopyMultiple
- PyMac_PRECHECK(CFPreferencesCopyMultiple);
+ PyMac_PRECHECK(CFPreferencesCopyMultiple);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CFArrayRefObj_Convert, &keysToFetch,
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- _rv = CFPreferencesCopyMultiple(keysToFetch,
- applicationID,
- userName,
- hostName);
- _res = Py_BuildValue("O&",
- CFDictionaryRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CFArrayRefObj_Convert, &keysToFetch,
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ _rv = CFPreferencesCopyMultiple(keysToFetch,
+ applicationID,
+ userName,
+ hostName);
+ _res = Py_BuildValue("O&",
+ CFDictionaryRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesSetValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef key;
- CFTypeRef value;
- CFStringRef applicationID;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ CFStringRef key;
+ CFTypeRef value;
+ CFStringRef applicationID;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesSetValue
- PyMac_PRECHECK(CFPreferencesSetValue);
+ PyMac_PRECHECK(CFPreferencesSetValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
- CFStringRefObj_Convert, &key,
- CFTypeRefObj_Convert, &value,
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- CFPreferencesSetValue(key,
- value,
- applicationID,
- userName,
- hostName);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
+ CFStringRefObj_Convert, &key,
+ CFTypeRefObj_Convert, &value,
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ CFPreferencesSetValue(key,
+ value,
+ applicationID,
+ userName,
+ hostName);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CF_CFPreferencesSetMultiple(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFDictionaryRef keysToSet;
- CFArrayRef keysToRemove;
- CFStringRef applicationID;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ CFDictionaryRef keysToSet;
+ CFArrayRef keysToRemove;
+ CFStringRef applicationID;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesSetMultiple
- PyMac_PRECHECK(CFPreferencesSetMultiple);
+ PyMac_PRECHECK(CFPreferencesSetMultiple);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
- CFDictionaryRefObj_Convert, &keysToSet,
- CFArrayRefObj_Convert, &keysToRemove,
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- CFPreferencesSetMultiple(keysToSet,
- keysToRemove,
- applicationID,
- userName,
- hostName);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
+ CFDictionaryRefObj_Convert, &keysToSet,
+ CFArrayRefObj_Convert, &keysToRemove,
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ CFPreferencesSetMultiple(keysToSet,
+ keysToRemove,
+ applicationID,
+ userName,
+ hostName);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CF_CFPreferencesSynchronize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringRef applicationID;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringRef applicationID;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesSynchronize
- PyMac_PRECHECK(CFPreferencesSynchronize);
+ PyMac_PRECHECK(CFPreferencesSynchronize);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- _rv = CFPreferencesSynchronize(applicationID,
- userName,
- hostName);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ _rv = CFPreferencesSynchronize(applicationID,
+ userName,
+ hostName);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesCopyApplicationList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFArrayRef _rv;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ CFArrayRef _rv;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesCopyApplicationList
- PyMac_PRECHECK(CFPreferencesCopyApplicationList);
+ PyMac_PRECHECK(CFPreferencesCopyApplicationList);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- _rv = CFPreferencesCopyApplicationList(userName,
- hostName);
- _res = Py_BuildValue("O&",
- CFArrayRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ _rv = CFPreferencesCopyApplicationList(userName,
+ hostName);
+ _res = Py_BuildValue("O&",
+ CFArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFPreferencesCopyKeyList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFArrayRef _rv;
- CFStringRef applicationID;
- CFStringRef userName;
- CFStringRef hostName;
+ PyObject *_res = NULL;
+ CFArrayRef _rv;
+ CFStringRef applicationID;
+ CFStringRef userName;
+ CFStringRef hostName;
#ifndef CFPreferencesCopyKeyList
- PyMac_PRECHECK(CFPreferencesCopyKeyList);
+ PyMac_PRECHECK(CFPreferencesCopyKeyList);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CFStringRefObj_Convert, &applicationID,
- CFStringRefObj_Convert, &userName,
- CFStringRefObj_Convert, &hostName))
- return NULL;
- _rv = CFPreferencesCopyKeyList(applicationID,
- userName,
- hostName);
- _res = Py_BuildValue("O&",
- CFArrayRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CFStringRefObj_Convert, &applicationID,
+ CFStringRefObj_Convert, &userName,
+ CFStringRefObj_Convert, &hostName))
+ return NULL;
+ _rv = CFPreferencesCopyKeyList(applicationID,
+ userName,
+ hostName);
+ _res = Py_BuildValue("O&",
+ CFArrayRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringGetTypeID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFStringGetTypeID
- PyMac_PRECHECK(CFStringGetTypeID);
+ PyMac_PRECHECK(CFStringGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetTypeID();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetTypeID();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithPascalString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- Str255 pStr;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ Str255 pStr;
+ CFStringEncoding encoding;
#ifndef CFStringCreateWithPascalString
- PyMac_PRECHECK(CFStringCreateWithPascalString);
+ PyMac_PRECHECK(CFStringCreateWithPascalString);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetStr255, pStr,
- &encoding))
- return NULL;
- _rv = CFStringCreateWithPascalString((CFAllocatorRef)NULL,
- pStr,
- encoding);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetStr255, pStr,
+ &encoding))
+ return NULL;
+ _rv = CFStringCreateWithPascalString((CFAllocatorRef)NULL,
+ pStr,
+ encoding);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithCString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- char* cStr;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ char* cStr;
+ CFStringEncoding encoding;
#ifndef CFStringCreateWithCString
- PyMac_PRECHECK(CFStringCreateWithCString);
+ PyMac_PRECHECK(CFStringCreateWithCString);
#endif
- if (!PyArg_ParseTuple(_args, "sl",
- &cStr,
- &encoding))
- return NULL;
- _rv = CFStringCreateWithCString((CFAllocatorRef)NULL,
- cStr,
- encoding);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "sl",
+ &cStr,
+ &encoding))
+ return NULL;
+ _rv = CFStringCreateWithCString((CFAllocatorRef)NULL,
+ cStr,
+ encoding);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithCharacters(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- UniChar *chars__in__;
- UniCharCount chars__len__;
- int chars__in_len__;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ UniChar *chars__in__;
+ UniCharCount chars__len__;
+ int chars__in_len__;
#ifndef CFStringCreateWithCharacters
- PyMac_PRECHECK(CFStringCreateWithCharacters);
+ PyMac_PRECHECK(CFStringCreateWithCharacters);
#endif
- if (!PyArg_ParseTuple(_args, "u#",
- &chars__in__, &chars__in_len__))
- return NULL;
- chars__len__ = chars__in_len__;
- _rv = CFStringCreateWithCharacters((CFAllocatorRef)NULL,
- chars__in__, chars__len__);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "u#",
+ &chars__in__, &chars__in_len__))
+ return NULL;
+ chars__len__ = chars__in_len__;
+ _rv = CFStringCreateWithCharacters((CFAllocatorRef)NULL,
+ chars__in__, chars__len__);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithPascalStringNoCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- Str255 pStr;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ Str255 pStr;
+ CFStringEncoding encoding;
#ifndef CFStringCreateWithPascalStringNoCopy
- PyMac_PRECHECK(CFStringCreateWithPascalStringNoCopy);
+ PyMac_PRECHECK(CFStringCreateWithPascalStringNoCopy);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetStr255, pStr,
- &encoding))
- return NULL;
- _rv = CFStringCreateWithPascalStringNoCopy((CFAllocatorRef)NULL,
- pStr,
- encoding,
- (CFAllocatorRef)NULL);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetStr255, pStr,
+ &encoding))
+ return NULL;
+ _rv = CFStringCreateWithPascalStringNoCopy((CFAllocatorRef)NULL,
+ pStr,
+ encoding,
+ (CFAllocatorRef)NULL);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithCStringNoCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- char* cStr;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ char* cStr;
+ CFStringEncoding encoding;
#ifndef CFStringCreateWithCStringNoCopy
- PyMac_PRECHECK(CFStringCreateWithCStringNoCopy);
+ PyMac_PRECHECK(CFStringCreateWithCStringNoCopy);
#endif
- if (!PyArg_ParseTuple(_args, "sl",
- &cStr,
- &encoding))
- return NULL;
- _rv = CFStringCreateWithCStringNoCopy((CFAllocatorRef)NULL,
- cStr,
- encoding,
- (CFAllocatorRef)NULL);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "sl",
+ &cStr,
+ &encoding))
+ return NULL;
+ _rv = CFStringCreateWithCStringNoCopy((CFAllocatorRef)NULL,
+ cStr,
+ encoding,
+ (CFAllocatorRef)NULL);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithCharactersNoCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- UniChar *chars__in__;
- UniCharCount chars__len__;
- int chars__in_len__;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ UniChar *chars__in__;
+ UniCharCount chars__len__;
+ int chars__in_len__;
#ifndef CFStringCreateWithCharactersNoCopy
- PyMac_PRECHECK(CFStringCreateWithCharactersNoCopy);
+ PyMac_PRECHECK(CFStringCreateWithCharactersNoCopy);
#endif
- if (!PyArg_ParseTuple(_args, "u#",
- &chars__in__, &chars__in_len__))
- return NULL;
- chars__len__ = chars__in_len__;
- _rv = CFStringCreateWithCharactersNoCopy((CFAllocatorRef)NULL,
- chars__in__, chars__len__,
- (CFAllocatorRef)NULL);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "u#",
+ &chars__in__, &chars__in_len__))
+ return NULL;
+ chars__len__ = chars__in_len__;
+ _rv = CFStringCreateWithCharactersNoCopy((CFAllocatorRef)NULL,
+ chars__in__, chars__len__,
+ (CFAllocatorRef)NULL);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateMutable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableStringRef _rv;
- CFIndex maxLength;
+ PyObject *_res = NULL;
+ CFMutableStringRef _rv;
+ CFIndex maxLength;
#ifndef CFStringCreateMutable
- PyMac_PRECHECK(CFStringCreateMutable);
+ PyMac_PRECHECK(CFStringCreateMutable);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &maxLength))
- return NULL;
- _rv = CFStringCreateMutable((CFAllocatorRef)NULL,
- maxLength);
- _res = Py_BuildValue("O&",
- CFMutableStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &maxLength))
+ return NULL;
+ _rv = CFStringCreateMutable((CFAllocatorRef)NULL,
+ maxLength);
+ _res = Py_BuildValue("O&",
+ CFMutableStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateMutableCopy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFMutableStringRef _rv;
- CFIndex maxLength;
- CFStringRef theString;
+ PyObject *_res = NULL;
+ CFMutableStringRef _rv;
+ CFIndex maxLength;
+ CFStringRef theString;
#ifndef CFStringCreateMutableCopy
- PyMac_PRECHECK(CFStringCreateMutableCopy);
+ PyMac_PRECHECK(CFStringCreateMutableCopy);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &maxLength,
- CFStringRefObj_Convert, &theString))
- return NULL;
- _rv = CFStringCreateMutableCopy((CFAllocatorRef)NULL,
- maxLength,
- theString);
- _res = Py_BuildValue("O&",
- CFMutableStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &maxLength,
+ CFStringRefObj_Convert, &theString))
+ return NULL;
+ _rv = CFStringCreateMutableCopy((CFAllocatorRef)NULL,
+ maxLength,
+ theString);
+ _res = Py_BuildValue("O&",
+ CFMutableStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringCreateWithBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- unsigned char *bytes__in__;
- long bytes__len__;
- int bytes__in_len__;
- CFStringEncoding encoding;
- Boolean isExternalRepresentation;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ unsigned char *bytes__in__;
+ long bytes__len__;
+ int bytes__in_len__;
+ CFStringEncoding encoding;
+ Boolean isExternalRepresentation;
#ifndef CFStringCreateWithBytes
- PyMac_PRECHECK(CFStringCreateWithBytes);
+ PyMac_PRECHECK(CFStringCreateWithBytes);
#endif
- if (!PyArg_ParseTuple(_args, "s#ll",
- &bytes__in__, &bytes__in_len__,
- &encoding,
- &isExternalRepresentation))
- return NULL;
- bytes__len__ = bytes__in_len__;
- _rv = CFStringCreateWithBytes((CFAllocatorRef)NULL,
- bytes__in__, bytes__len__,
- encoding,
- isExternalRepresentation);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#ll",
+ &bytes__in__, &bytes__in_len__,
+ &encoding,
+ &isExternalRepresentation))
+ return NULL;
+ bytes__len__ = bytes__in_len__;
+ _rv = CFStringCreateWithBytes((CFAllocatorRef)NULL,
+ bytes__in__, bytes__len__,
+ encoding,
+ isExternalRepresentation);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringGetSystemEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
#ifndef CFStringGetSystemEncoding
- PyMac_PRECHECK(CFStringGetSystemEncoding);
+ PyMac_PRECHECK(CFStringGetSystemEncoding);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFStringGetSystemEncoding();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFStringGetSystemEncoding();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringGetMaximumSizeForEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFIndex _rv;
- CFIndex length;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFIndex _rv;
+ CFIndex length;
+ CFStringEncoding encoding;
#ifndef CFStringGetMaximumSizeForEncoding
- PyMac_PRECHECK(CFStringGetMaximumSizeForEncoding);
+ PyMac_PRECHECK(CFStringGetMaximumSizeForEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &length,
- &encoding))
- return NULL;
- _rv = CFStringGetMaximumSizeForEncoding(length,
- encoding);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &length,
+ &encoding))
+ return NULL;
+ _rv = CFStringGetMaximumSizeForEncoding(length,
+ encoding);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringIsEncodingAvailable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CFStringEncoding encoding;
#ifndef CFStringIsEncodingAvailable
- PyMac_PRECHECK(CFStringIsEncodingAvailable);
+ PyMac_PRECHECK(CFStringIsEncodingAvailable);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringIsEncodingAvailable(encoding);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringIsEncodingAvailable(encoding);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringGetNameOfEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringEncoding encoding;
#ifndef CFStringGetNameOfEncoding
- PyMac_PRECHECK(CFStringGetNameOfEncoding);
+ PyMac_PRECHECK(CFStringGetNameOfEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringGetNameOfEncoding(encoding);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringGetNameOfEncoding(encoding);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringConvertEncodingToNSStringEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ CFStringEncoding encoding;
#ifndef CFStringConvertEncodingToNSStringEncoding
- PyMac_PRECHECK(CFStringConvertEncodingToNSStringEncoding);
+ PyMac_PRECHECK(CFStringConvertEncodingToNSStringEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringConvertEncodingToNSStringEncoding(encoding);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringConvertEncodingToNSStringEncoding(encoding);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringConvertNSStringEncodingToEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
- UInt32 encoding;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
+ UInt32 encoding;
#ifndef CFStringConvertNSStringEncodingToEncoding
- PyMac_PRECHECK(CFStringConvertNSStringEncodingToEncoding);
+ PyMac_PRECHECK(CFStringConvertNSStringEncodingToEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringConvertNSStringEncodingToEncoding(encoding);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringConvertNSStringEncodingToEncoding(encoding);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringConvertEncodingToWindowsCodepage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ CFStringEncoding encoding;
#ifndef CFStringConvertEncodingToWindowsCodepage
- PyMac_PRECHECK(CFStringConvertEncodingToWindowsCodepage);
+ PyMac_PRECHECK(CFStringConvertEncodingToWindowsCodepage);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringConvertEncodingToWindowsCodepage(encoding);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringConvertEncodingToWindowsCodepage(encoding);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringConvertWindowsCodepageToEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
- UInt32 codepage;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
+ UInt32 codepage;
#ifndef CFStringConvertWindowsCodepageToEncoding
- PyMac_PRECHECK(CFStringConvertWindowsCodepageToEncoding);
+ PyMac_PRECHECK(CFStringConvertWindowsCodepageToEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &codepage))
- return NULL;
- _rv = CFStringConvertWindowsCodepageToEncoding(codepage);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &codepage))
+ return NULL;
+ _rv = CFStringConvertWindowsCodepageToEncoding(codepage);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFStringConvertEncodingToIANACharSetName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ CFStringEncoding encoding;
#ifndef CFStringConvertEncodingToIANACharSetName
- PyMac_PRECHECK(CFStringConvertEncodingToIANACharSetName);
+ PyMac_PRECHECK(CFStringConvertEncodingToIANACharSetName);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringConvertEncodingToIANACharSetName(encoding);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringConvertEncodingToIANACharSetName(encoding);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFStringGetMostCompatibleMacStringEncoding(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringEncoding _rv;
- CFStringEncoding encoding;
+ PyObject *_res = NULL;
+ CFStringEncoding _rv;
+ CFStringEncoding encoding;
#ifndef CFStringGetMostCompatibleMacStringEncoding
- PyMac_PRECHECK(CFStringGetMostCompatibleMacStringEncoding);
+ PyMac_PRECHECK(CFStringGetMostCompatibleMacStringEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &encoding))
- return NULL;
- _rv = CFStringGetMostCompatibleMacStringEncoding(encoding);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &encoding))
+ return NULL;
+ _rv = CFStringGetMostCompatibleMacStringEncoding(encoding);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF___CFStringMakeConstantString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFStringRef _rv;
- char* cStr;
+ PyObject *_res = NULL;
+ CFStringRef _rv;
+ char* cStr;
#ifndef __CFStringMakeConstantString
- PyMac_PRECHECK(__CFStringMakeConstantString);
+ PyMac_PRECHECK(__CFStringMakeConstantString);
#endif
- if (!PyArg_ParseTuple(_args, "s",
- &cStr))
- return NULL;
- _rv = __CFStringMakeConstantString(cStr);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s",
+ &cStr))
+ return NULL;
+ _rv = __CFStringMakeConstantString(cStr);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFURLGetTypeID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFTypeID _rv;
+ PyObject *_res = NULL;
+ CFTypeID _rv;
#ifndef CFURLGetTypeID
- PyMac_PRECHECK(CFURLGetTypeID);
+ PyMac_PRECHECK(CFURLGetTypeID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CFURLGetTypeID();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CFURLGetTypeID();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CF_CFURLCreateWithBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- unsigned char *URLBytes__in__;
- long URLBytes__len__;
- int URLBytes__in_len__;
- CFStringEncoding encoding;
- CFURLRef baseURL;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ unsigned char *URLBytes__in__;
+ long URLBytes__len__;
+ int URLBytes__in_len__;
+ CFStringEncoding encoding;
+ CFURLRef baseURL;
#ifndef CFURLCreateWithBytes
- PyMac_PRECHECK(CFURLCreateWithBytes);
+ PyMac_PRECHECK(CFURLCreateWithBytes);
#endif
- if (!PyArg_ParseTuple(_args, "s#lO&",
- &URLBytes__in__, &URLBytes__in_len__,
- &encoding,
- OptionalCFURLRefObj_Convert, &baseURL))
- return NULL;
- URLBytes__len__ = URLBytes__in_len__;
- _rv = CFURLCreateWithBytes((CFAllocatorRef)NULL,
- URLBytes__in__, URLBytes__len__,
- encoding,
- baseURL);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#lO&",
+ &URLBytes__in__, &URLBytes__in_len__,
+ &encoding,
+ OptionalCFURLRefObj_Convert, &baseURL))
+ return NULL;
+ URLBytes__len__ = URLBytes__in_len__;
+ _rv = CFURLCreateWithBytes((CFAllocatorRef)NULL,
+ URLBytes__in__, URLBytes__len__,
+ encoding,
+ baseURL);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFURLCreateFromFileSystemRepresentation(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- unsigned char *buffer__in__;
- long buffer__len__;
- int buffer__in_len__;
- Boolean isDirectory;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ unsigned char *buffer__in__;
+ long buffer__len__;
+ int buffer__in_len__;
+ Boolean isDirectory;
#ifndef CFURLCreateFromFileSystemRepresentation
- PyMac_PRECHECK(CFURLCreateFromFileSystemRepresentation);
+ PyMac_PRECHECK(CFURLCreateFromFileSystemRepresentation);
#endif
- if (!PyArg_ParseTuple(_args, "s#l",
- &buffer__in__, &buffer__in_len__,
- &isDirectory))
- return NULL;
- buffer__len__ = buffer__in_len__;
- _rv = CFURLCreateFromFileSystemRepresentation((CFAllocatorRef)NULL,
- buffer__in__, buffer__len__,
- isDirectory);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#l",
+ &buffer__in__, &buffer__in_len__,
+ &isDirectory))
+ return NULL;
+ buffer__len__ = buffer__in_len__;
+ _rv = CFURLCreateFromFileSystemRepresentation((CFAllocatorRef)NULL,
+ buffer__in__, buffer__len__,
+ isDirectory);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFURLCreateFromFileSystemRepresentationRelativeToBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- unsigned char *buffer__in__;
- long buffer__len__;
- int buffer__in_len__;
- Boolean isDirectory;
- CFURLRef baseURL;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ unsigned char *buffer__in__;
+ long buffer__len__;
+ int buffer__in_len__;
+ Boolean isDirectory;
+ CFURLRef baseURL;
#ifndef CFURLCreateFromFileSystemRepresentationRelativeToBase
- PyMac_PRECHECK(CFURLCreateFromFileSystemRepresentationRelativeToBase);
+ PyMac_PRECHECK(CFURLCreateFromFileSystemRepresentationRelativeToBase);
#endif
- if (!PyArg_ParseTuple(_args, "s#lO&",
- &buffer__in__, &buffer__in_len__,
- &isDirectory,
- OptionalCFURLRefObj_Convert, &baseURL))
- return NULL;
- buffer__len__ = buffer__in_len__;
- _rv = CFURLCreateFromFileSystemRepresentationRelativeToBase((CFAllocatorRef)NULL,
- buffer__in__, buffer__len__,
- isDirectory,
- baseURL);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#lO&",
+ &buffer__in__, &buffer__in_len__,
+ &isDirectory,
+ OptionalCFURLRefObj_Convert, &baseURL))
+ return NULL;
+ buffer__len__ = buffer__in_len__;
+ _rv = CFURLCreateFromFileSystemRepresentationRelativeToBase((CFAllocatorRef)NULL,
+ buffer__in__, buffer__len__,
+ isDirectory,
+ baseURL);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_CFURLCreateFromFSRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CFURLRef _rv;
- FSRef fsRef;
+ PyObject *_res = NULL;
+ CFURLRef _rv;
+ FSRef fsRef;
#ifndef CFURLCreateFromFSRef
- PyMac_PRECHECK(CFURLCreateFromFSRef);
+ PyMac_PRECHECK(CFURLCreateFromFSRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSRef, &fsRef))
- return NULL;
- _rv = CFURLCreateFromFSRef((CFAllocatorRef)NULL,
- &fsRef);
- _res = Py_BuildValue("O&",
- CFURLRefObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSRef, &fsRef))
+ return NULL;
+ _rv = CFURLCreateFromFSRef((CFAllocatorRef)NULL,
+ &fsRef);
+ _res = Py_BuildValue("O&",
+ CFURLRefObj_New, _rv);
+ return _res;
}
static PyObject *CF_toCF(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- CFTypeRef rv;
- CFTypeID typeid;
+ CFTypeRef rv;
+ CFTypeID typeid;
- if (!PyArg_ParseTuple(_args, "O&", PyCF_Python2CF, &rv))
- return NULL;
- typeid = CFGetTypeID(rv);
+ if (!PyArg_ParseTuple(_args, "O&", PyCF_Python2CF, &rv))
+ return NULL;
+ typeid = CFGetTypeID(rv);
- if (typeid == CFStringGetTypeID())
- return Py_BuildValue("O&", CFStringRefObj_New, rv);
- if (typeid == CFArrayGetTypeID())
- return Py_BuildValue("O&", CFArrayRefObj_New, rv);
- if (typeid == CFDictionaryGetTypeID())
- return Py_BuildValue("O&", CFDictionaryRefObj_New, rv);
- if (typeid == CFURLGetTypeID())
- return Py_BuildValue("O&", CFURLRefObj_New, rv);
+ if (typeid == CFStringGetTypeID())
+ return Py_BuildValue("O&", CFStringRefObj_New, rv);
+ if (typeid == CFArrayGetTypeID())
+ return Py_BuildValue("O&", CFArrayRefObj_New, rv);
+ if (typeid == CFDictionaryGetTypeID())
+ return Py_BuildValue("O&", CFDictionaryRefObj_New, rv);
+ if (typeid == CFURLGetTypeID())
+ return Py_BuildValue("O&", CFURLRefObj_New, rv);
- _res = Py_BuildValue("O&", CFTypeRefObj_New, rv);
- return _res;
+ _res = Py_BuildValue("O&", CFTypeRefObj_New, rv);
+ return _res;
}
static PyMethodDef CF_methods[] = {
- {"__CFRangeMake", (PyCFunction)CF___CFRangeMake, 1,
- PyDoc_STR("(CFIndex loc, CFIndex len) -> (CFRange _rv)")},
- {"CFAllocatorGetTypeID", (PyCFunction)CF_CFAllocatorGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFAllocatorGetPreferredSizeForSize", (PyCFunction)CF_CFAllocatorGetPreferredSizeForSize, 1,
- PyDoc_STR("(CFIndex size, CFOptionFlags hint) -> (CFIndex _rv)")},
- {"CFCopyTypeIDDescription", (PyCFunction)CF_CFCopyTypeIDDescription, 1,
- PyDoc_STR("(CFTypeID type_id) -> (CFStringRef _rv)")},
- {"CFArrayGetTypeID", (PyCFunction)CF_CFArrayGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFArrayCreateMutable", (PyCFunction)CF_CFArrayCreateMutable, 1,
- PyDoc_STR("(CFIndex capacity) -> (CFMutableArrayRef _rv)")},
- {"CFArrayCreateMutableCopy", (PyCFunction)CF_CFArrayCreateMutableCopy, 1,
- PyDoc_STR("(CFIndex capacity, CFArrayRef theArray) -> (CFMutableArrayRef _rv)")},
- {"CFDataGetTypeID", (PyCFunction)CF_CFDataGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFDataCreate", (PyCFunction)CF_CFDataCreate, 1,
- PyDoc_STR("(Buffer bytes) -> (CFDataRef _rv)")},
- {"CFDataCreateWithBytesNoCopy", (PyCFunction)CF_CFDataCreateWithBytesNoCopy, 1,
- PyDoc_STR("(Buffer bytes) -> (CFDataRef _rv)")},
- {"CFDataCreateMutable", (PyCFunction)CF_CFDataCreateMutable, 1,
- PyDoc_STR("(CFIndex capacity) -> (CFMutableDataRef _rv)")},
- {"CFDataCreateMutableCopy", (PyCFunction)CF_CFDataCreateMutableCopy, 1,
- PyDoc_STR("(CFIndex capacity, CFDataRef theData) -> (CFMutableDataRef _rv)")},
- {"CFDictionaryGetTypeID", (PyCFunction)CF_CFDictionaryGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFDictionaryCreateMutable", (PyCFunction)CF_CFDictionaryCreateMutable, 1,
- PyDoc_STR("(CFIndex capacity) -> (CFMutableDictionaryRef _rv)")},
- {"CFDictionaryCreateMutableCopy", (PyCFunction)CF_CFDictionaryCreateMutableCopy, 1,
- PyDoc_STR("(CFIndex capacity, CFDictionaryRef theDict) -> (CFMutableDictionaryRef _rv)")},
- {"CFPreferencesCopyAppValue", (PyCFunction)CF_CFPreferencesCopyAppValue, 1,
- PyDoc_STR("(CFStringRef key, CFStringRef applicationID) -> (CFTypeRef _rv)")},
- {"CFPreferencesGetAppBooleanValue", (PyCFunction)CF_CFPreferencesGetAppBooleanValue, 1,
- PyDoc_STR("(CFStringRef key, CFStringRef applicationID) -> (Boolean _rv, Boolean keyExistsAndHasValidFormat)")},
- {"CFPreferencesGetAppIntegerValue", (PyCFunction)CF_CFPreferencesGetAppIntegerValue, 1,
- PyDoc_STR("(CFStringRef key, CFStringRef applicationID) -> (CFIndex _rv, Boolean keyExistsAndHasValidFormat)")},
- {"CFPreferencesSetAppValue", (PyCFunction)CF_CFPreferencesSetAppValue, 1,
- PyDoc_STR("(CFStringRef key, CFTypeRef value, CFStringRef applicationID) -> None")},
- {"CFPreferencesAddSuitePreferencesToApp", (PyCFunction)CF_CFPreferencesAddSuitePreferencesToApp, 1,
- PyDoc_STR("(CFStringRef applicationID, CFStringRef suiteID) -> None")},
- {"CFPreferencesRemoveSuitePreferencesFromApp", (PyCFunction)CF_CFPreferencesRemoveSuitePreferencesFromApp, 1,
- PyDoc_STR("(CFStringRef applicationID, CFStringRef suiteID) -> None")},
- {"CFPreferencesAppSynchronize", (PyCFunction)CF_CFPreferencesAppSynchronize, 1,
- PyDoc_STR("(CFStringRef applicationID) -> (Boolean _rv)")},
- {"CFPreferencesCopyValue", (PyCFunction)CF_CFPreferencesCopyValue, 1,
- PyDoc_STR("(CFStringRef key, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (CFTypeRef _rv)")},
- {"CFPreferencesCopyMultiple", (PyCFunction)CF_CFPreferencesCopyMultiple, 1,
- PyDoc_STR("(CFArrayRef keysToFetch, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (CFDictionaryRef _rv)")},
- {"CFPreferencesSetValue", (PyCFunction)CF_CFPreferencesSetValue, 1,
- PyDoc_STR("(CFStringRef key, CFTypeRef value, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> None")},
- {"CFPreferencesSetMultiple", (PyCFunction)CF_CFPreferencesSetMultiple, 1,
- PyDoc_STR("(CFDictionaryRef keysToSet, CFArrayRef keysToRemove, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> None")},
- {"CFPreferencesSynchronize", (PyCFunction)CF_CFPreferencesSynchronize, 1,
- PyDoc_STR("(CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (Boolean _rv)")},
- {"CFPreferencesCopyApplicationList", (PyCFunction)CF_CFPreferencesCopyApplicationList, 1,
- PyDoc_STR("(CFStringRef userName, CFStringRef hostName) -> (CFArrayRef _rv)")},
- {"CFPreferencesCopyKeyList", (PyCFunction)CF_CFPreferencesCopyKeyList, 1,
- PyDoc_STR("(CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (CFArrayRef _rv)")},
- {"CFStringGetTypeID", (PyCFunction)CF_CFStringGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFStringCreateWithPascalString", (PyCFunction)CF_CFStringCreateWithPascalString, 1,
- PyDoc_STR("(Str255 pStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringCreateWithCString", (PyCFunction)CF_CFStringCreateWithCString, 1,
- PyDoc_STR("(char* cStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringCreateWithCharacters", (PyCFunction)CF_CFStringCreateWithCharacters, 1,
- PyDoc_STR("(Buffer chars) -> (CFStringRef _rv)")},
- {"CFStringCreateWithPascalStringNoCopy", (PyCFunction)CF_CFStringCreateWithPascalStringNoCopy, 1,
- PyDoc_STR("(Str255 pStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringCreateWithCStringNoCopy", (PyCFunction)CF_CFStringCreateWithCStringNoCopy, 1,
- PyDoc_STR("(char* cStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringCreateWithCharactersNoCopy", (PyCFunction)CF_CFStringCreateWithCharactersNoCopy, 1,
- PyDoc_STR("(Buffer chars) -> (CFStringRef _rv)")},
- {"CFStringCreateMutable", (PyCFunction)CF_CFStringCreateMutable, 1,
- PyDoc_STR("(CFIndex maxLength) -> (CFMutableStringRef _rv)")},
- {"CFStringCreateMutableCopy", (PyCFunction)CF_CFStringCreateMutableCopy, 1,
- PyDoc_STR("(CFIndex maxLength, CFStringRef theString) -> (CFMutableStringRef _rv)")},
- {"CFStringCreateWithBytes", (PyCFunction)CF_CFStringCreateWithBytes, 1,
- PyDoc_STR("(Buffer bytes, CFStringEncoding encoding, Boolean isExternalRepresentation) -> (CFStringRef _rv)")},
- {"CFStringGetSystemEncoding", (PyCFunction)CF_CFStringGetSystemEncoding, 1,
- PyDoc_STR("() -> (CFStringEncoding _rv)")},
- {"CFStringGetMaximumSizeForEncoding", (PyCFunction)CF_CFStringGetMaximumSizeForEncoding, 1,
- PyDoc_STR("(CFIndex length, CFStringEncoding encoding) -> (CFIndex _rv)")},
- {"CFStringIsEncodingAvailable", (PyCFunction)CF_CFStringIsEncodingAvailable, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (Boolean _rv)")},
- {"CFStringGetNameOfEncoding", (PyCFunction)CF_CFStringGetNameOfEncoding, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringConvertEncodingToNSStringEncoding", (PyCFunction)CF_CFStringConvertEncodingToNSStringEncoding, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (UInt32 _rv)")},
- {"CFStringConvertNSStringEncodingToEncoding", (PyCFunction)CF_CFStringConvertNSStringEncodingToEncoding, 1,
- PyDoc_STR("(UInt32 encoding) -> (CFStringEncoding _rv)")},
- {"CFStringConvertEncodingToWindowsCodepage", (PyCFunction)CF_CFStringConvertEncodingToWindowsCodepage, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (UInt32 _rv)")},
- {"CFStringConvertWindowsCodepageToEncoding", (PyCFunction)CF_CFStringConvertWindowsCodepageToEncoding, 1,
- PyDoc_STR("(UInt32 codepage) -> (CFStringEncoding _rv)")},
- {"CFStringConvertEncodingToIANACharSetName", (PyCFunction)CF_CFStringConvertEncodingToIANACharSetName, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (CFStringRef _rv)")},
- {"CFStringGetMostCompatibleMacStringEncoding", (PyCFunction)CF_CFStringGetMostCompatibleMacStringEncoding, 1,
- PyDoc_STR("(CFStringEncoding encoding) -> (CFStringEncoding _rv)")},
- {"__CFStringMakeConstantString", (PyCFunction)CF___CFStringMakeConstantString, 1,
- PyDoc_STR("(char* cStr) -> (CFStringRef _rv)")},
- {"CFURLGetTypeID", (PyCFunction)CF_CFURLGetTypeID, 1,
- PyDoc_STR("() -> (CFTypeID _rv)")},
- {"CFURLCreateWithBytes", (PyCFunction)CF_CFURLCreateWithBytes, 1,
- PyDoc_STR("(Buffer URLBytes, CFStringEncoding encoding, CFURLRef baseURL) -> (CFURLRef _rv)")},
- {"CFURLCreateFromFileSystemRepresentation", (PyCFunction)CF_CFURLCreateFromFileSystemRepresentation, 1,
- PyDoc_STR("(Buffer buffer, Boolean isDirectory) -> (CFURLRef _rv)")},
- {"CFURLCreateFromFileSystemRepresentationRelativeToBase", (PyCFunction)CF_CFURLCreateFromFileSystemRepresentationRelativeToBase, 1,
- PyDoc_STR("(Buffer buffer, Boolean isDirectory, CFURLRef baseURL) -> (CFURLRef _rv)")},
- {"CFURLCreateFromFSRef", (PyCFunction)CF_CFURLCreateFromFSRef, 1,
- PyDoc_STR("(FSRef fsRef) -> (CFURLRef _rv)")},
- {"toCF", (PyCFunction)CF_toCF, 1,
- PyDoc_STR("(python_object) -> (CF_object)")},
- {NULL, NULL, 0}
+ {"__CFRangeMake", (PyCFunction)CF___CFRangeMake, 1,
+ PyDoc_STR("(CFIndex loc, CFIndex len) -> (CFRange _rv)")},
+ {"CFAllocatorGetTypeID", (PyCFunction)CF_CFAllocatorGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFAllocatorGetPreferredSizeForSize", (PyCFunction)CF_CFAllocatorGetPreferredSizeForSize, 1,
+ PyDoc_STR("(CFIndex size, CFOptionFlags hint) -> (CFIndex _rv)")},
+ {"CFCopyTypeIDDescription", (PyCFunction)CF_CFCopyTypeIDDescription, 1,
+ PyDoc_STR("(CFTypeID type_id) -> (CFStringRef _rv)")},
+ {"CFArrayGetTypeID", (PyCFunction)CF_CFArrayGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFArrayCreateMutable", (PyCFunction)CF_CFArrayCreateMutable, 1,
+ PyDoc_STR("(CFIndex capacity) -> (CFMutableArrayRef _rv)")},
+ {"CFArrayCreateMutableCopy", (PyCFunction)CF_CFArrayCreateMutableCopy, 1,
+ PyDoc_STR("(CFIndex capacity, CFArrayRef theArray) -> (CFMutableArrayRef _rv)")},
+ {"CFDataGetTypeID", (PyCFunction)CF_CFDataGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFDataCreate", (PyCFunction)CF_CFDataCreate, 1,
+ PyDoc_STR("(Buffer bytes) -> (CFDataRef _rv)")},
+ {"CFDataCreateWithBytesNoCopy", (PyCFunction)CF_CFDataCreateWithBytesNoCopy, 1,
+ PyDoc_STR("(Buffer bytes) -> (CFDataRef _rv)")},
+ {"CFDataCreateMutable", (PyCFunction)CF_CFDataCreateMutable, 1,
+ PyDoc_STR("(CFIndex capacity) -> (CFMutableDataRef _rv)")},
+ {"CFDataCreateMutableCopy", (PyCFunction)CF_CFDataCreateMutableCopy, 1,
+ PyDoc_STR("(CFIndex capacity, CFDataRef theData) -> (CFMutableDataRef _rv)")},
+ {"CFDictionaryGetTypeID", (PyCFunction)CF_CFDictionaryGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFDictionaryCreateMutable", (PyCFunction)CF_CFDictionaryCreateMutable, 1,
+ PyDoc_STR("(CFIndex capacity) -> (CFMutableDictionaryRef _rv)")},
+ {"CFDictionaryCreateMutableCopy", (PyCFunction)CF_CFDictionaryCreateMutableCopy, 1,
+ PyDoc_STR("(CFIndex capacity, CFDictionaryRef theDict) -> (CFMutableDictionaryRef _rv)")},
+ {"CFPreferencesCopyAppValue", (PyCFunction)CF_CFPreferencesCopyAppValue, 1,
+ PyDoc_STR("(CFStringRef key, CFStringRef applicationID) -> (CFTypeRef _rv)")},
+ {"CFPreferencesGetAppBooleanValue", (PyCFunction)CF_CFPreferencesGetAppBooleanValue, 1,
+ PyDoc_STR("(CFStringRef key, CFStringRef applicationID) -> (Boolean _rv, Boolean keyExistsAndHasValidFormat)")},
+ {"CFPreferencesGetAppIntegerValue", (PyCFunction)CF_CFPreferencesGetAppIntegerValue, 1,
+ PyDoc_STR("(CFStringRef key, CFStringRef applicationID) -> (CFIndex _rv, Boolean keyExistsAndHasValidFormat)")},
+ {"CFPreferencesSetAppValue", (PyCFunction)CF_CFPreferencesSetAppValue, 1,
+ PyDoc_STR("(CFStringRef key, CFTypeRef value, CFStringRef applicationID) -> None")},
+ {"CFPreferencesAddSuitePreferencesToApp", (PyCFunction)CF_CFPreferencesAddSuitePreferencesToApp, 1,
+ PyDoc_STR("(CFStringRef applicationID, CFStringRef suiteID) -> None")},
+ {"CFPreferencesRemoveSuitePreferencesFromApp", (PyCFunction)CF_CFPreferencesRemoveSuitePreferencesFromApp, 1,
+ PyDoc_STR("(CFStringRef applicationID, CFStringRef suiteID) -> None")},
+ {"CFPreferencesAppSynchronize", (PyCFunction)CF_CFPreferencesAppSynchronize, 1,
+ PyDoc_STR("(CFStringRef applicationID) -> (Boolean _rv)")},
+ {"CFPreferencesCopyValue", (PyCFunction)CF_CFPreferencesCopyValue, 1,
+ PyDoc_STR("(CFStringRef key, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (CFTypeRef _rv)")},
+ {"CFPreferencesCopyMultiple", (PyCFunction)CF_CFPreferencesCopyMultiple, 1,
+ PyDoc_STR("(CFArrayRef keysToFetch, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (CFDictionaryRef _rv)")},
+ {"CFPreferencesSetValue", (PyCFunction)CF_CFPreferencesSetValue, 1,
+ PyDoc_STR("(CFStringRef key, CFTypeRef value, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> None")},
+ {"CFPreferencesSetMultiple", (PyCFunction)CF_CFPreferencesSetMultiple, 1,
+ PyDoc_STR("(CFDictionaryRef keysToSet, CFArrayRef keysToRemove, CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> None")},
+ {"CFPreferencesSynchronize", (PyCFunction)CF_CFPreferencesSynchronize, 1,
+ PyDoc_STR("(CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (Boolean _rv)")},
+ {"CFPreferencesCopyApplicationList", (PyCFunction)CF_CFPreferencesCopyApplicationList, 1,
+ PyDoc_STR("(CFStringRef userName, CFStringRef hostName) -> (CFArrayRef _rv)")},
+ {"CFPreferencesCopyKeyList", (PyCFunction)CF_CFPreferencesCopyKeyList, 1,
+ PyDoc_STR("(CFStringRef applicationID, CFStringRef userName, CFStringRef hostName) -> (CFArrayRef _rv)")},
+ {"CFStringGetTypeID", (PyCFunction)CF_CFStringGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFStringCreateWithPascalString", (PyCFunction)CF_CFStringCreateWithPascalString, 1,
+ PyDoc_STR("(Str255 pStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringCreateWithCString", (PyCFunction)CF_CFStringCreateWithCString, 1,
+ PyDoc_STR("(char* cStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringCreateWithCharacters", (PyCFunction)CF_CFStringCreateWithCharacters, 1,
+ PyDoc_STR("(Buffer chars) -> (CFStringRef _rv)")},
+ {"CFStringCreateWithPascalStringNoCopy", (PyCFunction)CF_CFStringCreateWithPascalStringNoCopy, 1,
+ PyDoc_STR("(Str255 pStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringCreateWithCStringNoCopy", (PyCFunction)CF_CFStringCreateWithCStringNoCopy, 1,
+ PyDoc_STR("(char* cStr, CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringCreateWithCharactersNoCopy", (PyCFunction)CF_CFStringCreateWithCharactersNoCopy, 1,
+ PyDoc_STR("(Buffer chars) -> (CFStringRef _rv)")},
+ {"CFStringCreateMutable", (PyCFunction)CF_CFStringCreateMutable, 1,
+ PyDoc_STR("(CFIndex maxLength) -> (CFMutableStringRef _rv)")},
+ {"CFStringCreateMutableCopy", (PyCFunction)CF_CFStringCreateMutableCopy, 1,
+ PyDoc_STR("(CFIndex maxLength, CFStringRef theString) -> (CFMutableStringRef _rv)")},
+ {"CFStringCreateWithBytes", (PyCFunction)CF_CFStringCreateWithBytes, 1,
+ PyDoc_STR("(Buffer bytes, CFStringEncoding encoding, Boolean isExternalRepresentation) -> (CFStringRef _rv)")},
+ {"CFStringGetSystemEncoding", (PyCFunction)CF_CFStringGetSystemEncoding, 1,
+ PyDoc_STR("() -> (CFStringEncoding _rv)")},
+ {"CFStringGetMaximumSizeForEncoding", (PyCFunction)CF_CFStringGetMaximumSizeForEncoding, 1,
+ PyDoc_STR("(CFIndex length, CFStringEncoding encoding) -> (CFIndex _rv)")},
+ {"CFStringIsEncodingAvailable", (PyCFunction)CF_CFStringIsEncodingAvailable, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (Boolean _rv)")},
+ {"CFStringGetNameOfEncoding", (PyCFunction)CF_CFStringGetNameOfEncoding, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringConvertEncodingToNSStringEncoding", (PyCFunction)CF_CFStringConvertEncodingToNSStringEncoding, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (UInt32 _rv)")},
+ {"CFStringConvertNSStringEncodingToEncoding", (PyCFunction)CF_CFStringConvertNSStringEncodingToEncoding, 1,
+ PyDoc_STR("(UInt32 encoding) -> (CFStringEncoding _rv)")},
+ {"CFStringConvertEncodingToWindowsCodepage", (PyCFunction)CF_CFStringConvertEncodingToWindowsCodepage, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (UInt32 _rv)")},
+ {"CFStringConvertWindowsCodepageToEncoding", (PyCFunction)CF_CFStringConvertWindowsCodepageToEncoding, 1,
+ PyDoc_STR("(UInt32 codepage) -> (CFStringEncoding _rv)")},
+ {"CFStringConvertEncodingToIANACharSetName", (PyCFunction)CF_CFStringConvertEncodingToIANACharSetName, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (CFStringRef _rv)")},
+ {"CFStringGetMostCompatibleMacStringEncoding", (PyCFunction)CF_CFStringGetMostCompatibleMacStringEncoding, 1,
+ PyDoc_STR("(CFStringEncoding encoding) -> (CFStringEncoding _rv)")},
+ {"__CFStringMakeConstantString", (PyCFunction)CF___CFStringMakeConstantString, 1,
+ PyDoc_STR("(char* cStr) -> (CFStringRef _rv)")},
+ {"CFURLGetTypeID", (PyCFunction)CF_CFURLGetTypeID, 1,
+ PyDoc_STR("() -> (CFTypeID _rv)")},
+ {"CFURLCreateWithBytes", (PyCFunction)CF_CFURLCreateWithBytes, 1,
+ PyDoc_STR("(Buffer URLBytes, CFStringEncoding encoding, CFURLRef baseURL) -> (CFURLRef _rv)")},
+ {"CFURLCreateFromFileSystemRepresentation", (PyCFunction)CF_CFURLCreateFromFileSystemRepresentation, 1,
+ PyDoc_STR("(Buffer buffer, Boolean isDirectory) -> (CFURLRef _rv)")},
+ {"CFURLCreateFromFileSystemRepresentationRelativeToBase", (PyCFunction)CF_CFURLCreateFromFileSystemRepresentationRelativeToBase, 1,
+ PyDoc_STR("(Buffer buffer, Boolean isDirectory, CFURLRef baseURL) -> (CFURLRef _rv)")},
+ {"CFURLCreateFromFSRef", (PyCFunction)CF_CFURLCreateFromFSRef, 1,
+ PyDoc_STR("(FSRef fsRef) -> (CFURLRef _rv)")},
+ {"toCF", (PyCFunction)CF_toCF, 1,
+ PyDoc_STR("(python_object) -> (CF_object)")},
+ {NULL, NULL, 0}
};
@@ -4828,165 +4828,165 @@ static PyMethodDef CF_methods[] = {
/* Routines to convert any CF type to/from the corresponding CFxxxObj */
PyObject *CFObj_New(CFTypeRef itself)
{
- if (itself == NULL)
- {
- PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
- return NULL;
- }
- if (CFGetTypeID(itself) == CFArrayGetTypeID()) return CFArrayRefObj_New((CFArrayRef)itself);
- if (CFGetTypeID(itself) == CFDictionaryGetTypeID()) return CFDictionaryRefObj_New((CFDictionaryRef)itself);
- if (CFGetTypeID(itself) == CFDataGetTypeID()) return CFDataRefObj_New((CFDataRef)itself);
- if (CFGetTypeID(itself) == CFStringGetTypeID()) return CFStringRefObj_New((CFStringRef)itself);
- if (CFGetTypeID(itself) == CFURLGetTypeID()) return CFURLRefObj_New((CFURLRef)itself);
- /* XXXX Or should we use PyCF_CF2Python here?? */
- return CFTypeRefObj_New(itself);
+ if (itself == NULL)
+ {
+ PyErr_SetString(PyExc_RuntimeError, "cannot wrap NULL");
+ return NULL;
+ }
+ if (CFGetTypeID(itself) == CFArrayGetTypeID()) return CFArrayRefObj_New((CFArrayRef)itself);
+ if (CFGetTypeID(itself) == CFDictionaryGetTypeID()) return CFDictionaryRefObj_New((CFDictionaryRef)itself);
+ if (CFGetTypeID(itself) == CFDataGetTypeID()) return CFDataRefObj_New((CFDataRef)itself);
+ if (CFGetTypeID(itself) == CFStringGetTypeID()) return CFStringRefObj_New((CFStringRef)itself);
+ if (CFGetTypeID(itself) == CFURLGetTypeID()) return CFURLRefObj_New((CFURLRef)itself);
+ /* XXXX Or should we use PyCF_CF2Python here?? */
+ return CFTypeRefObj_New(itself);
}
int CFObj_Convert(PyObject *v, CFTypeRef *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- /* Check for other CF objects here */
-
- if (!CFTypeRefObj_Check(v) &&
- !CFArrayRefObj_Check(v) &&
- !CFMutableArrayRefObj_Check(v) &&
- !CFDictionaryRefObj_Check(v) &&
- !CFMutableDictionaryRefObj_Check(v) &&
- !CFDataRefObj_Check(v) &&
- !CFMutableDataRefObj_Check(v) &&
- !CFStringRefObj_Check(v) &&
- !CFMutableStringRefObj_Check(v) &&
- !CFURLRefObj_Check(v) )
- {
- /* XXXX Or should we use PyCF_Python2CF here?? */
- PyErr_SetString(PyExc_TypeError, "CF object required");
- return 0;
- }
- *p_itself = ((CFTypeRefObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ /* Check for other CF objects here */
+
+ if (!CFTypeRefObj_Check(v) &&
+ !CFArrayRefObj_Check(v) &&
+ !CFMutableArrayRefObj_Check(v) &&
+ !CFDictionaryRefObj_Check(v) &&
+ !CFMutableDictionaryRefObj_Check(v) &&
+ !CFDataRefObj_Check(v) &&
+ !CFMutableDataRefObj_Check(v) &&
+ !CFStringRefObj_Check(v) &&
+ !CFMutableStringRefObj_Check(v) &&
+ !CFURLRefObj_Check(v) )
+ {
+ /* XXXX Or should we use PyCF_Python2CF here?? */
+ PyErr_SetString(PyExc_TypeError, "CF object required");
+ return 0;
+ }
+ *p_itself = ((CFTypeRefObject *)v)->ob_itself;
+ return 1;
}
void init_CF(void)
{
- PyObject *m;
- PyObject *d;
-
-
-
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFTypeRef, CFObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFTypeRef, CFObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFTypeRef, CFTypeRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFTypeRef, CFTypeRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFStringRef, CFStringRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFStringRef, CFStringRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFMutableStringRef, CFMutableStringRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFMutableStringRef, CFMutableStringRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFArrayRef, CFArrayRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFArrayRef, CFArrayRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFMutableArrayRef, CFMutableArrayRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFMutableArrayRef, CFMutableArrayRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFDictionaryRef, CFDictionaryRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFDictionaryRef, CFDictionaryRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFMutableDictionaryRef, CFMutableDictionaryRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFMutableDictionaryRef, CFMutableDictionaryRefObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(CFURLRef, CFURLRefObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFURLRef, CFURLRefObj_Convert);
-
-
- m = Py_InitModule("_CF", CF_methods);
- d = PyModule_GetDict(m);
- CF_Error = PyMac_GetOSErrException();
- if (CF_Error == NULL ||
- PyDict_SetItemString(d, "Error", CF_Error) != 0)
- return;
- CFTypeRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&CFTypeRef_Type) < 0) return;
- Py_INCREF(&CFTypeRef_Type);
- PyModule_AddObject(m, "CFTypeRef", (PyObject *)&CFTypeRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFTypeRef_Type);
- PyModule_AddObject(m, "CFTypeRefType", (PyObject *)&CFTypeRef_Type);
- CFArrayRef_Type.ob_type = &PyType_Type;
- CFArrayRef_Type.tp_base = &CFTypeRef_Type;
- if (PyType_Ready(&CFArrayRef_Type) < 0) return;
- Py_INCREF(&CFArrayRef_Type);
- PyModule_AddObject(m, "CFArrayRef", (PyObject *)&CFArrayRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFArrayRef_Type);
- PyModule_AddObject(m, "CFArrayRefType", (PyObject *)&CFArrayRef_Type);
- CFMutableArrayRef_Type.ob_type = &PyType_Type;
- CFMutableArrayRef_Type.tp_base = &CFArrayRef_Type;
- if (PyType_Ready(&CFMutableArrayRef_Type) < 0) return;
- Py_INCREF(&CFMutableArrayRef_Type);
- PyModule_AddObject(m, "CFMutableArrayRef", (PyObject *)&CFMutableArrayRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFMutableArrayRef_Type);
- PyModule_AddObject(m, "CFMutableArrayRefType", (PyObject *)&CFMutableArrayRef_Type);
- CFDictionaryRef_Type.ob_type = &PyType_Type;
- CFDictionaryRef_Type.tp_base = &CFTypeRef_Type;
- if (PyType_Ready(&CFDictionaryRef_Type) < 0) return;
- Py_INCREF(&CFDictionaryRef_Type);
- PyModule_AddObject(m, "CFDictionaryRef", (PyObject *)&CFDictionaryRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFDictionaryRef_Type);
- PyModule_AddObject(m, "CFDictionaryRefType", (PyObject *)&CFDictionaryRef_Type);
- CFMutableDictionaryRef_Type.ob_type = &PyType_Type;
- CFMutableDictionaryRef_Type.tp_base = &CFDictionaryRef_Type;
- if (PyType_Ready(&CFMutableDictionaryRef_Type) < 0) return;
- Py_INCREF(&CFMutableDictionaryRef_Type);
- PyModule_AddObject(m, "CFMutableDictionaryRef", (PyObject *)&CFMutableDictionaryRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFMutableDictionaryRef_Type);
- PyModule_AddObject(m, "CFMutableDictionaryRefType", (PyObject *)&CFMutableDictionaryRef_Type);
- CFDataRef_Type.ob_type = &PyType_Type;
- CFDataRef_Type.tp_base = &CFTypeRef_Type;
- if (PyType_Ready(&CFDataRef_Type) < 0) return;
- Py_INCREF(&CFDataRef_Type);
- PyModule_AddObject(m, "CFDataRef", (PyObject *)&CFDataRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFDataRef_Type);
- PyModule_AddObject(m, "CFDataRefType", (PyObject *)&CFDataRef_Type);
- CFMutableDataRef_Type.ob_type = &PyType_Type;
- CFMutableDataRef_Type.tp_base = &CFDataRef_Type;
- if (PyType_Ready(&CFMutableDataRef_Type) < 0) return;
- Py_INCREF(&CFMutableDataRef_Type);
- PyModule_AddObject(m, "CFMutableDataRef", (PyObject *)&CFMutableDataRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFMutableDataRef_Type);
- PyModule_AddObject(m, "CFMutableDataRefType", (PyObject *)&CFMutableDataRef_Type);
- CFStringRef_Type.ob_type = &PyType_Type;
- CFStringRef_Type.tp_base = &CFTypeRef_Type;
- if (PyType_Ready(&CFStringRef_Type) < 0) return;
- Py_INCREF(&CFStringRef_Type);
- PyModule_AddObject(m, "CFStringRef", (PyObject *)&CFStringRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFStringRef_Type);
- PyModule_AddObject(m, "CFStringRefType", (PyObject *)&CFStringRef_Type);
- CFMutableStringRef_Type.ob_type = &PyType_Type;
- CFMutableStringRef_Type.tp_base = &CFStringRef_Type;
- if (PyType_Ready(&CFMutableStringRef_Type) < 0) return;
- Py_INCREF(&CFMutableStringRef_Type);
- PyModule_AddObject(m, "CFMutableStringRef", (PyObject *)&CFMutableStringRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFMutableStringRef_Type);
- PyModule_AddObject(m, "CFMutableStringRefType", (PyObject *)&CFMutableStringRef_Type);
- CFURLRef_Type.ob_type = &PyType_Type;
- CFURLRef_Type.tp_base = &CFTypeRef_Type;
- if (PyType_Ready(&CFURLRef_Type) < 0) return;
- Py_INCREF(&CFURLRef_Type);
- PyModule_AddObject(m, "CFURLRef", (PyObject *)&CFURLRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CFURLRef_Type);
- PyModule_AddObject(m, "CFURLRefType", (PyObject *)&CFURLRef_Type);
+ PyObject *m;
+ PyObject *d;
+
+
+
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFTypeRef, CFObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFTypeRef, CFObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFTypeRef, CFTypeRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFTypeRef, CFTypeRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFStringRef, CFStringRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFStringRef, CFStringRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFMutableStringRef, CFMutableStringRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFMutableStringRef, CFMutableStringRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFArrayRef, CFArrayRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFArrayRef, CFArrayRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFMutableArrayRef, CFMutableArrayRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFMutableArrayRef, CFMutableArrayRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFDictionaryRef, CFDictionaryRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFDictionaryRef, CFDictionaryRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFMutableDictionaryRef, CFMutableDictionaryRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFMutableDictionaryRef, CFMutableDictionaryRefObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(CFURLRef, CFURLRefObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(CFURLRef, CFURLRefObj_Convert);
+
+
+ m = Py_InitModule("_CF", CF_methods);
+ d = PyModule_GetDict(m);
+ CF_Error = PyMac_GetOSErrException();
+ if (CF_Error == NULL ||
+ PyDict_SetItemString(d, "Error", CF_Error) != 0)
+ return;
+ CFTypeRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&CFTypeRef_Type) < 0) return;
+ Py_INCREF(&CFTypeRef_Type);
+ PyModule_AddObject(m, "CFTypeRef", (PyObject *)&CFTypeRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFTypeRef_Type);
+ PyModule_AddObject(m, "CFTypeRefType", (PyObject *)&CFTypeRef_Type);
+ CFArrayRef_Type.ob_type = &PyType_Type;
+ CFArrayRef_Type.tp_base = &CFTypeRef_Type;
+ if (PyType_Ready(&CFArrayRef_Type) < 0) return;
+ Py_INCREF(&CFArrayRef_Type);
+ PyModule_AddObject(m, "CFArrayRef", (PyObject *)&CFArrayRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFArrayRef_Type);
+ PyModule_AddObject(m, "CFArrayRefType", (PyObject *)&CFArrayRef_Type);
+ CFMutableArrayRef_Type.ob_type = &PyType_Type;
+ CFMutableArrayRef_Type.tp_base = &CFArrayRef_Type;
+ if (PyType_Ready(&CFMutableArrayRef_Type) < 0) return;
+ Py_INCREF(&CFMutableArrayRef_Type);
+ PyModule_AddObject(m, "CFMutableArrayRef", (PyObject *)&CFMutableArrayRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFMutableArrayRef_Type);
+ PyModule_AddObject(m, "CFMutableArrayRefType", (PyObject *)&CFMutableArrayRef_Type);
+ CFDictionaryRef_Type.ob_type = &PyType_Type;
+ CFDictionaryRef_Type.tp_base = &CFTypeRef_Type;
+ if (PyType_Ready(&CFDictionaryRef_Type) < 0) return;
+ Py_INCREF(&CFDictionaryRef_Type);
+ PyModule_AddObject(m, "CFDictionaryRef", (PyObject *)&CFDictionaryRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFDictionaryRef_Type);
+ PyModule_AddObject(m, "CFDictionaryRefType", (PyObject *)&CFDictionaryRef_Type);
+ CFMutableDictionaryRef_Type.ob_type = &PyType_Type;
+ CFMutableDictionaryRef_Type.tp_base = &CFDictionaryRef_Type;
+ if (PyType_Ready(&CFMutableDictionaryRef_Type) < 0) return;
+ Py_INCREF(&CFMutableDictionaryRef_Type);
+ PyModule_AddObject(m, "CFMutableDictionaryRef", (PyObject *)&CFMutableDictionaryRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFMutableDictionaryRef_Type);
+ PyModule_AddObject(m, "CFMutableDictionaryRefType", (PyObject *)&CFMutableDictionaryRef_Type);
+ CFDataRef_Type.ob_type = &PyType_Type;
+ CFDataRef_Type.tp_base = &CFTypeRef_Type;
+ if (PyType_Ready(&CFDataRef_Type) < 0) return;
+ Py_INCREF(&CFDataRef_Type);
+ PyModule_AddObject(m, "CFDataRef", (PyObject *)&CFDataRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFDataRef_Type);
+ PyModule_AddObject(m, "CFDataRefType", (PyObject *)&CFDataRef_Type);
+ CFMutableDataRef_Type.ob_type = &PyType_Type;
+ CFMutableDataRef_Type.tp_base = &CFDataRef_Type;
+ if (PyType_Ready(&CFMutableDataRef_Type) < 0) return;
+ Py_INCREF(&CFMutableDataRef_Type);
+ PyModule_AddObject(m, "CFMutableDataRef", (PyObject *)&CFMutableDataRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFMutableDataRef_Type);
+ PyModule_AddObject(m, "CFMutableDataRefType", (PyObject *)&CFMutableDataRef_Type);
+ CFStringRef_Type.ob_type = &PyType_Type;
+ CFStringRef_Type.tp_base = &CFTypeRef_Type;
+ if (PyType_Ready(&CFStringRef_Type) < 0) return;
+ Py_INCREF(&CFStringRef_Type);
+ PyModule_AddObject(m, "CFStringRef", (PyObject *)&CFStringRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFStringRef_Type);
+ PyModule_AddObject(m, "CFStringRefType", (PyObject *)&CFStringRef_Type);
+ CFMutableStringRef_Type.ob_type = &PyType_Type;
+ CFMutableStringRef_Type.tp_base = &CFStringRef_Type;
+ if (PyType_Ready(&CFMutableStringRef_Type) < 0) return;
+ Py_INCREF(&CFMutableStringRef_Type);
+ PyModule_AddObject(m, "CFMutableStringRef", (PyObject *)&CFMutableStringRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFMutableStringRef_Type);
+ PyModule_AddObject(m, "CFMutableStringRefType", (PyObject *)&CFMutableStringRef_Type);
+ CFURLRef_Type.ob_type = &PyType_Type;
+ CFURLRef_Type.tp_base = &CFTypeRef_Type;
+ if (PyType_Ready(&CFURLRef_Type) < 0) return;
+ Py_INCREF(&CFURLRef_Type);
+ PyModule_AddObject(m, "CFURLRef", (PyObject *)&CFURLRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CFURLRef_Type);
+ PyModule_AddObject(m, "CFURLRefType", (PyObject *)&CFURLRef_Type);
#define _STRINGCONST(name) PyModule_AddObject(m, #name, CFStringRefObj_New(name))
- _STRINGCONST(kCFPreferencesAnyApplication);
- _STRINGCONST(kCFPreferencesCurrentApplication);
- _STRINGCONST(kCFPreferencesAnyHost);
- _STRINGCONST(kCFPreferencesCurrentHost);
- _STRINGCONST(kCFPreferencesAnyUser);
- _STRINGCONST(kCFPreferencesCurrentUser);
+ _STRINGCONST(kCFPreferencesAnyApplication);
+ _STRINGCONST(kCFPreferencesCurrentApplication);
+ _STRINGCONST(kCFPreferencesAnyHost);
+ _STRINGCONST(kCFPreferencesCurrentHost);
+ _STRINGCONST(kCFPreferencesAnyUser);
+ _STRINGCONST(kCFPreferencesCurrentUser);
diff --git a/Mac/Modules/cf/pycfbridge.c b/Mac/Modules/cf/pycfbridge.c
index 06700b3..708c1e6 100644
--- a/Mac/Modules/cf/pycfbridge.c
+++ b/Mac/Modules/cf/pycfbridge.c
@@ -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;
+
+ 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;
+ 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;
}
diff --git a/Mac/Modules/cg/CFMLateImport.c b/Mac/Modules/cg/CFMLateImport.c
index bc2976e..955acfb 100755
--- a/Mac/Modules/cg/CFMLateImport.c
+++ b/Mac/Modules/cg/CFMLateImport.c
@@ -1,45 +1,45 @@
/*
- File: CFMLateImport.c
-
- Contains: Implementation of CFM late import library.
-
- Written by: Quinn
-
- 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.
-
- Change History (most recent first):
-
- <13> 24/9/01 Quinn Fixes to compile with C++ activated.
- <12> 21/9/01 Quinn [2710489] Fix typo in the comments for FragmentLookup.
- <11> 21/9/01 Quinn Changes for CWPro7 Mach-O build.
- <10> 19/9/01 Quinn Corrected implementation of kPEFRelocSmBySection. Added
- implementations of kPEFRelocSetPosition and kPEFRelocLgByImport
- (from code contributed by Eric Grant, Ned Holbrook, and Steve
- Kalkwarf), although I can't test them yet.
- <9> 19/9/01 Quinn We now handle unpacked data sections, courtesy of some code from
- Ned Holbrook.
- <8> 19/9/01 Quinn Minor fixes for the previous checkin. Updated some comments and
- killed some dead code.
- <7> 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.
- <6> 15/2/01 Quinn Modify compile-time warnings to complain if you try to build
- this module into a Mach-O binary.
- <5> 5/2/01 Quinn Removed redundant assignment in CFMLateImportCore.
- <4> 30/11/00 Quinn Added comment about future of data symbols in CF.
- <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.
+ File: CFMLateImport.c
+
+ Contains: Implementation of CFM late import library.
+
+ Written by: Quinn
+
+ 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.
+
+ Change History (most recent first):
+
+ <13> 24/9/01 Quinn Fixes to compile with C++ activated.
+ <12> 21/9/01 Quinn [2710489] Fix typo in the comments for FragmentLookup.
+ <11> 21/9/01 Quinn Changes for CWPro7 Mach-O build.
+ <10> 19/9/01 Quinn Corrected implementation of kPEFRelocSmBySection. Added
+ implementations of kPEFRelocSetPosition and kPEFRelocLgByImport
+ (from code contributed by Eric Grant, Ned Holbrook, and Steve
+ Kalkwarf), although I can't test them yet.
+ <9> 19/9/01 Quinn We now handle unpacked data sections, courtesy of some code from
+ Ned Holbrook.
+ <8> 19/9/01 Quinn Minor fixes for the previous checkin. Updated some comments and
+ killed some dead code.
+ <7> 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.
+ <6> 15/2/01 Quinn Modify compile-time warnings to complain if you try to build
+ this module into a Mach-O binary.
+ <5> 5/2/01 Quinn Removed redundant assignment in CFMLateImportCore.
+ <4> 30/11/00 Quinn Added comment about future of data symbols in CF.
+ <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.
*/
// To Do List:
@@ -66,8 +66,8 @@
// Mac OS Interfaces
#if ! MORE_FRAMEWORK_INCLUDES
- #include <CodeFragments.h>
- #include <PEFBinaryFormat.h>
+ #include <CodeFragments.h>
+ #include <PEFBinaryFormat.h>
#endif
// Standard C Interfaces
@@ -86,32 +86,32 @@
/////////////////////////////////////////////////////////////////
#if TARGET_RT_MAC_MACHO
- #error CFMLateImport is not suitable for use in a Mach-O project.
+ #error CFMLateImport is not suitable for use in a Mach-O project.
#elif !TARGET_RT_MAC_CFM || !TARGET_CPU_PPC
- #error CFMLateImport has not been qualified for 68K or CFM-68K use.
+ #error CFMLateImport has not been qualified for 68K or CFM-68K use.
#endif
/////////////////////////////////////////////////////////////////
#pragma mark ----- Utility Routines -----
static OSStatus FSReadAtOffset(SInt16 refNum, SInt32 offset, SInt32 count, void *buffer)
- // A convenient wrapper around PBRead which has two advantages
- // over FSRead. First, it takes count as a value parameter.
- // Second, it reads from an arbitrary offset into the file,
- // which avoids a bunch of SetFPos calls.
- //
- // I guess this should go into "MoreFiles.h", but I'm not sure
- // how we're going to integrate such a concept into MIB yet.
+ // A convenient wrapper around PBRead which has two advantages
+ // over FSRead. First, it takes count as a value parameter.
+ // Second, it reads from an arbitrary offset into the file,
+ // which avoids a bunch of SetFPos calls.
+ //
+ // I guess this should go into "MoreFiles.h", but I'm not sure
+ // how we're going to integrate such a concept into MIB yet.
{
- ParamBlockRec pb;
-
- pb.ioParam.ioRefNum = refNum;
- pb.ioParam.ioBuffer = (Ptr) buffer;
- pb.ioParam.ioReqCount = count;
- pb.ioParam.ioPosMode = fsFromStart;
- pb.ioParam.ioPosOffset = offset;
-
- return PBReadSync(&pb);
+ ParamBlockRec pb;
+
+ pb.ioParam.ioRefNum = refNum;
+ pb.ioParam.ioBuffer = (Ptr) buffer;
+ pb.ioParam.ioReqCount = count;
+ pb.ioParam.ioPosMode = fsFromStart;
+ pb.ioParam.ioPosOffset = offset;
+
+ return PBReadSync(&pb);
}
/////////////////////////////////////////////////////////////////
@@ -124,16 +124,16 @@ static OSStatus FSReadAtOffset(SInt16 refNum, SInt32 offset, SInt32 count, void
// we fill out more fields.
struct FragToFixInfo {
- CFragSystem7DiskFlatLocator locator; // How to find the fragment's container.
- CFragConnectionID connID; // CFM connection to the fragment.
- CFragInitFunction initRoutine; // The CFM init routine for the fragment.
- PEFContainerHeader containerHeader; // The CFM header, read in from the container.
- PEFSectionHeader *sectionHeaders; // The CFM section headers. A pointer block containing an array of containerHeader.sectionCount elements.
- PEFLoaderInfoHeader *loaderSection; // The entire CFM loader section in a pointer block.
- SInt16 fileRef; // A read-only path to the CFM container. We keep this here because one that one routine needs to read from the container.
- void *section0Base; // The base address of section 0, which we go through hoops to calculate.
- void *section1Base; // The base address of section 1, which we go through hoops to calculate.
- Boolean disposeSectionPointers; // See below.
+ CFragSystem7DiskFlatLocator locator; // How to find the fragment's container.
+ CFragConnectionID connID; // CFM connection to the fragment.
+ CFragInitFunction initRoutine; // The CFM init routine for the fragment.
+ PEFContainerHeader containerHeader; // The CFM header, read in from the container.
+ PEFSectionHeader *sectionHeaders; // The CFM section headers. A pointer block containing an array of containerHeader.sectionCount elements.
+ PEFLoaderInfoHeader *loaderSection; // The entire CFM loader section in a pointer block.
+ SInt16 fileRef; // A read-only path to the CFM container. We keep this here because one that one routine needs to read from the container.
+ void *section0Base; // The base address of section 0, which we go through hoops to calculate.
+ void *section1Base; // The base address of section 1, which we go through hoops to calculate.
+ Boolean disposeSectionPointers; // See below.
};
typedef struct FragToFixInfo FragToFixInfo;
@@ -151,614 +151,614 @@ typedef struct FragToFixInfo FragToFixInfo;
// disposeSectionPointers remains as vestigial support for the concept.
static OSStatus ReadContainerBasics(FragToFixInfo *fragToFix)
- // Reads some basic information from the container of the
- // fragment to fix and stores it in various fields of
- // fragToFix. This includes:
- //
- // o containerHeader -- The contain header itself.
- // o sectionHeaders -- The array of section headers (in a newly allocated pointer block).
- // o loaderSection -- The entire loader section (in a newly allocated pointer block).
- //
- // Also sets disposeSectionPointers to indicate whether
- // the last two pointers should be disposed of.
- //
- // Finally, it leaves the container file open for later
- // folks who want to read data from it.
+ // Reads some basic information from the container of the
+ // fragment to fix and stores it in various fields of
+ // fragToFix. This includes:
+ //
+ // o containerHeader -- The contain header itself.
+ // o sectionHeaders -- The array of section headers (in a newly allocated pointer block).
+ // o loaderSection -- The entire loader section (in a newly allocated pointer block).
+ //
+ // Also sets disposeSectionPointers to indicate whether
+ // the last two pointers should be disposed of.
+ //
+ // Finally, it leaves the container file open for later
+ // folks who want to read data from it.
{
- OSStatus err;
- UInt16 sectionIndex;
- Boolean found;
-
- MoreAssertQ(fragToFix != nil);
- MoreAssertQ(fragToFix->locator.fileSpec != nil);
- MoreAssertQ(fragToFix->connID != nil);
- MoreAssertQ(fragToFix->loaderSection == nil);
- MoreAssertQ(fragToFix->sectionHeaders == nil);
- MoreAssertQ(fragToFix->fileRef == 0);
-
- fragToFix->disposeSectionPointers = true;
-
- // Open up the file, read the container head, then read in
- // all the section headers, then go looking through the
- // section headers for the loader section (PEF defines
- // that there can be only one).
-
- err = FSpOpenDF(fragToFix->locator.fileSpec, fsRdPerm, &fragToFix->fileRef);
- if (err == noErr) {
- err = FSReadAtOffset(fragToFix->fileRef,
- fragToFix->locator.offset,
- sizeof(fragToFix->containerHeader),
- &fragToFix->containerHeader);
- if (err == noErr) {
- if ( fragToFix->containerHeader.tag1 != kPEFTag1
- || fragToFix->containerHeader.tag2 != kPEFTag2
- || fragToFix->containerHeader.architecture != kCompiledCFragArch
- || fragToFix->containerHeader.formatVersion != kPEFVersion) {
- err = cfragFragmentFormatErr;
- }
- }
- if (err == noErr) {
- fragToFix->sectionHeaders = (PEFSectionHeader *) NewPtr(fragToFix->containerHeader.sectionCount * sizeof(PEFSectionHeader));
- err = MemError();
- }
- if (err == noErr) {
- err = FSReadAtOffset(fragToFix->fileRef,
- fragToFix->locator.offset + sizeof(fragToFix->containerHeader),
- fragToFix->containerHeader.sectionCount * sizeof(PEFSectionHeader),
- fragToFix->sectionHeaders);
- }
- if (err == noErr) {
- sectionIndex = 0;
- found = false;
- while ( sectionIndex < fragToFix->containerHeader.sectionCount && ! found ) {
- found = (fragToFix->sectionHeaders[sectionIndex].sectionKind == kPEFLoaderSection);
- if ( ! found ) {
- sectionIndex += 1;
- }
- }
- }
- if (err == noErr && ! found) {
- err = cfragNoSectionErr;
- }
-
- // Now read allocate a pointer block and read the loader section into it.
-
- if (err == noErr) {
- fragToFix->loaderSection = (PEFLoaderInfoHeader *) NewPtr(fragToFix->sectionHeaders[sectionIndex].containerLength);
- err = MemError();
- }
- if (err == noErr) {
- err = FSReadAtOffset(fragToFix->fileRef,
- fragToFix->locator.offset + fragToFix->sectionHeaders[sectionIndex].containerOffset,
- fragToFix->sectionHeaders[sectionIndex].containerLength,
- fragToFix->loaderSection);
- }
- }
-
- // No clean up. The client must init fragToFix to zeros and then
- // clean up regardless of whether we return an error.
-
- return err;
+ OSStatus err;
+ UInt16 sectionIndex;
+ Boolean found;
+
+ MoreAssertQ(fragToFix != nil);
+ MoreAssertQ(fragToFix->locator.fileSpec != nil);
+ MoreAssertQ(fragToFix->connID != nil);
+ MoreAssertQ(fragToFix->loaderSection == nil);
+ MoreAssertQ(fragToFix->sectionHeaders == nil);
+ MoreAssertQ(fragToFix->fileRef == 0);
+
+ fragToFix->disposeSectionPointers = true;
+
+ // Open up the file, read the container head, then read in
+ // all the section headers, then go looking through the
+ // section headers for the loader section (PEF defines
+ // that there can be only one).
+
+ err = FSpOpenDF(fragToFix->locator.fileSpec, fsRdPerm, &fragToFix->fileRef);
+ if (err == noErr) {
+ err = FSReadAtOffset(fragToFix->fileRef,
+ fragToFix->locator.offset,
+ sizeof(fragToFix->containerHeader),
+ &fragToFix->containerHeader);
+ if (err == noErr) {
+ if ( fragToFix->containerHeader.tag1 != kPEFTag1
+ || fragToFix->containerHeader.tag2 != kPEFTag2
+ || fragToFix->containerHeader.architecture != kCompiledCFragArch
+ || fragToFix->containerHeader.formatVersion != kPEFVersion) {
+ err = cfragFragmentFormatErr;
+ }
+ }
+ if (err == noErr) {
+ fragToFix->sectionHeaders = (PEFSectionHeader *) NewPtr(fragToFix->containerHeader.sectionCount * sizeof(PEFSectionHeader));
+ err = MemError();
+ }
+ if (err == noErr) {
+ err = FSReadAtOffset(fragToFix->fileRef,
+ fragToFix->locator.offset + sizeof(fragToFix->containerHeader),
+ fragToFix->containerHeader.sectionCount * sizeof(PEFSectionHeader),
+ fragToFix->sectionHeaders);
+ }
+ if (err == noErr) {
+ sectionIndex = 0;
+ found = false;
+ while ( sectionIndex < fragToFix->containerHeader.sectionCount && ! found ) {
+ found = (fragToFix->sectionHeaders[sectionIndex].sectionKind == kPEFLoaderSection);
+ if ( ! found ) {
+ sectionIndex += 1;
+ }
+ }
+ }
+ if (err == noErr && ! found) {
+ err = cfragNoSectionErr;
+ }
+
+ // Now read allocate a pointer block and read the loader section into it.
+
+ if (err == noErr) {
+ fragToFix->loaderSection = (PEFLoaderInfoHeader *) NewPtr(fragToFix->sectionHeaders[sectionIndex].containerLength);
+ err = MemError();
+ }
+ if (err == noErr) {
+ err = FSReadAtOffset(fragToFix->fileRef,
+ fragToFix->locator.offset + fragToFix->sectionHeaders[sectionIndex].containerOffset,
+ fragToFix->sectionHeaders[sectionIndex].containerLength,
+ fragToFix->loaderSection);
+ }
+ }
+
+ // No clean up. The client must init fragToFix to zeros and then
+ // clean up regardless of whether we return an error.
+
+ return err;
}
static UInt32 DecodeVCountValue(const UInt8 *start, UInt32 *outCount)
- // Given a pointer to the start of a variable length PEF value,
- // work out the value (in *outCount). Returns the number of bytes
- // consumed by the value.
+ // Given a pointer to the start of a variable length PEF value,
+ // work out the value (in *outCount). Returns the number of bytes
+ // consumed by the value.
{
- UInt8 * bytePtr;
- UInt8 byte;
- UInt32 count;
-
- bytePtr = (UInt8 *)start;
-
- // Code taken from "PEFBinaryFormat.h".
- count = 0;
- do {
- byte = *bytePtr++;
- count = (count << kPEFPkDataVCountShift) | (byte & kPEFPkDataVCountMask);
- } while ((byte & kPEFPkDataVCountEndMask) != 0);
-
- *outCount = count;
- return bytePtr - start;
+ UInt8 * bytePtr;
+ UInt8 byte;
+ UInt32 count;
+
+ bytePtr = (UInt8 *)start;
+
+ // Code taken from "PEFBinaryFormat.h".
+ count = 0;
+ do {
+ byte = *bytePtr++;
+ count = (count << kPEFPkDataVCountShift) | (byte & kPEFPkDataVCountMask);
+ } while ((byte & kPEFPkDataVCountEndMask) != 0);
+
+ *outCount = count;
+ return bytePtr - start;
}
static UInt32 DecodeInstrCountValue(const UInt8 *inOpStart, UInt32 *outCount)
- // Given a pointer to the start of an opcode (inOpStart), work out the
- // count argument for that opcode (*outCount). Returns the number of
- // bytes consumed by the opcode and count combination.
+ // Given a pointer to the start of an opcode (inOpStart), work out the
+ // count argument for that opcode (*outCount). Returns the number of
+ // bytes consumed by the opcode and count combination.
{
- MoreAssertQ(inOpStart != nil);
- MoreAssertQ(outCount != nil);
-
- if (PEFPkDataCount5(*inOpStart) != 0)
- {
- // Simple case, count encoded in opcode.
- *outCount = PEFPkDataCount5(*inOpStart);
- return 1;
- }
- else
- {
- // Variable-length case.
- return 1 + DecodeVCountValue(inOpStart + 1, outCount);
- }
+ MoreAssertQ(inOpStart != nil);
+ MoreAssertQ(outCount != nil);
+
+ if (PEFPkDataCount5(*inOpStart) != 0)
+ {
+ // Simple case, count encoded in opcode.
+ *outCount = PEFPkDataCount5(*inOpStart);
+ return 1;
+ }
+ else
+ {
+ // Variable-length case.
+ return 1 + DecodeVCountValue(inOpStart + 1, outCount);
+ }
}
static OSStatus UnpackPEFDataSection(const UInt8 * const packedData, UInt32 packedSize,
- UInt8 * const unpackedData, UInt32 unpackedSize)
+ UInt8 * const unpackedData, UInt32 unpackedSize)
{
- OSErr err;
- UInt32 offset;
- UInt8 opCode;
- UInt8 * unpackCursor;
-
- MoreAssertQ(packedData != nil);
- MoreAssertQ(unpackedData != nil);
- MoreAssertQ(unpackedSize >= packedSize);
-
- // The following asserts assume that the client allocated the memory with NewPtr,
- // which may not always be true. However, the asserts' value in preventing accidental
- // memory block overruns outweighs the possible maintenance effort.
-
- MoreAssertQ( packedSize == GetPtrSize( (Ptr) packedData ) );
- MoreAssertQ( unpackedSize == GetPtrSize( (Ptr) unpackedData) );
-
- err = noErr;
- offset = 0;
- unpackCursor = unpackedData;
- while (offset < packedSize) {
- MoreAssertQ(unpackCursor < &unpackedData[unpackedSize]);
-
- opCode = packedData[offset];
-
- switch (PEFPkDataOpcode(opCode)) {
- case kPEFPkDataZero:
- {
- UInt32 count;
-
- offset += DecodeInstrCountValue(&packedData[offset], &count);
-
- MoreBlockZero(unpackCursor, count);
- unpackCursor += count;
- }
- break;
-
- case kPEFPkDataBlock:
- {
- UInt32 blockSize;
-
- offset += DecodeInstrCountValue(&packedData[offset], &blockSize);
-
- BlockMoveData(&packedData[offset], unpackCursor, blockSize);
- unpackCursor += blockSize;
- offset += blockSize;
- }
- break;
-
- case kPEFPkDataRepeat:
- {
- UInt32 blockSize;
- UInt32 repeatCount;
- UInt32 loopCounter;
-
- offset += DecodeInstrCountValue(&packedData[offset], &blockSize);
- offset += DecodeVCountValue(&packedData[offset], &repeatCount);
- repeatCount += 1; // stored value is (repeatCount - 1)
-
- for (loopCounter = 0; loopCounter < repeatCount; loopCounter++) {
- BlockMoveData(&packedData[offset], unpackCursor, blockSize);
- unpackCursor += blockSize;
- }
- offset += blockSize;
- }
- break;
-
- case kPEFPkDataRepeatBlock:
- {
- UInt32 commonSize;
- UInt32 customSize;
- UInt32 repeatCount;
- const UInt8 *commonData;
- const UInt8 *customData;
- UInt32 loopCounter;
-
- offset += DecodeInstrCountValue(&packedData[offset], &commonSize);
- offset += DecodeVCountValue(&packedData[offset], &customSize);
- offset += DecodeVCountValue(&packedData[offset], &repeatCount);
-
- commonData = &packedData[offset];
- customData = &packedData[offset + commonSize];
-
- for (loopCounter = 0; loopCounter < repeatCount; loopCounter++) {
- BlockMoveData(commonData, unpackCursor, commonSize);
- unpackCursor += commonSize;
- BlockMoveData(customData, unpackCursor, customSize);
- unpackCursor += customSize;
- customData += customSize;
- }
- BlockMoveData(commonData, unpackCursor, commonSize);
- unpackCursor += commonSize;
- offset += (repeatCount * (commonSize + customSize)) + commonSize;
- }
- break;
-
- case kPEFPkDataRepeatZero:
- {
- UInt32 commonSize;
- UInt32 customSize;
- UInt32 repeatCount;
- const UInt8 *customData;
- UInt32 loopCounter;
-
- offset += DecodeInstrCountValue(&packedData[offset], &commonSize);
- offset += DecodeVCountValue(&packedData[offset], &customSize);
- offset += DecodeVCountValue(&packedData[offset], &repeatCount);
-
- customData = &packedData[offset];
-
- for (loopCounter = 0; loopCounter < repeatCount; loopCounter++) {
- MoreBlockZero(unpackCursor, commonSize);
- unpackCursor += commonSize;
- BlockMoveData(customData, unpackCursor, customSize);
- unpackCursor += customSize;
- customData += customSize;
- }
- MoreBlockZero(unpackCursor, commonSize);
- unpackCursor += commonSize;
- offset += repeatCount * customSize;
- }
- break;
-
- default:
- #if MORE_DEBUG
- DebugStr("\pUnpackPEFDataSection: Unexpected data opcode");
- #endif
- err = cfragFragmentCorruptErr;
- goto leaveNow;
- break;
- }
- }
-
+ OSErr err;
+ UInt32 offset;
+ UInt8 opCode;
+ UInt8 * unpackCursor;
+
+ MoreAssertQ(packedData != nil);
+ MoreAssertQ(unpackedData != nil);
+ MoreAssertQ(unpackedSize >= packedSize);
+
+ // The following asserts assume that the client allocated the memory with NewPtr,
+ // which may not always be true. However, the asserts' value in preventing accidental
+ // memory block overruns outweighs the possible maintenance effort.
+
+ MoreAssertQ( packedSize == GetPtrSize( (Ptr) packedData ) );
+ MoreAssertQ( unpackedSize == GetPtrSize( (Ptr) unpackedData) );
+
+ err = noErr;
+ offset = 0;
+ unpackCursor = unpackedData;
+ while (offset < packedSize) {
+ MoreAssertQ(unpackCursor < &unpackedData[unpackedSize]);
+
+ opCode = packedData[offset];
+
+ switch (PEFPkDataOpcode(opCode)) {
+ case kPEFPkDataZero:
+ {
+ UInt32 count;
+
+ offset += DecodeInstrCountValue(&packedData[offset], &count);
+
+ MoreBlockZero(unpackCursor, count);
+ unpackCursor += count;
+ }
+ break;
+
+ case kPEFPkDataBlock:
+ {
+ UInt32 blockSize;
+
+ offset += DecodeInstrCountValue(&packedData[offset], &blockSize);
+
+ BlockMoveData(&packedData[offset], unpackCursor, blockSize);
+ unpackCursor += blockSize;
+ offset += blockSize;
+ }
+ break;
+
+ case kPEFPkDataRepeat:
+ {
+ UInt32 blockSize;
+ UInt32 repeatCount;
+ UInt32 loopCounter;
+
+ offset += DecodeInstrCountValue(&packedData[offset], &blockSize);
+ offset += DecodeVCountValue(&packedData[offset], &repeatCount);
+ repeatCount += 1; // stored value is (repeatCount - 1)
+
+ for (loopCounter = 0; loopCounter < repeatCount; loopCounter++) {
+ BlockMoveData(&packedData[offset], unpackCursor, blockSize);
+ unpackCursor += blockSize;
+ }
+ offset += blockSize;
+ }
+ break;
+
+ case kPEFPkDataRepeatBlock:
+ {
+ UInt32 commonSize;
+ UInt32 customSize;
+ UInt32 repeatCount;
+ const UInt8 *commonData;
+ const UInt8 *customData;
+ UInt32 loopCounter;
+
+ offset += DecodeInstrCountValue(&packedData[offset], &commonSize);
+ offset += DecodeVCountValue(&packedData[offset], &customSize);
+ offset += DecodeVCountValue(&packedData[offset], &repeatCount);
+
+ commonData = &packedData[offset];
+ customData = &packedData[offset + commonSize];
+
+ for (loopCounter = 0; loopCounter < repeatCount; loopCounter++) {
+ BlockMoveData(commonData, unpackCursor, commonSize);
+ unpackCursor += commonSize;
+ BlockMoveData(customData, unpackCursor, customSize);
+ unpackCursor += customSize;
+ customData += customSize;
+ }
+ BlockMoveData(commonData, unpackCursor, commonSize);
+ unpackCursor += commonSize;
+ offset += (repeatCount * (commonSize + customSize)) + commonSize;
+ }
+ break;
+
+ case kPEFPkDataRepeatZero:
+ {
+ UInt32 commonSize;
+ UInt32 customSize;
+ UInt32 repeatCount;
+ const UInt8 *customData;
+ UInt32 loopCounter;
+
+ offset += DecodeInstrCountValue(&packedData[offset], &commonSize);
+ offset += DecodeVCountValue(&packedData[offset], &customSize);
+ offset += DecodeVCountValue(&packedData[offset], &repeatCount);
+
+ customData = &packedData[offset];
+
+ for (loopCounter = 0; loopCounter < repeatCount; loopCounter++) {
+ MoreBlockZero(unpackCursor, commonSize);
+ unpackCursor += commonSize;
+ BlockMoveData(customData, unpackCursor, customSize);
+ unpackCursor += customSize;
+ customData += customSize;
+ }
+ MoreBlockZero(unpackCursor, commonSize);
+ unpackCursor += commonSize;
+ offset += repeatCount * customSize;
+ }
+ break;
+
+ default:
+ #if MORE_DEBUG
+ DebugStr("\pUnpackPEFDataSection: Unexpected data opcode");
+ #endif
+ err = cfragFragmentCorruptErr;
+ goto leaveNow;
+ break;
+ }
+ }
+
leaveNow:
- return err;
+ return err;
}
-/* SetupSectionBaseAddresses Rationale
- -----------------------------------
-
- OK, here's where things get weird. In order to run the relocation
- engine, I need to be able to find the base address of an instantiated
- section of the fragment we're fixing up given only its section number.
- This isn't hard for CFM to do because it's the one that instantiated the
- sections in the first place. It's surprisingly difficult to do if
- you're not CFM. [And you don't have access to the private CFM APis for
- doing it.]
-
- [Alan Lillich is going to kill me when he reads this! I should point out
- that TVector's don't have to contain two words, they can be longer,
- and that the second word isn't necessarily a TOC pointer, it's
- just that the calling conventions require that it be put in the
- TOC register when the code is called.
-
- Furthermore, the code section isn't always section 0, and the data
- section isn't always section 1, and there can be zero to many sections
- of each type.
-
- But these niceties are besides the point: I'm doing something tricky
- because I don't have a nice API for getting section base addresses.
- If I had a nice API for doing that, none of this code would exist.
- ]
-
- The technique is very sneaky (thanks to Eric Grant). The fragment to
- fix necessarily has a CFM init routine (because it needs that routine
- in order to capture the fragment location and connection ID). Thus the
- fragment to fix must have a TVector in its data section. TVectors are
- interesting because they're made up of two words. The first is a pointer
- to the code that implements the routine; the second is a pointer to the TOC
- for the fragment that's exporting the TVector. How TVectors are
- created is interesting too. On disk, a TVector consists of two words,
- the first being the offset from the start of the code section to the
- routine, the second being the offset from the start of the data section
- to the TOC base. When CFM prepares a TVector, it applies the following
- transform:
-
- tvector.codePtr = tvector.codeOffset + base of code section
- tvector.tocPtr = tvector.tocOffset + base of data section
-
- Now, you can reverse these questions to make them:
-
- base of code section = tvector.codePtr - tvector.codeOffset
- base of data section = tvector.dataPtr - tvector.dataOffset
-
- So if you can find the relocated contents of the TVector and
- find the original offsets that made up the TVector, you can then
- calculate the base address of both the code and data sections.
-
- Finding the relocated contents of the TVector is easy; I simply
- require the client to pass in a pointer to its init routine.
- A routine pointer is a TVector pointer, so you can just cast it
- and extract the pair of words.
-
- Finding the original offsets is a trickier. My technique is to
- look up the init routine in the fragment's loader info header. This
- yields the section number and offset where the init routine's unrelocated
- TVector exists. Once I have that, I can just read the unrelocated TVector
- out of the file and extract the offsets.
+/* SetupSectionBaseAddresses Rationale
+ -----------------------------------
+
+ OK, here's where things get weird. In order to run the relocation
+ engine, I need to be able to find the base address of an instantiated
+ section of the fragment we're fixing up given only its section number.
+ This isn't hard for CFM to do because it's the one that instantiated the
+ sections in the first place. It's surprisingly difficult to do if
+ you're not CFM. [And you don't have access to the private CFM APis for
+ doing it.]
+
+ [Alan Lillich is going to kill me when he reads this! I should point out
+ that TVector's don't have to contain two words, they can be longer,
+ and that the second word isn't necessarily a TOC pointer, it's
+ just that the calling conventions require that it be put in the
+ TOC register when the code is called.
+
+ Furthermore, the code section isn't always section 0, and the data
+ section isn't always section 1, and there can be zero to many sections
+ of each type.
+
+ But these niceties are besides the point: I'm doing something tricky
+ because I don't have a nice API for getting section base addresses.
+ If I had a nice API for doing that, none of this code would exist.
+ ]
+
+ The technique is very sneaky (thanks to Eric Grant). The fragment to
+ fix necessarily has a CFM init routine (because it needs that routine
+ in order to capture the fragment location and connection ID). Thus the
+ fragment to fix must have a TVector in its data section. TVectors are
+ interesting because they're made up of two words. The first is a pointer
+ to the code that implements the routine; the second is a pointer to the TOC
+ for the fragment that's exporting the TVector. How TVectors are
+ created is interesting too. On disk, a TVector consists of two words,
+ the first being the offset from the start of the code section to the
+ routine, the second being the offset from the start of the data section
+ to the TOC base. When CFM prepares a TVector, it applies the following
+ transform:
+
+ tvector.codePtr = tvector.codeOffset + base of code section
+ tvector.tocPtr = tvector.tocOffset + base of data section
+
+ Now, you can reverse these questions to make them:
+
+ base of code section = tvector.codePtr - tvector.codeOffset
+ base of data section = tvector.dataPtr - tvector.dataOffset
+
+ So if you can find the relocated contents of the TVector and
+ find the original offsets that made up the TVector, you can then
+ calculate the base address of both the code and data sections.
+
+ Finding the relocated contents of the TVector is easy; I simply
+ require the client to pass in a pointer to its init routine.
+ A routine pointer is a TVector pointer, so you can just cast it
+ and extract the pair of words.
+
+ Finding the original offsets is a trickier. My technique is to
+ look up the init routine in the fragment's loader info header. This
+ yields the section number and offset where the init routine's unrelocated
+ TVector exists. Once I have that, I can just read the unrelocated TVector
+ out of the file and extract the offsets.
*/
struct TVector {
- void *codePtr;
- void *tocPtr;
+ void *codePtr;
+ void *tocPtr;
};
typedef struct TVector TVector;
static OSStatus SetupSectionBaseAddresses(FragToFixInfo *fragToFix)
- // This routine initialises the section0Base and section1Base
- // base fields of fragToFix to the base addresses of the
- // instantiated fragment represented by the other fields
- // of fragToFix. The process works in three states:
- //
- // 1. Find the contents of the relocated TVector of the
- // fragment's initialisation routine, provided to us by
- // the caller.
- //
- // 2. Find the contents of the non-relocated TVector by
- // looking it up in the PEF loader info header and then
- // using that to read the TVector contents from disk.
- // This yields the offsets from the section bases for
- // the init routine.
- //
- // 3. Subtract 2 from 3.
+ // This routine initialises the section0Base and section1Base
+ // base fields of fragToFix to the base addresses of the
+ // instantiated fragment represented by the other fields
+ // of fragToFix. The process works in three states:
+ //
+ // 1. Find the contents of the relocated TVector of the
+ // fragment's initialisation routine, provided to us by
+ // the caller.
+ //
+ // 2. Find the contents of the non-relocated TVector by
+ // looking it up in the PEF loader info header and then
+ // using that to read the TVector contents from disk.
+ // This yields the offsets from the section bases for
+ // the init routine.
+ //
+ // 3. Subtract 2 from 3.
{
- OSStatus err;
- TVector * relocatedExport;
- SInt32 initSection;
- UInt32 initOffset;
- PEFSectionHeader * initSectionHeader;
- Ptr packedDataSection;
- Ptr unpackedDataSection;
- TVector originalOffsets;
-
- packedDataSection = nil;
- unpackedDataSection = nil;
-
- // Step 1.
-
- // First find the init routine's TVector, which gives us the relocated
- // offsets of the init routine into the data and code sections.
-
- relocatedExport = (TVector *) fragToFix->initRoutine;
-
- // Step 2.
-
- // Now find the init routine's TVector's offsets in the data section on
- // disk. This gives us the raw offsets from the data and code section
- // of the beginning of the init routine.
-
- err = noErr;
- initSection = fragToFix->loaderSection->initSection;
- initOffset = fragToFix->loaderSection->initOffset;
- if (initSection == -1) {
- err = cfragFragmentUsageErr;
- }
- if (err == noErr) {
- MoreAssertQ( initSection >= 0 ); // Negative indexes are pseudo-sections which are just not allowed!
- MoreAssertQ( initSection < fragToFix->containerHeader.sectionCount );
-
- initSectionHeader = &fragToFix->sectionHeaders[initSection];
-
- // If the data section is packed, unpack it to a temporary buffer and then get the
- // original offsets from that buffer. If the data section is unpacked, just read
- // the original offsets directly off the disk.
-
- if ( initSectionHeader->sectionKind == kPEFPackedDataSection ) {
-
- // Allocate space for packed and unpacked copies of the section.
-
- packedDataSection = NewPtr(initSectionHeader->containerLength);
- err = MemError();
-
- if (err == noErr) {
- unpackedDataSection = NewPtr(initSectionHeader->unpackedLength);
- err = MemError();
- }
-
- // Read the contents of the packed section.
-
- if (err == noErr) {
- err = FSReadAtOffset( fragToFix->fileRef,
- fragToFix->locator.offset
- + initSectionHeader->containerOffset,
- initSectionHeader->containerLength,
- packedDataSection);
- }
-
- // Unpack the data into the unpacked section.
-
- if (err == noErr) {
- err = UnpackPEFDataSection( (UInt8 *) packedDataSection, initSectionHeader->containerLength,
- (UInt8 *) unpackedDataSection, initSectionHeader->unpackedLength);
- }
-
- // Extract the init routine's TVector from the unpacked section.
-
- if (err == noErr) {
- BlockMoveData(unpackedDataSection + initOffset, &originalOffsets, sizeof(TVector));
- }
-
- } else {
- MoreAssertQ(fragToFix->sectionHeaders[initSection].sectionKind == kPEFUnpackedDataSection);
- err = FSReadAtOffset(fragToFix->fileRef,
- fragToFix->locator.offset
- + fragToFix->sectionHeaders[initSection].containerOffset
- + initOffset,
- sizeof(TVector),
- &originalOffsets);
- }
- }
-
- // Step 3.
-
- // Do the maths to subtract the unrelocated offsets from the current address
- // to get the base address.
-
- if (err == noErr) {
- fragToFix->section0Base = ((char *) relocatedExport->codePtr) - (UInt32) originalOffsets.codePtr;
- fragToFix->section1Base = ((char *) relocatedExport->tocPtr) - (UInt32) originalOffsets.tocPtr;
- }
-
- // Clean up.
-
- if (packedDataSection != nil) {
- DisposePtr(packedDataSection);
- MoreAssertQ( MemError() == noErr );
- }
- if (unpackedDataSection != nil) {
- DisposePtr(unpackedDataSection);
- MoreAssertQ( MemError() == noErr );
- }
- return err;
+ OSStatus err;
+ TVector * relocatedExport;
+ SInt32 initSection;
+ UInt32 initOffset;
+ PEFSectionHeader * initSectionHeader;
+ Ptr packedDataSection;
+ Ptr unpackedDataSection;
+ TVector originalOffsets;
+
+ packedDataSection = nil;
+ unpackedDataSection = nil;
+
+ // Step 1.
+
+ // First find the init routine's TVector, which gives us the relocated
+ // offsets of the init routine into the data and code sections.
+
+ relocatedExport = (TVector *) fragToFix->initRoutine;
+
+ // Step 2.
+
+ // Now find the init routine's TVector's offsets in the data section on
+ // disk. This gives us the raw offsets from the data and code section
+ // of the beginning of the init routine.
+
+ err = noErr;
+ initSection = fragToFix->loaderSection->initSection;
+ initOffset = fragToFix->loaderSection->initOffset;
+ if (initSection == -1) {
+ err = cfragFragmentUsageErr;
+ }
+ if (err == noErr) {
+ MoreAssertQ( initSection >= 0 ); // Negative indexes are pseudo-sections which are just not allowed!
+ MoreAssertQ( initSection < fragToFix->containerHeader.sectionCount );
+
+ initSectionHeader = &fragToFix->sectionHeaders[initSection];
+
+ // If the data section is packed, unpack it to a temporary buffer and then get the
+ // original offsets from that buffer. If the data section is unpacked, just read
+ // the original offsets directly off the disk.
+
+ if ( initSectionHeader->sectionKind == kPEFPackedDataSection ) {
+
+ // Allocate space for packed and unpacked copies of the section.
+
+ packedDataSection = NewPtr(initSectionHeader->containerLength);
+ err = MemError();
+
+ if (err == noErr) {
+ unpackedDataSection = NewPtr(initSectionHeader->unpackedLength);
+ err = MemError();
+ }
+
+ // Read the contents of the packed section.
+
+ if (err == noErr) {
+ err = FSReadAtOffset( fragToFix->fileRef,
+ fragToFix->locator.offset
+ + initSectionHeader->containerOffset,
+ initSectionHeader->containerLength,
+ packedDataSection);
+ }
+
+ // Unpack the data into the unpacked section.
+
+ if (err == noErr) {
+ err = UnpackPEFDataSection( (UInt8 *) packedDataSection, initSectionHeader->containerLength,
+ (UInt8 *) unpackedDataSection, initSectionHeader->unpackedLength);
+ }
+
+ // Extract the init routine's TVector from the unpacked section.
+
+ if (err == noErr) {
+ BlockMoveData(unpackedDataSection + initOffset, &originalOffsets, sizeof(TVector));
+ }
+
+ } else {
+ MoreAssertQ(fragToFix->sectionHeaders[initSection].sectionKind == kPEFUnpackedDataSection);
+ err = FSReadAtOffset(fragToFix->fileRef,
+ fragToFix->locator.offset
+ + fragToFix->sectionHeaders[initSection].containerOffset
+ + initOffset,
+ sizeof(TVector),
+ &originalOffsets);
+ }
+ }
+
+ // Step 3.
+
+ // Do the maths to subtract the unrelocated offsets from the current address
+ // to get the base address.
+
+ if (err == noErr) {
+ fragToFix->section0Base = ((char *) relocatedExport->codePtr) - (UInt32) originalOffsets.codePtr;
+ fragToFix->section1Base = ((char *) relocatedExport->tocPtr) - (UInt32) originalOffsets.tocPtr;
+ }
+
+ // Clean up.
+
+ if (packedDataSection != nil) {
+ DisposePtr(packedDataSection);
+ MoreAssertQ( MemError() == noErr );
+ }
+ if (unpackedDataSection != nil) {
+ DisposePtr(unpackedDataSection);
+ MoreAssertQ( MemError() == noErr );
+ }
+ return err;
}
static void *GetSectionBaseAddress(const FragToFixInfo *fragToFix, UInt16 sectionIndex)
- // This routine returns the base of the instantiated section
- // whose index is sectionIndex. This routine is the evil twin
- // of SetupSectionBaseAddresses. It simply returns the values
- // for section 0 and 1 that we derived in SetupSectionBaseAddresses.
- // In a real implementation, this routine would call CFM API
- // to get this information, and SetupSectionBaseAddresses would
- // not exist, but CFM does not export the necessary APIs to
- // third parties.
+ // This routine returns the base of the instantiated section
+ // whose index is sectionIndex. This routine is the evil twin
+ // of SetupSectionBaseAddresses. It simply returns the values
+ // for section 0 and 1 that we derived in SetupSectionBaseAddresses.
+ // In a real implementation, this routine would call CFM API
+ // to get this information, and SetupSectionBaseAddresses would
+ // not exist, but CFM does not export the necessary APIs to
+ // third parties.
{
- void *result;
-
- MoreAssertQ(fragToFix != nil);
- MoreAssertQ(fragToFix->containerHeader.tag1 == kPEFTag1);
-
- switch (sectionIndex) {
- case 0:
- result = fragToFix->section0Base;
- break;
- case 1:
- result = fragToFix->section1Base;
- break;
- default:
- result = nil;
- break;
- }
- return result;
+ void *result;
+
+ MoreAssertQ(fragToFix != nil);
+ MoreAssertQ(fragToFix->containerHeader.tag1 == kPEFTag1);
+
+ switch (sectionIndex) {
+ case 0:
+ result = fragToFix->section0Base;
+ break;
+ case 1:
+ result = fragToFix->section1Base;
+ break;
+ default:
+ result = nil;
+ break;
+ }
+ return result;
}
static OSStatus FindImportLibrary(PEFLoaderInfoHeader *loaderSection, const char *libraryName, PEFImportedLibrary **importLibrary)
- // This routine finds the import library description (PEFImportedLibrary)
- // for the import library libraryName in the PEF loader section.
- // It sets *importLibrary to the address of the description.
+ // This routine finds the import library description (PEFImportedLibrary)
+ // for the import library libraryName in the PEF loader section.
+ // It sets *importLibrary to the address of the description.
{
- OSStatus err;
- UInt32 librariesRemaining;
- PEFImportedLibrary *thisImportLibrary;
- Boolean found;
-
- MoreAssertQ(loaderSection != nil);
- MoreAssertQ(libraryName != nil);
- MoreAssertQ(importLibrary != nil);
-
- // Loop through each import library looking for a matching name.
-
- // Initialise thisImportLibrary to point to the byte after the
- // end of the loader section's header.
-
- thisImportLibrary = (PEFImportedLibrary *) (loaderSection + 1);
- librariesRemaining = loaderSection->importedLibraryCount;
- found = false;
- while ( librariesRemaining > 0 && ! found ) {
- // PEF defines that import library names will have
- // a null terminator, so we can just use strcmp.
- found = (strcmp( libraryName,
- ((char *)loaderSection)
- + loaderSection->loaderStringsOffset
- + thisImportLibrary->nameOffset) == 0);
- // *** Remove ANSI strcmp eventually.
- if ( ! found ) {
- thisImportLibrary += 1;
- librariesRemaining -= 1;
- }
- }
-
- if (found) {
- *importLibrary = thisImportLibrary;
- err = noErr;
- } else {
- *importLibrary = nil;
- err = cfragNoLibraryErr;
- }
- return err;
+ OSStatus err;
+ UInt32 librariesRemaining;
+ PEFImportedLibrary *thisImportLibrary;
+ Boolean found;
+
+ MoreAssertQ(loaderSection != nil);
+ MoreAssertQ(libraryName != nil);
+ MoreAssertQ(importLibrary != nil);
+
+ // Loop through each import library looking for a matching name.
+
+ // Initialise thisImportLibrary to point to the byte after the
+ // end of the loader section's header.
+
+ thisImportLibrary = (PEFImportedLibrary *) (loaderSection + 1);
+ librariesRemaining = loaderSection->importedLibraryCount;
+ found = false;
+ while ( librariesRemaining > 0 && ! found ) {
+ // PEF defines that import library names will have
+ // a null terminator, so we can just use strcmp.
+ found = (strcmp( libraryName,
+ ((char *)loaderSection)
+ + loaderSection->loaderStringsOffset
+ + thisImportLibrary->nameOffset) == 0);
+ // *** Remove ANSI strcmp eventually.
+ if ( ! found ) {
+ thisImportLibrary += 1;
+ librariesRemaining -= 1;
+ }
+ }
+
+ if (found) {
+ *importLibrary = thisImportLibrary;
+ err = noErr;
+ } else {
+ *importLibrary = nil;
+ err = cfragNoLibraryErr;
+ }
+ return err;
}
static OSStatus LookupSymbol(CFMLateImportLookupProc lookup, void *refCon,
- PEFLoaderInfoHeader *loaderSection,
- UInt32 symbolIndex,
- UInt32 *symbolValue)
- // This routine is used to look up a symbol during relocation.
- // "lookup" is a client callback and refCon is its argument.
- // Typically refCon is the CFM connection to the library that is
- // substituting for the weak linked library. loaderSection
- // is a pointer to the loader section of the fragment to fix up.
- // symbolIndex is the index of the imported symbol in the loader section.
- // The routine sets the word pointed to by symbolValue to the
- // value of the symbol.
- //
- // The routine works by using symbolIndex to index into the imported
- // symbol table to find the offset of the symbol's name in the string
- // table. It then looks up the symbol by calling the client's "lookup"
- // function and passes the resulting symbol address back in symbolValue.
+ PEFLoaderInfoHeader *loaderSection,
+ UInt32 symbolIndex,
+ UInt32 *symbolValue)
+ // This routine is used to look up a symbol during relocation.
+ // "lookup" is a client callback and refCon is its argument.
+ // Typically refCon is the CFM connection to the library that is
+ // substituting for the weak linked library. loaderSection
+ // is a pointer to the loader section of the fragment to fix up.
+ // symbolIndex is the index of the imported symbol in the loader section.
+ // The routine sets the word pointed to by symbolValue to the
+ // value of the symbol.
+ //
+ // The routine works by using symbolIndex to index into the imported
+ // symbol table to find the offset of the symbol's name in the string
+ // table. It then looks up the symbol by calling the client's "lookup"
+ // function and passes the resulting symbol address back in symbolValue.
{
- OSStatus err;
- UInt32 *importSymbolTable;
- UInt32 symbolStringOffset;
- Boolean symbolIsWeak;
- CFragSymbolClass symbolClass;
- char *symbolStringAddress;
- Str255 symbolString;
-
- MoreAssertQ(lookup != nil);
- MoreAssertQ(loaderSection != nil);
- MoreAssertQ(symbolIndex < loaderSection->totalImportedSymbolCount);
- MoreAssertQ(symbolValue != nil);
-
- // Find the base of the imported symbol table.
-
- importSymbolTable = (UInt32 *)(((char *)(loaderSection + 1)) + (loaderSection->importedLibraryCount * sizeof(PEFImportedLibrary)));
-
- // Grab the appropriate entry out of the table and
- // extract the information from that entry.
-
- symbolStringOffset = importSymbolTable[symbolIndex];
- symbolClass = PEFImportedSymbolClass(symbolStringOffset);
- symbolIsWeak = ((symbolClass & kPEFWeakImportSymMask) != 0);
- symbolClass = symbolClass & ~kPEFWeakImportSymMask;
- symbolStringOffset = PEFImportedSymbolNameOffset(symbolStringOffset);
-
- // Find the string for the symbol in the strings table and
- // extract it from the table into a Pascal string on the stack.
-
- symbolStringAddress = ((char *)loaderSection) + loaderSection->loaderStringsOffset + symbolStringOffset;
- symbolString[0] = strlen(symbolStringAddress); // *** remove ANSI strlen
- BlockMoveData(symbolStringAddress, &symbolString[1], symbolString[0]);
-
- // Look up the symbol in substitute library. If it fails, return
- // a 0 value and check whether the error is fatal (a strong linked
- // symbol) or benign (a weak linked symbol).
-
- err = lookup(symbolString, symbolClass, (void **) symbolValue, refCon);
- if (err != noErr) {
- *symbolValue = 0;
- if (symbolIsWeak) {
- err = noErr;
- }
- }
- return err;
+ OSStatus err;
+ UInt32 *importSymbolTable;
+ UInt32 symbolStringOffset;
+ Boolean symbolIsWeak;
+ CFragSymbolClass symbolClass;
+ char *symbolStringAddress;
+ Str255 symbolString;
+
+ MoreAssertQ(lookup != nil);
+ MoreAssertQ(loaderSection != nil);
+ MoreAssertQ(symbolIndex < loaderSection->totalImportedSymbolCount);
+ MoreAssertQ(symbolValue != nil);
+
+ // Find the base of the imported symbol table.
+
+ importSymbolTable = (UInt32 *)(((char *)(loaderSection + 1)) + (loaderSection->importedLibraryCount * sizeof(PEFImportedLibrary)));
+
+ // Grab the appropriate entry out of the table and
+ // extract the information from that entry.
+
+ symbolStringOffset = importSymbolTable[symbolIndex];
+ symbolClass = PEFImportedSymbolClass(symbolStringOffset);
+ symbolIsWeak = ((symbolClass & kPEFWeakImportSymMask) != 0);
+ symbolClass = symbolClass & ~kPEFWeakImportSymMask;
+ symbolStringOffset = PEFImportedSymbolNameOffset(symbolStringOffset);
+
+ // Find the string for the symbol in the strings table and
+ // extract it from the table into a Pascal string on the stack.
+
+ symbolStringAddress = ((char *)loaderSection) + loaderSection->loaderStringsOffset + symbolStringOffset;
+ symbolString[0] = strlen(symbolStringAddress); // *** remove ANSI strlen
+ BlockMoveData(symbolStringAddress, &symbolString[1], symbolString[0]);
+
+ // Look up the symbol in substitute library. If it fails, return
+ // a 0 value and check whether the error is fatal (a strong linked
+ // symbol) or benign (a weak linked symbol).
+
+ err = lookup(symbolString, symbolClass, (void **) symbolValue, refCon);
+ if (err != noErr) {
+ *symbolValue = 0;
+ if (symbolIsWeak) {
+ err = noErr;
+ }
+ }
+ return err;
}
// The EngineState structure encapsulates all of the persistent state
@@ -771,13 +771,13 @@ static OSStatus LookupSymbol(CFMLateImportLookupProc lookup, void *refCon,
// instructional design.
struct EngineState {
- UInt32 currentReloc; // Index of current relocation opcodes
- UInt32 terminatingReloc; // Index of relocation opcodes which terminates relocation
- UInt32 *sectionBase; // Start of the section
- UInt32 *relocAddress; // Address within the section where the relocations are to be performed
- UInt32 importIndex; // Symbol index, which is used to access an imported symbol's address
- void *sectionC; // Memory address of an instantiated section within the PEF container; this variable is used by relocation opcodes that relocate section addresses
- void *sectionD; // Memory address of an instantiated section within the PEF container; this variable is used by relocation opcodes that relocate section addresses
+ UInt32 currentReloc; // Index of current relocation opcodes
+ UInt32 terminatingReloc; // Index of relocation opcodes which terminates relocation
+ UInt32 *sectionBase; // Start of the section
+ UInt32 *relocAddress; // Address within the section where the relocations are to be performed
+ UInt32 importIndex; // Symbol index, which is used to access an imported symbol's address
+ void *sectionC; // Memory address of an instantiated section within the PEF container; this variable is used by relocation opcodes that relocate section addresses
+ void *sectionD; // Memory address of an instantiated section within the PEF container; this variable is used by relocation opcodes that relocate section addresses
};
typedef struct EngineState EngineState;
@@ -786,83 +786,83 @@ typedef struct EngineState EngineState;
// have to add a repeat counter to EngineState.
static OSStatus InitEngineState(const FragToFixInfo *fragToFix,
- UInt16 relocHeaderIndex,
- EngineState *state)
- // This routine initialises the engine state suitably for
- // running the relocation opcodes for the section whose
- // index is relocHeaderIndex. relocHeaderIndex is not a
- // a section number. See the comment where it's used below
- // for details. The routine basically fills out all the fields
- // in the EngineState structure as described by
- // "Mac OS Runtime Architectures".
+ UInt16 relocHeaderIndex,
+ EngineState *state)
+ // This routine initialises the engine state suitably for
+ // running the relocation opcodes for the section whose
+ // index is relocHeaderIndex. relocHeaderIndex is not a
+ // a section number. See the comment where it's used below
+ // for details. The routine basically fills out all the fields
+ // in the EngineState structure as described by
+ // "Mac OS Runtime Architectures".
{
- OSStatus err;
- PEFLoaderRelocationHeader *relocHeader;
-
- MoreAssertQ(fragToFix != nil);
- MoreAssertQ(state != nil);
-
- // This bit is tricky. relocHeaderIndex is an index into the relocation
- // header table, starting at relocSectionCount (which is in the loader
- // section header) for the first relocated section and decrementing
- // down to 1 for the last relocated section. I find the relocation
- // header by using relocHeaderIndex as a index backwards from the
- // start of the relocation opcodes (ie relocInstrOffset). If you
- // look at the diagram of the layout of the container in
- // "PEFBinaryFormat.h", you'll see that the relocation opcodes
- // immediately follow the relocation headers.
- //
- // I did this because the alternative (starting at the loader
- // header and stepping past the import library table and the
- // import symbol table) was a pain.
-
- relocHeader = (PEFLoaderRelocationHeader *) (((char *) fragToFix->loaderSection) + fragToFix->loaderSection->relocInstrOffset - relocHeaderIndex * sizeof(PEFLoaderRelocationHeader));
-
- MoreAssertQ(relocHeader->reservedA == 0); // PEF spec says it must be; we check to try to catch bugs in calculation of relocHeader
-
- state->currentReloc = relocHeader->firstRelocOffset;
- state->terminatingReloc = relocHeader->firstRelocOffset + relocHeader->relocCount;
- state->sectionBase = (UInt32 *) GetSectionBaseAddress(fragToFix, relocHeader->sectionIndex);
- state->relocAddress = state->sectionBase;
- state->importIndex = 0;
-
- // From "Mac OS Runtime Architectures":
- //
- // The sectionC and sectionD variables actually contain the
- // memory address of an instantiated section minus the
- // default address for that section. The default address for a
- // section is contained in the defaultAddress field of the
- // section header. However, in almost all cases the default
- // address should be 0, so the simplified definition suffices.
- //
- // In the debug version, we drop into MacsBug if this weird case
- // ever executes because it's more likely we made a mistake than
- // we encountered a section with a default address.
-
- state->sectionC = GetSectionBaseAddress(fragToFix, 0);
- if (state->sectionC != nil) {
- #if MORE_DEBUG
- if (fragToFix->sectionHeaders[0].defaultAddress != 0) {
- DebugStr("\pInitEngineState: Executing weird case.");
- }
- #endif
- (char *) state->sectionC -= fragToFix->sectionHeaders[0].defaultAddress;
- }
- state->sectionD = GetSectionBaseAddress(fragToFix, 1);
- if (state->sectionD != nil) {
- #if MORE_DEBUG
- if (fragToFix->sectionHeaders[1].defaultAddress != 0) {
- DebugStr("\pInitEngineState: Executing weird case.");
- }
- #endif
- (char *) state->sectionD -= fragToFix->sectionHeaders[1].defaultAddress;
- }
-
- err = noErr;
- if (state->relocAddress == nil) {
- err = cfragFragmentUsageErr;
- }
- return err;
+ OSStatus err;
+ PEFLoaderRelocationHeader *relocHeader;
+
+ MoreAssertQ(fragToFix != nil);
+ MoreAssertQ(state != nil);
+
+ // This bit is tricky. relocHeaderIndex is an index into the relocation
+ // header table, starting at relocSectionCount (which is in the loader
+ // section header) for the first relocated section and decrementing
+ // down to 1 for the last relocated section. I find the relocation
+ // header by using relocHeaderIndex as a index backwards from the
+ // start of the relocation opcodes (ie relocInstrOffset). If you
+ // look at the diagram of the layout of the container in
+ // "PEFBinaryFormat.h", you'll see that the relocation opcodes
+ // immediately follow the relocation headers.
+ //
+ // I did this because the alternative (starting at the loader
+ // header and stepping past the import library table and the
+ // import symbol table) was a pain.
+
+ relocHeader = (PEFLoaderRelocationHeader *) (((char *) fragToFix->loaderSection) + fragToFix->loaderSection->relocInstrOffset - relocHeaderIndex * sizeof(PEFLoaderRelocationHeader));
+
+ MoreAssertQ(relocHeader->reservedA == 0); // PEF spec says it must be; we check to try to catch bugs in calculation of relocHeader
+
+ state->currentReloc = relocHeader->firstRelocOffset;
+ state->terminatingReloc = relocHeader->firstRelocOffset + relocHeader->relocCount;
+ state->sectionBase = (UInt32 *) GetSectionBaseAddress(fragToFix, relocHeader->sectionIndex);
+ state->relocAddress = state->sectionBase;
+ state->importIndex = 0;
+
+ // From "Mac OS Runtime Architectures":
+ //
+ // The sectionC and sectionD variables actually contain the
+ // memory address of an instantiated section minus the
+ // default address for that section. The default address for a
+ // section is contained in the defaultAddress field of the
+ // section header. However, in almost all cases the default
+ // address should be 0, so the simplified definition suffices.
+ //
+ // In the debug version, we drop into MacsBug if this weird case
+ // ever executes because it's more likely we made a mistake than
+ // we encountered a section with a default address.
+
+ state->sectionC = GetSectionBaseAddress(fragToFix, 0);
+ if (state->sectionC != nil) {
+ #if MORE_DEBUG
+ if (fragToFix->sectionHeaders[0].defaultAddress != 0) {
+ DebugStr("\pInitEngineState: Executing weird case.");
+ }
+ #endif
+ (char *) state->sectionC -= fragToFix->sectionHeaders[0].defaultAddress;
+ }
+ state->sectionD = GetSectionBaseAddress(fragToFix, 1);
+ if (state->sectionD != nil) {
+ #if MORE_DEBUG
+ if (fragToFix->sectionHeaders[1].defaultAddress != 0) {
+ DebugStr("\pInitEngineState: Executing weird case.");
+ }
+ #endif
+ (char *) state->sectionD -= fragToFix->sectionHeaders[1].defaultAddress;
+ }
+
+ err = noErr;
+ if (state->relocAddress == nil) {
+ err = cfragFragmentUsageErr;
+ }
+ return err;
}
// kPEFRelocBasicOpcodes is a table that maps the top 7 bits of the opcode
@@ -871,490 +871,490 @@ static OSStatus InitEngineState(const FragToFixInfo *fragToFix,
static UInt8 kPEFRelocBasicOpcodes[kPEFRelocBasicOpcodeRange] = { PEFMaskedBasicOpcodes };
-static OSStatus RunRelocationEngine(const FragToFixInfo *fragToFix,
- PEFImportedLibrary *importLibrary,
- CFMLateImportLookupProc lookup, void *refCon)
- // This is where the rubber really hits the. Given a fully
- // populated fragToFix structure, the import library description
- // of the weak imported library we're resolving, and a connection
- // to the library we're going to substitute it, re-execute the
- // relocation instructions (CFM has already executed them once)
- // but only *do* instructions (ie store the change to the data section)
- // that CFM skipped because the weak symbols were missing.
+static OSStatus RunRelocationEngine(const FragToFixInfo *fragToFix,
+ PEFImportedLibrary *importLibrary,
+ CFMLateImportLookupProc lookup, void *refCon)
+ // This is where the rubber really hits the. Given a fully
+ // populated fragToFix structure, the import library description
+ // of the weak imported library we're resolving, and a connection
+ // to the library we're going to substitute it, re-execute the
+ // relocation instructions (CFM has already executed them once)
+ // but only *do* instructions (ie store the change to the data section)
+ // that CFM skipped because the weak symbols were missing.
{
- OSStatus err;
- EngineState state;
- UInt16 sectionsLeftToRelocate;
- UInt32 totalRelocs;
- UInt16 *relocInstrTable;
- UInt16 opCode;
-
- MoreAssertQ(fragToFix != nil);
- MoreAssertQ(fragToFix->containerHeader.tag1 == kPEFTag1);
- MoreAssertQ(fragToFix->sectionHeaders != nil);
- MoreAssertQ(fragToFix->loaderSection != nil);
- MoreAssertQ(fragToFix->section0Base != nil); // Technically, having a nil for these two is not a problem, ...
- MoreAssertQ(fragToFix->section1Base != nil); // but in practise it a wildly deviant case and we should know about it.
- MoreAssertQ(importLibrary != nil);
- MoreAssertQ(lookup != nil);
-
- // Before entering the loop, work out some information in advance.
-
- // totalRelocs is only used for debugging, to make sure our
- // relocation PC (state.currentReloc) doesn't run wild.
-
- totalRelocs = (fragToFix->loaderSection->loaderStringsOffset - fragToFix->loaderSection->relocInstrOffset) / sizeof(UInt16);
-
- // relocInstrTable is the base address of the table of relocation
- // instructions in the fragment to fix.
-
- relocInstrTable = (UInt16 *)((char *) fragToFix->loaderSection + fragToFix->loaderSection->relocInstrOffset);
-
- // sectionsLeftToRelocate is the loop counter for the outer loop.
-
- MoreAssertQ(fragToFix->loaderSection->relocSectionCount <= 0x0FFFF);
- sectionsLeftToRelocate = fragToFix->loaderSection->relocSectionCount;
-
- // Now let's run the relocation engine. We run it once per
- // section in the table. Each time around, we init the engine
- // and then loop again, this time executing individual opcodes.
- // The opcode loop terminates when the relocation PC
- // (state.currentReloc) hits the final opcode (state.terminatingReloc).
-
- // Note:
- // One design decision I made was to totally re-init the engine state
- // for each section. The CFM spec is unclear as to whether you're supposed
- // to totally re-init the engine state, or just re-init the section-specific
- // state (ie currentReloc, terminatingReloc, and relocAddress). I hope this
- // is correct, but it's hard to test without having a fragment with multiple
- // relocated sections, which is difficult to create.
-
- // How do I decide which opcodes should be effective (ie make changes to
- // the section being relocated) and which opcodes should just be executed
- // for their side effects (ie updated state.relocAddress or state.importIndex)?
- // The answer is both simple and subtle. Opcodes whose actions are dependent
- // on a symbol that was in the weak linked library are effective, those that
- // an independent of those symbols are not. The only opcodes that use
- // symbolic values are kPEFRelocImportRun and kPEFRelocSmByImport, and
- // these are only if the symbol is in the weak linked library.
- // All other cases are executed for their side effects only.
- //
- // How do I determine if a symbol is in the weak linked library?
- // Well I know the symbol's index and I know the lower bound and count
- // of the symbols in the weak linked library, so I just do a simple
- // bounds test, ie
- //
- // firstImportedSymbol <= importIndex < firstImportedSymbol + importedSymbolCount
-
- // From this code, it's relatively easy to see which relocation opcodes
- // aren't implemented. If you ever encounter one, you'll find yourself
- // in MacsBug with a message telling you which opcode was found. The
- // two big groups of opcodes I skipped were the large format opcodes
- // and the repeating opcodes. I skipped them because:
- //
- // a) I haven't got a way to generate them in a PEF container that I can
- // test against. Without that, there's no way I could be assured that
- // the code worked.
- //
- // b) I'm lazy.
-
- err = noErr;
- while ( sectionsLeftToRelocate > 0 ) {
- err = InitEngineState(fragToFix, sectionsLeftToRelocate, &state);
- if (err != noErr) {
- goto leaveNow;
- }
-
- while ( state.currentReloc != state.terminatingReloc ) {
-
- MoreAssertQ( state.currentReloc < totalRelocs );
-
- opCode = relocInstrTable[state.currentReloc];
- switch ( PEFRelocBasicOpcode(opCode) ) {
- case kPEFRelocBySectDWithSkip:
- {
- UInt16 skipCount;
- UInt16 relocCount;
-
- skipCount = ((opCode >> 6) & 0x00FF);
- relocCount = (opCode & 0x003F);
- state.relocAddress += skipCount;
- state.relocAddress += relocCount;
- }
- break;
- case kPEFRelocBySectC:
- case kPEFRelocBySectD:
- {
- UInt16 runLength;
-
- runLength = (opCode & 0x01FF) + 1;
- state.relocAddress += runLength;
- }
- break;
- case kPEFRelocTVector12:
- {
- UInt16 runLength;
-
- runLength = (opCode & 0x01FF) + 1;
- state.relocAddress += (runLength * 3);
- }
- break;
- case kPEFRelocTVector8:
- case kPEFRelocVTable8:
- {
- UInt16 runLength;
-
- runLength = (opCode & 0x01FF) + 1;
- state.relocAddress += (runLength * 2);
- }
- break;
- case kPEFRelocImportRun:
- {
- UInt32 symbolValue;
- UInt16 runLength;
-
- runLength = (opCode & 0x01FF) + 1;
- while (runLength > 0) {
- if ( state.importIndex >= importLibrary->firstImportedSymbol && state.importIndex < (importLibrary->firstImportedSymbol + importLibrary->importedSymbolCount) ) {
- err = LookupSymbol(lookup, refCon, fragToFix->loaderSection, state.importIndex, &symbolValue);
- if (err != noErr) {
- goto leaveNow;
- }
- *(state.relocAddress) += symbolValue;
- }
- state.importIndex += 1;
- state.relocAddress += 1;
- runLength -= 1;
- }
- }
- break;
- case kPEFRelocSmByImport:
- {
- UInt32 symbolValue;
- UInt32 index;
-
- index = (opCode & 0x01FF);
- if ( index >= importLibrary->firstImportedSymbol && index < (importLibrary->firstImportedSymbol + importLibrary->importedSymbolCount) ) {
- err = LookupSymbol(lookup, refCon, fragToFix->loaderSection, index, &symbolValue);
- if (err != noErr) {
- goto leaveNow;
- }
- *(state.relocAddress) += symbolValue;
- }
- state.importIndex = index + 1;
- state.relocAddress += 1;
- }
- break;
- case kPEFRelocSmSetSectC:
- {
- UInt32 index;
-
- index = (opCode & 0x01FF);
- state.sectionC = GetSectionBaseAddress(fragToFix, index);
- MoreAssertQ(state.sectionC != nil);
- }
- break;
- case kPEFRelocSmSetSectD:
- {
- UInt32 index;
-
- index = (opCode & 0x01FF);
- state.sectionD = GetSectionBaseAddress(fragToFix, index);
- MoreAssertQ(state.sectionD != nil);
- }
- break;
- case kPEFRelocSmBySection:
- state.relocAddress += 1;
- break;
- case kPEFRelocIncrPosition:
- {
- UInt16 offset;
-
- offset = (opCode & 0x0FFF) + 1;
- ((char *) state.relocAddress) += offset;
- }
- break;
- case kPEFRelocSmRepeat:
- #if MORE_DEBUG
- DebugStr("\pRunRelocationEngine: kPEFRelocSmRepeat not yet implemented");
- #endif
- err = unimpErr;
- goto leaveNow;
- break;
- case kPEFRelocSetPosition:
- {
- UInt32 offset;
-
- // Lot's of folks have tried various interpretations of the description of
- // this opCode in "Mac OS Runtime Architectures" (which states "This instruction
- // sets relocAddress to the address of the section offset offset." *smile*).
- // I eventually dug into the CFM source code to find my interpretation, which
- // I believe is correct. The key point is tht the offset is relative to
- // the start of the section for which these relocations are being performed.
-
- // Skip to next reloc word, which is the second chunk of the offset.
-
- state.currentReloc += 1;
-
- // Extract offset based on the most significant 10 bits in opCode and
- // the next significant 16 bits in the next reloc word.
-
- offset = PEFRelocSetPosFullOffset(opCode, relocInstrTable[state.currentReloc]);
-
- state.relocAddress = (UInt32 *) ( ((char *) state.sectionBase) + offset);
- }
- break;
- case kPEFRelocLgByImport:
- {
- UInt32 symbolValue;
- UInt32 index;
-
- // Get the 26 bit symbol index from the current and next reloc words.
-
- state.currentReloc += 1;
- index = PEFRelocLgByImportFullIndex(opCode, relocInstrTable[state.currentReloc]);
-
- if ( index >= importLibrary->firstImportedSymbol && index < (importLibrary->firstImportedSymbol + importLibrary->importedSymbolCount) ) {
- err = LookupSymbol(lookup, refCon, fragToFix->loaderSection, index, &symbolValue);
- if (err != noErr) {
- goto leaveNow;
- }
- *(state.relocAddress) += symbolValue;
- }
- state.importIndex = index + 1;
- state.relocAddress += 1;
- }
- break;
- case kPEFRelocLgRepeat:
- #if MORE_DEBUG
- DebugStr("\pRunRelocationEngine: kPEFRelocLgRepeat not yet implemented");
- #endif
- err = unimpErr;
- goto leaveNow;
- break;
- case kPEFRelocLgSetOrBySection:
- #if MORE_DEBUG
- DebugStr("\pRunRelocationEngine: kPEFRelocLgSetOrBySection not yet implemented");
- #endif
- err = unimpErr;
- goto leaveNow;
- break;
- case kPEFRelocUndefinedOpcode:
- err = cfragFragmentCorruptErr;
- goto leaveNow;
- break;
- default:
- MoreAssertQ(false);
- err = cfragFragmentCorruptErr;
- goto leaveNow;
- break;
- }
- state.currentReloc += 1;
- }
-
- sectionsLeftToRelocate -= 1;
- }
+ OSStatus err;
+ EngineState state;
+ UInt16 sectionsLeftToRelocate;
+ UInt32 totalRelocs;
+ UInt16 *relocInstrTable;
+ UInt16 opCode;
+
+ MoreAssertQ(fragToFix != nil);
+ MoreAssertQ(fragToFix->containerHeader.tag1 == kPEFTag1);
+ MoreAssertQ(fragToFix->sectionHeaders != nil);
+ MoreAssertQ(fragToFix->loaderSection != nil);
+ MoreAssertQ(fragToFix->section0Base != nil); // Technically, having a nil for these two is not a problem, ...
+ MoreAssertQ(fragToFix->section1Base != nil); // but in practise it a wildly deviant case and we should know about it.
+ MoreAssertQ(importLibrary != nil);
+ MoreAssertQ(lookup != nil);
+
+ // Before entering the loop, work out some information in advance.
+
+ // totalRelocs is only used for debugging, to make sure our
+ // relocation PC (state.currentReloc) doesn't run wild.
+
+ totalRelocs = (fragToFix->loaderSection->loaderStringsOffset - fragToFix->loaderSection->relocInstrOffset) / sizeof(UInt16);
+
+ // relocInstrTable is the base address of the table of relocation
+ // instructions in the fragment to fix.
+
+ relocInstrTable = (UInt16 *)((char *) fragToFix->loaderSection + fragToFix->loaderSection->relocInstrOffset);
+
+ // sectionsLeftToRelocate is the loop counter for the outer loop.
+
+ MoreAssertQ(fragToFix->loaderSection->relocSectionCount <= 0x0FFFF);
+ sectionsLeftToRelocate = fragToFix->loaderSection->relocSectionCount;
+
+ // Now let's run the relocation engine. We run it once per
+ // section in the table. Each time around, we init the engine
+ // and then loop again, this time executing individual opcodes.
+ // The opcode loop terminates when the relocation PC
+ // (state.currentReloc) hits the final opcode (state.terminatingReloc).
+
+ // Note:
+ // One design decision I made was to totally re-init the engine state
+ // for each section. The CFM spec is unclear as to whether you're supposed
+ // to totally re-init the engine state, or just re-init the section-specific
+ // state (ie currentReloc, terminatingReloc, and relocAddress). I hope this
+ // is correct, but it's hard to test without having a fragment with multiple
+ // relocated sections, which is difficult to create.
+
+ // How do I decide which opcodes should be effective (ie make changes to
+ // the section being relocated) and which opcodes should just be executed
+ // for their side effects (ie updated state.relocAddress or state.importIndex)?
+ // The answer is both simple and subtle. Opcodes whose actions are dependent
+ // on a symbol that was in the weak linked library are effective, those that
+ // an independent of those symbols are not. The only opcodes that use
+ // symbolic values are kPEFRelocImportRun and kPEFRelocSmByImport, and
+ // these are only if the symbol is in the weak linked library.
+ // All other cases are executed for their side effects only.
+ //
+ // How do I determine if a symbol is in the weak linked library?
+ // Well I know the symbol's index and I know the lower bound and count
+ // of the symbols in the weak linked library, so I just do a simple
+ // bounds test, ie
+ //
+ // firstImportedSymbol <= importIndex < firstImportedSymbol + importedSymbolCount
+
+ // From this code, it's relatively easy to see which relocation opcodes
+ // aren't implemented. If you ever encounter one, you'll find yourself
+ // in MacsBug with a message telling you which opcode was found. The
+ // two big groups of opcodes I skipped were the large format opcodes
+ // and the repeating opcodes. I skipped them because:
+ //
+ // a) I haven't got a way to generate them in a PEF container that I can
+ // test against. Without that, there's no way I could be assured that
+ // the code worked.
+ //
+ // b) I'm lazy.
+
+ err = noErr;
+ while ( sectionsLeftToRelocate > 0 ) {
+ err = InitEngineState(fragToFix, sectionsLeftToRelocate, &state);
+ if (err != noErr) {
+ goto leaveNow;
+ }
+
+ while ( state.currentReloc != state.terminatingReloc ) {
+
+ MoreAssertQ( state.currentReloc < totalRelocs );
+
+ opCode = relocInstrTable[state.currentReloc];
+ switch ( PEFRelocBasicOpcode(opCode) ) {
+ case kPEFRelocBySectDWithSkip:
+ {
+ UInt16 skipCount;
+ UInt16 relocCount;
+
+ skipCount = ((opCode >> 6) & 0x00FF);
+ relocCount = (opCode & 0x003F);
+ state.relocAddress += skipCount;
+ state.relocAddress += relocCount;
+ }
+ break;
+ case kPEFRelocBySectC:
+ case kPEFRelocBySectD:
+ {
+ UInt16 runLength;
+
+ runLength = (opCode & 0x01FF) + 1;
+ state.relocAddress += runLength;
+ }
+ break;
+ case kPEFRelocTVector12:
+ {
+ UInt16 runLength;
+
+ runLength = (opCode & 0x01FF) + 1;
+ state.relocAddress += (runLength * 3);
+ }
+ break;
+ case kPEFRelocTVector8:
+ case kPEFRelocVTable8:
+ {
+ UInt16 runLength;
+
+ runLength = (opCode & 0x01FF) + 1;
+ state.relocAddress += (runLength * 2);
+ }
+ break;
+ case kPEFRelocImportRun:
+ {
+ UInt32 symbolValue;
+ UInt16 runLength;
+
+ runLength = (opCode & 0x01FF) + 1;
+ while (runLength > 0) {
+ if ( state.importIndex >= importLibrary->firstImportedSymbol && state.importIndex < (importLibrary->firstImportedSymbol + importLibrary->importedSymbolCount) ) {
+ err = LookupSymbol(lookup, refCon, fragToFix->loaderSection, state.importIndex, &symbolValue);
+ if (err != noErr) {
+ goto leaveNow;
+ }
+ *(state.relocAddress) += symbolValue;
+ }
+ state.importIndex += 1;
+ state.relocAddress += 1;
+ runLength -= 1;
+ }
+ }
+ break;
+ case kPEFRelocSmByImport:
+ {
+ UInt32 symbolValue;
+ UInt32 index;
+
+ index = (opCode & 0x01FF);
+ if ( index >= importLibrary->firstImportedSymbol && index < (importLibrary->firstImportedSymbol + importLibrary->importedSymbolCount) ) {
+ err = LookupSymbol(lookup, refCon, fragToFix->loaderSection, index, &symbolValue);
+ if (err != noErr) {
+ goto leaveNow;
+ }
+ *(state.relocAddress) += symbolValue;
+ }
+ state.importIndex = index + 1;
+ state.relocAddress += 1;
+ }
+ break;
+ case kPEFRelocSmSetSectC:
+ {
+ UInt32 index;
+
+ index = (opCode & 0x01FF);
+ state.sectionC = GetSectionBaseAddress(fragToFix, index);
+ MoreAssertQ(state.sectionC != nil);
+ }
+ break;
+ case kPEFRelocSmSetSectD:
+ {
+ UInt32 index;
+
+ index = (opCode & 0x01FF);
+ state.sectionD = GetSectionBaseAddress(fragToFix, index);
+ MoreAssertQ(state.sectionD != nil);
+ }
+ break;
+ case kPEFRelocSmBySection:
+ state.relocAddress += 1;
+ break;
+ case kPEFRelocIncrPosition:
+ {
+ UInt16 offset;
+
+ offset = (opCode & 0x0FFF) + 1;
+ ((char *) state.relocAddress) += offset;
+ }
+ break;
+ case kPEFRelocSmRepeat:
+ #if MORE_DEBUG
+ DebugStr("\pRunRelocationEngine: kPEFRelocSmRepeat not yet implemented");
+ #endif
+ err = unimpErr;
+ goto leaveNow;
+ break;
+ case kPEFRelocSetPosition:
+ {
+ UInt32 offset;
+
+ // Lot's of folks have tried various interpretations of the description of
+ // this opCode in "Mac OS Runtime Architectures" (which states "This instruction
+ // sets relocAddress to the address of the section offset offset." *smile*).
+ // I eventually dug into the CFM source code to find my interpretation, which
+ // I believe is correct. The key point is tht the offset is relative to
+ // the start of the section for which these relocations are being performed.
+
+ // Skip to next reloc word, which is the second chunk of the offset.
+
+ state.currentReloc += 1;
+
+ // Extract offset based on the most significant 10 bits in opCode and
+ // the next significant 16 bits in the next reloc word.
+
+ offset = PEFRelocSetPosFullOffset(opCode, relocInstrTable[state.currentReloc]);
+
+ state.relocAddress = (UInt32 *) ( ((char *) state.sectionBase) + offset);
+ }
+ break;
+ case kPEFRelocLgByImport:
+ {
+ UInt32 symbolValue;
+ UInt32 index;
+
+ // Get the 26 bit symbol index from the current and next reloc words.
+
+ state.currentReloc += 1;
+ index = PEFRelocLgByImportFullIndex(opCode, relocInstrTable[state.currentReloc]);
+
+ if ( index >= importLibrary->firstImportedSymbol && index < (importLibrary->firstImportedSymbol + importLibrary->importedSymbolCount) ) {
+ err = LookupSymbol(lookup, refCon, fragToFix->loaderSection, index, &symbolValue);
+ if (err != noErr) {
+ goto leaveNow;
+ }
+ *(state.relocAddress) += symbolValue;
+ }
+ state.importIndex = index + 1;
+ state.relocAddress += 1;
+ }
+ break;
+ case kPEFRelocLgRepeat:
+ #if MORE_DEBUG
+ DebugStr("\pRunRelocationEngine: kPEFRelocLgRepeat not yet implemented");
+ #endif
+ err = unimpErr;
+ goto leaveNow;
+ break;
+ case kPEFRelocLgSetOrBySection:
+ #if MORE_DEBUG
+ DebugStr("\pRunRelocationEngine: kPEFRelocLgSetOrBySection not yet implemented");
+ #endif
+ err = unimpErr;
+ goto leaveNow;
+ break;
+ case kPEFRelocUndefinedOpcode:
+ err = cfragFragmentCorruptErr;
+ goto leaveNow;
+ break;
+ default:
+ MoreAssertQ(false);
+ err = cfragFragmentCorruptErr;
+ goto leaveNow;
+ break;
+ }
+ state.currentReloc += 1;
+ }
+
+ sectionsLeftToRelocate -= 1;
+ }
leaveNow:
- return err;
+ return err;
}
extern pascal OSStatus CFMLateImportCore(const CFragSystem7DiskFlatLocator *fragToFixLocator,
- CFragConnectionID fragToFixConnID,
- CFragInitFunction fragToFixInitRoutine,
- ConstStr255Param weakLinkedLibraryName,
- CFMLateImportLookupProc lookup,
- void *refCon)
- // See comments in interface part.
+ CFragConnectionID fragToFixConnID,
+ CFragInitFunction fragToFixInitRoutine,
+ ConstStr255Param weakLinkedLibraryName,
+ CFMLateImportLookupProc lookup,
+ void *refCon)
+ // See comments in interface part.
{
- OSStatus err;
- OSStatus junk;
- FragToFixInfo fragToFix;
- PEFImportedLibrary *importLibrary;
- char weakLinkedLibraryNameCString[256];
-
- MoreAssertQ(fragToFixLocator != nil);
- MoreAssertQ(fragToFixConnID != nil);
- MoreAssertQ(fragToFixInitRoutine != nil);
- MoreAssertQ(weakLinkedLibraryName != nil);
- MoreAssertQ(lookup != nil);
-
- // Fill out the bits of fragToFix which are passed in
- // by the client.
-
- MoreBlockZero(&fragToFix, sizeof(fragToFix));
- fragToFix.locator = *fragToFixLocator;
- fragToFix.connID = fragToFixConnID;
- fragToFix.initRoutine = fragToFixInitRoutine;
-
- // Make a C string from weakLinkedLibraryName.
-
- BlockMoveData(weakLinkedLibraryName + 1, weakLinkedLibraryNameCString, weakLinkedLibraryName[0]);
- weakLinkedLibraryNameCString[weakLinkedLibraryName[0]] = 0;
-
- // Get the basic information from the fragment.
- // Fills out the containerHeader, sectionHeaders, loaderSection and fileRef fields
- // of fragToFix.
-
- err = ReadContainerBasics(&fragToFix);
-
- // Set up the base address fields in fragToFix (ie section0Base and section1Base)
- // by looking up our init routine (fragToFix.initRoutine) and subtracting
- // away the section offsets (which we get from the disk copy of the section)
- // to derive the bases of the sections themselves.
-
- if (err == noErr) {
- err = SetupSectionBaseAddresses(&fragToFix);
- }
-
- // Look inside the loader section for the import library description
- // of weakLinkedLibraryName. We need this to know the range of symbol
- // indexes we're going to fix up.
-
- if (err == noErr) {
- err = FindImportLibrary(fragToFix.loaderSection, weakLinkedLibraryNameCString, &importLibrary);
- }
-
- // Do a quick check to ensure that the library was actually imported weak.
- // If it wasn't, it doesn't make much sense to resolve its weak imports
- // later on. Resolving them again is likely to be bad.
-
- if (err == noErr) {
- if ((importLibrary->options & kPEFWeakImportLibMask) == 0) {
- err = cfragFragmentUsageErr;
- }
- }
-
- // Now run the main relocation engine.
-
- if (err == noErr) {
- err = RunRelocationEngine(&fragToFix, importLibrary, lookup, refCon);
- }
-
- // Clean up.
-
- if (fragToFix.disposeSectionPointers) {
- if (fragToFix.fileRef != 0) {
- junk = FSClose(fragToFix.fileRef);
- MoreAssertQ(junk == noErr);
- }
- if (fragToFix.loaderSection != nil) {
- DisposePtr( (Ptr) fragToFix.loaderSection);
- MoreAssertQ(MemError() == noErr);
- }
- if (fragToFix.sectionHeaders != nil) {
- DisposePtr( (Ptr) fragToFix.sectionHeaders);
- MoreAssertQ(MemError() == noErr);
- }
- }
- return err;
+ OSStatus err;
+ OSStatus junk;
+ FragToFixInfo fragToFix;
+ PEFImportedLibrary *importLibrary;
+ char weakLinkedLibraryNameCString[256];
+
+ MoreAssertQ(fragToFixLocator != nil);
+ MoreAssertQ(fragToFixConnID != nil);
+ MoreAssertQ(fragToFixInitRoutine != nil);
+ MoreAssertQ(weakLinkedLibraryName != nil);
+ MoreAssertQ(lookup != nil);
+
+ // Fill out the bits of fragToFix which are passed in
+ // by the client.
+
+ MoreBlockZero(&fragToFix, sizeof(fragToFix));
+ fragToFix.locator = *fragToFixLocator;
+ fragToFix.connID = fragToFixConnID;
+ fragToFix.initRoutine = fragToFixInitRoutine;
+
+ // Make a C string from weakLinkedLibraryName.
+
+ BlockMoveData(weakLinkedLibraryName + 1, weakLinkedLibraryNameCString, weakLinkedLibraryName[0]);
+ weakLinkedLibraryNameCString[weakLinkedLibraryName[0]] = 0;
+
+ // Get the basic information from the fragment.
+ // Fills out the containerHeader, sectionHeaders, loaderSection and fileRef fields
+ // of fragToFix.
+
+ err = ReadContainerBasics(&fragToFix);
+
+ // Set up the base address fields in fragToFix (ie section0Base and section1Base)
+ // by looking up our init routine (fragToFix.initRoutine) and subtracting
+ // away the section offsets (which we get from the disk copy of the section)
+ // to derive the bases of the sections themselves.
+
+ if (err == noErr) {
+ err = SetupSectionBaseAddresses(&fragToFix);
+ }
+
+ // Look inside the loader section for the import library description
+ // of weakLinkedLibraryName. We need this to know the range of symbol
+ // indexes we're going to fix up.
+
+ if (err == noErr) {
+ err = FindImportLibrary(fragToFix.loaderSection, weakLinkedLibraryNameCString, &importLibrary);
+ }
+
+ // Do a quick check to ensure that the library was actually imported weak.
+ // If it wasn't, it doesn't make much sense to resolve its weak imports
+ // later on. Resolving them again is likely to be bad.
+
+ if (err == noErr) {
+ if ((importLibrary->options & kPEFWeakImportLibMask) == 0) {
+ err = cfragFragmentUsageErr;
+ }
+ }
+
+ // Now run the main relocation engine.
+
+ if (err == noErr) {
+ err = RunRelocationEngine(&fragToFix, importLibrary, lookup, refCon);
+ }
+
+ // Clean up.
+
+ if (fragToFix.disposeSectionPointers) {
+ if (fragToFix.fileRef != 0) {
+ junk = FSClose(fragToFix.fileRef);
+ MoreAssertQ(junk == noErr);
+ }
+ if (fragToFix.loaderSection != nil) {
+ DisposePtr( (Ptr) fragToFix.loaderSection);
+ MoreAssertQ(MemError() == noErr);
+ }
+ if (fragToFix.sectionHeaders != nil) {
+ DisposePtr( (Ptr) fragToFix.sectionHeaders);
+ MoreAssertQ(MemError() == noErr);
+ }
+ }
+ return err;
}
static pascal OSStatus FragmentLookup(ConstStr255Param symName, CFragSymbolClass symClass,
- void **symAddr, void *refCon)
- // This is the CFMLateImportLookupProc callback used when
- // late importing from a CFM shared library.
+ void **symAddr, void *refCon)
+ // This is the CFMLateImportLookupProc callback used when
+ // late importing from a CFM shared library.
{
- OSStatus err;
- CFragConnectionID connIDToImport;
- CFragSymbolClass foundSymClass;
-
- MoreAssertQ(symName != nil);
- MoreAssertQ(symAddr != nil);
- MoreAssertQ(refCon != nil);
-
- connIDToImport = (CFragConnectionID) refCon;
-
- // Shame there's no way to validate that connIDToImport is valid.
-
- err = FindSymbol(connIDToImport, symName, (Ptr *) symAddr, &foundSymClass);
- if (err == noErr) {
- // If the symbol isn't of the right class, we act like we didn't
- // find it, but also assert in the debug build because weird things
- // are afoot.
- if (foundSymClass != symClass) {
- MoreAssertQ(false);
- *symAddr = nil;
- err = cfragNoSymbolErr;
- }
- }
- return err;
+ OSStatus err;
+ CFragConnectionID connIDToImport;
+ CFragSymbolClass foundSymClass;
+
+ MoreAssertQ(symName != nil);
+ MoreAssertQ(symAddr != nil);
+ MoreAssertQ(refCon != nil);
+
+ connIDToImport = (CFragConnectionID) refCon;
+
+ // Shame there's no way to validate that connIDToImport is valid.
+
+ err = FindSymbol(connIDToImport, symName, (Ptr *) symAddr, &foundSymClass);
+ if (err == noErr) {
+ // If the symbol isn't of the right class, we act like we didn't
+ // find it, but also assert in the debug build because weird things
+ // are afoot.
+ if (foundSymClass != symClass) {
+ MoreAssertQ(false);
+ *symAddr = nil;
+ err = cfragNoSymbolErr;
+ }
+ }
+ return err;
}
extern pascal OSStatus CFMLateImportLibrary(const CFragSystem7DiskFlatLocator *fragToFixLocator,
- CFragConnectionID fragToFixConnID,
- CFragInitFunction fragToFixInitRoutine,
- ConstStr255Param weakLinkedLibraryName,
- CFragConnectionID connIDToImport)
- // See comments in interface part.
+ CFragConnectionID fragToFixConnID,
+ CFragInitFunction fragToFixInitRoutine,
+ ConstStr255Param weakLinkedLibraryName,
+ CFragConnectionID connIDToImport)
+ // See comments in interface part.
{
- MoreAssertQ(connIDToImport != nil);
- return CFMLateImportCore(fragToFixLocator, fragToFixConnID, fragToFixInitRoutine,
- weakLinkedLibraryName, FragmentLookup, connIDToImport);
+ MoreAssertQ(connIDToImport != nil);
+ return CFMLateImportCore(fragToFixLocator, fragToFixConnID, fragToFixInitRoutine,
+ weakLinkedLibraryName, FragmentLookup, connIDToImport);
}
static pascal OSStatus BundleLookup(ConstStr255Param symName, CFragSymbolClass symClass,
- void **symAddr, void *refCon)
- // This is the CFMLateImportLookupProc callback used when
- // late importing from a CFBundle.
+ void **symAddr, void *refCon)
+ // This is the CFMLateImportLookupProc callback used when
+ // late importing from a CFBundle.
{
- OSStatus err;
- CFBundleRef bundleToImport;
- CFStringRef symNameStr;
-
- MoreAssertQ(symName != nil);
- MoreAssertQ(symAddr != nil);
- MoreAssertQ(refCon != nil);
-
- symNameStr = nil;
-
- bundleToImport = (CFBundleRef) refCon;
-
- // Shame there's no way to validate that bundleToImport is really a bundle.
-
- // We can only find function pointers because CFBundleGetFunctionPointerForName
- // only works for function pointers. So if the client is asking for something
- // other than a function pointer (ie TVector symbol) then we don't even true.
- // Also assert in the debug build because this shows a certain lack of
- // understanding on the part of the client.
- //
- // CF is being revise to support accessing data symbols using a new API
- // (currently this is available to Apple internal developers as
- // CFBundleGetDataPointerForName). When the new API is available in a
- // public header file I should revise this code to lift this restriction.
-
- err = noErr;
- if (symClass != kTVectorCFragSymbol) {
- MoreAssertQ(false);
- err = cfragNoSymbolErr;
- }
- if (err == noErr) {
- symNameStr = CFStringCreateWithPascalString(kCFAllocatorSystemDefault,
- symName, kCFStringEncodingMacRoman);
- if (symNameStr == nil) {
- err = coreFoundationUnknownErr;
- }
- }
- if (err == noErr) {
- *symAddr = CFBundleGetFunctionPointerForName(bundleToImport, symNameStr);
- if (*symAddr == nil) {
- err = cfragNoSymbolErr;
- }
- }
- if (symNameStr != nil) {
- CFRelease(symNameStr);
- }
- return err;
+ OSStatus err;
+ CFBundleRef bundleToImport;
+ CFStringRef symNameStr;
+
+ MoreAssertQ(symName != nil);
+ MoreAssertQ(symAddr != nil);
+ MoreAssertQ(refCon != nil);
+
+ symNameStr = nil;
+
+ bundleToImport = (CFBundleRef) refCon;
+
+ // Shame there's no way to validate that bundleToImport is really a bundle.
+
+ // We can only find function pointers because CFBundleGetFunctionPointerForName
+ // only works for function pointers. So if the client is asking for something
+ // other than a function pointer (ie TVector symbol) then we don't even true.
+ // Also assert in the debug build because this shows a certain lack of
+ // understanding on the part of the client.
+ //
+ // CF is being revise to support accessing data symbols using a new API
+ // (currently this is available to Apple internal developers as
+ // CFBundleGetDataPointerForName). When the new API is available in a
+ // public header file I should revise this code to lift this restriction.
+
+ err = noErr;
+ if (symClass != kTVectorCFragSymbol) {
+ MoreAssertQ(false);
+ err = cfragNoSymbolErr;
+ }
+ if (err == noErr) {
+ symNameStr = CFStringCreateWithPascalString(kCFAllocatorSystemDefault,
+ symName, kCFStringEncodingMacRoman);
+ if (symNameStr == nil) {
+ err = coreFoundationUnknownErr;
+ }
+ }
+ if (err == noErr) {
+ *symAddr = CFBundleGetFunctionPointerForName(bundleToImport, symNameStr);
+ if (*symAddr == nil) {
+ err = cfragNoSymbolErr;
+ }
+ }
+ if (symNameStr != nil) {
+ CFRelease(symNameStr);
+ }
+ return err;
}
extern pascal OSStatus CFMLateImportBundle(const CFragSystem7DiskFlatLocator *fragToFixLocator,
- CFragConnectionID fragToFixConnID,
- CFragInitFunction fragToFixInitRoutine,
- ConstStr255Param weakLinkedLibraryName,
- CFBundleRef bundleToImport)
- // See comments in interface part.
+ CFragConnectionID fragToFixConnID,
+ CFragInitFunction fragToFixInitRoutine,
+ ConstStr255Param weakLinkedLibraryName,
+ CFBundleRef bundleToImport)
+ // See comments in interface part.
{
- MoreAssertQ(bundleToImport != nil);
- return CFMLateImportCore(fragToFixLocator, fragToFixConnID, fragToFixInitRoutine,
- weakLinkedLibraryName, BundleLookup, bundleToImport);
+ MoreAssertQ(bundleToImport != nil);
+ return CFMLateImportCore(fragToFixLocator, fragToFixConnID, fragToFixInitRoutine,
+ weakLinkedLibraryName, BundleLookup, bundleToImport);
}
diff --git a/Mac/Modules/cg/CFMLateImport.h b/Mac/Modules/cg/CFMLateImport.h
index f3a89bc..0878960 100755
--- a/Mac/Modules/cg/CFMLateImport.h
+++ b/Mac/Modules/cg/CFMLateImport.h
@@ -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
}
diff --git a/Mac/Modules/cg/_CGmodule.c b/Mac/Modules/cg/_CGmodule.c
index e36fce9..7169101 100755
--- a/Mac/Modules/cg/_CGmodule.c
+++ b/Mac/Modules/cg/_CGmodule.c
@@ -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)
@@ -26,67 +26,67 @@ extern int GrafObj_Convert(PyObject *, GrafPtr *);
PyObject *CGPoint_New(CGPoint *itself)
{
- return Py_BuildValue("(ff)",
- itself->x,
- itself->y);
+ return Py_BuildValue("(ff)",
+ itself->x,
+ itself->y);
}
int
CGPoint_Convert(PyObject *v, CGPoint *p_itself)
{
- if( !PyArg_Parse(v, "(ff)",
- &p_itself->x,
- &p_itself->y) )
- return 0;
- return 1;
+ if( !PyArg_Parse(v, "(ff)",
+ &p_itself->x,
+ &p_itself->y) )
+ return 0;
+ return 1;
}
PyObject *CGRect_New(CGRect *itself)
{
- return Py_BuildValue("(ffff)",
- itself->origin.x,
- itself->origin.y,
- itself->size.width,
- itself->size.height);
+ return Py_BuildValue("(ffff)",
+ itself->origin.x,
+ itself->origin.y,
+ itself->size.width,
+ itself->size.height);
}
int
CGRect_Convert(PyObject *v, CGRect *p_itself)
{
- if( !PyArg_Parse(v, "(ffff)",
- &p_itself->origin.x,
- &p_itself->origin.y,
- &p_itself->size.width,
- &p_itself->size.height) )
- return 0;
- return 1;
+ if( !PyArg_Parse(v, "(ffff)",
+ &p_itself->origin.x,
+ &p_itself->origin.y,
+ &p_itself->size.width,
+ &p_itself->size.height) )
+ return 0;
+ return 1;
}
PyObject *CGAffineTransform_New(CGAffineTransform *itself)
{
- return Py_BuildValue("(ffffff)",
- itself->a,
- itself->b,
- itself->c,
- itself->d,
- itself->tx,
- itself->ty);
+ return Py_BuildValue("(ffffff)",
+ itself->a,
+ itself->b,
+ itself->c,
+ itself->d,
+ itself->tx,
+ itself->ty);
}
int
CGAffineTransform_Convert(PyObject *v, CGAffineTransform *p_itself)
{
- if( !PyArg_Parse(v, "(ffffff)",
- &p_itself->a,
- &p_itself->b,
- &p_itself->c,
- &p_itself->d,
- &p_itself->tx,
- &p_itself->ty) )
- return 0;
- return 1;
+ if( !PyArg_Parse(v, "(ffffff)",
+ &p_itself->a,
+ &p_itself->b,
+ &p_itself->c,
+ &p_itself->d,
+ &p_itself->tx,
+ &p_itself->ty) )
+ return 0;
+ return 1;
}
static PyObject *CG_Error;
@@ -98,1090 +98,1090 @@ PyTypeObject CGContextRef_Type;
#define CGContextRefObj_Check(x) ((x)->ob_type == &CGContextRef_Type || PyObject_TypeCheck((x), &CGContextRef_Type))
typedef struct CGContextRefObject {
- PyObject_HEAD
- CGContextRef ob_itself;
+ PyObject_HEAD
+ CGContextRef ob_itself;
} CGContextRefObject;
PyObject *CGContextRefObj_New(CGContextRef itself)
{
- CGContextRefObject *it;
- it = PyObject_NEW(CGContextRefObject, &CGContextRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ CGContextRefObject *it;
+ it = PyObject_NEW(CGContextRefObject, &CGContextRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int CGContextRefObj_Convert(PyObject *v, CGContextRef *p_itself)
{
- if (!CGContextRefObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "CGContextRef required");
- return 0;
- }
- *p_itself = ((CGContextRefObject *)v)->ob_itself;
- return 1;
+ if (!CGContextRefObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "CGContextRef required");
+ return 0;
+ }
+ *p_itself = ((CGContextRefObject *)v)->ob_itself;
+ return 1;
}
static void CGContextRefObj_dealloc(CGContextRefObject *self)
{
- CGContextRelease(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ CGContextRelease(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *CGContextRefObj_CGContextSaveGState(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextSaveGState(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextSaveGState(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextRestoreGState(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextRestoreGState(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextRestoreGState(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextScaleCTM(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float sx;
- float sy;
- if (!PyArg_ParseTuple(_args, "ff",
- &sx,
- &sy))
- return NULL;
- CGContextScaleCTM(_self->ob_itself,
- sx,
- sy);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float sx;
+ float sy;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &sx,
+ &sy))
+ return NULL;
+ CGContextScaleCTM(_self->ob_itself,
+ sx,
+ sy);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextTranslateCTM(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float tx;
- float ty;
- if (!PyArg_ParseTuple(_args, "ff",
- &tx,
- &ty))
- return NULL;
- CGContextTranslateCTM(_self->ob_itself,
- tx,
- ty);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float tx;
+ float ty;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &tx,
+ &ty))
+ return NULL;
+ CGContextTranslateCTM(_self->ob_itself,
+ tx,
+ ty);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextRotateCTM(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float angle;
- if (!PyArg_ParseTuple(_args, "f",
- &angle))
- return NULL;
- CGContextRotateCTM(_self->ob_itself,
- angle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float angle;
+ if (!PyArg_ParseTuple(_args, "f",
+ &angle))
+ return NULL;
+ CGContextRotateCTM(_self->ob_itself,
+ angle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextConcatCTM(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGAffineTransform transform;
- if (!PyArg_ParseTuple(_args, "O&",
- CGAffineTransform_Convert, &transform))
- return NULL;
- CGContextConcatCTM(_self->ob_itself,
- transform);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGAffineTransform transform;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGAffineTransform_Convert, &transform))
+ return NULL;
+ CGContextConcatCTM(_self->ob_itself,
+ transform);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextGetCTM(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGAffineTransform _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextGetCTM(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CGAffineTransform_New, &_rv);
- return _res;
+ PyObject *_res = NULL;
+ CGAffineTransform _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextGetCTM(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CGAffineTransform_New, &_rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetLineWidth(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float width;
- if (!PyArg_ParseTuple(_args, "f",
- &width))
- return NULL;
- CGContextSetLineWidth(_self->ob_itself,
- width);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float width;
+ if (!PyArg_ParseTuple(_args, "f",
+ &width))
+ return NULL;
+ CGContextSetLineWidth(_self->ob_itself,
+ width);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetLineCap(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int cap;
- if (!PyArg_ParseTuple(_args, "i",
- &cap))
- return NULL;
- CGContextSetLineCap(_self->ob_itself,
- cap);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ int cap;
+ if (!PyArg_ParseTuple(_args, "i",
+ &cap))
+ return NULL;
+ CGContextSetLineCap(_self->ob_itself,
+ cap);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetLineJoin(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int join;
- if (!PyArg_ParseTuple(_args, "i",
- &join))
- return NULL;
- CGContextSetLineJoin(_self->ob_itself,
- join);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ int join;
+ if (!PyArg_ParseTuple(_args, "i",
+ &join))
+ return NULL;
+ CGContextSetLineJoin(_self->ob_itself,
+ join);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetMiterLimit(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float limit;
- if (!PyArg_ParseTuple(_args, "f",
- &limit))
- return NULL;
- CGContextSetMiterLimit(_self->ob_itself,
- limit);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float limit;
+ if (!PyArg_ParseTuple(_args, "f",
+ &limit))
+ return NULL;
+ CGContextSetMiterLimit(_self->ob_itself,
+ limit);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetFlatness(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float flatness;
- if (!PyArg_ParseTuple(_args, "f",
- &flatness))
- return NULL;
- CGContextSetFlatness(_self->ob_itself,
- flatness);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float flatness;
+ if (!PyArg_ParseTuple(_args, "f",
+ &flatness))
+ return NULL;
+ CGContextSetFlatness(_self->ob_itself,
+ flatness);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetAlpha(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float alpha;
- if (!PyArg_ParseTuple(_args, "f",
- &alpha))
- return NULL;
- CGContextSetAlpha(_self->ob_itself,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "f",
+ &alpha))
+ return NULL;
+ CGContextSetAlpha(_self->ob_itself,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextBeginPath(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextBeginPath(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextBeginPath(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextMoveToPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float x;
- float y;
- if (!PyArg_ParseTuple(_args, "ff",
- &x,
- &y))
- return NULL;
- CGContextMoveToPoint(_self->ob_itself,
- x,
- y);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float x;
+ float y;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &x,
+ &y))
+ return NULL;
+ CGContextMoveToPoint(_self->ob_itself,
+ x,
+ y);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextAddLineToPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float x;
- float y;
- if (!PyArg_ParseTuple(_args, "ff",
- &x,
- &y))
- return NULL;
- CGContextAddLineToPoint(_self->ob_itself,
- x,
- y);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float x;
+ float y;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &x,
+ &y))
+ return NULL;
+ CGContextAddLineToPoint(_self->ob_itself,
+ x,
+ y);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextAddCurveToPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float cp1x;
- float cp1y;
- float cp2x;
- float cp2y;
- float x;
- float y;
- if (!PyArg_ParseTuple(_args, "ffffff",
- &cp1x,
- &cp1y,
- &cp2x,
- &cp2y,
- &x,
- &y))
- return NULL;
- CGContextAddCurveToPoint(_self->ob_itself,
- cp1x,
- cp1y,
- cp2x,
- cp2y,
- x,
- y);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float cp1x;
+ float cp1y;
+ float cp2x;
+ float cp2y;
+ float x;
+ float y;
+ if (!PyArg_ParseTuple(_args, "ffffff",
+ &cp1x,
+ &cp1y,
+ &cp2x,
+ &cp2y,
+ &x,
+ &y))
+ return NULL;
+ CGContextAddCurveToPoint(_self->ob_itself,
+ cp1x,
+ cp1y,
+ cp2x,
+ cp2y,
+ x,
+ y);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextAddQuadCurveToPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float cpx;
- float cpy;
- float x;
- float y;
- if (!PyArg_ParseTuple(_args, "ffff",
- &cpx,
- &cpy,
- &x,
- &y))
- return NULL;
- CGContextAddQuadCurveToPoint(_self->ob_itself,
- cpx,
- cpy,
- x,
- y);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float cpx;
+ float cpy;
+ float x;
+ float y;
+ if (!PyArg_ParseTuple(_args, "ffff",
+ &cpx,
+ &cpy,
+ &x,
+ &y))
+ return NULL;
+ CGContextAddQuadCurveToPoint(_self->ob_itself,
+ cpx,
+ cpy,
+ x,
+ y);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextClosePath(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextClosePath(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextClosePath(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextAddRect(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect rect;
- if (!PyArg_ParseTuple(_args, "O&",
- CGRect_Convert, &rect))
- return NULL;
- CGContextAddRect(_self->ob_itself,
- rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGRect rect;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGRect_Convert, &rect))
+ return NULL;
+ CGContextAddRect(_self->ob_itself,
+ rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextAddArc(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float x;
- float y;
- float radius;
- float startAngle;
- float endAngle;
- int clockwise;
- if (!PyArg_ParseTuple(_args, "fffffi",
- &x,
- &y,
- &radius,
- &startAngle,
- &endAngle,
- &clockwise))
- return NULL;
- CGContextAddArc(_self->ob_itself,
- x,
- y,
- radius,
- startAngle,
- endAngle,
- clockwise);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float x;
+ float y;
+ float radius;
+ float startAngle;
+ float endAngle;
+ int clockwise;
+ if (!PyArg_ParseTuple(_args, "fffffi",
+ &x,
+ &y,
+ &radius,
+ &startAngle,
+ &endAngle,
+ &clockwise))
+ return NULL;
+ CGContextAddArc(_self->ob_itself,
+ x,
+ y,
+ radius,
+ startAngle,
+ endAngle,
+ clockwise);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextAddArcToPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float x1;
- float y1;
- float x2;
- float y2;
- float radius;
- if (!PyArg_ParseTuple(_args, "fffff",
- &x1,
- &y1,
- &x2,
- &y2,
- &radius))
- return NULL;
- CGContextAddArcToPoint(_self->ob_itself,
- x1,
- y1,
- x2,
- y2,
- radius);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float x1;
+ float y1;
+ float x2;
+ float y2;
+ float radius;
+ if (!PyArg_ParseTuple(_args, "fffff",
+ &x1,
+ &y1,
+ &x2,
+ &y2,
+ &radius))
+ return NULL;
+ CGContextAddArcToPoint(_self->ob_itself,
+ x1,
+ y1,
+ x2,
+ y2,
+ radius);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextIsPathEmpty(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextIsPathEmpty(_self->ob_itself);
- _res = Py_BuildValue("i",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ int _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextIsPathEmpty(_self->ob_itself);
+ _res = Py_BuildValue("i",
+ _rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextGetPathCurrentPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGPoint _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextGetPathCurrentPoint(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CGPoint_New, &_rv);
- return _res;
+ PyObject *_res = NULL;
+ CGPoint _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextGetPathCurrentPoint(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CGPoint_New, &_rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextGetPathBoundingBox(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextGetPathBoundingBox(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CGRect_New, &_rv);
- return _res;
+ PyObject *_res = NULL;
+ CGRect _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextGetPathBoundingBox(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CGRect_New, &_rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextDrawPath(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int mode;
- if (!PyArg_ParseTuple(_args, "i",
- &mode))
- return NULL;
- CGContextDrawPath(_self->ob_itself,
- mode);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ int mode;
+ if (!PyArg_ParseTuple(_args, "i",
+ &mode))
+ return NULL;
+ CGContextDrawPath(_self->ob_itself,
+ mode);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextFillPath(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextFillPath(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextFillPath(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextEOFillPath(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextEOFillPath(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextEOFillPath(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextStrokePath(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextStrokePath(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextStrokePath(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextFillRect(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect rect;
- if (!PyArg_ParseTuple(_args, "O&",
- CGRect_Convert, &rect))
- return NULL;
- CGContextFillRect(_self->ob_itself,
- rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGRect rect;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGRect_Convert, &rect))
+ return NULL;
+ CGContextFillRect(_self->ob_itself,
+ rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextStrokeRect(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect rect;
- if (!PyArg_ParseTuple(_args, "O&",
- CGRect_Convert, &rect))
- return NULL;
- CGContextStrokeRect(_self->ob_itself,
- rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGRect rect;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGRect_Convert, &rect))
+ return NULL;
+ CGContextStrokeRect(_self->ob_itself,
+ rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextStrokeRectWithWidth(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect rect;
- float width;
- if (!PyArg_ParseTuple(_args, "O&f",
- CGRect_Convert, &rect,
- &width))
- return NULL;
- CGContextStrokeRectWithWidth(_self->ob_itself,
- rect,
- width);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGRect rect;
+ float width;
+ if (!PyArg_ParseTuple(_args, "O&f",
+ CGRect_Convert, &rect,
+ &width))
+ return NULL;
+ CGContextStrokeRectWithWidth(_self->ob_itself,
+ rect,
+ width);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextClearRect(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect rect;
- if (!PyArg_ParseTuple(_args, "O&",
- CGRect_Convert, &rect))
- return NULL;
- CGContextClearRect(_self->ob_itself,
- rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGRect rect;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGRect_Convert, &rect))
+ return NULL;
+ CGContextClearRect(_self->ob_itself,
+ rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextClip(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextClip(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextClip(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextEOClip(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextEOClip(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextEOClip(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextClipToRect(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGRect rect;
- if (!PyArg_ParseTuple(_args, "O&",
- CGRect_Convert, &rect))
- return NULL;
- CGContextClipToRect(_self->ob_itself,
- rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGRect rect;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGRect_Convert, &rect))
+ return NULL;
+ CGContextClipToRect(_self->ob_itself,
+ rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetGrayFillColor(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float gray;
- float alpha;
- if (!PyArg_ParseTuple(_args, "ff",
- &gray,
- &alpha))
- return NULL;
- CGContextSetGrayFillColor(_self->ob_itself,
- gray,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float gray;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &gray,
+ &alpha))
+ return NULL;
+ CGContextSetGrayFillColor(_self->ob_itself,
+ gray,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetGrayStrokeColor(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float gray;
- float alpha;
- if (!PyArg_ParseTuple(_args, "ff",
- &gray,
- &alpha))
- return NULL;
- CGContextSetGrayStrokeColor(_self->ob_itself,
- gray,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float gray;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &gray,
+ &alpha))
+ return NULL;
+ CGContextSetGrayStrokeColor(_self->ob_itself,
+ gray,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetRGBFillColor(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float red;
- float green;
- float blue;
- float alpha;
- if (!PyArg_ParseTuple(_args, "ffff",
- &red,
- &green,
- &blue,
- &alpha))
- return NULL;
- CGContextSetRGBFillColor(_self->ob_itself,
- red,
- green,
- blue,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float red;
+ float green;
+ float blue;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "ffff",
+ &red,
+ &green,
+ &blue,
+ &alpha))
+ return NULL;
+ CGContextSetRGBFillColor(_self->ob_itself,
+ red,
+ green,
+ blue,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetRGBStrokeColor(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float red;
- float green;
- float blue;
- float alpha;
- if (!PyArg_ParseTuple(_args, "ffff",
- &red,
- &green,
- &blue,
- &alpha))
- return NULL;
- CGContextSetRGBStrokeColor(_self->ob_itself,
- red,
- green,
- blue,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float red;
+ float green;
+ float blue;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "ffff",
+ &red,
+ &green,
+ &blue,
+ &alpha))
+ return NULL;
+ CGContextSetRGBStrokeColor(_self->ob_itself,
+ red,
+ green,
+ blue,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetCMYKFillColor(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float cyan;
- float magenta;
- float yellow;
- float black;
- float alpha;
- if (!PyArg_ParseTuple(_args, "fffff",
- &cyan,
- &magenta,
- &yellow,
- &black,
- &alpha))
- return NULL;
- CGContextSetCMYKFillColor(_self->ob_itself,
- cyan,
- magenta,
- yellow,
- black,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float cyan;
+ float magenta;
+ float yellow;
+ float black;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "fffff",
+ &cyan,
+ &magenta,
+ &yellow,
+ &black,
+ &alpha))
+ return NULL;
+ CGContextSetCMYKFillColor(_self->ob_itself,
+ cyan,
+ magenta,
+ yellow,
+ black,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetCMYKStrokeColor(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float cyan;
- float magenta;
- float yellow;
- float black;
- float alpha;
- if (!PyArg_ParseTuple(_args, "fffff",
- &cyan,
- &magenta,
- &yellow,
- &black,
- &alpha))
- return NULL;
- CGContextSetCMYKStrokeColor(_self->ob_itself,
- cyan,
- magenta,
- yellow,
- black,
- alpha);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float cyan;
+ float magenta;
+ float yellow;
+ float black;
+ float alpha;
+ if (!PyArg_ParseTuple(_args, "fffff",
+ &cyan,
+ &magenta,
+ &yellow,
+ &black,
+ &alpha))
+ return NULL;
+ CGContextSetCMYKStrokeColor(_self->ob_itself,
+ cyan,
+ magenta,
+ yellow,
+ black,
+ alpha);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextGetInterpolationQuality(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextGetInterpolationQuality(_self->ob_itself);
- _res = Py_BuildValue("i",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ int _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextGetInterpolationQuality(_self->ob_itself);
+ _res = Py_BuildValue("i",
+ _rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetInterpolationQuality(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int quality;
- if (!PyArg_ParseTuple(_args, "i",
- &quality))
- return NULL;
- CGContextSetInterpolationQuality(_self->ob_itself,
- quality);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ int quality;
+ if (!PyArg_ParseTuple(_args, "i",
+ &quality))
+ return NULL;
+ CGContextSetInterpolationQuality(_self->ob_itself,
+ quality);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetCharacterSpacing(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float spacing;
- if (!PyArg_ParseTuple(_args, "f",
- &spacing))
- return NULL;
- CGContextSetCharacterSpacing(_self->ob_itself,
- spacing);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float spacing;
+ if (!PyArg_ParseTuple(_args, "f",
+ &spacing))
+ return NULL;
+ CGContextSetCharacterSpacing(_self->ob_itself,
+ spacing);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetTextPosition(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float x;
- float y;
- if (!PyArg_ParseTuple(_args, "ff",
- &x,
- &y))
- return NULL;
- CGContextSetTextPosition(_self->ob_itself,
- x,
- y);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float x;
+ float y;
+ if (!PyArg_ParseTuple(_args, "ff",
+ &x,
+ &y))
+ return NULL;
+ CGContextSetTextPosition(_self->ob_itself,
+ x,
+ y);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextGetTextPosition(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGPoint _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextGetTextPosition(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CGPoint_New, &_rv);
- return _res;
+ PyObject *_res = NULL;
+ CGPoint _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextGetTextPosition(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CGPoint_New, &_rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetTextMatrix(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGAffineTransform transform;
- if (!PyArg_ParseTuple(_args, "O&",
- CGAffineTransform_Convert, &transform))
- return NULL;
- CGContextSetTextMatrix(_self->ob_itself,
- transform);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGAffineTransform transform;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CGAffineTransform_Convert, &transform))
+ return NULL;
+ CGContextSetTextMatrix(_self->ob_itself,
+ transform);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextGetTextMatrix(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGAffineTransform _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CGContextGetTextMatrix(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CGAffineTransform_New, &_rv);
- return _res;
+ PyObject *_res = NULL;
+ CGAffineTransform _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CGContextGetTextMatrix(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CGAffineTransform_New, &_rv);
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetTextDrawingMode(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int mode;
- if (!PyArg_ParseTuple(_args, "i",
- &mode))
- return NULL;
- CGContextSetTextDrawingMode(_self->ob_itself,
- mode);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ int mode;
+ if (!PyArg_ParseTuple(_args, "i",
+ &mode))
+ return NULL;
+ CGContextSetTextDrawingMode(_self->ob_itself,
+ mode);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetFontSize(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float size;
- if (!PyArg_ParseTuple(_args, "f",
- &size))
- return NULL;
- CGContextSetFontSize(_self->ob_itself,
- size);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float size;
+ if (!PyArg_ParseTuple(_args, "f",
+ &size))
+ return NULL;
+ CGContextSetFontSize(_self->ob_itself,
+ size);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSelectFont(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char * name;
- float size;
- int textEncoding;
- if (!PyArg_ParseTuple(_args, "sfi",
- &name,
- &size,
- &textEncoding))
- return NULL;
- CGContextSelectFont(_self->ob_itself,
- name,
- size,
- textEncoding);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ char * name;
+ float size;
+ int textEncoding;
+ if (!PyArg_ParseTuple(_args, "sfi",
+ &name,
+ &size,
+ &textEncoding))
+ return NULL;
+ CGContextSelectFont(_self->ob_itself,
+ name,
+ size,
+ textEncoding);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextShowText(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *cstring__in__;
- long cstring__len__;
- int cstring__in_len__;
- if (!PyArg_ParseTuple(_args, "s#",
- &cstring__in__, &cstring__in_len__))
- return NULL;
- cstring__len__ = cstring__in_len__;
- CGContextShowText(_self->ob_itself,
- cstring__in__, cstring__len__);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ char *cstring__in__;
+ long cstring__len__;
+ int cstring__in_len__;
+ if (!PyArg_ParseTuple(_args, "s#",
+ &cstring__in__, &cstring__in_len__))
+ return NULL;
+ cstring__len__ = cstring__in_len__;
+ CGContextShowText(_self->ob_itself,
+ cstring__in__, cstring__len__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextShowTextAtPoint(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- float x;
- float y;
- char *cstring__in__;
- long cstring__len__;
- int cstring__in_len__;
- if (!PyArg_ParseTuple(_args, "ffs#",
- &x,
- &y,
- &cstring__in__, &cstring__in_len__))
- return NULL;
- cstring__len__ = cstring__in_len__;
- CGContextShowTextAtPoint(_self->ob_itself,
- x,
- y,
- cstring__in__, cstring__len__);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ float x;
+ float y;
+ char *cstring__in__;
+ long cstring__len__;
+ int cstring__in_len__;
+ if (!PyArg_ParseTuple(_args, "ffs#",
+ &x,
+ &y,
+ &cstring__in__, &cstring__in_len__))
+ return NULL;
+ cstring__len__ = cstring__in_len__;
+ CGContextShowTextAtPoint(_self->ob_itself,
+ x,
+ y,
+ cstring__in__, cstring__len__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextEndPage(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextEndPage(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextEndPage(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextFlush(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextFlush(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextFlush(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSynchronize(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CGContextSynchronize(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CGContextSynchronize(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_CGContextSetShouldAntialias(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- int shouldAntialias;
- if (!PyArg_ParseTuple(_args, "i",
- &shouldAntialias))
- return NULL;
- CGContextSetShouldAntialias(_self->ob_itself,
- shouldAntialias);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ int shouldAntialias;
+ if (!PyArg_ParseTuple(_args, "i",
+ &shouldAntialias))
+ return NULL;
+ CGContextSetShouldAntialias(_self->ob_itself,
+ shouldAntialias);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#ifndef __LP64__
static PyObject *CGContextRefObj_SyncCGContextOriginWithPort(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr port;
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &port))
- return NULL;
- SyncCGContextOriginWithPort(_self->ob_itself,
- port);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ CGrafPtr port;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &port))
+ return NULL;
+ SyncCGContextOriginWithPort(_self->ob_itself,
+ port);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CGContextRefObj_ClipCGContextToRegion(CGContextRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect portRect;
- RgnHandle region;
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &portRect,
- ResObj_Convert, &region))
- return NULL;
- ClipCGContextToRegion(_self->ob_itself,
- &portRect,
- region);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Rect portRect;
+ RgnHandle region;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &portRect,
+ ResObj_Convert, &region))
+ return NULL;
+ ClipCGContextToRegion(_self->ob_itself,
+ &portRect,
+ region);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#endif
static PyMethodDef CGContextRefObj_methods[] = {
- {"CGContextSaveGState", (PyCFunction)CGContextRefObj_CGContextSaveGState, 1,
- PyDoc_STR("() -> None")},
- {"CGContextRestoreGState", (PyCFunction)CGContextRefObj_CGContextRestoreGState, 1,
- PyDoc_STR("() -> None")},
- {"CGContextScaleCTM", (PyCFunction)CGContextRefObj_CGContextScaleCTM, 1,
- PyDoc_STR("(float sx, float sy) -> None")},
- {"CGContextTranslateCTM", (PyCFunction)CGContextRefObj_CGContextTranslateCTM, 1,
- PyDoc_STR("(float tx, float ty) -> None")},
- {"CGContextRotateCTM", (PyCFunction)CGContextRefObj_CGContextRotateCTM, 1,
- PyDoc_STR("(float angle) -> None")},
- {"CGContextConcatCTM", (PyCFunction)CGContextRefObj_CGContextConcatCTM, 1,
- PyDoc_STR("(CGAffineTransform transform) -> None")},
- {"CGContextGetCTM", (PyCFunction)CGContextRefObj_CGContextGetCTM, 1,
- PyDoc_STR("() -> (CGAffineTransform _rv)")},
- {"CGContextSetLineWidth", (PyCFunction)CGContextRefObj_CGContextSetLineWidth, 1,
- PyDoc_STR("(float width) -> None")},
- {"CGContextSetLineCap", (PyCFunction)CGContextRefObj_CGContextSetLineCap, 1,
- PyDoc_STR("(int cap) -> None")},
- {"CGContextSetLineJoin", (PyCFunction)CGContextRefObj_CGContextSetLineJoin, 1,
- PyDoc_STR("(int join) -> None")},
- {"CGContextSetMiterLimit", (PyCFunction)CGContextRefObj_CGContextSetMiterLimit, 1,
- PyDoc_STR("(float limit) -> None")},
- {"CGContextSetFlatness", (PyCFunction)CGContextRefObj_CGContextSetFlatness, 1,
- PyDoc_STR("(float flatness) -> None")},
- {"CGContextSetAlpha", (PyCFunction)CGContextRefObj_CGContextSetAlpha, 1,
- PyDoc_STR("(float alpha) -> None")},
- {"CGContextBeginPath", (PyCFunction)CGContextRefObj_CGContextBeginPath, 1,
- PyDoc_STR("() -> None")},
- {"CGContextMoveToPoint", (PyCFunction)CGContextRefObj_CGContextMoveToPoint, 1,
- PyDoc_STR("(float x, float y) -> None")},
- {"CGContextAddLineToPoint", (PyCFunction)CGContextRefObj_CGContextAddLineToPoint, 1,
- PyDoc_STR("(float x, float y) -> None")},
- {"CGContextAddCurveToPoint", (PyCFunction)CGContextRefObj_CGContextAddCurveToPoint, 1,
- PyDoc_STR("(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y) -> None")},
- {"CGContextAddQuadCurveToPoint", (PyCFunction)CGContextRefObj_CGContextAddQuadCurveToPoint, 1,
- PyDoc_STR("(float cpx, float cpy, float x, float y) -> None")},
- {"CGContextClosePath", (PyCFunction)CGContextRefObj_CGContextClosePath, 1,
- PyDoc_STR("() -> None")},
- {"CGContextAddRect", (PyCFunction)CGContextRefObj_CGContextAddRect, 1,
- PyDoc_STR("(CGRect rect) -> None")},
- {"CGContextAddArc", (PyCFunction)CGContextRefObj_CGContextAddArc, 1,
- PyDoc_STR("(float x, float y, float radius, float startAngle, float endAngle, int clockwise) -> None")},
- {"CGContextAddArcToPoint", (PyCFunction)CGContextRefObj_CGContextAddArcToPoint, 1,
- PyDoc_STR("(float x1, float y1, float x2, float y2, float radius) -> None")},
- {"CGContextIsPathEmpty", (PyCFunction)CGContextRefObj_CGContextIsPathEmpty, 1,
- PyDoc_STR("() -> (int _rv)")},
- {"CGContextGetPathCurrentPoint", (PyCFunction)CGContextRefObj_CGContextGetPathCurrentPoint, 1,
- PyDoc_STR("() -> (CGPoint _rv)")},
- {"CGContextGetPathBoundingBox", (PyCFunction)CGContextRefObj_CGContextGetPathBoundingBox, 1,
- PyDoc_STR("() -> (CGRect _rv)")},
- {"CGContextDrawPath", (PyCFunction)CGContextRefObj_CGContextDrawPath, 1,
- PyDoc_STR("(int mode) -> None")},
- {"CGContextFillPath", (PyCFunction)CGContextRefObj_CGContextFillPath, 1,
- PyDoc_STR("() -> None")},
- {"CGContextEOFillPath", (PyCFunction)CGContextRefObj_CGContextEOFillPath, 1,
- PyDoc_STR("() -> None")},
- {"CGContextStrokePath", (PyCFunction)CGContextRefObj_CGContextStrokePath, 1,
- PyDoc_STR("() -> None")},
- {"CGContextFillRect", (PyCFunction)CGContextRefObj_CGContextFillRect, 1,
- PyDoc_STR("(CGRect rect) -> None")},
- {"CGContextStrokeRect", (PyCFunction)CGContextRefObj_CGContextStrokeRect, 1,
- PyDoc_STR("(CGRect rect) -> None")},
- {"CGContextStrokeRectWithWidth", (PyCFunction)CGContextRefObj_CGContextStrokeRectWithWidth, 1,
- PyDoc_STR("(CGRect rect, float width) -> None")},
- {"CGContextClearRect", (PyCFunction)CGContextRefObj_CGContextClearRect, 1,
- PyDoc_STR("(CGRect rect) -> None")},
- {"CGContextClip", (PyCFunction)CGContextRefObj_CGContextClip, 1,
- PyDoc_STR("() -> None")},
- {"CGContextEOClip", (PyCFunction)CGContextRefObj_CGContextEOClip, 1,
- PyDoc_STR("() -> None")},
- {"CGContextClipToRect", (PyCFunction)CGContextRefObj_CGContextClipToRect, 1,
- PyDoc_STR("(CGRect rect) -> None")},
- {"CGContextSetGrayFillColor", (PyCFunction)CGContextRefObj_CGContextSetGrayFillColor, 1,
- PyDoc_STR("(float gray, float alpha) -> None")},
- {"CGContextSetGrayStrokeColor", (PyCFunction)CGContextRefObj_CGContextSetGrayStrokeColor, 1,
- PyDoc_STR("(float gray, float alpha) -> None")},
- {"CGContextSetRGBFillColor", (PyCFunction)CGContextRefObj_CGContextSetRGBFillColor, 1,
- PyDoc_STR("(float red, float green, float blue, float alpha) -> None")},
- {"CGContextSetRGBStrokeColor", (PyCFunction)CGContextRefObj_CGContextSetRGBStrokeColor, 1,
- PyDoc_STR("(float red, float green, float blue, float alpha) -> None")},
- {"CGContextSetCMYKFillColor", (PyCFunction)CGContextRefObj_CGContextSetCMYKFillColor, 1,
- PyDoc_STR("(float cyan, float magenta, float yellow, float black, float alpha) -> None")},
- {"CGContextSetCMYKStrokeColor", (PyCFunction)CGContextRefObj_CGContextSetCMYKStrokeColor, 1,
- PyDoc_STR("(float cyan, float magenta, float yellow, float black, float alpha) -> None")},
- {"CGContextGetInterpolationQuality", (PyCFunction)CGContextRefObj_CGContextGetInterpolationQuality, 1,
- PyDoc_STR("() -> (int _rv)")},
- {"CGContextSetInterpolationQuality", (PyCFunction)CGContextRefObj_CGContextSetInterpolationQuality, 1,
- PyDoc_STR("(int quality) -> None")},
- {"CGContextSetCharacterSpacing", (PyCFunction)CGContextRefObj_CGContextSetCharacterSpacing, 1,
- PyDoc_STR("(float spacing) -> None")},
- {"CGContextSetTextPosition", (PyCFunction)CGContextRefObj_CGContextSetTextPosition, 1,
- PyDoc_STR("(float x, float y) -> None")},
- {"CGContextGetTextPosition", (PyCFunction)CGContextRefObj_CGContextGetTextPosition, 1,
- PyDoc_STR("() -> (CGPoint _rv)")},
- {"CGContextSetTextMatrix", (PyCFunction)CGContextRefObj_CGContextSetTextMatrix, 1,
- PyDoc_STR("(CGAffineTransform transform) -> None")},
- {"CGContextGetTextMatrix", (PyCFunction)CGContextRefObj_CGContextGetTextMatrix, 1,
- PyDoc_STR("() -> (CGAffineTransform _rv)")},
- {"CGContextSetTextDrawingMode", (PyCFunction)CGContextRefObj_CGContextSetTextDrawingMode, 1,
- PyDoc_STR("(int mode) -> None")},
- {"CGContextSetFontSize", (PyCFunction)CGContextRefObj_CGContextSetFontSize, 1,
- PyDoc_STR("(float size) -> None")},
- {"CGContextSelectFont", (PyCFunction)CGContextRefObj_CGContextSelectFont, 1,
- PyDoc_STR("(char * name, float size, int textEncoding) -> None")},
- {"CGContextShowText", (PyCFunction)CGContextRefObj_CGContextShowText, 1,
- PyDoc_STR("(Buffer cstring) -> None")},
- {"CGContextShowTextAtPoint", (PyCFunction)CGContextRefObj_CGContextShowTextAtPoint, 1,
- PyDoc_STR("(float x, float y, Buffer cstring) -> None")},
- {"CGContextEndPage", (PyCFunction)CGContextRefObj_CGContextEndPage, 1,
- PyDoc_STR("() -> None")},
- {"CGContextFlush", (PyCFunction)CGContextRefObj_CGContextFlush, 1,
- PyDoc_STR("() -> None")},
- {"CGContextSynchronize", (PyCFunction)CGContextRefObj_CGContextSynchronize, 1,
- PyDoc_STR("() -> None")},
- {"CGContextSetShouldAntialias", (PyCFunction)CGContextRefObj_CGContextSetShouldAntialias, 1,
- PyDoc_STR("(int shouldAntialias) -> None")},
+ {"CGContextSaveGState", (PyCFunction)CGContextRefObj_CGContextSaveGState, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextRestoreGState", (PyCFunction)CGContextRefObj_CGContextRestoreGState, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextScaleCTM", (PyCFunction)CGContextRefObj_CGContextScaleCTM, 1,
+ PyDoc_STR("(float sx, float sy) -> None")},
+ {"CGContextTranslateCTM", (PyCFunction)CGContextRefObj_CGContextTranslateCTM, 1,
+ PyDoc_STR("(float tx, float ty) -> None")},
+ {"CGContextRotateCTM", (PyCFunction)CGContextRefObj_CGContextRotateCTM, 1,
+ PyDoc_STR("(float angle) -> None")},
+ {"CGContextConcatCTM", (PyCFunction)CGContextRefObj_CGContextConcatCTM, 1,
+ PyDoc_STR("(CGAffineTransform transform) -> None")},
+ {"CGContextGetCTM", (PyCFunction)CGContextRefObj_CGContextGetCTM, 1,
+ PyDoc_STR("() -> (CGAffineTransform _rv)")},
+ {"CGContextSetLineWidth", (PyCFunction)CGContextRefObj_CGContextSetLineWidth, 1,
+ PyDoc_STR("(float width) -> None")},
+ {"CGContextSetLineCap", (PyCFunction)CGContextRefObj_CGContextSetLineCap, 1,
+ PyDoc_STR("(int cap) -> None")},
+ {"CGContextSetLineJoin", (PyCFunction)CGContextRefObj_CGContextSetLineJoin, 1,
+ PyDoc_STR("(int join) -> None")},
+ {"CGContextSetMiterLimit", (PyCFunction)CGContextRefObj_CGContextSetMiterLimit, 1,
+ PyDoc_STR("(float limit) -> None")},
+ {"CGContextSetFlatness", (PyCFunction)CGContextRefObj_CGContextSetFlatness, 1,
+ PyDoc_STR("(float flatness) -> None")},
+ {"CGContextSetAlpha", (PyCFunction)CGContextRefObj_CGContextSetAlpha, 1,
+ PyDoc_STR("(float alpha) -> None")},
+ {"CGContextBeginPath", (PyCFunction)CGContextRefObj_CGContextBeginPath, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextMoveToPoint", (PyCFunction)CGContextRefObj_CGContextMoveToPoint, 1,
+ PyDoc_STR("(float x, float y) -> None")},
+ {"CGContextAddLineToPoint", (PyCFunction)CGContextRefObj_CGContextAddLineToPoint, 1,
+ PyDoc_STR("(float x, float y) -> None")},
+ {"CGContextAddCurveToPoint", (PyCFunction)CGContextRefObj_CGContextAddCurveToPoint, 1,
+ PyDoc_STR("(float cp1x, float cp1y, float cp2x, float cp2y, float x, float y) -> None")},
+ {"CGContextAddQuadCurveToPoint", (PyCFunction)CGContextRefObj_CGContextAddQuadCurveToPoint, 1,
+ PyDoc_STR("(float cpx, float cpy, float x, float y) -> None")},
+ {"CGContextClosePath", (PyCFunction)CGContextRefObj_CGContextClosePath, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextAddRect", (PyCFunction)CGContextRefObj_CGContextAddRect, 1,
+ PyDoc_STR("(CGRect rect) -> None")},
+ {"CGContextAddArc", (PyCFunction)CGContextRefObj_CGContextAddArc, 1,
+ PyDoc_STR("(float x, float y, float radius, float startAngle, float endAngle, int clockwise) -> None")},
+ {"CGContextAddArcToPoint", (PyCFunction)CGContextRefObj_CGContextAddArcToPoint, 1,
+ PyDoc_STR("(float x1, float y1, float x2, float y2, float radius) -> None")},
+ {"CGContextIsPathEmpty", (PyCFunction)CGContextRefObj_CGContextIsPathEmpty, 1,
+ PyDoc_STR("() -> (int _rv)")},
+ {"CGContextGetPathCurrentPoint", (PyCFunction)CGContextRefObj_CGContextGetPathCurrentPoint, 1,
+ PyDoc_STR("() -> (CGPoint _rv)")},
+ {"CGContextGetPathBoundingBox", (PyCFunction)CGContextRefObj_CGContextGetPathBoundingBox, 1,
+ PyDoc_STR("() -> (CGRect _rv)")},
+ {"CGContextDrawPath", (PyCFunction)CGContextRefObj_CGContextDrawPath, 1,
+ PyDoc_STR("(int mode) -> None")},
+ {"CGContextFillPath", (PyCFunction)CGContextRefObj_CGContextFillPath, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextEOFillPath", (PyCFunction)CGContextRefObj_CGContextEOFillPath, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextStrokePath", (PyCFunction)CGContextRefObj_CGContextStrokePath, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextFillRect", (PyCFunction)CGContextRefObj_CGContextFillRect, 1,
+ PyDoc_STR("(CGRect rect) -> None")},
+ {"CGContextStrokeRect", (PyCFunction)CGContextRefObj_CGContextStrokeRect, 1,
+ PyDoc_STR("(CGRect rect) -> None")},
+ {"CGContextStrokeRectWithWidth", (PyCFunction)CGContextRefObj_CGContextStrokeRectWithWidth, 1,
+ PyDoc_STR("(CGRect rect, float width) -> None")},
+ {"CGContextClearRect", (PyCFunction)CGContextRefObj_CGContextClearRect, 1,
+ PyDoc_STR("(CGRect rect) -> None")},
+ {"CGContextClip", (PyCFunction)CGContextRefObj_CGContextClip, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextEOClip", (PyCFunction)CGContextRefObj_CGContextEOClip, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextClipToRect", (PyCFunction)CGContextRefObj_CGContextClipToRect, 1,
+ PyDoc_STR("(CGRect rect) -> None")},
+ {"CGContextSetGrayFillColor", (PyCFunction)CGContextRefObj_CGContextSetGrayFillColor, 1,
+ PyDoc_STR("(float gray, float alpha) -> None")},
+ {"CGContextSetGrayStrokeColor", (PyCFunction)CGContextRefObj_CGContextSetGrayStrokeColor, 1,
+ PyDoc_STR("(float gray, float alpha) -> None")},
+ {"CGContextSetRGBFillColor", (PyCFunction)CGContextRefObj_CGContextSetRGBFillColor, 1,
+ PyDoc_STR("(float red, float green, float blue, float alpha) -> None")},
+ {"CGContextSetRGBStrokeColor", (PyCFunction)CGContextRefObj_CGContextSetRGBStrokeColor, 1,
+ PyDoc_STR("(float red, float green, float blue, float alpha) -> None")},
+ {"CGContextSetCMYKFillColor", (PyCFunction)CGContextRefObj_CGContextSetCMYKFillColor, 1,
+ PyDoc_STR("(float cyan, float magenta, float yellow, float black, float alpha) -> None")},
+ {"CGContextSetCMYKStrokeColor", (PyCFunction)CGContextRefObj_CGContextSetCMYKStrokeColor, 1,
+ PyDoc_STR("(float cyan, float magenta, float yellow, float black, float alpha) -> None")},
+ {"CGContextGetInterpolationQuality", (PyCFunction)CGContextRefObj_CGContextGetInterpolationQuality, 1,
+ PyDoc_STR("() -> (int _rv)")},
+ {"CGContextSetInterpolationQuality", (PyCFunction)CGContextRefObj_CGContextSetInterpolationQuality, 1,
+ PyDoc_STR("(int quality) -> None")},
+ {"CGContextSetCharacterSpacing", (PyCFunction)CGContextRefObj_CGContextSetCharacterSpacing, 1,
+ PyDoc_STR("(float spacing) -> None")},
+ {"CGContextSetTextPosition", (PyCFunction)CGContextRefObj_CGContextSetTextPosition, 1,
+ PyDoc_STR("(float x, float y) -> None")},
+ {"CGContextGetTextPosition", (PyCFunction)CGContextRefObj_CGContextGetTextPosition, 1,
+ PyDoc_STR("() -> (CGPoint _rv)")},
+ {"CGContextSetTextMatrix", (PyCFunction)CGContextRefObj_CGContextSetTextMatrix, 1,
+ PyDoc_STR("(CGAffineTransform transform) -> None")},
+ {"CGContextGetTextMatrix", (PyCFunction)CGContextRefObj_CGContextGetTextMatrix, 1,
+ PyDoc_STR("() -> (CGAffineTransform _rv)")},
+ {"CGContextSetTextDrawingMode", (PyCFunction)CGContextRefObj_CGContextSetTextDrawingMode, 1,
+ PyDoc_STR("(int mode) -> None")},
+ {"CGContextSetFontSize", (PyCFunction)CGContextRefObj_CGContextSetFontSize, 1,
+ PyDoc_STR("(float size) -> None")},
+ {"CGContextSelectFont", (PyCFunction)CGContextRefObj_CGContextSelectFont, 1,
+ PyDoc_STR("(char * name, float size, int textEncoding) -> None")},
+ {"CGContextShowText", (PyCFunction)CGContextRefObj_CGContextShowText, 1,
+ PyDoc_STR("(Buffer cstring) -> None")},
+ {"CGContextShowTextAtPoint", (PyCFunction)CGContextRefObj_CGContextShowTextAtPoint, 1,
+ PyDoc_STR("(float x, float y, Buffer cstring) -> None")},
+ {"CGContextEndPage", (PyCFunction)CGContextRefObj_CGContextEndPage, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextFlush", (PyCFunction)CGContextRefObj_CGContextFlush, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextSynchronize", (PyCFunction)CGContextRefObj_CGContextSynchronize, 1,
+ PyDoc_STR("() -> None")},
+ {"CGContextSetShouldAntialias", (PyCFunction)CGContextRefObj_CGContextSetShouldAntialias, 1,
+ PyDoc_STR("(int shouldAntialias) -> None")},
#ifndef __LP64__
- {"SyncCGContextOriginWithPort", (PyCFunction)CGContextRefObj_SyncCGContextOriginWithPort, 1,
- PyDoc_STR("(CGrafPtr port) -> None")},
- {"ClipCGContextToRegion", (PyCFunction)CGContextRefObj_ClipCGContextToRegion, 1,
- PyDoc_STR("(Rect portRect, RgnHandle region) -> None")},
+ {"SyncCGContextOriginWithPort", (PyCFunction)CGContextRefObj_SyncCGContextOriginWithPort, 1,
+ PyDoc_STR("(CGrafPtr port) -> None")},
+ {"ClipCGContextToRegion", (PyCFunction)CGContextRefObj_ClipCGContextToRegion, 1,
+ PyDoc_STR("(Rect portRect, RgnHandle region) -> None")},
#endif
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#define CGContextRefObj_getsetlist NULL
@@ -1198,61 +1198,61 @@ static PyMethodDef CGContextRefObj_methods[] = {
static PyObject *CGContextRefObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- CGContextRef itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ CGContextRef itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CGContextRefObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((CGContextRefObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CGContextRefObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((CGContextRefObject *)_self)->ob_itself = itself;
+ return _self;
}
#define CGContextRefObj_tp_free PyObject_Del
PyTypeObject CGContextRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_CG.CGContextRef", /*tp_name*/
- sizeof(CGContextRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CGContextRefObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CGContextRefObj_compare, /*tp_compare*/
- (reprfunc) CGContextRefObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CGContextRefObj_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*/
- CGContextRefObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CGContextRefObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CGContextRefObj_tp_init, /* tp_init */
- CGContextRefObj_tp_alloc, /* tp_alloc */
- CGContextRefObj_tp_new, /* tp_new */
- CGContextRefObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_CG.CGContextRef", /*tp_name*/
+ sizeof(CGContextRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CGContextRefObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CGContextRefObj_compare, /*tp_compare*/
+ (reprfunc) CGContextRefObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CGContextRefObj_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*/
+ CGContextRefObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CGContextRefObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CGContextRefObj_tp_init, /* tp_init */
+ CGContextRefObj_tp_alloc, /* tp_alloc */
+ CGContextRefObj_tp_new, /* tp_new */
+ CGContextRefObj_tp_free, /* tp_free */
};
/* ------------------ End object type CGContextRef ------------------ */
@@ -1261,29 +1261,29 @@ PyTypeObject CGContextRef_Type = {
#ifndef __LP64__
static PyObject *CG_CreateCGContextForPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GrafPtr port;
- CGContextRef ctx;
- OSStatus _err;
+ PyObject *_res = NULL;
+ GrafPtr port;
+ CGContextRef ctx;
+ OSStatus _err;
- if (!PyArg_ParseTuple(_args, "O&", GrafObj_Convert, &port))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "O&", GrafObj_Convert, &port))
+ return NULL;
- _err = CreateCGContextForPort(port, &ctx);
- if (_err != noErr)
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&", CGContextRefObj_New, ctx);
- return _res;
+ _err = CreateCGContextForPort(port, &ctx);
+ if (_err != noErr)
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&", CGContextRefObj_New, ctx);
+ return _res;
}
#endif
static PyMethodDef CG_methods[] = {
#ifndef __LP64__
- {"CreateCGContextForPort", (PyCFunction)CG_CreateCGContextForPort, 1,
- PyDoc_STR("(CGrafPtr) -> CGContextRef")},
+ {"CreateCGContextForPort", (PyCFunction)CG_CreateCGContextForPort, 1,
+ PyDoc_STR("(CGrafPtr) -> CGContextRef")},
#endif
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -1291,25 +1291,25 @@ static PyMethodDef CG_methods[] = {
void init_CG(void)
{
- PyObject *m;
- PyObject *d;
+ PyObject *m;
+ PyObject *d;
- m = Py_InitModule("_CG", CG_methods);
- d = PyModule_GetDict(m);
- CG_Error = PyMac_GetOSErrException();
- if (CG_Error == NULL ||
- PyDict_SetItemString(d, "Error", CG_Error) != 0)
- return;
- CGContextRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&CGContextRef_Type) < 0) return;
- Py_INCREF(&CGContextRef_Type);
- PyModule_AddObject(m, "CGContextRef", (PyObject *)&CGContextRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&CGContextRef_Type);
- PyModule_AddObject(m, "CGContextRefType", (PyObject *)&CGContextRef_Type);
+ m = Py_InitModule("_CG", CG_methods);
+ d = PyModule_GetDict(m);
+ CG_Error = PyMac_GetOSErrException();
+ if (CG_Error == NULL ||
+ PyDict_SetItemString(d, "Error", CG_Error) != 0)
+ return;
+ CGContextRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&CGContextRef_Type) < 0) return;
+ Py_INCREF(&CGContextRef_Type);
+ PyModule_AddObject(m, "CGContextRef", (PyObject *)&CGContextRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&CGContextRef_Type);
+ PyModule_AddObject(m, "CGContextRefType", (PyObject *)&CGContextRef_Type);
}
/* ========================= End module _CG ========================= */
diff --git a/Mac/Modules/cm/_Cmmodule.c b/Mac/Modules/cm/_Cmmodule.c
index 03a25dd..f07f121 100644
--- a/Mac/Modules/cm/_Cmmodule.c
+++ b/Mac/Modules/cm/_Cmmodule.c
@@ -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)
@@ -36,21 +36,21 @@ static PyObject *
CmpDesc_New(ComponentDescription *itself)
{
- return Py_BuildValue("O&O&O&ll",
- PyMac_BuildOSType, itself->componentType,
- PyMac_BuildOSType, itself->componentSubType,
- PyMac_BuildOSType, itself->componentManufacturer,
- itself->componentFlags, itself->componentFlagsMask);
+ return Py_BuildValue("O&O&O&ll",
+ PyMac_BuildOSType, itself->componentType,
+ PyMac_BuildOSType, itself->componentSubType,
+ PyMac_BuildOSType, itself->componentManufacturer,
+ itself->componentFlags, itself->componentFlagsMask);
}
static int
CmpDesc_Convert(PyObject *v, ComponentDescription *p_itself)
{
- return PyArg_ParseTuple(v, "O&O&O&ll",
- PyMac_GetOSType, &p_itself->componentType,
- PyMac_GetOSType, &p_itself->componentSubType,
- PyMac_GetOSType, &p_itself->componentManufacturer,
- &p_itself->componentFlags, &p_itself->componentFlagsMask);
+ return PyArg_ParseTuple(v, "O&O&O&ll",
+ PyMac_GetOSType, &p_itself->componentType,
+ PyMac_GetOSType, &p_itself->componentSubType,
+ PyMac_GetOSType, &p_itself->componentManufacturer,
+ &p_itself->componentFlags, &p_itself->componentFlagsMask);
}
@@ -63,194 +63,194 @@ PyTypeObject ComponentInstance_Type;
#define CmpInstObj_Check(x) ((x)->ob_type == &ComponentInstance_Type || PyObject_TypeCheck((x), &ComponentInstance_Type))
typedef struct ComponentInstanceObject {
- PyObject_HEAD
- ComponentInstance ob_itself;
+ PyObject_HEAD
+ ComponentInstance ob_itself;
} ComponentInstanceObject;
PyObject *CmpInstObj_New(ComponentInstance itself)
{
- ComponentInstanceObject *it;
- if (itself == NULL) {
- PyErr_SetString(Cm_Error,"NULL ComponentInstance");
- return NULL;
- }
- it = PyObject_NEW(ComponentInstanceObject, &ComponentInstance_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ ComponentInstanceObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Cm_Error,"NULL ComponentInstance");
+ return NULL;
+ }
+ it = PyObject_NEW(ComponentInstanceObject, &ComponentInstance_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int CmpInstObj_Convert(PyObject *v, ComponentInstance *p_itself)
{
- if (!CmpInstObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "ComponentInstance required");
- return 0;
- }
- *p_itself = ((ComponentInstanceObject *)v)->ob_itself;
- return 1;
+ if (!CmpInstObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "ComponentInstance required");
+ return 0;
+ }
+ *p_itself = ((ComponentInstanceObject *)v)->ob_itself;
+ return 1;
}
static void CmpInstObj_dealloc(ComponentInstanceObject *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 *CmpInstObj_CloseComponent(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef CloseComponent
- PyMac_PRECHECK(CloseComponent);
+ PyMac_PRECHECK(CloseComponent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CloseComponent(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CloseComponent(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpInstObj_GetComponentInstanceError(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef GetComponentInstanceError
- PyMac_PRECHECK(GetComponentInstanceError);
+ PyMac_PRECHECK(GetComponentInstanceError);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetComponentInstanceError(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetComponentInstanceError(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpInstObj_SetComponentInstanceError(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr theError;
+ PyObject *_res = NULL;
+ OSErr theError;
#ifndef SetComponentInstanceError
- PyMac_PRECHECK(SetComponentInstanceError);
+ PyMac_PRECHECK(SetComponentInstanceError);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &theError))
- return NULL;
- SetComponentInstanceError(_self->ob_itself,
- theError);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &theError))
+ return NULL;
+ SetComponentInstanceError(_self->ob_itself,
+ theError);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpInstObj_GetComponentInstanceStorage(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef GetComponentInstanceStorage
- PyMac_PRECHECK(GetComponentInstanceStorage);
+ PyMac_PRECHECK(GetComponentInstanceStorage);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetComponentInstanceStorage(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetComponentInstanceStorage(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *CmpInstObj_SetComponentInstanceStorage(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle theStorage;
+ PyObject *_res = NULL;
+ Handle theStorage;
#ifndef SetComponentInstanceStorage
- PyMac_PRECHECK(SetComponentInstanceStorage);
+ PyMac_PRECHECK(SetComponentInstanceStorage);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theStorage))
- return NULL;
- SetComponentInstanceStorage(_self->ob_itself,
- theStorage);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theStorage))
+ return NULL;
+ SetComponentInstanceStorage(_self->ob_itself,
+ theStorage);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#ifndef __LP64__
static PyObject *CmpInstObj_ComponentFunctionImplemented(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- short ftnNumber;
+ PyObject *_res = NULL;
+ long _rv;
+ short ftnNumber;
#ifndef ComponentFunctionImplemented
- PyMac_PRECHECK(ComponentFunctionImplemented);
+ PyMac_PRECHECK(ComponentFunctionImplemented);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &ftnNumber))
- return NULL;
- _rv = ComponentFunctionImplemented(_self->ob_itself,
- ftnNumber);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &ftnNumber))
+ return NULL;
+ _rv = ComponentFunctionImplemented(_self->ob_itself,
+ ftnNumber);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CmpInstObj_GetComponentVersion(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetComponentVersion
- PyMac_PRECHECK(GetComponentVersion);
+ PyMac_PRECHECK(GetComponentVersion);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetComponentVersion(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetComponentVersion(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CmpInstObj_ComponentSetTarget(ComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- ComponentInstance target;
+ PyObject *_res = NULL;
+ long _rv;
+ ComponentInstance target;
#ifndef ComponentSetTarget
- PyMac_PRECHECK(ComponentSetTarget);
+ PyMac_PRECHECK(ComponentSetTarget);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &target))
- return NULL;
- _rv = ComponentSetTarget(_self->ob_itself,
- target);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &target))
+ return NULL;
+ _rv = ComponentSetTarget(_self->ob_itself,
+ target);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
#endif /* !__LP64__*/
static PyMethodDef CmpInstObj_methods[] = {
- {"CloseComponent", (PyCFunction)CmpInstObj_CloseComponent, 1,
- PyDoc_STR("() -> None")},
- {"GetComponentInstanceError", (PyCFunction)CmpInstObj_GetComponentInstanceError, 1,
- PyDoc_STR("() -> None")},
- {"SetComponentInstanceError", (PyCFunction)CmpInstObj_SetComponentInstanceError, 1,
- PyDoc_STR("(OSErr theError) -> None")},
- {"GetComponentInstanceStorage", (PyCFunction)CmpInstObj_GetComponentInstanceStorage, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"SetComponentInstanceStorage", (PyCFunction)CmpInstObj_SetComponentInstanceStorage, 1,
- PyDoc_STR("(Handle theStorage) -> None")},
+ {"CloseComponent", (PyCFunction)CmpInstObj_CloseComponent, 1,
+ PyDoc_STR("() -> None")},
+ {"GetComponentInstanceError", (PyCFunction)CmpInstObj_GetComponentInstanceError, 1,
+ PyDoc_STR("() -> None")},
+ {"SetComponentInstanceError", (PyCFunction)CmpInstObj_SetComponentInstanceError, 1,
+ PyDoc_STR("(OSErr theError) -> None")},
+ {"GetComponentInstanceStorage", (PyCFunction)CmpInstObj_GetComponentInstanceStorage, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"SetComponentInstanceStorage", (PyCFunction)CmpInstObj_SetComponentInstanceStorage, 1,
+ PyDoc_STR("(Handle theStorage) -> None")},
#ifndef __LP64__
- {"ComponentFunctionImplemented", (PyCFunction)CmpInstObj_ComponentFunctionImplemented, 1,
- PyDoc_STR("(short ftnNumber) -> (long _rv)")},
- {"GetComponentVersion", (PyCFunction)CmpInstObj_GetComponentVersion, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"ComponentSetTarget", (PyCFunction)CmpInstObj_ComponentSetTarget, 1,
- PyDoc_STR("(ComponentInstance target) -> (long _rv)")},
+ {"ComponentFunctionImplemented", (PyCFunction)CmpInstObj_ComponentFunctionImplemented, 1,
+ PyDoc_STR("(short ftnNumber) -> (long _rv)")},
+ {"GetComponentVersion", (PyCFunction)CmpInstObj_GetComponentVersion, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"ComponentSetTarget", (PyCFunction)CmpInstObj_ComponentSetTarget, 1,
+ PyDoc_STR("(ComponentInstance target) -> (long _rv)")},
#endif /* !__LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#define CmpInstObj_getsetlist NULL
@@ -267,61 +267,61 @@ static PyMethodDef CmpInstObj_methods[] = {
static PyObject *CmpInstObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- ComponentInstance itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ ComponentInstance itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CmpInstObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((ComponentInstanceObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CmpInstObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((ComponentInstanceObject *)_self)->ob_itself = itself;
+ return _self;
}
#define CmpInstObj_tp_free PyObject_Del
PyTypeObject ComponentInstance_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Cm.ComponentInstance", /*tp_name*/
- sizeof(ComponentInstanceObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CmpInstObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CmpInstObj_compare, /*tp_compare*/
- (reprfunc) CmpInstObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CmpInstObj_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*/
- CmpInstObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CmpInstObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CmpInstObj_tp_init, /* tp_init */
- CmpInstObj_tp_alloc, /* tp_alloc */
- CmpInstObj_tp_new, /* tp_new */
- CmpInstObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Cm.ComponentInstance", /*tp_name*/
+ sizeof(ComponentInstanceObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CmpInstObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CmpInstObj_compare, /*tp_compare*/
+ (reprfunc) CmpInstObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CmpInstObj_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*/
+ CmpInstObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CmpInstObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CmpInstObj_tp_init, /* tp_init */
+ CmpInstObj_tp_alloc, /* tp_alloc */
+ CmpInstObj_tp_new, /* tp_new */
+ CmpInstObj_tp_free, /* tp_free */
};
/* --------------- End object type ComponentInstance ---------------- */
@@ -334,361 +334,361 @@ PyTypeObject Component_Type;
#define CmpObj_Check(x) ((x)->ob_type == &Component_Type || PyObject_TypeCheck((x), &Component_Type))
typedef struct ComponentObject {
- PyObject_HEAD
- Component ob_itself;
+ PyObject_HEAD
+ Component ob_itself;
} ComponentObject;
PyObject *CmpObj_New(Component itself)
{
- ComponentObject *it;
- if (itself == NULL) {
- /* XXXX Or should we return None? */
- PyErr_SetString(Cm_Error,"No such component");
- return NULL;
- }
- it = PyObject_NEW(ComponentObject, &Component_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ ComponentObject *it;
+ if (itself == NULL) {
+ /* XXXX Or should we return None? */
+ PyErr_SetString(Cm_Error,"No such component");
+ return NULL;
+ }
+ it = PyObject_NEW(ComponentObject, &Component_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int CmpObj_Convert(PyObject *v, Component *p_itself)
{
- if ( v == Py_None ) {
- *p_itself = 0;
- return 1;
- }
- if (!CmpObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Component required");
- return 0;
- }
- *p_itself = ((ComponentObject *)v)->ob_itself;
- return 1;
+ if ( v == Py_None ) {
+ *p_itself = 0;
+ return 1;
+ }
+ if (!CmpObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Component required");
+ return 0;
+ }
+ *p_itself = ((ComponentObject *)v)->ob_itself;
+ return 1;
}
static void CmpObj_dealloc(ComponentObject *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 *CmpObj_UnregisterComponent(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef UnregisterComponent
- PyMac_PRECHECK(UnregisterComponent);
+ PyMac_PRECHECK(UnregisterComponent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UnregisterComponent(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = UnregisterComponent(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpObj_GetComponentInfo(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ComponentDescription cd;
- Handle componentName;
- Handle componentInfo;
- Handle componentIcon;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ComponentDescription cd;
+ Handle componentName;
+ Handle componentInfo;
+ Handle componentIcon;
#ifndef GetComponentInfo
- PyMac_PRECHECK(GetComponentInfo);
+ PyMac_PRECHECK(GetComponentInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &componentName,
- ResObj_Convert, &componentInfo,
- ResObj_Convert, &componentIcon))
- return NULL;
- _err = GetComponentInfo(_self->ob_itself,
- &cd,
- componentName,
- componentInfo,
- componentIcon);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpDesc_New, &cd);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &componentName,
+ ResObj_Convert, &componentInfo,
+ ResObj_Convert, &componentIcon))
+ return NULL;
+ _err = GetComponentInfo(_self->ob_itself,
+ &cd,
+ componentName,
+ componentInfo,
+ componentIcon);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpDesc_New, &cd);
+ return _res;
}
static PyObject *CmpObj_OpenComponent(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentInstance _rv;
+ PyObject *_res = NULL;
+ ComponentInstance _rv;
#ifndef OpenComponent
- PyMac_PRECHECK(OpenComponent);
+ PyMac_PRECHECK(OpenComponent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = OpenComponent(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = OpenComponent(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *CmpObj_ResolveComponentAlias(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component _rv;
+ PyObject *_res = NULL;
+ Component _rv;
#ifndef ResolveComponentAlias
- PyMac_PRECHECK(ResolveComponentAlias);
+ PyMac_PRECHECK(ResolveComponentAlias);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = ResolveComponentAlias(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CmpObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = ResolveComponentAlias(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, _rv);
+ return _res;
}
static PyObject *CmpObj_GetComponentPublicIndString(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str255 theString;
- short strListID;
- short index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str255 theString;
+ short strListID;
+ short index;
#ifndef GetComponentPublicIndString
- PyMac_PRECHECK(GetComponentPublicIndString);
+ PyMac_PRECHECK(GetComponentPublicIndString);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetStr255, theString,
- &strListID,
- &index))
- return NULL;
- _err = GetComponentPublicIndString(_self->ob_itself,
- theString,
- strListID,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetStr255, theString,
+ &strListID,
+ &index))
+ return NULL;
+ _err = GetComponentPublicIndString(_self->ob_itself,
+ theString,
+ strListID,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpObj_GetComponentRefcon(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetComponentRefcon
- PyMac_PRECHECK(GetComponentRefcon);
+ PyMac_PRECHECK(GetComponentRefcon);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetComponentRefcon(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetComponentRefcon(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CmpObj_SetComponentRefcon(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long theRefcon;
+ PyObject *_res = NULL;
+ long theRefcon;
#ifndef SetComponentRefcon
- PyMac_PRECHECK(SetComponentRefcon);
+ PyMac_PRECHECK(SetComponentRefcon);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &theRefcon))
- return NULL;
- SetComponentRefcon(_self->ob_itself,
- theRefcon);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &theRefcon))
+ return NULL;
+ SetComponentRefcon(_self->ob_itself,
+ theRefcon);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpObj_OpenComponentResFile(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef OpenComponentResFile
- PyMac_PRECHECK(OpenComponentResFile);
+ PyMac_PRECHECK(OpenComponentResFile);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = OpenComponentResFile(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = OpenComponentResFile(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CmpObj_GetComponentResource(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType resType;
- short resID;
- Handle theResource;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType resType;
+ short resID;
+ Handle theResource;
#ifndef GetComponentResource
- PyMac_PRECHECK(GetComponentResource);
+ PyMac_PRECHECK(GetComponentResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetOSType, &resType,
- &resID))
- return NULL;
- _err = GetComponentResource(_self->ob_itself,
- resType,
- resID,
- &theResource);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theResource);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetOSType, &resType,
+ &resID))
+ return NULL;
+ _err = GetComponentResource(_self->ob_itself,
+ resType,
+ resID,
+ &theResource);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theResource);
+ return _res;
}
static PyObject *CmpObj_GetComponentIndString(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str255 theString;
- short strListID;
- short index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str255 theString;
+ short strListID;
+ short index;
#ifndef GetComponentIndString
- PyMac_PRECHECK(GetComponentIndString);
+ PyMac_PRECHECK(GetComponentIndString);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetStr255, theString,
- &strListID,
- &index))
- return NULL;
- _err = GetComponentIndString(_self->ob_itself,
- theString,
- strListID,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetStr255, theString,
+ &strListID,
+ &index))
+ return NULL;
+ _err = GetComponentIndString(_self->ob_itself,
+ theString,
+ strListID,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpObj_CountComponentInstances(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef CountComponentInstances
- PyMac_PRECHECK(CountComponentInstances);
+ PyMac_PRECHECK(CountComponentInstances);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CountComponentInstances(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CountComponentInstances(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CmpObj_SetDefaultComponent(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short flags;
#ifndef SetDefaultComponent
- PyMac_PRECHECK(SetDefaultComponent);
+ PyMac_PRECHECK(SetDefaultComponent);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &flags))
- return NULL;
- _err = SetDefaultComponent(_self->ob_itself,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &flags))
+ return NULL;
+ _err = SetDefaultComponent(_self->ob_itself,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CmpObj_CaptureComponent(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component _rv;
- Component capturingComponent;
+ PyObject *_res = NULL;
+ Component _rv;
+ Component capturingComponent;
#ifndef CaptureComponent
- PyMac_PRECHECK(CaptureComponent);
+ PyMac_PRECHECK(CaptureComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpObj_Convert, &capturingComponent))
- return NULL;
- _rv = CaptureComponent(_self->ob_itself,
- capturingComponent);
- _res = Py_BuildValue("O&",
- CmpObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpObj_Convert, &capturingComponent))
+ return NULL;
+ _rv = CaptureComponent(_self->ob_itself,
+ capturingComponent);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, _rv);
+ return _res;
}
static PyObject *CmpObj_UncaptureComponent(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef UncaptureComponent
- PyMac_PRECHECK(UncaptureComponent);
+ PyMac_PRECHECK(UncaptureComponent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UncaptureComponent(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = UncaptureComponent(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#ifndef __LP64__
static PyObject *CmpObj_GetComponentIconSuite(ComponentObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle iconSuite;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle iconSuite;
#ifndef GetComponentIconSuite
- PyMac_PRECHECK(GetComponentIconSuite);
+ PyMac_PRECHECK(GetComponentIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetComponentIconSuite(_self->ob_itself,
- &iconSuite);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, iconSuite);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetComponentIconSuite(_self->ob_itself,
+ &iconSuite);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, iconSuite);
+ return _res;
}
#endif /* !__LP64__ */
static PyMethodDef CmpObj_methods[] = {
- {"UnregisterComponent", (PyCFunction)CmpObj_UnregisterComponent, 1,
- PyDoc_STR("() -> None")},
- {"GetComponentInfo", (PyCFunction)CmpObj_GetComponentInfo, 1,
- PyDoc_STR("(Handle componentName, Handle componentInfo, Handle componentIcon) -> (ComponentDescription cd)")},
- {"OpenComponent", (PyCFunction)CmpObj_OpenComponent, 1,
- PyDoc_STR("() -> (ComponentInstance _rv)")},
- {"ResolveComponentAlias", (PyCFunction)CmpObj_ResolveComponentAlias, 1,
- PyDoc_STR("() -> (Component _rv)")},
- {"GetComponentPublicIndString", (PyCFunction)CmpObj_GetComponentPublicIndString, 1,
- PyDoc_STR("(Str255 theString, short strListID, short index) -> None")},
- {"GetComponentRefcon", (PyCFunction)CmpObj_GetComponentRefcon, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SetComponentRefcon", (PyCFunction)CmpObj_SetComponentRefcon, 1,
- PyDoc_STR("(long theRefcon) -> None")},
- {"OpenComponentResFile", (PyCFunction)CmpObj_OpenComponentResFile, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetComponentResource", (PyCFunction)CmpObj_GetComponentResource, 1,
- PyDoc_STR("(OSType resType, short resID) -> (Handle theResource)")},
- {"GetComponentIndString", (PyCFunction)CmpObj_GetComponentIndString, 1,
- PyDoc_STR("(Str255 theString, short strListID, short index) -> None")},
- {"CountComponentInstances", (PyCFunction)CmpObj_CountComponentInstances, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SetDefaultComponent", (PyCFunction)CmpObj_SetDefaultComponent, 1,
- PyDoc_STR("(short flags) -> None")},
- {"CaptureComponent", (PyCFunction)CmpObj_CaptureComponent, 1,
- PyDoc_STR("(Component capturingComponent) -> (Component _rv)")},
- {"UncaptureComponent", (PyCFunction)CmpObj_UncaptureComponent, 1,
- PyDoc_STR("() -> None")},
+ {"UnregisterComponent", (PyCFunction)CmpObj_UnregisterComponent, 1,
+ PyDoc_STR("() -> None")},
+ {"GetComponentInfo", (PyCFunction)CmpObj_GetComponentInfo, 1,
+ PyDoc_STR("(Handle componentName, Handle componentInfo, Handle componentIcon) -> (ComponentDescription cd)")},
+ {"OpenComponent", (PyCFunction)CmpObj_OpenComponent, 1,
+ PyDoc_STR("() -> (ComponentInstance _rv)")},
+ {"ResolveComponentAlias", (PyCFunction)CmpObj_ResolveComponentAlias, 1,
+ PyDoc_STR("() -> (Component _rv)")},
+ {"GetComponentPublicIndString", (PyCFunction)CmpObj_GetComponentPublicIndString, 1,
+ PyDoc_STR("(Str255 theString, short strListID, short index) -> None")},
+ {"GetComponentRefcon", (PyCFunction)CmpObj_GetComponentRefcon, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SetComponentRefcon", (PyCFunction)CmpObj_SetComponentRefcon, 1,
+ PyDoc_STR("(long theRefcon) -> None")},
+ {"OpenComponentResFile", (PyCFunction)CmpObj_OpenComponentResFile, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetComponentResource", (PyCFunction)CmpObj_GetComponentResource, 1,
+ PyDoc_STR("(OSType resType, short resID) -> (Handle theResource)")},
+ {"GetComponentIndString", (PyCFunction)CmpObj_GetComponentIndString, 1,
+ PyDoc_STR("(Str255 theString, short strListID, short index) -> None")},
+ {"CountComponentInstances", (PyCFunction)CmpObj_CountComponentInstances, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SetDefaultComponent", (PyCFunction)CmpObj_SetDefaultComponent, 1,
+ PyDoc_STR("(short flags) -> None")},
+ {"CaptureComponent", (PyCFunction)CmpObj_CaptureComponent, 1,
+ PyDoc_STR("(Component capturingComponent) -> (Component _rv)")},
+ {"UncaptureComponent", (PyCFunction)CmpObj_UncaptureComponent, 1,
+ PyDoc_STR("() -> None")},
#ifndef __LP64__
- {"GetComponentIconSuite", (PyCFunction)CmpObj_GetComponentIconSuite, 1,
- PyDoc_STR("() -> (Handle iconSuite)")},
+ {"GetComponentIconSuite", (PyCFunction)CmpObj_GetComponentIconSuite, 1,
+ PyDoc_STR("() -> (Handle iconSuite)")},
#endif /* !__LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#define CmpObj_getsetlist NULL
@@ -705,61 +705,61 @@ static PyMethodDef CmpObj_methods[] = {
static PyObject *CmpObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- Component itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ Component itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CmpObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((ComponentObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CmpObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((ComponentObject *)_self)->ob_itself = itself;
+ return _self;
}
#define CmpObj_tp_free PyObject_Del
PyTypeObject Component_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Cm.Component", /*tp_name*/
- sizeof(ComponentObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CmpObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CmpObj_compare, /*tp_compare*/
- (reprfunc) CmpObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CmpObj_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*/
- CmpObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CmpObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CmpObj_tp_init, /* tp_init */
- CmpObj_tp_alloc, /* tp_alloc */
- CmpObj_tp_new, /* tp_new */
- CmpObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Cm.Component", /*tp_name*/
+ sizeof(ComponentObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CmpObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CmpObj_compare, /*tp_compare*/
+ (reprfunc) CmpObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CmpObj_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*/
+ CmpObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CmpObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CmpObj_tp_init, /* tp_init */
+ CmpObj_tp_alloc, /* tp_alloc */
+ CmpObj_tp_new, /* tp_new */
+ CmpObj_tp_free, /* tp_free */
};
/* ------------------- End object type Component -------------------- */
@@ -767,150 +767,150 @@ PyTypeObject Component_Type = {
static PyObject *Cm_RegisterComponentResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component _rv;
- ComponentResourceHandle cr;
- short global;
+ PyObject *_res = NULL;
+ Component _rv;
+ ComponentResourceHandle cr;
+ short global;
#ifndef RegisterComponentResource
- PyMac_PRECHECK(RegisterComponentResource);
+ PyMac_PRECHECK(RegisterComponentResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- ResObj_Convert, &cr,
- &global))
- return NULL;
- _rv = RegisterComponentResource(cr,
- global);
- _res = Py_BuildValue("O&",
- CmpObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ ResObj_Convert, &cr,
+ &global))
+ return NULL;
+ _rv = RegisterComponentResource(cr,
+ global);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, _rv);
+ return _res;
}
static PyObject *Cm_FindNextComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component _rv;
- Component aComponent;
- ComponentDescription looking;
+ PyObject *_res = NULL;
+ Component _rv;
+ Component aComponent;
+ ComponentDescription looking;
#ifndef FindNextComponent
- PyMac_PRECHECK(FindNextComponent);
+ PyMac_PRECHECK(FindNextComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpObj_Convert, &aComponent,
- CmpDesc_Convert, &looking))
- return NULL;
- _rv = FindNextComponent(aComponent,
- &looking);
- _res = Py_BuildValue("O&",
- CmpObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpObj_Convert, &aComponent,
+ CmpDesc_Convert, &looking))
+ return NULL;
+ _rv = FindNextComponent(aComponent,
+ &looking);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, _rv);
+ return _res;
}
static PyObject *Cm_CountComponents(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- ComponentDescription looking;
+ PyObject *_res = NULL;
+ long _rv;
+ ComponentDescription looking;
#ifndef CountComponents
- PyMac_PRECHECK(CountComponents);
+ PyMac_PRECHECK(CountComponents);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpDesc_Convert, &looking))
- return NULL;
- _rv = CountComponents(&looking);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpDesc_Convert, &looking))
+ return NULL;
+ _rv = CountComponents(&looking);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Cm_GetComponentListModSeed(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetComponentListModSeed
- PyMac_PRECHECK(GetComponentListModSeed);
+ PyMac_PRECHECK(GetComponentListModSeed);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetComponentListModSeed();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetComponentListModSeed();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Cm_CloseComponentResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refnum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refnum;
#ifndef CloseComponentResFile
- PyMac_PRECHECK(CloseComponentResFile);
+ PyMac_PRECHECK(CloseComponentResFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &refnum))
- return NULL;
- _err = CloseComponentResFile(refnum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refnum))
+ return NULL;
+ _err = CloseComponentResFile(refnum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Cm_OpenDefaultComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentInstance _rv;
- OSType componentType;
- OSType componentSubType;
+ PyObject *_res = NULL;
+ ComponentInstance _rv;
+ OSType componentType;
+ OSType componentSubType;
#ifndef OpenDefaultComponent
- PyMac_PRECHECK(OpenDefaultComponent);
+ PyMac_PRECHECK(OpenDefaultComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &componentType,
- PyMac_GetOSType, &componentSubType))
- return NULL;
- _rv = OpenDefaultComponent(componentType,
- componentSubType);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &componentType,
+ PyMac_GetOSType, &componentSubType))
+ return NULL;
+ _rv = OpenDefaultComponent(componentType,
+ componentSubType);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *Cm_RegisterComponentResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- short resRefNum;
- short global;
+ PyObject *_res = NULL;
+ long _rv;
+ short resRefNum;
+ short global;
#ifndef RegisterComponentResourceFile
- PyMac_PRECHECK(RegisterComponentResourceFile);
+ PyMac_PRECHECK(RegisterComponentResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &resRefNum,
- &global))
- return NULL;
- _rv = RegisterComponentResourceFile(resRefNum,
- global);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &resRefNum,
+ &global))
+ return NULL;
+ _rv = RegisterComponentResourceFile(resRefNum,
+ global);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyMethodDef Cm_methods[] = {
- {"RegisterComponentResource", (PyCFunction)Cm_RegisterComponentResource, 1,
- PyDoc_STR("(ComponentResourceHandle cr, short global) -> (Component _rv)")},
- {"FindNextComponent", (PyCFunction)Cm_FindNextComponent, 1,
- PyDoc_STR("(Component aComponent, ComponentDescription looking) -> (Component _rv)")},
- {"CountComponents", (PyCFunction)Cm_CountComponents, 1,
- PyDoc_STR("(ComponentDescription looking) -> (long _rv)")},
- {"GetComponentListModSeed", (PyCFunction)Cm_GetComponentListModSeed, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"CloseComponentResFile", (PyCFunction)Cm_CloseComponentResFile, 1,
- PyDoc_STR("(short refnum) -> None")},
- {"OpenDefaultComponent", (PyCFunction)Cm_OpenDefaultComponent, 1,
- PyDoc_STR("(OSType componentType, OSType componentSubType) -> (ComponentInstance _rv)")},
- {"RegisterComponentResourceFile", (PyCFunction)Cm_RegisterComponentResourceFile, 1,
- PyDoc_STR("(short resRefNum, short global) -> (long _rv)")},
- {NULL, NULL, 0}
+ {"RegisterComponentResource", (PyCFunction)Cm_RegisterComponentResource, 1,
+ PyDoc_STR("(ComponentResourceHandle cr, short global) -> (Component _rv)")},
+ {"FindNextComponent", (PyCFunction)Cm_FindNextComponent, 1,
+ PyDoc_STR("(Component aComponent, ComponentDescription looking) -> (Component _rv)")},
+ {"CountComponents", (PyCFunction)Cm_CountComponents, 1,
+ PyDoc_STR("(ComponentDescription looking) -> (long _rv)")},
+ {"GetComponentListModSeed", (PyCFunction)Cm_GetComponentListModSeed, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"CloseComponentResFile", (PyCFunction)Cm_CloseComponentResFile, 1,
+ PyDoc_STR("(short refnum) -> None")},
+ {"OpenDefaultComponent", (PyCFunction)Cm_OpenDefaultComponent, 1,
+ PyDoc_STR("(OSType componentType, OSType componentSubType) -> (ComponentInstance _rv)")},
+ {"RegisterComponentResourceFile", (PyCFunction)Cm_RegisterComponentResourceFile, 1,
+ PyDoc_STR("(short resRefNum, short global) -> (long _rv)")},
+ {NULL, NULL, 0}
};
@@ -918,37 +918,37 @@ static PyMethodDef Cm_methods[] = {
void init_Cm(void)
{
- PyObject *m;
- PyObject *d;
-
-
-
- PyMac_INIT_TOOLBOX_OBJECT_NEW(Component, CmpObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Component, CmpObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, CmpInstObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, CmpInstObj_Convert);
-
-
- m = Py_InitModule("_Cm", Cm_methods);
- d = PyModule_GetDict(m);
- Cm_Error = PyMac_GetOSErrException();
- if (Cm_Error == NULL ||
- PyDict_SetItemString(d, "Error", Cm_Error) != 0)
- return;
- ComponentInstance_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&ComponentInstance_Type) < 0) return;
- Py_INCREF(&ComponentInstance_Type);
- PyModule_AddObject(m, "ComponentInstance", (PyObject *)&ComponentInstance_Type);
- /* Backward-compatible name */
- Py_INCREF(&ComponentInstance_Type);
- PyModule_AddObject(m, "ComponentInstanceType", (PyObject *)&ComponentInstance_Type);
- Component_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Component_Type) < 0) return;
- Py_INCREF(&Component_Type);
- PyModule_AddObject(m, "Component", (PyObject *)&Component_Type);
- /* Backward-compatible name */
- Py_INCREF(&Component_Type);
- PyModule_AddObject(m, "ComponentType", (PyObject *)&Component_Type);
+ PyObject *m;
+ PyObject *d;
+
+
+
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(Component, CmpObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Component, CmpObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, CmpInstObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, CmpInstObj_Convert);
+
+
+ m = Py_InitModule("_Cm", Cm_methods);
+ d = PyModule_GetDict(m);
+ Cm_Error = PyMac_GetOSErrException();
+ if (Cm_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Cm_Error) != 0)
+ return;
+ ComponentInstance_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&ComponentInstance_Type) < 0) return;
+ Py_INCREF(&ComponentInstance_Type);
+ PyModule_AddObject(m, "ComponentInstance", (PyObject *)&ComponentInstance_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&ComponentInstance_Type);
+ PyModule_AddObject(m, "ComponentInstanceType", (PyObject *)&ComponentInstance_Type);
+ Component_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Component_Type) < 0) return;
+ Py_INCREF(&Component_Type);
+ PyModule_AddObject(m, "Component", (PyObject *)&Component_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Component_Type);
+ PyModule_AddObject(m, "ComponentType", (PyObject *)&Component_Type);
}
/* ========================= End module _Cm ========================= */
diff --git a/Mac/Modules/ctl/_Ctlmodule.c b/Mac/Modules/ctl/_Ctlmodule.c
index cdb8557..a959eb4 100644
--- a/Mac/Modules/ctl/_Ctlmodule.c
+++ b/Mac/Modules/ctl/_Ctlmodule.c
@@ -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)
@@ -41,19 +41,19 @@ static PyObject *
ControlFontStyle_New(ControlFontStyleRec *itself)
{
- return Py_BuildValue("hhhhhhO&O&", itself->flags, itself->font,
- itself->size, itself->style, itself->mode, itself->just,
- QdRGB_New, &itself->foreColor, QdRGB_New, &itself->backColor);
+ return Py_BuildValue("hhhhhhO&O&", itself->flags, itself->font,
+ itself->size, itself->style, itself->mode, itself->just,
+ QdRGB_New, &itself->foreColor, QdRGB_New, &itself->backColor);
}
#endif
static int
ControlFontStyle_Convert(PyObject *v, ControlFontStyleRec *itself)
{
- return PyArg_Parse(v, "(hhhhhhO&O&)", &itself->flags,
- &itself->font, &itself->size, &itself->style, &itself->mode,
- &itself->just, QdRGB_Convert, &itself->foreColor,
- QdRGB_Convert, &itself->backColor);
+ return PyArg_Parse(v, "(hhhhhhO&O&)", &itself->flags,
+ &itself->font, &itself->size, &itself->style, &itself->mode,
+ &itself->just, QdRGB_Convert, &itself->foreColor,
+ QdRGB_Convert, &itself->backColor);
}
/*
@@ -63,13 +63,13 @@ static PyObject *
PyControlID_New(ControlID *itself)
{
- return Py_BuildValue("O&l", PyMac_BuildOSType, itself->signature, itself->id);
+ return Py_BuildValue("O&l", PyMac_BuildOSType, itself->signature, itself->id);
}
static int
PyControlID_Convert(PyObject *v, ControlID *itself)
{
- return PyArg_Parse(v, "(O&l)", PyMac_GetOSType, &itself->signature, &itself->id);
+ return PyArg_Parse(v, "(O&l)", PyMac_GetOSType, &itself->signature, &itself->id);
}
/*
@@ -78,40 +78,40 @@ PyControlID_Convert(PyObject *v, ControlID *itself)
static int
DataBrowserTableViewColumnDesc_Convert(PyObject *v, DataBrowserTableViewColumnDesc *itself)
{
- return PyArg_Parse(v, "(lO&l)",
- &itself->propertyID,
- PyMac_GetOSType, &itself->propertyType,
- &itself->propertyFlags);
+ return PyArg_Parse(v, "(lO&l)",
+ &itself->propertyID,
+ PyMac_GetOSType, &itself->propertyType,
+ &itself->propertyFlags);
}
static int
ControlButtonContentInfo_Convert(PyObject *v, ControlButtonContentInfo *itself)
{
- return PyArg_Parse(v, "(hO&)",
- &itself->contentType,
- OptResObj_Convert, &itself->u.iconSuite);
+ return PyArg_Parse(v, "(hO&)",
+ &itself->contentType,
+ OptResObj_Convert, &itself->u.iconSuite);
}
static int
DataBrowserListViewHeaderDesc_Convert(PyObject *v, DataBrowserListViewHeaderDesc *itself)
{
- itself->version = kDataBrowserListViewLatestHeaderDesc;
- return PyArg_Parse(v, "(HHhO&HO&O&)",
- &itself->minimumWidth,
- &itself->maximumWidth,
- &itself->titleOffset,
- CFStringRefObj_Convert, &itself->titleString,
- &itself->initialOrder,
- ControlFontStyle_Convert, &itself->btnFontStyle,
- ControlButtonContentInfo_Convert, &itself->btnContentInfo);
+ itself->version = kDataBrowserListViewLatestHeaderDesc;
+ return PyArg_Parse(v, "(HHhO&HO&O&)",
+ &itself->minimumWidth,
+ &itself->maximumWidth,
+ &itself->titleOffset,
+ CFStringRefObj_Convert, &itself->titleString,
+ &itself->initialOrder,
+ ControlFontStyle_Convert, &itself->btnFontStyle,
+ ControlButtonContentInfo_Convert, &itself->btnContentInfo);
}
static int
DataBrowserListViewColumnDesc_Convert(PyObject *v, DataBrowserListViewColumnDesc *itself)
{
- return PyArg_Parse(v, "(O&O&)",
- DataBrowserTableViewColumnDesc_Convert, &itself->propertyDesc,
- DataBrowserListViewHeaderDesc_Convert, &itself->headerBtnDesc);
+ return PyArg_Parse(v, "(O&O&)",
+ DataBrowserTableViewColumnDesc_Convert, &itself->propertyDesc,
+ DataBrowserListViewHeaderDesc_Convert, &itself->headerBtnDesc);
}
/* TrackControl and HandleControlClick callback support */
@@ -139,3683 +139,3683 @@ PyTypeObject Control_Type;
#define CtlObj_Check(x) ((x)->ob_type == &Control_Type || PyObject_TypeCheck((x), &Control_Type))
typedef struct ControlObject {
- PyObject_HEAD
- ControlHandle ob_itself;
- PyObject *ob_callbackdict;
+ PyObject_HEAD
+ ControlHandle ob_itself;
+ PyObject *ob_callbackdict;
} ControlObject;
PyObject *CtlObj_New(ControlHandle itself)
{
- ControlObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(ControlObject, &Control_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- SetControlReference(itself, (long)it);
- it->ob_callbackdict = NULL;
- return (PyObject *)it;
+ ControlObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(ControlObject, &Control_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ SetControlReference(itself, (long)it);
+ it->ob_callbackdict = NULL;
+ return (PyObject *)it;
}
int CtlObj_Convert(PyObject *v, ControlHandle *p_itself)
{
- if (!CtlObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Control required");
- return 0;
- }
- *p_itself = ((ControlObject *)v)->ob_itself;
- return 1;
+ if (!CtlObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Control required");
+ return 0;
+ }
+ *p_itself = ((ControlObject *)v)->ob_itself;
+ return 1;
}
static void CtlObj_dealloc(ControlObject *self)
{
- Py_XDECREF(self->ob_callbackdict);
- if (self->ob_itself)SetControlReference(self->ob_itself, (long)0); /* Make it forget about us */
- self->ob_type->tp_free((PyObject *)self);
+ Py_XDECREF(self->ob_callbackdict);
+ if (self->ob_itself)SetControlReference(self->ob_itself, (long)0); /* Make it forget about us */
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *CtlObj_HiliteControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlPartCode hiliteState;
+ PyObject *_res = NULL;
+ ControlPartCode hiliteState;
#ifndef HiliteControl
- PyMac_PRECHECK(HiliteControl);
+ PyMac_PRECHECK(HiliteControl);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &hiliteState))
- return NULL;
- HiliteControl(_self->ob_itself,
- hiliteState);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &hiliteState))
+ return NULL;
+ HiliteControl(_self->ob_itself,
+ hiliteState);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_ShowControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ShowControl
- PyMac_PRECHECK(ShowControl);
+ PyMac_PRECHECK(ShowControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ShowControl(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ShowControl(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_HideControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef HideControl
- PyMac_PRECHECK(HideControl);
+ PyMac_PRECHECK(HideControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- HideControl(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ HideControl(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_IsControlActive(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsControlActive
- PyMac_PRECHECK(IsControlActive);
+ PyMac_PRECHECK(IsControlActive);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsControlActive(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsControlActive(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_IsControlVisible(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsControlVisible
- PyMac_PRECHECK(IsControlVisible);
+ PyMac_PRECHECK(IsControlVisible);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsControlVisible(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsControlVisible(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_ActivateControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef ActivateControl
- PyMac_PRECHECK(ActivateControl);
+ PyMac_PRECHECK(ActivateControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = ActivateControl(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = ActivateControl(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_DeactivateControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef DeactivateControl
- PyMac_PRECHECK(DeactivateControl);
+ PyMac_PRECHECK(DeactivateControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = DeactivateControl(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = DeactivateControl(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetControlVisibility(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Boolean inIsVisible;
- Boolean inDoDraw;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Boolean inIsVisible;
+ Boolean inDoDraw;
#ifndef SetControlVisibility
- PyMac_PRECHECK(SetControlVisibility);
+ PyMac_PRECHECK(SetControlVisibility);
#endif
- if (!PyArg_ParseTuple(_args, "bb",
- &inIsVisible,
- &inDoDraw))
- return NULL;
- _err = SetControlVisibility(_self->ob_itself,
- inIsVisible,
- inDoDraw);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "bb",
+ &inIsVisible,
+ &inDoDraw))
+ return NULL;
+ _err = SetControlVisibility(_self->ob_itself,
+ inIsVisible,
+ inDoDraw);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_IsControlEnabled(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsControlEnabled
- PyMac_PRECHECK(IsControlEnabled);
+ PyMac_PRECHECK(IsControlEnabled);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsControlEnabled(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsControlEnabled(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_EnableControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef EnableControl
- PyMac_PRECHECK(EnableControl);
+ PyMac_PRECHECK(EnableControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = EnableControl(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = EnableControl(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_DisableControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef DisableControl
- PyMac_PRECHECK(DisableControl);
+ PyMac_PRECHECK(DisableControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = DisableControl(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = DisableControl(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_Draw1Control(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef Draw1Control
- PyMac_PRECHECK(Draw1Control);
+ PyMac_PRECHECK(Draw1Control);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- Draw1Control(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ Draw1Control(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetBestControlRect(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect outRect;
- SInt16 outBaseLineOffset;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect outRect;
+ SInt16 outBaseLineOffset;
#ifndef GetBestControlRect
- PyMac_PRECHECK(GetBestControlRect);
+ PyMac_PRECHECK(GetBestControlRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetBestControlRect(_self->ob_itself,
- &outRect,
- &outBaseLineOffset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- PyMac_BuildRect, &outRect,
- outBaseLineOffset);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetBestControlRect(_self->ob_itself,
+ &outRect,
+ &outBaseLineOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ PyMac_BuildRect, &outRect,
+ outBaseLineOffset);
+ return _res;
}
static PyObject *CtlObj_SetControlFontStyle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlFontStyleRec inStyle;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlFontStyleRec inStyle;
#ifndef SetControlFontStyle
- PyMac_PRECHECK(SetControlFontStyle);
+ PyMac_PRECHECK(SetControlFontStyle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ControlFontStyle_Convert, &inStyle))
- return NULL;
- _err = SetControlFontStyle(_self->ob_itself,
- &inStyle);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ControlFontStyle_Convert, &inStyle))
+ return NULL;
+ _err = SetControlFontStyle(_self->ob_itself,
+ &inStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_DrawControlInCurrentPort(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DrawControlInCurrentPort
- PyMac_PRECHECK(DrawControlInCurrentPort);
+ PyMac_PRECHECK(DrawControlInCurrentPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DrawControlInCurrentPort(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DrawControlInCurrentPort(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetUpControlBackground(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inDepth;
- Boolean inIsColorDevice;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inDepth;
+ Boolean inIsColorDevice;
#ifndef SetUpControlBackground
- PyMac_PRECHECK(SetUpControlBackground);
+ PyMac_PRECHECK(SetUpControlBackground);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &inDepth,
- &inIsColorDevice))
- return NULL;
- _err = SetUpControlBackground(_self->ob_itself,
- inDepth,
- inIsColorDevice);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &inDepth,
+ &inIsColorDevice))
+ return NULL;
+ _err = SetUpControlBackground(_self->ob_itself,
+ inDepth,
+ inIsColorDevice);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetUpControlTextColor(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inDepth;
- Boolean inIsColorDevice;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inDepth;
+ Boolean inIsColorDevice;
#ifndef SetUpControlTextColor
- PyMac_PRECHECK(SetUpControlTextColor);
+ PyMac_PRECHECK(SetUpControlTextColor);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &inDepth,
- &inIsColorDevice))
- return NULL;
- _err = SetUpControlTextColor(_self->ob_itself,
- inDepth,
- inIsColorDevice);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &inDepth,
+ &inIsColorDevice))
+ return NULL;
+ _err = SetUpControlTextColor(_self->ob_itself,
+ inDepth,
+ inIsColorDevice);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_DragControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point startPoint;
- Rect limitRect;
- Rect slopRect;
- DragConstraint axis;
+ PyObject *_res = NULL;
+ Point startPoint;
+ Rect limitRect;
+ Rect slopRect;
+ DragConstraint axis;
#ifndef DragControl
- PyMac_PRECHECK(DragControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&H",
- PyMac_GetPoint, &startPoint,
- PyMac_GetRect, &limitRect,
- PyMac_GetRect, &slopRect,
- &axis))
- return NULL;
- DragControl(_self->ob_itself,
- startPoint,
- &limitRect,
- &slopRect,
- axis);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DragControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&H",
+ PyMac_GetPoint, &startPoint,
+ PyMac_GetRect, &limitRect,
+ PyMac_GetRect, &slopRect,
+ &axis))
+ return NULL;
+ DragControl(_self->ob_itself,
+ startPoint,
+ &limitRect,
+ &slopRect,
+ axis);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_TestControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlPartCode _rv;
- Point testPoint;
+ PyObject *_res = NULL;
+ ControlPartCode _rv;
+ Point testPoint;
#ifndef TestControl
- PyMac_PRECHECK(TestControl);
+ PyMac_PRECHECK(TestControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &testPoint))
- return NULL;
- _rv = TestControl(_self->ob_itself,
- testPoint);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &testPoint))
+ return NULL;
+ _rv = TestControl(_self->ob_itself,
+ testPoint);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_HandleControlContextualMenuClick(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point inWhere;
- Boolean menuDisplayed;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point inWhere;
+ Boolean menuDisplayed;
#ifndef HandleControlContextualMenuClick
- PyMac_PRECHECK(HandleControlContextualMenuClick);
+ PyMac_PRECHECK(HandleControlContextualMenuClick);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &inWhere))
- return NULL;
- _err = HandleControlContextualMenuClick(_self->ob_itself,
- inWhere,
- &menuDisplayed);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- menuDisplayed);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &inWhere))
+ return NULL;
+ _err = HandleControlContextualMenuClick(_self->ob_itself,
+ inWhere,
+ &menuDisplayed);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ menuDisplayed);
+ return _res;
}
static PyObject *CtlObj_GetControlClickActivation(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point inWhere;
- EventModifiers inModifiers;
- ClickActivationResult outResult;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point inWhere;
+ EventModifiers inModifiers;
+ ClickActivationResult outResult;
#ifndef GetControlClickActivation
- PyMac_PRECHECK(GetControlClickActivation);
-#endif
- if (!PyArg_ParseTuple(_args, "O&H",
- PyMac_GetPoint, &inWhere,
- &inModifiers))
- return NULL;
- _err = GetControlClickActivation(_self->ob_itself,
- inWhere,
- inModifiers,
- &outResult);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outResult);
- return _res;
+ PyMac_PRECHECK(GetControlClickActivation);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&H",
+ PyMac_GetPoint, &inWhere,
+ &inModifiers))
+ return NULL;
+ _err = GetControlClickActivation(_self->ob_itself,
+ inWhere,
+ inModifiers,
+ &outResult);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outResult);
+ return _res;
}
static PyObject *CtlObj_HandleControlKey(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlPartCode _rv;
- SInt16 inKeyCode;
- SInt16 inCharCode;
- EventModifiers inModifiers;
+ PyObject *_res = NULL;
+ ControlPartCode _rv;
+ SInt16 inKeyCode;
+ SInt16 inCharCode;
+ EventModifiers inModifiers;
#ifndef HandleControlKey
- PyMac_PRECHECK(HandleControlKey);
-#endif
- if (!PyArg_ParseTuple(_args, "hhH",
- &inKeyCode,
- &inCharCode,
- &inModifiers))
- return NULL;
- _rv = HandleControlKey(_self->ob_itself,
- inKeyCode,
- inCharCode,
- inModifiers);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ PyMac_PRECHECK(HandleControlKey);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhH",
+ &inKeyCode,
+ &inCharCode,
+ &inModifiers))
+ return NULL;
+ _rv = HandleControlKey(_self->ob_itself,
+ inKeyCode,
+ inCharCode,
+ inModifiers);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_HandleControlSetCursor(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point localPoint;
- EventModifiers modifiers;
- Boolean cursorWasSet;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point localPoint;
+ EventModifiers modifiers;
+ Boolean cursorWasSet;
#ifndef HandleControlSetCursor
- PyMac_PRECHECK(HandleControlSetCursor);
-#endif
- if (!PyArg_ParseTuple(_args, "O&H",
- PyMac_GetPoint, &localPoint,
- &modifiers))
- return NULL;
- _err = HandleControlSetCursor(_self->ob_itself,
- localPoint,
- modifiers,
- &cursorWasSet);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- cursorWasSet);
- return _res;
+ PyMac_PRECHECK(HandleControlSetCursor);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&H",
+ PyMac_GetPoint, &localPoint,
+ &modifiers))
+ return NULL;
+ _err = HandleControlSetCursor(_self->ob_itself,
+ localPoint,
+ modifiers,
+ &cursorWasSet);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ cursorWasSet);
+ return _res;
}
static PyObject *CtlObj_MoveControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 h;
- SInt16 v;
+ PyObject *_res = NULL;
+ SInt16 h;
+ SInt16 v;
#ifndef MoveControl
- PyMac_PRECHECK(MoveControl);
+ PyMac_PRECHECK(MoveControl);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- MoveControl(_self->ob_itself,
- h,
- v);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ MoveControl(_self->ob_itself,
+ h,
+ v);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SizeControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 w;
- SInt16 h;
+ PyObject *_res = NULL;
+ SInt16 w;
+ SInt16 h;
#ifndef SizeControl
- PyMac_PRECHECK(SizeControl);
+ PyMac_PRECHECK(SizeControl);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &w,
- &h))
- return NULL;
- SizeControl(_self->ob_itself,
- w,
- h);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &w,
+ &h))
+ return NULL;
+ SizeControl(_self->ob_itself,
+ w,
+ h);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetControlTitle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 title;
+ PyObject *_res = NULL;
+ Str255 title;
#ifndef SetControlTitle
- PyMac_PRECHECK(SetControlTitle);
+ PyMac_PRECHECK(SetControlTitle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, title))
- return NULL;
- SetControlTitle(_self->ob_itself,
- title);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, title))
+ return NULL;
+ SetControlTitle(_self->ob_itself,
+ title);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlTitle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 title;
+ PyObject *_res = NULL;
+ Str255 title;
#ifndef GetControlTitle
- PyMac_PRECHECK(GetControlTitle);
+ PyMac_PRECHECK(GetControlTitle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetControlTitle(_self->ob_itself,
- title);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, title);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetControlTitle(_self->ob_itself,
+ title);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, title);
+ return _res;
}
static PyObject *CtlObj_SetControlTitleWithCFString(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
#ifndef SetControlTitleWithCFString
- PyMac_PRECHECK(SetControlTitleWithCFString);
+ PyMac_PRECHECK(SetControlTitleWithCFString);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &inString))
- return NULL;
- _err = SetControlTitleWithCFString(_self->ob_itself,
- inString);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &inString))
+ return NULL;
+ _err = SetControlTitleWithCFString(_self->ob_itself,
+ inString);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_CopyControlTitleAsCFString(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef outString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef outString;
#ifndef CopyControlTitleAsCFString
- PyMac_PRECHECK(CopyControlTitleAsCFString);
+ PyMac_PRECHECK(CopyControlTitleAsCFString);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CopyControlTitleAsCFString(_self->ob_itself,
- &outString);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, outString);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CopyControlTitleAsCFString(_self->ob_itself,
+ &outString);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, outString);
+ return _res;
}
static PyObject *CtlObj_GetControlValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetControlValue
- PyMac_PRECHECK(GetControlValue);
+ PyMac_PRECHECK(GetControlValue);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlValue(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlValue(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 newValue;
+ PyObject *_res = NULL;
+ SInt16 newValue;
#ifndef SetControlValue
- PyMac_PRECHECK(SetControlValue);
+ PyMac_PRECHECK(SetControlValue);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &newValue))
- return NULL;
- SetControlValue(_self->ob_itself,
- newValue);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &newValue))
+ return NULL;
+ SetControlValue(_self->ob_itself,
+ newValue);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlMinimum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetControlMinimum
- PyMac_PRECHECK(GetControlMinimum);
+ PyMac_PRECHECK(GetControlMinimum);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlMinimum(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlMinimum(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlMinimum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 newMinimum;
+ PyObject *_res = NULL;
+ SInt16 newMinimum;
#ifndef SetControlMinimum
- PyMac_PRECHECK(SetControlMinimum);
+ PyMac_PRECHECK(SetControlMinimum);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &newMinimum))
- return NULL;
- SetControlMinimum(_self->ob_itself,
- newMinimum);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &newMinimum))
+ return NULL;
+ SetControlMinimum(_self->ob_itself,
+ newMinimum);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlMaximum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetControlMaximum
- PyMac_PRECHECK(GetControlMaximum);
+ PyMac_PRECHECK(GetControlMaximum);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlMaximum(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlMaximum(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlMaximum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 newMaximum;
+ PyObject *_res = NULL;
+ SInt16 newMaximum;
#ifndef SetControlMaximum
- PyMac_PRECHECK(SetControlMaximum);
+ PyMac_PRECHECK(SetControlMaximum);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &newMaximum))
- return NULL;
- SetControlMaximum(_self->ob_itself,
- newMaximum);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &newMaximum))
+ return NULL;
+ SetControlMaximum(_self->ob_itself,
+ newMaximum);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlViewSize(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef GetControlViewSize
- PyMac_PRECHECK(GetControlViewSize);
+ PyMac_PRECHECK(GetControlViewSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlViewSize(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlViewSize(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlViewSize(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 newViewSize;
+ PyObject *_res = NULL;
+ SInt32 newViewSize;
#ifndef SetControlViewSize
- PyMac_PRECHECK(SetControlViewSize);
+ PyMac_PRECHECK(SetControlViewSize);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newViewSize))
- return NULL;
- SetControlViewSize(_self->ob_itself,
- newViewSize);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newViewSize))
+ return NULL;
+ SetControlViewSize(_self->ob_itself,
+ newViewSize);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControl32BitValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef GetControl32BitValue
- PyMac_PRECHECK(GetControl32BitValue);
+ PyMac_PRECHECK(GetControl32BitValue);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControl32BitValue(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControl32BitValue(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControl32BitValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 newValue;
+ PyObject *_res = NULL;
+ SInt32 newValue;
#ifndef SetControl32BitValue
- PyMac_PRECHECK(SetControl32BitValue);
+ PyMac_PRECHECK(SetControl32BitValue);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newValue))
- return NULL;
- SetControl32BitValue(_self->ob_itself,
- newValue);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newValue))
+ return NULL;
+ SetControl32BitValue(_self->ob_itself,
+ newValue);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControl32BitMaximum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef GetControl32BitMaximum
- PyMac_PRECHECK(GetControl32BitMaximum);
+ PyMac_PRECHECK(GetControl32BitMaximum);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControl32BitMaximum(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControl32BitMaximum(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControl32BitMaximum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 newMaximum;
+ PyObject *_res = NULL;
+ SInt32 newMaximum;
#ifndef SetControl32BitMaximum
- PyMac_PRECHECK(SetControl32BitMaximum);
+ PyMac_PRECHECK(SetControl32BitMaximum);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newMaximum))
- return NULL;
- SetControl32BitMaximum(_self->ob_itself,
- newMaximum);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newMaximum))
+ return NULL;
+ SetControl32BitMaximum(_self->ob_itself,
+ newMaximum);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControl32BitMinimum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef GetControl32BitMinimum
- PyMac_PRECHECK(GetControl32BitMinimum);
+ PyMac_PRECHECK(GetControl32BitMinimum);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControl32BitMinimum(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControl32BitMinimum(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControl32BitMinimum(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 newMinimum;
+ PyObject *_res = NULL;
+ SInt32 newMinimum;
#ifndef SetControl32BitMinimum
- PyMac_PRECHECK(SetControl32BitMinimum);
+ PyMac_PRECHECK(SetControl32BitMinimum);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newMinimum))
- return NULL;
- SetControl32BitMinimum(_self->ob_itself,
- newMinimum);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newMinimum))
+ return NULL;
+ SetControl32BitMinimum(_self->ob_itself,
+ newMinimum);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_IsValidControlHandle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsValidControlHandle
- PyMac_PRECHECK(IsValidControlHandle);
+ PyMac_PRECHECK(IsValidControlHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsValidControlHandle(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsValidControlHandle(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ControlID inID;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ControlID inID;
#ifndef SetControlID
- PyMac_PRECHECK(SetControlID);
+ PyMac_PRECHECK(SetControlID);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyControlID_Convert, &inID))
- return NULL;
- _err = SetControlID(_self->ob_itself,
- &inID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyControlID_Convert, &inID))
+ return NULL;
+ _err = SetControlID(_self->ob_itself,
+ &inID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ControlID outID;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ControlID outID;
#ifndef GetControlID
- PyMac_PRECHECK(GetControlID);
+ PyMac_PRECHECK(GetControlID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetControlID(_self->ob_itself,
- &outID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyControlID_New, &outID);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetControlID(_self->ob_itself,
+ &outID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyControlID_New, &outID);
+ return _res;
}
static PyObject *CtlObj_SetControlCommandID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 inCommandID;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 inCommandID;
#ifndef SetControlCommandID
- PyMac_PRECHECK(SetControlCommandID);
+ PyMac_PRECHECK(SetControlCommandID);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCommandID))
- return NULL;
- _err = SetControlCommandID(_self->ob_itself,
- inCommandID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCommandID))
+ return NULL;
+ _err = SetControlCommandID(_self->ob_itself,
+ inCommandID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlCommandID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 outCommandID;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 outCommandID;
#ifndef GetControlCommandID
- PyMac_PRECHECK(GetControlCommandID);
+ PyMac_PRECHECK(GetControlCommandID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetControlCommandID(_self->ob_itself,
- &outCommandID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outCommandID);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetControlCommandID(_self->ob_itself,
+ &outCommandID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outCommandID);
+ return _res;
}
static PyObject *CtlObj_RemoveControlProperty(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyCreator;
- OSType propertyTag;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyCreator;
+ OSType propertyTag;
#ifndef RemoveControlProperty
- PyMac_PRECHECK(RemoveControlProperty);
+ PyMac_PRECHECK(RemoveControlProperty);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag))
- return NULL;
- _err = RemoveControlProperty(_self->ob_itself,
- propertyCreator,
- propertyTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag))
+ return NULL;
+ _err = RemoveControlProperty(_self->ob_itself,
+ propertyCreator,
+ propertyTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlPropertyAttributes(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyCreator;
- OSType propertyTag;
- UInt32 attributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyCreator;
+ OSType propertyTag;
+ UInt32 attributes;
#ifndef GetControlPropertyAttributes
- PyMac_PRECHECK(GetControlPropertyAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag))
- return NULL;
- _err = GetControlPropertyAttributes(_self->ob_itself,
- propertyCreator,
- propertyTag,
- &attributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- attributes);
- return _res;
+ PyMac_PRECHECK(GetControlPropertyAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag))
+ return NULL;
+ _err = GetControlPropertyAttributes(_self->ob_itself,
+ propertyCreator,
+ propertyTag,
+ &attributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ attributes);
+ return _res;
}
static PyObject *CtlObj_ChangeControlPropertyAttributes(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyCreator;
- OSType propertyTag;
- UInt32 attributesToSet;
- UInt32 attributesToClear;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyCreator;
+ OSType propertyTag;
+ UInt32 attributesToSet;
+ UInt32 attributesToClear;
#ifndef ChangeControlPropertyAttributes
- PyMac_PRECHECK(ChangeControlPropertyAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&ll",
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag,
- &attributesToSet,
- &attributesToClear))
- return NULL;
- _err = ChangeControlPropertyAttributes(_self->ob_itself,
- propertyCreator,
- propertyTag,
- attributesToSet,
- attributesToClear);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ChangeControlPropertyAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&ll",
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag,
+ &attributesToSet,
+ &attributesToClear))
+ return NULL;
+ _err = ChangeControlPropertyAttributes(_self->ob_itself,
+ propertyCreator,
+ propertyTag,
+ attributesToSet,
+ attributesToClear);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlRegion(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ControlPartCode inPart;
- RgnHandle outRegion;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ControlPartCode inPart;
+ RgnHandle outRegion;
#ifndef GetControlRegion
- PyMac_PRECHECK(GetControlRegion);
+ PyMac_PRECHECK(GetControlRegion);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &inPart,
- ResObj_Convert, &outRegion))
- return NULL;
- _err = GetControlRegion(_self->ob_itself,
- inPart,
- outRegion);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inPart,
+ ResObj_Convert, &outRegion))
+ return NULL;
+ _err = GetControlRegion(_self->ob_itself,
+ inPart,
+ outRegion);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlVariant(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlVariant _rv;
+ PyObject *_res = NULL;
+ ControlVariant _rv;
#ifndef GetControlVariant
- PyMac_PRECHECK(GetControlVariant);
+ PyMac_PRECHECK(GetControlVariant);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlVariant(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlVariant(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlAction(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PyObject* actionProc;
- UniversalProcPtr c_callback;
+ PyObject *_res = NULL;
+ PyObject* actionProc;
+ UniversalProcPtr c_callback;
#ifndef SetControlAction
- PyMac_PRECHECK(SetControlAction);
+ PyMac_PRECHECK(SetControlAction);
#endif
- if (!PyArg_ParseTuple(_args, "O",
- &actionProc))
- return NULL;
- SetControlAction(_self->ob_itself,
- myactionproc_upp);
- Py_INCREF(Py_None);
- _res = Py_None;
- setcallback((PyObject*)_self, kMyControlActionProcTag, actionProc, &c_callback);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O",
+ &actionProc))
+ return NULL;
+ SetControlAction(_self->ob_itself,
+ myactionproc_upp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ setcallback((PyObject*)_self, kMyControlActionProcTag, actionProc, &c_callback);
+ return _res;
}
static PyObject *CtlObj_SetControlReference(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 data;
+ PyObject *_res = NULL;
+ SInt32 data;
#ifndef SetControlReference
- PyMac_PRECHECK(SetControlReference);
+ PyMac_PRECHECK(SetControlReference);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &data))
- return NULL;
- SetControlReference(_self->ob_itself,
- data);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &data))
+ return NULL;
+ SetControlReference(_self->ob_itself,
+ data);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlReference(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef GetControlReference
- PyMac_PRECHECK(GetControlReference);
+ PyMac_PRECHECK(GetControlReference);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlReference(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlReference(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_EmbedControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlHandle inContainer;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlHandle inContainer;
#ifndef EmbedControl
- PyMac_PRECHECK(EmbedControl);
+ PyMac_PRECHECK(EmbedControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CtlObj_Convert, &inContainer))
- return NULL;
- _err = EmbedControl(_self->ob_itself,
- inContainer);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CtlObj_Convert, &inContainer))
+ return NULL;
+ _err = EmbedControl(_self->ob_itself,
+ inContainer);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_AutoEmbedControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
#ifndef AutoEmbedControl
- PyMac_PRECHECK(AutoEmbedControl);
+ PyMac_PRECHECK(AutoEmbedControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = AutoEmbedControl(_self->ob_itself,
- inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = AutoEmbedControl(_self->ob_itself,
+ inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetSuperControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlHandle outParent;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlHandle outParent;
#ifndef GetSuperControl
- PyMac_PRECHECK(GetSuperControl);
+ PyMac_PRECHECK(GetSuperControl);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetSuperControl(_self->ob_itself,
- &outParent);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_WhichControl, outParent);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetSuperControl(_self->ob_itself,
+ &outParent);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_WhichControl, outParent);
+ return _res;
}
static PyObject *CtlObj_CountSubControls(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UInt16 outNumChildren;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UInt16 outNumChildren;
#ifndef CountSubControls
- PyMac_PRECHECK(CountSubControls);
+ PyMac_PRECHECK(CountSubControls);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CountSubControls(_self->ob_itself,
- &outNumChildren);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outNumChildren);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CountSubControls(_self->ob_itself,
+ &outNumChildren);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outNumChildren);
+ return _res;
}
static PyObject *CtlObj_GetIndexedSubControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UInt16 inIndex;
- ControlHandle outSubControl;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UInt16 inIndex;
+ ControlHandle outSubControl;
#ifndef GetIndexedSubControl
- PyMac_PRECHECK(GetIndexedSubControl);
+ PyMac_PRECHECK(GetIndexedSubControl);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &inIndex))
- return NULL;
- _err = GetIndexedSubControl(_self->ob_itself,
- inIndex,
- &outSubControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_WhichControl, outSubControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &inIndex))
+ return NULL;
+ _err = GetIndexedSubControl(_self->ob_itself,
+ inIndex,
+ &outSubControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_WhichControl, outSubControl);
+ return _res;
}
static PyObject *CtlObj_SetControlSupervisor(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlHandle inBoss;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlHandle inBoss;
#ifndef SetControlSupervisor
- PyMac_PRECHECK(SetControlSupervisor);
+ PyMac_PRECHECK(SetControlSupervisor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CtlObj_Convert, &inBoss))
- return NULL;
- _err = SetControlSupervisor(_self->ob_itself,
- inBoss);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CtlObj_Convert, &inBoss))
+ return NULL;
+ _err = SetControlSupervisor(_self->ob_itself,
+ inBoss);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlFeatures(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UInt32 outFeatures;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UInt32 outFeatures;
#ifndef GetControlFeatures
- PyMac_PRECHECK(GetControlFeatures);
+ PyMac_PRECHECK(GetControlFeatures);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetControlFeatures(_self->ob_itself,
- &outFeatures);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outFeatures);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetControlFeatures(_self->ob_itself,
+ &outFeatures);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outFeatures);
+ return _res;
}
static PyObject *CtlObj_GetControlDataSize(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlPartCode inPart;
- ResType inTagName;
- Size outMaxSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlPartCode inPart;
+ ResType inTagName;
+ Size outMaxSize;
#ifndef GetControlDataSize
- PyMac_PRECHECK(GetControlDataSize);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &inPart,
- PyMac_GetOSType, &inTagName))
- return NULL;
- _err = GetControlDataSize(_self->ob_itself,
- inPart,
- inTagName,
- &outMaxSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outMaxSize);
- return _res;
+ PyMac_PRECHECK(GetControlDataSize);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inPart,
+ PyMac_GetOSType, &inTagName))
+ return NULL;
+ _err = GetControlDataSize(_self->ob_itself,
+ inPart,
+ inTagName,
+ &outMaxSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outMaxSize);
+ return _res;
}
static PyObject *CtlObj_HandleControlDragTracking(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DragTrackingMessage inMessage;
- DragReference inDrag;
- Boolean outLikesDrag;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DragTrackingMessage inMessage;
+ DragReference inDrag;
+ Boolean outLikesDrag;
#ifndef HandleControlDragTracking
- PyMac_PRECHECK(HandleControlDragTracking);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &inMessage,
- DragObj_Convert, &inDrag))
- return NULL;
- _err = HandleControlDragTracking(_self->ob_itself,
- inMessage,
- inDrag,
- &outLikesDrag);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- outLikesDrag);
- return _res;
+ PyMac_PRECHECK(HandleControlDragTracking);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inMessage,
+ DragObj_Convert, &inDrag))
+ return NULL;
+ _err = HandleControlDragTracking(_self->ob_itself,
+ inMessage,
+ inDrag,
+ &outLikesDrag);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ outLikesDrag);
+ return _res;
}
static PyObject *CtlObj_HandleControlDragReceive(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DragReference inDrag;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DragReference inDrag;
#ifndef HandleControlDragReceive
- PyMac_PRECHECK(HandleControlDragReceive);
+ PyMac_PRECHECK(HandleControlDragReceive);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- DragObj_Convert, &inDrag))
- return NULL;
- _err = HandleControlDragReceive(_self->ob_itself,
- inDrag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ DragObj_Convert, &inDrag))
+ return NULL;
+ _err = HandleControlDragReceive(_self->ob_itself,
+ inDrag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetControlDragTrackingEnabled(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean inTracks;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean inTracks;
#ifndef SetControlDragTrackingEnabled
- PyMac_PRECHECK(SetControlDragTrackingEnabled);
+ PyMac_PRECHECK(SetControlDragTrackingEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &inTracks))
- return NULL;
- _err = SetControlDragTrackingEnabled(_self->ob_itself,
- inTracks);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &inTracks))
+ return NULL;
+ _err = SetControlDragTrackingEnabled(_self->ob_itself,
+ inTracks);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_IsControlDragTrackingEnabled(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean outTracks;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean outTracks;
#ifndef IsControlDragTrackingEnabled
- PyMac_PRECHECK(IsControlDragTrackingEnabled);
+ PyMac_PRECHECK(IsControlDragTrackingEnabled);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = IsControlDragTrackingEnabled(_self->ob_itself,
- &outTracks);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- outTracks);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = IsControlDragTrackingEnabled(_self->ob_itself,
+ &outTracks);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ outTracks);
+ return _res;
}
static PyObject *CtlObj_GetControlBounds(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect bounds;
+ PyObject *_res = NULL;
+ Rect bounds;
#ifndef GetControlBounds
- PyMac_PRECHECK(GetControlBounds);
+ PyMac_PRECHECK(GetControlBounds);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetControlBounds(_self->ob_itself,
- &bounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetControlBounds(_self->ob_itself,
+ &bounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *CtlObj_IsControlHilited(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsControlHilited
- PyMac_PRECHECK(IsControlHilited);
+ PyMac_PRECHECK(IsControlHilited);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsControlHilited(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsControlHilited(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_GetControlHilite(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt16 _rv;
+ PyObject *_res = NULL;
+ UInt16 _rv;
#ifndef GetControlHilite
- PyMac_PRECHECK(GetControlHilite);
+ PyMac_PRECHECK(GetControlHilite);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlHilite(_self->ob_itself);
- _res = Py_BuildValue("H",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlHilite(_self->ob_itself);
+ _res = Py_BuildValue("H",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_GetControlOwner(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
#ifndef GetControlOwner
- PyMac_PRECHECK(GetControlOwner);
+ PyMac_PRECHECK(GetControlOwner);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlOwner(_self->ob_itself);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlOwner(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *CtlObj_GetControlDataHandle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef GetControlDataHandle
- PyMac_PRECHECK(GetControlDataHandle);
+ PyMac_PRECHECK(GetControlDataHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlDataHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlDataHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *CtlObj_GetControlPopupMenuHandle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
#ifndef GetControlPopupMenuHandle
- PyMac_PRECHECK(GetControlPopupMenuHandle);
+ PyMac_PRECHECK(GetControlPopupMenuHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlPopupMenuHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlPopupMenuHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *CtlObj_GetControlPopupMenuID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetControlPopupMenuID
- PyMac_PRECHECK(GetControlPopupMenuID);
+ PyMac_PRECHECK(GetControlPopupMenuID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetControlPopupMenuID(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetControlPopupMenuID(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlDataHandle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle dataHandle;
+ PyObject *_res = NULL;
+ Handle dataHandle;
#ifndef SetControlDataHandle
- PyMac_PRECHECK(SetControlDataHandle);
+ PyMac_PRECHECK(SetControlDataHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &dataHandle))
- return NULL;
- SetControlDataHandle(_self->ob_itself,
- dataHandle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &dataHandle))
+ return NULL;
+ SetControlDataHandle(_self->ob_itself,
+ dataHandle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetControlBounds(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect bounds;
+ PyObject *_res = NULL;
+ Rect bounds;
#ifndef SetControlBounds
- PyMac_PRECHECK(SetControlBounds);
+ PyMac_PRECHECK(SetControlBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &bounds))
- return NULL;
- SetControlBounds(_self->ob_itself,
- &bounds);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &bounds))
+ return NULL;
+ SetControlBounds(_self->ob_itself,
+ &bounds);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetControlPopupMenuHandle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle popupMenu;
+ PyObject *_res = NULL;
+ MenuHandle popupMenu;
#ifndef SetControlPopupMenuHandle
- PyMac_PRECHECK(SetControlPopupMenuHandle);
+ PyMac_PRECHECK(SetControlPopupMenuHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MenuObj_Convert, &popupMenu))
- return NULL;
- SetControlPopupMenuHandle(_self->ob_itself,
- popupMenu);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MenuObj_Convert, &popupMenu))
+ return NULL;
+ SetControlPopupMenuHandle(_self->ob_itself,
+ popupMenu);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetControlPopupMenuID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short menuID;
+ PyObject *_res = NULL;
+ short menuID;
#ifndef SetControlPopupMenuID
- PyMac_PRECHECK(SetControlPopupMenuID);
+ PyMac_PRECHECK(SetControlPopupMenuID);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- SetControlPopupMenuID(_self->ob_itself,
- menuID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ SetControlPopupMenuID(_self->ob_itself,
+ menuID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetBevelButtonMenuValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UInt16 outValue;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UInt16 outValue;
#ifndef GetBevelButtonMenuValue
- PyMac_PRECHECK(GetBevelButtonMenuValue);
+ PyMac_PRECHECK(GetBevelButtonMenuValue);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetBevelButtonMenuValue(_self->ob_itself,
- &outValue);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outValue);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetBevelButtonMenuValue(_self->ob_itself,
+ &outValue);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outValue);
+ return _res;
}
static PyObject *CtlObj_SetBevelButtonMenuValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inValue;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inValue;
#ifndef SetBevelButtonMenuValue
- PyMac_PRECHECK(SetBevelButtonMenuValue);
+ PyMac_PRECHECK(SetBevelButtonMenuValue);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inValue))
- return NULL;
- _err = SetBevelButtonMenuValue(_self->ob_itself,
- inValue);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inValue))
+ return NULL;
+ _err = SetBevelButtonMenuValue(_self->ob_itself,
+ inValue);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetBevelButtonMenuHandle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- MenuHandle outHandle;
+ PyObject *_res = NULL;
+ OSErr _err;
+ MenuHandle outHandle;
#ifndef GetBevelButtonMenuHandle
- PyMac_PRECHECK(GetBevelButtonMenuHandle);
+ PyMac_PRECHECK(GetBevelButtonMenuHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetBevelButtonMenuHandle(_self->ob_itself,
- &outHandle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- MenuObj_New, outHandle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetBevelButtonMenuHandle(_self->ob_itself,
+ &outHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, outHandle);
+ return _res;
}
static PyObject *CtlObj_SetBevelButtonContentInfo(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlButtonContentInfo inContent;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlButtonContentInfo inContent;
#ifndef SetBevelButtonContentInfo
- PyMac_PRECHECK(SetBevelButtonContentInfo);
+ PyMac_PRECHECK(SetBevelButtonContentInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ControlButtonContentInfo_Convert, &inContent))
- return NULL;
- _err = SetBevelButtonContentInfo(_self->ob_itself,
- &inContent);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ControlButtonContentInfo_Convert, &inContent))
+ return NULL;
+ _err = SetBevelButtonContentInfo(_self->ob_itself,
+ &inContent);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetBevelButtonTransform(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconTransformType transform;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconTransformType transform;
#ifndef SetBevelButtonTransform
- PyMac_PRECHECK(SetBevelButtonTransform);
+ PyMac_PRECHECK(SetBevelButtonTransform);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &transform))
- return NULL;
- _err = SetBevelButtonTransform(_self->ob_itself,
- transform);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &transform))
+ return NULL;
+ _err = SetBevelButtonTransform(_self->ob_itself,
+ transform);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetDisclosureTriangleLastValue(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inValue;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inValue;
#ifndef SetDisclosureTriangleLastValue
- PyMac_PRECHECK(SetDisclosureTriangleLastValue);
+ PyMac_PRECHECK(SetDisclosureTriangleLastValue);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inValue))
- return NULL;
- _err = SetDisclosureTriangleLastValue(_self->ob_itself,
- inValue);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inValue))
+ return NULL;
+ _err = SetDisclosureTriangleLastValue(_self->ob_itself,
+ inValue);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetTabContentRect(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect outContentRect;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect outContentRect;
#ifndef GetTabContentRect
- PyMac_PRECHECK(GetTabContentRect);
+ PyMac_PRECHECK(GetTabContentRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetTabContentRect(_self->ob_itself,
- &outContentRect);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outContentRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetTabContentRect(_self->ob_itself,
+ &outContentRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outContentRect);
+ return _res;
}
static PyObject *CtlObj_SetTabEnabled(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inTabToHilite;
- Boolean inEnabled;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inTabToHilite;
+ Boolean inEnabled;
#ifndef SetTabEnabled
- PyMac_PRECHECK(SetTabEnabled);
+ PyMac_PRECHECK(SetTabEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &inTabToHilite,
- &inEnabled))
- return NULL;
- _err = SetTabEnabled(_self->ob_itself,
- inTabToHilite,
- inEnabled);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &inTabToHilite,
+ &inEnabled))
+ return NULL;
+ _err = SetTabEnabled(_self->ob_itself,
+ inTabToHilite,
+ inEnabled);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetImageWellContentInfo(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ControlButtonContentInfo inContent;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ControlButtonContentInfo inContent;
#ifndef SetImageWellContentInfo
- PyMac_PRECHECK(SetImageWellContentInfo);
+ PyMac_PRECHECK(SetImageWellContentInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ControlButtonContentInfo_Convert, &inContent))
- return NULL;
- _err = SetImageWellContentInfo(_self->ob_itself,
- &inContent);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ControlButtonContentInfo_Convert, &inContent))
+ return NULL;
+ _err = SetImageWellContentInfo(_self->ob_itself,
+ &inContent);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetImageWellTransform(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconTransformType inTransform;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconTransformType inTransform;
#ifndef SetImageWellTransform
- PyMac_PRECHECK(SetImageWellTransform);
+ PyMac_PRECHECK(SetImageWellTransform);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inTransform))
- return NULL;
- _err = SetImageWellTransform(_self->ob_itself,
- inTransform);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inTransform))
+ return NULL;
+ _err = SetImageWellTransform(_self->ob_itself,
+ inTransform);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserViewStyle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType style;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType style;
#ifndef GetDataBrowserViewStyle
- PyMac_PRECHECK(GetDataBrowserViewStyle);
+ PyMac_PRECHECK(GetDataBrowserViewStyle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserViewStyle(_self->ob_itself,
- &style);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildOSType, style);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserViewStyle(_self->ob_itself,
+ &style);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildOSType, style);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserViewStyle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType style;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType style;
#ifndef SetDataBrowserViewStyle
- PyMac_PRECHECK(SetDataBrowserViewStyle);
+ PyMac_PRECHECK(SetDataBrowserViewStyle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &style))
- return NULL;
- _err = SetDataBrowserViewStyle(_self->ob_itself,
- style);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &style))
+ return NULL;
+ _err = SetDataBrowserViewStyle(_self->ob_itself,
+ style);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_EnableDataBrowserEditCommand(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- UInt32 command;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ UInt32 command;
#ifndef EnableDataBrowserEditCommand
- PyMac_PRECHECK(EnableDataBrowserEditCommand);
+ PyMac_PRECHECK(EnableDataBrowserEditCommand);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &command))
- return NULL;
- _rv = EnableDataBrowserEditCommand(_self->ob_itself,
- command);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &command))
+ return NULL;
+ _rv = EnableDataBrowserEditCommand(_self->ob_itself,
+ command);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_ExecuteDataBrowserEditCommand(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 command;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 command;
#ifndef ExecuteDataBrowserEditCommand
- PyMac_PRECHECK(ExecuteDataBrowserEditCommand);
+ PyMac_PRECHECK(ExecuteDataBrowserEditCommand);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &command))
- return NULL;
- _err = ExecuteDataBrowserEditCommand(_self->ob_itself,
- command);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &command))
+ return NULL;
+ _err = ExecuteDataBrowserEditCommand(_self->ob_itself,
+ command);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserSelectionAnchor(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 first;
- UInt32 last;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 first;
+ UInt32 last;
#ifndef GetDataBrowserSelectionAnchor
- PyMac_PRECHECK(GetDataBrowserSelectionAnchor);
+ PyMac_PRECHECK(GetDataBrowserSelectionAnchor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserSelectionAnchor(_self->ob_itself,
- &first,
- &last);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("ll",
- first,
- last);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserSelectionAnchor(_self->ob_itself,
+ &first,
+ &last);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("ll",
+ first,
+ last);
+ return _res;
}
static PyObject *CtlObj_MoveDataBrowserSelectionAnchor(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 direction;
- Boolean extendSelection;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 direction;
+ Boolean extendSelection;
#ifndef MoveDataBrowserSelectionAnchor
- PyMac_PRECHECK(MoveDataBrowserSelectionAnchor);
+ PyMac_PRECHECK(MoveDataBrowserSelectionAnchor);
#endif
- if (!PyArg_ParseTuple(_args, "lb",
- &direction,
- &extendSelection))
- return NULL;
- _err = MoveDataBrowserSelectionAnchor(_self->ob_itself,
- direction,
- extendSelection);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lb",
+ &direction,
+ &extendSelection))
+ return NULL;
+ _err = MoveDataBrowserSelectionAnchor(_self->ob_itself,
+ direction,
+ extendSelection);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_OpenDataBrowserContainer(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 container;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 container;
#ifndef OpenDataBrowserContainer
- PyMac_PRECHECK(OpenDataBrowserContainer);
+ PyMac_PRECHECK(OpenDataBrowserContainer);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &container))
- return NULL;
- _err = OpenDataBrowserContainer(_self->ob_itself,
- container);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &container))
+ return NULL;
+ _err = OpenDataBrowserContainer(_self->ob_itself,
+ container);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_CloseDataBrowserContainer(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 container;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 container;
#ifndef CloseDataBrowserContainer
- PyMac_PRECHECK(CloseDataBrowserContainer);
+ PyMac_PRECHECK(CloseDataBrowserContainer);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &container))
- return NULL;
- _err = CloseDataBrowserContainer(_self->ob_itself,
- container);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &container))
+ return NULL;
+ _err = CloseDataBrowserContainer(_self->ob_itself,
+ container);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SortDataBrowserContainer(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 container;
- Boolean sortChildren;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 container;
+ Boolean sortChildren;
#ifndef SortDataBrowserContainer
- PyMac_PRECHECK(SortDataBrowserContainer);
+ PyMac_PRECHECK(SortDataBrowserContainer);
#endif
- if (!PyArg_ParseTuple(_args, "lb",
- &container,
- &sortChildren))
- return NULL;
- _err = SortDataBrowserContainer(_self->ob_itself,
- container,
- sortChildren);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lb",
+ &container,
+ &sortChildren))
+ return NULL;
+ _err = SortDataBrowserContainer(_self->ob_itself,
+ container,
+ sortChildren);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserItems(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 container;
- Boolean recurse;
- UInt32 state;
- Handle items;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 container;
+ Boolean recurse;
+ UInt32 state;
+ Handle items;
#ifndef GetDataBrowserItems
- PyMac_PRECHECK(GetDataBrowserItems);
-#endif
- if (!PyArg_ParseTuple(_args, "lblO&",
- &container,
- &recurse,
- &state,
- ResObj_Convert, &items))
- return NULL;
- _err = GetDataBrowserItems(_self->ob_itself,
- container,
- recurse,
- state,
- items);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(GetDataBrowserItems);
+#endif
+ if (!PyArg_ParseTuple(_args, "lblO&",
+ &container,
+ &recurse,
+ &state,
+ ResObj_Convert, &items))
+ return NULL;
+ _err = GetDataBrowserItems(_self->ob_itself,
+ container,
+ recurse,
+ state,
+ items);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserItemCount(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 container;
- Boolean recurse;
- UInt32 state;
- UInt32 numItems;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 container;
+ Boolean recurse;
+ UInt32 state;
+ UInt32 numItems;
#ifndef GetDataBrowserItemCount
- PyMac_PRECHECK(GetDataBrowserItemCount);
-#endif
- if (!PyArg_ParseTuple(_args, "lbl",
- &container,
- &recurse,
- &state))
- return NULL;
- _err = GetDataBrowserItemCount(_self->ob_itself,
- container,
- recurse,
- state,
- &numItems);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- numItems);
- return _res;
+ PyMac_PRECHECK(GetDataBrowserItemCount);
+#endif
+ if (!PyArg_ParseTuple(_args, "lbl",
+ &container,
+ &recurse,
+ &state))
+ return NULL;
+ _err = GetDataBrowserItemCount(_self->ob_itself,
+ container,
+ recurse,
+ state,
+ &numItems);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ numItems);
+ return _res;
}
static PyObject *CtlObj_IsDataBrowserItemSelected(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- UInt32 item;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ UInt32 item;
#ifndef IsDataBrowserItemSelected
- PyMac_PRECHECK(IsDataBrowserItemSelected);
+ PyMac_PRECHECK(IsDataBrowserItemSelected);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &item))
- return NULL;
- _rv = IsDataBrowserItemSelected(_self->ob_itself,
- item);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &item))
+ return NULL;
+ _rv = IsDataBrowserItemSelected(_self->ob_itself,
+ item);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserItemState(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 state;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 state;
#ifndef GetDataBrowserItemState
- PyMac_PRECHECK(GetDataBrowserItemState);
+ PyMac_PRECHECK(GetDataBrowserItemState);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &item))
- return NULL;
- _err = GetDataBrowserItemState(_self->ob_itself,
- item,
- &state);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- state);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &item))
+ return NULL;
+ _err = GetDataBrowserItemState(_self->ob_itself,
+ item,
+ &state);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ state);
+ return _res;
}
static PyObject *CtlObj_RevealDataBrowserItem(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 propertyID;
- UInt8 options;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 propertyID;
+ UInt8 options;
#ifndef RevealDataBrowserItem
- PyMac_PRECHECK(RevealDataBrowserItem);
-#endif
- if (!PyArg_ParseTuple(_args, "llb",
- &item,
- &propertyID,
- &options))
- return NULL;
- _err = RevealDataBrowserItem(_self->ob_itself,
- item,
- propertyID,
- options);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(RevealDataBrowserItem);
+#endif
+ if (!PyArg_ParseTuple(_args, "llb",
+ &item,
+ &propertyID,
+ &options))
+ return NULL;
+ _err = RevealDataBrowserItem(_self->ob_itself,
+ item,
+ propertyID,
+ options);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserActiveItems(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean active;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean active;
#ifndef SetDataBrowserActiveItems
- PyMac_PRECHECK(SetDataBrowserActiveItems);
+ PyMac_PRECHECK(SetDataBrowserActiveItems);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &active))
- return NULL;
- _err = SetDataBrowserActiveItems(_self->ob_itself,
- active);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &active))
+ return NULL;
+ _err = SetDataBrowserActiveItems(_self->ob_itself,
+ active);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserActiveItems(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean active;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean active;
#ifndef GetDataBrowserActiveItems
- PyMac_PRECHECK(GetDataBrowserActiveItems);
+ PyMac_PRECHECK(GetDataBrowserActiveItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserActiveItems(_self->ob_itself,
- &active);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- active);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserActiveItems(_self->ob_itself,
+ &active);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ active);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserScrollBarInset(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect insetRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect insetRect;
#ifndef SetDataBrowserScrollBarInset
- PyMac_PRECHECK(SetDataBrowserScrollBarInset);
+ PyMac_PRECHECK(SetDataBrowserScrollBarInset);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = SetDataBrowserScrollBarInset(_self->ob_itself,
- &insetRect);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &insetRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = SetDataBrowserScrollBarInset(_self->ob_itself,
+ &insetRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &insetRect);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserScrollBarInset(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect insetRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect insetRect;
#ifndef GetDataBrowserScrollBarInset
- PyMac_PRECHECK(GetDataBrowserScrollBarInset);
+ PyMac_PRECHECK(GetDataBrowserScrollBarInset);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserScrollBarInset(_self->ob_itself,
- &insetRect);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &insetRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserScrollBarInset(_self->ob_itself,
+ &insetRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &insetRect);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTarget(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 target;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 target;
#ifndef SetDataBrowserTarget
- PyMac_PRECHECK(SetDataBrowserTarget);
+ PyMac_PRECHECK(SetDataBrowserTarget);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &target))
- return NULL;
- _err = SetDataBrowserTarget(_self->ob_itself,
- target);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &target))
+ return NULL;
+ _err = SetDataBrowserTarget(_self->ob_itself,
+ target);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTarget(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 target;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 target;
#ifndef GetDataBrowserTarget
- PyMac_PRECHECK(GetDataBrowserTarget);
+ PyMac_PRECHECK(GetDataBrowserTarget);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserTarget(_self->ob_itself,
- &target);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- target);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserTarget(_self->ob_itself,
+ &target);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ target);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserSortOrder(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 order;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 order;
#ifndef SetDataBrowserSortOrder
- PyMac_PRECHECK(SetDataBrowserSortOrder);
+ PyMac_PRECHECK(SetDataBrowserSortOrder);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &order))
- return NULL;
- _err = SetDataBrowserSortOrder(_self->ob_itself,
- order);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &order))
+ return NULL;
+ _err = SetDataBrowserSortOrder(_self->ob_itself,
+ order);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserSortOrder(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 order;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 order;
#ifndef GetDataBrowserSortOrder
- PyMac_PRECHECK(GetDataBrowserSortOrder);
+ PyMac_PRECHECK(GetDataBrowserSortOrder);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserSortOrder(_self->ob_itself,
- &order);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- order);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserSortOrder(_self->ob_itself,
+ &order);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ order);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserScrollPosition(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 top;
- UInt32 left;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 top;
+ UInt32 left;
#ifndef SetDataBrowserScrollPosition
- PyMac_PRECHECK(SetDataBrowserScrollPosition);
+ PyMac_PRECHECK(SetDataBrowserScrollPosition);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &top,
- &left))
- return NULL;
- _err = SetDataBrowserScrollPosition(_self->ob_itself,
- top,
- left);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &top,
+ &left))
+ return NULL;
+ _err = SetDataBrowserScrollPosition(_self->ob_itself,
+ top,
+ left);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserScrollPosition(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 top;
- UInt32 left;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 top;
+ UInt32 left;
#ifndef GetDataBrowserScrollPosition
- PyMac_PRECHECK(GetDataBrowserScrollPosition);
+ PyMac_PRECHECK(GetDataBrowserScrollPosition);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserScrollPosition(_self->ob_itself,
- &top,
- &left);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("ll",
- top,
- left);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserScrollPosition(_self->ob_itself,
+ &top,
+ &left);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("ll",
+ top,
+ left);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserHasScrollBars(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean horiz;
- Boolean vert;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean horiz;
+ Boolean vert;
#ifndef SetDataBrowserHasScrollBars
- PyMac_PRECHECK(SetDataBrowserHasScrollBars);
+ PyMac_PRECHECK(SetDataBrowserHasScrollBars);
#endif
- if (!PyArg_ParseTuple(_args, "bb",
- &horiz,
- &vert))
- return NULL;
- _err = SetDataBrowserHasScrollBars(_self->ob_itself,
- horiz,
- vert);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "bb",
+ &horiz,
+ &vert))
+ return NULL;
+ _err = SetDataBrowserHasScrollBars(_self->ob_itself,
+ horiz,
+ vert);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserHasScrollBars(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean horiz;
- Boolean vert;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean horiz;
+ Boolean vert;
#ifndef GetDataBrowserHasScrollBars
- PyMac_PRECHECK(GetDataBrowserHasScrollBars);
+ PyMac_PRECHECK(GetDataBrowserHasScrollBars);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserHasScrollBars(_self->ob_itself,
- &horiz,
- &vert);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bb",
- horiz,
- vert);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserHasScrollBars(_self->ob_itself,
+ &horiz,
+ &vert);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bb",
+ horiz,
+ vert);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserSortProperty(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 property;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 property;
#ifndef SetDataBrowserSortProperty
- PyMac_PRECHECK(SetDataBrowserSortProperty);
+ PyMac_PRECHECK(SetDataBrowserSortProperty);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &property))
- return NULL;
- _err = SetDataBrowserSortProperty(_self->ob_itself,
- property);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &property))
+ return NULL;
+ _err = SetDataBrowserSortProperty(_self->ob_itself,
+ property);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserSortProperty(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 property;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 property;
#ifndef GetDataBrowserSortProperty
- PyMac_PRECHECK(GetDataBrowserSortProperty);
+ PyMac_PRECHECK(GetDataBrowserSortProperty);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserSortProperty(_self->ob_itself,
- &property);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- property);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserSortProperty(_self->ob_itself,
+ &property);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ property);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserSelectionFlags(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 selectionFlags;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 selectionFlags;
#ifndef SetDataBrowserSelectionFlags
- PyMac_PRECHECK(SetDataBrowserSelectionFlags);
+ PyMac_PRECHECK(SetDataBrowserSelectionFlags);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &selectionFlags))
- return NULL;
- _err = SetDataBrowserSelectionFlags(_self->ob_itself,
- selectionFlags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &selectionFlags))
+ return NULL;
+ _err = SetDataBrowserSelectionFlags(_self->ob_itself,
+ selectionFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserSelectionFlags(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 selectionFlags;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 selectionFlags;
#ifndef GetDataBrowserSelectionFlags
- PyMac_PRECHECK(GetDataBrowserSelectionFlags);
+ PyMac_PRECHECK(GetDataBrowserSelectionFlags);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserSelectionFlags(_self->ob_itself,
- &selectionFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- selectionFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserSelectionFlags(_self->ob_itself,
+ &selectionFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ selectionFlags);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserPropertyFlags(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 property;
- UInt32 flags;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 property;
+ UInt32 flags;
#ifndef SetDataBrowserPropertyFlags
- PyMac_PRECHECK(SetDataBrowserPropertyFlags);
+ PyMac_PRECHECK(SetDataBrowserPropertyFlags);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &property,
- &flags))
- return NULL;
- _err = SetDataBrowserPropertyFlags(_self->ob_itself,
- property,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &property,
+ &flags))
+ return NULL;
+ _err = SetDataBrowserPropertyFlags(_self->ob_itself,
+ property,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserPropertyFlags(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 property;
- UInt32 flags;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 property;
+ UInt32 flags;
#ifndef GetDataBrowserPropertyFlags
- PyMac_PRECHECK(GetDataBrowserPropertyFlags);
+ PyMac_PRECHECK(GetDataBrowserPropertyFlags);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &property))
- return NULL;
- _err = GetDataBrowserPropertyFlags(_self->ob_itself,
- property,
- &flags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &property))
+ return NULL;
+ _err = GetDataBrowserPropertyFlags(_self->ob_itself,
+ property,
+ &flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ flags);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserEditText(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef text;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef text;
#ifndef SetDataBrowserEditText
- PyMac_PRECHECK(SetDataBrowserEditText);
+ PyMac_PRECHECK(SetDataBrowserEditText);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &text))
- return NULL;
- _err = SetDataBrowserEditText(_self->ob_itself,
- text);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &text))
+ return NULL;
+ _err = SetDataBrowserEditText(_self->ob_itself,
+ text);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_CopyDataBrowserEditText(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef text;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef text;
#ifndef CopyDataBrowserEditText
- PyMac_PRECHECK(CopyDataBrowserEditText);
+ PyMac_PRECHECK(CopyDataBrowserEditText);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CopyDataBrowserEditText(_self->ob_itself,
- &text);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, text);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CopyDataBrowserEditText(_self->ob_itself,
+ &text);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, text);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserEditText(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFMutableStringRef text;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFMutableStringRef text;
#ifndef GetDataBrowserEditText
- PyMac_PRECHECK(GetDataBrowserEditText);
+ PyMac_PRECHECK(GetDataBrowserEditText);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFMutableStringRefObj_Convert, &text))
- return NULL;
- _err = GetDataBrowserEditText(_self->ob_itself,
- text);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFMutableStringRefObj_Convert, &text))
+ return NULL;
+ _err = GetDataBrowserEditText(_self->ob_itself,
+ text);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserEditItem(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 property;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 property;
#ifndef SetDataBrowserEditItem
- PyMac_PRECHECK(SetDataBrowserEditItem);
+ PyMac_PRECHECK(SetDataBrowserEditItem);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &item,
- &property))
- return NULL;
- _err = SetDataBrowserEditItem(_self->ob_itself,
- item,
- property);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &item,
+ &property))
+ return NULL;
+ _err = SetDataBrowserEditItem(_self->ob_itself,
+ item,
+ property);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserEditItem(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 property;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 property;
#ifndef GetDataBrowserEditItem
- PyMac_PRECHECK(GetDataBrowserEditItem);
+ PyMac_PRECHECK(GetDataBrowserEditItem);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserEditItem(_self->ob_itself,
- &item,
- &property);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("ll",
- item,
- property);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserEditItem(_self->ob_itself,
+ &item,
+ &property);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("ll",
+ item,
+ property);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserItemPartBounds(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 property;
- OSType part;
- Rect bounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 property;
+ OSType part;
+ Rect bounds;
#ifndef GetDataBrowserItemPartBounds
- PyMac_PRECHECK(GetDataBrowserItemPartBounds);
-#endif
- if (!PyArg_ParseTuple(_args, "llO&",
- &item,
- &property,
- PyMac_GetOSType, &part))
- return NULL;
- _err = GetDataBrowserItemPartBounds(_self->ob_itself,
- item,
- property,
- part,
- &bounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ PyMac_PRECHECK(GetDataBrowserItemPartBounds);
+#endif
+ if (!PyArg_ParseTuple(_args, "llO&",
+ &item,
+ &property,
+ PyMac_GetOSType, &part))
+ return NULL;
+ _err = GetDataBrowserItemPartBounds(_self->ob_itself,
+ item,
+ property,
+ part,
+ &bounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *CtlObj_RemoveDataBrowserTableViewColumn(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
#ifndef RemoveDataBrowserTableViewColumn
- PyMac_PRECHECK(RemoveDataBrowserTableViewColumn);
+ PyMac_PRECHECK(RemoveDataBrowserTableViewColumn);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &column))
- return NULL;
- _err = RemoveDataBrowserTableViewColumn(_self->ob_itself,
- column);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &column))
+ return NULL;
+ _err = RemoveDataBrowserTableViewColumn(_self->ob_itself,
+ column);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewColumnCount(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 numColumns;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 numColumns;
#ifndef GetDataBrowserTableViewColumnCount
- PyMac_PRECHECK(GetDataBrowserTableViewColumnCount);
+ PyMac_PRECHECK(GetDataBrowserTableViewColumnCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserTableViewColumnCount(_self->ob_itself,
- &numColumns);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- numColumns);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserTableViewColumnCount(_self->ob_itself,
+ &numColumns);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ numColumns);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewHiliteStyle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 hiliteStyle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 hiliteStyle;
#ifndef SetDataBrowserTableViewHiliteStyle
- PyMac_PRECHECK(SetDataBrowserTableViewHiliteStyle);
+ PyMac_PRECHECK(SetDataBrowserTableViewHiliteStyle);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &hiliteStyle))
- return NULL;
- _err = SetDataBrowserTableViewHiliteStyle(_self->ob_itself,
- hiliteStyle);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &hiliteStyle))
+ return NULL;
+ _err = SetDataBrowserTableViewHiliteStyle(_self->ob_itself,
+ hiliteStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewHiliteStyle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 hiliteStyle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 hiliteStyle;
#ifndef GetDataBrowserTableViewHiliteStyle
- PyMac_PRECHECK(GetDataBrowserTableViewHiliteStyle);
+ PyMac_PRECHECK(GetDataBrowserTableViewHiliteStyle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserTableViewHiliteStyle(_self->ob_itself,
- &hiliteStyle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- hiliteStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserTableViewHiliteStyle(_self->ob_itself,
+ &hiliteStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ hiliteStyle);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewRowHeight(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 height;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 height;
#ifndef SetDataBrowserTableViewRowHeight
- PyMac_PRECHECK(SetDataBrowserTableViewRowHeight);
+ PyMac_PRECHECK(SetDataBrowserTableViewRowHeight);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &height))
- return NULL;
- _err = SetDataBrowserTableViewRowHeight(_self->ob_itself,
- height);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &height))
+ return NULL;
+ _err = SetDataBrowserTableViewRowHeight(_self->ob_itself,
+ height);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewRowHeight(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 height;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 height;
#ifndef GetDataBrowserTableViewRowHeight
- PyMac_PRECHECK(GetDataBrowserTableViewRowHeight);
+ PyMac_PRECHECK(GetDataBrowserTableViewRowHeight);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserTableViewRowHeight(_self->ob_itself,
- &height);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- height);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserTableViewRowHeight(_self->ob_itself,
+ &height);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ height);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewColumnWidth(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 width;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 width;
#ifndef SetDataBrowserTableViewColumnWidth
- PyMac_PRECHECK(SetDataBrowserTableViewColumnWidth);
+ PyMac_PRECHECK(SetDataBrowserTableViewColumnWidth);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &width))
- return NULL;
- _err = SetDataBrowserTableViewColumnWidth(_self->ob_itself,
- width);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &width))
+ return NULL;
+ _err = SetDataBrowserTableViewColumnWidth(_self->ob_itself,
+ width);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewColumnWidth(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 width;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 width;
#ifndef GetDataBrowserTableViewColumnWidth
- PyMac_PRECHECK(GetDataBrowserTableViewColumnWidth);
+ PyMac_PRECHECK(GetDataBrowserTableViewColumnWidth);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserTableViewColumnWidth(_self->ob_itself,
- &width);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- width);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserTableViewColumnWidth(_self->ob_itself,
+ &width);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ width);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewItemRowHeight(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt16 height;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt16 height;
#ifndef SetDataBrowserTableViewItemRowHeight
- PyMac_PRECHECK(SetDataBrowserTableViewItemRowHeight);
+ PyMac_PRECHECK(SetDataBrowserTableViewItemRowHeight);
#endif
- if (!PyArg_ParseTuple(_args, "lH",
- &item,
- &height))
- return NULL;
- _err = SetDataBrowserTableViewItemRowHeight(_self->ob_itself,
- item,
- height);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lH",
+ &item,
+ &height))
+ return NULL;
+ _err = SetDataBrowserTableViewItemRowHeight(_self->ob_itself,
+ item,
+ height);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewItemRowHeight(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt16 height;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt16 height;
#ifndef GetDataBrowserTableViewItemRowHeight
- PyMac_PRECHECK(GetDataBrowserTableViewItemRowHeight);
+ PyMac_PRECHECK(GetDataBrowserTableViewItemRowHeight);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &item))
- return NULL;
- _err = GetDataBrowserTableViewItemRowHeight(_self->ob_itself,
- item,
- &height);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- height);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &item))
+ return NULL;
+ _err = GetDataBrowserTableViewItemRowHeight(_self->ob_itself,
+ item,
+ &height);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ height);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewNamedColumnWidth(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- UInt16 width;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ UInt16 width;
#ifndef SetDataBrowserTableViewNamedColumnWidth
- PyMac_PRECHECK(SetDataBrowserTableViewNamedColumnWidth);
+ PyMac_PRECHECK(SetDataBrowserTableViewNamedColumnWidth);
#endif
- if (!PyArg_ParseTuple(_args, "lH",
- &column,
- &width))
- return NULL;
- _err = SetDataBrowserTableViewNamedColumnWidth(_self->ob_itself,
- column,
- width);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lH",
+ &column,
+ &width))
+ return NULL;
+ _err = SetDataBrowserTableViewNamedColumnWidth(_self->ob_itself,
+ column,
+ width);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewNamedColumnWidth(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- UInt16 width;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ UInt16 width;
#ifndef GetDataBrowserTableViewNamedColumnWidth
- PyMac_PRECHECK(GetDataBrowserTableViewNamedColumnWidth);
+ PyMac_PRECHECK(GetDataBrowserTableViewNamedColumnWidth);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &column))
- return NULL;
- _err = GetDataBrowserTableViewNamedColumnWidth(_self->ob_itself,
- column,
- &width);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- width);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &column))
+ return NULL;
+ _err = GetDataBrowserTableViewNamedColumnWidth(_self->ob_itself,
+ column,
+ &width);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ width);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewGeometry(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean variableWidthColumns;
- Boolean variableHeightRows;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean variableWidthColumns;
+ Boolean variableHeightRows;
#ifndef SetDataBrowserTableViewGeometry
- PyMac_PRECHECK(SetDataBrowserTableViewGeometry);
+ PyMac_PRECHECK(SetDataBrowserTableViewGeometry);
#endif
- if (!PyArg_ParseTuple(_args, "bb",
- &variableWidthColumns,
- &variableHeightRows))
- return NULL;
- _err = SetDataBrowserTableViewGeometry(_self->ob_itself,
- variableWidthColumns,
- variableHeightRows);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "bb",
+ &variableWidthColumns,
+ &variableHeightRows))
+ return NULL;
+ _err = SetDataBrowserTableViewGeometry(_self->ob_itself,
+ variableWidthColumns,
+ variableHeightRows);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewGeometry(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean variableWidthColumns;
- Boolean variableHeightRows;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean variableWidthColumns;
+ Boolean variableHeightRows;
#ifndef GetDataBrowserTableViewGeometry
- PyMac_PRECHECK(GetDataBrowserTableViewGeometry);
+ PyMac_PRECHECK(GetDataBrowserTableViewGeometry);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserTableViewGeometry(_self->ob_itself,
- &variableWidthColumns,
- &variableHeightRows);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bb",
- variableWidthColumns,
- variableHeightRows);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserTableViewGeometry(_self->ob_itself,
+ &variableWidthColumns,
+ &variableHeightRows);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bb",
+ variableWidthColumns,
+ variableHeightRows);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewItemID(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 row;
- UInt32 item;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 row;
+ UInt32 item;
#ifndef GetDataBrowserTableViewItemID
- PyMac_PRECHECK(GetDataBrowserTableViewItemID);
+ PyMac_PRECHECK(GetDataBrowserTableViewItemID);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &row))
- return NULL;
- _err = GetDataBrowserTableViewItemID(_self->ob_itself,
- row,
- &item);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- item);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &row))
+ return NULL;
+ _err = GetDataBrowserTableViewItemID(_self->ob_itself,
+ row,
+ &item);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ item);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewItemRow(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 row;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 row;
#ifndef SetDataBrowserTableViewItemRow
- PyMac_PRECHECK(SetDataBrowserTableViewItemRow);
+ PyMac_PRECHECK(SetDataBrowserTableViewItemRow);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &item,
- &row))
- return NULL;
- _err = SetDataBrowserTableViewItemRow(_self->ob_itself,
- item,
- row);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &item,
+ &row))
+ return NULL;
+ _err = SetDataBrowserTableViewItemRow(_self->ob_itself,
+ item,
+ row);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewItemRow(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 item;
- UInt32 row;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 item;
+ UInt32 row;
#ifndef GetDataBrowserTableViewItemRow
- PyMac_PRECHECK(GetDataBrowserTableViewItemRow);
+ PyMac_PRECHECK(GetDataBrowserTableViewItemRow);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &item))
- return NULL;
- _err = GetDataBrowserTableViewItemRow(_self->ob_itself,
- item,
- &row);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- row);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &item))
+ return NULL;
+ _err = GetDataBrowserTableViewItemRow(_self->ob_itself,
+ item,
+ &row);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ row);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserTableViewColumnPosition(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- UInt32 position;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ UInt32 position;
#ifndef SetDataBrowserTableViewColumnPosition
- PyMac_PRECHECK(SetDataBrowserTableViewColumnPosition);
+ PyMac_PRECHECK(SetDataBrowserTableViewColumnPosition);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &column,
- &position))
- return NULL;
- _err = SetDataBrowserTableViewColumnPosition(_self->ob_itself,
- column,
- position);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &column,
+ &position))
+ return NULL;
+ _err = SetDataBrowserTableViewColumnPosition(_self->ob_itself,
+ column,
+ position);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewColumnPosition(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- UInt32 position;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ UInt32 position;
#ifndef GetDataBrowserTableViewColumnPosition
- PyMac_PRECHECK(GetDataBrowserTableViewColumnPosition);
+ PyMac_PRECHECK(GetDataBrowserTableViewColumnPosition);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &column))
- return NULL;
- _err = GetDataBrowserTableViewColumnPosition(_self->ob_itself,
- column,
- &position);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- position);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &column))
+ return NULL;
+ _err = GetDataBrowserTableViewColumnPosition(_self->ob_itself,
+ column,
+ &position);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ position);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserTableViewColumnProperty(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- UInt32 property;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ UInt32 property;
#ifndef GetDataBrowserTableViewColumnProperty
- PyMac_PRECHECK(GetDataBrowserTableViewColumnProperty);
+ PyMac_PRECHECK(GetDataBrowserTableViewColumnProperty);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &column))
- return NULL;
- _err = GetDataBrowserTableViewColumnProperty(_self->ob_itself,
- column,
- &property);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- property);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &column))
+ return NULL;
+ _err = GetDataBrowserTableViewColumnProperty(_self->ob_itself,
+ column,
+ &property);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ property);
+ return _res;
}
static PyObject *CtlObj_AutoSizeDataBrowserListViewColumns(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef AutoSizeDataBrowserListViewColumns
- PyMac_PRECHECK(AutoSizeDataBrowserListViewColumns);
+ PyMac_PRECHECK(AutoSizeDataBrowserListViewColumns);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AutoSizeDataBrowserListViewColumns(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AutoSizeDataBrowserListViewColumns(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_AddDataBrowserListViewColumn(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DataBrowserListViewColumnDesc columnDesc;
- UInt32 position;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DataBrowserListViewColumnDesc columnDesc;
+ UInt32 position;
#ifndef AddDataBrowserListViewColumn
- PyMac_PRECHECK(AddDataBrowserListViewColumn);
+ PyMac_PRECHECK(AddDataBrowserListViewColumn);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- DataBrowserListViewColumnDesc_Convert, &columnDesc,
- &position))
- return NULL;
- _err = AddDataBrowserListViewColumn(_self->ob_itself,
- &columnDesc,
- position);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ DataBrowserListViewColumnDesc_Convert, &columnDesc,
+ &position))
+ return NULL;
+ _err = AddDataBrowserListViewColumn(_self->ob_itself,
+ &columnDesc,
+ position);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserListViewHeaderBtnHeight(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 height;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 height;
#ifndef SetDataBrowserListViewHeaderBtnHeight
- PyMac_PRECHECK(SetDataBrowserListViewHeaderBtnHeight);
+ PyMac_PRECHECK(SetDataBrowserListViewHeaderBtnHeight);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &height))
- return NULL;
- _err = SetDataBrowserListViewHeaderBtnHeight(_self->ob_itself,
- height);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &height))
+ return NULL;
+ _err = SetDataBrowserListViewHeaderBtnHeight(_self->ob_itself,
+ height);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserListViewHeaderBtnHeight(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 height;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 height;
#ifndef GetDataBrowserListViewHeaderBtnHeight
- PyMac_PRECHECK(GetDataBrowserListViewHeaderBtnHeight);
+ PyMac_PRECHECK(GetDataBrowserListViewHeaderBtnHeight);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserListViewHeaderBtnHeight(_self->ob_itself,
- &height);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- height);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserListViewHeaderBtnHeight(_self->ob_itself,
+ &height);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ height);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserListViewUsePlainBackground(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean usePlainBackground;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean usePlainBackground;
#ifndef SetDataBrowserListViewUsePlainBackground
- PyMac_PRECHECK(SetDataBrowserListViewUsePlainBackground);
+ PyMac_PRECHECK(SetDataBrowserListViewUsePlainBackground);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &usePlainBackground))
- return NULL;
- _err = SetDataBrowserListViewUsePlainBackground(_self->ob_itself,
- usePlainBackground);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &usePlainBackground))
+ return NULL;
+ _err = SetDataBrowserListViewUsePlainBackground(_self->ob_itself,
+ usePlainBackground);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserListViewUsePlainBackground(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean usePlainBackground;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean usePlainBackground;
#ifndef GetDataBrowserListViewUsePlainBackground
- PyMac_PRECHECK(GetDataBrowserListViewUsePlainBackground);
+ PyMac_PRECHECK(GetDataBrowserListViewUsePlainBackground);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserListViewUsePlainBackground(_self->ob_itself,
- &usePlainBackground);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- usePlainBackground);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserListViewUsePlainBackground(_self->ob_itself,
+ &usePlainBackground);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ usePlainBackground);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserListViewDisclosureColumn(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- Boolean expandableRows;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ Boolean expandableRows;
#ifndef SetDataBrowserListViewDisclosureColumn
- PyMac_PRECHECK(SetDataBrowserListViewDisclosureColumn);
+ PyMac_PRECHECK(SetDataBrowserListViewDisclosureColumn);
#endif
- if (!PyArg_ParseTuple(_args, "lb",
- &column,
- &expandableRows))
- return NULL;
- _err = SetDataBrowserListViewDisclosureColumn(_self->ob_itself,
- column,
- expandableRows);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lb",
+ &column,
+ &expandableRows))
+ return NULL;
+ _err = SetDataBrowserListViewDisclosureColumn(_self->ob_itself,
+ column,
+ expandableRows);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserListViewDisclosureColumn(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 column;
- Boolean expandableRows;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 column;
+ Boolean expandableRows;
#ifndef GetDataBrowserListViewDisclosureColumn
- PyMac_PRECHECK(GetDataBrowserListViewDisclosureColumn);
+ PyMac_PRECHECK(GetDataBrowserListViewDisclosureColumn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserListViewDisclosureColumn(_self->ob_itself,
- &column,
- &expandableRows);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("lb",
- column,
- expandableRows);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserListViewDisclosureColumn(_self->ob_itself,
+ &column,
+ &expandableRows);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("lb",
+ column,
+ expandableRows);
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserColumnViewPath(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Handle path;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Handle path;
#ifndef GetDataBrowserColumnViewPath
- PyMac_PRECHECK(GetDataBrowserColumnViewPath);
+ PyMac_PRECHECK(GetDataBrowserColumnViewPath);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &path))
- return NULL;
- _err = GetDataBrowserColumnViewPath(_self->ob_itself,
- path);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &path))
+ return NULL;
+ _err = GetDataBrowserColumnViewPath(_self->ob_itself,
+ path);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserColumnViewPathLength(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 pathLength;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 pathLength;
#ifndef GetDataBrowserColumnViewPathLength
- PyMac_PRECHECK(GetDataBrowserColumnViewPathLength);
+ PyMac_PRECHECK(GetDataBrowserColumnViewPathLength);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserColumnViewPathLength(_self->ob_itself,
- &pathLength);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- pathLength);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserColumnViewPathLength(_self->ob_itself,
+ &pathLength);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ pathLength);
+ return _res;
}
static PyObject *CtlObj_SetDataBrowserColumnViewDisplayType(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyType;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyType;
#ifndef SetDataBrowserColumnViewDisplayType
- PyMac_PRECHECK(SetDataBrowserColumnViewDisplayType);
+ PyMac_PRECHECK(SetDataBrowserColumnViewDisplayType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &propertyType))
- return NULL;
- _err = SetDataBrowserColumnViewDisplayType(_self->ob_itself,
- propertyType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &propertyType))
+ return NULL;
+ _err = SetDataBrowserColumnViewDisplayType(_self->ob_itself,
+ propertyType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetDataBrowserColumnViewDisplayType(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyType;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyType;
#ifndef GetDataBrowserColumnViewDisplayType
- PyMac_PRECHECK(GetDataBrowserColumnViewDisplayType);
+ PyMac_PRECHECK(GetDataBrowserColumnViewDisplayType);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDataBrowserColumnViewDisplayType(_self->ob_itself,
- &propertyType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildOSType, propertyType);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDataBrowserColumnViewDisplayType(_self->ob_itself,
+ &propertyType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildOSType, propertyType);
+ return _res;
}
static PyObject *CtlObj_as_Resource(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef as_Resource
- PyMac_PRECHECK(as_Resource);
+ PyMac_PRECHECK(as_Resource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = as_Resource(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = as_Resource(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *CtlObj_GetControlRect(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef GetControlRect
- PyMac_PRECHECK(GetControlRect);
+ PyMac_PRECHECK(GetControlRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetControlRect(_self->ob_itself,
- &rect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &rect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetControlRect(_self->ob_itself,
+ &rect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &rect);
+ return _res;
}
static PyObject *CtlObj_DisposeControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- if ( _self->ob_itself ) {
- SetControlReference(_self->ob_itself, (long)0); /* Make it forget about us */
- DisposeControl(_self->ob_itself);
- _self->ob_itself = NULL;
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ if ( _self->ob_itself ) {
+ SetControlReference(_self->ob_itself, (long)0); /* Make it forget about us */
+ DisposeControl(_self->ob_itself);
+ _self->ob_itself = NULL;
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_TrackControl(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- ControlPartCode _rv;
- Point startPoint;
- ControlActionUPP upp = 0;
- PyObject *callback = 0;
-
- if (!PyArg_ParseTuple(_args, "O&|O",
- PyMac_GetPoint, &startPoint, &callback))
- return NULL;
- if (callback && callback != Py_None) {
- if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1)
- upp = (ControlActionUPP)-1;
- else {
- settrackfunc(callback);
- upp = mytracker_upp;
- }
- }
- _rv = TrackControl(_self->ob_itself,
- startPoint,
- upp);
- clrtrackfunc();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+
+ ControlPartCode _rv;
+ Point startPoint;
+ ControlActionUPP upp = 0;
+ PyObject *callback = 0;
+
+ if (!PyArg_ParseTuple(_args, "O&|O",
+ PyMac_GetPoint, &startPoint, &callback))
+ return NULL;
+ if (callback && callback != Py_None) {
+ if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1)
+ upp = (ControlActionUPP)-1;
+ else {
+ settrackfunc(callback);
+ upp = mytracker_upp;
+ }
+ }
+ _rv = TrackControl(_self->ob_itself,
+ startPoint,
+ upp);
+ clrtrackfunc();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_HandleControlClick(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- ControlPartCode _rv;
- Point startPoint;
- SInt16 modifiers;
- ControlActionUPP upp = 0;
- PyObject *callback = 0;
-
- if (!PyArg_ParseTuple(_args, "O&h|O",
- PyMac_GetPoint, &startPoint,
- &modifiers,
- &callback))
- return NULL;
- if (callback && callback != Py_None) {
- if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1)
- upp = (ControlActionUPP)-1;
- else {
- settrackfunc(callback);
- upp = mytracker_upp;
- }
- }
- _rv = HandleControlClick(_self->ob_itself,
- startPoint,
- modifiers,
- upp);
- clrtrackfunc();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+
+ ControlPartCode _rv;
+ Point startPoint;
+ SInt16 modifiers;
+ ControlActionUPP upp = 0;
+ PyObject *callback = 0;
+
+ if (!PyArg_ParseTuple(_args, "O&h|O",
+ PyMac_GetPoint, &startPoint,
+ &modifiers,
+ &callback))
+ return NULL;
+ if (callback && callback != Py_None) {
+ if (PyInt_Check(callback) && PyInt_AS_LONG(callback) == -1)
+ upp = (ControlActionUPP)-1;
+ else {
+ settrackfunc(callback);
+ upp = mytracker_upp;
+ }
+ }
+ _rv = HandleControlClick(_self->ob_itself,
+ startPoint,
+ modifiers,
+ upp);
+ clrtrackfunc();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *CtlObj_SetControlData(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- OSErr _err;
- ControlPartCode inPart;
- ResType inTagName;
- Size bufferSize;
- Ptr buffer;
+ OSErr _err;
+ ControlPartCode inPart;
+ ResType inTagName;
+ Size bufferSize;
+ Ptr buffer;
- if (!PyArg_ParseTuple(_args, "hO&s#",
- &inPart,
- PyMac_GetOSType, &inTagName,
- &buffer, &bufferSize))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "hO&s#",
+ &inPart,
+ PyMac_GetOSType, &inTagName,
+ &buffer, &bufferSize))
+ return NULL;
- _err = SetControlData(_self->ob_itself,
- inPart,
- inTagName,
- bufferSize,
- buffer);
+ _err = SetControlData(_self->ob_itself,
+ inPart,
+ inTagName,
+ bufferSize,
+ buffer);
- if (_err != noErr)
- return PyMac_Error(_err);
- _res = Py_None;
- return _res;
+ if (_err != noErr)
+ return PyMac_Error(_err);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlData(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- OSErr _err;
- ControlPartCode inPart;
- ResType inTagName;
- Size bufferSize;
- Ptr buffer;
- Size outSize;
-
- if (!PyArg_ParseTuple(_args, "hO&",
- &inPart,
- PyMac_GetOSType, &inTagName))
- return NULL;
-
- /* allocate a buffer for the data */
- _err = GetControlDataSize(_self->ob_itself,
- inPart,
- inTagName,
- &bufferSize);
- if (_err != noErr)
- return PyMac_Error(_err);
- buffer = PyMem_NEW(char, bufferSize);
- if (buffer == NULL)
- return PyErr_NoMemory();
-
- _err = GetControlData(_self->ob_itself,
- inPart,
- inTagName,
- bufferSize,
- buffer,
- &outSize);
-
- if (_err != noErr) {
- PyMem_DEL(buffer);
- return PyMac_Error(_err);
- }
- _res = Py_BuildValue("s#", buffer, outSize);
- PyMem_DEL(buffer);
- return _res;
+ PyObject *_res = NULL;
+
+ OSErr _err;
+ ControlPartCode inPart;
+ ResType inTagName;
+ Size bufferSize;
+ Ptr buffer;
+ Size outSize;
+
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inPart,
+ PyMac_GetOSType, &inTagName))
+ return NULL;
+
+ /* allocate a buffer for the data */
+ _err = GetControlDataSize(_self->ob_itself,
+ inPart,
+ inTagName,
+ &bufferSize);
+ if (_err != noErr)
+ return PyMac_Error(_err);
+ buffer = PyMem_NEW(char, bufferSize);
+ if (buffer == NULL)
+ return PyErr_NoMemory();
+
+ _err = GetControlData(_self->ob_itself,
+ inPart,
+ inTagName,
+ bufferSize,
+ buffer,
+ &outSize);
+
+ if (_err != noErr) {
+ PyMem_DEL(buffer);
+ return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("s#", buffer, outSize);
+ PyMem_DEL(buffer);
+ return _res;
}
static PyObject *CtlObj_SetControlData_Handle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- OSErr _err;
- ControlPartCode inPart;
- ResType inTagName;
- Handle buffer;
+ OSErr _err;
+ ControlPartCode inPart;
+ ResType inTagName;
+ Handle buffer;
- if (!PyArg_ParseTuple(_args, "hO&O&",
- &inPart,
- PyMac_GetOSType, &inTagName,
- OptResObj_Convert, &buffer))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "hO&O&",
+ &inPart,
+ PyMac_GetOSType, &inTagName,
+ OptResObj_Convert, &buffer))
+ return NULL;
- _err = SetControlData(_self->ob_itself,
- inPart,
- inTagName,
- sizeof(buffer),
- (Ptr)&buffer);
+ _err = SetControlData(_self->ob_itself,
+ inPart,
+ inTagName,
+ sizeof(buffer),
+ (Ptr)&buffer);
- if (_err != noErr)
- return PyMac_Error(_err);
- _res = Py_None;
- return _res;
+ if (_err != noErr)
+ return PyMac_Error(_err);
+ _res = Py_None;
+ return _res;
}
static PyObject *CtlObj_GetControlData_Handle(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- OSErr _err;
- ControlPartCode inPart;
- ResType inTagName;
- Size bufferSize;
- Handle hdl;
-
- if (!PyArg_ParseTuple(_args, "hO&",
- &inPart,
- PyMac_GetOSType, &inTagName))
- return NULL;
-
- /* Check it is handle-sized */
- _err = GetControlDataSize(_self->ob_itself,
- inPart,
- inTagName,
- &bufferSize);
- if (_err != noErr)
- return PyMac_Error(_err);
- if (bufferSize != sizeof(Handle)) {
- PyErr_SetString(Ctl_Error, "GetControlDataSize() != sizeof(Handle)");
- return NULL;
- }
-
- _err = GetControlData(_self->ob_itself,
- inPart,
- inTagName,
- sizeof(Handle),
- (Ptr)&hdl,
- &bufferSize);
-
- if (_err != noErr) {
- return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&", OptResObj_New, hdl);
- return _res;
+ PyObject *_res = NULL;
+
+ OSErr _err;
+ ControlPartCode inPart;
+ ResType inTagName;
+ Size bufferSize;
+ Handle hdl;
+
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inPart,
+ PyMac_GetOSType, &inTagName))
+ return NULL;
+
+ /* Check it is handle-sized */
+ _err = GetControlDataSize(_self->ob_itself,
+ inPart,
+ inTagName,
+ &bufferSize);
+ if (_err != noErr)
+ return PyMac_Error(_err);
+ if (bufferSize != sizeof(Handle)) {
+ PyErr_SetString(Ctl_Error, "GetControlDataSize() != sizeof(Handle)");
+ return NULL;
+ }
+
+ _err = GetControlData(_self->ob_itself,
+ inPart,
+ inTagName,
+ sizeof(Handle),
+ (Ptr)&hdl,
+ &bufferSize);
+
+ if (_err != noErr) {
+ return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&", OptResObj_New, hdl);
+ return _res;
}
static PyObject *CtlObj_SetControlData_Callback(ControlObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- OSErr _err;
- ControlPartCode inPart;
- ResType inTagName;
- PyObject *callback;
- UniversalProcPtr c_callback;
+ OSErr _err;
+ ControlPartCode inPart;
+ ResType inTagName;
+ PyObject *callback;
+ UniversalProcPtr c_callback;
- if (!PyArg_ParseTuple(_args, "hO&O",
- &inPart,
- PyMac_GetOSType, &inTagName,
- &callback))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "hO&O",
+ &inPart,
+ PyMac_GetOSType, &inTagName,
+ &callback))
+ return NULL;
- if ( setcallback((PyObject *)_self, inTagName, callback, &c_callback) < 0 )
- return NULL;
- _err = SetControlData(_self->ob_itself,
- inPart,
- inTagName,
- sizeof(c_callback),
- (Ptr)&c_callback);
+ if ( setcallback((PyObject *)_self, inTagName, callback, &c_callback) < 0 )
+ return NULL;
+ _err = SetControlData(_self->ob_itself,
+ inPart,
+ inTagName,
+ sizeof(c_callback),
+ (Ptr)&c_callback);
- if (_err != noErr)
- return PyMac_Error(_err);
- _res = Py_None;
- return _res;
+ if (_err != noErr)
+ return PyMac_Error(_err);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef CtlObj_methods[] = {
- {"HiliteControl", (PyCFunction)CtlObj_HiliteControl, 1,
- PyDoc_STR("(ControlPartCode hiliteState) -> None")},
- {"ShowControl", (PyCFunction)CtlObj_ShowControl, 1,
- PyDoc_STR("() -> None")},
- {"HideControl", (PyCFunction)CtlObj_HideControl, 1,
- PyDoc_STR("() -> None")},
- {"IsControlActive", (PyCFunction)CtlObj_IsControlActive, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsControlVisible", (PyCFunction)CtlObj_IsControlVisible, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"ActivateControl", (PyCFunction)CtlObj_ActivateControl, 1,
- PyDoc_STR("() -> None")},
- {"DeactivateControl", (PyCFunction)CtlObj_DeactivateControl, 1,
- PyDoc_STR("() -> None")},
- {"SetControlVisibility", (PyCFunction)CtlObj_SetControlVisibility, 1,
- PyDoc_STR("(Boolean inIsVisible, Boolean inDoDraw) -> None")},
- {"IsControlEnabled", (PyCFunction)CtlObj_IsControlEnabled, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"EnableControl", (PyCFunction)CtlObj_EnableControl, 1,
- PyDoc_STR("() -> None")},
- {"DisableControl", (PyCFunction)CtlObj_DisableControl, 1,
- PyDoc_STR("() -> None")},
- {"Draw1Control", (PyCFunction)CtlObj_Draw1Control, 1,
- PyDoc_STR("() -> None")},
- {"GetBestControlRect", (PyCFunction)CtlObj_GetBestControlRect, 1,
- PyDoc_STR("() -> (Rect outRect, SInt16 outBaseLineOffset)")},
- {"SetControlFontStyle", (PyCFunction)CtlObj_SetControlFontStyle, 1,
- PyDoc_STR("(ControlFontStyleRec inStyle) -> None")},
- {"DrawControlInCurrentPort", (PyCFunction)CtlObj_DrawControlInCurrentPort, 1,
- PyDoc_STR("() -> None")},
- {"SetUpControlBackground", (PyCFunction)CtlObj_SetUpControlBackground, 1,
- PyDoc_STR("(SInt16 inDepth, Boolean inIsColorDevice) -> None")},
- {"SetUpControlTextColor", (PyCFunction)CtlObj_SetUpControlTextColor, 1,
- PyDoc_STR("(SInt16 inDepth, Boolean inIsColorDevice) -> None")},
- {"DragControl", (PyCFunction)CtlObj_DragControl, 1,
- PyDoc_STR("(Point startPoint, Rect limitRect, Rect slopRect, DragConstraint axis) -> None")},
- {"TestControl", (PyCFunction)CtlObj_TestControl, 1,
- PyDoc_STR("(Point testPoint) -> (ControlPartCode _rv)")},
- {"HandleControlContextualMenuClick", (PyCFunction)CtlObj_HandleControlContextualMenuClick, 1,
- PyDoc_STR("(Point inWhere) -> (Boolean menuDisplayed)")},
- {"GetControlClickActivation", (PyCFunction)CtlObj_GetControlClickActivation, 1,
- PyDoc_STR("(Point inWhere, EventModifiers inModifiers) -> (ClickActivationResult outResult)")},
- {"HandleControlKey", (PyCFunction)CtlObj_HandleControlKey, 1,
- PyDoc_STR("(SInt16 inKeyCode, SInt16 inCharCode, EventModifiers inModifiers) -> (ControlPartCode _rv)")},
- {"HandleControlSetCursor", (PyCFunction)CtlObj_HandleControlSetCursor, 1,
- PyDoc_STR("(Point localPoint, EventModifiers modifiers) -> (Boolean cursorWasSet)")},
- {"MoveControl", (PyCFunction)CtlObj_MoveControl, 1,
- PyDoc_STR("(SInt16 h, SInt16 v) -> None")},
- {"SizeControl", (PyCFunction)CtlObj_SizeControl, 1,
- PyDoc_STR("(SInt16 w, SInt16 h) -> None")},
- {"SetControlTitle", (PyCFunction)CtlObj_SetControlTitle, 1,
- PyDoc_STR("(Str255 title) -> None")},
- {"GetControlTitle", (PyCFunction)CtlObj_GetControlTitle, 1,
- PyDoc_STR("() -> (Str255 title)")},
- {"SetControlTitleWithCFString", (PyCFunction)CtlObj_SetControlTitleWithCFString, 1,
- PyDoc_STR("(CFStringRef inString) -> None")},
- {"CopyControlTitleAsCFString", (PyCFunction)CtlObj_CopyControlTitleAsCFString, 1,
- PyDoc_STR("() -> (CFStringRef outString)")},
- {"GetControlValue", (PyCFunction)CtlObj_GetControlValue, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"SetControlValue", (PyCFunction)CtlObj_SetControlValue, 1,
- PyDoc_STR("(SInt16 newValue) -> None")},
- {"GetControlMinimum", (PyCFunction)CtlObj_GetControlMinimum, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"SetControlMinimum", (PyCFunction)CtlObj_SetControlMinimum, 1,
- PyDoc_STR("(SInt16 newMinimum) -> None")},
- {"GetControlMaximum", (PyCFunction)CtlObj_GetControlMaximum, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"SetControlMaximum", (PyCFunction)CtlObj_SetControlMaximum, 1,
- PyDoc_STR("(SInt16 newMaximum) -> None")},
- {"GetControlViewSize", (PyCFunction)CtlObj_GetControlViewSize, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"SetControlViewSize", (PyCFunction)CtlObj_SetControlViewSize, 1,
- PyDoc_STR("(SInt32 newViewSize) -> None")},
- {"GetControl32BitValue", (PyCFunction)CtlObj_GetControl32BitValue, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"SetControl32BitValue", (PyCFunction)CtlObj_SetControl32BitValue, 1,
- PyDoc_STR("(SInt32 newValue) -> None")},
- {"GetControl32BitMaximum", (PyCFunction)CtlObj_GetControl32BitMaximum, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"SetControl32BitMaximum", (PyCFunction)CtlObj_SetControl32BitMaximum, 1,
- PyDoc_STR("(SInt32 newMaximum) -> None")},
- {"GetControl32BitMinimum", (PyCFunction)CtlObj_GetControl32BitMinimum, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"SetControl32BitMinimum", (PyCFunction)CtlObj_SetControl32BitMinimum, 1,
- PyDoc_STR("(SInt32 newMinimum) -> None")},
- {"IsValidControlHandle", (PyCFunction)CtlObj_IsValidControlHandle, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SetControlID", (PyCFunction)CtlObj_SetControlID, 1,
- PyDoc_STR("(ControlID inID) -> None")},
- {"GetControlID", (PyCFunction)CtlObj_GetControlID, 1,
- PyDoc_STR("() -> (ControlID outID)")},
- {"SetControlCommandID", (PyCFunction)CtlObj_SetControlCommandID, 1,
- PyDoc_STR("(UInt32 inCommandID) -> None")},
- {"GetControlCommandID", (PyCFunction)CtlObj_GetControlCommandID, 1,
- PyDoc_STR("() -> (UInt32 outCommandID)")},
- {"RemoveControlProperty", (PyCFunction)CtlObj_RemoveControlProperty, 1,
- PyDoc_STR("(OSType propertyCreator, OSType propertyTag) -> None")},
- {"GetControlPropertyAttributes", (PyCFunction)CtlObj_GetControlPropertyAttributes, 1,
- PyDoc_STR("(OSType propertyCreator, OSType propertyTag) -> (UInt32 attributes)")},
- {"ChangeControlPropertyAttributes", (PyCFunction)CtlObj_ChangeControlPropertyAttributes, 1,
- PyDoc_STR("(OSType propertyCreator, OSType propertyTag, UInt32 attributesToSet, UInt32 attributesToClear) -> None")},
- {"GetControlRegion", (PyCFunction)CtlObj_GetControlRegion, 1,
- PyDoc_STR("(ControlPartCode inPart, RgnHandle outRegion) -> None")},
- {"GetControlVariant", (PyCFunction)CtlObj_GetControlVariant, 1,
- PyDoc_STR("() -> (ControlVariant _rv)")},
- {"SetControlAction", (PyCFunction)CtlObj_SetControlAction, 1,
- PyDoc_STR("(PyObject* actionProc) -> None")},
- {"SetControlReference", (PyCFunction)CtlObj_SetControlReference, 1,
- PyDoc_STR("(SInt32 data) -> None")},
- {"GetControlReference", (PyCFunction)CtlObj_GetControlReference, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"EmbedControl", (PyCFunction)CtlObj_EmbedControl, 1,
- PyDoc_STR("(ControlHandle inContainer) -> None")},
- {"AutoEmbedControl", (PyCFunction)CtlObj_AutoEmbedControl, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"GetSuperControl", (PyCFunction)CtlObj_GetSuperControl, 1,
- PyDoc_STR("() -> (ControlHandle outParent)")},
- {"CountSubControls", (PyCFunction)CtlObj_CountSubControls, 1,
- PyDoc_STR("() -> (UInt16 outNumChildren)")},
- {"GetIndexedSubControl", (PyCFunction)CtlObj_GetIndexedSubControl, 1,
- PyDoc_STR("(UInt16 inIndex) -> (ControlHandle outSubControl)")},
- {"SetControlSupervisor", (PyCFunction)CtlObj_SetControlSupervisor, 1,
- PyDoc_STR("(ControlHandle inBoss) -> None")},
- {"GetControlFeatures", (PyCFunction)CtlObj_GetControlFeatures, 1,
- PyDoc_STR("() -> (UInt32 outFeatures)")},
- {"GetControlDataSize", (PyCFunction)CtlObj_GetControlDataSize, 1,
- PyDoc_STR("(ControlPartCode inPart, ResType inTagName) -> (Size outMaxSize)")},
- {"HandleControlDragTracking", (PyCFunction)CtlObj_HandleControlDragTracking, 1,
- PyDoc_STR("(DragTrackingMessage inMessage, DragReference inDrag) -> (Boolean outLikesDrag)")},
- {"HandleControlDragReceive", (PyCFunction)CtlObj_HandleControlDragReceive, 1,
- PyDoc_STR("(DragReference inDrag) -> None")},
- {"SetControlDragTrackingEnabled", (PyCFunction)CtlObj_SetControlDragTrackingEnabled, 1,
- PyDoc_STR("(Boolean inTracks) -> None")},
- {"IsControlDragTrackingEnabled", (PyCFunction)CtlObj_IsControlDragTrackingEnabled, 1,
- PyDoc_STR("() -> (Boolean outTracks)")},
- {"GetControlBounds", (PyCFunction)CtlObj_GetControlBounds, 1,
- PyDoc_STR("() -> (Rect bounds)")},
- {"IsControlHilited", (PyCFunction)CtlObj_IsControlHilited, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetControlHilite", (PyCFunction)CtlObj_GetControlHilite, 1,
- PyDoc_STR("() -> (UInt16 _rv)")},
- {"GetControlOwner", (PyCFunction)CtlObj_GetControlOwner, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"GetControlDataHandle", (PyCFunction)CtlObj_GetControlDataHandle, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"GetControlPopupMenuHandle", (PyCFunction)CtlObj_GetControlPopupMenuHandle, 1,
- PyDoc_STR("() -> (MenuHandle _rv)")},
- {"GetControlPopupMenuID", (PyCFunction)CtlObj_GetControlPopupMenuID, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetControlDataHandle", (PyCFunction)CtlObj_SetControlDataHandle, 1,
- PyDoc_STR("(Handle dataHandle) -> None")},
- {"SetControlBounds", (PyCFunction)CtlObj_SetControlBounds, 1,
- PyDoc_STR("(Rect bounds) -> None")},
- {"SetControlPopupMenuHandle", (PyCFunction)CtlObj_SetControlPopupMenuHandle, 1,
- PyDoc_STR("(MenuHandle popupMenu) -> None")},
- {"SetControlPopupMenuID", (PyCFunction)CtlObj_SetControlPopupMenuID, 1,
- PyDoc_STR("(short menuID) -> None")},
- {"GetBevelButtonMenuValue", (PyCFunction)CtlObj_GetBevelButtonMenuValue, 1,
- PyDoc_STR("() -> (SInt16 outValue)")},
- {"SetBevelButtonMenuValue", (PyCFunction)CtlObj_SetBevelButtonMenuValue, 1,
- PyDoc_STR("(SInt16 inValue) -> None")},
- {"GetBevelButtonMenuHandle", (PyCFunction)CtlObj_GetBevelButtonMenuHandle, 1,
- PyDoc_STR("() -> (MenuHandle outHandle)")},
- {"SetBevelButtonContentInfo", (PyCFunction)CtlObj_SetBevelButtonContentInfo, 1,
- PyDoc_STR("(ControlButtonContentInfo inContent) -> None")},
- {"SetBevelButtonTransform", (PyCFunction)CtlObj_SetBevelButtonTransform, 1,
- PyDoc_STR("(IconTransformType transform) -> None")},
- {"SetDisclosureTriangleLastValue", (PyCFunction)CtlObj_SetDisclosureTriangleLastValue, 1,
- PyDoc_STR("(SInt16 inValue) -> None")},
- {"GetTabContentRect", (PyCFunction)CtlObj_GetTabContentRect, 1,
- PyDoc_STR("() -> (Rect outContentRect)")},
- {"SetTabEnabled", (PyCFunction)CtlObj_SetTabEnabled, 1,
- PyDoc_STR("(SInt16 inTabToHilite, Boolean inEnabled) -> None")},
- {"SetImageWellContentInfo", (PyCFunction)CtlObj_SetImageWellContentInfo, 1,
- PyDoc_STR("(ControlButtonContentInfo inContent) -> None")},
- {"SetImageWellTransform", (PyCFunction)CtlObj_SetImageWellTransform, 1,
- PyDoc_STR("(IconTransformType inTransform) -> None")},
- {"GetDataBrowserViewStyle", (PyCFunction)CtlObj_GetDataBrowserViewStyle, 1,
- PyDoc_STR("() -> (OSType style)")},
- {"SetDataBrowserViewStyle", (PyCFunction)CtlObj_SetDataBrowserViewStyle, 1,
- PyDoc_STR("(OSType style) -> None")},
- {"EnableDataBrowserEditCommand", (PyCFunction)CtlObj_EnableDataBrowserEditCommand, 1,
- PyDoc_STR("(UInt32 command) -> (Boolean _rv)")},
- {"ExecuteDataBrowserEditCommand", (PyCFunction)CtlObj_ExecuteDataBrowserEditCommand, 1,
- PyDoc_STR("(UInt32 command) -> None")},
- {"GetDataBrowserSelectionAnchor", (PyCFunction)CtlObj_GetDataBrowserSelectionAnchor, 1,
- PyDoc_STR("() -> (UInt32 first, UInt32 last)")},
- {"MoveDataBrowserSelectionAnchor", (PyCFunction)CtlObj_MoveDataBrowserSelectionAnchor, 1,
- PyDoc_STR("(UInt32 direction, Boolean extendSelection) -> None")},
- {"OpenDataBrowserContainer", (PyCFunction)CtlObj_OpenDataBrowserContainer, 1,
- PyDoc_STR("(UInt32 container) -> None")},
- {"CloseDataBrowserContainer", (PyCFunction)CtlObj_CloseDataBrowserContainer, 1,
- PyDoc_STR("(UInt32 container) -> None")},
- {"SortDataBrowserContainer", (PyCFunction)CtlObj_SortDataBrowserContainer, 1,
- PyDoc_STR("(UInt32 container, Boolean sortChildren) -> None")},
- {"GetDataBrowserItems", (PyCFunction)CtlObj_GetDataBrowserItems, 1,
- PyDoc_STR("(UInt32 container, Boolean recurse, UInt32 state, Handle items) -> None")},
- {"GetDataBrowserItemCount", (PyCFunction)CtlObj_GetDataBrowserItemCount, 1,
- PyDoc_STR("(UInt32 container, Boolean recurse, UInt32 state) -> (UInt32 numItems)")},
- {"IsDataBrowserItemSelected", (PyCFunction)CtlObj_IsDataBrowserItemSelected, 1,
- PyDoc_STR("(UInt32 item) -> (Boolean _rv)")},
- {"GetDataBrowserItemState", (PyCFunction)CtlObj_GetDataBrowserItemState, 1,
- PyDoc_STR("(UInt32 item) -> (UInt32 state)")},
- {"RevealDataBrowserItem", (PyCFunction)CtlObj_RevealDataBrowserItem, 1,
- PyDoc_STR("(UInt32 item, UInt32 propertyID, UInt8 options) -> None")},
- {"SetDataBrowserActiveItems", (PyCFunction)CtlObj_SetDataBrowserActiveItems, 1,
- PyDoc_STR("(Boolean active) -> None")},
- {"GetDataBrowserActiveItems", (PyCFunction)CtlObj_GetDataBrowserActiveItems, 1,
- PyDoc_STR("() -> (Boolean active)")},
- {"SetDataBrowserScrollBarInset", (PyCFunction)CtlObj_SetDataBrowserScrollBarInset, 1,
- PyDoc_STR("() -> (Rect insetRect)")},
- {"GetDataBrowserScrollBarInset", (PyCFunction)CtlObj_GetDataBrowserScrollBarInset, 1,
- PyDoc_STR("() -> (Rect insetRect)")},
- {"SetDataBrowserTarget", (PyCFunction)CtlObj_SetDataBrowserTarget, 1,
- PyDoc_STR("(UInt32 target) -> None")},
- {"GetDataBrowserTarget", (PyCFunction)CtlObj_GetDataBrowserTarget, 1,
- PyDoc_STR("() -> (UInt32 target)")},
- {"SetDataBrowserSortOrder", (PyCFunction)CtlObj_SetDataBrowserSortOrder, 1,
- PyDoc_STR("(UInt16 order) -> None")},
- {"GetDataBrowserSortOrder", (PyCFunction)CtlObj_GetDataBrowserSortOrder, 1,
- PyDoc_STR("() -> (UInt16 order)")},
- {"SetDataBrowserScrollPosition", (PyCFunction)CtlObj_SetDataBrowserScrollPosition, 1,
- PyDoc_STR("(UInt32 top, UInt32 left) -> None")},
- {"GetDataBrowserScrollPosition", (PyCFunction)CtlObj_GetDataBrowserScrollPosition, 1,
- PyDoc_STR("() -> (UInt32 top, UInt32 left)")},
- {"SetDataBrowserHasScrollBars", (PyCFunction)CtlObj_SetDataBrowserHasScrollBars, 1,
- PyDoc_STR("(Boolean horiz, Boolean vert) -> None")},
- {"GetDataBrowserHasScrollBars", (PyCFunction)CtlObj_GetDataBrowserHasScrollBars, 1,
- PyDoc_STR("() -> (Boolean horiz, Boolean vert)")},
- {"SetDataBrowserSortProperty", (PyCFunction)CtlObj_SetDataBrowserSortProperty, 1,
- PyDoc_STR("(UInt32 property) -> None")},
- {"GetDataBrowserSortProperty", (PyCFunction)CtlObj_GetDataBrowserSortProperty, 1,
- PyDoc_STR("() -> (UInt32 property)")},
- {"SetDataBrowserSelectionFlags", (PyCFunction)CtlObj_SetDataBrowserSelectionFlags, 1,
- PyDoc_STR("(UInt32 selectionFlags) -> None")},
- {"GetDataBrowserSelectionFlags", (PyCFunction)CtlObj_GetDataBrowserSelectionFlags, 1,
- PyDoc_STR("() -> (UInt32 selectionFlags)")},
- {"SetDataBrowserPropertyFlags", (PyCFunction)CtlObj_SetDataBrowserPropertyFlags, 1,
- PyDoc_STR("(UInt32 property, UInt32 flags) -> None")},
- {"GetDataBrowserPropertyFlags", (PyCFunction)CtlObj_GetDataBrowserPropertyFlags, 1,
- PyDoc_STR("(UInt32 property) -> (UInt32 flags)")},
- {"SetDataBrowserEditText", (PyCFunction)CtlObj_SetDataBrowserEditText, 1,
- PyDoc_STR("(CFStringRef text) -> None")},
- {"CopyDataBrowserEditText", (PyCFunction)CtlObj_CopyDataBrowserEditText, 1,
- PyDoc_STR("() -> (CFStringRef text)")},
- {"GetDataBrowserEditText", (PyCFunction)CtlObj_GetDataBrowserEditText, 1,
- PyDoc_STR("(CFMutableStringRef text) -> None")},
- {"SetDataBrowserEditItem", (PyCFunction)CtlObj_SetDataBrowserEditItem, 1,
- PyDoc_STR("(UInt32 item, UInt32 property) -> None")},
- {"GetDataBrowserEditItem", (PyCFunction)CtlObj_GetDataBrowserEditItem, 1,
- PyDoc_STR("() -> (UInt32 item, UInt32 property)")},
- {"GetDataBrowserItemPartBounds", (PyCFunction)CtlObj_GetDataBrowserItemPartBounds, 1,
- PyDoc_STR("(UInt32 item, UInt32 property, OSType part) -> (Rect bounds)")},
- {"RemoveDataBrowserTableViewColumn", (PyCFunction)CtlObj_RemoveDataBrowserTableViewColumn, 1,
- PyDoc_STR("(UInt32 column) -> None")},
- {"GetDataBrowserTableViewColumnCount", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnCount, 1,
- PyDoc_STR("() -> (UInt32 numColumns)")},
- {"SetDataBrowserTableViewHiliteStyle", (PyCFunction)CtlObj_SetDataBrowserTableViewHiliteStyle, 1,
- PyDoc_STR("(UInt32 hiliteStyle) -> None")},
- {"GetDataBrowserTableViewHiliteStyle", (PyCFunction)CtlObj_GetDataBrowserTableViewHiliteStyle, 1,
- PyDoc_STR("() -> (UInt32 hiliteStyle)")},
- {"SetDataBrowserTableViewRowHeight", (PyCFunction)CtlObj_SetDataBrowserTableViewRowHeight, 1,
- PyDoc_STR("(UInt16 height) -> None")},
- {"GetDataBrowserTableViewRowHeight", (PyCFunction)CtlObj_GetDataBrowserTableViewRowHeight, 1,
- PyDoc_STR("() -> (UInt16 height)")},
- {"SetDataBrowserTableViewColumnWidth", (PyCFunction)CtlObj_SetDataBrowserTableViewColumnWidth, 1,
- PyDoc_STR("(UInt16 width) -> None")},
- {"GetDataBrowserTableViewColumnWidth", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnWidth, 1,
- PyDoc_STR("() -> (UInt16 width)")},
- {"SetDataBrowserTableViewItemRowHeight", (PyCFunction)CtlObj_SetDataBrowserTableViewItemRowHeight, 1,
- PyDoc_STR("(UInt32 item, UInt16 height) -> None")},
- {"GetDataBrowserTableViewItemRowHeight", (PyCFunction)CtlObj_GetDataBrowserTableViewItemRowHeight, 1,
- PyDoc_STR("(UInt32 item) -> (UInt16 height)")},
- {"SetDataBrowserTableViewNamedColumnWidth", (PyCFunction)CtlObj_SetDataBrowserTableViewNamedColumnWidth, 1,
- PyDoc_STR("(UInt32 column, UInt16 width) -> None")},
- {"GetDataBrowserTableViewNamedColumnWidth", (PyCFunction)CtlObj_GetDataBrowserTableViewNamedColumnWidth, 1,
- PyDoc_STR("(UInt32 column) -> (UInt16 width)")},
- {"SetDataBrowserTableViewGeometry", (PyCFunction)CtlObj_SetDataBrowserTableViewGeometry, 1,
- PyDoc_STR("(Boolean variableWidthColumns, Boolean variableHeightRows) -> None")},
- {"GetDataBrowserTableViewGeometry", (PyCFunction)CtlObj_GetDataBrowserTableViewGeometry, 1,
- PyDoc_STR("() -> (Boolean variableWidthColumns, Boolean variableHeightRows)")},
- {"GetDataBrowserTableViewItemID", (PyCFunction)CtlObj_GetDataBrowserTableViewItemID, 1,
- PyDoc_STR("(UInt32 row) -> (UInt32 item)")},
- {"SetDataBrowserTableViewItemRow", (PyCFunction)CtlObj_SetDataBrowserTableViewItemRow, 1,
- PyDoc_STR("(UInt32 item, UInt32 row) -> None")},
- {"GetDataBrowserTableViewItemRow", (PyCFunction)CtlObj_GetDataBrowserTableViewItemRow, 1,
- PyDoc_STR("(UInt32 item) -> (UInt32 row)")},
- {"SetDataBrowserTableViewColumnPosition", (PyCFunction)CtlObj_SetDataBrowserTableViewColumnPosition, 1,
- PyDoc_STR("(UInt32 column, UInt32 position) -> None")},
- {"GetDataBrowserTableViewColumnPosition", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnPosition, 1,
- PyDoc_STR("(UInt32 column) -> (UInt32 position)")},
- {"GetDataBrowserTableViewColumnProperty", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnProperty, 1,
- PyDoc_STR("(UInt32 column) -> (UInt32 property)")},
- {"AutoSizeDataBrowserListViewColumns", (PyCFunction)CtlObj_AutoSizeDataBrowserListViewColumns, 1,
- PyDoc_STR("() -> None")},
- {"AddDataBrowserListViewColumn", (PyCFunction)CtlObj_AddDataBrowserListViewColumn, 1,
- PyDoc_STR("(DataBrowserListViewColumnDesc columnDesc, UInt32 position) -> None")},
- {"SetDataBrowserListViewHeaderBtnHeight", (PyCFunction)CtlObj_SetDataBrowserListViewHeaderBtnHeight, 1,
- PyDoc_STR("(UInt16 height) -> None")},
- {"GetDataBrowserListViewHeaderBtnHeight", (PyCFunction)CtlObj_GetDataBrowserListViewHeaderBtnHeight, 1,
- PyDoc_STR("() -> (UInt16 height)")},
- {"SetDataBrowserListViewUsePlainBackground", (PyCFunction)CtlObj_SetDataBrowserListViewUsePlainBackground, 1,
- PyDoc_STR("(Boolean usePlainBackground) -> None")},
- {"GetDataBrowserListViewUsePlainBackground", (PyCFunction)CtlObj_GetDataBrowserListViewUsePlainBackground, 1,
- PyDoc_STR("() -> (Boolean usePlainBackground)")},
- {"SetDataBrowserListViewDisclosureColumn", (PyCFunction)CtlObj_SetDataBrowserListViewDisclosureColumn, 1,
- PyDoc_STR("(UInt32 column, Boolean expandableRows) -> None")},
- {"GetDataBrowserListViewDisclosureColumn", (PyCFunction)CtlObj_GetDataBrowserListViewDisclosureColumn, 1,
- PyDoc_STR("() -> (UInt32 column, Boolean expandableRows)")},
- {"GetDataBrowserColumnViewPath", (PyCFunction)CtlObj_GetDataBrowserColumnViewPath, 1,
- PyDoc_STR("(Handle path) -> None")},
- {"GetDataBrowserColumnViewPathLength", (PyCFunction)CtlObj_GetDataBrowserColumnViewPathLength, 1,
- PyDoc_STR("() -> (UInt32 pathLength)")},
- {"SetDataBrowserColumnViewDisplayType", (PyCFunction)CtlObj_SetDataBrowserColumnViewDisplayType, 1,
- PyDoc_STR("(OSType propertyType) -> None")},
- {"GetDataBrowserColumnViewDisplayType", (PyCFunction)CtlObj_GetDataBrowserColumnViewDisplayType, 1,
- PyDoc_STR("() -> (OSType propertyType)")},
- {"as_Resource", (PyCFunction)CtlObj_as_Resource, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"GetControlRect", (PyCFunction)CtlObj_GetControlRect, 1,
- PyDoc_STR("() -> (Rect rect)")},
- {"DisposeControl", (PyCFunction)CtlObj_DisposeControl, 1,
- PyDoc_STR("() -> None")},
- {"TrackControl", (PyCFunction)CtlObj_TrackControl, 1,
- PyDoc_STR("(Point startPoint [,trackercallback]) -> (ControlPartCode _rv)")},
- {"HandleControlClick", (PyCFunction)CtlObj_HandleControlClick, 1,
- PyDoc_STR("(Point startPoint, Integer modifiers, [,trackercallback]) -> (ControlPartCode _rv)")},
- {"SetControlData", (PyCFunction)CtlObj_SetControlData, 1,
- PyDoc_STR("(stuff) -> None")},
- {"GetControlData", (PyCFunction)CtlObj_GetControlData, 1,
- PyDoc_STR("(part, type) -> String")},
- {"SetControlData_Handle", (PyCFunction)CtlObj_SetControlData_Handle, 1,
- PyDoc_STR("(ResObj) -> None")},
- {"GetControlData_Handle", (PyCFunction)CtlObj_GetControlData_Handle, 1,
- PyDoc_STR("(part, type) -> ResObj")},
- {"SetControlData_Callback", (PyCFunction)CtlObj_SetControlData_Callback, 1,
- PyDoc_STR("(callbackfunc) -> None")},
- {NULL, NULL, 0}
+ {"HiliteControl", (PyCFunction)CtlObj_HiliteControl, 1,
+ PyDoc_STR("(ControlPartCode hiliteState) -> None")},
+ {"ShowControl", (PyCFunction)CtlObj_ShowControl, 1,
+ PyDoc_STR("() -> None")},
+ {"HideControl", (PyCFunction)CtlObj_HideControl, 1,
+ PyDoc_STR("() -> None")},
+ {"IsControlActive", (PyCFunction)CtlObj_IsControlActive, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsControlVisible", (PyCFunction)CtlObj_IsControlVisible, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"ActivateControl", (PyCFunction)CtlObj_ActivateControl, 1,
+ PyDoc_STR("() -> None")},
+ {"DeactivateControl", (PyCFunction)CtlObj_DeactivateControl, 1,
+ PyDoc_STR("() -> None")},
+ {"SetControlVisibility", (PyCFunction)CtlObj_SetControlVisibility, 1,
+ PyDoc_STR("(Boolean inIsVisible, Boolean inDoDraw) -> None")},
+ {"IsControlEnabled", (PyCFunction)CtlObj_IsControlEnabled, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"EnableControl", (PyCFunction)CtlObj_EnableControl, 1,
+ PyDoc_STR("() -> None")},
+ {"DisableControl", (PyCFunction)CtlObj_DisableControl, 1,
+ PyDoc_STR("() -> None")},
+ {"Draw1Control", (PyCFunction)CtlObj_Draw1Control, 1,
+ PyDoc_STR("() -> None")},
+ {"GetBestControlRect", (PyCFunction)CtlObj_GetBestControlRect, 1,
+ PyDoc_STR("() -> (Rect outRect, SInt16 outBaseLineOffset)")},
+ {"SetControlFontStyle", (PyCFunction)CtlObj_SetControlFontStyle, 1,
+ PyDoc_STR("(ControlFontStyleRec inStyle) -> None")},
+ {"DrawControlInCurrentPort", (PyCFunction)CtlObj_DrawControlInCurrentPort, 1,
+ PyDoc_STR("() -> None")},
+ {"SetUpControlBackground", (PyCFunction)CtlObj_SetUpControlBackground, 1,
+ PyDoc_STR("(SInt16 inDepth, Boolean inIsColorDevice) -> None")},
+ {"SetUpControlTextColor", (PyCFunction)CtlObj_SetUpControlTextColor, 1,
+ PyDoc_STR("(SInt16 inDepth, Boolean inIsColorDevice) -> None")},
+ {"DragControl", (PyCFunction)CtlObj_DragControl, 1,
+ PyDoc_STR("(Point startPoint, Rect limitRect, Rect slopRect, DragConstraint axis) -> None")},
+ {"TestControl", (PyCFunction)CtlObj_TestControl, 1,
+ PyDoc_STR("(Point testPoint) -> (ControlPartCode _rv)")},
+ {"HandleControlContextualMenuClick", (PyCFunction)CtlObj_HandleControlContextualMenuClick, 1,
+ PyDoc_STR("(Point inWhere) -> (Boolean menuDisplayed)")},
+ {"GetControlClickActivation", (PyCFunction)CtlObj_GetControlClickActivation, 1,
+ PyDoc_STR("(Point inWhere, EventModifiers inModifiers) -> (ClickActivationResult outResult)")},
+ {"HandleControlKey", (PyCFunction)CtlObj_HandleControlKey, 1,
+ PyDoc_STR("(SInt16 inKeyCode, SInt16 inCharCode, EventModifiers inModifiers) -> (ControlPartCode _rv)")},
+ {"HandleControlSetCursor", (PyCFunction)CtlObj_HandleControlSetCursor, 1,
+ PyDoc_STR("(Point localPoint, EventModifiers modifiers) -> (Boolean cursorWasSet)")},
+ {"MoveControl", (PyCFunction)CtlObj_MoveControl, 1,
+ PyDoc_STR("(SInt16 h, SInt16 v) -> None")},
+ {"SizeControl", (PyCFunction)CtlObj_SizeControl, 1,
+ PyDoc_STR("(SInt16 w, SInt16 h) -> None")},
+ {"SetControlTitle", (PyCFunction)CtlObj_SetControlTitle, 1,
+ PyDoc_STR("(Str255 title) -> None")},
+ {"GetControlTitle", (PyCFunction)CtlObj_GetControlTitle, 1,
+ PyDoc_STR("() -> (Str255 title)")},
+ {"SetControlTitleWithCFString", (PyCFunction)CtlObj_SetControlTitleWithCFString, 1,
+ PyDoc_STR("(CFStringRef inString) -> None")},
+ {"CopyControlTitleAsCFString", (PyCFunction)CtlObj_CopyControlTitleAsCFString, 1,
+ PyDoc_STR("() -> (CFStringRef outString)")},
+ {"GetControlValue", (PyCFunction)CtlObj_GetControlValue, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"SetControlValue", (PyCFunction)CtlObj_SetControlValue, 1,
+ PyDoc_STR("(SInt16 newValue) -> None")},
+ {"GetControlMinimum", (PyCFunction)CtlObj_GetControlMinimum, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"SetControlMinimum", (PyCFunction)CtlObj_SetControlMinimum, 1,
+ PyDoc_STR("(SInt16 newMinimum) -> None")},
+ {"GetControlMaximum", (PyCFunction)CtlObj_GetControlMaximum, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"SetControlMaximum", (PyCFunction)CtlObj_SetControlMaximum, 1,
+ PyDoc_STR("(SInt16 newMaximum) -> None")},
+ {"GetControlViewSize", (PyCFunction)CtlObj_GetControlViewSize, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"SetControlViewSize", (PyCFunction)CtlObj_SetControlViewSize, 1,
+ PyDoc_STR("(SInt32 newViewSize) -> None")},
+ {"GetControl32BitValue", (PyCFunction)CtlObj_GetControl32BitValue, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"SetControl32BitValue", (PyCFunction)CtlObj_SetControl32BitValue, 1,
+ PyDoc_STR("(SInt32 newValue) -> None")},
+ {"GetControl32BitMaximum", (PyCFunction)CtlObj_GetControl32BitMaximum, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"SetControl32BitMaximum", (PyCFunction)CtlObj_SetControl32BitMaximum, 1,
+ PyDoc_STR("(SInt32 newMaximum) -> None")},
+ {"GetControl32BitMinimum", (PyCFunction)CtlObj_GetControl32BitMinimum, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"SetControl32BitMinimum", (PyCFunction)CtlObj_SetControl32BitMinimum, 1,
+ PyDoc_STR("(SInt32 newMinimum) -> None")},
+ {"IsValidControlHandle", (PyCFunction)CtlObj_IsValidControlHandle, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SetControlID", (PyCFunction)CtlObj_SetControlID, 1,
+ PyDoc_STR("(ControlID inID) -> None")},
+ {"GetControlID", (PyCFunction)CtlObj_GetControlID, 1,
+ PyDoc_STR("() -> (ControlID outID)")},
+ {"SetControlCommandID", (PyCFunction)CtlObj_SetControlCommandID, 1,
+ PyDoc_STR("(UInt32 inCommandID) -> None")},
+ {"GetControlCommandID", (PyCFunction)CtlObj_GetControlCommandID, 1,
+ PyDoc_STR("() -> (UInt32 outCommandID)")},
+ {"RemoveControlProperty", (PyCFunction)CtlObj_RemoveControlProperty, 1,
+ PyDoc_STR("(OSType propertyCreator, OSType propertyTag) -> None")},
+ {"GetControlPropertyAttributes", (PyCFunction)CtlObj_GetControlPropertyAttributes, 1,
+ PyDoc_STR("(OSType propertyCreator, OSType propertyTag) -> (UInt32 attributes)")},
+ {"ChangeControlPropertyAttributes", (PyCFunction)CtlObj_ChangeControlPropertyAttributes, 1,
+ PyDoc_STR("(OSType propertyCreator, OSType propertyTag, UInt32 attributesToSet, UInt32 attributesToClear) -> None")},
+ {"GetControlRegion", (PyCFunction)CtlObj_GetControlRegion, 1,
+ PyDoc_STR("(ControlPartCode inPart, RgnHandle outRegion) -> None")},
+ {"GetControlVariant", (PyCFunction)CtlObj_GetControlVariant, 1,
+ PyDoc_STR("() -> (ControlVariant _rv)")},
+ {"SetControlAction", (PyCFunction)CtlObj_SetControlAction, 1,
+ PyDoc_STR("(PyObject* actionProc) -> None")},
+ {"SetControlReference", (PyCFunction)CtlObj_SetControlReference, 1,
+ PyDoc_STR("(SInt32 data) -> None")},
+ {"GetControlReference", (PyCFunction)CtlObj_GetControlReference, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"EmbedControl", (PyCFunction)CtlObj_EmbedControl, 1,
+ PyDoc_STR("(ControlHandle inContainer) -> None")},
+ {"AutoEmbedControl", (PyCFunction)CtlObj_AutoEmbedControl, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"GetSuperControl", (PyCFunction)CtlObj_GetSuperControl, 1,
+ PyDoc_STR("() -> (ControlHandle outParent)")},
+ {"CountSubControls", (PyCFunction)CtlObj_CountSubControls, 1,
+ PyDoc_STR("() -> (UInt16 outNumChildren)")},
+ {"GetIndexedSubControl", (PyCFunction)CtlObj_GetIndexedSubControl, 1,
+ PyDoc_STR("(UInt16 inIndex) -> (ControlHandle outSubControl)")},
+ {"SetControlSupervisor", (PyCFunction)CtlObj_SetControlSupervisor, 1,
+ PyDoc_STR("(ControlHandle inBoss) -> None")},
+ {"GetControlFeatures", (PyCFunction)CtlObj_GetControlFeatures, 1,
+ PyDoc_STR("() -> (UInt32 outFeatures)")},
+ {"GetControlDataSize", (PyCFunction)CtlObj_GetControlDataSize, 1,
+ PyDoc_STR("(ControlPartCode inPart, ResType inTagName) -> (Size outMaxSize)")},
+ {"HandleControlDragTracking", (PyCFunction)CtlObj_HandleControlDragTracking, 1,
+ PyDoc_STR("(DragTrackingMessage inMessage, DragReference inDrag) -> (Boolean outLikesDrag)")},
+ {"HandleControlDragReceive", (PyCFunction)CtlObj_HandleControlDragReceive, 1,
+ PyDoc_STR("(DragReference inDrag) -> None")},
+ {"SetControlDragTrackingEnabled", (PyCFunction)CtlObj_SetControlDragTrackingEnabled, 1,
+ PyDoc_STR("(Boolean inTracks) -> None")},
+ {"IsControlDragTrackingEnabled", (PyCFunction)CtlObj_IsControlDragTrackingEnabled, 1,
+ PyDoc_STR("() -> (Boolean outTracks)")},
+ {"GetControlBounds", (PyCFunction)CtlObj_GetControlBounds, 1,
+ PyDoc_STR("() -> (Rect bounds)")},
+ {"IsControlHilited", (PyCFunction)CtlObj_IsControlHilited, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetControlHilite", (PyCFunction)CtlObj_GetControlHilite, 1,
+ PyDoc_STR("() -> (UInt16 _rv)")},
+ {"GetControlOwner", (PyCFunction)CtlObj_GetControlOwner, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"GetControlDataHandle", (PyCFunction)CtlObj_GetControlDataHandle, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"GetControlPopupMenuHandle", (PyCFunction)CtlObj_GetControlPopupMenuHandle, 1,
+ PyDoc_STR("() -> (MenuHandle _rv)")},
+ {"GetControlPopupMenuID", (PyCFunction)CtlObj_GetControlPopupMenuID, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetControlDataHandle", (PyCFunction)CtlObj_SetControlDataHandle, 1,
+ PyDoc_STR("(Handle dataHandle) -> None")},
+ {"SetControlBounds", (PyCFunction)CtlObj_SetControlBounds, 1,
+ PyDoc_STR("(Rect bounds) -> None")},
+ {"SetControlPopupMenuHandle", (PyCFunction)CtlObj_SetControlPopupMenuHandle, 1,
+ PyDoc_STR("(MenuHandle popupMenu) -> None")},
+ {"SetControlPopupMenuID", (PyCFunction)CtlObj_SetControlPopupMenuID, 1,
+ PyDoc_STR("(short menuID) -> None")},
+ {"GetBevelButtonMenuValue", (PyCFunction)CtlObj_GetBevelButtonMenuValue, 1,
+ PyDoc_STR("() -> (SInt16 outValue)")},
+ {"SetBevelButtonMenuValue", (PyCFunction)CtlObj_SetBevelButtonMenuValue, 1,
+ PyDoc_STR("(SInt16 inValue) -> None")},
+ {"GetBevelButtonMenuHandle", (PyCFunction)CtlObj_GetBevelButtonMenuHandle, 1,
+ PyDoc_STR("() -> (MenuHandle outHandle)")},
+ {"SetBevelButtonContentInfo", (PyCFunction)CtlObj_SetBevelButtonContentInfo, 1,
+ PyDoc_STR("(ControlButtonContentInfo inContent) -> None")},
+ {"SetBevelButtonTransform", (PyCFunction)CtlObj_SetBevelButtonTransform, 1,
+ PyDoc_STR("(IconTransformType transform) -> None")},
+ {"SetDisclosureTriangleLastValue", (PyCFunction)CtlObj_SetDisclosureTriangleLastValue, 1,
+ PyDoc_STR("(SInt16 inValue) -> None")},
+ {"GetTabContentRect", (PyCFunction)CtlObj_GetTabContentRect, 1,
+ PyDoc_STR("() -> (Rect outContentRect)")},
+ {"SetTabEnabled", (PyCFunction)CtlObj_SetTabEnabled, 1,
+ PyDoc_STR("(SInt16 inTabToHilite, Boolean inEnabled) -> None")},
+ {"SetImageWellContentInfo", (PyCFunction)CtlObj_SetImageWellContentInfo, 1,
+ PyDoc_STR("(ControlButtonContentInfo inContent) -> None")},
+ {"SetImageWellTransform", (PyCFunction)CtlObj_SetImageWellTransform, 1,
+ PyDoc_STR("(IconTransformType inTransform) -> None")},
+ {"GetDataBrowserViewStyle", (PyCFunction)CtlObj_GetDataBrowserViewStyle, 1,
+ PyDoc_STR("() -> (OSType style)")},
+ {"SetDataBrowserViewStyle", (PyCFunction)CtlObj_SetDataBrowserViewStyle, 1,
+ PyDoc_STR("(OSType style) -> None")},
+ {"EnableDataBrowserEditCommand", (PyCFunction)CtlObj_EnableDataBrowserEditCommand, 1,
+ PyDoc_STR("(UInt32 command) -> (Boolean _rv)")},
+ {"ExecuteDataBrowserEditCommand", (PyCFunction)CtlObj_ExecuteDataBrowserEditCommand, 1,
+ PyDoc_STR("(UInt32 command) -> None")},
+ {"GetDataBrowserSelectionAnchor", (PyCFunction)CtlObj_GetDataBrowserSelectionAnchor, 1,
+ PyDoc_STR("() -> (UInt32 first, UInt32 last)")},
+ {"MoveDataBrowserSelectionAnchor", (PyCFunction)CtlObj_MoveDataBrowserSelectionAnchor, 1,
+ PyDoc_STR("(UInt32 direction, Boolean extendSelection) -> None")},
+ {"OpenDataBrowserContainer", (PyCFunction)CtlObj_OpenDataBrowserContainer, 1,
+ PyDoc_STR("(UInt32 container) -> None")},
+ {"CloseDataBrowserContainer", (PyCFunction)CtlObj_CloseDataBrowserContainer, 1,
+ PyDoc_STR("(UInt32 container) -> None")},
+ {"SortDataBrowserContainer", (PyCFunction)CtlObj_SortDataBrowserContainer, 1,
+ PyDoc_STR("(UInt32 container, Boolean sortChildren) -> None")},
+ {"GetDataBrowserItems", (PyCFunction)CtlObj_GetDataBrowserItems, 1,
+ PyDoc_STR("(UInt32 container, Boolean recurse, UInt32 state, Handle items) -> None")},
+ {"GetDataBrowserItemCount", (PyCFunction)CtlObj_GetDataBrowserItemCount, 1,
+ PyDoc_STR("(UInt32 container, Boolean recurse, UInt32 state) -> (UInt32 numItems)")},
+ {"IsDataBrowserItemSelected", (PyCFunction)CtlObj_IsDataBrowserItemSelected, 1,
+ PyDoc_STR("(UInt32 item) -> (Boolean _rv)")},
+ {"GetDataBrowserItemState", (PyCFunction)CtlObj_GetDataBrowserItemState, 1,
+ PyDoc_STR("(UInt32 item) -> (UInt32 state)")},
+ {"RevealDataBrowserItem", (PyCFunction)CtlObj_RevealDataBrowserItem, 1,
+ PyDoc_STR("(UInt32 item, UInt32 propertyID, UInt8 options) -> None")},
+ {"SetDataBrowserActiveItems", (PyCFunction)CtlObj_SetDataBrowserActiveItems, 1,
+ PyDoc_STR("(Boolean active) -> None")},
+ {"GetDataBrowserActiveItems", (PyCFunction)CtlObj_GetDataBrowserActiveItems, 1,
+ PyDoc_STR("() -> (Boolean active)")},
+ {"SetDataBrowserScrollBarInset", (PyCFunction)CtlObj_SetDataBrowserScrollBarInset, 1,
+ PyDoc_STR("() -> (Rect insetRect)")},
+ {"GetDataBrowserScrollBarInset", (PyCFunction)CtlObj_GetDataBrowserScrollBarInset, 1,
+ PyDoc_STR("() -> (Rect insetRect)")},
+ {"SetDataBrowserTarget", (PyCFunction)CtlObj_SetDataBrowserTarget, 1,
+ PyDoc_STR("(UInt32 target) -> None")},
+ {"GetDataBrowserTarget", (PyCFunction)CtlObj_GetDataBrowserTarget, 1,
+ PyDoc_STR("() -> (UInt32 target)")},
+ {"SetDataBrowserSortOrder", (PyCFunction)CtlObj_SetDataBrowserSortOrder, 1,
+ PyDoc_STR("(UInt16 order) -> None")},
+ {"GetDataBrowserSortOrder", (PyCFunction)CtlObj_GetDataBrowserSortOrder, 1,
+ PyDoc_STR("() -> (UInt16 order)")},
+ {"SetDataBrowserScrollPosition", (PyCFunction)CtlObj_SetDataBrowserScrollPosition, 1,
+ PyDoc_STR("(UInt32 top, UInt32 left) -> None")},
+ {"GetDataBrowserScrollPosition", (PyCFunction)CtlObj_GetDataBrowserScrollPosition, 1,
+ PyDoc_STR("() -> (UInt32 top, UInt32 left)")},
+ {"SetDataBrowserHasScrollBars", (PyCFunction)CtlObj_SetDataBrowserHasScrollBars, 1,
+ PyDoc_STR("(Boolean horiz, Boolean vert) -> None")},
+ {"GetDataBrowserHasScrollBars", (PyCFunction)CtlObj_GetDataBrowserHasScrollBars, 1,
+ PyDoc_STR("() -> (Boolean horiz, Boolean vert)")},
+ {"SetDataBrowserSortProperty", (PyCFunction)CtlObj_SetDataBrowserSortProperty, 1,
+ PyDoc_STR("(UInt32 property) -> None")},
+ {"GetDataBrowserSortProperty", (PyCFunction)CtlObj_GetDataBrowserSortProperty, 1,
+ PyDoc_STR("() -> (UInt32 property)")},
+ {"SetDataBrowserSelectionFlags", (PyCFunction)CtlObj_SetDataBrowserSelectionFlags, 1,
+ PyDoc_STR("(UInt32 selectionFlags) -> None")},
+ {"GetDataBrowserSelectionFlags", (PyCFunction)CtlObj_GetDataBrowserSelectionFlags, 1,
+ PyDoc_STR("() -> (UInt32 selectionFlags)")},
+ {"SetDataBrowserPropertyFlags", (PyCFunction)CtlObj_SetDataBrowserPropertyFlags, 1,
+ PyDoc_STR("(UInt32 property, UInt32 flags) -> None")},
+ {"GetDataBrowserPropertyFlags", (PyCFunction)CtlObj_GetDataBrowserPropertyFlags, 1,
+ PyDoc_STR("(UInt32 property) -> (UInt32 flags)")},
+ {"SetDataBrowserEditText", (PyCFunction)CtlObj_SetDataBrowserEditText, 1,
+ PyDoc_STR("(CFStringRef text) -> None")},
+ {"CopyDataBrowserEditText", (PyCFunction)CtlObj_CopyDataBrowserEditText, 1,
+ PyDoc_STR("() -> (CFStringRef text)")},
+ {"GetDataBrowserEditText", (PyCFunction)CtlObj_GetDataBrowserEditText, 1,
+ PyDoc_STR("(CFMutableStringRef text) -> None")},
+ {"SetDataBrowserEditItem", (PyCFunction)CtlObj_SetDataBrowserEditItem, 1,
+ PyDoc_STR("(UInt32 item, UInt32 property) -> None")},
+ {"GetDataBrowserEditItem", (PyCFunction)CtlObj_GetDataBrowserEditItem, 1,
+ PyDoc_STR("() -> (UInt32 item, UInt32 property)")},
+ {"GetDataBrowserItemPartBounds", (PyCFunction)CtlObj_GetDataBrowserItemPartBounds, 1,
+ PyDoc_STR("(UInt32 item, UInt32 property, OSType part) -> (Rect bounds)")},
+ {"RemoveDataBrowserTableViewColumn", (PyCFunction)CtlObj_RemoveDataBrowserTableViewColumn, 1,
+ PyDoc_STR("(UInt32 column) -> None")},
+ {"GetDataBrowserTableViewColumnCount", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnCount, 1,
+ PyDoc_STR("() -> (UInt32 numColumns)")},
+ {"SetDataBrowserTableViewHiliteStyle", (PyCFunction)CtlObj_SetDataBrowserTableViewHiliteStyle, 1,
+ PyDoc_STR("(UInt32 hiliteStyle) -> None")},
+ {"GetDataBrowserTableViewHiliteStyle", (PyCFunction)CtlObj_GetDataBrowserTableViewHiliteStyle, 1,
+ PyDoc_STR("() -> (UInt32 hiliteStyle)")},
+ {"SetDataBrowserTableViewRowHeight", (PyCFunction)CtlObj_SetDataBrowserTableViewRowHeight, 1,
+ PyDoc_STR("(UInt16 height) -> None")},
+ {"GetDataBrowserTableViewRowHeight", (PyCFunction)CtlObj_GetDataBrowserTableViewRowHeight, 1,
+ PyDoc_STR("() -> (UInt16 height)")},
+ {"SetDataBrowserTableViewColumnWidth", (PyCFunction)CtlObj_SetDataBrowserTableViewColumnWidth, 1,
+ PyDoc_STR("(UInt16 width) -> None")},
+ {"GetDataBrowserTableViewColumnWidth", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnWidth, 1,
+ PyDoc_STR("() -> (UInt16 width)")},
+ {"SetDataBrowserTableViewItemRowHeight", (PyCFunction)CtlObj_SetDataBrowserTableViewItemRowHeight, 1,
+ PyDoc_STR("(UInt32 item, UInt16 height) -> None")},
+ {"GetDataBrowserTableViewItemRowHeight", (PyCFunction)CtlObj_GetDataBrowserTableViewItemRowHeight, 1,
+ PyDoc_STR("(UInt32 item) -> (UInt16 height)")},
+ {"SetDataBrowserTableViewNamedColumnWidth", (PyCFunction)CtlObj_SetDataBrowserTableViewNamedColumnWidth, 1,
+ PyDoc_STR("(UInt32 column, UInt16 width) -> None")},
+ {"GetDataBrowserTableViewNamedColumnWidth", (PyCFunction)CtlObj_GetDataBrowserTableViewNamedColumnWidth, 1,
+ PyDoc_STR("(UInt32 column) -> (UInt16 width)")},
+ {"SetDataBrowserTableViewGeometry", (PyCFunction)CtlObj_SetDataBrowserTableViewGeometry, 1,
+ PyDoc_STR("(Boolean variableWidthColumns, Boolean variableHeightRows) -> None")},
+ {"GetDataBrowserTableViewGeometry", (PyCFunction)CtlObj_GetDataBrowserTableViewGeometry, 1,
+ PyDoc_STR("() -> (Boolean variableWidthColumns, Boolean variableHeightRows)")},
+ {"GetDataBrowserTableViewItemID", (PyCFunction)CtlObj_GetDataBrowserTableViewItemID, 1,
+ PyDoc_STR("(UInt32 row) -> (UInt32 item)")},
+ {"SetDataBrowserTableViewItemRow", (PyCFunction)CtlObj_SetDataBrowserTableViewItemRow, 1,
+ PyDoc_STR("(UInt32 item, UInt32 row) -> None")},
+ {"GetDataBrowserTableViewItemRow", (PyCFunction)CtlObj_GetDataBrowserTableViewItemRow, 1,
+ PyDoc_STR("(UInt32 item) -> (UInt32 row)")},
+ {"SetDataBrowserTableViewColumnPosition", (PyCFunction)CtlObj_SetDataBrowserTableViewColumnPosition, 1,
+ PyDoc_STR("(UInt32 column, UInt32 position) -> None")},
+ {"GetDataBrowserTableViewColumnPosition", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnPosition, 1,
+ PyDoc_STR("(UInt32 column) -> (UInt32 position)")},
+ {"GetDataBrowserTableViewColumnProperty", (PyCFunction)CtlObj_GetDataBrowserTableViewColumnProperty, 1,
+ PyDoc_STR("(UInt32 column) -> (UInt32 property)")},
+ {"AutoSizeDataBrowserListViewColumns", (PyCFunction)CtlObj_AutoSizeDataBrowserListViewColumns, 1,
+ PyDoc_STR("() -> None")},
+ {"AddDataBrowserListViewColumn", (PyCFunction)CtlObj_AddDataBrowserListViewColumn, 1,
+ PyDoc_STR("(DataBrowserListViewColumnDesc columnDesc, UInt32 position) -> None")},
+ {"SetDataBrowserListViewHeaderBtnHeight", (PyCFunction)CtlObj_SetDataBrowserListViewHeaderBtnHeight, 1,
+ PyDoc_STR("(UInt16 height) -> None")},
+ {"GetDataBrowserListViewHeaderBtnHeight", (PyCFunction)CtlObj_GetDataBrowserListViewHeaderBtnHeight, 1,
+ PyDoc_STR("() -> (UInt16 height)")},
+ {"SetDataBrowserListViewUsePlainBackground", (PyCFunction)CtlObj_SetDataBrowserListViewUsePlainBackground, 1,
+ PyDoc_STR("(Boolean usePlainBackground) -> None")},
+ {"GetDataBrowserListViewUsePlainBackground", (PyCFunction)CtlObj_GetDataBrowserListViewUsePlainBackground, 1,
+ PyDoc_STR("() -> (Boolean usePlainBackground)")},
+ {"SetDataBrowserListViewDisclosureColumn", (PyCFunction)CtlObj_SetDataBrowserListViewDisclosureColumn, 1,
+ PyDoc_STR("(UInt32 column, Boolean expandableRows) -> None")},
+ {"GetDataBrowserListViewDisclosureColumn", (PyCFunction)CtlObj_GetDataBrowserListViewDisclosureColumn, 1,
+ PyDoc_STR("() -> (UInt32 column, Boolean expandableRows)")},
+ {"GetDataBrowserColumnViewPath", (PyCFunction)CtlObj_GetDataBrowserColumnViewPath, 1,
+ PyDoc_STR("(Handle path) -> None")},
+ {"GetDataBrowserColumnViewPathLength", (PyCFunction)CtlObj_GetDataBrowserColumnViewPathLength, 1,
+ PyDoc_STR("() -> (UInt32 pathLength)")},
+ {"SetDataBrowserColumnViewDisplayType", (PyCFunction)CtlObj_SetDataBrowserColumnViewDisplayType, 1,
+ PyDoc_STR("(OSType propertyType) -> None")},
+ {"GetDataBrowserColumnViewDisplayType", (PyCFunction)CtlObj_GetDataBrowserColumnViewDisplayType, 1,
+ PyDoc_STR("() -> (OSType propertyType)")},
+ {"as_Resource", (PyCFunction)CtlObj_as_Resource, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"GetControlRect", (PyCFunction)CtlObj_GetControlRect, 1,
+ PyDoc_STR("() -> (Rect rect)")},
+ {"DisposeControl", (PyCFunction)CtlObj_DisposeControl, 1,
+ PyDoc_STR("() -> None")},
+ {"TrackControl", (PyCFunction)CtlObj_TrackControl, 1,
+ PyDoc_STR("(Point startPoint [,trackercallback]) -> (ControlPartCode _rv)")},
+ {"HandleControlClick", (PyCFunction)CtlObj_HandleControlClick, 1,
+ PyDoc_STR("(Point startPoint, Integer modifiers, [,trackercallback]) -> (ControlPartCode _rv)")},
+ {"SetControlData", (PyCFunction)CtlObj_SetControlData, 1,
+ PyDoc_STR("(stuff) -> None")},
+ {"GetControlData", (PyCFunction)CtlObj_GetControlData, 1,
+ PyDoc_STR("(part, type) -> String")},
+ {"SetControlData_Handle", (PyCFunction)CtlObj_SetControlData_Handle, 1,
+ PyDoc_STR("(ResObj) -> None")},
+ {"GetControlData_Handle", (PyCFunction)CtlObj_GetControlData_Handle, 1,
+ PyDoc_STR("(part, type) -> ResObj")},
+ {"SetControlData_Callback", (PyCFunction)CtlObj_SetControlData_Callback, 1,
+ PyDoc_STR("(callbackfunc) -> None")},
+ {NULL, NULL, 0}
};
#define CtlObj_getsetlist NULL
@@ -3823,28 +3823,28 @@ static PyMethodDef CtlObj_methods[] = {
static int CtlObj_compare(ControlObject *self, ControlObject *other)
{
- unsigned long v, w;
+ unsigned long v, w;
- if (!CtlObj_Check((PyObject *)other))
- {
- v=(unsigned long)self;
- w=(unsigned long)other;
- }
- else
- {
- v=(unsigned long)self->ob_itself;
- w=(unsigned long)other->ob_itself;
- }
- if( v < w ) return -1;
- if( v > w ) return 1;
- return 0;
+ if (!CtlObj_Check((PyObject *)other))
+ {
+ v=(unsigned long)self;
+ w=(unsigned long)other;
+ }
+ else
+ {
+ v=(unsigned long)self->ob_itself;
+ w=(unsigned long)other->ob_itself;
+ }
+ if( v < w ) return -1;
+ if( v > w ) return 1;
+ return 0;
}
#define CtlObj_repr NULL
static long CtlObj_hash(ControlObject *self)
{
- return (long)self->ob_itself;
+ return (long)self->ob_itself;
}
#define CtlObj_tp_init 0
@@ -3852,61 +3852,61 @@ static long CtlObj_hash(ControlObject *self)
static PyObject *CtlObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- ControlHandle itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ ControlHandle itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CtlObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((ControlObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, CtlObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((ControlObject *)_self)->ob_itself = itself;
+ return _self;
}
#define CtlObj_tp_free PyObject_Del
PyTypeObject Control_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Ctl.Control", /*tp_name*/
- sizeof(ControlObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) CtlObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) CtlObj_compare, /*tp_compare*/
- (reprfunc) CtlObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) CtlObj_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*/
- CtlObj_methods, /* tp_methods */
- 0, /*tp_members*/
- CtlObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- CtlObj_tp_init, /* tp_init */
- CtlObj_tp_alloc, /* tp_alloc */
- CtlObj_tp_new, /* tp_new */
- CtlObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Ctl.Control", /*tp_name*/
+ sizeof(ControlObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) CtlObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) CtlObj_compare, /*tp_compare*/
+ (reprfunc) CtlObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) CtlObj_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*/
+ CtlObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ CtlObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ CtlObj_tp_init, /* tp_init */
+ CtlObj_tp_alloc, /* tp_alloc */
+ CtlObj_tp_new, /* tp_new */
+ CtlObj_tp_free, /* tp_free */
};
/* -------------------- End object type Control --------------------- */
@@ -3914,1616 +3914,1616 @@ PyTypeObject Control_Type = {
static PyObject *Ctl_NewControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlHandle _rv;
- WindowPtr owningWindow;
- Rect boundsRect;
- Str255 controlTitle;
- Boolean initiallyVisible;
- SInt16 initialValue;
- SInt16 minimumValue;
- SInt16 maximumValue;
- SInt16 procID;
- SInt32 controlReference;
+ PyObject *_res = NULL;
+ ControlHandle _rv;
+ WindowPtr owningWindow;
+ Rect boundsRect;
+ Str255 controlTitle;
+ Boolean initiallyVisible;
+ SInt16 initialValue;
+ SInt16 minimumValue;
+ SInt16 maximumValue;
+ SInt16 procID;
+ SInt32 controlReference;
#ifndef NewControl
- PyMac_PRECHECK(NewControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&bhhhhl",
- WinObj_Convert, &owningWindow,
- PyMac_GetRect, &boundsRect,
- PyMac_GetStr255, controlTitle,
- &initiallyVisible,
- &initialValue,
- &minimumValue,
- &maximumValue,
- &procID,
- &controlReference))
- return NULL;
- _rv = NewControl(owningWindow,
- &boundsRect,
- controlTitle,
- initiallyVisible,
- initialValue,
- minimumValue,
- maximumValue,
- procID,
- controlReference);
- _res = Py_BuildValue("O&",
- CtlObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(NewControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&bhhhhl",
+ WinObj_Convert, &owningWindow,
+ PyMac_GetRect, &boundsRect,
+ PyMac_GetStr255, controlTitle,
+ &initiallyVisible,
+ &initialValue,
+ &minimumValue,
+ &maximumValue,
+ &procID,
+ &controlReference))
+ return NULL;
+ _rv = NewControl(owningWindow,
+ &boundsRect,
+ controlTitle,
+ initiallyVisible,
+ initialValue,
+ minimumValue,
+ maximumValue,
+ procID,
+ controlReference);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, _rv);
+ return _res;
}
static PyObject *Ctl_GetNewControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlHandle _rv;
- SInt16 resourceID;
- WindowPtr owningWindow;
+ PyObject *_res = NULL;
+ ControlHandle _rv;
+ SInt16 resourceID;
+ WindowPtr owningWindow;
#ifndef GetNewControl
- PyMac_PRECHECK(GetNewControl);
+ PyMac_PRECHECK(GetNewControl);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &resourceID,
- WinObj_Convert, &owningWindow))
- return NULL;
- _rv = GetNewControl(resourceID,
- owningWindow);
- _res = Py_BuildValue("O&",
- CtlObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &resourceID,
+ WinObj_Convert, &owningWindow))
+ return NULL;
+ _rv = GetNewControl(resourceID,
+ owningWindow);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, _rv);
+ return _res;
}
static PyObject *Ctl_DrawControls(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr theWindow;
+ PyObject *_res = NULL;
+ WindowPtr theWindow;
#ifndef DrawControls
- PyMac_PRECHECK(DrawControls);
+ PyMac_PRECHECK(DrawControls);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &theWindow))
- return NULL;
- DrawControls(theWindow);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &theWindow))
+ return NULL;
+ DrawControls(theWindow);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_UpdateControls(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr inWindow;
- RgnHandle inUpdateRegion;
+ PyObject *_res = NULL;
+ WindowPtr inWindow;
+ RgnHandle inUpdateRegion;
#ifndef UpdateControls
- PyMac_PRECHECK(UpdateControls);
+ PyMac_PRECHECK(UpdateControls);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &inWindow,
- ResObj_Convert, &inUpdateRegion))
- return NULL;
- UpdateControls(inWindow,
- inUpdateRegion);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &inWindow,
+ ResObj_Convert, &inUpdateRegion))
+ return NULL;
+ UpdateControls(inWindow,
+ inUpdateRegion);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_FindControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlPartCode _rv;
- Point testPoint;
- WindowPtr theWindow;
- ControlHandle theControl;
+ PyObject *_res = NULL;
+ ControlPartCode _rv;
+ Point testPoint;
+ WindowPtr theWindow;
+ ControlHandle theControl;
#ifndef FindControl
- PyMac_PRECHECK(FindControl);
+ PyMac_PRECHECK(FindControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &testPoint,
- WinObj_Convert, &theWindow))
- return NULL;
- _rv = FindControl(testPoint,
- theWindow,
- &theControl);
- _res = Py_BuildValue("hO&",
- _rv,
- CtlObj_WhichControl, theControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &testPoint,
+ WinObj_Convert, &theWindow))
+ return NULL;
+ _rv = FindControl(testPoint,
+ theWindow,
+ &theControl);
+ _res = Py_BuildValue("hO&",
+ _rv,
+ CtlObj_WhichControl, theControl);
+ return _res;
}
static PyObject *Ctl_IdleControls(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr inWindow;
+ PyObject *_res = NULL;
+ WindowPtr inWindow;
#ifndef IdleControls
- PyMac_PRECHECK(IdleControls);
+ PyMac_PRECHECK(IdleControls);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- IdleControls(inWindow);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ IdleControls(inWindow);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_GetControlByID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- ControlID inID;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ ControlID inID;
+ ControlHandle outControl;
#ifndef GetControlByID
- PyMac_PRECHECK(GetControlByID);
+ PyMac_PRECHECK(GetControlByID);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &inWindow,
- PyControlID_Convert, &inID))
- return NULL;
- _err = GetControlByID(inWindow,
- &inID,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_WhichControl, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &inWindow,
+ PyControlID_Convert, &inID))
+ return NULL;
+ _err = GetControlByID(inWindow,
+ &inID,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_WhichControl, outControl);
+ return _res;
}
static PyObject *Ctl_DumpControlHierarchy(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
- FSSpec inDumpFile;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
+ FSSpec inDumpFile;
#ifndef DumpControlHierarchy
- PyMac_PRECHECK(DumpControlHierarchy);
+ PyMac_PRECHECK(DumpControlHierarchy);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &inWindow,
- PyMac_GetFSSpec, &inDumpFile))
- return NULL;
- _err = DumpControlHierarchy(inWindow,
- &inDumpFile);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &inWindow,
+ PyMac_GetFSSpec, &inDumpFile))
+ return NULL;
+ _err = DumpControlHierarchy(inWindow,
+ &inDumpFile);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_CreateRootControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
+ ControlHandle outControl;
#ifndef CreateRootControl
- PyMac_PRECHECK(CreateRootControl);
+ PyMac_PRECHECK(CreateRootControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = CreateRootControl(inWindow,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = CreateRootControl(inWindow,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_GetRootControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
+ ControlHandle outControl;
#ifndef GetRootControl
- PyMac_PRECHECK(GetRootControl);
+ PyMac_PRECHECK(GetRootControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = GetRootControl(inWindow,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_WhichControl, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = GetRootControl(inWindow,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_WhichControl, outControl);
+ return _res;
}
static PyObject *Ctl_GetKeyboardFocus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
+ ControlHandle outControl;
#ifndef GetKeyboardFocus
- PyMac_PRECHECK(GetKeyboardFocus);
+ PyMac_PRECHECK(GetKeyboardFocus);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = GetKeyboardFocus(inWindow,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_WhichControl, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = GetKeyboardFocus(inWindow,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_WhichControl, outControl);
+ return _res;
}
static PyObject *Ctl_SetKeyboardFocus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
- ControlHandle inControl;
- ControlFocusPart inPart;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
+ ControlHandle inControl;
+ ControlFocusPart inPart;
#ifndef SetKeyboardFocus
- PyMac_PRECHECK(SetKeyboardFocus);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- WinObj_Convert, &inWindow,
- CtlObj_Convert, &inControl,
- &inPart))
- return NULL;
- _err = SetKeyboardFocus(inWindow,
- inControl,
- inPart);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetKeyboardFocus);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ WinObj_Convert, &inWindow,
+ CtlObj_Convert, &inControl,
+ &inPart))
+ return NULL;
+ _err = SetKeyboardFocus(inWindow,
+ inControl,
+ inPart);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_AdvanceKeyboardFocus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
#ifndef AdvanceKeyboardFocus
- PyMac_PRECHECK(AdvanceKeyboardFocus);
+ PyMac_PRECHECK(AdvanceKeyboardFocus);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = AdvanceKeyboardFocus(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = AdvanceKeyboardFocus(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_ReverseKeyboardFocus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
#ifndef ReverseKeyboardFocus
- PyMac_PRECHECK(ReverseKeyboardFocus);
+ PyMac_PRECHECK(ReverseKeyboardFocus);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = ReverseKeyboardFocus(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = ReverseKeyboardFocus(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_ClearKeyboardFocus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr inWindow;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr inWindow;
#ifndef ClearKeyboardFocus
- PyMac_PRECHECK(ClearKeyboardFocus);
+ PyMac_PRECHECK(ClearKeyboardFocus);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = ClearKeyboardFocus(inWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = ClearKeyboardFocus(inWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_SetAutomaticControlDragTrackingEnabledForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- Boolean inTracks;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ Boolean inTracks;
#ifndef SetAutomaticControlDragTrackingEnabledForWindow
- PyMac_PRECHECK(SetAutomaticControlDragTrackingEnabledForWindow);
+ PyMac_PRECHECK(SetAutomaticControlDragTrackingEnabledForWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- WinObj_Convert, &inWindow,
- &inTracks))
- return NULL;
- _err = SetAutomaticControlDragTrackingEnabledForWindow(inWindow,
- inTracks);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ WinObj_Convert, &inWindow,
+ &inTracks))
+ return NULL;
+ _err = SetAutomaticControlDragTrackingEnabledForWindow(inWindow,
+ inTracks);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Ctl_IsAutomaticControlDragTrackingEnabledForWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- Boolean outTracks;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ Boolean outTracks;
#ifndef IsAutomaticControlDragTrackingEnabledForWindow
- PyMac_PRECHECK(IsAutomaticControlDragTrackingEnabledForWindow);
+ PyMac_PRECHECK(IsAutomaticControlDragTrackingEnabledForWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inWindow))
- return NULL;
- _err = IsAutomaticControlDragTrackingEnabledForWindow(inWindow,
- &outTracks);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- outTracks);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _err = IsAutomaticControlDragTrackingEnabledForWindow(inWindow,
+ &outTracks);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ outTracks);
+ return _res;
}
static PyObject *Ctl_CreateBevelButtonControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- UInt16 thickness;
- UInt16 behavior;
- ControlButtonContentInfo info;
- SInt16 menuID;
- UInt16 menuBehavior;
- UInt16 menuPlacement;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ UInt16 thickness;
+ UInt16 behavior;
+ ControlButtonContentInfo info;
+ SInt16 menuID;
+ UInt16 menuBehavior;
+ UInt16 menuPlacement;
+ ControlHandle outControl;
#ifndef CreateBevelButtonControl
- PyMac_PRECHECK(CreateBevelButtonControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&HHO&hHH",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &thickness,
- &behavior,
- ControlButtonContentInfo_Convert, &info,
- &menuID,
- &menuBehavior,
- &menuPlacement))
- return NULL;
- _err = CreateBevelButtonControl(window,
- &boundsRect,
- title,
- thickness,
- behavior,
- &info,
- menuID,
- menuBehavior,
- menuPlacement,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateBevelButtonControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&HHO&hHH",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &thickness,
+ &behavior,
+ ControlButtonContentInfo_Convert, &info,
+ &menuID,
+ &menuBehavior,
+ &menuPlacement))
+ return NULL;
+ _err = CreateBevelButtonControl(window,
+ &boundsRect,
+ title,
+ thickness,
+ behavior,
+ &info,
+ menuID,
+ menuBehavior,
+ menuPlacement,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateSliderControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- SInt32 value;
- SInt32 minimum;
- SInt32 maximum;
- UInt16 orientation;
- UInt16 numTickMarks;
- Boolean liveTracking;
- PyObject* liveTrackingProc;
- UniversalProcPtr c_callback;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ SInt32 value;
+ SInt32 minimum;
+ SInt32 maximum;
+ UInt16 orientation;
+ UInt16 numTickMarks;
+ Boolean liveTracking;
+ PyObject* liveTrackingProc;
+ UniversalProcPtr c_callback;
+ ControlHandle outControl;
#ifndef CreateSliderControl
- PyMac_PRECHECK(CreateSliderControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lllHHbO",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &value,
- &minimum,
- &maximum,
- &orientation,
- &numTickMarks,
- &liveTracking,
- &liveTrackingProc))
- return NULL;
- _err = CreateSliderControl(window,
- &boundsRect,
- value,
- minimum,
- maximum,
- orientation,
- numTickMarks,
- liveTracking,
- myactionproc_upp,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- setcallback(_res, kMyControlActionProcTag, liveTrackingProc, &c_callback);
- return _res;
+ PyMac_PRECHECK(CreateSliderControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lllHHbO",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &value,
+ &minimum,
+ &maximum,
+ &orientation,
+ &numTickMarks,
+ &liveTracking,
+ &liveTrackingProc))
+ return NULL;
+ _err = CreateSliderControl(window,
+ &boundsRect,
+ value,
+ minimum,
+ maximum,
+ orientation,
+ numTickMarks,
+ liveTracking,
+ myactionproc_upp,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ setcallback(_res, kMyControlActionProcTag, liveTrackingProc, &c_callback);
+ return _res;
}
static PyObject *Ctl_CreateDisclosureTriangleControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- Rect inBoundsRect;
- UInt16 inOrientation;
- CFStringRef inTitle;
- SInt32 inInitialValue;
- Boolean inDrawTitle;
- Boolean inAutoToggles;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ Rect inBoundsRect;
+ UInt16 inOrientation;
+ CFStringRef inTitle;
+ SInt32 inInitialValue;
+ Boolean inDrawTitle;
+ Boolean inAutoToggles;
+ ControlHandle outControl;
#ifndef CreateDisclosureTriangleControl
- PyMac_PRECHECK(CreateDisclosureTriangleControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&HO&lbb",
- WinObj_Convert, &inWindow,
- PyMac_GetRect, &inBoundsRect,
- &inOrientation,
- CFStringRefObj_Convert, &inTitle,
- &inInitialValue,
- &inDrawTitle,
- &inAutoToggles))
- return NULL;
- _err = CreateDisclosureTriangleControl(inWindow,
- &inBoundsRect,
- inOrientation,
- inTitle,
- inInitialValue,
- inDrawTitle,
- inAutoToggles,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateDisclosureTriangleControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&HO&lbb",
+ WinObj_Convert, &inWindow,
+ PyMac_GetRect, &inBoundsRect,
+ &inOrientation,
+ CFStringRefObj_Convert, &inTitle,
+ &inInitialValue,
+ &inDrawTitle,
+ &inAutoToggles))
+ return NULL;
+ _err = CreateDisclosureTriangleControl(inWindow,
+ &inBoundsRect,
+ inOrientation,
+ inTitle,
+ inInitialValue,
+ inDrawTitle,
+ inAutoToggles,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateProgressBarControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- SInt32 value;
- SInt32 minimum;
- SInt32 maximum;
- Boolean indeterminate;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ SInt32 value;
+ SInt32 minimum;
+ SInt32 maximum;
+ Boolean indeterminate;
+ ControlHandle outControl;
#ifndef CreateProgressBarControl
- PyMac_PRECHECK(CreateProgressBarControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lllb",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &value,
- &minimum,
- &maximum,
- &indeterminate))
- return NULL;
- _err = CreateProgressBarControl(window,
- &boundsRect,
- value,
- minimum,
- maximum,
- indeterminate,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateProgressBarControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lllb",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &value,
+ &minimum,
+ &maximum,
+ &indeterminate))
+ return NULL;
+ _err = CreateProgressBarControl(window,
+ &boundsRect,
+ value,
+ minimum,
+ maximum,
+ indeterminate,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateRelevanceBarControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- SInt32 value;
- SInt32 minimum;
- SInt32 maximum;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ SInt32 value;
+ SInt32 minimum;
+ SInt32 maximum;
+ ControlHandle outControl;
#ifndef CreateRelevanceBarControl
- PyMac_PRECHECK(CreateRelevanceBarControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lll",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &value,
- &minimum,
- &maximum))
- return NULL;
- _err = CreateRelevanceBarControl(window,
- &boundsRect,
- value,
- minimum,
- maximum,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateRelevanceBarControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lll",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &value,
+ &minimum,
+ &maximum))
+ return NULL;
+ _err = CreateRelevanceBarControl(window,
+ &boundsRect,
+ value,
+ minimum,
+ maximum,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateLittleArrowsControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- SInt32 value;
- SInt32 minimum;
- SInt32 maximum;
- SInt32 increment;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ SInt32 value;
+ SInt32 minimum;
+ SInt32 maximum;
+ SInt32 increment;
+ ControlHandle outControl;
#ifndef CreateLittleArrowsControl
- PyMac_PRECHECK(CreateLittleArrowsControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&llll",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &value,
- &minimum,
- &maximum,
- &increment))
- return NULL;
- _err = CreateLittleArrowsControl(window,
- &boundsRect,
- value,
- minimum,
- maximum,
- increment,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateLittleArrowsControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&llll",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &value,
+ &minimum,
+ &maximum,
+ &increment))
+ return NULL;
+ _err = CreateLittleArrowsControl(window,
+ &boundsRect,
+ value,
+ minimum,
+ maximum,
+ increment,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateChasingArrowsControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ ControlHandle outControl;
#ifndef CreateChasingArrowsControl
- PyMac_PRECHECK(CreateChasingArrowsControl);
+ PyMac_PRECHECK(CreateChasingArrowsControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect))
- return NULL;
- _err = CreateChasingArrowsControl(window,
- &boundsRect,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect))
+ return NULL;
+ _err = CreateChasingArrowsControl(window,
+ &boundsRect,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateSeparatorControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ ControlHandle outControl;
#ifndef CreateSeparatorControl
- PyMac_PRECHECK(CreateSeparatorControl);
+ PyMac_PRECHECK(CreateSeparatorControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect))
- return NULL;
- _err = CreateSeparatorControl(window,
- &boundsRect,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect))
+ return NULL;
+ _err = CreateSeparatorControl(window,
+ &boundsRect,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateGroupBoxControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- Boolean primary;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ Boolean primary;
+ ControlHandle outControl;
#ifndef CreateGroupBoxControl
- PyMac_PRECHECK(CreateGroupBoxControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&b",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &primary))
- return NULL;
- _err = CreateGroupBoxControl(window,
- &boundsRect,
- title,
- primary,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateGroupBoxControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&b",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &primary))
+ return NULL;
+ _err = CreateGroupBoxControl(window,
+ &boundsRect,
+ title,
+ primary,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateCheckGroupBoxControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- SInt32 initialValue;
- Boolean primary;
- Boolean autoToggle;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ SInt32 initialValue;
+ Boolean primary;
+ Boolean autoToggle;
+ ControlHandle outControl;
#ifndef CreateCheckGroupBoxControl
- PyMac_PRECHECK(CreateCheckGroupBoxControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&lbb",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &initialValue,
- &primary,
- &autoToggle))
- return NULL;
- _err = CreateCheckGroupBoxControl(window,
- &boundsRect,
- title,
- initialValue,
- primary,
- autoToggle,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateCheckGroupBoxControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&lbb",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &initialValue,
+ &primary,
+ &autoToggle))
+ return NULL;
+ _err = CreateCheckGroupBoxControl(window,
+ &boundsRect,
+ title,
+ initialValue,
+ primary,
+ autoToggle,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreatePopupGroupBoxControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- Boolean primary;
- SInt16 menuID;
- Boolean variableWidth;
- SInt16 titleWidth;
- SInt16 titleJustification;
- Style titleStyle;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ Boolean primary;
+ SInt16 menuID;
+ Boolean variableWidth;
+ SInt16 titleWidth;
+ SInt16 titleJustification;
+ Style titleStyle;
+ ControlHandle outControl;
#ifndef CreatePopupGroupBoxControl
- PyMac_PRECHECK(CreatePopupGroupBoxControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&bhbhhb",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &primary,
- &menuID,
- &variableWidth,
- &titleWidth,
- &titleJustification,
- &titleStyle))
- return NULL;
- _err = CreatePopupGroupBoxControl(window,
- &boundsRect,
- title,
- primary,
- menuID,
- variableWidth,
- titleWidth,
- titleJustification,
- titleStyle,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreatePopupGroupBoxControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&bhbhhb",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &primary,
+ &menuID,
+ &variableWidth,
+ &titleWidth,
+ &titleJustification,
+ &titleStyle))
+ return NULL;
+ _err = CreatePopupGroupBoxControl(window,
+ &boundsRect,
+ title,
+ primary,
+ menuID,
+ variableWidth,
+ titleWidth,
+ titleJustification,
+ titleStyle,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateImageWellControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- ControlButtonContentInfo info;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ ControlButtonContentInfo info;
+ ControlHandle outControl;
#ifndef CreateImageWellControl
- PyMac_PRECHECK(CreateImageWellControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- ControlButtonContentInfo_Convert, &info))
- return NULL;
- _err = CreateImageWellControl(window,
- &boundsRect,
- &info,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateImageWellControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ ControlButtonContentInfo_Convert, &info))
+ return NULL;
+ _err = CreateImageWellControl(window,
+ &boundsRect,
+ &info,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreatePopupArrowControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- UInt16 orientation;
- UInt16 size;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ UInt16 orientation;
+ UInt16 size;
+ ControlHandle outControl;
#ifndef CreatePopupArrowControl
- PyMac_PRECHECK(CreatePopupArrowControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&HH",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &orientation,
- &size))
- return NULL;
- _err = CreatePopupArrowControl(window,
- &boundsRect,
- orientation,
- size,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreatePopupArrowControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&HH",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &orientation,
+ &size))
+ return NULL;
+ _err = CreatePopupArrowControl(window,
+ &boundsRect,
+ orientation,
+ size,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreatePlacardControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ ControlHandle outControl;
#ifndef CreatePlacardControl
- PyMac_PRECHECK(CreatePlacardControl);
+ PyMac_PRECHECK(CreatePlacardControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect))
- return NULL;
- _err = CreatePlacardControl(window,
- &boundsRect,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect))
+ return NULL;
+ _err = CreatePlacardControl(window,
+ &boundsRect,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateClockControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- UInt16 clockType;
- UInt32 clockFlags;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ UInt16 clockType;
+ UInt32 clockFlags;
+ ControlHandle outControl;
#ifndef CreateClockControl
- PyMac_PRECHECK(CreateClockControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&Hl",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &clockType,
- &clockFlags))
- return NULL;
- _err = CreateClockControl(window,
- &boundsRect,
- clockType,
- clockFlags,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateClockControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&Hl",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &clockType,
+ &clockFlags))
+ return NULL;
+ _err = CreateClockControl(window,
+ &boundsRect,
+ clockType,
+ clockFlags,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateUserPaneControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- UInt32 features;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ UInt32 features;
+ ControlHandle outControl;
#ifndef CreateUserPaneControl
- PyMac_PRECHECK(CreateUserPaneControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &features))
- return NULL;
- _err = CreateUserPaneControl(window,
- &boundsRect,
- features,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateUserPaneControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &features))
+ return NULL;
+ _err = CreateUserPaneControl(window,
+ &boundsRect,
+ features,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateEditTextControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef text;
- Boolean isPassword;
- Boolean useInlineInput;
- ControlFontStyleRec style;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef text;
+ Boolean isPassword;
+ Boolean useInlineInput;
+ ControlFontStyleRec style;
+ ControlHandle outControl;
#ifndef CreateEditTextControl
- PyMac_PRECHECK(CreateEditTextControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&bbO&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &text,
- &isPassword,
- &useInlineInput,
- ControlFontStyle_Convert, &style))
- return NULL;
- _err = CreateEditTextControl(window,
- &boundsRect,
- text,
- isPassword,
- useInlineInput,
- &style,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateEditTextControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&bbO&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &text,
+ &isPassword,
+ &useInlineInput,
+ ControlFontStyle_Convert, &style))
+ return NULL;
+ _err = CreateEditTextControl(window,
+ &boundsRect,
+ text,
+ isPassword,
+ useInlineInput,
+ &style,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateStaticTextControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef text;
- ControlFontStyleRec style;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef text;
+ ControlFontStyleRec style;
+ ControlHandle outControl;
#ifndef CreateStaticTextControl
- PyMac_PRECHECK(CreateStaticTextControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &text,
- ControlFontStyle_Convert, &style))
- return NULL;
- _err = CreateStaticTextControl(window,
- &boundsRect,
- text,
- &style,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateStaticTextControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &text,
+ ControlFontStyle_Convert, &style))
+ return NULL;
+ _err = CreateStaticTextControl(window,
+ &boundsRect,
+ text,
+ &style,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreatePictureControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- ControlButtonContentInfo content;
- Boolean dontTrack;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ ControlButtonContentInfo content;
+ Boolean dontTrack;
+ ControlHandle outControl;
#ifndef CreatePictureControl
- PyMac_PRECHECK(CreatePictureControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&b",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- ControlButtonContentInfo_Convert, &content,
- &dontTrack))
- return NULL;
- _err = CreatePictureControl(window,
- &boundsRect,
- &content,
- dontTrack,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreatePictureControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&b",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ ControlButtonContentInfo_Convert, &content,
+ &dontTrack))
+ return NULL;
+ _err = CreatePictureControl(window,
+ &boundsRect,
+ &content,
+ dontTrack,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateIconControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- Rect inBoundsRect;
- ControlButtonContentInfo inIconContent;
- Boolean inDontTrack;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ Rect inBoundsRect;
+ ControlButtonContentInfo inIconContent;
+ Boolean inDontTrack;
+ ControlHandle outControl;
#ifndef CreateIconControl
- PyMac_PRECHECK(CreateIconControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&b",
- WinObj_Convert, &inWindow,
- PyMac_GetRect, &inBoundsRect,
- ControlButtonContentInfo_Convert, &inIconContent,
- &inDontTrack))
- return NULL;
- _err = CreateIconControl(inWindow,
- &inBoundsRect,
- &inIconContent,
- inDontTrack,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateIconControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&b",
+ WinObj_Convert, &inWindow,
+ PyMac_GetRect, &inBoundsRect,
+ ControlButtonContentInfo_Convert, &inIconContent,
+ &inDontTrack))
+ return NULL;
+ _err = CreateIconControl(inWindow,
+ &inBoundsRect,
+ &inIconContent,
+ inDontTrack,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateWindowHeaderControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- Boolean isListHeader;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ Boolean isListHeader;
+ ControlHandle outControl;
#ifndef CreateWindowHeaderControl
- PyMac_PRECHECK(CreateWindowHeaderControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&b",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &isListHeader))
- return NULL;
- _err = CreateWindowHeaderControl(window,
- &boundsRect,
- isListHeader,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateWindowHeaderControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&b",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &isListHeader))
+ return NULL;
+ _err = CreateWindowHeaderControl(window,
+ &boundsRect,
+ isListHeader,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreatePushButtonControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ ControlHandle outControl;
#ifndef CreatePushButtonControl
- PyMac_PRECHECK(CreatePushButtonControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title))
- return NULL;
- _err = CreatePushButtonControl(window,
- &boundsRect,
- title,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreatePushButtonControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title))
+ return NULL;
+ _err = CreatePushButtonControl(window,
+ &boundsRect,
+ title,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreatePushButtonWithIconControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- ControlButtonContentInfo icon;
- UInt16 iconAlignment;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ ControlButtonContentInfo icon;
+ UInt16 iconAlignment;
+ ControlHandle outControl;
#ifndef CreatePushButtonWithIconControl
- PyMac_PRECHECK(CreatePushButtonWithIconControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&H",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- ControlButtonContentInfo_Convert, &icon,
- &iconAlignment))
- return NULL;
- _err = CreatePushButtonWithIconControl(window,
- &boundsRect,
- title,
- &icon,
- iconAlignment,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreatePushButtonWithIconControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&H",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ ControlButtonContentInfo_Convert, &icon,
+ &iconAlignment))
+ return NULL;
+ _err = CreatePushButtonWithIconControl(window,
+ &boundsRect,
+ title,
+ &icon,
+ iconAlignment,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateRadioButtonControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- SInt32 initialValue;
- Boolean autoToggle;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ SInt32 initialValue;
+ Boolean autoToggle;
+ ControlHandle outControl;
#ifndef CreateRadioButtonControl
- PyMac_PRECHECK(CreateRadioButtonControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&lb",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &initialValue,
- &autoToggle))
- return NULL;
- _err = CreateRadioButtonControl(window,
- &boundsRect,
- title,
- initialValue,
- autoToggle,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateRadioButtonControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&lb",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &initialValue,
+ &autoToggle))
+ return NULL;
+ _err = CreateRadioButtonControl(window,
+ &boundsRect,
+ title,
+ initialValue,
+ autoToggle,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateCheckBoxControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- SInt32 initialValue;
- Boolean autoToggle;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ SInt32 initialValue;
+ Boolean autoToggle;
+ ControlHandle outControl;
#ifndef CreateCheckBoxControl
- PyMac_PRECHECK(CreateCheckBoxControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&lb",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &initialValue,
- &autoToggle))
- return NULL;
- _err = CreateCheckBoxControl(window,
- &boundsRect,
- title,
- initialValue,
- autoToggle,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateCheckBoxControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&lb",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &initialValue,
+ &autoToggle))
+ return NULL;
+ _err = CreateCheckBoxControl(window,
+ &boundsRect,
+ title,
+ initialValue,
+ autoToggle,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateScrollBarControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- SInt32 value;
- SInt32 minimum;
- SInt32 maximum;
- SInt32 viewSize;
- Boolean liveTracking;
- PyObject* liveTrackingProc;
- UniversalProcPtr c_callback;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ SInt32 value;
+ SInt32 minimum;
+ SInt32 maximum;
+ SInt32 viewSize;
+ Boolean liveTracking;
+ PyObject* liveTrackingProc;
+ UniversalProcPtr c_callback;
+ ControlHandle outControl;
#ifndef CreateScrollBarControl
- PyMac_PRECHECK(CreateScrollBarControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&llllbO",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &value,
- &minimum,
- &maximum,
- &viewSize,
- &liveTracking,
- &liveTrackingProc))
- return NULL;
- _err = CreateScrollBarControl(window,
- &boundsRect,
- value,
- minimum,
- maximum,
- viewSize,
- liveTracking,
- myactionproc_upp,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- setcallback(_res, kMyControlActionProcTag, liveTrackingProc, &c_callback);
- return _res;
+ PyMac_PRECHECK(CreateScrollBarControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&llllbO",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &value,
+ &minimum,
+ &maximum,
+ &viewSize,
+ &liveTracking,
+ &liveTrackingProc))
+ return NULL;
+ _err = CreateScrollBarControl(window,
+ &boundsRect,
+ value,
+ minimum,
+ maximum,
+ viewSize,
+ liveTracking,
+ myactionproc_upp,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ setcallback(_res, kMyControlActionProcTag, liveTrackingProc, &c_callback);
+ return _res;
}
static PyObject *Ctl_CreatePopupButtonControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef title;
- SInt16 menuID;
- Boolean variableWidth;
- SInt16 titleWidth;
- SInt16 titleJustification;
- Style titleStyle;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef title;
+ SInt16 menuID;
+ Boolean variableWidth;
+ SInt16 titleWidth;
+ SInt16 titleJustification;
+ Style titleStyle;
+ ControlHandle outControl;
#ifndef CreatePopupButtonControl
- PyMac_PRECHECK(CreatePopupButtonControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&hbhhb",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &title,
- &menuID,
- &variableWidth,
- &titleWidth,
- &titleJustification,
- &titleStyle))
- return NULL;
- _err = CreatePopupButtonControl(window,
- &boundsRect,
- title,
- menuID,
- variableWidth,
- titleWidth,
- titleJustification,
- titleStyle,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreatePopupButtonControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&hbhhb",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &title,
+ &menuID,
+ &variableWidth,
+ &titleWidth,
+ &titleJustification,
+ &titleStyle))
+ return NULL;
+ _err = CreatePopupButtonControl(window,
+ &boundsRect,
+ title,
+ menuID,
+ variableWidth,
+ titleWidth,
+ titleJustification,
+ titleStyle,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateRadioGroupControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ ControlHandle outControl;
#ifndef CreateRadioGroupControl
- PyMac_PRECHECK(CreateRadioGroupControl);
+ PyMac_PRECHECK(CreateRadioGroupControl);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect))
- return NULL;
- _err = CreateRadioGroupControl(window,
- &boundsRect,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect))
+ return NULL;
+ _err = CreateRadioGroupControl(window,
+ &boundsRect,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateScrollingTextBoxControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- SInt16 contentResID;
- Boolean autoScroll;
- UInt32 delayBeforeAutoScroll;
- UInt32 delayBetweenAutoScroll;
- UInt16 autoScrollAmount;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ SInt16 contentResID;
+ Boolean autoScroll;
+ UInt32 delayBeforeAutoScroll;
+ UInt32 delayBetweenAutoScroll;
+ UInt16 autoScrollAmount;
+ ControlHandle outControl;
#ifndef CreateScrollingTextBoxControl
- PyMac_PRECHECK(CreateScrollingTextBoxControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hbllH",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &contentResID,
- &autoScroll,
- &delayBeforeAutoScroll,
- &delayBetweenAutoScroll,
- &autoScrollAmount))
- return NULL;
- _err = CreateScrollingTextBoxControl(window,
- &boundsRect,
- contentResID,
- autoScroll,
- delayBeforeAutoScroll,
- delayBetweenAutoScroll,
- autoScrollAmount,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateScrollingTextBoxControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hbllH",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &contentResID,
+ &autoScroll,
+ &delayBeforeAutoScroll,
+ &delayBetweenAutoScroll,
+ &autoScrollAmount))
+ return NULL;
+ _err = CreateScrollingTextBoxControl(window,
+ &boundsRect,
+ contentResID,
+ autoScroll,
+ delayBeforeAutoScroll,
+ delayBetweenAutoScroll,
+ autoScrollAmount,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateDisclosureButtonControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- Rect inBoundsRect;
- SInt32 inValue;
- Boolean inAutoToggles;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ Rect inBoundsRect;
+ SInt32 inValue;
+ Boolean inAutoToggles;
+ ControlHandle outControl;
#ifndef CreateDisclosureButtonControl
- PyMac_PRECHECK(CreateDisclosureButtonControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lb",
- WinObj_Convert, &inWindow,
- PyMac_GetRect, &inBoundsRect,
- &inValue,
- &inAutoToggles))
- return NULL;
- _err = CreateDisclosureButtonControl(inWindow,
- &inBoundsRect,
- inValue,
- inAutoToggles,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateDisclosureButtonControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lb",
+ WinObj_Convert, &inWindow,
+ PyMac_GetRect, &inBoundsRect,
+ &inValue,
+ &inAutoToggles))
+ return NULL;
+ _err = CreateDisclosureButtonControl(inWindow,
+ &inBoundsRect,
+ inValue,
+ inAutoToggles,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateRoundButtonControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inWindow;
- Rect inBoundsRect;
- SInt16 inSize;
- ControlButtonContentInfo inContent;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inWindow;
+ Rect inBoundsRect;
+ SInt16 inSize;
+ ControlButtonContentInfo inContent;
+ ControlHandle outControl;
#ifndef CreateRoundButtonControl
- PyMac_PRECHECK(CreateRoundButtonControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hO&",
- WinObj_Convert, &inWindow,
- PyMac_GetRect, &inBoundsRect,
- &inSize,
- ControlButtonContentInfo_Convert, &inContent))
- return NULL;
- _err = CreateRoundButtonControl(inWindow,
- &inBoundsRect,
- inSize,
- &inContent,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateRoundButtonControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hO&",
+ WinObj_Convert, &inWindow,
+ PyMac_GetRect, &inBoundsRect,
+ &inSize,
+ ControlButtonContentInfo_Convert, &inContent))
+ return NULL;
+ _err = CreateRoundButtonControl(inWindow,
+ &inBoundsRect,
+ inSize,
+ &inContent,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateDataBrowserControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- OSType style;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ OSType style;
+ ControlHandle outControl;
#ifndef CreateDataBrowserControl
- PyMac_PRECHECK(CreateDataBrowserControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- PyMac_GetOSType, &style))
- return NULL;
- _err = CreateDataBrowserControl(window,
- &boundsRect,
- style,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateDataBrowserControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ PyMac_GetOSType, &style))
+ return NULL;
+ _err = CreateDataBrowserControl(window,
+ &boundsRect,
+ style,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_CreateEditUnicodeTextControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- CFStringRef text;
- Boolean isPassword;
- ControlFontStyleRec style;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ CFStringRef text;
+ Boolean isPassword;
+ ControlFontStyleRec style;
+ ControlHandle outControl;
#ifndef CreateEditUnicodeTextControl
- PyMac_PRECHECK(CreateEditUnicodeTextControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&bO&",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- CFStringRefObj_Convert, &text,
- &isPassword,
- ControlFontStyle_Convert, &style))
- return NULL;
- _err = CreateEditUnicodeTextControl(window,
- &boundsRect,
- text,
- isPassword,
- &style,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateEditUnicodeTextControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&bO&",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ CFStringRefObj_Convert, &text,
+ &isPassword,
+ ControlFontStyle_Convert, &style))
+ return NULL;
+ _err = CreateEditUnicodeTextControl(window,
+ &boundsRect,
+ text,
+ isPassword,
+ &style,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *Ctl_FindControlUnderMouse(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlHandle _rv;
- Point inWhere;
- WindowPtr inWindow;
- SInt16 outPart;
+ PyObject *_res = NULL;
+ ControlHandle _rv;
+ Point inWhere;
+ WindowPtr inWindow;
+ SInt16 outPart;
#ifndef FindControlUnderMouse
- PyMac_PRECHECK(FindControlUnderMouse);
+ PyMac_PRECHECK(FindControlUnderMouse);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &inWhere,
- WinObj_Convert, &inWindow))
- return NULL;
- _rv = FindControlUnderMouse(inWhere,
- inWindow,
- &outPart);
- _res = Py_BuildValue("O&h",
- CtlObj_WhichControl, _rv,
- outPart);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &inWhere,
+ WinObj_Convert, &inWindow))
+ return NULL;
+ _rv = FindControlUnderMouse(inWhere,
+ inWindow,
+ &outPart);
+ _res = Py_BuildValue("O&h",
+ CtlObj_WhichControl, _rv,
+ outPart);
+ return _res;
}
static PyObject *Ctl_as_Control(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlHandle _rv;
- Handle h;
+ PyObject *_res = NULL;
+ ControlHandle _rv;
+ Handle h;
#ifndef as_Control
- PyMac_PRECHECK(as_Control);
+ PyMac_PRECHECK(as_Control);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &h))
- return NULL;
- _rv = as_Control(h);
- _res = Py_BuildValue("O&",
- CtlObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = as_Control(h);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, _rv);
+ return _res;
}
static PyObject *Ctl_CreateTabsControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr window;
- Rect boundsRect;
- UInt16 size;
- UInt16 direction;
- int i;
- UInt16 numTabs;
- ControlTabEntry tabArray[MAXTABS];
- ControlHandle outControl;
- PyObject *tabArrayObj, *tabEntry;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr window;
+ Rect boundsRect;
+ UInt16 size;
+ UInt16 direction;
+ int i;
+ UInt16 numTabs;
+ ControlTabEntry tabArray[MAXTABS];
+ ControlHandle outControl;
+ PyObject *tabArrayObj, *tabEntry;
#ifndef CreateTabsControl
- PyMac_PRECHECK(CreateTabsControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&HHO",
- WinObj_Convert, &window,
- PyMac_GetRect, &boundsRect,
- &size,
- &direction,
- &tabArrayObj))
- return NULL;
-
- i = PySequence_Length(tabArrayObj);
- if (i == -1)
- return NULL;
- if (i > MAXTABS) {
- PyErr_SetString(Ctl_Error, "Too many tabs");
- return NULL;
- }
- numTabs = i;
- for (i=0; i<numTabs; i++) {
- tabEntry = PySequence_GetItem(tabArrayObj, i);
- if (tabEntry == NULL)
- return NULL;
- if (!PyArg_Parse(tabEntry, "(O&O&B)",
- ControlButtonContentInfo_Convert, &tabArray[i].icon,
- CFStringRefObj_Convert, &tabArray[i].name,
- &tabArray[i].enabled
- ))
- return NULL;
- }
-
- _err = CreateTabsControl(window,
- &boundsRect,
- size,
- direction,
- numTabs,
- tabArray,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ PyMac_PRECHECK(CreateTabsControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&HHO",
+ WinObj_Convert, &window,
+ PyMac_GetRect, &boundsRect,
+ &size,
+ &direction,
+ &tabArrayObj))
+ return NULL;
+
+ i = PySequence_Length(tabArrayObj);
+ if (i == -1)
+ return NULL;
+ if (i > MAXTABS) {
+ PyErr_SetString(Ctl_Error, "Too many tabs");
+ return NULL;
+ }
+ numTabs = i;
+ for (i=0; i<numTabs; i++) {
+ tabEntry = PySequence_GetItem(tabArrayObj, i);
+ if (tabEntry == NULL)
+ return NULL;
+ if (!PyArg_Parse(tabEntry, "(O&O&B)",
+ ControlButtonContentInfo_Convert, &tabArray[i].icon,
+ CFStringRefObj_Convert, &tabArray[i].name,
+ &tabArray[i].enabled
+ ))
+ return NULL;
+ }
+
+ _err = CreateTabsControl(window,
+ &boundsRect,
+ size,
+ direction,
+ numTabs,
+ tabArray,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyMethodDef Ctl_methods[] = {
- {"NewControl", (PyCFunction)Ctl_NewControl, 1,
- PyDoc_STR("(WindowPtr owningWindow, Rect boundsRect, Str255 controlTitle, Boolean initiallyVisible, SInt16 initialValue, SInt16 minimumValue, SInt16 maximumValue, SInt16 procID, SInt32 controlReference) -> (ControlHandle _rv)")},
- {"GetNewControl", (PyCFunction)Ctl_GetNewControl, 1,
- PyDoc_STR("(SInt16 resourceID, WindowPtr owningWindow) -> (ControlHandle _rv)")},
- {"DrawControls", (PyCFunction)Ctl_DrawControls, 1,
- PyDoc_STR("(WindowPtr theWindow) -> None")},
- {"UpdateControls", (PyCFunction)Ctl_UpdateControls, 1,
- PyDoc_STR("(WindowPtr inWindow, RgnHandle inUpdateRegion) -> None")},
- {"FindControl", (PyCFunction)Ctl_FindControl, 1,
- PyDoc_STR("(Point testPoint, WindowPtr theWindow) -> (ControlPartCode _rv, ControlHandle theControl)")},
- {"IdleControls", (PyCFunction)Ctl_IdleControls, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"GetControlByID", (PyCFunction)Ctl_GetControlByID, 1,
- PyDoc_STR("(WindowPtr inWindow, ControlID inID) -> (ControlHandle outControl)")},
- {"DumpControlHierarchy", (PyCFunction)Ctl_DumpControlHierarchy, 1,
- PyDoc_STR("(WindowPtr inWindow, FSSpec inDumpFile) -> None")},
- {"CreateRootControl", (PyCFunction)Ctl_CreateRootControl, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
- {"GetRootControl", (PyCFunction)Ctl_GetRootControl, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
- {"GetKeyboardFocus", (PyCFunction)Ctl_GetKeyboardFocus, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
- {"SetKeyboardFocus", (PyCFunction)Ctl_SetKeyboardFocus, 1,
- PyDoc_STR("(WindowPtr inWindow, ControlHandle inControl, ControlFocusPart inPart) -> None")},
- {"AdvanceKeyboardFocus", (PyCFunction)Ctl_AdvanceKeyboardFocus, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"ReverseKeyboardFocus", (PyCFunction)Ctl_ReverseKeyboardFocus, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"ClearKeyboardFocus", (PyCFunction)Ctl_ClearKeyboardFocus, 1,
- PyDoc_STR("(WindowPtr inWindow) -> None")},
- {"SetAutomaticControlDragTrackingEnabledForWindow", (PyCFunction)Ctl_SetAutomaticControlDragTrackingEnabledForWindow, 1,
- PyDoc_STR("(WindowPtr inWindow, Boolean inTracks) -> None")},
- {"IsAutomaticControlDragTrackingEnabledForWindow", (PyCFunction)Ctl_IsAutomaticControlDragTrackingEnabledForWindow, 1,
- PyDoc_STR("(WindowPtr inWindow) -> (Boolean outTracks)")},
- {"CreateBevelButtonControl", (PyCFunction)Ctl_CreateBevelButtonControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, UInt16 thickness, UInt16 behavior, ControlButtonContentInfo info, SInt16 menuID, UInt16 menuBehavior, UInt16 menuPlacement) -> (ControlHandle outControl)")},
- {"CreateSliderControl", (PyCFunction)Ctl_CreateSliderControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, UInt16 orientation, UInt16 numTickMarks, Boolean liveTracking, PyObject* liveTrackingProc) -> (ControlHandle outControl)")},
- {"CreateDisclosureTriangleControl", (PyCFunction)Ctl_CreateDisclosureTriangleControl, 1,
- PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, UInt16 inOrientation, CFStringRef inTitle, SInt32 inInitialValue, Boolean inDrawTitle, Boolean inAutoToggles) -> (ControlHandle outControl)")},
- {"CreateProgressBarControl", (PyCFunction)Ctl_CreateProgressBarControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, Boolean indeterminate) -> (ControlHandle outControl)")},
- {"CreateRelevanceBarControl", (PyCFunction)Ctl_CreateRelevanceBarControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum) -> (ControlHandle outControl)")},
- {"CreateLittleArrowsControl", (PyCFunction)Ctl_CreateLittleArrowsControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, SInt32 increment) -> (ControlHandle outControl)")},
- {"CreateChasingArrowsControl", (PyCFunction)Ctl_CreateChasingArrowsControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
- {"CreateSeparatorControl", (PyCFunction)Ctl_CreateSeparatorControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
- {"CreateGroupBoxControl", (PyCFunction)Ctl_CreateGroupBoxControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, Boolean primary) -> (ControlHandle outControl)")},
- {"CreateCheckGroupBoxControl", (PyCFunction)Ctl_CreateCheckGroupBoxControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt32 initialValue, Boolean primary, Boolean autoToggle) -> (ControlHandle outControl)")},
- {"CreatePopupGroupBoxControl", (PyCFunction)Ctl_CreatePopupGroupBoxControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, Boolean primary, SInt16 menuID, Boolean variableWidth, SInt16 titleWidth, SInt16 titleJustification, Style titleStyle) -> (ControlHandle outControl)")},
- {"CreateImageWellControl", (PyCFunction)Ctl_CreateImageWellControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, ControlButtonContentInfo info) -> (ControlHandle outControl)")},
- {"CreatePopupArrowControl", (PyCFunction)Ctl_CreatePopupArrowControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt16 orientation, UInt16 size) -> (ControlHandle outControl)")},
- {"CreatePlacardControl", (PyCFunction)Ctl_CreatePlacardControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
- {"CreateClockControl", (PyCFunction)Ctl_CreateClockControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt16 clockType, UInt32 clockFlags) -> (ControlHandle outControl)")},
- {"CreateUserPaneControl", (PyCFunction)Ctl_CreateUserPaneControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt32 features) -> (ControlHandle outControl)")},
- {"CreateEditTextControl", (PyCFunction)Ctl_CreateEditTextControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef text, Boolean isPassword, Boolean useInlineInput, ControlFontStyleRec style) -> (ControlHandle outControl)")},
- {"CreateStaticTextControl", (PyCFunction)Ctl_CreateStaticTextControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef text, ControlFontStyleRec style) -> (ControlHandle outControl)")},
- {"CreatePictureControl", (PyCFunction)Ctl_CreatePictureControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, ControlButtonContentInfo content, Boolean dontTrack) -> (ControlHandle outControl)")},
- {"CreateIconControl", (PyCFunction)Ctl_CreateIconControl, 1,
- PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, ControlButtonContentInfo inIconContent, Boolean inDontTrack) -> (ControlHandle outControl)")},
- {"CreateWindowHeaderControl", (PyCFunction)Ctl_CreateWindowHeaderControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, Boolean isListHeader) -> (ControlHandle outControl)")},
- {"CreatePushButtonControl", (PyCFunction)Ctl_CreatePushButtonControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title) -> (ControlHandle outControl)")},
- {"CreatePushButtonWithIconControl", (PyCFunction)Ctl_CreatePushButtonWithIconControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, ControlButtonContentInfo icon, UInt16 iconAlignment) -> (ControlHandle outControl)")},
- {"CreateRadioButtonControl", (PyCFunction)Ctl_CreateRadioButtonControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt32 initialValue, Boolean autoToggle) -> (ControlHandle outControl)")},
- {"CreateCheckBoxControl", (PyCFunction)Ctl_CreateCheckBoxControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt32 initialValue, Boolean autoToggle) -> (ControlHandle outControl)")},
- {"CreateScrollBarControl", (PyCFunction)Ctl_CreateScrollBarControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, SInt32 viewSize, Boolean liveTracking, PyObject* liveTrackingProc) -> (ControlHandle outControl)")},
- {"CreatePopupButtonControl", (PyCFunction)Ctl_CreatePopupButtonControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt16 menuID, Boolean variableWidth, SInt16 titleWidth, SInt16 titleJustification, Style titleStyle) -> (ControlHandle outControl)")},
- {"CreateRadioGroupControl", (PyCFunction)Ctl_CreateRadioGroupControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
- {"CreateScrollingTextBoxControl", (PyCFunction)Ctl_CreateScrollingTextBoxControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt16 contentResID, Boolean autoScroll, UInt32 delayBeforeAutoScroll, UInt32 delayBetweenAutoScroll, UInt16 autoScrollAmount) -> (ControlHandle outControl)")},
- {"CreateDisclosureButtonControl", (PyCFunction)Ctl_CreateDisclosureButtonControl, 1,
- PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, SInt32 inValue, Boolean inAutoToggles) -> (ControlHandle outControl)")},
- {"CreateRoundButtonControl", (PyCFunction)Ctl_CreateRoundButtonControl, 1,
- PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, SInt16 inSize, ControlButtonContentInfo inContent) -> (ControlHandle outControl)")},
- {"CreateDataBrowserControl", (PyCFunction)Ctl_CreateDataBrowserControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, OSType style) -> (ControlHandle outControl)")},
- {"CreateEditUnicodeTextControl", (PyCFunction)Ctl_CreateEditUnicodeTextControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef text, Boolean isPassword, ControlFontStyleRec style) -> (ControlHandle outControl)")},
- {"FindControlUnderMouse", (PyCFunction)Ctl_FindControlUnderMouse, 1,
- PyDoc_STR("(Point inWhere, WindowPtr inWindow) -> (ControlHandle _rv, SInt16 outPart)")},
- {"as_Control", (PyCFunction)Ctl_as_Control, 1,
- PyDoc_STR("(Handle h) -> (ControlHandle _rv)")},
- {"CreateTabsControl", (PyCFunction)Ctl_CreateTabsControl, 1,
- PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt16 size, UInt16 direction, ControlTabEntry tabArray) -> (ControlHandle outControl)")},
- {NULL, NULL, 0}
+ {"NewControl", (PyCFunction)Ctl_NewControl, 1,
+ PyDoc_STR("(WindowPtr owningWindow, Rect boundsRect, Str255 controlTitle, Boolean initiallyVisible, SInt16 initialValue, SInt16 minimumValue, SInt16 maximumValue, SInt16 procID, SInt32 controlReference) -> (ControlHandle _rv)")},
+ {"GetNewControl", (PyCFunction)Ctl_GetNewControl, 1,
+ PyDoc_STR("(SInt16 resourceID, WindowPtr owningWindow) -> (ControlHandle _rv)")},
+ {"DrawControls", (PyCFunction)Ctl_DrawControls, 1,
+ PyDoc_STR("(WindowPtr theWindow) -> None")},
+ {"UpdateControls", (PyCFunction)Ctl_UpdateControls, 1,
+ PyDoc_STR("(WindowPtr inWindow, RgnHandle inUpdateRegion) -> None")},
+ {"FindControl", (PyCFunction)Ctl_FindControl, 1,
+ PyDoc_STR("(Point testPoint, WindowPtr theWindow) -> (ControlPartCode _rv, ControlHandle theControl)")},
+ {"IdleControls", (PyCFunction)Ctl_IdleControls, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"GetControlByID", (PyCFunction)Ctl_GetControlByID, 1,
+ PyDoc_STR("(WindowPtr inWindow, ControlID inID) -> (ControlHandle outControl)")},
+ {"DumpControlHierarchy", (PyCFunction)Ctl_DumpControlHierarchy, 1,
+ PyDoc_STR("(WindowPtr inWindow, FSSpec inDumpFile) -> None")},
+ {"CreateRootControl", (PyCFunction)Ctl_CreateRootControl, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
+ {"GetRootControl", (PyCFunction)Ctl_GetRootControl, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
+ {"GetKeyboardFocus", (PyCFunction)Ctl_GetKeyboardFocus, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (ControlHandle outControl)")},
+ {"SetKeyboardFocus", (PyCFunction)Ctl_SetKeyboardFocus, 1,
+ PyDoc_STR("(WindowPtr inWindow, ControlHandle inControl, ControlFocusPart inPart) -> None")},
+ {"AdvanceKeyboardFocus", (PyCFunction)Ctl_AdvanceKeyboardFocus, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"ReverseKeyboardFocus", (PyCFunction)Ctl_ReverseKeyboardFocus, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"ClearKeyboardFocus", (PyCFunction)Ctl_ClearKeyboardFocus, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> None")},
+ {"SetAutomaticControlDragTrackingEnabledForWindow", (PyCFunction)Ctl_SetAutomaticControlDragTrackingEnabledForWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow, Boolean inTracks) -> None")},
+ {"IsAutomaticControlDragTrackingEnabledForWindow", (PyCFunction)Ctl_IsAutomaticControlDragTrackingEnabledForWindow, 1,
+ PyDoc_STR("(WindowPtr inWindow) -> (Boolean outTracks)")},
+ {"CreateBevelButtonControl", (PyCFunction)Ctl_CreateBevelButtonControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, UInt16 thickness, UInt16 behavior, ControlButtonContentInfo info, SInt16 menuID, UInt16 menuBehavior, UInt16 menuPlacement) -> (ControlHandle outControl)")},
+ {"CreateSliderControl", (PyCFunction)Ctl_CreateSliderControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, UInt16 orientation, UInt16 numTickMarks, Boolean liveTracking, PyObject* liveTrackingProc) -> (ControlHandle outControl)")},
+ {"CreateDisclosureTriangleControl", (PyCFunction)Ctl_CreateDisclosureTriangleControl, 1,
+ PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, UInt16 inOrientation, CFStringRef inTitle, SInt32 inInitialValue, Boolean inDrawTitle, Boolean inAutoToggles) -> (ControlHandle outControl)")},
+ {"CreateProgressBarControl", (PyCFunction)Ctl_CreateProgressBarControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, Boolean indeterminate) -> (ControlHandle outControl)")},
+ {"CreateRelevanceBarControl", (PyCFunction)Ctl_CreateRelevanceBarControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum) -> (ControlHandle outControl)")},
+ {"CreateLittleArrowsControl", (PyCFunction)Ctl_CreateLittleArrowsControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, SInt32 increment) -> (ControlHandle outControl)")},
+ {"CreateChasingArrowsControl", (PyCFunction)Ctl_CreateChasingArrowsControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
+ {"CreateSeparatorControl", (PyCFunction)Ctl_CreateSeparatorControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
+ {"CreateGroupBoxControl", (PyCFunction)Ctl_CreateGroupBoxControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, Boolean primary) -> (ControlHandle outControl)")},
+ {"CreateCheckGroupBoxControl", (PyCFunction)Ctl_CreateCheckGroupBoxControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt32 initialValue, Boolean primary, Boolean autoToggle) -> (ControlHandle outControl)")},
+ {"CreatePopupGroupBoxControl", (PyCFunction)Ctl_CreatePopupGroupBoxControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, Boolean primary, SInt16 menuID, Boolean variableWidth, SInt16 titleWidth, SInt16 titleJustification, Style titleStyle) -> (ControlHandle outControl)")},
+ {"CreateImageWellControl", (PyCFunction)Ctl_CreateImageWellControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, ControlButtonContentInfo info) -> (ControlHandle outControl)")},
+ {"CreatePopupArrowControl", (PyCFunction)Ctl_CreatePopupArrowControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt16 orientation, UInt16 size) -> (ControlHandle outControl)")},
+ {"CreatePlacardControl", (PyCFunction)Ctl_CreatePlacardControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
+ {"CreateClockControl", (PyCFunction)Ctl_CreateClockControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt16 clockType, UInt32 clockFlags) -> (ControlHandle outControl)")},
+ {"CreateUserPaneControl", (PyCFunction)Ctl_CreateUserPaneControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt32 features) -> (ControlHandle outControl)")},
+ {"CreateEditTextControl", (PyCFunction)Ctl_CreateEditTextControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef text, Boolean isPassword, Boolean useInlineInput, ControlFontStyleRec style) -> (ControlHandle outControl)")},
+ {"CreateStaticTextControl", (PyCFunction)Ctl_CreateStaticTextControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef text, ControlFontStyleRec style) -> (ControlHandle outControl)")},
+ {"CreatePictureControl", (PyCFunction)Ctl_CreatePictureControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, ControlButtonContentInfo content, Boolean dontTrack) -> (ControlHandle outControl)")},
+ {"CreateIconControl", (PyCFunction)Ctl_CreateIconControl, 1,
+ PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, ControlButtonContentInfo inIconContent, Boolean inDontTrack) -> (ControlHandle outControl)")},
+ {"CreateWindowHeaderControl", (PyCFunction)Ctl_CreateWindowHeaderControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, Boolean isListHeader) -> (ControlHandle outControl)")},
+ {"CreatePushButtonControl", (PyCFunction)Ctl_CreatePushButtonControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title) -> (ControlHandle outControl)")},
+ {"CreatePushButtonWithIconControl", (PyCFunction)Ctl_CreatePushButtonWithIconControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, ControlButtonContentInfo icon, UInt16 iconAlignment) -> (ControlHandle outControl)")},
+ {"CreateRadioButtonControl", (PyCFunction)Ctl_CreateRadioButtonControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt32 initialValue, Boolean autoToggle) -> (ControlHandle outControl)")},
+ {"CreateCheckBoxControl", (PyCFunction)Ctl_CreateCheckBoxControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt32 initialValue, Boolean autoToggle) -> (ControlHandle outControl)")},
+ {"CreateScrollBarControl", (PyCFunction)Ctl_CreateScrollBarControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt32 value, SInt32 minimum, SInt32 maximum, SInt32 viewSize, Boolean liveTracking, PyObject* liveTrackingProc) -> (ControlHandle outControl)")},
+ {"CreatePopupButtonControl", (PyCFunction)Ctl_CreatePopupButtonControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef title, SInt16 menuID, Boolean variableWidth, SInt16 titleWidth, SInt16 titleJustification, Style titleStyle) -> (ControlHandle outControl)")},
+ {"CreateRadioGroupControl", (PyCFunction)Ctl_CreateRadioGroupControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect) -> (ControlHandle outControl)")},
+ {"CreateScrollingTextBoxControl", (PyCFunction)Ctl_CreateScrollingTextBoxControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, SInt16 contentResID, Boolean autoScroll, UInt32 delayBeforeAutoScroll, UInt32 delayBetweenAutoScroll, UInt16 autoScrollAmount) -> (ControlHandle outControl)")},
+ {"CreateDisclosureButtonControl", (PyCFunction)Ctl_CreateDisclosureButtonControl, 1,
+ PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, SInt32 inValue, Boolean inAutoToggles) -> (ControlHandle outControl)")},
+ {"CreateRoundButtonControl", (PyCFunction)Ctl_CreateRoundButtonControl, 1,
+ PyDoc_STR("(WindowPtr inWindow, Rect inBoundsRect, SInt16 inSize, ControlButtonContentInfo inContent) -> (ControlHandle outControl)")},
+ {"CreateDataBrowserControl", (PyCFunction)Ctl_CreateDataBrowserControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, OSType style) -> (ControlHandle outControl)")},
+ {"CreateEditUnicodeTextControl", (PyCFunction)Ctl_CreateEditUnicodeTextControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, CFStringRef text, Boolean isPassword, ControlFontStyleRec style) -> (ControlHandle outControl)")},
+ {"FindControlUnderMouse", (PyCFunction)Ctl_FindControlUnderMouse, 1,
+ PyDoc_STR("(Point inWhere, WindowPtr inWindow) -> (ControlHandle _rv, SInt16 outPart)")},
+ {"as_Control", (PyCFunction)Ctl_as_Control, 1,
+ PyDoc_STR("(Handle h) -> (ControlHandle _rv)")},
+ {"CreateTabsControl", (PyCFunction)Ctl_CreateTabsControl, 1,
+ PyDoc_STR("(WindowPtr window, Rect boundsRect, UInt16 size, UInt16 direction, ControlTabEntry tabArray) -> (ControlHandle outControl)")},
+ {NULL, NULL, 0}
};
@@ -5531,283 +5531,283 @@ static PyMethodDef Ctl_methods[] = {
static PyObject *
CtlObj_NewUnmanaged(ControlHandle itself)
{
- ControlObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(ControlObject, &Control_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_callbackdict = NULL;
- return (PyObject *)it;
+ ControlObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(ControlObject, &Control_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_callbackdict = NULL;
+ return (PyObject *)it;
}
static PyObject *
CtlObj_WhichControl(ControlHandle c)
{
- PyObject *it;
+ PyObject *it;
- if (c == NULL)
- it = Py_None;
- else {
- it = (PyObject *) GetControlReference(c);
- /*
- ** If the refcon is zero or doesn't point back to the Python object
- ** the control is not ours. Return a temporary object.
- */
- if (it == NULL || ((ControlObject *)it)->ob_itself != c)
- return CtlObj_NewUnmanaged(c);
- }
- Py_INCREF(it);
- return it;
+ if (c == NULL)
+ it = Py_None;
+ else {
+ it = (PyObject *) GetControlReference(c);
+ /*
+ ** If the refcon is zero or doesn't point back to the Python object
+ ** the control is not ours. Return a temporary object.
+ */
+ if (it == NULL || ((ControlObject *)it)->ob_itself != c)
+ return CtlObj_NewUnmanaged(c);
+ }
+ Py_INCREF(it);
+ return it;
}
static int
settrackfunc(PyObject *obj)
{
- if (tracker) {
- PyErr_SetString(Ctl_Error, "Tracker function in use");
- return 0;
- }
- tracker = obj;
- Py_INCREF(tracker);
- return 1;
+ if (tracker) {
+ PyErr_SetString(Ctl_Error, "Tracker function in use");
+ return 0;
+ }
+ tracker = obj;
+ Py_INCREF(tracker);
+ return 1;
}
static void
clrtrackfunc(void)
{
- Py_XDECREF(tracker);
- tracker = 0;
+ Py_XDECREF(tracker);
+ tracker = 0;
}
static pascal void
mytracker(ControlHandle ctl, short part)
{
- PyObject *args, *rv=0;
+ PyObject *args, *rv=0;
- args = Py_BuildValue("(O&i)", CtlObj_WhichControl, ctl, (int)part);
- if (args && tracker) {
- rv = PyEval_CallObject(tracker, args);
- Py_DECREF(args);
- }
- if (rv)
- Py_DECREF(rv);
- else {
- PySys_WriteStderr("TrackControl or HandleControlClick: exception in tracker function\n");
- PyErr_Print();
- }
+ args = Py_BuildValue("(O&i)", CtlObj_WhichControl, ctl, (int)part);
+ if (args && tracker) {
+ rv = PyEval_CallObject(tracker, args);
+ Py_DECREF(args);
+ }
+ if (rv)
+ Py_DECREF(rv);
+ else {
+ PySys_WriteStderr("TrackControl or HandleControlClick: exception in tracker function\n");
+ PyErr_Print();
+ }
}
static int
setcallback(PyObject *myself, OSType which, PyObject *callback, UniversalProcPtr *uppp)
{
- ControlObject *self = (ControlObject *)myself;
- char keybuf[9];
-
- if ( which == kMyControlActionProcTag )
- *uppp = (UniversalProcPtr)myactionproc_upp;
- else if ( which == kControlUserPaneKeyDownProcTag )
- *uppp = (UniversalProcPtr)mykeydownproc_upp;
- else if ( which == kControlUserPaneFocusProcTag )
- *uppp = (UniversalProcPtr)myfocusproc_upp;
- else if ( which == kControlUserPaneDrawProcTag )
- *uppp = (UniversalProcPtr)mydrawproc_upp;
- else if ( which == kControlUserPaneIdleProcTag )
- *uppp = (UniversalProcPtr)myidleproc_upp;
- else if ( which == kControlUserPaneHitTestProcTag )
- *uppp = (UniversalProcPtr)myhittestproc_upp;
- else if ( which == kControlUserPaneTrackingProcTag )
- *uppp = (UniversalProcPtr)mytrackingproc_upp;
- else
- return -1;
- /* Only now do we test for clearing of the callback: */
- if ( callback == Py_None )
- *uppp = NULL;
- /* Create the dict if it doesn't exist yet (so we don't get such a dict for every control) */
- if ( self->ob_callbackdict == NULL )
- if ( (self->ob_callbackdict = PyDict_New()) == NULL )
- return -1;
- /* And store the Python callback */
- sprintf(keybuf, "%x", (unsigned)which);
- if (PyDict_SetItemString(self->ob_callbackdict, keybuf, callback) < 0)
- return -1;
- return 0;
+ ControlObject *self = (ControlObject *)myself;
+ char keybuf[9];
+
+ if ( which == kMyControlActionProcTag )
+ *uppp = (UniversalProcPtr)myactionproc_upp;
+ else if ( which == kControlUserPaneKeyDownProcTag )
+ *uppp = (UniversalProcPtr)mykeydownproc_upp;
+ else if ( which == kControlUserPaneFocusProcTag )
+ *uppp = (UniversalProcPtr)myfocusproc_upp;
+ else if ( which == kControlUserPaneDrawProcTag )
+ *uppp = (UniversalProcPtr)mydrawproc_upp;
+ else if ( which == kControlUserPaneIdleProcTag )
+ *uppp = (UniversalProcPtr)myidleproc_upp;
+ else if ( which == kControlUserPaneHitTestProcTag )
+ *uppp = (UniversalProcPtr)myhittestproc_upp;
+ else if ( which == kControlUserPaneTrackingProcTag )
+ *uppp = (UniversalProcPtr)mytrackingproc_upp;
+ else
+ return -1;
+ /* Only now do we test for clearing of the callback: */
+ if ( callback == Py_None )
+ *uppp = NULL;
+ /* Create the dict if it doesn't exist yet (so we don't get such a dict for every control) */
+ if ( self->ob_callbackdict == NULL )
+ if ( (self->ob_callbackdict = PyDict_New()) == NULL )
+ return -1;
+ /* And store the Python callback */
+ sprintf(keybuf, "%x", (unsigned)which);
+ if (PyDict_SetItemString(self->ob_callbackdict, keybuf, callback) < 0)
+ return -1;
+ return 0;
}
static PyObject *
callcallback(ControlObject *self, OSType which, PyObject *arglist)
{
- char keybuf[9];
- PyObject *func, *rv;
+ char keybuf[9];
+ PyObject *func, *rv;
- sprintf(keybuf, "%x", (unsigned)which);
- if ( self->ob_callbackdict == NULL ||
- (func = PyDict_GetItemString(self->ob_callbackdict, keybuf)) == NULL ) {
- PySys_WriteStderr("Control callback %x without callback object\n", (unsigned)which);
- return NULL;
- }
- rv = PyEval_CallObject(func, arglist);
- if ( rv == NULL ) {
- PySys_WriteStderr("Exception in control callback %x handler\n", (unsigned)which);
- PyErr_Print();
- }
- return rv;
+ sprintf(keybuf, "%x", (unsigned)which);
+ if ( self->ob_callbackdict == NULL ||
+ (func = PyDict_GetItemString(self->ob_callbackdict, keybuf)) == NULL ) {
+ PySys_WriteStderr("Control callback %x without callback object\n", (unsigned)which);
+ return NULL;
+ }
+ rv = PyEval_CallObject(func, arglist);
+ if ( rv == NULL ) {
+ PySys_WriteStderr("Exception in control callback %x handler\n", (unsigned)which);
+ PyErr_Print();
+ }
+ return rv;
}
static pascal void
myactionproc(ControlHandle control, SInt16 part)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- arglist = Py_BuildValue("Oh", ctl_obj, part);
- rv = callcallback(ctl_obj, kMyControlActionProcTag, arglist);
- Py_XDECREF(arglist);
- Py_XDECREF(rv);
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ arglist = Py_BuildValue("Oh", ctl_obj, part);
+ rv = callcallback(ctl_obj, kMyControlActionProcTag, arglist);
+ Py_XDECREF(arglist);
+ Py_XDECREF(rv);
}
static pascal ControlPartCode
mykeydownproc(ControlHandle control, SInt16 keyCode, SInt16 charCode, SInt16 modifiers)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
- short c_rv = 0;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
+ short c_rv = 0;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- arglist = Py_BuildValue("Ohhh", ctl_obj, keyCode, charCode, modifiers);
- rv = callcallback(ctl_obj, kControlUserPaneKeyDownProcTag, arglist);
- Py_XDECREF(arglist);
- if ( rv )
- if (!PyArg_Parse(rv, "h", &c_rv))
- PyErr_Clear();
- Py_XDECREF(rv);
- return (ControlPartCode)c_rv;
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ arglist = Py_BuildValue("Ohhh", ctl_obj, keyCode, charCode, modifiers);
+ rv = callcallback(ctl_obj, kControlUserPaneKeyDownProcTag, arglist);
+ Py_XDECREF(arglist);
+ if ( rv )
+ if (!PyArg_Parse(rv, "h", &c_rv))
+ PyErr_Clear();
+ Py_XDECREF(rv);
+ return (ControlPartCode)c_rv;
}
static pascal ControlPartCode
myfocusproc(ControlHandle control, ControlPartCode part)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
- short c_rv = kControlFocusNoPart;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
+ short c_rv = kControlFocusNoPart;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- arglist = Py_BuildValue("Oh", ctl_obj, part);
- rv = callcallback(ctl_obj, kControlUserPaneFocusProcTag, arglist);
- Py_XDECREF(arglist);
- if ( rv )
- if (!PyArg_Parse(rv, "h", &c_rv))
- PyErr_Clear();
- Py_XDECREF(rv);
- return (ControlPartCode)c_rv;
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ arglist = Py_BuildValue("Oh", ctl_obj, part);
+ rv = callcallback(ctl_obj, kControlUserPaneFocusProcTag, arglist);
+ Py_XDECREF(arglist);
+ if ( rv )
+ if (!PyArg_Parse(rv, "h", &c_rv))
+ PyErr_Clear();
+ Py_XDECREF(rv);
+ return (ControlPartCode)c_rv;
}
static pascal void
mydrawproc(ControlHandle control, SInt16 part)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- arglist = Py_BuildValue("Oh", ctl_obj, part);
- rv = callcallback(ctl_obj, kControlUserPaneDrawProcTag, arglist);
- Py_XDECREF(arglist);
- Py_XDECREF(rv);
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ arglist = Py_BuildValue("Oh", ctl_obj, part);
+ rv = callcallback(ctl_obj, kControlUserPaneDrawProcTag, arglist);
+ Py_XDECREF(arglist);
+ Py_XDECREF(rv);
}
static pascal void
myidleproc(ControlHandle control)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- arglist = Py_BuildValue("O", ctl_obj);
- rv = callcallback(ctl_obj, kControlUserPaneIdleProcTag, arglist);
- Py_XDECREF(arglist);
- Py_XDECREF(rv);
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ arglist = Py_BuildValue("O", ctl_obj);
+ rv = callcallback(ctl_obj, kControlUserPaneIdleProcTag, arglist);
+ Py_XDECREF(arglist);
+ Py_XDECREF(rv);
}
static pascal ControlPartCode
myhittestproc(ControlHandle control, Point where)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
- short c_rv = -1;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
+ short c_rv = -1;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, where);
- rv = callcallback(ctl_obj, kControlUserPaneHitTestProcTag, arglist);
- Py_XDECREF(arglist);
- /* Ignore errors, nothing we can do about them */
- if ( rv )
- if (!PyArg_Parse(rv, "h", &c_rv))
- PyErr_Clear();
- Py_XDECREF(rv);
- return (ControlPartCode)c_rv;
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, where);
+ rv = callcallback(ctl_obj, kControlUserPaneHitTestProcTag, arglist);
+ Py_XDECREF(arglist);
+ /* Ignore errors, nothing we can do about them */
+ if ( rv )
+ if (!PyArg_Parse(rv, "h", &c_rv))
+ PyErr_Clear();
+ Py_XDECREF(rv);
+ return (ControlPartCode)c_rv;
}
static pascal ControlPartCode
mytrackingproc(ControlHandle control, Point startPt, ControlActionUPP actionProc)
{
- ControlObject *ctl_obj;
- PyObject *arglist, *rv;
- short c_rv = -1;
+ ControlObject *ctl_obj;
+ PyObject *arglist, *rv;
+ short c_rv = -1;
- ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
- /* We cannot pass the actionProc without lots of work */
- arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, startPt);
- rv = callcallback(ctl_obj, kControlUserPaneTrackingProcTag, arglist);
- Py_XDECREF(arglist);
- if ( rv )
- if (!PyArg_Parse(rv, "h", &c_rv))
- PyErr_Clear();
- Py_XDECREF(rv);
- return (ControlPartCode)c_rv;
+ ctl_obj = (ControlObject *)CtlObj_WhichControl(control);
+ /* We cannot pass the actionProc without lots of work */
+ arglist = Py_BuildValue("OO&", ctl_obj, PyMac_BuildPoint, startPt);
+ rv = callcallback(ctl_obj, kControlUserPaneTrackingProcTag, arglist);
+ Py_XDECREF(arglist);
+ if ( rv )
+ if (!PyArg_Parse(rv, "h", &c_rv))
+ PyErr_Clear();
+ Py_XDECREF(rv);
+ return (ControlPartCode)c_rv;
}
#else /* __LP64__ */
static PyMethodDef Ctl_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#endif /* __LP64__ */
void init_Ctl(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
-
- mytracker_upp = NewControlActionUPP(mytracker);
- myactionproc_upp = NewControlActionUPP(myactionproc);
- mykeydownproc_upp = NewControlUserPaneKeyDownUPP(mykeydownproc);
- myfocusproc_upp = NewControlUserPaneFocusUPP(myfocusproc);
- mydrawproc_upp = NewControlUserPaneDrawUPP(mydrawproc);
- myidleproc_upp = NewControlUserPaneIdleUPP(myidleproc);
- myhittestproc_upp = NewControlUserPaneHitTestUPP(myhittestproc);
- mytrackingproc_upp = NewControlUserPaneTrackingUPP(mytrackingproc);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(ControlHandle, CtlObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ControlHandle, CtlObj_Convert);
+ PyObject *d;
+
+ mytracker_upp = NewControlActionUPP(mytracker);
+ myactionproc_upp = NewControlActionUPP(myactionproc);
+ mykeydownproc_upp = NewControlUserPaneKeyDownUPP(mykeydownproc);
+ myfocusproc_upp = NewControlUserPaneFocusUPP(myfocusproc);
+ mydrawproc_upp = NewControlUserPaneDrawUPP(mydrawproc);
+ myidleproc_upp = NewControlUserPaneIdleUPP(myidleproc);
+ myhittestproc_upp = NewControlUserPaneHitTestUPP(myhittestproc);
+ mytrackingproc_upp = NewControlUserPaneTrackingUPP(mytrackingproc);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(ControlHandle, CtlObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ControlHandle, CtlObj_Convert);
#endif /* !__LP64__ */
- m = Py_InitModule("_Ctl", Ctl_methods);
+ m = Py_InitModule("_Ctl", Ctl_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Ctl_Error = PyMac_GetOSErrException();
- if (Ctl_Error == NULL ||
- PyDict_SetItemString(d, "Error", Ctl_Error) != 0)
- return;
- Control_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Control_Type) < 0) return;
- Py_INCREF(&Control_Type);
- PyModule_AddObject(m, "Control", (PyObject *)&Control_Type);
- /* Backward-compatible name */
- Py_INCREF(&Control_Type);
- PyModule_AddObject(m, "ControlType", (PyObject *)&Control_Type);
+ d = PyModule_GetDict(m);
+ Ctl_Error = PyMac_GetOSErrException();
+ if (Ctl_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Ctl_Error) != 0)
+ return;
+ Control_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Control_Type) < 0) return;
+ Py_INCREF(&Control_Type);
+ PyModule_AddObject(m, "Control", (PyObject *)&Control_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Control_Type);
+ PyModule_AddObject(m, "ControlType", (PyObject *)&Control_Type);
#endif /* !__LP64__ */
}
diff --git a/Mac/Modules/dlg/_Dlgmodule.c b/Mac/Modules/dlg/_Dlgmodule.c
index 9afa477..c4d66a9 100644
--- a/Mac/Modules/dlg/_Dlgmodule.c
+++ b/Mac/Modules/dlg/_Dlgmodule.c
@@ -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)
@@ -35,55 +35,55 @@ static pascal Boolean Dlg_UnivFilterProc(DialogPtr dialog,
EventRecord *event,
short *itemHit)
{
- Boolean rv;
- PyObject *args, *res;
- PyObject *callback = Dlg_FilterProc_callback;
- if (callback == NULL)
- return 0; /* Default behavior */
- Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */
- args = Py_BuildValue("O&O&", DlgObj_WhichDialog, dialog, PyMac_BuildEventRecord, event);
- if (args == NULL)
- res = NULL;
- else {
- res = PyEval_CallObject(callback, args);
- Py_DECREF(args);
- }
- if (res == NULL) {
- PySys_WriteStderr("Exception in Dialog Filter\n");
- PyErr_Print();
- *itemHit = -1; /* Fake return item */
- return 1; /* We handled it */
- }
- else {
- Dlg_FilterProc_callback = callback;
- if (PyInt_Check(res)) {
- *itemHit = PyInt_AsLong(res);
- rv = 1;
- }
- else
- rv = PyObject_IsTrue(res);
+ Boolean rv;
+ PyObject *args, *res;
+ PyObject *callback = Dlg_FilterProc_callback;
+ if (callback == NULL)
+ return 0; /* Default behavior */
+ Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */
+ args = Py_BuildValue("O&O&", DlgObj_WhichDialog, dialog, PyMac_BuildEventRecord, event);
+ if (args == NULL)
+ res = NULL;
+ else {
+ res = PyEval_CallObject(callback, args);
+ Py_DECREF(args);
+ }
+ if (res == NULL) {
+ PySys_WriteStderr("Exception in Dialog Filter\n");
+ PyErr_Print();
+ *itemHit = -1; /* Fake return item */
+ return 1; /* We handled it */
+ }
+ else {
+ Dlg_FilterProc_callback = callback;
+ if (PyInt_Check(res)) {
+ *itemHit = PyInt_AsLong(res);
+ rv = 1;
}
- Py_DECREF(res);
- return rv;
+ else
+ rv = PyObject_IsTrue(res);
+ }
+ Py_DECREF(res);
+ return rv;
}
static ModalFilterUPP
Dlg_PassFilterProc(PyObject *callback)
{
- PyObject *tmp = Dlg_FilterProc_callback;
- static ModalFilterUPP UnivFilterUpp = NULL;
+ PyObject *tmp = Dlg_FilterProc_callback;
+ static ModalFilterUPP UnivFilterUpp = NULL;
- Dlg_FilterProc_callback = NULL;
- if (callback == Py_None) {
- Py_XDECREF(tmp);
- return NULL;
- }
- Py_INCREF(callback);
- Dlg_FilterProc_callback = callback;
+ Dlg_FilterProc_callback = NULL;
+ if (callback == Py_None) {
Py_XDECREF(tmp);
- if ( UnivFilterUpp == NULL )
- UnivFilterUpp = NewModalFilterUPP(&Dlg_UnivFilterProc);
- return UnivFilterUpp;
+ return NULL;
+ }
+ Py_INCREF(callback);
+ Dlg_FilterProc_callback = callback;
+ Py_XDECREF(tmp);
+ if ( UnivFilterUpp == NULL )
+ UnivFilterUpp = NewModalFilterUPP(&Dlg_UnivFilterProc);
+ return UnivFilterUpp;
}
static PyObject *Dlg_UserItemProc_callback = NULL;
@@ -91,24 +91,24 @@ static PyObject *Dlg_UserItemProc_callback = NULL;
static pascal void Dlg_UnivUserItemProc(DialogPtr dialog,
short item)
{
- PyObject *args, *res;
-
- if (Dlg_UserItemProc_callback == NULL)
- return; /* Default behavior */
- Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */
- args = Py_BuildValue("O&h", DlgObj_WhichDialog, dialog, item);
- if (args == NULL)
- res = NULL;
- else {
- res = PyEval_CallObject(Dlg_UserItemProc_callback, args);
- Py_DECREF(args);
- }
- if (res == NULL) {
- PySys_WriteStderr("Exception in Dialog UserItem proc\n");
- PyErr_Print();
- }
- Py_XDECREF(res);
- return;
+ PyObject *args, *res;
+
+ if (Dlg_UserItemProc_callback == NULL)
+ return; /* Default behavior */
+ Dlg_FilterProc_callback = NULL; /* We'll restore it when call successful */
+ args = Py_BuildValue("O&h", DlgObj_WhichDialog, dialog, item);
+ if (args == NULL)
+ res = NULL;
+ else {
+ res = PyEval_CallObject(Dlg_UserItemProc_callback, args);
+ Py_DECREF(args);
+ }
+ if (res == NULL) {
+ PySys_WriteStderr("Exception in Dialog UserItem proc\n");
+ PyErr_Print();
+ }
+ Py_XDECREF(res);
+ return;
}
#if 0
@@ -133,811 +133,811 @@ PyTypeObject Dialog_Type;
#define DlgObj_Check(x) ((x)->ob_type == &Dialog_Type || PyObject_TypeCheck((x), &Dialog_Type))
typedef struct DialogObject {
- PyObject_HEAD
- DialogPtr ob_itself;
+ PyObject_HEAD
+ DialogPtr ob_itself;
} DialogObject;
PyObject *DlgObj_New(DialogPtr itself)
{
- DialogObject *it;
- if (itself == NULL) { Py_INCREF(Py_None); return Py_None; }
- it = PyObject_NEW(DialogObject, &Dialog_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- SetWRefCon(GetDialogWindow(itself), (long)it);
- return (PyObject *)it;
+ DialogObject *it;
+ if (itself == NULL) { Py_INCREF(Py_None); return Py_None; }
+ it = PyObject_NEW(DialogObject, &Dialog_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ SetWRefCon(GetDialogWindow(itself), (long)it);
+ return (PyObject *)it;
}
int DlgObj_Convert(PyObject *v, DialogPtr *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- if (PyInt_Check(v)) { *p_itself = (DialogPtr)PyInt_AsLong(v);
- return 1; }
- if (!DlgObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Dialog required");
- return 0;
- }
- *p_itself = ((DialogObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ if (PyInt_Check(v)) { *p_itself = (DialogPtr)PyInt_AsLong(v);
+ return 1; }
+ if (!DlgObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Dialog required");
+ return 0;
+ }
+ *p_itself = ((DialogObject *)v)->ob_itself;
+ return 1;
}
static void DlgObj_dealloc(DialogObject *self)
{
- DisposeDialog(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ DisposeDialog(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *DlgObj_DrawDialog(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DrawDialog
- PyMac_PRECHECK(DrawDialog);
+ PyMac_PRECHECK(DrawDialog);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DrawDialog(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DrawDialog(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_UpdateDialog(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle updateRgn;
+ PyObject *_res = NULL;
+ RgnHandle updateRgn;
#ifndef UpdateDialog
- PyMac_PRECHECK(UpdateDialog);
+ PyMac_PRECHECK(UpdateDialog);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &updateRgn))
- return NULL;
- UpdateDialog(_self->ob_itself,
- updateRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &updateRgn))
+ return NULL;
+ UpdateDialog(_self->ob_itself,
+ updateRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_HideDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex itemNo;
+ PyObject *_res = NULL;
+ DialogItemIndex itemNo;
#ifndef HideDialogItem
- PyMac_PRECHECK(HideDialogItem);
+ PyMac_PRECHECK(HideDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &itemNo))
- return NULL;
- HideDialogItem(_self->ob_itself,
- itemNo);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &itemNo))
+ return NULL;
+ HideDialogItem(_self->ob_itself,
+ itemNo);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_ShowDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex itemNo;
+ PyObject *_res = NULL;
+ DialogItemIndex itemNo;
#ifndef ShowDialogItem
- PyMac_PRECHECK(ShowDialogItem);
+ PyMac_PRECHECK(ShowDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &itemNo))
- return NULL;
- ShowDialogItem(_self->ob_itself,
- itemNo);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &itemNo))
+ return NULL;
+ ShowDialogItem(_self->ob_itself,
+ itemNo);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_FindDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndexZeroBased _rv;
- Point thePt;
+ PyObject *_res = NULL;
+ DialogItemIndexZeroBased _rv;
+ Point thePt;
#ifndef FindDialogItem
- PyMac_PRECHECK(FindDialogItem);
+ PyMac_PRECHECK(FindDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &thePt))
- return NULL;
- _rv = FindDialogItem(_self->ob_itself,
- thePt);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &thePt))
+ return NULL;
+ _rv = FindDialogItem(_self->ob_itself,
+ thePt);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *DlgObj_DialogCut(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DialogCut
- PyMac_PRECHECK(DialogCut);
+ PyMac_PRECHECK(DialogCut);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DialogCut(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DialogCut(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_DialogPaste(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DialogPaste
- PyMac_PRECHECK(DialogPaste);
+ PyMac_PRECHECK(DialogPaste);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DialogPaste(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DialogPaste(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_DialogCopy(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DialogCopy
- PyMac_PRECHECK(DialogCopy);
+ PyMac_PRECHECK(DialogCopy);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DialogCopy(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DialogCopy(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_DialogDelete(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DialogDelete
- PyMac_PRECHECK(DialogDelete);
+ PyMac_PRECHECK(DialogDelete);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DialogDelete(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DialogDelete(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_GetDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex itemNo;
- DialogItemType itemType;
- Handle item;
- Rect box;
+ PyObject *_res = NULL;
+ DialogItemIndex itemNo;
+ DialogItemType itemType;
+ Handle item;
+ Rect box;
#ifndef GetDialogItem
- PyMac_PRECHECK(GetDialogItem);
+ PyMac_PRECHECK(GetDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &itemNo))
- return NULL;
- GetDialogItem(_self->ob_itself,
- itemNo,
- &itemType,
- &item,
- &box);
- _res = Py_BuildValue("hO&O&",
- itemType,
- OptResObj_New, item,
- PyMac_BuildRect, &box);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &itemNo))
+ return NULL;
+ GetDialogItem(_self->ob_itself,
+ itemNo,
+ &itemType,
+ &item,
+ &box);
+ _res = Py_BuildValue("hO&O&",
+ itemType,
+ OptResObj_New, item,
+ PyMac_BuildRect, &box);
+ return _res;
}
static PyObject *DlgObj_SetDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex itemNo;
- DialogItemType itemType;
- Handle item;
- Rect box;
+ PyObject *_res = NULL;
+ DialogItemIndex itemNo;
+ DialogItemType itemType;
+ Handle item;
+ Rect box;
#ifndef SetDialogItem
- PyMac_PRECHECK(SetDialogItem);
+ PyMac_PRECHECK(SetDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "hhO&O&",
- &itemNo,
- &itemType,
- ResObj_Convert, &item,
- PyMac_GetRect, &box))
- return NULL;
- SetDialogItem(_self->ob_itself,
- itemNo,
- itemType,
- item,
- &box);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhO&O&",
+ &itemNo,
+ &itemType,
+ ResObj_Convert, &item,
+ PyMac_GetRect, &box))
+ return NULL;
+ SetDialogItem(_self->ob_itself,
+ itemNo,
+ itemType,
+ item,
+ &box);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_SelectDialogItemText(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex itemNo;
- SInt16 strtSel;
- SInt16 endSel;
+ PyObject *_res = NULL;
+ DialogItemIndex itemNo;
+ SInt16 strtSel;
+ SInt16 endSel;
#ifndef SelectDialogItemText
- PyMac_PRECHECK(SelectDialogItemText);
+ PyMac_PRECHECK(SelectDialogItemText);
#endif
- if (!PyArg_ParseTuple(_args, "hhh",
- &itemNo,
- &strtSel,
- &endSel))
- return NULL;
- SelectDialogItemText(_self->ob_itself,
- itemNo,
- strtSel,
- endSel);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhh",
+ &itemNo,
+ &strtSel,
+ &endSel))
+ return NULL;
+ SelectDialogItemText(_self->ob_itself,
+ itemNo,
+ strtSel,
+ endSel);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_AppendDITL(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle theHandle;
- DITLMethod method;
+ PyObject *_res = NULL;
+ Handle theHandle;
+ DITLMethod method;
#ifndef AppendDITL
- PyMac_PRECHECK(AppendDITL);
+ PyMac_PRECHECK(AppendDITL);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- ResObj_Convert, &theHandle,
- &method))
- return NULL;
- AppendDITL(_self->ob_itself,
- theHandle,
- method);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ ResObj_Convert, &theHandle,
+ &method))
+ return NULL;
+ AppendDITL(_self->ob_itself,
+ theHandle,
+ method);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_CountDITL(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex _rv;
+ PyObject *_res = NULL;
+ DialogItemIndex _rv;
#ifndef CountDITL
- PyMac_PRECHECK(CountDITL);
+ PyMac_PRECHECK(CountDITL);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CountDITL(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CountDITL(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *DlgObj_ShortenDITL(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex numberItems;
+ PyObject *_res = NULL;
+ DialogItemIndex numberItems;
#ifndef ShortenDITL
- PyMac_PRECHECK(ShortenDITL);
+ PyMac_PRECHECK(ShortenDITL);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &numberItems))
- return NULL;
- ShortenDITL(_self->ob_itself,
- numberItems);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &numberItems))
+ return NULL;
+ ShortenDITL(_self->ob_itself,
+ numberItems);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_InsertDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DialogItemIndex afterItem;
- DialogItemType itemType;
- Handle itemHandle;
- Rect box;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DialogItemIndex afterItem;
+ DialogItemType itemType;
+ Handle itemHandle;
+ Rect box;
#ifndef InsertDialogItem
- PyMac_PRECHECK(InsertDialogItem);
+ PyMac_PRECHECK(InsertDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "hhO&O&",
- &afterItem,
- &itemType,
- ResObj_Convert, &itemHandle,
- PyMac_GetRect, &box))
- return NULL;
- _err = InsertDialogItem(_self->ob_itself,
- afterItem,
- itemType,
- itemHandle,
- &box);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhO&O&",
+ &afterItem,
+ &itemType,
+ ResObj_Convert, &itemHandle,
+ PyMac_GetRect, &box))
+ return NULL;
+ _err = InsertDialogItem(_self->ob_itself,
+ afterItem,
+ itemType,
+ itemHandle,
+ &box);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_RemoveDialogItems(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DialogItemIndex itemNo;
- DialogItemIndex amountToRemove;
- Boolean disposeItemData;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DialogItemIndex itemNo;
+ DialogItemIndex amountToRemove;
+ Boolean disposeItemData;
#ifndef RemoveDialogItems
- PyMac_PRECHECK(RemoveDialogItems);
+ PyMac_PRECHECK(RemoveDialogItems);
#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &itemNo,
- &amountToRemove,
- &disposeItemData))
- return NULL;
- _err = RemoveDialogItems(_self->ob_itself,
- itemNo,
- amountToRemove,
- disposeItemData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &itemNo,
+ &amountToRemove,
+ &disposeItemData))
+ return NULL;
+ _err = RemoveDialogItems(_self->ob_itself,
+ itemNo,
+ amountToRemove,
+ disposeItemData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_StdFilterProc(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord event;
- DialogItemIndex itemHit;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord event;
+ DialogItemIndex itemHit;
#ifndef StdFilterProc
- PyMac_PRECHECK(StdFilterProc);
+ PyMac_PRECHECK(StdFilterProc);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetEventRecord, &event,
- &itemHit))
- return NULL;
- _rv = StdFilterProc(_self->ob_itself,
- &event,
- &itemHit);
- _res = Py_BuildValue("bO&h",
- _rv,
- PyMac_BuildEventRecord, &event,
- itemHit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetEventRecord, &event,
+ &itemHit))
+ return NULL;
+ _rv = StdFilterProc(_self->ob_itself,
+ &event,
+ &itemHit);
+ _res = Py_BuildValue("bO&h",
+ _rv,
+ PyMac_BuildEventRecord, &event,
+ itemHit);
+ return _res;
}
static PyObject *DlgObj_SetDialogDefaultItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DialogItemIndex newItem;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DialogItemIndex newItem;
#ifndef SetDialogDefaultItem
- PyMac_PRECHECK(SetDialogDefaultItem);
+ PyMac_PRECHECK(SetDialogDefaultItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &newItem))
- return NULL;
- _err = SetDialogDefaultItem(_self->ob_itself,
- newItem);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &newItem))
+ return NULL;
+ _err = SetDialogDefaultItem(_self->ob_itself,
+ newItem);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_SetDialogCancelItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DialogItemIndex newItem;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DialogItemIndex newItem;
#ifndef SetDialogCancelItem
- PyMac_PRECHECK(SetDialogCancelItem);
+ PyMac_PRECHECK(SetDialogCancelItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &newItem))
- return NULL;
- _err = SetDialogCancelItem(_self->ob_itself,
- newItem);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &newItem))
+ return NULL;
+ _err = SetDialogCancelItem(_self->ob_itself,
+ newItem);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_SetDialogTracksCursor(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Boolean tracks;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Boolean tracks;
#ifndef SetDialogTracksCursor
- PyMac_PRECHECK(SetDialogTracksCursor);
+ PyMac_PRECHECK(SetDialogTracksCursor);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &tracks))
- return NULL;
- _err = SetDialogTracksCursor(_self->ob_itself,
- tracks);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &tracks))
+ return NULL;
+ _err = SetDialogTracksCursor(_self->ob_itself,
+ tracks);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_AutoSizeDialog(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef AutoSizeDialog
- PyMac_PRECHECK(AutoSizeDialog);
+ PyMac_PRECHECK(AutoSizeDialog);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = AutoSizeDialog(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = AutoSizeDialog(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_GetDialogItemAsControl(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItemNo;
- ControlHandle outControl;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItemNo;
+ ControlHandle outControl;
#ifndef GetDialogItemAsControl
- PyMac_PRECHECK(GetDialogItemAsControl);
+ PyMac_PRECHECK(GetDialogItemAsControl);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItemNo))
- return NULL;
- _err = GetDialogItemAsControl(_self->ob_itself,
- inItemNo,
- &outControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CtlObj_New, outControl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItemNo))
+ return NULL;
+ _err = GetDialogItemAsControl(_self->ob_itself,
+ inItemNo,
+ &outControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, outControl);
+ return _res;
}
static PyObject *DlgObj_MoveDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItemNo;
- SInt16 inHoriz;
- SInt16 inVert;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItemNo;
+ SInt16 inHoriz;
+ SInt16 inVert;
#ifndef MoveDialogItem
- PyMac_PRECHECK(MoveDialogItem);
+ PyMac_PRECHECK(MoveDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "hhh",
- &inItemNo,
- &inHoriz,
- &inVert))
- return NULL;
- _err = MoveDialogItem(_self->ob_itself,
- inItemNo,
- inHoriz,
- inVert);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhh",
+ &inItemNo,
+ &inHoriz,
+ &inVert))
+ return NULL;
+ _err = MoveDialogItem(_self->ob_itself,
+ inItemNo,
+ inHoriz,
+ inVert);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_SizeDialogItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItemNo;
- SInt16 inWidth;
- SInt16 inHeight;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItemNo;
+ SInt16 inWidth;
+ SInt16 inHeight;
#ifndef SizeDialogItem
- PyMac_PRECHECK(SizeDialogItem);
+ PyMac_PRECHECK(SizeDialogItem);
#endif
- if (!PyArg_ParseTuple(_args, "hhh",
- &inItemNo,
- &inWidth,
- &inHeight))
- return NULL;
- _err = SizeDialogItem(_self->ob_itself,
- inItemNo,
- inWidth,
- inHeight);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhh",
+ &inItemNo,
+ &inWidth,
+ &inHeight))
+ return NULL;
+ _err = SizeDialogItem(_self->ob_itself,
+ inItemNo,
+ inWidth,
+ inHeight);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_AppendDialogItemList(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 ditlID;
- DITLMethod method;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 ditlID;
+ DITLMethod method;
#ifndef AppendDialogItemList
- PyMac_PRECHECK(AppendDialogItemList);
+ PyMac_PRECHECK(AppendDialogItemList);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &ditlID,
- &method))
- return NULL;
- _err = AppendDialogItemList(_self->ob_itself,
- ditlID,
- method);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &ditlID,
+ &method))
+ return NULL;
+ _err = AppendDialogItemList(_self->ob_itself,
+ ditlID,
+ method);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_SetDialogTimeout(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 inButtonToPress;
- UInt32 inSecondsToWait;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 inButtonToPress;
+ UInt32 inSecondsToWait;
#ifndef SetDialogTimeout
- PyMac_PRECHECK(SetDialogTimeout);
+ PyMac_PRECHECK(SetDialogTimeout);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inButtonToPress,
- &inSecondsToWait))
- return NULL;
- _err = SetDialogTimeout(_self->ob_itself,
- inButtonToPress,
- inSecondsToWait);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inButtonToPress,
+ &inSecondsToWait))
+ return NULL;
+ _err = SetDialogTimeout(_self->ob_itself,
+ inButtonToPress,
+ inSecondsToWait);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_GetDialogTimeout(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 outButtonToPress;
- UInt32 outSecondsToWait;
- UInt32 outSecondsRemaining;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 outButtonToPress;
+ UInt32 outSecondsToWait;
+ UInt32 outSecondsRemaining;
#ifndef GetDialogTimeout
- PyMac_PRECHECK(GetDialogTimeout);
+ PyMac_PRECHECK(GetDialogTimeout);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDialogTimeout(_self->ob_itself,
- &outButtonToPress,
- &outSecondsToWait,
- &outSecondsRemaining);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hll",
- outButtonToPress,
- outSecondsToWait,
- outSecondsRemaining);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDialogTimeout(_self->ob_itself,
+ &outButtonToPress,
+ &outSecondsToWait,
+ &outSecondsRemaining);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hll",
+ outButtonToPress,
+ outSecondsToWait,
+ outSecondsRemaining);
+ return _res;
}
static PyObject *DlgObj_SetModalDialogEventMask(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- EventMask inMask;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ EventMask inMask;
#ifndef SetModalDialogEventMask
- PyMac_PRECHECK(SetModalDialogEventMask);
+ PyMac_PRECHECK(SetModalDialogEventMask);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &inMask))
- return NULL;
- _err = SetModalDialogEventMask(_self->ob_itself,
- inMask);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &inMask))
+ return NULL;
+ _err = SetModalDialogEventMask(_self->ob_itself,
+ inMask);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_GetModalDialogEventMask(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- EventMask outMask;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ EventMask outMask;
#ifndef GetModalDialogEventMask
- PyMac_PRECHECK(GetModalDialogEventMask);
+ PyMac_PRECHECK(GetModalDialogEventMask);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetModalDialogEventMask(_self->ob_itself,
- &outMask);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outMask);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetModalDialogEventMask(_self->ob_itself,
+ &outMask);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outMask);
+ return _res;
}
static PyObject *DlgObj_GetDialogWindow(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
#ifndef GetDialogWindow
- PyMac_PRECHECK(GetDialogWindow);
+ PyMac_PRECHECK(GetDialogWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDialogWindow(_self->ob_itself);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDialogWindow(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *DlgObj_GetDialogTextEditHandle(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TEHandle _rv;
+ PyObject *_res = NULL;
+ TEHandle _rv;
#ifndef GetDialogTextEditHandle
- PyMac_PRECHECK(GetDialogTextEditHandle);
+ PyMac_PRECHECK(GetDialogTextEditHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDialogTextEditHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDialogTextEditHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *DlgObj_GetDialogDefaultItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetDialogDefaultItem
- PyMac_PRECHECK(GetDialogDefaultItem);
+ PyMac_PRECHECK(GetDialogDefaultItem);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDialogDefaultItem(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDialogDefaultItem(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *DlgObj_GetDialogCancelItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetDialogCancelItem
- PyMac_PRECHECK(GetDialogCancelItem);
+ PyMac_PRECHECK(GetDialogCancelItem);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDialogCancelItem(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDialogCancelItem(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *DlgObj_GetDialogKeyboardFocusItem(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetDialogKeyboardFocusItem
- PyMac_PRECHECK(GetDialogKeyboardFocusItem);
+ PyMac_PRECHECK(GetDialogKeyboardFocusItem);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDialogKeyboardFocusItem(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDialogKeyboardFocusItem(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *DlgObj_SetPortDialogPort(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef SetPortDialogPort
- PyMac_PRECHECK(SetPortDialogPort);
+ PyMac_PRECHECK(SetPortDialogPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- SetPortDialogPort(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ SetPortDialogPort(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DlgObj_GetDialogPort(DialogObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
#ifndef GetDialogPort
- PyMac_PRECHECK(GetDialogPort);
+ PyMac_PRECHECK(GetDialogPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDialogPort(_self->ob_itself);
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDialogPort(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyMethodDef DlgObj_methods[] = {
- {"DrawDialog", (PyCFunction)DlgObj_DrawDialog, 1,
- PyDoc_STR("() -> None")},
- {"UpdateDialog", (PyCFunction)DlgObj_UpdateDialog, 1,
- PyDoc_STR("(RgnHandle updateRgn) -> None")},
- {"HideDialogItem", (PyCFunction)DlgObj_HideDialogItem, 1,
- PyDoc_STR("(DialogItemIndex itemNo) -> None")},
- {"ShowDialogItem", (PyCFunction)DlgObj_ShowDialogItem, 1,
- PyDoc_STR("(DialogItemIndex itemNo) -> None")},
- {"FindDialogItem", (PyCFunction)DlgObj_FindDialogItem, 1,
- PyDoc_STR("(Point thePt) -> (DialogItemIndexZeroBased _rv)")},
- {"DialogCut", (PyCFunction)DlgObj_DialogCut, 1,
- PyDoc_STR("() -> None")},
- {"DialogPaste", (PyCFunction)DlgObj_DialogPaste, 1,
- PyDoc_STR("() -> None")},
- {"DialogCopy", (PyCFunction)DlgObj_DialogCopy, 1,
- PyDoc_STR("() -> None")},
- {"DialogDelete", (PyCFunction)DlgObj_DialogDelete, 1,
- PyDoc_STR("() -> None")},
- {"GetDialogItem", (PyCFunction)DlgObj_GetDialogItem, 1,
- PyDoc_STR("(DialogItemIndex itemNo) -> (DialogItemType itemType, Handle item, Rect box)")},
- {"SetDialogItem", (PyCFunction)DlgObj_SetDialogItem, 1,
- PyDoc_STR("(DialogItemIndex itemNo, DialogItemType itemType, Handle item, Rect box) -> None")},
- {"SelectDialogItemText", (PyCFunction)DlgObj_SelectDialogItemText, 1,
- PyDoc_STR("(DialogItemIndex itemNo, SInt16 strtSel, SInt16 endSel) -> None")},
- {"AppendDITL", (PyCFunction)DlgObj_AppendDITL, 1,
- PyDoc_STR("(Handle theHandle, DITLMethod method) -> None")},
- {"CountDITL", (PyCFunction)DlgObj_CountDITL, 1,
- PyDoc_STR("() -> (DialogItemIndex _rv)")},
- {"ShortenDITL", (PyCFunction)DlgObj_ShortenDITL, 1,
- PyDoc_STR("(DialogItemIndex numberItems) -> None")},
- {"InsertDialogItem", (PyCFunction)DlgObj_InsertDialogItem, 1,
- PyDoc_STR("(DialogItemIndex afterItem, DialogItemType itemType, Handle itemHandle, Rect box) -> None")},
- {"RemoveDialogItems", (PyCFunction)DlgObj_RemoveDialogItems, 1,
- PyDoc_STR("(DialogItemIndex itemNo, DialogItemIndex amountToRemove, Boolean disposeItemData) -> None")},
- {"StdFilterProc", (PyCFunction)DlgObj_StdFilterProc, 1,
- PyDoc_STR("(EventRecord event, DialogItemIndex itemHit) -> (Boolean _rv, EventRecord event, DialogItemIndex itemHit)")},
- {"SetDialogDefaultItem", (PyCFunction)DlgObj_SetDialogDefaultItem, 1,
- PyDoc_STR("(DialogItemIndex newItem) -> None")},
- {"SetDialogCancelItem", (PyCFunction)DlgObj_SetDialogCancelItem, 1,
- PyDoc_STR("(DialogItemIndex newItem) -> None")},
- {"SetDialogTracksCursor", (PyCFunction)DlgObj_SetDialogTracksCursor, 1,
- PyDoc_STR("(Boolean tracks) -> None")},
- {"AutoSizeDialog", (PyCFunction)DlgObj_AutoSizeDialog, 1,
- PyDoc_STR("() -> None")},
- {"GetDialogItemAsControl", (PyCFunction)DlgObj_GetDialogItemAsControl, 1,
- PyDoc_STR("(SInt16 inItemNo) -> (ControlHandle outControl)")},
- {"MoveDialogItem", (PyCFunction)DlgObj_MoveDialogItem, 1,
- PyDoc_STR("(SInt16 inItemNo, SInt16 inHoriz, SInt16 inVert) -> None")},
- {"SizeDialogItem", (PyCFunction)DlgObj_SizeDialogItem, 1,
- PyDoc_STR("(SInt16 inItemNo, SInt16 inWidth, SInt16 inHeight) -> None")},
- {"AppendDialogItemList", (PyCFunction)DlgObj_AppendDialogItemList, 1,
- PyDoc_STR("(SInt16 ditlID, DITLMethod method) -> None")},
- {"SetDialogTimeout", (PyCFunction)DlgObj_SetDialogTimeout, 1,
- PyDoc_STR("(SInt16 inButtonToPress, UInt32 inSecondsToWait) -> None")},
- {"GetDialogTimeout", (PyCFunction)DlgObj_GetDialogTimeout, 1,
- PyDoc_STR("() -> (SInt16 outButtonToPress, UInt32 outSecondsToWait, UInt32 outSecondsRemaining)")},
- {"SetModalDialogEventMask", (PyCFunction)DlgObj_SetModalDialogEventMask, 1,
- PyDoc_STR("(EventMask inMask) -> None")},
- {"GetModalDialogEventMask", (PyCFunction)DlgObj_GetModalDialogEventMask, 1,
- PyDoc_STR("() -> (EventMask outMask)")},
- {"GetDialogWindow", (PyCFunction)DlgObj_GetDialogWindow, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"GetDialogTextEditHandle", (PyCFunction)DlgObj_GetDialogTextEditHandle, 1,
- PyDoc_STR("() -> (TEHandle _rv)")},
- {"GetDialogDefaultItem", (PyCFunction)DlgObj_GetDialogDefaultItem, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"GetDialogCancelItem", (PyCFunction)DlgObj_GetDialogCancelItem, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"GetDialogKeyboardFocusItem", (PyCFunction)DlgObj_GetDialogKeyboardFocusItem, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"SetPortDialogPort", (PyCFunction)DlgObj_SetPortDialogPort, 1,
- PyDoc_STR("() -> None")},
- {"GetDialogPort", (PyCFunction)DlgObj_GetDialogPort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {NULL, NULL, 0}
+ {"DrawDialog", (PyCFunction)DlgObj_DrawDialog, 1,
+ PyDoc_STR("() -> None")},
+ {"UpdateDialog", (PyCFunction)DlgObj_UpdateDialog, 1,
+ PyDoc_STR("(RgnHandle updateRgn) -> None")},
+ {"HideDialogItem", (PyCFunction)DlgObj_HideDialogItem, 1,
+ PyDoc_STR("(DialogItemIndex itemNo) -> None")},
+ {"ShowDialogItem", (PyCFunction)DlgObj_ShowDialogItem, 1,
+ PyDoc_STR("(DialogItemIndex itemNo) -> None")},
+ {"FindDialogItem", (PyCFunction)DlgObj_FindDialogItem, 1,
+ PyDoc_STR("(Point thePt) -> (DialogItemIndexZeroBased _rv)")},
+ {"DialogCut", (PyCFunction)DlgObj_DialogCut, 1,
+ PyDoc_STR("() -> None")},
+ {"DialogPaste", (PyCFunction)DlgObj_DialogPaste, 1,
+ PyDoc_STR("() -> None")},
+ {"DialogCopy", (PyCFunction)DlgObj_DialogCopy, 1,
+ PyDoc_STR("() -> None")},
+ {"DialogDelete", (PyCFunction)DlgObj_DialogDelete, 1,
+ PyDoc_STR("() -> None")},
+ {"GetDialogItem", (PyCFunction)DlgObj_GetDialogItem, 1,
+ PyDoc_STR("(DialogItemIndex itemNo) -> (DialogItemType itemType, Handle item, Rect box)")},
+ {"SetDialogItem", (PyCFunction)DlgObj_SetDialogItem, 1,
+ PyDoc_STR("(DialogItemIndex itemNo, DialogItemType itemType, Handle item, Rect box) -> None")},
+ {"SelectDialogItemText", (PyCFunction)DlgObj_SelectDialogItemText, 1,
+ PyDoc_STR("(DialogItemIndex itemNo, SInt16 strtSel, SInt16 endSel) -> None")},
+ {"AppendDITL", (PyCFunction)DlgObj_AppendDITL, 1,
+ PyDoc_STR("(Handle theHandle, DITLMethod method) -> None")},
+ {"CountDITL", (PyCFunction)DlgObj_CountDITL, 1,
+ PyDoc_STR("() -> (DialogItemIndex _rv)")},
+ {"ShortenDITL", (PyCFunction)DlgObj_ShortenDITL, 1,
+ PyDoc_STR("(DialogItemIndex numberItems) -> None")},
+ {"InsertDialogItem", (PyCFunction)DlgObj_InsertDialogItem, 1,
+ PyDoc_STR("(DialogItemIndex afterItem, DialogItemType itemType, Handle itemHandle, Rect box) -> None")},
+ {"RemoveDialogItems", (PyCFunction)DlgObj_RemoveDialogItems, 1,
+ PyDoc_STR("(DialogItemIndex itemNo, DialogItemIndex amountToRemove, Boolean disposeItemData) -> None")},
+ {"StdFilterProc", (PyCFunction)DlgObj_StdFilterProc, 1,
+ PyDoc_STR("(EventRecord event, DialogItemIndex itemHit) -> (Boolean _rv, EventRecord event, DialogItemIndex itemHit)")},
+ {"SetDialogDefaultItem", (PyCFunction)DlgObj_SetDialogDefaultItem, 1,
+ PyDoc_STR("(DialogItemIndex newItem) -> None")},
+ {"SetDialogCancelItem", (PyCFunction)DlgObj_SetDialogCancelItem, 1,
+ PyDoc_STR("(DialogItemIndex newItem) -> None")},
+ {"SetDialogTracksCursor", (PyCFunction)DlgObj_SetDialogTracksCursor, 1,
+ PyDoc_STR("(Boolean tracks) -> None")},
+ {"AutoSizeDialog", (PyCFunction)DlgObj_AutoSizeDialog, 1,
+ PyDoc_STR("() -> None")},
+ {"GetDialogItemAsControl", (PyCFunction)DlgObj_GetDialogItemAsControl, 1,
+ PyDoc_STR("(SInt16 inItemNo) -> (ControlHandle outControl)")},
+ {"MoveDialogItem", (PyCFunction)DlgObj_MoveDialogItem, 1,
+ PyDoc_STR("(SInt16 inItemNo, SInt16 inHoriz, SInt16 inVert) -> None")},
+ {"SizeDialogItem", (PyCFunction)DlgObj_SizeDialogItem, 1,
+ PyDoc_STR("(SInt16 inItemNo, SInt16 inWidth, SInt16 inHeight) -> None")},
+ {"AppendDialogItemList", (PyCFunction)DlgObj_AppendDialogItemList, 1,
+ PyDoc_STR("(SInt16 ditlID, DITLMethod method) -> None")},
+ {"SetDialogTimeout", (PyCFunction)DlgObj_SetDialogTimeout, 1,
+ PyDoc_STR("(SInt16 inButtonToPress, UInt32 inSecondsToWait) -> None")},
+ {"GetDialogTimeout", (PyCFunction)DlgObj_GetDialogTimeout, 1,
+ PyDoc_STR("() -> (SInt16 outButtonToPress, UInt32 outSecondsToWait, UInt32 outSecondsRemaining)")},
+ {"SetModalDialogEventMask", (PyCFunction)DlgObj_SetModalDialogEventMask, 1,
+ PyDoc_STR("(EventMask inMask) -> None")},
+ {"GetModalDialogEventMask", (PyCFunction)DlgObj_GetModalDialogEventMask, 1,
+ PyDoc_STR("() -> (EventMask outMask)")},
+ {"GetDialogWindow", (PyCFunction)DlgObj_GetDialogWindow, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"GetDialogTextEditHandle", (PyCFunction)DlgObj_GetDialogTextEditHandle, 1,
+ PyDoc_STR("() -> (TEHandle _rv)")},
+ {"GetDialogDefaultItem", (PyCFunction)DlgObj_GetDialogDefaultItem, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"GetDialogCancelItem", (PyCFunction)DlgObj_GetDialogCancelItem, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"GetDialogKeyboardFocusItem", (PyCFunction)DlgObj_GetDialogKeyboardFocusItem, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"SetPortDialogPort", (PyCFunction)DlgObj_SetPortDialogPort, 1,
+ PyDoc_STR("() -> None")},
+ {"GetDialogPort", (PyCFunction)DlgObj_GetDialogPort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {NULL, NULL, 0}
};
#define DlgObj_getsetlist NULL
@@ -945,16 +945,16 @@ static PyMethodDef DlgObj_methods[] = {
static int DlgObj_compare(DialogObject *self, DialogObject *other)
{
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
#define DlgObj_repr NULL
static int DlgObj_hash(DialogObject *self)
{
- return (int)self->ob_itself;
+ return (int)self->ob_itself;
}
#define DlgObj_tp_init 0
@@ -962,61 +962,61 @@ static int DlgObj_hash(DialogObject *self)
static PyObject *DlgObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- DialogPtr itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ DialogPtr itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, DlgObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((DialogObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, DlgObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((DialogObject *)_self)->ob_itself = itself;
+ return _self;
}
#define DlgObj_tp_free PyObject_Del
PyTypeObject Dialog_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Dlg.Dialog", /*tp_name*/
- sizeof(DialogObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) DlgObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) DlgObj_compare, /*tp_compare*/
- (reprfunc) DlgObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) DlgObj_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*/
- DlgObj_methods, /* tp_methods */
- 0, /*tp_members*/
- DlgObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- DlgObj_tp_init, /* tp_init */
- DlgObj_tp_alloc, /* tp_alloc */
- DlgObj_tp_new, /* tp_new */
- DlgObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Dlg.Dialog", /*tp_name*/
+ sizeof(DialogObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) DlgObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) DlgObj_compare, /*tp_compare*/
+ (reprfunc) DlgObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) DlgObj_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*/
+ DlgObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ DlgObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ DlgObj_tp_init, /* tp_init */
+ DlgObj_tp_alloc, /* tp_alloc */
+ DlgObj_tp_new, /* tp_new */
+ DlgObj_tp_free, /* tp_free */
};
/* --------------------- End object type Dialog --------------------- */
@@ -1024,503 +1024,503 @@ PyTypeObject Dialog_Type = {
static PyObject *Dlg_NewDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogPtr _rv;
- Rect boundsRect;
- Str255 title;
- Boolean visible;
- SInt16 procID;
- WindowPtr behind;
- Boolean goAwayFlag;
- SInt32 refCon;
- Handle items;
+ PyObject *_res = NULL;
+ DialogPtr _rv;
+ Rect boundsRect;
+ Str255 title;
+ Boolean visible;
+ SInt16 procID;
+ WindowPtr behind;
+ Boolean goAwayFlag;
+ SInt32 refCon;
+ Handle items;
#ifndef NewDialog
- PyMac_PRECHECK(NewDialog);
+ PyMac_PRECHECK(NewDialog);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&bhO&blO&",
- PyMac_GetRect, &boundsRect,
- PyMac_GetStr255, title,
- &visible,
- &procID,
- WinObj_Convert, &behind,
- &goAwayFlag,
- &refCon,
- ResObj_Convert, &items))
- return NULL;
- _rv = NewDialog((void *)0,
- &boundsRect,
- title,
- visible,
- procID,
- behind,
- goAwayFlag,
- refCon,
- items);
- _res = Py_BuildValue("O&",
- DlgObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&bhO&blO&",
+ PyMac_GetRect, &boundsRect,
+ PyMac_GetStr255, title,
+ &visible,
+ &procID,
+ WinObj_Convert, &behind,
+ &goAwayFlag,
+ &refCon,
+ ResObj_Convert, &items))
+ return NULL;
+ _rv = NewDialog((void *)0,
+ &boundsRect,
+ title,
+ visible,
+ procID,
+ behind,
+ goAwayFlag,
+ refCon,
+ items);
+ _res = Py_BuildValue("O&",
+ DlgObj_New, _rv);
+ return _res;
}
static PyObject *Dlg_GetNewDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogPtr _rv;
- SInt16 dialogID;
- WindowPtr behind;
+ PyObject *_res = NULL;
+ DialogPtr _rv;
+ SInt16 dialogID;
+ WindowPtr behind;
#ifndef GetNewDialog
- PyMac_PRECHECK(GetNewDialog);
+ PyMac_PRECHECK(GetNewDialog);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &dialogID,
- WinObj_Convert, &behind))
- return NULL;
- _rv = GetNewDialog(dialogID,
- (void *)0,
- behind);
- _res = Py_BuildValue("O&",
- DlgObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &dialogID,
+ WinObj_Convert, &behind))
+ return NULL;
+ _rv = GetNewDialog(dialogID,
+ (void *)0,
+ behind);
+ _res = Py_BuildValue("O&",
+ DlgObj_New, _rv);
+ return _res;
}
static PyObject *Dlg_NewColorDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogPtr _rv;
- Rect boundsRect;
- Str255 title;
- Boolean visible;
- SInt16 procID;
- WindowPtr behind;
- Boolean goAwayFlag;
- SInt32 refCon;
- Handle items;
+ PyObject *_res = NULL;
+ DialogPtr _rv;
+ Rect boundsRect;
+ Str255 title;
+ Boolean visible;
+ SInt16 procID;
+ WindowPtr behind;
+ Boolean goAwayFlag;
+ SInt32 refCon;
+ Handle items;
#ifndef NewColorDialog
- PyMac_PRECHECK(NewColorDialog);
+ PyMac_PRECHECK(NewColorDialog);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&bhO&blO&",
- PyMac_GetRect, &boundsRect,
- PyMac_GetStr255, title,
- &visible,
- &procID,
- WinObj_Convert, &behind,
- &goAwayFlag,
- &refCon,
- ResObj_Convert, &items))
- return NULL;
- _rv = NewColorDialog((void *)0,
- &boundsRect,
- title,
- visible,
- procID,
- behind,
- goAwayFlag,
- refCon,
- items);
- _res = Py_BuildValue("O&",
- DlgObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&bhO&blO&",
+ PyMac_GetRect, &boundsRect,
+ PyMac_GetStr255, title,
+ &visible,
+ &procID,
+ WinObj_Convert, &behind,
+ &goAwayFlag,
+ &refCon,
+ ResObj_Convert, &items))
+ return NULL;
+ _rv = NewColorDialog((void *)0,
+ &boundsRect,
+ title,
+ visible,
+ procID,
+ behind,
+ goAwayFlag,
+ refCon,
+ items);
+ _res = Py_BuildValue("O&",
+ DlgObj_New, _rv);
+ return _res;
}
static PyObject *Dlg_ModalDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PyObject* modalFilter;
- DialogItemIndex itemHit;
+ PyObject *_res = NULL;
+ PyObject* modalFilter;
+ DialogItemIndex itemHit;
#ifndef ModalDialog
- PyMac_PRECHECK(ModalDialog);
+ PyMac_PRECHECK(ModalDialog);
#endif
- if (!PyArg_ParseTuple(_args, "O",
- &modalFilter))
- return NULL;
- ModalDialog(Dlg_PassFilterProc(modalFilter),
- &itemHit);
- _res = Py_BuildValue("h",
- itemHit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O",
+ &modalFilter))
+ return NULL;
+ ModalDialog(Dlg_PassFilterProc(modalFilter),
+ &itemHit);
+ _res = Py_BuildValue("h",
+ itemHit);
+ return _res;
}
static PyObject *Dlg_IsDialogEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord theEvent;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord theEvent;
#ifndef IsDialogEvent
- PyMac_PRECHECK(IsDialogEvent);
+ PyMac_PRECHECK(IsDialogEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &theEvent))
- return NULL;
- _rv = IsDialogEvent(&theEvent);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &theEvent))
+ return NULL;
+ _rv = IsDialogEvent(&theEvent);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Dlg_DialogSelect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord theEvent;
- DialogPtr theDialog;
- DialogItemIndex itemHit;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord theEvent;
+ DialogPtr theDialog;
+ DialogItemIndex itemHit;
#ifndef DialogSelect
- PyMac_PRECHECK(DialogSelect);
+ PyMac_PRECHECK(DialogSelect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &theEvent))
- return NULL;
- _rv = DialogSelect(&theEvent,
- &theDialog,
- &itemHit);
- _res = Py_BuildValue("bO&h",
- _rv,
- DlgObj_WhichDialog, theDialog,
- itemHit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &theEvent))
+ return NULL;
+ _rv = DialogSelect(&theEvent,
+ &theDialog,
+ &itemHit);
+ _res = Py_BuildValue("bO&h",
+ _rv,
+ DlgObj_WhichDialog, theDialog,
+ itemHit);
+ return _res;
}
static PyObject *Dlg_Alert(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex _rv;
- SInt16 alertID;
- PyObject* modalFilter;
+ PyObject *_res = NULL;
+ DialogItemIndex _rv;
+ SInt16 alertID;
+ PyObject* modalFilter;
#ifndef Alert
- PyMac_PRECHECK(Alert);
+ PyMac_PRECHECK(Alert);
#endif
- if (!PyArg_ParseTuple(_args, "hO",
- &alertID,
- &modalFilter))
- return NULL;
- _rv = Alert(alertID,
- Dlg_PassFilterProc(modalFilter));
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO",
+ &alertID,
+ &modalFilter))
+ return NULL;
+ _rv = Alert(alertID,
+ Dlg_PassFilterProc(modalFilter));
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Dlg_StopAlert(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex _rv;
- SInt16 alertID;
- PyObject* modalFilter;
+ PyObject *_res = NULL;
+ DialogItemIndex _rv;
+ SInt16 alertID;
+ PyObject* modalFilter;
#ifndef StopAlert
- PyMac_PRECHECK(StopAlert);
+ PyMac_PRECHECK(StopAlert);
#endif
- if (!PyArg_ParseTuple(_args, "hO",
- &alertID,
- &modalFilter))
- return NULL;
- _rv = StopAlert(alertID,
- Dlg_PassFilterProc(modalFilter));
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO",
+ &alertID,
+ &modalFilter))
+ return NULL;
+ _rv = StopAlert(alertID,
+ Dlg_PassFilterProc(modalFilter));
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Dlg_NoteAlert(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex _rv;
- SInt16 alertID;
- PyObject* modalFilter;
+ PyObject *_res = NULL;
+ DialogItemIndex _rv;
+ SInt16 alertID;
+ PyObject* modalFilter;
#ifndef NoteAlert
- PyMac_PRECHECK(NoteAlert);
+ PyMac_PRECHECK(NoteAlert);
#endif
- if (!PyArg_ParseTuple(_args, "hO",
- &alertID,
- &modalFilter))
- return NULL;
- _rv = NoteAlert(alertID,
- Dlg_PassFilterProc(modalFilter));
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO",
+ &alertID,
+ &modalFilter))
+ return NULL;
+ _rv = NoteAlert(alertID,
+ Dlg_PassFilterProc(modalFilter));
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Dlg_CautionAlert(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogItemIndex _rv;
- SInt16 alertID;
- PyObject* modalFilter;
+ PyObject *_res = NULL;
+ DialogItemIndex _rv;
+ SInt16 alertID;
+ PyObject* modalFilter;
#ifndef CautionAlert
- PyMac_PRECHECK(CautionAlert);
+ PyMac_PRECHECK(CautionAlert);
#endif
- if (!PyArg_ParseTuple(_args, "hO",
- &alertID,
- &modalFilter))
- return NULL;
- _rv = CautionAlert(alertID,
- Dlg_PassFilterProc(modalFilter));
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO",
+ &alertID,
+ &modalFilter))
+ return NULL;
+ _rv = CautionAlert(alertID,
+ Dlg_PassFilterProc(modalFilter));
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Dlg_ParamText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 param0;
- Str255 param1;
- Str255 param2;
- Str255 param3;
+ PyObject *_res = NULL;
+ Str255 param0;
+ Str255 param1;
+ Str255 param2;
+ Str255 param3;
#ifndef ParamText
- PyMac_PRECHECK(ParamText);
+ PyMac_PRECHECK(ParamText);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- PyMac_GetStr255, param0,
- PyMac_GetStr255, param1,
- PyMac_GetStr255, param2,
- PyMac_GetStr255, param3))
- return NULL;
- ParamText(param0,
- param1,
- param2,
- param3);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ PyMac_GetStr255, param0,
+ PyMac_GetStr255, param1,
+ PyMac_GetStr255, param2,
+ PyMac_GetStr255, param3))
+ return NULL;
+ ParamText(param0,
+ param1,
+ param2,
+ param3);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Dlg_GetDialogItemText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle item;
- Str255 text;
+ PyObject *_res = NULL;
+ Handle item;
+ Str255 text;
#ifndef GetDialogItemText
- PyMac_PRECHECK(GetDialogItemText);
+ PyMac_PRECHECK(GetDialogItemText);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &item))
- return NULL;
- GetDialogItemText(item,
- text);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, text);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &item))
+ return NULL;
+ GetDialogItemText(item,
+ text);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, text);
+ return _res;
}
static PyObject *Dlg_SetDialogItemText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle item;
- Str255 text;
+ PyObject *_res = NULL;
+ Handle item;
+ Str255 text;
#ifndef SetDialogItemText
- PyMac_PRECHECK(SetDialogItemText);
+ PyMac_PRECHECK(SetDialogItemText);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &item,
- PyMac_GetStr255, text))
- return NULL;
- SetDialogItemText(item,
- text);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &item,
+ PyMac_GetStr255, text))
+ return NULL;
+ SetDialogItemText(item,
+ text);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Dlg_GetAlertStage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetAlertStage
- PyMac_PRECHECK(GetAlertStage);
+ PyMac_PRECHECK(GetAlertStage);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetAlertStage();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetAlertStage();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Dlg_SetDialogFont(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 fontNum;
+ PyObject *_res = NULL;
+ SInt16 fontNum;
#ifndef SetDialogFont
- PyMac_PRECHECK(SetDialogFont);
+ PyMac_PRECHECK(SetDialogFont);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &fontNum))
- return NULL;
- SetDialogFont(fontNum);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &fontNum))
+ return NULL;
+ SetDialogFont(fontNum);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Dlg_ResetAlertStage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ResetAlertStage
- PyMac_PRECHECK(ResetAlertStage);
+ PyMac_PRECHECK(ResetAlertStage);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ResetAlertStage();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ResetAlertStage();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Dlg_GetParamText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 param0;
- Str255 param1;
- Str255 param2;
- Str255 param3;
+ PyObject *_res = NULL;
+ Str255 param0;
+ Str255 param1;
+ Str255 param2;
+ Str255 param3;
#ifndef GetParamText
- PyMac_PRECHECK(GetParamText);
+ PyMac_PRECHECK(GetParamText);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- PyMac_GetStr255, param0,
- PyMac_GetStr255, param1,
- PyMac_GetStr255, param2,
- PyMac_GetStr255, param3))
- return NULL;
- GetParamText(param0,
- param1,
- param2,
- param3);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ PyMac_GetStr255, param0,
+ PyMac_GetStr255, param1,
+ PyMac_GetStr255, param2,
+ PyMac_GetStr255, param3))
+ return NULL;
+ GetParamText(param0,
+ param1,
+ param2,
+ param3);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Dlg_NewFeaturesDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogPtr _rv;
- Rect inBoundsRect;
- Str255 inTitle;
- Boolean inIsVisible;
- SInt16 inProcID;
- WindowPtr inBehind;
- Boolean inGoAwayFlag;
- SInt32 inRefCon;
- Handle inItemListHandle;
- UInt32 inFlags;
+ PyObject *_res = NULL;
+ DialogPtr _rv;
+ Rect inBoundsRect;
+ Str255 inTitle;
+ Boolean inIsVisible;
+ SInt16 inProcID;
+ WindowPtr inBehind;
+ Boolean inGoAwayFlag;
+ SInt32 inRefCon;
+ Handle inItemListHandle;
+ UInt32 inFlags;
#ifndef NewFeaturesDialog
- PyMac_PRECHECK(NewFeaturesDialog);
+ PyMac_PRECHECK(NewFeaturesDialog);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&bhO&blO&l",
- PyMac_GetRect, &inBoundsRect,
- PyMac_GetStr255, inTitle,
- &inIsVisible,
- &inProcID,
- WinObj_Convert, &inBehind,
- &inGoAwayFlag,
- &inRefCon,
- ResObj_Convert, &inItemListHandle,
- &inFlags))
- return NULL;
- _rv = NewFeaturesDialog((void *)0,
- &inBoundsRect,
- inTitle,
- inIsVisible,
- inProcID,
- inBehind,
- inGoAwayFlag,
- inRefCon,
- inItemListHandle,
- inFlags);
- _res = Py_BuildValue("O&",
- DlgObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&bhO&blO&l",
+ PyMac_GetRect, &inBoundsRect,
+ PyMac_GetStr255, inTitle,
+ &inIsVisible,
+ &inProcID,
+ WinObj_Convert, &inBehind,
+ &inGoAwayFlag,
+ &inRefCon,
+ ResObj_Convert, &inItemListHandle,
+ &inFlags))
+ return NULL;
+ _rv = NewFeaturesDialog((void *)0,
+ &inBoundsRect,
+ inTitle,
+ inIsVisible,
+ inProcID,
+ inBehind,
+ inGoAwayFlag,
+ inRefCon,
+ inItemListHandle,
+ inFlags);
+ _res = Py_BuildValue("O&",
+ DlgObj_New, _rv);
+ return _res;
}
static PyObject *Dlg_GetDialogFromWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DialogPtr _rv;
- WindowPtr window;
+ PyObject *_res = NULL;
+ DialogPtr _rv;
+ WindowPtr window;
#ifndef GetDialogFromWindow
- PyMac_PRECHECK(GetDialogFromWindow);
+ PyMac_PRECHECK(GetDialogFromWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &window))
- return NULL;
- _rv = GetDialogFromWindow(window);
- _res = Py_BuildValue("O&",
- DlgObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &window))
+ return NULL;
+ _rv = GetDialogFromWindow(window);
+ _res = Py_BuildValue("O&",
+ DlgObj_New, _rv);
+ return _res;
}
static PyObject *Dlg_SetUserItemHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- PyObject *new = NULL;
+ PyObject *new = NULL;
- if (!PyArg_ParseTuple(_args, "|O", &new))
- return NULL;
+ if (!PyArg_ParseTuple(_args, "|O", &new))
+ return NULL;
- if (Dlg_UserItemProc_callback && new && new != Py_None) {
- PyErr_SetString(Dlg_Error, "Another UserItemProc is already installed");
- return NULL;
- }
+ if (Dlg_UserItemProc_callback && new && new != Py_None) {
+ PyErr_SetString(Dlg_Error, "Another UserItemProc is already installed");
+ return NULL;
+ }
- if (new == NULL || new == Py_None) {
- new = NULL;
- _res = Py_None;
- Py_INCREF(Py_None);
- } else {
- Py_INCREF(new);
- _res = Py_BuildValue("O&", ResObj_New, (Handle)NewUserItemUPP(Dlg_UnivUserItemProc));
- }
+ if (new == NULL || new == Py_None) {
+ new = NULL;
+ _res = Py_None;
+ Py_INCREF(Py_None);
+ } else {
+ Py_INCREF(new);
+ _res = Py_BuildValue("O&", ResObj_New, (Handle)NewUserItemUPP(Dlg_UnivUserItemProc));
+ }
- Dlg_UserItemProc_callback = new;
- return _res;
+ Dlg_UserItemProc_callback = new;
+ return _res;
}
static PyMethodDef Dlg_methods[] = {
- {"NewDialog", (PyCFunction)Dlg_NewDialog, 1,
- PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, SInt16 procID, WindowPtr behind, Boolean goAwayFlag, SInt32 refCon, Handle items) -> (DialogPtr _rv)")},
- {"GetNewDialog", (PyCFunction)Dlg_GetNewDialog, 1,
- PyDoc_STR("(SInt16 dialogID, WindowPtr behind) -> (DialogPtr _rv)")},
- {"NewColorDialog", (PyCFunction)Dlg_NewColorDialog, 1,
- PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, SInt16 procID, WindowPtr behind, Boolean goAwayFlag, SInt32 refCon, Handle items) -> (DialogPtr _rv)")},
- {"ModalDialog", (PyCFunction)Dlg_ModalDialog, 1,
- PyDoc_STR("(PyObject* modalFilter) -> (DialogItemIndex itemHit)")},
- {"IsDialogEvent", (PyCFunction)Dlg_IsDialogEvent, 1,
- PyDoc_STR("(EventRecord theEvent) -> (Boolean _rv)")},
- {"DialogSelect", (PyCFunction)Dlg_DialogSelect, 1,
- PyDoc_STR("(EventRecord theEvent) -> (Boolean _rv, DialogPtr theDialog, DialogItemIndex itemHit)")},
- {"Alert", (PyCFunction)Dlg_Alert, 1,
- PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
- {"StopAlert", (PyCFunction)Dlg_StopAlert, 1,
- PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
- {"NoteAlert", (PyCFunction)Dlg_NoteAlert, 1,
- PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
- {"CautionAlert", (PyCFunction)Dlg_CautionAlert, 1,
- PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
- {"ParamText", (PyCFunction)Dlg_ParamText, 1,
- PyDoc_STR("(Str255 param0, Str255 param1, Str255 param2, Str255 param3) -> None")},
- {"GetDialogItemText", (PyCFunction)Dlg_GetDialogItemText, 1,
- PyDoc_STR("(Handle item) -> (Str255 text)")},
- {"SetDialogItemText", (PyCFunction)Dlg_SetDialogItemText, 1,
- PyDoc_STR("(Handle item, Str255 text) -> None")},
- {"GetAlertStage", (PyCFunction)Dlg_GetAlertStage, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"SetDialogFont", (PyCFunction)Dlg_SetDialogFont, 1,
- PyDoc_STR("(SInt16 fontNum) -> None")},
- {"ResetAlertStage", (PyCFunction)Dlg_ResetAlertStage, 1,
- PyDoc_STR("() -> None")},
- {"GetParamText", (PyCFunction)Dlg_GetParamText, 1,
- PyDoc_STR("(Str255 param0, Str255 param1, Str255 param2, Str255 param3) -> None")},
- {"NewFeaturesDialog", (PyCFunction)Dlg_NewFeaturesDialog, 1,
- PyDoc_STR("(Rect inBoundsRect, Str255 inTitle, Boolean inIsVisible, SInt16 inProcID, WindowPtr inBehind, Boolean inGoAwayFlag, SInt32 inRefCon, Handle inItemListHandle, UInt32 inFlags) -> (DialogPtr _rv)")},
- {"GetDialogFromWindow", (PyCFunction)Dlg_GetDialogFromWindow, 1,
- PyDoc_STR("(WindowPtr window) -> (DialogPtr _rv)")},
- {"SetUserItemHandler", (PyCFunction)Dlg_SetUserItemHandler, 1,
- PyDoc_STR(NULL)},
- {NULL, NULL, 0}
+ {"NewDialog", (PyCFunction)Dlg_NewDialog, 1,
+ PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, SInt16 procID, WindowPtr behind, Boolean goAwayFlag, SInt32 refCon, Handle items) -> (DialogPtr _rv)")},
+ {"GetNewDialog", (PyCFunction)Dlg_GetNewDialog, 1,
+ PyDoc_STR("(SInt16 dialogID, WindowPtr behind) -> (DialogPtr _rv)")},
+ {"NewColorDialog", (PyCFunction)Dlg_NewColorDialog, 1,
+ PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, SInt16 procID, WindowPtr behind, Boolean goAwayFlag, SInt32 refCon, Handle items) -> (DialogPtr _rv)")},
+ {"ModalDialog", (PyCFunction)Dlg_ModalDialog, 1,
+ PyDoc_STR("(PyObject* modalFilter) -> (DialogItemIndex itemHit)")},
+ {"IsDialogEvent", (PyCFunction)Dlg_IsDialogEvent, 1,
+ PyDoc_STR("(EventRecord theEvent) -> (Boolean _rv)")},
+ {"DialogSelect", (PyCFunction)Dlg_DialogSelect, 1,
+ PyDoc_STR("(EventRecord theEvent) -> (Boolean _rv, DialogPtr theDialog, DialogItemIndex itemHit)")},
+ {"Alert", (PyCFunction)Dlg_Alert, 1,
+ PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
+ {"StopAlert", (PyCFunction)Dlg_StopAlert, 1,
+ PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
+ {"NoteAlert", (PyCFunction)Dlg_NoteAlert, 1,
+ PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
+ {"CautionAlert", (PyCFunction)Dlg_CautionAlert, 1,
+ PyDoc_STR("(SInt16 alertID, PyObject* modalFilter) -> (DialogItemIndex _rv)")},
+ {"ParamText", (PyCFunction)Dlg_ParamText, 1,
+ PyDoc_STR("(Str255 param0, Str255 param1, Str255 param2, Str255 param3) -> None")},
+ {"GetDialogItemText", (PyCFunction)Dlg_GetDialogItemText, 1,
+ PyDoc_STR("(Handle item) -> (Str255 text)")},
+ {"SetDialogItemText", (PyCFunction)Dlg_SetDialogItemText, 1,
+ PyDoc_STR("(Handle item, Str255 text) -> None")},
+ {"GetAlertStage", (PyCFunction)Dlg_GetAlertStage, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"SetDialogFont", (PyCFunction)Dlg_SetDialogFont, 1,
+ PyDoc_STR("(SInt16 fontNum) -> None")},
+ {"ResetAlertStage", (PyCFunction)Dlg_ResetAlertStage, 1,
+ PyDoc_STR("() -> None")},
+ {"GetParamText", (PyCFunction)Dlg_GetParamText, 1,
+ PyDoc_STR("(Str255 param0, Str255 param1, Str255 param2, Str255 param3) -> None")},
+ {"NewFeaturesDialog", (PyCFunction)Dlg_NewFeaturesDialog, 1,
+ PyDoc_STR("(Rect inBoundsRect, Str255 inTitle, Boolean inIsVisible, SInt16 inProcID, WindowPtr inBehind, Boolean inGoAwayFlag, SInt32 inRefCon, Handle inItemListHandle, UInt32 inFlags) -> (DialogPtr _rv)")},
+ {"GetDialogFromWindow", (PyCFunction)Dlg_GetDialogFromWindow, 1,
+ PyDoc_STR("(WindowPtr window) -> (DialogPtr _rv)")},
+ {"SetUserItemHandler", (PyCFunction)Dlg_SetUserItemHandler, 1,
+ PyDoc_STR(NULL)},
+ {NULL, NULL, 0}
};
@@ -1530,9 +1530,9 @@ static PyMethodDef Dlg_methods[] = {
WindowPtr
DlgObj_ConvertToWindow(PyObject *self)
{
- if ( DlgObj_Check(self) )
- return GetDialogWindow(((DialogObject *)self)->ob_itself);
- return NULL;
+ if ( DlgObj_Check(self) )
+ return GetDialogWindow(((DialogObject *)self)->ob_itself);
+ return NULL;
}
#endif
/* Return the object corresponding to the dialog, or None */
@@ -1540,35 +1540,35 @@ DlgObj_ConvertToWindow(PyObject *self)
PyObject *
DlgObj_WhichDialog(DialogPtr d)
{
- PyObject *it;
+ PyObject *it;
- if (d == NULL) {
- it = Py_None;
- Py_INCREF(it);
- } else {
- WindowPtr w = GetDialogWindow(d);
+ if (d == NULL) {
+ it = Py_None;
+ Py_INCREF(it);
+ } else {
+ WindowPtr w = GetDialogWindow(d);
- it = (PyObject *) GetWRefCon(w);
- if (it == NULL || ((DialogObject *)it)->ob_itself != d || !DlgObj_Check(it)) {
+ it = (PyObject *) GetWRefCon(w);
+ if (it == NULL || ((DialogObject *)it)->ob_itself != d || !DlgObj_Check(it)) {
#if 0
- /* Should do this, but we don't have an ob_freeit for dialogs yet. */
- it = WinObj_New(w);
- ((WindowObject *)it)->ob_freeit = NULL;
+ /* Should do this, but we don't have an ob_freeit for dialogs yet. */
+ it = WinObj_New(w);
+ ((WindowObject *)it)->ob_freeit = NULL;
#else
- it = Py_None;
- Py_INCREF(it);
+ it = Py_None;
+ Py_INCREF(it);
#endif
- } else {
- Py_INCREF(it);
- }
+ } else {
+ Py_INCREF(it);
}
- return it;
+ }
+ return it;
}
#else /* __LP64__ */
static PyMethodDef Dlg_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#endif /* __LP64__ */
@@ -1576,32 +1576,32 @@ static PyMethodDef Dlg_methods[] = {
void init_Dlg(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_WhichDialog);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DialogPtr, DlgObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(DialogPtr, DlgObj_WhichDialog);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DialogPtr, DlgObj_Convert);
#endif /* !__LP64__ */
- m = Py_InitModule("_Dlg", Dlg_methods);
+ m = Py_InitModule("_Dlg", Dlg_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Dlg_Error = PyMac_GetOSErrException();
- if (Dlg_Error == NULL ||
- PyDict_SetItemString(d, "Error", Dlg_Error) != 0)
- return;
- Dialog_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Dialog_Type) < 0) return;
- Py_INCREF(&Dialog_Type);
- PyModule_AddObject(m, "Dialog", (PyObject *)&Dialog_Type);
- /* Backward-compatible name */
- Py_INCREF(&Dialog_Type);
- PyModule_AddObject(m, "DialogType", (PyObject *)&Dialog_Type);
+ d = PyModule_GetDict(m);
+ Dlg_Error = PyMac_GetOSErrException();
+ if (Dlg_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Dlg_Error) != 0)
+ return;
+ Dialog_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Dialog_Type) < 0) return;
+ Py_INCREF(&Dialog_Type);
+ PyModule_AddObject(m, "Dialog", (PyObject *)&Dialog_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Dialog_Type);
+ PyModule_AddObject(m, "DialogType", (PyObject *)&Dialog_Type);
#endif /* !__LP64__ */
}
diff --git a/Mac/Modules/drag/_Dragmodule.c b/Mac/Modules/drag/_Dragmodule.c
index 797fb32..aa87690 100644
--- a/Mac/Modules/drag/_Dragmodule.c
+++ b/Mac/Modules/drag/_Dragmodule.c
@@ -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)
@@ -44,693 +44,693 @@ PyTypeObject DragObj_Type;
#define DragObj_Check(x) ((x)->ob_type == &DragObj_Type || PyObject_TypeCheck((x), &DragObj_Type))
typedef struct DragObjObject {
- PyObject_HEAD
- DragRef ob_itself;
- PyObject *sendproc;
+ PyObject_HEAD
+ DragRef ob_itself;
+ PyObject *sendproc;
} DragObjObject;
PyObject *DragObj_New(DragRef itself)
{
- DragObjObject *it;
- if (itself == NULL) {
- PyErr_SetString(Drag_Error,"Cannot create null Drag");
- return NULL;
- }
- it = PyObject_NEW(DragObjObject, &DragObj_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->sendproc = NULL;
- return (PyObject *)it;
+ DragObjObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Drag_Error,"Cannot create null Drag");
+ return NULL;
+ }
+ it = PyObject_NEW(DragObjObject, &DragObj_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->sendproc = NULL;
+ return (PyObject *)it;
}
int DragObj_Convert(PyObject *v, DragRef *p_itself)
{
- if (!DragObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "DragObj required");
- return 0;
- }
- *p_itself = ((DragObjObject *)v)->ob_itself;
- return 1;
+ if (!DragObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "DragObj required");
+ return 0;
+ }
+ *p_itself = ((DragObjObject *)v)->ob_itself;
+ return 1;
}
static void DragObj_dealloc(DragObjObject *self)
{
- Py_XDECREF(self->sendproc);
- self->ob_type->tp_free((PyObject *)self);
+ Py_XDECREF(self->sendproc);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *DragObj_DisposeDrag(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef DisposeDrag
- PyMac_PRECHECK(DisposeDrag);
+ PyMac_PRECHECK(DisposeDrag);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = DisposeDrag(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = DisposeDrag(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_AddDragItemFlavor(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- FlavorType theType;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
- FlavorFlags theFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ FlavorType theType;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
+ FlavorFlags theFlags;
#ifndef AddDragItemFlavor
- PyMac_PRECHECK(AddDragItemFlavor);
+ PyMac_PRECHECK(AddDragItemFlavor);
#endif
- if (!PyArg_ParseTuple(_args, "lO&z#l",
- &theItemRef,
- PyMac_GetOSType, &theType,
- &dataPtr__in__, &dataPtr__in_len__,
- &theFlags))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = AddDragItemFlavor(_self->ob_itself,
- theItemRef,
- theType,
- dataPtr__in__, dataPtr__len__,
- theFlags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&z#l",
+ &theItemRef,
+ PyMac_GetOSType, &theType,
+ &dataPtr__in__, &dataPtr__in_len__,
+ &theFlags))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = AddDragItemFlavor(_self->ob_itself,
+ theItemRef,
+ theType,
+ dataPtr__in__, dataPtr__len__,
+ theFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_SetDragItemFlavorData(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- FlavorType theType;
- char *dataPtr__in__;
- long dataPtr__len__;
- int dataPtr__in_len__;
- UInt32 dataOffset;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ FlavorType theType;
+ char *dataPtr__in__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
+ UInt32 dataOffset;
#ifndef SetDragItemFlavorData
- PyMac_PRECHECK(SetDragItemFlavorData);
+ PyMac_PRECHECK(SetDragItemFlavorData);
#endif
- if (!PyArg_ParseTuple(_args, "lO&z#l",
- &theItemRef,
- PyMac_GetOSType, &theType,
- &dataPtr__in__, &dataPtr__in_len__,
- &dataOffset))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- _err = SetDragItemFlavorData(_self->ob_itself,
- theItemRef,
- theType,
- dataPtr__in__, dataPtr__len__,
- dataOffset);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&z#l",
+ &theItemRef,
+ PyMac_GetOSType, &theType,
+ &dataPtr__in__, &dataPtr__in_len__,
+ &dataOffset))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = SetDragItemFlavorData(_self->ob_itself,
+ theItemRef,
+ theType,
+ dataPtr__in__, dataPtr__len__,
+ dataOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_SetDragImage(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle imagePixMap;
- RgnHandle imageRgn;
- Point imageOffsetPt;
- DragImageFlags theImageFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle imagePixMap;
+ RgnHandle imageRgn;
+ Point imageOffsetPt;
+ DragImageFlags theImageFlags;
#ifndef SetDragImage
- PyMac_PRECHECK(SetDragImage);
+ PyMac_PRECHECK(SetDragImage);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- ResObj_Convert, &imagePixMap,
- ResObj_Convert, &imageRgn,
- PyMac_GetPoint, &imageOffsetPt,
- &theImageFlags))
- return NULL;
- _err = SetDragImage(_self->ob_itself,
- imagePixMap,
- imageRgn,
- imageOffsetPt,
- theImageFlags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ ResObj_Convert, &imagePixMap,
+ ResObj_Convert, &imageRgn,
+ PyMac_GetPoint, &imageOffsetPt,
+ &theImageFlags))
+ return NULL;
+ _err = SetDragImage(_self->ob_itself,
+ imagePixMap,
+ imageRgn,
+ imageOffsetPt,
+ theImageFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_ChangeDragBehaviors(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DragBehaviors inBehaviorsToSet;
- DragBehaviors inBehaviorsToClear;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DragBehaviors inBehaviorsToSet;
+ DragBehaviors inBehaviorsToClear;
#ifndef ChangeDragBehaviors
- PyMac_PRECHECK(ChangeDragBehaviors);
+ PyMac_PRECHECK(ChangeDragBehaviors);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &inBehaviorsToSet,
- &inBehaviorsToClear))
- return NULL;
- _err = ChangeDragBehaviors(_self->ob_itself,
- inBehaviorsToSet,
- inBehaviorsToClear);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &inBehaviorsToSet,
+ &inBehaviorsToClear))
+ return NULL;
+ _err = ChangeDragBehaviors(_self->ob_itself,
+ inBehaviorsToSet,
+ inBehaviorsToClear);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_TrackDrag(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- EventRecord theEvent;
- RgnHandle theRegion;
+ PyObject *_res = NULL;
+ OSErr _err;
+ EventRecord theEvent;
+ RgnHandle theRegion;
#ifndef TrackDrag
- PyMac_PRECHECK(TrackDrag);
+ PyMac_PRECHECK(TrackDrag);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetEventRecord, &theEvent,
- ResObj_Convert, &theRegion))
- return NULL;
- _err = TrackDrag(_self->ob_itself,
- &theEvent,
- theRegion);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetEventRecord, &theEvent,
+ ResObj_Convert, &theRegion))
+ return NULL;
+ _err = TrackDrag(_self->ob_itself,
+ &theEvent,
+ theRegion);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_CountDragItems(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UInt16 numItems;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UInt16 numItems;
#ifndef CountDragItems
- PyMac_PRECHECK(CountDragItems);
+ PyMac_PRECHECK(CountDragItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CountDragItems(_self->ob_itself,
- &numItems);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- numItems);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CountDragItems(_self->ob_itself,
+ &numItems);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ numItems);
+ return _res;
}
static PyObject *DragObj_GetDragItemReferenceNumber(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UInt16 index;
- ItemReference theItemRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UInt16 index;
+ ItemReference theItemRef;
#ifndef GetDragItemReferenceNumber
- PyMac_PRECHECK(GetDragItemReferenceNumber);
+ PyMac_PRECHECK(GetDragItemReferenceNumber);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &index))
- return NULL;
- _err = GetDragItemReferenceNumber(_self->ob_itself,
- index,
- &theItemRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- theItemRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &index))
+ return NULL;
+ _err = GetDragItemReferenceNumber(_self->ob_itself,
+ index,
+ &theItemRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ theItemRef);
+ return _res;
}
static PyObject *DragObj_CountDragItemFlavors(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- UInt16 numFlavors;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ UInt16 numFlavors;
#ifndef CountDragItemFlavors
- PyMac_PRECHECK(CountDragItemFlavors);
+ PyMac_PRECHECK(CountDragItemFlavors);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &theItemRef))
- return NULL;
- _err = CountDragItemFlavors(_self->ob_itself,
- theItemRef,
- &numFlavors);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- numFlavors);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &theItemRef))
+ return NULL;
+ _err = CountDragItemFlavors(_self->ob_itself,
+ theItemRef,
+ &numFlavors);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ numFlavors);
+ return _res;
}
static PyObject *DragObj_GetFlavorType(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- UInt16 index;
- FlavorType theType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ UInt16 index;
+ FlavorType theType;
#ifndef GetFlavorType
- PyMac_PRECHECK(GetFlavorType);
+ PyMac_PRECHECK(GetFlavorType);
#endif
- if (!PyArg_ParseTuple(_args, "lH",
- &theItemRef,
- &index))
- return NULL;
- _err = GetFlavorType(_self->ob_itself,
- theItemRef,
- index,
- &theType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildOSType, theType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lH",
+ &theItemRef,
+ &index))
+ return NULL;
+ _err = GetFlavorType(_self->ob_itself,
+ theItemRef,
+ index,
+ &theType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildOSType, theType);
+ return _res;
}
static PyObject *DragObj_GetFlavorFlags(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- FlavorType theType;
- FlavorFlags theFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ FlavorType theType;
+ FlavorFlags theFlags;
#ifndef GetFlavorFlags
- PyMac_PRECHECK(GetFlavorFlags);
+ PyMac_PRECHECK(GetFlavorFlags);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &theItemRef,
- PyMac_GetOSType, &theType))
- return NULL;
- _err = GetFlavorFlags(_self->ob_itself,
- theItemRef,
- theType,
- &theFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- theFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &theItemRef,
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _err = GetFlavorFlags(_self->ob_itself,
+ theItemRef,
+ theType,
+ &theFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ theFlags);
+ return _res;
}
static PyObject *DragObj_GetFlavorDataSize(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- FlavorType theType;
- Size dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ FlavorType theType;
+ Size dataSize;
#ifndef GetFlavorDataSize
- PyMac_PRECHECK(GetFlavorDataSize);
+ PyMac_PRECHECK(GetFlavorDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &theItemRef,
- PyMac_GetOSType, &theType))
- return NULL;
- _err = GetFlavorDataSize(_self->ob_itself,
- theItemRef,
- theType,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- dataSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &theItemRef,
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _err = GetFlavorDataSize(_self->ob_itself,
+ theItemRef,
+ theType,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ dataSize);
+ return _res;
}
static PyObject *DragObj_GetFlavorData(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- FlavorType theType;
- char *dataPtr__out__;
- long dataPtr__len__;
- int dataPtr__in_len__;
- UInt32 dataOffset;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ FlavorType theType;
+ char *dataPtr__out__;
+ long dataPtr__len__;
+ int dataPtr__in_len__;
+ UInt32 dataOffset;
#ifndef GetFlavorData
- PyMac_PRECHECK(GetFlavorData);
+ PyMac_PRECHECK(GetFlavorData);
#endif
- if (!PyArg_ParseTuple(_args, "lO&il",
- &theItemRef,
- PyMac_GetOSType, &theType,
- &dataPtr__in_len__,
- &dataOffset))
- return NULL;
- if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
- {
- PyErr_NoMemory();
- goto dataPtr__error__;
- }
- dataPtr__len__ = dataPtr__in_len__;
- _err = GetFlavorData(_self->ob_itself,
- theItemRef,
- theType,
- dataPtr__out__, &dataPtr__len__,
- dataOffset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("s#",
- dataPtr__out__, (int)dataPtr__len__);
- free(dataPtr__out__);
+ if (!PyArg_ParseTuple(_args, "lO&il",
+ &theItemRef,
+ PyMac_GetOSType, &theType,
+ &dataPtr__in_len__,
+ &dataOffset))
+ return NULL;
+ if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
+ {
+ PyErr_NoMemory();
+ goto dataPtr__error__;
+ }
+ dataPtr__len__ = dataPtr__in_len__;
+ _err = GetFlavorData(_self->ob_itself,
+ theItemRef,
+ theType,
+ dataPtr__out__, &dataPtr__len__,
+ dataOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("s#",
+ dataPtr__out__, (int)dataPtr__len__);
+ free(dataPtr__out__);
dataPtr__error__: ;
- return _res;
+ return _res;
}
static PyObject *DragObj_GetDragItemBounds(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- Rect itemBounds;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ Rect itemBounds;
#ifndef GetDragItemBounds
- PyMac_PRECHECK(GetDragItemBounds);
+ PyMac_PRECHECK(GetDragItemBounds);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &theItemRef))
- return NULL;
- _err = GetDragItemBounds(_self->ob_itself,
- theItemRef,
- &itemBounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &itemBounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &theItemRef))
+ return NULL;
+ _err = GetDragItemBounds(_self->ob_itself,
+ theItemRef,
+ &itemBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &itemBounds);
+ return _res;
}
static PyObject *DragObj_SetDragItemBounds(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ItemReference theItemRef;
- Rect itemBounds;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ItemReference theItemRef;
+ Rect itemBounds;
#ifndef SetDragItemBounds
- PyMac_PRECHECK(SetDragItemBounds);
+ PyMac_PRECHECK(SetDragItemBounds);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &theItemRef,
- PyMac_GetRect, &itemBounds))
- return NULL;
- _err = SetDragItemBounds(_self->ob_itself,
- theItemRef,
- &itemBounds);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &theItemRef,
+ PyMac_GetRect, &itemBounds))
+ return NULL;
+ _err = SetDragItemBounds(_self->ob_itself,
+ theItemRef,
+ &itemBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_GetDropLocation(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEDesc dropLocation;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEDesc dropLocation;
#ifndef GetDropLocation
- PyMac_PRECHECK(GetDropLocation);
+ PyMac_PRECHECK(GetDropLocation);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDropLocation(_self->ob_itself,
- &dropLocation);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &dropLocation);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDropLocation(_self->ob_itself,
+ &dropLocation);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &dropLocation);
+ return _res;
}
static PyObject *DragObj_SetDropLocation(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AEDesc dropLocation;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AEDesc dropLocation;
#ifndef SetDropLocation
- PyMac_PRECHECK(SetDropLocation);
+ PyMac_PRECHECK(SetDropLocation);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- AEDesc_Convert, &dropLocation))
- return NULL;
- _err = SetDropLocation(_self->ob_itself,
- &dropLocation);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ AEDesc_Convert, &dropLocation))
+ return NULL;
+ _err = SetDropLocation(_self->ob_itself,
+ &dropLocation);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_GetDragAttributes(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DragAttributes flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DragAttributes flags;
#ifndef GetDragAttributes
- PyMac_PRECHECK(GetDragAttributes);
+ PyMac_PRECHECK(GetDragAttributes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDragAttributes(_self->ob_itself,
- &flags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDragAttributes(_self->ob_itself,
+ &flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ flags);
+ return _res;
}
static PyObject *DragObj_GetDragMouse(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Point mouse;
- Point globalPinnedMouse;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Point mouse;
+ Point globalPinnedMouse;
#ifndef GetDragMouse
- PyMac_PRECHECK(GetDragMouse);
+ PyMac_PRECHECK(GetDragMouse);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDragMouse(_self->ob_itself,
- &mouse,
- &globalPinnedMouse);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildPoint, mouse,
- PyMac_BuildPoint, globalPinnedMouse);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDragMouse(_self->ob_itself,
+ &mouse,
+ &globalPinnedMouse);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildPoint, mouse,
+ PyMac_BuildPoint, globalPinnedMouse);
+ return _res;
}
static PyObject *DragObj_SetDragMouse(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Point globalPinnedMouse;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Point globalPinnedMouse;
#ifndef SetDragMouse
- PyMac_PRECHECK(SetDragMouse);
+ PyMac_PRECHECK(SetDragMouse);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &globalPinnedMouse))
- return NULL;
- _err = SetDragMouse(_self->ob_itself,
- globalPinnedMouse);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &globalPinnedMouse))
+ return NULL;
+ _err = SetDragMouse(_self->ob_itself,
+ globalPinnedMouse);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_GetDragOrigin(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Point globalInitialMouse;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Point globalInitialMouse;
#ifndef GetDragOrigin
- PyMac_PRECHECK(GetDragOrigin);
+ PyMac_PRECHECK(GetDragOrigin);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDragOrigin(_self->ob_itself,
- &globalInitialMouse);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, globalInitialMouse);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDragOrigin(_self->ob_itself,
+ &globalInitialMouse);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, globalInitialMouse);
+ return _res;
}
static PyObject *DragObj_GetDragModifiers(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 modifiers;
- SInt16 mouseDownModifiers;
- SInt16 mouseUpModifiers;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 modifiers;
+ SInt16 mouseDownModifiers;
+ SInt16 mouseUpModifiers;
#ifndef GetDragModifiers
- PyMac_PRECHECK(GetDragModifiers);
+ PyMac_PRECHECK(GetDragModifiers);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDragModifiers(_self->ob_itself,
- &modifiers,
- &mouseDownModifiers,
- &mouseUpModifiers);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hhh",
- modifiers,
- mouseDownModifiers,
- mouseUpModifiers);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDragModifiers(_self->ob_itself,
+ &modifiers,
+ &mouseDownModifiers,
+ &mouseUpModifiers);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hhh",
+ modifiers,
+ mouseDownModifiers,
+ mouseUpModifiers);
+ return _res;
}
static PyObject *DragObj_ShowDragHilite(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle hiliteFrame;
- Boolean inside;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle hiliteFrame;
+ Boolean inside;
#ifndef ShowDragHilite
- PyMac_PRECHECK(ShowDragHilite);
+ PyMac_PRECHECK(ShowDragHilite);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- ResObj_Convert, &hiliteFrame,
- &inside))
- return NULL;
- _err = ShowDragHilite(_self->ob_itself,
- hiliteFrame,
- inside);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ ResObj_Convert, &hiliteFrame,
+ &inside))
+ return NULL;
+ _err = ShowDragHilite(_self->ob_itself,
+ hiliteFrame,
+ inside);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_HideDragHilite(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef HideDragHilite
- PyMac_PRECHECK(HideDragHilite);
+ PyMac_PRECHECK(HideDragHilite);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = HideDragHilite(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = HideDragHilite(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_DragPreScroll(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 dH;
- SInt16 dV;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 dH;
+ SInt16 dV;
#ifndef DragPreScroll
- PyMac_PRECHECK(DragPreScroll);
+ PyMac_PRECHECK(DragPreScroll);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &dH,
- &dV))
- return NULL;
- _err = DragPreScroll(_self->ob_itself,
- dH,
- dV);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &dH,
+ &dV))
+ return NULL;
+ _err = DragPreScroll(_self->ob_itself,
+ dH,
+ dV);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_DragPostScroll(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef DragPostScroll
- PyMac_PRECHECK(DragPostScroll);
+ PyMac_PRECHECK(DragPostScroll);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = DragPostScroll(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = DragPostScroll(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *DragObj_UpdateDragHilite(DragObjObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle updateRgn;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle updateRgn;
#ifndef UpdateDragHilite
- PyMac_PRECHECK(UpdateDragHilite);
+ PyMac_PRECHECK(UpdateDragHilite);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &updateRgn))
- return NULL;
- _err = UpdateDragHilite(_self->ob_itself,
- updateRgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &updateRgn))
+ return NULL;
+ _err = UpdateDragHilite(_self->ob_itself,
+ updateRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef DragObj_methods[] = {
- {"DisposeDrag", (PyCFunction)DragObj_DisposeDrag, 1,
- PyDoc_STR("() -> None")},
- {"AddDragItemFlavor", (PyCFunction)DragObj_AddDragItemFlavor, 1,
- PyDoc_STR("(ItemReference theItemRef, FlavorType theType, Buffer dataPtr, FlavorFlags theFlags) -> None")},
- {"SetDragItemFlavorData", (PyCFunction)DragObj_SetDragItemFlavorData, 1,
- PyDoc_STR("(ItemReference theItemRef, FlavorType theType, Buffer dataPtr, UInt32 dataOffset) -> None")},
- {"SetDragImage", (PyCFunction)DragObj_SetDragImage, 1,
- PyDoc_STR("(PixMapHandle imagePixMap, RgnHandle imageRgn, Point imageOffsetPt, DragImageFlags theImageFlags) -> None")},
- {"ChangeDragBehaviors", (PyCFunction)DragObj_ChangeDragBehaviors, 1,
- PyDoc_STR("(DragBehaviors inBehaviorsToSet, DragBehaviors inBehaviorsToClear) -> None")},
- {"TrackDrag", (PyCFunction)DragObj_TrackDrag, 1,
- PyDoc_STR("(EventRecord theEvent, RgnHandle theRegion) -> None")},
- {"CountDragItems", (PyCFunction)DragObj_CountDragItems, 1,
- PyDoc_STR("() -> (UInt16 numItems)")},
- {"GetDragItemReferenceNumber", (PyCFunction)DragObj_GetDragItemReferenceNumber, 1,
- PyDoc_STR("(UInt16 index) -> (ItemReference theItemRef)")},
- {"CountDragItemFlavors", (PyCFunction)DragObj_CountDragItemFlavors, 1,
- PyDoc_STR("(ItemReference theItemRef) -> (UInt16 numFlavors)")},
- {"GetFlavorType", (PyCFunction)DragObj_GetFlavorType, 1,
- PyDoc_STR("(ItemReference theItemRef, UInt16 index) -> (FlavorType theType)")},
- {"GetFlavorFlags", (PyCFunction)DragObj_GetFlavorFlags, 1,
- PyDoc_STR("(ItemReference theItemRef, FlavorType theType) -> (FlavorFlags theFlags)")},
- {"GetFlavorDataSize", (PyCFunction)DragObj_GetFlavorDataSize, 1,
- PyDoc_STR("(ItemReference theItemRef, FlavorType theType) -> (Size dataSize)")},
- {"GetFlavorData", (PyCFunction)DragObj_GetFlavorData, 1,
- PyDoc_STR("(ItemReference theItemRef, FlavorType theType, Buffer dataPtr, UInt32 dataOffset) -> (Buffer dataPtr)")},
- {"GetDragItemBounds", (PyCFunction)DragObj_GetDragItemBounds, 1,
- PyDoc_STR("(ItemReference theItemRef) -> (Rect itemBounds)")},
- {"SetDragItemBounds", (PyCFunction)DragObj_SetDragItemBounds, 1,
- PyDoc_STR("(ItemReference theItemRef, Rect itemBounds) -> None")},
- {"GetDropLocation", (PyCFunction)DragObj_GetDropLocation, 1,
- PyDoc_STR("() -> (AEDesc dropLocation)")},
- {"SetDropLocation", (PyCFunction)DragObj_SetDropLocation, 1,
- PyDoc_STR("(AEDesc dropLocation) -> None")},
- {"GetDragAttributes", (PyCFunction)DragObj_GetDragAttributes, 1,
- PyDoc_STR("() -> (DragAttributes flags)")},
- {"GetDragMouse", (PyCFunction)DragObj_GetDragMouse, 1,
- PyDoc_STR("() -> (Point mouse, Point globalPinnedMouse)")},
- {"SetDragMouse", (PyCFunction)DragObj_SetDragMouse, 1,
- PyDoc_STR("(Point globalPinnedMouse) -> None")},
- {"GetDragOrigin", (PyCFunction)DragObj_GetDragOrigin, 1,
- PyDoc_STR("() -> (Point globalInitialMouse)")},
- {"GetDragModifiers", (PyCFunction)DragObj_GetDragModifiers, 1,
- PyDoc_STR("() -> (SInt16 modifiers, SInt16 mouseDownModifiers, SInt16 mouseUpModifiers)")},
- {"ShowDragHilite", (PyCFunction)DragObj_ShowDragHilite, 1,
- PyDoc_STR("(RgnHandle hiliteFrame, Boolean inside) -> None")},
- {"HideDragHilite", (PyCFunction)DragObj_HideDragHilite, 1,
- PyDoc_STR("() -> None")},
- {"DragPreScroll", (PyCFunction)DragObj_DragPreScroll, 1,
- PyDoc_STR("(SInt16 dH, SInt16 dV) -> None")},
- {"DragPostScroll", (PyCFunction)DragObj_DragPostScroll, 1,
- PyDoc_STR("() -> None")},
- {"UpdateDragHilite", (PyCFunction)DragObj_UpdateDragHilite, 1,
- PyDoc_STR("(RgnHandle updateRgn) -> None")},
- {NULL, NULL, 0}
+ {"DisposeDrag", (PyCFunction)DragObj_DisposeDrag, 1,
+ PyDoc_STR("() -> None")},
+ {"AddDragItemFlavor", (PyCFunction)DragObj_AddDragItemFlavor, 1,
+ PyDoc_STR("(ItemReference theItemRef, FlavorType theType, Buffer dataPtr, FlavorFlags theFlags) -> None")},
+ {"SetDragItemFlavorData", (PyCFunction)DragObj_SetDragItemFlavorData, 1,
+ PyDoc_STR("(ItemReference theItemRef, FlavorType theType, Buffer dataPtr, UInt32 dataOffset) -> None")},
+ {"SetDragImage", (PyCFunction)DragObj_SetDragImage, 1,
+ PyDoc_STR("(PixMapHandle imagePixMap, RgnHandle imageRgn, Point imageOffsetPt, DragImageFlags theImageFlags) -> None")},
+ {"ChangeDragBehaviors", (PyCFunction)DragObj_ChangeDragBehaviors, 1,
+ PyDoc_STR("(DragBehaviors inBehaviorsToSet, DragBehaviors inBehaviorsToClear) -> None")},
+ {"TrackDrag", (PyCFunction)DragObj_TrackDrag, 1,
+ PyDoc_STR("(EventRecord theEvent, RgnHandle theRegion) -> None")},
+ {"CountDragItems", (PyCFunction)DragObj_CountDragItems, 1,
+ PyDoc_STR("() -> (UInt16 numItems)")},
+ {"GetDragItemReferenceNumber", (PyCFunction)DragObj_GetDragItemReferenceNumber, 1,
+ PyDoc_STR("(UInt16 index) -> (ItemReference theItemRef)")},
+ {"CountDragItemFlavors", (PyCFunction)DragObj_CountDragItemFlavors, 1,
+ PyDoc_STR("(ItemReference theItemRef) -> (UInt16 numFlavors)")},
+ {"GetFlavorType", (PyCFunction)DragObj_GetFlavorType, 1,
+ PyDoc_STR("(ItemReference theItemRef, UInt16 index) -> (FlavorType theType)")},
+ {"GetFlavorFlags", (PyCFunction)DragObj_GetFlavorFlags, 1,
+ PyDoc_STR("(ItemReference theItemRef, FlavorType theType) -> (FlavorFlags theFlags)")},
+ {"GetFlavorDataSize", (PyCFunction)DragObj_GetFlavorDataSize, 1,
+ PyDoc_STR("(ItemReference theItemRef, FlavorType theType) -> (Size dataSize)")},
+ {"GetFlavorData", (PyCFunction)DragObj_GetFlavorData, 1,
+ PyDoc_STR("(ItemReference theItemRef, FlavorType theType, Buffer dataPtr, UInt32 dataOffset) -> (Buffer dataPtr)")},
+ {"GetDragItemBounds", (PyCFunction)DragObj_GetDragItemBounds, 1,
+ PyDoc_STR("(ItemReference theItemRef) -> (Rect itemBounds)")},
+ {"SetDragItemBounds", (PyCFunction)DragObj_SetDragItemBounds, 1,
+ PyDoc_STR("(ItemReference theItemRef, Rect itemBounds) -> None")},
+ {"GetDropLocation", (PyCFunction)DragObj_GetDropLocation, 1,
+ PyDoc_STR("() -> (AEDesc dropLocation)")},
+ {"SetDropLocation", (PyCFunction)DragObj_SetDropLocation, 1,
+ PyDoc_STR("(AEDesc dropLocation) -> None")},
+ {"GetDragAttributes", (PyCFunction)DragObj_GetDragAttributes, 1,
+ PyDoc_STR("() -> (DragAttributes flags)")},
+ {"GetDragMouse", (PyCFunction)DragObj_GetDragMouse, 1,
+ PyDoc_STR("() -> (Point mouse, Point globalPinnedMouse)")},
+ {"SetDragMouse", (PyCFunction)DragObj_SetDragMouse, 1,
+ PyDoc_STR("(Point globalPinnedMouse) -> None")},
+ {"GetDragOrigin", (PyCFunction)DragObj_GetDragOrigin, 1,
+ PyDoc_STR("() -> (Point globalInitialMouse)")},
+ {"GetDragModifiers", (PyCFunction)DragObj_GetDragModifiers, 1,
+ PyDoc_STR("() -> (SInt16 modifiers, SInt16 mouseDownModifiers, SInt16 mouseUpModifiers)")},
+ {"ShowDragHilite", (PyCFunction)DragObj_ShowDragHilite, 1,
+ PyDoc_STR("(RgnHandle hiliteFrame, Boolean inside) -> None")},
+ {"HideDragHilite", (PyCFunction)DragObj_HideDragHilite, 1,
+ PyDoc_STR("() -> None")},
+ {"DragPreScroll", (PyCFunction)DragObj_DragPreScroll, 1,
+ PyDoc_STR("(SInt16 dH, SInt16 dV) -> None")},
+ {"DragPostScroll", (PyCFunction)DragObj_DragPostScroll, 1,
+ PyDoc_STR("() -> None")},
+ {"UpdateDragHilite", (PyCFunction)DragObj_UpdateDragHilite, 1,
+ PyDoc_STR("(RgnHandle updateRgn) -> None")},
+ {NULL, NULL, 0}
};
#define DragObj_getsetlist NULL
@@ -747,61 +747,61 @@ static PyMethodDef DragObj_methods[] = {
static PyObject *DragObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- DragRef itself;
- char *kw[] = {"itself", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, DragObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((DragObjObject *)_self)->ob_itself = itself;
- return _self;
+ PyObject *_self;
+ DragRef itself;
+ char *kw[] = {"itself", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, DragObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((DragObjObject *)_self)->ob_itself = itself;
+ return _self;
}
#define DragObj_tp_free PyObject_Del
PyTypeObject DragObj_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Drag.DragObj", /*tp_name*/
- sizeof(DragObjObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) DragObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) DragObj_compare, /*tp_compare*/
- (reprfunc) DragObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) DragObj_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*/
- DragObj_methods, /* tp_methods */
- 0, /*tp_members*/
- DragObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- DragObj_tp_init, /* tp_init */
- DragObj_tp_alloc, /* tp_alloc */
- DragObj_tp_new, /* tp_new */
- DragObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Drag.DragObj", /*tp_name*/
+ sizeof(DragObjObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) DragObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) DragObj_compare, /*tp_compare*/
+ (reprfunc) DragObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) DragObj_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*/
+ DragObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ DragObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ DragObj_tp_init, /* tp_init */
+ DragObj_tp_alloc, /* tp_alloc */
+ DragObj_tp_new, /* tp_new */
+ DragObj_tp_free, /* tp_free */
};
/* -------------------- End object type DragObj --------------------- */
@@ -809,204 +809,204 @@ PyTypeObject DragObj_Type = {
static PyObject *Drag_NewDrag(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DragRef theDrag;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DragRef theDrag;
#ifndef NewDrag
- PyMac_PRECHECK(NewDrag);
+ PyMac_PRECHECK(NewDrag);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = NewDrag(&theDrag);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- DragObj_New, theDrag);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = NewDrag(&theDrag);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ DragObj_New, theDrag);
+ return _res;
}
static PyObject *Drag_GetDragHiliteColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr window;
- RGBColor color;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr window;
+ RGBColor color;
#ifndef GetDragHiliteColor
- PyMac_PRECHECK(GetDragHiliteColor);
+ PyMac_PRECHECK(GetDragHiliteColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &window))
- return NULL;
- _err = GetDragHiliteColor(window,
- &color);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- QdRGB_New, &color);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &window))
+ return NULL;
+ _err = GetDragHiliteColor(window,
+ &color);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &color);
+ return _res;
}
static PyObject *Drag_WaitMouseMoved(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point initialMouse;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point initialMouse;
#ifndef WaitMouseMoved
- PyMac_PRECHECK(WaitMouseMoved);
+ PyMac_PRECHECK(WaitMouseMoved);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &initialMouse))
- return NULL;
- _rv = WaitMouseMoved(initialMouse);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &initialMouse))
+ return NULL;
+ _rv = WaitMouseMoved(initialMouse);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Drag_ZoomRects(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect fromRect;
- Rect toRect;
- SInt16 zoomSteps;
- ZoomAcceleration acceleration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect fromRect;
+ Rect toRect;
+ SInt16 zoomSteps;
+ ZoomAcceleration acceleration;
#ifndef ZoomRects
- PyMac_PRECHECK(ZoomRects);
+ PyMac_PRECHECK(ZoomRects);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hh",
- PyMac_GetRect, &fromRect,
- PyMac_GetRect, &toRect,
- &zoomSteps,
- &acceleration))
- return NULL;
- _err = ZoomRects(&fromRect,
- &toRect,
- zoomSteps,
- acceleration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hh",
+ PyMac_GetRect, &fromRect,
+ PyMac_GetRect, &toRect,
+ &zoomSteps,
+ &acceleration))
+ return NULL;
+ _err = ZoomRects(&fromRect,
+ &toRect,
+ zoomSteps,
+ acceleration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Drag_ZoomRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle region;
- Point zoomDistance;
- SInt16 zoomSteps;
- ZoomAcceleration acceleration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle region;
+ Point zoomDistance;
+ SInt16 zoomSteps;
+ ZoomAcceleration acceleration;
#ifndef ZoomRegion
- PyMac_PRECHECK(ZoomRegion);
+ PyMac_PRECHECK(ZoomRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hh",
- ResObj_Convert, &region,
- PyMac_GetPoint, &zoomDistance,
- &zoomSteps,
- &acceleration))
- return NULL;
- _err = ZoomRegion(region,
- zoomDistance,
- zoomSteps,
- acceleration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hh",
+ ResObj_Convert, &region,
+ PyMac_GetPoint, &zoomDistance,
+ &zoomSteps,
+ &acceleration))
+ return NULL;
+ _err = ZoomRegion(region,
+ zoomDistance,
+ zoomSteps,
+ acceleration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Drag_InstallTrackingHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- PyObject *callback;
- WindowPtr theWindow = NULL;
- OSErr _err;
+ PyObject *callback;
+ WindowPtr theWindow = NULL;
+ OSErr _err;
- if ( !PyArg_ParseTuple(_args, "O|O&", &callback, WinObj_Convert, &theWindow) )
- return NULL;
- Py_INCREF(callback); /* Cannot decref later, too bad */
- _err = InstallTrackingHandler(dragglue_TrackingHandlerUPP, theWindow, (void *)callback);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if ( !PyArg_ParseTuple(_args, "O|O&", &callback, WinObj_Convert, &theWindow) )
+ return NULL;
+ Py_INCREF(callback); /* Cannot decref later, too bad */
+ _err = InstallTrackingHandler(dragglue_TrackingHandlerUPP, theWindow, (void *)callback);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Drag_InstallReceiveHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- PyObject *callback;
- WindowPtr theWindow = NULL;
- OSErr _err;
+ PyObject *callback;
+ WindowPtr theWindow = NULL;
+ OSErr _err;
- if ( !PyArg_ParseTuple(_args, "O|O&", &callback, WinObj_Convert, &theWindow) )
- return NULL;
- Py_INCREF(callback); /* Cannot decref later, too bad */
- _err = InstallReceiveHandler(dragglue_ReceiveHandlerUPP, theWindow, (void *)callback);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if ( !PyArg_ParseTuple(_args, "O|O&", &callback, WinObj_Convert, &theWindow) )
+ return NULL;
+ Py_INCREF(callback); /* Cannot decref later, too bad */
+ _err = InstallReceiveHandler(dragglue_ReceiveHandlerUPP, theWindow, (void *)callback);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Drag_RemoveTrackingHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- WindowPtr theWindow = NULL;
- OSErr _err;
+ WindowPtr theWindow = NULL;
+ OSErr _err;
- if ( !PyArg_ParseTuple(_args, "|O&", WinObj_Convert, &theWindow) )
- return NULL;
- _err = RemoveTrackingHandler(dragglue_TrackingHandlerUPP, theWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if ( !PyArg_ParseTuple(_args, "|O&", WinObj_Convert, &theWindow) )
+ return NULL;
+ _err = RemoveTrackingHandler(dragglue_TrackingHandlerUPP, theWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Drag_RemoveReceiveHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- WindowPtr theWindow = NULL;
- OSErr _err;
+ WindowPtr theWindow = NULL;
+ OSErr _err;
- if ( !PyArg_ParseTuple(_args, "|O&", WinObj_Convert, &theWindow) )
- return NULL;
- _err = RemoveReceiveHandler(dragglue_ReceiveHandlerUPP, theWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if ( !PyArg_ParseTuple(_args, "|O&", WinObj_Convert, &theWindow) )
+ return NULL;
+ _err = RemoveReceiveHandler(dragglue_ReceiveHandlerUPP, theWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef Drag_methods[] = {
- {"NewDrag", (PyCFunction)Drag_NewDrag, 1,
- PyDoc_STR("() -> (DragRef theDrag)")},
- {"GetDragHiliteColor", (PyCFunction)Drag_GetDragHiliteColor, 1,
- PyDoc_STR("(WindowPtr window) -> (RGBColor color)")},
- {"WaitMouseMoved", (PyCFunction)Drag_WaitMouseMoved, 1,
- PyDoc_STR("(Point initialMouse) -> (Boolean _rv)")},
- {"ZoomRects", (PyCFunction)Drag_ZoomRects, 1,
- PyDoc_STR("(Rect fromRect, Rect toRect, SInt16 zoomSteps, ZoomAcceleration acceleration) -> None")},
- {"ZoomRegion", (PyCFunction)Drag_ZoomRegion, 1,
- PyDoc_STR("(RgnHandle region, Point zoomDistance, SInt16 zoomSteps, ZoomAcceleration acceleration) -> None")},
- {"InstallTrackingHandler", (PyCFunction)Drag_InstallTrackingHandler, 1,
- PyDoc_STR(NULL)},
- {"InstallReceiveHandler", (PyCFunction)Drag_InstallReceiveHandler, 1,
- PyDoc_STR(NULL)},
- {"RemoveTrackingHandler", (PyCFunction)Drag_RemoveTrackingHandler, 1,
- PyDoc_STR(NULL)},
- {"RemoveReceiveHandler", (PyCFunction)Drag_RemoveReceiveHandler, 1,
- PyDoc_STR(NULL)},
- {NULL, NULL, 0}
+ {"NewDrag", (PyCFunction)Drag_NewDrag, 1,
+ PyDoc_STR("() -> (DragRef theDrag)")},
+ {"GetDragHiliteColor", (PyCFunction)Drag_GetDragHiliteColor, 1,
+ PyDoc_STR("(WindowPtr window) -> (RGBColor color)")},
+ {"WaitMouseMoved", (PyCFunction)Drag_WaitMouseMoved, 1,
+ PyDoc_STR("(Point initialMouse) -> (Boolean _rv)")},
+ {"ZoomRects", (PyCFunction)Drag_ZoomRects, 1,
+ PyDoc_STR("(Rect fromRect, Rect toRect, SInt16 zoomSteps, ZoomAcceleration acceleration) -> None")},
+ {"ZoomRegion", (PyCFunction)Drag_ZoomRegion, 1,
+ PyDoc_STR("(RgnHandle region, Point zoomDistance, SInt16 zoomSteps, ZoomAcceleration acceleration) -> None")},
+ {"InstallTrackingHandler", (PyCFunction)Drag_InstallTrackingHandler, 1,
+ PyDoc_STR(NULL)},
+ {"InstallReceiveHandler", (PyCFunction)Drag_InstallReceiveHandler, 1,
+ PyDoc_STR(NULL)},
+ {"RemoveTrackingHandler", (PyCFunction)Drag_RemoveTrackingHandler, 1,
+ PyDoc_STR(NULL)},
+ {"RemoveReceiveHandler", (PyCFunction)Drag_RemoveReceiveHandler, 1,
+ PyDoc_STR(NULL)},
+ {NULL, NULL, 0}
};
@@ -1015,81 +1015,81 @@ static pascal OSErr
dragglue_TrackingHandler(DragTrackingMessage theMessage, WindowPtr theWindow,
void *handlerRefCon, DragReference theDrag)
{
- PyObject *args, *rv;
- int i;
-
- args = Py_BuildValue("hO&O&", theMessage, DragObj_New, theDrag, WinObj_WhichWindow, theWindow);
- if ( args == NULL )
- return -1;
- rv = PyEval_CallObject((PyObject *)handlerRefCon, args);
- Py_DECREF(args);
- if ( rv == NULL ) {
- PySys_WriteStderr("Drag: Exception in TrackingHandler\n");
- PyErr_Print();
- return -1;
- }
- i = -1;
- if ( rv == Py_None )
- i = 0;
- else
- PyArg_Parse(rv, "l", &i);
- Py_DECREF(rv);
- return i;
+ PyObject *args, *rv;
+ int i;
+
+ args = Py_BuildValue("hO&O&", theMessage, DragObj_New, theDrag, WinObj_WhichWindow, theWindow);
+ if ( args == NULL )
+ return -1;
+ rv = PyEval_CallObject((PyObject *)handlerRefCon, args);
+ Py_DECREF(args);
+ if ( rv == NULL ) {
+ PySys_WriteStderr("Drag: Exception in TrackingHandler\n");
+ PyErr_Print();
+ return -1;
+ }
+ i = -1;
+ if ( rv == Py_None )
+ i = 0;
+ else
+ PyArg_Parse(rv, "l", &i);
+ Py_DECREF(rv);
+ return i;
}
static pascal OSErr
dragglue_ReceiveHandler(WindowPtr theWindow, void *handlerRefCon,
DragReference theDrag)
{
- PyObject *args, *rv;
- int i;
-
- args = Py_BuildValue("O&O&", DragObj_New, theDrag, WinObj_WhichWindow, theWindow);
- if ( args == NULL )
- return -1;
- rv = PyEval_CallObject((PyObject *)handlerRefCon, args);
- Py_DECREF(args);
- if ( rv == NULL ) {
- PySys_WriteStderr("Drag: Exception in ReceiveHandler\n");
- PyErr_Print();
- return -1;
- }
- i = -1;
- if ( rv == Py_None )
- i = 0;
- else
- PyArg_Parse(rv, "l", &i);
- Py_DECREF(rv);
- return i;
+ PyObject *args, *rv;
+ int i;
+
+ args = Py_BuildValue("O&O&", DragObj_New, theDrag, WinObj_WhichWindow, theWindow);
+ if ( args == NULL )
+ return -1;
+ rv = PyEval_CallObject((PyObject *)handlerRefCon, args);
+ Py_DECREF(args);
+ if ( rv == NULL ) {
+ PySys_WriteStderr("Drag: Exception in ReceiveHandler\n");
+ PyErr_Print();
+ return -1;
+ }
+ i = -1;
+ if ( rv == Py_None )
+ i = 0;
+ else
+ PyArg_Parse(rv, "l", &i);
+ Py_DECREF(rv);
+ return i;
}
static pascal OSErr
dragglue_SendData(FlavorType theType, void *dragSendRefCon,
ItemReference theItem, DragReference theDrag)
{
- DragObjObject *self = (DragObjObject *)dragSendRefCon;
- PyObject *args, *rv;
- int i;
-
- if ( self->sendproc == NULL )
- return -1;
- args = Py_BuildValue("O&l", PyMac_BuildOSType, theType, theItem);
- if ( args == NULL )
- return -1;
- rv = PyEval_CallObject(self->sendproc, args);
- Py_DECREF(args);
- if ( rv == NULL ) {
- PySys_WriteStderr("Drag: Exception in SendDataHandler\n");
- PyErr_Print();
- return -1;
- }
- i = -1;
- if ( rv == Py_None )
- i = 0;
- else
- PyArg_Parse(rv, "l", &i);
- Py_DECREF(rv);
- return i;
+ DragObjObject *self = (DragObjObject *)dragSendRefCon;
+ PyObject *args, *rv;
+ int i;
+
+ if ( self->sendproc == NULL )
+ return -1;
+ args = Py_BuildValue("O&l", PyMac_BuildOSType, theType, theItem);
+ if ( args == NULL )
+ return -1;
+ rv = PyEval_CallObject(self->sendproc, args);
+ Py_DECREF(args);
+ if ( rv == NULL ) {
+ PySys_WriteStderr("Drag: Exception in SendDataHandler\n");
+ PyErr_Print();
+ return -1;
+ }
+ i = -1;
+ if ( rv == Py_None )
+ i = 0;
+ else
+ PyArg_Parse(rv, "l", &i);
+ Py_DECREF(rv);
+ return i;
}
#if 0
@@ -1109,45 +1109,45 @@ dragglue_Drawing(xxxx
#endif
#else /* __LP64__ */
static PyMethodDef Drag_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#endif /* __LP64__ */
void init_Drag(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(DragRef, DragObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DragRef, DragObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(DragRef, DragObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(DragRef, DragObj_Convert);
#endif /* !__LP64__ */
- m = Py_InitModule("_Drag", Drag_methods);
+ m = Py_InitModule("_Drag", Drag_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Drag_Error = PyMac_GetOSErrException();
- if (Drag_Error == NULL ||
- PyDict_SetItemString(d, "Error", Drag_Error) != 0)
- return;
- DragObj_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&DragObj_Type) < 0) return;
- Py_INCREF(&DragObj_Type);
- PyModule_AddObject(m, "DragObj", (PyObject *)&DragObj_Type);
- /* Backward-compatible name */
- Py_INCREF(&DragObj_Type);
- PyModule_AddObject(m, "DragObjType", (PyObject *)&DragObj_Type);
-
- dragglue_TrackingHandlerUPP = NewDragTrackingHandlerUPP(dragglue_TrackingHandler);
- dragglue_ReceiveHandlerUPP = NewDragReceiveHandlerUPP(dragglue_ReceiveHandler);
- dragglue_SendDataUPP = NewDragSendDataUPP(dragglue_SendData);
+ d = PyModule_GetDict(m);
+ Drag_Error = PyMac_GetOSErrException();
+ if (Drag_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Drag_Error) != 0)
+ return;
+ DragObj_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&DragObj_Type) < 0) return;
+ Py_INCREF(&DragObj_Type);
+ PyModule_AddObject(m, "DragObj", (PyObject *)&DragObj_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&DragObj_Type);
+ PyModule_AddObject(m, "DragObjType", (PyObject *)&DragObj_Type);
+
+ dragglue_TrackingHandlerUPP = NewDragTrackingHandlerUPP(dragglue_TrackingHandler);
+ dragglue_ReceiveHandlerUPP = NewDragReceiveHandlerUPP(dragglue_ReceiveHandler);
+ dragglue_SendDataUPP = NewDragSendDataUPP(dragglue_SendData);
#if 0
- dragglue_InputUPP = NewDragInputUPP(dragglue_Input);
- dragglue_DrawingUPP = NewDragDrawingUPP(dragglue_Drawing);
+ dragglue_InputUPP = NewDragInputUPP(dragglue_Input);
+ dragglue_DrawingUPP = NewDragDrawingUPP(dragglue_Drawing);
#endif
#endif /* !__LP64__ */
diff --git a/Mac/Modules/evt/_Evtmodule.c b/Mac/Modules/evt/_Evtmodule.c
index 04f3b23..bd61efa 100644
--- a/Mac/Modules/evt/_Evtmodule.c
+++ b/Mac/Modules/evt/_Evtmodule.c
@@ -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;
-
- 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;
+ PyObject *_res = NULL;
+
+ 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;
}
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__ */
}
diff --git a/Mac/Modules/file/_Filemodule.c b/Mac/Modules/file/_Filemodule.c
index 22e12ec..eb5b16d 100644
--- a/Mac/Modules/file/_Filemodule.c
+++ b/Mac/Modules/file/_Filemodule.c
@@ -8,14 +8,14 @@
#include "pymactoolbox.h"
#ifndef HAVE_OSX105_SDK
-typedef SInt16 FSIORefNum;
+typedef SInt16 FSIORefNum;
#endif
/* 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)
@@ -35,7 +35,7 @@ extern PyObject *_PyMac_BuildFSRef(FSRef *spec);
#define PyMac_GetFSSpec _PyMac_GetFSSpec
#define PyMac_GetFSRef _PyMac_GetFSRef
-#else /* !USE_TOOLBOX_OBJECT_GLUE */
+#else /* !USE_TOOLBOX_OBJECT_GLUE */
#ifndef __LP64__
extern int PyMac_GetFSSpec(PyObject *v, FSSpec *spec);
@@ -45,7 +45,7 @@ extern PyObject *PyMac_BuildFSSpec(FSSpec *spec);
extern int PyMac_GetFSRef(PyObject *v, FSRef *fsr);
extern PyObject *PyMac_BuildFSRef(FSRef *spec);
-#endif /* !USE_TOOLBOX_OBJECT_GLUE */
+#endif /* !USE_TOOLBOX_OBJECT_GLUE */
/* Forward declarations */
static PyObject *FSRef_New(FSRef *itself);
@@ -69,13 +69,13 @@ static int Alias_Convert(PyObject *v, AliasHandle *p_itself);
static int
UTCDateTime_Convert(PyObject *v, UTCDateTime *ptr)
{
- return PyArg_Parse(v, "(HlH)", &ptr->highSeconds, &ptr->lowSeconds, &ptr->fraction);
+ return PyArg_Parse(v, "(HlH)", &ptr->highSeconds, &ptr->lowSeconds, &ptr->fraction);
}
static PyObject *
UTCDateTime_New(UTCDateTime *ptr)
{
- return Py_BuildValue("(HlH)", ptr->highSeconds, ptr->lowSeconds, ptr->fraction);
+ return Py_BuildValue("(HlH)", ptr->highSeconds, ptr->lowSeconds, ptr->fraction);
}
/*
@@ -85,22 +85,22 @@ UTCDateTime_New(UTCDateTime *ptr)
static int
myPyMac_GetOptFSSpecPtr(PyObject *v, FSSpec **spec)
{
- if (v == Py_None) {
- *spec = NULL;
- return 1;
- }
- return PyMac_GetFSSpec(v, *spec);
+ if (v == Py_None) {
+ *spec = NULL;
+ return 1;
+ }
+ return PyMac_GetFSSpec(v, *spec);
}
#endif /* !__LP64__ */
static int
myPyMac_GetOptFSRefPtr(PyObject *v, FSRef **ref)
{
- if (v == Py_None) {
- *ref = NULL;
- return 1;
- }
- return PyMac_GetFSRef(v, *ref);
+ if (v == Py_None) {
+ *ref = NULL;
+ return 1;
+ }
+ return PyMac_GetFSRef(v, *ref);
}
/*
@@ -110,52 +110,52 @@ static PyObject *
PyMac_BuildHFSUniStr255(HFSUniStr255 *itself)
{
- return Py_BuildValue("u#", itself->unicode, itself->length);
+ return Py_BuildValue("u#", itself->unicode, itself->length);
}
#ifndef __LP64__
static OSErr
_PyMac_GetFullPathname(FSSpec *fss, char *path, int len)
{
- FSRef fsr;
- OSErr err;
-
- *path = '\0';
- err = FSpMakeFSRef(fss, &fsr);
- if (err == fnfErr) {
- /* FSSpecs can point to non-existing files, fsrefs can't. */
- FSSpec fss2;
- int tocopy;
-
- err = FSMakeFSSpec(fss->vRefNum, fss->parID,
- (unsigned char*)"", &fss2);
- if (err)
- return err;
- err = FSpMakeFSRef(&fss2, &fsr);
- if (err)
- return err;
- err = (OSErr)FSRefMakePath(&fsr, (unsigned char*)path, len-1);
- if (err)
- return err;
- /* This part is not 100% safe: we append the filename part, but
- ** I'm not sure that we don't run afoul of the various 8bit
- ** encodings here. Will have to look this up at some point...
- */
- strcat(path, "/");
- tocopy = fss->name[0];
- if ((strlen(path) + tocopy) >= len)
- tocopy = len - strlen(path) - 1;
- if (tocopy > 0)
- strncat(path, (char*)fss->name+1, tocopy);
- }
- else {
- if (err)
- return err;
- err = (OSErr)FSRefMakePath(&fsr, (unsigned char*)path, len);
- if (err)
- return err;
- }
- return 0;
+ FSRef fsr;
+ OSErr err;
+
+ *path = '\0';
+ err = FSpMakeFSRef(fss, &fsr);
+ if (err == fnfErr) {
+ /* FSSpecs can point to non-existing files, fsrefs can't. */
+ FSSpec fss2;
+ int tocopy;
+
+ err = FSMakeFSSpec(fss->vRefNum, fss->parID,
+ (unsigned char*)"", &fss2);
+ if (err)
+ return err;
+ err = FSpMakeFSRef(&fss2, &fsr);
+ if (err)
+ return err;
+ err = (OSErr)FSRefMakePath(&fsr, (unsigned char*)path, len-1);
+ if (err)
+ return err;
+ /* This part is not 100% safe: we append the filename part, but
+ ** I'm not sure that we don't run afoul of the various 8bit
+ ** encodings here. Will have to look this up at some point...
+ */
+ strcat(path, "/");
+ tocopy = fss->name[0];
+ if ((strlen(path) + tocopy) >= len)
+ tocopy = len - strlen(path) - 1;
+ if (tocopy > 0)
+ strncat(path, (char*)fss->name+1, tocopy);
+ }
+ else {
+ if (err)
+ return err;
+ err = (OSErr)FSRefMakePath(&fsr, (unsigned char*)path, len);
+ if (err)
+ return err;
+ }
+ return 0;
}
#endif /* !__LP64__ */
@@ -169,263 +169,263 @@ static PyTypeObject FSCatalogInfo_Type;
#define FSCatalogInfo_Check(x) ((x)->ob_type == &FSCatalogInfo_Type || PyObject_TypeCheck((x), &FSCatalogInfo_Type))
typedef struct FSCatalogInfoObject {
- PyObject_HEAD
- FSCatalogInfo ob_itself;
+ PyObject_HEAD
+ FSCatalogInfo ob_itself;
} FSCatalogInfoObject;
static PyObject *FSCatalogInfo_New(FSCatalogInfo *itself)
{
- FSCatalogInfoObject *it;
- if (itself == NULL) { Py_INCREF(Py_None); return Py_None; }
- it = PyObject_NEW(FSCatalogInfoObject, &FSCatalogInfo_Type);
- if (it == NULL) return NULL;
- it->ob_itself = *itself;
- return (PyObject *)it;
+ FSCatalogInfoObject *it;
+ if (itself == NULL) { Py_INCREF(Py_None); return Py_None; }
+ it = PyObject_NEW(FSCatalogInfoObject, &FSCatalogInfo_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = *itself;
+ return (PyObject *)it;
}
static int FSCatalogInfo_Convert(PyObject *v, FSCatalogInfo *p_itself)
{
- if (!FSCatalogInfo_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "FSCatalogInfo required");
- return 0;
- }
- *p_itself = ((FSCatalogInfoObject *)v)->ob_itself;
- return 1;
+ if (!FSCatalogInfo_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "FSCatalogInfo required");
+ return 0;
+ }
+ *p_itself = ((FSCatalogInfoObject *)v)->ob_itself;
+ return 1;
}
static void FSCatalogInfo_dealloc(FSCatalogInfoObject *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 PyMethodDef FSCatalogInfo_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
static PyObject *FSCatalogInfo_get_nodeFlags(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("H", self->ob_itself.nodeFlags);
+ return Py_BuildValue("H", self->ob_itself.nodeFlags);
}
static int FSCatalogInfo_set_nodeFlags(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "H", &self->ob_itself.nodeFlags)-1;
- return 0;
+ return PyArg_Parse(v, "H", &self->ob_itself.nodeFlags)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_volume(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("h", self->ob_itself.volume);
+ return Py_BuildValue("h", self->ob_itself.volume);
}
static int FSCatalogInfo_set_volume(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "h", &self->ob_itself.volume)-1;
- return 0;
+ return PyArg_Parse(v, "h", &self->ob_itself.volume)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_parentDirID(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.parentDirID);
+ return Py_BuildValue("l", self->ob_itself.parentDirID);
}
static int FSCatalogInfo_set_parentDirID(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.parentDirID)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.parentDirID)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_nodeID(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.nodeID);
+ return Py_BuildValue("l", self->ob_itself.nodeID);
}
static int FSCatalogInfo_set_nodeID(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.nodeID)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.nodeID)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_createDate(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.createDate);
+ return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.createDate);
}
static int FSCatalogInfo_set_createDate(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.createDate)-1;
- return 0;
+ return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.createDate)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_contentModDate(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.contentModDate);
+ return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.contentModDate);
}
static int FSCatalogInfo_set_contentModDate(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.contentModDate)-1;
- return 0;
+ return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.contentModDate)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_attributeModDate(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.attributeModDate);
+ return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.attributeModDate);
}
static int FSCatalogInfo_set_attributeModDate(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.attributeModDate)-1;
- return 0;
+ return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.attributeModDate)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_accessDate(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.accessDate);
+ return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.accessDate);
}
static int FSCatalogInfo_set_accessDate(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.accessDate)-1;
- return 0;
+ return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.accessDate)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_backupDate(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.backupDate);
+ return Py_BuildValue("O&", UTCDateTime_New, &self->ob_itself.backupDate);
}
static int FSCatalogInfo_set_backupDate(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.backupDate)-1;
- return 0;
+ return PyArg_Parse(v, "O&", UTCDateTime_Convert, &self->ob_itself.backupDate)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_permissions(FSCatalogInfoObject *self, void *closure)
{
- FSPermissionInfo* info = (FSPermissionInfo*)&(self->ob_itself.permissions);
- return Py_BuildValue("(llll)", info->userID, info->groupID, info->userAccess, info->mode);
+ FSPermissionInfo* info = (FSPermissionInfo*)&(self->ob_itself.permissions);
+ return Py_BuildValue("(llll)", info->userID, info->groupID, info->userAccess, info->mode);
}
static int FSCatalogInfo_set_permissions(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- long userID;
- long groupID;
- long userAccess;
- long mode;
- int r;
+ long userID;
+ long groupID;
+ long userAccess;
+ long mode;
+ int r;
- FSPermissionInfo* info = (FSPermissionInfo*)&(self->ob_itself.permissions);
+ FSPermissionInfo* info = (FSPermissionInfo*)&(self->ob_itself.permissions);
- r = PyArg_Parse(v, "(llll)", &userID, &groupID, &userAccess, &mode);
- if (!r) {
- return -1;
- }
- info->userID = userID;
- info->groupID = groupID;
- info->userAccess = userAccess;
- info->mode = mode;
- return 0;
+ r = PyArg_Parse(v, "(llll)", &userID, &groupID, &userAccess, &mode);
+ if (!r) {
+ return -1;
+ }
+ info->userID = userID;
+ info->groupID = groupID;
+ info->userAccess = userAccess;
+ info->mode = mode;
+ return 0;
}
static PyObject *FSCatalogInfo_get_valence(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.valence);
+ return Py_BuildValue("l", self->ob_itself.valence);
}
static int FSCatalogInfo_set_valence(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.valence)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.valence)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_dataLogicalSize(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.dataLogicalSize);
+ return Py_BuildValue("l", self->ob_itself.dataLogicalSize);
}
static int FSCatalogInfo_set_dataLogicalSize(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.dataLogicalSize)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.dataLogicalSize)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_dataPhysicalSize(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.dataPhysicalSize);
+ return Py_BuildValue("l", self->ob_itself.dataPhysicalSize);
}
static int FSCatalogInfo_set_dataPhysicalSize(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.dataPhysicalSize)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.dataPhysicalSize)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_rsrcLogicalSize(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.rsrcLogicalSize);
+ return Py_BuildValue("l", self->ob_itself.rsrcLogicalSize);
}
static int FSCatalogInfo_set_rsrcLogicalSize(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.rsrcLogicalSize)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.rsrcLogicalSize)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_rsrcPhysicalSize(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.rsrcPhysicalSize);
+ return Py_BuildValue("l", self->ob_itself.rsrcPhysicalSize);
}
static int FSCatalogInfo_set_rsrcPhysicalSize(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.rsrcPhysicalSize)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.rsrcPhysicalSize)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_sharingFlags(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_itself.sharingFlags);
+ return Py_BuildValue("l", self->ob_itself.sharingFlags);
}
static int FSCatalogInfo_set_sharingFlags(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "l", &self->ob_itself.sharingFlags)-1;
- return 0;
+ return PyArg_Parse(v, "l", &self->ob_itself.sharingFlags)-1;
+ return 0;
}
static PyObject *FSCatalogInfo_get_userPrivileges(FSCatalogInfoObject *self, void *closure)
{
- return Py_BuildValue("b", self->ob_itself.userPrivileges);
+ return Py_BuildValue("b", self->ob_itself.userPrivileges);
}
static int FSCatalogInfo_set_userPrivileges(FSCatalogInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "b", &self->ob_itself.userPrivileges)-1;
- return 0;
+ return PyArg_Parse(v, "b", &self->ob_itself.userPrivileges)-1;
+ return 0;
}
static PyGetSetDef FSCatalogInfo_getsetlist[] = {
- {"nodeFlags", (getter)FSCatalogInfo_get_nodeFlags, (setter)FSCatalogInfo_set_nodeFlags, NULL},
- {"volume", (getter)FSCatalogInfo_get_volume, (setter)FSCatalogInfo_set_volume, NULL},
- {"parentDirID", (getter)FSCatalogInfo_get_parentDirID, (setter)FSCatalogInfo_set_parentDirID, NULL},
- {"nodeID", (getter)FSCatalogInfo_get_nodeID, (setter)FSCatalogInfo_set_nodeID, NULL},
- {"createDate", (getter)FSCatalogInfo_get_createDate, (setter)FSCatalogInfo_set_createDate, NULL},
- {"contentModDate", (getter)FSCatalogInfo_get_contentModDate, (setter)FSCatalogInfo_set_contentModDate, NULL},
- {"attributeModDate", (getter)FSCatalogInfo_get_attributeModDate, (setter)FSCatalogInfo_set_attributeModDate, NULL},
- {"accessDate", (getter)FSCatalogInfo_get_accessDate, (setter)FSCatalogInfo_set_accessDate, NULL},
- {"backupDate", (getter)FSCatalogInfo_get_backupDate, (setter)FSCatalogInfo_set_backupDate, NULL},
- {"permissions", (getter)FSCatalogInfo_get_permissions, (setter)FSCatalogInfo_set_permissions, NULL},
- {"valence", (getter)FSCatalogInfo_get_valence, (setter)FSCatalogInfo_set_valence, NULL},
- {"dataLogicalSize", (getter)FSCatalogInfo_get_dataLogicalSize, (setter)FSCatalogInfo_set_dataLogicalSize, NULL},
- {"dataPhysicalSize", (getter)FSCatalogInfo_get_dataPhysicalSize, (setter)FSCatalogInfo_set_dataPhysicalSize, NULL},
- {"rsrcLogicalSize", (getter)FSCatalogInfo_get_rsrcLogicalSize, (setter)FSCatalogInfo_set_rsrcLogicalSize, NULL},
- {"rsrcPhysicalSize", (getter)FSCatalogInfo_get_rsrcPhysicalSize, (setter)FSCatalogInfo_set_rsrcPhysicalSize, NULL},
- {"sharingFlags", (getter)FSCatalogInfo_get_sharingFlags, (setter)FSCatalogInfo_set_sharingFlags, NULL},
- {"userPrivileges", (getter)FSCatalogInfo_get_userPrivileges, (setter)FSCatalogInfo_set_userPrivileges, NULL},
- {NULL, NULL, NULL, NULL},
+ {"nodeFlags", (getter)FSCatalogInfo_get_nodeFlags, (setter)FSCatalogInfo_set_nodeFlags, NULL},
+ {"volume", (getter)FSCatalogInfo_get_volume, (setter)FSCatalogInfo_set_volume, NULL},
+ {"parentDirID", (getter)FSCatalogInfo_get_parentDirID, (setter)FSCatalogInfo_set_parentDirID, NULL},
+ {"nodeID", (getter)FSCatalogInfo_get_nodeID, (setter)FSCatalogInfo_set_nodeID, NULL},
+ {"createDate", (getter)FSCatalogInfo_get_createDate, (setter)FSCatalogInfo_set_createDate, NULL},
+ {"contentModDate", (getter)FSCatalogInfo_get_contentModDate, (setter)FSCatalogInfo_set_contentModDate, NULL},
+ {"attributeModDate", (getter)FSCatalogInfo_get_attributeModDate, (setter)FSCatalogInfo_set_attributeModDate, NULL},
+ {"accessDate", (getter)FSCatalogInfo_get_accessDate, (setter)FSCatalogInfo_set_accessDate, NULL},
+ {"backupDate", (getter)FSCatalogInfo_get_backupDate, (setter)FSCatalogInfo_set_backupDate, NULL},
+ {"permissions", (getter)FSCatalogInfo_get_permissions, (setter)FSCatalogInfo_set_permissions, NULL},
+ {"valence", (getter)FSCatalogInfo_get_valence, (setter)FSCatalogInfo_set_valence, NULL},
+ {"dataLogicalSize", (getter)FSCatalogInfo_get_dataLogicalSize, (setter)FSCatalogInfo_set_dataLogicalSize, NULL},
+ {"dataPhysicalSize", (getter)FSCatalogInfo_get_dataPhysicalSize, (setter)FSCatalogInfo_set_dataPhysicalSize, NULL},
+ {"rsrcLogicalSize", (getter)FSCatalogInfo_get_rsrcLogicalSize, (setter)FSCatalogInfo_set_rsrcLogicalSize, NULL},
+ {"rsrcPhysicalSize", (getter)FSCatalogInfo_get_rsrcPhysicalSize, (setter)FSCatalogInfo_set_rsrcPhysicalSize, NULL},
+ {"sharingFlags", (getter)FSCatalogInfo_get_sharingFlags, (setter)FSCatalogInfo_set_sharingFlags, NULL},
+ {"userPrivileges", (getter)FSCatalogInfo_get_userPrivileges, (setter)FSCatalogInfo_set_userPrivileges, NULL},
+ {NULL, NULL, NULL, NULL},
};
@@ -436,103 +436,103 @@ static PyGetSetDef FSCatalogInfo_getsetlist[] = {
#define FSCatalogInfo_hash NULL
static int FSCatalogInfo_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- static char *kw[] = {
- "nodeFlags",
- "volume",
- "parentDirID",
- "nodeID",
- "createDate",
- "contentModDate",
- "atributeModDate",
- "accessDate",
- "backupDate",
- "valence",
- "dataLogicalSize",
- "dataPhysicalSize",
- "rsrcLogicalSize",
- "rsrcPhysicalSize",
- "sharingFlags",
- "userPrivileges"
- , 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|HhllO&O&O&O&O&llllllb", kw, &((FSCatalogInfoObject *)_self)->ob_itself.nodeFlags,
- &((FSCatalogInfoObject *)_self)->ob_itself.volume,
- &((FSCatalogInfoObject *)_self)->ob_itself.parentDirID,
- &((FSCatalogInfoObject *)_self)->ob_itself.nodeID,
- UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.createDate,
- UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.contentModDate,
- UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.attributeModDate,
- UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.accessDate,
- UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.backupDate,
- &((FSCatalogInfoObject *)_self)->ob_itself.valence,
- &((FSCatalogInfoObject *)_self)->ob_itself.dataLogicalSize,
- &((FSCatalogInfoObject *)_self)->ob_itself.dataPhysicalSize,
- &((FSCatalogInfoObject *)_self)->ob_itself.rsrcLogicalSize,
- &((FSCatalogInfoObject *)_self)->ob_itself.rsrcPhysicalSize,
- &((FSCatalogInfoObject *)_self)->ob_itself.sharingFlags,
- &((FSCatalogInfoObject *)_self)->ob_itself.userPrivileges))
- {
- return -1;
- }
- return 0;
+ static char *kw[] = {
+ "nodeFlags",
+ "volume",
+ "parentDirID",
+ "nodeID",
+ "createDate",
+ "contentModDate",
+ "atributeModDate",
+ "accessDate",
+ "backupDate",
+ "valence",
+ "dataLogicalSize",
+ "dataPhysicalSize",
+ "rsrcLogicalSize",
+ "rsrcPhysicalSize",
+ "sharingFlags",
+ "userPrivileges"
+ , 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|HhllO&O&O&O&O&llllllb", kw, &((FSCatalogInfoObject *)_self)->ob_itself.nodeFlags,
+ &((FSCatalogInfoObject *)_self)->ob_itself.volume,
+ &((FSCatalogInfoObject *)_self)->ob_itself.parentDirID,
+ &((FSCatalogInfoObject *)_self)->ob_itself.nodeID,
+ UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.createDate,
+ UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.contentModDate,
+ UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.attributeModDate,
+ UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.accessDate,
+ UTCDateTime_Convert, &((FSCatalogInfoObject *)_self)->ob_itself.backupDate,
+ &((FSCatalogInfoObject *)_self)->ob_itself.valence,
+ &((FSCatalogInfoObject *)_self)->ob_itself.dataLogicalSize,
+ &((FSCatalogInfoObject *)_self)->ob_itself.dataPhysicalSize,
+ &((FSCatalogInfoObject *)_self)->ob_itself.rsrcLogicalSize,
+ &((FSCatalogInfoObject *)_self)->ob_itself.rsrcPhysicalSize,
+ &((FSCatalogInfoObject *)_self)->ob_itself.sharingFlags,
+ &((FSCatalogInfoObject *)_self)->ob_itself.userPrivileges))
+ {
+ return -1;
+ }
+ return 0;
}
#define FSCatalogInfo_tp_alloc PyType_GenericAlloc
static PyObject *FSCatalogInfo_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
+ PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- memset(&((FSCatalogInfoObject *)self)->ob_itself, 0, sizeof(FSCatalogInfo));
- return self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ memset(&((FSCatalogInfoObject *)self)->ob_itself, 0, sizeof(FSCatalogInfo));
+ return self;
}
#define FSCatalogInfo_tp_free PyObject_Del
static PyTypeObject FSCatalogInfo_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "Carbon.File.FSCatalogInfo", /*tp_name*/
- sizeof(FSCatalogInfoObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) FSCatalogInfo_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) FSCatalogInfo_compare, /*tp_compare*/
- (reprfunc) FSCatalogInfo_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) FSCatalogInfo_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*/
- FSCatalogInfo_methods, /* tp_methods */
- 0, /*tp_members*/
- FSCatalogInfo_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- FSCatalogInfo_tp_init, /* tp_init */
- FSCatalogInfo_tp_alloc, /* tp_alloc */
- FSCatalogInfo_tp_new, /* tp_new */
- FSCatalogInfo_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "Carbon.File.FSCatalogInfo", /*tp_name*/
+ sizeof(FSCatalogInfoObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) FSCatalogInfo_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) FSCatalogInfo_compare, /*tp_compare*/
+ (reprfunc) FSCatalogInfo_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) FSCatalogInfo_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*/
+ FSCatalogInfo_methods, /* tp_methods */
+ 0, /*tp_members*/
+ FSCatalogInfo_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ FSCatalogInfo_tp_init, /* tp_init */
+ FSCatalogInfo_tp_alloc, /* tp_alloc */
+ FSCatalogInfo_tp_new, /* tp_new */
+ FSCatalogInfo_tp_free, /* tp_free */
};
/* ----------------- End object type FSCatalogInfo ------------------ */
@@ -547,103 +547,103 @@ static PyTypeObject FInfo_Type;
#define FInfo_Check(x) ((x)->ob_type == &FInfo_Type || PyObject_TypeCheck((x), &FInfo_Type))
typedef struct FInfoObject {
- PyObject_HEAD
- FInfo ob_itself;
+ PyObject_HEAD
+ FInfo ob_itself;
} FInfoObject;
static PyObject *FInfo_New(FInfo *itself)
{
- FInfoObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(FInfoObject, &FInfo_Type);
- if (it == NULL) return NULL;
- it->ob_itself = *itself;
- return (PyObject *)it;
+ FInfoObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(FInfoObject, &FInfo_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = *itself;
+ return (PyObject *)it;
}
static int FInfo_Convert(PyObject *v, FInfo *p_itself)
{
- if (!FInfo_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "FInfo required");
- return 0;
- }
- *p_itself = ((FInfoObject *)v)->ob_itself;
- return 1;
+ if (!FInfo_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "FInfo required");
+ return 0;
+ }
+ *p_itself = ((FInfoObject *)v)->ob_itself;
+ return 1;
}
static void FInfo_dealloc(FInfoObject *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 PyMethodDef FInfo_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
static PyObject *FInfo_get_Type(FInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildOSType, self->ob_itself.fdType);
+ return Py_BuildValue("O&", PyMac_BuildOSType, self->ob_itself.fdType);
}
static int FInfo_set_Type(FInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", PyMac_GetOSType, &self->ob_itself.fdType)-1;
- return 0;
+ return PyArg_Parse(v, "O&", PyMac_GetOSType, &self->ob_itself.fdType)-1;
+ return 0;
}
static PyObject *FInfo_get_Creator(FInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildOSType, self->ob_itself.fdCreator);
+ return Py_BuildValue("O&", PyMac_BuildOSType, self->ob_itself.fdCreator);
}
static int FInfo_set_Creator(FInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", PyMac_GetOSType, &self->ob_itself.fdCreator)-1;
- return 0;
+ return PyArg_Parse(v, "O&", PyMac_GetOSType, &self->ob_itself.fdCreator)-1;
+ return 0;
}
static PyObject *FInfo_get_Flags(FInfoObject *self, void *closure)
{
- return Py_BuildValue("H", self->ob_itself.fdFlags);
+ return Py_BuildValue("H", self->ob_itself.fdFlags);
}
static int FInfo_set_Flags(FInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "H", &self->ob_itself.fdFlags)-1;
- return 0;
+ return PyArg_Parse(v, "H", &self->ob_itself.fdFlags)-1;
+ return 0;
}
static PyObject *FInfo_get_Location(FInfoObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildPoint, self->ob_itself.fdLocation);
+ return Py_BuildValue("O&", PyMac_BuildPoint, self->ob_itself.fdLocation);
}
static int FInfo_set_Location(FInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "O&", PyMac_GetPoint, &self->ob_itself.fdLocation)-1;
- return 0;
+ return PyArg_Parse(v, "O&", PyMac_GetPoint, &self->ob_itself.fdLocation)-1;
+ return 0;
}
static PyObject *FInfo_get_Fldr(FInfoObject *self, void *closure)
{
- return Py_BuildValue("h", self->ob_itself.fdFldr);
+ return Py_BuildValue("h", self->ob_itself.fdFldr);
}
static int FInfo_set_Fldr(FInfoObject *self, PyObject *v, void *closure)
{
- return PyArg_Parse(v, "h", &self->ob_itself.fdFldr)-1;
- return 0;
+ return PyArg_Parse(v, "h", &self->ob_itself.fdFldr)-1;
+ return 0;
}
static PyGetSetDef FInfo_getsetlist[] = {
- {"Type", (getter)FInfo_get_Type, (setter)FInfo_set_Type, "4-char file type"},
- {"Creator", (getter)FInfo_get_Creator, (setter)FInfo_set_Creator, "4-char file creator"},
- {"Flags", (getter)FInfo_get_Flags, (setter)FInfo_set_Flags, "Finder flag bits"},
- {"Location", (getter)FInfo_get_Location, (setter)FInfo_set_Location, "(x, y) location of the file's icon in its parent finder window"},
- {"Fldr", (getter)FInfo_get_Fldr, (setter)FInfo_set_Fldr, "Original folder, for 'put away'"},
- {NULL, NULL, NULL, NULL},
+ {"Type", (getter)FInfo_get_Type, (setter)FInfo_set_Type, "4-char file type"},
+ {"Creator", (getter)FInfo_get_Creator, (setter)FInfo_set_Creator, "4-char file creator"},
+ {"Flags", (getter)FInfo_get_Flags, (setter)FInfo_set_Flags, "Finder flag bits"},
+ {"Location", (getter)FInfo_get_Location, (setter)FInfo_set_Location, "(x, y) location of the file's icon in its parent finder window"},
+ {"Fldr", (getter)FInfo_get_Fldr, (setter)FInfo_set_Fldr, "Original folder, for 'put away'"},
+ {NULL, NULL, NULL, NULL},
};
@@ -654,73 +654,73 @@ static PyGetSetDef FInfo_getsetlist[] = {
#define FInfo_hash NULL
static int FInfo_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- FInfo *itself = NULL;
- static char *kw[] = {"itself", 0};
+ FInfo *itself = NULL;
+ static char *kw[] = {"itself", 0};
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "|O&", kw, FInfo_Convert, &itself))
- {
- if (itself) memcpy(&((FInfoObject *)_self)->ob_itself, itself, sizeof(FInfo));
- return 0;
- }
- return -1;
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "|O&", kw, FInfo_Convert, &itself))
+ {
+ if (itself) memcpy(&((FInfoObject *)_self)->ob_itself, itself, sizeof(FInfo));
+ return 0;
+ }
+ return -1;
}
#define FInfo_tp_alloc PyType_GenericAlloc
static PyObject *FInfo_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
+ PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- memset(&((FInfoObject *)self)->ob_itself, 0, sizeof(FInfo));
- return self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ memset(&((FInfoObject *)self)->ob_itself, 0, sizeof(FInfo));
+ return self;
}
#define FInfo_tp_free PyObject_Del
static PyTypeObject FInfo_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "Carbon.File.FInfo", /*tp_name*/
- sizeof(FInfoObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) FInfo_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) FInfo_compare, /*tp_compare*/
- (reprfunc) FInfo_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) FInfo_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*/
- FInfo_methods, /* tp_methods */
- 0, /*tp_members*/
- FInfo_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- FInfo_tp_init, /* tp_init */
- FInfo_tp_alloc, /* tp_alloc */
- FInfo_tp_new, /* tp_new */
- FInfo_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "Carbon.File.FInfo", /*tp_name*/
+ sizeof(FInfoObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) FInfo_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) FInfo_compare, /*tp_compare*/
+ (reprfunc) FInfo_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) FInfo_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*/
+ FInfo_methods, /* tp_methods */
+ 0, /*tp_members*/
+ FInfo_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ FInfo_tp_init, /* tp_init */
+ FInfo_tp_alloc, /* tp_alloc */
+ FInfo_tp_new, /* tp_new */
+ FInfo_tp_free, /* tp_free */
};
#endif /* !__LP64__ */
@@ -734,244 +734,244 @@ static PyTypeObject Alias_Type;
#define Alias_Check(x) ((x)->ob_type == &Alias_Type || PyObject_TypeCheck((x), &Alias_Type))
typedef struct AliasObject {
- PyObject_HEAD
- AliasHandle ob_itself;
- void (*ob_freeit)(AliasHandle ptr);
+ PyObject_HEAD
+ AliasHandle ob_itself;
+ void (*ob_freeit)(AliasHandle ptr);
} AliasObject;
static PyObject *Alias_New(AliasHandle itself)
{
- AliasObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(AliasObject, &Alias_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_freeit = NULL;
- return (PyObject *)it;
+ AliasObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(AliasObject, &Alias_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_freeit = NULL;
+ return (PyObject *)it;
}
static int Alias_Convert(PyObject *v, AliasHandle *p_itself)
{
- if (!Alias_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Alias required");
- return 0;
- }
- *p_itself = ((AliasObject *)v)->ob_itself;
- return 1;
+ if (!Alias_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Alias required");
+ return 0;
+ }
+ *p_itself = ((AliasObject *)v)->ob_itself;
+ return 1;
}
static void Alias_dealloc(AliasObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit(self->ob_itself);
- }
- self->ob_itself = NULL;
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit(self->ob_itself);
+ }
+ self->ob_itself = NULL;
+ self->ob_type->tp_free((PyObject *)self);
}
#ifndef __LP64__
static PyObject *Alias_ResolveAlias(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fromFile__buf__;
- FSSpec *fromFile = &fromFile__buf__;
- FSSpec target;
- Boolean wasChanged;
- if (!PyArg_ParseTuple(_args, "O&",
- myPyMac_GetOptFSSpecPtr, &fromFile))
- return NULL;
- _err = ResolveAlias(fromFile,
- _self->ob_itself,
- &target,
- &wasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- FSSpec_New, &target,
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fromFile__buf__;
+ FSSpec *fromFile = &fromFile__buf__;
+ FSSpec target;
+ Boolean wasChanged;
+ if (!PyArg_ParseTuple(_args, "O&",
+ myPyMac_GetOptFSSpecPtr, &fromFile))
+ return NULL;
+ _err = ResolveAlias(fromFile,
+ _self->ob_itself,
+ &target,
+ &wasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ FSSpec_New, &target,
+ wasChanged);
+ return _res;
}
static PyObject *Alias_GetAliasInfo(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AliasInfoType index;
- Str63 theString;
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- _err = GetAliasInfo(_self->ob_itself,
- index,
- theString);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, theString);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AliasInfoType index;
+ Str63 theString;
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ _err = GetAliasInfo(_self->ob_itself,
+ index,
+ theString);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, theString);
+ return _res;
}
static PyObject *Alias_ResolveAliasWithMountFlags(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fromFile__buf__;
- FSSpec *fromFile = &fromFile__buf__;
- FSSpec target;
- Boolean wasChanged;
- unsigned long mountFlags;
- if (!PyArg_ParseTuple(_args, "O&l",
- myPyMac_GetOptFSSpecPtr, &fromFile,
- &mountFlags))
- return NULL;
- _err = ResolveAliasWithMountFlags(fromFile,
- _self->ob_itself,
- &target,
- &wasChanged,
- mountFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- FSSpec_New, &target,
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fromFile__buf__;
+ FSSpec *fromFile = &fromFile__buf__;
+ FSSpec target;
+ Boolean wasChanged;
+ unsigned long mountFlags;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ myPyMac_GetOptFSSpecPtr, &fromFile,
+ &mountFlags))
+ return NULL;
+ _err = ResolveAliasWithMountFlags(fromFile,
+ _self->ob_itself,
+ &target,
+ &wasChanged,
+ mountFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ FSSpec_New, &target,
+ wasChanged);
+ return _res;
}
static PyObject *Alias_FollowFinderAlias(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fromFile__buf__;
- FSSpec *fromFile = &fromFile__buf__;
- Boolean logon;
- FSSpec target;
- Boolean wasChanged;
- if (!PyArg_ParseTuple(_args, "O&b",
- myPyMac_GetOptFSSpecPtr, &fromFile,
- &logon))
- return NULL;
- _err = FollowFinderAlias(fromFile,
- _self->ob_itself,
- logon,
- &target,
- &wasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- FSSpec_New, &target,
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fromFile__buf__;
+ FSSpec *fromFile = &fromFile__buf__;
+ Boolean logon;
+ FSSpec target;
+ Boolean wasChanged;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ myPyMac_GetOptFSSpecPtr, &fromFile,
+ &logon))
+ return NULL;
+ _err = FollowFinderAlias(fromFile,
+ _self->ob_itself,
+ logon,
+ &target,
+ &wasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ FSSpec_New, &target,
+ wasChanged);
+ return _res;
}
#endif /* !__LP64__ */
static PyObject *Alias_FSResolveAliasWithMountFlags(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef fromFile__buf__;
- FSRef *fromFile = &fromFile__buf__;
- FSRef target;
- Boolean wasChanged;
- unsigned long mountFlags;
- if (!PyArg_ParseTuple(_args, "O&l",
- myPyMac_GetOptFSRefPtr, &fromFile,
- &mountFlags))
- return NULL;
- _err = FSResolveAliasWithMountFlags(fromFile,
- _self->ob_itself,
- &target,
- &wasChanged,
- mountFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- FSRef_New, &target,
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef fromFile__buf__;
+ FSRef *fromFile = &fromFile__buf__;
+ FSRef target;
+ Boolean wasChanged;
+ unsigned long mountFlags;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ myPyMac_GetOptFSRefPtr, &fromFile,
+ &mountFlags))
+ return NULL;
+ _err = FSResolveAliasWithMountFlags(fromFile,
+ _self->ob_itself,
+ &target,
+ &wasChanged,
+ mountFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ FSRef_New, &target,
+ wasChanged);
+ return _res;
}
static PyObject *Alias_FSResolveAlias(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef fromFile__buf__;
- FSRef *fromFile = &fromFile__buf__;
- FSRef target;
- Boolean wasChanged;
- if (!PyArg_ParseTuple(_args, "O&",
- myPyMac_GetOptFSRefPtr, &fromFile))
- return NULL;
- _err = FSResolveAlias(fromFile,
- _self->ob_itself,
- &target,
- &wasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- FSRef_New, &target,
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef fromFile__buf__;
+ FSRef *fromFile = &fromFile__buf__;
+ FSRef target;
+ Boolean wasChanged;
+ if (!PyArg_ParseTuple(_args, "O&",
+ myPyMac_GetOptFSRefPtr, &fromFile))
+ return NULL;
+ _err = FSResolveAlias(fromFile,
+ _self->ob_itself,
+ &target,
+ &wasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ FSRef_New, &target,
+ wasChanged);
+ return _res;
}
static PyObject *Alias_FSFollowFinderAlias(AliasObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef fromFile;
- Boolean logon;
- FSRef target;
- Boolean wasChanged;
- if (!PyArg_ParseTuple(_args, "b",
- &logon))
- return NULL;
- _err = FSFollowFinderAlias(&fromFile,
- _self->ob_itself,
- logon,
- &target,
- &wasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&b",
- FSRef_New, &fromFile,
- FSRef_New, &target,
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef fromFile;
+ Boolean logon;
+ FSRef target;
+ Boolean wasChanged;
+ if (!PyArg_ParseTuple(_args, "b",
+ &logon))
+ return NULL;
+ _err = FSFollowFinderAlias(&fromFile,
+ _self->ob_itself,
+ logon,
+ &target,
+ &wasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&b",
+ FSRef_New, &fromFile,
+ FSRef_New, &target,
+ wasChanged);
+ return _res;
}
static PyMethodDef Alias_methods[] = {
#ifndef __LP64__
- {"ResolveAlias", (PyCFunction)Alias_ResolveAlias, 1,
- PyDoc_STR("(FSSpec fromFile) -> (FSSpec target, Boolean wasChanged)")},
- {"GetAliasInfo", (PyCFunction)Alias_GetAliasInfo, 1,
- PyDoc_STR("(AliasInfoType index) -> (Str63 theString)")},
- {"ResolveAliasWithMountFlags", (PyCFunction)Alias_ResolveAliasWithMountFlags, 1,
- PyDoc_STR("(FSSpec fromFile, unsigned long mountFlags) -> (FSSpec target, Boolean wasChanged)")},
- {"FollowFinderAlias", (PyCFunction)Alias_FollowFinderAlias, 1,
- PyDoc_STR("(FSSpec fromFile, Boolean logon) -> (FSSpec target, Boolean wasChanged)")},
+ {"ResolveAlias", (PyCFunction)Alias_ResolveAlias, 1,
+ PyDoc_STR("(FSSpec fromFile) -> (FSSpec target, Boolean wasChanged)")},
+ {"GetAliasInfo", (PyCFunction)Alias_GetAliasInfo, 1,
+ PyDoc_STR("(AliasInfoType index) -> (Str63 theString)")},
+ {"ResolveAliasWithMountFlags", (PyCFunction)Alias_ResolveAliasWithMountFlags, 1,
+ PyDoc_STR("(FSSpec fromFile, unsigned long mountFlags) -> (FSSpec target, Boolean wasChanged)")},
+ {"FollowFinderAlias", (PyCFunction)Alias_FollowFinderAlias, 1,
+ PyDoc_STR("(FSSpec fromFile, Boolean logon) -> (FSSpec target, Boolean wasChanged)")},
#endif /* !__LP64__ */
- {"FSResolveAliasWithMountFlags", (PyCFunction)Alias_FSResolveAliasWithMountFlags, 1,
- PyDoc_STR("(FSRef fromFile, unsigned long mountFlags) -> (FSRef target, Boolean wasChanged)")},
- {"FSResolveAlias", (PyCFunction)Alias_FSResolveAlias, 1,
- PyDoc_STR("(FSRef fromFile) -> (FSRef target, Boolean wasChanged)")},
- {"FSFollowFinderAlias", (PyCFunction)Alias_FSFollowFinderAlias, 1,
- PyDoc_STR("(Boolean logon) -> (FSRef fromFile, FSRef target, Boolean wasChanged)")},
- {NULL, NULL, 0}
+ {"FSResolveAliasWithMountFlags", (PyCFunction)Alias_FSResolveAliasWithMountFlags, 1,
+ PyDoc_STR("(FSRef fromFile, unsigned long mountFlags) -> (FSRef target, Boolean wasChanged)")},
+ {"FSResolveAlias", (PyCFunction)Alias_FSResolveAlias, 1,
+ PyDoc_STR("(FSRef fromFile) -> (FSRef target, Boolean wasChanged)")},
+ {"FSFollowFinderAlias", (PyCFunction)Alias_FSFollowFinderAlias, 1,
+ PyDoc_STR("(Boolean logon) -> (FSRef fromFile, FSRef target, Boolean wasChanged)")},
+ {NULL, NULL, 0}
};
static PyObject *Alias_get_data(AliasObject *self, void *closure)
{
- int size;
- PyObject *rv;
+ int size;
+ PyObject *rv;
+
+ size = GetHandleSize((Handle)self->ob_itself);
+ HLock((Handle)self->ob_itself);
+ rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size);
+ HUnlock((Handle)self->ob_itself);
+ return rv;
- size = GetHandleSize((Handle)self->ob_itself);
- HLock((Handle)self->ob_itself);
- rv = PyString_FromStringAndSize(*(Handle)self->ob_itself, size);
- HUnlock((Handle)self->ob_itself);
- return rv;
-
}
#define Alias_set_data NULL
static PyGetSetDef Alias_getsetlist[] = {
- {"data", (getter)Alias_get_data, (setter)Alias_set_data, "Raw data of the alias object"},
- {NULL, NULL, NULL, NULL},
+ {"data", (getter)Alias_get_data, (setter)Alias_set_data, "Raw data of the alias object"},
+ {NULL, NULL, NULL, NULL},
};
@@ -982,97 +982,97 @@ static PyGetSetDef Alias_getsetlist[] = {
#define Alias_hash NULL
static int Alias_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- AliasHandle itself = NULL;
- char *rawdata = NULL;
- int rawdatalen = 0;
- Handle h;
- static char *kw[] = {"itself", "rawdata", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|O&s#", kw, Alias_Convert, &itself, &rawdata, &rawdatalen))
- return -1;
- if (itself && rawdata)
- {
- PyErr_SetString(PyExc_TypeError, "Only one of itself or rawdata may be specified");
- return -1;
- }
- if (!itself && !rawdata)
- {
- PyErr_SetString(PyExc_TypeError, "One of itself or rawdata must be specified");
- return -1;
- }
- if (rawdata)
- {
- if ((h = NewHandle(rawdatalen)) == NULL)
- {
- PyErr_NoMemory();
- return -1;
- }
- HLock(h);
- memcpy((char *)*h, rawdata, rawdatalen);
- HUnlock(h);
- ((AliasObject *)_self)->ob_itself = (AliasHandle)h;
- return 0;
- }
- ((AliasObject *)_self)->ob_itself = itself;
- return 0;
+ AliasHandle itself = NULL;
+ char *rawdata = NULL;
+ int rawdatalen = 0;
+ Handle h;
+ static char *kw[] = {"itself", "rawdata", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|O&s#", kw, Alias_Convert, &itself, &rawdata, &rawdatalen))
+ return -1;
+ if (itself && rawdata)
+ {
+ PyErr_SetString(PyExc_TypeError, "Only one of itself or rawdata may be specified");
+ return -1;
+ }
+ if (!itself && !rawdata)
+ {
+ PyErr_SetString(PyExc_TypeError, "One of itself or rawdata must be specified");
+ return -1;
+ }
+ if (rawdata)
+ {
+ if ((h = NewHandle(rawdatalen)) == NULL)
+ {
+ PyErr_NoMemory();
+ return -1;
+ }
+ HLock(h);
+ memcpy((char *)*h, rawdata, rawdatalen);
+ HUnlock(h);
+ ((AliasObject *)_self)->ob_itself = (AliasHandle)h;
+ return 0;
+ }
+ ((AliasObject *)_self)->ob_itself = itself;
+ return 0;
}
#define Alias_tp_alloc PyType_GenericAlloc
static PyObject *Alias_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
+ PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((AliasObject *)self)->ob_itself = NULL;
- return self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((AliasObject *)self)->ob_itself = NULL;
+ return self;
}
#define Alias_tp_free PyObject_Del
static PyTypeObject Alias_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "Carbon.File.Alias", /*tp_name*/
- sizeof(AliasObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) Alias_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) Alias_compare, /*tp_compare*/
- (reprfunc) Alias_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) Alias_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*/
- Alias_methods, /* tp_methods */
- 0, /*tp_members*/
- Alias_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- Alias_tp_init, /* tp_init */
- Alias_tp_alloc, /* tp_alloc */
- Alias_tp_new, /* tp_new */
- Alias_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "Carbon.File.Alias", /*tp_name*/
+ sizeof(AliasObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) Alias_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) Alias_compare, /*tp_compare*/
+ (reprfunc) Alias_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) Alias_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*/
+ Alias_methods, /* tp_methods */
+ 0, /*tp_members*/
+ Alias_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ Alias_tp_init, /* tp_init */
+ Alias_tp_alloc, /* tp_alloc */
+ Alias_tp_new, /* tp_new */
+ Alias_tp_free, /* tp_free */
};
/* --------------------- End object type Alias ---------------------- */
@@ -1086,347 +1086,347 @@ static PyTypeObject FSSpec_Type;
#define FSSpec_Check(x) ((x)->ob_type == &FSSpec_Type || PyObject_TypeCheck((x), &FSSpec_Type))
typedef struct FSSpecObject {
- PyObject_HEAD
- FSSpec ob_itself;
+ PyObject_HEAD
+ FSSpec ob_itself;
} FSSpecObject;
static PyObject *FSSpec_New(FSSpec *itself)
{
- FSSpecObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(FSSpecObject, &FSSpec_Type);
- if (it == NULL) return NULL;
- it->ob_itself = *itself;
- return (PyObject *)it;
+ FSSpecObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(FSSpecObject, &FSSpec_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = *itself;
+ return (PyObject *)it;
}
static void FSSpec_dealloc(FSSpecObject *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 *FSSpec_FSpOpenDF(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt8 permission;
- short refNum;
- if (!PyArg_ParseTuple(_args, "b",
- &permission))
- return NULL;
- _err = FSpOpenDF(&_self->ob_itself,
- permission,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt8 permission;
+ short refNum;
+ if (!PyArg_ParseTuple(_args, "b",
+ &permission))
+ return NULL;
+ _err = FSpOpenDF(&_self->ob_itself,
+ permission,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *FSSpec_FSpOpenRF(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt8 permission;
- short refNum;
- if (!PyArg_ParseTuple(_args, "b",
- &permission))
- return NULL;
- _err = FSpOpenRF(&_self->ob_itself,
- permission,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt8 permission;
+ short refNum;
+ if (!PyArg_ParseTuple(_args, "b",
+ &permission))
+ return NULL;
+ _err = FSpOpenRF(&_self->ob_itself,
+ permission,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *FSSpec_FSpCreate(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType creator;
- OSType fileType;
- ScriptCode scriptTag;
- if (!PyArg_ParseTuple(_args, "O&O&h",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &fileType,
- &scriptTag))
- return NULL;
- _err = FSpCreate(&_self->ob_itself,
- creator,
- fileType,
- scriptTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType creator;
+ OSType fileType;
+ ScriptCode scriptTag;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &fileType,
+ &scriptTag))
+ return NULL;
+ _err = FSpCreate(&_self->ob_itself,
+ creator,
+ fileType,
+ scriptTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpDirCreate(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ScriptCode scriptTag;
- long createdDirID;
- if (!PyArg_ParseTuple(_args, "h",
- &scriptTag))
- return NULL;
- _err = FSpDirCreate(&_self->ob_itself,
- scriptTag,
- &createdDirID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- createdDirID);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ScriptCode scriptTag;
+ long createdDirID;
+ if (!PyArg_ParseTuple(_args, "h",
+ &scriptTag))
+ return NULL;
+ _err = FSpDirCreate(&_self->ob_itself,
+ scriptTag,
+ &createdDirID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ createdDirID);
+ return _res;
}
static PyObject *FSSpec_FSpDelete(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSpDelete(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSpDelete(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpGetFInfo(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FInfo fndrInfo;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSpGetFInfo(&_self->ob_itself,
- &fndrInfo);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FInfo_New, &fndrInfo);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FInfo fndrInfo;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSpGetFInfo(&_self->ob_itself,
+ &fndrInfo);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FInfo_New, &fndrInfo);
+ return _res;
}
static PyObject *FSSpec_FSpSetFInfo(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FInfo fndrInfo;
- if (!PyArg_ParseTuple(_args, "O&",
- FInfo_Convert, &fndrInfo))
- return NULL;
- _err = FSpSetFInfo(&_self->ob_itself,
- &fndrInfo);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FInfo fndrInfo;
+ if (!PyArg_ParseTuple(_args, "O&",
+ FInfo_Convert, &fndrInfo))
+ return NULL;
+ _err = FSpSetFInfo(&_self->ob_itself,
+ &fndrInfo);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpSetFLock(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSpSetFLock(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSpSetFLock(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpRstFLock(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSpRstFLock(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSpRstFLock(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpRename(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str255 newName;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, newName))
- return NULL;
- _err = FSpRename(&_self->ob_itself,
- newName);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str255 newName;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, newName))
+ return NULL;
+ _err = FSpRename(&_self->ob_itself,
+ newName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpCatMove(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec dest;
- if (!PyArg_ParseTuple(_args, "O&",
- FSSpec_Convert, &dest))
- return NULL;
- _err = FSpCatMove(&_self->ob_itself,
- &dest);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec dest;
+ if (!PyArg_ParseTuple(_args, "O&",
+ FSSpec_Convert, &dest))
+ return NULL;
+ _err = FSpCatMove(&_self->ob_itself,
+ &dest);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpExchangeFiles(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec dest;
- if (!PyArg_ParseTuple(_args, "O&",
- FSSpec_Convert, &dest))
- return NULL;
- _err = FSpExchangeFiles(&_self->ob_itself,
- &dest);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec dest;
+ if (!PyArg_ParseTuple(_args, "O&",
+ FSSpec_Convert, &dest))
+ return NULL;
+ _err = FSpExchangeFiles(&_self->ob_itself,
+ &dest);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSSpec_FSpMakeFSRef(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef newRef;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSpMakeFSRef(&_self->ob_itself,
- &newRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FSRef_New, &newRef);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef newRef;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSpMakeFSRef(&_self->ob_itself,
+ &newRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FSRef_New, &newRef);
+ return _res;
}
static PyObject *FSSpec_NewAliasMinimal(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AliasHandle alias;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = NewAliasMinimal(&_self->ob_itself,
- &alias);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- Alias_New, alias);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AliasHandle alias;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = NewAliasMinimal(&_self->ob_itself,
+ &alias);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ Alias_New, alias);
+ return _res;
}
static PyObject *FSSpec_IsAliasFile(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Boolean aliasFileFlag;
- Boolean folderFlag;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = IsAliasFile(&_self->ob_itself,
- &aliasFileFlag,
- &folderFlag);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bb",
- aliasFileFlag,
- folderFlag);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Boolean aliasFileFlag;
+ Boolean folderFlag;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = IsAliasFile(&_self->ob_itself,
+ &aliasFileFlag,
+ &folderFlag);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bb",
+ aliasFileFlag,
+ folderFlag);
+ return _res;
}
static PyObject *FSSpec_as_pathname(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- char strbuf[1024];
- OSErr err;
+ char strbuf[1024];
+ OSErr err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- err = _PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf));
- if ( err ) {
- PyMac_Error(err);
- return NULL;
- }
- _res = PyString_FromString(strbuf);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ err = _PyMac_GetFullPathname(&_self->ob_itself, strbuf, sizeof(strbuf));
+ if ( err ) {
+ PyMac_Error(err);
+ return NULL;
+ }
+ _res = PyString_FromString(strbuf);
+ return _res;
}
static PyObject *FSSpec_as_tuple(FSSpecObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _res = Py_BuildValue("(iis#)", _self->ob_itself.vRefNum, _self->ob_itself.parID,
- &_self->ob_itself.name[1], _self->ob_itself.name[0]);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _res = Py_BuildValue("(iis#)", _self->ob_itself.vRefNum, _self->ob_itself.parID,
+ &_self->ob_itself.name[1], _self->ob_itself.name[0]);
+ return _res;
}
static PyMethodDef FSSpec_methods[] = {
- {"FSpOpenDF", (PyCFunction)FSSpec_FSpOpenDF, 1,
- PyDoc_STR("(SInt8 permission) -> (short refNum)")},
- {"FSpOpenRF", (PyCFunction)FSSpec_FSpOpenRF, 1,
- PyDoc_STR("(SInt8 permission) -> (short refNum)")},
- {"FSpCreate", (PyCFunction)FSSpec_FSpCreate, 1,
- PyDoc_STR("(OSType creator, OSType fileType, ScriptCode scriptTag) -> None")},
- {"FSpDirCreate", (PyCFunction)FSSpec_FSpDirCreate, 1,
- PyDoc_STR("(ScriptCode scriptTag) -> (long createdDirID)")},
- {"FSpDelete", (PyCFunction)FSSpec_FSpDelete, 1,
- PyDoc_STR("() -> None")},
- {"FSpGetFInfo", (PyCFunction)FSSpec_FSpGetFInfo, 1,
- PyDoc_STR("() -> (FInfo fndrInfo)")},
- {"FSpSetFInfo", (PyCFunction)FSSpec_FSpSetFInfo, 1,
- PyDoc_STR("(FInfo fndrInfo) -> None")},
- {"FSpSetFLock", (PyCFunction)FSSpec_FSpSetFLock, 1,
- PyDoc_STR("() -> None")},
- {"FSpRstFLock", (PyCFunction)FSSpec_FSpRstFLock, 1,
- PyDoc_STR("() -> None")},
- {"FSpRename", (PyCFunction)FSSpec_FSpRename, 1,
- PyDoc_STR("(Str255 newName) -> None")},
- {"FSpCatMove", (PyCFunction)FSSpec_FSpCatMove, 1,
- PyDoc_STR("(FSSpec dest) -> None")},
- {"FSpExchangeFiles", (PyCFunction)FSSpec_FSpExchangeFiles, 1,
- PyDoc_STR("(FSSpec dest) -> None")},
- {"FSpMakeFSRef", (PyCFunction)FSSpec_FSpMakeFSRef, 1,
- PyDoc_STR("() -> (FSRef newRef)")},
- {"NewAliasMinimal", (PyCFunction)FSSpec_NewAliasMinimal, 1,
- PyDoc_STR("() -> (AliasHandle alias)")},
- {"IsAliasFile", (PyCFunction)FSSpec_IsAliasFile, 1,
- PyDoc_STR("() -> (Boolean aliasFileFlag, Boolean folderFlag)")},
- {"as_pathname", (PyCFunction)FSSpec_as_pathname, 1,
- PyDoc_STR("() -> string")},
- {"as_tuple", (PyCFunction)FSSpec_as_tuple, 1,
- PyDoc_STR("() -> (vRefNum, dirID, name)")},
- {NULL, NULL, 0}
+ {"FSpOpenDF", (PyCFunction)FSSpec_FSpOpenDF, 1,
+ PyDoc_STR("(SInt8 permission) -> (short refNum)")},
+ {"FSpOpenRF", (PyCFunction)FSSpec_FSpOpenRF, 1,
+ PyDoc_STR("(SInt8 permission) -> (short refNum)")},
+ {"FSpCreate", (PyCFunction)FSSpec_FSpCreate, 1,
+ PyDoc_STR("(OSType creator, OSType fileType, ScriptCode scriptTag) -> None")},
+ {"FSpDirCreate", (PyCFunction)FSSpec_FSpDirCreate, 1,
+ PyDoc_STR("(ScriptCode scriptTag) -> (long createdDirID)")},
+ {"FSpDelete", (PyCFunction)FSSpec_FSpDelete, 1,
+ PyDoc_STR("() -> None")},
+ {"FSpGetFInfo", (PyCFunction)FSSpec_FSpGetFInfo, 1,
+ PyDoc_STR("() -> (FInfo fndrInfo)")},
+ {"FSpSetFInfo", (PyCFunction)FSSpec_FSpSetFInfo, 1,
+ PyDoc_STR("(FInfo fndrInfo) -> None")},
+ {"FSpSetFLock", (PyCFunction)FSSpec_FSpSetFLock, 1,
+ PyDoc_STR("() -> None")},
+ {"FSpRstFLock", (PyCFunction)FSSpec_FSpRstFLock, 1,
+ PyDoc_STR("() -> None")},
+ {"FSpRename", (PyCFunction)FSSpec_FSpRename, 1,
+ PyDoc_STR("(Str255 newName) -> None")},
+ {"FSpCatMove", (PyCFunction)FSSpec_FSpCatMove, 1,
+ PyDoc_STR("(FSSpec dest) -> None")},
+ {"FSpExchangeFiles", (PyCFunction)FSSpec_FSpExchangeFiles, 1,
+ PyDoc_STR("(FSSpec dest) -> None")},
+ {"FSpMakeFSRef", (PyCFunction)FSSpec_FSpMakeFSRef, 1,
+ PyDoc_STR("() -> (FSRef newRef)")},
+ {"NewAliasMinimal", (PyCFunction)FSSpec_NewAliasMinimal, 1,
+ PyDoc_STR("() -> (AliasHandle alias)")},
+ {"IsAliasFile", (PyCFunction)FSSpec_IsAliasFile, 1,
+ PyDoc_STR("() -> (Boolean aliasFileFlag, Boolean folderFlag)")},
+ {"as_pathname", (PyCFunction)FSSpec_as_pathname, 1,
+ PyDoc_STR("() -> string")},
+ {"as_tuple", (PyCFunction)FSSpec_as_tuple, 1,
+ PyDoc_STR("() -> (vRefNum, dirID, name)")},
+ {NULL, NULL, 0}
};
static PyObject *FSSpec_get_data(FSSpecObject *self, void *closure)
{
- return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
+ return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
}
#define FSSpec_set_data NULL
static PyGetSetDef FSSpec_getsetlist[] = {
- {"data", (getter)FSSpec_get_data, (setter)FSSpec_set_data, "Raw data of the FSSpec object"},
- {NULL, NULL, NULL, NULL},
+ {"data", (getter)FSSpec_get_data, (setter)FSSpec_set_data, "Raw data of the FSSpec object"},
+ {NULL, NULL, NULL, NULL},
};
@@ -1434,105 +1434,105 @@ static PyGetSetDef FSSpec_getsetlist[] = {
static PyObject * FSSpec_repr(FSSpecObject *self)
{
- char buf[512];
- PyOS_snprintf(buf, sizeof(buf), "%s((%d, %ld, '%.*s'))",
- self->ob_type->tp_name,
- self->ob_itself.vRefNum,
- self->ob_itself.parID,
- self->ob_itself.name[0], self->ob_itself.name+1);
- return PyString_FromString(buf);
+ char buf[512];
+ PyOS_snprintf(buf, sizeof(buf), "%s((%d, %ld, '%.*s'))",
+ self->ob_type->tp_name,
+ self->ob_itself.vRefNum,
+ self->ob_itself.parID,
+ self->ob_itself.name[0], self->ob_itself.name+1);
+ return PyString_FromString(buf);
}
#define FSSpec_hash NULL
static int FSSpec_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- PyObject *v = NULL;
- char *rawdata = NULL;
- int rawdatalen = 0;
- static char *kw[] = {"itself", "rawdata", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|Os#", kw, &v, &rawdata, &rawdatalen))
- return -1;
- if (v && rawdata)
- {
- PyErr_SetString(PyExc_TypeError, "Only one of itself or rawdata may be specified");
- return -1;
- }
- if (!v && !rawdata)
- {
- PyErr_SetString(PyExc_TypeError, "One of itself or rawdata must be specified");
- return -1;
- }
- if (rawdata)
- {
- if (rawdatalen != sizeof(FSSpec))
- {
- PyErr_SetString(PyExc_TypeError, "FSSpec rawdata incorrect size");
- return -1;
- }
- memcpy(&((FSSpecObject *)_self)->ob_itself, rawdata, rawdatalen);
- return 0;
- }
- if (PyMac_GetFSSpec(v, &((FSSpecObject *)_self)->ob_itself)) return 0;
- return -1;
+ PyObject *v = NULL;
+ char *rawdata = NULL;
+ int rawdatalen = 0;
+ static char *kw[] = {"itself", "rawdata", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|Os#", kw, &v, &rawdata, &rawdatalen))
+ return -1;
+ if (v && rawdata)
+ {
+ PyErr_SetString(PyExc_TypeError, "Only one of itself or rawdata may be specified");
+ return -1;
+ }
+ if (!v && !rawdata)
+ {
+ PyErr_SetString(PyExc_TypeError, "One of itself or rawdata must be specified");
+ return -1;
+ }
+ if (rawdata)
+ {
+ if (rawdatalen != sizeof(FSSpec))
+ {
+ PyErr_SetString(PyExc_TypeError, "FSSpec rawdata incorrect size");
+ return -1;
+ }
+ memcpy(&((FSSpecObject *)_self)->ob_itself, rawdata, rawdatalen);
+ return 0;
+ }
+ if (PyMac_GetFSSpec(v, &((FSSpecObject *)_self)->ob_itself)) return 0;
+ return -1;
}
#define FSSpec_tp_alloc PyType_GenericAlloc
static PyObject *FSSpec_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
+ PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- memset(&((FSSpecObject *)self)->ob_itself, 0, sizeof(FSSpec));
- return self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ memset(&((FSSpecObject *)self)->ob_itself, 0, sizeof(FSSpec));
+ return self;
}
#define FSSpec_tp_free PyObject_Del
static PyTypeObject FSSpec_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "Carbon.File.FSSpec", /*tp_name*/
- sizeof(FSSpecObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) FSSpec_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) FSSpec_compare, /*tp_compare*/
- (reprfunc) FSSpec_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) FSSpec_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*/
- FSSpec_methods, /* tp_methods */
- 0, /*tp_members*/
- FSSpec_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- FSSpec_tp_init, /* tp_init */
- FSSpec_tp_alloc, /* tp_alloc */
- FSSpec_tp_new, /* tp_new */
- FSSpec_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "Carbon.File.FSSpec", /*tp_name*/
+ sizeof(FSSpecObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) FSSpec_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) FSSpec_compare, /*tp_compare*/
+ (reprfunc) FSSpec_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) FSSpec_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*/
+ FSSpec_methods, /* tp_methods */
+ 0, /*tp_members*/
+ FSSpec_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ FSSpec_tp_init, /* tp_init */
+ FSSpec_tp_alloc, /* tp_alloc */
+ FSSpec_tp_new, /* tp_new */
+ FSSpec_tp_free, /* tp_free */
};
#endif /* !__LP64__ */
@@ -1546,483 +1546,483 @@ static PyTypeObject FSRef_Type;
#define FSRef_Check(x) ((x)->ob_type == &FSRef_Type || PyObject_TypeCheck((x), &FSRef_Type))
typedef struct FSRefObject {
- PyObject_HEAD
- FSRef ob_itself;
+ PyObject_HEAD
+ FSRef ob_itself;
} FSRefObject;
static PyObject *FSRef_New(FSRef *itself)
{
- FSRefObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(FSRefObject, &FSRef_Type);
- if (it == NULL) return NULL;
- it->ob_itself = *itself;
- return (PyObject *)it;
+ FSRefObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(FSRefObject, &FSRef_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = *itself;
+ return (PyObject *)it;
}
static void FSRef_dealloc(FSRefObject *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 *FSRef_FSMakeFSRefUnicode(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *nameLength__in__;
- UniCharCount nameLength__len__;
- int nameLength__in_len__;
- TextEncoding textEncodingHint;
- FSRef newRef;
- if (!PyArg_ParseTuple(_args, "u#l",
- &nameLength__in__, &nameLength__in_len__,
- &textEncodingHint))
- return NULL;
- nameLength__len__ = nameLength__in_len__;
- _err = FSMakeFSRefUnicode(&_self->ob_itself,
- nameLength__len__, nameLength__in__,
- textEncodingHint,
- &newRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FSRef_New, &newRef);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *nameLength__in__;
+ UniCharCount nameLength__len__;
+ int nameLength__in_len__;
+ TextEncoding textEncodingHint;
+ FSRef newRef;
+ if (!PyArg_ParseTuple(_args, "u#l",
+ &nameLength__in__, &nameLength__in_len__,
+ &textEncodingHint))
+ return NULL;
+ nameLength__len__ = nameLength__in_len__;
+ _err = FSMakeFSRefUnicode(&_self->ob_itself,
+ nameLength__len__, nameLength__in__,
+ textEncodingHint,
+ &newRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FSRef_New, &newRef);
+ return _res;
}
static PyObject *FSRef_FSCompareFSRefs(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef ref2;
- if (!PyArg_ParseTuple(_args, "O&",
- FSRef_Convert, &ref2))
- return NULL;
- _err = FSCompareFSRefs(&_self->ob_itself,
- &ref2);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef ref2;
+ if (!PyArg_ParseTuple(_args, "O&",
+ FSRef_Convert, &ref2))
+ return NULL;
+ _err = FSCompareFSRefs(&_self->ob_itself,
+ &ref2);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSCreateFileUnicode(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *nameLength__in__;
- UniCharCount nameLength__len__;
- int nameLength__in_len__;
- FSCatalogInfoBitmap whichInfo;
- FSCatalogInfo catalogInfo;
- FSRef newRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *nameLength__in__;
+ UniCharCount nameLength__len__;
+ int nameLength__in_len__;
+ FSCatalogInfoBitmap whichInfo;
+ FSCatalogInfo catalogInfo;
+ FSRef newRef;
#ifndef __LP64__
- FSSpec newSpec;
+ FSSpec newSpec;
#endif
- if (!PyArg_ParseTuple(_args, "u#lO&",
- &nameLength__in__, &nameLength__in_len__,
- &whichInfo,
- FSCatalogInfo_Convert, &catalogInfo))
- return NULL;
- nameLength__len__ = nameLength__in_len__;
- _err = FSCreateFileUnicode(&_self->ob_itself,
- nameLength__len__, nameLength__in__,
- whichInfo,
- &catalogInfo,
- &newRef,
+ if (!PyArg_ParseTuple(_args, "u#lO&",
+ &nameLength__in__, &nameLength__in_len__,
+ &whichInfo,
+ FSCatalogInfo_Convert, &catalogInfo))
+ return NULL;
+ nameLength__len__ = nameLength__in_len__;
+ _err = FSCreateFileUnicode(&_self->ob_itself,
+ nameLength__len__, nameLength__in__,
+ whichInfo,
+ &catalogInfo,
+ &newRef,
#ifndef __LP64__
- &newSpec
-#else /* __LP64__ */
- NULL
+ &newSpec
+#else /* __LP64__ */
+ NULL
#endif /* __LP64__*/
- );
- if (_err != noErr) return PyMac_Error(_err);
+ );
+ if (_err != noErr) return PyMac_Error(_err);
#ifndef __LP64__
- _res = Py_BuildValue("O&O&",
- FSRef_New, &newRef,
- FSSpec_New, &newSpec);
+ _res = Py_BuildValue("O&O&",
+ FSRef_New, &newRef,
+ FSSpec_New, &newSpec);
#else /* __LP64__ */
- _res = Py_BuildValue("O&O", FSRef_New, &newRef, Py_None);
+ _res = Py_BuildValue("O&O", FSRef_New, &newRef, Py_None);
#endif /* __LP64__ */
- return _res;
+ return _res;
}
static PyObject *FSRef_FSCreateDirectoryUnicode(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *nameLength__in__;
- UniCharCount nameLength__len__;
- int nameLength__in_len__;
- FSCatalogInfoBitmap whichInfo;
- FSCatalogInfo catalogInfo;
- FSRef newRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *nameLength__in__;
+ UniCharCount nameLength__len__;
+ int nameLength__in_len__;
+ FSCatalogInfoBitmap whichInfo;
+ FSCatalogInfo catalogInfo;
+ FSRef newRef;
#ifndef __LP64__
- FSSpec newSpec;
+ FSSpec newSpec;
#endif /* !__LP64__ */
- UInt32 newDirID;
- if (!PyArg_ParseTuple(_args, "u#lO&",
- &nameLength__in__, &nameLength__in_len__,
- &whichInfo,
- FSCatalogInfo_Convert, &catalogInfo))
- return NULL;
- nameLength__len__ = nameLength__in_len__;
- _err = FSCreateDirectoryUnicode(&_self->ob_itself,
- nameLength__len__, nameLength__in__,
- whichInfo,
- &catalogInfo,
- &newRef,
+ UInt32 newDirID;
+ if (!PyArg_ParseTuple(_args, "u#lO&",
+ &nameLength__in__, &nameLength__in_len__,
+ &whichInfo,
+ FSCatalogInfo_Convert, &catalogInfo))
+ return NULL;
+ nameLength__len__ = nameLength__in_len__;
+ _err = FSCreateDirectoryUnicode(&_self->ob_itself,
+ nameLength__len__, nameLength__in__,
+ whichInfo,
+ &catalogInfo,
+ &newRef,
#ifndef __LP64__
- &newSpec,
+ &newSpec,
#else /* !__LP64__ */
- NULL,
+ NULL,
#endif /* !__LP64__ */
- &newDirID);
- if (_err != noErr) return PyMac_Error(_err);
+ &newDirID);
+ if (_err != noErr) return PyMac_Error(_err);
#ifndef __LP64__
- _res = Py_BuildValue("O&O&l",
- FSRef_New, &newRef,
- FSSpec_New, &newSpec,
- newDirID);
-#else /* __LP64__ */
- _res = Py_BuildValue("O&Ol",
- FSRef_New, &newRef,
- Py_None,
- newDirID);
+ _res = Py_BuildValue("O&O&l",
+ FSRef_New, &newRef,
+ FSSpec_New, &newSpec,
+ newDirID);
+#else /* __LP64__ */
+ _res = Py_BuildValue("O&Ol",
+ FSRef_New, &newRef,
+ Py_None,
+ newDirID);
#endif /* __LP64__ */
- return _res;
+ return _res;
}
static PyObject *FSRef_FSDeleteObject(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSDeleteObject(&_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSDeleteObject(&_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSMoveObject(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef destDirectory;
- FSRef newRef;
- if (!PyArg_ParseTuple(_args, "O&",
- FSRef_Convert, &destDirectory))
- return NULL;
- _err = FSMoveObject(&_self->ob_itself,
- &destDirectory,
- &newRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FSRef_New, &newRef);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef destDirectory;
+ FSRef newRef;
+ if (!PyArg_ParseTuple(_args, "O&",
+ FSRef_Convert, &destDirectory))
+ return NULL;
+ _err = FSMoveObject(&_self->ob_itself,
+ &destDirectory,
+ &newRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FSRef_New, &newRef);
+ return _res;
}
static PyObject *FSRef_FSExchangeObjects(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef destRef;
- if (!PyArg_ParseTuple(_args, "O&",
- FSRef_Convert, &destRef))
- return NULL;
- _err = FSExchangeObjects(&_self->ob_itself,
- &destRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef destRef;
+ if (!PyArg_ParseTuple(_args, "O&",
+ FSRef_Convert, &destRef))
+ return NULL;
+ _err = FSExchangeObjects(&_self->ob_itself,
+ &destRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSRenameUnicode(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *nameLength__in__;
- UniCharCount nameLength__len__;
- int nameLength__in_len__;
- TextEncoding textEncodingHint;
- FSRef newRef;
- if (!PyArg_ParseTuple(_args, "u#l",
- &nameLength__in__, &nameLength__in_len__,
- &textEncodingHint))
- return NULL;
- nameLength__len__ = nameLength__in_len__;
- _err = FSRenameUnicode(&_self->ob_itself,
- nameLength__len__, nameLength__in__,
- textEncodingHint,
- &newRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FSRef_New, &newRef);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *nameLength__in__;
+ UniCharCount nameLength__len__;
+ int nameLength__in_len__;
+ TextEncoding textEncodingHint;
+ FSRef newRef;
+ if (!PyArg_ParseTuple(_args, "u#l",
+ &nameLength__in__, &nameLength__in_len__,
+ &textEncodingHint))
+ return NULL;
+ nameLength__len__ = nameLength__in_len__;
+ _err = FSRenameUnicode(&_self->ob_itself,
+ nameLength__len__, nameLength__in__,
+ textEncodingHint,
+ &newRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FSRef_New, &newRef);
+ return _res;
}
static PyObject *FSRef_FSGetCatalogInfo(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSCatalogInfoBitmap whichInfo;
- FSCatalogInfo catalogInfo;
- HFSUniStr255 outName;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSCatalogInfoBitmap whichInfo;
+ FSCatalogInfo catalogInfo;
+ HFSUniStr255 outName;
#ifndef __LP64__
- FSSpec fsSpec;
+ FSSpec fsSpec;
#endif /* !__LP64__ */
- FSRef parentRef;
- if (!PyArg_ParseTuple(_args, "l",
- &whichInfo))
- return NULL;
- _err = FSGetCatalogInfo(&_self->ob_itself,
- whichInfo,
- &catalogInfo,
- &outName,
+ FSRef parentRef;
+ if (!PyArg_ParseTuple(_args, "l",
+ &whichInfo))
+ return NULL;
+ _err = FSGetCatalogInfo(&_self->ob_itself,
+ whichInfo,
+ &catalogInfo,
+ &outName,
#ifndef __LP64__
- &fsSpec,
-#else /* __LP64__ */
- NULL,
+ &fsSpec,
+#else /* __LP64__ */
+ NULL,
#endif /* __LP64__ */
- &parentRef);
- if (_err != noErr) return PyMac_Error(_err);
+ &parentRef);
+ if (_err != noErr) return PyMac_Error(_err);
#ifndef __LP64__
- _res = Py_BuildValue("O&O&O&O&",
- FSCatalogInfo_New, &catalogInfo,
- PyMac_BuildHFSUniStr255, &outName,
- FSSpec_New, &fsSpec,
- FSRef_New, &parentRef);
-#else /* __LP64__ */
- _res = Py_BuildValue("O&O&OO&",
- FSCatalogInfo_New, &catalogInfo,
- PyMac_BuildHFSUniStr255, &outName,
- Py_None,
- FSRef_New, &parentRef);
+ _res = Py_BuildValue("O&O&O&O&",
+ FSCatalogInfo_New, &catalogInfo,
+ PyMac_BuildHFSUniStr255, &outName,
+ FSSpec_New, &fsSpec,
+ FSRef_New, &parentRef);
+#else /* __LP64__ */
+ _res = Py_BuildValue("O&O&OO&",
+ FSCatalogInfo_New, &catalogInfo,
+ PyMac_BuildHFSUniStr255, &outName,
+ Py_None,
+ FSRef_New, &parentRef);
#endif /* __LP64__ */
- return _res;
+ return _res;
}
static PyObject *FSRef_FSSetCatalogInfo(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSCatalogInfoBitmap whichInfo;
- FSCatalogInfo catalogInfo;
- if (!PyArg_ParseTuple(_args, "lO&",
- &whichInfo,
- FSCatalogInfo_Convert, &catalogInfo))
- return NULL;
- _err = FSSetCatalogInfo(&_self->ob_itself,
- whichInfo,
- &catalogInfo);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSCatalogInfoBitmap whichInfo;
+ FSCatalogInfo catalogInfo;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &whichInfo,
+ FSCatalogInfo_Convert, &catalogInfo))
+ return NULL;
+ _err = FSSetCatalogInfo(&_self->ob_itself,
+ whichInfo,
+ &catalogInfo);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSCreateFork(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *forkNameLength__in__;
- UniCharCount forkNameLength__len__;
- int forkNameLength__in_len__;
- if (!PyArg_ParseTuple(_args, "u#",
- &forkNameLength__in__, &forkNameLength__in_len__))
- return NULL;
- forkNameLength__len__ = forkNameLength__in_len__;
- _err = FSCreateFork(&_self->ob_itself,
- forkNameLength__len__, forkNameLength__in__);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *forkNameLength__in__;
+ UniCharCount forkNameLength__len__;
+ int forkNameLength__in_len__;
+ if (!PyArg_ParseTuple(_args, "u#",
+ &forkNameLength__in__, &forkNameLength__in_len__))
+ return NULL;
+ forkNameLength__len__ = forkNameLength__in_len__;
+ _err = FSCreateFork(&_self->ob_itself,
+ forkNameLength__len__, forkNameLength__in__);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSDeleteFork(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *forkNameLength__in__;
- UniCharCount forkNameLength__len__;
- int forkNameLength__in_len__;
- if (!PyArg_ParseTuple(_args, "u#",
- &forkNameLength__in__, &forkNameLength__in_len__))
- return NULL;
- forkNameLength__len__ = forkNameLength__in_len__;
- _err = FSDeleteFork(&_self->ob_itself,
- forkNameLength__len__, forkNameLength__in__);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *forkNameLength__in__;
+ UniCharCount forkNameLength__len__;
+ int forkNameLength__in_len__;
+ if (!PyArg_ParseTuple(_args, "u#",
+ &forkNameLength__in__, &forkNameLength__in_len__))
+ return NULL;
+ forkNameLength__len__ = forkNameLength__in_len__;
+ _err = FSDeleteFork(&_self->ob_itself,
+ forkNameLength__len__, forkNameLength__in__);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSOpenFork(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UniChar *forkNameLength__in__;
- UniCharCount forkNameLength__len__;
- int forkNameLength__in_len__;
- SInt8 permissions;
- FSIORefNum forkRefNum;
- if (!PyArg_ParseTuple(_args, "u#b",
- &forkNameLength__in__, &forkNameLength__in_len__,
- &permissions))
- return NULL;
- forkNameLength__len__ = forkNameLength__in_len__;
- _err = FSOpenFork(&_self->ob_itself,
- forkNameLength__len__, forkNameLength__in__,
- permissions,
- &forkRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- forkRefNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UniChar *forkNameLength__in__;
+ UniCharCount forkNameLength__len__;
+ int forkNameLength__in_len__;
+ SInt8 permissions;
+ FSIORefNum forkRefNum;
+ if (!PyArg_ParseTuple(_args, "u#b",
+ &forkNameLength__in__, &forkNameLength__in_len__,
+ &permissions))
+ return NULL;
+ forkNameLength__len__ = forkNameLength__in_len__;
+ _err = FSOpenFork(&_self->ob_itself,
+ forkNameLength__len__, forkNameLength__in__,
+ permissions,
+ &forkRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ forkRefNum);
+ return _res;
}
static PyObject *FSRef_FNNotify(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- FNMessage message;
- OptionBits flags;
- if (!PyArg_ParseTuple(_args, "ll",
- &message,
- &flags))
- return NULL;
- _err = FNNotify(&_self->ob_itself,
- message,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ FNMessage message;
+ OptionBits flags;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &message,
+ &flags))
+ return NULL;
+ _err = FNNotify(&_self->ob_itself,
+ message,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *FSRef_FSNewAliasMinimal(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- AliasHandle inAlias;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSNewAliasMinimal(&_self->ob_itself,
- &inAlias);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- Alias_New, inAlias);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ AliasHandle inAlias;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSNewAliasMinimal(&_self->ob_itself,
+ &inAlias);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ Alias_New, inAlias);
+ return _res;
}
static PyObject *FSRef_FSIsAliasFile(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Boolean aliasFileFlag;
- Boolean folderFlag;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSIsAliasFile(&_self->ob_itself,
- &aliasFileFlag,
- &folderFlag);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bb",
- aliasFileFlag,
- folderFlag);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Boolean aliasFileFlag;
+ Boolean folderFlag;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSIsAliasFile(&_self->ob_itself,
+ &aliasFileFlag,
+ &folderFlag);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bb",
+ aliasFileFlag,
+ folderFlag);
+ return _res;
}
static PyObject *FSRef_FSRefMakePath(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- OSStatus _err;
+ OSStatus _err;
#define MAXPATHNAME 1024
- UInt8 path[MAXPATHNAME];
- UInt32 maxPathSize = MAXPATHNAME;
+ UInt8 path[MAXPATHNAME];
+ UInt32 maxPathSize = MAXPATHNAME;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSRefMakePath(&_self->ob_itself,
- path,
- maxPathSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("s", path);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSRefMakePath(&_self->ob_itself,
+ path,
+ maxPathSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("s", path);
+ return _res;
}
static PyObject *FSRef_as_pathname(FSRefObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _res = FSRef_FSRefMakePath(_self, _args);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _res = FSRef_FSRefMakePath(_self, _args);
+ return _res;
}
static PyMethodDef FSRef_methods[] = {
- {"FSMakeFSRefUnicode", (PyCFunction)FSRef_FSMakeFSRefUnicode, 1,
- PyDoc_STR("(Buffer nameLength, TextEncoding textEncodingHint) -> (FSRef newRef)")},
- {"FSCompareFSRefs", (PyCFunction)FSRef_FSCompareFSRefs, 1,
- PyDoc_STR("(FSRef ref2) -> None")},
- {"FSCreateFileUnicode", (PyCFunction)FSRef_FSCreateFileUnicode, 1,
- PyDoc_STR("(Buffer nameLength, FSCatalogInfoBitmap whichInfo, FSCatalogInfo catalogInfo) -> (FSRef newRef, FSSpec newSpec)")},
- {"FSCreateDirectoryUnicode", (PyCFunction)FSRef_FSCreateDirectoryUnicode, 1,
- PyDoc_STR("(Buffer nameLength, FSCatalogInfoBitmap whichInfo, FSCatalogInfo catalogInfo) -> (FSRef newRef, FSSpec newSpec, UInt32 newDirID)")},
- {"FSDeleteObject", (PyCFunction)FSRef_FSDeleteObject, 1,
- PyDoc_STR("() -> None")},
- {"FSMoveObject", (PyCFunction)FSRef_FSMoveObject, 1,
- PyDoc_STR("(FSRef destDirectory) -> (FSRef newRef)")},
- {"FSExchangeObjects", (PyCFunction)FSRef_FSExchangeObjects, 1,
- PyDoc_STR("(FSRef destRef) -> None")},
- {"FSRenameUnicode", (PyCFunction)FSRef_FSRenameUnicode, 1,
- PyDoc_STR("(Buffer nameLength, TextEncoding textEncodingHint) -> (FSRef newRef)")},
- {"FSGetCatalogInfo", (PyCFunction)FSRef_FSGetCatalogInfo, 1,
- PyDoc_STR("(FSCatalogInfoBitmap whichInfo) -> (FSCatalogInfo catalogInfo, HFSUniStr255 outName, FSSpec fsSpec, FSRef parentRef)")},
- {"FSSetCatalogInfo", (PyCFunction)FSRef_FSSetCatalogInfo, 1,
- PyDoc_STR("(FSCatalogInfoBitmap whichInfo, FSCatalogInfo catalogInfo) -> None")},
- {"FSCreateFork", (PyCFunction)FSRef_FSCreateFork, 1,
- PyDoc_STR("(Buffer forkNameLength) -> None")},
- {"FSDeleteFork", (PyCFunction)FSRef_FSDeleteFork, 1,
- PyDoc_STR("(Buffer forkNameLength) -> None")},
- {"FSOpenFork", (PyCFunction)FSRef_FSOpenFork, 1,
- PyDoc_STR("(Buffer forkNameLength, SInt8 permissions) -> (SInt16 forkRefNum)")},
- {"FNNotify", (PyCFunction)FSRef_FNNotify, 1,
- PyDoc_STR("(FNMessage message, OptionBits flags) -> None")},
- {"FSNewAliasMinimal", (PyCFunction)FSRef_FSNewAliasMinimal, 1,
- PyDoc_STR("() -> (AliasHandle inAlias)")},
- {"FSIsAliasFile", (PyCFunction)FSRef_FSIsAliasFile, 1,
- PyDoc_STR("() -> (Boolean aliasFileFlag, Boolean folderFlag)")},
- {"FSRefMakePath", (PyCFunction)FSRef_FSRefMakePath, 1,
- PyDoc_STR("() -> string")},
- {"as_pathname", (PyCFunction)FSRef_as_pathname, 1,
- PyDoc_STR("() -> string")},
- {NULL, NULL, 0}
+ {"FSMakeFSRefUnicode", (PyCFunction)FSRef_FSMakeFSRefUnicode, 1,
+ PyDoc_STR("(Buffer nameLength, TextEncoding textEncodingHint) -> (FSRef newRef)")},
+ {"FSCompareFSRefs", (PyCFunction)FSRef_FSCompareFSRefs, 1,
+ PyDoc_STR("(FSRef ref2) -> None")},
+ {"FSCreateFileUnicode", (PyCFunction)FSRef_FSCreateFileUnicode, 1,
+ PyDoc_STR("(Buffer nameLength, FSCatalogInfoBitmap whichInfo, FSCatalogInfo catalogInfo) -> (FSRef newRef, FSSpec newSpec)")},
+ {"FSCreateDirectoryUnicode", (PyCFunction)FSRef_FSCreateDirectoryUnicode, 1,
+ PyDoc_STR("(Buffer nameLength, FSCatalogInfoBitmap whichInfo, FSCatalogInfo catalogInfo) -> (FSRef newRef, FSSpec newSpec, UInt32 newDirID)")},
+ {"FSDeleteObject", (PyCFunction)FSRef_FSDeleteObject, 1,
+ PyDoc_STR("() -> None")},
+ {"FSMoveObject", (PyCFunction)FSRef_FSMoveObject, 1,
+ PyDoc_STR("(FSRef destDirectory) -> (FSRef newRef)")},
+ {"FSExchangeObjects", (PyCFunction)FSRef_FSExchangeObjects, 1,
+ PyDoc_STR("(FSRef destRef) -> None")},
+ {"FSRenameUnicode", (PyCFunction)FSRef_FSRenameUnicode, 1,
+ PyDoc_STR("(Buffer nameLength, TextEncoding textEncodingHint) -> (FSRef newRef)")},
+ {"FSGetCatalogInfo", (PyCFunction)FSRef_FSGetCatalogInfo, 1,
+ PyDoc_STR("(FSCatalogInfoBitmap whichInfo) -> (FSCatalogInfo catalogInfo, HFSUniStr255 outName, FSSpec fsSpec, FSRef parentRef)")},
+ {"FSSetCatalogInfo", (PyCFunction)FSRef_FSSetCatalogInfo, 1,
+ PyDoc_STR("(FSCatalogInfoBitmap whichInfo, FSCatalogInfo catalogInfo) -> None")},
+ {"FSCreateFork", (PyCFunction)FSRef_FSCreateFork, 1,
+ PyDoc_STR("(Buffer forkNameLength) -> None")},
+ {"FSDeleteFork", (PyCFunction)FSRef_FSDeleteFork, 1,
+ PyDoc_STR("(Buffer forkNameLength) -> None")},
+ {"FSOpenFork", (PyCFunction)FSRef_FSOpenFork, 1,
+ PyDoc_STR("(Buffer forkNameLength, SInt8 permissions) -> (SInt16 forkRefNum)")},
+ {"FNNotify", (PyCFunction)FSRef_FNNotify, 1,
+ PyDoc_STR("(FNMessage message, OptionBits flags) -> None")},
+ {"FSNewAliasMinimal", (PyCFunction)FSRef_FSNewAliasMinimal, 1,
+ PyDoc_STR("() -> (AliasHandle inAlias)")},
+ {"FSIsAliasFile", (PyCFunction)FSRef_FSIsAliasFile, 1,
+ PyDoc_STR("() -> (Boolean aliasFileFlag, Boolean folderFlag)")},
+ {"FSRefMakePath", (PyCFunction)FSRef_FSRefMakePath, 1,
+ PyDoc_STR("() -> string")},
+ {"as_pathname", (PyCFunction)FSRef_as_pathname, 1,
+ PyDoc_STR("() -> string")},
+ {NULL, NULL, 0}
};
static PyObject *FSRef_get_data(FSRefObject *self, void *closure)
{
- return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
+ return PyString_FromStringAndSize((char *)&self->ob_itself, sizeof(self->ob_itself));
}
#define FSRef_set_data NULL
static PyGetSetDef FSRef_getsetlist[] = {
- {"data", (getter)FSRef_get_data, (setter)FSRef_set_data, "Raw data of the FSRef object"},
- {NULL, NULL, NULL, NULL},
+ {"data", (getter)FSRef_get_data, (setter)FSRef_set_data, "Raw data of the FSRef object"},
+ {NULL, NULL, NULL, NULL},
};
@@ -2033,93 +2033,93 @@ static PyGetSetDef FSRef_getsetlist[] = {
#define FSRef_hash NULL
static int FSRef_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- PyObject *v = NULL;
- char *rawdata = NULL;
- int rawdatalen = 0;
- static char *kw[] = {"itself", "rawdata", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|Os#", kw, &v, &rawdata, &rawdatalen))
- return -1;
- if (v && rawdata)
- {
- PyErr_SetString(PyExc_TypeError, "Only one of itself or rawdata may be specified");
- return -1;
- }
- if (!v && !rawdata)
- {
- PyErr_SetString(PyExc_TypeError, "One of itself or rawdata must be specified");
- return -1;
- }
- if (rawdata)
- {
- if (rawdatalen != sizeof(FSRef))
- {
- PyErr_SetString(PyExc_TypeError, "FSRef rawdata incorrect size");
- return -1;
- }
- memcpy(&((FSRefObject *)_self)->ob_itself, rawdata, rawdatalen);
- return 0;
- }
- if (PyMac_GetFSRef(v, &((FSRefObject *)_self)->ob_itself)) return 0;
- return -1;
+ PyObject *v = NULL;
+ char *rawdata = NULL;
+ int rawdatalen = 0;
+ static char *kw[] = {"itself", "rawdata", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|Os#", kw, &v, &rawdata, &rawdatalen))
+ return -1;
+ if (v && rawdata)
+ {
+ PyErr_SetString(PyExc_TypeError, "Only one of itself or rawdata may be specified");
+ return -1;
+ }
+ if (!v && !rawdata)
+ {
+ PyErr_SetString(PyExc_TypeError, "One of itself or rawdata must be specified");
+ return -1;
+ }
+ if (rawdata)
+ {
+ if (rawdatalen != sizeof(FSRef))
+ {
+ PyErr_SetString(PyExc_TypeError, "FSRef rawdata incorrect size");
+ return -1;
+ }
+ memcpy(&((FSRefObject *)_self)->ob_itself, rawdata, rawdatalen);
+ return 0;
+ }
+ if (PyMac_GetFSRef(v, &((FSRefObject *)_self)->ob_itself)) return 0;
+ return -1;
}
#define FSRef_tp_alloc PyType_GenericAlloc
static PyObject *FSRef_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
+ PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- memset(&((FSRefObject *)self)->ob_itself, 0, sizeof(FSRef));
- return self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ memset(&((FSRefObject *)self)->ob_itself, 0, sizeof(FSRef));
+ return self;
}
#define FSRef_tp_free PyObject_Del
static PyTypeObject FSRef_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "Carbon.File.FSRef", /*tp_name*/
- sizeof(FSRefObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) FSRef_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) FSRef_compare, /*tp_compare*/
- (reprfunc) FSRef_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) FSRef_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*/
- FSRef_methods, /* tp_methods */
- 0, /*tp_members*/
- FSRef_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- FSRef_tp_init, /* tp_init */
- FSRef_tp_alloc, /* tp_alloc */
- FSRef_tp_new, /* tp_new */
- FSRef_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "Carbon.File.FSRef", /*tp_name*/
+ sizeof(FSRefObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) FSRef_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) FSRef_compare, /*tp_compare*/
+ (reprfunc) FSRef_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) FSRef_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*/
+ FSRef_methods, /* tp_methods */
+ 0, /*tp_members*/
+ FSRef_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ FSRef_tp_init, /* tp_init */
+ FSRef_tp_alloc, /* tp_alloc */
+ FSRef_tp_new, /* tp_new */
+ FSRef_tp_free, /* tp_free */
};
/* --------------------- End object type FSRef ---------------------- */
@@ -2127,1123 +2127,1123 @@ static PyTypeObject FSRef_Type = {
#ifndef __LP64__
static PyObject *File_UnmountVol(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str63 volName;
- short vRefNum;
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetStr255, volName,
- &vRefNum))
- return NULL;
- _err = UnmountVol(volName,
- vRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str63 volName;
+ short vRefNum;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetStr255, volName,
+ &vRefNum))
+ return NULL;
+ _err = UnmountVol(volName,
+ vRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FlushVol(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str63 volName;
- short vRefNum;
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetStr255, volName,
- &vRefNum))
- return NULL;
- _err = FlushVol(volName,
- vRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str63 volName;
+ short vRefNum;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetStr255, volName,
+ &vRefNum))
+ return NULL;
+ _err = FlushVol(volName,
+ vRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_HSetVol(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str63 volName;
- short vRefNum;
- long dirID;
- if (!PyArg_ParseTuple(_args, "O&hl",
- PyMac_GetStr255, volName,
- &vRefNum,
- &dirID))
- return NULL;
- _err = HSetVol(volName,
- vRefNum,
- dirID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str63 volName;
+ short vRefNum;
+ long dirID;
+ if (!PyArg_ParseTuple(_args, "O&hl",
+ PyMac_GetStr255, volName,
+ &vRefNum,
+ &dirID))
+ return NULL;
+ _err = HSetVol(volName,
+ vRefNum,
+ dirID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FSClose(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _err = FSClose(refNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _err = FSClose(refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_Allocate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- long count;
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _err = Allocate(refNum,
- &count);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- count);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ long count;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _err = Allocate(refNum,
+ &count);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ count);
+ return _res;
}
static PyObject *File_GetEOF(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- long logEOF;
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _err = GetEOF(refNum,
- &logEOF);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- logEOF);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ long logEOF;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _err = GetEOF(refNum,
+ &logEOF);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ logEOF);
+ return _res;
}
static PyObject *File_SetEOF(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- long logEOF;
- if (!PyArg_ParseTuple(_args, "hl",
- &refNum,
- &logEOF))
- return NULL;
- _err = SetEOF(refNum,
- logEOF);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ long logEOF;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &refNum,
+ &logEOF))
+ return NULL;
+ _err = SetEOF(refNum,
+ logEOF);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_GetFPos(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- long filePos;
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _err = GetFPos(refNum,
- &filePos);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- filePos);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ long filePos;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _err = GetFPos(refNum,
+ &filePos);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ filePos);
+ return _res;
}
static PyObject *File_SetFPos(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- short posMode;
- long posOff;
- if (!PyArg_ParseTuple(_args, "hhl",
- &refNum,
- &posMode,
- &posOff))
- return NULL;
- _err = SetFPos(refNum,
- posMode,
- posOff);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ short posMode;
+ long posOff;
+ if (!PyArg_ParseTuple(_args, "hhl",
+ &refNum,
+ &posMode,
+ &posOff))
+ return NULL;
+ _err = SetFPos(refNum,
+ posMode,
+ posOff);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_GetVRefNum(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short fileRefNum;
- short vRefNum;
- if (!PyArg_ParseTuple(_args, "h",
- &fileRefNum))
- return NULL;
- _err = GetVRefNum(fileRefNum,
- &vRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- vRefNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short fileRefNum;
+ short vRefNum;
+ if (!PyArg_ParseTuple(_args, "h",
+ &fileRefNum))
+ return NULL;
+ _err = GetVRefNum(fileRefNum,
+ &vRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ vRefNum);
+ return _res;
}
static PyObject *File_HGetVol(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- StringPtr volName;
- short vRefNum;
- long dirID;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, &volName))
- return NULL;
- _err = HGetVol(volName,
- &vRefNum,
- &dirID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hl",
- vRefNum,
- dirID);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ StringPtr volName;
+ short vRefNum;
+ long dirID;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, &volName))
+ return NULL;
+ _err = HGetVol(volName,
+ &vRefNum,
+ &dirID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hl",
+ vRefNum,
+ dirID);
+ return _res;
}
static PyObject *File_HOpen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- SInt8 permission;
- short refNum;
- if (!PyArg_ParseTuple(_args, "hlO&b",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName,
- &permission))
- return NULL;
- _err = HOpen(vRefNum,
- dirID,
- fileName,
- permission,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
+ SInt8 permission;
+ short refNum;
+ if (!PyArg_ParseTuple(_args, "hlO&b",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName,
+ &permission))
+ return NULL;
+ _err = HOpen(vRefNum,
+ dirID,
+ fileName,
+ permission,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *File_HOpenDF(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- SInt8 permission;
- short refNum;
- if (!PyArg_ParseTuple(_args, "hlO&b",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName,
- &permission))
- return NULL;
- _err = HOpenDF(vRefNum,
- dirID,
- fileName,
- permission,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
+ SInt8 permission;
+ short refNum;
+ if (!PyArg_ParseTuple(_args, "hlO&b",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName,
+ &permission))
+ return NULL;
+ _err = HOpenDF(vRefNum,
+ dirID,
+ fileName,
+ permission,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *File_HOpenRF(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- SInt8 permission;
- short refNum;
- if (!PyArg_ParseTuple(_args, "hlO&b",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName,
- &permission))
- return NULL;
- _err = HOpenRF(vRefNum,
- dirID,
- fileName,
- permission,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
+ SInt8 permission;
+ short refNum;
+ if (!PyArg_ParseTuple(_args, "hlO&b",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName,
+ &permission))
+ return NULL;
+ _err = HOpenRF(vRefNum,
+ dirID,
+ fileName,
+ permission,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *File_AllocContig(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short refNum;
- long count;
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _err = AllocContig(refNum,
- &count);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- count);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short refNum;
+ long count;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _err = AllocContig(refNum,
+ &count);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ count);
+ return _res;
}
static PyObject *File_HCreate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- OSType creator;
- OSType fileType;
- if (!PyArg_ParseTuple(_args, "hlO&O&O&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName,
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &fileType))
- return NULL;
- _err = HCreate(vRefNum,
- dirID,
- fileName,
- creator,
- fileType);
- 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;
+ Str255 fileName;
+ OSType creator;
+ OSType fileType;
+ if (!PyArg_ParseTuple(_args, "hlO&O&O&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName,
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &fileType))
+ return NULL;
+ _err = HCreate(vRefNum,
+ dirID,
+ fileName,
+ creator,
+ fileType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_DirCreate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long parentDirID;
- Str255 directoryName;
- long createdDirID;
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &parentDirID,
- PyMac_GetStr255, directoryName))
- return NULL;
- _err = DirCreate(vRefNum,
- parentDirID,
- directoryName,
- &createdDirID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- createdDirID);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short vRefNum;
+ long parentDirID;
+ Str255 directoryName;
+ long createdDirID;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &parentDirID,
+ PyMac_GetStr255, directoryName))
+ return NULL;
+ _err = DirCreate(vRefNum,
+ parentDirID,
+ directoryName,
+ &createdDirID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ createdDirID);
+ return _res;
}
static PyObject *File_HDelete(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName))
- return NULL;
- _err = HDelete(vRefNum,
- dirID,
- fileName);
- 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;
+ Str255 fileName;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName))
+ return NULL;
+ _err = HDelete(vRefNum,
+ dirID,
+ fileName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_HGetFInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- FInfo fndrInfo;
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName))
- return NULL;
- _err = HGetFInfo(vRefNum,
- dirID,
- fileName,
- &fndrInfo);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FInfo_New, &fndrInfo);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
+ FInfo fndrInfo;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName))
+ return NULL;
+ _err = HGetFInfo(vRefNum,
+ dirID,
+ fileName,
+ &fndrInfo);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FInfo_New, &fndrInfo);
+ return _res;
}
static PyObject *File_HSetFInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- FInfo fndrInfo;
- if (!PyArg_ParseTuple(_args, "hlO&O&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName,
- FInfo_Convert, &fndrInfo))
- return NULL;
- _err = HSetFInfo(vRefNum,
- dirID,
- fileName,
- &fndrInfo);
- 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;
+ Str255 fileName;
+ FInfo fndrInfo;
+ if (!PyArg_ParseTuple(_args, "hlO&O&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName,
+ FInfo_Convert, &fndrInfo))
+ return NULL;
+ _err = HSetFInfo(vRefNum,
+ dirID,
+ fileName,
+ &fndrInfo);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_HSetFLock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName))
- return NULL;
- _err = HSetFLock(vRefNum,
- dirID,
- fileName);
- 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;
+ Str255 fileName;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName))
+ return NULL;
+ _err = HSetFLock(vRefNum,
+ dirID,
+ fileName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_HRstFLock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName))
- return NULL;
- _err = HRstFLock(vRefNum,
- dirID,
- fileName);
- 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;
+ Str255 fileName;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName))
+ return NULL;
+ _err = HRstFLock(vRefNum,
+ dirID,
+ fileName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_HRename(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 oldName;
- Str255 newName;
- if (!PyArg_ParseTuple(_args, "hlO&O&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, oldName,
- PyMac_GetStr255, newName))
- return NULL;
- _err = HRename(vRefNum,
- dirID,
- oldName,
- newName);
- 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;
+ Str255 oldName;
+ Str255 newName;
+ if (!PyArg_ParseTuple(_args, "hlO&O&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, oldName,
+ PyMac_GetStr255, newName))
+ return NULL;
+ _err = HRename(vRefNum,
+ dirID,
+ oldName,
+ newName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_CatMove(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 oldName;
- long newDirID;
- Str255 newName;
- if (!PyArg_ParseTuple(_args, "hlO&lO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, oldName,
- &newDirID,
- PyMac_GetStr255, newName))
- return NULL;
- _err = CatMove(vRefNum,
- dirID,
- oldName,
- newDirID,
- newName);
- 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;
+ Str255 oldName;
+ long newDirID;
+ Str255 newName;
+ if (!PyArg_ParseTuple(_args, "hlO&lO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, oldName,
+ &newDirID,
+ PyMac_GetStr255, newName))
+ return NULL;
+ _err = CatMove(vRefNum,
+ dirID,
+ oldName,
+ newDirID,
+ newName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FSMakeFSSpec(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short vRefNum;
- long dirID;
- Str255 fileName;
- FSSpec spec;
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName))
- return NULL;
- _err = FSMakeFSSpec(vRefNum,
- dirID,
- fileName,
- &spec);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- FSSpec_New, &spec);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
+ FSSpec spec;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName))
+ return NULL;
+ _err = FSMakeFSSpec(vRefNum,
+ dirID,
+ fileName,
+ &spec);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ FSSpec_New, &spec);
+ return _res;
}
#endif /* !__LP64__ */
static PyObject *File_FSGetForkPosition(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- SInt64 position;
- if (!PyArg_ParseTuple(_args, "h",
- &forkRefNum))
- return NULL;
- _err = FSGetForkPosition(forkRefNum,
- &position);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("L",
- position);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ SInt64 position;
+ if (!PyArg_ParseTuple(_args, "h",
+ &forkRefNum))
+ return NULL;
+ _err = FSGetForkPosition(forkRefNum,
+ &position);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("L",
+ position);
+ return _res;
}
static PyObject *File_FSSetForkPosition(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- UInt16 positionMode;
- SInt64 positionOffset;
- if (!PyArg_ParseTuple(_args, "hHL",
- &forkRefNum,
- &positionMode,
- &positionOffset))
- return NULL;
- _err = FSSetForkPosition(forkRefNum,
- positionMode,
- positionOffset);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ UInt16 positionMode;
+ SInt64 positionOffset;
+ if (!PyArg_ParseTuple(_args, "hHL",
+ &forkRefNum,
+ &positionMode,
+ &positionOffset))
+ return NULL;
+ _err = FSSetForkPosition(forkRefNum,
+ positionMode,
+ positionOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FSGetForkSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- SInt64 forkSize;
- if (!PyArg_ParseTuple(_args, "h",
- &forkRefNum))
- return NULL;
- _err = FSGetForkSize(forkRefNum,
- &forkSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("L",
- forkSize);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ SInt64 forkSize;
+ if (!PyArg_ParseTuple(_args, "h",
+ &forkRefNum))
+ return NULL;
+ _err = FSGetForkSize(forkRefNum,
+ &forkSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("L",
+ forkSize);
+ return _res;
}
static PyObject *File_FSSetForkSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- UInt16 positionMode;
- SInt64 positionOffset;
- if (!PyArg_ParseTuple(_args, "hHL",
- &forkRefNum,
- &positionMode,
- &positionOffset))
- return NULL;
- _err = FSSetForkSize(forkRefNum,
- positionMode,
- positionOffset);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ UInt16 positionMode;
+ SInt64 positionOffset;
+ if (!PyArg_ParseTuple(_args, "hHL",
+ &forkRefNum,
+ &positionMode,
+ &positionOffset))
+ return NULL;
+ _err = FSSetForkSize(forkRefNum,
+ positionMode,
+ positionOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FSAllocateFork(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- FSAllocationFlags flags;
- UInt16 positionMode;
- SInt64 positionOffset;
- UInt64 requestCount;
- UInt64 actualCount;
- if (!PyArg_ParseTuple(_args, "hHHLL",
- &forkRefNum,
- &flags,
- &positionMode,
- &positionOffset,
- &requestCount))
- return NULL;
- _err = FSAllocateFork(forkRefNum,
- flags,
- positionMode,
- positionOffset,
- requestCount,
- &actualCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("L",
- actualCount);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ FSAllocationFlags flags;
+ UInt16 positionMode;
+ SInt64 positionOffset;
+ UInt64 requestCount;
+ UInt64 actualCount;
+ if (!PyArg_ParseTuple(_args, "hHHLL",
+ &forkRefNum,
+ &flags,
+ &positionMode,
+ &positionOffset,
+ &requestCount))
+ return NULL;
+ _err = FSAllocateFork(forkRefNum,
+ flags,
+ positionMode,
+ positionOffset,
+ requestCount,
+ &actualCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("L",
+ actualCount);
+ return _res;
}
static PyObject *File_FSFlushFork(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- if (!PyArg_ParseTuple(_args, "h",
- &forkRefNum))
- return NULL;
- _err = FSFlushFork(forkRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ if (!PyArg_ParseTuple(_args, "h",
+ &forkRefNum))
+ return NULL;
+ _err = FSFlushFork(forkRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FSCloseFork(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 forkRefNum;
- if (!PyArg_ParseTuple(_args, "h",
- &forkRefNum))
- return NULL;
- _err = FSCloseFork(forkRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 forkRefNum;
+ if (!PyArg_ParseTuple(_args, "h",
+ &forkRefNum))
+ return NULL;
+ _err = FSCloseFork(forkRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FSGetDataForkName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- HFSUniStr255 dataForkName;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSGetDataForkName(&dataForkName);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildHFSUniStr255, &dataForkName);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ HFSUniStr255 dataForkName;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSGetDataForkName(&dataForkName);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildHFSUniStr255, &dataForkName);
+ return _res;
}
static PyObject *File_FSGetResourceForkName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- HFSUniStr255 resourceForkName;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = FSGetResourceForkName(&resourceForkName);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildHFSUniStr255, &resourceForkName);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ HFSUniStr255 resourceForkName;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = FSGetResourceForkName(&resourceForkName);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildHFSUniStr255, &resourceForkName);
+ return _res;
}
static PyObject *File_FSPathMakeRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt8 * path;
- FSRef ref;
- Boolean isDirectory;
- if (!PyArg_ParseTuple(_args, "s",
- &path))
- return NULL;
- _err = FSPathMakeRef(path,
- &ref,
- &isDirectory);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- FSRef_New, &ref,
- isDirectory);
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt8 * path;
+ FSRef ref;
+ Boolean isDirectory;
+ if (!PyArg_ParseTuple(_args, "s",
+ &path))
+ return NULL;
+ _err = FSPathMakeRef(path,
+ &ref,
+ &isDirectory);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ FSRef_New, &ref,
+ isDirectory);
+ return _res;
}
static PyObject *File_FNNotifyByPath(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt8 * path;
- FNMessage message;
- OptionBits flags;
- if (!PyArg_ParseTuple(_args, "sll",
- &path,
- &message,
- &flags))
- return NULL;
- _err = FNNotifyByPath(path,
- message,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt8 * path;
+ FNMessage message;
+ OptionBits flags;
+ if (!PyArg_ParseTuple(_args, "sll",
+ &path,
+ &message,
+ &flags))
+ return NULL;
+ _err = FNNotifyByPath(path,
+ message,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *File_FNNotifyAll(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- FNMessage message;
- OptionBits flags;
- if (!PyArg_ParseTuple(_args, "ll",
- &message,
- &flags))
- return NULL;
- _err = FNNotifyAll(message,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ FNMessage message;
+ OptionBits flags;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &message,
+ &flags))
+ return NULL;
+ _err = FNNotifyAll(message,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#ifndef __LP64__
static PyObject *File_NewAlias(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fromFile__buf__;
- FSSpec *fromFile = &fromFile__buf__;
- FSSpec target;
- AliasHandle alias;
- if (!PyArg_ParseTuple(_args, "O&O&",
- myPyMac_GetOptFSSpecPtr, &fromFile,
- FSSpec_Convert, &target))
- return NULL;
- _err = NewAlias(fromFile,
- &target,
- &alias);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- Alias_New, alias);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fromFile__buf__;
+ FSSpec *fromFile = &fromFile__buf__;
+ FSSpec target;
+ AliasHandle alias;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ myPyMac_GetOptFSSpecPtr, &fromFile,
+ FSSpec_Convert, &target))
+ return NULL;
+ _err = NewAlias(fromFile,
+ &target,
+ &alias);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ Alias_New, alias);
+ return _res;
}
static PyObject *File_NewAliasMinimalFromFullPath(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- char *fullPath__in__;
- int fullPath__len__;
- int fullPath__in_len__;
- Str32 zoneName;
- Str31 serverName;
- AliasHandle alias;
- if (!PyArg_ParseTuple(_args, "s#O&O&",
- &fullPath__in__, &fullPath__in_len__,
- PyMac_GetStr255, zoneName,
- PyMac_GetStr255, serverName))
- return NULL;
- fullPath__len__ = fullPath__in_len__;
- _err = NewAliasMinimalFromFullPath(fullPath__len__, fullPath__in__,
- zoneName,
- serverName,
- &alias);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- Alias_New, alias);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ char *fullPath__in__;
+ int fullPath__len__;
+ int fullPath__in_len__;
+ Str32 zoneName;
+ Str31 serverName;
+ AliasHandle alias;
+ if (!PyArg_ParseTuple(_args, "s#O&O&",
+ &fullPath__in__, &fullPath__in_len__,
+ PyMac_GetStr255, zoneName,
+ PyMac_GetStr255, serverName))
+ return NULL;
+ fullPath__len__ = fullPath__in_len__;
+ _err = NewAliasMinimalFromFullPath(fullPath__len__, fullPath__in__,
+ zoneName,
+ serverName,
+ &alias);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ Alias_New, alias);
+ return _res;
}
static PyObject *File_ResolveAliasFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec theSpec;
- Boolean resolveAliasChains;
- Boolean targetIsFolder;
- Boolean wasAliased;
- if (!PyArg_ParseTuple(_args, "O&b",
- FSSpec_Convert, &theSpec,
- &resolveAliasChains))
- return NULL;
- _err = ResolveAliasFile(&theSpec,
- resolveAliasChains,
- &targetIsFolder,
- &wasAliased);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&bb",
- FSSpec_New, &theSpec,
- targetIsFolder,
- wasAliased);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec theSpec;
+ Boolean resolveAliasChains;
+ Boolean targetIsFolder;
+ Boolean wasAliased;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ FSSpec_Convert, &theSpec,
+ &resolveAliasChains))
+ return NULL;
+ _err = ResolveAliasFile(&theSpec,
+ resolveAliasChains,
+ &targetIsFolder,
+ &wasAliased);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&bb",
+ FSSpec_New, &theSpec,
+ targetIsFolder,
+ wasAliased);
+ return _res;
}
static PyObject *File_ResolveAliasFileWithMountFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec theSpec;
- Boolean resolveAliasChains;
- Boolean targetIsFolder;
- Boolean wasAliased;
- unsigned long mountFlags;
- if (!PyArg_ParseTuple(_args, "O&bl",
- FSSpec_Convert, &theSpec,
- &resolveAliasChains,
- &mountFlags))
- return NULL;
- _err = ResolveAliasFileWithMountFlags(&theSpec,
- resolveAliasChains,
- &targetIsFolder,
- &wasAliased,
- mountFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&bb",
- FSSpec_New, &theSpec,
- targetIsFolder,
- wasAliased);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec theSpec;
+ Boolean resolveAliasChains;
+ Boolean targetIsFolder;
+ Boolean wasAliased;
+ unsigned long mountFlags;
+ if (!PyArg_ParseTuple(_args, "O&bl",
+ FSSpec_Convert, &theSpec,
+ &resolveAliasChains,
+ &mountFlags))
+ return NULL;
+ _err = ResolveAliasFileWithMountFlags(&theSpec,
+ resolveAliasChains,
+ &targetIsFolder,
+ &wasAliased,
+ mountFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&bb",
+ FSSpec_New, &theSpec,
+ targetIsFolder,
+ wasAliased);
+ return _res;
}
static PyObject *File_UpdateAlias(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fromFile__buf__;
- FSSpec *fromFile = &fromFile__buf__;
- FSSpec target;
- AliasHandle alias;
- Boolean wasChanged;
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- myPyMac_GetOptFSSpecPtr, &fromFile,
- FSSpec_Convert, &target,
- Alias_Convert, &alias))
- return NULL;
- _err = UpdateAlias(fromFile,
- &target,
- alias,
- &wasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fromFile__buf__;
+ FSSpec *fromFile = &fromFile__buf__;
+ FSSpec target;
+ AliasHandle alias;
+ Boolean wasChanged;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ myPyMac_GetOptFSSpecPtr, &fromFile,
+ FSSpec_Convert, &target,
+ Alias_Convert, &alias))
+ return NULL;
+ _err = UpdateAlias(fromFile,
+ &target,
+ alias,
+ &wasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ wasChanged);
+ return _res;
}
static PyObject *File_ResolveAliasFileWithMountFlagsNoUI(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec theSpec;
- Boolean resolveAliasChains;
- Boolean targetIsFolder;
- Boolean wasAliased;
- unsigned long mountFlags;
- if (!PyArg_ParseTuple(_args, "O&bl",
- FSSpec_Convert, &theSpec,
- &resolveAliasChains,
- &mountFlags))
- return NULL;
- _err = ResolveAliasFileWithMountFlagsNoUI(&theSpec,
- resolveAliasChains,
- &targetIsFolder,
- &wasAliased,
- mountFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&bb",
- FSSpec_New, &theSpec,
- targetIsFolder,
- wasAliased);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec theSpec;
+ Boolean resolveAliasChains;
+ Boolean targetIsFolder;
+ Boolean wasAliased;
+ unsigned long mountFlags;
+ if (!PyArg_ParseTuple(_args, "O&bl",
+ FSSpec_Convert, &theSpec,
+ &resolveAliasChains,
+ &mountFlags))
+ return NULL;
+ _err = ResolveAliasFileWithMountFlagsNoUI(&theSpec,
+ resolveAliasChains,
+ &targetIsFolder,
+ &wasAliased,
+ mountFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&bb",
+ FSSpec_New, &theSpec,
+ targetIsFolder,
+ wasAliased);
+ return _res;
}
#endif /* !__LP64__ */
static PyObject *File_FSNewAlias(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef fromFile__buf__;
- FSRef *fromFile = &fromFile__buf__;
- FSRef target;
- AliasHandle inAlias;
- if (!PyArg_ParseTuple(_args, "O&O&",
- myPyMac_GetOptFSRefPtr, &fromFile,
- FSRef_Convert, &target))
- return NULL;
- _err = FSNewAlias(fromFile,
- &target,
- &inAlias);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- Alias_New, inAlias);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef fromFile__buf__;
+ FSRef *fromFile = &fromFile__buf__;
+ FSRef target;
+ AliasHandle inAlias;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ myPyMac_GetOptFSRefPtr, &fromFile,
+ FSRef_Convert, &target))
+ return NULL;
+ _err = FSNewAlias(fromFile,
+ &target,
+ &inAlias);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ Alias_New, inAlias);
+ return _res;
}
static PyObject *File_FSResolveAliasFileWithMountFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef theRef;
- Boolean resolveAliasChains;
- Boolean targetIsFolder;
- Boolean wasAliased;
- unsigned long mountFlags;
- if (!PyArg_ParseTuple(_args, "O&bl",
- FSRef_Convert, &theRef,
- &resolveAliasChains,
- &mountFlags))
- return NULL;
- _err = FSResolveAliasFileWithMountFlags(&theRef,
- resolveAliasChains,
- &targetIsFolder,
- &wasAliased,
- mountFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&bb",
- FSRef_New, &theRef,
- targetIsFolder,
- wasAliased);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef theRef;
+ Boolean resolveAliasChains;
+ Boolean targetIsFolder;
+ Boolean wasAliased;
+ unsigned long mountFlags;
+ if (!PyArg_ParseTuple(_args, "O&bl",
+ FSRef_Convert, &theRef,
+ &resolveAliasChains,
+ &mountFlags))
+ return NULL;
+ _err = FSResolveAliasFileWithMountFlags(&theRef,
+ resolveAliasChains,
+ &targetIsFolder,
+ &wasAliased,
+ mountFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&bb",
+ FSRef_New, &theRef,
+ targetIsFolder,
+ wasAliased);
+ return _res;
}
static PyObject *File_FSResolveAliasFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef theRef;
- Boolean resolveAliasChains;
- Boolean targetIsFolder;
- Boolean wasAliased;
- if (!PyArg_ParseTuple(_args, "O&b",
- FSRef_Convert, &theRef,
- &resolveAliasChains))
- return NULL;
- _err = FSResolveAliasFile(&theRef,
- resolveAliasChains,
- &targetIsFolder,
- &wasAliased);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&bb",
- FSRef_New, &theRef,
- targetIsFolder,
- wasAliased);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef theRef;
+ Boolean resolveAliasChains;
+ Boolean targetIsFolder;
+ Boolean wasAliased;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ FSRef_Convert, &theRef,
+ &resolveAliasChains))
+ return NULL;
+ _err = FSResolveAliasFile(&theRef,
+ resolveAliasChains,
+ &targetIsFolder,
+ &wasAliased);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&bb",
+ FSRef_New, &theRef,
+ targetIsFolder,
+ wasAliased);
+ return _res;
}
static PyObject *File_FSUpdateAlias(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef fromFile__buf__;
- FSRef *fromFile = &fromFile__buf__;
- FSRef target;
- AliasHandle alias;
- Boolean wasChanged;
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- myPyMac_GetOptFSRefPtr, &fromFile,
- FSRef_Convert, &target,
- Alias_Convert, &alias))
- return NULL;
- _err = FSUpdateAlias(fromFile,
- &target,
- alias,
- &wasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- wasChanged);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef fromFile__buf__;
+ FSRef *fromFile = &fromFile__buf__;
+ FSRef target;
+ AliasHandle alias;
+ Boolean wasChanged;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ myPyMac_GetOptFSRefPtr, &fromFile,
+ FSRef_Convert, &target,
+ Alias_Convert, &alias))
+ return NULL;
+ _err = FSUpdateAlias(fromFile,
+ &target,
+ alias,
+ &wasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ wasChanged);
+ return _res;
}
static PyObject *File_pathname(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- PyObject *obj;
+ PyObject *obj;
- if (!PyArg_ParseTuple(_args, "O", &obj))
- return NULL;
- if (PyString_Check(obj)) {
- Py_INCREF(obj);
- return obj;
- }
- if (PyUnicode_Check(obj))
- return PyUnicode_AsEncodedString(obj, "utf8", "strict");
- _res = PyObject_CallMethod(obj, "as_pathname", NULL);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O", &obj))
+ return NULL;
+ if (PyString_Check(obj)) {
+ Py_INCREF(obj);
+ return obj;
+ }
+ if (PyUnicode_Check(obj))
+ return PyUnicode_AsEncodedString(obj, "utf8", "strict");
+ _res = PyObject_CallMethod(obj, "as_pathname", NULL);
+ return _res;
}
static PyMethodDef File_methods[] = {
#ifndef __LP64__
- {"UnmountVol", (PyCFunction)File_UnmountVol, 1,
- PyDoc_STR("(Str63 volName, short vRefNum) -> None")},
- {"FlushVol", (PyCFunction)File_FlushVol, 1,
- PyDoc_STR("(Str63 volName, short vRefNum) -> None")},
- {"HSetVol", (PyCFunction)File_HSetVol, 1,
- PyDoc_STR("(Str63 volName, short vRefNum, long dirID) -> None")},
- {"FSClose", (PyCFunction)File_FSClose, 1,
- PyDoc_STR("(short refNum) -> None")},
- {"Allocate", (PyCFunction)File_Allocate, 1,
- PyDoc_STR("(short refNum) -> (long count)")},
- {"GetEOF", (PyCFunction)File_GetEOF, 1,
- PyDoc_STR("(short refNum) -> (long logEOF)")},
- {"SetEOF", (PyCFunction)File_SetEOF, 1,
- PyDoc_STR("(short refNum, long logEOF) -> None")},
- {"GetFPos", (PyCFunction)File_GetFPos, 1,
- PyDoc_STR("(short refNum) -> (long filePos)")},
- {"SetFPos", (PyCFunction)File_SetFPos, 1,
- PyDoc_STR("(short refNum, short posMode, long posOff) -> None")},
- {"GetVRefNum", (PyCFunction)File_GetVRefNum, 1,
- PyDoc_STR("(short fileRefNum) -> (short vRefNum)")},
- {"HGetVol", (PyCFunction)File_HGetVol, 1,
- PyDoc_STR("(StringPtr volName) -> (short vRefNum, long dirID)")},
- {"HOpen", (PyCFunction)File_HOpen, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SInt8 permission) -> (short refNum)")},
- {"HOpenDF", (PyCFunction)File_HOpenDF, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SInt8 permission) -> (short refNum)")},
- {"HOpenRF", (PyCFunction)File_HOpenRF, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SInt8 permission) -> (short refNum)")},
- {"AllocContig", (PyCFunction)File_AllocContig, 1,
- PyDoc_STR("(short refNum) -> (long count)")},
- {"HCreate", (PyCFunction)File_HCreate, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, OSType creator, OSType fileType) -> None")},
- {"DirCreate", (PyCFunction)File_DirCreate, 1,
- PyDoc_STR("(short vRefNum, long parentDirID, Str255 directoryName) -> (long createdDirID)")},
- {"HDelete", (PyCFunction)File_HDelete, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
- {"HGetFInfo", (PyCFunction)File_HGetFInfo, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> (FInfo fndrInfo)")},
- {"HSetFInfo", (PyCFunction)File_HSetFInfo, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, FInfo fndrInfo) -> None")},
- {"HSetFLock", (PyCFunction)File_HSetFLock, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
- {"HRstFLock", (PyCFunction)File_HRstFLock, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
- {"HRename", (PyCFunction)File_HRename, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 oldName, Str255 newName) -> None")},
- {"CatMove", (PyCFunction)File_CatMove, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 oldName, long newDirID, Str255 newName) -> None")},
- {"FSMakeFSSpec", (PyCFunction)File_FSMakeFSSpec, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> (FSSpec spec)")},
+ {"UnmountVol", (PyCFunction)File_UnmountVol, 1,
+ PyDoc_STR("(Str63 volName, short vRefNum) -> None")},
+ {"FlushVol", (PyCFunction)File_FlushVol, 1,
+ PyDoc_STR("(Str63 volName, short vRefNum) -> None")},
+ {"HSetVol", (PyCFunction)File_HSetVol, 1,
+ PyDoc_STR("(Str63 volName, short vRefNum, long dirID) -> None")},
+ {"FSClose", (PyCFunction)File_FSClose, 1,
+ PyDoc_STR("(short refNum) -> None")},
+ {"Allocate", (PyCFunction)File_Allocate, 1,
+ PyDoc_STR("(short refNum) -> (long count)")},
+ {"GetEOF", (PyCFunction)File_GetEOF, 1,
+ PyDoc_STR("(short refNum) -> (long logEOF)")},
+ {"SetEOF", (PyCFunction)File_SetEOF, 1,
+ PyDoc_STR("(short refNum, long logEOF) -> None")},
+ {"GetFPos", (PyCFunction)File_GetFPos, 1,
+ PyDoc_STR("(short refNum) -> (long filePos)")},
+ {"SetFPos", (PyCFunction)File_SetFPos, 1,
+ PyDoc_STR("(short refNum, short posMode, long posOff) -> None")},
+ {"GetVRefNum", (PyCFunction)File_GetVRefNum, 1,
+ PyDoc_STR("(short fileRefNum) -> (short vRefNum)")},
+ {"HGetVol", (PyCFunction)File_HGetVol, 1,
+ PyDoc_STR("(StringPtr volName) -> (short vRefNum, long dirID)")},
+ {"HOpen", (PyCFunction)File_HOpen, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SInt8 permission) -> (short refNum)")},
+ {"HOpenDF", (PyCFunction)File_HOpenDF, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SInt8 permission) -> (short refNum)")},
+ {"HOpenRF", (PyCFunction)File_HOpenRF, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SInt8 permission) -> (short refNum)")},
+ {"AllocContig", (PyCFunction)File_AllocContig, 1,
+ PyDoc_STR("(short refNum) -> (long count)")},
+ {"HCreate", (PyCFunction)File_HCreate, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, OSType creator, OSType fileType) -> None")},
+ {"DirCreate", (PyCFunction)File_DirCreate, 1,
+ PyDoc_STR("(short vRefNum, long parentDirID, Str255 directoryName) -> (long createdDirID)")},
+ {"HDelete", (PyCFunction)File_HDelete, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
+ {"HGetFInfo", (PyCFunction)File_HGetFInfo, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> (FInfo fndrInfo)")},
+ {"HSetFInfo", (PyCFunction)File_HSetFInfo, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, FInfo fndrInfo) -> None")},
+ {"HSetFLock", (PyCFunction)File_HSetFLock, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
+ {"HRstFLock", (PyCFunction)File_HRstFLock, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
+ {"HRename", (PyCFunction)File_HRename, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 oldName, Str255 newName) -> None")},
+ {"CatMove", (PyCFunction)File_CatMove, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 oldName, long newDirID, Str255 newName) -> None")},
+ {"FSMakeFSSpec", (PyCFunction)File_FSMakeFSSpec, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> (FSSpec spec)")},
#endif /* !__LP64__*/
- {"FSGetForkPosition", (PyCFunction)File_FSGetForkPosition, 1,
- PyDoc_STR("(SInt16 forkRefNum) -> (SInt64 position)")},
- {"FSSetForkPosition", (PyCFunction)File_FSSetForkPosition, 1,
- PyDoc_STR("(SInt16 forkRefNum, UInt16 positionMode, SInt64 positionOffset) -> None")},
- {"FSGetForkSize", (PyCFunction)File_FSGetForkSize, 1,
- PyDoc_STR("(SInt16 forkRefNum) -> (SInt64 forkSize)")},
- {"FSSetForkSize", (PyCFunction)File_FSSetForkSize, 1,
- PyDoc_STR("(SInt16 forkRefNum, UInt16 positionMode, SInt64 positionOffset) -> None")},
- {"FSAllocateFork", (PyCFunction)File_FSAllocateFork, 1,
- PyDoc_STR("(SInt16 forkRefNum, FSAllocationFlags flags, UInt16 positionMode, SInt64 positionOffset, UInt64 requestCount) -> (UInt64 actualCount)")},
- {"FSFlushFork", (PyCFunction)File_FSFlushFork, 1,
- PyDoc_STR("(SInt16 forkRefNum) -> None")},
- {"FSCloseFork", (PyCFunction)File_FSCloseFork, 1,
- PyDoc_STR("(SInt16 forkRefNum) -> None")},
- {"FSGetDataForkName", (PyCFunction)File_FSGetDataForkName, 1,
- PyDoc_STR("() -> (HFSUniStr255 dataForkName)")},
- {"FSGetResourceForkName", (PyCFunction)File_FSGetResourceForkName, 1,
- PyDoc_STR("() -> (HFSUniStr255 resourceForkName)")},
- {"FSPathMakeRef", (PyCFunction)File_FSPathMakeRef, 1,
- PyDoc_STR("(UInt8 * path) -> (FSRef ref, Boolean isDirectory)")},
- {"FNNotifyByPath", (PyCFunction)File_FNNotifyByPath, 1,
- PyDoc_STR("(UInt8 * path, FNMessage message, OptionBits flags) -> None")},
- {"FNNotifyAll", (PyCFunction)File_FNNotifyAll, 1,
- PyDoc_STR("(FNMessage message, OptionBits flags) -> None")},
+ {"FSGetForkPosition", (PyCFunction)File_FSGetForkPosition, 1,
+ PyDoc_STR("(SInt16 forkRefNum) -> (SInt64 position)")},
+ {"FSSetForkPosition", (PyCFunction)File_FSSetForkPosition, 1,
+ PyDoc_STR("(SInt16 forkRefNum, UInt16 positionMode, SInt64 positionOffset) -> None")},
+ {"FSGetForkSize", (PyCFunction)File_FSGetForkSize, 1,
+ PyDoc_STR("(SInt16 forkRefNum) -> (SInt64 forkSize)")},
+ {"FSSetForkSize", (PyCFunction)File_FSSetForkSize, 1,
+ PyDoc_STR("(SInt16 forkRefNum, UInt16 positionMode, SInt64 positionOffset) -> None")},
+ {"FSAllocateFork", (PyCFunction)File_FSAllocateFork, 1,
+ PyDoc_STR("(SInt16 forkRefNum, FSAllocationFlags flags, UInt16 positionMode, SInt64 positionOffset, UInt64 requestCount) -> (UInt64 actualCount)")},
+ {"FSFlushFork", (PyCFunction)File_FSFlushFork, 1,
+ PyDoc_STR("(SInt16 forkRefNum) -> None")},
+ {"FSCloseFork", (PyCFunction)File_FSCloseFork, 1,
+ PyDoc_STR("(SInt16 forkRefNum) -> None")},
+ {"FSGetDataForkName", (PyCFunction)File_FSGetDataForkName, 1,
+ PyDoc_STR("() -> (HFSUniStr255 dataForkName)")},
+ {"FSGetResourceForkName", (PyCFunction)File_FSGetResourceForkName, 1,
+ PyDoc_STR("() -> (HFSUniStr255 resourceForkName)")},
+ {"FSPathMakeRef", (PyCFunction)File_FSPathMakeRef, 1,
+ PyDoc_STR("(UInt8 * path) -> (FSRef ref, Boolean isDirectory)")},
+ {"FNNotifyByPath", (PyCFunction)File_FNNotifyByPath, 1,
+ PyDoc_STR("(UInt8 * path, FNMessage message, OptionBits flags) -> None")},
+ {"FNNotifyAll", (PyCFunction)File_FNNotifyAll, 1,
+ PyDoc_STR("(FNMessage message, OptionBits flags) -> None")},
#ifndef __LP64__
- {"NewAlias", (PyCFunction)File_NewAlias, 1,
- PyDoc_STR("(FSSpec fromFile, FSSpec target) -> (AliasHandle alias)")},
- {"NewAliasMinimalFromFullPath", (PyCFunction)File_NewAliasMinimalFromFullPath, 1,
- PyDoc_STR("(Buffer fullPath, Str32 zoneName, Str31 serverName) -> (AliasHandle alias)")},
- {"ResolveAliasFile", (PyCFunction)File_ResolveAliasFile, 1,
- PyDoc_STR("(FSSpec theSpec, Boolean resolveAliasChains) -> (FSSpec theSpec, Boolean targetIsFolder, Boolean wasAliased)")},
- {"ResolveAliasFileWithMountFlags", (PyCFunction)File_ResolveAliasFileWithMountFlags, 1,
- PyDoc_STR("(FSSpec theSpec, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSSpec theSpec, Boolean targetIsFolder, Boolean wasAliased)")},
- {"UpdateAlias", (PyCFunction)File_UpdateAlias, 1,
- PyDoc_STR("(FSSpec fromFile, FSSpec target, AliasHandle alias) -> (Boolean wasChanged)")},
- {"ResolveAliasFileWithMountFlagsNoUI", (PyCFunction)File_ResolveAliasFileWithMountFlagsNoUI, 1,
- PyDoc_STR("(FSSpec theSpec, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSSpec theSpec, Boolean targetIsFolder, Boolean wasAliased)")},
+ {"NewAlias", (PyCFunction)File_NewAlias, 1,
+ PyDoc_STR("(FSSpec fromFile, FSSpec target) -> (AliasHandle alias)")},
+ {"NewAliasMinimalFromFullPath", (PyCFunction)File_NewAliasMinimalFromFullPath, 1,
+ PyDoc_STR("(Buffer fullPath, Str32 zoneName, Str31 serverName) -> (AliasHandle alias)")},
+ {"ResolveAliasFile", (PyCFunction)File_ResolveAliasFile, 1,
+ PyDoc_STR("(FSSpec theSpec, Boolean resolveAliasChains) -> (FSSpec theSpec, Boolean targetIsFolder, Boolean wasAliased)")},
+ {"ResolveAliasFileWithMountFlags", (PyCFunction)File_ResolveAliasFileWithMountFlags, 1,
+ PyDoc_STR("(FSSpec theSpec, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSSpec theSpec, Boolean targetIsFolder, Boolean wasAliased)")},
+ {"UpdateAlias", (PyCFunction)File_UpdateAlias, 1,
+ PyDoc_STR("(FSSpec fromFile, FSSpec target, AliasHandle alias) -> (Boolean wasChanged)")},
+ {"ResolveAliasFileWithMountFlagsNoUI", (PyCFunction)File_ResolveAliasFileWithMountFlagsNoUI, 1,
+ PyDoc_STR("(FSSpec theSpec, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSSpec theSpec, Boolean targetIsFolder, Boolean wasAliased)")},
#endif /* !__LP64__ */
- {"FSNewAlias", (PyCFunction)File_FSNewAlias, 1,
- PyDoc_STR("(FSRef fromFile, FSRef target) -> (AliasHandle inAlias)")},
- {"FSResolveAliasFileWithMountFlags", (PyCFunction)File_FSResolveAliasFileWithMountFlags, 1,
- PyDoc_STR("(FSRef theRef, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")},
- {"FSResolveAliasFile", (PyCFunction)File_FSResolveAliasFile, 1,
- PyDoc_STR("(FSRef theRef, Boolean resolveAliasChains) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")},
- {"FSUpdateAlias", (PyCFunction)File_FSUpdateAlias, 1,
- PyDoc_STR("(FSRef fromFile, FSRef target, AliasHandle alias) -> (Boolean wasChanged)")},
- {"pathname", (PyCFunction)File_pathname, 1,
- PyDoc_STR("(str|unicode|FSSpec|FSref) -> pathname")},
- {NULL, NULL, 0}
+ {"FSNewAlias", (PyCFunction)File_FSNewAlias, 1,
+ PyDoc_STR("(FSRef fromFile, FSRef target) -> (AliasHandle inAlias)")},
+ {"FSResolveAliasFileWithMountFlags", (PyCFunction)File_FSResolveAliasFileWithMountFlags, 1,
+ PyDoc_STR("(FSRef theRef, Boolean resolveAliasChains, unsigned long mountFlags) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")},
+ {"FSResolveAliasFile", (PyCFunction)File_FSResolveAliasFile, 1,
+ PyDoc_STR("(FSRef theRef, Boolean resolveAliasChains) -> (FSRef theRef, Boolean targetIsFolder, Boolean wasAliased)")},
+ {"FSUpdateAlias", (PyCFunction)File_FSUpdateAlias, 1,
+ PyDoc_STR("(FSRef fromFile, FSRef target, AliasHandle alias) -> (Boolean wasChanged)")},
+ {"pathname", (PyCFunction)File_pathname, 1,
+ PyDoc_STR("(str|unicode|FSSpec|FSref) -> pathname")},
+ {NULL, NULL, 0}
};
@@ -3251,159 +3251,159 @@ static PyMethodDef File_methods[] = {
int
PyMac_GetFSSpec(PyObject *v, FSSpec *spec)
{
- Str255 path;
- short refnum;
- long parid;
- OSErr err;
- FSRef fsr;
-
- if (FSSpec_Check(v)) {
- *spec = ((FSSpecObject *)v)->ob_itself;
- return 1;
- }
-
- if (PyArg_Parse(v, "(hlO&)",
- &refnum, &parid, PyMac_GetStr255, &path)) {
- err = FSMakeFSSpec(refnum, parid, path, spec);
- if ( err && err != fnfErr ) {
- PyMac_Error(err);
- return 0;
- }
- return 1;
+ Str255 path;
+ short refnum;
+ long parid;
+ OSErr err;
+ FSRef fsr;
+
+ if (FSSpec_Check(v)) {
+ *spec = ((FSSpecObject *)v)->ob_itself;
+ return 1;
+ }
+
+ if (PyArg_Parse(v, "(hlO&)",
+ &refnum, &parid, PyMac_GetStr255, &path)) {
+ err = FSMakeFSSpec(refnum, parid, path, spec);
+ if ( err && err != fnfErr ) {
+ PyMac_Error(err);
+ return 0;
}
- PyErr_Clear();
- /* Otherwise we try to go via an FSRef. On OSX we go all the way,
- ** on OS9 we accept only a real FSRef object
- */
- if ( PyMac_GetFSRef(v, &fsr) ) {
- err = FSGetCatalogInfo(&fsr, kFSCatInfoNone, NULL, NULL, spec, NULL);
- if (err != noErr) {
- PyMac_Error(err);
- return 0;
- }
- return 1;
+ return 1;
+ }
+ PyErr_Clear();
+ /* Otherwise we try to go via an FSRef. On OSX we go all the way,
+ ** on OS9 we accept only a real FSRef object
+ */
+ if ( PyMac_GetFSRef(v, &fsr) ) {
+ err = FSGetCatalogInfo(&fsr, kFSCatInfoNone, NULL, NULL, spec, NULL);
+ if (err != noErr) {
+ PyMac_Error(err);
+ return 0;
}
- return 0;
+ return 1;
+ }
+ return 0;
}
#endif /* !__LP64__ */
int
PyMac_GetFSRef(PyObject *v, FSRef *fsr)
{
- OSStatus err;
+ OSStatus err;
#ifndef __LP64__
- FSSpec fss;
+ FSSpec fss;
#endif /* !__LP64__ */
- if (FSRef_Check(v)) {
- *fsr = ((FSRefObject *)v)->ob_itself;
- return 1;
- }
-
- /* On OSX we now try a pathname */
- if ( PyString_Check(v) || PyUnicode_Check(v)) {
- char *path = NULL;
- if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path))
- return 0;
- if ( (err=FSPathMakeRef((unsigned char*)path, fsr, NULL)) )
- PyMac_Error(err);
- PyMem_Free(path);
- return !err;
- }
- /* XXXX Should try unicode here too */
+ if (FSRef_Check(v)) {
+ *fsr = ((FSRefObject *)v)->ob_itself;
+ return 1;
+ }
+
+ /* On OSX we now try a pathname */
+ if ( PyString_Check(v) || PyUnicode_Check(v)) {
+ char *path = NULL;
+ if (!PyArg_Parse(v, "et", Py_FileSystemDefaultEncoding, &path))
+ return 0;
+ if ( (err=FSPathMakeRef((unsigned char*)path, fsr, NULL)) )
+ PyMac_Error(err);
+ PyMem_Free(path);
+ return !err;
+ }
+ /* XXXX Should try unicode here too */
#ifndef __LP64__
- /* Otherwise we try to go via an FSSpec */
- if (FSSpec_Check(v)) {
- fss = ((FSSpecObject *)v)->ob_itself;
- if ((err=FSpMakeFSRef(&fss, fsr)) == 0)
- return 1;
- PyMac_Error(err);
- return 0;
- }
+ /* Otherwise we try to go via an FSSpec */
+ if (FSSpec_Check(v)) {
+ fss = ((FSSpecObject *)v)->ob_itself;
+ if ((err=FSpMakeFSRef(&fss, fsr)) == 0)
+ return 1;
+ PyMac_Error(err);
+ return 0;
+ }
#endif /* !__LP64__ */
- PyErr_SetString(PyExc_TypeError, "FSRef, FSSpec or pathname required");
- return 0;
+ PyErr_SetString(PyExc_TypeError, "FSRef, FSSpec or pathname required");
+ return 0;
}
#ifndef __LP64__
extern PyObject *
PyMac_BuildFSSpec(FSSpec *spec)
{
- return FSSpec_New(spec);
+ return FSSpec_New(spec);
}
#endif /* !__LP64__ */
extern PyObject *
PyMac_BuildFSRef(FSRef *spec)
{
- return FSRef_New(spec);
+ return FSRef_New(spec);
}
void init_File(void)
{
- PyObject *m;
- PyObject *d;
+ PyObject *m;
+ PyObject *d;
#ifndef __LP64__
- PyMac_INIT_TOOLBOX_OBJECT_NEW(FSSpec *, PyMac_BuildFSSpec);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSSpec, PyMac_GetFSSpec);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(FSSpec *, PyMac_BuildFSSpec);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSSpec, PyMac_GetFSSpec);
#endif /* !__LP64__ */
- PyMac_INIT_TOOLBOX_OBJECT_NEW(FSRef *, PyMac_BuildFSRef);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSRef, PyMac_GetFSRef);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(FSRef *, PyMac_BuildFSRef);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(FSRef, PyMac_GetFSRef);
- m = Py_InitModule("_File", File_methods);
- d = PyModule_GetDict(m);
- File_Error = PyMac_GetOSErrException();
- if (File_Error == NULL ||
- PyDict_SetItemString(d, "Error", File_Error) != 0)
- return;
- FSCatalogInfo_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&FSCatalogInfo_Type) < 0) return;
- Py_INCREF(&FSCatalogInfo_Type);
- PyModule_AddObject(m, "FSCatalogInfo", (PyObject *)&FSCatalogInfo_Type);
- /* Backward-compatible name */
- Py_INCREF(&FSCatalogInfo_Type);
- PyModule_AddObject(m, "FSCatalogInfoType", (PyObject *)&FSCatalogInfo_Type);
+ m = Py_InitModule("_File", File_methods);
+ d = PyModule_GetDict(m);
+ File_Error = PyMac_GetOSErrException();
+ if (File_Error == NULL ||
+ PyDict_SetItemString(d, "Error", File_Error) != 0)
+ return;
+ FSCatalogInfo_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&FSCatalogInfo_Type) < 0) return;
+ Py_INCREF(&FSCatalogInfo_Type);
+ PyModule_AddObject(m, "FSCatalogInfo", (PyObject *)&FSCatalogInfo_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&FSCatalogInfo_Type);
+ PyModule_AddObject(m, "FSCatalogInfoType", (PyObject *)&FSCatalogInfo_Type);
#ifndef __LP64__
- FInfo_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&FInfo_Type) < 0) return;
- Py_INCREF(&FInfo_Type);
- PyModule_AddObject(m, "FInfo", (PyObject *)&FInfo_Type);
- /* Backward-compatible name */
- Py_INCREF(&FInfo_Type);
- PyModule_AddObject(m, "FInfoType", (PyObject *)&FInfo_Type);
+ FInfo_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&FInfo_Type) < 0) return;
+ Py_INCREF(&FInfo_Type);
+ PyModule_AddObject(m, "FInfo", (PyObject *)&FInfo_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&FInfo_Type);
+ PyModule_AddObject(m, "FInfoType", (PyObject *)&FInfo_Type);
#endif /* !__LP64__ */
- Alias_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Alias_Type) < 0) return;
- Py_INCREF(&Alias_Type);
- PyModule_AddObject(m, "Alias", (PyObject *)&Alias_Type);
- /* Backward-compatible name */
- Py_INCREF(&Alias_Type);
- PyModule_AddObject(m, "AliasType", (PyObject *)&Alias_Type);
+ Alias_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Alias_Type) < 0) return;
+ Py_INCREF(&Alias_Type);
+ PyModule_AddObject(m, "Alias", (PyObject *)&Alias_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Alias_Type);
+ PyModule_AddObject(m, "AliasType", (PyObject *)&Alias_Type);
#ifndef __LP64__
- FSSpec_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&FSSpec_Type) < 0) return;
- Py_INCREF(&FSSpec_Type);
- PyModule_AddObject(m, "FSSpec", (PyObject *)&FSSpec_Type);
- /* Backward-compatible name */
- Py_INCREF(&FSSpec_Type);
- PyModule_AddObject(m, "FSSpecType", (PyObject *)&FSSpec_Type);
+ FSSpec_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&FSSpec_Type) < 0) return;
+ Py_INCREF(&FSSpec_Type);
+ PyModule_AddObject(m, "FSSpec", (PyObject *)&FSSpec_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&FSSpec_Type);
+ PyModule_AddObject(m, "FSSpecType", (PyObject *)&FSSpec_Type);
#endif /* !__LP64__ */
- FSRef_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&FSRef_Type) < 0) return;
- Py_INCREF(&FSRef_Type);
- PyModule_AddObject(m, "FSRef", (PyObject *)&FSRef_Type);
- /* Backward-compatible name */
- Py_INCREF(&FSRef_Type);
- PyModule_AddObject(m, "FSRefType", (PyObject *)&FSRef_Type);
+ FSRef_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&FSRef_Type) < 0) return;
+ Py_INCREF(&FSRef_Type);
+ PyModule_AddObject(m, "FSRef", (PyObject *)&FSRef_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&FSRef_Type);
+ PyModule_AddObject(m, "FSRefType", (PyObject *)&FSRef_Type);
}
/* ======================== End module _File ======================== */
diff --git a/Mac/Modules/fm/_Fmmodule.c b/Mac/Modules/fm/_Fmmodule.c
index b982cc3..adc47aa 100644
--- a/Mac/Modules/fm/_Fmmodule.c
+++ b/Mac/Modules/fm/_Fmmodule.c
@@ -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__ */
}
diff --git a/Mac/Modules/folder/_Foldermodule.c b/Mac/Modules/folder/_Foldermodule.c
index 035dab8..10597f5 100644
--- a/Mac/Modules/folder/_Foldermodule.c
+++ b/Mac/Modules/folder/_Foldermodule.c
@@ -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 ======================= */
diff --git a/Mac/Modules/gestaltmodule.c b/Mac/Modules/gestaltmodule.c
index fa1c93c..56757ab 100644
--- a/Mac/Modules/gestaltmodule.c
+++ b/Mac/Modules/gestaltmodule.c
@@ -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);
}
diff --git a/Mac/Modules/help/_Helpmodule.c b/Mac/Modules/help/_Helpmodule.c
index a6eccf3..eaa2e8a 100644
--- a/Mac/Modules/help/_Helpmodule.c
+++ b/Mac/Modules/help/_Helpmodule.c
@@ -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__ */
}
diff --git a/Mac/Modules/ibcarbon/_IBCarbon.c b/Mac/Modules/ibcarbon/_IBCarbon.c
index c7c819c..2a65f42 100644
--- a/Mac/Modules/ibcarbon/_IBCarbon.c
+++ b/Mac/Modules/ibcarbon/_IBCarbon.c
@@ -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};
-
- 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;
+ 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;
}
#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__ */
}
diff --git a/Mac/Modules/icgluemodule.c b/Mac/Modules/icgluemodule.c
index 70ca1e3..4d17bf7 100644
--- a/Mac/Modules/icgluemodule.c
+++ b/Mac/Modules/icgluemodule.c
@@ -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;
-
- 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;
+ 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;
}
-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*/
-
- /* Space for future expansion */
- 0L,0L,0L,0L,
- Icitype__doc__ /* Documentation string */
+ 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 */
};
/* 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;
-
- /* Create the module and add the functions */
- m = Py_InitModule4("icglue", ic_methods,
- icglue_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
-
- /* 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");
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("In 3.x, the icglue module is removed.", 1))
+ return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule4("icglue", ic_methods,
+ icglue_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
+
+ /* 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");
}
diff --git a/Mac/Modules/icn/_Icnmodule.c b/Mac/Modules/icn/_Icnmodule.c
index 80201a2..6967ae4 100644
--- a/Mac/Modules/icn/_Icnmodule.c
+++ b/Mac/Modules/icn/_Icnmodule.c
@@ -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,1561 +23,1561 @@ static PyObject *Icn_Error;
static PyObject *Icn_GetCIcon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CIconHandle _rv;
- SInt16 iconID;
+ PyObject *_res = NULL;
+ CIconHandle _rv;
+ SInt16 iconID;
#ifndef GetCIcon
- PyMac_PRECHECK(GetCIcon);
+ PyMac_PRECHECK(GetCIcon);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &iconID))
- return NULL;
- _rv = GetCIcon(iconID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &iconID))
+ return NULL;
+ _rv = GetCIcon(iconID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Icn_PlotCIcon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect theRect;
- CIconHandle theIcon;
+ PyObject *_res = NULL;
+ Rect theRect;
+ CIconHandle theIcon;
#ifndef PlotCIcon
- PyMac_PRECHECK(PlotCIcon);
+ PyMac_PRECHECK(PlotCIcon);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &theRect,
- ResObj_Convert, &theIcon))
- return NULL;
- PlotCIcon(&theRect,
- theIcon);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &theRect,
+ ResObj_Convert, &theIcon))
+ return NULL;
+ PlotCIcon(&theRect,
+ theIcon);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_DisposeCIcon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CIconHandle theIcon;
+ PyObject *_res = NULL;
+ CIconHandle theIcon;
#ifndef DisposeCIcon
- PyMac_PRECHECK(DisposeCIcon);
+ PyMac_PRECHECK(DisposeCIcon);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIcon))
- return NULL;
- DisposeCIcon(theIcon);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIcon))
+ return NULL;
+ DisposeCIcon(theIcon);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetIcon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- SInt16 iconID;
+ PyObject *_res = NULL;
+ Handle _rv;
+ SInt16 iconID;
#ifndef GetIcon
- PyMac_PRECHECK(GetIcon);
+ PyMac_PRECHECK(GetIcon);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &iconID))
- return NULL;
- _rv = GetIcon(iconID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &iconID))
+ return NULL;
+ _rv = GetIcon(iconID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Icn_PlotIcon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect theRect;
- Handle theIcon;
+ PyObject *_res = NULL;
+ Rect theRect;
+ Handle theIcon;
#ifndef PlotIcon
- PyMac_PRECHECK(PlotIcon);
+ PyMac_PRECHECK(PlotIcon);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &theRect,
- ResObj_Convert, &theIcon))
- return NULL;
- PlotIcon(&theRect,
- theIcon);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &theRect,
+ ResObj_Convert, &theIcon))
+ return NULL;
+ PlotIcon(&theRect,
+ theIcon);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_PlotIconID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- SInt16 theResID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ SInt16 theResID;
#ifndef PlotIconID
- PyMac_PRECHECK(PlotIconID);
+ PyMac_PRECHECK(PlotIconID);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhh",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- &theResID))
- return NULL;
- _err = PlotIconID(&theRect,
- align,
- transform,
- theResID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhh",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ &theResID))
+ return NULL;
+ _err = PlotIconID(&theRect,
+ align,
+ transform,
+ theResID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_NewIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconSuiteRef theIconSuite;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconSuiteRef theIconSuite;
#ifndef NewIconSuite
- PyMac_PRECHECK(NewIconSuite);
+ PyMac_PRECHECK(NewIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = NewIconSuite(&theIconSuite);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconSuite);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = NewIconSuite(&theIconSuite);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconSuite);
+ return _res;
}
static PyObject *Icn_AddIconToSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle theIconData;
- IconSuiteRef theSuite;
- ResType theType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle theIconData;
+ IconSuiteRef theSuite;
+ ResType theType;
#ifndef AddIconToSuite
- PyMac_PRECHECK(AddIconToSuite);
+ PyMac_PRECHECK(AddIconToSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &theIconData,
- ResObj_Convert, &theSuite,
- PyMac_GetOSType, &theType))
- return NULL;
- _err = AddIconToSuite(theIconData,
- theSuite,
- theType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &theIconData,
+ ResObj_Convert, &theSuite,
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _err = AddIconToSuite(theIconData,
+ theSuite,
+ theType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetIconFromSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle theIconData;
- IconSuiteRef theSuite;
- ResType theType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle theIconData;
+ IconSuiteRef theSuite;
+ ResType theType;
#ifndef GetIconFromSuite
- PyMac_PRECHECK(GetIconFromSuite);
+ PyMac_PRECHECK(GetIconFromSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &theSuite,
- PyMac_GetOSType, &theType))
- return NULL;
- _err = GetIconFromSuite(&theIconData,
- theSuite,
- theType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconData);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &theSuite,
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _err = GetIconFromSuite(&theIconData,
+ theSuite,
+ theType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconData);
+ return _res;
}
static PyObject *Icn_GetIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconSuiteRef theIconSuite;
- SInt16 theResID;
- IconSelectorValue selector;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconSuiteRef theIconSuite;
+ SInt16 theResID;
+ IconSelectorValue selector;
#ifndef GetIconSuite
- PyMac_PRECHECK(GetIconSuite);
+ PyMac_PRECHECK(GetIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &theResID,
- &selector))
- return NULL;
- _err = GetIconSuite(&theIconSuite,
- theResID,
- selector);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconSuite);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &theResID,
+ &selector))
+ return NULL;
+ _err = GetIconSuite(&theIconSuite,
+ theResID,
+ selector);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconSuite);
+ return _res;
}
static PyObject *Icn_DisposeIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconSuiteRef theIconSuite;
- Boolean disposeData;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconSuiteRef theIconSuite;
+ Boolean disposeData;
#ifndef DisposeIconSuite
- PyMac_PRECHECK(DisposeIconSuite);
+ PyMac_PRECHECK(DisposeIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- ResObj_Convert, &theIconSuite,
- &disposeData))
- return NULL;
- _err = DisposeIconSuite(theIconSuite,
- disposeData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ ResObj_Convert, &theIconSuite,
+ &disposeData))
+ return NULL;
+ _err = DisposeIconSuite(theIconSuite,
+ disposeData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_PlotIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- IconSuiteRef theIconSuite;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ IconSuiteRef theIconSuite;
#ifndef PlotIconSuite
- PyMac_PRECHECK(PlotIconSuite);
+ PyMac_PRECHECK(PlotIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- ResObj_Convert, &theIconSuite))
- return NULL;
- _err = PlotIconSuite(&theRect,
- align,
- transform,
- theIconSuite);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ ResObj_Convert, &theIconSuite))
+ return NULL;
+ _err = PlotIconSuite(&theRect,
+ align,
+ transform,
+ theIconSuite);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_LoadIconCache(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- IconCacheRef theIconCache;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ IconCacheRef theIconCache;
#ifndef LoadIconCache
- PyMac_PRECHECK(LoadIconCache);
+ PyMac_PRECHECK(LoadIconCache);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- ResObj_Convert, &theIconCache))
- return NULL;
- _err = LoadIconCache(&theRect,
- align,
- transform,
- theIconCache);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ ResObj_Convert, &theIconCache))
+ return NULL;
+ _err = LoadIconCache(&theRect,
+ align,
+ transform,
+ theIconCache);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetLabel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 labelNumber;
- RGBColor labelColor;
- Str255 labelString;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 labelNumber;
+ RGBColor labelColor;
+ Str255 labelString;
#ifndef GetLabel
- PyMac_PRECHECK(GetLabel);
+ PyMac_PRECHECK(GetLabel);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &labelNumber,
- PyMac_GetStr255, labelString))
- return NULL;
- _err = GetLabel(labelNumber,
- &labelColor,
- labelString);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- QdRGB_New, &labelColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &labelNumber,
+ PyMac_GetStr255, labelString))
+ return NULL;
+ _err = GetLabel(labelNumber,
+ &labelColor,
+ labelString);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &labelColor);
+ return _res;
}
static PyObject *Icn_PtInIconID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point testPt;
- Rect iconRect;
- IconAlignmentType align;
- SInt16 iconID;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point testPt;
+ Rect iconRect;
+ IconAlignmentType align;
+ SInt16 iconID;
#ifndef PtInIconID
- PyMac_PRECHECK(PtInIconID);
+ PyMac_PRECHECK(PtInIconID);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hh",
- PyMac_GetPoint, &testPt,
- PyMac_GetRect, &iconRect,
- &align,
- &iconID))
- return NULL;
- _rv = PtInIconID(testPt,
- &iconRect,
- align,
- iconID);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hh",
+ PyMac_GetPoint, &testPt,
+ PyMac_GetRect, &iconRect,
+ &align,
+ &iconID))
+ return NULL;
+ _rv = PtInIconID(testPt,
+ &iconRect,
+ align,
+ iconID);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_PtInIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point testPt;
- Rect iconRect;
- IconAlignmentType align;
- IconSuiteRef theIconSuite;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point testPt;
+ Rect iconRect;
+ IconAlignmentType align;
+ IconSuiteRef theIconSuite;
#ifndef PtInIconSuite
- PyMac_PRECHECK(PtInIconSuite);
+ PyMac_PRECHECK(PtInIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hO&",
- PyMac_GetPoint, &testPt,
- PyMac_GetRect, &iconRect,
- &align,
- ResObj_Convert, &theIconSuite))
- return NULL;
- _rv = PtInIconSuite(testPt,
- &iconRect,
- align,
- theIconSuite);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hO&",
+ PyMac_GetPoint, &testPt,
+ PyMac_GetRect, &iconRect,
+ &align,
+ ResObj_Convert, &theIconSuite))
+ return NULL;
+ _rv = PtInIconSuite(testPt,
+ &iconRect,
+ align,
+ theIconSuite);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_RectInIconID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect testRect;
- Rect iconRect;
- IconAlignmentType align;
- SInt16 iconID;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect testRect;
+ Rect iconRect;
+ IconAlignmentType align;
+ SInt16 iconID;
#ifndef RectInIconID
- PyMac_PRECHECK(RectInIconID);
+ PyMac_PRECHECK(RectInIconID);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hh",
- PyMac_GetRect, &testRect,
- PyMac_GetRect, &iconRect,
- &align,
- &iconID))
- return NULL;
- _rv = RectInIconID(&testRect,
- &iconRect,
- align,
- iconID);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hh",
+ PyMac_GetRect, &testRect,
+ PyMac_GetRect, &iconRect,
+ &align,
+ &iconID))
+ return NULL;
+ _rv = RectInIconID(&testRect,
+ &iconRect,
+ align,
+ iconID);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_RectInIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect testRect;
- Rect iconRect;
- IconAlignmentType align;
- IconSuiteRef theIconSuite;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect testRect;
+ Rect iconRect;
+ IconAlignmentType align;
+ IconSuiteRef theIconSuite;
#ifndef RectInIconSuite
- PyMac_PRECHECK(RectInIconSuite);
+ PyMac_PRECHECK(RectInIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hO&",
- PyMac_GetRect, &testRect,
- PyMac_GetRect, &iconRect,
- &align,
- ResObj_Convert, &theIconSuite))
- return NULL;
- _rv = RectInIconSuite(&testRect,
- &iconRect,
- align,
- theIconSuite);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hO&",
+ PyMac_GetRect, &testRect,
+ PyMac_GetRect, &iconRect,
+ &align,
+ ResObj_Convert, &theIconSuite))
+ return NULL;
+ _rv = RectInIconSuite(&testRect,
+ &iconRect,
+ align,
+ theIconSuite);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_IconIDToRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle theRgn;
- Rect iconRect;
- IconAlignmentType align;
- SInt16 iconID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle theRgn;
+ Rect iconRect;
+ IconAlignmentType align;
+ SInt16 iconID;
#ifndef IconIDToRgn
- PyMac_PRECHECK(IconIDToRgn);
+ PyMac_PRECHECK(IconIDToRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hh",
- ResObj_Convert, &theRgn,
- PyMac_GetRect, &iconRect,
- &align,
- &iconID))
- return NULL;
- _err = IconIDToRgn(theRgn,
- &iconRect,
- align,
- iconID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hh",
+ ResObj_Convert, &theRgn,
+ PyMac_GetRect, &iconRect,
+ &align,
+ &iconID))
+ return NULL;
+ _err = IconIDToRgn(theRgn,
+ &iconRect,
+ align,
+ iconID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_IconSuiteToRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle theRgn;
- Rect iconRect;
- IconAlignmentType align;
- IconSuiteRef theIconSuite;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle theRgn;
+ Rect iconRect;
+ IconAlignmentType align;
+ IconSuiteRef theIconSuite;
#ifndef IconSuiteToRgn
- PyMac_PRECHECK(IconSuiteToRgn);
+ PyMac_PRECHECK(IconSuiteToRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hO&",
- ResObj_Convert, &theRgn,
- PyMac_GetRect, &iconRect,
- &align,
- ResObj_Convert, &theIconSuite))
- return NULL;
- _err = IconSuiteToRgn(theRgn,
- &iconRect,
- align,
- theIconSuite);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hO&",
+ ResObj_Convert, &theRgn,
+ PyMac_GetRect, &iconRect,
+ &align,
+ ResObj_Convert, &theIconSuite))
+ return NULL;
+ _err = IconSuiteToRgn(theRgn,
+ &iconRect,
+ align,
+ theIconSuite);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_SetSuiteLabel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconSuiteRef theSuite;
- SInt16 theLabel;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconSuiteRef theSuite;
+ SInt16 theLabel;
#ifndef SetSuiteLabel
- PyMac_PRECHECK(SetSuiteLabel);
+ PyMac_PRECHECK(SetSuiteLabel);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- ResObj_Convert, &theSuite,
- &theLabel))
- return NULL;
- _err = SetSuiteLabel(theSuite,
- theLabel);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ ResObj_Convert, &theSuite,
+ &theLabel))
+ return NULL;
+ _err = SetSuiteLabel(theSuite,
+ theLabel);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetSuiteLabel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
- IconSuiteRef theSuite;
+ PyObject *_res = NULL;
+ SInt16 _rv;
+ IconSuiteRef theSuite;
#ifndef GetSuiteLabel
- PyMac_PRECHECK(GetSuiteLabel);
+ PyMac_PRECHECK(GetSuiteLabel);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theSuite))
- return NULL;
- _rv = GetSuiteLabel(theSuite);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theSuite))
+ return NULL;
+ _rv = GetSuiteLabel(theSuite);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Icn_PlotIconHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- Handle theIcon;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ Handle theIcon;
#ifndef PlotIconHandle
- PyMac_PRECHECK(PlotIconHandle);
+ PyMac_PRECHECK(PlotIconHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- ResObj_Convert, &theIcon))
- return NULL;
- _err = PlotIconHandle(&theRect,
- align,
- transform,
- theIcon);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ ResObj_Convert, &theIcon))
+ return NULL;
+ _err = PlotIconHandle(&theRect,
+ align,
+ transform,
+ theIcon);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_PlotSICNHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- Handle theSICN;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ Handle theSICN;
#ifndef PlotSICNHandle
- PyMac_PRECHECK(PlotSICNHandle);
+ PyMac_PRECHECK(PlotSICNHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- ResObj_Convert, &theSICN))
- return NULL;
- _err = PlotSICNHandle(&theRect,
- align,
- transform,
- theSICN);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ ResObj_Convert, &theSICN))
+ return NULL;
+ _err = PlotSICNHandle(&theRect,
+ align,
+ transform,
+ theSICN);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_PlotCIconHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- CIconHandle theCIcon;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ CIconHandle theCIcon;
#ifndef PlotCIconHandle
- PyMac_PRECHECK(PlotCIconHandle);
+ PyMac_PRECHECK(PlotCIconHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- ResObj_Convert, &theCIcon))
- return NULL;
- _err = PlotCIconHandle(&theRect,
- align,
- transform,
- theCIcon);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ ResObj_Convert, &theCIcon))
+ return NULL;
+ _err = PlotCIconHandle(&theRect,
+ align,
+ transform,
+ theCIcon);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_IconRefToIconFamily(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
- IconSelectorValue whichIcons;
- IconFamilyHandle iconFamily;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
+ IconSelectorValue whichIcons;
+ IconFamilyHandle iconFamily;
#ifndef IconRefToIconFamily
- PyMac_PRECHECK(IconRefToIconFamily);
+ PyMac_PRECHECK(IconRefToIconFamily);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- ResObj_Convert, &theIconRef,
- &whichIcons))
- return NULL;
- _err = IconRefToIconFamily(theIconRef,
- whichIcons,
- &iconFamily);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, iconFamily);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ResObj_Convert, &theIconRef,
+ &whichIcons))
+ return NULL;
+ _err = IconRefToIconFamily(theIconRef,
+ whichIcons,
+ &iconFamily);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, iconFamily);
+ return _res;
}
static PyObject *Icn_IconFamilyToIconSuite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconFamilyHandle iconFamily;
- IconSelectorValue whichIcons;
- IconSuiteRef iconSuite;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconFamilyHandle iconFamily;
+ IconSelectorValue whichIcons;
+ IconSuiteRef iconSuite;
#ifndef IconFamilyToIconSuite
- PyMac_PRECHECK(IconFamilyToIconSuite);
+ PyMac_PRECHECK(IconFamilyToIconSuite);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- ResObj_Convert, &iconFamily,
- &whichIcons))
- return NULL;
- _err = IconFamilyToIconSuite(iconFamily,
- whichIcons,
- &iconSuite);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, iconSuite);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ResObj_Convert, &iconFamily,
+ &whichIcons))
+ return NULL;
+ _err = IconFamilyToIconSuite(iconFamily,
+ whichIcons,
+ &iconSuite);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, iconSuite);
+ return _res;
}
static PyObject *Icn_IconSuiteToIconFamily(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconSuiteRef iconSuite;
- IconSelectorValue whichIcons;
- IconFamilyHandle iconFamily;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconSuiteRef iconSuite;
+ IconSelectorValue whichIcons;
+ IconFamilyHandle iconFamily;
#ifndef IconSuiteToIconFamily
- PyMac_PRECHECK(IconSuiteToIconFamily);
+ PyMac_PRECHECK(IconSuiteToIconFamily);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- ResObj_Convert, &iconSuite,
- &whichIcons))
- return NULL;
- _err = IconSuiteToIconFamily(iconSuite,
- whichIcons,
- &iconFamily);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, iconFamily);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ResObj_Convert, &iconSuite,
+ &whichIcons))
+ return NULL;
+ _err = IconSuiteToIconFamily(iconSuite,
+ whichIcons,
+ &iconFamily);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, iconFamily);
+ return _res;
}
static PyObject *Icn_SetIconFamilyData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconFamilyHandle iconFamily;
- OSType iconType;
- Handle h;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconFamilyHandle iconFamily;
+ OSType iconType;
+ Handle h;
#ifndef SetIconFamilyData
- PyMac_PRECHECK(SetIconFamilyData);
+ PyMac_PRECHECK(SetIconFamilyData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &iconFamily,
- PyMac_GetOSType, &iconType,
- ResObj_Convert, &h))
- return NULL;
- _err = SetIconFamilyData(iconFamily,
- iconType,
- h);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &iconFamily,
+ PyMac_GetOSType, &iconType,
+ ResObj_Convert, &h))
+ return NULL;
+ _err = SetIconFamilyData(iconFamily,
+ iconType,
+ h);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetIconFamilyData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconFamilyHandle iconFamily;
- OSType iconType;
- Handle h;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconFamilyHandle iconFamily;
+ OSType iconType;
+ Handle h;
#ifndef GetIconFamilyData
- PyMac_PRECHECK(GetIconFamilyData);
+ PyMac_PRECHECK(GetIconFamilyData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &iconFamily,
- PyMac_GetOSType, &iconType,
- ResObj_Convert, &h))
- return NULL;
- _err = GetIconFamilyData(iconFamily,
- iconType,
- h);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &iconFamily,
+ PyMac_GetOSType, &iconType,
+ ResObj_Convert, &h))
+ return NULL;
+ _err = GetIconFamilyData(iconFamily,
+ iconType,
+ h);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetIconRefOwners(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
- UInt16 owners;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
+ UInt16 owners;
#ifndef GetIconRefOwners
- PyMac_PRECHECK(GetIconRefOwners);
+ PyMac_PRECHECK(GetIconRefOwners);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = GetIconRefOwners(theIconRef,
- &owners);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- owners);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = GetIconRefOwners(theIconRef,
+ &owners);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ owners);
+ return _res;
}
static PyObject *Icn_AcquireIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
#ifndef AcquireIconRef
- PyMac_PRECHECK(AcquireIconRef);
+ PyMac_PRECHECK(AcquireIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = AcquireIconRef(theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = AcquireIconRef(theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_ReleaseIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
#ifndef ReleaseIconRef
- PyMac_PRECHECK(ReleaseIconRef);
+ PyMac_PRECHECK(ReleaseIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = ReleaseIconRef(theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = ReleaseIconRef(theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetIconRefFromFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec theFile;
- IconRef theIconRef;
- SInt16 theLabel;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec theFile;
+ IconRef theIconRef;
+ SInt16 theLabel;
#ifndef GetIconRefFromFile
- PyMac_PRECHECK(GetIconRefFromFile);
+ PyMac_PRECHECK(GetIconRefFromFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _err = GetIconRefFromFile(&theFile,
- &theIconRef,
- &theLabel);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- ResObj_New, theIconRef,
- theLabel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _err = GetIconRefFromFile(&theFile,
+ &theIconRef,
+ &theLabel);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ ResObj_New, theIconRef,
+ theLabel);
+ return _res;
}
static PyObject *Icn_GetIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 vRefNum;
- OSType creator;
- OSType iconType;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 vRefNum;
+ OSType creator;
+ OSType iconType;
+ IconRef theIconRef;
#ifndef GetIconRef
- PyMac_PRECHECK(GetIconRef);
+ PyMac_PRECHECK(GetIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "hO&O&",
- &vRefNum,
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType))
- return NULL;
- _err = GetIconRef(vRefNum,
- creator,
- iconType,
- &theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&O&",
+ &vRefNum,
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType))
+ return NULL;
+ _err = GetIconRef(vRefNum,
+ creator,
+ iconType,
+ &theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconRef);
+ return _res;
}
static PyObject *Icn_GetIconRefFromFolder(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 vRefNum;
- SInt32 parentFolderID;
- SInt32 folderID;
- SInt8 attributes;
- SInt8 accessPrivileges;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 vRefNum;
+ SInt32 parentFolderID;
+ SInt32 folderID;
+ SInt8 attributes;
+ SInt8 accessPrivileges;
+ IconRef theIconRef;
#ifndef GetIconRefFromFolder
- PyMac_PRECHECK(GetIconRefFromFolder);
+ PyMac_PRECHECK(GetIconRefFromFolder);
#endif
- if (!PyArg_ParseTuple(_args, "hllbb",
- &vRefNum,
- &parentFolderID,
- &folderID,
- &attributes,
- &accessPrivileges))
- return NULL;
- _err = GetIconRefFromFolder(vRefNum,
- parentFolderID,
- folderID,
- attributes,
- accessPrivileges,
- &theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hllbb",
+ &vRefNum,
+ &parentFolderID,
+ &folderID,
+ &attributes,
+ &accessPrivileges))
+ return NULL;
+ _err = GetIconRefFromFolder(vRefNum,
+ parentFolderID,
+ folderID,
+ attributes,
+ accessPrivileges,
+ &theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconRef);
+ return _res;
}
static PyObject *Icn_RegisterIconRefFromIconFamily(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType creator;
- OSType iconType;
- IconFamilyHandle iconFamily;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType creator;
+ OSType iconType;
+ IconFamilyHandle iconFamily;
+ IconRef theIconRef;
#ifndef RegisterIconRefFromIconFamily
- PyMac_PRECHECK(RegisterIconRefFromIconFamily);
+ PyMac_PRECHECK(RegisterIconRefFromIconFamily);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType,
- ResObj_Convert, &iconFamily))
- return NULL;
- _err = RegisterIconRefFromIconFamily(creator,
- iconType,
- iconFamily,
- &theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType,
+ ResObj_Convert, &iconFamily))
+ return NULL;
+ _err = RegisterIconRefFromIconFamily(creator,
+ iconType,
+ iconFamily,
+ &theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconRef);
+ return _res;
}
static PyObject *Icn_RegisterIconRefFromResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType creator;
- OSType iconType;
- FSSpec resourceFile;
- SInt16 resourceID;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType creator;
+ OSType iconType;
+ FSSpec resourceFile;
+ SInt16 resourceID;
+ IconRef theIconRef;
#ifndef RegisterIconRefFromResource
- PyMac_PRECHECK(RegisterIconRefFromResource);
+ PyMac_PRECHECK(RegisterIconRefFromResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&h",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType,
- PyMac_GetFSSpec, &resourceFile,
- &resourceID))
- return NULL;
- _err = RegisterIconRefFromResource(creator,
- iconType,
- &resourceFile,
- resourceID,
- &theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&h",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType,
+ PyMac_GetFSSpec, &resourceFile,
+ &resourceID))
+ return NULL;
+ _err = RegisterIconRefFromResource(creator,
+ iconType,
+ &resourceFile,
+ resourceID,
+ &theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconRef);
+ return _res;
}
static PyObject *Icn_RegisterIconRefFromFSRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType creator;
- OSType iconType;
- FSRef iconFile;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType creator;
+ OSType iconType;
+ FSRef iconFile;
+ IconRef theIconRef;
#ifndef RegisterIconRefFromFSRef
- PyMac_PRECHECK(RegisterIconRefFromFSRef);
+ PyMac_PRECHECK(RegisterIconRefFromFSRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType,
- PyMac_GetFSRef, &iconFile))
- return NULL;
- _err = RegisterIconRefFromFSRef(creator,
- iconType,
- &iconFile,
- &theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType,
+ PyMac_GetFSRef, &iconFile))
+ return NULL;
+ _err = RegisterIconRefFromFSRef(creator,
+ iconType,
+ &iconFile,
+ &theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconRef);
+ return _res;
}
static PyObject *Icn_UnregisterIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType creator;
- OSType iconType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType creator;
+ OSType iconType;
#ifndef UnregisterIconRef
- PyMac_PRECHECK(UnregisterIconRef);
+ PyMac_PRECHECK(UnregisterIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType))
- return NULL;
- _err = UnregisterIconRef(creator,
- iconType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType))
+ return NULL;
+ _err = UnregisterIconRef(creator,
+ iconType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_UpdateIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
#ifndef UpdateIconRef
- PyMac_PRECHECK(UpdateIconRef);
+ PyMac_PRECHECK(UpdateIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = UpdateIconRef(theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = UpdateIconRef(theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_OverrideIconRefFromResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
- FSSpec resourceFile;
- SInt16 resourceID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
+ FSSpec resourceFile;
+ SInt16 resourceID;
#ifndef OverrideIconRefFromResource
- PyMac_PRECHECK(OverrideIconRefFromResource);
+ PyMac_PRECHECK(OverrideIconRefFromResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- ResObj_Convert, &theIconRef,
- PyMac_GetFSSpec, &resourceFile,
- &resourceID))
- return NULL;
- _err = OverrideIconRefFromResource(theIconRef,
- &resourceFile,
- resourceID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ ResObj_Convert, &theIconRef,
+ PyMac_GetFSSpec, &resourceFile,
+ &resourceID))
+ return NULL;
+ _err = OverrideIconRefFromResource(theIconRef,
+ &resourceFile,
+ resourceID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_OverrideIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef oldIconRef;
- IconRef newIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef oldIconRef;
+ IconRef newIconRef;
#ifndef OverrideIconRef
- PyMac_PRECHECK(OverrideIconRef);
+ PyMac_PRECHECK(OverrideIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &oldIconRef,
- ResObj_Convert, &newIconRef))
- return NULL;
- _err = OverrideIconRef(oldIconRef,
- newIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &oldIconRef,
+ ResObj_Convert, &newIconRef))
+ return NULL;
+ _err = OverrideIconRef(oldIconRef,
+ newIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_RemoveIconRefOverride(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef theIconRef;
#ifndef RemoveIconRefOverride
- PyMac_PRECHECK(RemoveIconRefOverride);
+ PyMac_PRECHECK(RemoveIconRefOverride);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = RemoveIconRefOverride(theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = RemoveIconRefOverride(theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_CompositeIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef backgroundIconRef;
- IconRef foregroundIconRef;
- IconRef compositeIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef backgroundIconRef;
+ IconRef foregroundIconRef;
+ IconRef compositeIconRef;
#ifndef CompositeIconRef
- PyMac_PRECHECK(CompositeIconRef);
+ PyMac_PRECHECK(CompositeIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &backgroundIconRef,
- ResObj_Convert, &foregroundIconRef))
- return NULL;
- _err = CompositeIconRef(backgroundIconRef,
- foregroundIconRef,
- &compositeIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, compositeIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &backgroundIconRef,
+ ResObj_Convert, &foregroundIconRef))
+ return NULL;
+ _err = CompositeIconRef(backgroundIconRef,
+ foregroundIconRef,
+ &compositeIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, compositeIconRef);
+ return _res;
}
static PyObject *Icn_IsIconRefComposite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconRef compositeIconRef;
- IconRef backgroundIconRef;
- IconRef foregroundIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconRef compositeIconRef;
+ IconRef backgroundIconRef;
+ IconRef foregroundIconRef;
#ifndef IsIconRefComposite
- PyMac_PRECHECK(IsIconRefComposite);
+ PyMac_PRECHECK(IsIconRefComposite);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &compositeIconRef))
- return NULL;
- _err = IsIconRefComposite(compositeIconRef,
- &backgroundIconRef,
- &foregroundIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- ResObj_New, backgroundIconRef,
- ResObj_New, foregroundIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &compositeIconRef))
+ return NULL;
+ _err = IsIconRefComposite(compositeIconRef,
+ &backgroundIconRef,
+ &foregroundIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ ResObj_New, backgroundIconRef,
+ ResObj_New, foregroundIconRef);
+ return _res;
}
static PyObject *Icn_IsValidIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ IconRef theIconRef;
#ifndef IsValidIconRef
- PyMac_PRECHECK(IsValidIconRef);
+ PyMac_PRECHECK(IsValidIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theIconRef))
- return NULL;
- _rv = IsValidIconRef(theIconRef);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _rv = IsValidIconRef(theIconRef);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_PlotIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Rect theRect;
- IconAlignmentType align;
- IconTransformType transform;
- IconServicesUsageFlags theIconServicesUsageFlags;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Rect theRect;
+ IconAlignmentType align;
+ IconTransformType transform;
+ IconServicesUsageFlags theIconServicesUsageFlags;
+ IconRef theIconRef;
#ifndef PlotIconRef
- PyMac_PRECHECK(PlotIconRef);
+ PyMac_PRECHECK(PlotIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&hhlO&",
- PyMac_GetRect, &theRect,
- &align,
- &transform,
- &theIconServicesUsageFlags,
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = PlotIconRef(&theRect,
- align,
- transform,
- theIconServicesUsageFlags,
- theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hhlO&",
+ PyMac_GetRect, &theRect,
+ &align,
+ &transform,
+ &theIconServicesUsageFlags,
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = PlotIconRef(&theRect,
+ align,
+ transform,
+ theIconServicesUsageFlags,
+ theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_PtInIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point testPt;
- Rect iconRect;
- IconAlignmentType align;
- IconServicesUsageFlags theIconServicesUsageFlags;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point testPt;
+ Rect iconRect;
+ IconAlignmentType align;
+ IconServicesUsageFlags theIconServicesUsageFlags;
+ IconRef theIconRef;
#ifndef PtInIconRef
- PyMac_PRECHECK(PtInIconRef);
+ PyMac_PRECHECK(PtInIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hlO&",
- PyMac_GetPoint, &testPt,
- PyMac_GetRect, &iconRect,
- &align,
- &theIconServicesUsageFlags,
- ResObj_Convert, &theIconRef))
- return NULL;
- _rv = PtInIconRef(&testPt,
- &iconRect,
- align,
- theIconServicesUsageFlags,
- theIconRef);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hlO&",
+ PyMac_GetPoint, &testPt,
+ PyMac_GetRect, &iconRect,
+ &align,
+ &theIconServicesUsageFlags,
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _rv = PtInIconRef(&testPt,
+ &iconRect,
+ align,
+ theIconServicesUsageFlags,
+ theIconRef);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_RectInIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect testRect;
- Rect iconRect;
- IconAlignmentType align;
- IconServicesUsageFlags iconServicesUsageFlags;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect testRect;
+ Rect iconRect;
+ IconAlignmentType align;
+ IconServicesUsageFlags iconServicesUsageFlags;
+ IconRef theIconRef;
#ifndef RectInIconRef
- PyMac_PRECHECK(RectInIconRef);
+ PyMac_PRECHECK(RectInIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hlO&",
- PyMac_GetRect, &testRect,
- PyMac_GetRect, &iconRect,
- &align,
- &iconServicesUsageFlags,
- ResObj_Convert, &theIconRef))
- return NULL;
- _rv = RectInIconRef(&testRect,
- &iconRect,
- align,
- iconServicesUsageFlags,
- theIconRef);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hlO&",
+ PyMac_GetRect, &testRect,
+ PyMac_GetRect, &iconRect,
+ &align,
+ &iconServicesUsageFlags,
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _rv = RectInIconRef(&testRect,
+ &iconRect,
+ align,
+ iconServicesUsageFlags,
+ theIconRef);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_IconRefToRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle theRgn;
- Rect iconRect;
- IconAlignmentType align;
- IconServicesUsageFlags iconServicesUsageFlags;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle theRgn;
+ Rect iconRect;
+ IconAlignmentType align;
+ IconServicesUsageFlags iconServicesUsageFlags;
+ IconRef theIconRef;
#ifndef IconRefToRgn
- PyMac_PRECHECK(IconRefToRgn);
+ PyMac_PRECHECK(IconRefToRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&hlO&",
- ResObj_Convert, &theRgn,
- PyMac_GetRect, &iconRect,
- &align,
- &iconServicesUsageFlags,
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = IconRefToRgn(theRgn,
- &iconRect,
- align,
- iconServicesUsageFlags,
- theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&hlO&",
+ ResObj_Convert, &theRgn,
+ PyMac_GetRect, &iconRect,
+ &align,
+ &iconServicesUsageFlags,
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = IconRefToRgn(theRgn,
+ &iconRect,
+ align,
+ iconServicesUsageFlags,
+ theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetIconSizesFromIconRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconSelectorValue iconSelectorInput;
- IconSelectorValue iconSelectorOutputPtr;
- IconServicesUsageFlags iconServicesUsageFlags;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconSelectorValue iconSelectorInput;
+ IconSelectorValue iconSelectorOutputPtr;
+ IconServicesUsageFlags iconServicesUsageFlags;
+ IconRef theIconRef;
#ifndef GetIconSizesFromIconRef
- PyMac_PRECHECK(GetIconSizesFromIconRef);
+ PyMac_PRECHECK(GetIconSizesFromIconRef);
#endif
- if (!PyArg_ParseTuple(_args, "llO&",
- &iconSelectorInput,
- &iconServicesUsageFlags,
- ResObj_Convert, &theIconRef))
- return NULL;
- _err = GetIconSizesFromIconRef(iconSelectorInput,
- &iconSelectorOutputPtr,
- iconServicesUsageFlags,
- theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- iconSelectorOutputPtr);
- return _res;
+ if (!PyArg_ParseTuple(_args, "llO&",
+ &iconSelectorInput,
+ &iconServicesUsageFlags,
+ ResObj_Convert, &theIconRef))
+ return NULL;
+ _err = GetIconSizesFromIconRef(iconSelectorInput,
+ &iconSelectorOutputPtr,
+ iconServicesUsageFlags,
+ theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ iconSelectorOutputPtr);
+ return _res;
}
static PyObject *Icn_FlushIconRefs(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType creator;
- OSType iconType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType creator;
+ OSType iconType;
#ifndef FlushIconRefs
- PyMac_PRECHECK(FlushIconRefs);
+ PyMac_PRECHECK(FlushIconRefs);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType))
- return NULL;
- _err = FlushIconRefs(creator,
- iconType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType))
+ return NULL;
+ _err = FlushIconRefs(creator,
+ iconType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_FlushIconRefsByVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 vRefNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 vRefNum;
#ifndef FlushIconRefsByVolume
- PyMac_PRECHECK(FlushIconRefsByVolume);
+ PyMac_PRECHECK(FlushIconRefsByVolume);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &vRefNum))
- return NULL;
- _err = FlushIconRefsByVolume(vRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &vRefNum))
+ return NULL;
+ _err = FlushIconRefsByVolume(vRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_SetCustomIconsEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 vRefNum;
- Boolean enableCustomIcons;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 vRefNum;
+ Boolean enableCustomIcons;
#ifndef SetCustomIconsEnabled
- PyMac_PRECHECK(SetCustomIconsEnabled);
+ PyMac_PRECHECK(SetCustomIconsEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &vRefNum,
- &enableCustomIcons))
- return NULL;
- _err = SetCustomIconsEnabled(vRefNum,
- enableCustomIcons);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &vRefNum,
+ &enableCustomIcons))
+ return NULL;
+ _err = SetCustomIconsEnabled(vRefNum,
+ enableCustomIcons);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Icn_GetCustomIconsEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 vRefNum;
- Boolean customIconsEnabled;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 vRefNum;
+ Boolean customIconsEnabled;
#ifndef GetCustomIconsEnabled
- PyMac_PRECHECK(GetCustomIconsEnabled);
+ PyMac_PRECHECK(GetCustomIconsEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &vRefNum))
- return NULL;
- _err = GetCustomIconsEnabled(vRefNum,
- &customIconsEnabled);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- customIconsEnabled);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &vRefNum))
+ return NULL;
+ _err = GetCustomIconsEnabled(vRefNum,
+ &customIconsEnabled);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ customIconsEnabled);
+ return _res;
}
static PyObject *Icn_IsIconRefMaskEmpty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- IconRef iconRef;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ IconRef iconRef;
#ifndef IsIconRefMaskEmpty
- PyMac_PRECHECK(IsIconRefMaskEmpty);
+ PyMac_PRECHECK(IsIconRefMaskEmpty);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &iconRef))
- return NULL;
- _rv = IsIconRefMaskEmpty(iconRef);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &iconRef))
+ return NULL;
+ _rv = IsIconRefMaskEmpty(iconRef);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Icn_GetIconRefVariant(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- IconRef _rv;
- IconRef inIconRef;
- OSType inVariant;
- IconTransformType outTransform;
+ PyObject *_res = NULL;
+ IconRef _rv;
+ IconRef inIconRef;
+ OSType inVariant;
+ IconTransformType outTransform;
#ifndef GetIconRefVariant
- PyMac_PRECHECK(GetIconRefVariant);
+ PyMac_PRECHECK(GetIconRefVariant);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &inIconRef,
- PyMac_GetOSType, &inVariant))
- return NULL;
- _rv = GetIconRefVariant(inIconRef,
- inVariant,
- &outTransform);
- _res = Py_BuildValue("O&h",
- ResObj_New, _rv,
- outTransform);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &inIconRef,
+ PyMac_GetOSType, &inVariant))
+ return NULL;
+ _rv = GetIconRefVariant(inIconRef,
+ inVariant,
+ &outTransform);
+ _res = Py_BuildValue("O&h",
+ ResObj_New, _rv,
+ outTransform);
+ return _res;
}
static PyObject *Icn_RegisterIconRefFromIconFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType creator;
- OSType iconType;
- FSSpec iconFile;
- IconRef theIconRef;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType creator;
+ OSType iconType;
+ FSSpec iconFile;
+ IconRef theIconRef;
#ifndef RegisterIconRefFromIconFile
- PyMac_PRECHECK(RegisterIconRefFromIconFile);
+ PyMac_PRECHECK(RegisterIconRefFromIconFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &iconType,
- PyMac_GetFSSpec, &iconFile))
- return NULL;
- _err = RegisterIconRefFromIconFile(creator,
- iconType,
- &iconFile,
- &theIconRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, theIconRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &iconType,
+ PyMac_GetFSSpec, &iconFile))
+ return NULL;
+ _err = RegisterIconRefFromIconFile(creator,
+ iconType,
+ &iconFile,
+ &theIconRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, theIconRef);
+ return _res;
}
static PyObject *Icn_ReadIconFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec iconFile;
- IconFamilyHandle iconFamily;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec iconFile;
+ IconFamilyHandle iconFamily;
#ifndef ReadIconFile
- PyMac_PRECHECK(ReadIconFile);
+ PyMac_PRECHECK(ReadIconFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSSpec, &iconFile))
- return NULL;
- _err = ReadIconFile(&iconFile,
- &iconFamily);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, iconFamily);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSSpec, &iconFile))
+ return NULL;
+ _err = ReadIconFile(&iconFile,
+ &iconFamily);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, iconFamily);
+ return _res;
}
static PyObject *Icn_ReadIconFromFSRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- FSRef ref;
- IconFamilyHandle iconFamily;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ FSRef ref;
+ IconFamilyHandle iconFamily;
#ifndef ReadIconFromFSRef
- PyMac_PRECHECK(ReadIconFromFSRef);
+ PyMac_PRECHECK(ReadIconFromFSRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSRef, &ref))
- return NULL;
- _err = ReadIconFromFSRef(&ref,
- &iconFamily);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, iconFamily);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSRef, &ref))
+ return NULL;
+ _err = ReadIconFromFSRef(&ref,
+ &iconFamily);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, iconFamily);
+ return _res;
}
static PyObject *Icn_WriteIconFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- IconFamilyHandle iconFamily;
- FSSpec iconFile;
+ PyObject *_res = NULL;
+ OSErr _err;
+ IconFamilyHandle iconFamily;
+ FSSpec iconFile;
#ifndef WriteIconFile
- PyMac_PRECHECK(WriteIconFile);
+ PyMac_PRECHECK(WriteIconFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &iconFamily,
- PyMac_GetFSSpec, &iconFile))
- return NULL;
- _err = WriteIconFile(iconFamily,
- &iconFile);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &iconFamily,
+ PyMac_GetFSSpec, &iconFile))
+ return NULL;
+ _err = WriteIconFile(iconFamily,
+ &iconFile);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Icn_methods[] = {
#ifndef __LP64__
- {"GetCIcon", (PyCFunction)Icn_GetCIcon, 1,
- PyDoc_STR("(SInt16 iconID) -> (CIconHandle _rv)")},
- {"PlotCIcon", (PyCFunction)Icn_PlotCIcon, 1,
- PyDoc_STR("(Rect theRect, CIconHandle theIcon) -> None")},
- {"DisposeCIcon", (PyCFunction)Icn_DisposeCIcon, 1,
- PyDoc_STR("(CIconHandle theIcon) -> None")},
- {"GetIcon", (PyCFunction)Icn_GetIcon, 1,
- PyDoc_STR("(SInt16 iconID) -> (Handle _rv)")},
- {"PlotIcon", (PyCFunction)Icn_PlotIcon, 1,
- PyDoc_STR("(Rect theRect, Handle theIcon) -> None")},
- {"PlotIconID", (PyCFunction)Icn_PlotIconID, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, SInt16 theResID) -> None")},
- {"NewIconSuite", (PyCFunction)Icn_NewIconSuite, 1,
- PyDoc_STR("() -> (IconSuiteRef theIconSuite)")},
- {"AddIconToSuite", (PyCFunction)Icn_AddIconToSuite, 1,
- PyDoc_STR("(Handle theIconData, IconSuiteRef theSuite, ResType theType) -> None")},
- {"GetIconFromSuite", (PyCFunction)Icn_GetIconFromSuite, 1,
- PyDoc_STR("(IconSuiteRef theSuite, ResType theType) -> (Handle theIconData)")},
- {"GetIconSuite", (PyCFunction)Icn_GetIconSuite, 1,
- PyDoc_STR("(SInt16 theResID, IconSelectorValue selector) -> (IconSuiteRef theIconSuite)")},
- {"DisposeIconSuite", (PyCFunction)Icn_DisposeIconSuite, 1,
- PyDoc_STR("(IconSuiteRef theIconSuite, Boolean disposeData) -> None")},
- {"PlotIconSuite", (PyCFunction)Icn_PlotIconSuite, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, IconSuiteRef theIconSuite) -> None")},
- {"LoadIconCache", (PyCFunction)Icn_LoadIconCache, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, IconCacheRef theIconCache) -> None")},
- {"GetLabel", (PyCFunction)Icn_GetLabel, 1,
- PyDoc_STR("(SInt16 labelNumber, Str255 labelString) -> (RGBColor labelColor)")},
- {"PtInIconID", (PyCFunction)Icn_PtInIconID, 1,
- PyDoc_STR("(Point testPt, Rect iconRect, IconAlignmentType align, SInt16 iconID) -> (Boolean _rv)")},
- {"PtInIconSuite", (PyCFunction)Icn_PtInIconSuite, 1,
- PyDoc_STR("(Point testPt, Rect iconRect, IconAlignmentType align, IconSuiteRef theIconSuite) -> (Boolean _rv)")},
- {"RectInIconID", (PyCFunction)Icn_RectInIconID, 1,
- PyDoc_STR("(Rect testRect, Rect iconRect, IconAlignmentType align, SInt16 iconID) -> (Boolean _rv)")},
- {"RectInIconSuite", (PyCFunction)Icn_RectInIconSuite, 1,
- PyDoc_STR("(Rect testRect, Rect iconRect, IconAlignmentType align, IconSuiteRef theIconSuite) -> (Boolean _rv)")},
- {"IconIDToRgn", (PyCFunction)Icn_IconIDToRgn, 1,
- PyDoc_STR("(RgnHandle theRgn, Rect iconRect, IconAlignmentType align, SInt16 iconID) -> None")},
- {"IconSuiteToRgn", (PyCFunction)Icn_IconSuiteToRgn, 1,
- PyDoc_STR("(RgnHandle theRgn, Rect iconRect, IconAlignmentType align, IconSuiteRef theIconSuite) -> None")},
- {"SetSuiteLabel", (PyCFunction)Icn_SetSuiteLabel, 1,
- PyDoc_STR("(IconSuiteRef theSuite, SInt16 theLabel) -> None")},
- {"GetSuiteLabel", (PyCFunction)Icn_GetSuiteLabel, 1,
- PyDoc_STR("(IconSuiteRef theSuite) -> (SInt16 _rv)")},
- {"PlotIconHandle", (PyCFunction)Icn_PlotIconHandle, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, Handle theIcon) -> None")},
- {"PlotSICNHandle", (PyCFunction)Icn_PlotSICNHandle, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, Handle theSICN) -> None")},
- {"PlotCIconHandle", (PyCFunction)Icn_PlotCIconHandle, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, CIconHandle theCIcon) -> None")},
- {"IconRefToIconFamily", (PyCFunction)Icn_IconRefToIconFamily, 1,
- PyDoc_STR("(IconRef theIconRef, IconSelectorValue whichIcons) -> (IconFamilyHandle iconFamily)")},
- {"IconFamilyToIconSuite", (PyCFunction)Icn_IconFamilyToIconSuite, 1,
- PyDoc_STR("(IconFamilyHandle iconFamily, IconSelectorValue whichIcons) -> (IconSuiteRef iconSuite)")},
- {"IconSuiteToIconFamily", (PyCFunction)Icn_IconSuiteToIconFamily, 1,
- PyDoc_STR("(IconSuiteRef iconSuite, IconSelectorValue whichIcons) -> (IconFamilyHandle iconFamily)")},
- {"SetIconFamilyData", (PyCFunction)Icn_SetIconFamilyData, 1,
- PyDoc_STR("(IconFamilyHandle iconFamily, OSType iconType, Handle h) -> None")},
- {"GetIconFamilyData", (PyCFunction)Icn_GetIconFamilyData, 1,
- PyDoc_STR("(IconFamilyHandle iconFamily, OSType iconType, Handle h) -> None")},
- {"GetIconRefOwners", (PyCFunction)Icn_GetIconRefOwners, 1,
- PyDoc_STR("(IconRef theIconRef) -> (UInt16 owners)")},
- {"AcquireIconRef", (PyCFunction)Icn_AcquireIconRef, 1,
- PyDoc_STR("(IconRef theIconRef) -> None")},
- {"ReleaseIconRef", (PyCFunction)Icn_ReleaseIconRef, 1,
- PyDoc_STR("(IconRef theIconRef) -> None")},
- {"GetIconRefFromFile", (PyCFunction)Icn_GetIconRefFromFile, 1,
- PyDoc_STR("(FSSpec theFile) -> (IconRef theIconRef, SInt16 theLabel)")},
- {"GetIconRef", (PyCFunction)Icn_GetIconRef, 1,
- PyDoc_STR("(SInt16 vRefNum, OSType creator, OSType iconType) -> (IconRef theIconRef)")},
- {"GetIconRefFromFolder", (PyCFunction)Icn_GetIconRefFromFolder, 1,
- PyDoc_STR("(SInt16 vRefNum, SInt32 parentFolderID, SInt32 folderID, SInt8 attributes, SInt8 accessPrivileges) -> (IconRef theIconRef)")},
- {"RegisterIconRefFromIconFamily", (PyCFunction)Icn_RegisterIconRefFromIconFamily, 1,
- PyDoc_STR("(OSType creator, OSType iconType, IconFamilyHandle iconFamily) -> (IconRef theIconRef)")},
- {"RegisterIconRefFromResource", (PyCFunction)Icn_RegisterIconRefFromResource, 1,
- PyDoc_STR("(OSType creator, OSType iconType, FSSpec resourceFile, SInt16 resourceID) -> (IconRef theIconRef)")},
- {"RegisterIconRefFromFSRef", (PyCFunction)Icn_RegisterIconRefFromFSRef, 1,
- PyDoc_STR("(OSType creator, OSType iconType, FSRef iconFile) -> (IconRef theIconRef)")},
- {"UnregisterIconRef", (PyCFunction)Icn_UnregisterIconRef, 1,
- PyDoc_STR("(OSType creator, OSType iconType) -> None")},
- {"UpdateIconRef", (PyCFunction)Icn_UpdateIconRef, 1,
- PyDoc_STR("(IconRef theIconRef) -> None")},
- {"OverrideIconRefFromResource", (PyCFunction)Icn_OverrideIconRefFromResource, 1,
- PyDoc_STR("(IconRef theIconRef, FSSpec resourceFile, SInt16 resourceID) -> None")},
- {"OverrideIconRef", (PyCFunction)Icn_OverrideIconRef, 1,
- PyDoc_STR("(IconRef oldIconRef, IconRef newIconRef) -> None")},
- {"RemoveIconRefOverride", (PyCFunction)Icn_RemoveIconRefOverride, 1,
- PyDoc_STR("(IconRef theIconRef) -> None")},
- {"CompositeIconRef", (PyCFunction)Icn_CompositeIconRef, 1,
- PyDoc_STR("(IconRef backgroundIconRef, IconRef foregroundIconRef) -> (IconRef compositeIconRef)")},
- {"IsIconRefComposite", (PyCFunction)Icn_IsIconRefComposite, 1,
- PyDoc_STR("(IconRef compositeIconRef) -> (IconRef backgroundIconRef, IconRef foregroundIconRef)")},
- {"IsValidIconRef", (PyCFunction)Icn_IsValidIconRef, 1,
- PyDoc_STR("(IconRef theIconRef) -> (Boolean _rv)")},
- {"PlotIconRef", (PyCFunction)Icn_PlotIconRef, 1,
- PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, IconServicesUsageFlags theIconServicesUsageFlags, IconRef theIconRef) -> None")},
- {"PtInIconRef", (PyCFunction)Icn_PtInIconRef, 1,
- PyDoc_STR("(Point testPt, Rect iconRect, IconAlignmentType align, IconServicesUsageFlags theIconServicesUsageFlags, IconRef theIconRef) -> (Boolean _rv)")},
- {"RectInIconRef", (PyCFunction)Icn_RectInIconRef, 1,
- PyDoc_STR("(Rect testRect, Rect iconRect, IconAlignmentType align, IconServicesUsageFlags iconServicesUsageFlags, IconRef theIconRef) -> (Boolean _rv)")},
- {"IconRefToRgn", (PyCFunction)Icn_IconRefToRgn, 1,
- PyDoc_STR("(RgnHandle theRgn, Rect iconRect, IconAlignmentType align, IconServicesUsageFlags iconServicesUsageFlags, IconRef theIconRef) -> None")},
- {"GetIconSizesFromIconRef", (PyCFunction)Icn_GetIconSizesFromIconRef, 1,
- PyDoc_STR("(IconSelectorValue iconSelectorInput, IconServicesUsageFlags iconServicesUsageFlags, IconRef theIconRef) -> (IconSelectorValue iconSelectorOutputPtr)")},
- {"FlushIconRefs", (PyCFunction)Icn_FlushIconRefs, 1,
- PyDoc_STR("(OSType creator, OSType iconType) -> None")},
- {"FlushIconRefsByVolume", (PyCFunction)Icn_FlushIconRefsByVolume, 1,
- PyDoc_STR("(SInt16 vRefNum) -> None")},
- {"SetCustomIconsEnabled", (PyCFunction)Icn_SetCustomIconsEnabled, 1,
- PyDoc_STR("(SInt16 vRefNum, Boolean enableCustomIcons) -> None")},
- {"GetCustomIconsEnabled", (PyCFunction)Icn_GetCustomIconsEnabled, 1,
- PyDoc_STR("(SInt16 vRefNum) -> (Boolean customIconsEnabled)")},
- {"IsIconRefMaskEmpty", (PyCFunction)Icn_IsIconRefMaskEmpty, 1,
- PyDoc_STR("(IconRef iconRef) -> (Boolean _rv)")},
- {"GetIconRefVariant", (PyCFunction)Icn_GetIconRefVariant, 1,
- PyDoc_STR("(IconRef inIconRef, OSType inVariant) -> (IconRef _rv, IconTransformType outTransform)")},
- {"RegisterIconRefFromIconFile", (PyCFunction)Icn_RegisterIconRefFromIconFile, 1,
- PyDoc_STR("(OSType creator, OSType iconType, FSSpec iconFile) -> (IconRef theIconRef)")},
- {"ReadIconFile", (PyCFunction)Icn_ReadIconFile, 1,
- PyDoc_STR("(FSSpec iconFile) -> (IconFamilyHandle iconFamily)")},
- {"ReadIconFromFSRef", (PyCFunction)Icn_ReadIconFromFSRef, 1,
- PyDoc_STR("(FSRef ref) -> (IconFamilyHandle iconFamily)")},
- {"WriteIconFile", (PyCFunction)Icn_WriteIconFile, 1,
- PyDoc_STR("(IconFamilyHandle iconFamily, FSSpec iconFile) -> None")},
+ {"GetCIcon", (PyCFunction)Icn_GetCIcon, 1,
+ PyDoc_STR("(SInt16 iconID) -> (CIconHandle _rv)")},
+ {"PlotCIcon", (PyCFunction)Icn_PlotCIcon, 1,
+ PyDoc_STR("(Rect theRect, CIconHandle theIcon) -> None")},
+ {"DisposeCIcon", (PyCFunction)Icn_DisposeCIcon, 1,
+ PyDoc_STR("(CIconHandle theIcon) -> None")},
+ {"GetIcon", (PyCFunction)Icn_GetIcon, 1,
+ PyDoc_STR("(SInt16 iconID) -> (Handle _rv)")},
+ {"PlotIcon", (PyCFunction)Icn_PlotIcon, 1,
+ PyDoc_STR("(Rect theRect, Handle theIcon) -> None")},
+ {"PlotIconID", (PyCFunction)Icn_PlotIconID, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, SInt16 theResID) -> None")},
+ {"NewIconSuite", (PyCFunction)Icn_NewIconSuite, 1,
+ PyDoc_STR("() -> (IconSuiteRef theIconSuite)")},
+ {"AddIconToSuite", (PyCFunction)Icn_AddIconToSuite, 1,
+ PyDoc_STR("(Handle theIconData, IconSuiteRef theSuite, ResType theType) -> None")},
+ {"GetIconFromSuite", (PyCFunction)Icn_GetIconFromSuite, 1,
+ PyDoc_STR("(IconSuiteRef theSuite, ResType theType) -> (Handle theIconData)")},
+ {"GetIconSuite", (PyCFunction)Icn_GetIconSuite, 1,
+ PyDoc_STR("(SInt16 theResID, IconSelectorValue selector) -> (IconSuiteRef theIconSuite)")},
+ {"DisposeIconSuite", (PyCFunction)Icn_DisposeIconSuite, 1,
+ PyDoc_STR("(IconSuiteRef theIconSuite, Boolean disposeData) -> None")},
+ {"PlotIconSuite", (PyCFunction)Icn_PlotIconSuite, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, IconSuiteRef theIconSuite) -> None")},
+ {"LoadIconCache", (PyCFunction)Icn_LoadIconCache, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, IconCacheRef theIconCache) -> None")},
+ {"GetLabel", (PyCFunction)Icn_GetLabel, 1,
+ PyDoc_STR("(SInt16 labelNumber, Str255 labelString) -> (RGBColor labelColor)")},
+ {"PtInIconID", (PyCFunction)Icn_PtInIconID, 1,
+ PyDoc_STR("(Point testPt, Rect iconRect, IconAlignmentType align, SInt16 iconID) -> (Boolean _rv)")},
+ {"PtInIconSuite", (PyCFunction)Icn_PtInIconSuite, 1,
+ PyDoc_STR("(Point testPt, Rect iconRect, IconAlignmentType align, IconSuiteRef theIconSuite) -> (Boolean _rv)")},
+ {"RectInIconID", (PyCFunction)Icn_RectInIconID, 1,
+ PyDoc_STR("(Rect testRect, Rect iconRect, IconAlignmentType align, SInt16 iconID) -> (Boolean _rv)")},
+ {"RectInIconSuite", (PyCFunction)Icn_RectInIconSuite, 1,
+ PyDoc_STR("(Rect testRect, Rect iconRect, IconAlignmentType align, IconSuiteRef theIconSuite) -> (Boolean _rv)")},
+ {"IconIDToRgn", (PyCFunction)Icn_IconIDToRgn, 1,
+ PyDoc_STR("(RgnHandle theRgn, Rect iconRect, IconAlignmentType align, SInt16 iconID) -> None")},
+ {"IconSuiteToRgn", (PyCFunction)Icn_IconSuiteToRgn, 1,
+ PyDoc_STR("(RgnHandle theRgn, Rect iconRect, IconAlignmentType align, IconSuiteRef theIconSuite) -> None")},
+ {"SetSuiteLabel", (PyCFunction)Icn_SetSuiteLabel, 1,
+ PyDoc_STR("(IconSuiteRef theSuite, SInt16 theLabel) -> None")},
+ {"GetSuiteLabel", (PyCFunction)Icn_GetSuiteLabel, 1,
+ PyDoc_STR("(IconSuiteRef theSuite) -> (SInt16 _rv)")},
+ {"PlotIconHandle", (PyCFunction)Icn_PlotIconHandle, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, Handle theIcon) -> None")},
+ {"PlotSICNHandle", (PyCFunction)Icn_PlotSICNHandle, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, Handle theSICN) -> None")},
+ {"PlotCIconHandle", (PyCFunction)Icn_PlotCIconHandle, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, CIconHandle theCIcon) -> None")},
+ {"IconRefToIconFamily", (PyCFunction)Icn_IconRefToIconFamily, 1,
+ PyDoc_STR("(IconRef theIconRef, IconSelectorValue whichIcons) -> (IconFamilyHandle iconFamily)")},
+ {"IconFamilyToIconSuite", (PyCFunction)Icn_IconFamilyToIconSuite, 1,
+ PyDoc_STR("(IconFamilyHandle iconFamily, IconSelectorValue whichIcons) -> (IconSuiteRef iconSuite)")},
+ {"IconSuiteToIconFamily", (PyCFunction)Icn_IconSuiteToIconFamily, 1,
+ PyDoc_STR("(IconSuiteRef iconSuite, IconSelectorValue whichIcons) -> (IconFamilyHandle iconFamily)")},
+ {"SetIconFamilyData", (PyCFunction)Icn_SetIconFamilyData, 1,
+ PyDoc_STR("(IconFamilyHandle iconFamily, OSType iconType, Handle h) -> None")},
+ {"GetIconFamilyData", (PyCFunction)Icn_GetIconFamilyData, 1,
+ PyDoc_STR("(IconFamilyHandle iconFamily, OSType iconType, Handle h) -> None")},
+ {"GetIconRefOwners", (PyCFunction)Icn_GetIconRefOwners, 1,
+ PyDoc_STR("(IconRef theIconRef) -> (UInt16 owners)")},
+ {"AcquireIconRef", (PyCFunction)Icn_AcquireIconRef, 1,
+ PyDoc_STR("(IconRef theIconRef) -> None")},
+ {"ReleaseIconRef", (PyCFunction)Icn_ReleaseIconRef, 1,
+ PyDoc_STR("(IconRef theIconRef) -> None")},
+ {"GetIconRefFromFile", (PyCFunction)Icn_GetIconRefFromFile, 1,
+ PyDoc_STR("(FSSpec theFile) -> (IconRef theIconRef, SInt16 theLabel)")},
+ {"GetIconRef", (PyCFunction)Icn_GetIconRef, 1,
+ PyDoc_STR("(SInt16 vRefNum, OSType creator, OSType iconType) -> (IconRef theIconRef)")},
+ {"GetIconRefFromFolder", (PyCFunction)Icn_GetIconRefFromFolder, 1,
+ PyDoc_STR("(SInt16 vRefNum, SInt32 parentFolderID, SInt32 folderID, SInt8 attributes, SInt8 accessPrivileges) -> (IconRef theIconRef)")},
+ {"RegisterIconRefFromIconFamily", (PyCFunction)Icn_RegisterIconRefFromIconFamily, 1,
+ PyDoc_STR("(OSType creator, OSType iconType, IconFamilyHandle iconFamily) -> (IconRef theIconRef)")},
+ {"RegisterIconRefFromResource", (PyCFunction)Icn_RegisterIconRefFromResource, 1,
+ PyDoc_STR("(OSType creator, OSType iconType, FSSpec resourceFile, SInt16 resourceID) -> (IconRef theIconRef)")},
+ {"RegisterIconRefFromFSRef", (PyCFunction)Icn_RegisterIconRefFromFSRef, 1,
+ PyDoc_STR("(OSType creator, OSType iconType, FSRef iconFile) -> (IconRef theIconRef)")},
+ {"UnregisterIconRef", (PyCFunction)Icn_UnregisterIconRef, 1,
+ PyDoc_STR("(OSType creator, OSType iconType) -> None")},
+ {"UpdateIconRef", (PyCFunction)Icn_UpdateIconRef, 1,
+ PyDoc_STR("(IconRef theIconRef) -> None")},
+ {"OverrideIconRefFromResource", (PyCFunction)Icn_OverrideIconRefFromResource, 1,
+ PyDoc_STR("(IconRef theIconRef, FSSpec resourceFile, SInt16 resourceID) -> None")},
+ {"OverrideIconRef", (PyCFunction)Icn_OverrideIconRef, 1,
+ PyDoc_STR("(IconRef oldIconRef, IconRef newIconRef) -> None")},
+ {"RemoveIconRefOverride", (PyCFunction)Icn_RemoveIconRefOverride, 1,
+ PyDoc_STR("(IconRef theIconRef) -> None")},
+ {"CompositeIconRef", (PyCFunction)Icn_CompositeIconRef, 1,
+ PyDoc_STR("(IconRef backgroundIconRef, IconRef foregroundIconRef) -> (IconRef compositeIconRef)")},
+ {"IsIconRefComposite", (PyCFunction)Icn_IsIconRefComposite, 1,
+ PyDoc_STR("(IconRef compositeIconRef) -> (IconRef backgroundIconRef, IconRef foregroundIconRef)")},
+ {"IsValidIconRef", (PyCFunction)Icn_IsValidIconRef, 1,
+ PyDoc_STR("(IconRef theIconRef) -> (Boolean _rv)")},
+ {"PlotIconRef", (PyCFunction)Icn_PlotIconRef, 1,
+ PyDoc_STR("(Rect theRect, IconAlignmentType align, IconTransformType transform, IconServicesUsageFlags theIconServicesUsageFlags, IconRef theIconRef) -> None")},
+ {"PtInIconRef", (PyCFunction)Icn_PtInIconRef, 1,
+ PyDoc_STR("(Point testPt, Rect iconRect, IconAlignmentType align, IconServicesUsageFlags theIconServicesUsageFlags, IconRef theIconRef) -> (Boolean _rv)")},
+ {"RectInIconRef", (PyCFunction)Icn_RectInIconRef, 1,
+ PyDoc_STR("(Rect testRect, Rect iconRect, IconAlignmentType align, IconServicesUsageFlags iconServicesUsageFlags, IconRef theIconRef) -> (Boolean _rv)")},
+ {"IconRefToRgn", (PyCFunction)Icn_IconRefToRgn, 1,
+ PyDoc_STR("(RgnHandle theRgn, Rect iconRect, IconAlignmentType align, IconServicesUsageFlags iconServicesUsageFlags, IconRef theIconRef) -> None")},
+ {"GetIconSizesFromIconRef", (PyCFunction)Icn_GetIconSizesFromIconRef, 1,
+ PyDoc_STR("(IconSelectorValue iconSelectorInput, IconServicesUsageFlags iconServicesUsageFlags, IconRef theIconRef) -> (IconSelectorValue iconSelectorOutputPtr)")},
+ {"FlushIconRefs", (PyCFunction)Icn_FlushIconRefs, 1,
+ PyDoc_STR("(OSType creator, OSType iconType) -> None")},
+ {"FlushIconRefsByVolume", (PyCFunction)Icn_FlushIconRefsByVolume, 1,
+ PyDoc_STR("(SInt16 vRefNum) -> None")},
+ {"SetCustomIconsEnabled", (PyCFunction)Icn_SetCustomIconsEnabled, 1,
+ PyDoc_STR("(SInt16 vRefNum, Boolean enableCustomIcons) -> None")},
+ {"GetCustomIconsEnabled", (PyCFunction)Icn_GetCustomIconsEnabled, 1,
+ PyDoc_STR("(SInt16 vRefNum) -> (Boolean customIconsEnabled)")},
+ {"IsIconRefMaskEmpty", (PyCFunction)Icn_IsIconRefMaskEmpty, 1,
+ PyDoc_STR("(IconRef iconRef) -> (Boolean _rv)")},
+ {"GetIconRefVariant", (PyCFunction)Icn_GetIconRefVariant, 1,
+ PyDoc_STR("(IconRef inIconRef, OSType inVariant) -> (IconRef _rv, IconTransformType outTransform)")},
+ {"RegisterIconRefFromIconFile", (PyCFunction)Icn_RegisterIconRefFromIconFile, 1,
+ PyDoc_STR("(OSType creator, OSType iconType, FSSpec iconFile) -> (IconRef theIconRef)")},
+ {"ReadIconFile", (PyCFunction)Icn_ReadIconFile, 1,
+ PyDoc_STR("(FSSpec iconFile) -> (IconFamilyHandle iconFamily)")},
+ {"ReadIconFromFSRef", (PyCFunction)Icn_ReadIconFromFSRef, 1,
+ PyDoc_STR("(FSRef ref) -> (IconFamilyHandle iconFamily)")},
+ {"WriteIconFile", (PyCFunction)Icn_WriteIconFile, 1,
+ PyDoc_STR("(IconFamilyHandle iconFamily, FSSpec iconFile) -> None")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -1585,21 +1585,21 @@ static PyMethodDef Icn_methods[] = {
void init_Icn(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
#endif /* __LP64__ */
- m = Py_InitModule("_Icn", Icn_methods);
+ m = Py_InitModule("_Icn", Icn_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Icn_Error = PyMac_GetOSErrException();
- if (Icn_Error == NULL ||
- PyDict_SetItemString(d, "Error", Icn_Error) != 0)
- return;
+ d = PyModule_GetDict(m);
+ Icn_Error = PyMac_GetOSErrException();
+ if (Icn_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Icn_Error) != 0)
+ return;
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/launch/_Launchmodule.c b/Mac/Modules/launch/_Launchmodule.c
index fa21ece..88912b2 100644
--- a/Mac/Modules/launch/_Launchmodule.c
+++ b/Mac/Modules/launch/_Launchmodule.c
@@ -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 ======================= */
diff --git a/Mac/Modules/list/_Listmodule.c b/Mac/Modules/list/_Listmodule.c
index 0797404..3f43b06 100644
--- a/Mac/Modules/list/_Listmodule.c
+++ b/Mac/Modules/list/_Listmodule.c
@@ -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)
@@ -41,693 +41,693 @@ PyTypeObject List_Type;
#define ListObj_Check(x) ((x)->ob_type == &List_Type || PyObject_TypeCheck((x), &List_Type))
typedef struct ListObject {
- PyObject_HEAD
- ListHandle ob_itself;
- PyObject *ob_ldef_func;
- int ob_must_be_disposed;
+ PyObject_HEAD
+ ListHandle ob_itself;
+ PyObject *ob_ldef_func;
+ int ob_must_be_disposed;
} ListObject;
PyObject *ListObj_New(ListHandle itself)
{
- ListObject *it;
- if (itself == NULL) {
- PyErr_SetString(List_Error,"Cannot create null List");
- return NULL;
- }
- it = PyObject_NEW(ListObject, &List_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_ldef_func = NULL;
- it->ob_must_be_disposed = 1;
- SetListRefCon(itself, (long)it);
- return (PyObject *)it;
+ ListObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(List_Error,"Cannot create null List");
+ return NULL;
+ }
+ it = PyObject_NEW(ListObject, &List_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_ldef_func = NULL;
+ it->ob_must_be_disposed = 1;
+ SetListRefCon(itself, (long)it);
+ return (PyObject *)it;
}
int ListObj_Convert(PyObject *v, ListHandle *p_itself)
{
- if (!ListObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "List required");
- return 0;
- }
- *p_itself = ((ListObject *)v)->ob_itself;
- return 1;
+ if (!ListObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "List required");
+ return 0;
+ }
+ *p_itself = ((ListObject *)v)->ob_itself;
+ return 1;
}
static void ListObj_dealloc(ListObject *self)
{
- Py_XDECREF(self->ob_ldef_func);
- self->ob_ldef_func = NULL;
- SetListRefCon(self->ob_itself, (long)0);
- if (self->ob_must_be_disposed && self->ob_itself) LDispose(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ Py_XDECREF(self->ob_ldef_func);
+ self->ob_ldef_func = NULL;
+ SetListRefCon(self->ob_itself, (long)0);
+ if (self->ob_must_be_disposed && self->ob_itself) LDispose(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *ListObj_LAddColumn(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- short count;
- short colNum;
- if (!PyArg_ParseTuple(_args, "hh",
- &count,
- &colNum))
- return NULL;
- _rv = LAddColumn(count,
- colNum,
- _self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ short _rv;
+ short count;
+ short colNum;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &count,
+ &colNum))
+ return NULL;
+ _rv = LAddColumn(count,
+ colNum,
+ _self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *ListObj_LAddRow(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- short count;
- short rowNum;
- if (!PyArg_ParseTuple(_args, "hh",
- &count,
- &rowNum))
- return NULL;
- _rv = LAddRow(count,
- rowNum,
- _self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ short _rv;
+ short count;
+ short rowNum;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &count,
+ &rowNum))
+ return NULL;
+ _rv = LAddRow(count,
+ rowNum,
+ _self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *ListObj_LDelColumn(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short count;
- short colNum;
- if (!PyArg_ParseTuple(_args, "hh",
- &count,
- &colNum))
- return NULL;
- LDelColumn(count,
- colNum,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ short count;
+ short colNum;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &count,
+ &colNum))
+ return NULL;
+ LDelColumn(count,
+ colNum,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LDelRow(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short count;
- short rowNum;
- if (!PyArg_ParseTuple(_args, "hh",
- &count,
- &rowNum))
- return NULL;
- LDelRow(count,
- rowNum,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ short count;
+ short rowNum;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &count,
+ &rowNum))
+ return NULL;
+ LDelRow(count,
+ rowNum,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LGetSelect(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Boolean next;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "bO&",
- &next,
- PyMac_GetPoint, &theCell))
- return NULL;
- _rv = LGetSelect(next,
- &theCell,
- _self->ob_itself);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildPoint, theCell);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Boolean next;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "bO&",
+ &next,
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ _rv = LGetSelect(next,
+ &theCell,
+ _self->ob_itself);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildPoint, theCell);
+ return _res;
}
static PyObject *ListObj_LLastClick(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LLastClick(_self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, _rv);
- return _res;
+ PyObject *_res = NULL;
+ Point _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LLastClick(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, _rv);
+ return _res;
}
static PyObject *ListObj_LNextCell(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Boolean hNext;
- Boolean vNext;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "bbO&",
- &hNext,
- &vNext,
- PyMac_GetPoint, &theCell))
- return NULL;
- _rv = LNextCell(hNext,
- vNext,
- &theCell,
- _self->ob_itself);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildPoint, theCell);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Boolean hNext;
+ Boolean vNext;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "bbO&",
+ &hNext,
+ &vNext,
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ _rv = LNextCell(hNext,
+ vNext,
+ &theCell,
+ _self->ob_itself);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildPoint, theCell);
+ return _res;
}
static PyObject *ListObj_LSize(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short listWidth;
- short listHeight;
- if (!PyArg_ParseTuple(_args, "hh",
- &listWidth,
- &listHeight))
- return NULL;
- LSize(listWidth,
- listHeight,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ short listWidth;
+ short listHeight;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &listWidth,
+ &listHeight))
+ return NULL;
+ LSize(listWidth,
+ listHeight,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LSetDrawingMode(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean drawIt;
- if (!PyArg_ParseTuple(_args, "b",
- &drawIt))
- return NULL;
- LSetDrawingMode(drawIt,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Boolean drawIt;
+ if (!PyArg_ParseTuple(_args, "b",
+ &drawIt))
+ return NULL;
+ LSetDrawingMode(drawIt,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LScroll(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short dCols;
- short dRows;
- if (!PyArg_ParseTuple(_args, "hh",
- &dCols,
- &dRows))
- return NULL;
- LScroll(dCols,
- dRows,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ short dCols;
+ short dRows;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &dCols,
+ &dRows))
+ return NULL;
+ LScroll(dCols,
+ dRows,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LAutoScroll(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- LAutoScroll(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ LAutoScroll(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LUpdate(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle theRgn;
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theRgn))
- return NULL;
- LUpdate(theRgn,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ RgnHandle theRgn;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theRgn))
+ return NULL;
+ LUpdate(theRgn,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LActivate(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean act;
- if (!PyArg_ParseTuple(_args, "b",
- &act))
- return NULL;
- LActivate(act,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Boolean act;
+ if (!PyArg_ParseTuple(_args, "b",
+ &act))
+ return NULL;
+ LActivate(act,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LCellSize(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point cSize;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &cSize))
- return NULL;
- LCellSize(cSize,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Point cSize;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &cSize))
+ return NULL;
+ LCellSize(cSize,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LClick(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt;
- EventModifiers modifiers;
- if (!PyArg_ParseTuple(_args, "O&H",
- PyMac_GetPoint, &pt,
- &modifiers))
- return NULL;
- _rv = LClick(pt,
- modifiers,
- _self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt;
+ EventModifiers modifiers;
+ if (!PyArg_ParseTuple(_args, "O&H",
+ PyMac_GetPoint, &pt,
+ &modifiers))
+ return NULL;
+ _rv = LClick(pt,
+ modifiers,
+ _self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *ListObj_LAddToCell(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *dataPtr__in__;
- short dataPtr__len__;
- int dataPtr__in_len__;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "s#O&",
- &dataPtr__in__, &dataPtr__in_len__,
- PyMac_GetPoint, &theCell))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- LAddToCell(dataPtr__in__, dataPtr__len__,
- theCell,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ char *dataPtr__in__;
+ short dataPtr__len__;
+ int dataPtr__in_len__;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "s#O&",
+ &dataPtr__in__, &dataPtr__in_len__,
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ LAddToCell(dataPtr__in__, dataPtr__len__,
+ theCell,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LClrCell(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &theCell))
- return NULL;
- LClrCell(theCell,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ LClrCell(theCell,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LGetCell(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *dataPtr__out__;
- short dataPtr__len__;
- int dataPtr__in_len__;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "iO&",
- &dataPtr__in_len__,
- PyMac_GetPoint, &theCell))
- return NULL;
- if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
- {
- PyErr_NoMemory();
- goto dataPtr__error__;
- }
- dataPtr__len__ = dataPtr__in_len__;
- LGetCell(dataPtr__out__, &dataPtr__len__,
- theCell,
- _self->ob_itself);
- _res = Py_BuildValue("s#",
- dataPtr__out__, (int)dataPtr__len__);
- free(dataPtr__out__);
+ PyObject *_res = NULL;
+ char *dataPtr__out__;
+ short dataPtr__len__;
+ int dataPtr__in_len__;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "iO&",
+ &dataPtr__in_len__,
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ if ((dataPtr__out__ = malloc(dataPtr__in_len__)) == NULL)
+ {
+ PyErr_NoMemory();
+ goto dataPtr__error__;
+ }
+ dataPtr__len__ = dataPtr__in_len__;
+ LGetCell(dataPtr__out__, &dataPtr__len__,
+ theCell,
+ _self->ob_itself);
+ _res = Py_BuildValue("s#",
+ dataPtr__out__, (int)dataPtr__len__);
+ free(dataPtr__out__);
dataPtr__error__: ;
- return _res;
+ return _res;
}
static PyObject *ListObj_LRect(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect cellRect;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &theCell))
- return NULL;
- LRect(&cellRect,
- theCell,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &cellRect);
- return _res;
+ PyObject *_res = NULL;
+ Rect cellRect;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ LRect(&cellRect,
+ theCell,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &cellRect);
+ return _res;
}
static PyObject *ListObj_LSetCell(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *dataPtr__in__;
- short dataPtr__len__;
- int dataPtr__in_len__;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "s#O&",
- &dataPtr__in__, &dataPtr__in_len__,
- PyMac_GetPoint, &theCell))
- return NULL;
- dataPtr__len__ = dataPtr__in_len__;
- LSetCell(dataPtr__in__, dataPtr__len__,
- theCell,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ char *dataPtr__in__;
+ short dataPtr__len__;
+ int dataPtr__in_len__;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "s#O&",
+ &dataPtr__in__, &dataPtr__in_len__,
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ dataPtr__len__ = dataPtr__in_len__;
+ LSetCell(dataPtr__in__, dataPtr__len__,
+ theCell,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LSetSelect(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean setIt;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "bO&",
- &setIt,
- PyMac_GetPoint, &theCell))
- return NULL;
- LSetSelect(setIt,
- theCell,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Boolean setIt;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "bO&",
+ &setIt,
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ LSetSelect(setIt,
+ theCell,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LDraw(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &theCell))
- return NULL;
- LDraw(theCell,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ LDraw(theCell,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ListObj_LGetCellDataLocation(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short offset;
- short len;
- Point theCell;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &theCell))
- return NULL;
- LGetCellDataLocation(&offset,
- &len,
- theCell,
- _self->ob_itself);
- _res = Py_BuildValue("hh",
- offset,
- len);
- return _res;
+ PyObject *_res = NULL;
+ short offset;
+ short len;
+ Point theCell;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &theCell))
+ return NULL;
+ LGetCellDataLocation(&offset,
+ &len,
+ theCell,
+ _self->ob_itself);
+ _res = Py_BuildValue("hh",
+ offset,
+ len);
+ return _res;
}
static PyObject *ListObj_GetListPort(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListPort(_self->ob_itself);
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListPort(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyObject *ListObj_GetListVerticalScrollBar(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlHandle _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListVerticalScrollBar(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CtlObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ ControlHandle _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListVerticalScrollBar(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, _rv);
+ return _res;
}
static PyObject *ListObj_GetListHorizontalScrollBar(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ControlHandle _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListHorizontalScrollBar(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CtlObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ ControlHandle _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListHorizontalScrollBar(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CtlObj_New, _rv);
+ return _res;
}
static PyObject *ListObj_GetListActive(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListActive(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListActive(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *ListObj_GetListClickTime(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListClickTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ SInt32 _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListClickTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ListObj_GetListRefCon(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListRefCon(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ SInt32 _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListRefCon(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ListObj_GetListDefinition(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListDefinition(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ Handle _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListDefinition(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *ListObj_GetListUserHandle(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListUserHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ Handle _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListUserHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *ListObj_GetListDataHandle(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DataHandle _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListDataHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ DataHandle _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListDataHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *ListObj_GetListFlags(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OptionBits _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListFlags(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ OptionBits _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListFlags(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ListObj_GetListSelectionFlags(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OptionBits _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetListSelectionFlags(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyObject *_res = NULL;
+ OptionBits _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetListSelectionFlags(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ListObj_as_Resource(ListObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = as_Resource(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ Handle _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = as_Resource(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyMethodDef ListObj_methods[] = {
- {"LAddColumn", (PyCFunction)ListObj_LAddColumn, 1,
- PyDoc_STR("(short count, short colNum) -> (short _rv)")},
- {"LAddRow", (PyCFunction)ListObj_LAddRow, 1,
- PyDoc_STR("(short count, short rowNum) -> (short _rv)")},
- {"LDelColumn", (PyCFunction)ListObj_LDelColumn, 1,
- PyDoc_STR("(short count, short colNum) -> None")},
- {"LDelRow", (PyCFunction)ListObj_LDelRow, 1,
- PyDoc_STR("(short count, short rowNum) -> None")},
- {"LGetSelect", (PyCFunction)ListObj_LGetSelect, 1,
- PyDoc_STR("(Boolean next, Point theCell) -> (Boolean _rv, Point theCell)")},
- {"LLastClick", (PyCFunction)ListObj_LLastClick, 1,
- PyDoc_STR("() -> (Point _rv)")},
- {"LNextCell", (PyCFunction)ListObj_LNextCell, 1,
- PyDoc_STR("(Boolean hNext, Boolean vNext, Point theCell) -> (Boolean _rv, Point theCell)")},
- {"LSize", (PyCFunction)ListObj_LSize, 1,
- PyDoc_STR("(short listWidth, short listHeight) -> None")},
- {"LSetDrawingMode", (PyCFunction)ListObj_LSetDrawingMode, 1,
- PyDoc_STR("(Boolean drawIt) -> None")},
- {"LScroll", (PyCFunction)ListObj_LScroll, 1,
- PyDoc_STR("(short dCols, short dRows) -> None")},
- {"LAutoScroll", (PyCFunction)ListObj_LAutoScroll, 1,
- PyDoc_STR("() -> None")},
- {"LUpdate", (PyCFunction)ListObj_LUpdate, 1,
- PyDoc_STR("(RgnHandle theRgn) -> None")},
- {"LActivate", (PyCFunction)ListObj_LActivate, 1,
- PyDoc_STR("(Boolean act) -> None")},
- {"LCellSize", (PyCFunction)ListObj_LCellSize, 1,
- PyDoc_STR("(Point cSize) -> None")},
- {"LClick", (PyCFunction)ListObj_LClick, 1,
- PyDoc_STR("(Point pt, EventModifiers modifiers) -> (Boolean _rv)")},
- {"LAddToCell", (PyCFunction)ListObj_LAddToCell, 1,
- PyDoc_STR("(Buffer dataPtr, Point theCell) -> None")},
- {"LClrCell", (PyCFunction)ListObj_LClrCell, 1,
- PyDoc_STR("(Point theCell) -> None")},
- {"LGetCell", (PyCFunction)ListObj_LGetCell, 1,
- PyDoc_STR("(Buffer dataPtr, Point theCell) -> (Buffer dataPtr)")},
- {"LRect", (PyCFunction)ListObj_LRect, 1,
- PyDoc_STR("(Point theCell) -> (Rect cellRect)")},
- {"LSetCell", (PyCFunction)ListObj_LSetCell, 1,
- PyDoc_STR("(Buffer dataPtr, Point theCell) -> None")},
- {"LSetSelect", (PyCFunction)ListObj_LSetSelect, 1,
- PyDoc_STR("(Boolean setIt, Point theCell) -> None")},
- {"LDraw", (PyCFunction)ListObj_LDraw, 1,
- PyDoc_STR("(Point theCell) -> None")},
- {"LGetCellDataLocation", (PyCFunction)ListObj_LGetCellDataLocation, 1,
- PyDoc_STR("(Point theCell) -> (short offset, short len)")},
- {"GetListPort", (PyCFunction)ListObj_GetListPort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {"GetListVerticalScrollBar", (PyCFunction)ListObj_GetListVerticalScrollBar, 1,
- PyDoc_STR("() -> (ControlHandle _rv)")},
- {"GetListHorizontalScrollBar", (PyCFunction)ListObj_GetListHorizontalScrollBar, 1,
- PyDoc_STR("() -> (ControlHandle _rv)")},
- {"GetListActive", (PyCFunction)ListObj_GetListActive, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetListClickTime", (PyCFunction)ListObj_GetListClickTime, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"GetListRefCon", (PyCFunction)ListObj_GetListRefCon, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"GetListDefinition", (PyCFunction)ListObj_GetListDefinition, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"GetListUserHandle", (PyCFunction)ListObj_GetListUserHandle, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"GetListDataHandle", (PyCFunction)ListObj_GetListDataHandle, 1,
- PyDoc_STR("() -> (DataHandle _rv)")},
- {"GetListFlags", (PyCFunction)ListObj_GetListFlags, 1,
- PyDoc_STR("() -> (OptionBits _rv)")},
- {"GetListSelectionFlags", (PyCFunction)ListObj_GetListSelectionFlags, 1,
- PyDoc_STR("() -> (OptionBits _rv)")},
- {"as_Resource", (PyCFunction)ListObj_as_Resource, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {NULL, NULL, 0}
+ {"LAddColumn", (PyCFunction)ListObj_LAddColumn, 1,
+ PyDoc_STR("(short count, short colNum) -> (short _rv)")},
+ {"LAddRow", (PyCFunction)ListObj_LAddRow, 1,
+ PyDoc_STR("(short count, short rowNum) -> (short _rv)")},
+ {"LDelColumn", (PyCFunction)ListObj_LDelColumn, 1,
+ PyDoc_STR("(short count, short colNum) -> None")},
+ {"LDelRow", (PyCFunction)ListObj_LDelRow, 1,
+ PyDoc_STR("(short count, short rowNum) -> None")},
+ {"LGetSelect", (PyCFunction)ListObj_LGetSelect, 1,
+ PyDoc_STR("(Boolean next, Point theCell) -> (Boolean _rv, Point theCell)")},
+ {"LLastClick", (PyCFunction)ListObj_LLastClick, 1,
+ PyDoc_STR("() -> (Point _rv)")},
+ {"LNextCell", (PyCFunction)ListObj_LNextCell, 1,
+ PyDoc_STR("(Boolean hNext, Boolean vNext, Point theCell) -> (Boolean _rv, Point theCell)")},
+ {"LSize", (PyCFunction)ListObj_LSize, 1,
+ PyDoc_STR("(short listWidth, short listHeight) -> None")},
+ {"LSetDrawingMode", (PyCFunction)ListObj_LSetDrawingMode, 1,
+ PyDoc_STR("(Boolean drawIt) -> None")},
+ {"LScroll", (PyCFunction)ListObj_LScroll, 1,
+ PyDoc_STR("(short dCols, short dRows) -> None")},
+ {"LAutoScroll", (PyCFunction)ListObj_LAutoScroll, 1,
+ PyDoc_STR("() -> None")},
+ {"LUpdate", (PyCFunction)ListObj_LUpdate, 1,
+ PyDoc_STR("(RgnHandle theRgn) -> None")},
+ {"LActivate", (PyCFunction)ListObj_LActivate, 1,
+ PyDoc_STR("(Boolean act) -> None")},
+ {"LCellSize", (PyCFunction)ListObj_LCellSize, 1,
+ PyDoc_STR("(Point cSize) -> None")},
+ {"LClick", (PyCFunction)ListObj_LClick, 1,
+ PyDoc_STR("(Point pt, EventModifiers modifiers) -> (Boolean _rv)")},
+ {"LAddToCell", (PyCFunction)ListObj_LAddToCell, 1,
+ PyDoc_STR("(Buffer dataPtr, Point theCell) -> None")},
+ {"LClrCell", (PyCFunction)ListObj_LClrCell, 1,
+ PyDoc_STR("(Point theCell) -> None")},
+ {"LGetCell", (PyCFunction)ListObj_LGetCell, 1,
+ PyDoc_STR("(Buffer dataPtr, Point theCell) -> (Buffer dataPtr)")},
+ {"LRect", (PyCFunction)ListObj_LRect, 1,
+ PyDoc_STR("(Point theCell) -> (Rect cellRect)")},
+ {"LSetCell", (PyCFunction)ListObj_LSetCell, 1,
+ PyDoc_STR("(Buffer dataPtr, Point theCell) -> None")},
+ {"LSetSelect", (PyCFunction)ListObj_LSetSelect, 1,
+ PyDoc_STR("(Boolean setIt, Point theCell) -> None")},
+ {"LDraw", (PyCFunction)ListObj_LDraw, 1,
+ PyDoc_STR("(Point theCell) -> None")},
+ {"LGetCellDataLocation", (PyCFunction)ListObj_LGetCellDataLocation, 1,
+ PyDoc_STR("(Point theCell) -> (short offset, short len)")},
+ {"GetListPort", (PyCFunction)ListObj_GetListPort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {"GetListVerticalScrollBar", (PyCFunction)ListObj_GetListVerticalScrollBar, 1,
+ PyDoc_STR("() -> (ControlHandle _rv)")},
+ {"GetListHorizontalScrollBar", (PyCFunction)ListObj_GetListHorizontalScrollBar, 1,
+ PyDoc_STR("() -> (ControlHandle _rv)")},
+ {"GetListActive", (PyCFunction)ListObj_GetListActive, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetListClickTime", (PyCFunction)ListObj_GetListClickTime, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"GetListRefCon", (PyCFunction)ListObj_GetListRefCon, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"GetListDefinition", (PyCFunction)ListObj_GetListDefinition, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"GetListUserHandle", (PyCFunction)ListObj_GetListUserHandle, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"GetListDataHandle", (PyCFunction)ListObj_GetListDataHandle, 1,
+ PyDoc_STR("() -> (DataHandle _rv)")},
+ {"GetListFlags", (PyCFunction)ListObj_GetListFlags, 1,
+ PyDoc_STR("() -> (OptionBits _rv)")},
+ {"GetListSelectionFlags", (PyCFunction)ListObj_GetListSelectionFlags, 1,
+ PyDoc_STR("() -> (OptionBits _rv)")},
+ {"as_Resource", (PyCFunction)ListObj_as_Resource, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {NULL, NULL, 0}
};
static PyObject *ListObj_get_listFlags(ListObject *self, void *closure)
{
- return Py_BuildValue("l", (long)GetListFlags(self->ob_itself) & 0xff);
+ return Py_BuildValue("l", (long)GetListFlags(self->ob_itself) & 0xff);
}
static int ListObj_set_listFlags(ListObject *self, PyObject *v, void *closure)
{
- if (!PyArg_Parse(v, "B", &(*self->ob_itself)->listFlags)) return -1;
- return 0;
+ if (!PyArg_Parse(v, "B", &(*self->ob_itself)->listFlags)) return -1;
+ return 0;
}
static PyObject *ListObj_get_selFlags(ListObject *self, void *closure)
{
- return Py_BuildValue("l", (long)GetListSelectionFlags(self->ob_itself) & 0xff);
+ return Py_BuildValue("l", (long)GetListSelectionFlags(self->ob_itself) & 0xff);
}
static int ListObj_set_selFlags(ListObject *self, PyObject *v, void *closure)
{
- if (!PyArg_Parse(v, "B", &(*self->ob_itself)->selFlags)) return -1;
- return 0;
+ if (!PyArg_Parse(v, "B", &(*self->ob_itself)->selFlags)) return -1;
+ return 0;
}
static PyObject *ListObj_get_cellSize(ListObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->cellSize);
+ return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->cellSize);
}
static int ListObj_set_cellSize(ListObject *self, PyObject *v, void *closure)
{
- if (!PyArg_Parse(v, "O&", PyMac_GetPoint, &(*self->ob_itself)->cellSize)) return -1;
- return 0;
+ if (!PyArg_Parse(v, "O&", PyMac_GetPoint, &(*self->ob_itself)->cellSize)) return -1;
+ return 0;
}
static PyGetSetDef ListObj_getsetlist[] = {
- {"listFlags", (getter)ListObj_get_listFlags, (setter)ListObj_set_listFlags, NULL},
- {"selFlags", (getter)ListObj_get_selFlags, (setter)ListObj_set_selFlags, NULL},
- {"cellSize", (getter)ListObj_get_cellSize, (setter)ListObj_set_cellSize, NULL},
- {NULL, NULL, NULL, NULL},
+ {"listFlags", (getter)ListObj_get_listFlags, (setter)ListObj_set_listFlags, NULL},
+ {"selFlags", (getter)ListObj_get_selFlags, (setter)ListObj_set_selFlags, NULL},
+ {"cellSize", (getter)ListObj_get_cellSize, (setter)ListObj_set_cellSize, NULL},
+ {NULL, NULL, NULL, NULL},
};
@@ -742,61 +742,61 @@ static PyGetSetDef ListObj_getsetlist[] = {
static PyObject *ListObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- ListHandle itself;
- char *kw[] = {"itself", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, ListObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((ListObject *)_self)->ob_itself = itself;
- return _self;
+ PyObject *_self;
+ ListHandle itself;
+ char *kw[] = {"itself", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, ListObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((ListObject *)_self)->ob_itself = itself;
+ return _self;
}
#define ListObj_tp_free PyObject_Del
PyTypeObject List_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_List.List", /*tp_name*/
- sizeof(ListObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) ListObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) ListObj_compare, /*tp_compare*/
- (reprfunc) ListObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) ListObj_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*/
- ListObj_methods, /* tp_methods */
- 0, /*tp_members*/
- ListObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- ListObj_tp_init, /* tp_init */
- ListObj_tp_alloc, /* tp_alloc */
- ListObj_tp_new, /* tp_new */
- ListObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_List.List", /*tp_name*/
+ sizeof(ListObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) ListObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) ListObj_compare, /*tp_compare*/
+ (reprfunc) ListObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) ListObj_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*/
+ ListObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ ListObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ ListObj_tp_init, /* tp_init */
+ ListObj_tp_alloc, /* tp_alloc */
+ ListObj_tp_new, /* tp_new */
+ ListObj_tp_free, /* tp_free */
};
/* ---------------------- End object type List ---------------------- */
@@ -804,263 +804,263 @@ PyTypeObject List_Type = {
static PyObject *List_CreateCustomList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rView;
- Rect dataBounds;
- Point cellSize;
-
- PyObject *listDefFunc;
- ListDefSpec theSpec;
- WindowPtr theWindow;
- Boolean drawIt;
- Boolean hasGrow;
- Boolean scrollHoriz;
- Boolean scrollVert;
- ListHandle outList;
-
- if (!PyArg_ParseTuple(_args, "O&O&O&(iO)O&bbbb",
- PyMac_GetRect, &rView,
- PyMac_GetRect, &dataBounds,
- PyMac_GetPoint, &cellSize,
- &theSpec.defType, &listDefFunc,
- WinObj_Convert, &theWindow,
- &drawIt,
- &hasGrow,
- &scrollHoriz,
- &scrollVert))
- return NULL;
-
-
- /* Carbon applications use the CreateCustomList API */
- theSpec.u.userProc = myListDefFunctionUPP;
- CreateCustomList(&rView,
- &dataBounds,
- cellSize,
- &theSpec,
- theWindow,
- drawIt,
- hasGrow,
- scrollHoriz,
- scrollVert,
- &outList);
-
-
- _res = ListObj_New(outList);
- if (_res == NULL)
- return NULL;
- Py_INCREF(listDefFunc);
- ((ListObject*)_res)->ob_ldef_func = listDefFunc;
- return _res;
+ PyObject *_res = NULL;
+ Rect rView;
+ Rect dataBounds;
+ Point cellSize;
+
+ PyObject *listDefFunc;
+ ListDefSpec theSpec;
+ WindowPtr theWindow;
+ Boolean drawIt;
+ Boolean hasGrow;
+ Boolean scrollHoriz;
+ Boolean scrollVert;
+ ListHandle outList;
+
+ if (!PyArg_ParseTuple(_args, "O&O&O&(iO)O&bbbb",
+ PyMac_GetRect, &rView,
+ PyMac_GetRect, &dataBounds,
+ PyMac_GetPoint, &cellSize,
+ &theSpec.defType, &listDefFunc,
+ WinObj_Convert, &theWindow,
+ &drawIt,
+ &hasGrow,
+ &scrollHoriz,
+ &scrollVert))
+ return NULL;
+
+
+ /* Carbon applications use the CreateCustomList API */
+ theSpec.u.userProc = myListDefFunctionUPP;
+ CreateCustomList(&rView,
+ &dataBounds,
+ cellSize,
+ &theSpec,
+ theWindow,
+ drawIt,
+ hasGrow,
+ scrollHoriz,
+ scrollVert,
+ &outList);
+
+
+ _res = ListObj_New(outList);
+ if (_res == NULL)
+ return NULL;
+ Py_INCREF(listDefFunc);
+ ((ListObject*)_res)->ob_ldef_func = listDefFunc;
+ return _res;
}
static PyObject *List_LNew(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle _rv;
- Rect rView;
- Rect dataBounds;
- Point cSize;
- short theProc;
- WindowPtr theWindow;
- Boolean drawIt;
- Boolean hasGrow;
- Boolean scrollHoriz;
- Boolean scrollVert;
- if (!PyArg_ParseTuple(_args, "O&O&O&hO&bbbb",
- PyMac_GetRect, &rView,
- PyMac_GetRect, &dataBounds,
- PyMac_GetPoint, &cSize,
- &theProc,
- WinObj_Convert, &theWindow,
- &drawIt,
- &hasGrow,
- &scrollHoriz,
- &scrollVert))
- return NULL;
- _rv = LNew(&rView,
- &dataBounds,
- cSize,
- theProc,
- theWindow,
- drawIt,
- hasGrow,
- scrollHoriz,
- scrollVert);
- _res = Py_BuildValue("O&",
- ListObj_New, _rv);
- return _res;
+ PyObject *_res = NULL;
+ ListHandle _rv;
+ Rect rView;
+ Rect dataBounds;
+ Point cSize;
+ short theProc;
+ WindowPtr theWindow;
+ Boolean drawIt;
+ Boolean hasGrow;
+ Boolean scrollHoriz;
+ Boolean scrollVert;
+ if (!PyArg_ParseTuple(_args, "O&O&O&hO&bbbb",
+ PyMac_GetRect, &rView,
+ PyMac_GetRect, &dataBounds,
+ PyMac_GetPoint, &cSize,
+ &theProc,
+ WinObj_Convert, &theWindow,
+ &drawIt,
+ &hasGrow,
+ &scrollHoriz,
+ &scrollVert))
+ return NULL;
+ _rv = LNew(&rView,
+ &dataBounds,
+ cSize,
+ theProc,
+ theWindow,
+ drawIt,
+ hasGrow,
+ scrollHoriz,
+ scrollVert);
+ _res = Py_BuildValue("O&",
+ ListObj_New, _rv);
+ return _res;
}
static PyObject *List_SetListViewBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- Rect view;
- if (!PyArg_ParseTuple(_args, "O&O&",
- ListObj_Convert, &list,
- PyMac_GetRect, &view))
- return NULL;
- SetListViewBounds(list,
- &view);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ Rect view;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ListObj_Convert, &list,
+ PyMac_GetRect, &view))
+ return NULL;
+ SetListViewBounds(list,
+ &view);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- CGrafPtr port;
- if (!PyArg_ParseTuple(_args, "O&O&",
- ListObj_Convert, &list,
- GrafObj_Convert, &port))
- return NULL;
- SetListPort(list,
- port);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ CGrafPtr port;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ListObj_Convert, &list,
+ GrafObj_Convert, &port))
+ return NULL;
+ SetListPort(list,
+ port);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListCellIndent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- Point indent;
- if (!PyArg_ParseTuple(_args, "O&O&",
- ListObj_Convert, &list,
- PyMac_GetPoint, &indent))
- return NULL;
- SetListCellIndent(list,
- &indent);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ Point indent;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ListObj_Convert, &list,
+ PyMac_GetPoint, &indent))
+ return NULL;
+ SetListCellIndent(list,
+ &indent);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListClickTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- SInt32 time;
- if (!PyArg_ParseTuple(_args, "O&l",
- ListObj_Convert, &list,
- &time))
- return NULL;
- SetListClickTime(list,
- time);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ SInt32 time;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ListObj_Convert, &list,
+ &time))
+ return NULL;
+ SetListClickTime(list,
+ time);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- SInt32 refCon;
- if (!PyArg_ParseTuple(_args, "O&l",
- ListObj_Convert, &list,
- &refCon))
- return NULL;
- SetListRefCon(list,
- refCon);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ SInt32 refCon;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ListObj_Convert, &list,
+ &refCon))
+ return NULL;
+ SetListRefCon(list,
+ refCon);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListUserHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- Handle userHandle;
- if (!PyArg_ParseTuple(_args, "O&O&",
- ListObj_Convert, &list,
- ResObj_Convert, &userHandle))
- return NULL;
- SetListUserHandle(list,
- userHandle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ Handle userHandle;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ListObj_Convert, &list,
+ ResObj_Convert, &userHandle))
+ return NULL;
+ SetListUserHandle(list,
+ userHandle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- OptionBits listFlags;
- if (!PyArg_ParseTuple(_args, "O&l",
- ListObj_Convert, &list,
- &listFlags))
- return NULL;
- SetListFlags(list,
- listFlags);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ OptionBits listFlags;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ListObj_Convert, &list,
+ &listFlags))
+ return NULL;
+ SetListFlags(list,
+ listFlags);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_SetListSelectionFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ListHandle list;
- OptionBits selectionFlags;
- if (!PyArg_ParseTuple(_args, "O&l",
- ListObj_Convert, &list,
- &selectionFlags))
- return NULL;
- SetListSelectionFlags(list,
- selectionFlags);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ ListHandle list;
+ OptionBits selectionFlags;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ListObj_Convert, &list,
+ &selectionFlags))
+ return NULL;
+ SetListSelectionFlags(list,
+ selectionFlags);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *List_as_List(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- Handle h;
- ListObject *l;
- if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &h))
- return NULL;
- l = (ListObject *)ListObj_New(as_List(h));
- l->ob_must_be_disposed = 0;
- _res = Py_BuildValue("O", l);
- return _res;
+ Handle h;
+ ListObject *l;
+ if (!PyArg_ParseTuple(_args, "O&", ResObj_Convert, &h))
+ return NULL;
+ l = (ListObject *)ListObj_New(as_List(h));
+ l->ob_must_be_disposed = 0;
+ _res = Py_BuildValue("O", l);
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef List_methods[] = {
#ifndef __LP64__
- {"CreateCustomList", (PyCFunction)List_CreateCustomList, 1,
- PyDoc_STR("(Rect rView, Rect dataBounds, Point cellSize, ListDefSpec theSpec, WindowPtr theWindow, Boolean drawIt, Boolean hasGrow, Boolean scrollHoriz, Boolean scrollVert) -> (ListHandle outList)")},
- {"LNew", (PyCFunction)List_LNew, 1,
- PyDoc_STR("(Rect rView, Rect dataBounds, Point cSize, short theProc, WindowPtr theWindow, Boolean drawIt, Boolean hasGrow, Boolean scrollHoriz, Boolean scrollVert) -> (ListHandle _rv)")},
- {"SetListViewBounds", (PyCFunction)List_SetListViewBounds, 1,
- PyDoc_STR("(ListHandle list, Rect view) -> None")},
- {"SetListPort", (PyCFunction)List_SetListPort, 1,
- PyDoc_STR("(ListHandle list, CGrafPtr port) -> None")},
- {"SetListCellIndent", (PyCFunction)List_SetListCellIndent, 1,
- PyDoc_STR("(ListHandle list, Point indent) -> None")},
- {"SetListClickTime", (PyCFunction)List_SetListClickTime, 1,
- PyDoc_STR("(ListHandle list, SInt32 time) -> None")},
- {"SetListRefCon", (PyCFunction)List_SetListRefCon, 1,
- PyDoc_STR("(ListHandle list, SInt32 refCon) -> None")},
- {"SetListUserHandle", (PyCFunction)List_SetListUserHandle, 1,
- PyDoc_STR("(ListHandle list, Handle userHandle) -> None")},
- {"SetListFlags", (PyCFunction)List_SetListFlags, 1,
- PyDoc_STR("(ListHandle list, OptionBits listFlags) -> None")},
- {"SetListSelectionFlags", (PyCFunction)List_SetListSelectionFlags, 1,
- PyDoc_STR("(ListHandle list, OptionBits selectionFlags) -> None")},
- {"as_List", (PyCFunction)List_as_List, 1,
- PyDoc_STR("(Resource)->List.\nReturns List object (which is not auto-freed!)")},
+ {"CreateCustomList", (PyCFunction)List_CreateCustomList, 1,
+ PyDoc_STR("(Rect rView, Rect dataBounds, Point cellSize, ListDefSpec theSpec, WindowPtr theWindow, Boolean drawIt, Boolean hasGrow, Boolean scrollHoriz, Boolean scrollVert) -> (ListHandle outList)")},
+ {"LNew", (PyCFunction)List_LNew, 1,
+ PyDoc_STR("(Rect rView, Rect dataBounds, Point cSize, short theProc, WindowPtr theWindow, Boolean drawIt, Boolean hasGrow, Boolean scrollHoriz, Boolean scrollVert) -> (ListHandle _rv)")},
+ {"SetListViewBounds", (PyCFunction)List_SetListViewBounds, 1,
+ PyDoc_STR("(ListHandle list, Rect view) -> None")},
+ {"SetListPort", (PyCFunction)List_SetListPort, 1,
+ PyDoc_STR("(ListHandle list, CGrafPtr port) -> None")},
+ {"SetListCellIndent", (PyCFunction)List_SetListCellIndent, 1,
+ PyDoc_STR("(ListHandle list, Point indent) -> None")},
+ {"SetListClickTime", (PyCFunction)List_SetListClickTime, 1,
+ PyDoc_STR("(ListHandle list, SInt32 time) -> None")},
+ {"SetListRefCon", (PyCFunction)List_SetListRefCon, 1,
+ PyDoc_STR("(ListHandle list, SInt32 refCon) -> None")},
+ {"SetListUserHandle", (PyCFunction)List_SetListUserHandle, 1,
+ PyDoc_STR("(ListHandle list, Handle userHandle) -> None")},
+ {"SetListFlags", (PyCFunction)List_SetListFlags, 1,
+ PyDoc_STR("(ListHandle list, OptionBits listFlags) -> None")},
+ {"SetListSelectionFlags", (PyCFunction)List_SetListSelectionFlags, 1,
+ PyDoc_STR("(ListHandle list, OptionBits selectionFlags) -> None")},
+ {"as_List", (PyCFunction)List_as_List, 1,
+ PyDoc_STR("(Resource)->List.\nReturns List object (which is not auto-freed!)")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#ifndef __LP64__
@@ -1074,65 +1074,65 @@ static void myListDefFunction(SInt16 message,
SInt16 dataLen,
ListHandle theList)
{
- PyObject *listDefFunc, *args, *rv=NULL;
- ListObject *self;
-
- self = (ListObject*)GetListRefCon(theList);
- if (self == NULL || self->ob_itself != theList)
- return; /* nothing we can do */
- listDefFunc = self->ob_ldef_func;
- if (listDefFunc == NULL)
- return; /* nothing we can do */
- args = Py_BuildValue("hbO&O&hhO", message,
- selected,
- PyMac_BuildRect, cellRect,
- PyMac_BuildPoint, theCell,
- dataOffset,
- dataLen,
- self);
- if (args != NULL) {
- rv = PyEval_CallObject(listDefFunc, args);
- Py_DECREF(args);
- }
- if (rv == NULL) {
- PySys_WriteStderr("error in list definition callback:\n");
- PyErr_Print();
- } else {
- Py_DECREF(rv);
- }
+ PyObject *listDefFunc, *args, *rv=NULL;
+ ListObject *self;
+
+ self = (ListObject*)GetListRefCon(theList);
+ if (self == NULL || self->ob_itself != theList)
+ return; /* nothing we can do */
+ listDefFunc = self->ob_ldef_func;
+ if (listDefFunc == NULL)
+ return; /* nothing we can do */
+ args = Py_BuildValue("hbO&O&hhO", message,
+ selected,
+ PyMac_BuildRect, cellRect,
+ PyMac_BuildPoint, theCell,
+ dataOffset,
+ dataLen,
+ self);
+ if (args != NULL) {
+ rv = PyEval_CallObject(listDefFunc, args);
+ Py_DECREF(args);
+ }
+ if (rv == NULL) {
+ PySys_WriteStderr("error in list definition callback:\n");
+ PyErr_Print();
+ } else {
+ Py_DECREF(rv);
+ }
}
#endif /* __LP64__ */
void init_List(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- myListDefFunctionUPP = NewListDefUPP((ListDefProcPtr)myListDefFunction);
+ myListDefFunctionUPP = NewListDefUPP((ListDefProcPtr)myListDefFunction);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(ListHandle, ListObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ListHandle, ListObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(ListHandle, ListObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ListHandle, ListObj_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_List", List_methods);
+ m = Py_InitModule("_List", List_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- List_Error = PyMac_GetOSErrException();
- if (List_Error == NULL ||
- PyDict_SetItemString(d, "Error", List_Error) != 0)
- return;
- List_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&List_Type) < 0) return;
- Py_INCREF(&List_Type);
- PyModule_AddObject(m, "List", (PyObject *)&List_Type);
- /* Backward-compatible name */
- Py_INCREF(&List_Type);
- PyModule_AddObject(m, "ListType", (PyObject *)&List_Type);
+ d = PyModule_GetDict(m);
+ List_Error = PyMac_GetOSErrException();
+ if (List_Error == NULL ||
+ PyDict_SetItemString(d, "Error", List_Error) != 0)
+ return;
+ List_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&List_Type) < 0) return;
+ Py_INCREF(&List_Type);
+ PyModule_AddObject(m, "List", (PyObject *)&List_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&List_Type);
+ PyModule_AddObject(m, "ListType", (PyObject *)&List_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/menu/_Menumodule.c b/Mac/Modules/menu/_Menumodule.c
index 66ebf79..dbb075c 100644
--- a/Mac/Modules/menu/_Menumodule.c
+++ b/Mac/Modules/menu/_Menumodule.c
@@ -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)
@@ -35,21 +35,21 @@ extern int _MenuObj_Convert(PyObject *, MenuHandle *);
/* Alternative version of MenuObj_New, which returns None for NULL argument */
PyObject *OptMenuObj_New(MenuRef itself)
{
- if (itself == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return MenuObj_New(itself);
+ if (itself == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return MenuObj_New(itself);
}
/* Alternative version of MenuObj_Convert, which returns NULL for a None argument */
int OptMenuObj_Convert(PyObject *v, MenuRef *p_itself)
{
- if ( v == Py_None ) {
- *p_itself = NULL;
- return 1;
- }
- return MenuObj_Convert(v, p_itself);
+ if ( v == Py_None ) {
+ *p_itself = NULL;
+ return 1;
+ }
+ return MenuObj_Convert(v, p_itself);
}
static PyObject *Menu_Error;
@@ -61,2469 +61,2469 @@ PyTypeObject Menu_Type;
#define MenuObj_Check(x) ((x)->ob_type == &Menu_Type || PyObject_TypeCheck((x), &Menu_Type))
typedef struct MenuObject {
- PyObject_HEAD
- MenuHandle ob_itself;
+ PyObject_HEAD
+ MenuHandle ob_itself;
} MenuObject;
PyObject *MenuObj_New(MenuHandle itself)
{
- MenuObject *it;
- it = PyObject_NEW(MenuObject, &Menu_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ MenuObject *it;
+ it = PyObject_NEW(MenuObject, &Menu_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int MenuObj_Convert(PyObject *v, MenuHandle *p_itself)
{
- if (!MenuObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Menu required");
- return 0;
- }
- *p_itself = ((MenuObject *)v)->ob_itself;
- return 1;
+ if (!MenuObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Menu required");
+ return 0;
+ }
+ *p_itself = ((MenuObject *)v)->ob_itself;
+ return 1;
}
static void MenuObj_dealloc(MenuObject *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 *MenuObj_DisposeMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DisposeMenu
- PyMac_PRECHECK(DisposeMenu);
+ PyMac_PRECHECK(DisposeMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DisposeMenu(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DisposeMenu(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_CalcMenuSize(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CalcMenuSize
- PyMac_PRECHECK(CalcMenuSize);
+ PyMac_PRECHECK(CalcMenuSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CalcMenuSize(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CalcMenuSize(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_CountMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt16 _rv;
+ PyObject *_res = NULL;
+ UInt16 _rv;
#ifndef CountMenuItems
- PyMac_PRECHECK(CountMenuItems);
+ PyMac_PRECHECK(CountMenuItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CountMenuItems(_self->ob_itself);
- _res = Py_BuildValue("H",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CountMenuItems(_self->ob_itself);
+ _res = Py_BuildValue("H",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_GetMenuFont(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 outFontID;
- UInt16 outFontSize;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 outFontID;
+ UInt16 outFontSize;
#ifndef GetMenuFont
- PyMac_PRECHECK(GetMenuFont);
+ PyMac_PRECHECK(GetMenuFont);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMenuFont(_self->ob_itself,
- &outFontID,
- &outFontSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hH",
- outFontID,
- outFontSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMenuFont(_self->ob_itself,
+ &outFontID,
+ &outFontSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hH",
+ outFontID,
+ outFontSize);
+ return _res;
}
static PyObject *MenuObj_SetMenuFont(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 inFontID;
- UInt16 inFontSize;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 inFontID;
+ UInt16 inFontSize;
#ifndef SetMenuFont
- PyMac_PRECHECK(SetMenuFont);
+ PyMac_PRECHECK(SetMenuFont);
#endif
- if (!PyArg_ParseTuple(_args, "hH",
- &inFontID,
- &inFontSize))
- return NULL;
- _err = SetMenuFont(_self->ob_itself,
- inFontID,
- inFontSize);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hH",
+ &inFontID,
+ &inFontSize))
+ return NULL;
+ _err = SetMenuFont(_self->ob_itself,
+ inFontID,
+ inFontSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuExcludesMarkColumn(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef GetMenuExcludesMarkColumn
- PyMac_PRECHECK(GetMenuExcludesMarkColumn);
+ PyMac_PRECHECK(GetMenuExcludesMarkColumn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMenuExcludesMarkColumn(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMenuExcludesMarkColumn(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_SetMenuExcludesMarkColumn(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean excludesMark;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean excludesMark;
#ifndef SetMenuExcludesMarkColumn
- PyMac_PRECHECK(SetMenuExcludesMarkColumn);
+ PyMac_PRECHECK(SetMenuExcludesMarkColumn);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &excludesMark))
- return NULL;
- _err = SetMenuExcludesMarkColumn(_self->ob_itself,
- excludesMark);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &excludesMark))
+ return NULL;
+ _err = SetMenuExcludesMarkColumn(_self->ob_itself,
+ excludesMark);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsValidMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsValidMenu
- PyMac_PRECHECK(IsValidMenu);
+ PyMac_PRECHECK(IsValidMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsValidMenu(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsValidMenu(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_GetMenuRetainCount(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ItemCount _rv;
+ PyObject *_res = NULL;
+ ItemCount _rv;
#ifndef GetMenuRetainCount
- PyMac_PRECHECK(GetMenuRetainCount);
+ PyMac_PRECHECK(GetMenuRetainCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMenuRetainCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMenuRetainCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_RetainMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef RetainMenu
- PyMac_PRECHECK(RetainMenu);
+ PyMac_PRECHECK(RetainMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = RetainMenu(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = RetainMenu(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_ReleaseMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef ReleaseMenu
- PyMac_PRECHECK(ReleaseMenu);
+ PyMac_PRECHECK(ReleaseMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = ReleaseMenu(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = ReleaseMenu(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DuplicateMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle outMenu;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle outMenu;
#ifndef DuplicateMenu
- PyMac_PRECHECK(DuplicateMenu);
+ PyMac_PRECHECK(DuplicateMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = DuplicateMenu(_self->ob_itself,
- &outMenu);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- MenuObj_New, outMenu);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = DuplicateMenu(_self->ob_itself,
+ &outMenu);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, outMenu);
+ return _res;
}
static PyObject *MenuObj_CopyMenuTitleAsCFString(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef outString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef outString;
#ifndef CopyMenuTitleAsCFString
- PyMac_PRECHECK(CopyMenuTitleAsCFString);
+ PyMac_PRECHECK(CopyMenuTitleAsCFString);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CopyMenuTitleAsCFString(_self->ob_itself,
- &outString);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, outString);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CopyMenuTitleAsCFString(_self->ob_itself,
+ &outString);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, outString);
+ return _res;
}
static PyObject *MenuObj_SetMenuTitleWithCFString(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
#ifndef SetMenuTitleWithCFString
- PyMac_PRECHECK(SetMenuTitleWithCFString);
+ PyMac_PRECHECK(SetMenuTitleWithCFString);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &inString))
- return NULL;
- _err = SetMenuTitleWithCFString(_self->ob_itself,
- inString);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &inString))
+ return NULL;
+ _err = SetMenuTitleWithCFString(_self->ob_itself,
+ inString);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InvalidateMenuSize(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef InvalidateMenuSize
- PyMac_PRECHECK(InvalidateMenuSize);
+ PyMac_PRECHECK(InvalidateMenuSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = InvalidateMenuSize(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = InvalidateMenuSize(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsMenuSizeInvalid(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsMenuSizeInvalid
- PyMac_PRECHECK(IsMenuSizeInvalid);
+ PyMac_PRECHECK(IsMenuSizeInvalid);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsMenuSizeInvalid(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsMenuSizeInvalid(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_MacAppendMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 data;
+ PyObject *_res = NULL;
+ Str255 data;
#ifndef MacAppendMenu
- PyMac_PRECHECK(MacAppendMenu);
+ PyMac_PRECHECK(MacAppendMenu);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, data))
- return NULL;
- MacAppendMenu(_self->ob_itself,
- data);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, data))
+ return NULL;
+ MacAppendMenu(_self->ob_itself,
+ data);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InsertResMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ResType theType;
- short afterItem;
+ PyObject *_res = NULL;
+ ResType theType;
+ short afterItem;
#ifndef InsertResMenu
- PyMac_PRECHECK(InsertResMenu);
+ PyMac_PRECHECK(InsertResMenu);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetOSType, &theType,
- &afterItem))
- return NULL;
- InsertResMenu(_self->ob_itself,
- theType,
- afterItem);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetOSType, &theType,
+ &afterItem))
+ return NULL;
+ InsertResMenu(_self->ob_itself,
+ theType,
+ afterItem);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_AppendResMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ResType theType;
+ PyObject *_res = NULL;
+ ResType theType;
#ifndef AppendResMenu
- PyMac_PRECHECK(AppendResMenu);
+ PyMac_PRECHECK(AppendResMenu);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theType))
- return NULL;
- AppendResMenu(_self->ob_itself,
- theType);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theType))
+ return NULL;
+ AppendResMenu(_self->ob_itself,
+ theType);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_MacInsertMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 itemString;
- short afterItem;
+ PyObject *_res = NULL;
+ Str255 itemString;
+ short afterItem;
#ifndef MacInsertMenuItem
- PyMac_PRECHECK(MacInsertMenuItem);
+ PyMac_PRECHECK(MacInsertMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetStr255, itemString,
- &afterItem))
- return NULL;
- MacInsertMenuItem(_self->ob_itself,
- itemString,
- afterItem);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetStr255, itemString,
+ &afterItem))
+ return NULL;
+ MacInsertMenuItem(_self->ob_itself,
+ itemString,
+ afterItem);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DeleteMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
+ PyObject *_res = NULL;
+ short item;
#ifndef DeleteMenuItem
- PyMac_PRECHECK(DeleteMenuItem);
+ PyMac_PRECHECK(DeleteMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- DeleteMenuItem(_self->ob_itself,
- item);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ DeleteMenuItem(_self->ob_itself,
+ item);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InsertFontResMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short afterItem;
- short scriptFilter;
+ PyObject *_res = NULL;
+ short afterItem;
+ short scriptFilter;
#ifndef InsertFontResMenu
- PyMac_PRECHECK(InsertFontResMenu);
+ PyMac_PRECHECK(InsertFontResMenu);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &afterItem,
- &scriptFilter))
- return NULL;
- InsertFontResMenu(_self->ob_itself,
- afterItem,
- scriptFilter);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &afterItem,
+ &scriptFilter))
+ return NULL;
+ InsertFontResMenu(_self->ob_itself,
+ afterItem,
+ scriptFilter);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InsertIntlResMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ResType theType;
- short afterItem;
- short scriptFilter;
+ PyObject *_res = NULL;
+ ResType theType;
+ short afterItem;
+ short scriptFilter;
#ifndef InsertIntlResMenu
- PyMac_PRECHECK(InsertIntlResMenu);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetOSType, &theType,
- &afterItem,
- &scriptFilter))
- return NULL;
- InsertIntlResMenu(_self->ob_itself,
- theType,
- afterItem,
- scriptFilter);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(InsertIntlResMenu);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetOSType, &theType,
+ &afterItem,
+ &scriptFilter))
+ return NULL;
+ InsertIntlResMenu(_self->ob_itself,
+ theType,
+ afterItem,
+ scriptFilter);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_AppendMenuItemText(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Str255 inString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Str255 inString;
#ifndef AppendMenuItemText
- PyMac_PRECHECK(AppendMenuItemText);
+ PyMac_PRECHECK(AppendMenuItemText);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, inString))
- return NULL;
- _err = AppendMenuItemText(_self->ob_itself,
- inString);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, inString))
+ return NULL;
+ _err = AppendMenuItemText(_self->ob_itself,
+ inString);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InsertMenuItemText(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Str255 inString;
- MenuItemIndex afterItem;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Str255 inString;
+ MenuItemIndex afterItem;
#ifndef InsertMenuItemText
- PyMac_PRECHECK(InsertMenuItemText);
+ PyMac_PRECHECK(InsertMenuItemText);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetStr255, inString,
- &afterItem))
- return NULL;
- _err = InsertMenuItemText(_self->ob_itself,
- inString,
- afterItem);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetStr255, inString,
+ &afterItem))
+ return NULL;
+ _err = InsertMenuItemText(_self->ob_itself,
+ inString,
+ afterItem);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_CopyMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inFirstItem;
- ItemCount inNumItems;
- MenuHandle inDestMenu;
- MenuItemIndex inInsertAfter;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inFirstItem;
+ ItemCount inNumItems;
+ MenuHandle inDestMenu;
+ MenuItemIndex inInsertAfter;
#ifndef CopyMenuItems
- PyMac_PRECHECK(CopyMenuItems);
-#endif
- if (!PyArg_ParseTuple(_args, "hlO&h",
- &inFirstItem,
- &inNumItems,
- MenuObj_Convert, &inDestMenu,
- &inInsertAfter))
- return NULL;
- _err = CopyMenuItems(_self->ob_itself,
- inFirstItem,
- inNumItems,
- inDestMenu,
- inInsertAfter);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CopyMenuItems);
+#endif
+ if (!PyArg_ParseTuple(_args, "hlO&h",
+ &inFirstItem,
+ &inNumItems,
+ MenuObj_Convert, &inDestMenu,
+ &inInsertAfter))
+ return NULL;
+ _err = CopyMenuItems(_self->ob_itself,
+ inFirstItem,
+ inNumItems,
+ inDestMenu,
+ inInsertAfter);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DeleteMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inFirstItem;
- ItemCount inNumItems;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inFirstItem;
+ ItemCount inNumItems;
#ifndef DeleteMenuItems
- PyMac_PRECHECK(DeleteMenuItems);
+ PyMac_PRECHECK(DeleteMenuItems);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inFirstItem,
- &inNumItems))
- return NULL;
- _err = DeleteMenuItems(_self->ob_itself,
- inFirstItem,
- inNumItems);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inFirstItem,
+ &inNumItems))
+ return NULL;
+ _err = DeleteMenuItems(_self->ob_itself,
+ inFirstItem,
+ inNumItems);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_AppendMenuItemTextWithCFString(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
- MenuItemAttributes inAttributes;
- MenuCommand inCommandID;
- MenuItemIndex outNewItem;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
+ MenuItemAttributes inAttributes;
+ MenuCommand inCommandID;
+ MenuItemIndex outNewItem;
#ifndef AppendMenuItemTextWithCFString
- PyMac_PRECHECK(AppendMenuItemTextWithCFString);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CFStringRefObj_Convert, &inString,
- &inAttributes,
- &inCommandID))
- return NULL;
- _err = AppendMenuItemTextWithCFString(_self->ob_itself,
- inString,
- inAttributes,
- inCommandID,
- &outNewItem);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outNewItem);
- return _res;
+ PyMac_PRECHECK(AppendMenuItemTextWithCFString);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CFStringRefObj_Convert, &inString,
+ &inAttributes,
+ &inCommandID))
+ return NULL;
+ _err = AppendMenuItemTextWithCFString(_self->ob_itself,
+ inString,
+ inAttributes,
+ inCommandID,
+ &outNewItem);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outNewItem);
+ return _res;
}
static PyObject *MenuObj_InsertMenuItemTextWithCFString(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
- MenuItemIndex inAfterItem;
- MenuItemAttributes inAttributes;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
+ MenuItemIndex inAfterItem;
+ MenuItemAttributes inAttributes;
+ MenuCommand inCommandID;
#ifndef InsertMenuItemTextWithCFString
- PyMac_PRECHECK(InsertMenuItemTextWithCFString);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hll",
- CFStringRefObj_Convert, &inString,
- &inAfterItem,
- &inAttributes,
- &inCommandID))
- return NULL;
- _err = InsertMenuItemTextWithCFString(_self->ob_itself,
- inString,
- inAfterItem,
- inAttributes,
- inCommandID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(InsertMenuItemTextWithCFString);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hll",
+ CFStringRefObj_Convert, &inString,
+ &inAfterItem,
+ &inAttributes,
+ &inCommandID))
+ return NULL;
+ _err = InsertMenuItemTextWithCFString(_self->ob_itself,
+ inString,
+ inAfterItem,
+ inAttributes,
+ inCommandID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_PopUpMenuSelect(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- short top;
- short left;
- short popUpItem;
+ PyObject *_res = NULL;
+ long _rv;
+ short top;
+ short left;
+ short popUpItem;
#ifndef PopUpMenuSelect
- PyMac_PRECHECK(PopUpMenuSelect);
-#endif
- if (!PyArg_ParseTuple(_args, "hhh",
- &top,
- &left,
- &popUpItem))
- return NULL;
- _rv = PopUpMenuSelect(_self->ob_itself,
- top,
- left,
- popUpItem);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(PopUpMenuSelect);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhh",
+ &top,
+ &left,
+ &popUpItem))
+ return NULL;
+ _rv = PopUpMenuSelect(_self->ob_itself,
+ top,
+ left,
+ popUpItem);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_InvalidateMenuEnabling(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef InvalidateMenuEnabling
- PyMac_PRECHECK(InvalidateMenuEnabling);
+ PyMac_PRECHECK(InvalidateMenuEnabling);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = InvalidateMenuEnabling(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = InvalidateMenuEnabling(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsMenuBarInvalid(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsMenuBarInvalid
- PyMac_PRECHECK(IsMenuBarInvalid);
+ PyMac_PRECHECK(IsMenuBarInvalid);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsMenuBarInvalid(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsMenuBarInvalid(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_MacInsertMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID beforeID;
+ PyObject *_res = NULL;
+ MenuID beforeID;
#ifndef MacInsertMenu
- PyMac_PRECHECK(MacInsertMenu);
+ PyMac_PRECHECK(MacInsertMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &beforeID))
- return NULL;
- MacInsertMenu(_self->ob_itself,
- beforeID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &beforeID))
+ return NULL;
+ MacInsertMenu(_self->ob_itself,
+ beforeID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_SetRootMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef SetRootMenu
- PyMac_PRECHECK(SetRootMenu);
+ PyMac_PRECHECK(SetRootMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = SetRootMenu(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = SetRootMenu(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_MacCheckMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- Boolean checked;
+ PyObject *_res = NULL;
+ short item;
+ Boolean checked;
#ifndef MacCheckMenuItem
- PyMac_PRECHECK(MacCheckMenuItem);
+ PyMac_PRECHECK(MacCheckMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &item,
- &checked))
- return NULL;
- MacCheckMenuItem(_self->ob_itself,
- item,
- checked);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &item,
+ &checked))
+ return NULL;
+ MacCheckMenuItem(_self->ob_itself,
+ item,
+ checked);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_SetMenuItemText(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- Str255 itemString;
+ PyObject *_res = NULL;
+ short item;
+ Str255 itemString;
#ifndef SetMenuItemText
- PyMac_PRECHECK(SetMenuItemText);
+ PyMac_PRECHECK(SetMenuItemText);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &item,
- PyMac_GetStr255, itemString))
- return NULL;
- SetMenuItemText(_self->ob_itself,
- item,
- itemString);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &item,
+ PyMac_GetStr255, itemString))
+ return NULL;
+ SetMenuItemText(_self->ob_itself,
+ item,
+ itemString);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemText(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- Str255 itemString;
+ PyObject *_res = NULL;
+ short item;
+ Str255 itemString;
#ifndef GetMenuItemText
- PyMac_PRECHECK(GetMenuItemText);
+ PyMac_PRECHECK(GetMenuItemText);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- GetMenuItemText(_self->ob_itself,
- item,
- itemString);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, itemString);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ GetMenuItemText(_self->ob_itself,
+ item,
+ itemString);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, itemString);
+ return _res;
}
static PyObject *MenuObj_SetItemMark(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- CharParameter markChar;
+ PyObject *_res = NULL;
+ short item;
+ CharParameter markChar;
#ifndef SetItemMark
- PyMac_PRECHECK(SetItemMark);
+ PyMac_PRECHECK(SetItemMark);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &item,
- &markChar))
- return NULL;
- SetItemMark(_self->ob_itself,
- item,
- markChar);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &item,
+ &markChar))
+ return NULL;
+ SetItemMark(_self->ob_itself,
+ item,
+ markChar);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetItemMark(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- CharParameter markChar;
+ PyObject *_res = NULL;
+ short item;
+ CharParameter markChar;
#ifndef GetItemMark
- PyMac_PRECHECK(GetItemMark);
+ PyMac_PRECHECK(GetItemMark);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- GetItemMark(_self->ob_itself,
- item,
- &markChar);
- _res = Py_BuildValue("h",
- markChar);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ GetItemMark(_self->ob_itself,
+ item,
+ &markChar);
+ _res = Py_BuildValue("h",
+ markChar);
+ return _res;
}
static PyObject *MenuObj_SetItemCmd(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- CharParameter cmdChar;
+ PyObject *_res = NULL;
+ short item;
+ CharParameter cmdChar;
#ifndef SetItemCmd
- PyMac_PRECHECK(SetItemCmd);
+ PyMac_PRECHECK(SetItemCmd);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &item,
- &cmdChar))
- return NULL;
- SetItemCmd(_self->ob_itself,
- item,
- cmdChar);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &item,
+ &cmdChar))
+ return NULL;
+ SetItemCmd(_self->ob_itself,
+ item,
+ cmdChar);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetItemCmd(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- CharParameter cmdChar;
+ PyObject *_res = NULL;
+ short item;
+ CharParameter cmdChar;
#ifndef GetItemCmd
- PyMac_PRECHECK(GetItemCmd);
+ PyMac_PRECHECK(GetItemCmd);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- GetItemCmd(_self->ob_itself,
- item,
- &cmdChar);
- _res = Py_BuildValue("h",
- cmdChar);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ GetItemCmd(_self->ob_itself,
+ item,
+ &cmdChar);
+ _res = Py_BuildValue("h",
+ cmdChar);
+ return _res;
}
static PyObject *MenuObj_SetItemIcon(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- short iconIndex;
+ PyObject *_res = NULL;
+ short item;
+ short iconIndex;
#ifndef SetItemIcon
- PyMac_PRECHECK(SetItemIcon);
+ PyMac_PRECHECK(SetItemIcon);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &item,
- &iconIndex))
- return NULL;
- SetItemIcon(_self->ob_itself,
- item,
- iconIndex);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &item,
+ &iconIndex))
+ return NULL;
+ SetItemIcon(_self->ob_itself,
+ item,
+ iconIndex);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetItemIcon(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- short iconIndex;
+ PyObject *_res = NULL;
+ short item;
+ short iconIndex;
#ifndef GetItemIcon
- PyMac_PRECHECK(GetItemIcon);
+ PyMac_PRECHECK(GetItemIcon);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- GetItemIcon(_self->ob_itself,
- item,
- &iconIndex);
- _res = Py_BuildValue("h",
- iconIndex);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ GetItemIcon(_self->ob_itself,
+ item,
+ &iconIndex);
+ _res = Py_BuildValue("h",
+ iconIndex);
+ return _res;
}
static PyObject *MenuObj_SetItemStyle(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- StyleParameter chStyle;
+ PyObject *_res = NULL;
+ short item;
+ StyleParameter chStyle;
#ifndef SetItemStyle
- PyMac_PRECHECK(SetItemStyle);
+ PyMac_PRECHECK(SetItemStyle);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &item,
- &chStyle))
- return NULL;
- SetItemStyle(_self->ob_itself,
- item,
- chStyle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &item,
+ &chStyle))
+ return NULL;
+ SetItemStyle(_self->ob_itself,
+ item,
+ chStyle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetItemStyle(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- Style chStyle;
+ PyObject *_res = NULL;
+ short item;
+ Style chStyle;
#ifndef GetItemStyle
- PyMac_PRECHECK(GetItemStyle);
+ PyMac_PRECHECK(GetItemStyle);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- GetItemStyle(_self->ob_itself,
- item,
- &chStyle);
- _res = Py_BuildValue("b",
- chStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ GetItemStyle(_self->ob_itself,
+ item,
+ &chStyle);
+ _res = Py_BuildValue("b",
+ chStyle);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemCommandID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ MenuCommand inCommandID;
#ifndef SetMenuItemCommandID
- PyMac_PRECHECK(SetMenuItemCommandID);
+ PyMac_PRECHECK(SetMenuItemCommandID);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inItem,
- &inCommandID))
- return NULL;
- _err = SetMenuItemCommandID(_self->ob_itself,
- inItem,
- inCommandID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inItem,
+ &inCommandID))
+ return NULL;
+ _err = SetMenuItemCommandID(_self->ob_itself,
+ inItem,
+ inCommandID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemCommandID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- MenuCommand outCommandID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ MenuCommand outCommandID;
#ifndef GetMenuItemCommandID
- PyMac_PRECHECK(GetMenuItemCommandID);
+ PyMac_PRECHECK(GetMenuItemCommandID);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemCommandID(_self->ob_itself,
- inItem,
- &outCommandID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outCommandID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemCommandID(_self->ob_itself,
+ inItem,
+ &outCommandID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outCommandID);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemModifiers(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- UInt8 inModifiers;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ UInt8 inModifiers;
#ifndef SetMenuItemModifiers
- PyMac_PRECHECK(SetMenuItemModifiers);
+ PyMac_PRECHECK(SetMenuItemModifiers);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &inItem,
- &inModifiers))
- return NULL;
- _err = SetMenuItemModifiers(_self->ob_itself,
- inItem,
- inModifiers);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &inItem,
+ &inModifiers))
+ return NULL;
+ _err = SetMenuItemModifiers(_self->ob_itself,
+ inItem,
+ inModifiers);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemModifiers(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- UInt8 outModifiers;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ UInt8 outModifiers;
#ifndef GetMenuItemModifiers
- PyMac_PRECHECK(GetMenuItemModifiers);
+ PyMac_PRECHECK(GetMenuItemModifiers);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemModifiers(_self->ob_itself,
- inItem,
- &outModifiers);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- outModifiers);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemModifiers(_self->ob_itself,
+ inItem,
+ &outModifiers);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ outModifiers);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemIconHandle(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- UInt8 inIconType;
- Handle inIconHandle;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ UInt8 inIconType;
+ Handle inIconHandle;
#ifndef SetMenuItemIconHandle
- PyMac_PRECHECK(SetMenuItemIconHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "hbO&",
- &inItem,
- &inIconType,
- ResObj_Convert, &inIconHandle))
- return NULL;
- _err = SetMenuItemIconHandle(_self->ob_itself,
- inItem,
- inIconType,
- inIconHandle);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetMenuItemIconHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "hbO&",
+ &inItem,
+ &inIconType,
+ ResObj_Convert, &inIconHandle))
+ return NULL;
+ _err = SetMenuItemIconHandle(_self->ob_itself,
+ inItem,
+ inIconType,
+ inIconHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemIconHandle(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- UInt8 outIconType;
- Handle outIconHandle;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ UInt8 outIconType;
+ Handle outIconHandle;
#ifndef GetMenuItemIconHandle
- PyMac_PRECHECK(GetMenuItemIconHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemIconHandle(_self->ob_itself,
- inItem,
- &outIconType,
- &outIconHandle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bO&",
- outIconType,
- ResObj_New, outIconHandle);
- return _res;
+ PyMac_PRECHECK(GetMenuItemIconHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemIconHandle(_self->ob_itself,
+ inItem,
+ &outIconType,
+ &outIconHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bO&",
+ outIconType,
+ ResObj_New, outIconHandle);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemTextEncoding(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- TextEncoding inScriptID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ TextEncoding inScriptID;
#ifndef SetMenuItemTextEncoding
- PyMac_PRECHECK(SetMenuItemTextEncoding);
+ PyMac_PRECHECK(SetMenuItemTextEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inItem,
- &inScriptID))
- return NULL;
- _err = SetMenuItemTextEncoding(_self->ob_itself,
- inItem,
- inScriptID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inItem,
+ &inScriptID))
+ return NULL;
+ _err = SetMenuItemTextEncoding(_self->ob_itself,
+ inItem,
+ inScriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemTextEncoding(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- TextEncoding outScriptID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ TextEncoding outScriptID;
#ifndef GetMenuItemTextEncoding
- PyMac_PRECHECK(GetMenuItemTextEncoding);
+ PyMac_PRECHECK(GetMenuItemTextEncoding);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemTextEncoding(_self->ob_itself,
- inItem,
- &outScriptID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outScriptID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemTextEncoding(_self->ob_itself,
+ inItem,
+ &outScriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outScriptID);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemHierarchicalID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- MenuID inHierID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ MenuID inHierID;
#ifndef SetMenuItemHierarchicalID
- PyMac_PRECHECK(SetMenuItemHierarchicalID);
+ PyMac_PRECHECK(SetMenuItemHierarchicalID);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &inItem,
- &inHierID))
- return NULL;
- _err = SetMenuItemHierarchicalID(_self->ob_itself,
- inItem,
- inHierID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &inItem,
+ &inHierID))
+ return NULL;
+ _err = SetMenuItemHierarchicalID(_self->ob_itself,
+ inItem,
+ inHierID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemHierarchicalID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- MenuID outHierID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ MenuID outHierID;
#ifndef GetMenuItemHierarchicalID
- PyMac_PRECHECK(GetMenuItemHierarchicalID);
+ PyMac_PRECHECK(GetMenuItemHierarchicalID);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemHierarchicalID(_self->ob_itself,
- inItem,
- &outHierID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outHierID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemHierarchicalID(_self->ob_itself,
+ inItem,
+ &outHierID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outHierID);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemFontID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- SInt16 inFontID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ SInt16 inFontID;
#ifndef SetMenuItemFontID
- PyMac_PRECHECK(SetMenuItemFontID);
+ PyMac_PRECHECK(SetMenuItemFontID);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &inItem,
- &inFontID))
- return NULL;
- _err = SetMenuItemFontID(_self->ob_itself,
- inItem,
- inFontID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &inItem,
+ &inFontID))
+ return NULL;
+ _err = SetMenuItemFontID(_self->ob_itself,
+ inItem,
+ inFontID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemFontID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- SInt16 outFontID;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ SInt16 outFontID;
#ifndef GetMenuItemFontID
- PyMac_PRECHECK(GetMenuItemFontID);
+ PyMac_PRECHECK(GetMenuItemFontID);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemFontID(_self->ob_itself,
- inItem,
- &outFontID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outFontID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemFontID(_self->ob_itself,
+ inItem,
+ &outFontID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outFontID);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemRefCon(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- UInt32 inRefCon;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ UInt32 inRefCon;
#ifndef SetMenuItemRefCon
- PyMac_PRECHECK(SetMenuItemRefCon);
+ PyMac_PRECHECK(SetMenuItemRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inItem,
- &inRefCon))
- return NULL;
- _err = SetMenuItemRefCon(_self->ob_itself,
- inItem,
- inRefCon);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inItem,
+ &inRefCon))
+ return NULL;
+ _err = SetMenuItemRefCon(_self->ob_itself,
+ inItem,
+ inRefCon);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemRefCon(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- UInt32 outRefCon;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ UInt32 outRefCon;
#ifndef GetMenuItemRefCon
- PyMac_PRECHECK(GetMenuItemRefCon);
+ PyMac_PRECHECK(GetMenuItemRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemRefCon(_self->ob_itself,
- inItem,
- &outRefCon);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outRefCon);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemRefCon(_self->ob_itself,
+ inItem,
+ &outRefCon);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outRefCon);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemKeyGlyph(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- SInt16 inGlyph;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ SInt16 inGlyph;
#ifndef SetMenuItemKeyGlyph
- PyMac_PRECHECK(SetMenuItemKeyGlyph);
+ PyMac_PRECHECK(SetMenuItemKeyGlyph);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &inItem,
- &inGlyph))
- return NULL;
- _err = SetMenuItemKeyGlyph(_self->ob_itself,
- inItem,
- inGlyph);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &inItem,
+ &inGlyph))
+ return NULL;
+ _err = SetMenuItemKeyGlyph(_self->ob_itself,
+ inItem,
+ inGlyph);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemKeyGlyph(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 inItem;
- SInt16 outGlyph;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 inItem;
+ SInt16 outGlyph;
#ifndef GetMenuItemKeyGlyph
- PyMac_PRECHECK(GetMenuItemKeyGlyph);
+ PyMac_PRECHECK(GetMenuItemKeyGlyph);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemKeyGlyph(_self->ob_itself,
- inItem,
- &outGlyph);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outGlyph);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemKeyGlyph(_self->ob_itself,
+ inItem,
+ &outGlyph);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outGlyph);
+ return _res;
}
static PyObject *MenuObj_MacEnableMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuItemIndex item;
+ PyObject *_res = NULL;
+ MenuItemIndex item;
#ifndef MacEnableMenuItem
- PyMac_PRECHECK(MacEnableMenuItem);
+ PyMac_PRECHECK(MacEnableMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- MacEnableMenuItem(_self->ob_itself,
- item);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ MacEnableMenuItem(_self->ob_itself,
+ item);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DisableMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuItemIndex item;
+ PyObject *_res = NULL;
+ MenuItemIndex item;
#ifndef DisableMenuItem
- PyMac_PRECHECK(DisableMenuItem);
+ PyMac_PRECHECK(DisableMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- DisableMenuItem(_self->ob_itself,
- item);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ DisableMenuItem(_self->ob_itself,
+ item);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsMenuItemEnabled(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- MenuItemIndex item;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ MenuItemIndex item;
#ifndef IsMenuItemEnabled
- PyMac_PRECHECK(IsMenuItemEnabled);
+ PyMac_PRECHECK(IsMenuItemEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- _rv = IsMenuItemEnabled(_self->ob_itself,
- item);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ _rv = IsMenuItemEnabled(_self->ob_itself,
+ item);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_EnableMenuItemIcon(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuItemIndex item;
+ PyObject *_res = NULL;
+ MenuItemIndex item;
#ifndef EnableMenuItemIcon
- PyMac_PRECHECK(EnableMenuItemIcon);
+ PyMac_PRECHECK(EnableMenuItemIcon);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- EnableMenuItemIcon(_self->ob_itself,
- item);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ EnableMenuItemIcon(_self->ob_itself,
+ item);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DisableMenuItemIcon(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuItemIndex item;
+ PyObject *_res = NULL;
+ MenuItemIndex item;
#ifndef DisableMenuItemIcon
- PyMac_PRECHECK(DisableMenuItemIcon);
+ PyMac_PRECHECK(DisableMenuItemIcon);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- DisableMenuItemIcon(_self->ob_itself,
- item);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ DisableMenuItemIcon(_self->ob_itself,
+ item);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsMenuItemIconEnabled(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- MenuItemIndex item;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ MenuItemIndex item;
#ifndef IsMenuItemIconEnabled
- PyMac_PRECHECK(IsMenuItemIconEnabled);
+ PyMac_PRECHECK(IsMenuItemIconEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- _rv = IsMenuItemIconEnabled(_self->ob_itself,
- item);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ _rv = IsMenuItemIconEnabled(_self->ob_itself,
+ item);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemHierarchicalMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- MenuHandle inHierMenu;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ MenuHandle inHierMenu;
#ifndef SetMenuItemHierarchicalMenu
- PyMac_PRECHECK(SetMenuItemHierarchicalMenu);
+ PyMac_PRECHECK(SetMenuItemHierarchicalMenu);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &inItem,
- MenuObj_Convert, &inHierMenu))
- return NULL;
- _err = SetMenuItemHierarchicalMenu(_self->ob_itself,
- inItem,
- inHierMenu);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inItem,
+ MenuObj_Convert, &inHierMenu))
+ return NULL;
+ _err = SetMenuItemHierarchicalMenu(_self->ob_itself,
+ inItem,
+ inHierMenu);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemHierarchicalMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- MenuHandle outHierMenu;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ MenuHandle outHierMenu;
#ifndef GetMenuItemHierarchicalMenu
- PyMac_PRECHECK(GetMenuItemHierarchicalMenu);
+ PyMac_PRECHECK(GetMenuItemHierarchicalMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemHierarchicalMenu(_self->ob_itself,
- inItem,
- &outHierMenu);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- OptMenuObj_New, outHierMenu);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemHierarchicalMenu(_self->ob_itself,
+ inItem,
+ &outHierMenu);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ OptMenuObj_New, outHierMenu);
+ return _res;
}
static PyObject *MenuObj_CopyMenuItemTextAsCFString(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- CFStringRef outString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ CFStringRef outString;
#ifndef CopyMenuItemTextAsCFString
- PyMac_PRECHECK(CopyMenuItemTextAsCFString);
+ PyMac_PRECHECK(CopyMenuItemTextAsCFString);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = CopyMenuItemTextAsCFString(_self->ob_itself,
- inItem,
- &outString);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, outString);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = CopyMenuItemTextAsCFString(_self->ob_itself,
+ inItem,
+ &outString);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, outString);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemTextWithCFString(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- CFStringRef inString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ CFStringRef inString;
#ifndef SetMenuItemTextWithCFString
- PyMac_PRECHECK(SetMenuItemTextWithCFString);
+ PyMac_PRECHECK(SetMenuItemTextWithCFString);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &inItem,
- CFStringRefObj_Convert, &inString))
- return NULL;
- _err = SetMenuItemTextWithCFString(_self->ob_itself,
- inItem,
- inString);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &inItem,
+ CFStringRefObj_Convert, &inString))
+ return NULL;
+ _err = SetMenuItemTextWithCFString(_self->ob_itself,
+ inItem,
+ inString);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemIndent(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- UInt32 outIndent;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ UInt32 outIndent;
#ifndef GetMenuItemIndent
- PyMac_PRECHECK(GetMenuItemIndent);
+ PyMac_PRECHECK(GetMenuItemIndent);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _err = GetMenuItemIndent(_self->ob_itself,
- inItem,
- &outIndent);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outIndent);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _err = GetMenuItemIndent(_self->ob_itself,
+ inItem,
+ &outIndent);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outIndent);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemIndent(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- UInt32 inIndent;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ UInt32 inIndent;
#ifndef SetMenuItemIndent
- PyMac_PRECHECK(SetMenuItemIndent);
+ PyMac_PRECHECK(SetMenuItemIndent);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inItem,
- &inIndent))
- return NULL;
- _err = SetMenuItemIndent(_self->ob_itself,
- inItem,
- inIndent);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inItem,
+ &inIndent))
+ return NULL;
+ _err = SetMenuItemIndent(_self->ob_itself,
+ inItem,
+ inIndent);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemCommandKey(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- Boolean inGetVirtualKey;
- UInt16 outKey;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ Boolean inGetVirtualKey;
+ UInt16 outKey;
#ifndef GetMenuItemCommandKey
- PyMac_PRECHECK(GetMenuItemCommandKey);
-#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &inItem,
- &inGetVirtualKey))
- return NULL;
- _err = GetMenuItemCommandKey(_self->ob_itself,
- inItem,
- inGetVirtualKey,
- &outKey);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outKey);
- return _res;
+ PyMac_PRECHECK(GetMenuItemCommandKey);
+#endif
+ if (!PyArg_ParseTuple(_args, "hb",
+ &inItem,
+ &inGetVirtualKey))
+ return NULL;
+ _err = GetMenuItemCommandKey(_self->ob_itself,
+ inItem,
+ inGetVirtualKey,
+ &outKey);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outKey);
+ return _res;
}
static PyObject *MenuObj_SetMenuItemCommandKey(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inItem;
- Boolean inSetVirtualKey;
- UInt16 inKey;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inItem;
+ Boolean inSetVirtualKey;
+ UInt16 inKey;
#ifndef SetMenuItemCommandKey
- PyMac_PRECHECK(SetMenuItemCommandKey);
-#endif
- if (!PyArg_ParseTuple(_args, "hbH",
- &inItem,
- &inSetVirtualKey,
- &inKey))
- return NULL;
- _err = SetMenuItemCommandKey(_self->ob_itself,
- inItem,
- inSetVirtualKey,
- inKey);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetMenuItemCommandKey);
+#endif
+ if (!PyArg_ParseTuple(_args, "hbH",
+ &inItem,
+ &inSetVirtualKey,
+ &inKey))
+ return NULL;
+ _err = SetMenuItemCommandKey(_self->ob_itself,
+ inItem,
+ inSetVirtualKey,
+ inKey);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemPropertyAttributes(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex item;
- OSType propertyCreator;
- OSType propertyTag;
- UInt32 attributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex item;
+ OSType propertyCreator;
+ OSType propertyTag;
+ UInt32 attributes;
#ifndef GetMenuItemPropertyAttributes
- PyMac_PRECHECK(GetMenuItemPropertyAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&O&",
- &item,
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag))
- return NULL;
- _err = GetMenuItemPropertyAttributes(_self->ob_itself,
- item,
- propertyCreator,
- propertyTag,
- &attributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- attributes);
- return _res;
+ PyMac_PRECHECK(GetMenuItemPropertyAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&O&",
+ &item,
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag))
+ return NULL;
+ _err = GetMenuItemPropertyAttributes(_self->ob_itself,
+ item,
+ propertyCreator,
+ propertyTag,
+ &attributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ attributes);
+ return _res;
}
static PyObject *MenuObj_ChangeMenuItemPropertyAttributes(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex item;
- OSType propertyCreator;
- OSType propertyTag;
- UInt32 attributesToSet;
- UInt32 attributesToClear;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex item;
+ OSType propertyCreator;
+ OSType propertyTag;
+ UInt32 attributesToSet;
+ UInt32 attributesToClear;
#ifndef ChangeMenuItemPropertyAttributes
- PyMac_PRECHECK(ChangeMenuItemPropertyAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&O&ll",
- &item,
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag,
- &attributesToSet,
- &attributesToClear))
- return NULL;
- _err = ChangeMenuItemPropertyAttributes(_self->ob_itself,
- item,
- propertyCreator,
- propertyTag,
- attributesToSet,
- attributesToClear);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ChangeMenuItemPropertyAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&O&ll",
+ &item,
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag,
+ &attributesToSet,
+ &attributesToClear))
+ return NULL;
+ _err = ChangeMenuItemPropertyAttributes(_self->ob_itself,
+ item,
+ propertyCreator,
+ propertyTag,
+ attributesToSet,
+ attributesToClear);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuAttributes(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuAttributes outAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuAttributes outAttributes;
#ifndef GetMenuAttributes
- PyMac_PRECHECK(GetMenuAttributes);
+ PyMac_PRECHECK(GetMenuAttributes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMenuAttributes(_self->ob_itself,
- &outAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outAttributes);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMenuAttributes(_self->ob_itself,
+ &outAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outAttributes);
+ return _res;
}
static PyObject *MenuObj_ChangeMenuAttributes(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuAttributes setTheseAttributes;
- MenuAttributes clearTheseAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuAttributes setTheseAttributes;
+ MenuAttributes clearTheseAttributes;
#ifndef ChangeMenuAttributes
- PyMac_PRECHECK(ChangeMenuAttributes);
+ PyMac_PRECHECK(ChangeMenuAttributes);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &setTheseAttributes,
- &clearTheseAttributes))
- return NULL;
- _err = ChangeMenuAttributes(_self->ob_itself,
- setTheseAttributes,
- clearTheseAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &setTheseAttributes,
+ &clearTheseAttributes))
+ return NULL;
+ _err = ChangeMenuAttributes(_self->ob_itself,
+ setTheseAttributes,
+ clearTheseAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuItemAttributes(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex item;
- MenuItemAttributes outAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex item;
+ MenuItemAttributes outAttributes;
#ifndef GetMenuItemAttributes
- PyMac_PRECHECK(GetMenuItemAttributes);
+ PyMac_PRECHECK(GetMenuItemAttributes);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- _err = GetMenuItemAttributes(_self->ob_itself,
- item,
- &outAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outAttributes);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ _err = GetMenuItemAttributes(_self->ob_itself,
+ item,
+ &outAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outAttributes);
+ return _res;
}
static PyObject *MenuObj_ChangeMenuItemAttributes(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex item;
- MenuItemAttributes setTheseAttributes;
- MenuItemAttributes clearTheseAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex item;
+ MenuItemAttributes setTheseAttributes;
+ MenuItemAttributes clearTheseAttributes;
#ifndef ChangeMenuItemAttributes
- PyMac_PRECHECK(ChangeMenuItemAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "hll",
- &item,
- &setTheseAttributes,
- &clearTheseAttributes))
- return NULL;
- _err = ChangeMenuItemAttributes(_self->ob_itself,
- item,
- setTheseAttributes,
- clearTheseAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ChangeMenuItemAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "hll",
+ &item,
+ &setTheseAttributes,
+ &clearTheseAttributes))
+ return NULL;
+ _err = ChangeMenuItemAttributes(_self->ob_itself,
+ item,
+ setTheseAttributes,
+ clearTheseAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DisableAllMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DisableAllMenuItems
- PyMac_PRECHECK(DisableAllMenuItems);
+ PyMac_PRECHECK(DisableAllMenuItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DisableAllMenuItems(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DisableAllMenuItems(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_EnableAllMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef EnableAllMenuItems
- PyMac_PRECHECK(EnableAllMenuItems);
+ PyMac_PRECHECK(EnableAllMenuItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- EnableAllMenuItems(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ EnableAllMenuItems(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_MenuHasEnabledItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef MenuHasEnabledItems
- PyMac_PRECHECK(MenuHasEnabledItems);
+ PyMac_PRECHECK(MenuHasEnabledItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MenuHasEnabledItems(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MenuHasEnabledItems(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_GetMenuType(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt16 outType;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt16 outType;
#ifndef GetMenuType
- PyMac_PRECHECK(GetMenuType);
+ PyMac_PRECHECK(GetMenuType);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMenuType(_self->ob_itself,
- &outType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("H",
- outType);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMenuType(_self->ob_itself,
+ &outType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("H",
+ outType);
+ return _res;
}
static PyObject *MenuObj_CountMenuItemsWithCommandID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ItemCount _rv;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ ItemCount _rv;
+ MenuCommand inCommandID;
#ifndef CountMenuItemsWithCommandID
- PyMac_PRECHECK(CountMenuItemsWithCommandID);
+ PyMac_PRECHECK(CountMenuItemsWithCommandID);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCommandID))
- return NULL;
- _rv = CountMenuItemsWithCommandID(_self->ob_itself,
- inCommandID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCommandID))
+ return NULL;
+ _rv = CountMenuItemsWithCommandID(_self->ob_itself,
+ inCommandID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_GetIndMenuItemWithCommandID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuCommand inCommandID;
- UInt32 inItemIndex;
- MenuHandle outMenu;
- MenuItemIndex outIndex;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuCommand inCommandID;
+ UInt32 inItemIndex;
+ MenuHandle outMenu;
+ MenuItemIndex outIndex;
#ifndef GetIndMenuItemWithCommandID
- PyMac_PRECHECK(GetIndMenuItemWithCommandID);
-#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &inCommandID,
- &inItemIndex))
- return NULL;
- _err = GetIndMenuItemWithCommandID(_self->ob_itself,
- inCommandID,
- inItemIndex,
- &outMenu,
- &outIndex);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- MenuObj_New, outMenu,
- outIndex);
- return _res;
+ PyMac_PRECHECK(GetIndMenuItemWithCommandID);
+#endif
+ if (!PyArg_ParseTuple(_args, "ll",
+ &inCommandID,
+ &inItemIndex))
+ return NULL;
+ _err = GetIndMenuItemWithCommandID(_self->ob_itself,
+ inCommandID,
+ inItemIndex,
+ &outMenu,
+ &outIndex);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ MenuObj_New, outMenu,
+ outIndex);
+ return _res;
}
static PyObject *MenuObj_EnableMenuCommand(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ MenuCommand inCommandID;
#ifndef EnableMenuCommand
- PyMac_PRECHECK(EnableMenuCommand);
+ PyMac_PRECHECK(EnableMenuCommand);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCommandID))
- return NULL;
- EnableMenuCommand(_self->ob_itself,
- inCommandID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCommandID))
+ return NULL;
+ EnableMenuCommand(_self->ob_itself,
+ inCommandID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_DisableMenuCommand(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ MenuCommand inCommandID;
#ifndef DisableMenuCommand
- PyMac_PRECHECK(DisableMenuCommand);
+ PyMac_PRECHECK(DisableMenuCommand);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCommandID))
- return NULL;
- DisableMenuCommand(_self->ob_itself,
- inCommandID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCommandID))
+ return NULL;
+ DisableMenuCommand(_self->ob_itself,
+ inCommandID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsMenuCommandEnabled(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ MenuCommand inCommandID;
#ifndef IsMenuCommandEnabled
- PyMac_PRECHECK(IsMenuCommandEnabled);
+ PyMac_PRECHECK(IsMenuCommandEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCommandID))
- return NULL;
- _rv = IsMenuCommandEnabled(_self->ob_itself,
- inCommandID);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCommandID))
+ return NULL;
+ _rv = IsMenuCommandEnabled(_self->ob_itself,
+ inCommandID);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_SetMenuCommandMark(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuCommand inCommandID;
- UniChar inMark;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuCommand inCommandID;
+ UniChar inMark;
#ifndef SetMenuCommandMark
- PyMac_PRECHECK(SetMenuCommandMark);
+ PyMac_PRECHECK(SetMenuCommandMark);
#endif
- if (!PyArg_ParseTuple(_args, "lh",
- &inCommandID,
- &inMark))
- return NULL;
- _err = SetMenuCommandMark(_self->ob_itself,
- inCommandID,
- inMark);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lh",
+ &inCommandID,
+ &inMark))
+ return NULL;
+ _err = SetMenuCommandMark(_self->ob_itself,
+ inCommandID,
+ inMark);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_GetMenuCommandMark(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuCommand inCommandID;
- UniChar outMark;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuCommand inCommandID;
+ UniChar outMark;
#ifndef GetMenuCommandMark
- PyMac_PRECHECK(GetMenuCommandMark);
+ PyMac_PRECHECK(GetMenuCommandMark);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inCommandID))
- return NULL;
- _err = GetMenuCommandMark(_self->ob_itself,
- inCommandID,
- &outMark);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outMark);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inCommandID))
+ return NULL;
+ _err = GetMenuCommandMark(_self->ob_itself,
+ inCommandID,
+ &outMark);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outMark);
+ return _res;
}
static PyObject *MenuObj_GetMenuCommandPropertySize(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuCommand inCommandID;
- OSType inPropertyCreator;
- OSType inPropertyTag;
- ByteCount outSize;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuCommand inCommandID;
+ OSType inPropertyCreator;
+ OSType inPropertyTag;
+ ByteCount outSize;
#ifndef GetMenuCommandPropertySize
- PyMac_PRECHECK(GetMenuCommandPropertySize);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&O&",
- &inCommandID,
- PyMac_GetOSType, &inPropertyCreator,
- PyMac_GetOSType, &inPropertyTag))
- return NULL;
- _err = GetMenuCommandPropertySize(_self->ob_itself,
- inCommandID,
- inPropertyCreator,
- inPropertyTag,
- &outSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outSize);
- return _res;
+ PyMac_PRECHECK(GetMenuCommandPropertySize);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&O&",
+ &inCommandID,
+ PyMac_GetOSType, &inPropertyCreator,
+ PyMac_GetOSType, &inPropertyTag))
+ return NULL;
+ _err = GetMenuCommandPropertySize(_self->ob_itself,
+ inCommandID,
+ inPropertyCreator,
+ inPropertyTag,
+ &outSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outSize);
+ return _res;
}
static PyObject *MenuObj_RemoveMenuCommandProperty(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuCommand inCommandID;
- OSType inPropertyCreator;
- OSType inPropertyTag;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuCommand inCommandID;
+ OSType inPropertyCreator;
+ OSType inPropertyTag;
#ifndef RemoveMenuCommandProperty
- PyMac_PRECHECK(RemoveMenuCommandProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&O&",
- &inCommandID,
- PyMac_GetOSType, &inPropertyCreator,
- PyMac_GetOSType, &inPropertyTag))
- return NULL;
- _err = RemoveMenuCommandProperty(_self->ob_itself,
- inCommandID,
- inPropertyCreator,
- inPropertyTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(RemoveMenuCommandProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&O&",
+ &inCommandID,
+ PyMac_GetOSType, &inPropertyCreator,
+ PyMac_GetOSType, &inPropertyTag))
+ return NULL;
+ _err = RemoveMenuCommandProperty(_self->ob_itself,
+ inCommandID,
+ inPropertyCreator,
+ inPropertyTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_IsMenuItemInvalid(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- MenuItemIndex inItem;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ MenuItemIndex inItem;
#ifndef IsMenuItemInvalid
- PyMac_PRECHECK(IsMenuItemInvalid);
+ PyMac_PRECHECK(IsMenuItemInvalid);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inItem))
- return NULL;
- _rv = IsMenuItemInvalid(_self->ob_itself,
- inItem);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inItem))
+ return NULL;
+ _rv = IsMenuItemInvalid(_self->ob_itself,
+ inItem);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_InvalidateMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex inFirstItem;
- ItemCount inNumItems;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex inFirstItem;
+ ItemCount inNumItems;
#ifndef InvalidateMenuItems
- PyMac_PRECHECK(InvalidateMenuItems);
+ PyMac_PRECHECK(InvalidateMenuItems);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inFirstItem,
- &inNumItems))
- return NULL;
- _err = InvalidateMenuItems(_self->ob_itself,
- inFirstItem,
- inNumItems);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inFirstItem,
+ &inNumItems))
+ return NULL;
+ _err = InvalidateMenuItems(_self->ob_itself,
+ inFirstItem,
+ inNumItems);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_UpdateInvalidMenuItems(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef UpdateInvalidMenuItems
- PyMac_PRECHECK(UpdateInvalidMenuItems);
+ PyMac_PRECHECK(UpdateInvalidMenuItems);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UpdateInvalidMenuItems(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = UpdateInvalidMenuItems(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_CreateStandardFontMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex afterItem;
- MenuID firstHierMenuID;
- OptionBits options;
- ItemCount outHierMenuCount;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex afterItem;
+ MenuID firstHierMenuID;
+ OptionBits options;
+ ItemCount outHierMenuCount;
#ifndef CreateStandardFontMenu
- PyMac_PRECHECK(CreateStandardFontMenu);
-#endif
- if (!PyArg_ParseTuple(_args, "hhl",
- &afterItem,
- &firstHierMenuID,
- &options))
- return NULL;
- _err = CreateStandardFontMenu(_self->ob_itself,
- afterItem,
- firstHierMenuID,
- options,
- &outHierMenuCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outHierMenuCount);
- return _res;
+ PyMac_PRECHECK(CreateStandardFontMenu);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhl",
+ &afterItem,
+ &firstHierMenuID,
+ &options))
+ return NULL;
+ _err = CreateStandardFontMenu(_self->ob_itself,
+ afterItem,
+ firstHierMenuID,
+ options,
+ &outHierMenuCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outHierMenuCount);
+ return _res;
}
static PyObject *MenuObj_UpdateStandardFontMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ItemCount outHierMenuCount;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ItemCount outHierMenuCount;
#ifndef UpdateStandardFontMenu
- PyMac_PRECHECK(UpdateStandardFontMenu);
+ PyMac_PRECHECK(UpdateStandardFontMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UpdateStandardFontMenu(_self->ob_itself,
- &outHierMenuCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outHierMenuCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = UpdateStandardFontMenu(_self->ob_itself,
+ &outHierMenuCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outHierMenuCount);
+ return _res;
}
static PyObject *MenuObj_GetFontFamilyFromMenuSelection(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuItemIndex item;
- FMFontFamily outFontFamily;
- FMFontStyle outStyle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuItemIndex item;
+ FMFontFamily outFontFamily;
+ FMFontStyle outStyle;
#ifndef GetFontFamilyFromMenuSelection
- PyMac_PRECHECK(GetFontFamilyFromMenuSelection);
-#endif
- if (!PyArg_ParseTuple(_args, "h",
- &item))
- return NULL;
- _err = GetFontFamilyFromMenuSelection(_self->ob_itself,
- item,
- &outFontFamily,
- &outStyle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hh",
- outFontFamily,
- outStyle);
- return _res;
+ PyMac_PRECHECK(GetFontFamilyFromMenuSelection);
+#endif
+ if (!PyArg_ParseTuple(_args, "h",
+ &item))
+ return NULL;
+ _err = GetFontFamilyFromMenuSelection(_self->ob_itself,
+ item,
+ &outFontFamily,
+ &outStyle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hh",
+ outFontFamily,
+ outStyle);
+ return _res;
}
static PyObject *MenuObj_GetMenuID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID _rv;
+ PyObject *_res = NULL;
+ MenuID _rv;
#ifndef GetMenuID
- PyMac_PRECHECK(GetMenuID);
+ PyMac_PRECHECK(GetMenuID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMenuID(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMenuID(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_GetMenuWidth(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetMenuWidth
- PyMac_PRECHECK(GetMenuWidth);
+ PyMac_PRECHECK(GetMenuWidth);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMenuWidth(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMenuWidth(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_GetMenuHeight(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef GetMenuHeight
- PyMac_PRECHECK(GetMenuHeight);
+ PyMac_PRECHECK(GetMenuHeight);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMenuHeight(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMenuHeight(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MenuObj_SetMenuID(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID menuID;
+ PyObject *_res = NULL;
+ MenuID menuID;
#ifndef SetMenuID
- PyMac_PRECHECK(SetMenuID);
+ PyMac_PRECHECK(SetMenuID);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- SetMenuID(_self->ob_itself,
- menuID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ SetMenuID(_self->ob_itself,
+ menuID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_SetMenuWidth(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 width;
+ PyObject *_res = NULL;
+ SInt16 width;
#ifndef SetMenuWidth
- PyMac_PRECHECK(SetMenuWidth);
+ PyMac_PRECHECK(SetMenuWidth);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &width))
- return NULL;
- SetMenuWidth(_self->ob_itself,
- width);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &width))
+ return NULL;
+ SetMenuWidth(_self->ob_itself,
+ width);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_SetMenuHeight(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 height;
+ PyObject *_res = NULL;
+ SInt16 height;
#ifndef SetMenuHeight
- PyMac_PRECHECK(SetMenuHeight);
+ PyMac_PRECHECK(SetMenuHeight);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &height))
- return NULL;
- SetMenuHeight(_self->ob_itself,
- height);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &height))
+ return NULL;
+ SetMenuHeight(_self->ob_itself,
+ height);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_as_Resource(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef as_Resource
- PyMac_PRECHECK(as_Resource);
+ PyMac_PRECHECK(as_Resource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = as_Resource(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = as_Resource(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MenuObj_AppendMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 data;
+ PyObject *_res = NULL;
+ Str255 data;
#ifndef AppendMenu
- PyMac_PRECHECK(AppendMenu);
+ PyMac_PRECHECK(AppendMenu);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, data))
- return NULL;
- AppendMenu(_self->ob_itself,
- data);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, data))
+ return NULL;
+ AppendMenu(_self->ob_itself,
+ data);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InsertMenu(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short beforeID;
+ PyObject *_res = NULL;
+ short beforeID;
#ifndef InsertMenu
- PyMac_PRECHECK(InsertMenu);
+ PyMac_PRECHECK(InsertMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &beforeID))
- return NULL;
- InsertMenu(_self->ob_itself,
- beforeID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &beforeID))
+ return NULL;
+ InsertMenu(_self->ob_itself,
+ beforeID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_InsertMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 itemString;
- short afterItem;
+ PyObject *_res = NULL;
+ Str255 itemString;
+ short afterItem;
#ifndef InsertMenuItem
- PyMac_PRECHECK(InsertMenuItem);
+ PyMac_PRECHECK(InsertMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetStr255, itemString,
- &afterItem))
- return NULL;
- InsertMenuItem(_self->ob_itself,
- itemString,
- afterItem);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetStr255, itemString,
+ &afterItem))
+ return NULL;
+ InsertMenuItem(_self->ob_itself,
+ itemString,
+ afterItem);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_EnableMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt16 item;
+ PyObject *_res = NULL;
+ UInt16 item;
#ifndef EnableMenuItem
- PyMac_PRECHECK(EnableMenuItem);
+ PyMac_PRECHECK(EnableMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &item))
- return NULL;
- EnableMenuItem(_self->ob_itself,
- item);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &item))
+ return NULL;
+ EnableMenuItem(_self->ob_itself,
+ item);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MenuObj_CheckMenuItem(MenuObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short item;
- Boolean checked;
+ PyObject *_res = NULL;
+ short item;
+ Boolean checked;
#ifndef CheckMenuItem
- PyMac_PRECHECK(CheckMenuItem);
+ PyMac_PRECHECK(CheckMenuItem);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &item,
- &checked))
- return NULL;
- CheckMenuItem(_self->ob_itself,
- item,
- checked);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &item,
+ &checked))
+ return NULL;
+ CheckMenuItem(_self->ob_itself,
+ item,
+ checked);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef MenuObj_methods[] = {
- {"DisposeMenu", (PyCFunction)MenuObj_DisposeMenu, 1,
- PyDoc_STR("() -> None")},
- {"CalcMenuSize", (PyCFunction)MenuObj_CalcMenuSize, 1,
- PyDoc_STR("() -> None")},
- {"CountMenuItems", (PyCFunction)MenuObj_CountMenuItems, 1,
- PyDoc_STR("() -> (UInt16 _rv)")},
- {"GetMenuFont", (PyCFunction)MenuObj_GetMenuFont, 1,
- PyDoc_STR("() -> (SInt16 outFontID, UInt16 outFontSize)")},
- {"SetMenuFont", (PyCFunction)MenuObj_SetMenuFont, 1,
- PyDoc_STR("(SInt16 inFontID, UInt16 inFontSize) -> None")},
- {"GetMenuExcludesMarkColumn", (PyCFunction)MenuObj_GetMenuExcludesMarkColumn, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SetMenuExcludesMarkColumn", (PyCFunction)MenuObj_SetMenuExcludesMarkColumn, 1,
- PyDoc_STR("(Boolean excludesMark) -> None")},
- {"IsValidMenu", (PyCFunction)MenuObj_IsValidMenu, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetMenuRetainCount", (PyCFunction)MenuObj_GetMenuRetainCount, 1,
- PyDoc_STR("() -> (ItemCount _rv)")},
- {"RetainMenu", (PyCFunction)MenuObj_RetainMenu, 1,
- PyDoc_STR("() -> None")},
- {"ReleaseMenu", (PyCFunction)MenuObj_ReleaseMenu, 1,
- PyDoc_STR("() -> None")},
- {"DuplicateMenu", (PyCFunction)MenuObj_DuplicateMenu, 1,
- PyDoc_STR("() -> (MenuHandle outMenu)")},
- {"CopyMenuTitleAsCFString", (PyCFunction)MenuObj_CopyMenuTitleAsCFString, 1,
- PyDoc_STR("() -> (CFStringRef outString)")},
- {"SetMenuTitleWithCFString", (PyCFunction)MenuObj_SetMenuTitleWithCFString, 1,
- PyDoc_STR("(CFStringRef inString) -> None")},
- {"InvalidateMenuSize", (PyCFunction)MenuObj_InvalidateMenuSize, 1,
- PyDoc_STR("() -> None")},
- {"IsMenuSizeInvalid", (PyCFunction)MenuObj_IsMenuSizeInvalid, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"MacAppendMenu", (PyCFunction)MenuObj_MacAppendMenu, 1,
- PyDoc_STR("(Str255 data) -> None")},
- {"InsertResMenu", (PyCFunction)MenuObj_InsertResMenu, 1,
- PyDoc_STR("(ResType theType, short afterItem) -> None")},
- {"AppendResMenu", (PyCFunction)MenuObj_AppendResMenu, 1,
- PyDoc_STR("(ResType theType) -> None")},
- {"MacInsertMenuItem", (PyCFunction)MenuObj_MacInsertMenuItem, 1,
- PyDoc_STR("(Str255 itemString, short afterItem) -> None")},
- {"DeleteMenuItem", (PyCFunction)MenuObj_DeleteMenuItem, 1,
- PyDoc_STR("(short item) -> None")},
- {"InsertFontResMenu", (PyCFunction)MenuObj_InsertFontResMenu, 1,
- PyDoc_STR("(short afterItem, short scriptFilter) -> None")},
- {"InsertIntlResMenu", (PyCFunction)MenuObj_InsertIntlResMenu, 1,
- PyDoc_STR("(ResType theType, short afterItem, short scriptFilter) -> None")},
- {"AppendMenuItemText", (PyCFunction)MenuObj_AppendMenuItemText, 1,
- PyDoc_STR("(Str255 inString) -> None")},
- {"InsertMenuItemText", (PyCFunction)MenuObj_InsertMenuItemText, 1,
- PyDoc_STR("(Str255 inString, MenuItemIndex afterItem) -> None")},
- {"CopyMenuItems", (PyCFunction)MenuObj_CopyMenuItems, 1,
- PyDoc_STR("(MenuItemIndex inFirstItem, ItemCount inNumItems, MenuHandle inDestMenu, MenuItemIndex inInsertAfter) -> None")},
- {"DeleteMenuItems", (PyCFunction)MenuObj_DeleteMenuItems, 1,
- PyDoc_STR("(MenuItemIndex inFirstItem, ItemCount inNumItems) -> None")},
- {"AppendMenuItemTextWithCFString", (PyCFunction)MenuObj_AppendMenuItemTextWithCFString, 1,
- PyDoc_STR("(CFStringRef inString, MenuItemAttributes inAttributes, MenuCommand inCommandID) -> (MenuItemIndex outNewItem)")},
- {"InsertMenuItemTextWithCFString", (PyCFunction)MenuObj_InsertMenuItemTextWithCFString, 1,
- PyDoc_STR("(CFStringRef inString, MenuItemIndex inAfterItem, MenuItemAttributes inAttributes, MenuCommand inCommandID) -> None")},
- {"PopUpMenuSelect", (PyCFunction)MenuObj_PopUpMenuSelect, 1,
- PyDoc_STR("(short top, short left, short popUpItem) -> (long _rv)")},
- {"InvalidateMenuEnabling", (PyCFunction)MenuObj_InvalidateMenuEnabling, 1,
- PyDoc_STR("() -> None")},
- {"IsMenuBarInvalid", (PyCFunction)MenuObj_IsMenuBarInvalid, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"MacInsertMenu", (PyCFunction)MenuObj_MacInsertMenu, 1,
- PyDoc_STR("(MenuID beforeID) -> None")},
- {"SetRootMenu", (PyCFunction)MenuObj_SetRootMenu, 1,
- PyDoc_STR("() -> None")},
- {"MacCheckMenuItem", (PyCFunction)MenuObj_MacCheckMenuItem, 1,
- PyDoc_STR("(short item, Boolean checked) -> None")},
- {"SetMenuItemText", (PyCFunction)MenuObj_SetMenuItemText, 1,
- PyDoc_STR("(short item, Str255 itemString) -> None")},
- {"GetMenuItemText", (PyCFunction)MenuObj_GetMenuItemText, 1,
- PyDoc_STR("(short item) -> (Str255 itemString)")},
- {"SetItemMark", (PyCFunction)MenuObj_SetItemMark, 1,
- PyDoc_STR("(short item, CharParameter markChar) -> None")},
- {"GetItemMark", (PyCFunction)MenuObj_GetItemMark, 1,
- PyDoc_STR("(short item) -> (CharParameter markChar)")},
- {"SetItemCmd", (PyCFunction)MenuObj_SetItemCmd, 1,
- PyDoc_STR("(short item, CharParameter cmdChar) -> None")},
- {"GetItemCmd", (PyCFunction)MenuObj_GetItemCmd, 1,
- PyDoc_STR("(short item) -> (CharParameter cmdChar)")},
- {"SetItemIcon", (PyCFunction)MenuObj_SetItemIcon, 1,
- PyDoc_STR("(short item, short iconIndex) -> None")},
- {"GetItemIcon", (PyCFunction)MenuObj_GetItemIcon, 1,
- PyDoc_STR("(short item) -> (short iconIndex)")},
- {"SetItemStyle", (PyCFunction)MenuObj_SetItemStyle, 1,
- PyDoc_STR("(short item, StyleParameter chStyle) -> None")},
- {"GetItemStyle", (PyCFunction)MenuObj_GetItemStyle, 1,
- PyDoc_STR("(short item) -> (Style chStyle)")},
- {"SetMenuItemCommandID", (PyCFunction)MenuObj_SetMenuItemCommandID, 1,
- PyDoc_STR("(SInt16 inItem, MenuCommand inCommandID) -> None")},
- {"GetMenuItemCommandID", (PyCFunction)MenuObj_GetMenuItemCommandID, 1,
- PyDoc_STR("(SInt16 inItem) -> (MenuCommand outCommandID)")},
- {"SetMenuItemModifiers", (PyCFunction)MenuObj_SetMenuItemModifiers, 1,
- PyDoc_STR("(SInt16 inItem, UInt8 inModifiers) -> None")},
- {"GetMenuItemModifiers", (PyCFunction)MenuObj_GetMenuItemModifiers, 1,
- PyDoc_STR("(SInt16 inItem) -> (UInt8 outModifiers)")},
- {"SetMenuItemIconHandle", (PyCFunction)MenuObj_SetMenuItemIconHandle, 1,
- PyDoc_STR("(SInt16 inItem, UInt8 inIconType, Handle inIconHandle) -> None")},
- {"GetMenuItemIconHandle", (PyCFunction)MenuObj_GetMenuItemIconHandle, 1,
- PyDoc_STR("(SInt16 inItem) -> (UInt8 outIconType, Handle outIconHandle)")},
- {"SetMenuItemTextEncoding", (PyCFunction)MenuObj_SetMenuItemTextEncoding, 1,
- PyDoc_STR("(SInt16 inItem, TextEncoding inScriptID) -> None")},
- {"GetMenuItemTextEncoding", (PyCFunction)MenuObj_GetMenuItemTextEncoding, 1,
- PyDoc_STR("(SInt16 inItem) -> (TextEncoding outScriptID)")},
- {"SetMenuItemHierarchicalID", (PyCFunction)MenuObj_SetMenuItemHierarchicalID, 1,
- PyDoc_STR("(SInt16 inItem, MenuID inHierID) -> None")},
- {"GetMenuItemHierarchicalID", (PyCFunction)MenuObj_GetMenuItemHierarchicalID, 1,
- PyDoc_STR("(SInt16 inItem) -> (MenuID outHierID)")},
- {"SetMenuItemFontID", (PyCFunction)MenuObj_SetMenuItemFontID, 1,
- PyDoc_STR("(SInt16 inItem, SInt16 inFontID) -> None")},
- {"GetMenuItemFontID", (PyCFunction)MenuObj_GetMenuItemFontID, 1,
- PyDoc_STR("(SInt16 inItem) -> (SInt16 outFontID)")},
- {"SetMenuItemRefCon", (PyCFunction)MenuObj_SetMenuItemRefCon, 1,
- PyDoc_STR("(SInt16 inItem, UInt32 inRefCon) -> None")},
- {"GetMenuItemRefCon", (PyCFunction)MenuObj_GetMenuItemRefCon, 1,
- PyDoc_STR("(SInt16 inItem) -> (UInt32 outRefCon)")},
- {"SetMenuItemKeyGlyph", (PyCFunction)MenuObj_SetMenuItemKeyGlyph, 1,
- PyDoc_STR("(SInt16 inItem, SInt16 inGlyph) -> None")},
- {"GetMenuItemKeyGlyph", (PyCFunction)MenuObj_GetMenuItemKeyGlyph, 1,
- PyDoc_STR("(SInt16 inItem) -> (SInt16 outGlyph)")},
- {"MacEnableMenuItem", (PyCFunction)MenuObj_MacEnableMenuItem, 1,
- PyDoc_STR("(MenuItemIndex item) -> None")},
- {"DisableMenuItem", (PyCFunction)MenuObj_DisableMenuItem, 1,
- PyDoc_STR("(MenuItemIndex item) -> None")},
- {"IsMenuItemEnabled", (PyCFunction)MenuObj_IsMenuItemEnabled, 1,
- PyDoc_STR("(MenuItemIndex item) -> (Boolean _rv)")},
- {"EnableMenuItemIcon", (PyCFunction)MenuObj_EnableMenuItemIcon, 1,
- PyDoc_STR("(MenuItemIndex item) -> None")},
- {"DisableMenuItemIcon", (PyCFunction)MenuObj_DisableMenuItemIcon, 1,
- PyDoc_STR("(MenuItemIndex item) -> None")},
- {"IsMenuItemIconEnabled", (PyCFunction)MenuObj_IsMenuItemIconEnabled, 1,
- PyDoc_STR("(MenuItemIndex item) -> (Boolean _rv)")},
- {"SetMenuItemHierarchicalMenu", (PyCFunction)MenuObj_SetMenuItemHierarchicalMenu, 1,
- PyDoc_STR("(MenuItemIndex inItem, MenuHandle inHierMenu) -> None")},
- {"GetMenuItemHierarchicalMenu", (PyCFunction)MenuObj_GetMenuItemHierarchicalMenu, 1,
- PyDoc_STR("(MenuItemIndex inItem) -> (MenuHandle outHierMenu)")},
- {"CopyMenuItemTextAsCFString", (PyCFunction)MenuObj_CopyMenuItemTextAsCFString, 1,
- PyDoc_STR("(MenuItemIndex inItem) -> (CFStringRef outString)")},
- {"SetMenuItemTextWithCFString", (PyCFunction)MenuObj_SetMenuItemTextWithCFString, 1,
- PyDoc_STR("(MenuItemIndex inItem, CFStringRef inString) -> None")},
- {"GetMenuItemIndent", (PyCFunction)MenuObj_GetMenuItemIndent, 1,
- PyDoc_STR("(MenuItemIndex inItem) -> (UInt32 outIndent)")},
- {"SetMenuItemIndent", (PyCFunction)MenuObj_SetMenuItemIndent, 1,
- PyDoc_STR("(MenuItemIndex inItem, UInt32 inIndent) -> None")},
- {"GetMenuItemCommandKey", (PyCFunction)MenuObj_GetMenuItemCommandKey, 1,
- PyDoc_STR("(MenuItemIndex inItem, Boolean inGetVirtualKey) -> (UInt16 outKey)")},
- {"SetMenuItemCommandKey", (PyCFunction)MenuObj_SetMenuItemCommandKey, 1,
- PyDoc_STR("(MenuItemIndex inItem, Boolean inSetVirtualKey, UInt16 inKey) -> None")},
- {"GetMenuItemPropertyAttributes", (PyCFunction)MenuObj_GetMenuItemPropertyAttributes, 1,
- PyDoc_STR("(MenuItemIndex item, OSType propertyCreator, OSType propertyTag) -> (UInt32 attributes)")},
- {"ChangeMenuItemPropertyAttributes", (PyCFunction)MenuObj_ChangeMenuItemPropertyAttributes, 1,
- PyDoc_STR("(MenuItemIndex item, OSType propertyCreator, OSType propertyTag, UInt32 attributesToSet, UInt32 attributesToClear) -> None")},
- {"GetMenuAttributes", (PyCFunction)MenuObj_GetMenuAttributes, 1,
- PyDoc_STR("() -> (MenuAttributes outAttributes)")},
- {"ChangeMenuAttributes", (PyCFunction)MenuObj_ChangeMenuAttributes, 1,
- PyDoc_STR("(MenuAttributes setTheseAttributes, MenuAttributes clearTheseAttributes) -> None")},
- {"GetMenuItemAttributes", (PyCFunction)MenuObj_GetMenuItemAttributes, 1,
- PyDoc_STR("(MenuItemIndex item) -> (MenuItemAttributes outAttributes)")},
- {"ChangeMenuItemAttributes", (PyCFunction)MenuObj_ChangeMenuItemAttributes, 1,
- PyDoc_STR("(MenuItemIndex item, MenuItemAttributes setTheseAttributes, MenuItemAttributes clearTheseAttributes) -> None")},
- {"DisableAllMenuItems", (PyCFunction)MenuObj_DisableAllMenuItems, 1,
- PyDoc_STR("() -> None")},
- {"EnableAllMenuItems", (PyCFunction)MenuObj_EnableAllMenuItems, 1,
- PyDoc_STR("() -> None")},
- {"MenuHasEnabledItems", (PyCFunction)MenuObj_MenuHasEnabledItems, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetMenuType", (PyCFunction)MenuObj_GetMenuType, 1,
- PyDoc_STR("() -> (UInt16 outType)")},
- {"CountMenuItemsWithCommandID", (PyCFunction)MenuObj_CountMenuItemsWithCommandID, 1,
- PyDoc_STR("(MenuCommand inCommandID) -> (ItemCount _rv)")},
- {"GetIndMenuItemWithCommandID", (PyCFunction)MenuObj_GetIndMenuItemWithCommandID, 1,
- PyDoc_STR("(MenuCommand inCommandID, UInt32 inItemIndex) -> (MenuHandle outMenu, MenuItemIndex outIndex)")},
- {"EnableMenuCommand", (PyCFunction)MenuObj_EnableMenuCommand, 1,
- PyDoc_STR("(MenuCommand inCommandID) -> None")},
- {"DisableMenuCommand", (PyCFunction)MenuObj_DisableMenuCommand, 1,
- PyDoc_STR("(MenuCommand inCommandID) -> None")},
- {"IsMenuCommandEnabled", (PyCFunction)MenuObj_IsMenuCommandEnabled, 1,
- PyDoc_STR("(MenuCommand inCommandID) -> (Boolean _rv)")},
- {"SetMenuCommandMark", (PyCFunction)MenuObj_SetMenuCommandMark, 1,
- PyDoc_STR("(MenuCommand inCommandID, UniChar inMark) -> None")},
- {"GetMenuCommandMark", (PyCFunction)MenuObj_GetMenuCommandMark, 1,
- PyDoc_STR("(MenuCommand inCommandID) -> (UniChar outMark)")},
- {"GetMenuCommandPropertySize", (PyCFunction)MenuObj_GetMenuCommandPropertySize, 1,
- PyDoc_STR("(MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> (ByteCount outSize)")},
- {"RemoveMenuCommandProperty", (PyCFunction)MenuObj_RemoveMenuCommandProperty, 1,
- PyDoc_STR("(MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> None")},
- {"IsMenuItemInvalid", (PyCFunction)MenuObj_IsMenuItemInvalid, 1,
- PyDoc_STR("(MenuItemIndex inItem) -> (Boolean _rv)")},
- {"InvalidateMenuItems", (PyCFunction)MenuObj_InvalidateMenuItems, 1,
- PyDoc_STR("(MenuItemIndex inFirstItem, ItemCount inNumItems) -> None")},
- {"UpdateInvalidMenuItems", (PyCFunction)MenuObj_UpdateInvalidMenuItems, 1,
- PyDoc_STR("() -> None")},
- {"CreateStandardFontMenu", (PyCFunction)MenuObj_CreateStandardFontMenu, 1,
- PyDoc_STR("(MenuItemIndex afterItem, MenuID firstHierMenuID, OptionBits options) -> (ItemCount outHierMenuCount)")},
- {"UpdateStandardFontMenu", (PyCFunction)MenuObj_UpdateStandardFontMenu, 1,
- PyDoc_STR("() -> (ItemCount outHierMenuCount)")},
- {"GetFontFamilyFromMenuSelection", (PyCFunction)MenuObj_GetFontFamilyFromMenuSelection, 1,
- PyDoc_STR("(MenuItemIndex item) -> (FMFontFamily outFontFamily, FMFontStyle outStyle)")},
- {"GetMenuID", (PyCFunction)MenuObj_GetMenuID, 1,
- PyDoc_STR("() -> (MenuID _rv)")},
- {"GetMenuWidth", (PyCFunction)MenuObj_GetMenuWidth, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"GetMenuHeight", (PyCFunction)MenuObj_GetMenuHeight, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"SetMenuID", (PyCFunction)MenuObj_SetMenuID, 1,
- PyDoc_STR("(MenuID menuID) -> None")},
- {"SetMenuWidth", (PyCFunction)MenuObj_SetMenuWidth, 1,
- PyDoc_STR("(SInt16 width) -> None")},
- {"SetMenuHeight", (PyCFunction)MenuObj_SetMenuHeight, 1,
- PyDoc_STR("(SInt16 height) -> None")},
- {"as_Resource", (PyCFunction)MenuObj_as_Resource, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"AppendMenu", (PyCFunction)MenuObj_AppendMenu, 1,
- PyDoc_STR("(Str255 data) -> None")},
- {"InsertMenu", (PyCFunction)MenuObj_InsertMenu, 1,
- PyDoc_STR("(short beforeID) -> None")},
- {"InsertMenuItem", (PyCFunction)MenuObj_InsertMenuItem, 1,
- PyDoc_STR("(Str255 itemString, short afterItem) -> None")},
- {"EnableMenuItem", (PyCFunction)MenuObj_EnableMenuItem, 1,
- PyDoc_STR("(UInt16 item) -> None")},
- {"CheckMenuItem", (PyCFunction)MenuObj_CheckMenuItem, 1,
- PyDoc_STR("(short item, Boolean checked) -> None")},
- {NULL, NULL, 0}
+ {"DisposeMenu", (PyCFunction)MenuObj_DisposeMenu, 1,
+ PyDoc_STR("() -> None")},
+ {"CalcMenuSize", (PyCFunction)MenuObj_CalcMenuSize, 1,
+ PyDoc_STR("() -> None")},
+ {"CountMenuItems", (PyCFunction)MenuObj_CountMenuItems, 1,
+ PyDoc_STR("() -> (UInt16 _rv)")},
+ {"GetMenuFont", (PyCFunction)MenuObj_GetMenuFont, 1,
+ PyDoc_STR("() -> (SInt16 outFontID, UInt16 outFontSize)")},
+ {"SetMenuFont", (PyCFunction)MenuObj_SetMenuFont, 1,
+ PyDoc_STR("(SInt16 inFontID, UInt16 inFontSize) -> None")},
+ {"GetMenuExcludesMarkColumn", (PyCFunction)MenuObj_GetMenuExcludesMarkColumn, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SetMenuExcludesMarkColumn", (PyCFunction)MenuObj_SetMenuExcludesMarkColumn, 1,
+ PyDoc_STR("(Boolean excludesMark) -> None")},
+ {"IsValidMenu", (PyCFunction)MenuObj_IsValidMenu, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetMenuRetainCount", (PyCFunction)MenuObj_GetMenuRetainCount, 1,
+ PyDoc_STR("() -> (ItemCount _rv)")},
+ {"RetainMenu", (PyCFunction)MenuObj_RetainMenu, 1,
+ PyDoc_STR("() -> None")},
+ {"ReleaseMenu", (PyCFunction)MenuObj_ReleaseMenu, 1,
+ PyDoc_STR("() -> None")},
+ {"DuplicateMenu", (PyCFunction)MenuObj_DuplicateMenu, 1,
+ PyDoc_STR("() -> (MenuHandle outMenu)")},
+ {"CopyMenuTitleAsCFString", (PyCFunction)MenuObj_CopyMenuTitleAsCFString, 1,
+ PyDoc_STR("() -> (CFStringRef outString)")},
+ {"SetMenuTitleWithCFString", (PyCFunction)MenuObj_SetMenuTitleWithCFString, 1,
+ PyDoc_STR("(CFStringRef inString) -> None")},
+ {"InvalidateMenuSize", (PyCFunction)MenuObj_InvalidateMenuSize, 1,
+ PyDoc_STR("() -> None")},
+ {"IsMenuSizeInvalid", (PyCFunction)MenuObj_IsMenuSizeInvalid, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"MacAppendMenu", (PyCFunction)MenuObj_MacAppendMenu, 1,
+ PyDoc_STR("(Str255 data) -> None")},
+ {"InsertResMenu", (PyCFunction)MenuObj_InsertResMenu, 1,
+ PyDoc_STR("(ResType theType, short afterItem) -> None")},
+ {"AppendResMenu", (PyCFunction)MenuObj_AppendResMenu, 1,
+ PyDoc_STR("(ResType theType) -> None")},
+ {"MacInsertMenuItem", (PyCFunction)MenuObj_MacInsertMenuItem, 1,
+ PyDoc_STR("(Str255 itemString, short afterItem) -> None")},
+ {"DeleteMenuItem", (PyCFunction)MenuObj_DeleteMenuItem, 1,
+ PyDoc_STR("(short item) -> None")},
+ {"InsertFontResMenu", (PyCFunction)MenuObj_InsertFontResMenu, 1,
+ PyDoc_STR("(short afterItem, short scriptFilter) -> None")},
+ {"InsertIntlResMenu", (PyCFunction)MenuObj_InsertIntlResMenu, 1,
+ PyDoc_STR("(ResType theType, short afterItem, short scriptFilter) -> None")},
+ {"AppendMenuItemText", (PyCFunction)MenuObj_AppendMenuItemText, 1,
+ PyDoc_STR("(Str255 inString) -> None")},
+ {"InsertMenuItemText", (PyCFunction)MenuObj_InsertMenuItemText, 1,
+ PyDoc_STR("(Str255 inString, MenuItemIndex afterItem) -> None")},
+ {"CopyMenuItems", (PyCFunction)MenuObj_CopyMenuItems, 1,
+ PyDoc_STR("(MenuItemIndex inFirstItem, ItemCount inNumItems, MenuHandle inDestMenu, MenuItemIndex inInsertAfter) -> None")},
+ {"DeleteMenuItems", (PyCFunction)MenuObj_DeleteMenuItems, 1,
+ PyDoc_STR("(MenuItemIndex inFirstItem, ItemCount inNumItems) -> None")},
+ {"AppendMenuItemTextWithCFString", (PyCFunction)MenuObj_AppendMenuItemTextWithCFString, 1,
+ PyDoc_STR("(CFStringRef inString, MenuItemAttributes inAttributes, MenuCommand inCommandID) -> (MenuItemIndex outNewItem)")},
+ {"InsertMenuItemTextWithCFString", (PyCFunction)MenuObj_InsertMenuItemTextWithCFString, 1,
+ PyDoc_STR("(CFStringRef inString, MenuItemIndex inAfterItem, MenuItemAttributes inAttributes, MenuCommand inCommandID) -> None")},
+ {"PopUpMenuSelect", (PyCFunction)MenuObj_PopUpMenuSelect, 1,
+ PyDoc_STR("(short top, short left, short popUpItem) -> (long _rv)")},
+ {"InvalidateMenuEnabling", (PyCFunction)MenuObj_InvalidateMenuEnabling, 1,
+ PyDoc_STR("() -> None")},
+ {"IsMenuBarInvalid", (PyCFunction)MenuObj_IsMenuBarInvalid, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"MacInsertMenu", (PyCFunction)MenuObj_MacInsertMenu, 1,
+ PyDoc_STR("(MenuID beforeID) -> None")},
+ {"SetRootMenu", (PyCFunction)MenuObj_SetRootMenu, 1,
+ PyDoc_STR("() -> None")},
+ {"MacCheckMenuItem", (PyCFunction)MenuObj_MacCheckMenuItem, 1,
+ PyDoc_STR("(short item, Boolean checked) -> None")},
+ {"SetMenuItemText", (PyCFunction)MenuObj_SetMenuItemText, 1,
+ PyDoc_STR("(short item, Str255 itemString) -> None")},
+ {"GetMenuItemText", (PyCFunction)MenuObj_GetMenuItemText, 1,
+ PyDoc_STR("(short item) -> (Str255 itemString)")},
+ {"SetItemMark", (PyCFunction)MenuObj_SetItemMark, 1,
+ PyDoc_STR("(short item, CharParameter markChar) -> None")},
+ {"GetItemMark", (PyCFunction)MenuObj_GetItemMark, 1,
+ PyDoc_STR("(short item) -> (CharParameter markChar)")},
+ {"SetItemCmd", (PyCFunction)MenuObj_SetItemCmd, 1,
+ PyDoc_STR("(short item, CharParameter cmdChar) -> None")},
+ {"GetItemCmd", (PyCFunction)MenuObj_GetItemCmd, 1,
+ PyDoc_STR("(short item) -> (CharParameter cmdChar)")},
+ {"SetItemIcon", (PyCFunction)MenuObj_SetItemIcon, 1,
+ PyDoc_STR("(short item, short iconIndex) -> None")},
+ {"GetItemIcon", (PyCFunction)MenuObj_GetItemIcon, 1,
+ PyDoc_STR("(short item) -> (short iconIndex)")},
+ {"SetItemStyle", (PyCFunction)MenuObj_SetItemStyle, 1,
+ PyDoc_STR("(short item, StyleParameter chStyle) -> None")},
+ {"GetItemStyle", (PyCFunction)MenuObj_GetItemStyle, 1,
+ PyDoc_STR("(short item) -> (Style chStyle)")},
+ {"SetMenuItemCommandID", (PyCFunction)MenuObj_SetMenuItemCommandID, 1,
+ PyDoc_STR("(SInt16 inItem, MenuCommand inCommandID) -> None")},
+ {"GetMenuItemCommandID", (PyCFunction)MenuObj_GetMenuItemCommandID, 1,
+ PyDoc_STR("(SInt16 inItem) -> (MenuCommand outCommandID)")},
+ {"SetMenuItemModifiers", (PyCFunction)MenuObj_SetMenuItemModifiers, 1,
+ PyDoc_STR("(SInt16 inItem, UInt8 inModifiers) -> None")},
+ {"GetMenuItemModifiers", (PyCFunction)MenuObj_GetMenuItemModifiers, 1,
+ PyDoc_STR("(SInt16 inItem) -> (UInt8 outModifiers)")},
+ {"SetMenuItemIconHandle", (PyCFunction)MenuObj_SetMenuItemIconHandle, 1,
+ PyDoc_STR("(SInt16 inItem, UInt8 inIconType, Handle inIconHandle) -> None")},
+ {"GetMenuItemIconHandle", (PyCFunction)MenuObj_GetMenuItemIconHandle, 1,
+ PyDoc_STR("(SInt16 inItem) -> (UInt8 outIconType, Handle outIconHandle)")},
+ {"SetMenuItemTextEncoding", (PyCFunction)MenuObj_SetMenuItemTextEncoding, 1,
+ PyDoc_STR("(SInt16 inItem, TextEncoding inScriptID) -> None")},
+ {"GetMenuItemTextEncoding", (PyCFunction)MenuObj_GetMenuItemTextEncoding, 1,
+ PyDoc_STR("(SInt16 inItem) -> (TextEncoding outScriptID)")},
+ {"SetMenuItemHierarchicalID", (PyCFunction)MenuObj_SetMenuItemHierarchicalID, 1,
+ PyDoc_STR("(SInt16 inItem, MenuID inHierID) -> None")},
+ {"GetMenuItemHierarchicalID", (PyCFunction)MenuObj_GetMenuItemHierarchicalID, 1,
+ PyDoc_STR("(SInt16 inItem) -> (MenuID outHierID)")},
+ {"SetMenuItemFontID", (PyCFunction)MenuObj_SetMenuItemFontID, 1,
+ PyDoc_STR("(SInt16 inItem, SInt16 inFontID) -> None")},
+ {"GetMenuItemFontID", (PyCFunction)MenuObj_GetMenuItemFontID, 1,
+ PyDoc_STR("(SInt16 inItem) -> (SInt16 outFontID)")},
+ {"SetMenuItemRefCon", (PyCFunction)MenuObj_SetMenuItemRefCon, 1,
+ PyDoc_STR("(SInt16 inItem, UInt32 inRefCon) -> None")},
+ {"GetMenuItemRefCon", (PyCFunction)MenuObj_GetMenuItemRefCon, 1,
+ PyDoc_STR("(SInt16 inItem) -> (UInt32 outRefCon)")},
+ {"SetMenuItemKeyGlyph", (PyCFunction)MenuObj_SetMenuItemKeyGlyph, 1,
+ PyDoc_STR("(SInt16 inItem, SInt16 inGlyph) -> None")},
+ {"GetMenuItemKeyGlyph", (PyCFunction)MenuObj_GetMenuItemKeyGlyph, 1,
+ PyDoc_STR("(SInt16 inItem) -> (SInt16 outGlyph)")},
+ {"MacEnableMenuItem", (PyCFunction)MenuObj_MacEnableMenuItem, 1,
+ PyDoc_STR("(MenuItemIndex item) -> None")},
+ {"DisableMenuItem", (PyCFunction)MenuObj_DisableMenuItem, 1,
+ PyDoc_STR("(MenuItemIndex item) -> None")},
+ {"IsMenuItemEnabled", (PyCFunction)MenuObj_IsMenuItemEnabled, 1,
+ PyDoc_STR("(MenuItemIndex item) -> (Boolean _rv)")},
+ {"EnableMenuItemIcon", (PyCFunction)MenuObj_EnableMenuItemIcon, 1,
+ PyDoc_STR("(MenuItemIndex item) -> None")},
+ {"DisableMenuItemIcon", (PyCFunction)MenuObj_DisableMenuItemIcon, 1,
+ PyDoc_STR("(MenuItemIndex item) -> None")},
+ {"IsMenuItemIconEnabled", (PyCFunction)MenuObj_IsMenuItemIconEnabled, 1,
+ PyDoc_STR("(MenuItemIndex item) -> (Boolean _rv)")},
+ {"SetMenuItemHierarchicalMenu", (PyCFunction)MenuObj_SetMenuItemHierarchicalMenu, 1,
+ PyDoc_STR("(MenuItemIndex inItem, MenuHandle inHierMenu) -> None")},
+ {"GetMenuItemHierarchicalMenu", (PyCFunction)MenuObj_GetMenuItemHierarchicalMenu, 1,
+ PyDoc_STR("(MenuItemIndex inItem) -> (MenuHandle outHierMenu)")},
+ {"CopyMenuItemTextAsCFString", (PyCFunction)MenuObj_CopyMenuItemTextAsCFString, 1,
+ PyDoc_STR("(MenuItemIndex inItem) -> (CFStringRef outString)")},
+ {"SetMenuItemTextWithCFString", (PyCFunction)MenuObj_SetMenuItemTextWithCFString, 1,
+ PyDoc_STR("(MenuItemIndex inItem, CFStringRef inString) -> None")},
+ {"GetMenuItemIndent", (PyCFunction)MenuObj_GetMenuItemIndent, 1,
+ PyDoc_STR("(MenuItemIndex inItem) -> (UInt32 outIndent)")},
+ {"SetMenuItemIndent", (PyCFunction)MenuObj_SetMenuItemIndent, 1,
+ PyDoc_STR("(MenuItemIndex inItem, UInt32 inIndent) -> None")},
+ {"GetMenuItemCommandKey", (PyCFunction)MenuObj_GetMenuItemCommandKey, 1,
+ PyDoc_STR("(MenuItemIndex inItem, Boolean inGetVirtualKey) -> (UInt16 outKey)")},
+ {"SetMenuItemCommandKey", (PyCFunction)MenuObj_SetMenuItemCommandKey, 1,
+ PyDoc_STR("(MenuItemIndex inItem, Boolean inSetVirtualKey, UInt16 inKey) -> None")},
+ {"GetMenuItemPropertyAttributes", (PyCFunction)MenuObj_GetMenuItemPropertyAttributes, 1,
+ PyDoc_STR("(MenuItemIndex item, OSType propertyCreator, OSType propertyTag) -> (UInt32 attributes)")},
+ {"ChangeMenuItemPropertyAttributes", (PyCFunction)MenuObj_ChangeMenuItemPropertyAttributes, 1,
+ PyDoc_STR("(MenuItemIndex item, OSType propertyCreator, OSType propertyTag, UInt32 attributesToSet, UInt32 attributesToClear) -> None")},
+ {"GetMenuAttributes", (PyCFunction)MenuObj_GetMenuAttributes, 1,
+ PyDoc_STR("() -> (MenuAttributes outAttributes)")},
+ {"ChangeMenuAttributes", (PyCFunction)MenuObj_ChangeMenuAttributes, 1,
+ PyDoc_STR("(MenuAttributes setTheseAttributes, MenuAttributes clearTheseAttributes) -> None")},
+ {"GetMenuItemAttributes", (PyCFunction)MenuObj_GetMenuItemAttributes, 1,
+ PyDoc_STR("(MenuItemIndex item) -> (MenuItemAttributes outAttributes)")},
+ {"ChangeMenuItemAttributes", (PyCFunction)MenuObj_ChangeMenuItemAttributes, 1,
+ PyDoc_STR("(MenuItemIndex item, MenuItemAttributes setTheseAttributes, MenuItemAttributes clearTheseAttributes) -> None")},
+ {"DisableAllMenuItems", (PyCFunction)MenuObj_DisableAllMenuItems, 1,
+ PyDoc_STR("() -> None")},
+ {"EnableAllMenuItems", (PyCFunction)MenuObj_EnableAllMenuItems, 1,
+ PyDoc_STR("() -> None")},
+ {"MenuHasEnabledItems", (PyCFunction)MenuObj_MenuHasEnabledItems, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetMenuType", (PyCFunction)MenuObj_GetMenuType, 1,
+ PyDoc_STR("() -> (UInt16 outType)")},
+ {"CountMenuItemsWithCommandID", (PyCFunction)MenuObj_CountMenuItemsWithCommandID, 1,
+ PyDoc_STR("(MenuCommand inCommandID) -> (ItemCount _rv)")},
+ {"GetIndMenuItemWithCommandID", (PyCFunction)MenuObj_GetIndMenuItemWithCommandID, 1,
+ PyDoc_STR("(MenuCommand inCommandID, UInt32 inItemIndex) -> (MenuHandle outMenu, MenuItemIndex outIndex)")},
+ {"EnableMenuCommand", (PyCFunction)MenuObj_EnableMenuCommand, 1,
+ PyDoc_STR("(MenuCommand inCommandID) -> None")},
+ {"DisableMenuCommand", (PyCFunction)MenuObj_DisableMenuCommand, 1,
+ PyDoc_STR("(MenuCommand inCommandID) -> None")},
+ {"IsMenuCommandEnabled", (PyCFunction)MenuObj_IsMenuCommandEnabled, 1,
+ PyDoc_STR("(MenuCommand inCommandID) -> (Boolean _rv)")},
+ {"SetMenuCommandMark", (PyCFunction)MenuObj_SetMenuCommandMark, 1,
+ PyDoc_STR("(MenuCommand inCommandID, UniChar inMark) -> None")},
+ {"GetMenuCommandMark", (PyCFunction)MenuObj_GetMenuCommandMark, 1,
+ PyDoc_STR("(MenuCommand inCommandID) -> (UniChar outMark)")},
+ {"GetMenuCommandPropertySize", (PyCFunction)MenuObj_GetMenuCommandPropertySize, 1,
+ PyDoc_STR("(MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> (ByteCount outSize)")},
+ {"RemoveMenuCommandProperty", (PyCFunction)MenuObj_RemoveMenuCommandProperty, 1,
+ PyDoc_STR("(MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> None")},
+ {"IsMenuItemInvalid", (PyCFunction)MenuObj_IsMenuItemInvalid, 1,
+ PyDoc_STR("(MenuItemIndex inItem) -> (Boolean _rv)")},
+ {"InvalidateMenuItems", (PyCFunction)MenuObj_InvalidateMenuItems, 1,
+ PyDoc_STR("(MenuItemIndex inFirstItem, ItemCount inNumItems) -> None")},
+ {"UpdateInvalidMenuItems", (PyCFunction)MenuObj_UpdateInvalidMenuItems, 1,
+ PyDoc_STR("() -> None")},
+ {"CreateStandardFontMenu", (PyCFunction)MenuObj_CreateStandardFontMenu, 1,
+ PyDoc_STR("(MenuItemIndex afterItem, MenuID firstHierMenuID, OptionBits options) -> (ItemCount outHierMenuCount)")},
+ {"UpdateStandardFontMenu", (PyCFunction)MenuObj_UpdateStandardFontMenu, 1,
+ PyDoc_STR("() -> (ItemCount outHierMenuCount)")},
+ {"GetFontFamilyFromMenuSelection", (PyCFunction)MenuObj_GetFontFamilyFromMenuSelection, 1,
+ PyDoc_STR("(MenuItemIndex item) -> (FMFontFamily outFontFamily, FMFontStyle outStyle)")},
+ {"GetMenuID", (PyCFunction)MenuObj_GetMenuID, 1,
+ PyDoc_STR("() -> (MenuID _rv)")},
+ {"GetMenuWidth", (PyCFunction)MenuObj_GetMenuWidth, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"GetMenuHeight", (PyCFunction)MenuObj_GetMenuHeight, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"SetMenuID", (PyCFunction)MenuObj_SetMenuID, 1,
+ PyDoc_STR("(MenuID menuID) -> None")},
+ {"SetMenuWidth", (PyCFunction)MenuObj_SetMenuWidth, 1,
+ PyDoc_STR("(SInt16 width) -> None")},
+ {"SetMenuHeight", (PyCFunction)MenuObj_SetMenuHeight, 1,
+ PyDoc_STR("(SInt16 height) -> None")},
+ {"as_Resource", (PyCFunction)MenuObj_as_Resource, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"AppendMenu", (PyCFunction)MenuObj_AppendMenu, 1,
+ PyDoc_STR("(Str255 data) -> None")},
+ {"InsertMenu", (PyCFunction)MenuObj_InsertMenu, 1,
+ PyDoc_STR("(short beforeID) -> None")},
+ {"InsertMenuItem", (PyCFunction)MenuObj_InsertMenuItem, 1,
+ PyDoc_STR("(Str255 itemString, short afterItem) -> None")},
+ {"EnableMenuItem", (PyCFunction)MenuObj_EnableMenuItem, 1,
+ PyDoc_STR("(UInt16 item) -> None")},
+ {"CheckMenuItem", (PyCFunction)MenuObj_CheckMenuItem, 1,
+ PyDoc_STR("(short item, Boolean checked) -> None")},
+ {NULL, NULL, 0}
};
#define MenuObj_getsetlist NULL
@@ -2540,61 +2540,61 @@ static PyMethodDef MenuObj_methods[] = {
static PyObject *MenuObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- MenuHandle itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ MenuHandle itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MenuObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((MenuObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MenuObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((MenuObject *)_self)->ob_itself = itself;
+ return _self;
}
#define MenuObj_tp_free PyObject_Del
PyTypeObject Menu_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Menu.Menu", /*tp_name*/
- sizeof(MenuObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) MenuObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) MenuObj_compare, /*tp_compare*/
- (reprfunc) MenuObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) MenuObj_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*/
- MenuObj_methods, /* tp_methods */
- 0, /*tp_members*/
- MenuObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- MenuObj_tp_init, /* tp_init */
- MenuObj_tp_alloc, /* tp_alloc */
- MenuObj_tp_new, /* tp_new */
- MenuObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Menu.Menu", /*tp_name*/
+ sizeof(MenuObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) MenuObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) MenuObj_compare, /*tp_compare*/
+ (reprfunc) MenuObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) MenuObj_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*/
+ MenuObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ MenuObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ MenuObj_tp_init, /* tp_init */
+ MenuObj_tp_alloc, /* tp_alloc */
+ MenuObj_tp_new, /* tp_new */
+ MenuObj_tp_free, /* tp_free */
};
/* ---------------------- End object type Menu ---------------------- */
@@ -2602,842 +2602,842 @@ PyTypeObject Menu_Type = {
static PyObject *Menu_NewMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
- MenuID menuID;
- Str255 menuTitle;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
+ MenuID menuID;
+ Str255 menuTitle;
#ifndef NewMenu
- PyMac_PRECHECK(NewMenu);
+ PyMac_PRECHECK(NewMenu);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &menuID,
- PyMac_GetStr255, menuTitle))
- return NULL;
- _rv = NewMenu(menuID,
- menuTitle);
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &menuID,
+ PyMac_GetStr255, menuTitle))
+ return NULL;
+ _rv = NewMenu(menuID,
+ menuTitle);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *Menu_MacGetMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
- short resourceID;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
+ short resourceID;
#ifndef MacGetMenu
- PyMac_PRECHECK(MacGetMenu);
+ PyMac_PRECHECK(MacGetMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &resourceID))
- return NULL;
- _rv = MacGetMenu(resourceID);
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &resourceID))
+ return NULL;
+ _rv = MacGetMenu(resourceID);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *Menu_CreateNewMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuID inMenuID;
- MenuAttributes inMenuAttributes;
- MenuHandle outMenuRef;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuID inMenuID;
+ MenuAttributes inMenuAttributes;
+ MenuHandle outMenuRef;
#ifndef CreateNewMenu
- PyMac_PRECHECK(CreateNewMenu);
+ PyMac_PRECHECK(CreateNewMenu);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &inMenuID,
- &inMenuAttributes))
- return NULL;
- _err = CreateNewMenu(inMenuID,
- inMenuAttributes,
- &outMenuRef);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- MenuObj_New, outMenuRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &inMenuID,
+ &inMenuAttributes))
+ return NULL;
+ _err = CreateNewMenu(inMenuID,
+ inMenuAttributes,
+ &outMenuRef);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, outMenuRef);
+ return _res;
}
static PyObject *Menu_MenuKey(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- CharParameter ch;
+ PyObject *_res = NULL;
+ long _rv;
+ CharParameter ch;
#ifndef MenuKey
- PyMac_PRECHECK(MenuKey);
+ PyMac_PRECHECK(MenuKey);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &ch))
- return NULL;
- _rv = MenuKey(ch);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &ch))
+ return NULL;
+ _rv = MenuKey(ch);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Menu_MenuSelect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- Point startPt;
+ PyObject *_res = NULL;
+ long _rv;
+ Point startPt;
#ifndef MenuSelect
- PyMac_PRECHECK(MenuSelect);
+ PyMac_PRECHECK(MenuSelect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &startPt))
- return NULL;
- _rv = MenuSelect(startPt);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &startPt))
+ return NULL;
+ _rv = MenuSelect(startPt);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Menu_MenuChoice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef MenuChoice
- PyMac_PRECHECK(MenuChoice);
+ PyMac_PRECHECK(MenuChoice);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MenuChoice();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MenuChoice();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Menu_MenuEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
- EventRecord inEvent;
+ PyObject *_res = NULL;
+ UInt32 _rv;
+ EventRecord inEvent;
#ifndef MenuEvent
- PyMac_PRECHECK(MenuEvent);
+ PyMac_PRECHECK(MenuEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &inEvent))
- return NULL;
- _rv = MenuEvent(&inEvent);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &inEvent))
+ return NULL;
+ _rv = MenuEvent(&inEvent);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Menu_GetMBarHeight(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetMBarHeight
- PyMac_PRECHECK(GetMBarHeight);
+ PyMac_PRECHECK(GetMBarHeight);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMBarHeight();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMBarHeight();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Menu_MacDrawMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef MacDrawMenuBar
- PyMac_PRECHECK(MacDrawMenuBar);
+ PyMac_PRECHECK(MacDrawMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- MacDrawMenuBar();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ MacDrawMenuBar();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_InvalMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef InvalMenuBar
- PyMac_PRECHECK(InvalMenuBar);
+ PyMac_PRECHECK(InvalMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- InvalMenuBar();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ InvalMenuBar();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_HiliteMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID menuID;
+ PyObject *_res = NULL;
+ MenuID menuID;
#ifndef HiliteMenu
- PyMac_PRECHECK(HiliteMenu);
+ PyMac_PRECHECK(HiliteMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- HiliteMenu(menuID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ HiliteMenu(menuID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_GetNewMBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuBarHandle _rv;
- short menuBarID;
+ PyObject *_res = NULL;
+ MenuBarHandle _rv;
+ short menuBarID;
#ifndef GetNewMBar
- PyMac_PRECHECK(GetNewMBar);
+ PyMac_PRECHECK(GetNewMBar);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuBarID))
- return NULL;
- _rv = GetNewMBar(menuBarID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuBarID))
+ return NULL;
+ _rv = GetNewMBar(menuBarID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Menu_GetMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuBarHandle _rv;
+ PyObject *_res = NULL;
+ MenuBarHandle _rv;
#ifndef GetMenuBar
- PyMac_PRECHECK(GetMenuBar);
+ PyMac_PRECHECK(GetMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMenuBar();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMenuBar();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Menu_SetMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuBarHandle mbar;
+ PyObject *_res = NULL;
+ MenuBarHandle mbar;
#ifndef SetMenuBar
- PyMac_PRECHECK(SetMenuBar);
+ PyMac_PRECHECK(SetMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &mbar))
- return NULL;
- SetMenuBar(mbar);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &mbar))
+ return NULL;
+ SetMenuBar(mbar);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_DuplicateMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuBarHandle inMbar;
- MenuBarHandle outMbar;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuBarHandle inMbar;
+ MenuBarHandle outMbar;
#ifndef DuplicateMenuBar
- PyMac_PRECHECK(DuplicateMenuBar);
+ PyMac_PRECHECK(DuplicateMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inMbar))
- return NULL;
- _err = DuplicateMenuBar(inMbar,
- &outMbar);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, outMbar);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inMbar))
+ return NULL;
+ _err = DuplicateMenuBar(inMbar,
+ &outMbar);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, outMbar);
+ return _res;
}
static PyObject *Menu_DisposeMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuBarHandle inMbar;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuBarHandle inMbar;
#ifndef DisposeMenuBar
- PyMac_PRECHECK(DisposeMenuBar);
+ PyMac_PRECHECK(DisposeMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inMbar))
- return NULL;
- _err = DisposeMenuBar(inMbar);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inMbar))
+ return NULL;
+ _err = DisposeMenuBar(inMbar);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_GetMenuHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
- MenuID menuID;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
+ MenuID menuID;
#ifndef GetMenuHandle
- PyMac_PRECHECK(GetMenuHandle);
+ PyMac_PRECHECK(GetMenuHandle);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- _rv = GetMenuHandle(menuID);
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ _rv = GetMenuHandle(menuID);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *Menu_MacDeleteMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID menuID;
+ PyObject *_res = NULL;
+ MenuID menuID;
#ifndef MacDeleteMenu
- PyMac_PRECHECK(MacDeleteMenu);
+ PyMac_PRECHECK(MacDeleteMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- MacDeleteMenu(menuID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ MacDeleteMenu(menuID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_ClearMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClearMenuBar
- PyMac_PRECHECK(ClearMenuBar);
+ PyMac_PRECHECK(ClearMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClearMenuBar();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClearMenuBar();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_SetMenuFlashCount(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short count;
+ PyObject *_res = NULL;
+ short count;
#ifndef SetMenuFlashCount
- PyMac_PRECHECK(SetMenuFlashCount);
+ PyMac_PRECHECK(SetMenuFlashCount);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &count))
- return NULL;
- SetMenuFlashCount(count);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &count))
+ return NULL;
+ SetMenuFlashCount(count);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_FlashMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID menuID;
+ PyObject *_res = NULL;
+ MenuID menuID;
#ifndef FlashMenuBar
- PyMac_PRECHECK(FlashMenuBar);
+ PyMac_PRECHECK(FlashMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- FlashMenuBar(menuID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ FlashMenuBar(menuID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_IsMenuBarVisible(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsMenuBarVisible
- PyMac_PRECHECK(IsMenuBarVisible);
+ PyMac_PRECHECK(IsMenuBarVisible);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsMenuBarVisible();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsMenuBarVisible();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Menu_ShowMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ShowMenuBar
- PyMac_PRECHECK(ShowMenuBar);
+ PyMac_PRECHECK(ShowMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ShowMenuBar();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ShowMenuBar();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_HideMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef HideMenuBar
- PyMac_PRECHECK(HideMenuBar);
+ PyMac_PRECHECK(HideMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- HideMenuBar();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ HideMenuBar();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_AcquireRootMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
#ifndef AcquireRootMenu
- PyMac_PRECHECK(AcquireRootMenu);
+ PyMac_PRECHECK(AcquireRootMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = AcquireRootMenu();
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = AcquireRootMenu();
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *Menu_DeleteMCEntries(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuID menuID;
- short menuItem;
+ PyObject *_res = NULL;
+ MenuID menuID;
+ short menuItem;
#ifndef DeleteMCEntries
- PyMac_PRECHECK(DeleteMCEntries);
+ PyMac_PRECHECK(DeleteMCEntries);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &menuID,
- &menuItem))
- return NULL;
- DeleteMCEntries(menuID,
- menuItem);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &menuID,
+ &menuItem))
+ return NULL;
+ DeleteMCEntries(menuID,
+ menuItem);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_InitContextualMenus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef InitContextualMenus
- PyMac_PRECHECK(InitContextualMenus);
+ PyMac_PRECHECK(InitContextualMenus);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = InitContextualMenus();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = InitContextualMenus();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_IsShowContextualMenuClick(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord inEvent;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord inEvent;
#ifndef IsShowContextualMenuClick
- PyMac_PRECHECK(IsShowContextualMenuClick);
+ PyMac_PRECHECK(IsShowContextualMenuClick);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &inEvent))
- return NULL;
- _rv = IsShowContextualMenuClick(&inEvent);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &inEvent))
+ return NULL;
+ _rv = IsShowContextualMenuClick(&inEvent);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Menu_LMGetTheMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef LMGetTheMenu
- PyMac_PRECHECK(LMGetTheMenu);
+ PyMac_PRECHECK(LMGetTheMenu);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetTheMenu();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetTheMenu();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Menu_as_Menu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
- Handle h;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
+ Handle h;
#ifndef as_Menu
- PyMac_PRECHECK(as_Menu);
+ PyMac_PRECHECK(as_Menu);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &h))
- return NULL;
- _rv = as_Menu(h);
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = as_Menu(h);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *Menu_GetMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle _rv;
- short resourceID;
+ PyObject *_res = NULL;
+ MenuHandle _rv;
+ short resourceID;
#ifndef GetMenu
- PyMac_PRECHECK(GetMenu);
+ PyMac_PRECHECK(GetMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &resourceID))
- return NULL;
- _rv = GetMenu(resourceID);
- _res = Py_BuildValue("O&",
- MenuObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &resourceID))
+ return NULL;
+ _rv = GetMenu(resourceID);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, _rv);
+ return _res;
}
static PyObject *Menu_DeleteMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short menuID;
+ PyObject *_res = NULL;
+ short menuID;
#ifndef DeleteMenu
- PyMac_PRECHECK(DeleteMenu);
+ PyMac_PRECHECK(DeleteMenu);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &menuID))
- return NULL;
- DeleteMenu(menuID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &menuID))
+ return NULL;
+ DeleteMenu(menuID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_DrawMenuBar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DrawMenuBar
- PyMac_PRECHECK(DrawMenuBar);
+ PyMac_PRECHECK(DrawMenuBar);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DrawMenuBar();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DrawMenuBar();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_CountMenuItemsWithCommandID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ItemCount _rv;
- MenuHandle inMenu;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ ItemCount _rv;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
#ifndef CountMenuItemsWithCommandID
- PyMac_PRECHECK(CountMenuItemsWithCommandID);
+ PyMac_PRECHECK(CountMenuItemsWithCommandID);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- OptMenuObj_Convert, &inMenu,
- &inCommandID))
- return NULL;
- _rv = CountMenuItemsWithCommandID(inMenu,
- inCommandID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID))
+ return NULL;
+ _rv = CountMenuItemsWithCommandID(inMenu,
+ inCommandID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Menu_GetIndMenuItemWithCommandID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle inMenu;
- MenuCommand inCommandID;
- UInt32 inItemIndex;
- MenuHandle outMenu;
- MenuItemIndex outIndex;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
+ UInt32 inItemIndex;
+ MenuHandle outMenu;
+ MenuItemIndex outIndex;
#ifndef GetIndMenuItemWithCommandID
- PyMac_PRECHECK(GetIndMenuItemWithCommandID);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- OptMenuObj_Convert, &inMenu,
- &inCommandID,
- &inItemIndex))
- return NULL;
- _err = GetIndMenuItemWithCommandID(inMenu,
- inCommandID,
- inItemIndex,
- &outMenu,
- &outIndex);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- MenuObj_New, outMenu,
- outIndex);
- return _res;
+ PyMac_PRECHECK(GetIndMenuItemWithCommandID);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID,
+ &inItemIndex))
+ return NULL;
+ _err = GetIndMenuItemWithCommandID(inMenu,
+ inCommandID,
+ inItemIndex,
+ &outMenu,
+ &outIndex);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ MenuObj_New, outMenu,
+ outIndex);
+ return _res;
}
static PyObject *Menu_EnableMenuCommand(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle inMenu;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
#ifndef EnableMenuCommand
- PyMac_PRECHECK(EnableMenuCommand);
+ PyMac_PRECHECK(EnableMenuCommand);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- OptMenuObj_Convert, &inMenu,
- &inCommandID))
- return NULL;
- EnableMenuCommand(inMenu,
- inCommandID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID))
+ return NULL;
+ EnableMenuCommand(inMenu,
+ inCommandID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_DisableMenuCommand(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MenuHandle inMenu;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
#ifndef DisableMenuCommand
- PyMac_PRECHECK(DisableMenuCommand);
+ PyMac_PRECHECK(DisableMenuCommand);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- OptMenuObj_Convert, &inMenu,
- &inCommandID))
- return NULL;
- DisableMenuCommand(inMenu,
- inCommandID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID))
+ return NULL;
+ DisableMenuCommand(inMenu,
+ inCommandID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_IsMenuCommandEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- MenuHandle inMenu;
- MenuCommand inCommandID;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
#ifndef IsMenuCommandEnabled
- PyMac_PRECHECK(IsMenuCommandEnabled);
+ PyMac_PRECHECK(IsMenuCommandEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- OptMenuObj_Convert, &inMenu,
- &inCommandID))
- return NULL;
- _rv = IsMenuCommandEnabled(inMenu,
- inCommandID);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID))
+ return NULL;
+ _rv = IsMenuCommandEnabled(inMenu,
+ inCommandID);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Menu_SetMenuCommandMark(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle inMenu;
- MenuCommand inCommandID;
- UniChar inMark;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
+ UniChar inMark;
#ifndef SetMenuCommandMark
- PyMac_PRECHECK(SetMenuCommandMark);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lh",
- OptMenuObj_Convert, &inMenu,
- &inCommandID,
- &inMark))
- return NULL;
- _err = SetMenuCommandMark(inMenu,
- inCommandID,
- inMark);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetMenuCommandMark);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lh",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID,
+ &inMark))
+ return NULL;
+ _err = SetMenuCommandMark(inMenu,
+ inCommandID,
+ inMark);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Menu_GetMenuCommandMark(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle inMenu;
- MenuCommand inCommandID;
- UniChar outMark;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
+ UniChar outMark;
#ifndef GetMenuCommandMark
- PyMac_PRECHECK(GetMenuCommandMark);
+ PyMac_PRECHECK(GetMenuCommandMark);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- OptMenuObj_Convert, &inMenu,
- &inCommandID))
- return NULL;
- _err = GetMenuCommandMark(inMenu,
- inCommandID,
- &outMark);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outMark);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID))
+ return NULL;
+ _err = GetMenuCommandMark(inMenu,
+ inCommandID,
+ &outMark);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outMark);
+ return _res;
}
static PyObject *Menu_GetMenuCommandPropertySize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle inMenu;
- MenuCommand inCommandID;
- OSType inPropertyCreator;
- OSType inPropertyTag;
- ByteCount outSize;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
+ OSType inPropertyCreator;
+ OSType inPropertyTag;
+ ByteCount outSize;
#ifndef GetMenuCommandPropertySize
- PyMac_PRECHECK(GetMenuCommandPropertySize);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&O&",
- OptMenuObj_Convert, &inMenu,
- &inCommandID,
- PyMac_GetOSType, &inPropertyCreator,
- PyMac_GetOSType, &inPropertyTag))
- return NULL;
- _err = GetMenuCommandPropertySize(inMenu,
- inCommandID,
- inPropertyCreator,
- inPropertyTag,
- &outSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outSize);
- return _res;
+ PyMac_PRECHECK(GetMenuCommandPropertySize);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&O&",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID,
+ PyMac_GetOSType, &inPropertyCreator,
+ PyMac_GetOSType, &inPropertyTag))
+ return NULL;
+ _err = GetMenuCommandPropertySize(inMenu,
+ inCommandID,
+ inPropertyCreator,
+ inPropertyTag,
+ &outSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outSize);
+ return _res;
}
static PyObject *Menu_RemoveMenuCommandProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle inMenu;
- MenuCommand inCommandID;
- OSType inPropertyCreator;
- OSType inPropertyTag;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle inMenu;
+ MenuCommand inCommandID;
+ OSType inPropertyCreator;
+ OSType inPropertyTag;
#ifndef RemoveMenuCommandProperty
- PyMac_PRECHECK(RemoveMenuCommandProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&O&",
- OptMenuObj_Convert, &inMenu,
- &inCommandID,
- PyMac_GetOSType, &inPropertyCreator,
- PyMac_GetOSType, &inPropertyTag))
- return NULL;
- _err = RemoveMenuCommandProperty(inMenu,
- inCommandID,
- inPropertyCreator,
- inPropertyTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(RemoveMenuCommandProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&O&",
+ OptMenuObj_Convert, &inMenu,
+ &inCommandID,
+ PyMac_GetOSType, &inPropertyCreator,
+ PyMac_GetOSType, &inPropertyTag))
+ return NULL;
+ _err = RemoveMenuCommandProperty(inMenu,
+ inCommandID,
+ inPropertyCreator,
+ inPropertyTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Menu_methods[] = {
#ifndef __LP64__
- {"NewMenu", (PyCFunction)Menu_NewMenu, 1,
- PyDoc_STR("(MenuID menuID, Str255 menuTitle) -> (MenuHandle _rv)")},
- {"MacGetMenu", (PyCFunction)Menu_MacGetMenu, 1,
- PyDoc_STR("(short resourceID) -> (MenuHandle _rv)")},
- {"CreateNewMenu", (PyCFunction)Menu_CreateNewMenu, 1,
- PyDoc_STR("(MenuID inMenuID, MenuAttributes inMenuAttributes) -> (MenuHandle outMenuRef)")},
- {"MenuKey", (PyCFunction)Menu_MenuKey, 1,
- PyDoc_STR("(CharParameter ch) -> (long _rv)")},
- {"MenuSelect", (PyCFunction)Menu_MenuSelect, 1,
- PyDoc_STR("(Point startPt) -> (long _rv)")},
- {"MenuChoice", (PyCFunction)Menu_MenuChoice, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"MenuEvent", (PyCFunction)Menu_MenuEvent, 1,
- PyDoc_STR("(EventRecord inEvent) -> (UInt32 _rv)")},
- {"GetMBarHeight", (PyCFunction)Menu_GetMBarHeight, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"MacDrawMenuBar", (PyCFunction)Menu_MacDrawMenuBar, 1,
- PyDoc_STR("() -> None")},
- {"InvalMenuBar", (PyCFunction)Menu_InvalMenuBar, 1,
- PyDoc_STR("() -> None")},
- {"HiliteMenu", (PyCFunction)Menu_HiliteMenu, 1,
- PyDoc_STR("(MenuID menuID) -> None")},
- {"GetNewMBar", (PyCFunction)Menu_GetNewMBar, 1,
- PyDoc_STR("(short menuBarID) -> (MenuBarHandle _rv)")},
- {"GetMenuBar", (PyCFunction)Menu_GetMenuBar, 1,
- PyDoc_STR("() -> (MenuBarHandle _rv)")},
- {"SetMenuBar", (PyCFunction)Menu_SetMenuBar, 1,
- PyDoc_STR("(MenuBarHandle mbar) -> None")},
- {"DuplicateMenuBar", (PyCFunction)Menu_DuplicateMenuBar, 1,
- PyDoc_STR("(MenuBarHandle inMbar) -> (MenuBarHandle outMbar)")},
- {"DisposeMenuBar", (PyCFunction)Menu_DisposeMenuBar, 1,
- PyDoc_STR("(MenuBarHandle inMbar) -> None")},
- {"GetMenuHandle", (PyCFunction)Menu_GetMenuHandle, 1,
- PyDoc_STR("(MenuID menuID) -> (MenuHandle _rv)")},
- {"MacDeleteMenu", (PyCFunction)Menu_MacDeleteMenu, 1,
- PyDoc_STR("(MenuID menuID) -> None")},
- {"ClearMenuBar", (PyCFunction)Menu_ClearMenuBar, 1,
- PyDoc_STR("() -> None")},
- {"SetMenuFlashCount", (PyCFunction)Menu_SetMenuFlashCount, 1,
- PyDoc_STR("(short count) -> None")},
- {"FlashMenuBar", (PyCFunction)Menu_FlashMenuBar, 1,
- PyDoc_STR("(MenuID menuID) -> None")},
- {"IsMenuBarVisible", (PyCFunction)Menu_IsMenuBarVisible, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"ShowMenuBar", (PyCFunction)Menu_ShowMenuBar, 1,
- PyDoc_STR("() -> None")},
- {"HideMenuBar", (PyCFunction)Menu_HideMenuBar, 1,
- PyDoc_STR("() -> None")},
- {"AcquireRootMenu", (PyCFunction)Menu_AcquireRootMenu, 1,
- PyDoc_STR("() -> (MenuHandle _rv)")},
- {"DeleteMCEntries", (PyCFunction)Menu_DeleteMCEntries, 1,
- PyDoc_STR("(MenuID menuID, short menuItem) -> None")},
- {"InitContextualMenus", (PyCFunction)Menu_InitContextualMenus, 1,
- PyDoc_STR("() -> None")},
- {"IsShowContextualMenuClick", (PyCFunction)Menu_IsShowContextualMenuClick, 1,
- PyDoc_STR("(EventRecord inEvent) -> (Boolean _rv)")},
- {"LMGetTheMenu", (PyCFunction)Menu_LMGetTheMenu, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"as_Menu", (PyCFunction)Menu_as_Menu, 1,
- PyDoc_STR("(Handle h) -> (MenuHandle _rv)")},
- {"GetMenu", (PyCFunction)Menu_GetMenu, 1,
- PyDoc_STR("(short resourceID) -> (MenuHandle _rv)")},
- {"DeleteMenu", (PyCFunction)Menu_DeleteMenu, 1,
- PyDoc_STR("(short menuID) -> None")},
- {"DrawMenuBar", (PyCFunction)Menu_DrawMenuBar, 1,
- PyDoc_STR("() -> None")},
- {"CountMenuItemsWithCommandID", (PyCFunction)Menu_CountMenuItemsWithCommandID, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> (ItemCount _rv)")},
- {"GetIndMenuItemWithCommandID", (PyCFunction)Menu_GetIndMenuItemWithCommandID, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, UInt32 inItemIndex) -> (MenuHandle outMenu, MenuItemIndex outIndex)")},
- {"EnableMenuCommand", (PyCFunction)Menu_EnableMenuCommand, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> None")},
- {"DisableMenuCommand", (PyCFunction)Menu_DisableMenuCommand, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> None")},
- {"IsMenuCommandEnabled", (PyCFunction)Menu_IsMenuCommandEnabled, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> (Boolean _rv)")},
- {"SetMenuCommandMark", (PyCFunction)Menu_SetMenuCommandMark, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, UniChar inMark) -> None")},
- {"GetMenuCommandMark", (PyCFunction)Menu_GetMenuCommandMark, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> (UniChar outMark)")},
- {"GetMenuCommandPropertySize", (PyCFunction)Menu_GetMenuCommandPropertySize, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> (ByteCount outSize)")},
- {"RemoveMenuCommandProperty", (PyCFunction)Menu_RemoveMenuCommandProperty, 1,
- PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> None")},
+ {"NewMenu", (PyCFunction)Menu_NewMenu, 1,
+ PyDoc_STR("(MenuID menuID, Str255 menuTitle) -> (MenuHandle _rv)")},
+ {"MacGetMenu", (PyCFunction)Menu_MacGetMenu, 1,
+ PyDoc_STR("(short resourceID) -> (MenuHandle _rv)")},
+ {"CreateNewMenu", (PyCFunction)Menu_CreateNewMenu, 1,
+ PyDoc_STR("(MenuID inMenuID, MenuAttributes inMenuAttributes) -> (MenuHandle outMenuRef)")},
+ {"MenuKey", (PyCFunction)Menu_MenuKey, 1,
+ PyDoc_STR("(CharParameter ch) -> (long _rv)")},
+ {"MenuSelect", (PyCFunction)Menu_MenuSelect, 1,
+ PyDoc_STR("(Point startPt) -> (long _rv)")},
+ {"MenuChoice", (PyCFunction)Menu_MenuChoice, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"MenuEvent", (PyCFunction)Menu_MenuEvent, 1,
+ PyDoc_STR("(EventRecord inEvent) -> (UInt32 _rv)")},
+ {"GetMBarHeight", (PyCFunction)Menu_GetMBarHeight, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"MacDrawMenuBar", (PyCFunction)Menu_MacDrawMenuBar, 1,
+ PyDoc_STR("() -> None")},
+ {"InvalMenuBar", (PyCFunction)Menu_InvalMenuBar, 1,
+ PyDoc_STR("() -> None")},
+ {"HiliteMenu", (PyCFunction)Menu_HiliteMenu, 1,
+ PyDoc_STR("(MenuID menuID) -> None")},
+ {"GetNewMBar", (PyCFunction)Menu_GetNewMBar, 1,
+ PyDoc_STR("(short menuBarID) -> (MenuBarHandle _rv)")},
+ {"GetMenuBar", (PyCFunction)Menu_GetMenuBar, 1,
+ PyDoc_STR("() -> (MenuBarHandle _rv)")},
+ {"SetMenuBar", (PyCFunction)Menu_SetMenuBar, 1,
+ PyDoc_STR("(MenuBarHandle mbar) -> None")},
+ {"DuplicateMenuBar", (PyCFunction)Menu_DuplicateMenuBar, 1,
+ PyDoc_STR("(MenuBarHandle inMbar) -> (MenuBarHandle outMbar)")},
+ {"DisposeMenuBar", (PyCFunction)Menu_DisposeMenuBar, 1,
+ PyDoc_STR("(MenuBarHandle inMbar) -> None")},
+ {"GetMenuHandle", (PyCFunction)Menu_GetMenuHandle, 1,
+ PyDoc_STR("(MenuID menuID) -> (MenuHandle _rv)")},
+ {"MacDeleteMenu", (PyCFunction)Menu_MacDeleteMenu, 1,
+ PyDoc_STR("(MenuID menuID) -> None")},
+ {"ClearMenuBar", (PyCFunction)Menu_ClearMenuBar, 1,
+ PyDoc_STR("() -> None")},
+ {"SetMenuFlashCount", (PyCFunction)Menu_SetMenuFlashCount, 1,
+ PyDoc_STR("(short count) -> None")},
+ {"FlashMenuBar", (PyCFunction)Menu_FlashMenuBar, 1,
+ PyDoc_STR("(MenuID menuID) -> None")},
+ {"IsMenuBarVisible", (PyCFunction)Menu_IsMenuBarVisible, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"ShowMenuBar", (PyCFunction)Menu_ShowMenuBar, 1,
+ PyDoc_STR("() -> None")},
+ {"HideMenuBar", (PyCFunction)Menu_HideMenuBar, 1,
+ PyDoc_STR("() -> None")},
+ {"AcquireRootMenu", (PyCFunction)Menu_AcquireRootMenu, 1,
+ PyDoc_STR("() -> (MenuHandle _rv)")},
+ {"DeleteMCEntries", (PyCFunction)Menu_DeleteMCEntries, 1,
+ PyDoc_STR("(MenuID menuID, short menuItem) -> None")},
+ {"InitContextualMenus", (PyCFunction)Menu_InitContextualMenus, 1,
+ PyDoc_STR("() -> None")},
+ {"IsShowContextualMenuClick", (PyCFunction)Menu_IsShowContextualMenuClick, 1,
+ PyDoc_STR("(EventRecord inEvent) -> (Boolean _rv)")},
+ {"LMGetTheMenu", (PyCFunction)Menu_LMGetTheMenu, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"as_Menu", (PyCFunction)Menu_as_Menu, 1,
+ PyDoc_STR("(Handle h) -> (MenuHandle _rv)")},
+ {"GetMenu", (PyCFunction)Menu_GetMenu, 1,
+ PyDoc_STR("(short resourceID) -> (MenuHandle _rv)")},
+ {"DeleteMenu", (PyCFunction)Menu_DeleteMenu, 1,
+ PyDoc_STR("(short menuID) -> None")},
+ {"DrawMenuBar", (PyCFunction)Menu_DrawMenuBar, 1,
+ PyDoc_STR("() -> None")},
+ {"CountMenuItemsWithCommandID", (PyCFunction)Menu_CountMenuItemsWithCommandID, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> (ItemCount _rv)")},
+ {"GetIndMenuItemWithCommandID", (PyCFunction)Menu_GetIndMenuItemWithCommandID, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, UInt32 inItemIndex) -> (MenuHandle outMenu, MenuItemIndex outIndex)")},
+ {"EnableMenuCommand", (PyCFunction)Menu_EnableMenuCommand, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> None")},
+ {"DisableMenuCommand", (PyCFunction)Menu_DisableMenuCommand, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> None")},
+ {"IsMenuCommandEnabled", (PyCFunction)Menu_IsMenuCommandEnabled, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> (Boolean _rv)")},
+ {"SetMenuCommandMark", (PyCFunction)Menu_SetMenuCommandMark, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, UniChar inMark) -> None")},
+ {"GetMenuCommandMark", (PyCFunction)Menu_GetMenuCommandMark, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID) -> (UniChar outMark)")},
+ {"GetMenuCommandPropertySize", (PyCFunction)Menu_GetMenuCommandPropertySize, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> (ByteCount outSize)")},
+ {"RemoveMenuCommandProperty", (PyCFunction)Menu_RemoveMenuCommandProperty, 1,
+ PyDoc_STR("(MenuHandle inMenu, MenuCommand inCommandID, OSType inPropertyCreator, OSType inPropertyTag) -> None")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -3445,31 +3445,31 @@ static PyMethodDef Menu_methods[] = {
void init_Menu(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(MenuHandle, MenuObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MenuHandle, MenuObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(MenuHandle, MenuObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MenuHandle, MenuObj_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_Menu", Menu_methods);
+ m = Py_InitModule("_Menu", Menu_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Menu_Error = PyMac_GetOSErrException();
- if (Menu_Error == NULL ||
- PyDict_SetItemString(d, "Error", Menu_Error) != 0)
- return;
- Menu_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Menu_Type) < 0) return;
- Py_INCREF(&Menu_Type);
- PyModule_AddObject(m, "Menu", (PyObject *)&Menu_Type);
- /* Backward-compatible name */
- Py_INCREF(&Menu_Type);
- PyModule_AddObject(m, "MenuType", (PyObject *)&Menu_Type);
+ d = PyModule_GetDict(m);
+ Menu_Error = PyMac_GetOSErrException();
+ if (Menu_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Menu_Error) != 0)
+ return;
+ Menu_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Menu_Type) < 0) return;
+ Py_INCREF(&Menu_Type);
+ PyModule_AddObject(m, "Menu", (PyObject *)&Menu_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Menu_Type);
+ PyModule_AddObject(m, "MenuType", (PyObject *)&Menu_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/mlte/_Mltemodule.c b/Mac/Modules/mlte/_Mltemodule.c
index 1a6b6a4..cd698f4 100644
--- a/Mac/Modules/mlte/_Mltemodule.c
+++ b/Mac/Modules/mlte/_Mltemodule.c
@@ -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)
@@ -39,14 +39,14 @@ static int TXNFontMenuObj_Convert(PyObject *, TXNFontMenuObject *);
static int
OptFSSpecPtr_Convert(PyObject *v, FSSpec **p_itself)
{
- static FSSpec fss;
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- *p_itself = &fss;
- return PyMac_GetFSSpec(v, *p_itself);
+ static FSSpec fss;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ *p_itself = &fss;
+ return PyMac_GetFSSpec(v, *p_itself);
}
/*
@@ -55,12 +55,12 @@ OptFSSpecPtr_Convert(PyObject *v, FSSpec **p_itself)
static int
OptGWorldObj_Convert(PyObject *v, GWorldPtr *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- return GWorldObj_Convert(v, p_itself);
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ return GWorldObj_Convert(v, p_itself);
}
@@ -73,1159 +73,1159 @@ PyTypeObject TXNObject_Type;
#define TXNObj_Check(x) ((x)->ob_type == &TXNObject_Type || PyObject_TypeCheck((x), &TXNObject_Type))
typedef struct TXNObjectObject {
- PyObject_HEAD
- TXNObject ob_itself;
+ PyObject_HEAD
+ TXNObject ob_itself;
} TXNObjectObject;
PyObject *TXNObj_New(TXNObject itself)
{
- TXNObjectObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(TXNObjectObject, &TXNObject_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ TXNObjectObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(TXNObjectObject, &TXNObject_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int TXNObj_Convert(PyObject *v, TXNObject *p_itself)
{
- if (!TXNObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "TXNObject required");
- return 0;
- }
- *p_itself = ((TXNObjectObject *)v)->ob_itself;
- return 1;
+ if (!TXNObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "TXNObject required");
+ return 0;
+ }
+ *p_itself = ((TXNObjectObject *)v)->ob_itself;
+ return 1;
}
static void TXNObj_dealloc(TXNObjectObject *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 *TXNObj_TXNDeleteObject(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNDeleteObject
- PyMac_PRECHECK(TXNDeleteObject);
+ PyMac_PRECHECK(TXNDeleteObject);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNDeleteObject(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNDeleteObject(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNResizeFrame(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 iWidth;
- UInt32 iHeight;
- TXNFrameID iTXNFrameID;
+ PyObject *_res = NULL;
+ UInt32 iWidth;
+ UInt32 iHeight;
+ TXNFrameID iTXNFrameID;
#ifndef TXNResizeFrame
- PyMac_PRECHECK(TXNResizeFrame);
+ PyMac_PRECHECK(TXNResizeFrame);
#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &iWidth,
- &iHeight,
- &iTXNFrameID))
- return NULL;
- TXNResizeFrame(_self->ob_itself,
- iWidth,
- iHeight,
- iTXNFrameID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lll",
+ &iWidth,
+ &iHeight,
+ &iTXNFrameID))
+ return NULL;
+ TXNResizeFrame(_self->ob_itself,
+ iWidth,
+ iHeight,
+ iTXNFrameID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNSetFrameBounds(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 iTop;
- SInt32 iLeft;
- SInt32 iBottom;
- SInt32 iRight;
- TXNFrameID iTXNFrameID;
+ PyObject *_res = NULL;
+ SInt32 iTop;
+ SInt32 iLeft;
+ SInt32 iBottom;
+ SInt32 iRight;
+ TXNFrameID iTXNFrameID;
#ifndef TXNSetFrameBounds
- PyMac_PRECHECK(TXNSetFrameBounds);
+ PyMac_PRECHECK(TXNSetFrameBounds);
#endif
- if (!PyArg_ParseTuple(_args, "lllll",
- &iTop,
- &iLeft,
- &iBottom,
- &iRight,
- &iTXNFrameID))
- return NULL;
- TXNSetFrameBounds(_self->ob_itself,
- iTop,
- iLeft,
- iBottom,
- iRight,
- iTXNFrameID);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lllll",
+ &iTop,
+ &iLeft,
+ &iBottom,
+ &iRight,
+ &iTXNFrameID))
+ return NULL;
+ TXNSetFrameBounds(_self->ob_itself,
+ iTop,
+ iLeft,
+ iBottom,
+ iRight,
+ iTXNFrameID);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNKeyDown(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventRecord iEvent;
+ PyObject *_res = NULL;
+ EventRecord iEvent;
#ifndef TXNKeyDown
- PyMac_PRECHECK(TXNKeyDown);
+ PyMac_PRECHECK(TXNKeyDown);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &iEvent))
- return NULL;
- TXNKeyDown(_self->ob_itself,
- &iEvent);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &iEvent))
+ return NULL;
+ TXNKeyDown(_self->ob_itself,
+ &iEvent);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNAdjustCursor(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle ioCursorRgn;
+ PyObject *_res = NULL;
+ RgnHandle ioCursorRgn;
#ifndef TXNAdjustCursor
- PyMac_PRECHECK(TXNAdjustCursor);
+ PyMac_PRECHECK(TXNAdjustCursor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- OptResObj_Convert, &ioCursorRgn))
- return NULL;
- TXNAdjustCursor(_self->ob_itself,
- ioCursorRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptResObj_Convert, &ioCursorRgn))
+ return NULL;
+ TXNAdjustCursor(_self->ob_itself,
+ ioCursorRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNClick(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventRecord iEvent;
+ PyObject *_res = NULL;
+ EventRecord iEvent;
#ifndef TXNClick
- PyMac_PRECHECK(TXNClick);
+ PyMac_PRECHECK(TXNClick);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &iEvent))
- return NULL;
- TXNClick(_self->ob_itself,
- &iEvent);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &iEvent))
+ return NULL;
+ TXNClick(_self->ob_itself,
+ &iEvent);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNSelectAll(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNSelectAll
- PyMac_PRECHECK(TXNSelectAll);
+ PyMac_PRECHECK(TXNSelectAll);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNSelectAll(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNSelectAll(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNFocus(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean iBecomingFocused;
+ PyObject *_res = NULL;
+ Boolean iBecomingFocused;
#ifndef TXNFocus
- PyMac_PRECHECK(TXNFocus);
+ PyMac_PRECHECK(TXNFocus);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &iBecomingFocused))
- return NULL;
- TXNFocus(_self->ob_itself,
- iBecomingFocused);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &iBecomingFocused))
+ return NULL;
+ TXNFocus(_self->ob_itself,
+ iBecomingFocused);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNUpdate(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNUpdate
- PyMac_PRECHECK(TXNUpdate);
+ PyMac_PRECHECK(TXNUpdate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNUpdate(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNUpdate(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNDraw(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GWorldPtr iDrawPort;
+ PyObject *_res = NULL;
+ GWorldPtr iDrawPort;
#ifndef TXNDraw
- PyMac_PRECHECK(TXNDraw);
+ PyMac_PRECHECK(TXNDraw);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- OptGWorldObj_Convert, &iDrawPort))
- return NULL;
- TXNDraw(_self->ob_itself,
- iDrawPort);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptGWorldObj_Convert, &iDrawPort))
+ return NULL;
+ TXNDraw(_self->ob_itself,
+ iDrawPort);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNForceUpdate(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNForceUpdate
- PyMac_PRECHECK(TXNForceUpdate);
+ PyMac_PRECHECK(TXNForceUpdate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNForceUpdate(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNForceUpdate(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNGetSleepTicks(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt32 _rv;
+ PyObject *_res = NULL;
+ UInt32 _rv;
#ifndef TXNGetSleepTicks
- PyMac_PRECHECK(TXNGetSleepTicks);
+ PyMac_PRECHECK(TXNGetSleepTicks);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNGetSleepTicks(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNGetSleepTicks(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TXNObj_TXNIdle(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNIdle
- PyMac_PRECHECK(TXNIdle);
+ PyMac_PRECHECK(TXNIdle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNIdle(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNIdle(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNGrowWindow(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- EventRecord iEvent;
+ PyObject *_res = NULL;
+ EventRecord iEvent;
#ifndef TXNGrowWindow
- PyMac_PRECHECK(TXNGrowWindow);
+ PyMac_PRECHECK(TXNGrowWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &iEvent))
- return NULL;
- TXNGrowWindow(_self->ob_itself,
- &iEvent);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &iEvent))
+ return NULL;
+ TXNGrowWindow(_self->ob_itself,
+ &iEvent);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNZoomWindow(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 iPart;
+ PyObject *_res = NULL;
+ SInt16 iPart;
#ifndef TXNZoomWindow
- PyMac_PRECHECK(TXNZoomWindow);
+ PyMac_PRECHECK(TXNZoomWindow);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &iPart))
- return NULL;
- TXNZoomWindow(_self->ob_itself,
- iPart);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &iPart))
+ return NULL;
+ TXNZoomWindow(_self->ob_itself,
+ iPart);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNCanUndo(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- TXNActionKey oTXNActionKey;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ TXNActionKey oTXNActionKey;
#ifndef TXNCanUndo
- PyMac_PRECHECK(TXNCanUndo);
+ PyMac_PRECHECK(TXNCanUndo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNCanUndo(_self->ob_itself,
- &oTXNActionKey);
- _res = Py_BuildValue("bl",
- _rv,
- oTXNActionKey);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNCanUndo(_self->ob_itself,
+ &oTXNActionKey);
+ _res = Py_BuildValue("bl",
+ _rv,
+ oTXNActionKey);
+ return _res;
}
static PyObject *TXNObj_TXNUndo(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNUndo
- PyMac_PRECHECK(TXNUndo);
+ PyMac_PRECHECK(TXNUndo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNUndo(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNUndo(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNCanRedo(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- TXNActionKey oTXNActionKey;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ TXNActionKey oTXNActionKey;
#ifndef TXNCanRedo
- PyMac_PRECHECK(TXNCanRedo);
+ PyMac_PRECHECK(TXNCanRedo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNCanRedo(_self->ob_itself,
- &oTXNActionKey);
- _res = Py_BuildValue("bl",
- _rv,
- oTXNActionKey);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNCanRedo(_self->ob_itself,
+ &oTXNActionKey);
+ _res = Py_BuildValue("bl",
+ _rv,
+ oTXNActionKey);
+ return _res;
}
static PyObject *TXNObj_TXNRedo(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNRedo
- PyMac_PRECHECK(TXNRedo);
+ PyMac_PRECHECK(TXNRedo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNRedo(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNRedo(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNCut(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNCut
- PyMac_PRECHECK(TXNCut);
+ PyMac_PRECHECK(TXNCut);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNCut(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNCut(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNCopy(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNCopy
- PyMac_PRECHECK(TXNCopy);
+ PyMac_PRECHECK(TXNCopy);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNCopy(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNCopy(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNPaste(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNPaste
- PyMac_PRECHECK(TXNPaste);
+ PyMac_PRECHECK(TXNPaste);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNPaste(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNPaste(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNClear(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNClear
- PyMac_PRECHECK(TXNClear);
+ PyMac_PRECHECK(TXNClear);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNClear(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNClear(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNGetSelection(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TXNOffset oStartOffset;
- TXNOffset oEndOffset;
+ PyObject *_res = NULL;
+ TXNOffset oStartOffset;
+ TXNOffset oEndOffset;
#ifndef TXNGetSelection
- PyMac_PRECHECK(TXNGetSelection);
+ PyMac_PRECHECK(TXNGetSelection);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNGetSelection(_self->ob_itself,
- &oStartOffset,
- &oEndOffset);
- _res = Py_BuildValue("ll",
- oStartOffset,
- oEndOffset);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNGetSelection(_self->ob_itself,
+ &oStartOffset,
+ &oEndOffset);
+ _res = Py_BuildValue("ll",
+ oStartOffset,
+ oEndOffset);
+ return _res;
}
static PyObject *TXNObj_TXNShowSelection(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean iShowEnd;
+ PyObject *_res = NULL;
+ Boolean iShowEnd;
#ifndef TXNShowSelection
- PyMac_PRECHECK(TXNShowSelection);
+ PyMac_PRECHECK(TXNShowSelection);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &iShowEnd))
- return NULL;
- TXNShowSelection(_self->ob_itself,
- iShowEnd);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &iShowEnd))
+ return NULL;
+ TXNShowSelection(_self->ob_itself,
+ iShowEnd);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNIsSelectionEmpty(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef TXNIsSelectionEmpty
- PyMac_PRECHECK(TXNIsSelectionEmpty);
+ PyMac_PRECHECK(TXNIsSelectionEmpty);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNIsSelectionEmpty(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNIsSelectionEmpty(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *TXNObj_TXNSetSelection(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNOffset iStartOffset;
- TXNOffset iEndOffset;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNOffset iStartOffset;
+ TXNOffset iEndOffset;
#ifndef TXNSetSelection
- PyMac_PRECHECK(TXNSetSelection);
+ PyMac_PRECHECK(TXNSetSelection);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &iStartOffset,
- &iEndOffset))
- return NULL;
- _err = TXNSetSelection(_self->ob_itself,
- iStartOffset,
- iEndOffset);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &iStartOffset,
+ &iEndOffset))
+ return NULL;
+ _err = TXNSetSelection(_self->ob_itself,
+ iStartOffset,
+ iEndOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNCountRunsInRange(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNOffset iStartOffset;
- TXNOffset iEndOffset;
- ItemCount oRunCount;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNOffset iStartOffset;
+ TXNOffset iEndOffset;
+ ItemCount oRunCount;
#ifndef TXNCountRunsInRange
- PyMac_PRECHECK(TXNCountRunsInRange);
+ PyMac_PRECHECK(TXNCountRunsInRange);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &iStartOffset,
- &iEndOffset))
- return NULL;
- _err = TXNCountRunsInRange(_self->ob_itself,
- iStartOffset,
- iEndOffset,
- &oRunCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- oRunCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &iStartOffset,
+ &iEndOffset))
+ return NULL;
+ _err = TXNCountRunsInRange(_self->ob_itself,
+ iStartOffset,
+ iEndOffset,
+ &oRunCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ oRunCount);
+ return _res;
}
static PyObject *TXNObj_TXNDataSize(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ByteCount _rv;
+ PyObject *_res = NULL;
+ ByteCount _rv;
#ifndef TXNDataSize
- PyMac_PRECHECK(TXNDataSize);
+ PyMac_PRECHECK(TXNDataSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNDataSize(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNDataSize(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TXNObj_TXNGetData(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNOffset iStartOffset;
- TXNOffset iEndOffset;
- Handle oDataHandle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNOffset iStartOffset;
+ TXNOffset iEndOffset;
+ Handle oDataHandle;
#ifndef TXNGetData
- PyMac_PRECHECK(TXNGetData);
+ PyMac_PRECHECK(TXNGetData);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &iStartOffset,
- &iEndOffset))
- return NULL;
- _err = TXNGetData(_self->ob_itself,
- iStartOffset,
- iEndOffset,
- &oDataHandle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, oDataHandle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &iStartOffset,
+ &iEndOffset))
+ return NULL;
+ _err = TXNGetData(_self->ob_itself,
+ iStartOffset,
+ iEndOffset,
+ &oDataHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, oDataHandle);
+ return _res;
}
static PyObject *TXNObj_TXNGetDataEncoded(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNOffset iStartOffset;
- TXNOffset iEndOffset;
- Handle oDataHandle;
- TXNDataType iEncoding;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNOffset iStartOffset;
+ TXNOffset iEndOffset;
+ Handle oDataHandle;
+ TXNDataType iEncoding;
#ifndef TXNGetDataEncoded
- PyMac_PRECHECK(TXNGetDataEncoded);
+ PyMac_PRECHECK(TXNGetDataEncoded);
#endif
- if (!PyArg_ParseTuple(_args, "llO&",
- &iStartOffset,
- &iEndOffset,
- PyMac_GetOSType, &iEncoding))
- return NULL;
- _err = TXNGetDataEncoded(_self->ob_itself,
- iStartOffset,
- iEndOffset,
- &oDataHandle,
- iEncoding);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, oDataHandle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "llO&",
+ &iStartOffset,
+ &iEndOffset,
+ PyMac_GetOSType, &iEncoding))
+ return NULL;
+ _err = TXNGetDataEncoded(_self->ob_itself,
+ iStartOffset,
+ iEndOffset,
+ &oDataHandle,
+ iEncoding);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, oDataHandle);
+ return _res;
}
static PyObject *TXNObj_TXNSetDataFromFile(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 iFileRefNum;
- OSType iFileType;
- ByteCount iFileLength;
- TXNOffset iStartOffset;
- TXNOffset iEndOffset;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 iFileRefNum;
+ OSType iFileType;
+ ByteCount iFileLength;
+ TXNOffset iStartOffset;
+ TXNOffset iEndOffset;
#ifndef TXNSetDataFromFile
- PyMac_PRECHECK(TXNSetDataFromFile);
+ PyMac_PRECHECK(TXNSetDataFromFile);
#endif
- if (!PyArg_ParseTuple(_args, "hO&lll",
- &iFileRefNum,
- PyMac_GetOSType, &iFileType,
- &iFileLength,
- &iStartOffset,
- &iEndOffset))
- return NULL;
- _err = TXNSetDataFromFile(_self->ob_itself,
- iFileRefNum,
- iFileType,
- iFileLength,
- iStartOffset,
- iEndOffset);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&lll",
+ &iFileRefNum,
+ PyMac_GetOSType, &iFileType,
+ &iFileLength,
+ &iStartOffset,
+ &iEndOffset))
+ return NULL;
+ _err = TXNSetDataFromFile(_self->ob_itself,
+ iFileRefNum,
+ iFileType,
+ iFileLength,
+ iStartOffset,
+ iEndOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNGetChangeCount(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ItemCount _rv;
+ PyObject *_res = NULL;
+ ItemCount _rv;
#ifndef TXNGetChangeCount
- PyMac_PRECHECK(TXNGetChangeCount);
+ PyMac_PRECHECK(TXNGetChangeCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNGetChangeCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNGetChangeCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TXNObj_TXNSave(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNFileType iType;
- OSType iResType;
- TXNPermanentTextEncodingType iPermanentEncoding;
- FSSpec iFileSpecification;
- SInt16 iDataReference;
- SInt16 iResourceReference;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNFileType iType;
+ OSType iResType;
+ TXNPermanentTextEncodingType iPermanentEncoding;
+ FSSpec iFileSpecification;
+ SInt16 iDataReference;
+ SInt16 iResourceReference;
#ifndef TXNSave
- PyMac_PRECHECK(TXNSave);
+ PyMac_PRECHECK(TXNSave);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&lO&hh",
- PyMac_GetOSType, &iType,
- PyMac_GetOSType, &iResType,
- &iPermanentEncoding,
- PyMac_GetFSSpec, &iFileSpecification,
- &iDataReference,
- &iResourceReference))
- return NULL;
- _err = TXNSave(_self->ob_itself,
- iType,
- iResType,
- iPermanentEncoding,
- &iFileSpecification,
- iDataReference,
- iResourceReference);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&lO&hh",
+ PyMac_GetOSType, &iType,
+ PyMac_GetOSType, &iResType,
+ &iPermanentEncoding,
+ PyMac_GetFSSpec, &iFileSpecification,
+ &iDataReference,
+ &iResourceReference))
+ return NULL;
+ _err = TXNSave(_self->ob_itself,
+ iType,
+ iResType,
+ iPermanentEncoding,
+ &iFileSpecification,
+ iDataReference,
+ iResourceReference);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNRevert(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNRevert
- PyMac_PRECHECK(TXNRevert);
+ PyMac_PRECHECK(TXNRevert);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNRevert(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNRevert(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNPageSetup(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNPageSetup
- PyMac_PRECHECK(TXNPageSetup);
+ PyMac_PRECHECK(TXNPageSetup);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNPageSetup(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNPageSetup(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNPrint(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNPrint
- PyMac_PRECHECK(TXNPrint);
+ PyMac_PRECHECK(TXNPrint);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNPrint(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNPrint(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNGetViewRect(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect oViewRect;
+ PyObject *_res = NULL;
+ Rect oViewRect;
#ifndef TXNGetViewRect
- PyMac_PRECHECK(TXNGetViewRect);
+ PyMac_PRECHECK(TXNGetViewRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNGetViewRect(_self->ob_itself,
- &oViewRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &oViewRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNGetViewRect(_self->ob_itself,
+ &oViewRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &oViewRect);
+ return _res;
}
static PyObject *TXNObj_TXNSetViewRect(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect iViewRect;
+ PyObject *_res = NULL;
+ Rect iViewRect;
#ifndef TXNSetViewRect
- PyMac_PRECHECK(TXNSetViewRect);
+ PyMac_PRECHECK(TXNSetViewRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &iViewRect))
- return NULL;
- TXNSetViewRect(_self->ob_itself,
- &iViewRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &iViewRect))
+ return NULL;
+ TXNSetViewRect(_self->ob_itself,
+ &iViewRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNAttachObjectToWindow(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- GWorldPtr iWindow;
- Boolean iIsActualWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ GWorldPtr iWindow;
+ Boolean iIsActualWindow;
#ifndef TXNAttachObjectToWindow
- PyMac_PRECHECK(TXNAttachObjectToWindow);
+ PyMac_PRECHECK(TXNAttachObjectToWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- GWorldObj_Convert, &iWindow,
- &iIsActualWindow))
- return NULL;
- _err = TXNAttachObjectToWindow(_self->ob_itself,
- iWindow,
- iIsActualWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ GWorldObj_Convert, &iWindow,
+ &iIsActualWindow))
+ return NULL;
+ _err = TXNAttachObjectToWindow(_self->ob_itself,
+ iWindow,
+ iIsActualWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNIsObjectAttachedToWindow(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef TXNIsObjectAttachedToWindow
- PyMac_PRECHECK(TXNIsObjectAttachedToWindow);
+ PyMac_PRECHECK(TXNIsObjectAttachedToWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNIsObjectAttachedToWindow(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNIsObjectAttachedToWindow(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *TXNObj_TXNDragTracker(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TXNFrameID iTXNFrameID;
- DragTrackingMessage iMessage;
- WindowPtr iWindow;
- DragReference iDragReference;
- Boolean iDifferentObjectSameWindow;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TXNFrameID iTXNFrameID;
+ DragTrackingMessage iMessage;
+ WindowPtr iWindow;
+ DragReference iDragReference;
+ Boolean iDifferentObjectSameWindow;
#ifndef TXNDragTracker
- PyMac_PRECHECK(TXNDragTracker);
+ PyMac_PRECHECK(TXNDragTracker);
#endif
- if (!PyArg_ParseTuple(_args, "lhO&O&b",
- &iTXNFrameID,
- &iMessage,
- WinObj_Convert, &iWindow,
- DragObj_Convert, &iDragReference,
- &iDifferentObjectSameWindow))
- return NULL;
- _err = TXNDragTracker(_self->ob_itself,
- iTXNFrameID,
- iMessage,
- iWindow,
- iDragReference,
- iDifferentObjectSameWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lhO&O&b",
+ &iTXNFrameID,
+ &iMessage,
+ WinObj_Convert, &iWindow,
+ DragObj_Convert, &iDragReference,
+ &iDifferentObjectSameWindow))
+ return NULL;
+ _err = TXNDragTracker(_self->ob_itself,
+ iTXNFrameID,
+ iMessage,
+ iWindow,
+ iDragReference,
+ iDifferentObjectSameWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNDragReceiver(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TXNFrameID iTXNFrameID;
- WindowPtr iWindow;
- DragReference iDragReference;
- Boolean iDifferentObjectSameWindow;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TXNFrameID iTXNFrameID;
+ WindowPtr iWindow;
+ DragReference iDragReference;
+ Boolean iDifferentObjectSameWindow;
#ifndef TXNDragReceiver
- PyMac_PRECHECK(TXNDragReceiver);
+ PyMac_PRECHECK(TXNDragReceiver);
#endif
- if (!PyArg_ParseTuple(_args, "lO&O&b",
- &iTXNFrameID,
- WinObj_Convert, &iWindow,
- DragObj_Convert, &iDragReference,
- &iDifferentObjectSameWindow))
- return NULL;
- _err = TXNDragReceiver(_self->ob_itself,
- iTXNFrameID,
- iWindow,
- iDragReference,
- iDifferentObjectSameWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&O&b",
+ &iTXNFrameID,
+ WinObj_Convert, &iWindow,
+ DragObj_Convert, &iDragReference,
+ &iDifferentObjectSameWindow))
+ return NULL;
+ _err = TXNDragReceiver(_self->ob_itself,
+ iTXNFrameID,
+ iWindow,
+ iDragReference,
+ iDifferentObjectSameWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNActivate(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNFrameID iTXNFrameID;
- TXNScrollBarState iActiveState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNFrameID iTXNFrameID;
+ TXNScrollBarState iActiveState;
#ifndef TXNActivate
- PyMac_PRECHECK(TXNActivate);
+ PyMac_PRECHECK(TXNActivate);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &iTXNFrameID,
- &iActiveState))
- return NULL;
- _err = TXNActivate(_self->ob_itself,
- iTXNFrameID,
- iActiveState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &iTXNFrameID,
+ &iActiveState))
+ return NULL;
+ _err = TXNActivate(_self->ob_itself,
+ iTXNFrameID,
+ iActiveState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNEchoMode(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UniChar iEchoCharacter;
- TextEncoding iEncoding;
- Boolean iOn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UniChar iEchoCharacter;
+ TextEncoding iEncoding;
+ Boolean iOn;
#ifndef TXNEchoMode
- PyMac_PRECHECK(TXNEchoMode);
+ PyMac_PRECHECK(TXNEchoMode);
#endif
- if (!PyArg_ParseTuple(_args, "hlb",
- &iEchoCharacter,
- &iEncoding,
- &iOn))
- return NULL;
- _err = TXNEchoMode(_self->ob_itself,
- iEchoCharacter,
- iEncoding,
- iOn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hlb",
+ &iEchoCharacter,
+ &iEncoding,
+ &iOn))
+ return NULL;
+ _err = TXNEchoMode(_self->ob_itself,
+ iEchoCharacter,
+ iEncoding,
+ iOn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNDoFontMenuSelection(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNFontMenuObject iTXNFontMenuObject;
- SInt16 iMenuID;
- SInt16 iMenuItem;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNFontMenuObject iTXNFontMenuObject;
+ SInt16 iMenuID;
+ SInt16 iMenuItem;
#ifndef TXNDoFontMenuSelection
- PyMac_PRECHECK(TXNDoFontMenuSelection);
+ PyMac_PRECHECK(TXNDoFontMenuSelection);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- TXNFontMenuObj_Convert, &iTXNFontMenuObject,
- &iMenuID,
- &iMenuItem))
- return NULL;
- _err = TXNDoFontMenuSelection(_self->ob_itself,
- iTXNFontMenuObject,
- iMenuID,
- iMenuItem);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ TXNFontMenuObj_Convert, &iTXNFontMenuObject,
+ &iMenuID,
+ &iMenuItem))
+ return NULL;
+ _err = TXNDoFontMenuSelection(_self->ob_itself,
+ iTXNFontMenuObject,
+ iMenuID,
+ iMenuItem);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNPrepareFontMenu(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNFontMenuObject iTXNFontMenuObject;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNFontMenuObject iTXNFontMenuObject;
#ifndef TXNPrepareFontMenu
- PyMac_PRECHECK(TXNPrepareFontMenu);
+ PyMac_PRECHECK(TXNPrepareFontMenu);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- TXNFontMenuObj_Convert, &iTXNFontMenuObject))
- return NULL;
- _err = TXNPrepareFontMenu(_self->ob_itself,
- iTXNFontMenuObject);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ TXNFontMenuObj_Convert, &iTXNFontMenuObject))
+ return NULL;
+ _err = TXNPrepareFontMenu(_self->ob_itself,
+ iTXNFontMenuObject);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TXNObj_TXNPointToOffset(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point iPoint;
- TXNOffset oOffset;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point iPoint;
+ TXNOffset oOffset;
#ifndef TXNPointToOffset
- PyMac_PRECHECK(TXNPointToOffset);
+ PyMac_PRECHECK(TXNPointToOffset);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &iPoint))
- return NULL;
- _err = TXNPointToOffset(_self->ob_itself,
- iPoint,
- &oOffset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- oOffset);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &iPoint))
+ return NULL;
+ _err = TXNPointToOffset(_self->ob_itself,
+ iPoint,
+ &oOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ oOffset);
+ return _res;
}
static PyObject *TXNObj_TXNOffsetToPoint(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- TXNOffset iOffset;
- Point oPoint;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ TXNOffset iOffset;
+ Point oPoint;
#ifndef TXNOffsetToPoint
- PyMac_PRECHECK(TXNOffsetToPoint);
+ PyMac_PRECHECK(TXNOffsetToPoint);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &iOffset))
- return NULL;
- _err = TXNOffsetToPoint(_self->ob_itself,
- iOffset,
- &oPoint);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, oPoint);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &iOffset))
+ return NULL;
+ _err = TXNOffsetToPoint(_self->ob_itself,
+ iOffset,
+ &oPoint);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, oPoint);
+ return _res;
}
static PyObject *TXNObj_TXNGetLineCount(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- ItemCount oLineTotal;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ ItemCount oLineTotal;
#ifndef TXNGetLineCount
- PyMac_PRECHECK(TXNGetLineCount);
+ PyMac_PRECHECK(TXNGetLineCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNGetLineCount(_self->ob_itself,
- &oLineTotal);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- oLineTotal);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNGetLineCount(_self->ob_itself,
+ &oLineTotal);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ oLineTotal);
+ return _res;
}
static PyObject *TXNObj_TXNGetLineMetrics(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 iLineNumber;
- Fixed oLineWidth;
- Fixed oLineHeight;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 iLineNumber;
+ Fixed oLineWidth;
+ Fixed oLineHeight;
#ifndef TXNGetLineMetrics
- PyMac_PRECHECK(TXNGetLineMetrics);
+ PyMac_PRECHECK(TXNGetLineMetrics);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &iLineNumber))
- return NULL;
- _err = TXNGetLineMetrics(_self->ob_itself,
- iLineNumber,
- &oLineWidth,
- &oLineHeight);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildFixed, oLineWidth,
- PyMac_BuildFixed, oLineHeight);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &iLineNumber))
+ return NULL;
+ _err = TXNGetLineMetrics(_self->ob_itself,
+ iLineNumber,
+ &oLineWidth,
+ &oLineHeight);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildFixed, oLineWidth,
+ PyMac_BuildFixed, oLineHeight);
+ return _res;
}
static PyObject *TXNObj_TXNIsObjectAttachedToSpecificWindow(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr iWindow;
- Boolean oAttached;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr iWindow;
+ Boolean oAttached;
#ifndef TXNIsObjectAttachedToSpecificWindow
- PyMac_PRECHECK(TXNIsObjectAttachedToSpecificWindow);
+ PyMac_PRECHECK(TXNIsObjectAttachedToSpecificWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &iWindow))
- return NULL;
- _err = TXNIsObjectAttachedToSpecificWindow(_self->ob_itself,
- iWindow,
- &oAttached);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- oAttached);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &iWindow))
+ return NULL;
+ _err = TXNIsObjectAttachedToSpecificWindow(_self->ob_itself,
+ iWindow,
+ &oAttached);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ oAttached);
+ return _res;
}
static PyObject *TXNObj_TXNRecalcTextLayout(TXNObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNRecalcTextLayout
- PyMac_PRECHECK(TXNRecalcTextLayout);
+ PyMac_PRECHECK(TXNRecalcTextLayout);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNRecalcTextLayout(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNRecalcTextLayout(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef TXNObj_methods[] = {
- {"TXNDeleteObject", (PyCFunction)TXNObj_TXNDeleteObject, 1,
- PyDoc_STR("() -> None")},
- {"TXNResizeFrame", (PyCFunction)TXNObj_TXNResizeFrame, 1,
- PyDoc_STR("(UInt32 iWidth, UInt32 iHeight, TXNFrameID iTXNFrameID) -> None")},
- {"TXNSetFrameBounds", (PyCFunction)TXNObj_TXNSetFrameBounds, 1,
- PyDoc_STR("(SInt32 iTop, SInt32 iLeft, SInt32 iBottom, SInt32 iRight, TXNFrameID iTXNFrameID) -> None")},
- {"TXNKeyDown", (PyCFunction)TXNObj_TXNKeyDown, 1,
- PyDoc_STR("(EventRecord iEvent) -> None")},
- {"TXNAdjustCursor", (PyCFunction)TXNObj_TXNAdjustCursor, 1,
- PyDoc_STR("(RgnHandle ioCursorRgn) -> None")},
- {"TXNClick", (PyCFunction)TXNObj_TXNClick, 1,
- PyDoc_STR("(EventRecord iEvent) -> None")},
- {"TXNSelectAll", (PyCFunction)TXNObj_TXNSelectAll, 1,
- PyDoc_STR("() -> None")},
- {"TXNFocus", (PyCFunction)TXNObj_TXNFocus, 1,
- PyDoc_STR("(Boolean iBecomingFocused) -> None")},
- {"TXNUpdate", (PyCFunction)TXNObj_TXNUpdate, 1,
- PyDoc_STR("() -> None")},
- {"TXNDraw", (PyCFunction)TXNObj_TXNDraw, 1,
- PyDoc_STR("(GWorldPtr iDrawPort) -> None")},
- {"TXNForceUpdate", (PyCFunction)TXNObj_TXNForceUpdate, 1,
- PyDoc_STR("() -> None")},
- {"TXNGetSleepTicks", (PyCFunction)TXNObj_TXNGetSleepTicks, 1,
- PyDoc_STR("() -> (UInt32 _rv)")},
- {"TXNIdle", (PyCFunction)TXNObj_TXNIdle, 1,
- PyDoc_STR("() -> None")},
- {"TXNGrowWindow", (PyCFunction)TXNObj_TXNGrowWindow, 1,
- PyDoc_STR("(EventRecord iEvent) -> None")},
- {"TXNZoomWindow", (PyCFunction)TXNObj_TXNZoomWindow, 1,
- PyDoc_STR("(SInt16 iPart) -> None")},
- {"TXNCanUndo", (PyCFunction)TXNObj_TXNCanUndo, 1,
- PyDoc_STR("() -> (Boolean _rv, TXNActionKey oTXNActionKey)")},
- {"TXNUndo", (PyCFunction)TXNObj_TXNUndo, 1,
- PyDoc_STR("() -> None")},
- {"TXNCanRedo", (PyCFunction)TXNObj_TXNCanRedo, 1,
- PyDoc_STR("() -> (Boolean _rv, TXNActionKey oTXNActionKey)")},
- {"TXNRedo", (PyCFunction)TXNObj_TXNRedo, 1,
- PyDoc_STR("() -> None")},
- {"TXNCut", (PyCFunction)TXNObj_TXNCut, 1,
- PyDoc_STR("() -> None")},
- {"TXNCopy", (PyCFunction)TXNObj_TXNCopy, 1,
- PyDoc_STR("() -> None")},
- {"TXNPaste", (PyCFunction)TXNObj_TXNPaste, 1,
- PyDoc_STR("() -> None")},
- {"TXNClear", (PyCFunction)TXNObj_TXNClear, 1,
- PyDoc_STR("() -> None")},
- {"TXNGetSelection", (PyCFunction)TXNObj_TXNGetSelection, 1,
- PyDoc_STR("() -> (TXNOffset oStartOffset, TXNOffset oEndOffset)")},
- {"TXNShowSelection", (PyCFunction)TXNObj_TXNShowSelection, 1,
- PyDoc_STR("(Boolean iShowEnd) -> None")},
- {"TXNIsSelectionEmpty", (PyCFunction)TXNObj_TXNIsSelectionEmpty, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"TXNSetSelection", (PyCFunction)TXNObj_TXNSetSelection, 1,
- PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset) -> None")},
- {"TXNCountRunsInRange", (PyCFunction)TXNObj_TXNCountRunsInRange, 1,
- PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset) -> (ItemCount oRunCount)")},
- {"TXNDataSize", (PyCFunction)TXNObj_TXNDataSize, 1,
- PyDoc_STR("() -> (ByteCount _rv)")},
- {"TXNGetData", (PyCFunction)TXNObj_TXNGetData, 1,
- PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset) -> (Handle oDataHandle)")},
- {"TXNGetDataEncoded", (PyCFunction)TXNObj_TXNGetDataEncoded, 1,
- PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset, TXNDataType iEncoding) -> (Handle oDataHandle)")},
- {"TXNSetDataFromFile", (PyCFunction)TXNObj_TXNSetDataFromFile, 1,
- PyDoc_STR("(SInt16 iFileRefNum, OSType iFileType, ByteCount iFileLength, TXNOffset iStartOffset, TXNOffset iEndOffset) -> None")},
- {"TXNGetChangeCount", (PyCFunction)TXNObj_TXNGetChangeCount, 1,
- PyDoc_STR("() -> (ItemCount _rv)")},
- {"TXNSave", (PyCFunction)TXNObj_TXNSave, 1,
- PyDoc_STR("(TXNFileType iType, OSType iResType, TXNPermanentTextEncodingType iPermanentEncoding, FSSpec iFileSpecification, SInt16 iDataReference, SInt16 iResourceReference) -> None")},
- {"TXNRevert", (PyCFunction)TXNObj_TXNRevert, 1,
- PyDoc_STR("() -> None")},
- {"TXNPageSetup", (PyCFunction)TXNObj_TXNPageSetup, 1,
- PyDoc_STR("() -> None")},
- {"TXNPrint", (PyCFunction)TXNObj_TXNPrint, 1,
- PyDoc_STR("() -> None")},
- {"TXNGetViewRect", (PyCFunction)TXNObj_TXNGetViewRect, 1,
- PyDoc_STR("() -> (Rect oViewRect)")},
- {"TXNSetViewRect", (PyCFunction)TXNObj_TXNSetViewRect, 1,
- PyDoc_STR("(Rect iViewRect) -> None")},
- {"TXNAttachObjectToWindow", (PyCFunction)TXNObj_TXNAttachObjectToWindow, 1,
- PyDoc_STR("(GWorldPtr iWindow, Boolean iIsActualWindow) -> None")},
- {"TXNIsObjectAttachedToWindow", (PyCFunction)TXNObj_TXNIsObjectAttachedToWindow, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"TXNDragTracker", (PyCFunction)TXNObj_TXNDragTracker, 1,
- PyDoc_STR("(TXNFrameID iTXNFrameID, DragTrackingMessage iMessage, WindowPtr iWindow, DragReference iDragReference, Boolean iDifferentObjectSameWindow) -> None")},
- {"TXNDragReceiver", (PyCFunction)TXNObj_TXNDragReceiver, 1,
- PyDoc_STR("(TXNFrameID iTXNFrameID, WindowPtr iWindow, DragReference iDragReference, Boolean iDifferentObjectSameWindow) -> None")},
- {"TXNActivate", (PyCFunction)TXNObj_TXNActivate, 1,
- PyDoc_STR("(TXNFrameID iTXNFrameID, TXNScrollBarState iActiveState) -> None")},
- {"TXNEchoMode", (PyCFunction)TXNObj_TXNEchoMode, 1,
- PyDoc_STR("(UniChar iEchoCharacter, TextEncoding iEncoding, Boolean iOn) -> None")},
- {"TXNDoFontMenuSelection", (PyCFunction)TXNObj_TXNDoFontMenuSelection, 1,
- PyDoc_STR("(TXNFontMenuObject iTXNFontMenuObject, SInt16 iMenuID, SInt16 iMenuItem) -> None")},
- {"TXNPrepareFontMenu", (PyCFunction)TXNObj_TXNPrepareFontMenu, 1,
- PyDoc_STR("(TXNFontMenuObject iTXNFontMenuObject) -> None")},
- {"TXNPointToOffset", (PyCFunction)TXNObj_TXNPointToOffset, 1,
- PyDoc_STR("(Point iPoint) -> (TXNOffset oOffset)")},
- {"TXNOffsetToPoint", (PyCFunction)TXNObj_TXNOffsetToPoint, 1,
- PyDoc_STR("(TXNOffset iOffset) -> (Point oPoint)")},
- {"TXNGetLineCount", (PyCFunction)TXNObj_TXNGetLineCount, 1,
- PyDoc_STR("() -> (ItemCount oLineTotal)")},
- {"TXNGetLineMetrics", (PyCFunction)TXNObj_TXNGetLineMetrics, 1,
- PyDoc_STR("(UInt32 iLineNumber) -> (Fixed oLineWidth, Fixed oLineHeight)")},
- {"TXNIsObjectAttachedToSpecificWindow", (PyCFunction)TXNObj_TXNIsObjectAttachedToSpecificWindow, 1,
- PyDoc_STR("(WindowPtr iWindow) -> (Boolean oAttached)")},
- {"TXNRecalcTextLayout", (PyCFunction)TXNObj_TXNRecalcTextLayout, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"TXNDeleteObject", (PyCFunction)TXNObj_TXNDeleteObject, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNResizeFrame", (PyCFunction)TXNObj_TXNResizeFrame, 1,
+ PyDoc_STR("(UInt32 iWidth, UInt32 iHeight, TXNFrameID iTXNFrameID) -> None")},
+ {"TXNSetFrameBounds", (PyCFunction)TXNObj_TXNSetFrameBounds, 1,
+ PyDoc_STR("(SInt32 iTop, SInt32 iLeft, SInt32 iBottom, SInt32 iRight, TXNFrameID iTXNFrameID) -> None")},
+ {"TXNKeyDown", (PyCFunction)TXNObj_TXNKeyDown, 1,
+ PyDoc_STR("(EventRecord iEvent) -> None")},
+ {"TXNAdjustCursor", (PyCFunction)TXNObj_TXNAdjustCursor, 1,
+ PyDoc_STR("(RgnHandle ioCursorRgn) -> None")},
+ {"TXNClick", (PyCFunction)TXNObj_TXNClick, 1,
+ PyDoc_STR("(EventRecord iEvent) -> None")},
+ {"TXNSelectAll", (PyCFunction)TXNObj_TXNSelectAll, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNFocus", (PyCFunction)TXNObj_TXNFocus, 1,
+ PyDoc_STR("(Boolean iBecomingFocused) -> None")},
+ {"TXNUpdate", (PyCFunction)TXNObj_TXNUpdate, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNDraw", (PyCFunction)TXNObj_TXNDraw, 1,
+ PyDoc_STR("(GWorldPtr iDrawPort) -> None")},
+ {"TXNForceUpdate", (PyCFunction)TXNObj_TXNForceUpdate, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNGetSleepTicks", (PyCFunction)TXNObj_TXNGetSleepTicks, 1,
+ PyDoc_STR("() -> (UInt32 _rv)")},
+ {"TXNIdle", (PyCFunction)TXNObj_TXNIdle, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNGrowWindow", (PyCFunction)TXNObj_TXNGrowWindow, 1,
+ PyDoc_STR("(EventRecord iEvent) -> None")},
+ {"TXNZoomWindow", (PyCFunction)TXNObj_TXNZoomWindow, 1,
+ PyDoc_STR("(SInt16 iPart) -> None")},
+ {"TXNCanUndo", (PyCFunction)TXNObj_TXNCanUndo, 1,
+ PyDoc_STR("() -> (Boolean _rv, TXNActionKey oTXNActionKey)")},
+ {"TXNUndo", (PyCFunction)TXNObj_TXNUndo, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNCanRedo", (PyCFunction)TXNObj_TXNCanRedo, 1,
+ PyDoc_STR("() -> (Boolean _rv, TXNActionKey oTXNActionKey)")},
+ {"TXNRedo", (PyCFunction)TXNObj_TXNRedo, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNCut", (PyCFunction)TXNObj_TXNCut, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNCopy", (PyCFunction)TXNObj_TXNCopy, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNPaste", (PyCFunction)TXNObj_TXNPaste, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNClear", (PyCFunction)TXNObj_TXNClear, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNGetSelection", (PyCFunction)TXNObj_TXNGetSelection, 1,
+ PyDoc_STR("() -> (TXNOffset oStartOffset, TXNOffset oEndOffset)")},
+ {"TXNShowSelection", (PyCFunction)TXNObj_TXNShowSelection, 1,
+ PyDoc_STR("(Boolean iShowEnd) -> None")},
+ {"TXNIsSelectionEmpty", (PyCFunction)TXNObj_TXNIsSelectionEmpty, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"TXNSetSelection", (PyCFunction)TXNObj_TXNSetSelection, 1,
+ PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset) -> None")},
+ {"TXNCountRunsInRange", (PyCFunction)TXNObj_TXNCountRunsInRange, 1,
+ PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset) -> (ItemCount oRunCount)")},
+ {"TXNDataSize", (PyCFunction)TXNObj_TXNDataSize, 1,
+ PyDoc_STR("() -> (ByteCount _rv)")},
+ {"TXNGetData", (PyCFunction)TXNObj_TXNGetData, 1,
+ PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset) -> (Handle oDataHandle)")},
+ {"TXNGetDataEncoded", (PyCFunction)TXNObj_TXNGetDataEncoded, 1,
+ PyDoc_STR("(TXNOffset iStartOffset, TXNOffset iEndOffset, TXNDataType iEncoding) -> (Handle oDataHandle)")},
+ {"TXNSetDataFromFile", (PyCFunction)TXNObj_TXNSetDataFromFile, 1,
+ PyDoc_STR("(SInt16 iFileRefNum, OSType iFileType, ByteCount iFileLength, TXNOffset iStartOffset, TXNOffset iEndOffset) -> None")},
+ {"TXNGetChangeCount", (PyCFunction)TXNObj_TXNGetChangeCount, 1,
+ PyDoc_STR("() -> (ItemCount _rv)")},
+ {"TXNSave", (PyCFunction)TXNObj_TXNSave, 1,
+ PyDoc_STR("(TXNFileType iType, OSType iResType, TXNPermanentTextEncodingType iPermanentEncoding, FSSpec iFileSpecification, SInt16 iDataReference, SInt16 iResourceReference) -> None")},
+ {"TXNRevert", (PyCFunction)TXNObj_TXNRevert, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNPageSetup", (PyCFunction)TXNObj_TXNPageSetup, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNPrint", (PyCFunction)TXNObj_TXNPrint, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNGetViewRect", (PyCFunction)TXNObj_TXNGetViewRect, 1,
+ PyDoc_STR("() -> (Rect oViewRect)")},
+ {"TXNSetViewRect", (PyCFunction)TXNObj_TXNSetViewRect, 1,
+ PyDoc_STR("(Rect iViewRect) -> None")},
+ {"TXNAttachObjectToWindow", (PyCFunction)TXNObj_TXNAttachObjectToWindow, 1,
+ PyDoc_STR("(GWorldPtr iWindow, Boolean iIsActualWindow) -> None")},
+ {"TXNIsObjectAttachedToWindow", (PyCFunction)TXNObj_TXNIsObjectAttachedToWindow, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"TXNDragTracker", (PyCFunction)TXNObj_TXNDragTracker, 1,
+ PyDoc_STR("(TXNFrameID iTXNFrameID, DragTrackingMessage iMessage, WindowPtr iWindow, DragReference iDragReference, Boolean iDifferentObjectSameWindow) -> None")},
+ {"TXNDragReceiver", (PyCFunction)TXNObj_TXNDragReceiver, 1,
+ PyDoc_STR("(TXNFrameID iTXNFrameID, WindowPtr iWindow, DragReference iDragReference, Boolean iDifferentObjectSameWindow) -> None")},
+ {"TXNActivate", (PyCFunction)TXNObj_TXNActivate, 1,
+ PyDoc_STR("(TXNFrameID iTXNFrameID, TXNScrollBarState iActiveState) -> None")},
+ {"TXNEchoMode", (PyCFunction)TXNObj_TXNEchoMode, 1,
+ PyDoc_STR("(UniChar iEchoCharacter, TextEncoding iEncoding, Boolean iOn) -> None")},
+ {"TXNDoFontMenuSelection", (PyCFunction)TXNObj_TXNDoFontMenuSelection, 1,
+ PyDoc_STR("(TXNFontMenuObject iTXNFontMenuObject, SInt16 iMenuID, SInt16 iMenuItem) -> None")},
+ {"TXNPrepareFontMenu", (PyCFunction)TXNObj_TXNPrepareFontMenu, 1,
+ PyDoc_STR("(TXNFontMenuObject iTXNFontMenuObject) -> None")},
+ {"TXNPointToOffset", (PyCFunction)TXNObj_TXNPointToOffset, 1,
+ PyDoc_STR("(Point iPoint) -> (TXNOffset oOffset)")},
+ {"TXNOffsetToPoint", (PyCFunction)TXNObj_TXNOffsetToPoint, 1,
+ PyDoc_STR("(TXNOffset iOffset) -> (Point oPoint)")},
+ {"TXNGetLineCount", (PyCFunction)TXNObj_TXNGetLineCount, 1,
+ PyDoc_STR("() -> (ItemCount oLineTotal)")},
+ {"TXNGetLineMetrics", (PyCFunction)TXNObj_TXNGetLineMetrics, 1,
+ PyDoc_STR("(UInt32 iLineNumber) -> (Fixed oLineWidth, Fixed oLineHeight)")},
+ {"TXNIsObjectAttachedToSpecificWindow", (PyCFunction)TXNObj_TXNIsObjectAttachedToSpecificWindow, 1,
+ PyDoc_STR("(WindowPtr iWindow) -> (Boolean oAttached)")},
+ {"TXNRecalcTextLayout", (PyCFunction)TXNObj_TXNRecalcTextLayout, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define TXNObj_getsetlist NULL
@@ -1242,61 +1242,61 @@ static PyMethodDef TXNObj_methods[] = {
static PyObject *TXNObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- TXNObject itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ TXNObject itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TXNObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((TXNObjectObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TXNObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((TXNObjectObject *)_self)->ob_itself = itself;
+ return _self;
}
#define TXNObj_tp_free PyObject_Del
PyTypeObject TXNObject_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Mlte.TXNObject", /*tp_name*/
- sizeof(TXNObjectObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) TXNObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) TXNObj_compare, /*tp_compare*/
- (reprfunc) TXNObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) TXNObj_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*/
- TXNObj_methods, /* tp_methods */
- 0, /*tp_members*/
- TXNObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- TXNObj_tp_init, /* tp_init */
- TXNObj_tp_alloc, /* tp_alloc */
- TXNObj_tp_new, /* tp_new */
- TXNObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Mlte.TXNObject", /*tp_name*/
+ sizeof(TXNObjectObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) TXNObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) TXNObj_compare, /*tp_compare*/
+ (reprfunc) TXNObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) TXNObj_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*/
+ TXNObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ TXNObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ TXNObj_tp_init, /* tp_init */
+ TXNObj_tp_alloc, /* tp_alloc */
+ TXNObj_tp_new, /* tp_new */
+ TXNObj_tp_free, /* tp_free */
};
/* ------------------- End object type TXNObject -------------------- */
@@ -1309,77 +1309,77 @@ PyTypeObject TXNFontMenuObject_Type;
#define TXNFontMenuObj_Check(x) ((x)->ob_type == &TXNFontMenuObject_Type || PyObject_TypeCheck((x), &TXNFontMenuObject_Type))
typedef struct TXNFontMenuObjectObject {
- PyObject_HEAD
- TXNFontMenuObject ob_itself;
+ PyObject_HEAD
+ TXNFontMenuObject ob_itself;
} TXNFontMenuObjectObject;
PyObject *TXNFontMenuObj_New(TXNFontMenuObject itself)
{
- TXNFontMenuObjectObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(TXNFontMenuObjectObject, &TXNFontMenuObject_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ TXNFontMenuObjectObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(TXNFontMenuObjectObject, &TXNFontMenuObject_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int TXNFontMenuObj_Convert(PyObject *v, TXNFontMenuObject *p_itself)
{
- if (!TXNFontMenuObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "TXNFontMenuObject required");
- return 0;
- }
- *p_itself = ((TXNFontMenuObjectObject *)v)->ob_itself;
- return 1;
+ if (!TXNFontMenuObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "TXNFontMenuObject required");
+ return 0;
+ }
+ *p_itself = ((TXNFontMenuObjectObject *)v)->ob_itself;
+ return 1;
}
static void TXNFontMenuObj_dealloc(TXNFontMenuObjectObject *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 *TXNFontMenuObj_TXNGetFontMenuHandle(TXNFontMenuObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle oFontMenuHandle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle oFontMenuHandle;
#ifndef TXNGetFontMenuHandle
- PyMac_PRECHECK(TXNGetFontMenuHandle);
+ PyMac_PRECHECK(TXNGetFontMenuHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNGetFontMenuHandle(_self->ob_itself,
- &oFontMenuHandle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- MenuObj_New, oFontMenuHandle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNGetFontMenuHandle(_self->ob_itself,
+ &oFontMenuHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, oFontMenuHandle);
+ return _res;
}
static PyObject *TXNFontMenuObj_TXNDisposeFontMenuObject(TXNFontMenuObjectObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNDisposeFontMenuObject
- PyMac_PRECHECK(TXNDisposeFontMenuObject);
+ PyMac_PRECHECK(TXNDisposeFontMenuObject);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNDisposeFontMenuObject(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNDisposeFontMenuObject(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef TXNFontMenuObj_methods[] = {
- {"TXNGetFontMenuHandle", (PyCFunction)TXNFontMenuObj_TXNGetFontMenuHandle, 1,
- PyDoc_STR("() -> (MenuHandle oFontMenuHandle)")},
- {"TXNDisposeFontMenuObject", (PyCFunction)TXNFontMenuObj_TXNDisposeFontMenuObject, 1,
- PyDoc_STR("() -> None")},
- {NULL, NULL, 0}
+ {"TXNGetFontMenuHandle", (PyCFunction)TXNFontMenuObj_TXNGetFontMenuHandle, 1,
+ PyDoc_STR("() -> (MenuHandle oFontMenuHandle)")},
+ {"TXNDisposeFontMenuObject", (PyCFunction)TXNFontMenuObj_TXNDisposeFontMenuObject, 1,
+ PyDoc_STR("() -> None")},
+ {NULL, NULL, 0}
};
#define TXNFontMenuObj_getsetlist NULL
@@ -1396,61 +1396,61 @@ static PyMethodDef TXNFontMenuObj_methods[] = {
static PyObject *TXNFontMenuObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- TXNFontMenuObject itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ TXNFontMenuObject itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TXNFontMenuObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((TXNFontMenuObjectObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TXNFontMenuObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((TXNFontMenuObjectObject *)_self)->ob_itself = itself;
+ return _self;
}
#define TXNFontMenuObj_tp_free PyObject_Del
PyTypeObject TXNFontMenuObject_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Mlte.TXNFontMenuObject", /*tp_name*/
- sizeof(TXNFontMenuObjectObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) TXNFontMenuObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) TXNFontMenuObj_compare, /*tp_compare*/
- (reprfunc) TXNFontMenuObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) TXNFontMenuObj_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*/
- TXNFontMenuObj_methods, /* tp_methods */
- 0, /*tp_members*/
- TXNFontMenuObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- TXNFontMenuObj_tp_init, /* tp_init */
- TXNFontMenuObj_tp_alloc, /* tp_alloc */
- TXNFontMenuObj_tp_new, /* tp_new */
- TXNFontMenuObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Mlte.TXNFontMenuObject", /*tp_name*/
+ sizeof(TXNFontMenuObjectObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) TXNFontMenuObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) TXNFontMenuObj_compare, /*tp_compare*/
+ (reprfunc) TXNFontMenuObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) TXNFontMenuObj_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*/
+ TXNFontMenuObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ TXNFontMenuObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ TXNFontMenuObj_tp_init, /* tp_init */
+ TXNFontMenuObj_tp_alloc, /* tp_alloc */
+ TXNFontMenuObj_tp_new, /* tp_new */
+ TXNFontMenuObj_tp_free, /* tp_free */
};
/* --------------- End object type TXNFontMenuObject ---------------- */
@@ -1458,168 +1458,168 @@ PyTypeObject TXNFontMenuObject_Type = {
static PyObject *Mlte_TXNNewObject(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- FSSpec * iFileSpec;
- WindowPtr iWindow;
- Rect iFrame;
- TXNFrameOptions iFrameOptions;
- TXNFrameType iFrameType;
- TXNFileType iFileType;
- TXNPermanentTextEncodingType iPermanentEncoding;
- TXNObject oTXNObject;
- TXNFrameID oTXNFrameID;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ FSSpec * iFileSpec;
+ WindowPtr iWindow;
+ Rect iFrame;
+ TXNFrameOptions iFrameOptions;
+ TXNFrameType iFrameType;
+ TXNFileType iFileType;
+ TXNPermanentTextEncodingType iPermanentEncoding;
+ TXNObject oTXNObject;
+ TXNFrameID oTXNFrameID;
#ifndef TXNNewObject
- PyMac_PRECHECK(TXNNewObject);
+ PyMac_PRECHECK(TXNNewObject);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&llO&l",
- OptFSSpecPtr_Convert, &iFileSpec,
- WinObj_Convert, &iWindow,
- PyMac_GetRect, &iFrame,
- &iFrameOptions,
- &iFrameType,
- PyMac_GetOSType, &iFileType,
- &iPermanentEncoding))
- return NULL;
- _err = TXNNewObject(iFileSpec,
- iWindow,
- &iFrame,
- iFrameOptions,
- iFrameType,
- iFileType,
- iPermanentEncoding,
- &oTXNObject,
- &oTXNFrameID,
- (TXNObjectRefcon)0);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&l",
- TXNObj_New, oTXNObject,
- oTXNFrameID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&llO&l",
+ OptFSSpecPtr_Convert, &iFileSpec,
+ WinObj_Convert, &iWindow,
+ PyMac_GetRect, &iFrame,
+ &iFrameOptions,
+ &iFrameType,
+ PyMac_GetOSType, &iFileType,
+ &iPermanentEncoding))
+ return NULL;
+ _err = TXNNewObject(iFileSpec,
+ iWindow,
+ &iFrame,
+ iFrameOptions,
+ iFrameType,
+ iFileType,
+ iPermanentEncoding,
+ &oTXNObject,
+ &oTXNFrameID,
+ (TXNObjectRefcon)0);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&l",
+ TXNObj_New, oTXNObject,
+ oTXNFrameID);
+ return _res;
}
static PyObject *Mlte_TXNTerminateTextension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TXNTerminateTextension
- PyMac_PRECHECK(TXNTerminateTextension);
+ PyMac_PRECHECK(TXNTerminateTextension);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TXNTerminateTextension();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TXNTerminateTextension();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Mlte_TXNIsScrapPastable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef TXNIsScrapPastable
- PyMac_PRECHECK(TXNIsScrapPastable);
+ PyMac_PRECHECK(TXNIsScrapPastable);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNIsScrapPastable();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNIsScrapPastable();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Mlte_TXNConvertToPublicScrap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNConvertToPublicScrap
- PyMac_PRECHECK(TXNConvertToPublicScrap);
+ PyMac_PRECHECK(TXNConvertToPublicScrap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNConvertToPublicScrap();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNConvertToPublicScrap();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Mlte_TXNConvertFromPublicScrap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef TXNConvertFromPublicScrap
- PyMac_PRECHECK(TXNConvertFromPublicScrap);
+ PyMac_PRECHECK(TXNConvertFromPublicScrap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TXNConvertFromPublicScrap();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TXNConvertFromPublicScrap();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Mlte_TXNNewFontMenuObject(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle iFontMenuHandle;
- SInt16 iMenuID;
- SInt16 iStartHierMenuID;
- TXNFontMenuObject oTXNFontMenuObject;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle iFontMenuHandle;
+ SInt16 iMenuID;
+ SInt16 iStartHierMenuID;
+ TXNFontMenuObject oTXNFontMenuObject;
#ifndef TXNNewFontMenuObject
- PyMac_PRECHECK(TXNNewFontMenuObject);
+ PyMac_PRECHECK(TXNNewFontMenuObject);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- MenuObj_Convert, &iFontMenuHandle,
- &iMenuID,
- &iStartHierMenuID))
- return NULL;
- _err = TXNNewFontMenuObject(iFontMenuHandle,
- iMenuID,
- iStartHierMenuID,
- &oTXNFontMenuObject);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- TXNFontMenuObj_New, oTXNFontMenuObject);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ MenuObj_Convert, &iFontMenuHandle,
+ &iMenuID,
+ &iStartHierMenuID))
+ return NULL;
+ _err = TXNNewFontMenuObject(iFontMenuHandle,
+ iMenuID,
+ iStartHierMenuID,
+ &oTXNFontMenuObject);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ TXNFontMenuObj_New, oTXNFontMenuObject);
+ return _res;
}
static PyObject *Mlte_TXNVersionInformation(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TXNVersionValue _rv;
- TXNFeatureBits oFeatureFlags;
+ PyObject *_res = NULL;
+ TXNVersionValue _rv;
+ TXNFeatureBits oFeatureFlags;
#ifndef TXNVersionInformation
- PyMac_PRECHECK(TXNVersionInformation);
+ PyMac_PRECHECK(TXNVersionInformation);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TXNVersionInformation(&oFeatureFlags);
- _res = Py_BuildValue("ll",
- _rv,
- oFeatureFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TXNVersionInformation(&oFeatureFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ oFeatureFlags);
+ return _res;
}
static PyObject *Mlte_TXNInitTextension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- OSStatus _err;
- TXNMacOSPreferredFontDescription * iDefaultFonts = NULL;
- ItemCount iCountDefaultFonts = 0;
- TXNInitOptions iUsageFlags;
- PyMac_PRECHECK(TXNInitTextension);
- if (!PyArg_ParseTuple(_args, "l", &iUsageFlags))
- return NULL;
- _err = TXNInitTextension(iDefaultFonts,
- iCountDefaultFonts,
- iUsageFlags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ OSStatus _err;
+ TXNMacOSPreferredFontDescription * iDefaultFonts = NULL;
+ ItemCount iCountDefaultFonts = 0;
+ TXNInitOptions iUsageFlags;
+ PyMac_PRECHECK(TXNInitTextension);
+ if (!PyArg_ParseTuple(_args, "l", &iUsageFlags))
+ return NULL;
+ _err = TXNInitTextension(iDefaultFonts,
+ iCountDefaultFonts,
+ iUsageFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
@@ -1627,24 +1627,24 @@ static PyObject *Mlte_TXNInitTextension(PyObject *_self, PyObject *_args)
static PyMethodDef Mlte_methods[] = {
#ifndef __LP64__
- {"TXNNewObject", (PyCFunction)Mlte_TXNNewObject, 1,
- PyDoc_STR("(FSSpec * iFileSpec, WindowPtr iWindow, Rect iFrame, TXNFrameOptions iFrameOptions, TXNFrameType iFrameType, TXNFileType iFileType, TXNPermanentTextEncodingType iPermanentEncoding) -> (TXNObject oTXNObject, TXNFrameID oTXNFrameID)")},
- {"TXNTerminateTextension", (PyCFunction)Mlte_TXNTerminateTextension, 1,
- PyDoc_STR("() -> None")},
- {"TXNIsScrapPastable", (PyCFunction)Mlte_TXNIsScrapPastable, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"TXNConvertToPublicScrap", (PyCFunction)Mlte_TXNConvertToPublicScrap, 1,
- PyDoc_STR("() -> None")},
- {"TXNConvertFromPublicScrap", (PyCFunction)Mlte_TXNConvertFromPublicScrap, 1,
- PyDoc_STR("() -> None")},
- {"TXNNewFontMenuObject", (PyCFunction)Mlte_TXNNewFontMenuObject, 1,
- PyDoc_STR("(MenuHandle iFontMenuHandle, SInt16 iMenuID, SInt16 iStartHierMenuID) -> (TXNFontMenuObject oTXNFontMenuObject)")},
- {"TXNVersionInformation", (PyCFunction)Mlte_TXNVersionInformation, 1,
- PyDoc_STR("() -> (TXNVersionValue _rv, TXNFeatureBits oFeatureFlags)")},
- {"TXNInitTextension", (PyCFunction)Mlte_TXNInitTextension, 1,
- PyDoc_STR("(TXNInitOptions) -> None")},
+ {"TXNNewObject", (PyCFunction)Mlte_TXNNewObject, 1,
+ PyDoc_STR("(FSSpec * iFileSpec, WindowPtr iWindow, Rect iFrame, TXNFrameOptions iFrameOptions, TXNFrameType iFrameType, TXNFileType iFileType, TXNPermanentTextEncodingType iPermanentEncoding) -> (TXNObject oTXNObject, TXNFrameID oTXNFrameID)")},
+ {"TXNTerminateTextension", (PyCFunction)Mlte_TXNTerminateTextension, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNIsScrapPastable", (PyCFunction)Mlte_TXNIsScrapPastable, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"TXNConvertToPublicScrap", (PyCFunction)Mlte_TXNConvertToPublicScrap, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNConvertFromPublicScrap", (PyCFunction)Mlte_TXNConvertFromPublicScrap, 1,
+ PyDoc_STR("() -> None")},
+ {"TXNNewFontMenuObject", (PyCFunction)Mlte_TXNNewFontMenuObject, 1,
+ PyDoc_STR("(MenuHandle iFontMenuHandle, SInt16 iMenuID, SInt16 iStartHierMenuID) -> (TXNFontMenuObject oTXNFontMenuObject)")},
+ {"TXNVersionInformation", (PyCFunction)Mlte_TXNVersionInformation, 1,
+ PyDoc_STR("() -> (TXNVersionValue _rv, TXNFeatureBits oFeatureFlags)")},
+ {"TXNInitTextension", (PyCFunction)Mlte_TXNInitTextension, 1,
+ PyDoc_STR("(TXNInitOptions) -> None")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -1652,37 +1652,37 @@ static PyMethodDef Mlte_methods[] = {
void init_Mlte(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- // PyMac_INIT_TOOLBOX_OBJECT_NEW(xxxx);
+ // PyMac_INIT_TOOLBOX_OBJECT_NEW(xxxx);
#endif /* __LP64__ */
- m = Py_InitModule("_Mlte", Mlte_methods);
+ m = Py_InitModule("_Mlte", Mlte_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Mlte_Error = PyMac_GetOSErrException();
- if (Mlte_Error == NULL ||
- PyDict_SetItemString(d, "Error", Mlte_Error) != 0)
- return;
- TXNObject_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&TXNObject_Type) < 0) return;
- Py_INCREF(&TXNObject_Type);
- PyModule_AddObject(m, "TXNObject", (PyObject *)&TXNObject_Type);
- /* Backward-compatible name */
- Py_INCREF(&TXNObject_Type);
- PyModule_AddObject(m, "TXNObjectType", (PyObject *)&TXNObject_Type);
- TXNFontMenuObject_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&TXNFontMenuObject_Type) < 0) return;
- Py_INCREF(&TXNFontMenuObject_Type);
- PyModule_AddObject(m, "TXNFontMenuObject", (PyObject *)&TXNFontMenuObject_Type);
- /* Backward-compatible name */
- Py_INCREF(&TXNFontMenuObject_Type);
- PyModule_AddObject(m, "TXNFontMenuObjectType", (PyObject *)&TXNFontMenuObject_Type);
+ d = PyModule_GetDict(m);
+ Mlte_Error = PyMac_GetOSErrException();
+ if (Mlte_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Mlte_Error) != 0)
+ return;
+ TXNObject_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&TXNObject_Type) < 0) return;
+ Py_INCREF(&TXNObject_Type);
+ PyModule_AddObject(m, "TXNObject", (PyObject *)&TXNObject_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&TXNObject_Type);
+ PyModule_AddObject(m, "TXNObjectType", (PyObject *)&TXNObject_Type);
+ TXNFontMenuObject_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&TXNFontMenuObject_Type) < 0) return;
+ Py_INCREF(&TXNFontMenuObject_Type);
+ PyModule_AddObject(m, "TXNFontMenuObject", (PyObject *)&TXNFontMenuObject_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&TXNFontMenuObject_Type);
+ PyModule_AddObject(m, "TXNFontMenuObjectType", (PyObject *)&TXNFontMenuObject_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/osa/_OSAmodule.c b/Mac/Modules/osa/_OSAmodule.c
index ab30320..10dd0ff 100644
--- a/Mac/Modules/osa/_OSAmodule.c
+++ b/Mac/Modules/osa/_OSAmodule.c
@@ -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)
@@ -37,753 +37,753 @@ PyTypeObject OSAComponentInstance_Type;
#define OSAObj_Check(x) ((x)->ob_type == &OSAComponentInstance_Type || PyObject_TypeCheck((x), &OSAComponentInstance_Type))
typedef struct OSAComponentInstanceObject {
- PyObject_HEAD
- ComponentInstance ob_itself;
+ PyObject_HEAD
+ ComponentInstance ob_itself;
} OSAComponentInstanceObject;
PyObject *OSAObj_New(ComponentInstance itself)
{
- OSAComponentInstanceObject *it;
- if (itself == NULL) {
- PyErr_SetString(OSA_Error,"NULL ComponentInstance");
- return NULL;
- }
- it = PyObject_NEW(OSAComponentInstanceObject, &OSAComponentInstance_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ OSAComponentInstanceObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(OSA_Error,"NULL ComponentInstance");
+ return NULL;
+ }
+ it = PyObject_NEW(OSAComponentInstanceObject, &OSAComponentInstance_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int OSAObj_Convert(PyObject *v, ComponentInstance *p_itself)
{
- if (CmpInstObj_Convert(v, p_itself))
- return 1;
- PyErr_Clear();
-
- if (!OSAObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "OSAComponentInstance required");
- return 0;
- }
- *p_itself = ((OSAComponentInstanceObject *)v)->ob_itself;
- return 1;
+ if (CmpInstObj_Convert(v, p_itself))
+ return 1;
+ PyErr_Clear();
+
+ if (!OSAObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "OSAComponentInstance required");
+ return 0;
+ }
+ *p_itself = ((OSAComponentInstanceObject *)v)->ob_itself;
+ return 1;
}
static void OSAObj_dealloc(OSAComponentInstanceObject *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 *OSAObj_OSALoad(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc scriptData;
- long modeFlags;
- OSAID resultingScriptID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc scriptData;
+ long modeFlags;
+ OSAID resultingScriptID;
#ifndef OSALoad
- PyMac_PRECHECK(OSALoad);
+ PyMac_PRECHECK(OSALoad);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- AEDesc_Convert, &scriptData,
- &modeFlags))
- return NULL;
- _err = OSALoad(_self->ob_itself,
- &scriptData,
- modeFlags,
- &resultingScriptID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingScriptID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ AEDesc_Convert, &scriptData,
+ &modeFlags))
+ return NULL;
+ _err = OSALoad(_self->ob_itself,
+ &scriptData,
+ modeFlags,
+ &resultingScriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingScriptID);
+ return _res;
}
static PyObject *OSAObj_OSAStore(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptID;
- DescType desiredType;
- long modeFlags;
- AEDesc resultingScriptData;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptID;
+ DescType desiredType;
+ long modeFlags;
+ AEDesc resultingScriptData;
#ifndef OSAStore
- PyMac_PRECHECK(OSAStore);
+ PyMac_PRECHECK(OSAStore);
#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &scriptID,
- PyMac_GetOSType, &desiredType,
- &modeFlags))
- return NULL;
- _err = OSAStore(_self->ob_itself,
- scriptID,
- desiredType,
- modeFlags,
- &resultingScriptData);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingScriptData);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &scriptID,
+ PyMac_GetOSType, &desiredType,
+ &modeFlags))
+ return NULL;
+ _err = OSAStore(_self->ob_itself,
+ scriptID,
+ desiredType,
+ modeFlags,
+ &resultingScriptData);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingScriptData);
+ return _res;
}
static PyObject *OSAObj_OSAExecute(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID compiledScriptID;
- OSAID contextID;
- long modeFlags;
- OSAID resultingScriptValueID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID compiledScriptID;
+ OSAID contextID;
+ long modeFlags;
+ OSAID resultingScriptValueID;
#ifndef OSAExecute
- PyMac_PRECHECK(OSAExecute);
+ PyMac_PRECHECK(OSAExecute);
#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &compiledScriptID,
- &contextID,
- &modeFlags))
- return NULL;
- _err = OSAExecute(_self->ob_itself,
- compiledScriptID,
- contextID,
- modeFlags,
- &resultingScriptValueID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingScriptValueID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lll",
+ &compiledScriptID,
+ &contextID,
+ &modeFlags))
+ return NULL;
+ _err = OSAExecute(_self->ob_itself,
+ compiledScriptID,
+ contextID,
+ modeFlags,
+ &resultingScriptValueID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingScriptValueID);
+ return _res;
}
static PyObject *OSAObj_OSADisplay(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptValueID;
- DescType desiredType;
- long modeFlags;
- AEDesc resultingText;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptValueID;
+ DescType desiredType;
+ long modeFlags;
+ AEDesc resultingText;
#ifndef OSADisplay
- PyMac_PRECHECK(OSADisplay);
+ PyMac_PRECHECK(OSADisplay);
#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &scriptValueID,
- PyMac_GetOSType, &desiredType,
- &modeFlags))
- return NULL;
- _err = OSADisplay(_self->ob_itself,
- scriptValueID,
- desiredType,
- modeFlags,
- &resultingText);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingText);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &scriptValueID,
+ PyMac_GetOSType, &desiredType,
+ &modeFlags))
+ return NULL;
+ _err = OSADisplay(_self->ob_itself,
+ scriptValueID,
+ desiredType,
+ modeFlags,
+ &resultingText);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingText);
+ return _res;
}
static PyObject *OSAObj_OSAScriptError(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSType selector;
- DescType desiredType;
- AEDesc resultingErrorDescription;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSType selector;
+ DescType desiredType;
+ AEDesc resultingErrorDescription;
#ifndef OSAScriptError
- PyMac_PRECHECK(OSAScriptError);
+ PyMac_PRECHECK(OSAScriptError);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &selector,
- PyMac_GetOSType, &desiredType))
- return NULL;
- _err = OSAScriptError(_self->ob_itself,
- selector,
- desiredType,
- &resultingErrorDescription);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingErrorDescription);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &selector,
+ PyMac_GetOSType, &desiredType))
+ return NULL;
+ _err = OSAScriptError(_self->ob_itself,
+ selector,
+ desiredType,
+ &resultingErrorDescription);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingErrorDescription);
+ return _res;
}
static PyObject *OSAObj_OSADispose(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptID;
#ifndef OSADispose
- PyMac_PRECHECK(OSADispose);
+ PyMac_PRECHECK(OSADispose);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &scriptID))
- return NULL;
- _err = OSADispose(_self->ob_itself,
- scriptID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &scriptID))
+ return NULL;
+ _err = OSADispose(_self->ob_itself,
+ scriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *OSAObj_OSASetScriptInfo(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptID;
- OSType selector;
- long value;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptID;
+ OSType selector;
+ long value;
#ifndef OSASetScriptInfo
- PyMac_PRECHECK(OSASetScriptInfo);
+ PyMac_PRECHECK(OSASetScriptInfo);
#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &scriptID,
- PyMac_GetOSType, &selector,
- &value))
- return NULL;
- _err = OSASetScriptInfo(_self->ob_itself,
- scriptID,
- selector,
- value);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &scriptID,
+ PyMac_GetOSType, &selector,
+ &value))
+ return NULL;
+ _err = OSASetScriptInfo(_self->ob_itself,
+ scriptID,
+ selector,
+ value);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *OSAObj_OSAGetScriptInfo(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptID;
- OSType selector;
- long result;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptID;
+ OSType selector;
+ long result;
#ifndef OSAGetScriptInfo
- PyMac_PRECHECK(OSAGetScriptInfo);
+ PyMac_PRECHECK(OSAGetScriptInfo);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &scriptID,
- PyMac_GetOSType, &selector))
- return NULL;
- _err = OSAGetScriptInfo(_self->ob_itself,
- scriptID,
- selector,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &scriptID,
+ PyMac_GetOSType, &selector))
+ return NULL;
+ _err = OSAGetScriptInfo(_self->ob_itself,
+ scriptID,
+ selector,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ result);
+ return _res;
}
static PyObject *OSAObj_OSAScriptingComponentName(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc resultingScriptingComponentName;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc resultingScriptingComponentName;
#ifndef OSAScriptingComponentName
- PyMac_PRECHECK(OSAScriptingComponentName);
+ PyMac_PRECHECK(OSAScriptingComponentName);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = OSAScriptingComponentName(_self->ob_itself,
- &resultingScriptingComponentName);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingScriptingComponentName);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = OSAScriptingComponentName(_self->ob_itself,
+ &resultingScriptingComponentName);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingScriptingComponentName);
+ return _res;
}
static PyObject *OSAObj_OSACompile(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc sourceData;
- long modeFlags;
- OSAID previousAndResultingScriptID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc sourceData;
+ long modeFlags;
+ OSAID previousAndResultingScriptID;
#ifndef OSACompile
- PyMac_PRECHECK(OSACompile);
+ PyMac_PRECHECK(OSACompile);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- AEDesc_Convert, &sourceData,
- &modeFlags))
- return NULL;
- _err = OSACompile(_self->ob_itself,
- &sourceData,
- modeFlags,
- &previousAndResultingScriptID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- previousAndResultingScriptID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ AEDesc_Convert, &sourceData,
+ &modeFlags))
+ return NULL;
+ _err = OSACompile(_self->ob_itself,
+ &sourceData,
+ modeFlags,
+ &previousAndResultingScriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ previousAndResultingScriptID);
+ return _res;
}
static PyObject *OSAObj_OSACopyID(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID fromID;
- OSAID toID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID fromID;
+ OSAID toID;
#ifndef OSACopyID
- PyMac_PRECHECK(OSACopyID);
+ PyMac_PRECHECK(OSACopyID);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &fromID))
- return NULL;
- _err = OSACopyID(_self->ob_itself,
- fromID,
- &toID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- toID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &fromID))
+ return NULL;
+ _err = OSACopyID(_self->ob_itself,
+ fromID,
+ &toID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ toID);
+ return _res;
}
static PyObject *OSAObj_OSAGetSource(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptID;
- DescType desiredType;
- AEDesc resultingSourceData;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptID;
+ DescType desiredType;
+ AEDesc resultingSourceData;
#ifndef OSAGetSource
- PyMac_PRECHECK(OSAGetSource);
+ PyMac_PRECHECK(OSAGetSource);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &scriptID,
- PyMac_GetOSType, &desiredType))
- return NULL;
- _err = OSAGetSource(_self->ob_itself,
- scriptID,
- desiredType,
- &resultingSourceData);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingSourceData);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &scriptID,
+ PyMac_GetOSType, &desiredType))
+ return NULL;
+ _err = OSAGetSource(_self->ob_itself,
+ scriptID,
+ desiredType,
+ &resultingSourceData);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingSourceData);
+ return _res;
}
static PyObject *OSAObj_OSACoerceFromDesc(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc scriptData;
- long modeFlags;
- OSAID resultingScriptID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc scriptData;
+ long modeFlags;
+ OSAID resultingScriptID;
#ifndef OSACoerceFromDesc
- PyMac_PRECHECK(OSACoerceFromDesc);
+ PyMac_PRECHECK(OSACoerceFromDesc);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- AEDesc_Convert, &scriptData,
- &modeFlags))
- return NULL;
- _err = OSACoerceFromDesc(_self->ob_itself,
- &scriptData,
- modeFlags,
- &resultingScriptID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingScriptID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ AEDesc_Convert, &scriptData,
+ &modeFlags))
+ return NULL;
+ _err = OSACoerceFromDesc(_self->ob_itself,
+ &scriptData,
+ modeFlags,
+ &resultingScriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingScriptID);
+ return _res;
}
static PyObject *OSAObj_OSACoerceToDesc(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID scriptID;
- DescType desiredType;
- long modeFlags;
- AEDesc result;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID scriptID;
+ DescType desiredType;
+ long modeFlags;
+ AEDesc result;
#ifndef OSACoerceToDesc
- PyMac_PRECHECK(OSACoerceToDesc);
+ PyMac_PRECHECK(OSACoerceToDesc);
#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &scriptID,
- PyMac_GetOSType, &desiredType,
- &modeFlags))
- return NULL;
- _err = OSACoerceToDesc(_self->ob_itself,
- scriptID,
- desiredType,
- modeFlags,
- &result);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &result);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &scriptID,
+ PyMac_GetOSType, &desiredType,
+ &modeFlags))
+ return NULL;
+ _err = OSACoerceToDesc(_self->ob_itself,
+ scriptID,
+ desiredType,
+ modeFlags,
+ &result);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &result);
+ return _res;
}
static PyObject *OSAObj_OSASetDefaultTarget(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEAddressDesc target;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEAddressDesc target;
#ifndef OSASetDefaultTarget
- PyMac_PRECHECK(OSASetDefaultTarget);
+ PyMac_PRECHECK(OSASetDefaultTarget);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- AEDesc_Convert, &target))
- return NULL;
- _err = OSASetDefaultTarget(_self->ob_itself,
- &target);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ AEDesc_Convert, &target))
+ return NULL;
+ _err = OSASetDefaultTarget(_self->ob_itself,
+ &target);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *OSAObj_OSAStartRecording(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID compiledScriptToModifyID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID compiledScriptToModifyID;
#ifndef OSAStartRecording
- PyMac_PRECHECK(OSAStartRecording);
+ PyMac_PRECHECK(OSAStartRecording);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = OSAStartRecording(_self->ob_itself,
- &compiledScriptToModifyID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- compiledScriptToModifyID);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = OSAStartRecording(_self->ob_itself,
+ &compiledScriptToModifyID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ compiledScriptToModifyID);
+ return _res;
}
static PyObject *OSAObj_OSAStopRecording(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- OSAID compiledScriptID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ OSAID compiledScriptID;
#ifndef OSAStopRecording
- PyMac_PRECHECK(OSAStopRecording);
+ PyMac_PRECHECK(OSAStopRecording);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &compiledScriptID))
- return NULL;
- _err = OSAStopRecording(_self->ob_itself,
- compiledScriptID);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &compiledScriptID))
+ return NULL;
+ _err = OSAStopRecording(_self->ob_itself,
+ compiledScriptID);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *OSAObj_OSALoadExecute(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc scriptData;
- OSAID contextID;
- long modeFlags;
- OSAID resultingScriptValueID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc scriptData;
+ OSAID contextID;
+ long modeFlags;
+ OSAID resultingScriptValueID;
#ifndef OSALoadExecute
- PyMac_PRECHECK(OSALoadExecute);
+ PyMac_PRECHECK(OSALoadExecute);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- AEDesc_Convert, &scriptData,
- &contextID,
- &modeFlags))
- return NULL;
- _err = OSALoadExecute(_self->ob_itself,
- &scriptData,
- contextID,
- modeFlags,
- &resultingScriptValueID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingScriptValueID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ AEDesc_Convert, &scriptData,
+ &contextID,
+ &modeFlags))
+ return NULL;
+ _err = OSALoadExecute(_self->ob_itself,
+ &scriptData,
+ contextID,
+ modeFlags,
+ &resultingScriptValueID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingScriptValueID);
+ return _res;
}
static PyObject *OSAObj_OSACompileExecute(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc sourceData;
- OSAID contextID;
- long modeFlags;
- OSAID resultingScriptValueID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc sourceData;
+ OSAID contextID;
+ long modeFlags;
+ OSAID resultingScriptValueID;
#ifndef OSACompileExecute
- PyMac_PRECHECK(OSACompileExecute);
+ PyMac_PRECHECK(OSACompileExecute);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- AEDesc_Convert, &sourceData,
- &contextID,
- &modeFlags))
- return NULL;
- _err = OSACompileExecute(_self->ob_itself,
- &sourceData,
- contextID,
- modeFlags,
- &resultingScriptValueID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingScriptValueID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ AEDesc_Convert, &sourceData,
+ &contextID,
+ &modeFlags))
+ return NULL;
+ _err = OSACompileExecute(_self->ob_itself,
+ &sourceData,
+ contextID,
+ modeFlags,
+ &resultingScriptValueID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingScriptValueID);
+ return _res;
}
static PyObject *OSAObj_OSADoScript(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc sourceData;
- OSAID contextID;
- DescType desiredType;
- long modeFlags;
- AEDesc resultingText;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc sourceData;
+ OSAID contextID;
+ DescType desiredType;
+ long modeFlags;
+ AEDesc resultingText;
#ifndef OSADoScript
- PyMac_PRECHECK(OSADoScript);
+ PyMac_PRECHECK(OSADoScript);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&l",
- AEDesc_Convert, &sourceData,
- &contextID,
- PyMac_GetOSType, &desiredType,
- &modeFlags))
- return NULL;
- _err = OSADoScript(_self->ob_itself,
- &sourceData,
- contextID,
- desiredType,
- modeFlags,
- &resultingText);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingText);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&l",
+ AEDesc_Convert, &sourceData,
+ &contextID,
+ PyMac_GetOSType, &desiredType,
+ &modeFlags))
+ return NULL;
+ _err = OSADoScript(_self->ob_itself,
+ &sourceData,
+ contextID,
+ desiredType,
+ modeFlags,
+ &resultingText);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingText);
+ return _res;
}
static PyObject *OSAObj_OSASetCurrentDialect(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- short dialectCode;
+ PyObject *_res = NULL;
+ OSAError _err;
+ short dialectCode;
#ifndef OSASetCurrentDialect
- PyMac_PRECHECK(OSASetCurrentDialect);
+ PyMac_PRECHECK(OSASetCurrentDialect);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &dialectCode))
- return NULL;
- _err = OSASetCurrentDialect(_self->ob_itself,
- dialectCode);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &dialectCode))
+ return NULL;
+ _err = OSASetCurrentDialect(_self->ob_itself,
+ dialectCode);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *OSAObj_OSAGetCurrentDialect(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- short resultingDialectCode;
+ PyObject *_res = NULL;
+ OSAError _err;
+ short resultingDialectCode;
#ifndef OSAGetCurrentDialect
- PyMac_PRECHECK(OSAGetCurrentDialect);
+ PyMac_PRECHECK(OSAGetCurrentDialect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = OSAGetCurrentDialect(_self->ob_itself,
- &resultingDialectCode);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- resultingDialectCode);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = OSAGetCurrentDialect(_self->ob_itself,
+ &resultingDialectCode);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ resultingDialectCode);
+ return _res;
}
static PyObject *OSAObj_OSAAvailableDialects(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc resultingDialectInfoList;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc resultingDialectInfoList;
#ifndef OSAAvailableDialects
- PyMac_PRECHECK(OSAAvailableDialects);
+ PyMac_PRECHECK(OSAAvailableDialects);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = OSAAvailableDialects(_self->ob_itself,
- &resultingDialectInfoList);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingDialectInfoList);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = OSAAvailableDialects(_self->ob_itself,
+ &resultingDialectInfoList);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingDialectInfoList);
+ return _res;
}
static PyObject *OSAObj_OSAGetDialectInfo(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- short dialectCode;
- OSType selector;
- AEDesc resultingDialectInfo;
+ PyObject *_res = NULL;
+ OSAError _err;
+ short dialectCode;
+ OSType selector;
+ AEDesc resultingDialectInfo;
#ifndef OSAGetDialectInfo
- PyMac_PRECHECK(OSAGetDialectInfo);
+ PyMac_PRECHECK(OSAGetDialectInfo);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &dialectCode,
- PyMac_GetOSType, &selector))
- return NULL;
- _err = OSAGetDialectInfo(_self->ob_itself,
- dialectCode,
- selector,
- &resultingDialectInfo);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingDialectInfo);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &dialectCode,
+ PyMac_GetOSType, &selector))
+ return NULL;
+ _err = OSAGetDialectInfo(_self->ob_itself,
+ dialectCode,
+ selector,
+ &resultingDialectInfo);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingDialectInfo);
+ return _res;
}
static PyObject *OSAObj_OSAAvailableDialectCodeList(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc resultingDialectCodeList;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc resultingDialectCodeList;
#ifndef OSAAvailableDialectCodeList
- PyMac_PRECHECK(OSAAvailableDialectCodeList);
+ PyMac_PRECHECK(OSAAvailableDialectCodeList);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = OSAAvailableDialectCodeList(_self->ob_itself,
- &resultingDialectCodeList);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &resultingDialectCodeList);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = OSAAvailableDialectCodeList(_self->ob_itself,
+ &resultingDialectCodeList);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &resultingDialectCodeList);
+ return _res;
}
static PyObject *OSAObj_OSAExecuteEvent(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AppleEvent theAppleEvent;
- OSAID contextID;
- long modeFlags;
- OSAID resultingScriptValueID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AppleEvent theAppleEvent;
+ OSAID contextID;
+ long modeFlags;
+ OSAID resultingScriptValueID;
#ifndef OSAExecuteEvent
- PyMac_PRECHECK(OSAExecuteEvent);
+ PyMac_PRECHECK(OSAExecuteEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- AEDesc_Convert, &theAppleEvent,
- &contextID,
- &modeFlags))
- return NULL;
- _err = OSAExecuteEvent(_self->ob_itself,
- &theAppleEvent,
- contextID,
- modeFlags,
- &resultingScriptValueID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingScriptValueID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ AEDesc_Convert, &theAppleEvent,
+ &contextID,
+ &modeFlags))
+ return NULL;
+ _err = OSAExecuteEvent(_self->ob_itself,
+ &theAppleEvent,
+ contextID,
+ modeFlags,
+ &resultingScriptValueID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingScriptValueID);
+ return _res;
}
static PyObject *OSAObj_OSADoEvent(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AppleEvent theAppleEvent;
- OSAID contextID;
- long modeFlags;
- AppleEvent reply;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AppleEvent theAppleEvent;
+ OSAID contextID;
+ long modeFlags;
+ AppleEvent reply;
#ifndef OSADoEvent
- PyMac_PRECHECK(OSADoEvent);
+ PyMac_PRECHECK(OSADoEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- AEDesc_Convert, &theAppleEvent,
- &contextID,
- &modeFlags))
- return NULL;
- _err = OSADoEvent(_self->ob_itself,
- &theAppleEvent,
- contextID,
- modeFlags,
- &reply);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- AEDesc_New, &reply);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ AEDesc_Convert, &theAppleEvent,
+ &contextID,
+ &modeFlags))
+ return NULL;
+ _err = OSADoEvent(_self->ob_itself,
+ &theAppleEvent,
+ contextID,
+ modeFlags,
+ &reply);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ AEDesc_New, &reply);
+ return _res;
}
static PyObject *OSAObj_OSAMakeContext(OSAComponentInstanceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSAError _err;
- AEDesc contextName;
- OSAID parentContext;
- OSAID resultingContextID;
+ PyObject *_res = NULL;
+ OSAError _err;
+ AEDesc contextName;
+ OSAID parentContext;
+ OSAID resultingContextID;
#ifndef OSAMakeContext
- PyMac_PRECHECK(OSAMakeContext);
+ PyMac_PRECHECK(OSAMakeContext);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- AEDesc_Convert, &contextName,
- &parentContext))
- return NULL;
- _err = OSAMakeContext(_self->ob_itself,
- &contextName,
- parentContext,
- &resultingContextID);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- resultingContextID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ AEDesc_Convert, &contextName,
+ &parentContext))
+ return NULL;
+ _err = OSAMakeContext(_self->ob_itself,
+ &contextName,
+ parentContext,
+ &resultingContextID);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ resultingContextID);
+ return _res;
}
static PyMethodDef OSAObj_methods[] = {
- {"OSALoad", (PyCFunction)OSAObj_OSALoad, 1,
- PyDoc_STR("(AEDesc scriptData, long modeFlags) -> (OSAID resultingScriptID)")},
- {"OSAStore", (PyCFunction)OSAObj_OSAStore, 1,
- PyDoc_STR("(OSAID scriptID, DescType desiredType, long modeFlags) -> (AEDesc resultingScriptData)")},
- {"OSAExecute", (PyCFunction)OSAObj_OSAExecute, 1,
- PyDoc_STR("(OSAID compiledScriptID, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
- {"OSADisplay", (PyCFunction)OSAObj_OSADisplay, 1,
- PyDoc_STR("(OSAID scriptValueID, DescType desiredType, long modeFlags) -> (AEDesc resultingText)")},
- {"OSAScriptError", (PyCFunction)OSAObj_OSAScriptError, 1,
- PyDoc_STR("(OSType selector, DescType desiredType) -> (AEDesc resultingErrorDescription)")},
- {"OSADispose", (PyCFunction)OSAObj_OSADispose, 1,
- PyDoc_STR("(OSAID scriptID) -> None")},
- {"OSASetScriptInfo", (PyCFunction)OSAObj_OSASetScriptInfo, 1,
- PyDoc_STR("(OSAID scriptID, OSType selector, long value) -> None")},
- {"OSAGetScriptInfo", (PyCFunction)OSAObj_OSAGetScriptInfo, 1,
- PyDoc_STR("(OSAID scriptID, OSType selector) -> (long result)")},
- {"OSAScriptingComponentName", (PyCFunction)OSAObj_OSAScriptingComponentName, 1,
- PyDoc_STR("() -> (AEDesc resultingScriptingComponentName)")},
- {"OSACompile", (PyCFunction)OSAObj_OSACompile, 1,
- PyDoc_STR("(AEDesc sourceData, long modeFlags) -> (OSAID previousAndResultingScriptID)")},
- {"OSACopyID", (PyCFunction)OSAObj_OSACopyID, 1,
- PyDoc_STR("(OSAID fromID) -> (OSAID toID)")},
- {"OSAGetSource", (PyCFunction)OSAObj_OSAGetSource, 1,
- PyDoc_STR("(OSAID scriptID, DescType desiredType) -> (AEDesc resultingSourceData)")},
- {"OSACoerceFromDesc", (PyCFunction)OSAObj_OSACoerceFromDesc, 1,
- PyDoc_STR("(AEDesc scriptData, long modeFlags) -> (OSAID resultingScriptID)")},
- {"OSACoerceToDesc", (PyCFunction)OSAObj_OSACoerceToDesc, 1,
- PyDoc_STR("(OSAID scriptID, DescType desiredType, long modeFlags) -> (AEDesc result)")},
- {"OSASetDefaultTarget", (PyCFunction)OSAObj_OSASetDefaultTarget, 1,
- PyDoc_STR("(AEAddressDesc target) -> None")},
- {"OSAStartRecording", (PyCFunction)OSAObj_OSAStartRecording, 1,
- PyDoc_STR("() -> (OSAID compiledScriptToModifyID)")},
- {"OSAStopRecording", (PyCFunction)OSAObj_OSAStopRecording, 1,
- PyDoc_STR("(OSAID compiledScriptID) -> None")},
- {"OSALoadExecute", (PyCFunction)OSAObj_OSALoadExecute, 1,
- PyDoc_STR("(AEDesc scriptData, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
- {"OSACompileExecute", (PyCFunction)OSAObj_OSACompileExecute, 1,
- PyDoc_STR("(AEDesc sourceData, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
- {"OSADoScript", (PyCFunction)OSAObj_OSADoScript, 1,
- PyDoc_STR("(AEDesc sourceData, OSAID contextID, DescType desiredType, long modeFlags) -> (AEDesc resultingText)")},
- {"OSASetCurrentDialect", (PyCFunction)OSAObj_OSASetCurrentDialect, 1,
- PyDoc_STR("(short dialectCode) -> None")},
- {"OSAGetCurrentDialect", (PyCFunction)OSAObj_OSAGetCurrentDialect, 1,
- PyDoc_STR("() -> (short resultingDialectCode)")},
- {"OSAAvailableDialects", (PyCFunction)OSAObj_OSAAvailableDialects, 1,
- PyDoc_STR("() -> (AEDesc resultingDialectInfoList)")},
- {"OSAGetDialectInfo", (PyCFunction)OSAObj_OSAGetDialectInfo, 1,
- PyDoc_STR("(short dialectCode, OSType selector) -> (AEDesc resultingDialectInfo)")},
- {"OSAAvailableDialectCodeList", (PyCFunction)OSAObj_OSAAvailableDialectCodeList, 1,
- PyDoc_STR("() -> (AEDesc resultingDialectCodeList)")},
- {"OSAExecuteEvent", (PyCFunction)OSAObj_OSAExecuteEvent, 1,
- PyDoc_STR("(AppleEvent theAppleEvent, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
- {"OSADoEvent", (PyCFunction)OSAObj_OSADoEvent, 1,
- PyDoc_STR("(AppleEvent theAppleEvent, OSAID contextID, long modeFlags) -> (AppleEvent reply)")},
- {"OSAMakeContext", (PyCFunction)OSAObj_OSAMakeContext, 1,
- PyDoc_STR("(AEDesc contextName, OSAID parentContext) -> (OSAID resultingContextID)")},
- {NULL, NULL, 0}
+ {"OSALoad", (PyCFunction)OSAObj_OSALoad, 1,
+ PyDoc_STR("(AEDesc scriptData, long modeFlags) -> (OSAID resultingScriptID)")},
+ {"OSAStore", (PyCFunction)OSAObj_OSAStore, 1,
+ PyDoc_STR("(OSAID scriptID, DescType desiredType, long modeFlags) -> (AEDesc resultingScriptData)")},
+ {"OSAExecute", (PyCFunction)OSAObj_OSAExecute, 1,
+ PyDoc_STR("(OSAID compiledScriptID, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
+ {"OSADisplay", (PyCFunction)OSAObj_OSADisplay, 1,
+ PyDoc_STR("(OSAID scriptValueID, DescType desiredType, long modeFlags) -> (AEDesc resultingText)")},
+ {"OSAScriptError", (PyCFunction)OSAObj_OSAScriptError, 1,
+ PyDoc_STR("(OSType selector, DescType desiredType) -> (AEDesc resultingErrorDescription)")},
+ {"OSADispose", (PyCFunction)OSAObj_OSADispose, 1,
+ PyDoc_STR("(OSAID scriptID) -> None")},
+ {"OSASetScriptInfo", (PyCFunction)OSAObj_OSASetScriptInfo, 1,
+ PyDoc_STR("(OSAID scriptID, OSType selector, long value) -> None")},
+ {"OSAGetScriptInfo", (PyCFunction)OSAObj_OSAGetScriptInfo, 1,
+ PyDoc_STR("(OSAID scriptID, OSType selector) -> (long result)")},
+ {"OSAScriptingComponentName", (PyCFunction)OSAObj_OSAScriptingComponentName, 1,
+ PyDoc_STR("() -> (AEDesc resultingScriptingComponentName)")},
+ {"OSACompile", (PyCFunction)OSAObj_OSACompile, 1,
+ PyDoc_STR("(AEDesc sourceData, long modeFlags) -> (OSAID previousAndResultingScriptID)")},
+ {"OSACopyID", (PyCFunction)OSAObj_OSACopyID, 1,
+ PyDoc_STR("(OSAID fromID) -> (OSAID toID)")},
+ {"OSAGetSource", (PyCFunction)OSAObj_OSAGetSource, 1,
+ PyDoc_STR("(OSAID scriptID, DescType desiredType) -> (AEDesc resultingSourceData)")},
+ {"OSACoerceFromDesc", (PyCFunction)OSAObj_OSACoerceFromDesc, 1,
+ PyDoc_STR("(AEDesc scriptData, long modeFlags) -> (OSAID resultingScriptID)")},
+ {"OSACoerceToDesc", (PyCFunction)OSAObj_OSACoerceToDesc, 1,
+ PyDoc_STR("(OSAID scriptID, DescType desiredType, long modeFlags) -> (AEDesc result)")},
+ {"OSASetDefaultTarget", (PyCFunction)OSAObj_OSASetDefaultTarget, 1,
+ PyDoc_STR("(AEAddressDesc target) -> None")},
+ {"OSAStartRecording", (PyCFunction)OSAObj_OSAStartRecording, 1,
+ PyDoc_STR("() -> (OSAID compiledScriptToModifyID)")},
+ {"OSAStopRecording", (PyCFunction)OSAObj_OSAStopRecording, 1,
+ PyDoc_STR("(OSAID compiledScriptID) -> None")},
+ {"OSALoadExecute", (PyCFunction)OSAObj_OSALoadExecute, 1,
+ PyDoc_STR("(AEDesc scriptData, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
+ {"OSACompileExecute", (PyCFunction)OSAObj_OSACompileExecute, 1,
+ PyDoc_STR("(AEDesc sourceData, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
+ {"OSADoScript", (PyCFunction)OSAObj_OSADoScript, 1,
+ PyDoc_STR("(AEDesc sourceData, OSAID contextID, DescType desiredType, long modeFlags) -> (AEDesc resultingText)")},
+ {"OSASetCurrentDialect", (PyCFunction)OSAObj_OSASetCurrentDialect, 1,
+ PyDoc_STR("(short dialectCode) -> None")},
+ {"OSAGetCurrentDialect", (PyCFunction)OSAObj_OSAGetCurrentDialect, 1,
+ PyDoc_STR("() -> (short resultingDialectCode)")},
+ {"OSAAvailableDialects", (PyCFunction)OSAObj_OSAAvailableDialects, 1,
+ PyDoc_STR("() -> (AEDesc resultingDialectInfoList)")},
+ {"OSAGetDialectInfo", (PyCFunction)OSAObj_OSAGetDialectInfo, 1,
+ PyDoc_STR("(short dialectCode, OSType selector) -> (AEDesc resultingDialectInfo)")},
+ {"OSAAvailableDialectCodeList", (PyCFunction)OSAObj_OSAAvailableDialectCodeList, 1,
+ PyDoc_STR("() -> (AEDesc resultingDialectCodeList)")},
+ {"OSAExecuteEvent", (PyCFunction)OSAObj_OSAExecuteEvent, 1,
+ PyDoc_STR("(AppleEvent theAppleEvent, OSAID contextID, long modeFlags) -> (OSAID resultingScriptValueID)")},
+ {"OSADoEvent", (PyCFunction)OSAObj_OSADoEvent, 1,
+ PyDoc_STR("(AppleEvent theAppleEvent, OSAID contextID, long modeFlags) -> (AppleEvent reply)")},
+ {"OSAMakeContext", (PyCFunction)OSAObj_OSAMakeContext, 1,
+ PyDoc_STR("(AEDesc contextName, OSAID parentContext) -> (OSAID resultingContextID)")},
+ {NULL, NULL, 0}
};
#define OSAObj_getsetlist NULL
@@ -800,68 +800,68 @@ static PyMethodDef OSAObj_methods[] = {
static PyObject *OSAObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- ComponentInstance itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ ComponentInstance itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, OSAObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((OSAComponentInstanceObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, OSAObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((OSAComponentInstanceObject *)_self)->ob_itself = itself;
+ return _self;
}
#define OSAObj_tp_free PyObject_Del
PyTypeObject OSAComponentInstance_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_OSA.OSAComponentInstance", /*tp_name*/
- sizeof(OSAComponentInstanceObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) OSAObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) OSAObj_compare, /*tp_compare*/
- (reprfunc) OSAObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) OSAObj_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*/
- OSAObj_methods, /* tp_methods */
- 0, /*tp_members*/
- OSAObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- OSAObj_tp_init, /* tp_init */
- OSAObj_tp_alloc, /* tp_alloc */
- OSAObj_tp_new, /* tp_new */
- OSAObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_OSA.OSAComponentInstance", /*tp_name*/
+ sizeof(OSAComponentInstanceObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) OSAObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) OSAObj_compare, /*tp_compare*/
+ (reprfunc) OSAObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) OSAObj_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*/
+ OSAObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ OSAObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ OSAObj_tp_init, /* tp_init */
+ OSAObj_tp_alloc, /* tp_alloc */
+ OSAObj_tp_new, /* tp_new */
+ OSAObj_tp_free, /* tp_free */
};
/* -------------- End object type OSAComponentInstance -------------- */
static PyMethodDef OSA_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -869,30 +869,30 @@ static PyMethodDef OSA_methods[] = {
void init_OSA(void)
{
- PyObject *m;
- PyObject *d;
+ PyObject *m;
+ PyObject *d;
- /*
- PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, OSAObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, OSAObj_Convert);
- */
+ /*
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(ComponentInstance, OSAObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(ComponentInstance, OSAObj_Convert);
+ */
- m = Py_InitModule("_OSA", OSA_methods);
- d = PyModule_GetDict(m);
- OSA_Error = PyMac_GetOSErrException();
- if (OSA_Error == NULL ||
- PyDict_SetItemString(d, "Error", OSA_Error) != 0)
- return;
- OSAComponentInstance_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&OSAComponentInstance_Type) < 0) return;
- Py_INCREF(&OSAComponentInstance_Type);
- PyModule_AddObject(m, "OSAComponentInstance", (PyObject *)&OSAComponentInstance_Type);
- /* Backward-compatible name */
- Py_INCREF(&OSAComponentInstance_Type);
- PyModule_AddObject(m, "OSAComponentInstanceType", (PyObject *)&OSAComponentInstance_Type);
+ m = Py_InitModule("_OSA", OSA_methods);
+ d = PyModule_GetDict(m);
+ OSA_Error = PyMac_GetOSErrException();
+ if (OSA_Error == NULL ||
+ PyDict_SetItemString(d, "Error", OSA_Error) != 0)
+ return;
+ OSAComponentInstance_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&OSAComponentInstance_Type) < 0) return;
+ Py_INCREF(&OSAComponentInstance_Type);
+ PyModule_AddObject(m, "OSAComponentInstance", (PyObject *)&OSAComponentInstance_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&OSAComponentInstance_Type);
+ PyModule_AddObject(m, "OSAComponentInstanceType", (PyObject *)&OSAComponentInstance_Type);
}
/* ======================== End module _OSA ========================= */
diff --git a/Mac/Modules/qd/_Qdmodule.c b/Mac/Modules/qd/_Qdmodule.c
index 8c98fa1..c7594b9 100644
--- a/Mac/Modules/qd/_Qdmodule.c
+++ b/Mac/Modules/qd/_Qdmodule.c
@@ -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)
@@ -42,19 +42,19 @@ static PyObject *BMObj_NewCopied(BitMapPtr);
PyObject *QdRGB_New(RGBColorPtr itself)
{
- return Py_BuildValue("lll", (long)itself->red, (long)itself->green, (long)itself->blue);
+ return Py_BuildValue("lll", (long)itself->red, (long)itself->green, (long)itself->blue);
}
int QdRGB_Convert(PyObject *v, RGBColorPtr p_itself)
{
- long red, green, blue;
+ long red, green, blue;
- if( !PyArg_ParseTuple(v, "lll", &red, &green, &blue) )
- return 0;
- p_itself->red = (unsigned short)red;
- p_itself->green = (unsigned short)green;
- p_itself->blue = (unsigned short)blue;
- return 1;
+ if( !PyArg_ParseTuple(v, "lll", &red, &green, &blue) )
+ return 0;
+ p_itself->red = (unsigned short)red;
+ p_itself->green = (unsigned short)green;
+ p_itself->blue = (unsigned short)blue;
+ return 1;
}
/*
@@ -64,8 +64,8 @@ static
PyObject *QdFI_New(FontInfo *itself)
{
- return Py_BuildValue("hhhh", itself->ascent, itself->descent,
- itself->widMax, itself->leading);
+ return Py_BuildValue("hhhh", itself->ascent, itself->descent,
+ itself->widMax, itself->leading);
}
static PyObject *Qd_Error;
@@ -77,1260 +77,1260 @@ PyTypeObject GrafPort_Type;
#define GrafObj_Check(x) ((x)->ob_type == &GrafPort_Type || PyObject_TypeCheck((x), &GrafPort_Type))
typedef struct GrafPortObject {
- PyObject_HEAD
- GrafPtr ob_itself;
+ PyObject_HEAD
+ GrafPtr ob_itself;
} GrafPortObject;
PyObject *GrafObj_New(GrafPtr itself)
{
- GrafPortObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(GrafPortObject, &GrafPort_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ GrafPortObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(GrafPortObject, &GrafPort_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int GrafObj_Convert(PyObject *v, GrafPtr *p_itself)
{
#if 1
- {
- WindowRef win;
- if (WinObj_Convert(v, &win) && v) {
- *p_itself = (GrafPtr)GetWindowPort(win);
- return 1;
- }
- PyErr_Clear();
- }
+ {
+ WindowRef win;
+ if (WinObj_Convert(v, &win) && v) {
+ *p_itself = (GrafPtr)GetWindowPort(win);
+ return 1;
+ }
+ PyErr_Clear();
+ }
#else
- if (DlgObj_Check(v)) {
- DialogRef dlg = (DialogRef)((GrafPortObject *)v)->ob_itself;
- *p_itself = (GrafPtr)GetWindowPort(GetDialogWindow(dlg));
- return 1;
- }
- if (WinObj_Check(v)) {
- WindowRef win = (WindowRef)((GrafPortObject *)v)->ob_itself;
- *p_itself = (GrafPtr)GetWindowPort(win);
- return 1;
- }
-#endif
- if (!GrafObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "GrafPort required");
- return 0;
- }
- *p_itself = ((GrafPortObject *)v)->ob_itself;
- return 1;
+ if (DlgObj_Check(v)) {
+ DialogRef dlg = (DialogRef)((GrafPortObject *)v)->ob_itself;
+ *p_itself = (GrafPtr)GetWindowPort(GetDialogWindow(dlg));
+ return 1;
+ }
+ if (WinObj_Check(v)) {
+ WindowRef win = (WindowRef)((GrafPortObject *)v)->ob_itself;
+ *p_itself = (GrafPtr)GetWindowPort(win);
+ return 1;
+ }
+#endif
+ if (!GrafObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "GrafPort required");
+ return 0;
+ }
+ *p_itself = ((GrafPortObject *)v)->ob_itself;
+ return 1;
}
static void GrafObj_dealloc(GrafPortObject *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 *GrafObj_MacSetPort(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef MacSetPort
- PyMac_PRECHECK(MacSetPort);
+ PyMac_PRECHECK(MacSetPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- MacSetPort(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ MacSetPort(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_QDSwapPort(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- CGrafPtr outOldPort;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ CGrafPtr outOldPort;
#ifndef QDSwapPort
- PyMac_PRECHECK(QDSwapPort);
+ PyMac_PRECHECK(QDSwapPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = QDSwapPort(_self->ob_itself,
- &outOldPort);
- _res = Py_BuildValue("bO&",
- _rv,
- GrafObj_New, outOldPort);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = QDSwapPort(_self->ob_itself,
+ &outOldPort);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ GrafObj_New, outOldPort);
+ return _res;
}
static PyObject *GrafObj_IsValidPort(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsValidPort
- PyMac_PRECHECK(IsValidPort);
+ PyMac_PRECHECK(IsValidPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsValidPort(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsValidPort(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortPixMap(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle _rv;
+ PyObject *_res = NULL;
+ PixMapHandle _rv;
#ifndef GetPortPixMap
- PyMac_PRECHECK(GetPortPixMap);
+ PyMac_PRECHECK(GetPortPixMap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortPixMap(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortPixMap(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortBitMapForCopyBits(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- const BitMap * _rv;
+ PyObject *_res = NULL;
+ const BitMap * _rv;
#ifndef GetPortBitMapForCopyBits
- PyMac_PRECHECK(GetPortBitMapForCopyBits);
+ PyMac_PRECHECK(GetPortBitMapForCopyBits);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortBitMapForCopyBits(_self->ob_itself);
- _res = Py_BuildValue("O&",
- BMObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortBitMapForCopyBits(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ BMObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortBounds(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef GetPortBounds
- PyMac_PRECHECK(GetPortBounds);
+ PyMac_PRECHECK(GetPortBounds);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPortBounds(_self->ob_itself,
- &rect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &rect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPortBounds(_self->ob_itself,
+ &rect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &rect);
+ return _res;
}
static PyObject *GrafObj_GetPortForeColor(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor foreColor;
+ PyObject *_res = NULL;
+ RGBColor foreColor;
#ifndef GetPortForeColor
- PyMac_PRECHECK(GetPortForeColor);
+ PyMac_PRECHECK(GetPortForeColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPortForeColor(_self->ob_itself,
- &foreColor);
- _res = Py_BuildValue("O&",
- QdRGB_New, &foreColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPortForeColor(_self->ob_itself,
+ &foreColor);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &foreColor);
+ return _res;
}
static PyObject *GrafObj_GetPortBackColor(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor backColor;
+ PyObject *_res = NULL;
+ RGBColor backColor;
#ifndef GetPortBackColor
- PyMac_PRECHECK(GetPortBackColor);
+ PyMac_PRECHECK(GetPortBackColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPortBackColor(_self->ob_itself,
- &backColor);
- _res = Py_BuildValue("O&",
- QdRGB_New, &backColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPortBackColor(_self->ob_itself,
+ &backColor);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &backColor);
+ return _res;
}
static PyObject *GrafObj_GetPortOpColor(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor opColor;
+ PyObject *_res = NULL;
+ RGBColor opColor;
#ifndef GetPortOpColor
- PyMac_PRECHECK(GetPortOpColor);
+ PyMac_PRECHECK(GetPortOpColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPortOpColor(_self->ob_itself,
- &opColor);
- _res = Py_BuildValue("O&",
- QdRGB_New, &opColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPortOpColor(_self->ob_itself,
+ &opColor);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &opColor);
+ return _res;
}
static PyObject *GrafObj_GetPortHiliteColor(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor hiliteColor;
+ PyObject *_res = NULL;
+ RGBColor hiliteColor;
#ifndef GetPortHiliteColor
- PyMac_PRECHECK(GetPortHiliteColor);
+ PyMac_PRECHECK(GetPortHiliteColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPortHiliteColor(_self->ob_itself,
- &hiliteColor);
- _res = Py_BuildValue("O&",
- QdRGB_New, &hiliteColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPortHiliteColor(_self->ob_itself,
+ &hiliteColor);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &hiliteColor);
+ return _res;
}
static PyObject *GrafObj_GetPortTextFont(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetPortTextFont
- PyMac_PRECHECK(GetPortTextFont);
+ PyMac_PRECHECK(GetPortTextFont);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortTextFont(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortTextFont(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortTextFace(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Style _rv;
+ PyObject *_res = NULL;
+ Style _rv;
#ifndef GetPortTextFace
- PyMac_PRECHECK(GetPortTextFace);
+ PyMac_PRECHECK(GetPortTextFace);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortTextFace(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortTextFace(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortTextMode(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetPortTextMode
- PyMac_PRECHECK(GetPortTextMode);
+ PyMac_PRECHECK(GetPortTextMode);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortTextMode(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortTextMode(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortTextSize(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetPortTextSize
- PyMac_PRECHECK(GetPortTextSize);
+ PyMac_PRECHECK(GetPortTextSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortTextSize(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortTextSize(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortChExtra(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetPortChExtra
- PyMac_PRECHECK(GetPortChExtra);
+ PyMac_PRECHECK(GetPortChExtra);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortChExtra(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortChExtra(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortFracHPenLocation(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetPortFracHPenLocation
- PyMac_PRECHECK(GetPortFracHPenLocation);
+ PyMac_PRECHECK(GetPortFracHPenLocation);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortFracHPenLocation(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortFracHPenLocation(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortSpExtra(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
+ PyObject *_res = NULL;
+ Fixed _rv;
#ifndef GetPortSpExtra
- PyMac_PRECHECK(GetPortSpExtra);
+ PyMac_PRECHECK(GetPortSpExtra);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortSpExtra(_self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortSpExtra(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortPenVisibility(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetPortPenVisibility
- PyMac_PRECHECK(GetPortPenVisibility);
+ PyMac_PRECHECK(GetPortPenVisibility);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortPenVisibility(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortPenVisibility(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortVisibleRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- RgnHandle visRgn;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ RgnHandle visRgn;
#ifndef GetPortVisibleRegion
- PyMac_PRECHECK(GetPortVisibleRegion);
+ PyMac_PRECHECK(GetPortVisibleRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &visRgn))
- return NULL;
- _rv = GetPortVisibleRegion(_self->ob_itself,
- visRgn);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &visRgn))
+ return NULL;
+ _rv = GetPortVisibleRegion(_self->ob_itself,
+ visRgn);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortClipRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- RgnHandle clipRgn;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ RgnHandle clipRgn;
#ifndef GetPortClipRegion
- PyMac_PRECHECK(GetPortClipRegion);
+ PyMac_PRECHECK(GetPortClipRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &clipRgn))
- return NULL;
- _rv = GetPortClipRegion(_self->ob_itself,
- clipRgn);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &clipRgn))
+ return NULL;
+ _rv = GetPortClipRegion(_self->ob_itself,
+ clipRgn);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortBackPixPat(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle _rv;
- PixPatHandle backPattern;
+ PyObject *_res = NULL;
+ PixPatHandle _rv;
+ PixPatHandle backPattern;
#ifndef GetPortBackPixPat
- PyMac_PRECHECK(GetPortBackPixPat);
+ PyMac_PRECHECK(GetPortBackPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &backPattern))
- return NULL;
- _rv = GetPortBackPixPat(_self->ob_itself,
- backPattern);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &backPattern))
+ return NULL;
+ _rv = GetPortBackPixPat(_self->ob_itself,
+ backPattern);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortPenPixPat(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle _rv;
- PixPatHandle penPattern;
+ PyObject *_res = NULL;
+ PixPatHandle _rv;
+ PixPatHandle penPattern;
#ifndef GetPortPenPixPat
- PyMac_PRECHECK(GetPortPenPixPat);
+ PyMac_PRECHECK(GetPortPenPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &penPattern))
- return NULL;
- _rv = GetPortPenPixPat(_self->ob_itself,
- penPattern);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &penPattern))
+ return NULL;
+ _rv = GetPortPenPixPat(_self->ob_itself,
+ penPattern);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortFillPixPat(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle _rv;
- PixPatHandle fillPattern;
+ PyObject *_res = NULL;
+ PixPatHandle _rv;
+ PixPatHandle fillPattern;
#ifndef GetPortFillPixPat
- PyMac_PRECHECK(GetPortFillPixPat);
+ PyMac_PRECHECK(GetPortFillPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &fillPattern))
- return NULL;
- _rv = GetPortFillPixPat(_self->ob_itself,
- fillPattern);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &fillPattern))
+ return NULL;
+ _rv = GetPortFillPixPat(_self->ob_itself,
+ fillPattern);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortPenSize(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point penSize;
+ PyObject *_res = NULL;
+ Point penSize;
#ifndef GetPortPenSize
- PyMac_PRECHECK(GetPortPenSize);
+ PyMac_PRECHECK(GetPortPenSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &penSize))
- return NULL;
- GetPortPenSize(_self->ob_itself,
- &penSize);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, penSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &penSize))
+ return NULL;
+ GetPortPenSize(_self->ob_itself,
+ &penSize);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, penSize);
+ return _res;
}
static PyObject *GrafObj_GetPortPenMode(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef GetPortPenMode
- PyMac_PRECHECK(GetPortPenMode);
+ PyMac_PRECHECK(GetPortPenMode);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetPortPenMode(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetPortPenMode(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_GetPortPenLocation(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point penLocation;
+ PyObject *_res = NULL;
+ Point penLocation;
#ifndef GetPortPenLocation
- PyMac_PRECHECK(GetPortPenLocation);
+ PyMac_PRECHECK(GetPortPenLocation);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &penLocation))
- return NULL;
- GetPortPenLocation(_self->ob_itself,
- &penLocation);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, penLocation);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &penLocation))
+ return NULL;
+ GetPortPenLocation(_self->ob_itself,
+ &penLocation);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, penLocation);
+ return _res;
}
static PyObject *GrafObj_IsPortRegionBeingDefined(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortRegionBeingDefined
- PyMac_PRECHECK(IsPortRegionBeingDefined);
+ PyMac_PRECHECK(IsPortRegionBeingDefined);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortRegionBeingDefined(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortRegionBeingDefined(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_IsPortPictureBeingDefined(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortPictureBeingDefined
- PyMac_PRECHECK(IsPortPictureBeingDefined);
+ PyMac_PRECHECK(IsPortPictureBeingDefined);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortPictureBeingDefined(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortPictureBeingDefined(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_IsPortPolyBeingDefined(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortPolyBeingDefined
- PyMac_PRECHECK(IsPortPolyBeingDefined);
+ PyMac_PRECHECK(IsPortPolyBeingDefined);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortPolyBeingDefined(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortPolyBeingDefined(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_IsPortOffscreen(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortOffscreen
- PyMac_PRECHECK(IsPortOffscreen);
+ PyMac_PRECHECK(IsPortOffscreen);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortOffscreen(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortOffscreen(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_IsPortColor(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortColor
- PyMac_PRECHECK(IsPortColor);
+ PyMac_PRECHECK(IsPortColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortColor(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortColor(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_IsPortVisibleRegionEmpty(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortVisibleRegionEmpty
- PyMac_PRECHECK(IsPortVisibleRegionEmpty);
+ PyMac_PRECHECK(IsPortVisibleRegionEmpty);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortVisibleRegionEmpty(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortVisibleRegionEmpty(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_IsPortClipRegionEmpty(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsPortClipRegionEmpty
- PyMac_PRECHECK(IsPortClipRegionEmpty);
+ PyMac_PRECHECK(IsPortClipRegionEmpty);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsPortClipRegionEmpty(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsPortClipRegionEmpty(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_SectRegionWithPortClipRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle ioRegion;
+ PyObject *_res = NULL;
+ RgnHandle ioRegion;
#ifndef SectRegionWithPortClipRegion
- PyMac_PRECHECK(SectRegionWithPortClipRegion);
+ PyMac_PRECHECK(SectRegionWithPortClipRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &ioRegion))
- return NULL;
- SectRegionWithPortClipRegion(_self->ob_itself,
- ioRegion);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &ioRegion))
+ return NULL;
+ SectRegionWithPortClipRegion(_self->ob_itself,
+ ioRegion);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SectRegionWithPortVisibleRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle ioRegion;
+ PyObject *_res = NULL;
+ RgnHandle ioRegion;
#ifndef SectRegionWithPortVisibleRegion
- PyMac_PRECHECK(SectRegionWithPortVisibleRegion);
+ PyMac_PRECHECK(SectRegionWithPortVisibleRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &ioRegion))
- return NULL;
- SectRegionWithPortVisibleRegion(_self->ob_itself,
- ioRegion);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &ioRegion))
+ return NULL;
+ SectRegionWithPortVisibleRegion(_self->ob_itself,
+ ioRegion);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SwapPortPicSaveHandle(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- Handle inPicSaveHdl;
+ PyObject *_res = NULL;
+ Handle _rv;
+ Handle inPicSaveHdl;
#ifndef SwapPortPicSaveHandle
- PyMac_PRECHECK(SwapPortPicSaveHandle);
+ PyMac_PRECHECK(SwapPortPicSaveHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inPicSaveHdl))
- return NULL;
- _rv = SwapPortPicSaveHandle(_self->ob_itself,
- inPicSaveHdl);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inPicSaveHdl))
+ return NULL;
+ _rv = SwapPortPicSaveHandle(_self->ob_itself,
+ inPicSaveHdl);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_SwapPortPolySaveHandle(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- Handle inPolySaveHdl;
+ PyObject *_res = NULL;
+ Handle _rv;
+ Handle inPolySaveHdl;
#ifndef SwapPortPolySaveHandle
- PyMac_PRECHECK(SwapPortPolySaveHandle);
+ PyMac_PRECHECK(SwapPortPolySaveHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inPolySaveHdl))
- return NULL;
- _rv = SwapPortPolySaveHandle(_self->ob_itself,
- inPolySaveHdl);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inPolySaveHdl))
+ return NULL;
+ _rv = SwapPortPolySaveHandle(_self->ob_itself,
+ inPolySaveHdl);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_SwapPortRegionSaveHandle(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- Handle inRegionSaveHdl;
+ PyObject *_res = NULL;
+ Handle _rv;
+ Handle inRegionSaveHdl;
#ifndef SwapPortRegionSaveHandle
- PyMac_PRECHECK(SwapPortRegionSaveHandle);
+ PyMac_PRECHECK(SwapPortRegionSaveHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inRegionSaveHdl))
- return NULL;
- _rv = SwapPortRegionSaveHandle(_self->ob_itself,
- inRegionSaveHdl);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inRegionSaveHdl))
+ return NULL;
+ _rv = SwapPortRegionSaveHandle(_self->ob_itself,
+ inRegionSaveHdl);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_SetPortBounds(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef SetPortBounds
- PyMac_PRECHECK(SetPortBounds);
+ PyMac_PRECHECK(SetPortBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &rect))
- return NULL;
- SetPortBounds(_self->ob_itself,
- &rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &rect))
+ return NULL;
+ SetPortBounds(_self->ob_itself,
+ &rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortOpColor(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor opColor;
+ PyObject *_res = NULL;
+ RGBColor opColor;
#ifndef SetPortOpColor
- PyMac_PRECHECK(SetPortOpColor);
+ PyMac_PRECHECK(SetPortOpColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &opColor))
- return NULL;
- SetPortOpColor(_self->ob_itself,
- &opColor);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &opColor))
+ return NULL;
+ SetPortOpColor(_self->ob_itself,
+ &opColor);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortTextFont(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short txFont;
+ PyObject *_res = NULL;
+ short txFont;
#ifndef SetPortTextFont
- PyMac_PRECHECK(SetPortTextFont);
+ PyMac_PRECHECK(SetPortTextFont);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &txFont))
- return NULL;
- SetPortTextFont(_self->ob_itself,
- txFont);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &txFont))
+ return NULL;
+ SetPortTextFont(_self->ob_itself,
+ txFont);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortTextSize(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short txSize;
+ PyObject *_res = NULL;
+ short txSize;
#ifndef SetPortTextSize
- PyMac_PRECHECK(SetPortTextSize);
+ PyMac_PRECHECK(SetPortTextSize);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &txSize))
- return NULL;
- SetPortTextSize(_self->ob_itself,
- txSize);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &txSize))
+ return NULL;
+ SetPortTextSize(_self->ob_itself,
+ txSize);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortTextFace(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- StyleParameter face;
+ PyObject *_res = NULL;
+ StyleParameter face;
#ifndef SetPortTextFace
- PyMac_PRECHECK(SetPortTextFace);
+ PyMac_PRECHECK(SetPortTextFace);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &face))
- return NULL;
- SetPortTextFace(_self->ob_itself,
- face);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &face))
+ return NULL;
+ SetPortTextFace(_self->ob_itself,
+ face);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortTextMode(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short mode;
+ PyObject *_res = NULL;
+ short mode;
#ifndef SetPortTextMode
- PyMac_PRECHECK(SetPortTextMode);
+ PyMac_PRECHECK(SetPortTextMode);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &mode))
- return NULL;
- SetPortTextMode(_self->ob_itself,
- mode);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &mode))
+ return NULL;
+ SetPortTextMode(_self->ob_itself,
+ mode);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortVisibleRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle visRgn;
+ PyObject *_res = NULL;
+ RgnHandle visRgn;
#ifndef SetPortVisibleRegion
- PyMac_PRECHECK(SetPortVisibleRegion);
+ PyMac_PRECHECK(SetPortVisibleRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &visRgn))
- return NULL;
- SetPortVisibleRegion(_self->ob_itself,
- visRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &visRgn))
+ return NULL;
+ SetPortVisibleRegion(_self->ob_itself,
+ visRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortClipRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle clipRgn;
+ PyObject *_res = NULL;
+ RgnHandle clipRgn;
#ifndef SetPortClipRegion
- PyMac_PRECHECK(SetPortClipRegion);
+ PyMac_PRECHECK(SetPortClipRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &clipRgn))
- return NULL;
- SetPortClipRegion(_self->ob_itself,
- clipRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &clipRgn))
+ return NULL;
+ SetPortClipRegion(_self->ob_itself,
+ clipRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortPenPixPat(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle penPattern;
+ PyObject *_res = NULL;
+ PixPatHandle penPattern;
#ifndef SetPortPenPixPat
- PyMac_PRECHECK(SetPortPenPixPat);
+ PyMac_PRECHECK(SetPortPenPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &penPattern))
- return NULL;
- SetPortPenPixPat(_self->ob_itself,
- penPattern);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &penPattern))
+ return NULL;
+ SetPortPenPixPat(_self->ob_itself,
+ penPattern);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortFillPixPat(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle penPattern;
+ PyObject *_res = NULL;
+ PixPatHandle penPattern;
#ifndef SetPortFillPixPat
- PyMac_PRECHECK(SetPortFillPixPat);
+ PyMac_PRECHECK(SetPortFillPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &penPattern))
- return NULL;
- SetPortFillPixPat(_self->ob_itself,
- penPattern);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &penPattern))
+ return NULL;
+ SetPortFillPixPat(_self->ob_itself,
+ penPattern);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortBackPixPat(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle backPattern;
+ PyObject *_res = NULL;
+ PixPatHandle backPattern;
#ifndef SetPortBackPixPat
- PyMac_PRECHECK(SetPortBackPixPat);
+ PyMac_PRECHECK(SetPortBackPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &backPattern))
- return NULL;
- SetPortBackPixPat(_self->ob_itself,
- backPattern);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &backPattern))
+ return NULL;
+ SetPortBackPixPat(_self->ob_itself,
+ backPattern);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortPenSize(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point penSize;
+ PyObject *_res = NULL;
+ Point penSize;
#ifndef SetPortPenSize
- PyMac_PRECHECK(SetPortPenSize);
+ PyMac_PRECHECK(SetPortPenSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &penSize))
- return NULL;
- SetPortPenSize(_self->ob_itself,
- penSize);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &penSize))
+ return NULL;
+ SetPortPenSize(_self->ob_itself,
+ penSize);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortPenMode(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 penMode;
+ PyObject *_res = NULL;
+ SInt32 penMode;
#ifndef SetPortPenMode
- PyMac_PRECHECK(SetPortPenMode);
+ PyMac_PRECHECK(SetPortPenMode);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &penMode))
- return NULL;
- SetPortPenMode(_self->ob_itself,
- penMode);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &penMode))
+ return NULL;
+ SetPortPenMode(_self->ob_itself,
+ penMode);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_SetPortFracHPenLocation(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short pnLocHFrac;
+ PyObject *_res = NULL;
+ short pnLocHFrac;
#ifndef SetPortFracHPenLocation
- PyMac_PRECHECK(SetPortFracHPenLocation);
+ PyMac_PRECHECK(SetPortFracHPenLocation);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &pnLocHFrac))
- return NULL;
- SetPortFracHPenLocation(_self->ob_itself,
- pnLocHFrac);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &pnLocHFrac))
+ return NULL;
+ SetPortFracHPenLocation(_self->ob_itself,
+ pnLocHFrac);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_DisposePort(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DisposePort
- PyMac_PRECHECK(DisposePort);
+ PyMac_PRECHECK(DisposePort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DisposePort(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DisposePort(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_QDLocalToGlobalPoint(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point point;
+ PyObject *_res = NULL;
+ Point point;
#ifndef QDLocalToGlobalPoint
- PyMac_PRECHECK(QDLocalToGlobalPoint);
+ PyMac_PRECHECK(QDLocalToGlobalPoint);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &point))
- return NULL;
- QDLocalToGlobalPoint(_self->ob_itself,
- &point);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, point);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &point))
+ return NULL;
+ QDLocalToGlobalPoint(_self->ob_itself,
+ &point);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, point);
+ return _res;
}
static PyObject *GrafObj_QDGlobalToLocalPoint(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point point;
+ PyObject *_res = NULL;
+ Point point;
#ifndef QDGlobalToLocalPoint
- PyMac_PRECHECK(QDGlobalToLocalPoint);
+ PyMac_PRECHECK(QDGlobalToLocalPoint);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &point))
- return NULL;
- QDGlobalToLocalPoint(_self->ob_itself,
- &point);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, point);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &point))
+ return NULL;
+ QDGlobalToLocalPoint(_self->ob_itself,
+ &point);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, point);
+ return _res;
}
static PyObject *GrafObj_QDLocalToGlobalRect(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect bounds;
+ PyObject *_res = NULL;
+ Rect bounds;
#ifndef QDLocalToGlobalRect
- PyMac_PRECHECK(QDLocalToGlobalRect);
+ PyMac_PRECHECK(QDLocalToGlobalRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- QDLocalToGlobalRect(_self->ob_itself,
- &bounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ QDLocalToGlobalRect(_self->ob_itself,
+ &bounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *GrafObj_QDGlobalToLocalRect(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect bounds;
+ PyObject *_res = NULL;
+ Rect bounds;
#ifndef QDGlobalToLocalRect
- PyMac_PRECHECK(QDGlobalToLocalRect);
+ PyMac_PRECHECK(QDGlobalToLocalRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- QDGlobalToLocalRect(_self->ob_itself,
- &bounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ QDGlobalToLocalRect(_self->ob_itself,
+ &bounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *GrafObj_QDLocalToGlobalRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- RgnHandle region;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ RgnHandle region;
#ifndef QDLocalToGlobalRegion
- PyMac_PRECHECK(QDLocalToGlobalRegion);
+ PyMac_PRECHECK(QDLocalToGlobalRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- _rv = QDLocalToGlobalRegion(_self->ob_itself,
- region);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ _rv = QDLocalToGlobalRegion(_self->ob_itself,
+ region);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_QDGlobalToLocalRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- RgnHandle region;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ RgnHandle region;
#ifndef QDGlobalToLocalRegion
- PyMac_PRECHECK(QDGlobalToLocalRegion);
+ PyMac_PRECHECK(QDGlobalToLocalRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- _rv = QDGlobalToLocalRegion(_self->ob_itself,
- region);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ _rv = QDGlobalToLocalRegion(_self->ob_itself,
+ region);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GrafObj_QDIsPortBuffered(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef QDIsPortBuffered
- PyMac_PRECHECK(QDIsPortBuffered);
+ PyMac_PRECHECK(QDIsPortBuffered);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = QDIsPortBuffered(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = QDIsPortBuffered(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_QDIsPortBufferDirty(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef QDIsPortBufferDirty
- PyMac_PRECHECK(QDIsPortBufferDirty);
+ PyMac_PRECHECK(QDIsPortBufferDirty);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = QDIsPortBufferDirty(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = QDIsPortBufferDirty(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *GrafObj_QDFlushPortBuffer(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle region;
+ PyObject *_res = NULL;
+ RgnHandle region;
#ifndef QDFlushPortBuffer
- PyMac_PRECHECK(QDFlushPortBuffer);
+ PyMac_PRECHECK(QDFlushPortBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- OptResObj_Convert, &region))
- return NULL;
- QDFlushPortBuffer(_self->ob_itself,
- region);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptResObj_Convert, &region))
+ return NULL;
+ QDFlushPortBuffer(_self->ob_itself,
+ region);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_QDGetDirtyRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RgnHandle rgn;
#ifndef QDGetDirtyRegion
- PyMac_PRECHECK(QDGetDirtyRegion);
+ PyMac_PRECHECK(QDGetDirtyRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- _err = QDGetDirtyRegion(_self->ob_itself,
- rgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ _err = QDGetDirtyRegion(_self->ob_itself,
+ rgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *GrafObj_QDSetDirtyRegion(GrafPortObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RgnHandle rgn;
#ifndef QDSetDirtyRegion
- PyMac_PRECHECK(QDSetDirtyRegion);
+ PyMac_PRECHECK(QDSetDirtyRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- _err = QDSetDirtyRegion(_self->ob_itself,
- rgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ _err = QDSetDirtyRegion(_self->ob_itself,
+ rgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef GrafObj_methods[] = {
- {"MacSetPort", (PyCFunction)GrafObj_MacSetPort, 1,
- PyDoc_STR("() -> None")},
- {"QDSwapPort", (PyCFunction)GrafObj_QDSwapPort, 1,
- PyDoc_STR("() -> (Boolean _rv, CGrafPtr outOldPort)")},
- {"IsValidPort", (PyCFunction)GrafObj_IsValidPort, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetPortPixMap", (PyCFunction)GrafObj_GetPortPixMap, 1,
- PyDoc_STR("() -> (PixMapHandle _rv)")},
- {"GetPortBitMapForCopyBits", (PyCFunction)GrafObj_GetPortBitMapForCopyBits, 1,
- PyDoc_STR("() -> (const BitMap * _rv)")},
- {"GetPortBounds", (PyCFunction)GrafObj_GetPortBounds, 1,
- PyDoc_STR("() -> (Rect rect)")},
- {"GetPortForeColor", (PyCFunction)GrafObj_GetPortForeColor, 1,
- PyDoc_STR("() -> (RGBColor foreColor)")},
- {"GetPortBackColor", (PyCFunction)GrafObj_GetPortBackColor, 1,
- PyDoc_STR("() -> (RGBColor backColor)")},
- {"GetPortOpColor", (PyCFunction)GrafObj_GetPortOpColor, 1,
- PyDoc_STR("() -> (RGBColor opColor)")},
- {"GetPortHiliteColor", (PyCFunction)GrafObj_GetPortHiliteColor, 1,
- PyDoc_STR("() -> (RGBColor hiliteColor)")},
- {"GetPortTextFont", (PyCFunction)GrafObj_GetPortTextFont, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetPortTextFace", (PyCFunction)GrafObj_GetPortTextFace, 1,
- PyDoc_STR("() -> (Style _rv)")},
- {"GetPortTextMode", (PyCFunction)GrafObj_GetPortTextMode, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetPortTextSize", (PyCFunction)GrafObj_GetPortTextSize, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetPortChExtra", (PyCFunction)GrafObj_GetPortChExtra, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetPortFracHPenLocation", (PyCFunction)GrafObj_GetPortFracHPenLocation, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetPortSpExtra", (PyCFunction)GrafObj_GetPortSpExtra, 1,
- PyDoc_STR("() -> (Fixed _rv)")},
- {"GetPortPenVisibility", (PyCFunction)GrafObj_GetPortPenVisibility, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetPortVisibleRegion", (PyCFunction)GrafObj_GetPortVisibleRegion, 1,
- PyDoc_STR("(RgnHandle visRgn) -> (RgnHandle _rv)")},
- {"GetPortClipRegion", (PyCFunction)GrafObj_GetPortClipRegion, 1,
- PyDoc_STR("(RgnHandle clipRgn) -> (RgnHandle _rv)")},
- {"GetPortBackPixPat", (PyCFunction)GrafObj_GetPortBackPixPat, 1,
- PyDoc_STR("(PixPatHandle backPattern) -> (PixPatHandle _rv)")},
- {"GetPortPenPixPat", (PyCFunction)GrafObj_GetPortPenPixPat, 1,
- PyDoc_STR("(PixPatHandle penPattern) -> (PixPatHandle _rv)")},
- {"GetPortFillPixPat", (PyCFunction)GrafObj_GetPortFillPixPat, 1,
- PyDoc_STR("(PixPatHandle fillPattern) -> (PixPatHandle _rv)")},
- {"GetPortPenSize", (PyCFunction)GrafObj_GetPortPenSize, 1,
- PyDoc_STR("(Point penSize) -> (Point penSize)")},
- {"GetPortPenMode", (PyCFunction)GrafObj_GetPortPenMode, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"GetPortPenLocation", (PyCFunction)GrafObj_GetPortPenLocation, 1,
- PyDoc_STR("(Point penLocation) -> (Point penLocation)")},
- {"IsPortRegionBeingDefined", (PyCFunction)GrafObj_IsPortRegionBeingDefined, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsPortPictureBeingDefined", (PyCFunction)GrafObj_IsPortPictureBeingDefined, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsPortPolyBeingDefined", (PyCFunction)GrafObj_IsPortPolyBeingDefined, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsPortOffscreen", (PyCFunction)GrafObj_IsPortOffscreen, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsPortColor", (PyCFunction)GrafObj_IsPortColor, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsPortVisibleRegionEmpty", (PyCFunction)GrafObj_IsPortVisibleRegionEmpty, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsPortClipRegionEmpty", (PyCFunction)GrafObj_IsPortClipRegionEmpty, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SectRegionWithPortClipRegion", (PyCFunction)GrafObj_SectRegionWithPortClipRegion, 1,
- PyDoc_STR("(RgnHandle ioRegion) -> None")},
- {"SectRegionWithPortVisibleRegion", (PyCFunction)GrafObj_SectRegionWithPortVisibleRegion, 1,
- PyDoc_STR("(RgnHandle ioRegion) -> None")},
- {"SwapPortPicSaveHandle", (PyCFunction)GrafObj_SwapPortPicSaveHandle, 1,
- PyDoc_STR("(Handle inPicSaveHdl) -> (Handle _rv)")},
- {"SwapPortPolySaveHandle", (PyCFunction)GrafObj_SwapPortPolySaveHandle, 1,
- PyDoc_STR("(Handle inPolySaveHdl) -> (Handle _rv)")},
- {"SwapPortRegionSaveHandle", (PyCFunction)GrafObj_SwapPortRegionSaveHandle, 1,
- PyDoc_STR("(Handle inRegionSaveHdl) -> (Handle _rv)")},
- {"SetPortBounds", (PyCFunction)GrafObj_SetPortBounds, 1,
- PyDoc_STR("(Rect rect) -> None")},
- {"SetPortOpColor", (PyCFunction)GrafObj_SetPortOpColor, 1,
- PyDoc_STR("(RGBColor opColor) -> None")},
- {"SetPortTextFont", (PyCFunction)GrafObj_SetPortTextFont, 1,
- PyDoc_STR("(short txFont) -> None")},
- {"SetPortTextSize", (PyCFunction)GrafObj_SetPortTextSize, 1,
- PyDoc_STR("(short txSize) -> None")},
- {"SetPortTextFace", (PyCFunction)GrafObj_SetPortTextFace, 1,
- PyDoc_STR("(StyleParameter face) -> None")},
- {"SetPortTextMode", (PyCFunction)GrafObj_SetPortTextMode, 1,
- PyDoc_STR("(short mode) -> None")},
- {"SetPortVisibleRegion", (PyCFunction)GrafObj_SetPortVisibleRegion, 1,
- PyDoc_STR("(RgnHandle visRgn) -> None")},
- {"SetPortClipRegion", (PyCFunction)GrafObj_SetPortClipRegion, 1,
- PyDoc_STR("(RgnHandle clipRgn) -> None")},
- {"SetPortPenPixPat", (PyCFunction)GrafObj_SetPortPenPixPat, 1,
- PyDoc_STR("(PixPatHandle penPattern) -> None")},
- {"SetPortFillPixPat", (PyCFunction)GrafObj_SetPortFillPixPat, 1,
- PyDoc_STR("(PixPatHandle penPattern) -> None")},
- {"SetPortBackPixPat", (PyCFunction)GrafObj_SetPortBackPixPat, 1,
- PyDoc_STR("(PixPatHandle backPattern) -> None")},
- {"SetPortPenSize", (PyCFunction)GrafObj_SetPortPenSize, 1,
- PyDoc_STR("(Point penSize) -> None")},
- {"SetPortPenMode", (PyCFunction)GrafObj_SetPortPenMode, 1,
- PyDoc_STR("(SInt32 penMode) -> None")},
- {"SetPortFracHPenLocation", (PyCFunction)GrafObj_SetPortFracHPenLocation, 1,
- PyDoc_STR("(short pnLocHFrac) -> None")},
- {"DisposePort", (PyCFunction)GrafObj_DisposePort, 1,
- PyDoc_STR("() -> None")},
- {"QDLocalToGlobalPoint", (PyCFunction)GrafObj_QDLocalToGlobalPoint, 1,
- PyDoc_STR("(Point point) -> (Point point)")},
- {"QDGlobalToLocalPoint", (PyCFunction)GrafObj_QDGlobalToLocalPoint, 1,
- PyDoc_STR("(Point point) -> (Point point)")},
- {"QDLocalToGlobalRect", (PyCFunction)GrafObj_QDLocalToGlobalRect, 1,
- PyDoc_STR("() -> (Rect bounds)")},
- {"QDGlobalToLocalRect", (PyCFunction)GrafObj_QDGlobalToLocalRect, 1,
- PyDoc_STR("() -> (Rect bounds)")},
- {"QDLocalToGlobalRegion", (PyCFunction)GrafObj_QDLocalToGlobalRegion, 1,
- PyDoc_STR("(RgnHandle region) -> (RgnHandle _rv)")},
- {"QDGlobalToLocalRegion", (PyCFunction)GrafObj_QDGlobalToLocalRegion, 1,
- PyDoc_STR("(RgnHandle region) -> (RgnHandle _rv)")},
- {"QDIsPortBuffered", (PyCFunction)GrafObj_QDIsPortBuffered, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"QDIsPortBufferDirty", (PyCFunction)GrafObj_QDIsPortBufferDirty, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"QDFlushPortBuffer", (PyCFunction)GrafObj_QDFlushPortBuffer, 1,
- PyDoc_STR("(RgnHandle region) -> None")},
- {"QDGetDirtyRegion", (PyCFunction)GrafObj_QDGetDirtyRegion, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"QDSetDirtyRegion", (PyCFunction)GrafObj_QDSetDirtyRegion, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {NULL, NULL, 0}
+ {"MacSetPort", (PyCFunction)GrafObj_MacSetPort, 1,
+ PyDoc_STR("() -> None")},
+ {"QDSwapPort", (PyCFunction)GrafObj_QDSwapPort, 1,
+ PyDoc_STR("() -> (Boolean _rv, CGrafPtr outOldPort)")},
+ {"IsValidPort", (PyCFunction)GrafObj_IsValidPort, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetPortPixMap", (PyCFunction)GrafObj_GetPortPixMap, 1,
+ PyDoc_STR("() -> (PixMapHandle _rv)")},
+ {"GetPortBitMapForCopyBits", (PyCFunction)GrafObj_GetPortBitMapForCopyBits, 1,
+ PyDoc_STR("() -> (const BitMap * _rv)")},
+ {"GetPortBounds", (PyCFunction)GrafObj_GetPortBounds, 1,
+ PyDoc_STR("() -> (Rect rect)")},
+ {"GetPortForeColor", (PyCFunction)GrafObj_GetPortForeColor, 1,
+ PyDoc_STR("() -> (RGBColor foreColor)")},
+ {"GetPortBackColor", (PyCFunction)GrafObj_GetPortBackColor, 1,
+ PyDoc_STR("() -> (RGBColor backColor)")},
+ {"GetPortOpColor", (PyCFunction)GrafObj_GetPortOpColor, 1,
+ PyDoc_STR("() -> (RGBColor opColor)")},
+ {"GetPortHiliteColor", (PyCFunction)GrafObj_GetPortHiliteColor, 1,
+ PyDoc_STR("() -> (RGBColor hiliteColor)")},
+ {"GetPortTextFont", (PyCFunction)GrafObj_GetPortTextFont, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetPortTextFace", (PyCFunction)GrafObj_GetPortTextFace, 1,
+ PyDoc_STR("() -> (Style _rv)")},
+ {"GetPortTextMode", (PyCFunction)GrafObj_GetPortTextMode, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetPortTextSize", (PyCFunction)GrafObj_GetPortTextSize, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetPortChExtra", (PyCFunction)GrafObj_GetPortChExtra, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetPortFracHPenLocation", (PyCFunction)GrafObj_GetPortFracHPenLocation, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetPortSpExtra", (PyCFunction)GrafObj_GetPortSpExtra, 1,
+ PyDoc_STR("() -> (Fixed _rv)")},
+ {"GetPortPenVisibility", (PyCFunction)GrafObj_GetPortPenVisibility, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetPortVisibleRegion", (PyCFunction)GrafObj_GetPortVisibleRegion, 1,
+ PyDoc_STR("(RgnHandle visRgn) -> (RgnHandle _rv)")},
+ {"GetPortClipRegion", (PyCFunction)GrafObj_GetPortClipRegion, 1,
+ PyDoc_STR("(RgnHandle clipRgn) -> (RgnHandle _rv)")},
+ {"GetPortBackPixPat", (PyCFunction)GrafObj_GetPortBackPixPat, 1,
+ PyDoc_STR("(PixPatHandle backPattern) -> (PixPatHandle _rv)")},
+ {"GetPortPenPixPat", (PyCFunction)GrafObj_GetPortPenPixPat, 1,
+ PyDoc_STR("(PixPatHandle penPattern) -> (PixPatHandle _rv)")},
+ {"GetPortFillPixPat", (PyCFunction)GrafObj_GetPortFillPixPat, 1,
+ PyDoc_STR("(PixPatHandle fillPattern) -> (PixPatHandle _rv)")},
+ {"GetPortPenSize", (PyCFunction)GrafObj_GetPortPenSize, 1,
+ PyDoc_STR("(Point penSize) -> (Point penSize)")},
+ {"GetPortPenMode", (PyCFunction)GrafObj_GetPortPenMode, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"GetPortPenLocation", (PyCFunction)GrafObj_GetPortPenLocation, 1,
+ PyDoc_STR("(Point penLocation) -> (Point penLocation)")},
+ {"IsPortRegionBeingDefined", (PyCFunction)GrafObj_IsPortRegionBeingDefined, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsPortPictureBeingDefined", (PyCFunction)GrafObj_IsPortPictureBeingDefined, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsPortPolyBeingDefined", (PyCFunction)GrafObj_IsPortPolyBeingDefined, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsPortOffscreen", (PyCFunction)GrafObj_IsPortOffscreen, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsPortColor", (PyCFunction)GrafObj_IsPortColor, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsPortVisibleRegionEmpty", (PyCFunction)GrafObj_IsPortVisibleRegionEmpty, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsPortClipRegionEmpty", (PyCFunction)GrafObj_IsPortClipRegionEmpty, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SectRegionWithPortClipRegion", (PyCFunction)GrafObj_SectRegionWithPortClipRegion, 1,
+ PyDoc_STR("(RgnHandle ioRegion) -> None")},
+ {"SectRegionWithPortVisibleRegion", (PyCFunction)GrafObj_SectRegionWithPortVisibleRegion, 1,
+ PyDoc_STR("(RgnHandle ioRegion) -> None")},
+ {"SwapPortPicSaveHandle", (PyCFunction)GrafObj_SwapPortPicSaveHandle, 1,
+ PyDoc_STR("(Handle inPicSaveHdl) -> (Handle _rv)")},
+ {"SwapPortPolySaveHandle", (PyCFunction)GrafObj_SwapPortPolySaveHandle, 1,
+ PyDoc_STR("(Handle inPolySaveHdl) -> (Handle _rv)")},
+ {"SwapPortRegionSaveHandle", (PyCFunction)GrafObj_SwapPortRegionSaveHandle, 1,
+ PyDoc_STR("(Handle inRegionSaveHdl) -> (Handle _rv)")},
+ {"SetPortBounds", (PyCFunction)GrafObj_SetPortBounds, 1,
+ PyDoc_STR("(Rect rect) -> None")},
+ {"SetPortOpColor", (PyCFunction)GrafObj_SetPortOpColor, 1,
+ PyDoc_STR("(RGBColor opColor) -> None")},
+ {"SetPortTextFont", (PyCFunction)GrafObj_SetPortTextFont, 1,
+ PyDoc_STR("(short txFont) -> None")},
+ {"SetPortTextSize", (PyCFunction)GrafObj_SetPortTextSize, 1,
+ PyDoc_STR("(short txSize) -> None")},
+ {"SetPortTextFace", (PyCFunction)GrafObj_SetPortTextFace, 1,
+ PyDoc_STR("(StyleParameter face) -> None")},
+ {"SetPortTextMode", (PyCFunction)GrafObj_SetPortTextMode, 1,
+ PyDoc_STR("(short mode) -> None")},
+ {"SetPortVisibleRegion", (PyCFunction)GrafObj_SetPortVisibleRegion, 1,
+ PyDoc_STR("(RgnHandle visRgn) -> None")},
+ {"SetPortClipRegion", (PyCFunction)GrafObj_SetPortClipRegion, 1,
+ PyDoc_STR("(RgnHandle clipRgn) -> None")},
+ {"SetPortPenPixPat", (PyCFunction)GrafObj_SetPortPenPixPat, 1,
+ PyDoc_STR("(PixPatHandle penPattern) -> None")},
+ {"SetPortFillPixPat", (PyCFunction)GrafObj_SetPortFillPixPat, 1,
+ PyDoc_STR("(PixPatHandle penPattern) -> None")},
+ {"SetPortBackPixPat", (PyCFunction)GrafObj_SetPortBackPixPat, 1,
+ PyDoc_STR("(PixPatHandle backPattern) -> None")},
+ {"SetPortPenSize", (PyCFunction)GrafObj_SetPortPenSize, 1,
+ PyDoc_STR("(Point penSize) -> None")},
+ {"SetPortPenMode", (PyCFunction)GrafObj_SetPortPenMode, 1,
+ PyDoc_STR("(SInt32 penMode) -> None")},
+ {"SetPortFracHPenLocation", (PyCFunction)GrafObj_SetPortFracHPenLocation, 1,
+ PyDoc_STR("(short pnLocHFrac) -> None")},
+ {"DisposePort", (PyCFunction)GrafObj_DisposePort, 1,
+ PyDoc_STR("() -> None")},
+ {"QDLocalToGlobalPoint", (PyCFunction)GrafObj_QDLocalToGlobalPoint, 1,
+ PyDoc_STR("(Point point) -> (Point point)")},
+ {"QDGlobalToLocalPoint", (PyCFunction)GrafObj_QDGlobalToLocalPoint, 1,
+ PyDoc_STR("(Point point) -> (Point point)")},
+ {"QDLocalToGlobalRect", (PyCFunction)GrafObj_QDLocalToGlobalRect, 1,
+ PyDoc_STR("() -> (Rect bounds)")},
+ {"QDGlobalToLocalRect", (PyCFunction)GrafObj_QDGlobalToLocalRect, 1,
+ PyDoc_STR("() -> (Rect bounds)")},
+ {"QDLocalToGlobalRegion", (PyCFunction)GrafObj_QDLocalToGlobalRegion, 1,
+ PyDoc_STR("(RgnHandle region) -> (RgnHandle _rv)")},
+ {"QDGlobalToLocalRegion", (PyCFunction)GrafObj_QDGlobalToLocalRegion, 1,
+ PyDoc_STR("(RgnHandle region) -> (RgnHandle _rv)")},
+ {"QDIsPortBuffered", (PyCFunction)GrafObj_QDIsPortBuffered, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"QDIsPortBufferDirty", (PyCFunction)GrafObj_QDIsPortBufferDirty, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"QDFlushPortBuffer", (PyCFunction)GrafObj_QDFlushPortBuffer, 1,
+ PyDoc_STR("(RgnHandle region) -> None")},
+ {"QDGetDirtyRegion", (PyCFunction)GrafObj_QDGetDirtyRegion, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"QDSetDirtyRegion", (PyCFunction)GrafObj_QDSetDirtyRegion, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {NULL, NULL, 0}
};
static PyObject *GrafObj_get_visRgn(GrafPortObject *self, void *closure)
{
- RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */
- return Py_BuildValue("O&", ResObj_New, (Handle)GetPortVisibleRegion(self->ob_itself, h));
-
+ RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */
+ return Py_BuildValue("O&", ResObj_New, (Handle)GetPortVisibleRegion(self->ob_itself, h));
+
}
#define GrafObj_set_visRgn NULL
static PyObject *GrafObj_get_clipRgn(GrafPortObject *self, void *closure)
{
- RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */
- return Py_BuildValue("O&", ResObj_New, (Handle)GetPortClipRegion(self->ob_itself, h));
-
+ RgnHandle h=NewRgn(); /* XXXX wrong dispose routine */
+ return Py_BuildValue("O&", ResObj_New, (Handle)GetPortClipRegion(self->ob_itself, h));
+
}
#define GrafObj_set_clipRgn NULL
static PyGetSetDef GrafObj_getsetlist[] = {
- {"visRgn", (getter)GrafObj_get_visRgn, (setter)GrafObj_set_visRgn, "Convenience attribute: return a copy of the visible region"},
- {"clipRgn", (getter)GrafObj_get_clipRgn, (setter)GrafObj_set_clipRgn, "Convenience attribute: return a copy of the clipping region"},
- {NULL, NULL, NULL, NULL},
+ {"visRgn", (getter)GrafObj_get_visRgn, (setter)GrafObj_set_visRgn, "Convenience attribute: return a copy of the visible region"},
+ {"clipRgn", (getter)GrafObj_get_clipRgn, (setter)GrafObj_set_clipRgn, "Convenience attribute: return a copy of the clipping region"},
+ {NULL, NULL, NULL, NULL},
};
@@ -1345,61 +1345,61 @@ static PyGetSetDef GrafObj_getsetlist[] = {
static PyObject *GrafObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- GrafPtr itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ GrafPtr itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, GrafObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((GrafPortObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, GrafObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((GrafPortObject *)_self)->ob_itself = itself;
+ return _self;
}
#define GrafObj_tp_free PyObject_Del
PyTypeObject GrafPort_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qd.GrafPort", /*tp_name*/
- sizeof(GrafPortObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) GrafObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) GrafObj_compare, /*tp_compare*/
- (reprfunc) GrafObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) GrafObj_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*/
- GrafObj_methods, /* tp_methods */
- 0, /*tp_members*/
- GrafObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- GrafObj_tp_init, /* tp_init */
- GrafObj_tp_alloc, /* tp_alloc */
- GrafObj_tp_new, /* tp_new */
- GrafObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qd.GrafPort", /*tp_name*/
+ sizeof(GrafPortObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) GrafObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) GrafObj_compare, /*tp_compare*/
+ (reprfunc) GrafObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) GrafObj_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*/
+ GrafObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ GrafObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ GrafObj_tp_init, /* tp_init */
+ GrafObj_tp_alloc, /* tp_alloc */
+ GrafObj_tp_new, /* tp_new */
+ GrafObj_tp_free, /* tp_free */
};
/* -------------------- End object type GrafPort -------------------- */
@@ -1412,124 +1412,124 @@ PyTypeObject BitMap_Type;
#define BMObj_Check(x) ((x)->ob_type == &BitMap_Type || PyObject_TypeCheck((x), &BitMap_Type))
typedef struct BitMapObject {
- PyObject_HEAD
- BitMapPtr ob_itself;
- PyObject *referred_object;
- BitMap *referred_bitmap;
+ PyObject_HEAD
+ BitMapPtr ob_itself;
+ PyObject *referred_object;
+ BitMap *referred_bitmap;
} BitMapObject;
PyObject *BMObj_New(BitMapPtr itself)
{
- BitMapObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(BitMapObject, &BitMap_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->referred_object = NULL;
- it->referred_bitmap = NULL;
- return (PyObject *)it;
+ BitMapObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(BitMapObject, &BitMap_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->referred_object = NULL;
+ it->referred_bitmap = NULL;
+ return (PyObject *)it;
}
int BMObj_Convert(PyObject *v, BitMapPtr *p_itself)
{
- if (!BMObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "BitMap required");
- return 0;
- }
- *p_itself = ((BitMapObject *)v)->ob_itself;
- return 1;
+ if (!BMObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "BitMap required");
+ return 0;
+ }
+ *p_itself = ((BitMapObject *)v)->ob_itself;
+ return 1;
}
static void BMObj_dealloc(BitMapObject *self)
{
- Py_XDECREF(self->referred_object);
- if (self->referred_bitmap) free(self->referred_bitmap);
- self->ob_type->tp_free((PyObject *)self);
+ Py_XDECREF(self->referred_object);
+ if (self->referred_bitmap) free(self->referred_bitmap);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *BMObj_getdata(BitMapObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int from, length;
- char *cp;
+ int from, length;
+ char *cp;
- if ( !PyArg_ParseTuple(_args, "ii", &from, &length) )
- return NULL;
- cp = _self->ob_itself->baseAddr+from;
- _res = PyString_FromStringAndSize(cp, length);
- return _res;
+ if ( !PyArg_ParseTuple(_args, "ii", &from, &length) )
+ return NULL;
+ cp = _self->ob_itself->baseAddr+from;
+ _res = PyString_FromStringAndSize(cp, length);
+ return _res;
}
static PyObject *BMObj_putdata(BitMapObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int from, length;
- char *cp, *icp;
+ int from, length;
+ char *cp, *icp;
- if ( !PyArg_ParseTuple(_args, "is#", &from, &icp, &length) )
- return NULL;
- cp = _self->ob_itself->baseAddr+from;
- memcpy(cp, icp, length);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if ( !PyArg_ParseTuple(_args, "is#", &from, &icp, &length) )
+ return NULL;
+ cp = _self->ob_itself->baseAddr+from;
+ memcpy(cp, icp, length);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef BMObj_methods[] = {
- {"getdata", (PyCFunction)BMObj_getdata, 1,
- PyDoc_STR("(int start, int size) -> string. Return bytes from the bitmap")},
- {"putdata", (PyCFunction)BMObj_putdata, 1,
- PyDoc_STR("(int start, string data). Store bytes into the bitmap")},
- {NULL, NULL, 0}
+ {"getdata", (PyCFunction)BMObj_getdata, 1,
+ PyDoc_STR("(int start, int size) -> string. Return bytes from the bitmap")},
+ {"putdata", (PyCFunction)BMObj_putdata, 1,
+ PyDoc_STR("(int start, string data). Store bytes into the bitmap")},
+ {NULL, NULL, 0}
};
static PyObject *BMObj_get_baseAddr(BitMapObject *self, void *closure)
{
- return PyInt_FromLong((long)self->ob_itself->baseAddr);
+ return PyInt_FromLong((long)self->ob_itself->baseAddr);
}
#define BMObj_set_baseAddr NULL
static PyObject *BMObj_get_rowBytes(BitMapObject *self, void *closure)
{
- return PyInt_FromLong((long)self->ob_itself->rowBytes);
+ return PyInt_FromLong((long)self->ob_itself->rowBytes);
}
#define BMObj_set_rowBytes NULL
static PyObject *BMObj_get_bounds(BitMapObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildRect, &self->ob_itself->bounds);
+ return Py_BuildValue("O&", PyMac_BuildRect, &self->ob_itself->bounds);
}
#define BMObj_set_bounds NULL
static PyObject *BMObj_get_bitmap_data(BitMapObject *self, void *closure)
{
- return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(BitMap));
+ return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(BitMap));
}
#define BMObj_set_bitmap_data NULL
static PyObject *BMObj_get_pixmap_data(BitMapObject *self, void *closure)
{
- return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(PixMap));
+ return PyString_FromStringAndSize((char *)self->ob_itself, sizeof(PixMap));
}
#define BMObj_set_pixmap_data NULL
static PyGetSetDef BMObj_getsetlist[] = {
- {"baseAddr", (getter)BMObj_get_baseAddr, (setter)BMObj_set_baseAddr, NULL},
- {"rowBytes", (getter)BMObj_get_rowBytes, (setter)BMObj_set_rowBytes, NULL},
- {"bounds", (getter)BMObj_get_bounds, (setter)BMObj_set_bounds, NULL},
- {"bitmap_data", (getter)BMObj_get_bitmap_data, (setter)BMObj_set_bitmap_data, NULL},
- {"pixmap_data", (getter)BMObj_get_pixmap_data, (setter)BMObj_set_pixmap_data, NULL},
- {NULL, NULL, NULL, NULL},
+ {"baseAddr", (getter)BMObj_get_baseAddr, (setter)BMObj_set_baseAddr, NULL},
+ {"rowBytes", (getter)BMObj_get_rowBytes, (setter)BMObj_set_rowBytes, NULL},
+ {"bounds", (getter)BMObj_get_bounds, (setter)BMObj_set_bounds, NULL},
+ {"bitmap_data", (getter)BMObj_get_bitmap_data, (setter)BMObj_set_bitmap_data, NULL},
+ {"pixmap_data", (getter)BMObj_get_pixmap_data, (setter)BMObj_set_pixmap_data, NULL},
+ {NULL, NULL, NULL, NULL},
};
@@ -1544,61 +1544,61 @@ static PyGetSetDef BMObj_getsetlist[] = {
static PyObject *BMObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- BitMapPtr itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ BitMapPtr itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, BMObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((BitMapObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, BMObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((BitMapObject *)_self)->ob_itself = itself;
+ return _self;
}
#define BMObj_tp_free PyObject_Del
PyTypeObject BitMap_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qd.BitMap", /*tp_name*/
- sizeof(BitMapObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) BMObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) BMObj_compare, /*tp_compare*/
- (reprfunc) BMObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) BMObj_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*/
- BMObj_methods, /* tp_methods */
- 0, /*tp_members*/
- BMObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- BMObj_tp_init, /* tp_init */
- BMObj_tp_alloc, /* tp_alloc */
- BMObj_tp_new, /* tp_new */
- BMObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qd.BitMap", /*tp_name*/
+ sizeof(BitMapObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) BMObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) BMObj_compare, /*tp_compare*/
+ (reprfunc) BMObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) BMObj_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*/
+ BMObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ BMObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ BMObj_tp_init, /* tp_init */
+ BMObj_tp_alloc, /* tp_alloc */
+ BMObj_tp_new, /* tp_new */
+ BMObj_tp_free, /* tp_free */
};
/* --------------------- End object type BitMap --------------------- */
@@ -1606,5485 +1606,5485 @@ PyTypeObject BitMap_Type = {
static PyObject *Qd_GetPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GrafPtr port;
+ PyObject *_res = NULL;
+ GrafPtr port;
#ifndef GetPort
- PyMac_PRECHECK(GetPort);
+ PyMac_PRECHECK(GetPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPort(&port);
- _res = Py_BuildValue("O&",
- GrafObj_New, port);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPort(&port);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, port);
+ return _res;
}
static PyObject *Qd_GrafDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short device;
+ PyObject *_res = NULL;
+ short device;
#ifndef GrafDevice
- PyMac_PRECHECK(GrafDevice);
+ PyMac_PRECHECK(GrafDevice);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &device))
- return NULL;
- GrafDevice(device);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &device))
+ return NULL;
+ GrafDevice(device);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetPortBits(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- BitMapPtr bm;
+ PyObject *_res = NULL;
+ BitMapPtr bm;
#ifndef SetPortBits
- PyMac_PRECHECK(SetPortBits);
+ PyMac_PRECHECK(SetPortBits);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- BMObj_Convert, &bm))
- return NULL;
- SetPortBits(bm);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ BMObj_Convert, &bm))
+ return NULL;
+ SetPortBits(bm);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PortSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short width;
- short height;
+ PyObject *_res = NULL;
+ short width;
+ short height;
#ifndef PortSize
- PyMac_PRECHECK(PortSize);
+ PyMac_PRECHECK(PortSize);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &width,
- &height))
- return NULL;
- PortSize(width,
- height);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &width,
+ &height))
+ return NULL;
+ PortSize(width,
+ height);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MovePortTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short leftGlobal;
- short topGlobal;
+ PyObject *_res = NULL;
+ short leftGlobal;
+ short topGlobal;
#ifndef MovePortTo
- PyMac_PRECHECK(MovePortTo);
+ PyMac_PRECHECK(MovePortTo);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &leftGlobal,
- &topGlobal))
- return NULL;
- MovePortTo(leftGlobal,
- topGlobal);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &leftGlobal,
+ &topGlobal))
+ return NULL;
+ MovePortTo(leftGlobal,
+ topGlobal);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetOrigin(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short h;
- short v;
+ PyObject *_res = NULL;
+ short h;
+ short v;
#ifndef SetOrigin
- PyMac_PRECHECK(SetOrigin);
+ PyMac_PRECHECK(SetOrigin);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- SetOrigin(h,
- v);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ SetOrigin(h,
+ v);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef SetClip
- PyMac_PRECHECK(SetClip);
+ PyMac_PRECHECK(SetClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- SetClip(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ SetClip(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef GetClip
- PyMac_PRECHECK(GetClip);
+ PyMac_PRECHECK(GetClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- GetClip(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ GetClip(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ClipRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef ClipRect
- PyMac_PRECHECK(ClipRect);
+ PyMac_PRECHECK(ClipRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- ClipRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ ClipRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_BackPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef BackPat
- PyMac_PRECHECK(BackPat);
-#endif
- if (!PyArg_ParseTuple(_args, "s#",
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- BackPat(pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(BackPat);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#",
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ BackPat(pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_InitCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef InitCursor
- PyMac_PRECHECK(InitCursor);
+ PyMac_PRECHECK(InitCursor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- InitCursor();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ InitCursor();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacSetCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Cursor *crsr__in__;
- int crsr__in_len__;
+ PyObject *_res = NULL;
+ Cursor *crsr__in__;
+ int crsr__in_len__;
#ifndef MacSetCursor
- PyMac_PRECHECK(MacSetCursor);
-#endif
- if (!PyArg_ParseTuple(_args, "s#",
- (char **)&crsr__in__, &crsr__in_len__))
- return NULL;
- if (crsr__in_len__ != sizeof(Cursor))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Cursor)");
- goto crsr__error__;
- }
- MacSetCursor(crsr__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(MacSetCursor);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#",
+ (char **)&crsr__in__, &crsr__in_len__))
+ return NULL;
+ if (crsr__in_len__ != sizeof(Cursor))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Cursor)");
+ goto crsr__error__;
+ }
+ MacSetCursor(crsr__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
crsr__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_HideCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef HideCursor
- PyMac_PRECHECK(HideCursor);
+ PyMac_PRECHECK(HideCursor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- HideCursor();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ HideCursor();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacShowCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef MacShowCursor
- PyMac_PRECHECK(MacShowCursor);
+ PyMac_PRECHECK(MacShowCursor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- MacShowCursor();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ MacShowCursor();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ObscureCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ObscureCursor
- PyMac_PRECHECK(ObscureCursor);
+ PyMac_PRECHECK(ObscureCursor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ObscureCursor();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ObscureCursor();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_HidePen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef HidePen
- PyMac_PRECHECK(HidePen);
+ PyMac_PRECHECK(HidePen);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- HidePen();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ HidePen();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ShowPen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ShowPen
- PyMac_PRECHECK(ShowPen);
+ PyMac_PRECHECK(ShowPen);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ShowPen();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ShowPen();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetPen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
+ PyObject *_res = NULL;
+ Point pt;
#ifndef GetPen
- PyMac_PRECHECK(GetPen);
+ PyMac_PRECHECK(GetPen);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPen(&pt);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, pt);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPen(&pt);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, pt);
+ return _res;
}
static PyObject *Qd_GetPenState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PenState pnState__out__;
+ PyObject *_res = NULL;
+ PenState pnState__out__;
#ifndef GetPenState
- PyMac_PRECHECK(GetPenState);
+ PyMac_PRECHECK(GetPenState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPenState(&pnState__out__);
- _res = Py_BuildValue("s#",
- (char *)&pnState__out__, (int)sizeof(PenState));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPenState(&pnState__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&pnState__out__, (int)sizeof(PenState));
+ return _res;
}
static PyObject *Qd_SetPenState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PenState *pnState__in__;
- int pnState__in_len__;
+ PyObject *_res = NULL;
+ PenState *pnState__in__;
+ int pnState__in_len__;
#ifndef SetPenState
- PyMac_PRECHECK(SetPenState);
-#endif
- if (!PyArg_ParseTuple(_args, "s#",
- (char **)&pnState__in__, &pnState__in_len__))
- return NULL;
- if (pnState__in_len__ != sizeof(PenState))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(PenState)");
- goto pnState__error__;
- }
- SetPenState(pnState__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(SetPenState);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#",
+ (char **)&pnState__in__, &pnState__in_len__))
+ return NULL;
+ if (pnState__in_len__ != sizeof(PenState))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(PenState)");
+ goto pnState__error__;
+ }
+ SetPenState(pnState__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pnState__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_PenSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short width;
- short height;
+ PyObject *_res = NULL;
+ short width;
+ short height;
#ifndef PenSize
- PyMac_PRECHECK(PenSize);
+ PyMac_PRECHECK(PenSize);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &width,
- &height))
- return NULL;
- PenSize(width,
- height);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &width,
+ &height))
+ return NULL;
+ PenSize(width,
+ height);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PenMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short mode;
+ PyObject *_res = NULL;
+ short mode;
#ifndef PenMode
- PyMac_PRECHECK(PenMode);
+ PyMac_PRECHECK(PenMode);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &mode))
- return NULL;
- PenMode(mode);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &mode))
+ return NULL;
+ PenMode(mode);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PenPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef PenPat
- PyMac_PRECHECK(PenPat);
-#endif
- if (!PyArg_ParseTuple(_args, "s#",
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- PenPat(pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(PenPat);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#",
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ PenPat(pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_PenNormal(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef PenNormal
- PyMac_PRECHECK(PenNormal);
+ PyMac_PRECHECK(PenNormal);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- PenNormal();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ PenNormal();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MoveTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short h;
- short v;
+ PyObject *_res = NULL;
+ short h;
+ short v;
#ifndef MoveTo
- PyMac_PRECHECK(MoveTo);
+ PyMac_PRECHECK(MoveTo);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- MoveTo(h,
- v);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ MoveTo(h,
+ v);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_Move(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ short dh;
+ short dv;
#ifndef Move
- PyMac_PRECHECK(Move);
+ PyMac_PRECHECK(Move);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &dh,
- &dv))
- return NULL;
- Move(dh,
- dv);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &dh,
+ &dv))
+ return NULL;
+ Move(dh,
+ dv);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacLineTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short h;
- short v;
+ PyObject *_res = NULL;
+ short h;
+ short v;
#ifndef MacLineTo
- PyMac_PRECHECK(MacLineTo);
+ PyMac_PRECHECK(MacLineTo);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- MacLineTo(h,
- v);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ MacLineTo(h,
+ v);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_Line(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ short dh;
+ short dv;
#ifndef Line
- PyMac_PRECHECK(Line);
+ PyMac_PRECHECK(Line);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &dh,
- &dv))
- return NULL;
- Line(dh,
- dv);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &dh,
+ &dv))
+ return NULL;
+ Line(dh,
+ dv);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ForeColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long color;
+ PyObject *_res = NULL;
+ long color;
#ifndef ForeColor
- PyMac_PRECHECK(ForeColor);
+ PyMac_PRECHECK(ForeColor);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &color))
- return NULL;
- ForeColor(color);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &color))
+ return NULL;
+ ForeColor(color);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_BackColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long color;
+ PyObject *_res = NULL;
+ long color;
#ifndef BackColor
- PyMac_PRECHECK(BackColor);
+ PyMac_PRECHECK(BackColor);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &color))
- return NULL;
- BackColor(color);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &color))
+ return NULL;
+ BackColor(color);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ColorBit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short whichBit;
+ PyObject *_res = NULL;
+ short whichBit;
#ifndef ColorBit
- PyMac_PRECHECK(ColorBit);
+ PyMac_PRECHECK(ColorBit);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &whichBit))
- return NULL;
- ColorBit(whichBit);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &whichBit))
+ return NULL;
+ ColorBit(whichBit);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacSetRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short left;
- short top;
- short right;
- short bottom;
+ PyObject *_res = NULL;
+ Rect r;
+ short left;
+ short top;
+ short right;
+ short bottom;
#ifndef MacSetRect
- PyMac_PRECHECK(MacSetRect);
-#endif
- if (!PyArg_ParseTuple(_args, "hhhh",
- &left,
- &top,
- &right,
- &bottom))
- return NULL;
- MacSetRect(&r,
- left,
- top,
- right,
- bottom);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ PyMac_PRECHECK(MacSetRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhhh",
+ &left,
+ &top,
+ &right,
+ &bottom))
+ return NULL;
+ MacSetRect(&r,
+ left,
+ top,
+ right,
+ bottom);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_MacOffsetRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ Rect r;
+ short dh;
+ short dv;
#ifndef MacOffsetRect
- PyMac_PRECHECK(MacOffsetRect);
+ PyMac_PRECHECK(MacOffsetRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &dh,
- &dv))
- return NULL;
- MacOffsetRect(&r,
- dh,
- dv);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &dh,
+ &dv))
+ return NULL;
+ MacOffsetRect(&r,
+ dh,
+ dv);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_MacInsetRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ Rect r;
+ short dh;
+ short dv;
#ifndef MacInsetRect
- PyMac_PRECHECK(MacInsetRect);
+ PyMac_PRECHECK(MacInsetRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &dh,
- &dv))
- return NULL;
- MacInsetRect(&r,
- dh,
- dv);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &dh,
+ &dv))
+ return NULL;
+ MacInsetRect(&r,
+ dh,
+ dv);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_SectRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect src1;
- Rect src2;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect src1;
+ Rect src2;
+ Rect dstRect;
#ifndef SectRect
- PyMac_PRECHECK(SectRect);
+ PyMac_PRECHECK(SectRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &src1,
- PyMac_GetRect, &src2))
- return NULL;
- _rv = SectRect(&src1,
- &src2,
- &dstRect);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildRect, &dstRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &src1,
+ PyMac_GetRect, &src2))
+ return NULL;
+ _rv = SectRect(&src1,
+ &src2,
+ &dstRect);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildRect, &dstRect);
+ return _res;
}
static PyObject *Qd_MacUnionRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect src1;
- Rect src2;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Rect src1;
+ Rect src2;
+ Rect dstRect;
#ifndef MacUnionRect
- PyMac_PRECHECK(MacUnionRect);
+ PyMac_PRECHECK(MacUnionRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &src1,
- PyMac_GetRect, &src2))
- return NULL;
- MacUnionRect(&src1,
- &src2,
- &dstRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &dstRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &src1,
+ PyMac_GetRect, &src2))
+ return NULL;
+ MacUnionRect(&src1,
+ &src2,
+ &dstRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &dstRect);
+ return _res;
}
static PyObject *Qd_MacEqualRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect rect1;
- Rect rect2;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect rect1;
+ Rect rect2;
#ifndef MacEqualRect
- PyMac_PRECHECK(MacEqualRect);
+ PyMac_PRECHECK(MacEqualRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &rect1,
- PyMac_GetRect, &rect2))
- return NULL;
- _rv = MacEqualRect(&rect1,
- &rect2);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &rect1,
+ PyMac_GetRect, &rect2))
+ return NULL;
+ _rv = MacEqualRect(&rect1,
+ &rect2);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_EmptyRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect r;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect r;
#ifndef EmptyRect
- PyMac_PRECHECK(EmptyRect);
+ PyMac_PRECHECK(EmptyRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- _rv = EmptyRect(&r);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ _rv = EmptyRect(&r);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_MacFrameRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef MacFrameRect
- PyMac_PRECHECK(MacFrameRect);
+ PyMac_PRECHECK(MacFrameRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- MacFrameRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ MacFrameRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PaintRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef PaintRect
- PyMac_PRECHECK(PaintRect);
+ PyMac_PRECHECK(PaintRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- PaintRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ PaintRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_EraseRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef EraseRect
- PyMac_PRECHECK(EraseRect);
+ PyMac_PRECHECK(EraseRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- EraseRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ EraseRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacInvertRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef MacInvertRect
- PyMac_PRECHECK(MacInvertRect);
+ PyMac_PRECHECK(MacInvertRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- MacInvertRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ MacInvertRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacFillRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Rect r;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef MacFillRect
- PyMac_PRECHECK(MacFillRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- PyMac_GetRect, &r,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- MacFillRect(&r,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(MacFillRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ PyMac_GetRect, &r,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ MacFillRect(&r,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_FrameOval(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef FrameOval
- PyMac_PRECHECK(FrameOval);
+ PyMac_PRECHECK(FrameOval);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- FrameOval(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ FrameOval(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PaintOval(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef PaintOval
- PyMac_PRECHECK(PaintOval);
+ PyMac_PRECHECK(PaintOval);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- PaintOval(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ PaintOval(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_EraseOval(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef EraseOval
- PyMac_PRECHECK(EraseOval);
+ PyMac_PRECHECK(EraseOval);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- EraseOval(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ EraseOval(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InvertOval(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef InvertOval
- PyMac_PRECHECK(InvertOval);
+ PyMac_PRECHECK(InvertOval);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- InvertOval(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ InvertOval(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillOval(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Rect r;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef FillOval
- PyMac_PRECHECK(FillOval);
-#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- PyMac_GetRect, &r,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- FillOval(&r,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(FillOval);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ PyMac_GetRect, &r,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ FillOval(&r,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_FrameRoundRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short ovalWidth;
- short ovalHeight;
+ PyObject *_res = NULL;
+ Rect r;
+ short ovalWidth;
+ short ovalHeight;
#ifndef FrameRoundRect
- PyMac_PRECHECK(FrameRoundRect);
+ PyMac_PRECHECK(FrameRoundRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &ovalWidth,
- &ovalHeight))
- return NULL;
- FrameRoundRect(&r,
- ovalWidth,
- ovalHeight);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &ovalWidth,
+ &ovalHeight))
+ return NULL;
+ FrameRoundRect(&r,
+ ovalWidth,
+ ovalHeight);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PaintRoundRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short ovalWidth;
- short ovalHeight;
+ PyObject *_res = NULL;
+ Rect r;
+ short ovalWidth;
+ short ovalHeight;
#ifndef PaintRoundRect
- PyMac_PRECHECK(PaintRoundRect);
+ PyMac_PRECHECK(PaintRoundRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &ovalWidth,
- &ovalHeight))
- return NULL;
- PaintRoundRect(&r,
- ovalWidth,
- ovalHeight);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &ovalWidth,
+ &ovalHeight))
+ return NULL;
+ PaintRoundRect(&r,
+ ovalWidth,
+ ovalHeight);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_EraseRoundRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short ovalWidth;
- short ovalHeight;
+ PyObject *_res = NULL;
+ Rect r;
+ short ovalWidth;
+ short ovalHeight;
#ifndef EraseRoundRect
- PyMac_PRECHECK(EraseRoundRect);
+ PyMac_PRECHECK(EraseRoundRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &ovalWidth,
- &ovalHeight))
- return NULL;
- EraseRoundRect(&r,
- ovalWidth,
- ovalHeight);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &ovalWidth,
+ &ovalHeight))
+ return NULL;
+ EraseRoundRect(&r,
+ ovalWidth,
+ ovalHeight);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InvertRoundRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short ovalWidth;
- short ovalHeight;
+ PyObject *_res = NULL;
+ Rect r;
+ short ovalWidth;
+ short ovalHeight;
#ifndef InvertRoundRect
- PyMac_PRECHECK(InvertRoundRect);
+ PyMac_PRECHECK(InvertRoundRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &ovalWidth,
- &ovalHeight))
- return NULL;
- InvertRoundRect(&r,
- ovalWidth,
- ovalHeight);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &ovalWidth,
+ &ovalHeight))
+ return NULL;
+ InvertRoundRect(&r,
+ ovalWidth,
+ ovalHeight);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillRoundRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short ovalWidth;
- short ovalHeight;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Rect r;
+ short ovalWidth;
+ short ovalHeight;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef FillRoundRect
- PyMac_PRECHECK(FillRoundRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhs#",
- PyMac_GetRect, &r,
- &ovalWidth,
- &ovalHeight,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- FillRoundRect(&r,
- ovalWidth,
- ovalHeight,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(FillRoundRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhs#",
+ PyMac_GetRect, &r,
+ &ovalWidth,
+ &ovalHeight,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ FillRoundRect(&r,
+ ovalWidth,
+ ovalHeight,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_FrameArc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short startAngle;
- short arcAngle;
+ PyObject *_res = NULL;
+ Rect r;
+ short startAngle;
+ short arcAngle;
#ifndef FrameArc
- PyMac_PRECHECK(FrameArc);
+ PyMac_PRECHECK(FrameArc);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &startAngle,
- &arcAngle))
- return NULL;
- FrameArc(&r,
- startAngle,
- arcAngle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &startAngle,
+ &arcAngle))
+ return NULL;
+ FrameArc(&r,
+ startAngle,
+ arcAngle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PaintArc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short startAngle;
- short arcAngle;
+ PyObject *_res = NULL;
+ Rect r;
+ short startAngle;
+ short arcAngle;
#ifndef PaintArc
- PyMac_PRECHECK(PaintArc);
+ PyMac_PRECHECK(PaintArc);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &startAngle,
- &arcAngle))
- return NULL;
- PaintArc(&r,
- startAngle,
- arcAngle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &startAngle,
+ &arcAngle))
+ return NULL;
+ PaintArc(&r,
+ startAngle,
+ arcAngle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_EraseArc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short startAngle;
- short arcAngle;
+ PyObject *_res = NULL;
+ Rect r;
+ short startAngle;
+ short arcAngle;
#ifndef EraseArc
- PyMac_PRECHECK(EraseArc);
+ PyMac_PRECHECK(EraseArc);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &startAngle,
- &arcAngle))
- return NULL;
- EraseArc(&r,
- startAngle,
- arcAngle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &startAngle,
+ &arcAngle))
+ return NULL;
+ EraseArc(&r,
+ startAngle,
+ arcAngle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InvertArc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short startAngle;
- short arcAngle;
+ PyObject *_res = NULL;
+ Rect r;
+ short startAngle;
+ short arcAngle;
#ifndef InvertArc
- PyMac_PRECHECK(InvertArc);
+ PyMac_PRECHECK(InvertArc);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &startAngle,
- &arcAngle))
- return NULL;
- InvertArc(&r,
- startAngle,
- arcAngle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &startAngle,
+ &arcAngle))
+ return NULL;
+ InvertArc(&r,
+ startAngle,
+ arcAngle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillArc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short startAngle;
- short arcAngle;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Rect r;
+ short startAngle;
+ short arcAngle;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef FillArc
- PyMac_PRECHECK(FillArc);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhs#",
- PyMac_GetRect, &r,
- &startAngle,
- &arcAngle,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- FillArc(&r,
- startAngle,
- arcAngle,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(FillArc);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhs#",
+ PyMac_GetRect, &r,
+ &startAngle,
+ &arcAngle,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ FillArc(&r,
+ startAngle,
+ arcAngle,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_NewRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef NewRgn
- PyMac_PRECHECK(NewRgn);
+ PyMac_PRECHECK(NewRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = NewRgn();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = NewRgn();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_OpenRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef OpenRgn
- PyMac_PRECHECK(OpenRgn);
+ PyMac_PRECHECK(OpenRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- OpenRgn();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ OpenRgn();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_CloseRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle dstRgn;
#ifndef CloseRgn
- PyMac_PRECHECK(CloseRgn);
+ PyMac_PRECHECK(CloseRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &dstRgn))
- return NULL;
- CloseRgn(dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ CloseRgn(dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_BitMapToRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle region;
- BitMapPtr bMap;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle region;
+ BitMapPtr bMap;
#ifndef BitMapToRegion
- PyMac_PRECHECK(BitMapToRegion);
+ PyMac_PRECHECK(BitMapToRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &region,
- BMObj_Convert, &bMap))
- return NULL;
- _err = BitMapToRegion(region,
- bMap);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &region,
+ BMObj_Convert, &bMap))
+ return NULL;
+ _err = BitMapToRegion(region,
+ bMap);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_RgnToHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle region;
- Handle flattenedRgnDataHdl;
+ PyObject *_res = NULL;
+ RgnHandle region;
+ Handle flattenedRgnDataHdl;
#ifndef RgnToHandle
- PyMac_PRECHECK(RgnToHandle);
+ PyMac_PRECHECK(RgnToHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &region,
- ResObj_Convert, &flattenedRgnDataHdl))
- return NULL;
- RgnToHandle(region,
- flattenedRgnDataHdl);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &region,
+ ResObj_Convert, &flattenedRgnDataHdl))
+ return NULL;
+ RgnToHandle(region,
+ flattenedRgnDataHdl);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DisposeRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef DisposeRgn
- PyMac_PRECHECK(DisposeRgn);
+ PyMac_PRECHECK(DisposeRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- DisposeRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ DisposeRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacCopyRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgn;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgn;
+ RgnHandle dstRgn;
#ifndef MacCopyRgn
- PyMac_PRECHECK(MacCopyRgn);
+ PyMac_PRECHECK(MacCopyRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &srcRgn,
- ResObj_Convert, &dstRgn))
- return NULL;
- MacCopyRgn(srcRgn,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &srcRgn,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ MacCopyRgn(srcRgn,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetEmptyRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef SetEmptyRgn
- PyMac_PRECHECK(SetEmptyRgn);
+ PyMac_PRECHECK(SetEmptyRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- SetEmptyRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ SetEmptyRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacSetRectRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- short left;
- short top;
- short right;
- short bottom;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ short left;
+ short top;
+ short right;
+ short bottom;
#ifndef MacSetRectRgn
- PyMac_PRECHECK(MacSetRectRgn);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhhh",
- ResObj_Convert, &rgn,
- &left,
- &top,
- &right,
- &bottom))
- return NULL;
- MacSetRectRgn(rgn,
- left,
- top,
- right,
- bottom);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(MacSetRectRgn);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhhh",
+ ResObj_Convert, &rgn,
+ &left,
+ &top,
+ &right,
+ &bottom))
+ return NULL;
+ MacSetRectRgn(rgn,
+ left,
+ top,
+ right,
+ bottom);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_RectRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- Rect r;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ Rect r;
#ifndef RectRgn
- PyMac_PRECHECK(RectRgn);
+ PyMac_PRECHECK(RectRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &rgn,
- PyMac_GetRect, &r))
- return NULL;
- RectRgn(rgn,
- &r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &rgn,
+ PyMac_GetRect, &r))
+ return NULL;
+ RectRgn(rgn,
+ &r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacOffsetRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ short dh;
+ short dv;
#ifndef MacOffsetRgn
- PyMac_PRECHECK(MacOffsetRgn);
+ PyMac_PRECHECK(MacOffsetRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- ResObj_Convert, &rgn,
- &dh,
- &dv))
- return NULL;
- MacOffsetRgn(rgn,
- dh,
- dv);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ ResObj_Convert, &rgn,
+ &dh,
+ &dv))
+ return NULL;
+ MacOffsetRgn(rgn,
+ dh,
+ dv);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InsetRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ short dh;
+ short dv;
#ifndef InsetRgn
- PyMac_PRECHECK(InsetRgn);
+ PyMac_PRECHECK(InsetRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- ResObj_Convert, &rgn,
- &dh,
- &dv))
- return NULL;
- InsetRgn(rgn,
- dh,
- dv);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ ResObj_Convert, &rgn,
+ &dh,
+ &dv))
+ return NULL;
+ InsetRgn(rgn,
+ dh,
+ dv);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SectRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgnA;
- RgnHandle srcRgnB;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgnA;
+ RgnHandle srcRgnB;
+ RgnHandle dstRgn;
#ifndef SectRgn
- PyMac_PRECHECK(SectRgn);
+ PyMac_PRECHECK(SectRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &srcRgnA,
- ResObj_Convert, &srcRgnB,
- ResObj_Convert, &dstRgn))
- return NULL;
- SectRgn(srcRgnA,
- srcRgnB,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &srcRgnA,
+ ResObj_Convert, &srcRgnB,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ SectRgn(srcRgnA,
+ srcRgnB,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacUnionRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgnA;
- RgnHandle srcRgnB;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgnA;
+ RgnHandle srcRgnB;
+ RgnHandle dstRgn;
#ifndef MacUnionRgn
- PyMac_PRECHECK(MacUnionRgn);
+ PyMac_PRECHECK(MacUnionRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &srcRgnA,
- ResObj_Convert, &srcRgnB,
- ResObj_Convert, &dstRgn))
- return NULL;
- MacUnionRgn(srcRgnA,
- srcRgnB,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &srcRgnA,
+ ResObj_Convert, &srcRgnB,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ MacUnionRgn(srcRgnA,
+ srcRgnB,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DiffRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgnA;
- RgnHandle srcRgnB;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgnA;
+ RgnHandle srcRgnB;
+ RgnHandle dstRgn;
#ifndef DiffRgn
- PyMac_PRECHECK(DiffRgn);
+ PyMac_PRECHECK(DiffRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &srcRgnA,
- ResObj_Convert, &srcRgnB,
- ResObj_Convert, &dstRgn))
- return NULL;
- DiffRgn(srcRgnA,
- srcRgnB,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &srcRgnA,
+ ResObj_Convert, &srcRgnB,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ DiffRgn(srcRgnA,
+ srcRgnB,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacXorRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgnA;
- RgnHandle srcRgnB;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgnA;
+ RgnHandle srcRgnB;
+ RgnHandle dstRgn;
#ifndef MacXorRgn
- PyMac_PRECHECK(MacXorRgn);
+ PyMac_PRECHECK(MacXorRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &srcRgnA,
- ResObj_Convert, &srcRgnB,
- ResObj_Convert, &dstRgn))
- return NULL;
- MacXorRgn(srcRgnA,
- srcRgnB,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &srcRgnA,
+ ResObj_Convert, &srcRgnB,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ MacXorRgn(srcRgnA,
+ srcRgnB,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_RectInRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect r;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect r;
+ RgnHandle rgn;
#ifndef RectInRgn
- PyMac_PRECHECK(RectInRgn);
+ PyMac_PRECHECK(RectInRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &r,
- ResObj_Convert, &rgn))
- return NULL;
- _rv = RectInRgn(&r,
- rgn);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &r,
+ ResObj_Convert, &rgn))
+ return NULL;
+ _rv = RectInRgn(&r,
+ rgn);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_MacEqualRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- RgnHandle rgnA;
- RgnHandle rgnB;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ RgnHandle rgnA;
+ RgnHandle rgnB;
#ifndef MacEqualRgn
- PyMac_PRECHECK(MacEqualRgn);
+ PyMac_PRECHECK(MacEqualRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &rgnA,
- ResObj_Convert, &rgnB))
- return NULL;
- _rv = MacEqualRgn(rgnA,
- rgnB);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &rgnA,
+ ResObj_Convert, &rgnB))
+ return NULL;
+ _rv = MacEqualRgn(rgnA,
+ rgnB);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_EmptyRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ RgnHandle rgn;
#ifndef EmptyRgn
- PyMac_PRECHECK(EmptyRgn);
+ PyMac_PRECHECK(EmptyRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- _rv = EmptyRgn(rgn);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ _rv = EmptyRgn(rgn);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_MacFrameRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef MacFrameRgn
- PyMac_PRECHECK(MacFrameRgn);
+ PyMac_PRECHECK(MacFrameRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- MacFrameRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ MacFrameRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacPaintRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef MacPaintRgn
- PyMac_PRECHECK(MacPaintRgn);
+ PyMac_PRECHECK(MacPaintRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- MacPaintRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ MacPaintRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_EraseRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef EraseRgn
- PyMac_PRECHECK(EraseRgn);
+ PyMac_PRECHECK(EraseRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- EraseRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ EraseRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacInvertRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef MacInvertRgn
- PyMac_PRECHECK(MacInvertRgn);
+ PyMac_PRECHECK(MacInvertRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- MacInvertRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ MacInvertRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacFillRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef MacFillRgn
- PyMac_PRECHECK(MacFillRgn);
-#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- ResObj_Convert, &rgn,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- MacFillRgn(rgn,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(MacFillRgn);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ ResObj_Convert, &rgn,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ MacFillRgn(rgn,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_ScrollRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short dh;
- short dv;
- RgnHandle updateRgn;
+ PyObject *_res = NULL;
+ Rect r;
+ short dh;
+ short dv;
+ RgnHandle updateRgn;
#ifndef ScrollRect
- PyMac_PRECHECK(ScrollRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &r,
- &dh,
- &dv,
- ResObj_Convert, &updateRgn))
- return NULL;
- ScrollRect(&r,
- dh,
- dv,
- updateRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ScrollRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &r,
+ &dh,
+ &dv,
+ ResObj_Convert, &updateRgn))
+ return NULL;
+ ScrollRect(&r,
+ dh,
+ dv,
+ updateRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_CopyBits(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- BitMapPtr srcBits;
- BitMapPtr dstBits;
- Rect srcRect;
- Rect dstRect;
- short mode;
- RgnHandle maskRgn;
+ PyObject *_res = NULL;
+ BitMapPtr srcBits;
+ BitMapPtr dstBits;
+ Rect srcRect;
+ Rect dstRect;
+ short mode;
+ RgnHandle maskRgn;
#ifndef CopyBits
- PyMac_PRECHECK(CopyBits);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&hO&",
- BMObj_Convert, &srcBits,
- BMObj_Convert, &dstBits,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect,
- &mode,
- OptResObj_Convert, &maskRgn))
- return NULL;
- CopyBits(srcBits,
- dstBits,
- &srcRect,
- &dstRect,
- mode,
- maskRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CopyBits);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&hO&",
+ BMObj_Convert, &srcBits,
+ BMObj_Convert, &dstBits,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect,
+ &mode,
+ OptResObj_Convert, &maskRgn))
+ return NULL;
+ CopyBits(srcBits,
+ dstBits,
+ &srcRect,
+ &dstRect,
+ mode,
+ maskRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_CopyMask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- BitMapPtr srcBits;
- BitMapPtr maskBits;
- BitMapPtr dstBits;
- Rect srcRect;
- Rect maskRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ BitMapPtr srcBits;
+ BitMapPtr maskBits;
+ BitMapPtr dstBits;
+ Rect srcRect;
+ Rect maskRect;
+ Rect dstRect;
#ifndef CopyMask
- PyMac_PRECHECK(CopyMask);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&O&",
- BMObj_Convert, &srcBits,
- BMObj_Convert, &maskBits,
- BMObj_Convert, &dstBits,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &maskRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- CopyMask(srcBits,
- maskBits,
- dstBits,
- &srcRect,
- &maskRect,
- &dstRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CopyMask);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&O&",
+ BMObj_Convert, &srcBits,
+ BMObj_Convert, &maskBits,
+ BMObj_Convert, &dstBits,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &maskRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ CopyMask(srcBits,
+ maskBits,
+ dstBits,
+ &srcRect,
+ &maskRect,
+ &dstRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_OpenPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle _rv;
- Rect picFrame;
+ PyObject *_res = NULL;
+ PicHandle _rv;
+ Rect picFrame;
#ifndef OpenPicture
- PyMac_PRECHECK(OpenPicture);
+ PyMac_PRECHECK(OpenPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &picFrame))
- return NULL;
- _rv = OpenPicture(&picFrame);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &picFrame))
+ return NULL;
+ _rv = OpenPicture(&picFrame);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_PicComment(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short kind;
- short dataSize;
- Handle dataHandle;
+ PyObject *_res = NULL;
+ short kind;
+ short dataSize;
+ Handle dataHandle;
#ifndef PicComment
- PyMac_PRECHECK(PicComment);
+ PyMac_PRECHECK(PicComment);
#endif
- if (!PyArg_ParseTuple(_args, "hhO&",
- &kind,
- &dataSize,
- ResObj_Convert, &dataHandle))
- return NULL;
- PicComment(kind,
- dataSize,
- dataHandle);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhO&",
+ &kind,
+ &dataSize,
+ ResObj_Convert, &dataHandle))
+ return NULL;
+ PicComment(kind,
+ dataSize,
+ dataHandle);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ClosePicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClosePicture
- PyMac_PRECHECK(ClosePicture);
+ PyMac_PRECHECK(ClosePicture);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClosePicture();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClosePicture();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DrawPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle myPicture;
- Rect dstRect;
+ PyObject *_res = NULL;
+ PicHandle myPicture;
+ Rect dstRect;
#ifndef DrawPicture
- PyMac_PRECHECK(DrawPicture);
+ PyMac_PRECHECK(DrawPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &myPicture,
- PyMac_GetRect, &dstRect))
- return NULL;
- DrawPicture(myPicture,
- &dstRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &myPicture,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ DrawPicture(myPicture,
+ &dstRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_KillPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle myPicture;
+ PyObject *_res = NULL;
+ PicHandle myPicture;
#ifndef KillPicture
- PyMac_PRECHECK(KillPicture);
+ PyMac_PRECHECK(KillPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &myPicture))
- return NULL;
- KillPicture(myPicture);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &myPicture))
+ return NULL;
+ KillPicture(myPicture);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_OpenPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle _rv;
+ PyObject *_res = NULL;
+ PolyHandle _rv;
#ifndef OpenPoly
- PyMac_PRECHECK(OpenPoly);
+ PyMac_PRECHECK(OpenPoly);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = OpenPoly();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = OpenPoly();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_ClosePoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClosePoly
- PyMac_PRECHECK(ClosePoly);
+ PyMac_PRECHECK(ClosePoly);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClosePoly();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClosePoly();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_KillPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
+ PyObject *_res = NULL;
+ PolyHandle poly;
#ifndef KillPoly
- PyMac_PRECHECK(KillPoly);
+ PyMac_PRECHECK(KillPoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &poly))
- return NULL;
- KillPoly(poly);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &poly))
+ return NULL;
+ KillPoly(poly);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_OffsetPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ PolyHandle poly;
+ short dh;
+ short dv;
#ifndef OffsetPoly
- PyMac_PRECHECK(OffsetPoly);
+ PyMac_PRECHECK(OffsetPoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- ResObj_Convert, &poly,
- &dh,
- &dv))
- return NULL;
- OffsetPoly(poly,
- dh,
- dv);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ ResObj_Convert, &poly,
+ &dh,
+ &dv))
+ return NULL;
+ OffsetPoly(poly,
+ dh,
+ dv);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FramePoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
+ PyObject *_res = NULL;
+ PolyHandle poly;
#ifndef FramePoly
- PyMac_PRECHECK(FramePoly);
+ PyMac_PRECHECK(FramePoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &poly))
- return NULL;
- FramePoly(poly);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &poly))
+ return NULL;
+ FramePoly(poly);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PaintPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
+ PyObject *_res = NULL;
+ PolyHandle poly;
#ifndef PaintPoly
- PyMac_PRECHECK(PaintPoly);
+ PyMac_PRECHECK(PaintPoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &poly))
- return NULL;
- PaintPoly(poly);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &poly))
+ return NULL;
+ PaintPoly(poly);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ErasePoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
+ PyObject *_res = NULL;
+ PolyHandle poly;
#ifndef ErasePoly
- PyMac_PRECHECK(ErasePoly);
+ PyMac_PRECHECK(ErasePoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &poly))
- return NULL;
- ErasePoly(poly);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &poly))
+ return NULL;
+ ErasePoly(poly);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InvertPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
+ PyObject *_res = NULL;
+ PolyHandle poly;
#ifndef InvertPoly
- PyMac_PRECHECK(InvertPoly);
+ PyMac_PRECHECK(InvertPoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &poly))
- return NULL;
- InvertPoly(poly);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &poly))
+ return NULL;
+ InvertPoly(poly);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ PolyHandle poly;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef FillPoly
- PyMac_PRECHECK(FillPoly);
-#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- ResObj_Convert, &poly,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- FillPoly(poly,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(FillPoly);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ ResObj_Convert, &poly,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ FillPoly(poly,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_SetPt(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
- short h;
- short v;
+ PyObject *_res = NULL;
+ Point pt;
+ short h;
+ short v;
#ifndef SetPt
- PyMac_PRECHECK(SetPt);
+ PyMac_PRECHECK(SetPt);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- SetPt(&pt,
- h,
- v);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, pt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ SetPt(&pt,
+ h,
+ v);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, pt);
+ return _res;
}
static PyObject *Qd_LocalToGlobal(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
+ PyObject *_res = NULL;
+ Point pt;
#ifndef LocalToGlobal
- PyMac_PRECHECK(LocalToGlobal);
+ PyMac_PRECHECK(LocalToGlobal);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &pt))
- return NULL;
- LocalToGlobal(&pt);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, pt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &pt))
+ return NULL;
+ LocalToGlobal(&pt);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, pt);
+ return _res;
}
static PyObject *Qd_GlobalToLocal(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
+ PyObject *_res = NULL;
+ Point pt;
#ifndef GlobalToLocal
- PyMac_PRECHECK(GlobalToLocal);
+ PyMac_PRECHECK(GlobalToLocal);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &pt))
- return NULL;
- GlobalToLocal(&pt);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, pt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &pt))
+ return NULL;
+ GlobalToLocal(&pt);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, pt);
+ return _res;
}
static PyObject *Qd_Random(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef Random
- PyMac_PRECHECK(Random);
+ PyMac_PRECHECK(Random);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = Random();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = Random();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_MacGetPixel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- short h;
- short v;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ short h;
+ short v;
#ifndef MacGetPixel
- PyMac_PRECHECK(MacGetPixel);
+ PyMac_PRECHECK(MacGetPixel);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- _rv = MacGetPixel(h,
- v);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ _rv = MacGetPixel(h,
+ v);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_ScalePt(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
- Rect srcRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Point pt;
+ Rect srcRect;
+ Rect dstRect;
#ifndef ScalePt
- PyMac_PRECHECK(ScalePt);
+ PyMac_PRECHECK(ScalePt);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetPoint, &pt,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- ScalePt(&pt,
- &srcRect,
- &dstRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, pt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetPoint, &pt,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ ScalePt(&pt,
+ &srcRect,
+ &dstRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, pt);
+ return _res;
}
static PyObject *Qd_MapPt(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
- Rect srcRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Point pt;
+ Rect srcRect;
+ Rect dstRect;
#ifndef MapPt
- PyMac_PRECHECK(MapPt);
+ PyMac_PRECHECK(MapPt);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetPoint, &pt,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- MapPt(&pt,
- &srcRect,
- &dstRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, pt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetPoint, &pt,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ MapPt(&pt,
+ &srcRect,
+ &dstRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, pt);
+ return _res;
}
static PyObject *Qd_MapRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- Rect srcRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Rect r;
+ Rect srcRect;
+ Rect dstRect;
#ifndef MapRect
- PyMac_PRECHECK(MapRect);
+ PyMac_PRECHECK(MapRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetRect, &r,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- MapRect(&r,
- &srcRect,
- &dstRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetRect, &r,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ MapRect(&r,
+ &srcRect,
+ &dstRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_MapRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- Rect srcRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ Rect srcRect;
+ Rect dstRect;
#ifndef MapRgn
- PyMac_PRECHECK(MapRgn);
+ PyMac_PRECHECK(MapRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &rgn,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- MapRgn(rgn,
- &srcRect,
- &dstRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &rgn,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ MapRgn(rgn,
+ &srcRect,
+ &dstRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MapPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
- Rect srcRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ PolyHandle poly;
+ Rect srcRect;
+ Rect dstRect;
#ifndef MapPoly
- PyMac_PRECHECK(MapPoly);
+ PyMac_PRECHECK(MapPoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &poly,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- MapPoly(poly,
- &srcRect,
- &dstRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &poly,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ MapPoly(poly,
+ &srcRect,
+ &dstRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_StdBits(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- BitMapPtr srcBits;
- Rect srcRect;
- Rect dstRect;
- short mode;
- RgnHandle maskRgn;
+ PyObject *_res = NULL;
+ BitMapPtr srcBits;
+ Rect srcRect;
+ Rect dstRect;
+ short mode;
+ RgnHandle maskRgn;
#ifndef StdBits
- PyMac_PRECHECK(StdBits);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&hO&",
- BMObj_Convert, &srcBits,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect,
- &mode,
- OptResObj_Convert, &maskRgn))
- return NULL;
- StdBits(srcBits,
- &srcRect,
- &dstRect,
- mode,
- maskRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(StdBits);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&hO&",
+ BMObj_Convert, &srcBits,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect,
+ &mode,
+ OptResObj_Convert, &maskRgn))
+ return NULL;
+ StdBits(srcBits,
+ &srcRect,
+ &dstRect,
+ mode,
+ maskRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_AddPt(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point src;
- Point dst;
+ PyObject *_res = NULL;
+ Point src;
+ Point dst;
#ifndef AddPt
- PyMac_PRECHECK(AddPt);
+ PyMac_PRECHECK(AddPt);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &src,
- PyMac_GetPoint, &dst))
- return NULL;
- AddPt(src,
- &dst);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &src,
+ PyMac_GetPoint, &dst))
+ return NULL;
+ AddPt(src,
+ &dst);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, dst);
+ return _res;
}
static PyObject *Qd_EqualPt(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt1;
- Point pt2;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt1;
+ Point pt2;
#ifndef EqualPt
- PyMac_PRECHECK(EqualPt);
+ PyMac_PRECHECK(EqualPt);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &pt1,
- PyMac_GetPoint, &pt2))
- return NULL;
- _rv = EqualPt(pt1,
- pt2);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &pt1,
+ PyMac_GetPoint, &pt2))
+ return NULL;
+ _rv = EqualPt(pt1,
+ pt2);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_MacPtInRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt;
- Rect r;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt;
+ Rect r;
#ifndef MacPtInRect
- PyMac_PRECHECK(MacPtInRect);
+ PyMac_PRECHECK(MacPtInRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &pt,
- PyMac_GetRect, &r))
- return NULL;
- _rv = MacPtInRect(pt,
- &r);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &pt,
+ PyMac_GetRect, &r))
+ return NULL;
+ _rv = MacPtInRect(pt,
+ &r);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_Pt2Rect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt1;
- Point pt2;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Point pt1;
+ Point pt2;
+ Rect dstRect;
#ifndef Pt2Rect
- PyMac_PRECHECK(Pt2Rect);
+ PyMac_PRECHECK(Pt2Rect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &pt1,
- PyMac_GetPoint, &pt2))
- return NULL;
- Pt2Rect(pt1,
- pt2,
- &dstRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &dstRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &pt1,
+ PyMac_GetPoint, &pt2))
+ return NULL;
+ Pt2Rect(pt1,
+ pt2,
+ &dstRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &dstRect);
+ return _res;
}
static PyObject *Qd_PtToAngle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- Point pt;
- short angle;
+ PyObject *_res = NULL;
+ Rect r;
+ Point pt;
+ short angle;
#ifndef PtToAngle
- PyMac_PRECHECK(PtToAngle);
+ PyMac_PRECHECK(PtToAngle);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &r,
- PyMac_GetPoint, &pt))
- return NULL;
- PtToAngle(&r,
- pt,
- &angle);
- _res = Py_BuildValue("h",
- angle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &r,
+ PyMac_GetPoint, &pt))
+ return NULL;
+ PtToAngle(&r,
+ pt,
+ &angle);
+ _res = Py_BuildValue("h",
+ angle);
+ return _res;
}
static PyObject *Qd_SubPt(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point src;
- Point dst;
+ PyObject *_res = NULL;
+ Point src;
+ Point dst;
#ifndef SubPt
- PyMac_PRECHECK(SubPt);
+ PyMac_PRECHECK(SubPt);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &src,
- PyMac_GetPoint, &dst))
- return NULL;
- SubPt(src,
- &dst);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &src,
+ PyMac_GetPoint, &dst))
+ return NULL;
+ SubPt(src,
+ &dst);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, dst);
+ return _res;
}
static PyObject *Qd_PtInRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt;
+ RgnHandle rgn;
#ifndef PtInRgn
- PyMac_PRECHECK(PtInRgn);
+ PyMac_PRECHECK(PtInRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &pt,
- ResObj_Convert, &rgn))
- return NULL;
- _rv = PtInRgn(pt,
- rgn);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &pt,
+ ResObj_Convert, &rgn))
+ return NULL;
+ _rv = PtInRgn(pt,
+ rgn);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_NewPixMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle _rv;
+ PyObject *_res = NULL;
+ PixMapHandle _rv;
#ifndef NewPixMap
- PyMac_PRECHECK(NewPixMap);
+ PyMac_PRECHECK(NewPixMap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = NewPixMap();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = NewPixMap();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_DisposePixMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ PixMapHandle pm;
#ifndef DisposePixMap
- PyMac_PRECHECK(DisposePixMap);
+ PyMac_PRECHECK(DisposePixMap);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- DisposePixMap(pm);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ DisposePixMap(pm);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_CopyPixMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle srcPM;
- PixMapHandle dstPM;
+ PyObject *_res = NULL;
+ PixMapHandle srcPM;
+ PixMapHandle dstPM;
#ifndef CopyPixMap
- PyMac_PRECHECK(CopyPixMap);
+ PyMac_PRECHECK(CopyPixMap);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &srcPM,
- ResObj_Convert, &dstPM))
- return NULL;
- CopyPixMap(srcPM,
- dstPM);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &srcPM,
+ ResObj_Convert, &dstPM))
+ return NULL;
+ CopyPixMap(srcPM,
+ dstPM);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_NewPixPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle _rv;
+ PyObject *_res = NULL;
+ PixPatHandle _rv;
#ifndef NewPixPat
- PyMac_PRECHECK(NewPixPat);
+ PyMac_PRECHECK(NewPixPat);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = NewPixPat();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = NewPixPat();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_DisposePixPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ PixPatHandle pp;
#ifndef DisposePixPat
- PyMac_PRECHECK(DisposePixPat);
+ PyMac_PRECHECK(DisposePixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pp))
- return NULL;
- DisposePixPat(pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pp))
+ return NULL;
+ DisposePixPat(pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_CopyPixPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle srcPP;
- PixPatHandle dstPP;
+ PyObject *_res = NULL;
+ PixPatHandle srcPP;
+ PixPatHandle dstPP;
#ifndef CopyPixPat
- PyMac_PRECHECK(CopyPixPat);
+ PyMac_PRECHECK(CopyPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &srcPP,
- ResObj_Convert, &dstPP))
- return NULL;
- CopyPixPat(srcPP,
- dstPP);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &srcPP,
+ ResObj_Convert, &dstPP))
+ return NULL;
+ CopyPixPat(srcPP,
+ dstPP);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PenPixPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ PixPatHandle pp;
#ifndef PenPixPat
- PyMac_PRECHECK(PenPixPat);
+ PyMac_PRECHECK(PenPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pp))
- return NULL;
- PenPixPat(pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pp))
+ return NULL;
+ PenPixPat(pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_BackPixPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ PixPatHandle pp;
#ifndef BackPixPat
- PyMac_PRECHECK(BackPixPat);
+ PyMac_PRECHECK(BackPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pp))
- return NULL;
- BackPixPat(pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pp))
+ return NULL;
+ BackPixPat(pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetPixPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle _rv;
- short patID;
+ PyObject *_res = NULL;
+ PixPatHandle _rv;
+ short patID;
#ifndef GetPixPat
- PyMac_PRECHECK(GetPixPat);
+ PyMac_PRECHECK(GetPixPat);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &patID))
- return NULL;
- _rv = GetPixPat(patID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &patID))
+ return NULL;
+ _rv = GetPixPat(patID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_MakeRGBPat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle pp;
- RGBColor myColor;
+ PyObject *_res = NULL;
+ PixPatHandle pp;
+ RGBColor myColor;
#ifndef MakeRGBPat
- PyMac_PRECHECK(MakeRGBPat);
+ PyMac_PRECHECK(MakeRGBPat);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &pp,
- QdRGB_Convert, &myColor))
- return NULL;
- MakeRGBPat(pp,
- &myColor);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &pp,
+ QdRGB_Convert, &myColor))
+ return NULL;
+ MakeRGBPat(pp,
+ &myColor);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillCRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ Rect r;
+ PixPatHandle pp;
#ifndef FillCRect
- PyMac_PRECHECK(FillCRect);
+ PyMac_PRECHECK(FillCRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &r,
- ResObj_Convert, &pp))
- return NULL;
- FillCRect(&r,
- pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &r,
+ ResObj_Convert, &pp))
+ return NULL;
+ FillCRect(&r,
+ pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillCOval(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ Rect r;
+ PixPatHandle pp;
#ifndef FillCOval
- PyMac_PRECHECK(FillCOval);
+ PyMac_PRECHECK(FillCOval);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &r,
- ResObj_Convert, &pp))
- return NULL;
- FillCOval(&r,
- pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &r,
+ ResObj_Convert, &pp))
+ return NULL;
+ FillCOval(&r,
+ pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillCRoundRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short ovalWidth;
- short ovalHeight;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ Rect r;
+ short ovalWidth;
+ short ovalHeight;
+ PixPatHandle pp;
#ifndef FillCRoundRect
- PyMac_PRECHECK(FillCRoundRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &r,
- &ovalWidth,
- &ovalHeight,
- ResObj_Convert, &pp))
- return NULL;
- FillCRoundRect(&r,
- ovalWidth,
- ovalHeight,
- pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(FillCRoundRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &r,
+ &ovalWidth,
+ &ovalHeight,
+ ResObj_Convert, &pp))
+ return NULL;
+ FillCRoundRect(&r,
+ ovalWidth,
+ ovalHeight,
+ pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillCArc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short startAngle;
- short arcAngle;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ Rect r;
+ short startAngle;
+ short arcAngle;
+ PixPatHandle pp;
#ifndef FillCArc
- PyMac_PRECHECK(FillCArc);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- PyMac_GetRect, &r,
- &startAngle,
- &arcAngle,
- ResObj_Convert, &pp))
- return NULL;
- FillCArc(&r,
- startAngle,
- arcAngle,
- pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(FillCArc);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ PyMac_GetRect, &r,
+ &startAngle,
+ &arcAngle,
+ ResObj_Convert, &pp))
+ return NULL;
+ FillCArc(&r,
+ startAngle,
+ arcAngle,
+ pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillCRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ PixPatHandle pp;
#ifndef FillCRgn
- PyMac_PRECHECK(FillCRgn);
+ PyMac_PRECHECK(FillCRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &rgn,
- ResObj_Convert, &pp))
- return NULL;
- FillCRgn(rgn,
- pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &rgn,
+ ResObj_Convert, &pp))
+ return NULL;
+ FillCRgn(rgn,
+ pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillCPoly(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PolyHandle poly;
- PixPatHandle pp;
+ PyObject *_res = NULL;
+ PolyHandle poly;
+ PixPatHandle pp;
#ifndef FillCPoly
- PyMac_PRECHECK(FillCPoly);
+ PyMac_PRECHECK(FillCPoly);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &poly,
- ResObj_Convert, &pp))
- return NULL;
- FillCPoly(poly,
- pp);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &poly,
+ ResObj_Convert, &pp))
+ return NULL;
+ FillCPoly(poly,
+ pp);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_RGBForeColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor color;
+ PyObject *_res = NULL;
+ RGBColor color;
#ifndef RGBForeColor
- PyMac_PRECHECK(RGBForeColor);
+ PyMac_PRECHECK(RGBForeColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &color))
- return NULL;
- RGBForeColor(&color);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &color))
+ return NULL;
+ RGBForeColor(&color);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_RGBBackColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor color;
+ PyObject *_res = NULL;
+ RGBColor color;
#ifndef RGBBackColor
- PyMac_PRECHECK(RGBBackColor);
+ PyMac_PRECHECK(RGBBackColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &color))
- return NULL;
- RGBBackColor(&color);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &color))
+ return NULL;
+ RGBBackColor(&color);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetCPixel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short h;
- short v;
- RGBColor cPix;
+ PyObject *_res = NULL;
+ short h;
+ short v;
+ RGBColor cPix;
#ifndef SetCPixel
- PyMac_PRECHECK(SetCPixel);
+ PyMac_PRECHECK(SetCPixel);
#endif
- if (!PyArg_ParseTuple(_args, "hhO&",
- &h,
- &v,
- QdRGB_Convert, &cPix))
- return NULL;
- SetCPixel(h,
- v,
- &cPix);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hhO&",
+ &h,
+ &v,
+ QdRGB_Convert, &cPix))
+ return NULL;
+ SetCPixel(h,
+ v,
+ &cPix);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetPortPix(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ PixMapHandle pm;
#ifndef SetPortPix
- PyMac_PRECHECK(SetPortPix);
+ PyMac_PRECHECK(SetPortPix);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- SetPortPix(pm);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ SetPortPix(pm);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetCPixel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short h;
- short v;
- RGBColor cPix;
+ PyObject *_res = NULL;
+ short h;
+ short v;
+ RGBColor cPix;
#ifndef GetCPixel
- PyMac_PRECHECK(GetCPixel);
+ PyMac_PRECHECK(GetCPixel);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- GetCPixel(h,
- v,
- &cPix);
- _res = Py_BuildValue("O&",
- QdRGB_New, &cPix);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ GetCPixel(h,
+ v,
+ &cPix);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &cPix);
+ return _res;
}
static PyObject *Qd_GetForeColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor color;
+ PyObject *_res = NULL;
+ RGBColor color;
#ifndef GetForeColor
- PyMac_PRECHECK(GetForeColor);
+ PyMac_PRECHECK(GetForeColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetForeColor(&color);
- _res = Py_BuildValue("O&",
- QdRGB_New, &color);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetForeColor(&color);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &color);
+ return _res;
}
static PyObject *Qd_GetBackColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor color;
+ PyObject *_res = NULL;
+ RGBColor color;
#ifndef GetBackColor
- PyMac_PRECHECK(GetBackColor);
+ PyMac_PRECHECK(GetBackColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetBackColor(&color);
- _res = Py_BuildValue("O&",
- QdRGB_New, &color);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetBackColor(&color);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &color);
+ return _res;
}
static PyObject *Qd_OpColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor color;
+ PyObject *_res = NULL;
+ RGBColor color;
#ifndef OpColor
- PyMac_PRECHECK(OpColor);
+ PyMac_PRECHECK(OpColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &color))
- return NULL;
- OpColor(&color);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &color))
+ return NULL;
+ OpColor(&color);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_HiliteColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor color;
+ PyObject *_res = NULL;
+ RGBColor color;
#ifndef HiliteColor
- PyMac_PRECHECK(HiliteColor);
+ PyMac_PRECHECK(HiliteColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &color))
- return NULL;
- HiliteColor(&color);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &color))
+ return NULL;
+ HiliteColor(&color);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DisposeCTable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CTabHandle cTable;
+ PyObject *_res = NULL;
+ CTabHandle cTable;
#ifndef DisposeCTable
- PyMac_PRECHECK(DisposeCTable);
+ PyMac_PRECHECK(DisposeCTable);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &cTable))
- return NULL;
- DisposeCTable(cTable);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &cTable))
+ return NULL;
+ DisposeCTable(cTable);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetCTable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CTabHandle _rv;
- short ctID;
+ PyObject *_res = NULL;
+ CTabHandle _rv;
+ short ctID;
#ifndef GetCTable
- PyMac_PRECHECK(GetCTable);
+ PyMac_PRECHECK(GetCTable);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &ctID))
- return NULL;
- _rv = GetCTable(ctID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &ctID))
+ return NULL;
+ _rv = GetCTable(ctID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_GetCCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CCrsrHandle _rv;
- short crsrID;
+ PyObject *_res = NULL;
+ CCrsrHandle _rv;
+ short crsrID;
#ifndef GetCCursor
- PyMac_PRECHECK(GetCCursor);
+ PyMac_PRECHECK(GetCCursor);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &crsrID))
- return NULL;
- _rv = GetCCursor(crsrID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &crsrID))
+ return NULL;
+ _rv = GetCCursor(crsrID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_SetCCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CCrsrHandle cCrsr;
+ PyObject *_res = NULL;
+ CCrsrHandle cCrsr;
#ifndef SetCCursor
- PyMac_PRECHECK(SetCCursor);
+ PyMac_PRECHECK(SetCCursor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &cCrsr))
- return NULL;
- SetCCursor(cCrsr);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &cCrsr))
+ return NULL;
+ SetCCursor(cCrsr);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_AllocCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef AllocCursor
- PyMac_PRECHECK(AllocCursor);
+ PyMac_PRECHECK(AllocCursor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- AllocCursor();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ AllocCursor();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DisposeCCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CCrsrHandle cCrsr;
+ PyObject *_res = NULL;
+ CCrsrHandle cCrsr;
#ifndef DisposeCCursor
- PyMac_PRECHECK(DisposeCCursor);
+ PyMac_PRECHECK(DisposeCCursor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &cCrsr))
- return NULL;
- DisposeCCursor(cCrsr);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &cCrsr))
+ return NULL;
+ DisposeCCursor(cCrsr);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetMaxDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
- Rect globalRect;
+ PyObject *_res = NULL;
+ GDHandle _rv;
+ Rect globalRect;
#ifndef GetMaxDevice
- PyMac_PRECHECK(GetMaxDevice);
+ PyMac_PRECHECK(GetMaxDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &globalRect))
- return NULL;
- _rv = GetMaxDevice(&globalRect);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &globalRect))
+ return NULL;
+ _rv = GetMaxDevice(&globalRect);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_GetCTSeed(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetCTSeed
- PyMac_PRECHECK(GetCTSeed);
+ PyMac_PRECHECK(GetCTSeed);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetCTSeed();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetCTSeed();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qd_GetDeviceList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef GetDeviceList
- PyMac_PRECHECK(GetDeviceList);
+ PyMac_PRECHECK(GetDeviceList);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetDeviceList();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetDeviceList();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_GetMainDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef GetMainDevice
- PyMac_PRECHECK(GetMainDevice);
+ PyMac_PRECHECK(GetMainDevice);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMainDevice();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMainDevice();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_GetNextDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
- GDHandle curDevice;
+ PyObject *_res = NULL;
+ GDHandle _rv;
+ GDHandle curDevice;
#ifndef GetNextDevice
- PyMac_PRECHECK(GetNextDevice);
+ PyMac_PRECHECK(GetNextDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &curDevice))
- return NULL;
- _rv = GetNextDevice(curDevice);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &curDevice))
+ return NULL;
+ _rv = GetNextDevice(curDevice);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_TestDeviceAttribute(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- GDHandle gdh;
- short attribute;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ GDHandle gdh;
+ short attribute;
#ifndef TestDeviceAttribute
- PyMac_PRECHECK(TestDeviceAttribute);
+ PyMac_PRECHECK(TestDeviceAttribute);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- ResObj_Convert, &gdh,
- &attribute))
- return NULL;
- _rv = TestDeviceAttribute(gdh,
- attribute);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ ResObj_Convert, &gdh,
+ &attribute))
+ return NULL;
+ _rv = TestDeviceAttribute(gdh,
+ attribute);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_SetDeviceAttribute(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle gdh;
- short attribute;
- Boolean value;
+ PyObject *_res = NULL;
+ GDHandle gdh;
+ short attribute;
+ Boolean value;
#ifndef SetDeviceAttribute
- PyMac_PRECHECK(SetDeviceAttribute);
+ PyMac_PRECHECK(SetDeviceAttribute);
#endif
- if (!PyArg_ParseTuple(_args, "O&hb",
- ResObj_Convert, &gdh,
- &attribute,
- &value))
- return NULL;
- SetDeviceAttribute(gdh,
- attribute,
- value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hb",
+ ResObj_Convert, &gdh,
+ &attribute,
+ &value))
+ return NULL;
+ SetDeviceAttribute(gdh,
+ attribute,
+ value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InitGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short qdRefNum;
- long mode;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ short qdRefNum;
+ long mode;
+ GDHandle gdh;
#ifndef InitGDevice
- PyMac_PRECHECK(InitGDevice);
+ PyMac_PRECHECK(InitGDevice);
#endif
- if (!PyArg_ParseTuple(_args, "hlO&",
- &qdRefNum,
- &mode,
- ResObj_Convert, &gdh))
- return NULL;
- InitGDevice(qdRefNum,
- mode,
- gdh);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &qdRefNum,
+ &mode,
+ ResObj_Convert, &gdh))
+ return NULL;
+ InitGDevice(qdRefNum,
+ mode,
+ gdh);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_NewGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
- short refNum;
- long mode;
+ PyObject *_res = NULL;
+ GDHandle _rv;
+ short refNum;
+ long mode;
#ifndef NewGDevice
- PyMac_PRECHECK(NewGDevice);
+ PyMac_PRECHECK(NewGDevice);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &refNum,
- &mode))
- return NULL;
- _rv = NewGDevice(refNum,
- mode);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &refNum,
+ &mode))
+ return NULL;
+ _rv = NewGDevice(refNum,
+ mode);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_DisposeGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ GDHandle gdh;
#ifndef DisposeGDevice
- PyMac_PRECHECK(DisposeGDevice);
+ PyMac_PRECHECK(DisposeGDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &gdh))
- return NULL;
- DisposeGDevice(gdh);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &gdh))
+ return NULL;
+ DisposeGDevice(gdh);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle gd;
+ PyObject *_res = NULL;
+ GDHandle gd;
#ifndef SetGDevice
- PyMac_PRECHECK(SetGDevice);
+ PyMac_PRECHECK(SetGDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &gd))
- return NULL;
- SetGDevice(gd);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &gd))
+ return NULL;
+ SetGDevice(gd);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef GetGDevice
- PyMac_PRECHECK(GetGDevice);
+ PyMac_PRECHECK(GetGDevice);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetGDevice();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetGDevice();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_Color2Index(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- RGBColor myColor;
+ PyObject *_res = NULL;
+ long _rv;
+ RGBColor myColor;
#ifndef Color2Index
- PyMac_PRECHECK(Color2Index);
+ PyMac_PRECHECK(Color2Index);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &myColor))
- return NULL;
- _rv = Color2Index(&myColor);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &myColor))
+ return NULL;
+ _rv = Color2Index(&myColor);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qd_Index2Color(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long index;
- RGBColor aColor;
+ PyObject *_res = NULL;
+ long index;
+ RGBColor aColor;
#ifndef Index2Color
- PyMac_PRECHECK(Index2Color);
+ PyMac_PRECHECK(Index2Color);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &index))
- return NULL;
- Index2Color(index,
- &aColor);
- _res = Py_BuildValue("O&",
- QdRGB_New, &aColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &index))
+ return NULL;
+ Index2Color(index,
+ &aColor);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &aColor);
+ return _res;
}
static PyObject *Qd_InvertColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor myColor;
+ PyObject *_res = NULL;
+ RGBColor myColor;
#ifndef InvertColor
- PyMac_PRECHECK(InvertColor);
+ PyMac_PRECHECK(InvertColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- InvertColor(&myColor);
- _res = Py_BuildValue("O&",
- QdRGB_New, &myColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ InvertColor(&myColor);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &myColor);
+ return _res;
}
static PyObject *Qd_RealColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- RGBColor color;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ RGBColor color;
#ifndef RealColor
- PyMac_PRECHECK(RealColor);
+ PyMac_PRECHECK(RealColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &color))
- return NULL;
- _rv = RealColor(&color);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &color))
+ return NULL;
+ _rv = RealColor(&color);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_GetSubTable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CTabHandle myColors;
- short iTabRes;
- CTabHandle targetTbl;
+ PyObject *_res = NULL;
+ CTabHandle myColors;
+ short iTabRes;
+ CTabHandle targetTbl;
#ifndef GetSubTable
- PyMac_PRECHECK(GetSubTable);
+ PyMac_PRECHECK(GetSubTable);
#endif
- if (!PyArg_ParseTuple(_args, "O&hO&",
- ResObj_Convert, &myColors,
- &iTabRes,
- ResObj_Convert, &targetTbl))
- return NULL;
- GetSubTable(myColors,
- iTabRes,
- targetTbl);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hO&",
+ ResObj_Convert, &myColors,
+ &iTabRes,
+ ResObj_Convert, &targetTbl))
+ return NULL;
+ GetSubTable(myColors,
+ iTabRes,
+ targetTbl);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MakeITable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CTabHandle cTabH;
- ITabHandle iTabH;
- short res;
+ PyObject *_res = NULL;
+ CTabHandle cTabH;
+ ITabHandle iTabH;
+ short res;
#ifndef MakeITable
- PyMac_PRECHECK(MakeITable);
+ PyMac_PRECHECK(MakeITable);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- ResObj_Convert, &cTabH,
- ResObj_Convert, &iTabH,
- &res))
- return NULL;
- MakeITable(cTabH,
- iTabH,
- res);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ ResObj_Convert, &cTabH,
+ ResObj_Convert, &iTabH,
+ &res))
+ return NULL;
+ MakeITable(cTabH,
+ iTabH,
+ res);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetClientID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short id;
+ PyObject *_res = NULL;
+ short id;
#ifndef SetClientID
- PyMac_PRECHECK(SetClientID);
+ PyMac_PRECHECK(SetClientID);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &id))
- return NULL;
- SetClientID(id);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &id))
+ return NULL;
+ SetClientID(id);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ProtectEntry(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short index;
- Boolean protect;
+ PyObject *_res = NULL;
+ short index;
+ Boolean protect;
#ifndef ProtectEntry
- PyMac_PRECHECK(ProtectEntry);
+ PyMac_PRECHECK(ProtectEntry);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &index,
- &protect))
- return NULL;
- ProtectEntry(index,
- protect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &index,
+ &protect))
+ return NULL;
+ ProtectEntry(index,
+ protect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ReserveEntry(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short index;
- Boolean reserve;
+ PyObject *_res = NULL;
+ short index;
+ Boolean reserve;
#ifndef ReserveEntry
- PyMac_PRECHECK(ReserveEntry);
+ PyMac_PRECHECK(ReserveEntry);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &index,
- &reserve))
- return NULL;
- ReserveEntry(index,
- reserve);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &index,
+ &reserve))
+ return NULL;
+ ReserveEntry(index,
+ reserve);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_QDError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef QDError
- PyMac_PRECHECK(QDError);
+ PyMac_PRECHECK(QDError);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = QDError();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = QDError();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_CopyDeepMask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- BitMapPtr srcBits;
- BitMapPtr maskBits;
- BitMapPtr dstBits;
- Rect srcRect;
- Rect maskRect;
- Rect dstRect;
- short mode;
- RgnHandle maskRgn;
+ PyObject *_res = NULL;
+ BitMapPtr srcBits;
+ BitMapPtr maskBits;
+ BitMapPtr dstBits;
+ Rect srcRect;
+ Rect maskRect;
+ Rect dstRect;
+ short mode;
+ RgnHandle maskRgn;
#ifndef CopyDeepMask
- PyMac_PRECHECK(CopyDeepMask);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&O&hO&",
- BMObj_Convert, &srcBits,
- BMObj_Convert, &maskBits,
- BMObj_Convert, &dstBits,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &maskRect,
- PyMac_GetRect, &dstRect,
- &mode,
- OptResObj_Convert, &maskRgn))
- return NULL;
- CopyDeepMask(srcBits,
- maskBits,
- dstBits,
- &srcRect,
- &maskRect,
- &dstRect,
- mode,
- maskRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CopyDeepMask);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&O&hO&",
+ BMObj_Convert, &srcBits,
+ BMObj_Convert, &maskBits,
+ BMObj_Convert, &dstBits,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &maskRect,
+ PyMac_GetRect, &dstRect,
+ &mode,
+ OptResObj_Convert, &maskRgn))
+ return NULL;
+ CopyDeepMask(srcBits,
+ maskBits,
+ dstBits,
+ &srcRect,
+ &maskRect,
+ &dstRect,
+ mode,
+ maskRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetPattern(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PatHandle _rv;
- short patternID;
+ PyObject *_res = NULL;
+ PatHandle _rv;
+ short patternID;
#ifndef GetPattern
- PyMac_PRECHECK(GetPattern);
+ PyMac_PRECHECK(GetPattern);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &patternID))
- return NULL;
- _rv = GetPattern(patternID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &patternID))
+ return NULL;
+ _rv = GetPattern(patternID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_MacGetCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CursHandle _rv;
- short cursorID;
+ PyObject *_res = NULL;
+ CursHandle _rv;
+ short cursorID;
#ifndef MacGetCursor
- PyMac_PRECHECK(MacGetCursor);
+ PyMac_PRECHECK(MacGetCursor);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &cursorID))
- return NULL;
- _rv = MacGetCursor(cursorID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &cursorID))
+ return NULL;
+ _rv = MacGetCursor(cursorID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_GetPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle _rv;
- short pictureID;
+ PyObject *_res = NULL;
+ PicHandle _rv;
+ short pictureID;
#ifndef GetPicture
- PyMac_PRECHECK(GetPicture);
+ PyMac_PRECHECK(GetPicture);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &pictureID))
- return NULL;
- _rv = GetPicture(pictureID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &pictureID))
+ return NULL;
+ _rv = GetPicture(pictureID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_DeltaPoint(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- Point ptA;
- Point ptB;
+ PyObject *_res = NULL;
+ long _rv;
+ Point ptA;
+ Point ptB;
#ifndef DeltaPoint
- PyMac_PRECHECK(DeltaPoint);
+ PyMac_PRECHECK(DeltaPoint);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &ptA,
- PyMac_GetPoint, &ptB))
- return NULL;
- _rv = DeltaPoint(ptA,
- ptB);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &ptA,
+ PyMac_GetPoint, &ptB))
+ return NULL;
+ _rv = DeltaPoint(ptA,
+ ptB);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qd_ShieldCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect shieldRect;
- Point offsetPt;
+ PyObject *_res = NULL;
+ Rect shieldRect;
+ Point offsetPt;
#ifndef ShieldCursor
- PyMac_PRECHECK(ShieldCursor);
+ PyMac_PRECHECK(ShieldCursor);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &shieldRect,
- PyMac_GetPoint, &offsetPt))
- return NULL;
- ShieldCursor(&shieldRect,
- offsetPt);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &shieldRect,
+ PyMac_GetPoint, &offsetPt))
+ return NULL;
+ ShieldCursor(&shieldRect,
+ offsetPt);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_ScreenRes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short scrnHRes;
- short scrnVRes;
+ PyObject *_res = NULL;
+ short scrnHRes;
+ short scrnVRes;
#ifndef ScreenRes
- PyMac_PRECHECK(ScreenRes);
+ PyMac_PRECHECK(ScreenRes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ScreenRes(&scrnHRes,
- &scrnVRes);
- _res = Py_BuildValue("hh",
- scrnHRes,
- scrnVRes);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ScreenRes(&scrnHRes,
+ &scrnVRes);
+ _res = Py_BuildValue("hh",
+ scrnHRes,
+ scrnVRes);
+ return _res;
}
static PyObject *Qd_GetIndPattern(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern thePat__out__;
- short patternListID;
- short index;
+ PyObject *_res = NULL;
+ Pattern thePat__out__;
+ short patternListID;
+ short index;
#ifndef GetIndPattern
- PyMac_PRECHECK(GetIndPattern);
+ PyMac_PRECHECK(GetIndPattern);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &patternListID,
- &index))
- return NULL;
- GetIndPattern(&thePat__out__,
- patternListID,
- index);
- _res = Py_BuildValue("s#",
- (char *)&thePat__out__, (int)sizeof(Pattern));
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &patternListID,
+ &index))
+ return NULL;
+ GetIndPattern(&thePat__out__,
+ patternListID,
+ index);
+ _res = Py_BuildValue("s#",
+ (char *)&thePat__out__, (int)sizeof(Pattern));
+ return _res;
}
static PyObject *Qd_SlopeFromAngle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- short angle;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ short angle;
#ifndef SlopeFromAngle
- PyMac_PRECHECK(SlopeFromAngle);
+ PyMac_PRECHECK(SlopeFromAngle);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &angle))
- return NULL;
- _rv = SlopeFromAngle(angle);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &angle))
+ return NULL;
+ _rv = SlopeFromAngle(angle);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qd_AngleFromSlope(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- Fixed slope;
+ PyObject *_res = NULL;
+ short _rv;
+ Fixed slope;
#ifndef AngleFromSlope
- PyMac_PRECHECK(AngleFromSlope);
+ PyMac_PRECHECK(AngleFromSlope);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &slope))
- return NULL;
- _rv = AngleFromSlope(slope);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &slope))
+ return NULL;
+ _rv = AngleFromSlope(slope);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_GetPixBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pixMap;
- Rect bounds;
+ PyObject *_res = NULL;
+ PixMapHandle pixMap;
+ Rect bounds;
#ifndef GetPixBounds
- PyMac_PRECHECK(GetPixBounds);
+ PyMac_PRECHECK(GetPixBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pixMap))
- return NULL;
- GetPixBounds(pixMap,
- &bounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pixMap))
+ return NULL;
+ GetPixBounds(pixMap,
+ &bounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *Qd_GetPixDepth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- PixMapHandle pixMap;
+ PyObject *_res = NULL;
+ short _rv;
+ PixMapHandle pixMap;
#ifndef GetPixDepth
- PyMac_PRECHECK(GetPixDepth);
+ PyMac_PRECHECK(GetPixDepth);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pixMap))
- return NULL;
- _rv = GetPixDepth(pixMap);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pixMap))
+ return NULL;
+ _rv = GetPixDepth(pixMap);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_GetQDGlobalsRandomSeed(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetQDGlobalsRandomSeed
- PyMac_PRECHECK(GetQDGlobalsRandomSeed);
+ PyMac_PRECHECK(GetQDGlobalsRandomSeed);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetQDGlobalsRandomSeed();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetQDGlobalsRandomSeed();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qd_GetQDGlobalsScreenBits(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- BitMap screenBits;
+ PyObject *_res = NULL;
+ BitMap screenBits;
#ifndef GetQDGlobalsScreenBits
- PyMac_PRECHECK(GetQDGlobalsScreenBits);
+ PyMac_PRECHECK(GetQDGlobalsScreenBits);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsScreenBits(&screenBits);
- _res = Py_BuildValue("O&",
- BMObj_NewCopied, &screenBits);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsScreenBits(&screenBits);
+ _res = Py_BuildValue("O&",
+ BMObj_NewCopied, &screenBits);
+ return _res;
}
static PyObject *Qd_GetQDGlobalsArrow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Cursor arrow__out__;
+ PyObject *_res = NULL;
+ Cursor arrow__out__;
#ifndef GetQDGlobalsArrow
- PyMac_PRECHECK(GetQDGlobalsArrow);
+ PyMac_PRECHECK(GetQDGlobalsArrow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsArrow(&arrow__out__);
- _res = Py_BuildValue("s#",
- (char *)&arrow__out__, (int)sizeof(Cursor));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsArrow(&arrow__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&arrow__out__, (int)sizeof(Cursor));
+ return _res;
}
static PyObject *Qd_GetQDGlobalsDarkGray(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern dkGray__out__;
+ PyObject *_res = NULL;
+ Pattern dkGray__out__;
#ifndef GetQDGlobalsDarkGray
- PyMac_PRECHECK(GetQDGlobalsDarkGray);
+ PyMac_PRECHECK(GetQDGlobalsDarkGray);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsDarkGray(&dkGray__out__);
- _res = Py_BuildValue("s#",
- (char *)&dkGray__out__, (int)sizeof(Pattern));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsDarkGray(&dkGray__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&dkGray__out__, (int)sizeof(Pattern));
+ return _res;
}
static PyObject *Qd_GetQDGlobalsLightGray(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern ltGray__out__;
+ PyObject *_res = NULL;
+ Pattern ltGray__out__;
#ifndef GetQDGlobalsLightGray
- PyMac_PRECHECK(GetQDGlobalsLightGray);
+ PyMac_PRECHECK(GetQDGlobalsLightGray);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsLightGray(&ltGray__out__);
- _res = Py_BuildValue("s#",
- (char *)&ltGray__out__, (int)sizeof(Pattern));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsLightGray(&ltGray__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&ltGray__out__, (int)sizeof(Pattern));
+ return _res;
}
static PyObject *Qd_GetQDGlobalsGray(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern gray__out__;
+ PyObject *_res = NULL;
+ Pattern gray__out__;
#ifndef GetQDGlobalsGray
- PyMac_PRECHECK(GetQDGlobalsGray);
+ PyMac_PRECHECK(GetQDGlobalsGray);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsGray(&gray__out__);
- _res = Py_BuildValue("s#",
- (char *)&gray__out__, (int)sizeof(Pattern));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsGray(&gray__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&gray__out__, (int)sizeof(Pattern));
+ return _res;
}
static PyObject *Qd_GetQDGlobalsBlack(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern black__out__;
+ PyObject *_res = NULL;
+ Pattern black__out__;
#ifndef GetQDGlobalsBlack
- PyMac_PRECHECK(GetQDGlobalsBlack);
+ PyMac_PRECHECK(GetQDGlobalsBlack);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsBlack(&black__out__);
- _res = Py_BuildValue("s#",
- (char *)&black__out__, (int)sizeof(Pattern));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsBlack(&black__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&black__out__, (int)sizeof(Pattern));
+ return _res;
}
static PyObject *Qd_GetQDGlobalsWhite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Pattern white__out__;
+ PyObject *_res = NULL;
+ Pattern white__out__;
#ifndef GetQDGlobalsWhite
- PyMac_PRECHECK(GetQDGlobalsWhite);
+ PyMac_PRECHECK(GetQDGlobalsWhite);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetQDGlobalsWhite(&white__out__);
- _res = Py_BuildValue("s#",
- (char *)&white__out__, (int)sizeof(Pattern));
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetQDGlobalsWhite(&white__out__);
+ _res = Py_BuildValue("s#",
+ (char *)&white__out__, (int)sizeof(Pattern));
+ return _res;
}
static PyObject *Qd_GetQDGlobalsThePort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
#ifndef GetQDGlobalsThePort
- PyMac_PRECHECK(GetQDGlobalsThePort);
+ PyMac_PRECHECK(GetQDGlobalsThePort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetQDGlobalsThePort();
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetQDGlobalsThePort();
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyObject *Qd_SetQDGlobalsRandomSeed(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long randomSeed;
+ PyObject *_res = NULL;
+ long randomSeed;
#ifndef SetQDGlobalsRandomSeed
- PyMac_PRECHECK(SetQDGlobalsRandomSeed);
+ PyMac_PRECHECK(SetQDGlobalsRandomSeed);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &randomSeed))
- return NULL;
- SetQDGlobalsRandomSeed(randomSeed);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &randomSeed))
+ return NULL;
+ SetQDGlobalsRandomSeed(randomSeed);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetQDGlobalsArrow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Cursor *arrow__in__;
- int arrow__in_len__;
+ PyObject *_res = NULL;
+ Cursor *arrow__in__;
+ int arrow__in_len__;
#ifndef SetQDGlobalsArrow
- PyMac_PRECHECK(SetQDGlobalsArrow);
-#endif
- if (!PyArg_ParseTuple(_args, "s#",
- (char **)&arrow__in__, &arrow__in_len__))
- return NULL;
- if (arrow__in_len__ != sizeof(Cursor))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Cursor)");
- goto arrow__error__;
- }
- SetQDGlobalsArrow(arrow__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(SetQDGlobalsArrow);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#",
+ (char **)&arrow__in__, &arrow__in_len__))
+ return NULL;
+ if (arrow__in_len__ != sizeof(Cursor))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Cursor)");
+ goto arrow__error__;
+ }
+ SetQDGlobalsArrow(arrow__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
arrow__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_GetRegionBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle region;
- Rect bounds;
+ PyObject *_res = NULL;
+ RgnHandle region;
+ Rect bounds;
#ifndef GetRegionBounds
- PyMac_PRECHECK(GetRegionBounds);
+ PyMac_PRECHECK(GetRegionBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- GetRegionBounds(region,
- &bounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ GetRegionBounds(region,
+ &bounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *Qd_IsRegionRectangular(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- RgnHandle region;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ RgnHandle region;
#ifndef IsRegionRectangular
- PyMac_PRECHECK(IsRegionRectangular);
+ PyMac_PRECHECK(IsRegionRectangular);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- _rv = IsRegionRectangular(region);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ _rv = IsRegionRectangular(region);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_CreateNewPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
#ifndef CreateNewPort
- PyMac_PRECHECK(CreateNewPort);
+ PyMac_PRECHECK(CreateNewPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CreateNewPort();
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CreateNewPort();
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyObject *Qd_SetQDError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr err;
+ PyObject *_res = NULL;
+ OSErr err;
#ifndef SetQDError
- PyMac_PRECHECK(SetQDError);
+ PyMac_PRECHECK(SetQDError);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &err))
- return NULL;
- SetQDError(err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &err))
+ return NULL;
+ SetQDError(err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetScrVRes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef LMGetScrVRes
- PyMac_PRECHECK(LMGetScrVRes);
+ PyMac_PRECHECK(LMGetScrVRes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetScrVRes();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetScrVRes();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_LMSetScrVRes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 value;
+ PyObject *_res = NULL;
+ SInt16 value;
#ifndef LMSetScrVRes
- PyMac_PRECHECK(LMSetScrVRes);
+ PyMac_PRECHECK(LMSetScrVRes);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &value))
- return NULL;
- LMSetScrVRes(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &value))
+ return NULL;
+ LMSetScrVRes(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetScrHRes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 _rv;
+ PyObject *_res = NULL;
+ SInt16 _rv;
#ifndef LMGetScrHRes
- PyMac_PRECHECK(LMGetScrHRes);
+ PyMac_PRECHECK(LMGetScrHRes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetScrHRes();
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetScrHRes();
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_LMSetScrHRes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt16 value;
+ PyObject *_res = NULL;
+ SInt16 value;
#ifndef LMSetScrHRes
- PyMac_PRECHECK(LMSetScrHRes);
+ PyMac_PRECHECK(LMSetScrHRes);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &value))
- return NULL;
- LMSetScrHRes(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &value))
+ return NULL;
+ LMSetScrHRes(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetMainDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef LMGetMainDevice
- PyMac_PRECHECK(LMGetMainDevice);
+ PyMac_PRECHECK(LMGetMainDevice);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetMainDevice();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetMainDevice();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetMainDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle value;
+ PyObject *_res = NULL;
+ GDHandle value;
#ifndef LMSetMainDevice
- PyMac_PRECHECK(LMSetMainDevice);
+ PyMac_PRECHECK(LMSetMainDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetMainDevice(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetMainDevice(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetDeviceList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef LMGetDeviceList
- PyMac_PRECHECK(LMGetDeviceList);
+ PyMac_PRECHECK(LMGetDeviceList);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetDeviceList();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetDeviceList();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetDeviceList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle value;
+ PyObject *_res = NULL;
+ GDHandle value;
#ifndef LMSetDeviceList
- PyMac_PRECHECK(LMSetDeviceList);
+ PyMac_PRECHECK(LMSetDeviceList);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetDeviceList(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetDeviceList(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetQDColors(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef LMGetQDColors
- PyMac_PRECHECK(LMGetQDColors);
+ PyMac_PRECHECK(LMGetQDColors);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetQDColors();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetQDColors();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetQDColors(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle value;
+ PyObject *_res = NULL;
+ Handle value;
#ifndef LMSetQDColors
- PyMac_PRECHECK(LMSetQDColors);
+ PyMac_PRECHECK(LMSetQDColors);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetQDColors(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetQDColors(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetWidthListHand(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef LMGetWidthListHand
- PyMac_PRECHECK(LMGetWidthListHand);
+ PyMac_PRECHECK(LMGetWidthListHand);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetWidthListHand();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetWidthListHand();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetWidthListHand(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle value;
+ PyObject *_res = NULL;
+ Handle value;
#ifndef LMSetWidthListHand
- PyMac_PRECHECK(LMSetWidthListHand);
+ PyMac_PRECHECK(LMSetWidthListHand);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetWidthListHand(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetWidthListHand(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetHiliteMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt8 _rv;
+ PyObject *_res = NULL;
+ UInt8 _rv;
#ifndef LMGetHiliteMode
- PyMac_PRECHECK(LMGetHiliteMode);
+ PyMac_PRECHECK(LMGetHiliteMode);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetHiliteMode();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetHiliteMode();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_LMSetHiliteMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt8 value;
+ PyObject *_res = NULL;
+ UInt8 value;
#ifndef LMSetHiliteMode
- PyMac_PRECHECK(LMSetHiliteMode);
+ PyMac_PRECHECK(LMSetHiliteMode);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &value))
- return NULL;
- LMSetHiliteMode(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &value))
+ return NULL;
+ LMSetHiliteMode(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetWidthTabHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef LMGetWidthTabHandle
- PyMac_PRECHECK(LMGetWidthTabHandle);
+ PyMac_PRECHECK(LMGetWidthTabHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetWidthTabHandle();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetWidthTabHandle();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetWidthTabHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle value;
+ PyObject *_res = NULL;
+ Handle value;
#ifndef LMSetWidthTabHandle
- PyMac_PRECHECK(LMSetWidthTabHandle);
+ PyMac_PRECHECK(LMSetWidthTabHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetWidthTabHandle(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetWidthTabHandle(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetLastSPExtra(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 _rv;
+ PyObject *_res = NULL;
+ SInt32 _rv;
#ifndef LMGetLastSPExtra
- PyMac_PRECHECK(LMGetLastSPExtra);
+ PyMac_PRECHECK(LMGetLastSPExtra);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetLastSPExtra();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetLastSPExtra();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qd_LMSetLastSPExtra(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- SInt32 value;
+ PyObject *_res = NULL;
+ SInt32 value;
#ifndef LMSetLastSPExtra
- PyMac_PRECHECK(LMSetLastSPExtra);
+ PyMac_PRECHECK(LMSetLastSPExtra);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &value))
- return NULL;
- LMSetLastSPExtra(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &value))
+ return NULL;
+ LMSetLastSPExtra(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetLastFOND(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef LMGetLastFOND
- PyMac_PRECHECK(LMGetLastFOND);
+ PyMac_PRECHECK(LMGetLastFOND);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetLastFOND();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetLastFOND();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetLastFOND(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle value;
+ PyObject *_res = NULL;
+ Handle value;
#ifndef LMSetLastFOND
- PyMac_PRECHECK(LMSetLastFOND);
+ PyMac_PRECHECK(LMSetLastFOND);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetLastFOND(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetLastFOND(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetFractEnable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt8 _rv;
+ PyObject *_res = NULL;
+ UInt8 _rv;
#ifndef LMGetFractEnable
- PyMac_PRECHECK(LMGetFractEnable);
+ PyMac_PRECHECK(LMGetFractEnable);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetFractEnable();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetFractEnable();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_LMSetFractEnable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt8 value;
+ PyObject *_res = NULL;
+ UInt8 value;
#ifndef LMSetFractEnable
- PyMac_PRECHECK(LMSetFractEnable);
+ PyMac_PRECHECK(LMSetFractEnable);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &value))
- return NULL;
- LMSetFractEnable(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &value))
+ return NULL;
+ LMSetFractEnable(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetTheGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef LMGetTheGDevice
- PyMac_PRECHECK(LMGetTheGDevice);
+ PyMac_PRECHECK(LMGetTheGDevice);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetTheGDevice();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetTheGDevice();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_LMSetTheGDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle value;
+ PyObject *_res = NULL;
+ GDHandle value;
#ifndef LMSetTheGDevice
- PyMac_PRECHECK(LMSetTheGDevice);
+ PyMac_PRECHECK(LMSetTheGDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- LMSetTheGDevice(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ LMSetTheGDevice(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetHiliteRGB(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor hiliteRGBValue;
+ PyObject *_res = NULL;
+ RGBColor hiliteRGBValue;
#ifndef LMGetHiliteRGB
- PyMac_PRECHECK(LMGetHiliteRGB);
+ PyMac_PRECHECK(LMGetHiliteRGB);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- LMGetHiliteRGB(&hiliteRGBValue);
- _res = Py_BuildValue("O&",
- QdRGB_New, &hiliteRGBValue);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ LMGetHiliteRGB(&hiliteRGBValue);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &hiliteRGBValue);
+ return _res;
}
static PyObject *Qd_LMSetHiliteRGB(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RGBColor hiliteRGBValue;
+ PyObject *_res = NULL;
+ RGBColor hiliteRGBValue;
#ifndef LMSetHiliteRGB
- PyMac_PRECHECK(LMSetHiliteRGB);
+ PyMac_PRECHECK(LMSetHiliteRGB);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &hiliteRGBValue))
- return NULL;
- LMSetHiliteRGB(&hiliteRGBValue);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &hiliteRGBValue))
+ return NULL;
+ LMSetHiliteRGB(&hiliteRGBValue);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LMGetCursorNew(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef LMGetCursorNew
- PyMac_PRECHECK(LMGetCursorNew);
+ PyMac_PRECHECK(LMGetCursorNew);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetCursorNew();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetCursorNew();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_LMSetCursorNew(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean value;
+ PyObject *_res = NULL;
+ Boolean value;
#ifndef LMSetCursorNew
- PyMac_PRECHECK(LMSetCursorNew);
+ PyMac_PRECHECK(LMSetCursorNew);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &value))
- return NULL;
- LMSetCursorNew(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &value))
+ return NULL;
+ LMSetCursorNew(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_TextFont(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short font;
+ PyObject *_res = NULL;
+ short font;
#ifndef TextFont
- PyMac_PRECHECK(TextFont);
+ PyMac_PRECHECK(TextFont);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &font))
- return NULL;
- TextFont(font);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &font))
+ return NULL;
+ TextFont(font);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_TextFace(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- StyleParameter face;
+ PyObject *_res = NULL;
+ StyleParameter face;
#ifndef TextFace
- PyMac_PRECHECK(TextFace);
+ PyMac_PRECHECK(TextFace);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &face))
- return NULL;
- TextFace(face);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &face))
+ return NULL;
+ TextFace(face);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_TextMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short mode;
+ PyObject *_res = NULL;
+ short mode;
#ifndef TextMode
- PyMac_PRECHECK(TextMode);
+ PyMac_PRECHECK(TextMode);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &mode))
- return NULL;
- TextMode(mode);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &mode))
+ return NULL;
+ TextMode(mode);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_TextSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short size;
+ PyObject *_res = NULL;
+ short size;
#ifndef TextSize
- PyMac_PRECHECK(TextSize);
+ PyMac_PRECHECK(TextSize);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &size))
- return NULL;
- TextSize(size);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &size))
+ return NULL;
+ TextSize(size);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SpaceExtra(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed extra;
+ PyObject *_res = NULL;
+ Fixed extra;
#ifndef SpaceExtra
- PyMac_PRECHECK(SpaceExtra);
+ PyMac_PRECHECK(SpaceExtra);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &extra))
- return NULL;
- SpaceExtra(extra);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &extra))
+ return NULL;
+ SpaceExtra(extra);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DrawChar(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CharParameter ch;
+ PyObject *_res = NULL;
+ CharParameter ch;
#ifndef DrawChar
- PyMac_PRECHECK(DrawChar);
+ PyMac_PRECHECK(DrawChar);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &ch))
- return NULL;
- DrawChar(ch);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &ch))
+ return NULL;
+ DrawChar(ch);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_DrawString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 s;
+ PyObject *_res = NULL;
+ Str255 s;
#ifndef DrawString
- PyMac_PRECHECK(DrawString);
+ PyMac_PRECHECK(DrawString);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, s))
- return NULL;
- DrawString(s);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, s))
+ return NULL;
+ DrawString(s);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_MacDrawText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *textBuf__in__;
- int textBuf__in_len__;
- short firstByte;
- short byteCount;
+ PyObject *_res = NULL;
+ char *textBuf__in__;
+ int textBuf__in_len__;
+ short firstByte;
+ short byteCount;
#ifndef MacDrawText
- PyMac_PRECHECK(MacDrawText);
-#endif
- if (!PyArg_ParseTuple(_args, "s#hh",
- &textBuf__in__, &textBuf__in_len__,
- &firstByte,
- &byteCount))
- return NULL;
- /* Fool compiler warnings */
- textBuf__in_len__ = textBuf__in_len__;
- MacDrawText(textBuf__in__,
- firstByte,
- byteCount);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(MacDrawText);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#hh",
+ &textBuf__in__, &textBuf__in_len__,
+ &firstByte,
+ &byteCount))
+ return NULL;
+ /* Fool compiler warnings */
+ textBuf__in_len__ = textBuf__in_len__;
+ MacDrawText(textBuf__in__,
+ firstByte,
+ byteCount);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_CharWidth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- CharParameter ch;
+ PyObject *_res = NULL;
+ short _rv;
+ CharParameter ch;
#ifndef CharWidth
- PyMac_PRECHECK(CharWidth);
+ PyMac_PRECHECK(CharWidth);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &ch))
- return NULL;
- _rv = CharWidth(ch);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &ch))
+ return NULL;
+ _rv = CharWidth(ch);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_StringWidth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- Str255 s;
+ PyObject *_res = NULL;
+ short _rv;
+ Str255 s;
#ifndef StringWidth
- PyMac_PRECHECK(StringWidth);
+ PyMac_PRECHECK(StringWidth);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, s))
- return NULL;
- _rv = StringWidth(s);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, s))
+ return NULL;
+ _rv = StringWidth(s);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_TextWidth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- char *textBuf__in__;
- int textBuf__in_len__;
- short firstByte;
- short byteCount;
+ PyObject *_res = NULL;
+ short _rv;
+ char *textBuf__in__;
+ int textBuf__in_len__;
+ short firstByte;
+ short byteCount;
#ifndef TextWidth
- PyMac_PRECHECK(TextWidth);
-#endif
- if (!PyArg_ParseTuple(_args, "s#hh",
- &textBuf__in__, &textBuf__in_len__,
- &firstByte,
- &byteCount))
- return NULL;
- /* Fool compiler warnings */
- textBuf__in_len__ = textBuf__in_len__;
- _rv = TextWidth(textBuf__in__,
- firstByte,
- byteCount);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ PyMac_PRECHECK(TextWidth);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#hh",
+ &textBuf__in__, &textBuf__in_len__,
+ &firstByte,
+ &byteCount))
+ return NULL;
+ /* Fool compiler warnings */
+ textBuf__in_len__ = textBuf__in_len__;
+ _rv = TextWidth(textBuf__in__,
+ firstByte,
+ byteCount);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_GetFontInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- FontInfo info;
+ PyObject *_res = NULL;
+ FontInfo info;
#ifndef GetFontInfo
- PyMac_PRECHECK(GetFontInfo);
+ PyMac_PRECHECK(GetFontInfo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetFontInfo(&info);
- _res = Py_BuildValue("O&",
- QdFI_New, &info);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetFontInfo(&info);
+ _res = Py_BuildValue("O&",
+ QdFI_New, &info);
+ return _res;
}
static PyObject *Qd_CharExtra(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed extra;
+ PyObject *_res = NULL;
+ Fixed extra;
#ifndef CharExtra
- PyMac_PRECHECK(CharExtra);
+ PyMac_PRECHECK(CharExtra);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &extra))
- return NULL;
- CharExtra(extra);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &extra))
+ return NULL;
+ CharExtra(extra);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_TruncString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- short width;
- Str255 theString;
- TruncCode truncWhere;
+ PyObject *_res = NULL;
+ short _rv;
+ short width;
+ Str255 theString;
+ TruncCode truncWhere;
#ifndef TruncString
- PyMac_PRECHECK(TruncString);
+ PyMac_PRECHECK(TruncString);
#endif
- if (!PyArg_ParseTuple(_args, "hO&h",
- &width,
- PyMac_GetStr255, theString,
- &truncWhere))
- return NULL;
- _rv = TruncString(width,
- theString,
- truncWhere);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&h",
+ &width,
+ PyMac_GetStr255, theString,
+ &truncWhere))
+ return NULL;
+ _rv = TruncString(width,
+ theString,
+ truncWhere);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qd_SetPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GrafPtr thePort;
+ PyObject *_res = NULL;
+ GrafPtr thePort;
#ifndef SetPort
- PyMac_PRECHECK(SetPort);
+ PyMac_PRECHECK(SetPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &thePort))
- return NULL;
- SetPort(thePort);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &thePort))
+ return NULL;
+ SetPort(thePort);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_GetCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CursHandle _rv;
- short cursorID;
+ PyObject *_res = NULL;
+ CursHandle _rv;
+ short cursorID;
#ifndef GetCursor
- PyMac_PRECHECK(GetCursor);
+ PyMac_PRECHECK(GetCursor);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &cursorID))
- return NULL;
- _rv = GetCursor(cursorID);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &cursorID))
+ return NULL;
+ _rv = GetCursor(cursorID);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Qd_SetCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Cursor *crsr__in__;
- int crsr__in_len__;
+ PyObject *_res = NULL;
+ Cursor *crsr__in__;
+ int crsr__in_len__;
#ifndef SetCursor
- PyMac_PRECHECK(SetCursor);
-#endif
- if (!PyArg_ParseTuple(_args, "s#",
- (char **)&crsr__in__, &crsr__in_len__))
- return NULL;
- if (crsr__in_len__ != sizeof(Cursor))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Cursor)");
- goto crsr__error__;
- }
- SetCursor(crsr__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(SetCursor);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#",
+ (char **)&crsr__in__, &crsr__in_len__))
+ return NULL;
+ if (crsr__in_len__ != sizeof(Cursor))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Cursor)");
+ goto crsr__error__;
+ }
+ SetCursor(crsr__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
crsr__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_ShowCursor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ShowCursor
- PyMac_PRECHECK(ShowCursor);
+ PyMac_PRECHECK(ShowCursor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ShowCursor();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ShowCursor();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_LineTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short h;
- short v;
+ PyObject *_res = NULL;
+ short h;
+ short v;
#ifndef LineTo
- PyMac_PRECHECK(LineTo);
+ PyMac_PRECHECK(LineTo);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- LineTo(h,
- v);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ LineTo(h,
+ v);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short left;
- short top;
- short right;
- short bottom;
+ PyObject *_res = NULL;
+ Rect r;
+ short left;
+ short top;
+ short right;
+ short bottom;
#ifndef SetRect
- PyMac_PRECHECK(SetRect);
-#endif
- if (!PyArg_ParseTuple(_args, "hhhh",
- &left,
- &top,
- &right,
- &bottom))
- return NULL;
- SetRect(&r,
- left,
- top,
- right,
- bottom);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ PyMac_PRECHECK(SetRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhhh",
+ &left,
+ &top,
+ &right,
+ &bottom))
+ return NULL;
+ SetRect(&r,
+ left,
+ top,
+ right,
+ bottom);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_OffsetRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ Rect r;
+ short dh;
+ short dv;
#ifndef OffsetRect
- PyMac_PRECHECK(OffsetRect);
+ PyMac_PRECHECK(OffsetRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &dh,
- &dv))
- return NULL;
- OffsetRect(&r,
- dh,
- dv);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &dh,
+ &dv))
+ return NULL;
+ OffsetRect(&r,
+ dh,
+ dv);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_InsetRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ Rect r;
+ short dh;
+ short dv;
#ifndef InsetRect
- PyMac_PRECHECK(InsetRect);
+ PyMac_PRECHECK(InsetRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- PyMac_GetRect, &r,
- &dh,
- &dv))
- return NULL;
- InsetRect(&r,
- dh,
- dv);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ PyMac_GetRect, &r,
+ &dh,
+ &dv))
+ return NULL;
+ InsetRect(&r,
+ dh,
+ dv);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qd_UnionRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect src1;
- Rect src2;
- Rect dstRect;
+ PyObject *_res = NULL;
+ Rect src1;
+ Rect src2;
+ Rect dstRect;
#ifndef UnionRect
- PyMac_PRECHECK(UnionRect);
+ PyMac_PRECHECK(UnionRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &src1,
- PyMac_GetRect, &src2))
- return NULL;
- UnionRect(&src1,
- &src2,
- &dstRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &dstRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &src1,
+ PyMac_GetRect, &src2))
+ return NULL;
+ UnionRect(&src1,
+ &src2,
+ &dstRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &dstRect);
+ return _res;
}
static PyObject *Qd_EqualRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Rect rect1;
- Rect rect2;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Rect rect1;
+ Rect rect2;
#ifndef EqualRect
- PyMac_PRECHECK(EqualRect);
+ PyMac_PRECHECK(EqualRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &rect1,
- PyMac_GetRect, &rect2))
- return NULL;
- _rv = EqualRect(&rect1,
- &rect2);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &rect1,
+ PyMac_GetRect, &rect2))
+ return NULL;
+ _rv = EqualRect(&rect1,
+ &rect2);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_FrameRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef FrameRect
- PyMac_PRECHECK(FrameRect);
+ PyMac_PRECHECK(FrameRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- FrameRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ FrameRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InvertRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
+ PyObject *_res = NULL;
+ Rect r;
#ifndef InvertRect
- PyMac_PRECHECK(InvertRect);
+ PyMac_PRECHECK(InvertRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &r))
- return NULL;
- InvertRect(&r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &r))
+ return NULL;
+ InvertRect(&r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect r;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ Rect r;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef FillRect
- PyMac_PRECHECK(FillRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- PyMac_GetRect, &r,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- FillRect(&r,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(FillRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ PyMac_GetRect, &r,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ FillRect(&r,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_CopyRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgn;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgn;
+ RgnHandle dstRgn;
#ifndef CopyRgn
- PyMac_PRECHECK(CopyRgn);
+ PyMac_PRECHECK(CopyRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &srcRgn,
- ResObj_Convert, &dstRgn))
- return NULL;
- CopyRgn(srcRgn,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &srcRgn,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ CopyRgn(srcRgn,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_SetRectRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- short left;
- short top;
- short right;
- short bottom;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ short left;
+ short top;
+ short right;
+ short bottom;
#ifndef SetRectRgn
- PyMac_PRECHECK(SetRectRgn);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhhh",
- ResObj_Convert, &rgn,
- &left,
- &top,
- &right,
- &bottom))
- return NULL;
- SetRectRgn(rgn,
- left,
- top,
- right,
- bottom);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetRectRgn);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhhh",
+ ResObj_Convert, &rgn,
+ &left,
+ &top,
+ &right,
+ &bottom))
+ return NULL;
+ SetRectRgn(rgn,
+ left,
+ top,
+ right,
+ bottom);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_OffsetRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ short dh;
+ short dv;
#ifndef OffsetRgn
- PyMac_PRECHECK(OffsetRgn);
+ PyMac_PRECHECK(OffsetRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- ResObj_Convert, &rgn,
- &dh,
- &dv))
- return NULL;
- OffsetRgn(rgn,
- dh,
- dv);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ ResObj_Convert, &rgn,
+ &dh,
+ &dv))
+ return NULL;
+ OffsetRgn(rgn,
+ dh,
+ dv);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_UnionRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgnA;
- RgnHandle srcRgnB;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgnA;
+ RgnHandle srcRgnB;
+ RgnHandle dstRgn;
#ifndef UnionRgn
- PyMac_PRECHECK(UnionRgn);
+ PyMac_PRECHECK(UnionRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &srcRgnA,
- ResObj_Convert, &srcRgnB,
- ResObj_Convert, &dstRgn))
- return NULL;
- UnionRgn(srcRgnA,
- srcRgnB,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &srcRgnA,
+ ResObj_Convert, &srcRgnB,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ UnionRgn(srcRgnA,
+ srcRgnB,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_XorRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle srcRgnA;
- RgnHandle srcRgnB;
- RgnHandle dstRgn;
+ PyObject *_res = NULL;
+ RgnHandle srcRgnA;
+ RgnHandle srcRgnB;
+ RgnHandle dstRgn;
#ifndef XorRgn
- PyMac_PRECHECK(XorRgn);
+ PyMac_PRECHECK(XorRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &srcRgnA,
- ResObj_Convert, &srcRgnB,
- ResObj_Convert, &dstRgn))
- return NULL;
- XorRgn(srcRgnA,
- srcRgnB,
- dstRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &srcRgnA,
+ ResObj_Convert, &srcRgnB,
+ ResObj_Convert, &dstRgn))
+ return NULL;
+ XorRgn(srcRgnA,
+ srcRgnB,
+ dstRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_EqualRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- RgnHandle rgnA;
- RgnHandle rgnB;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ RgnHandle rgnA;
+ RgnHandle rgnB;
#ifndef EqualRgn
- PyMac_PRECHECK(EqualRgn);
+ PyMac_PRECHECK(EqualRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &rgnA,
- ResObj_Convert, &rgnB))
- return NULL;
- _rv = EqualRgn(rgnA,
- rgnB);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &rgnA,
+ ResObj_Convert, &rgnB))
+ return NULL;
+ _rv = EqualRgn(rgnA,
+ rgnB);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_FrameRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef FrameRgn
- PyMac_PRECHECK(FrameRgn);
+ PyMac_PRECHECK(FrameRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- FrameRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ FrameRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_PaintRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef PaintRgn
- PyMac_PRECHECK(PaintRgn);
+ PyMac_PRECHECK(PaintRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- PaintRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ PaintRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_InvertRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
#ifndef InvertRgn
- PyMac_PRECHECK(InvertRgn);
+ PyMac_PRECHECK(InvertRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &rgn))
- return NULL;
- InvertRgn(rgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &rgn))
+ return NULL;
+ InvertRgn(rgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_FillRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle rgn;
- Pattern *pat__in__;
- int pat__in_len__;
+ PyObject *_res = NULL;
+ RgnHandle rgn;
+ Pattern *pat__in__;
+ int pat__in_len__;
#ifndef FillRgn
- PyMac_PRECHECK(FillRgn);
-#endif
- if (!PyArg_ParseTuple(_args, "O&s#",
- ResObj_Convert, &rgn,
- (char **)&pat__in__, &pat__in_len__))
- return NULL;
- if (pat__in_len__ != sizeof(Pattern))
- {
- PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
- goto pat__error__;
- }
- FillRgn(rgn,
- pat__in__);
- Py_INCREF(Py_None);
- _res = Py_None;
+ PyMac_PRECHECK(FillRgn);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&s#",
+ ResObj_Convert, &rgn,
+ (char **)&pat__in__, &pat__in_len__))
+ return NULL;
+ if (pat__in_len__ != sizeof(Pattern))
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer length should be sizeof(Pattern)");
+ goto pat__error__;
+ }
+ FillRgn(rgn,
+ pat__in__);
+ Py_INCREF(Py_None);
+ _res = Py_None;
pat__error__: ;
- return _res;
+ return _res;
}
static PyObject *Qd_GetPixel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- short h;
- short v;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ short h;
+ short v;
#ifndef GetPixel
- PyMac_PRECHECK(GetPixel);
+ PyMac_PRECHECK(GetPixel);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &h,
- &v))
- return NULL;
- _rv = GetPixel(h,
- v);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &h,
+ &v))
+ return NULL;
+ _rv = GetPixel(h,
+ v);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_PtInRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt;
- Rect r;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt;
+ Rect r;
#ifndef PtInRect
- PyMac_PRECHECK(PtInRect);
+ PyMac_PRECHECK(PtInRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &pt,
- PyMac_GetRect, &r))
- return NULL;
- _rv = PtInRect(pt,
- &r);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &pt,
+ PyMac_GetRect, &r))
+ return NULL;
+ _rv = PtInRect(pt,
+ &r);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qd_DrawText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *textBuf__in__;
- int textBuf__in_len__;
- short firstByte;
- short byteCount;
+ PyObject *_res = NULL;
+ char *textBuf__in__;
+ int textBuf__in_len__;
+ short firstByte;
+ short byteCount;
#ifndef DrawText
- PyMac_PRECHECK(DrawText);
-#endif
- if (!PyArg_ParseTuple(_args, "s#hh",
- &textBuf__in__, &textBuf__in_len__,
- &firstByte,
- &byteCount))
- return NULL;
- /* Fool compiler warnings */
- textBuf__in_len__ = textBuf__in_len__;
- DrawText(textBuf__in__,
- firstByte,
- byteCount);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DrawText);
+#endif
+ if (!PyArg_ParseTuple(_args, "s#hh",
+ &textBuf__in__, &textBuf__in_len__,
+ &firstByte,
+ &byteCount))
+ return NULL;
+ /* Fool compiler warnings */
+ textBuf__in_len__ = textBuf__in_len__;
+ DrawText(textBuf__in__,
+ firstByte,
+ byteCount);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qd_BitMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
-
- BitMap *ptr;
- PyObject *source;
- Rect bounds;
- int rowbytes;
- char *data;
-
- if ( !PyArg_ParseTuple(_args, "O!iO&", &PyString_Type, &source, &rowbytes, PyMac_GetRect,
- &bounds) )
- return NULL;
- data = PyString_AsString(source);
- if ((ptr=(BitMap *)malloc(sizeof(BitMap))) == NULL )
- return PyErr_NoMemory();
- ptr->baseAddr = (Ptr)data;
- ptr->rowBytes = rowbytes;
- ptr->bounds = bounds;
- if ( (_res = BMObj_New(ptr)) == NULL ) {
- free(ptr);
- return NULL;
- }
- ((BitMapObject *)_res)->referred_object = source;
- Py_INCREF(source);
- ((BitMapObject *)_res)->referred_bitmap = ptr;
- return _res;
+ PyObject *_res = NULL;
+
+ BitMap *ptr;
+ PyObject *source;
+ Rect bounds;
+ int rowbytes;
+ char *data;
+
+ if ( !PyArg_ParseTuple(_args, "O!iO&", &PyString_Type, &source, &rowbytes, PyMac_GetRect,
+ &bounds) )
+ return NULL;
+ data = PyString_AsString(source);
+ if ((ptr=(BitMap *)malloc(sizeof(BitMap))) == NULL )
+ return PyErr_NoMemory();
+ ptr->baseAddr = (Ptr)data;
+ ptr->rowBytes = rowbytes;
+ ptr->bounds = bounds;
+ if ( (_res = BMObj_New(ptr)) == NULL ) {
+ free(ptr);
+ return NULL;
+ }
+ ((BitMapObject *)_res)->referred_object = source;
+ Py_INCREF(source);
+ ((BitMapObject *)_res)->referred_bitmap = ptr;
+ return _res;
}
static PyObject *Qd_RawBitMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- BitMap *ptr;
- PyObject *source;
+ BitMap *ptr;
+ PyObject *source;
- if ( !PyArg_ParseTuple(_args, "O!", &PyString_Type, &source) )
- return NULL;
- if ( PyString_Size(source) != sizeof(BitMap) && PyString_Size(source) != sizeof(PixMap) ) {
- PyErr_Format(PyExc_TypeError,
- "Argument size was %ld, should be %lu (sizeof BitMap) or %lu (sizeof PixMap)",
- PyString_Size(source), sizeof(BitMap), sizeof(PixMap));
- return NULL;
- }
- ptr = (BitMapPtr)PyString_AsString(source);
- if ( (_res = BMObj_New(ptr)) == NULL ) {
- return NULL;
- }
- ((BitMapObject *)_res)->referred_object = source;
- Py_INCREF(source);
- return _res;
+ if ( !PyArg_ParseTuple(_args, "O!", &PyString_Type, &source) )
+ return NULL;
+ if ( PyString_Size(source) != sizeof(BitMap) && PyString_Size(source) != sizeof(PixMap) ) {
+ PyErr_Format(PyExc_TypeError,
+ "Argument size was %ld, should be %lu (sizeof BitMap) or %lu (sizeof PixMap)",
+ PyString_Size(source), sizeof(BitMap), sizeof(PixMap));
+ return NULL;
+ }
+ ptr = (BitMapPtr)PyString_AsString(source);
+ if ( (_res = BMObj_New(ptr)) == NULL ) {
+ return NULL;
+ }
+ ((BitMapObject *)_res)->referred_object = source;
+ Py_INCREF(source);
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Qd_methods[] = {
#ifndef __LP64__
- {"GetPort", (PyCFunction)Qd_GetPort, 1,
- PyDoc_STR("() -> (GrafPtr port)")},
- {"GrafDevice", (PyCFunction)Qd_GrafDevice, 1,
- PyDoc_STR("(short device) -> None")},
- {"SetPortBits", (PyCFunction)Qd_SetPortBits, 1,
- PyDoc_STR("(BitMapPtr bm) -> None")},
- {"PortSize", (PyCFunction)Qd_PortSize, 1,
- PyDoc_STR("(short width, short height) -> None")},
- {"MovePortTo", (PyCFunction)Qd_MovePortTo, 1,
- PyDoc_STR("(short leftGlobal, short topGlobal) -> None")},
- {"SetOrigin", (PyCFunction)Qd_SetOrigin, 1,
- PyDoc_STR("(short h, short v) -> None")},
- {"SetClip", (PyCFunction)Qd_SetClip, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"GetClip", (PyCFunction)Qd_GetClip, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"ClipRect", (PyCFunction)Qd_ClipRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"BackPat", (PyCFunction)Qd_BackPat, 1,
- PyDoc_STR("(Pattern pat) -> None")},
- {"InitCursor", (PyCFunction)Qd_InitCursor, 1,
- PyDoc_STR("() -> None")},
- {"MacSetCursor", (PyCFunction)Qd_MacSetCursor, 1,
- PyDoc_STR("(Cursor crsr) -> None")},
- {"HideCursor", (PyCFunction)Qd_HideCursor, 1,
- PyDoc_STR("() -> None")},
- {"MacShowCursor", (PyCFunction)Qd_MacShowCursor, 1,
- PyDoc_STR("() -> None")},
- {"ObscureCursor", (PyCFunction)Qd_ObscureCursor, 1,
- PyDoc_STR("() -> None")},
- {"HidePen", (PyCFunction)Qd_HidePen, 1,
- PyDoc_STR("() -> None")},
- {"ShowPen", (PyCFunction)Qd_ShowPen, 1,
- PyDoc_STR("() -> None")},
- {"GetPen", (PyCFunction)Qd_GetPen, 1,
- PyDoc_STR("() -> (Point pt)")},
- {"GetPenState", (PyCFunction)Qd_GetPenState, 1,
- PyDoc_STR("() -> (PenState pnState)")},
- {"SetPenState", (PyCFunction)Qd_SetPenState, 1,
- PyDoc_STR("(PenState pnState) -> None")},
- {"PenSize", (PyCFunction)Qd_PenSize, 1,
- PyDoc_STR("(short width, short height) -> None")},
- {"PenMode", (PyCFunction)Qd_PenMode, 1,
- PyDoc_STR("(short mode) -> None")},
- {"PenPat", (PyCFunction)Qd_PenPat, 1,
- PyDoc_STR("(Pattern pat) -> None")},
- {"PenNormal", (PyCFunction)Qd_PenNormal, 1,
- PyDoc_STR("() -> None")},
- {"MoveTo", (PyCFunction)Qd_MoveTo, 1,
- PyDoc_STR("(short h, short v) -> None")},
- {"Move", (PyCFunction)Qd_Move, 1,
- PyDoc_STR("(short dh, short dv) -> None")},
- {"MacLineTo", (PyCFunction)Qd_MacLineTo, 1,
- PyDoc_STR("(short h, short v) -> None")},
- {"Line", (PyCFunction)Qd_Line, 1,
- PyDoc_STR("(short dh, short dv) -> None")},
- {"ForeColor", (PyCFunction)Qd_ForeColor, 1,
- PyDoc_STR("(long color) -> None")},
- {"BackColor", (PyCFunction)Qd_BackColor, 1,
- PyDoc_STR("(long color) -> None")},
- {"ColorBit", (PyCFunction)Qd_ColorBit, 1,
- PyDoc_STR("(short whichBit) -> None")},
- {"MacSetRect", (PyCFunction)Qd_MacSetRect, 1,
- PyDoc_STR("(short left, short top, short right, short bottom) -> (Rect r)")},
- {"MacOffsetRect", (PyCFunction)Qd_MacOffsetRect, 1,
- PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
- {"MacInsetRect", (PyCFunction)Qd_MacInsetRect, 1,
- PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
- {"SectRect", (PyCFunction)Qd_SectRect, 1,
- PyDoc_STR("(Rect src1, Rect src2) -> (Boolean _rv, Rect dstRect)")},
- {"MacUnionRect", (PyCFunction)Qd_MacUnionRect, 1,
- PyDoc_STR("(Rect src1, Rect src2) -> (Rect dstRect)")},
- {"MacEqualRect", (PyCFunction)Qd_MacEqualRect, 1,
- PyDoc_STR("(Rect rect1, Rect rect2) -> (Boolean _rv)")},
- {"EmptyRect", (PyCFunction)Qd_EmptyRect, 1,
- PyDoc_STR("(Rect r) -> (Boolean _rv)")},
- {"MacFrameRect", (PyCFunction)Qd_MacFrameRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"PaintRect", (PyCFunction)Qd_PaintRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"EraseRect", (PyCFunction)Qd_EraseRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"MacInvertRect", (PyCFunction)Qd_MacInvertRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"MacFillRect", (PyCFunction)Qd_MacFillRect, 1,
- PyDoc_STR("(Rect r, Pattern pat) -> None")},
- {"FrameOval", (PyCFunction)Qd_FrameOval, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"PaintOval", (PyCFunction)Qd_PaintOval, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"EraseOval", (PyCFunction)Qd_EraseOval, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"InvertOval", (PyCFunction)Qd_InvertOval, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"FillOval", (PyCFunction)Qd_FillOval, 1,
- PyDoc_STR("(Rect r, Pattern pat) -> None")},
- {"FrameRoundRect", (PyCFunction)Qd_FrameRoundRect, 1,
- PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
- {"PaintRoundRect", (PyCFunction)Qd_PaintRoundRect, 1,
- PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
- {"EraseRoundRect", (PyCFunction)Qd_EraseRoundRect, 1,
- PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
- {"InvertRoundRect", (PyCFunction)Qd_InvertRoundRect, 1,
- PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
- {"FillRoundRect", (PyCFunction)Qd_FillRoundRect, 1,
- PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight, Pattern pat) -> None")},
- {"FrameArc", (PyCFunction)Qd_FrameArc, 1,
- PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
- {"PaintArc", (PyCFunction)Qd_PaintArc, 1,
- PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
- {"EraseArc", (PyCFunction)Qd_EraseArc, 1,
- PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
- {"InvertArc", (PyCFunction)Qd_InvertArc, 1,
- PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
- {"FillArc", (PyCFunction)Qd_FillArc, 1,
- PyDoc_STR("(Rect r, short startAngle, short arcAngle, Pattern pat) -> None")},
- {"NewRgn", (PyCFunction)Qd_NewRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"OpenRgn", (PyCFunction)Qd_OpenRgn, 1,
- PyDoc_STR("() -> None")},
- {"CloseRgn", (PyCFunction)Qd_CloseRgn, 1,
- PyDoc_STR("(RgnHandle dstRgn) -> None")},
- {"BitMapToRegion", (PyCFunction)Qd_BitMapToRegion, 1,
- PyDoc_STR("(RgnHandle region, BitMapPtr bMap) -> None")},
- {"RgnToHandle", (PyCFunction)Qd_RgnToHandle, 1,
- PyDoc_STR("(RgnHandle region, Handle flattenedRgnDataHdl) -> None")},
- {"DisposeRgn", (PyCFunction)Qd_DisposeRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"MacCopyRgn", (PyCFunction)Qd_MacCopyRgn, 1,
- PyDoc_STR("(RgnHandle srcRgn, RgnHandle dstRgn) -> None")},
- {"SetEmptyRgn", (PyCFunction)Qd_SetEmptyRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"MacSetRectRgn", (PyCFunction)Qd_MacSetRectRgn, 1,
- PyDoc_STR("(RgnHandle rgn, short left, short top, short right, short bottom) -> None")},
- {"RectRgn", (PyCFunction)Qd_RectRgn, 1,
- PyDoc_STR("(RgnHandle rgn, Rect r) -> None")},
- {"MacOffsetRgn", (PyCFunction)Qd_MacOffsetRgn, 1,
- PyDoc_STR("(RgnHandle rgn, short dh, short dv) -> None")},
- {"InsetRgn", (PyCFunction)Qd_InsetRgn, 1,
- PyDoc_STR("(RgnHandle rgn, short dh, short dv) -> None")},
- {"SectRgn", (PyCFunction)Qd_SectRgn, 1,
- PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
- {"MacUnionRgn", (PyCFunction)Qd_MacUnionRgn, 1,
- PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
- {"DiffRgn", (PyCFunction)Qd_DiffRgn, 1,
- PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
- {"MacXorRgn", (PyCFunction)Qd_MacXorRgn, 1,
- PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
- {"RectInRgn", (PyCFunction)Qd_RectInRgn, 1,
- PyDoc_STR("(Rect r, RgnHandle rgn) -> (Boolean _rv)")},
- {"MacEqualRgn", (PyCFunction)Qd_MacEqualRgn, 1,
- PyDoc_STR("(RgnHandle rgnA, RgnHandle rgnB) -> (Boolean _rv)")},
- {"EmptyRgn", (PyCFunction)Qd_EmptyRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> (Boolean _rv)")},
- {"MacFrameRgn", (PyCFunction)Qd_MacFrameRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"MacPaintRgn", (PyCFunction)Qd_MacPaintRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"EraseRgn", (PyCFunction)Qd_EraseRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"MacInvertRgn", (PyCFunction)Qd_MacInvertRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"MacFillRgn", (PyCFunction)Qd_MacFillRgn, 1,
- PyDoc_STR("(RgnHandle rgn, Pattern pat) -> None")},
- {"ScrollRect", (PyCFunction)Qd_ScrollRect, 1,
- PyDoc_STR("(Rect r, short dh, short dv, RgnHandle updateRgn) -> None")},
- {"CopyBits", (PyCFunction)Qd_CopyBits, 1,
- PyDoc_STR("(BitMapPtr srcBits, BitMapPtr dstBits, Rect srcRect, Rect dstRect, short mode, RgnHandle maskRgn) -> None")},
- {"CopyMask", (PyCFunction)Qd_CopyMask, 1,
- PyDoc_STR("(BitMapPtr srcBits, BitMapPtr maskBits, BitMapPtr dstBits, Rect srcRect, Rect maskRect, Rect dstRect) -> None")},
- {"OpenPicture", (PyCFunction)Qd_OpenPicture, 1,
- PyDoc_STR("(Rect picFrame) -> (PicHandle _rv)")},
- {"PicComment", (PyCFunction)Qd_PicComment, 1,
- PyDoc_STR("(short kind, short dataSize, Handle dataHandle) -> None")},
- {"ClosePicture", (PyCFunction)Qd_ClosePicture, 1,
- PyDoc_STR("() -> None")},
- {"DrawPicture", (PyCFunction)Qd_DrawPicture, 1,
- PyDoc_STR("(PicHandle myPicture, Rect dstRect) -> None")},
- {"KillPicture", (PyCFunction)Qd_KillPicture, 1,
- PyDoc_STR("(PicHandle myPicture) -> None")},
- {"OpenPoly", (PyCFunction)Qd_OpenPoly, 1,
- PyDoc_STR("() -> (PolyHandle _rv)")},
- {"ClosePoly", (PyCFunction)Qd_ClosePoly, 1,
- PyDoc_STR("() -> None")},
- {"KillPoly", (PyCFunction)Qd_KillPoly, 1,
- PyDoc_STR("(PolyHandle poly) -> None")},
- {"OffsetPoly", (PyCFunction)Qd_OffsetPoly, 1,
- PyDoc_STR("(PolyHandle poly, short dh, short dv) -> None")},
- {"FramePoly", (PyCFunction)Qd_FramePoly, 1,
- PyDoc_STR("(PolyHandle poly) -> None")},
- {"PaintPoly", (PyCFunction)Qd_PaintPoly, 1,
- PyDoc_STR("(PolyHandle poly) -> None")},
- {"ErasePoly", (PyCFunction)Qd_ErasePoly, 1,
- PyDoc_STR("(PolyHandle poly) -> None")},
- {"InvertPoly", (PyCFunction)Qd_InvertPoly, 1,
- PyDoc_STR("(PolyHandle poly) -> None")},
- {"FillPoly", (PyCFunction)Qd_FillPoly, 1,
- PyDoc_STR("(PolyHandle poly, Pattern pat) -> None")},
- {"SetPt", (PyCFunction)Qd_SetPt, 1,
- PyDoc_STR("(short h, short v) -> (Point pt)")},
- {"LocalToGlobal", (PyCFunction)Qd_LocalToGlobal, 1,
- PyDoc_STR("(Point pt) -> (Point pt)")},
- {"GlobalToLocal", (PyCFunction)Qd_GlobalToLocal, 1,
- PyDoc_STR("(Point pt) -> (Point pt)")},
- {"Random", (PyCFunction)Qd_Random, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"MacGetPixel", (PyCFunction)Qd_MacGetPixel, 1,
- PyDoc_STR("(short h, short v) -> (Boolean _rv)")},
- {"ScalePt", (PyCFunction)Qd_ScalePt, 1,
- PyDoc_STR("(Point pt, Rect srcRect, Rect dstRect) -> (Point pt)")},
- {"MapPt", (PyCFunction)Qd_MapPt, 1,
- PyDoc_STR("(Point pt, Rect srcRect, Rect dstRect) -> (Point pt)")},
- {"MapRect", (PyCFunction)Qd_MapRect, 1,
- PyDoc_STR("(Rect r, Rect srcRect, Rect dstRect) -> (Rect r)")},
- {"MapRgn", (PyCFunction)Qd_MapRgn, 1,
- PyDoc_STR("(RgnHandle rgn, Rect srcRect, Rect dstRect) -> None")},
- {"MapPoly", (PyCFunction)Qd_MapPoly, 1,
- PyDoc_STR("(PolyHandle poly, Rect srcRect, Rect dstRect) -> None")},
- {"StdBits", (PyCFunction)Qd_StdBits, 1,
- PyDoc_STR("(BitMapPtr srcBits, Rect srcRect, Rect dstRect, short mode, RgnHandle maskRgn) -> None")},
- {"AddPt", (PyCFunction)Qd_AddPt, 1,
- PyDoc_STR("(Point src, Point dst) -> (Point dst)")},
- {"EqualPt", (PyCFunction)Qd_EqualPt, 1,
- PyDoc_STR("(Point pt1, Point pt2) -> (Boolean _rv)")},
- {"MacPtInRect", (PyCFunction)Qd_MacPtInRect, 1,
- PyDoc_STR("(Point pt, Rect r) -> (Boolean _rv)")},
- {"Pt2Rect", (PyCFunction)Qd_Pt2Rect, 1,
- PyDoc_STR("(Point pt1, Point pt2) -> (Rect dstRect)")},
- {"PtToAngle", (PyCFunction)Qd_PtToAngle, 1,
- PyDoc_STR("(Rect r, Point pt) -> (short angle)")},
- {"SubPt", (PyCFunction)Qd_SubPt, 1,
- PyDoc_STR("(Point src, Point dst) -> (Point dst)")},
- {"PtInRgn", (PyCFunction)Qd_PtInRgn, 1,
- PyDoc_STR("(Point pt, RgnHandle rgn) -> (Boolean _rv)")},
- {"NewPixMap", (PyCFunction)Qd_NewPixMap, 1,
- PyDoc_STR("() -> (PixMapHandle _rv)")},
- {"DisposePixMap", (PyCFunction)Qd_DisposePixMap, 1,
- PyDoc_STR("(PixMapHandle pm) -> None")},
- {"CopyPixMap", (PyCFunction)Qd_CopyPixMap, 1,
- PyDoc_STR("(PixMapHandle srcPM, PixMapHandle dstPM) -> None")},
- {"NewPixPat", (PyCFunction)Qd_NewPixPat, 1,
- PyDoc_STR("() -> (PixPatHandle _rv)")},
- {"DisposePixPat", (PyCFunction)Qd_DisposePixPat, 1,
- PyDoc_STR("(PixPatHandle pp) -> None")},
- {"CopyPixPat", (PyCFunction)Qd_CopyPixPat, 1,
- PyDoc_STR("(PixPatHandle srcPP, PixPatHandle dstPP) -> None")},
- {"PenPixPat", (PyCFunction)Qd_PenPixPat, 1,
- PyDoc_STR("(PixPatHandle pp) -> None")},
- {"BackPixPat", (PyCFunction)Qd_BackPixPat, 1,
- PyDoc_STR("(PixPatHandle pp) -> None")},
- {"GetPixPat", (PyCFunction)Qd_GetPixPat, 1,
- PyDoc_STR("(short patID) -> (PixPatHandle _rv)")},
- {"MakeRGBPat", (PyCFunction)Qd_MakeRGBPat, 1,
- PyDoc_STR("(PixPatHandle pp, RGBColor myColor) -> None")},
- {"FillCRect", (PyCFunction)Qd_FillCRect, 1,
- PyDoc_STR("(Rect r, PixPatHandle pp) -> None")},
- {"FillCOval", (PyCFunction)Qd_FillCOval, 1,
- PyDoc_STR("(Rect r, PixPatHandle pp) -> None")},
- {"FillCRoundRect", (PyCFunction)Qd_FillCRoundRect, 1,
- PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight, PixPatHandle pp) -> None")},
- {"FillCArc", (PyCFunction)Qd_FillCArc, 1,
- PyDoc_STR("(Rect r, short startAngle, short arcAngle, PixPatHandle pp) -> None")},
- {"FillCRgn", (PyCFunction)Qd_FillCRgn, 1,
- PyDoc_STR("(RgnHandle rgn, PixPatHandle pp) -> None")},
- {"FillCPoly", (PyCFunction)Qd_FillCPoly, 1,
- PyDoc_STR("(PolyHandle poly, PixPatHandle pp) -> None")},
- {"RGBForeColor", (PyCFunction)Qd_RGBForeColor, 1,
- PyDoc_STR("(RGBColor color) -> None")},
- {"RGBBackColor", (PyCFunction)Qd_RGBBackColor, 1,
- PyDoc_STR("(RGBColor color) -> None")},
- {"SetCPixel", (PyCFunction)Qd_SetCPixel, 1,
- PyDoc_STR("(short h, short v, RGBColor cPix) -> None")},
- {"SetPortPix", (PyCFunction)Qd_SetPortPix, 1,
- PyDoc_STR("(PixMapHandle pm) -> None")},
- {"GetCPixel", (PyCFunction)Qd_GetCPixel, 1,
- PyDoc_STR("(short h, short v) -> (RGBColor cPix)")},
- {"GetForeColor", (PyCFunction)Qd_GetForeColor, 1,
- PyDoc_STR("() -> (RGBColor color)")},
- {"GetBackColor", (PyCFunction)Qd_GetBackColor, 1,
- PyDoc_STR("() -> (RGBColor color)")},
- {"OpColor", (PyCFunction)Qd_OpColor, 1,
- PyDoc_STR("(RGBColor color) -> None")},
- {"HiliteColor", (PyCFunction)Qd_HiliteColor, 1,
- PyDoc_STR("(RGBColor color) -> None")},
- {"DisposeCTable", (PyCFunction)Qd_DisposeCTable, 1,
- PyDoc_STR("(CTabHandle cTable) -> None")},
- {"GetCTable", (PyCFunction)Qd_GetCTable, 1,
- PyDoc_STR("(short ctID) -> (CTabHandle _rv)")},
- {"GetCCursor", (PyCFunction)Qd_GetCCursor, 1,
- PyDoc_STR("(short crsrID) -> (CCrsrHandle _rv)")},
- {"SetCCursor", (PyCFunction)Qd_SetCCursor, 1,
- PyDoc_STR("(CCrsrHandle cCrsr) -> None")},
- {"AllocCursor", (PyCFunction)Qd_AllocCursor, 1,
- PyDoc_STR("() -> None")},
- {"DisposeCCursor", (PyCFunction)Qd_DisposeCCursor, 1,
- PyDoc_STR("(CCrsrHandle cCrsr) -> None")},
- {"GetMaxDevice", (PyCFunction)Qd_GetMaxDevice, 1,
- PyDoc_STR("(Rect globalRect) -> (GDHandle _rv)")},
- {"GetCTSeed", (PyCFunction)Qd_GetCTSeed, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetDeviceList", (PyCFunction)Qd_GetDeviceList, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"GetMainDevice", (PyCFunction)Qd_GetMainDevice, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"GetNextDevice", (PyCFunction)Qd_GetNextDevice, 1,
- PyDoc_STR("(GDHandle curDevice) -> (GDHandle _rv)")},
- {"TestDeviceAttribute", (PyCFunction)Qd_TestDeviceAttribute, 1,
- PyDoc_STR("(GDHandle gdh, short attribute) -> (Boolean _rv)")},
- {"SetDeviceAttribute", (PyCFunction)Qd_SetDeviceAttribute, 1,
- PyDoc_STR("(GDHandle gdh, short attribute, Boolean value) -> None")},
- {"InitGDevice", (PyCFunction)Qd_InitGDevice, 1,
- PyDoc_STR("(short qdRefNum, long mode, GDHandle gdh) -> None")},
- {"NewGDevice", (PyCFunction)Qd_NewGDevice, 1,
- PyDoc_STR("(short refNum, long mode) -> (GDHandle _rv)")},
- {"DisposeGDevice", (PyCFunction)Qd_DisposeGDevice, 1,
- PyDoc_STR("(GDHandle gdh) -> None")},
- {"SetGDevice", (PyCFunction)Qd_SetGDevice, 1,
- PyDoc_STR("(GDHandle gd) -> None")},
- {"GetGDevice", (PyCFunction)Qd_GetGDevice, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"Color2Index", (PyCFunction)Qd_Color2Index, 1,
- PyDoc_STR("(RGBColor myColor) -> (long _rv)")},
- {"Index2Color", (PyCFunction)Qd_Index2Color, 1,
- PyDoc_STR("(long index) -> (RGBColor aColor)")},
- {"InvertColor", (PyCFunction)Qd_InvertColor, 1,
- PyDoc_STR("() -> (RGBColor myColor)")},
- {"RealColor", (PyCFunction)Qd_RealColor, 1,
- PyDoc_STR("(RGBColor color) -> (Boolean _rv)")},
- {"GetSubTable", (PyCFunction)Qd_GetSubTable, 1,
- PyDoc_STR("(CTabHandle myColors, short iTabRes, CTabHandle targetTbl) -> None")},
- {"MakeITable", (PyCFunction)Qd_MakeITable, 1,
- PyDoc_STR("(CTabHandle cTabH, ITabHandle iTabH, short res) -> None")},
- {"SetClientID", (PyCFunction)Qd_SetClientID, 1,
- PyDoc_STR("(short id) -> None")},
- {"ProtectEntry", (PyCFunction)Qd_ProtectEntry, 1,
- PyDoc_STR("(short index, Boolean protect) -> None")},
- {"ReserveEntry", (PyCFunction)Qd_ReserveEntry, 1,
- PyDoc_STR("(short index, Boolean reserve) -> None")},
- {"QDError", (PyCFunction)Qd_QDError, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"CopyDeepMask", (PyCFunction)Qd_CopyDeepMask, 1,
- PyDoc_STR("(BitMapPtr srcBits, BitMapPtr maskBits, BitMapPtr dstBits, Rect srcRect, Rect maskRect, Rect dstRect, short mode, RgnHandle maskRgn) -> None")},
- {"GetPattern", (PyCFunction)Qd_GetPattern, 1,
- PyDoc_STR("(short patternID) -> (PatHandle _rv)")},
- {"MacGetCursor", (PyCFunction)Qd_MacGetCursor, 1,
- PyDoc_STR("(short cursorID) -> (CursHandle _rv)")},
- {"GetPicture", (PyCFunction)Qd_GetPicture, 1,
- PyDoc_STR("(short pictureID) -> (PicHandle _rv)")},
- {"DeltaPoint", (PyCFunction)Qd_DeltaPoint, 1,
- PyDoc_STR("(Point ptA, Point ptB) -> (long _rv)")},
- {"ShieldCursor", (PyCFunction)Qd_ShieldCursor, 1,
- PyDoc_STR("(Rect shieldRect, Point offsetPt) -> None")},
- {"ScreenRes", (PyCFunction)Qd_ScreenRes, 1,
- PyDoc_STR("() -> (short scrnHRes, short scrnVRes)")},
- {"GetIndPattern", (PyCFunction)Qd_GetIndPattern, 1,
- PyDoc_STR("(short patternListID, short index) -> (Pattern thePat)")},
- {"SlopeFromAngle", (PyCFunction)Qd_SlopeFromAngle, 1,
- PyDoc_STR("(short angle) -> (Fixed _rv)")},
- {"AngleFromSlope", (PyCFunction)Qd_AngleFromSlope, 1,
- PyDoc_STR("(Fixed slope) -> (short _rv)")},
- {"GetPixBounds", (PyCFunction)Qd_GetPixBounds, 1,
- PyDoc_STR("(PixMapHandle pixMap) -> (Rect bounds)")},
- {"GetPixDepth", (PyCFunction)Qd_GetPixDepth, 1,
- PyDoc_STR("(PixMapHandle pixMap) -> (short _rv)")},
- {"GetQDGlobalsRandomSeed", (PyCFunction)Qd_GetQDGlobalsRandomSeed, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetQDGlobalsScreenBits", (PyCFunction)Qd_GetQDGlobalsScreenBits, 1,
- PyDoc_STR("() -> (BitMap screenBits)")},
- {"GetQDGlobalsArrow", (PyCFunction)Qd_GetQDGlobalsArrow, 1,
- PyDoc_STR("() -> (Cursor arrow)")},
- {"GetQDGlobalsDarkGray", (PyCFunction)Qd_GetQDGlobalsDarkGray, 1,
- PyDoc_STR("() -> (Pattern dkGray)")},
- {"GetQDGlobalsLightGray", (PyCFunction)Qd_GetQDGlobalsLightGray, 1,
- PyDoc_STR("() -> (Pattern ltGray)")},
- {"GetQDGlobalsGray", (PyCFunction)Qd_GetQDGlobalsGray, 1,
- PyDoc_STR("() -> (Pattern gray)")},
- {"GetQDGlobalsBlack", (PyCFunction)Qd_GetQDGlobalsBlack, 1,
- PyDoc_STR("() -> (Pattern black)")},
- {"GetQDGlobalsWhite", (PyCFunction)Qd_GetQDGlobalsWhite, 1,
- PyDoc_STR("() -> (Pattern white)")},
- {"GetQDGlobalsThePort", (PyCFunction)Qd_GetQDGlobalsThePort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {"SetQDGlobalsRandomSeed", (PyCFunction)Qd_SetQDGlobalsRandomSeed, 1,
- PyDoc_STR("(long randomSeed) -> None")},
- {"SetQDGlobalsArrow", (PyCFunction)Qd_SetQDGlobalsArrow, 1,
- PyDoc_STR("(Cursor arrow) -> None")},
- {"GetRegionBounds", (PyCFunction)Qd_GetRegionBounds, 1,
- PyDoc_STR("(RgnHandle region) -> (Rect bounds)")},
- {"IsRegionRectangular", (PyCFunction)Qd_IsRegionRectangular, 1,
- PyDoc_STR("(RgnHandle region) -> (Boolean _rv)")},
- {"CreateNewPort", (PyCFunction)Qd_CreateNewPort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {"SetQDError", (PyCFunction)Qd_SetQDError, 1,
- PyDoc_STR("(OSErr err) -> None")},
- {"LMGetScrVRes", (PyCFunction)Qd_LMGetScrVRes, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"LMSetScrVRes", (PyCFunction)Qd_LMSetScrVRes, 1,
- PyDoc_STR("(SInt16 value) -> None")},
- {"LMGetScrHRes", (PyCFunction)Qd_LMGetScrHRes, 1,
- PyDoc_STR("() -> (SInt16 _rv)")},
- {"LMSetScrHRes", (PyCFunction)Qd_LMSetScrHRes, 1,
- PyDoc_STR("(SInt16 value) -> None")},
- {"LMGetMainDevice", (PyCFunction)Qd_LMGetMainDevice, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"LMSetMainDevice", (PyCFunction)Qd_LMSetMainDevice, 1,
- PyDoc_STR("(GDHandle value) -> None")},
- {"LMGetDeviceList", (PyCFunction)Qd_LMGetDeviceList, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"LMSetDeviceList", (PyCFunction)Qd_LMSetDeviceList, 1,
- PyDoc_STR("(GDHandle value) -> None")},
- {"LMGetQDColors", (PyCFunction)Qd_LMGetQDColors, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"LMSetQDColors", (PyCFunction)Qd_LMSetQDColors, 1,
- PyDoc_STR("(Handle value) -> None")},
- {"LMGetWidthListHand", (PyCFunction)Qd_LMGetWidthListHand, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"LMSetWidthListHand", (PyCFunction)Qd_LMSetWidthListHand, 1,
- PyDoc_STR("(Handle value) -> None")},
- {"LMGetHiliteMode", (PyCFunction)Qd_LMGetHiliteMode, 1,
- PyDoc_STR("() -> (UInt8 _rv)")},
- {"LMSetHiliteMode", (PyCFunction)Qd_LMSetHiliteMode, 1,
- PyDoc_STR("(UInt8 value) -> None")},
- {"LMGetWidthTabHandle", (PyCFunction)Qd_LMGetWidthTabHandle, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"LMSetWidthTabHandle", (PyCFunction)Qd_LMSetWidthTabHandle, 1,
- PyDoc_STR("(Handle value) -> None")},
- {"LMGetLastSPExtra", (PyCFunction)Qd_LMGetLastSPExtra, 1,
- PyDoc_STR("() -> (SInt32 _rv)")},
- {"LMSetLastSPExtra", (PyCFunction)Qd_LMSetLastSPExtra, 1,
- PyDoc_STR("(SInt32 value) -> None")},
- {"LMGetLastFOND", (PyCFunction)Qd_LMGetLastFOND, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"LMSetLastFOND", (PyCFunction)Qd_LMSetLastFOND, 1,
- PyDoc_STR("(Handle value) -> None")},
- {"LMGetFractEnable", (PyCFunction)Qd_LMGetFractEnable, 1,
- PyDoc_STR("() -> (UInt8 _rv)")},
- {"LMSetFractEnable", (PyCFunction)Qd_LMSetFractEnable, 1,
- PyDoc_STR("(UInt8 value) -> None")},
- {"LMGetTheGDevice", (PyCFunction)Qd_LMGetTheGDevice, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"LMSetTheGDevice", (PyCFunction)Qd_LMSetTheGDevice, 1,
- PyDoc_STR("(GDHandle value) -> None")},
- {"LMGetHiliteRGB", (PyCFunction)Qd_LMGetHiliteRGB, 1,
- PyDoc_STR("() -> (RGBColor hiliteRGBValue)")},
- {"LMSetHiliteRGB", (PyCFunction)Qd_LMSetHiliteRGB, 1,
- PyDoc_STR("(RGBColor hiliteRGBValue) -> None")},
- {"LMGetCursorNew", (PyCFunction)Qd_LMGetCursorNew, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"LMSetCursorNew", (PyCFunction)Qd_LMSetCursorNew, 1,
- PyDoc_STR("(Boolean value) -> None")},
- {"TextFont", (PyCFunction)Qd_TextFont, 1,
- PyDoc_STR("(short font) -> None")},
- {"TextFace", (PyCFunction)Qd_TextFace, 1,
- PyDoc_STR("(StyleParameter face) -> None")},
- {"TextMode", (PyCFunction)Qd_TextMode, 1,
- PyDoc_STR("(short mode) -> None")},
- {"TextSize", (PyCFunction)Qd_TextSize, 1,
- PyDoc_STR("(short size) -> None")},
- {"SpaceExtra", (PyCFunction)Qd_SpaceExtra, 1,
- PyDoc_STR("(Fixed extra) -> None")},
- {"DrawChar", (PyCFunction)Qd_DrawChar, 1,
- PyDoc_STR("(CharParameter ch) -> None")},
- {"DrawString", (PyCFunction)Qd_DrawString, 1,
- PyDoc_STR("(Str255 s) -> None")},
- {"MacDrawText", (PyCFunction)Qd_MacDrawText, 1,
- PyDoc_STR("(Buffer textBuf, short firstByte, short byteCount) -> None")},
- {"CharWidth", (PyCFunction)Qd_CharWidth, 1,
- PyDoc_STR("(CharParameter ch) -> (short _rv)")},
- {"StringWidth", (PyCFunction)Qd_StringWidth, 1,
- PyDoc_STR("(Str255 s) -> (short _rv)")},
- {"TextWidth", (PyCFunction)Qd_TextWidth, 1,
- PyDoc_STR("(Buffer textBuf, short firstByte, short byteCount) -> (short _rv)")},
- {"GetFontInfo", (PyCFunction)Qd_GetFontInfo, 1,
- PyDoc_STR("() -> (FontInfo info)")},
- {"CharExtra", (PyCFunction)Qd_CharExtra, 1,
- PyDoc_STR("(Fixed extra) -> None")},
- {"TruncString", (PyCFunction)Qd_TruncString, 1,
- PyDoc_STR("(short width, Str255 theString, TruncCode truncWhere) -> (short _rv)")},
- {"SetPort", (PyCFunction)Qd_SetPort, 1,
- PyDoc_STR("(GrafPtr thePort) -> None")},
- {"GetCursor", (PyCFunction)Qd_GetCursor, 1,
- PyDoc_STR("(short cursorID) -> (CursHandle _rv)")},
- {"SetCursor", (PyCFunction)Qd_SetCursor, 1,
- PyDoc_STR("(Cursor crsr) -> None")},
- {"ShowCursor", (PyCFunction)Qd_ShowCursor, 1,
- PyDoc_STR("() -> None")},
- {"LineTo", (PyCFunction)Qd_LineTo, 1,
- PyDoc_STR("(short h, short v) -> None")},
- {"SetRect", (PyCFunction)Qd_SetRect, 1,
- PyDoc_STR("(short left, short top, short right, short bottom) -> (Rect r)")},
- {"OffsetRect", (PyCFunction)Qd_OffsetRect, 1,
- PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
- {"InsetRect", (PyCFunction)Qd_InsetRect, 1,
- PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
- {"UnionRect", (PyCFunction)Qd_UnionRect, 1,
- PyDoc_STR("(Rect src1, Rect src2) -> (Rect dstRect)")},
- {"EqualRect", (PyCFunction)Qd_EqualRect, 1,
- PyDoc_STR("(Rect rect1, Rect rect2) -> (Boolean _rv)")},
- {"FrameRect", (PyCFunction)Qd_FrameRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"InvertRect", (PyCFunction)Qd_InvertRect, 1,
- PyDoc_STR("(Rect r) -> None")},
- {"FillRect", (PyCFunction)Qd_FillRect, 1,
- PyDoc_STR("(Rect r, Pattern pat) -> None")},
- {"CopyRgn", (PyCFunction)Qd_CopyRgn, 1,
- PyDoc_STR("(RgnHandle srcRgn, RgnHandle dstRgn) -> None")},
- {"SetRectRgn", (PyCFunction)Qd_SetRectRgn, 1,
- PyDoc_STR("(RgnHandle rgn, short left, short top, short right, short bottom) -> None")},
- {"OffsetRgn", (PyCFunction)Qd_OffsetRgn, 1,
- PyDoc_STR("(RgnHandle rgn, short dh, short dv) -> None")},
- {"UnionRgn", (PyCFunction)Qd_UnionRgn, 1,
- PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
- {"XorRgn", (PyCFunction)Qd_XorRgn, 1,
- PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
- {"EqualRgn", (PyCFunction)Qd_EqualRgn, 1,
- PyDoc_STR("(RgnHandle rgnA, RgnHandle rgnB) -> (Boolean _rv)")},
- {"FrameRgn", (PyCFunction)Qd_FrameRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"PaintRgn", (PyCFunction)Qd_PaintRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"InvertRgn", (PyCFunction)Qd_InvertRgn, 1,
- PyDoc_STR("(RgnHandle rgn) -> None")},
- {"FillRgn", (PyCFunction)Qd_FillRgn, 1,
- PyDoc_STR("(RgnHandle rgn, Pattern pat) -> None")},
- {"GetPixel", (PyCFunction)Qd_GetPixel, 1,
- PyDoc_STR("(short h, short v) -> (Boolean _rv)")},
- {"PtInRect", (PyCFunction)Qd_PtInRect, 1,
- PyDoc_STR("(Point pt, Rect r) -> (Boolean _rv)")},
- {"DrawText", (PyCFunction)Qd_DrawText, 1,
- PyDoc_STR("(Buffer textBuf, short firstByte, short byteCount) -> None")},
- {"BitMap", (PyCFunction)Qd_BitMap, 1,
- PyDoc_STR("Take (string, int, Rect) argument and create BitMap")},
- {"RawBitMap", (PyCFunction)Qd_RawBitMap, 1,
- PyDoc_STR("Take string BitMap and turn into BitMap object")},
+ {"GetPort", (PyCFunction)Qd_GetPort, 1,
+ PyDoc_STR("() -> (GrafPtr port)")},
+ {"GrafDevice", (PyCFunction)Qd_GrafDevice, 1,
+ PyDoc_STR("(short device) -> None")},
+ {"SetPortBits", (PyCFunction)Qd_SetPortBits, 1,
+ PyDoc_STR("(BitMapPtr bm) -> None")},
+ {"PortSize", (PyCFunction)Qd_PortSize, 1,
+ PyDoc_STR("(short width, short height) -> None")},
+ {"MovePortTo", (PyCFunction)Qd_MovePortTo, 1,
+ PyDoc_STR("(short leftGlobal, short topGlobal) -> None")},
+ {"SetOrigin", (PyCFunction)Qd_SetOrigin, 1,
+ PyDoc_STR("(short h, short v) -> None")},
+ {"SetClip", (PyCFunction)Qd_SetClip, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"GetClip", (PyCFunction)Qd_GetClip, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"ClipRect", (PyCFunction)Qd_ClipRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"BackPat", (PyCFunction)Qd_BackPat, 1,
+ PyDoc_STR("(Pattern pat) -> None")},
+ {"InitCursor", (PyCFunction)Qd_InitCursor, 1,
+ PyDoc_STR("() -> None")},
+ {"MacSetCursor", (PyCFunction)Qd_MacSetCursor, 1,
+ PyDoc_STR("(Cursor crsr) -> None")},
+ {"HideCursor", (PyCFunction)Qd_HideCursor, 1,
+ PyDoc_STR("() -> None")},
+ {"MacShowCursor", (PyCFunction)Qd_MacShowCursor, 1,
+ PyDoc_STR("() -> None")},
+ {"ObscureCursor", (PyCFunction)Qd_ObscureCursor, 1,
+ PyDoc_STR("() -> None")},
+ {"HidePen", (PyCFunction)Qd_HidePen, 1,
+ PyDoc_STR("() -> None")},
+ {"ShowPen", (PyCFunction)Qd_ShowPen, 1,
+ PyDoc_STR("() -> None")},
+ {"GetPen", (PyCFunction)Qd_GetPen, 1,
+ PyDoc_STR("() -> (Point pt)")},
+ {"GetPenState", (PyCFunction)Qd_GetPenState, 1,
+ PyDoc_STR("() -> (PenState pnState)")},
+ {"SetPenState", (PyCFunction)Qd_SetPenState, 1,
+ PyDoc_STR("(PenState pnState) -> None")},
+ {"PenSize", (PyCFunction)Qd_PenSize, 1,
+ PyDoc_STR("(short width, short height) -> None")},
+ {"PenMode", (PyCFunction)Qd_PenMode, 1,
+ PyDoc_STR("(short mode) -> None")},
+ {"PenPat", (PyCFunction)Qd_PenPat, 1,
+ PyDoc_STR("(Pattern pat) -> None")},
+ {"PenNormal", (PyCFunction)Qd_PenNormal, 1,
+ PyDoc_STR("() -> None")},
+ {"MoveTo", (PyCFunction)Qd_MoveTo, 1,
+ PyDoc_STR("(short h, short v) -> None")},
+ {"Move", (PyCFunction)Qd_Move, 1,
+ PyDoc_STR("(short dh, short dv) -> None")},
+ {"MacLineTo", (PyCFunction)Qd_MacLineTo, 1,
+ PyDoc_STR("(short h, short v) -> None")},
+ {"Line", (PyCFunction)Qd_Line, 1,
+ PyDoc_STR("(short dh, short dv) -> None")},
+ {"ForeColor", (PyCFunction)Qd_ForeColor, 1,
+ PyDoc_STR("(long color) -> None")},
+ {"BackColor", (PyCFunction)Qd_BackColor, 1,
+ PyDoc_STR("(long color) -> None")},
+ {"ColorBit", (PyCFunction)Qd_ColorBit, 1,
+ PyDoc_STR("(short whichBit) -> None")},
+ {"MacSetRect", (PyCFunction)Qd_MacSetRect, 1,
+ PyDoc_STR("(short left, short top, short right, short bottom) -> (Rect r)")},
+ {"MacOffsetRect", (PyCFunction)Qd_MacOffsetRect, 1,
+ PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
+ {"MacInsetRect", (PyCFunction)Qd_MacInsetRect, 1,
+ PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
+ {"SectRect", (PyCFunction)Qd_SectRect, 1,
+ PyDoc_STR("(Rect src1, Rect src2) -> (Boolean _rv, Rect dstRect)")},
+ {"MacUnionRect", (PyCFunction)Qd_MacUnionRect, 1,
+ PyDoc_STR("(Rect src1, Rect src2) -> (Rect dstRect)")},
+ {"MacEqualRect", (PyCFunction)Qd_MacEqualRect, 1,
+ PyDoc_STR("(Rect rect1, Rect rect2) -> (Boolean _rv)")},
+ {"EmptyRect", (PyCFunction)Qd_EmptyRect, 1,
+ PyDoc_STR("(Rect r) -> (Boolean _rv)")},
+ {"MacFrameRect", (PyCFunction)Qd_MacFrameRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"PaintRect", (PyCFunction)Qd_PaintRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"EraseRect", (PyCFunction)Qd_EraseRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"MacInvertRect", (PyCFunction)Qd_MacInvertRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"MacFillRect", (PyCFunction)Qd_MacFillRect, 1,
+ PyDoc_STR("(Rect r, Pattern pat) -> None")},
+ {"FrameOval", (PyCFunction)Qd_FrameOval, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"PaintOval", (PyCFunction)Qd_PaintOval, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"EraseOval", (PyCFunction)Qd_EraseOval, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"InvertOval", (PyCFunction)Qd_InvertOval, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"FillOval", (PyCFunction)Qd_FillOval, 1,
+ PyDoc_STR("(Rect r, Pattern pat) -> None")},
+ {"FrameRoundRect", (PyCFunction)Qd_FrameRoundRect, 1,
+ PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
+ {"PaintRoundRect", (PyCFunction)Qd_PaintRoundRect, 1,
+ PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
+ {"EraseRoundRect", (PyCFunction)Qd_EraseRoundRect, 1,
+ PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
+ {"InvertRoundRect", (PyCFunction)Qd_InvertRoundRect, 1,
+ PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight) -> None")},
+ {"FillRoundRect", (PyCFunction)Qd_FillRoundRect, 1,
+ PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight, Pattern pat) -> None")},
+ {"FrameArc", (PyCFunction)Qd_FrameArc, 1,
+ PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
+ {"PaintArc", (PyCFunction)Qd_PaintArc, 1,
+ PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
+ {"EraseArc", (PyCFunction)Qd_EraseArc, 1,
+ PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
+ {"InvertArc", (PyCFunction)Qd_InvertArc, 1,
+ PyDoc_STR("(Rect r, short startAngle, short arcAngle) -> None")},
+ {"FillArc", (PyCFunction)Qd_FillArc, 1,
+ PyDoc_STR("(Rect r, short startAngle, short arcAngle, Pattern pat) -> None")},
+ {"NewRgn", (PyCFunction)Qd_NewRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"OpenRgn", (PyCFunction)Qd_OpenRgn, 1,
+ PyDoc_STR("() -> None")},
+ {"CloseRgn", (PyCFunction)Qd_CloseRgn, 1,
+ PyDoc_STR("(RgnHandle dstRgn) -> None")},
+ {"BitMapToRegion", (PyCFunction)Qd_BitMapToRegion, 1,
+ PyDoc_STR("(RgnHandle region, BitMapPtr bMap) -> None")},
+ {"RgnToHandle", (PyCFunction)Qd_RgnToHandle, 1,
+ PyDoc_STR("(RgnHandle region, Handle flattenedRgnDataHdl) -> None")},
+ {"DisposeRgn", (PyCFunction)Qd_DisposeRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"MacCopyRgn", (PyCFunction)Qd_MacCopyRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgn, RgnHandle dstRgn) -> None")},
+ {"SetEmptyRgn", (PyCFunction)Qd_SetEmptyRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"MacSetRectRgn", (PyCFunction)Qd_MacSetRectRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, short left, short top, short right, short bottom) -> None")},
+ {"RectRgn", (PyCFunction)Qd_RectRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, Rect r) -> None")},
+ {"MacOffsetRgn", (PyCFunction)Qd_MacOffsetRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, short dh, short dv) -> None")},
+ {"InsetRgn", (PyCFunction)Qd_InsetRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, short dh, short dv) -> None")},
+ {"SectRgn", (PyCFunction)Qd_SectRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
+ {"MacUnionRgn", (PyCFunction)Qd_MacUnionRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
+ {"DiffRgn", (PyCFunction)Qd_DiffRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
+ {"MacXorRgn", (PyCFunction)Qd_MacXorRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
+ {"RectInRgn", (PyCFunction)Qd_RectInRgn, 1,
+ PyDoc_STR("(Rect r, RgnHandle rgn) -> (Boolean _rv)")},
+ {"MacEqualRgn", (PyCFunction)Qd_MacEqualRgn, 1,
+ PyDoc_STR("(RgnHandle rgnA, RgnHandle rgnB) -> (Boolean _rv)")},
+ {"EmptyRgn", (PyCFunction)Qd_EmptyRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> (Boolean _rv)")},
+ {"MacFrameRgn", (PyCFunction)Qd_MacFrameRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"MacPaintRgn", (PyCFunction)Qd_MacPaintRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"EraseRgn", (PyCFunction)Qd_EraseRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"MacInvertRgn", (PyCFunction)Qd_MacInvertRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"MacFillRgn", (PyCFunction)Qd_MacFillRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, Pattern pat) -> None")},
+ {"ScrollRect", (PyCFunction)Qd_ScrollRect, 1,
+ PyDoc_STR("(Rect r, short dh, short dv, RgnHandle updateRgn) -> None")},
+ {"CopyBits", (PyCFunction)Qd_CopyBits, 1,
+ PyDoc_STR("(BitMapPtr srcBits, BitMapPtr dstBits, Rect srcRect, Rect dstRect, short mode, RgnHandle maskRgn) -> None")},
+ {"CopyMask", (PyCFunction)Qd_CopyMask, 1,
+ PyDoc_STR("(BitMapPtr srcBits, BitMapPtr maskBits, BitMapPtr dstBits, Rect srcRect, Rect maskRect, Rect dstRect) -> None")},
+ {"OpenPicture", (PyCFunction)Qd_OpenPicture, 1,
+ PyDoc_STR("(Rect picFrame) -> (PicHandle _rv)")},
+ {"PicComment", (PyCFunction)Qd_PicComment, 1,
+ PyDoc_STR("(short kind, short dataSize, Handle dataHandle) -> None")},
+ {"ClosePicture", (PyCFunction)Qd_ClosePicture, 1,
+ PyDoc_STR("() -> None")},
+ {"DrawPicture", (PyCFunction)Qd_DrawPicture, 1,
+ PyDoc_STR("(PicHandle myPicture, Rect dstRect) -> None")},
+ {"KillPicture", (PyCFunction)Qd_KillPicture, 1,
+ PyDoc_STR("(PicHandle myPicture) -> None")},
+ {"OpenPoly", (PyCFunction)Qd_OpenPoly, 1,
+ PyDoc_STR("() -> (PolyHandle _rv)")},
+ {"ClosePoly", (PyCFunction)Qd_ClosePoly, 1,
+ PyDoc_STR("() -> None")},
+ {"KillPoly", (PyCFunction)Qd_KillPoly, 1,
+ PyDoc_STR("(PolyHandle poly) -> None")},
+ {"OffsetPoly", (PyCFunction)Qd_OffsetPoly, 1,
+ PyDoc_STR("(PolyHandle poly, short dh, short dv) -> None")},
+ {"FramePoly", (PyCFunction)Qd_FramePoly, 1,
+ PyDoc_STR("(PolyHandle poly) -> None")},
+ {"PaintPoly", (PyCFunction)Qd_PaintPoly, 1,
+ PyDoc_STR("(PolyHandle poly) -> None")},
+ {"ErasePoly", (PyCFunction)Qd_ErasePoly, 1,
+ PyDoc_STR("(PolyHandle poly) -> None")},
+ {"InvertPoly", (PyCFunction)Qd_InvertPoly, 1,
+ PyDoc_STR("(PolyHandle poly) -> None")},
+ {"FillPoly", (PyCFunction)Qd_FillPoly, 1,
+ PyDoc_STR("(PolyHandle poly, Pattern pat) -> None")},
+ {"SetPt", (PyCFunction)Qd_SetPt, 1,
+ PyDoc_STR("(short h, short v) -> (Point pt)")},
+ {"LocalToGlobal", (PyCFunction)Qd_LocalToGlobal, 1,
+ PyDoc_STR("(Point pt) -> (Point pt)")},
+ {"GlobalToLocal", (PyCFunction)Qd_GlobalToLocal, 1,
+ PyDoc_STR("(Point pt) -> (Point pt)")},
+ {"Random", (PyCFunction)Qd_Random, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"MacGetPixel", (PyCFunction)Qd_MacGetPixel, 1,
+ PyDoc_STR("(short h, short v) -> (Boolean _rv)")},
+ {"ScalePt", (PyCFunction)Qd_ScalePt, 1,
+ PyDoc_STR("(Point pt, Rect srcRect, Rect dstRect) -> (Point pt)")},
+ {"MapPt", (PyCFunction)Qd_MapPt, 1,
+ PyDoc_STR("(Point pt, Rect srcRect, Rect dstRect) -> (Point pt)")},
+ {"MapRect", (PyCFunction)Qd_MapRect, 1,
+ PyDoc_STR("(Rect r, Rect srcRect, Rect dstRect) -> (Rect r)")},
+ {"MapRgn", (PyCFunction)Qd_MapRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, Rect srcRect, Rect dstRect) -> None")},
+ {"MapPoly", (PyCFunction)Qd_MapPoly, 1,
+ PyDoc_STR("(PolyHandle poly, Rect srcRect, Rect dstRect) -> None")},
+ {"StdBits", (PyCFunction)Qd_StdBits, 1,
+ PyDoc_STR("(BitMapPtr srcBits, Rect srcRect, Rect dstRect, short mode, RgnHandle maskRgn) -> None")},
+ {"AddPt", (PyCFunction)Qd_AddPt, 1,
+ PyDoc_STR("(Point src, Point dst) -> (Point dst)")},
+ {"EqualPt", (PyCFunction)Qd_EqualPt, 1,
+ PyDoc_STR("(Point pt1, Point pt2) -> (Boolean _rv)")},
+ {"MacPtInRect", (PyCFunction)Qd_MacPtInRect, 1,
+ PyDoc_STR("(Point pt, Rect r) -> (Boolean _rv)")},
+ {"Pt2Rect", (PyCFunction)Qd_Pt2Rect, 1,
+ PyDoc_STR("(Point pt1, Point pt2) -> (Rect dstRect)")},
+ {"PtToAngle", (PyCFunction)Qd_PtToAngle, 1,
+ PyDoc_STR("(Rect r, Point pt) -> (short angle)")},
+ {"SubPt", (PyCFunction)Qd_SubPt, 1,
+ PyDoc_STR("(Point src, Point dst) -> (Point dst)")},
+ {"PtInRgn", (PyCFunction)Qd_PtInRgn, 1,
+ PyDoc_STR("(Point pt, RgnHandle rgn) -> (Boolean _rv)")},
+ {"NewPixMap", (PyCFunction)Qd_NewPixMap, 1,
+ PyDoc_STR("() -> (PixMapHandle _rv)")},
+ {"DisposePixMap", (PyCFunction)Qd_DisposePixMap, 1,
+ PyDoc_STR("(PixMapHandle pm) -> None")},
+ {"CopyPixMap", (PyCFunction)Qd_CopyPixMap, 1,
+ PyDoc_STR("(PixMapHandle srcPM, PixMapHandle dstPM) -> None")},
+ {"NewPixPat", (PyCFunction)Qd_NewPixPat, 1,
+ PyDoc_STR("() -> (PixPatHandle _rv)")},
+ {"DisposePixPat", (PyCFunction)Qd_DisposePixPat, 1,
+ PyDoc_STR("(PixPatHandle pp) -> None")},
+ {"CopyPixPat", (PyCFunction)Qd_CopyPixPat, 1,
+ PyDoc_STR("(PixPatHandle srcPP, PixPatHandle dstPP) -> None")},
+ {"PenPixPat", (PyCFunction)Qd_PenPixPat, 1,
+ PyDoc_STR("(PixPatHandle pp) -> None")},
+ {"BackPixPat", (PyCFunction)Qd_BackPixPat, 1,
+ PyDoc_STR("(PixPatHandle pp) -> None")},
+ {"GetPixPat", (PyCFunction)Qd_GetPixPat, 1,
+ PyDoc_STR("(short patID) -> (PixPatHandle _rv)")},
+ {"MakeRGBPat", (PyCFunction)Qd_MakeRGBPat, 1,
+ PyDoc_STR("(PixPatHandle pp, RGBColor myColor) -> None")},
+ {"FillCRect", (PyCFunction)Qd_FillCRect, 1,
+ PyDoc_STR("(Rect r, PixPatHandle pp) -> None")},
+ {"FillCOval", (PyCFunction)Qd_FillCOval, 1,
+ PyDoc_STR("(Rect r, PixPatHandle pp) -> None")},
+ {"FillCRoundRect", (PyCFunction)Qd_FillCRoundRect, 1,
+ PyDoc_STR("(Rect r, short ovalWidth, short ovalHeight, PixPatHandle pp) -> None")},
+ {"FillCArc", (PyCFunction)Qd_FillCArc, 1,
+ PyDoc_STR("(Rect r, short startAngle, short arcAngle, PixPatHandle pp) -> None")},
+ {"FillCRgn", (PyCFunction)Qd_FillCRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, PixPatHandle pp) -> None")},
+ {"FillCPoly", (PyCFunction)Qd_FillCPoly, 1,
+ PyDoc_STR("(PolyHandle poly, PixPatHandle pp) -> None")},
+ {"RGBForeColor", (PyCFunction)Qd_RGBForeColor, 1,
+ PyDoc_STR("(RGBColor color) -> None")},
+ {"RGBBackColor", (PyCFunction)Qd_RGBBackColor, 1,
+ PyDoc_STR("(RGBColor color) -> None")},
+ {"SetCPixel", (PyCFunction)Qd_SetCPixel, 1,
+ PyDoc_STR("(short h, short v, RGBColor cPix) -> None")},
+ {"SetPortPix", (PyCFunction)Qd_SetPortPix, 1,
+ PyDoc_STR("(PixMapHandle pm) -> None")},
+ {"GetCPixel", (PyCFunction)Qd_GetCPixel, 1,
+ PyDoc_STR("(short h, short v) -> (RGBColor cPix)")},
+ {"GetForeColor", (PyCFunction)Qd_GetForeColor, 1,
+ PyDoc_STR("() -> (RGBColor color)")},
+ {"GetBackColor", (PyCFunction)Qd_GetBackColor, 1,
+ PyDoc_STR("() -> (RGBColor color)")},
+ {"OpColor", (PyCFunction)Qd_OpColor, 1,
+ PyDoc_STR("(RGBColor color) -> None")},
+ {"HiliteColor", (PyCFunction)Qd_HiliteColor, 1,
+ PyDoc_STR("(RGBColor color) -> None")},
+ {"DisposeCTable", (PyCFunction)Qd_DisposeCTable, 1,
+ PyDoc_STR("(CTabHandle cTable) -> None")},
+ {"GetCTable", (PyCFunction)Qd_GetCTable, 1,
+ PyDoc_STR("(short ctID) -> (CTabHandle _rv)")},
+ {"GetCCursor", (PyCFunction)Qd_GetCCursor, 1,
+ PyDoc_STR("(short crsrID) -> (CCrsrHandle _rv)")},
+ {"SetCCursor", (PyCFunction)Qd_SetCCursor, 1,
+ PyDoc_STR("(CCrsrHandle cCrsr) -> None")},
+ {"AllocCursor", (PyCFunction)Qd_AllocCursor, 1,
+ PyDoc_STR("() -> None")},
+ {"DisposeCCursor", (PyCFunction)Qd_DisposeCCursor, 1,
+ PyDoc_STR("(CCrsrHandle cCrsr) -> None")},
+ {"GetMaxDevice", (PyCFunction)Qd_GetMaxDevice, 1,
+ PyDoc_STR("(Rect globalRect) -> (GDHandle _rv)")},
+ {"GetCTSeed", (PyCFunction)Qd_GetCTSeed, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetDeviceList", (PyCFunction)Qd_GetDeviceList, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"GetMainDevice", (PyCFunction)Qd_GetMainDevice, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"GetNextDevice", (PyCFunction)Qd_GetNextDevice, 1,
+ PyDoc_STR("(GDHandle curDevice) -> (GDHandle _rv)")},
+ {"TestDeviceAttribute", (PyCFunction)Qd_TestDeviceAttribute, 1,
+ PyDoc_STR("(GDHandle gdh, short attribute) -> (Boolean _rv)")},
+ {"SetDeviceAttribute", (PyCFunction)Qd_SetDeviceAttribute, 1,
+ PyDoc_STR("(GDHandle gdh, short attribute, Boolean value) -> None")},
+ {"InitGDevice", (PyCFunction)Qd_InitGDevice, 1,
+ PyDoc_STR("(short qdRefNum, long mode, GDHandle gdh) -> None")},
+ {"NewGDevice", (PyCFunction)Qd_NewGDevice, 1,
+ PyDoc_STR("(short refNum, long mode) -> (GDHandle _rv)")},
+ {"DisposeGDevice", (PyCFunction)Qd_DisposeGDevice, 1,
+ PyDoc_STR("(GDHandle gdh) -> None")},
+ {"SetGDevice", (PyCFunction)Qd_SetGDevice, 1,
+ PyDoc_STR("(GDHandle gd) -> None")},
+ {"GetGDevice", (PyCFunction)Qd_GetGDevice, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"Color2Index", (PyCFunction)Qd_Color2Index, 1,
+ PyDoc_STR("(RGBColor myColor) -> (long _rv)")},
+ {"Index2Color", (PyCFunction)Qd_Index2Color, 1,
+ PyDoc_STR("(long index) -> (RGBColor aColor)")},
+ {"InvertColor", (PyCFunction)Qd_InvertColor, 1,
+ PyDoc_STR("() -> (RGBColor myColor)")},
+ {"RealColor", (PyCFunction)Qd_RealColor, 1,
+ PyDoc_STR("(RGBColor color) -> (Boolean _rv)")},
+ {"GetSubTable", (PyCFunction)Qd_GetSubTable, 1,
+ PyDoc_STR("(CTabHandle myColors, short iTabRes, CTabHandle targetTbl) -> None")},
+ {"MakeITable", (PyCFunction)Qd_MakeITable, 1,
+ PyDoc_STR("(CTabHandle cTabH, ITabHandle iTabH, short res) -> None")},
+ {"SetClientID", (PyCFunction)Qd_SetClientID, 1,
+ PyDoc_STR("(short id) -> None")},
+ {"ProtectEntry", (PyCFunction)Qd_ProtectEntry, 1,
+ PyDoc_STR("(short index, Boolean protect) -> None")},
+ {"ReserveEntry", (PyCFunction)Qd_ReserveEntry, 1,
+ PyDoc_STR("(short index, Boolean reserve) -> None")},
+ {"QDError", (PyCFunction)Qd_QDError, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"CopyDeepMask", (PyCFunction)Qd_CopyDeepMask, 1,
+ PyDoc_STR("(BitMapPtr srcBits, BitMapPtr maskBits, BitMapPtr dstBits, Rect srcRect, Rect maskRect, Rect dstRect, short mode, RgnHandle maskRgn) -> None")},
+ {"GetPattern", (PyCFunction)Qd_GetPattern, 1,
+ PyDoc_STR("(short patternID) -> (PatHandle _rv)")},
+ {"MacGetCursor", (PyCFunction)Qd_MacGetCursor, 1,
+ PyDoc_STR("(short cursorID) -> (CursHandle _rv)")},
+ {"GetPicture", (PyCFunction)Qd_GetPicture, 1,
+ PyDoc_STR("(short pictureID) -> (PicHandle _rv)")},
+ {"DeltaPoint", (PyCFunction)Qd_DeltaPoint, 1,
+ PyDoc_STR("(Point ptA, Point ptB) -> (long _rv)")},
+ {"ShieldCursor", (PyCFunction)Qd_ShieldCursor, 1,
+ PyDoc_STR("(Rect shieldRect, Point offsetPt) -> None")},
+ {"ScreenRes", (PyCFunction)Qd_ScreenRes, 1,
+ PyDoc_STR("() -> (short scrnHRes, short scrnVRes)")},
+ {"GetIndPattern", (PyCFunction)Qd_GetIndPattern, 1,
+ PyDoc_STR("(short patternListID, short index) -> (Pattern thePat)")},
+ {"SlopeFromAngle", (PyCFunction)Qd_SlopeFromAngle, 1,
+ PyDoc_STR("(short angle) -> (Fixed _rv)")},
+ {"AngleFromSlope", (PyCFunction)Qd_AngleFromSlope, 1,
+ PyDoc_STR("(Fixed slope) -> (short _rv)")},
+ {"GetPixBounds", (PyCFunction)Qd_GetPixBounds, 1,
+ PyDoc_STR("(PixMapHandle pixMap) -> (Rect bounds)")},
+ {"GetPixDepth", (PyCFunction)Qd_GetPixDepth, 1,
+ PyDoc_STR("(PixMapHandle pixMap) -> (short _rv)")},
+ {"GetQDGlobalsRandomSeed", (PyCFunction)Qd_GetQDGlobalsRandomSeed, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetQDGlobalsScreenBits", (PyCFunction)Qd_GetQDGlobalsScreenBits, 1,
+ PyDoc_STR("() -> (BitMap screenBits)")},
+ {"GetQDGlobalsArrow", (PyCFunction)Qd_GetQDGlobalsArrow, 1,
+ PyDoc_STR("() -> (Cursor arrow)")},
+ {"GetQDGlobalsDarkGray", (PyCFunction)Qd_GetQDGlobalsDarkGray, 1,
+ PyDoc_STR("() -> (Pattern dkGray)")},
+ {"GetQDGlobalsLightGray", (PyCFunction)Qd_GetQDGlobalsLightGray, 1,
+ PyDoc_STR("() -> (Pattern ltGray)")},
+ {"GetQDGlobalsGray", (PyCFunction)Qd_GetQDGlobalsGray, 1,
+ PyDoc_STR("() -> (Pattern gray)")},
+ {"GetQDGlobalsBlack", (PyCFunction)Qd_GetQDGlobalsBlack, 1,
+ PyDoc_STR("() -> (Pattern black)")},
+ {"GetQDGlobalsWhite", (PyCFunction)Qd_GetQDGlobalsWhite, 1,
+ PyDoc_STR("() -> (Pattern white)")},
+ {"GetQDGlobalsThePort", (PyCFunction)Qd_GetQDGlobalsThePort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {"SetQDGlobalsRandomSeed", (PyCFunction)Qd_SetQDGlobalsRandomSeed, 1,
+ PyDoc_STR("(long randomSeed) -> None")},
+ {"SetQDGlobalsArrow", (PyCFunction)Qd_SetQDGlobalsArrow, 1,
+ PyDoc_STR("(Cursor arrow) -> None")},
+ {"GetRegionBounds", (PyCFunction)Qd_GetRegionBounds, 1,
+ PyDoc_STR("(RgnHandle region) -> (Rect bounds)")},
+ {"IsRegionRectangular", (PyCFunction)Qd_IsRegionRectangular, 1,
+ PyDoc_STR("(RgnHandle region) -> (Boolean _rv)")},
+ {"CreateNewPort", (PyCFunction)Qd_CreateNewPort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {"SetQDError", (PyCFunction)Qd_SetQDError, 1,
+ PyDoc_STR("(OSErr err) -> None")},
+ {"LMGetScrVRes", (PyCFunction)Qd_LMGetScrVRes, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"LMSetScrVRes", (PyCFunction)Qd_LMSetScrVRes, 1,
+ PyDoc_STR("(SInt16 value) -> None")},
+ {"LMGetScrHRes", (PyCFunction)Qd_LMGetScrHRes, 1,
+ PyDoc_STR("() -> (SInt16 _rv)")},
+ {"LMSetScrHRes", (PyCFunction)Qd_LMSetScrHRes, 1,
+ PyDoc_STR("(SInt16 value) -> None")},
+ {"LMGetMainDevice", (PyCFunction)Qd_LMGetMainDevice, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"LMSetMainDevice", (PyCFunction)Qd_LMSetMainDevice, 1,
+ PyDoc_STR("(GDHandle value) -> None")},
+ {"LMGetDeviceList", (PyCFunction)Qd_LMGetDeviceList, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"LMSetDeviceList", (PyCFunction)Qd_LMSetDeviceList, 1,
+ PyDoc_STR("(GDHandle value) -> None")},
+ {"LMGetQDColors", (PyCFunction)Qd_LMGetQDColors, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"LMSetQDColors", (PyCFunction)Qd_LMSetQDColors, 1,
+ PyDoc_STR("(Handle value) -> None")},
+ {"LMGetWidthListHand", (PyCFunction)Qd_LMGetWidthListHand, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"LMSetWidthListHand", (PyCFunction)Qd_LMSetWidthListHand, 1,
+ PyDoc_STR("(Handle value) -> None")},
+ {"LMGetHiliteMode", (PyCFunction)Qd_LMGetHiliteMode, 1,
+ PyDoc_STR("() -> (UInt8 _rv)")},
+ {"LMSetHiliteMode", (PyCFunction)Qd_LMSetHiliteMode, 1,
+ PyDoc_STR("(UInt8 value) -> None")},
+ {"LMGetWidthTabHandle", (PyCFunction)Qd_LMGetWidthTabHandle, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"LMSetWidthTabHandle", (PyCFunction)Qd_LMSetWidthTabHandle, 1,
+ PyDoc_STR("(Handle value) -> None")},
+ {"LMGetLastSPExtra", (PyCFunction)Qd_LMGetLastSPExtra, 1,
+ PyDoc_STR("() -> (SInt32 _rv)")},
+ {"LMSetLastSPExtra", (PyCFunction)Qd_LMSetLastSPExtra, 1,
+ PyDoc_STR("(SInt32 value) -> None")},
+ {"LMGetLastFOND", (PyCFunction)Qd_LMGetLastFOND, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"LMSetLastFOND", (PyCFunction)Qd_LMSetLastFOND, 1,
+ PyDoc_STR("(Handle value) -> None")},
+ {"LMGetFractEnable", (PyCFunction)Qd_LMGetFractEnable, 1,
+ PyDoc_STR("() -> (UInt8 _rv)")},
+ {"LMSetFractEnable", (PyCFunction)Qd_LMSetFractEnable, 1,
+ PyDoc_STR("(UInt8 value) -> None")},
+ {"LMGetTheGDevice", (PyCFunction)Qd_LMGetTheGDevice, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"LMSetTheGDevice", (PyCFunction)Qd_LMSetTheGDevice, 1,
+ PyDoc_STR("(GDHandle value) -> None")},
+ {"LMGetHiliteRGB", (PyCFunction)Qd_LMGetHiliteRGB, 1,
+ PyDoc_STR("() -> (RGBColor hiliteRGBValue)")},
+ {"LMSetHiliteRGB", (PyCFunction)Qd_LMSetHiliteRGB, 1,
+ PyDoc_STR("(RGBColor hiliteRGBValue) -> None")},
+ {"LMGetCursorNew", (PyCFunction)Qd_LMGetCursorNew, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"LMSetCursorNew", (PyCFunction)Qd_LMSetCursorNew, 1,
+ PyDoc_STR("(Boolean value) -> None")},
+ {"TextFont", (PyCFunction)Qd_TextFont, 1,
+ PyDoc_STR("(short font) -> None")},
+ {"TextFace", (PyCFunction)Qd_TextFace, 1,
+ PyDoc_STR("(StyleParameter face) -> None")},
+ {"TextMode", (PyCFunction)Qd_TextMode, 1,
+ PyDoc_STR("(short mode) -> None")},
+ {"TextSize", (PyCFunction)Qd_TextSize, 1,
+ PyDoc_STR("(short size) -> None")},
+ {"SpaceExtra", (PyCFunction)Qd_SpaceExtra, 1,
+ PyDoc_STR("(Fixed extra) -> None")},
+ {"DrawChar", (PyCFunction)Qd_DrawChar, 1,
+ PyDoc_STR("(CharParameter ch) -> None")},
+ {"DrawString", (PyCFunction)Qd_DrawString, 1,
+ PyDoc_STR("(Str255 s) -> None")},
+ {"MacDrawText", (PyCFunction)Qd_MacDrawText, 1,
+ PyDoc_STR("(Buffer textBuf, short firstByte, short byteCount) -> None")},
+ {"CharWidth", (PyCFunction)Qd_CharWidth, 1,
+ PyDoc_STR("(CharParameter ch) -> (short _rv)")},
+ {"StringWidth", (PyCFunction)Qd_StringWidth, 1,
+ PyDoc_STR("(Str255 s) -> (short _rv)")},
+ {"TextWidth", (PyCFunction)Qd_TextWidth, 1,
+ PyDoc_STR("(Buffer textBuf, short firstByte, short byteCount) -> (short _rv)")},
+ {"GetFontInfo", (PyCFunction)Qd_GetFontInfo, 1,
+ PyDoc_STR("() -> (FontInfo info)")},
+ {"CharExtra", (PyCFunction)Qd_CharExtra, 1,
+ PyDoc_STR("(Fixed extra) -> None")},
+ {"TruncString", (PyCFunction)Qd_TruncString, 1,
+ PyDoc_STR("(short width, Str255 theString, TruncCode truncWhere) -> (short _rv)")},
+ {"SetPort", (PyCFunction)Qd_SetPort, 1,
+ PyDoc_STR("(GrafPtr thePort) -> None")},
+ {"GetCursor", (PyCFunction)Qd_GetCursor, 1,
+ PyDoc_STR("(short cursorID) -> (CursHandle _rv)")},
+ {"SetCursor", (PyCFunction)Qd_SetCursor, 1,
+ PyDoc_STR("(Cursor crsr) -> None")},
+ {"ShowCursor", (PyCFunction)Qd_ShowCursor, 1,
+ PyDoc_STR("() -> None")},
+ {"LineTo", (PyCFunction)Qd_LineTo, 1,
+ PyDoc_STR("(short h, short v) -> None")},
+ {"SetRect", (PyCFunction)Qd_SetRect, 1,
+ PyDoc_STR("(short left, short top, short right, short bottom) -> (Rect r)")},
+ {"OffsetRect", (PyCFunction)Qd_OffsetRect, 1,
+ PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
+ {"InsetRect", (PyCFunction)Qd_InsetRect, 1,
+ PyDoc_STR("(Rect r, short dh, short dv) -> (Rect r)")},
+ {"UnionRect", (PyCFunction)Qd_UnionRect, 1,
+ PyDoc_STR("(Rect src1, Rect src2) -> (Rect dstRect)")},
+ {"EqualRect", (PyCFunction)Qd_EqualRect, 1,
+ PyDoc_STR("(Rect rect1, Rect rect2) -> (Boolean _rv)")},
+ {"FrameRect", (PyCFunction)Qd_FrameRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"InvertRect", (PyCFunction)Qd_InvertRect, 1,
+ PyDoc_STR("(Rect r) -> None")},
+ {"FillRect", (PyCFunction)Qd_FillRect, 1,
+ PyDoc_STR("(Rect r, Pattern pat) -> None")},
+ {"CopyRgn", (PyCFunction)Qd_CopyRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgn, RgnHandle dstRgn) -> None")},
+ {"SetRectRgn", (PyCFunction)Qd_SetRectRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, short left, short top, short right, short bottom) -> None")},
+ {"OffsetRgn", (PyCFunction)Qd_OffsetRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, short dh, short dv) -> None")},
+ {"UnionRgn", (PyCFunction)Qd_UnionRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
+ {"XorRgn", (PyCFunction)Qd_XorRgn, 1,
+ PyDoc_STR("(RgnHandle srcRgnA, RgnHandle srcRgnB, RgnHandle dstRgn) -> None")},
+ {"EqualRgn", (PyCFunction)Qd_EqualRgn, 1,
+ PyDoc_STR("(RgnHandle rgnA, RgnHandle rgnB) -> (Boolean _rv)")},
+ {"FrameRgn", (PyCFunction)Qd_FrameRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"PaintRgn", (PyCFunction)Qd_PaintRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"InvertRgn", (PyCFunction)Qd_InvertRgn, 1,
+ PyDoc_STR("(RgnHandle rgn) -> None")},
+ {"FillRgn", (PyCFunction)Qd_FillRgn, 1,
+ PyDoc_STR("(RgnHandle rgn, Pattern pat) -> None")},
+ {"GetPixel", (PyCFunction)Qd_GetPixel, 1,
+ PyDoc_STR("(short h, short v) -> (Boolean _rv)")},
+ {"PtInRect", (PyCFunction)Qd_PtInRect, 1,
+ PyDoc_STR("(Point pt, Rect r) -> (Boolean _rv)")},
+ {"DrawText", (PyCFunction)Qd_DrawText, 1,
+ PyDoc_STR("(Buffer textBuf, short firstByte, short byteCount) -> None")},
+ {"BitMap", (PyCFunction)Qd_BitMap, 1,
+ PyDoc_STR("Take (string, int, Rect) argument and create BitMap")},
+ {"RawBitMap", (PyCFunction)Qd_RawBitMap, 1,
+ PyDoc_STR("Take string BitMap and turn into BitMap object")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -7095,15 +7095,15 @@ static PyMethodDef Qd_methods[] = {
*/
PyObject *BMObj_NewCopied(BitMapPtr itself)
{
- BitMapObject *it;
- BitMapPtr itself_copy;
+ BitMapObject *it;
+ BitMapPtr itself_copy;
- if ((itself_copy=(BitMapPtr)malloc(sizeof(BitMap))) == NULL)
- return PyErr_NoMemory();
- *itself_copy = *itself;
- it = (BitMapObject *)BMObj_New(itself_copy);
- it->referred_bitmap = itself_copy;
- return (PyObject *)it;
+ if ((itself_copy=(BitMapPtr)malloc(sizeof(BitMap))) == NULL)
+ return PyErr_NoMemory();
+ *itself_copy = *itself;
+ it = (BitMapObject *)BMObj_New(itself_copy);
+ it->referred_bitmap = itself_copy;
+ return (PyObject *)it;
}
#endif /* __LP64__ */
@@ -7111,42 +7111,42 @@ PyObject *BMObj_NewCopied(BitMapPtr itself)
void init_Qd(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(BitMapPtr, BMObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(BitMapPtr, BMObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(GrafPtr, GrafObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GrafPtr, GrafObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(RGBColorPtr, QdRGB_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColor, QdRGB_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(BitMapPtr, BMObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(BitMapPtr, BMObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(GrafPtr, GrafObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GrafPtr, GrafObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(RGBColorPtr, QdRGB_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(RGBColor, QdRGB_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_Qd", Qd_methods);
+ m = Py_InitModule("_Qd", Qd_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Qd_Error = PyMac_GetOSErrException();
- if (Qd_Error == NULL ||
- PyDict_SetItemString(d, "Error", Qd_Error) != 0)
- return;
- GrafPort_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&GrafPort_Type) < 0) return;
- Py_INCREF(&GrafPort_Type);
- PyModule_AddObject(m, "GrafPort", (PyObject *)&GrafPort_Type);
- /* Backward-compatible name */
- Py_INCREF(&GrafPort_Type);
- PyModule_AddObject(m, "GrafPortType", (PyObject *)&GrafPort_Type);
- BitMap_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&BitMap_Type) < 0) return;
- Py_INCREF(&BitMap_Type);
- PyModule_AddObject(m, "BitMap", (PyObject *)&BitMap_Type);
- /* Backward-compatible name */
- Py_INCREF(&BitMap_Type);
- PyModule_AddObject(m, "BitMapType", (PyObject *)&BitMap_Type);
+ d = PyModule_GetDict(m);
+ Qd_Error = PyMac_GetOSErrException();
+ if (Qd_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Qd_Error) != 0)
+ return;
+ GrafPort_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&GrafPort_Type) < 0) return;
+ Py_INCREF(&GrafPort_Type);
+ PyModule_AddObject(m, "GrafPort", (PyObject *)&GrafPort_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&GrafPort_Type);
+ PyModule_AddObject(m, "GrafPortType", (PyObject *)&GrafPort_Type);
+ BitMap_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&BitMap_Type) < 0) return;
+ Py_INCREF(&BitMap_Type);
+ PyModule_AddObject(m, "BitMap", (PyObject *)&BitMap_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&BitMap_Type);
+ PyModule_AddObject(m, "BitMapType", (PyObject *)&BitMap_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/qdoffs/_Qdoffsmodule.c b/Mac/Modules/qdoffs/_Qdoffsmodule.c
index b451472..686eca4 100644
--- a/Mac/Modules/qdoffs/_Qdoffsmodule.c
+++ b/Mac/Modules/qdoffs/_Qdoffsmodule.c
@@ -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)
@@ -38,90 +38,90 @@ PyTypeObject GWorld_Type;
#define GWorldObj_Check(x) ((x)->ob_type == &GWorld_Type || PyObject_TypeCheck((x), &GWorld_Type))
typedef struct GWorldObject {
- PyObject_HEAD
- GWorldPtr ob_itself;
+ PyObject_HEAD
+ GWorldPtr ob_itself;
} GWorldObject;
PyObject *GWorldObj_New(GWorldPtr itself)
{
- GWorldObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(GWorldObject, &GWorld_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ GWorldObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(GWorldObject, &GWorld_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int GWorldObj_Convert(PyObject *v, GWorldPtr *p_itself)
{
- if (!GWorldObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "GWorld required");
- return 0;
- }
- *p_itself = ((GWorldObject *)v)->ob_itself;
- return 1;
+ if (!GWorldObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "GWorld required");
+ return 0;
+ }
+ *p_itself = ((GWorldObject *)v)->ob_itself;
+ return 1;
}
static void GWorldObj_dealloc(GWorldObject *self)
{
- DisposeGWorld(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ DisposeGWorld(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *GWorldObj_GetGWorldDevice(GWorldObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle _rv;
+ PyObject *_res = NULL;
+ GDHandle _rv;
#ifndef GetGWorldDevice
- PyMac_PRECHECK(GetGWorldDevice);
+ PyMac_PRECHECK(GetGWorldDevice);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetGWorldDevice(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetGWorldDevice(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GWorldObj_GetGWorldPixMap(GWorldObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle _rv;
+ PyObject *_res = NULL;
+ PixMapHandle _rv;
#ifndef GetGWorldPixMap
- PyMac_PRECHECK(GetGWorldPixMap);
+ PyMac_PRECHECK(GetGWorldPixMap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetGWorldPixMap(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetGWorldPixMap(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *GWorldObj_as_GrafPtr(GWorldObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GrafPtr _rv;
+ PyObject *_res = NULL;
+ GrafPtr _rv;
#ifndef as_GrafPtr
- PyMac_PRECHECK(as_GrafPtr);
+ PyMac_PRECHECK(as_GrafPtr);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = as_GrafPtr(_self->ob_itself);
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = as_GrafPtr(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyMethodDef GWorldObj_methods[] = {
- {"GetGWorldDevice", (PyCFunction)GWorldObj_GetGWorldDevice, 1,
- PyDoc_STR("() -> (GDHandle _rv)")},
- {"GetGWorldPixMap", (PyCFunction)GWorldObj_GetGWorldPixMap, 1,
- PyDoc_STR("() -> (PixMapHandle _rv)")},
- {"as_GrafPtr", (PyCFunction)GWorldObj_as_GrafPtr, 1,
- PyDoc_STR("() -> (GrafPtr _rv)")},
- {NULL, NULL, 0}
+ {"GetGWorldDevice", (PyCFunction)GWorldObj_GetGWorldDevice, 1,
+ PyDoc_STR("() -> (GDHandle _rv)")},
+ {"GetGWorldPixMap", (PyCFunction)GWorldObj_GetGWorldPixMap, 1,
+ PyDoc_STR("() -> (PixMapHandle _rv)")},
+ {"as_GrafPtr", (PyCFunction)GWorldObj_as_GrafPtr, 1,
+ PyDoc_STR("() -> (GrafPtr _rv)")},
+ {NULL, NULL, 0}
};
#define GWorldObj_getsetlist NULL
@@ -138,61 +138,61 @@ static PyMethodDef GWorldObj_methods[] = {
static PyObject *GWorldObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- GWorldPtr itself;
- char *kw[] = {"itself", 0};
-
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, GWorldObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((GWorldObject *)_self)->ob_itself = itself;
- return _self;
+ PyObject *_self;
+ GWorldPtr itself;
+ char *kw[] = {"itself", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, GWorldObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((GWorldObject *)_self)->ob_itself = itself;
+ return _self;
}
#define GWorldObj_tp_free PyObject_Del
PyTypeObject GWorld_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qdoffs.GWorld", /*tp_name*/
- sizeof(GWorldObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) GWorldObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) GWorldObj_compare, /*tp_compare*/
- (reprfunc) GWorldObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) GWorldObj_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*/
- GWorldObj_methods, /* tp_methods */
- 0, /*tp_members*/
- GWorldObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- GWorldObj_tp_init, /* tp_init */
- GWorldObj_tp_alloc, /* tp_alloc */
- GWorldObj_tp_new, /* tp_new */
- GWorldObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qdoffs.GWorld", /*tp_name*/
+ sizeof(GWorldObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) GWorldObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) GWorldObj_compare, /*tp_compare*/
+ (reprfunc) GWorldObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) GWorldObj_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*/
+ GWorldObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ GWorldObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ GWorldObj_tp_init, /* tp_init */
+ GWorldObj_tp_alloc, /* tp_alloc */
+ GWorldObj_tp_new, /* tp_new */
+ GWorldObj_tp_free, /* tp_free */
};
/* --------------------- End object type GWorld --------------------- */
@@ -200,489 +200,489 @@ PyTypeObject GWorld_Type = {
static PyObject *Qdoffs_NewGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- QDErr _err;
- GWorldPtr offscreenGWorld;
- short PixelDepth;
- Rect boundsRect;
- CTabHandle cTable;
- GDHandle aGDevice;
- GWorldFlags flags;
+ PyObject *_res = NULL;
+ QDErr _err;
+ GWorldPtr offscreenGWorld;
+ short PixelDepth;
+ Rect boundsRect;
+ CTabHandle cTable;
+ GDHandle aGDevice;
+ GWorldFlags flags;
#ifndef NewGWorld
- PyMac_PRECHECK(NewGWorld);
+ PyMac_PRECHECK(NewGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "hO&O&O&l",
- &PixelDepth,
- PyMac_GetRect, &boundsRect,
- OptResObj_Convert, &cTable,
- OptResObj_Convert, &aGDevice,
- &flags))
- return NULL;
- _err = NewGWorld(&offscreenGWorld,
- PixelDepth,
- &boundsRect,
- cTable,
- aGDevice,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- GWorldObj_New, offscreenGWorld);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&O&O&l",
+ &PixelDepth,
+ PyMac_GetRect, &boundsRect,
+ OptResObj_Convert, &cTable,
+ OptResObj_Convert, &aGDevice,
+ &flags))
+ return NULL;
+ _err = NewGWorld(&offscreenGWorld,
+ PixelDepth,
+ &boundsRect,
+ cTable,
+ aGDevice,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ GWorldObj_New, offscreenGWorld);
+ return _res;
}
static PyObject *Qdoffs_LockPixels(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ PixMapHandle pm;
#ifndef LockPixels
- PyMac_PRECHECK(LockPixels);
+ PyMac_PRECHECK(LockPixels);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- _rv = LockPixels(pm);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ _rv = LockPixels(pm);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qdoffs_UnlockPixels(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ PixMapHandle pm;
#ifndef UnlockPixels
- PyMac_PRECHECK(UnlockPixels);
+ PyMac_PRECHECK(UnlockPixels);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- UnlockPixels(pm);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ UnlockPixels(pm);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_UpdateGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GWorldFlags _rv;
- GWorldPtr offscreenGWorld;
- short pixelDepth;
- Rect boundsRect;
- CTabHandle cTable;
- GDHandle aGDevice;
- GWorldFlags flags;
+ PyObject *_res = NULL;
+ GWorldFlags _rv;
+ GWorldPtr offscreenGWorld;
+ short pixelDepth;
+ Rect boundsRect;
+ CTabHandle cTable;
+ GDHandle aGDevice;
+ GWorldFlags flags;
#ifndef UpdateGWorld
- PyMac_PRECHECK(UpdateGWorld);
+ PyMac_PRECHECK(UpdateGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "hO&O&O&l",
- &pixelDepth,
- PyMac_GetRect, &boundsRect,
- OptResObj_Convert, &cTable,
- OptResObj_Convert, &aGDevice,
- &flags))
- return NULL;
- _rv = UpdateGWorld(&offscreenGWorld,
- pixelDepth,
- &boundsRect,
- cTable,
- aGDevice,
- flags);
- _res = Py_BuildValue("lO&",
- _rv,
- GWorldObj_New, offscreenGWorld);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&O&O&l",
+ &pixelDepth,
+ PyMac_GetRect, &boundsRect,
+ OptResObj_Convert, &cTable,
+ OptResObj_Convert, &aGDevice,
+ &flags))
+ return NULL;
+ _rv = UpdateGWorld(&offscreenGWorld,
+ pixelDepth,
+ &boundsRect,
+ cTable,
+ aGDevice,
+ flags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ GWorldObj_New, offscreenGWorld);
+ return _res;
}
static PyObject *Qdoffs_GetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr port;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ CGrafPtr port;
+ GDHandle gdh;
#ifndef GetGWorld
- PyMac_PRECHECK(GetGWorld);
+ PyMac_PRECHECK(GetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetGWorld(&port,
- &gdh);
- _res = Py_BuildValue("O&O&",
- GrafObj_New, port,
- ResObj_New, gdh);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetGWorld(&port,
+ &gdh);
+ _res = Py_BuildValue("O&O&",
+ GrafObj_New, port,
+ ResObj_New, gdh);
+ return _res;
}
static PyObject *Qdoffs_SetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr port;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ CGrafPtr port;
+ GDHandle gdh;
#ifndef SetGWorld
- PyMac_PRECHECK(SetGWorld);
+ PyMac_PRECHECK(SetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- GrafObj_Convert, &port,
- OptResObj_Convert, &gdh))
- return NULL;
- SetGWorld(port,
- gdh);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ GrafObj_Convert, &port,
+ OptResObj_Convert, &gdh))
+ return NULL;
+ SetGWorld(port,
+ gdh);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_CTabChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CTabHandle ctab;
+ PyObject *_res = NULL;
+ CTabHandle ctab;
#ifndef CTabChanged
- PyMac_PRECHECK(CTabChanged);
+ PyMac_PRECHECK(CTabChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- OptResObj_Convert, &ctab))
- return NULL;
- CTabChanged(ctab);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptResObj_Convert, &ctab))
+ return NULL;
+ CTabChanged(ctab);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_PixPatChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixPatHandle ppat;
+ PyObject *_res = NULL;
+ PixPatHandle ppat;
#ifndef PixPatChanged
- PyMac_PRECHECK(PixPatChanged);
+ PyMac_PRECHECK(PixPatChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &ppat))
- return NULL;
- PixPatChanged(ppat);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &ppat))
+ return NULL;
+ PixPatChanged(ppat);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_PortChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GrafPtr port;
+ PyObject *_res = NULL;
+ GrafPtr port;
#ifndef PortChanged
- PyMac_PRECHECK(PortChanged);
+ PyMac_PRECHECK(PortChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &port))
- return NULL;
- PortChanged(port);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &port))
+ return NULL;
+ PortChanged(port);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_GDeviceChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ GDHandle gdh;
#ifndef GDeviceChanged
- PyMac_PRECHECK(GDeviceChanged);
+ PyMac_PRECHECK(GDeviceChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- OptResObj_Convert, &gdh))
- return NULL;
- GDeviceChanged(gdh);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptResObj_Convert, &gdh))
+ return NULL;
+ GDeviceChanged(gdh);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_AllowPurgePixels(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ PixMapHandle pm;
#ifndef AllowPurgePixels
- PyMac_PRECHECK(AllowPurgePixels);
+ PyMac_PRECHECK(AllowPurgePixels);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- AllowPurgePixels(pm);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ AllowPurgePixels(pm);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_NoPurgePixels(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ PixMapHandle pm;
#ifndef NoPurgePixels
- PyMac_PRECHECK(NoPurgePixels);
+ PyMac_PRECHECK(NoPurgePixels);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- NoPurgePixels(pm);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ NoPurgePixels(pm);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_GetPixelsState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- GWorldFlags _rv;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ GWorldFlags _rv;
+ PixMapHandle pm;
#ifndef GetPixelsState
- PyMac_PRECHECK(GetPixelsState);
+ PyMac_PRECHECK(GetPixelsState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- _rv = GetPixelsState(pm);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ _rv = GetPixelsState(pm);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qdoffs_SetPixelsState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle pm;
- GWorldFlags state;
+ PyObject *_res = NULL;
+ PixMapHandle pm;
+ GWorldFlags state;
#ifndef SetPixelsState
- PyMac_PRECHECK(SetPixelsState);
+ PyMac_PRECHECK(SetPixelsState);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- ResObj_Convert, &pm,
- &state))
- return NULL;
- SetPixelsState(pm,
- state);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ResObj_Convert, &pm,
+ &state))
+ return NULL;
+ SetPixelsState(pm,
+ state);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_GetPixRowBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ long _rv;
+ PixMapHandle pm;
#ifndef GetPixRowBytes
- PyMac_PRECHECK(GetPixRowBytes);
+ PyMac_PRECHECK(GetPixRowBytes);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- _rv = GetPixRowBytes(pm);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ _rv = GetPixRowBytes(pm);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qdoffs_NewScreenBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- QDErr _err;
- Rect globalRect;
- Boolean purgeable;
- GDHandle gdh;
- PixMapHandle offscreenPixMap;
+ PyObject *_res = NULL;
+ QDErr _err;
+ Rect globalRect;
+ Boolean purgeable;
+ GDHandle gdh;
+ PixMapHandle offscreenPixMap;
#ifndef NewScreenBuffer
- PyMac_PRECHECK(NewScreenBuffer);
+ PyMac_PRECHECK(NewScreenBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetRect, &globalRect,
- &purgeable))
- return NULL;
- _err = NewScreenBuffer(&globalRect,
- purgeable,
- &gdh,
- &offscreenPixMap);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- ResObj_New, gdh,
- ResObj_New, offscreenPixMap);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetRect, &globalRect,
+ &purgeable))
+ return NULL;
+ _err = NewScreenBuffer(&globalRect,
+ purgeable,
+ &gdh,
+ &offscreenPixMap);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ ResObj_New, gdh,
+ ResObj_New, offscreenPixMap);
+ return _res;
}
static PyObject *Qdoffs_DisposeScreenBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle offscreenPixMap;
+ PyObject *_res = NULL;
+ PixMapHandle offscreenPixMap;
#ifndef DisposeScreenBuffer
- PyMac_PRECHECK(DisposeScreenBuffer);
+ PyMac_PRECHECK(DisposeScreenBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &offscreenPixMap))
- return NULL;
- DisposeScreenBuffer(offscreenPixMap);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &offscreenPixMap))
+ return NULL;
+ DisposeScreenBuffer(offscreenPixMap);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qdoffs_QDDone(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- GrafPtr port;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ GrafPtr port;
#ifndef QDDone
- PyMac_PRECHECK(QDDone);
+ PyMac_PRECHECK(QDDone);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &port))
- return NULL;
- _rv = QDDone(port);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &port))
+ return NULL;
+ _rv = QDDone(port);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qdoffs_OffscreenVersion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef OffscreenVersion
- PyMac_PRECHECK(OffscreenVersion);
+ PyMac_PRECHECK(OffscreenVersion);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = OffscreenVersion();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = OffscreenVersion();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qdoffs_NewTempScreenBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- QDErr _err;
- Rect globalRect;
- Boolean purgeable;
- GDHandle gdh;
- PixMapHandle offscreenPixMap;
+ PyObject *_res = NULL;
+ QDErr _err;
+ Rect globalRect;
+ Boolean purgeable;
+ GDHandle gdh;
+ PixMapHandle offscreenPixMap;
#ifndef NewTempScreenBuffer
- PyMac_PRECHECK(NewTempScreenBuffer);
+ PyMac_PRECHECK(NewTempScreenBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetRect, &globalRect,
- &purgeable))
- return NULL;
- _err = NewTempScreenBuffer(&globalRect,
- purgeable,
- &gdh,
- &offscreenPixMap);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- ResObj_New, gdh,
- ResObj_New, offscreenPixMap);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetRect, &globalRect,
+ &purgeable))
+ return NULL;
+ _err = NewTempScreenBuffer(&globalRect,
+ purgeable,
+ &gdh,
+ &offscreenPixMap);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ ResObj_New, gdh,
+ ResObj_New, offscreenPixMap);
+ return _res;
}
static PyObject *Qdoffs_PixMap32Bit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- PixMapHandle pmHandle;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ PixMapHandle pmHandle;
#ifndef PixMap32Bit
- PyMac_PRECHECK(PixMap32Bit);
+ PyMac_PRECHECK(PixMap32Bit);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pmHandle))
- return NULL;
- _rv = PixMap32Bit(pmHandle);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pmHandle))
+ return NULL;
+ _rv = PixMap32Bit(pmHandle);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Qdoffs_GetPixMapBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- PixMapHandle pm;
- int from, length;
- char *cp;
+ PixMapHandle pm;
+ int from, length;
+ char *cp;
- if ( !PyArg_ParseTuple(_args, "O&ii", ResObj_Convert, &pm, &from, &length) )
- return NULL;
- cp = GetPixBaseAddr(pm)+from;
- _res = PyString_FromStringAndSize(cp, length);
- return _res;
+ if ( !PyArg_ParseTuple(_args, "O&ii", ResObj_Convert, &pm, &from, &length) )
+ return NULL;
+ cp = GetPixBaseAddr(pm)+from;
+ _res = PyString_FromStringAndSize(cp, length);
+ return _res;
}
static PyObject *Qdoffs_PutPixMapBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- PixMapHandle pm;
- int from, length;
- char *cp, *icp;
+ PixMapHandle pm;
+ int from, length;
+ char *cp, *icp;
- if ( !PyArg_ParseTuple(_args, "O&is#", ResObj_Convert, &pm, &from, &icp, &length) )
- return NULL;
- cp = GetPixBaseAddr(pm)+from;
- memcpy(cp, icp, length);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if ( !PyArg_ParseTuple(_args, "O&is#", ResObj_Convert, &pm, &from, &icp, &length) )
+ return NULL;
+ cp = GetPixBaseAddr(pm)+from;
+ memcpy(cp, icp, length);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Qdoffs_methods[] = {
#ifndef __LP64__
- {"NewGWorld", (PyCFunction)Qdoffs_NewGWorld, 1,
- PyDoc_STR("(short PixelDepth, Rect boundsRect, CTabHandle cTable, GDHandle aGDevice, GWorldFlags flags) -> (GWorldPtr offscreenGWorld)")},
- {"LockPixels", (PyCFunction)Qdoffs_LockPixels, 1,
- PyDoc_STR("(PixMapHandle pm) -> (Boolean _rv)")},
- {"UnlockPixels", (PyCFunction)Qdoffs_UnlockPixels, 1,
- PyDoc_STR("(PixMapHandle pm) -> None")},
- {"UpdateGWorld", (PyCFunction)Qdoffs_UpdateGWorld, 1,
- PyDoc_STR("(short pixelDepth, Rect boundsRect, CTabHandle cTable, GDHandle aGDevice, GWorldFlags flags) -> (GWorldFlags _rv, GWorldPtr offscreenGWorld)")},
- {"GetGWorld", (PyCFunction)Qdoffs_GetGWorld, 1,
- PyDoc_STR("() -> (CGrafPtr port, GDHandle gdh)")},
- {"SetGWorld", (PyCFunction)Qdoffs_SetGWorld, 1,
- PyDoc_STR("(CGrafPtr port, GDHandle gdh) -> None")},
- {"CTabChanged", (PyCFunction)Qdoffs_CTabChanged, 1,
- PyDoc_STR("(CTabHandle ctab) -> None")},
- {"PixPatChanged", (PyCFunction)Qdoffs_PixPatChanged, 1,
- PyDoc_STR("(PixPatHandle ppat) -> None")},
- {"PortChanged", (PyCFunction)Qdoffs_PortChanged, 1,
- PyDoc_STR("(GrafPtr port) -> None")},
- {"GDeviceChanged", (PyCFunction)Qdoffs_GDeviceChanged, 1,
- PyDoc_STR("(GDHandle gdh) -> None")},
- {"AllowPurgePixels", (PyCFunction)Qdoffs_AllowPurgePixels, 1,
- PyDoc_STR("(PixMapHandle pm) -> None")},
- {"NoPurgePixels", (PyCFunction)Qdoffs_NoPurgePixels, 1,
- PyDoc_STR("(PixMapHandle pm) -> None")},
- {"GetPixelsState", (PyCFunction)Qdoffs_GetPixelsState, 1,
- PyDoc_STR("(PixMapHandle pm) -> (GWorldFlags _rv)")},
- {"SetPixelsState", (PyCFunction)Qdoffs_SetPixelsState, 1,
- PyDoc_STR("(PixMapHandle pm, GWorldFlags state) -> None")},
- {"GetPixRowBytes", (PyCFunction)Qdoffs_GetPixRowBytes, 1,
- PyDoc_STR("(PixMapHandle pm) -> (long _rv)")},
- {"NewScreenBuffer", (PyCFunction)Qdoffs_NewScreenBuffer, 1,
- PyDoc_STR("(Rect globalRect, Boolean purgeable) -> (GDHandle gdh, PixMapHandle offscreenPixMap)")},
- {"DisposeScreenBuffer", (PyCFunction)Qdoffs_DisposeScreenBuffer, 1,
- PyDoc_STR("(PixMapHandle offscreenPixMap) -> None")},
- {"QDDone", (PyCFunction)Qdoffs_QDDone, 1,
- PyDoc_STR("(GrafPtr port) -> (Boolean _rv)")},
- {"OffscreenVersion", (PyCFunction)Qdoffs_OffscreenVersion, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"NewTempScreenBuffer", (PyCFunction)Qdoffs_NewTempScreenBuffer, 1,
- PyDoc_STR("(Rect globalRect, Boolean purgeable) -> (GDHandle gdh, PixMapHandle offscreenPixMap)")},
- {"PixMap32Bit", (PyCFunction)Qdoffs_PixMap32Bit, 1,
- PyDoc_STR("(PixMapHandle pmHandle) -> (Boolean _rv)")},
- {"GetPixMapBytes", (PyCFunction)Qdoffs_GetPixMapBytes, 1,
- PyDoc_STR("(pixmap, int start, int size) -> string. Return bytes from the pixmap")},
- {"PutPixMapBytes", (PyCFunction)Qdoffs_PutPixMapBytes, 1,
- PyDoc_STR("(pixmap, int start, string data). Store bytes into the pixmap")},
+ {"NewGWorld", (PyCFunction)Qdoffs_NewGWorld, 1,
+ PyDoc_STR("(short PixelDepth, Rect boundsRect, CTabHandle cTable, GDHandle aGDevice, GWorldFlags flags) -> (GWorldPtr offscreenGWorld)")},
+ {"LockPixels", (PyCFunction)Qdoffs_LockPixels, 1,
+ PyDoc_STR("(PixMapHandle pm) -> (Boolean _rv)")},
+ {"UnlockPixels", (PyCFunction)Qdoffs_UnlockPixels, 1,
+ PyDoc_STR("(PixMapHandle pm) -> None")},
+ {"UpdateGWorld", (PyCFunction)Qdoffs_UpdateGWorld, 1,
+ PyDoc_STR("(short pixelDepth, Rect boundsRect, CTabHandle cTable, GDHandle aGDevice, GWorldFlags flags) -> (GWorldFlags _rv, GWorldPtr offscreenGWorld)")},
+ {"GetGWorld", (PyCFunction)Qdoffs_GetGWorld, 1,
+ PyDoc_STR("() -> (CGrafPtr port, GDHandle gdh)")},
+ {"SetGWorld", (PyCFunction)Qdoffs_SetGWorld, 1,
+ PyDoc_STR("(CGrafPtr port, GDHandle gdh) -> None")},
+ {"CTabChanged", (PyCFunction)Qdoffs_CTabChanged, 1,
+ PyDoc_STR("(CTabHandle ctab) -> None")},
+ {"PixPatChanged", (PyCFunction)Qdoffs_PixPatChanged, 1,
+ PyDoc_STR("(PixPatHandle ppat) -> None")},
+ {"PortChanged", (PyCFunction)Qdoffs_PortChanged, 1,
+ PyDoc_STR("(GrafPtr port) -> None")},
+ {"GDeviceChanged", (PyCFunction)Qdoffs_GDeviceChanged, 1,
+ PyDoc_STR("(GDHandle gdh) -> None")},
+ {"AllowPurgePixels", (PyCFunction)Qdoffs_AllowPurgePixels, 1,
+ PyDoc_STR("(PixMapHandle pm) -> None")},
+ {"NoPurgePixels", (PyCFunction)Qdoffs_NoPurgePixels, 1,
+ PyDoc_STR("(PixMapHandle pm) -> None")},
+ {"GetPixelsState", (PyCFunction)Qdoffs_GetPixelsState, 1,
+ PyDoc_STR("(PixMapHandle pm) -> (GWorldFlags _rv)")},
+ {"SetPixelsState", (PyCFunction)Qdoffs_SetPixelsState, 1,
+ PyDoc_STR("(PixMapHandle pm, GWorldFlags state) -> None")},
+ {"GetPixRowBytes", (PyCFunction)Qdoffs_GetPixRowBytes, 1,
+ PyDoc_STR("(PixMapHandle pm) -> (long _rv)")},
+ {"NewScreenBuffer", (PyCFunction)Qdoffs_NewScreenBuffer, 1,
+ PyDoc_STR("(Rect globalRect, Boolean purgeable) -> (GDHandle gdh, PixMapHandle offscreenPixMap)")},
+ {"DisposeScreenBuffer", (PyCFunction)Qdoffs_DisposeScreenBuffer, 1,
+ PyDoc_STR("(PixMapHandle offscreenPixMap) -> None")},
+ {"QDDone", (PyCFunction)Qdoffs_QDDone, 1,
+ PyDoc_STR("(GrafPtr port) -> (Boolean _rv)")},
+ {"OffscreenVersion", (PyCFunction)Qdoffs_OffscreenVersion, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"NewTempScreenBuffer", (PyCFunction)Qdoffs_NewTempScreenBuffer, 1,
+ PyDoc_STR("(Rect globalRect, Boolean purgeable) -> (GDHandle gdh, PixMapHandle offscreenPixMap)")},
+ {"PixMap32Bit", (PyCFunction)Qdoffs_PixMap32Bit, 1,
+ PyDoc_STR("(PixMapHandle pmHandle) -> (Boolean _rv)")},
+ {"GetPixMapBytes", (PyCFunction)Qdoffs_GetPixMapBytes, 1,
+ PyDoc_STR("(pixmap, int start, int size) -> string. Return bytes from the pixmap")},
+ {"PutPixMapBytes", (PyCFunction)Qdoffs_PutPixMapBytes, 1,
+ PyDoc_STR("(pixmap, int start, string data). Store bytes into the pixmap")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -690,31 +690,31 @@ static PyMethodDef Qdoffs_methods[] = {
void init_Qdoffs(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(GWorldPtr, GWorldObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GWorldPtr, GWorldObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(GWorldPtr, GWorldObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(GWorldPtr, GWorldObj_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_Qdoffs", Qdoffs_methods);
+ m = Py_InitModule("_Qdoffs", Qdoffs_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Qdoffs_Error = PyMac_GetOSErrException();
- if (Qdoffs_Error == NULL ||
- PyDict_SetItemString(d, "Error", Qdoffs_Error) != 0)
- return;
- GWorld_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&GWorld_Type) < 0) return;
- Py_INCREF(&GWorld_Type);
- PyModule_AddObject(m, "GWorld", (PyObject *)&GWorld_Type);
- /* Backward-compatible name */
- Py_INCREF(&GWorld_Type);
- PyModule_AddObject(m, "GWorldType", (PyObject *)&GWorld_Type);
+ d = PyModule_GetDict(m);
+ Qdoffs_Error = PyMac_GetOSErrException();
+ if (Qdoffs_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Qdoffs_Error) != 0)
+ return;
+ GWorld_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&GWorld_Type) < 0) return;
+ Py_INCREF(&GWorld_Type);
+ PyModule_AddObject(m, "GWorld", (PyObject *)&GWorld_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&GWorld_Type);
+ PyModule_AddObject(m, "GWorldType", (PyObject *)&GWorld_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/qt/_Qtmodule.c b/Mac/Modules/qt/_Qtmodule.c
index 4845e4a..bf67cda 100644
--- a/Mac/Modules/qt/_Qtmodule.c
+++ b/Mac/Modules/qt/_Qtmodule.c
@@ -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)
@@ -56,37 +56,37 @@ extern int _MediaObj_Convert(PyObject *, Media *);
static PyObject *
QtTimeRecord_New(TimeRecord *itself)
{
- if (itself->base)
- return Py_BuildValue("O&lO&", PyMac_Buildwide, &itself->value, itself->scale,
- TimeBaseObj_New, itself->base);
- else
- return Py_BuildValue("O&lO", PyMac_Buildwide, &itself->value, itself->scale,
- Py_None);
+ if (itself->base)
+ return Py_BuildValue("O&lO&", PyMac_Buildwide, &itself->value, itself->scale,
+ TimeBaseObj_New, itself->base);
+ else
+ return Py_BuildValue("O&lO", PyMac_Buildwide, &itself->value, itself->scale,
+ Py_None);
}
static int
QtTimeRecord_Convert(PyObject *v, TimeRecord *p_itself)
{
- PyObject *base = NULL;
- if( !PyArg_ParseTuple(v, "O&l|O", PyMac_Getwide, &p_itself->value, &p_itself->scale,
- &base) )
- return 0;
- if ( base == NULL || base == Py_None )
- p_itself->base = NULL;
- else
- if ( !TimeBaseObj_Convert(base, &p_itself->base) )
- return 0;
- return 1;
+ PyObject *base = NULL;
+ if( !PyArg_ParseTuple(v, "O&l|O", PyMac_Getwide, &p_itself->value, &p_itself->scale,
+ &base) )
+ return 0;
+ if ( base == NULL || base == Py_None )
+ p_itself->base = NULL;
+ else
+ if ( !TimeBaseObj_Convert(base, &p_itself->base) )
+ return 0;
+ return 1;
}
static int
QtMusicMIDIPacket_Convert(PyObject *v, MusicMIDIPacket *p_itself)
{
- int dummy;
+ int dummy;
- if( !PyArg_ParseTuple(v, "hls#", &p_itself->length, &p_itself->reserved, p_itself->data, dummy) )
- return 0;
- return 1;
+ if( !PyArg_ParseTuple(v, "hls#", &p_itself->length, &p_itself->reserved, p_itself->data, dummy) )
+ return 0;
+ return 1;
}
@@ -101,47 +101,47 @@ PyTypeObject IdleManager_Type;
#define IdleManagerObj_Check(x) ((x)->ob_type == &IdleManager_Type || PyObject_TypeCheck((x), &IdleManager_Type))
typedef struct IdleManagerObject {
- PyObject_HEAD
- IdleManager ob_itself;
+ PyObject_HEAD
+ IdleManager ob_itself;
} IdleManagerObject;
PyObject *IdleManagerObj_New(IdleManager itself)
{
- IdleManagerObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create IdleManager from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(IdleManagerObject, &IdleManager_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ IdleManagerObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create IdleManager from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(IdleManagerObject, &IdleManager_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int IdleManagerObj_Convert(PyObject *v, IdleManager *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!IdleManagerObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "IdleManager required");
- return 0;
- }
- *p_itself = ((IdleManagerObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!IdleManagerObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "IdleManager required");
+ return 0;
+ }
+ *p_itself = ((IdleManagerObject *)v)->ob_itself;
+ return 1;
}
static void IdleManagerObj_dealloc(IdleManagerObject *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 PyMethodDef IdleManagerObj_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#define IdleManagerObj_getsetlist NULL
@@ -158,61 +158,61 @@ static PyMethodDef IdleManagerObj_methods[] = {
static PyObject *IdleManagerObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- IdleManager itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ IdleManager itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, IdleManagerObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((IdleManagerObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, IdleManagerObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((IdleManagerObject *)_self)->ob_itself = itself;
+ return _self;
}
#define IdleManagerObj_tp_free PyObject_Del
PyTypeObject IdleManager_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.IdleManager", /*tp_name*/
- sizeof(IdleManagerObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) IdleManagerObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) IdleManagerObj_compare, /*tp_compare*/
- (reprfunc) IdleManagerObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) IdleManagerObj_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*/
- IdleManagerObj_methods, /* tp_methods */
- 0, /*tp_members*/
- IdleManagerObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- IdleManagerObj_tp_init, /* tp_init */
- IdleManagerObj_tp_alloc, /* tp_alloc */
- IdleManagerObj_tp_new, /* tp_new */
- IdleManagerObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.IdleManager", /*tp_name*/
+ sizeof(IdleManagerObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) IdleManagerObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) IdleManagerObj_compare, /*tp_compare*/
+ (reprfunc) IdleManagerObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) IdleManagerObj_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*/
+ IdleManagerObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ IdleManagerObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ IdleManagerObj_tp_init, /* tp_init */
+ IdleManagerObj_tp_alloc, /* tp_alloc */
+ IdleManagerObj_tp_new, /* tp_new */
+ IdleManagerObj_tp_free, /* tp_free */
};
/* ------------------ End object type IdleManager ------------------- */
@@ -225,1043 +225,1043 @@ PyTypeObject MovieController_Type;
#define MovieCtlObj_Check(x) ((x)->ob_type == &MovieController_Type || PyObject_TypeCheck((x), &MovieController_Type))
typedef struct MovieControllerObject {
- PyObject_HEAD
- MovieController ob_itself;
+ PyObject_HEAD
+ MovieController ob_itself;
} MovieControllerObject;
PyObject *MovieCtlObj_New(MovieController itself)
{
- MovieControllerObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create MovieController from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(MovieControllerObject, &MovieController_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ MovieControllerObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create MovieController from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(MovieControllerObject, &MovieController_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int MovieCtlObj_Convert(PyObject *v, MovieController *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!MovieCtlObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "MovieController required");
- return 0;
- }
- *p_itself = ((MovieControllerObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!MovieCtlObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "MovieController required");
+ return 0;
+ }
+ *p_itself = ((MovieControllerObject *)v)->ob_itself;
+ return 1;
}
static void MovieCtlObj_dealloc(MovieControllerObject *self)
{
- if (self->ob_itself) DisposeMovieController(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_itself) DisposeMovieController(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *MovieCtlObj_MCSetMovie(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Movie theMovie;
- WindowPtr movieWindow;
- Point where;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Movie theMovie;
+ WindowPtr movieWindow;
+ Point where;
#ifndef MCSetMovie
- PyMac_PRECHECK(MCSetMovie);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- MovieObj_Convert, &theMovie,
- WinObj_Convert, &movieWindow,
- PyMac_GetPoint, &where))
- return NULL;
- _rv = MCSetMovie(_self->ob_itself,
- theMovie,
- movieWindow,
- where);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MCSetMovie);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ MovieObj_Convert, &theMovie,
+ WinObj_Convert, &movieWindow,
+ PyMac_GetPoint, &where))
+ return NULL;
+ _rv = MCSetMovie(_self->ob_itself,
+ theMovie,
+ movieWindow,
+ where);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetIndMovie(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
- short index;
+ PyObject *_res = NULL;
+ Movie _rv;
+ short index;
#ifndef MCGetIndMovie
- PyMac_PRECHECK(MCGetIndMovie);
+ PyMac_PRECHECK(MCGetIndMovie);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- _rv = MCGetIndMovie(_self->ob_itself,
- index);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ _rv = MCGetIndMovie(_self->ob_itself,
+ index);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCRemoveAllMovies(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCRemoveAllMovies
- PyMac_PRECHECK(MCRemoveAllMovies);
+ PyMac_PRECHECK(MCRemoveAllMovies);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCRemoveAllMovies(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCRemoveAllMovies(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCRemoveAMovie(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Movie m;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Movie m;
#ifndef MCRemoveAMovie
- PyMac_PRECHECK(MCRemoveAMovie);
+ PyMac_PRECHECK(MCRemoveAMovie);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MovieObj_Convert, &m))
- return NULL;
- _rv = MCRemoveAMovie(_self->ob_itself,
- m);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MovieObj_Convert, &m))
+ return NULL;
+ _rv = MCRemoveAMovie(_self->ob_itself,
+ m);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCRemoveMovie(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCRemoveMovie
- PyMac_PRECHECK(MCRemoveMovie);
+ PyMac_PRECHECK(MCRemoveMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCRemoveMovie(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCRemoveMovie(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCIsPlayerEvent(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- EventRecord e;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ EventRecord e;
#ifndef MCIsPlayerEvent
- PyMac_PRECHECK(MCIsPlayerEvent);
+ PyMac_PRECHECK(MCIsPlayerEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &e))
- return NULL;
- _rv = MCIsPlayerEvent(_self->ob_itself,
- &e);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &e))
+ return NULL;
+ _rv = MCIsPlayerEvent(_self->ob_itself,
+ &e);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCDoAction(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- short action;
- void * params;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ short action;
+ void * params;
#ifndef MCDoAction
- PyMac_PRECHECK(MCDoAction);
+ PyMac_PRECHECK(MCDoAction);
#endif
- if (!PyArg_ParseTuple(_args, "hs",
- &action,
- &params))
- return NULL;
- _rv = MCDoAction(_self->ob_itself,
- action,
- params);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hs",
+ &action,
+ &params))
+ return NULL;
+ _rv = MCDoAction(_self->ob_itself,
+ action,
+ params);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetControllerAttached(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Boolean attach;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Boolean attach;
#ifndef MCSetControllerAttached
- PyMac_PRECHECK(MCSetControllerAttached);
+ PyMac_PRECHECK(MCSetControllerAttached);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &attach))
- return NULL;
- _rv = MCSetControllerAttached(_self->ob_itself,
- attach);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &attach))
+ return NULL;
+ _rv = MCSetControllerAttached(_self->ob_itself,
+ attach);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCIsControllerAttached(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCIsControllerAttached
- PyMac_PRECHECK(MCIsControllerAttached);
+ PyMac_PRECHECK(MCIsControllerAttached);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCIsControllerAttached(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCIsControllerAttached(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetControllerPort(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- CGrafPtr gp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ CGrafPtr gp;
#ifndef MCSetControllerPort
- PyMac_PRECHECK(MCSetControllerPort);
+ PyMac_PRECHECK(MCSetControllerPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &gp))
- return NULL;
- _rv = MCSetControllerPort(_self->ob_itself,
- gp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &gp))
+ return NULL;
+ _rv = MCSetControllerPort(_self->ob_itself,
+ gp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetControllerPort(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
#ifndef MCGetControllerPort
- PyMac_PRECHECK(MCGetControllerPort);
+ PyMac_PRECHECK(MCGetControllerPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetControllerPort(_self->ob_itself);
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetControllerPort(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetVisible(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Boolean visible;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Boolean visible;
#ifndef MCSetVisible
- PyMac_PRECHECK(MCSetVisible);
+ PyMac_PRECHECK(MCSetVisible);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &visible))
- return NULL;
- _rv = MCSetVisible(_self->ob_itself,
- visible);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &visible))
+ return NULL;
+ _rv = MCSetVisible(_self->ob_itself,
+ visible);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetVisible(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCGetVisible
- PyMac_PRECHECK(MCGetVisible);
+ PyMac_PRECHECK(MCGetVisible);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetVisible(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetVisible(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetControllerBoundsRect(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Rect bounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Rect bounds;
#ifndef MCGetControllerBoundsRect
- PyMac_PRECHECK(MCGetControllerBoundsRect);
+ PyMac_PRECHECK(MCGetControllerBoundsRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetControllerBoundsRect(_self->ob_itself,
- &bounds);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetControllerBoundsRect(_self->ob_itself,
+ &bounds);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetControllerBoundsRect(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Rect bounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Rect bounds;
#ifndef MCSetControllerBoundsRect
- PyMac_PRECHECK(MCSetControllerBoundsRect);
+ PyMac_PRECHECK(MCSetControllerBoundsRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &bounds))
- return NULL;
- _rv = MCSetControllerBoundsRect(_self->ob_itself,
- &bounds);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &bounds))
+ return NULL;
+ _rv = MCSetControllerBoundsRect(_self->ob_itself,
+ &bounds);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetControllerBoundsRgn(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef MCGetControllerBoundsRgn
- PyMac_PRECHECK(MCGetControllerBoundsRgn);
+ PyMac_PRECHECK(MCGetControllerBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetControllerBoundsRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetControllerBoundsRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetWindowRgn(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- WindowPtr w;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ WindowPtr w;
#ifndef MCGetWindowRgn
- PyMac_PRECHECK(MCGetWindowRgn);
+ PyMac_PRECHECK(MCGetWindowRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &w))
- return NULL;
- _rv = MCGetWindowRgn(_self->ob_itself,
- w);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &w))
+ return NULL;
+ _rv = MCGetWindowRgn(_self->ob_itself,
+ w);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCMovieChanged(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Movie m;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Movie m;
#ifndef MCMovieChanged
- PyMac_PRECHECK(MCMovieChanged);
+ PyMac_PRECHECK(MCMovieChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MovieObj_Convert, &m))
- return NULL;
- _rv = MCMovieChanged(_self->ob_itself,
- m);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MovieObj_Convert, &m))
+ return NULL;
+ _rv = MCMovieChanged(_self->ob_itself,
+ m);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetDuration(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TimeValue duration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TimeValue duration;
#ifndef MCSetDuration
- PyMac_PRECHECK(MCSetDuration);
+ PyMac_PRECHECK(MCSetDuration);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &duration))
- return NULL;
- _rv = MCSetDuration(_self->ob_itself,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &duration))
+ return NULL;
+ _rv = MCSetDuration(_self->ob_itself,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetCurrentTime(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
- TimeScale scale;
+ PyObject *_res = NULL;
+ TimeValue _rv;
+ TimeScale scale;
#ifndef MCGetCurrentTime
- PyMac_PRECHECK(MCGetCurrentTime);
+ PyMac_PRECHECK(MCGetCurrentTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetCurrentTime(_self->ob_itself,
- &scale);
- _res = Py_BuildValue("ll",
- _rv,
- scale);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetCurrentTime(_self->ob_itself,
+ &scale);
+ _res = Py_BuildValue("ll",
+ _rv,
+ scale);
+ return _res;
}
static PyObject *MovieCtlObj_MCNewAttachedController(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Movie theMovie;
- WindowPtr w;
- Point where;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Movie theMovie;
+ WindowPtr w;
+ Point where;
#ifndef MCNewAttachedController
- PyMac_PRECHECK(MCNewAttachedController);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- MovieObj_Convert, &theMovie,
- WinObj_Convert, &w,
- PyMac_GetPoint, &where))
- return NULL;
- _rv = MCNewAttachedController(_self->ob_itself,
- theMovie,
- w,
- where);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MCNewAttachedController);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ MovieObj_Convert, &theMovie,
+ WinObj_Convert, &w,
+ PyMac_GetPoint, &where))
+ return NULL;
+ _rv = MCNewAttachedController(_self->ob_itself,
+ theMovie,
+ w,
+ where);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCDraw(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- WindowPtr w;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ WindowPtr w;
#ifndef MCDraw
- PyMac_PRECHECK(MCDraw);
+ PyMac_PRECHECK(MCDraw);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &w))
- return NULL;
- _rv = MCDraw(_self->ob_itself,
- w);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &w))
+ return NULL;
+ _rv = MCDraw(_self->ob_itself,
+ w);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCActivate(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- WindowPtr w;
- Boolean activate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ WindowPtr w;
+ Boolean activate;
#ifndef MCActivate
- PyMac_PRECHECK(MCActivate);
+ PyMac_PRECHECK(MCActivate);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- WinObj_Convert, &w,
- &activate))
- return NULL;
- _rv = MCActivate(_self->ob_itself,
- w,
- activate);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ WinObj_Convert, &w,
+ &activate))
+ return NULL;
+ _rv = MCActivate(_self->ob_itself,
+ w,
+ activate);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCIdle(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCIdle
- PyMac_PRECHECK(MCIdle);
+ PyMac_PRECHECK(MCIdle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCIdle(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCIdle(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCKey(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SInt8 key;
- long modifiers;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SInt8 key;
+ long modifiers;
#ifndef MCKey
- PyMac_PRECHECK(MCKey);
+ PyMac_PRECHECK(MCKey);
#endif
- if (!PyArg_ParseTuple(_args, "bl",
- &key,
- &modifiers))
- return NULL;
- _rv = MCKey(_self->ob_itself,
- key,
- modifiers);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "bl",
+ &key,
+ &modifiers))
+ return NULL;
+ _rv = MCKey(_self->ob_itself,
+ key,
+ modifiers);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCClick(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- WindowPtr w;
- Point where;
- long when;
- long modifiers;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ WindowPtr w;
+ Point where;
+ long when;
+ long modifiers;
#ifndef MCClick
- PyMac_PRECHECK(MCClick);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&ll",
- WinObj_Convert, &w,
- PyMac_GetPoint, &where,
- &when,
- &modifiers))
- return NULL;
- _rv = MCClick(_self->ob_itself,
- w,
- where,
- when,
- modifiers);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MCClick);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&ll",
+ WinObj_Convert, &w,
+ PyMac_GetPoint, &where,
+ &when,
+ &modifiers))
+ return NULL;
+ _rv = MCClick(_self->ob_itself,
+ w,
+ where,
+ when,
+ modifiers);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCEnableEditing(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Boolean enabled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Boolean enabled;
#ifndef MCEnableEditing
- PyMac_PRECHECK(MCEnableEditing);
+ PyMac_PRECHECK(MCEnableEditing);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &enabled))
- return NULL;
- _rv = MCEnableEditing(_self->ob_itself,
- enabled);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &enabled))
+ return NULL;
+ _rv = MCEnableEditing(_self->ob_itself,
+ enabled);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCIsEditingEnabled(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef MCIsEditingEnabled
- PyMac_PRECHECK(MCIsEditingEnabled);
+ PyMac_PRECHECK(MCIsEditingEnabled);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCIsEditingEnabled(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCIsEditingEnabled(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCCopy(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
+ PyObject *_res = NULL;
+ Movie _rv;
#ifndef MCCopy
- PyMac_PRECHECK(MCCopy);
+ PyMac_PRECHECK(MCCopy);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCCopy(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCCopy(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCCut(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
+ PyObject *_res = NULL;
+ Movie _rv;
#ifndef MCCut
- PyMac_PRECHECK(MCCut);
+ PyMac_PRECHECK(MCCut);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCCut(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCCut(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCPaste(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Movie srcMovie;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Movie srcMovie;
#ifndef MCPaste
- PyMac_PRECHECK(MCPaste);
+ PyMac_PRECHECK(MCPaste);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MovieObj_Convert, &srcMovie))
- return NULL;
- _rv = MCPaste(_self->ob_itself,
- srcMovie);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MovieObj_Convert, &srcMovie))
+ return NULL;
+ _rv = MCPaste(_self->ob_itself,
+ srcMovie);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCClear(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCClear
- PyMac_PRECHECK(MCClear);
+ PyMac_PRECHECK(MCClear);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCClear(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCClear(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCUndo(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCUndo
- PyMac_PRECHECK(MCUndo);
+ PyMac_PRECHECK(MCUndo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCUndo(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCUndo(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCPositionController(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Rect movieRect;
- Rect controllerRect;
- long someFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Rect movieRect;
+ Rect controllerRect;
+ long someFlags;
#ifndef MCPositionController
- PyMac_PRECHECK(MCPositionController);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- PyMac_GetRect, &movieRect,
- PyMac_GetRect, &controllerRect,
- &someFlags))
- return NULL;
- _rv = MCPositionController(_self->ob_itself,
- &movieRect,
- &controllerRect,
- someFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MCPositionController);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ PyMac_GetRect, &movieRect,
+ PyMac_GetRect, &controllerRect,
+ &someFlags))
+ return NULL;
+ _rv = MCPositionController(_self->ob_itself,
+ &movieRect,
+ &controllerRect,
+ someFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetControllerInfo(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- long someFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ long someFlags;
#ifndef MCGetControllerInfo
- PyMac_PRECHECK(MCGetControllerInfo);
+ PyMac_PRECHECK(MCGetControllerInfo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetControllerInfo(_self->ob_itself,
- &someFlags);
- _res = Py_BuildValue("ll",
- _rv,
- someFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetControllerInfo(_self->ob_itself,
+ &someFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ someFlags);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetClip(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- RgnHandle theClip;
- RgnHandle movieClip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ RgnHandle theClip;
+ RgnHandle movieClip;
#ifndef MCSetClip
- PyMac_PRECHECK(MCSetClip);
+ PyMac_PRECHECK(MCSetClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &theClip,
- ResObj_Convert, &movieClip))
- return NULL;
- _rv = MCSetClip(_self->ob_itself,
- theClip,
- movieClip);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &theClip,
+ ResObj_Convert, &movieClip))
+ return NULL;
+ _rv = MCSetClip(_self->ob_itself,
+ theClip,
+ movieClip);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetClip(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- RgnHandle theClip;
- RgnHandle movieClip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ RgnHandle theClip;
+ RgnHandle movieClip;
#ifndef MCGetClip
- PyMac_PRECHECK(MCGetClip);
+ PyMac_PRECHECK(MCGetClip);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCGetClip(_self->ob_itself,
- &theClip,
- &movieClip);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, theClip,
- ResObj_New, movieClip);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCGetClip(_self->ob_itself,
+ &theClip,
+ &movieClip);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, theClip,
+ ResObj_New, movieClip);
+ return _res;
}
static PyObject *MovieCtlObj_MCDrawBadge(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- RgnHandle movieRgn;
- RgnHandle badgeRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ RgnHandle movieRgn;
+ RgnHandle badgeRgn;
#ifndef MCDrawBadge
- PyMac_PRECHECK(MCDrawBadge);
+ PyMac_PRECHECK(MCDrawBadge);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &movieRgn))
- return NULL;
- _rv = MCDrawBadge(_self->ob_itself,
- movieRgn,
- &badgeRgn);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, badgeRgn);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &movieRgn))
+ return NULL;
+ _rv = MCDrawBadge(_self->ob_itself,
+ movieRgn,
+ &badgeRgn);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, badgeRgn);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetUpEditMenu(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- long modifiers;
- MenuHandle mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ long modifiers;
+ MenuHandle mh;
#ifndef MCSetUpEditMenu
- PyMac_PRECHECK(MCSetUpEditMenu);
+ PyMac_PRECHECK(MCSetUpEditMenu);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &modifiers,
- MenuObj_Convert, &mh))
- return NULL;
- _rv = MCSetUpEditMenu(_self->ob_itself,
- modifiers,
- mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &modifiers,
+ MenuObj_Convert, &mh))
+ return NULL;
+ _rv = MCSetUpEditMenu(_self->ob_itself,
+ modifiers,
+ mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetMenuString(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- long modifiers;
- short item;
- Str255 aString;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ long modifiers;
+ short item;
+ Str255 aString;
#ifndef MCGetMenuString
- PyMac_PRECHECK(MCGetMenuString);
-#endif
- if (!PyArg_ParseTuple(_args, "lhO&",
- &modifiers,
- &item,
- PyMac_GetStr255, aString))
- return NULL;
- _rv = MCGetMenuString(_self->ob_itself,
- modifiers,
- item,
- aString);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MCGetMenuString);
+#endif
+ if (!PyArg_ParseTuple(_args, "lhO&",
+ &modifiers,
+ &item,
+ PyMac_GetStr255, aString))
+ return NULL;
+ _rv = MCGetMenuString(_self->ob_itself,
+ modifiers,
+ item,
+ aString);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCPtInController(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Point thePt;
- Boolean inController;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Point thePt;
+ Boolean inController;
#ifndef MCPtInController
- PyMac_PRECHECK(MCPtInController);
+ PyMac_PRECHECK(MCPtInController);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &thePt))
- return NULL;
- _rv = MCPtInController(_self->ob_itself,
- thePt,
- &inController);
- _res = Py_BuildValue("lb",
- _rv,
- inController);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &thePt))
+ return NULL;
+ _rv = MCPtInController(_self->ob_itself,
+ thePt,
+ &inController);
+ _res = Py_BuildValue("lb",
+ _rv,
+ inController);
+ return _res;
}
static PyObject *MovieCtlObj_MCInvalidate(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- WindowPtr w;
- RgnHandle invalidRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ WindowPtr w;
+ RgnHandle invalidRgn;
#ifndef MCInvalidate
- PyMac_PRECHECK(MCInvalidate);
+ PyMac_PRECHECK(MCInvalidate);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- WinObj_Convert, &w,
- ResObj_Convert, &invalidRgn))
- return NULL;
- _rv = MCInvalidate(_self->ob_itself,
- w,
- invalidRgn);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ WinObj_Convert, &w,
+ ResObj_Convert, &invalidRgn))
+ return NULL;
+ _rv = MCInvalidate(_self->ob_itself,
+ w,
+ invalidRgn);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCAdjustCursor(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- WindowPtr w;
- Point where;
- long modifiers;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ WindowPtr w;
+ Point where;
+ long modifiers;
#ifndef MCAdjustCursor
- PyMac_PRECHECK(MCAdjustCursor);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- WinObj_Convert, &w,
- PyMac_GetPoint, &where,
- &modifiers))
- return NULL;
- _rv = MCAdjustCursor(_self->ob_itself,
- w,
- where,
- modifiers);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MCAdjustCursor);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ WinObj_Convert, &w,
+ PyMac_GetPoint, &where,
+ &modifiers))
+ return NULL;
+ _rv = MCAdjustCursor(_self->ob_itself,
+ w,
+ where,
+ modifiers);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCGetInterfaceElement(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MCInterfaceElement whichElement;
- void * element;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MCInterfaceElement whichElement;
+ void * element;
#ifndef MCGetInterfaceElement
- PyMac_PRECHECK(MCGetInterfaceElement);
+ PyMac_PRECHECK(MCGetInterfaceElement);
#endif
- if (!PyArg_ParseTuple(_args, "ls",
- &whichElement,
- &element))
- return NULL;
- _rv = MCGetInterfaceElement(_self->ob_itself,
- whichElement,
- element);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ls",
+ &whichElement,
+ &element))
+ return NULL;
+ _rv = MCGetInterfaceElement(_self->ob_itself,
+ whichElement,
+ element);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCAddMovieSegment(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Movie srcMovie;
- Boolean scaled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Movie srcMovie;
+ Boolean scaled;
#ifndef MCAddMovieSegment
- PyMac_PRECHECK(MCAddMovieSegment);
+ PyMac_PRECHECK(MCAddMovieSegment);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- MovieObj_Convert, &srcMovie,
- &scaled))
- return NULL;
- _rv = MCAddMovieSegment(_self->ob_itself,
- srcMovie,
- scaled);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ MovieObj_Convert, &srcMovie,
+ &scaled))
+ return NULL;
+ _rv = MCAddMovieSegment(_self->ob_itself,
+ srcMovie,
+ scaled);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCTrimMovieSegment(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef MCTrimMovieSegment
- PyMac_PRECHECK(MCTrimMovieSegment);
+ PyMac_PRECHECK(MCTrimMovieSegment);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MCTrimMovieSegment(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MCTrimMovieSegment(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetIdleManager(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- IdleManager im;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ IdleManager im;
#ifndef MCSetIdleManager
- PyMac_PRECHECK(MCSetIdleManager);
+ PyMac_PRECHECK(MCSetIdleManager);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- IdleManagerObj_Convert, &im))
- return NULL;
- _rv = MCSetIdleManager(_self->ob_itself,
- im);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ IdleManagerObj_Convert, &im))
+ return NULL;
+ _rv = MCSetIdleManager(_self->ob_itself,
+ im);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieCtlObj_MCSetControllerCapabilities(MovieControllerObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- long flags;
- long flagsMask;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ long flags;
+ long flagsMask;
#ifndef MCSetControllerCapabilities
- PyMac_PRECHECK(MCSetControllerCapabilities);
+ PyMac_PRECHECK(MCSetControllerCapabilities);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &flags,
- &flagsMask))
- return NULL;
- _rv = MCSetControllerCapabilities(_self->ob_itself,
- flags,
- flagsMask);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &flags,
+ &flagsMask))
+ return NULL;
+ _rv = MCSetControllerCapabilities(_self->ob_itself,
+ flags,
+ flagsMask);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyMethodDef MovieCtlObj_methods[] = {
- {"MCSetMovie", (PyCFunction)MovieCtlObj_MCSetMovie, 1,
- PyDoc_STR("(Movie theMovie, WindowPtr movieWindow, Point where) -> (ComponentResult _rv)")},
- {"MCGetIndMovie", (PyCFunction)MovieCtlObj_MCGetIndMovie, 1,
- PyDoc_STR("(short index) -> (Movie _rv)")},
- {"MCRemoveAllMovies", (PyCFunction)MovieCtlObj_MCRemoveAllMovies, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCRemoveAMovie", (PyCFunction)MovieCtlObj_MCRemoveAMovie, 1,
- PyDoc_STR("(Movie m) -> (ComponentResult _rv)")},
- {"MCRemoveMovie", (PyCFunction)MovieCtlObj_MCRemoveMovie, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCIsPlayerEvent", (PyCFunction)MovieCtlObj_MCIsPlayerEvent, 1,
- PyDoc_STR("(EventRecord e) -> (ComponentResult _rv)")},
- {"MCDoAction", (PyCFunction)MovieCtlObj_MCDoAction, 1,
- PyDoc_STR("(short action, void * params) -> (ComponentResult _rv)")},
- {"MCSetControllerAttached", (PyCFunction)MovieCtlObj_MCSetControllerAttached, 1,
- PyDoc_STR("(Boolean attach) -> (ComponentResult _rv)")},
- {"MCIsControllerAttached", (PyCFunction)MovieCtlObj_MCIsControllerAttached, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCSetControllerPort", (PyCFunction)MovieCtlObj_MCSetControllerPort, 1,
- PyDoc_STR("(CGrafPtr gp) -> (ComponentResult _rv)")},
- {"MCGetControllerPort", (PyCFunction)MovieCtlObj_MCGetControllerPort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {"MCSetVisible", (PyCFunction)MovieCtlObj_MCSetVisible, 1,
- PyDoc_STR("(Boolean visible) -> (ComponentResult _rv)")},
- {"MCGetVisible", (PyCFunction)MovieCtlObj_MCGetVisible, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCGetControllerBoundsRect", (PyCFunction)MovieCtlObj_MCGetControllerBoundsRect, 1,
- PyDoc_STR("() -> (ComponentResult _rv, Rect bounds)")},
- {"MCSetControllerBoundsRect", (PyCFunction)MovieCtlObj_MCSetControllerBoundsRect, 1,
- PyDoc_STR("(Rect bounds) -> (ComponentResult _rv)")},
- {"MCGetControllerBoundsRgn", (PyCFunction)MovieCtlObj_MCGetControllerBoundsRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"MCGetWindowRgn", (PyCFunction)MovieCtlObj_MCGetWindowRgn, 1,
- PyDoc_STR("(WindowPtr w) -> (RgnHandle _rv)")},
- {"MCMovieChanged", (PyCFunction)MovieCtlObj_MCMovieChanged, 1,
- PyDoc_STR("(Movie m) -> (ComponentResult _rv)")},
- {"MCSetDuration", (PyCFunction)MovieCtlObj_MCSetDuration, 1,
- PyDoc_STR("(TimeValue duration) -> (ComponentResult _rv)")},
- {"MCGetCurrentTime", (PyCFunction)MovieCtlObj_MCGetCurrentTime, 1,
- PyDoc_STR("() -> (TimeValue _rv, TimeScale scale)")},
- {"MCNewAttachedController", (PyCFunction)MovieCtlObj_MCNewAttachedController, 1,
- PyDoc_STR("(Movie theMovie, WindowPtr w, Point where) -> (ComponentResult _rv)")},
- {"MCDraw", (PyCFunction)MovieCtlObj_MCDraw, 1,
- PyDoc_STR("(WindowPtr w) -> (ComponentResult _rv)")},
- {"MCActivate", (PyCFunction)MovieCtlObj_MCActivate, 1,
- PyDoc_STR("(WindowPtr w, Boolean activate) -> (ComponentResult _rv)")},
- {"MCIdle", (PyCFunction)MovieCtlObj_MCIdle, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCKey", (PyCFunction)MovieCtlObj_MCKey, 1,
- PyDoc_STR("(SInt8 key, long modifiers) -> (ComponentResult _rv)")},
- {"MCClick", (PyCFunction)MovieCtlObj_MCClick, 1,
- PyDoc_STR("(WindowPtr w, Point where, long when, long modifiers) -> (ComponentResult _rv)")},
- {"MCEnableEditing", (PyCFunction)MovieCtlObj_MCEnableEditing, 1,
- PyDoc_STR("(Boolean enabled) -> (ComponentResult _rv)")},
- {"MCIsEditingEnabled", (PyCFunction)MovieCtlObj_MCIsEditingEnabled, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"MCCopy", (PyCFunction)MovieCtlObj_MCCopy, 1,
- PyDoc_STR("() -> (Movie _rv)")},
- {"MCCut", (PyCFunction)MovieCtlObj_MCCut, 1,
- PyDoc_STR("() -> (Movie _rv)")},
- {"MCPaste", (PyCFunction)MovieCtlObj_MCPaste, 1,
- PyDoc_STR("(Movie srcMovie) -> (ComponentResult _rv)")},
- {"MCClear", (PyCFunction)MovieCtlObj_MCClear, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCUndo", (PyCFunction)MovieCtlObj_MCUndo, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCPositionController", (PyCFunction)MovieCtlObj_MCPositionController, 1,
- PyDoc_STR("(Rect movieRect, Rect controllerRect, long someFlags) -> (ComponentResult _rv)")},
- {"MCGetControllerInfo", (PyCFunction)MovieCtlObj_MCGetControllerInfo, 1,
- PyDoc_STR("() -> (ComponentResult _rv, long someFlags)")},
- {"MCSetClip", (PyCFunction)MovieCtlObj_MCSetClip, 1,
- PyDoc_STR("(RgnHandle theClip, RgnHandle movieClip) -> (ComponentResult _rv)")},
- {"MCGetClip", (PyCFunction)MovieCtlObj_MCGetClip, 1,
- PyDoc_STR("() -> (ComponentResult _rv, RgnHandle theClip, RgnHandle movieClip)")},
- {"MCDrawBadge", (PyCFunction)MovieCtlObj_MCDrawBadge, 1,
- PyDoc_STR("(RgnHandle movieRgn) -> (ComponentResult _rv, RgnHandle badgeRgn)")},
- {"MCSetUpEditMenu", (PyCFunction)MovieCtlObj_MCSetUpEditMenu, 1,
- PyDoc_STR("(long modifiers, MenuHandle mh) -> (ComponentResult _rv)")},
- {"MCGetMenuString", (PyCFunction)MovieCtlObj_MCGetMenuString, 1,
- PyDoc_STR("(long modifiers, short item, Str255 aString) -> (ComponentResult _rv)")},
- {"MCPtInController", (PyCFunction)MovieCtlObj_MCPtInController, 1,
- PyDoc_STR("(Point thePt) -> (ComponentResult _rv, Boolean inController)")},
- {"MCInvalidate", (PyCFunction)MovieCtlObj_MCInvalidate, 1,
- PyDoc_STR("(WindowPtr w, RgnHandle invalidRgn) -> (ComponentResult _rv)")},
- {"MCAdjustCursor", (PyCFunction)MovieCtlObj_MCAdjustCursor, 1,
- PyDoc_STR("(WindowPtr w, Point where, long modifiers) -> (ComponentResult _rv)")},
- {"MCGetInterfaceElement", (PyCFunction)MovieCtlObj_MCGetInterfaceElement, 1,
- PyDoc_STR("(MCInterfaceElement whichElement, void * element) -> (ComponentResult _rv)")},
- {"MCAddMovieSegment", (PyCFunction)MovieCtlObj_MCAddMovieSegment, 1,
- PyDoc_STR("(Movie srcMovie, Boolean scaled) -> (ComponentResult _rv)")},
- {"MCTrimMovieSegment", (PyCFunction)MovieCtlObj_MCTrimMovieSegment, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"MCSetIdleManager", (PyCFunction)MovieCtlObj_MCSetIdleManager, 1,
- PyDoc_STR("(IdleManager im) -> (ComponentResult _rv)")},
- {"MCSetControllerCapabilities", (PyCFunction)MovieCtlObj_MCSetControllerCapabilities, 1,
- PyDoc_STR("(long flags, long flagsMask) -> (ComponentResult _rv)")},
- {NULL, NULL, 0}
+ {"MCSetMovie", (PyCFunction)MovieCtlObj_MCSetMovie, 1,
+ PyDoc_STR("(Movie theMovie, WindowPtr movieWindow, Point where) -> (ComponentResult _rv)")},
+ {"MCGetIndMovie", (PyCFunction)MovieCtlObj_MCGetIndMovie, 1,
+ PyDoc_STR("(short index) -> (Movie _rv)")},
+ {"MCRemoveAllMovies", (PyCFunction)MovieCtlObj_MCRemoveAllMovies, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCRemoveAMovie", (PyCFunction)MovieCtlObj_MCRemoveAMovie, 1,
+ PyDoc_STR("(Movie m) -> (ComponentResult _rv)")},
+ {"MCRemoveMovie", (PyCFunction)MovieCtlObj_MCRemoveMovie, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCIsPlayerEvent", (PyCFunction)MovieCtlObj_MCIsPlayerEvent, 1,
+ PyDoc_STR("(EventRecord e) -> (ComponentResult _rv)")},
+ {"MCDoAction", (PyCFunction)MovieCtlObj_MCDoAction, 1,
+ PyDoc_STR("(short action, void * params) -> (ComponentResult _rv)")},
+ {"MCSetControllerAttached", (PyCFunction)MovieCtlObj_MCSetControllerAttached, 1,
+ PyDoc_STR("(Boolean attach) -> (ComponentResult _rv)")},
+ {"MCIsControllerAttached", (PyCFunction)MovieCtlObj_MCIsControllerAttached, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCSetControllerPort", (PyCFunction)MovieCtlObj_MCSetControllerPort, 1,
+ PyDoc_STR("(CGrafPtr gp) -> (ComponentResult _rv)")},
+ {"MCGetControllerPort", (PyCFunction)MovieCtlObj_MCGetControllerPort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {"MCSetVisible", (PyCFunction)MovieCtlObj_MCSetVisible, 1,
+ PyDoc_STR("(Boolean visible) -> (ComponentResult _rv)")},
+ {"MCGetVisible", (PyCFunction)MovieCtlObj_MCGetVisible, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCGetControllerBoundsRect", (PyCFunction)MovieCtlObj_MCGetControllerBoundsRect, 1,
+ PyDoc_STR("() -> (ComponentResult _rv, Rect bounds)")},
+ {"MCSetControllerBoundsRect", (PyCFunction)MovieCtlObj_MCSetControllerBoundsRect, 1,
+ PyDoc_STR("(Rect bounds) -> (ComponentResult _rv)")},
+ {"MCGetControllerBoundsRgn", (PyCFunction)MovieCtlObj_MCGetControllerBoundsRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"MCGetWindowRgn", (PyCFunction)MovieCtlObj_MCGetWindowRgn, 1,
+ PyDoc_STR("(WindowPtr w) -> (RgnHandle _rv)")},
+ {"MCMovieChanged", (PyCFunction)MovieCtlObj_MCMovieChanged, 1,
+ PyDoc_STR("(Movie m) -> (ComponentResult _rv)")},
+ {"MCSetDuration", (PyCFunction)MovieCtlObj_MCSetDuration, 1,
+ PyDoc_STR("(TimeValue duration) -> (ComponentResult _rv)")},
+ {"MCGetCurrentTime", (PyCFunction)MovieCtlObj_MCGetCurrentTime, 1,
+ PyDoc_STR("() -> (TimeValue _rv, TimeScale scale)")},
+ {"MCNewAttachedController", (PyCFunction)MovieCtlObj_MCNewAttachedController, 1,
+ PyDoc_STR("(Movie theMovie, WindowPtr w, Point where) -> (ComponentResult _rv)")},
+ {"MCDraw", (PyCFunction)MovieCtlObj_MCDraw, 1,
+ PyDoc_STR("(WindowPtr w) -> (ComponentResult _rv)")},
+ {"MCActivate", (PyCFunction)MovieCtlObj_MCActivate, 1,
+ PyDoc_STR("(WindowPtr w, Boolean activate) -> (ComponentResult _rv)")},
+ {"MCIdle", (PyCFunction)MovieCtlObj_MCIdle, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCKey", (PyCFunction)MovieCtlObj_MCKey, 1,
+ PyDoc_STR("(SInt8 key, long modifiers) -> (ComponentResult _rv)")},
+ {"MCClick", (PyCFunction)MovieCtlObj_MCClick, 1,
+ PyDoc_STR("(WindowPtr w, Point where, long when, long modifiers) -> (ComponentResult _rv)")},
+ {"MCEnableEditing", (PyCFunction)MovieCtlObj_MCEnableEditing, 1,
+ PyDoc_STR("(Boolean enabled) -> (ComponentResult _rv)")},
+ {"MCIsEditingEnabled", (PyCFunction)MovieCtlObj_MCIsEditingEnabled, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"MCCopy", (PyCFunction)MovieCtlObj_MCCopy, 1,
+ PyDoc_STR("() -> (Movie _rv)")},
+ {"MCCut", (PyCFunction)MovieCtlObj_MCCut, 1,
+ PyDoc_STR("() -> (Movie _rv)")},
+ {"MCPaste", (PyCFunction)MovieCtlObj_MCPaste, 1,
+ PyDoc_STR("(Movie srcMovie) -> (ComponentResult _rv)")},
+ {"MCClear", (PyCFunction)MovieCtlObj_MCClear, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCUndo", (PyCFunction)MovieCtlObj_MCUndo, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCPositionController", (PyCFunction)MovieCtlObj_MCPositionController, 1,
+ PyDoc_STR("(Rect movieRect, Rect controllerRect, long someFlags) -> (ComponentResult _rv)")},
+ {"MCGetControllerInfo", (PyCFunction)MovieCtlObj_MCGetControllerInfo, 1,
+ PyDoc_STR("() -> (ComponentResult _rv, long someFlags)")},
+ {"MCSetClip", (PyCFunction)MovieCtlObj_MCSetClip, 1,
+ PyDoc_STR("(RgnHandle theClip, RgnHandle movieClip) -> (ComponentResult _rv)")},
+ {"MCGetClip", (PyCFunction)MovieCtlObj_MCGetClip, 1,
+ PyDoc_STR("() -> (ComponentResult _rv, RgnHandle theClip, RgnHandle movieClip)")},
+ {"MCDrawBadge", (PyCFunction)MovieCtlObj_MCDrawBadge, 1,
+ PyDoc_STR("(RgnHandle movieRgn) -> (ComponentResult _rv, RgnHandle badgeRgn)")},
+ {"MCSetUpEditMenu", (PyCFunction)MovieCtlObj_MCSetUpEditMenu, 1,
+ PyDoc_STR("(long modifiers, MenuHandle mh) -> (ComponentResult _rv)")},
+ {"MCGetMenuString", (PyCFunction)MovieCtlObj_MCGetMenuString, 1,
+ PyDoc_STR("(long modifiers, short item, Str255 aString) -> (ComponentResult _rv)")},
+ {"MCPtInController", (PyCFunction)MovieCtlObj_MCPtInController, 1,
+ PyDoc_STR("(Point thePt) -> (ComponentResult _rv, Boolean inController)")},
+ {"MCInvalidate", (PyCFunction)MovieCtlObj_MCInvalidate, 1,
+ PyDoc_STR("(WindowPtr w, RgnHandle invalidRgn) -> (ComponentResult _rv)")},
+ {"MCAdjustCursor", (PyCFunction)MovieCtlObj_MCAdjustCursor, 1,
+ PyDoc_STR("(WindowPtr w, Point where, long modifiers) -> (ComponentResult _rv)")},
+ {"MCGetInterfaceElement", (PyCFunction)MovieCtlObj_MCGetInterfaceElement, 1,
+ PyDoc_STR("(MCInterfaceElement whichElement, void * element) -> (ComponentResult _rv)")},
+ {"MCAddMovieSegment", (PyCFunction)MovieCtlObj_MCAddMovieSegment, 1,
+ PyDoc_STR("(Movie srcMovie, Boolean scaled) -> (ComponentResult _rv)")},
+ {"MCTrimMovieSegment", (PyCFunction)MovieCtlObj_MCTrimMovieSegment, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"MCSetIdleManager", (PyCFunction)MovieCtlObj_MCSetIdleManager, 1,
+ PyDoc_STR("(IdleManager im) -> (ComponentResult _rv)")},
+ {"MCSetControllerCapabilities", (PyCFunction)MovieCtlObj_MCSetControllerCapabilities, 1,
+ PyDoc_STR("(long flags, long flagsMask) -> (ComponentResult _rv)")},
+ {NULL, NULL, 0}
};
#define MovieCtlObj_getsetlist NULL
@@ -1278,61 +1278,61 @@ static PyMethodDef MovieCtlObj_methods[] = {
static PyObject *MovieCtlObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- MovieController itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ MovieController itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MovieCtlObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((MovieControllerObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MovieCtlObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((MovieControllerObject *)_self)->ob_itself = itself;
+ return _self;
}
#define MovieCtlObj_tp_free PyObject_Del
PyTypeObject MovieController_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.MovieController", /*tp_name*/
- sizeof(MovieControllerObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) MovieCtlObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) MovieCtlObj_compare, /*tp_compare*/
- (reprfunc) MovieCtlObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) MovieCtlObj_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*/
- MovieCtlObj_methods, /* tp_methods */
- 0, /*tp_members*/
- MovieCtlObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- MovieCtlObj_tp_init, /* tp_init */
- MovieCtlObj_tp_alloc, /* tp_alloc */
- MovieCtlObj_tp_new, /* tp_new */
- MovieCtlObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.MovieController", /*tp_name*/
+ sizeof(MovieControllerObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) MovieCtlObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) MovieCtlObj_compare, /*tp_compare*/
+ (reprfunc) MovieCtlObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) MovieCtlObj_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*/
+ MovieCtlObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ MovieCtlObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ MovieCtlObj_tp_init, /* tp_init */
+ MovieCtlObj_tp_alloc, /* tp_alloc */
+ MovieCtlObj_tp_new, /* tp_new */
+ MovieCtlObj_tp_free, /* tp_free */
};
/* ---------------- End object type MovieController ----------------- */
@@ -1345,417 +1345,417 @@ PyTypeObject TimeBase_Type;
#define TimeBaseObj_Check(x) ((x)->ob_type == &TimeBase_Type || PyObject_TypeCheck((x), &TimeBase_Type))
typedef struct TimeBaseObject {
- PyObject_HEAD
- TimeBase ob_itself;
+ PyObject_HEAD
+ TimeBase ob_itself;
} TimeBaseObject;
PyObject *TimeBaseObj_New(TimeBase itself)
{
- TimeBaseObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create TimeBase from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(TimeBaseObject, &TimeBase_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ TimeBaseObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create TimeBase from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(TimeBaseObject, &TimeBase_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int TimeBaseObj_Convert(PyObject *v, TimeBase *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!TimeBaseObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "TimeBase required");
- return 0;
- }
- *p_itself = ((TimeBaseObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!TimeBaseObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "TimeBase required");
+ return 0;
+ }
+ *p_itself = ((TimeBaseObject *)v)->ob_itself;
+ return 1;
}
static void TimeBaseObj_dealloc(TimeBaseObject *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 *TimeBaseObj_DisposeTimeBase(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DisposeTimeBase
- PyMac_PRECHECK(DisposeTimeBase);
+ PyMac_PRECHECK(DisposeTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DisposeTimeBase(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DisposeTimeBase(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseTime(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
- TimeScale s;
- TimeRecord tr;
+ PyObject *_res = NULL;
+ TimeValue _rv;
+ TimeScale s;
+ TimeRecord tr;
#ifndef GetTimeBaseTime
- PyMac_PRECHECK(GetTimeBaseTime);
+ PyMac_PRECHECK(GetTimeBaseTime);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &s))
- return NULL;
- _rv = GetTimeBaseTime(_self->ob_itself,
- s,
- &tr);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &tr);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &s))
+ return NULL;
+ _rv = GetTimeBaseTime(_self->ob_itself,
+ s,
+ &tr);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &tr);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseTime(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord tr;
+ PyObject *_res = NULL;
+ TimeRecord tr;
#ifndef SetTimeBaseTime
- PyMac_PRECHECK(SetTimeBaseTime);
+ PyMac_PRECHECK(SetTimeBaseTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QtTimeRecord_Convert, &tr))
- return NULL;
- SetTimeBaseTime(_self->ob_itself,
- &tr);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QtTimeRecord_Convert, &tr))
+ return NULL;
+ SetTimeBaseTime(_self->ob_itself,
+ &tr);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseValue(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue t;
- TimeScale s;
+ PyObject *_res = NULL;
+ TimeValue t;
+ TimeScale s;
#ifndef SetTimeBaseValue
- PyMac_PRECHECK(SetTimeBaseValue);
+ PyMac_PRECHECK(SetTimeBaseValue);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &t,
- &s))
- return NULL;
- SetTimeBaseValue(_self->ob_itself,
- t,
- s);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &t,
+ &s))
+ return NULL;
+ SetTimeBaseValue(_self->ob_itself,
+ t,
+ s);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseRate(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
+ PyObject *_res = NULL;
+ Fixed _rv;
#ifndef GetTimeBaseRate
- PyMac_PRECHECK(GetTimeBaseRate);
+ PyMac_PRECHECK(GetTimeBaseRate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTimeBaseRate(_self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTimeBaseRate(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseRate(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed r;
+ PyObject *_res = NULL;
+ Fixed r;
#ifndef SetTimeBaseRate
- PyMac_PRECHECK(SetTimeBaseRate);
+ PyMac_PRECHECK(SetTimeBaseRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &r))
- return NULL;
- SetTimeBaseRate(_self->ob_itself,
- r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &r))
+ return NULL;
+ SetTimeBaseRate(_self->ob_itself,
+ r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseStartTime(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
- TimeScale s;
- TimeRecord tr;
+ PyObject *_res = NULL;
+ TimeValue _rv;
+ TimeScale s;
+ TimeRecord tr;
#ifndef GetTimeBaseStartTime
- PyMac_PRECHECK(GetTimeBaseStartTime);
+ PyMac_PRECHECK(GetTimeBaseStartTime);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &s))
- return NULL;
- _rv = GetTimeBaseStartTime(_self->ob_itself,
- s,
- &tr);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &tr);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &s))
+ return NULL;
+ _rv = GetTimeBaseStartTime(_self->ob_itself,
+ s,
+ &tr);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &tr);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseStartTime(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord tr;
+ PyObject *_res = NULL;
+ TimeRecord tr;
#ifndef SetTimeBaseStartTime
- PyMac_PRECHECK(SetTimeBaseStartTime);
+ PyMac_PRECHECK(SetTimeBaseStartTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QtTimeRecord_Convert, &tr))
- return NULL;
- SetTimeBaseStartTime(_self->ob_itself,
- &tr);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QtTimeRecord_Convert, &tr))
+ return NULL;
+ SetTimeBaseStartTime(_self->ob_itself,
+ &tr);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseStopTime(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
- TimeScale s;
- TimeRecord tr;
+ PyObject *_res = NULL;
+ TimeValue _rv;
+ TimeScale s;
+ TimeRecord tr;
#ifndef GetTimeBaseStopTime
- PyMac_PRECHECK(GetTimeBaseStopTime);
+ PyMac_PRECHECK(GetTimeBaseStopTime);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &s))
- return NULL;
- _rv = GetTimeBaseStopTime(_self->ob_itself,
- s,
- &tr);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &tr);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &s))
+ return NULL;
+ _rv = GetTimeBaseStopTime(_self->ob_itself,
+ s,
+ &tr);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &tr);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseStopTime(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord tr;
+ PyObject *_res = NULL;
+ TimeRecord tr;
#ifndef SetTimeBaseStopTime
- PyMac_PRECHECK(SetTimeBaseStopTime);
+ PyMac_PRECHECK(SetTimeBaseStopTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QtTimeRecord_Convert, &tr))
- return NULL;
- SetTimeBaseStopTime(_self->ob_itself,
- &tr);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QtTimeRecord_Convert, &tr))
+ return NULL;
+ SetTimeBaseStopTime(_self->ob_itself,
+ &tr);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseFlags(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetTimeBaseFlags
- PyMac_PRECHECK(GetTimeBaseFlags);
+ PyMac_PRECHECK(GetTimeBaseFlags);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTimeBaseFlags(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTimeBaseFlags(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseFlags(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long timeBaseFlags;
+ PyObject *_res = NULL;
+ long timeBaseFlags;
#ifndef SetTimeBaseFlags
- PyMac_PRECHECK(SetTimeBaseFlags);
+ PyMac_PRECHECK(SetTimeBaseFlags);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &timeBaseFlags))
- return NULL;
- SetTimeBaseFlags(_self->ob_itself,
- timeBaseFlags);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &timeBaseFlags))
+ return NULL;
+ SetTimeBaseFlags(_self->ob_itself,
+ timeBaseFlags);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseMasterTimeBase(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeBase master;
- TimeRecord slaveZero;
+ PyObject *_res = NULL;
+ TimeBase master;
+ TimeRecord slaveZero;
#ifndef SetTimeBaseMasterTimeBase
- PyMac_PRECHECK(SetTimeBaseMasterTimeBase);
+ PyMac_PRECHECK(SetTimeBaseMasterTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- TimeBaseObj_Convert, &master,
- QtTimeRecord_Convert, &slaveZero))
- return NULL;
- SetTimeBaseMasterTimeBase(_self->ob_itself,
- master,
- &slaveZero);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ TimeBaseObj_Convert, &master,
+ QtTimeRecord_Convert, &slaveZero))
+ return NULL;
+ SetTimeBaseMasterTimeBase(_self->ob_itself,
+ master,
+ &slaveZero);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseMasterTimeBase(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeBase _rv;
+ PyObject *_res = NULL;
+ TimeBase _rv;
#ifndef GetTimeBaseMasterTimeBase
- PyMac_PRECHECK(GetTimeBaseMasterTimeBase);
+ PyMac_PRECHECK(GetTimeBaseMasterTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTimeBaseMasterTimeBase(_self->ob_itself);
- _res = Py_BuildValue("O&",
- TimeBaseObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTimeBaseMasterTimeBase(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ TimeBaseObj_New, _rv);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseMasterClock(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component clockMeister;
- TimeRecord slaveZero;
+ PyObject *_res = NULL;
+ Component clockMeister;
+ TimeRecord slaveZero;
#ifndef SetTimeBaseMasterClock
- PyMac_PRECHECK(SetTimeBaseMasterClock);
+ PyMac_PRECHECK(SetTimeBaseMasterClock);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpObj_Convert, &clockMeister,
- QtTimeRecord_Convert, &slaveZero))
- return NULL;
- SetTimeBaseMasterClock(_self->ob_itself,
- clockMeister,
- &slaveZero);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpObj_Convert, &clockMeister,
+ QtTimeRecord_Convert, &slaveZero))
+ return NULL;
+ SetTimeBaseMasterClock(_self->ob_itself,
+ clockMeister,
+ &slaveZero);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseMasterClock(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentInstance _rv;
+ PyObject *_res = NULL;
+ ComponentInstance _rv;
#ifndef GetTimeBaseMasterClock
- PyMac_PRECHECK(GetTimeBaseMasterClock);
+ PyMac_PRECHECK(GetTimeBaseMasterClock);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTimeBaseMasterClock(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTimeBaseMasterClock(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseStatus(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- TimeRecord unpinnedTime;
+ PyObject *_res = NULL;
+ long _rv;
+ TimeRecord unpinnedTime;
#ifndef GetTimeBaseStatus
- PyMac_PRECHECK(GetTimeBaseStatus);
+ PyMac_PRECHECK(GetTimeBaseStatus);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTimeBaseStatus(_self->ob_itself,
- &unpinnedTime);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &unpinnedTime);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTimeBaseStatus(_self->ob_itself,
+ &unpinnedTime);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &unpinnedTime);
+ return _res;
}
static PyObject *TimeBaseObj_SetTimeBaseZero(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord zero;
+ PyObject *_res = NULL;
+ TimeRecord zero;
#ifndef SetTimeBaseZero
- PyMac_PRECHECK(SetTimeBaseZero);
+ PyMac_PRECHECK(SetTimeBaseZero);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QtTimeRecord_Convert, &zero))
- return NULL;
- SetTimeBaseZero(_self->ob_itself,
- &zero);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QtTimeRecord_Convert, &zero))
+ return NULL;
+ SetTimeBaseZero(_self->ob_itself,
+ &zero);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TimeBaseObj_GetTimeBaseEffectiveRate(TimeBaseObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
+ PyObject *_res = NULL;
+ Fixed _rv;
#ifndef GetTimeBaseEffectiveRate
- PyMac_PRECHECK(GetTimeBaseEffectiveRate);
+ PyMac_PRECHECK(GetTimeBaseEffectiveRate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTimeBaseEffectiveRate(_self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTimeBaseEffectiveRate(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyMethodDef TimeBaseObj_methods[] = {
- {"DisposeTimeBase", (PyCFunction)TimeBaseObj_DisposeTimeBase, 1,
- PyDoc_STR("() -> None")},
- {"GetTimeBaseTime", (PyCFunction)TimeBaseObj_GetTimeBaseTime, 1,
- PyDoc_STR("(TimeScale s) -> (TimeValue _rv, TimeRecord tr)")},
- {"SetTimeBaseTime", (PyCFunction)TimeBaseObj_SetTimeBaseTime, 1,
- PyDoc_STR("(TimeRecord tr) -> None")},
- {"SetTimeBaseValue", (PyCFunction)TimeBaseObj_SetTimeBaseValue, 1,
- PyDoc_STR("(TimeValue t, TimeScale s) -> None")},
- {"GetTimeBaseRate", (PyCFunction)TimeBaseObj_GetTimeBaseRate, 1,
- PyDoc_STR("() -> (Fixed _rv)")},
- {"SetTimeBaseRate", (PyCFunction)TimeBaseObj_SetTimeBaseRate, 1,
- PyDoc_STR("(Fixed r) -> None")},
- {"GetTimeBaseStartTime", (PyCFunction)TimeBaseObj_GetTimeBaseStartTime, 1,
- PyDoc_STR("(TimeScale s) -> (TimeValue _rv, TimeRecord tr)")},
- {"SetTimeBaseStartTime", (PyCFunction)TimeBaseObj_SetTimeBaseStartTime, 1,
- PyDoc_STR("(TimeRecord tr) -> None")},
- {"GetTimeBaseStopTime", (PyCFunction)TimeBaseObj_GetTimeBaseStopTime, 1,
- PyDoc_STR("(TimeScale s) -> (TimeValue _rv, TimeRecord tr)")},
- {"SetTimeBaseStopTime", (PyCFunction)TimeBaseObj_SetTimeBaseStopTime, 1,
- PyDoc_STR("(TimeRecord tr) -> None")},
- {"GetTimeBaseFlags", (PyCFunction)TimeBaseObj_GetTimeBaseFlags, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SetTimeBaseFlags", (PyCFunction)TimeBaseObj_SetTimeBaseFlags, 1,
- PyDoc_STR("(long timeBaseFlags) -> None")},
- {"SetTimeBaseMasterTimeBase", (PyCFunction)TimeBaseObj_SetTimeBaseMasterTimeBase, 1,
- PyDoc_STR("(TimeBase master, TimeRecord slaveZero) -> None")},
- {"GetTimeBaseMasterTimeBase", (PyCFunction)TimeBaseObj_GetTimeBaseMasterTimeBase, 1,
- PyDoc_STR("() -> (TimeBase _rv)")},
- {"SetTimeBaseMasterClock", (PyCFunction)TimeBaseObj_SetTimeBaseMasterClock, 1,
- PyDoc_STR("(Component clockMeister, TimeRecord slaveZero) -> None")},
- {"GetTimeBaseMasterClock", (PyCFunction)TimeBaseObj_GetTimeBaseMasterClock, 1,
- PyDoc_STR("() -> (ComponentInstance _rv)")},
- {"GetTimeBaseStatus", (PyCFunction)TimeBaseObj_GetTimeBaseStatus, 1,
- PyDoc_STR("() -> (long _rv, TimeRecord unpinnedTime)")},
- {"SetTimeBaseZero", (PyCFunction)TimeBaseObj_SetTimeBaseZero, 1,
- PyDoc_STR("(TimeRecord zero) -> None")},
- {"GetTimeBaseEffectiveRate", (PyCFunction)TimeBaseObj_GetTimeBaseEffectiveRate, 1,
- PyDoc_STR("() -> (Fixed _rv)")},
- {NULL, NULL, 0}
+ {"DisposeTimeBase", (PyCFunction)TimeBaseObj_DisposeTimeBase, 1,
+ PyDoc_STR("() -> None")},
+ {"GetTimeBaseTime", (PyCFunction)TimeBaseObj_GetTimeBaseTime, 1,
+ PyDoc_STR("(TimeScale s) -> (TimeValue _rv, TimeRecord tr)")},
+ {"SetTimeBaseTime", (PyCFunction)TimeBaseObj_SetTimeBaseTime, 1,
+ PyDoc_STR("(TimeRecord tr) -> None")},
+ {"SetTimeBaseValue", (PyCFunction)TimeBaseObj_SetTimeBaseValue, 1,
+ PyDoc_STR("(TimeValue t, TimeScale s) -> None")},
+ {"GetTimeBaseRate", (PyCFunction)TimeBaseObj_GetTimeBaseRate, 1,
+ PyDoc_STR("() -> (Fixed _rv)")},
+ {"SetTimeBaseRate", (PyCFunction)TimeBaseObj_SetTimeBaseRate, 1,
+ PyDoc_STR("(Fixed r) -> None")},
+ {"GetTimeBaseStartTime", (PyCFunction)TimeBaseObj_GetTimeBaseStartTime, 1,
+ PyDoc_STR("(TimeScale s) -> (TimeValue _rv, TimeRecord tr)")},
+ {"SetTimeBaseStartTime", (PyCFunction)TimeBaseObj_SetTimeBaseStartTime, 1,
+ PyDoc_STR("(TimeRecord tr) -> None")},
+ {"GetTimeBaseStopTime", (PyCFunction)TimeBaseObj_GetTimeBaseStopTime, 1,
+ PyDoc_STR("(TimeScale s) -> (TimeValue _rv, TimeRecord tr)")},
+ {"SetTimeBaseStopTime", (PyCFunction)TimeBaseObj_SetTimeBaseStopTime, 1,
+ PyDoc_STR("(TimeRecord tr) -> None")},
+ {"GetTimeBaseFlags", (PyCFunction)TimeBaseObj_GetTimeBaseFlags, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SetTimeBaseFlags", (PyCFunction)TimeBaseObj_SetTimeBaseFlags, 1,
+ PyDoc_STR("(long timeBaseFlags) -> None")},
+ {"SetTimeBaseMasterTimeBase", (PyCFunction)TimeBaseObj_SetTimeBaseMasterTimeBase, 1,
+ PyDoc_STR("(TimeBase master, TimeRecord slaveZero) -> None")},
+ {"GetTimeBaseMasterTimeBase", (PyCFunction)TimeBaseObj_GetTimeBaseMasterTimeBase, 1,
+ PyDoc_STR("() -> (TimeBase _rv)")},
+ {"SetTimeBaseMasterClock", (PyCFunction)TimeBaseObj_SetTimeBaseMasterClock, 1,
+ PyDoc_STR("(Component clockMeister, TimeRecord slaveZero) -> None")},
+ {"GetTimeBaseMasterClock", (PyCFunction)TimeBaseObj_GetTimeBaseMasterClock, 1,
+ PyDoc_STR("() -> (ComponentInstance _rv)")},
+ {"GetTimeBaseStatus", (PyCFunction)TimeBaseObj_GetTimeBaseStatus, 1,
+ PyDoc_STR("() -> (long _rv, TimeRecord unpinnedTime)")},
+ {"SetTimeBaseZero", (PyCFunction)TimeBaseObj_SetTimeBaseZero, 1,
+ PyDoc_STR("(TimeRecord zero) -> None")},
+ {"GetTimeBaseEffectiveRate", (PyCFunction)TimeBaseObj_GetTimeBaseEffectiveRate, 1,
+ PyDoc_STR("() -> (Fixed _rv)")},
+ {NULL, NULL, 0}
};
#define TimeBaseObj_getsetlist NULL
@@ -1772,61 +1772,61 @@ static PyMethodDef TimeBaseObj_methods[] = {
static PyObject *TimeBaseObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- TimeBase itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ TimeBase itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TimeBaseObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((TimeBaseObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TimeBaseObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((TimeBaseObject *)_self)->ob_itself = itself;
+ return _self;
}
#define TimeBaseObj_tp_free PyObject_Del
PyTypeObject TimeBase_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.TimeBase", /*tp_name*/
- sizeof(TimeBaseObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) TimeBaseObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) TimeBaseObj_compare, /*tp_compare*/
- (reprfunc) TimeBaseObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) TimeBaseObj_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*/
- TimeBaseObj_methods, /* tp_methods */
- 0, /*tp_members*/
- TimeBaseObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- TimeBaseObj_tp_init, /* tp_init */
- TimeBaseObj_tp_alloc, /* tp_alloc */
- TimeBaseObj_tp_new, /* tp_new */
- TimeBaseObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.TimeBase", /*tp_name*/
+ sizeof(TimeBaseObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) TimeBaseObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) TimeBaseObj_compare, /*tp_compare*/
+ (reprfunc) TimeBaseObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) TimeBaseObj_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*/
+ TimeBaseObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ TimeBaseObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ TimeBaseObj_tp_init, /* tp_init */
+ TimeBaseObj_tp_alloc, /* tp_alloc */
+ TimeBaseObj_tp_new, /* tp_new */
+ TimeBaseObj_tp_free, /* tp_free */
};
/* -------------------- End object type TimeBase -------------------- */
@@ -1839,294 +1839,294 @@ PyTypeObject UserData_Type;
#define UserDataObj_Check(x) ((x)->ob_type == &UserData_Type || PyObject_TypeCheck((x), &UserData_Type))
typedef struct UserDataObject {
- PyObject_HEAD
- UserData ob_itself;
+ PyObject_HEAD
+ UserData ob_itself;
} UserDataObject;
PyObject *UserDataObj_New(UserData itself)
{
- UserDataObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create UserData from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(UserDataObject, &UserData_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ UserDataObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create UserData from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(UserDataObject, &UserData_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int UserDataObj_Convert(PyObject *v, UserData *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!UserDataObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "UserData required");
- return 0;
- }
- *p_itself = ((UserDataObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!UserDataObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "UserData required");
+ return 0;
+ }
+ *p_itself = ((UserDataObject *)v)->ob_itself;
+ return 1;
}
static void UserDataObj_dealloc(UserDataObject *self)
{
- if (self->ob_itself) DisposeUserData(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_itself) DisposeUserData(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *UserDataObj_GetUserData(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle data;
- OSType udType;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle data;
+ OSType udType;
+ long index;
#ifndef GetUserData
- PyMac_PRECHECK(GetUserData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- ResObj_Convert, &data,
- PyMac_GetOSType, &udType,
- &index))
- return NULL;
- _err = GetUserData(_self->ob_itself,
- data,
- udType,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(GetUserData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ ResObj_Convert, &data,
+ PyMac_GetOSType, &udType,
+ &index))
+ return NULL;
+ _err = GetUserData(_self->ob_itself,
+ data,
+ udType,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_AddUserData(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle data;
- OSType udType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle data;
+ OSType udType;
#ifndef AddUserData
- PyMac_PRECHECK(AddUserData);
+ PyMac_PRECHECK(AddUserData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &data,
- PyMac_GetOSType, &udType))
- return NULL;
- _err = AddUserData(_self->ob_itself,
- data,
- udType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &data,
+ PyMac_GetOSType, &udType))
+ return NULL;
+ _err = AddUserData(_self->ob_itself,
+ data,
+ udType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_RemoveUserData(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType udType;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType udType;
+ long index;
#ifndef RemoveUserData
- PyMac_PRECHECK(RemoveUserData);
+ PyMac_PRECHECK(RemoveUserData);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetOSType, &udType,
- &index))
- return NULL;
- _err = RemoveUserData(_self->ob_itself,
- udType,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetOSType, &udType,
+ &index))
+ return NULL;
+ _err = RemoveUserData(_self->ob_itself,
+ udType,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_CountUserDataType(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- OSType udType;
+ PyObject *_res = NULL;
+ short _rv;
+ OSType udType;
#ifndef CountUserDataType
- PyMac_PRECHECK(CountUserDataType);
+ PyMac_PRECHECK(CountUserDataType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &udType))
- return NULL;
- _rv = CountUserDataType(_self->ob_itself,
- udType);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &udType))
+ return NULL;
+ _rv = CountUserDataType(_self->ob_itself,
+ udType);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *UserDataObj_GetNextUserDataType(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- OSType udType;
+ PyObject *_res = NULL;
+ long _rv;
+ OSType udType;
#ifndef GetNextUserDataType
- PyMac_PRECHECK(GetNextUserDataType);
+ PyMac_PRECHECK(GetNextUserDataType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &udType))
- return NULL;
- _rv = GetNextUserDataType(_self->ob_itself,
- udType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &udType))
+ return NULL;
+ _rv = GetNextUserDataType(_self->ob_itself,
+ udType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *UserDataObj_AddUserDataText(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle data;
- OSType udType;
- long index;
- short itlRegionTag;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle data;
+ OSType udType;
+ long index;
+ short itlRegionTag;
#ifndef AddUserDataText
- PyMac_PRECHECK(AddUserDataText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lh",
- ResObj_Convert, &data,
- PyMac_GetOSType, &udType,
- &index,
- &itlRegionTag))
- return NULL;
- _err = AddUserDataText(_self->ob_itself,
- data,
- udType,
- index,
- itlRegionTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(AddUserDataText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lh",
+ ResObj_Convert, &data,
+ PyMac_GetOSType, &udType,
+ &index,
+ &itlRegionTag))
+ return NULL;
+ _err = AddUserDataText(_self->ob_itself,
+ data,
+ udType,
+ index,
+ itlRegionTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_GetUserDataText(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle data;
- OSType udType;
- long index;
- short itlRegionTag;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle data;
+ OSType udType;
+ long index;
+ short itlRegionTag;
#ifndef GetUserDataText
- PyMac_PRECHECK(GetUserDataText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lh",
- ResObj_Convert, &data,
- PyMac_GetOSType, &udType,
- &index,
- &itlRegionTag))
- return NULL;
- _err = GetUserDataText(_self->ob_itself,
- data,
- udType,
- index,
- itlRegionTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(GetUserDataText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lh",
+ ResObj_Convert, &data,
+ PyMac_GetOSType, &udType,
+ &index,
+ &itlRegionTag))
+ return NULL;
+ _err = GetUserDataText(_self->ob_itself,
+ data,
+ udType,
+ index,
+ itlRegionTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_RemoveUserDataText(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType udType;
- long index;
- short itlRegionTag;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType udType;
+ long index;
+ short itlRegionTag;
#ifndef RemoveUserDataText
- PyMac_PRECHECK(RemoveUserDataText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lh",
- PyMac_GetOSType, &udType,
- &index,
- &itlRegionTag))
- return NULL;
- _err = RemoveUserDataText(_self->ob_itself,
- udType,
- index,
- itlRegionTag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(RemoveUserDataText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lh",
+ PyMac_GetOSType, &udType,
+ &index,
+ &itlRegionTag))
+ return NULL;
+ _err = RemoveUserDataText(_self->ob_itself,
+ udType,
+ index,
+ itlRegionTag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_PutUserDataIntoHandle(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle h;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle h;
#ifndef PutUserDataIntoHandle
- PyMac_PRECHECK(PutUserDataIntoHandle);
+ PyMac_PRECHECK(PutUserDataIntoHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &h))
- return NULL;
- _err = PutUserDataIntoHandle(_self->ob_itself,
- h);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &h))
+ return NULL;
+ _err = PutUserDataIntoHandle(_self->ob_itself,
+ h);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *UserDataObj_CopyUserData(UserDataObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UserData dstUserData;
- OSType copyRule;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UserData dstUserData;
+ OSType copyRule;
#ifndef CopyUserData
- PyMac_PRECHECK(CopyUserData);
+ PyMac_PRECHECK(CopyUserData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- UserDataObj_Convert, &dstUserData,
- PyMac_GetOSType, &copyRule))
- return NULL;
- _err = CopyUserData(_self->ob_itself,
- dstUserData,
- copyRule);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ UserDataObj_Convert, &dstUserData,
+ PyMac_GetOSType, &copyRule))
+ return NULL;
+ _err = CopyUserData(_self->ob_itself,
+ dstUserData,
+ copyRule);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef UserDataObj_methods[] = {
- {"GetUserData", (PyCFunction)UserDataObj_GetUserData, 1,
- PyDoc_STR("(Handle data, OSType udType, long index) -> None")},
- {"AddUserData", (PyCFunction)UserDataObj_AddUserData, 1,
- PyDoc_STR("(Handle data, OSType udType) -> None")},
- {"RemoveUserData", (PyCFunction)UserDataObj_RemoveUserData, 1,
- PyDoc_STR("(OSType udType, long index) -> None")},
- {"CountUserDataType", (PyCFunction)UserDataObj_CountUserDataType, 1,
- PyDoc_STR("(OSType udType) -> (short _rv)")},
- {"GetNextUserDataType", (PyCFunction)UserDataObj_GetNextUserDataType, 1,
- PyDoc_STR("(OSType udType) -> (long _rv)")},
- {"AddUserDataText", (PyCFunction)UserDataObj_AddUserDataText, 1,
- PyDoc_STR("(Handle data, OSType udType, long index, short itlRegionTag) -> None")},
- {"GetUserDataText", (PyCFunction)UserDataObj_GetUserDataText, 1,
- PyDoc_STR("(Handle data, OSType udType, long index, short itlRegionTag) -> None")},
- {"RemoveUserDataText", (PyCFunction)UserDataObj_RemoveUserDataText, 1,
- PyDoc_STR("(OSType udType, long index, short itlRegionTag) -> None")},
- {"PutUserDataIntoHandle", (PyCFunction)UserDataObj_PutUserDataIntoHandle, 1,
- PyDoc_STR("(Handle h) -> None")},
- {"CopyUserData", (PyCFunction)UserDataObj_CopyUserData, 1,
- PyDoc_STR("(UserData dstUserData, OSType copyRule) -> None")},
- {NULL, NULL, 0}
+ {"GetUserData", (PyCFunction)UserDataObj_GetUserData, 1,
+ PyDoc_STR("(Handle data, OSType udType, long index) -> None")},
+ {"AddUserData", (PyCFunction)UserDataObj_AddUserData, 1,
+ PyDoc_STR("(Handle data, OSType udType) -> None")},
+ {"RemoveUserData", (PyCFunction)UserDataObj_RemoveUserData, 1,
+ PyDoc_STR("(OSType udType, long index) -> None")},
+ {"CountUserDataType", (PyCFunction)UserDataObj_CountUserDataType, 1,
+ PyDoc_STR("(OSType udType) -> (short _rv)")},
+ {"GetNextUserDataType", (PyCFunction)UserDataObj_GetNextUserDataType, 1,
+ PyDoc_STR("(OSType udType) -> (long _rv)")},
+ {"AddUserDataText", (PyCFunction)UserDataObj_AddUserDataText, 1,
+ PyDoc_STR("(Handle data, OSType udType, long index, short itlRegionTag) -> None")},
+ {"GetUserDataText", (PyCFunction)UserDataObj_GetUserDataText, 1,
+ PyDoc_STR("(Handle data, OSType udType, long index, short itlRegionTag) -> None")},
+ {"RemoveUserDataText", (PyCFunction)UserDataObj_RemoveUserDataText, 1,
+ PyDoc_STR("(OSType udType, long index, short itlRegionTag) -> None")},
+ {"PutUserDataIntoHandle", (PyCFunction)UserDataObj_PutUserDataIntoHandle, 1,
+ PyDoc_STR("(Handle h) -> None")},
+ {"CopyUserData", (PyCFunction)UserDataObj_CopyUserData, 1,
+ PyDoc_STR("(UserData dstUserData, OSType copyRule) -> None")},
+ {NULL, NULL, 0}
};
#define UserDataObj_getsetlist NULL
@@ -2143,61 +2143,61 @@ static PyMethodDef UserDataObj_methods[] = {
static PyObject *UserDataObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- UserData itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ UserData itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, UserDataObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((UserDataObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, UserDataObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((UserDataObject *)_self)->ob_itself = itself;
+ return _self;
}
#define UserDataObj_tp_free PyObject_Del
PyTypeObject UserData_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.UserData", /*tp_name*/
- sizeof(UserDataObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) UserDataObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) UserDataObj_compare, /*tp_compare*/
- (reprfunc) UserDataObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) UserDataObj_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*/
- UserDataObj_methods, /* tp_methods */
- 0, /*tp_members*/
- UserDataObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- UserDataObj_tp_init, /* tp_init */
- UserDataObj_tp_alloc, /* tp_alloc */
- UserDataObj_tp_new, /* tp_new */
- UserDataObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.UserData", /*tp_name*/
+ sizeof(UserDataObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) UserDataObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) UserDataObj_compare, /*tp_compare*/
+ (reprfunc) UserDataObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) UserDataObj_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*/
+ UserDataObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ UserDataObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ UserDataObj_tp_init, /* tp_init */
+ UserDataObj_tp_alloc, /* tp_alloc */
+ UserDataObj_tp_new, /* tp_new */
+ UserDataObj_tp_free, /* tp_free */
};
/* -------------------- End object type UserData -------------------- */
@@ -2210,1165 +2210,1165 @@ PyTypeObject Media_Type;
#define MediaObj_Check(x) ((x)->ob_type == &Media_Type || PyObject_TypeCheck((x), &Media_Type))
typedef struct MediaObject {
- PyObject_HEAD
- Media ob_itself;
+ PyObject_HEAD
+ Media ob_itself;
} MediaObject;
PyObject *MediaObj_New(Media itself)
{
- MediaObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create Media from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(MediaObject, &Media_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ MediaObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create Media from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(MediaObject, &Media_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int MediaObj_Convert(PyObject *v, Media *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!MediaObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Media required");
- return 0;
- }
- *p_itself = ((MediaObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!MediaObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Media required");
+ return 0;
+ }
+ *p_itself = ((MediaObject *)v)->ob_itself;
+ return 1;
}
static void MediaObj_dealloc(MediaObject *self)
{
- if (self->ob_itself) DisposeTrackMedia(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_itself) DisposeTrackMedia(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *MediaObj_LoadMediaIntoRam(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue time;
- TimeValue duration;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue time;
+ TimeValue duration;
+ long flags;
#ifndef LoadMediaIntoRam
- PyMac_PRECHECK(LoadMediaIntoRam);
-#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &time,
- &duration,
- &flags))
- return NULL;
- _err = LoadMediaIntoRam(_self->ob_itself,
- time,
- duration,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(LoadMediaIntoRam);
+#endif
+ if (!PyArg_ParseTuple(_args, "lll",
+ &time,
+ &duration,
+ &flags))
+ return NULL;
+ _err = LoadMediaIntoRam(_self->ob_itself,
+ time,
+ duration,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaTrack(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
+ PyObject *_res = NULL;
+ Track _rv;
#ifndef GetMediaTrack
- PyMac_PRECHECK(GetMediaTrack);
+ PyMac_PRECHECK(GetMediaTrack);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaTrack(_self->ob_itself);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaTrack(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaCreationTime(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
+ PyObject *_res = NULL;
+ unsigned long _rv;
#ifndef GetMediaCreationTime
- PyMac_PRECHECK(GetMediaCreationTime);
+ PyMac_PRECHECK(GetMediaCreationTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaCreationTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaCreationTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaModificationTime(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
+ PyObject *_res = NULL;
+ unsigned long _rv;
#ifndef GetMediaModificationTime
- PyMac_PRECHECK(GetMediaModificationTime);
+ PyMac_PRECHECK(GetMediaModificationTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaModificationTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaModificationTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaTimeScale(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeScale _rv;
+ PyObject *_res = NULL;
+ TimeScale _rv;
#ifndef GetMediaTimeScale
- PyMac_PRECHECK(GetMediaTimeScale);
+ PyMac_PRECHECK(GetMediaTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaTimeScale(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaTimeScale(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_SetMediaTimeScale(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeScale timeScale;
+ PyObject *_res = NULL;
+ TimeScale timeScale;
#ifndef SetMediaTimeScale
- PyMac_PRECHECK(SetMediaTimeScale);
+ PyMac_PRECHECK(SetMediaTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &timeScale))
- return NULL;
- SetMediaTimeScale(_self->ob_itself,
- timeScale);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &timeScale))
+ return NULL;
+ SetMediaTimeScale(_self->ob_itself,
+ timeScale);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaDuration(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
+ PyObject *_res = NULL;
+ TimeValue _rv;
#ifndef GetMediaDuration
- PyMac_PRECHECK(GetMediaDuration);
+ PyMac_PRECHECK(GetMediaDuration);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaDuration(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaDuration(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaLanguage(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetMediaLanguage
- PyMac_PRECHECK(GetMediaLanguage);
+ PyMac_PRECHECK(GetMediaLanguage);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaLanguage(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaLanguage(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_SetMediaLanguage(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short language;
+ PyObject *_res = NULL;
+ short language;
#ifndef SetMediaLanguage
- PyMac_PRECHECK(SetMediaLanguage);
+ PyMac_PRECHECK(SetMediaLanguage);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &language))
- return NULL;
- SetMediaLanguage(_self->ob_itself,
- language);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &language))
+ return NULL;
+ SetMediaLanguage(_self->ob_itself,
+ language);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaQuality(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetMediaQuality
- PyMac_PRECHECK(GetMediaQuality);
+ PyMac_PRECHECK(GetMediaQuality);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaQuality(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaQuality(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_SetMediaQuality(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short quality;
+ PyObject *_res = NULL;
+ short quality;
#ifndef SetMediaQuality
- PyMac_PRECHECK(SetMediaQuality);
+ PyMac_PRECHECK(SetMediaQuality);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &quality))
- return NULL;
- SetMediaQuality(_self->ob_itself,
- quality);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &quality))
+ return NULL;
+ SetMediaQuality(_self->ob_itself,
+ quality);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaHandlerDescription(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSType mediaType;
- Str255 creatorName;
- OSType creatorManufacturer;
+ PyObject *_res = NULL;
+ OSType mediaType;
+ Str255 creatorName;
+ OSType creatorManufacturer;
#ifndef GetMediaHandlerDescription
- PyMac_PRECHECK(GetMediaHandlerDescription);
+ PyMac_PRECHECK(GetMediaHandlerDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, creatorName))
- return NULL;
- GetMediaHandlerDescription(_self->ob_itself,
- &mediaType,
- creatorName,
- &creatorManufacturer);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildOSType, mediaType,
- PyMac_BuildOSType, creatorManufacturer);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, creatorName))
+ return NULL;
+ GetMediaHandlerDescription(_self->ob_itself,
+ &mediaType,
+ creatorName,
+ &creatorManufacturer);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildOSType, mediaType,
+ PyMac_BuildOSType, creatorManufacturer);
+ return _res;
}
static PyObject *MediaObj_GetMediaUserData(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UserData _rv;
+ PyObject *_res = NULL;
+ UserData _rv;
#ifndef GetMediaUserData
- PyMac_PRECHECK(GetMediaUserData);
+ PyMac_PRECHECK(GetMediaUserData);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaUserData(_self->ob_itself);
- _res = Py_BuildValue("O&",
- UserDataObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaUserData(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ UserDataObj_New, _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaHandler(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MediaHandler _rv;
+ PyObject *_res = NULL;
+ MediaHandler _rv;
#ifndef GetMediaHandler
- PyMac_PRECHECK(GetMediaHandler);
+ PyMac_PRECHECK(GetMediaHandler);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaHandler(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaHandler(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *MediaObj_SetMediaHandler(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- MediaHandlerComponent mH;
+ PyObject *_res = NULL;
+ OSErr _err;
+ MediaHandlerComponent mH;
#ifndef SetMediaHandler
- PyMac_PRECHECK(SetMediaHandler);
+ PyMac_PRECHECK(SetMediaHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpObj_Convert, &mH))
- return NULL;
- _err = SetMediaHandler(_self->ob_itself,
- mH);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpObj_Convert, &mH))
+ return NULL;
+ _err = SetMediaHandler(_self->ob_itself,
+ mH);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_BeginMediaEdits(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef BeginMediaEdits
- PyMac_PRECHECK(BeginMediaEdits);
+ PyMac_PRECHECK(BeginMediaEdits);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = BeginMediaEdits(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = BeginMediaEdits(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_EndMediaEdits(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef EndMediaEdits
- PyMac_PRECHECK(EndMediaEdits);
+ PyMac_PRECHECK(EndMediaEdits);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = EndMediaEdits(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = EndMediaEdits(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_SetMediaDefaultDataRefIndex(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short index;
#ifndef SetMediaDefaultDataRefIndex
- PyMac_PRECHECK(SetMediaDefaultDataRefIndex);
+ PyMac_PRECHECK(SetMediaDefaultDataRefIndex);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- _err = SetMediaDefaultDataRefIndex(_self->ob_itself,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ _err = SetMediaDefaultDataRefIndex(_self->ob_itself,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaDataHandlerDescription(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short index;
- OSType dhType;
- Str255 creatorName;
- OSType creatorManufacturer;
+ PyObject *_res = NULL;
+ short index;
+ OSType dhType;
+ Str255 creatorName;
+ OSType creatorManufacturer;
#ifndef GetMediaDataHandlerDescription
- PyMac_PRECHECK(GetMediaDataHandlerDescription);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &index,
- PyMac_GetStr255, creatorName))
- return NULL;
- GetMediaDataHandlerDescription(_self->ob_itself,
- index,
- &dhType,
- creatorName,
- &creatorManufacturer);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildOSType, dhType,
- PyMac_BuildOSType, creatorManufacturer);
- return _res;
+ PyMac_PRECHECK(GetMediaDataHandlerDescription);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &index,
+ PyMac_GetStr255, creatorName))
+ return NULL;
+ GetMediaDataHandlerDescription(_self->ob_itself,
+ index,
+ &dhType,
+ creatorName,
+ &creatorManufacturer);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildOSType, dhType,
+ PyMac_BuildOSType, creatorManufacturer);
+ return _res;
}
static PyObject *MediaObj_GetMediaDataHandler(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- DataHandler _rv;
- short index;
+ PyObject *_res = NULL;
+ DataHandler _rv;
+ short index;
#ifndef GetMediaDataHandler
- PyMac_PRECHECK(GetMediaDataHandler);
+ PyMac_PRECHECK(GetMediaDataHandler);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- _rv = GetMediaDataHandler(_self->ob_itself,
- index);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ _rv = GetMediaDataHandler(_self->ob_itself,
+ index);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *MediaObj_SetMediaDataHandler(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short index;
- DataHandlerComponent dataHandler;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short index;
+ DataHandlerComponent dataHandler;
#ifndef SetMediaDataHandler
- PyMac_PRECHECK(SetMediaDataHandler);
+ PyMac_PRECHECK(SetMediaDataHandler);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &index,
- CmpObj_Convert, &dataHandler))
- return NULL;
- _err = SetMediaDataHandler(_self->ob_itself,
- index,
- dataHandler);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &index,
+ CmpObj_Convert, &dataHandler))
+ return NULL;
+ _err = SetMediaDataHandler(_self->ob_itself,
+ index,
+ dataHandler);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaSampleDescriptionCount(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetMediaSampleDescriptionCount
- PyMac_PRECHECK(GetMediaSampleDescriptionCount);
+ PyMac_PRECHECK(GetMediaSampleDescriptionCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaSampleDescriptionCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaSampleDescriptionCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaSampleDescription(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long index;
- SampleDescriptionHandle descH;
+ PyObject *_res = NULL;
+ long index;
+ SampleDescriptionHandle descH;
#ifndef GetMediaSampleDescription
- PyMac_PRECHECK(GetMediaSampleDescription);
+ PyMac_PRECHECK(GetMediaSampleDescription);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &index,
- ResObj_Convert, &descH))
- return NULL;
- GetMediaSampleDescription(_self->ob_itself,
- index,
- descH);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &index,
+ ResObj_Convert, &descH))
+ return NULL;
+ GetMediaSampleDescription(_self->ob_itself,
+ index,
+ descH);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_SetMediaSampleDescription(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long index;
- SampleDescriptionHandle descH;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long index;
+ SampleDescriptionHandle descH;
#ifndef SetMediaSampleDescription
- PyMac_PRECHECK(SetMediaSampleDescription);
+ PyMac_PRECHECK(SetMediaSampleDescription);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &index,
- ResObj_Convert, &descH))
- return NULL;
- _err = SetMediaSampleDescription(_self->ob_itself,
- index,
- descH);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &index,
+ ResObj_Convert, &descH))
+ return NULL;
+ _err = SetMediaSampleDescription(_self->ob_itself,
+ index,
+ descH);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaSampleCount(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetMediaSampleCount
- PyMac_PRECHECK(GetMediaSampleCount);
+ PyMac_PRECHECK(GetMediaSampleCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaSampleCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaSampleCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaSyncSampleCount(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetMediaSyncSampleCount
- PyMac_PRECHECK(GetMediaSyncSampleCount);
+ PyMac_PRECHECK(GetMediaSyncSampleCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMediaSyncSampleCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMediaSyncSampleCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_SampleNumToMediaTime(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long logicalSampleNum;
- TimeValue sampleTime;
- TimeValue sampleDuration;
+ PyObject *_res = NULL;
+ long logicalSampleNum;
+ TimeValue sampleTime;
+ TimeValue sampleDuration;
#ifndef SampleNumToMediaTime
- PyMac_PRECHECK(SampleNumToMediaTime);
+ PyMac_PRECHECK(SampleNumToMediaTime);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &logicalSampleNum))
- return NULL;
- SampleNumToMediaTime(_self->ob_itself,
- logicalSampleNum,
- &sampleTime,
- &sampleDuration);
- _res = Py_BuildValue("ll",
- sampleTime,
- sampleDuration);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &logicalSampleNum))
+ return NULL;
+ SampleNumToMediaTime(_self->ob_itself,
+ logicalSampleNum,
+ &sampleTime,
+ &sampleDuration);
+ _res = Py_BuildValue("ll",
+ sampleTime,
+ sampleDuration);
+ return _res;
}
static PyObject *MediaObj_MediaTimeToSampleNum(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue time;
- long sampleNum;
- TimeValue sampleTime;
- TimeValue sampleDuration;
+ PyObject *_res = NULL;
+ TimeValue time;
+ long sampleNum;
+ TimeValue sampleTime;
+ TimeValue sampleDuration;
#ifndef MediaTimeToSampleNum
- PyMac_PRECHECK(MediaTimeToSampleNum);
-#endif
- if (!PyArg_ParseTuple(_args, "l",
- &time))
- return NULL;
- MediaTimeToSampleNum(_self->ob_itself,
- time,
- &sampleNum,
- &sampleTime,
- &sampleDuration);
- _res = Py_BuildValue("lll",
- sampleNum,
- sampleTime,
- sampleDuration);
- return _res;
+ PyMac_PRECHECK(MediaTimeToSampleNum);
+#endif
+ if (!PyArg_ParseTuple(_args, "l",
+ &time))
+ return NULL;
+ MediaTimeToSampleNum(_self->ob_itself,
+ time,
+ &sampleNum,
+ &sampleTime,
+ &sampleDuration);
+ _res = Py_BuildValue("lll",
+ sampleNum,
+ sampleTime,
+ sampleDuration);
+ return _res;
}
static PyObject *MediaObj_AddMediaSample(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataIn;
- long inOffset;
- unsigned long size;
- TimeValue durationPerSample;
- SampleDescriptionHandle sampleDescriptionH;
- long numberOfSamples;
- short sampleFlags;
- TimeValue sampleTime;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataIn;
+ long inOffset;
+ unsigned long size;
+ TimeValue durationPerSample;
+ SampleDescriptionHandle sampleDescriptionH;
+ long numberOfSamples;
+ short sampleFlags;
+ TimeValue sampleTime;
#ifndef AddMediaSample
- PyMac_PRECHECK(AddMediaSample);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lllO&lh",
- ResObj_Convert, &dataIn,
- &inOffset,
- &size,
- &durationPerSample,
- ResObj_Convert, &sampleDescriptionH,
- &numberOfSamples,
- &sampleFlags))
- return NULL;
- _err = AddMediaSample(_self->ob_itself,
- dataIn,
- inOffset,
- size,
- durationPerSample,
- sampleDescriptionH,
- numberOfSamples,
- sampleFlags,
- &sampleTime);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- sampleTime);
- return _res;
+ PyMac_PRECHECK(AddMediaSample);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lllO&lh",
+ ResObj_Convert, &dataIn,
+ &inOffset,
+ &size,
+ &durationPerSample,
+ ResObj_Convert, &sampleDescriptionH,
+ &numberOfSamples,
+ &sampleFlags))
+ return NULL;
+ _err = AddMediaSample(_self->ob_itself,
+ dataIn,
+ inOffset,
+ size,
+ durationPerSample,
+ sampleDescriptionH,
+ numberOfSamples,
+ sampleFlags,
+ &sampleTime);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ sampleTime);
+ return _res;
}
static PyObject *MediaObj_AddMediaSampleReference(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long dataOffset;
- unsigned long size;
- TimeValue durationPerSample;
- SampleDescriptionHandle sampleDescriptionH;
- long numberOfSamples;
- short sampleFlags;
- TimeValue sampleTime;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long dataOffset;
+ unsigned long size;
+ TimeValue durationPerSample;
+ SampleDescriptionHandle sampleDescriptionH;
+ long numberOfSamples;
+ short sampleFlags;
+ TimeValue sampleTime;
#ifndef AddMediaSampleReference
- PyMac_PRECHECK(AddMediaSampleReference);
-#endif
- if (!PyArg_ParseTuple(_args, "lllO&lh",
- &dataOffset,
- &size,
- &durationPerSample,
- ResObj_Convert, &sampleDescriptionH,
- &numberOfSamples,
- &sampleFlags))
- return NULL;
- _err = AddMediaSampleReference(_self->ob_itself,
- dataOffset,
- size,
- durationPerSample,
- sampleDescriptionH,
- numberOfSamples,
- sampleFlags,
- &sampleTime);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- sampleTime);
- return _res;
+ PyMac_PRECHECK(AddMediaSampleReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "lllO&lh",
+ &dataOffset,
+ &size,
+ &durationPerSample,
+ ResObj_Convert, &sampleDescriptionH,
+ &numberOfSamples,
+ &sampleFlags))
+ return NULL;
+ _err = AddMediaSampleReference(_self->ob_itself,
+ dataOffset,
+ size,
+ durationPerSample,
+ sampleDescriptionH,
+ numberOfSamples,
+ sampleFlags,
+ &sampleTime);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ sampleTime);
+ return _res;
}
static PyObject *MediaObj_GetMediaSample(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataOut;
- long maxSizeToGrow;
- long size;
- TimeValue time;
- TimeValue sampleTime;
- TimeValue durationPerSample;
- SampleDescriptionHandle sampleDescriptionH;
- long sampleDescriptionIndex;
- long maxNumberOfSamples;
- long numberOfSamples;
- short sampleFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataOut;
+ long maxSizeToGrow;
+ long size;
+ TimeValue time;
+ TimeValue sampleTime;
+ TimeValue durationPerSample;
+ SampleDescriptionHandle sampleDescriptionH;
+ long sampleDescriptionIndex;
+ long maxNumberOfSamples;
+ long numberOfSamples;
+ short sampleFlags;
#ifndef GetMediaSample
- PyMac_PRECHECK(GetMediaSample);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llO&l",
- ResObj_Convert, &dataOut,
- &maxSizeToGrow,
- &time,
- ResObj_Convert, &sampleDescriptionH,
- &maxNumberOfSamples))
- return NULL;
- _err = GetMediaSample(_self->ob_itself,
- dataOut,
- maxSizeToGrow,
- &size,
- time,
- &sampleTime,
- &durationPerSample,
- sampleDescriptionH,
- &sampleDescriptionIndex,
- maxNumberOfSamples,
- &numberOfSamples,
- &sampleFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("lllllh",
- size,
- sampleTime,
- durationPerSample,
- sampleDescriptionIndex,
- numberOfSamples,
- sampleFlags);
- return _res;
+ PyMac_PRECHECK(GetMediaSample);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llO&l",
+ ResObj_Convert, &dataOut,
+ &maxSizeToGrow,
+ &time,
+ ResObj_Convert, &sampleDescriptionH,
+ &maxNumberOfSamples))
+ return NULL;
+ _err = GetMediaSample(_self->ob_itself,
+ dataOut,
+ maxSizeToGrow,
+ &size,
+ time,
+ &sampleTime,
+ &durationPerSample,
+ sampleDescriptionH,
+ &sampleDescriptionIndex,
+ maxNumberOfSamples,
+ &numberOfSamples,
+ &sampleFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("lllllh",
+ size,
+ sampleTime,
+ durationPerSample,
+ sampleDescriptionIndex,
+ numberOfSamples,
+ sampleFlags);
+ return _res;
}
static PyObject *MediaObj_GetMediaSampleReference(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long dataOffset;
- long size;
- TimeValue time;
- TimeValue sampleTime;
- TimeValue durationPerSample;
- SampleDescriptionHandle sampleDescriptionH;
- long sampleDescriptionIndex;
- long maxNumberOfSamples;
- long numberOfSamples;
- short sampleFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long dataOffset;
+ long size;
+ TimeValue time;
+ TimeValue sampleTime;
+ TimeValue durationPerSample;
+ SampleDescriptionHandle sampleDescriptionH;
+ long sampleDescriptionIndex;
+ long maxNumberOfSamples;
+ long numberOfSamples;
+ short sampleFlags;
#ifndef GetMediaSampleReference
- PyMac_PRECHECK(GetMediaSampleReference);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &time,
- ResObj_Convert, &sampleDescriptionH,
- &maxNumberOfSamples))
- return NULL;
- _err = GetMediaSampleReference(_self->ob_itself,
- &dataOffset,
- &size,
- time,
- &sampleTime,
- &durationPerSample,
- sampleDescriptionH,
- &sampleDescriptionIndex,
- maxNumberOfSamples,
- &numberOfSamples,
- &sampleFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("llllllh",
- dataOffset,
- size,
- sampleTime,
- durationPerSample,
- sampleDescriptionIndex,
- numberOfSamples,
- sampleFlags);
- return _res;
+ PyMac_PRECHECK(GetMediaSampleReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &time,
+ ResObj_Convert, &sampleDescriptionH,
+ &maxNumberOfSamples))
+ return NULL;
+ _err = GetMediaSampleReference(_self->ob_itself,
+ &dataOffset,
+ &size,
+ time,
+ &sampleTime,
+ &durationPerSample,
+ sampleDescriptionH,
+ &sampleDescriptionIndex,
+ maxNumberOfSamples,
+ &numberOfSamples,
+ &sampleFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("llllllh",
+ dataOffset,
+ size,
+ sampleTime,
+ durationPerSample,
+ sampleDescriptionIndex,
+ numberOfSamples,
+ sampleFlags);
+ return _res;
}
static PyObject *MediaObj_SetMediaPreferredChunkSize(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long maxChunkSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long maxChunkSize;
#ifndef SetMediaPreferredChunkSize
- PyMac_PRECHECK(SetMediaPreferredChunkSize);
+ PyMac_PRECHECK(SetMediaPreferredChunkSize);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &maxChunkSize))
- return NULL;
- _err = SetMediaPreferredChunkSize(_self->ob_itself,
- maxChunkSize);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &maxChunkSize))
+ return NULL;
+ _err = SetMediaPreferredChunkSize(_self->ob_itself,
+ maxChunkSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaPreferredChunkSize(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long maxChunkSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long maxChunkSize;
#ifndef GetMediaPreferredChunkSize
- PyMac_PRECHECK(GetMediaPreferredChunkSize);
+ PyMac_PRECHECK(GetMediaPreferredChunkSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMediaPreferredChunkSize(_self->ob_itself,
- &maxChunkSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- maxChunkSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMediaPreferredChunkSize(_self->ob_itself,
+ &maxChunkSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ maxChunkSize);
+ return _res;
}
static PyObject *MediaObj_SetMediaShadowSync(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long frameDiffSampleNum;
- long syncSampleNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long frameDiffSampleNum;
+ long syncSampleNum;
#ifndef SetMediaShadowSync
- PyMac_PRECHECK(SetMediaShadowSync);
+ PyMac_PRECHECK(SetMediaShadowSync);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &frameDiffSampleNum,
- &syncSampleNum))
- return NULL;
- _err = SetMediaShadowSync(_self->ob_itself,
- frameDiffSampleNum,
- syncSampleNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &frameDiffSampleNum,
+ &syncSampleNum))
+ return NULL;
+ _err = SetMediaShadowSync(_self->ob_itself,
+ frameDiffSampleNum,
+ syncSampleNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaShadowSync(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long frameDiffSampleNum;
- long syncSampleNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long frameDiffSampleNum;
+ long syncSampleNum;
#ifndef GetMediaShadowSync
- PyMac_PRECHECK(GetMediaShadowSync);
+ PyMac_PRECHECK(GetMediaShadowSync);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &frameDiffSampleNum))
- return NULL;
- _err = GetMediaShadowSync(_self->ob_itself,
- frameDiffSampleNum,
- &syncSampleNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- syncSampleNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &frameDiffSampleNum))
+ return NULL;
+ _err = GetMediaShadowSync(_self->ob_itself,
+ frameDiffSampleNum,
+ &syncSampleNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ syncSampleNum);
+ return _res;
}
static PyObject *MediaObj_GetMediaDataSize(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ long _rv;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef GetMediaDataSize
- PyMac_PRECHECK(GetMediaDataSize);
+ PyMac_PRECHECK(GetMediaDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _rv = GetMediaDataSize(_self->ob_itself,
- startTime,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = GetMediaDataSize(_self->ob_itself,
+ startTime,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MediaObj_GetMediaDataSize64(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue duration;
- wide dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue duration;
+ wide dataSize;
#ifndef GetMediaDataSize64
- PyMac_PRECHECK(GetMediaDataSize64);
-#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _err = GetMediaDataSize64(_self->ob_itself,
- startTime,
- duration,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, dataSize);
- return _res;
+ PyMac_PRECHECK(GetMediaDataSize64);
+#endif
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _err = GetMediaDataSize64(_self->ob_itself,
+ startTime,
+ duration,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, dataSize);
+ return _res;
}
static PyObject *MediaObj_CopyMediaUserData(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Media dstMedia;
- OSType copyRule;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Media dstMedia;
+ OSType copyRule;
#ifndef CopyMediaUserData
- PyMac_PRECHECK(CopyMediaUserData);
+ PyMac_PRECHECK(CopyMediaUserData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- MediaObj_Convert, &dstMedia,
- PyMac_GetOSType, &copyRule))
- return NULL;
- _err = CopyMediaUserData(_self->ob_itself,
- dstMedia,
- copyRule);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ MediaObj_Convert, &dstMedia,
+ PyMac_GetOSType, &copyRule))
+ return NULL;
+ _err = CopyMediaUserData(_self->ob_itself,
+ dstMedia,
+ copyRule);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaNextInterestingTime(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short interestingTimeFlags;
- TimeValue time;
- Fixed rate;
- TimeValue interestingTime;
- TimeValue interestingDuration;
+ PyObject *_res = NULL;
+ short interestingTimeFlags;
+ TimeValue time;
+ Fixed rate;
+ TimeValue interestingTime;
+ TimeValue interestingDuration;
#ifndef GetMediaNextInterestingTime
- PyMac_PRECHECK(GetMediaNextInterestingTime);
-#endif
- if (!PyArg_ParseTuple(_args, "hlO&",
- &interestingTimeFlags,
- &time,
- PyMac_GetFixed, &rate))
- return NULL;
- GetMediaNextInterestingTime(_self->ob_itself,
- interestingTimeFlags,
- time,
- rate,
- &interestingTime,
- &interestingDuration);
- _res = Py_BuildValue("ll",
- interestingTime,
- interestingDuration);
- return _res;
+ PyMac_PRECHECK(GetMediaNextInterestingTime);
+#endif
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &interestingTimeFlags,
+ &time,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ GetMediaNextInterestingTime(_self->ob_itself,
+ interestingTimeFlags,
+ time,
+ rate,
+ &interestingTime,
+ &interestingDuration);
+ _res = Py_BuildValue("ll",
+ interestingTime,
+ interestingDuration);
+ return _res;
}
static PyObject *MediaObj_GetMediaDataRef(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short index;
- Handle dataRef;
- OSType dataRefType;
- long dataRefAttributes;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short index;
+ Handle dataRef;
+ OSType dataRefType;
+ long dataRefAttributes;
#ifndef GetMediaDataRef
- PyMac_PRECHECK(GetMediaDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- _err = GetMediaDataRef(_self->ob_itself,
- index,
- &dataRef,
- &dataRefType,
- &dataRefAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&l",
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType,
- dataRefAttributes);
- return _res;
+ PyMac_PRECHECK(GetMediaDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ _err = GetMediaDataRef(_self->ob_itself,
+ index,
+ &dataRef,
+ &dataRefType,
+ &dataRefAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&l",
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType,
+ dataRefAttributes);
+ return _res;
}
static PyObject *MediaObj_SetMediaDataRef(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short index;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short index;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef SetMediaDataRef
- PyMac_PRECHECK(SetMediaDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&O&",
- &index,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = SetMediaDataRef(_self->ob_itself,
- index,
- dataRef,
- dataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetMediaDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&O&",
+ &index,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = SetMediaDataRef(_self->ob_itself,
+ index,
+ dataRef,
+ dataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_SetMediaDataRefAttributes(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short index;
- long dataRefAttributes;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short index;
+ long dataRefAttributes;
#ifndef SetMediaDataRefAttributes
- PyMac_PRECHECK(SetMediaDataRefAttributes);
+ PyMac_PRECHECK(SetMediaDataRefAttributes);
#endif
- if (!PyArg_ParseTuple(_args, "hl",
- &index,
- &dataRefAttributes))
- return NULL;
- _err = SetMediaDataRefAttributes(_self->ob_itself,
- index,
- dataRefAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hl",
+ &index,
+ &dataRefAttributes))
+ return NULL;
+ _err = SetMediaDataRefAttributes(_self->ob_itself,
+ index,
+ dataRefAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_AddMediaDataRef(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short index;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short index;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef AddMediaDataRef
- PyMac_PRECHECK(AddMediaDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = AddMediaDataRef(_self->ob_itself,
- &index,
- dataRef,
- dataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- index);
- return _res;
+ PyMac_PRECHECK(AddMediaDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = AddMediaDataRef(_self->ob_itself,
+ &index,
+ dataRef,
+ dataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ index);
+ return _res;
}
static PyObject *MediaObj_GetMediaDataRefCount(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short count;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short count;
#ifndef GetMediaDataRefCount
- PyMac_PRECHECK(GetMediaDataRefCount);
+ PyMac_PRECHECK(GetMediaDataRefCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMediaDataRefCount(_self->ob_itself,
- &count);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- count);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMediaDataRefCount(_self->ob_itself,
+ &count);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ count);
+ return _res;
}
static PyObject *MediaObj_SetMediaPlayHints(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long flags;
- long flagsMask;
+ PyObject *_res = NULL;
+ long flags;
+ long flagsMask;
#ifndef SetMediaPlayHints
- PyMac_PRECHECK(SetMediaPlayHints);
+ PyMac_PRECHECK(SetMediaPlayHints);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &flags,
- &flagsMask))
- return NULL;
- SetMediaPlayHints(_self->ob_itself,
- flags,
- flagsMask);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &flags,
+ &flagsMask))
+ return NULL;
+ SetMediaPlayHints(_self->ob_itself,
+ flags,
+ flagsMask);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MediaObj_GetMediaPlayHints(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long flags;
+ PyObject *_res = NULL;
+ long flags;
#ifndef GetMediaPlayHints
- PyMac_PRECHECK(GetMediaPlayHints);
+ PyMac_PRECHECK(GetMediaPlayHints);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMediaPlayHints(_self->ob_itself,
- &flags);
- _res = Py_BuildValue("l",
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMediaPlayHints(_self->ob_itself,
+ &flags);
+ _res = Py_BuildValue("l",
+ flags);
+ return _res;
}
static PyObject *MediaObj_GetMediaNextInterestingTimeOnly(MediaObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short interestingTimeFlags;
- TimeValue time;
- Fixed rate;
- TimeValue interestingTime;
+ PyObject *_res = NULL;
+ short interestingTimeFlags;
+ TimeValue time;
+ Fixed rate;
+ TimeValue interestingTime;
#ifndef GetMediaNextInterestingTimeOnly
- PyMac_PRECHECK(GetMediaNextInterestingTimeOnly);
-#endif
- if (!PyArg_ParseTuple(_args, "hlO&",
- &interestingTimeFlags,
- &time,
- PyMac_GetFixed, &rate))
- return NULL;
- GetMediaNextInterestingTimeOnly(_self->ob_itself,
- interestingTimeFlags,
- time,
- rate,
- &interestingTime);
- _res = Py_BuildValue("l",
- interestingTime);
- return _res;
+ PyMac_PRECHECK(GetMediaNextInterestingTimeOnly);
+#endif
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &interestingTimeFlags,
+ &time,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ GetMediaNextInterestingTimeOnly(_self->ob_itself,
+ interestingTimeFlags,
+ time,
+ rate,
+ &interestingTime);
+ _res = Py_BuildValue("l",
+ interestingTime);
+ return _res;
}
static PyMethodDef MediaObj_methods[] = {
- {"LoadMediaIntoRam", (PyCFunction)MediaObj_LoadMediaIntoRam, 1,
- PyDoc_STR("(TimeValue time, TimeValue duration, long flags) -> None")},
- {"GetMediaTrack", (PyCFunction)MediaObj_GetMediaTrack, 1,
- PyDoc_STR("() -> (Track _rv)")},
- {"GetMediaCreationTime", (PyCFunction)MediaObj_GetMediaCreationTime, 1,
- PyDoc_STR("() -> (unsigned long _rv)")},
- {"GetMediaModificationTime", (PyCFunction)MediaObj_GetMediaModificationTime, 1,
- PyDoc_STR("() -> (unsigned long _rv)")},
- {"GetMediaTimeScale", (PyCFunction)MediaObj_GetMediaTimeScale, 1,
- PyDoc_STR("() -> (TimeScale _rv)")},
- {"SetMediaTimeScale", (PyCFunction)MediaObj_SetMediaTimeScale, 1,
- PyDoc_STR("(TimeScale timeScale) -> None")},
- {"GetMediaDuration", (PyCFunction)MediaObj_GetMediaDuration, 1,
- PyDoc_STR("() -> (TimeValue _rv)")},
- {"GetMediaLanguage", (PyCFunction)MediaObj_GetMediaLanguage, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetMediaLanguage", (PyCFunction)MediaObj_SetMediaLanguage, 1,
- PyDoc_STR("(short language) -> None")},
- {"GetMediaQuality", (PyCFunction)MediaObj_GetMediaQuality, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetMediaQuality", (PyCFunction)MediaObj_SetMediaQuality, 1,
- PyDoc_STR("(short quality) -> None")},
- {"GetMediaHandlerDescription", (PyCFunction)MediaObj_GetMediaHandlerDescription, 1,
- PyDoc_STR("(Str255 creatorName) -> (OSType mediaType, OSType creatorManufacturer)")},
- {"GetMediaUserData", (PyCFunction)MediaObj_GetMediaUserData, 1,
- PyDoc_STR("() -> (UserData _rv)")},
- {"GetMediaHandler", (PyCFunction)MediaObj_GetMediaHandler, 1,
- PyDoc_STR("() -> (MediaHandler _rv)")},
- {"SetMediaHandler", (PyCFunction)MediaObj_SetMediaHandler, 1,
- PyDoc_STR("(MediaHandlerComponent mH) -> None")},
- {"BeginMediaEdits", (PyCFunction)MediaObj_BeginMediaEdits, 1,
- PyDoc_STR("() -> None")},
- {"EndMediaEdits", (PyCFunction)MediaObj_EndMediaEdits, 1,
- PyDoc_STR("() -> None")},
- {"SetMediaDefaultDataRefIndex", (PyCFunction)MediaObj_SetMediaDefaultDataRefIndex, 1,
- PyDoc_STR("(short index) -> None")},
- {"GetMediaDataHandlerDescription", (PyCFunction)MediaObj_GetMediaDataHandlerDescription, 1,
- PyDoc_STR("(short index, Str255 creatorName) -> (OSType dhType, OSType creatorManufacturer)")},
- {"GetMediaDataHandler", (PyCFunction)MediaObj_GetMediaDataHandler, 1,
- PyDoc_STR("(short index) -> (DataHandler _rv)")},
- {"SetMediaDataHandler", (PyCFunction)MediaObj_SetMediaDataHandler, 1,
- PyDoc_STR("(short index, DataHandlerComponent dataHandler) -> None")},
- {"GetMediaSampleDescriptionCount", (PyCFunction)MediaObj_GetMediaSampleDescriptionCount, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetMediaSampleDescription", (PyCFunction)MediaObj_GetMediaSampleDescription, 1,
- PyDoc_STR("(long index, SampleDescriptionHandle descH) -> None")},
- {"SetMediaSampleDescription", (PyCFunction)MediaObj_SetMediaSampleDescription, 1,
- PyDoc_STR("(long index, SampleDescriptionHandle descH) -> None")},
- {"GetMediaSampleCount", (PyCFunction)MediaObj_GetMediaSampleCount, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetMediaSyncSampleCount", (PyCFunction)MediaObj_GetMediaSyncSampleCount, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SampleNumToMediaTime", (PyCFunction)MediaObj_SampleNumToMediaTime, 1,
- PyDoc_STR("(long logicalSampleNum) -> (TimeValue sampleTime, TimeValue sampleDuration)")},
- {"MediaTimeToSampleNum", (PyCFunction)MediaObj_MediaTimeToSampleNum, 1,
- PyDoc_STR("(TimeValue time) -> (long sampleNum, TimeValue sampleTime, TimeValue sampleDuration)")},
- {"AddMediaSample", (PyCFunction)MediaObj_AddMediaSample, 1,
- PyDoc_STR("(Handle dataIn, long inOffset, unsigned long size, TimeValue durationPerSample, SampleDescriptionHandle sampleDescriptionH, long numberOfSamples, short sampleFlags) -> (TimeValue sampleTime)")},
- {"AddMediaSampleReference", (PyCFunction)MediaObj_AddMediaSampleReference, 1,
- PyDoc_STR("(long dataOffset, unsigned long size, TimeValue durationPerSample, SampleDescriptionHandle sampleDescriptionH, long numberOfSamples, short sampleFlags) -> (TimeValue sampleTime)")},
- {"GetMediaSample", (PyCFunction)MediaObj_GetMediaSample, 1,
- PyDoc_STR("(Handle dataOut, long maxSizeToGrow, TimeValue time, SampleDescriptionHandle sampleDescriptionH, long maxNumberOfSamples) -> (long size, TimeValue sampleTime, TimeValue durationPerSample, long sampleDescriptionIndex, long numberOfSamples, short sampleFlags)")},
- {"GetMediaSampleReference", (PyCFunction)MediaObj_GetMediaSampleReference, 1,
- PyDoc_STR("(TimeValue time, SampleDescriptionHandle sampleDescriptionH, long maxNumberOfSamples) -> (long dataOffset, long size, TimeValue sampleTime, TimeValue durationPerSample, long sampleDescriptionIndex, long numberOfSamples, short sampleFlags)")},
- {"SetMediaPreferredChunkSize", (PyCFunction)MediaObj_SetMediaPreferredChunkSize, 1,
- PyDoc_STR("(long maxChunkSize) -> None")},
- {"GetMediaPreferredChunkSize", (PyCFunction)MediaObj_GetMediaPreferredChunkSize, 1,
- PyDoc_STR("() -> (long maxChunkSize)")},
- {"SetMediaShadowSync", (PyCFunction)MediaObj_SetMediaShadowSync, 1,
- PyDoc_STR("(long frameDiffSampleNum, long syncSampleNum) -> None")},
- {"GetMediaShadowSync", (PyCFunction)MediaObj_GetMediaShadowSync, 1,
- PyDoc_STR("(long frameDiffSampleNum) -> (long syncSampleNum)")},
- {"GetMediaDataSize", (PyCFunction)MediaObj_GetMediaDataSize, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (long _rv)")},
- {"GetMediaDataSize64", (PyCFunction)MediaObj_GetMediaDataSize64, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (wide dataSize)")},
- {"CopyMediaUserData", (PyCFunction)MediaObj_CopyMediaUserData, 1,
- PyDoc_STR("(Media dstMedia, OSType copyRule) -> None")},
- {"GetMediaNextInterestingTime", (PyCFunction)MediaObj_GetMediaNextInterestingTime, 1,
- PyDoc_STR("(short interestingTimeFlags, TimeValue time, Fixed rate) -> (TimeValue interestingTime, TimeValue interestingDuration)")},
- {"GetMediaDataRef", (PyCFunction)MediaObj_GetMediaDataRef, 1,
- PyDoc_STR("(short index) -> (Handle dataRef, OSType dataRefType, long dataRefAttributes)")},
- {"SetMediaDataRef", (PyCFunction)MediaObj_SetMediaDataRef, 1,
- PyDoc_STR("(short index, Handle dataRef, OSType dataRefType) -> None")},
- {"SetMediaDataRefAttributes", (PyCFunction)MediaObj_SetMediaDataRefAttributes, 1,
- PyDoc_STR("(short index, long dataRefAttributes) -> None")},
- {"AddMediaDataRef", (PyCFunction)MediaObj_AddMediaDataRef, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType) -> (short index)")},
- {"GetMediaDataRefCount", (PyCFunction)MediaObj_GetMediaDataRefCount, 1,
- PyDoc_STR("() -> (short count)")},
- {"SetMediaPlayHints", (PyCFunction)MediaObj_SetMediaPlayHints, 1,
- PyDoc_STR("(long flags, long flagsMask) -> None")},
- {"GetMediaPlayHints", (PyCFunction)MediaObj_GetMediaPlayHints, 1,
- PyDoc_STR("() -> (long flags)")},
- {"GetMediaNextInterestingTimeOnly", (PyCFunction)MediaObj_GetMediaNextInterestingTimeOnly, 1,
- PyDoc_STR("(short interestingTimeFlags, TimeValue time, Fixed rate) -> (TimeValue interestingTime)")},
- {NULL, NULL, 0}
+ {"LoadMediaIntoRam", (PyCFunction)MediaObj_LoadMediaIntoRam, 1,
+ PyDoc_STR("(TimeValue time, TimeValue duration, long flags) -> None")},
+ {"GetMediaTrack", (PyCFunction)MediaObj_GetMediaTrack, 1,
+ PyDoc_STR("() -> (Track _rv)")},
+ {"GetMediaCreationTime", (PyCFunction)MediaObj_GetMediaCreationTime, 1,
+ PyDoc_STR("() -> (unsigned long _rv)")},
+ {"GetMediaModificationTime", (PyCFunction)MediaObj_GetMediaModificationTime, 1,
+ PyDoc_STR("() -> (unsigned long _rv)")},
+ {"GetMediaTimeScale", (PyCFunction)MediaObj_GetMediaTimeScale, 1,
+ PyDoc_STR("() -> (TimeScale _rv)")},
+ {"SetMediaTimeScale", (PyCFunction)MediaObj_SetMediaTimeScale, 1,
+ PyDoc_STR("(TimeScale timeScale) -> None")},
+ {"GetMediaDuration", (PyCFunction)MediaObj_GetMediaDuration, 1,
+ PyDoc_STR("() -> (TimeValue _rv)")},
+ {"GetMediaLanguage", (PyCFunction)MediaObj_GetMediaLanguage, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetMediaLanguage", (PyCFunction)MediaObj_SetMediaLanguage, 1,
+ PyDoc_STR("(short language) -> None")},
+ {"GetMediaQuality", (PyCFunction)MediaObj_GetMediaQuality, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetMediaQuality", (PyCFunction)MediaObj_SetMediaQuality, 1,
+ PyDoc_STR("(short quality) -> None")},
+ {"GetMediaHandlerDescription", (PyCFunction)MediaObj_GetMediaHandlerDescription, 1,
+ PyDoc_STR("(Str255 creatorName) -> (OSType mediaType, OSType creatorManufacturer)")},
+ {"GetMediaUserData", (PyCFunction)MediaObj_GetMediaUserData, 1,
+ PyDoc_STR("() -> (UserData _rv)")},
+ {"GetMediaHandler", (PyCFunction)MediaObj_GetMediaHandler, 1,
+ PyDoc_STR("() -> (MediaHandler _rv)")},
+ {"SetMediaHandler", (PyCFunction)MediaObj_SetMediaHandler, 1,
+ PyDoc_STR("(MediaHandlerComponent mH) -> None")},
+ {"BeginMediaEdits", (PyCFunction)MediaObj_BeginMediaEdits, 1,
+ PyDoc_STR("() -> None")},
+ {"EndMediaEdits", (PyCFunction)MediaObj_EndMediaEdits, 1,
+ PyDoc_STR("() -> None")},
+ {"SetMediaDefaultDataRefIndex", (PyCFunction)MediaObj_SetMediaDefaultDataRefIndex, 1,
+ PyDoc_STR("(short index) -> None")},
+ {"GetMediaDataHandlerDescription", (PyCFunction)MediaObj_GetMediaDataHandlerDescription, 1,
+ PyDoc_STR("(short index, Str255 creatorName) -> (OSType dhType, OSType creatorManufacturer)")},
+ {"GetMediaDataHandler", (PyCFunction)MediaObj_GetMediaDataHandler, 1,
+ PyDoc_STR("(short index) -> (DataHandler _rv)")},
+ {"SetMediaDataHandler", (PyCFunction)MediaObj_SetMediaDataHandler, 1,
+ PyDoc_STR("(short index, DataHandlerComponent dataHandler) -> None")},
+ {"GetMediaSampleDescriptionCount", (PyCFunction)MediaObj_GetMediaSampleDescriptionCount, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetMediaSampleDescription", (PyCFunction)MediaObj_GetMediaSampleDescription, 1,
+ PyDoc_STR("(long index, SampleDescriptionHandle descH) -> None")},
+ {"SetMediaSampleDescription", (PyCFunction)MediaObj_SetMediaSampleDescription, 1,
+ PyDoc_STR("(long index, SampleDescriptionHandle descH) -> None")},
+ {"GetMediaSampleCount", (PyCFunction)MediaObj_GetMediaSampleCount, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetMediaSyncSampleCount", (PyCFunction)MediaObj_GetMediaSyncSampleCount, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SampleNumToMediaTime", (PyCFunction)MediaObj_SampleNumToMediaTime, 1,
+ PyDoc_STR("(long logicalSampleNum) -> (TimeValue sampleTime, TimeValue sampleDuration)")},
+ {"MediaTimeToSampleNum", (PyCFunction)MediaObj_MediaTimeToSampleNum, 1,
+ PyDoc_STR("(TimeValue time) -> (long sampleNum, TimeValue sampleTime, TimeValue sampleDuration)")},
+ {"AddMediaSample", (PyCFunction)MediaObj_AddMediaSample, 1,
+ PyDoc_STR("(Handle dataIn, long inOffset, unsigned long size, TimeValue durationPerSample, SampleDescriptionHandle sampleDescriptionH, long numberOfSamples, short sampleFlags) -> (TimeValue sampleTime)")},
+ {"AddMediaSampleReference", (PyCFunction)MediaObj_AddMediaSampleReference, 1,
+ PyDoc_STR("(long dataOffset, unsigned long size, TimeValue durationPerSample, SampleDescriptionHandle sampleDescriptionH, long numberOfSamples, short sampleFlags) -> (TimeValue sampleTime)")},
+ {"GetMediaSample", (PyCFunction)MediaObj_GetMediaSample, 1,
+ PyDoc_STR("(Handle dataOut, long maxSizeToGrow, TimeValue time, SampleDescriptionHandle sampleDescriptionH, long maxNumberOfSamples) -> (long size, TimeValue sampleTime, TimeValue durationPerSample, long sampleDescriptionIndex, long numberOfSamples, short sampleFlags)")},
+ {"GetMediaSampleReference", (PyCFunction)MediaObj_GetMediaSampleReference, 1,
+ PyDoc_STR("(TimeValue time, SampleDescriptionHandle sampleDescriptionH, long maxNumberOfSamples) -> (long dataOffset, long size, TimeValue sampleTime, TimeValue durationPerSample, long sampleDescriptionIndex, long numberOfSamples, short sampleFlags)")},
+ {"SetMediaPreferredChunkSize", (PyCFunction)MediaObj_SetMediaPreferredChunkSize, 1,
+ PyDoc_STR("(long maxChunkSize) -> None")},
+ {"GetMediaPreferredChunkSize", (PyCFunction)MediaObj_GetMediaPreferredChunkSize, 1,
+ PyDoc_STR("() -> (long maxChunkSize)")},
+ {"SetMediaShadowSync", (PyCFunction)MediaObj_SetMediaShadowSync, 1,
+ PyDoc_STR("(long frameDiffSampleNum, long syncSampleNum) -> None")},
+ {"GetMediaShadowSync", (PyCFunction)MediaObj_GetMediaShadowSync, 1,
+ PyDoc_STR("(long frameDiffSampleNum) -> (long syncSampleNum)")},
+ {"GetMediaDataSize", (PyCFunction)MediaObj_GetMediaDataSize, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (long _rv)")},
+ {"GetMediaDataSize64", (PyCFunction)MediaObj_GetMediaDataSize64, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (wide dataSize)")},
+ {"CopyMediaUserData", (PyCFunction)MediaObj_CopyMediaUserData, 1,
+ PyDoc_STR("(Media dstMedia, OSType copyRule) -> None")},
+ {"GetMediaNextInterestingTime", (PyCFunction)MediaObj_GetMediaNextInterestingTime, 1,
+ PyDoc_STR("(short interestingTimeFlags, TimeValue time, Fixed rate) -> (TimeValue interestingTime, TimeValue interestingDuration)")},
+ {"GetMediaDataRef", (PyCFunction)MediaObj_GetMediaDataRef, 1,
+ PyDoc_STR("(short index) -> (Handle dataRef, OSType dataRefType, long dataRefAttributes)")},
+ {"SetMediaDataRef", (PyCFunction)MediaObj_SetMediaDataRef, 1,
+ PyDoc_STR("(short index, Handle dataRef, OSType dataRefType) -> None")},
+ {"SetMediaDataRefAttributes", (PyCFunction)MediaObj_SetMediaDataRefAttributes, 1,
+ PyDoc_STR("(short index, long dataRefAttributes) -> None")},
+ {"AddMediaDataRef", (PyCFunction)MediaObj_AddMediaDataRef, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType) -> (short index)")},
+ {"GetMediaDataRefCount", (PyCFunction)MediaObj_GetMediaDataRefCount, 1,
+ PyDoc_STR("() -> (short count)")},
+ {"SetMediaPlayHints", (PyCFunction)MediaObj_SetMediaPlayHints, 1,
+ PyDoc_STR("(long flags, long flagsMask) -> None")},
+ {"GetMediaPlayHints", (PyCFunction)MediaObj_GetMediaPlayHints, 1,
+ PyDoc_STR("() -> (long flags)")},
+ {"GetMediaNextInterestingTimeOnly", (PyCFunction)MediaObj_GetMediaNextInterestingTimeOnly, 1,
+ PyDoc_STR("(short interestingTimeFlags, TimeValue time, Fixed rate) -> (TimeValue interestingTime)")},
+ {NULL, NULL, 0}
};
#define MediaObj_getsetlist NULL
@@ -3385,61 +3385,61 @@ static PyMethodDef MediaObj_methods[] = {
static PyObject *MediaObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- Media itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ Media itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MediaObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((MediaObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MediaObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((MediaObject *)_self)->ob_itself = itself;
+ return _self;
}
#define MediaObj_tp_free PyObject_Del
PyTypeObject Media_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.Media", /*tp_name*/
- sizeof(MediaObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) MediaObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) MediaObj_compare, /*tp_compare*/
- (reprfunc) MediaObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) MediaObj_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*/
- MediaObj_methods, /* tp_methods */
- 0, /*tp_members*/
- MediaObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- MediaObj_tp_init, /* tp_init */
- MediaObj_tp_alloc, /* tp_alloc */
- MediaObj_tp_new, /* tp_new */
- MediaObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.Media", /*tp_name*/
+ sizeof(MediaObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) MediaObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) MediaObj_compare, /*tp_compare*/
+ (reprfunc) MediaObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) MediaObj_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*/
+ MediaObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ MediaObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ MediaObj_tp_init, /* tp_init */
+ MediaObj_tp_alloc, /* tp_alloc */
+ MediaObj_tp_new, /* tp_new */
+ MediaObj_tp_free, /* tp_free */
};
/* --------------------- End object type Media ---------------------- */
@@ -3452,1271 +3452,1271 @@ PyTypeObject Track_Type;
#define TrackObj_Check(x) ((x)->ob_type == &Track_Type || PyObject_TypeCheck((x), &Track_Type))
typedef struct TrackObject {
- PyObject_HEAD
- Track ob_itself;
+ PyObject_HEAD
+ Track ob_itself;
} TrackObject;
PyObject *TrackObj_New(Track itself)
{
- TrackObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create Track from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(TrackObject, &Track_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ TrackObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create Track from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(TrackObject, &Track_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int TrackObj_Convert(PyObject *v, Track *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!TrackObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Track required");
- return 0;
- }
- *p_itself = ((TrackObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!TrackObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Track required");
+ return 0;
+ }
+ *p_itself = ((TrackObject *)v)->ob_itself;
+ return 1;
}
static void TrackObj_dealloc(TrackObject *self)
{
- if (self->ob_itself) DisposeMovieTrack(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_itself) DisposeMovieTrack(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *TrackObj_LoadTrackIntoRam(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue time;
- TimeValue duration;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue time;
+ TimeValue duration;
+ long flags;
#ifndef LoadTrackIntoRam
- PyMac_PRECHECK(LoadTrackIntoRam);
-#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &time,
- &duration,
- &flags))
- return NULL;
- _err = LoadTrackIntoRam(_self->ob_itself,
- time,
- duration,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(LoadTrackIntoRam);
+#endif
+ if (!PyArg_ParseTuple(_args, "lll",
+ &time,
+ &duration,
+ &flags))
+ return NULL;
+ _err = LoadTrackIntoRam(_self->ob_itself,
+ time,
+ duration,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackPict(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle _rv;
- TimeValue time;
+ PyObject *_res = NULL;
+ PicHandle _rv;
+ TimeValue time;
#ifndef GetTrackPict
- PyMac_PRECHECK(GetTrackPict);
+ PyMac_PRECHECK(GetTrackPict);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &time))
- return NULL;
- _rv = GetTrackPict(_self->ob_itself,
- time);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &time))
+ return NULL;
+ _rv = GetTrackPict(_self->ob_itself,
+ time);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackClipRgn(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetTrackClipRgn
- PyMac_PRECHECK(GetTrackClipRgn);
+ PyMac_PRECHECK(GetTrackClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackClipRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackClipRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackClipRgn(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle theClip;
+ PyObject *_res = NULL;
+ RgnHandle theClip;
#ifndef SetTrackClipRgn
- PyMac_PRECHECK(SetTrackClipRgn);
+ PyMac_PRECHECK(SetTrackClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theClip))
- return NULL;
- SetTrackClipRgn(_self->ob_itself,
- theClip);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theClip))
+ return NULL;
+ SetTrackClipRgn(_self->ob_itself,
+ theClip);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackDisplayBoundsRgn(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetTrackDisplayBoundsRgn
- PyMac_PRECHECK(GetTrackDisplayBoundsRgn);
+ PyMac_PRECHECK(GetTrackDisplayBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackDisplayBoundsRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackDisplayBoundsRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackMovieBoundsRgn(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetTrackMovieBoundsRgn
- PyMac_PRECHECK(GetTrackMovieBoundsRgn);
+ PyMac_PRECHECK(GetTrackMovieBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackMovieBoundsRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackMovieBoundsRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackBoundsRgn(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetTrackBoundsRgn
- PyMac_PRECHECK(GetTrackBoundsRgn);
+ PyMac_PRECHECK(GetTrackBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackBoundsRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackBoundsRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackMatte(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle _rv;
+ PyObject *_res = NULL;
+ PixMapHandle _rv;
#ifndef GetTrackMatte
- PyMac_PRECHECK(GetTrackMatte);
+ PyMac_PRECHECK(GetTrackMatte);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackMatte(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackMatte(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackMatte(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle theMatte;
+ PyObject *_res = NULL;
+ PixMapHandle theMatte;
#ifndef SetTrackMatte
- PyMac_PRECHECK(SetTrackMatte);
+ PyMac_PRECHECK(SetTrackMatte);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theMatte))
- return NULL;
- SetTrackMatte(_self->ob_itself,
- theMatte);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theMatte))
+ return NULL;
+ SetTrackMatte(_self->ob_itself,
+ theMatte);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackID(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetTrackID
- PyMac_PRECHECK(GetTrackID);
+ PyMac_PRECHECK(GetTrackID);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackID(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackID(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackMovie(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
+ PyObject *_res = NULL;
+ Movie _rv;
#ifndef GetTrackMovie
- PyMac_PRECHECK(GetTrackMovie);
+ PyMac_PRECHECK(GetTrackMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackMovie(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackMovie(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackCreationTime(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
+ PyObject *_res = NULL;
+ unsigned long _rv;
#ifndef GetTrackCreationTime
- PyMac_PRECHECK(GetTrackCreationTime);
+ PyMac_PRECHECK(GetTrackCreationTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackCreationTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackCreationTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackModificationTime(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
+ PyObject *_res = NULL;
+ unsigned long _rv;
#ifndef GetTrackModificationTime
- PyMac_PRECHECK(GetTrackModificationTime);
+ PyMac_PRECHECK(GetTrackModificationTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackModificationTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackModificationTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackEnabled(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef GetTrackEnabled
- PyMac_PRECHECK(GetTrackEnabled);
+ PyMac_PRECHECK(GetTrackEnabled);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackEnabled(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackEnabled(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackEnabled(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean isEnabled;
+ PyObject *_res = NULL;
+ Boolean isEnabled;
#ifndef SetTrackEnabled
- PyMac_PRECHECK(SetTrackEnabled);
+ PyMac_PRECHECK(SetTrackEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &isEnabled))
- return NULL;
- SetTrackEnabled(_self->ob_itself,
- isEnabled);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &isEnabled))
+ return NULL;
+ SetTrackEnabled(_self->ob_itself,
+ isEnabled);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackUsage(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetTrackUsage
- PyMac_PRECHECK(GetTrackUsage);
+ PyMac_PRECHECK(GetTrackUsage);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackUsage(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackUsage(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackUsage(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long usage;
+ PyObject *_res = NULL;
+ long usage;
#ifndef SetTrackUsage
- PyMac_PRECHECK(SetTrackUsage);
+ PyMac_PRECHECK(SetTrackUsage);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &usage))
- return NULL;
- SetTrackUsage(_self->ob_itself,
- usage);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &usage))
+ return NULL;
+ SetTrackUsage(_self->ob_itself,
+ usage);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackDuration(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
+ PyObject *_res = NULL;
+ TimeValue _rv;
#ifndef GetTrackDuration
- PyMac_PRECHECK(GetTrackDuration);
+ PyMac_PRECHECK(GetTrackDuration);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackDuration(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackDuration(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackOffset(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
+ PyObject *_res = NULL;
+ TimeValue _rv;
#ifndef GetTrackOffset
- PyMac_PRECHECK(GetTrackOffset);
+ PyMac_PRECHECK(GetTrackOffset);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackOffset(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackOffset(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackOffset(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue movieOffsetTime;
+ PyObject *_res = NULL;
+ TimeValue movieOffsetTime;
#ifndef SetTrackOffset
- PyMac_PRECHECK(SetTrackOffset);
+ PyMac_PRECHECK(SetTrackOffset);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &movieOffsetTime))
- return NULL;
- SetTrackOffset(_self->ob_itself,
- movieOffsetTime);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &movieOffsetTime))
+ return NULL;
+ SetTrackOffset(_self->ob_itself,
+ movieOffsetTime);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackLayer(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetTrackLayer
- PyMac_PRECHECK(GetTrackLayer);
+ PyMac_PRECHECK(GetTrackLayer);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackLayer(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackLayer(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackLayer(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short layer;
+ PyObject *_res = NULL;
+ short layer;
#ifndef SetTrackLayer
- PyMac_PRECHECK(SetTrackLayer);
+ PyMac_PRECHECK(SetTrackLayer);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &layer))
- return NULL;
- SetTrackLayer(_self->ob_itself,
- layer);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &layer))
+ return NULL;
+ SetTrackLayer(_self->ob_itself,
+ layer);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackAlternate(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
+ PyObject *_res = NULL;
+ Track _rv;
#ifndef GetTrackAlternate
- PyMac_PRECHECK(GetTrackAlternate);
+ PyMac_PRECHECK(GetTrackAlternate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackAlternate(_self->ob_itself);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackAlternate(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackAlternate(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track alternateT;
+ PyObject *_res = NULL;
+ Track alternateT;
#ifndef SetTrackAlternate
- PyMac_PRECHECK(SetTrackAlternate);
+ PyMac_PRECHECK(SetTrackAlternate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- TrackObj_Convert, &alternateT))
- return NULL;
- SetTrackAlternate(_self->ob_itself,
- alternateT);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ TrackObj_Convert, &alternateT))
+ return NULL;
+ SetTrackAlternate(_self->ob_itself,
+ alternateT);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackVolume(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetTrackVolume
- PyMac_PRECHECK(GetTrackVolume);
+ PyMac_PRECHECK(GetTrackVolume);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackVolume(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackVolume(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackVolume(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short volume;
+ PyObject *_res = NULL;
+ short volume;
#ifndef SetTrackVolume
- PyMac_PRECHECK(SetTrackVolume);
+ PyMac_PRECHECK(SetTrackVolume);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &volume))
- return NULL;
- SetTrackVolume(_self->ob_itself,
- volume);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &volume))
+ return NULL;
+ SetTrackVolume(_self->ob_itself,
+ volume);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackDimensions(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed width;
- Fixed height;
+ PyObject *_res = NULL;
+ Fixed width;
+ Fixed height;
#ifndef GetTrackDimensions
- PyMac_PRECHECK(GetTrackDimensions);
+ PyMac_PRECHECK(GetTrackDimensions);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetTrackDimensions(_self->ob_itself,
- &width,
- &height);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildFixed, width,
- PyMac_BuildFixed, height);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetTrackDimensions(_self->ob_itself,
+ &width,
+ &height);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildFixed, width,
+ PyMac_BuildFixed, height);
+ return _res;
}
static PyObject *TrackObj_SetTrackDimensions(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed width;
- Fixed height;
+ PyObject *_res = NULL;
+ Fixed width;
+ Fixed height;
#ifndef SetTrackDimensions
- PyMac_PRECHECK(SetTrackDimensions);
+ PyMac_PRECHECK(SetTrackDimensions);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetFixed, &width,
- PyMac_GetFixed, &height))
- return NULL;
- SetTrackDimensions(_self->ob_itself,
- width,
- height);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetFixed, &width,
+ PyMac_GetFixed, &height))
+ return NULL;
+ SetTrackDimensions(_self->ob_itself,
+ width,
+ height);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackUserData(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UserData _rv;
+ PyObject *_res = NULL;
+ UserData _rv;
#ifndef GetTrackUserData
- PyMac_PRECHECK(GetTrackUserData);
+ PyMac_PRECHECK(GetTrackUserData);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackUserData(_self->ob_itself);
- _res = Py_BuildValue("O&",
- UserDataObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackUserData(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ UserDataObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackSoundLocalizationSettings(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle settings;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle settings;
#ifndef GetTrackSoundLocalizationSettings
- PyMac_PRECHECK(GetTrackSoundLocalizationSettings);
+ PyMac_PRECHECK(GetTrackSoundLocalizationSettings);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetTrackSoundLocalizationSettings(_self->ob_itself,
- &settings);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, settings);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetTrackSoundLocalizationSettings(_self->ob_itself,
+ &settings);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, settings);
+ return _res;
}
static PyObject *TrackObj_SetTrackSoundLocalizationSettings(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle settings;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle settings;
#ifndef SetTrackSoundLocalizationSettings
- PyMac_PRECHECK(SetTrackSoundLocalizationSettings);
+ PyMac_PRECHECK(SetTrackSoundLocalizationSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &settings))
- return NULL;
- _err = SetTrackSoundLocalizationSettings(_self->ob_itself,
- settings);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &settings))
+ return NULL;
+ _err = SetTrackSoundLocalizationSettings(_self->ob_itself,
+ settings);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_NewTrackMedia(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Media _rv;
- OSType mediaType;
- TimeScale timeScale;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ Media _rv;
+ OSType mediaType;
+ TimeScale timeScale;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef NewTrackMedia
- PyMac_PRECHECK(NewTrackMedia);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&O&",
- PyMac_GetOSType, &mediaType,
- &timeScale,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _rv = NewTrackMedia(_self->ob_itself,
- mediaType,
- timeScale,
- dataRef,
- dataRefType);
- _res = Py_BuildValue("O&",
- MediaObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(NewTrackMedia);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&O&",
+ PyMac_GetOSType, &mediaType,
+ &timeScale,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _rv = NewTrackMedia(_self->ob_itself,
+ mediaType,
+ timeScale,
+ dataRef,
+ dataRefType);
+ _res = Py_BuildValue("O&",
+ MediaObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackMedia(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Media _rv;
+ PyObject *_res = NULL;
+ Media _rv;
#ifndef GetTrackMedia
- PyMac_PRECHECK(GetTrackMedia);
+ PyMac_PRECHECK(GetTrackMedia);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackMedia(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MediaObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackMedia(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MediaObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_InsertMediaIntoTrack(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue trackStart;
- TimeValue mediaTime;
- TimeValue mediaDuration;
- Fixed mediaRate;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue trackStart;
+ TimeValue mediaTime;
+ TimeValue mediaDuration;
+ Fixed mediaRate;
#ifndef InsertMediaIntoTrack
- PyMac_PRECHECK(InsertMediaIntoTrack);
-#endif
- if (!PyArg_ParseTuple(_args, "lllO&",
- &trackStart,
- &mediaTime,
- &mediaDuration,
- PyMac_GetFixed, &mediaRate))
- return NULL;
- _err = InsertMediaIntoTrack(_self->ob_itself,
- trackStart,
- mediaTime,
- mediaDuration,
- mediaRate);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(InsertMediaIntoTrack);
+#endif
+ if (!PyArg_ParseTuple(_args, "lllO&",
+ &trackStart,
+ &mediaTime,
+ &mediaDuration,
+ PyMac_GetFixed, &mediaRate))
+ return NULL;
+ _err = InsertMediaIntoTrack(_self->ob_itself,
+ trackStart,
+ mediaTime,
+ mediaDuration,
+ mediaRate);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_InsertTrackSegment(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track dstTrack;
- TimeValue srcIn;
- TimeValue srcDuration;
- TimeValue dstIn;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track dstTrack;
+ TimeValue srcIn;
+ TimeValue srcDuration;
+ TimeValue dstIn;
#ifndef InsertTrackSegment
- PyMac_PRECHECK(InsertTrackSegment);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- TrackObj_Convert, &dstTrack,
- &srcIn,
- &srcDuration,
- &dstIn))
- return NULL;
- _err = InsertTrackSegment(_self->ob_itself,
- dstTrack,
- srcIn,
- srcDuration,
- dstIn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(InsertTrackSegment);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ TrackObj_Convert, &dstTrack,
+ &srcIn,
+ &srcDuration,
+ &dstIn))
+ return NULL;
+ _err = InsertTrackSegment(_self->ob_itself,
+ dstTrack,
+ srcIn,
+ srcDuration,
+ dstIn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_InsertEmptyTrackSegment(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue dstIn;
- TimeValue dstDuration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue dstIn;
+ TimeValue dstDuration;
#ifndef InsertEmptyTrackSegment
- PyMac_PRECHECK(InsertEmptyTrackSegment);
+ PyMac_PRECHECK(InsertEmptyTrackSegment);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &dstIn,
- &dstDuration))
- return NULL;
- _err = InsertEmptyTrackSegment(_self->ob_itself,
- dstIn,
- dstDuration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &dstIn,
+ &dstDuration))
+ return NULL;
+ _err = InsertEmptyTrackSegment(_self->ob_itself,
+ dstIn,
+ dstDuration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_DeleteTrackSegment(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef DeleteTrackSegment
- PyMac_PRECHECK(DeleteTrackSegment);
+ PyMac_PRECHECK(DeleteTrackSegment);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _err = DeleteTrackSegment(_self->ob_itself,
- startTime,
- duration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _err = DeleteTrackSegment(_self->ob_itself,
+ startTime,
+ duration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_ScaleTrackSegment(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue oldDuration;
- TimeValue newDuration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue oldDuration;
+ TimeValue newDuration;
#ifndef ScaleTrackSegment
- PyMac_PRECHECK(ScaleTrackSegment);
-#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &startTime,
- &oldDuration,
- &newDuration))
- return NULL;
- _err = ScaleTrackSegment(_self->ob_itself,
- startTime,
- oldDuration,
- newDuration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ScaleTrackSegment);
+#endif
+ if (!PyArg_ParseTuple(_args, "lll",
+ &startTime,
+ &oldDuration,
+ &newDuration))
+ return NULL;
+ _err = ScaleTrackSegment(_self->ob_itself,
+ startTime,
+ oldDuration,
+ newDuration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_IsScrapMovie(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component _rv;
+ PyObject *_res = NULL;
+ Component _rv;
#ifndef IsScrapMovie
- PyMac_PRECHECK(IsScrapMovie);
+ PyMac_PRECHECK(IsScrapMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsScrapMovie(_self->ob_itself);
- _res = Py_BuildValue("O&",
- CmpObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsScrapMovie(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_CopyTrackSettings(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track dstTrack;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track dstTrack;
#ifndef CopyTrackSettings
- PyMac_PRECHECK(CopyTrackSettings);
+ PyMac_PRECHECK(CopyTrackSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- TrackObj_Convert, &dstTrack))
- return NULL;
- _err = CopyTrackSettings(_self->ob_itself,
- dstTrack);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ TrackObj_Convert, &dstTrack))
+ return NULL;
+ _err = CopyTrackSettings(_self->ob_itself,
+ dstTrack);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_AddEmptyTrackToMovie(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie dstMovie;
- Handle dataRef;
- OSType dataRefType;
- Track dstTrack;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie dstMovie;
+ Handle dataRef;
+ OSType dataRefType;
+ Track dstTrack;
#ifndef AddEmptyTrackToMovie
- PyMac_PRECHECK(AddEmptyTrackToMovie);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- MovieObj_Convert, &dstMovie,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = AddEmptyTrackToMovie(_self->ob_itself,
- dstMovie,
- dataRef,
- dataRefType,
- &dstTrack);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- TrackObj_New, dstTrack);
- return _res;
+ PyMac_PRECHECK(AddEmptyTrackToMovie);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ MovieObj_Convert, &dstMovie,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = AddEmptyTrackToMovie(_self->ob_itself,
+ dstMovie,
+ dataRef,
+ dataRefType,
+ &dstTrack);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, dstTrack);
+ return _res;
}
static PyObject *TrackObj_AddClonedTrackToMovie(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie dstMovie;
- long flags;
- Track dstTrack;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie dstMovie;
+ long flags;
+ Track dstTrack;
#ifndef AddClonedTrackToMovie
- PyMac_PRECHECK(AddClonedTrackToMovie);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- MovieObj_Convert, &dstMovie,
- &flags))
- return NULL;
- _err = AddClonedTrackToMovie(_self->ob_itself,
- dstMovie,
- flags,
- &dstTrack);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- TrackObj_New, dstTrack);
- return _res;
+ PyMac_PRECHECK(AddClonedTrackToMovie);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ MovieObj_Convert, &dstMovie,
+ &flags))
+ return NULL;
+ _err = AddClonedTrackToMovie(_self->ob_itself,
+ dstMovie,
+ flags,
+ &dstTrack);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, dstTrack);
+ return _res;
}
static PyObject *TrackObj_AddTrackReference(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track refTrack;
- OSType refType;
- long addedIndex;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track refTrack;
+ OSType refType;
+ long addedIndex;
#ifndef AddTrackReference
- PyMac_PRECHECK(AddTrackReference);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- TrackObj_Convert, &refTrack,
- PyMac_GetOSType, &refType))
- return NULL;
- _err = AddTrackReference(_self->ob_itself,
- refTrack,
- refType,
- &addedIndex);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- addedIndex);
- return _res;
+ PyMac_PRECHECK(AddTrackReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ TrackObj_Convert, &refTrack,
+ PyMac_GetOSType, &refType))
+ return NULL;
+ _err = AddTrackReference(_self->ob_itself,
+ refTrack,
+ refType,
+ &addedIndex);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ addedIndex);
+ return _res;
}
static PyObject *TrackObj_DeleteTrackReference(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType refType;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType refType;
+ long index;
#ifndef DeleteTrackReference
- PyMac_PRECHECK(DeleteTrackReference);
+ PyMac_PRECHECK(DeleteTrackReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetOSType, &refType,
- &index))
- return NULL;
- _err = DeleteTrackReference(_self->ob_itself,
- refType,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetOSType, &refType,
+ &index))
+ return NULL;
+ _err = DeleteTrackReference(_self->ob_itself,
+ refType,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_SetTrackReference(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track refTrack;
- OSType refType;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track refTrack;
+ OSType refType;
+ long index;
#ifndef SetTrackReference
- PyMac_PRECHECK(SetTrackReference);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- TrackObj_Convert, &refTrack,
- PyMac_GetOSType, &refType,
- &index))
- return NULL;
- _err = SetTrackReference(_self->ob_itself,
- refTrack,
- refType,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetTrackReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ TrackObj_Convert, &refTrack,
+ PyMac_GetOSType, &refType,
+ &index))
+ return NULL;
+ _err = SetTrackReference(_self->ob_itself,
+ refTrack,
+ refType,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackReference(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- OSType refType;
- long index;
+ PyObject *_res = NULL;
+ Track _rv;
+ OSType refType;
+ long index;
#ifndef GetTrackReference
- PyMac_PRECHECK(GetTrackReference);
+ PyMac_PRECHECK(GetTrackReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetOSType, &refType,
- &index))
- return NULL;
- _rv = GetTrackReference(_self->ob_itself,
- refType,
- index);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetOSType, &refType,
+ &index))
+ return NULL;
+ _rv = GetTrackReference(_self->ob_itself,
+ refType,
+ index);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetNextTrackReferenceType(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSType _rv;
- OSType refType;
+ PyObject *_res = NULL;
+ OSType _rv;
+ OSType refType;
#ifndef GetNextTrackReferenceType
- PyMac_PRECHECK(GetNextTrackReferenceType);
+ PyMac_PRECHECK(GetNextTrackReferenceType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &refType))
- return NULL;
- _rv = GetNextTrackReferenceType(_self->ob_itself,
- refType);
- _res = Py_BuildValue("O&",
- PyMac_BuildOSType, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &refType))
+ return NULL;
+ _rv = GetNextTrackReferenceType(_self->ob_itself,
+ refType);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildOSType, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackReferenceCount(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- OSType refType;
+ PyObject *_res = NULL;
+ long _rv;
+ OSType refType;
#ifndef GetTrackReferenceCount
- PyMac_PRECHECK(GetTrackReferenceCount);
+ PyMac_PRECHECK(GetTrackReferenceCount);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &refType))
- return NULL;
- _rv = GetTrackReferenceCount(_self->ob_itself,
- refType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &refType))
+ return NULL;
+ _rv = GetTrackReferenceCount(_self->ob_itself,
+ refType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackEditRate(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- TimeValue atTime;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ TimeValue atTime;
#ifndef GetTrackEditRate
- PyMac_PRECHECK(GetTrackEditRate);
+ PyMac_PRECHECK(GetTrackEditRate);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &atTime))
- return NULL;
- _rv = GetTrackEditRate(_self->ob_itself,
- atTime);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &atTime))
+ return NULL;
+ _rv = GetTrackEditRate(_self->ob_itself,
+ atTime);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackDataSize(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ long _rv;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef GetTrackDataSize
- PyMac_PRECHECK(GetTrackDataSize);
+ PyMac_PRECHECK(GetTrackDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _rv = GetTrackDataSize(_self->ob_itself,
- startTime,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = GetTrackDataSize(_self->ob_itself,
+ startTime,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackDataSize64(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue duration;
- wide dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue duration;
+ wide dataSize;
#ifndef GetTrackDataSize64
- PyMac_PRECHECK(GetTrackDataSize64);
-#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _err = GetTrackDataSize64(_self->ob_itself,
- startTime,
- duration,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, dataSize);
- return _res;
+ PyMac_PRECHECK(GetTrackDataSize64);
+#endif
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _err = GetTrackDataSize64(_self->ob_itself,
+ startTime,
+ duration,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, dataSize);
+ return _res;
}
static PyObject *TrackObj_PtInTrack(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt;
#ifndef PtInTrack
- PyMac_PRECHECK(PtInTrack);
+ PyMac_PRECHECK(PtInTrack);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &pt))
- return NULL;
- _rv = PtInTrack(_self->ob_itself,
- pt);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &pt))
+ return NULL;
+ _rv = PtInTrack(_self->ob_itself,
+ pt);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_CopyTrackUserData(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track dstTrack;
- OSType copyRule;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track dstTrack;
+ OSType copyRule;
#ifndef CopyTrackUserData
- PyMac_PRECHECK(CopyTrackUserData);
+ PyMac_PRECHECK(CopyTrackUserData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- TrackObj_Convert, &dstTrack,
- PyMac_GetOSType, &copyRule))
- return NULL;
- _err = CopyTrackUserData(_self->ob_itself,
- dstTrack,
- copyRule);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ TrackObj_Convert, &dstTrack,
+ PyMac_GetOSType, &copyRule))
+ return NULL;
+ _err = CopyTrackUserData(_self->ob_itself,
+ dstTrack,
+ copyRule);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackNextInterestingTime(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short interestingTimeFlags;
- TimeValue time;
- Fixed rate;
- TimeValue interestingTime;
- TimeValue interestingDuration;
+ PyObject *_res = NULL;
+ short interestingTimeFlags;
+ TimeValue time;
+ Fixed rate;
+ TimeValue interestingTime;
+ TimeValue interestingDuration;
#ifndef GetTrackNextInterestingTime
- PyMac_PRECHECK(GetTrackNextInterestingTime);
-#endif
- if (!PyArg_ParseTuple(_args, "hlO&",
- &interestingTimeFlags,
- &time,
- PyMac_GetFixed, &rate))
- return NULL;
- GetTrackNextInterestingTime(_self->ob_itself,
- interestingTimeFlags,
- time,
- rate,
- &interestingTime,
- &interestingDuration);
- _res = Py_BuildValue("ll",
- interestingTime,
- interestingDuration);
- return _res;
+ PyMac_PRECHECK(GetTrackNextInterestingTime);
+#endif
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &interestingTimeFlags,
+ &time,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ GetTrackNextInterestingTime(_self->ob_itself,
+ interestingTimeFlags,
+ time,
+ rate,
+ &interestingTime,
+ &interestingDuration);
+ _res = Py_BuildValue("ll",
+ interestingTime,
+ interestingDuration);
+ return _res;
}
static PyObject *TrackObj_GetTrackSegmentDisplayBoundsRgn(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- TimeValue time;
- TimeValue duration;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ TimeValue time;
+ TimeValue duration;
#ifndef GetTrackSegmentDisplayBoundsRgn
- PyMac_PRECHECK(GetTrackSegmentDisplayBoundsRgn);
+ PyMac_PRECHECK(GetTrackSegmentDisplayBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &time,
- &duration))
- return NULL;
- _rv = GetTrackSegmentDisplayBoundsRgn(_self->ob_itself,
- time,
- duration);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &time,
+ &duration))
+ return NULL;
+ _rv = GetTrackSegmentDisplayBoundsRgn(_self->ob_itself,
+ time,
+ duration);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TrackObj_GetTrackStatus(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
#ifndef GetTrackStatus
- PyMac_PRECHECK(GetTrackStatus);
+ PyMac_PRECHECK(GetTrackStatus);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetTrackStatus(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetTrackStatus(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TrackObj_SetTrackLoadSettings(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue preloadTime;
- TimeValue preloadDuration;
- long preloadFlags;
- long defaultHints;
+ PyObject *_res = NULL;
+ TimeValue preloadTime;
+ TimeValue preloadDuration;
+ long preloadFlags;
+ long defaultHints;
#ifndef SetTrackLoadSettings
- PyMac_PRECHECK(SetTrackLoadSettings);
-#endif
- if (!PyArg_ParseTuple(_args, "llll",
- &preloadTime,
- &preloadDuration,
- &preloadFlags,
- &defaultHints))
- return NULL;
- SetTrackLoadSettings(_self->ob_itself,
- preloadTime,
- preloadDuration,
- preloadFlags,
- defaultHints);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetTrackLoadSettings);
+#endif
+ if (!PyArg_ParseTuple(_args, "llll",
+ &preloadTime,
+ &preloadDuration,
+ &preloadFlags,
+ &defaultHints))
+ return NULL;
+ SetTrackLoadSettings(_self->ob_itself,
+ preloadTime,
+ preloadDuration,
+ preloadFlags,
+ defaultHints);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TrackObj_GetTrackLoadSettings(TrackObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue preloadTime;
- TimeValue preloadDuration;
- long preloadFlags;
- long defaultHints;
+ PyObject *_res = NULL;
+ TimeValue preloadTime;
+ TimeValue preloadDuration;
+ long preloadFlags;
+ long defaultHints;
#ifndef GetTrackLoadSettings
- PyMac_PRECHECK(GetTrackLoadSettings);
-#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetTrackLoadSettings(_self->ob_itself,
- &preloadTime,
- &preloadDuration,
- &preloadFlags,
- &defaultHints);
- _res = Py_BuildValue("llll",
- preloadTime,
- preloadDuration,
- preloadFlags,
- defaultHints);
- return _res;
+ PyMac_PRECHECK(GetTrackLoadSettings);
+#endif
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetTrackLoadSettings(_self->ob_itself,
+ &preloadTime,
+ &preloadDuration,
+ &preloadFlags,
+ &defaultHints);
+ _res = Py_BuildValue("llll",
+ preloadTime,
+ preloadDuration,
+ preloadFlags,
+ defaultHints);
+ return _res;
}
static PyMethodDef TrackObj_methods[] = {
- {"LoadTrackIntoRam", (PyCFunction)TrackObj_LoadTrackIntoRam, 1,
- PyDoc_STR("(TimeValue time, TimeValue duration, long flags) -> None")},
- {"GetTrackPict", (PyCFunction)TrackObj_GetTrackPict, 1,
- PyDoc_STR("(TimeValue time) -> (PicHandle _rv)")},
- {"GetTrackClipRgn", (PyCFunction)TrackObj_GetTrackClipRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"SetTrackClipRgn", (PyCFunction)TrackObj_SetTrackClipRgn, 1,
- PyDoc_STR("(RgnHandle theClip) -> None")},
- {"GetTrackDisplayBoundsRgn", (PyCFunction)TrackObj_GetTrackDisplayBoundsRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"GetTrackMovieBoundsRgn", (PyCFunction)TrackObj_GetTrackMovieBoundsRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"GetTrackBoundsRgn", (PyCFunction)TrackObj_GetTrackBoundsRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"GetTrackMatte", (PyCFunction)TrackObj_GetTrackMatte, 1,
- PyDoc_STR("() -> (PixMapHandle _rv)")},
- {"SetTrackMatte", (PyCFunction)TrackObj_SetTrackMatte, 1,
- PyDoc_STR("(PixMapHandle theMatte) -> None")},
- {"GetTrackID", (PyCFunction)TrackObj_GetTrackID, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetTrackMovie", (PyCFunction)TrackObj_GetTrackMovie, 1,
- PyDoc_STR("() -> (Movie _rv)")},
- {"GetTrackCreationTime", (PyCFunction)TrackObj_GetTrackCreationTime, 1,
- PyDoc_STR("() -> (unsigned long _rv)")},
- {"GetTrackModificationTime", (PyCFunction)TrackObj_GetTrackModificationTime, 1,
- PyDoc_STR("() -> (unsigned long _rv)")},
- {"GetTrackEnabled", (PyCFunction)TrackObj_GetTrackEnabled, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SetTrackEnabled", (PyCFunction)TrackObj_SetTrackEnabled, 1,
- PyDoc_STR("(Boolean isEnabled) -> None")},
- {"GetTrackUsage", (PyCFunction)TrackObj_GetTrackUsage, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SetTrackUsage", (PyCFunction)TrackObj_SetTrackUsage, 1,
- PyDoc_STR("(long usage) -> None")},
- {"GetTrackDuration", (PyCFunction)TrackObj_GetTrackDuration, 1,
- PyDoc_STR("() -> (TimeValue _rv)")},
- {"GetTrackOffset", (PyCFunction)TrackObj_GetTrackOffset, 1,
- PyDoc_STR("() -> (TimeValue _rv)")},
- {"SetTrackOffset", (PyCFunction)TrackObj_SetTrackOffset, 1,
- PyDoc_STR("(TimeValue movieOffsetTime) -> None")},
- {"GetTrackLayer", (PyCFunction)TrackObj_GetTrackLayer, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetTrackLayer", (PyCFunction)TrackObj_SetTrackLayer, 1,
- PyDoc_STR("(short layer) -> None")},
- {"GetTrackAlternate", (PyCFunction)TrackObj_GetTrackAlternate, 1,
- PyDoc_STR("() -> (Track _rv)")},
- {"SetTrackAlternate", (PyCFunction)TrackObj_SetTrackAlternate, 1,
- PyDoc_STR("(Track alternateT) -> None")},
- {"GetTrackVolume", (PyCFunction)TrackObj_GetTrackVolume, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetTrackVolume", (PyCFunction)TrackObj_SetTrackVolume, 1,
- PyDoc_STR("(short volume) -> None")},
- {"GetTrackDimensions", (PyCFunction)TrackObj_GetTrackDimensions, 1,
- PyDoc_STR("() -> (Fixed width, Fixed height)")},
- {"SetTrackDimensions", (PyCFunction)TrackObj_SetTrackDimensions, 1,
- PyDoc_STR("(Fixed width, Fixed height) -> None")},
- {"GetTrackUserData", (PyCFunction)TrackObj_GetTrackUserData, 1,
- PyDoc_STR("() -> (UserData _rv)")},
- {"GetTrackSoundLocalizationSettings", (PyCFunction)TrackObj_GetTrackSoundLocalizationSettings, 1,
- PyDoc_STR("() -> (Handle settings)")},
- {"SetTrackSoundLocalizationSettings", (PyCFunction)TrackObj_SetTrackSoundLocalizationSettings, 1,
- PyDoc_STR("(Handle settings) -> None")},
- {"NewTrackMedia", (PyCFunction)TrackObj_NewTrackMedia, 1,
- PyDoc_STR("(OSType mediaType, TimeScale timeScale, Handle dataRef, OSType dataRefType) -> (Media _rv)")},
- {"GetTrackMedia", (PyCFunction)TrackObj_GetTrackMedia, 1,
- PyDoc_STR("() -> (Media _rv)")},
- {"InsertMediaIntoTrack", (PyCFunction)TrackObj_InsertMediaIntoTrack, 1,
- PyDoc_STR("(TimeValue trackStart, TimeValue mediaTime, TimeValue mediaDuration, Fixed mediaRate) -> None")},
- {"InsertTrackSegment", (PyCFunction)TrackObj_InsertTrackSegment, 1,
- PyDoc_STR("(Track dstTrack, TimeValue srcIn, TimeValue srcDuration, TimeValue dstIn) -> None")},
- {"InsertEmptyTrackSegment", (PyCFunction)TrackObj_InsertEmptyTrackSegment, 1,
- PyDoc_STR("(TimeValue dstIn, TimeValue dstDuration) -> None")},
- {"DeleteTrackSegment", (PyCFunction)TrackObj_DeleteTrackSegment, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> None")},
- {"ScaleTrackSegment", (PyCFunction)TrackObj_ScaleTrackSegment, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue oldDuration, TimeValue newDuration) -> None")},
- {"IsScrapMovie", (PyCFunction)TrackObj_IsScrapMovie, 1,
- PyDoc_STR("() -> (Component _rv)")},
- {"CopyTrackSettings", (PyCFunction)TrackObj_CopyTrackSettings, 1,
- PyDoc_STR("(Track dstTrack) -> None")},
- {"AddEmptyTrackToMovie", (PyCFunction)TrackObj_AddEmptyTrackToMovie, 1,
- PyDoc_STR("(Movie dstMovie, Handle dataRef, OSType dataRefType) -> (Track dstTrack)")},
- {"AddClonedTrackToMovie", (PyCFunction)TrackObj_AddClonedTrackToMovie, 1,
- PyDoc_STR("(Movie dstMovie, long flags) -> (Track dstTrack)")},
- {"AddTrackReference", (PyCFunction)TrackObj_AddTrackReference, 1,
- PyDoc_STR("(Track refTrack, OSType refType) -> (long addedIndex)")},
- {"DeleteTrackReference", (PyCFunction)TrackObj_DeleteTrackReference, 1,
- PyDoc_STR("(OSType refType, long index) -> None")},
- {"SetTrackReference", (PyCFunction)TrackObj_SetTrackReference, 1,
- PyDoc_STR("(Track refTrack, OSType refType, long index) -> None")},
- {"GetTrackReference", (PyCFunction)TrackObj_GetTrackReference, 1,
- PyDoc_STR("(OSType refType, long index) -> (Track _rv)")},
- {"GetNextTrackReferenceType", (PyCFunction)TrackObj_GetNextTrackReferenceType, 1,
- PyDoc_STR("(OSType refType) -> (OSType _rv)")},
- {"GetTrackReferenceCount", (PyCFunction)TrackObj_GetTrackReferenceCount, 1,
- PyDoc_STR("(OSType refType) -> (long _rv)")},
- {"GetTrackEditRate", (PyCFunction)TrackObj_GetTrackEditRate, 1,
- PyDoc_STR("(TimeValue atTime) -> (Fixed _rv)")},
- {"GetTrackDataSize", (PyCFunction)TrackObj_GetTrackDataSize, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (long _rv)")},
- {"GetTrackDataSize64", (PyCFunction)TrackObj_GetTrackDataSize64, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (wide dataSize)")},
- {"PtInTrack", (PyCFunction)TrackObj_PtInTrack, 1,
- PyDoc_STR("(Point pt) -> (Boolean _rv)")},
- {"CopyTrackUserData", (PyCFunction)TrackObj_CopyTrackUserData, 1,
- PyDoc_STR("(Track dstTrack, OSType copyRule) -> None")},
- {"GetTrackNextInterestingTime", (PyCFunction)TrackObj_GetTrackNextInterestingTime, 1,
- PyDoc_STR("(short interestingTimeFlags, TimeValue time, Fixed rate) -> (TimeValue interestingTime, TimeValue interestingDuration)")},
- {"GetTrackSegmentDisplayBoundsRgn", (PyCFunction)TrackObj_GetTrackSegmentDisplayBoundsRgn, 1,
- PyDoc_STR("(TimeValue time, TimeValue duration) -> (RgnHandle _rv)")},
- {"GetTrackStatus", (PyCFunction)TrackObj_GetTrackStatus, 1,
- PyDoc_STR("() -> (ComponentResult _rv)")},
- {"SetTrackLoadSettings", (PyCFunction)TrackObj_SetTrackLoadSettings, 1,
- PyDoc_STR("(TimeValue preloadTime, TimeValue preloadDuration, long preloadFlags, long defaultHints) -> None")},
- {"GetTrackLoadSettings", (PyCFunction)TrackObj_GetTrackLoadSettings, 1,
- PyDoc_STR("() -> (TimeValue preloadTime, TimeValue preloadDuration, long preloadFlags, long defaultHints)")},
- {NULL, NULL, 0}
+ {"LoadTrackIntoRam", (PyCFunction)TrackObj_LoadTrackIntoRam, 1,
+ PyDoc_STR("(TimeValue time, TimeValue duration, long flags) -> None")},
+ {"GetTrackPict", (PyCFunction)TrackObj_GetTrackPict, 1,
+ PyDoc_STR("(TimeValue time) -> (PicHandle _rv)")},
+ {"GetTrackClipRgn", (PyCFunction)TrackObj_GetTrackClipRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"SetTrackClipRgn", (PyCFunction)TrackObj_SetTrackClipRgn, 1,
+ PyDoc_STR("(RgnHandle theClip) -> None")},
+ {"GetTrackDisplayBoundsRgn", (PyCFunction)TrackObj_GetTrackDisplayBoundsRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"GetTrackMovieBoundsRgn", (PyCFunction)TrackObj_GetTrackMovieBoundsRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"GetTrackBoundsRgn", (PyCFunction)TrackObj_GetTrackBoundsRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"GetTrackMatte", (PyCFunction)TrackObj_GetTrackMatte, 1,
+ PyDoc_STR("() -> (PixMapHandle _rv)")},
+ {"SetTrackMatte", (PyCFunction)TrackObj_SetTrackMatte, 1,
+ PyDoc_STR("(PixMapHandle theMatte) -> None")},
+ {"GetTrackID", (PyCFunction)TrackObj_GetTrackID, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetTrackMovie", (PyCFunction)TrackObj_GetTrackMovie, 1,
+ PyDoc_STR("() -> (Movie _rv)")},
+ {"GetTrackCreationTime", (PyCFunction)TrackObj_GetTrackCreationTime, 1,
+ PyDoc_STR("() -> (unsigned long _rv)")},
+ {"GetTrackModificationTime", (PyCFunction)TrackObj_GetTrackModificationTime, 1,
+ PyDoc_STR("() -> (unsigned long _rv)")},
+ {"GetTrackEnabled", (PyCFunction)TrackObj_GetTrackEnabled, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SetTrackEnabled", (PyCFunction)TrackObj_SetTrackEnabled, 1,
+ PyDoc_STR("(Boolean isEnabled) -> None")},
+ {"GetTrackUsage", (PyCFunction)TrackObj_GetTrackUsage, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SetTrackUsage", (PyCFunction)TrackObj_SetTrackUsage, 1,
+ PyDoc_STR("(long usage) -> None")},
+ {"GetTrackDuration", (PyCFunction)TrackObj_GetTrackDuration, 1,
+ PyDoc_STR("() -> (TimeValue _rv)")},
+ {"GetTrackOffset", (PyCFunction)TrackObj_GetTrackOffset, 1,
+ PyDoc_STR("() -> (TimeValue _rv)")},
+ {"SetTrackOffset", (PyCFunction)TrackObj_SetTrackOffset, 1,
+ PyDoc_STR("(TimeValue movieOffsetTime) -> None")},
+ {"GetTrackLayer", (PyCFunction)TrackObj_GetTrackLayer, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetTrackLayer", (PyCFunction)TrackObj_SetTrackLayer, 1,
+ PyDoc_STR("(short layer) -> None")},
+ {"GetTrackAlternate", (PyCFunction)TrackObj_GetTrackAlternate, 1,
+ PyDoc_STR("() -> (Track _rv)")},
+ {"SetTrackAlternate", (PyCFunction)TrackObj_SetTrackAlternate, 1,
+ PyDoc_STR("(Track alternateT) -> None")},
+ {"GetTrackVolume", (PyCFunction)TrackObj_GetTrackVolume, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetTrackVolume", (PyCFunction)TrackObj_SetTrackVolume, 1,
+ PyDoc_STR("(short volume) -> None")},
+ {"GetTrackDimensions", (PyCFunction)TrackObj_GetTrackDimensions, 1,
+ PyDoc_STR("() -> (Fixed width, Fixed height)")},
+ {"SetTrackDimensions", (PyCFunction)TrackObj_SetTrackDimensions, 1,
+ PyDoc_STR("(Fixed width, Fixed height) -> None")},
+ {"GetTrackUserData", (PyCFunction)TrackObj_GetTrackUserData, 1,
+ PyDoc_STR("() -> (UserData _rv)")},
+ {"GetTrackSoundLocalizationSettings", (PyCFunction)TrackObj_GetTrackSoundLocalizationSettings, 1,
+ PyDoc_STR("() -> (Handle settings)")},
+ {"SetTrackSoundLocalizationSettings", (PyCFunction)TrackObj_SetTrackSoundLocalizationSettings, 1,
+ PyDoc_STR("(Handle settings) -> None")},
+ {"NewTrackMedia", (PyCFunction)TrackObj_NewTrackMedia, 1,
+ PyDoc_STR("(OSType mediaType, TimeScale timeScale, Handle dataRef, OSType dataRefType) -> (Media _rv)")},
+ {"GetTrackMedia", (PyCFunction)TrackObj_GetTrackMedia, 1,
+ PyDoc_STR("() -> (Media _rv)")},
+ {"InsertMediaIntoTrack", (PyCFunction)TrackObj_InsertMediaIntoTrack, 1,
+ PyDoc_STR("(TimeValue trackStart, TimeValue mediaTime, TimeValue mediaDuration, Fixed mediaRate) -> None")},
+ {"InsertTrackSegment", (PyCFunction)TrackObj_InsertTrackSegment, 1,
+ PyDoc_STR("(Track dstTrack, TimeValue srcIn, TimeValue srcDuration, TimeValue dstIn) -> None")},
+ {"InsertEmptyTrackSegment", (PyCFunction)TrackObj_InsertEmptyTrackSegment, 1,
+ PyDoc_STR("(TimeValue dstIn, TimeValue dstDuration) -> None")},
+ {"DeleteTrackSegment", (PyCFunction)TrackObj_DeleteTrackSegment, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> None")},
+ {"ScaleTrackSegment", (PyCFunction)TrackObj_ScaleTrackSegment, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue oldDuration, TimeValue newDuration) -> None")},
+ {"IsScrapMovie", (PyCFunction)TrackObj_IsScrapMovie, 1,
+ PyDoc_STR("() -> (Component _rv)")},
+ {"CopyTrackSettings", (PyCFunction)TrackObj_CopyTrackSettings, 1,
+ PyDoc_STR("(Track dstTrack) -> None")},
+ {"AddEmptyTrackToMovie", (PyCFunction)TrackObj_AddEmptyTrackToMovie, 1,
+ PyDoc_STR("(Movie dstMovie, Handle dataRef, OSType dataRefType) -> (Track dstTrack)")},
+ {"AddClonedTrackToMovie", (PyCFunction)TrackObj_AddClonedTrackToMovie, 1,
+ PyDoc_STR("(Movie dstMovie, long flags) -> (Track dstTrack)")},
+ {"AddTrackReference", (PyCFunction)TrackObj_AddTrackReference, 1,
+ PyDoc_STR("(Track refTrack, OSType refType) -> (long addedIndex)")},
+ {"DeleteTrackReference", (PyCFunction)TrackObj_DeleteTrackReference, 1,
+ PyDoc_STR("(OSType refType, long index) -> None")},
+ {"SetTrackReference", (PyCFunction)TrackObj_SetTrackReference, 1,
+ PyDoc_STR("(Track refTrack, OSType refType, long index) -> None")},
+ {"GetTrackReference", (PyCFunction)TrackObj_GetTrackReference, 1,
+ PyDoc_STR("(OSType refType, long index) -> (Track _rv)")},
+ {"GetNextTrackReferenceType", (PyCFunction)TrackObj_GetNextTrackReferenceType, 1,
+ PyDoc_STR("(OSType refType) -> (OSType _rv)")},
+ {"GetTrackReferenceCount", (PyCFunction)TrackObj_GetTrackReferenceCount, 1,
+ PyDoc_STR("(OSType refType) -> (long _rv)")},
+ {"GetTrackEditRate", (PyCFunction)TrackObj_GetTrackEditRate, 1,
+ PyDoc_STR("(TimeValue atTime) -> (Fixed _rv)")},
+ {"GetTrackDataSize", (PyCFunction)TrackObj_GetTrackDataSize, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (long _rv)")},
+ {"GetTrackDataSize64", (PyCFunction)TrackObj_GetTrackDataSize64, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (wide dataSize)")},
+ {"PtInTrack", (PyCFunction)TrackObj_PtInTrack, 1,
+ PyDoc_STR("(Point pt) -> (Boolean _rv)")},
+ {"CopyTrackUserData", (PyCFunction)TrackObj_CopyTrackUserData, 1,
+ PyDoc_STR("(Track dstTrack, OSType copyRule) -> None")},
+ {"GetTrackNextInterestingTime", (PyCFunction)TrackObj_GetTrackNextInterestingTime, 1,
+ PyDoc_STR("(short interestingTimeFlags, TimeValue time, Fixed rate) -> (TimeValue interestingTime, TimeValue interestingDuration)")},
+ {"GetTrackSegmentDisplayBoundsRgn", (PyCFunction)TrackObj_GetTrackSegmentDisplayBoundsRgn, 1,
+ PyDoc_STR("(TimeValue time, TimeValue duration) -> (RgnHandle _rv)")},
+ {"GetTrackStatus", (PyCFunction)TrackObj_GetTrackStatus, 1,
+ PyDoc_STR("() -> (ComponentResult _rv)")},
+ {"SetTrackLoadSettings", (PyCFunction)TrackObj_SetTrackLoadSettings, 1,
+ PyDoc_STR("(TimeValue preloadTime, TimeValue preloadDuration, long preloadFlags, long defaultHints) -> None")},
+ {"GetTrackLoadSettings", (PyCFunction)TrackObj_GetTrackLoadSettings, 1,
+ PyDoc_STR("() -> (TimeValue preloadTime, TimeValue preloadDuration, long preloadFlags, long defaultHints)")},
+ {NULL, NULL, 0}
};
#define TrackObj_getsetlist NULL
@@ -4733,61 +4733,61 @@ static PyMethodDef TrackObj_methods[] = {
static PyObject *TrackObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- Track itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ Track itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TrackObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((TrackObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TrackObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((TrackObject *)_self)->ob_itself = itself;
+ return _self;
}
#define TrackObj_tp_free PyObject_Del
PyTypeObject Track_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.Track", /*tp_name*/
- sizeof(TrackObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) TrackObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) TrackObj_compare, /*tp_compare*/
- (reprfunc) TrackObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) TrackObj_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*/
- TrackObj_methods, /* tp_methods */
- 0, /*tp_members*/
- TrackObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- TrackObj_tp_init, /* tp_init */
- TrackObj_tp_alloc, /* tp_alloc */
- TrackObj_tp_new, /* tp_new */
- TrackObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.Track", /*tp_name*/
+ sizeof(TrackObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) TrackObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) TrackObj_compare, /*tp_compare*/
+ (reprfunc) TrackObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) TrackObj_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*/
+ TrackObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ TrackObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ TrackObj_tp_init, /* tp_init */
+ TrackObj_tp_alloc, /* tp_alloc */
+ TrackObj_tp_new, /* tp_new */
+ TrackObj_tp_free, /* tp_free */
};
/* --------------------- End object type Track ---------------------- */
@@ -4800,2476 +4800,2476 @@ PyTypeObject Movie_Type;
#define MovieObj_Check(x) ((x)->ob_type == &Movie_Type || PyObject_TypeCheck((x), &Movie_Type))
typedef struct MovieObject {
- PyObject_HEAD
- Movie ob_itself;
+ PyObject_HEAD
+ Movie ob_itself;
} MovieObject;
PyObject *MovieObj_New(Movie itself)
{
- MovieObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create Movie from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(MovieObject, &Movie_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ MovieObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create Movie from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(MovieObject, &Movie_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int MovieObj_Convert(PyObject *v, Movie *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!MovieObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Movie required");
- return 0;
- }
- *p_itself = ((MovieObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!MovieObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Movie required");
+ return 0;
+ }
+ *p_itself = ((MovieObject *)v)->ob_itself;
+ return 1;
}
static void MovieObj_dealloc(MovieObject *self)
{
- if (self->ob_itself) DisposeMovie(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_itself) DisposeMovie(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *MovieObj_MoviesTask(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long maxMilliSecToUse;
+ PyObject *_res = NULL;
+ long maxMilliSecToUse;
#ifndef MoviesTask
- PyMac_PRECHECK(MoviesTask);
+ PyMac_PRECHECK(MoviesTask);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &maxMilliSecToUse))
- return NULL;
- MoviesTask(_self->ob_itself,
- maxMilliSecToUse);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &maxMilliSecToUse))
+ return NULL;
+ MoviesTask(_self->ob_itself,
+ maxMilliSecToUse);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PrerollMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue time;
- Fixed Rate;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue time;
+ Fixed Rate;
#ifndef PrerollMovie
- PyMac_PRECHECK(PrerollMovie);
+ PyMac_PRECHECK(PrerollMovie);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &time,
- PyMac_GetFixed, &Rate))
- return NULL;
- _err = PrerollMovie(_self->ob_itself,
- time,
- Rate);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &time,
+ PyMac_GetFixed, &Rate))
+ return NULL;
+ _err = PrerollMovie(_self->ob_itself,
+ time,
+ Rate);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_AbortPrePrerollMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr err;
+ PyObject *_res = NULL;
+ OSErr err;
#ifndef AbortPrePrerollMovie
- PyMac_PRECHECK(AbortPrePrerollMovie);
+ PyMac_PRECHECK(AbortPrePrerollMovie);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &err))
- return NULL;
- AbortPrePrerollMovie(_self->ob_itself,
- err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &err))
+ return NULL;
+ AbortPrePrerollMovie(_self->ob_itself,
+ err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_LoadMovieIntoRam(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue time;
- TimeValue duration;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue time;
+ TimeValue duration;
+ long flags;
#ifndef LoadMovieIntoRam
- PyMac_PRECHECK(LoadMovieIntoRam);
-#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &time,
- &duration,
- &flags))
- return NULL;
- _err = LoadMovieIntoRam(_self->ob_itself,
- time,
- duration,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(LoadMovieIntoRam);
+#endif
+ if (!PyArg_ParseTuple(_args, "lll",
+ &time,
+ &duration,
+ &flags))
+ return NULL;
+ _err = LoadMovieIntoRam(_self->ob_itself,
+ time,
+ duration,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SetMovieActive(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean active;
+ PyObject *_res = NULL;
+ Boolean active;
#ifndef SetMovieActive
- PyMac_PRECHECK(SetMovieActive);
+ PyMac_PRECHECK(SetMovieActive);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &active))
- return NULL;
- SetMovieActive(_self->ob_itself,
- active);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &active))
+ return NULL;
+ SetMovieActive(_self->ob_itself,
+ active);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieActive(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef GetMovieActive
- PyMac_PRECHECK(GetMovieActive);
+ PyMac_PRECHECK(GetMovieActive);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieActive(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieActive(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_StartMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef StartMovie
- PyMac_PRECHECK(StartMovie);
+ PyMac_PRECHECK(StartMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- StartMovie(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ StartMovie(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_StopMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef StopMovie
- PyMac_PRECHECK(StopMovie);
+ PyMac_PRECHECK(StopMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- StopMovie(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ StopMovie(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GoToBeginningOfMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef GoToBeginningOfMovie
- PyMac_PRECHECK(GoToBeginningOfMovie);
+ PyMac_PRECHECK(GoToBeginningOfMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GoToBeginningOfMovie(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GoToBeginningOfMovie(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GoToEndOfMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef GoToEndOfMovie
- PyMac_PRECHECK(GoToEndOfMovie);
+ PyMac_PRECHECK(GoToEndOfMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GoToEndOfMovie(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GoToEndOfMovie(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_IsMovieDone(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsMovieDone
- PyMac_PRECHECK(IsMovieDone);
+ PyMac_PRECHECK(IsMovieDone);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsMovieDone(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsMovieDone(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_GetMoviePreviewMode(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef GetMoviePreviewMode
- PyMac_PRECHECK(GetMoviePreviewMode);
+ PyMac_PRECHECK(GetMoviePreviewMode);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMoviePreviewMode(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMoviePreviewMode(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_SetMoviePreviewMode(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean usePreview;
+ PyObject *_res = NULL;
+ Boolean usePreview;
#ifndef SetMoviePreviewMode
- PyMac_PRECHECK(SetMoviePreviewMode);
+ PyMac_PRECHECK(SetMoviePreviewMode);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &usePreview))
- return NULL;
- SetMoviePreviewMode(_self->ob_itself,
- usePreview);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &usePreview))
+ return NULL;
+ SetMoviePreviewMode(_self->ob_itself,
+ usePreview);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_ShowMoviePoster(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ShowMoviePoster
- PyMac_PRECHECK(ShowMoviePoster);
+ PyMac_PRECHECK(ShowMoviePoster);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ShowMoviePoster(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ShowMoviePoster(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieTimeBase(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeBase _rv;
+ PyObject *_res = NULL;
+ TimeBase _rv;
#ifndef GetMovieTimeBase
- PyMac_PRECHECK(GetMovieTimeBase);
+ PyMac_PRECHECK(GetMovieTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieTimeBase(_self->ob_itself);
- _res = Py_BuildValue("O&",
- TimeBaseObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieTimeBase(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ TimeBaseObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieMasterTimeBase(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeBase tb;
- TimeRecord slaveZero;
+ PyObject *_res = NULL;
+ TimeBase tb;
+ TimeRecord slaveZero;
#ifndef SetMovieMasterTimeBase
- PyMac_PRECHECK(SetMovieMasterTimeBase);
+ PyMac_PRECHECK(SetMovieMasterTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- TimeBaseObj_Convert, &tb,
- QtTimeRecord_Convert, &slaveZero))
- return NULL;
- SetMovieMasterTimeBase(_self->ob_itself,
- tb,
- &slaveZero);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ TimeBaseObj_Convert, &tb,
+ QtTimeRecord_Convert, &slaveZero))
+ return NULL;
+ SetMovieMasterTimeBase(_self->ob_itself,
+ tb,
+ &slaveZero);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SetMovieMasterClock(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component clockMeister;
- TimeRecord slaveZero;
+ PyObject *_res = NULL;
+ Component clockMeister;
+ TimeRecord slaveZero;
#ifndef SetMovieMasterClock
- PyMac_PRECHECK(SetMovieMasterClock);
+ PyMac_PRECHECK(SetMovieMasterClock);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpObj_Convert, &clockMeister,
- QtTimeRecord_Convert, &slaveZero))
- return NULL;
- SetMovieMasterClock(_self->ob_itself,
- clockMeister,
- &slaveZero);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpObj_Convert, &clockMeister,
+ QtTimeRecord_Convert, &slaveZero))
+ return NULL;
+ SetMovieMasterClock(_self->ob_itself,
+ clockMeister,
+ &slaveZero);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_ChooseMovieClock(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long flags;
+ PyObject *_res = NULL;
+ long flags;
#ifndef ChooseMovieClock
- PyMac_PRECHECK(ChooseMovieClock);
+ PyMac_PRECHECK(ChooseMovieClock);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &flags))
- return NULL;
- ChooseMovieClock(_self->ob_itself,
- flags);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &flags))
+ return NULL;
+ ChooseMovieClock(_self->ob_itself,
+ flags);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieGWorld(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr port;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ CGrafPtr port;
+ GDHandle gdh;
#ifndef GetMovieGWorld
- PyMac_PRECHECK(GetMovieGWorld);
+ PyMac_PRECHECK(GetMovieGWorld);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMovieGWorld(_self->ob_itself,
- &port,
- &gdh);
- _res = Py_BuildValue("O&O&",
- GrafObj_New, port,
- OptResObj_New, gdh);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMovieGWorld(_self->ob_itself,
+ &port,
+ &gdh);
+ _res = Py_BuildValue("O&O&",
+ GrafObj_New, port,
+ OptResObj_New, gdh);
+ return _res;
}
static PyObject *MovieObj_SetMovieGWorld(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr port;
- GDHandle gdh;
+ PyObject *_res = NULL;
+ CGrafPtr port;
+ GDHandle gdh;
#ifndef SetMovieGWorld
- PyMac_PRECHECK(SetMovieGWorld);
+ PyMac_PRECHECK(SetMovieGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- GrafObj_Convert, &port,
- OptResObj_Convert, &gdh))
- return NULL;
- SetMovieGWorld(_self->ob_itself,
- port,
- gdh);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ GrafObj_Convert, &port,
+ OptResObj_Convert, &gdh))
+ return NULL;
+ SetMovieGWorld(_self->ob_itself,
+ port,
+ gdh);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieNaturalBoundsRect(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect naturalBounds;
+ PyObject *_res = NULL;
+ Rect naturalBounds;
#ifndef GetMovieNaturalBoundsRect
- PyMac_PRECHECK(GetMovieNaturalBoundsRect);
+ PyMac_PRECHECK(GetMovieNaturalBoundsRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMovieNaturalBoundsRect(_self->ob_itself,
- &naturalBounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &naturalBounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMovieNaturalBoundsRect(_self->ob_itself,
+ &naturalBounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &naturalBounds);
+ return _res;
}
static PyObject *MovieObj_GetNextTrackForCompositing(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- Track theTrack;
+ PyObject *_res = NULL;
+ Track _rv;
+ Track theTrack;
#ifndef GetNextTrackForCompositing
- PyMac_PRECHECK(GetNextTrackForCompositing);
+ PyMac_PRECHECK(GetNextTrackForCompositing);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- TrackObj_Convert, &theTrack))
- return NULL;
- _rv = GetNextTrackForCompositing(_self->ob_itself,
- theTrack);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ TrackObj_Convert, &theTrack))
+ return NULL;
+ _rv = GetNextTrackForCompositing(_self->ob_itself,
+ theTrack);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetPrevTrackForCompositing(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- Track theTrack;
+ PyObject *_res = NULL;
+ Track _rv;
+ Track theTrack;
#ifndef GetPrevTrackForCompositing
- PyMac_PRECHECK(GetPrevTrackForCompositing);
+ PyMac_PRECHECK(GetPrevTrackForCompositing);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- TrackObj_Convert, &theTrack))
- return NULL;
- _rv = GetPrevTrackForCompositing(_self->ob_itself,
- theTrack);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ TrackObj_Convert, &theTrack))
+ return NULL;
+ _rv = GetPrevTrackForCompositing(_self->ob_itself,
+ theTrack);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMoviePict(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle _rv;
- TimeValue time;
+ PyObject *_res = NULL;
+ PicHandle _rv;
+ TimeValue time;
#ifndef GetMoviePict
- PyMac_PRECHECK(GetMoviePict);
+ PyMac_PRECHECK(GetMoviePict);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &time))
- return NULL;
- _rv = GetMoviePict(_self->ob_itself,
- time);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &time))
+ return NULL;
+ _rv = GetMoviePict(_self->ob_itself,
+ time);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMoviePosterPict(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle _rv;
+ PyObject *_res = NULL;
+ PicHandle _rv;
#ifndef GetMoviePosterPict
- PyMac_PRECHECK(GetMoviePosterPict);
+ PyMac_PRECHECK(GetMoviePosterPict);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMoviePosterPict(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMoviePosterPict(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_UpdateMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef UpdateMovie
- PyMac_PRECHECK(UpdateMovie);
+ PyMac_PRECHECK(UpdateMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = UpdateMovie(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = UpdateMovie(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_InvalidateMovieRegion(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle invalidRgn;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle invalidRgn;
#ifndef InvalidateMovieRegion
- PyMac_PRECHECK(InvalidateMovieRegion);
+ PyMac_PRECHECK(InvalidateMovieRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &invalidRgn))
- return NULL;
- _err = InvalidateMovieRegion(_self->ob_itself,
- invalidRgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &invalidRgn))
+ return NULL;
+ _err = InvalidateMovieRegion(_self->ob_itself,
+ invalidRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieBox(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect boxRect;
+ PyObject *_res = NULL;
+ Rect boxRect;
#ifndef GetMovieBox
- PyMac_PRECHECK(GetMovieBox);
+ PyMac_PRECHECK(GetMovieBox);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMovieBox(_self->ob_itself,
- &boxRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &boxRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMovieBox(_self->ob_itself,
+ &boxRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &boxRect);
+ return _res;
}
static PyObject *MovieObj_SetMovieBox(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect boxRect;
+ PyObject *_res = NULL;
+ Rect boxRect;
#ifndef SetMovieBox
- PyMac_PRECHECK(SetMovieBox);
+ PyMac_PRECHECK(SetMovieBox);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &boxRect))
- return NULL;
- SetMovieBox(_self->ob_itself,
- &boxRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &boxRect))
+ return NULL;
+ SetMovieBox(_self->ob_itself,
+ &boxRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieDisplayClipRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetMovieDisplayClipRgn
- PyMac_PRECHECK(GetMovieDisplayClipRgn);
+ PyMac_PRECHECK(GetMovieDisplayClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieDisplayClipRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieDisplayClipRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieDisplayClipRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle theClip;
+ PyObject *_res = NULL;
+ RgnHandle theClip;
#ifndef SetMovieDisplayClipRgn
- PyMac_PRECHECK(SetMovieDisplayClipRgn);
+ PyMac_PRECHECK(SetMovieDisplayClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theClip))
- return NULL;
- SetMovieDisplayClipRgn(_self->ob_itself,
- theClip);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theClip))
+ return NULL;
+ SetMovieDisplayClipRgn(_self->ob_itself,
+ theClip);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieClipRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetMovieClipRgn
- PyMac_PRECHECK(GetMovieClipRgn);
+ PyMac_PRECHECK(GetMovieClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieClipRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieClipRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieClipRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle theClip;
+ PyObject *_res = NULL;
+ RgnHandle theClip;
#ifndef SetMovieClipRgn
- PyMac_PRECHECK(SetMovieClipRgn);
+ PyMac_PRECHECK(SetMovieClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theClip))
- return NULL;
- SetMovieClipRgn(_self->ob_itself,
- theClip);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theClip))
+ return NULL;
+ SetMovieClipRgn(_self->ob_itself,
+ theClip);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieDisplayBoundsRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetMovieDisplayBoundsRgn
- PyMac_PRECHECK(GetMovieDisplayBoundsRgn);
+ PyMac_PRECHECK(GetMovieDisplayBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieDisplayBoundsRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieDisplayBoundsRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieBoundsRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetMovieBoundsRgn
- PyMac_PRECHECK(GetMovieBoundsRgn);
+ PyMac_PRECHECK(GetMovieBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieBoundsRgn(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieBoundsRgn(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieVideoOutput(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentInstance vout;
+ PyObject *_res = NULL;
+ ComponentInstance vout;
#ifndef SetMovieVideoOutput
- PyMac_PRECHECK(SetMovieVideoOutput);
+ PyMac_PRECHECK(SetMovieVideoOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &vout))
- return NULL;
- SetMovieVideoOutput(_self->ob_itself,
- vout);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &vout))
+ return NULL;
+ SetMovieVideoOutput(_self->ob_itself,
+ vout);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PutMovieIntoHandle(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle publicMovie;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle publicMovie;
#ifndef PutMovieIntoHandle
- PyMac_PRECHECK(PutMovieIntoHandle);
+ PyMac_PRECHECK(PutMovieIntoHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &publicMovie))
- return NULL;
- _err = PutMovieIntoHandle(_self->ob_itself,
- publicMovie);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &publicMovie))
+ return NULL;
+ _err = PutMovieIntoHandle(_self->ob_itself,
+ publicMovie);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PutMovieIntoDataFork(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short fRefNum;
- long offset;
- long maxSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short fRefNum;
+ long offset;
+ long maxSize;
#ifndef PutMovieIntoDataFork
- PyMac_PRECHECK(PutMovieIntoDataFork);
-#endif
- if (!PyArg_ParseTuple(_args, "hll",
- &fRefNum,
- &offset,
- &maxSize))
- return NULL;
- _err = PutMovieIntoDataFork(_self->ob_itself,
- fRefNum,
- offset,
- maxSize);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(PutMovieIntoDataFork);
+#endif
+ if (!PyArg_ParseTuple(_args, "hll",
+ &fRefNum,
+ &offset,
+ &maxSize))
+ return NULL;
+ _err = PutMovieIntoDataFork(_self->ob_itself,
+ fRefNum,
+ offset,
+ maxSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PutMovieIntoDataFork64(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long fRefNum;
- wide offset;
- unsigned long maxSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long fRefNum;
+ wide offset;
+ unsigned long maxSize;
#ifndef PutMovieIntoDataFork64
- PyMac_PRECHECK(PutMovieIntoDataFork64);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &fRefNum,
- PyMac_Getwide, &offset,
- &maxSize))
- return NULL;
- _err = PutMovieIntoDataFork64(_self->ob_itself,
- fRefNum,
- &offset,
- maxSize);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(PutMovieIntoDataFork64);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &fRefNum,
+ PyMac_Getwide, &offset,
+ &maxSize))
+ return NULL;
+ _err = PutMovieIntoDataFork64(_self->ob_itself,
+ fRefNum,
+ &offset,
+ maxSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PutMovieIntoStorage(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DataHandler dh;
- wide offset;
- unsigned long maxSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DataHandler dh;
+ wide offset;
+ unsigned long maxSize;
#ifndef PutMovieIntoStorage
- PyMac_PRECHECK(PutMovieIntoStorage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &dh,
- PyMac_Getwide, &offset,
- &maxSize))
- return NULL;
- _err = PutMovieIntoStorage(_self->ob_itself,
- dh,
- &offset,
- maxSize);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(PutMovieIntoStorage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &dh,
+ PyMac_Getwide, &offset,
+ &maxSize))
+ return NULL;
+ _err = PutMovieIntoStorage(_self->ob_itself,
+ dh,
+ &offset,
+ maxSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PutMovieForDataRefIntoHandle(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
- Handle publicMovie;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
+ Handle publicMovie;
#ifndef PutMovieForDataRefIntoHandle
- PyMac_PRECHECK(PutMovieForDataRefIntoHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- ResObj_Convert, &publicMovie))
- return NULL;
- _err = PutMovieForDataRefIntoHandle(_self->ob_itself,
- dataRef,
- dataRefType,
- publicMovie);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(PutMovieForDataRefIntoHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ ResObj_Convert, &publicMovie))
+ return NULL;
+ _err = PutMovieForDataRefIntoHandle(_self->ob_itself,
+ dataRef,
+ dataRefType,
+ publicMovie);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieCreationTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
+ PyObject *_res = NULL;
+ unsigned long _rv;
#ifndef GetMovieCreationTime
- PyMac_PRECHECK(GetMovieCreationTime);
+ PyMac_PRECHECK(GetMovieCreationTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieCreationTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieCreationTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieModificationTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
+ PyObject *_res = NULL;
+ unsigned long _rv;
#ifndef GetMovieModificationTime
- PyMac_PRECHECK(GetMovieModificationTime);
+ PyMac_PRECHECK(GetMovieModificationTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieModificationTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieModificationTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieTimeScale(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeScale _rv;
+ PyObject *_res = NULL;
+ TimeScale _rv;
#ifndef GetMovieTimeScale
- PyMac_PRECHECK(GetMovieTimeScale);
+ PyMac_PRECHECK(GetMovieTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieTimeScale(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieTimeScale(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieTimeScale(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeScale timeScale;
+ PyObject *_res = NULL;
+ TimeScale timeScale;
#ifndef SetMovieTimeScale
- PyMac_PRECHECK(SetMovieTimeScale);
+ PyMac_PRECHECK(SetMovieTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &timeScale))
- return NULL;
- SetMovieTimeScale(_self->ob_itself,
- timeScale);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &timeScale))
+ return NULL;
+ SetMovieTimeScale(_self->ob_itself,
+ timeScale);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieDuration(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
+ PyObject *_res = NULL;
+ TimeValue _rv;
#ifndef GetMovieDuration
- PyMac_PRECHECK(GetMovieDuration);
+ PyMac_PRECHECK(GetMovieDuration);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieDuration(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieDuration(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieRate(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
+ PyObject *_res = NULL;
+ Fixed _rv;
#ifndef GetMovieRate
- PyMac_PRECHECK(GetMovieRate);
+ PyMac_PRECHECK(GetMovieRate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieRate(_self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieRate(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieRate(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed rate;
+ PyObject *_res = NULL;
+ Fixed rate;
#ifndef SetMovieRate
- PyMac_PRECHECK(SetMovieRate);
+ PyMac_PRECHECK(SetMovieRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &rate))
- return NULL;
- SetMovieRate(_self->ob_itself,
- rate);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &rate))
+ return NULL;
+ SetMovieRate(_self->ob_itself,
+ rate);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMoviePreferredRate(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
+ PyObject *_res = NULL;
+ Fixed _rv;
#ifndef GetMoviePreferredRate
- PyMac_PRECHECK(GetMoviePreferredRate);
+ PyMac_PRECHECK(GetMoviePreferredRate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMoviePreferredRate(_self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMoviePreferredRate(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *MovieObj_SetMoviePreferredRate(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed rate;
+ PyObject *_res = NULL;
+ Fixed rate;
#ifndef SetMoviePreferredRate
- PyMac_PRECHECK(SetMoviePreferredRate);
+ PyMac_PRECHECK(SetMoviePreferredRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &rate))
- return NULL;
- SetMoviePreferredRate(_self->ob_itself,
- rate);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &rate))
+ return NULL;
+ SetMoviePreferredRate(_self->ob_itself,
+ rate);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMoviePreferredVolume(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetMoviePreferredVolume
- PyMac_PRECHECK(GetMoviePreferredVolume);
+ PyMac_PRECHECK(GetMoviePreferredVolume);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMoviePreferredVolume(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMoviePreferredVolume(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_SetMoviePreferredVolume(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short volume;
+ PyObject *_res = NULL;
+ short volume;
#ifndef SetMoviePreferredVolume
- PyMac_PRECHECK(SetMoviePreferredVolume);
+ PyMac_PRECHECK(SetMoviePreferredVolume);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &volume))
- return NULL;
- SetMoviePreferredVolume(_self->ob_itself,
- volume);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &volume))
+ return NULL;
+ SetMoviePreferredVolume(_self->ob_itself,
+ volume);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieVolume(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetMovieVolume
- PyMac_PRECHECK(GetMovieVolume);
+ PyMac_PRECHECK(GetMovieVolume);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieVolume(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieVolume(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieVolume(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short volume;
+ PyObject *_res = NULL;
+ short volume;
#ifndef SetMovieVolume
- PyMac_PRECHECK(SetMovieVolume);
+ PyMac_PRECHECK(SetMovieVolume);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &volume))
- return NULL;
- SetMovieVolume(_self->ob_itself,
- volume);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &volume))
+ return NULL;
+ SetMovieVolume(_self->ob_itself,
+ volume);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMoviePreviewTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue previewTime;
- TimeValue previewDuration;
+ PyObject *_res = NULL;
+ TimeValue previewTime;
+ TimeValue previewDuration;
#ifndef GetMoviePreviewTime
- PyMac_PRECHECK(GetMoviePreviewTime);
+ PyMac_PRECHECK(GetMoviePreviewTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMoviePreviewTime(_self->ob_itself,
- &previewTime,
- &previewDuration);
- _res = Py_BuildValue("ll",
- previewTime,
- previewDuration);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMoviePreviewTime(_self->ob_itself,
+ &previewTime,
+ &previewDuration);
+ _res = Py_BuildValue("ll",
+ previewTime,
+ previewDuration);
+ return _res;
}
static PyObject *MovieObj_SetMoviePreviewTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue previewTime;
- TimeValue previewDuration;
+ PyObject *_res = NULL;
+ TimeValue previewTime;
+ TimeValue previewDuration;
#ifndef SetMoviePreviewTime
- PyMac_PRECHECK(SetMoviePreviewTime);
+ PyMac_PRECHECK(SetMoviePreviewTime);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &previewTime,
- &previewDuration))
- return NULL;
- SetMoviePreviewTime(_self->ob_itself,
- previewTime,
- previewDuration);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &previewTime,
+ &previewDuration))
+ return NULL;
+ SetMoviePreviewTime(_self->ob_itself,
+ previewTime,
+ previewDuration);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMoviePosterTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
+ PyObject *_res = NULL;
+ TimeValue _rv;
#ifndef GetMoviePosterTime
- PyMac_PRECHECK(GetMoviePosterTime);
+ PyMac_PRECHECK(GetMoviePosterTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMoviePosterTime(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMoviePosterTime(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_SetMoviePosterTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue posterTime;
+ PyObject *_res = NULL;
+ TimeValue posterTime;
#ifndef SetMoviePosterTime
- PyMac_PRECHECK(SetMoviePosterTime);
+ PyMac_PRECHECK(SetMoviePosterTime);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &posterTime))
- return NULL;
- SetMoviePosterTime(_self->ob_itself,
- posterTime);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &posterTime))
+ return NULL;
+ SetMoviePosterTime(_self->ob_itself,
+ posterTime);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue selectionTime;
- TimeValue selectionDuration;
+ PyObject *_res = NULL;
+ TimeValue selectionTime;
+ TimeValue selectionDuration;
#ifndef GetMovieSelection
- PyMac_PRECHECK(GetMovieSelection);
+ PyMac_PRECHECK(GetMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMovieSelection(_self->ob_itself,
- &selectionTime,
- &selectionDuration);
- _res = Py_BuildValue("ll",
- selectionTime,
- selectionDuration);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMovieSelection(_self->ob_itself,
+ &selectionTime,
+ &selectionDuration);
+ _res = Py_BuildValue("ll",
+ selectionTime,
+ selectionDuration);
+ return _res;
}
static PyObject *MovieObj_SetMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue selectionTime;
- TimeValue selectionDuration;
+ PyObject *_res = NULL;
+ TimeValue selectionTime;
+ TimeValue selectionDuration;
#ifndef SetMovieSelection
- PyMac_PRECHECK(SetMovieSelection);
+ PyMac_PRECHECK(SetMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &selectionTime,
- &selectionDuration))
- return NULL;
- SetMovieSelection(_self->ob_itself,
- selectionTime,
- selectionDuration);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &selectionTime,
+ &selectionDuration))
+ return NULL;
+ SetMovieSelection(_self->ob_itself,
+ selectionTime,
+ selectionDuration);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SetMovieActiveSegment(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef SetMovieActiveSegment
- PyMac_PRECHECK(SetMovieActiveSegment);
+ PyMac_PRECHECK(SetMovieActiveSegment);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- SetMovieActiveSegment(_self->ob_itself,
- startTime,
- duration);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ SetMovieActiveSegment(_self->ob_itself,
+ startTime,
+ duration);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieActiveSegment(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef GetMovieActiveSegment
- PyMac_PRECHECK(GetMovieActiveSegment);
+ PyMac_PRECHECK(GetMovieActiveSegment);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetMovieActiveSegment(_self->ob_itself,
- &startTime,
- &duration);
- _res = Py_BuildValue("ll",
- startTime,
- duration);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetMovieActiveSegment(_self->ob_itself,
+ &startTime,
+ &duration);
+ _res = Py_BuildValue("ll",
+ startTime,
+ duration);
+ return _res;
}
static PyObject *MovieObj_GetMovieTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
- TimeRecord currentTime;
+ PyObject *_res = NULL;
+ TimeValue _rv;
+ TimeRecord currentTime;
#ifndef GetMovieTime
- PyMac_PRECHECK(GetMovieTime);
+ PyMac_PRECHECK(GetMovieTime);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieTime(_self->ob_itself,
- &currentTime);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &currentTime);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieTime(_self->ob_itself,
+ &currentTime);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &currentTime);
+ return _res;
}
static PyObject *MovieObj_SetMovieTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord newtime;
+ PyObject *_res = NULL;
+ TimeRecord newtime;
#ifndef SetMovieTime
- PyMac_PRECHECK(SetMovieTime);
+ PyMac_PRECHECK(SetMovieTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QtTimeRecord_Convert, &newtime))
- return NULL;
- SetMovieTime(_self->ob_itself,
- &newtime);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QtTimeRecord_Convert, &newtime))
+ return NULL;
+ SetMovieTime(_self->ob_itself,
+ &newtime);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SetMovieTimeValue(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue newtime;
+ PyObject *_res = NULL;
+ TimeValue newtime;
#ifndef SetMovieTimeValue
- PyMac_PRECHECK(SetMovieTimeValue);
+ PyMac_PRECHECK(SetMovieTimeValue);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newtime))
- return NULL;
- SetMovieTimeValue(_self->ob_itself,
- newtime);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newtime))
+ return NULL;
+ SetMovieTimeValue(_self->ob_itself,
+ newtime);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieUserData(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UserData _rv;
+ PyObject *_res = NULL;
+ UserData _rv;
#ifndef GetMovieUserData
- PyMac_PRECHECK(GetMovieUserData);
+ PyMac_PRECHECK(GetMovieUserData);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieUserData(_self->ob_itself);
- _res = Py_BuildValue("O&",
- UserDataObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieUserData(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ UserDataObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieTrackCount(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetMovieTrackCount
- PyMac_PRECHECK(GetMovieTrackCount);
+ PyMac_PRECHECK(GetMovieTrackCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieTrackCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieTrackCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieTrack(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- long trackID;
+ PyObject *_res = NULL;
+ Track _rv;
+ long trackID;
#ifndef GetMovieTrack
- PyMac_PRECHECK(GetMovieTrack);
+ PyMac_PRECHECK(GetMovieTrack);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &trackID))
- return NULL;
- _rv = GetMovieTrack(_self->ob_itself,
- trackID);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &trackID))
+ return NULL;
+ _rv = GetMovieTrack(_self->ob_itself,
+ trackID);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieIndTrack(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- long index;
+ PyObject *_res = NULL;
+ Track _rv;
+ long index;
#ifndef GetMovieIndTrack
- PyMac_PRECHECK(GetMovieIndTrack);
+ PyMac_PRECHECK(GetMovieIndTrack);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &index))
- return NULL;
- _rv = GetMovieIndTrack(_self->ob_itself,
- index);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &index))
+ return NULL;
+ _rv = GetMovieIndTrack(_self->ob_itself,
+ index);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieIndTrackType(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- long index;
- OSType trackType;
- long flags;
+ PyObject *_res = NULL;
+ Track _rv;
+ long index;
+ OSType trackType;
+ long flags;
#ifndef GetMovieIndTrackType
- PyMac_PRECHECK(GetMovieIndTrackType);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&l",
- &index,
- PyMac_GetOSType, &trackType,
- &flags))
- return NULL;
- _rv = GetMovieIndTrackType(_self->ob_itself,
- index,
- trackType,
- flags);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(GetMovieIndTrackType);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&l",
+ &index,
+ PyMac_GetOSType, &trackType,
+ &flags))
+ return NULL;
+ _rv = GetMovieIndTrackType(_self->ob_itself,
+ index,
+ trackType,
+ flags);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_NewMovieTrack(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Track _rv;
- Fixed width;
- Fixed height;
- short trackVolume;
+ PyObject *_res = NULL;
+ Track _rv;
+ Fixed width;
+ Fixed height;
+ short trackVolume;
#ifndef NewMovieTrack
- PyMac_PRECHECK(NewMovieTrack);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- PyMac_GetFixed, &width,
- PyMac_GetFixed, &height,
- &trackVolume))
- return NULL;
- _rv = NewMovieTrack(_self->ob_itself,
- width,
- height,
- trackVolume);
- _res = Py_BuildValue("O&",
- TrackObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(NewMovieTrack);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ PyMac_GetFixed, &width,
+ PyMac_GetFixed, &height,
+ &trackVolume))
+ return NULL;
+ _rv = NewMovieTrack(_self->ob_itself,
+ width,
+ height,
+ trackVolume);
+ _res = Py_BuildValue("O&",
+ TrackObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_SetAutoTrackAlternatesEnabled(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean enable;
+ PyObject *_res = NULL;
+ Boolean enable;
#ifndef SetAutoTrackAlternatesEnabled
- PyMac_PRECHECK(SetAutoTrackAlternatesEnabled);
+ PyMac_PRECHECK(SetAutoTrackAlternatesEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &enable))
- return NULL;
- SetAutoTrackAlternatesEnabled(_self->ob_itself,
- enable);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &enable))
+ return NULL;
+ SetAutoTrackAlternatesEnabled(_self->ob_itself,
+ enable);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SelectMovieAlternates(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef SelectMovieAlternates
- PyMac_PRECHECK(SelectMovieAlternates);
+ PyMac_PRECHECK(SelectMovieAlternates);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- SelectMovieAlternates(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ SelectMovieAlternates(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_InsertMovieSegment(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie dstMovie;
- TimeValue srcIn;
- TimeValue srcDuration;
- TimeValue dstIn;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie dstMovie;
+ TimeValue srcIn;
+ TimeValue srcDuration;
+ TimeValue dstIn;
#ifndef InsertMovieSegment
- PyMac_PRECHECK(InsertMovieSegment);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- MovieObj_Convert, &dstMovie,
- &srcIn,
- &srcDuration,
- &dstIn))
- return NULL;
- _err = InsertMovieSegment(_self->ob_itself,
- dstMovie,
- srcIn,
- srcDuration,
- dstIn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(InsertMovieSegment);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ MovieObj_Convert, &dstMovie,
+ &srcIn,
+ &srcDuration,
+ &dstIn))
+ return NULL;
+ _err = InsertMovieSegment(_self->ob_itself,
+ dstMovie,
+ srcIn,
+ srcDuration,
+ dstIn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_InsertEmptyMovieSegment(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue dstIn;
- TimeValue dstDuration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue dstIn;
+ TimeValue dstDuration;
#ifndef InsertEmptyMovieSegment
- PyMac_PRECHECK(InsertEmptyMovieSegment);
+ PyMac_PRECHECK(InsertEmptyMovieSegment);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &dstIn,
- &dstDuration))
- return NULL;
- _err = InsertEmptyMovieSegment(_self->ob_itself,
- dstIn,
- dstDuration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &dstIn,
+ &dstDuration))
+ return NULL;
+ _err = InsertEmptyMovieSegment(_self->ob_itself,
+ dstIn,
+ dstDuration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_DeleteMovieSegment(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef DeleteMovieSegment
- PyMac_PRECHECK(DeleteMovieSegment);
+ PyMac_PRECHECK(DeleteMovieSegment);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _err = DeleteMovieSegment(_self->ob_itself,
- startTime,
- duration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _err = DeleteMovieSegment(_self->ob_itself,
+ startTime,
+ duration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_ScaleMovieSegment(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue oldDuration;
- TimeValue newDuration;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue oldDuration;
+ TimeValue newDuration;
#ifndef ScaleMovieSegment
- PyMac_PRECHECK(ScaleMovieSegment);
-#endif
- if (!PyArg_ParseTuple(_args, "lll",
- &startTime,
- &oldDuration,
- &newDuration))
- return NULL;
- _err = ScaleMovieSegment(_self->ob_itself,
- startTime,
- oldDuration,
- newDuration);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ScaleMovieSegment);
+#endif
+ if (!PyArg_ParseTuple(_args, "lll",
+ &startTime,
+ &oldDuration,
+ &newDuration))
+ return NULL;
+ _err = ScaleMovieSegment(_self->ob_itself,
+ startTime,
+ oldDuration,
+ newDuration);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_CutMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
+ PyObject *_res = NULL;
+ Movie _rv;
#ifndef CutMovieSelection
- PyMac_PRECHECK(CutMovieSelection);
+ PyMac_PRECHECK(CutMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CutMovieSelection(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CutMovieSelection(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_CopyMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
+ PyObject *_res = NULL;
+ Movie _rv;
#ifndef CopyMovieSelection
- PyMac_PRECHECK(CopyMovieSelection);
+ PyMac_PRECHECK(CopyMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CopyMovieSelection(_self->ob_itself);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CopyMovieSelection(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_PasteMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie src;
+ PyObject *_res = NULL;
+ Movie src;
#ifndef PasteMovieSelection
- PyMac_PRECHECK(PasteMovieSelection);
+ PyMac_PRECHECK(PasteMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MovieObj_Convert, &src))
- return NULL;
- PasteMovieSelection(_self->ob_itself,
- src);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MovieObj_Convert, &src))
+ return NULL;
+ PasteMovieSelection(_self->ob_itself,
+ src);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_AddMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie src;
+ PyObject *_res = NULL;
+ Movie src;
#ifndef AddMovieSelection
- PyMac_PRECHECK(AddMovieSelection);
+ PyMac_PRECHECK(AddMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MovieObj_Convert, &src))
- return NULL;
- AddMovieSelection(_self->ob_itself,
- src);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MovieObj_Convert, &src))
+ return NULL;
+ AddMovieSelection(_self->ob_itself,
+ src);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_ClearMovieSelection(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClearMovieSelection
- PyMac_PRECHECK(ClearMovieSelection);
+ PyMac_PRECHECK(ClearMovieSelection);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClearMovieSelection(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClearMovieSelection(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_PutMovieIntoTypedHandle(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track targetTrack;
- OSType handleType;
- Handle publicMovie;
- TimeValue start;
- TimeValue dur;
- long flags;
- ComponentInstance userComp;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track targetTrack;
+ OSType handleType;
+ Handle publicMovie;
+ TimeValue start;
+ TimeValue dur;
+ long flags;
+ ComponentInstance userComp;
#ifndef PutMovieIntoTypedHandle
- PyMac_PRECHECK(PutMovieIntoTypedHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&lllO&",
- TrackObj_Convert, &targetTrack,
- PyMac_GetOSType, &handleType,
- ResObj_Convert, &publicMovie,
- &start,
- &dur,
- &flags,
- CmpInstObj_Convert, &userComp))
- return NULL;
- _err = PutMovieIntoTypedHandle(_self->ob_itself,
- targetTrack,
- handleType,
- publicMovie,
- start,
- dur,
- flags,
- userComp);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(PutMovieIntoTypedHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&lllO&",
+ TrackObj_Convert, &targetTrack,
+ PyMac_GetOSType, &handleType,
+ ResObj_Convert, &publicMovie,
+ &start,
+ &dur,
+ &flags,
+ CmpInstObj_Convert, &userComp))
+ return NULL;
+ _err = PutMovieIntoTypedHandle(_self->ob_itself,
+ targetTrack,
+ handleType,
+ publicMovie,
+ start,
+ dur,
+ flags,
+ userComp);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_CopyMovieSettings(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie dstMovie;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie dstMovie;
#ifndef CopyMovieSettings
- PyMac_PRECHECK(CopyMovieSettings);
+ PyMac_PRECHECK(CopyMovieSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MovieObj_Convert, &dstMovie))
- return NULL;
- _err = CopyMovieSettings(_self->ob_itself,
- dstMovie);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MovieObj_Convert, &dstMovie))
+ return NULL;
+ _err = CopyMovieSettings(_self->ob_itself,
+ dstMovie);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_ConvertMovieToFile(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Track onlyTrack;
- FSSpec outputFile;
- OSType fileType;
- OSType creator;
- ScriptCode scriptTag;
- short resID;
- long flags;
- ComponentInstance userComp;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Track onlyTrack;
+ FSSpec outputFile;
+ OSType fileType;
+ OSType creator;
+ ScriptCode scriptTag;
+ short resID;
+ long flags;
+ ComponentInstance userComp;
#ifndef ConvertMovieToFile
- PyMac_PRECHECK(ConvertMovieToFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&hlO&",
- TrackObj_Convert, &onlyTrack,
- PyMac_GetFSSpec, &outputFile,
- PyMac_GetOSType, &fileType,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &flags,
- CmpInstObj_Convert, &userComp))
- return NULL;
- _err = ConvertMovieToFile(_self->ob_itself,
- onlyTrack,
- &outputFile,
- fileType,
- creator,
- scriptTag,
- &resID,
- flags,
- userComp);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- resID);
- return _res;
+ PyMac_PRECHECK(ConvertMovieToFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&hlO&",
+ TrackObj_Convert, &onlyTrack,
+ PyMac_GetFSSpec, &outputFile,
+ PyMac_GetOSType, &fileType,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &flags,
+ CmpInstObj_Convert, &userComp))
+ return NULL;
+ _err = ConvertMovieToFile(_self->ob_itself,
+ onlyTrack,
+ &outputFile,
+ fileType,
+ creator,
+ scriptTag,
+ &resID,
+ flags,
+ userComp);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ resID);
+ return _res;
}
static PyObject *MovieObj_GetMovieDataSize(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ long _rv;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef GetMovieDataSize
- PyMac_PRECHECK(GetMovieDataSize);
+ PyMac_PRECHECK(GetMovieDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _rv = GetMovieDataSize(_self->ob_itself,
- startTime,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = GetMovieDataSize(_self->ob_itself,
+ startTime,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieDataSize64(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue startTime;
- TimeValue duration;
- wide dataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue startTime;
+ TimeValue duration;
+ wide dataSize;
#ifndef GetMovieDataSize64
- PyMac_PRECHECK(GetMovieDataSize64);
-#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &startTime,
- &duration))
- return NULL;
- _err = GetMovieDataSize64(_self->ob_itself,
- startTime,
- duration,
- &dataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, dataSize);
- return _res;
+ PyMac_PRECHECK(GetMovieDataSize64);
+#endif
+ if (!PyArg_ParseTuple(_args, "ll",
+ &startTime,
+ &duration))
+ return NULL;
+ _err = GetMovieDataSize64(_self->ob_itself,
+ startTime,
+ duration,
+ &dataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, dataSize);
+ return _res;
}
static PyObject *MovieObj_PtInMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point pt;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point pt;
#ifndef PtInMovie
- PyMac_PRECHECK(PtInMovie);
+ PyMac_PRECHECK(PtInMovie);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &pt))
- return NULL;
- _rv = PtInMovie(_self->ob_itself,
- pt);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &pt))
+ return NULL;
+ _rv = PtInMovie(_self->ob_itself,
+ pt);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_SetMovieLanguage(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long language;
+ PyObject *_res = NULL;
+ long language;
#ifndef SetMovieLanguage
- PyMac_PRECHECK(SetMovieLanguage);
+ PyMac_PRECHECK(SetMovieLanguage);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &language))
- return NULL;
- SetMovieLanguage(_self->ob_itself,
- language);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &language))
+ return NULL;
+ SetMovieLanguage(_self->ob_itself,
+ language);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_CopyMovieUserData(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie dstMovie;
- OSType copyRule;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie dstMovie;
+ OSType copyRule;
#ifndef CopyMovieUserData
- PyMac_PRECHECK(CopyMovieUserData);
+ PyMac_PRECHECK(CopyMovieUserData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- MovieObj_Convert, &dstMovie,
- PyMac_GetOSType, &copyRule))
- return NULL;
- _err = CopyMovieUserData(_self->ob_itself,
- dstMovie,
- copyRule);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ MovieObj_Convert, &dstMovie,
+ PyMac_GetOSType, &copyRule))
+ return NULL;
+ _err = CopyMovieUserData(_self->ob_itself,
+ dstMovie,
+ copyRule);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieNextInterestingTime(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short interestingTimeFlags;
- short numMediaTypes;
- OSType whichMediaTypes;
- TimeValue time;
- Fixed rate;
- TimeValue interestingTime;
- TimeValue interestingDuration;
+ PyObject *_res = NULL;
+ short interestingTimeFlags;
+ short numMediaTypes;
+ OSType whichMediaTypes;
+ TimeValue time;
+ Fixed rate;
+ TimeValue interestingTime;
+ TimeValue interestingDuration;
#ifndef GetMovieNextInterestingTime
- PyMac_PRECHECK(GetMovieNextInterestingTime);
-#endif
- if (!PyArg_ParseTuple(_args, "hhO&lO&",
- &interestingTimeFlags,
- &numMediaTypes,
- PyMac_GetOSType, &whichMediaTypes,
- &time,
- PyMac_GetFixed, &rate))
- return NULL;
- GetMovieNextInterestingTime(_self->ob_itself,
- interestingTimeFlags,
- numMediaTypes,
- &whichMediaTypes,
- time,
- rate,
- &interestingTime,
- &interestingDuration);
- _res = Py_BuildValue("ll",
- interestingTime,
- interestingDuration);
- return _res;
+ PyMac_PRECHECK(GetMovieNextInterestingTime);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhO&lO&",
+ &interestingTimeFlags,
+ &numMediaTypes,
+ PyMac_GetOSType, &whichMediaTypes,
+ &time,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ GetMovieNextInterestingTime(_self->ob_itself,
+ interestingTimeFlags,
+ numMediaTypes,
+ &whichMediaTypes,
+ time,
+ rate,
+ &interestingTime,
+ &interestingDuration);
+ _res = Py_BuildValue("ll",
+ interestingTime,
+ interestingDuration);
+ return _res;
}
static PyObject *MovieObj_AddMovieResource(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short resRefNum;
- short resId;
- Str255 resName;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short resRefNum;
+ short resId;
+ Str255 resName;
#ifndef AddMovieResource
- PyMac_PRECHECK(AddMovieResource);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &resRefNum,
- PyMac_GetStr255, resName))
- return NULL;
- _err = AddMovieResource(_self->ob_itself,
- resRefNum,
- &resId,
- resName);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- resId);
- return _res;
+ PyMac_PRECHECK(AddMovieResource);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &resRefNum,
+ PyMac_GetStr255, resName))
+ return NULL;
+ _err = AddMovieResource(_self->ob_itself,
+ resRefNum,
+ &resId,
+ resName);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ resId);
+ return _res;
}
static PyObject *MovieObj_UpdateMovieResource(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short resRefNum;
- short resId;
- Str255 resName;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short resRefNum;
+ short resId;
+ Str255 resName;
#ifndef UpdateMovieResource
- PyMac_PRECHECK(UpdateMovieResource);
-#endif
- if (!PyArg_ParseTuple(_args, "hhO&",
- &resRefNum,
- &resId,
- PyMac_GetStr255, resName))
- return NULL;
- _err = UpdateMovieResource(_self->ob_itself,
- resRefNum,
- resId,
- resName);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(UpdateMovieResource);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhO&",
+ &resRefNum,
+ &resId,
+ PyMac_GetStr255, resName))
+ return NULL;
+ _err = UpdateMovieResource(_self->ob_itself,
+ resRefNum,
+ resId,
+ resName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_AddMovieToStorage(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DataHandler dh;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DataHandler dh;
#ifndef AddMovieToStorage
- PyMac_PRECHECK(AddMovieToStorage);
+ PyMac_PRECHECK(AddMovieToStorage);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _err = AddMovieToStorage(_self->ob_itself,
- dh);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _err = AddMovieToStorage(_self->ob_itself,
+ dh);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_UpdateMovieInStorage(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DataHandler dh;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DataHandler dh;
#ifndef UpdateMovieInStorage
- PyMac_PRECHECK(UpdateMovieInStorage);
+ PyMac_PRECHECK(UpdateMovieInStorage);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _err = UpdateMovieInStorage(_self->ob_itself,
- dh);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _err = UpdateMovieInStorage(_self->ob_itself,
+ dh);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_HasMovieChanged(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef HasMovieChanged
- PyMac_PRECHECK(HasMovieChanged);
+ PyMac_PRECHECK(HasMovieChanged);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = HasMovieChanged(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = HasMovieChanged(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *MovieObj_ClearMovieChanged(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClearMovieChanged
- PyMac_PRECHECK(ClearMovieChanged);
+ PyMac_PRECHECK(ClearMovieChanged);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClearMovieChanged(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClearMovieChanged(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SetMovieDefaultDataRef(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef SetMovieDefaultDataRef
- PyMac_PRECHECK(SetMovieDefaultDataRef);
+ PyMac_PRECHECK(SetMovieDefaultDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = SetMovieDefaultDataRef(_self->ob_itself,
- dataRef,
- dataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = SetMovieDefaultDataRef(_self->ob_itself,
+ dataRef,
+ dataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieDefaultDataRef(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef GetMovieDefaultDataRef
- PyMac_PRECHECK(GetMovieDefaultDataRef);
+ PyMac_PRECHECK(GetMovieDefaultDataRef);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMovieDefaultDataRef(_self->ob_itself,
- &dataRef,
- &dataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMovieDefaultDataRef(_self->ob_itself,
+ &dataRef,
+ &dataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType);
+ return _res;
}
static PyObject *MovieObj_SetMovieColorTable(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- CTabHandle ctab;
+ PyObject *_res = NULL;
+ OSErr _err;
+ CTabHandle ctab;
#ifndef SetMovieColorTable
- PyMac_PRECHECK(SetMovieColorTable);
+ PyMac_PRECHECK(SetMovieColorTable);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &ctab))
- return NULL;
- _err = SetMovieColorTable(_self->ob_itself,
- ctab);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &ctab))
+ return NULL;
+ _err = SetMovieColorTable(_self->ob_itself,
+ ctab);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieColorTable(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- CTabHandle ctab;
+ PyObject *_res = NULL;
+ OSErr _err;
+ CTabHandle ctab;
#ifndef GetMovieColorTable
- PyMac_PRECHECK(GetMovieColorTable);
+ PyMac_PRECHECK(GetMovieColorTable);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMovieColorTable(_self->ob_itself,
- &ctab);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, ctab);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMovieColorTable(_self->ob_itself,
+ &ctab);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, ctab);
+ return _res;
}
static PyObject *MovieObj_FlattenMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long movieFlattenFlags;
- FSSpec theFile;
- OSType creator;
- ScriptCode scriptTag;
- long createMovieFileFlags;
- short resId;
- Str255 resName;
+ PyObject *_res = NULL;
+ long movieFlattenFlags;
+ FSSpec theFile;
+ OSType creator;
+ ScriptCode scriptTag;
+ long createMovieFileFlags;
+ short resId;
+ Str255 resName;
#ifndef FlattenMovie
- PyMac_PRECHECK(FlattenMovie);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&O&hlO&",
- &movieFlattenFlags,
- PyMac_GetFSSpec, &theFile,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &createMovieFileFlags,
- PyMac_GetStr255, resName))
- return NULL;
- FlattenMovie(_self->ob_itself,
- movieFlattenFlags,
- &theFile,
- creator,
- scriptTag,
- createMovieFileFlags,
- &resId,
- resName);
- _res = Py_BuildValue("h",
- resId);
- return _res;
+ PyMac_PRECHECK(FlattenMovie);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&O&hlO&",
+ &movieFlattenFlags,
+ PyMac_GetFSSpec, &theFile,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &createMovieFileFlags,
+ PyMac_GetStr255, resName))
+ return NULL;
+ FlattenMovie(_self->ob_itself,
+ movieFlattenFlags,
+ &theFile,
+ creator,
+ scriptTag,
+ createMovieFileFlags,
+ &resId,
+ resName);
+ _res = Py_BuildValue("h",
+ resId);
+ return _res;
}
static PyObject *MovieObj_FlattenMovieData(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
- long movieFlattenFlags;
- FSSpec theFile;
- OSType creator;
- ScriptCode scriptTag;
- long createMovieFileFlags;
+ PyObject *_res = NULL;
+ Movie _rv;
+ long movieFlattenFlags;
+ FSSpec theFile;
+ OSType creator;
+ ScriptCode scriptTag;
+ long createMovieFileFlags;
#ifndef FlattenMovieData
- PyMac_PRECHECK(FlattenMovieData);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&O&hl",
- &movieFlattenFlags,
- PyMac_GetFSSpec, &theFile,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &createMovieFileFlags))
- return NULL;
- _rv = FlattenMovieData(_self->ob_itself,
- movieFlattenFlags,
- &theFile,
- creator,
- scriptTag,
- createMovieFileFlags);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(FlattenMovieData);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&O&hl",
+ &movieFlattenFlags,
+ PyMac_GetFSSpec, &theFile,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &createMovieFileFlags))
+ return NULL;
+ _rv = FlattenMovieData(_self->ob_itself,
+ movieFlattenFlags,
+ &theFile,
+ creator,
+ scriptTag,
+ createMovieFileFlags);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_FlattenMovieDataToDataRef(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
- long movieFlattenFlags;
- Handle dataRef;
- OSType dataRefType;
- OSType creator;
- ScriptCode scriptTag;
- long createMovieFileFlags;
+ PyObject *_res = NULL;
+ Movie _rv;
+ long movieFlattenFlags;
+ Handle dataRef;
+ OSType dataRefType;
+ OSType creator;
+ ScriptCode scriptTag;
+ long createMovieFileFlags;
#ifndef FlattenMovieDataToDataRef
- PyMac_PRECHECK(FlattenMovieDataToDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&O&O&hl",
- &movieFlattenFlags,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &createMovieFileFlags))
- return NULL;
- _rv = FlattenMovieDataToDataRef(_self->ob_itself,
- movieFlattenFlags,
- dataRef,
- dataRefType,
- creator,
- scriptTag,
- createMovieFileFlags);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(FlattenMovieDataToDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&O&O&hl",
+ &movieFlattenFlags,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &createMovieFileFlags))
+ return NULL;
+ _rv = FlattenMovieDataToDataRef(_self->ob_itself,
+ movieFlattenFlags,
+ dataRef,
+ dataRefType,
+ creator,
+ scriptTag,
+ createMovieFileFlags);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_MovieSearchText(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Ptr text;
- long size;
- long searchFlags;
- Track searchTrack;
- TimeValue searchTime;
- long searchOffset;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Ptr text;
+ long size;
+ long searchFlags;
+ Track searchTrack;
+ TimeValue searchTime;
+ long searchOffset;
#ifndef MovieSearchText
- PyMac_PRECHECK(MovieSearchText);
-#endif
- if (!PyArg_ParseTuple(_args, "sll",
- &text,
- &size,
- &searchFlags))
- return NULL;
- _err = MovieSearchText(_self->ob_itself,
- text,
- size,
- searchFlags,
- &searchTrack,
- &searchTime,
- &searchOffset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&ll",
- TrackObj_New, searchTrack,
- searchTime,
- searchOffset);
- return _res;
+ PyMac_PRECHECK(MovieSearchText);
+#endif
+ if (!PyArg_ParseTuple(_args, "sll",
+ &text,
+ &size,
+ &searchFlags))
+ return NULL;
+ _err = MovieSearchText(_self->ob_itself,
+ text,
+ size,
+ searchFlags,
+ &searchTrack,
+ &searchTime,
+ &searchOffset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&ll",
+ TrackObj_New, searchTrack,
+ searchTime,
+ searchOffset);
+ return _res;
}
static PyObject *MovieObj_GetPosterBox(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect boxRect;
+ PyObject *_res = NULL;
+ Rect boxRect;
#ifndef GetPosterBox
- PyMac_PRECHECK(GetPosterBox);
+ PyMac_PRECHECK(GetPosterBox);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetPosterBox(_self->ob_itself,
- &boxRect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &boxRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetPosterBox(_self->ob_itself,
+ &boxRect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &boxRect);
+ return _res;
}
static PyObject *MovieObj_SetPosterBox(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect boxRect;
+ PyObject *_res = NULL;
+ Rect boxRect;
#ifndef SetPosterBox
- PyMac_PRECHECK(SetPosterBox);
+ PyMac_PRECHECK(SetPosterBox);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &boxRect))
- return NULL;
- SetPosterBox(_self->ob_itself,
- &boxRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &boxRect))
+ return NULL;
+ SetPosterBox(_self->ob_itself,
+ &boxRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMovieSegmentDisplayBoundsRgn(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
- TimeValue time;
- TimeValue duration;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
+ TimeValue time;
+ TimeValue duration;
#ifndef GetMovieSegmentDisplayBoundsRgn
- PyMac_PRECHECK(GetMovieSegmentDisplayBoundsRgn);
+ PyMac_PRECHECK(GetMovieSegmentDisplayBoundsRgn);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &time,
- &duration))
- return NULL;
- _rv = GetMovieSegmentDisplayBoundsRgn(_self->ob_itself,
- time,
- duration);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &time,
+ &duration))
+ return NULL;
+ _rv = GetMovieSegmentDisplayBoundsRgn(_self->ob_itself,
+ time,
+ duration);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_GetMovieStatus(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- Track firstProblemTrack;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ Track firstProblemTrack;
#ifndef GetMovieStatus
- PyMac_PRECHECK(GetMovieStatus);
+ PyMac_PRECHECK(GetMovieStatus);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMovieStatus(_self->ob_itself,
- &firstProblemTrack);
- _res = Py_BuildValue("lO&",
- _rv,
- TrackObj_New, firstProblemTrack);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMovieStatus(_self->ob_itself,
+ &firstProblemTrack);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ TrackObj_New, firstProblemTrack);
+ return _res;
}
static PyObject *MovieObj_NewMovieController(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- MovieController _rv;
- Rect movieRect;
- long someFlags;
+ PyObject *_res = NULL;
+ MovieController _rv;
+ Rect movieRect;
+ long someFlags;
#ifndef NewMovieController
- PyMac_PRECHECK(NewMovieController);
+ PyMac_PRECHECK(NewMovieController);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetRect, &movieRect,
- &someFlags))
- return NULL;
- _rv = NewMovieController(_self->ob_itself,
- &movieRect,
- someFlags);
- _res = Py_BuildValue("O&",
- MovieCtlObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetRect, &movieRect,
+ &someFlags))
+ return NULL;
+ _rv = NewMovieController(_self->ob_itself,
+ &movieRect,
+ someFlags);
+ _res = Py_BuildValue("O&",
+ MovieCtlObj_New, _rv);
+ return _res;
}
static PyObject *MovieObj_PutMovieOnScrap(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long movieScrapFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long movieScrapFlags;
#ifndef PutMovieOnScrap
- PyMac_PRECHECK(PutMovieOnScrap);
+ PyMac_PRECHECK(PutMovieOnScrap);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &movieScrapFlags))
- return NULL;
- _err = PutMovieOnScrap(_self->ob_itself,
- movieScrapFlags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &movieScrapFlags))
+ return NULL;
+ _err = PutMovieOnScrap(_self->ob_itself,
+ movieScrapFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_SetMoviePlayHints(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long flags;
- long flagsMask;
+ PyObject *_res = NULL;
+ long flags;
+ long flagsMask;
#ifndef SetMoviePlayHints
- PyMac_PRECHECK(SetMoviePlayHints);
+ PyMac_PRECHECK(SetMoviePlayHints);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &flags,
- &flagsMask))
- return NULL;
- SetMoviePlayHints(_self->ob_itself,
- flags,
- flagsMask);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &flags,
+ &flagsMask))
+ return NULL;
+ SetMoviePlayHints(_self->ob_itself,
+ flags,
+ flagsMask);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *MovieObj_GetMaxLoadedTimeInMovie(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeValue time;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeValue time;
#ifndef GetMaxLoadedTimeInMovie
- PyMac_PRECHECK(GetMaxLoadedTimeInMovie);
+ PyMac_PRECHECK(GetMaxLoadedTimeInMovie);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMaxLoadedTimeInMovie(_self->ob_itself,
- &time);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- time);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMaxLoadedTimeInMovie(_self->ob_itself,
+ &time);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ time);
+ return _res;
}
static PyObject *MovieObj_QTMovieNeedsTimeTable(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Boolean needsTimeTable;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Boolean needsTimeTable;
#ifndef QTMovieNeedsTimeTable
- PyMac_PRECHECK(QTMovieNeedsTimeTable);
+ PyMac_PRECHECK(QTMovieNeedsTimeTable);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = QTMovieNeedsTimeTable(_self->ob_itself,
- &needsTimeTable);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("b",
- needsTimeTable);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = QTMovieNeedsTimeTable(_self->ob_itself,
+ &needsTimeTable);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("b",
+ needsTimeTable);
+ return _res;
}
static PyObject *MovieObj_QTGetDataRefMaxFileOffset(MovieObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType dataRefType;
- Handle dataRef;
- long offset;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType dataRefType;
+ Handle dataRef;
+ long offset;
#ifndef QTGetDataRefMaxFileOffset
- PyMac_PRECHECK(QTGetDataRefMaxFileOffset);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &dataRefType,
- ResObj_Convert, &dataRef))
- return NULL;
- _err = QTGetDataRefMaxFileOffset(_self->ob_itself,
- dataRefType,
- dataRef,
- &offset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- offset);
- return _res;
+ PyMac_PRECHECK(QTGetDataRefMaxFileOffset);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &dataRefType,
+ ResObj_Convert, &dataRef))
+ return NULL;
+ _err = QTGetDataRefMaxFileOffset(_self->ob_itself,
+ dataRefType,
+ dataRef,
+ &offset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ offset);
+ return _res;
}
static PyMethodDef MovieObj_methods[] = {
- {"MoviesTask", (PyCFunction)MovieObj_MoviesTask, 1,
- PyDoc_STR("(long maxMilliSecToUse) -> None")},
- {"PrerollMovie", (PyCFunction)MovieObj_PrerollMovie, 1,
- PyDoc_STR("(TimeValue time, Fixed Rate) -> None")},
- {"AbortPrePrerollMovie", (PyCFunction)MovieObj_AbortPrePrerollMovie, 1,
- PyDoc_STR("(OSErr err) -> None")},
- {"LoadMovieIntoRam", (PyCFunction)MovieObj_LoadMovieIntoRam, 1,
- PyDoc_STR("(TimeValue time, TimeValue duration, long flags) -> None")},
- {"SetMovieActive", (PyCFunction)MovieObj_SetMovieActive, 1,
- PyDoc_STR("(Boolean active) -> None")},
- {"GetMovieActive", (PyCFunction)MovieObj_GetMovieActive, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"StartMovie", (PyCFunction)MovieObj_StartMovie, 1,
- PyDoc_STR("() -> None")},
- {"StopMovie", (PyCFunction)MovieObj_StopMovie, 1,
- PyDoc_STR("() -> None")},
- {"GoToBeginningOfMovie", (PyCFunction)MovieObj_GoToBeginningOfMovie, 1,
- PyDoc_STR("() -> None")},
- {"GoToEndOfMovie", (PyCFunction)MovieObj_GoToEndOfMovie, 1,
- PyDoc_STR("() -> None")},
- {"IsMovieDone", (PyCFunction)MovieObj_IsMovieDone, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetMoviePreviewMode", (PyCFunction)MovieObj_GetMoviePreviewMode, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SetMoviePreviewMode", (PyCFunction)MovieObj_SetMoviePreviewMode, 1,
- PyDoc_STR("(Boolean usePreview) -> None")},
- {"ShowMoviePoster", (PyCFunction)MovieObj_ShowMoviePoster, 1,
- PyDoc_STR("() -> None")},
- {"GetMovieTimeBase", (PyCFunction)MovieObj_GetMovieTimeBase, 1,
- PyDoc_STR("() -> (TimeBase _rv)")},
- {"SetMovieMasterTimeBase", (PyCFunction)MovieObj_SetMovieMasterTimeBase, 1,
- PyDoc_STR("(TimeBase tb, TimeRecord slaveZero) -> None")},
- {"SetMovieMasterClock", (PyCFunction)MovieObj_SetMovieMasterClock, 1,
- PyDoc_STR("(Component clockMeister, TimeRecord slaveZero) -> None")},
- {"ChooseMovieClock", (PyCFunction)MovieObj_ChooseMovieClock, 1,
- PyDoc_STR("(long flags) -> None")},
- {"GetMovieGWorld", (PyCFunction)MovieObj_GetMovieGWorld, 1,
- PyDoc_STR("() -> (CGrafPtr port, GDHandle gdh)")},
- {"SetMovieGWorld", (PyCFunction)MovieObj_SetMovieGWorld, 1,
- PyDoc_STR("(CGrafPtr port, GDHandle gdh) -> None")},
- {"GetMovieNaturalBoundsRect", (PyCFunction)MovieObj_GetMovieNaturalBoundsRect, 1,
- PyDoc_STR("() -> (Rect naturalBounds)")},
- {"GetNextTrackForCompositing", (PyCFunction)MovieObj_GetNextTrackForCompositing, 1,
- PyDoc_STR("(Track theTrack) -> (Track _rv)")},
- {"GetPrevTrackForCompositing", (PyCFunction)MovieObj_GetPrevTrackForCompositing, 1,
- PyDoc_STR("(Track theTrack) -> (Track _rv)")},
- {"GetMoviePict", (PyCFunction)MovieObj_GetMoviePict, 1,
- PyDoc_STR("(TimeValue time) -> (PicHandle _rv)")},
- {"GetMoviePosterPict", (PyCFunction)MovieObj_GetMoviePosterPict, 1,
- PyDoc_STR("() -> (PicHandle _rv)")},
- {"UpdateMovie", (PyCFunction)MovieObj_UpdateMovie, 1,
- PyDoc_STR("() -> None")},
- {"InvalidateMovieRegion", (PyCFunction)MovieObj_InvalidateMovieRegion, 1,
- PyDoc_STR("(RgnHandle invalidRgn) -> None")},
- {"GetMovieBox", (PyCFunction)MovieObj_GetMovieBox, 1,
- PyDoc_STR("() -> (Rect boxRect)")},
- {"SetMovieBox", (PyCFunction)MovieObj_SetMovieBox, 1,
- PyDoc_STR("(Rect boxRect) -> None")},
- {"GetMovieDisplayClipRgn", (PyCFunction)MovieObj_GetMovieDisplayClipRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"SetMovieDisplayClipRgn", (PyCFunction)MovieObj_SetMovieDisplayClipRgn, 1,
- PyDoc_STR("(RgnHandle theClip) -> None")},
- {"GetMovieClipRgn", (PyCFunction)MovieObj_GetMovieClipRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"SetMovieClipRgn", (PyCFunction)MovieObj_SetMovieClipRgn, 1,
- PyDoc_STR("(RgnHandle theClip) -> None")},
- {"GetMovieDisplayBoundsRgn", (PyCFunction)MovieObj_GetMovieDisplayBoundsRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"GetMovieBoundsRgn", (PyCFunction)MovieObj_GetMovieBoundsRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"SetMovieVideoOutput", (PyCFunction)MovieObj_SetMovieVideoOutput, 1,
- PyDoc_STR("(ComponentInstance vout) -> None")},
- {"PutMovieIntoHandle", (PyCFunction)MovieObj_PutMovieIntoHandle, 1,
- PyDoc_STR("(Handle publicMovie) -> None")},
- {"PutMovieIntoDataFork", (PyCFunction)MovieObj_PutMovieIntoDataFork, 1,
- PyDoc_STR("(short fRefNum, long offset, long maxSize) -> None")},
- {"PutMovieIntoDataFork64", (PyCFunction)MovieObj_PutMovieIntoDataFork64, 1,
- PyDoc_STR("(long fRefNum, wide offset, unsigned long maxSize) -> None")},
- {"PutMovieIntoStorage", (PyCFunction)MovieObj_PutMovieIntoStorage, 1,
- PyDoc_STR("(DataHandler dh, wide offset, unsigned long maxSize) -> None")},
- {"PutMovieForDataRefIntoHandle", (PyCFunction)MovieObj_PutMovieForDataRefIntoHandle, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType, Handle publicMovie) -> None")},
- {"GetMovieCreationTime", (PyCFunction)MovieObj_GetMovieCreationTime, 1,
- PyDoc_STR("() -> (unsigned long _rv)")},
- {"GetMovieModificationTime", (PyCFunction)MovieObj_GetMovieModificationTime, 1,
- PyDoc_STR("() -> (unsigned long _rv)")},
- {"GetMovieTimeScale", (PyCFunction)MovieObj_GetMovieTimeScale, 1,
- PyDoc_STR("() -> (TimeScale _rv)")},
- {"SetMovieTimeScale", (PyCFunction)MovieObj_SetMovieTimeScale, 1,
- PyDoc_STR("(TimeScale timeScale) -> None")},
- {"GetMovieDuration", (PyCFunction)MovieObj_GetMovieDuration, 1,
- PyDoc_STR("() -> (TimeValue _rv)")},
- {"GetMovieRate", (PyCFunction)MovieObj_GetMovieRate, 1,
- PyDoc_STR("() -> (Fixed _rv)")},
- {"SetMovieRate", (PyCFunction)MovieObj_SetMovieRate, 1,
- PyDoc_STR("(Fixed rate) -> None")},
- {"GetMoviePreferredRate", (PyCFunction)MovieObj_GetMoviePreferredRate, 1,
- PyDoc_STR("() -> (Fixed _rv)")},
- {"SetMoviePreferredRate", (PyCFunction)MovieObj_SetMoviePreferredRate, 1,
- PyDoc_STR("(Fixed rate) -> None")},
- {"GetMoviePreferredVolume", (PyCFunction)MovieObj_GetMoviePreferredVolume, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetMoviePreferredVolume", (PyCFunction)MovieObj_SetMoviePreferredVolume, 1,
- PyDoc_STR("(short volume) -> None")},
- {"GetMovieVolume", (PyCFunction)MovieObj_GetMovieVolume, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"SetMovieVolume", (PyCFunction)MovieObj_SetMovieVolume, 1,
- PyDoc_STR("(short volume) -> None")},
- {"GetMoviePreviewTime", (PyCFunction)MovieObj_GetMoviePreviewTime, 1,
- PyDoc_STR("() -> (TimeValue previewTime, TimeValue previewDuration)")},
- {"SetMoviePreviewTime", (PyCFunction)MovieObj_SetMoviePreviewTime, 1,
- PyDoc_STR("(TimeValue previewTime, TimeValue previewDuration) -> None")},
- {"GetMoviePosterTime", (PyCFunction)MovieObj_GetMoviePosterTime, 1,
- PyDoc_STR("() -> (TimeValue _rv)")},
- {"SetMoviePosterTime", (PyCFunction)MovieObj_SetMoviePosterTime, 1,
- PyDoc_STR("(TimeValue posterTime) -> None")},
- {"GetMovieSelection", (PyCFunction)MovieObj_GetMovieSelection, 1,
- PyDoc_STR("() -> (TimeValue selectionTime, TimeValue selectionDuration)")},
- {"SetMovieSelection", (PyCFunction)MovieObj_SetMovieSelection, 1,
- PyDoc_STR("(TimeValue selectionTime, TimeValue selectionDuration) -> None")},
- {"SetMovieActiveSegment", (PyCFunction)MovieObj_SetMovieActiveSegment, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> None")},
- {"GetMovieActiveSegment", (PyCFunction)MovieObj_GetMovieActiveSegment, 1,
- PyDoc_STR("() -> (TimeValue startTime, TimeValue duration)")},
- {"GetMovieTime", (PyCFunction)MovieObj_GetMovieTime, 1,
- PyDoc_STR("() -> (TimeValue _rv, TimeRecord currentTime)")},
- {"SetMovieTime", (PyCFunction)MovieObj_SetMovieTime, 1,
- PyDoc_STR("(TimeRecord newtime) -> None")},
- {"SetMovieTimeValue", (PyCFunction)MovieObj_SetMovieTimeValue, 1,
- PyDoc_STR("(TimeValue newtime) -> None")},
- {"GetMovieUserData", (PyCFunction)MovieObj_GetMovieUserData, 1,
- PyDoc_STR("() -> (UserData _rv)")},
- {"GetMovieTrackCount", (PyCFunction)MovieObj_GetMovieTrackCount, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetMovieTrack", (PyCFunction)MovieObj_GetMovieTrack, 1,
- PyDoc_STR("(long trackID) -> (Track _rv)")},
- {"GetMovieIndTrack", (PyCFunction)MovieObj_GetMovieIndTrack, 1,
- PyDoc_STR("(long index) -> (Track _rv)")},
- {"GetMovieIndTrackType", (PyCFunction)MovieObj_GetMovieIndTrackType, 1,
- PyDoc_STR("(long index, OSType trackType, long flags) -> (Track _rv)")},
- {"NewMovieTrack", (PyCFunction)MovieObj_NewMovieTrack, 1,
- PyDoc_STR("(Fixed width, Fixed height, short trackVolume) -> (Track _rv)")},
- {"SetAutoTrackAlternatesEnabled", (PyCFunction)MovieObj_SetAutoTrackAlternatesEnabled, 1,
- PyDoc_STR("(Boolean enable) -> None")},
- {"SelectMovieAlternates", (PyCFunction)MovieObj_SelectMovieAlternates, 1,
- PyDoc_STR("() -> None")},
- {"InsertMovieSegment", (PyCFunction)MovieObj_InsertMovieSegment, 1,
- PyDoc_STR("(Movie dstMovie, TimeValue srcIn, TimeValue srcDuration, TimeValue dstIn) -> None")},
- {"InsertEmptyMovieSegment", (PyCFunction)MovieObj_InsertEmptyMovieSegment, 1,
- PyDoc_STR("(TimeValue dstIn, TimeValue dstDuration) -> None")},
- {"DeleteMovieSegment", (PyCFunction)MovieObj_DeleteMovieSegment, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> None")},
- {"ScaleMovieSegment", (PyCFunction)MovieObj_ScaleMovieSegment, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue oldDuration, TimeValue newDuration) -> None")},
- {"CutMovieSelection", (PyCFunction)MovieObj_CutMovieSelection, 1,
- PyDoc_STR("() -> (Movie _rv)")},
- {"CopyMovieSelection", (PyCFunction)MovieObj_CopyMovieSelection, 1,
- PyDoc_STR("() -> (Movie _rv)")},
- {"PasteMovieSelection", (PyCFunction)MovieObj_PasteMovieSelection, 1,
- PyDoc_STR("(Movie src) -> None")},
- {"AddMovieSelection", (PyCFunction)MovieObj_AddMovieSelection, 1,
- PyDoc_STR("(Movie src) -> None")},
- {"ClearMovieSelection", (PyCFunction)MovieObj_ClearMovieSelection, 1,
- PyDoc_STR("() -> None")},
- {"PutMovieIntoTypedHandle", (PyCFunction)MovieObj_PutMovieIntoTypedHandle, 1,
- PyDoc_STR("(Track targetTrack, OSType handleType, Handle publicMovie, TimeValue start, TimeValue dur, long flags, ComponentInstance userComp) -> None")},
- {"CopyMovieSettings", (PyCFunction)MovieObj_CopyMovieSettings, 1,
- PyDoc_STR("(Movie dstMovie) -> None")},
- {"ConvertMovieToFile", (PyCFunction)MovieObj_ConvertMovieToFile, 1,
- PyDoc_STR("(Track onlyTrack, FSSpec outputFile, OSType fileType, OSType creator, ScriptCode scriptTag, long flags, ComponentInstance userComp) -> (short resID)")},
- {"GetMovieDataSize", (PyCFunction)MovieObj_GetMovieDataSize, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (long _rv)")},
- {"GetMovieDataSize64", (PyCFunction)MovieObj_GetMovieDataSize64, 1,
- PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (wide dataSize)")},
- {"PtInMovie", (PyCFunction)MovieObj_PtInMovie, 1,
- PyDoc_STR("(Point pt) -> (Boolean _rv)")},
- {"SetMovieLanguage", (PyCFunction)MovieObj_SetMovieLanguage, 1,
- PyDoc_STR("(long language) -> None")},
- {"CopyMovieUserData", (PyCFunction)MovieObj_CopyMovieUserData, 1,
- PyDoc_STR("(Movie dstMovie, OSType copyRule) -> None")},
- {"GetMovieNextInterestingTime", (PyCFunction)MovieObj_GetMovieNextInterestingTime, 1,
- PyDoc_STR("(short interestingTimeFlags, short numMediaTypes, OSType whichMediaTypes, TimeValue time, Fixed rate) -> (TimeValue interestingTime, TimeValue interestingDuration)")},
- {"AddMovieResource", (PyCFunction)MovieObj_AddMovieResource, 1,
- PyDoc_STR("(short resRefNum, Str255 resName) -> (short resId)")},
- {"UpdateMovieResource", (PyCFunction)MovieObj_UpdateMovieResource, 1,
- PyDoc_STR("(short resRefNum, short resId, Str255 resName) -> None")},
- {"AddMovieToStorage", (PyCFunction)MovieObj_AddMovieToStorage, 1,
- PyDoc_STR("(DataHandler dh) -> None")},
- {"UpdateMovieInStorage", (PyCFunction)MovieObj_UpdateMovieInStorage, 1,
- PyDoc_STR("(DataHandler dh) -> None")},
- {"HasMovieChanged", (PyCFunction)MovieObj_HasMovieChanged, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"ClearMovieChanged", (PyCFunction)MovieObj_ClearMovieChanged, 1,
- PyDoc_STR("() -> None")},
- {"SetMovieDefaultDataRef", (PyCFunction)MovieObj_SetMovieDefaultDataRef, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType) -> None")},
- {"GetMovieDefaultDataRef", (PyCFunction)MovieObj_GetMovieDefaultDataRef, 1,
- PyDoc_STR("() -> (Handle dataRef, OSType dataRefType)")},
- {"SetMovieColorTable", (PyCFunction)MovieObj_SetMovieColorTable, 1,
- PyDoc_STR("(CTabHandle ctab) -> None")},
- {"GetMovieColorTable", (PyCFunction)MovieObj_GetMovieColorTable, 1,
- PyDoc_STR("() -> (CTabHandle ctab)")},
- {"FlattenMovie", (PyCFunction)MovieObj_FlattenMovie, 1,
- PyDoc_STR("(long movieFlattenFlags, FSSpec theFile, OSType creator, ScriptCode scriptTag, long createMovieFileFlags, Str255 resName) -> (short resId)")},
- {"FlattenMovieData", (PyCFunction)MovieObj_FlattenMovieData, 1,
- PyDoc_STR("(long movieFlattenFlags, FSSpec theFile, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (Movie _rv)")},
- {"FlattenMovieDataToDataRef", (PyCFunction)MovieObj_FlattenMovieDataToDataRef, 1,
- PyDoc_STR("(long movieFlattenFlags, Handle dataRef, OSType dataRefType, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (Movie _rv)")},
- {"MovieSearchText", (PyCFunction)MovieObj_MovieSearchText, 1,
- PyDoc_STR("(Ptr text, long size, long searchFlags) -> (Track searchTrack, TimeValue searchTime, long searchOffset)")},
- {"GetPosterBox", (PyCFunction)MovieObj_GetPosterBox, 1,
- PyDoc_STR("() -> (Rect boxRect)")},
- {"SetPosterBox", (PyCFunction)MovieObj_SetPosterBox, 1,
- PyDoc_STR("(Rect boxRect) -> None")},
- {"GetMovieSegmentDisplayBoundsRgn", (PyCFunction)MovieObj_GetMovieSegmentDisplayBoundsRgn, 1,
- PyDoc_STR("(TimeValue time, TimeValue duration) -> (RgnHandle _rv)")},
- {"GetMovieStatus", (PyCFunction)MovieObj_GetMovieStatus, 1,
- PyDoc_STR("() -> (ComponentResult _rv, Track firstProblemTrack)")},
- {"NewMovieController", (PyCFunction)MovieObj_NewMovieController, 1,
- PyDoc_STR("(Rect movieRect, long someFlags) -> (MovieController _rv)")},
- {"PutMovieOnScrap", (PyCFunction)MovieObj_PutMovieOnScrap, 1,
- PyDoc_STR("(long movieScrapFlags) -> None")},
- {"SetMoviePlayHints", (PyCFunction)MovieObj_SetMoviePlayHints, 1,
- PyDoc_STR("(long flags, long flagsMask) -> None")},
- {"GetMaxLoadedTimeInMovie", (PyCFunction)MovieObj_GetMaxLoadedTimeInMovie, 1,
- PyDoc_STR("() -> (TimeValue time)")},
- {"QTMovieNeedsTimeTable", (PyCFunction)MovieObj_QTMovieNeedsTimeTable, 1,
- PyDoc_STR("() -> (Boolean needsTimeTable)")},
- {"QTGetDataRefMaxFileOffset", (PyCFunction)MovieObj_QTGetDataRefMaxFileOffset, 1,
- PyDoc_STR("(OSType dataRefType, Handle dataRef) -> (long offset)")},
- {NULL, NULL, 0}
+ {"MoviesTask", (PyCFunction)MovieObj_MoviesTask, 1,
+ PyDoc_STR("(long maxMilliSecToUse) -> None")},
+ {"PrerollMovie", (PyCFunction)MovieObj_PrerollMovie, 1,
+ PyDoc_STR("(TimeValue time, Fixed Rate) -> None")},
+ {"AbortPrePrerollMovie", (PyCFunction)MovieObj_AbortPrePrerollMovie, 1,
+ PyDoc_STR("(OSErr err) -> None")},
+ {"LoadMovieIntoRam", (PyCFunction)MovieObj_LoadMovieIntoRam, 1,
+ PyDoc_STR("(TimeValue time, TimeValue duration, long flags) -> None")},
+ {"SetMovieActive", (PyCFunction)MovieObj_SetMovieActive, 1,
+ PyDoc_STR("(Boolean active) -> None")},
+ {"GetMovieActive", (PyCFunction)MovieObj_GetMovieActive, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"StartMovie", (PyCFunction)MovieObj_StartMovie, 1,
+ PyDoc_STR("() -> None")},
+ {"StopMovie", (PyCFunction)MovieObj_StopMovie, 1,
+ PyDoc_STR("() -> None")},
+ {"GoToBeginningOfMovie", (PyCFunction)MovieObj_GoToBeginningOfMovie, 1,
+ PyDoc_STR("() -> None")},
+ {"GoToEndOfMovie", (PyCFunction)MovieObj_GoToEndOfMovie, 1,
+ PyDoc_STR("() -> None")},
+ {"IsMovieDone", (PyCFunction)MovieObj_IsMovieDone, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetMoviePreviewMode", (PyCFunction)MovieObj_GetMoviePreviewMode, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SetMoviePreviewMode", (PyCFunction)MovieObj_SetMoviePreviewMode, 1,
+ PyDoc_STR("(Boolean usePreview) -> None")},
+ {"ShowMoviePoster", (PyCFunction)MovieObj_ShowMoviePoster, 1,
+ PyDoc_STR("() -> None")},
+ {"GetMovieTimeBase", (PyCFunction)MovieObj_GetMovieTimeBase, 1,
+ PyDoc_STR("() -> (TimeBase _rv)")},
+ {"SetMovieMasterTimeBase", (PyCFunction)MovieObj_SetMovieMasterTimeBase, 1,
+ PyDoc_STR("(TimeBase tb, TimeRecord slaveZero) -> None")},
+ {"SetMovieMasterClock", (PyCFunction)MovieObj_SetMovieMasterClock, 1,
+ PyDoc_STR("(Component clockMeister, TimeRecord slaveZero) -> None")},
+ {"ChooseMovieClock", (PyCFunction)MovieObj_ChooseMovieClock, 1,
+ PyDoc_STR("(long flags) -> None")},
+ {"GetMovieGWorld", (PyCFunction)MovieObj_GetMovieGWorld, 1,
+ PyDoc_STR("() -> (CGrafPtr port, GDHandle gdh)")},
+ {"SetMovieGWorld", (PyCFunction)MovieObj_SetMovieGWorld, 1,
+ PyDoc_STR("(CGrafPtr port, GDHandle gdh) -> None")},
+ {"GetMovieNaturalBoundsRect", (PyCFunction)MovieObj_GetMovieNaturalBoundsRect, 1,
+ PyDoc_STR("() -> (Rect naturalBounds)")},
+ {"GetNextTrackForCompositing", (PyCFunction)MovieObj_GetNextTrackForCompositing, 1,
+ PyDoc_STR("(Track theTrack) -> (Track _rv)")},
+ {"GetPrevTrackForCompositing", (PyCFunction)MovieObj_GetPrevTrackForCompositing, 1,
+ PyDoc_STR("(Track theTrack) -> (Track _rv)")},
+ {"GetMoviePict", (PyCFunction)MovieObj_GetMoviePict, 1,
+ PyDoc_STR("(TimeValue time) -> (PicHandle _rv)")},
+ {"GetMoviePosterPict", (PyCFunction)MovieObj_GetMoviePosterPict, 1,
+ PyDoc_STR("() -> (PicHandle _rv)")},
+ {"UpdateMovie", (PyCFunction)MovieObj_UpdateMovie, 1,
+ PyDoc_STR("() -> None")},
+ {"InvalidateMovieRegion", (PyCFunction)MovieObj_InvalidateMovieRegion, 1,
+ PyDoc_STR("(RgnHandle invalidRgn) -> None")},
+ {"GetMovieBox", (PyCFunction)MovieObj_GetMovieBox, 1,
+ PyDoc_STR("() -> (Rect boxRect)")},
+ {"SetMovieBox", (PyCFunction)MovieObj_SetMovieBox, 1,
+ PyDoc_STR("(Rect boxRect) -> None")},
+ {"GetMovieDisplayClipRgn", (PyCFunction)MovieObj_GetMovieDisplayClipRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"SetMovieDisplayClipRgn", (PyCFunction)MovieObj_SetMovieDisplayClipRgn, 1,
+ PyDoc_STR("(RgnHandle theClip) -> None")},
+ {"GetMovieClipRgn", (PyCFunction)MovieObj_GetMovieClipRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"SetMovieClipRgn", (PyCFunction)MovieObj_SetMovieClipRgn, 1,
+ PyDoc_STR("(RgnHandle theClip) -> None")},
+ {"GetMovieDisplayBoundsRgn", (PyCFunction)MovieObj_GetMovieDisplayBoundsRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"GetMovieBoundsRgn", (PyCFunction)MovieObj_GetMovieBoundsRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"SetMovieVideoOutput", (PyCFunction)MovieObj_SetMovieVideoOutput, 1,
+ PyDoc_STR("(ComponentInstance vout) -> None")},
+ {"PutMovieIntoHandle", (PyCFunction)MovieObj_PutMovieIntoHandle, 1,
+ PyDoc_STR("(Handle publicMovie) -> None")},
+ {"PutMovieIntoDataFork", (PyCFunction)MovieObj_PutMovieIntoDataFork, 1,
+ PyDoc_STR("(short fRefNum, long offset, long maxSize) -> None")},
+ {"PutMovieIntoDataFork64", (PyCFunction)MovieObj_PutMovieIntoDataFork64, 1,
+ PyDoc_STR("(long fRefNum, wide offset, unsigned long maxSize) -> None")},
+ {"PutMovieIntoStorage", (PyCFunction)MovieObj_PutMovieIntoStorage, 1,
+ PyDoc_STR("(DataHandler dh, wide offset, unsigned long maxSize) -> None")},
+ {"PutMovieForDataRefIntoHandle", (PyCFunction)MovieObj_PutMovieForDataRefIntoHandle, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType, Handle publicMovie) -> None")},
+ {"GetMovieCreationTime", (PyCFunction)MovieObj_GetMovieCreationTime, 1,
+ PyDoc_STR("() -> (unsigned long _rv)")},
+ {"GetMovieModificationTime", (PyCFunction)MovieObj_GetMovieModificationTime, 1,
+ PyDoc_STR("() -> (unsigned long _rv)")},
+ {"GetMovieTimeScale", (PyCFunction)MovieObj_GetMovieTimeScale, 1,
+ PyDoc_STR("() -> (TimeScale _rv)")},
+ {"SetMovieTimeScale", (PyCFunction)MovieObj_SetMovieTimeScale, 1,
+ PyDoc_STR("(TimeScale timeScale) -> None")},
+ {"GetMovieDuration", (PyCFunction)MovieObj_GetMovieDuration, 1,
+ PyDoc_STR("() -> (TimeValue _rv)")},
+ {"GetMovieRate", (PyCFunction)MovieObj_GetMovieRate, 1,
+ PyDoc_STR("() -> (Fixed _rv)")},
+ {"SetMovieRate", (PyCFunction)MovieObj_SetMovieRate, 1,
+ PyDoc_STR("(Fixed rate) -> None")},
+ {"GetMoviePreferredRate", (PyCFunction)MovieObj_GetMoviePreferredRate, 1,
+ PyDoc_STR("() -> (Fixed _rv)")},
+ {"SetMoviePreferredRate", (PyCFunction)MovieObj_SetMoviePreferredRate, 1,
+ PyDoc_STR("(Fixed rate) -> None")},
+ {"GetMoviePreferredVolume", (PyCFunction)MovieObj_GetMoviePreferredVolume, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetMoviePreferredVolume", (PyCFunction)MovieObj_SetMoviePreferredVolume, 1,
+ PyDoc_STR("(short volume) -> None")},
+ {"GetMovieVolume", (PyCFunction)MovieObj_GetMovieVolume, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"SetMovieVolume", (PyCFunction)MovieObj_SetMovieVolume, 1,
+ PyDoc_STR("(short volume) -> None")},
+ {"GetMoviePreviewTime", (PyCFunction)MovieObj_GetMoviePreviewTime, 1,
+ PyDoc_STR("() -> (TimeValue previewTime, TimeValue previewDuration)")},
+ {"SetMoviePreviewTime", (PyCFunction)MovieObj_SetMoviePreviewTime, 1,
+ PyDoc_STR("(TimeValue previewTime, TimeValue previewDuration) -> None")},
+ {"GetMoviePosterTime", (PyCFunction)MovieObj_GetMoviePosterTime, 1,
+ PyDoc_STR("() -> (TimeValue _rv)")},
+ {"SetMoviePosterTime", (PyCFunction)MovieObj_SetMoviePosterTime, 1,
+ PyDoc_STR("(TimeValue posterTime) -> None")},
+ {"GetMovieSelection", (PyCFunction)MovieObj_GetMovieSelection, 1,
+ PyDoc_STR("() -> (TimeValue selectionTime, TimeValue selectionDuration)")},
+ {"SetMovieSelection", (PyCFunction)MovieObj_SetMovieSelection, 1,
+ PyDoc_STR("(TimeValue selectionTime, TimeValue selectionDuration) -> None")},
+ {"SetMovieActiveSegment", (PyCFunction)MovieObj_SetMovieActiveSegment, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> None")},
+ {"GetMovieActiveSegment", (PyCFunction)MovieObj_GetMovieActiveSegment, 1,
+ PyDoc_STR("() -> (TimeValue startTime, TimeValue duration)")},
+ {"GetMovieTime", (PyCFunction)MovieObj_GetMovieTime, 1,
+ PyDoc_STR("() -> (TimeValue _rv, TimeRecord currentTime)")},
+ {"SetMovieTime", (PyCFunction)MovieObj_SetMovieTime, 1,
+ PyDoc_STR("(TimeRecord newtime) -> None")},
+ {"SetMovieTimeValue", (PyCFunction)MovieObj_SetMovieTimeValue, 1,
+ PyDoc_STR("(TimeValue newtime) -> None")},
+ {"GetMovieUserData", (PyCFunction)MovieObj_GetMovieUserData, 1,
+ PyDoc_STR("() -> (UserData _rv)")},
+ {"GetMovieTrackCount", (PyCFunction)MovieObj_GetMovieTrackCount, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetMovieTrack", (PyCFunction)MovieObj_GetMovieTrack, 1,
+ PyDoc_STR("(long trackID) -> (Track _rv)")},
+ {"GetMovieIndTrack", (PyCFunction)MovieObj_GetMovieIndTrack, 1,
+ PyDoc_STR("(long index) -> (Track _rv)")},
+ {"GetMovieIndTrackType", (PyCFunction)MovieObj_GetMovieIndTrackType, 1,
+ PyDoc_STR("(long index, OSType trackType, long flags) -> (Track _rv)")},
+ {"NewMovieTrack", (PyCFunction)MovieObj_NewMovieTrack, 1,
+ PyDoc_STR("(Fixed width, Fixed height, short trackVolume) -> (Track _rv)")},
+ {"SetAutoTrackAlternatesEnabled", (PyCFunction)MovieObj_SetAutoTrackAlternatesEnabled, 1,
+ PyDoc_STR("(Boolean enable) -> None")},
+ {"SelectMovieAlternates", (PyCFunction)MovieObj_SelectMovieAlternates, 1,
+ PyDoc_STR("() -> None")},
+ {"InsertMovieSegment", (PyCFunction)MovieObj_InsertMovieSegment, 1,
+ PyDoc_STR("(Movie dstMovie, TimeValue srcIn, TimeValue srcDuration, TimeValue dstIn) -> None")},
+ {"InsertEmptyMovieSegment", (PyCFunction)MovieObj_InsertEmptyMovieSegment, 1,
+ PyDoc_STR("(TimeValue dstIn, TimeValue dstDuration) -> None")},
+ {"DeleteMovieSegment", (PyCFunction)MovieObj_DeleteMovieSegment, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> None")},
+ {"ScaleMovieSegment", (PyCFunction)MovieObj_ScaleMovieSegment, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue oldDuration, TimeValue newDuration) -> None")},
+ {"CutMovieSelection", (PyCFunction)MovieObj_CutMovieSelection, 1,
+ PyDoc_STR("() -> (Movie _rv)")},
+ {"CopyMovieSelection", (PyCFunction)MovieObj_CopyMovieSelection, 1,
+ PyDoc_STR("() -> (Movie _rv)")},
+ {"PasteMovieSelection", (PyCFunction)MovieObj_PasteMovieSelection, 1,
+ PyDoc_STR("(Movie src) -> None")},
+ {"AddMovieSelection", (PyCFunction)MovieObj_AddMovieSelection, 1,
+ PyDoc_STR("(Movie src) -> None")},
+ {"ClearMovieSelection", (PyCFunction)MovieObj_ClearMovieSelection, 1,
+ PyDoc_STR("() -> None")},
+ {"PutMovieIntoTypedHandle", (PyCFunction)MovieObj_PutMovieIntoTypedHandle, 1,
+ PyDoc_STR("(Track targetTrack, OSType handleType, Handle publicMovie, TimeValue start, TimeValue dur, long flags, ComponentInstance userComp) -> None")},
+ {"CopyMovieSettings", (PyCFunction)MovieObj_CopyMovieSettings, 1,
+ PyDoc_STR("(Movie dstMovie) -> None")},
+ {"ConvertMovieToFile", (PyCFunction)MovieObj_ConvertMovieToFile, 1,
+ PyDoc_STR("(Track onlyTrack, FSSpec outputFile, OSType fileType, OSType creator, ScriptCode scriptTag, long flags, ComponentInstance userComp) -> (short resID)")},
+ {"GetMovieDataSize", (PyCFunction)MovieObj_GetMovieDataSize, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (long _rv)")},
+ {"GetMovieDataSize64", (PyCFunction)MovieObj_GetMovieDataSize64, 1,
+ PyDoc_STR("(TimeValue startTime, TimeValue duration) -> (wide dataSize)")},
+ {"PtInMovie", (PyCFunction)MovieObj_PtInMovie, 1,
+ PyDoc_STR("(Point pt) -> (Boolean _rv)")},
+ {"SetMovieLanguage", (PyCFunction)MovieObj_SetMovieLanguage, 1,
+ PyDoc_STR("(long language) -> None")},
+ {"CopyMovieUserData", (PyCFunction)MovieObj_CopyMovieUserData, 1,
+ PyDoc_STR("(Movie dstMovie, OSType copyRule) -> None")},
+ {"GetMovieNextInterestingTime", (PyCFunction)MovieObj_GetMovieNextInterestingTime, 1,
+ PyDoc_STR("(short interestingTimeFlags, short numMediaTypes, OSType whichMediaTypes, TimeValue time, Fixed rate) -> (TimeValue interestingTime, TimeValue interestingDuration)")},
+ {"AddMovieResource", (PyCFunction)MovieObj_AddMovieResource, 1,
+ PyDoc_STR("(short resRefNum, Str255 resName) -> (short resId)")},
+ {"UpdateMovieResource", (PyCFunction)MovieObj_UpdateMovieResource, 1,
+ PyDoc_STR("(short resRefNum, short resId, Str255 resName) -> None")},
+ {"AddMovieToStorage", (PyCFunction)MovieObj_AddMovieToStorage, 1,
+ PyDoc_STR("(DataHandler dh) -> None")},
+ {"UpdateMovieInStorage", (PyCFunction)MovieObj_UpdateMovieInStorage, 1,
+ PyDoc_STR("(DataHandler dh) -> None")},
+ {"HasMovieChanged", (PyCFunction)MovieObj_HasMovieChanged, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"ClearMovieChanged", (PyCFunction)MovieObj_ClearMovieChanged, 1,
+ PyDoc_STR("() -> None")},
+ {"SetMovieDefaultDataRef", (PyCFunction)MovieObj_SetMovieDefaultDataRef, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType) -> None")},
+ {"GetMovieDefaultDataRef", (PyCFunction)MovieObj_GetMovieDefaultDataRef, 1,
+ PyDoc_STR("() -> (Handle dataRef, OSType dataRefType)")},
+ {"SetMovieColorTable", (PyCFunction)MovieObj_SetMovieColorTable, 1,
+ PyDoc_STR("(CTabHandle ctab) -> None")},
+ {"GetMovieColorTable", (PyCFunction)MovieObj_GetMovieColorTable, 1,
+ PyDoc_STR("() -> (CTabHandle ctab)")},
+ {"FlattenMovie", (PyCFunction)MovieObj_FlattenMovie, 1,
+ PyDoc_STR("(long movieFlattenFlags, FSSpec theFile, OSType creator, ScriptCode scriptTag, long createMovieFileFlags, Str255 resName) -> (short resId)")},
+ {"FlattenMovieData", (PyCFunction)MovieObj_FlattenMovieData, 1,
+ PyDoc_STR("(long movieFlattenFlags, FSSpec theFile, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (Movie _rv)")},
+ {"FlattenMovieDataToDataRef", (PyCFunction)MovieObj_FlattenMovieDataToDataRef, 1,
+ PyDoc_STR("(long movieFlattenFlags, Handle dataRef, OSType dataRefType, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (Movie _rv)")},
+ {"MovieSearchText", (PyCFunction)MovieObj_MovieSearchText, 1,
+ PyDoc_STR("(Ptr text, long size, long searchFlags) -> (Track searchTrack, TimeValue searchTime, long searchOffset)")},
+ {"GetPosterBox", (PyCFunction)MovieObj_GetPosterBox, 1,
+ PyDoc_STR("() -> (Rect boxRect)")},
+ {"SetPosterBox", (PyCFunction)MovieObj_SetPosterBox, 1,
+ PyDoc_STR("(Rect boxRect) -> None")},
+ {"GetMovieSegmentDisplayBoundsRgn", (PyCFunction)MovieObj_GetMovieSegmentDisplayBoundsRgn, 1,
+ PyDoc_STR("(TimeValue time, TimeValue duration) -> (RgnHandle _rv)")},
+ {"GetMovieStatus", (PyCFunction)MovieObj_GetMovieStatus, 1,
+ PyDoc_STR("() -> (ComponentResult _rv, Track firstProblemTrack)")},
+ {"NewMovieController", (PyCFunction)MovieObj_NewMovieController, 1,
+ PyDoc_STR("(Rect movieRect, long someFlags) -> (MovieController _rv)")},
+ {"PutMovieOnScrap", (PyCFunction)MovieObj_PutMovieOnScrap, 1,
+ PyDoc_STR("(long movieScrapFlags) -> None")},
+ {"SetMoviePlayHints", (PyCFunction)MovieObj_SetMoviePlayHints, 1,
+ PyDoc_STR("(long flags, long flagsMask) -> None")},
+ {"GetMaxLoadedTimeInMovie", (PyCFunction)MovieObj_GetMaxLoadedTimeInMovie, 1,
+ PyDoc_STR("() -> (TimeValue time)")},
+ {"QTMovieNeedsTimeTable", (PyCFunction)MovieObj_QTMovieNeedsTimeTable, 1,
+ PyDoc_STR("() -> (Boolean needsTimeTable)")},
+ {"QTGetDataRefMaxFileOffset", (PyCFunction)MovieObj_QTGetDataRefMaxFileOffset, 1,
+ PyDoc_STR("(OSType dataRefType, Handle dataRef) -> (long offset)")},
+ {NULL, NULL, 0}
};
#define MovieObj_getsetlist NULL
@@ -7286,61 +7286,61 @@ static PyMethodDef MovieObj_methods[] = {
static PyObject *MovieObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- Movie itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ Movie itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MovieObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((MovieObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, MovieObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((MovieObject *)_self)->ob_itself = itself;
+ return _self;
}
#define MovieObj_tp_free PyObject_Del
PyTypeObject Movie_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.Movie", /*tp_name*/
- sizeof(MovieObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) MovieObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) MovieObj_compare, /*tp_compare*/
- (reprfunc) MovieObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) MovieObj_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*/
- MovieObj_methods, /* tp_methods */
- 0, /*tp_members*/
- MovieObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- MovieObj_tp_init, /* tp_init */
- MovieObj_tp_alloc, /* tp_alloc */
- MovieObj_tp_new, /* tp_new */
- MovieObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.Movie", /*tp_name*/
+ sizeof(MovieObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) MovieObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) MovieObj_compare, /*tp_compare*/
+ (reprfunc) MovieObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) MovieObj_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*/
+ MovieObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ MovieObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ MovieObj_tp_init, /* tp_init */
+ MovieObj_tp_alloc, /* tp_alloc */
+ MovieObj_tp_new, /* tp_new */
+ MovieObj_tp_free, /* tp_free */
};
/* --------------------- End object type Movie ---------------------- */
@@ -7353,47 +7353,47 @@ PyTypeObject SGOutput_Type;
#define SGOutputObj_Check(x) ((x)->ob_type == &SGOutput_Type || PyObject_TypeCheck((x), &SGOutput_Type))
typedef struct SGOutputObject {
- PyObject_HEAD
- SGOutput ob_itself;
+ PyObject_HEAD
+ SGOutput ob_itself;
} SGOutputObject;
PyObject *SGOutputObj_New(SGOutput itself)
{
- SGOutputObject *it;
- if (itself == NULL) {
- PyErr_SetString(Qt_Error,"Cannot create SGOutput from NULL pointer");
- return NULL;
- }
- it = PyObject_NEW(SGOutputObject, &SGOutput_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ SGOutputObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(Qt_Error,"Cannot create SGOutput from NULL pointer");
+ return NULL;
+ }
+ it = PyObject_NEW(SGOutputObject, &SGOutput_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int SGOutputObj_Convert(PyObject *v, SGOutput *p_itself)
{
- if (v == Py_None)
- {
- *p_itself = NULL;
- return 1;
- }
- if (!SGOutputObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "SGOutput required");
- return 0;
- }
- *p_itself = ((SGOutputObject *)v)->ob_itself;
- return 1;
+ if (v == Py_None)
+ {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (!SGOutputObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "SGOutput required");
+ return 0;
+ }
+ *p_itself = ((SGOutputObject *)v)->ob_itself;
+ return 1;
}
static void SGOutputObj_dealloc(SGOutputObject *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 PyMethodDef SGOutputObj_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
#define SGOutputObj_getsetlist NULL
@@ -7410,61 +7410,61 @@ static PyMethodDef SGOutputObj_methods[] = {
static PyObject *SGOutputObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- SGOutput itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ SGOutput itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, SGOutputObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((SGOutputObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, SGOutputObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((SGOutputObject *)_self)->ob_itself = itself;
+ return _self;
}
#define SGOutputObj_tp_free PyObject_Del
PyTypeObject SGOutput_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Qt.SGOutput", /*tp_name*/
- sizeof(SGOutputObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) SGOutputObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) SGOutputObj_compare, /*tp_compare*/
- (reprfunc) SGOutputObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) SGOutputObj_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*/
- SGOutputObj_methods, /* tp_methods */
- 0, /*tp_members*/
- SGOutputObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- SGOutputObj_tp_init, /* tp_init */
- SGOutputObj_tp_alloc, /* tp_alloc */
- SGOutputObj_tp_new, /* tp_new */
- SGOutputObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Qt.SGOutput", /*tp_name*/
+ sizeof(SGOutputObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) SGOutputObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) SGOutputObj_compare, /*tp_compare*/
+ (reprfunc) SGOutputObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) SGOutputObj_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*/
+ SGOutputObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ SGOutputObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ SGOutputObj_tp_init, /* tp_init */
+ SGOutputObj_tp_alloc, /* tp_alloc */
+ SGOutputObj_tp_new, /* tp_new */
+ SGOutputObj_tp_free, /* tp_free */
};
/* -------------------- End object type SGOutput -------------------- */
@@ -7472,20527 +7472,20527 @@ PyTypeObject SGOutput_Type = {
static PyObject *Qt_EnterMovies(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef EnterMovies
- PyMac_PRECHECK(EnterMovies);
+ PyMac_PRECHECK(EnterMovies);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = EnterMovies();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = EnterMovies();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_ExitMovies(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ExitMovies
- PyMac_PRECHECK(ExitMovies);
+ PyMac_PRECHECK(ExitMovies);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ExitMovies();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ExitMovies();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetMoviesError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef GetMoviesError
- PyMac_PRECHECK(GetMoviesError);
+ PyMac_PRECHECK(GetMoviesError);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMoviesError();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMoviesError();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_ClearMoviesStickyError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClearMoviesStickyError
- PyMac_PRECHECK(ClearMoviesStickyError);
+ PyMac_PRECHECK(ClearMoviesStickyError);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClearMoviesStickyError();
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClearMoviesStickyError();
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetMoviesStickyError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef GetMoviesStickyError
- PyMac_PRECHECK(GetMoviesStickyError);
+ PyMac_PRECHECK(GetMoviesStickyError);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetMoviesStickyError();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetMoviesStickyError();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTGetWallClockTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- TimeBase wallClockTimeBase;
+ PyObject *_res = NULL;
+ OSErr _err;
+ TimeBase wallClockTimeBase;
#ifndef QTGetWallClockTimeBase
- PyMac_PRECHECK(QTGetWallClockTimeBase);
+ PyMac_PRECHECK(QTGetWallClockTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = QTGetWallClockTimeBase(&wallClockTimeBase);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- TimeBaseObj_New, wallClockTimeBase);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = QTGetWallClockTimeBase(&wallClockTimeBase);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ TimeBaseObj_New, wallClockTimeBase);
+ return _res;
}
static PyObject *Qt_QTIdleManagerOpen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- IdleManager _rv;
+ PyObject *_res = NULL;
+ IdleManager _rv;
#ifndef QTIdleManagerOpen
- PyMac_PRECHECK(QTIdleManagerOpen);
+ PyMac_PRECHECK(QTIdleManagerOpen);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = QTIdleManagerOpen();
- _res = Py_BuildValue("O&",
- IdleManagerObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = QTIdleManagerOpen();
+ _res = Py_BuildValue("O&",
+ IdleManagerObj_New, _rv);
+ return _res;
}
static PyObject *Qt_CreateMovieControl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- WindowPtr theWindow;
- Rect localRect;
- Movie theMovie;
- UInt32 options;
- ControlHandle returnedControl;
+ PyObject *_res = NULL;
+ OSErr _err;
+ WindowPtr theWindow;
+ Rect localRect;
+ Movie theMovie;
+ UInt32 options;
+ ControlHandle returnedControl;
#ifndef CreateMovieControl
- PyMac_PRECHECK(CreateMovieControl);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- WinObj_Convert, &theWindow,
- MovieObj_Convert, &theMovie,
- &options))
- return NULL;
- _err = CreateMovieControl(theWindow,
- &localRect,
- theMovie,
- options,
- &returnedControl);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildRect, &localRect,
- CtlObj_New, returnedControl);
- return _res;
+ PyMac_PRECHECK(CreateMovieControl);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ WinObj_Convert, &theWindow,
+ MovieObj_Convert, &theMovie,
+ &options))
+ return NULL;
+ _err = CreateMovieControl(theWindow,
+ &localRect,
+ theMovie,
+ options,
+ &returnedControl);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildRect, &localRect,
+ CtlObj_New, returnedControl);
+ return _res;
}
static PyObject *Qt_DisposeMatte(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PixMapHandle theMatte;
+ PyObject *_res = NULL;
+ PixMapHandle theMatte;
#ifndef DisposeMatte
- PyMac_PRECHECK(DisposeMatte);
+ PyMac_PRECHECK(DisposeMatte);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theMatte))
- return NULL;
- DisposeMatte(theMatte);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theMatte))
+ return NULL;
+ DisposeMatte(theMatte);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_NewMovie(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
- long flags;
+ PyObject *_res = NULL;
+ Movie _rv;
+ long flags;
#ifndef NewMovie
- PyMac_PRECHECK(NewMovie);
+ PyMac_PRECHECK(NewMovie);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &flags))
- return NULL;
- _rv = NewMovie(flags);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &flags))
+ return NULL;
+ _rv = NewMovie(flags);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *Qt_QTGetTimeUntilNextTask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long duration;
- long scale;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long duration;
+ long scale;
#ifndef QTGetTimeUntilNextTask
- PyMac_PRECHECK(QTGetTimeUntilNextTask);
+ PyMac_PRECHECK(QTGetTimeUntilNextTask);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &scale))
- return NULL;
- _err = QTGetTimeUntilNextTask(&duration,
- scale);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- duration);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &scale))
+ return NULL;
+ _err = QTGetTimeUntilNextTask(&duration,
+ scale);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ duration);
+ return _res;
}
static PyObject *Qt_GetDataHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Component _rv;
- Handle dataRef;
- OSType dataHandlerSubType;
- long flags;
+ PyObject *_res = NULL;
+ Component _rv;
+ Handle dataRef;
+ OSType dataHandlerSubType;
+ long flags;
#ifndef GetDataHandler
- PyMac_PRECHECK(GetDataHandler);
+ PyMac_PRECHECK(GetDataHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataHandlerSubType,
- &flags))
- return NULL;
- _rv = GetDataHandler(dataRef,
- dataHandlerSubType,
- flags);
- _res = Py_BuildValue("O&",
- CmpObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataHandlerSubType,
+ &flags))
+ return NULL;
+ _rv = GetDataHandler(dataRef,
+ dataHandlerSubType,
+ flags);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, _rv);
+ return _res;
}
static PyObject *Qt_PasteHandleIntoMovie(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle h;
- OSType handleType;
- Movie theMovie;
- long flags;
- ComponentInstance userComp;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle h;
+ OSType handleType;
+ Movie theMovie;
+ long flags;
+ ComponentInstance userComp;
#ifndef PasteHandleIntoMovie
- PyMac_PRECHECK(PasteHandleIntoMovie);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&lO&",
- ResObj_Convert, &h,
- PyMac_GetOSType, &handleType,
- MovieObj_Convert, &theMovie,
- &flags,
- CmpInstObj_Convert, &userComp))
- return NULL;
- _err = PasteHandleIntoMovie(h,
- handleType,
- theMovie,
- flags,
- userComp);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(PasteHandleIntoMovie);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&lO&",
+ ResObj_Convert, &h,
+ PyMac_GetOSType, &handleType,
+ MovieObj_Convert, &theMovie,
+ &flags,
+ CmpInstObj_Convert, &userComp))
+ return NULL;
+ _err = PasteHandleIntoMovie(h,
+ handleType,
+ theMovie,
+ flags,
+ userComp);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetMovieImporterForDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType dataRefType;
- Handle dataRef;
- long flags;
- Component importer;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType dataRefType;
+ Handle dataRef;
+ long flags;
+ Component importer;
#ifndef GetMovieImporterForDataRef
- PyMac_PRECHECK(GetMovieImporterForDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- PyMac_GetOSType, &dataRefType,
- ResObj_Convert, &dataRef,
- &flags))
- return NULL;
- _err = GetMovieImporterForDataRef(dataRefType,
- dataRef,
- flags,
- &importer);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpObj_New, importer);
- return _res;
+ PyMac_PRECHECK(GetMovieImporterForDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ PyMac_GetOSType, &dataRefType,
+ ResObj_Convert, &dataRef,
+ &flags))
+ return NULL;
+ _err = GetMovieImporterForDataRef(dataRefType,
+ dataRef,
+ flags,
+ &importer);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpObj_New, importer);
+ return _res;
}
static PyObject *Qt_QTGetMIMETypeInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- char* mimeStringStart;
- short mimeStringLength;
- OSType infoSelector;
- void * infoDataPtr;
- long infoDataSize;
+ PyObject *_res = NULL;
+ OSErr _err;
+ char* mimeStringStart;
+ short mimeStringLength;
+ OSType infoSelector;
+ void * infoDataPtr;
+ long infoDataSize;
#ifndef QTGetMIMETypeInfo
- PyMac_PRECHECK(QTGetMIMETypeInfo);
-#endif
- if (!PyArg_ParseTuple(_args, "shO&s",
- &mimeStringStart,
- &mimeStringLength,
- PyMac_GetOSType, &infoSelector,
- &infoDataPtr))
- return NULL;
- _err = QTGetMIMETypeInfo(mimeStringStart,
- mimeStringLength,
- infoSelector,
- infoDataPtr,
- &infoDataSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- infoDataSize);
- return _res;
+ PyMac_PRECHECK(QTGetMIMETypeInfo);
+#endif
+ if (!PyArg_ParseTuple(_args, "shO&s",
+ &mimeStringStart,
+ &mimeStringLength,
+ PyMac_GetOSType, &infoSelector,
+ &infoDataPtr))
+ return NULL;
+ _err = QTGetMIMETypeInfo(mimeStringStart,
+ mimeStringLength,
+ infoSelector,
+ infoDataPtr,
+ &infoDataSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ infoDataSize);
+ return _res;
}
static PyObject *Qt_TrackTimeToMediaTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeValue _rv;
- TimeValue value;
- Track theTrack;
+ PyObject *_res = NULL;
+ TimeValue _rv;
+ TimeValue value;
+ Track theTrack;
#ifndef TrackTimeToMediaTime
- PyMac_PRECHECK(TrackTimeToMediaTime);
+ PyMac_PRECHECK(TrackTimeToMediaTime);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &value,
- TrackObj_Convert, &theTrack))
- return NULL;
- _rv = TrackTimeToMediaTime(value,
- theTrack);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &value,
+ TrackObj_Convert, &theTrack))
+ return NULL;
+ _rv = TrackTimeToMediaTime(value,
+ theTrack);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_NewUserData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- UserData theUserData;
+ PyObject *_res = NULL;
+ OSErr _err;
+ UserData theUserData;
#ifndef NewUserData
- PyMac_PRECHECK(NewUserData);
+ PyMac_PRECHECK(NewUserData);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = NewUserData(&theUserData);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- UserDataObj_New, theUserData);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = NewUserData(&theUserData);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ UserDataObj_New, theUserData);
+ return _res;
}
static PyObject *Qt_NewUserDataFromHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle h;
- UserData theUserData;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle h;
+ UserData theUserData;
#ifndef NewUserDataFromHandle
- PyMac_PRECHECK(NewUserDataFromHandle);
+ PyMac_PRECHECK(NewUserDataFromHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &h))
- return NULL;
- _err = NewUserDataFromHandle(h,
- &theUserData);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- UserDataObj_New, theUserData);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &h))
+ return NULL;
+ _err = NewUserDataFromHandle(h,
+ &theUserData);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ UserDataObj_New, theUserData);
+ return _res;
}
static PyObject *Qt_CreateMovieFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fileSpec;
- OSType creator;
- ScriptCode scriptTag;
- long createMovieFileFlags;
- short resRefNum;
- Movie newmovie;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fileSpec;
+ OSType creator;
+ ScriptCode scriptTag;
+ long createMovieFileFlags;
+ short resRefNum;
+ Movie newmovie;
#ifndef CreateMovieFile
- PyMac_PRECHECK(CreateMovieFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hl",
- PyMac_GetFSSpec, &fileSpec,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &createMovieFileFlags))
- return NULL;
- _err = CreateMovieFile(&fileSpec,
- creator,
- scriptTag,
- createMovieFileFlags,
- &resRefNum,
- &newmovie);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hO&",
- resRefNum,
- MovieObj_New, newmovie);
- return _res;
+ PyMac_PRECHECK(CreateMovieFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hl",
+ PyMac_GetFSSpec, &fileSpec,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &createMovieFileFlags))
+ return NULL;
+ _err = CreateMovieFile(&fileSpec,
+ creator,
+ scriptTag,
+ createMovieFileFlags,
+ &resRefNum,
+ &newmovie);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hO&",
+ resRefNum,
+ MovieObj_New, newmovie);
+ return _res;
}
static PyObject *Qt_OpenMovieFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fileSpec;
- short resRefNum;
- SInt8 permission;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fileSpec;
+ short resRefNum;
+ SInt8 permission;
#ifndef OpenMovieFile
- PyMac_PRECHECK(OpenMovieFile);
+ PyMac_PRECHECK(OpenMovieFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetFSSpec, &fileSpec,
- &permission))
- return NULL;
- _err = OpenMovieFile(&fileSpec,
- &resRefNum,
- permission);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- resRefNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetFSSpec, &fileSpec,
+ &permission))
+ return NULL;
+ _err = OpenMovieFile(&fileSpec,
+ &resRefNum,
+ permission);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ resRefNum);
+ return _res;
}
static PyObject *Qt_CloseMovieFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short resRefNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short resRefNum;
#ifndef CloseMovieFile
- PyMac_PRECHECK(CloseMovieFile);
+ PyMac_PRECHECK(CloseMovieFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &resRefNum))
- return NULL;
- _err = CloseMovieFile(resRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &resRefNum))
+ return NULL;
+ _err = CloseMovieFile(resRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_DeleteMovieFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fileSpec;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fileSpec;
#ifndef DeleteMovieFile
- PyMac_PRECHECK(DeleteMovieFile);
+ PyMac_PRECHECK(DeleteMovieFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSSpec, &fileSpec))
- return NULL;
- _err = DeleteMovieFile(&fileSpec);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSSpec, &fileSpec))
+ return NULL;
+ _err = DeleteMovieFile(&fileSpec);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_NewMovieFromFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie theMovie;
- short resRefNum;
- short resId;
- short newMovieFlags;
- Boolean dataRefWasChanged;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie theMovie;
+ short resRefNum;
+ short resId;
+ short newMovieFlags;
+ Boolean dataRefWasChanged;
#ifndef NewMovieFromFile
- PyMac_PRECHECK(NewMovieFromFile);
-#endif
- if (!PyArg_ParseTuple(_args, "hhh",
- &resRefNum,
- &resId,
- &newMovieFlags))
- return NULL;
- _err = NewMovieFromFile(&theMovie,
- resRefNum,
- &resId,
- (StringPtr)0,
- newMovieFlags,
- &dataRefWasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&hb",
- MovieObj_New, theMovie,
- resId,
- dataRefWasChanged);
- return _res;
+ PyMac_PRECHECK(NewMovieFromFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhh",
+ &resRefNum,
+ &resId,
+ &newMovieFlags))
+ return NULL;
+ _err = NewMovieFromFile(&theMovie,
+ resRefNum,
+ &resId,
+ (StringPtr)0,
+ newMovieFlags,
+ &dataRefWasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&hb",
+ MovieObj_New, theMovie,
+ resId,
+ dataRefWasChanged);
+ return _res;
}
static PyObject *Qt_NewMovieFromHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie theMovie;
- Handle h;
- short newMovieFlags;
- Boolean dataRefWasChanged;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie theMovie;
+ Handle h;
+ short newMovieFlags;
+ Boolean dataRefWasChanged;
#ifndef NewMovieFromHandle
- PyMac_PRECHECK(NewMovieFromHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- ResObj_Convert, &h,
- &newMovieFlags))
- return NULL;
- _err = NewMovieFromHandle(&theMovie,
- h,
- newMovieFlags,
- &dataRefWasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- MovieObj_New, theMovie,
- dataRefWasChanged);
- return _res;
+ PyMac_PRECHECK(NewMovieFromHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&h",
+ ResObj_Convert, &h,
+ &newMovieFlags))
+ return NULL;
+ _err = NewMovieFromHandle(&theMovie,
+ h,
+ newMovieFlags,
+ &dataRefWasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ MovieObj_New, theMovie,
+ dataRefWasChanged);
+ return _res;
}
static PyObject *Qt_NewMovieFromDataFork(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie theMovie;
- short fRefNum;
- long fileOffset;
- short newMovieFlags;
- Boolean dataRefWasChanged;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie theMovie;
+ short fRefNum;
+ long fileOffset;
+ short newMovieFlags;
+ Boolean dataRefWasChanged;
#ifndef NewMovieFromDataFork
- PyMac_PRECHECK(NewMovieFromDataFork);
-#endif
- if (!PyArg_ParseTuple(_args, "hlh",
- &fRefNum,
- &fileOffset,
- &newMovieFlags))
- return NULL;
- _err = NewMovieFromDataFork(&theMovie,
- fRefNum,
- fileOffset,
- newMovieFlags,
- &dataRefWasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- MovieObj_New, theMovie,
- dataRefWasChanged);
- return _res;
+ PyMac_PRECHECK(NewMovieFromDataFork);
+#endif
+ if (!PyArg_ParseTuple(_args, "hlh",
+ &fRefNum,
+ &fileOffset,
+ &newMovieFlags))
+ return NULL;
+ _err = NewMovieFromDataFork(&theMovie,
+ fRefNum,
+ fileOffset,
+ newMovieFlags,
+ &dataRefWasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ MovieObj_New, theMovie,
+ dataRefWasChanged);
+ return _res;
}
static PyObject *Qt_NewMovieFromDataFork64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie theMovie;
- long fRefNum;
- wide fileOffset;
- short newMovieFlags;
- Boolean dataRefWasChanged;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie theMovie;
+ long fRefNum;
+ wide fileOffset;
+ short newMovieFlags;
+ Boolean dataRefWasChanged;
#ifndef NewMovieFromDataFork64
- PyMac_PRECHECK(NewMovieFromDataFork64);
-#endif
- if (!PyArg_ParseTuple(_args, "lO&h",
- &fRefNum,
- PyMac_Getwide, &fileOffset,
- &newMovieFlags))
- return NULL;
- _err = NewMovieFromDataFork64(&theMovie,
- fRefNum,
- &fileOffset,
- newMovieFlags,
- &dataRefWasChanged);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- MovieObj_New, theMovie,
- dataRefWasChanged);
- return _res;
+ PyMac_PRECHECK(NewMovieFromDataFork64);
+#endif
+ if (!PyArg_ParseTuple(_args, "lO&h",
+ &fRefNum,
+ PyMac_Getwide, &fileOffset,
+ &newMovieFlags))
+ return NULL;
+ _err = NewMovieFromDataFork64(&theMovie,
+ fRefNum,
+ &fileOffset,
+ newMovieFlags,
+ &dataRefWasChanged);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ MovieObj_New, theMovie,
+ dataRefWasChanged);
+ return _res;
}
static PyObject *Qt_NewMovieFromDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie m;
- short flags;
- short id;
- Handle dataRef;
- OSType dtaRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie m;
+ short flags;
+ short id;
+ Handle dataRef;
+ OSType dtaRefType;
#ifndef NewMovieFromDataRef
- PyMac_PRECHECK(NewMovieFromDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&O&",
- &flags,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dtaRefType))
- return NULL;
- _err = NewMovieFromDataRef(&m,
- flags,
- &id,
- dataRef,
- dtaRefType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- MovieObj_New, m,
- id);
- return _res;
+ PyMac_PRECHECK(NewMovieFromDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&O&",
+ &flags,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dtaRefType))
+ return NULL;
+ _err = NewMovieFromDataRef(&m,
+ flags,
+ &id,
+ dataRef,
+ dtaRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ MovieObj_New, m,
+ id);
+ return _res;
}
static PyObject *Qt_NewMovieFromStorageOffset(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie theMovie;
- DataHandler dh;
- wide fileOffset;
- short newMovieFlags;
- Boolean dataRefWasCataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie theMovie;
+ DataHandler dh;
+ wide fileOffset;
+ short newMovieFlags;
+ Boolean dataRefWasCataRefType;
#ifndef NewMovieFromStorageOffset
- PyMac_PRECHECK(NewMovieFromStorageOffset);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &dh,
- PyMac_Getwide, &fileOffset,
- &newMovieFlags))
- return NULL;
- _err = NewMovieFromStorageOffset(&theMovie,
- dh,
- &fileOffset,
- newMovieFlags,
- &dataRefWasCataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- MovieObj_New, theMovie,
- dataRefWasCataRefType);
- return _res;
+ PyMac_PRECHECK(NewMovieFromStorageOffset);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &dh,
+ PyMac_Getwide, &fileOffset,
+ &newMovieFlags))
+ return NULL;
+ _err = NewMovieFromStorageOffset(&theMovie,
+ dh,
+ &fileOffset,
+ newMovieFlags,
+ &dataRefWasCataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ MovieObj_New, theMovie,
+ dataRefWasCataRefType);
+ return _res;
}
static PyObject *Qt_NewMovieForDataRefFromHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Movie theMovie;
- Handle h;
- short newMovieFlags;
- Boolean dataRefWasChanged;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Movie theMovie;
+ Handle h;
+ short newMovieFlags;
+ Boolean dataRefWasChanged;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef NewMovieForDataRefFromHandle
- PyMac_PRECHECK(NewMovieForDataRefFromHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hO&O&",
- ResObj_Convert, &h,
- &newMovieFlags,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = NewMovieForDataRefFromHandle(&theMovie,
- h,
- newMovieFlags,
- &dataRefWasChanged,
- dataRef,
- dataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&b",
- MovieObj_New, theMovie,
- dataRefWasChanged);
- return _res;
+ PyMac_PRECHECK(NewMovieForDataRefFromHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hO&O&",
+ ResObj_Convert, &h,
+ &newMovieFlags,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = NewMovieForDataRefFromHandle(&theMovie,
+ h,
+ newMovieFlags,
+ &dataRefWasChanged,
+ dataRef,
+ dataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&b",
+ MovieObj_New, theMovie,
+ dataRefWasChanged);
+ return _res;
}
static PyObject *Qt_RemoveMovieResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short resRefNum;
- short resId;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short resRefNum;
+ short resId;
#ifndef RemoveMovieResource
- PyMac_PRECHECK(RemoveMovieResource);
+ PyMac_PRECHECK(RemoveMovieResource);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &resRefNum,
- &resId))
- return NULL;
- _err = RemoveMovieResource(resRefNum,
- resId);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &resRefNum,
+ &resId))
+ return NULL;
+ _err = RemoveMovieResource(resRefNum,
+ resId);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_CreateMovieStorage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
- OSType creator;
- ScriptCode scriptTag;
- long createMovieFileFlags;
- DataHandler outDataHandler;
- Movie newmovie;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
+ OSType creator;
+ ScriptCode scriptTag;
+ long createMovieFileFlags;
+ DataHandler outDataHandler;
+ Movie newmovie;
#ifndef CreateMovieStorage
- PyMac_PRECHECK(CreateMovieStorage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&hl",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &createMovieFileFlags))
- return NULL;
- _err = CreateMovieStorage(dataRef,
- dataRefType,
- creator,
- scriptTag,
- createMovieFileFlags,
- &outDataHandler,
- &newmovie);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- CmpInstObj_New, outDataHandler,
- MovieObj_New, newmovie);
- return _res;
+ PyMac_PRECHECK(CreateMovieStorage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&hl",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &createMovieFileFlags))
+ return NULL;
+ _err = CreateMovieStorage(dataRef,
+ dataRefType,
+ creator,
+ scriptTag,
+ createMovieFileFlags,
+ &outDataHandler,
+ &newmovie);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ CmpInstObj_New, outDataHandler,
+ MovieObj_New, newmovie);
+ return _res;
}
static PyObject *Qt_OpenMovieStorage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
- long flags;
- DataHandler outDataHandler;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
+ long flags;
+ DataHandler outDataHandler;
#ifndef OpenMovieStorage
- PyMac_PRECHECK(OpenMovieStorage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- &flags))
- return NULL;
- _err = OpenMovieStorage(dataRef,
- dataRefType,
- flags,
- &outDataHandler);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, outDataHandler);
- return _res;
+ PyMac_PRECHECK(OpenMovieStorage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ &flags))
+ return NULL;
+ _err = OpenMovieStorage(dataRef,
+ dataRefType,
+ flags,
+ &outDataHandler);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, outDataHandler);
+ return _res;
}
static PyObject *Qt_CloseMovieStorage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- DataHandler dh;
+ PyObject *_res = NULL;
+ OSErr _err;
+ DataHandler dh;
#ifndef CloseMovieStorage
- PyMac_PRECHECK(CloseMovieStorage);
+ PyMac_PRECHECK(CloseMovieStorage);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _err = CloseMovieStorage(dh);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _err = CloseMovieStorage(dh);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_DeleteMovieStorage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef DeleteMovieStorage
- PyMac_PRECHECK(DeleteMovieStorage);
+ PyMac_PRECHECK(DeleteMovieStorage);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = DeleteMovieStorage(dataRef,
- dataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = DeleteMovieStorage(dataRef,
+ dataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_CreateShortcutMovieFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fileSpec;
- OSType creator;
- ScriptCode scriptTag;
- long createMovieFileFlags;
- Handle targetDataRef;
- OSType targetDataRefType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fileSpec;
+ OSType creator;
+ ScriptCode scriptTag;
+ long createMovieFileFlags;
+ Handle targetDataRef;
+ OSType targetDataRefType;
#ifndef CreateShortcutMovieFile
- PyMac_PRECHECK(CreateShortcutMovieFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hlO&O&",
- PyMac_GetFSSpec, &fileSpec,
- PyMac_GetOSType, &creator,
- &scriptTag,
- &createMovieFileFlags,
- ResObj_Convert, &targetDataRef,
- PyMac_GetOSType, &targetDataRefType))
- return NULL;
- _err = CreateShortcutMovieFile(&fileSpec,
- creator,
- scriptTag,
- createMovieFileFlags,
- targetDataRef,
- targetDataRefType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CreateShortcutMovieFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hlO&O&",
+ PyMac_GetFSSpec, &fileSpec,
+ PyMac_GetOSType, &creator,
+ &scriptTag,
+ &createMovieFileFlags,
+ ResObj_Convert, &targetDataRef,
+ PyMac_GetOSType, &targetDataRefType))
+ return NULL;
+ _err = CreateShortcutMovieFile(&fileSpec,
+ creator,
+ scriptTag,
+ createMovieFileFlags,
+ targetDataRef,
+ targetDataRefType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_CanQuickTimeOpenFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fileSpec;
- OSType fileType;
- OSType fileNameExtension;
- Boolean outCanOpenWithGraphicsImporter;
- Boolean outCanOpenAsMovie;
- Boolean outPreferGraphicsImporter;
- UInt32 inFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fileSpec;
+ OSType fileType;
+ OSType fileNameExtension;
+ Boolean outCanOpenWithGraphicsImporter;
+ Boolean outCanOpenAsMovie;
+ Boolean outPreferGraphicsImporter;
+ UInt32 inFlags;
#ifndef CanQuickTimeOpenFile
- PyMac_PRECHECK(CanQuickTimeOpenFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- PyMac_GetFSSpec, &fileSpec,
- PyMac_GetOSType, &fileType,
- PyMac_GetOSType, &fileNameExtension,
- &inFlags))
- return NULL;
- _err = CanQuickTimeOpenFile(&fileSpec,
- fileType,
- fileNameExtension,
- &outCanOpenWithGraphicsImporter,
- &outCanOpenAsMovie,
- &outPreferGraphicsImporter,
- inFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bbb",
- outCanOpenWithGraphicsImporter,
- outCanOpenAsMovie,
- outPreferGraphicsImporter);
- return _res;
+ PyMac_PRECHECK(CanQuickTimeOpenFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ PyMac_GetFSSpec, &fileSpec,
+ PyMac_GetOSType, &fileType,
+ PyMac_GetOSType, &fileNameExtension,
+ &inFlags))
+ return NULL;
+ _err = CanQuickTimeOpenFile(&fileSpec,
+ fileType,
+ fileNameExtension,
+ &outCanOpenWithGraphicsImporter,
+ &outCanOpenAsMovie,
+ &outPreferGraphicsImporter,
+ inFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bbb",
+ outCanOpenWithGraphicsImporter,
+ outCanOpenAsMovie,
+ outPreferGraphicsImporter);
+ return _res;
}
static PyObject *Qt_CanQuickTimeOpenDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
- Boolean outCanOpenWithGraphicsImporter;
- Boolean outCanOpenAsMovie;
- Boolean outPreferGraphicsImporter;
- UInt32 inFlags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
+ Boolean outCanOpenWithGraphicsImporter;
+ Boolean outCanOpenAsMovie;
+ Boolean outPreferGraphicsImporter;
+ UInt32 inFlags;
#ifndef CanQuickTimeOpenDataRef
- PyMac_PRECHECK(CanQuickTimeOpenDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- &inFlags))
- return NULL;
- _err = CanQuickTimeOpenDataRef(dataRef,
- dataRefType,
- &outCanOpenWithGraphicsImporter,
- &outCanOpenAsMovie,
- &outPreferGraphicsImporter,
- inFlags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("bbb",
- outCanOpenWithGraphicsImporter,
- outCanOpenAsMovie,
- outPreferGraphicsImporter);
- return _res;
+ PyMac_PRECHECK(CanQuickTimeOpenDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ &inFlags))
+ return NULL;
+ _err = CanQuickTimeOpenDataRef(dataRef,
+ dataRefType,
+ &outCanOpenWithGraphicsImporter,
+ &outCanOpenAsMovie,
+ &outPreferGraphicsImporter,
+ inFlags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("bbb",
+ outCanOpenWithGraphicsImporter,
+ outCanOpenAsMovie,
+ outPreferGraphicsImporter);
+ return _res;
}
static PyObject *Qt_NewMovieFromScrap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
- long newMovieFlags;
+ PyObject *_res = NULL;
+ Movie _rv;
+ long newMovieFlags;
#ifndef NewMovieFromScrap
- PyMac_PRECHECK(NewMovieFromScrap);
+ PyMac_PRECHECK(NewMovieFromScrap);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newMovieFlags))
- return NULL;
- _rv = NewMovieFromScrap(newMovieFlags);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newMovieFlags))
+ return NULL;
+ _rv = NewMovieFromScrap(newMovieFlags);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *Qt_QTNewAlias(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec fss;
- AliasHandle alias;
- Boolean minimal;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec fss;
+ AliasHandle alias;
+ Boolean minimal;
#ifndef QTNewAlias
- PyMac_PRECHECK(QTNewAlias);
+ PyMac_PRECHECK(QTNewAlias);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetFSSpec, &fss,
- &minimal))
- return NULL;
- _err = QTNewAlias(&fss,
- &alias,
- minimal);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, alias);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetFSSpec, &fss,
+ &minimal))
+ return NULL;
+ _err = QTNewAlias(&fss,
+ &alias,
+ minimal);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, alias);
+ return _res;
}
static PyObject *Qt_EndFullScreen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Ptr fullState;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Ptr fullState;
+ long flags;
#ifndef EndFullScreen
- PyMac_PRECHECK(EndFullScreen);
+ PyMac_PRECHECK(EndFullScreen);
#endif
- if (!PyArg_ParseTuple(_args, "sl",
- &fullState,
- &flags))
- return NULL;
- _err = EndFullScreen(fullState,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "sl",
+ &fullState,
+ &flags))
+ return NULL;
+ _err = EndFullScreen(fullState,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_AddSoundDescriptionExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SoundDescriptionHandle desc;
- Handle extension;
- OSType idType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SoundDescriptionHandle desc;
+ Handle extension;
+ OSType idType;
#ifndef AddSoundDescriptionExtension
- PyMac_PRECHECK(AddSoundDescriptionExtension);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- ResObj_Convert, &desc,
- ResObj_Convert, &extension,
- PyMac_GetOSType, &idType))
- return NULL;
- _err = AddSoundDescriptionExtension(desc,
- extension,
- idType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(AddSoundDescriptionExtension);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ ResObj_Convert, &desc,
+ ResObj_Convert, &extension,
+ PyMac_GetOSType, &idType))
+ return NULL;
+ _err = AddSoundDescriptionExtension(desc,
+ extension,
+ idType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetSoundDescriptionExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SoundDescriptionHandle desc;
- Handle extension;
- OSType idType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SoundDescriptionHandle desc;
+ Handle extension;
+ OSType idType;
#ifndef GetSoundDescriptionExtension
- PyMac_PRECHECK(GetSoundDescriptionExtension);
+ PyMac_PRECHECK(GetSoundDescriptionExtension);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &desc,
- PyMac_GetOSType, &idType))
- return NULL;
- _err = GetSoundDescriptionExtension(desc,
- &extension,
- idType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, extension);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &desc,
+ PyMac_GetOSType, &idType))
+ return NULL;
+ _err = GetSoundDescriptionExtension(desc,
+ &extension,
+ idType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, extension);
+ return _res;
}
static PyObject *Qt_RemoveSoundDescriptionExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SoundDescriptionHandle desc;
- OSType idType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SoundDescriptionHandle desc;
+ OSType idType;
#ifndef RemoveSoundDescriptionExtension
- PyMac_PRECHECK(RemoveSoundDescriptionExtension);
+ PyMac_PRECHECK(RemoveSoundDescriptionExtension);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &desc,
- PyMac_GetOSType, &idType))
- return NULL;
- _err = RemoveSoundDescriptionExtension(desc,
- idType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &desc,
+ PyMac_GetOSType, &idType))
+ return NULL;
+ _err = RemoveSoundDescriptionExtension(desc,
+ idType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTIsStandardParameterDialogEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- EventRecord pEvent;
- QTParameterDialog createdDialog;
+ PyObject *_res = NULL;
+ OSErr _err;
+ EventRecord pEvent;
+ QTParameterDialog createdDialog;
#ifndef QTIsStandardParameterDialogEvent
- PyMac_PRECHECK(QTIsStandardParameterDialogEvent);
+ PyMac_PRECHECK(QTIsStandardParameterDialogEvent);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &createdDialog))
- return NULL;
- _err = QTIsStandardParameterDialogEvent(&pEvent,
- createdDialog);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildEventRecord, &pEvent);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &createdDialog))
+ return NULL;
+ _err = QTIsStandardParameterDialogEvent(&pEvent,
+ createdDialog);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildEventRecord, &pEvent);
+ return _res;
}
static PyObject *Qt_QTDismissStandardParameterDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- QTParameterDialog createdDialog;
+ PyObject *_res = NULL;
+ OSErr _err;
+ QTParameterDialog createdDialog;
#ifndef QTDismissStandardParameterDialog
- PyMac_PRECHECK(QTDismissStandardParameterDialog);
+ PyMac_PRECHECK(QTDismissStandardParameterDialog);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &createdDialog))
- return NULL;
- _err = QTDismissStandardParameterDialog(createdDialog);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &createdDialog))
+ return NULL;
+ _err = QTDismissStandardParameterDialog(createdDialog);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTStandardParameterDialogDoAction(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- QTParameterDialog createdDialog;
- long action;
- void * params;
+ PyObject *_res = NULL;
+ OSErr _err;
+ QTParameterDialog createdDialog;
+ long action;
+ void * params;
#ifndef QTStandardParameterDialogDoAction
- PyMac_PRECHECK(QTStandardParameterDialogDoAction);
-#endif
- if (!PyArg_ParseTuple(_args, "lls",
- &createdDialog,
- &action,
- &params))
- return NULL;
- _err = QTStandardParameterDialogDoAction(createdDialog,
- action,
- params);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(QTStandardParameterDialogDoAction);
+#endif
+ if (!PyArg_ParseTuple(_args, "lls",
+ &createdDialog,
+ &action,
+ &params))
+ return NULL;
+ _err = QTStandardParameterDialogDoAction(createdDialog,
+ action,
+ params);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTRegisterAccessKey(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str255 accessKeyType;
- long flags;
- Handle accessKey;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str255 accessKeyType;
+ long flags;
+ Handle accessKey;
#ifndef QTRegisterAccessKey
- PyMac_PRECHECK(QTRegisterAccessKey);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- PyMac_GetStr255, accessKeyType,
- &flags,
- ResObj_Convert, &accessKey))
- return NULL;
- _err = QTRegisterAccessKey(accessKeyType,
- flags,
- accessKey);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(QTRegisterAccessKey);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ PyMac_GetStr255, accessKeyType,
+ &flags,
+ ResObj_Convert, &accessKey))
+ return NULL;
+ _err = QTRegisterAccessKey(accessKeyType,
+ flags,
+ accessKey);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTUnregisterAccessKey(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str255 accessKeyType;
- long flags;
- Handle accessKey;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str255 accessKeyType;
+ long flags;
+ Handle accessKey;
#ifndef QTUnregisterAccessKey
- PyMac_PRECHECK(QTUnregisterAccessKey);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- PyMac_GetStr255, accessKeyType,
- &flags,
- ResObj_Convert, &accessKey))
- return NULL;
- _err = QTUnregisterAccessKey(accessKeyType,
- flags,
- accessKey);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(QTUnregisterAccessKey);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ PyMac_GetStr255, accessKeyType,
+ &flags,
+ ResObj_Convert, &accessKey))
+ return NULL;
+ _err = QTUnregisterAccessKey(accessKeyType,
+ flags,
+ accessKey);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTGetSupportedRestrictions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType inRestrictionClass;
- UInt32 outRestrictionIDs;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType inRestrictionClass;
+ UInt32 outRestrictionIDs;
#ifndef QTGetSupportedRestrictions
- PyMac_PRECHECK(QTGetSupportedRestrictions);
+ PyMac_PRECHECK(QTGetSupportedRestrictions);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &inRestrictionClass))
- return NULL;
- _err = QTGetSupportedRestrictions(inRestrictionClass,
- &outRestrictionIDs);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outRestrictionIDs);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &inRestrictionClass))
+ return NULL;
+ _err = QTGetSupportedRestrictions(inRestrictionClass,
+ &outRestrictionIDs);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outRestrictionIDs);
+ return _res;
}
static PyObject *Qt_QTTextToNativeText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle theText;
- long encoding;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle theText;
+ long encoding;
+ long flags;
#ifndef QTTextToNativeText
- PyMac_PRECHECK(QTTextToNativeText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- ResObj_Convert, &theText,
- &encoding,
- &flags))
- return NULL;
- _err = QTTextToNativeText(theText,
- encoding,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(QTTextToNativeText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ ResObj_Convert, &theText,
+ &encoding,
+ &flags))
+ return NULL;
+ _err = QTTextToNativeText(theText,
+ encoding,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_VideoMediaResetStatistics(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef VideoMediaResetStatistics
- PyMac_PRECHECK(VideoMediaResetStatistics);
+ PyMac_PRECHECK(VideoMediaResetStatistics);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = VideoMediaResetStatistics(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = VideoMediaResetStatistics(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VideoMediaGetStatistics(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef VideoMediaGetStatistics
- PyMac_PRECHECK(VideoMediaGetStatistics);
+ PyMac_PRECHECK(VideoMediaGetStatistics);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = VideoMediaGetStatistics(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = VideoMediaGetStatistics(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VideoMediaGetStallCount(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- unsigned long stalls;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ unsigned long stalls;
#ifndef VideoMediaGetStallCount
- PyMac_PRECHECK(VideoMediaGetStallCount);
+ PyMac_PRECHECK(VideoMediaGetStallCount);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = VideoMediaGetStallCount(mh,
- &stalls);
- _res = Py_BuildValue("ll",
- _rv,
- stalls);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = VideoMediaGetStallCount(mh,
+ &stalls);
+ _res = Py_BuildValue("ll",
+ _rv,
+ stalls);
+ return _res;
}
static PyObject *Qt_VideoMediaSetCodecParameter(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- CodecType cType;
- OSType parameterID;
- long parameterChangeSeed;
- void * dataPtr;
- long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ CodecType cType;
+ OSType parameterID;
+ long parameterChangeSeed;
+ void * dataPtr;
+ long dataSize;
#ifndef VideoMediaSetCodecParameter
- PyMac_PRECHECK(VideoMediaSetCodecParameter);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&lsl",
- CmpInstObj_Convert, &mh,
- PyMac_GetOSType, &cType,
- PyMac_GetOSType, &parameterID,
- &parameterChangeSeed,
- &dataPtr,
- &dataSize))
- return NULL;
- _rv = VideoMediaSetCodecParameter(mh,
- cType,
- parameterID,
- parameterChangeSeed,
- dataPtr,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(VideoMediaSetCodecParameter);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&lsl",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetOSType, &cType,
+ PyMac_GetOSType, &parameterID,
+ &parameterChangeSeed,
+ &dataPtr,
+ &dataSize))
+ return NULL;
+ _rv = VideoMediaSetCodecParameter(mh,
+ cType,
+ parameterID,
+ parameterChangeSeed,
+ dataPtr,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VideoMediaGetCodecParameter(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- CodecType cType;
- OSType parameterID;
- Handle outParameterData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ CodecType cType;
+ OSType parameterID;
+ Handle outParameterData;
#ifndef VideoMediaGetCodecParameter
- PyMac_PRECHECK(VideoMediaGetCodecParameter);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetOSType, &cType,
- PyMac_GetOSType, &parameterID,
- ResObj_Convert, &outParameterData))
- return NULL;
- _rv = VideoMediaGetCodecParameter(mh,
- cType,
- parameterID,
- outParameterData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(VideoMediaGetCodecParameter);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetOSType, &cType,
+ PyMac_GetOSType, &parameterID,
+ ResObj_Convert, &outParameterData))
+ return NULL;
+ _rv = VideoMediaGetCodecParameter(mh,
+ cType,
+ parameterID,
+ outParameterData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TextMediaAddTextSample(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Ptr text;
- unsigned long size;
- short fontNumber;
- short fontSize;
- Style textFace;
- RGBColor textColor;
- RGBColor backColor;
- short textJustification;
- Rect textBox;
- long displayFlags;
- TimeValue scrollDelay;
- short hiliteStart;
- short hiliteEnd;
- RGBColor rgbHiliteColor;
- TimeValue duration;
- TimeValue sampleTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Ptr text;
+ unsigned long size;
+ short fontNumber;
+ short fontSize;
+ Style textFace;
+ RGBColor textColor;
+ RGBColor backColor;
+ short textJustification;
+ Rect textBox;
+ long displayFlags;
+ TimeValue scrollDelay;
+ short hiliteStart;
+ short hiliteEnd;
+ RGBColor rgbHiliteColor;
+ TimeValue duration;
+ TimeValue sampleTime;
#ifndef TextMediaAddTextSample
- PyMac_PRECHECK(TextMediaAddTextSample);
-#endif
- if (!PyArg_ParseTuple(_args, "O&slhhbhllhhl",
- CmpInstObj_Convert, &mh,
- &text,
- &size,
- &fontNumber,
- &fontSize,
- &textFace,
- &textJustification,
- &displayFlags,
- &scrollDelay,
- &hiliteStart,
- &hiliteEnd,
- &duration))
- return NULL;
- _rv = TextMediaAddTextSample(mh,
- text,
- size,
- fontNumber,
- fontSize,
- textFace,
- &textColor,
- &backColor,
- textJustification,
- &textBox,
- displayFlags,
- scrollDelay,
- hiliteStart,
- hiliteEnd,
- &rgbHiliteColor,
- duration,
- &sampleTime);
- _res = Py_BuildValue("lO&O&O&O&l",
- _rv,
- QdRGB_New, &textColor,
- QdRGB_New, &backColor,
- PyMac_BuildRect, &textBox,
- QdRGB_New, &rgbHiliteColor,
- sampleTime);
- return _res;
+ PyMac_PRECHECK(TextMediaAddTextSample);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&slhhbhllhhl",
+ CmpInstObj_Convert, &mh,
+ &text,
+ &size,
+ &fontNumber,
+ &fontSize,
+ &textFace,
+ &textJustification,
+ &displayFlags,
+ &scrollDelay,
+ &hiliteStart,
+ &hiliteEnd,
+ &duration))
+ return NULL;
+ _rv = TextMediaAddTextSample(mh,
+ text,
+ size,
+ fontNumber,
+ fontSize,
+ textFace,
+ &textColor,
+ &backColor,
+ textJustification,
+ &textBox,
+ displayFlags,
+ scrollDelay,
+ hiliteStart,
+ hiliteEnd,
+ &rgbHiliteColor,
+ duration,
+ &sampleTime);
+ _res = Py_BuildValue("lO&O&O&O&l",
+ _rv,
+ QdRGB_New, &textColor,
+ QdRGB_New, &backColor,
+ PyMac_BuildRect, &textBox,
+ QdRGB_New, &rgbHiliteColor,
+ sampleTime);
+ return _res;
}
static PyObject *Qt_TextMediaAddTESample(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TEHandle hTE;
- RGBColor backColor;
- short textJustification;
- Rect textBox;
- long displayFlags;
- TimeValue scrollDelay;
- short hiliteStart;
- short hiliteEnd;
- RGBColor rgbHiliteColor;
- TimeValue duration;
- TimeValue sampleTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TEHandle hTE;
+ RGBColor backColor;
+ short textJustification;
+ Rect textBox;
+ long displayFlags;
+ TimeValue scrollDelay;
+ short hiliteStart;
+ short hiliteEnd;
+ RGBColor rgbHiliteColor;
+ TimeValue duration;
+ TimeValue sampleTime;
#ifndef TextMediaAddTESample
- PyMac_PRECHECK(TextMediaAddTESample);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hllhhl",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &hTE,
- &textJustification,
- &displayFlags,
- &scrollDelay,
- &hiliteStart,
- &hiliteEnd,
- &duration))
- return NULL;
- _rv = TextMediaAddTESample(mh,
- hTE,
- &backColor,
- textJustification,
- &textBox,
- displayFlags,
- scrollDelay,
- hiliteStart,
- hiliteEnd,
- &rgbHiliteColor,
- duration,
- &sampleTime);
- _res = Py_BuildValue("lO&O&O&l",
- _rv,
- QdRGB_New, &backColor,
- PyMac_BuildRect, &textBox,
- QdRGB_New, &rgbHiliteColor,
- sampleTime);
- return _res;
+ PyMac_PRECHECK(TextMediaAddTESample);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hllhhl",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &hTE,
+ &textJustification,
+ &displayFlags,
+ &scrollDelay,
+ &hiliteStart,
+ &hiliteEnd,
+ &duration))
+ return NULL;
+ _rv = TextMediaAddTESample(mh,
+ hTE,
+ &backColor,
+ textJustification,
+ &textBox,
+ displayFlags,
+ scrollDelay,
+ hiliteStart,
+ hiliteEnd,
+ &rgbHiliteColor,
+ duration,
+ &sampleTime);
+ _res = Py_BuildValue("lO&O&O&l",
+ _rv,
+ QdRGB_New, &backColor,
+ PyMac_BuildRect, &textBox,
+ QdRGB_New, &rgbHiliteColor,
+ sampleTime);
+ return _res;
}
static PyObject *Qt_TextMediaAddHiliteSample(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short hiliteStart;
- short hiliteEnd;
- RGBColor rgbHiliteColor;
- TimeValue duration;
- TimeValue sampleTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short hiliteStart;
+ short hiliteEnd;
+ RGBColor rgbHiliteColor;
+ TimeValue duration;
+ TimeValue sampleTime;
#ifndef TextMediaAddHiliteSample
- PyMac_PRECHECK(TextMediaAddHiliteSample);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhl",
- CmpInstObj_Convert, &mh,
- &hiliteStart,
- &hiliteEnd,
- &duration))
- return NULL;
- _rv = TextMediaAddHiliteSample(mh,
- hiliteStart,
- hiliteEnd,
- &rgbHiliteColor,
- duration,
- &sampleTime);
- _res = Py_BuildValue("lO&l",
- _rv,
- QdRGB_New, &rgbHiliteColor,
- sampleTime);
- return _res;
+ PyMac_PRECHECK(TextMediaAddHiliteSample);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhl",
+ CmpInstObj_Convert, &mh,
+ &hiliteStart,
+ &hiliteEnd,
+ &duration))
+ return NULL;
+ _rv = TextMediaAddHiliteSample(mh,
+ hiliteStart,
+ hiliteEnd,
+ &rgbHiliteColor,
+ duration,
+ &sampleTime);
+ _res = Py_BuildValue("lO&l",
+ _rv,
+ QdRGB_New, &rgbHiliteColor,
+ sampleTime);
+ return _res;
}
static PyObject *Qt_TextMediaDrawRaw(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- GWorldPtr gw;
- GDHandle gd;
- void * data;
- long dataSize;
- TextDescriptionHandle tdh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ GWorldPtr gw;
+ GDHandle gd;
+ void * data;
+ long dataSize;
+ TextDescriptionHandle tdh;
#ifndef TextMediaDrawRaw
- PyMac_PRECHECK(TextMediaDrawRaw);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&slO&",
- CmpInstObj_Convert, &mh,
- GWorldObj_Convert, &gw,
- OptResObj_Convert, &gd,
- &data,
- &dataSize,
- ResObj_Convert, &tdh))
- return NULL;
- _rv = TextMediaDrawRaw(mh,
- gw,
- gd,
- data,
- dataSize,
- tdh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(TextMediaDrawRaw);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&slO&",
+ CmpInstObj_Convert, &mh,
+ GWorldObj_Convert, &gw,
+ OptResObj_Convert, &gd,
+ &data,
+ &dataSize,
+ ResObj_Convert, &tdh))
+ return NULL;
+ _rv = TextMediaDrawRaw(mh,
+ gw,
+ gd,
+ data,
+ dataSize,
+ tdh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TextMediaSetTextProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue atMediaTime;
- long propertyType;
- void * data;
- long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue atMediaTime;
+ long propertyType;
+ void * data;
+ long dataSize;
#ifndef TextMediaSetTextProperty
- PyMac_PRECHECK(TextMediaSetTextProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llsl",
- CmpInstObj_Convert, &mh,
- &atMediaTime,
- &propertyType,
- &data,
- &dataSize))
- return NULL;
- _rv = TextMediaSetTextProperty(mh,
- atMediaTime,
- propertyType,
- data,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(TextMediaSetTextProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llsl",
+ CmpInstObj_Convert, &mh,
+ &atMediaTime,
+ &propertyType,
+ &data,
+ &dataSize))
+ return NULL;
+ _rv = TextMediaSetTextProperty(mh,
+ atMediaTime,
+ propertyType,
+ data,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TextMediaRawSetup(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- GWorldPtr gw;
- GDHandle gd;
- void * data;
- long dataSize;
- TextDescriptionHandle tdh;
- TimeValue sampleDuration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ GWorldPtr gw;
+ GDHandle gd;
+ void * data;
+ long dataSize;
+ TextDescriptionHandle tdh;
+ TimeValue sampleDuration;
#ifndef TextMediaRawSetup
- PyMac_PRECHECK(TextMediaRawSetup);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&slO&l",
- CmpInstObj_Convert, &mh,
- GWorldObj_Convert, &gw,
- OptResObj_Convert, &gd,
- &data,
- &dataSize,
- ResObj_Convert, &tdh,
- &sampleDuration))
- return NULL;
- _rv = TextMediaRawSetup(mh,
- gw,
- gd,
- data,
- dataSize,
- tdh,
- sampleDuration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(TextMediaRawSetup);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&slO&l",
+ CmpInstObj_Convert, &mh,
+ GWorldObj_Convert, &gw,
+ OptResObj_Convert, &gd,
+ &data,
+ &dataSize,
+ ResObj_Convert, &tdh,
+ &sampleDuration))
+ return NULL;
+ _rv = TextMediaRawSetup(mh,
+ gw,
+ gd,
+ data,
+ dataSize,
+ tdh,
+ sampleDuration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TextMediaRawIdle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- GWorldPtr gw;
- GDHandle gd;
- TimeValue sampleTime;
- long flagsIn;
- long flagsOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ GWorldPtr gw;
+ GDHandle gd;
+ TimeValue sampleTime;
+ long flagsIn;
+ long flagsOut;
#ifndef TextMediaRawIdle
- PyMac_PRECHECK(TextMediaRawIdle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&ll",
- CmpInstObj_Convert, &mh,
- GWorldObj_Convert, &gw,
- OptResObj_Convert, &gd,
- &sampleTime,
- &flagsIn))
- return NULL;
- _rv = TextMediaRawIdle(mh,
- gw,
- gd,
- sampleTime,
- flagsIn,
- &flagsOut);
- _res = Py_BuildValue("ll",
- _rv,
- flagsOut);
- return _res;
+ PyMac_PRECHECK(TextMediaRawIdle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&ll",
+ CmpInstObj_Convert, &mh,
+ GWorldObj_Convert, &gw,
+ OptResObj_Convert, &gd,
+ &sampleTime,
+ &flagsIn))
+ return NULL;
+ _rv = TextMediaRawIdle(mh,
+ gw,
+ gd,
+ sampleTime,
+ flagsIn,
+ &flagsOut);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flagsOut);
+ return _res;
}
static PyObject *Qt_TextMediaGetTextProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue atMediaTime;
- long propertyType;
- void * data;
- long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue atMediaTime;
+ long propertyType;
+ void * data;
+ long dataSize;
#ifndef TextMediaGetTextProperty
- PyMac_PRECHECK(TextMediaGetTextProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llsl",
- CmpInstObj_Convert, &mh,
- &atMediaTime,
- &propertyType,
- &data,
- &dataSize))
- return NULL;
- _rv = TextMediaGetTextProperty(mh,
- atMediaTime,
- propertyType,
- data,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(TextMediaGetTextProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llsl",
+ CmpInstObj_Convert, &mh,
+ &atMediaTime,
+ &propertyType,
+ &data,
+ &dataSize))
+ return NULL;
+ _rv = TextMediaGetTextProperty(mh,
+ atMediaTime,
+ propertyType,
+ data,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TextMediaFindNextText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Ptr text;
- long size;
- short findFlags;
- TimeValue startTime;
- TimeValue foundTime;
- TimeValue foundDuration;
- long offset;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Ptr text;
+ long size;
+ short findFlags;
+ TimeValue startTime;
+ TimeValue foundTime;
+ TimeValue foundDuration;
+ long offset;
#ifndef TextMediaFindNextText
- PyMac_PRECHECK(TextMediaFindNextText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&slhl",
- CmpInstObj_Convert, &mh,
- &text,
- &size,
- &findFlags,
- &startTime))
- return NULL;
- _rv = TextMediaFindNextText(mh,
- text,
- size,
- findFlags,
- startTime,
- &foundTime,
- &foundDuration,
- &offset);
- _res = Py_BuildValue("llll",
- _rv,
- foundTime,
- foundDuration,
- offset);
- return _res;
+ PyMac_PRECHECK(TextMediaFindNextText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&slhl",
+ CmpInstObj_Convert, &mh,
+ &text,
+ &size,
+ &findFlags,
+ &startTime))
+ return NULL;
+ _rv = TextMediaFindNextText(mh,
+ text,
+ size,
+ findFlags,
+ startTime,
+ &foundTime,
+ &foundDuration,
+ &offset);
+ _res = Py_BuildValue("llll",
+ _rv,
+ foundTime,
+ foundDuration,
+ offset);
+ return _res;
}
static PyObject *Qt_TextMediaHiliteTextSample(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue sampleTime;
- short hiliteStart;
- short hiliteEnd;
- RGBColor rgbHiliteColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue sampleTime;
+ short hiliteStart;
+ short hiliteEnd;
+ RGBColor rgbHiliteColor;
#ifndef TextMediaHiliteTextSample
- PyMac_PRECHECK(TextMediaHiliteTextSample);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lhh",
- CmpInstObj_Convert, &mh,
- &sampleTime,
- &hiliteStart,
- &hiliteEnd))
- return NULL;
- _rv = TextMediaHiliteTextSample(mh,
- sampleTime,
- hiliteStart,
- hiliteEnd,
- &rgbHiliteColor);
- _res = Py_BuildValue("lO&",
- _rv,
- QdRGB_New, &rgbHiliteColor);
- return _res;
+ PyMac_PRECHECK(TextMediaHiliteTextSample);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lhh",
+ CmpInstObj_Convert, &mh,
+ &sampleTime,
+ &hiliteStart,
+ &hiliteEnd))
+ return NULL;
+ _rv = TextMediaHiliteTextSample(mh,
+ sampleTime,
+ hiliteStart,
+ hiliteEnd,
+ &rgbHiliteColor);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QdRGB_New, &rgbHiliteColor);
+ return _res;
}
static PyObject *Qt_TextMediaSetTextSampleData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * data;
- OSType dataType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * data;
+ OSType dataType;
#ifndef TextMediaSetTextSampleData
- PyMac_PRECHECK(TextMediaSetTextSampleData);
+ PyMac_PRECHECK(TextMediaSetTextSampleData);
#endif
- if (!PyArg_ParseTuple(_args, "O&sO&",
- CmpInstObj_Convert, &mh,
- &data,
- PyMac_GetOSType, &dataType))
- return NULL;
- _rv = TextMediaSetTextSampleData(mh,
- data,
- dataType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&sO&",
+ CmpInstObj_Convert, &mh,
+ &data,
+ PyMac_GetOSType, &dataType))
+ return NULL;
+ _rv = TextMediaSetTextSampleData(mh,
+ data,
+ dataType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaSetProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short spriteIndex;
- long propertyType;
- void * propertyValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short spriteIndex;
+ long propertyType;
+ void * propertyValue;
#ifndef SpriteMediaSetProperty
- PyMac_PRECHECK(SpriteMediaSetProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hls",
- CmpInstObj_Convert, &mh,
- &spriteIndex,
- &propertyType,
- &propertyValue))
- return NULL;
- _rv = SpriteMediaSetProperty(mh,
- spriteIndex,
- propertyType,
- propertyValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SpriteMediaSetProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hls",
+ CmpInstObj_Convert, &mh,
+ &spriteIndex,
+ &propertyType,
+ &propertyValue))
+ return NULL;
+ _rv = SpriteMediaSetProperty(mh,
+ spriteIndex,
+ propertyType,
+ propertyValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short spriteIndex;
- long propertyType;
- void * propertyValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short spriteIndex;
+ long propertyType;
+ void * propertyValue;
#ifndef SpriteMediaGetProperty
- PyMac_PRECHECK(SpriteMediaGetProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hls",
- CmpInstObj_Convert, &mh,
- &spriteIndex,
- &propertyType,
- &propertyValue))
- return NULL;
- _rv = SpriteMediaGetProperty(mh,
- spriteIndex,
- propertyType,
- propertyValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SpriteMediaGetProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hls",
+ CmpInstObj_Convert, &mh,
+ &spriteIndex,
+ &propertyType,
+ &propertyValue))
+ return NULL;
+ _rv = SpriteMediaGetProperty(mh,
+ spriteIndex,
+ propertyType,
+ propertyValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaHitTestSprites(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long flags;
- Point loc;
- short spriteHitIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long flags;
+ Point loc;
+ short spriteHitIndex;
#ifndef SpriteMediaHitTestSprites
- PyMac_PRECHECK(SpriteMediaHitTestSprites);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &flags,
- PyMac_GetPoint, &loc))
- return NULL;
- _rv = SpriteMediaHitTestSprites(mh,
- flags,
- loc,
- &spriteHitIndex);
- _res = Py_BuildValue("lh",
- _rv,
- spriteHitIndex);
- return _res;
+ PyMac_PRECHECK(SpriteMediaHitTestSprites);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ PyMac_GetPoint, &loc))
+ return NULL;
+ _rv = SpriteMediaHitTestSprites(mh,
+ flags,
+ loc,
+ &spriteHitIndex);
+ _res = Py_BuildValue("lh",
+ _rv,
+ spriteHitIndex);
+ return _res;
}
static PyObject *Qt_SpriteMediaCountSprites(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short numSprites;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short numSprites;
#ifndef SpriteMediaCountSprites
- PyMac_PRECHECK(SpriteMediaCountSprites);
+ PyMac_PRECHECK(SpriteMediaCountSprites);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = SpriteMediaCountSprites(mh,
- &numSprites);
- _res = Py_BuildValue("lh",
- _rv,
- numSprites);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = SpriteMediaCountSprites(mh,
+ &numSprites);
+ _res = Py_BuildValue("lh",
+ _rv,
+ numSprites);
+ return _res;
}
static PyObject *Qt_SpriteMediaCountImages(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short numImages;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short numImages;
#ifndef SpriteMediaCountImages
- PyMac_PRECHECK(SpriteMediaCountImages);
+ PyMac_PRECHECK(SpriteMediaCountImages);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = SpriteMediaCountImages(mh,
- &numImages);
- _res = Py_BuildValue("lh",
- _rv,
- numImages);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = SpriteMediaCountImages(mh,
+ &numImages);
+ _res = Py_BuildValue("lh",
+ _rv,
+ numImages);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetIndImageDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short imageIndex;
- ImageDescriptionHandle imageDescription;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short imageIndex;
+ ImageDescriptionHandle imageDescription;
#ifndef SpriteMediaGetIndImageDescription
- PyMac_PRECHECK(SpriteMediaGetIndImageDescription);
+ PyMac_PRECHECK(SpriteMediaGetIndImageDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&hO&",
- CmpInstObj_Convert, &mh,
- &imageIndex,
- ResObj_Convert, &imageDescription))
- return NULL;
- _rv = SpriteMediaGetIndImageDescription(mh,
- imageIndex,
- imageDescription);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hO&",
+ CmpInstObj_Convert, &mh,
+ &imageIndex,
+ ResObj_Convert, &imageDescription))
+ return NULL;
+ _rv = SpriteMediaGetIndImageDescription(mh,
+ imageIndex,
+ imageDescription);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetDisplayedSampleNumber(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long sampleNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long sampleNum;
#ifndef SpriteMediaGetDisplayedSampleNumber
- PyMac_PRECHECK(SpriteMediaGetDisplayedSampleNumber);
+ PyMac_PRECHECK(SpriteMediaGetDisplayedSampleNumber);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = SpriteMediaGetDisplayedSampleNumber(mh,
- &sampleNum);
- _res = Py_BuildValue("ll",
- _rv,
- sampleNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = SpriteMediaGetDisplayedSampleNumber(mh,
+ &sampleNum);
+ _res = Py_BuildValue("ll",
+ _rv,
+ sampleNum);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetSpriteName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID spriteID;
- Str255 spriteName;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID spriteID;
+ Str255 spriteName;
#ifndef SpriteMediaGetSpriteName
- PyMac_PRECHECK(SpriteMediaGetSpriteName);
+ PyMac_PRECHECK(SpriteMediaGetSpriteName);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &spriteID,
- PyMac_GetStr255, spriteName))
- return NULL;
- _rv = SpriteMediaGetSpriteName(mh,
- spriteID,
- spriteName);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &spriteID,
+ PyMac_GetStr255, spriteName))
+ return NULL;
+ _rv = SpriteMediaGetSpriteName(mh,
+ spriteID,
+ spriteName);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetImageName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short imageIndex;
- Str255 imageName;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short imageIndex;
+ Str255 imageName;
#ifndef SpriteMediaGetImageName
- PyMac_PRECHECK(SpriteMediaGetImageName);
+ PyMac_PRECHECK(SpriteMediaGetImageName);
#endif
- if (!PyArg_ParseTuple(_args, "O&hO&",
- CmpInstObj_Convert, &mh,
- &imageIndex,
- PyMac_GetStr255, imageName))
- return NULL;
- _rv = SpriteMediaGetImageName(mh,
- imageIndex,
- imageName);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hO&",
+ CmpInstObj_Convert, &mh,
+ &imageIndex,
+ PyMac_GetStr255, imageName))
+ return NULL;
+ _rv = SpriteMediaGetImageName(mh,
+ imageIndex,
+ imageName);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaSetSpriteProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID spriteID;
- long propertyType;
- void * propertyValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID spriteID;
+ long propertyType;
+ void * propertyValue;
#ifndef SpriteMediaSetSpriteProperty
- PyMac_PRECHECK(SpriteMediaSetSpriteProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lls",
- CmpInstObj_Convert, &mh,
- &spriteID,
- &propertyType,
- &propertyValue))
- return NULL;
- _rv = SpriteMediaSetSpriteProperty(mh,
- spriteID,
- propertyType,
- propertyValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SpriteMediaSetSpriteProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lls",
+ CmpInstObj_Convert, &mh,
+ &spriteID,
+ &propertyType,
+ &propertyValue))
+ return NULL;
+ _rv = SpriteMediaSetSpriteProperty(mh,
+ spriteID,
+ propertyType,
+ propertyValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetSpriteProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID spriteID;
- long propertyType;
- void * propertyValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID spriteID;
+ long propertyType;
+ void * propertyValue;
#ifndef SpriteMediaGetSpriteProperty
- PyMac_PRECHECK(SpriteMediaGetSpriteProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lls",
- CmpInstObj_Convert, &mh,
- &spriteID,
- &propertyType,
- &propertyValue))
- return NULL;
- _rv = SpriteMediaGetSpriteProperty(mh,
- spriteID,
- propertyType,
- propertyValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SpriteMediaGetSpriteProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lls",
+ CmpInstObj_Convert, &mh,
+ &spriteID,
+ &propertyType,
+ &propertyValue))
+ return NULL;
+ _rv = SpriteMediaGetSpriteProperty(mh,
+ spriteID,
+ propertyType,
+ propertyValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaHitTestAllSprites(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long flags;
- Point loc;
- QTAtomID spriteHitID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long flags;
+ Point loc;
+ QTAtomID spriteHitID;
#ifndef SpriteMediaHitTestAllSprites
- PyMac_PRECHECK(SpriteMediaHitTestAllSprites);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &flags,
- PyMac_GetPoint, &loc))
- return NULL;
- _rv = SpriteMediaHitTestAllSprites(mh,
- flags,
- loc,
- &spriteHitID);
- _res = Py_BuildValue("ll",
- _rv,
- spriteHitID);
- return _res;
+ PyMac_PRECHECK(SpriteMediaHitTestAllSprites);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ PyMac_GetPoint, &loc))
+ return NULL;
+ _rv = SpriteMediaHitTestAllSprites(mh,
+ flags,
+ loc,
+ &spriteHitID);
+ _res = Py_BuildValue("ll",
+ _rv,
+ spriteHitID);
+ return _res;
}
static PyObject *Qt_SpriteMediaHitTestOneSprite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID spriteID;
- long flags;
- Point loc;
- Boolean wasHit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID spriteID;
+ long flags;
+ Point loc;
+ Boolean wasHit;
#ifndef SpriteMediaHitTestOneSprite
- PyMac_PRECHECK(SpriteMediaHitTestOneSprite);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llO&",
- CmpInstObj_Convert, &mh,
- &spriteID,
- &flags,
- PyMac_GetPoint, &loc))
- return NULL;
- _rv = SpriteMediaHitTestOneSprite(mh,
- spriteID,
- flags,
- loc,
- &wasHit);
- _res = Py_BuildValue("lb",
- _rv,
- wasHit);
- return _res;
+ PyMac_PRECHECK(SpriteMediaHitTestOneSprite);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llO&",
+ CmpInstObj_Convert, &mh,
+ &spriteID,
+ &flags,
+ PyMac_GetPoint, &loc))
+ return NULL;
+ _rv = SpriteMediaHitTestOneSprite(mh,
+ spriteID,
+ flags,
+ loc,
+ &wasHit);
+ _res = Py_BuildValue("lb",
+ _rv,
+ wasHit);
+ return _res;
}
static PyObject *Qt_SpriteMediaSpriteIndexToID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short spriteIndex;
- QTAtomID spriteID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short spriteIndex;
+ QTAtomID spriteID;
#ifndef SpriteMediaSpriteIndexToID
- PyMac_PRECHECK(SpriteMediaSpriteIndexToID);
+ PyMac_PRECHECK(SpriteMediaSpriteIndexToID);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mh,
- &spriteIndex))
- return NULL;
- _rv = SpriteMediaSpriteIndexToID(mh,
- spriteIndex,
- &spriteID);
- _res = Py_BuildValue("ll",
- _rv,
- spriteID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mh,
+ &spriteIndex))
+ return NULL;
+ _rv = SpriteMediaSpriteIndexToID(mh,
+ spriteIndex,
+ &spriteID);
+ _res = Py_BuildValue("ll",
+ _rv,
+ spriteID);
+ return _res;
}
static PyObject *Qt_SpriteMediaSpriteIDToIndex(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID spriteID;
- short spriteIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID spriteID;
+ short spriteIndex;
#ifndef SpriteMediaSpriteIDToIndex
- PyMac_PRECHECK(SpriteMediaSpriteIDToIndex);
+ PyMac_PRECHECK(SpriteMediaSpriteIDToIndex);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &spriteID))
- return NULL;
- _rv = SpriteMediaSpriteIDToIndex(mh,
- spriteID,
- &spriteIndex);
- _res = Py_BuildValue("lh",
- _rv,
- spriteIndex);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &spriteID))
+ return NULL;
+ _rv = SpriteMediaSpriteIDToIndex(mh,
+ spriteID,
+ &spriteIndex);
+ _res = Py_BuildValue("lh",
+ _rv,
+ spriteIndex);
+ return _res;
}
static PyObject *Qt_SpriteMediaSetActionVariable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID variableID;
- float value;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID variableID;
+ float value;
#ifndef SpriteMediaSetActionVariable
- PyMac_PRECHECK(SpriteMediaSetActionVariable);
+ PyMac_PRECHECK(SpriteMediaSetActionVariable);
#endif
- if (!PyArg_ParseTuple(_args, "O&lf",
- CmpInstObj_Convert, &mh,
- &variableID,
- &value))
- return NULL;
- _rv = SpriteMediaSetActionVariable(mh,
- variableID,
- &value);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lf",
+ CmpInstObj_Convert, &mh,
+ &variableID,
+ &value))
+ return NULL;
+ _rv = SpriteMediaSetActionVariable(mh,
+ variableID,
+ &value);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetActionVariable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID variableID;
- float value;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID variableID;
+ float value;
#ifndef SpriteMediaGetActionVariable
- PyMac_PRECHECK(SpriteMediaGetActionVariable);
+ PyMac_PRECHECK(SpriteMediaGetActionVariable);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &variableID))
- return NULL;
- _rv = SpriteMediaGetActionVariable(mh,
- variableID,
- &value);
- _res = Py_BuildValue("lf",
- _rv,
- value);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &variableID))
+ return NULL;
+ _rv = SpriteMediaGetActionVariable(mh,
+ variableID,
+ &value);
+ _res = Py_BuildValue("lf",
+ _rv,
+ value);
+ return _res;
}
static PyObject *Qt_SpriteMediaDisposeSprite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID spriteID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID spriteID;
#ifndef SpriteMediaDisposeSprite
- PyMac_PRECHECK(SpriteMediaDisposeSprite);
+ PyMac_PRECHECK(SpriteMediaDisposeSprite);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &spriteID))
- return NULL;
- _rv = SpriteMediaDisposeSprite(mh,
- spriteID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &spriteID))
+ return NULL;
+ _rv = SpriteMediaDisposeSprite(mh,
+ spriteID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaSetActionVariableToString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID variableID;
- Ptr theCString;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID variableID;
+ Ptr theCString;
#ifndef SpriteMediaSetActionVariableToString
- PyMac_PRECHECK(SpriteMediaSetActionVariableToString);
+ PyMac_PRECHECK(SpriteMediaSetActionVariableToString);
#endif
- if (!PyArg_ParseTuple(_args, "O&ls",
- CmpInstObj_Convert, &mh,
- &variableID,
- &theCString))
- return NULL;
- _rv = SpriteMediaSetActionVariableToString(mh,
- variableID,
- theCString);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ls",
+ CmpInstObj_Convert, &mh,
+ &variableID,
+ &theCString))
+ return NULL;
+ _rv = SpriteMediaSetActionVariableToString(mh,
+ variableID,
+ theCString);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaGetActionVariableAsString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID variableID;
- Handle theCString;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID variableID;
+ Handle theCString;
#ifndef SpriteMediaGetActionVariableAsString
- PyMac_PRECHECK(SpriteMediaGetActionVariableAsString);
+ PyMac_PRECHECK(SpriteMediaGetActionVariableAsString);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &variableID))
- return NULL;
- _rv = SpriteMediaGetActionVariableAsString(mh,
- variableID,
- &theCString);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, theCString);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &variableID))
+ return NULL;
+ _rv = SpriteMediaGetActionVariableAsString(mh,
+ variableID,
+ &theCString);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, theCString);
+ return _res;
}
static PyObject *Qt_SpriteMediaNewImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Handle dataRef;
- OSType dataRefType;
- QTAtomID desiredID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Handle dataRef;
+ OSType dataRefType;
+ QTAtomID desiredID;
#ifndef SpriteMediaNewImage
- PyMac_PRECHECK(SpriteMediaNewImage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- &desiredID))
- return NULL;
- _rv = SpriteMediaNewImage(mh,
- dataRef,
- dataRefType,
- desiredID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SpriteMediaNewImage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ &desiredID))
+ return NULL;
+ _rv = SpriteMediaNewImage(mh,
+ dataRef,
+ dataRefType,
+ desiredID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaDisposeImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short imageIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short imageIndex;
#ifndef SpriteMediaDisposeImage
- PyMac_PRECHECK(SpriteMediaDisposeImage);
+ PyMac_PRECHECK(SpriteMediaDisposeImage);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mh,
- &imageIndex))
- return NULL;
- _rv = SpriteMediaDisposeImage(mh,
- imageIndex);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mh,
+ &imageIndex))
+ return NULL;
+ _rv = SpriteMediaDisposeImage(mh,
+ imageIndex);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SpriteMediaImageIndexToID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short imageIndex;
- QTAtomID imageID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short imageIndex;
+ QTAtomID imageID;
#ifndef SpriteMediaImageIndexToID
- PyMac_PRECHECK(SpriteMediaImageIndexToID);
+ PyMac_PRECHECK(SpriteMediaImageIndexToID);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mh,
- &imageIndex))
- return NULL;
- _rv = SpriteMediaImageIndexToID(mh,
- imageIndex,
- &imageID);
- _res = Py_BuildValue("ll",
- _rv,
- imageID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mh,
+ &imageIndex))
+ return NULL;
+ _rv = SpriteMediaImageIndexToID(mh,
+ imageIndex,
+ &imageID);
+ _res = Py_BuildValue("ll",
+ _rv,
+ imageID);
+ return _res;
}
static PyObject *Qt_SpriteMediaImageIDToIndex(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTAtomID imageID;
- short imageIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTAtomID imageID;
+ short imageIndex;
#ifndef SpriteMediaImageIDToIndex
- PyMac_PRECHECK(SpriteMediaImageIDToIndex);
+ PyMac_PRECHECK(SpriteMediaImageIDToIndex);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &imageID))
- return NULL;
- _rv = SpriteMediaImageIDToIndex(mh,
- imageID,
- &imageIndex);
- _res = Py_BuildValue("lh",
- _rv,
- imageIndex);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &imageID))
+ return NULL;
+ _rv = SpriteMediaImageIDToIndex(mh,
+ imageID,
+ &imageIndex);
+ _res = Py_BuildValue("lh",
+ _rv,
+ imageIndex);
+ return _res;
}
static PyObject *Qt_FlashMediaSetPan(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short xPercent;
- short yPercent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short xPercent;
+ short yPercent;
#ifndef FlashMediaSetPan
- PyMac_PRECHECK(FlashMediaSetPan);
+ PyMac_PRECHECK(FlashMediaSetPan);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- CmpInstObj_Convert, &mh,
- &xPercent,
- &yPercent))
- return NULL;
- _rv = FlashMediaSetPan(mh,
- xPercent,
- yPercent);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ CmpInstObj_Convert, &mh,
+ &xPercent,
+ &yPercent))
+ return NULL;
+ _rv = FlashMediaSetPan(mh,
+ xPercent,
+ yPercent);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_FlashMediaSetZoom(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short factor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short factor;
#ifndef FlashMediaSetZoom
- PyMac_PRECHECK(FlashMediaSetZoom);
+ PyMac_PRECHECK(FlashMediaSetZoom);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mh,
- &factor))
- return NULL;
- _rv = FlashMediaSetZoom(mh,
- factor);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mh,
+ &factor))
+ return NULL;
+ _rv = FlashMediaSetZoom(mh,
+ factor);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_FlashMediaSetZoomRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long left;
- long top;
- long right;
- long bottom;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long left;
+ long top;
+ long right;
+ long bottom;
#ifndef FlashMediaSetZoomRect
- PyMac_PRECHECK(FlashMediaSetZoomRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llll",
- CmpInstObj_Convert, &mh,
- &left,
- &top,
- &right,
- &bottom))
- return NULL;
- _rv = FlashMediaSetZoomRect(mh,
- left,
- top,
- right,
- bottom);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(FlashMediaSetZoomRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llll",
+ CmpInstObj_Convert, &mh,
+ &left,
+ &top,
+ &right,
+ &bottom))
+ return NULL;
+ _rv = FlashMediaSetZoomRect(mh,
+ left,
+ top,
+ right,
+ bottom);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_FlashMediaGetRefConBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long refCon;
- long left;
- long top;
- long right;
- long bottom;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long refCon;
+ long left;
+ long top;
+ long right;
+ long bottom;
#ifndef FlashMediaGetRefConBounds
- PyMac_PRECHECK(FlashMediaGetRefConBounds);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &refCon))
- return NULL;
- _rv = FlashMediaGetRefConBounds(mh,
- refCon,
- &left,
- &top,
- &right,
- &bottom);
- _res = Py_BuildValue("lllll",
- _rv,
- left,
- top,
- right,
- bottom);
- return _res;
+ PyMac_PRECHECK(FlashMediaGetRefConBounds);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &refCon))
+ return NULL;
+ _rv = FlashMediaGetRefConBounds(mh,
+ refCon,
+ &left,
+ &top,
+ &right,
+ &bottom);
+ _res = Py_BuildValue("lllll",
+ _rv,
+ left,
+ top,
+ right,
+ bottom);
+ return _res;
}
static PyObject *Qt_FlashMediaGetRefConID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long refCon;
- long refConID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long refCon;
+ long refConID;
#ifndef FlashMediaGetRefConID
- PyMac_PRECHECK(FlashMediaGetRefConID);
+ PyMac_PRECHECK(FlashMediaGetRefConID);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &refCon))
- return NULL;
- _rv = FlashMediaGetRefConID(mh,
- refCon,
- &refConID);
- _res = Py_BuildValue("ll",
- _rv,
- refConID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &refCon))
+ return NULL;
+ _rv = FlashMediaGetRefConID(mh,
+ refCon,
+ &refConID);
+ _res = Py_BuildValue("ll",
+ _rv,
+ refConID);
+ return _res;
}
static PyObject *Qt_FlashMediaIDToRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long refConID;
- long refCon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long refConID;
+ long refCon;
#ifndef FlashMediaIDToRefCon
- PyMac_PRECHECK(FlashMediaIDToRefCon);
+ PyMac_PRECHECK(FlashMediaIDToRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &refConID))
- return NULL;
- _rv = FlashMediaIDToRefCon(mh,
- refConID,
- &refCon);
- _res = Py_BuildValue("ll",
- _rv,
- refCon);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &refConID))
+ return NULL;
+ _rv = FlashMediaIDToRefCon(mh,
+ refConID,
+ &refCon);
+ _res = Py_BuildValue("ll",
+ _rv,
+ refCon);
+ return _res;
}
static PyObject *Qt_FlashMediaGetDisplayedFrameNumber(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long flashFrameNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long flashFrameNumber;
#ifndef FlashMediaGetDisplayedFrameNumber
- PyMac_PRECHECK(FlashMediaGetDisplayedFrameNumber);
+ PyMac_PRECHECK(FlashMediaGetDisplayedFrameNumber);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = FlashMediaGetDisplayedFrameNumber(mh,
- &flashFrameNumber);
- _res = Py_BuildValue("ll",
- _rv,
- flashFrameNumber);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = FlashMediaGetDisplayedFrameNumber(mh,
+ &flashFrameNumber);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flashFrameNumber);
+ return _res;
}
static PyObject *Qt_FlashMediaFrameNumberToMovieTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long flashFrameNumber;
- TimeValue movieTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long flashFrameNumber;
+ TimeValue movieTime;
#ifndef FlashMediaFrameNumberToMovieTime
- PyMac_PRECHECK(FlashMediaFrameNumberToMovieTime);
+ PyMac_PRECHECK(FlashMediaFrameNumberToMovieTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &flashFrameNumber))
- return NULL;
- _rv = FlashMediaFrameNumberToMovieTime(mh,
- flashFrameNumber,
- &movieTime);
- _res = Py_BuildValue("ll",
- _rv,
- movieTime);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &flashFrameNumber))
+ return NULL;
+ _rv = FlashMediaFrameNumberToMovieTime(mh,
+ flashFrameNumber,
+ &movieTime);
+ _res = Py_BuildValue("ll",
+ _rv,
+ movieTime);
+ return _res;
}
static PyObject *Qt_FlashMediaFrameLabelToMovieTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Ptr theLabel;
- TimeValue movieTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Ptr theLabel;
+ TimeValue movieTime;
#ifndef FlashMediaFrameLabelToMovieTime
- PyMac_PRECHECK(FlashMediaFrameLabelToMovieTime);
+ PyMac_PRECHECK(FlashMediaFrameLabelToMovieTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &theLabel))
- return NULL;
- _rv = FlashMediaFrameLabelToMovieTime(mh,
- theLabel,
- &movieTime);
- _res = Py_BuildValue("ll",
- _rv,
- movieTime);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &theLabel))
+ return NULL;
+ _rv = FlashMediaFrameLabelToMovieTime(mh,
+ theLabel,
+ &movieTime);
+ _res = Py_BuildValue("ll",
+ _rv,
+ movieTime);
+ return _res;
}
static PyObject *Qt_FlashMediaGetFlashVariable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- char path;
- char name;
- Handle theVariableCStringOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ char path;
+ char name;
+ Handle theVariableCStringOut;
#ifndef FlashMediaGetFlashVariable
- PyMac_PRECHECK(FlashMediaGetFlashVariable);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = FlashMediaGetFlashVariable(mh,
- &path,
- &name,
- &theVariableCStringOut);
- _res = Py_BuildValue("lccO&",
- _rv,
- path,
- name,
- ResObj_New, theVariableCStringOut);
- return _res;
+ PyMac_PRECHECK(FlashMediaGetFlashVariable);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = FlashMediaGetFlashVariable(mh,
+ &path,
+ &name,
+ &theVariableCStringOut);
+ _res = Py_BuildValue("lccO&",
+ _rv,
+ path,
+ name,
+ ResObj_New, theVariableCStringOut);
+ return _res;
}
static PyObject *Qt_FlashMediaSetFlashVariable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- char path;
- char name;
- char value;
- Boolean updateFocus;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ char path;
+ char name;
+ char value;
+ Boolean updateFocus;
#ifndef FlashMediaSetFlashVariable
- PyMac_PRECHECK(FlashMediaSetFlashVariable);
-#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &mh,
- &updateFocus))
- return NULL;
- _rv = FlashMediaSetFlashVariable(mh,
- &path,
- &name,
- &value,
- updateFocus);
- _res = Py_BuildValue("lccc",
- _rv,
- path,
- name,
- value);
- return _res;
+ PyMac_PRECHECK(FlashMediaSetFlashVariable);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &mh,
+ &updateFocus))
+ return NULL;
+ _rv = FlashMediaSetFlashVariable(mh,
+ &path,
+ &name,
+ &value,
+ updateFocus);
+ _res = Py_BuildValue("lccc",
+ _rv,
+ path,
+ name,
+ value);
+ return _res;
}
static PyObject *Qt_FlashMediaDoButtonActions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- char path;
- long buttonID;
- long transition;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ char path;
+ long buttonID;
+ long transition;
#ifndef FlashMediaDoButtonActions
- PyMac_PRECHECK(FlashMediaDoButtonActions);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &buttonID,
- &transition))
- return NULL;
- _rv = FlashMediaDoButtonActions(mh,
- &path,
- buttonID,
- transition);
- _res = Py_BuildValue("lc",
- _rv,
- path);
- return _res;
+ PyMac_PRECHECK(FlashMediaDoButtonActions);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &buttonID,
+ &transition))
+ return NULL;
+ _rv = FlashMediaDoButtonActions(mh,
+ &path,
+ buttonID,
+ transition);
+ _res = Py_BuildValue("lc",
+ _rv,
+ path);
+ return _res;
}
static PyObject *Qt_FlashMediaGetSupportedSwfVersion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- UInt8 swfVersion;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ UInt8 swfVersion;
#ifndef FlashMediaGetSupportedSwfVersion
- PyMac_PRECHECK(FlashMediaGetSupportedSwfVersion);
+ PyMac_PRECHECK(FlashMediaGetSupportedSwfVersion);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = FlashMediaGetSupportedSwfVersion(mh,
- &swfVersion);
- _res = Py_BuildValue("lb",
- _rv,
- swfVersion);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = FlashMediaGetSupportedSwfVersion(mh,
+ &swfVersion);
+ _res = Py_BuildValue("lb",
+ _rv,
+ swfVersion);
+ return _res;
}
static PyObject *Qt_Media3DGetCurrentGroup(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * group;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * group;
#ifndef Media3DGetCurrentGroup
- PyMac_PRECHECK(Media3DGetCurrentGroup);
+ PyMac_PRECHECK(Media3DGetCurrentGroup);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &group))
- return NULL;
- _rv = Media3DGetCurrentGroup(mh,
- group);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &group))
+ return NULL;
+ _rv = Media3DGetCurrentGroup(mh,
+ group);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_Media3DTranslateNamedObjectTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- char objectName;
- Fixed x;
- Fixed y;
- Fixed z;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ char objectName;
+ Fixed x;
+ Fixed y;
+ Fixed z;
#ifndef Media3DTranslateNamedObjectTo
- PyMac_PRECHECK(Media3DTranslateNamedObjectTo);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetFixed, &x,
- PyMac_GetFixed, &y,
- PyMac_GetFixed, &z))
- return NULL;
- _rv = Media3DTranslateNamedObjectTo(mh,
- &objectName,
- x,
- y,
- z);
- _res = Py_BuildValue("lc",
- _rv,
- objectName);
- return _res;
+ PyMac_PRECHECK(Media3DTranslateNamedObjectTo);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetFixed, &x,
+ PyMac_GetFixed, &y,
+ PyMac_GetFixed, &z))
+ return NULL;
+ _rv = Media3DTranslateNamedObjectTo(mh,
+ &objectName,
+ x,
+ y,
+ z);
+ _res = Py_BuildValue("lc",
+ _rv,
+ objectName);
+ return _res;
}
static PyObject *Qt_Media3DScaleNamedObjectTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- char objectName;
- Fixed xScale;
- Fixed yScale;
- Fixed zScale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ char objectName;
+ Fixed xScale;
+ Fixed yScale;
+ Fixed zScale;
#ifndef Media3DScaleNamedObjectTo
- PyMac_PRECHECK(Media3DScaleNamedObjectTo);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetFixed, &xScale,
- PyMac_GetFixed, &yScale,
- PyMac_GetFixed, &zScale))
- return NULL;
- _rv = Media3DScaleNamedObjectTo(mh,
- &objectName,
- xScale,
- yScale,
- zScale);
- _res = Py_BuildValue("lc",
- _rv,
- objectName);
- return _res;
+ PyMac_PRECHECK(Media3DScaleNamedObjectTo);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetFixed, &xScale,
+ PyMac_GetFixed, &yScale,
+ PyMac_GetFixed, &zScale))
+ return NULL;
+ _rv = Media3DScaleNamedObjectTo(mh,
+ &objectName,
+ xScale,
+ yScale,
+ zScale);
+ _res = Py_BuildValue("lc",
+ _rv,
+ objectName);
+ return _res;
}
static PyObject *Qt_Media3DRotateNamedObjectTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- char objectName;
- Fixed xDegrees;
- Fixed yDegrees;
- Fixed zDegrees;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ char objectName;
+ Fixed xDegrees;
+ Fixed yDegrees;
+ Fixed zDegrees;
#ifndef Media3DRotateNamedObjectTo
- PyMac_PRECHECK(Media3DRotateNamedObjectTo);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetFixed, &xDegrees,
- PyMac_GetFixed, &yDegrees,
- PyMac_GetFixed, &zDegrees))
- return NULL;
- _rv = Media3DRotateNamedObjectTo(mh,
- &objectName,
- xDegrees,
- yDegrees,
- zDegrees);
- _res = Py_BuildValue("lc",
- _rv,
- objectName);
- return _res;
+ PyMac_PRECHECK(Media3DRotateNamedObjectTo);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetFixed, &xDegrees,
+ PyMac_GetFixed, &yDegrees,
+ PyMac_GetFixed, &zDegrees))
+ return NULL;
+ _rv = Media3DRotateNamedObjectTo(mh,
+ &objectName,
+ xDegrees,
+ yDegrees,
+ zDegrees);
+ _res = Py_BuildValue("lc",
+ _rv,
+ objectName);
+ return _res;
}
static PyObject *Qt_Media3DSetCameraData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * cameraData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * cameraData;
#ifndef Media3DSetCameraData
- PyMac_PRECHECK(Media3DSetCameraData);
+ PyMac_PRECHECK(Media3DSetCameraData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &cameraData))
- return NULL;
- _rv = Media3DSetCameraData(mh,
- cameraData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &cameraData))
+ return NULL;
+ _rv = Media3DSetCameraData(mh,
+ cameraData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_Media3DGetCameraData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * cameraData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * cameraData;
#ifndef Media3DGetCameraData
- PyMac_PRECHECK(Media3DGetCameraData);
+ PyMac_PRECHECK(Media3DGetCameraData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &cameraData))
- return NULL;
- _rv = Media3DGetCameraData(mh,
- cameraData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &cameraData))
+ return NULL;
+ _rv = Media3DGetCameraData(mh,
+ cameraData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_Media3DSetCameraAngleAspect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTFloatSingle fov;
- QTFloatSingle aspectRatioXToY;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTFloatSingle fov;
+ QTFloatSingle aspectRatioXToY;
#ifndef Media3DSetCameraAngleAspect
- PyMac_PRECHECK(Media3DSetCameraAngleAspect);
+ PyMac_PRECHECK(Media3DSetCameraAngleAspect);
#endif
- if (!PyArg_ParseTuple(_args, "O&ff",
- CmpInstObj_Convert, &mh,
- &fov,
- &aspectRatioXToY))
- return NULL;
- _rv = Media3DSetCameraAngleAspect(mh,
- fov,
- aspectRatioXToY);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ff",
+ CmpInstObj_Convert, &mh,
+ &fov,
+ &aspectRatioXToY))
+ return NULL;
+ _rv = Media3DSetCameraAngleAspect(mh,
+ fov,
+ aspectRatioXToY);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_Media3DGetCameraAngleAspect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- QTFloatSingle fov;
- QTFloatSingle aspectRatioXToY;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ QTFloatSingle fov;
+ QTFloatSingle aspectRatioXToY;
#ifndef Media3DGetCameraAngleAspect
- PyMac_PRECHECK(Media3DGetCameraAngleAspect);
+ PyMac_PRECHECK(Media3DGetCameraAngleAspect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = Media3DGetCameraAngleAspect(mh,
- &fov,
- &aspectRatioXToY);
- _res = Py_BuildValue("lff",
- _rv,
- fov,
- aspectRatioXToY);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = Media3DGetCameraAngleAspect(mh,
+ &fov,
+ &aspectRatioXToY);
+ _res = Py_BuildValue("lff",
+ _rv,
+ fov,
+ aspectRatioXToY);
+ return _res;
}
static PyObject *Qt_Media3DSetCameraRange(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * tQ3CameraRange;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * tQ3CameraRange;
#ifndef Media3DSetCameraRange
- PyMac_PRECHECK(Media3DSetCameraRange);
+ PyMac_PRECHECK(Media3DSetCameraRange);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &tQ3CameraRange))
- return NULL;
- _rv = Media3DSetCameraRange(mh,
- tQ3CameraRange);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &tQ3CameraRange))
+ return NULL;
+ _rv = Media3DSetCameraRange(mh,
+ tQ3CameraRange);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_Media3DGetCameraRange(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * tQ3CameraRange;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * tQ3CameraRange;
#ifndef Media3DGetCameraRange
- PyMac_PRECHECK(Media3DGetCameraRange);
+ PyMac_PRECHECK(Media3DGetCameraRange);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &tQ3CameraRange))
- return NULL;
- _rv = Media3DGetCameraRange(mh,
- tQ3CameraRange);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &tQ3CameraRange))
+ return NULL;
+ _rv = Media3DGetCameraRange(mh,
+ tQ3CameraRange);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_NewTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeBase _rv;
+ PyObject *_res = NULL;
+ TimeBase _rv;
#ifndef NewTimeBase
- PyMac_PRECHECK(NewTimeBase);
+ PyMac_PRECHECK(NewTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = NewTimeBase();
- _res = Py_BuildValue("O&",
- TimeBaseObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = NewTimeBase();
+ _res = Py_BuildValue("O&",
+ TimeBaseObj_New, _rv);
+ return _res;
}
static PyObject *Qt_ConvertTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord theTime;
- TimeBase newBase;
+ PyObject *_res = NULL;
+ TimeRecord theTime;
+ TimeBase newBase;
#ifndef ConvertTime
- PyMac_PRECHECK(ConvertTime);
+ PyMac_PRECHECK(ConvertTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- QtTimeRecord_Convert, &theTime,
- TimeBaseObj_Convert, &newBase))
- return NULL;
- ConvertTime(&theTime,
- newBase);
- _res = Py_BuildValue("O&",
- QtTimeRecord_New, &theTime);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ QtTimeRecord_Convert, &theTime,
+ TimeBaseObj_Convert, &newBase))
+ return NULL;
+ ConvertTime(&theTime,
+ newBase);
+ _res = Py_BuildValue("O&",
+ QtTimeRecord_New, &theTime);
+ return _res;
}
static PyObject *Qt_ConvertTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord theTime;
- TimeScale newScale;
+ PyObject *_res = NULL;
+ TimeRecord theTime;
+ TimeScale newScale;
#ifndef ConvertTimeScale
- PyMac_PRECHECK(ConvertTimeScale);
+ PyMac_PRECHECK(ConvertTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- QtTimeRecord_Convert, &theTime,
- &newScale))
- return NULL;
- ConvertTimeScale(&theTime,
- newScale);
- _res = Py_BuildValue("O&",
- QtTimeRecord_New, &theTime);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ QtTimeRecord_Convert, &theTime,
+ &newScale))
+ return NULL;
+ ConvertTimeScale(&theTime,
+ newScale);
+ _res = Py_BuildValue("O&",
+ QtTimeRecord_New, &theTime);
+ return _res;
}
static PyObject *Qt_AddTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord dst;
- TimeRecord src;
+ PyObject *_res = NULL;
+ TimeRecord dst;
+ TimeRecord src;
#ifndef AddTime
- PyMac_PRECHECK(AddTime);
+ PyMac_PRECHECK(AddTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- QtTimeRecord_Convert, &dst,
- QtTimeRecord_Convert, &src))
- return NULL;
- AddTime(&dst,
- &src);
- _res = Py_BuildValue("O&",
- QtTimeRecord_New, &dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ QtTimeRecord_Convert, &dst,
+ QtTimeRecord_Convert, &src))
+ return NULL;
+ AddTime(&dst,
+ &src);
+ _res = Py_BuildValue("O&",
+ QtTimeRecord_New, &dst);
+ return _res;
}
static PyObject *Qt_SubtractTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TimeRecord dst;
- TimeRecord src;
+ PyObject *_res = NULL;
+ TimeRecord dst;
+ TimeRecord src;
#ifndef SubtractTime
- PyMac_PRECHECK(SubtractTime);
+ PyMac_PRECHECK(SubtractTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- QtTimeRecord_Convert, &dst,
- QtTimeRecord_Convert, &src))
- return NULL;
- SubtractTime(&dst,
- &src);
- _res = Py_BuildValue("O&",
- QtTimeRecord_New, &dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ QtTimeRecord_Convert, &dst,
+ QtTimeRecord_Convert, &src))
+ return NULL;
+ SubtractTime(&dst,
+ &src);
+ _res = Py_BuildValue("O&",
+ QtTimeRecord_New, &dst);
+ return _res;
}
static PyObject *Qt_MusicMediaGetIndexedTunePlayer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ti;
- long sampleDescIndex;
- ComponentInstance tp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ti;
+ long sampleDescIndex;
+ ComponentInstance tp;
#ifndef MusicMediaGetIndexedTunePlayer
- PyMac_PRECHECK(MusicMediaGetIndexedTunePlayer);
+ PyMac_PRECHECK(MusicMediaGetIndexedTunePlayer);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ti,
- &sampleDescIndex))
- return NULL;
- _rv = MusicMediaGetIndexedTunePlayer(ti,
- sampleDescIndex,
- &tp);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpInstObj_New, tp);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ti,
+ &sampleDescIndex))
+ return NULL;
+ _rv = MusicMediaGetIndexedTunePlayer(ti,
+ sampleDescIndex,
+ &tp);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpInstObj_New, tp);
+ return _res;
}
static PyObject *Qt_CodecManagerVersion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long version;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long version;
#ifndef CodecManagerVersion
- PyMac_PRECHECK(CodecManagerVersion);
+ PyMac_PRECHECK(CodecManagerVersion);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CodecManagerVersion(&version);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- version);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CodecManagerVersion(&version);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ version);
+ return _res;
}
static PyObject *Qt_GetMaxCompressionSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle src;
- Rect srcRect;
- short colorDepth;
- CodecQ quality;
- CodecType cType;
- CompressorComponent codec;
- long size;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle src;
+ Rect srcRect;
+ short colorDepth;
+ CodecQ quality;
+ CodecType cType;
+ CompressorComponent codec;
+ long size;
#ifndef GetMaxCompressionSize
- PyMac_PRECHECK(GetMaxCompressionSize);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hlO&O&",
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect,
- &colorDepth,
- &quality,
- PyMac_GetOSType, &cType,
- CmpObj_Convert, &codec))
- return NULL;
- _err = GetMaxCompressionSize(src,
- &srcRect,
- colorDepth,
- quality,
- cType,
- codec,
- &size);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- size);
- return _res;
+ PyMac_PRECHECK(GetMaxCompressionSize);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hlO&O&",
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect,
+ &colorDepth,
+ &quality,
+ PyMac_GetOSType, &cType,
+ CmpObj_Convert, &codec))
+ return NULL;
+ _err = GetMaxCompressionSize(src,
+ &srcRect,
+ colorDepth,
+ quality,
+ cType,
+ codec,
+ &size);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ size);
+ return _res;
}
static PyObject *Qt_GetCompressionTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle src;
- Rect srcRect;
- short colorDepth;
- CodecType cType;
- CompressorComponent codec;
- CodecQ spatialQuality;
- CodecQ temporalQuality;
- unsigned long compressTime;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle src;
+ Rect srcRect;
+ short colorDepth;
+ CodecType cType;
+ CompressorComponent codec;
+ CodecQ spatialQuality;
+ CodecQ temporalQuality;
+ unsigned long compressTime;
#ifndef GetCompressionTime
- PyMac_PRECHECK(GetCompressionTime);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hO&O&",
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect,
- &colorDepth,
- PyMac_GetOSType, &cType,
- CmpObj_Convert, &codec))
- return NULL;
- _err = GetCompressionTime(src,
- &srcRect,
- colorDepth,
- cType,
- codec,
- &spatialQuality,
- &temporalQuality,
- &compressTime);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("lll",
- spatialQuality,
- temporalQuality,
- compressTime);
- return _res;
+ PyMac_PRECHECK(GetCompressionTime);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hO&O&",
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect,
+ &colorDepth,
+ PyMac_GetOSType, &cType,
+ CmpObj_Convert, &codec))
+ return NULL;
+ _err = GetCompressionTime(src,
+ &srcRect,
+ colorDepth,
+ cType,
+ codec,
+ &spatialQuality,
+ &temporalQuality,
+ &compressTime);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("lll",
+ spatialQuality,
+ temporalQuality,
+ compressTime);
+ return _res;
}
static PyObject *Qt_CompressImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle src;
- Rect srcRect;
- CodecQ quality;
- CodecType cType;
- ImageDescriptionHandle desc;
- Ptr data;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle src;
+ Rect srcRect;
+ CodecQ quality;
+ CodecType cType;
+ ImageDescriptionHandle desc;
+ Ptr data;
#ifndef CompressImage
- PyMac_PRECHECK(CompressImage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lO&O&s",
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect,
- &quality,
- PyMac_GetOSType, &cType,
- ResObj_Convert, &desc,
- &data))
- return NULL;
- _err = CompressImage(src,
- &srcRect,
- quality,
- cType,
- desc,
- data);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CompressImage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lO&O&s",
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect,
+ &quality,
+ PyMac_GetOSType, &cType,
+ ResObj_Convert, &desc,
+ &data))
+ return NULL;
+ _err = CompressImage(src,
+ &srcRect,
+ quality,
+ cType,
+ desc,
+ data);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_DecompressImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Ptr data;
- ImageDescriptionHandle desc;
- PixMapHandle dst;
- Rect srcRect;
- Rect dstRect;
- short mode;
- RgnHandle mask;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Ptr data;
+ ImageDescriptionHandle desc;
+ PixMapHandle dst;
+ Rect srcRect;
+ Rect dstRect;
+ short mode;
+ RgnHandle mask;
#ifndef DecompressImage
- PyMac_PRECHECK(DecompressImage);
-#endif
- if (!PyArg_ParseTuple(_args, "sO&O&O&O&hO&",
- &data,
- ResObj_Convert, &desc,
- ResObj_Convert, &dst,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect,
- &mode,
- ResObj_Convert, &mask))
- return NULL;
- _err = DecompressImage(data,
- desc,
- dst,
- &srcRect,
- &dstRect,
- mode,
- mask);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DecompressImage);
+#endif
+ if (!PyArg_ParseTuple(_args, "sO&O&O&O&hO&",
+ &data,
+ ResObj_Convert, &desc,
+ ResObj_Convert, &dst,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect,
+ &mode,
+ ResObj_Convert, &mask))
+ return NULL;
+ _err = DecompressImage(data,
+ desc,
+ dst,
+ &srcRect,
+ &dstRect,
+ mode,
+ mask);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetSimilarity(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle src;
- Rect srcRect;
- ImageDescriptionHandle desc;
- Ptr data;
- Fixed similarity;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle src;
+ Rect srcRect;
+ ImageDescriptionHandle desc;
+ Ptr data;
+ Fixed similarity;
#ifndef GetSimilarity
- PyMac_PRECHECK(GetSimilarity);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&s",
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect,
- ResObj_Convert, &desc,
- &data))
- return NULL;
- _err = GetSimilarity(src,
- &srcRect,
- desc,
- data,
- &similarity);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, similarity);
- return _res;
+ PyMac_PRECHECK(GetSimilarity);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&s",
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect,
+ ResObj_Convert, &desc,
+ &data))
+ return NULL;
+ _err = GetSimilarity(src,
+ &srcRect,
+ desc,
+ data,
+ &similarity);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, similarity);
+ return _res;
}
static PyObject *Qt_GetImageDescriptionCTable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- CTabHandle ctable;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ CTabHandle ctable;
#ifndef GetImageDescriptionCTable
- PyMac_PRECHECK(GetImageDescriptionCTable);
+ PyMac_PRECHECK(GetImageDescriptionCTable);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &desc))
- return NULL;
- _err = GetImageDescriptionCTable(desc,
- &ctable);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, ctable);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &desc))
+ return NULL;
+ _err = GetImageDescriptionCTable(desc,
+ &ctable);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, ctable);
+ return _res;
}
static PyObject *Qt_SetImageDescriptionCTable(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- CTabHandle ctable;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ CTabHandle ctable;
#ifndef SetImageDescriptionCTable
- PyMac_PRECHECK(SetImageDescriptionCTable);
+ PyMac_PRECHECK(SetImageDescriptionCTable);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &desc,
- ResObj_Convert, &ctable))
- return NULL;
- _err = SetImageDescriptionCTable(desc,
- ctable);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &desc,
+ ResObj_Convert, &ctable))
+ return NULL;
+ _err = SetImageDescriptionCTable(desc,
+ ctable);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetImageDescriptionExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- Handle extension;
- long idType;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ Handle extension;
+ long idType;
+ long index;
#ifndef GetImageDescriptionExtension
- PyMac_PRECHECK(GetImageDescriptionExtension);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- ResObj_Convert, &desc,
- &idType,
- &index))
- return NULL;
- _err = GetImageDescriptionExtension(desc,
- &extension,
- idType,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, extension);
- return _res;
+ PyMac_PRECHECK(GetImageDescriptionExtension);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ ResObj_Convert, &desc,
+ &idType,
+ &index))
+ return NULL;
+ _err = GetImageDescriptionExtension(desc,
+ &extension,
+ idType,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, extension);
+ return _res;
}
static PyObject *Qt_AddImageDescriptionExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- Handle extension;
- long idType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ Handle extension;
+ long idType;
#ifndef AddImageDescriptionExtension
- PyMac_PRECHECK(AddImageDescriptionExtension);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- ResObj_Convert, &desc,
- ResObj_Convert, &extension,
- &idType))
- return NULL;
- _err = AddImageDescriptionExtension(desc,
- extension,
- idType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(AddImageDescriptionExtension);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ ResObj_Convert, &desc,
+ ResObj_Convert, &extension,
+ &idType))
+ return NULL;
+ _err = AddImageDescriptionExtension(desc,
+ extension,
+ idType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_RemoveImageDescriptionExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- long idType;
- long index;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ long idType;
+ long index;
#ifndef RemoveImageDescriptionExtension
- PyMac_PRECHECK(RemoveImageDescriptionExtension);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- ResObj_Convert, &desc,
- &idType,
- &index))
- return NULL;
- _err = RemoveImageDescriptionExtension(desc,
- idType,
- index);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(RemoveImageDescriptionExtension);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ ResObj_Convert, &desc,
+ &idType,
+ &index))
+ return NULL;
+ _err = RemoveImageDescriptionExtension(desc,
+ idType,
+ index);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_CountImageDescriptionExtensionType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- long idType;
- long count;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ long idType;
+ long count;
#ifndef CountImageDescriptionExtensionType
- PyMac_PRECHECK(CountImageDescriptionExtensionType);
+ PyMac_PRECHECK(CountImageDescriptionExtensionType);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- ResObj_Convert, &desc,
- &idType))
- return NULL;
- _err = CountImageDescriptionExtensionType(desc,
- idType,
- &count);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- count);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ResObj_Convert, &desc,
+ &idType))
+ return NULL;
+ _err = CountImageDescriptionExtensionType(desc,
+ idType,
+ &count);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ count);
+ return _res;
}
static PyObject *Qt_GetNextImageDescriptionExtensionType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle desc;
- long idType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle desc;
+ long idType;
#ifndef GetNextImageDescriptionExtensionType
- PyMac_PRECHECK(GetNextImageDescriptionExtensionType);
+ PyMac_PRECHECK(GetNextImageDescriptionExtensionType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &desc))
- return NULL;
- _err = GetNextImageDescriptionExtensionType(desc,
- &idType);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- idType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &desc))
+ return NULL;
+ _err = GetNextImageDescriptionExtensionType(desc,
+ &idType);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ idType);
+ return _res;
}
static PyObject *Qt_FindCodec(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- CodecType cType;
- CodecComponent specCodec;
- CompressorComponent compressor;
- DecompressorComponent decompressor;
+ PyObject *_res = NULL;
+ OSErr _err;
+ CodecType cType;
+ CodecComponent specCodec;
+ CompressorComponent compressor;
+ DecompressorComponent decompressor;
#ifndef FindCodec
- PyMac_PRECHECK(FindCodec);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &cType,
- CmpObj_Convert, &specCodec))
- return NULL;
- _err = FindCodec(cType,
- specCodec,
- &compressor,
- &decompressor);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- CmpObj_New, compressor,
- CmpObj_New, decompressor);
- return _res;
+ PyMac_PRECHECK(FindCodec);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &cType,
+ CmpObj_Convert, &specCodec))
+ return NULL;
+ _err = FindCodec(cType,
+ specCodec,
+ &compressor,
+ &decompressor);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ CmpObj_New, compressor,
+ CmpObj_New, decompressor);
+ return _res;
}
static PyObject *Qt_CompressPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PicHandle srcPicture;
- PicHandle dstPicture;
- CodecQ quality;
- CodecType cType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PicHandle srcPicture;
+ PicHandle dstPicture;
+ CodecQ quality;
+ CodecType cType;
#ifndef CompressPicture
- PyMac_PRECHECK(CompressPicture);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lO&",
- ResObj_Convert, &srcPicture,
- ResObj_Convert, &dstPicture,
- &quality,
- PyMac_GetOSType, &cType))
- return NULL;
- _err = CompressPicture(srcPicture,
- dstPicture,
- quality,
- cType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CompressPicture);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lO&",
+ ResObj_Convert, &srcPicture,
+ ResObj_Convert, &dstPicture,
+ &quality,
+ PyMac_GetOSType, &cType))
+ return NULL;
+ _err = CompressPicture(srcPicture,
+ dstPicture,
+ quality,
+ cType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_CompressPictureFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short srcRefNum;
- short dstRefNum;
- CodecQ quality;
- CodecType cType;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short srcRefNum;
+ short dstRefNum;
+ CodecQ quality;
+ CodecType cType;
#ifndef CompressPictureFile
- PyMac_PRECHECK(CompressPictureFile);
-#endif
- if (!PyArg_ParseTuple(_args, "hhlO&",
- &srcRefNum,
- &dstRefNum,
- &quality,
- PyMac_GetOSType, &cType))
- return NULL;
- _err = CompressPictureFile(srcRefNum,
- dstRefNum,
- quality,
- cType);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(CompressPictureFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhlO&",
+ &srcRefNum,
+ &dstRefNum,
+ &quality,
+ PyMac_GetOSType, &cType))
+ return NULL;
+ _err = CompressPictureFile(srcRefNum,
+ dstRefNum,
+ quality,
+ cType);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_ConvertImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- ImageDescriptionHandle srcDD;
- Ptr srcData;
- short colorDepth;
- CTabHandle ctable;
- CodecQ accuracy;
- CodecQ quality;
- CodecType cType;
- CodecComponent codec;
- ImageDescriptionHandle dstDD;
- Ptr dstData;
+ PyObject *_res = NULL;
+ OSErr _err;
+ ImageDescriptionHandle srcDD;
+ Ptr srcData;
+ short colorDepth;
+ CTabHandle ctable;
+ CodecQ accuracy;
+ CodecQ quality;
+ CodecType cType;
+ CodecComponent codec;
+ ImageDescriptionHandle dstDD;
+ Ptr dstData;
#ifndef ConvertImage
- PyMac_PRECHECK(ConvertImage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&shO&llO&O&O&s",
- ResObj_Convert, &srcDD,
- &srcData,
- &colorDepth,
- ResObj_Convert, &ctable,
- &accuracy,
- &quality,
- PyMac_GetOSType, &cType,
- CmpObj_Convert, &codec,
- ResObj_Convert, &dstDD,
- &dstData))
- return NULL;
- _err = ConvertImage(srcDD,
- srcData,
- colorDepth,
- ctable,
- accuracy,
- quality,
- cType,
- codec,
- dstDD,
- dstData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ConvertImage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&shO&llO&O&O&s",
+ ResObj_Convert, &srcDD,
+ &srcData,
+ &colorDepth,
+ ResObj_Convert, &ctable,
+ &accuracy,
+ &quality,
+ PyMac_GetOSType, &cType,
+ CmpObj_Convert, &codec,
+ ResObj_Convert, &dstDD,
+ &dstData))
+ return NULL;
+ _err = ConvertImage(srcDD,
+ srcData,
+ colorDepth,
+ ctable,
+ accuracy,
+ quality,
+ cType,
+ codec,
+ dstDD,
+ dstData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_AddFilePreview(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short resRefNum;
- OSType previewType;
- Handle previewData;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short resRefNum;
+ OSType previewType;
+ Handle previewData;
#ifndef AddFilePreview
- PyMac_PRECHECK(AddFilePreview);
-#endif
- if (!PyArg_ParseTuple(_args, "hO&O&",
- &resRefNum,
- PyMac_GetOSType, &previewType,
- ResObj_Convert, &previewData))
- return NULL;
- _err = AddFilePreview(resRefNum,
- previewType,
- previewData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(AddFilePreview);
+#endif
+ if (!PyArg_ParseTuple(_args, "hO&O&",
+ &resRefNum,
+ PyMac_GetOSType, &previewType,
+ ResObj_Convert, &previewData))
+ return NULL;
+ _err = AddFilePreview(resRefNum,
+ previewType,
+ previewData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetBestDeviceRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- GDHandle gdh;
- Rect rp;
+ PyObject *_res = NULL;
+ OSErr _err;
+ GDHandle gdh;
+ Rect rp;
#ifndef GetBestDeviceRect
- PyMac_PRECHECK(GetBestDeviceRect);
+ PyMac_PRECHECK(GetBestDeviceRect);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetBestDeviceRect(&gdh,
- &rp);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- OptResObj_New, gdh,
- PyMac_BuildRect, &rp);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetBestDeviceRect(&gdh,
+ &rp);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ OptResObj_New, gdh,
+ PyMac_BuildRect, &rp);
+ return _res;
}
static PyObject *Qt_GDHasScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- GDHandle gdh;
- short depth;
- Fixed scale;
+ PyObject *_res = NULL;
+ OSErr _err;
+ GDHandle gdh;
+ short depth;
+ Fixed scale;
#ifndef GDHasScale
- PyMac_PRECHECK(GDHasScale);
+ PyMac_PRECHECK(GDHasScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- OptResObj_Convert, &gdh,
- &depth))
- return NULL;
- _err = GDHasScale(gdh,
- depth,
- &scale);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, scale);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ OptResObj_Convert, &gdh,
+ &depth))
+ return NULL;
+ _err = GDHasScale(gdh,
+ depth,
+ &scale);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, scale);
+ return _res;
}
static PyObject *Qt_GDGetScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- GDHandle gdh;
- Fixed scale;
- short flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ GDHandle gdh;
+ Fixed scale;
+ short flags;
#ifndef GDGetScale
- PyMac_PRECHECK(GDGetScale);
+ PyMac_PRECHECK(GDGetScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- OptResObj_Convert, &gdh))
- return NULL;
- _err = GDGetScale(gdh,
- &scale,
- &flags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- PyMac_BuildFixed, scale,
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ OptResObj_Convert, &gdh))
+ return NULL;
+ _err = GDGetScale(gdh,
+ &scale,
+ &flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ PyMac_BuildFixed, scale,
+ flags);
+ return _res;
}
static PyObject *Qt_GDSetScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- GDHandle gdh;
- Fixed scale;
- short flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ GDHandle gdh;
+ Fixed scale;
+ short flags;
#ifndef GDSetScale
- PyMac_PRECHECK(GDSetScale);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- OptResObj_Convert, &gdh,
- PyMac_GetFixed, &scale,
- &flags))
- return NULL;
- _err = GDSetScale(gdh,
- scale,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(GDSetScale);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ OptResObj_Convert, &gdh,
+ PyMac_GetFixed, &scale,
+ &flags))
+ return NULL;
+ _err = GDSetScale(gdh,
+ scale,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_GetGraphicsImporterForFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec theFile;
- ComponentInstance gi;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec theFile;
+ ComponentInstance gi;
#ifndef GetGraphicsImporterForFile
- PyMac_PRECHECK(GetGraphicsImporterForFile);
+ PyMac_PRECHECK(GetGraphicsImporterForFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _err = GetGraphicsImporterForFile(&theFile,
- &gi);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, gi);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _err = GetGraphicsImporterForFile(&theFile,
+ &gi);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, gi);
+ return _res;
}
static PyObject *Qt_GetGraphicsImporterForDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
- ComponentInstance gi;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
+ ComponentInstance gi;
#ifndef GetGraphicsImporterForDataRef
- PyMac_PRECHECK(GetGraphicsImporterForDataRef);
+ PyMac_PRECHECK(GetGraphicsImporterForDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _err = GetGraphicsImporterForDataRef(dataRef,
- dataRefType,
- &gi);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, gi);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _err = GetGraphicsImporterForDataRef(dataRef,
+ dataRefType,
+ &gi);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, gi);
+ return _res;
}
static PyObject *Qt_GetGraphicsImporterForFileWithFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec theFile;
- ComponentInstance gi;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec theFile;
+ ComponentInstance gi;
+ long flags;
#ifndef GetGraphicsImporterForFileWithFlags
- PyMac_PRECHECK(GetGraphicsImporterForFileWithFlags);
+ PyMac_PRECHECK(GetGraphicsImporterForFileWithFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetFSSpec, &theFile,
- &flags))
- return NULL;
- _err = GetGraphicsImporterForFileWithFlags(&theFile,
- &gi,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, gi);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetFSSpec, &theFile,
+ &flags))
+ return NULL;
+ _err = GetGraphicsImporterForFileWithFlags(&theFile,
+ &gi,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, gi);
+ return _res;
}
static PyObject *Qt_GetGraphicsImporterForDataRefWithFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Handle dataRef;
- OSType dataRefType;
- ComponentInstance gi;
- long flags;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Handle dataRef;
+ OSType dataRefType;
+ ComponentInstance gi;
+ long flags;
#ifndef GetGraphicsImporterForDataRefWithFlags
- PyMac_PRECHECK(GetGraphicsImporterForDataRefWithFlags);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- &flags))
- return NULL;
- _err = GetGraphicsImporterForDataRefWithFlags(dataRef,
- dataRefType,
- &gi,
- flags);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, gi);
- return _res;
+ PyMac_PRECHECK(GetGraphicsImporterForDataRefWithFlags);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ &flags))
+ return NULL;
+ _err = GetGraphicsImporterForDataRefWithFlags(dataRef,
+ dataRefType,
+ &gi,
+ flags);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, gi);
+ return _res;
}
static PyObject *Qt_MakeImageDescriptionForPixMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle pixmap;
- ImageDescriptionHandle idh;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle pixmap;
+ ImageDescriptionHandle idh;
#ifndef MakeImageDescriptionForPixMap
- PyMac_PRECHECK(MakeImageDescriptionForPixMap);
+ PyMac_PRECHECK(MakeImageDescriptionForPixMap);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pixmap))
- return NULL;
- _err = MakeImageDescriptionForPixMap(pixmap,
- &idh);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, idh);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pixmap))
+ return NULL;
+ _err = MakeImageDescriptionForPixMap(pixmap,
+ &idh);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, idh);
+ return _res;
}
static PyObject *Qt_MakeImageDescriptionForEffect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType effectType;
- ImageDescriptionHandle idh;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType effectType;
+ ImageDescriptionHandle idh;
#ifndef MakeImageDescriptionForEffect
- PyMac_PRECHECK(MakeImageDescriptionForEffect);
+ PyMac_PRECHECK(MakeImageDescriptionForEffect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &effectType))
- return NULL;
- _err = MakeImageDescriptionForEffect(effectType,
- &idh);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, idh);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &effectType))
+ return NULL;
+ _err = MakeImageDescriptionForEffect(effectType,
+ &idh);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, idh);
+ return _res;
}
static PyObject *Qt_QTGetPixelSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- OSType PixelFormat;
+ PyObject *_res = NULL;
+ short _rv;
+ OSType PixelFormat;
#ifndef QTGetPixelSize
- PyMac_PRECHECK(QTGetPixelSize);
+ PyMac_PRECHECK(QTGetPixelSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &PixelFormat))
- return NULL;
- _rv = QTGetPixelSize(PixelFormat);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &PixelFormat))
+ return NULL;
+ _rv = QTGetPixelSize(PixelFormat);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTGetPixelFormatDepthForImageDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- OSType PixelFormat;
+ PyObject *_res = NULL;
+ short _rv;
+ OSType PixelFormat;
#ifndef QTGetPixelFormatDepthForImageDescription
- PyMac_PRECHECK(QTGetPixelFormatDepthForImageDescription);
+ PyMac_PRECHECK(QTGetPixelFormatDepthForImageDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &PixelFormat))
- return NULL;
- _rv = QTGetPixelFormatDepthForImageDescription(PixelFormat);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &PixelFormat))
+ return NULL;
+ _rv = QTGetPixelFormatDepthForImageDescription(PixelFormat);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTGetPixMapHandleRowBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ long _rv;
+ PixMapHandle pm;
#ifndef QTGetPixMapHandleRowBytes
- PyMac_PRECHECK(QTGetPixMapHandleRowBytes);
+ PyMac_PRECHECK(QTGetPixMapHandleRowBytes);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- _rv = QTGetPixMapHandleRowBytes(pm);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ _rv = QTGetPixMapHandleRowBytes(pm);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTSetPixMapHandleRowBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle pm;
- long rowBytes;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle pm;
+ long rowBytes;
#ifndef QTSetPixMapHandleRowBytes
- PyMac_PRECHECK(QTSetPixMapHandleRowBytes);
+ PyMac_PRECHECK(QTSetPixMapHandleRowBytes);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- ResObj_Convert, &pm,
- &rowBytes))
- return NULL;
- _err = QTSetPixMapHandleRowBytes(pm,
- rowBytes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ ResObj_Convert, &pm,
+ &rowBytes))
+ return NULL;
+ _err = QTSetPixMapHandleRowBytes(pm,
+ rowBytes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTGetPixMapHandleGammaLevel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ PixMapHandle pm;
#ifndef QTGetPixMapHandleGammaLevel
- PyMac_PRECHECK(QTGetPixMapHandleGammaLevel);
+ PyMac_PRECHECK(QTGetPixMapHandleGammaLevel);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- _rv = QTGetPixMapHandleGammaLevel(pm);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ _rv = QTGetPixMapHandleGammaLevel(pm);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_QTSetPixMapHandleGammaLevel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle pm;
- Fixed gammaLevel;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle pm;
+ Fixed gammaLevel;
#ifndef QTSetPixMapHandleGammaLevel
- PyMac_PRECHECK(QTSetPixMapHandleGammaLevel);
+ PyMac_PRECHECK(QTSetPixMapHandleGammaLevel);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &pm,
- PyMac_GetFixed, &gammaLevel))
- return NULL;
- _err = QTSetPixMapHandleGammaLevel(pm,
- gammaLevel);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &pm,
+ PyMac_GetFixed, &gammaLevel))
+ return NULL;
+ _err = QTSetPixMapHandleGammaLevel(pm,
+ gammaLevel);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_QTGetPixMapHandleRequestedGammaLevel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- PixMapHandle pm;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ PixMapHandle pm;
#ifndef QTGetPixMapHandleRequestedGammaLevel
- PyMac_PRECHECK(QTGetPixMapHandleRequestedGammaLevel);
+ PyMac_PRECHECK(QTGetPixMapHandleRequestedGammaLevel);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pm))
- return NULL;
- _rv = QTGetPixMapHandleRequestedGammaLevel(pm);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pm))
+ return NULL;
+ _rv = QTGetPixMapHandleRequestedGammaLevel(pm);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_QTSetPixMapHandleRequestedGammaLevel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- PixMapHandle pm;
- Fixed requestedGammaLevel;
+ PyObject *_res = NULL;
+ OSErr _err;
+ PixMapHandle pm;
+ Fixed requestedGammaLevel;
#ifndef QTSetPixMapHandleRequestedGammaLevel
- PyMac_PRECHECK(QTSetPixMapHandleRequestedGammaLevel);
+ PyMac_PRECHECK(QTSetPixMapHandleRequestedGammaLevel);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- ResObj_Convert, &pm,
- PyMac_GetFixed, &requestedGammaLevel))
- return NULL;
- _err = QTSetPixMapHandleRequestedGammaLevel(pm,
- requestedGammaLevel);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ ResObj_Convert, &pm,
+ PyMac_GetFixed, &requestedGammaLevel))
+ return NULL;
+ _err = QTSetPixMapHandleRequestedGammaLevel(pm,
+ requestedGammaLevel);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_CompAdd(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide src;
- wide dst;
+ PyObject *_res = NULL;
+ wide src;
+ wide dst;
#ifndef CompAdd
- PyMac_PRECHECK(CompAdd);
+ PyMac_PRECHECK(CompAdd);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CompAdd(&src,
- &dst);
- _res = Py_BuildValue("O&O&",
- PyMac_Buildwide, src,
- PyMac_Buildwide, dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CompAdd(&src,
+ &dst);
+ _res = Py_BuildValue("O&O&",
+ PyMac_Buildwide, src,
+ PyMac_Buildwide, dst);
+ return _res;
}
static PyObject *Qt_CompSub(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide src;
- wide dst;
+ PyObject *_res = NULL;
+ wide src;
+ wide dst;
#ifndef CompSub
- PyMac_PRECHECK(CompSub);
+ PyMac_PRECHECK(CompSub);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CompSub(&src,
- &dst);
- _res = Py_BuildValue("O&O&",
- PyMac_Buildwide, src,
- PyMac_Buildwide, dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CompSub(&src,
+ &dst);
+ _res = Py_BuildValue("O&O&",
+ PyMac_Buildwide, src,
+ PyMac_Buildwide, dst);
+ return _res;
}
static PyObject *Qt_CompNeg(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide dst;
+ PyObject *_res = NULL;
+ wide dst;
#ifndef CompNeg
- PyMac_PRECHECK(CompNeg);
+ PyMac_PRECHECK(CompNeg);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CompNeg(&dst);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CompNeg(&dst);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, dst);
+ return _res;
}
static PyObject *Qt_CompShift(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide src;
- short shift;
+ PyObject *_res = NULL;
+ wide src;
+ short shift;
#ifndef CompShift
- PyMac_PRECHECK(CompShift);
+ PyMac_PRECHECK(CompShift);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &shift))
- return NULL;
- CompShift(&src,
- shift);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, src);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &shift))
+ return NULL;
+ CompShift(&src,
+ shift);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, src);
+ return _res;
}
static PyObject *Qt_CompMul(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long src1;
- long src2;
- wide dst;
+ PyObject *_res = NULL;
+ long src1;
+ long src2;
+ wide dst;
#ifndef CompMul
- PyMac_PRECHECK(CompMul);
+ PyMac_PRECHECK(CompMul);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &src1,
- &src2))
- return NULL;
- CompMul(src1,
- src2,
- &dst);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, dst);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &src1,
+ &src2))
+ return NULL;
+ CompMul(src1,
+ src2,
+ &dst);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, dst);
+ return _res;
}
static PyObject *Qt_CompDiv(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- wide numerator;
- long denominator;
- long remainder;
+ PyObject *_res = NULL;
+ long _rv;
+ wide numerator;
+ long denominator;
+ long remainder;
#ifndef CompDiv
- PyMac_PRECHECK(CompDiv);
+ PyMac_PRECHECK(CompDiv);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &denominator))
- return NULL;
- _rv = CompDiv(&numerator,
- denominator,
- &remainder);
- _res = Py_BuildValue("lO&l",
- _rv,
- PyMac_Buildwide, numerator,
- remainder);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &denominator))
+ return NULL;
+ _rv = CompDiv(&numerator,
+ denominator,
+ &remainder);
+ _res = Py_BuildValue("lO&l",
+ _rv,
+ PyMac_Buildwide, numerator,
+ remainder);
+ return _res;
}
static PyObject *Qt_CompFixMul(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide compSrc;
- Fixed fixSrc;
- wide compDst;
+ PyObject *_res = NULL;
+ wide compSrc;
+ Fixed fixSrc;
+ wide compDst;
#ifndef CompFixMul
- PyMac_PRECHECK(CompFixMul);
+ PyMac_PRECHECK(CompFixMul);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &fixSrc))
- return NULL;
- CompFixMul(&compSrc,
- fixSrc,
- &compDst);
- _res = Py_BuildValue("O&O&",
- PyMac_Buildwide, compSrc,
- PyMac_Buildwide, compDst);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &fixSrc))
+ return NULL;
+ CompFixMul(&compSrc,
+ fixSrc,
+ &compDst);
+ _res = Py_BuildValue("O&O&",
+ PyMac_Buildwide, compSrc,
+ PyMac_Buildwide, compDst);
+ return _res;
}
static PyObject *Qt_CompMulDiv(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide co;
- long mul;
- long divisor;
+ PyObject *_res = NULL;
+ wide co;
+ long mul;
+ long divisor;
#ifndef CompMulDiv
- PyMac_PRECHECK(CompMulDiv);
+ PyMac_PRECHECK(CompMulDiv);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &mul,
- &divisor))
- return NULL;
- CompMulDiv(&co,
- mul,
- divisor);
- _res = Py_BuildValue("O&",
- PyMac_Buildwide, co);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &mul,
+ &divisor))
+ return NULL;
+ CompMulDiv(&co,
+ mul,
+ divisor);
+ _res = Py_BuildValue("O&",
+ PyMac_Buildwide, co);
+ return _res;
}
static PyObject *Qt_CompMulDivTrunc(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- wide co;
- long mul;
- long divisor;
- long remainder;
+ PyObject *_res = NULL;
+ wide co;
+ long mul;
+ long divisor;
+ long remainder;
#ifndef CompMulDivTrunc
- PyMac_PRECHECK(CompMulDivTrunc);
-#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &mul,
- &divisor))
- return NULL;
- CompMulDivTrunc(&co,
- mul,
- divisor,
- &remainder);
- _res = Py_BuildValue("O&l",
- PyMac_Buildwide, co,
- remainder);
- return _res;
+ PyMac_PRECHECK(CompMulDivTrunc);
+#endif
+ if (!PyArg_ParseTuple(_args, "ll",
+ &mul,
+ &divisor))
+ return NULL;
+ CompMulDivTrunc(&co,
+ mul,
+ divisor,
+ &remainder);
+ _res = Py_BuildValue("O&l",
+ PyMac_Buildwide, co,
+ remainder);
+ return _res;
}
static PyObject *Qt_CompCompare(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- wide a;
- wide minusb;
+ PyObject *_res = NULL;
+ long _rv;
+ wide a;
+ wide minusb;
#ifndef CompCompare
- PyMac_PRECHECK(CompCompare);
+ PyMac_PRECHECK(CompCompare);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_Getwide, &a,
- PyMac_Getwide, &minusb))
- return NULL;
- _rv = CompCompare(&a,
- &minusb);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_Getwide, &a,
+ PyMac_Getwide, &minusb))
+ return NULL;
+ _rv = CompCompare(&a,
+ &minusb);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_CompSquareRoot(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- unsigned long _rv;
- wide src;
+ PyObject *_res = NULL;
+ unsigned long _rv;
+ wide src;
#ifndef CompSquareRoot
- PyMac_PRECHECK(CompSquareRoot);
+ PyMac_PRECHECK(CompSquareRoot);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_Getwide, &src))
- return NULL;
- _rv = CompSquareRoot(&src);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_Getwide, &src))
+ return NULL;
+ _rv = CompSquareRoot(&src);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_FixMulDiv(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- Fixed src;
- Fixed mul;
- Fixed divisor;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ Fixed src;
+ Fixed mul;
+ Fixed divisor;
#ifndef FixMulDiv
- PyMac_PRECHECK(FixMulDiv);
+ PyMac_PRECHECK(FixMulDiv);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetFixed, &src,
- PyMac_GetFixed, &mul,
- PyMac_GetFixed, &divisor))
- return NULL;
- _rv = FixMulDiv(src,
- mul,
- divisor);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetFixed, &src,
+ PyMac_GetFixed, &mul,
+ PyMac_GetFixed, &divisor))
+ return NULL;
+ _rv = FixMulDiv(src,
+ mul,
+ divisor);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_UnsignedFixMulDiv(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- Fixed src;
- Fixed mul;
- Fixed divisor;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ Fixed src;
+ Fixed mul;
+ Fixed divisor;
#ifndef UnsignedFixMulDiv
- PyMac_PRECHECK(UnsignedFixMulDiv);
+ PyMac_PRECHECK(UnsignedFixMulDiv);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetFixed, &src,
- PyMac_GetFixed, &mul,
- PyMac_GetFixed, &divisor))
- return NULL;
- _rv = UnsignedFixMulDiv(src,
- mul,
- divisor);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetFixed, &src,
+ PyMac_GetFixed, &mul,
+ PyMac_GetFixed, &divisor))
+ return NULL;
+ _rv = UnsignedFixMulDiv(src,
+ mul,
+ divisor);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_FixExp2(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- Fixed src;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ Fixed src;
#ifndef FixExp2
- PyMac_PRECHECK(FixExp2);
+ PyMac_PRECHECK(FixExp2);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &src))
- return NULL;
- _rv = FixExp2(src);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &src))
+ return NULL;
+ _rv = FixExp2(src);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_FixLog2(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- Fixed src;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ Fixed src;
#ifndef FixLog2
- PyMac_PRECHECK(FixLog2);
+ PyMac_PRECHECK(FixLog2);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFixed, &src))
- return NULL;
- _rv = FixLog2(src);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFixed, &src))
+ return NULL;
+ _rv = FixLog2(src);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_FixPow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- Fixed base;
- Fixed exp;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ Fixed base;
+ Fixed exp;
#ifndef FixPow
- PyMac_PRECHECK(FixPow);
+ PyMac_PRECHECK(FixPow);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetFixed, &base,
- PyMac_GetFixed, &exp))
- return NULL;
- _rv = FixPow(base,
- exp);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetFixed, &base,
+ PyMac_GetFixed, &exp))
+ return NULL;
+ _rv = FixPow(base,
+ exp);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Handle dataRef;
- OSType dataReType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Handle dataRef;
+ OSType dataReType;
#ifndef GraphicsImportSetDataReference
- PyMac_PRECHECK(GraphicsImportSetDataReference);
+ PyMac_PRECHECK(GraphicsImportSetDataReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataReType))
- return NULL;
- _rv = GraphicsImportSetDataReference(ci,
- dataRef,
- dataReType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataReType))
+ return NULL;
+ _rv = GraphicsImportSetDataReference(ci,
+ dataRef,
+ dataReType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Handle dataRef;
- OSType dataReType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Handle dataRef;
+ OSType dataReType;
#ifndef GraphicsImportGetDataReference
- PyMac_PRECHECK(GraphicsImportGetDataReference);
+ PyMac_PRECHECK(GraphicsImportGetDataReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDataReference(ci,
- &dataRef,
- &dataReType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataReType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDataReference(ci,
+ &dataRef,
+ &dataReType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataReType);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetDataFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- FSSpec theFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ FSSpec theFile;
#ifndef GraphicsImportSetDataFile
- PyMac_PRECHECK(GraphicsImportSetDataFile);
+ PyMac_PRECHECK(GraphicsImportSetDataFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _rv = GraphicsImportSetDataFile(ci,
- &theFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _rv = GraphicsImportSetDataFile(ci,
+ &theFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- FSSpec theFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ FSSpec theFile;
#ifndef GraphicsImportGetDataFile
- PyMac_PRECHECK(GraphicsImportGetDataFile);
+ PyMac_PRECHECK(GraphicsImportGetDataFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _rv = GraphicsImportGetDataFile(ci,
- &theFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _rv = GraphicsImportGetDataFile(ci,
+ &theFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetDataHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Handle h;
#ifndef GraphicsImportSetDataHandle
- PyMac_PRECHECK(GraphicsImportSetDataHandle);
+ PyMac_PRECHECK(GraphicsImportSetDataHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &h))
- return NULL;
- _rv = GraphicsImportSetDataHandle(ci,
- h);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = GraphicsImportSetDataHandle(ci,
+ h);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Handle h;
#ifndef GraphicsImportGetDataHandle
- PyMac_PRECHECK(GraphicsImportGetDataHandle);
+ PyMac_PRECHECK(GraphicsImportGetDataHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDataHandle(ci,
- &h);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, h);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDataHandle(ci,
+ &h);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, h);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetImageDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ ImageDescriptionHandle desc;
#ifndef GraphicsImportGetImageDescription
- PyMac_PRECHECK(GraphicsImportGetImageDescription);
+ PyMac_PRECHECK(GraphicsImportGetImageDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetImageDescription(ci,
- &desc);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, desc);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetImageDescription(ci,
+ &desc);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, desc);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataOffsetAndSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- unsigned long offset;
- unsigned long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ unsigned long offset;
+ unsigned long size;
#ifndef GraphicsImportGetDataOffsetAndSize
- PyMac_PRECHECK(GraphicsImportGetDataOffsetAndSize);
+ PyMac_PRECHECK(GraphicsImportGetDataOffsetAndSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDataOffsetAndSize(ci,
- &offset,
- &size);
- _res = Py_BuildValue("lll",
- _rv,
- offset,
- size);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDataOffsetAndSize(ci,
+ &offset,
+ &size);
+ _res = Py_BuildValue("lll",
+ _rv,
+ offset,
+ size);
+ return _res;
}
static PyObject *Qt_GraphicsImportReadData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * dataPtr;
- unsigned long dataOffset;
- unsigned long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * dataPtr;
+ unsigned long dataOffset;
+ unsigned long dataSize;
#ifndef GraphicsImportReadData
- PyMac_PRECHECK(GraphicsImportReadData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&sll",
- CmpInstObj_Convert, &ci,
- &dataPtr,
- &dataOffset,
- &dataSize))
- return NULL;
- _rv = GraphicsImportReadData(ci,
- dataPtr,
- dataOffset,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsImportReadData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&sll",
+ CmpInstObj_Convert, &ci,
+ &dataPtr,
+ &dataOffset,
+ &dataSize))
+ return NULL;
+ _rv = GraphicsImportReadData(ci,
+ dataPtr,
+ dataOffset,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- RgnHandle clipRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ RgnHandle clipRgn;
#ifndef GraphicsImportSetClip
- PyMac_PRECHECK(GraphicsImportSetClip);
+ PyMac_PRECHECK(GraphicsImportSetClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &clipRgn))
- return NULL;
- _rv = GraphicsImportSetClip(ci,
- clipRgn);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &clipRgn))
+ return NULL;
+ _rv = GraphicsImportSetClip(ci,
+ clipRgn);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- RgnHandle clipRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ RgnHandle clipRgn;
#ifndef GraphicsImportGetClip
- PyMac_PRECHECK(GraphicsImportGetClip);
+ PyMac_PRECHECK(GraphicsImportGetClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetClip(ci,
- &clipRgn);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, clipRgn);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetClip(ci,
+ &clipRgn);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, clipRgn);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetSourceRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect sourceRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect sourceRect;
#ifndef GraphicsImportSetSourceRect
- PyMac_PRECHECK(GraphicsImportSetSourceRect);
+ PyMac_PRECHECK(GraphicsImportSetSourceRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetRect, &sourceRect))
- return NULL;
- _rv = GraphicsImportSetSourceRect(ci,
- &sourceRect);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetRect, &sourceRect))
+ return NULL;
+ _rv = GraphicsImportSetSourceRect(ci,
+ &sourceRect);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetSourceRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect sourceRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect sourceRect;
#ifndef GraphicsImportGetSourceRect
- PyMac_PRECHECK(GraphicsImportGetSourceRect);
+ PyMac_PRECHECK(GraphicsImportGetSourceRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetSourceRect(ci,
- &sourceRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &sourceRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetSourceRect(ci,
+ &sourceRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &sourceRect);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetNaturalBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect naturalBounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect naturalBounds;
#ifndef GraphicsImportGetNaturalBounds
- PyMac_PRECHECK(GraphicsImportGetNaturalBounds);
+ PyMac_PRECHECK(GraphicsImportGetNaturalBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetNaturalBounds(ci,
- &naturalBounds);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &naturalBounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetNaturalBounds(ci,
+ &naturalBounds);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &naturalBounds);
+ return _res;
}
static PyObject *Qt_GraphicsImportDraw(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
#ifndef GraphicsImportDraw
- PyMac_PRECHECK(GraphicsImportDraw);
+ PyMac_PRECHECK(GraphicsImportDraw);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportDraw(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportDraw(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- CGrafPtr port;
- GDHandle gd;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ CGrafPtr port;
+ GDHandle gd;
#ifndef GraphicsImportSetGWorld
- PyMac_PRECHECK(GraphicsImportSetGWorld);
+ PyMac_PRECHECK(GraphicsImportSetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- GrafObj_Convert, &port,
- OptResObj_Convert, &gd))
- return NULL;
- _rv = GraphicsImportSetGWorld(ci,
- port,
- gd);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ GrafObj_Convert, &port,
+ OptResObj_Convert, &gd))
+ return NULL;
+ _rv = GraphicsImportSetGWorld(ci,
+ port,
+ gd);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- CGrafPtr port;
- GDHandle gd;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ CGrafPtr port;
+ GDHandle gd;
#ifndef GraphicsImportGetGWorld
- PyMac_PRECHECK(GraphicsImportGetGWorld);
+ PyMac_PRECHECK(GraphicsImportGetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetGWorld(ci,
- &port,
- &gd);
- _res = Py_BuildValue("lO&O&",
- _rv,
- GrafObj_New, port,
- OptResObj_New, gd);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetGWorld(ci,
+ &port,
+ &gd);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ GrafObj_New, port,
+ OptResObj_New, gd);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetBoundsRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect bounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect bounds;
#ifndef GraphicsImportSetBoundsRect
- PyMac_PRECHECK(GraphicsImportSetBoundsRect);
+ PyMac_PRECHECK(GraphicsImportSetBoundsRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetRect, &bounds))
- return NULL;
- _rv = GraphicsImportSetBoundsRect(ci,
- &bounds);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetRect, &bounds))
+ return NULL;
+ _rv = GraphicsImportSetBoundsRect(ci,
+ &bounds);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetBoundsRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect bounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect bounds;
#ifndef GraphicsImportGetBoundsRect
- PyMac_PRECHECK(GraphicsImportGetBoundsRect);
+ PyMac_PRECHECK(GraphicsImportGetBoundsRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetBoundsRect(ci,
- &bounds);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetBoundsRect(ci,
+ &bounds);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *Qt_GraphicsImportSaveAsPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- FSSpec fss;
- ScriptCode scriptTag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ FSSpec fss;
+ ScriptCode scriptTag;
#ifndef GraphicsImportSaveAsPicture
- PyMac_PRECHECK(GraphicsImportSaveAsPicture);
+ PyMac_PRECHECK(GraphicsImportSaveAsPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &fss,
- &scriptTag))
- return NULL;
- _rv = GraphicsImportSaveAsPicture(ci,
- &fss,
- scriptTag);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &fss,
+ &scriptTag))
+ return NULL;
+ _rv = GraphicsImportSaveAsPicture(ci,
+ &fss,
+ scriptTag);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetGraphicsMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- long graphicsMode;
- RGBColor opColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ long graphicsMode;
+ RGBColor opColor;
#ifndef GraphicsImportSetGraphicsMode
- PyMac_PRECHECK(GraphicsImportSetGraphicsMode);
+ PyMac_PRECHECK(GraphicsImportSetGraphicsMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &ci,
- &graphicsMode,
- QdRGB_Convert, &opColor))
- return NULL;
- _rv = GraphicsImportSetGraphicsMode(ci,
- graphicsMode,
- &opColor);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &ci,
+ &graphicsMode,
+ QdRGB_Convert, &opColor))
+ return NULL;
+ _rv = GraphicsImportSetGraphicsMode(ci,
+ graphicsMode,
+ &opColor);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetGraphicsMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- long graphicsMode;
- RGBColor opColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ long graphicsMode;
+ RGBColor opColor;
#ifndef GraphicsImportGetGraphicsMode
- PyMac_PRECHECK(GraphicsImportGetGraphicsMode);
+ PyMac_PRECHECK(GraphicsImportGetGraphicsMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetGraphicsMode(ci,
- &graphicsMode,
- &opColor);
- _res = Py_BuildValue("llO&",
- _rv,
- graphicsMode,
- QdRGB_New, &opColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetGraphicsMode(ci,
+ &graphicsMode,
+ &opColor);
+ _res = Py_BuildValue("llO&",
+ _rv,
+ graphicsMode,
+ QdRGB_New, &opColor);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetQuality(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- CodecQ quality;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ CodecQ quality;
#ifndef GraphicsImportSetQuality
- PyMac_PRECHECK(GraphicsImportSetQuality);
+ PyMac_PRECHECK(GraphicsImportSetQuality);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &quality))
- return NULL;
- _rv = GraphicsImportSetQuality(ci,
- quality);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &quality))
+ return NULL;
+ _rv = GraphicsImportSetQuality(ci,
+ quality);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetQuality(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- CodecQ quality;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ CodecQ quality;
#ifndef GraphicsImportGetQuality
- PyMac_PRECHECK(GraphicsImportGetQuality);
+ PyMac_PRECHECK(GraphicsImportGetQuality);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetQuality(ci,
- &quality);
- _res = Py_BuildValue("ll",
- _rv,
- quality);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetQuality(ci,
+ &quality);
+ _res = Py_BuildValue("ll",
+ _rv,
+ quality);
+ return _res;
}
static PyObject *Qt_GraphicsImportSaveAsQuickTimeImageFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- FSSpec fss;
- ScriptCode scriptTag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ FSSpec fss;
+ ScriptCode scriptTag;
#ifndef GraphicsImportSaveAsQuickTimeImageFile
- PyMac_PRECHECK(GraphicsImportSaveAsQuickTimeImageFile);
+ PyMac_PRECHECK(GraphicsImportSaveAsQuickTimeImageFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &fss,
- &scriptTag))
- return NULL;
- _rv = GraphicsImportSaveAsQuickTimeImageFile(ci,
- &fss,
- scriptTag);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &fss,
+ &scriptTag))
+ return NULL;
+ _rv = GraphicsImportSaveAsQuickTimeImageFile(ci,
+ &fss,
+ scriptTag);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetDataReferenceOffsetAndLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- unsigned long offset;
- unsigned long limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ unsigned long offset;
+ unsigned long limit;
#ifndef GraphicsImportSetDataReferenceOffsetAndLimit
- PyMac_PRECHECK(GraphicsImportSetDataReferenceOffsetAndLimit);
+ PyMac_PRECHECK(GraphicsImportSetDataReferenceOffsetAndLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &ci,
- &offset,
- &limit))
- return NULL;
- _rv = GraphicsImportSetDataReferenceOffsetAndLimit(ci,
- offset,
- limit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &ci,
+ &offset,
+ &limit))
+ return NULL;
+ _rv = GraphicsImportSetDataReferenceOffsetAndLimit(ci,
+ offset,
+ limit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataReferenceOffsetAndLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- unsigned long offset;
- unsigned long limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ unsigned long offset;
+ unsigned long limit;
#ifndef GraphicsImportGetDataReferenceOffsetAndLimit
- PyMac_PRECHECK(GraphicsImportGetDataReferenceOffsetAndLimit);
+ PyMac_PRECHECK(GraphicsImportGetDataReferenceOffsetAndLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDataReferenceOffsetAndLimit(ci,
- &offset,
- &limit);
- _res = Py_BuildValue("lll",
- _rv,
- offset,
- limit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDataReferenceOffsetAndLimit(ci,
+ &offset,
+ &limit);
+ _res = Py_BuildValue("lll",
+ _rv,
+ offset,
+ limit);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetAliasedDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef GraphicsImportGetAliasedDataReference
- PyMac_PRECHECK(GraphicsImportGetAliasedDataReference);
+ PyMac_PRECHECK(GraphicsImportGetAliasedDataReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetAliasedDataReference(ci,
- &dataRef,
- &dataRefType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetAliasedDataReference(ci,
+ &dataRef,
+ &dataRefType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType);
+ return _res;
}
static PyObject *Qt_GraphicsImportValidate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Boolean valid;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Boolean valid;
#ifndef GraphicsImportValidate
- PyMac_PRECHECK(GraphicsImportValidate);
+ PyMac_PRECHECK(GraphicsImportValidate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportValidate(ci,
- &valid);
- _res = Py_BuildValue("lb",
- _rv,
- valid);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportValidate(ci,
+ &valid);
+ _res = Py_BuildValue("lb",
+ _rv,
+ valid);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetMetaData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * userData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * userData;
#ifndef GraphicsImportGetMetaData
- PyMac_PRECHECK(GraphicsImportGetMetaData);
+ PyMac_PRECHECK(GraphicsImportGetMetaData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &userData))
- return NULL;
- _rv = GraphicsImportGetMetaData(ci,
- userData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &userData))
+ return NULL;
+ _rv = GraphicsImportGetMetaData(ci,
+ userData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetMIMETypeList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * qtAtomContainerPtr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * qtAtomContainerPtr;
#ifndef GraphicsImportGetMIMETypeList
- PyMac_PRECHECK(GraphicsImportGetMIMETypeList);
+ PyMac_PRECHECK(GraphicsImportGetMIMETypeList);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainerPtr))
- return NULL;
- _rv = GraphicsImportGetMIMETypeList(ci,
- qtAtomContainerPtr);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainerPtr))
+ return NULL;
+ _rv = GraphicsImportGetMIMETypeList(ci,
+ qtAtomContainerPtr);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportDoesDrawAllPixels(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- short drawsAllPixels;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ short drawsAllPixels;
#ifndef GraphicsImportDoesDrawAllPixels
- PyMac_PRECHECK(GraphicsImportDoesDrawAllPixels);
+ PyMac_PRECHECK(GraphicsImportDoesDrawAllPixels);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportDoesDrawAllPixels(ci,
- &drawsAllPixels);
- _res = Py_BuildValue("lh",
- _rv,
- drawsAllPixels);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportDoesDrawAllPixels(ci,
+ &drawsAllPixels);
+ _res = Py_BuildValue("lh",
+ _rv,
+ drawsAllPixels);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetAsPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- PicHandle picture;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ PicHandle picture;
#ifndef GraphicsImportGetAsPicture
- PyMac_PRECHECK(GraphicsImportGetAsPicture);
+ PyMac_PRECHECK(GraphicsImportGetAsPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetAsPicture(ci,
- &picture);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, picture);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetAsPicture(ci,
+ &picture);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, picture);
+ return _res;
}
static PyObject *Qt_GraphicsImportExportImageFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- OSType fileType;
- OSType fileCreator;
- FSSpec fss;
- ScriptCode scriptTag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ OSType fileType;
+ OSType fileCreator;
+ FSSpec fss;
+ ScriptCode scriptTag;
#ifndef GraphicsImportExportImageFile
- PyMac_PRECHECK(GraphicsImportExportImageFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&h",
- CmpInstObj_Convert, &ci,
- PyMac_GetOSType, &fileType,
- PyMac_GetOSType, &fileCreator,
- PyMac_GetFSSpec, &fss,
- &scriptTag))
- return NULL;
- _rv = GraphicsImportExportImageFile(ci,
- fileType,
- fileCreator,
- &fss,
- scriptTag);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsImportExportImageFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&h",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetOSType, &fileType,
+ PyMac_GetOSType, &fileCreator,
+ PyMac_GetFSSpec, &fss,
+ &scriptTag))
+ return NULL;
+ _rv = GraphicsImportExportImageFile(ci,
+ fileType,
+ fileCreator,
+ &fss,
+ scriptTag);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetExportImageTypeList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * qtAtomContainerPtr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * qtAtomContainerPtr;
#ifndef GraphicsImportGetExportImageTypeList
- PyMac_PRECHECK(GraphicsImportGetExportImageTypeList);
+ PyMac_PRECHECK(GraphicsImportGetExportImageTypeList);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainerPtr))
- return NULL;
- _rv = GraphicsImportGetExportImageTypeList(ci,
- qtAtomContainerPtr);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainerPtr))
+ return NULL;
+ _rv = GraphicsImportGetExportImageTypeList(ci,
+ qtAtomContainerPtr);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetExportSettingsAsAtomContainer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * qtAtomContainerPtr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * qtAtomContainerPtr;
#ifndef GraphicsImportGetExportSettingsAsAtomContainer
- PyMac_PRECHECK(GraphicsImportGetExportSettingsAsAtomContainer);
+ PyMac_PRECHECK(GraphicsImportGetExportSettingsAsAtomContainer);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainerPtr))
- return NULL;
- _rv = GraphicsImportGetExportSettingsAsAtomContainer(ci,
- qtAtomContainerPtr);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainerPtr))
+ return NULL;
+ _rv = GraphicsImportGetExportSettingsAsAtomContainer(ci,
+ qtAtomContainerPtr);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetExportSettingsFromAtomContainer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * qtAtomContainer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * qtAtomContainer;
#ifndef GraphicsImportSetExportSettingsFromAtomContainer
- PyMac_PRECHECK(GraphicsImportSetExportSettingsFromAtomContainer);
+ PyMac_PRECHECK(GraphicsImportSetExportSettingsFromAtomContainer);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainer))
- return NULL;
- _rv = GraphicsImportSetExportSettingsFromAtomContainer(ci,
- qtAtomContainer);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainer))
+ return NULL;
+ _rv = GraphicsImportSetExportSettingsFromAtomContainer(ci,
+ qtAtomContainer);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetImageCount(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- unsigned long imageCount;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ unsigned long imageCount;
#ifndef GraphicsImportGetImageCount
- PyMac_PRECHECK(GraphicsImportGetImageCount);
+ PyMac_PRECHECK(GraphicsImportGetImageCount);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetImageCount(ci,
- &imageCount);
- _res = Py_BuildValue("ll",
- _rv,
- imageCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetImageCount(ci,
+ &imageCount);
+ _res = Py_BuildValue("ll",
+ _rv,
+ imageCount);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetImageIndex(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- unsigned long imageIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ unsigned long imageIndex;
#ifndef GraphicsImportSetImageIndex
- PyMac_PRECHECK(GraphicsImportSetImageIndex);
+ PyMac_PRECHECK(GraphicsImportSetImageIndex);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &imageIndex))
- return NULL;
- _rv = GraphicsImportSetImageIndex(ci,
- imageIndex);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &imageIndex))
+ return NULL;
+ _rv = GraphicsImportSetImageIndex(ci,
+ imageIndex);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetImageIndex(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- unsigned long imageIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ unsigned long imageIndex;
#ifndef GraphicsImportGetImageIndex
- PyMac_PRECHECK(GraphicsImportGetImageIndex);
+ PyMac_PRECHECK(GraphicsImportGetImageIndex);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetImageIndex(ci,
- &imageIndex);
- _res = Py_BuildValue("ll",
- _rv,
- imageIndex);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetImageIndex(ci,
+ &imageIndex);
+ _res = Py_BuildValue("ll",
+ _rv,
+ imageIndex);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataOffsetAndSize64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- wide offset;
- wide size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ wide offset;
+ wide size;
#ifndef GraphicsImportGetDataOffsetAndSize64
- PyMac_PRECHECK(GraphicsImportGetDataOffsetAndSize64);
+ PyMac_PRECHECK(GraphicsImportGetDataOffsetAndSize64);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDataOffsetAndSize64(ci,
- &offset,
- &size);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_Buildwide, offset,
- PyMac_Buildwide, size);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDataOffsetAndSize64(ci,
+ &offset,
+ &size);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_Buildwide, offset,
+ PyMac_Buildwide, size);
+ return _res;
}
static PyObject *Qt_GraphicsImportReadData64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- void * dataPtr;
- wide dataOffset;
- unsigned long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ void * dataPtr;
+ wide dataOffset;
+ unsigned long dataSize;
#ifndef GraphicsImportReadData64
- PyMac_PRECHECK(GraphicsImportReadData64);
-#endif
- if (!PyArg_ParseTuple(_args, "O&sO&l",
- CmpInstObj_Convert, &ci,
- &dataPtr,
- PyMac_Getwide, &dataOffset,
- &dataSize))
- return NULL;
- _rv = GraphicsImportReadData64(ci,
- dataPtr,
- &dataOffset,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsImportReadData64);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&sO&l",
+ CmpInstObj_Convert, &ci,
+ &dataPtr,
+ PyMac_Getwide, &dataOffset,
+ &dataSize))
+ return NULL;
+ _rv = GraphicsImportReadData64(ci,
+ dataPtr,
+ &dataOffset,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetDataReferenceOffsetAndLimit64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- wide offset;
- wide limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ wide offset;
+ wide limit;
#ifndef GraphicsImportSetDataReferenceOffsetAndLimit64
- PyMac_PRECHECK(GraphicsImportSetDataReferenceOffsetAndLimit64);
+ PyMac_PRECHECK(GraphicsImportSetDataReferenceOffsetAndLimit64);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_Getwide, &offset,
- PyMac_Getwide, &limit))
- return NULL;
- _rv = GraphicsImportSetDataReferenceOffsetAndLimit64(ci,
- &offset,
- &limit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_Getwide, &offset,
+ PyMac_Getwide, &limit))
+ return NULL;
+ _rv = GraphicsImportSetDataReferenceOffsetAndLimit64(ci,
+ &offset,
+ &limit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDataReferenceOffsetAndLimit64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- wide offset;
- wide limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ wide offset;
+ wide limit;
#ifndef GraphicsImportGetDataReferenceOffsetAndLimit64
- PyMac_PRECHECK(GraphicsImportGetDataReferenceOffsetAndLimit64);
+ PyMac_PRECHECK(GraphicsImportGetDataReferenceOffsetAndLimit64);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDataReferenceOffsetAndLimit64(ci,
- &offset,
- &limit);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_Buildwide, offset,
- PyMac_Buildwide, limit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDataReferenceOffsetAndLimit64(ci,
+ &offset,
+ &limit);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_Buildwide, offset,
+ PyMac_Buildwide, limit);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDefaultClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- RgnHandle defaultRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ RgnHandle defaultRgn;
#ifndef GraphicsImportGetDefaultClip
- PyMac_PRECHECK(GraphicsImportGetDefaultClip);
+ PyMac_PRECHECK(GraphicsImportGetDefaultClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDefaultClip(ci,
- &defaultRgn);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, defaultRgn);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDefaultClip(ci,
+ &defaultRgn);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, defaultRgn);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDefaultGraphicsMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- long defaultGraphicsMode;
- RGBColor defaultOpColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ long defaultGraphicsMode;
+ RGBColor defaultOpColor;
#ifndef GraphicsImportGetDefaultGraphicsMode
- PyMac_PRECHECK(GraphicsImportGetDefaultGraphicsMode);
+ PyMac_PRECHECK(GraphicsImportGetDefaultGraphicsMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDefaultGraphicsMode(ci,
- &defaultGraphicsMode,
- &defaultOpColor);
- _res = Py_BuildValue("llO&",
- _rv,
- defaultGraphicsMode,
- QdRGB_New, &defaultOpColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDefaultGraphicsMode(ci,
+ &defaultGraphicsMode,
+ &defaultOpColor);
+ _res = Py_BuildValue("llO&",
+ _rv,
+ defaultGraphicsMode,
+ QdRGB_New, &defaultOpColor);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDefaultSourceRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect defaultSourceRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect defaultSourceRect;
#ifndef GraphicsImportGetDefaultSourceRect
- PyMac_PRECHECK(GraphicsImportGetDefaultSourceRect);
+ PyMac_PRECHECK(GraphicsImportGetDefaultSourceRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDefaultSourceRect(ci,
- &defaultSourceRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &defaultSourceRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDefaultSourceRect(ci,
+ &defaultSourceRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &defaultSourceRect);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetColorSyncProfile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Handle profile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Handle profile;
#ifndef GraphicsImportGetColorSyncProfile
- PyMac_PRECHECK(GraphicsImportGetColorSyncProfile);
+ PyMac_PRECHECK(GraphicsImportGetColorSyncProfile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetColorSyncProfile(ci,
- &profile);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, profile);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetColorSyncProfile(ci,
+ &profile);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, profile);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetDestRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect destRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect destRect;
#ifndef GraphicsImportSetDestRect
- PyMac_PRECHECK(GraphicsImportSetDestRect);
+ PyMac_PRECHECK(GraphicsImportSetDestRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetRect, &destRect))
- return NULL;
- _rv = GraphicsImportSetDestRect(ci,
- &destRect);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetRect, &destRect))
+ return NULL;
+ _rv = GraphicsImportSetDestRect(ci,
+ &destRect);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetDestRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- Rect destRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ Rect destRect;
#ifndef GraphicsImportGetDestRect
- PyMac_PRECHECK(GraphicsImportGetDestRect);
+ PyMac_PRECHECK(GraphicsImportGetDestRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetDestRect(ci,
- &destRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &destRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetDestRect(ci,
+ &destRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &destRect);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ long flags;
#ifndef GraphicsImportSetFlags
- PyMac_PRECHECK(GraphicsImportSetFlags);
+ PyMac_PRECHECK(GraphicsImportSetFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &flags))
- return NULL;
- _rv = GraphicsImportSetFlags(ci,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &flags))
+ return NULL;
+ _rv = GraphicsImportSetFlags(ci,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ long flags;
#ifndef GraphicsImportGetFlags
- PyMac_PRECHECK(GraphicsImportGetFlags);
+ PyMac_PRECHECK(GraphicsImportGetFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetFlags(ci,
- &flags);
- _res = Py_BuildValue("ll",
- _rv,
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetFlags(ci,
+ &flags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flags);
+ return _res;
}
static PyObject *Qt_GraphicsImportGetBaseDataOffsetAndSize64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
- wide offset;
- wide size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
+ wide offset;
+ wide size;
#ifndef GraphicsImportGetBaseDataOffsetAndSize64
- PyMac_PRECHECK(GraphicsImportGetBaseDataOffsetAndSize64);
+ PyMac_PRECHECK(GraphicsImportGetBaseDataOffsetAndSize64);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportGetBaseDataOffsetAndSize64(ci,
- &offset,
- &size);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_Buildwide, offset,
- PyMac_Buildwide, size);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportGetBaseDataOffsetAndSize64(ci,
+ &offset,
+ &size);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_Buildwide, offset,
+ PyMac_Buildwide, size);
+ return _res;
}
static PyObject *Qt_GraphicsImportSetImageIndexToThumbnail(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsImportComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsImportComponent ci;
#ifndef GraphicsImportSetImageIndexToThumbnail
- PyMac_PRECHECK(GraphicsImportSetImageIndexToThumbnail);
+ PyMac_PRECHECK(GraphicsImportSetImageIndexToThumbnail);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImportSetImageIndexToThumbnail(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImportSetImageIndexToThumbnail(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportDoExport(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long actualSizeWritten;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long actualSizeWritten;
#ifndef GraphicsExportDoExport
- PyMac_PRECHECK(GraphicsExportDoExport);
+ PyMac_PRECHECK(GraphicsExportDoExport);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportDoExport(ci,
- &actualSizeWritten);
- _res = Py_BuildValue("ll",
- _rv,
- actualSizeWritten);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportDoExport(ci,
+ &actualSizeWritten);
+ _res = Py_BuildValue("ll",
+ _rv,
+ actualSizeWritten);
+ return _res;
}
static PyObject *Qt_GraphicsExportCanTranscode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean canTranscode;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean canTranscode;
#ifndef GraphicsExportCanTranscode
- PyMac_PRECHECK(GraphicsExportCanTranscode);
+ PyMac_PRECHECK(GraphicsExportCanTranscode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportCanTranscode(ci,
- &canTranscode);
- _res = Py_BuildValue("lb",
- _rv,
- canTranscode);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportCanTranscode(ci,
+ &canTranscode);
+ _res = Py_BuildValue("lb",
+ _rv,
+ canTranscode);
+ return _res;
}
static PyObject *Qt_GraphicsExportDoTranscode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
#ifndef GraphicsExportDoTranscode
- PyMac_PRECHECK(GraphicsExportDoTranscode);
+ PyMac_PRECHECK(GraphicsExportDoTranscode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportDoTranscode(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportDoTranscode(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportCanUseCompressor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean canUseCompressor;
- void * codecSettingsAtomContainerPtr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean canUseCompressor;
+ void * codecSettingsAtomContainerPtr;
#ifndef GraphicsExportCanUseCompressor
- PyMac_PRECHECK(GraphicsExportCanUseCompressor);
+ PyMac_PRECHECK(GraphicsExportCanUseCompressor);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &codecSettingsAtomContainerPtr))
- return NULL;
- _rv = GraphicsExportCanUseCompressor(ci,
- &canUseCompressor,
- codecSettingsAtomContainerPtr);
- _res = Py_BuildValue("lb",
- _rv,
- canUseCompressor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &codecSettingsAtomContainerPtr))
+ return NULL;
+ _rv = GraphicsExportCanUseCompressor(ci,
+ &canUseCompressor,
+ codecSettingsAtomContainerPtr);
+ _res = Py_BuildValue("lb",
+ _rv,
+ canUseCompressor);
+ return _res;
}
static PyObject *Qt_GraphicsExportDoUseCompressor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * codecSettingsAtomContainer;
- ImageDescriptionHandle outDesc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * codecSettingsAtomContainer;
+ ImageDescriptionHandle outDesc;
#ifndef GraphicsExportDoUseCompressor
- PyMac_PRECHECK(GraphicsExportDoUseCompressor);
+ PyMac_PRECHECK(GraphicsExportDoUseCompressor);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &codecSettingsAtomContainer))
- return NULL;
- _rv = GraphicsExportDoUseCompressor(ci,
- codecSettingsAtomContainer,
- &outDesc);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, outDesc);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &codecSettingsAtomContainer))
+ return NULL;
+ _rv = GraphicsExportDoUseCompressor(ci,
+ codecSettingsAtomContainer,
+ &outDesc);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, outDesc);
+ return _res;
}
static PyObject *Qt_GraphicsExportDoStandaloneExport(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
#ifndef GraphicsExportDoStandaloneExport
- PyMac_PRECHECK(GraphicsExportDoStandaloneExport);
+ PyMac_PRECHECK(GraphicsExportDoStandaloneExport);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportDoStandaloneExport(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportDoStandaloneExport(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetDefaultFileTypeAndCreator(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- OSType fileType;
- OSType fileCreator;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ OSType fileType;
+ OSType fileCreator;
#ifndef GraphicsExportGetDefaultFileTypeAndCreator
- PyMac_PRECHECK(GraphicsExportGetDefaultFileTypeAndCreator);
+ PyMac_PRECHECK(GraphicsExportGetDefaultFileTypeAndCreator);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetDefaultFileTypeAndCreator(ci,
- &fileType,
- &fileCreator);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_BuildOSType, fileType,
- PyMac_BuildOSType, fileCreator);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetDefaultFileTypeAndCreator(ci,
+ &fileType,
+ &fileCreator);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_BuildOSType, fileType,
+ PyMac_BuildOSType, fileCreator);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetDefaultFileNameExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- OSType fileNameExtension;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ OSType fileNameExtension;
#ifndef GraphicsExportGetDefaultFileNameExtension
- PyMac_PRECHECK(GraphicsExportGetDefaultFileNameExtension);
+ PyMac_PRECHECK(GraphicsExportGetDefaultFileNameExtension);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetDefaultFileNameExtension(ci,
- &fileNameExtension);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, fileNameExtension);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetDefaultFileNameExtension(ci,
+ &fileNameExtension);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, fileNameExtension);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetMIMETypeList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * qtAtomContainerPtr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * qtAtomContainerPtr;
#ifndef GraphicsExportGetMIMETypeList
- PyMac_PRECHECK(GraphicsExportGetMIMETypeList);
+ PyMac_PRECHECK(GraphicsExportGetMIMETypeList);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainerPtr))
- return NULL;
- _rv = GraphicsExportGetMIMETypeList(ci,
- qtAtomContainerPtr);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainerPtr))
+ return NULL;
+ _rv = GraphicsExportGetMIMETypeList(ci,
+ qtAtomContainerPtr);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetSettingsFromAtomContainer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * qtAtomContainer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * qtAtomContainer;
#ifndef GraphicsExportSetSettingsFromAtomContainer
- PyMac_PRECHECK(GraphicsExportSetSettingsFromAtomContainer);
+ PyMac_PRECHECK(GraphicsExportSetSettingsFromAtomContainer);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainer))
- return NULL;
- _rv = GraphicsExportSetSettingsFromAtomContainer(ci,
- qtAtomContainer);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainer))
+ return NULL;
+ _rv = GraphicsExportSetSettingsFromAtomContainer(ci,
+ qtAtomContainer);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetSettingsAsAtomContainer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * qtAtomContainerPtr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * qtAtomContainerPtr;
#ifndef GraphicsExportGetSettingsAsAtomContainer
- PyMac_PRECHECK(GraphicsExportGetSettingsAsAtomContainer);
+ PyMac_PRECHECK(GraphicsExportGetSettingsAsAtomContainer);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &qtAtomContainerPtr))
- return NULL;
- _rv = GraphicsExportGetSettingsAsAtomContainer(ci,
- qtAtomContainerPtr);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &qtAtomContainerPtr))
+ return NULL;
+ _rv = GraphicsExportGetSettingsAsAtomContainer(ci,
+ qtAtomContainerPtr);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetSettingsAsText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle theText;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle theText;
#ifndef GraphicsExportGetSettingsAsText
- PyMac_PRECHECK(GraphicsExportGetSettingsAsText);
+ PyMac_PRECHECK(GraphicsExportGetSettingsAsText);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetSettingsAsText(ci,
- &theText);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, theText);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetSettingsAsText(ci,
+ &theText);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, theText);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetDontRecompress(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean dontRecompress;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean dontRecompress;
#ifndef GraphicsExportSetDontRecompress
- PyMac_PRECHECK(GraphicsExportSetDontRecompress);
+ PyMac_PRECHECK(GraphicsExportSetDontRecompress);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &dontRecompress))
- return NULL;
- _rv = GraphicsExportSetDontRecompress(ci,
- dontRecompress);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &dontRecompress))
+ return NULL;
+ _rv = GraphicsExportSetDontRecompress(ci,
+ dontRecompress);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetDontRecompress(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean dontRecompress;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean dontRecompress;
#ifndef GraphicsExportGetDontRecompress
- PyMac_PRECHECK(GraphicsExportGetDontRecompress);
+ PyMac_PRECHECK(GraphicsExportGetDontRecompress);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetDontRecompress(ci,
- &dontRecompress);
- _res = Py_BuildValue("lb",
- _rv,
- dontRecompress);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetDontRecompress(ci,
+ &dontRecompress);
+ _res = Py_BuildValue("lb",
+ _rv,
+ dontRecompress);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInterlaceStyle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long interlaceStyle;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long interlaceStyle;
#ifndef GraphicsExportSetInterlaceStyle
- PyMac_PRECHECK(GraphicsExportSetInterlaceStyle);
+ PyMac_PRECHECK(GraphicsExportSetInterlaceStyle);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &interlaceStyle))
- return NULL;
- _rv = GraphicsExportSetInterlaceStyle(ci,
- interlaceStyle);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &interlaceStyle))
+ return NULL;
+ _rv = GraphicsExportSetInterlaceStyle(ci,
+ interlaceStyle);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInterlaceStyle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long interlaceStyle;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long interlaceStyle;
#ifndef GraphicsExportGetInterlaceStyle
- PyMac_PRECHECK(GraphicsExportGetInterlaceStyle);
+ PyMac_PRECHECK(GraphicsExportGetInterlaceStyle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInterlaceStyle(ci,
- &interlaceStyle);
- _res = Py_BuildValue("ll",
- _rv,
- interlaceStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInterlaceStyle(ci,
+ &interlaceStyle);
+ _res = Py_BuildValue("ll",
+ _rv,
+ interlaceStyle);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetMetaData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * userData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * userData;
#ifndef GraphicsExportSetMetaData
- PyMac_PRECHECK(GraphicsExportSetMetaData);
+ PyMac_PRECHECK(GraphicsExportSetMetaData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &userData))
- return NULL;
- _rv = GraphicsExportSetMetaData(ci,
- userData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &userData))
+ return NULL;
+ _rv = GraphicsExportSetMetaData(ci,
+ userData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetMetaData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * userData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * userData;
#ifndef GraphicsExportGetMetaData
- PyMac_PRECHECK(GraphicsExportGetMetaData);
+ PyMac_PRECHECK(GraphicsExportGetMetaData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &ci,
- &userData))
- return NULL;
- _rv = GraphicsExportGetMetaData(ci,
- userData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &ci,
+ &userData))
+ return NULL;
+ _rv = GraphicsExportGetMetaData(ci,
+ userData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetTargetDataSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long targetDataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long targetDataSize;
#ifndef GraphicsExportSetTargetDataSize
- PyMac_PRECHECK(GraphicsExportSetTargetDataSize);
+ PyMac_PRECHECK(GraphicsExportSetTargetDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &targetDataSize))
- return NULL;
- _rv = GraphicsExportSetTargetDataSize(ci,
- targetDataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &targetDataSize))
+ return NULL;
+ _rv = GraphicsExportSetTargetDataSize(ci,
+ targetDataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetTargetDataSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long targetDataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long targetDataSize;
#ifndef GraphicsExportGetTargetDataSize
- PyMac_PRECHECK(GraphicsExportGetTargetDataSize);
+ PyMac_PRECHECK(GraphicsExportGetTargetDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetTargetDataSize(ci,
- &targetDataSize);
- _res = Py_BuildValue("ll",
- _rv,
- targetDataSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetTargetDataSize(ci,
+ &targetDataSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ targetDataSize);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetCompressionMethod(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- long compressionMethod;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ long compressionMethod;
#ifndef GraphicsExportSetCompressionMethod
- PyMac_PRECHECK(GraphicsExportSetCompressionMethod);
+ PyMac_PRECHECK(GraphicsExportSetCompressionMethod);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &compressionMethod))
- return NULL;
- _rv = GraphicsExportSetCompressionMethod(ci,
- compressionMethod);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &compressionMethod))
+ return NULL;
+ _rv = GraphicsExportSetCompressionMethod(ci,
+ compressionMethod);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetCompressionMethod(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- long compressionMethod;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ long compressionMethod;
#ifndef GraphicsExportGetCompressionMethod
- PyMac_PRECHECK(GraphicsExportGetCompressionMethod);
+ PyMac_PRECHECK(GraphicsExportGetCompressionMethod);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetCompressionMethod(ci,
- &compressionMethod);
- _res = Py_BuildValue("ll",
- _rv,
- compressionMethod);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetCompressionMethod(ci,
+ &compressionMethod);
+ _res = Py_BuildValue("ll",
+ _rv,
+ compressionMethod);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetCompressionQuality(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- CodecQ spatialQuality;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ CodecQ spatialQuality;
#ifndef GraphicsExportSetCompressionQuality
- PyMac_PRECHECK(GraphicsExportSetCompressionQuality);
+ PyMac_PRECHECK(GraphicsExportSetCompressionQuality);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &spatialQuality))
- return NULL;
- _rv = GraphicsExportSetCompressionQuality(ci,
- spatialQuality);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &spatialQuality))
+ return NULL;
+ _rv = GraphicsExportSetCompressionQuality(ci,
+ spatialQuality);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetCompressionQuality(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- CodecQ spatialQuality;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ CodecQ spatialQuality;
#ifndef GraphicsExportGetCompressionQuality
- PyMac_PRECHECK(GraphicsExportGetCompressionQuality);
+ PyMac_PRECHECK(GraphicsExportGetCompressionQuality);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetCompressionQuality(ci,
- &spatialQuality);
- _res = Py_BuildValue("ll",
- _rv,
- spatialQuality);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetCompressionQuality(ci,
+ &spatialQuality);
+ _res = Py_BuildValue("ll",
+ _rv,
+ spatialQuality);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetResolution(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Fixed horizontalResolution;
- Fixed verticalResolution;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Fixed horizontalResolution;
+ Fixed verticalResolution;
#ifndef GraphicsExportSetResolution
- PyMac_PRECHECK(GraphicsExportSetResolution);
+ PyMac_PRECHECK(GraphicsExportSetResolution);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFixed, &horizontalResolution,
- PyMac_GetFixed, &verticalResolution))
- return NULL;
- _rv = GraphicsExportSetResolution(ci,
- horizontalResolution,
- verticalResolution);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFixed, &horizontalResolution,
+ PyMac_GetFixed, &verticalResolution))
+ return NULL;
+ _rv = GraphicsExportSetResolution(ci,
+ horizontalResolution,
+ verticalResolution);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetResolution(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Fixed horizontalResolution;
- Fixed verticalResolution;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Fixed horizontalResolution;
+ Fixed verticalResolution;
#ifndef GraphicsExportGetResolution
- PyMac_PRECHECK(GraphicsExportGetResolution);
+ PyMac_PRECHECK(GraphicsExportGetResolution);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetResolution(ci,
- &horizontalResolution,
- &verticalResolution);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_BuildFixed, horizontalResolution,
- PyMac_BuildFixed, verticalResolution);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetResolution(ci,
+ &horizontalResolution,
+ &verticalResolution);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_BuildFixed, horizontalResolution,
+ PyMac_BuildFixed, verticalResolution);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetDepth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- long depth;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ long depth;
#ifndef GraphicsExportSetDepth
- PyMac_PRECHECK(GraphicsExportSetDepth);
+ PyMac_PRECHECK(GraphicsExportSetDepth);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &depth))
- return NULL;
- _rv = GraphicsExportSetDepth(ci,
- depth);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &depth))
+ return NULL;
+ _rv = GraphicsExportSetDepth(ci,
+ depth);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetDepth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- long depth;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ long depth;
#ifndef GraphicsExportGetDepth
- PyMac_PRECHECK(GraphicsExportGetDepth);
+ PyMac_PRECHECK(GraphicsExportGetDepth);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetDepth(ci,
- &depth);
- _res = Py_BuildValue("ll",
- _rv,
- depth);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetDepth(ci,
+ &depth);
+ _res = Py_BuildValue("ll",
+ _rv,
+ depth);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetColorSyncProfile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle colorSyncProfile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle colorSyncProfile;
#ifndef GraphicsExportSetColorSyncProfile
- PyMac_PRECHECK(GraphicsExportSetColorSyncProfile);
+ PyMac_PRECHECK(GraphicsExportSetColorSyncProfile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &colorSyncProfile))
- return NULL;
- _rv = GraphicsExportSetColorSyncProfile(ci,
- colorSyncProfile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &colorSyncProfile))
+ return NULL;
+ _rv = GraphicsExportSetColorSyncProfile(ci,
+ colorSyncProfile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetColorSyncProfile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle colorSyncProfile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle colorSyncProfile;
#ifndef GraphicsExportGetColorSyncProfile
- PyMac_PRECHECK(GraphicsExportGetColorSyncProfile);
+ PyMac_PRECHECK(GraphicsExportGetColorSyncProfile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetColorSyncProfile(ci,
- &colorSyncProfile);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, colorSyncProfile);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetColorSyncProfile(ci,
+ &colorSyncProfile);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, colorSyncProfile);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle dataRef;
- OSType dataRefType;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
+ ImageDescriptionHandle desc;
#ifndef GraphicsExportSetInputDataReference
- PyMac_PRECHECK(GraphicsExportSetInputDataReference);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- ResObj_Convert, &desc))
- return NULL;
- _rv = GraphicsExportSetInputDataReference(ci,
- dataRef,
- dataRefType,
- desc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportSetInputDataReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ ResObj_Convert, &desc))
+ return NULL;
+ _rv = GraphicsExportSetInputDataReference(ci,
+ dataRef,
+ dataRefType,
+ desc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef GraphicsExportGetInputDataReference
- PyMac_PRECHECK(GraphicsExportGetInputDataReference);
+ PyMac_PRECHECK(GraphicsExportGetInputDataReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputDataReference(ci,
- &dataRef,
- &dataRefType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputDataReference(ci,
+ &dataRef,
+ &dataRefType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- FSSpec theFile;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ FSSpec theFile;
+ ImageDescriptionHandle desc;
#ifndef GraphicsExportSetInputFile
- PyMac_PRECHECK(GraphicsExportSetInputFile);
+ PyMac_PRECHECK(GraphicsExportSetInputFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile,
- ResObj_Convert, &desc))
- return NULL;
- _rv = GraphicsExportSetInputFile(ci,
- &theFile,
- desc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile,
+ ResObj_Convert, &desc))
+ return NULL;
+ _rv = GraphicsExportSetInputFile(ci,
+ &theFile,
+ desc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- FSSpec theFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ FSSpec theFile;
#ifndef GraphicsExportGetInputFile
- PyMac_PRECHECK(GraphicsExportGetInputFile);
+ PyMac_PRECHECK(GraphicsExportGetInputFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _rv = GraphicsExportGetInputFile(ci,
- &theFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _rv = GraphicsExportGetInputFile(ci,
+ &theFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle h;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle h;
+ ImageDescriptionHandle desc;
#ifndef GraphicsExportSetInputHandle
- PyMac_PRECHECK(GraphicsExportSetInputHandle);
+ PyMac_PRECHECK(GraphicsExportSetInputHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &h,
- ResObj_Convert, &desc))
- return NULL;
- _rv = GraphicsExportSetInputHandle(ci,
- h,
- desc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &h,
+ ResObj_Convert, &desc))
+ return NULL;
+ _rv = GraphicsExportSetInputHandle(ci,
+ h,
+ desc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle h;
#ifndef GraphicsExportGetInputHandle
- PyMac_PRECHECK(GraphicsExportGetInputHandle);
+ PyMac_PRECHECK(GraphicsExportGetInputHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputHandle(ci,
- &h);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, h);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputHandle(ci,
+ &h);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, h);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputPtr(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Ptr p;
- unsigned long size;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Ptr p;
+ unsigned long size;
+ ImageDescriptionHandle desc;
#ifndef GraphicsExportSetInputPtr
- PyMac_PRECHECK(GraphicsExportSetInputPtr);
-#endif
- if (!PyArg_ParseTuple(_args, "O&slO&",
- CmpInstObj_Convert, &ci,
- &p,
- &size,
- ResObj_Convert, &desc))
- return NULL;
- _rv = GraphicsExportSetInputPtr(ci,
- p,
- size,
- desc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportSetInputPtr);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&slO&",
+ CmpInstObj_Convert, &ci,
+ &p,
+ &size,
+ ResObj_Convert, &desc))
+ return NULL;
+ _rv = GraphicsExportSetInputPtr(ci,
+ p,
+ size,
+ desc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputGraphicsImporter(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- GraphicsImportComponent grip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ GraphicsImportComponent grip;
#ifndef GraphicsExportSetInputGraphicsImporter
- PyMac_PRECHECK(GraphicsExportSetInputGraphicsImporter);
+ PyMac_PRECHECK(GraphicsExportSetInputGraphicsImporter);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- CmpInstObj_Convert, &grip))
- return NULL;
- _rv = GraphicsExportSetInputGraphicsImporter(ci,
- grip);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ CmpInstObj_Convert, &grip))
+ return NULL;
+ _rv = GraphicsExportSetInputGraphicsImporter(ci,
+ grip);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputGraphicsImporter(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- GraphicsImportComponent grip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ GraphicsImportComponent grip;
#ifndef GraphicsExportGetInputGraphicsImporter
- PyMac_PRECHECK(GraphicsExportGetInputGraphicsImporter);
+ PyMac_PRECHECK(GraphicsExportGetInputGraphicsImporter);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputGraphicsImporter(ci,
- &grip);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpInstObj_New, grip);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputGraphicsImporter(ci,
+ &grip);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpInstObj_New, grip);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- PicHandle picture;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ PicHandle picture;
#ifndef GraphicsExportSetInputPicture
- PyMac_PRECHECK(GraphicsExportSetInputPicture);
+ PyMac_PRECHECK(GraphicsExportSetInputPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &picture))
- return NULL;
- _rv = GraphicsExportSetInputPicture(ci,
- picture);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &picture))
+ return NULL;
+ _rv = GraphicsExportSetInputPicture(ci,
+ picture);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- PicHandle picture;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ PicHandle picture;
#ifndef GraphicsExportGetInputPicture
- PyMac_PRECHECK(GraphicsExportGetInputPicture);
+ PyMac_PRECHECK(GraphicsExportGetInputPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputPicture(ci,
- &picture);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, picture);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputPicture(ci,
+ &picture);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, picture);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- GWorldPtr gworld;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ GWorldPtr gworld;
#ifndef GraphicsExportSetInputGWorld
- PyMac_PRECHECK(GraphicsExportSetInputGWorld);
+ PyMac_PRECHECK(GraphicsExportSetInputGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- GWorldObj_Convert, &gworld))
- return NULL;
- _rv = GraphicsExportSetInputGWorld(ci,
- gworld);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ GWorldObj_Convert, &gworld))
+ return NULL;
+ _rv = GraphicsExportSetInputGWorld(ci,
+ gworld);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- GWorldPtr gworld;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ GWorldPtr gworld;
#ifndef GraphicsExportGetInputGWorld
- PyMac_PRECHECK(GraphicsExportGetInputGWorld);
+ PyMac_PRECHECK(GraphicsExportGetInputGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputGWorld(ci,
- &gworld);
- _res = Py_BuildValue("lO&",
- _rv,
- GWorldObj_New, gworld);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputGWorld(ci,
+ &gworld);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ GWorldObj_New, gworld);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputPixmap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- PixMapHandle pixmap;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ PixMapHandle pixmap;
#ifndef GraphicsExportSetInputPixmap
- PyMac_PRECHECK(GraphicsExportSetInputPixmap);
+ PyMac_PRECHECK(GraphicsExportSetInputPixmap);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &pixmap))
- return NULL;
- _rv = GraphicsExportSetInputPixmap(ci,
- pixmap);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &pixmap))
+ return NULL;
+ _rv = GraphicsExportSetInputPixmap(ci,
+ pixmap);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputPixmap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- PixMapHandle pixmap;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ PixMapHandle pixmap;
#ifndef GraphicsExportGetInputPixmap
- PyMac_PRECHECK(GraphicsExportGetInputPixmap);
+ PyMac_PRECHECK(GraphicsExportGetInputPixmap);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputPixmap(ci,
- &pixmap);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, pixmap);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputPixmap(ci,
+ &pixmap);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, pixmap);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetInputOffsetAndLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long offset;
- unsigned long limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long offset;
+ unsigned long limit;
#ifndef GraphicsExportSetInputOffsetAndLimit
- PyMac_PRECHECK(GraphicsExportSetInputOffsetAndLimit);
+ PyMac_PRECHECK(GraphicsExportSetInputOffsetAndLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &ci,
- &offset,
- &limit))
- return NULL;
- _rv = GraphicsExportSetInputOffsetAndLimit(ci,
- offset,
- limit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &ci,
+ &offset,
+ &limit))
+ return NULL;
+ _rv = GraphicsExportSetInputOffsetAndLimit(ci,
+ offset,
+ limit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputOffsetAndLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long offset;
- unsigned long limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long offset;
+ unsigned long limit;
#ifndef GraphicsExportGetInputOffsetAndLimit
- PyMac_PRECHECK(GraphicsExportGetInputOffsetAndLimit);
+ PyMac_PRECHECK(GraphicsExportGetInputOffsetAndLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputOffsetAndLimit(ci,
- &offset,
- &limit);
- _res = Py_BuildValue("lll",
- _rv,
- offset,
- limit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputOffsetAndLimit(ci,
+ &offset,
+ &limit);
+ _res = Py_BuildValue("lll",
+ _rv,
+ offset,
+ limit);
+ return _res;
}
static PyObject *Qt_GraphicsExportMayExporterReadInputData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean mayReadInputData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean mayReadInputData;
#ifndef GraphicsExportMayExporterReadInputData
- PyMac_PRECHECK(GraphicsExportMayExporterReadInputData);
+ PyMac_PRECHECK(GraphicsExportMayExporterReadInputData);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportMayExporterReadInputData(ci,
- &mayReadInputData);
- _res = Py_BuildValue("lb",
- _rv,
- mayReadInputData);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportMayExporterReadInputData(ci,
+ &mayReadInputData);
+ _res = Py_BuildValue("lb",
+ _rv,
+ mayReadInputData);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputDataSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long size;
#ifndef GraphicsExportGetInputDataSize
- PyMac_PRECHECK(GraphicsExportGetInputDataSize);
+ PyMac_PRECHECK(GraphicsExportGetInputDataSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputDataSize(ci,
- &size);
- _res = Py_BuildValue("ll",
- _rv,
- size);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputDataSize(ci,
+ &size);
+ _res = Py_BuildValue("ll",
+ _rv,
+ size);
+ return _res;
}
static PyObject *Qt_GraphicsExportReadInputData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * dataPtr;
- unsigned long dataOffset;
- unsigned long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * dataPtr;
+ unsigned long dataOffset;
+ unsigned long dataSize;
#ifndef GraphicsExportReadInputData
- PyMac_PRECHECK(GraphicsExportReadInputData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&sll",
- CmpInstObj_Convert, &ci,
- &dataPtr,
- &dataOffset,
- &dataSize))
- return NULL;
- _rv = GraphicsExportReadInputData(ci,
- dataPtr,
- dataOffset,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportReadInputData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&sll",
+ CmpInstObj_Convert, &ci,
+ &dataPtr,
+ &dataOffset,
+ &dataSize))
+ return NULL;
+ _rv = GraphicsExportReadInputData(ci,
+ dataPtr,
+ dataOffset,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputImageDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ ImageDescriptionHandle desc;
#ifndef GraphicsExportGetInputImageDescription
- PyMac_PRECHECK(GraphicsExportGetInputImageDescription);
+ PyMac_PRECHECK(GraphicsExportGetInputImageDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputImageDescription(ci,
- &desc);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, desc);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputImageDescription(ci,
+ &desc);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, desc);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputImageDimensions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Rect dimensions;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Rect dimensions;
#ifndef GraphicsExportGetInputImageDimensions
- PyMac_PRECHECK(GraphicsExportGetInputImageDimensions);
+ PyMac_PRECHECK(GraphicsExportGetInputImageDimensions);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputImageDimensions(ci,
- &dimensions);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &dimensions);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputImageDimensions(ci,
+ &dimensions);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &dimensions);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetInputImageDepth(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- long inputDepth;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ long inputDepth;
#ifndef GraphicsExportGetInputImageDepth
- PyMac_PRECHECK(GraphicsExportGetInputImageDepth);
+ PyMac_PRECHECK(GraphicsExportGetInputImageDepth);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetInputImageDepth(ci,
- &inputDepth);
- _res = Py_BuildValue("ll",
- _rv,
- inputDepth);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetInputImageDepth(ci,
+ &inputDepth);
+ _res = Py_BuildValue("ll",
+ _rv,
+ inputDepth);
+ return _res;
}
static PyObject *Qt_GraphicsExportDrawInputImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- CGrafPtr gw;
- GDHandle gd;
- Rect srcRect;
- Rect dstRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ CGrafPtr gw;
+ GDHandle gd;
+ Rect srcRect;
+ Rect dstRect;
#ifndef GraphicsExportDrawInputImage
- PyMac_PRECHECK(GraphicsExportDrawInputImage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
- CmpInstObj_Convert, &ci,
- GrafObj_Convert, &gw,
- OptResObj_Convert, &gd,
- PyMac_GetRect, &srcRect,
- PyMac_GetRect, &dstRect))
- return NULL;
- _rv = GraphicsExportDrawInputImage(ci,
- gw,
- gd,
- &srcRect,
- &dstRect);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportDrawInputImage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&",
+ CmpInstObj_Convert, &ci,
+ GrafObj_Convert, &gw,
+ OptResObj_Convert, &gd,
+ PyMac_GetRect, &srcRect,
+ PyMac_GetRect, &dstRect))
+ return NULL;
+ _rv = GraphicsExportDrawInputImage(ci,
+ gw,
+ gd,
+ &srcRect,
+ &dstRect);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetOutputDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef GraphicsExportSetOutputDataReference
- PyMac_PRECHECK(GraphicsExportSetOutputDataReference);
+ PyMac_PRECHECK(GraphicsExportSetOutputDataReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _rv = GraphicsExportSetOutputDataReference(ci,
- dataRef,
- dataRefType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _rv = GraphicsExportSetOutputDataReference(ci,
+ dataRef,
+ dataRefType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetOutputDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef GraphicsExportGetOutputDataReference
- PyMac_PRECHECK(GraphicsExportGetOutputDataReference);
+ PyMac_PRECHECK(GraphicsExportGetOutputDataReference);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetOutputDataReference(ci,
- &dataRef,
- &dataRefType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetOutputDataReference(ci,
+ &dataRef,
+ &dataRefType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetOutputFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- FSSpec theFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ FSSpec theFile;
#ifndef GraphicsExportSetOutputFile
- PyMac_PRECHECK(GraphicsExportSetOutputFile);
+ PyMac_PRECHECK(GraphicsExportSetOutputFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _rv = GraphicsExportSetOutputFile(ci,
- &theFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _rv = GraphicsExportSetOutputFile(ci,
+ &theFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetOutputFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- FSSpec theFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ FSSpec theFile;
#ifndef GraphicsExportGetOutputFile
- PyMac_PRECHECK(GraphicsExportGetOutputFile);
+ PyMac_PRECHECK(GraphicsExportGetOutputFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile))
- return NULL;
- _rv = GraphicsExportGetOutputFile(ci,
- &theFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile))
+ return NULL;
+ _rv = GraphicsExportGetOutputFile(ci,
+ &theFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetOutputHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle h;
#ifndef GraphicsExportSetOutputHandle
- PyMac_PRECHECK(GraphicsExportSetOutputHandle);
+ PyMac_PRECHECK(GraphicsExportSetOutputHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &h))
- return NULL;
- _rv = GraphicsExportSetOutputHandle(ci,
- h);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = GraphicsExportSetOutputHandle(ci,
+ h);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetOutputHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Handle h;
#ifndef GraphicsExportGetOutputHandle
- PyMac_PRECHECK(GraphicsExportGetOutputHandle);
+ PyMac_PRECHECK(GraphicsExportGetOutputHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetOutputHandle(ci,
- &h);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, h);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetOutputHandle(ci,
+ &h);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, h);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetOutputOffsetAndMaxSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long offset;
- unsigned long maxSize;
- Boolean truncateFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long offset;
+ unsigned long maxSize;
+ Boolean truncateFile;
#ifndef GraphicsExportSetOutputOffsetAndMaxSize
- PyMac_PRECHECK(GraphicsExportSetOutputOffsetAndMaxSize);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llb",
- CmpInstObj_Convert, &ci,
- &offset,
- &maxSize,
- &truncateFile))
- return NULL;
- _rv = GraphicsExportSetOutputOffsetAndMaxSize(ci,
- offset,
- maxSize,
- truncateFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportSetOutputOffsetAndMaxSize);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llb",
+ CmpInstObj_Convert, &ci,
+ &offset,
+ &maxSize,
+ &truncateFile))
+ return NULL;
+ _rv = GraphicsExportSetOutputOffsetAndMaxSize(ci,
+ offset,
+ maxSize,
+ truncateFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetOutputOffsetAndMaxSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long offset;
- unsigned long maxSize;
- Boolean truncateFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long offset;
+ unsigned long maxSize;
+ Boolean truncateFile;
#ifndef GraphicsExportGetOutputOffsetAndMaxSize
- PyMac_PRECHECK(GraphicsExportGetOutputOffsetAndMaxSize);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetOutputOffsetAndMaxSize(ci,
- &offset,
- &maxSize,
- &truncateFile);
- _res = Py_BuildValue("lllb",
- _rv,
- offset,
- maxSize,
- truncateFile);
- return _res;
+ PyMac_PRECHECK(GraphicsExportGetOutputOffsetAndMaxSize);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetOutputOffsetAndMaxSize(ci,
+ &offset,
+ &maxSize,
+ &truncateFile);
+ _res = Py_BuildValue("lllb",
+ _rv,
+ offset,
+ maxSize,
+ truncateFile);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetOutputFileTypeAndCreator(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- OSType fileType;
- OSType fileCreator;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ OSType fileType;
+ OSType fileCreator;
#ifndef GraphicsExportSetOutputFileTypeAndCreator
- PyMac_PRECHECK(GraphicsExportSetOutputFileTypeAndCreator);
+ PyMac_PRECHECK(GraphicsExportSetOutputFileTypeAndCreator);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetOSType, &fileType,
- PyMac_GetOSType, &fileCreator))
- return NULL;
- _rv = GraphicsExportSetOutputFileTypeAndCreator(ci,
- fileType,
- fileCreator);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetOSType, &fileType,
+ PyMac_GetOSType, &fileCreator))
+ return NULL;
+ _rv = GraphicsExportSetOutputFileTypeAndCreator(ci,
+ fileType,
+ fileCreator);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetOutputFileTypeAndCreator(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- OSType fileType;
- OSType fileCreator;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ OSType fileType;
+ OSType fileCreator;
#ifndef GraphicsExportGetOutputFileTypeAndCreator
- PyMac_PRECHECK(GraphicsExportGetOutputFileTypeAndCreator);
+ PyMac_PRECHECK(GraphicsExportGetOutputFileTypeAndCreator);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetOutputFileTypeAndCreator(ci,
- &fileType,
- &fileCreator);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_BuildOSType, fileType,
- PyMac_BuildOSType, fileCreator);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetOutputFileTypeAndCreator(ci,
+ &fileType,
+ &fileCreator);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_BuildOSType, fileType,
+ PyMac_BuildOSType, fileCreator);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetOutputMark(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long mark;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long mark;
#ifndef GraphicsExportSetOutputMark
- PyMac_PRECHECK(GraphicsExportSetOutputMark);
+ PyMac_PRECHECK(GraphicsExportSetOutputMark);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &mark))
- return NULL;
- _rv = GraphicsExportSetOutputMark(ci,
- mark);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &mark))
+ return NULL;
+ _rv = GraphicsExportSetOutputMark(ci,
+ mark);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetOutputMark(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- unsigned long mark;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ unsigned long mark;
#ifndef GraphicsExportGetOutputMark
- PyMac_PRECHECK(GraphicsExportGetOutputMark);
+ PyMac_PRECHECK(GraphicsExportGetOutputMark);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetOutputMark(ci,
- &mark);
- _res = Py_BuildValue("ll",
- _rv,
- mark);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetOutputMark(ci,
+ &mark);
+ _res = Py_BuildValue("ll",
+ _rv,
+ mark);
+ return _res;
}
static PyObject *Qt_GraphicsExportReadOutputData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- void * dataPtr;
- unsigned long dataOffset;
- unsigned long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ void * dataPtr;
+ unsigned long dataOffset;
+ unsigned long dataSize;
#ifndef GraphicsExportReadOutputData
- PyMac_PRECHECK(GraphicsExportReadOutputData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&sll",
- CmpInstObj_Convert, &ci,
- &dataPtr,
- &dataOffset,
- &dataSize))
- return NULL;
- _rv = GraphicsExportReadOutputData(ci,
- dataPtr,
- dataOffset,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportReadOutputData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&sll",
+ CmpInstObj_Convert, &ci,
+ &dataPtr,
+ &dataOffset,
+ &dataSize))
+ return NULL;
+ _rv = GraphicsExportReadOutputData(ci,
+ dataPtr,
+ dataOffset,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetThumbnailEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean enableThumbnail;
- long maxThumbnailWidth;
- long maxThumbnailHeight;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean enableThumbnail;
+ long maxThumbnailWidth;
+ long maxThumbnailHeight;
#ifndef GraphicsExportSetThumbnailEnabled
- PyMac_PRECHECK(GraphicsExportSetThumbnailEnabled);
-#endif
- if (!PyArg_ParseTuple(_args, "O&bll",
- CmpInstObj_Convert, &ci,
- &enableThumbnail,
- &maxThumbnailWidth,
- &maxThumbnailHeight))
- return NULL;
- _rv = GraphicsExportSetThumbnailEnabled(ci,
- enableThumbnail,
- maxThumbnailWidth,
- maxThumbnailHeight);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(GraphicsExportSetThumbnailEnabled);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&bll",
+ CmpInstObj_Convert, &ci,
+ &enableThumbnail,
+ &maxThumbnailWidth,
+ &maxThumbnailHeight))
+ return NULL;
+ _rv = GraphicsExportSetThumbnailEnabled(ci,
+ enableThumbnail,
+ maxThumbnailWidth,
+ maxThumbnailHeight);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetThumbnailEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean thumbnailEnabled;
- long maxThumbnailWidth;
- long maxThumbnailHeight;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean thumbnailEnabled;
+ long maxThumbnailWidth;
+ long maxThumbnailHeight;
#ifndef GraphicsExportGetThumbnailEnabled
- PyMac_PRECHECK(GraphicsExportGetThumbnailEnabled);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetThumbnailEnabled(ci,
- &thumbnailEnabled,
- &maxThumbnailWidth,
- &maxThumbnailHeight);
- _res = Py_BuildValue("lbll",
- _rv,
- thumbnailEnabled,
- maxThumbnailWidth,
- maxThumbnailHeight);
- return _res;
+ PyMac_PRECHECK(GraphicsExportGetThumbnailEnabled);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetThumbnailEnabled(ci,
+ &thumbnailEnabled,
+ &maxThumbnailWidth,
+ &maxThumbnailHeight);
+ _res = Py_BuildValue("lbll",
+ _rv,
+ thumbnailEnabled,
+ maxThumbnailWidth,
+ maxThumbnailHeight);
+ return _res;
}
static PyObject *Qt_GraphicsExportSetExifEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean enableExif;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean enableExif;
#ifndef GraphicsExportSetExifEnabled
- PyMac_PRECHECK(GraphicsExportSetExifEnabled);
+ PyMac_PRECHECK(GraphicsExportSetExifEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &enableExif))
- return NULL;
- _rv = GraphicsExportSetExifEnabled(ci,
- enableExif);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &enableExif))
+ return NULL;
+ _rv = GraphicsExportSetExifEnabled(ci,
+ enableExif);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsExportGetExifEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicsExportComponent ci;
- Boolean exifEnabled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicsExportComponent ci;
+ Boolean exifEnabled;
#ifndef GraphicsExportGetExifEnabled
- PyMac_PRECHECK(GraphicsExportGetExifEnabled);
+ PyMac_PRECHECK(GraphicsExportGetExifEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsExportGetExifEnabled(ci,
- &exifEnabled);
- _res = Py_BuildValue("lb",
- _rv,
- exifEnabled);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsExportGetExifEnabled(ci,
+ &exifEnabled);
+ _res = Py_BuildValue("lb",
+ _rv,
+ exifEnabled);
+ return _res;
}
static PyObject *Qt_ImageTranscoderBeginSequence(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ImageTranscoderComponent itc;
- ImageDescriptionHandle srcDesc;
- ImageDescriptionHandle dstDesc;
- void * data;
- long dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ImageTranscoderComponent itc;
+ ImageDescriptionHandle srcDesc;
+ ImageDescriptionHandle dstDesc;
+ void * data;
+ long dataSize;
#ifndef ImageTranscoderBeginSequence
- PyMac_PRECHECK(ImageTranscoderBeginSequence);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&sl",
- CmpInstObj_Convert, &itc,
- ResObj_Convert, &srcDesc,
- &data,
- &dataSize))
- return NULL;
- _rv = ImageTranscoderBeginSequence(itc,
- srcDesc,
- &dstDesc,
- data,
- dataSize);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, dstDesc);
- return _res;
+ PyMac_PRECHECK(ImageTranscoderBeginSequence);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&sl",
+ CmpInstObj_Convert, &itc,
+ ResObj_Convert, &srcDesc,
+ &data,
+ &dataSize))
+ return NULL;
+ _rv = ImageTranscoderBeginSequence(itc,
+ srcDesc,
+ &dstDesc,
+ data,
+ dataSize);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, dstDesc);
+ return _res;
}
static PyObject *Qt_ImageTranscoderDisposeData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ImageTranscoderComponent itc;
- void * dstData;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ImageTranscoderComponent itc;
+ void * dstData;
#ifndef ImageTranscoderDisposeData
- PyMac_PRECHECK(ImageTranscoderDisposeData);
+ PyMac_PRECHECK(ImageTranscoderDisposeData);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &itc,
- &dstData))
- return NULL;
- _rv = ImageTranscoderDisposeData(itc,
- dstData);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &itc,
+ &dstData))
+ return NULL;
+ _rv = ImageTranscoderDisposeData(itc,
+ dstData);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_ImageTranscoderEndSequence(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ImageTranscoderComponent itc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ImageTranscoderComponent itc;
#ifndef ImageTranscoderEndSequence
- PyMac_PRECHECK(ImageTranscoderEndSequence);
+ PyMac_PRECHECK(ImageTranscoderEndSequence);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &itc))
- return NULL;
- _rv = ImageTranscoderEndSequence(itc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &itc))
+ return NULL;
+ _rv = ImageTranscoderEndSequence(itc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_ClockGetTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aClock;
- TimeRecord out;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aClock;
+ TimeRecord out;
#ifndef ClockGetTime
- PyMac_PRECHECK(ClockGetTime);
+ PyMac_PRECHECK(ClockGetTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &aClock))
- return NULL;
- _rv = ClockGetTime(aClock,
- &out);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &out);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &aClock))
+ return NULL;
+ _rv = ClockGetTime(aClock,
+ &out);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &out);
+ return _res;
}
static PyObject *Qt_ClockSetTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aClock;
- TimeBase tb;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aClock;
+ TimeBase tb;
#ifndef ClockSetTimeBase
- PyMac_PRECHECK(ClockSetTimeBase);
+ PyMac_PRECHECK(ClockSetTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &aClock,
- TimeBaseObj_Convert, &tb))
- return NULL;
- _rv = ClockSetTimeBase(aClock,
- tb);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &aClock,
+ TimeBaseObj_Convert, &tb))
+ return NULL;
+ _rv = ClockSetTimeBase(aClock,
+ tb);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_ClockGetRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aClock;
- Fixed rate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aClock;
+ Fixed rate;
#ifndef ClockGetRate
- PyMac_PRECHECK(ClockGetRate);
+ PyMac_PRECHECK(ClockGetRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &aClock))
- return NULL;
- _rv = ClockGetRate(aClock,
- &rate);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildFixed, rate);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &aClock))
+ return NULL;
+ _rv = ClockGetRate(aClock,
+ &rate);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildFixed, rate);
+ return _res;
}
static PyObject *Qt_SCPositionRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- Rect rp;
- Point where;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ Rect rp;
+ Point where;
#ifndef SCPositionRect
- PyMac_PRECHECK(SCPositionRect);
+ PyMac_PRECHECK(SCPositionRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCPositionRect(ci,
- &rp,
- &where);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_BuildRect, &rp,
- PyMac_BuildPoint, where);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCPositionRect(ci,
+ &rp,
+ &where);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_BuildRect, &rp,
+ PyMac_BuildPoint, where);
+ return _res;
}
static PyObject *Qt_SCPositionDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- short id;
- Point where;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ short id;
+ Point where;
#ifndef SCPositionDialog
- PyMac_PRECHECK(SCPositionDialog);
+ PyMac_PRECHECK(SCPositionDialog);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &id))
- return NULL;
- _rv = SCPositionDialog(ci,
- id,
- &where);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildPoint, where);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &id))
+ return NULL;
+ _rv = SCPositionDialog(ci,
+ id,
+ &where);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildPoint, where);
+ return _res;
}
static PyObject *Qt_SCSetTestImagePictHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PicHandle testPict;
- Rect testRect;
- short testFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PicHandle testPict;
+ Rect testRect;
+ short testFlags;
#ifndef SCSetTestImagePictHandle
- PyMac_PRECHECK(SCSetTestImagePictHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &testPict,
- &testFlags))
- return NULL;
- _rv = SCSetTestImagePictHandle(ci,
- testPict,
- &testRect,
- testFlags);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &testRect);
- return _res;
+ PyMac_PRECHECK(SCSetTestImagePictHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &testPict,
+ &testFlags))
+ return NULL;
+ _rv = SCSetTestImagePictHandle(ci,
+ testPict,
+ &testRect,
+ testFlags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &testRect);
+ return _res;
}
static PyObject *Qt_SCSetTestImagePictFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- short testFileRef;
- Rect testRect;
- short testFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ short testFileRef;
+ Rect testRect;
+ short testFlags;
#ifndef SCSetTestImagePictFile
- PyMac_PRECHECK(SCSetTestImagePictFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- CmpInstObj_Convert, &ci,
- &testFileRef,
- &testFlags))
- return NULL;
- _rv = SCSetTestImagePictFile(ci,
- testFileRef,
- &testRect,
- testFlags);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &testRect);
- return _res;
+ PyMac_PRECHECK(SCSetTestImagePictFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ CmpInstObj_Convert, &ci,
+ &testFileRef,
+ &testFlags))
+ return NULL;
+ _rv = SCSetTestImagePictFile(ci,
+ testFileRef,
+ &testRect,
+ testFlags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &testRect);
+ return _res;
}
static PyObject *Qt_SCSetTestImagePixMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PixMapHandle testPixMap;
- Rect testRect;
- short testFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PixMapHandle testPixMap;
+ Rect testRect;
+ short testFlags;
#ifndef SCSetTestImagePixMap
- PyMac_PRECHECK(SCSetTestImagePixMap);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &testPixMap,
- &testFlags))
- return NULL;
- _rv = SCSetTestImagePixMap(ci,
- testPixMap,
- &testRect,
- testFlags);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &testRect);
- return _res;
+ PyMac_PRECHECK(SCSetTestImagePixMap);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &testPixMap,
+ &testFlags))
+ return NULL;
+ _rv = SCSetTestImagePixMap(ci,
+ testPixMap,
+ &testRect,
+ testFlags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &testRect);
+ return _res;
}
static PyObject *Qt_SCGetBestDeviceRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- Rect r;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ Rect r;
#ifndef SCGetBestDeviceRect
- PyMac_PRECHECK(SCGetBestDeviceRect);
+ PyMac_PRECHECK(SCGetBestDeviceRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCGetBestDeviceRect(ci,
- &r);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCGetBestDeviceRect(ci,
+ &r);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qt_SCRequestImageSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
#ifndef SCRequestImageSettings
- PyMac_PRECHECK(SCRequestImageSettings);
+ PyMac_PRECHECK(SCRequestImageSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCRequestImageSettings(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCRequestImageSettings(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCCompressImage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PixMapHandle src;
- Rect srcRect;
- ImageDescriptionHandle desc;
- Handle data;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PixMapHandle src;
+ Rect srcRect;
+ ImageDescriptionHandle desc;
+ Handle data;
#ifndef SCCompressImage
- PyMac_PRECHECK(SCCompressImage);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect))
- return NULL;
- _rv = SCCompressImage(ci,
- src,
- &srcRect,
- &desc,
- &data);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, desc,
- ResObj_New, data);
- return _res;
+ PyMac_PRECHECK(SCCompressImage);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect))
+ return NULL;
+ _rv = SCCompressImage(ci,
+ src,
+ &srcRect,
+ &desc,
+ &data);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, desc,
+ ResObj_New, data);
+ return _res;
}
static PyObject *Qt_SCCompressPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PicHandle srcPicture;
- PicHandle dstPicture;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PicHandle srcPicture;
+ PicHandle dstPicture;
#ifndef SCCompressPicture
- PyMac_PRECHECK(SCCompressPicture);
+ PyMac_PRECHECK(SCCompressPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &srcPicture,
- ResObj_Convert, &dstPicture))
- return NULL;
- _rv = SCCompressPicture(ci,
- srcPicture,
- dstPicture);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &srcPicture,
+ ResObj_Convert, &dstPicture))
+ return NULL;
+ _rv = SCCompressPicture(ci,
+ srcPicture,
+ dstPicture);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCCompressPictureFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- short srcRefNum;
- short dstRefNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ short srcRefNum;
+ short dstRefNum;
#ifndef SCCompressPictureFile
- PyMac_PRECHECK(SCCompressPictureFile);
+ PyMac_PRECHECK(SCCompressPictureFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- CmpInstObj_Convert, &ci,
- &srcRefNum,
- &dstRefNum))
- return NULL;
- _rv = SCCompressPictureFile(ci,
- srcRefNum,
- dstRefNum);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ CmpInstObj_Convert, &ci,
+ &srcRefNum,
+ &dstRefNum))
+ return NULL;
+ _rv = SCCompressPictureFile(ci,
+ srcRefNum,
+ dstRefNum);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCRequestSequenceSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
#ifndef SCRequestSequenceSettings
- PyMac_PRECHECK(SCRequestSequenceSettings);
+ PyMac_PRECHECK(SCRequestSequenceSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCRequestSequenceSettings(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCRequestSequenceSettings(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCCompressSequenceBegin(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PixMapHandle src;
- Rect srcRect;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PixMapHandle src;
+ Rect srcRect;
+ ImageDescriptionHandle desc;
#ifndef SCCompressSequenceBegin
- PyMac_PRECHECK(SCCompressSequenceBegin);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect))
- return NULL;
- _rv = SCCompressSequenceBegin(ci,
- src,
- &srcRect,
- &desc);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, desc);
- return _res;
+ PyMac_PRECHECK(SCCompressSequenceBegin);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect))
+ return NULL;
+ _rv = SCCompressSequenceBegin(ci,
+ src,
+ &srcRect,
+ &desc);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, desc);
+ return _res;
}
static PyObject *Qt_SCCompressSequenceFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PixMapHandle src;
- Rect srcRect;
- Handle data;
- long dataSize;
- short notSyncFlag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PixMapHandle src;
+ Rect srcRect;
+ Handle data;
+ long dataSize;
+ short notSyncFlag;
#ifndef SCCompressSequenceFrame
- PyMac_PRECHECK(SCCompressSequenceFrame);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &src,
- PyMac_GetRect, &srcRect))
- return NULL;
- _rv = SCCompressSequenceFrame(ci,
- src,
- &srcRect,
- &data,
- &dataSize,
- &notSyncFlag);
- _res = Py_BuildValue("lO&lh",
- _rv,
- ResObj_New, data,
- dataSize,
- notSyncFlag);
- return _res;
+ PyMac_PRECHECK(SCCompressSequenceFrame);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &src,
+ PyMac_GetRect, &srcRect))
+ return NULL;
+ _rv = SCCompressSequenceFrame(ci,
+ src,
+ &srcRect,
+ &data,
+ &dataSize,
+ &notSyncFlag);
+ _res = Py_BuildValue("lO&lh",
+ _rv,
+ ResObj_New, data,
+ dataSize,
+ notSyncFlag);
+ return _res;
}
static PyObject *Qt_SCCompressSequenceEnd(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
#ifndef SCCompressSequenceEnd
- PyMac_PRECHECK(SCCompressSequenceEnd);
+ PyMac_PRECHECK(SCCompressSequenceEnd);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCCompressSequenceEnd(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCCompressSequenceEnd(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCDefaultPictHandleSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PicHandle srcPicture;
- short motion;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PicHandle srcPicture;
+ short motion;
#ifndef SCDefaultPictHandleSettings
- PyMac_PRECHECK(SCDefaultPictHandleSettings);
+ PyMac_PRECHECK(SCDefaultPictHandleSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &srcPicture,
- &motion))
- return NULL;
- _rv = SCDefaultPictHandleSettings(ci,
- srcPicture,
- motion);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &srcPicture,
+ &motion))
+ return NULL;
+ _rv = SCDefaultPictHandleSettings(ci,
+ srcPicture,
+ motion);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCDefaultPictFileSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- short srcRef;
- short motion;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ short srcRef;
+ short motion;
#ifndef SCDefaultPictFileSettings
- PyMac_PRECHECK(SCDefaultPictFileSettings);
+ PyMac_PRECHECK(SCDefaultPictFileSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- CmpInstObj_Convert, &ci,
- &srcRef,
- &motion))
- return NULL;
- _rv = SCDefaultPictFileSettings(ci,
- srcRef,
- motion);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ CmpInstObj_Convert, &ci,
+ &srcRef,
+ &motion))
+ return NULL;
+ _rv = SCDefaultPictFileSettings(ci,
+ srcRef,
+ motion);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCDefaultPixMapSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- PixMapHandle src;
- short motion;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ PixMapHandle src;
+ short motion;
#ifndef SCDefaultPixMapSettings
- PyMac_PRECHECK(SCDefaultPixMapSettings);
+ PyMac_PRECHECK(SCDefaultPixMapSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &src,
- &motion))
- return NULL;
- _rv = SCDefaultPixMapSettings(ci,
- src,
- motion);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &src,
+ &motion))
+ return NULL;
+ _rv = SCDefaultPixMapSettings(ci,
+ src,
+ motion);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCGetInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- OSType infoType;
- void * info;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ OSType infoType;
+ void * info;
#ifndef SCGetInfo
- PyMac_PRECHECK(SCGetInfo);
+ PyMac_PRECHECK(SCGetInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&s",
- CmpInstObj_Convert, &ci,
- PyMac_GetOSType, &infoType,
- &info))
- return NULL;
- _rv = SCGetInfo(ci,
- infoType,
- info);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&s",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetOSType, &infoType,
+ &info))
+ return NULL;
+ _rv = SCGetInfo(ci,
+ infoType,
+ info);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCSetInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- OSType infoType;
- void * info;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ OSType infoType;
+ void * info;
#ifndef SCSetInfo
- PyMac_PRECHECK(SCSetInfo);
+ PyMac_PRECHECK(SCSetInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&s",
- CmpInstObj_Convert, &ci,
- PyMac_GetOSType, &infoType,
- &info))
- return NULL;
- _rv = SCSetInfo(ci,
- infoType,
- info);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&s",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetOSType, &infoType,
+ &info))
+ return NULL;
+ _rv = SCSetInfo(ci,
+ infoType,
+ info);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCSetCompressFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ long flags;
#ifndef SCSetCompressFlags
- PyMac_PRECHECK(SCSetCompressFlags);
+ PyMac_PRECHECK(SCSetCompressFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &flags))
- return NULL;
- _rv = SCSetCompressFlags(ci,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &flags))
+ return NULL;
+ _rv = SCSetCompressFlags(ci,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SCGetCompressFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ long flags;
#ifndef SCGetCompressFlags
- PyMac_PRECHECK(SCGetCompressFlags);
+ PyMac_PRECHECK(SCGetCompressFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCGetCompressFlags(ci,
- &flags);
- _res = Py_BuildValue("ll",
- _rv,
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCGetCompressFlags(ci,
+ &flags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flags);
+ return _res;
}
static PyObject *Qt_SCGetSettingsAsText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
- Handle text;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
+ Handle text;
#ifndef SCGetSettingsAsText
- PyMac_PRECHECK(SCGetSettingsAsText);
+ PyMac_PRECHECK(SCGetSettingsAsText);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCGetSettingsAsText(ci,
- &text);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, text);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCGetSettingsAsText(ci,
+ &text);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, text);
+ return _res;
}
static PyObject *Qt_SCAsyncIdle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance ci;
#ifndef SCAsyncIdle
- PyMac_PRECHECK(SCAsyncIdle);
+ PyMac_PRECHECK(SCAsyncIdle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = SCAsyncIdle(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = SCAsyncIdle(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TweenerReset(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TweenerComponent tc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TweenerComponent tc;
#ifndef TweenerReset
- PyMac_PRECHECK(TweenerReset);
+ PyMac_PRECHECK(TweenerReset);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tc))
- return NULL;
- _rv = TweenerReset(tc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tc))
+ return NULL;
+ _rv = TweenerReset(tc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TCGetSourceRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- HandlerError _rv;
- MediaHandler mh;
- TimeCodeDescriptionHandle tcdH;
- UserData srefH;
+ PyObject *_res = NULL;
+ HandlerError _rv;
+ MediaHandler mh;
+ TimeCodeDescriptionHandle tcdH;
+ UserData srefH;
#ifndef TCGetSourceRef
- PyMac_PRECHECK(TCGetSourceRef);
+ PyMac_PRECHECK(TCGetSourceRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &tcdH))
- return NULL;
- _rv = TCGetSourceRef(mh,
- tcdH,
- &srefH);
- _res = Py_BuildValue("lO&",
- _rv,
- UserDataObj_New, srefH);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &tcdH))
+ return NULL;
+ _rv = TCGetSourceRef(mh,
+ tcdH,
+ &srefH);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ UserDataObj_New, srefH);
+ return _res;
}
static PyObject *Qt_TCSetSourceRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- HandlerError _rv;
- MediaHandler mh;
- TimeCodeDescriptionHandle tcdH;
- UserData srefH;
+ PyObject *_res = NULL;
+ HandlerError _rv;
+ MediaHandler mh;
+ TimeCodeDescriptionHandle tcdH;
+ UserData srefH;
#ifndef TCSetSourceRef
- PyMac_PRECHECK(TCSetSourceRef);
+ PyMac_PRECHECK(TCSetSourceRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &tcdH,
- UserDataObj_Convert, &srefH))
- return NULL;
- _rv = TCSetSourceRef(mh,
- tcdH,
- srefH);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &tcdH,
+ UserDataObj_Convert, &srefH))
+ return NULL;
+ _rv = TCSetSourceRef(mh,
+ tcdH,
+ srefH);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TCSetTimeCodeFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- HandlerError _rv;
- MediaHandler mh;
- long flags;
- long flagsMask;
+ PyObject *_res = NULL;
+ HandlerError _rv;
+ MediaHandler mh;
+ long flags;
+ long flagsMask;
#ifndef TCSetTimeCodeFlags
- PyMac_PRECHECK(TCSetTimeCodeFlags);
+ PyMac_PRECHECK(TCSetTimeCodeFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &flags,
- &flagsMask))
- return NULL;
- _rv = TCSetTimeCodeFlags(mh,
- flags,
- flagsMask);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ &flagsMask))
+ return NULL;
+ _rv = TCSetTimeCodeFlags(mh,
+ flags,
+ flagsMask);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TCGetTimeCodeFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- HandlerError _rv;
- MediaHandler mh;
- long flags;
+ PyObject *_res = NULL;
+ HandlerError _rv;
+ MediaHandler mh;
+ long flags;
#ifndef TCGetTimeCodeFlags
- PyMac_PRECHECK(TCGetTimeCodeFlags);
+ PyMac_PRECHECK(TCGetTimeCodeFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = TCGetTimeCodeFlags(mh,
- &flags);
- _res = Py_BuildValue("ll",
- _rv,
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = TCGetTimeCodeFlags(mh,
+ &flags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flags);
+ return _res;
}
static PyObject *Qt_MovieImportHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Handle dataH;
- Movie theMovie;
- Track targetTrack;
- Track usedTrack;
- TimeValue atTime;
- TimeValue addedDuration;
- long inFlags;
- long outFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Handle dataH;
+ Movie theMovie;
+ Track targetTrack;
+ Track usedTrack;
+ TimeValue atTime;
+ TimeValue addedDuration;
+ long inFlags;
+ long outFlags;
#ifndef MovieImportHandle
- PyMac_PRECHECK(MovieImportHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataH,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &targetTrack,
- &atTime,
- &inFlags))
- return NULL;
- _rv = MovieImportHandle(ci,
- dataH,
- theMovie,
- targetTrack,
- &usedTrack,
- atTime,
- &addedDuration,
- inFlags,
- &outFlags);
- _res = Py_BuildValue("lO&ll",
- _rv,
- TrackObj_New, usedTrack,
- addedDuration,
- outFlags);
- return _res;
+ PyMac_PRECHECK(MovieImportHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataH,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &targetTrack,
+ &atTime,
+ &inFlags))
+ return NULL;
+ _rv = MovieImportHandle(ci,
+ dataH,
+ theMovie,
+ targetTrack,
+ &usedTrack,
+ atTime,
+ &addedDuration,
+ inFlags,
+ &outFlags);
+ _res = Py_BuildValue("lO&ll",
+ _rv,
+ TrackObj_New, usedTrack,
+ addedDuration,
+ outFlags);
+ return _res;
}
static PyObject *Qt_MovieImportFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- FSSpec theFile;
- Movie theMovie;
- Track targetTrack;
- Track usedTrack;
- TimeValue atTime;
- TimeValue addedDuration;
- long inFlags;
- long outFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ FSSpec theFile;
+ Movie theMovie;
+ Track targetTrack;
+ Track usedTrack;
+ TimeValue atTime;
+ TimeValue addedDuration;
+ long inFlags;
+ long outFlags;
#ifndef MovieImportFile
- PyMac_PRECHECK(MovieImportFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &targetTrack,
- &atTime,
- &inFlags))
- return NULL;
- _rv = MovieImportFile(ci,
- &theFile,
- theMovie,
- targetTrack,
- &usedTrack,
- atTime,
- &addedDuration,
- inFlags,
- &outFlags);
- _res = Py_BuildValue("lO&ll",
- _rv,
- TrackObj_New, usedTrack,
- addedDuration,
- outFlags);
- return _res;
+ PyMac_PRECHECK(MovieImportFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &targetTrack,
+ &atTime,
+ &inFlags))
+ return NULL;
+ _rv = MovieImportFile(ci,
+ &theFile,
+ theMovie,
+ targetTrack,
+ &usedTrack,
+ atTime,
+ &addedDuration,
+ inFlags,
+ &outFlags);
+ _res = Py_BuildValue("lO&ll",
+ _rv,
+ TrackObj_New, usedTrack,
+ addedDuration,
+ outFlags);
+ return _res;
}
static PyObject *Qt_MovieImportSetSampleDuration(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- TimeValue duration;
- TimeScale scale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ TimeValue duration;
+ TimeScale scale;
#ifndef MovieImportSetSampleDuration
- PyMac_PRECHECK(MovieImportSetSampleDuration);
+ PyMac_PRECHECK(MovieImportSetSampleDuration);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &ci,
- &duration,
- &scale))
- return NULL;
- _rv = MovieImportSetSampleDuration(ci,
- duration,
- scale);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &ci,
+ &duration,
+ &scale))
+ return NULL;
+ _rv = MovieImportSetSampleDuration(ci,
+ duration,
+ scale);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetSampleDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- SampleDescriptionHandle desc;
- OSType mediaType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ SampleDescriptionHandle desc;
+ OSType mediaType;
#ifndef MovieImportSetSampleDescription
- PyMac_PRECHECK(MovieImportSetSampleDescription);
+ PyMac_PRECHECK(MovieImportSetSampleDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &desc,
- PyMac_GetOSType, &mediaType))
- return NULL;
- _rv = MovieImportSetSampleDescription(ci,
- desc,
- mediaType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &desc,
+ PyMac_GetOSType, &mediaType))
+ return NULL;
+ _rv = MovieImportSetSampleDescription(ci,
+ desc,
+ mediaType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetMediaFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- AliasHandle alias;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ AliasHandle alias;
#ifndef MovieImportSetMediaFile
- PyMac_PRECHECK(MovieImportSetMediaFile);
+ PyMac_PRECHECK(MovieImportSetMediaFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &alias))
- return NULL;
- _rv = MovieImportSetMediaFile(ci,
- alias);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &alias))
+ return NULL;
+ _rv = MovieImportSetMediaFile(ci,
+ alias);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetDimensions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Fixed width;
- Fixed height;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Fixed width;
+ Fixed height;
#ifndef MovieImportSetDimensions
- PyMac_PRECHECK(MovieImportSetDimensions);
+ PyMac_PRECHECK(MovieImportSetDimensions);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFixed, &width,
- PyMac_GetFixed, &height))
- return NULL;
- _rv = MovieImportSetDimensions(ci,
- width,
- height);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFixed, &width,
+ PyMac_GetFixed, &height))
+ return NULL;
+ _rv = MovieImportSetDimensions(ci,
+ width,
+ height);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetChunkSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- long chunkSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ long chunkSize;
#ifndef MovieImportSetChunkSize
- PyMac_PRECHECK(MovieImportSetChunkSize);
+ PyMac_PRECHECK(MovieImportSetChunkSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &chunkSize))
- return NULL;
- _rv = MovieImportSetChunkSize(ci,
- chunkSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &chunkSize))
+ return NULL;
+ _rv = MovieImportSetChunkSize(ci,
+ chunkSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetAuxiliaryData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Handle data;
- OSType handleType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Handle data;
+ OSType handleType;
#ifndef MovieImportSetAuxiliaryData
- PyMac_PRECHECK(MovieImportSetAuxiliaryData);
+ PyMac_PRECHECK(MovieImportSetAuxiliaryData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &data,
- PyMac_GetOSType, &handleType))
- return NULL;
- _rv = MovieImportSetAuxiliaryData(ci,
- data,
- handleType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &data,
+ PyMac_GetOSType, &handleType))
+ return NULL;
+ _rv = MovieImportSetAuxiliaryData(ci,
+ data,
+ handleType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetFromScrap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Boolean fromScrap;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Boolean fromScrap;
#ifndef MovieImportSetFromScrap
- PyMac_PRECHECK(MovieImportSetFromScrap);
+ PyMac_PRECHECK(MovieImportSetFromScrap);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &fromScrap))
- return NULL;
- _rv = MovieImportSetFromScrap(ci,
- fromScrap);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &fromScrap))
+ return NULL;
+ _rv = MovieImportSetFromScrap(ci,
+ fromScrap);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportDoUserDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- FSSpec theFile;
- Handle theData;
- Boolean canceled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ FSSpec theFile;
+ Handle theData;
+ Boolean canceled;
#ifndef MovieImportDoUserDialog
- PyMac_PRECHECK(MovieImportDoUserDialog);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile,
- ResObj_Convert, &theData))
- return NULL;
- _rv = MovieImportDoUserDialog(ci,
- &theFile,
- theData,
- &canceled);
- _res = Py_BuildValue("lb",
- _rv,
- canceled);
- return _res;
+ PyMac_PRECHECK(MovieImportDoUserDialog);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile,
+ ResObj_Convert, &theData))
+ return NULL;
+ _rv = MovieImportDoUserDialog(ci,
+ &theFile,
+ theData,
+ &canceled);
+ _res = Py_BuildValue("lb",
+ _rv,
+ canceled);
+ return _res;
}
static PyObject *Qt_MovieImportSetDuration(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- TimeValue duration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ TimeValue duration;
#ifndef MovieImportSetDuration
- PyMac_PRECHECK(MovieImportSetDuration);
+ PyMac_PRECHECK(MovieImportSetDuration);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &duration))
- return NULL;
- _rv = MovieImportSetDuration(ci,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &duration))
+ return NULL;
+ _rv = MovieImportSetDuration(ci,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportGetAuxiliaryDataType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- OSType auxType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ OSType auxType;
#ifndef MovieImportGetAuxiliaryDataType
- PyMac_PRECHECK(MovieImportGetAuxiliaryDataType);
+ PyMac_PRECHECK(MovieImportGetAuxiliaryDataType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetAuxiliaryDataType(ci,
- &auxType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, auxType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetAuxiliaryDataType(ci,
+ &auxType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, auxType);
+ return _res;
}
static PyObject *Qt_MovieImportValidate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- FSSpec theFile;
- Handle theData;
- Boolean valid;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ FSSpec theFile;
+ Handle theData;
+ Boolean valid;
#ifndef MovieImportValidate
- PyMac_PRECHECK(MovieImportValidate);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile,
- ResObj_Convert, &theData))
- return NULL;
- _rv = MovieImportValidate(ci,
- &theFile,
- theData,
- &valid);
- _res = Py_BuildValue("lb",
- _rv,
- valid);
- return _res;
+ PyMac_PRECHECK(MovieImportValidate);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile,
+ ResObj_Convert, &theData))
+ return NULL;
+ _rv = MovieImportValidate(ci,
+ &theFile,
+ theData,
+ &valid);
+ _res = Py_BuildValue("lb",
+ _rv,
+ valid);
+ return _res;
}
static PyObject *Qt_MovieImportGetFileType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- OSType fileType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ OSType fileType;
#ifndef MovieImportGetFileType
- PyMac_PRECHECK(MovieImportGetFileType);
+ PyMac_PRECHECK(MovieImportGetFileType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetFileType(ci,
- &fileType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, fileType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetFileType(ci,
+ &fileType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, fileType);
+ return _res;
}
static PyObject *Qt_MovieImportDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Handle dataRef;
- OSType dataRefType;
- Movie theMovie;
- Track targetTrack;
- Track usedTrack;
- TimeValue atTime;
- TimeValue addedDuration;
- long inFlags;
- long outFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
+ Movie theMovie;
+ Track targetTrack;
+ Track usedTrack;
+ TimeValue atTime;
+ TimeValue addedDuration;
+ long inFlags;
+ long outFlags;
#ifndef MovieImportDataRef
- PyMac_PRECHECK(MovieImportDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&ll",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &targetTrack,
- &atTime,
- &inFlags))
- return NULL;
- _rv = MovieImportDataRef(ci,
- dataRef,
- dataRefType,
- theMovie,
- targetTrack,
- &usedTrack,
- atTime,
- &addedDuration,
- inFlags,
- &outFlags);
- _res = Py_BuildValue("lO&ll",
- _rv,
- TrackObj_New, usedTrack,
- addedDuration,
- outFlags);
- return _res;
+ PyMac_PRECHECK(MovieImportDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &targetTrack,
+ &atTime,
+ &inFlags))
+ return NULL;
+ _rv = MovieImportDataRef(ci,
+ dataRef,
+ dataRefType,
+ theMovie,
+ targetTrack,
+ &usedTrack,
+ atTime,
+ &addedDuration,
+ inFlags,
+ &outFlags);
+ _res = Py_BuildValue("lO&ll",
+ _rv,
+ TrackObj_New, usedTrack,
+ addedDuration,
+ outFlags);
+ return _res;
}
static PyObject *Qt_MovieImportGetSampleDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- SampleDescriptionHandle desc;
- OSType mediaType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ SampleDescriptionHandle desc;
+ OSType mediaType;
#ifndef MovieImportGetSampleDescription
- PyMac_PRECHECK(MovieImportGetSampleDescription);
+ PyMac_PRECHECK(MovieImportGetSampleDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetSampleDescription(ci,
- &desc,
- &mediaType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, desc,
- PyMac_BuildOSType, mediaType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetSampleDescription(ci,
+ &desc,
+ &mediaType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, desc,
+ PyMac_BuildOSType, mediaType);
+ return _res;
}
static PyObject *Qt_MovieImportSetOffsetAndLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- unsigned long offset;
- unsigned long limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ unsigned long offset;
+ unsigned long limit;
#ifndef MovieImportSetOffsetAndLimit
- PyMac_PRECHECK(MovieImportSetOffsetAndLimit);
+ PyMac_PRECHECK(MovieImportSetOffsetAndLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &ci,
- &offset,
- &limit))
- return NULL;
- _rv = MovieImportSetOffsetAndLimit(ci,
- offset,
- limit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &ci,
+ &offset,
+ &limit))
+ return NULL;
+ _rv = MovieImportSetOffsetAndLimit(ci,
+ offset,
+ limit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetOffsetAndLimit64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- wide offset;
- wide limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ wide offset;
+ wide limit;
#ifndef MovieImportSetOffsetAndLimit64
- PyMac_PRECHECK(MovieImportSetOffsetAndLimit64);
+ PyMac_PRECHECK(MovieImportSetOffsetAndLimit64);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_Getwide, &offset,
- PyMac_Getwide, &limit))
- return NULL;
- _rv = MovieImportSetOffsetAndLimit64(ci,
- &offset,
- &limit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_Getwide, &offset,
+ PyMac_Getwide, &limit))
+ return NULL;
+ _rv = MovieImportSetOffsetAndLimit64(ci,
+ &offset,
+ &limit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportIdle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- long inFlags;
- long outFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ long inFlags;
+ long outFlags;
#ifndef MovieImportIdle
- PyMac_PRECHECK(MovieImportIdle);
+ PyMac_PRECHECK(MovieImportIdle);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &inFlags))
- return NULL;
- _rv = MovieImportIdle(ci,
- inFlags,
- &outFlags);
- _res = Py_BuildValue("ll",
- _rv,
- outFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &inFlags))
+ return NULL;
+ _rv = MovieImportIdle(ci,
+ inFlags,
+ &outFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ outFlags);
+ return _res;
}
static PyObject *Qt_MovieImportValidateDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Handle dataRef;
- OSType dataRefType;
- UInt8 valid;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
+ UInt8 valid;
#ifndef MovieImportValidateDataRef
- PyMac_PRECHECK(MovieImportValidateDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _rv = MovieImportValidateDataRef(ci,
- dataRef,
- dataRefType,
- &valid);
- _res = Py_BuildValue("lb",
- _rv,
- valid);
- return _res;
+ PyMac_PRECHECK(MovieImportValidateDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _rv = MovieImportValidateDataRef(ci,
+ dataRef,
+ dataRefType,
+ &valid);
+ _res = Py_BuildValue("lb",
+ _rv,
+ valid);
+ return _res;
}
static PyObject *Qt_MovieImportGetLoadState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- long importerLoadState;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ long importerLoadState;
#ifndef MovieImportGetLoadState
- PyMac_PRECHECK(MovieImportGetLoadState);
+ PyMac_PRECHECK(MovieImportGetLoadState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetLoadState(ci,
- &importerLoadState);
- _res = Py_BuildValue("ll",
- _rv,
- importerLoadState);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetLoadState(ci,
+ &importerLoadState);
+ _res = Py_BuildValue("ll",
+ _rv,
+ importerLoadState);
+ return _res;
}
static PyObject *Qt_MovieImportGetMaxLoadedTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- TimeValue time;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ TimeValue time;
#ifndef MovieImportGetMaxLoadedTime
- PyMac_PRECHECK(MovieImportGetMaxLoadedTime);
+ PyMac_PRECHECK(MovieImportGetMaxLoadedTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetMaxLoadedTime(ci,
- &time);
- _res = Py_BuildValue("ll",
- _rv,
- time);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetMaxLoadedTime(ci,
+ &time);
+ _res = Py_BuildValue("ll",
+ _rv,
+ time);
+ return _res;
}
static PyObject *Qt_MovieImportEstimateCompletionTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- TimeRecord time;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ TimeRecord time;
#ifndef MovieImportEstimateCompletionTime
- PyMac_PRECHECK(MovieImportEstimateCompletionTime);
+ PyMac_PRECHECK(MovieImportEstimateCompletionTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportEstimateCompletionTime(ci,
- &time);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &time);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportEstimateCompletionTime(ci,
+ &time);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &time);
+ return _res;
}
static PyObject *Qt_MovieImportSetDontBlock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Boolean dontBlock;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Boolean dontBlock;
#ifndef MovieImportSetDontBlock
- PyMac_PRECHECK(MovieImportSetDontBlock);
+ PyMac_PRECHECK(MovieImportSetDontBlock);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &dontBlock))
- return NULL;
- _rv = MovieImportSetDontBlock(ci,
- dontBlock);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &dontBlock))
+ return NULL;
+ _rv = MovieImportSetDontBlock(ci,
+ dontBlock);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportGetDontBlock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- Boolean willBlock;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ Boolean willBlock;
#ifndef MovieImportGetDontBlock
- PyMac_PRECHECK(MovieImportGetDontBlock);
+ PyMac_PRECHECK(MovieImportGetDontBlock);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetDontBlock(ci,
- &willBlock);
- _res = Py_BuildValue("lb",
- _rv,
- willBlock);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetDontBlock(ci,
+ &willBlock);
+ _res = Py_BuildValue("lb",
+ _rv,
+ willBlock);
+ return _res;
}
static PyObject *Qt_MovieImportSetIdleManager(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- IdleManager im;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ IdleManager im;
#ifndef MovieImportSetIdleManager
- PyMac_PRECHECK(MovieImportSetIdleManager);
+ PyMac_PRECHECK(MovieImportSetIdleManager);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- IdleManagerObj_Convert, &im))
- return NULL;
- _rv = MovieImportSetIdleManager(ci,
- im);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ IdleManagerObj_Convert, &im))
+ return NULL;
+ _rv = MovieImportSetIdleManager(ci,
+ im);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportSetNewMovieFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- long newMovieFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ long newMovieFlags;
#ifndef MovieImportSetNewMovieFlags
- PyMac_PRECHECK(MovieImportSetNewMovieFlags);
+ PyMac_PRECHECK(MovieImportSetNewMovieFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &newMovieFlags))
- return NULL;
- _rv = MovieImportSetNewMovieFlags(ci,
- newMovieFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &newMovieFlags))
+ return NULL;
+ _rv = MovieImportSetNewMovieFlags(ci,
+ newMovieFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieImportGetDestinationMediaType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieImportComponent ci;
- OSType mediaType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieImportComponent ci;
+ OSType mediaType;
#ifndef MovieImportGetDestinationMediaType
- PyMac_PRECHECK(MovieImportGetDestinationMediaType);
+ PyMac_PRECHECK(MovieImportGetDestinationMediaType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieImportGetDestinationMediaType(ci,
- &mediaType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, mediaType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieImportGetDestinationMediaType(ci,
+ &mediaType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, mediaType);
+ return _res;
}
static PyObject *Qt_MovieExportToHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Handle dataH;
- Movie theMovie;
- Track onlyThisTrack;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Handle dataH;
+ Movie theMovie;
+ Track onlyThisTrack;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef MovieExportToHandle
- PyMac_PRECHECK(MovieExportToHandle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataH,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &onlyThisTrack,
- &startTime,
- &duration))
- return NULL;
- _rv = MovieExportToHandle(ci,
- dataH,
- theMovie,
- onlyThisTrack,
- startTime,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MovieExportToHandle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataH,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &onlyThisTrack,
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = MovieExportToHandle(ci,
+ dataH,
+ theMovie,
+ onlyThisTrack,
+ startTime,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieExportToFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- FSSpec theFile;
- Movie theMovie;
- Track onlyThisTrack;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ FSSpec theFile;
+ Movie theMovie;
+ Track onlyThisTrack;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef MovieExportToFile
- PyMac_PRECHECK(MovieExportToFile);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
- CmpInstObj_Convert, &ci,
- PyMac_GetFSSpec, &theFile,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &onlyThisTrack,
- &startTime,
- &duration))
- return NULL;
- _rv = MovieExportToFile(ci,
- &theFile,
- theMovie,
- onlyThisTrack,
- startTime,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MovieExportToFile);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFSSpec, &theFile,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &onlyThisTrack,
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = MovieExportToFile(ci,
+ &theFile,
+ theMovie,
+ onlyThisTrack,
+ startTime,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieExportGetAuxiliaryData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Handle dataH;
- OSType handleType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Handle dataH;
+ OSType handleType;
#ifndef MovieExportGetAuxiliaryData
- PyMac_PRECHECK(MovieExportGetAuxiliaryData);
+ PyMac_PRECHECK(MovieExportGetAuxiliaryData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataH))
- return NULL;
- _rv = MovieExportGetAuxiliaryData(ci,
- dataH,
- &handleType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, handleType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataH))
+ return NULL;
+ _rv = MovieExportGetAuxiliaryData(ci,
+ dataH,
+ &handleType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, handleType);
+ return _res;
}
static PyObject *Qt_MovieExportSetSampleDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- SampleDescriptionHandle desc;
- OSType mediaType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ SampleDescriptionHandle desc;
+ OSType mediaType;
#ifndef MovieExportSetSampleDescription
- PyMac_PRECHECK(MovieExportSetSampleDescription);
+ PyMac_PRECHECK(MovieExportSetSampleDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &desc,
- PyMac_GetOSType, &mediaType))
- return NULL;
- _rv = MovieExportSetSampleDescription(ci,
- desc,
- mediaType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &desc,
+ PyMac_GetOSType, &mediaType))
+ return NULL;
+ _rv = MovieExportSetSampleDescription(ci,
+ desc,
+ mediaType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieExportDoUserDialog(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Movie theMovie;
- Track onlyThisTrack;
- TimeValue startTime;
- TimeValue duration;
- Boolean canceled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Movie theMovie;
+ Track onlyThisTrack;
+ TimeValue startTime;
+ TimeValue duration;
+ Boolean canceled;
#ifndef MovieExportDoUserDialog
- PyMac_PRECHECK(MovieExportDoUserDialog);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&ll",
- CmpInstObj_Convert, &ci,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &onlyThisTrack,
- &startTime,
- &duration))
- return NULL;
- _rv = MovieExportDoUserDialog(ci,
- theMovie,
- onlyThisTrack,
- startTime,
- duration,
- &canceled);
- _res = Py_BuildValue("lb",
- _rv,
- canceled);
- return _res;
+ PyMac_PRECHECK(MovieExportDoUserDialog);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &onlyThisTrack,
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = MovieExportDoUserDialog(ci,
+ theMovie,
+ onlyThisTrack,
+ startTime,
+ duration,
+ &canceled);
+ _res = Py_BuildValue("lb",
+ _rv,
+ canceled);
+ return _res;
}
static PyObject *Qt_MovieExportGetCreatorType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- OSType creator;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ OSType creator;
#ifndef MovieExportGetCreatorType
- PyMac_PRECHECK(MovieExportGetCreatorType);
+ PyMac_PRECHECK(MovieExportGetCreatorType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieExportGetCreatorType(ci,
- &creator);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, creator);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieExportGetCreatorType(ci,
+ &creator);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, creator);
+ return _res;
}
static PyObject *Qt_MovieExportToDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Handle dataRef;
- OSType dataRefType;
- Movie theMovie;
- Track onlyThisTrack;
- TimeValue startTime;
- TimeValue duration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
+ Movie theMovie;
+ Track onlyThisTrack;
+ TimeValue startTime;
+ TimeValue duration;
#ifndef MovieExportToDataRef
- PyMac_PRECHECK(MovieExportToDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&O&ll",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &onlyThisTrack,
- &startTime,
- &duration))
- return NULL;
- _rv = MovieExportToDataRef(ci,
- dataRef,
- dataRefType,
- theMovie,
- onlyThisTrack,
- startTime,
- duration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MovieExportToDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&O&ll",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &onlyThisTrack,
+ &startTime,
+ &duration))
+ return NULL;
+ _rv = MovieExportToDataRef(ci,
+ dataRef,
+ dataRefType,
+ theMovie,
+ onlyThisTrack,
+ startTime,
+ duration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieExportFromProceduresToDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef MovieExportFromProceduresToDataRef
- PyMac_PRECHECK(MovieExportFromProceduresToDataRef);
+ PyMac_PRECHECK(MovieExportFromProceduresToDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _rv = MovieExportFromProceduresToDataRef(ci,
- dataRef,
- dataRefType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _rv = MovieExportFromProceduresToDataRef(ci,
+ dataRef,
+ dataRefType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieExportValidate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Movie theMovie;
- Track onlyThisTrack;
- Boolean valid;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Movie theMovie;
+ Track onlyThisTrack;
+ Boolean valid;
#ifndef MovieExportValidate
- PyMac_PRECHECK(MovieExportValidate);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &ci,
- MovieObj_Convert, &theMovie,
- TrackObj_Convert, &onlyThisTrack))
- return NULL;
- _rv = MovieExportValidate(ci,
- theMovie,
- onlyThisTrack,
- &valid);
- _res = Py_BuildValue("lb",
- _rv,
- valid);
- return _res;
+ PyMac_PRECHECK(MovieExportValidate);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &ci,
+ MovieObj_Convert, &theMovie,
+ TrackObj_Convert, &onlyThisTrack))
+ return NULL;
+ _rv = MovieExportValidate(ci,
+ theMovie,
+ onlyThisTrack,
+ &valid);
+ _res = Py_BuildValue("lb",
+ _rv,
+ valid);
+ return _res;
}
static PyObject *Qt_MovieExportGetFileNameExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- OSType extension;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ OSType extension;
#ifndef MovieExportGetFileNameExtension
- PyMac_PRECHECK(MovieExportGetFileNameExtension);
+ PyMac_PRECHECK(MovieExportGetFileNameExtension);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieExportGetFileNameExtension(ci,
- &extension);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, extension);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieExportGetFileNameExtension(ci,
+ &extension);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, extension);
+ return _res;
}
static PyObject *Qt_MovieExportGetShortFileTypeString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- Str255 typeString;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ Str255 typeString;
#ifndef MovieExportGetShortFileTypeString
- PyMac_PRECHECK(MovieExportGetShortFileTypeString);
+ PyMac_PRECHECK(MovieExportGetShortFileTypeString);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetStr255, typeString))
- return NULL;
- _rv = MovieExportGetShortFileTypeString(ci,
- typeString);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetStr255, typeString))
+ return NULL;
+ _rv = MovieExportGetShortFileTypeString(ci,
+ typeString);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MovieExportGetSourceMediaType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MovieExportComponent ci;
- OSType mediaType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MovieExportComponent ci;
+ OSType mediaType;
#ifndef MovieExportGetSourceMediaType
- PyMac_PRECHECK(MovieExportGetSourceMediaType);
+ PyMac_PRECHECK(MovieExportGetSourceMediaType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MovieExportGetSourceMediaType(ci,
- &mediaType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, mediaType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MovieExportGetSourceMediaType(ci,
+ &mediaType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, mediaType);
+ return _res;
}
static PyObject *Qt_TextExportGetTimeFraction(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TextExportComponent ci;
- long movieTimeFraction;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TextExportComponent ci;
+ long movieTimeFraction;
#ifndef TextExportGetTimeFraction
- PyMac_PRECHECK(TextExportGetTimeFraction);
+ PyMac_PRECHECK(TextExportGetTimeFraction);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = TextExportGetTimeFraction(ci,
- &movieTimeFraction);
- _res = Py_BuildValue("ll",
- _rv,
- movieTimeFraction);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = TextExportGetTimeFraction(ci,
+ &movieTimeFraction);
+ _res = Py_BuildValue("ll",
+ _rv,
+ movieTimeFraction);
+ return _res;
}
static PyObject *Qt_TextExportSetTimeFraction(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TextExportComponent ci;
- long movieTimeFraction;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TextExportComponent ci;
+ long movieTimeFraction;
#ifndef TextExportSetTimeFraction
- PyMac_PRECHECK(TextExportSetTimeFraction);
+ PyMac_PRECHECK(TextExportSetTimeFraction);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &movieTimeFraction))
- return NULL;
- _rv = TextExportSetTimeFraction(ci,
- movieTimeFraction);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &movieTimeFraction))
+ return NULL;
+ _rv = TextExportSetTimeFraction(ci,
+ movieTimeFraction);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TextExportGetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TextExportComponent ci;
- long setting;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TextExportComponent ci;
+ long setting;
#ifndef TextExportGetSettings
- PyMac_PRECHECK(TextExportGetSettings);
+ PyMac_PRECHECK(TextExportGetSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = TextExportGetSettings(ci,
- &setting);
- _res = Py_BuildValue("ll",
- _rv,
- setting);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = TextExportGetSettings(ci,
+ &setting);
+ _res = Py_BuildValue("ll",
+ _rv,
+ setting);
+ return _res;
}
static PyObject *Qt_TextExportSetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TextExportComponent ci;
- long setting;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TextExportComponent ci;
+ long setting;
#ifndef TextExportSetSettings
- PyMac_PRECHECK(TextExportSetSettings);
+ PyMac_PRECHECK(TextExportSetSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &setting))
- return NULL;
- _rv = TextExportSetSettings(ci,
- setting);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &setting))
+ return NULL;
+ _rv = TextExportSetSettings(ci,
+ setting);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MIDIImportGetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TextExportComponent ci;
- long setting;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TextExportComponent ci;
+ long setting;
#ifndef MIDIImportGetSettings
- PyMac_PRECHECK(MIDIImportGetSettings);
+ PyMac_PRECHECK(MIDIImportGetSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = MIDIImportGetSettings(ci,
- &setting);
- _res = Py_BuildValue("ll",
- _rv,
- setting);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = MIDIImportGetSettings(ci,
+ &setting);
+ _res = Py_BuildValue("ll",
+ _rv,
+ setting);
+ return _res;
}
static PyObject *Qt_MIDIImportSetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TextExportComponent ci;
- long setting;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TextExportComponent ci;
+ long setting;
#ifndef MIDIImportSetSettings
- PyMac_PRECHECK(MIDIImportSetSettings);
+ PyMac_PRECHECK(MIDIImportSetSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &setting))
- return NULL;
- _rv = MIDIImportSetSettings(ci,
- setting);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &setting))
+ return NULL;
+ _rv = MIDIImportSetSettings(ci,
+ setting);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImageImportSetSequenceEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicImageMovieImportComponent ci;
- Boolean enable;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicImageMovieImportComponent ci;
+ Boolean enable;
#ifndef GraphicsImageImportSetSequenceEnabled
- PyMac_PRECHECK(GraphicsImageImportSetSequenceEnabled);
+ PyMac_PRECHECK(GraphicsImageImportSetSequenceEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &enable))
- return NULL;
- _rv = GraphicsImageImportSetSequenceEnabled(ci,
- enable);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &enable))
+ return NULL;
+ _rv = GraphicsImageImportSetSequenceEnabled(ci,
+ enable);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_GraphicsImageImportGetSequenceEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- GraphicImageMovieImportComponent ci;
- Boolean enable;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ GraphicImageMovieImportComponent ci;
+ Boolean enable;
#ifndef GraphicsImageImportGetSequenceEnabled
- PyMac_PRECHECK(GraphicsImageImportGetSequenceEnabled);
+ PyMac_PRECHECK(GraphicsImageImportGetSequenceEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = GraphicsImageImportGetSequenceEnabled(ci,
- &enable);
- _res = Py_BuildValue("lb",
- _rv,
- enable);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = GraphicsImageImportGetSequenceEnabled(ci,
+ &enable);
+ _res = Py_BuildValue("lb",
+ _rv,
+ enable);
+ return _res;
}
static PyObject *Qt_PreviewShowData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- pnotComponent p;
- OSType dataType;
- Handle data;
- Rect inHere;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ pnotComponent p;
+ OSType dataType;
+ Handle data;
+ Rect inHere;
#ifndef PreviewShowData
- PyMac_PRECHECK(PreviewShowData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &p,
- PyMac_GetOSType, &dataType,
- ResObj_Convert, &data,
- PyMac_GetRect, &inHere))
- return NULL;
- _rv = PreviewShowData(p,
- dataType,
- data,
- &inHere);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(PreviewShowData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &p,
+ PyMac_GetOSType, &dataType,
+ ResObj_Convert, &data,
+ PyMac_GetRect, &inHere))
+ return NULL;
+ _rv = PreviewShowData(p,
+ dataType,
+ data,
+ &inHere);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_PreviewMakePreviewReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- pnotComponent p;
- OSType previewType;
- short resID;
- FSSpec sourceFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ pnotComponent p;
+ OSType previewType;
+ short resID;
+ FSSpec sourceFile;
#ifndef PreviewMakePreviewReference
- PyMac_PRECHECK(PreviewMakePreviewReference);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &p,
- PyMac_GetFSSpec, &sourceFile))
- return NULL;
- _rv = PreviewMakePreviewReference(p,
- &previewType,
- &resID,
- &sourceFile);
- _res = Py_BuildValue("lO&h",
- _rv,
- PyMac_BuildOSType, previewType,
- resID);
- return _res;
+ PyMac_PRECHECK(PreviewMakePreviewReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &p,
+ PyMac_GetFSSpec, &sourceFile))
+ return NULL;
+ _rv = PreviewMakePreviewReference(p,
+ &previewType,
+ &resID,
+ &sourceFile);
+ _res = Py_BuildValue("lO&h",
+ _rv,
+ PyMac_BuildOSType, previewType,
+ resID);
+ return _res;
}
static PyObject *Qt_PreviewEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- pnotComponent p;
- EventRecord e;
- Boolean handledEvent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ pnotComponent p;
+ EventRecord e;
+ Boolean handledEvent;
#ifndef PreviewEvent
- PyMac_PRECHECK(PreviewEvent);
+ PyMac_PRECHECK(PreviewEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &p))
- return NULL;
- _rv = PreviewEvent(p,
- &e,
- &handledEvent);
- _res = Py_BuildValue("lO&b",
- _rv,
- PyMac_BuildEventRecord, &e,
- handledEvent);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &p))
+ return NULL;
+ _rv = PreviewEvent(p,
+ &e,
+ &handledEvent);
+ _res = Py_BuildValue("lO&b",
+ _rv,
+ PyMac_BuildEventRecord, &e,
+ handledEvent);
+ return _res;
}
static PyObject *Qt_DataCodecDecompress(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataCodecComponent dc;
- void * srcData;
- UInt32 srcSize;
- void * dstData;
- UInt32 dstBufferSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataCodecComponent dc;
+ void * srcData;
+ UInt32 srcSize;
+ void * dstData;
+ UInt32 dstBufferSize;
#ifndef DataCodecDecompress
- PyMac_PRECHECK(DataCodecDecompress);
-#endif
- if (!PyArg_ParseTuple(_args, "O&slsl",
- CmpInstObj_Convert, &dc,
- &srcData,
- &srcSize,
- &dstData,
- &dstBufferSize))
- return NULL;
- _rv = DataCodecDecompress(dc,
- srcData,
- srcSize,
- dstData,
- dstBufferSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataCodecDecompress);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&slsl",
+ CmpInstObj_Convert, &dc,
+ &srcData,
+ &srcSize,
+ &dstData,
+ &dstBufferSize))
+ return NULL;
+ _rv = DataCodecDecompress(dc,
+ srcData,
+ srcSize,
+ dstData,
+ dstBufferSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataCodecGetCompressBufferSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataCodecComponent dc;
- UInt32 srcSize;
- UInt32 dstSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataCodecComponent dc;
+ UInt32 srcSize;
+ UInt32 dstSize;
#ifndef DataCodecGetCompressBufferSize
- PyMac_PRECHECK(DataCodecGetCompressBufferSize);
+ PyMac_PRECHECK(DataCodecGetCompressBufferSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dc,
- &srcSize))
- return NULL;
- _rv = DataCodecGetCompressBufferSize(dc,
- srcSize,
- &dstSize);
- _res = Py_BuildValue("ll",
- _rv,
- dstSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dc,
+ &srcSize))
+ return NULL;
+ _rv = DataCodecGetCompressBufferSize(dc,
+ srcSize,
+ &dstSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ dstSize);
+ return _res;
}
static PyObject *Qt_DataCodecCompress(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataCodecComponent dc;
- void * srcData;
- UInt32 srcSize;
- void * dstData;
- UInt32 dstBufferSize;
- UInt32 actualDstSize;
- UInt32 decompressSlop;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataCodecComponent dc;
+ void * srcData;
+ UInt32 srcSize;
+ void * dstData;
+ UInt32 dstBufferSize;
+ UInt32 actualDstSize;
+ UInt32 decompressSlop;
#ifndef DataCodecCompress
- PyMac_PRECHECK(DataCodecCompress);
-#endif
- if (!PyArg_ParseTuple(_args, "O&slsl",
- CmpInstObj_Convert, &dc,
- &srcData,
- &srcSize,
- &dstData,
- &dstBufferSize))
- return NULL;
- _rv = DataCodecCompress(dc,
- srcData,
- srcSize,
- dstData,
- dstBufferSize,
- &actualDstSize,
- &decompressSlop);
- _res = Py_BuildValue("lll",
- _rv,
- actualDstSize,
- decompressSlop);
- return _res;
+ PyMac_PRECHECK(DataCodecCompress);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&slsl",
+ CmpInstObj_Convert, &dc,
+ &srcData,
+ &srcSize,
+ &dstData,
+ &dstBufferSize))
+ return NULL;
+ _rv = DataCodecCompress(dc,
+ srcData,
+ srcSize,
+ dstData,
+ dstBufferSize,
+ &actualDstSize,
+ &decompressSlop);
+ _res = Py_BuildValue("lll",
+ _rv,
+ actualDstSize,
+ decompressSlop);
+ return _res;
}
static PyObject *Qt_DataCodecBeginInterruptSafe(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataCodecComponent dc;
- unsigned long maxSrcSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataCodecComponent dc;
+ unsigned long maxSrcSize;
#ifndef DataCodecBeginInterruptSafe
- PyMac_PRECHECK(DataCodecBeginInterruptSafe);
+ PyMac_PRECHECK(DataCodecBeginInterruptSafe);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dc,
- &maxSrcSize))
- return NULL;
- _rv = DataCodecBeginInterruptSafe(dc,
- maxSrcSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dc,
+ &maxSrcSize))
+ return NULL;
+ _rv = DataCodecBeginInterruptSafe(dc,
+ maxSrcSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataCodecEndInterruptSafe(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataCodecComponent dc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataCodecComponent dc;
#ifndef DataCodecEndInterruptSafe
- PyMac_PRECHECK(DataCodecEndInterruptSafe);
+ PyMac_PRECHECK(DataCodecEndInterruptSafe);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dc))
- return NULL;
- _rv = DataCodecEndInterruptSafe(dc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dc))
+ return NULL;
+ _rv = DataCodecEndInterruptSafe(dc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle h;
- long hOffset;
- long offset;
- long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle h;
+ long hOffset;
+ long offset;
+ long size;
#ifndef DataHGetData
- PyMac_PRECHECK(DataHGetData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&lll",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &h,
- &hOffset,
- &offset,
- &size))
- return NULL;
- _rv = DataHGetData(dh,
- h,
- hOffset,
- offset,
- size);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataHGetData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&lll",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &h,
+ &hOffset,
+ &offset,
+ &size))
+ return NULL;
+ _rv = DataHGetData(dh,
+ h,
+ hOffset,
+ offset,
+ size);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHPutData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle h;
- long hOffset;
- long offset;
- long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle h;
+ long hOffset;
+ long offset;
+ long size;
#ifndef DataHPutData
- PyMac_PRECHECK(DataHPutData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&ll",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &h,
- &hOffset,
- &size))
- return NULL;
- _rv = DataHPutData(dh,
- h,
- hOffset,
- &offset,
- size);
- _res = Py_BuildValue("ll",
- _rv,
- offset);
- return _res;
+ PyMac_PRECHECK(DataHPutData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&ll",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &h,
+ &hOffset,
+ &size))
+ return NULL;
+ _rv = DataHPutData(dh,
+ h,
+ hOffset,
+ &offset,
+ size);
+ _res = Py_BuildValue("ll",
+ _rv,
+ offset);
+ return _res;
}
static PyObject *Qt_DataHFlushData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHFlushData
- PyMac_PRECHECK(DataHFlushData);
+ PyMac_PRECHECK(DataHFlushData);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHFlushData(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHFlushData(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHOpenForWrite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHOpenForWrite
- PyMac_PRECHECK(DataHOpenForWrite);
+ PyMac_PRECHECK(DataHOpenForWrite);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHOpenForWrite(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHOpenForWrite(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHCloseForWrite(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHCloseForWrite
- PyMac_PRECHECK(DataHCloseForWrite);
+ PyMac_PRECHECK(DataHCloseForWrite);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHCloseForWrite(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHCloseForWrite(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHOpenForRead(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHOpenForRead
- PyMac_PRECHECK(DataHOpenForRead);
+ PyMac_PRECHECK(DataHOpenForRead);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHOpenForRead(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHOpenForRead(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHCloseForRead(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHCloseForRead
- PyMac_PRECHECK(DataHCloseForRead);
+ PyMac_PRECHECK(DataHCloseForRead);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHCloseForRead(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHCloseForRead(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHSetDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle dataRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle dataRef;
#ifndef DataHSetDataRef
- PyMac_PRECHECK(DataHSetDataRef);
+ PyMac_PRECHECK(DataHSetDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &dataRef))
- return NULL;
- _rv = DataHSetDataRef(dh,
- dataRef);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &dataRef))
+ return NULL;
+ _rv = DataHSetDataRef(dh,
+ dataRef);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle dataRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle dataRef;
#ifndef DataHGetDataRef
- PyMac_PRECHECK(DataHGetDataRef);
+ PyMac_PRECHECK(DataHGetDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetDataRef(dh,
- &dataRef);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, dataRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetDataRef(dh,
+ &dataRef);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, dataRef);
+ return _res;
}
static PyObject *Qt_DataHCompareDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle dataRef;
- Boolean equal;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle dataRef;
+ Boolean equal;
#ifndef DataHCompareDataRef
- PyMac_PRECHECK(DataHCompareDataRef);
+ PyMac_PRECHECK(DataHCompareDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &dataRef))
- return NULL;
- _rv = DataHCompareDataRef(dh,
- dataRef,
- &equal);
- _res = Py_BuildValue("lb",
- _rv,
- equal);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &dataRef))
+ return NULL;
+ _rv = DataHCompareDataRef(dh,
+ dataRef,
+ &equal);
+ _res = Py_BuildValue("lb",
+ _rv,
+ equal);
+ return _res;
}
static PyObject *Qt_DataHTask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHTask
- PyMac_PRECHECK(DataHTask);
+ PyMac_PRECHECK(DataHTask);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHTask(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHTask(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHFinishData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Ptr PlaceToPutDataPtr;
- Boolean Cancel;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Ptr PlaceToPutDataPtr;
+ Boolean Cancel;
#ifndef DataHFinishData
- PyMac_PRECHECK(DataHFinishData);
+ PyMac_PRECHECK(DataHFinishData);
#endif
- if (!PyArg_ParseTuple(_args, "O&sb",
- CmpInstObj_Convert, &dh,
- &PlaceToPutDataPtr,
- &Cancel))
- return NULL;
- _rv = DataHFinishData(dh,
- PlaceToPutDataPtr,
- Cancel);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&sb",
+ CmpInstObj_Convert, &dh,
+ &PlaceToPutDataPtr,
+ &Cancel))
+ return NULL;
+ _rv = DataHFinishData(dh,
+ PlaceToPutDataPtr,
+ Cancel);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHFlushCache(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHFlushCache
- PyMac_PRECHECK(DataHFlushCache);
+ PyMac_PRECHECK(DataHFlushCache);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHFlushCache(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHFlushCache(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHResolveDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle theDataRef;
- Boolean wasChanged;
- Boolean userInterfaceAllowed;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle theDataRef;
+ Boolean wasChanged;
+ Boolean userInterfaceAllowed;
#ifndef DataHResolveDataRef
- PyMac_PRECHECK(DataHResolveDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&b",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &theDataRef,
- &userInterfaceAllowed))
- return NULL;
- _rv = DataHResolveDataRef(dh,
- theDataRef,
- &wasChanged,
- userInterfaceAllowed);
- _res = Py_BuildValue("lb",
- _rv,
- wasChanged);
- return _res;
+ PyMac_PRECHECK(DataHResolveDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&b",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &theDataRef,
+ &userInterfaceAllowed))
+ return NULL;
+ _rv = DataHResolveDataRef(dh,
+ theDataRef,
+ &wasChanged,
+ userInterfaceAllowed);
+ _res = Py_BuildValue("lb",
+ _rv,
+ wasChanged);
+ return _res;
}
static PyObject *Qt_DataHGetFileSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long fileSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long fileSize;
#ifndef DataHGetFileSize
- PyMac_PRECHECK(DataHGetFileSize);
+ PyMac_PRECHECK(DataHGetFileSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetFileSize(dh,
- &fileSize);
- _res = Py_BuildValue("ll",
- _rv,
- fileSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetFileSize(dh,
+ &fileSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ fileSize);
+ return _res;
}
static PyObject *Qt_DataHCanUseDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle dataRef;
- long useFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle dataRef;
+ long useFlags;
#ifndef DataHCanUseDataRef
- PyMac_PRECHECK(DataHCanUseDataRef);
+ PyMac_PRECHECK(DataHCanUseDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &dataRef))
- return NULL;
- _rv = DataHCanUseDataRef(dh,
- dataRef,
- &useFlags);
- _res = Py_BuildValue("ll",
- _rv,
- useFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &dataRef))
+ return NULL;
+ _rv = DataHCanUseDataRef(dh,
+ dataRef,
+ &useFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ useFlags);
+ return _res;
}
static PyObject *Qt_DataHPreextend(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- unsigned long maxToAdd;
- unsigned long spaceAdded;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ unsigned long maxToAdd;
+ unsigned long spaceAdded;
#ifndef DataHPreextend
- PyMac_PRECHECK(DataHPreextend);
+ PyMac_PRECHECK(DataHPreextend);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &maxToAdd))
- return NULL;
- _rv = DataHPreextend(dh,
- maxToAdd,
- &spaceAdded);
- _res = Py_BuildValue("ll",
- _rv,
- spaceAdded);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &maxToAdd))
+ return NULL;
+ _rv = DataHPreextend(dh,
+ maxToAdd,
+ &spaceAdded);
+ _res = Py_BuildValue("ll",
+ _rv,
+ spaceAdded);
+ return _res;
}
static PyObject *Qt_DataHSetFileSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long fileSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long fileSize;
#ifndef DataHSetFileSize
- PyMac_PRECHECK(DataHSetFileSize);
+ PyMac_PRECHECK(DataHSetFileSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &fileSize))
- return NULL;
- _rv = DataHSetFileSize(dh,
- fileSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &fileSize))
+ return NULL;
+ _rv = DataHSetFileSize(dh,
+ fileSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetFreeSpace(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- unsigned long freeSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ unsigned long freeSize;
#ifndef DataHGetFreeSpace
- PyMac_PRECHECK(DataHGetFreeSpace);
+ PyMac_PRECHECK(DataHGetFreeSpace);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetFreeSpace(dh,
- &freeSize);
- _res = Py_BuildValue("ll",
- _rv,
- freeSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetFreeSpace(dh,
+ &freeSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ freeSize);
+ return _res;
}
static PyObject *Qt_DataHCreateFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- OSType creator;
- Boolean deleteExisting;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ OSType creator;
+ Boolean deleteExisting;
#ifndef DataHCreateFile
- PyMac_PRECHECK(DataHCreateFile);
+ PyMac_PRECHECK(DataHCreateFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&b",
- CmpInstObj_Convert, &dh,
- PyMac_GetOSType, &creator,
- &deleteExisting))
- return NULL;
- _rv = DataHCreateFile(dh,
- creator,
- deleteExisting);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&b",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetOSType, &creator,
+ &deleteExisting))
+ return NULL;
+ _rv = DataHCreateFile(dh,
+ creator,
+ deleteExisting);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetPreferredBlockSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long blockSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long blockSize;
#ifndef DataHGetPreferredBlockSize
- PyMac_PRECHECK(DataHGetPreferredBlockSize);
+ PyMac_PRECHECK(DataHGetPreferredBlockSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetPreferredBlockSize(dh,
- &blockSize);
- _res = Py_BuildValue("ll",
- _rv,
- blockSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetPreferredBlockSize(dh,
+ &blockSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ blockSize);
+ return _res;
}
static PyObject *Qt_DataHGetDeviceIndex(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long deviceIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long deviceIndex;
#ifndef DataHGetDeviceIndex
- PyMac_PRECHECK(DataHGetDeviceIndex);
+ PyMac_PRECHECK(DataHGetDeviceIndex);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetDeviceIndex(dh,
- &deviceIndex);
- _res = Py_BuildValue("ll",
- _rv,
- deviceIndex);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetDeviceIndex(dh,
+ &deviceIndex);
+ _res = Py_BuildValue("ll",
+ _rv,
+ deviceIndex);
+ return _res;
}
static PyObject *Qt_DataHIsStreamingDataHandler(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Boolean yes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Boolean yes;
#ifndef DataHIsStreamingDataHandler
- PyMac_PRECHECK(DataHIsStreamingDataHandler);
+ PyMac_PRECHECK(DataHIsStreamingDataHandler);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHIsStreamingDataHandler(dh,
- &yes);
- _res = Py_BuildValue("lb",
- _rv,
- yes);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHIsStreamingDataHandler(dh,
+ &yes);
+ _res = Py_BuildValue("lb",
+ _rv,
+ yes);
+ return _res;
}
static PyObject *Qt_DataHGetDataInBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long startOffset;
- long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long startOffset;
+ long size;
#ifndef DataHGetDataInBuffer
- PyMac_PRECHECK(DataHGetDataInBuffer);
+ PyMac_PRECHECK(DataHGetDataInBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &startOffset))
- return NULL;
- _rv = DataHGetDataInBuffer(dh,
- startOffset,
- &size);
- _res = Py_BuildValue("ll",
- _rv,
- size);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &startOffset))
+ return NULL;
+ _rv = DataHGetDataInBuffer(dh,
+ startOffset,
+ &size);
+ _res = Py_BuildValue("ll",
+ _rv,
+ size);
+ return _res;
}
static PyObject *Qt_DataHGetScheduleAheadTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long millisecs;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long millisecs;
#ifndef DataHGetScheduleAheadTime
- PyMac_PRECHECK(DataHGetScheduleAheadTime);
+ PyMac_PRECHECK(DataHGetScheduleAheadTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetScheduleAheadTime(dh,
- &millisecs);
- _res = Py_BuildValue("ll",
- _rv,
- millisecs);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetScheduleAheadTime(dh,
+ &millisecs);
+ _res = Py_BuildValue("ll",
+ _rv,
+ millisecs);
+ return _res;
}
static PyObject *Qt_DataHSetCacheSizeLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Size cacheSizeLimit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Size cacheSizeLimit;
#ifndef DataHSetCacheSizeLimit
- PyMac_PRECHECK(DataHSetCacheSizeLimit);
+ PyMac_PRECHECK(DataHSetCacheSizeLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &cacheSizeLimit))
- return NULL;
- _rv = DataHSetCacheSizeLimit(dh,
- cacheSizeLimit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &cacheSizeLimit))
+ return NULL;
+ _rv = DataHSetCacheSizeLimit(dh,
+ cacheSizeLimit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetCacheSizeLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Size cacheSizeLimit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Size cacheSizeLimit;
#ifndef DataHGetCacheSizeLimit
- PyMac_PRECHECK(DataHGetCacheSizeLimit);
+ PyMac_PRECHECK(DataHGetCacheSizeLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetCacheSizeLimit(dh,
- &cacheSizeLimit);
- _res = Py_BuildValue("ll",
- _rv,
- cacheSizeLimit);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetCacheSizeLimit(dh,
+ &cacheSizeLimit);
+ _res = Py_BuildValue("ll",
+ _rv,
+ cacheSizeLimit);
+ return _res;
}
static PyObject *Qt_DataHGetMovie(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Movie theMovie;
- short id;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Movie theMovie;
+ short id;
#ifndef DataHGetMovie
- PyMac_PRECHECK(DataHGetMovie);
+ PyMac_PRECHECK(DataHGetMovie);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetMovie(dh,
- &theMovie,
- &id);
- _res = Py_BuildValue("lO&h",
- _rv,
- MovieObj_New, theMovie,
- id);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetMovie(dh,
+ &theMovie,
+ &id);
+ _res = Py_BuildValue("lO&h",
+ _rv,
+ MovieObj_New, theMovie,
+ id);
+ return _res;
}
static PyObject *Qt_DataHAddMovie(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Movie theMovie;
- short id;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Movie theMovie;
+ short id;
#ifndef DataHAddMovie
- PyMac_PRECHECK(DataHAddMovie);
+ PyMac_PRECHECK(DataHAddMovie);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- MovieObj_Convert, &theMovie))
- return NULL;
- _rv = DataHAddMovie(dh,
- theMovie,
- &id);
- _res = Py_BuildValue("lh",
- _rv,
- id);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ MovieObj_Convert, &theMovie))
+ return NULL;
+ _rv = DataHAddMovie(dh,
+ theMovie,
+ &id);
+ _res = Py_BuildValue("lh",
+ _rv,
+ id);
+ return _res;
}
static PyObject *Qt_DataHUpdateMovie(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Movie theMovie;
- short id;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Movie theMovie;
+ short id;
#ifndef DataHUpdateMovie
- PyMac_PRECHECK(DataHUpdateMovie);
+ PyMac_PRECHECK(DataHUpdateMovie);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &dh,
- MovieObj_Convert, &theMovie,
- &id))
- return NULL;
- _rv = DataHUpdateMovie(dh,
- theMovie,
- id);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &dh,
+ MovieObj_Convert, &theMovie,
+ &id))
+ return NULL;
+ _rv = DataHUpdateMovie(dh,
+ theMovie,
+ id);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHDoesBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Boolean buffersReads;
- Boolean buffersWrites;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Boolean buffersReads;
+ Boolean buffersWrites;
#ifndef DataHDoesBuffer
- PyMac_PRECHECK(DataHDoesBuffer);
+ PyMac_PRECHECK(DataHDoesBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHDoesBuffer(dh,
- &buffersReads,
- &buffersWrites);
- _res = Py_BuildValue("lbb",
- _rv,
- buffersReads,
- buffersWrites);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHDoesBuffer(dh,
+ &buffersReads,
+ &buffersWrites);
+ _res = Py_BuildValue("lbb",
+ _rv,
+ buffersReads,
+ buffersWrites);
+ return _res;
}
static PyObject *Qt_DataHGetFileName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Str255 str;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Str255 str;
#ifndef DataHGetFileName
- PyMac_PRECHECK(DataHGetFileName);
+ PyMac_PRECHECK(DataHGetFileName);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_GetStr255, str))
- return NULL;
- _rv = DataHGetFileName(dh,
- str);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetStr255, str))
+ return NULL;
+ _rv = DataHGetFileName(dh,
+ str);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetAvailableFileSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long fileSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long fileSize;
#ifndef DataHGetAvailableFileSize
- PyMac_PRECHECK(DataHGetAvailableFileSize);
+ PyMac_PRECHECK(DataHGetAvailableFileSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetAvailableFileSize(dh,
- &fileSize);
- _res = Py_BuildValue("ll",
- _rv,
- fileSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetAvailableFileSize(dh,
+ &fileSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ fileSize);
+ return _res;
}
static PyObject *Qt_DataHGetMacOSFileType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- OSType fileType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ OSType fileType;
#ifndef DataHGetMacOSFileType
- PyMac_PRECHECK(DataHGetMacOSFileType);
+ PyMac_PRECHECK(DataHGetMacOSFileType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetMacOSFileType(dh,
- &fileType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, fileType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetMacOSFileType(dh,
+ &fileType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, fileType);
+ return _res;
}
static PyObject *Qt_DataHGetMIMEType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Str255 mimeType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Str255 mimeType;
#ifndef DataHGetMIMEType
- PyMac_PRECHECK(DataHGetMIMEType);
+ PyMac_PRECHECK(DataHGetMIMEType);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_GetStr255, mimeType))
- return NULL;
- _rv = DataHGetMIMEType(dh,
- mimeType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetStr255, mimeType))
+ return NULL;
+ _rv = DataHGetMIMEType(dh,
+ mimeType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHSetDataRefWithAnchor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle anchorDataRef;
- OSType dataRefType;
- Handle dataRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle anchorDataRef;
+ OSType dataRefType;
+ Handle dataRef;
#ifndef DataHSetDataRefWithAnchor
- PyMac_PRECHECK(DataHSetDataRefWithAnchor);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &anchorDataRef,
- PyMac_GetOSType, &dataRefType,
- ResObj_Convert, &dataRef))
- return NULL;
- _rv = DataHSetDataRefWithAnchor(dh,
- anchorDataRef,
- dataRefType,
- dataRef);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataHSetDataRefWithAnchor);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &anchorDataRef,
+ PyMac_GetOSType, &dataRefType,
+ ResObj_Convert, &dataRef))
+ return NULL;
+ _rv = DataHSetDataRefWithAnchor(dh,
+ anchorDataRef,
+ dataRefType,
+ dataRef);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetDataRefWithAnchor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle anchorDataRef;
- OSType dataRefType;
- Handle dataRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle anchorDataRef;
+ OSType dataRefType;
+ Handle dataRef;
#ifndef DataHGetDataRefWithAnchor
- PyMac_PRECHECK(DataHGetDataRefWithAnchor);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &anchorDataRef,
- PyMac_GetOSType, &dataRefType))
- return NULL;
- _rv = DataHGetDataRefWithAnchor(dh,
- anchorDataRef,
- dataRefType,
- &dataRef);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, dataRef);
- return _res;
+ PyMac_PRECHECK(DataHGetDataRefWithAnchor);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &anchorDataRef,
+ PyMac_GetOSType, &dataRefType))
+ return NULL;
+ _rv = DataHGetDataRefWithAnchor(dh,
+ anchorDataRef,
+ dataRefType,
+ &dataRef);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, dataRef);
+ return _res;
}
static PyObject *Qt_DataHSetMacOSFileType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- OSType fileType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ OSType fileType;
#ifndef DataHSetMacOSFileType
- PyMac_PRECHECK(DataHSetMacOSFileType);
+ PyMac_PRECHECK(DataHSetMacOSFileType);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_GetOSType, &fileType))
- return NULL;
- _rv = DataHSetMacOSFileType(dh,
- fileType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetOSType, &fileType))
+ return NULL;
+ _rv = DataHSetMacOSFileType(dh,
+ fileType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHSetTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- TimeBase tb;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ TimeBase tb;
#ifndef DataHSetTimeBase
- PyMac_PRECHECK(DataHSetTimeBase);
+ PyMac_PRECHECK(DataHSetTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- TimeBaseObj_Convert, &tb))
- return NULL;
- _rv = DataHSetTimeBase(dh,
- tb);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ TimeBaseObj_Convert, &tb))
+ return NULL;
+ _rv = DataHSetTimeBase(dh,
+ tb);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetInfoFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- UInt32 flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ UInt32 flags;
#ifndef DataHGetInfoFlags
- PyMac_PRECHECK(DataHGetInfoFlags);
+ PyMac_PRECHECK(DataHGetInfoFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetInfoFlags(dh,
- &flags);
- _res = Py_BuildValue("ll",
- _rv,
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetInfoFlags(dh,
+ &flags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flags);
+ return _res;
}
static PyObject *Qt_DataHGetFileSize64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- wide fileSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ wide fileSize;
#ifndef DataHGetFileSize64
- PyMac_PRECHECK(DataHGetFileSize64);
+ PyMac_PRECHECK(DataHGetFileSize64);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetFileSize64(dh,
- &fileSize);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, fileSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetFileSize64(dh,
+ &fileSize);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, fileSize);
+ return _res;
}
static PyObject *Qt_DataHPreextend64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- wide maxToAdd;
- wide spaceAdded;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ wide maxToAdd;
+ wide spaceAdded;
#ifndef DataHPreextend64
- PyMac_PRECHECK(DataHPreextend64);
+ PyMac_PRECHECK(DataHPreextend64);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_Getwide, &maxToAdd))
- return NULL;
- _rv = DataHPreextend64(dh,
- &maxToAdd,
- &spaceAdded);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, spaceAdded);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_Getwide, &maxToAdd))
+ return NULL;
+ _rv = DataHPreextend64(dh,
+ &maxToAdd,
+ &spaceAdded);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, spaceAdded);
+ return _res;
}
static PyObject *Qt_DataHSetFileSize64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- wide fileSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ wide fileSize;
#ifndef DataHSetFileSize64
- PyMac_PRECHECK(DataHSetFileSize64);
+ PyMac_PRECHECK(DataHSetFileSize64);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_Getwide, &fileSize))
- return NULL;
- _rv = DataHSetFileSize64(dh,
- &fileSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_Getwide, &fileSize))
+ return NULL;
+ _rv = DataHSetFileSize64(dh,
+ &fileSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetFreeSpace64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- wide freeSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ wide freeSize;
#ifndef DataHGetFreeSpace64
- PyMac_PRECHECK(DataHGetFreeSpace64);
+ PyMac_PRECHECK(DataHGetFreeSpace64);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetFreeSpace64(dh,
- &freeSize);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, freeSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetFreeSpace64(dh,
+ &freeSize);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, freeSize);
+ return _res;
}
static PyObject *Qt_DataHAppend64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- void * data;
- wide fileOffset;
- unsigned long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ void * data;
+ wide fileOffset;
+ unsigned long size;
#ifndef DataHAppend64
- PyMac_PRECHECK(DataHAppend64);
-#endif
- if (!PyArg_ParseTuple(_args, "O&sl",
- CmpInstObj_Convert, &dh,
- &data,
- &size))
- return NULL;
- _rv = DataHAppend64(dh,
- data,
- &fileOffset,
- size);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, fileOffset);
- return _res;
+ PyMac_PRECHECK(DataHAppend64);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&sl",
+ CmpInstObj_Convert, &dh,
+ &data,
+ &size))
+ return NULL;
+ _rv = DataHAppend64(dh,
+ data,
+ &fileOffset,
+ size);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, fileOffset);
+ return _res;
}
static PyObject *Qt_DataHPollRead(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- void * dataPtr;
- UInt32 dataSizeSoFar;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ void * dataPtr;
+ UInt32 dataSizeSoFar;
#ifndef DataHPollRead
- PyMac_PRECHECK(DataHPollRead);
+ PyMac_PRECHECK(DataHPollRead);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &dh,
- &dataPtr))
- return NULL;
- _rv = DataHPollRead(dh,
- dataPtr,
- &dataSizeSoFar);
- _res = Py_BuildValue("ll",
- _rv,
- dataSizeSoFar);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &dh,
+ &dataPtr))
+ return NULL;
+ _rv = DataHPollRead(dh,
+ dataPtr,
+ &dataSizeSoFar);
+ _res = Py_BuildValue("ll",
+ _rv,
+ dataSizeSoFar);
+ return _res;
}
static PyObject *Qt_DataHGetDataAvailability(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long offset;
- long len;
- long missing_offset;
- long missing_len;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long offset;
+ long len;
+ long missing_offset;
+ long missing_len;
#ifndef DataHGetDataAvailability
- PyMac_PRECHECK(DataHGetDataAvailability);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &dh,
- &offset,
- &len))
- return NULL;
- _rv = DataHGetDataAvailability(dh,
- offset,
- len,
- &missing_offset,
- &missing_len);
- _res = Py_BuildValue("lll",
- _rv,
- missing_offset,
- missing_len);
- return _res;
+ PyMac_PRECHECK(DataHGetDataAvailability);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &dh,
+ &offset,
+ &len))
+ return NULL;
+ _rv = DataHGetDataAvailability(dh,
+ offset,
+ len,
+ &missing_offset,
+ &missing_len);
+ _res = Py_BuildValue("lll",
+ _rv,
+ missing_offset,
+ missing_len);
+ return _res;
}
static PyObject *Qt_DataHGetDataRefAsType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- OSType requestedType;
- Handle dataRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ OSType requestedType;
+ Handle dataRef;
#ifndef DataHGetDataRefAsType
- PyMac_PRECHECK(DataHGetDataRefAsType);
+ PyMac_PRECHECK(DataHGetDataRefAsType);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_GetOSType, &requestedType))
- return NULL;
- _rv = DataHGetDataRefAsType(dh,
- requestedType,
- &dataRef);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, dataRef);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetOSType, &requestedType))
+ return NULL;
+ _rv = DataHGetDataRefAsType(dh,
+ requestedType,
+ &dataRef);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, dataRef);
+ return _res;
}
static PyObject *Qt_DataHSetDataRefExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle extension;
- OSType idType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle extension;
+ OSType idType;
#ifndef DataHSetDataRefExtension
- PyMac_PRECHECK(DataHSetDataRefExtension);
+ PyMac_PRECHECK(DataHSetDataRefExtension);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &extension,
- PyMac_GetOSType, &idType))
- return NULL;
- _rv = DataHSetDataRefExtension(dh,
- extension,
- idType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &extension,
+ PyMac_GetOSType, &idType))
+ return NULL;
+ _rv = DataHSetDataRefExtension(dh,
+ extension,
+ idType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetDataRefExtension(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle extension;
- OSType idType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle extension;
+ OSType idType;
#ifndef DataHGetDataRefExtension
- PyMac_PRECHECK(DataHGetDataRefExtension);
+ PyMac_PRECHECK(DataHGetDataRefExtension);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- PyMac_GetOSType, &idType))
- return NULL;
- _rv = DataHGetDataRefExtension(dh,
- &extension,
- idType);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, extension);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetOSType, &idType))
+ return NULL;
+ _rv = DataHGetDataRefExtension(dh,
+ &extension,
+ idType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, extension);
+ return _res;
}
static PyObject *Qt_DataHGetMovieWithFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Movie theMovie;
- short id;
- short flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Movie theMovie;
+ short id;
+ short flags;
#ifndef DataHGetMovieWithFlags
- PyMac_PRECHECK(DataHGetMovieWithFlags);
-#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &dh,
- &flags))
- return NULL;
- _rv = DataHGetMovieWithFlags(dh,
- &theMovie,
- &id,
- flags);
- _res = Py_BuildValue("lO&h",
- _rv,
- MovieObj_New, theMovie,
- id);
- return _res;
+ PyMac_PRECHECK(DataHGetMovieWithFlags);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &dh,
+ &flags))
+ return NULL;
+ _rv = DataHGetMovieWithFlags(dh,
+ &theMovie,
+ &id,
+ flags);
+ _res = Py_BuildValue("lO&h",
+ _rv,
+ MovieObj_New, theMovie,
+ id);
+ return _res;
}
static PyObject *Qt_DataHGetFileTypeOrdering(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- DataHFileTypeOrderingHandle orderingListHandle;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ DataHFileTypeOrderingHandle orderingListHandle;
#ifndef DataHGetFileTypeOrdering
- PyMac_PRECHECK(DataHGetFileTypeOrdering);
+ PyMac_PRECHECK(DataHGetFileTypeOrdering);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetFileTypeOrdering(dh,
- &orderingListHandle);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, orderingListHandle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetFileTypeOrdering(dh,
+ &orderingListHandle);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, orderingListHandle);
+ return _res;
}
static PyObject *Qt_DataHCreateFileWithFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- OSType creator;
- Boolean deleteExisting;
- UInt32 flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ OSType creator;
+ Boolean deleteExisting;
+ UInt32 flags;
#ifndef DataHCreateFileWithFlags
- PyMac_PRECHECK(DataHCreateFileWithFlags);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&bl",
- CmpInstObj_Convert, &dh,
- PyMac_GetOSType, &creator,
- &deleteExisting,
- &flags))
- return NULL;
- _rv = DataHCreateFileWithFlags(dh,
- creator,
- deleteExisting,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataHCreateFileWithFlags);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&bl",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetOSType, &creator,
+ &deleteExisting,
+ &flags))
+ return NULL;
+ _rv = DataHCreateFileWithFlags(dh,
+ creator,
+ deleteExisting,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- OSType what;
- void * info;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ OSType what;
+ void * info;
#ifndef DataHGetInfo
- PyMac_PRECHECK(DataHGetInfo);
+ PyMac_PRECHECK(DataHGetInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&s",
- CmpInstObj_Convert, &dh,
- PyMac_GetOSType, &what,
- &info))
- return NULL;
- _rv = DataHGetInfo(dh,
- what,
- info);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&s",
+ CmpInstObj_Convert, &dh,
+ PyMac_GetOSType, &what,
+ &info))
+ return NULL;
+ _rv = DataHGetInfo(dh,
+ what,
+ info);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHSetIdleManager(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- IdleManager im;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ IdleManager im;
#ifndef DataHSetIdleManager
- PyMac_PRECHECK(DataHSetIdleManager);
+ PyMac_PRECHECK(DataHSetIdleManager);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- IdleManagerObj_Convert, &im))
- return NULL;
- _rv = DataHSetIdleManager(dh,
- im);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ IdleManagerObj_Convert, &im))
+ return NULL;
+ _rv = DataHSetIdleManager(dh,
+ im);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHDeleteFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
#ifndef DataHDeleteFile
- PyMac_PRECHECK(DataHDeleteFile);
+ PyMac_PRECHECK(DataHDeleteFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHDeleteFile(dh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHDeleteFile(dh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHSetMovieUsageFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long flags;
#ifndef DataHSetMovieUsageFlags
- PyMac_PRECHECK(DataHSetMovieUsageFlags);
+ PyMac_PRECHECK(DataHSetMovieUsageFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &flags))
- return NULL;
- _rv = DataHSetMovieUsageFlags(dh,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &flags))
+ return NULL;
+ _rv = DataHSetMovieUsageFlags(dh,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHUseTemporaryDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long inFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long inFlags;
#ifndef DataHUseTemporaryDataRef
- PyMac_PRECHECK(DataHUseTemporaryDataRef);
+ PyMac_PRECHECK(DataHUseTemporaryDataRef);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &inFlags))
- return NULL;
- _rv = DataHUseTemporaryDataRef(dh,
- inFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &inFlags))
+ return NULL;
+ _rv = DataHUseTemporaryDataRef(dh,
+ inFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetTemporaryDataRefCapabilities(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long outUnderstoodFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long outUnderstoodFlags;
#ifndef DataHGetTemporaryDataRefCapabilities
- PyMac_PRECHECK(DataHGetTemporaryDataRefCapabilities);
+ PyMac_PRECHECK(DataHGetTemporaryDataRefCapabilities);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &dh))
- return NULL;
- _rv = DataHGetTemporaryDataRefCapabilities(dh,
- &outUnderstoodFlags);
- _res = Py_BuildValue("ll",
- _rv,
- outUnderstoodFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &dh))
+ return NULL;
+ _rv = DataHGetTemporaryDataRefCapabilities(dh,
+ &outUnderstoodFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ outUnderstoodFlags);
+ return _res;
}
static PyObject *Qt_DataHRenameFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- Handle newDataRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ Handle newDataRef;
#ifndef DataHRenameFile
- PyMac_PRECHECK(DataHRenameFile);
+ PyMac_PRECHECK(DataHRenameFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &dh,
- ResObj_Convert, &newDataRef))
- return NULL;
- _rv = DataHRenameFile(dh,
- newDataRef);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &dh,
+ ResObj_Convert, &newDataRef))
+ return NULL;
+ _rv = DataHRenameFile(dh,
+ newDataRef);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHPlaybackHints(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long flags;
- unsigned long minFileOffset;
- unsigned long maxFileOffset;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long flags;
+ unsigned long minFileOffset;
+ unsigned long maxFileOffset;
+ long bytesPerSecond;
#ifndef DataHPlaybackHints
- PyMac_PRECHECK(DataHPlaybackHints);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llll",
- CmpInstObj_Convert, &dh,
- &flags,
- &minFileOffset,
- &maxFileOffset,
- &bytesPerSecond))
- return NULL;
- _rv = DataHPlaybackHints(dh,
- flags,
- minFileOffset,
- maxFileOffset,
- bytesPerSecond);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataHPlaybackHints);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llll",
+ CmpInstObj_Convert, &dh,
+ &flags,
+ &minFileOffset,
+ &maxFileOffset,
+ &bytesPerSecond))
+ return NULL;
+ _rv = DataHPlaybackHints(dh,
+ flags,
+ minFileOffset,
+ maxFileOffset,
+ bytesPerSecond);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHPlaybackHints64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long flags;
- wide minFileOffset;
- wide maxFileOffset;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long flags;
+ wide minFileOffset;
+ wide maxFileOffset;
+ long bytesPerSecond;
#ifndef DataHPlaybackHints64
- PyMac_PRECHECK(DataHPlaybackHints64);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&O&l",
- CmpInstObj_Convert, &dh,
- &flags,
- PyMac_Getwide, &minFileOffset,
- PyMac_Getwide, &maxFileOffset,
- &bytesPerSecond))
- return NULL;
- _rv = DataHPlaybackHints64(dh,
- flags,
- &minFileOffset,
- &maxFileOffset,
- bytesPerSecond);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataHPlaybackHints64);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&O&l",
+ CmpInstObj_Convert, &dh,
+ &flags,
+ PyMac_Getwide, &minFileOffset,
+ PyMac_Getwide, &maxFileOffset,
+ &bytesPerSecond))
+ return NULL;
+ _rv = DataHPlaybackHints64(dh,
+ flags,
+ &minFileOffset,
+ &maxFileOffset,
+ bytesPerSecond);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_DataHGetDataRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long flags;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long flags;
+ long bytesPerSecond;
#ifndef DataHGetDataRate
- PyMac_PRECHECK(DataHGetDataRate);
+ PyMac_PRECHECK(DataHGetDataRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &dh,
- &flags))
- return NULL;
- _rv = DataHGetDataRate(dh,
- flags,
- &bytesPerSecond);
- _res = Py_BuildValue("ll",
- _rv,
- bytesPerSecond);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &dh,
+ &flags))
+ return NULL;
+ _rv = DataHGetDataRate(dh,
+ flags,
+ &bytesPerSecond);
+ _res = Py_BuildValue("ll",
+ _rv,
+ bytesPerSecond);
+ return _res;
}
static PyObject *Qt_DataHSetTimeHints(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- DataHandler dh;
- long flags;
- long bandwidthPriority;
- TimeScale scale;
- TimeValue minTime;
- TimeValue maxTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ DataHandler dh;
+ long flags;
+ long bandwidthPriority;
+ TimeScale scale;
+ TimeValue minTime;
+ TimeValue maxTime;
#ifndef DataHSetTimeHints
- PyMac_PRECHECK(DataHSetTimeHints);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lllll",
- CmpInstObj_Convert, &dh,
- &flags,
- &bandwidthPriority,
- &scale,
- &minTime,
- &maxTime))
- return NULL;
- _rv = DataHSetTimeHints(dh,
- flags,
- bandwidthPriority,
- scale,
- minTime,
- maxTime);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(DataHSetTimeHints);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lllll",
+ CmpInstObj_Convert, &dh,
+ &flags,
+ &bandwidthPriority,
+ &scale,
+ &minTime,
+ &maxTime))
+ return NULL;
+ _rv = DataHSetTimeHints(dh,
+ flags,
+ bandwidthPriority,
+ scale,
+ minTime,
+ maxTime);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetMaxSrcRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short inputStd;
- Rect maxSrcRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short inputStd;
+ Rect maxSrcRect;
#ifndef VDGetMaxSrcRect
- PyMac_PRECHECK(VDGetMaxSrcRect);
+ PyMac_PRECHECK(VDGetMaxSrcRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &inputStd))
- return NULL;
- _rv = VDGetMaxSrcRect(ci,
- inputStd,
- &maxSrcRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &maxSrcRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &inputStd))
+ return NULL;
+ _rv = VDGetMaxSrcRect(ci,
+ inputStd,
+ &maxSrcRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &maxSrcRect);
+ return _res;
}
static PyObject *Qt_VDGetActiveSrcRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short inputStd;
- Rect activeSrcRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short inputStd;
+ Rect activeSrcRect;
#ifndef VDGetActiveSrcRect
- PyMac_PRECHECK(VDGetActiveSrcRect);
+ PyMac_PRECHECK(VDGetActiveSrcRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &inputStd))
- return NULL;
- _rv = VDGetActiveSrcRect(ci,
- inputStd,
- &activeSrcRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &activeSrcRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &inputStd))
+ return NULL;
+ _rv = VDGetActiveSrcRect(ci,
+ inputStd,
+ &activeSrcRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &activeSrcRect);
+ return _res;
}
static PyObject *Qt_VDSetDigitizerRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Rect digitizerRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Rect digitizerRect;
#ifndef VDSetDigitizerRect
- PyMac_PRECHECK(VDSetDigitizerRect);
+ PyMac_PRECHECK(VDSetDigitizerRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetDigitizerRect(ci,
- &digitizerRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &digitizerRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetDigitizerRect(ci,
+ &digitizerRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &digitizerRect);
+ return _res;
}
static PyObject *Qt_VDGetDigitizerRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Rect digitizerRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Rect digitizerRect;
#ifndef VDGetDigitizerRect
- PyMac_PRECHECK(VDGetDigitizerRect);
+ PyMac_PRECHECK(VDGetDigitizerRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetDigitizerRect(ci,
- &digitizerRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &digitizerRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetDigitizerRect(ci,
+ &digitizerRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &digitizerRect);
+ return _res;
}
static PyObject *Qt_VDGetVBlankRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short inputStd;
- Rect vBlankRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short inputStd;
+ Rect vBlankRect;
#ifndef VDGetVBlankRect
- PyMac_PRECHECK(VDGetVBlankRect);
+ PyMac_PRECHECK(VDGetVBlankRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &inputStd))
- return NULL;
- _rv = VDGetVBlankRect(ci,
- inputStd,
- &vBlankRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &vBlankRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &inputStd))
+ return NULL;
+ _rv = VDGetVBlankRect(ci,
+ inputStd,
+ &vBlankRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &vBlankRect);
+ return _res;
}
static PyObject *Qt_VDGetMaskPixMap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- PixMapHandle maskPixMap;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ PixMapHandle maskPixMap;
#ifndef VDGetMaskPixMap
- PyMac_PRECHECK(VDGetMaskPixMap);
+ PyMac_PRECHECK(VDGetMaskPixMap);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &maskPixMap))
- return NULL;
- _rv = VDGetMaskPixMap(ci,
- maskPixMap);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &maskPixMap))
+ return NULL;
+ _rv = VDGetMaskPixMap(ci,
+ maskPixMap);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDUseThisCLUT(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- CTabHandle colorTableHandle;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ CTabHandle colorTableHandle;
#ifndef VDUseThisCLUT
- PyMac_PRECHECK(VDUseThisCLUT);
+ PyMac_PRECHECK(VDUseThisCLUT);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &colorTableHandle))
- return NULL;
- _rv = VDUseThisCLUT(ci,
- colorTableHandle);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &colorTableHandle))
+ return NULL;
+ _rv = VDUseThisCLUT(ci,
+ colorTableHandle);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetInputGammaValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Fixed channel1;
- Fixed channel2;
- Fixed channel3;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Fixed channel1;
+ Fixed channel2;
+ Fixed channel3;
#ifndef VDSetInputGammaValue
- PyMac_PRECHECK(VDSetInputGammaValue);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFixed, &channel1,
- PyMac_GetFixed, &channel2,
- PyMac_GetFixed, &channel3))
- return NULL;
- _rv = VDSetInputGammaValue(ci,
- channel1,
- channel2,
- channel3);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(VDSetInputGammaValue);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFixed, &channel1,
+ PyMac_GetFixed, &channel2,
+ PyMac_GetFixed, &channel3))
+ return NULL;
+ _rv = VDSetInputGammaValue(ci,
+ channel1,
+ channel2,
+ channel3);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetInputGammaValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Fixed channel1;
- Fixed channel2;
- Fixed channel3;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Fixed channel1;
+ Fixed channel2;
+ Fixed channel3;
#ifndef VDGetInputGammaValue
- PyMac_PRECHECK(VDGetInputGammaValue);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetInputGammaValue(ci,
- &channel1,
- &channel2,
- &channel3);
- _res = Py_BuildValue("lO&O&O&",
- _rv,
- PyMac_BuildFixed, channel1,
- PyMac_BuildFixed, channel2,
- PyMac_BuildFixed, channel3);
- return _res;
+ PyMac_PRECHECK(VDGetInputGammaValue);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetInputGammaValue(ci,
+ &channel1,
+ &channel2,
+ &channel3);
+ _res = Py_BuildValue("lO&O&O&",
+ _rv,
+ PyMac_BuildFixed, channel1,
+ PyMac_BuildFixed, channel2,
+ PyMac_BuildFixed, channel3);
+ return _res;
}
static PyObject *Qt_VDSetBrightness(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short brightness;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short brightness;
#ifndef VDSetBrightness
- PyMac_PRECHECK(VDSetBrightness);
+ PyMac_PRECHECK(VDSetBrightness);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetBrightness(ci,
- &brightness);
- _res = Py_BuildValue("lH",
- _rv,
- brightness);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetBrightness(ci,
+ &brightness);
+ _res = Py_BuildValue("lH",
+ _rv,
+ brightness);
+ return _res;
}
static PyObject *Qt_VDGetBrightness(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short brightness;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short brightness;
#ifndef VDGetBrightness
- PyMac_PRECHECK(VDGetBrightness);
+ PyMac_PRECHECK(VDGetBrightness);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetBrightness(ci,
- &brightness);
- _res = Py_BuildValue("lH",
- _rv,
- brightness);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetBrightness(ci,
+ &brightness);
+ _res = Py_BuildValue("lH",
+ _rv,
+ brightness);
+ return _res;
}
static PyObject *Qt_VDSetContrast(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short contrast;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short contrast;
#ifndef VDSetContrast
- PyMac_PRECHECK(VDSetContrast);
+ PyMac_PRECHECK(VDSetContrast);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetContrast(ci,
- &contrast);
- _res = Py_BuildValue("lH",
- _rv,
- contrast);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetContrast(ci,
+ &contrast);
+ _res = Py_BuildValue("lH",
+ _rv,
+ contrast);
+ return _res;
}
static PyObject *Qt_VDSetHue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short hue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short hue;
#ifndef VDSetHue
- PyMac_PRECHECK(VDSetHue);
+ PyMac_PRECHECK(VDSetHue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetHue(ci,
- &hue);
- _res = Py_BuildValue("lH",
- _rv,
- hue);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetHue(ci,
+ &hue);
+ _res = Py_BuildValue("lH",
+ _rv,
+ hue);
+ return _res;
}
static PyObject *Qt_VDSetSharpness(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short sharpness;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short sharpness;
#ifndef VDSetSharpness
- PyMac_PRECHECK(VDSetSharpness);
+ PyMac_PRECHECK(VDSetSharpness);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetSharpness(ci,
- &sharpness);
- _res = Py_BuildValue("lH",
- _rv,
- sharpness);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetSharpness(ci,
+ &sharpness);
+ _res = Py_BuildValue("lH",
+ _rv,
+ sharpness);
+ return _res;
}
static PyObject *Qt_VDSetSaturation(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short saturation;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short saturation;
#ifndef VDSetSaturation
- PyMac_PRECHECK(VDSetSaturation);
+ PyMac_PRECHECK(VDSetSaturation);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetSaturation(ci,
- &saturation);
- _res = Py_BuildValue("lH",
- _rv,
- saturation);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetSaturation(ci,
+ &saturation);
+ _res = Py_BuildValue("lH",
+ _rv,
+ saturation);
+ return _res;
}
static PyObject *Qt_VDGetContrast(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short contrast;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short contrast;
#ifndef VDGetContrast
- PyMac_PRECHECK(VDGetContrast);
+ PyMac_PRECHECK(VDGetContrast);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetContrast(ci,
- &contrast);
- _res = Py_BuildValue("lH",
- _rv,
- contrast);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetContrast(ci,
+ &contrast);
+ _res = Py_BuildValue("lH",
+ _rv,
+ contrast);
+ return _res;
}
static PyObject *Qt_VDGetHue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short hue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short hue;
#ifndef VDGetHue
- PyMac_PRECHECK(VDGetHue);
+ PyMac_PRECHECK(VDGetHue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetHue(ci,
- &hue);
- _res = Py_BuildValue("lH",
- _rv,
- hue);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetHue(ci,
+ &hue);
+ _res = Py_BuildValue("lH",
+ _rv,
+ hue);
+ return _res;
}
static PyObject *Qt_VDGetSharpness(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short sharpness;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short sharpness;
#ifndef VDGetSharpness
- PyMac_PRECHECK(VDGetSharpness);
+ PyMac_PRECHECK(VDGetSharpness);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetSharpness(ci,
- &sharpness);
- _res = Py_BuildValue("lH",
- _rv,
- sharpness);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetSharpness(ci,
+ &sharpness);
+ _res = Py_BuildValue("lH",
+ _rv,
+ sharpness);
+ return _res;
}
static PyObject *Qt_VDGetSaturation(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short saturation;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short saturation;
#ifndef VDGetSaturation
- PyMac_PRECHECK(VDGetSaturation);
+ PyMac_PRECHECK(VDGetSaturation);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetSaturation(ci,
- &saturation);
- _res = Py_BuildValue("lH",
- _rv,
- saturation);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetSaturation(ci,
+ &saturation);
+ _res = Py_BuildValue("lH",
+ _rv,
+ saturation);
+ return _res;
}
static PyObject *Qt_VDGrabOneFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
#ifndef VDGrabOneFrame
- PyMac_PRECHECK(VDGrabOneFrame);
+ PyMac_PRECHECK(VDGrabOneFrame);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGrabOneFrame(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGrabOneFrame(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetMaxAuxBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- PixMapHandle pm;
- Rect r;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ PixMapHandle pm;
+ Rect r;
#ifndef VDGetMaxAuxBuffer
- PyMac_PRECHECK(VDGetMaxAuxBuffer);
+ PyMac_PRECHECK(VDGetMaxAuxBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetMaxAuxBuffer(ci,
- &pm,
- &r);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, pm,
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetMaxAuxBuffer(ci,
+ &pm,
+ &r);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, pm,
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qt_VDGetCurrentFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long inputCurrentFlag;
- long outputCurrentFlag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long inputCurrentFlag;
+ long outputCurrentFlag;
#ifndef VDGetCurrentFlags
- PyMac_PRECHECK(VDGetCurrentFlags);
+ PyMac_PRECHECK(VDGetCurrentFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetCurrentFlags(ci,
- &inputCurrentFlag,
- &outputCurrentFlag);
- _res = Py_BuildValue("lll",
- _rv,
- inputCurrentFlag,
- outputCurrentFlag);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetCurrentFlags(ci,
+ &inputCurrentFlag,
+ &outputCurrentFlag);
+ _res = Py_BuildValue("lll",
+ _rv,
+ inputCurrentFlag,
+ outputCurrentFlag);
+ return _res;
}
static PyObject *Qt_VDSetKeyColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long index;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long index;
#ifndef VDSetKeyColor
- PyMac_PRECHECK(VDSetKeyColor);
+ PyMac_PRECHECK(VDSetKeyColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &index))
- return NULL;
- _rv = VDSetKeyColor(ci,
- index);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &index))
+ return NULL;
+ _rv = VDSetKeyColor(ci,
+ index);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetKeyColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long index;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long index;
#ifndef VDGetKeyColor
- PyMac_PRECHECK(VDGetKeyColor);
+ PyMac_PRECHECK(VDGetKeyColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetKeyColor(ci,
- &index);
- _res = Py_BuildValue("ll",
- _rv,
- index);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetKeyColor(ci,
+ &index);
+ _res = Py_BuildValue("ll",
+ _rv,
+ index);
+ return _res;
}
static PyObject *Qt_VDAddKeyColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long index;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long index;
#ifndef VDAddKeyColor
- PyMac_PRECHECK(VDAddKeyColor);
+ PyMac_PRECHECK(VDAddKeyColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDAddKeyColor(ci,
- &index);
- _res = Py_BuildValue("ll",
- _rv,
- index);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDAddKeyColor(ci,
+ &index);
+ _res = Py_BuildValue("ll",
+ _rv,
+ index);
+ return _res;
}
static PyObject *Qt_VDGetNextKeyColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long index;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long index;
#ifndef VDGetNextKeyColor
- PyMac_PRECHECK(VDGetNextKeyColor);
+ PyMac_PRECHECK(VDGetNextKeyColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &index))
- return NULL;
- _rv = VDGetNextKeyColor(ci,
- index);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &index))
+ return NULL;
+ _rv = VDGetNextKeyColor(ci,
+ index);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetKeyColorRange(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- RGBColor minRGB;
- RGBColor maxRGB;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ RGBColor minRGB;
+ RGBColor maxRGB;
#ifndef VDSetKeyColorRange
- PyMac_PRECHECK(VDSetKeyColorRange);
+ PyMac_PRECHECK(VDSetKeyColorRange);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetKeyColorRange(ci,
- &minRGB,
- &maxRGB);
- _res = Py_BuildValue("lO&O&",
- _rv,
- QdRGB_New, &minRGB,
- QdRGB_New, &maxRGB);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetKeyColorRange(ci,
+ &minRGB,
+ &maxRGB);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ QdRGB_New, &minRGB,
+ QdRGB_New, &maxRGB);
+ return _res;
}
static PyObject *Qt_VDGetKeyColorRange(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- RGBColor minRGB;
- RGBColor maxRGB;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ RGBColor minRGB;
+ RGBColor maxRGB;
#ifndef VDGetKeyColorRange
- PyMac_PRECHECK(VDGetKeyColorRange);
+ PyMac_PRECHECK(VDGetKeyColorRange);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetKeyColorRange(ci,
- &minRGB,
- &maxRGB);
- _res = Py_BuildValue("lO&O&",
- _rv,
- QdRGB_New, &minRGB,
- QdRGB_New, &maxRGB);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetKeyColorRange(ci,
+ &minRGB,
+ &maxRGB);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ QdRGB_New, &minRGB,
+ QdRGB_New, &maxRGB);
+ return _res;
}
static PyObject *Qt_VDSetInputColorSpaceMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short colorSpaceMode;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short colorSpaceMode;
#ifndef VDSetInputColorSpaceMode
- PyMac_PRECHECK(VDSetInputColorSpaceMode);
+ PyMac_PRECHECK(VDSetInputColorSpaceMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &colorSpaceMode))
- return NULL;
- _rv = VDSetInputColorSpaceMode(ci,
- colorSpaceMode);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &colorSpaceMode))
+ return NULL;
+ _rv = VDSetInputColorSpaceMode(ci,
+ colorSpaceMode);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetInputColorSpaceMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short colorSpaceMode;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short colorSpaceMode;
#ifndef VDGetInputColorSpaceMode
- PyMac_PRECHECK(VDGetInputColorSpaceMode);
+ PyMac_PRECHECK(VDGetInputColorSpaceMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetInputColorSpaceMode(ci,
- &colorSpaceMode);
- _res = Py_BuildValue("lh",
- _rv,
- colorSpaceMode);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetInputColorSpaceMode(ci,
+ &colorSpaceMode);
+ _res = Py_BuildValue("lh",
+ _rv,
+ colorSpaceMode);
+ return _res;
}
static PyObject *Qt_VDSetClipState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short clipEnable;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short clipEnable;
#ifndef VDSetClipState
- PyMac_PRECHECK(VDSetClipState);
+ PyMac_PRECHECK(VDSetClipState);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &clipEnable))
- return NULL;
- _rv = VDSetClipState(ci,
- clipEnable);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &clipEnable))
+ return NULL;
+ _rv = VDSetClipState(ci,
+ clipEnable);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetClipState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short clipEnable;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short clipEnable;
#ifndef VDGetClipState
- PyMac_PRECHECK(VDGetClipState);
+ PyMac_PRECHECK(VDGetClipState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetClipState(ci,
- &clipEnable);
- _res = Py_BuildValue("lh",
- _rv,
- clipEnable);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetClipState(ci,
+ &clipEnable);
+ _res = Py_BuildValue("lh",
+ _rv,
+ clipEnable);
+ return _res;
}
static PyObject *Qt_VDSetClipRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- RgnHandle clipRegion;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ RgnHandle clipRegion;
#ifndef VDSetClipRgn
- PyMac_PRECHECK(VDSetClipRgn);
+ PyMac_PRECHECK(VDSetClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &clipRegion))
- return NULL;
- _rv = VDSetClipRgn(ci,
- clipRegion);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &clipRegion))
+ return NULL;
+ _rv = VDSetClipRgn(ci,
+ clipRegion);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDClearClipRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- RgnHandle clipRegion;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ RgnHandle clipRegion;
#ifndef VDClearClipRgn
- PyMac_PRECHECK(VDClearClipRgn);
+ PyMac_PRECHECK(VDClearClipRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &clipRegion))
- return NULL;
- _rv = VDClearClipRgn(ci,
- clipRegion);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &clipRegion))
+ return NULL;
+ _rv = VDClearClipRgn(ci,
+ clipRegion);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetCLUTInUse(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- CTabHandle colorTableHandle;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ CTabHandle colorTableHandle;
#ifndef VDGetCLUTInUse
- PyMac_PRECHECK(VDGetCLUTInUse);
+ PyMac_PRECHECK(VDGetCLUTInUse);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetCLUTInUse(ci,
- &colorTableHandle);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, colorTableHandle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetCLUTInUse(ci,
+ &colorTableHandle);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, colorTableHandle);
+ return _res;
}
static PyObject *Qt_VDSetPLLFilterType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short pllType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short pllType;
#ifndef VDSetPLLFilterType
- PyMac_PRECHECK(VDSetPLLFilterType);
+ PyMac_PRECHECK(VDSetPLLFilterType);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &pllType))
- return NULL;
- _rv = VDSetPLLFilterType(ci,
- pllType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &pllType))
+ return NULL;
+ _rv = VDSetPLLFilterType(ci,
+ pllType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetPLLFilterType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short pllType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short pllType;
#ifndef VDGetPLLFilterType
- PyMac_PRECHECK(VDGetPLLFilterType);
+ PyMac_PRECHECK(VDGetPLLFilterType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetPLLFilterType(ci,
- &pllType);
- _res = Py_BuildValue("lh",
- _rv,
- pllType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetPLLFilterType(ci,
+ &pllType);
+ _res = Py_BuildValue("lh",
+ _rv,
+ pllType);
+ return _res;
}
static PyObject *Qt_VDGetMaskandValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short blendLevel;
- long mask;
- long value;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short blendLevel;
+ long mask;
+ long value;
#ifndef VDGetMaskandValue
- PyMac_PRECHECK(VDGetMaskandValue);
-#endif
- if (!PyArg_ParseTuple(_args, "O&H",
- CmpInstObj_Convert, &ci,
- &blendLevel))
- return NULL;
- _rv = VDGetMaskandValue(ci,
- blendLevel,
- &mask,
- &value);
- _res = Py_BuildValue("lll",
- _rv,
- mask,
- value);
- return _res;
+ PyMac_PRECHECK(VDGetMaskandValue);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&H",
+ CmpInstObj_Convert, &ci,
+ &blendLevel))
+ return NULL;
+ _rv = VDGetMaskandValue(ci,
+ blendLevel,
+ &mask,
+ &value);
+ _res = Py_BuildValue("lll",
+ _rv,
+ mask,
+ value);
+ return _res;
}
static PyObject *Qt_VDSetMasterBlendLevel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short blendLevel;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short blendLevel;
#ifndef VDSetMasterBlendLevel
- PyMac_PRECHECK(VDSetMasterBlendLevel);
+ PyMac_PRECHECK(VDSetMasterBlendLevel);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetMasterBlendLevel(ci,
- &blendLevel);
- _res = Py_BuildValue("lH",
- _rv,
- blendLevel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetMasterBlendLevel(ci,
+ &blendLevel);
+ _res = Py_BuildValue("lH",
+ _rv,
+ blendLevel);
+ return _res;
}
static PyObject *Qt_VDSetPlayThruOnOff(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short state;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short state;
#ifndef VDSetPlayThruOnOff
- PyMac_PRECHECK(VDSetPlayThruOnOff);
+ PyMac_PRECHECK(VDSetPlayThruOnOff);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &state))
- return NULL;
- _rv = VDSetPlayThruOnOff(ci,
- state);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &state))
+ return NULL;
+ _rv = VDSetPlayThruOnOff(ci,
+ state);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetFieldPreference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short fieldFlag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short fieldFlag;
#ifndef VDSetFieldPreference
- PyMac_PRECHECK(VDSetFieldPreference);
+ PyMac_PRECHECK(VDSetFieldPreference);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &fieldFlag))
- return NULL;
- _rv = VDSetFieldPreference(ci,
- fieldFlag);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &fieldFlag))
+ return NULL;
+ _rv = VDSetFieldPreference(ci,
+ fieldFlag);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetFieldPreference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short fieldFlag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short fieldFlag;
#ifndef VDGetFieldPreference
- PyMac_PRECHECK(VDGetFieldPreference);
+ PyMac_PRECHECK(VDGetFieldPreference);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetFieldPreference(ci,
- &fieldFlag);
- _res = Py_BuildValue("lh",
- _rv,
- fieldFlag);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetFieldPreference(ci,
+ &fieldFlag);
+ _res = Py_BuildValue("lh",
+ _rv,
+ fieldFlag);
+ return _res;
}
static PyObject *Qt_VDPreflightGlobalRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- GrafPtr theWindow;
- Rect globalRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ GrafPtr theWindow;
+ Rect globalRect;
#ifndef VDPreflightGlobalRect
- PyMac_PRECHECK(VDPreflightGlobalRect);
+ PyMac_PRECHECK(VDPreflightGlobalRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- GrafObj_Convert, &theWindow))
- return NULL;
- _rv = VDPreflightGlobalRect(ci,
- theWindow,
- &globalRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &globalRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ GrafObj_Convert, &theWindow))
+ return NULL;
+ _rv = VDPreflightGlobalRect(ci,
+ theWindow,
+ &globalRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &globalRect);
+ return _res;
}
static PyObject *Qt_VDSetPlayThruGlobalRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- GrafPtr theWindow;
- Rect globalRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ GrafPtr theWindow;
+ Rect globalRect;
#ifndef VDSetPlayThruGlobalRect
- PyMac_PRECHECK(VDSetPlayThruGlobalRect);
+ PyMac_PRECHECK(VDSetPlayThruGlobalRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- GrafObj_Convert, &theWindow))
- return NULL;
- _rv = VDSetPlayThruGlobalRect(ci,
- theWindow,
- &globalRect);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &globalRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ GrafObj_Convert, &theWindow))
+ return NULL;
+ _rv = VDSetPlayThruGlobalRect(ci,
+ theWindow,
+ &globalRect);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &globalRect);
+ return _res;
}
static PyObject *Qt_VDSetBlackLevelValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short blackLevel;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short blackLevel;
#ifndef VDSetBlackLevelValue
- PyMac_PRECHECK(VDSetBlackLevelValue);
+ PyMac_PRECHECK(VDSetBlackLevelValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetBlackLevelValue(ci,
- &blackLevel);
- _res = Py_BuildValue("lH",
- _rv,
- blackLevel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetBlackLevelValue(ci,
+ &blackLevel);
+ _res = Py_BuildValue("lH",
+ _rv,
+ blackLevel);
+ return _res;
}
static PyObject *Qt_VDGetBlackLevelValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short blackLevel;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short blackLevel;
#ifndef VDGetBlackLevelValue
- PyMac_PRECHECK(VDGetBlackLevelValue);
+ PyMac_PRECHECK(VDGetBlackLevelValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetBlackLevelValue(ci,
- &blackLevel);
- _res = Py_BuildValue("lH",
- _rv,
- blackLevel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetBlackLevelValue(ci,
+ &blackLevel);
+ _res = Py_BuildValue("lH",
+ _rv,
+ blackLevel);
+ return _res;
}
static PyObject *Qt_VDSetWhiteLevelValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short whiteLevel;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short whiteLevel;
#ifndef VDSetWhiteLevelValue
- PyMac_PRECHECK(VDSetWhiteLevelValue);
+ PyMac_PRECHECK(VDSetWhiteLevelValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDSetWhiteLevelValue(ci,
- &whiteLevel);
- _res = Py_BuildValue("lH",
- _rv,
- whiteLevel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDSetWhiteLevelValue(ci,
+ &whiteLevel);
+ _res = Py_BuildValue("lH",
+ _rv,
+ whiteLevel);
+ return _res;
}
static PyObject *Qt_VDGetWhiteLevelValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short whiteLevel;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short whiteLevel;
#ifndef VDGetWhiteLevelValue
- PyMac_PRECHECK(VDGetWhiteLevelValue);
+ PyMac_PRECHECK(VDGetWhiteLevelValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetWhiteLevelValue(ci,
- &whiteLevel);
- _res = Py_BuildValue("lH",
- _rv,
- whiteLevel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetWhiteLevelValue(ci,
+ &whiteLevel);
+ _res = Py_BuildValue("lH",
+ _rv,
+ whiteLevel);
+ return _res;
}
static PyObject *Qt_VDGetVideoDefaults(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- unsigned short blackLevel;
- unsigned short whiteLevel;
- unsigned short brightness;
- unsigned short hue;
- unsigned short saturation;
- unsigned short contrast;
- unsigned short sharpness;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ unsigned short blackLevel;
+ unsigned short whiteLevel;
+ unsigned short brightness;
+ unsigned short hue;
+ unsigned short saturation;
+ unsigned short contrast;
+ unsigned short sharpness;
#ifndef VDGetVideoDefaults
- PyMac_PRECHECK(VDGetVideoDefaults);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetVideoDefaults(ci,
- &blackLevel,
- &whiteLevel,
- &brightness,
- &hue,
- &saturation,
- &contrast,
- &sharpness);
- _res = Py_BuildValue("lHHHHHHH",
- _rv,
- blackLevel,
- whiteLevel,
- brightness,
- hue,
- saturation,
- contrast,
- sharpness);
- return _res;
+ PyMac_PRECHECK(VDGetVideoDefaults);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetVideoDefaults(ci,
+ &blackLevel,
+ &whiteLevel,
+ &brightness,
+ &hue,
+ &saturation,
+ &contrast,
+ &sharpness);
+ _res = Py_BuildValue("lHHHHHHH",
+ _rv,
+ blackLevel,
+ whiteLevel,
+ brightness,
+ hue,
+ saturation,
+ contrast,
+ sharpness);
+ return _res;
}
static PyObject *Qt_VDGetNumberOfInputs(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short inputs;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short inputs;
#ifndef VDGetNumberOfInputs
- PyMac_PRECHECK(VDGetNumberOfInputs);
+ PyMac_PRECHECK(VDGetNumberOfInputs);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetNumberOfInputs(ci,
- &inputs);
- _res = Py_BuildValue("lh",
- _rv,
- inputs);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetNumberOfInputs(ci,
+ &inputs);
+ _res = Py_BuildValue("lh",
+ _rv,
+ inputs);
+ return _res;
}
static PyObject *Qt_VDGetInputFormat(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short input;
- short format;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short input;
+ short format;
#ifndef VDGetInputFormat
- PyMac_PRECHECK(VDGetInputFormat);
+ PyMac_PRECHECK(VDGetInputFormat);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &input))
- return NULL;
- _rv = VDGetInputFormat(ci,
- input,
- &format);
- _res = Py_BuildValue("lh",
- _rv,
- format);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &input))
+ return NULL;
+ _rv = VDGetInputFormat(ci,
+ input,
+ &format);
+ _res = Py_BuildValue("lh",
+ _rv,
+ format);
+ return _res;
}
static PyObject *Qt_VDSetInput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short input;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short input;
#ifndef VDSetInput
- PyMac_PRECHECK(VDSetInput);
+ PyMac_PRECHECK(VDSetInput);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &input))
- return NULL;
- _rv = VDSetInput(ci,
- input);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &input))
+ return NULL;
+ _rv = VDSetInput(ci,
+ input);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetInput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short input;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short input;
#ifndef VDGetInput
- PyMac_PRECHECK(VDGetInput);
+ PyMac_PRECHECK(VDGetInput);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetInput(ci,
- &input);
- _res = Py_BuildValue("lh",
- _rv,
- input);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetInput(ci,
+ &input);
+ _res = Py_BuildValue("lh",
+ _rv,
+ input);
+ return _res;
}
static PyObject *Qt_VDSetInputStandard(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short inputStandard;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short inputStandard;
#ifndef VDSetInputStandard
- PyMac_PRECHECK(VDSetInputStandard);
+ PyMac_PRECHECK(VDSetInputStandard);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &inputStandard))
- return NULL;
- _rv = VDSetInputStandard(ci,
- inputStandard);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &inputStandard))
+ return NULL;
+ _rv = VDSetInputStandard(ci,
+ inputStandard);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetupBuffers(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- VdigBufferRecListHandle bufferList;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ VdigBufferRecListHandle bufferList;
#ifndef VDSetupBuffers
- PyMac_PRECHECK(VDSetupBuffers);
+ PyMac_PRECHECK(VDSetupBuffers);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &bufferList))
- return NULL;
- _rv = VDSetupBuffers(ci,
- bufferList);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &bufferList))
+ return NULL;
+ _rv = VDSetupBuffers(ci,
+ bufferList);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGrabOneFrameAsync(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short buffer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short buffer;
#ifndef VDGrabOneFrameAsync
- PyMac_PRECHECK(VDGrabOneFrameAsync);
+ PyMac_PRECHECK(VDGrabOneFrameAsync);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &buffer))
- return NULL;
- _rv = VDGrabOneFrameAsync(ci,
- buffer);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &buffer))
+ return NULL;
+ _rv = VDGrabOneFrameAsync(ci,
+ buffer);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDDone(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- short buffer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ short buffer;
#ifndef VDDone
- PyMac_PRECHECK(VDDone);
+ PyMac_PRECHECK(VDDone);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &ci,
- &buffer))
- return NULL;
- _rv = VDDone(ci,
- buffer);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &ci,
+ &buffer))
+ return NULL;
+ _rv = VDDone(ci,
+ buffer);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetCompression(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- OSType compressType;
- short depth;
- Rect bounds;
- CodecQ spatialQuality;
- CodecQ temporalQuality;
- long keyFrameRate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ OSType compressType;
+ short depth;
+ Rect bounds;
+ CodecQ spatialQuality;
+ CodecQ temporalQuality;
+ long keyFrameRate;
#ifndef VDSetCompression
- PyMac_PRECHECK(VDSetCompression);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hlll",
- CmpInstObj_Convert, &ci,
- PyMac_GetOSType, &compressType,
- &depth,
- &spatialQuality,
- &temporalQuality,
- &keyFrameRate))
- return NULL;
- _rv = VDSetCompression(ci,
- compressType,
- depth,
- &bounds,
- spatialQuality,
- temporalQuality,
- keyFrameRate);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &bounds);
- return _res;
+ PyMac_PRECHECK(VDSetCompression);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hlll",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetOSType, &compressType,
+ &depth,
+ &spatialQuality,
+ &temporalQuality,
+ &keyFrameRate))
+ return NULL;
+ _rv = VDSetCompression(ci,
+ compressType,
+ depth,
+ &bounds,
+ spatialQuality,
+ temporalQuality,
+ keyFrameRate);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *Qt_VDCompressOneFrameAsync(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
#ifndef VDCompressOneFrameAsync
- PyMac_PRECHECK(VDCompressOneFrameAsync);
+ PyMac_PRECHECK(VDCompressOneFrameAsync);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDCompressOneFrameAsync(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDCompressOneFrameAsync(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetImageDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- ImageDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ ImageDescriptionHandle desc;
#ifndef VDGetImageDescription
- PyMac_PRECHECK(VDGetImageDescription);
+ PyMac_PRECHECK(VDGetImageDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &desc))
- return NULL;
- _rv = VDGetImageDescription(ci,
- desc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &desc))
+ return NULL;
+ _rv = VDGetImageDescription(ci,
+ desc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDResetCompressSequence(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
#ifndef VDResetCompressSequence
- PyMac_PRECHECK(VDResetCompressSequence);
+ PyMac_PRECHECK(VDResetCompressSequence);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDResetCompressSequence(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDResetCompressSequence(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetCompressionOnOff(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Boolean state;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Boolean state;
#ifndef VDSetCompressionOnOff
- PyMac_PRECHECK(VDSetCompressionOnOff);
+ PyMac_PRECHECK(VDSetCompressionOnOff);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &state))
- return NULL;
- _rv = VDSetCompressionOnOff(ci,
- state);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &state))
+ return NULL;
+ _rv = VDSetCompressionOnOff(ci,
+ state);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetCompressionTypes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- VDCompressionListHandle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ VDCompressionListHandle h;
#ifndef VDGetCompressionTypes
- PyMac_PRECHECK(VDGetCompressionTypes);
+ PyMac_PRECHECK(VDGetCompressionTypes);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- ResObj_Convert, &h))
- return NULL;
- _rv = VDGetCompressionTypes(ci,
- h);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = VDGetCompressionTypes(ci,
+ h);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- TimeBase t;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ TimeBase t;
#ifndef VDSetTimeBase
- PyMac_PRECHECK(VDSetTimeBase);
+ PyMac_PRECHECK(VDSetTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- TimeBaseObj_Convert, &t))
- return NULL;
- _rv = VDSetTimeBase(ci,
- t);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ TimeBaseObj_Convert, &t))
+ return NULL;
+ _rv = VDSetTimeBase(ci,
+ t);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetFrameRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Fixed framesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Fixed framesPerSecond;
#ifndef VDSetFrameRate
- PyMac_PRECHECK(VDSetFrameRate);
+ PyMac_PRECHECK(VDSetFrameRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetFixed, &framesPerSecond))
- return NULL;
- _rv = VDSetFrameRate(ci,
- framesPerSecond);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetFixed, &framesPerSecond))
+ return NULL;
+ _rv = VDSetFrameRate(ci,
+ framesPerSecond);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetDataRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long milliSecPerFrame;
- Fixed framesPerSecond;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long milliSecPerFrame;
+ Fixed framesPerSecond;
+ long bytesPerSecond;
#ifndef VDGetDataRate
- PyMac_PRECHECK(VDGetDataRate);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetDataRate(ci,
- &milliSecPerFrame,
- &framesPerSecond,
- &bytesPerSecond);
- _res = Py_BuildValue("llO&l",
- _rv,
- milliSecPerFrame,
- PyMac_BuildFixed, framesPerSecond,
- bytesPerSecond);
- return _res;
+ PyMac_PRECHECK(VDGetDataRate);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetDataRate(ci,
+ &milliSecPerFrame,
+ &framesPerSecond,
+ &bytesPerSecond);
+ _res = Py_BuildValue("llO&l",
+ _rv,
+ milliSecPerFrame,
+ PyMac_BuildFixed, framesPerSecond,
+ bytesPerSecond);
+ return _res;
}
static PyObject *Qt_VDGetSoundInputDriver(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Str255 soundDriverName;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Str255 soundDriverName;
#ifndef VDGetSoundInputDriver
- PyMac_PRECHECK(VDGetSoundInputDriver);
+ PyMac_PRECHECK(VDGetSoundInputDriver);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetStr255, soundDriverName))
- return NULL;
- _rv = VDGetSoundInputDriver(ci,
- soundDriverName);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetStr255, soundDriverName))
+ return NULL;
+ _rv = VDGetSoundInputDriver(ci,
+ soundDriverName);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetDMADepths(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long depthArray;
- long preferredDepth;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long depthArray;
+ long preferredDepth;
#ifndef VDGetDMADepths
- PyMac_PRECHECK(VDGetDMADepths);
+ PyMac_PRECHECK(VDGetDMADepths);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetDMADepths(ci,
- &depthArray,
- &preferredDepth);
- _res = Py_BuildValue("lll",
- _rv,
- depthArray,
- preferredDepth);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetDMADepths(ci,
+ &depthArray,
+ &preferredDepth);
+ _res = Py_BuildValue("lll",
+ _rv,
+ depthArray,
+ preferredDepth);
+ return _res;
}
static PyObject *Qt_VDGetPreferredTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- TimeScale preferred;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ TimeScale preferred;
#ifndef VDGetPreferredTimeScale
- PyMac_PRECHECK(VDGetPreferredTimeScale);
+ PyMac_PRECHECK(VDGetPreferredTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetPreferredTimeScale(ci,
- &preferred);
- _res = Py_BuildValue("ll",
- _rv,
- preferred);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetPreferredTimeScale(ci,
+ &preferred);
+ _res = Py_BuildValue("ll",
+ _rv,
+ preferred);
+ return _res;
}
static PyObject *Qt_VDReleaseAsyncBuffers(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
#ifndef VDReleaseAsyncBuffers
- PyMac_PRECHECK(VDReleaseAsyncBuffers);
+ PyMac_PRECHECK(VDReleaseAsyncBuffers);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDReleaseAsyncBuffers(ci);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDReleaseAsyncBuffers(ci);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetDataRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long bytesPerSecond;
#ifndef VDSetDataRate
- PyMac_PRECHECK(VDSetDataRate);
+ PyMac_PRECHECK(VDSetDataRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &bytesPerSecond))
- return NULL;
- _rv = VDSetDataRate(ci,
- bytesPerSecond);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &bytesPerSecond))
+ return NULL;
+ _rv = VDSetDataRate(ci,
+ bytesPerSecond);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetTimeCode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- TimeRecord atTime;
- void * timeCodeFormat;
- void * timeCodeTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ TimeRecord atTime;
+ void * timeCodeFormat;
+ void * timeCodeTime;
#ifndef VDGetTimeCode
- PyMac_PRECHECK(VDGetTimeCode);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ss",
- CmpInstObj_Convert, &ci,
- &timeCodeFormat,
- &timeCodeTime))
- return NULL;
- _rv = VDGetTimeCode(ci,
- &atTime,
- timeCodeFormat,
- timeCodeTime);
- _res = Py_BuildValue("lO&",
- _rv,
- QtTimeRecord_New, &atTime);
- return _res;
+ PyMac_PRECHECK(VDGetTimeCode);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ss",
+ CmpInstObj_Convert, &ci,
+ &timeCodeFormat,
+ &timeCodeTime))
+ return NULL;
+ _rv = VDGetTimeCode(ci,
+ &atTime,
+ timeCodeFormat,
+ timeCodeTime);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QtTimeRecord_New, &atTime);
+ return _res;
}
static PyObject *Qt_VDUseSafeBuffers(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Boolean useSafeBuffers;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Boolean useSafeBuffers;
#ifndef VDUseSafeBuffers
- PyMac_PRECHECK(VDUseSafeBuffers);
+ PyMac_PRECHECK(VDUseSafeBuffers);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &ci,
- &useSafeBuffers))
- return NULL;
- _rv = VDUseSafeBuffers(ci,
- useSafeBuffers);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &ci,
+ &useSafeBuffers))
+ return NULL;
+ _rv = VDUseSafeBuffers(ci,
+ useSafeBuffers);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetSoundInputSource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long videoInput;
- long soundInput;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long videoInput;
+ long soundInput;
#ifndef VDGetSoundInputSource
- PyMac_PRECHECK(VDGetSoundInputSource);
+ PyMac_PRECHECK(VDGetSoundInputSource);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &videoInput))
- return NULL;
- _rv = VDGetSoundInputSource(ci,
- videoInput,
- &soundInput);
- _res = Py_BuildValue("ll",
- _rv,
- soundInput);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &videoInput))
+ return NULL;
+ _rv = VDGetSoundInputSource(ci,
+ videoInput,
+ &soundInput);
+ _res = Py_BuildValue("ll",
+ _rv,
+ soundInput);
+ return _res;
}
static PyObject *Qt_VDGetCompressionTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- OSType compressionType;
- short depth;
- Rect srcRect;
- CodecQ spatialQuality;
- CodecQ temporalQuality;
- unsigned long compressTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ OSType compressionType;
+ short depth;
+ Rect srcRect;
+ CodecQ spatialQuality;
+ CodecQ temporalQuality;
+ unsigned long compressTime;
#ifndef VDGetCompressionTime
- PyMac_PRECHECK(VDGetCompressionTime);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &ci,
- PyMac_GetOSType, &compressionType,
- &depth))
- return NULL;
- _rv = VDGetCompressionTime(ci,
- compressionType,
- depth,
- &srcRect,
- &spatialQuality,
- &temporalQuality,
- &compressTime);
- _res = Py_BuildValue("lO&lll",
- _rv,
- PyMac_BuildRect, &srcRect,
- spatialQuality,
- temporalQuality,
- compressTime);
- return _res;
+ PyMac_PRECHECK(VDGetCompressionTime);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetOSType, &compressionType,
+ &depth))
+ return NULL;
+ _rv = VDGetCompressionTime(ci,
+ compressionType,
+ depth,
+ &srcRect,
+ &spatialQuality,
+ &temporalQuality,
+ &compressTime);
+ _res = Py_BuildValue("lO&lll",
+ _rv,
+ PyMac_BuildRect, &srcRect,
+ spatialQuality,
+ temporalQuality,
+ compressTime);
+ return _res;
}
static PyObject *Qt_VDSetPreferredPacketSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long preferredPacketSizeInBytes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long preferredPacketSizeInBytes;
#ifndef VDSetPreferredPacketSize
- PyMac_PRECHECK(VDSetPreferredPacketSize);
+ PyMac_PRECHECK(VDSetPreferredPacketSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &preferredPacketSizeInBytes))
- return NULL;
- _rv = VDSetPreferredPacketSize(ci,
- preferredPacketSizeInBytes);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &preferredPacketSizeInBytes))
+ return NULL;
+ _rv = VDSetPreferredPacketSize(ci,
+ preferredPacketSizeInBytes);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetPreferredImageDimensions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long width;
- long height;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long width;
+ long height;
#ifndef VDSetPreferredImageDimensions
- PyMac_PRECHECK(VDSetPreferredImageDimensions);
+ PyMac_PRECHECK(VDSetPreferredImageDimensions);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &ci,
- &width,
- &height))
- return NULL;
- _rv = VDSetPreferredImageDimensions(ci,
- width,
- height);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &ci,
+ &width,
+ &height))
+ return NULL;
+ _rv = VDSetPreferredImageDimensions(ci,
+ width,
+ height);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetPreferredImageDimensions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long width;
- long height;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long width;
+ long height;
#ifndef VDGetPreferredImageDimensions
- PyMac_PRECHECK(VDGetPreferredImageDimensions);
+ PyMac_PRECHECK(VDGetPreferredImageDimensions);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = VDGetPreferredImageDimensions(ci,
- &width,
- &height);
- _res = Py_BuildValue("lll",
- _rv,
- width,
- height);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = VDGetPreferredImageDimensions(ci,
+ &width,
+ &height);
+ _res = Py_BuildValue("lll",
+ _rv,
+ width,
+ height);
+ return _res;
}
static PyObject *Qt_VDGetInputName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- long videoInput;
- Str255 name;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ long videoInput;
+ Str255 name;
#ifndef VDGetInputName
- PyMac_PRECHECK(VDGetInputName);
+ PyMac_PRECHECK(VDGetInputName);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &ci,
- &videoInput,
- PyMac_GetStr255, name))
- return NULL;
- _rv = VDGetInputName(ci,
- videoInput,
- name);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &ci,
+ &videoInput,
+ PyMac_GetStr255, name))
+ return NULL;
+ _rv = VDGetInputName(ci,
+ videoInput,
+ name);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDSetDestinationPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- CGrafPtr destPort;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ CGrafPtr destPort;
#ifndef VDSetDestinationPort
- PyMac_PRECHECK(VDSetDestinationPort);
+ PyMac_PRECHECK(VDSetDestinationPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- GrafObj_Convert, &destPort))
- return NULL;
- _rv = VDSetDestinationPort(ci,
- destPort);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ GrafObj_Convert, &destPort))
+ return NULL;
+ _rv = VDSetDestinationPort(ci,
+ destPort);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_VDGetDeviceNameAndFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- Str255 outName;
- UInt32 outNameFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ Str255 outName;
+ UInt32 outNameFlags;
#ifndef VDGetDeviceNameAndFlags
- PyMac_PRECHECK(VDGetDeviceNameAndFlags);
+ PyMac_PRECHECK(VDGetDeviceNameAndFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &ci,
- PyMac_GetStr255, outName))
- return NULL;
- _rv = VDGetDeviceNameAndFlags(ci,
- outName,
- &outNameFlags);
- _res = Py_BuildValue("ll",
- _rv,
- outNameFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &ci,
+ PyMac_GetStr255, outName))
+ return NULL;
+ _rv = VDGetDeviceNameAndFlags(ci,
+ outName,
+ &outNameFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ outNameFlags);
+ return _res;
}
static PyObject *Qt_VDCaptureStateChanging(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- VideoDigitizerComponent ci;
- UInt32 inStateFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ VideoDigitizerComponent ci;
+ UInt32 inStateFlags;
#ifndef VDCaptureStateChanging
- PyMac_PRECHECK(VDCaptureStateChanging);
+ PyMac_PRECHECK(VDCaptureStateChanging);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &ci,
- &inStateFlags))
- return NULL;
- _rv = VDCaptureStateChanging(ci,
- inStateFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &ci,
+ &inStateFlags))
+ return NULL;
+ _rv = VDCaptureStateChanging(ci,
+ inStateFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_XMLParseGetDetailedParseError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- long errorLine;
- StringPtr errDesc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ long errorLine;
+ StringPtr errDesc;
#ifndef XMLParseGetDetailedParseError
- PyMac_PRECHECK(XMLParseGetDetailedParseError);
+ PyMac_PRECHECK(XMLParseGetDetailedParseError);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &aParser,
- &errDesc))
- return NULL;
- _rv = XMLParseGetDetailedParseError(aParser,
- &errorLine,
- errDesc);
- _res = Py_BuildValue("ll",
- _rv,
- errorLine);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &aParser,
+ &errDesc))
+ return NULL;
+ _rv = XMLParseGetDetailedParseError(aParser,
+ &errorLine,
+ errDesc);
+ _res = Py_BuildValue("ll",
+ _rv,
+ errorLine);
+ return _res;
}
static PyObject *Qt_XMLParseAddElement(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- char elementName;
- UInt32 nameSpaceID;
- UInt32 elementID;
- long elementFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ char elementName;
+ UInt32 nameSpaceID;
+ UInt32 elementID;
+ long elementFlags;
#ifndef XMLParseAddElement
- PyMac_PRECHECK(XMLParseAddElement);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &aParser,
- &nameSpaceID,
- &elementFlags))
- return NULL;
- _rv = XMLParseAddElement(aParser,
- &elementName,
- nameSpaceID,
- &elementID,
- elementFlags);
- _res = Py_BuildValue("lcl",
- _rv,
- elementName,
- elementID);
- return _res;
+ PyMac_PRECHECK(XMLParseAddElement);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &aParser,
+ &nameSpaceID,
+ &elementFlags))
+ return NULL;
+ _rv = XMLParseAddElement(aParser,
+ &elementName,
+ nameSpaceID,
+ &elementID,
+ elementFlags);
+ _res = Py_BuildValue("lcl",
+ _rv,
+ elementName,
+ elementID);
+ return _res;
}
static PyObject *Qt_XMLParseAddAttribute(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- UInt32 elementID;
- UInt32 nameSpaceID;
- char attributeName;
- UInt32 attributeID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ UInt32 elementID;
+ UInt32 nameSpaceID;
+ char attributeName;
+ UInt32 attributeID;
#ifndef XMLParseAddAttribute
- PyMac_PRECHECK(XMLParseAddAttribute);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &aParser,
- &elementID,
- &nameSpaceID))
- return NULL;
- _rv = XMLParseAddAttribute(aParser,
- elementID,
- nameSpaceID,
- &attributeName,
- &attributeID);
- _res = Py_BuildValue("lcl",
- _rv,
- attributeName,
- attributeID);
- return _res;
+ PyMac_PRECHECK(XMLParseAddAttribute);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &aParser,
+ &elementID,
+ &nameSpaceID))
+ return NULL;
+ _rv = XMLParseAddAttribute(aParser,
+ elementID,
+ nameSpaceID,
+ &attributeName,
+ &attributeID);
+ _res = Py_BuildValue("lcl",
+ _rv,
+ attributeName,
+ attributeID);
+ return _res;
}
static PyObject *Qt_XMLParseAddMultipleAttributes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- UInt32 elementID;
- UInt32 nameSpaceIDs;
- char attributeNames;
- UInt32 attributeIDs;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ UInt32 elementID;
+ UInt32 nameSpaceIDs;
+ char attributeNames;
+ UInt32 attributeIDs;
#ifndef XMLParseAddMultipleAttributes
- PyMac_PRECHECK(XMLParseAddMultipleAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &aParser,
- &elementID))
- return NULL;
- _rv = XMLParseAddMultipleAttributes(aParser,
- elementID,
- &nameSpaceIDs,
- &attributeNames,
- &attributeIDs);
- _res = Py_BuildValue("llcl",
- _rv,
- nameSpaceIDs,
- attributeNames,
- attributeIDs);
- return _res;
+ PyMac_PRECHECK(XMLParseAddMultipleAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &aParser,
+ &elementID))
+ return NULL;
+ _rv = XMLParseAddMultipleAttributes(aParser,
+ elementID,
+ &nameSpaceIDs,
+ &attributeNames,
+ &attributeIDs);
+ _res = Py_BuildValue("llcl",
+ _rv,
+ nameSpaceIDs,
+ attributeNames,
+ attributeIDs);
+ return _res;
}
static PyObject *Qt_XMLParseAddAttributeAndValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- UInt32 elementID;
- UInt32 nameSpaceID;
- char attributeName;
- UInt32 attributeID;
- UInt32 attributeValueKind;
- void * attributeValueKindInfo;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ UInt32 elementID;
+ UInt32 nameSpaceID;
+ char attributeName;
+ UInt32 attributeID;
+ UInt32 attributeValueKind;
+ void * attributeValueKindInfo;
#ifndef XMLParseAddAttributeAndValue
- PyMac_PRECHECK(XMLParseAddAttributeAndValue);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llls",
- CmpInstObj_Convert, &aParser,
- &elementID,
- &nameSpaceID,
- &attributeValueKind,
- &attributeValueKindInfo))
- return NULL;
- _rv = XMLParseAddAttributeAndValue(aParser,
- elementID,
- nameSpaceID,
- &attributeName,
- &attributeID,
- attributeValueKind,
- attributeValueKindInfo);
- _res = Py_BuildValue("lcl",
- _rv,
- attributeName,
- attributeID);
- return _res;
+ PyMac_PRECHECK(XMLParseAddAttributeAndValue);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llls",
+ CmpInstObj_Convert, &aParser,
+ &elementID,
+ &nameSpaceID,
+ &attributeValueKind,
+ &attributeValueKindInfo))
+ return NULL;
+ _rv = XMLParseAddAttributeAndValue(aParser,
+ elementID,
+ nameSpaceID,
+ &attributeName,
+ &attributeID,
+ attributeValueKind,
+ attributeValueKindInfo);
+ _res = Py_BuildValue("lcl",
+ _rv,
+ attributeName,
+ attributeID);
+ return _res;
}
static PyObject *Qt_XMLParseAddAttributeValueKind(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- UInt32 elementID;
- UInt32 attributeID;
- UInt32 attributeValueKind;
- void * attributeValueKindInfo;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ UInt32 elementID;
+ UInt32 attributeID;
+ UInt32 attributeValueKind;
+ void * attributeValueKindInfo;
#ifndef XMLParseAddAttributeValueKind
- PyMac_PRECHECK(XMLParseAddAttributeValueKind);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llls",
- CmpInstObj_Convert, &aParser,
- &elementID,
- &attributeID,
- &attributeValueKind,
- &attributeValueKindInfo))
- return NULL;
- _rv = XMLParseAddAttributeValueKind(aParser,
- elementID,
- attributeID,
- attributeValueKind,
- attributeValueKindInfo);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(XMLParseAddAttributeValueKind);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llls",
+ CmpInstObj_Convert, &aParser,
+ &elementID,
+ &attributeID,
+ &attributeValueKind,
+ &attributeValueKindInfo))
+ return NULL;
+ _rv = XMLParseAddAttributeValueKind(aParser,
+ elementID,
+ attributeID,
+ attributeValueKind,
+ attributeValueKindInfo);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_XMLParseAddNameSpace(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- char nameSpaceURL;
- UInt32 nameSpaceID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ char nameSpaceURL;
+ UInt32 nameSpaceID;
#ifndef XMLParseAddNameSpace
- PyMac_PRECHECK(XMLParseAddNameSpace);
+ PyMac_PRECHECK(XMLParseAddNameSpace);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &aParser))
- return NULL;
- _rv = XMLParseAddNameSpace(aParser,
- &nameSpaceURL,
- &nameSpaceID);
- _res = Py_BuildValue("lcl",
- _rv,
- nameSpaceURL,
- nameSpaceID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &aParser))
+ return NULL;
+ _rv = XMLParseAddNameSpace(aParser,
+ &nameSpaceURL,
+ &nameSpaceID);
+ _res = Py_BuildValue("lcl",
+ _rv,
+ nameSpaceURL,
+ nameSpaceID);
+ return _res;
}
static PyObject *Qt_XMLParseSetOffsetAndLimit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- UInt32 offset;
- UInt32 limit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ UInt32 offset;
+ UInt32 limit;
#ifndef XMLParseSetOffsetAndLimit
- PyMac_PRECHECK(XMLParseSetOffsetAndLimit);
+ PyMac_PRECHECK(XMLParseSetOffsetAndLimit);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &aParser,
- &offset,
- &limit))
- return NULL;
- _rv = XMLParseSetOffsetAndLimit(aParser,
- offset,
- limit);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &aParser,
+ &offset,
+ &limit))
+ return NULL;
+ _rv = XMLParseSetOffsetAndLimit(aParser,
+ offset,
+ limit);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_XMLParseSetEventParseRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- ComponentInstance aParser;
- long refcon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ ComponentInstance aParser;
+ long refcon;
#ifndef XMLParseSetEventParseRefCon
- PyMac_PRECHECK(XMLParseSetEventParseRefCon);
+ PyMac_PRECHECK(XMLParseSetEventParseRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &aParser,
- &refcon))
- return NULL;
- _rv = XMLParseSetEventParseRefCon(aParser,
- refcon);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &aParser,
+ &refcon))
+ return NULL;
+ _rv = XMLParseSetEventParseRefCon(aParser,
+ refcon);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGInitialize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
#ifndef SGInitialize
- PyMac_PRECHECK(SGInitialize);
+ PyMac_PRECHECK(SGInitialize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGInitialize(s);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGInitialize(s);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetDataOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- FSSpec movieFile;
- long whereFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ FSSpec movieFile;
+ long whereFlags;
#ifndef SGSetDataOutput
- PyMac_PRECHECK(SGSetDataOutput);
+ PyMac_PRECHECK(SGSetDataOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &s,
- PyMac_GetFSSpec, &movieFile,
- &whereFlags))
- return NULL;
- _rv = SGSetDataOutput(s,
- &movieFile,
- whereFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &s,
+ PyMac_GetFSSpec, &movieFile,
+ &whereFlags))
+ return NULL;
+ _rv = SGSetDataOutput(s,
+ &movieFile,
+ whereFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetDataOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- FSSpec movieFile;
- long whereFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ FSSpec movieFile;
+ long whereFlags;
#ifndef SGGetDataOutput
- PyMac_PRECHECK(SGGetDataOutput);
+ PyMac_PRECHECK(SGGetDataOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- PyMac_GetFSSpec, &movieFile))
- return NULL;
- _rv = SGGetDataOutput(s,
- &movieFile,
- &whereFlags);
- _res = Py_BuildValue("ll",
- _rv,
- whereFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ PyMac_GetFSSpec, &movieFile))
+ return NULL;
+ _rv = SGGetDataOutput(s,
+ &movieFile,
+ &whereFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ whereFlags);
+ return _res;
}
static PyObject *Qt_SGSetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- CGrafPtr gp;
- GDHandle gd;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ CGrafPtr gp;
+ GDHandle gd;
#ifndef SGSetGWorld
- PyMac_PRECHECK(SGSetGWorld);
+ PyMac_PRECHECK(SGSetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &s,
- GrafObj_Convert, &gp,
- OptResObj_Convert, &gd))
- return NULL;
- _rv = SGSetGWorld(s,
- gp,
- gd);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &s,
+ GrafObj_Convert, &gp,
+ OptResObj_Convert, &gd))
+ return NULL;
+ _rv = SGSetGWorld(s,
+ gp,
+ gd);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- CGrafPtr gp;
- GDHandle gd;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ CGrafPtr gp;
+ GDHandle gd;
#ifndef SGGetGWorld
- PyMac_PRECHECK(SGGetGWorld);
+ PyMac_PRECHECK(SGGetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetGWorld(s,
- &gp,
- &gd);
- _res = Py_BuildValue("lO&O&",
- _rv,
- GrafObj_New, gp,
- OptResObj_New, gd);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetGWorld(s,
+ &gp,
+ &gd);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ GrafObj_New, gp,
+ OptResObj_New, gd);
+ return _res;
}
static PyObject *Qt_SGNewChannel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- OSType channelType;
- SGChannel ref;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ OSType channelType;
+ SGChannel ref;
#ifndef SGNewChannel
- PyMac_PRECHECK(SGNewChannel);
+ PyMac_PRECHECK(SGNewChannel);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- PyMac_GetOSType, &channelType))
- return NULL;
- _rv = SGNewChannel(s,
- channelType,
- &ref);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpInstObj_New, ref);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ PyMac_GetOSType, &channelType))
+ return NULL;
+ _rv = SGNewChannel(s,
+ channelType,
+ &ref);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpInstObj_New, ref);
+ return _res;
}
static PyObject *Qt_SGDisposeChannel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
#ifndef SGDisposeChannel
- PyMac_PRECHECK(SGDisposeChannel);
+ PyMac_PRECHECK(SGDisposeChannel);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGDisposeChannel(s,
- c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGDisposeChannel(s,
+ c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGStartPreview(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
#ifndef SGStartPreview
- PyMac_PRECHECK(SGStartPreview);
+ PyMac_PRECHECK(SGStartPreview);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGStartPreview(s);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGStartPreview(s);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGStartRecord(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
#ifndef SGStartRecord
- PyMac_PRECHECK(SGStartRecord);
+ PyMac_PRECHECK(SGStartRecord);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGStartRecord(s);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGStartRecord(s);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGIdle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
#ifndef SGIdle
- PyMac_PRECHECK(SGIdle);
+ PyMac_PRECHECK(SGIdle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGIdle(s);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGIdle(s);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGStop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
#ifndef SGStop
- PyMac_PRECHECK(SGStop);
+ PyMac_PRECHECK(SGStop);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGStop(s);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGStop(s);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPause(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Boolean pause;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Boolean pause;
#ifndef SGPause
- PyMac_PRECHECK(SGPause);
+ PyMac_PRECHECK(SGPause);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &s,
- &pause))
- return NULL;
- _rv = SGPause(s,
- pause);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &s,
+ &pause))
+ return NULL;
+ _rv = SGPause(s,
+ pause);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPrepare(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Boolean prepareForPreview;
- Boolean prepareForRecord;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Boolean prepareForPreview;
+ Boolean prepareForRecord;
#ifndef SGPrepare
- PyMac_PRECHECK(SGPrepare);
+ PyMac_PRECHECK(SGPrepare);
#endif
- if (!PyArg_ParseTuple(_args, "O&bb",
- CmpInstObj_Convert, &s,
- &prepareForPreview,
- &prepareForRecord))
- return NULL;
- _rv = SGPrepare(s,
- prepareForPreview,
- prepareForRecord);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&bb",
+ CmpInstObj_Convert, &s,
+ &prepareForPreview,
+ &prepareForRecord))
+ return NULL;
+ _rv = SGPrepare(s,
+ prepareForPreview,
+ prepareForRecord);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGRelease(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
#ifndef SGRelease
- PyMac_PRECHECK(SGRelease);
+ PyMac_PRECHECK(SGRelease);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGRelease(s);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGRelease(s);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetMovie(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Movie _rv;
- SeqGrabComponent s;
+ PyObject *_res = NULL;
+ Movie _rv;
+ SeqGrabComponent s;
#ifndef SGGetMovie
- PyMac_PRECHECK(SGGetMovie);
+ PyMac_PRECHECK(SGGetMovie);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetMovie(s);
- _res = Py_BuildValue("O&",
- MovieObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetMovie(s);
+ _res = Py_BuildValue("O&",
+ MovieObj_New, _rv);
+ return _res;
}
static PyObject *Qt_SGSetMaximumRecordTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- unsigned long ticks;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ unsigned long ticks;
#ifndef SGSetMaximumRecordTime
- PyMac_PRECHECK(SGSetMaximumRecordTime);
+ PyMac_PRECHECK(SGSetMaximumRecordTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &s,
- &ticks))
- return NULL;
- _rv = SGSetMaximumRecordTime(s,
- ticks);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &s,
+ &ticks))
+ return NULL;
+ _rv = SGSetMaximumRecordTime(s,
+ ticks);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetMaximumRecordTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- unsigned long ticks;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ unsigned long ticks;
#ifndef SGGetMaximumRecordTime
- PyMac_PRECHECK(SGGetMaximumRecordTime);
+ PyMac_PRECHECK(SGGetMaximumRecordTime);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetMaximumRecordTime(s,
- &ticks);
- _res = Py_BuildValue("ll",
- _rv,
- ticks);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetMaximumRecordTime(s,
+ &ticks);
+ _res = Py_BuildValue("ll",
+ _rv,
+ ticks);
+ return _res;
}
static PyObject *Qt_SGGetStorageSpaceRemaining(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- unsigned long bytes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ unsigned long bytes;
#ifndef SGGetStorageSpaceRemaining
- PyMac_PRECHECK(SGGetStorageSpaceRemaining);
+ PyMac_PRECHECK(SGGetStorageSpaceRemaining);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetStorageSpaceRemaining(s,
- &bytes);
- _res = Py_BuildValue("ll",
- _rv,
- bytes);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetStorageSpaceRemaining(s,
+ &bytes);
+ _res = Py_BuildValue("ll",
+ _rv,
+ bytes);
+ return _res;
}
static PyObject *Qt_SGGetTimeRemaining(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- long ticksLeft;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ long ticksLeft;
#ifndef SGGetTimeRemaining
- PyMac_PRECHECK(SGGetTimeRemaining);
+ PyMac_PRECHECK(SGGetTimeRemaining);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetTimeRemaining(s,
- &ticksLeft);
- _res = Py_BuildValue("ll",
- _rv,
- ticksLeft);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetTimeRemaining(s,
+ &ticksLeft);
+ _res = Py_BuildValue("ll",
+ _rv,
+ ticksLeft);
+ return _res;
}
static PyObject *Qt_SGGrabPict(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- PicHandle p;
- Rect bounds;
- short offscreenDepth;
- long grabPictFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ PicHandle p;
+ Rect bounds;
+ short offscreenDepth;
+ long grabPictFlags;
#ifndef SGGrabPict
- PyMac_PRECHECK(SGGrabPict);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&hl",
- CmpInstObj_Convert, &s,
- PyMac_GetRect, &bounds,
- &offscreenDepth,
- &grabPictFlags))
- return NULL;
- _rv = SGGrabPict(s,
- &p,
- &bounds,
- offscreenDepth,
- grabPictFlags);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, p);
- return _res;
+ PyMac_PRECHECK(SGGrabPict);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&hl",
+ CmpInstObj_Convert, &s,
+ PyMac_GetRect, &bounds,
+ &offscreenDepth,
+ &grabPictFlags))
+ return NULL;
+ _rv = SGGrabPict(s,
+ &p,
+ &bounds,
+ offscreenDepth,
+ grabPictFlags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, p);
+ return _res;
}
static PyObject *Qt_SGGetLastMovieResID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- short resID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ short resID;
#ifndef SGGetLastMovieResID
- PyMac_PRECHECK(SGGetLastMovieResID);
+ PyMac_PRECHECK(SGGetLastMovieResID);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetLastMovieResID(s,
- &resID);
- _res = Py_BuildValue("lh",
- _rv,
- resID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetLastMovieResID(s,
+ &resID);
+ _res = Py_BuildValue("lh",
+ _rv,
+ resID);
+ return _res;
}
static PyObject *Qt_SGSetFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- long sgFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ long sgFlags;
#ifndef SGSetFlags
- PyMac_PRECHECK(SGSetFlags);
+ PyMac_PRECHECK(SGSetFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &s,
- &sgFlags))
- return NULL;
- _rv = SGSetFlags(s,
- sgFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &s,
+ &sgFlags))
+ return NULL;
+ _rv = SGSetFlags(s,
+ sgFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- long sgFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ long sgFlags;
#ifndef SGGetFlags
- PyMac_PRECHECK(SGGetFlags);
+ PyMac_PRECHECK(SGGetFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetFlags(s,
- &sgFlags);
- _res = Py_BuildValue("ll",
- _rv,
- sgFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetFlags(s,
+ &sgFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ sgFlags);
+ return _res;
}
static PyObject *Qt_SGNewChannelFromComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel newChannel;
- Component sgChannelComponent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel newChannel;
+ Component sgChannelComponent;
#ifndef SGNewChannelFromComponent
- PyMac_PRECHECK(SGNewChannelFromComponent);
+ PyMac_PRECHECK(SGNewChannelFromComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- CmpObj_Convert, &sgChannelComponent))
- return NULL;
- _rv = SGNewChannelFromComponent(s,
- &newChannel,
- sgChannelComponent);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpInstObj_New, newChannel);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ CmpObj_Convert, &sgChannelComponent))
+ return NULL;
+ _rv = SGNewChannelFromComponent(s,
+ &newChannel,
+ sgChannelComponent);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpInstObj_New, newChannel);
+ return _res;
}
static PyObject *Qt_SGSetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- UserData ud;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ UserData ud;
+ long flags;
#ifndef SGSetSettings
- PyMac_PRECHECK(SGSetSettings);
+ PyMac_PRECHECK(SGSetSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &s,
- UserDataObj_Convert, &ud,
- &flags))
- return NULL;
- _rv = SGSetSettings(s,
- ud,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &s,
+ UserDataObj_Convert, &ud,
+ &flags))
+ return NULL;
+ _rv = SGSetSettings(s,
+ ud,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- UserData ud;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ UserData ud;
+ long flags;
#ifndef SGGetSettings
- PyMac_PRECHECK(SGGetSettings);
+ PyMac_PRECHECK(SGGetSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &s,
- &flags))
- return NULL;
- _rv = SGGetSettings(s,
- &ud,
- flags);
- _res = Py_BuildValue("lO&",
- _rv,
- UserDataObj_New, ud);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &s,
+ &flags))
+ return NULL;
+ _rv = SGGetSettings(s,
+ &ud,
+ flags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ UserDataObj_New, ud);
+ return _res;
}
static PyObject *Qt_SGGetIndChannel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- short index;
- SGChannel ref;
- OSType chanType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ short index;
+ SGChannel ref;
+ OSType chanType;
#ifndef SGGetIndChannel
- PyMac_PRECHECK(SGGetIndChannel);
-#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &s,
- &index))
- return NULL;
- _rv = SGGetIndChannel(s,
- index,
- &ref,
- &chanType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- CmpInstObj_New, ref,
- PyMac_BuildOSType, chanType);
- return _res;
+ PyMac_PRECHECK(SGGetIndChannel);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &s,
+ &index))
+ return NULL;
+ _rv = SGGetIndChannel(s,
+ index,
+ &ref,
+ &chanType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ CmpInstObj_New, ref,
+ PyMac_BuildOSType, chanType);
+ return _res;
}
static PyObject *Qt_SGUpdate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- RgnHandle updateRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ RgnHandle updateRgn;
#ifndef SGUpdate
- PyMac_PRECHECK(SGUpdate);
+ PyMac_PRECHECK(SGUpdate);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- ResObj_Convert, &updateRgn))
- return NULL;
- _rv = SGUpdate(s,
- updateRgn);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ ResObj_Convert, &updateRgn))
+ return NULL;
+ _rv = SGUpdate(s,
+ updateRgn);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetPause(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Boolean paused;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Boolean paused;
#ifndef SGGetPause
- PyMac_PRECHECK(SGGetPause);
+ PyMac_PRECHECK(SGGetPause);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetPause(s,
- &paused);
- _res = Py_BuildValue("lb",
- _rv,
- paused);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetPause(s,
+ &paused);
+ _res = Py_BuildValue("lb",
+ _rv,
+ paused);
+ return _res;
}
static PyObject *Qt_SGSetChannelSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- UserData ud;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ UserData ud;
+ long flags;
#ifndef SGSetChannelSettings
- PyMac_PRECHECK(SGSetChannelSettings);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- UserDataObj_Convert, &ud,
- &flags))
- return NULL;
- _rv = SGSetChannelSettings(s,
- c,
- ud,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGSetChannelSettings);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ UserDataObj_Convert, &ud,
+ &flags))
+ return NULL;
+ _rv = SGSetChannelSettings(s,
+ c,
+ ud,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- UserData ud;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ UserData ud;
+ long flags;
#ifndef SGGetChannelSettings
- PyMac_PRECHECK(SGGetChannelSettings);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- &flags))
- return NULL;
- _rv = SGGetChannelSettings(s,
- c,
- &ud,
- flags);
- _res = Py_BuildValue("lO&",
- _rv,
- UserDataObj_New, ud);
- return _res;
+ PyMac_PRECHECK(SGGetChannelSettings);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ &flags))
+ return NULL;
+ _rv = SGGetChannelSettings(s,
+ c,
+ &ud,
+ flags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ UserDataObj_New, ud);
+ return _res;
}
static PyObject *Qt_SGGetMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Boolean previewMode;
- Boolean recordMode;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Boolean previewMode;
+ Boolean recordMode;
#ifndef SGGetMode
- PyMac_PRECHECK(SGGetMode);
+ PyMac_PRECHECK(SGGetMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetMode(s,
- &previewMode,
- &recordMode);
- _res = Py_BuildValue("lbb",
- _rv,
- previewMode,
- recordMode);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetMode(s,
+ &previewMode,
+ &recordMode);
+ _res = Py_BuildValue("lbb",
+ _rv,
+ previewMode,
+ recordMode);
+ return _res;
}
static PyObject *Qt_SGSetDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Handle dataRef;
- OSType dataRefType;
- long whereFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Handle dataRef;
+ OSType dataRefType;
+ long whereFlags;
#ifndef SGSetDataRef
- PyMac_PRECHECK(SGSetDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- CmpInstObj_Convert, &s,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- &whereFlags))
- return NULL;
- _rv = SGSetDataRef(s,
- dataRef,
- dataRefType,
- whereFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGSetDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ CmpInstObj_Convert, &s,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ &whereFlags))
+ return NULL;
+ _rv = SGSetDataRef(s,
+ dataRef,
+ dataRefType,
+ whereFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetDataRef(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Handle dataRef;
- OSType dataRefType;
- long whereFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Handle dataRef;
+ OSType dataRefType;
+ long whereFlags;
#ifndef SGGetDataRef
- PyMac_PRECHECK(SGGetDataRef);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetDataRef(s,
- &dataRef,
- &dataRefType,
- &whereFlags);
- _res = Py_BuildValue("lO&O&l",
- _rv,
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType,
- whereFlags);
- return _res;
+ PyMac_PRECHECK(SGGetDataRef);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetDataRef(s,
+ &dataRef,
+ &dataRefType,
+ &whereFlags);
+ _res = Py_BuildValue("lO&O&l",
+ _rv,
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType,
+ whereFlags);
+ return _res;
}
static PyObject *Qt_SGNewOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Handle dataRef;
- OSType dataRefType;
- long whereFlags;
- SGOutput sgOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Handle dataRef;
+ OSType dataRefType;
+ long whereFlags;
+ SGOutput sgOut;
#ifndef SGNewOutput
- PyMac_PRECHECK(SGNewOutput);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- CmpInstObj_Convert, &s,
- ResObj_Convert, &dataRef,
- PyMac_GetOSType, &dataRefType,
- &whereFlags))
- return NULL;
- _rv = SGNewOutput(s,
- dataRef,
- dataRefType,
- whereFlags,
- &sgOut);
- _res = Py_BuildValue("lO&",
- _rv,
- SGOutputObj_New, sgOut);
- return _res;
+ PyMac_PRECHECK(SGNewOutput);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ CmpInstObj_Convert, &s,
+ ResObj_Convert, &dataRef,
+ PyMac_GetOSType, &dataRefType,
+ &whereFlags))
+ return NULL;
+ _rv = SGNewOutput(s,
+ dataRef,
+ dataRefType,
+ whereFlags,
+ &sgOut);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ SGOutputObj_New, sgOut);
+ return _res;
}
static PyObject *Qt_SGDisposeOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
#ifndef SGDisposeOutput
- PyMac_PRECHECK(SGDisposeOutput);
+ PyMac_PRECHECK(SGDisposeOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGDisposeOutput(s,
- sgOut);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGDisposeOutput(s,
+ sgOut);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetOutputFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- long whereFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ long whereFlags;
#ifndef SGSetOutputFlags
- PyMac_PRECHECK(SGSetOutputFlags);
+ PyMac_PRECHECK(SGSetOutputFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut,
- &whereFlags))
- return NULL;
- _rv = SGSetOutputFlags(s,
- sgOut,
- whereFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut,
+ &whereFlags))
+ return NULL;
+ _rv = SGSetOutputFlags(s,
+ sgOut,
+ whereFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetChannelOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- SGOutput sgOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ SGOutput sgOut;
#ifndef SGSetChannelOutput
- PyMac_PRECHECK(SGSetChannelOutput);
+ PyMac_PRECHECK(SGSetChannelOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGSetChannelOutput(s,
- c,
- sgOut);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGSetChannelOutput(s,
+ c,
+ sgOut);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetDataOutputStorageSpaceRemaining(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- unsigned long space;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ unsigned long space;
#ifndef SGGetDataOutputStorageSpaceRemaining
- PyMac_PRECHECK(SGGetDataOutputStorageSpaceRemaining);
+ PyMac_PRECHECK(SGGetDataOutputStorageSpaceRemaining);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGGetDataOutputStorageSpaceRemaining(s,
- sgOut,
- &space);
- _res = Py_BuildValue("ll",
- _rv,
- space);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGGetDataOutputStorageSpaceRemaining(s,
+ sgOut,
+ &space);
+ _res = Py_BuildValue("ll",
+ _rv,
+ space);
+ return _res;
}
static PyObject *Qt_SGHandleUpdateEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- EventRecord event;
- Boolean handled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ EventRecord event;
+ Boolean handled;
#ifndef SGHandleUpdateEvent
- PyMac_PRECHECK(SGHandleUpdateEvent);
+ PyMac_PRECHECK(SGHandleUpdateEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- PyMac_GetEventRecord, &event))
- return NULL;
- _rv = SGHandleUpdateEvent(s,
- &event,
- &handled);
- _res = Py_BuildValue("lb",
- _rv,
- handled);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ PyMac_GetEventRecord, &event))
+ return NULL;
+ _rv = SGHandleUpdateEvent(s,
+ &event,
+ &handled);
+ _res = Py_BuildValue("lb",
+ _rv,
+ handled);
+ return _res;
}
static PyObject *Qt_SGSetOutputNextOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- SGOutput nextOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ SGOutput nextOut;
#ifndef SGSetOutputNextOutput
- PyMac_PRECHECK(SGSetOutputNextOutput);
+ PyMac_PRECHECK(SGSetOutputNextOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut,
- SGOutputObj_Convert, &nextOut))
- return NULL;
- _rv = SGSetOutputNextOutput(s,
- sgOut,
- nextOut);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut,
+ SGOutputObj_Convert, &nextOut))
+ return NULL;
+ _rv = SGSetOutputNextOutput(s,
+ sgOut,
+ nextOut);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetOutputNextOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- SGOutput nextOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ SGOutput nextOut;
#ifndef SGGetOutputNextOutput
- PyMac_PRECHECK(SGGetOutputNextOutput);
+ PyMac_PRECHECK(SGGetOutputNextOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGGetOutputNextOutput(s,
- sgOut,
- &nextOut);
- _res = Py_BuildValue("lO&",
- _rv,
- SGOutputObj_New, nextOut);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGGetOutputNextOutput(s,
+ sgOut,
+ &nextOut);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ SGOutputObj_New, nextOut);
+ return _res;
}
static PyObject *Qt_SGSetOutputMaximumOffset(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- wide maxOffset;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ wide maxOffset;
#ifndef SGSetOutputMaximumOffset
- PyMac_PRECHECK(SGSetOutputMaximumOffset);
+ PyMac_PRECHECK(SGSetOutputMaximumOffset);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut,
- PyMac_Getwide, &maxOffset))
- return NULL;
- _rv = SGSetOutputMaximumOffset(s,
- sgOut,
- &maxOffset);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut,
+ PyMac_Getwide, &maxOffset))
+ return NULL;
+ _rv = SGSetOutputMaximumOffset(s,
+ sgOut,
+ &maxOffset);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetOutputMaximumOffset(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- wide maxOffset;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ wide maxOffset;
#ifndef SGGetOutputMaximumOffset
- PyMac_PRECHECK(SGGetOutputMaximumOffset);
+ PyMac_PRECHECK(SGGetOutputMaximumOffset);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGGetOutputMaximumOffset(s,
- sgOut,
- &maxOffset);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, maxOffset);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGGetOutputMaximumOffset(s,
+ sgOut,
+ &maxOffset);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, maxOffset);
+ return _res;
}
static PyObject *Qt_SGGetOutputDataReference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- Handle dataRef;
- OSType dataRefType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ Handle dataRef;
+ OSType dataRefType;
#ifndef SGGetOutputDataReference
- PyMac_PRECHECK(SGGetOutputDataReference);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGGetOutputDataReference(s,
- sgOut,
- &dataRef,
- &dataRefType);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, dataRef,
- PyMac_BuildOSType, dataRefType);
- return _res;
+ PyMac_PRECHECK(SGGetOutputDataReference);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGGetOutputDataReference(s,
+ sgOut,
+ &dataRef,
+ &dataRefType);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, dataRef,
+ PyMac_BuildOSType, dataRefType);
+ return _res;
}
static PyObject *Qt_SGWriteExtendedMovieData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- Ptr p;
- long len;
- wide offset;
- SGOutput sgOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ Ptr p;
+ long len;
+ wide offset;
+ SGOutput sgOut;
#ifndef SGWriteExtendedMovieData
- PyMac_PRECHECK(SGWriteExtendedMovieData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&sl",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- &p,
- &len))
- return NULL;
- _rv = SGWriteExtendedMovieData(s,
- c,
- p,
- len,
- &offset,
- &sgOut);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_Buildwide, offset,
- SGOutputObj_New, sgOut);
- return _res;
+ PyMac_PRECHECK(SGWriteExtendedMovieData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&sl",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ &p,
+ &len))
+ return NULL;
+ _rv = SGWriteExtendedMovieData(s,
+ c,
+ p,
+ len,
+ &offset,
+ &sgOut);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_Buildwide, offset,
+ SGOutputObj_New, sgOut);
+ return _res;
}
static PyObject *Qt_SGGetStorageSpaceRemaining64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- wide bytes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ wide bytes;
#ifndef SGGetStorageSpaceRemaining64
- PyMac_PRECHECK(SGGetStorageSpaceRemaining64);
+ PyMac_PRECHECK(SGGetStorageSpaceRemaining64);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetStorageSpaceRemaining64(s,
- &bytes);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, bytes);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetStorageSpaceRemaining64(s,
+ &bytes);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, bytes);
+ return _res;
}
static PyObject *Qt_SGGetDataOutputStorageSpaceRemaining64(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- wide space;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ wide space;
#ifndef SGGetDataOutputStorageSpaceRemaining64
- PyMac_PRECHECK(SGGetDataOutputStorageSpaceRemaining64);
+ PyMac_PRECHECK(SGGetDataOutputStorageSpaceRemaining64);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut))
- return NULL;
- _rv = SGGetDataOutputStorageSpaceRemaining64(s,
- sgOut,
- &space);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_Buildwide, space);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut))
+ return NULL;
+ _rv = SGGetDataOutputStorageSpaceRemaining64(s,
+ sgOut,
+ &space);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_Buildwide, space);
+ return _res;
}
static PyObject *Qt_SGWriteMovieData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- Ptr p;
- long len;
- long offset;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ Ptr p;
+ long len;
+ long offset;
#ifndef SGWriteMovieData
- PyMac_PRECHECK(SGWriteMovieData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&sl",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- &p,
- &len))
- return NULL;
- _rv = SGWriteMovieData(s,
- c,
- p,
- len,
- &offset);
- _res = Py_BuildValue("ll",
- _rv,
- offset);
- return _res;
+ PyMac_PRECHECK(SGWriteMovieData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&sl",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ &p,
+ &len))
+ return NULL;
+ _rv = SGWriteMovieData(s,
+ c,
+ p,
+ len,
+ &offset);
+ _res = Py_BuildValue("ll",
+ _rv,
+ offset);
+ return _res;
}
static PyObject *Qt_SGGetTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- TimeBase tb;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ TimeBase tb;
#ifndef SGGetTimeBase
- PyMac_PRECHECK(SGGetTimeBase);
+ PyMac_PRECHECK(SGGetTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGGetTimeBase(s,
- &tb);
- _res = Py_BuildValue("lO&",
- _rv,
- TimeBaseObj_New, tb);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGGetTimeBase(s,
+ &tb);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ TimeBaseObj_New, tb);
+ return _res;
}
static PyObject *Qt_SGAddMovieData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- Ptr p;
- long len;
- long offset;
- long chRefCon;
- TimeValue time;
- short writeType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ Ptr p;
+ long len;
+ long offset;
+ long chRefCon;
+ TimeValue time;
+ short writeType;
#ifndef SGAddMovieData
- PyMac_PRECHECK(SGAddMovieData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&slllh",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- &p,
- &len,
- &chRefCon,
- &time,
- &writeType))
- return NULL;
- _rv = SGAddMovieData(s,
- c,
- p,
- len,
- &offset,
- chRefCon,
- time,
- writeType);
- _res = Py_BuildValue("ll",
- _rv,
- offset);
- return _res;
+ PyMac_PRECHECK(SGAddMovieData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&slllh",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ &p,
+ &len,
+ &chRefCon,
+ &time,
+ &writeType))
+ return NULL;
+ _rv = SGAddMovieData(s,
+ c,
+ p,
+ len,
+ &offset,
+ chRefCon,
+ time,
+ writeType);
+ _res = Py_BuildValue("ll",
+ _rv,
+ offset);
+ return _res;
}
static PyObject *Qt_SGChangedSource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
#ifndef SGChangedSource
- PyMac_PRECHECK(SGChangedSource);
+ PyMac_PRECHECK(SGChangedSource);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGChangedSource(s,
- c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGChangedSource(s,
+ c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGAddExtendedMovieData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- Ptr p;
- long len;
- wide offset;
- long chRefCon;
- TimeValue time;
- short writeType;
- SGOutput whichOutput;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ Ptr p;
+ long len;
+ wide offset;
+ long chRefCon;
+ TimeValue time;
+ short writeType;
+ SGOutput whichOutput;
#ifndef SGAddExtendedMovieData
- PyMac_PRECHECK(SGAddExtendedMovieData);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&slllh",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- &p,
- &len,
- &chRefCon,
- &time,
- &writeType))
- return NULL;
- _rv = SGAddExtendedMovieData(s,
- c,
- p,
- len,
- &offset,
- chRefCon,
- time,
- writeType,
- &whichOutput);
- _res = Py_BuildValue("lO&O&",
- _rv,
- PyMac_Buildwide, offset,
- SGOutputObj_New, whichOutput);
- return _res;
+ PyMac_PRECHECK(SGAddExtendedMovieData);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&slllh",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ &p,
+ &len,
+ &chRefCon,
+ &time,
+ &writeType))
+ return NULL;
+ _rv = SGAddExtendedMovieData(s,
+ c,
+ p,
+ len,
+ &offset,
+ chRefCon,
+ time,
+ writeType,
+ &whichOutput);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ PyMac_Buildwide, offset,
+ SGOutputObj_New, whichOutput);
+ return _res;
}
static PyObject *Qt_SGAddOutputDataRefToMedia(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGOutput sgOut;
- Media theMedia;
- SampleDescriptionHandle desc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGOutput sgOut;
+ Media theMedia;
+ SampleDescriptionHandle desc;
#ifndef SGAddOutputDataRefToMedia
- PyMac_PRECHECK(SGAddOutputDataRefToMedia);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&O&",
- CmpInstObj_Convert, &s,
- SGOutputObj_Convert, &sgOut,
- MediaObj_Convert, &theMedia,
- ResObj_Convert, &desc))
- return NULL;
- _rv = SGAddOutputDataRefToMedia(s,
- sgOut,
- theMedia,
- desc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGAddOutputDataRefToMedia);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&O&",
+ CmpInstObj_Convert, &s,
+ SGOutputObj_Convert, &sgOut,
+ MediaObj_Convert, &theMedia,
+ ResObj_Convert, &desc))
+ return NULL;
+ _rv = SGAddOutputDataRefToMedia(s,
+ sgOut,
+ theMedia,
+ desc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetSettingsSummary(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Handle summaryText;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Handle summaryText;
#ifndef SGSetSettingsSummary
- PyMac_PRECHECK(SGSetSettingsSummary);
+ PyMac_PRECHECK(SGSetSettingsSummary);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- ResObj_Convert, &summaryText))
- return NULL;
- _rv = SGSetSettingsSummary(s,
- summaryText);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ ResObj_Convert, &summaryText))
+ return NULL;
+ _rv = SGSetSettingsSummary(s,
+ summaryText);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetChannelUsage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long usage;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long usage;
#ifndef SGSetChannelUsage
- PyMac_PRECHECK(SGSetChannelUsage);
+ PyMac_PRECHECK(SGSetChannelUsage);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &usage))
- return NULL;
- _rv = SGSetChannelUsage(c,
- usage);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &usage))
+ return NULL;
+ _rv = SGSetChannelUsage(c,
+ usage);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelUsage(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long usage;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long usage;
#ifndef SGGetChannelUsage
- PyMac_PRECHECK(SGGetChannelUsage);
+ PyMac_PRECHECK(SGGetChannelUsage);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelUsage(c,
- &usage);
- _res = Py_BuildValue("ll",
- _rv,
- usage);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelUsage(c,
+ &usage);
+ _res = Py_BuildValue("ll",
+ _rv,
+ usage);
+ return _res;
}
static PyObject *Qt_SGSetChannelBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Rect bounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Rect bounds;
#ifndef SGSetChannelBounds
- PyMac_PRECHECK(SGSetChannelBounds);
+ PyMac_PRECHECK(SGSetChannelBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetRect, &bounds))
- return NULL;
- _rv = SGSetChannelBounds(c,
- &bounds);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetRect, &bounds))
+ return NULL;
+ _rv = SGSetChannelBounds(c,
+ &bounds);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Rect bounds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Rect bounds;
#ifndef SGGetChannelBounds
- PyMac_PRECHECK(SGGetChannelBounds);
+ PyMac_PRECHECK(SGGetChannelBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelBounds(c,
- &bounds);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelBounds(c,
+ &bounds);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *Qt_SGSetChannelVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short volume;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short volume;
#ifndef SGSetChannelVolume
- PyMac_PRECHECK(SGSetChannelVolume);
+ PyMac_PRECHECK(SGSetChannelVolume);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &volume))
- return NULL;
- _rv = SGSetChannelVolume(c,
- volume);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &volume))
+ return NULL;
+ _rv = SGSetChannelVolume(c,
+ volume);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short volume;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short volume;
#ifndef SGGetChannelVolume
- PyMac_PRECHECK(SGGetChannelVolume);
+ PyMac_PRECHECK(SGGetChannelVolume);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelVolume(c,
- &volume);
- _res = Py_BuildValue("lh",
- _rv,
- volume);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelVolume(c,
+ &volume);
+ _res = Py_BuildValue("lh",
+ _rv,
+ volume);
+ return _res;
}
static PyObject *Qt_SGGetChannelInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long channelInfo;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long channelInfo;
#ifndef SGGetChannelInfo
- PyMac_PRECHECK(SGGetChannelInfo);
+ PyMac_PRECHECK(SGGetChannelInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelInfo(c,
- &channelInfo);
- _res = Py_BuildValue("ll",
- _rv,
- channelInfo);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelInfo(c,
+ &channelInfo);
+ _res = Py_BuildValue("ll",
+ _rv,
+ channelInfo);
+ return _res;
}
static PyObject *Qt_SGSetChannelPlayFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long playFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long playFlags;
#ifndef SGSetChannelPlayFlags
- PyMac_PRECHECK(SGSetChannelPlayFlags);
+ PyMac_PRECHECK(SGSetChannelPlayFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &playFlags))
- return NULL;
- _rv = SGSetChannelPlayFlags(c,
- playFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &playFlags))
+ return NULL;
+ _rv = SGSetChannelPlayFlags(c,
+ playFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelPlayFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long playFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long playFlags;
#ifndef SGGetChannelPlayFlags
- PyMac_PRECHECK(SGGetChannelPlayFlags);
+ PyMac_PRECHECK(SGGetChannelPlayFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelPlayFlags(c,
- &playFlags);
- _res = Py_BuildValue("ll",
- _rv,
- playFlags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelPlayFlags(c,
+ &playFlags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ playFlags);
+ return _res;
}
static PyObject *Qt_SGSetChannelMaxFrames(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long frameCount;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long frameCount;
#ifndef SGSetChannelMaxFrames
- PyMac_PRECHECK(SGSetChannelMaxFrames);
+ PyMac_PRECHECK(SGSetChannelMaxFrames);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &frameCount))
- return NULL;
- _rv = SGSetChannelMaxFrames(c,
- frameCount);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &frameCount))
+ return NULL;
+ _rv = SGSetChannelMaxFrames(c,
+ frameCount);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelMaxFrames(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long frameCount;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long frameCount;
#ifndef SGGetChannelMaxFrames
- PyMac_PRECHECK(SGGetChannelMaxFrames);
+ PyMac_PRECHECK(SGGetChannelMaxFrames);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelMaxFrames(c,
- &frameCount);
- _res = Py_BuildValue("ll",
- _rv,
- frameCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelMaxFrames(c,
+ &frameCount);
+ _res = Py_BuildValue("ll",
+ _rv,
+ frameCount);
+ return _res;
}
static PyObject *Qt_SGSetChannelRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long refCon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long refCon;
#ifndef SGSetChannelRefCon
- PyMac_PRECHECK(SGSetChannelRefCon);
+ PyMac_PRECHECK(SGSetChannelRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &refCon))
- return NULL;
- _rv = SGSetChannelRefCon(c,
- refCon);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &refCon))
+ return NULL;
+ _rv = SGSetChannelRefCon(c,
+ refCon);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetChannelClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- RgnHandle theClip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ RgnHandle theClip;
#ifndef SGSetChannelClip
- PyMac_PRECHECK(SGSetChannelClip);
+ PyMac_PRECHECK(SGSetChannelClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- ResObj_Convert, &theClip))
- return NULL;
- _rv = SGSetChannelClip(c,
- theClip);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ ResObj_Convert, &theClip))
+ return NULL;
+ _rv = SGSetChannelClip(c,
+ theClip);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- RgnHandle theClip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ RgnHandle theClip;
#ifndef SGGetChannelClip
- PyMac_PRECHECK(SGGetChannelClip);
+ PyMac_PRECHECK(SGGetChannelClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelClip(c,
- &theClip);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, theClip);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelClip(c,
+ &theClip);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, theClip);
+ return _res;
}
static PyObject *Qt_SGGetChannelSampleDescription(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle sampleDesc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle sampleDesc;
#ifndef SGGetChannelSampleDescription
- PyMac_PRECHECK(SGGetChannelSampleDescription);
+ PyMac_PRECHECK(SGGetChannelSampleDescription);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- ResObj_Convert, &sampleDesc))
- return NULL;
- _rv = SGGetChannelSampleDescription(c,
- sampleDesc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ ResObj_Convert, &sampleDesc))
+ return NULL;
+ _rv = SGGetChannelSampleDescription(c,
+ sampleDesc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetChannelDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- StringPtr name;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ StringPtr name;
#ifndef SGSetChannelDevice
- PyMac_PRECHECK(SGSetChannelDevice);
+ PyMac_PRECHECK(SGSetChannelDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &c,
- &name))
- return NULL;
- _rv = SGSetChannelDevice(c,
- name);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &c,
+ &name))
+ return NULL;
+ _rv = SGSetChannelDevice(c,
+ name);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetChannelTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- TimeScale scale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ TimeScale scale;
#ifndef SGGetChannelTimeScale
- PyMac_PRECHECK(SGGetChannelTimeScale);
+ PyMac_PRECHECK(SGGetChannelTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelTimeScale(c,
- &scale);
- _res = Py_BuildValue("ll",
- _rv,
- scale);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelTimeScale(c,
+ &scale);
+ _res = Py_BuildValue("ll",
+ _rv,
+ scale);
+ return _res;
}
static PyObject *Qt_SGChannelPutPicture(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
#ifndef SGChannelPutPicture
- PyMac_PRECHECK(SGChannelPutPicture);
+ PyMac_PRECHECK(SGChannelPutPicture);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGChannelPutPicture(c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGChannelPutPicture(c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGChannelSetRequestedDataRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long bytesPerSecond;
#ifndef SGChannelSetRequestedDataRate
- PyMac_PRECHECK(SGChannelSetRequestedDataRate);
+ PyMac_PRECHECK(SGChannelSetRequestedDataRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &bytesPerSecond))
- return NULL;
- _rv = SGChannelSetRequestedDataRate(c,
- bytesPerSecond);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &bytesPerSecond))
+ return NULL;
+ _rv = SGChannelSetRequestedDataRate(c,
+ bytesPerSecond);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGChannelGetRequestedDataRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long bytesPerSecond;
#ifndef SGChannelGetRequestedDataRate
- PyMac_PRECHECK(SGChannelGetRequestedDataRate);
+ PyMac_PRECHECK(SGChannelGetRequestedDataRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGChannelGetRequestedDataRate(c,
- &bytesPerSecond);
- _res = Py_BuildValue("ll",
- _rv,
- bytesPerSecond);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGChannelGetRequestedDataRate(c,
+ &bytesPerSecond);
+ _res = Py_BuildValue("ll",
+ _rv,
+ bytesPerSecond);
+ return _res;
}
static PyObject *Qt_SGChannelSetDataSourceName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Str255 name;
- ScriptCode scriptTag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Str255 name;
+ ScriptCode scriptTag;
#ifndef SGChannelSetDataSourceName
- PyMac_PRECHECK(SGChannelSetDataSourceName);
+ PyMac_PRECHECK(SGChannelSetDataSourceName);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- CmpInstObj_Convert, &c,
- PyMac_GetStr255, name,
- &scriptTag))
- return NULL;
- _rv = SGChannelSetDataSourceName(c,
- name,
- scriptTag);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ CmpInstObj_Convert, &c,
+ PyMac_GetStr255, name,
+ &scriptTag))
+ return NULL;
+ _rv = SGChannelSetDataSourceName(c,
+ name,
+ scriptTag);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGChannelGetDataSourceName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Str255 name;
- ScriptCode scriptTag;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Str255 name;
+ ScriptCode scriptTag;
#ifndef SGChannelGetDataSourceName
- PyMac_PRECHECK(SGChannelGetDataSourceName);
+ PyMac_PRECHECK(SGChannelGetDataSourceName);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetStr255, name))
- return NULL;
- _rv = SGChannelGetDataSourceName(c,
- name,
- &scriptTag);
- _res = Py_BuildValue("lh",
- _rv,
- scriptTag);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetStr255, name))
+ return NULL;
+ _rv = SGChannelGetDataSourceName(c,
+ name,
+ &scriptTag);
+ _res = Py_BuildValue("lh",
+ _rv,
+ scriptTag);
+ return _res;
}
static PyObject *Qt_SGChannelSetCodecSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle settings;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle settings;
#ifndef SGChannelSetCodecSettings
- PyMac_PRECHECK(SGChannelSetCodecSettings);
+ PyMac_PRECHECK(SGChannelSetCodecSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- ResObj_Convert, &settings))
- return NULL;
- _rv = SGChannelSetCodecSettings(c,
- settings);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ ResObj_Convert, &settings))
+ return NULL;
+ _rv = SGChannelSetCodecSettings(c,
+ settings);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGChannelGetCodecSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle settings;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle settings;
#ifndef SGChannelGetCodecSettings
- PyMac_PRECHECK(SGChannelGetCodecSettings);
+ PyMac_PRECHECK(SGChannelGetCodecSettings);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGChannelGetCodecSettings(c,
- &settings);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, settings);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGChannelGetCodecSettings(c,
+ &settings);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, settings);
+ return _res;
}
static PyObject *Qt_SGGetChannelTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- TimeBase tb;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ TimeBase tb;
#ifndef SGGetChannelTimeBase
- PyMac_PRECHECK(SGGetChannelTimeBase);
+ PyMac_PRECHECK(SGGetChannelTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelTimeBase(c,
- &tb);
- _res = Py_BuildValue("lO&",
- _rv,
- TimeBaseObj_New, tb);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelTimeBase(c,
+ &tb);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ TimeBaseObj_New, tb);
+ return _res;
}
static PyObject *Qt_SGGetChannelRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long refCon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long refCon;
#ifndef SGGetChannelRefCon
- PyMac_PRECHECK(SGGetChannelRefCon);
+ PyMac_PRECHECK(SGGetChannelRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetChannelRefCon(c,
- &refCon);
- _res = Py_BuildValue("ll",
- _rv,
- refCon);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetChannelRefCon(c,
+ &refCon);
+ _res = Py_BuildValue("ll",
+ _rv,
+ refCon);
+ return _res;
}
static PyObject *Qt_SGGetChannelDeviceAndInputNames(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Str255 outDeviceName;
- Str255 outInputName;
- short outInputNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Str255 outDeviceName;
+ Str255 outInputName;
+ short outInputNumber;
#ifndef SGGetChannelDeviceAndInputNames
- PyMac_PRECHECK(SGGetChannelDeviceAndInputNames);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetStr255, outDeviceName,
- PyMac_GetStr255, outInputName))
- return NULL;
- _rv = SGGetChannelDeviceAndInputNames(c,
- outDeviceName,
- outInputName,
- &outInputNumber);
- _res = Py_BuildValue("lh",
- _rv,
- outInputNumber);
- return _res;
+ PyMac_PRECHECK(SGGetChannelDeviceAndInputNames);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetStr255, outDeviceName,
+ PyMac_GetStr255, outInputName))
+ return NULL;
+ _rv = SGGetChannelDeviceAndInputNames(c,
+ outDeviceName,
+ outInputName,
+ &outInputNumber);
+ _res = Py_BuildValue("lh",
+ _rv,
+ outInputNumber);
+ return _res;
}
static PyObject *Qt_SGSetChannelDeviceInput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short inInputNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short inInputNumber;
#ifndef SGSetChannelDeviceInput
- PyMac_PRECHECK(SGSetChannelDeviceInput);
+ PyMac_PRECHECK(SGSetChannelDeviceInput);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &inInputNumber))
- return NULL;
- _rv = SGSetChannelDeviceInput(c,
- inInputNumber);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &inInputNumber))
+ return NULL;
+ _rv = SGSetChannelDeviceInput(c,
+ inInputNumber);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetChannelSettingsStateChanging(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- UInt32 inFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ UInt32 inFlags;
#ifndef SGSetChannelSettingsStateChanging
- PyMac_PRECHECK(SGSetChannelSettingsStateChanging);
+ PyMac_PRECHECK(SGSetChannelSettingsStateChanging);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &inFlags))
- return NULL;
- _rv = SGSetChannelSettingsStateChanging(c,
- inFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &inFlags))
+ return NULL;
+ _rv = SGSetChannelSettingsStateChanging(c,
+ inFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGInitChannel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- SeqGrabComponent owner;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ SeqGrabComponent owner;
#ifndef SGInitChannel
- PyMac_PRECHECK(SGInitChannel);
+ PyMac_PRECHECK(SGInitChannel);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- CmpInstObj_Convert, &owner))
- return NULL;
- _rv = SGInitChannel(c,
- owner);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ CmpInstObj_Convert, &owner))
+ return NULL;
+ _rv = SGInitChannel(c,
+ owner);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGWriteSamples(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Movie m;
- AliasHandle theFile;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Movie m;
+ AliasHandle theFile;
#ifndef SGWriteSamples
- PyMac_PRECHECK(SGWriteSamples);
+ PyMac_PRECHECK(SGWriteSamples);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &c,
- MovieObj_Convert, &m,
- ResObj_Convert, &theFile))
- return NULL;
- _rv = SGWriteSamples(c,
- m,
- theFile);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &c,
+ MovieObj_Convert, &m,
+ ResObj_Convert, &theFile))
+ return NULL;
+ _rv = SGWriteSamples(c,
+ m,
+ theFile);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetDataRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long bytesPerSecond;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long bytesPerSecond;
#ifndef SGGetDataRate
- PyMac_PRECHECK(SGGetDataRate);
+ PyMac_PRECHECK(SGGetDataRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetDataRate(c,
- &bytesPerSecond);
- _res = Py_BuildValue("ll",
- _rv,
- bytesPerSecond);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetDataRate(c,
+ &bytesPerSecond);
+ _res = Py_BuildValue("ll",
+ _rv,
+ bytesPerSecond);
+ return _res;
}
static PyObject *Qt_SGAlignChannelRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Rect r;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Rect r;
#ifndef SGAlignChannelRect
- PyMac_PRECHECK(SGAlignChannelRect);
+ PyMac_PRECHECK(SGAlignChannelRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGAlignChannelRect(c,
- &r);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGAlignChannelRect(c,
+ &r);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qt_SGPanelGetDitl(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Handle ditl;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Handle ditl;
#ifndef SGPanelGetDitl
- PyMac_PRECHECK(SGPanelGetDitl);
+ PyMac_PRECHECK(SGPanelGetDitl);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGPanelGetDitl(s,
- &ditl);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, ditl);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGPanelGetDitl(s,
+ &ditl);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, ditl);
+ return _res;
}
static PyObject *Qt_SGPanelGetTitle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Str255 title;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Str255 title;
#ifndef SGPanelGetTitle
- PyMac_PRECHECK(SGPanelGetTitle);
+ PyMac_PRECHECK(SGPanelGetTitle);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- PyMac_GetStr255, title))
- return NULL;
- _rv = SGPanelGetTitle(s,
- title);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ PyMac_GetStr255, title))
+ return NULL;
+ _rv = SGPanelGetTitle(s,
+ title);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelCanRun(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
#ifndef SGPanelCanRun
- PyMac_PRECHECK(SGPanelCanRun);
+ PyMac_PRECHECK(SGPanelCanRun);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGPanelCanRun(s,
- c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGPanelCanRun(s,
+ c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelInstall(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- DialogPtr d;
- short itemOffset;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ DialogPtr d;
+ short itemOffset;
#ifndef SGPanelInstall
- PyMac_PRECHECK(SGPanelInstall);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&h",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- DlgObj_Convert, &d,
- &itemOffset))
- return NULL;
- _rv = SGPanelInstall(s,
- c,
- d,
- itemOffset);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGPanelInstall);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&h",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ DlgObj_Convert, &d,
+ &itemOffset))
+ return NULL;
+ _rv = SGPanelInstall(s,
+ c,
+ d,
+ itemOffset);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- DialogPtr d;
- short itemOffset;
- EventRecord theEvent;
- short itemHit;
- Boolean handled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ DialogPtr d;
+ short itemOffset;
+ EventRecord theEvent;
+ short itemHit;
+ Boolean handled;
#ifndef SGPanelEvent
- PyMac_PRECHECK(SGPanelEvent);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&hO&",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- DlgObj_Convert, &d,
- &itemOffset,
- PyMac_GetEventRecord, &theEvent))
- return NULL;
- _rv = SGPanelEvent(s,
- c,
- d,
- itemOffset,
- &theEvent,
- &itemHit,
- &handled);
- _res = Py_BuildValue("lhb",
- _rv,
- itemHit,
- handled);
- return _res;
+ PyMac_PRECHECK(SGPanelEvent);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&hO&",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ DlgObj_Convert, &d,
+ &itemOffset,
+ PyMac_GetEventRecord, &theEvent))
+ return NULL;
+ _rv = SGPanelEvent(s,
+ c,
+ d,
+ itemOffset,
+ &theEvent,
+ &itemHit,
+ &handled);
+ _res = Py_BuildValue("lhb",
+ _rv,
+ itemHit,
+ handled);
+ return _res;
}
static PyObject *Qt_SGPanelItem(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- DialogPtr d;
- short itemOffset;
- short itemNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ DialogPtr d;
+ short itemOffset;
+ short itemNum;
#ifndef SGPanelItem
- PyMac_PRECHECK(SGPanelItem);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&hh",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- DlgObj_Convert, &d,
- &itemOffset,
- &itemNum))
- return NULL;
- _rv = SGPanelItem(s,
- c,
- d,
- itemOffset,
- itemNum);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGPanelItem);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&hh",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ DlgObj_Convert, &d,
+ &itemOffset,
+ &itemNum))
+ return NULL;
+ _rv = SGPanelItem(s,
+ c,
+ d,
+ itemOffset,
+ itemNum);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelRemove(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- DialogPtr d;
- short itemOffset;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ DialogPtr d;
+ short itemOffset;
#ifndef SGPanelRemove
- PyMac_PRECHECK(SGPanelRemove);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&h",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- DlgObj_Convert, &d,
- &itemOffset))
- return NULL;
- _rv = SGPanelRemove(s,
- c,
- d,
- itemOffset);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGPanelRemove);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&h",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ DlgObj_Convert, &d,
+ &itemOffset))
+ return NULL;
+ _rv = SGPanelRemove(s,
+ c,
+ d,
+ itemOffset);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelSetGrabber(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SeqGrabComponent sg;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SeqGrabComponent sg;
#ifndef SGPanelSetGrabber
- PyMac_PRECHECK(SGPanelSetGrabber);
+ PyMac_PRECHECK(SGPanelSetGrabber);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &sg))
- return NULL;
- _rv = SGPanelSetGrabber(s,
- sg);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &sg))
+ return NULL;
+ _rv = SGPanelSetGrabber(s,
+ sg);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelSetResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- short resRef;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ short resRef;
#ifndef SGPanelSetResFile
- PyMac_PRECHECK(SGPanelSetResFile);
+ PyMac_PRECHECK(SGPanelSetResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &s,
- &resRef))
- return NULL;
- _rv = SGPanelSetResFile(s,
- resRef);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &s,
+ &resRef))
+ return NULL;
+ _rv = SGPanelSetResFile(s,
+ resRef);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelGetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- UserData ud;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ UserData ud;
+ long flags;
#ifndef SGPanelGetSettings
- PyMac_PRECHECK(SGPanelGetSettings);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- &flags))
- return NULL;
- _rv = SGPanelGetSettings(s,
- c,
- &ud,
- flags);
- _res = Py_BuildValue("lO&",
- _rv,
- UserDataObj_New, ud);
- return _res;
+ PyMac_PRECHECK(SGPanelGetSettings);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ &flags))
+ return NULL;
+ _rv = SGPanelGetSettings(s,
+ c,
+ &ud,
+ flags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ UserDataObj_New, ud);
+ return _res;
}
static PyObject *Qt_SGPanelSetSettings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- SGChannel c;
- UserData ud;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ SGChannel c;
+ UserData ud;
+ long flags;
#ifndef SGPanelSetSettings
- PyMac_PRECHECK(SGPanelSetSettings);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&l",
- CmpInstObj_Convert, &s,
- CmpInstObj_Convert, &c,
- UserDataObj_Convert, &ud,
- &flags))
- return NULL;
- _rv = SGPanelSetSettings(s,
- c,
- ud,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGPanelSetSettings);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&l",
+ CmpInstObj_Convert, &s,
+ CmpInstObj_Convert, &c,
+ UserDataObj_Convert, &ud,
+ &flags))
+ return NULL;
+ _rv = SGPanelSetSettings(s,
+ c,
+ ud,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGPanelValidateInput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Boolean ok;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Boolean ok;
#ifndef SGPanelValidateInput
- PyMac_PRECHECK(SGPanelValidateInput);
+ PyMac_PRECHECK(SGPanelValidateInput);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGPanelValidateInput(s,
- &ok);
- _res = Py_BuildValue("lb",
- _rv,
- ok);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGPanelValidateInput(s,
+ &ok);
+ _res = Py_BuildValue("lb",
+ _rv,
+ ok);
+ return _res;
}
static PyObject *Qt_SGPanelGetDITLForSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SeqGrabComponent s;
- Handle ditl;
- Point requestedSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SeqGrabComponent s;
+ Handle ditl;
+ Point requestedSize;
#ifndef SGPanelGetDITLForSize
- PyMac_PRECHECK(SGPanelGetDITLForSize);
+ PyMac_PRECHECK(SGPanelGetDITLForSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &s))
- return NULL;
- _rv = SGPanelGetDITLForSize(s,
- &ditl,
- &requestedSize);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, ditl,
- PyMac_BuildPoint, requestedSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &s))
+ return NULL;
+ _rv = SGPanelGetDITLForSize(s,
+ &ditl,
+ &requestedSize);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, ditl,
+ PyMac_BuildPoint, requestedSize);
+ return _res;
}
static PyObject *Qt_SGGetSrcVideoBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Rect r;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Rect r;
#ifndef SGGetSrcVideoBounds
- PyMac_PRECHECK(SGGetSrcVideoBounds);
+ PyMac_PRECHECK(SGGetSrcVideoBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetSrcVideoBounds(c,
- &r);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetSrcVideoBounds(c,
+ &r);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qt_SGSetVideoRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Rect r;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Rect r;
#ifndef SGSetVideoRect
- PyMac_PRECHECK(SGSetVideoRect);
+ PyMac_PRECHECK(SGSetVideoRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetRect, &r))
- return NULL;
- _rv = SGSetVideoRect(c,
- &r);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetRect, &r))
+ return NULL;
+ _rv = SGSetVideoRect(c,
+ &r);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetVideoRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Rect r;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Rect r;
#ifndef SGGetVideoRect
- PyMac_PRECHECK(SGGetVideoRect);
+ PyMac_PRECHECK(SGGetVideoRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetVideoRect(c,
- &r);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &r);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetVideoRect(c,
+ &r);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &r);
+ return _res;
}
static PyObject *Qt_SGGetVideoCompressorType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- OSType compressorType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ OSType compressorType;
#ifndef SGGetVideoCompressorType
- PyMac_PRECHECK(SGGetVideoCompressorType);
+ PyMac_PRECHECK(SGGetVideoCompressorType);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetVideoCompressorType(c,
- &compressorType);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildOSType, compressorType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetVideoCompressorType(c,
+ &compressorType);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildOSType, compressorType);
+ return _res;
}
static PyObject *Qt_SGSetVideoCompressorType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- OSType compressorType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ OSType compressorType;
#ifndef SGSetVideoCompressorType
- PyMac_PRECHECK(SGSetVideoCompressorType);
+ PyMac_PRECHECK(SGSetVideoCompressorType);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetOSType, &compressorType))
- return NULL;
- _rv = SGSetVideoCompressorType(c,
- compressorType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetOSType, &compressorType))
+ return NULL;
+ _rv = SGSetVideoCompressorType(c,
+ compressorType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetVideoCompressor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short depth;
- CompressorComponent compressor;
- CodecQ spatialQuality;
- CodecQ temporalQuality;
- long keyFrameRate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short depth;
+ CompressorComponent compressor;
+ CodecQ spatialQuality;
+ CodecQ temporalQuality;
+ long keyFrameRate;
#ifndef SGSetVideoCompressor
- PyMac_PRECHECK(SGSetVideoCompressor);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hO&lll",
- CmpInstObj_Convert, &c,
- &depth,
- CmpObj_Convert, &compressor,
- &spatialQuality,
- &temporalQuality,
- &keyFrameRate))
- return NULL;
- _rv = SGSetVideoCompressor(c,
- depth,
- compressor,
- spatialQuality,
- temporalQuality,
- keyFrameRate);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGSetVideoCompressor);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hO&lll",
+ CmpInstObj_Convert, &c,
+ &depth,
+ CmpObj_Convert, &compressor,
+ &spatialQuality,
+ &temporalQuality,
+ &keyFrameRate))
+ return NULL;
+ _rv = SGSetVideoCompressor(c,
+ depth,
+ compressor,
+ spatialQuality,
+ temporalQuality,
+ keyFrameRate);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetVideoCompressor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short depth;
- CompressorComponent compressor;
- CodecQ spatialQuality;
- CodecQ temporalQuality;
- long keyFrameRate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short depth;
+ CompressorComponent compressor;
+ CodecQ spatialQuality;
+ CodecQ temporalQuality;
+ long keyFrameRate;
#ifndef SGGetVideoCompressor
- PyMac_PRECHECK(SGGetVideoCompressor);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetVideoCompressor(c,
- &depth,
- &compressor,
- &spatialQuality,
- &temporalQuality,
- &keyFrameRate);
- _res = Py_BuildValue("lhO&lll",
- _rv,
- depth,
- CmpObj_New, compressor,
- spatialQuality,
- temporalQuality,
- keyFrameRate);
- return _res;
+ PyMac_PRECHECK(SGGetVideoCompressor);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetVideoCompressor(c,
+ &depth,
+ &compressor,
+ &spatialQuality,
+ &temporalQuality,
+ &keyFrameRate);
+ _res = Py_BuildValue("lhO&lll",
+ _rv,
+ depth,
+ CmpObj_New, compressor,
+ spatialQuality,
+ temporalQuality,
+ keyFrameRate);
+ return _res;
}
static PyObject *Qt_SGGetVideoDigitizerComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentInstance _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentInstance _rv;
+ SGChannel c;
#ifndef SGGetVideoDigitizerComponent
- PyMac_PRECHECK(SGGetVideoDigitizerComponent);
+ PyMac_PRECHECK(SGGetVideoDigitizerComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetVideoDigitizerComponent(c);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetVideoDigitizerComponent(c);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *Qt_SGSetVideoDigitizerComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- ComponentInstance vdig;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ ComponentInstance vdig;
#ifndef SGSetVideoDigitizerComponent
- PyMac_PRECHECK(SGSetVideoDigitizerComponent);
+ PyMac_PRECHECK(SGSetVideoDigitizerComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- CmpInstObj_Convert, &vdig))
- return NULL;
- _rv = SGSetVideoDigitizerComponent(c,
- vdig);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ CmpInstObj_Convert, &vdig))
+ return NULL;
+ _rv = SGSetVideoDigitizerComponent(c,
+ vdig);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGVideoDigitizerChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
#ifndef SGVideoDigitizerChanged
- PyMac_PRECHECK(SGVideoDigitizerChanged);
+ PyMac_PRECHECK(SGVideoDigitizerChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGVideoDigitizerChanged(c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGVideoDigitizerChanged(c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGrabFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short bufferNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short bufferNum;
#ifndef SGGrabFrame
- PyMac_PRECHECK(SGGrabFrame);
+ PyMac_PRECHECK(SGGrabFrame);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &bufferNum))
- return NULL;
- _rv = SGGrabFrame(c,
- bufferNum);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &bufferNum))
+ return NULL;
+ _rv = SGGrabFrame(c,
+ bufferNum);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGrabFrameComplete(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short bufferNum;
- Boolean done;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short bufferNum;
+ Boolean done;
#ifndef SGGrabFrameComplete
- PyMac_PRECHECK(SGGrabFrameComplete);
+ PyMac_PRECHECK(SGGrabFrameComplete);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &bufferNum))
- return NULL;
- _rv = SGGrabFrameComplete(c,
- bufferNum,
- &done);
- _res = Py_BuildValue("lb",
- _rv,
- done);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &bufferNum))
+ return NULL;
+ _rv = SGGrabFrameComplete(c,
+ bufferNum,
+ &done);
+ _res = Py_BuildValue("lb",
+ _rv,
+ done);
+ return _res;
}
static PyObject *Qt_SGCompressFrame(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short bufferNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short bufferNum;
#ifndef SGCompressFrame
- PyMac_PRECHECK(SGCompressFrame);
+ PyMac_PRECHECK(SGCompressFrame);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &bufferNum))
- return NULL;
- _rv = SGCompressFrame(c,
- bufferNum);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &bufferNum))
+ return NULL;
+ _rv = SGCompressFrame(c,
+ bufferNum);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetCompressBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short depth;
- Rect compressSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short depth;
+ Rect compressSize;
#ifndef SGSetCompressBuffer
- PyMac_PRECHECK(SGSetCompressBuffer);
+ PyMac_PRECHECK(SGSetCompressBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&hO&",
- CmpInstObj_Convert, &c,
- &depth,
- PyMac_GetRect, &compressSize))
- return NULL;
- _rv = SGSetCompressBuffer(c,
- depth,
- &compressSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hO&",
+ CmpInstObj_Convert, &c,
+ &depth,
+ PyMac_GetRect, &compressSize))
+ return NULL;
+ _rv = SGSetCompressBuffer(c,
+ depth,
+ &compressSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetCompressBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short depth;
- Rect compressSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short depth;
+ Rect compressSize;
#ifndef SGGetCompressBuffer
- PyMac_PRECHECK(SGGetCompressBuffer);
+ PyMac_PRECHECK(SGGetCompressBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetCompressBuffer(c,
- &depth,
- &compressSize);
- _res = Py_BuildValue("lhO&",
- _rv,
- depth,
- PyMac_BuildRect, &compressSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetCompressBuffer(c,
+ &depth,
+ &compressSize);
+ _res = Py_BuildValue("lhO&",
+ _rv,
+ depth,
+ PyMac_BuildRect, &compressSize);
+ return _res;
}
static PyObject *Qt_SGGetBufferInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short bufferNum;
- PixMapHandle bufferPM;
- Rect bufferRect;
- GWorldPtr compressBuffer;
- Rect compressBufferRect;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short bufferNum;
+ PixMapHandle bufferPM;
+ Rect bufferRect;
+ GWorldPtr compressBuffer;
+ Rect compressBufferRect;
#ifndef SGGetBufferInfo
- PyMac_PRECHECK(SGGetBufferInfo);
-#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &bufferNum))
- return NULL;
- _rv = SGGetBufferInfo(c,
- bufferNum,
- &bufferPM,
- &bufferRect,
- &compressBuffer,
- &compressBufferRect);
- _res = Py_BuildValue("lO&O&O&O&",
- _rv,
- ResObj_New, bufferPM,
- PyMac_BuildRect, &bufferRect,
- GWorldObj_New, compressBuffer,
- PyMac_BuildRect, &compressBufferRect);
- return _res;
+ PyMac_PRECHECK(SGGetBufferInfo);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &bufferNum))
+ return NULL;
+ _rv = SGGetBufferInfo(c,
+ bufferNum,
+ &bufferPM,
+ &bufferRect,
+ &compressBuffer,
+ &compressBufferRect);
+ _res = Py_BuildValue("lO&O&O&O&",
+ _rv,
+ ResObj_New, bufferPM,
+ PyMac_BuildRect, &bufferRect,
+ GWorldObj_New, compressBuffer,
+ PyMac_BuildRect, &compressBufferRect);
+ return _res;
}
static PyObject *Qt_SGSetUseScreenBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Boolean useScreenBuffer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Boolean useScreenBuffer;
#ifndef SGSetUseScreenBuffer
- PyMac_PRECHECK(SGSetUseScreenBuffer);
+ PyMac_PRECHECK(SGSetUseScreenBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &c,
- &useScreenBuffer))
- return NULL;
- _rv = SGSetUseScreenBuffer(c,
- useScreenBuffer);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &c,
+ &useScreenBuffer))
+ return NULL;
+ _rv = SGSetUseScreenBuffer(c,
+ useScreenBuffer);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetUseScreenBuffer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Boolean useScreenBuffer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Boolean useScreenBuffer;
#ifndef SGGetUseScreenBuffer
- PyMac_PRECHECK(SGGetUseScreenBuffer);
+ PyMac_PRECHECK(SGGetUseScreenBuffer);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetUseScreenBuffer(c,
- &useScreenBuffer);
- _res = Py_BuildValue("lb",
- _rv,
- useScreenBuffer);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetUseScreenBuffer(c,
+ &useScreenBuffer);
+ _res = Py_BuildValue("lb",
+ _rv,
+ useScreenBuffer);
+ return _res;
}
static PyObject *Qt_SGSetFrameRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Fixed frameRate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Fixed frameRate;
#ifndef SGSetFrameRate
- PyMac_PRECHECK(SGSetFrameRate);
+ PyMac_PRECHECK(SGSetFrameRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetFixed, &frameRate))
- return NULL;
- _rv = SGSetFrameRate(c,
- frameRate);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetFixed, &frameRate))
+ return NULL;
+ _rv = SGSetFrameRate(c,
+ frameRate);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetFrameRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Fixed frameRate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Fixed frameRate;
#ifndef SGGetFrameRate
- PyMac_PRECHECK(SGGetFrameRate);
+ PyMac_PRECHECK(SGGetFrameRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetFrameRate(c,
- &frameRate);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildFixed, frameRate);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetFrameRate(c,
+ &frameRate);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildFixed, frameRate);
+ return _res;
}
static PyObject *Qt_SGSetPreferredPacketSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long preferredPacketSizeInBytes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long preferredPacketSizeInBytes;
#ifndef SGSetPreferredPacketSize
- PyMac_PRECHECK(SGSetPreferredPacketSize);
+ PyMac_PRECHECK(SGSetPreferredPacketSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &preferredPacketSizeInBytes))
- return NULL;
- _rv = SGSetPreferredPacketSize(c,
- preferredPacketSizeInBytes);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &preferredPacketSizeInBytes))
+ return NULL;
+ _rv = SGSetPreferredPacketSize(c,
+ preferredPacketSizeInBytes);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetPreferredPacketSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long preferredPacketSizeInBytes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long preferredPacketSizeInBytes;
#ifndef SGGetPreferredPacketSize
- PyMac_PRECHECK(SGGetPreferredPacketSize);
+ PyMac_PRECHECK(SGGetPreferredPacketSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetPreferredPacketSize(c,
- &preferredPacketSizeInBytes);
- _res = Py_BuildValue("ll",
- _rv,
- preferredPacketSizeInBytes);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetPreferredPacketSize(c,
+ &preferredPacketSizeInBytes);
+ _res = Py_BuildValue("ll",
+ _rv,
+ preferredPacketSizeInBytes);
+ return _res;
}
static PyObject *Qt_SGSetUserVideoCompressorList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle compressorTypes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle compressorTypes;
#ifndef SGSetUserVideoCompressorList
- PyMac_PRECHECK(SGSetUserVideoCompressorList);
+ PyMac_PRECHECK(SGSetUserVideoCompressorList);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- ResObj_Convert, &compressorTypes))
- return NULL;
- _rv = SGSetUserVideoCompressorList(c,
- compressorTypes);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ ResObj_Convert, &compressorTypes))
+ return NULL;
+ _rv = SGSetUserVideoCompressorList(c,
+ compressorTypes);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetUserVideoCompressorList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle compressorTypes;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle compressorTypes;
#ifndef SGGetUserVideoCompressorList
- PyMac_PRECHECK(SGGetUserVideoCompressorList);
+ PyMac_PRECHECK(SGGetUserVideoCompressorList);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetUserVideoCompressorList(c,
- &compressorTypes);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, compressorTypes);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetUserVideoCompressorList(c,
+ &compressorTypes);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, compressorTypes);
+ return _res;
}
static PyObject *Qt_SGSetSoundInputDriver(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Str255 driverName;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Str255 driverName;
#ifndef SGSetSoundInputDriver
- PyMac_PRECHECK(SGSetSoundInputDriver);
+ PyMac_PRECHECK(SGSetSoundInputDriver);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetStr255, driverName))
- return NULL;
- _rv = SGSetSoundInputDriver(c,
- driverName);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetStr255, driverName))
+ return NULL;
+ _rv = SGSetSoundInputDriver(c,
+ driverName);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetSoundInputDriver(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ long _rv;
+ SGChannel c;
#ifndef SGGetSoundInputDriver
- PyMac_PRECHECK(SGGetSoundInputDriver);
+ PyMac_PRECHECK(SGGetSoundInputDriver);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetSoundInputDriver(c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetSoundInputDriver(c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSoundInputDriverChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
#ifndef SGSoundInputDriverChanged
- PyMac_PRECHECK(SGSoundInputDriverChanged);
+ PyMac_PRECHECK(SGSoundInputDriverChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGSoundInputDriverChanged(c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGSoundInputDriverChanged(c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetSoundRecordChunkSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- long seconds;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ long seconds;
#ifndef SGSetSoundRecordChunkSize
- PyMac_PRECHECK(SGSetSoundRecordChunkSize);
+ PyMac_PRECHECK(SGSetSoundRecordChunkSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &c,
- &seconds))
- return NULL;
- _rv = SGSetSoundRecordChunkSize(c,
- seconds);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &c,
+ &seconds))
+ return NULL;
+ _rv = SGSetSoundRecordChunkSize(c,
+ seconds);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetSoundRecordChunkSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ long _rv;
+ SGChannel c;
#ifndef SGGetSoundRecordChunkSize
- PyMac_PRECHECK(SGGetSoundRecordChunkSize);
+ PyMac_PRECHECK(SGGetSoundRecordChunkSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetSoundRecordChunkSize(c);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetSoundRecordChunkSize(c);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetSoundInputRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Fixed rate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Fixed rate;
#ifndef SGSetSoundInputRate
- PyMac_PRECHECK(SGSetSoundInputRate);
+ PyMac_PRECHECK(SGSetSoundInputRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- PyMac_GetFixed, &rate))
- return NULL;
- _rv = SGSetSoundInputRate(c,
- rate);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ _rv = SGSetSoundInputRate(c,
+ rate);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetSoundInputRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Fixed _rv;
- SGChannel c;
+ PyObject *_res = NULL;
+ Fixed _rv;
+ SGChannel c;
#ifndef SGGetSoundInputRate
- PyMac_PRECHECK(SGGetSoundInputRate);
+ PyMac_PRECHECK(SGGetSoundInputRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetSoundInputRate(c);
- _res = Py_BuildValue("O&",
- PyMac_BuildFixed, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetSoundInputRate(c);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFixed, _rv);
+ return _res;
}
static PyObject *Qt_SGSetSoundInputParameters(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short sampleSize;
- short numChannels;
- OSType compressionType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short sampleSize;
+ short numChannels;
+ OSType compressionType;
#ifndef SGSetSoundInputParameters
- PyMac_PRECHECK(SGSetSoundInputParameters);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhO&",
- CmpInstObj_Convert, &c,
- &sampleSize,
- &numChannels,
- PyMac_GetOSType, &compressionType))
- return NULL;
- _rv = SGSetSoundInputParameters(c,
- sampleSize,
- numChannels,
- compressionType);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(SGSetSoundInputParameters);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhO&",
+ CmpInstObj_Convert, &c,
+ &sampleSize,
+ &numChannels,
+ PyMac_GetOSType, &compressionType))
+ return NULL;
+ _rv = SGSetSoundInputParameters(c,
+ sampleSize,
+ numChannels,
+ compressionType);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetSoundInputParameters(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short sampleSize;
- short numChannels;
- OSType compressionType;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short sampleSize;
+ short numChannels;
+ OSType compressionType;
#ifndef SGGetSoundInputParameters
- PyMac_PRECHECK(SGGetSoundInputParameters);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetSoundInputParameters(c,
- &sampleSize,
- &numChannels,
- &compressionType);
- _res = Py_BuildValue("lhhO&",
- _rv,
- sampleSize,
- numChannels,
- PyMac_BuildOSType, compressionType);
- return _res;
+ PyMac_PRECHECK(SGGetSoundInputParameters);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetSoundInputParameters(c,
+ &sampleSize,
+ &numChannels,
+ &compressionType);
+ _res = Py_BuildValue("lhhO&",
+ _rv,
+ sampleSize,
+ numChannels,
+ PyMac_BuildOSType, compressionType);
+ return _res;
}
static PyObject *Qt_SGSetAdditionalSoundRates(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle rates;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle rates;
#ifndef SGSetAdditionalSoundRates
- PyMac_PRECHECK(SGSetAdditionalSoundRates);
+ PyMac_PRECHECK(SGSetAdditionalSoundRates);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &c,
- ResObj_Convert, &rates))
- return NULL;
- _rv = SGSetAdditionalSoundRates(c,
- rates);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &c,
+ ResObj_Convert, &rates))
+ return NULL;
+ _rv = SGSetAdditionalSoundRates(c,
+ rates);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetAdditionalSoundRates(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- Handle rates;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ Handle rates;
#ifndef SGGetAdditionalSoundRates
- PyMac_PRECHECK(SGGetAdditionalSoundRates);
+ PyMac_PRECHECK(SGGetAdditionalSoundRates);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetAdditionalSoundRates(c,
- &rates);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, rates);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetAdditionalSoundRates(c,
+ &rates);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, rates);
+ return _res;
}
static PyObject *Qt_SGSetFontName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- StringPtr pstr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ StringPtr pstr;
#ifndef SGSetFontName
- PyMac_PRECHECK(SGSetFontName);
+ PyMac_PRECHECK(SGSetFontName);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &c,
- &pstr))
- return NULL;
- _rv = SGSetFontName(c,
- pstr);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &c,
+ &pstr))
+ return NULL;
+ _rv = SGSetFontName(c,
+ pstr);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetFontSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short fontSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short fontSize;
#ifndef SGSetFontSize
- PyMac_PRECHECK(SGSetFontSize);
+ PyMac_PRECHECK(SGSetFontSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &fontSize))
- return NULL;
- _rv = SGSetFontSize(c,
- fontSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &fontSize))
+ return NULL;
+ _rv = SGSetFontSize(c,
+ fontSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGSetTextForeColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- RGBColor theColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ RGBColor theColor;
#ifndef SGSetTextForeColor
- PyMac_PRECHECK(SGSetTextForeColor);
+ PyMac_PRECHECK(SGSetTextForeColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGSetTextForeColor(c,
- &theColor);
- _res = Py_BuildValue("lO&",
- _rv,
- QdRGB_New, &theColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGSetTextForeColor(c,
+ &theColor);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QdRGB_New, &theColor);
+ return _res;
}
static PyObject *Qt_SGSetTextBackColor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- RGBColor theColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ RGBColor theColor;
#ifndef SGSetTextBackColor
- PyMac_PRECHECK(SGSetTextBackColor);
+ PyMac_PRECHECK(SGSetTextBackColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGSetTextBackColor(c,
- &theColor);
- _res = Py_BuildValue("lO&",
- _rv,
- QdRGB_New, &theColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGSetTextBackColor(c,
+ &theColor);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ QdRGB_New, &theColor);
+ return _res;
}
static PyObject *Qt_SGSetJustification(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short just;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short just;
#ifndef SGSetJustification
- PyMac_PRECHECK(SGSetJustification);
+ PyMac_PRECHECK(SGSetJustification);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &just))
- return NULL;
- _rv = SGSetJustification(c,
- just);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &just))
+ return NULL;
+ _rv = SGSetJustification(c,
+ just);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_SGGetTextReturnToSpaceValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short rettospace;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short rettospace;
#ifndef SGGetTextReturnToSpaceValue
- PyMac_PRECHECK(SGGetTextReturnToSpaceValue);
+ PyMac_PRECHECK(SGGetTextReturnToSpaceValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &c))
- return NULL;
- _rv = SGGetTextReturnToSpaceValue(c,
- &rettospace);
- _res = Py_BuildValue("lh",
- _rv,
- rettospace);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &c))
+ return NULL;
+ _rv = SGGetTextReturnToSpaceValue(c,
+ &rettospace);
+ _res = Py_BuildValue("lh",
+ _rv,
+ rettospace);
+ return _res;
}
static PyObject *Qt_SGSetTextReturnToSpaceValue(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- SGChannel c;
- short rettospace;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ SGChannel c;
+ short rettospace;
#ifndef SGSetTextReturnToSpaceValue
- PyMac_PRECHECK(SGSetTextReturnToSpaceValue);
+ PyMac_PRECHECK(SGSetTextReturnToSpaceValue);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &c,
- &rettospace))
- return NULL;
- _rv = SGSetTextReturnToSpaceValue(c,
- rettospace);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &c,
+ &rettospace))
+ return NULL;
+ _rv = SGSetTextReturnToSpaceValue(c,
+ rettospace);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetCurrentClientName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- Str255 str;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ Str255 str;
#ifndef QTVideoOutputGetCurrentClientName
- PyMac_PRECHECK(QTVideoOutputGetCurrentClientName);
+ PyMac_PRECHECK(QTVideoOutputGetCurrentClientName);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &vo,
- PyMac_GetStr255, str))
- return NULL;
- _rv = QTVideoOutputGetCurrentClientName(vo,
- str);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &vo,
+ PyMac_GetStr255, str))
+ return NULL;
+ _rv = QTVideoOutputGetCurrentClientName(vo,
+ str);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputSetClientName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- Str255 str;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ Str255 str;
#ifndef QTVideoOutputSetClientName
- PyMac_PRECHECK(QTVideoOutputSetClientName);
+ PyMac_PRECHECK(QTVideoOutputSetClientName);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &vo,
- PyMac_GetStr255, str))
- return NULL;
- _rv = QTVideoOutputSetClientName(vo,
- str);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &vo,
+ PyMac_GetStr255, str))
+ return NULL;
+ _rv = QTVideoOutputSetClientName(vo,
+ str);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetClientName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- Str255 str;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ Str255 str;
#ifndef QTVideoOutputGetClientName
- PyMac_PRECHECK(QTVideoOutputGetClientName);
+ PyMac_PRECHECK(QTVideoOutputGetClientName);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &vo,
- PyMac_GetStr255, str))
- return NULL;
- _rv = QTVideoOutputGetClientName(vo,
- str);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &vo,
+ PyMac_GetStr255, str))
+ return NULL;
+ _rv = QTVideoOutputGetClientName(vo,
+ str);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputBegin(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
#ifndef QTVideoOutputBegin
- PyMac_PRECHECK(QTVideoOutputBegin);
+ PyMac_PRECHECK(QTVideoOutputBegin);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &vo))
- return NULL;
- _rv = QTVideoOutputBegin(vo);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &vo))
+ return NULL;
+ _rv = QTVideoOutputBegin(vo);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputEnd(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
#ifndef QTVideoOutputEnd
- PyMac_PRECHECK(QTVideoOutputEnd);
+ PyMac_PRECHECK(QTVideoOutputEnd);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &vo))
- return NULL;
- _rv = QTVideoOutputEnd(vo);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &vo))
+ return NULL;
+ _rv = QTVideoOutputEnd(vo);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputSetDisplayMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- long displayModeID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ long displayModeID;
#ifndef QTVideoOutputSetDisplayMode
- PyMac_PRECHECK(QTVideoOutputSetDisplayMode);
+ PyMac_PRECHECK(QTVideoOutputSetDisplayMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &vo,
- &displayModeID))
- return NULL;
- _rv = QTVideoOutputSetDisplayMode(vo,
- displayModeID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &vo,
+ &displayModeID))
+ return NULL;
+ _rv = QTVideoOutputSetDisplayMode(vo,
+ displayModeID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetDisplayMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- long displayModeID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ long displayModeID;
#ifndef QTVideoOutputGetDisplayMode
- PyMac_PRECHECK(QTVideoOutputGetDisplayMode);
+ PyMac_PRECHECK(QTVideoOutputGetDisplayMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &vo))
- return NULL;
- _rv = QTVideoOutputGetDisplayMode(vo,
- &displayModeID);
- _res = Py_BuildValue("ll",
- _rv,
- displayModeID);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &vo))
+ return NULL;
+ _rv = QTVideoOutputGetDisplayMode(vo,
+ &displayModeID);
+ _res = Py_BuildValue("ll",
+ _rv,
+ displayModeID);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- GWorldPtr gw;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ GWorldPtr gw;
#ifndef QTVideoOutputGetGWorld
- PyMac_PRECHECK(QTVideoOutputGetGWorld);
+ PyMac_PRECHECK(QTVideoOutputGetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &vo))
- return NULL;
- _rv = QTVideoOutputGetGWorld(vo,
- &gw);
- _res = Py_BuildValue("lO&",
- _rv,
- GWorldObj_New, gw);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &vo))
+ return NULL;
+ _rv = QTVideoOutputGetGWorld(vo,
+ &gw);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ GWorldObj_New, gw);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetIndSoundOutput(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- long index;
- Component outputComponent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ long index;
+ Component outputComponent;
#ifndef QTVideoOutputGetIndSoundOutput
- PyMac_PRECHECK(QTVideoOutputGetIndSoundOutput);
+ PyMac_PRECHECK(QTVideoOutputGetIndSoundOutput);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &vo,
- &index))
- return NULL;
- _rv = QTVideoOutputGetIndSoundOutput(vo,
- index,
- &outputComponent);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpObj_New, outputComponent);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &vo,
+ &index))
+ return NULL;
+ _rv = QTVideoOutputGetIndSoundOutput(vo,
+ index,
+ &outputComponent);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpObj_New, outputComponent);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetClock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- ComponentInstance clock;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ ComponentInstance clock;
#ifndef QTVideoOutputGetClock
- PyMac_PRECHECK(QTVideoOutputGetClock);
+ PyMac_PRECHECK(QTVideoOutputGetClock);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &vo))
- return NULL;
- _rv = QTVideoOutputGetClock(vo,
- &clock);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpInstObj_New, clock);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &vo))
+ return NULL;
+ _rv = QTVideoOutputGetClock(vo,
+ &clock);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpInstObj_New, clock);
+ return _res;
}
static PyObject *Qt_QTVideoOutputSetEchoPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- CGrafPtr echoPort;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ CGrafPtr echoPort;
#ifndef QTVideoOutputSetEchoPort
- PyMac_PRECHECK(QTVideoOutputSetEchoPort);
+ PyMac_PRECHECK(QTVideoOutputSetEchoPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &vo,
- GrafObj_Convert, &echoPort))
- return NULL;
- _rv = QTVideoOutputSetEchoPort(vo,
- echoPort);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &vo,
+ GrafObj_Convert, &echoPort))
+ return NULL;
+ _rv = QTVideoOutputSetEchoPort(vo,
+ echoPort);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTVideoOutputGetIndImageDecompressor(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- long index;
- Component codec;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ long index;
+ Component codec;
#ifndef QTVideoOutputGetIndImageDecompressor
- PyMac_PRECHECK(QTVideoOutputGetIndImageDecompressor);
+ PyMac_PRECHECK(QTVideoOutputGetIndImageDecompressor);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &vo,
- &index))
- return NULL;
- _rv = QTVideoOutputGetIndImageDecompressor(vo,
- index,
- &codec);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpObj_New, codec);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &vo,
+ &index))
+ return NULL;
+ _rv = QTVideoOutputGetIndImageDecompressor(vo,
+ index,
+ &codec);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpObj_New, codec);
+ return _res;
}
static PyObject *Qt_QTVideoOutputBaseSetEchoPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTVideoOutputComponent vo;
- CGrafPtr echoPort;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTVideoOutputComponent vo;
+ CGrafPtr echoPort;
#ifndef QTVideoOutputBaseSetEchoPort
- PyMac_PRECHECK(QTVideoOutputBaseSetEchoPort);
+ PyMac_PRECHECK(QTVideoOutputBaseSetEchoPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &vo,
- GrafObj_Convert, &echoPort))
- return NULL;
- _rv = QTVideoOutputBaseSetEchoPort(vo,
- echoPort);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &vo,
+ GrafObj_Convert, &echoPort))
+ return NULL;
+ _rv = QTVideoOutputBaseSetEchoPort(vo,
+ echoPort);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetChunkManagementFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- UInt32 flags;
- UInt32 flagsMask;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ UInt32 flags;
+ UInt32 flagsMask;
#ifndef MediaSetChunkManagementFlags
- PyMac_PRECHECK(MediaSetChunkManagementFlags);
+ PyMac_PRECHECK(MediaSetChunkManagementFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &flags,
- &flagsMask))
- return NULL;
- _rv = MediaSetChunkManagementFlags(mh,
- flags,
- flagsMask);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ &flagsMask))
+ return NULL;
+ _rv = MediaSetChunkManagementFlags(mh,
+ flags,
+ flagsMask);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetChunkManagementFlags(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- UInt32 flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ UInt32 flags;
#ifndef MediaGetChunkManagementFlags
- PyMac_PRECHECK(MediaGetChunkManagementFlags);
+ PyMac_PRECHECK(MediaGetChunkManagementFlags);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetChunkManagementFlags(mh,
- &flags);
- _res = Py_BuildValue("ll",
- _rv,
- flags);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetChunkManagementFlags(mh,
+ &flags);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flags);
+ return _res;
}
static PyObject *Qt_MediaSetPurgeableChunkMemoryAllowance(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Size allowance;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Size allowance;
#ifndef MediaSetPurgeableChunkMemoryAllowance
- PyMac_PRECHECK(MediaSetPurgeableChunkMemoryAllowance);
+ PyMac_PRECHECK(MediaSetPurgeableChunkMemoryAllowance);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &allowance))
- return NULL;
- _rv = MediaSetPurgeableChunkMemoryAllowance(mh,
- allowance);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &allowance))
+ return NULL;
+ _rv = MediaSetPurgeableChunkMemoryAllowance(mh,
+ allowance);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetPurgeableChunkMemoryAllowance(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Size allowance;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Size allowance;
#ifndef MediaGetPurgeableChunkMemoryAllowance
- PyMac_PRECHECK(MediaGetPurgeableChunkMemoryAllowance);
+ PyMac_PRECHECK(MediaGetPurgeableChunkMemoryAllowance);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetPurgeableChunkMemoryAllowance(mh,
- &allowance);
- _res = Py_BuildValue("ll",
- _rv,
- allowance);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetPurgeableChunkMemoryAllowance(mh,
+ &allowance);
+ _res = Py_BuildValue("ll",
+ _rv,
+ allowance);
+ return _res;
}
static PyObject *Qt_MediaEmptyAllPurgeableChunks(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaEmptyAllPurgeableChunks
- PyMac_PRECHECK(MediaEmptyAllPurgeableChunks);
+ PyMac_PRECHECK(MediaEmptyAllPurgeableChunks);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaEmptyAllPurgeableChunks(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaEmptyAllPurgeableChunks(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetHandlerCapabilities(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long flags;
- long flagsMask;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long flags;
+ long flagsMask;
#ifndef MediaSetHandlerCapabilities
- PyMac_PRECHECK(MediaSetHandlerCapabilities);
+ PyMac_PRECHECK(MediaSetHandlerCapabilities);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &flags,
- &flagsMask))
- return NULL;
- _rv = MediaSetHandlerCapabilities(mh,
- flags,
- flagsMask);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ &flagsMask))
+ return NULL;
+ _rv = MediaSetHandlerCapabilities(mh,
+ flags,
+ flagsMask);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaIdle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue atMediaTime;
- long flagsIn;
- long flagsOut;
- TimeRecord movieTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue atMediaTime;
+ long flagsIn;
+ long flagsOut;
+ TimeRecord movieTime;
#ifndef MediaIdle
- PyMac_PRECHECK(MediaIdle);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llO&",
- CmpInstObj_Convert, &mh,
- &atMediaTime,
- &flagsIn,
- QtTimeRecord_Convert, &movieTime))
- return NULL;
- _rv = MediaIdle(mh,
- atMediaTime,
- flagsIn,
- &flagsOut,
- &movieTime);
- _res = Py_BuildValue("ll",
- _rv,
- flagsOut);
- return _res;
+ PyMac_PRECHECK(MediaIdle);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llO&",
+ CmpInstObj_Convert, &mh,
+ &atMediaTime,
+ &flagsIn,
+ QtTimeRecord_Convert, &movieTime))
+ return NULL;
+ _rv = MediaIdle(mh,
+ atMediaTime,
+ flagsIn,
+ &flagsOut,
+ &movieTime);
+ _res = Py_BuildValue("ll",
+ _rv,
+ flagsOut);
+ return _res;
}
static PyObject *Qt_MediaGetMediaInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Handle h;
#ifndef MediaGetMediaInfo
- PyMac_PRECHECK(MediaGetMediaInfo);
+ PyMac_PRECHECK(MediaGetMediaInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &h))
- return NULL;
- _rv = MediaGetMediaInfo(mh,
- h);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = MediaGetMediaInfo(mh,
+ h);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaPutMediaInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Handle h;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Handle h;
#ifndef MediaPutMediaInfo
- PyMac_PRECHECK(MediaPutMediaInfo);
+ PyMac_PRECHECK(MediaPutMediaInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &h))
- return NULL;
- _rv = MediaPutMediaInfo(mh,
- h);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = MediaPutMediaInfo(mh,
+ h);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetActive(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Boolean enableMedia;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Boolean enableMedia;
#ifndef MediaSetActive
- PyMac_PRECHECK(MediaSetActive);
+ PyMac_PRECHECK(MediaSetActive);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &mh,
- &enableMedia))
- return NULL;
- _rv = MediaSetActive(mh,
- enableMedia);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &mh,
+ &enableMedia))
+ return NULL;
+ _rv = MediaSetActive(mh,
+ enableMedia);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetRate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Fixed rate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Fixed rate;
#ifndef MediaSetRate
- PyMac_PRECHECK(MediaSetRate);
+ PyMac_PRECHECK(MediaSetRate);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetFixed, &rate))
- return NULL;
- _rv = MediaSetRate(mh,
- rate);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ _rv = MediaSetRate(mh,
+ rate);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGGetStatus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- ComponentResult statusErr;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ ComponentResult statusErr;
#ifndef MediaGGetStatus
- PyMac_PRECHECK(MediaGGetStatus);
+ PyMac_PRECHECK(MediaGGetStatus);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGGetStatus(mh,
- &statusErr);
- _res = Py_BuildValue("ll",
- _rv,
- statusErr);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGGetStatus(mh,
+ &statusErr);
+ _res = Py_BuildValue("ll",
+ _rv,
+ statusErr);
+ return _res;
}
static PyObject *Qt_MediaTrackEdited(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaTrackEdited
- PyMac_PRECHECK(MediaTrackEdited);
+ PyMac_PRECHECK(MediaTrackEdited);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaTrackEdited(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaTrackEdited(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetMediaTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeScale newTimeScale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeScale newTimeScale;
#ifndef MediaSetMediaTimeScale
- PyMac_PRECHECK(MediaSetMediaTimeScale);
+ PyMac_PRECHECK(MediaSetMediaTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &newTimeScale))
- return NULL;
- _rv = MediaSetMediaTimeScale(mh,
- newTimeScale);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &newTimeScale))
+ return NULL;
+ _rv = MediaSetMediaTimeScale(mh,
+ newTimeScale);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetMovieTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeScale newTimeScale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeScale newTimeScale;
#ifndef MediaSetMovieTimeScale
- PyMac_PRECHECK(MediaSetMovieTimeScale);
+ PyMac_PRECHECK(MediaSetMovieTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &newTimeScale))
- return NULL;
- _rv = MediaSetMovieTimeScale(mh,
- newTimeScale);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &newTimeScale))
+ return NULL;
+ _rv = MediaSetMovieTimeScale(mh,
+ newTimeScale);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetGWorld(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- CGrafPtr aPort;
- GDHandle aGD;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ CGrafPtr aPort;
+ GDHandle aGD;
#ifndef MediaSetGWorld
- PyMac_PRECHECK(MediaSetGWorld);
+ PyMac_PRECHECK(MediaSetGWorld);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &mh,
- GrafObj_Convert, &aPort,
- OptResObj_Convert, &aGD))
- return NULL;
- _rv = MediaSetGWorld(mh,
- aPort,
- aGD);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &mh,
+ GrafObj_Convert, &aPort,
+ OptResObj_Convert, &aGD))
+ return NULL;
+ _rv = MediaSetGWorld(mh,
+ aPort,
+ aGD);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetDimensions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Fixed width;
- Fixed height;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Fixed width;
+ Fixed height;
#ifndef MediaSetDimensions
- PyMac_PRECHECK(MediaSetDimensions);
+ PyMac_PRECHECK(MediaSetDimensions);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetFixed, &width,
- PyMac_GetFixed, &height))
- return NULL;
- _rv = MediaSetDimensions(mh,
- width,
- height);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetFixed, &width,
+ PyMac_GetFixed, &height))
+ return NULL;
+ _rv = MediaSetDimensions(mh,
+ width,
+ height);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetClip(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- RgnHandle theClip;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ RgnHandle theClip;
#ifndef MediaSetClip
- PyMac_PRECHECK(MediaSetClip);
+ PyMac_PRECHECK(MediaSetClip);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &theClip))
- return NULL;
- _rv = MediaSetClip(mh,
- theClip);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &theClip))
+ return NULL;
+ _rv = MediaSetClip(mh,
+ theClip);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetTrackOpaque(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Boolean trackIsOpaque;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Boolean trackIsOpaque;
#ifndef MediaGetTrackOpaque
- PyMac_PRECHECK(MediaGetTrackOpaque);
+ PyMac_PRECHECK(MediaGetTrackOpaque);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetTrackOpaque(mh,
- &trackIsOpaque);
- _res = Py_BuildValue("lb",
- _rv,
- trackIsOpaque);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetTrackOpaque(mh,
+ &trackIsOpaque);
+ _res = Py_BuildValue("lb",
+ _rv,
+ trackIsOpaque);
+ return _res;
}
static PyObject *Qt_MediaSetGraphicsMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long mode;
- RGBColor opColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long mode;
+ RGBColor opColor;
#ifndef MediaSetGraphicsMode
- PyMac_PRECHECK(MediaSetGraphicsMode);
+ PyMac_PRECHECK(MediaSetGraphicsMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &mode,
- QdRGB_Convert, &opColor))
- return NULL;
- _rv = MediaSetGraphicsMode(mh,
- mode,
- &opColor);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &mode,
+ QdRGB_Convert, &opColor))
+ return NULL;
+ _rv = MediaSetGraphicsMode(mh,
+ mode,
+ &opColor);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetGraphicsMode(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long mode;
- RGBColor opColor;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long mode;
+ RGBColor opColor;
#ifndef MediaGetGraphicsMode
- PyMac_PRECHECK(MediaGetGraphicsMode);
+ PyMac_PRECHECK(MediaGetGraphicsMode);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetGraphicsMode(mh,
- &mode,
- &opColor);
- _res = Py_BuildValue("llO&",
- _rv,
- mode,
- QdRGB_New, &opColor);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetGraphicsMode(mh,
+ &mode,
+ &opColor);
+ _res = Py_BuildValue("llO&",
+ _rv,
+ mode,
+ QdRGB_New, &opColor);
+ return _res;
}
static PyObject *Qt_MediaGSetVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short volume;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short volume;
#ifndef MediaGSetVolume
- PyMac_PRECHECK(MediaGSetVolume);
+ PyMac_PRECHECK(MediaGSetVolume);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mh,
- &volume))
- return NULL;
- _rv = MediaGSetVolume(mh,
- volume);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mh,
+ &volume))
+ return NULL;
+ _rv = MediaGSetVolume(mh,
+ volume);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetSoundBalance(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short balance;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short balance;
#ifndef MediaSetSoundBalance
- PyMac_PRECHECK(MediaSetSoundBalance);
+ PyMac_PRECHECK(MediaSetSoundBalance);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mh,
- &balance))
- return NULL;
- _rv = MediaSetSoundBalance(mh,
- balance);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mh,
+ &balance))
+ return NULL;
+ _rv = MediaSetSoundBalance(mh,
+ balance);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetSoundBalance(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short balance;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short balance;
#ifndef MediaGetSoundBalance
- PyMac_PRECHECK(MediaGetSoundBalance);
+ PyMac_PRECHECK(MediaGetSoundBalance);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetSoundBalance(mh,
- &balance);
- _res = Py_BuildValue("lh",
- _rv,
- balance);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetSoundBalance(mh,
+ &balance);
+ _res = Py_BuildValue("lh",
+ _rv,
+ balance);
+ return _res;
}
static PyObject *Qt_MediaGetNextBoundsChange(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue when;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue when;
#ifndef MediaGetNextBoundsChange
- PyMac_PRECHECK(MediaGetNextBoundsChange);
+ PyMac_PRECHECK(MediaGetNextBoundsChange);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetNextBoundsChange(mh,
- &when);
- _res = Py_BuildValue("ll",
- _rv,
- when);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetNextBoundsChange(mh,
+ &when);
+ _res = Py_BuildValue("ll",
+ _rv,
+ when);
+ return _res;
}
static PyObject *Qt_MediaGetSrcRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- RgnHandle rgn;
- TimeValue atMediaTime;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ RgnHandle rgn;
+ TimeValue atMediaTime;
#ifndef MediaGetSrcRgn
- PyMac_PRECHECK(MediaGetSrcRgn);
+ PyMac_PRECHECK(MediaGetSrcRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &rgn,
- &atMediaTime))
- return NULL;
- _rv = MediaGetSrcRgn(mh,
- rgn,
- atMediaTime);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &rgn,
+ &atMediaTime))
+ return NULL;
+ _rv = MediaGetSrcRgn(mh,
+ rgn,
+ atMediaTime);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaPreroll(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue time;
- Fixed rate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue time;
+ Fixed rate;
#ifndef MediaPreroll
- PyMac_PRECHECK(MediaPreroll);
+ PyMac_PRECHECK(MediaPreroll);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &time,
- PyMac_GetFixed, &rate))
- return NULL;
- _rv = MediaPreroll(mh,
- time,
- rate);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &time,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ _rv = MediaPreroll(mh,
+ time,
+ rate);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSampleDescriptionChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long index;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long index;
#ifndef MediaSampleDescriptionChanged
- PyMac_PRECHECK(MediaSampleDescriptionChanged);
+ PyMac_PRECHECK(MediaSampleDescriptionChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &index))
- return NULL;
- _rv = MediaSampleDescriptionChanged(mh,
- index);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &index))
+ return NULL;
+ _rv = MediaSampleDescriptionChanged(mh,
+ index);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaHasCharacteristic(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- OSType characteristic;
- Boolean hasIt;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ OSType characteristic;
+ Boolean hasIt;
#ifndef MediaHasCharacteristic
- PyMac_PRECHECK(MediaHasCharacteristic);
+ PyMac_PRECHECK(MediaHasCharacteristic);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetOSType, &characteristic))
- return NULL;
- _rv = MediaHasCharacteristic(mh,
- characteristic,
- &hasIt);
- _res = Py_BuildValue("lb",
- _rv,
- hasIt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetOSType, &characteristic))
+ return NULL;
+ _rv = MediaHasCharacteristic(mh,
+ characteristic,
+ &hasIt);
+ _res = Py_BuildValue("lb",
+ _rv,
+ hasIt);
+ return _res;
}
static PyObject *Qt_MediaGetOffscreenBufferSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Rect bounds;
- short depth;
- CTabHandle ctab;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Rect bounds;
+ short depth;
+ CTabHandle ctab;
#ifndef MediaGetOffscreenBufferSize
- PyMac_PRECHECK(MediaGetOffscreenBufferSize);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hO&",
- CmpInstObj_Convert, &mh,
- &depth,
- ResObj_Convert, &ctab))
- return NULL;
- _rv = MediaGetOffscreenBufferSize(mh,
- &bounds,
- depth,
- ctab);
- _res = Py_BuildValue("lO&",
- _rv,
- PyMac_BuildRect, &bounds);
- return _res;
+ PyMac_PRECHECK(MediaGetOffscreenBufferSize);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hO&",
+ CmpInstObj_Convert, &mh,
+ &depth,
+ ResObj_Convert, &ctab))
+ return NULL;
+ _rv = MediaGetOffscreenBufferSize(mh,
+ &bounds,
+ depth,
+ ctab);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *Qt_MediaSetHints(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long hints;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long hints;
#ifndef MediaSetHints
- PyMac_PRECHECK(MediaSetHints);
+ PyMac_PRECHECK(MediaSetHints);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &hints))
- return NULL;
- _rv = MediaSetHints(mh,
- hints);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &hints))
+ return NULL;
+ _rv = MediaSetHints(mh,
+ hints);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Str255 name;
- long requestedLanguage;
- long actualLanguage;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Str255 name;
+ long requestedLanguage;
+ long actualLanguage;
#ifndef MediaGetName
- PyMac_PRECHECK(MediaGetName);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&l",
- CmpInstObj_Convert, &mh,
- PyMac_GetStr255, name,
- &requestedLanguage))
- return NULL;
- _rv = MediaGetName(mh,
- name,
- requestedLanguage,
- &actualLanguage);
- _res = Py_BuildValue("ll",
- _rv,
- actualLanguage);
- return _res;
+ PyMac_PRECHECK(MediaGetName);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&l",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetStr255, name,
+ &requestedLanguage))
+ return NULL;
+ _rv = MediaGetName(mh,
+ name,
+ requestedLanguage,
+ &actualLanguage);
+ _res = Py_BuildValue("ll",
+ _rv,
+ actualLanguage);
+ return _res;
}
static PyObject *Qt_MediaForceUpdate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long forceUpdateFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long forceUpdateFlags;
#ifndef MediaForceUpdate
- PyMac_PRECHECK(MediaForceUpdate);
+ PyMac_PRECHECK(MediaForceUpdate);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &forceUpdateFlags))
- return NULL;
- _rv = MediaForceUpdate(mh,
- forceUpdateFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &forceUpdateFlags))
+ return NULL;
+ _rv = MediaForceUpdate(mh,
+ forceUpdateFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetDrawingRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- RgnHandle partialRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ RgnHandle partialRgn;
#ifndef MediaGetDrawingRgn
- PyMac_PRECHECK(MediaGetDrawingRgn);
+ PyMac_PRECHECK(MediaGetDrawingRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetDrawingRgn(mh,
- &partialRgn);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, partialRgn);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetDrawingRgn(mh,
+ &partialRgn);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, partialRgn);
+ return _res;
}
static PyObject *Qt_MediaGSetActiveSegment(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- TimeValue activeStart;
- TimeValue activeDuration;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ TimeValue activeStart;
+ TimeValue activeDuration;
#ifndef MediaGSetActiveSegment
- PyMac_PRECHECK(MediaGSetActiveSegment);
+ PyMac_PRECHECK(MediaGSetActiveSegment);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &activeStart,
- &activeDuration))
- return NULL;
- _rv = MediaGSetActiveSegment(mh,
- activeStart,
- activeDuration);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &activeStart,
+ &activeDuration))
+ return NULL;
+ _rv = MediaGSetActiveSegment(mh,
+ activeStart,
+ activeDuration);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaInvalidateRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- RgnHandle invalRgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ RgnHandle invalRgn;
#ifndef MediaInvalidateRegion
- PyMac_PRECHECK(MediaInvalidateRegion);
+ PyMac_PRECHECK(MediaInvalidateRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &invalRgn))
- return NULL;
- _rv = MediaInvalidateRegion(mh,
- invalRgn);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &invalRgn))
+ return NULL;
+ _rv = MediaInvalidateRegion(mh,
+ invalRgn);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetNextStepTime(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short flags;
- TimeValue mediaTimeIn;
- TimeValue mediaTimeOut;
- Fixed rate;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short flags;
+ TimeValue mediaTimeIn;
+ TimeValue mediaTimeOut;
+ Fixed rate;
#ifndef MediaGetNextStepTime
- PyMac_PRECHECK(MediaGetNextStepTime);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hlO&",
- CmpInstObj_Convert, &mh,
- &flags,
- &mediaTimeIn,
- PyMac_GetFixed, &rate))
- return NULL;
- _rv = MediaGetNextStepTime(mh,
- flags,
- mediaTimeIn,
- &mediaTimeOut,
- rate);
- _res = Py_BuildValue("ll",
- _rv,
- mediaTimeOut);
- return _res;
+ PyMac_PRECHECK(MediaGetNextStepTime);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hlO&",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ &mediaTimeIn,
+ PyMac_GetFixed, &rate))
+ return NULL;
+ _rv = MediaGetNextStepTime(mh,
+ flags,
+ mediaTimeIn,
+ &mediaTimeOut,
+ rate);
+ _res = Py_BuildValue("ll",
+ _rv,
+ mediaTimeOut);
+ return _res;
}
static PyObject *Qt_MediaChangedNonPrimarySource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long inputIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long inputIndex;
#ifndef MediaChangedNonPrimarySource
- PyMac_PRECHECK(MediaChangedNonPrimarySource);
+ PyMac_PRECHECK(MediaChangedNonPrimarySource);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &inputIndex))
- return NULL;
- _rv = MediaChangedNonPrimarySource(mh,
- inputIndex);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &inputIndex))
+ return NULL;
+ _rv = MediaChangedNonPrimarySource(mh,
+ inputIndex);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaTrackReferencesChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaTrackReferencesChanged
- PyMac_PRECHECK(MediaTrackReferencesChanged);
+ PyMac_PRECHECK(MediaTrackReferencesChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaTrackReferencesChanged(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaTrackReferencesChanged(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaReleaseSampleDataPointer(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long sampleNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long sampleNum;
#ifndef MediaReleaseSampleDataPointer
- PyMac_PRECHECK(MediaReleaseSampleDataPointer);
+ PyMac_PRECHECK(MediaReleaseSampleDataPointer);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &sampleNum))
- return NULL;
- _rv = MediaReleaseSampleDataPointer(mh,
- sampleNum);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &sampleNum))
+ return NULL;
+ _rv = MediaReleaseSampleDataPointer(mh,
+ sampleNum);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaTrackPropertyAtomChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaTrackPropertyAtomChanged
- PyMac_PRECHECK(MediaTrackPropertyAtomChanged);
+ PyMac_PRECHECK(MediaTrackPropertyAtomChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaTrackPropertyAtomChanged(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaTrackPropertyAtomChanged(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetVideoParam(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long whichParam;
- unsigned short value;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long whichParam;
+ unsigned short value;
#ifndef MediaSetVideoParam
- PyMac_PRECHECK(MediaSetVideoParam);
+ PyMac_PRECHECK(MediaSetVideoParam);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &whichParam))
- return NULL;
- _rv = MediaSetVideoParam(mh,
- whichParam,
- &value);
- _res = Py_BuildValue("lH",
- _rv,
- value);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &whichParam))
+ return NULL;
+ _rv = MediaSetVideoParam(mh,
+ whichParam,
+ &value);
+ _res = Py_BuildValue("lH",
+ _rv,
+ value);
+ return _res;
}
static PyObject *Qt_MediaGetVideoParam(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long whichParam;
- unsigned short value;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long whichParam;
+ unsigned short value;
#ifndef MediaGetVideoParam
- PyMac_PRECHECK(MediaGetVideoParam);
+ PyMac_PRECHECK(MediaGetVideoParam);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &whichParam))
- return NULL;
- _rv = MediaGetVideoParam(mh,
- whichParam,
- &value);
- _res = Py_BuildValue("lH",
- _rv,
- value);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &whichParam))
+ return NULL;
+ _rv = MediaGetVideoParam(mh,
+ whichParam,
+ &value);
+ _res = Py_BuildValue("lH",
+ _rv,
+ value);
+ return _res;
}
static PyObject *Qt_MediaCompare(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Boolean isOK;
- Media srcMedia;
- ComponentInstance srcMediaComponent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Boolean isOK;
+ Media srcMedia;
+ ComponentInstance srcMediaComponent;
#ifndef MediaCompare
- PyMac_PRECHECK(MediaCompare);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- CmpInstObj_Convert, &mh,
- MediaObj_Convert, &srcMedia,
- CmpInstObj_Convert, &srcMediaComponent))
- return NULL;
- _rv = MediaCompare(mh,
- &isOK,
- srcMedia,
- srcMediaComponent);
- _res = Py_BuildValue("lb",
- _rv,
- isOK);
- return _res;
+ PyMac_PRECHECK(MediaCompare);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ CmpInstObj_Convert, &mh,
+ MediaObj_Convert, &srcMedia,
+ CmpInstObj_Convert, &srcMediaComponent))
+ return NULL;
+ _rv = MediaCompare(mh,
+ &isOK,
+ srcMedia,
+ srcMediaComponent);
+ _res = Py_BuildValue("lb",
+ _rv,
+ isOK);
+ return _res;
}
static PyObject *Qt_MediaGetClock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- ComponentInstance clock;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ ComponentInstance clock;
#ifndef MediaGetClock
- PyMac_PRECHECK(MediaGetClock);
+ PyMac_PRECHECK(MediaGetClock);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetClock(mh,
- &clock);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpInstObj_New, clock);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetClock(mh,
+ &clock);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpInstObj_New, clock);
+ return _res;
}
static PyObject *Qt_MediaSetSoundOutputComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Component outputComponent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Component outputComponent;
#ifndef MediaSetSoundOutputComponent
- PyMac_PRECHECK(MediaSetSoundOutputComponent);
+ PyMac_PRECHECK(MediaSetSoundOutputComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- CmpObj_Convert, &outputComponent))
- return NULL;
- _rv = MediaSetSoundOutputComponent(mh,
- outputComponent);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ CmpObj_Convert, &outputComponent))
+ return NULL;
+ _rv = MediaSetSoundOutputComponent(mh,
+ outputComponent);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetSoundOutputComponent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Component outputComponent;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Component outputComponent;
#ifndef MediaGetSoundOutputComponent
- PyMac_PRECHECK(MediaGetSoundOutputComponent);
+ PyMac_PRECHECK(MediaGetSoundOutputComponent);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetSoundOutputComponent(mh,
- &outputComponent);
- _res = Py_BuildValue("lO&",
- _rv,
- CmpObj_New, outputComponent);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetSoundOutputComponent(mh,
+ &outputComponent);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ CmpObj_New, outputComponent);
+ return _res;
}
static PyObject *Qt_MediaSetSoundLocalizationData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Handle data;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Handle data;
#ifndef MediaSetSoundLocalizationData
- PyMac_PRECHECK(MediaSetSoundLocalizationData);
+ PyMac_PRECHECK(MediaSetSoundLocalizationData);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &data))
- return NULL;
- _rv = MediaSetSoundLocalizationData(mh,
- data);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &data))
+ return NULL;
+ _rv = MediaSetSoundLocalizationData(mh,
+ data);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetInvalidRegion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- RgnHandle rgn;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ RgnHandle rgn;
#ifndef MediaGetInvalidRegion
- PyMac_PRECHECK(MediaGetInvalidRegion);
+ PyMac_PRECHECK(MediaGetInvalidRegion);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &rgn))
- return NULL;
- _rv = MediaGetInvalidRegion(mh,
- rgn);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &rgn))
+ return NULL;
+ _rv = MediaGetInvalidRegion(mh,
+ rgn);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSampleDescriptionB2N(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- SampleDescriptionHandle sampleDescriptionH;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ SampleDescriptionHandle sampleDescriptionH;
#ifndef MediaSampleDescriptionB2N
- PyMac_PRECHECK(MediaSampleDescriptionB2N);
+ PyMac_PRECHECK(MediaSampleDescriptionB2N);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &sampleDescriptionH))
- return NULL;
- _rv = MediaSampleDescriptionB2N(mh,
- sampleDescriptionH);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &sampleDescriptionH))
+ return NULL;
+ _rv = MediaSampleDescriptionB2N(mh,
+ sampleDescriptionH);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSampleDescriptionN2B(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- SampleDescriptionHandle sampleDescriptionH;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ SampleDescriptionHandle sampleDescriptionH;
#ifndef MediaSampleDescriptionN2B
- PyMac_PRECHECK(MediaSampleDescriptionN2B);
+ PyMac_PRECHECK(MediaSampleDescriptionN2B);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- ResObj_Convert, &sampleDescriptionH))
- return NULL;
- _rv = MediaSampleDescriptionN2B(mh,
- sampleDescriptionH);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ ResObj_Convert, &sampleDescriptionH))
+ return NULL;
+ _rv = MediaSampleDescriptionN2B(mh,
+ sampleDescriptionH);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaFlushNonPrimarySourceData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long inputIndex;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long inputIndex;
#ifndef MediaFlushNonPrimarySourceData
- PyMac_PRECHECK(MediaFlushNonPrimarySourceData);
+ PyMac_PRECHECK(MediaFlushNonPrimarySourceData);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &inputIndex))
- return NULL;
- _rv = MediaFlushNonPrimarySourceData(mh,
- inputIndex);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &inputIndex))
+ return NULL;
+ _rv = MediaFlushNonPrimarySourceData(mh,
+ inputIndex);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetURLLink(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Point displayWhere;
- Handle urlLink;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Point displayWhere;
+ Handle urlLink;
#ifndef MediaGetURLLink
- PyMac_PRECHECK(MediaGetURLLink);
+ PyMac_PRECHECK(MediaGetURLLink);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetPoint, &displayWhere))
- return NULL;
- _rv = MediaGetURLLink(mh,
- displayWhere,
- &urlLink);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, urlLink);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetPoint, &displayWhere))
+ return NULL;
+ _rv = MediaGetURLLink(mh,
+ displayWhere,
+ &urlLink);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, urlLink);
+ return _res;
}
static PyObject *Qt_MediaHitTestForTargetRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long flags;
- Point loc;
- long targetRefCon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long flags;
+ Point loc;
+ long targetRefCon;
#ifndef MediaHitTestForTargetRefCon
- PyMac_PRECHECK(MediaHitTestForTargetRefCon);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &flags,
- PyMac_GetPoint, &loc))
- return NULL;
- _rv = MediaHitTestForTargetRefCon(mh,
- flags,
- loc,
- &targetRefCon);
- _res = Py_BuildValue("ll",
- _rv,
- targetRefCon);
- return _res;
+ PyMac_PRECHECK(MediaHitTestForTargetRefCon);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &flags,
+ PyMac_GetPoint, &loc))
+ return NULL;
+ _rv = MediaHitTestForTargetRefCon(mh,
+ flags,
+ loc,
+ &targetRefCon);
+ _res = Py_BuildValue("ll",
+ _rv,
+ targetRefCon);
+ return _res;
}
static PyObject *Qt_MediaHitTestTargetRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long targetRefCon;
- long flags;
- Point loc;
- Boolean wasHit;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long targetRefCon;
+ long flags;
+ Point loc;
+ Boolean wasHit;
#ifndef MediaHitTestTargetRefCon
- PyMac_PRECHECK(MediaHitTestTargetRefCon);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llO&",
- CmpInstObj_Convert, &mh,
- &targetRefCon,
- &flags,
- PyMac_GetPoint, &loc))
- return NULL;
- _rv = MediaHitTestTargetRefCon(mh,
- targetRefCon,
- flags,
- loc,
- &wasHit);
- _res = Py_BuildValue("lb",
- _rv,
- wasHit);
- return _res;
+ PyMac_PRECHECK(MediaHitTestTargetRefCon);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llO&",
+ CmpInstObj_Convert, &mh,
+ &targetRefCon,
+ &flags,
+ PyMac_GetPoint, &loc))
+ return NULL;
+ _rv = MediaHitTestTargetRefCon(mh,
+ targetRefCon,
+ flags,
+ loc,
+ &wasHit);
+ _res = Py_BuildValue("lb",
+ _rv,
+ wasHit);
+ return _res;
}
static PyObject *Qt_MediaDisposeTargetRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long targetRefCon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long targetRefCon;
#ifndef MediaDisposeTargetRefCon
- PyMac_PRECHECK(MediaDisposeTargetRefCon);
+ PyMac_PRECHECK(MediaDisposeTargetRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &targetRefCon))
- return NULL;
- _rv = MediaDisposeTargetRefCon(mh,
- targetRefCon);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &targetRefCon))
+ return NULL;
+ _rv = MediaDisposeTargetRefCon(mh,
+ targetRefCon);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaTargetRefConsEqual(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long firstRefCon;
- long secondRefCon;
- Boolean equal;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long firstRefCon;
+ long secondRefCon;
+ Boolean equal;
#ifndef MediaTargetRefConsEqual
- PyMac_PRECHECK(MediaTargetRefConsEqual);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &firstRefCon,
- &secondRefCon))
- return NULL;
- _rv = MediaTargetRefConsEqual(mh,
- firstRefCon,
- secondRefCon,
- &equal);
- _res = Py_BuildValue("lb",
- _rv,
- equal);
- return _res;
+ PyMac_PRECHECK(MediaTargetRefConsEqual);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &firstRefCon,
+ &secondRefCon))
+ return NULL;
+ _rv = MediaTargetRefConsEqual(mh,
+ firstRefCon,
+ secondRefCon,
+ &equal);
+ _res = Py_BuildValue("lb",
+ _rv,
+ equal);
+ return _res;
}
static PyObject *Qt_MediaPrePrerollCancel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- void * refcon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ void * refcon;
#ifndef MediaPrePrerollCancel
- PyMac_PRECHECK(MediaPrePrerollCancel);
+ PyMac_PRECHECK(MediaPrePrerollCancel);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &mh,
- &refcon))
- return NULL;
- _rv = MediaPrePrerollCancel(mh,
- refcon);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &mh,
+ &refcon))
+ return NULL;
+ _rv = MediaPrePrerollCancel(mh,
+ refcon);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaEnterEmptyEdit(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaEnterEmptyEdit
- PyMac_PRECHECK(MediaEnterEmptyEdit);
+ PyMac_PRECHECK(MediaEnterEmptyEdit);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaEnterEmptyEdit(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaEnterEmptyEdit(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaCurrentMediaQueuedData(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long milliSecs;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long milliSecs;
#ifndef MediaCurrentMediaQueuedData
- PyMac_PRECHECK(MediaCurrentMediaQueuedData);
+ PyMac_PRECHECK(MediaCurrentMediaQueuedData);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaCurrentMediaQueuedData(mh,
- &milliSecs);
- _res = Py_BuildValue("ll",
- _rv,
- milliSecs);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaCurrentMediaQueuedData(mh,
+ &milliSecs);
+ _res = Py_BuildValue("ll",
+ _rv,
+ milliSecs);
+ return _res;
}
static PyObject *Qt_MediaGetEffectiveVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short volume;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short volume;
#ifndef MediaGetEffectiveVolume
- PyMac_PRECHECK(MediaGetEffectiveVolume);
+ PyMac_PRECHECK(MediaGetEffectiveVolume);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetEffectiveVolume(mh,
- &volume);
- _res = Py_BuildValue("lh",
- _rv,
- volume);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetEffectiveVolume(mh,
+ &volume);
+ _res = Py_BuildValue("lh",
+ _rv,
+ volume);
+ return _res;
}
static PyObject *Qt_MediaGetSoundLevelMeteringEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Boolean enabled;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Boolean enabled;
#ifndef MediaGetSoundLevelMeteringEnabled
- PyMac_PRECHECK(MediaGetSoundLevelMeteringEnabled);
+ PyMac_PRECHECK(MediaGetSoundLevelMeteringEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetSoundLevelMeteringEnabled(mh,
- &enabled);
- _res = Py_BuildValue("lb",
- _rv,
- enabled);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetSoundLevelMeteringEnabled(mh,
+ &enabled);
+ _res = Py_BuildValue("lb",
+ _rv,
+ enabled);
+ return _res;
}
static PyObject *Qt_MediaSetSoundLevelMeteringEnabled(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Boolean enable;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Boolean enable;
#ifndef MediaSetSoundLevelMeteringEnabled
- PyMac_PRECHECK(MediaSetSoundLevelMeteringEnabled);
+ PyMac_PRECHECK(MediaSetSoundLevelMeteringEnabled);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &mh,
- &enable))
- return NULL;
- _rv = MediaSetSoundLevelMeteringEnabled(mh,
- enable);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &mh,
+ &enable))
+ return NULL;
+ _rv = MediaSetSoundLevelMeteringEnabled(mh,
+ enable);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetEffectiveSoundBalance(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short balance;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short balance;
#ifndef MediaGetEffectiveSoundBalance
- PyMac_PRECHECK(MediaGetEffectiveSoundBalance);
+ PyMac_PRECHECK(MediaGetEffectiveSoundBalance);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetEffectiveSoundBalance(mh,
- &balance);
- _res = Py_BuildValue("lh",
- _rv,
- balance);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetEffectiveSoundBalance(mh,
+ &balance);
+ _res = Py_BuildValue("lh",
+ _rv,
+ balance);
+ return _res;
}
static PyObject *Qt_MediaSetScreenLock(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- Boolean lockIt;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ Boolean lockIt;
#ifndef MediaSetScreenLock
- PyMac_PRECHECK(MediaSetScreenLock);
+ PyMac_PRECHECK(MediaSetScreenLock);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- CmpInstObj_Convert, &mh,
- &lockIt))
- return NULL;
- _rv = MediaSetScreenLock(mh,
- lockIt);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ CmpInstObj_Convert, &mh,
+ &lockIt))
+ return NULL;
+ _rv = MediaSetScreenLock(mh,
+ lockIt);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetErrorString(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- ComponentResult theError;
- Str255 errorString;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ ComponentResult theError;
+ Str255 errorString;
#ifndef MediaGetErrorString
- PyMac_PRECHECK(MediaGetErrorString);
+ PyMac_PRECHECK(MediaGetErrorString);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mh,
- &theError,
- PyMac_GetStr255, errorString))
- return NULL;
- _rv = MediaGetErrorString(mh,
- theError,
- errorString);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mh,
+ &theError,
+ PyMac_GetStr255, errorString))
+ return NULL;
+ _rv = MediaGetErrorString(mh,
+ theError,
+ errorString);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetSoundEqualizerBandLevels(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- UInt8 bandLevels;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ UInt8 bandLevels;
#ifndef MediaGetSoundEqualizerBandLevels
- PyMac_PRECHECK(MediaGetSoundEqualizerBandLevels);
+ PyMac_PRECHECK(MediaGetSoundEqualizerBandLevels);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetSoundEqualizerBandLevels(mh,
- &bandLevels);
- _res = Py_BuildValue("lb",
- _rv,
- bandLevels);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetSoundEqualizerBandLevels(mh,
+ &bandLevels);
+ _res = Py_BuildValue("lb",
+ _rv,
+ bandLevels);
+ return _res;
}
static PyObject *Qt_MediaDoIdleActions(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaDoIdleActions
- PyMac_PRECHECK(MediaDoIdleActions);
+ PyMac_PRECHECK(MediaDoIdleActions);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaDoIdleActions(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaDoIdleActions(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaSetSoundBassAndTreble(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short bass;
- short treble;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short bass;
+ short treble;
#ifndef MediaSetSoundBassAndTreble
- PyMac_PRECHECK(MediaSetSoundBassAndTreble);
+ PyMac_PRECHECK(MediaSetSoundBassAndTreble);
#endif
- if (!PyArg_ParseTuple(_args, "O&hh",
- CmpInstObj_Convert, &mh,
- &bass,
- &treble))
- return NULL;
- _rv = MediaSetSoundBassAndTreble(mh,
- bass,
- treble);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hh",
+ CmpInstObj_Convert, &mh,
+ &bass,
+ &treble))
+ return NULL;
+ _rv = MediaSetSoundBassAndTreble(mh,
+ bass,
+ treble);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetSoundBassAndTreble(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- short bass;
- short treble;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ short bass;
+ short treble;
#ifndef MediaGetSoundBassAndTreble
- PyMac_PRECHECK(MediaGetSoundBassAndTreble);
+ PyMac_PRECHECK(MediaGetSoundBassAndTreble);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetSoundBassAndTreble(mh,
- &bass,
- &treble);
- _res = Py_BuildValue("lhh",
- _rv,
- bass,
- treble);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetSoundBassAndTreble(mh,
+ &bass,
+ &treble);
+ _res = Py_BuildValue("lhh",
+ _rv,
+ bass,
+ treble);
+ return _res;
}
static PyObject *Qt_MediaTimeBaseChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
#ifndef MediaTimeBaseChanged
- PyMac_PRECHECK(MediaTimeBaseChanged);
+ PyMac_PRECHECK(MediaTimeBaseChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaTimeBaseChanged(mh);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaTimeBaseChanged(mh);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaMCIsPlayerEvent(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- EventRecord e;
- Boolean handledIt;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ EventRecord e;
+ Boolean handledIt;
#ifndef MediaMCIsPlayerEvent
- PyMac_PRECHECK(MediaMCIsPlayerEvent);
+ PyMac_PRECHECK(MediaMCIsPlayerEvent);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- PyMac_GetEventRecord, &e))
- return NULL;
- _rv = MediaMCIsPlayerEvent(mh,
- &e,
- &handledIt);
- _res = Py_BuildValue("lb",
- _rv,
- handledIt);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetEventRecord, &e))
+ return NULL;
+ _rv = MediaMCIsPlayerEvent(mh,
+ &e,
+ &handledIt);
+ _res = Py_BuildValue("lb",
+ _rv,
+ handledIt);
+ return _res;
}
static PyObject *Qt_MediaGetMediaLoadState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long mediaLoadState;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long mediaLoadState;
#ifndef MediaGetMediaLoadState
- PyMac_PRECHECK(MediaGetMediaLoadState);
+ PyMac_PRECHECK(MediaGetMediaLoadState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGetMediaLoadState(mh,
- &mediaLoadState);
- _res = Py_BuildValue("ll",
- _rv,
- mediaLoadState);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGetMediaLoadState(mh,
+ &mediaLoadState);
+ _res = Py_BuildValue("ll",
+ _rv,
+ mediaLoadState);
+ return _res;
}
static PyObject *Qt_MediaVideoOutputChanged(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- ComponentInstance vout;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ ComponentInstance vout;
#ifndef MediaVideoOutputChanged
- PyMac_PRECHECK(MediaVideoOutputChanged);
+ PyMac_PRECHECK(MediaVideoOutputChanged);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- CmpInstObj_Convert, &vout))
- return NULL;
- _rv = MediaVideoOutputChanged(mh,
- vout);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ CmpInstObj_Convert, &vout))
+ return NULL;
+ _rv = MediaVideoOutputChanged(mh,
+ vout);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaEmptySampleCache(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long sampleNum;
- long sampleCount;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long sampleNum;
+ long sampleCount;
#ifndef MediaEmptySampleCache
- PyMac_PRECHECK(MediaEmptySampleCache);
+ PyMac_PRECHECK(MediaEmptySampleCache);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mh,
- &sampleNum,
- &sampleCount))
- return NULL;
- _rv = MediaEmptySampleCache(mh,
- sampleNum,
- sampleCount);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mh,
+ &sampleNum,
+ &sampleCount))
+ return NULL;
+ _rv = MediaEmptySampleCache(mh,
+ sampleNum,
+ sampleCount);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaGetPublicInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- OSType infoSelector;
- void * infoDataPtr;
- Size ioDataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ OSType infoSelector;
+ void * infoDataPtr;
+ Size ioDataSize;
#ifndef MediaGetPublicInfo
- PyMac_PRECHECK(MediaGetPublicInfo);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&s",
- CmpInstObj_Convert, &mh,
- PyMac_GetOSType, &infoSelector,
- &infoDataPtr))
- return NULL;
- _rv = MediaGetPublicInfo(mh,
- infoSelector,
- infoDataPtr,
- &ioDataSize);
- _res = Py_BuildValue("ll",
- _rv,
- ioDataSize);
- return _res;
+ PyMac_PRECHECK(MediaGetPublicInfo);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&s",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetOSType, &infoSelector,
+ &infoDataPtr))
+ return NULL;
+ _rv = MediaGetPublicInfo(mh,
+ infoSelector,
+ infoDataPtr,
+ &ioDataSize);
+ _res = Py_BuildValue("ll",
+ _rv,
+ ioDataSize);
+ return _res;
}
static PyObject *Qt_MediaSetPublicInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- OSType infoSelector;
- void * infoDataPtr;
- Size dataSize;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ OSType infoSelector;
+ void * infoDataPtr;
+ Size dataSize;
#ifndef MediaSetPublicInfo
- PyMac_PRECHECK(MediaSetPublicInfo);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&sl",
- CmpInstObj_Convert, &mh,
- PyMac_GetOSType, &infoSelector,
- &infoDataPtr,
- &dataSize))
- return NULL;
- _rv = MediaSetPublicInfo(mh,
- infoSelector,
- infoDataPtr,
- dataSize);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MediaSetPublicInfo);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&sl",
+ CmpInstObj_Convert, &mh,
+ PyMac_GetOSType, &infoSelector,
+ &infoDataPtr,
+ &dataSize))
+ return NULL;
+ _rv = MediaSetPublicInfo(mh,
+ infoSelector,
+ infoDataPtr,
+ dataSize);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaRefConSetProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long refCon;
- long propertyType;
- void * propertyValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long refCon;
+ long propertyType;
+ void * propertyValue;
#ifndef MediaRefConSetProperty
- PyMac_PRECHECK(MediaRefConSetProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lls",
- CmpInstObj_Convert, &mh,
- &refCon,
- &propertyType,
- &propertyValue))
- return NULL;
- _rv = MediaRefConSetProperty(mh,
- refCon,
- propertyType,
- propertyValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MediaRefConSetProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lls",
+ CmpInstObj_Convert, &mh,
+ &refCon,
+ &propertyType,
+ &propertyValue))
+ return NULL;
+ _rv = MediaRefConSetProperty(mh,
+ refCon,
+ propertyType,
+ propertyValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaRefConGetProperty(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long refCon;
- long propertyType;
- void * propertyValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long refCon;
+ long propertyType;
+ void * propertyValue;
#ifndef MediaRefConGetProperty
- PyMac_PRECHECK(MediaRefConGetProperty);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lls",
- CmpInstObj_Convert, &mh,
- &refCon,
- &propertyType,
- &propertyValue))
- return NULL;
- _rv = MediaRefConGetProperty(mh,
- refCon,
- propertyType,
- propertyValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MediaRefConGetProperty);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lls",
+ CmpInstObj_Convert, &mh,
+ &refCon,
+ &propertyType,
+ &propertyValue))
+ return NULL;
+ _rv = MediaRefConGetProperty(mh,
+ refCon,
+ propertyType,
+ propertyValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MediaNavigateTargetRefCon(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- long navigation;
- long refCon;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ long navigation;
+ long refCon;
#ifndef MediaNavigateTargetRefCon
- PyMac_PRECHECK(MediaNavigateTargetRefCon);
+ PyMac_PRECHECK(MediaNavigateTargetRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mh,
- &navigation))
- return NULL;
- _rv = MediaNavigateTargetRefCon(mh,
- navigation,
- &refCon);
- _res = Py_BuildValue("ll",
- _rv,
- refCon);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mh,
+ &navigation))
+ return NULL;
+ _rv = MediaNavigateTargetRefCon(mh,
+ navigation,
+ &refCon);
+ _res = Py_BuildValue("ll",
+ _rv,
+ refCon);
+ return _res;
}
static PyObject *Qt_MediaGGetIdleManager(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- IdleManager pim;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ IdleManager pim;
#ifndef MediaGGetIdleManager
- PyMac_PRECHECK(MediaGGetIdleManager);
+ PyMac_PRECHECK(MediaGGetIdleManager);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mh))
- return NULL;
- _rv = MediaGGetIdleManager(mh,
- &pim);
- _res = Py_BuildValue("lO&",
- _rv,
- IdleManagerObj_New, pim);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mh))
+ return NULL;
+ _rv = MediaGGetIdleManager(mh,
+ &pim);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ IdleManagerObj_New, pim);
+ return _res;
}
static PyObject *Qt_MediaGSetIdleManager(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MediaHandler mh;
- IdleManager im;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MediaHandler mh;
+ IdleManager im;
#ifndef MediaGSetIdleManager
- PyMac_PRECHECK(MediaGSetIdleManager);
+ PyMac_PRECHECK(MediaGSetIdleManager);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mh,
- IdleManagerObj_Convert, &im))
- return NULL;
- _rv = MediaGSetIdleManager(mh,
- im);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mh,
+ IdleManagerObj_Convert, &im))
+ return NULL;
+ _rv = MediaGSetIdleManager(mh,
+ im);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTMIDIGetMIDIPorts(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTMIDIComponent ci;
- QTMIDIPortListHandle inputPorts;
- QTMIDIPortListHandle outputPorts;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTMIDIComponent ci;
+ QTMIDIPortListHandle inputPorts;
+ QTMIDIPortListHandle outputPorts;
#ifndef QTMIDIGetMIDIPorts
- PyMac_PRECHECK(QTMIDIGetMIDIPorts);
+ PyMac_PRECHECK(QTMIDIGetMIDIPorts);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &ci))
- return NULL;
- _rv = QTMIDIGetMIDIPorts(ci,
- &inputPorts,
- &outputPorts);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, inputPorts,
- ResObj_New, outputPorts);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &ci))
+ return NULL;
+ _rv = QTMIDIGetMIDIPorts(ci,
+ &inputPorts,
+ &outputPorts);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, inputPorts,
+ ResObj_New, outputPorts);
+ return _res;
}
static PyObject *Qt_QTMIDIUseSendPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTMIDIComponent ci;
- long portIndex;
- long inUse;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTMIDIComponent ci;
+ long portIndex;
+ long inUse;
#ifndef QTMIDIUseSendPort
- PyMac_PRECHECK(QTMIDIUseSendPort);
+ PyMac_PRECHECK(QTMIDIUseSendPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &ci,
- &portIndex,
- &inUse))
- return NULL;
- _rv = QTMIDIUseSendPort(ci,
- portIndex,
- inUse);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &ci,
+ &portIndex,
+ &inUse))
+ return NULL;
+ _rv = QTMIDIUseSendPort(ci,
+ portIndex,
+ inUse);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_QTMIDISendMIDI(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- QTMIDIComponent ci;
- long portIndex;
- MusicMIDIPacket mp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ QTMIDIComponent ci;
+ long portIndex;
+ MusicMIDIPacket mp;
#ifndef QTMIDISendMIDI
- PyMac_PRECHECK(QTMIDISendMIDI);
+ PyMac_PRECHECK(QTMIDISendMIDI);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &ci,
- &portIndex,
- QtMusicMIDIPacket_Convert, &mp))
- return NULL;
- _rv = QTMIDISendMIDI(ci,
- portIndex,
- &mp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &ci,
+ &portIndex,
+ QtMusicMIDIPacket_Convert, &mp))
+ return NULL;
+ _rv = QTMIDISendMIDI(ci,
+ portIndex,
+ &mp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetPart(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long midiChannel;
- long polyphony;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long midiChannel;
+ long polyphony;
#ifndef MusicGetPart
- PyMac_PRECHECK(MusicGetPart);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &part))
- return NULL;
- _rv = MusicGetPart(mc,
- part,
- &midiChannel,
- &polyphony);
- _res = Py_BuildValue("lll",
- _rv,
- midiChannel,
- polyphony);
- return _res;
+ PyMac_PRECHECK(MusicGetPart);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &part))
+ return NULL;
+ _rv = MusicGetPart(mc,
+ part,
+ &midiChannel,
+ &polyphony);
+ _res = Py_BuildValue("lll",
+ _rv,
+ midiChannel,
+ polyphony);
+ return _res;
}
static PyObject *Qt_MusicSetPart(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long midiChannel;
- long polyphony;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long midiChannel;
+ long polyphony;
#ifndef MusicSetPart
- PyMac_PRECHECK(MusicSetPart);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- CmpInstObj_Convert, &mc,
- &part,
- &midiChannel,
- &polyphony))
- return NULL;
- _rv = MusicSetPart(mc,
- part,
- midiChannel,
- polyphony);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MusicSetPart);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &midiChannel,
+ &polyphony))
+ return NULL;
+ _rv = MusicSetPart(mc,
+ part,
+ midiChannel,
+ polyphony);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetPartInstrumentNumber(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long instrumentNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long instrumentNumber;
#ifndef MusicSetPartInstrumentNumber
- PyMac_PRECHECK(MusicSetPartInstrumentNumber);
+ PyMac_PRECHECK(MusicSetPartInstrumentNumber);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &part,
- &instrumentNumber))
- return NULL;
- _rv = MusicSetPartInstrumentNumber(mc,
- part,
- instrumentNumber);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &instrumentNumber))
+ return NULL;
+ _rv = MusicSetPartInstrumentNumber(mc,
+ part,
+ instrumentNumber);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetPartInstrumentNumber(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
#ifndef MusicGetPartInstrumentNumber
- PyMac_PRECHECK(MusicGetPartInstrumentNumber);
+ PyMac_PRECHECK(MusicGetPartInstrumentNumber);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &part))
- return NULL;
- _rv = MusicGetPartInstrumentNumber(mc,
- part);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &part))
+ return NULL;
+ _rv = MusicGetPartInstrumentNumber(mc,
+ part);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicStorePartInstrument(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long instrumentNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long instrumentNumber;
#ifndef MusicStorePartInstrument
- PyMac_PRECHECK(MusicStorePartInstrument);
+ PyMac_PRECHECK(MusicStorePartInstrument);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &part,
- &instrumentNumber))
- return NULL;
- _rv = MusicStorePartInstrument(mc,
- part,
- instrumentNumber);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &instrumentNumber))
+ return NULL;
+ _rv = MusicStorePartInstrument(mc,
+ part,
+ instrumentNumber);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetPartAtomicInstrument(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- AtomicInstrument ai;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ AtomicInstrument ai;
+ long flags;
#ifndef MusicGetPartAtomicInstrument
- PyMac_PRECHECK(MusicGetPartAtomicInstrument);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &part,
- &flags))
- return NULL;
- _rv = MusicGetPartAtomicInstrument(mc,
- part,
- &ai,
- flags);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, ai);
- return _res;
+ PyMac_PRECHECK(MusicGetPartAtomicInstrument);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &flags))
+ return NULL;
+ _rv = MusicGetPartAtomicInstrument(mc,
+ part,
+ &ai,
+ flags);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, ai);
+ return _res;
}
static PyObject *Qt_MusicSetPartAtomicInstrument(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- AtomicInstrumentPtr aiP;
- long flags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ AtomicInstrumentPtr aiP;
+ long flags;
#ifndef MusicSetPartAtomicInstrument
- PyMac_PRECHECK(MusicSetPartAtomicInstrument);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lsl",
- CmpInstObj_Convert, &mc,
- &part,
- &aiP,
- &flags))
- return NULL;
- _rv = MusicSetPartAtomicInstrument(mc,
- part,
- aiP,
- flags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MusicSetPartAtomicInstrument);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lsl",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &aiP,
+ &flags))
+ return NULL;
+ _rv = MusicSetPartAtomicInstrument(mc,
+ part,
+ aiP,
+ flags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetPartKnob(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long knobID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long knobID;
#ifndef MusicGetPartKnob
- PyMac_PRECHECK(MusicGetPartKnob);
+ PyMac_PRECHECK(MusicGetPartKnob);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &part,
- &knobID))
- return NULL;
- _rv = MusicGetPartKnob(mc,
- part,
- knobID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &knobID))
+ return NULL;
+ _rv = MusicGetPartKnob(mc,
+ part,
+ knobID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetPartKnob(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long knobID;
- long knobValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long knobID;
+ long knobValue;
#ifndef MusicSetPartKnob
- PyMac_PRECHECK(MusicSetPartKnob);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- CmpInstObj_Convert, &mc,
- &part,
- &knobID,
- &knobValue))
- return NULL;
- _rv = MusicSetPartKnob(mc,
- part,
- knobID,
- knobValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MusicSetPartKnob);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &knobID,
+ &knobValue))
+ return NULL;
+ _rv = MusicSetPartKnob(mc,
+ part,
+ knobID,
+ knobValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetKnob(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long knobID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long knobID;
#ifndef MusicGetKnob
- PyMac_PRECHECK(MusicGetKnob);
+ PyMac_PRECHECK(MusicGetKnob);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &knobID))
- return NULL;
- _rv = MusicGetKnob(mc,
- knobID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &knobID))
+ return NULL;
+ _rv = MusicGetKnob(mc,
+ knobID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetKnob(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long knobID;
- long knobValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long knobID;
+ long knobValue;
#ifndef MusicSetKnob
- PyMac_PRECHECK(MusicSetKnob);
+ PyMac_PRECHECK(MusicSetKnob);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &knobID,
- &knobValue))
- return NULL;
- _rv = MusicSetKnob(mc,
- knobID,
- knobValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &knobID,
+ &knobValue))
+ return NULL;
+ _rv = MusicSetKnob(mc,
+ knobID,
+ knobValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetPartName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- StringPtr name;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ StringPtr name;
#ifndef MusicGetPartName
- PyMac_PRECHECK(MusicGetPartName);
+ PyMac_PRECHECK(MusicGetPartName);
#endif
- if (!PyArg_ParseTuple(_args, "O&ls",
- CmpInstObj_Convert, &mc,
- &part,
- &name))
- return NULL;
- _rv = MusicGetPartName(mc,
- part,
- name);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ls",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &name))
+ return NULL;
+ _rv = MusicGetPartName(mc,
+ part,
+ name);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetPartName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- StringPtr name;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ StringPtr name;
#ifndef MusicSetPartName
- PyMac_PRECHECK(MusicSetPartName);
+ PyMac_PRECHECK(MusicSetPartName);
#endif
- if (!PyArg_ParseTuple(_args, "O&ls",
- CmpInstObj_Convert, &mc,
- &part,
- &name))
- return NULL;
- _rv = MusicSetPartName(mc,
- part,
- name);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ls",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &name))
+ return NULL;
+ _rv = MusicSetPartName(mc,
+ part,
+ name);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicPlayNote(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long pitch;
- long velocity;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long pitch;
+ long velocity;
#ifndef MusicPlayNote
- PyMac_PRECHECK(MusicPlayNote);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- CmpInstObj_Convert, &mc,
- &part,
- &pitch,
- &velocity))
- return NULL;
- _rv = MusicPlayNote(mc,
- part,
- pitch,
- velocity);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MusicPlayNote);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &pitch,
+ &velocity))
+ return NULL;
+ _rv = MusicPlayNote(mc,
+ part,
+ pitch,
+ velocity);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicResetPart(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
#ifndef MusicResetPart
- PyMac_PRECHECK(MusicResetPart);
+ PyMac_PRECHECK(MusicResetPart);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &part))
- return NULL;
- _rv = MusicResetPart(mc,
- part);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &part))
+ return NULL;
+ _rv = MusicResetPart(mc,
+ part);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetPartController(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- MusicController controllerNumber;
- long controllerValue;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ MusicController controllerNumber;
+ long controllerValue;
#ifndef MusicSetPartController
- PyMac_PRECHECK(MusicSetPartController);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- CmpInstObj_Convert, &mc,
- &part,
- &controllerNumber,
- &controllerValue))
- return NULL;
- _rv = MusicSetPartController(mc,
- part,
- controllerNumber,
- controllerValue);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MusicSetPartController);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &controllerNumber,
+ &controllerValue))
+ return NULL;
+ _rv = MusicSetPartController(mc,
+ part,
+ controllerNumber,
+ controllerValue);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetPartController(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- MusicController controllerNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ MusicController controllerNumber;
#ifndef MusicGetPartController
- PyMac_PRECHECK(MusicGetPartController);
+ PyMac_PRECHECK(MusicGetPartController);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &part,
- &controllerNumber))
- return NULL;
- _rv = MusicGetPartController(mc,
- part,
- controllerNumber);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &controllerNumber))
+ return NULL;
+ _rv = MusicGetPartController(mc,
+ part,
+ controllerNumber);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetInstrumentNames(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long modifiableInstruments;
- Handle instrumentNames;
- Handle instrumentCategoryLasts;
- Handle instrumentCategoryNames;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long modifiableInstruments;
+ Handle instrumentNames;
+ Handle instrumentCategoryLasts;
+ Handle instrumentCategoryNames;
#ifndef MusicGetInstrumentNames
- PyMac_PRECHECK(MusicGetInstrumentNames);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &modifiableInstruments))
- return NULL;
- _rv = MusicGetInstrumentNames(mc,
- modifiableInstruments,
- &instrumentNames,
- &instrumentCategoryLasts,
- &instrumentCategoryNames);
- _res = Py_BuildValue("lO&O&O&",
- _rv,
- ResObj_New, instrumentNames,
- ResObj_New, instrumentCategoryLasts,
- ResObj_New, instrumentCategoryNames);
- return _res;
+ PyMac_PRECHECK(MusicGetInstrumentNames);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &modifiableInstruments))
+ return NULL;
+ _rv = MusicGetInstrumentNames(mc,
+ modifiableInstruments,
+ &instrumentNames,
+ &instrumentCategoryLasts,
+ &instrumentCategoryNames);
+ _res = Py_BuildValue("lO&O&O&",
+ _rv,
+ ResObj_New, instrumentNames,
+ ResObj_New, instrumentCategoryLasts,
+ ResObj_New, instrumentCategoryNames);
+ return _res;
}
static PyObject *Qt_MusicGetDrumNames(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long modifiableInstruments;
- Handle instrumentNumbers;
- Handle instrumentNames;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long modifiableInstruments;
+ Handle instrumentNumbers;
+ Handle instrumentNames;
#ifndef MusicGetDrumNames
- PyMac_PRECHECK(MusicGetDrumNames);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &modifiableInstruments))
- return NULL;
- _rv = MusicGetDrumNames(mc,
- modifiableInstruments,
- &instrumentNumbers,
- &instrumentNames);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, instrumentNumbers,
- ResObj_New, instrumentNames);
- return _res;
+ PyMac_PRECHECK(MusicGetDrumNames);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &modifiableInstruments))
+ return NULL;
+ _rv = MusicGetDrumNames(mc,
+ modifiableInstruments,
+ &instrumentNumbers,
+ &instrumentNames);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, instrumentNumbers,
+ ResObj_New, instrumentNames);
+ return _res;
}
static PyObject *Qt_MusicGetMasterTune(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
#ifndef MusicGetMasterTune
- PyMac_PRECHECK(MusicGetMasterTune);
+ PyMac_PRECHECK(MusicGetMasterTune);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mc))
- return NULL;
- _rv = MusicGetMasterTune(mc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mc))
+ return NULL;
+ _rv = MusicGetMasterTune(mc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetMasterTune(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long masterTune;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long masterTune;
#ifndef MusicSetMasterTune
- PyMac_PRECHECK(MusicSetMasterTune);
+ PyMac_PRECHECK(MusicSetMasterTune);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &masterTune))
- return NULL;
- _rv = MusicSetMasterTune(mc,
- masterTune);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &masterTune))
+ return NULL;
+ _rv = MusicSetMasterTune(mc,
+ masterTune);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetDeviceConnection(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long index;
- long id1;
- long id2;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long index;
+ long id1;
+ long id2;
#ifndef MusicGetDeviceConnection
- PyMac_PRECHECK(MusicGetDeviceConnection);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &index))
- return NULL;
- _rv = MusicGetDeviceConnection(mc,
- index,
- &id1,
- &id2);
- _res = Py_BuildValue("lll",
- _rv,
- id1,
- id2);
- return _res;
+ PyMac_PRECHECK(MusicGetDeviceConnection);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &index))
+ return NULL;
+ _rv = MusicGetDeviceConnection(mc,
+ index,
+ &id1,
+ &id2);
+ _res = Py_BuildValue("lll",
+ _rv,
+ id1,
+ id2);
+ return _res;
}
static PyObject *Qt_MusicUseDeviceConnection(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long id1;
- long id2;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long id1;
+ long id2;
#ifndef MusicUseDeviceConnection
- PyMac_PRECHECK(MusicUseDeviceConnection);
+ PyMac_PRECHECK(MusicUseDeviceConnection);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &id1,
- &id2))
- return NULL;
- _rv = MusicUseDeviceConnection(mc,
- id1,
- id2);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &id1,
+ &id2))
+ return NULL;
+ _rv = MusicUseDeviceConnection(mc,
+ id1,
+ id2);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetKnobSettingStrings(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long knobIndex;
- long isGlobal;
- Handle settingsNames;
- Handle settingsCategoryLasts;
- Handle settingsCategoryNames;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long knobIndex;
+ long isGlobal;
+ Handle settingsNames;
+ Handle settingsCategoryLasts;
+ Handle settingsCategoryNames;
#ifndef MusicGetKnobSettingStrings
- PyMac_PRECHECK(MusicGetKnobSettingStrings);
-#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &knobIndex,
- &isGlobal))
- return NULL;
- _rv = MusicGetKnobSettingStrings(mc,
- knobIndex,
- isGlobal,
- &settingsNames,
- &settingsCategoryLasts,
- &settingsCategoryNames);
- _res = Py_BuildValue("lO&O&O&",
- _rv,
- ResObj_New, settingsNames,
- ResObj_New, settingsCategoryLasts,
- ResObj_New, settingsCategoryNames);
- return _res;
+ PyMac_PRECHECK(MusicGetKnobSettingStrings);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &knobIndex,
+ &isGlobal))
+ return NULL;
+ _rv = MusicGetKnobSettingStrings(mc,
+ knobIndex,
+ isGlobal,
+ &settingsNames,
+ &settingsCategoryLasts,
+ &settingsCategoryNames);
+ _res = Py_BuildValue("lO&O&O&",
+ _rv,
+ ResObj_New, settingsNames,
+ ResObj_New, settingsCategoryLasts,
+ ResObj_New, settingsCategoryNames);
+ return _res;
}
static PyObject *Qt_MusicGetMIDIPorts(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long inputPortCount;
- long outputPortCount;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long inputPortCount;
+ long outputPortCount;
#ifndef MusicGetMIDIPorts
- PyMac_PRECHECK(MusicGetMIDIPorts);
+ PyMac_PRECHECK(MusicGetMIDIPorts);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mc))
- return NULL;
- _rv = MusicGetMIDIPorts(mc,
- &inputPortCount,
- &outputPortCount);
- _res = Py_BuildValue("lll",
- _rv,
- inputPortCount,
- outputPortCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mc))
+ return NULL;
+ _rv = MusicGetMIDIPorts(mc,
+ &inputPortCount,
+ &outputPortCount);
+ _res = Py_BuildValue("lll",
+ _rv,
+ inputPortCount,
+ outputPortCount);
+ return _res;
}
static PyObject *Qt_MusicSendMIDI(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long portIndex;
- MusicMIDIPacket mp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long portIndex;
+ MusicMIDIPacket mp;
#ifndef MusicSendMIDI
- PyMac_PRECHECK(MusicSendMIDI);
+ PyMac_PRECHECK(MusicSendMIDI);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mc,
- &portIndex,
- QtMusicMIDIPacket_Convert, &mp))
- return NULL;
- _rv = MusicSendMIDI(mc,
- portIndex,
- &mp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mc,
+ &portIndex,
+ QtMusicMIDIPacket_Convert, &mp))
+ return NULL;
+ _rv = MusicSendMIDI(mc,
+ portIndex,
+ &mp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetOfflineTimeTo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long newTimeStamp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long newTimeStamp;
#ifndef MusicSetOfflineTimeTo
- PyMac_PRECHECK(MusicSetOfflineTimeTo);
+ PyMac_PRECHECK(MusicSetOfflineTimeTo);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &newTimeStamp))
- return NULL;
- _rv = MusicSetOfflineTimeTo(mc,
- newTimeStamp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &newTimeStamp))
+ return NULL;
+ _rv = MusicSetOfflineTimeTo(mc,
+ newTimeStamp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGetInfoText(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long selector;
- Handle textH;
- Handle styleH;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long selector;
+ Handle textH;
+ Handle styleH;
#ifndef MusicGetInfoText
- PyMac_PRECHECK(MusicGetInfoText);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &selector))
- return NULL;
- _rv = MusicGetInfoText(mc,
- selector,
- &textH,
- &styleH);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, textH,
- ResObj_New, styleH);
- return _res;
+ PyMac_PRECHECK(MusicGetInfoText);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &selector))
+ return NULL;
+ _rv = MusicGetInfoText(mc,
+ selector,
+ &textH,
+ &styleH);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, textH,
+ ResObj_New, styleH);
+ return _res;
}
static PyObject *Qt_MusicGetInstrumentInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long getInstrumentInfoFlags;
- InstrumentInfoListHandle infoListH;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long getInstrumentInfoFlags;
+ InstrumentInfoListHandle infoListH;
#ifndef MusicGetInstrumentInfo
- PyMac_PRECHECK(MusicGetInstrumentInfo);
+ PyMac_PRECHECK(MusicGetInstrumentInfo);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &getInstrumentInfoFlags))
- return NULL;
- _rv = MusicGetInstrumentInfo(mc,
- getInstrumentInfoFlags,
- &infoListH);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, infoListH);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &getInstrumentInfoFlags))
+ return NULL;
+ _rv = MusicGetInstrumentInfo(mc,
+ getInstrumentInfoFlags,
+ &infoListH);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, infoListH);
+ return _res;
}
static PyObject *Qt_MusicTask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
#ifndef MusicTask
- PyMac_PRECHECK(MusicTask);
+ PyMac_PRECHECK(MusicTask);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mc))
- return NULL;
- _rv = MusicTask(mc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mc))
+ return NULL;
+ _rv = MusicTask(mc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetPartInstrumentNumberInterruptSafe(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- long instrumentNumber;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ long instrumentNumber;
#ifndef MusicSetPartInstrumentNumberInterruptSafe
- PyMac_PRECHECK(MusicSetPartInstrumentNumberInterruptSafe);
+ PyMac_PRECHECK(MusicSetPartInstrumentNumberInterruptSafe);
#endif
- if (!PyArg_ParseTuple(_args, "O&ll",
- CmpInstObj_Convert, &mc,
- &part,
- &instrumentNumber))
- return NULL;
- _rv = MusicSetPartInstrumentNumberInterruptSafe(mc,
- part,
- instrumentNumber);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&ll",
+ CmpInstObj_Convert, &mc,
+ &part,
+ &instrumentNumber))
+ return NULL;
+ _rv = MusicSetPartInstrumentNumberInterruptSafe(mc,
+ part,
+ instrumentNumber);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicSetPartSoundLocalization(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long part;
- Handle data;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long part;
+ Handle data;
#ifndef MusicSetPartSoundLocalization
- PyMac_PRECHECK(MusicSetPartSoundLocalization);
+ PyMac_PRECHECK(MusicSetPartSoundLocalization);
#endif
- if (!PyArg_ParseTuple(_args, "O&lO&",
- CmpInstObj_Convert, &mc,
- &part,
- ResObj_Convert, &data))
- return NULL;
- _rv = MusicSetPartSoundLocalization(mc,
- part,
- data);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&lO&",
+ CmpInstObj_Convert, &mc,
+ &part,
+ ResObj_Convert, &data))
+ return NULL;
+ _rv = MusicSetPartSoundLocalization(mc,
+ part,
+ data);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGenericConfigure(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long mode;
- long flags;
- long baseResID;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long mode;
+ long flags;
+ long baseResID;
#ifndef MusicGenericConfigure
- PyMac_PRECHECK(MusicGenericConfigure);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- CmpInstObj_Convert, &mc,
- &mode,
- &flags,
- &baseResID))
- return NULL;
- _rv = MusicGenericConfigure(mc,
- mode,
- flags,
- baseResID);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(MusicGenericConfigure);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ CmpInstObj_Convert, &mc,
+ &mode,
+ &flags,
+ &baseResID))
+ return NULL;
+ _rv = MusicGenericConfigure(mc,
+ mode,
+ flags,
+ baseResID);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicGenericGetKnobList(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- long knobType;
- GenericKnobDescriptionListHandle gkdlH;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ long knobType;
+ GenericKnobDescriptionListHandle gkdlH;
#ifndef MusicGenericGetKnobList
- PyMac_PRECHECK(MusicGenericGetKnobList);
+ PyMac_PRECHECK(MusicGenericGetKnobList);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &mc,
- &knobType))
- return NULL;
- _rv = MusicGenericGetKnobList(mc,
- knobType,
- &gkdlH);
- _res = Py_BuildValue("lO&",
- _rv,
- ResObj_New, gkdlH);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &mc,
+ &knobType))
+ return NULL;
+ _rv = MusicGenericGetKnobList(mc,
+ knobType,
+ &gkdlH);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ ResObj_New, gkdlH);
+ return _res;
}
static PyObject *Qt_MusicGenericSetResourceNumbers(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- Handle resourceIDH;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ Handle resourceIDH;
#ifndef MusicGenericSetResourceNumbers
- PyMac_PRECHECK(MusicGenericSetResourceNumbers);
+ PyMac_PRECHECK(MusicGenericSetResourceNumbers);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mc,
- ResObj_Convert, &resourceIDH))
- return NULL;
- _rv = MusicGenericSetResourceNumbers(mc,
- resourceIDH);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mc,
+ ResObj_Convert, &resourceIDH))
+ return NULL;
+ _rv = MusicGenericSetResourceNumbers(mc,
+ resourceIDH);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicDerivedMIDISend(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- MusicMIDIPacket packet;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ MusicMIDIPacket packet;
#ifndef MusicDerivedMIDISend
- PyMac_PRECHECK(MusicDerivedMIDISend);
+ PyMac_PRECHECK(MusicDerivedMIDISend);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &mc,
- QtMusicMIDIPacket_Convert, &packet))
- return NULL;
- _rv = MusicDerivedMIDISend(mc,
- &packet);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &mc,
+ QtMusicMIDIPacket_Convert, &packet))
+ return NULL;
+ _rv = MusicDerivedMIDISend(mc,
+ &packet);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicDerivedOpenResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
#ifndef MusicDerivedOpenResFile
- PyMac_PRECHECK(MusicDerivedOpenResFile);
+ PyMac_PRECHECK(MusicDerivedOpenResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &mc))
- return NULL;
- _rv = MusicDerivedOpenResFile(mc);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &mc))
+ return NULL;
+ _rv = MusicDerivedOpenResFile(mc);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_MusicDerivedCloseResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- MusicComponent mc;
- short resRefNum;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ MusicComponent mc;
+ short resRefNum;
#ifndef MusicDerivedCloseResFile
- PyMac_PRECHECK(MusicDerivedCloseResFile);
+ PyMac_PRECHECK(MusicDerivedCloseResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- CmpInstObj_Convert, &mc,
- &resRefNum))
- return NULL;
- _rv = MusicDerivedCloseResFile(mc,
- resRefNum);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ CmpInstObj_Convert, &mc,
+ &resRefNum))
+ return NULL;
+ _rv = MusicDerivedCloseResFile(mc,
+ resRefNum);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_NAUnregisterMusicDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- NoteAllocator na;
- long index;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ NoteAllocator na;
+ long index;
#ifndef NAUnregisterMusicDevice
- PyMac_PRECHECK(NAUnregisterMusicDevice);
+ PyMac_PRECHECK(NAUnregisterMusicDevice);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &na,
- &index))
- return NULL;
- _rv = NAUnregisterMusicDevice(na,
- index);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &na,
+ &index))
+ return NULL;
+ _rv = NAUnregisterMusicDevice(na,
+ index);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_NASaveMusicConfiguration(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- NoteAllocator na;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ NoteAllocator na;
#ifndef NASaveMusicConfiguration
- PyMac_PRECHECK(NASaveMusicConfiguration);
+ PyMac_PRECHECK(NASaveMusicConfiguration);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &na))
- return NULL;
- _rv = NASaveMusicConfiguration(na);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &na))
+ return NULL;
+ _rv = NASaveMusicConfiguration(na);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_NAGetMIDIPorts(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- NoteAllocator na;
- QTMIDIPortListHandle inputPorts;
- QTMIDIPortListHandle outputPorts;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ NoteAllocator na;
+ QTMIDIPortListHandle inputPorts;
+ QTMIDIPortListHandle outputPorts;
#ifndef NAGetMIDIPorts
- PyMac_PRECHECK(NAGetMIDIPorts);
+ PyMac_PRECHECK(NAGetMIDIPorts);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &na))
- return NULL;
- _rv = NAGetMIDIPorts(na,
- &inputPorts,
- &outputPorts);
- _res = Py_BuildValue("lO&O&",
- _rv,
- ResObj_New, inputPorts,
- ResObj_New, outputPorts);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &na))
+ return NULL;
+ _rv = NAGetMIDIPorts(na,
+ &inputPorts,
+ &outputPorts);
+ _res = Py_BuildValue("lO&O&",
+ _rv,
+ ResObj_New, inputPorts,
+ ResObj_New, outputPorts);
+ return _res;
}
static PyObject *Qt_NATask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- NoteAllocator na;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ NoteAllocator na;
#ifndef NATask
- PyMac_PRECHECK(NATask);
+ PyMac_PRECHECK(NATask);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &na))
- return NULL;
- _rv = NATask(na);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &na))
+ return NULL;
+ _rv = NATask(na);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetHeader(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- unsigned long * header;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ unsigned long * header;
#ifndef TuneSetHeader
- PyMac_PRECHECK(TuneSetHeader);
+ PyMac_PRECHECK(TuneSetHeader);
#endif
- if (!PyArg_ParseTuple(_args, "O&s",
- CmpInstObj_Convert, &tp,
- &header))
- return NULL;
- _rv = TuneSetHeader(tp,
- header);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&s",
+ CmpInstObj_Convert, &tp,
+ &header))
+ return NULL;
+ _rv = TuneSetHeader(tp,
+ header);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneGetTimeBase(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- TimeBase tb;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ TimeBase tb;
#ifndef TuneGetTimeBase
- PyMac_PRECHECK(TuneGetTimeBase);
+ PyMac_PRECHECK(TuneGetTimeBase);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TuneGetTimeBase(tp,
- &tb);
- _res = Py_BuildValue("lO&",
- _rv,
- TimeBaseObj_New, tb);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TuneGetTimeBase(tp,
+ &tb);
+ _res = Py_BuildValue("lO&",
+ _rv,
+ TimeBaseObj_New, tb);
+ return _res;
}
static PyObject *Qt_TuneSetTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- TimeScale scale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ TimeScale scale;
#ifndef TuneSetTimeScale
- PyMac_PRECHECK(TuneSetTimeScale);
+ PyMac_PRECHECK(TuneSetTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &tp,
- &scale))
- return NULL;
- _rv = TuneSetTimeScale(tp,
- scale);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &tp,
+ &scale))
+ return NULL;
+ _rv = TuneSetTimeScale(tp,
+ scale);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneGetTimeScale(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- TimeScale scale;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ TimeScale scale;
#ifndef TuneGetTimeScale
- PyMac_PRECHECK(TuneGetTimeScale);
+ PyMac_PRECHECK(TuneGetTimeScale);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TuneGetTimeScale(tp,
- &scale);
- _res = Py_BuildValue("ll",
- _rv,
- scale);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TuneGetTimeScale(tp,
+ &scale);
+ _res = Py_BuildValue("ll",
+ _rv,
+ scale);
+ return _res;
}
static PyObject *Qt_TuneInstant(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- unsigned long tune;
- unsigned long tunePosition;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ unsigned long tune;
+ unsigned long tunePosition;
#ifndef TuneInstant
- PyMac_PRECHECK(TuneInstant);
+ PyMac_PRECHECK(TuneInstant);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &tp,
- &tunePosition))
- return NULL;
- _rv = TuneInstant(tp,
- &tune,
- tunePosition);
- _res = Py_BuildValue("ll",
- _rv,
- tune);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &tp,
+ &tunePosition))
+ return NULL;
+ _rv = TuneInstant(tp,
+ &tune,
+ tunePosition);
+ _res = Py_BuildValue("ll",
+ _rv,
+ tune);
+ return _res;
}
static PyObject *Qt_TuneStop(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- long stopFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ long stopFlags;
#ifndef TuneStop
- PyMac_PRECHECK(TuneStop);
+ PyMac_PRECHECK(TuneStop);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &tp,
- &stopFlags))
- return NULL;
- _rv = TuneStop(tp,
- stopFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &tp,
+ &stopFlags))
+ return NULL;
+ _rv = TuneStop(tp,
+ stopFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- Fixed volume;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ Fixed volume;
#ifndef TuneSetVolume
- PyMac_PRECHECK(TuneSetVolume);
+ PyMac_PRECHECK(TuneSetVolume);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &tp,
- PyMac_GetFixed, &volume))
- return NULL;
- _rv = TuneSetVolume(tp,
- volume);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &tp,
+ PyMac_GetFixed, &volume))
+ return NULL;
+ _rv = TuneSetVolume(tp,
+ volume);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneGetVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
#ifndef TuneGetVolume
- PyMac_PRECHECK(TuneGetVolume);
+ PyMac_PRECHECK(TuneGetVolume);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TuneGetVolume(tp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TuneGetVolume(tp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TunePreroll(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
#ifndef TunePreroll
- PyMac_PRECHECK(TunePreroll);
+ PyMac_PRECHECK(TunePreroll);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TunePreroll(tp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TunePreroll(tp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneUnroll(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
#ifndef TuneUnroll
- PyMac_PRECHECK(TuneUnroll);
+ PyMac_PRECHECK(TuneUnroll);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TuneUnroll(tp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TuneUnroll(tp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetPartTranspose(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- unsigned long part;
- long transpose;
- long velocityShift;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ unsigned long part;
+ long transpose;
+ long velocityShift;
#ifndef TuneSetPartTranspose
- PyMac_PRECHECK(TuneSetPartTranspose);
-#endif
- if (!PyArg_ParseTuple(_args, "O&lll",
- CmpInstObj_Convert, &tp,
- &part,
- &transpose,
- &velocityShift))
- return NULL;
- _rv = TuneSetPartTranspose(tp,
- part,
- transpose,
- velocityShift);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(TuneSetPartTranspose);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&lll",
+ CmpInstObj_Convert, &tp,
+ &part,
+ &transpose,
+ &velocityShift))
+ return NULL;
+ _rv = TuneSetPartTranspose(tp,
+ part,
+ transpose,
+ velocityShift);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneGetNoteAllocator(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- NoteAllocator _rv;
- TunePlayer tp;
+ PyObject *_res = NULL;
+ NoteAllocator _rv;
+ TunePlayer tp;
#ifndef TuneGetNoteAllocator
- PyMac_PRECHECK(TuneGetNoteAllocator);
+ PyMac_PRECHECK(TuneGetNoteAllocator);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TuneGetNoteAllocator(tp);
- _res = Py_BuildValue("O&",
- CmpInstObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TuneGetNoteAllocator(tp);
+ _res = Py_BuildValue("O&",
+ CmpInstObj_New, _rv);
+ return _res;
}
static PyObject *Qt_TuneSetSofter(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- long softer;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ long softer;
#ifndef TuneSetSofter
- PyMac_PRECHECK(TuneSetSofter);
+ PyMac_PRECHECK(TuneSetSofter);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &tp,
- &softer))
- return NULL;
- _rv = TuneSetSofter(tp,
- softer);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &tp,
+ &softer))
+ return NULL;
+ _rv = TuneSetSofter(tp,
+ softer);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneTask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
#ifndef TuneTask
- PyMac_PRECHECK(TuneTask);
+ PyMac_PRECHECK(TuneTask);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CmpInstObj_Convert, &tp))
- return NULL;
- _rv = TuneTask(tp);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CmpInstObj_Convert, &tp))
+ return NULL;
+ _rv = TuneTask(tp);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetBalance(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- long balance;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ long balance;
#ifndef TuneSetBalance
- PyMac_PRECHECK(TuneSetBalance);
+ PyMac_PRECHECK(TuneSetBalance);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &tp,
- &balance))
- return NULL;
- _rv = TuneSetBalance(tp,
- balance);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &tp,
+ &balance))
+ return NULL;
+ _rv = TuneSetBalance(tp,
+ balance);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetSoundLocalization(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- Handle data;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ Handle data;
#ifndef TuneSetSoundLocalization
- PyMac_PRECHECK(TuneSetSoundLocalization);
+ PyMac_PRECHECK(TuneSetSoundLocalization);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- CmpInstObj_Convert, &tp,
- ResObj_Convert, &data))
- return NULL;
- _rv = TuneSetSoundLocalization(tp,
- data);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ CmpInstObj_Convert, &tp,
+ ResObj_Convert, &data))
+ return NULL;
+ _rv = TuneSetSoundLocalization(tp,
+ data);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetHeaderWithSize(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- unsigned long * header;
- unsigned long size;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ unsigned long * header;
+ unsigned long size;
#ifndef TuneSetHeaderWithSize
- PyMac_PRECHECK(TuneSetHeaderWithSize);
+ PyMac_PRECHECK(TuneSetHeaderWithSize);
#endif
- if (!PyArg_ParseTuple(_args, "O&sl",
- CmpInstObj_Convert, &tp,
- &header,
- &size))
- return NULL;
- _rv = TuneSetHeaderWithSize(tp,
- header,
- size);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&sl",
+ CmpInstObj_Convert, &tp,
+ &header,
+ &size))
+ return NULL;
+ _rv = TuneSetHeaderWithSize(tp,
+ header,
+ size);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneSetPartMix(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- unsigned long partNumber;
- long volume;
- long balance;
- long mixFlags;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ unsigned long partNumber;
+ long volume;
+ long balance;
+ long mixFlags;
#ifndef TuneSetPartMix
- PyMac_PRECHECK(TuneSetPartMix);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llll",
- CmpInstObj_Convert, &tp,
- &partNumber,
- &volume,
- &balance,
- &mixFlags))
- return NULL;
- _rv = TuneSetPartMix(tp,
- partNumber,
- volume,
- balance,
- mixFlags);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ PyMac_PRECHECK(TuneSetPartMix);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llll",
+ CmpInstObj_Convert, &tp,
+ &partNumber,
+ &volume,
+ &balance,
+ &mixFlags))
+ return NULL;
+ _rv = TuneSetPartMix(tp,
+ partNumber,
+ volume,
+ balance,
+ mixFlags);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Qt_TuneGetPartMix(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ComponentResult _rv;
- TunePlayer tp;
- unsigned long partNumber;
- long volumeOut;
- long balanceOut;
- long mixFlagsOut;
+ PyObject *_res = NULL;
+ ComponentResult _rv;
+ TunePlayer tp;
+ unsigned long partNumber;
+ long volumeOut;
+ long balanceOut;
+ long mixFlagsOut;
#ifndef TuneGetPartMix
- PyMac_PRECHECK(TuneGetPartMix);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- CmpInstObj_Convert, &tp,
- &partNumber))
- return NULL;
- _rv = TuneGetPartMix(tp,
- partNumber,
- &volumeOut,
- &balanceOut,
- &mixFlagsOut);
- _res = Py_BuildValue("llll",
- _rv,
- volumeOut,
- balanceOut,
- mixFlagsOut);
- return _res;
+ PyMac_PRECHECK(TuneGetPartMix);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ CmpInstObj_Convert, &tp,
+ &partNumber))
+ return NULL;
+ _rv = TuneGetPartMix(tp,
+ partNumber,
+ &volumeOut,
+ &balanceOut,
+ &mixFlagsOut);
+ _res = Py_BuildValue("llll",
+ _rv,
+ volumeOut,
+ balanceOut,
+ mixFlagsOut);
+ return _res;
}
static PyObject *Qt_AlignWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr wp;
- Boolean front;
+ PyObject *_res = NULL;
+ WindowPtr wp;
+ Boolean front;
#ifndef AlignWindow
- PyMac_PRECHECK(AlignWindow);
+ PyMac_PRECHECK(AlignWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- WinObj_Convert, &wp,
- &front))
- return NULL;
- AlignWindow(wp,
- front,
- (Rect *)0,
- (ICMAlignmentProcRecordPtr)0);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ WinObj_Convert, &wp,
+ &front))
+ return NULL;
+ AlignWindow(wp,
+ front,
+ (Rect *)0,
+ (ICMAlignmentProcRecordPtr)0);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_DragAlignedWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr wp;
- Point startPt;
- Rect boundsRect;
+ PyObject *_res = NULL;
+ WindowPtr wp;
+ Point startPt;
+ Rect boundsRect;
#ifndef DragAlignedWindow
- PyMac_PRECHECK(DragAlignedWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- WinObj_Convert, &wp,
- PyMac_GetPoint, &startPt,
- PyMac_GetRect, &boundsRect))
- return NULL;
- DragAlignedWindow(wp,
- startPt,
- &boundsRect,
- (Rect *)0,
- (ICMAlignmentProcRecordPtr)0);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(DragAlignedWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ WinObj_Convert, &wp,
+ PyMac_GetPoint, &startPt,
+ PyMac_GetRect, &boundsRect))
+ return NULL;
+ DragAlignedWindow(wp,
+ startPt,
+ &boundsRect,
+ (Rect *)0,
+ (ICMAlignmentProcRecordPtr)0);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Qt_MoviesTask(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long maxMilliSecToUse;
+ PyObject *_res = NULL;
+ long maxMilliSecToUse;
#ifndef MoviesTask
- PyMac_PRECHECK(MoviesTask);
+ PyMac_PRECHECK(MoviesTask);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &maxMilliSecToUse))
- return NULL;
- MoviesTask((Movie)0,
- maxMilliSecToUse);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &maxMilliSecToUse))
+ return NULL;
+ MoviesTask((Movie)0,
+ maxMilliSecToUse);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Qt_methods[] = {
#ifndef __LP64__
- {"EnterMovies", (PyCFunction)Qt_EnterMovies, 1,
- PyDoc_STR("() -> None")},
- {"ExitMovies", (PyCFunction)Qt_ExitMovies, 1,
- PyDoc_STR("() -> None")},
- {"GetMoviesError", (PyCFunction)Qt_GetMoviesError, 1,
- PyDoc_STR("() -> None")},
- {"ClearMoviesStickyError", (PyCFunction)Qt_ClearMoviesStickyError, 1,
- PyDoc_STR("() -> None")},
- {"GetMoviesStickyError", (PyCFunction)Qt_GetMoviesStickyError, 1,
- PyDoc_STR("() -> None")},
- {"QTGetWallClockTimeBase", (PyCFunction)Qt_QTGetWallClockTimeBase, 1,
- PyDoc_STR("() -> (TimeBase wallClockTimeBase)")},
- {"QTIdleManagerOpen", (PyCFunction)Qt_QTIdleManagerOpen, 1,
- PyDoc_STR("() -> (IdleManager _rv)")},
- {"CreateMovieControl", (PyCFunction)Qt_CreateMovieControl, 1,
- PyDoc_STR("(WindowPtr theWindow, Movie theMovie, UInt32 options) -> (Rect localRect, ControlHandle returnedControl)")},
- {"DisposeMatte", (PyCFunction)Qt_DisposeMatte, 1,
- PyDoc_STR("(PixMapHandle theMatte) -> None")},
- {"NewMovie", (PyCFunction)Qt_NewMovie, 1,
- PyDoc_STR("(long flags) -> (Movie _rv)")},
- {"QTGetTimeUntilNextTask", (PyCFunction)Qt_QTGetTimeUntilNextTask, 1,
- PyDoc_STR("(long scale) -> (long duration)")},
- {"GetDataHandler", (PyCFunction)Qt_GetDataHandler, 1,
- PyDoc_STR("(Handle dataRef, OSType dataHandlerSubType, long flags) -> (Component _rv)")},
- {"PasteHandleIntoMovie", (PyCFunction)Qt_PasteHandleIntoMovie, 1,
- PyDoc_STR("(Handle h, OSType handleType, Movie theMovie, long flags, ComponentInstance userComp) -> None")},
- {"GetMovieImporterForDataRef", (PyCFunction)Qt_GetMovieImporterForDataRef, 1,
- PyDoc_STR("(OSType dataRefType, Handle dataRef, long flags) -> (Component importer)")},
- {"QTGetMIMETypeInfo", (PyCFunction)Qt_QTGetMIMETypeInfo, 1,
- PyDoc_STR("(char* mimeStringStart, short mimeStringLength, OSType infoSelector, void * infoDataPtr) -> (long infoDataSize)")},
- {"TrackTimeToMediaTime", (PyCFunction)Qt_TrackTimeToMediaTime, 1,
- PyDoc_STR("(TimeValue value, Track theTrack) -> (TimeValue _rv)")},
- {"NewUserData", (PyCFunction)Qt_NewUserData, 1,
- PyDoc_STR("() -> (UserData theUserData)")},
- {"NewUserDataFromHandle", (PyCFunction)Qt_NewUserDataFromHandle, 1,
- PyDoc_STR("(Handle h) -> (UserData theUserData)")},
- {"CreateMovieFile", (PyCFunction)Qt_CreateMovieFile, 1,
- PyDoc_STR("(FSSpec fileSpec, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (short resRefNum, Movie newmovie)")},
- {"OpenMovieFile", (PyCFunction)Qt_OpenMovieFile, 1,
- PyDoc_STR("(FSSpec fileSpec, SInt8 permission) -> (short resRefNum)")},
- {"CloseMovieFile", (PyCFunction)Qt_CloseMovieFile, 1,
- PyDoc_STR("(short resRefNum) -> None")},
- {"DeleteMovieFile", (PyCFunction)Qt_DeleteMovieFile, 1,
- PyDoc_STR("(FSSpec fileSpec) -> None")},
- {"NewMovieFromFile", (PyCFunction)Qt_NewMovieFromFile, 1,
- PyDoc_STR("(short resRefNum, short resId, short newMovieFlags) -> (Movie theMovie, short resId, Boolean dataRefWasChanged)")},
- {"NewMovieFromHandle", (PyCFunction)Qt_NewMovieFromHandle, 1,
- PyDoc_STR("(Handle h, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasChanged)")},
- {"NewMovieFromDataFork", (PyCFunction)Qt_NewMovieFromDataFork, 1,
- PyDoc_STR("(short fRefNum, long fileOffset, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasChanged)")},
- {"NewMovieFromDataFork64", (PyCFunction)Qt_NewMovieFromDataFork64, 1,
- PyDoc_STR("(long fRefNum, wide fileOffset, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasChanged)")},
- {"NewMovieFromDataRef", (PyCFunction)Qt_NewMovieFromDataRef, 1,
- PyDoc_STR("(short flags, Handle dataRef, OSType dtaRefType) -> (Movie m, short id)")},
- {"NewMovieFromStorageOffset", (PyCFunction)Qt_NewMovieFromStorageOffset, 1,
- PyDoc_STR("(DataHandler dh, wide fileOffset, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasCataRefType)")},
- {"NewMovieForDataRefFromHandle", (PyCFunction)Qt_NewMovieForDataRefFromHandle, 1,
- PyDoc_STR("(Handle h, short newMovieFlags, Handle dataRef, OSType dataRefType) -> (Movie theMovie, Boolean dataRefWasChanged)")},
- {"RemoveMovieResource", (PyCFunction)Qt_RemoveMovieResource, 1,
- PyDoc_STR("(short resRefNum, short resId) -> None")},
- {"CreateMovieStorage", (PyCFunction)Qt_CreateMovieStorage, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (DataHandler outDataHandler, Movie newmovie)")},
- {"OpenMovieStorage", (PyCFunction)Qt_OpenMovieStorage, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType, long flags) -> (DataHandler outDataHandler)")},
- {"CloseMovieStorage", (PyCFunction)Qt_CloseMovieStorage, 1,
- PyDoc_STR("(DataHandler dh) -> None")},
- {"DeleteMovieStorage", (PyCFunction)Qt_DeleteMovieStorage, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType) -> None")},
- {"CreateShortcutMovieFile", (PyCFunction)Qt_CreateShortcutMovieFile, 1,
- PyDoc_STR("(FSSpec fileSpec, OSType creator, ScriptCode scriptTag, long createMovieFileFlags, Handle targetDataRef, OSType targetDataRefType) -> None")},
- {"CanQuickTimeOpenFile", (PyCFunction)Qt_CanQuickTimeOpenFile, 1,
- PyDoc_STR("(FSSpec fileSpec, OSType fileType, OSType fileNameExtension, UInt32 inFlags) -> (Boolean outCanOpenWithGraphicsImporter, Boolean outCanOpenAsMovie, Boolean outPreferGraphicsImporter)")},
- {"CanQuickTimeOpenDataRef", (PyCFunction)Qt_CanQuickTimeOpenDataRef, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType, UInt32 inFlags) -> (Boolean outCanOpenWithGraphicsImporter, Boolean outCanOpenAsMovie, Boolean outPreferGraphicsImporter)")},
- {"NewMovieFromScrap", (PyCFunction)Qt_NewMovieFromScrap, 1,
- PyDoc_STR("(long newMovieFlags) -> (Movie _rv)")},
- {"QTNewAlias", (PyCFunction)Qt_QTNewAlias, 1,
- PyDoc_STR("(FSSpec fss, Boolean minimal) -> (AliasHandle alias)")},
- {"EndFullScreen", (PyCFunction)Qt_EndFullScreen, 1,
- PyDoc_STR("(Ptr fullState, long flags) -> None")},
- {"AddSoundDescriptionExtension", (PyCFunction)Qt_AddSoundDescriptionExtension, 1,
- PyDoc_STR("(SoundDescriptionHandle desc, Handle extension, OSType idType) -> None")},
- {"GetSoundDescriptionExtension", (PyCFunction)Qt_GetSoundDescriptionExtension, 1,
- PyDoc_STR("(SoundDescriptionHandle desc, OSType idType) -> (Handle extension)")},
- {"RemoveSoundDescriptionExtension", (PyCFunction)Qt_RemoveSoundDescriptionExtension, 1,
- PyDoc_STR("(SoundDescriptionHandle desc, OSType idType) -> None")},
- {"QTIsStandardParameterDialogEvent", (PyCFunction)Qt_QTIsStandardParameterDialogEvent, 1,
- PyDoc_STR("(QTParameterDialog createdDialog) -> (EventRecord pEvent)")},
- {"QTDismissStandardParameterDialog", (PyCFunction)Qt_QTDismissStandardParameterDialog, 1,
- PyDoc_STR("(QTParameterDialog createdDialog) -> None")},
- {"QTStandardParameterDialogDoAction", (PyCFunction)Qt_QTStandardParameterDialogDoAction, 1,
- PyDoc_STR("(QTParameterDialog createdDialog, long action, void * params) -> None")},
- {"QTRegisterAccessKey", (PyCFunction)Qt_QTRegisterAccessKey, 1,
- PyDoc_STR("(Str255 accessKeyType, long flags, Handle accessKey) -> None")},
- {"QTUnregisterAccessKey", (PyCFunction)Qt_QTUnregisterAccessKey, 1,
- PyDoc_STR("(Str255 accessKeyType, long flags, Handle accessKey) -> None")},
- {"QTGetSupportedRestrictions", (PyCFunction)Qt_QTGetSupportedRestrictions, 1,
- PyDoc_STR("(OSType inRestrictionClass) -> (UInt32 outRestrictionIDs)")},
- {"QTTextToNativeText", (PyCFunction)Qt_QTTextToNativeText, 1,
- PyDoc_STR("(Handle theText, long encoding, long flags) -> None")},
- {"VideoMediaResetStatistics", (PyCFunction)Qt_VideoMediaResetStatistics, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"VideoMediaGetStatistics", (PyCFunction)Qt_VideoMediaGetStatistics, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"VideoMediaGetStallCount", (PyCFunction)Qt_VideoMediaGetStallCount, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, unsigned long stalls)")},
- {"VideoMediaSetCodecParameter", (PyCFunction)Qt_VideoMediaSetCodecParameter, 1,
- PyDoc_STR("(MediaHandler mh, CodecType cType, OSType parameterID, long parameterChangeSeed, void * dataPtr, long dataSize) -> (ComponentResult _rv)")},
- {"VideoMediaGetCodecParameter", (PyCFunction)Qt_VideoMediaGetCodecParameter, 1,
- PyDoc_STR("(MediaHandler mh, CodecType cType, OSType parameterID, Handle outParameterData) -> (ComponentResult _rv)")},
- {"TextMediaAddTextSample", (PyCFunction)Qt_TextMediaAddTextSample, 1,
- PyDoc_STR("(MediaHandler mh, Ptr text, unsigned long size, short fontNumber, short fontSize, Style textFace, short textJustification, long displayFlags, TimeValue scrollDelay, short hiliteStart, short hiliteEnd, TimeValue duration) -> (ComponentResult _rv, RGBColor textColor, RGBColor backColor, Rect textBox, RGBColor rgbHiliteColor, TimeValue sampleTime)")},
- {"TextMediaAddTESample", (PyCFunction)Qt_TextMediaAddTESample, 1,
- PyDoc_STR("(MediaHandler mh, TEHandle hTE, short textJustification, long displayFlags, TimeValue scrollDelay, short hiliteStart, short hiliteEnd, TimeValue duration) -> (ComponentResult _rv, RGBColor backColor, Rect textBox, RGBColor rgbHiliteColor, TimeValue sampleTime)")},
- {"TextMediaAddHiliteSample", (PyCFunction)Qt_TextMediaAddHiliteSample, 1,
- PyDoc_STR("(MediaHandler mh, short hiliteStart, short hiliteEnd, TimeValue duration) -> (ComponentResult _rv, RGBColor rgbHiliteColor, TimeValue sampleTime)")},
- {"TextMediaDrawRaw", (PyCFunction)Qt_TextMediaDrawRaw, 1,
- PyDoc_STR("(MediaHandler mh, GWorldPtr gw, GDHandle gd, void * data, long dataSize, TextDescriptionHandle tdh) -> (ComponentResult _rv)")},
- {"TextMediaSetTextProperty", (PyCFunction)Qt_TextMediaSetTextProperty, 1,
- PyDoc_STR("(MediaHandler mh, TimeValue atMediaTime, long propertyType, void * data, long dataSize) -> (ComponentResult _rv)")},
- {"TextMediaRawSetup", (PyCFunction)Qt_TextMediaRawSetup, 1,
- PyDoc_STR("(MediaHandler mh, GWorldPtr gw, GDHandle gd, void * data, long dataSize, TextDescriptionHandle tdh, TimeValue sampleDuration) -> (ComponentResult _rv)")},
- {"TextMediaRawIdle", (PyCFunction)Qt_TextMediaRawIdle, 1,
- PyDoc_STR("(MediaHandler mh, GWorldPtr gw, GDHandle gd, TimeValue sampleTime, long flagsIn) -> (ComponentResult _rv, long flagsOut)")},
- {"TextMediaGetTextProperty", (PyCFunction)Qt_TextMediaGetTextProperty, 1,
- PyDoc_STR("(MediaHandler mh, TimeValue atMediaTime, long propertyType, void * data, long dataSize) -> (ComponentResult _rv)")},
- {"TextMediaFindNextText", (PyCFunction)Qt_TextMediaFindNextText, 1,
- PyDoc_STR("(MediaHandler mh, Ptr text, long size, short findFlags, TimeValue startTime) -> (ComponentResult _rv, TimeValue foundTime, TimeValue foundDuration, long offset)")},
- {"TextMediaHiliteTextSample", (PyCFunction)Qt_TextMediaHiliteTextSample, 1,
- PyDoc_STR("(MediaHandler mh, TimeValue sampleTime, short hiliteStart, short hiliteEnd) -> (ComponentResult _rv, RGBColor rgbHiliteColor)")},
- {"TextMediaSetTextSampleData", (PyCFunction)Qt_TextMediaSetTextSampleData, 1,
- PyDoc_STR("(MediaHandler mh, void * data, OSType dataType) -> (ComponentResult _rv)")},
- {"SpriteMediaSetProperty", (PyCFunction)Qt_SpriteMediaSetProperty, 1,
- PyDoc_STR("(MediaHandler mh, short spriteIndex, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
- {"SpriteMediaGetProperty", (PyCFunction)Qt_SpriteMediaGetProperty, 1,
- PyDoc_STR("(MediaHandler mh, short spriteIndex, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
- {"SpriteMediaHitTestSprites", (PyCFunction)Qt_SpriteMediaHitTestSprites, 1,
- PyDoc_STR("(MediaHandler mh, long flags, Point loc) -> (ComponentResult _rv, short spriteHitIndex)")},
- {"SpriteMediaCountSprites", (PyCFunction)Qt_SpriteMediaCountSprites, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short numSprites)")},
- {"SpriteMediaCountImages", (PyCFunction)Qt_SpriteMediaCountImages, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short numImages)")},
- {"SpriteMediaGetIndImageDescription", (PyCFunction)Qt_SpriteMediaGetIndImageDescription, 1,
- PyDoc_STR("(MediaHandler mh, short imageIndex, ImageDescriptionHandle imageDescription) -> (ComponentResult _rv)")},
- {"SpriteMediaGetDisplayedSampleNumber", (PyCFunction)Qt_SpriteMediaGetDisplayedSampleNumber, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long sampleNum)")},
- {"SpriteMediaGetSpriteName", (PyCFunction)Qt_SpriteMediaGetSpriteName, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, Str255 spriteName) -> (ComponentResult _rv)")},
- {"SpriteMediaGetImageName", (PyCFunction)Qt_SpriteMediaGetImageName, 1,
- PyDoc_STR("(MediaHandler mh, short imageIndex, Str255 imageName) -> (ComponentResult _rv)")},
- {"SpriteMediaSetSpriteProperty", (PyCFunction)Qt_SpriteMediaSetSpriteProperty, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
- {"SpriteMediaGetSpriteProperty", (PyCFunction)Qt_SpriteMediaGetSpriteProperty, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
- {"SpriteMediaHitTestAllSprites", (PyCFunction)Qt_SpriteMediaHitTestAllSprites, 1,
- PyDoc_STR("(MediaHandler mh, long flags, Point loc) -> (ComponentResult _rv, QTAtomID spriteHitID)")},
- {"SpriteMediaHitTestOneSprite", (PyCFunction)Qt_SpriteMediaHitTestOneSprite, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, long flags, Point loc) -> (ComponentResult _rv, Boolean wasHit)")},
- {"SpriteMediaSpriteIndexToID", (PyCFunction)Qt_SpriteMediaSpriteIndexToID, 1,
- PyDoc_STR("(MediaHandler mh, short spriteIndex) -> (ComponentResult _rv, QTAtomID spriteID)")},
- {"SpriteMediaSpriteIDToIndex", (PyCFunction)Qt_SpriteMediaSpriteIDToIndex, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID spriteID) -> (ComponentResult _rv, short spriteIndex)")},
- {"SpriteMediaSetActionVariable", (PyCFunction)Qt_SpriteMediaSetActionVariable, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID variableID, float value) -> (ComponentResult _rv)")},
- {"SpriteMediaGetActionVariable", (PyCFunction)Qt_SpriteMediaGetActionVariable, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID variableID) -> (ComponentResult _rv, float value)")},
- {"SpriteMediaDisposeSprite", (PyCFunction)Qt_SpriteMediaDisposeSprite, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID spriteID) -> (ComponentResult _rv)")},
- {"SpriteMediaSetActionVariableToString", (PyCFunction)Qt_SpriteMediaSetActionVariableToString, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID variableID, Ptr theCString) -> (ComponentResult _rv)")},
- {"SpriteMediaGetActionVariableAsString", (PyCFunction)Qt_SpriteMediaGetActionVariableAsString, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID variableID) -> (ComponentResult _rv, Handle theCString)")},
- {"SpriteMediaNewImage", (PyCFunction)Qt_SpriteMediaNewImage, 1,
- PyDoc_STR("(MediaHandler mh, Handle dataRef, OSType dataRefType, QTAtomID desiredID) -> (ComponentResult _rv)")},
- {"SpriteMediaDisposeImage", (PyCFunction)Qt_SpriteMediaDisposeImage, 1,
- PyDoc_STR("(MediaHandler mh, short imageIndex) -> (ComponentResult _rv)")},
- {"SpriteMediaImageIndexToID", (PyCFunction)Qt_SpriteMediaImageIndexToID, 1,
- PyDoc_STR("(MediaHandler mh, short imageIndex) -> (ComponentResult _rv, QTAtomID imageID)")},
- {"SpriteMediaImageIDToIndex", (PyCFunction)Qt_SpriteMediaImageIDToIndex, 1,
- PyDoc_STR("(MediaHandler mh, QTAtomID imageID) -> (ComponentResult _rv, short imageIndex)")},
- {"FlashMediaSetPan", (PyCFunction)Qt_FlashMediaSetPan, 1,
- PyDoc_STR("(MediaHandler mh, short xPercent, short yPercent) -> (ComponentResult _rv)")},
- {"FlashMediaSetZoom", (PyCFunction)Qt_FlashMediaSetZoom, 1,
- PyDoc_STR("(MediaHandler mh, short factor) -> (ComponentResult _rv)")},
- {"FlashMediaSetZoomRect", (PyCFunction)Qt_FlashMediaSetZoomRect, 1,
- PyDoc_STR("(MediaHandler mh, long left, long top, long right, long bottom) -> (ComponentResult _rv)")},
- {"FlashMediaGetRefConBounds", (PyCFunction)Qt_FlashMediaGetRefConBounds, 1,
- PyDoc_STR("(MediaHandler mh, long refCon) -> (ComponentResult _rv, long left, long top, long right, long bottom)")},
- {"FlashMediaGetRefConID", (PyCFunction)Qt_FlashMediaGetRefConID, 1,
- PyDoc_STR("(MediaHandler mh, long refCon) -> (ComponentResult _rv, long refConID)")},
- {"FlashMediaIDToRefCon", (PyCFunction)Qt_FlashMediaIDToRefCon, 1,
- PyDoc_STR("(MediaHandler mh, long refConID) -> (ComponentResult _rv, long refCon)")},
- {"FlashMediaGetDisplayedFrameNumber", (PyCFunction)Qt_FlashMediaGetDisplayedFrameNumber, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long flashFrameNumber)")},
- {"FlashMediaFrameNumberToMovieTime", (PyCFunction)Qt_FlashMediaFrameNumberToMovieTime, 1,
- PyDoc_STR("(MediaHandler mh, long flashFrameNumber) -> (ComponentResult _rv, TimeValue movieTime)")},
- {"FlashMediaFrameLabelToMovieTime", (PyCFunction)Qt_FlashMediaFrameLabelToMovieTime, 1,
- PyDoc_STR("(MediaHandler mh, Ptr theLabel) -> (ComponentResult _rv, TimeValue movieTime)")},
- {"FlashMediaGetFlashVariable", (PyCFunction)Qt_FlashMediaGetFlashVariable, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, char path, char name, Handle theVariableCStringOut)")},
- {"FlashMediaSetFlashVariable", (PyCFunction)Qt_FlashMediaSetFlashVariable, 1,
- PyDoc_STR("(MediaHandler mh, Boolean updateFocus) -> (ComponentResult _rv, char path, char name, char value)")},
- {"FlashMediaDoButtonActions", (PyCFunction)Qt_FlashMediaDoButtonActions, 1,
- PyDoc_STR("(MediaHandler mh, long buttonID, long transition) -> (ComponentResult _rv, char path)")},
- {"FlashMediaGetSupportedSwfVersion", (PyCFunction)Qt_FlashMediaGetSupportedSwfVersion, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt8 swfVersion)")},
- {"Media3DGetCurrentGroup", (PyCFunction)Qt_Media3DGetCurrentGroup, 1,
- PyDoc_STR("(MediaHandler mh, void * group) -> (ComponentResult _rv)")},
- {"Media3DTranslateNamedObjectTo", (PyCFunction)Qt_Media3DTranslateNamedObjectTo, 1,
- PyDoc_STR("(MediaHandler mh, Fixed x, Fixed y, Fixed z) -> (ComponentResult _rv, char objectName)")},
- {"Media3DScaleNamedObjectTo", (PyCFunction)Qt_Media3DScaleNamedObjectTo, 1,
- PyDoc_STR("(MediaHandler mh, Fixed xScale, Fixed yScale, Fixed zScale) -> (ComponentResult _rv, char objectName)")},
- {"Media3DRotateNamedObjectTo", (PyCFunction)Qt_Media3DRotateNamedObjectTo, 1,
- PyDoc_STR("(MediaHandler mh, Fixed xDegrees, Fixed yDegrees, Fixed zDegrees) -> (ComponentResult _rv, char objectName)")},
- {"Media3DSetCameraData", (PyCFunction)Qt_Media3DSetCameraData, 1,
- PyDoc_STR("(MediaHandler mh, void * cameraData) -> (ComponentResult _rv)")},
- {"Media3DGetCameraData", (PyCFunction)Qt_Media3DGetCameraData, 1,
- PyDoc_STR("(MediaHandler mh, void * cameraData) -> (ComponentResult _rv)")},
- {"Media3DSetCameraAngleAspect", (PyCFunction)Qt_Media3DSetCameraAngleAspect, 1,
- PyDoc_STR("(MediaHandler mh, QTFloatSingle fov, QTFloatSingle aspectRatioXToY) -> (ComponentResult _rv)")},
- {"Media3DGetCameraAngleAspect", (PyCFunction)Qt_Media3DGetCameraAngleAspect, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, QTFloatSingle fov, QTFloatSingle aspectRatioXToY)")},
- {"Media3DSetCameraRange", (PyCFunction)Qt_Media3DSetCameraRange, 1,
- PyDoc_STR("(MediaHandler mh, void * tQ3CameraRange) -> (ComponentResult _rv)")},
- {"Media3DGetCameraRange", (PyCFunction)Qt_Media3DGetCameraRange, 1,
- PyDoc_STR("(MediaHandler mh, void * tQ3CameraRange) -> (ComponentResult _rv)")},
- {"NewTimeBase", (PyCFunction)Qt_NewTimeBase, 1,
- PyDoc_STR("() -> (TimeBase _rv)")},
- {"ConvertTime", (PyCFunction)Qt_ConvertTime, 1,
- PyDoc_STR("(TimeRecord theTime, TimeBase newBase) -> (TimeRecord theTime)")},
- {"ConvertTimeScale", (PyCFunction)Qt_ConvertTimeScale, 1,
- PyDoc_STR("(TimeRecord theTime, TimeScale newScale) -> (TimeRecord theTime)")},
- {"AddTime", (PyCFunction)Qt_AddTime, 1,
- PyDoc_STR("(TimeRecord dst, TimeRecord src) -> (TimeRecord dst)")},
- {"SubtractTime", (PyCFunction)Qt_SubtractTime, 1,
- PyDoc_STR("(TimeRecord dst, TimeRecord src) -> (TimeRecord dst)")},
- {"MusicMediaGetIndexedTunePlayer", (PyCFunction)Qt_MusicMediaGetIndexedTunePlayer, 1,
- PyDoc_STR("(ComponentInstance ti, long sampleDescIndex) -> (ComponentResult _rv, ComponentInstance tp)")},
- {"CodecManagerVersion", (PyCFunction)Qt_CodecManagerVersion, 1,
- PyDoc_STR("() -> (long version)")},
- {"GetMaxCompressionSize", (PyCFunction)Qt_GetMaxCompressionSize, 1,
- PyDoc_STR("(PixMapHandle src, Rect srcRect, short colorDepth, CodecQ quality, CodecType cType, CompressorComponent codec) -> (long size)")},
- {"GetCompressionTime", (PyCFunction)Qt_GetCompressionTime, 1,
- PyDoc_STR("(PixMapHandle src, Rect srcRect, short colorDepth, CodecType cType, CompressorComponent codec) -> (CodecQ spatialQuality, CodecQ temporalQuality, unsigned long compressTime)")},
- {"CompressImage", (PyCFunction)Qt_CompressImage, 1,
- PyDoc_STR("(PixMapHandle src, Rect srcRect, CodecQ quality, CodecType cType, ImageDescriptionHandle desc, Ptr data) -> None")},
- {"DecompressImage", (PyCFunction)Qt_DecompressImage, 1,
- PyDoc_STR("(Ptr data, ImageDescriptionHandle desc, PixMapHandle dst, Rect srcRect, Rect dstRect, short mode, RgnHandle mask) -> None")},
- {"GetSimilarity", (PyCFunction)Qt_GetSimilarity, 1,
- PyDoc_STR("(PixMapHandle src, Rect srcRect, ImageDescriptionHandle desc, Ptr data) -> (Fixed similarity)")},
- {"GetImageDescriptionCTable", (PyCFunction)Qt_GetImageDescriptionCTable, 1,
- PyDoc_STR("(ImageDescriptionHandle desc) -> (CTabHandle ctable)")},
- {"SetImageDescriptionCTable", (PyCFunction)Qt_SetImageDescriptionCTable, 1,
- PyDoc_STR("(ImageDescriptionHandle desc, CTabHandle ctable) -> None")},
- {"GetImageDescriptionExtension", (PyCFunction)Qt_GetImageDescriptionExtension, 1,
- PyDoc_STR("(ImageDescriptionHandle desc, long idType, long index) -> (Handle extension)")},
- {"AddImageDescriptionExtension", (PyCFunction)Qt_AddImageDescriptionExtension, 1,
- PyDoc_STR("(ImageDescriptionHandle desc, Handle extension, long idType) -> None")},
- {"RemoveImageDescriptionExtension", (PyCFunction)Qt_RemoveImageDescriptionExtension, 1,
- PyDoc_STR("(ImageDescriptionHandle desc, long idType, long index) -> None")},
- {"CountImageDescriptionExtensionType", (PyCFunction)Qt_CountImageDescriptionExtensionType, 1,
- PyDoc_STR("(ImageDescriptionHandle desc, long idType) -> (long count)")},
- {"GetNextImageDescriptionExtensionType", (PyCFunction)Qt_GetNextImageDescriptionExtensionType, 1,
- PyDoc_STR("(ImageDescriptionHandle desc) -> (long idType)")},
- {"FindCodec", (PyCFunction)Qt_FindCodec, 1,
- PyDoc_STR("(CodecType cType, CodecComponent specCodec) -> (CompressorComponent compressor, DecompressorComponent decompressor)")},
- {"CompressPicture", (PyCFunction)Qt_CompressPicture, 1,
- PyDoc_STR("(PicHandle srcPicture, PicHandle dstPicture, CodecQ quality, CodecType cType) -> None")},
- {"CompressPictureFile", (PyCFunction)Qt_CompressPictureFile, 1,
- PyDoc_STR("(short srcRefNum, short dstRefNum, CodecQ quality, CodecType cType) -> None")},
- {"ConvertImage", (PyCFunction)Qt_ConvertImage, 1,
- PyDoc_STR("(ImageDescriptionHandle srcDD, Ptr srcData, short colorDepth, CTabHandle ctable, CodecQ accuracy, CodecQ quality, CodecType cType, CodecComponent codec, ImageDescriptionHandle dstDD, Ptr dstData) -> None")},
- {"AddFilePreview", (PyCFunction)Qt_AddFilePreview, 1,
- PyDoc_STR("(short resRefNum, OSType previewType, Handle previewData) -> None")},
- {"GetBestDeviceRect", (PyCFunction)Qt_GetBestDeviceRect, 1,
- PyDoc_STR("() -> (GDHandle gdh, Rect rp)")},
- {"GDHasScale", (PyCFunction)Qt_GDHasScale, 1,
- PyDoc_STR("(GDHandle gdh, short depth) -> (Fixed scale)")},
- {"GDGetScale", (PyCFunction)Qt_GDGetScale, 1,
- PyDoc_STR("(GDHandle gdh) -> (Fixed scale, short flags)")},
- {"GDSetScale", (PyCFunction)Qt_GDSetScale, 1,
- PyDoc_STR("(GDHandle gdh, Fixed scale, short flags) -> None")},
- {"GetGraphicsImporterForFile", (PyCFunction)Qt_GetGraphicsImporterForFile, 1,
- PyDoc_STR("(FSSpec theFile) -> (ComponentInstance gi)")},
- {"GetGraphicsImporterForDataRef", (PyCFunction)Qt_GetGraphicsImporterForDataRef, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType) -> (ComponentInstance gi)")},
- {"GetGraphicsImporterForFileWithFlags", (PyCFunction)Qt_GetGraphicsImporterForFileWithFlags, 1,
- PyDoc_STR("(FSSpec theFile, long flags) -> (ComponentInstance gi)")},
- {"GetGraphicsImporterForDataRefWithFlags", (PyCFunction)Qt_GetGraphicsImporterForDataRefWithFlags, 1,
- PyDoc_STR("(Handle dataRef, OSType dataRefType, long flags) -> (ComponentInstance gi)")},
- {"MakeImageDescriptionForPixMap", (PyCFunction)Qt_MakeImageDescriptionForPixMap, 1,
- PyDoc_STR("(PixMapHandle pixmap) -> (ImageDescriptionHandle idh)")},
- {"MakeImageDescriptionForEffect", (PyCFunction)Qt_MakeImageDescriptionForEffect, 1,
- PyDoc_STR("(OSType effectType) -> (ImageDescriptionHandle idh)")},
- {"QTGetPixelSize", (PyCFunction)Qt_QTGetPixelSize, 1,
- PyDoc_STR("(OSType PixelFormat) -> (short _rv)")},
- {"QTGetPixelFormatDepthForImageDescription", (PyCFunction)Qt_QTGetPixelFormatDepthForImageDescription, 1,
- PyDoc_STR("(OSType PixelFormat) -> (short _rv)")},
- {"QTGetPixMapHandleRowBytes", (PyCFunction)Qt_QTGetPixMapHandleRowBytes, 1,
- PyDoc_STR("(PixMapHandle pm) -> (long _rv)")},
- {"QTSetPixMapHandleRowBytes", (PyCFunction)Qt_QTSetPixMapHandleRowBytes, 1,
- PyDoc_STR("(PixMapHandle pm, long rowBytes) -> None")},
- {"QTGetPixMapHandleGammaLevel", (PyCFunction)Qt_QTGetPixMapHandleGammaLevel, 1,
- PyDoc_STR("(PixMapHandle pm) -> (Fixed _rv)")},
- {"QTSetPixMapHandleGammaLevel", (PyCFunction)Qt_QTSetPixMapHandleGammaLevel, 1,
- PyDoc_STR("(PixMapHandle pm, Fixed gammaLevel) -> None")},
- {"QTGetPixMapHandleRequestedGammaLevel", (PyCFunction)Qt_QTGetPixMapHandleRequestedGammaLevel, 1,
- PyDoc_STR("(PixMapHandle pm) -> (Fixed _rv)")},
- {"QTSetPixMapHandleRequestedGammaLevel", (PyCFunction)Qt_QTSetPixMapHandleRequestedGammaLevel, 1,
- PyDoc_STR("(PixMapHandle pm, Fixed requestedGammaLevel) -> None")},
- {"CompAdd", (PyCFunction)Qt_CompAdd, 1,
- PyDoc_STR("() -> (wide src, wide dst)")},
- {"CompSub", (PyCFunction)Qt_CompSub, 1,
- PyDoc_STR("() -> (wide src, wide dst)")},
- {"CompNeg", (PyCFunction)Qt_CompNeg, 1,
- PyDoc_STR("() -> (wide dst)")},
- {"CompShift", (PyCFunction)Qt_CompShift, 1,
- PyDoc_STR("(short shift) -> (wide src)")},
- {"CompMul", (PyCFunction)Qt_CompMul, 1,
- PyDoc_STR("(long src1, long src2) -> (wide dst)")},
- {"CompDiv", (PyCFunction)Qt_CompDiv, 1,
- PyDoc_STR("(long denominator) -> (long _rv, wide numerator, long remainder)")},
- {"CompFixMul", (PyCFunction)Qt_CompFixMul, 1,
- PyDoc_STR("(Fixed fixSrc) -> (wide compSrc, wide compDst)")},
- {"CompMulDiv", (PyCFunction)Qt_CompMulDiv, 1,
- PyDoc_STR("(long mul, long divisor) -> (wide co)")},
- {"CompMulDivTrunc", (PyCFunction)Qt_CompMulDivTrunc, 1,
- PyDoc_STR("(long mul, long divisor) -> (wide co, long remainder)")},
- {"CompCompare", (PyCFunction)Qt_CompCompare, 1,
- PyDoc_STR("(wide a, wide minusb) -> (long _rv)")},
- {"CompSquareRoot", (PyCFunction)Qt_CompSquareRoot, 1,
- PyDoc_STR("(wide src) -> (unsigned long _rv)")},
- {"FixMulDiv", (PyCFunction)Qt_FixMulDiv, 1,
- PyDoc_STR("(Fixed src, Fixed mul, Fixed divisor) -> (Fixed _rv)")},
- {"UnsignedFixMulDiv", (PyCFunction)Qt_UnsignedFixMulDiv, 1,
- PyDoc_STR("(Fixed src, Fixed mul, Fixed divisor) -> (Fixed _rv)")},
- {"FixExp2", (PyCFunction)Qt_FixExp2, 1,
- PyDoc_STR("(Fixed src) -> (Fixed _rv)")},
- {"FixLog2", (PyCFunction)Qt_FixLog2, 1,
- PyDoc_STR("(Fixed src) -> (Fixed _rv)")},
- {"FixPow", (PyCFunction)Qt_FixPow, 1,
- PyDoc_STR("(Fixed base, Fixed exp) -> (Fixed _rv)")},
- {"GraphicsImportSetDataReference", (PyCFunction)Qt_GraphicsImportSetDataReference, 1,
- PyDoc_STR("(GraphicsImportComponent ci, Handle dataRef, OSType dataReType) -> (ComponentResult _rv)")},
- {"GraphicsImportGetDataReference", (PyCFunction)Qt_GraphicsImportGetDataReference, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataReType)")},
- {"GraphicsImportSetDataFile", (PyCFunction)Qt_GraphicsImportSetDataFile, 1,
- PyDoc_STR("(GraphicsImportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
- {"GraphicsImportGetDataFile", (PyCFunction)Qt_GraphicsImportGetDataFile, 1,
- PyDoc_STR("(GraphicsImportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
- {"GraphicsImportSetDataHandle", (PyCFunction)Qt_GraphicsImportSetDataHandle, 1,
- PyDoc_STR("(GraphicsImportComponent ci, Handle h) -> (ComponentResult _rv)")},
- {"GraphicsImportGetDataHandle", (PyCFunction)Qt_GraphicsImportGetDataHandle, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle h)")},
- {"GraphicsImportGetImageDescription", (PyCFunction)Qt_GraphicsImportGetImageDescription, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, ImageDescriptionHandle desc)")},
- {"GraphicsImportGetDataOffsetAndSize", (PyCFunction)Qt_GraphicsImportGetDataOffsetAndSize, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long size)")},
- {"GraphicsImportReadData", (PyCFunction)Qt_GraphicsImportReadData, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * dataPtr, unsigned long dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
- {"GraphicsImportSetClip", (PyCFunction)Qt_GraphicsImportSetClip, 1,
- PyDoc_STR("(GraphicsImportComponent ci, RgnHandle clipRgn) -> (ComponentResult _rv)")},
- {"GraphicsImportGetClip", (PyCFunction)Qt_GraphicsImportGetClip, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, RgnHandle clipRgn)")},
- {"GraphicsImportSetSourceRect", (PyCFunction)Qt_GraphicsImportSetSourceRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci, Rect sourceRect) -> (ComponentResult _rv)")},
- {"GraphicsImportGetSourceRect", (PyCFunction)Qt_GraphicsImportGetSourceRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect sourceRect)")},
- {"GraphicsImportGetNaturalBounds", (PyCFunction)Qt_GraphicsImportGetNaturalBounds, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect naturalBounds)")},
- {"GraphicsImportDraw", (PyCFunction)Qt_GraphicsImportDraw, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv)")},
- {"GraphicsImportSetGWorld", (PyCFunction)Qt_GraphicsImportSetGWorld, 1,
- PyDoc_STR("(GraphicsImportComponent ci, CGrafPtr port, GDHandle gd) -> (ComponentResult _rv)")},
- {"GraphicsImportGetGWorld", (PyCFunction)Qt_GraphicsImportGetGWorld, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, CGrafPtr port, GDHandle gd)")},
- {"GraphicsImportSetBoundsRect", (PyCFunction)Qt_GraphicsImportSetBoundsRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci, Rect bounds) -> (ComponentResult _rv)")},
- {"GraphicsImportGetBoundsRect", (PyCFunction)Qt_GraphicsImportGetBoundsRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect bounds)")},
- {"GraphicsImportSaveAsPicture", (PyCFunction)Qt_GraphicsImportSaveAsPicture, 1,
- PyDoc_STR("(GraphicsImportComponent ci, FSSpec fss, ScriptCode scriptTag) -> (ComponentResult _rv)")},
- {"GraphicsImportSetGraphicsMode", (PyCFunction)Qt_GraphicsImportSetGraphicsMode, 1,
- PyDoc_STR("(GraphicsImportComponent ci, long graphicsMode, RGBColor opColor) -> (ComponentResult _rv)")},
- {"GraphicsImportGetGraphicsMode", (PyCFunction)Qt_GraphicsImportGetGraphicsMode, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, long graphicsMode, RGBColor opColor)")},
- {"GraphicsImportSetQuality", (PyCFunction)Qt_GraphicsImportSetQuality, 1,
- PyDoc_STR("(GraphicsImportComponent ci, CodecQ quality) -> (ComponentResult _rv)")},
- {"GraphicsImportGetQuality", (PyCFunction)Qt_GraphicsImportGetQuality, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, CodecQ quality)")},
- {"GraphicsImportSaveAsQuickTimeImageFile", (PyCFunction)Qt_GraphicsImportSaveAsQuickTimeImageFile, 1,
- PyDoc_STR("(GraphicsImportComponent ci, FSSpec fss, ScriptCode scriptTag) -> (ComponentResult _rv)")},
- {"GraphicsImportSetDataReferenceOffsetAndLimit", (PyCFunction)Qt_GraphicsImportSetDataReferenceOffsetAndLimit, 1,
- PyDoc_STR("(GraphicsImportComponent ci, unsigned long offset, unsigned long limit) -> (ComponentResult _rv)")},
- {"GraphicsImportGetDataReferenceOffsetAndLimit", (PyCFunction)Qt_GraphicsImportGetDataReferenceOffsetAndLimit, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long limit)")},
- {"GraphicsImportGetAliasedDataReference", (PyCFunction)Qt_GraphicsImportGetAliasedDataReference, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
- {"GraphicsImportValidate", (PyCFunction)Qt_GraphicsImportValidate, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Boolean valid)")},
- {"GraphicsImportGetMetaData", (PyCFunction)Qt_GraphicsImportGetMetaData, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * userData) -> (ComponentResult _rv)")},
- {"GraphicsImportGetMIMETypeList", (PyCFunction)Qt_GraphicsImportGetMIMETypeList, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
- {"GraphicsImportDoesDrawAllPixels", (PyCFunction)Qt_GraphicsImportDoesDrawAllPixels, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, short drawsAllPixels)")},
- {"GraphicsImportGetAsPicture", (PyCFunction)Qt_GraphicsImportGetAsPicture, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, PicHandle picture)")},
- {"GraphicsImportExportImageFile", (PyCFunction)Qt_GraphicsImportExportImageFile, 1,
- PyDoc_STR("(GraphicsImportComponent ci, OSType fileType, OSType fileCreator, FSSpec fss, ScriptCode scriptTag) -> (ComponentResult _rv)")},
- {"GraphicsImportGetExportImageTypeList", (PyCFunction)Qt_GraphicsImportGetExportImageTypeList, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
- {"GraphicsImportGetExportSettingsAsAtomContainer", (PyCFunction)Qt_GraphicsImportGetExportSettingsAsAtomContainer, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
- {"GraphicsImportSetExportSettingsFromAtomContainer", (PyCFunction)Qt_GraphicsImportSetExportSettingsFromAtomContainer, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainer) -> (ComponentResult _rv)")},
- {"GraphicsImportGetImageCount", (PyCFunction)Qt_GraphicsImportGetImageCount, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long imageCount)")},
- {"GraphicsImportSetImageIndex", (PyCFunction)Qt_GraphicsImportSetImageIndex, 1,
- PyDoc_STR("(GraphicsImportComponent ci, unsigned long imageIndex) -> (ComponentResult _rv)")},
- {"GraphicsImportGetImageIndex", (PyCFunction)Qt_GraphicsImportGetImageIndex, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long imageIndex)")},
- {"GraphicsImportGetDataOffsetAndSize64", (PyCFunction)Qt_GraphicsImportGetDataOffsetAndSize64, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, wide offset, wide size)")},
- {"GraphicsImportReadData64", (PyCFunction)Qt_GraphicsImportReadData64, 1,
- PyDoc_STR("(GraphicsImportComponent ci, void * dataPtr, wide dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
- {"GraphicsImportSetDataReferenceOffsetAndLimit64", (PyCFunction)Qt_GraphicsImportSetDataReferenceOffsetAndLimit64, 1,
- PyDoc_STR("(GraphicsImportComponent ci, wide offset, wide limit) -> (ComponentResult _rv)")},
- {"GraphicsImportGetDataReferenceOffsetAndLimit64", (PyCFunction)Qt_GraphicsImportGetDataReferenceOffsetAndLimit64, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, wide offset, wide limit)")},
- {"GraphicsImportGetDefaultClip", (PyCFunction)Qt_GraphicsImportGetDefaultClip, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, RgnHandle defaultRgn)")},
- {"GraphicsImportGetDefaultGraphicsMode", (PyCFunction)Qt_GraphicsImportGetDefaultGraphicsMode, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, long defaultGraphicsMode, RGBColor defaultOpColor)")},
- {"GraphicsImportGetDefaultSourceRect", (PyCFunction)Qt_GraphicsImportGetDefaultSourceRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect defaultSourceRect)")},
- {"GraphicsImportGetColorSyncProfile", (PyCFunction)Qt_GraphicsImportGetColorSyncProfile, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle profile)")},
- {"GraphicsImportSetDestRect", (PyCFunction)Qt_GraphicsImportSetDestRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci, Rect destRect) -> (ComponentResult _rv)")},
- {"GraphicsImportGetDestRect", (PyCFunction)Qt_GraphicsImportGetDestRect, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect destRect)")},
- {"GraphicsImportSetFlags", (PyCFunction)Qt_GraphicsImportSetFlags, 1,
- PyDoc_STR("(GraphicsImportComponent ci, long flags) -> (ComponentResult _rv)")},
- {"GraphicsImportGetFlags", (PyCFunction)Qt_GraphicsImportGetFlags, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, long flags)")},
- {"GraphicsImportGetBaseDataOffsetAndSize64", (PyCFunction)Qt_GraphicsImportGetBaseDataOffsetAndSize64, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, wide offset, wide size)")},
- {"GraphicsImportSetImageIndexToThumbnail", (PyCFunction)Qt_GraphicsImportSetImageIndexToThumbnail, 1,
- PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv)")},
- {"GraphicsExportDoExport", (PyCFunction)Qt_GraphicsExportDoExport, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long actualSizeWritten)")},
- {"GraphicsExportCanTranscode", (PyCFunction)Qt_GraphicsExportCanTranscode, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean canTranscode)")},
- {"GraphicsExportDoTranscode", (PyCFunction)Qt_GraphicsExportDoTranscode, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv)")},
- {"GraphicsExportCanUseCompressor", (PyCFunction)Qt_GraphicsExportCanUseCompressor, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * codecSettingsAtomContainerPtr) -> (ComponentResult _rv, Boolean canUseCompressor)")},
- {"GraphicsExportDoUseCompressor", (PyCFunction)Qt_GraphicsExportDoUseCompressor, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * codecSettingsAtomContainer) -> (ComponentResult _rv, ImageDescriptionHandle outDesc)")},
- {"GraphicsExportDoStandaloneExport", (PyCFunction)Qt_GraphicsExportDoStandaloneExport, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv)")},
- {"GraphicsExportGetDefaultFileTypeAndCreator", (PyCFunction)Qt_GraphicsExportGetDefaultFileTypeAndCreator, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, OSType fileType, OSType fileCreator)")},
- {"GraphicsExportGetDefaultFileNameExtension", (PyCFunction)Qt_GraphicsExportGetDefaultFileNameExtension, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, OSType fileNameExtension)")},
- {"GraphicsExportGetMIMETypeList", (PyCFunction)Qt_GraphicsExportGetMIMETypeList, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
- {"GraphicsExportSetSettingsFromAtomContainer", (PyCFunction)Qt_GraphicsExportSetSettingsFromAtomContainer, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * qtAtomContainer) -> (ComponentResult _rv)")},
- {"GraphicsExportGetSettingsAsAtomContainer", (PyCFunction)Qt_GraphicsExportGetSettingsAsAtomContainer, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
- {"GraphicsExportGetSettingsAsText", (PyCFunction)Qt_GraphicsExportGetSettingsAsText, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle theText)")},
- {"GraphicsExportSetDontRecompress", (PyCFunction)Qt_GraphicsExportSetDontRecompress, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Boolean dontRecompress) -> (ComponentResult _rv)")},
- {"GraphicsExportGetDontRecompress", (PyCFunction)Qt_GraphicsExportGetDontRecompress, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean dontRecompress)")},
- {"GraphicsExportSetInterlaceStyle", (PyCFunction)Qt_GraphicsExportSetInterlaceStyle, 1,
- PyDoc_STR("(GraphicsExportComponent ci, unsigned long interlaceStyle) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInterlaceStyle", (PyCFunction)Qt_GraphicsExportGetInterlaceStyle, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long interlaceStyle)")},
- {"GraphicsExportSetMetaData", (PyCFunction)Qt_GraphicsExportSetMetaData, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * userData) -> (ComponentResult _rv)")},
- {"GraphicsExportGetMetaData", (PyCFunction)Qt_GraphicsExportGetMetaData, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * userData) -> (ComponentResult _rv)")},
- {"GraphicsExportSetTargetDataSize", (PyCFunction)Qt_GraphicsExportSetTargetDataSize, 1,
- PyDoc_STR("(GraphicsExportComponent ci, unsigned long targetDataSize) -> (ComponentResult _rv)")},
- {"GraphicsExportGetTargetDataSize", (PyCFunction)Qt_GraphicsExportGetTargetDataSize, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long targetDataSize)")},
- {"GraphicsExportSetCompressionMethod", (PyCFunction)Qt_GraphicsExportSetCompressionMethod, 1,
- PyDoc_STR("(GraphicsExportComponent ci, long compressionMethod) -> (ComponentResult _rv)")},
- {"GraphicsExportGetCompressionMethod", (PyCFunction)Qt_GraphicsExportGetCompressionMethod, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, long compressionMethod)")},
- {"GraphicsExportSetCompressionQuality", (PyCFunction)Qt_GraphicsExportSetCompressionQuality, 1,
- PyDoc_STR("(GraphicsExportComponent ci, CodecQ spatialQuality) -> (ComponentResult _rv)")},
- {"GraphicsExportGetCompressionQuality", (PyCFunction)Qt_GraphicsExportGetCompressionQuality, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, CodecQ spatialQuality)")},
- {"GraphicsExportSetResolution", (PyCFunction)Qt_GraphicsExportSetResolution, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Fixed horizontalResolution, Fixed verticalResolution) -> (ComponentResult _rv)")},
- {"GraphicsExportGetResolution", (PyCFunction)Qt_GraphicsExportGetResolution, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Fixed horizontalResolution, Fixed verticalResolution)")},
- {"GraphicsExportSetDepth", (PyCFunction)Qt_GraphicsExportSetDepth, 1,
- PyDoc_STR("(GraphicsExportComponent ci, long depth) -> (ComponentResult _rv)")},
- {"GraphicsExportGetDepth", (PyCFunction)Qt_GraphicsExportGetDepth, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, long depth)")},
- {"GraphicsExportSetColorSyncProfile", (PyCFunction)Qt_GraphicsExportSetColorSyncProfile, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Handle colorSyncProfile) -> (ComponentResult _rv)")},
- {"GraphicsExportGetColorSyncProfile", (PyCFunction)Qt_GraphicsExportGetColorSyncProfile, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle colorSyncProfile)")},
- {"GraphicsExportSetInputDataReference", (PyCFunction)Qt_GraphicsExportSetInputDataReference, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Handle dataRef, OSType dataRefType, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputDataReference", (PyCFunction)Qt_GraphicsExportGetInputDataReference, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
- {"GraphicsExportSetInputFile", (PyCFunction)Qt_GraphicsExportSetInputFile, 1,
- PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputFile", (PyCFunction)Qt_GraphicsExportGetInputFile, 1,
- PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
- {"GraphicsExportSetInputHandle", (PyCFunction)Qt_GraphicsExportSetInputHandle, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Handle h, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputHandle", (PyCFunction)Qt_GraphicsExportGetInputHandle, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle h)")},
- {"GraphicsExportSetInputPtr", (PyCFunction)Qt_GraphicsExportSetInputPtr, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Ptr p, unsigned long size, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
- {"GraphicsExportSetInputGraphicsImporter", (PyCFunction)Qt_GraphicsExportSetInputGraphicsImporter, 1,
- PyDoc_STR("(GraphicsExportComponent ci, GraphicsImportComponent grip) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputGraphicsImporter", (PyCFunction)Qt_GraphicsExportGetInputGraphicsImporter, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, GraphicsImportComponent grip)")},
- {"GraphicsExportSetInputPicture", (PyCFunction)Qt_GraphicsExportSetInputPicture, 1,
- PyDoc_STR("(GraphicsExportComponent ci, PicHandle picture) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputPicture", (PyCFunction)Qt_GraphicsExportGetInputPicture, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, PicHandle picture)")},
- {"GraphicsExportSetInputGWorld", (PyCFunction)Qt_GraphicsExportSetInputGWorld, 1,
- PyDoc_STR("(GraphicsExportComponent ci, GWorldPtr gworld) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputGWorld", (PyCFunction)Qt_GraphicsExportGetInputGWorld, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, GWorldPtr gworld)")},
- {"GraphicsExportSetInputPixmap", (PyCFunction)Qt_GraphicsExportSetInputPixmap, 1,
- PyDoc_STR("(GraphicsExportComponent ci, PixMapHandle pixmap) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputPixmap", (PyCFunction)Qt_GraphicsExportGetInputPixmap, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, PixMapHandle pixmap)")},
- {"GraphicsExportSetInputOffsetAndLimit", (PyCFunction)Qt_GraphicsExportSetInputOffsetAndLimit, 1,
- PyDoc_STR("(GraphicsExportComponent ci, unsigned long offset, unsigned long limit) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputOffsetAndLimit", (PyCFunction)Qt_GraphicsExportGetInputOffsetAndLimit, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long limit)")},
- {"GraphicsExportMayExporterReadInputData", (PyCFunction)Qt_GraphicsExportMayExporterReadInputData, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean mayReadInputData)")},
- {"GraphicsExportGetInputDataSize", (PyCFunction)Qt_GraphicsExportGetInputDataSize, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long size)")},
- {"GraphicsExportReadInputData", (PyCFunction)Qt_GraphicsExportReadInputData, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * dataPtr, unsigned long dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
- {"GraphicsExportGetInputImageDescription", (PyCFunction)Qt_GraphicsExportGetInputImageDescription, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, ImageDescriptionHandle desc)")},
- {"GraphicsExportGetInputImageDimensions", (PyCFunction)Qt_GraphicsExportGetInputImageDimensions, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Rect dimensions)")},
- {"GraphicsExportGetInputImageDepth", (PyCFunction)Qt_GraphicsExportGetInputImageDepth, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, long inputDepth)")},
- {"GraphicsExportDrawInputImage", (PyCFunction)Qt_GraphicsExportDrawInputImage, 1,
- PyDoc_STR("(GraphicsExportComponent ci, CGrafPtr gw, GDHandle gd, Rect srcRect, Rect dstRect) -> (ComponentResult _rv)")},
- {"GraphicsExportSetOutputDataReference", (PyCFunction)Qt_GraphicsExportSetOutputDataReference, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Handle dataRef, OSType dataRefType) -> (ComponentResult _rv)")},
- {"GraphicsExportGetOutputDataReference", (PyCFunction)Qt_GraphicsExportGetOutputDataReference, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
- {"GraphicsExportSetOutputFile", (PyCFunction)Qt_GraphicsExportSetOutputFile, 1,
- PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
- {"GraphicsExportGetOutputFile", (PyCFunction)Qt_GraphicsExportGetOutputFile, 1,
- PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
- {"GraphicsExportSetOutputHandle", (PyCFunction)Qt_GraphicsExportSetOutputHandle, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Handle h) -> (ComponentResult _rv)")},
- {"GraphicsExportGetOutputHandle", (PyCFunction)Qt_GraphicsExportGetOutputHandle, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle h)")},
- {"GraphicsExportSetOutputOffsetAndMaxSize", (PyCFunction)Qt_GraphicsExportSetOutputOffsetAndMaxSize, 1,
- PyDoc_STR("(GraphicsExportComponent ci, unsigned long offset, unsigned long maxSize, Boolean truncateFile) -> (ComponentResult _rv)")},
- {"GraphicsExportGetOutputOffsetAndMaxSize", (PyCFunction)Qt_GraphicsExportGetOutputOffsetAndMaxSize, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long maxSize, Boolean truncateFile)")},
- {"GraphicsExportSetOutputFileTypeAndCreator", (PyCFunction)Qt_GraphicsExportSetOutputFileTypeAndCreator, 1,
- PyDoc_STR("(GraphicsExportComponent ci, OSType fileType, OSType fileCreator) -> (ComponentResult _rv)")},
- {"GraphicsExportGetOutputFileTypeAndCreator", (PyCFunction)Qt_GraphicsExportGetOutputFileTypeAndCreator, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, OSType fileType, OSType fileCreator)")},
- {"GraphicsExportSetOutputMark", (PyCFunction)Qt_GraphicsExportSetOutputMark, 1,
- PyDoc_STR("(GraphicsExportComponent ci, unsigned long mark) -> (ComponentResult _rv)")},
- {"GraphicsExportGetOutputMark", (PyCFunction)Qt_GraphicsExportGetOutputMark, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long mark)")},
- {"GraphicsExportReadOutputData", (PyCFunction)Qt_GraphicsExportReadOutputData, 1,
- PyDoc_STR("(GraphicsExportComponent ci, void * dataPtr, unsigned long dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
- {"GraphicsExportSetThumbnailEnabled", (PyCFunction)Qt_GraphicsExportSetThumbnailEnabled, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Boolean enableThumbnail, long maxThumbnailWidth, long maxThumbnailHeight) -> (ComponentResult _rv)")},
- {"GraphicsExportGetThumbnailEnabled", (PyCFunction)Qt_GraphicsExportGetThumbnailEnabled, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean thumbnailEnabled, long maxThumbnailWidth, long maxThumbnailHeight)")},
- {"GraphicsExportSetExifEnabled", (PyCFunction)Qt_GraphicsExportSetExifEnabled, 1,
- PyDoc_STR("(GraphicsExportComponent ci, Boolean enableExif) -> (ComponentResult _rv)")},
- {"GraphicsExportGetExifEnabled", (PyCFunction)Qt_GraphicsExportGetExifEnabled, 1,
- PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean exifEnabled)")},
- {"ImageTranscoderBeginSequence", (PyCFunction)Qt_ImageTranscoderBeginSequence, 1,
- PyDoc_STR("(ImageTranscoderComponent itc, ImageDescriptionHandle srcDesc, void * data, long dataSize) -> (ComponentResult _rv, ImageDescriptionHandle dstDesc)")},
- {"ImageTranscoderDisposeData", (PyCFunction)Qt_ImageTranscoderDisposeData, 1,
- PyDoc_STR("(ImageTranscoderComponent itc, void * dstData) -> (ComponentResult _rv)")},
- {"ImageTranscoderEndSequence", (PyCFunction)Qt_ImageTranscoderEndSequence, 1,
- PyDoc_STR("(ImageTranscoderComponent itc) -> (ComponentResult _rv)")},
- {"ClockGetTime", (PyCFunction)Qt_ClockGetTime, 1,
- PyDoc_STR("(ComponentInstance aClock) -> (ComponentResult _rv, TimeRecord out)")},
- {"ClockSetTimeBase", (PyCFunction)Qt_ClockSetTimeBase, 1,
- PyDoc_STR("(ComponentInstance aClock, TimeBase tb) -> (ComponentResult _rv)")},
- {"ClockGetRate", (PyCFunction)Qt_ClockGetRate, 1,
- PyDoc_STR("(ComponentInstance aClock) -> (ComponentResult _rv, Fixed rate)")},
- {"SCPositionRect", (PyCFunction)Qt_SCPositionRect, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, Rect rp, Point where)")},
- {"SCPositionDialog", (PyCFunction)Qt_SCPositionDialog, 1,
- PyDoc_STR("(ComponentInstance ci, short id) -> (ComponentResult _rv, Point where)")},
- {"SCSetTestImagePictHandle", (PyCFunction)Qt_SCSetTestImagePictHandle, 1,
- PyDoc_STR("(ComponentInstance ci, PicHandle testPict, short testFlags) -> (ComponentResult _rv, Rect testRect)")},
- {"SCSetTestImagePictFile", (PyCFunction)Qt_SCSetTestImagePictFile, 1,
- PyDoc_STR("(ComponentInstance ci, short testFileRef, short testFlags) -> (ComponentResult _rv, Rect testRect)")},
- {"SCSetTestImagePixMap", (PyCFunction)Qt_SCSetTestImagePixMap, 1,
- PyDoc_STR("(ComponentInstance ci, PixMapHandle testPixMap, short testFlags) -> (ComponentResult _rv, Rect testRect)")},
- {"SCGetBestDeviceRect", (PyCFunction)Qt_SCGetBestDeviceRect, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, Rect r)")},
- {"SCRequestImageSettings", (PyCFunction)Qt_SCRequestImageSettings, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
- {"SCCompressImage", (PyCFunction)Qt_SCCompressImage, 1,
- PyDoc_STR("(ComponentInstance ci, PixMapHandle src, Rect srcRect) -> (ComponentResult _rv, ImageDescriptionHandle desc, Handle data)")},
- {"SCCompressPicture", (PyCFunction)Qt_SCCompressPicture, 1,
- PyDoc_STR("(ComponentInstance ci, PicHandle srcPicture, PicHandle dstPicture) -> (ComponentResult _rv)")},
- {"SCCompressPictureFile", (PyCFunction)Qt_SCCompressPictureFile, 1,
- PyDoc_STR("(ComponentInstance ci, short srcRefNum, short dstRefNum) -> (ComponentResult _rv)")},
- {"SCRequestSequenceSettings", (PyCFunction)Qt_SCRequestSequenceSettings, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
- {"SCCompressSequenceBegin", (PyCFunction)Qt_SCCompressSequenceBegin, 1,
- PyDoc_STR("(ComponentInstance ci, PixMapHandle src, Rect srcRect) -> (ComponentResult _rv, ImageDescriptionHandle desc)")},
- {"SCCompressSequenceFrame", (PyCFunction)Qt_SCCompressSequenceFrame, 1,
- PyDoc_STR("(ComponentInstance ci, PixMapHandle src, Rect srcRect) -> (ComponentResult _rv, Handle data, long dataSize, short notSyncFlag)")},
- {"SCCompressSequenceEnd", (PyCFunction)Qt_SCCompressSequenceEnd, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
- {"SCDefaultPictHandleSettings", (PyCFunction)Qt_SCDefaultPictHandleSettings, 1,
- PyDoc_STR("(ComponentInstance ci, PicHandle srcPicture, short motion) -> (ComponentResult _rv)")},
- {"SCDefaultPictFileSettings", (PyCFunction)Qt_SCDefaultPictFileSettings, 1,
- PyDoc_STR("(ComponentInstance ci, short srcRef, short motion) -> (ComponentResult _rv)")},
- {"SCDefaultPixMapSettings", (PyCFunction)Qt_SCDefaultPixMapSettings, 1,
- PyDoc_STR("(ComponentInstance ci, PixMapHandle src, short motion) -> (ComponentResult _rv)")},
- {"SCGetInfo", (PyCFunction)Qt_SCGetInfo, 1,
- PyDoc_STR("(ComponentInstance ci, OSType infoType, void * info) -> (ComponentResult _rv)")},
- {"SCSetInfo", (PyCFunction)Qt_SCSetInfo, 1,
- PyDoc_STR("(ComponentInstance ci, OSType infoType, void * info) -> (ComponentResult _rv)")},
- {"SCSetCompressFlags", (PyCFunction)Qt_SCSetCompressFlags, 1,
- PyDoc_STR("(ComponentInstance ci, long flags) -> (ComponentResult _rv)")},
- {"SCGetCompressFlags", (PyCFunction)Qt_SCGetCompressFlags, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, long flags)")},
- {"SCGetSettingsAsText", (PyCFunction)Qt_SCGetSettingsAsText, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, Handle text)")},
- {"SCAsyncIdle", (PyCFunction)Qt_SCAsyncIdle, 1,
- PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
- {"TweenerReset", (PyCFunction)Qt_TweenerReset, 1,
- PyDoc_STR("(TweenerComponent tc) -> (ComponentResult _rv)")},
- {"TCGetSourceRef", (PyCFunction)Qt_TCGetSourceRef, 1,
- PyDoc_STR("(MediaHandler mh, TimeCodeDescriptionHandle tcdH) -> (HandlerError _rv, UserData srefH)")},
- {"TCSetSourceRef", (PyCFunction)Qt_TCSetSourceRef, 1,
- PyDoc_STR("(MediaHandler mh, TimeCodeDescriptionHandle tcdH, UserData srefH) -> (HandlerError _rv)")},
- {"TCSetTimeCodeFlags", (PyCFunction)Qt_TCSetTimeCodeFlags, 1,
- PyDoc_STR("(MediaHandler mh, long flags, long flagsMask) -> (HandlerError _rv)")},
- {"TCGetTimeCodeFlags", (PyCFunction)Qt_TCGetTimeCodeFlags, 1,
- PyDoc_STR("(MediaHandler mh) -> (HandlerError _rv, long flags)")},
- {"MovieImportHandle", (PyCFunction)Qt_MovieImportHandle, 1,
- PyDoc_STR("(MovieImportComponent ci, Handle dataH, Movie theMovie, Track targetTrack, TimeValue atTime, long inFlags) -> (ComponentResult _rv, Track usedTrack, TimeValue addedDuration, long outFlags)")},
- {"MovieImportFile", (PyCFunction)Qt_MovieImportFile, 1,
- PyDoc_STR("(MovieImportComponent ci, FSSpec theFile, Movie theMovie, Track targetTrack, TimeValue atTime, long inFlags) -> (ComponentResult _rv, Track usedTrack, TimeValue addedDuration, long outFlags)")},
- {"MovieImportSetSampleDuration", (PyCFunction)Qt_MovieImportSetSampleDuration, 1,
- PyDoc_STR("(MovieImportComponent ci, TimeValue duration, TimeScale scale) -> (ComponentResult _rv)")},
- {"MovieImportSetSampleDescription", (PyCFunction)Qt_MovieImportSetSampleDescription, 1,
- PyDoc_STR("(MovieImportComponent ci, SampleDescriptionHandle desc, OSType mediaType) -> (ComponentResult _rv)")},
- {"MovieImportSetMediaFile", (PyCFunction)Qt_MovieImportSetMediaFile, 1,
- PyDoc_STR("(MovieImportComponent ci, AliasHandle alias) -> (ComponentResult _rv)")},
- {"MovieImportSetDimensions", (PyCFunction)Qt_MovieImportSetDimensions, 1,
- PyDoc_STR("(MovieImportComponent ci, Fixed width, Fixed height) -> (ComponentResult _rv)")},
- {"MovieImportSetChunkSize", (PyCFunction)Qt_MovieImportSetChunkSize, 1,
- PyDoc_STR("(MovieImportComponent ci, long chunkSize) -> (ComponentResult _rv)")},
- {"MovieImportSetAuxiliaryData", (PyCFunction)Qt_MovieImportSetAuxiliaryData, 1,
- PyDoc_STR("(MovieImportComponent ci, Handle data, OSType handleType) -> (ComponentResult _rv)")},
- {"MovieImportSetFromScrap", (PyCFunction)Qt_MovieImportSetFromScrap, 1,
- PyDoc_STR("(MovieImportComponent ci, Boolean fromScrap) -> (ComponentResult _rv)")},
- {"MovieImportDoUserDialog", (PyCFunction)Qt_MovieImportDoUserDialog, 1,
- PyDoc_STR("(MovieImportComponent ci, FSSpec theFile, Handle theData) -> (ComponentResult _rv, Boolean canceled)")},
- {"MovieImportSetDuration", (PyCFunction)Qt_MovieImportSetDuration, 1,
- PyDoc_STR("(MovieImportComponent ci, TimeValue duration) -> (ComponentResult _rv)")},
- {"MovieImportGetAuxiliaryDataType", (PyCFunction)Qt_MovieImportGetAuxiliaryDataType, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, OSType auxType)")},
- {"MovieImportValidate", (PyCFunction)Qt_MovieImportValidate, 1,
- PyDoc_STR("(MovieImportComponent ci, FSSpec theFile, Handle theData) -> (ComponentResult _rv, Boolean valid)")},
- {"MovieImportGetFileType", (PyCFunction)Qt_MovieImportGetFileType, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, OSType fileType)")},
- {"MovieImportDataRef", (PyCFunction)Qt_MovieImportDataRef, 1,
- PyDoc_STR("(MovieImportComponent ci, Handle dataRef, OSType dataRefType, Movie theMovie, Track targetTrack, TimeValue atTime, long inFlags) -> (ComponentResult _rv, Track usedTrack, TimeValue addedDuration, long outFlags)")},
- {"MovieImportGetSampleDescription", (PyCFunction)Qt_MovieImportGetSampleDescription, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, SampleDescriptionHandle desc, OSType mediaType)")},
- {"MovieImportSetOffsetAndLimit", (PyCFunction)Qt_MovieImportSetOffsetAndLimit, 1,
- PyDoc_STR("(MovieImportComponent ci, unsigned long offset, unsigned long limit) -> (ComponentResult _rv)")},
- {"MovieImportSetOffsetAndLimit64", (PyCFunction)Qt_MovieImportSetOffsetAndLimit64, 1,
- PyDoc_STR("(MovieImportComponent ci, wide offset, wide limit) -> (ComponentResult _rv)")},
- {"MovieImportIdle", (PyCFunction)Qt_MovieImportIdle, 1,
- PyDoc_STR("(MovieImportComponent ci, long inFlags) -> (ComponentResult _rv, long outFlags)")},
- {"MovieImportValidateDataRef", (PyCFunction)Qt_MovieImportValidateDataRef, 1,
- PyDoc_STR("(MovieImportComponent ci, Handle dataRef, OSType dataRefType) -> (ComponentResult _rv, UInt8 valid)")},
- {"MovieImportGetLoadState", (PyCFunction)Qt_MovieImportGetLoadState, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, long importerLoadState)")},
- {"MovieImportGetMaxLoadedTime", (PyCFunction)Qt_MovieImportGetMaxLoadedTime, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, TimeValue time)")},
- {"MovieImportEstimateCompletionTime", (PyCFunction)Qt_MovieImportEstimateCompletionTime, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, TimeRecord time)")},
- {"MovieImportSetDontBlock", (PyCFunction)Qt_MovieImportSetDontBlock, 1,
- PyDoc_STR("(MovieImportComponent ci, Boolean dontBlock) -> (ComponentResult _rv)")},
- {"MovieImportGetDontBlock", (PyCFunction)Qt_MovieImportGetDontBlock, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, Boolean willBlock)")},
- {"MovieImportSetIdleManager", (PyCFunction)Qt_MovieImportSetIdleManager, 1,
- PyDoc_STR("(MovieImportComponent ci, IdleManager im) -> (ComponentResult _rv)")},
- {"MovieImportSetNewMovieFlags", (PyCFunction)Qt_MovieImportSetNewMovieFlags, 1,
- PyDoc_STR("(MovieImportComponent ci, long newMovieFlags) -> (ComponentResult _rv)")},
- {"MovieImportGetDestinationMediaType", (PyCFunction)Qt_MovieImportGetDestinationMediaType, 1,
- PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, OSType mediaType)")},
- {"MovieExportToHandle", (PyCFunction)Qt_MovieExportToHandle, 1,
- PyDoc_STR("(MovieExportComponent ci, Handle dataH, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv)")},
- {"MovieExportToFile", (PyCFunction)Qt_MovieExportToFile, 1,
- PyDoc_STR("(MovieExportComponent ci, FSSpec theFile, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv)")},
- {"MovieExportGetAuxiliaryData", (PyCFunction)Qt_MovieExportGetAuxiliaryData, 1,
- PyDoc_STR("(MovieExportComponent ci, Handle dataH) -> (ComponentResult _rv, OSType handleType)")},
- {"MovieExportSetSampleDescription", (PyCFunction)Qt_MovieExportSetSampleDescription, 1,
- PyDoc_STR("(MovieExportComponent ci, SampleDescriptionHandle desc, OSType mediaType) -> (ComponentResult _rv)")},
- {"MovieExportDoUserDialog", (PyCFunction)Qt_MovieExportDoUserDialog, 1,
- PyDoc_STR("(MovieExportComponent ci, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv, Boolean canceled)")},
- {"MovieExportGetCreatorType", (PyCFunction)Qt_MovieExportGetCreatorType, 1,
- PyDoc_STR("(MovieExportComponent ci) -> (ComponentResult _rv, OSType creator)")},
- {"MovieExportToDataRef", (PyCFunction)Qt_MovieExportToDataRef, 1,
- PyDoc_STR("(MovieExportComponent ci, Handle dataRef, OSType dataRefType, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv)")},
- {"MovieExportFromProceduresToDataRef", (PyCFunction)Qt_MovieExportFromProceduresToDataRef, 1,
- PyDoc_STR("(MovieExportComponent ci, Handle dataRef, OSType dataRefType) -> (ComponentResult _rv)")},
- {"MovieExportValidate", (PyCFunction)Qt_MovieExportValidate, 1,
- PyDoc_STR("(MovieExportComponent ci, Movie theMovie, Track onlyThisTrack) -> (ComponentResult _rv, Boolean valid)")},
- {"MovieExportGetFileNameExtension", (PyCFunction)Qt_MovieExportGetFileNameExtension, 1,
- PyDoc_STR("(MovieExportComponent ci) -> (ComponentResult _rv, OSType extension)")},
- {"MovieExportGetShortFileTypeString", (PyCFunction)Qt_MovieExportGetShortFileTypeString, 1,
- PyDoc_STR("(MovieExportComponent ci, Str255 typeString) -> (ComponentResult _rv)")},
- {"MovieExportGetSourceMediaType", (PyCFunction)Qt_MovieExportGetSourceMediaType, 1,
- PyDoc_STR("(MovieExportComponent ci) -> (ComponentResult _rv, OSType mediaType)")},
- {"TextExportGetTimeFraction", (PyCFunction)Qt_TextExportGetTimeFraction, 1,
- PyDoc_STR("(TextExportComponent ci) -> (ComponentResult _rv, long movieTimeFraction)")},
- {"TextExportSetTimeFraction", (PyCFunction)Qt_TextExportSetTimeFraction, 1,
- PyDoc_STR("(TextExportComponent ci, long movieTimeFraction) -> (ComponentResult _rv)")},
- {"TextExportGetSettings", (PyCFunction)Qt_TextExportGetSettings, 1,
- PyDoc_STR("(TextExportComponent ci) -> (ComponentResult _rv, long setting)")},
- {"TextExportSetSettings", (PyCFunction)Qt_TextExportSetSettings, 1,
- PyDoc_STR("(TextExportComponent ci, long setting) -> (ComponentResult _rv)")},
- {"MIDIImportGetSettings", (PyCFunction)Qt_MIDIImportGetSettings, 1,
- PyDoc_STR("(TextExportComponent ci) -> (ComponentResult _rv, long setting)")},
- {"MIDIImportSetSettings", (PyCFunction)Qt_MIDIImportSetSettings, 1,
- PyDoc_STR("(TextExportComponent ci, long setting) -> (ComponentResult _rv)")},
- {"GraphicsImageImportSetSequenceEnabled", (PyCFunction)Qt_GraphicsImageImportSetSequenceEnabled, 1,
- PyDoc_STR("(GraphicImageMovieImportComponent ci, Boolean enable) -> (ComponentResult _rv)")},
- {"GraphicsImageImportGetSequenceEnabled", (PyCFunction)Qt_GraphicsImageImportGetSequenceEnabled, 1,
- PyDoc_STR("(GraphicImageMovieImportComponent ci) -> (ComponentResult _rv, Boolean enable)")},
- {"PreviewShowData", (PyCFunction)Qt_PreviewShowData, 1,
- PyDoc_STR("(pnotComponent p, OSType dataType, Handle data, Rect inHere) -> (ComponentResult _rv)")},
- {"PreviewMakePreviewReference", (PyCFunction)Qt_PreviewMakePreviewReference, 1,
- PyDoc_STR("(pnotComponent p, FSSpec sourceFile) -> (ComponentResult _rv, OSType previewType, short resID)")},
- {"PreviewEvent", (PyCFunction)Qt_PreviewEvent, 1,
- PyDoc_STR("(pnotComponent p) -> (ComponentResult _rv, EventRecord e, Boolean handledEvent)")},
- {"DataCodecDecompress", (PyCFunction)Qt_DataCodecDecompress, 1,
- PyDoc_STR("(DataCodecComponent dc, void * srcData, UInt32 srcSize, void * dstData, UInt32 dstBufferSize) -> (ComponentResult _rv)")},
- {"DataCodecGetCompressBufferSize", (PyCFunction)Qt_DataCodecGetCompressBufferSize, 1,
- PyDoc_STR("(DataCodecComponent dc, UInt32 srcSize) -> (ComponentResult _rv, UInt32 dstSize)")},
- {"DataCodecCompress", (PyCFunction)Qt_DataCodecCompress, 1,
- PyDoc_STR("(DataCodecComponent dc, void * srcData, UInt32 srcSize, void * dstData, UInt32 dstBufferSize) -> (ComponentResult _rv, UInt32 actualDstSize, UInt32 decompressSlop)")},
- {"DataCodecBeginInterruptSafe", (PyCFunction)Qt_DataCodecBeginInterruptSafe, 1,
- PyDoc_STR("(DataCodecComponent dc, unsigned long maxSrcSize) -> (ComponentResult _rv)")},
- {"DataCodecEndInterruptSafe", (PyCFunction)Qt_DataCodecEndInterruptSafe, 1,
- PyDoc_STR("(DataCodecComponent dc) -> (ComponentResult _rv)")},
- {"DataHGetData", (PyCFunction)Qt_DataHGetData, 1,
- PyDoc_STR("(DataHandler dh, Handle h, long hOffset, long offset, long size) -> (ComponentResult _rv)")},
- {"DataHPutData", (PyCFunction)Qt_DataHPutData, 1,
- PyDoc_STR("(DataHandler dh, Handle h, long hOffset, long size) -> (ComponentResult _rv, long offset)")},
- {"DataHFlushData", (PyCFunction)Qt_DataHFlushData, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHOpenForWrite", (PyCFunction)Qt_DataHOpenForWrite, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHCloseForWrite", (PyCFunction)Qt_DataHCloseForWrite, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHOpenForRead", (PyCFunction)Qt_DataHOpenForRead, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHCloseForRead", (PyCFunction)Qt_DataHCloseForRead, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHSetDataRef", (PyCFunction)Qt_DataHSetDataRef, 1,
- PyDoc_STR("(DataHandler dh, Handle dataRef) -> (ComponentResult _rv)")},
- {"DataHGetDataRef", (PyCFunction)Qt_DataHGetDataRef, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Handle dataRef)")},
- {"DataHCompareDataRef", (PyCFunction)Qt_DataHCompareDataRef, 1,
- PyDoc_STR("(DataHandler dh, Handle dataRef) -> (ComponentResult _rv, Boolean equal)")},
- {"DataHTask", (PyCFunction)Qt_DataHTask, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHFinishData", (PyCFunction)Qt_DataHFinishData, 1,
- PyDoc_STR("(DataHandler dh, Ptr PlaceToPutDataPtr, Boolean Cancel) -> (ComponentResult _rv)")},
- {"DataHFlushCache", (PyCFunction)Qt_DataHFlushCache, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHResolveDataRef", (PyCFunction)Qt_DataHResolveDataRef, 1,
- PyDoc_STR("(DataHandler dh, Handle theDataRef, Boolean userInterfaceAllowed) -> (ComponentResult _rv, Boolean wasChanged)")},
- {"DataHGetFileSize", (PyCFunction)Qt_DataHGetFileSize, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long fileSize)")},
- {"DataHCanUseDataRef", (PyCFunction)Qt_DataHCanUseDataRef, 1,
- PyDoc_STR("(DataHandler dh, Handle dataRef) -> (ComponentResult _rv, long useFlags)")},
- {"DataHPreextend", (PyCFunction)Qt_DataHPreextend, 1,
- PyDoc_STR("(DataHandler dh, unsigned long maxToAdd) -> (ComponentResult _rv, unsigned long spaceAdded)")},
- {"DataHSetFileSize", (PyCFunction)Qt_DataHSetFileSize, 1,
- PyDoc_STR("(DataHandler dh, long fileSize) -> (ComponentResult _rv)")},
- {"DataHGetFreeSpace", (PyCFunction)Qt_DataHGetFreeSpace, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, unsigned long freeSize)")},
- {"DataHCreateFile", (PyCFunction)Qt_DataHCreateFile, 1,
- PyDoc_STR("(DataHandler dh, OSType creator, Boolean deleteExisting) -> (ComponentResult _rv)")},
- {"DataHGetPreferredBlockSize", (PyCFunction)Qt_DataHGetPreferredBlockSize, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long blockSize)")},
- {"DataHGetDeviceIndex", (PyCFunction)Qt_DataHGetDeviceIndex, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long deviceIndex)")},
- {"DataHIsStreamingDataHandler", (PyCFunction)Qt_DataHIsStreamingDataHandler, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Boolean yes)")},
- {"DataHGetDataInBuffer", (PyCFunction)Qt_DataHGetDataInBuffer, 1,
- PyDoc_STR("(DataHandler dh, long startOffset) -> (ComponentResult _rv, long size)")},
- {"DataHGetScheduleAheadTime", (PyCFunction)Qt_DataHGetScheduleAheadTime, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long millisecs)")},
- {"DataHSetCacheSizeLimit", (PyCFunction)Qt_DataHSetCacheSizeLimit, 1,
- PyDoc_STR("(DataHandler dh, Size cacheSizeLimit) -> (ComponentResult _rv)")},
- {"DataHGetCacheSizeLimit", (PyCFunction)Qt_DataHGetCacheSizeLimit, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Size cacheSizeLimit)")},
- {"DataHGetMovie", (PyCFunction)Qt_DataHGetMovie, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Movie theMovie, short id)")},
- {"DataHAddMovie", (PyCFunction)Qt_DataHAddMovie, 1,
- PyDoc_STR("(DataHandler dh, Movie theMovie) -> (ComponentResult _rv, short id)")},
- {"DataHUpdateMovie", (PyCFunction)Qt_DataHUpdateMovie, 1,
- PyDoc_STR("(DataHandler dh, Movie theMovie, short id) -> (ComponentResult _rv)")},
- {"DataHDoesBuffer", (PyCFunction)Qt_DataHDoesBuffer, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Boolean buffersReads, Boolean buffersWrites)")},
- {"DataHGetFileName", (PyCFunction)Qt_DataHGetFileName, 1,
- PyDoc_STR("(DataHandler dh, Str255 str) -> (ComponentResult _rv)")},
- {"DataHGetAvailableFileSize", (PyCFunction)Qt_DataHGetAvailableFileSize, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long fileSize)")},
- {"DataHGetMacOSFileType", (PyCFunction)Qt_DataHGetMacOSFileType, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, OSType fileType)")},
- {"DataHGetMIMEType", (PyCFunction)Qt_DataHGetMIMEType, 1,
- PyDoc_STR("(DataHandler dh, Str255 mimeType) -> (ComponentResult _rv)")},
- {"DataHSetDataRefWithAnchor", (PyCFunction)Qt_DataHSetDataRefWithAnchor, 1,
- PyDoc_STR("(DataHandler dh, Handle anchorDataRef, OSType dataRefType, Handle dataRef) -> (ComponentResult _rv)")},
- {"DataHGetDataRefWithAnchor", (PyCFunction)Qt_DataHGetDataRefWithAnchor, 1,
- PyDoc_STR("(DataHandler dh, Handle anchorDataRef, OSType dataRefType) -> (ComponentResult _rv, Handle dataRef)")},
- {"DataHSetMacOSFileType", (PyCFunction)Qt_DataHSetMacOSFileType, 1,
- PyDoc_STR("(DataHandler dh, OSType fileType) -> (ComponentResult _rv)")},
- {"DataHSetTimeBase", (PyCFunction)Qt_DataHSetTimeBase, 1,
- PyDoc_STR("(DataHandler dh, TimeBase tb) -> (ComponentResult _rv)")},
- {"DataHGetInfoFlags", (PyCFunction)Qt_DataHGetInfoFlags, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, UInt32 flags)")},
- {"DataHGetFileSize64", (PyCFunction)Qt_DataHGetFileSize64, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, wide fileSize)")},
- {"DataHPreextend64", (PyCFunction)Qt_DataHPreextend64, 1,
- PyDoc_STR("(DataHandler dh, wide maxToAdd) -> (ComponentResult _rv, wide spaceAdded)")},
- {"DataHSetFileSize64", (PyCFunction)Qt_DataHSetFileSize64, 1,
- PyDoc_STR("(DataHandler dh, wide fileSize) -> (ComponentResult _rv)")},
- {"DataHGetFreeSpace64", (PyCFunction)Qt_DataHGetFreeSpace64, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, wide freeSize)")},
- {"DataHAppend64", (PyCFunction)Qt_DataHAppend64, 1,
- PyDoc_STR("(DataHandler dh, void * data, unsigned long size) -> (ComponentResult _rv, wide fileOffset)")},
- {"DataHPollRead", (PyCFunction)Qt_DataHPollRead, 1,
- PyDoc_STR("(DataHandler dh, void * dataPtr) -> (ComponentResult _rv, UInt32 dataSizeSoFar)")},
- {"DataHGetDataAvailability", (PyCFunction)Qt_DataHGetDataAvailability, 1,
- PyDoc_STR("(DataHandler dh, long offset, long len) -> (ComponentResult _rv, long missing_offset, long missing_len)")},
- {"DataHGetDataRefAsType", (PyCFunction)Qt_DataHGetDataRefAsType, 1,
- PyDoc_STR("(DataHandler dh, OSType requestedType) -> (ComponentResult _rv, Handle dataRef)")},
- {"DataHSetDataRefExtension", (PyCFunction)Qt_DataHSetDataRefExtension, 1,
- PyDoc_STR("(DataHandler dh, Handle extension, OSType idType) -> (ComponentResult _rv)")},
- {"DataHGetDataRefExtension", (PyCFunction)Qt_DataHGetDataRefExtension, 1,
- PyDoc_STR("(DataHandler dh, OSType idType) -> (ComponentResult _rv, Handle extension)")},
- {"DataHGetMovieWithFlags", (PyCFunction)Qt_DataHGetMovieWithFlags, 1,
- PyDoc_STR("(DataHandler dh, short flags) -> (ComponentResult _rv, Movie theMovie, short id)")},
- {"DataHGetFileTypeOrdering", (PyCFunction)Qt_DataHGetFileTypeOrdering, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, DataHFileTypeOrderingHandle orderingListHandle)")},
- {"DataHCreateFileWithFlags", (PyCFunction)Qt_DataHCreateFileWithFlags, 1,
- PyDoc_STR("(DataHandler dh, OSType creator, Boolean deleteExisting, UInt32 flags) -> (ComponentResult _rv)")},
- {"DataHGetInfo", (PyCFunction)Qt_DataHGetInfo, 1,
- PyDoc_STR("(DataHandler dh, OSType what, void * info) -> (ComponentResult _rv)")},
- {"DataHSetIdleManager", (PyCFunction)Qt_DataHSetIdleManager, 1,
- PyDoc_STR("(DataHandler dh, IdleManager im) -> (ComponentResult _rv)")},
- {"DataHDeleteFile", (PyCFunction)Qt_DataHDeleteFile, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
- {"DataHSetMovieUsageFlags", (PyCFunction)Qt_DataHSetMovieUsageFlags, 1,
- PyDoc_STR("(DataHandler dh, long flags) -> (ComponentResult _rv)")},
- {"DataHUseTemporaryDataRef", (PyCFunction)Qt_DataHUseTemporaryDataRef, 1,
- PyDoc_STR("(DataHandler dh, long inFlags) -> (ComponentResult _rv)")},
- {"DataHGetTemporaryDataRefCapabilities", (PyCFunction)Qt_DataHGetTemporaryDataRefCapabilities, 1,
- PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long outUnderstoodFlags)")},
- {"DataHRenameFile", (PyCFunction)Qt_DataHRenameFile, 1,
- PyDoc_STR("(DataHandler dh, Handle newDataRef) -> (ComponentResult _rv)")},
- {"DataHPlaybackHints", (PyCFunction)Qt_DataHPlaybackHints, 1,
- PyDoc_STR("(DataHandler dh, long flags, unsigned long minFileOffset, unsigned long maxFileOffset, long bytesPerSecond) -> (ComponentResult _rv)")},
- {"DataHPlaybackHints64", (PyCFunction)Qt_DataHPlaybackHints64, 1,
- PyDoc_STR("(DataHandler dh, long flags, wide minFileOffset, wide maxFileOffset, long bytesPerSecond) -> (ComponentResult _rv)")},
- {"DataHGetDataRate", (PyCFunction)Qt_DataHGetDataRate, 1,
- PyDoc_STR("(DataHandler dh, long flags) -> (ComponentResult _rv, long bytesPerSecond)")},
- {"DataHSetTimeHints", (PyCFunction)Qt_DataHSetTimeHints, 1,
- PyDoc_STR("(DataHandler dh, long flags, long bandwidthPriority, TimeScale scale, TimeValue minTime, TimeValue maxTime) -> (ComponentResult _rv)")},
- {"VDGetMaxSrcRect", (PyCFunction)Qt_VDGetMaxSrcRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short inputStd) -> (ComponentResult _rv, Rect maxSrcRect)")},
- {"VDGetActiveSrcRect", (PyCFunction)Qt_VDGetActiveSrcRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short inputStd) -> (ComponentResult _rv, Rect activeSrcRect)")},
- {"VDSetDigitizerRect", (PyCFunction)Qt_VDSetDigitizerRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, Rect digitizerRect)")},
- {"VDGetDigitizerRect", (PyCFunction)Qt_VDGetDigitizerRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, Rect digitizerRect)")},
- {"VDGetVBlankRect", (PyCFunction)Qt_VDGetVBlankRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short inputStd) -> (ComponentResult _rv, Rect vBlankRect)")},
- {"VDGetMaskPixMap", (PyCFunction)Qt_VDGetMaskPixMap, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, PixMapHandle maskPixMap) -> (ComponentResult _rv)")},
- {"VDUseThisCLUT", (PyCFunction)Qt_VDUseThisCLUT, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, CTabHandle colorTableHandle) -> (ComponentResult _rv)")},
- {"VDSetInputGammaValue", (PyCFunction)Qt_VDSetInputGammaValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, Fixed channel1, Fixed channel2, Fixed channel3) -> (ComponentResult _rv)")},
- {"VDGetInputGammaValue", (PyCFunction)Qt_VDGetInputGammaValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, Fixed channel1, Fixed channel2, Fixed channel3)")},
- {"VDSetBrightness", (PyCFunction)Qt_VDSetBrightness, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short brightness)")},
- {"VDGetBrightness", (PyCFunction)Qt_VDGetBrightness, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short brightness)")},
- {"VDSetContrast", (PyCFunction)Qt_VDSetContrast, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short contrast)")},
- {"VDSetHue", (PyCFunction)Qt_VDSetHue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short hue)")},
- {"VDSetSharpness", (PyCFunction)Qt_VDSetSharpness, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short sharpness)")},
- {"VDSetSaturation", (PyCFunction)Qt_VDSetSaturation, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short saturation)")},
- {"VDGetContrast", (PyCFunction)Qt_VDGetContrast, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short contrast)")},
- {"VDGetHue", (PyCFunction)Qt_VDGetHue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short hue)")},
- {"VDGetSharpness", (PyCFunction)Qt_VDGetSharpness, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short sharpness)")},
- {"VDGetSaturation", (PyCFunction)Qt_VDGetSaturation, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short saturation)")},
- {"VDGrabOneFrame", (PyCFunction)Qt_VDGrabOneFrame, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
- {"VDGetMaxAuxBuffer", (PyCFunction)Qt_VDGetMaxAuxBuffer, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, PixMapHandle pm, Rect r)")},
- {"VDGetCurrentFlags", (PyCFunction)Qt_VDGetCurrentFlags, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long inputCurrentFlag, long outputCurrentFlag)")},
- {"VDSetKeyColor", (PyCFunction)Qt_VDSetKeyColor, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long index) -> (ComponentResult _rv)")},
- {"VDGetKeyColor", (PyCFunction)Qt_VDGetKeyColor, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long index)")},
- {"VDAddKeyColor", (PyCFunction)Qt_VDAddKeyColor, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long index)")},
- {"VDGetNextKeyColor", (PyCFunction)Qt_VDGetNextKeyColor, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long index) -> (ComponentResult _rv)")},
- {"VDSetKeyColorRange", (PyCFunction)Qt_VDSetKeyColorRange, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, RGBColor minRGB, RGBColor maxRGB)")},
- {"VDGetKeyColorRange", (PyCFunction)Qt_VDGetKeyColorRange, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, RGBColor minRGB, RGBColor maxRGB)")},
- {"VDSetInputColorSpaceMode", (PyCFunction)Qt_VDSetInputColorSpaceMode, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short colorSpaceMode) -> (ComponentResult _rv)")},
- {"VDGetInputColorSpaceMode", (PyCFunction)Qt_VDGetInputColorSpaceMode, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short colorSpaceMode)")},
- {"VDSetClipState", (PyCFunction)Qt_VDSetClipState, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short clipEnable) -> (ComponentResult _rv)")},
- {"VDGetClipState", (PyCFunction)Qt_VDGetClipState, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short clipEnable)")},
- {"VDSetClipRgn", (PyCFunction)Qt_VDSetClipRgn, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, RgnHandle clipRegion) -> (ComponentResult _rv)")},
- {"VDClearClipRgn", (PyCFunction)Qt_VDClearClipRgn, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, RgnHandle clipRegion) -> (ComponentResult _rv)")},
- {"VDGetCLUTInUse", (PyCFunction)Qt_VDGetCLUTInUse, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, CTabHandle colorTableHandle)")},
- {"VDSetPLLFilterType", (PyCFunction)Qt_VDSetPLLFilterType, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short pllType) -> (ComponentResult _rv)")},
- {"VDGetPLLFilterType", (PyCFunction)Qt_VDGetPLLFilterType, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short pllType)")},
- {"VDGetMaskandValue", (PyCFunction)Qt_VDGetMaskandValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, unsigned short blendLevel) -> (ComponentResult _rv, long mask, long value)")},
- {"VDSetMasterBlendLevel", (PyCFunction)Qt_VDSetMasterBlendLevel, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blendLevel)")},
- {"VDSetPlayThruOnOff", (PyCFunction)Qt_VDSetPlayThruOnOff, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short state) -> (ComponentResult _rv)")},
- {"VDSetFieldPreference", (PyCFunction)Qt_VDSetFieldPreference, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short fieldFlag) -> (ComponentResult _rv)")},
- {"VDGetFieldPreference", (PyCFunction)Qt_VDGetFieldPreference, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short fieldFlag)")},
- {"VDPreflightGlobalRect", (PyCFunction)Qt_VDPreflightGlobalRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, GrafPtr theWindow) -> (ComponentResult _rv, Rect globalRect)")},
- {"VDSetPlayThruGlobalRect", (PyCFunction)Qt_VDSetPlayThruGlobalRect, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, GrafPtr theWindow) -> (ComponentResult _rv, Rect globalRect)")},
- {"VDSetBlackLevelValue", (PyCFunction)Qt_VDSetBlackLevelValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blackLevel)")},
- {"VDGetBlackLevelValue", (PyCFunction)Qt_VDGetBlackLevelValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blackLevel)")},
- {"VDSetWhiteLevelValue", (PyCFunction)Qt_VDSetWhiteLevelValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short whiteLevel)")},
- {"VDGetWhiteLevelValue", (PyCFunction)Qt_VDGetWhiteLevelValue, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short whiteLevel)")},
- {"VDGetVideoDefaults", (PyCFunction)Qt_VDGetVideoDefaults, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blackLevel, unsigned short whiteLevel, unsigned short brightness, unsigned short hue, unsigned short saturation, unsigned short contrast, unsigned short sharpness)")},
- {"VDGetNumberOfInputs", (PyCFunction)Qt_VDGetNumberOfInputs, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short inputs)")},
- {"VDGetInputFormat", (PyCFunction)Qt_VDGetInputFormat, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short input) -> (ComponentResult _rv, short format)")},
- {"VDSetInput", (PyCFunction)Qt_VDSetInput, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short input) -> (ComponentResult _rv)")},
- {"VDGetInput", (PyCFunction)Qt_VDGetInput, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short input)")},
- {"VDSetInputStandard", (PyCFunction)Qt_VDSetInputStandard, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short inputStandard) -> (ComponentResult _rv)")},
- {"VDSetupBuffers", (PyCFunction)Qt_VDSetupBuffers, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, VdigBufferRecListHandle bufferList) -> (ComponentResult _rv)")},
- {"VDGrabOneFrameAsync", (PyCFunction)Qt_VDGrabOneFrameAsync, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short buffer) -> (ComponentResult _rv)")},
- {"VDDone", (PyCFunction)Qt_VDDone, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, short buffer) -> (ComponentResult _rv)")},
- {"VDSetCompression", (PyCFunction)Qt_VDSetCompression, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, OSType compressType, short depth, CodecQ spatialQuality, CodecQ temporalQuality, long keyFrameRate) -> (ComponentResult _rv, Rect bounds)")},
- {"VDCompressOneFrameAsync", (PyCFunction)Qt_VDCompressOneFrameAsync, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
- {"VDGetImageDescription", (PyCFunction)Qt_VDGetImageDescription, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
- {"VDResetCompressSequence", (PyCFunction)Qt_VDResetCompressSequence, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
- {"VDSetCompressionOnOff", (PyCFunction)Qt_VDSetCompressionOnOff, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, Boolean state) -> (ComponentResult _rv)")},
- {"VDGetCompressionTypes", (PyCFunction)Qt_VDGetCompressionTypes, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, VDCompressionListHandle h) -> (ComponentResult _rv)")},
- {"VDSetTimeBase", (PyCFunction)Qt_VDSetTimeBase, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, TimeBase t) -> (ComponentResult _rv)")},
- {"VDSetFrameRate", (PyCFunction)Qt_VDSetFrameRate, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, Fixed framesPerSecond) -> (ComponentResult _rv)")},
- {"VDGetDataRate", (PyCFunction)Qt_VDGetDataRate, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long milliSecPerFrame, Fixed framesPerSecond, long bytesPerSecond)")},
- {"VDGetSoundInputDriver", (PyCFunction)Qt_VDGetSoundInputDriver, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, Str255 soundDriverName) -> (ComponentResult _rv)")},
- {"VDGetDMADepths", (PyCFunction)Qt_VDGetDMADepths, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long depthArray, long preferredDepth)")},
- {"VDGetPreferredTimeScale", (PyCFunction)Qt_VDGetPreferredTimeScale, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, TimeScale preferred)")},
- {"VDReleaseAsyncBuffers", (PyCFunction)Qt_VDReleaseAsyncBuffers, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
- {"VDSetDataRate", (PyCFunction)Qt_VDSetDataRate, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long bytesPerSecond) -> (ComponentResult _rv)")},
- {"VDGetTimeCode", (PyCFunction)Qt_VDGetTimeCode, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, void * timeCodeFormat, void * timeCodeTime) -> (ComponentResult _rv, TimeRecord atTime)")},
- {"VDUseSafeBuffers", (PyCFunction)Qt_VDUseSafeBuffers, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, Boolean useSafeBuffers) -> (ComponentResult _rv)")},
- {"VDGetSoundInputSource", (PyCFunction)Qt_VDGetSoundInputSource, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long videoInput) -> (ComponentResult _rv, long soundInput)")},
- {"VDGetCompressionTime", (PyCFunction)Qt_VDGetCompressionTime, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, OSType compressionType, short depth) -> (ComponentResult _rv, Rect srcRect, CodecQ spatialQuality, CodecQ temporalQuality, unsigned long compressTime)")},
- {"VDSetPreferredPacketSize", (PyCFunction)Qt_VDSetPreferredPacketSize, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long preferredPacketSizeInBytes) -> (ComponentResult _rv)")},
- {"VDSetPreferredImageDimensions", (PyCFunction)Qt_VDSetPreferredImageDimensions, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long width, long height) -> (ComponentResult _rv)")},
- {"VDGetPreferredImageDimensions", (PyCFunction)Qt_VDGetPreferredImageDimensions, 1,
- PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long width, long height)")},
- {"VDGetInputName", (PyCFunction)Qt_VDGetInputName, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, long videoInput, Str255 name) -> (ComponentResult _rv)")},
- {"VDSetDestinationPort", (PyCFunction)Qt_VDSetDestinationPort, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, CGrafPtr destPort) -> (ComponentResult _rv)")},
- {"VDGetDeviceNameAndFlags", (PyCFunction)Qt_VDGetDeviceNameAndFlags, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, Str255 outName) -> (ComponentResult _rv, UInt32 outNameFlags)")},
- {"VDCaptureStateChanging", (PyCFunction)Qt_VDCaptureStateChanging, 1,
- PyDoc_STR("(VideoDigitizerComponent ci, UInt32 inStateFlags) -> (ComponentResult _rv)")},
- {"XMLParseGetDetailedParseError", (PyCFunction)Qt_XMLParseGetDetailedParseError, 1,
- PyDoc_STR("(ComponentInstance aParser, StringPtr errDesc) -> (ComponentResult _rv, long errorLine)")},
- {"XMLParseAddElement", (PyCFunction)Qt_XMLParseAddElement, 1,
- PyDoc_STR("(ComponentInstance aParser, UInt32 nameSpaceID, long elementFlags) -> (ComponentResult _rv, char elementName, UInt32 elementID)")},
- {"XMLParseAddAttribute", (PyCFunction)Qt_XMLParseAddAttribute, 1,
- PyDoc_STR("(ComponentInstance aParser, UInt32 elementID, UInt32 nameSpaceID) -> (ComponentResult _rv, char attributeName, UInt32 attributeID)")},
- {"XMLParseAddMultipleAttributes", (PyCFunction)Qt_XMLParseAddMultipleAttributes, 1,
- PyDoc_STR("(ComponentInstance aParser, UInt32 elementID) -> (ComponentResult _rv, UInt32 nameSpaceIDs, char attributeNames, UInt32 attributeIDs)")},
- {"XMLParseAddAttributeAndValue", (PyCFunction)Qt_XMLParseAddAttributeAndValue, 1,
- PyDoc_STR("(ComponentInstance aParser, UInt32 elementID, UInt32 nameSpaceID, UInt32 attributeValueKind, void * attributeValueKindInfo) -> (ComponentResult _rv, char attributeName, UInt32 attributeID)")},
- {"XMLParseAddAttributeValueKind", (PyCFunction)Qt_XMLParseAddAttributeValueKind, 1,
- PyDoc_STR("(ComponentInstance aParser, UInt32 elementID, UInt32 attributeID, UInt32 attributeValueKind, void * attributeValueKindInfo) -> (ComponentResult _rv)")},
- {"XMLParseAddNameSpace", (PyCFunction)Qt_XMLParseAddNameSpace, 1,
- PyDoc_STR("(ComponentInstance aParser) -> (ComponentResult _rv, char nameSpaceURL, UInt32 nameSpaceID)")},
- {"XMLParseSetOffsetAndLimit", (PyCFunction)Qt_XMLParseSetOffsetAndLimit, 1,
- PyDoc_STR("(ComponentInstance aParser, UInt32 offset, UInt32 limit) -> (ComponentResult _rv)")},
- {"XMLParseSetEventParseRefCon", (PyCFunction)Qt_XMLParseSetEventParseRefCon, 1,
- PyDoc_STR("(ComponentInstance aParser, long refcon) -> (ComponentResult _rv)")},
- {"SGInitialize", (PyCFunction)Qt_SGInitialize, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
- {"SGSetDataOutput", (PyCFunction)Qt_SGSetDataOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, FSSpec movieFile, long whereFlags) -> (ComponentResult _rv)")},
- {"SGGetDataOutput", (PyCFunction)Qt_SGGetDataOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, FSSpec movieFile) -> (ComponentResult _rv, long whereFlags)")},
- {"SGSetGWorld", (PyCFunction)Qt_SGSetGWorld, 1,
- PyDoc_STR("(SeqGrabComponent s, CGrafPtr gp, GDHandle gd) -> (ComponentResult _rv)")},
- {"SGGetGWorld", (PyCFunction)Qt_SGGetGWorld, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, CGrafPtr gp, GDHandle gd)")},
- {"SGNewChannel", (PyCFunction)Qt_SGNewChannel, 1,
- PyDoc_STR("(SeqGrabComponent s, OSType channelType) -> (ComponentResult _rv, SGChannel ref)")},
- {"SGDisposeChannel", (PyCFunction)Qt_SGDisposeChannel, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c) -> (ComponentResult _rv)")},
- {"SGStartPreview", (PyCFunction)Qt_SGStartPreview, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
- {"SGStartRecord", (PyCFunction)Qt_SGStartRecord, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
- {"SGIdle", (PyCFunction)Qt_SGIdle, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
- {"SGStop", (PyCFunction)Qt_SGStop, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
- {"SGPause", (PyCFunction)Qt_SGPause, 1,
- PyDoc_STR("(SeqGrabComponent s, Boolean pause) -> (ComponentResult _rv)")},
- {"SGPrepare", (PyCFunction)Qt_SGPrepare, 1,
- PyDoc_STR("(SeqGrabComponent s, Boolean prepareForPreview, Boolean prepareForRecord) -> (ComponentResult _rv)")},
- {"SGRelease", (PyCFunction)Qt_SGRelease, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
- {"SGGetMovie", (PyCFunction)Qt_SGGetMovie, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (Movie _rv)")},
- {"SGSetMaximumRecordTime", (PyCFunction)Qt_SGSetMaximumRecordTime, 1,
- PyDoc_STR("(SeqGrabComponent s, unsigned long ticks) -> (ComponentResult _rv)")},
- {"SGGetMaximumRecordTime", (PyCFunction)Qt_SGGetMaximumRecordTime, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, unsigned long ticks)")},
- {"SGGetStorageSpaceRemaining", (PyCFunction)Qt_SGGetStorageSpaceRemaining, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, unsigned long bytes)")},
- {"SGGetTimeRemaining", (PyCFunction)Qt_SGGetTimeRemaining, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, long ticksLeft)")},
- {"SGGrabPict", (PyCFunction)Qt_SGGrabPict, 1,
- PyDoc_STR("(SeqGrabComponent s, Rect bounds, short offscreenDepth, long grabPictFlags) -> (ComponentResult _rv, PicHandle p)")},
- {"SGGetLastMovieResID", (PyCFunction)Qt_SGGetLastMovieResID, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, short resID)")},
- {"SGSetFlags", (PyCFunction)Qt_SGSetFlags, 1,
- PyDoc_STR("(SeqGrabComponent s, long sgFlags) -> (ComponentResult _rv)")},
- {"SGGetFlags", (PyCFunction)Qt_SGGetFlags, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, long sgFlags)")},
- {"SGNewChannelFromComponent", (PyCFunction)Qt_SGNewChannelFromComponent, 1,
- PyDoc_STR("(SeqGrabComponent s, Component sgChannelComponent) -> (ComponentResult _rv, SGChannel newChannel)")},
- {"SGSetSettings", (PyCFunction)Qt_SGSetSettings, 1,
- PyDoc_STR("(SeqGrabComponent s, UserData ud, long flags) -> (ComponentResult _rv)")},
- {"SGGetSettings", (PyCFunction)Qt_SGGetSettings, 1,
- PyDoc_STR("(SeqGrabComponent s, long flags) -> (ComponentResult _rv, UserData ud)")},
- {"SGGetIndChannel", (PyCFunction)Qt_SGGetIndChannel, 1,
- PyDoc_STR("(SeqGrabComponent s, short index) -> (ComponentResult _rv, SGChannel ref, OSType chanType)")},
- {"SGUpdate", (PyCFunction)Qt_SGUpdate, 1,
- PyDoc_STR("(SeqGrabComponent s, RgnHandle updateRgn) -> (ComponentResult _rv)")},
- {"SGGetPause", (PyCFunction)Qt_SGGetPause, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Boolean paused)")},
- {"SGSetChannelSettings", (PyCFunction)Qt_SGSetChannelSettings, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, UserData ud, long flags) -> (ComponentResult _rv)")},
- {"SGGetChannelSettings", (PyCFunction)Qt_SGGetChannelSettings, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, long flags) -> (ComponentResult _rv, UserData ud)")},
- {"SGGetMode", (PyCFunction)Qt_SGGetMode, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Boolean previewMode, Boolean recordMode)")},
- {"SGSetDataRef", (PyCFunction)Qt_SGSetDataRef, 1,
- PyDoc_STR("(SeqGrabComponent s, Handle dataRef, OSType dataRefType, long whereFlags) -> (ComponentResult _rv)")},
- {"SGGetDataRef", (PyCFunction)Qt_SGGetDataRef, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType, long whereFlags)")},
- {"SGNewOutput", (PyCFunction)Qt_SGNewOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, Handle dataRef, OSType dataRefType, long whereFlags) -> (ComponentResult _rv, SGOutput sgOut)")},
- {"SGDisposeOutput", (PyCFunction)Qt_SGDisposeOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv)")},
- {"SGSetOutputFlags", (PyCFunction)Qt_SGSetOutputFlags, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, long whereFlags) -> (ComponentResult _rv)")},
- {"SGSetChannelOutput", (PyCFunction)Qt_SGSetChannelOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, SGOutput sgOut) -> (ComponentResult _rv)")},
- {"SGGetDataOutputStorageSpaceRemaining", (PyCFunction)Qt_SGGetDataOutputStorageSpaceRemaining, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, unsigned long space)")},
- {"SGHandleUpdateEvent", (PyCFunction)Qt_SGHandleUpdateEvent, 1,
- PyDoc_STR("(SeqGrabComponent s, EventRecord event) -> (ComponentResult _rv, Boolean handled)")},
- {"SGSetOutputNextOutput", (PyCFunction)Qt_SGSetOutputNextOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, SGOutput nextOut) -> (ComponentResult _rv)")},
- {"SGGetOutputNextOutput", (PyCFunction)Qt_SGGetOutputNextOutput, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, SGOutput nextOut)")},
- {"SGSetOutputMaximumOffset", (PyCFunction)Qt_SGSetOutputMaximumOffset, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, wide maxOffset) -> (ComponentResult _rv)")},
- {"SGGetOutputMaximumOffset", (PyCFunction)Qt_SGGetOutputMaximumOffset, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, wide maxOffset)")},
- {"SGGetOutputDataReference", (PyCFunction)Qt_SGGetOutputDataReference, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
- {"SGWriteExtendedMovieData", (PyCFunction)Qt_SGWriteExtendedMovieData, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len) -> (ComponentResult _rv, wide offset, SGOutput sgOut)")},
- {"SGGetStorageSpaceRemaining64", (PyCFunction)Qt_SGGetStorageSpaceRemaining64, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, wide bytes)")},
- {"SGGetDataOutputStorageSpaceRemaining64", (PyCFunction)Qt_SGGetDataOutputStorageSpaceRemaining64, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, wide space)")},
- {"SGWriteMovieData", (PyCFunction)Qt_SGWriteMovieData, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len) -> (ComponentResult _rv, long offset)")},
- {"SGGetTimeBase", (PyCFunction)Qt_SGGetTimeBase, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, TimeBase tb)")},
- {"SGAddMovieData", (PyCFunction)Qt_SGAddMovieData, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len, long chRefCon, TimeValue time, short writeType) -> (ComponentResult _rv, long offset)")},
- {"SGChangedSource", (PyCFunction)Qt_SGChangedSource, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c) -> (ComponentResult _rv)")},
- {"SGAddExtendedMovieData", (PyCFunction)Qt_SGAddExtendedMovieData, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len, long chRefCon, TimeValue time, short writeType) -> (ComponentResult _rv, wide offset, SGOutput whichOutput)")},
- {"SGAddOutputDataRefToMedia", (PyCFunction)Qt_SGAddOutputDataRefToMedia, 1,
- PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, Media theMedia, SampleDescriptionHandle desc) -> (ComponentResult _rv)")},
- {"SGSetSettingsSummary", (PyCFunction)Qt_SGSetSettingsSummary, 1,
- PyDoc_STR("(SeqGrabComponent s, Handle summaryText) -> (ComponentResult _rv)")},
- {"SGSetChannelUsage", (PyCFunction)Qt_SGSetChannelUsage, 1,
- PyDoc_STR("(SGChannel c, long usage) -> (ComponentResult _rv)")},
- {"SGGetChannelUsage", (PyCFunction)Qt_SGGetChannelUsage, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long usage)")},
- {"SGSetChannelBounds", (PyCFunction)Qt_SGSetChannelBounds, 1,
- PyDoc_STR("(SGChannel c, Rect bounds) -> (ComponentResult _rv)")},
- {"SGGetChannelBounds", (PyCFunction)Qt_SGGetChannelBounds, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect bounds)")},
- {"SGSetChannelVolume", (PyCFunction)Qt_SGSetChannelVolume, 1,
- PyDoc_STR("(SGChannel c, short volume) -> (ComponentResult _rv)")},
- {"SGGetChannelVolume", (PyCFunction)Qt_SGGetChannelVolume, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short volume)")},
- {"SGGetChannelInfo", (PyCFunction)Qt_SGGetChannelInfo, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long channelInfo)")},
- {"SGSetChannelPlayFlags", (PyCFunction)Qt_SGSetChannelPlayFlags, 1,
- PyDoc_STR("(SGChannel c, long playFlags) -> (ComponentResult _rv)")},
- {"SGGetChannelPlayFlags", (PyCFunction)Qt_SGGetChannelPlayFlags, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long playFlags)")},
- {"SGSetChannelMaxFrames", (PyCFunction)Qt_SGSetChannelMaxFrames, 1,
- PyDoc_STR("(SGChannel c, long frameCount) -> (ComponentResult _rv)")},
- {"SGGetChannelMaxFrames", (PyCFunction)Qt_SGGetChannelMaxFrames, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long frameCount)")},
- {"SGSetChannelRefCon", (PyCFunction)Qt_SGSetChannelRefCon, 1,
- PyDoc_STR("(SGChannel c, long refCon) -> (ComponentResult _rv)")},
- {"SGSetChannelClip", (PyCFunction)Qt_SGSetChannelClip, 1,
- PyDoc_STR("(SGChannel c, RgnHandle theClip) -> (ComponentResult _rv)")},
- {"SGGetChannelClip", (PyCFunction)Qt_SGGetChannelClip, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, RgnHandle theClip)")},
- {"SGGetChannelSampleDescription", (PyCFunction)Qt_SGGetChannelSampleDescription, 1,
- PyDoc_STR("(SGChannel c, Handle sampleDesc) -> (ComponentResult _rv)")},
- {"SGSetChannelDevice", (PyCFunction)Qt_SGSetChannelDevice, 1,
- PyDoc_STR("(SGChannel c, StringPtr name) -> (ComponentResult _rv)")},
- {"SGGetChannelTimeScale", (PyCFunction)Qt_SGGetChannelTimeScale, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, TimeScale scale)")},
- {"SGChannelPutPicture", (PyCFunction)Qt_SGChannelPutPicture, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv)")},
- {"SGChannelSetRequestedDataRate", (PyCFunction)Qt_SGChannelSetRequestedDataRate, 1,
- PyDoc_STR("(SGChannel c, long bytesPerSecond) -> (ComponentResult _rv)")},
- {"SGChannelGetRequestedDataRate", (PyCFunction)Qt_SGChannelGetRequestedDataRate, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long bytesPerSecond)")},
- {"SGChannelSetDataSourceName", (PyCFunction)Qt_SGChannelSetDataSourceName, 1,
- PyDoc_STR("(SGChannel c, Str255 name, ScriptCode scriptTag) -> (ComponentResult _rv)")},
- {"SGChannelGetDataSourceName", (PyCFunction)Qt_SGChannelGetDataSourceName, 1,
- PyDoc_STR("(SGChannel c, Str255 name) -> (ComponentResult _rv, ScriptCode scriptTag)")},
- {"SGChannelSetCodecSettings", (PyCFunction)Qt_SGChannelSetCodecSettings, 1,
- PyDoc_STR("(SGChannel c, Handle settings) -> (ComponentResult _rv)")},
- {"SGChannelGetCodecSettings", (PyCFunction)Qt_SGChannelGetCodecSettings, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Handle settings)")},
- {"SGGetChannelTimeBase", (PyCFunction)Qt_SGGetChannelTimeBase, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, TimeBase tb)")},
- {"SGGetChannelRefCon", (PyCFunction)Qt_SGGetChannelRefCon, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long refCon)")},
- {"SGGetChannelDeviceAndInputNames", (PyCFunction)Qt_SGGetChannelDeviceAndInputNames, 1,
- PyDoc_STR("(SGChannel c, Str255 outDeviceName, Str255 outInputName) -> (ComponentResult _rv, short outInputNumber)")},
- {"SGSetChannelDeviceInput", (PyCFunction)Qt_SGSetChannelDeviceInput, 1,
- PyDoc_STR("(SGChannel c, short inInputNumber) -> (ComponentResult _rv)")},
- {"SGSetChannelSettingsStateChanging", (PyCFunction)Qt_SGSetChannelSettingsStateChanging, 1,
- PyDoc_STR("(SGChannel c, UInt32 inFlags) -> (ComponentResult _rv)")},
- {"SGInitChannel", (PyCFunction)Qt_SGInitChannel, 1,
- PyDoc_STR("(SGChannel c, SeqGrabComponent owner) -> (ComponentResult _rv)")},
- {"SGWriteSamples", (PyCFunction)Qt_SGWriteSamples, 1,
- PyDoc_STR("(SGChannel c, Movie m, AliasHandle theFile) -> (ComponentResult _rv)")},
- {"SGGetDataRate", (PyCFunction)Qt_SGGetDataRate, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long bytesPerSecond)")},
- {"SGAlignChannelRect", (PyCFunction)Qt_SGAlignChannelRect, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect r)")},
- {"SGPanelGetDitl", (PyCFunction)Qt_SGPanelGetDitl, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Handle ditl)")},
- {"SGPanelGetTitle", (PyCFunction)Qt_SGPanelGetTitle, 1,
- PyDoc_STR("(SeqGrabComponent s, Str255 title) -> (ComponentResult _rv)")},
- {"SGPanelCanRun", (PyCFunction)Qt_SGPanelCanRun, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c) -> (ComponentResult _rv)")},
- {"SGPanelInstall", (PyCFunction)Qt_SGPanelInstall, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset) -> (ComponentResult _rv)")},
- {"SGPanelEvent", (PyCFunction)Qt_SGPanelEvent, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset, EventRecord theEvent) -> (ComponentResult _rv, short itemHit, Boolean handled)")},
- {"SGPanelItem", (PyCFunction)Qt_SGPanelItem, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset, short itemNum) -> (ComponentResult _rv)")},
- {"SGPanelRemove", (PyCFunction)Qt_SGPanelRemove, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset) -> (ComponentResult _rv)")},
- {"SGPanelSetGrabber", (PyCFunction)Qt_SGPanelSetGrabber, 1,
- PyDoc_STR("(SeqGrabComponent s, SeqGrabComponent sg) -> (ComponentResult _rv)")},
- {"SGPanelSetResFile", (PyCFunction)Qt_SGPanelSetResFile, 1,
- PyDoc_STR("(SeqGrabComponent s, short resRef) -> (ComponentResult _rv)")},
- {"SGPanelGetSettings", (PyCFunction)Qt_SGPanelGetSettings, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, long flags) -> (ComponentResult _rv, UserData ud)")},
- {"SGPanelSetSettings", (PyCFunction)Qt_SGPanelSetSettings, 1,
- PyDoc_STR("(SeqGrabComponent s, SGChannel c, UserData ud, long flags) -> (ComponentResult _rv)")},
- {"SGPanelValidateInput", (PyCFunction)Qt_SGPanelValidateInput, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Boolean ok)")},
- {"SGPanelGetDITLForSize", (PyCFunction)Qt_SGPanelGetDITLForSize, 1,
- PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Handle ditl, Point requestedSize)")},
- {"SGGetSrcVideoBounds", (PyCFunction)Qt_SGGetSrcVideoBounds, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect r)")},
- {"SGSetVideoRect", (PyCFunction)Qt_SGSetVideoRect, 1,
- PyDoc_STR("(SGChannel c, Rect r) -> (ComponentResult _rv)")},
- {"SGGetVideoRect", (PyCFunction)Qt_SGGetVideoRect, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect r)")},
- {"SGGetVideoCompressorType", (PyCFunction)Qt_SGGetVideoCompressorType, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, OSType compressorType)")},
- {"SGSetVideoCompressorType", (PyCFunction)Qt_SGSetVideoCompressorType, 1,
- PyDoc_STR("(SGChannel c, OSType compressorType) -> (ComponentResult _rv)")},
- {"SGSetVideoCompressor", (PyCFunction)Qt_SGSetVideoCompressor, 1,
- PyDoc_STR("(SGChannel c, short depth, CompressorComponent compressor, CodecQ spatialQuality, CodecQ temporalQuality, long keyFrameRate) -> (ComponentResult _rv)")},
- {"SGGetVideoCompressor", (PyCFunction)Qt_SGGetVideoCompressor, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short depth, CompressorComponent compressor, CodecQ spatialQuality, CodecQ temporalQuality, long keyFrameRate)")},
- {"SGGetVideoDigitizerComponent", (PyCFunction)Qt_SGGetVideoDigitizerComponent, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentInstance _rv)")},
- {"SGSetVideoDigitizerComponent", (PyCFunction)Qt_SGSetVideoDigitizerComponent, 1,
- PyDoc_STR("(SGChannel c, ComponentInstance vdig) -> (ComponentResult _rv)")},
- {"SGVideoDigitizerChanged", (PyCFunction)Qt_SGVideoDigitizerChanged, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv)")},
- {"SGGrabFrame", (PyCFunction)Qt_SGGrabFrame, 1,
- PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv)")},
- {"SGGrabFrameComplete", (PyCFunction)Qt_SGGrabFrameComplete, 1,
- PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv, Boolean done)")},
- {"SGCompressFrame", (PyCFunction)Qt_SGCompressFrame, 1,
- PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv)")},
- {"SGSetCompressBuffer", (PyCFunction)Qt_SGSetCompressBuffer, 1,
- PyDoc_STR("(SGChannel c, short depth, Rect compressSize) -> (ComponentResult _rv)")},
- {"SGGetCompressBuffer", (PyCFunction)Qt_SGGetCompressBuffer, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short depth, Rect compressSize)")},
- {"SGGetBufferInfo", (PyCFunction)Qt_SGGetBufferInfo, 1,
- PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv, PixMapHandle bufferPM, Rect bufferRect, GWorldPtr compressBuffer, Rect compressBufferRect)")},
- {"SGSetUseScreenBuffer", (PyCFunction)Qt_SGSetUseScreenBuffer, 1,
- PyDoc_STR("(SGChannel c, Boolean useScreenBuffer) -> (ComponentResult _rv)")},
- {"SGGetUseScreenBuffer", (PyCFunction)Qt_SGGetUseScreenBuffer, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Boolean useScreenBuffer)")},
- {"SGSetFrameRate", (PyCFunction)Qt_SGSetFrameRate, 1,
- PyDoc_STR("(SGChannel c, Fixed frameRate) -> (ComponentResult _rv)")},
- {"SGGetFrameRate", (PyCFunction)Qt_SGGetFrameRate, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Fixed frameRate)")},
- {"SGSetPreferredPacketSize", (PyCFunction)Qt_SGSetPreferredPacketSize, 1,
- PyDoc_STR("(SGChannel c, long preferredPacketSizeInBytes) -> (ComponentResult _rv)")},
- {"SGGetPreferredPacketSize", (PyCFunction)Qt_SGGetPreferredPacketSize, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long preferredPacketSizeInBytes)")},
- {"SGSetUserVideoCompressorList", (PyCFunction)Qt_SGSetUserVideoCompressorList, 1,
- PyDoc_STR("(SGChannel c, Handle compressorTypes) -> (ComponentResult _rv)")},
- {"SGGetUserVideoCompressorList", (PyCFunction)Qt_SGGetUserVideoCompressorList, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Handle compressorTypes)")},
- {"SGSetSoundInputDriver", (PyCFunction)Qt_SGSetSoundInputDriver, 1,
- PyDoc_STR("(SGChannel c, Str255 driverName) -> (ComponentResult _rv)")},
- {"SGGetSoundInputDriver", (PyCFunction)Qt_SGGetSoundInputDriver, 1,
- PyDoc_STR("(SGChannel c) -> (long _rv)")},
- {"SGSoundInputDriverChanged", (PyCFunction)Qt_SGSoundInputDriverChanged, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv)")},
- {"SGSetSoundRecordChunkSize", (PyCFunction)Qt_SGSetSoundRecordChunkSize, 1,
- PyDoc_STR("(SGChannel c, long seconds) -> (ComponentResult _rv)")},
- {"SGGetSoundRecordChunkSize", (PyCFunction)Qt_SGGetSoundRecordChunkSize, 1,
- PyDoc_STR("(SGChannel c) -> (long _rv)")},
- {"SGSetSoundInputRate", (PyCFunction)Qt_SGSetSoundInputRate, 1,
- PyDoc_STR("(SGChannel c, Fixed rate) -> (ComponentResult _rv)")},
- {"SGGetSoundInputRate", (PyCFunction)Qt_SGGetSoundInputRate, 1,
- PyDoc_STR("(SGChannel c) -> (Fixed _rv)")},
- {"SGSetSoundInputParameters", (PyCFunction)Qt_SGSetSoundInputParameters, 1,
- PyDoc_STR("(SGChannel c, short sampleSize, short numChannels, OSType compressionType) -> (ComponentResult _rv)")},
- {"SGGetSoundInputParameters", (PyCFunction)Qt_SGGetSoundInputParameters, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short sampleSize, short numChannels, OSType compressionType)")},
- {"SGSetAdditionalSoundRates", (PyCFunction)Qt_SGSetAdditionalSoundRates, 1,
- PyDoc_STR("(SGChannel c, Handle rates) -> (ComponentResult _rv)")},
- {"SGGetAdditionalSoundRates", (PyCFunction)Qt_SGGetAdditionalSoundRates, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Handle rates)")},
- {"SGSetFontName", (PyCFunction)Qt_SGSetFontName, 1,
- PyDoc_STR("(SGChannel c, StringPtr pstr) -> (ComponentResult _rv)")},
- {"SGSetFontSize", (PyCFunction)Qt_SGSetFontSize, 1,
- PyDoc_STR("(SGChannel c, short fontSize) -> (ComponentResult _rv)")},
- {"SGSetTextForeColor", (PyCFunction)Qt_SGSetTextForeColor, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, RGBColor theColor)")},
- {"SGSetTextBackColor", (PyCFunction)Qt_SGSetTextBackColor, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, RGBColor theColor)")},
- {"SGSetJustification", (PyCFunction)Qt_SGSetJustification, 1,
- PyDoc_STR("(SGChannel c, short just) -> (ComponentResult _rv)")},
- {"SGGetTextReturnToSpaceValue", (PyCFunction)Qt_SGGetTextReturnToSpaceValue, 1,
- PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short rettospace)")},
- {"SGSetTextReturnToSpaceValue", (PyCFunction)Qt_SGSetTextReturnToSpaceValue, 1,
- PyDoc_STR("(SGChannel c, short rettospace) -> (ComponentResult _rv)")},
- {"QTVideoOutputGetCurrentClientName", (PyCFunction)Qt_QTVideoOutputGetCurrentClientName, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, Str255 str) -> (ComponentResult _rv)")},
- {"QTVideoOutputSetClientName", (PyCFunction)Qt_QTVideoOutputSetClientName, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, Str255 str) -> (ComponentResult _rv)")},
- {"QTVideoOutputGetClientName", (PyCFunction)Qt_QTVideoOutputGetClientName, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, Str255 str) -> (ComponentResult _rv)")},
- {"QTVideoOutputBegin", (PyCFunction)Qt_QTVideoOutputBegin, 1,
- PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv)")},
- {"QTVideoOutputEnd", (PyCFunction)Qt_QTVideoOutputEnd, 1,
- PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv)")},
- {"QTVideoOutputSetDisplayMode", (PyCFunction)Qt_QTVideoOutputSetDisplayMode, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, long displayModeID) -> (ComponentResult _rv)")},
- {"QTVideoOutputGetDisplayMode", (PyCFunction)Qt_QTVideoOutputGetDisplayMode, 1,
- PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv, long displayModeID)")},
- {"QTVideoOutputGetGWorld", (PyCFunction)Qt_QTVideoOutputGetGWorld, 1,
- PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv, GWorldPtr gw)")},
- {"QTVideoOutputGetIndSoundOutput", (PyCFunction)Qt_QTVideoOutputGetIndSoundOutput, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, long index) -> (ComponentResult _rv, Component outputComponent)")},
- {"QTVideoOutputGetClock", (PyCFunction)Qt_QTVideoOutputGetClock, 1,
- PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv, ComponentInstance clock)")},
- {"QTVideoOutputSetEchoPort", (PyCFunction)Qt_QTVideoOutputSetEchoPort, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, CGrafPtr echoPort) -> (ComponentResult _rv)")},
- {"QTVideoOutputGetIndImageDecompressor", (PyCFunction)Qt_QTVideoOutputGetIndImageDecompressor, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, long index) -> (ComponentResult _rv, Component codec)")},
- {"QTVideoOutputBaseSetEchoPort", (PyCFunction)Qt_QTVideoOutputBaseSetEchoPort, 1,
- PyDoc_STR("(QTVideoOutputComponent vo, CGrafPtr echoPort) -> (ComponentResult _rv)")},
- {"MediaSetChunkManagementFlags", (PyCFunction)Qt_MediaSetChunkManagementFlags, 1,
- PyDoc_STR("(MediaHandler mh, UInt32 flags, UInt32 flagsMask) -> (ComponentResult _rv)")},
- {"MediaGetChunkManagementFlags", (PyCFunction)Qt_MediaGetChunkManagementFlags, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt32 flags)")},
- {"MediaSetPurgeableChunkMemoryAllowance", (PyCFunction)Qt_MediaSetPurgeableChunkMemoryAllowance, 1,
- PyDoc_STR("(MediaHandler mh, Size allowance) -> (ComponentResult _rv)")},
- {"MediaGetPurgeableChunkMemoryAllowance", (PyCFunction)Qt_MediaGetPurgeableChunkMemoryAllowance, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Size allowance)")},
- {"MediaEmptyAllPurgeableChunks", (PyCFunction)Qt_MediaEmptyAllPurgeableChunks, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaSetHandlerCapabilities", (PyCFunction)Qt_MediaSetHandlerCapabilities, 1,
- PyDoc_STR("(MediaHandler mh, long flags, long flagsMask) -> (ComponentResult _rv)")},
- {"MediaIdle", (PyCFunction)Qt_MediaIdle, 1,
- PyDoc_STR("(MediaHandler mh, TimeValue atMediaTime, long flagsIn, TimeRecord movieTime) -> (ComponentResult _rv, long flagsOut)")},
- {"MediaGetMediaInfo", (PyCFunction)Qt_MediaGetMediaInfo, 1,
- PyDoc_STR("(MediaHandler mh, Handle h) -> (ComponentResult _rv)")},
- {"MediaPutMediaInfo", (PyCFunction)Qt_MediaPutMediaInfo, 1,
- PyDoc_STR("(MediaHandler mh, Handle h) -> (ComponentResult _rv)")},
- {"MediaSetActive", (PyCFunction)Qt_MediaSetActive, 1,
- PyDoc_STR("(MediaHandler mh, Boolean enableMedia) -> (ComponentResult _rv)")},
- {"MediaSetRate", (PyCFunction)Qt_MediaSetRate, 1,
- PyDoc_STR("(MediaHandler mh, Fixed rate) -> (ComponentResult _rv)")},
- {"MediaGGetStatus", (PyCFunction)Qt_MediaGGetStatus, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, ComponentResult statusErr)")},
- {"MediaTrackEdited", (PyCFunction)Qt_MediaTrackEdited, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaSetMediaTimeScale", (PyCFunction)Qt_MediaSetMediaTimeScale, 1,
- PyDoc_STR("(MediaHandler mh, TimeScale newTimeScale) -> (ComponentResult _rv)")},
- {"MediaSetMovieTimeScale", (PyCFunction)Qt_MediaSetMovieTimeScale, 1,
- PyDoc_STR("(MediaHandler mh, TimeScale newTimeScale) -> (ComponentResult _rv)")},
- {"MediaSetGWorld", (PyCFunction)Qt_MediaSetGWorld, 1,
- PyDoc_STR("(MediaHandler mh, CGrafPtr aPort, GDHandle aGD) -> (ComponentResult _rv)")},
- {"MediaSetDimensions", (PyCFunction)Qt_MediaSetDimensions, 1,
- PyDoc_STR("(MediaHandler mh, Fixed width, Fixed height) -> (ComponentResult _rv)")},
- {"MediaSetClip", (PyCFunction)Qt_MediaSetClip, 1,
- PyDoc_STR("(MediaHandler mh, RgnHandle theClip) -> (ComponentResult _rv)")},
- {"MediaGetTrackOpaque", (PyCFunction)Qt_MediaGetTrackOpaque, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Boolean trackIsOpaque)")},
- {"MediaSetGraphicsMode", (PyCFunction)Qt_MediaSetGraphicsMode, 1,
- PyDoc_STR("(MediaHandler mh, long mode, RGBColor opColor) -> (ComponentResult _rv)")},
- {"MediaGetGraphicsMode", (PyCFunction)Qt_MediaGetGraphicsMode, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long mode, RGBColor opColor)")},
- {"MediaGSetVolume", (PyCFunction)Qt_MediaGSetVolume, 1,
- PyDoc_STR("(MediaHandler mh, short volume) -> (ComponentResult _rv)")},
- {"MediaSetSoundBalance", (PyCFunction)Qt_MediaSetSoundBalance, 1,
- PyDoc_STR("(MediaHandler mh, short balance) -> (ComponentResult _rv)")},
- {"MediaGetSoundBalance", (PyCFunction)Qt_MediaGetSoundBalance, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short balance)")},
- {"MediaGetNextBoundsChange", (PyCFunction)Qt_MediaGetNextBoundsChange, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, TimeValue when)")},
- {"MediaGetSrcRgn", (PyCFunction)Qt_MediaGetSrcRgn, 1,
- PyDoc_STR("(MediaHandler mh, RgnHandle rgn, TimeValue atMediaTime) -> (ComponentResult _rv)")},
- {"MediaPreroll", (PyCFunction)Qt_MediaPreroll, 1,
- PyDoc_STR("(MediaHandler mh, TimeValue time, Fixed rate) -> (ComponentResult _rv)")},
- {"MediaSampleDescriptionChanged", (PyCFunction)Qt_MediaSampleDescriptionChanged, 1,
- PyDoc_STR("(MediaHandler mh, long index) -> (ComponentResult _rv)")},
- {"MediaHasCharacteristic", (PyCFunction)Qt_MediaHasCharacteristic, 1,
- PyDoc_STR("(MediaHandler mh, OSType characteristic) -> (ComponentResult _rv, Boolean hasIt)")},
- {"MediaGetOffscreenBufferSize", (PyCFunction)Qt_MediaGetOffscreenBufferSize, 1,
- PyDoc_STR("(MediaHandler mh, short depth, CTabHandle ctab) -> (ComponentResult _rv, Rect bounds)")},
- {"MediaSetHints", (PyCFunction)Qt_MediaSetHints, 1,
- PyDoc_STR("(MediaHandler mh, long hints) -> (ComponentResult _rv)")},
- {"MediaGetName", (PyCFunction)Qt_MediaGetName, 1,
- PyDoc_STR("(MediaHandler mh, Str255 name, long requestedLanguage) -> (ComponentResult _rv, long actualLanguage)")},
- {"MediaForceUpdate", (PyCFunction)Qt_MediaForceUpdate, 1,
- PyDoc_STR("(MediaHandler mh, long forceUpdateFlags) -> (ComponentResult _rv)")},
- {"MediaGetDrawingRgn", (PyCFunction)Qt_MediaGetDrawingRgn, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, RgnHandle partialRgn)")},
- {"MediaGSetActiveSegment", (PyCFunction)Qt_MediaGSetActiveSegment, 1,
- PyDoc_STR("(MediaHandler mh, TimeValue activeStart, TimeValue activeDuration) -> (ComponentResult _rv)")},
- {"MediaInvalidateRegion", (PyCFunction)Qt_MediaInvalidateRegion, 1,
- PyDoc_STR("(MediaHandler mh, RgnHandle invalRgn) -> (ComponentResult _rv)")},
- {"MediaGetNextStepTime", (PyCFunction)Qt_MediaGetNextStepTime, 1,
- PyDoc_STR("(MediaHandler mh, short flags, TimeValue mediaTimeIn, Fixed rate) -> (ComponentResult _rv, TimeValue mediaTimeOut)")},
- {"MediaChangedNonPrimarySource", (PyCFunction)Qt_MediaChangedNonPrimarySource, 1,
- PyDoc_STR("(MediaHandler mh, long inputIndex) -> (ComponentResult _rv)")},
- {"MediaTrackReferencesChanged", (PyCFunction)Qt_MediaTrackReferencesChanged, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaReleaseSampleDataPointer", (PyCFunction)Qt_MediaReleaseSampleDataPointer, 1,
- PyDoc_STR("(MediaHandler mh, long sampleNum) -> (ComponentResult _rv)")},
- {"MediaTrackPropertyAtomChanged", (PyCFunction)Qt_MediaTrackPropertyAtomChanged, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaSetVideoParam", (PyCFunction)Qt_MediaSetVideoParam, 1,
- PyDoc_STR("(MediaHandler mh, long whichParam) -> (ComponentResult _rv, unsigned short value)")},
- {"MediaGetVideoParam", (PyCFunction)Qt_MediaGetVideoParam, 1,
- PyDoc_STR("(MediaHandler mh, long whichParam) -> (ComponentResult _rv, unsigned short value)")},
- {"MediaCompare", (PyCFunction)Qt_MediaCompare, 1,
- PyDoc_STR("(MediaHandler mh, Media srcMedia, ComponentInstance srcMediaComponent) -> (ComponentResult _rv, Boolean isOK)")},
- {"MediaGetClock", (PyCFunction)Qt_MediaGetClock, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, ComponentInstance clock)")},
- {"MediaSetSoundOutputComponent", (PyCFunction)Qt_MediaSetSoundOutputComponent, 1,
- PyDoc_STR("(MediaHandler mh, Component outputComponent) -> (ComponentResult _rv)")},
- {"MediaGetSoundOutputComponent", (PyCFunction)Qt_MediaGetSoundOutputComponent, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Component outputComponent)")},
- {"MediaSetSoundLocalizationData", (PyCFunction)Qt_MediaSetSoundLocalizationData, 1,
- PyDoc_STR("(MediaHandler mh, Handle data) -> (ComponentResult _rv)")},
- {"MediaGetInvalidRegion", (PyCFunction)Qt_MediaGetInvalidRegion, 1,
- PyDoc_STR("(MediaHandler mh, RgnHandle rgn) -> (ComponentResult _rv)")},
- {"MediaSampleDescriptionB2N", (PyCFunction)Qt_MediaSampleDescriptionB2N, 1,
- PyDoc_STR("(MediaHandler mh, SampleDescriptionHandle sampleDescriptionH) -> (ComponentResult _rv)")},
- {"MediaSampleDescriptionN2B", (PyCFunction)Qt_MediaSampleDescriptionN2B, 1,
- PyDoc_STR("(MediaHandler mh, SampleDescriptionHandle sampleDescriptionH) -> (ComponentResult _rv)")},
- {"MediaFlushNonPrimarySourceData", (PyCFunction)Qt_MediaFlushNonPrimarySourceData, 1,
- PyDoc_STR("(MediaHandler mh, long inputIndex) -> (ComponentResult _rv)")},
- {"MediaGetURLLink", (PyCFunction)Qt_MediaGetURLLink, 1,
- PyDoc_STR("(MediaHandler mh, Point displayWhere) -> (ComponentResult _rv, Handle urlLink)")},
- {"MediaHitTestForTargetRefCon", (PyCFunction)Qt_MediaHitTestForTargetRefCon, 1,
- PyDoc_STR("(MediaHandler mh, long flags, Point loc) -> (ComponentResult _rv, long targetRefCon)")},
- {"MediaHitTestTargetRefCon", (PyCFunction)Qt_MediaHitTestTargetRefCon, 1,
- PyDoc_STR("(MediaHandler mh, long targetRefCon, long flags, Point loc) -> (ComponentResult _rv, Boolean wasHit)")},
- {"MediaDisposeTargetRefCon", (PyCFunction)Qt_MediaDisposeTargetRefCon, 1,
- PyDoc_STR("(MediaHandler mh, long targetRefCon) -> (ComponentResult _rv)")},
- {"MediaTargetRefConsEqual", (PyCFunction)Qt_MediaTargetRefConsEqual, 1,
- PyDoc_STR("(MediaHandler mh, long firstRefCon, long secondRefCon) -> (ComponentResult _rv, Boolean equal)")},
- {"MediaPrePrerollCancel", (PyCFunction)Qt_MediaPrePrerollCancel, 1,
- PyDoc_STR("(MediaHandler mh, void * refcon) -> (ComponentResult _rv)")},
- {"MediaEnterEmptyEdit", (PyCFunction)Qt_MediaEnterEmptyEdit, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaCurrentMediaQueuedData", (PyCFunction)Qt_MediaCurrentMediaQueuedData, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long milliSecs)")},
- {"MediaGetEffectiveVolume", (PyCFunction)Qt_MediaGetEffectiveVolume, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short volume)")},
- {"MediaGetSoundLevelMeteringEnabled", (PyCFunction)Qt_MediaGetSoundLevelMeteringEnabled, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Boolean enabled)")},
- {"MediaSetSoundLevelMeteringEnabled", (PyCFunction)Qt_MediaSetSoundLevelMeteringEnabled, 1,
- PyDoc_STR("(MediaHandler mh, Boolean enable) -> (ComponentResult _rv)")},
- {"MediaGetEffectiveSoundBalance", (PyCFunction)Qt_MediaGetEffectiveSoundBalance, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short balance)")},
- {"MediaSetScreenLock", (PyCFunction)Qt_MediaSetScreenLock, 1,
- PyDoc_STR("(MediaHandler mh, Boolean lockIt) -> (ComponentResult _rv)")},
- {"MediaGetErrorString", (PyCFunction)Qt_MediaGetErrorString, 1,
- PyDoc_STR("(MediaHandler mh, ComponentResult theError, Str255 errorString) -> (ComponentResult _rv)")},
- {"MediaGetSoundEqualizerBandLevels", (PyCFunction)Qt_MediaGetSoundEqualizerBandLevels, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt8 bandLevels)")},
- {"MediaDoIdleActions", (PyCFunction)Qt_MediaDoIdleActions, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaSetSoundBassAndTreble", (PyCFunction)Qt_MediaSetSoundBassAndTreble, 1,
- PyDoc_STR("(MediaHandler mh, short bass, short treble) -> (ComponentResult _rv)")},
- {"MediaGetSoundBassAndTreble", (PyCFunction)Qt_MediaGetSoundBassAndTreble, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short bass, short treble)")},
- {"MediaTimeBaseChanged", (PyCFunction)Qt_MediaTimeBaseChanged, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
- {"MediaMCIsPlayerEvent", (PyCFunction)Qt_MediaMCIsPlayerEvent, 1,
- PyDoc_STR("(MediaHandler mh, EventRecord e) -> (ComponentResult _rv, Boolean handledIt)")},
- {"MediaGetMediaLoadState", (PyCFunction)Qt_MediaGetMediaLoadState, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long mediaLoadState)")},
- {"MediaVideoOutputChanged", (PyCFunction)Qt_MediaVideoOutputChanged, 1,
- PyDoc_STR("(MediaHandler mh, ComponentInstance vout) -> (ComponentResult _rv)")},
- {"MediaEmptySampleCache", (PyCFunction)Qt_MediaEmptySampleCache, 1,
- PyDoc_STR("(MediaHandler mh, long sampleNum, long sampleCount) -> (ComponentResult _rv)")},
- {"MediaGetPublicInfo", (PyCFunction)Qt_MediaGetPublicInfo, 1,
- PyDoc_STR("(MediaHandler mh, OSType infoSelector, void * infoDataPtr) -> (ComponentResult _rv, Size ioDataSize)")},
- {"MediaSetPublicInfo", (PyCFunction)Qt_MediaSetPublicInfo, 1,
- PyDoc_STR("(MediaHandler mh, OSType infoSelector, void * infoDataPtr, Size dataSize) -> (ComponentResult _rv)")},
- {"MediaRefConSetProperty", (PyCFunction)Qt_MediaRefConSetProperty, 1,
- PyDoc_STR("(MediaHandler mh, long refCon, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
- {"MediaRefConGetProperty", (PyCFunction)Qt_MediaRefConGetProperty, 1,
- PyDoc_STR("(MediaHandler mh, long refCon, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
- {"MediaNavigateTargetRefCon", (PyCFunction)Qt_MediaNavigateTargetRefCon, 1,
- PyDoc_STR("(MediaHandler mh, long navigation) -> (ComponentResult _rv, long refCon)")},
- {"MediaGGetIdleManager", (PyCFunction)Qt_MediaGGetIdleManager, 1,
- PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, IdleManager pim)")},
- {"MediaGSetIdleManager", (PyCFunction)Qt_MediaGSetIdleManager, 1,
- PyDoc_STR("(MediaHandler mh, IdleManager im) -> (ComponentResult _rv)")},
- {"QTMIDIGetMIDIPorts", (PyCFunction)Qt_QTMIDIGetMIDIPorts, 1,
- PyDoc_STR("(QTMIDIComponent ci) -> (ComponentResult _rv, QTMIDIPortListHandle inputPorts, QTMIDIPortListHandle outputPorts)")},
- {"QTMIDIUseSendPort", (PyCFunction)Qt_QTMIDIUseSendPort, 1,
- PyDoc_STR("(QTMIDIComponent ci, long portIndex, long inUse) -> (ComponentResult _rv)")},
- {"QTMIDISendMIDI", (PyCFunction)Qt_QTMIDISendMIDI, 1,
- PyDoc_STR("(QTMIDIComponent ci, long portIndex, MusicMIDIPacket mp) -> (ComponentResult _rv)")},
- {"MusicGetPart", (PyCFunction)Qt_MusicGetPart, 1,
- PyDoc_STR("(MusicComponent mc, long part) -> (ComponentResult _rv, long midiChannel, long polyphony)")},
- {"MusicSetPart", (PyCFunction)Qt_MusicSetPart, 1,
- PyDoc_STR("(MusicComponent mc, long part, long midiChannel, long polyphony) -> (ComponentResult _rv)")},
- {"MusicSetPartInstrumentNumber", (PyCFunction)Qt_MusicSetPartInstrumentNumber, 1,
- PyDoc_STR("(MusicComponent mc, long part, long instrumentNumber) -> (ComponentResult _rv)")},
- {"MusicGetPartInstrumentNumber", (PyCFunction)Qt_MusicGetPartInstrumentNumber, 1,
- PyDoc_STR("(MusicComponent mc, long part) -> (ComponentResult _rv)")},
- {"MusicStorePartInstrument", (PyCFunction)Qt_MusicStorePartInstrument, 1,
- PyDoc_STR("(MusicComponent mc, long part, long instrumentNumber) -> (ComponentResult _rv)")},
- {"MusicGetPartAtomicInstrument", (PyCFunction)Qt_MusicGetPartAtomicInstrument, 1,
- PyDoc_STR("(MusicComponent mc, long part, long flags) -> (ComponentResult _rv, AtomicInstrument ai)")},
- {"MusicSetPartAtomicInstrument", (PyCFunction)Qt_MusicSetPartAtomicInstrument, 1,
- PyDoc_STR("(MusicComponent mc, long part, AtomicInstrumentPtr aiP, long flags) -> (ComponentResult _rv)")},
- {"MusicGetPartKnob", (PyCFunction)Qt_MusicGetPartKnob, 1,
- PyDoc_STR("(MusicComponent mc, long part, long knobID) -> (ComponentResult _rv)")},
- {"MusicSetPartKnob", (PyCFunction)Qt_MusicSetPartKnob, 1,
- PyDoc_STR("(MusicComponent mc, long part, long knobID, long knobValue) -> (ComponentResult _rv)")},
- {"MusicGetKnob", (PyCFunction)Qt_MusicGetKnob, 1,
- PyDoc_STR("(MusicComponent mc, long knobID) -> (ComponentResult _rv)")},
- {"MusicSetKnob", (PyCFunction)Qt_MusicSetKnob, 1,
- PyDoc_STR("(MusicComponent mc, long knobID, long knobValue) -> (ComponentResult _rv)")},
- {"MusicGetPartName", (PyCFunction)Qt_MusicGetPartName, 1,
- PyDoc_STR("(MusicComponent mc, long part, StringPtr name) -> (ComponentResult _rv)")},
- {"MusicSetPartName", (PyCFunction)Qt_MusicSetPartName, 1,
- PyDoc_STR("(MusicComponent mc, long part, StringPtr name) -> (ComponentResult _rv)")},
- {"MusicPlayNote", (PyCFunction)Qt_MusicPlayNote, 1,
- PyDoc_STR("(MusicComponent mc, long part, long pitch, long velocity) -> (ComponentResult _rv)")},
- {"MusicResetPart", (PyCFunction)Qt_MusicResetPart, 1,
- PyDoc_STR("(MusicComponent mc, long part) -> (ComponentResult _rv)")},
- {"MusicSetPartController", (PyCFunction)Qt_MusicSetPartController, 1,
- PyDoc_STR("(MusicComponent mc, long part, MusicController controllerNumber, long controllerValue) -> (ComponentResult _rv)")},
- {"MusicGetPartController", (PyCFunction)Qt_MusicGetPartController, 1,
- PyDoc_STR("(MusicComponent mc, long part, MusicController controllerNumber) -> (ComponentResult _rv)")},
- {"MusicGetInstrumentNames", (PyCFunction)Qt_MusicGetInstrumentNames, 1,
- PyDoc_STR("(MusicComponent mc, long modifiableInstruments) -> (ComponentResult _rv, Handle instrumentNames, Handle instrumentCategoryLasts, Handle instrumentCategoryNames)")},
- {"MusicGetDrumNames", (PyCFunction)Qt_MusicGetDrumNames, 1,
- PyDoc_STR("(MusicComponent mc, long modifiableInstruments) -> (ComponentResult _rv, Handle instrumentNumbers, Handle instrumentNames)")},
- {"MusicGetMasterTune", (PyCFunction)Qt_MusicGetMasterTune, 1,
- PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv)")},
- {"MusicSetMasterTune", (PyCFunction)Qt_MusicSetMasterTune, 1,
- PyDoc_STR("(MusicComponent mc, long masterTune) -> (ComponentResult _rv)")},
- {"MusicGetDeviceConnection", (PyCFunction)Qt_MusicGetDeviceConnection, 1,
- PyDoc_STR("(MusicComponent mc, long index) -> (ComponentResult _rv, long id1, long id2)")},
- {"MusicUseDeviceConnection", (PyCFunction)Qt_MusicUseDeviceConnection, 1,
- PyDoc_STR("(MusicComponent mc, long id1, long id2) -> (ComponentResult _rv)")},
- {"MusicGetKnobSettingStrings", (PyCFunction)Qt_MusicGetKnobSettingStrings, 1,
- PyDoc_STR("(MusicComponent mc, long knobIndex, long isGlobal) -> (ComponentResult _rv, Handle settingsNames, Handle settingsCategoryLasts, Handle settingsCategoryNames)")},
- {"MusicGetMIDIPorts", (PyCFunction)Qt_MusicGetMIDIPorts, 1,
- PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv, long inputPortCount, long outputPortCount)")},
- {"MusicSendMIDI", (PyCFunction)Qt_MusicSendMIDI, 1,
- PyDoc_STR("(MusicComponent mc, long portIndex, MusicMIDIPacket mp) -> (ComponentResult _rv)")},
- {"MusicSetOfflineTimeTo", (PyCFunction)Qt_MusicSetOfflineTimeTo, 1,
- PyDoc_STR("(MusicComponent mc, long newTimeStamp) -> (ComponentResult _rv)")},
- {"MusicGetInfoText", (PyCFunction)Qt_MusicGetInfoText, 1,
- PyDoc_STR("(MusicComponent mc, long selector) -> (ComponentResult _rv, Handle textH, Handle styleH)")},
- {"MusicGetInstrumentInfo", (PyCFunction)Qt_MusicGetInstrumentInfo, 1,
- PyDoc_STR("(MusicComponent mc, long getInstrumentInfoFlags) -> (ComponentResult _rv, InstrumentInfoListHandle infoListH)")},
- {"MusicTask", (PyCFunction)Qt_MusicTask, 1,
- PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv)")},
- {"MusicSetPartInstrumentNumberInterruptSafe", (PyCFunction)Qt_MusicSetPartInstrumentNumberInterruptSafe, 1,
- PyDoc_STR("(MusicComponent mc, long part, long instrumentNumber) -> (ComponentResult _rv)")},
- {"MusicSetPartSoundLocalization", (PyCFunction)Qt_MusicSetPartSoundLocalization, 1,
- PyDoc_STR("(MusicComponent mc, long part, Handle data) -> (ComponentResult _rv)")},
- {"MusicGenericConfigure", (PyCFunction)Qt_MusicGenericConfigure, 1,
- PyDoc_STR("(MusicComponent mc, long mode, long flags, long baseResID) -> (ComponentResult _rv)")},
- {"MusicGenericGetKnobList", (PyCFunction)Qt_MusicGenericGetKnobList, 1,
- PyDoc_STR("(MusicComponent mc, long knobType) -> (ComponentResult _rv, GenericKnobDescriptionListHandle gkdlH)")},
- {"MusicGenericSetResourceNumbers", (PyCFunction)Qt_MusicGenericSetResourceNumbers, 1,
- PyDoc_STR("(MusicComponent mc, Handle resourceIDH) -> (ComponentResult _rv)")},
- {"MusicDerivedMIDISend", (PyCFunction)Qt_MusicDerivedMIDISend, 1,
- PyDoc_STR("(MusicComponent mc, MusicMIDIPacket packet) -> (ComponentResult _rv)")},
- {"MusicDerivedOpenResFile", (PyCFunction)Qt_MusicDerivedOpenResFile, 1,
- PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv)")},
- {"MusicDerivedCloseResFile", (PyCFunction)Qt_MusicDerivedCloseResFile, 1,
- PyDoc_STR("(MusicComponent mc, short resRefNum) -> (ComponentResult _rv)")},
- {"NAUnregisterMusicDevice", (PyCFunction)Qt_NAUnregisterMusicDevice, 1,
- PyDoc_STR("(NoteAllocator na, long index) -> (ComponentResult _rv)")},
- {"NASaveMusicConfiguration", (PyCFunction)Qt_NASaveMusicConfiguration, 1,
- PyDoc_STR("(NoteAllocator na) -> (ComponentResult _rv)")},
- {"NAGetMIDIPorts", (PyCFunction)Qt_NAGetMIDIPorts, 1,
- PyDoc_STR("(NoteAllocator na) -> (ComponentResult _rv, QTMIDIPortListHandle inputPorts, QTMIDIPortListHandle outputPorts)")},
- {"NATask", (PyCFunction)Qt_NATask, 1,
- PyDoc_STR("(NoteAllocator na) -> (ComponentResult _rv)")},
- {"TuneSetHeader", (PyCFunction)Qt_TuneSetHeader, 1,
- PyDoc_STR("(TunePlayer tp, unsigned long * header) -> (ComponentResult _rv)")},
- {"TuneGetTimeBase", (PyCFunction)Qt_TuneGetTimeBase, 1,
- PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv, TimeBase tb)")},
- {"TuneSetTimeScale", (PyCFunction)Qt_TuneSetTimeScale, 1,
- PyDoc_STR("(TunePlayer tp, TimeScale scale) -> (ComponentResult _rv)")},
- {"TuneGetTimeScale", (PyCFunction)Qt_TuneGetTimeScale, 1,
- PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv, TimeScale scale)")},
- {"TuneInstant", (PyCFunction)Qt_TuneInstant, 1,
- PyDoc_STR("(TunePlayer tp, unsigned long tunePosition) -> (ComponentResult _rv, unsigned long tune)")},
- {"TuneStop", (PyCFunction)Qt_TuneStop, 1,
- PyDoc_STR("(TunePlayer tp, long stopFlags) -> (ComponentResult _rv)")},
- {"TuneSetVolume", (PyCFunction)Qt_TuneSetVolume, 1,
- PyDoc_STR("(TunePlayer tp, Fixed volume) -> (ComponentResult _rv)")},
- {"TuneGetVolume", (PyCFunction)Qt_TuneGetVolume, 1,
- PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
- {"TunePreroll", (PyCFunction)Qt_TunePreroll, 1,
- PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
- {"TuneUnroll", (PyCFunction)Qt_TuneUnroll, 1,
- PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
- {"TuneSetPartTranspose", (PyCFunction)Qt_TuneSetPartTranspose, 1,
- PyDoc_STR("(TunePlayer tp, unsigned long part, long transpose, long velocityShift) -> (ComponentResult _rv)")},
- {"TuneGetNoteAllocator", (PyCFunction)Qt_TuneGetNoteAllocator, 1,
- PyDoc_STR("(TunePlayer tp) -> (NoteAllocator _rv)")},
- {"TuneSetSofter", (PyCFunction)Qt_TuneSetSofter, 1,
- PyDoc_STR("(TunePlayer tp, long softer) -> (ComponentResult _rv)")},
- {"TuneTask", (PyCFunction)Qt_TuneTask, 1,
- PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
- {"TuneSetBalance", (PyCFunction)Qt_TuneSetBalance, 1,
- PyDoc_STR("(TunePlayer tp, long balance) -> (ComponentResult _rv)")},
- {"TuneSetSoundLocalization", (PyCFunction)Qt_TuneSetSoundLocalization, 1,
- PyDoc_STR("(TunePlayer tp, Handle data) -> (ComponentResult _rv)")},
- {"TuneSetHeaderWithSize", (PyCFunction)Qt_TuneSetHeaderWithSize, 1,
- PyDoc_STR("(TunePlayer tp, unsigned long * header, unsigned long size) -> (ComponentResult _rv)")},
- {"TuneSetPartMix", (PyCFunction)Qt_TuneSetPartMix, 1,
- PyDoc_STR("(TunePlayer tp, unsigned long partNumber, long volume, long balance, long mixFlags) -> (ComponentResult _rv)")},
- {"TuneGetPartMix", (PyCFunction)Qt_TuneGetPartMix, 1,
- PyDoc_STR("(TunePlayer tp, unsigned long partNumber) -> (ComponentResult _rv, long volumeOut, long balanceOut, long mixFlagsOut)")},
- {"AlignWindow", (PyCFunction)Qt_AlignWindow, 1,
- PyDoc_STR("(WindowPtr wp, Boolean front) -> None")},
- {"DragAlignedWindow", (PyCFunction)Qt_DragAlignedWindow, 1,
- PyDoc_STR("(WindowPtr wp, Point startPt, Rect boundsRect) -> None")},
- {"MoviesTask", (PyCFunction)Qt_MoviesTask, 1,
- PyDoc_STR("(long maxMilliSecToUse) -> None")},
+ {"EnterMovies", (PyCFunction)Qt_EnterMovies, 1,
+ PyDoc_STR("() -> None")},
+ {"ExitMovies", (PyCFunction)Qt_ExitMovies, 1,
+ PyDoc_STR("() -> None")},
+ {"GetMoviesError", (PyCFunction)Qt_GetMoviesError, 1,
+ PyDoc_STR("() -> None")},
+ {"ClearMoviesStickyError", (PyCFunction)Qt_ClearMoviesStickyError, 1,
+ PyDoc_STR("() -> None")},
+ {"GetMoviesStickyError", (PyCFunction)Qt_GetMoviesStickyError, 1,
+ PyDoc_STR("() -> None")},
+ {"QTGetWallClockTimeBase", (PyCFunction)Qt_QTGetWallClockTimeBase, 1,
+ PyDoc_STR("() -> (TimeBase wallClockTimeBase)")},
+ {"QTIdleManagerOpen", (PyCFunction)Qt_QTIdleManagerOpen, 1,
+ PyDoc_STR("() -> (IdleManager _rv)")},
+ {"CreateMovieControl", (PyCFunction)Qt_CreateMovieControl, 1,
+ PyDoc_STR("(WindowPtr theWindow, Movie theMovie, UInt32 options) -> (Rect localRect, ControlHandle returnedControl)")},
+ {"DisposeMatte", (PyCFunction)Qt_DisposeMatte, 1,
+ PyDoc_STR("(PixMapHandle theMatte) -> None")},
+ {"NewMovie", (PyCFunction)Qt_NewMovie, 1,
+ PyDoc_STR("(long flags) -> (Movie _rv)")},
+ {"QTGetTimeUntilNextTask", (PyCFunction)Qt_QTGetTimeUntilNextTask, 1,
+ PyDoc_STR("(long scale) -> (long duration)")},
+ {"GetDataHandler", (PyCFunction)Qt_GetDataHandler, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataHandlerSubType, long flags) -> (Component _rv)")},
+ {"PasteHandleIntoMovie", (PyCFunction)Qt_PasteHandleIntoMovie, 1,
+ PyDoc_STR("(Handle h, OSType handleType, Movie theMovie, long flags, ComponentInstance userComp) -> None")},
+ {"GetMovieImporterForDataRef", (PyCFunction)Qt_GetMovieImporterForDataRef, 1,
+ PyDoc_STR("(OSType dataRefType, Handle dataRef, long flags) -> (Component importer)")},
+ {"QTGetMIMETypeInfo", (PyCFunction)Qt_QTGetMIMETypeInfo, 1,
+ PyDoc_STR("(char* mimeStringStart, short mimeStringLength, OSType infoSelector, void * infoDataPtr) -> (long infoDataSize)")},
+ {"TrackTimeToMediaTime", (PyCFunction)Qt_TrackTimeToMediaTime, 1,
+ PyDoc_STR("(TimeValue value, Track theTrack) -> (TimeValue _rv)")},
+ {"NewUserData", (PyCFunction)Qt_NewUserData, 1,
+ PyDoc_STR("() -> (UserData theUserData)")},
+ {"NewUserDataFromHandle", (PyCFunction)Qt_NewUserDataFromHandle, 1,
+ PyDoc_STR("(Handle h) -> (UserData theUserData)")},
+ {"CreateMovieFile", (PyCFunction)Qt_CreateMovieFile, 1,
+ PyDoc_STR("(FSSpec fileSpec, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (short resRefNum, Movie newmovie)")},
+ {"OpenMovieFile", (PyCFunction)Qt_OpenMovieFile, 1,
+ PyDoc_STR("(FSSpec fileSpec, SInt8 permission) -> (short resRefNum)")},
+ {"CloseMovieFile", (PyCFunction)Qt_CloseMovieFile, 1,
+ PyDoc_STR("(short resRefNum) -> None")},
+ {"DeleteMovieFile", (PyCFunction)Qt_DeleteMovieFile, 1,
+ PyDoc_STR("(FSSpec fileSpec) -> None")},
+ {"NewMovieFromFile", (PyCFunction)Qt_NewMovieFromFile, 1,
+ PyDoc_STR("(short resRefNum, short resId, short newMovieFlags) -> (Movie theMovie, short resId, Boolean dataRefWasChanged)")},
+ {"NewMovieFromHandle", (PyCFunction)Qt_NewMovieFromHandle, 1,
+ PyDoc_STR("(Handle h, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasChanged)")},
+ {"NewMovieFromDataFork", (PyCFunction)Qt_NewMovieFromDataFork, 1,
+ PyDoc_STR("(short fRefNum, long fileOffset, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasChanged)")},
+ {"NewMovieFromDataFork64", (PyCFunction)Qt_NewMovieFromDataFork64, 1,
+ PyDoc_STR("(long fRefNum, wide fileOffset, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasChanged)")},
+ {"NewMovieFromDataRef", (PyCFunction)Qt_NewMovieFromDataRef, 1,
+ PyDoc_STR("(short flags, Handle dataRef, OSType dtaRefType) -> (Movie m, short id)")},
+ {"NewMovieFromStorageOffset", (PyCFunction)Qt_NewMovieFromStorageOffset, 1,
+ PyDoc_STR("(DataHandler dh, wide fileOffset, short newMovieFlags) -> (Movie theMovie, Boolean dataRefWasCataRefType)")},
+ {"NewMovieForDataRefFromHandle", (PyCFunction)Qt_NewMovieForDataRefFromHandle, 1,
+ PyDoc_STR("(Handle h, short newMovieFlags, Handle dataRef, OSType dataRefType) -> (Movie theMovie, Boolean dataRefWasChanged)")},
+ {"RemoveMovieResource", (PyCFunction)Qt_RemoveMovieResource, 1,
+ PyDoc_STR("(short resRefNum, short resId) -> None")},
+ {"CreateMovieStorage", (PyCFunction)Qt_CreateMovieStorage, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType, OSType creator, ScriptCode scriptTag, long createMovieFileFlags) -> (DataHandler outDataHandler, Movie newmovie)")},
+ {"OpenMovieStorage", (PyCFunction)Qt_OpenMovieStorage, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType, long flags) -> (DataHandler outDataHandler)")},
+ {"CloseMovieStorage", (PyCFunction)Qt_CloseMovieStorage, 1,
+ PyDoc_STR("(DataHandler dh) -> None")},
+ {"DeleteMovieStorage", (PyCFunction)Qt_DeleteMovieStorage, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType) -> None")},
+ {"CreateShortcutMovieFile", (PyCFunction)Qt_CreateShortcutMovieFile, 1,
+ PyDoc_STR("(FSSpec fileSpec, OSType creator, ScriptCode scriptTag, long createMovieFileFlags, Handle targetDataRef, OSType targetDataRefType) -> None")},
+ {"CanQuickTimeOpenFile", (PyCFunction)Qt_CanQuickTimeOpenFile, 1,
+ PyDoc_STR("(FSSpec fileSpec, OSType fileType, OSType fileNameExtension, UInt32 inFlags) -> (Boolean outCanOpenWithGraphicsImporter, Boolean outCanOpenAsMovie, Boolean outPreferGraphicsImporter)")},
+ {"CanQuickTimeOpenDataRef", (PyCFunction)Qt_CanQuickTimeOpenDataRef, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType, UInt32 inFlags) -> (Boolean outCanOpenWithGraphicsImporter, Boolean outCanOpenAsMovie, Boolean outPreferGraphicsImporter)")},
+ {"NewMovieFromScrap", (PyCFunction)Qt_NewMovieFromScrap, 1,
+ PyDoc_STR("(long newMovieFlags) -> (Movie _rv)")},
+ {"QTNewAlias", (PyCFunction)Qt_QTNewAlias, 1,
+ PyDoc_STR("(FSSpec fss, Boolean minimal) -> (AliasHandle alias)")},
+ {"EndFullScreen", (PyCFunction)Qt_EndFullScreen, 1,
+ PyDoc_STR("(Ptr fullState, long flags) -> None")},
+ {"AddSoundDescriptionExtension", (PyCFunction)Qt_AddSoundDescriptionExtension, 1,
+ PyDoc_STR("(SoundDescriptionHandle desc, Handle extension, OSType idType) -> None")},
+ {"GetSoundDescriptionExtension", (PyCFunction)Qt_GetSoundDescriptionExtension, 1,
+ PyDoc_STR("(SoundDescriptionHandle desc, OSType idType) -> (Handle extension)")},
+ {"RemoveSoundDescriptionExtension", (PyCFunction)Qt_RemoveSoundDescriptionExtension, 1,
+ PyDoc_STR("(SoundDescriptionHandle desc, OSType idType) -> None")},
+ {"QTIsStandardParameterDialogEvent", (PyCFunction)Qt_QTIsStandardParameterDialogEvent, 1,
+ PyDoc_STR("(QTParameterDialog createdDialog) -> (EventRecord pEvent)")},
+ {"QTDismissStandardParameterDialog", (PyCFunction)Qt_QTDismissStandardParameterDialog, 1,
+ PyDoc_STR("(QTParameterDialog createdDialog) -> None")},
+ {"QTStandardParameterDialogDoAction", (PyCFunction)Qt_QTStandardParameterDialogDoAction, 1,
+ PyDoc_STR("(QTParameterDialog createdDialog, long action, void * params) -> None")},
+ {"QTRegisterAccessKey", (PyCFunction)Qt_QTRegisterAccessKey, 1,
+ PyDoc_STR("(Str255 accessKeyType, long flags, Handle accessKey) -> None")},
+ {"QTUnregisterAccessKey", (PyCFunction)Qt_QTUnregisterAccessKey, 1,
+ PyDoc_STR("(Str255 accessKeyType, long flags, Handle accessKey) -> None")},
+ {"QTGetSupportedRestrictions", (PyCFunction)Qt_QTGetSupportedRestrictions, 1,
+ PyDoc_STR("(OSType inRestrictionClass) -> (UInt32 outRestrictionIDs)")},
+ {"QTTextToNativeText", (PyCFunction)Qt_QTTextToNativeText, 1,
+ PyDoc_STR("(Handle theText, long encoding, long flags) -> None")},
+ {"VideoMediaResetStatistics", (PyCFunction)Qt_VideoMediaResetStatistics, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"VideoMediaGetStatistics", (PyCFunction)Qt_VideoMediaGetStatistics, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"VideoMediaGetStallCount", (PyCFunction)Qt_VideoMediaGetStallCount, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, unsigned long stalls)")},
+ {"VideoMediaSetCodecParameter", (PyCFunction)Qt_VideoMediaSetCodecParameter, 1,
+ PyDoc_STR("(MediaHandler mh, CodecType cType, OSType parameterID, long parameterChangeSeed, void * dataPtr, long dataSize) -> (ComponentResult _rv)")},
+ {"VideoMediaGetCodecParameter", (PyCFunction)Qt_VideoMediaGetCodecParameter, 1,
+ PyDoc_STR("(MediaHandler mh, CodecType cType, OSType parameterID, Handle outParameterData) -> (ComponentResult _rv)")},
+ {"TextMediaAddTextSample", (PyCFunction)Qt_TextMediaAddTextSample, 1,
+ PyDoc_STR("(MediaHandler mh, Ptr text, unsigned long size, short fontNumber, short fontSize, Style textFace, short textJustification, long displayFlags, TimeValue scrollDelay, short hiliteStart, short hiliteEnd, TimeValue duration) -> (ComponentResult _rv, RGBColor textColor, RGBColor backColor, Rect textBox, RGBColor rgbHiliteColor, TimeValue sampleTime)")},
+ {"TextMediaAddTESample", (PyCFunction)Qt_TextMediaAddTESample, 1,
+ PyDoc_STR("(MediaHandler mh, TEHandle hTE, short textJustification, long displayFlags, TimeValue scrollDelay, short hiliteStart, short hiliteEnd, TimeValue duration) -> (ComponentResult _rv, RGBColor backColor, Rect textBox, RGBColor rgbHiliteColor, TimeValue sampleTime)")},
+ {"TextMediaAddHiliteSample", (PyCFunction)Qt_TextMediaAddHiliteSample, 1,
+ PyDoc_STR("(MediaHandler mh, short hiliteStart, short hiliteEnd, TimeValue duration) -> (ComponentResult _rv, RGBColor rgbHiliteColor, TimeValue sampleTime)")},
+ {"TextMediaDrawRaw", (PyCFunction)Qt_TextMediaDrawRaw, 1,
+ PyDoc_STR("(MediaHandler mh, GWorldPtr gw, GDHandle gd, void * data, long dataSize, TextDescriptionHandle tdh) -> (ComponentResult _rv)")},
+ {"TextMediaSetTextProperty", (PyCFunction)Qt_TextMediaSetTextProperty, 1,
+ PyDoc_STR("(MediaHandler mh, TimeValue atMediaTime, long propertyType, void * data, long dataSize) -> (ComponentResult _rv)")},
+ {"TextMediaRawSetup", (PyCFunction)Qt_TextMediaRawSetup, 1,
+ PyDoc_STR("(MediaHandler mh, GWorldPtr gw, GDHandle gd, void * data, long dataSize, TextDescriptionHandle tdh, TimeValue sampleDuration) -> (ComponentResult _rv)")},
+ {"TextMediaRawIdle", (PyCFunction)Qt_TextMediaRawIdle, 1,
+ PyDoc_STR("(MediaHandler mh, GWorldPtr gw, GDHandle gd, TimeValue sampleTime, long flagsIn) -> (ComponentResult _rv, long flagsOut)")},
+ {"TextMediaGetTextProperty", (PyCFunction)Qt_TextMediaGetTextProperty, 1,
+ PyDoc_STR("(MediaHandler mh, TimeValue atMediaTime, long propertyType, void * data, long dataSize) -> (ComponentResult _rv)")},
+ {"TextMediaFindNextText", (PyCFunction)Qt_TextMediaFindNextText, 1,
+ PyDoc_STR("(MediaHandler mh, Ptr text, long size, short findFlags, TimeValue startTime) -> (ComponentResult _rv, TimeValue foundTime, TimeValue foundDuration, long offset)")},
+ {"TextMediaHiliteTextSample", (PyCFunction)Qt_TextMediaHiliteTextSample, 1,
+ PyDoc_STR("(MediaHandler mh, TimeValue sampleTime, short hiliteStart, short hiliteEnd) -> (ComponentResult _rv, RGBColor rgbHiliteColor)")},
+ {"TextMediaSetTextSampleData", (PyCFunction)Qt_TextMediaSetTextSampleData, 1,
+ PyDoc_STR("(MediaHandler mh, void * data, OSType dataType) -> (ComponentResult _rv)")},
+ {"SpriteMediaSetProperty", (PyCFunction)Qt_SpriteMediaSetProperty, 1,
+ PyDoc_STR("(MediaHandler mh, short spriteIndex, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
+ {"SpriteMediaGetProperty", (PyCFunction)Qt_SpriteMediaGetProperty, 1,
+ PyDoc_STR("(MediaHandler mh, short spriteIndex, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
+ {"SpriteMediaHitTestSprites", (PyCFunction)Qt_SpriteMediaHitTestSprites, 1,
+ PyDoc_STR("(MediaHandler mh, long flags, Point loc) -> (ComponentResult _rv, short spriteHitIndex)")},
+ {"SpriteMediaCountSprites", (PyCFunction)Qt_SpriteMediaCountSprites, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short numSprites)")},
+ {"SpriteMediaCountImages", (PyCFunction)Qt_SpriteMediaCountImages, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short numImages)")},
+ {"SpriteMediaGetIndImageDescription", (PyCFunction)Qt_SpriteMediaGetIndImageDescription, 1,
+ PyDoc_STR("(MediaHandler mh, short imageIndex, ImageDescriptionHandle imageDescription) -> (ComponentResult _rv)")},
+ {"SpriteMediaGetDisplayedSampleNumber", (PyCFunction)Qt_SpriteMediaGetDisplayedSampleNumber, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long sampleNum)")},
+ {"SpriteMediaGetSpriteName", (PyCFunction)Qt_SpriteMediaGetSpriteName, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, Str255 spriteName) -> (ComponentResult _rv)")},
+ {"SpriteMediaGetImageName", (PyCFunction)Qt_SpriteMediaGetImageName, 1,
+ PyDoc_STR("(MediaHandler mh, short imageIndex, Str255 imageName) -> (ComponentResult _rv)")},
+ {"SpriteMediaSetSpriteProperty", (PyCFunction)Qt_SpriteMediaSetSpriteProperty, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
+ {"SpriteMediaGetSpriteProperty", (PyCFunction)Qt_SpriteMediaGetSpriteProperty, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
+ {"SpriteMediaHitTestAllSprites", (PyCFunction)Qt_SpriteMediaHitTestAllSprites, 1,
+ PyDoc_STR("(MediaHandler mh, long flags, Point loc) -> (ComponentResult _rv, QTAtomID spriteHitID)")},
+ {"SpriteMediaHitTestOneSprite", (PyCFunction)Qt_SpriteMediaHitTestOneSprite, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID spriteID, long flags, Point loc) -> (ComponentResult _rv, Boolean wasHit)")},
+ {"SpriteMediaSpriteIndexToID", (PyCFunction)Qt_SpriteMediaSpriteIndexToID, 1,
+ PyDoc_STR("(MediaHandler mh, short spriteIndex) -> (ComponentResult _rv, QTAtomID spriteID)")},
+ {"SpriteMediaSpriteIDToIndex", (PyCFunction)Qt_SpriteMediaSpriteIDToIndex, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID spriteID) -> (ComponentResult _rv, short spriteIndex)")},
+ {"SpriteMediaSetActionVariable", (PyCFunction)Qt_SpriteMediaSetActionVariable, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID variableID, float value) -> (ComponentResult _rv)")},
+ {"SpriteMediaGetActionVariable", (PyCFunction)Qt_SpriteMediaGetActionVariable, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID variableID) -> (ComponentResult _rv, float value)")},
+ {"SpriteMediaDisposeSprite", (PyCFunction)Qt_SpriteMediaDisposeSprite, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID spriteID) -> (ComponentResult _rv)")},
+ {"SpriteMediaSetActionVariableToString", (PyCFunction)Qt_SpriteMediaSetActionVariableToString, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID variableID, Ptr theCString) -> (ComponentResult _rv)")},
+ {"SpriteMediaGetActionVariableAsString", (PyCFunction)Qt_SpriteMediaGetActionVariableAsString, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID variableID) -> (ComponentResult _rv, Handle theCString)")},
+ {"SpriteMediaNewImage", (PyCFunction)Qt_SpriteMediaNewImage, 1,
+ PyDoc_STR("(MediaHandler mh, Handle dataRef, OSType dataRefType, QTAtomID desiredID) -> (ComponentResult _rv)")},
+ {"SpriteMediaDisposeImage", (PyCFunction)Qt_SpriteMediaDisposeImage, 1,
+ PyDoc_STR("(MediaHandler mh, short imageIndex) -> (ComponentResult _rv)")},
+ {"SpriteMediaImageIndexToID", (PyCFunction)Qt_SpriteMediaImageIndexToID, 1,
+ PyDoc_STR("(MediaHandler mh, short imageIndex) -> (ComponentResult _rv, QTAtomID imageID)")},
+ {"SpriteMediaImageIDToIndex", (PyCFunction)Qt_SpriteMediaImageIDToIndex, 1,
+ PyDoc_STR("(MediaHandler mh, QTAtomID imageID) -> (ComponentResult _rv, short imageIndex)")},
+ {"FlashMediaSetPan", (PyCFunction)Qt_FlashMediaSetPan, 1,
+ PyDoc_STR("(MediaHandler mh, short xPercent, short yPercent) -> (ComponentResult _rv)")},
+ {"FlashMediaSetZoom", (PyCFunction)Qt_FlashMediaSetZoom, 1,
+ PyDoc_STR("(MediaHandler mh, short factor) -> (ComponentResult _rv)")},
+ {"FlashMediaSetZoomRect", (PyCFunction)Qt_FlashMediaSetZoomRect, 1,
+ PyDoc_STR("(MediaHandler mh, long left, long top, long right, long bottom) -> (ComponentResult _rv)")},
+ {"FlashMediaGetRefConBounds", (PyCFunction)Qt_FlashMediaGetRefConBounds, 1,
+ PyDoc_STR("(MediaHandler mh, long refCon) -> (ComponentResult _rv, long left, long top, long right, long bottom)")},
+ {"FlashMediaGetRefConID", (PyCFunction)Qt_FlashMediaGetRefConID, 1,
+ PyDoc_STR("(MediaHandler mh, long refCon) -> (ComponentResult _rv, long refConID)")},
+ {"FlashMediaIDToRefCon", (PyCFunction)Qt_FlashMediaIDToRefCon, 1,
+ PyDoc_STR("(MediaHandler mh, long refConID) -> (ComponentResult _rv, long refCon)")},
+ {"FlashMediaGetDisplayedFrameNumber", (PyCFunction)Qt_FlashMediaGetDisplayedFrameNumber, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long flashFrameNumber)")},
+ {"FlashMediaFrameNumberToMovieTime", (PyCFunction)Qt_FlashMediaFrameNumberToMovieTime, 1,
+ PyDoc_STR("(MediaHandler mh, long flashFrameNumber) -> (ComponentResult _rv, TimeValue movieTime)")},
+ {"FlashMediaFrameLabelToMovieTime", (PyCFunction)Qt_FlashMediaFrameLabelToMovieTime, 1,
+ PyDoc_STR("(MediaHandler mh, Ptr theLabel) -> (ComponentResult _rv, TimeValue movieTime)")},
+ {"FlashMediaGetFlashVariable", (PyCFunction)Qt_FlashMediaGetFlashVariable, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, char path, char name, Handle theVariableCStringOut)")},
+ {"FlashMediaSetFlashVariable", (PyCFunction)Qt_FlashMediaSetFlashVariable, 1,
+ PyDoc_STR("(MediaHandler mh, Boolean updateFocus) -> (ComponentResult _rv, char path, char name, char value)")},
+ {"FlashMediaDoButtonActions", (PyCFunction)Qt_FlashMediaDoButtonActions, 1,
+ PyDoc_STR("(MediaHandler mh, long buttonID, long transition) -> (ComponentResult _rv, char path)")},
+ {"FlashMediaGetSupportedSwfVersion", (PyCFunction)Qt_FlashMediaGetSupportedSwfVersion, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt8 swfVersion)")},
+ {"Media3DGetCurrentGroup", (PyCFunction)Qt_Media3DGetCurrentGroup, 1,
+ PyDoc_STR("(MediaHandler mh, void * group) -> (ComponentResult _rv)")},
+ {"Media3DTranslateNamedObjectTo", (PyCFunction)Qt_Media3DTranslateNamedObjectTo, 1,
+ PyDoc_STR("(MediaHandler mh, Fixed x, Fixed y, Fixed z) -> (ComponentResult _rv, char objectName)")},
+ {"Media3DScaleNamedObjectTo", (PyCFunction)Qt_Media3DScaleNamedObjectTo, 1,
+ PyDoc_STR("(MediaHandler mh, Fixed xScale, Fixed yScale, Fixed zScale) -> (ComponentResult _rv, char objectName)")},
+ {"Media3DRotateNamedObjectTo", (PyCFunction)Qt_Media3DRotateNamedObjectTo, 1,
+ PyDoc_STR("(MediaHandler mh, Fixed xDegrees, Fixed yDegrees, Fixed zDegrees) -> (ComponentResult _rv, char objectName)")},
+ {"Media3DSetCameraData", (PyCFunction)Qt_Media3DSetCameraData, 1,
+ PyDoc_STR("(MediaHandler mh, void * cameraData) -> (ComponentResult _rv)")},
+ {"Media3DGetCameraData", (PyCFunction)Qt_Media3DGetCameraData, 1,
+ PyDoc_STR("(MediaHandler mh, void * cameraData) -> (ComponentResult _rv)")},
+ {"Media3DSetCameraAngleAspect", (PyCFunction)Qt_Media3DSetCameraAngleAspect, 1,
+ PyDoc_STR("(MediaHandler mh, QTFloatSingle fov, QTFloatSingle aspectRatioXToY) -> (ComponentResult _rv)")},
+ {"Media3DGetCameraAngleAspect", (PyCFunction)Qt_Media3DGetCameraAngleAspect, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, QTFloatSingle fov, QTFloatSingle aspectRatioXToY)")},
+ {"Media3DSetCameraRange", (PyCFunction)Qt_Media3DSetCameraRange, 1,
+ PyDoc_STR("(MediaHandler mh, void * tQ3CameraRange) -> (ComponentResult _rv)")},
+ {"Media3DGetCameraRange", (PyCFunction)Qt_Media3DGetCameraRange, 1,
+ PyDoc_STR("(MediaHandler mh, void * tQ3CameraRange) -> (ComponentResult _rv)")},
+ {"NewTimeBase", (PyCFunction)Qt_NewTimeBase, 1,
+ PyDoc_STR("() -> (TimeBase _rv)")},
+ {"ConvertTime", (PyCFunction)Qt_ConvertTime, 1,
+ PyDoc_STR("(TimeRecord theTime, TimeBase newBase) -> (TimeRecord theTime)")},
+ {"ConvertTimeScale", (PyCFunction)Qt_ConvertTimeScale, 1,
+ PyDoc_STR("(TimeRecord theTime, TimeScale newScale) -> (TimeRecord theTime)")},
+ {"AddTime", (PyCFunction)Qt_AddTime, 1,
+ PyDoc_STR("(TimeRecord dst, TimeRecord src) -> (TimeRecord dst)")},
+ {"SubtractTime", (PyCFunction)Qt_SubtractTime, 1,
+ PyDoc_STR("(TimeRecord dst, TimeRecord src) -> (TimeRecord dst)")},
+ {"MusicMediaGetIndexedTunePlayer", (PyCFunction)Qt_MusicMediaGetIndexedTunePlayer, 1,
+ PyDoc_STR("(ComponentInstance ti, long sampleDescIndex) -> (ComponentResult _rv, ComponentInstance tp)")},
+ {"CodecManagerVersion", (PyCFunction)Qt_CodecManagerVersion, 1,
+ PyDoc_STR("() -> (long version)")},
+ {"GetMaxCompressionSize", (PyCFunction)Qt_GetMaxCompressionSize, 1,
+ PyDoc_STR("(PixMapHandle src, Rect srcRect, short colorDepth, CodecQ quality, CodecType cType, CompressorComponent codec) -> (long size)")},
+ {"GetCompressionTime", (PyCFunction)Qt_GetCompressionTime, 1,
+ PyDoc_STR("(PixMapHandle src, Rect srcRect, short colorDepth, CodecType cType, CompressorComponent codec) -> (CodecQ spatialQuality, CodecQ temporalQuality, unsigned long compressTime)")},
+ {"CompressImage", (PyCFunction)Qt_CompressImage, 1,
+ PyDoc_STR("(PixMapHandle src, Rect srcRect, CodecQ quality, CodecType cType, ImageDescriptionHandle desc, Ptr data) -> None")},
+ {"DecompressImage", (PyCFunction)Qt_DecompressImage, 1,
+ PyDoc_STR("(Ptr data, ImageDescriptionHandle desc, PixMapHandle dst, Rect srcRect, Rect dstRect, short mode, RgnHandle mask) -> None")},
+ {"GetSimilarity", (PyCFunction)Qt_GetSimilarity, 1,
+ PyDoc_STR("(PixMapHandle src, Rect srcRect, ImageDescriptionHandle desc, Ptr data) -> (Fixed similarity)")},
+ {"GetImageDescriptionCTable", (PyCFunction)Qt_GetImageDescriptionCTable, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc) -> (CTabHandle ctable)")},
+ {"SetImageDescriptionCTable", (PyCFunction)Qt_SetImageDescriptionCTable, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc, CTabHandle ctable) -> None")},
+ {"GetImageDescriptionExtension", (PyCFunction)Qt_GetImageDescriptionExtension, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc, long idType, long index) -> (Handle extension)")},
+ {"AddImageDescriptionExtension", (PyCFunction)Qt_AddImageDescriptionExtension, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc, Handle extension, long idType) -> None")},
+ {"RemoveImageDescriptionExtension", (PyCFunction)Qt_RemoveImageDescriptionExtension, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc, long idType, long index) -> None")},
+ {"CountImageDescriptionExtensionType", (PyCFunction)Qt_CountImageDescriptionExtensionType, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc, long idType) -> (long count)")},
+ {"GetNextImageDescriptionExtensionType", (PyCFunction)Qt_GetNextImageDescriptionExtensionType, 1,
+ PyDoc_STR("(ImageDescriptionHandle desc) -> (long idType)")},
+ {"FindCodec", (PyCFunction)Qt_FindCodec, 1,
+ PyDoc_STR("(CodecType cType, CodecComponent specCodec) -> (CompressorComponent compressor, DecompressorComponent decompressor)")},
+ {"CompressPicture", (PyCFunction)Qt_CompressPicture, 1,
+ PyDoc_STR("(PicHandle srcPicture, PicHandle dstPicture, CodecQ quality, CodecType cType) -> None")},
+ {"CompressPictureFile", (PyCFunction)Qt_CompressPictureFile, 1,
+ PyDoc_STR("(short srcRefNum, short dstRefNum, CodecQ quality, CodecType cType) -> None")},
+ {"ConvertImage", (PyCFunction)Qt_ConvertImage, 1,
+ PyDoc_STR("(ImageDescriptionHandle srcDD, Ptr srcData, short colorDepth, CTabHandle ctable, CodecQ accuracy, CodecQ quality, CodecType cType, CodecComponent codec, ImageDescriptionHandle dstDD, Ptr dstData) -> None")},
+ {"AddFilePreview", (PyCFunction)Qt_AddFilePreview, 1,
+ PyDoc_STR("(short resRefNum, OSType previewType, Handle previewData) -> None")},
+ {"GetBestDeviceRect", (PyCFunction)Qt_GetBestDeviceRect, 1,
+ PyDoc_STR("() -> (GDHandle gdh, Rect rp)")},
+ {"GDHasScale", (PyCFunction)Qt_GDHasScale, 1,
+ PyDoc_STR("(GDHandle gdh, short depth) -> (Fixed scale)")},
+ {"GDGetScale", (PyCFunction)Qt_GDGetScale, 1,
+ PyDoc_STR("(GDHandle gdh) -> (Fixed scale, short flags)")},
+ {"GDSetScale", (PyCFunction)Qt_GDSetScale, 1,
+ PyDoc_STR("(GDHandle gdh, Fixed scale, short flags) -> None")},
+ {"GetGraphicsImporterForFile", (PyCFunction)Qt_GetGraphicsImporterForFile, 1,
+ PyDoc_STR("(FSSpec theFile) -> (ComponentInstance gi)")},
+ {"GetGraphicsImporterForDataRef", (PyCFunction)Qt_GetGraphicsImporterForDataRef, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType) -> (ComponentInstance gi)")},
+ {"GetGraphicsImporterForFileWithFlags", (PyCFunction)Qt_GetGraphicsImporterForFileWithFlags, 1,
+ PyDoc_STR("(FSSpec theFile, long flags) -> (ComponentInstance gi)")},
+ {"GetGraphicsImporterForDataRefWithFlags", (PyCFunction)Qt_GetGraphicsImporterForDataRefWithFlags, 1,
+ PyDoc_STR("(Handle dataRef, OSType dataRefType, long flags) -> (ComponentInstance gi)")},
+ {"MakeImageDescriptionForPixMap", (PyCFunction)Qt_MakeImageDescriptionForPixMap, 1,
+ PyDoc_STR("(PixMapHandle pixmap) -> (ImageDescriptionHandle idh)")},
+ {"MakeImageDescriptionForEffect", (PyCFunction)Qt_MakeImageDescriptionForEffect, 1,
+ PyDoc_STR("(OSType effectType) -> (ImageDescriptionHandle idh)")},
+ {"QTGetPixelSize", (PyCFunction)Qt_QTGetPixelSize, 1,
+ PyDoc_STR("(OSType PixelFormat) -> (short _rv)")},
+ {"QTGetPixelFormatDepthForImageDescription", (PyCFunction)Qt_QTGetPixelFormatDepthForImageDescription, 1,
+ PyDoc_STR("(OSType PixelFormat) -> (short _rv)")},
+ {"QTGetPixMapHandleRowBytes", (PyCFunction)Qt_QTGetPixMapHandleRowBytes, 1,
+ PyDoc_STR("(PixMapHandle pm) -> (long _rv)")},
+ {"QTSetPixMapHandleRowBytes", (PyCFunction)Qt_QTSetPixMapHandleRowBytes, 1,
+ PyDoc_STR("(PixMapHandle pm, long rowBytes) -> None")},
+ {"QTGetPixMapHandleGammaLevel", (PyCFunction)Qt_QTGetPixMapHandleGammaLevel, 1,
+ PyDoc_STR("(PixMapHandle pm) -> (Fixed _rv)")},
+ {"QTSetPixMapHandleGammaLevel", (PyCFunction)Qt_QTSetPixMapHandleGammaLevel, 1,
+ PyDoc_STR("(PixMapHandle pm, Fixed gammaLevel) -> None")},
+ {"QTGetPixMapHandleRequestedGammaLevel", (PyCFunction)Qt_QTGetPixMapHandleRequestedGammaLevel, 1,
+ PyDoc_STR("(PixMapHandle pm) -> (Fixed _rv)")},
+ {"QTSetPixMapHandleRequestedGammaLevel", (PyCFunction)Qt_QTSetPixMapHandleRequestedGammaLevel, 1,
+ PyDoc_STR("(PixMapHandle pm, Fixed requestedGammaLevel) -> None")},
+ {"CompAdd", (PyCFunction)Qt_CompAdd, 1,
+ PyDoc_STR("() -> (wide src, wide dst)")},
+ {"CompSub", (PyCFunction)Qt_CompSub, 1,
+ PyDoc_STR("() -> (wide src, wide dst)")},
+ {"CompNeg", (PyCFunction)Qt_CompNeg, 1,
+ PyDoc_STR("() -> (wide dst)")},
+ {"CompShift", (PyCFunction)Qt_CompShift, 1,
+ PyDoc_STR("(short shift) -> (wide src)")},
+ {"CompMul", (PyCFunction)Qt_CompMul, 1,
+ PyDoc_STR("(long src1, long src2) -> (wide dst)")},
+ {"CompDiv", (PyCFunction)Qt_CompDiv, 1,
+ PyDoc_STR("(long denominator) -> (long _rv, wide numerator, long remainder)")},
+ {"CompFixMul", (PyCFunction)Qt_CompFixMul, 1,
+ PyDoc_STR("(Fixed fixSrc) -> (wide compSrc, wide compDst)")},
+ {"CompMulDiv", (PyCFunction)Qt_CompMulDiv, 1,
+ PyDoc_STR("(long mul, long divisor) -> (wide co)")},
+ {"CompMulDivTrunc", (PyCFunction)Qt_CompMulDivTrunc, 1,
+ PyDoc_STR("(long mul, long divisor) -> (wide co, long remainder)")},
+ {"CompCompare", (PyCFunction)Qt_CompCompare, 1,
+ PyDoc_STR("(wide a, wide minusb) -> (long _rv)")},
+ {"CompSquareRoot", (PyCFunction)Qt_CompSquareRoot, 1,
+ PyDoc_STR("(wide src) -> (unsigned long _rv)")},
+ {"FixMulDiv", (PyCFunction)Qt_FixMulDiv, 1,
+ PyDoc_STR("(Fixed src, Fixed mul, Fixed divisor) -> (Fixed _rv)")},
+ {"UnsignedFixMulDiv", (PyCFunction)Qt_UnsignedFixMulDiv, 1,
+ PyDoc_STR("(Fixed src, Fixed mul, Fixed divisor) -> (Fixed _rv)")},
+ {"FixExp2", (PyCFunction)Qt_FixExp2, 1,
+ PyDoc_STR("(Fixed src) -> (Fixed _rv)")},
+ {"FixLog2", (PyCFunction)Qt_FixLog2, 1,
+ PyDoc_STR("(Fixed src) -> (Fixed _rv)")},
+ {"FixPow", (PyCFunction)Qt_FixPow, 1,
+ PyDoc_STR("(Fixed base, Fixed exp) -> (Fixed _rv)")},
+ {"GraphicsImportSetDataReference", (PyCFunction)Qt_GraphicsImportSetDataReference, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, Handle dataRef, OSType dataReType) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetDataReference", (PyCFunction)Qt_GraphicsImportGetDataReference, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataReType)")},
+ {"GraphicsImportSetDataFile", (PyCFunction)Qt_GraphicsImportSetDataFile, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetDataFile", (PyCFunction)Qt_GraphicsImportGetDataFile, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetDataHandle", (PyCFunction)Qt_GraphicsImportSetDataHandle, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, Handle h) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetDataHandle", (PyCFunction)Qt_GraphicsImportGetDataHandle, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle h)")},
+ {"GraphicsImportGetImageDescription", (PyCFunction)Qt_GraphicsImportGetImageDescription, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, ImageDescriptionHandle desc)")},
+ {"GraphicsImportGetDataOffsetAndSize", (PyCFunction)Qt_GraphicsImportGetDataOffsetAndSize, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long size)")},
+ {"GraphicsImportReadData", (PyCFunction)Qt_GraphicsImportReadData, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * dataPtr, unsigned long dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetClip", (PyCFunction)Qt_GraphicsImportSetClip, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, RgnHandle clipRgn) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetClip", (PyCFunction)Qt_GraphicsImportGetClip, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, RgnHandle clipRgn)")},
+ {"GraphicsImportSetSourceRect", (PyCFunction)Qt_GraphicsImportSetSourceRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, Rect sourceRect) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetSourceRect", (PyCFunction)Qt_GraphicsImportGetSourceRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect sourceRect)")},
+ {"GraphicsImportGetNaturalBounds", (PyCFunction)Qt_GraphicsImportGetNaturalBounds, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect naturalBounds)")},
+ {"GraphicsImportDraw", (PyCFunction)Qt_GraphicsImportDraw, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetGWorld", (PyCFunction)Qt_GraphicsImportSetGWorld, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, CGrafPtr port, GDHandle gd) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetGWorld", (PyCFunction)Qt_GraphicsImportGetGWorld, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, CGrafPtr port, GDHandle gd)")},
+ {"GraphicsImportSetBoundsRect", (PyCFunction)Qt_GraphicsImportSetBoundsRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, Rect bounds) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetBoundsRect", (PyCFunction)Qt_GraphicsImportGetBoundsRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect bounds)")},
+ {"GraphicsImportSaveAsPicture", (PyCFunction)Qt_GraphicsImportSaveAsPicture, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, FSSpec fss, ScriptCode scriptTag) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetGraphicsMode", (PyCFunction)Qt_GraphicsImportSetGraphicsMode, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, long graphicsMode, RGBColor opColor) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetGraphicsMode", (PyCFunction)Qt_GraphicsImportGetGraphicsMode, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, long graphicsMode, RGBColor opColor)")},
+ {"GraphicsImportSetQuality", (PyCFunction)Qt_GraphicsImportSetQuality, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, CodecQ quality) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetQuality", (PyCFunction)Qt_GraphicsImportGetQuality, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, CodecQ quality)")},
+ {"GraphicsImportSaveAsQuickTimeImageFile", (PyCFunction)Qt_GraphicsImportSaveAsQuickTimeImageFile, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, FSSpec fss, ScriptCode scriptTag) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetDataReferenceOffsetAndLimit", (PyCFunction)Qt_GraphicsImportSetDataReferenceOffsetAndLimit, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, unsigned long offset, unsigned long limit) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetDataReferenceOffsetAndLimit", (PyCFunction)Qt_GraphicsImportGetDataReferenceOffsetAndLimit, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long limit)")},
+ {"GraphicsImportGetAliasedDataReference", (PyCFunction)Qt_GraphicsImportGetAliasedDataReference, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
+ {"GraphicsImportValidate", (PyCFunction)Qt_GraphicsImportValidate, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Boolean valid)")},
+ {"GraphicsImportGetMetaData", (PyCFunction)Qt_GraphicsImportGetMetaData, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * userData) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetMIMETypeList", (PyCFunction)Qt_GraphicsImportGetMIMETypeList, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
+ {"GraphicsImportDoesDrawAllPixels", (PyCFunction)Qt_GraphicsImportDoesDrawAllPixels, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, short drawsAllPixels)")},
+ {"GraphicsImportGetAsPicture", (PyCFunction)Qt_GraphicsImportGetAsPicture, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, PicHandle picture)")},
+ {"GraphicsImportExportImageFile", (PyCFunction)Qt_GraphicsImportExportImageFile, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, OSType fileType, OSType fileCreator, FSSpec fss, ScriptCode scriptTag) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetExportImageTypeList", (PyCFunction)Qt_GraphicsImportGetExportImageTypeList, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetExportSettingsAsAtomContainer", (PyCFunction)Qt_GraphicsImportGetExportSettingsAsAtomContainer, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetExportSettingsFromAtomContainer", (PyCFunction)Qt_GraphicsImportSetExportSettingsFromAtomContainer, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * qtAtomContainer) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetImageCount", (PyCFunction)Qt_GraphicsImportGetImageCount, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long imageCount)")},
+ {"GraphicsImportSetImageIndex", (PyCFunction)Qt_GraphicsImportSetImageIndex, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, unsigned long imageIndex) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetImageIndex", (PyCFunction)Qt_GraphicsImportGetImageIndex, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, unsigned long imageIndex)")},
+ {"GraphicsImportGetDataOffsetAndSize64", (PyCFunction)Qt_GraphicsImportGetDataOffsetAndSize64, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, wide offset, wide size)")},
+ {"GraphicsImportReadData64", (PyCFunction)Qt_GraphicsImportReadData64, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, void * dataPtr, wide dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
+ {"GraphicsImportSetDataReferenceOffsetAndLimit64", (PyCFunction)Qt_GraphicsImportSetDataReferenceOffsetAndLimit64, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, wide offset, wide limit) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetDataReferenceOffsetAndLimit64", (PyCFunction)Qt_GraphicsImportGetDataReferenceOffsetAndLimit64, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, wide offset, wide limit)")},
+ {"GraphicsImportGetDefaultClip", (PyCFunction)Qt_GraphicsImportGetDefaultClip, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, RgnHandle defaultRgn)")},
+ {"GraphicsImportGetDefaultGraphicsMode", (PyCFunction)Qt_GraphicsImportGetDefaultGraphicsMode, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, long defaultGraphicsMode, RGBColor defaultOpColor)")},
+ {"GraphicsImportGetDefaultSourceRect", (PyCFunction)Qt_GraphicsImportGetDefaultSourceRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect defaultSourceRect)")},
+ {"GraphicsImportGetColorSyncProfile", (PyCFunction)Qt_GraphicsImportGetColorSyncProfile, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Handle profile)")},
+ {"GraphicsImportSetDestRect", (PyCFunction)Qt_GraphicsImportSetDestRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, Rect destRect) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetDestRect", (PyCFunction)Qt_GraphicsImportGetDestRect, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, Rect destRect)")},
+ {"GraphicsImportSetFlags", (PyCFunction)Qt_GraphicsImportSetFlags, 1,
+ PyDoc_STR("(GraphicsImportComponent ci, long flags) -> (ComponentResult _rv)")},
+ {"GraphicsImportGetFlags", (PyCFunction)Qt_GraphicsImportGetFlags, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, long flags)")},
+ {"GraphicsImportGetBaseDataOffsetAndSize64", (PyCFunction)Qt_GraphicsImportGetBaseDataOffsetAndSize64, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv, wide offset, wide size)")},
+ {"GraphicsImportSetImageIndexToThumbnail", (PyCFunction)Qt_GraphicsImportSetImageIndexToThumbnail, 1,
+ PyDoc_STR("(GraphicsImportComponent ci) -> (ComponentResult _rv)")},
+ {"GraphicsExportDoExport", (PyCFunction)Qt_GraphicsExportDoExport, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long actualSizeWritten)")},
+ {"GraphicsExportCanTranscode", (PyCFunction)Qt_GraphicsExportCanTranscode, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean canTranscode)")},
+ {"GraphicsExportDoTranscode", (PyCFunction)Qt_GraphicsExportDoTranscode, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv)")},
+ {"GraphicsExportCanUseCompressor", (PyCFunction)Qt_GraphicsExportCanUseCompressor, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * codecSettingsAtomContainerPtr) -> (ComponentResult _rv, Boolean canUseCompressor)")},
+ {"GraphicsExportDoUseCompressor", (PyCFunction)Qt_GraphicsExportDoUseCompressor, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * codecSettingsAtomContainer) -> (ComponentResult _rv, ImageDescriptionHandle outDesc)")},
+ {"GraphicsExportDoStandaloneExport", (PyCFunction)Qt_GraphicsExportDoStandaloneExport, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetDefaultFileTypeAndCreator", (PyCFunction)Qt_GraphicsExportGetDefaultFileTypeAndCreator, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, OSType fileType, OSType fileCreator)")},
+ {"GraphicsExportGetDefaultFileNameExtension", (PyCFunction)Qt_GraphicsExportGetDefaultFileNameExtension, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, OSType fileNameExtension)")},
+ {"GraphicsExportGetMIMETypeList", (PyCFunction)Qt_GraphicsExportGetMIMETypeList, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetSettingsFromAtomContainer", (PyCFunction)Qt_GraphicsExportSetSettingsFromAtomContainer, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * qtAtomContainer) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetSettingsAsAtomContainer", (PyCFunction)Qt_GraphicsExportGetSettingsAsAtomContainer, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * qtAtomContainerPtr) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetSettingsAsText", (PyCFunction)Qt_GraphicsExportGetSettingsAsText, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle theText)")},
+ {"GraphicsExportSetDontRecompress", (PyCFunction)Qt_GraphicsExportSetDontRecompress, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Boolean dontRecompress) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetDontRecompress", (PyCFunction)Qt_GraphicsExportGetDontRecompress, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean dontRecompress)")},
+ {"GraphicsExportSetInterlaceStyle", (PyCFunction)Qt_GraphicsExportSetInterlaceStyle, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, unsigned long interlaceStyle) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInterlaceStyle", (PyCFunction)Qt_GraphicsExportGetInterlaceStyle, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long interlaceStyle)")},
+ {"GraphicsExportSetMetaData", (PyCFunction)Qt_GraphicsExportSetMetaData, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * userData) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetMetaData", (PyCFunction)Qt_GraphicsExportGetMetaData, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * userData) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetTargetDataSize", (PyCFunction)Qt_GraphicsExportSetTargetDataSize, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, unsigned long targetDataSize) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetTargetDataSize", (PyCFunction)Qt_GraphicsExportGetTargetDataSize, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long targetDataSize)")},
+ {"GraphicsExportSetCompressionMethod", (PyCFunction)Qt_GraphicsExportSetCompressionMethod, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, long compressionMethod) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetCompressionMethod", (PyCFunction)Qt_GraphicsExportGetCompressionMethod, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, long compressionMethod)")},
+ {"GraphicsExportSetCompressionQuality", (PyCFunction)Qt_GraphicsExportSetCompressionQuality, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, CodecQ spatialQuality) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetCompressionQuality", (PyCFunction)Qt_GraphicsExportGetCompressionQuality, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, CodecQ spatialQuality)")},
+ {"GraphicsExportSetResolution", (PyCFunction)Qt_GraphicsExportSetResolution, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Fixed horizontalResolution, Fixed verticalResolution) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetResolution", (PyCFunction)Qt_GraphicsExportGetResolution, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Fixed horizontalResolution, Fixed verticalResolution)")},
+ {"GraphicsExportSetDepth", (PyCFunction)Qt_GraphicsExportSetDepth, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, long depth) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetDepth", (PyCFunction)Qt_GraphicsExportGetDepth, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, long depth)")},
+ {"GraphicsExportSetColorSyncProfile", (PyCFunction)Qt_GraphicsExportSetColorSyncProfile, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Handle colorSyncProfile) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetColorSyncProfile", (PyCFunction)Qt_GraphicsExportGetColorSyncProfile, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle colorSyncProfile)")},
+ {"GraphicsExportSetInputDataReference", (PyCFunction)Qt_GraphicsExportSetInputDataReference, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Handle dataRef, OSType dataRefType, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputDataReference", (PyCFunction)Qt_GraphicsExportGetInputDataReference, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
+ {"GraphicsExportSetInputFile", (PyCFunction)Qt_GraphicsExportSetInputFile, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputFile", (PyCFunction)Qt_GraphicsExportGetInputFile, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetInputHandle", (PyCFunction)Qt_GraphicsExportSetInputHandle, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Handle h, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputHandle", (PyCFunction)Qt_GraphicsExportGetInputHandle, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle h)")},
+ {"GraphicsExportSetInputPtr", (PyCFunction)Qt_GraphicsExportSetInputPtr, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Ptr p, unsigned long size, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetInputGraphicsImporter", (PyCFunction)Qt_GraphicsExportSetInputGraphicsImporter, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, GraphicsImportComponent grip) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputGraphicsImporter", (PyCFunction)Qt_GraphicsExportGetInputGraphicsImporter, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, GraphicsImportComponent grip)")},
+ {"GraphicsExportSetInputPicture", (PyCFunction)Qt_GraphicsExportSetInputPicture, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, PicHandle picture) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputPicture", (PyCFunction)Qt_GraphicsExportGetInputPicture, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, PicHandle picture)")},
+ {"GraphicsExportSetInputGWorld", (PyCFunction)Qt_GraphicsExportSetInputGWorld, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, GWorldPtr gworld) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputGWorld", (PyCFunction)Qt_GraphicsExportGetInputGWorld, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, GWorldPtr gworld)")},
+ {"GraphicsExportSetInputPixmap", (PyCFunction)Qt_GraphicsExportSetInputPixmap, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, PixMapHandle pixmap) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputPixmap", (PyCFunction)Qt_GraphicsExportGetInputPixmap, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, PixMapHandle pixmap)")},
+ {"GraphicsExportSetInputOffsetAndLimit", (PyCFunction)Qt_GraphicsExportSetInputOffsetAndLimit, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, unsigned long offset, unsigned long limit) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputOffsetAndLimit", (PyCFunction)Qt_GraphicsExportGetInputOffsetAndLimit, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long limit)")},
+ {"GraphicsExportMayExporterReadInputData", (PyCFunction)Qt_GraphicsExportMayExporterReadInputData, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean mayReadInputData)")},
+ {"GraphicsExportGetInputDataSize", (PyCFunction)Qt_GraphicsExportGetInputDataSize, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long size)")},
+ {"GraphicsExportReadInputData", (PyCFunction)Qt_GraphicsExportReadInputData, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * dataPtr, unsigned long dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetInputImageDescription", (PyCFunction)Qt_GraphicsExportGetInputImageDescription, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, ImageDescriptionHandle desc)")},
+ {"GraphicsExportGetInputImageDimensions", (PyCFunction)Qt_GraphicsExportGetInputImageDimensions, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Rect dimensions)")},
+ {"GraphicsExportGetInputImageDepth", (PyCFunction)Qt_GraphicsExportGetInputImageDepth, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, long inputDepth)")},
+ {"GraphicsExportDrawInputImage", (PyCFunction)Qt_GraphicsExportDrawInputImage, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, CGrafPtr gw, GDHandle gd, Rect srcRect, Rect dstRect) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetOutputDataReference", (PyCFunction)Qt_GraphicsExportSetOutputDataReference, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Handle dataRef, OSType dataRefType) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetOutputDataReference", (PyCFunction)Qt_GraphicsExportGetOutputDataReference, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
+ {"GraphicsExportSetOutputFile", (PyCFunction)Qt_GraphicsExportSetOutputFile, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetOutputFile", (PyCFunction)Qt_GraphicsExportGetOutputFile, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, FSSpec theFile) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetOutputHandle", (PyCFunction)Qt_GraphicsExportSetOutputHandle, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Handle h) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetOutputHandle", (PyCFunction)Qt_GraphicsExportGetOutputHandle, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Handle h)")},
+ {"GraphicsExportSetOutputOffsetAndMaxSize", (PyCFunction)Qt_GraphicsExportSetOutputOffsetAndMaxSize, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, unsigned long offset, unsigned long maxSize, Boolean truncateFile) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetOutputOffsetAndMaxSize", (PyCFunction)Qt_GraphicsExportGetOutputOffsetAndMaxSize, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long offset, unsigned long maxSize, Boolean truncateFile)")},
+ {"GraphicsExportSetOutputFileTypeAndCreator", (PyCFunction)Qt_GraphicsExportSetOutputFileTypeAndCreator, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, OSType fileType, OSType fileCreator) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetOutputFileTypeAndCreator", (PyCFunction)Qt_GraphicsExportGetOutputFileTypeAndCreator, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, OSType fileType, OSType fileCreator)")},
+ {"GraphicsExportSetOutputMark", (PyCFunction)Qt_GraphicsExportSetOutputMark, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, unsigned long mark) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetOutputMark", (PyCFunction)Qt_GraphicsExportGetOutputMark, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, unsigned long mark)")},
+ {"GraphicsExportReadOutputData", (PyCFunction)Qt_GraphicsExportReadOutputData, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, void * dataPtr, unsigned long dataOffset, unsigned long dataSize) -> (ComponentResult _rv)")},
+ {"GraphicsExportSetThumbnailEnabled", (PyCFunction)Qt_GraphicsExportSetThumbnailEnabled, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Boolean enableThumbnail, long maxThumbnailWidth, long maxThumbnailHeight) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetThumbnailEnabled", (PyCFunction)Qt_GraphicsExportGetThumbnailEnabled, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean thumbnailEnabled, long maxThumbnailWidth, long maxThumbnailHeight)")},
+ {"GraphicsExportSetExifEnabled", (PyCFunction)Qt_GraphicsExportSetExifEnabled, 1,
+ PyDoc_STR("(GraphicsExportComponent ci, Boolean enableExif) -> (ComponentResult _rv)")},
+ {"GraphicsExportGetExifEnabled", (PyCFunction)Qt_GraphicsExportGetExifEnabled, 1,
+ PyDoc_STR("(GraphicsExportComponent ci) -> (ComponentResult _rv, Boolean exifEnabled)")},
+ {"ImageTranscoderBeginSequence", (PyCFunction)Qt_ImageTranscoderBeginSequence, 1,
+ PyDoc_STR("(ImageTranscoderComponent itc, ImageDescriptionHandle srcDesc, void * data, long dataSize) -> (ComponentResult _rv, ImageDescriptionHandle dstDesc)")},
+ {"ImageTranscoderDisposeData", (PyCFunction)Qt_ImageTranscoderDisposeData, 1,
+ PyDoc_STR("(ImageTranscoderComponent itc, void * dstData) -> (ComponentResult _rv)")},
+ {"ImageTranscoderEndSequence", (PyCFunction)Qt_ImageTranscoderEndSequence, 1,
+ PyDoc_STR("(ImageTranscoderComponent itc) -> (ComponentResult _rv)")},
+ {"ClockGetTime", (PyCFunction)Qt_ClockGetTime, 1,
+ PyDoc_STR("(ComponentInstance aClock) -> (ComponentResult _rv, TimeRecord out)")},
+ {"ClockSetTimeBase", (PyCFunction)Qt_ClockSetTimeBase, 1,
+ PyDoc_STR("(ComponentInstance aClock, TimeBase tb) -> (ComponentResult _rv)")},
+ {"ClockGetRate", (PyCFunction)Qt_ClockGetRate, 1,
+ PyDoc_STR("(ComponentInstance aClock) -> (ComponentResult _rv, Fixed rate)")},
+ {"SCPositionRect", (PyCFunction)Qt_SCPositionRect, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, Rect rp, Point where)")},
+ {"SCPositionDialog", (PyCFunction)Qt_SCPositionDialog, 1,
+ PyDoc_STR("(ComponentInstance ci, short id) -> (ComponentResult _rv, Point where)")},
+ {"SCSetTestImagePictHandle", (PyCFunction)Qt_SCSetTestImagePictHandle, 1,
+ PyDoc_STR("(ComponentInstance ci, PicHandle testPict, short testFlags) -> (ComponentResult _rv, Rect testRect)")},
+ {"SCSetTestImagePictFile", (PyCFunction)Qt_SCSetTestImagePictFile, 1,
+ PyDoc_STR("(ComponentInstance ci, short testFileRef, short testFlags) -> (ComponentResult _rv, Rect testRect)")},
+ {"SCSetTestImagePixMap", (PyCFunction)Qt_SCSetTestImagePixMap, 1,
+ PyDoc_STR("(ComponentInstance ci, PixMapHandle testPixMap, short testFlags) -> (ComponentResult _rv, Rect testRect)")},
+ {"SCGetBestDeviceRect", (PyCFunction)Qt_SCGetBestDeviceRect, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, Rect r)")},
+ {"SCRequestImageSettings", (PyCFunction)Qt_SCRequestImageSettings, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
+ {"SCCompressImage", (PyCFunction)Qt_SCCompressImage, 1,
+ PyDoc_STR("(ComponentInstance ci, PixMapHandle src, Rect srcRect) -> (ComponentResult _rv, ImageDescriptionHandle desc, Handle data)")},
+ {"SCCompressPicture", (PyCFunction)Qt_SCCompressPicture, 1,
+ PyDoc_STR("(ComponentInstance ci, PicHandle srcPicture, PicHandle dstPicture) -> (ComponentResult _rv)")},
+ {"SCCompressPictureFile", (PyCFunction)Qt_SCCompressPictureFile, 1,
+ PyDoc_STR("(ComponentInstance ci, short srcRefNum, short dstRefNum) -> (ComponentResult _rv)")},
+ {"SCRequestSequenceSettings", (PyCFunction)Qt_SCRequestSequenceSettings, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
+ {"SCCompressSequenceBegin", (PyCFunction)Qt_SCCompressSequenceBegin, 1,
+ PyDoc_STR("(ComponentInstance ci, PixMapHandle src, Rect srcRect) -> (ComponentResult _rv, ImageDescriptionHandle desc)")},
+ {"SCCompressSequenceFrame", (PyCFunction)Qt_SCCompressSequenceFrame, 1,
+ PyDoc_STR("(ComponentInstance ci, PixMapHandle src, Rect srcRect) -> (ComponentResult _rv, Handle data, long dataSize, short notSyncFlag)")},
+ {"SCCompressSequenceEnd", (PyCFunction)Qt_SCCompressSequenceEnd, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
+ {"SCDefaultPictHandleSettings", (PyCFunction)Qt_SCDefaultPictHandleSettings, 1,
+ PyDoc_STR("(ComponentInstance ci, PicHandle srcPicture, short motion) -> (ComponentResult _rv)")},
+ {"SCDefaultPictFileSettings", (PyCFunction)Qt_SCDefaultPictFileSettings, 1,
+ PyDoc_STR("(ComponentInstance ci, short srcRef, short motion) -> (ComponentResult _rv)")},
+ {"SCDefaultPixMapSettings", (PyCFunction)Qt_SCDefaultPixMapSettings, 1,
+ PyDoc_STR("(ComponentInstance ci, PixMapHandle src, short motion) -> (ComponentResult _rv)")},
+ {"SCGetInfo", (PyCFunction)Qt_SCGetInfo, 1,
+ PyDoc_STR("(ComponentInstance ci, OSType infoType, void * info) -> (ComponentResult _rv)")},
+ {"SCSetInfo", (PyCFunction)Qt_SCSetInfo, 1,
+ PyDoc_STR("(ComponentInstance ci, OSType infoType, void * info) -> (ComponentResult _rv)")},
+ {"SCSetCompressFlags", (PyCFunction)Qt_SCSetCompressFlags, 1,
+ PyDoc_STR("(ComponentInstance ci, long flags) -> (ComponentResult _rv)")},
+ {"SCGetCompressFlags", (PyCFunction)Qt_SCGetCompressFlags, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, long flags)")},
+ {"SCGetSettingsAsText", (PyCFunction)Qt_SCGetSettingsAsText, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv, Handle text)")},
+ {"SCAsyncIdle", (PyCFunction)Qt_SCAsyncIdle, 1,
+ PyDoc_STR("(ComponentInstance ci) -> (ComponentResult _rv)")},
+ {"TweenerReset", (PyCFunction)Qt_TweenerReset, 1,
+ PyDoc_STR("(TweenerComponent tc) -> (ComponentResult _rv)")},
+ {"TCGetSourceRef", (PyCFunction)Qt_TCGetSourceRef, 1,
+ PyDoc_STR("(MediaHandler mh, TimeCodeDescriptionHandle tcdH) -> (HandlerError _rv, UserData srefH)")},
+ {"TCSetSourceRef", (PyCFunction)Qt_TCSetSourceRef, 1,
+ PyDoc_STR("(MediaHandler mh, TimeCodeDescriptionHandle tcdH, UserData srefH) -> (HandlerError _rv)")},
+ {"TCSetTimeCodeFlags", (PyCFunction)Qt_TCSetTimeCodeFlags, 1,
+ PyDoc_STR("(MediaHandler mh, long flags, long flagsMask) -> (HandlerError _rv)")},
+ {"TCGetTimeCodeFlags", (PyCFunction)Qt_TCGetTimeCodeFlags, 1,
+ PyDoc_STR("(MediaHandler mh) -> (HandlerError _rv, long flags)")},
+ {"MovieImportHandle", (PyCFunction)Qt_MovieImportHandle, 1,
+ PyDoc_STR("(MovieImportComponent ci, Handle dataH, Movie theMovie, Track targetTrack, TimeValue atTime, long inFlags) -> (ComponentResult _rv, Track usedTrack, TimeValue addedDuration, long outFlags)")},
+ {"MovieImportFile", (PyCFunction)Qt_MovieImportFile, 1,
+ PyDoc_STR("(MovieImportComponent ci, FSSpec theFile, Movie theMovie, Track targetTrack, TimeValue atTime, long inFlags) -> (ComponentResult _rv, Track usedTrack, TimeValue addedDuration, long outFlags)")},
+ {"MovieImportSetSampleDuration", (PyCFunction)Qt_MovieImportSetSampleDuration, 1,
+ PyDoc_STR("(MovieImportComponent ci, TimeValue duration, TimeScale scale) -> (ComponentResult _rv)")},
+ {"MovieImportSetSampleDescription", (PyCFunction)Qt_MovieImportSetSampleDescription, 1,
+ PyDoc_STR("(MovieImportComponent ci, SampleDescriptionHandle desc, OSType mediaType) -> (ComponentResult _rv)")},
+ {"MovieImportSetMediaFile", (PyCFunction)Qt_MovieImportSetMediaFile, 1,
+ PyDoc_STR("(MovieImportComponent ci, AliasHandle alias) -> (ComponentResult _rv)")},
+ {"MovieImportSetDimensions", (PyCFunction)Qt_MovieImportSetDimensions, 1,
+ PyDoc_STR("(MovieImportComponent ci, Fixed width, Fixed height) -> (ComponentResult _rv)")},
+ {"MovieImportSetChunkSize", (PyCFunction)Qt_MovieImportSetChunkSize, 1,
+ PyDoc_STR("(MovieImportComponent ci, long chunkSize) -> (ComponentResult _rv)")},
+ {"MovieImportSetAuxiliaryData", (PyCFunction)Qt_MovieImportSetAuxiliaryData, 1,
+ PyDoc_STR("(MovieImportComponent ci, Handle data, OSType handleType) -> (ComponentResult _rv)")},
+ {"MovieImportSetFromScrap", (PyCFunction)Qt_MovieImportSetFromScrap, 1,
+ PyDoc_STR("(MovieImportComponent ci, Boolean fromScrap) -> (ComponentResult _rv)")},
+ {"MovieImportDoUserDialog", (PyCFunction)Qt_MovieImportDoUserDialog, 1,
+ PyDoc_STR("(MovieImportComponent ci, FSSpec theFile, Handle theData) -> (ComponentResult _rv, Boolean canceled)")},
+ {"MovieImportSetDuration", (PyCFunction)Qt_MovieImportSetDuration, 1,
+ PyDoc_STR("(MovieImportComponent ci, TimeValue duration) -> (ComponentResult _rv)")},
+ {"MovieImportGetAuxiliaryDataType", (PyCFunction)Qt_MovieImportGetAuxiliaryDataType, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, OSType auxType)")},
+ {"MovieImportValidate", (PyCFunction)Qt_MovieImportValidate, 1,
+ PyDoc_STR("(MovieImportComponent ci, FSSpec theFile, Handle theData) -> (ComponentResult _rv, Boolean valid)")},
+ {"MovieImportGetFileType", (PyCFunction)Qt_MovieImportGetFileType, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, OSType fileType)")},
+ {"MovieImportDataRef", (PyCFunction)Qt_MovieImportDataRef, 1,
+ PyDoc_STR("(MovieImportComponent ci, Handle dataRef, OSType dataRefType, Movie theMovie, Track targetTrack, TimeValue atTime, long inFlags) -> (ComponentResult _rv, Track usedTrack, TimeValue addedDuration, long outFlags)")},
+ {"MovieImportGetSampleDescription", (PyCFunction)Qt_MovieImportGetSampleDescription, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, SampleDescriptionHandle desc, OSType mediaType)")},
+ {"MovieImportSetOffsetAndLimit", (PyCFunction)Qt_MovieImportSetOffsetAndLimit, 1,
+ PyDoc_STR("(MovieImportComponent ci, unsigned long offset, unsigned long limit) -> (ComponentResult _rv)")},
+ {"MovieImportSetOffsetAndLimit64", (PyCFunction)Qt_MovieImportSetOffsetAndLimit64, 1,
+ PyDoc_STR("(MovieImportComponent ci, wide offset, wide limit) -> (ComponentResult _rv)")},
+ {"MovieImportIdle", (PyCFunction)Qt_MovieImportIdle, 1,
+ PyDoc_STR("(MovieImportComponent ci, long inFlags) -> (ComponentResult _rv, long outFlags)")},
+ {"MovieImportValidateDataRef", (PyCFunction)Qt_MovieImportValidateDataRef, 1,
+ PyDoc_STR("(MovieImportComponent ci, Handle dataRef, OSType dataRefType) -> (ComponentResult _rv, UInt8 valid)")},
+ {"MovieImportGetLoadState", (PyCFunction)Qt_MovieImportGetLoadState, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, long importerLoadState)")},
+ {"MovieImportGetMaxLoadedTime", (PyCFunction)Qt_MovieImportGetMaxLoadedTime, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, TimeValue time)")},
+ {"MovieImportEstimateCompletionTime", (PyCFunction)Qt_MovieImportEstimateCompletionTime, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, TimeRecord time)")},
+ {"MovieImportSetDontBlock", (PyCFunction)Qt_MovieImportSetDontBlock, 1,
+ PyDoc_STR("(MovieImportComponent ci, Boolean dontBlock) -> (ComponentResult _rv)")},
+ {"MovieImportGetDontBlock", (PyCFunction)Qt_MovieImportGetDontBlock, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, Boolean willBlock)")},
+ {"MovieImportSetIdleManager", (PyCFunction)Qt_MovieImportSetIdleManager, 1,
+ PyDoc_STR("(MovieImportComponent ci, IdleManager im) -> (ComponentResult _rv)")},
+ {"MovieImportSetNewMovieFlags", (PyCFunction)Qt_MovieImportSetNewMovieFlags, 1,
+ PyDoc_STR("(MovieImportComponent ci, long newMovieFlags) -> (ComponentResult _rv)")},
+ {"MovieImportGetDestinationMediaType", (PyCFunction)Qt_MovieImportGetDestinationMediaType, 1,
+ PyDoc_STR("(MovieImportComponent ci) -> (ComponentResult _rv, OSType mediaType)")},
+ {"MovieExportToHandle", (PyCFunction)Qt_MovieExportToHandle, 1,
+ PyDoc_STR("(MovieExportComponent ci, Handle dataH, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv)")},
+ {"MovieExportToFile", (PyCFunction)Qt_MovieExportToFile, 1,
+ PyDoc_STR("(MovieExportComponent ci, FSSpec theFile, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv)")},
+ {"MovieExportGetAuxiliaryData", (PyCFunction)Qt_MovieExportGetAuxiliaryData, 1,
+ PyDoc_STR("(MovieExportComponent ci, Handle dataH) -> (ComponentResult _rv, OSType handleType)")},
+ {"MovieExportSetSampleDescription", (PyCFunction)Qt_MovieExportSetSampleDescription, 1,
+ PyDoc_STR("(MovieExportComponent ci, SampleDescriptionHandle desc, OSType mediaType) -> (ComponentResult _rv)")},
+ {"MovieExportDoUserDialog", (PyCFunction)Qt_MovieExportDoUserDialog, 1,
+ PyDoc_STR("(MovieExportComponent ci, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv, Boolean canceled)")},
+ {"MovieExportGetCreatorType", (PyCFunction)Qt_MovieExportGetCreatorType, 1,
+ PyDoc_STR("(MovieExportComponent ci) -> (ComponentResult _rv, OSType creator)")},
+ {"MovieExportToDataRef", (PyCFunction)Qt_MovieExportToDataRef, 1,
+ PyDoc_STR("(MovieExportComponent ci, Handle dataRef, OSType dataRefType, Movie theMovie, Track onlyThisTrack, TimeValue startTime, TimeValue duration) -> (ComponentResult _rv)")},
+ {"MovieExportFromProceduresToDataRef", (PyCFunction)Qt_MovieExportFromProceduresToDataRef, 1,
+ PyDoc_STR("(MovieExportComponent ci, Handle dataRef, OSType dataRefType) -> (ComponentResult _rv)")},
+ {"MovieExportValidate", (PyCFunction)Qt_MovieExportValidate, 1,
+ PyDoc_STR("(MovieExportComponent ci, Movie theMovie, Track onlyThisTrack) -> (ComponentResult _rv, Boolean valid)")},
+ {"MovieExportGetFileNameExtension", (PyCFunction)Qt_MovieExportGetFileNameExtension, 1,
+ PyDoc_STR("(MovieExportComponent ci) -> (ComponentResult _rv, OSType extension)")},
+ {"MovieExportGetShortFileTypeString", (PyCFunction)Qt_MovieExportGetShortFileTypeString, 1,
+ PyDoc_STR("(MovieExportComponent ci, Str255 typeString) -> (ComponentResult _rv)")},
+ {"MovieExportGetSourceMediaType", (PyCFunction)Qt_MovieExportGetSourceMediaType, 1,
+ PyDoc_STR("(MovieExportComponent ci) -> (ComponentResult _rv, OSType mediaType)")},
+ {"TextExportGetTimeFraction", (PyCFunction)Qt_TextExportGetTimeFraction, 1,
+ PyDoc_STR("(TextExportComponent ci) -> (ComponentResult _rv, long movieTimeFraction)")},
+ {"TextExportSetTimeFraction", (PyCFunction)Qt_TextExportSetTimeFraction, 1,
+ PyDoc_STR("(TextExportComponent ci, long movieTimeFraction) -> (ComponentResult _rv)")},
+ {"TextExportGetSettings", (PyCFunction)Qt_TextExportGetSettings, 1,
+ PyDoc_STR("(TextExportComponent ci) -> (ComponentResult _rv, long setting)")},
+ {"TextExportSetSettings", (PyCFunction)Qt_TextExportSetSettings, 1,
+ PyDoc_STR("(TextExportComponent ci, long setting) -> (ComponentResult _rv)")},
+ {"MIDIImportGetSettings", (PyCFunction)Qt_MIDIImportGetSettings, 1,
+ PyDoc_STR("(TextExportComponent ci) -> (ComponentResult _rv, long setting)")},
+ {"MIDIImportSetSettings", (PyCFunction)Qt_MIDIImportSetSettings, 1,
+ PyDoc_STR("(TextExportComponent ci, long setting) -> (ComponentResult _rv)")},
+ {"GraphicsImageImportSetSequenceEnabled", (PyCFunction)Qt_GraphicsImageImportSetSequenceEnabled, 1,
+ PyDoc_STR("(GraphicImageMovieImportComponent ci, Boolean enable) -> (ComponentResult _rv)")},
+ {"GraphicsImageImportGetSequenceEnabled", (PyCFunction)Qt_GraphicsImageImportGetSequenceEnabled, 1,
+ PyDoc_STR("(GraphicImageMovieImportComponent ci) -> (ComponentResult _rv, Boolean enable)")},
+ {"PreviewShowData", (PyCFunction)Qt_PreviewShowData, 1,
+ PyDoc_STR("(pnotComponent p, OSType dataType, Handle data, Rect inHere) -> (ComponentResult _rv)")},
+ {"PreviewMakePreviewReference", (PyCFunction)Qt_PreviewMakePreviewReference, 1,
+ PyDoc_STR("(pnotComponent p, FSSpec sourceFile) -> (ComponentResult _rv, OSType previewType, short resID)")},
+ {"PreviewEvent", (PyCFunction)Qt_PreviewEvent, 1,
+ PyDoc_STR("(pnotComponent p) -> (ComponentResult _rv, EventRecord e, Boolean handledEvent)")},
+ {"DataCodecDecompress", (PyCFunction)Qt_DataCodecDecompress, 1,
+ PyDoc_STR("(DataCodecComponent dc, void * srcData, UInt32 srcSize, void * dstData, UInt32 dstBufferSize) -> (ComponentResult _rv)")},
+ {"DataCodecGetCompressBufferSize", (PyCFunction)Qt_DataCodecGetCompressBufferSize, 1,
+ PyDoc_STR("(DataCodecComponent dc, UInt32 srcSize) -> (ComponentResult _rv, UInt32 dstSize)")},
+ {"DataCodecCompress", (PyCFunction)Qt_DataCodecCompress, 1,
+ PyDoc_STR("(DataCodecComponent dc, void * srcData, UInt32 srcSize, void * dstData, UInt32 dstBufferSize) -> (ComponentResult _rv, UInt32 actualDstSize, UInt32 decompressSlop)")},
+ {"DataCodecBeginInterruptSafe", (PyCFunction)Qt_DataCodecBeginInterruptSafe, 1,
+ PyDoc_STR("(DataCodecComponent dc, unsigned long maxSrcSize) -> (ComponentResult _rv)")},
+ {"DataCodecEndInterruptSafe", (PyCFunction)Qt_DataCodecEndInterruptSafe, 1,
+ PyDoc_STR("(DataCodecComponent dc) -> (ComponentResult _rv)")},
+ {"DataHGetData", (PyCFunction)Qt_DataHGetData, 1,
+ PyDoc_STR("(DataHandler dh, Handle h, long hOffset, long offset, long size) -> (ComponentResult _rv)")},
+ {"DataHPutData", (PyCFunction)Qt_DataHPutData, 1,
+ PyDoc_STR("(DataHandler dh, Handle h, long hOffset, long size) -> (ComponentResult _rv, long offset)")},
+ {"DataHFlushData", (PyCFunction)Qt_DataHFlushData, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHOpenForWrite", (PyCFunction)Qt_DataHOpenForWrite, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHCloseForWrite", (PyCFunction)Qt_DataHCloseForWrite, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHOpenForRead", (PyCFunction)Qt_DataHOpenForRead, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHCloseForRead", (PyCFunction)Qt_DataHCloseForRead, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHSetDataRef", (PyCFunction)Qt_DataHSetDataRef, 1,
+ PyDoc_STR("(DataHandler dh, Handle dataRef) -> (ComponentResult _rv)")},
+ {"DataHGetDataRef", (PyCFunction)Qt_DataHGetDataRef, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Handle dataRef)")},
+ {"DataHCompareDataRef", (PyCFunction)Qt_DataHCompareDataRef, 1,
+ PyDoc_STR("(DataHandler dh, Handle dataRef) -> (ComponentResult _rv, Boolean equal)")},
+ {"DataHTask", (PyCFunction)Qt_DataHTask, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHFinishData", (PyCFunction)Qt_DataHFinishData, 1,
+ PyDoc_STR("(DataHandler dh, Ptr PlaceToPutDataPtr, Boolean Cancel) -> (ComponentResult _rv)")},
+ {"DataHFlushCache", (PyCFunction)Qt_DataHFlushCache, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHResolveDataRef", (PyCFunction)Qt_DataHResolveDataRef, 1,
+ PyDoc_STR("(DataHandler dh, Handle theDataRef, Boolean userInterfaceAllowed) -> (ComponentResult _rv, Boolean wasChanged)")},
+ {"DataHGetFileSize", (PyCFunction)Qt_DataHGetFileSize, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long fileSize)")},
+ {"DataHCanUseDataRef", (PyCFunction)Qt_DataHCanUseDataRef, 1,
+ PyDoc_STR("(DataHandler dh, Handle dataRef) -> (ComponentResult _rv, long useFlags)")},
+ {"DataHPreextend", (PyCFunction)Qt_DataHPreextend, 1,
+ PyDoc_STR("(DataHandler dh, unsigned long maxToAdd) -> (ComponentResult _rv, unsigned long spaceAdded)")},
+ {"DataHSetFileSize", (PyCFunction)Qt_DataHSetFileSize, 1,
+ PyDoc_STR("(DataHandler dh, long fileSize) -> (ComponentResult _rv)")},
+ {"DataHGetFreeSpace", (PyCFunction)Qt_DataHGetFreeSpace, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, unsigned long freeSize)")},
+ {"DataHCreateFile", (PyCFunction)Qt_DataHCreateFile, 1,
+ PyDoc_STR("(DataHandler dh, OSType creator, Boolean deleteExisting) -> (ComponentResult _rv)")},
+ {"DataHGetPreferredBlockSize", (PyCFunction)Qt_DataHGetPreferredBlockSize, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long blockSize)")},
+ {"DataHGetDeviceIndex", (PyCFunction)Qt_DataHGetDeviceIndex, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long deviceIndex)")},
+ {"DataHIsStreamingDataHandler", (PyCFunction)Qt_DataHIsStreamingDataHandler, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Boolean yes)")},
+ {"DataHGetDataInBuffer", (PyCFunction)Qt_DataHGetDataInBuffer, 1,
+ PyDoc_STR("(DataHandler dh, long startOffset) -> (ComponentResult _rv, long size)")},
+ {"DataHGetScheduleAheadTime", (PyCFunction)Qt_DataHGetScheduleAheadTime, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long millisecs)")},
+ {"DataHSetCacheSizeLimit", (PyCFunction)Qt_DataHSetCacheSizeLimit, 1,
+ PyDoc_STR("(DataHandler dh, Size cacheSizeLimit) -> (ComponentResult _rv)")},
+ {"DataHGetCacheSizeLimit", (PyCFunction)Qt_DataHGetCacheSizeLimit, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Size cacheSizeLimit)")},
+ {"DataHGetMovie", (PyCFunction)Qt_DataHGetMovie, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Movie theMovie, short id)")},
+ {"DataHAddMovie", (PyCFunction)Qt_DataHAddMovie, 1,
+ PyDoc_STR("(DataHandler dh, Movie theMovie) -> (ComponentResult _rv, short id)")},
+ {"DataHUpdateMovie", (PyCFunction)Qt_DataHUpdateMovie, 1,
+ PyDoc_STR("(DataHandler dh, Movie theMovie, short id) -> (ComponentResult _rv)")},
+ {"DataHDoesBuffer", (PyCFunction)Qt_DataHDoesBuffer, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, Boolean buffersReads, Boolean buffersWrites)")},
+ {"DataHGetFileName", (PyCFunction)Qt_DataHGetFileName, 1,
+ PyDoc_STR("(DataHandler dh, Str255 str) -> (ComponentResult _rv)")},
+ {"DataHGetAvailableFileSize", (PyCFunction)Qt_DataHGetAvailableFileSize, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long fileSize)")},
+ {"DataHGetMacOSFileType", (PyCFunction)Qt_DataHGetMacOSFileType, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, OSType fileType)")},
+ {"DataHGetMIMEType", (PyCFunction)Qt_DataHGetMIMEType, 1,
+ PyDoc_STR("(DataHandler dh, Str255 mimeType) -> (ComponentResult _rv)")},
+ {"DataHSetDataRefWithAnchor", (PyCFunction)Qt_DataHSetDataRefWithAnchor, 1,
+ PyDoc_STR("(DataHandler dh, Handle anchorDataRef, OSType dataRefType, Handle dataRef) -> (ComponentResult _rv)")},
+ {"DataHGetDataRefWithAnchor", (PyCFunction)Qt_DataHGetDataRefWithAnchor, 1,
+ PyDoc_STR("(DataHandler dh, Handle anchorDataRef, OSType dataRefType) -> (ComponentResult _rv, Handle dataRef)")},
+ {"DataHSetMacOSFileType", (PyCFunction)Qt_DataHSetMacOSFileType, 1,
+ PyDoc_STR("(DataHandler dh, OSType fileType) -> (ComponentResult _rv)")},
+ {"DataHSetTimeBase", (PyCFunction)Qt_DataHSetTimeBase, 1,
+ PyDoc_STR("(DataHandler dh, TimeBase tb) -> (ComponentResult _rv)")},
+ {"DataHGetInfoFlags", (PyCFunction)Qt_DataHGetInfoFlags, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, UInt32 flags)")},
+ {"DataHGetFileSize64", (PyCFunction)Qt_DataHGetFileSize64, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, wide fileSize)")},
+ {"DataHPreextend64", (PyCFunction)Qt_DataHPreextend64, 1,
+ PyDoc_STR("(DataHandler dh, wide maxToAdd) -> (ComponentResult _rv, wide spaceAdded)")},
+ {"DataHSetFileSize64", (PyCFunction)Qt_DataHSetFileSize64, 1,
+ PyDoc_STR("(DataHandler dh, wide fileSize) -> (ComponentResult _rv)")},
+ {"DataHGetFreeSpace64", (PyCFunction)Qt_DataHGetFreeSpace64, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, wide freeSize)")},
+ {"DataHAppend64", (PyCFunction)Qt_DataHAppend64, 1,
+ PyDoc_STR("(DataHandler dh, void * data, unsigned long size) -> (ComponentResult _rv, wide fileOffset)")},
+ {"DataHPollRead", (PyCFunction)Qt_DataHPollRead, 1,
+ PyDoc_STR("(DataHandler dh, void * dataPtr) -> (ComponentResult _rv, UInt32 dataSizeSoFar)")},
+ {"DataHGetDataAvailability", (PyCFunction)Qt_DataHGetDataAvailability, 1,
+ PyDoc_STR("(DataHandler dh, long offset, long len) -> (ComponentResult _rv, long missing_offset, long missing_len)")},
+ {"DataHGetDataRefAsType", (PyCFunction)Qt_DataHGetDataRefAsType, 1,
+ PyDoc_STR("(DataHandler dh, OSType requestedType) -> (ComponentResult _rv, Handle dataRef)")},
+ {"DataHSetDataRefExtension", (PyCFunction)Qt_DataHSetDataRefExtension, 1,
+ PyDoc_STR("(DataHandler dh, Handle extension, OSType idType) -> (ComponentResult _rv)")},
+ {"DataHGetDataRefExtension", (PyCFunction)Qt_DataHGetDataRefExtension, 1,
+ PyDoc_STR("(DataHandler dh, OSType idType) -> (ComponentResult _rv, Handle extension)")},
+ {"DataHGetMovieWithFlags", (PyCFunction)Qt_DataHGetMovieWithFlags, 1,
+ PyDoc_STR("(DataHandler dh, short flags) -> (ComponentResult _rv, Movie theMovie, short id)")},
+ {"DataHGetFileTypeOrdering", (PyCFunction)Qt_DataHGetFileTypeOrdering, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, DataHFileTypeOrderingHandle orderingListHandle)")},
+ {"DataHCreateFileWithFlags", (PyCFunction)Qt_DataHCreateFileWithFlags, 1,
+ PyDoc_STR("(DataHandler dh, OSType creator, Boolean deleteExisting, UInt32 flags) -> (ComponentResult _rv)")},
+ {"DataHGetInfo", (PyCFunction)Qt_DataHGetInfo, 1,
+ PyDoc_STR("(DataHandler dh, OSType what, void * info) -> (ComponentResult _rv)")},
+ {"DataHSetIdleManager", (PyCFunction)Qt_DataHSetIdleManager, 1,
+ PyDoc_STR("(DataHandler dh, IdleManager im) -> (ComponentResult _rv)")},
+ {"DataHDeleteFile", (PyCFunction)Qt_DataHDeleteFile, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv)")},
+ {"DataHSetMovieUsageFlags", (PyCFunction)Qt_DataHSetMovieUsageFlags, 1,
+ PyDoc_STR("(DataHandler dh, long flags) -> (ComponentResult _rv)")},
+ {"DataHUseTemporaryDataRef", (PyCFunction)Qt_DataHUseTemporaryDataRef, 1,
+ PyDoc_STR("(DataHandler dh, long inFlags) -> (ComponentResult _rv)")},
+ {"DataHGetTemporaryDataRefCapabilities", (PyCFunction)Qt_DataHGetTemporaryDataRefCapabilities, 1,
+ PyDoc_STR("(DataHandler dh) -> (ComponentResult _rv, long outUnderstoodFlags)")},
+ {"DataHRenameFile", (PyCFunction)Qt_DataHRenameFile, 1,
+ PyDoc_STR("(DataHandler dh, Handle newDataRef) -> (ComponentResult _rv)")},
+ {"DataHPlaybackHints", (PyCFunction)Qt_DataHPlaybackHints, 1,
+ PyDoc_STR("(DataHandler dh, long flags, unsigned long minFileOffset, unsigned long maxFileOffset, long bytesPerSecond) -> (ComponentResult _rv)")},
+ {"DataHPlaybackHints64", (PyCFunction)Qt_DataHPlaybackHints64, 1,
+ PyDoc_STR("(DataHandler dh, long flags, wide minFileOffset, wide maxFileOffset, long bytesPerSecond) -> (ComponentResult _rv)")},
+ {"DataHGetDataRate", (PyCFunction)Qt_DataHGetDataRate, 1,
+ PyDoc_STR("(DataHandler dh, long flags) -> (ComponentResult _rv, long bytesPerSecond)")},
+ {"DataHSetTimeHints", (PyCFunction)Qt_DataHSetTimeHints, 1,
+ PyDoc_STR("(DataHandler dh, long flags, long bandwidthPriority, TimeScale scale, TimeValue minTime, TimeValue maxTime) -> (ComponentResult _rv)")},
+ {"VDGetMaxSrcRect", (PyCFunction)Qt_VDGetMaxSrcRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short inputStd) -> (ComponentResult _rv, Rect maxSrcRect)")},
+ {"VDGetActiveSrcRect", (PyCFunction)Qt_VDGetActiveSrcRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short inputStd) -> (ComponentResult _rv, Rect activeSrcRect)")},
+ {"VDSetDigitizerRect", (PyCFunction)Qt_VDSetDigitizerRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, Rect digitizerRect)")},
+ {"VDGetDigitizerRect", (PyCFunction)Qt_VDGetDigitizerRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, Rect digitizerRect)")},
+ {"VDGetVBlankRect", (PyCFunction)Qt_VDGetVBlankRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short inputStd) -> (ComponentResult _rv, Rect vBlankRect)")},
+ {"VDGetMaskPixMap", (PyCFunction)Qt_VDGetMaskPixMap, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, PixMapHandle maskPixMap) -> (ComponentResult _rv)")},
+ {"VDUseThisCLUT", (PyCFunction)Qt_VDUseThisCLUT, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, CTabHandle colorTableHandle) -> (ComponentResult _rv)")},
+ {"VDSetInputGammaValue", (PyCFunction)Qt_VDSetInputGammaValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, Fixed channel1, Fixed channel2, Fixed channel3) -> (ComponentResult _rv)")},
+ {"VDGetInputGammaValue", (PyCFunction)Qt_VDGetInputGammaValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, Fixed channel1, Fixed channel2, Fixed channel3)")},
+ {"VDSetBrightness", (PyCFunction)Qt_VDSetBrightness, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short brightness)")},
+ {"VDGetBrightness", (PyCFunction)Qt_VDGetBrightness, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short brightness)")},
+ {"VDSetContrast", (PyCFunction)Qt_VDSetContrast, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short contrast)")},
+ {"VDSetHue", (PyCFunction)Qt_VDSetHue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short hue)")},
+ {"VDSetSharpness", (PyCFunction)Qt_VDSetSharpness, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short sharpness)")},
+ {"VDSetSaturation", (PyCFunction)Qt_VDSetSaturation, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short saturation)")},
+ {"VDGetContrast", (PyCFunction)Qt_VDGetContrast, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short contrast)")},
+ {"VDGetHue", (PyCFunction)Qt_VDGetHue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short hue)")},
+ {"VDGetSharpness", (PyCFunction)Qt_VDGetSharpness, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short sharpness)")},
+ {"VDGetSaturation", (PyCFunction)Qt_VDGetSaturation, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short saturation)")},
+ {"VDGrabOneFrame", (PyCFunction)Qt_VDGrabOneFrame, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
+ {"VDGetMaxAuxBuffer", (PyCFunction)Qt_VDGetMaxAuxBuffer, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, PixMapHandle pm, Rect r)")},
+ {"VDGetCurrentFlags", (PyCFunction)Qt_VDGetCurrentFlags, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long inputCurrentFlag, long outputCurrentFlag)")},
+ {"VDSetKeyColor", (PyCFunction)Qt_VDSetKeyColor, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long index) -> (ComponentResult _rv)")},
+ {"VDGetKeyColor", (PyCFunction)Qt_VDGetKeyColor, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long index)")},
+ {"VDAddKeyColor", (PyCFunction)Qt_VDAddKeyColor, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long index)")},
+ {"VDGetNextKeyColor", (PyCFunction)Qt_VDGetNextKeyColor, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long index) -> (ComponentResult _rv)")},
+ {"VDSetKeyColorRange", (PyCFunction)Qt_VDSetKeyColorRange, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, RGBColor minRGB, RGBColor maxRGB)")},
+ {"VDGetKeyColorRange", (PyCFunction)Qt_VDGetKeyColorRange, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, RGBColor minRGB, RGBColor maxRGB)")},
+ {"VDSetInputColorSpaceMode", (PyCFunction)Qt_VDSetInputColorSpaceMode, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short colorSpaceMode) -> (ComponentResult _rv)")},
+ {"VDGetInputColorSpaceMode", (PyCFunction)Qt_VDGetInputColorSpaceMode, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short colorSpaceMode)")},
+ {"VDSetClipState", (PyCFunction)Qt_VDSetClipState, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short clipEnable) -> (ComponentResult _rv)")},
+ {"VDGetClipState", (PyCFunction)Qt_VDGetClipState, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short clipEnable)")},
+ {"VDSetClipRgn", (PyCFunction)Qt_VDSetClipRgn, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, RgnHandle clipRegion) -> (ComponentResult _rv)")},
+ {"VDClearClipRgn", (PyCFunction)Qt_VDClearClipRgn, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, RgnHandle clipRegion) -> (ComponentResult _rv)")},
+ {"VDGetCLUTInUse", (PyCFunction)Qt_VDGetCLUTInUse, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, CTabHandle colorTableHandle)")},
+ {"VDSetPLLFilterType", (PyCFunction)Qt_VDSetPLLFilterType, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short pllType) -> (ComponentResult _rv)")},
+ {"VDGetPLLFilterType", (PyCFunction)Qt_VDGetPLLFilterType, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short pllType)")},
+ {"VDGetMaskandValue", (PyCFunction)Qt_VDGetMaskandValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, unsigned short blendLevel) -> (ComponentResult _rv, long mask, long value)")},
+ {"VDSetMasterBlendLevel", (PyCFunction)Qt_VDSetMasterBlendLevel, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blendLevel)")},
+ {"VDSetPlayThruOnOff", (PyCFunction)Qt_VDSetPlayThruOnOff, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short state) -> (ComponentResult _rv)")},
+ {"VDSetFieldPreference", (PyCFunction)Qt_VDSetFieldPreference, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short fieldFlag) -> (ComponentResult _rv)")},
+ {"VDGetFieldPreference", (PyCFunction)Qt_VDGetFieldPreference, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short fieldFlag)")},
+ {"VDPreflightGlobalRect", (PyCFunction)Qt_VDPreflightGlobalRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, GrafPtr theWindow) -> (ComponentResult _rv, Rect globalRect)")},
+ {"VDSetPlayThruGlobalRect", (PyCFunction)Qt_VDSetPlayThruGlobalRect, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, GrafPtr theWindow) -> (ComponentResult _rv, Rect globalRect)")},
+ {"VDSetBlackLevelValue", (PyCFunction)Qt_VDSetBlackLevelValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blackLevel)")},
+ {"VDGetBlackLevelValue", (PyCFunction)Qt_VDGetBlackLevelValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blackLevel)")},
+ {"VDSetWhiteLevelValue", (PyCFunction)Qt_VDSetWhiteLevelValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short whiteLevel)")},
+ {"VDGetWhiteLevelValue", (PyCFunction)Qt_VDGetWhiteLevelValue, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short whiteLevel)")},
+ {"VDGetVideoDefaults", (PyCFunction)Qt_VDGetVideoDefaults, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, unsigned short blackLevel, unsigned short whiteLevel, unsigned short brightness, unsigned short hue, unsigned short saturation, unsigned short contrast, unsigned short sharpness)")},
+ {"VDGetNumberOfInputs", (PyCFunction)Qt_VDGetNumberOfInputs, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short inputs)")},
+ {"VDGetInputFormat", (PyCFunction)Qt_VDGetInputFormat, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short input) -> (ComponentResult _rv, short format)")},
+ {"VDSetInput", (PyCFunction)Qt_VDSetInput, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short input) -> (ComponentResult _rv)")},
+ {"VDGetInput", (PyCFunction)Qt_VDGetInput, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, short input)")},
+ {"VDSetInputStandard", (PyCFunction)Qt_VDSetInputStandard, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short inputStandard) -> (ComponentResult _rv)")},
+ {"VDSetupBuffers", (PyCFunction)Qt_VDSetupBuffers, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, VdigBufferRecListHandle bufferList) -> (ComponentResult _rv)")},
+ {"VDGrabOneFrameAsync", (PyCFunction)Qt_VDGrabOneFrameAsync, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short buffer) -> (ComponentResult _rv)")},
+ {"VDDone", (PyCFunction)Qt_VDDone, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, short buffer) -> (ComponentResult _rv)")},
+ {"VDSetCompression", (PyCFunction)Qt_VDSetCompression, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, OSType compressType, short depth, CodecQ spatialQuality, CodecQ temporalQuality, long keyFrameRate) -> (ComponentResult _rv, Rect bounds)")},
+ {"VDCompressOneFrameAsync", (PyCFunction)Qt_VDCompressOneFrameAsync, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
+ {"VDGetImageDescription", (PyCFunction)Qt_VDGetImageDescription, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, ImageDescriptionHandle desc) -> (ComponentResult _rv)")},
+ {"VDResetCompressSequence", (PyCFunction)Qt_VDResetCompressSequence, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
+ {"VDSetCompressionOnOff", (PyCFunction)Qt_VDSetCompressionOnOff, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, Boolean state) -> (ComponentResult _rv)")},
+ {"VDGetCompressionTypes", (PyCFunction)Qt_VDGetCompressionTypes, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, VDCompressionListHandle h) -> (ComponentResult _rv)")},
+ {"VDSetTimeBase", (PyCFunction)Qt_VDSetTimeBase, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, TimeBase t) -> (ComponentResult _rv)")},
+ {"VDSetFrameRate", (PyCFunction)Qt_VDSetFrameRate, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, Fixed framesPerSecond) -> (ComponentResult _rv)")},
+ {"VDGetDataRate", (PyCFunction)Qt_VDGetDataRate, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long milliSecPerFrame, Fixed framesPerSecond, long bytesPerSecond)")},
+ {"VDGetSoundInputDriver", (PyCFunction)Qt_VDGetSoundInputDriver, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, Str255 soundDriverName) -> (ComponentResult _rv)")},
+ {"VDGetDMADepths", (PyCFunction)Qt_VDGetDMADepths, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long depthArray, long preferredDepth)")},
+ {"VDGetPreferredTimeScale", (PyCFunction)Qt_VDGetPreferredTimeScale, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, TimeScale preferred)")},
+ {"VDReleaseAsyncBuffers", (PyCFunction)Qt_VDReleaseAsyncBuffers, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv)")},
+ {"VDSetDataRate", (PyCFunction)Qt_VDSetDataRate, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long bytesPerSecond) -> (ComponentResult _rv)")},
+ {"VDGetTimeCode", (PyCFunction)Qt_VDGetTimeCode, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, void * timeCodeFormat, void * timeCodeTime) -> (ComponentResult _rv, TimeRecord atTime)")},
+ {"VDUseSafeBuffers", (PyCFunction)Qt_VDUseSafeBuffers, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, Boolean useSafeBuffers) -> (ComponentResult _rv)")},
+ {"VDGetSoundInputSource", (PyCFunction)Qt_VDGetSoundInputSource, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long videoInput) -> (ComponentResult _rv, long soundInput)")},
+ {"VDGetCompressionTime", (PyCFunction)Qt_VDGetCompressionTime, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, OSType compressionType, short depth) -> (ComponentResult _rv, Rect srcRect, CodecQ spatialQuality, CodecQ temporalQuality, unsigned long compressTime)")},
+ {"VDSetPreferredPacketSize", (PyCFunction)Qt_VDSetPreferredPacketSize, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long preferredPacketSizeInBytes) -> (ComponentResult _rv)")},
+ {"VDSetPreferredImageDimensions", (PyCFunction)Qt_VDSetPreferredImageDimensions, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long width, long height) -> (ComponentResult _rv)")},
+ {"VDGetPreferredImageDimensions", (PyCFunction)Qt_VDGetPreferredImageDimensions, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci) -> (ComponentResult _rv, long width, long height)")},
+ {"VDGetInputName", (PyCFunction)Qt_VDGetInputName, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, long videoInput, Str255 name) -> (ComponentResult _rv)")},
+ {"VDSetDestinationPort", (PyCFunction)Qt_VDSetDestinationPort, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, CGrafPtr destPort) -> (ComponentResult _rv)")},
+ {"VDGetDeviceNameAndFlags", (PyCFunction)Qt_VDGetDeviceNameAndFlags, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, Str255 outName) -> (ComponentResult _rv, UInt32 outNameFlags)")},
+ {"VDCaptureStateChanging", (PyCFunction)Qt_VDCaptureStateChanging, 1,
+ PyDoc_STR("(VideoDigitizerComponent ci, UInt32 inStateFlags) -> (ComponentResult _rv)")},
+ {"XMLParseGetDetailedParseError", (PyCFunction)Qt_XMLParseGetDetailedParseError, 1,
+ PyDoc_STR("(ComponentInstance aParser, StringPtr errDesc) -> (ComponentResult _rv, long errorLine)")},
+ {"XMLParseAddElement", (PyCFunction)Qt_XMLParseAddElement, 1,
+ PyDoc_STR("(ComponentInstance aParser, UInt32 nameSpaceID, long elementFlags) -> (ComponentResult _rv, char elementName, UInt32 elementID)")},
+ {"XMLParseAddAttribute", (PyCFunction)Qt_XMLParseAddAttribute, 1,
+ PyDoc_STR("(ComponentInstance aParser, UInt32 elementID, UInt32 nameSpaceID) -> (ComponentResult _rv, char attributeName, UInt32 attributeID)")},
+ {"XMLParseAddMultipleAttributes", (PyCFunction)Qt_XMLParseAddMultipleAttributes, 1,
+ PyDoc_STR("(ComponentInstance aParser, UInt32 elementID) -> (ComponentResult _rv, UInt32 nameSpaceIDs, char attributeNames, UInt32 attributeIDs)")},
+ {"XMLParseAddAttributeAndValue", (PyCFunction)Qt_XMLParseAddAttributeAndValue, 1,
+ PyDoc_STR("(ComponentInstance aParser, UInt32 elementID, UInt32 nameSpaceID, UInt32 attributeValueKind, void * attributeValueKindInfo) -> (ComponentResult _rv, char attributeName, UInt32 attributeID)")},
+ {"XMLParseAddAttributeValueKind", (PyCFunction)Qt_XMLParseAddAttributeValueKind, 1,
+ PyDoc_STR("(ComponentInstance aParser, UInt32 elementID, UInt32 attributeID, UInt32 attributeValueKind, void * attributeValueKindInfo) -> (ComponentResult _rv)")},
+ {"XMLParseAddNameSpace", (PyCFunction)Qt_XMLParseAddNameSpace, 1,
+ PyDoc_STR("(ComponentInstance aParser) -> (ComponentResult _rv, char nameSpaceURL, UInt32 nameSpaceID)")},
+ {"XMLParseSetOffsetAndLimit", (PyCFunction)Qt_XMLParseSetOffsetAndLimit, 1,
+ PyDoc_STR("(ComponentInstance aParser, UInt32 offset, UInt32 limit) -> (ComponentResult _rv)")},
+ {"XMLParseSetEventParseRefCon", (PyCFunction)Qt_XMLParseSetEventParseRefCon, 1,
+ PyDoc_STR("(ComponentInstance aParser, long refcon) -> (ComponentResult _rv)")},
+ {"SGInitialize", (PyCFunction)Qt_SGInitialize, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
+ {"SGSetDataOutput", (PyCFunction)Qt_SGSetDataOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, FSSpec movieFile, long whereFlags) -> (ComponentResult _rv)")},
+ {"SGGetDataOutput", (PyCFunction)Qt_SGGetDataOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, FSSpec movieFile) -> (ComponentResult _rv, long whereFlags)")},
+ {"SGSetGWorld", (PyCFunction)Qt_SGSetGWorld, 1,
+ PyDoc_STR("(SeqGrabComponent s, CGrafPtr gp, GDHandle gd) -> (ComponentResult _rv)")},
+ {"SGGetGWorld", (PyCFunction)Qt_SGGetGWorld, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, CGrafPtr gp, GDHandle gd)")},
+ {"SGNewChannel", (PyCFunction)Qt_SGNewChannel, 1,
+ PyDoc_STR("(SeqGrabComponent s, OSType channelType) -> (ComponentResult _rv, SGChannel ref)")},
+ {"SGDisposeChannel", (PyCFunction)Qt_SGDisposeChannel, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c) -> (ComponentResult _rv)")},
+ {"SGStartPreview", (PyCFunction)Qt_SGStartPreview, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
+ {"SGStartRecord", (PyCFunction)Qt_SGStartRecord, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
+ {"SGIdle", (PyCFunction)Qt_SGIdle, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
+ {"SGStop", (PyCFunction)Qt_SGStop, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
+ {"SGPause", (PyCFunction)Qt_SGPause, 1,
+ PyDoc_STR("(SeqGrabComponent s, Boolean pause) -> (ComponentResult _rv)")},
+ {"SGPrepare", (PyCFunction)Qt_SGPrepare, 1,
+ PyDoc_STR("(SeqGrabComponent s, Boolean prepareForPreview, Boolean prepareForRecord) -> (ComponentResult _rv)")},
+ {"SGRelease", (PyCFunction)Qt_SGRelease, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv)")},
+ {"SGGetMovie", (PyCFunction)Qt_SGGetMovie, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (Movie _rv)")},
+ {"SGSetMaximumRecordTime", (PyCFunction)Qt_SGSetMaximumRecordTime, 1,
+ PyDoc_STR("(SeqGrabComponent s, unsigned long ticks) -> (ComponentResult _rv)")},
+ {"SGGetMaximumRecordTime", (PyCFunction)Qt_SGGetMaximumRecordTime, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, unsigned long ticks)")},
+ {"SGGetStorageSpaceRemaining", (PyCFunction)Qt_SGGetStorageSpaceRemaining, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, unsigned long bytes)")},
+ {"SGGetTimeRemaining", (PyCFunction)Qt_SGGetTimeRemaining, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, long ticksLeft)")},
+ {"SGGrabPict", (PyCFunction)Qt_SGGrabPict, 1,
+ PyDoc_STR("(SeqGrabComponent s, Rect bounds, short offscreenDepth, long grabPictFlags) -> (ComponentResult _rv, PicHandle p)")},
+ {"SGGetLastMovieResID", (PyCFunction)Qt_SGGetLastMovieResID, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, short resID)")},
+ {"SGSetFlags", (PyCFunction)Qt_SGSetFlags, 1,
+ PyDoc_STR("(SeqGrabComponent s, long sgFlags) -> (ComponentResult _rv)")},
+ {"SGGetFlags", (PyCFunction)Qt_SGGetFlags, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, long sgFlags)")},
+ {"SGNewChannelFromComponent", (PyCFunction)Qt_SGNewChannelFromComponent, 1,
+ PyDoc_STR("(SeqGrabComponent s, Component sgChannelComponent) -> (ComponentResult _rv, SGChannel newChannel)")},
+ {"SGSetSettings", (PyCFunction)Qt_SGSetSettings, 1,
+ PyDoc_STR("(SeqGrabComponent s, UserData ud, long flags) -> (ComponentResult _rv)")},
+ {"SGGetSettings", (PyCFunction)Qt_SGGetSettings, 1,
+ PyDoc_STR("(SeqGrabComponent s, long flags) -> (ComponentResult _rv, UserData ud)")},
+ {"SGGetIndChannel", (PyCFunction)Qt_SGGetIndChannel, 1,
+ PyDoc_STR("(SeqGrabComponent s, short index) -> (ComponentResult _rv, SGChannel ref, OSType chanType)")},
+ {"SGUpdate", (PyCFunction)Qt_SGUpdate, 1,
+ PyDoc_STR("(SeqGrabComponent s, RgnHandle updateRgn) -> (ComponentResult _rv)")},
+ {"SGGetPause", (PyCFunction)Qt_SGGetPause, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Boolean paused)")},
+ {"SGSetChannelSettings", (PyCFunction)Qt_SGSetChannelSettings, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, UserData ud, long flags) -> (ComponentResult _rv)")},
+ {"SGGetChannelSettings", (PyCFunction)Qt_SGGetChannelSettings, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, long flags) -> (ComponentResult _rv, UserData ud)")},
+ {"SGGetMode", (PyCFunction)Qt_SGGetMode, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Boolean previewMode, Boolean recordMode)")},
+ {"SGSetDataRef", (PyCFunction)Qt_SGSetDataRef, 1,
+ PyDoc_STR("(SeqGrabComponent s, Handle dataRef, OSType dataRefType, long whereFlags) -> (ComponentResult _rv)")},
+ {"SGGetDataRef", (PyCFunction)Qt_SGGetDataRef, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType, long whereFlags)")},
+ {"SGNewOutput", (PyCFunction)Qt_SGNewOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, Handle dataRef, OSType dataRefType, long whereFlags) -> (ComponentResult _rv, SGOutput sgOut)")},
+ {"SGDisposeOutput", (PyCFunction)Qt_SGDisposeOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv)")},
+ {"SGSetOutputFlags", (PyCFunction)Qt_SGSetOutputFlags, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, long whereFlags) -> (ComponentResult _rv)")},
+ {"SGSetChannelOutput", (PyCFunction)Qt_SGSetChannelOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, SGOutput sgOut) -> (ComponentResult _rv)")},
+ {"SGGetDataOutputStorageSpaceRemaining", (PyCFunction)Qt_SGGetDataOutputStorageSpaceRemaining, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, unsigned long space)")},
+ {"SGHandleUpdateEvent", (PyCFunction)Qt_SGHandleUpdateEvent, 1,
+ PyDoc_STR("(SeqGrabComponent s, EventRecord event) -> (ComponentResult _rv, Boolean handled)")},
+ {"SGSetOutputNextOutput", (PyCFunction)Qt_SGSetOutputNextOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, SGOutput nextOut) -> (ComponentResult _rv)")},
+ {"SGGetOutputNextOutput", (PyCFunction)Qt_SGGetOutputNextOutput, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, SGOutput nextOut)")},
+ {"SGSetOutputMaximumOffset", (PyCFunction)Qt_SGSetOutputMaximumOffset, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, wide maxOffset) -> (ComponentResult _rv)")},
+ {"SGGetOutputMaximumOffset", (PyCFunction)Qt_SGGetOutputMaximumOffset, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, wide maxOffset)")},
+ {"SGGetOutputDataReference", (PyCFunction)Qt_SGGetOutputDataReference, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, Handle dataRef, OSType dataRefType)")},
+ {"SGWriteExtendedMovieData", (PyCFunction)Qt_SGWriteExtendedMovieData, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len) -> (ComponentResult _rv, wide offset, SGOutput sgOut)")},
+ {"SGGetStorageSpaceRemaining64", (PyCFunction)Qt_SGGetStorageSpaceRemaining64, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, wide bytes)")},
+ {"SGGetDataOutputStorageSpaceRemaining64", (PyCFunction)Qt_SGGetDataOutputStorageSpaceRemaining64, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut) -> (ComponentResult _rv, wide space)")},
+ {"SGWriteMovieData", (PyCFunction)Qt_SGWriteMovieData, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len) -> (ComponentResult _rv, long offset)")},
+ {"SGGetTimeBase", (PyCFunction)Qt_SGGetTimeBase, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, TimeBase tb)")},
+ {"SGAddMovieData", (PyCFunction)Qt_SGAddMovieData, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len, long chRefCon, TimeValue time, short writeType) -> (ComponentResult _rv, long offset)")},
+ {"SGChangedSource", (PyCFunction)Qt_SGChangedSource, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c) -> (ComponentResult _rv)")},
+ {"SGAddExtendedMovieData", (PyCFunction)Qt_SGAddExtendedMovieData, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, Ptr p, long len, long chRefCon, TimeValue time, short writeType) -> (ComponentResult _rv, wide offset, SGOutput whichOutput)")},
+ {"SGAddOutputDataRefToMedia", (PyCFunction)Qt_SGAddOutputDataRefToMedia, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGOutput sgOut, Media theMedia, SampleDescriptionHandle desc) -> (ComponentResult _rv)")},
+ {"SGSetSettingsSummary", (PyCFunction)Qt_SGSetSettingsSummary, 1,
+ PyDoc_STR("(SeqGrabComponent s, Handle summaryText) -> (ComponentResult _rv)")},
+ {"SGSetChannelUsage", (PyCFunction)Qt_SGSetChannelUsage, 1,
+ PyDoc_STR("(SGChannel c, long usage) -> (ComponentResult _rv)")},
+ {"SGGetChannelUsage", (PyCFunction)Qt_SGGetChannelUsage, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long usage)")},
+ {"SGSetChannelBounds", (PyCFunction)Qt_SGSetChannelBounds, 1,
+ PyDoc_STR("(SGChannel c, Rect bounds) -> (ComponentResult _rv)")},
+ {"SGGetChannelBounds", (PyCFunction)Qt_SGGetChannelBounds, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect bounds)")},
+ {"SGSetChannelVolume", (PyCFunction)Qt_SGSetChannelVolume, 1,
+ PyDoc_STR("(SGChannel c, short volume) -> (ComponentResult _rv)")},
+ {"SGGetChannelVolume", (PyCFunction)Qt_SGGetChannelVolume, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short volume)")},
+ {"SGGetChannelInfo", (PyCFunction)Qt_SGGetChannelInfo, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long channelInfo)")},
+ {"SGSetChannelPlayFlags", (PyCFunction)Qt_SGSetChannelPlayFlags, 1,
+ PyDoc_STR("(SGChannel c, long playFlags) -> (ComponentResult _rv)")},
+ {"SGGetChannelPlayFlags", (PyCFunction)Qt_SGGetChannelPlayFlags, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long playFlags)")},
+ {"SGSetChannelMaxFrames", (PyCFunction)Qt_SGSetChannelMaxFrames, 1,
+ PyDoc_STR("(SGChannel c, long frameCount) -> (ComponentResult _rv)")},
+ {"SGGetChannelMaxFrames", (PyCFunction)Qt_SGGetChannelMaxFrames, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long frameCount)")},
+ {"SGSetChannelRefCon", (PyCFunction)Qt_SGSetChannelRefCon, 1,
+ PyDoc_STR("(SGChannel c, long refCon) -> (ComponentResult _rv)")},
+ {"SGSetChannelClip", (PyCFunction)Qt_SGSetChannelClip, 1,
+ PyDoc_STR("(SGChannel c, RgnHandle theClip) -> (ComponentResult _rv)")},
+ {"SGGetChannelClip", (PyCFunction)Qt_SGGetChannelClip, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, RgnHandle theClip)")},
+ {"SGGetChannelSampleDescription", (PyCFunction)Qt_SGGetChannelSampleDescription, 1,
+ PyDoc_STR("(SGChannel c, Handle sampleDesc) -> (ComponentResult _rv)")},
+ {"SGSetChannelDevice", (PyCFunction)Qt_SGSetChannelDevice, 1,
+ PyDoc_STR("(SGChannel c, StringPtr name) -> (ComponentResult _rv)")},
+ {"SGGetChannelTimeScale", (PyCFunction)Qt_SGGetChannelTimeScale, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, TimeScale scale)")},
+ {"SGChannelPutPicture", (PyCFunction)Qt_SGChannelPutPicture, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv)")},
+ {"SGChannelSetRequestedDataRate", (PyCFunction)Qt_SGChannelSetRequestedDataRate, 1,
+ PyDoc_STR("(SGChannel c, long bytesPerSecond) -> (ComponentResult _rv)")},
+ {"SGChannelGetRequestedDataRate", (PyCFunction)Qt_SGChannelGetRequestedDataRate, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long bytesPerSecond)")},
+ {"SGChannelSetDataSourceName", (PyCFunction)Qt_SGChannelSetDataSourceName, 1,
+ PyDoc_STR("(SGChannel c, Str255 name, ScriptCode scriptTag) -> (ComponentResult _rv)")},
+ {"SGChannelGetDataSourceName", (PyCFunction)Qt_SGChannelGetDataSourceName, 1,
+ PyDoc_STR("(SGChannel c, Str255 name) -> (ComponentResult _rv, ScriptCode scriptTag)")},
+ {"SGChannelSetCodecSettings", (PyCFunction)Qt_SGChannelSetCodecSettings, 1,
+ PyDoc_STR("(SGChannel c, Handle settings) -> (ComponentResult _rv)")},
+ {"SGChannelGetCodecSettings", (PyCFunction)Qt_SGChannelGetCodecSettings, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Handle settings)")},
+ {"SGGetChannelTimeBase", (PyCFunction)Qt_SGGetChannelTimeBase, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, TimeBase tb)")},
+ {"SGGetChannelRefCon", (PyCFunction)Qt_SGGetChannelRefCon, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long refCon)")},
+ {"SGGetChannelDeviceAndInputNames", (PyCFunction)Qt_SGGetChannelDeviceAndInputNames, 1,
+ PyDoc_STR("(SGChannel c, Str255 outDeviceName, Str255 outInputName) -> (ComponentResult _rv, short outInputNumber)")},
+ {"SGSetChannelDeviceInput", (PyCFunction)Qt_SGSetChannelDeviceInput, 1,
+ PyDoc_STR("(SGChannel c, short inInputNumber) -> (ComponentResult _rv)")},
+ {"SGSetChannelSettingsStateChanging", (PyCFunction)Qt_SGSetChannelSettingsStateChanging, 1,
+ PyDoc_STR("(SGChannel c, UInt32 inFlags) -> (ComponentResult _rv)")},
+ {"SGInitChannel", (PyCFunction)Qt_SGInitChannel, 1,
+ PyDoc_STR("(SGChannel c, SeqGrabComponent owner) -> (ComponentResult _rv)")},
+ {"SGWriteSamples", (PyCFunction)Qt_SGWriteSamples, 1,
+ PyDoc_STR("(SGChannel c, Movie m, AliasHandle theFile) -> (ComponentResult _rv)")},
+ {"SGGetDataRate", (PyCFunction)Qt_SGGetDataRate, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long bytesPerSecond)")},
+ {"SGAlignChannelRect", (PyCFunction)Qt_SGAlignChannelRect, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect r)")},
+ {"SGPanelGetDitl", (PyCFunction)Qt_SGPanelGetDitl, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Handle ditl)")},
+ {"SGPanelGetTitle", (PyCFunction)Qt_SGPanelGetTitle, 1,
+ PyDoc_STR("(SeqGrabComponent s, Str255 title) -> (ComponentResult _rv)")},
+ {"SGPanelCanRun", (PyCFunction)Qt_SGPanelCanRun, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c) -> (ComponentResult _rv)")},
+ {"SGPanelInstall", (PyCFunction)Qt_SGPanelInstall, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset) -> (ComponentResult _rv)")},
+ {"SGPanelEvent", (PyCFunction)Qt_SGPanelEvent, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset, EventRecord theEvent) -> (ComponentResult _rv, short itemHit, Boolean handled)")},
+ {"SGPanelItem", (PyCFunction)Qt_SGPanelItem, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset, short itemNum) -> (ComponentResult _rv)")},
+ {"SGPanelRemove", (PyCFunction)Qt_SGPanelRemove, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, DialogPtr d, short itemOffset) -> (ComponentResult _rv)")},
+ {"SGPanelSetGrabber", (PyCFunction)Qt_SGPanelSetGrabber, 1,
+ PyDoc_STR("(SeqGrabComponent s, SeqGrabComponent sg) -> (ComponentResult _rv)")},
+ {"SGPanelSetResFile", (PyCFunction)Qt_SGPanelSetResFile, 1,
+ PyDoc_STR("(SeqGrabComponent s, short resRef) -> (ComponentResult _rv)")},
+ {"SGPanelGetSettings", (PyCFunction)Qt_SGPanelGetSettings, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, long flags) -> (ComponentResult _rv, UserData ud)")},
+ {"SGPanelSetSettings", (PyCFunction)Qt_SGPanelSetSettings, 1,
+ PyDoc_STR("(SeqGrabComponent s, SGChannel c, UserData ud, long flags) -> (ComponentResult _rv)")},
+ {"SGPanelValidateInput", (PyCFunction)Qt_SGPanelValidateInput, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Boolean ok)")},
+ {"SGPanelGetDITLForSize", (PyCFunction)Qt_SGPanelGetDITLForSize, 1,
+ PyDoc_STR("(SeqGrabComponent s) -> (ComponentResult _rv, Handle ditl, Point requestedSize)")},
+ {"SGGetSrcVideoBounds", (PyCFunction)Qt_SGGetSrcVideoBounds, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect r)")},
+ {"SGSetVideoRect", (PyCFunction)Qt_SGSetVideoRect, 1,
+ PyDoc_STR("(SGChannel c, Rect r) -> (ComponentResult _rv)")},
+ {"SGGetVideoRect", (PyCFunction)Qt_SGGetVideoRect, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Rect r)")},
+ {"SGGetVideoCompressorType", (PyCFunction)Qt_SGGetVideoCompressorType, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, OSType compressorType)")},
+ {"SGSetVideoCompressorType", (PyCFunction)Qt_SGSetVideoCompressorType, 1,
+ PyDoc_STR("(SGChannel c, OSType compressorType) -> (ComponentResult _rv)")},
+ {"SGSetVideoCompressor", (PyCFunction)Qt_SGSetVideoCompressor, 1,
+ PyDoc_STR("(SGChannel c, short depth, CompressorComponent compressor, CodecQ spatialQuality, CodecQ temporalQuality, long keyFrameRate) -> (ComponentResult _rv)")},
+ {"SGGetVideoCompressor", (PyCFunction)Qt_SGGetVideoCompressor, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short depth, CompressorComponent compressor, CodecQ spatialQuality, CodecQ temporalQuality, long keyFrameRate)")},
+ {"SGGetVideoDigitizerComponent", (PyCFunction)Qt_SGGetVideoDigitizerComponent, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentInstance _rv)")},
+ {"SGSetVideoDigitizerComponent", (PyCFunction)Qt_SGSetVideoDigitizerComponent, 1,
+ PyDoc_STR("(SGChannel c, ComponentInstance vdig) -> (ComponentResult _rv)")},
+ {"SGVideoDigitizerChanged", (PyCFunction)Qt_SGVideoDigitizerChanged, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv)")},
+ {"SGGrabFrame", (PyCFunction)Qt_SGGrabFrame, 1,
+ PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv)")},
+ {"SGGrabFrameComplete", (PyCFunction)Qt_SGGrabFrameComplete, 1,
+ PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv, Boolean done)")},
+ {"SGCompressFrame", (PyCFunction)Qt_SGCompressFrame, 1,
+ PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv)")},
+ {"SGSetCompressBuffer", (PyCFunction)Qt_SGSetCompressBuffer, 1,
+ PyDoc_STR("(SGChannel c, short depth, Rect compressSize) -> (ComponentResult _rv)")},
+ {"SGGetCompressBuffer", (PyCFunction)Qt_SGGetCompressBuffer, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short depth, Rect compressSize)")},
+ {"SGGetBufferInfo", (PyCFunction)Qt_SGGetBufferInfo, 1,
+ PyDoc_STR("(SGChannel c, short bufferNum) -> (ComponentResult _rv, PixMapHandle bufferPM, Rect bufferRect, GWorldPtr compressBuffer, Rect compressBufferRect)")},
+ {"SGSetUseScreenBuffer", (PyCFunction)Qt_SGSetUseScreenBuffer, 1,
+ PyDoc_STR("(SGChannel c, Boolean useScreenBuffer) -> (ComponentResult _rv)")},
+ {"SGGetUseScreenBuffer", (PyCFunction)Qt_SGGetUseScreenBuffer, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Boolean useScreenBuffer)")},
+ {"SGSetFrameRate", (PyCFunction)Qt_SGSetFrameRate, 1,
+ PyDoc_STR("(SGChannel c, Fixed frameRate) -> (ComponentResult _rv)")},
+ {"SGGetFrameRate", (PyCFunction)Qt_SGGetFrameRate, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Fixed frameRate)")},
+ {"SGSetPreferredPacketSize", (PyCFunction)Qt_SGSetPreferredPacketSize, 1,
+ PyDoc_STR("(SGChannel c, long preferredPacketSizeInBytes) -> (ComponentResult _rv)")},
+ {"SGGetPreferredPacketSize", (PyCFunction)Qt_SGGetPreferredPacketSize, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, long preferredPacketSizeInBytes)")},
+ {"SGSetUserVideoCompressorList", (PyCFunction)Qt_SGSetUserVideoCompressorList, 1,
+ PyDoc_STR("(SGChannel c, Handle compressorTypes) -> (ComponentResult _rv)")},
+ {"SGGetUserVideoCompressorList", (PyCFunction)Qt_SGGetUserVideoCompressorList, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Handle compressorTypes)")},
+ {"SGSetSoundInputDriver", (PyCFunction)Qt_SGSetSoundInputDriver, 1,
+ PyDoc_STR("(SGChannel c, Str255 driverName) -> (ComponentResult _rv)")},
+ {"SGGetSoundInputDriver", (PyCFunction)Qt_SGGetSoundInputDriver, 1,
+ PyDoc_STR("(SGChannel c) -> (long _rv)")},
+ {"SGSoundInputDriverChanged", (PyCFunction)Qt_SGSoundInputDriverChanged, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv)")},
+ {"SGSetSoundRecordChunkSize", (PyCFunction)Qt_SGSetSoundRecordChunkSize, 1,
+ PyDoc_STR("(SGChannel c, long seconds) -> (ComponentResult _rv)")},
+ {"SGGetSoundRecordChunkSize", (PyCFunction)Qt_SGGetSoundRecordChunkSize, 1,
+ PyDoc_STR("(SGChannel c) -> (long _rv)")},
+ {"SGSetSoundInputRate", (PyCFunction)Qt_SGSetSoundInputRate, 1,
+ PyDoc_STR("(SGChannel c, Fixed rate) -> (ComponentResult _rv)")},
+ {"SGGetSoundInputRate", (PyCFunction)Qt_SGGetSoundInputRate, 1,
+ PyDoc_STR("(SGChannel c) -> (Fixed _rv)")},
+ {"SGSetSoundInputParameters", (PyCFunction)Qt_SGSetSoundInputParameters, 1,
+ PyDoc_STR("(SGChannel c, short sampleSize, short numChannels, OSType compressionType) -> (ComponentResult _rv)")},
+ {"SGGetSoundInputParameters", (PyCFunction)Qt_SGGetSoundInputParameters, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short sampleSize, short numChannels, OSType compressionType)")},
+ {"SGSetAdditionalSoundRates", (PyCFunction)Qt_SGSetAdditionalSoundRates, 1,
+ PyDoc_STR("(SGChannel c, Handle rates) -> (ComponentResult _rv)")},
+ {"SGGetAdditionalSoundRates", (PyCFunction)Qt_SGGetAdditionalSoundRates, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, Handle rates)")},
+ {"SGSetFontName", (PyCFunction)Qt_SGSetFontName, 1,
+ PyDoc_STR("(SGChannel c, StringPtr pstr) -> (ComponentResult _rv)")},
+ {"SGSetFontSize", (PyCFunction)Qt_SGSetFontSize, 1,
+ PyDoc_STR("(SGChannel c, short fontSize) -> (ComponentResult _rv)")},
+ {"SGSetTextForeColor", (PyCFunction)Qt_SGSetTextForeColor, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, RGBColor theColor)")},
+ {"SGSetTextBackColor", (PyCFunction)Qt_SGSetTextBackColor, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, RGBColor theColor)")},
+ {"SGSetJustification", (PyCFunction)Qt_SGSetJustification, 1,
+ PyDoc_STR("(SGChannel c, short just) -> (ComponentResult _rv)")},
+ {"SGGetTextReturnToSpaceValue", (PyCFunction)Qt_SGGetTextReturnToSpaceValue, 1,
+ PyDoc_STR("(SGChannel c) -> (ComponentResult _rv, short rettospace)")},
+ {"SGSetTextReturnToSpaceValue", (PyCFunction)Qt_SGSetTextReturnToSpaceValue, 1,
+ PyDoc_STR("(SGChannel c, short rettospace) -> (ComponentResult _rv)")},
+ {"QTVideoOutputGetCurrentClientName", (PyCFunction)Qt_QTVideoOutputGetCurrentClientName, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, Str255 str) -> (ComponentResult _rv)")},
+ {"QTVideoOutputSetClientName", (PyCFunction)Qt_QTVideoOutputSetClientName, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, Str255 str) -> (ComponentResult _rv)")},
+ {"QTVideoOutputGetClientName", (PyCFunction)Qt_QTVideoOutputGetClientName, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, Str255 str) -> (ComponentResult _rv)")},
+ {"QTVideoOutputBegin", (PyCFunction)Qt_QTVideoOutputBegin, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv)")},
+ {"QTVideoOutputEnd", (PyCFunction)Qt_QTVideoOutputEnd, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv)")},
+ {"QTVideoOutputSetDisplayMode", (PyCFunction)Qt_QTVideoOutputSetDisplayMode, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, long displayModeID) -> (ComponentResult _rv)")},
+ {"QTVideoOutputGetDisplayMode", (PyCFunction)Qt_QTVideoOutputGetDisplayMode, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv, long displayModeID)")},
+ {"QTVideoOutputGetGWorld", (PyCFunction)Qt_QTVideoOutputGetGWorld, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv, GWorldPtr gw)")},
+ {"QTVideoOutputGetIndSoundOutput", (PyCFunction)Qt_QTVideoOutputGetIndSoundOutput, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, long index) -> (ComponentResult _rv, Component outputComponent)")},
+ {"QTVideoOutputGetClock", (PyCFunction)Qt_QTVideoOutputGetClock, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo) -> (ComponentResult _rv, ComponentInstance clock)")},
+ {"QTVideoOutputSetEchoPort", (PyCFunction)Qt_QTVideoOutputSetEchoPort, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, CGrafPtr echoPort) -> (ComponentResult _rv)")},
+ {"QTVideoOutputGetIndImageDecompressor", (PyCFunction)Qt_QTVideoOutputGetIndImageDecompressor, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, long index) -> (ComponentResult _rv, Component codec)")},
+ {"QTVideoOutputBaseSetEchoPort", (PyCFunction)Qt_QTVideoOutputBaseSetEchoPort, 1,
+ PyDoc_STR("(QTVideoOutputComponent vo, CGrafPtr echoPort) -> (ComponentResult _rv)")},
+ {"MediaSetChunkManagementFlags", (PyCFunction)Qt_MediaSetChunkManagementFlags, 1,
+ PyDoc_STR("(MediaHandler mh, UInt32 flags, UInt32 flagsMask) -> (ComponentResult _rv)")},
+ {"MediaGetChunkManagementFlags", (PyCFunction)Qt_MediaGetChunkManagementFlags, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt32 flags)")},
+ {"MediaSetPurgeableChunkMemoryAllowance", (PyCFunction)Qt_MediaSetPurgeableChunkMemoryAllowance, 1,
+ PyDoc_STR("(MediaHandler mh, Size allowance) -> (ComponentResult _rv)")},
+ {"MediaGetPurgeableChunkMemoryAllowance", (PyCFunction)Qt_MediaGetPurgeableChunkMemoryAllowance, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Size allowance)")},
+ {"MediaEmptyAllPurgeableChunks", (PyCFunction)Qt_MediaEmptyAllPurgeableChunks, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaSetHandlerCapabilities", (PyCFunction)Qt_MediaSetHandlerCapabilities, 1,
+ PyDoc_STR("(MediaHandler mh, long flags, long flagsMask) -> (ComponentResult _rv)")},
+ {"MediaIdle", (PyCFunction)Qt_MediaIdle, 1,
+ PyDoc_STR("(MediaHandler mh, TimeValue atMediaTime, long flagsIn, TimeRecord movieTime) -> (ComponentResult _rv, long flagsOut)")},
+ {"MediaGetMediaInfo", (PyCFunction)Qt_MediaGetMediaInfo, 1,
+ PyDoc_STR("(MediaHandler mh, Handle h) -> (ComponentResult _rv)")},
+ {"MediaPutMediaInfo", (PyCFunction)Qt_MediaPutMediaInfo, 1,
+ PyDoc_STR("(MediaHandler mh, Handle h) -> (ComponentResult _rv)")},
+ {"MediaSetActive", (PyCFunction)Qt_MediaSetActive, 1,
+ PyDoc_STR("(MediaHandler mh, Boolean enableMedia) -> (ComponentResult _rv)")},
+ {"MediaSetRate", (PyCFunction)Qt_MediaSetRate, 1,
+ PyDoc_STR("(MediaHandler mh, Fixed rate) -> (ComponentResult _rv)")},
+ {"MediaGGetStatus", (PyCFunction)Qt_MediaGGetStatus, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, ComponentResult statusErr)")},
+ {"MediaTrackEdited", (PyCFunction)Qt_MediaTrackEdited, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaSetMediaTimeScale", (PyCFunction)Qt_MediaSetMediaTimeScale, 1,
+ PyDoc_STR("(MediaHandler mh, TimeScale newTimeScale) -> (ComponentResult _rv)")},
+ {"MediaSetMovieTimeScale", (PyCFunction)Qt_MediaSetMovieTimeScale, 1,
+ PyDoc_STR("(MediaHandler mh, TimeScale newTimeScale) -> (ComponentResult _rv)")},
+ {"MediaSetGWorld", (PyCFunction)Qt_MediaSetGWorld, 1,
+ PyDoc_STR("(MediaHandler mh, CGrafPtr aPort, GDHandle aGD) -> (ComponentResult _rv)")},
+ {"MediaSetDimensions", (PyCFunction)Qt_MediaSetDimensions, 1,
+ PyDoc_STR("(MediaHandler mh, Fixed width, Fixed height) -> (ComponentResult _rv)")},
+ {"MediaSetClip", (PyCFunction)Qt_MediaSetClip, 1,
+ PyDoc_STR("(MediaHandler mh, RgnHandle theClip) -> (ComponentResult _rv)")},
+ {"MediaGetTrackOpaque", (PyCFunction)Qt_MediaGetTrackOpaque, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Boolean trackIsOpaque)")},
+ {"MediaSetGraphicsMode", (PyCFunction)Qt_MediaSetGraphicsMode, 1,
+ PyDoc_STR("(MediaHandler mh, long mode, RGBColor opColor) -> (ComponentResult _rv)")},
+ {"MediaGetGraphicsMode", (PyCFunction)Qt_MediaGetGraphicsMode, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long mode, RGBColor opColor)")},
+ {"MediaGSetVolume", (PyCFunction)Qt_MediaGSetVolume, 1,
+ PyDoc_STR("(MediaHandler mh, short volume) -> (ComponentResult _rv)")},
+ {"MediaSetSoundBalance", (PyCFunction)Qt_MediaSetSoundBalance, 1,
+ PyDoc_STR("(MediaHandler mh, short balance) -> (ComponentResult _rv)")},
+ {"MediaGetSoundBalance", (PyCFunction)Qt_MediaGetSoundBalance, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short balance)")},
+ {"MediaGetNextBoundsChange", (PyCFunction)Qt_MediaGetNextBoundsChange, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, TimeValue when)")},
+ {"MediaGetSrcRgn", (PyCFunction)Qt_MediaGetSrcRgn, 1,
+ PyDoc_STR("(MediaHandler mh, RgnHandle rgn, TimeValue atMediaTime) -> (ComponentResult _rv)")},
+ {"MediaPreroll", (PyCFunction)Qt_MediaPreroll, 1,
+ PyDoc_STR("(MediaHandler mh, TimeValue time, Fixed rate) -> (ComponentResult _rv)")},
+ {"MediaSampleDescriptionChanged", (PyCFunction)Qt_MediaSampleDescriptionChanged, 1,
+ PyDoc_STR("(MediaHandler mh, long index) -> (ComponentResult _rv)")},
+ {"MediaHasCharacteristic", (PyCFunction)Qt_MediaHasCharacteristic, 1,
+ PyDoc_STR("(MediaHandler mh, OSType characteristic) -> (ComponentResult _rv, Boolean hasIt)")},
+ {"MediaGetOffscreenBufferSize", (PyCFunction)Qt_MediaGetOffscreenBufferSize, 1,
+ PyDoc_STR("(MediaHandler mh, short depth, CTabHandle ctab) -> (ComponentResult _rv, Rect bounds)")},
+ {"MediaSetHints", (PyCFunction)Qt_MediaSetHints, 1,
+ PyDoc_STR("(MediaHandler mh, long hints) -> (ComponentResult _rv)")},
+ {"MediaGetName", (PyCFunction)Qt_MediaGetName, 1,
+ PyDoc_STR("(MediaHandler mh, Str255 name, long requestedLanguage) -> (ComponentResult _rv, long actualLanguage)")},
+ {"MediaForceUpdate", (PyCFunction)Qt_MediaForceUpdate, 1,
+ PyDoc_STR("(MediaHandler mh, long forceUpdateFlags) -> (ComponentResult _rv)")},
+ {"MediaGetDrawingRgn", (PyCFunction)Qt_MediaGetDrawingRgn, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, RgnHandle partialRgn)")},
+ {"MediaGSetActiveSegment", (PyCFunction)Qt_MediaGSetActiveSegment, 1,
+ PyDoc_STR("(MediaHandler mh, TimeValue activeStart, TimeValue activeDuration) -> (ComponentResult _rv)")},
+ {"MediaInvalidateRegion", (PyCFunction)Qt_MediaInvalidateRegion, 1,
+ PyDoc_STR("(MediaHandler mh, RgnHandle invalRgn) -> (ComponentResult _rv)")},
+ {"MediaGetNextStepTime", (PyCFunction)Qt_MediaGetNextStepTime, 1,
+ PyDoc_STR("(MediaHandler mh, short flags, TimeValue mediaTimeIn, Fixed rate) -> (ComponentResult _rv, TimeValue mediaTimeOut)")},
+ {"MediaChangedNonPrimarySource", (PyCFunction)Qt_MediaChangedNonPrimarySource, 1,
+ PyDoc_STR("(MediaHandler mh, long inputIndex) -> (ComponentResult _rv)")},
+ {"MediaTrackReferencesChanged", (PyCFunction)Qt_MediaTrackReferencesChanged, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaReleaseSampleDataPointer", (PyCFunction)Qt_MediaReleaseSampleDataPointer, 1,
+ PyDoc_STR("(MediaHandler mh, long sampleNum) -> (ComponentResult _rv)")},
+ {"MediaTrackPropertyAtomChanged", (PyCFunction)Qt_MediaTrackPropertyAtomChanged, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaSetVideoParam", (PyCFunction)Qt_MediaSetVideoParam, 1,
+ PyDoc_STR("(MediaHandler mh, long whichParam) -> (ComponentResult _rv, unsigned short value)")},
+ {"MediaGetVideoParam", (PyCFunction)Qt_MediaGetVideoParam, 1,
+ PyDoc_STR("(MediaHandler mh, long whichParam) -> (ComponentResult _rv, unsigned short value)")},
+ {"MediaCompare", (PyCFunction)Qt_MediaCompare, 1,
+ PyDoc_STR("(MediaHandler mh, Media srcMedia, ComponentInstance srcMediaComponent) -> (ComponentResult _rv, Boolean isOK)")},
+ {"MediaGetClock", (PyCFunction)Qt_MediaGetClock, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, ComponentInstance clock)")},
+ {"MediaSetSoundOutputComponent", (PyCFunction)Qt_MediaSetSoundOutputComponent, 1,
+ PyDoc_STR("(MediaHandler mh, Component outputComponent) -> (ComponentResult _rv)")},
+ {"MediaGetSoundOutputComponent", (PyCFunction)Qt_MediaGetSoundOutputComponent, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Component outputComponent)")},
+ {"MediaSetSoundLocalizationData", (PyCFunction)Qt_MediaSetSoundLocalizationData, 1,
+ PyDoc_STR("(MediaHandler mh, Handle data) -> (ComponentResult _rv)")},
+ {"MediaGetInvalidRegion", (PyCFunction)Qt_MediaGetInvalidRegion, 1,
+ PyDoc_STR("(MediaHandler mh, RgnHandle rgn) -> (ComponentResult _rv)")},
+ {"MediaSampleDescriptionB2N", (PyCFunction)Qt_MediaSampleDescriptionB2N, 1,
+ PyDoc_STR("(MediaHandler mh, SampleDescriptionHandle sampleDescriptionH) -> (ComponentResult _rv)")},
+ {"MediaSampleDescriptionN2B", (PyCFunction)Qt_MediaSampleDescriptionN2B, 1,
+ PyDoc_STR("(MediaHandler mh, SampleDescriptionHandle sampleDescriptionH) -> (ComponentResult _rv)")},
+ {"MediaFlushNonPrimarySourceData", (PyCFunction)Qt_MediaFlushNonPrimarySourceData, 1,
+ PyDoc_STR("(MediaHandler mh, long inputIndex) -> (ComponentResult _rv)")},
+ {"MediaGetURLLink", (PyCFunction)Qt_MediaGetURLLink, 1,
+ PyDoc_STR("(MediaHandler mh, Point displayWhere) -> (ComponentResult _rv, Handle urlLink)")},
+ {"MediaHitTestForTargetRefCon", (PyCFunction)Qt_MediaHitTestForTargetRefCon, 1,
+ PyDoc_STR("(MediaHandler mh, long flags, Point loc) -> (ComponentResult _rv, long targetRefCon)")},
+ {"MediaHitTestTargetRefCon", (PyCFunction)Qt_MediaHitTestTargetRefCon, 1,
+ PyDoc_STR("(MediaHandler mh, long targetRefCon, long flags, Point loc) -> (ComponentResult _rv, Boolean wasHit)")},
+ {"MediaDisposeTargetRefCon", (PyCFunction)Qt_MediaDisposeTargetRefCon, 1,
+ PyDoc_STR("(MediaHandler mh, long targetRefCon) -> (ComponentResult _rv)")},
+ {"MediaTargetRefConsEqual", (PyCFunction)Qt_MediaTargetRefConsEqual, 1,
+ PyDoc_STR("(MediaHandler mh, long firstRefCon, long secondRefCon) -> (ComponentResult _rv, Boolean equal)")},
+ {"MediaPrePrerollCancel", (PyCFunction)Qt_MediaPrePrerollCancel, 1,
+ PyDoc_STR("(MediaHandler mh, void * refcon) -> (ComponentResult _rv)")},
+ {"MediaEnterEmptyEdit", (PyCFunction)Qt_MediaEnterEmptyEdit, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaCurrentMediaQueuedData", (PyCFunction)Qt_MediaCurrentMediaQueuedData, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long milliSecs)")},
+ {"MediaGetEffectiveVolume", (PyCFunction)Qt_MediaGetEffectiveVolume, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short volume)")},
+ {"MediaGetSoundLevelMeteringEnabled", (PyCFunction)Qt_MediaGetSoundLevelMeteringEnabled, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, Boolean enabled)")},
+ {"MediaSetSoundLevelMeteringEnabled", (PyCFunction)Qt_MediaSetSoundLevelMeteringEnabled, 1,
+ PyDoc_STR("(MediaHandler mh, Boolean enable) -> (ComponentResult _rv)")},
+ {"MediaGetEffectiveSoundBalance", (PyCFunction)Qt_MediaGetEffectiveSoundBalance, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short balance)")},
+ {"MediaSetScreenLock", (PyCFunction)Qt_MediaSetScreenLock, 1,
+ PyDoc_STR("(MediaHandler mh, Boolean lockIt) -> (ComponentResult _rv)")},
+ {"MediaGetErrorString", (PyCFunction)Qt_MediaGetErrorString, 1,
+ PyDoc_STR("(MediaHandler mh, ComponentResult theError, Str255 errorString) -> (ComponentResult _rv)")},
+ {"MediaGetSoundEqualizerBandLevels", (PyCFunction)Qt_MediaGetSoundEqualizerBandLevels, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, UInt8 bandLevels)")},
+ {"MediaDoIdleActions", (PyCFunction)Qt_MediaDoIdleActions, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaSetSoundBassAndTreble", (PyCFunction)Qt_MediaSetSoundBassAndTreble, 1,
+ PyDoc_STR("(MediaHandler mh, short bass, short treble) -> (ComponentResult _rv)")},
+ {"MediaGetSoundBassAndTreble", (PyCFunction)Qt_MediaGetSoundBassAndTreble, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, short bass, short treble)")},
+ {"MediaTimeBaseChanged", (PyCFunction)Qt_MediaTimeBaseChanged, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv)")},
+ {"MediaMCIsPlayerEvent", (PyCFunction)Qt_MediaMCIsPlayerEvent, 1,
+ PyDoc_STR("(MediaHandler mh, EventRecord e) -> (ComponentResult _rv, Boolean handledIt)")},
+ {"MediaGetMediaLoadState", (PyCFunction)Qt_MediaGetMediaLoadState, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, long mediaLoadState)")},
+ {"MediaVideoOutputChanged", (PyCFunction)Qt_MediaVideoOutputChanged, 1,
+ PyDoc_STR("(MediaHandler mh, ComponentInstance vout) -> (ComponentResult _rv)")},
+ {"MediaEmptySampleCache", (PyCFunction)Qt_MediaEmptySampleCache, 1,
+ PyDoc_STR("(MediaHandler mh, long sampleNum, long sampleCount) -> (ComponentResult _rv)")},
+ {"MediaGetPublicInfo", (PyCFunction)Qt_MediaGetPublicInfo, 1,
+ PyDoc_STR("(MediaHandler mh, OSType infoSelector, void * infoDataPtr) -> (ComponentResult _rv, Size ioDataSize)")},
+ {"MediaSetPublicInfo", (PyCFunction)Qt_MediaSetPublicInfo, 1,
+ PyDoc_STR("(MediaHandler mh, OSType infoSelector, void * infoDataPtr, Size dataSize) -> (ComponentResult _rv)")},
+ {"MediaRefConSetProperty", (PyCFunction)Qt_MediaRefConSetProperty, 1,
+ PyDoc_STR("(MediaHandler mh, long refCon, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
+ {"MediaRefConGetProperty", (PyCFunction)Qt_MediaRefConGetProperty, 1,
+ PyDoc_STR("(MediaHandler mh, long refCon, long propertyType, void * propertyValue) -> (ComponentResult _rv)")},
+ {"MediaNavigateTargetRefCon", (PyCFunction)Qt_MediaNavigateTargetRefCon, 1,
+ PyDoc_STR("(MediaHandler mh, long navigation) -> (ComponentResult _rv, long refCon)")},
+ {"MediaGGetIdleManager", (PyCFunction)Qt_MediaGGetIdleManager, 1,
+ PyDoc_STR("(MediaHandler mh) -> (ComponentResult _rv, IdleManager pim)")},
+ {"MediaGSetIdleManager", (PyCFunction)Qt_MediaGSetIdleManager, 1,
+ PyDoc_STR("(MediaHandler mh, IdleManager im) -> (ComponentResult _rv)")},
+ {"QTMIDIGetMIDIPorts", (PyCFunction)Qt_QTMIDIGetMIDIPorts, 1,
+ PyDoc_STR("(QTMIDIComponent ci) -> (ComponentResult _rv, QTMIDIPortListHandle inputPorts, QTMIDIPortListHandle outputPorts)")},
+ {"QTMIDIUseSendPort", (PyCFunction)Qt_QTMIDIUseSendPort, 1,
+ PyDoc_STR("(QTMIDIComponent ci, long portIndex, long inUse) -> (ComponentResult _rv)")},
+ {"QTMIDISendMIDI", (PyCFunction)Qt_QTMIDISendMIDI, 1,
+ PyDoc_STR("(QTMIDIComponent ci, long portIndex, MusicMIDIPacket mp) -> (ComponentResult _rv)")},
+ {"MusicGetPart", (PyCFunction)Qt_MusicGetPart, 1,
+ PyDoc_STR("(MusicComponent mc, long part) -> (ComponentResult _rv, long midiChannel, long polyphony)")},
+ {"MusicSetPart", (PyCFunction)Qt_MusicSetPart, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long midiChannel, long polyphony) -> (ComponentResult _rv)")},
+ {"MusicSetPartInstrumentNumber", (PyCFunction)Qt_MusicSetPartInstrumentNumber, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long instrumentNumber) -> (ComponentResult _rv)")},
+ {"MusicGetPartInstrumentNumber", (PyCFunction)Qt_MusicGetPartInstrumentNumber, 1,
+ PyDoc_STR("(MusicComponent mc, long part) -> (ComponentResult _rv)")},
+ {"MusicStorePartInstrument", (PyCFunction)Qt_MusicStorePartInstrument, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long instrumentNumber) -> (ComponentResult _rv)")},
+ {"MusicGetPartAtomicInstrument", (PyCFunction)Qt_MusicGetPartAtomicInstrument, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long flags) -> (ComponentResult _rv, AtomicInstrument ai)")},
+ {"MusicSetPartAtomicInstrument", (PyCFunction)Qt_MusicSetPartAtomicInstrument, 1,
+ PyDoc_STR("(MusicComponent mc, long part, AtomicInstrumentPtr aiP, long flags) -> (ComponentResult _rv)")},
+ {"MusicGetPartKnob", (PyCFunction)Qt_MusicGetPartKnob, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long knobID) -> (ComponentResult _rv)")},
+ {"MusicSetPartKnob", (PyCFunction)Qt_MusicSetPartKnob, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long knobID, long knobValue) -> (ComponentResult _rv)")},
+ {"MusicGetKnob", (PyCFunction)Qt_MusicGetKnob, 1,
+ PyDoc_STR("(MusicComponent mc, long knobID) -> (ComponentResult _rv)")},
+ {"MusicSetKnob", (PyCFunction)Qt_MusicSetKnob, 1,
+ PyDoc_STR("(MusicComponent mc, long knobID, long knobValue) -> (ComponentResult _rv)")},
+ {"MusicGetPartName", (PyCFunction)Qt_MusicGetPartName, 1,
+ PyDoc_STR("(MusicComponent mc, long part, StringPtr name) -> (ComponentResult _rv)")},
+ {"MusicSetPartName", (PyCFunction)Qt_MusicSetPartName, 1,
+ PyDoc_STR("(MusicComponent mc, long part, StringPtr name) -> (ComponentResult _rv)")},
+ {"MusicPlayNote", (PyCFunction)Qt_MusicPlayNote, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long pitch, long velocity) -> (ComponentResult _rv)")},
+ {"MusicResetPart", (PyCFunction)Qt_MusicResetPart, 1,
+ PyDoc_STR("(MusicComponent mc, long part) -> (ComponentResult _rv)")},
+ {"MusicSetPartController", (PyCFunction)Qt_MusicSetPartController, 1,
+ PyDoc_STR("(MusicComponent mc, long part, MusicController controllerNumber, long controllerValue) -> (ComponentResult _rv)")},
+ {"MusicGetPartController", (PyCFunction)Qt_MusicGetPartController, 1,
+ PyDoc_STR("(MusicComponent mc, long part, MusicController controllerNumber) -> (ComponentResult _rv)")},
+ {"MusicGetInstrumentNames", (PyCFunction)Qt_MusicGetInstrumentNames, 1,
+ PyDoc_STR("(MusicComponent mc, long modifiableInstruments) -> (ComponentResult _rv, Handle instrumentNames, Handle instrumentCategoryLasts, Handle instrumentCategoryNames)")},
+ {"MusicGetDrumNames", (PyCFunction)Qt_MusicGetDrumNames, 1,
+ PyDoc_STR("(MusicComponent mc, long modifiableInstruments) -> (ComponentResult _rv, Handle instrumentNumbers, Handle instrumentNames)")},
+ {"MusicGetMasterTune", (PyCFunction)Qt_MusicGetMasterTune, 1,
+ PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv)")},
+ {"MusicSetMasterTune", (PyCFunction)Qt_MusicSetMasterTune, 1,
+ PyDoc_STR("(MusicComponent mc, long masterTune) -> (ComponentResult _rv)")},
+ {"MusicGetDeviceConnection", (PyCFunction)Qt_MusicGetDeviceConnection, 1,
+ PyDoc_STR("(MusicComponent mc, long index) -> (ComponentResult _rv, long id1, long id2)")},
+ {"MusicUseDeviceConnection", (PyCFunction)Qt_MusicUseDeviceConnection, 1,
+ PyDoc_STR("(MusicComponent mc, long id1, long id2) -> (ComponentResult _rv)")},
+ {"MusicGetKnobSettingStrings", (PyCFunction)Qt_MusicGetKnobSettingStrings, 1,
+ PyDoc_STR("(MusicComponent mc, long knobIndex, long isGlobal) -> (ComponentResult _rv, Handle settingsNames, Handle settingsCategoryLasts, Handle settingsCategoryNames)")},
+ {"MusicGetMIDIPorts", (PyCFunction)Qt_MusicGetMIDIPorts, 1,
+ PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv, long inputPortCount, long outputPortCount)")},
+ {"MusicSendMIDI", (PyCFunction)Qt_MusicSendMIDI, 1,
+ PyDoc_STR("(MusicComponent mc, long portIndex, MusicMIDIPacket mp) -> (ComponentResult _rv)")},
+ {"MusicSetOfflineTimeTo", (PyCFunction)Qt_MusicSetOfflineTimeTo, 1,
+ PyDoc_STR("(MusicComponent mc, long newTimeStamp) -> (ComponentResult _rv)")},
+ {"MusicGetInfoText", (PyCFunction)Qt_MusicGetInfoText, 1,
+ PyDoc_STR("(MusicComponent mc, long selector) -> (ComponentResult _rv, Handle textH, Handle styleH)")},
+ {"MusicGetInstrumentInfo", (PyCFunction)Qt_MusicGetInstrumentInfo, 1,
+ PyDoc_STR("(MusicComponent mc, long getInstrumentInfoFlags) -> (ComponentResult _rv, InstrumentInfoListHandle infoListH)")},
+ {"MusicTask", (PyCFunction)Qt_MusicTask, 1,
+ PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv)")},
+ {"MusicSetPartInstrumentNumberInterruptSafe", (PyCFunction)Qt_MusicSetPartInstrumentNumberInterruptSafe, 1,
+ PyDoc_STR("(MusicComponent mc, long part, long instrumentNumber) -> (ComponentResult _rv)")},
+ {"MusicSetPartSoundLocalization", (PyCFunction)Qt_MusicSetPartSoundLocalization, 1,
+ PyDoc_STR("(MusicComponent mc, long part, Handle data) -> (ComponentResult _rv)")},
+ {"MusicGenericConfigure", (PyCFunction)Qt_MusicGenericConfigure, 1,
+ PyDoc_STR("(MusicComponent mc, long mode, long flags, long baseResID) -> (ComponentResult _rv)")},
+ {"MusicGenericGetKnobList", (PyCFunction)Qt_MusicGenericGetKnobList, 1,
+ PyDoc_STR("(MusicComponent mc, long knobType) -> (ComponentResult _rv, GenericKnobDescriptionListHandle gkdlH)")},
+ {"MusicGenericSetResourceNumbers", (PyCFunction)Qt_MusicGenericSetResourceNumbers, 1,
+ PyDoc_STR("(MusicComponent mc, Handle resourceIDH) -> (ComponentResult _rv)")},
+ {"MusicDerivedMIDISend", (PyCFunction)Qt_MusicDerivedMIDISend, 1,
+ PyDoc_STR("(MusicComponent mc, MusicMIDIPacket packet) -> (ComponentResult _rv)")},
+ {"MusicDerivedOpenResFile", (PyCFunction)Qt_MusicDerivedOpenResFile, 1,
+ PyDoc_STR("(MusicComponent mc) -> (ComponentResult _rv)")},
+ {"MusicDerivedCloseResFile", (PyCFunction)Qt_MusicDerivedCloseResFile, 1,
+ PyDoc_STR("(MusicComponent mc, short resRefNum) -> (ComponentResult _rv)")},
+ {"NAUnregisterMusicDevice", (PyCFunction)Qt_NAUnregisterMusicDevice, 1,
+ PyDoc_STR("(NoteAllocator na, long index) -> (ComponentResult _rv)")},
+ {"NASaveMusicConfiguration", (PyCFunction)Qt_NASaveMusicConfiguration, 1,
+ PyDoc_STR("(NoteAllocator na) -> (ComponentResult _rv)")},
+ {"NAGetMIDIPorts", (PyCFunction)Qt_NAGetMIDIPorts, 1,
+ PyDoc_STR("(NoteAllocator na) -> (ComponentResult _rv, QTMIDIPortListHandle inputPorts, QTMIDIPortListHandle outputPorts)")},
+ {"NATask", (PyCFunction)Qt_NATask, 1,
+ PyDoc_STR("(NoteAllocator na) -> (ComponentResult _rv)")},
+ {"TuneSetHeader", (PyCFunction)Qt_TuneSetHeader, 1,
+ PyDoc_STR("(TunePlayer tp, unsigned long * header) -> (ComponentResult _rv)")},
+ {"TuneGetTimeBase", (PyCFunction)Qt_TuneGetTimeBase, 1,
+ PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv, TimeBase tb)")},
+ {"TuneSetTimeScale", (PyCFunction)Qt_TuneSetTimeScale, 1,
+ PyDoc_STR("(TunePlayer tp, TimeScale scale) -> (ComponentResult _rv)")},
+ {"TuneGetTimeScale", (PyCFunction)Qt_TuneGetTimeScale, 1,
+ PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv, TimeScale scale)")},
+ {"TuneInstant", (PyCFunction)Qt_TuneInstant, 1,
+ PyDoc_STR("(TunePlayer tp, unsigned long tunePosition) -> (ComponentResult _rv, unsigned long tune)")},
+ {"TuneStop", (PyCFunction)Qt_TuneStop, 1,
+ PyDoc_STR("(TunePlayer tp, long stopFlags) -> (ComponentResult _rv)")},
+ {"TuneSetVolume", (PyCFunction)Qt_TuneSetVolume, 1,
+ PyDoc_STR("(TunePlayer tp, Fixed volume) -> (ComponentResult _rv)")},
+ {"TuneGetVolume", (PyCFunction)Qt_TuneGetVolume, 1,
+ PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
+ {"TunePreroll", (PyCFunction)Qt_TunePreroll, 1,
+ PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
+ {"TuneUnroll", (PyCFunction)Qt_TuneUnroll, 1,
+ PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
+ {"TuneSetPartTranspose", (PyCFunction)Qt_TuneSetPartTranspose, 1,
+ PyDoc_STR("(TunePlayer tp, unsigned long part, long transpose, long velocityShift) -> (ComponentResult _rv)")},
+ {"TuneGetNoteAllocator", (PyCFunction)Qt_TuneGetNoteAllocator, 1,
+ PyDoc_STR("(TunePlayer tp) -> (NoteAllocator _rv)")},
+ {"TuneSetSofter", (PyCFunction)Qt_TuneSetSofter, 1,
+ PyDoc_STR("(TunePlayer tp, long softer) -> (ComponentResult _rv)")},
+ {"TuneTask", (PyCFunction)Qt_TuneTask, 1,
+ PyDoc_STR("(TunePlayer tp) -> (ComponentResult _rv)")},
+ {"TuneSetBalance", (PyCFunction)Qt_TuneSetBalance, 1,
+ PyDoc_STR("(TunePlayer tp, long balance) -> (ComponentResult _rv)")},
+ {"TuneSetSoundLocalization", (PyCFunction)Qt_TuneSetSoundLocalization, 1,
+ PyDoc_STR("(TunePlayer tp, Handle data) -> (ComponentResult _rv)")},
+ {"TuneSetHeaderWithSize", (PyCFunction)Qt_TuneSetHeaderWithSize, 1,
+ PyDoc_STR("(TunePlayer tp, unsigned long * header, unsigned long size) -> (ComponentResult _rv)")},
+ {"TuneSetPartMix", (PyCFunction)Qt_TuneSetPartMix, 1,
+ PyDoc_STR("(TunePlayer tp, unsigned long partNumber, long volume, long balance, long mixFlags) -> (ComponentResult _rv)")},
+ {"TuneGetPartMix", (PyCFunction)Qt_TuneGetPartMix, 1,
+ PyDoc_STR("(TunePlayer tp, unsigned long partNumber) -> (ComponentResult _rv, long volumeOut, long balanceOut, long mixFlagsOut)")},
+ {"AlignWindow", (PyCFunction)Qt_AlignWindow, 1,
+ PyDoc_STR("(WindowPtr wp, Boolean front) -> None")},
+ {"DragAlignedWindow", (PyCFunction)Qt_DragAlignedWindow, 1,
+ PyDoc_STR("(WindowPtr wp, Point startPt, Rect boundsRect) -> None")},
+ {"MoviesTask", (PyCFunction)Qt_MoviesTask, 1,
+ PyDoc_STR("(long maxMilliSecToUse) -> None")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -28000,90 +28000,90 @@ static PyMethodDef Qt_methods[] = {
void init_Qt(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
-
-
-
- PyMac_INIT_TOOLBOX_OBJECT_NEW(Track, TrackObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Track, TrackObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(Movie, MovieObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Movie, MovieObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(MovieController, MovieCtlObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MovieController, MovieCtlObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(TimeBase, TimeBaseObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TimeBase, TimeBaseObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(UserData, UserDataObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(UserData, UserDataObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(Media, MediaObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Media, MediaObj_Convert);
+ PyObject *d;
+
+
+
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(Track, TrackObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Track, TrackObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(Movie, MovieObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Movie, MovieObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(MovieController, MovieCtlObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(MovieController, MovieCtlObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(TimeBase, TimeBaseObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TimeBase, TimeBaseObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(UserData, UserDataObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(UserData, UserDataObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(Media, MediaObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Media, MediaObj_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_Qt", Qt_methods);
+ m = Py_InitModule("_Qt", Qt_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Qt_Error = PyMac_GetOSErrException();
- if (Qt_Error == NULL ||
- PyDict_SetItemString(d, "Error", Qt_Error) != 0)
- return;
- IdleManager_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&IdleManager_Type) < 0) return;
- Py_INCREF(&IdleManager_Type);
- PyModule_AddObject(m, "IdleManager", (PyObject *)&IdleManager_Type);
- /* Backward-compatible name */
- Py_INCREF(&IdleManager_Type);
- PyModule_AddObject(m, "IdleManagerType", (PyObject *)&IdleManager_Type);
- MovieController_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&MovieController_Type) < 0) return;
- Py_INCREF(&MovieController_Type);
- PyModule_AddObject(m, "MovieController", (PyObject *)&MovieController_Type);
- /* Backward-compatible name */
- Py_INCREF(&MovieController_Type);
- PyModule_AddObject(m, "MovieControllerType", (PyObject *)&MovieController_Type);
- TimeBase_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&TimeBase_Type) < 0) return;
- Py_INCREF(&TimeBase_Type);
- PyModule_AddObject(m, "TimeBase", (PyObject *)&TimeBase_Type);
- /* Backward-compatible name */
- Py_INCREF(&TimeBase_Type);
- PyModule_AddObject(m, "TimeBaseType", (PyObject *)&TimeBase_Type);
- UserData_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&UserData_Type) < 0) return;
- Py_INCREF(&UserData_Type);
- PyModule_AddObject(m, "UserData", (PyObject *)&UserData_Type);
- /* Backward-compatible name */
- Py_INCREF(&UserData_Type);
- PyModule_AddObject(m, "UserDataType", (PyObject *)&UserData_Type);
- Media_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Media_Type) < 0) return;
- Py_INCREF(&Media_Type);
- PyModule_AddObject(m, "Media", (PyObject *)&Media_Type);
- /* Backward-compatible name */
- Py_INCREF(&Media_Type);
- PyModule_AddObject(m, "MediaType", (PyObject *)&Media_Type);
- Track_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Track_Type) < 0) return;
- Py_INCREF(&Track_Type);
- PyModule_AddObject(m, "Track", (PyObject *)&Track_Type);
- /* Backward-compatible name */
- Py_INCREF(&Track_Type);
- PyModule_AddObject(m, "TrackType", (PyObject *)&Track_Type);
- Movie_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Movie_Type) < 0) return;
- Py_INCREF(&Movie_Type);
- PyModule_AddObject(m, "Movie", (PyObject *)&Movie_Type);
- /* Backward-compatible name */
- Py_INCREF(&Movie_Type);
- PyModule_AddObject(m, "MovieType", (PyObject *)&Movie_Type);
- SGOutput_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&SGOutput_Type) < 0) return;
- Py_INCREF(&SGOutput_Type);
- PyModule_AddObject(m, "SGOutput", (PyObject *)&SGOutput_Type);
- /* Backward-compatible name */
- Py_INCREF(&SGOutput_Type);
- PyModule_AddObject(m, "SGOutputType", (PyObject *)&SGOutput_Type);
+ d = PyModule_GetDict(m);
+ Qt_Error = PyMac_GetOSErrException();
+ if (Qt_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Qt_Error) != 0)
+ return;
+ IdleManager_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&IdleManager_Type) < 0) return;
+ Py_INCREF(&IdleManager_Type);
+ PyModule_AddObject(m, "IdleManager", (PyObject *)&IdleManager_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&IdleManager_Type);
+ PyModule_AddObject(m, "IdleManagerType", (PyObject *)&IdleManager_Type);
+ MovieController_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&MovieController_Type) < 0) return;
+ Py_INCREF(&MovieController_Type);
+ PyModule_AddObject(m, "MovieController", (PyObject *)&MovieController_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&MovieController_Type);
+ PyModule_AddObject(m, "MovieControllerType", (PyObject *)&MovieController_Type);
+ TimeBase_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&TimeBase_Type) < 0) return;
+ Py_INCREF(&TimeBase_Type);
+ PyModule_AddObject(m, "TimeBase", (PyObject *)&TimeBase_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&TimeBase_Type);
+ PyModule_AddObject(m, "TimeBaseType", (PyObject *)&TimeBase_Type);
+ UserData_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&UserData_Type) < 0) return;
+ Py_INCREF(&UserData_Type);
+ PyModule_AddObject(m, "UserData", (PyObject *)&UserData_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&UserData_Type);
+ PyModule_AddObject(m, "UserDataType", (PyObject *)&UserData_Type);
+ Media_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Media_Type) < 0) return;
+ Py_INCREF(&Media_Type);
+ PyModule_AddObject(m, "Media", (PyObject *)&Media_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Media_Type);
+ PyModule_AddObject(m, "MediaType", (PyObject *)&Media_Type);
+ Track_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Track_Type) < 0) return;
+ Py_INCREF(&Track_Type);
+ PyModule_AddObject(m, "Track", (PyObject *)&Track_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Track_Type);
+ PyModule_AddObject(m, "TrackType", (PyObject *)&Track_Type);
+ Movie_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Movie_Type) < 0) return;
+ Py_INCREF(&Movie_Type);
+ PyModule_AddObject(m, "Movie", (PyObject *)&Movie_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Movie_Type);
+ PyModule_AddObject(m, "MovieType", (PyObject *)&Movie_Type);
+ SGOutput_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&SGOutput_Type) < 0) return;
+ Py_INCREF(&SGOutput_Type);
+ PyModule_AddObject(m, "SGOutput", (PyObject *)&SGOutput_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&SGOutput_Type);
+ PyModule_AddObject(m, "SGOutputType", (PyObject *)&SGOutput_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/res/_Resmodule.c b/Mac/Modules/res/_Resmodule.c
index 89fd02c..f5824b1 100644
--- a/Mac/Modules/res/_Resmodule.c
+++ b/Mac/Modules/res/_Resmodule.c
@@ -8,9 +8,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)
@@ -31,7 +31,7 @@ extern int _OptResObj_Convert(PyObject *, Handle *);
static void
PyMac_AutoDisposeHandle(Handle h)
{
- DisposeHandle(h);
+ DisposeHandle(h);
}
static PyObject *Res_Error;
@@ -43,531 +43,531 @@ PyTypeObject Resource_Type;
#define ResObj_Check(x) ((x)->ob_type == &Resource_Type || PyObject_TypeCheck((x), &Resource_Type))
typedef struct ResourceObject {
- PyObject_HEAD
- Handle ob_itself;
- void (*ob_freeit)(Handle ptr);
+ PyObject_HEAD
+ Handle ob_itself;
+ void (*ob_freeit)(Handle ptr);
} ResourceObject;
PyObject *ResObj_New(Handle itself)
{
- ResourceObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- it = PyObject_NEW(ResourceObject, &Resource_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_freeit = NULL;
- return (PyObject *)it;
+ ResourceObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ it = PyObject_NEW(ResourceObject, &Resource_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_freeit = NULL;
+ return (PyObject *)it;
}
int ResObj_Convert(PyObject *v, Handle *p_itself)
{
- if (!ResObj_Check(v))
- {
- PyObject *tmp;
- if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) )
- {
- *p_itself = ((ResourceObject *)tmp)->ob_itself;
- Py_DECREF(tmp);
- return 1;
- }
- PyErr_Clear();
- }
- if (!ResObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Resource required");
- return 0;
- }
- *p_itself = ((ResourceObject *)v)->ob_itself;
- return 1;
+ if (!ResObj_Check(v))
+ {
+ PyObject *tmp;
+ if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) )
+ {
+ *p_itself = ((ResourceObject *)tmp)->ob_itself;
+ Py_DECREF(tmp);
+ return 1;
+ }
+ PyErr_Clear();
+ }
+ if (!ResObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Resource required");
+ return 0;
+ }
+ *p_itself = ((ResourceObject *)v)->ob_itself;
+ return 1;
}
static void ResObj_dealloc(ResourceObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- self->ob_freeit(self->ob_itself);
- }
- self->ob_itself = NULL;
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ self->ob_freeit(self->ob_itself);
+ }
+ self->ob_itself = NULL;
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *ResObj_HomeResFile(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef HomeResFile
- PyMac_PRECHECK(HomeResFile);
+ PyMac_PRECHECK(HomeResFile);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = HomeResFile(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = HomeResFile(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *ResObj_MacLoadResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef MacLoadResource
- PyMac_PRECHECK(MacLoadResource);
+ PyMac_PRECHECK(MacLoadResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- MacLoadResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ MacLoadResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_ReleaseResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ReleaseResource
- PyMac_PRECHECK(ReleaseResource);
+ PyMac_PRECHECK(ReleaseResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ReleaseResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ReleaseResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_DetachResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DetachResource
- PyMac_PRECHECK(DetachResource);
+ PyMac_PRECHECK(DetachResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DetachResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DetachResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_GetResAttrs(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetResAttrs
- PyMac_PRECHECK(GetResAttrs);
+ PyMac_PRECHECK(GetResAttrs);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetResAttrs(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetResAttrs(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *ResObj_GetResInfo(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short theID;
- ResType theType;
- Str255 name;
+ PyObject *_res = NULL;
+ short theID;
+ ResType theType;
+ Str255 name;
#ifndef GetResInfo
- PyMac_PRECHECK(GetResInfo);
+ PyMac_PRECHECK(GetResInfo);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetResInfo(_self->ob_itself,
- &theID,
- &theType,
- name);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("hO&O&",
- theID,
- PyMac_BuildOSType, theType,
- PyMac_BuildStr255, name);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetResInfo(_self->ob_itself,
+ &theID,
+ &theType,
+ name);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("hO&O&",
+ theID,
+ PyMac_BuildOSType, theType,
+ PyMac_BuildStr255, name);
+ return _res;
}
static PyObject *ResObj_SetResInfo(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short theID;
- Str255 name;
+ PyObject *_res = NULL;
+ short theID;
+ Str255 name;
#ifndef SetResInfo
- PyMac_PRECHECK(SetResInfo);
+ PyMac_PRECHECK(SetResInfo);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &theID,
- PyMac_GetStr255, name))
- return NULL;
- SetResInfo(_self->ob_itself,
- theID,
- name);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &theID,
+ PyMac_GetStr255, name))
+ return NULL;
+ SetResInfo(_self->ob_itself,
+ theID,
+ name);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_AddResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ResType theType;
- short theID;
- Str255 name;
+ PyObject *_res = NULL;
+ ResType theType;
+ short theID;
+ Str255 name;
#ifndef AddResource
- PyMac_PRECHECK(AddResource);
+ PyMac_PRECHECK(AddResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&hO&",
- PyMac_GetOSType, &theType,
- &theID,
- PyMac_GetStr255, name))
- return NULL;
- AddResource(_self->ob_itself,
- theType,
- theID,
- name);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hO&",
+ PyMac_GetOSType, &theType,
+ &theID,
+ PyMac_GetStr255, name))
+ return NULL;
+ AddResource(_self->ob_itself,
+ theType,
+ theID,
+ name);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_GetResourceSizeOnDisk(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetResourceSizeOnDisk
- PyMac_PRECHECK(GetResourceSizeOnDisk);
+ PyMac_PRECHECK(GetResourceSizeOnDisk);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetResourceSizeOnDisk(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetResourceSizeOnDisk(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ResObj_GetMaxResourceSize(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetMaxResourceSize
- PyMac_PRECHECK(GetMaxResourceSize);
+ PyMac_PRECHECK(GetMaxResourceSize);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetMaxResourceSize(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetMaxResourceSize(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *ResObj_SetResAttrs(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short attrs;
+ PyObject *_res = NULL;
+ short attrs;
#ifndef SetResAttrs
- PyMac_PRECHECK(SetResAttrs);
+ PyMac_PRECHECK(SetResAttrs);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &attrs))
- return NULL;
- SetResAttrs(_self->ob_itself,
- attrs);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &attrs))
+ return NULL;
+ SetResAttrs(_self->ob_itself,
+ attrs);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_ChangedResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ChangedResource
- PyMac_PRECHECK(ChangedResource);
+ PyMac_PRECHECK(ChangedResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ChangedResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ChangedResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_RemoveResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef RemoveResource
- PyMac_PRECHECK(RemoveResource);
+ PyMac_PRECHECK(RemoveResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- RemoveResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ RemoveResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_WriteResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef WriteResource
- PyMac_PRECHECK(WriteResource);
+ PyMac_PRECHECK(WriteResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- WriteResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ WriteResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_SetResourceSize(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long newSize;
+ PyObject *_res = NULL;
+ long newSize;
#ifndef SetResourceSize
- PyMac_PRECHECK(SetResourceSize);
+ PyMac_PRECHECK(SetResourceSize);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &newSize))
- return NULL;
- SetResourceSize(_self->ob_itself,
- newSize);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &newSize))
+ return NULL;
+ SetResourceSize(_self->ob_itself,
+ newSize);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_GetNextFOND(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef GetNextFOND
- PyMac_PRECHECK(GetNextFOND);
+ PyMac_PRECHECK(GetNextFOND);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetNextFOND(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetNextFOND(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
#ifndef __LP64__
static PyObject *ResObj_as_Control(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- _res = CtlObj_New((ControlHandle)_self->ob_itself);
- return _res;
+ _res = CtlObj_New((ControlHandle)_self->ob_itself);
+ return _res;
}
static PyObject *ResObj_as_Menu(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- _res = MenuObj_New((MenuHandle)_self->ob_itself);
- return _res;
+ _res = MenuObj_New((MenuHandle)_self->ob_itself);
+ return _res;
}
#endif /* !__LP64__ */
static PyObject *ResObj_LoadResource(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef LoadResource
- PyMac_PRECHECK(LoadResource);
+ PyMac_PRECHECK(LoadResource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- LoadResource(_self->ob_itself);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ LoadResource(_self->ob_itself);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *ResObj_AutoDispose(ResourceObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int onoff, old = 0;
- if (!PyArg_ParseTuple(_args, "i", &onoff))
- return NULL;
- if ( _self->ob_freeit )
- old = 1;
- if ( onoff )
- _self->ob_freeit = PyMac_AutoDisposeHandle;
- else
- _self->ob_freeit = NULL;
- _res = Py_BuildValue("i", old);
- return _res;
+ int onoff, old = 0;
+ if (!PyArg_ParseTuple(_args, "i", &onoff))
+ return NULL;
+ if ( _self->ob_freeit )
+ old = 1;
+ if ( onoff )
+ _self->ob_freeit = PyMac_AutoDisposeHandle;
+ else
+ _self->ob_freeit = NULL;
+ _res = Py_BuildValue("i", old);
+ return _res;
}
static PyMethodDef ResObj_methods[] = {
- {"HomeResFile", (PyCFunction)ResObj_HomeResFile, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"MacLoadResource", (PyCFunction)ResObj_MacLoadResource, 1,
- PyDoc_STR("() -> None")},
- {"ReleaseResource", (PyCFunction)ResObj_ReleaseResource, 1,
- PyDoc_STR("() -> None")},
- {"DetachResource", (PyCFunction)ResObj_DetachResource, 1,
- PyDoc_STR("() -> None")},
- {"GetResAttrs", (PyCFunction)ResObj_GetResAttrs, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetResInfo", (PyCFunction)ResObj_GetResInfo, 1,
- PyDoc_STR("() -> (short theID, ResType theType, Str255 name)")},
- {"SetResInfo", (PyCFunction)ResObj_SetResInfo, 1,
- PyDoc_STR("(short theID, Str255 name) -> None")},
- {"AddResource", (PyCFunction)ResObj_AddResource, 1,
- PyDoc_STR("(ResType theType, short theID, Str255 name) -> None")},
- {"GetResourceSizeOnDisk", (PyCFunction)ResObj_GetResourceSizeOnDisk, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"GetMaxResourceSize", (PyCFunction)ResObj_GetMaxResourceSize, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SetResAttrs", (PyCFunction)ResObj_SetResAttrs, 1,
- PyDoc_STR("(short attrs) -> None")},
- {"ChangedResource", (PyCFunction)ResObj_ChangedResource, 1,
- PyDoc_STR("() -> None")},
- {"RemoveResource", (PyCFunction)ResObj_RemoveResource, 1,
- PyDoc_STR("() -> None")},
- {"WriteResource", (PyCFunction)ResObj_WriteResource, 1,
- PyDoc_STR("() -> None")},
- {"SetResourceSize", (PyCFunction)ResObj_SetResourceSize, 1,
- PyDoc_STR("(long newSize) -> None")},
- {"GetNextFOND", (PyCFunction)ResObj_GetNextFOND, 1,
- PyDoc_STR("() -> (Handle _rv)")},
+ {"HomeResFile", (PyCFunction)ResObj_HomeResFile, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"MacLoadResource", (PyCFunction)ResObj_MacLoadResource, 1,
+ PyDoc_STR("() -> None")},
+ {"ReleaseResource", (PyCFunction)ResObj_ReleaseResource, 1,
+ PyDoc_STR("() -> None")},
+ {"DetachResource", (PyCFunction)ResObj_DetachResource, 1,
+ PyDoc_STR("() -> None")},
+ {"GetResAttrs", (PyCFunction)ResObj_GetResAttrs, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetResInfo", (PyCFunction)ResObj_GetResInfo, 1,
+ PyDoc_STR("() -> (short theID, ResType theType, Str255 name)")},
+ {"SetResInfo", (PyCFunction)ResObj_SetResInfo, 1,
+ PyDoc_STR("(short theID, Str255 name) -> None")},
+ {"AddResource", (PyCFunction)ResObj_AddResource, 1,
+ PyDoc_STR("(ResType theType, short theID, Str255 name) -> None")},
+ {"GetResourceSizeOnDisk", (PyCFunction)ResObj_GetResourceSizeOnDisk, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"GetMaxResourceSize", (PyCFunction)ResObj_GetMaxResourceSize, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SetResAttrs", (PyCFunction)ResObj_SetResAttrs, 1,
+ PyDoc_STR("(short attrs) -> None")},
+ {"ChangedResource", (PyCFunction)ResObj_ChangedResource, 1,
+ PyDoc_STR("() -> None")},
+ {"RemoveResource", (PyCFunction)ResObj_RemoveResource, 1,
+ PyDoc_STR("() -> None")},
+ {"WriteResource", (PyCFunction)ResObj_WriteResource, 1,
+ PyDoc_STR("() -> None")},
+ {"SetResourceSize", (PyCFunction)ResObj_SetResourceSize, 1,
+ PyDoc_STR("(long newSize) -> None")},
+ {"GetNextFOND", (PyCFunction)ResObj_GetNextFOND, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
#ifndef __LP64__
- {"as_Control", (PyCFunction)ResObj_as_Control, 1,
- PyDoc_STR("Return this resource/handle as a Control")},
- {"as_Menu", (PyCFunction)ResObj_as_Menu, 1,
- PyDoc_STR("Return this resource/handle as a Menu")},
+ {"as_Control", (PyCFunction)ResObj_as_Control, 1,
+ PyDoc_STR("Return this resource/handle as a Control")},
+ {"as_Menu", (PyCFunction)ResObj_as_Menu, 1,
+ PyDoc_STR("Return this resource/handle as a Menu")},
#endif /* !__LP64__ */
- {"LoadResource", (PyCFunction)ResObj_LoadResource, 1,
- PyDoc_STR("() -> None")},
- {"AutoDispose", (PyCFunction)ResObj_AutoDispose, 1,
- PyDoc_STR("(int)->int. Automatically DisposeHandle the object on Python object cleanup")},
- {NULL, NULL, 0}
+ {"LoadResource", (PyCFunction)ResObj_LoadResource, 1,
+ PyDoc_STR("() -> None")},
+ {"AutoDispose", (PyCFunction)ResObj_AutoDispose, 1,
+ PyDoc_STR("(int)->int. Automatically DisposeHandle the object on Python object cleanup")},
+ {NULL, NULL, 0}
};
static PyObject *ResObj_get_data(ResourceObject *self, void *closure)
{
- PyObject *res;
- char state;
+ PyObject *res;
+ char state;
+
+ state = HGetState(self->ob_itself);
+ HLock(self->ob_itself);
+ res = PyString_FromStringAndSize(
+ *self->ob_itself,
+ GetHandleSize(self->ob_itself));
+ HUnlock(self->ob_itself);
+ HSetState(self->ob_itself, state);
+ return res;
- state = HGetState(self->ob_itself);
- HLock(self->ob_itself);
- res = PyString_FromStringAndSize(
- *self->ob_itself,
- GetHandleSize(self->ob_itself));
- HUnlock(self->ob_itself);
- HSetState(self->ob_itself, state);
- return res;
-
}
static int ResObj_set_data(ResourceObject *self, PyObject *v, void *closure)
{
- char *data;
- long size;
-
- if ( v == NULL )
- return -1;
- if ( !PyString_Check(v) )
- return -1;
- size = PyString_Size(v);
- data = PyString_AsString(v);
- /* XXXX Do I need the GetState/SetState calls? */
- SetHandleSize(self->ob_itself, size);
- if ( MemError())
- return -1;
- HLock(self->ob_itself);
- memcpy((char *)*self->ob_itself, data, size);
- HUnlock(self->ob_itself);
- /* XXXX Should I do the Changed call immedeately? */
- return 0;
-
- return 0;
+ char *data;
+ long size;
+
+ if ( v == NULL )
+ return -1;
+ if ( !PyString_Check(v) )
+ return -1;
+ size = PyString_Size(v);
+ data = PyString_AsString(v);
+ /* XXXX Do I need the GetState/SetState calls? */
+ SetHandleSize(self->ob_itself, size);
+ if ( MemError())
+ return -1;
+ HLock(self->ob_itself);
+ memcpy((char *)*self->ob_itself, data, size);
+ HUnlock(self->ob_itself);
+ /* XXXX Should I do the Changed call immedeately? */
+ return 0;
+
+ return 0;
}
static PyObject *ResObj_get_size(ResourceObject *self, void *closure)
{
- return PyInt_FromLong(GetHandleSize(self->ob_itself));
+ return PyInt_FromLong(GetHandleSize(self->ob_itself));
}
#define ResObj_set_size NULL
static PyGetSetDef ResObj_getsetlist[] = {
- {"data", (getter)ResObj_get_data, (setter)ResObj_set_data, "The resource data"},
- {"size", (getter)ResObj_get_size, (setter)ResObj_set_size, "The length of the resource data"},
- {NULL, NULL, NULL, NULL},
+ {"data", (getter)ResObj_get_data, (setter)ResObj_set_data, "The resource data"},
+ {"size", (getter)ResObj_get_size, (setter)ResObj_set_size, "The length of the resource data"},
+ {NULL, NULL, NULL, NULL},
};
@@ -578,89 +578,89 @@ static PyGetSetDef ResObj_getsetlist[] = {
#define ResObj_hash NULL
static int ResObj_tp_init(PyObject *_self, PyObject *_args, PyObject *_kwds)
{
- char *srcdata = NULL;
- int srclen = 0;
- Handle itself;
- char *kw[] = {"itself", 0};
-
- if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, ResObj_Convert, &itself))
- {
- ((ResourceObject *)_self)->ob_itself = itself;
- return 0;
- }
- PyErr_Clear();
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|s#", kw, &srcdata, &srclen)) return -1;
- if ((itself = NewHandle(srclen)) == NULL)
- {
- PyErr_NoMemory();
- return 0;
- }
- ((ResourceObject *)_self)->ob_itself = itself;
- if (srclen && srcdata)
- {
- HLock(itself);
- memcpy(*itself, srcdata, srclen);
- HUnlock(itself);
- }
- return 0;
+ char *srcdata = NULL;
+ int srclen = 0;
+ Handle itself;
+ char *kw[] = {"itself", 0};
+
+ if (PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, ResObj_Convert, &itself))
+ {
+ ((ResourceObject *)_self)->ob_itself = itself;
+ return 0;
+ }
+ PyErr_Clear();
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "|s#", kw, &srcdata, &srclen)) return -1;
+ if ((itself = NewHandle(srclen)) == NULL)
+ {
+ PyErr_NoMemory();
+ return 0;
+ }
+ ((ResourceObject *)_self)->ob_itself = itself;
+ if (srclen && srcdata)
+ {
+ HLock(itself);
+ memcpy(*itself, srcdata, srclen);
+ HUnlock(itself);
+ }
+ return 0;
}
#define ResObj_tp_alloc PyType_GenericAlloc
static PyObject *ResObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *self;
- if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((ResourceObject *)self)->ob_itself = NULL;
- ((ResourceObject *)self)->ob_freeit = NULL;
- return self;
+ PyObject *self;
+ if ((self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((ResourceObject *)self)->ob_itself = NULL;
+ ((ResourceObject *)self)->ob_freeit = NULL;
+ return self;
}
#define ResObj_tp_free PyObject_Del
PyTypeObject Resource_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Res.Resource", /*tp_name*/
- sizeof(ResourceObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) ResObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) ResObj_compare, /*tp_compare*/
- (reprfunc) ResObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) ResObj_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*/
- ResObj_methods, /* tp_methods */
- 0, /*tp_members*/
- ResObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- ResObj_tp_init, /* tp_init */
- ResObj_tp_alloc, /* tp_alloc */
- ResObj_tp_new, /* tp_new */
- ResObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Res.Resource", /*tp_name*/
+ sizeof(ResourceObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) ResObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) ResObj_compare, /*tp_compare*/
+ (reprfunc) ResObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) ResObj_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*/
+ ResObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ ResObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ ResObj_tp_init, /* tp_init */
+ ResObj_tp_alloc, /* tp_alloc */
+ ResObj_tp_new, /* tp_new */
+ ResObj_tp_free, /* tp_free */
};
/* -------------------- End object type Resource -------------------- */
@@ -668,1027 +668,1027 @@ PyTypeObject Resource_Type = {
static PyObject *Res_CloseResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short refNum;
+ PyObject *_res = NULL;
+ short refNum;
#ifndef CloseResFile
- PyMac_PRECHECK(CloseResFile);
+ PyMac_PRECHECK(CloseResFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- CloseResFile(refNum);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ CloseResFile(refNum);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_ResError(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef ResError
- PyMac_PRECHECK(ResError);
+ PyMac_PRECHECK(ResError);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_CurResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef CurResFile
- PyMac_PRECHECK(CurResFile);
+ PyMac_PRECHECK(CurResFile);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CurResFile();
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CurResFile();
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_UseResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short refNum;
+ PyObject *_res = NULL;
+ short refNum;
#ifndef UseResFile
- PyMac_PRECHECK(UseResFile);
+ PyMac_PRECHECK(UseResFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- UseResFile(refNum);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ UseResFile(refNum);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_CountTypes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef CountTypes
- PyMac_PRECHECK(CountTypes);
+ PyMac_PRECHECK(CountTypes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CountTypes();
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CountTypes();
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_Count1Types(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef Count1Types
- PyMac_PRECHECK(Count1Types);
+ PyMac_PRECHECK(Count1Types);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = Count1Types();
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = Count1Types();
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_GetIndType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ResType theType;
- short index;
+ PyObject *_res = NULL;
+ ResType theType;
+ short index;
#ifndef GetIndType
- PyMac_PRECHECK(GetIndType);
+ PyMac_PRECHECK(GetIndType);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- GetIndType(&theType,
- index);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- PyMac_BuildOSType, theType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ GetIndType(&theType,
+ index);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ PyMac_BuildOSType, theType);
+ return _res;
}
static PyObject *Res_Get1IndType(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ResType theType;
- short index;
+ PyObject *_res = NULL;
+ ResType theType;
+ short index;
#ifndef Get1IndType
- PyMac_PRECHECK(Get1IndType);
+ PyMac_PRECHECK(Get1IndType);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &index))
- return NULL;
- Get1IndType(&theType,
- index);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- PyMac_BuildOSType, theType);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &index))
+ return NULL;
+ Get1IndType(&theType,
+ index);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ PyMac_BuildOSType, theType);
+ return _res;
}
static PyObject *Res_SetResLoad(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean load;
+ PyObject *_res = NULL;
+ Boolean load;
#ifndef SetResLoad
- PyMac_PRECHECK(SetResLoad);
+ PyMac_PRECHECK(SetResLoad);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &load))
- return NULL;
- SetResLoad(load);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &load))
+ return NULL;
+ SetResLoad(load);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_CountResources(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- ResType theType;
+ PyObject *_res = NULL;
+ short _rv;
+ ResType theType;
#ifndef CountResources
- PyMac_PRECHECK(CountResources);
+ PyMac_PRECHECK(CountResources);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theType))
- return NULL;
- _rv = CountResources(theType);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _rv = CountResources(theType);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_Count1Resources(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- ResType theType;
+ PyObject *_res = NULL;
+ short _rv;
+ ResType theType;
#ifndef Count1Resources
- PyMac_PRECHECK(Count1Resources);
+ PyMac_PRECHECK(Count1Resources);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theType))
- return NULL;
- _rv = Count1Resources(theType);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _rv = Count1Resources(theType);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_GetIndResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- ResType theType;
- short index;
+ PyObject *_res = NULL;
+ Handle _rv;
+ ResType theType;
+ short index;
#ifndef GetIndResource
- PyMac_PRECHECK(GetIndResource);
+ PyMac_PRECHECK(GetIndResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetOSType, &theType,
- &index))
- return NULL;
- _rv = GetIndResource(theType,
- index);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetOSType, &theType,
+ &index))
+ return NULL;
+ _rv = GetIndResource(theType,
+ index);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Res_Get1IndResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- ResType theType;
- short index;
+ PyObject *_res = NULL;
+ Handle _rv;
+ ResType theType;
+ short index;
#ifndef Get1IndResource
- PyMac_PRECHECK(Get1IndResource);
+ PyMac_PRECHECK(Get1IndResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetOSType, &theType,
- &index))
- return NULL;
- _rv = Get1IndResource(theType,
- index);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetOSType, &theType,
+ &index))
+ return NULL;
+ _rv = Get1IndResource(theType,
+ index);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Res_GetResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- ResType theType;
- short theID;
+ PyObject *_res = NULL;
+ Handle _rv;
+ ResType theType;
+ short theID;
#ifndef GetResource
- PyMac_PRECHECK(GetResource);
+ PyMac_PRECHECK(GetResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetOSType, &theType,
- &theID))
- return NULL;
- _rv = GetResource(theType,
- theID);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetOSType, &theType,
+ &theID))
+ return NULL;
+ _rv = GetResource(theType,
+ theID);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Res_Get1Resource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- ResType theType;
- short theID;
+ PyObject *_res = NULL;
+ Handle _rv;
+ ResType theType;
+ short theID;
#ifndef Get1Resource
- PyMac_PRECHECK(Get1Resource);
+ PyMac_PRECHECK(Get1Resource);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetOSType, &theType,
- &theID))
- return NULL;
- _rv = Get1Resource(theType,
- theID);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetOSType, &theType,
+ &theID))
+ return NULL;
+ _rv = Get1Resource(theType,
+ theID);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Res_GetNamedResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- ResType theType;
- Str255 name;
+ PyObject *_res = NULL;
+ Handle _rv;
+ ResType theType;
+ Str255 name;
#ifndef GetNamedResource
- PyMac_PRECHECK(GetNamedResource);
+ PyMac_PRECHECK(GetNamedResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theType,
- PyMac_GetStr255, name))
- return NULL;
- _rv = GetNamedResource(theType,
- name);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theType,
+ PyMac_GetStr255, name))
+ return NULL;
+ _rv = GetNamedResource(theType,
+ name);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Res_Get1NamedResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
- ResType theType;
- Str255 name;
+ PyObject *_res = NULL;
+ Handle _rv;
+ ResType theType;
+ Str255 name;
#ifndef Get1NamedResource
- PyMac_PRECHECK(Get1NamedResource);
+ PyMac_PRECHECK(Get1NamedResource);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theType,
- PyMac_GetStr255, name))
- return NULL;
- _rv = Get1NamedResource(theType,
- name);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theType,
+ PyMac_GetStr255, name))
+ return NULL;
+ _rv = Get1NamedResource(theType,
+ name);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Res_UniqueID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- ResType theType;
+ PyObject *_res = NULL;
+ short _rv;
+ ResType theType;
#ifndef UniqueID
- PyMac_PRECHECK(UniqueID);
+ PyMac_PRECHECK(UniqueID);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theType))
- return NULL;
- _rv = UniqueID(theType);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _rv = UniqueID(theType);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_Unique1ID(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- ResType theType;
+ PyObject *_res = NULL;
+ short _rv;
+ ResType theType;
#ifndef Unique1ID
- PyMac_PRECHECK(Unique1ID);
+ PyMac_PRECHECK(Unique1ID);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &theType))
- return NULL;
- _rv = Unique1ID(theType);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &theType))
+ return NULL;
+ _rv = Unique1ID(theType);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_UpdateResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short refNum;
+ PyObject *_res = NULL;
+ short refNum;
#ifndef UpdateResFile
- PyMac_PRECHECK(UpdateResFile);
+ PyMac_PRECHECK(UpdateResFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- UpdateResFile(refNum);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ UpdateResFile(refNum);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_SetResPurge(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean install;
+ PyObject *_res = NULL;
+ Boolean install;
#ifndef SetResPurge
- PyMac_PRECHECK(SetResPurge);
+ PyMac_PRECHECK(SetResPurge);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &install))
- return NULL;
- SetResPurge(install);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &install))
+ return NULL;
+ SetResPurge(install);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_GetResFileAttrs(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- short refNum;
+ PyObject *_res = NULL;
+ short _rv;
+ short refNum;
#ifndef GetResFileAttrs
- PyMac_PRECHECK(GetResFileAttrs);
+ PyMac_PRECHECK(GetResFileAttrs);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _rv = GetResFileAttrs(refNum);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _rv = GetResFileAttrs(refNum);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_SetResFileAttrs(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short refNum;
- short attrs;
+ PyObject *_res = NULL;
+ short refNum;
+ short attrs;
#ifndef SetResFileAttrs
- PyMac_PRECHECK(SetResFileAttrs);
+ PyMac_PRECHECK(SetResFileAttrs);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &refNum,
- &attrs))
- return NULL;
- SetResFileAttrs(refNum,
- attrs);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &refNum,
+ &attrs))
+ return NULL;
+ SetResFileAttrs(refNum,
+ attrs);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#ifndef __LP64__
static PyObject *Res_OpenRFPerm(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- Str255 fileName;
- short vRefNum;
- SignedByte permission;
+ PyObject *_res = NULL;
+ short _rv;
+ Str255 fileName;
+ short vRefNum;
+ SignedByte permission;
#ifndef OpenRFPerm
- PyMac_PRECHECK(OpenRFPerm);
+ PyMac_PRECHECK(OpenRFPerm);
#endif
- if (!PyArg_ParseTuple(_args, "O&hb",
- PyMac_GetStr255, fileName,
- &vRefNum,
- &permission))
- return NULL;
- _rv = OpenRFPerm(fileName,
- vRefNum,
- permission);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&hb",
+ PyMac_GetStr255, fileName,
+ &vRefNum,
+ &permission))
+ return NULL;
+ _rv = OpenRFPerm(fileName,
+ vRefNum,
+ permission);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_HOpenResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- short vRefNum;
- long dirID;
- Str255 fileName;
- SignedByte permission;
+ PyObject *_res = NULL;
+ short _rv;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
+ SignedByte permission;
#ifndef HOpenResFile
- PyMac_PRECHECK(HOpenResFile);
+ PyMac_PRECHECK(HOpenResFile);
#endif
- if (!PyArg_ParseTuple(_args, "hlO&b",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName,
- &permission))
- return NULL;
- _rv = HOpenResFile(vRefNum,
- dirID,
- fileName,
- permission);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hlO&b",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName,
+ &permission))
+ return NULL;
+ _rv = HOpenResFile(vRefNum,
+ dirID,
+ fileName,
+ permission);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_HCreateResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short vRefNum;
- long dirID;
- Str255 fileName;
+ PyObject *_res = NULL;
+ short vRefNum;
+ long dirID;
+ Str255 fileName;
#ifndef HCreateResFile
- PyMac_PRECHECK(HCreateResFile);
+ PyMac_PRECHECK(HCreateResFile);
#endif
- if (!PyArg_ParseTuple(_args, "hlO&",
- &vRefNum,
- &dirID,
- PyMac_GetStr255, fileName))
- return NULL;
- HCreateResFile(vRefNum,
- dirID,
- fileName);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hlO&",
+ &vRefNum,
+ &dirID,
+ PyMac_GetStr255, fileName))
+ return NULL;
+ HCreateResFile(vRefNum,
+ dirID,
+ fileName);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_FSpOpenResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- FSSpec spec;
- SignedByte permission;
+ PyObject *_res = NULL;
+ short _rv;
+ FSSpec spec;
+ SignedByte permission;
#ifndef FSpOpenResFile
- PyMac_PRECHECK(FSpOpenResFile);
+ PyMac_PRECHECK(FSpOpenResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetFSSpec, &spec,
- &permission))
- return NULL;
- _rv = FSpOpenResFile(&spec,
- permission);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetFSSpec, &spec,
+ &permission))
+ return NULL;
+ _rv = FSpOpenResFile(&spec,
+ permission);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *Res_FSpCreateResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- FSSpec spec;
- OSType creator;
- OSType fileType;
- ScriptCode scriptTag;
+ PyObject *_res = NULL;
+ FSSpec spec;
+ OSType creator;
+ OSType fileType;
+ ScriptCode scriptTag;
#ifndef FSpCreateResFile
- PyMac_PRECHECK(FSpCreateResFile);
+ PyMac_PRECHECK(FSpCreateResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&h",
- PyMac_GetFSSpec, &spec,
- PyMac_GetOSType, &creator,
- PyMac_GetOSType, &fileType,
- &scriptTag))
- return NULL;
- FSpCreateResFile(&spec,
- creator,
- fileType,
- scriptTag);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&O&h",
+ PyMac_GetFSSpec, &spec,
+ PyMac_GetOSType, &creator,
+ PyMac_GetOSType, &fileType,
+ &scriptTag))
+ return NULL;
+ FSpCreateResFile(&spec,
+ creator,
+ fileType,
+ scriptTag);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#endif /* !__LP64__ */
static PyObject *Res_InsertResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 refNum;
- RsrcChainLocation where;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 refNum;
+ RsrcChainLocation where;
#ifndef InsertResourceFile
- PyMac_PRECHECK(InsertResourceFile);
+ PyMac_PRECHECK(InsertResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &refNum,
- &where))
- return NULL;
- _err = InsertResourceFile(refNum,
- where);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &refNum,
+ &where))
+ return NULL;
+ _err = InsertResourceFile(refNum,
+ where);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Res_DetachResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 refNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 refNum;
#ifndef DetachResourceFile
- PyMac_PRECHECK(DetachResourceFile);
+ PyMac_PRECHECK(DetachResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &refNum))
- return NULL;
- _err = DetachResourceFile(refNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &refNum))
+ return NULL;
+ _err = DetachResourceFile(refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
#ifndef __LP64__
static PyObject *Res_FSpResourceFileAlreadyOpen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- FSSpec resourceFile;
- Boolean inChain;
- SInt16 refNum;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ FSSpec resourceFile;
+ Boolean inChain;
+ SInt16 refNum;
#ifndef FSpResourceFileAlreadyOpen
- PyMac_PRECHECK(FSpResourceFileAlreadyOpen);
+ PyMac_PRECHECK(FSpResourceFileAlreadyOpen);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSSpec, &resourceFile))
- return NULL;
- _rv = FSpResourceFileAlreadyOpen(&resourceFile,
- &inChain,
- &refNum);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("bbh",
- _rv,
- inChain,
- refNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSSpec, &resourceFile))
+ return NULL;
+ _rv = FSpResourceFileAlreadyOpen(&resourceFile,
+ &inChain,
+ &refNum);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("bbh",
+ _rv,
+ inChain,
+ refNum);
+ return _res;
}
static PyObject *Res_FSpOpenOrphanResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSSpec spec;
- SignedByte permission;
- SInt16 refNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSSpec spec;
+ SignedByte permission;
+ SInt16 refNum;
#ifndef FSpOpenOrphanResFile
- PyMac_PRECHECK(FSpOpenOrphanResFile);
+ PyMac_PRECHECK(FSpOpenOrphanResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetFSSpec, &spec,
- &permission))
- return NULL;
- _err = FSpOpenOrphanResFile(&spec,
- permission,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetFSSpec, &spec,
+ &permission))
+ return NULL;
+ _err = FSpOpenOrphanResFile(&spec,
+ permission,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *Res_GetTopResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 refNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 refNum;
#ifndef GetTopResourceFile
- PyMac_PRECHECK(GetTopResourceFile);
+ PyMac_PRECHECK(GetTopResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetTopResourceFile(&refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetTopResourceFile(&refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *Res_GetNextResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SInt16 curRefNum;
- SInt16 nextRefNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SInt16 curRefNum;
+ SInt16 nextRefNum;
#ifndef GetNextResourceFile
- PyMac_PRECHECK(GetNextResourceFile);
+ PyMac_PRECHECK(GetNextResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &curRefNum))
- return NULL;
- _err = GetNextResourceFile(curRefNum,
- &nextRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- nextRefNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &curRefNum))
+ return NULL;
+ _err = GetNextResourceFile(curRefNum,
+ &nextRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ nextRefNum);
+ return _res;
}
#endif /* !__LP64__ */
static PyObject *Res_FSOpenResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- FSRef ref;
- SignedByte permission;
+ PyObject *_res = NULL;
+ short _rv;
+ FSRef ref;
+ SignedByte permission;
#ifndef FSOpenResFile
- PyMac_PRECHECK(FSOpenResFile);
+ PyMac_PRECHECK(FSOpenResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetFSRef, &ref,
- &permission))
- return NULL;
- _rv = FSOpenResFile(&ref,
- permission);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetFSRef, &ref,
+ &permission))
+ return NULL;
+ _rv = FSOpenResFile(&ref,
+ permission);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
#ifndef __LP64__
static PyObject *Res_FSCreateResFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- FSRef parentRef;
- UniChar *nameLength__in__;
- UniCharCount nameLength__len__;
- int nameLength__in_len__;
- FSRef newRef;
- FSSpec newSpec;
+ PyObject *_res = NULL;
+ FSRef parentRef;
+ UniChar *nameLength__in__;
+ UniCharCount nameLength__len__;
+ int nameLength__in_len__;
+ FSRef newRef;
+ FSSpec newSpec;
#ifndef FSCreateResFile
- PyMac_PRECHECK(FSCreateResFile);
+ PyMac_PRECHECK(FSCreateResFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&u#",
- PyMac_GetFSRef, &parentRef,
- &nameLength__in__, &nameLength__in_len__))
- return NULL;
- nameLength__len__ = nameLength__in_len__;
- FSCreateResFile(&parentRef,
- nameLength__len__, nameLength__in__,
- 0,
- (FSCatalogInfo *)0,
- &newRef,
- &newSpec);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("O&O&",
- PyMac_BuildFSRef, &newRef,
- PyMac_BuildFSSpec, &newSpec);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&u#",
+ PyMac_GetFSRef, &parentRef,
+ &nameLength__in__, &nameLength__in_len__))
+ return NULL;
+ nameLength__len__ = nameLength__in_len__;
+ FSCreateResFile(&parentRef,
+ nameLength__len__, nameLength__in__,
+ 0,
+ (FSCatalogInfo *)0,
+ &newRef,
+ &newSpec);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildFSRef, &newRef,
+ PyMac_BuildFSSpec, &newSpec);
+ return _res;
}
static PyObject *Res_FSResourceFileAlreadyOpen(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- FSRef resourceFileRef;
- Boolean inChain;
- SInt16 refNum;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ FSRef resourceFileRef;
+ Boolean inChain;
+ SInt16 refNum;
#ifndef FSResourceFileAlreadyOpen
- PyMac_PRECHECK(FSResourceFileAlreadyOpen);
+ PyMac_PRECHECK(FSResourceFileAlreadyOpen);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSRef, &resourceFileRef))
- return NULL;
- _rv = FSResourceFileAlreadyOpen(&resourceFileRef,
- &inChain,
- &refNum);
- {
- OSErr _err = ResError();
- if (_err != noErr) return PyMac_Error(_err);
- }
- _res = Py_BuildValue("bbh",
- _rv,
- inChain,
- refNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSRef, &resourceFileRef))
+ return NULL;
+ _rv = FSResourceFileAlreadyOpen(&resourceFileRef,
+ &inChain,
+ &refNum);
+ {
+ OSErr _err = ResError();
+ if (_err != noErr) return PyMac_Error(_err);
+ }
+ _res = Py_BuildValue("bbh",
+ _rv,
+ inChain,
+ refNum);
+ return _res;
}
static PyObject *Res_FSCreateResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef parentRef;
- UniChar *nameLength__in__;
- UniCharCount nameLength__len__;
- int nameLength__in_len__;
- UniChar *forkNameLength__in__;
- UniCharCount forkNameLength__len__;
- int forkNameLength__in_len__;
- FSRef newRef;
- FSSpec newSpec;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef parentRef;
+ UniChar *nameLength__in__;
+ UniCharCount nameLength__len__;
+ int nameLength__in_len__;
+ UniChar *forkNameLength__in__;
+ UniCharCount forkNameLength__len__;
+ int forkNameLength__in_len__;
+ FSRef newRef;
+ FSSpec newSpec;
#ifndef FSCreateResourceFile
- PyMac_PRECHECK(FSCreateResourceFile);
+ PyMac_PRECHECK(FSCreateResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&u#u#",
- PyMac_GetFSRef, &parentRef,
- &nameLength__in__, &nameLength__in_len__,
- &forkNameLength__in__, &forkNameLength__in_len__))
- return NULL;
- nameLength__len__ = nameLength__in_len__;
- forkNameLength__len__ = forkNameLength__in_len__;
- _err = FSCreateResourceFile(&parentRef,
- nameLength__len__, nameLength__in__,
- 0,
- (FSCatalogInfo *)0,
- forkNameLength__len__, forkNameLength__in__,
- &newRef,
- &newSpec);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildFSRef, &newRef,
- PyMac_BuildFSSpec, &newSpec);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&u#u#",
+ PyMac_GetFSRef, &parentRef,
+ &nameLength__in__, &nameLength__in_len__,
+ &forkNameLength__in__, &forkNameLength__in_len__))
+ return NULL;
+ nameLength__len__ = nameLength__in_len__;
+ forkNameLength__len__ = forkNameLength__in_len__;
+ _err = FSCreateResourceFile(&parentRef,
+ nameLength__len__, nameLength__in__,
+ 0,
+ (FSCatalogInfo *)0,
+ forkNameLength__len__, forkNameLength__in__,
+ &newRef,
+ &newSpec);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildFSRef, &newRef,
+ PyMac_BuildFSSpec, &newSpec);
+ return _res;
}
#endif /* __LP64__ */
static PyObject *Res_FSOpenResourceFile(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- FSRef ref;
- UniChar *forkNameLength__in__;
- UniCharCount forkNameLength__len__;
- int forkNameLength__in_len__;
- SignedByte permissions;
- ResFileRefNum refNum;
+ PyObject *_res = NULL;
+ OSErr _err;
+ FSRef ref;
+ UniChar *forkNameLength__in__;
+ UniCharCount forkNameLength__len__;
+ int forkNameLength__in_len__;
+ SignedByte permissions;
+ ResFileRefNum refNum;
#ifndef FSOpenResourceFile
- PyMac_PRECHECK(FSOpenResourceFile);
+ PyMac_PRECHECK(FSOpenResourceFile);
#endif
- if (!PyArg_ParseTuple(_args, "O&u#b",
- PyMac_GetFSRef, &ref,
- &forkNameLength__in__, &forkNameLength__in_len__,
- &permissions))
- return NULL;
- forkNameLength__len__ = forkNameLength__in_len__;
- _err = FSOpenResourceFile(&ref,
- forkNameLength__len__, forkNameLength__in__,
- permissions,
- &refNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- refNum);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&u#b",
+ PyMac_GetFSRef, &ref,
+ &forkNameLength__in__, &forkNameLength__in_len__,
+ &permissions))
+ return NULL;
+ forkNameLength__len__ = forkNameLength__in_len__;
+ _err = FSOpenResourceFile(&ref,
+ forkNameLength__len__, forkNameLength__in__,
+ permissions,
+ &refNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ refNum);
+ return _res;
}
static PyObject *Res_Handle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- char *buf;
- int len;
- Handle h;
- ResourceObject *rv;
+ char *buf;
+ int len;
+ Handle h;
+ ResourceObject *rv;
- if (!PyArg_ParseTuple(_args, "s#", &buf, &len))
- return NULL;
- h = NewHandle(len);
- if ( h == NULL ) {
- PyErr_NoMemory();
- return NULL;
- }
- HLock(h);
- memcpy(*h, buf, len);
- HUnlock(h);
- rv = (ResourceObject *)ResObj_New(h);
- rv->ob_freeit = PyMac_AutoDisposeHandle;
- _res = (PyObject *)rv;
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#", &buf, &len))
+ return NULL;
+ h = NewHandle(len);
+ if ( h == NULL ) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ HLock(h);
+ memcpy(*h, buf, len);
+ HUnlock(h);
+ rv = (ResourceObject *)ResObj_New(h);
+ rv->ob_freeit = PyMac_AutoDisposeHandle;
+ _res = (PyObject *)rv;
+ return _res;
}
static PyMethodDef Res_methods[] = {
- {"CloseResFile", (PyCFunction)Res_CloseResFile, 1,
- PyDoc_STR("(short refNum) -> None")},
- {"ResError", (PyCFunction)Res_ResError, 1,
- PyDoc_STR("() -> None")},
- {"CurResFile", (PyCFunction)Res_CurResFile, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"UseResFile", (PyCFunction)Res_UseResFile, 1,
- PyDoc_STR("(short refNum) -> None")},
- {"CountTypes", (PyCFunction)Res_CountTypes, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"Count1Types", (PyCFunction)Res_Count1Types, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetIndType", (PyCFunction)Res_GetIndType, 1,
- PyDoc_STR("(short index) -> (ResType theType)")},
- {"Get1IndType", (PyCFunction)Res_Get1IndType, 1,
- PyDoc_STR("(short index) -> (ResType theType)")},
- {"SetResLoad", (PyCFunction)Res_SetResLoad, 1,
- PyDoc_STR("(Boolean load) -> None")},
- {"CountResources", (PyCFunction)Res_CountResources, 1,
- PyDoc_STR("(ResType theType) -> (short _rv)")},
- {"Count1Resources", (PyCFunction)Res_Count1Resources, 1,
- PyDoc_STR("(ResType theType) -> (short _rv)")},
- {"GetIndResource", (PyCFunction)Res_GetIndResource, 1,
- PyDoc_STR("(ResType theType, short index) -> (Handle _rv)")},
- {"Get1IndResource", (PyCFunction)Res_Get1IndResource, 1,
- PyDoc_STR("(ResType theType, short index) -> (Handle _rv)")},
- {"GetResource", (PyCFunction)Res_GetResource, 1,
- PyDoc_STR("(ResType theType, short theID) -> (Handle _rv)")},
- {"Get1Resource", (PyCFunction)Res_Get1Resource, 1,
- PyDoc_STR("(ResType theType, short theID) -> (Handle _rv)")},
- {"GetNamedResource", (PyCFunction)Res_GetNamedResource, 1,
- PyDoc_STR("(ResType theType, Str255 name) -> (Handle _rv)")},
- {"Get1NamedResource", (PyCFunction)Res_Get1NamedResource, 1,
- PyDoc_STR("(ResType theType, Str255 name) -> (Handle _rv)")},
- {"UniqueID", (PyCFunction)Res_UniqueID, 1,
- PyDoc_STR("(ResType theType) -> (short _rv)")},
- {"Unique1ID", (PyCFunction)Res_Unique1ID, 1,
- PyDoc_STR("(ResType theType) -> (short _rv)")},
- {"UpdateResFile", (PyCFunction)Res_UpdateResFile, 1,
- PyDoc_STR("(short refNum) -> None")},
- {"SetResPurge", (PyCFunction)Res_SetResPurge, 1,
- PyDoc_STR("(Boolean install) -> None")},
- {"GetResFileAttrs", (PyCFunction)Res_GetResFileAttrs, 1,
- PyDoc_STR("(short refNum) -> (short _rv)")},
- {"SetResFileAttrs", (PyCFunction)Res_SetResFileAttrs, 1,
- PyDoc_STR("(short refNum, short attrs) -> None")},
+ {"CloseResFile", (PyCFunction)Res_CloseResFile, 1,
+ PyDoc_STR("(short refNum) -> None")},
+ {"ResError", (PyCFunction)Res_ResError, 1,
+ PyDoc_STR("() -> None")},
+ {"CurResFile", (PyCFunction)Res_CurResFile, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"UseResFile", (PyCFunction)Res_UseResFile, 1,
+ PyDoc_STR("(short refNum) -> None")},
+ {"CountTypes", (PyCFunction)Res_CountTypes, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"Count1Types", (PyCFunction)Res_Count1Types, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetIndType", (PyCFunction)Res_GetIndType, 1,
+ PyDoc_STR("(short index) -> (ResType theType)")},
+ {"Get1IndType", (PyCFunction)Res_Get1IndType, 1,
+ PyDoc_STR("(short index) -> (ResType theType)")},
+ {"SetResLoad", (PyCFunction)Res_SetResLoad, 1,
+ PyDoc_STR("(Boolean load) -> None")},
+ {"CountResources", (PyCFunction)Res_CountResources, 1,
+ PyDoc_STR("(ResType theType) -> (short _rv)")},
+ {"Count1Resources", (PyCFunction)Res_Count1Resources, 1,
+ PyDoc_STR("(ResType theType) -> (short _rv)")},
+ {"GetIndResource", (PyCFunction)Res_GetIndResource, 1,
+ PyDoc_STR("(ResType theType, short index) -> (Handle _rv)")},
+ {"Get1IndResource", (PyCFunction)Res_Get1IndResource, 1,
+ PyDoc_STR("(ResType theType, short index) -> (Handle _rv)")},
+ {"GetResource", (PyCFunction)Res_GetResource, 1,
+ PyDoc_STR("(ResType theType, short theID) -> (Handle _rv)")},
+ {"Get1Resource", (PyCFunction)Res_Get1Resource, 1,
+ PyDoc_STR("(ResType theType, short theID) -> (Handle _rv)")},
+ {"GetNamedResource", (PyCFunction)Res_GetNamedResource, 1,
+ PyDoc_STR("(ResType theType, Str255 name) -> (Handle _rv)")},
+ {"Get1NamedResource", (PyCFunction)Res_Get1NamedResource, 1,
+ PyDoc_STR("(ResType theType, Str255 name) -> (Handle _rv)")},
+ {"UniqueID", (PyCFunction)Res_UniqueID, 1,
+ PyDoc_STR("(ResType theType) -> (short _rv)")},
+ {"Unique1ID", (PyCFunction)Res_Unique1ID, 1,
+ PyDoc_STR("(ResType theType) -> (short _rv)")},
+ {"UpdateResFile", (PyCFunction)Res_UpdateResFile, 1,
+ PyDoc_STR("(short refNum) -> None")},
+ {"SetResPurge", (PyCFunction)Res_SetResPurge, 1,
+ PyDoc_STR("(Boolean install) -> None")},
+ {"GetResFileAttrs", (PyCFunction)Res_GetResFileAttrs, 1,
+ PyDoc_STR("(short refNum) -> (short _rv)")},
+ {"SetResFileAttrs", (PyCFunction)Res_SetResFileAttrs, 1,
+ PyDoc_STR("(short refNum, short attrs) -> None")},
#ifndef __LP64__
- {"OpenRFPerm", (PyCFunction)Res_OpenRFPerm, 1,
- PyDoc_STR("(Str255 fileName, short vRefNum, SignedByte permission) -> (short _rv)")},
- {"HOpenResFile", (PyCFunction)Res_HOpenResFile, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SignedByte permission) -> (short _rv)")},
- {"HCreateResFile", (PyCFunction)Res_HCreateResFile, 1,
- PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
- {"FSpOpenResFile", (PyCFunction)Res_FSpOpenResFile, 1,
- PyDoc_STR("(FSSpec spec, SignedByte permission) -> (short _rv)")},
- {"FSpCreateResFile", (PyCFunction)Res_FSpCreateResFile, 1,
- PyDoc_STR("(FSSpec spec, OSType creator, OSType fileType, ScriptCode scriptTag) -> None")},
+ {"OpenRFPerm", (PyCFunction)Res_OpenRFPerm, 1,
+ PyDoc_STR("(Str255 fileName, short vRefNum, SignedByte permission) -> (short _rv)")},
+ {"HOpenResFile", (PyCFunction)Res_HOpenResFile, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName, SignedByte permission) -> (short _rv)")},
+ {"HCreateResFile", (PyCFunction)Res_HCreateResFile, 1,
+ PyDoc_STR("(short vRefNum, long dirID, Str255 fileName) -> None")},
+ {"FSpOpenResFile", (PyCFunction)Res_FSpOpenResFile, 1,
+ PyDoc_STR("(FSSpec spec, SignedByte permission) -> (short _rv)")},
+ {"FSpCreateResFile", (PyCFunction)Res_FSpCreateResFile, 1,
+ PyDoc_STR("(FSSpec spec, OSType creator, OSType fileType, ScriptCode scriptTag) -> None")},
#endif /* !__LP64__ */
- {"InsertResourceFile", (PyCFunction)Res_InsertResourceFile, 1,
- PyDoc_STR("(SInt16 refNum, RsrcChainLocation where) -> None")},
- {"DetachResourceFile", (PyCFunction)Res_DetachResourceFile, 1,
- PyDoc_STR("(SInt16 refNum) -> None")},
+ {"InsertResourceFile", (PyCFunction)Res_InsertResourceFile, 1,
+ PyDoc_STR("(SInt16 refNum, RsrcChainLocation where) -> None")},
+ {"DetachResourceFile", (PyCFunction)Res_DetachResourceFile, 1,
+ PyDoc_STR("(SInt16 refNum) -> None")},
#ifndef __LP64__
- {"FSpResourceFileAlreadyOpen", (PyCFunction)Res_FSpResourceFileAlreadyOpen, 1,
- PyDoc_STR("(FSSpec resourceFile) -> (Boolean _rv, Boolean inChain, SInt16 refNum)")},
- {"FSpOpenOrphanResFile", (PyCFunction)Res_FSpOpenOrphanResFile, 1,
- PyDoc_STR("(FSSpec spec, SignedByte permission) -> (SInt16 refNum)")},
- {"GetTopResourceFile", (PyCFunction)Res_GetTopResourceFile, 1,
- PyDoc_STR("() -> (SInt16 refNum)")},
- {"GetNextResourceFile", (PyCFunction)Res_GetNextResourceFile, 1,
- PyDoc_STR("(SInt16 curRefNum) -> (SInt16 nextRefNum)")},
+ {"FSpResourceFileAlreadyOpen", (PyCFunction)Res_FSpResourceFileAlreadyOpen, 1,
+ PyDoc_STR("(FSSpec resourceFile) -> (Boolean _rv, Boolean inChain, SInt16 refNum)")},
+ {"FSpOpenOrphanResFile", (PyCFunction)Res_FSpOpenOrphanResFile, 1,
+ PyDoc_STR("(FSSpec spec, SignedByte permission) -> (SInt16 refNum)")},
+ {"GetTopResourceFile", (PyCFunction)Res_GetTopResourceFile, 1,
+ PyDoc_STR("() -> (SInt16 refNum)")},
+ {"GetNextResourceFile", (PyCFunction)Res_GetNextResourceFile, 1,
+ PyDoc_STR("(SInt16 curRefNum) -> (SInt16 nextRefNum)")},
#endif /* __LP64__ */
- {"FSOpenResFile", (PyCFunction)Res_FSOpenResFile, 1,
- PyDoc_STR("(FSRef ref, SignedByte permission) -> (short _rv)")},
+ {"FSOpenResFile", (PyCFunction)Res_FSOpenResFile, 1,
+ PyDoc_STR("(FSRef ref, SignedByte permission) -> (short _rv)")},
#ifndef __LP64__
- {"FSCreateResFile", (PyCFunction)Res_FSCreateResFile, 1,
- PyDoc_STR("(FSRef parentRef, Buffer nameLength) -> (FSRef newRef, FSSpec newSpec)")},
- {"FSResourceFileAlreadyOpen", (PyCFunction)Res_FSResourceFileAlreadyOpen, 1,
- PyDoc_STR("(FSRef resourceFileRef) -> (Boolean _rv, Boolean inChain, SInt16 refNum)")},
- {"FSCreateResourceFile", (PyCFunction)Res_FSCreateResourceFile, 1,
- PyDoc_STR("(FSRef parentRef, Buffer nameLength, Buffer forkNameLength) -> (FSRef newRef, FSSpec newSpec)")},
+ {"FSCreateResFile", (PyCFunction)Res_FSCreateResFile, 1,
+ PyDoc_STR("(FSRef parentRef, Buffer nameLength) -> (FSRef newRef, FSSpec newSpec)")},
+ {"FSResourceFileAlreadyOpen", (PyCFunction)Res_FSResourceFileAlreadyOpen, 1,
+ PyDoc_STR("(FSRef resourceFileRef) -> (Boolean _rv, Boolean inChain, SInt16 refNum)")},
+ {"FSCreateResourceFile", (PyCFunction)Res_FSCreateResourceFile, 1,
+ PyDoc_STR("(FSRef parentRef, Buffer nameLength, Buffer forkNameLength) -> (FSRef newRef, FSSpec newSpec)")},
#endif /* __LP64__ */
- {"FSOpenResourceFile", (PyCFunction)Res_FSOpenResourceFile, 1,
- PyDoc_STR("(FSRef ref, Buffer forkNameLength, SignedByte permissions) -> (SInt16 refNum)")},
- {"Handle", (PyCFunction)Res_Handle, 1,
- PyDoc_STR("Convert a string to a Handle object.\n\nResource() and Handle() are very similar, but objects created with Handle() are\nby default automatically DisposeHandle()d upon object cleanup. Use AutoDispose()\nto change this.\n")},
- {NULL, NULL, 0}
+ {"FSOpenResourceFile", (PyCFunction)Res_FSOpenResourceFile, 1,
+ PyDoc_STR("(FSRef ref, Buffer forkNameLength, SignedByte permissions) -> (SInt16 refNum)")},
+ {"Handle", (PyCFunction)Res_Handle, 1,
+ PyDoc_STR("Convert a string to a Handle object.\n\nResource() and Handle() are very similar, but objects created with Handle() are\nby default automatically DisposeHandle()d upon object cleanup. Use AutoDispose()\nto change this.\n")},
+ {NULL, NULL, 0}
};
@@ -1696,64 +1696,64 @@ static PyMethodDef Res_methods[] = {
/* Alternative version of ResObj_New, which returns None for null argument */
PyObject *OptResObj_New(Handle itself)
{
- if (itself == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return ResObj_New(itself);
+ if (itself == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return ResObj_New(itself);
}
int OptResObj_Convert(PyObject *v, Handle *p_itself)
{
- PyObject *tmp;
-
- if ( v == Py_None ) {
- *p_itself = NULL;
- return 1;
- }
- if (ResObj_Check(v))
- {
- *p_itself = ((ResourceObject *)v)->ob_itself;
- return 1;
- }
- /* If it isn't a resource yet see whether it is convertible */
- if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) ) {
- *p_itself = ((ResourceObject *)tmp)->ob_itself;
- Py_DECREF(tmp);
- return 1;
- }
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError, "Resource required");
- return 0;
+ PyObject *tmp;
+
+ if ( v == Py_None ) {
+ *p_itself = NULL;
+ return 1;
+ }
+ if (ResObj_Check(v))
+ {
+ *p_itself = ((ResourceObject *)v)->ob_itself;
+ return 1;
+ }
+ /* If it isn't a resource yet see whether it is convertible */
+ if ( (tmp=PyObject_CallMethod(v, "as_Resource", "")) ) {
+ *p_itself = ((ResourceObject *)tmp)->ob_itself;
+ Py_DECREF(tmp);
+ return 1;
+ }
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError, "Resource required");
+ return 0;
}
void init_Res(void)
{
- PyObject *m;
- PyObject *d;
+ PyObject *m;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, ResObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, ResObj_Convert);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, OptResObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, OptResObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, ResObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, ResObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(Handle, OptResObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(Handle, OptResObj_Convert);
- m = Py_InitModule("_Res", Res_methods);
- d = PyModule_GetDict(m);
- Res_Error = PyMac_GetOSErrException();
- if (Res_Error == NULL ||
- PyDict_SetItemString(d, "Error", Res_Error) != 0)
- return;
- Resource_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Resource_Type) < 0) return;
- Py_INCREF(&Resource_Type);
- PyModule_AddObject(m, "Resource", (PyObject *)&Resource_Type);
- /* Backward-compatible name */
- Py_INCREF(&Resource_Type);
- PyModule_AddObject(m, "ResourceType", (PyObject *)&Resource_Type);
+ m = Py_InitModule("_Res", Res_methods);
+ d = PyModule_GetDict(m);
+ Res_Error = PyMac_GetOSErrException();
+ if (Res_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Res_Error) != 0)
+ return;
+ Resource_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Resource_Type) < 0) return;
+ Py_INCREF(&Resource_Type);
+ PyModule_AddObject(m, "Resource", (PyObject *)&Resource_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Resource_Type);
+ PyModule_AddObject(m, "ResourceType", (PyObject *)&Resource_Type);
}
/* ======================== End module _Res ========================= */
diff --git a/Mac/Modules/scrap/_Scrapmodule.c b/Mac/Modules/scrap/_Scrapmodule.c
index 14e3fd2..f24ed8b 100644
--- a/Mac/Modules/scrap/_Scrapmodule.c
+++ b/Mac/Modules/scrap/_Scrapmodule.c
@@ -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;
-
- 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;
+ 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;
}
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__ */
}
diff --git a/Mac/Modules/snd/_Sndihooks.c b/Mac/Modules/snd/_Sndihooks.c
index 74cad9b..254fc0c 100644
--- a/Mac/Modules/snd/_Sndihooks.c
+++ b/Mac/Modules/snd/_Sndihooks.c
@@ -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;
-
- 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);
+ 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);
}
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;
-
- 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);
+ 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);
}
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;
-
- 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;
+ 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;
}
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;
-
- 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);
+ 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);
}
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;
-
- 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;
+ 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;
}
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;
-
- 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);
+ 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);
}
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;
-
- 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);
+ 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);
}
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;
-
- 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;
+ 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;
}
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;
-
- 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);
+ 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);
}
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;
-
- 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;
+ 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;
}
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;
-
- 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);
+ 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);
}
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;
-
- 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;
+ 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;
}
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;
-
- 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);
+ 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);
}
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;
-
- 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;
+ 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;
}
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;
-
- 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;
+ 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;
}
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;
-
- 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);
+ 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);
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;
-
- /* 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);
-
- /* XXXX Add constants here */
-
- /* Check for errors */
- if (PyErr_Occurred())
- Py_FatalError("can't initialize module Sndihooks");
+ PyObject *m, *d;
+
+ /* 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);
+
+ /* XXXX Add constants here */
+
+ /* Check for errors */
+ if (PyErr_Occurred())
+ Py_FatalError("can't initialize module Sndihooks");
}
diff --git a/Mac/Modules/snd/_Sndmodule.c b/Mac/Modules/snd/_Sndmodule.c
index 1f64629..d713efe 100644
--- a/Mac/Modules/snd/_Sndmodule.c
+++ b/Mac/Modules/snd/_Sndmodule.c
@@ -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,16 +22,16 @@
static int
SndCmd_Convert(PyObject *v, SndCommand *pc)
{
- int len;
- pc->param1 = 0;
- pc->param2 = 0;
- if (PyTuple_Check(v)) {
- if (PyArg_ParseTuple(v, "h|hl", &pc->cmd, &pc->param1, &pc->param2))
- return 1;
- PyErr_Clear();
- return PyArg_ParseTuple(v, "Hhs#", &pc->cmd, &pc->param1, &pc->param2, &len);
- }
- return PyArg_Parse(v, "H", &pc->cmd);
+ int len;
+ pc->param1 = 0;
+ pc->param2 = 0;
+ if (PyTuple_Check(v)) {
+ if (PyArg_ParseTuple(v, "h|hl", &pc->cmd, &pc->param1, &pc->param2))
+ return 1;
+ PyErr_Clear();
+ return PyArg_ParseTuple(v, "Hhs#", &pc->cmd, &pc->param1, &pc->param2, &len);
+ }
+ return PyArg_Parse(v, "H", &pc->cmd);
}
static pascal void SndCh_UserRoutine(SndChannelPtr chan, SndCommand *cmd); /* Forward */
@@ -46,156 +46,156 @@ static PyTypeObject SndChannel_Type;
#define SndCh_Check(x) ((x)->ob_type == &SndChannel_Type || PyObject_TypeCheck((x), &SndChannel_Type))
typedef struct SndChannelObject {
- PyObject_HEAD
- SndChannelPtr ob_itself;
- /* Members used to implement callbacks: */
- PyObject *ob_callback;
- long ob_A5;
- SndCommand ob_cmd;
+ PyObject_HEAD
+ SndChannelPtr ob_itself;
+ /* Members used to implement callbacks: */
+ PyObject *ob_callback;
+ long ob_A5;
+ SndCommand ob_cmd;
} SndChannelObject;
static PyObject *SndCh_New(SndChannelPtr itself)
{
- SndChannelObject *it;
- it = PyObject_NEW(SndChannelObject, &SndChannel_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_callback = NULL;
- it->ob_A5 = SetCurrentA5();
- return (PyObject *)it;
+ SndChannelObject *it;
+ it = PyObject_NEW(SndChannelObject, &SndChannel_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_callback = NULL;
+ it->ob_A5 = SetCurrentA5();
+ return (PyObject *)it;
}
static void SndCh_dealloc(SndChannelObject *self)
{
- SndDisposeChannel(self->ob_itself, 1);
- Py_XDECREF(self->ob_callback);
- PyObject_Free((PyObject *)self);
+ SndDisposeChannel(self->ob_itself, 1);
+ Py_XDECREF(self->ob_callback);
+ PyObject_Free((PyObject *)self);
}
static PyObject *SndCh_SndDoCommand(SndChannelObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SndCommand cmd;
- Boolean noWait;
- if (!PyArg_ParseTuple(_args, "O&b",
- SndCmd_Convert, &cmd,
- &noWait))
- return NULL;
- _err = SndDoCommand(_self->ob_itself,
- &cmd,
- noWait);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SndCommand cmd;
+ Boolean noWait;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ SndCmd_Convert, &cmd,
+ &noWait))
+ return NULL;
+ _err = SndDoCommand(_self->ob_itself,
+ &cmd,
+ noWait);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *SndCh_SndDoImmediate(SndChannelObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SndCommand cmd;
- if (!PyArg_ParseTuple(_args, "O&",
- SndCmd_Convert, &cmd))
- return NULL;
- _err = SndDoImmediate(_self->ob_itself,
- &cmd);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SndCommand cmd;
+ if (!PyArg_ParseTuple(_args, "O&",
+ SndCmd_Convert, &cmd))
+ return NULL;
+ _err = SndDoImmediate(_self->ob_itself,
+ &cmd);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *SndCh_SndPlay(SndChannelObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SndListHandle sndHandle;
- Boolean async;
- if (!PyArg_ParseTuple(_args, "O&b",
- ResObj_Convert, &sndHandle,
- &async))
- return NULL;
- _err = SndPlay(_self->ob_itself,
- sndHandle,
- async);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SndListHandle sndHandle;
+ Boolean async;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ ResObj_Convert, &sndHandle,
+ &async))
+ return NULL;
+ _err = SndPlay(_self->ob_itself,
+ sndHandle,
+ async);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *SndCh_SndChannelStatus(SndChannelObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short theLength;
- SCStatus theStatus__out__;
- if (!PyArg_ParseTuple(_args, "h",
- &theLength))
- return NULL;
- _err = SndChannelStatus(_self->ob_itself,
- theLength,
- &theStatus__out__);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("s#",
- (char *)&theStatus__out__, (int)sizeof(SCStatus));
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short theLength;
+ SCStatus theStatus__out__;
+ if (!PyArg_ParseTuple(_args, "h",
+ &theLength))
+ return NULL;
+ _err = SndChannelStatus(_self->ob_itself,
+ theLength,
+ &theStatus__out__);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("s#",
+ (char *)&theStatus__out__, (int)sizeof(SCStatus));
+ return _res;
}
static PyObject *SndCh_SndGetInfo(SndChannelObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType selector;
- void * infoPtr;
- if (!PyArg_ParseTuple(_args, "O&w",
- PyMac_GetOSType, &selector,
- &infoPtr))
- return NULL;
- _err = SndGetInfo(_self->ob_itself,
- selector,
- infoPtr);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType selector;
+ void * infoPtr;
+ if (!PyArg_ParseTuple(_args, "O&w",
+ PyMac_GetOSType, &selector,
+ &infoPtr))
+ return NULL;
+ _err = SndGetInfo(_self->ob_itself,
+ selector,
+ infoPtr);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *SndCh_SndSetInfo(SndChannelObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType selector;
- void * infoPtr;
- if (!PyArg_ParseTuple(_args, "O&w",
- PyMac_GetOSType, &selector,
- &infoPtr))
- return NULL;
- _err = SndSetInfo(_self->ob_itself,
- selector,
- infoPtr);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType selector;
+ void * infoPtr;
+ if (!PyArg_ParseTuple(_args, "O&w",
+ PyMac_GetOSType, &selector,
+ &infoPtr))
+ return NULL;
+ _err = SndSetInfo(_self->ob_itself,
+ selector,
+ infoPtr);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyMethodDef SndCh_methods[] = {
- {"SndDoCommand", (PyCFunction)SndCh_SndDoCommand, 1,
- PyDoc_STR("(SndCommand cmd, Boolean noWait) -> None")},
- {"SndDoImmediate", (PyCFunction)SndCh_SndDoImmediate, 1,
- PyDoc_STR("(SndCommand cmd) -> None")},
- {"SndPlay", (PyCFunction)SndCh_SndPlay, 1,
- PyDoc_STR("(SndListHandle sndHandle, Boolean async) -> None")},
- {"SndChannelStatus", (PyCFunction)SndCh_SndChannelStatus, 1,
- PyDoc_STR("(short theLength) -> (SCStatus theStatus)")},
- {"SndGetInfo", (PyCFunction)SndCh_SndGetInfo, 1,
- PyDoc_STR("(OSType selector, void * infoPtr) -> None")},
- {"SndSetInfo", (PyCFunction)SndCh_SndSetInfo, 1,
- PyDoc_STR("(OSType selector, void * infoPtr) -> None")},
- {NULL, NULL, 0}
+ {"SndDoCommand", (PyCFunction)SndCh_SndDoCommand, 1,
+ PyDoc_STR("(SndCommand cmd, Boolean noWait) -> None")},
+ {"SndDoImmediate", (PyCFunction)SndCh_SndDoImmediate, 1,
+ PyDoc_STR("(SndCommand cmd) -> None")},
+ {"SndPlay", (PyCFunction)SndCh_SndPlay, 1,
+ PyDoc_STR("(SndListHandle sndHandle, Boolean async) -> None")},
+ {"SndChannelStatus", (PyCFunction)SndCh_SndChannelStatus, 1,
+ PyDoc_STR("(short theLength) -> (SCStatus theStatus)")},
+ {"SndGetInfo", (PyCFunction)SndCh_SndGetInfo, 1,
+ PyDoc_STR("(OSType selector, void * infoPtr) -> None")},
+ {"SndSetInfo", (PyCFunction)SndCh_SndSetInfo, 1,
+ PyDoc_STR("(OSType selector, void * infoPtr) -> None")},
+ {NULL, NULL, 0}
};
#define SndCh_getsetlist NULL
@@ -208,47 +208,47 @@ static PyMethodDef SndCh_methods[] = {
#define SndCh_hash NULL
static PyTypeObject SndChannel_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Snd.SndChannel", /*tp_name*/
- sizeof(SndChannelObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) SndCh_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) SndCh_compare, /*tp_compare*/
- (reprfunc) SndCh_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) SndCh_hash, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- PyObject_GenericSetAttr, /*tp_setattro */
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SndCh_methods, /* tp_methods */
- 0, /*tp_members*/
- SndCh_getsetlist, /*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*/
- 0, /*tp_free*/
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Snd.SndChannel", /*tp_name*/
+ sizeof(SndChannelObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) SndCh_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) SndCh_compare, /*tp_compare*/
+ (reprfunc) SndCh_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) SndCh_hash, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ PyObject_GenericSetAttr, /*tp_setattro */
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SndCh_methods, /* tp_methods */
+ 0, /*tp_members*/
+ SndCh_getsetlist, /*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*/
+ 0, /*tp_free*/
};
/* ------------------- End object type SndChannel ------------------- */
@@ -261,89 +261,89 @@ static PyTypeObject SPB_Type;
#define SPBObj_Check(x) ((x)->ob_type == &SPB_Type || PyObject_TypeCheck((x), &SPB_Type))
typedef struct SPBObject {
- PyObject_HEAD
- /* Members used to implement callbacks: */
- PyObject *ob_completion;
- PyObject *ob_interrupt;
- PyObject *ob_thiscallback;
- long ob_A5;
- SPB ob_spb;
+ PyObject_HEAD
+ /* Members used to implement callbacks: */
+ PyObject *ob_completion;
+ PyObject *ob_interrupt;
+ PyObject *ob_thiscallback;
+ long ob_A5;
+ SPB ob_spb;
} SPBObject;
static PyObject *SPBObj_New(void)
{
- SPBObject *it;
- it = PyObject_NEW(SPBObject, &SPB_Type);
- if (it == NULL) return NULL;
- it->ob_completion = NULL;
- it->ob_interrupt = NULL;
- it->ob_thiscallback = NULL;
- it->ob_A5 = SetCurrentA5();
- memset((char *)&it->ob_spb, 0, sizeof(it->ob_spb));
- it->ob_spb.userLong = (long)it;
- return (PyObject *)it;
+ SPBObject *it;
+ it = PyObject_NEW(SPBObject, &SPB_Type);
+ if (it == NULL) return NULL;
+ it->ob_completion = NULL;
+ it->ob_interrupt = NULL;
+ it->ob_thiscallback = NULL;
+ it->ob_A5 = SetCurrentA5();
+ memset((char *)&it->ob_spb, 0, sizeof(it->ob_spb));
+ it->ob_spb.userLong = (long)it;
+ return (PyObject *)it;
}
static int SPBObj_Convert(PyObject *v, SPBPtr *p_itself)
{
- if (!SPBObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "SPB required");
- return 0;
- }
- *p_itself = &((SPBObject *)v)->ob_spb;
- return 1;
+ if (!SPBObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "SPB required");
+ return 0;
+ }
+ *p_itself = &((SPBObject *)v)->ob_spb;
+ return 1;
}
static void SPBObj_dealloc(SPBObject *self)
{
- /* Cleanup of self->ob_itself goes here */
- self->ob_spb.userLong = 0;
- self->ob_thiscallback = 0;
- Py_XDECREF(self->ob_completion);
- Py_XDECREF(self->ob_interrupt);
- PyObject_Free((PyObject *)self);
+ /* Cleanup of self->ob_itself goes here */
+ self->ob_spb.userLong = 0;
+ self->ob_thiscallback = 0;
+ Py_XDECREF(self->ob_completion);
+ Py_XDECREF(self->ob_interrupt);
+ PyObject_Free((PyObject *)self);
}
static PyMethodDef SPBObj_methods[] = {
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
static PyObject *SPBObj_get_inRefNum(SPBObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_spb.inRefNum);
+ return Py_BuildValue("l", self->ob_spb.inRefNum);
}
static int SPBObj_set_inRefNum(SPBObject *self, PyObject *v, void *closure)
{
- return -1 + PyArg_Parse(v, "l", &self->ob_spb.inRefNum);
- return 0;
+ return -1 + PyArg_Parse(v, "l", &self->ob_spb.inRefNum);
+ return 0;
}
static PyObject *SPBObj_get_count(SPBObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_spb.count);
+ return Py_BuildValue("l", self->ob_spb.count);
}
static int SPBObj_set_count(SPBObject *self, PyObject *v, void *closure)
{
- return -1 + PyArg_Parse(v, "l", &self->ob_spb.count);
- return 0;
+ return -1 + PyArg_Parse(v, "l", &self->ob_spb.count);
+ return 0;
}
static PyObject *SPBObj_get_milliseconds(SPBObject *self, void *closure)
{
- return Py_BuildValue("l", self->ob_spb.milliseconds);
+ return Py_BuildValue("l", self->ob_spb.milliseconds);
}
static int SPBObj_set_milliseconds(SPBObject *self, PyObject *v, void *closure)
{
- return -1 + PyArg_Parse(v, "l", &self->ob_spb.milliseconds);
- return 0;
+ return -1 + PyArg_Parse(v, "l", &self->ob_spb.milliseconds);
+ return 0;
}
static PyObject *SPBObj_get_error(SPBObject *self, void *closure)
{
- return Py_BuildValue("h", self->ob_spb.error);
+ return Py_BuildValue("h", self->ob_spb.error);
}
#define SPBObj_set_error NULL
@@ -352,20 +352,20 @@ static PyObject *SPBObj_get_error(SPBObject *self, void *closure)
static int SPBObj_set_completionRoutine(SPBObject *self, PyObject *v, void *closure)
{
- self->ob_spb.completionRoutine = NewSICompletionUPP(SPB_completion);
- self->ob_completion = v;
- Py_INCREF(v);
- return 0;
- return 0;
+ self->ob_spb.completionRoutine = NewSICompletionUPP(SPB_completion);
+ self->ob_completion = v;
+ Py_INCREF(v);
+ return 0;
+ return 0;
}
static PyGetSetDef SPBObj_getsetlist[] = {
- {"inRefNum", (getter)SPBObj_get_inRefNum, (setter)SPBObj_set_inRefNum, NULL},
- {"count", (getter)SPBObj_get_count, (setter)SPBObj_set_count, NULL},
- {"milliseconds", (getter)SPBObj_get_milliseconds, (setter)SPBObj_set_milliseconds, NULL},
- {"error", (getter)SPBObj_get_error, (setter)SPBObj_set_error, NULL},
- {"completionRoutine", (getter)SPBObj_get_completionRoutine, (setter)SPBObj_set_completionRoutine, NULL},
- {NULL, NULL, NULL, NULL},
+ {"inRefNum", (getter)SPBObj_get_inRefNum, (setter)SPBObj_set_inRefNum, NULL},
+ {"count", (getter)SPBObj_get_count, (setter)SPBObj_set_count, NULL},
+ {"milliseconds", (getter)SPBObj_get_milliseconds, (setter)SPBObj_set_milliseconds, NULL},
+ {"error", (getter)SPBObj_get_error, (setter)SPBObj_set_error, NULL},
+ {"completionRoutine", (getter)SPBObj_get_completionRoutine, (setter)SPBObj_set_completionRoutine, NULL},
+ {NULL, NULL, NULL, NULL},
};
@@ -376,47 +376,47 @@ static PyGetSetDef SPBObj_getsetlist[] = {
#define SPBObj_hash NULL
static PyTypeObject SPB_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Snd.SPB", /*tp_name*/
- sizeof(SPBObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) SPBObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) SPBObj_compare, /*tp_compare*/
- (reprfunc) SPBObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) SPBObj_hash, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- PyObject_GenericSetAttr, /*tp_setattro */
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SPBObj_methods, /* tp_methods */
- 0, /*tp_members*/
- SPBObj_getsetlist, /*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*/
- 0, /*tp_free*/
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Snd.SPB", /*tp_name*/
+ sizeof(SPBObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) SPBObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) SPBObj_compare, /*tp_compare*/
+ (reprfunc) SPBObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) SPBObj_hash, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ PyObject_GenericSetAttr, /*tp_setattro */
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SPBObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ SPBObj_getsetlist, /*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*/
+ 0, /*tp_free*/
};
/* ---------------------- End object type SPB ----------------------- */
@@ -424,634 +424,634 @@ static PyTypeObject SPB_Type = {
static PyObject *Snd_SPB(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- _res = SPBObj_New(); return _res;
+ PyObject *_res = NULL;
+ _res = SPBObj_New(); return _res;
}
static PyObject *Snd_SysBeep(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short duration;
- if (!PyArg_ParseTuple(_args, "h",
- &duration))
- return NULL;
- SysBeep(duration);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ short duration;
+ if (!PyArg_ParseTuple(_args, "h",
+ &duration))
+ return NULL;
+ SysBeep(duration);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SndNewChannel(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SndChannelPtr chan = 0;
- short synth;
- long init;
- PyObject* userRoutine;
- if (!PyArg_ParseTuple(_args, "hlO",
- &synth,
- &init,
- &userRoutine))
- return NULL;
- if (userRoutine != Py_None && !PyCallable_Check(userRoutine))
- {
- PyErr_SetString(PyExc_TypeError, "callback must be callable");
- goto userRoutine__error__;
- }
- _err = SndNewChannel(&chan,
- synth,
- init,
- NewSndCallBackUPP(SndCh_UserRoutine));
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- SndCh_New, chan);
- if (_res != NULL && userRoutine != Py_None)
- {
- SndChannelObject *p = (SndChannelObject *)_res;
- p->ob_itself->userInfo = (long)p;
- Py_INCREF(userRoutine);
- p->ob_callback = userRoutine;
- }
+ PyObject *_res = NULL;
+ OSErr _err;
+ SndChannelPtr chan = 0;
+ short synth;
+ long init;
+ PyObject* userRoutine;
+ if (!PyArg_ParseTuple(_args, "hlO",
+ &synth,
+ &init,
+ &userRoutine))
+ return NULL;
+ if (userRoutine != Py_None && !PyCallable_Check(userRoutine))
+ {
+ PyErr_SetString(PyExc_TypeError, "callback must be callable");
+ goto userRoutine__error__;
+ }
+ _err = SndNewChannel(&chan,
+ synth,
+ init,
+ NewSndCallBackUPP(SndCh_UserRoutine));
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ SndCh_New, chan);
+ if (_res != NULL && userRoutine != Py_None)
+ {
+ SndChannelObject *p = (SndChannelObject *)_res;
+ p->ob_itself->userInfo = (long)p;
+ Py_INCREF(userRoutine);
+ p->ob_callback = userRoutine;
+ }
userRoutine__error__: ;
- return _res;
+ return _res;
}
static PyObject *Snd_SndSoundManagerVersion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- NumVersion _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = SndSoundManagerVersion();
- _res = Py_BuildValue("O&",
- PyMac_BuildNumVersion, _rv);
- return _res;
+ PyObject *_res = NULL;
+ NumVersion _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = SndSoundManagerVersion();
+ _res = Py_BuildValue("O&",
+ PyMac_BuildNumVersion, _rv);
+ return _res;
}
static PyObject *Snd_SndManagerStatus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short theLength;
- SMStatus theStatus__out__;
- if (!PyArg_ParseTuple(_args, "h",
- &theLength))
- return NULL;
- _err = SndManagerStatus(theLength,
- &theStatus__out__);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("s#",
- (char *)&theStatus__out__, (int)sizeof(SMStatus));
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short theLength;
+ SMStatus theStatus__out__;
+ if (!PyArg_ParseTuple(_args, "h",
+ &theLength))
+ return NULL;
+ _err = SndManagerStatus(theLength,
+ &theStatus__out__);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("s#",
+ (char *)&theStatus__out__, (int)sizeof(SMStatus));
+ return _res;
}
static PyObject *Snd_SndGetSysBeepState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short sysBeepState;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- SndGetSysBeepState(&sysBeepState);
- _res = Py_BuildValue("h",
- sysBeepState);
- return _res;
+ PyObject *_res = NULL;
+ short sysBeepState;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ SndGetSysBeepState(&sysBeepState);
+ _res = Py_BuildValue("h",
+ sysBeepState);
+ return _res;
}
static PyObject *Snd_SndSetSysBeepState(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short sysBeepState;
- if (!PyArg_ParseTuple(_args, "h",
- &sysBeepState))
- return NULL;
- _err = SndSetSysBeepState(sysBeepState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short sysBeepState;
+ if (!PyArg_ParseTuple(_args, "h",
+ &sysBeepState))
+ return NULL;
+ _err = SndSetSysBeepState(sysBeepState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_GetSysBeepVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long level;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetSysBeepVolume(&level);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- level);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long level;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetSysBeepVolume(&level);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ level);
+ return _res;
}
static PyObject *Snd_SetSysBeepVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long level;
- if (!PyArg_ParseTuple(_args, "l",
- &level))
- return NULL;
- _err = SetSysBeepVolume(level);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long level;
+ if (!PyArg_ParseTuple(_args, "l",
+ &level))
+ return NULL;
+ _err = SetSysBeepVolume(level);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_GetDefaultOutputVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long level;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetDefaultOutputVolume(&level);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- level);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long level;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetDefaultOutputVolume(&level);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ level);
+ return _res;
}
static PyObject *Snd_SetDefaultOutputVolume(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long level;
- if (!PyArg_ParseTuple(_args, "l",
- &level))
- return NULL;
- _err = SetDefaultOutputVolume(level);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long level;
+ if (!PyArg_ParseTuple(_args, "l",
+ &level))
+ return NULL;
+ _err = SetDefaultOutputVolume(level);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_GetSoundHeaderOffset(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SndListHandle sndHandle;
- long offset;
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &sndHandle))
- return NULL;
- _err = GetSoundHeaderOffset(sndHandle,
- &offset);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- offset);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SndListHandle sndHandle;
+ long offset;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &sndHandle))
+ return NULL;
+ _err = GetSoundHeaderOffset(sndHandle,
+ &offset);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ offset);
+ return _res;
}
static PyObject *Snd_GetCompressionInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short compressionID;
- OSType format;
- short numChannels;
- short sampleSize;
- CompressionInfo cp__out__;
- if (!PyArg_ParseTuple(_args, "hO&hh",
- &compressionID,
- PyMac_GetOSType, &format,
- &numChannels,
- &sampleSize))
- return NULL;
- _err = GetCompressionInfo(compressionID,
- format,
- numChannels,
- sampleSize,
- &cp__out__);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("s#",
- (char *)&cp__out__, (int)sizeof(CompressionInfo));
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short compressionID;
+ OSType format;
+ short numChannels;
+ short sampleSize;
+ CompressionInfo cp__out__;
+ if (!PyArg_ParseTuple(_args, "hO&hh",
+ &compressionID,
+ PyMac_GetOSType, &format,
+ &numChannels,
+ &sampleSize))
+ return NULL;
+ _err = GetCompressionInfo(compressionID,
+ format,
+ numChannels,
+ sampleSize,
+ &cp__out__);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("s#",
+ (char *)&cp__out__, (int)sizeof(CompressionInfo));
+ return _res;
}
static PyObject *Snd_SetSoundPreference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType theType;
- Str255 name;
- Handle settings;
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theType,
- ResObj_Convert, &settings))
- return NULL;
- _err = SetSoundPreference(theType,
- name,
- settings);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, name);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType theType;
+ Str255 name;
+ Handle settings;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theType,
+ ResObj_Convert, &settings))
+ return NULL;
+ _err = SetSoundPreference(theType,
+ name,
+ settings);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, name);
+ return _res;
}
static PyObject *Snd_GetSoundPreference(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType theType;
- Str255 name;
- Handle settings;
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &theType,
- ResObj_Convert, &settings))
- return NULL;
- _err = GetSoundPreference(theType,
- name,
- settings);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, name);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType theType;
+ Str255 name;
+ Handle settings;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &theType,
+ ResObj_Convert, &settings))
+ return NULL;
+ _err = GetSoundPreference(theType,
+ name,
+ settings);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, name);
+ return _res;
}
static PyObject *Snd_GetCompressionName(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- OSType compressionType;
- Str255 compressionName;
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetOSType, &compressionType))
- return NULL;
- _err = GetCompressionName(compressionType,
- compressionName);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, compressionName);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ OSType compressionType;
+ Str255 compressionName;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetOSType, &compressionType))
+ return NULL;
+ _err = GetCompressionName(compressionType,
+ compressionName);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, compressionName);
+ return _res;
}
static PyObject *Snd_SPBVersion(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- NumVersion _rv;
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = SPBVersion();
- _res = Py_BuildValue("O&",
- PyMac_BuildNumVersion, _rv);
- return _res;
+ PyObject *_res = NULL;
+ NumVersion _rv;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = SPBVersion();
+ _res = Py_BuildValue("O&",
+ PyMac_BuildNumVersion, _rv);
+ return _res;
}
static PyObject *Snd_SndRecord(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Point corner;
- OSType quality;
- SndListHandle sndHandle;
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &corner,
- PyMac_GetOSType, &quality))
- return NULL;
- _err = SndRecord((ModalFilterUPP)0,
- corner,
- quality,
- &sndHandle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, sndHandle);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Point corner;
+ OSType quality;
+ SndListHandle sndHandle;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &corner,
+ PyMac_GetOSType, &quality))
+ return NULL;
+ _err = SndRecord((ModalFilterUPP)0,
+ corner,
+ quality,
+ &sndHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, sndHandle);
+ return _res;
}
static PyObject *Snd_SPBSignInDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short deviceRefNum;
- Str255 deviceName;
- if (!PyArg_ParseTuple(_args, "hO&",
- &deviceRefNum,
- PyMac_GetStr255, deviceName))
- return NULL;
- _err = SPBSignInDevice(deviceRefNum,
- deviceName);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short deviceRefNum;
+ Str255 deviceName;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &deviceRefNum,
+ PyMac_GetStr255, deviceName))
+ return NULL;
+ _err = SPBSignInDevice(deviceRefNum,
+ deviceName);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBSignOutDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short deviceRefNum;
- if (!PyArg_ParseTuple(_args, "h",
- &deviceRefNum))
- return NULL;
- _err = SPBSignOutDevice(deviceRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short deviceRefNum;
+ if (!PyArg_ParseTuple(_args, "h",
+ &deviceRefNum))
+ return NULL;
+ _err = SPBSignOutDevice(deviceRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBGetIndexedDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- short count;
- Str255 deviceName;
- Handle deviceIconHandle;
- if (!PyArg_ParseTuple(_args, "h",
- &count))
- return NULL;
- _err = SPBGetIndexedDevice(count,
- deviceName,
- &deviceIconHandle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- PyMac_BuildStr255, deviceName,
- ResObj_New, deviceIconHandle);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ short count;
+ Str255 deviceName;
+ Handle deviceIconHandle;
+ if (!PyArg_ParseTuple(_args, "h",
+ &count))
+ return NULL;
+ _err = SPBGetIndexedDevice(count,
+ deviceName,
+ &deviceIconHandle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ PyMac_BuildStr255, deviceName,
+ ResObj_New, deviceIconHandle);
+ return _res;
}
static PyObject *Snd_SPBOpenDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- Str255 deviceName;
- short permission;
- long inRefNum;
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetStr255, deviceName,
- &permission))
- return NULL;
- _err = SPBOpenDevice(deviceName,
- permission,
- &inRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- inRefNum);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ Str255 deviceName;
+ short permission;
+ long inRefNum;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetStr255, deviceName,
+ &permission))
+ return NULL;
+ _err = SPBOpenDevice(deviceName,
+ permission,
+ &inRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ inRefNum);
+ return _res;
}
static PyObject *Snd_SPBCloseDevice(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBCloseDevice(inRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBCloseDevice(inRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBRecord(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- SPBPtr inParamPtr;
- Boolean asynchFlag;
- if (!PyArg_ParseTuple(_args, "O&b",
- SPBObj_Convert, &inParamPtr,
- &asynchFlag))
- return NULL;
- _err = SPBRecord(inParamPtr,
- asynchFlag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ SPBPtr inParamPtr;
+ Boolean asynchFlag;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ SPBObj_Convert, &inParamPtr,
+ &asynchFlag))
+ return NULL;
+ _err = SPBRecord(inParamPtr,
+ asynchFlag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBPauseRecording(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBPauseRecording(inRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBPauseRecording(inRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBResumeRecording(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBResumeRecording(inRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBResumeRecording(inRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBStopRecording(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBStopRecording(inRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBStopRecording(inRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBGetRecordingStatus(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- short recordingStatus;
- short meterLevel;
- unsigned long totalSamplesToRecord;
- unsigned long numberOfSamplesRecorded;
- unsigned long totalMsecsToRecord;
- unsigned long numberOfMsecsRecorded;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBGetRecordingStatus(inRefNum,
- &recordingStatus,
- &meterLevel,
- &totalSamplesToRecord,
- &numberOfSamplesRecorded,
- &totalMsecsToRecord,
- &numberOfMsecsRecorded);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("hhllll",
- recordingStatus,
- meterLevel,
- totalSamplesToRecord,
- numberOfSamplesRecorded,
- totalMsecsToRecord,
- numberOfMsecsRecorded);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ short recordingStatus;
+ short meterLevel;
+ unsigned long totalSamplesToRecord;
+ unsigned long numberOfSamplesRecorded;
+ unsigned long totalMsecsToRecord;
+ unsigned long numberOfMsecsRecorded;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBGetRecordingStatus(inRefNum,
+ &recordingStatus,
+ &meterLevel,
+ &totalSamplesToRecord,
+ &numberOfSamplesRecorded,
+ &totalMsecsToRecord,
+ &numberOfMsecsRecorded);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("hhllll",
+ recordingStatus,
+ meterLevel,
+ totalSamplesToRecord,
+ numberOfSamplesRecorded,
+ totalMsecsToRecord,
+ numberOfMsecsRecorded);
+ return _res;
}
static PyObject *Snd_SPBGetDeviceInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- OSType infoType;
- void * infoData;
- if (!PyArg_ParseTuple(_args, "lO&w",
- &inRefNum,
- PyMac_GetOSType, &infoType,
- &infoData))
- return NULL;
- _err = SPBGetDeviceInfo(inRefNum,
- infoType,
- infoData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ OSType infoType;
+ void * infoData;
+ if (!PyArg_ParseTuple(_args, "lO&w",
+ &inRefNum,
+ PyMac_GetOSType, &infoType,
+ &infoData))
+ return NULL;
+ _err = SPBGetDeviceInfo(inRefNum,
+ infoType,
+ infoData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBSetDeviceInfo(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- OSType infoType;
- void * infoData;
- if (!PyArg_ParseTuple(_args, "lO&w",
- &inRefNum,
- PyMac_GetOSType, &infoType,
- &infoData))
- return NULL;
- _err = SPBSetDeviceInfo(inRefNum,
- infoType,
- infoData);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ OSType infoType;
+ void * infoData;
+ if (!PyArg_ParseTuple(_args, "lO&w",
+ &inRefNum,
+ PyMac_GetOSType, &infoType,
+ &infoData))
+ return NULL;
+ _err = SPBSetDeviceInfo(inRefNum,
+ infoType,
+ infoData);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Snd_SPBMillisecondsToBytes(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- long milliseconds;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBMillisecondsToBytes(inRefNum,
- &milliseconds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- milliseconds);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ long milliseconds;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBMillisecondsToBytes(inRefNum,
+ &milliseconds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ milliseconds);
+ return _res;
}
static PyObject *Snd_SPBBytesToMilliseconds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- long inRefNum;
- long byteCount;
- if (!PyArg_ParseTuple(_args, "l",
- &inRefNum))
- return NULL;
- _err = SPBBytesToMilliseconds(inRefNum,
- &byteCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- byteCount);
- return _res;
+ PyObject *_res = NULL;
+ OSErr _err;
+ long inRefNum;
+ long byteCount;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inRefNum))
+ return NULL;
+ _err = SPBBytesToMilliseconds(inRefNum,
+ &byteCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ byteCount);
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Snd_methods[] = {
#ifndef __LP64__
- {"SPB", (PyCFunction)Snd_SPB, 1,
- PyDoc_STR(NULL)},
- {"SysBeep", (PyCFunction)Snd_SysBeep, 1,
- PyDoc_STR("(short duration) -> None")},
- {"SndNewChannel", (PyCFunction)Snd_SndNewChannel, 1,
- PyDoc_STR("(short synth, long init, PyObject* userRoutine) -> (SndChannelPtr chan)")},
- {"SndSoundManagerVersion", (PyCFunction)Snd_SndSoundManagerVersion, 1,
- PyDoc_STR("() -> (NumVersion _rv)")},
- {"SndManagerStatus", (PyCFunction)Snd_SndManagerStatus, 1,
- PyDoc_STR("(short theLength) -> (SMStatus theStatus)")},
- {"SndGetSysBeepState", (PyCFunction)Snd_SndGetSysBeepState, 1,
- PyDoc_STR("() -> (short sysBeepState)")},
- {"SndSetSysBeepState", (PyCFunction)Snd_SndSetSysBeepState, 1,
- PyDoc_STR("(short sysBeepState) -> None")},
- {"GetSysBeepVolume", (PyCFunction)Snd_GetSysBeepVolume, 1,
- PyDoc_STR("() -> (long level)")},
- {"SetSysBeepVolume", (PyCFunction)Snd_SetSysBeepVolume, 1,
- PyDoc_STR("(long level) -> None")},
- {"GetDefaultOutputVolume", (PyCFunction)Snd_GetDefaultOutputVolume, 1,
- PyDoc_STR("() -> (long level)")},
- {"SetDefaultOutputVolume", (PyCFunction)Snd_SetDefaultOutputVolume, 1,
- PyDoc_STR("(long level) -> None")},
- {"GetSoundHeaderOffset", (PyCFunction)Snd_GetSoundHeaderOffset, 1,
- PyDoc_STR("(SndListHandle sndHandle) -> (long offset)")},
- {"GetCompressionInfo", (PyCFunction)Snd_GetCompressionInfo, 1,
- PyDoc_STR("(short compressionID, OSType format, short numChannels, short sampleSize) -> (CompressionInfo cp)")},
- {"SetSoundPreference", (PyCFunction)Snd_SetSoundPreference, 1,
- PyDoc_STR("(OSType theType, Handle settings) -> (Str255 name)")},
- {"GetSoundPreference", (PyCFunction)Snd_GetSoundPreference, 1,
- PyDoc_STR("(OSType theType, Handle settings) -> (Str255 name)")},
- {"GetCompressionName", (PyCFunction)Snd_GetCompressionName, 1,
- PyDoc_STR("(OSType compressionType) -> (Str255 compressionName)")},
- {"SPBVersion", (PyCFunction)Snd_SPBVersion, 1,
- PyDoc_STR("() -> (NumVersion _rv)")},
- {"SndRecord", (PyCFunction)Snd_SndRecord, 1,
- PyDoc_STR("(Point corner, OSType quality) -> (SndListHandle sndHandle)")},
- {"SPBSignInDevice", (PyCFunction)Snd_SPBSignInDevice, 1,
- PyDoc_STR("(short deviceRefNum, Str255 deviceName) -> None")},
- {"SPBSignOutDevice", (PyCFunction)Snd_SPBSignOutDevice, 1,
- PyDoc_STR("(short deviceRefNum) -> None")},
- {"SPBGetIndexedDevice", (PyCFunction)Snd_SPBGetIndexedDevice, 1,
- PyDoc_STR("(short count) -> (Str255 deviceName, Handle deviceIconHandle)")},
- {"SPBOpenDevice", (PyCFunction)Snd_SPBOpenDevice, 1,
- PyDoc_STR("(Str255 deviceName, short permission) -> (long inRefNum)")},
- {"SPBCloseDevice", (PyCFunction)Snd_SPBCloseDevice, 1,
- PyDoc_STR("(long inRefNum) -> None")},
- {"SPBRecord", (PyCFunction)Snd_SPBRecord, 1,
- PyDoc_STR("(SPBPtr inParamPtr, Boolean asynchFlag) -> None")},
- {"SPBPauseRecording", (PyCFunction)Snd_SPBPauseRecording, 1,
- PyDoc_STR("(long inRefNum) -> None")},
- {"SPBResumeRecording", (PyCFunction)Snd_SPBResumeRecording, 1,
- PyDoc_STR("(long inRefNum) -> None")},
- {"SPBStopRecording", (PyCFunction)Snd_SPBStopRecording, 1,
- PyDoc_STR("(long inRefNum) -> None")},
- {"SPBGetRecordingStatus", (PyCFunction)Snd_SPBGetRecordingStatus, 1,
- PyDoc_STR("(long inRefNum) -> (short recordingStatus, short meterLevel, unsigned long totalSamplesToRecord, unsigned long numberOfSamplesRecorded, unsigned long totalMsecsToRecord, unsigned long numberOfMsecsRecorded)")},
- {"SPBGetDeviceInfo", (PyCFunction)Snd_SPBGetDeviceInfo, 1,
- PyDoc_STR("(long inRefNum, OSType infoType, void * infoData) -> None")},
- {"SPBSetDeviceInfo", (PyCFunction)Snd_SPBSetDeviceInfo, 1,
- PyDoc_STR("(long inRefNum, OSType infoType, void * infoData) -> None")},
- {"SPBMillisecondsToBytes", (PyCFunction)Snd_SPBMillisecondsToBytes, 1,
- PyDoc_STR("(long inRefNum) -> (long milliseconds)")},
- {"SPBBytesToMilliseconds", (PyCFunction)Snd_SPBBytesToMilliseconds, 1,
- PyDoc_STR("(long inRefNum) -> (long byteCount)")},
+ {"SPB", (PyCFunction)Snd_SPB, 1,
+ PyDoc_STR(NULL)},
+ {"SysBeep", (PyCFunction)Snd_SysBeep, 1,
+ PyDoc_STR("(short duration) -> None")},
+ {"SndNewChannel", (PyCFunction)Snd_SndNewChannel, 1,
+ PyDoc_STR("(short synth, long init, PyObject* userRoutine) -> (SndChannelPtr chan)")},
+ {"SndSoundManagerVersion", (PyCFunction)Snd_SndSoundManagerVersion, 1,
+ PyDoc_STR("() -> (NumVersion _rv)")},
+ {"SndManagerStatus", (PyCFunction)Snd_SndManagerStatus, 1,
+ PyDoc_STR("(short theLength) -> (SMStatus theStatus)")},
+ {"SndGetSysBeepState", (PyCFunction)Snd_SndGetSysBeepState, 1,
+ PyDoc_STR("() -> (short sysBeepState)")},
+ {"SndSetSysBeepState", (PyCFunction)Snd_SndSetSysBeepState, 1,
+ PyDoc_STR("(short sysBeepState) -> None")},
+ {"GetSysBeepVolume", (PyCFunction)Snd_GetSysBeepVolume, 1,
+ PyDoc_STR("() -> (long level)")},
+ {"SetSysBeepVolume", (PyCFunction)Snd_SetSysBeepVolume, 1,
+ PyDoc_STR("(long level) -> None")},
+ {"GetDefaultOutputVolume", (PyCFunction)Snd_GetDefaultOutputVolume, 1,
+ PyDoc_STR("() -> (long level)")},
+ {"SetDefaultOutputVolume", (PyCFunction)Snd_SetDefaultOutputVolume, 1,
+ PyDoc_STR("(long level) -> None")},
+ {"GetSoundHeaderOffset", (PyCFunction)Snd_GetSoundHeaderOffset, 1,
+ PyDoc_STR("(SndListHandle sndHandle) -> (long offset)")},
+ {"GetCompressionInfo", (PyCFunction)Snd_GetCompressionInfo, 1,
+ PyDoc_STR("(short compressionID, OSType format, short numChannels, short sampleSize) -> (CompressionInfo cp)")},
+ {"SetSoundPreference", (PyCFunction)Snd_SetSoundPreference, 1,
+ PyDoc_STR("(OSType theType, Handle settings) -> (Str255 name)")},
+ {"GetSoundPreference", (PyCFunction)Snd_GetSoundPreference, 1,
+ PyDoc_STR("(OSType theType, Handle settings) -> (Str255 name)")},
+ {"GetCompressionName", (PyCFunction)Snd_GetCompressionName, 1,
+ PyDoc_STR("(OSType compressionType) -> (Str255 compressionName)")},
+ {"SPBVersion", (PyCFunction)Snd_SPBVersion, 1,
+ PyDoc_STR("() -> (NumVersion _rv)")},
+ {"SndRecord", (PyCFunction)Snd_SndRecord, 1,
+ PyDoc_STR("(Point corner, OSType quality) -> (SndListHandle sndHandle)")},
+ {"SPBSignInDevice", (PyCFunction)Snd_SPBSignInDevice, 1,
+ PyDoc_STR("(short deviceRefNum, Str255 deviceName) -> None")},
+ {"SPBSignOutDevice", (PyCFunction)Snd_SPBSignOutDevice, 1,
+ PyDoc_STR("(short deviceRefNum) -> None")},
+ {"SPBGetIndexedDevice", (PyCFunction)Snd_SPBGetIndexedDevice, 1,
+ PyDoc_STR("(short count) -> (Str255 deviceName, Handle deviceIconHandle)")},
+ {"SPBOpenDevice", (PyCFunction)Snd_SPBOpenDevice, 1,
+ PyDoc_STR("(Str255 deviceName, short permission) -> (long inRefNum)")},
+ {"SPBCloseDevice", (PyCFunction)Snd_SPBCloseDevice, 1,
+ PyDoc_STR("(long inRefNum) -> None")},
+ {"SPBRecord", (PyCFunction)Snd_SPBRecord, 1,
+ PyDoc_STR("(SPBPtr inParamPtr, Boolean asynchFlag) -> None")},
+ {"SPBPauseRecording", (PyCFunction)Snd_SPBPauseRecording, 1,
+ PyDoc_STR("(long inRefNum) -> None")},
+ {"SPBResumeRecording", (PyCFunction)Snd_SPBResumeRecording, 1,
+ PyDoc_STR("(long inRefNum) -> None")},
+ {"SPBStopRecording", (PyCFunction)Snd_SPBStopRecording, 1,
+ PyDoc_STR("(long inRefNum) -> None")},
+ {"SPBGetRecordingStatus", (PyCFunction)Snd_SPBGetRecordingStatus, 1,
+ PyDoc_STR("(long inRefNum) -> (short recordingStatus, short meterLevel, unsigned long totalSamplesToRecord, unsigned long numberOfSamplesRecorded, unsigned long totalMsecsToRecord, unsigned long numberOfMsecsRecorded)")},
+ {"SPBGetDeviceInfo", (PyCFunction)Snd_SPBGetDeviceInfo, 1,
+ PyDoc_STR("(long inRefNum, OSType infoType, void * infoData) -> None")},
+ {"SPBSetDeviceInfo", (PyCFunction)Snd_SPBSetDeviceInfo, 1,
+ PyDoc_STR("(long inRefNum, OSType infoType, void * infoData) -> None")},
+ {"SPBMillisecondsToBytes", (PyCFunction)Snd_SPBMillisecondsToBytes, 1,
+ PyDoc_STR("(long inRefNum) -> (long milliseconds)")},
+ {"SPBBytesToMilliseconds", (PyCFunction)Snd_SPBBytesToMilliseconds, 1,
+ PyDoc_STR("(long inRefNum) -> (long byteCount)")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -1061,62 +1061,62 @@ static PyMethodDef Snd_methods[] = {
static int
SndCh_CallCallBack(void *arg)
{
- SndChannelObject *p = (SndChannelObject *)arg;
- PyObject *args;
- PyObject *res;
- args = Py_BuildValue("(O(hhl))",
- p, p->ob_cmd.cmd, p->ob_cmd.param1, p->ob_cmd.param2);
- res = PyEval_CallObject(p->ob_callback, args);
- Py_DECREF(args);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ SndChannelObject *p = (SndChannelObject *)arg;
+ PyObject *args;
+ PyObject *res;
+ args = Py_BuildValue("(O(hhl))",
+ p, p->ob_cmd.cmd, p->ob_cmd.param1, p->ob_cmd.param2);
+ res = PyEval_CallObject(p->ob_callback, args);
+ Py_DECREF(args);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
/* Routine passed to NewSndChannel -- schedule a call to SndCh_CallCallBack */
static pascal void
SndCh_UserRoutine(SndChannelPtr chan, SndCommand *cmd)
{
- SndChannelObject *p = (SndChannelObject *)(chan->userInfo);
- if (p->ob_callback != NULL) {
- long A5 = SetA5(p->ob_A5);
- p->ob_cmd = *cmd;
- Py_AddPendingCall(SndCh_CallCallBack, (void *)p);
- SetA5(A5);
- }
+ SndChannelObject *p = (SndChannelObject *)(chan->userInfo);
+ if (p->ob_callback != NULL) {
+ long A5 = SetA5(p->ob_A5);
+ p->ob_cmd = *cmd;
+ Py_AddPendingCall(SndCh_CallCallBack, (void *)p);
+ SetA5(A5);
+ }
}
/* SPB callbacks - Schedule callbacks to Python */
static int
SPB_CallCallBack(void *arg)
{
- SPBObject *p = (SPBObject *)arg;
- PyObject *args;
- PyObject *res;
-
- if ( p->ob_thiscallback == 0 ) return 0;
- args = Py_BuildValue("(O)", p);
- res = PyEval_CallObject(p->ob_thiscallback, args);
- p->ob_thiscallback = 0;
- Py_DECREF(args);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ SPBObject *p = (SPBObject *)arg;
+ PyObject *args;
+ PyObject *res;
+
+ if ( p->ob_thiscallback == 0 ) return 0;
+ args = Py_BuildValue("(O)", p);
+ res = PyEval_CallObject(p->ob_thiscallback, args);
+ p->ob_thiscallback = 0;
+ Py_DECREF(args);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static pascal void
SPB_completion(SPBPtr my_spb)
{
- SPBObject *p = (SPBObject *)(my_spb->userLong);
-
- if (p && p->ob_completion) {
- long A5 = SetA5(p->ob_A5);
- p->ob_thiscallback = p->ob_completion; /* Hope we cannot get two at the same time */
- Py_AddPendingCall(SPB_CallCallBack, (void *)p);
- SetA5(A5);
- }
+ SPBObject *p = (SPBObject *)(my_spb->userLong);
+
+ if (p && p->ob_completion) {
+ long A5 = SetA5(p->ob_A5);
+ p->ob_thiscallback = p->ob_completion; /* Hope we cannot get two at the same time */
+ Py_AddPendingCall(SPB_CallCallBack, (void *)p);
+ SetA5(A5);
+ }
}
#endif /* __LP64__ */
@@ -1124,38 +1124,38 @@ SPB_completion(SPBPtr my_spb)
void init_Snd(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
#endif /* __LP64__ */
- m = Py_InitModule("_Snd", Snd_methods);
+ m = Py_InitModule("_Snd", Snd_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Snd_Error = PyMac_GetOSErrException();
- if (Snd_Error == NULL ||
- PyDict_SetItemString(d, "Error", Snd_Error) != 0)
- return;
- SndChannel_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&SndChannel_Type) < 0) return;
- Py_INCREF(&SndChannel_Type);
- PyModule_AddObject(m, "SndChannel", (PyObject *)&SndChannel_Type);
- /* Backward-compatible name */
- Py_INCREF(&SndChannel_Type);
- PyModule_AddObject(m, "SndChannelType", (PyObject *)&SndChannel_Type);
- SPB_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&SPB_Type) < 0) return;
- Py_INCREF(&SPB_Type);
+ d = PyModule_GetDict(m);
+ Snd_Error = PyMac_GetOSErrException();
+ if (Snd_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Snd_Error) != 0)
+ return;
+ SndChannel_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&SndChannel_Type) < 0) return;
+ Py_INCREF(&SndChannel_Type);
+ PyModule_AddObject(m, "SndChannel", (PyObject *)&SndChannel_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&SndChannel_Type);
+ PyModule_AddObject(m, "SndChannelType", (PyObject *)&SndChannel_Type);
+ SPB_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&SPB_Type) < 0) return;
+ Py_INCREF(&SPB_Type);
#if 0
- PyModule_AddObject(m, "SPB", (PyObject *)&SPB_Type);
+ PyModule_AddObject(m, "SPB", (PyObject *)&SPB_Type);
#endif
- /* Backward-compatible name */
- Py_INCREF(&SPB_Type);
- PyModule_AddObject(m, "SPBType", (PyObject *)&SPB_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&SPB_Type);
+ PyModule_AddObject(m, "SPBType", (PyObject *)&SPB_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/te/_TEmodule.c b/Mac/Modules/te/_TEmodule.c
index f182688..a998fc8 100644
--- a/Mac/Modules/te/_TEmodule.c
+++ b/Mac/Modules/te/_TEmodule.c
@@ -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)
@@ -36,21 +36,21 @@ static PyObject *
TextStyle_New(TextStylePtr itself)
{
- return Py_BuildValue("lllO&", (long)itself->tsFont, (long)itself->tsFace, (long)itself->tsSize, QdRGB_New,
- &itself->tsColor);
+ return Py_BuildValue("lllO&", (long)itself->tsFont, (long)itself->tsFace, (long)itself->tsSize, QdRGB_New,
+ &itself->tsColor);
}
static int
TextStyle_Convert(PyObject *v, TextStylePtr p_itself)
{
- long font, face, size;
+ long font, face, size;
- if( !PyArg_ParseTuple(v, "lllO&", &font, &face, &size, QdRGB_Convert, &p_itself->tsColor) )
- return 0;
- p_itself->tsFont = (short)font;
- p_itself->tsFace = (Style)face;
- p_itself->tsSize = (short)size;
- return 1;
+ if( !PyArg_ParseTuple(v, "lllO&", &font, &face, &size, QdRGB_Convert, &p_itself->tsColor) )
+ return 0;
+ p_itself->tsFont = (short)font;
+ p_itself->tsFace = (Style)face;
+ p_itself->tsSize = (short)size;
+ return 1;
}
static PyObject *TE_Error;
@@ -62,917 +62,917 @@ PyTypeObject TE_Type;
#define TEObj_Check(x) ((x)->ob_type == &TE_Type || PyObject_TypeCheck((x), &TE_Type))
typedef struct TEObject {
- PyObject_HEAD
- TEHandle ob_itself;
+ PyObject_HEAD
+ TEHandle ob_itself;
} TEObject;
PyObject *TEObj_New(TEHandle itself)
{
- TEObject *it;
- if (itself == NULL) {
- PyErr_SetString(TE_Error,"Cannot create null TE");
- return NULL;
- }
- it = PyObject_NEW(TEObject, &TE_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- return (PyObject *)it;
+ TEObject *it;
+ if (itself == NULL) {
+ PyErr_SetString(TE_Error,"Cannot create null TE");
+ return NULL;
+ }
+ it = PyObject_NEW(TEObject, &TE_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ return (PyObject *)it;
}
int TEObj_Convert(PyObject *v, TEHandle *p_itself)
{
- if (!TEObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "TE required");
- return 0;
- }
- *p_itself = ((TEObject *)v)->ob_itself;
- return 1;
+ if (!TEObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "TE required");
+ return 0;
+ }
+ *p_itself = ((TEObject *)v)->ob_itself;
+ return 1;
}
static void TEObj_dealloc(TEObject *self)
{
- TEDispose(self->ob_itself);
- self->ob_type->tp_free((PyObject *)self);
+ TEDispose(self->ob_itself);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *TEObj_TESetText(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *text__in__;
- long text__len__;
- int text__in_len__;
+ PyObject *_res = NULL;
+ char *text__in__;
+ long text__len__;
+ int text__in_len__;
#ifndef TESetText
- PyMac_PRECHECK(TESetText);
+ PyMac_PRECHECK(TESetText);
#endif
- if (!PyArg_ParseTuple(_args, "s#",
- &text__in__, &text__in_len__))
- return NULL;
- text__len__ = text__in_len__;
- TESetText(text__in__, text__len__,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#",
+ &text__in__, &text__in_len__))
+ return NULL;
+ text__len__ = text__in_len__;
+ TESetText(text__in__, text__len__,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEGetText(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CharsHandle _rv;
+ PyObject *_res = NULL;
+ CharsHandle _rv;
#ifndef TEGetText
- PyMac_PRECHECK(TEGetText);
+ PyMac_PRECHECK(TEGetText);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TEGetText(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TEGetText(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TEObj_TEIdle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TEIdle
- PyMac_PRECHECK(TEIdle);
+ PyMac_PRECHECK(TEIdle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TEIdle(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TEIdle(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TESetSelect(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long selStart;
- long selEnd;
+ PyObject *_res = NULL;
+ long selStart;
+ long selEnd;
#ifndef TESetSelect
- PyMac_PRECHECK(TESetSelect);
+ PyMac_PRECHECK(TESetSelect);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &selStart,
- &selEnd))
- return NULL;
- TESetSelect(selStart,
- selEnd,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &selStart,
+ &selEnd))
+ return NULL;
+ TESetSelect(selStart,
+ selEnd,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEActivate(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TEActivate
- PyMac_PRECHECK(TEActivate);
+ PyMac_PRECHECK(TEActivate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TEActivate(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TEActivate(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEDeactivate(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TEDeactivate
- PyMac_PRECHECK(TEDeactivate);
+ PyMac_PRECHECK(TEDeactivate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TEDeactivate(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TEDeactivate(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEKey(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CharParameter key;
+ PyObject *_res = NULL;
+ CharParameter key;
#ifndef TEKey
- PyMac_PRECHECK(TEKey);
+ PyMac_PRECHECK(TEKey);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &key))
- return NULL;
- TEKey(key,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &key))
+ return NULL;
+ TEKey(key,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TECut(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TECut
- PyMac_PRECHECK(TECut);
+ PyMac_PRECHECK(TECut);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TECut(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TECut(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TECopy(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TECopy
- PyMac_PRECHECK(TECopy);
+ PyMac_PRECHECK(TECopy);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TECopy(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TECopy(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEPaste(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TEPaste
- PyMac_PRECHECK(TEPaste);
+ PyMac_PRECHECK(TEPaste);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TEPaste(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TEPaste(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEDelete(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TEDelete
- PyMac_PRECHECK(TEDelete);
+ PyMac_PRECHECK(TEDelete);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TEDelete(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TEDelete(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEInsert(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *text__in__;
- long text__len__;
- int text__in_len__;
+ PyObject *_res = NULL;
+ char *text__in__;
+ long text__len__;
+ int text__in_len__;
#ifndef TEInsert
- PyMac_PRECHECK(TEInsert);
+ PyMac_PRECHECK(TEInsert);
#endif
- if (!PyArg_ParseTuple(_args, "s#",
- &text__in__, &text__in_len__))
- return NULL;
- text__len__ = text__in_len__;
- TEInsert(text__in__, text__len__,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#",
+ &text__in__, &text__in_len__))
+ return NULL;
+ text__len__ = text__in_len__;
+ TEInsert(text__in__, text__len__,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TESetAlignment(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short just;
+ PyObject *_res = NULL;
+ short just;
#ifndef TESetAlignment
- PyMac_PRECHECK(TESetAlignment);
+ PyMac_PRECHECK(TESetAlignment);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &just))
- return NULL;
- TESetAlignment(just,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &just))
+ return NULL;
+ TESetAlignment(just,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEUpdate(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rUpdate;
+ PyObject *_res = NULL;
+ Rect rUpdate;
#ifndef TEUpdate
- PyMac_PRECHECK(TEUpdate);
+ PyMac_PRECHECK(TEUpdate);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &rUpdate))
- return NULL;
- TEUpdate(&rUpdate,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &rUpdate))
+ return NULL;
+ TEUpdate(&rUpdate,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEScroll(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ short dh;
+ short dv;
#ifndef TEScroll
- PyMac_PRECHECK(TEScroll);
+ PyMac_PRECHECK(TEScroll);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &dh,
- &dv))
- return NULL;
- TEScroll(dh,
- dv,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &dh,
+ &dv))
+ return NULL;
+ TEScroll(dh,
+ dv,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TESelView(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TESelView
- PyMac_PRECHECK(TESelView);
+ PyMac_PRECHECK(TESelView);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TESelView(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TESelView(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEPinScroll(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short dh;
- short dv;
+ PyObject *_res = NULL;
+ short dh;
+ short dv;
#ifndef TEPinScroll
- PyMac_PRECHECK(TEPinScroll);
+ PyMac_PRECHECK(TEPinScroll);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &dh,
- &dv))
- return NULL;
- TEPinScroll(dh,
- dv,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &dh,
+ &dv))
+ return NULL;
+ TEPinScroll(dh,
+ dv,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEAutoView(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean fAuto;
+ PyObject *_res = NULL;
+ Boolean fAuto;
#ifndef TEAutoView
- PyMac_PRECHECK(TEAutoView);
+ PyMac_PRECHECK(TEAutoView);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &fAuto))
- return NULL;
- TEAutoView(fAuto,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &fAuto))
+ return NULL;
+ TEAutoView(fAuto,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TECalText(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TECalText
- PyMac_PRECHECK(TECalText);
+ PyMac_PRECHECK(TECalText);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TECalText(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TECalText(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEGetOffset(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- Point pt;
+ PyObject *_res = NULL;
+ short _rv;
+ Point pt;
#ifndef TEGetOffset
- PyMac_PRECHECK(TEGetOffset);
+ PyMac_PRECHECK(TEGetOffset);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &pt))
- return NULL;
- _rv = TEGetOffset(pt,
- _self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &pt))
+ return NULL;
+ _rv = TEGetOffset(pt,
+ _self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *TEObj_TEGetPoint(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point _rv;
- short offset;
+ PyObject *_res = NULL;
+ Point _rv;
+ short offset;
#ifndef TEGetPoint
- PyMac_PRECHECK(TEGetPoint);
+ PyMac_PRECHECK(TEGetPoint);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &offset))
- return NULL;
- _rv = TEGetPoint(offset,
- _self->ob_itself);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &offset))
+ return NULL;
+ _rv = TEGetPoint(offset,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, _rv);
+ return _res;
}
static PyObject *TEObj_TEClick(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point pt;
- Boolean fExtend;
+ PyObject *_res = NULL;
+ Point pt;
+ Boolean fExtend;
#ifndef TEClick
- PyMac_PRECHECK(TEClick);
+ PyMac_PRECHECK(TEClick);
#endif
- if (!PyArg_ParseTuple(_args, "O&b",
- PyMac_GetPoint, &pt,
- &fExtend))
- return NULL;
- TEClick(pt,
- fExtend,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&b",
+ PyMac_GetPoint, &pt,
+ &fExtend))
+ return NULL;
+ TEClick(pt,
+ fExtend,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TESetStyleHandle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TEStyleHandle theHandle;
+ PyObject *_res = NULL;
+ TEStyleHandle theHandle;
#ifndef TESetStyleHandle
- PyMac_PRECHECK(TESetStyleHandle);
+ PyMac_PRECHECK(TESetStyleHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &theHandle))
- return NULL;
- TESetStyleHandle(theHandle,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &theHandle))
+ return NULL;
+ TESetStyleHandle(theHandle,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEGetStyleHandle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TEStyleHandle _rv;
+ PyObject *_res = NULL;
+ TEStyleHandle _rv;
#ifndef TEGetStyleHandle
- PyMac_PRECHECK(TEGetStyleHandle);
+ PyMac_PRECHECK(TEGetStyleHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TEGetStyleHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TEGetStyleHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TEObj_TEGetStyle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short offset;
- TextStyle theStyle;
- short lineHeight;
- short fontAscent;
+ PyObject *_res = NULL;
+ short offset;
+ TextStyle theStyle;
+ short lineHeight;
+ short fontAscent;
#ifndef TEGetStyle
- PyMac_PRECHECK(TEGetStyle);
+ PyMac_PRECHECK(TEGetStyle);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &offset))
- return NULL;
- TEGetStyle(offset,
- &theStyle,
- &lineHeight,
- &fontAscent,
- _self->ob_itself);
- _res = Py_BuildValue("O&hh",
- TextStyle_New, &theStyle,
- lineHeight,
- fontAscent);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &offset))
+ return NULL;
+ TEGetStyle(offset,
+ &theStyle,
+ &lineHeight,
+ &fontAscent,
+ _self->ob_itself);
+ _res = Py_BuildValue("O&hh",
+ TextStyle_New, &theStyle,
+ lineHeight,
+ fontAscent);
+ return _res;
}
static PyObject *TEObj_TEStylePaste(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef TEStylePaste
- PyMac_PRECHECK(TEStylePaste);
+ PyMac_PRECHECK(TEStylePaste);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- TEStylePaste(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ TEStylePaste(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TESetStyle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short mode;
- TextStyle newStyle;
- Boolean fRedraw;
+ PyObject *_res = NULL;
+ short mode;
+ TextStyle newStyle;
+ Boolean fRedraw;
#ifndef TESetStyle
- PyMac_PRECHECK(TESetStyle);
+ PyMac_PRECHECK(TESetStyle);
#endif
- if (!PyArg_ParseTuple(_args, "hO&b",
- &mode,
- TextStyle_Convert, &newStyle,
- &fRedraw))
- return NULL;
- TESetStyle(mode,
- &newStyle,
- fRedraw,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&b",
+ &mode,
+ TextStyle_Convert, &newStyle,
+ &fRedraw))
+ return NULL;
+ TESetStyle(mode,
+ &newStyle,
+ fRedraw,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEReplaceStyle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short mode;
- TextStyle oldStyle;
- TextStyle newStyle;
- Boolean fRedraw;
+ PyObject *_res = NULL;
+ short mode;
+ TextStyle oldStyle;
+ TextStyle newStyle;
+ Boolean fRedraw;
#ifndef TEReplaceStyle
- PyMac_PRECHECK(TEReplaceStyle);
+ PyMac_PRECHECK(TEReplaceStyle);
#endif
- if (!PyArg_ParseTuple(_args, "hO&O&b",
- &mode,
- TextStyle_Convert, &oldStyle,
- TextStyle_Convert, &newStyle,
- &fRedraw))
- return NULL;
- TEReplaceStyle(mode,
- &oldStyle,
- &newStyle,
- fRedraw,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&O&b",
+ &mode,
+ TextStyle_Convert, &oldStyle,
+ TextStyle_Convert, &newStyle,
+ &fRedraw))
+ return NULL;
+ TEReplaceStyle(mode,
+ &oldStyle,
+ &newStyle,
+ fRedraw,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEGetStyleScrapHandle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- StScrpHandle _rv;
+ PyObject *_res = NULL;
+ StScrpHandle _rv;
#ifndef TEGetStyleScrapHandle
- PyMac_PRECHECK(TEGetStyleScrapHandle);
+ PyMac_PRECHECK(TEGetStyleScrapHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TEGetStyleScrapHandle(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TEGetStyleScrapHandle(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TEObj_TEStyleInsert(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *text__in__;
- long text__len__;
- int text__in_len__;
- StScrpHandle hST;
+ PyObject *_res = NULL;
+ char *text__in__;
+ long text__len__;
+ int text__in_len__;
+ StScrpHandle hST;
#ifndef TEStyleInsert
- PyMac_PRECHECK(TEStyleInsert);
+ PyMac_PRECHECK(TEStyleInsert);
#endif
- if (!PyArg_ParseTuple(_args, "s#O&",
- &text__in__, &text__in_len__,
- ResObj_Convert, &hST))
- return NULL;
- text__len__ = text__in_len__;
- TEStyleInsert(text__in__, text__len__,
- hST,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#O&",
+ &text__in__, &text__in_len__,
+ ResObj_Convert, &hST))
+ return NULL;
+ text__len__ = text__in_len__;
+ TEStyleInsert(text__in__, text__len__,
+ hST,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TEGetHeight(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- long endLine;
- long startLine;
+ PyObject *_res = NULL;
+ long _rv;
+ long endLine;
+ long startLine;
#ifndef TEGetHeight
- PyMac_PRECHECK(TEGetHeight);
+ PyMac_PRECHECK(TEGetHeight);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &endLine,
- &startLine))
- return NULL;
- _rv = TEGetHeight(endLine,
- startLine,
- _self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &endLine,
+ &startLine))
+ return NULL;
+ _rv = TEGetHeight(endLine,
+ startLine,
+ _self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TEObj_TEContinuousStyle(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- short mode;
- TextStyle aStyle;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ short mode;
+ TextStyle aStyle;
#ifndef TEContinuousStyle
- PyMac_PRECHECK(TEContinuousStyle);
+ PyMac_PRECHECK(TEContinuousStyle);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &mode,
- TextStyle_Convert, &aStyle))
- return NULL;
- _rv = TEContinuousStyle(&mode,
- &aStyle,
- _self->ob_itself);
- _res = Py_BuildValue("bhO&",
- _rv,
- mode,
- TextStyle_New, &aStyle);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &mode,
+ TextStyle_Convert, &aStyle))
+ return NULL;
+ _rv = TEContinuousStyle(&mode,
+ &aStyle,
+ _self->ob_itself);
+ _res = Py_BuildValue("bhO&",
+ _rv,
+ mode,
+ TextStyle_New, &aStyle);
+ return _res;
}
static PyObject *TEObj_TEUseStyleScrap(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long rangeStart;
- long rangeEnd;
- StScrpHandle newStyles;
- Boolean fRedraw;
+ PyObject *_res = NULL;
+ long rangeStart;
+ long rangeEnd;
+ StScrpHandle newStyles;
+ Boolean fRedraw;
#ifndef TEUseStyleScrap
- PyMac_PRECHECK(TEUseStyleScrap);
+ PyMac_PRECHECK(TEUseStyleScrap);
#endif
- if (!PyArg_ParseTuple(_args, "llO&b",
- &rangeStart,
- &rangeEnd,
- ResObj_Convert, &newStyles,
- &fRedraw))
- return NULL;
- TEUseStyleScrap(rangeStart,
- rangeEnd,
- newStyles,
- fRedraw,
- _self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "llO&b",
+ &rangeStart,
+ &rangeEnd,
+ ResObj_Convert, &newStyles,
+ &fRedraw))
+ return NULL;
+ TEUseStyleScrap(rangeStart,
+ rangeEnd,
+ newStyles,
+ fRedraw,
+ _self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_TENumStyles(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- long rangeStart;
- long rangeEnd;
+ PyObject *_res = NULL;
+ long _rv;
+ long rangeStart;
+ long rangeEnd;
#ifndef TENumStyles
- PyMac_PRECHECK(TENumStyles);
+ PyMac_PRECHECK(TENumStyles);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &rangeStart,
- &rangeEnd))
- return NULL;
- _rv = TENumStyles(rangeStart,
- rangeEnd,
- _self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &rangeStart,
+ &rangeEnd))
+ return NULL;
+ _rv = TENumStyles(rangeStart,
+ rangeEnd,
+ _self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TEObj_TEFeatureFlag(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- short feature;
- short action;
+ PyObject *_res = NULL;
+ short _rv;
+ short feature;
+ short action;
#ifndef TEFeatureFlag
- PyMac_PRECHECK(TEFeatureFlag);
+ PyMac_PRECHECK(TEFeatureFlag);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &feature,
- &action))
- return NULL;
- _rv = TEFeatureFlag(feature,
- action,
- _self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &feature,
+ &action))
+ return NULL;
+ _rv = TEFeatureFlag(feature,
+ action,
+ _self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *TEObj_TEGetHiliteRgn(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
- RgnHandle region;
+ PyObject *_res = NULL;
+ OSErr _err;
+ RgnHandle region;
#ifndef TEGetHiliteRgn
- PyMac_PRECHECK(TEGetHiliteRgn);
+ PyMac_PRECHECK(TEGetHiliteRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- _err = TEGetHiliteRgn(region,
- _self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ _err = TEGetHiliteRgn(region,
+ _self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TEObj_as_Resource(TEObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef as_Resource
- PyMac_PRECHECK(as_Resource);
+ PyMac_PRECHECK(as_Resource);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = as_Resource(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = as_Resource(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyMethodDef TEObj_methods[] = {
- {"TESetText", (PyCFunction)TEObj_TESetText, 1,
- PyDoc_STR("(Buffer text) -> None")},
- {"TEGetText", (PyCFunction)TEObj_TEGetText, 1,
- PyDoc_STR("() -> (CharsHandle _rv)")},
- {"TEIdle", (PyCFunction)TEObj_TEIdle, 1,
- PyDoc_STR("() -> None")},
- {"TESetSelect", (PyCFunction)TEObj_TESetSelect, 1,
- PyDoc_STR("(long selStart, long selEnd) -> None")},
- {"TEActivate", (PyCFunction)TEObj_TEActivate, 1,
- PyDoc_STR("() -> None")},
- {"TEDeactivate", (PyCFunction)TEObj_TEDeactivate, 1,
- PyDoc_STR("() -> None")},
- {"TEKey", (PyCFunction)TEObj_TEKey, 1,
- PyDoc_STR("(CharParameter key) -> None")},
- {"TECut", (PyCFunction)TEObj_TECut, 1,
- PyDoc_STR("() -> None")},
- {"TECopy", (PyCFunction)TEObj_TECopy, 1,
- PyDoc_STR("() -> None")},
- {"TEPaste", (PyCFunction)TEObj_TEPaste, 1,
- PyDoc_STR("() -> None")},
- {"TEDelete", (PyCFunction)TEObj_TEDelete, 1,
- PyDoc_STR("() -> None")},
- {"TEInsert", (PyCFunction)TEObj_TEInsert, 1,
- PyDoc_STR("(Buffer text) -> None")},
- {"TESetAlignment", (PyCFunction)TEObj_TESetAlignment, 1,
- PyDoc_STR("(short just) -> None")},
- {"TEUpdate", (PyCFunction)TEObj_TEUpdate, 1,
- PyDoc_STR("(Rect rUpdate) -> None")},
- {"TEScroll", (PyCFunction)TEObj_TEScroll, 1,
- PyDoc_STR("(short dh, short dv) -> None")},
- {"TESelView", (PyCFunction)TEObj_TESelView, 1,
- PyDoc_STR("() -> None")},
- {"TEPinScroll", (PyCFunction)TEObj_TEPinScroll, 1,
- PyDoc_STR("(short dh, short dv) -> None")},
- {"TEAutoView", (PyCFunction)TEObj_TEAutoView, 1,
- PyDoc_STR("(Boolean fAuto) -> None")},
- {"TECalText", (PyCFunction)TEObj_TECalText, 1,
- PyDoc_STR("() -> None")},
- {"TEGetOffset", (PyCFunction)TEObj_TEGetOffset, 1,
- PyDoc_STR("(Point pt) -> (short _rv)")},
- {"TEGetPoint", (PyCFunction)TEObj_TEGetPoint, 1,
- PyDoc_STR("(short offset) -> (Point _rv)")},
- {"TEClick", (PyCFunction)TEObj_TEClick, 1,
- PyDoc_STR("(Point pt, Boolean fExtend) -> None")},
- {"TESetStyleHandle", (PyCFunction)TEObj_TESetStyleHandle, 1,
- PyDoc_STR("(TEStyleHandle theHandle) -> None")},
- {"TEGetStyleHandle", (PyCFunction)TEObj_TEGetStyleHandle, 1,
- PyDoc_STR("() -> (TEStyleHandle _rv)")},
- {"TEGetStyle", (PyCFunction)TEObj_TEGetStyle, 1,
- PyDoc_STR("(short offset) -> (TextStyle theStyle, short lineHeight, short fontAscent)")},
- {"TEStylePaste", (PyCFunction)TEObj_TEStylePaste, 1,
- PyDoc_STR("() -> None")},
- {"TESetStyle", (PyCFunction)TEObj_TESetStyle, 1,
- PyDoc_STR("(short mode, TextStyle newStyle, Boolean fRedraw) -> None")},
- {"TEReplaceStyle", (PyCFunction)TEObj_TEReplaceStyle, 1,
- PyDoc_STR("(short mode, TextStyle oldStyle, TextStyle newStyle, Boolean fRedraw) -> None")},
- {"TEGetStyleScrapHandle", (PyCFunction)TEObj_TEGetStyleScrapHandle, 1,
- PyDoc_STR("() -> (StScrpHandle _rv)")},
- {"TEStyleInsert", (PyCFunction)TEObj_TEStyleInsert, 1,
- PyDoc_STR("(Buffer text, StScrpHandle hST) -> None")},
- {"TEGetHeight", (PyCFunction)TEObj_TEGetHeight, 1,
- PyDoc_STR("(long endLine, long startLine) -> (long _rv)")},
- {"TEContinuousStyle", (PyCFunction)TEObj_TEContinuousStyle, 1,
- PyDoc_STR("(short mode, TextStyle aStyle) -> (Boolean _rv, short mode, TextStyle aStyle)")},
- {"TEUseStyleScrap", (PyCFunction)TEObj_TEUseStyleScrap, 1,
- PyDoc_STR("(long rangeStart, long rangeEnd, StScrpHandle newStyles, Boolean fRedraw) -> None")},
- {"TENumStyles", (PyCFunction)TEObj_TENumStyles, 1,
- PyDoc_STR("(long rangeStart, long rangeEnd) -> (long _rv)")},
- {"TEFeatureFlag", (PyCFunction)TEObj_TEFeatureFlag, 1,
- PyDoc_STR("(short feature, short action) -> (short _rv)")},
- {"TEGetHiliteRgn", (PyCFunction)TEObj_TEGetHiliteRgn, 1,
- PyDoc_STR("(RgnHandle region) -> None")},
- {"as_Resource", (PyCFunction)TEObj_as_Resource, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {NULL, NULL, 0}
+ {"TESetText", (PyCFunction)TEObj_TESetText, 1,
+ PyDoc_STR("(Buffer text) -> None")},
+ {"TEGetText", (PyCFunction)TEObj_TEGetText, 1,
+ PyDoc_STR("() -> (CharsHandle _rv)")},
+ {"TEIdle", (PyCFunction)TEObj_TEIdle, 1,
+ PyDoc_STR("() -> None")},
+ {"TESetSelect", (PyCFunction)TEObj_TESetSelect, 1,
+ PyDoc_STR("(long selStart, long selEnd) -> None")},
+ {"TEActivate", (PyCFunction)TEObj_TEActivate, 1,
+ PyDoc_STR("() -> None")},
+ {"TEDeactivate", (PyCFunction)TEObj_TEDeactivate, 1,
+ PyDoc_STR("() -> None")},
+ {"TEKey", (PyCFunction)TEObj_TEKey, 1,
+ PyDoc_STR("(CharParameter key) -> None")},
+ {"TECut", (PyCFunction)TEObj_TECut, 1,
+ PyDoc_STR("() -> None")},
+ {"TECopy", (PyCFunction)TEObj_TECopy, 1,
+ PyDoc_STR("() -> None")},
+ {"TEPaste", (PyCFunction)TEObj_TEPaste, 1,
+ PyDoc_STR("() -> None")},
+ {"TEDelete", (PyCFunction)TEObj_TEDelete, 1,
+ PyDoc_STR("() -> None")},
+ {"TEInsert", (PyCFunction)TEObj_TEInsert, 1,
+ PyDoc_STR("(Buffer text) -> None")},
+ {"TESetAlignment", (PyCFunction)TEObj_TESetAlignment, 1,
+ PyDoc_STR("(short just) -> None")},
+ {"TEUpdate", (PyCFunction)TEObj_TEUpdate, 1,
+ PyDoc_STR("(Rect rUpdate) -> None")},
+ {"TEScroll", (PyCFunction)TEObj_TEScroll, 1,
+ PyDoc_STR("(short dh, short dv) -> None")},
+ {"TESelView", (PyCFunction)TEObj_TESelView, 1,
+ PyDoc_STR("() -> None")},
+ {"TEPinScroll", (PyCFunction)TEObj_TEPinScroll, 1,
+ PyDoc_STR("(short dh, short dv) -> None")},
+ {"TEAutoView", (PyCFunction)TEObj_TEAutoView, 1,
+ PyDoc_STR("(Boolean fAuto) -> None")},
+ {"TECalText", (PyCFunction)TEObj_TECalText, 1,
+ PyDoc_STR("() -> None")},
+ {"TEGetOffset", (PyCFunction)TEObj_TEGetOffset, 1,
+ PyDoc_STR("(Point pt) -> (short _rv)")},
+ {"TEGetPoint", (PyCFunction)TEObj_TEGetPoint, 1,
+ PyDoc_STR("(short offset) -> (Point _rv)")},
+ {"TEClick", (PyCFunction)TEObj_TEClick, 1,
+ PyDoc_STR("(Point pt, Boolean fExtend) -> None")},
+ {"TESetStyleHandle", (PyCFunction)TEObj_TESetStyleHandle, 1,
+ PyDoc_STR("(TEStyleHandle theHandle) -> None")},
+ {"TEGetStyleHandle", (PyCFunction)TEObj_TEGetStyleHandle, 1,
+ PyDoc_STR("() -> (TEStyleHandle _rv)")},
+ {"TEGetStyle", (PyCFunction)TEObj_TEGetStyle, 1,
+ PyDoc_STR("(short offset) -> (TextStyle theStyle, short lineHeight, short fontAscent)")},
+ {"TEStylePaste", (PyCFunction)TEObj_TEStylePaste, 1,
+ PyDoc_STR("() -> None")},
+ {"TESetStyle", (PyCFunction)TEObj_TESetStyle, 1,
+ PyDoc_STR("(short mode, TextStyle newStyle, Boolean fRedraw) -> None")},
+ {"TEReplaceStyle", (PyCFunction)TEObj_TEReplaceStyle, 1,
+ PyDoc_STR("(short mode, TextStyle oldStyle, TextStyle newStyle, Boolean fRedraw) -> None")},
+ {"TEGetStyleScrapHandle", (PyCFunction)TEObj_TEGetStyleScrapHandle, 1,
+ PyDoc_STR("() -> (StScrpHandle _rv)")},
+ {"TEStyleInsert", (PyCFunction)TEObj_TEStyleInsert, 1,
+ PyDoc_STR("(Buffer text, StScrpHandle hST) -> None")},
+ {"TEGetHeight", (PyCFunction)TEObj_TEGetHeight, 1,
+ PyDoc_STR("(long endLine, long startLine) -> (long _rv)")},
+ {"TEContinuousStyle", (PyCFunction)TEObj_TEContinuousStyle, 1,
+ PyDoc_STR("(short mode, TextStyle aStyle) -> (Boolean _rv, short mode, TextStyle aStyle)")},
+ {"TEUseStyleScrap", (PyCFunction)TEObj_TEUseStyleScrap, 1,
+ PyDoc_STR("(long rangeStart, long rangeEnd, StScrpHandle newStyles, Boolean fRedraw) -> None")},
+ {"TENumStyles", (PyCFunction)TEObj_TENumStyles, 1,
+ PyDoc_STR("(long rangeStart, long rangeEnd) -> (long _rv)")},
+ {"TEFeatureFlag", (PyCFunction)TEObj_TEFeatureFlag, 1,
+ PyDoc_STR("(short feature, short action) -> (short _rv)")},
+ {"TEGetHiliteRgn", (PyCFunction)TEObj_TEGetHiliteRgn, 1,
+ PyDoc_STR("(RgnHandle region) -> None")},
+ {"as_Resource", (PyCFunction)TEObj_as_Resource, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {NULL, NULL, 0}
};
static PyObject *TEObj_get_destRect(TEObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->destRect);
+ return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->destRect);
}
#define TEObj_set_destRect NULL
static PyObject *TEObj_get_viewRect(TEObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->viewRect);
+ return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->viewRect);
}
#define TEObj_set_viewRect NULL
static PyObject *TEObj_get_selRect(TEObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->selRect);
+ return Py_BuildValue("O&", PyMac_BuildRect, &(*self->ob_itself)->selRect);
}
#define TEObj_set_selRect NULL
static PyObject *TEObj_get_lineHeight(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->lineHeight);
+ return Py_BuildValue("h", (*self->ob_itself)->lineHeight);
}
#define TEObj_set_lineHeight NULL
static PyObject *TEObj_get_fontAscent(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->fontAscent);
+ return Py_BuildValue("h", (*self->ob_itself)->fontAscent);
}
#define TEObj_set_fontAscent NULL
static PyObject *TEObj_get_selPoint(TEObject *self, void *closure)
{
- return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->selPoint);
+ return Py_BuildValue("O&", PyMac_BuildPoint, (*self->ob_itself)->selPoint);
}
#define TEObj_set_selPoint NULL
static PyObject *TEObj_get_selStart(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->selStart);
+ return Py_BuildValue("h", (*self->ob_itself)->selStart);
}
#define TEObj_set_selStart NULL
static PyObject *TEObj_get_selEnd(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->selEnd);
+ return Py_BuildValue("h", (*self->ob_itself)->selEnd);
}
#define TEObj_set_selEnd NULL
static PyObject *TEObj_get_active(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->active);
+ return Py_BuildValue("h", (*self->ob_itself)->active);
}
#define TEObj_set_active NULL
static PyObject *TEObj_get_just(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->just);
+ return Py_BuildValue("h", (*self->ob_itself)->just);
}
#define TEObj_set_just NULL
static PyObject *TEObj_get_teLength(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->teLength);
+ return Py_BuildValue("h", (*self->ob_itself)->teLength);
}
#define TEObj_set_teLength NULL
static PyObject *TEObj_get_txFont(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->txFont);
+ return Py_BuildValue("h", (*self->ob_itself)->txFont);
}
#define TEObj_set_txFont NULL
static PyObject *TEObj_get_txFace(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->txFace);
+ return Py_BuildValue("h", (*self->ob_itself)->txFace);
}
#define TEObj_set_txFace NULL
static PyObject *TEObj_get_txMode(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->txMode);
+ return Py_BuildValue("h", (*self->ob_itself)->txMode);
}
#define TEObj_set_txMode NULL
static PyObject *TEObj_get_txSize(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->txSize);
+ return Py_BuildValue("h", (*self->ob_itself)->txSize);
}
#define TEObj_set_txSize NULL
static PyObject *TEObj_get_nLines(TEObject *self, void *closure)
{
- return Py_BuildValue("h", (*self->ob_itself)->nLines);
+ return Py_BuildValue("h", (*self->ob_itself)->nLines);
}
#define TEObj_set_nLines NULL
static PyGetSetDef TEObj_getsetlist[] = {
- {"destRect", (getter)TEObj_get_destRect, (setter)TEObj_set_destRect, "Destination rectangle"},
- {"viewRect", (getter)TEObj_get_viewRect, (setter)TEObj_set_viewRect, "Viewing rectangle"},
- {"selRect", (getter)TEObj_get_selRect, (setter)TEObj_set_selRect, "Selection rectangle"},
- {"lineHeight", (getter)TEObj_get_lineHeight, (setter)TEObj_set_lineHeight, "Height of a line"},
- {"fontAscent", (getter)TEObj_get_fontAscent, (setter)TEObj_set_fontAscent, "Ascent of a line"},
- {"selPoint", (getter)TEObj_get_selPoint, (setter)TEObj_set_selPoint, "Selection Point"},
- {"selStart", (getter)TEObj_get_selStart, (setter)TEObj_set_selStart, "Start of selection"},
- {"selEnd", (getter)TEObj_get_selEnd, (setter)TEObj_set_selEnd, "End of selection"},
- {"active", (getter)TEObj_get_active, (setter)TEObj_set_active, "TBD"},
- {"just", (getter)TEObj_get_just, (setter)TEObj_set_just, "Justification"},
- {"teLength", (getter)TEObj_get_teLength, (setter)TEObj_set_teLength, "TBD"},
- {"txFont", (getter)TEObj_get_txFont, (setter)TEObj_set_txFont, "Current font"},
- {"txFace", (getter)TEObj_get_txFace, (setter)TEObj_set_txFace, "Current font variant"},
- {"txMode", (getter)TEObj_get_txMode, (setter)TEObj_set_txMode, "Current text-drawing mode"},
- {"txSize", (getter)TEObj_get_txSize, (setter)TEObj_set_txSize, "Current font size"},
- {"nLines", (getter)TEObj_get_nLines, (setter)TEObj_set_nLines, "TBD"},
- {NULL, NULL, NULL, NULL},
+ {"destRect", (getter)TEObj_get_destRect, (setter)TEObj_set_destRect, "Destination rectangle"},
+ {"viewRect", (getter)TEObj_get_viewRect, (setter)TEObj_set_viewRect, "Viewing rectangle"},
+ {"selRect", (getter)TEObj_get_selRect, (setter)TEObj_set_selRect, "Selection rectangle"},
+ {"lineHeight", (getter)TEObj_get_lineHeight, (setter)TEObj_set_lineHeight, "Height of a line"},
+ {"fontAscent", (getter)TEObj_get_fontAscent, (setter)TEObj_set_fontAscent, "Ascent of a line"},
+ {"selPoint", (getter)TEObj_get_selPoint, (setter)TEObj_set_selPoint, "Selection Point"},
+ {"selStart", (getter)TEObj_get_selStart, (setter)TEObj_set_selStart, "Start of selection"},
+ {"selEnd", (getter)TEObj_get_selEnd, (setter)TEObj_set_selEnd, "End of selection"},
+ {"active", (getter)TEObj_get_active, (setter)TEObj_set_active, "TBD"},
+ {"just", (getter)TEObj_get_just, (setter)TEObj_set_just, "Justification"},
+ {"teLength", (getter)TEObj_get_teLength, (setter)TEObj_set_teLength, "TBD"},
+ {"txFont", (getter)TEObj_get_txFont, (setter)TEObj_set_txFont, "Current font"},
+ {"txFace", (getter)TEObj_get_txFace, (setter)TEObj_set_txFace, "Current font variant"},
+ {"txMode", (getter)TEObj_get_txMode, (setter)TEObj_set_txMode, "Current text-drawing mode"},
+ {"txSize", (getter)TEObj_get_txSize, (setter)TEObj_set_txSize, "Current font size"},
+ {"nLines", (getter)TEObj_get_nLines, (setter)TEObj_set_nLines, "TBD"},
+ {NULL, NULL, NULL, NULL},
};
@@ -987,61 +987,61 @@ static PyGetSetDef TEObj_getsetlist[] = {
static PyObject *TEObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- TEHandle itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ TEHandle itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TEObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((TEObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, TEObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((TEObject *)_self)->ob_itself = itself;
+ return _self;
}
#define TEObj_tp_free PyObject_Del
PyTypeObject TE_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_TE.TE", /*tp_name*/
- sizeof(TEObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) TEObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) TEObj_compare, /*tp_compare*/
- (reprfunc) TEObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) TEObj_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*/
- TEObj_methods, /* tp_methods */
- 0, /*tp_members*/
- TEObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- TEObj_tp_init, /* tp_init */
- TEObj_tp_alloc, /* tp_alloc */
- TEObj_tp_new, /* tp_new */
- TEObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_TE.TE", /*tp_name*/
+ sizeof(TEObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) TEObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) TEObj_compare, /*tp_compare*/
+ (reprfunc) TEObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) TEObj_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*/
+ TEObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ TEObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ TEObj_tp_init, /* tp_init */
+ TEObj_tp_alloc, /* tp_alloc */
+ TEObj_tp_new, /* tp_new */
+ TEObj_tp_free, /* tp_free */
};
/* ----------------------- End object type TE ----------------------- */
@@ -1049,257 +1049,257 @@ PyTypeObject TE_Type = {
static PyObject *TE_TEScrapHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef TEScrapHandle
- PyMac_PRECHECK(TEScrapHandle);
+ PyMac_PRECHECK(TEScrapHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TEScrapHandle();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TEScrapHandle();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TE_TEGetScrapLength(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef TEGetScrapLength
- PyMac_PRECHECK(TEGetScrapLength);
+ PyMac_PRECHECK(TEGetScrapLength);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TEGetScrapLength();
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TEGetScrapLength();
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *TE_TENew(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TEHandle _rv;
- Rect destRect;
- Rect viewRect;
+ PyObject *_res = NULL;
+ TEHandle _rv;
+ Rect destRect;
+ Rect viewRect;
#ifndef TENew
- PyMac_PRECHECK(TENew);
+ PyMac_PRECHECK(TENew);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &destRect,
- PyMac_GetRect, &viewRect))
- return NULL;
- _rv = TENew(&destRect,
- &viewRect);
- _res = Py_BuildValue("O&",
- TEObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &destRect,
+ PyMac_GetRect, &viewRect))
+ return NULL;
+ _rv = TENew(&destRect,
+ &viewRect);
+ _res = Py_BuildValue("O&",
+ TEObj_New, _rv);
+ return _res;
}
static PyObject *TE_TETextBox(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- char *text__in__;
- long text__len__;
- int text__in_len__;
- Rect box;
- short just;
+ PyObject *_res = NULL;
+ char *text__in__;
+ long text__len__;
+ int text__in_len__;
+ Rect box;
+ short just;
#ifndef TETextBox
- PyMac_PRECHECK(TETextBox);
+ PyMac_PRECHECK(TETextBox);
#endif
- if (!PyArg_ParseTuple(_args, "s#O&h",
- &text__in__, &text__in_len__,
- PyMac_GetRect, &box,
- &just))
- return NULL;
- text__len__ = text__in_len__;
- TETextBox(text__in__, text__len__,
- &box,
- just);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "s#O&h",
+ &text__in__, &text__in_len__,
+ PyMac_GetRect, &box,
+ &just))
+ return NULL;
+ text__len__ = text__in_len__;
+ TETextBox(text__in__, text__len__,
+ &box,
+ just);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TE_TEStyleNew(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TEHandle _rv;
- Rect destRect;
- Rect viewRect;
+ PyObject *_res = NULL;
+ TEHandle _rv;
+ Rect destRect;
+ Rect viewRect;
#ifndef TEStyleNew
- PyMac_PRECHECK(TEStyleNew);
+ PyMac_PRECHECK(TEStyleNew);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &destRect,
- PyMac_GetRect, &viewRect))
- return NULL;
- _rv = TEStyleNew(&destRect,
- &viewRect);
- _res = Py_BuildValue("O&",
- TEObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &destRect,
+ PyMac_GetRect, &viewRect))
+ return NULL;
+ _rv = TEStyleNew(&destRect,
+ &viewRect);
+ _res = Py_BuildValue("O&",
+ TEObj_New, _rv);
+ return _res;
}
static PyObject *TE_TESetScrapLength(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long length;
+ PyObject *_res = NULL;
+ long length;
#ifndef TESetScrapLength
- PyMac_PRECHECK(TESetScrapLength);
+ PyMac_PRECHECK(TESetScrapLength);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &length))
- return NULL;
- TESetScrapLength(length);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &length))
+ return NULL;
+ TESetScrapLength(length);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TE_TEFromScrap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef TEFromScrap
- PyMac_PRECHECK(TEFromScrap);
+ PyMac_PRECHECK(TEFromScrap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TEFromScrap();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TEFromScrap();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TE_TEToScrap(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSErr _err;
+ PyObject *_res = NULL;
+ OSErr _err;
#ifndef TEToScrap
- PyMac_PRECHECK(TEToScrap);
+ PyMac_PRECHECK(TEToScrap);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = TEToScrap();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = TEToScrap();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TE_TEGetScrapHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle _rv;
+ PyObject *_res = NULL;
+ Handle _rv;
#ifndef TEGetScrapHandle
- PyMac_PRECHECK(TEGetScrapHandle);
+ PyMac_PRECHECK(TEGetScrapHandle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = TEGetScrapHandle();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = TEGetScrapHandle();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *TE_TESetScrapHandle(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Handle value;
+ PyObject *_res = NULL;
+ Handle value;
#ifndef TESetScrapHandle
- PyMac_PRECHECK(TESetScrapHandle);
+ PyMac_PRECHECK(TESetScrapHandle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &value))
- return NULL;
- TESetScrapHandle(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &value))
+ return NULL;
+ TESetScrapHandle(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TE_LMGetWordRedraw(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt8 _rv;
+ PyObject *_res = NULL;
+ UInt8 _rv;
#ifndef LMGetWordRedraw
- PyMac_PRECHECK(LMGetWordRedraw);
+ PyMac_PRECHECK(LMGetWordRedraw);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = LMGetWordRedraw();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = LMGetWordRedraw();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *TE_LMSetWordRedraw(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- UInt8 value;
+ PyObject *_res = NULL;
+ UInt8 value;
#ifndef LMSetWordRedraw
- PyMac_PRECHECK(LMSetWordRedraw);
+ PyMac_PRECHECK(LMSetWordRedraw);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &value))
- return NULL;
- LMSetWordRedraw(value);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &value))
+ return NULL;
+ LMSetWordRedraw(value);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *TE_as_TE(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- TEHandle _rv;
- Handle h;
+ PyObject *_res = NULL;
+ TEHandle _rv;
+ Handle h;
#ifndef as_TE
- PyMac_PRECHECK(as_TE);
+ PyMac_PRECHECK(as_TE);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &h))
- return NULL;
- _rv = as_TE(h);
- _res = Py_BuildValue("O&",
- TEObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &h))
+ return NULL;
+ _rv = as_TE(h);
+ _res = Py_BuildValue("O&",
+ TEObj_New, _rv);
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef TE_methods[] = {
#ifndef __LP64__
- {"TEScrapHandle", (PyCFunction)TE_TEScrapHandle, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"TEGetScrapLength", (PyCFunction)TE_TEGetScrapLength, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"TENew", (PyCFunction)TE_TENew, 1,
- PyDoc_STR("(Rect destRect, Rect viewRect) -> (TEHandle _rv)")},
- {"TETextBox", (PyCFunction)TE_TETextBox, 1,
- PyDoc_STR("(Buffer text, Rect box, short just) -> None")},
- {"TEStyleNew", (PyCFunction)TE_TEStyleNew, 1,
- PyDoc_STR("(Rect destRect, Rect viewRect) -> (TEHandle _rv)")},
- {"TESetScrapLength", (PyCFunction)TE_TESetScrapLength, 1,
- PyDoc_STR("(long length) -> None")},
- {"TEFromScrap", (PyCFunction)TE_TEFromScrap, 1,
- PyDoc_STR("() -> None")},
- {"TEToScrap", (PyCFunction)TE_TEToScrap, 1,
- PyDoc_STR("() -> None")},
- {"TEGetScrapHandle", (PyCFunction)TE_TEGetScrapHandle, 1,
- PyDoc_STR("() -> (Handle _rv)")},
- {"TESetScrapHandle", (PyCFunction)TE_TESetScrapHandle, 1,
- PyDoc_STR("(Handle value) -> None")},
- {"LMGetWordRedraw", (PyCFunction)TE_LMGetWordRedraw, 1,
- PyDoc_STR("() -> (UInt8 _rv)")},
- {"LMSetWordRedraw", (PyCFunction)TE_LMSetWordRedraw, 1,
- PyDoc_STR("(UInt8 value) -> None")},
- {"as_TE", (PyCFunction)TE_as_TE, 1,
- PyDoc_STR("(Handle h) -> (TEHandle _rv)")},
+ {"TEScrapHandle", (PyCFunction)TE_TEScrapHandle, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"TEGetScrapLength", (PyCFunction)TE_TEGetScrapLength, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"TENew", (PyCFunction)TE_TENew, 1,
+ PyDoc_STR("(Rect destRect, Rect viewRect) -> (TEHandle _rv)")},
+ {"TETextBox", (PyCFunction)TE_TETextBox, 1,
+ PyDoc_STR("(Buffer text, Rect box, short just) -> None")},
+ {"TEStyleNew", (PyCFunction)TE_TEStyleNew, 1,
+ PyDoc_STR("(Rect destRect, Rect viewRect) -> (TEHandle _rv)")},
+ {"TESetScrapLength", (PyCFunction)TE_TESetScrapLength, 1,
+ PyDoc_STR("(long length) -> None")},
+ {"TEFromScrap", (PyCFunction)TE_TEFromScrap, 1,
+ PyDoc_STR("() -> None")},
+ {"TEToScrap", (PyCFunction)TE_TEToScrap, 1,
+ PyDoc_STR("() -> None")},
+ {"TEGetScrapHandle", (PyCFunction)TE_TEGetScrapHandle, 1,
+ PyDoc_STR("() -> (Handle _rv)")},
+ {"TESetScrapHandle", (PyCFunction)TE_TESetScrapHandle, 1,
+ PyDoc_STR("(Handle value) -> None")},
+ {"LMGetWordRedraw", (PyCFunction)TE_LMGetWordRedraw, 1,
+ PyDoc_STR("() -> (UInt8 _rv)")},
+ {"LMSetWordRedraw", (PyCFunction)TE_LMSetWordRedraw, 1,
+ PyDoc_STR("(UInt8 value) -> None")},
+ {"as_TE", (PyCFunction)TE_as_TE, 1,
+ PyDoc_STR("(Handle h) -> (TEHandle _rv)")},
#endif /* __LP64__ */
- {NULL, NULL, 0}
+ {NULL, NULL, 0}
};
@@ -1307,31 +1307,31 @@ static PyMethodDef TE_methods[] = {
void init_TE(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(TEHandle, TEObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TEHandle, TEObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(TEHandle, TEObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(TEHandle, TEObj_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_TE", TE_methods);
+ m = Py_InitModule("_TE", TE_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- TE_Error = PyMac_GetOSErrException();
- if (TE_Error == NULL ||
- PyDict_SetItemString(d, "Error", TE_Error) != 0)
- return;
- TE_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&TE_Type) < 0) return;
- Py_INCREF(&TE_Type);
- PyModule_AddObject(m, "TE", (PyObject *)&TE_Type);
- /* Backward-compatible name */
- Py_INCREF(&TE_Type);
- PyModule_AddObject(m, "TEType", (PyObject *)&TE_Type);
+ d = PyModule_GetDict(m);
+ TE_Error = PyMac_GetOSErrException();
+ if (TE_Error == NULL ||
+ PyDict_SetItemString(d, "Error", TE_Error) != 0)
+ return;
+ TE_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&TE_Type) < 0) return;
+ Py_INCREF(&TE_Type);
+ PyModule_AddObject(m, "TE", (PyObject *)&TE_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&TE_Type);
+ PyModule_AddObject(m, "TEType", (PyObject *)&TE_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Modules/win/_Winmodule.c b/Mac/Modules/win/_Winmodule.c
index 87f7591..89233ed 100644
--- a/Mac/Modules/win/_Winmodule.c
+++ b/Mac/Modules/win/_Winmodule.c
@@ -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)
@@ -36,7 +36,7 @@ extern int _WinObj_Convert(PyObject *, WindowRef *);
static void
PyMac_AutoDisposeWindow(WindowPtr w)
{
- DisposeWindow(w);
+ DisposeWindow(w);
}
static PyObject *Win_Error;
@@ -48,2522 +48,2522 @@ PyTypeObject Window_Type;
#define WinObj_Check(x) ((x)->ob_type == &Window_Type || PyObject_TypeCheck((x), &Window_Type))
typedef struct WindowObject {
- PyObject_HEAD
- WindowPtr ob_itself;
- void (*ob_freeit)(WindowPtr ptr);
+ PyObject_HEAD
+ WindowPtr ob_itself;
+ void (*ob_freeit)(WindowPtr ptr);
} WindowObject;
PyObject *WinObj_New(WindowPtr itself)
{
- WindowObject *it;
- if (itself == NULL) return PyMac_Error(resNotFound);
- /* XXXX Or should we use WhichWindow code here? */
- it = PyObject_NEW(WindowObject, &Window_Type);
- if (it == NULL) return NULL;
- it->ob_itself = itself;
- it->ob_freeit = NULL;
- if (GetWRefCon(itself) == 0)
- {
- SetWRefCon(itself, (long)it);
- it->ob_freeit = PyMac_AutoDisposeWindow;
- }
- return (PyObject *)it;
+ WindowObject *it;
+ if (itself == NULL) return PyMac_Error(resNotFound);
+ /* XXXX Or should we use WhichWindow code here? */
+ it = PyObject_NEW(WindowObject, &Window_Type);
+ if (it == NULL) return NULL;
+ it->ob_itself = itself;
+ it->ob_freeit = NULL;
+ if (GetWRefCon(itself) == 0)
+ {
+ SetWRefCon(itself, (long)it);
+ it->ob_freeit = PyMac_AutoDisposeWindow;
+ }
+ return (PyObject *)it;
}
int WinObj_Convert(PyObject *v, WindowPtr *p_itself)
{
- if (v == Py_None) { *p_itself = NULL; return 1; }
- if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; }
+ if (v == Py_None) { *p_itself = NULL; return 1; }
+ if (PyInt_Check(v)) { *p_itself = (WindowPtr)PyInt_AsLong(v); return 1; }
- {
- DialogRef dlg;
- if (DlgObj_Convert(v, &dlg) && dlg) {
- *p_itself = GetDialogWindow(dlg);
- return 1;
- }
- PyErr_Clear();
- }
- if (!WinObj_Check(v))
- {
- PyErr_SetString(PyExc_TypeError, "Window required");
- return 0;
- }
- *p_itself = ((WindowObject *)v)->ob_itself;
- return 1;
+ {
+ DialogRef dlg;
+ if (DlgObj_Convert(v, &dlg) && dlg) {
+ *p_itself = GetDialogWindow(dlg);
+ return 1;
+ }
+ PyErr_Clear();
+ }
+ if (!WinObj_Check(v))
+ {
+ PyErr_SetString(PyExc_TypeError, "Window required");
+ return 0;
+ }
+ *p_itself = ((WindowObject *)v)->ob_itself;
+ return 1;
}
static void WinObj_dealloc(WindowObject *self)
{
- if (self->ob_freeit && self->ob_itself)
- {
- SetWRefCon(self->ob_itself, 0);
- self->ob_freeit(self->ob_itself);
- }
- self->ob_itself = NULL;
- self->ob_freeit = NULL;
- self->ob_type->tp_free((PyObject *)self);
+ if (self->ob_freeit && self->ob_itself)
+ {
+ SetWRefCon(self->ob_itself, 0);
+ self->ob_freeit(self->ob_itself);
+ }
+ self->ob_itself = NULL;
+ self->ob_freeit = NULL;
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *WinObj_GetWindowOwnerCount(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 outCount;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 outCount;
#ifndef GetWindowOwnerCount
- PyMac_PRECHECK(GetWindowOwnerCount);
+ PyMac_PRECHECK(GetWindowOwnerCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowOwnerCount(_self->ob_itself,
- &outCount);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outCount);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowOwnerCount(_self->ob_itself,
+ &outCount);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outCount);
+ return _res;
}
static PyObject *WinObj_CloneWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef CloneWindow
- PyMac_PRECHECK(CloneWindow);
+ PyMac_PRECHECK(CloneWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CloneWindow(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CloneWindow(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowRetainCount(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- ItemCount _rv;
+ PyObject *_res = NULL;
+ ItemCount _rv;
#ifndef GetWindowRetainCount
- PyMac_PRECHECK(GetWindowRetainCount);
+ PyMac_PRECHECK(GetWindowRetainCount);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWindowRetainCount(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWindowRetainCount(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *WinObj_RetainWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef RetainWindow
- PyMac_PRECHECK(RetainWindow);
+ PyMac_PRECHECK(RetainWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = RetainWindow(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = RetainWindow(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ReleaseWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef ReleaseWindow
- PyMac_PRECHECK(ReleaseWindow);
+ PyMac_PRECHECK(ReleaseWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = ReleaseWindow(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = ReleaseWindow(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ReshapeCustomWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef ReshapeCustomWindow
- PyMac_PRECHECK(ReshapeCustomWindow);
+ PyMac_PRECHECK(ReshapeCustomWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = ReshapeCustomWindow(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = ReshapeCustomWindow(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowWidgetHilite(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowDefPartCode outHilite;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowDefPartCode outHilite;
#ifndef GetWindowWidgetHilite
- PyMac_PRECHECK(GetWindowWidgetHilite);
+ PyMac_PRECHECK(GetWindowWidgetHilite);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowWidgetHilite(_self->ob_itself,
- &outHilite);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("h",
- outHilite);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowWidgetHilite(_self->ob_itself,
+ &outHilite);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("h",
+ outHilite);
+ return _res;
}
static PyObject *WinObj_GetWindowClass(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowClass outClass;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowClass outClass;
#ifndef GetWindowClass
- PyMac_PRECHECK(GetWindowClass);
+ PyMac_PRECHECK(GetWindowClass);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowClass(_self->ob_itself,
- &outClass);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outClass);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowClass(_self->ob_itself,
+ &outClass);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outClass);
+ return _res;
}
static PyObject *WinObj_GetWindowAttributes(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowAttributes outAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowAttributes outAttributes;
#ifndef GetWindowAttributes
- PyMac_PRECHECK(GetWindowAttributes);
+ PyMac_PRECHECK(GetWindowAttributes);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowAttributes(_self->ob_itself,
- &outAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outAttributes);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowAttributes(_self->ob_itself,
+ &outAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outAttributes);
+ return _res;
}
static PyObject *WinObj_ChangeWindowAttributes(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowAttributes setTheseAttributes;
- WindowAttributes clearTheseAttributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowAttributes setTheseAttributes;
+ WindowAttributes clearTheseAttributes;
#ifndef ChangeWindowAttributes
- PyMac_PRECHECK(ChangeWindowAttributes);
+ PyMac_PRECHECK(ChangeWindowAttributes);
#endif
- if (!PyArg_ParseTuple(_args, "ll",
- &setTheseAttributes,
- &clearTheseAttributes))
- return NULL;
- _err = ChangeWindowAttributes(_self->ob_itself,
- setTheseAttributes,
- clearTheseAttributes);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "ll",
+ &setTheseAttributes,
+ &clearTheseAttributes))
+ return NULL;
+ _err = ChangeWindowAttributes(_self->ob_itself,
+ setTheseAttributes,
+ clearTheseAttributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWindowClass(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowClass inWindowClass;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowClass inWindowClass;
#ifndef SetWindowClass
- PyMac_PRECHECK(SetWindowClass);
+ PyMac_PRECHECK(SetWindowClass);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inWindowClass))
- return NULL;
- _err = SetWindowClass(_self->ob_itself,
- inWindowClass);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inWindowClass))
+ return NULL;
+ _err = SetWindowClass(_self->ob_itself,
+ inWindowClass);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWindowModality(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowModality inModalKind;
- WindowPtr inUnavailableWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowModality inModalKind;
+ WindowPtr inUnavailableWindow;
#ifndef SetWindowModality
- PyMac_PRECHECK(SetWindowModality);
+ PyMac_PRECHECK(SetWindowModality);
#endif
- if (!PyArg_ParseTuple(_args, "lO&",
- &inModalKind,
- WinObj_Convert, &inUnavailableWindow))
- return NULL;
- _err = SetWindowModality(_self->ob_itself,
- inModalKind,
- inUnavailableWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "lO&",
+ &inModalKind,
+ WinObj_Convert, &inUnavailableWindow))
+ return NULL;
+ _err = SetWindowModality(_self->ob_itself,
+ inModalKind,
+ inUnavailableWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowModality(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowModality outModalKind;
- WindowPtr outUnavailableWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowModality outModalKind;
+ WindowPtr outUnavailableWindow;
#ifndef GetWindowModality
- PyMac_PRECHECK(GetWindowModality);
+ PyMac_PRECHECK(GetWindowModality);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowModality(_self->ob_itself,
- &outModalKind,
- &outUnavailableWindow);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("lO&",
- outModalKind,
- WinObj_WhichWindow, outUnavailableWindow);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowModality(_self->ob_itself,
+ &outModalKind,
+ &outUnavailableWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("lO&",
+ outModalKind,
+ WinObj_WhichWindow, outUnavailableWindow);
+ return _res;
}
static PyObject *WinObj_SetWindowContentColor(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RGBColor color;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RGBColor color;
#ifndef SetWindowContentColor
- PyMac_PRECHECK(SetWindowContentColor);
+ PyMac_PRECHECK(SetWindowContentColor);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- QdRGB_Convert, &color))
- return NULL;
- _err = SetWindowContentColor(_self->ob_itself,
- &color);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ QdRGB_Convert, &color))
+ return NULL;
+ _err = SetWindowContentColor(_self->ob_itself,
+ &color);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowContentColor(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RGBColor color;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RGBColor color;
#ifndef GetWindowContentColor
- PyMac_PRECHECK(GetWindowContentColor);
+ PyMac_PRECHECK(GetWindowContentColor);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowContentColor(_self->ob_itself,
- &color);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- QdRGB_New, &color);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowContentColor(_self->ob_itself,
+ &color);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ QdRGB_New, &color);
+ return _res;
}
static PyObject *WinObj_GetWindowContentPattern(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- PixPatHandle outPixPat;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ PixPatHandle outPixPat;
#ifndef GetWindowContentPattern
- PyMac_PRECHECK(GetWindowContentPattern);
+ PyMac_PRECHECK(GetWindowContentPattern);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &outPixPat))
- return NULL;
- _err = GetWindowContentPattern(_self->ob_itself,
- outPixPat);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &outPixPat))
+ return NULL;
+ _err = GetWindowContentPattern(_self->ob_itself,
+ outPixPat);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWindowContentPattern(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- PixPatHandle pixPat;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ PixPatHandle pixPat;
#ifndef SetWindowContentPattern
- PyMac_PRECHECK(SetWindowContentPattern);
+ PyMac_PRECHECK(SetWindowContentPattern);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pixPat))
- return NULL;
- _err = SetWindowContentPattern(_self->ob_itself,
- pixPat);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pixPat))
+ return NULL;
+ _err = SetWindowContentPattern(_self->ob_itself,
+ pixPat);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ScrollWindowRect(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inScrollRect;
- SInt16 inHPixels;
- SInt16 inVPixels;
- ScrollWindowOptions inOptions;
- RgnHandle outExposedRgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inScrollRect;
+ SInt16 inHPixels;
+ SInt16 inVPixels;
+ ScrollWindowOptions inOptions;
+ RgnHandle outExposedRgn;
#ifndef ScrollWindowRect
- PyMac_PRECHECK(ScrollWindowRect);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhlO&",
- PyMac_GetRect, &inScrollRect,
- &inHPixels,
- &inVPixels,
- &inOptions,
- ResObj_Convert, &outExposedRgn))
- return NULL;
- _err = ScrollWindowRect(_self->ob_itself,
- &inScrollRect,
- inHPixels,
- inVPixels,
- inOptions,
- outExposedRgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ScrollWindowRect);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhlO&",
+ PyMac_GetRect, &inScrollRect,
+ &inHPixels,
+ &inVPixels,
+ &inOptions,
+ ResObj_Convert, &outExposedRgn))
+ return NULL;
+ _err = ScrollWindowRect(_self->ob_itself,
+ &inScrollRect,
+ inHPixels,
+ inVPixels,
+ inOptions,
+ outExposedRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ScrollWindowRegion(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RgnHandle inScrollRgn;
- SInt16 inHPixels;
- SInt16 inVPixels;
- ScrollWindowOptions inOptions;
- RgnHandle outExposedRgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RgnHandle inScrollRgn;
+ SInt16 inHPixels;
+ SInt16 inVPixels;
+ ScrollWindowOptions inOptions;
+ RgnHandle outExposedRgn;
#ifndef ScrollWindowRegion
- PyMac_PRECHECK(ScrollWindowRegion);
-#endif
- if (!PyArg_ParseTuple(_args, "O&hhlO&",
- ResObj_Convert, &inScrollRgn,
- &inHPixels,
- &inVPixels,
- &inOptions,
- ResObj_Convert, &outExposedRgn))
- return NULL;
- _err = ScrollWindowRegion(_self->ob_itself,
- inScrollRgn,
- inHPixels,
- inVPixels,
- inOptions,
- outExposedRgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ScrollWindowRegion);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&hhlO&",
+ ResObj_Convert, &inScrollRgn,
+ &inHPixels,
+ &inVPixels,
+ &inOptions,
+ ResObj_Convert, &outExposedRgn))
+ return NULL;
+ _err = ScrollWindowRegion(_self->ob_itself,
+ inScrollRgn,
+ inHPixels,
+ inVPixels,
+ inOptions,
+ outExposedRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ClipAbove(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ClipAbove
- PyMac_PRECHECK(ClipAbove);
+ PyMac_PRECHECK(ClipAbove);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ClipAbove(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ClipAbove(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_PaintOne(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle clobberedRgn;
+ PyObject *_res = NULL;
+ RgnHandle clobberedRgn;
#ifndef PaintOne
- PyMac_PRECHECK(PaintOne);
+ PyMac_PRECHECK(PaintOne);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &clobberedRgn))
- return NULL;
- PaintOne(_self->ob_itself,
- clobberedRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &clobberedRgn))
+ return NULL;
+ PaintOne(_self->ob_itself,
+ clobberedRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_PaintBehind(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle clobberedRgn;
+ PyObject *_res = NULL;
+ RgnHandle clobberedRgn;
#ifndef PaintBehind
- PyMac_PRECHECK(PaintBehind);
+ PyMac_PRECHECK(PaintBehind);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &clobberedRgn))
- return NULL;
- PaintBehind(_self->ob_itself,
- clobberedRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &clobberedRgn))
+ return NULL;
+ PaintBehind(_self->ob_itself,
+ clobberedRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_CalcVis(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef CalcVis
- PyMac_PRECHECK(CalcVis);
+ PyMac_PRECHECK(CalcVis);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- CalcVis(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ CalcVis(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_CalcVisBehind(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle clobberedRgn;
+ PyObject *_res = NULL;
+ RgnHandle clobberedRgn;
#ifndef CalcVisBehind
- PyMac_PRECHECK(CalcVisBehind);
+ PyMac_PRECHECK(CalcVisBehind);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &clobberedRgn))
- return NULL;
- CalcVisBehind(_self->ob_itself,
- clobberedRgn);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &clobberedRgn))
+ return NULL;
+ CalcVisBehind(_self->ob_itself,
+ clobberedRgn);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_BringToFront(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef BringToFront
- PyMac_PRECHECK(BringToFront);
+ PyMac_PRECHECK(BringToFront);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- BringToFront(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ BringToFront(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SendBehind(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr behindWindow;
+ PyObject *_res = NULL;
+ WindowPtr behindWindow;
#ifndef SendBehind
- PyMac_PRECHECK(SendBehind);
+ PyMac_PRECHECK(SendBehind);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &behindWindow))
- return NULL;
- SendBehind(_self->ob_itself,
- behindWindow);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &behindWindow))
+ return NULL;
+ SendBehind(_self->ob_itself,
+ behindWindow);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SelectWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef SelectWindow
- PyMac_PRECHECK(SelectWindow);
+ PyMac_PRECHECK(SelectWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- SelectWindow(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ SelectWindow(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetNextWindowOfClass(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- WindowClass inWindowClass;
- Boolean mustBeVisible;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ WindowClass inWindowClass;
+ Boolean mustBeVisible;
#ifndef GetNextWindowOfClass
- PyMac_PRECHECK(GetNextWindowOfClass);
+ PyMac_PRECHECK(GetNextWindowOfClass);
#endif
- if (!PyArg_ParseTuple(_args, "lb",
- &inWindowClass,
- &mustBeVisible))
- return NULL;
- _rv = GetNextWindowOfClass(_self->ob_itself,
- inWindowClass,
- mustBeVisible);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lb",
+ &inWindowClass,
+ &mustBeVisible))
+ return NULL;
+ _rv = GetNextWindowOfClass(_self->ob_itself,
+ inWindowClass,
+ mustBeVisible);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *WinObj_SetWindowAlternateTitle(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inTitle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inTitle;
#ifndef SetWindowAlternateTitle
- PyMac_PRECHECK(SetWindowAlternateTitle);
+ PyMac_PRECHECK(SetWindowAlternateTitle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &inTitle))
- return NULL;
- _err = SetWindowAlternateTitle(_self->ob_itself,
- inTitle);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &inTitle))
+ return NULL;
+ _err = SetWindowAlternateTitle(_self->ob_itself,
+ inTitle);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_CopyWindowAlternateTitle(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef outTitle;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef outTitle;
#ifndef CopyWindowAlternateTitle
- PyMac_PRECHECK(CopyWindowAlternateTitle);
+ PyMac_PRECHECK(CopyWindowAlternateTitle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CopyWindowAlternateTitle(_self->ob_itself,
- &outTitle);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, outTitle);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CopyWindowAlternateTitle(_self->ob_itself,
+ &outTitle);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, outTitle);
+ return _res;
}
static PyObject *WinObj_HiliteWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean fHilite;
+ PyObject *_res = NULL;
+ Boolean fHilite;
#ifndef HiliteWindow
- PyMac_PRECHECK(HiliteWindow);
+ PyMac_PRECHECK(HiliteWindow);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &fHilite))
- return NULL;
- HiliteWindow(_self->ob_itself,
- fHilite);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &fHilite))
+ return NULL;
+ HiliteWindow(_self->ob_itself,
+ fHilite);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWRefCon(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long data;
+ PyObject *_res = NULL;
+ long data;
#ifndef SetWRefCon
- PyMac_PRECHECK(SetWRefCon);
+ PyMac_PRECHECK(SetWRefCon);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &data))
- return NULL;
- SetWRefCon(_self->ob_itself,
- data);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &data))
+ return NULL;
+ SetWRefCon(_self->ob_itself,
+ data);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWRefCon(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
+ PyObject *_res = NULL;
+ long _rv;
#ifndef GetWRefCon
- PyMac_PRECHECK(GetWRefCon);
+ PyMac_PRECHECK(GetWRefCon);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWRefCon(_self->ob_itself);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWRefCon(_self->ob_itself);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *WinObj_SetWindowPic(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle pic;
+ PyObject *_res = NULL;
+ PicHandle pic;
#ifndef SetWindowPic
- PyMac_PRECHECK(SetWindowPic);
+ PyMac_PRECHECK(SetWindowPic);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &pic))
- return NULL;
- SetWindowPic(_self->ob_itself,
- pic);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &pic))
+ return NULL;
+ SetWindowPic(_self->ob_itself,
+ pic);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowPic(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- PicHandle _rv;
+ PyObject *_res = NULL;
+ PicHandle _rv;
#ifndef GetWindowPic
- PyMac_PRECHECK(GetWindowPic);
+ PyMac_PRECHECK(GetWindowPic);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWindowPic(_self->ob_itself);
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWindowPic(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *WinObj_GetWVariant(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetWVariant
- PyMac_PRECHECK(GetWVariant);
+ PyMac_PRECHECK(GetWVariant);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWVariant(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWVariant(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *WinObj_GetWindowFeatures(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- UInt32 outFeatures;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ UInt32 outFeatures;
#ifndef GetWindowFeatures
- PyMac_PRECHECK(GetWindowFeatures);
+ PyMac_PRECHECK(GetWindowFeatures);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowFeatures(_self->ob_itself,
- &outFeatures);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outFeatures);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowFeatures(_self->ob_itself,
+ &outFeatures);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outFeatures);
+ return _res;
}
static PyObject *WinObj_GetWindowRegion(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowRegionCode inRegionCode;
- RgnHandle ioWinRgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowRegionCode inRegionCode;
+ RgnHandle ioWinRgn;
#ifndef GetWindowRegion
- PyMac_PRECHECK(GetWindowRegion);
+ PyMac_PRECHECK(GetWindowRegion);
#endif
- if (!PyArg_ParseTuple(_args, "HO&",
- &inRegionCode,
- ResObj_Convert, &ioWinRgn))
- return NULL;
- _err = GetWindowRegion(_self->ob_itself,
- inRegionCode,
- ioWinRgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "HO&",
+ &inRegionCode,
+ ResObj_Convert, &ioWinRgn))
+ return NULL;
+ _err = GetWindowRegion(_self->ob_itself,
+ inRegionCode,
+ ioWinRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowStructureWidths(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect outRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect outRect;
#ifndef GetWindowStructureWidths
- PyMac_PRECHECK(GetWindowStructureWidths);
+ PyMac_PRECHECK(GetWindowStructureWidths);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowStructureWidths(_self->ob_itself,
- &outRect);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowStructureWidths(_self->ob_itself,
+ &outRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outRect);
+ return _res;
}
static PyObject *WinObj_BeginUpdate(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef BeginUpdate
- PyMac_PRECHECK(BeginUpdate);
+ PyMac_PRECHECK(BeginUpdate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- BeginUpdate(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ BeginUpdate(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_EndUpdate(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef EndUpdate
- PyMac_PRECHECK(EndUpdate);
+ PyMac_PRECHECK(EndUpdate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- EndUpdate(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ EndUpdate(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_InvalWindowRgn(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RgnHandle region;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RgnHandle region;
#ifndef InvalWindowRgn
- PyMac_PRECHECK(InvalWindowRgn);
+ PyMac_PRECHECK(InvalWindowRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- _err = InvalWindowRgn(_self->ob_itself,
- region);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ _err = InvalWindowRgn(_self->ob_itself,
+ region);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_InvalWindowRect(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
#ifndef InvalWindowRect
- PyMac_PRECHECK(InvalWindowRect);
+ PyMac_PRECHECK(InvalWindowRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &bounds))
- return NULL;
- _err = InvalWindowRect(_self->ob_itself,
- &bounds);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &bounds))
+ return NULL;
+ _err = InvalWindowRect(_self->ob_itself,
+ &bounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ValidWindowRgn(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- RgnHandle region;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ RgnHandle region;
#ifndef ValidWindowRgn
- PyMac_PRECHECK(ValidWindowRgn);
+ PyMac_PRECHECK(ValidWindowRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &region))
- return NULL;
- _err = ValidWindowRgn(_self->ob_itself,
- region);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &region))
+ return NULL;
+ _err = ValidWindowRgn(_self->ob_itself,
+ region);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ValidWindowRect(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect bounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect bounds;
#ifndef ValidWindowRect
- PyMac_PRECHECK(ValidWindowRect);
+ PyMac_PRECHECK(ValidWindowRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &bounds))
- return NULL;
- _err = ValidWindowRect(_self->ob_itself,
- &bounds);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &bounds))
+ return NULL;
+ _err = ValidWindowRect(_self->ob_itself,
+ &bounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_DrawGrowIcon(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef DrawGrowIcon
- PyMac_PRECHECK(DrawGrowIcon);
+ PyMac_PRECHECK(DrawGrowIcon);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- DrawGrowIcon(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ DrawGrowIcon(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWTitle(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 title;
+ PyObject *_res = NULL;
+ Str255 title;
#ifndef SetWTitle
- PyMac_PRECHECK(SetWTitle);
+ PyMac_PRECHECK(SetWTitle);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetStr255, title))
- return NULL;
- SetWTitle(_self->ob_itself,
- title);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetStr255, title))
+ return NULL;
+ SetWTitle(_self->ob_itself,
+ title);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWTitle(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Str255 title;
+ PyObject *_res = NULL;
+ Str255 title;
#ifndef GetWTitle
- PyMac_PRECHECK(GetWTitle);
+ PyMac_PRECHECK(GetWTitle);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetWTitle(_self->ob_itself,
- title);
- _res = Py_BuildValue("O&",
- PyMac_BuildStr255, title);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetWTitle(_self->ob_itself,
+ title);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildStr255, title);
+ return _res;
}
static PyObject *WinObj_SetWindowTitleWithCFString(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef inString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef inString;
#ifndef SetWindowTitleWithCFString
- PyMac_PRECHECK(SetWindowTitleWithCFString);
+ PyMac_PRECHECK(SetWindowTitleWithCFString);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- CFStringRefObj_Convert, &inString))
- return NULL;
- _err = SetWindowTitleWithCFString(_self->ob_itself,
- inString);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ CFStringRefObj_Convert, &inString))
+ return NULL;
+ _err = SetWindowTitleWithCFString(_self->ob_itself,
+ inString);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_CopyWindowTitleAsCFString(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- CFStringRef outString;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ CFStringRef outString;
#ifndef CopyWindowTitleAsCFString
- PyMac_PRECHECK(CopyWindowTitleAsCFString);
+ PyMac_PRECHECK(CopyWindowTitleAsCFString);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = CopyWindowTitleAsCFString(_self->ob_itself,
- &outString);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- CFStringRefObj_New, outString);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = CopyWindowTitleAsCFString(_self->ob_itself,
+ &outString);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ CFStringRefObj_New, outString);
+ return _res;
}
static PyObject *WinObj_SetWindowProxyFSSpec(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- FSSpec inFile;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ FSSpec inFile;
#ifndef SetWindowProxyFSSpec
- PyMac_PRECHECK(SetWindowProxyFSSpec);
+ PyMac_PRECHECK(SetWindowProxyFSSpec);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetFSSpec, &inFile))
- return NULL;
- _err = SetWindowProxyFSSpec(_self->ob_itself,
- &inFile);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetFSSpec, &inFile))
+ return NULL;
+ _err = SetWindowProxyFSSpec(_self->ob_itself,
+ &inFile);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowProxyFSSpec(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- FSSpec outFile;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ FSSpec outFile;
#ifndef GetWindowProxyFSSpec
- PyMac_PRECHECK(GetWindowProxyFSSpec);
+ PyMac_PRECHECK(GetWindowProxyFSSpec);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowProxyFSSpec(_self->ob_itself,
- &outFile);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildFSSpec, &outFile);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowProxyFSSpec(_self->ob_itself,
+ &outFile);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildFSSpec, &outFile);
+ return _res;
}
static PyObject *WinObj_SetWindowProxyAlias(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- AliasHandle inAlias;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ AliasHandle inAlias;
#ifndef SetWindowProxyAlias
- PyMac_PRECHECK(SetWindowProxyAlias);
+ PyMac_PRECHECK(SetWindowProxyAlias);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inAlias))
- return NULL;
- _err = SetWindowProxyAlias(_self->ob_itself,
- inAlias);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inAlias))
+ return NULL;
+ _err = SetWindowProxyAlias(_self->ob_itself,
+ inAlias);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowProxyAlias(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- AliasHandle alias;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ AliasHandle alias;
#ifndef GetWindowProxyAlias
- PyMac_PRECHECK(GetWindowProxyAlias);
+ PyMac_PRECHECK(GetWindowProxyAlias);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowProxyAlias(_self->ob_itself,
- &alias);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, alias);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowProxyAlias(_self->ob_itself,
+ &alias);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, alias);
+ return _res;
}
static PyObject *WinObj_SetWindowProxyCreatorAndType(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType fileCreator;
- OSType fileType;
- SInt16 vRefNum;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType fileCreator;
+ OSType fileType;
+ SInt16 vRefNum;
#ifndef SetWindowProxyCreatorAndType
- PyMac_PRECHECK(SetWindowProxyCreatorAndType);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&h",
- PyMac_GetOSType, &fileCreator,
- PyMac_GetOSType, &fileType,
- &vRefNum))
- return NULL;
- _err = SetWindowProxyCreatorAndType(_self->ob_itself,
- fileCreator,
- fileType,
- vRefNum);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SetWindowProxyCreatorAndType);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&h",
+ PyMac_GetOSType, &fileCreator,
+ PyMac_GetOSType, &fileType,
+ &vRefNum))
+ return NULL;
+ _err = SetWindowProxyCreatorAndType(_self->ob_itself,
+ fileCreator,
+ fileType,
+ vRefNum);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowProxyIcon(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- IconRef outIcon;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ IconRef outIcon;
#ifndef GetWindowProxyIcon
- PyMac_PRECHECK(GetWindowProxyIcon);
+ PyMac_PRECHECK(GetWindowProxyIcon);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowProxyIcon(_self->ob_itself,
- &outIcon);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- ResObj_New, outIcon);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowProxyIcon(_self->ob_itself,
+ &outIcon);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ ResObj_New, outIcon);
+ return _res;
}
static PyObject *WinObj_SetWindowProxyIcon(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- IconRef icon;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ IconRef icon;
#ifndef SetWindowProxyIcon
- PyMac_PRECHECK(SetWindowProxyIcon);
+ PyMac_PRECHECK(SetWindowProxyIcon);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &icon))
- return NULL;
- _err = SetWindowProxyIcon(_self->ob_itself,
- icon);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &icon))
+ return NULL;
+ _err = SetWindowProxyIcon(_self->ob_itself,
+ icon);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_RemoveWindowProxy(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef RemoveWindowProxy
- PyMac_PRECHECK(RemoveWindowProxy);
+ PyMac_PRECHECK(RemoveWindowProxy);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = RemoveWindowProxy(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = RemoveWindowProxy(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_BeginWindowProxyDrag(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DragReference outNewDrag;
- RgnHandle outDragOutlineRgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DragReference outNewDrag;
+ RgnHandle outDragOutlineRgn;
#ifndef BeginWindowProxyDrag
- PyMac_PRECHECK(BeginWindowProxyDrag);
+ PyMac_PRECHECK(BeginWindowProxyDrag);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &outDragOutlineRgn))
- return NULL;
- _err = BeginWindowProxyDrag(_self->ob_itself,
- &outNewDrag,
- outDragOutlineRgn);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- DragObj_New, outNewDrag);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &outDragOutlineRgn))
+ return NULL;
+ _err = BeginWindowProxyDrag(_self->ob_itself,
+ &outNewDrag,
+ outDragOutlineRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ DragObj_New, outNewDrag);
+ return _res;
}
static PyObject *WinObj_EndWindowProxyDrag(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- DragReference theDrag;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ DragReference theDrag;
#ifndef EndWindowProxyDrag
- PyMac_PRECHECK(EndWindowProxyDrag);
+ PyMac_PRECHECK(EndWindowProxyDrag);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- DragObj_Convert, &theDrag))
- return NULL;
- _err = EndWindowProxyDrag(_self->ob_itself,
- theDrag);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ DragObj_Convert, &theDrag))
+ return NULL;
+ _err = EndWindowProxyDrag(_self->ob_itself,
+ theDrag);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_TrackWindowProxyFromExistingDrag(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point startPt;
- DragReference drag;
- RgnHandle inDragOutlineRgn;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point startPt;
+ DragReference drag;
+ RgnHandle inDragOutlineRgn;
#ifndef TrackWindowProxyFromExistingDrag
- PyMac_PRECHECK(TrackWindowProxyFromExistingDrag);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&O&",
- PyMac_GetPoint, &startPt,
- DragObj_Convert, &drag,
- ResObj_Convert, &inDragOutlineRgn))
- return NULL;
- _err = TrackWindowProxyFromExistingDrag(_self->ob_itself,
- startPt,
- drag,
- inDragOutlineRgn);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(TrackWindowProxyFromExistingDrag);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&O&",
+ PyMac_GetPoint, &startPt,
+ DragObj_Convert, &drag,
+ ResObj_Convert, &inDragOutlineRgn))
+ return NULL;
+ _err = TrackWindowProxyFromExistingDrag(_self->ob_itself,
+ startPt,
+ drag,
+ inDragOutlineRgn);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_TrackWindowProxyDrag(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point startPt;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point startPt;
#ifndef TrackWindowProxyDrag
- PyMac_PRECHECK(TrackWindowProxyDrag);
+ PyMac_PRECHECK(TrackWindowProxyDrag);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &startPt))
- return NULL;
- _err = TrackWindowProxyDrag(_self->ob_itself,
- startPt);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &startPt))
+ return NULL;
+ _err = TrackWindowProxyDrag(_self->ob_itself,
+ startPt);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_IsWindowModified(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsWindowModified
- PyMac_PRECHECK(IsWindowModified);
+ PyMac_PRECHECK(IsWindowModified);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsWindowModified(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsWindowModified(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_SetWindowModified(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean modified;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean modified;
#ifndef SetWindowModified
- PyMac_PRECHECK(SetWindowModified);
+ PyMac_PRECHECK(SetWindowModified);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &modified))
- return NULL;
- _err = SetWindowModified(_self->ob_itself,
- modified);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &modified))
+ return NULL;
+ _err = SetWindowModified(_self->ob_itself,
+ modified);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_IsWindowPathSelectClick(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord event;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord event;
#ifndef IsWindowPathSelectClick
- PyMac_PRECHECK(IsWindowPathSelectClick);
+ PyMac_PRECHECK(IsWindowPathSelectClick);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetEventRecord, &event))
- return NULL;
- _rv = IsWindowPathSelectClick(_self->ob_itself,
- &event);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetEventRecord, &event))
+ return NULL;
+ _rv = IsWindowPathSelectClick(_self->ob_itself,
+ &event);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_WindowPathSelect(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- MenuHandle menu;
- SInt32 outMenuResult;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ MenuHandle menu;
+ SInt32 outMenuResult;
#ifndef WindowPathSelect
- PyMac_PRECHECK(WindowPathSelect);
+ PyMac_PRECHECK(WindowPathSelect);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- MenuObj_Convert, &menu))
- return NULL;
- _err = WindowPathSelect(_self->ob_itself,
- menu,
- &outMenuResult);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- outMenuResult);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ MenuObj_Convert, &menu))
+ return NULL;
+ _err = WindowPathSelect(_self->ob_itself,
+ menu,
+ &outMenuResult);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ outMenuResult);
+ return _res;
}
static PyObject *WinObj_HiliteWindowFrameForDrag(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean hilited;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean hilited;
#ifndef HiliteWindowFrameForDrag
- PyMac_PRECHECK(HiliteWindowFrameForDrag);
+ PyMac_PRECHECK(HiliteWindowFrameForDrag);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &hilited))
- return NULL;
- _err = HiliteWindowFrameForDrag(_self->ob_itself,
- hilited);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &hilited))
+ return NULL;
+ _err = HiliteWindowFrameForDrag(_self->ob_itself,
+ hilited);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_TransitionWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowTransitionEffect inEffect;
- WindowTransitionAction inAction;
- Rect inRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowTransitionEffect inEffect;
+ WindowTransitionAction inAction;
+ Rect inRect;
#ifndef TransitionWindow
- PyMac_PRECHECK(TransitionWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "llO&",
- &inEffect,
- &inAction,
- PyMac_GetRect, &inRect))
- return NULL;
- _err = TransitionWindow(_self->ob_itself,
- inEffect,
- inAction,
- &inRect);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(TransitionWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "llO&",
+ &inEffect,
+ &inAction,
+ PyMac_GetRect, &inRect))
+ return NULL;
+ _err = TransitionWindow(_self->ob_itself,
+ inEffect,
+ inAction,
+ &inRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_TransitionWindowAndParent(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inParentWindow;
- WindowTransitionEffect inEffect;
- WindowTransitionAction inAction;
- Rect inRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inParentWindow;
+ WindowTransitionEffect inEffect;
+ WindowTransitionAction inAction;
+ Rect inRect;
#ifndef TransitionWindowAndParent
- PyMac_PRECHECK(TransitionWindowAndParent);
-#endif
- if (!PyArg_ParseTuple(_args, "O&llO&",
- WinObj_Convert, &inParentWindow,
- &inEffect,
- &inAction,
- PyMac_GetRect, &inRect))
- return NULL;
- _err = TransitionWindowAndParent(_self->ob_itself,
- inParentWindow,
- inEffect,
- inAction,
- &inRect);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(TransitionWindowAndParent);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&llO&",
+ WinObj_Convert, &inParentWindow,
+ &inEffect,
+ &inAction,
+ PyMac_GetRect, &inRect))
+ return NULL;
+ _err = TransitionWindowAndParent(_self->ob_itself,
+ inParentWindow,
+ inEffect,
+ inAction,
+ &inRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_MacMoveWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short hGlobal;
- short vGlobal;
- Boolean front;
+ PyObject *_res = NULL;
+ short hGlobal;
+ short vGlobal;
+ Boolean front;
#ifndef MacMoveWindow
- PyMac_PRECHECK(MacMoveWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &hGlobal,
- &vGlobal,
- &front))
- return NULL;
- MacMoveWindow(_self->ob_itself,
- hGlobal,
- vGlobal,
- front);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(MacMoveWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &hGlobal,
+ &vGlobal,
+ &front))
+ return NULL;
+ MacMoveWindow(_self->ob_itself,
+ hGlobal,
+ vGlobal,
+ front);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SizeWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short w;
- short h;
- Boolean fUpdate;
+ PyObject *_res = NULL;
+ short w;
+ short h;
+ Boolean fUpdate;
#ifndef SizeWindow
- PyMac_PRECHECK(SizeWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &w,
- &h,
- &fUpdate))
- return NULL;
- SizeWindow(_self->ob_itself,
- w,
- h,
- fUpdate);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(SizeWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &w,
+ &h,
+ &fUpdate))
+ return NULL;
+ SizeWindow(_self->ob_itself,
+ w,
+ h,
+ fUpdate);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GrowWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- Point startPt;
- Rect bBox;
+ PyObject *_res = NULL;
+ long _rv;
+ Point startPt;
+ Rect bBox;
#ifndef GrowWindow
- PyMac_PRECHECK(GrowWindow);
+ PyMac_PRECHECK(GrowWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &startPt,
- PyMac_GetRect, &bBox))
- return NULL;
- _rv = GrowWindow(_self->ob_itself,
- startPt,
- &bBox);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &startPt,
+ PyMac_GetRect, &bBox))
+ return NULL;
+ _rv = GrowWindow(_self->ob_itself,
+ startPt,
+ &bBox);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *WinObj_DragWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Point startPt;
- Rect boundsRect;
+ PyObject *_res = NULL;
+ Point startPt;
+ Rect boundsRect;
#ifndef DragWindow
- PyMac_PRECHECK(DragWindow);
+ PyMac_PRECHECK(DragWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &startPt,
- PyMac_GetRect, &boundsRect))
- return NULL;
- DragWindow(_self->ob_itself,
- startPt,
- &boundsRect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &startPt,
+ PyMac_GetRect, &boundsRect))
+ return NULL;
+ DragWindow(_self->ob_itself,
+ startPt,
+ &boundsRect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ZoomWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPartCode partCode;
- Boolean front;
+ PyObject *_res = NULL;
+ WindowPartCode partCode;
+ Boolean front;
#ifndef ZoomWindow
- PyMac_PRECHECK(ZoomWindow);
+ PyMac_PRECHECK(ZoomWindow);
#endif
- if (!PyArg_ParseTuple(_args, "hb",
- &partCode,
- &front))
- return NULL;
- ZoomWindow(_self->ob_itself,
- partCode,
- front);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hb",
+ &partCode,
+ &front))
+ return NULL;
+ ZoomWindow(_self->ob_itself,
+ partCode,
+ front);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_IsWindowCollapsable(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsWindowCollapsable
- PyMac_PRECHECK(IsWindowCollapsable);
+ PyMac_PRECHECK(IsWindowCollapsable);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsWindowCollapsable(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsWindowCollapsable(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_IsWindowCollapsed(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsWindowCollapsed
- PyMac_PRECHECK(IsWindowCollapsed);
+ PyMac_PRECHECK(IsWindowCollapsed);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsWindowCollapsed(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsWindowCollapsed(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_CollapseWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean collapse;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean collapse;
#ifndef CollapseWindow
- PyMac_PRECHECK(CollapseWindow);
+ PyMac_PRECHECK(CollapseWindow);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &collapse))
- return NULL;
- _err = CollapseWindow(_self->ob_itself,
- collapse);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &collapse))
+ return NULL;
+ _err = CollapseWindow(_self->ob_itself,
+ collapse);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowBounds(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowRegionCode regionCode;
- Rect globalBounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowRegionCode regionCode;
+ Rect globalBounds;
#ifndef GetWindowBounds
- PyMac_PRECHECK(GetWindowBounds);
+ PyMac_PRECHECK(GetWindowBounds);
#endif
- if (!PyArg_ParseTuple(_args, "H",
- &regionCode))
- return NULL;
- _err = GetWindowBounds(_self->ob_itself,
- regionCode,
- &globalBounds);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &globalBounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, "H",
+ &regionCode))
+ return NULL;
+ _err = GetWindowBounds(_self->ob_itself,
+ regionCode,
+ &globalBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &globalBounds);
+ return _res;
}
static PyObject *WinObj_ResizeWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point inStartPoint;
- Rect inSizeConstraints;
- Rect outNewContentRect;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point inStartPoint;
+ Rect inSizeConstraints;
+ Rect outNewContentRect;
#ifndef ResizeWindow
- PyMac_PRECHECK(ResizeWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetPoint, &inStartPoint,
- PyMac_GetRect, &inSizeConstraints))
- return NULL;
- _rv = ResizeWindow(_self->ob_itself,
- inStartPoint,
- &inSizeConstraints,
- &outNewContentRect);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildRect, &outNewContentRect);
- return _res;
+ PyMac_PRECHECK(ResizeWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetPoint, &inStartPoint,
+ PyMac_GetRect, &inSizeConstraints))
+ return NULL;
+ _rv = ResizeWindow(_self->ob_itself,
+ inStartPoint,
+ &inSizeConstraints,
+ &outNewContentRect);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildRect, &outNewContentRect);
+ return _res;
}
static PyObject *WinObj_SetWindowBounds(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowRegionCode regionCode;
- Rect globalBounds;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowRegionCode regionCode;
+ Rect globalBounds;
#ifndef SetWindowBounds
- PyMac_PRECHECK(SetWindowBounds);
+ PyMac_PRECHECK(SetWindowBounds);
#endif
- if (!PyArg_ParseTuple(_args, "HO&",
- &regionCode,
- PyMac_GetRect, &globalBounds))
- return NULL;
- _err = SetWindowBounds(_self->ob_itself,
- regionCode,
- &globalBounds);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "HO&",
+ &regionCode,
+ PyMac_GetRect, &globalBounds))
+ return NULL;
+ _err = SetWindowBounds(_self->ob_itself,
+ regionCode,
+ &globalBounds);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_RepositionWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr parentWindow;
- WindowPositionMethod method;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr parentWindow;
+ WindowPositionMethod method;
#ifndef RepositionWindow
- PyMac_PRECHECK(RepositionWindow);
+ PyMac_PRECHECK(RepositionWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- WinObj_Convert, &parentWindow,
- &method))
- return NULL;
- _err = RepositionWindow(_self->ob_itself,
- parentWindow,
- method);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&l",
+ WinObj_Convert, &parentWindow,
+ &method))
+ return NULL;
+ _err = RepositionWindow(_self->ob_itself,
+ parentWindow,
+ method);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_MoveWindowStructure(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- short hGlobal;
- short vGlobal;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ short hGlobal;
+ short vGlobal;
#ifndef MoveWindowStructure
- PyMac_PRECHECK(MoveWindowStructure);
+ PyMac_PRECHECK(MoveWindowStructure);
#endif
- if (!PyArg_ParseTuple(_args, "hh",
- &hGlobal,
- &vGlobal))
- return NULL;
- _err = MoveWindowStructure(_self->ob_itself,
- hGlobal,
- vGlobal);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "hh",
+ &hGlobal,
+ &vGlobal))
+ return NULL;
+ _err = MoveWindowStructure(_self->ob_itself,
+ hGlobal,
+ vGlobal);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_IsWindowInStandardState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point inIdealSize;
- Rect outIdealStandardState;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point inIdealSize;
+ Rect outIdealStandardState;
#ifndef IsWindowInStandardState
- PyMac_PRECHECK(IsWindowInStandardState);
+ PyMac_PRECHECK(IsWindowInStandardState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &inIdealSize))
- return NULL;
- _rv = IsWindowInStandardState(_self->ob_itself,
- &inIdealSize,
- &outIdealStandardState);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildRect, &outIdealStandardState);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &inIdealSize))
+ return NULL;
+ _rv = IsWindowInStandardState(_self->ob_itself,
+ &inIdealSize,
+ &outIdealStandardState);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildRect, &outIdealStandardState);
+ return _res;
}
static PyObject *WinObj_ZoomWindowIdeal(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPartCode inPartCode;
- Point ioIdealSize;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPartCode inPartCode;
+ Point ioIdealSize;
#ifndef ZoomWindowIdeal
- PyMac_PRECHECK(ZoomWindowIdeal);
+ PyMac_PRECHECK(ZoomWindowIdeal);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &inPartCode))
- return NULL;
- _err = ZoomWindowIdeal(_self->ob_itself,
- inPartCode,
- &ioIdealSize);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildPoint, ioIdealSize);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &inPartCode))
+ return NULL;
+ _err = ZoomWindowIdeal(_self->ob_itself,
+ inPartCode,
+ &ioIdealSize);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildPoint, ioIdealSize);
+ return _res;
}
static PyObject *WinObj_GetWindowIdealUserState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect outUserState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect outUserState;
#ifndef GetWindowIdealUserState
- PyMac_PRECHECK(GetWindowIdealUserState);
+ PyMac_PRECHECK(GetWindowIdealUserState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetWindowIdealUserState(_self->ob_itself,
- &outUserState);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outUserState);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetWindowIdealUserState(_self->ob_itself,
+ &outUserState);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outUserState);
+ return _res;
}
static PyObject *WinObj_SetWindowIdealUserState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Rect inUserState;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Rect inUserState;
#ifndef SetWindowIdealUserState
- PyMac_PRECHECK(SetWindowIdealUserState);
+ PyMac_PRECHECK(SetWindowIdealUserState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &inUserState))
- return NULL;
- _err = SetWindowIdealUserState(_self->ob_itself,
- &inUserState);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &inUserState))
+ return NULL;
+ _err = SetWindowIdealUserState(_self->ob_itself,
+ &inUserState);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowGreatestAreaDevice(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowRegionCode inRegion;
- GDHandle outGreatestDevice;
- Rect outGreatestDeviceRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowRegionCode inRegion;
+ GDHandle outGreatestDevice;
+ Rect outGreatestDeviceRect;
#ifndef GetWindowGreatestAreaDevice
- PyMac_PRECHECK(GetWindowGreatestAreaDevice);
-#endif
- if (!PyArg_ParseTuple(_args, "H",
- &inRegion))
- return NULL;
- _err = GetWindowGreatestAreaDevice(_self->ob_itself,
- inRegion,
- &outGreatestDevice,
- &outGreatestDeviceRect);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&O&",
- ResObj_New, outGreatestDevice,
- PyMac_BuildRect, &outGreatestDeviceRect);
- return _res;
+ PyMac_PRECHECK(GetWindowGreatestAreaDevice);
+#endif
+ if (!PyArg_ParseTuple(_args, "H",
+ &inRegion))
+ return NULL;
+ _err = GetWindowGreatestAreaDevice(_self->ob_itself,
+ inRegion,
+ &outGreatestDevice,
+ &outGreatestDeviceRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&O&",
+ ResObj_New, outGreatestDevice,
+ PyMac_BuildRect, &outGreatestDeviceRect);
+ return _res;
}
static PyObject *WinObj_ConstrainWindowToScreen(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowRegionCode inRegionCode;
- WindowConstrainOptions inOptions;
- Rect inScreenRect;
- Rect outStructure;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowRegionCode inRegionCode;
+ WindowConstrainOptions inOptions;
+ Rect inScreenRect;
+ Rect outStructure;
#ifndef ConstrainWindowToScreen
- PyMac_PRECHECK(ConstrainWindowToScreen);
-#endif
- if (!PyArg_ParseTuple(_args, "HlO&",
- &inRegionCode,
- &inOptions,
- PyMac_GetRect, &inScreenRect))
- return NULL;
- _err = ConstrainWindowToScreen(_self->ob_itself,
- inRegionCode,
- inOptions,
- &inScreenRect,
- &outStructure);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outStructure);
- return _res;
+ PyMac_PRECHECK(ConstrainWindowToScreen);
+#endif
+ if (!PyArg_ParseTuple(_args, "HlO&",
+ &inRegionCode,
+ &inOptions,
+ PyMac_GetRect, &inScreenRect))
+ return NULL;
+ _err = ConstrainWindowToScreen(_self->ob_itself,
+ inRegionCode,
+ inOptions,
+ &inScreenRect,
+ &outStructure);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outStructure);
+ return _res;
}
static PyObject *WinObj_HideWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef HideWindow
- PyMac_PRECHECK(HideWindow);
+ PyMac_PRECHECK(HideWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- HideWindow(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ HideWindow(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_MacShowWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef MacShowWindow
- PyMac_PRECHECK(MacShowWindow);
+ PyMac_PRECHECK(MacShowWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- MacShowWindow(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ MacShowWindow(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ShowHide(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean showFlag;
+ PyObject *_res = NULL;
+ Boolean showFlag;
#ifndef ShowHide
- PyMac_PRECHECK(ShowHide);
+ PyMac_PRECHECK(ShowHide);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &showFlag))
- return NULL;
- ShowHide(_self->ob_itself,
- showFlag);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &showFlag))
+ return NULL;
+ ShowHide(_self->ob_itself,
+ showFlag);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_MacIsWindowVisible(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef MacIsWindowVisible
- PyMac_PRECHECK(MacIsWindowVisible);
+ PyMac_PRECHECK(MacIsWindowVisible);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MacIsWindowVisible(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MacIsWindowVisible(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_ShowSheetWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr inParentWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr inParentWindow;
#ifndef ShowSheetWindow
- PyMac_PRECHECK(ShowSheetWindow);
+ PyMac_PRECHECK(ShowSheetWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- WinObj_Convert, &inParentWindow))
- return NULL;
- _err = ShowSheetWindow(_self->ob_itself,
- inParentWindow);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ WinObj_Convert, &inParentWindow))
+ return NULL;
+ _err = ShowSheetWindow(_self->ob_itself,
+ inParentWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_HideSheetWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef HideSheetWindow
- PyMac_PRECHECK(HideSheetWindow);
+ PyMac_PRECHECK(HideSheetWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = HideSheetWindow(_self->ob_itself);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = HideSheetWindow(_self->ob_itself);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetSheetWindowParent(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowPtr outParentWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowPtr outParentWindow;
#ifndef GetSheetWindowParent
- PyMac_PRECHECK(GetSheetWindowParent);
+ PyMac_PRECHECK(GetSheetWindowParent);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = GetSheetWindowParent(_self->ob_itself,
- &outParentWindow);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- WinObj_WhichWindow, outParentWindow);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = GetSheetWindowParent(_self->ob_itself,
+ &outParentWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ WinObj_WhichWindow, outParentWindow);
+ return _res;
}
static PyObject *WinObj_GetWindowPropertyAttributes(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyCreator;
- OSType propertyTag;
- UInt32 attributes;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyCreator;
+ OSType propertyTag;
+ UInt32 attributes;
#ifndef GetWindowPropertyAttributes
- PyMac_PRECHECK(GetWindowPropertyAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag))
- return NULL;
- _err = GetWindowPropertyAttributes(_self->ob_itself,
- propertyCreator,
- propertyTag,
- &attributes);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("l",
- attributes);
- return _res;
+ PyMac_PRECHECK(GetWindowPropertyAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag))
+ return NULL;
+ _err = GetWindowPropertyAttributes(_self->ob_itself,
+ propertyCreator,
+ propertyTag,
+ &attributes);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("l",
+ attributes);
+ return _res;
}
static PyObject *WinObj_ChangeWindowPropertyAttributes(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OSType propertyCreator;
- OSType propertyTag;
- UInt32 attributesToSet;
- UInt32 attributesToClear;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OSType propertyCreator;
+ OSType propertyTag;
+ UInt32 attributesToSet;
+ UInt32 attributesToClear;
#ifndef ChangeWindowPropertyAttributes
- PyMac_PRECHECK(ChangeWindowPropertyAttributes);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&ll",
- PyMac_GetOSType, &propertyCreator,
- PyMac_GetOSType, &propertyTag,
- &attributesToSet,
- &attributesToClear))
- return NULL;
- _err = ChangeWindowPropertyAttributes(_self->ob_itself,
- propertyCreator,
- propertyTag,
- attributesToSet,
- attributesToClear);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(ChangeWindowPropertyAttributes);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&ll",
+ PyMac_GetOSType, &propertyCreator,
+ PyMac_GetOSType, &propertyTag,
+ &attributesToSet,
+ &attributesToClear))
+ return NULL;
+ _err = ChangeWindowPropertyAttributes(_self->ob_itself,
+ propertyCreator,
+ propertyTag,
+ attributesToSet,
+ attributesToClear);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_TrackBox(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point thePt;
- WindowPartCode partCode;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point thePt;
+ WindowPartCode partCode;
#ifndef TrackBox
- PyMac_PRECHECK(TrackBox);
+ PyMac_PRECHECK(TrackBox);
#endif
- if (!PyArg_ParseTuple(_args, "O&h",
- PyMac_GetPoint, &thePt,
- &partCode))
- return NULL;
- _rv = TrackBox(_self->ob_itself,
- thePt,
- partCode);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&h",
+ PyMac_GetPoint, &thePt,
+ &partCode))
+ return NULL;
+ _rv = TrackBox(_self->ob_itself,
+ thePt,
+ partCode);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_TrackGoAway(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- Point thePt;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ Point thePt;
#ifndef TrackGoAway
- PyMac_PRECHECK(TrackGoAway);
+ PyMac_PRECHECK(TrackGoAway);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &thePt))
- return NULL;
- _rv = TrackGoAway(_self->ob_itself,
- thePt);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &thePt))
+ return NULL;
+ _rv = TrackGoAway(_self->ob_itself,
+ thePt);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_GetWindowPort(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
#ifndef GetWindowPort
- PyMac_PRECHECK(GetWindowPort);
+ PyMac_PRECHECK(GetWindowPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWindowPort(_self->ob_itself);
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWindowPort(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyObject *WinObj_GetWindowStructurePort(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- CGrafPtr _rv;
+ PyObject *_res = NULL;
+ CGrafPtr _rv;
#ifndef GetWindowStructurePort
- PyMac_PRECHECK(GetWindowStructurePort);
+ PyMac_PRECHECK(GetWindowStructurePort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWindowStructurePort(_self->ob_itself);
- _res = Py_BuildValue("O&",
- GrafObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWindowStructurePort(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ GrafObj_New, _rv);
+ return _res;
}
static PyObject *WinObj_GetWindowKind(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
+ PyObject *_res = NULL;
+ short _rv;
#ifndef GetWindowKind
- PyMac_PRECHECK(GetWindowKind);
+ PyMac_PRECHECK(GetWindowKind);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetWindowKind(_self->ob_itself);
- _res = Py_BuildValue("h",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetWindowKind(_self->ob_itself);
+ _res = Py_BuildValue("h",
+ _rv);
+ return _res;
}
static PyObject *WinObj_IsWindowHilited(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsWindowHilited
- PyMac_PRECHECK(IsWindowHilited);
+ PyMac_PRECHECK(IsWindowHilited);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsWindowHilited(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsWindowHilited(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_IsWindowUpdatePending(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsWindowUpdatePending
- PyMac_PRECHECK(IsWindowUpdatePending);
+ PyMac_PRECHECK(IsWindowUpdatePending);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsWindowUpdatePending(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsWindowUpdatePending(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_MacGetNextWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
#ifndef MacGetNextWindow
- PyMac_PRECHECK(MacGetNextWindow);
+ PyMac_PRECHECK(MacGetNextWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = MacGetNextWindow(_self->ob_itself);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = MacGetNextWindow(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *WinObj_GetWindowStandardState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef GetWindowStandardState
- PyMac_PRECHECK(GetWindowStandardState);
+ PyMac_PRECHECK(GetWindowStandardState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetWindowStandardState(_self->ob_itself,
- &rect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &rect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetWindowStandardState(_self->ob_itself,
+ &rect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &rect);
+ return _res;
}
static PyObject *WinObj_GetWindowUserState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef GetWindowUserState
- PyMac_PRECHECK(GetWindowUserState);
+ PyMac_PRECHECK(GetWindowUserState);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetWindowUserState(_self->ob_itself,
- &rect);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &rect);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetWindowUserState(_self->ob_itself,
+ &rect);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &rect);
+ return _res;
}
static PyObject *WinObj_SetWindowKind(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short kind;
+ PyObject *_res = NULL;
+ short kind;
#ifndef SetWindowKind
- PyMac_PRECHECK(SetWindowKind);
+ PyMac_PRECHECK(SetWindowKind);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &kind))
- return NULL;
- SetWindowKind(_self->ob_itself,
- kind);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &kind))
+ return NULL;
+ SetWindowKind(_self->ob_itself,
+ kind);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWindowStandardState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef SetWindowStandardState
- PyMac_PRECHECK(SetWindowStandardState);
+ PyMac_PRECHECK(SetWindowStandardState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &rect))
- return NULL;
- SetWindowStandardState(_self->ob_itself,
- &rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &rect))
+ return NULL;
+ SetWindowStandardState(_self->ob_itself,
+ &rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetWindowUserState(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect rect;
+ PyObject *_res = NULL;
+ Rect rect;
#ifndef SetWindowUserState
- PyMac_PRECHECK(SetWindowUserState);
+ PyMac_PRECHECK(SetWindowUserState);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetRect, &rect))
- return NULL;
- SetWindowUserState(_self->ob_itself,
- &rect);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetRect, &rect))
+ return NULL;
+ SetWindowUserState(_self->ob_itself,
+ &rect);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_SetPortWindowPort(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef SetPortWindowPort
- PyMac_PRECHECK(SetPortWindowPort);
+ PyMac_PRECHECK(SetPortWindowPort);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- SetPortWindowPort(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ SetPortWindowPort(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowPortBounds(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Rect bounds;
+ PyObject *_res = NULL;
+ Rect bounds;
#ifndef GetWindowPortBounds
- PyMac_PRECHECK(GetWindowPortBounds);
+ PyMac_PRECHECK(GetWindowPortBounds);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- GetWindowPortBounds(_self->ob_itself,
- &bounds);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &bounds);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ GetWindowPortBounds(_self->ob_itself,
+ &bounds);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &bounds);
+ return _res;
}
static PyObject *WinObj_IsWindowVisible(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef IsWindowVisible
- PyMac_PRECHECK(IsWindowVisible);
+ PyMac_PRECHECK(IsWindowVisible);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = IsWindowVisible(_self->ob_itself);
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = IsWindowVisible(_self->ob_itself);
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *WinObj_GetWindowStructureRgn(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle r;
+ PyObject *_res = NULL;
+ RgnHandle r;
#ifndef GetWindowStructureRgn
- PyMac_PRECHECK(GetWindowStructureRgn);
+ PyMac_PRECHECK(GetWindowStructureRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &r))
- return NULL;
- GetWindowStructureRgn(_self->ob_itself,
- r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &r))
+ return NULL;
+ GetWindowStructureRgn(_self->ob_itself,
+ r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowContentRgn(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle r;
+ PyObject *_res = NULL;
+ RgnHandle r;
#ifndef GetWindowContentRgn
- PyMac_PRECHECK(GetWindowContentRgn);
+ PyMac_PRECHECK(GetWindowContentRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &r))
- return NULL;
- GetWindowContentRgn(_self->ob_itself,
- r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &r))
+ return NULL;
+ GetWindowContentRgn(_self->ob_itself,
+ r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetWindowUpdateRgn(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle r;
+ PyObject *_res = NULL;
+ RgnHandle r;
#ifndef GetWindowUpdateRgn
- PyMac_PRECHECK(GetWindowUpdateRgn);
+ PyMac_PRECHECK(GetWindowUpdateRgn);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &r))
- return NULL;
- GetWindowUpdateRgn(_self->ob_itself,
- r);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &r))
+ return NULL;
+ GetWindowUpdateRgn(_self->ob_itself,
+ r);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_GetNextWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
#ifndef GetNextWindow
- PyMac_PRECHECK(GetNextWindow);
+ PyMac_PRECHECK(GetNextWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetNextWindow(_self->ob_itself);
- _res = Py_BuildValue("O&",
- WinObj_WhichWindow, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetNextWindow(_self->ob_itself);
+ _res = Py_BuildValue("O&",
+ WinObj_WhichWindow, _rv);
+ return _res;
}
static PyObject *WinObj_MoveWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short hGlobal;
- short vGlobal;
- Boolean front;
+ PyObject *_res = NULL;
+ short hGlobal;
+ short vGlobal;
+ Boolean front;
#ifndef MoveWindow
- PyMac_PRECHECK(MoveWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "hhb",
- &hGlobal,
- &vGlobal,
- &front))
- return NULL;
- MoveWindow(_self->ob_itself,
- hGlobal,
- vGlobal,
- front);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ PyMac_PRECHECK(MoveWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "hhb",
+ &hGlobal,
+ &vGlobal,
+ &front))
+ return NULL;
+ MoveWindow(_self->ob_itself,
+ hGlobal,
+ vGlobal,
+ front);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_ShowWindow(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
#ifndef ShowWindow
- PyMac_PRECHECK(ShowWindow);
+ PyMac_PRECHECK(ShowWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- ShowWindow(_self->ob_itself);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ ShowWindow(_self->ob_itself);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *WinObj_AutoDispose(WindowObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- int onoff, old = 0;
- if (!PyArg_ParseTuple(_args, "i", &onoff))
- return NULL;
- if ( _self->ob_freeit )
- old = 1;
- if ( onoff )
- _self->ob_freeit = PyMac_AutoDisposeWindow;
- else
- _self->ob_freeit = NULL;
- _res = Py_BuildValue("i", old);
- return _res;
+ int onoff, old = 0;
+ if (!PyArg_ParseTuple(_args, "i", &onoff))
+ return NULL;
+ if ( _self->ob_freeit )
+ old = 1;
+ if ( onoff )
+ _self->ob_freeit = PyMac_AutoDisposeWindow;
+ else
+ _self->ob_freeit = NULL;
+ _res = Py_BuildValue("i", old);
+ return _res;
}
static PyMethodDef WinObj_methods[] = {
- {"GetWindowOwnerCount", (PyCFunction)WinObj_GetWindowOwnerCount, 1,
- PyDoc_STR("() -> (UInt32 outCount)")},
- {"CloneWindow", (PyCFunction)WinObj_CloneWindow, 1,
- PyDoc_STR("() -> None")},
- {"GetWindowRetainCount", (PyCFunction)WinObj_GetWindowRetainCount, 1,
- PyDoc_STR("() -> (ItemCount _rv)")},
- {"RetainWindow", (PyCFunction)WinObj_RetainWindow, 1,
- PyDoc_STR("() -> None")},
- {"ReleaseWindow", (PyCFunction)WinObj_ReleaseWindow, 1,
- PyDoc_STR("() -> None")},
- {"ReshapeCustomWindow", (PyCFunction)WinObj_ReshapeCustomWindow, 1,
- PyDoc_STR("() -> None")},
- {"GetWindowWidgetHilite", (PyCFunction)WinObj_GetWindowWidgetHilite, 1,
- PyDoc_STR("() -> (WindowDefPartCode outHilite)")},
- {"GetWindowClass", (PyCFunction)WinObj_GetWindowClass, 1,
- PyDoc_STR("() -> (WindowClass outClass)")},
- {"GetWindowAttributes", (PyCFunction)WinObj_GetWindowAttributes, 1,
- PyDoc_STR("() -> (WindowAttributes outAttributes)")},
- {"ChangeWindowAttributes", (PyCFunction)WinObj_ChangeWindowAttributes, 1,
- PyDoc_STR("(WindowAttributes setTheseAttributes, WindowAttributes clearTheseAttributes) -> None")},
- {"SetWindowClass", (PyCFunction)WinObj_SetWindowClass, 1,
- PyDoc_STR("(WindowClass inWindowClass) -> None")},
- {"SetWindowModality", (PyCFunction)WinObj_SetWindowModality, 1,
- PyDoc_STR("(WindowModality inModalKind, WindowPtr inUnavailableWindow) -> None")},
- {"GetWindowModality", (PyCFunction)WinObj_GetWindowModality, 1,
- PyDoc_STR("() -> (WindowModality outModalKind, WindowPtr outUnavailableWindow)")},
- {"SetWindowContentColor", (PyCFunction)WinObj_SetWindowContentColor, 1,
- PyDoc_STR("(RGBColor color) -> None")},
- {"GetWindowContentColor", (PyCFunction)WinObj_GetWindowContentColor, 1,
- PyDoc_STR("() -> (RGBColor color)")},
- {"GetWindowContentPattern", (PyCFunction)WinObj_GetWindowContentPattern, 1,
- PyDoc_STR("(PixPatHandle outPixPat) -> None")},
- {"SetWindowContentPattern", (PyCFunction)WinObj_SetWindowContentPattern, 1,
- PyDoc_STR("(PixPatHandle pixPat) -> None")},
- {"ScrollWindowRect", (PyCFunction)WinObj_ScrollWindowRect, 1,
- PyDoc_STR("(Rect inScrollRect, SInt16 inHPixels, SInt16 inVPixels, ScrollWindowOptions inOptions, RgnHandle outExposedRgn) -> None")},
- {"ScrollWindowRegion", (PyCFunction)WinObj_ScrollWindowRegion, 1,
- PyDoc_STR("(RgnHandle inScrollRgn, SInt16 inHPixels, SInt16 inVPixels, ScrollWindowOptions inOptions, RgnHandle outExposedRgn) -> None")},
- {"ClipAbove", (PyCFunction)WinObj_ClipAbove, 1,
- PyDoc_STR("() -> None")},
- {"PaintOne", (PyCFunction)WinObj_PaintOne, 1,
- PyDoc_STR("(RgnHandle clobberedRgn) -> None")},
- {"PaintBehind", (PyCFunction)WinObj_PaintBehind, 1,
- PyDoc_STR("(RgnHandle clobberedRgn) -> None")},
- {"CalcVis", (PyCFunction)WinObj_CalcVis, 1,
- PyDoc_STR("() -> None")},
- {"CalcVisBehind", (PyCFunction)WinObj_CalcVisBehind, 1,
- PyDoc_STR("(RgnHandle clobberedRgn) -> None")},
- {"BringToFront", (PyCFunction)WinObj_BringToFront, 1,
- PyDoc_STR("() -> None")},
- {"SendBehind", (PyCFunction)WinObj_SendBehind, 1,
- PyDoc_STR("(WindowPtr behindWindow) -> None")},
- {"SelectWindow", (PyCFunction)WinObj_SelectWindow, 1,
- PyDoc_STR("() -> None")},
- {"GetNextWindowOfClass", (PyCFunction)WinObj_GetNextWindowOfClass, 1,
- PyDoc_STR("(WindowClass inWindowClass, Boolean mustBeVisible) -> (WindowPtr _rv)")},
- {"SetWindowAlternateTitle", (PyCFunction)WinObj_SetWindowAlternateTitle, 1,
- PyDoc_STR("(CFStringRef inTitle) -> None")},
- {"CopyWindowAlternateTitle", (PyCFunction)WinObj_CopyWindowAlternateTitle, 1,
- PyDoc_STR("() -> (CFStringRef outTitle)")},
- {"HiliteWindow", (PyCFunction)WinObj_HiliteWindow, 1,
- PyDoc_STR("(Boolean fHilite) -> None")},
- {"SetWRefCon", (PyCFunction)WinObj_SetWRefCon, 1,
- PyDoc_STR("(long data) -> None")},
- {"GetWRefCon", (PyCFunction)WinObj_GetWRefCon, 1,
- PyDoc_STR("() -> (long _rv)")},
- {"SetWindowPic", (PyCFunction)WinObj_SetWindowPic, 1,
- PyDoc_STR("(PicHandle pic) -> None")},
- {"GetWindowPic", (PyCFunction)WinObj_GetWindowPic, 1,
- PyDoc_STR("() -> (PicHandle _rv)")},
- {"GetWVariant", (PyCFunction)WinObj_GetWVariant, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"GetWindowFeatures", (PyCFunction)WinObj_GetWindowFeatures, 1,
- PyDoc_STR("() -> (UInt32 outFeatures)")},
- {"GetWindowRegion", (PyCFunction)WinObj_GetWindowRegion, 1,
- PyDoc_STR("(WindowRegionCode inRegionCode, RgnHandle ioWinRgn) -> None")},
- {"GetWindowStructureWidths", (PyCFunction)WinObj_GetWindowStructureWidths, 1,
- PyDoc_STR("() -> (Rect outRect)")},
- {"BeginUpdate", (PyCFunction)WinObj_BeginUpdate, 1,
- PyDoc_STR("() -> None")},
- {"EndUpdate", (PyCFunction)WinObj_EndUpdate, 1,
- PyDoc_STR("() -> None")},
- {"InvalWindowRgn", (PyCFunction)WinObj_InvalWindowRgn, 1,
- PyDoc_STR("(RgnHandle region) -> None")},
- {"InvalWindowRect", (PyCFunction)WinObj_InvalWindowRect, 1,
- PyDoc_STR("(Rect bounds) -> None")},
- {"ValidWindowRgn", (PyCFunction)WinObj_ValidWindowRgn, 1,
- PyDoc_STR("(RgnHandle region) -> None")},
- {"ValidWindowRect", (PyCFunction)WinObj_ValidWindowRect, 1,
- PyDoc_STR("(Rect bounds) -> None")},
- {"DrawGrowIcon", (PyCFunction)WinObj_DrawGrowIcon, 1,
- PyDoc_STR("() -> None")},
- {"SetWTitle", (PyCFunction)WinObj_SetWTitle, 1,
- PyDoc_STR("(Str255 title) -> None")},
- {"GetWTitle", (PyCFunction)WinObj_GetWTitle, 1,
- PyDoc_STR("() -> (Str255 title)")},
- {"SetWindowTitleWithCFString", (PyCFunction)WinObj_SetWindowTitleWithCFString, 1,
- PyDoc_STR("(CFStringRef inString) -> None")},
- {"CopyWindowTitleAsCFString", (PyCFunction)WinObj_CopyWindowTitleAsCFString, 1,
- PyDoc_STR("() -> (CFStringRef outString)")},
- {"SetWindowProxyFSSpec", (PyCFunction)WinObj_SetWindowProxyFSSpec, 1,
- PyDoc_STR("(FSSpec inFile) -> None")},
- {"GetWindowProxyFSSpec", (PyCFunction)WinObj_GetWindowProxyFSSpec, 1,
- PyDoc_STR("() -> (FSSpec outFile)")},
- {"SetWindowProxyAlias", (PyCFunction)WinObj_SetWindowProxyAlias, 1,
- PyDoc_STR("(AliasHandle inAlias) -> None")},
- {"GetWindowProxyAlias", (PyCFunction)WinObj_GetWindowProxyAlias, 1,
- PyDoc_STR("() -> (AliasHandle alias)")},
- {"SetWindowProxyCreatorAndType", (PyCFunction)WinObj_SetWindowProxyCreatorAndType, 1,
- PyDoc_STR("(OSType fileCreator, OSType fileType, SInt16 vRefNum) -> None")},
- {"GetWindowProxyIcon", (PyCFunction)WinObj_GetWindowProxyIcon, 1,
- PyDoc_STR("() -> (IconRef outIcon)")},
- {"SetWindowProxyIcon", (PyCFunction)WinObj_SetWindowProxyIcon, 1,
- PyDoc_STR("(IconRef icon) -> None")},
- {"RemoveWindowProxy", (PyCFunction)WinObj_RemoveWindowProxy, 1,
- PyDoc_STR("() -> None")},
- {"BeginWindowProxyDrag", (PyCFunction)WinObj_BeginWindowProxyDrag, 1,
- PyDoc_STR("(RgnHandle outDragOutlineRgn) -> (DragReference outNewDrag)")},
- {"EndWindowProxyDrag", (PyCFunction)WinObj_EndWindowProxyDrag, 1,
- PyDoc_STR("(DragReference theDrag) -> None")},
- {"TrackWindowProxyFromExistingDrag", (PyCFunction)WinObj_TrackWindowProxyFromExistingDrag, 1,
- PyDoc_STR("(Point startPt, DragReference drag, RgnHandle inDragOutlineRgn) -> None")},
- {"TrackWindowProxyDrag", (PyCFunction)WinObj_TrackWindowProxyDrag, 1,
- PyDoc_STR("(Point startPt) -> None")},
- {"IsWindowModified", (PyCFunction)WinObj_IsWindowModified, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"SetWindowModified", (PyCFunction)WinObj_SetWindowModified, 1,
- PyDoc_STR("(Boolean modified) -> None")},
- {"IsWindowPathSelectClick", (PyCFunction)WinObj_IsWindowPathSelectClick, 1,
- PyDoc_STR("(EventRecord event) -> (Boolean _rv)")},
- {"WindowPathSelect", (PyCFunction)WinObj_WindowPathSelect, 1,
- PyDoc_STR("(MenuHandle menu) -> (SInt32 outMenuResult)")},
- {"HiliteWindowFrameForDrag", (PyCFunction)WinObj_HiliteWindowFrameForDrag, 1,
- PyDoc_STR("(Boolean hilited) -> None")},
- {"TransitionWindow", (PyCFunction)WinObj_TransitionWindow, 1,
- PyDoc_STR("(WindowTransitionEffect inEffect, WindowTransitionAction inAction, Rect inRect) -> None")},
- {"TransitionWindowAndParent", (PyCFunction)WinObj_TransitionWindowAndParent, 1,
- PyDoc_STR("(WindowPtr inParentWindow, WindowTransitionEffect inEffect, WindowTransitionAction inAction, Rect inRect) -> None")},
- {"MacMoveWindow", (PyCFunction)WinObj_MacMoveWindow, 1,
- PyDoc_STR("(short hGlobal, short vGlobal, Boolean front) -> None")},
- {"SizeWindow", (PyCFunction)WinObj_SizeWindow, 1,
- PyDoc_STR("(short w, short h, Boolean fUpdate) -> None")},
- {"GrowWindow", (PyCFunction)WinObj_GrowWindow, 1,
- PyDoc_STR("(Point startPt, Rect bBox) -> (long _rv)")},
- {"DragWindow", (PyCFunction)WinObj_DragWindow, 1,
- PyDoc_STR("(Point startPt, Rect boundsRect) -> None")},
- {"ZoomWindow", (PyCFunction)WinObj_ZoomWindow, 1,
- PyDoc_STR("(WindowPartCode partCode, Boolean front) -> None")},
- {"IsWindowCollapsable", (PyCFunction)WinObj_IsWindowCollapsable, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsWindowCollapsed", (PyCFunction)WinObj_IsWindowCollapsed, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"CollapseWindow", (PyCFunction)WinObj_CollapseWindow, 1,
- PyDoc_STR("(Boolean collapse) -> None")},
- {"GetWindowBounds", (PyCFunction)WinObj_GetWindowBounds, 1,
- PyDoc_STR("(WindowRegionCode regionCode) -> (Rect globalBounds)")},
- {"ResizeWindow", (PyCFunction)WinObj_ResizeWindow, 1,
- PyDoc_STR("(Point inStartPoint, Rect inSizeConstraints) -> (Boolean _rv, Rect outNewContentRect)")},
- {"SetWindowBounds", (PyCFunction)WinObj_SetWindowBounds, 1,
- PyDoc_STR("(WindowRegionCode regionCode, Rect globalBounds) -> None")},
- {"RepositionWindow", (PyCFunction)WinObj_RepositionWindow, 1,
- PyDoc_STR("(WindowPtr parentWindow, WindowPositionMethod method) -> None")},
- {"MoveWindowStructure", (PyCFunction)WinObj_MoveWindowStructure, 1,
- PyDoc_STR("(short hGlobal, short vGlobal) -> None")},
- {"IsWindowInStandardState", (PyCFunction)WinObj_IsWindowInStandardState, 1,
- PyDoc_STR("(Point inIdealSize) -> (Boolean _rv, Rect outIdealStandardState)")},
- {"ZoomWindowIdeal", (PyCFunction)WinObj_ZoomWindowIdeal, 1,
- PyDoc_STR("(WindowPartCode inPartCode) -> (Point ioIdealSize)")},
- {"GetWindowIdealUserState", (PyCFunction)WinObj_GetWindowIdealUserState, 1,
- PyDoc_STR("() -> (Rect outUserState)")},
- {"SetWindowIdealUserState", (PyCFunction)WinObj_SetWindowIdealUserState, 1,
- PyDoc_STR("(Rect inUserState) -> None")},
- {"GetWindowGreatestAreaDevice", (PyCFunction)WinObj_GetWindowGreatestAreaDevice, 1,
- PyDoc_STR("(WindowRegionCode inRegion) -> (GDHandle outGreatestDevice, Rect outGreatestDeviceRect)")},
- {"ConstrainWindowToScreen", (PyCFunction)WinObj_ConstrainWindowToScreen, 1,
- PyDoc_STR("(WindowRegionCode inRegionCode, WindowConstrainOptions inOptions, Rect inScreenRect) -> (Rect outStructure)")},
- {"HideWindow", (PyCFunction)WinObj_HideWindow, 1,
- PyDoc_STR("() -> None")},
- {"MacShowWindow", (PyCFunction)WinObj_MacShowWindow, 1,
- PyDoc_STR("() -> None")},
- {"ShowHide", (PyCFunction)WinObj_ShowHide, 1,
- PyDoc_STR("(Boolean showFlag) -> None")},
- {"MacIsWindowVisible", (PyCFunction)WinObj_MacIsWindowVisible, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"ShowSheetWindow", (PyCFunction)WinObj_ShowSheetWindow, 1,
- PyDoc_STR("(WindowPtr inParentWindow) -> None")},
- {"HideSheetWindow", (PyCFunction)WinObj_HideSheetWindow, 1,
- PyDoc_STR("() -> None")},
- {"GetSheetWindowParent", (PyCFunction)WinObj_GetSheetWindowParent, 1,
- PyDoc_STR("() -> (WindowPtr outParentWindow)")},
- {"GetWindowPropertyAttributes", (PyCFunction)WinObj_GetWindowPropertyAttributes, 1,
- PyDoc_STR("(OSType propertyCreator, OSType propertyTag) -> (UInt32 attributes)")},
- {"ChangeWindowPropertyAttributes", (PyCFunction)WinObj_ChangeWindowPropertyAttributes, 1,
- PyDoc_STR("(OSType propertyCreator, OSType propertyTag, UInt32 attributesToSet, UInt32 attributesToClear) -> None")},
- {"TrackBox", (PyCFunction)WinObj_TrackBox, 1,
- PyDoc_STR("(Point thePt, WindowPartCode partCode) -> (Boolean _rv)")},
- {"TrackGoAway", (PyCFunction)WinObj_TrackGoAway, 1,
- PyDoc_STR("(Point thePt) -> (Boolean _rv)")},
- {"GetWindowPort", (PyCFunction)WinObj_GetWindowPort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {"GetWindowStructurePort", (PyCFunction)WinObj_GetWindowStructurePort, 1,
- PyDoc_STR("() -> (CGrafPtr _rv)")},
- {"GetWindowKind", (PyCFunction)WinObj_GetWindowKind, 1,
- PyDoc_STR("() -> (short _rv)")},
- {"IsWindowHilited", (PyCFunction)WinObj_IsWindowHilited, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"IsWindowUpdatePending", (PyCFunction)WinObj_IsWindowUpdatePending, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"MacGetNextWindow", (PyCFunction)WinObj_MacGetNextWindow, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"GetWindowStandardState", (PyCFunction)WinObj_GetWindowStandardState, 1,
- PyDoc_STR("() -> (Rect rect)")},
- {"GetWindowUserState", (PyCFunction)WinObj_GetWindowUserState, 1,
- PyDoc_STR("() -> (Rect rect)")},
- {"SetWindowKind", (PyCFunction)WinObj_SetWindowKind, 1,
- PyDoc_STR("(short kind) -> None")},
- {"SetWindowStandardState", (PyCFunction)WinObj_SetWindowStandardState, 1,
- PyDoc_STR("(Rect rect) -> None")},
- {"SetWindowUserState", (PyCFunction)WinObj_SetWindowUserState, 1,
- PyDoc_STR("(Rect rect) -> None")},
- {"SetPortWindowPort", (PyCFunction)WinObj_SetPortWindowPort, 1,
- PyDoc_STR("() -> None")},
- {"GetWindowPortBounds", (PyCFunction)WinObj_GetWindowPortBounds, 1,
- PyDoc_STR("() -> (Rect bounds)")},
- {"IsWindowVisible", (PyCFunction)WinObj_IsWindowVisible, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"GetWindowStructureRgn", (PyCFunction)WinObj_GetWindowStructureRgn, 1,
- PyDoc_STR("(RgnHandle r) -> None")},
- {"GetWindowContentRgn", (PyCFunction)WinObj_GetWindowContentRgn, 1,
- PyDoc_STR("(RgnHandle r) -> None")},
- {"GetWindowUpdateRgn", (PyCFunction)WinObj_GetWindowUpdateRgn, 1,
- PyDoc_STR("(RgnHandle r) -> None")},
- {"GetNextWindow", (PyCFunction)WinObj_GetNextWindow, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"MoveWindow", (PyCFunction)WinObj_MoveWindow, 1,
- PyDoc_STR("(short hGlobal, short vGlobal, Boolean front) -> None")},
- {"ShowWindow", (PyCFunction)WinObj_ShowWindow, 1,
- PyDoc_STR("() -> None")},
- {"AutoDispose", (PyCFunction)WinObj_AutoDispose, 1,
- PyDoc_STR("(int)->int. Automatically DisposeHandle the object on Python object cleanup")},
- {NULL, NULL, 0}
+ {"GetWindowOwnerCount", (PyCFunction)WinObj_GetWindowOwnerCount, 1,
+ PyDoc_STR("() -> (UInt32 outCount)")},
+ {"CloneWindow", (PyCFunction)WinObj_CloneWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"GetWindowRetainCount", (PyCFunction)WinObj_GetWindowRetainCount, 1,
+ PyDoc_STR("() -> (ItemCount _rv)")},
+ {"RetainWindow", (PyCFunction)WinObj_RetainWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"ReleaseWindow", (PyCFunction)WinObj_ReleaseWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"ReshapeCustomWindow", (PyCFunction)WinObj_ReshapeCustomWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"GetWindowWidgetHilite", (PyCFunction)WinObj_GetWindowWidgetHilite, 1,
+ PyDoc_STR("() -> (WindowDefPartCode outHilite)")},
+ {"GetWindowClass", (PyCFunction)WinObj_GetWindowClass, 1,
+ PyDoc_STR("() -> (WindowClass outClass)")},
+ {"GetWindowAttributes", (PyCFunction)WinObj_GetWindowAttributes, 1,
+ PyDoc_STR("() -> (WindowAttributes outAttributes)")},
+ {"ChangeWindowAttributes", (PyCFunction)WinObj_ChangeWindowAttributes, 1,
+ PyDoc_STR("(WindowAttributes setTheseAttributes, WindowAttributes clearTheseAttributes) -> None")},
+ {"SetWindowClass", (PyCFunction)WinObj_SetWindowClass, 1,
+ PyDoc_STR("(WindowClass inWindowClass) -> None")},
+ {"SetWindowModality", (PyCFunction)WinObj_SetWindowModality, 1,
+ PyDoc_STR("(WindowModality inModalKind, WindowPtr inUnavailableWindow) -> None")},
+ {"GetWindowModality", (PyCFunction)WinObj_GetWindowModality, 1,
+ PyDoc_STR("() -> (WindowModality outModalKind, WindowPtr outUnavailableWindow)")},
+ {"SetWindowContentColor", (PyCFunction)WinObj_SetWindowContentColor, 1,
+ PyDoc_STR("(RGBColor color) -> None")},
+ {"GetWindowContentColor", (PyCFunction)WinObj_GetWindowContentColor, 1,
+ PyDoc_STR("() -> (RGBColor color)")},
+ {"GetWindowContentPattern", (PyCFunction)WinObj_GetWindowContentPattern, 1,
+ PyDoc_STR("(PixPatHandle outPixPat) -> None")},
+ {"SetWindowContentPattern", (PyCFunction)WinObj_SetWindowContentPattern, 1,
+ PyDoc_STR("(PixPatHandle pixPat) -> None")},
+ {"ScrollWindowRect", (PyCFunction)WinObj_ScrollWindowRect, 1,
+ PyDoc_STR("(Rect inScrollRect, SInt16 inHPixels, SInt16 inVPixels, ScrollWindowOptions inOptions, RgnHandle outExposedRgn) -> None")},
+ {"ScrollWindowRegion", (PyCFunction)WinObj_ScrollWindowRegion, 1,
+ PyDoc_STR("(RgnHandle inScrollRgn, SInt16 inHPixels, SInt16 inVPixels, ScrollWindowOptions inOptions, RgnHandle outExposedRgn) -> None")},
+ {"ClipAbove", (PyCFunction)WinObj_ClipAbove, 1,
+ PyDoc_STR("() -> None")},
+ {"PaintOne", (PyCFunction)WinObj_PaintOne, 1,
+ PyDoc_STR("(RgnHandle clobberedRgn) -> None")},
+ {"PaintBehind", (PyCFunction)WinObj_PaintBehind, 1,
+ PyDoc_STR("(RgnHandle clobberedRgn) -> None")},
+ {"CalcVis", (PyCFunction)WinObj_CalcVis, 1,
+ PyDoc_STR("() -> None")},
+ {"CalcVisBehind", (PyCFunction)WinObj_CalcVisBehind, 1,
+ PyDoc_STR("(RgnHandle clobberedRgn) -> None")},
+ {"BringToFront", (PyCFunction)WinObj_BringToFront, 1,
+ PyDoc_STR("() -> None")},
+ {"SendBehind", (PyCFunction)WinObj_SendBehind, 1,
+ PyDoc_STR("(WindowPtr behindWindow) -> None")},
+ {"SelectWindow", (PyCFunction)WinObj_SelectWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"GetNextWindowOfClass", (PyCFunction)WinObj_GetNextWindowOfClass, 1,
+ PyDoc_STR("(WindowClass inWindowClass, Boolean mustBeVisible) -> (WindowPtr _rv)")},
+ {"SetWindowAlternateTitle", (PyCFunction)WinObj_SetWindowAlternateTitle, 1,
+ PyDoc_STR("(CFStringRef inTitle) -> None")},
+ {"CopyWindowAlternateTitle", (PyCFunction)WinObj_CopyWindowAlternateTitle, 1,
+ PyDoc_STR("() -> (CFStringRef outTitle)")},
+ {"HiliteWindow", (PyCFunction)WinObj_HiliteWindow, 1,
+ PyDoc_STR("(Boolean fHilite) -> None")},
+ {"SetWRefCon", (PyCFunction)WinObj_SetWRefCon, 1,
+ PyDoc_STR("(long data) -> None")},
+ {"GetWRefCon", (PyCFunction)WinObj_GetWRefCon, 1,
+ PyDoc_STR("() -> (long _rv)")},
+ {"SetWindowPic", (PyCFunction)WinObj_SetWindowPic, 1,
+ PyDoc_STR("(PicHandle pic) -> None")},
+ {"GetWindowPic", (PyCFunction)WinObj_GetWindowPic, 1,
+ PyDoc_STR("() -> (PicHandle _rv)")},
+ {"GetWVariant", (PyCFunction)WinObj_GetWVariant, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"GetWindowFeatures", (PyCFunction)WinObj_GetWindowFeatures, 1,
+ PyDoc_STR("() -> (UInt32 outFeatures)")},
+ {"GetWindowRegion", (PyCFunction)WinObj_GetWindowRegion, 1,
+ PyDoc_STR("(WindowRegionCode inRegionCode, RgnHandle ioWinRgn) -> None")},
+ {"GetWindowStructureWidths", (PyCFunction)WinObj_GetWindowStructureWidths, 1,
+ PyDoc_STR("() -> (Rect outRect)")},
+ {"BeginUpdate", (PyCFunction)WinObj_BeginUpdate, 1,
+ PyDoc_STR("() -> None")},
+ {"EndUpdate", (PyCFunction)WinObj_EndUpdate, 1,
+ PyDoc_STR("() -> None")},
+ {"InvalWindowRgn", (PyCFunction)WinObj_InvalWindowRgn, 1,
+ PyDoc_STR("(RgnHandle region) -> None")},
+ {"InvalWindowRect", (PyCFunction)WinObj_InvalWindowRect, 1,
+ PyDoc_STR("(Rect bounds) -> None")},
+ {"ValidWindowRgn", (PyCFunction)WinObj_ValidWindowRgn, 1,
+ PyDoc_STR("(RgnHandle region) -> None")},
+ {"ValidWindowRect", (PyCFunction)WinObj_ValidWindowRect, 1,
+ PyDoc_STR("(Rect bounds) -> None")},
+ {"DrawGrowIcon", (PyCFunction)WinObj_DrawGrowIcon, 1,
+ PyDoc_STR("() -> None")},
+ {"SetWTitle", (PyCFunction)WinObj_SetWTitle, 1,
+ PyDoc_STR("(Str255 title) -> None")},
+ {"GetWTitle", (PyCFunction)WinObj_GetWTitle, 1,
+ PyDoc_STR("() -> (Str255 title)")},
+ {"SetWindowTitleWithCFString", (PyCFunction)WinObj_SetWindowTitleWithCFString, 1,
+ PyDoc_STR("(CFStringRef inString) -> None")},
+ {"CopyWindowTitleAsCFString", (PyCFunction)WinObj_CopyWindowTitleAsCFString, 1,
+ PyDoc_STR("() -> (CFStringRef outString)")},
+ {"SetWindowProxyFSSpec", (PyCFunction)WinObj_SetWindowProxyFSSpec, 1,
+ PyDoc_STR("(FSSpec inFile) -> None")},
+ {"GetWindowProxyFSSpec", (PyCFunction)WinObj_GetWindowProxyFSSpec, 1,
+ PyDoc_STR("() -> (FSSpec outFile)")},
+ {"SetWindowProxyAlias", (PyCFunction)WinObj_SetWindowProxyAlias, 1,
+ PyDoc_STR("(AliasHandle inAlias) -> None")},
+ {"GetWindowProxyAlias", (PyCFunction)WinObj_GetWindowProxyAlias, 1,
+ PyDoc_STR("() -> (AliasHandle alias)")},
+ {"SetWindowProxyCreatorAndType", (PyCFunction)WinObj_SetWindowProxyCreatorAndType, 1,
+ PyDoc_STR("(OSType fileCreator, OSType fileType, SInt16 vRefNum) -> None")},
+ {"GetWindowProxyIcon", (PyCFunction)WinObj_GetWindowProxyIcon, 1,
+ PyDoc_STR("() -> (IconRef outIcon)")},
+ {"SetWindowProxyIcon", (PyCFunction)WinObj_SetWindowProxyIcon, 1,
+ PyDoc_STR("(IconRef icon) -> None")},
+ {"RemoveWindowProxy", (PyCFunction)WinObj_RemoveWindowProxy, 1,
+ PyDoc_STR("() -> None")},
+ {"BeginWindowProxyDrag", (PyCFunction)WinObj_BeginWindowProxyDrag, 1,
+ PyDoc_STR("(RgnHandle outDragOutlineRgn) -> (DragReference outNewDrag)")},
+ {"EndWindowProxyDrag", (PyCFunction)WinObj_EndWindowProxyDrag, 1,
+ PyDoc_STR("(DragReference theDrag) -> None")},
+ {"TrackWindowProxyFromExistingDrag", (PyCFunction)WinObj_TrackWindowProxyFromExistingDrag, 1,
+ PyDoc_STR("(Point startPt, DragReference drag, RgnHandle inDragOutlineRgn) -> None")},
+ {"TrackWindowProxyDrag", (PyCFunction)WinObj_TrackWindowProxyDrag, 1,
+ PyDoc_STR("(Point startPt) -> None")},
+ {"IsWindowModified", (PyCFunction)WinObj_IsWindowModified, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"SetWindowModified", (PyCFunction)WinObj_SetWindowModified, 1,
+ PyDoc_STR("(Boolean modified) -> None")},
+ {"IsWindowPathSelectClick", (PyCFunction)WinObj_IsWindowPathSelectClick, 1,
+ PyDoc_STR("(EventRecord event) -> (Boolean _rv)")},
+ {"WindowPathSelect", (PyCFunction)WinObj_WindowPathSelect, 1,
+ PyDoc_STR("(MenuHandle menu) -> (SInt32 outMenuResult)")},
+ {"HiliteWindowFrameForDrag", (PyCFunction)WinObj_HiliteWindowFrameForDrag, 1,
+ PyDoc_STR("(Boolean hilited) -> None")},
+ {"TransitionWindow", (PyCFunction)WinObj_TransitionWindow, 1,
+ PyDoc_STR("(WindowTransitionEffect inEffect, WindowTransitionAction inAction, Rect inRect) -> None")},
+ {"TransitionWindowAndParent", (PyCFunction)WinObj_TransitionWindowAndParent, 1,
+ PyDoc_STR("(WindowPtr inParentWindow, WindowTransitionEffect inEffect, WindowTransitionAction inAction, Rect inRect) -> None")},
+ {"MacMoveWindow", (PyCFunction)WinObj_MacMoveWindow, 1,
+ PyDoc_STR("(short hGlobal, short vGlobal, Boolean front) -> None")},
+ {"SizeWindow", (PyCFunction)WinObj_SizeWindow, 1,
+ PyDoc_STR("(short w, short h, Boolean fUpdate) -> None")},
+ {"GrowWindow", (PyCFunction)WinObj_GrowWindow, 1,
+ PyDoc_STR("(Point startPt, Rect bBox) -> (long _rv)")},
+ {"DragWindow", (PyCFunction)WinObj_DragWindow, 1,
+ PyDoc_STR("(Point startPt, Rect boundsRect) -> None")},
+ {"ZoomWindow", (PyCFunction)WinObj_ZoomWindow, 1,
+ PyDoc_STR("(WindowPartCode partCode, Boolean front) -> None")},
+ {"IsWindowCollapsable", (PyCFunction)WinObj_IsWindowCollapsable, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsWindowCollapsed", (PyCFunction)WinObj_IsWindowCollapsed, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"CollapseWindow", (PyCFunction)WinObj_CollapseWindow, 1,
+ PyDoc_STR("(Boolean collapse) -> None")},
+ {"GetWindowBounds", (PyCFunction)WinObj_GetWindowBounds, 1,
+ PyDoc_STR("(WindowRegionCode regionCode) -> (Rect globalBounds)")},
+ {"ResizeWindow", (PyCFunction)WinObj_ResizeWindow, 1,
+ PyDoc_STR("(Point inStartPoint, Rect inSizeConstraints) -> (Boolean _rv, Rect outNewContentRect)")},
+ {"SetWindowBounds", (PyCFunction)WinObj_SetWindowBounds, 1,
+ PyDoc_STR("(WindowRegionCode regionCode, Rect globalBounds) -> None")},
+ {"RepositionWindow", (PyCFunction)WinObj_RepositionWindow, 1,
+ PyDoc_STR("(WindowPtr parentWindow, WindowPositionMethod method) -> None")},
+ {"MoveWindowStructure", (PyCFunction)WinObj_MoveWindowStructure, 1,
+ PyDoc_STR("(short hGlobal, short vGlobal) -> None")},
+ {"IsWindowInStandardState", (PyCFunction)WinObj_IsWindowInStandardState, 1,
+ PyDoc_STR("(Point inIdealSize) -> (Boolean _rv, Rect outIdealStandardState)")},
+ {"ZoomWindowIdeal", (PyCFunction)WinObj_ZoomWindowIdeal, 1,
+ PyDoc_STR("(WindowPartCode inPartCode) -> (Point ioIdealSize)")},
+ {"GetWindowIdealUserState", (PyCFunction)WinObj_GetWindowIdealUserState, 1,
+ PyDoc_STR("() -> (Rect outUserState)")},
+ {"SetWindowIdealUserState", (PyCFunction)WinObj_SetWindowIdealUserState, 1,
+ PyDoc_STR("(Rect inUserState) -> None")},
+ {"GetWindowGreatestAreaDevice", (PyCFunction)WinObj_GetWindowGreatestAreaDevice, 1,
+ PyDoc_STR("(WindowRegionCode inRegion) -> (GDHandle outGreatestDevice, Rect outGreatestDeviceRect)")},
+ {"ConstrainWindowToScreen", (PyCFunction)WinObj_ConstrainWindowToScreen, 1,
+ PyDoc_STR("(WindowRegionCode inRegionCode, WindowConstrainOptions inOptions, Rect inScreenRect) -> (Rect outStructure)")},
+ {"HideWindow", (PyCFunction)WinObj_HideWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"MacShowWindow", (PyCFunction)WinObj_MacShowWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"ShowHide", (PyCFunction)WinObj_ShowHide, 1,
+ PyDoc_STR("(Boolean showFlag) -> None")},
+ {"MacIsWindowVisible", (PyCFunction)WinObj_MacIsWindowVisible, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"ShowSheetWindow", (PyCFunction)WinObj_ShowSheetWindow, 1,
+ PyDoc_STR("(WindowPtr inParentWindow) -> None")},
+ {"HideSheetWindow", (PyCFunction)WinObj_HideSheetWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"GetSheetWindowParent", (PyCFunction)WinObj_GetSheetWindowParent, 1,
+ PyDoc_STR("() -> (WindowPtr outParentWindow)")},
+ {"GetWindowPropertyAttributes", (PyCFunction)WinObj_GetWindowPropertyAttributes, 1,
+ PyDoc_STR("(OSType propertyCreator, OSType propertyTag) -> (UInt32 attributes)")},
+ {"ChangeWindowPropertyAttributes", (PyCFunction)WinObj_ChangeWindowPropertyAttributes, 1,
+ PyDoc_STR("(OSType propertyCreator, OSType propertyTag, UInt32 attributesToSet, UInt32 attributesToClear) -> None")},
+ {"TrackBox", (PyCFunction)WinObj_TrackBox, 1,
+ PyDoc_STR("(Point thePt, WindowPartCode partCode) -> (Boolean _rv)")},
+ {"TrackGoAway", (PyCFunction)WinObj_TrackGoAway, 1,
+ PyDoc_STR("(Point thePt) -> (Boolean _rv)")},
+ {"GetWindowPort", (PyCFunction)WinObj_GetWindowPort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {"GetWindowStructurePort", (PyCFunction)WinObj_GetWindowStructurePort, 1,
+ PyDoc_STR("() -> (CGrafPtr _rv)")},
+ {"GetWindowKind", (PyCFunction)WinObj_GetWindowKind, 1,
+ PyDoc_STR("() -> (short _rv)")},
+ {"IsWindowHilited", (PyCFunction)WinObj_IsWindowHilited, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"IsWindowUpdatePending", (PyCFunction)WinObj_IsWindowUpdatePending, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"MacGetNextWindow", (PyCFunction)WinObj_MacGetNextWindow, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"GetWindowStandardState", (PyCFunction)WinObj_GetWindowStandardState, 1,
+ PyDoc_STR("() -> (Rect rect)")},
+ {"GetWindowUserState", (PyCFunction)WinObj_GetWindowUserState, 1,
+ PyDoc_STR("() -> (Rect rect)")},
+ {"SetWindowKind", (PyCFunction)WinObj_SetWindowKind, 1,
+ PyDoc_STR("(short kind) -> None")},
+ {"SetWindowStandardState", (PyCFunction)WinObj_SetWindowStandardState, 1,
+ PyDoc_STR("(Rect rect) -> None")},
+ {"SetWindowUserState", (PyCFunction)WinObj_SetWindowUserState, 1,
+ PyDoc_STR("(Rect rect) -> None")},
+ {"SetPortWindowPort", (PyCFunction)WinObj_SetPortWindowPort, 1,
+ PyDoc_STR("() -> None")},
+ {"GetWindowPortBounds", (PyCFunction)WinObj_GetWindowPortBounds, 1,
+ PyDoc_STR("() -> (Rect bounds)")},
+ {"IsWindowVisible", (PyCFunction)WinObj_IsWindowVisible, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"GetWindowStructureRgn", (PyCFunction)WinObj_GetWindowStructureRgn, 1,
+ PyDoc_STR("(RgnHandle r) -> None")},
+ {"GetWindowContentRgn", (PyCFunction)WinObj_GetWindowContentRgn, 1,
+ PyDoc_STR("(RgnHandle r) -> None")},
+ {"GetWindowUpdateRgn", (PyCFunction)WinObj_GetWindowUpdateRgn, 1,
+ PyDoc_STR("(RgnHandle r) -> None")},
+ {"GetNextWindow", (PyCFunction)WinObj_GetNextWindow, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"MoveWindow", (PyCFunction)WinObj_MoveWindow, 1,
+ PyDoc_STR("(short hGlobal, short vGlobal, Boolean front) -> None")},
+ {"ShowWindow", (PyCFunction)WinObj_ShowWindow, 1,
+ PyDoc_STR("() -> None")},
+ {"AutoDispose", (PyCFunction)WinObj_AutoDispose, 1,
+ PyDoc_STR("(int)->int. Automatically DisposeHandle the object on Python object cleanup")},
+ {NULL, NULL, 0}
};
#define WinObj_getsetlist NULL
@@ -2571,21 +2571,21 @@ static PyMethodDef WinObj_methods[] = {
static int WinObj_compare(WindowObject *self, WindowObject *other)
{
- if ( self->ob_itself > other->ob_itself ) return 1;
- if ( self->ob_itself < other->ob_itself ) return -1;
- return 0;
+ if ( self->ob_itself > other->ob_itself ) return 1;
+ if ( self->ob_itself < other->ob_itself ) return -1;
+ return 0;
}
static PyObject * WinObj_repr(WindowObject *self)
{
- char buf[100];
- sprintf(buf, "<Window object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
- return PyString_FromString(buf);
+ char buf[100];
+ sprintf(buf, "<Window object at 0x%8.8x for 0x%8.8x>", (unsigned)self, (unsigned)self->ob_itself);
+ return PyString_FromString(buf);
}
static int WinObj_hash(WindowObject *self)
{
- return (int)self->ob_itself;
+ return (int)self->ob_itself;
}
#define WinObj_tp_init 0
@@ -2593,61 +2593,61 @@ static int WinObj_hash(WindowObject *self)
static PyObject *WinObj_tp_new(PyTypeObject *type, PyObject *_args, PyObject *_kwds)
{
- PyObject *_self;
- WindowPtr itself;
- char *kw[] = {"itself", 0};
+ PyObject *_self;
+ WindowPtr itself;
+ char *kw[] = {"itself", 0};
- if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, WinObj_Convert, &itself)) return NULL;
- if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
- ((WindowObject *)_self)->ob_itself = itself;
- return _self;
+ if (!PyArg_ParseTupleAndKeywords(_args, _kwds, "O&", kw, WinObj_Convert, &itself)) return NULL;
+ if ((_self = type->tp_alloc(type, 0)) == NULL) return NULL;
+ ((WindowObject *)_self)->ob_itself = itself;
+ return _self;
}
#define WinObj_tp_free PyObject_Del
PyTypeObject Window_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_Win.Window", /*tp_name*/
- sizeof(WindowObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor) WinObj_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)0, /*tp_getattr*/
- (setattrfunc)0, /*tp_setattr*/
- (cmpfunc) WinObj_compare, /*tp_compare*/
- (reprfunc) WinObj_repr, /*tp_repr*/
- (PyNumberMethods *)0, /* tp_as_number */
- (PySequenceMethods *)0, /* tp_as_sequence */
- (PyMappingMethods *)0, /* tp_as_mapping */
- (hashfunc) WinObj_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*/
- WinObj_methods, /* tp_methods */
- 0, /*tp_members*/
- WinObj_getsetlist, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- WinObj_tp_init, /* tp_init */
- WinObj_tp_alloc, /* tp_alloc */
- WinObj_tp_new, /* tp_new */
- WinObj_tp_free, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_Win.Window", /*tp_name*/
+ sizeof(WindowObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor) WinObj_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)0, /*tp_getattr*/
+ (setattrfunc)0, /*tp_setattr*/
+ (cmpfunc) WinObj_compare, /*tp_compare*/
+ (reprfunc) WinObj_repr, /*tp_repr*/
+ (PyNumberMethods *)0, /* tp_as_number */
+ (PySequenceMethods *)0, /* tp_as_sequence */
+ (PyMappingMethods *)0, /* tp_as_mapping */
+ (hashfunc) WinObj_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*/
+ WinObj_methods, /* tp_methods */
+ 0, /*tp_members*/
+ WinObj_getsetlist, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ WinObj_tp_init, /* tp_init */
+ WinObj_tp_alloc, /* tp_alloc */
+ WinObj_tp_new, /* tp_new */
+ WinObj_tp_free, /* tp_free */
};
/* --------------------- End object type Window --------------------- */
@@ -2655,553 +2655,553 @@ PyTypeObject Window_Type = {
static PyObject *Win_GetNewCWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- short windowID;
- WindowPtr behind;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ short windowID;
+ WindowPtr behind;
#ifndef GetNewCWindow
- PyMac_PRECHECK(GetNewCWindow);
+ PyMac_PRECHECK(GetNewCWindow);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &windowID,
- WinObj_Convert, &behind))
- return NULL;
- _rv = GetNewCWindow(windowID,
- (void *)0,
- behind);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &windowID,
+ WinObj_Convert, &behind))
+ return NULL;
+ _rv = GetNewCWindow(windowID,
+ (void *)0,
+ behind);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *Win_NewWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- Rect boundsRect;
- Str255 title;
- Boolean visible;
- short theProc;
- WindowPtr behind;
- Boolean goAwayFlag;
- long refCon;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ Rect boundsRect;
+ Str255 title;
+ Boolean visible;
+ short theProc;
+ WindowPtr behind;
+ Boolean goAwayFlag;
+ long refCon;
#ifndef NewWindow
- PyMac_PRECHECK(NewWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&bhO&bl",
- PyMac_GetRect, &boundsRect,
- PyMac_GetStr255, title,
- &visible,
- &theProc,
- WinObj_Convert, &behind,
- &goAwayFlag,
- &refCon))
- return NULL;
- _rv = NewWindow((void *)0,
- &boundsRect,
- title,
- visible,
- theProc,
- behind,
- goAwayFlag,
- refCon);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(NewWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&bhO&bl",
+ PyMac_GetRect, &boundsRect,
+ PyMac_GetStr255, title,
+ &visible,
+ &theProc,
+ WinObj_Convert, &behind,
+ &goAwayFlag,
+ &refCon))
+ return NULL;
+ _rv = NewWindow((void *)0,
+ &boundsRect,
+ title,
+ visible,
+ theProc,
+ behind,
+ goAwayFlag,
+ refCon);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *Win_GetNewWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- short windowID;
- WindowPtr behind;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ short windowID;
+ WindowPtr behind;
#ifndef GetNewWindow
- PyMac_PRECHECK(GetNewWindow);
+ PyMac_PRECHECK(GetNewWindow);
#endif
- if (!PyArg_ParseTuple(_args, "hO&",
- &windowID,
- WinObj_Convert, &behind))
- return NULL;
- _rv = GetNewWindow(windowID,
- (void *)0,
- behind);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "hO&",
+ &windowID,
+ WinObj_Convert, &behind))
+ return NULL;
+ _rv = GetNewWindow(windowID,
+ (void *)0,
+ behind);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *Win_NewCWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- Rect boundsRect;
- Str255 title;
- Boolean visible;
- short procID;
- WindowPtr behind;
- Boolean goAwayFlag;
- long refCon;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ Rect boundsRect;
+ Str255 title;
+ Boolean visible;
+ short procID;
+ WindowPtr behind;
+ Boolean goAwayFlag;
+ long refCon;
#ifndef NewCWindow
- PyMac_PRECHECK(NewCWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&O&bhO&bl",
- PyMac_GetRect, &boundsRect,
- PyMac_GetStr255, title,
- &visible,
- &procID,
- WinObj_Convert, &behind,
- &goAwayFlag,
- &refCon))
- return NULL;
- _rv = NewCWindow((void *)0,
- &boundsRect,
- title,
- visible,
- procID,
- behind,
- goAwayFlag,
- refCon);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ PyMac_PRECHECK(NewCWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&O&bhO&bl",
+ PyMac_GetRect, &boundsRect,
+ PyMac_GetStr255, title,
+ &visible,
+ &procID,
+ WinObj_Convert, &behind,
+ &goAwayFlag,
+ &refCon))
+ return NULL;
+ _rv = NewCWindow((void *)0,
+ &boundsRect,
+ title,
+ visible,
+ procID,
+ behind,
+ goAwayFlag,
+ refCon);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *Win_CreateNewWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- WindowClass windowClass;
- WindowAttributes attributes;
- Rect contentBounds;
- WindowPtr outWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ WindowClass windowClass;
+ WindowAttributes attributes;
+ Rect contentBounds;
+ WindowPtr outWindow;
#ifndef CreateNewWindow
- PyMac_PRECHECK(CreateNewWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "llO&",
- &windowClass,
- &attributes,
- PyMac_GetRect, &contentBounds))
- return NULL;
- _err = CreateNewWindow(windowClass,
- attributes,
- &contentBounds,
- &outWindow);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- WinObj_New, outWindow);
- return _res;
+ PyMac_PRECHECK(CreateNewWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "llO&",
+ &windowClass,
+ &attributes,
+ PyMac_GetRect, &contentBounds))
+ return NULL;
+ _err = CreateNewWindow(windowClass,
+ attributes,
+ &contentBounds,
+ &outWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ WinObj_New, outWindow);
+ return _res;
}
static PyObject *Win_CreateWindowFromResource(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- SInt16 resID;
- WindowPtr outWindow;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ SInt16 resID;
+ WindowPtr outWindow;
#ifndef CreateWindowFromResource
- PyMac_PRECHECK(CreateWindowFromResource);
+ PyMac_PRECHECK(CreateWindowFromResource);
#endif
- if (!PyArg_ParseTuple(_args, "h",
- &resID))
- return NULL;
- _err = CreateWindowFromResource(resID,
- &outWindow);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- WinObj_New, outWindow);
- return _res;
+ if (!PyArg_ParseTuple(_args, "h",
+ &resID))
+ return NULL;
+ _err = CreateWindowFromResource(resID,
+ &outWindow);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ WinObj_New, outWindow);
+ return _res;
}
static PyObject *Win_ShowFloatingWindows(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef ShowFloatingWindows
- PyMac_PRECHECK(ShowFloatingWindows);
+ PyMac_PRECHECK(ShowFloatingWindows);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = ShowFloatingWindows();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = ShowFloatingWindows();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Win_HideFloatingWindows(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef HideFloatingWindows
- PyMac_PRECHECK(HideFloatingWindows);
+ PyMac_PRECHECK(HideFloatingWindows);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = HideFloatingWindows();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = HideFloatingWindows();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Win_AreFloatingWindowsVisible(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
+ PyObject *_res = NULL;
+ Boolean _rv;
#ifndef AreFloatingWindowsVisible
- PyMac_PRECHECK(AreFloatingWindowsVisible);
+ PyMac_PRECHECK(AreFloatingWindowsVisible);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = AreFloatingWindowsVisible();
- _res = Py_BuildValue("b",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = AreFloatingWindowsVisible();
+ _res = Py_BuildValue("b",
+ _rv);
+ return _res;
}
static PyObject *Win_CheckUpdate(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- Boolean _rv;
- EventRecord theEvent;
+ PyObject *_res = NULL;
+ Boolean _rv;
+ EventRecord theEvent;
#ifndef CheckUpdate
- PyMac_PRECHECK(CheckUpdate);
+ PyMac_PRECHECK(CheckUpdate);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = CheckUpdate(&theEvent);
- _res = Py_BuildValue("bO&",
- _rv,
- PyMac_BuildEventRecord, &theEvent);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = CheckUpdate(&theEvent);
+ _res = Py_BuildValue("bO&",
+ _rv,
+ PyMac_BuildEventRecord, &theEvent);
+ return _res;
}
static PyObject *Win_MacFindWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPartCode _rv;
- Point thePoint;
- WindowPtr window;
+ PyObject *_res = NULL;
+ WindowPartCode _rv;
+ Point thePoint;
+ WindowPtr window;
#ifndef MacFindWindow
- PyMac_PRECHECK(MacFindWindow);
+ PyMac_PRECHECK(MacFindWindow);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &thePoint))
- return NULL;
- _rv = MacFindWindow(thePoint,
- &window);
- _res = Py_BuildValue("hO&",
- _rv,
- WinObj_WhichWindow, window);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &thePoint))
+ return NULL;
+ _rv = MacFindWindow(thePoint,
+ &window);
+ _res = Py_BuildValue("hO&",
+ _rv,
+ WinObj_WhichWindow, window);
+ return _res;
}
static PyObject *Win_FrontWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
#ifndef FrontWindow
- PyMac_PRECHECK(FrontWindow);
+ PyMac_PRECHECK(FrontWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = FrontWindow();
- _res = Py_BuildValue("O&",
- WinObj_WhichWindow, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = FrontWindow();
+ _res = Py_BuildValue("O&",
+ WinObj_WhichWindow, _rv);
+ return _res;
}
static PyObject *Win_FrontNonFloatingWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
#ifndef FrontNonFloatingWindow
- PyMac_PRECHECK(FrontNonFloatingWindow);
+ PyMac_PRECHECK(FrontNonFloatingWindow);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = FrontNonFloatingWindow();
- _res = Py_BuildValue("O&",
- WinObj_WhichWindow, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = FrontNonFloatingWindow();
+ _res = Py_BuildValue("O&",
+ WinObj_WhichWindow, _rv);
+ return _res;
}
static PyObject *Win_GetFrontWindowOfClass(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- WindowClass inWindowClass;
- Boolean mustBeVisible;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ WindowClass inWindowClass;
+ Boolean mustBeVisible;
#ifndef GetFrontWindowOfClass
- PyMac_PRECHECK(GetFrontWindowOfClass);
+ PyMac_PRECHECK(GetFrontWindowOfClass);
#endif
- if (!PyArg_ParseTuple(_args, "lb",
- &inWindowClass,
- &mustBeVisible))
- return NULL;
- _rv = GetFrontWindowOfClass(inWindowClass,
- mustBeVisible);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "lb",
+ &inWindowClass,
+ &mustBeVisible))
+ return NULL;
+ _rv = GetFrontWindowOfClass(inWindowClass,
+ mustBeVisible);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *Win_FindWindowOfClass(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Point where;
- WindowClass inWindowClass;
- WindowPtr outWindow;
- WindowPartCode outWindowPart;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Point where;
+ WindowClass inWindowClass;
+ WindowPtr outWindow;
+ WindowPartCode outWindowPart;
#ifndef FindWindowOfClass
- PyMac_PRECHECK(FindWindowOfClass);
-#endif
- if (!PyArg_ParseTuple(_args, "O&l",
- PyMac_GetPoint, &where,
- &inWindowClass))
- return NULL;
- _err = FindWindowOfClass(&where,
- inWindowClass,
- &outWindow,
- &outWindowPart);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&h",
- WinObj_WhichWindow, outWindow,
- outWindowPart);
- return _res;
+ PyMac_PRECHECK(FindWindowOfClass);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&l",
+ PyMac_GetPoint, &where,
+ &inWindowClass))
+ return NULL;
+ _err = FindWindowOfClass(&where,
+ inWindowClass,
+ &outWindow,
+ &outWindowPart);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&h",
+ WinObj_WhichWindow, outWindow,
+ outWindowPart);
+ return _res;
}
static PyObject *Win_CreateStandardWindowMenu(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- OptionBits inOptions;
- MenuHandle outMenu;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ OptionBits inOptions;
+ MenuHandle outMenu;
#ifndef CreateStandardWindowMenu
- PyMac_PRECHECK(CreateStandardWindowMenu);
+ PyMac_PRECHECK(CreateStandardWindowMenu);
#endif
- if (!PyArg_ParseTuple(_args, "l",
- &inOptions))
- return NULL;
- _err = CreateStandardWindowMenu(inOptions,
- &outMenu);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- MenuObj_New, outMenu);
- return _res;
+ if (!PyArg_ParseTuple(_args, "l",
+ &inOptions))
+ return NULL;
+ _err = CreateStandardWindowMenu(inOptions,
+ &outMenu);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ MenuObj_New, outMenu);
+ return _res;
}
static PyObject *Win_CollapseAllWindows(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- Boolean collapse;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ Boolean collapse;
#ifndef CollapseAllWindows
- PyMac_PRECHECK(CollapseAllWindows);
+ PyMac_PRECHECK(CollapseAllWindows);
#endif
- if (!PyArg_ParseTuple(_args, "b",
- &collapse))
- return NULL;
- _err = CollapseAllWindows(collapse);
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, "b",
+ &collapse))
+ return NULL;
+ _err = CollapseAllWindows(collapse);
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Win_GetAvailableWindowPositioningBounds(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
- GDHandle inDevice;
- Rect outAvailableRect;
+ PyObject *_res = NULL;
+ OSStatus _err;
+ GDHandle inDevice;
+ Rect outAvailableRect;
#ifndef GetAvailableWindowPositioningBounds
- PyMac_PRECHECK(GetAvailableWindowPositioningBounds);
+ PyMac_PRECHECK(GetAvailableWindowPositioningBounds);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- ResObj_Convert, &inDevice))
- return NULL;
- _err = GetAvailableWindowPositioningBounds(inDevice,
- &outAvailableRect);
- if (_err != noErr) return PyMac_Error(_err);
- _res = Py_BuildValue("O&",
- PyMac_BuildRect, &outAvailableRect);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ ResObj_Convert, &inDevice))
+ return NULL;
+ _err = GetAvailableWindowPositioningBounds(inDevice,
+ &outAvailableRect);
+ if (_err != noErr) return PyMac_Error(_err);
+ _res = Py_BuildValue("O&",
+ PyMac_BuildRect, &outAvailableRect);
+ return _res;
}
static PyObject *Win_DisableScreenUpdates(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef DisableScreenUpdates
- PyMac_PRECHECK(DisableScreenUpdates);
+ PyMac_PRECHECK(DisableScreenUpdates);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = DisableScreenUpdates();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = DisableScreenUpdates();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Win_EnableScreenUpdates(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- OSStatus _err;
+ PyObject *_res = NULL;
+ OSStatus _err;
#ifndef EnableScreenUpdates
- PyMac_PRECHECK(EnableScreenUpdates);
+ PyMac_PRECHECK(EnableScreenUpdates);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _err = EnableScreenUpdates();
- if (_err != noErr) return PyMac_Error(_err);
- Py_INCREF(Py_None);
- _res = Py_None;
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _err = EnableScreenUpdates();
+ if (_err != noErr) return PyMac_Error(_err);
+ Py_INCREF(Py_None);
+ _res = Py_None;
+ return _res;
}
static PyObject *Win_PinRect(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- long _rv;
- Rect theRect;
- Point thePt;
+ PyObject *_res = NULL;
+ long _rv;
+ Rect theRect;
+ Point thePt;
#ifndef PinRect
- PyMac_PRECHECK(PinRect);
+ PyMac_PRECHECK(PinRect);
#endif
- if (!PyArg_ParseTuple(_args, "O&O&",
- PyMac_GetRect, &theRect,
- PyMac_GetPoint, &thePt))
- return NULL;
- _rv = PinRect(&theRect,
- thePt);
- _res = Py_BuildValue("l",
- _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&O&",
+ PyMac_GetRect, &theRect,
+ PyMac_GetPoint, &thePt))
+ return NULL;
+ _rv = PinRect(&theRect,
+ thePt);
+ _res = Py_BuildValue("l",
+ _rv);
+ return _res;
}
static PyObject *Win_GetGrayRgn(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- RgnHandle _rv;
+ PyObject *_res = NULL;
+ RgnHandle _rv;
#ifndef GetGrayRgn
- PyMac_PRECHECK(GetGrayRgn);
+ PyMac_PRECHECK(GetGrayRgn);
#endif
- if (!PyArg_ParseTuple(_args, ""))
- return NULL;
- _rv = GetGrayRgn();
- _res = Py_BuildValue("O&",
- ResObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, ""))
+ return NULL;
+ _rv = GetGrayRgn();
+ _res = Py_BuildValue("O&",
+ ResObj_New, _rv);
+ return _res;
}
static PyObject *Win_GetWindowFromPort(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- WindowPtr _rv;
- CGrafPtr port;
+ PyObject *_res = NULL;
+ WindowPtr _rv;
+ CGrafPtr port;
#ifndef GetWindowFromPort
- PyMac_PRECHECK(GetWindowFromPort);
+ PyMac_PRECHECK(GetWindowFromPort);
#endif
- if (!PyArg_ParseTuple(_args, "O&",
- GrafObj_Convert, &port))
- return NULL;
- _rv = GetWindowFromPort(port);
- _res = Py_BuildValue("O&",
- WinObj_New, _rv);
- return _res;
+ if (!PyArg_ParseTuple(_args, "O&",
+ GrafObj_Convert, &port))
+ return NULL;
+ _rv = GetWindowFromPort(port);
+ _res = Py_BuildValue("O&",
+ WinObj_New, _rv);
+ return _res;
}
static PyObject *Win_WhichWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
+ PyObject *_res = NULL;
- long ptr;
+ long ptr;
- if ( !PyArg_ParseTuple(_args, "i", &ptr) )
- return NULL;
- _res = WinObj_WhichWindow((WindowPtr)ptr);
- return _res;
+ if ( !PyArg_ParseTuple(_args, "i", &ptr) )
+ return NULL;
+ _res = WinObj_WhichWindow((WindowPtr)ptr);
+ return _res;
}
static PyObject *Win_FindWindow(PyObject *_self, PyObject *_args)
{
- PyObject *_res = NULL;
- short _rv;
- Point thePoint;
- WindowPtr theWindow;
+ PyObject *_res = NULL;
+ short _rv;
+ Point thePoint;
+ WindowPtr theWindow;
#ifndef FindWindow
- PyMac_PRECHECK(FindWindow);
-#endif
- if (!PyArg_ParseTuple(_args, "O&",
- PyMac_GetPoint, &thePoint))
- return NULL;
- _rv = FindWindow(thePoint,
- &theWindow);
- _res = Py_BuildValue("hO&",
- _rv,
- WinObj_WhichWindow, theWindow);
- return _res;
+ PyMac_PRECHECK(FindWindow);
+#endif
+ if (!PyArg_ParseTuple(_args, "O&",
+ PyMac_GetPoint, &thePoint))
+ return NULL;
+ _rv = FindWindow(thePoint,
+ &theWindow);
+ _res = Py_BuildValue("hO&",
+ _rv,
+ WinObj_WhichWindow, theWindow);
+ return _res;
}
#endif /* __LP64__ */
static PyMethodDef Win_methods[] = {
#ifndef __LP64__
- {"GetNewCWindow", (PyCFunction)Win_GetNewCWindow, 1,
- PyDoc_STR("(short windowID, WindowPtr behind) -> (WindowPtr _rv)")},
- {"NewWindow", (PyCFunction)Win_NewWindow, 1,
- PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, short theProc, WindowPtr behind, Boolean goAwayFlag, long refCon) -> (WindowPtr _rv)")},
- {"GetNewWindow", (PyCFunction)Win_GetNewWindow, 1,
- PyDoc_STR("(short windowID, WindowPtr behind) -> (WindowPtr _rv)")},
- {"NewCWindow", (PyCFunction)Win_NewCWindow, 1,
- PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, short procID, WindowPtr behind, Boolean goAwayFlag, long refCon) -> (WindowPtr _rv)")},
- {"CreateNewWindow", (PyCFunction)Win_CreateNewWindow, 1,
- PyDoc_STR("(WindowClass windowClass, WindowAttributes attributes, Rect contentBounds) -> (WindowPtr outWindow)")},
- {"CreateWindowFromResource", (PyCFunction)Win_CreateWindowFromResource, 1,
- PyDoc_STR("(SInt16 resID) -> (WindowPtr outWindow)")},
- {"ShowFloatingWindows", (PyCFunction)Win_ShowFloatingWindows, 1,
- PyDoc_STR("() -> None")},
- {"HideFloatingWindows", (PyCFunction)Win_HideFloatingWindows, 1,
- PyDoc_STR("() -> None")},
- {"AreFloatingWindowsVisible", (PyCFunction)Win_AreFloatingWindowsVisible, 1,
- PyDoc_STR("() -> (Boolean _rv)")},
- {"CheckUpdate", (PyCFunction)Win_CheckUpdate, 1,
- PyDoc_STR("() -> (Boolean _rv, EventRecord theEvent)")},
- {"MacFindWindow", (PyCFunction)Win_MacFindWindow, 1,
- PyDoc_STR("(Point thePoint) -> (WindowPartCode _rv, WindowPtr window)")},
- {"FrontWindow", (PyCFunction)Win_FrontWindow, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"FrontNonFloatingWindow", (PyCFunction)Win_FrontNonFloatingWindow, 1,
- PyDoc_STR("() -> (WindowPtr _rv)")},
- {"GetFrontWindowOfClass", (PyCFunction)Win_GetFrontWindowOfClass, 1,
- PyDoc_STR("(WindowClass inWindowClass, Boolean mustBeVisible) -> (WindowPtr _rv)")},
- {"FindWindowOfClass", (PyCFunction)Win_FindWindowOfClass, 1,
- PyDoc_STR("(Point where, WindowClass inWindowClass) -> (WindowPtr outWindow, WindowPartCode outWindowPart)")},
- {"CreateStandardWindowMenu", (PyCFunction)Win_CreateStandardWindowMenu, 1,
- PyDoc_STR("(OptionBits inOptions) -> (MenuHandle outMenu)")},
- {"CollapseAllWindows", (PyCFunction)Win_CollapseAllWindows, 1,
- PyDoc_STR("(Boolean collapse) -> None")},
- {"GetAvailableWindowPositioningBounds", (PyCFunction)Win_GetAvailableWindowPositioningBounds, 1,
- PyDoc_STR("(GDHandle inDevice) -> (Rect outAvailableRect)")},
- {"DisableScreenUpdates", (PyCFunction)Win_DisableScreenUpdates, 1,
- PyDoc_STR("() -> None")},
- {"EnableScreenUpdates", (PyCFunction)Win_EnableScreenUpdates, 1,
- PyDoc_STR("() -> None")},
- {"PinRect", (PyCFunction)Win_PinRect, 1,
- PyDoc_STR("(Rect theRect, Point thePt) -> (long _rv)")},
- {"GetGrayRgn", (PyCFunction)Win_GetGrayRgn, 1,
- PyDoc_STR("() -> (RgnHandle _rv)")},
- {"GetWindowFromPort", (PyCFunction)Win_GetWindowFromPort, 1,
- PyDoc_STR("(CGrafPtr port) -> (WindowPtr _rv)")},
- {"WhichWindow", (PyCFunction)Win_WhichWindow, 1,
- PyDoc_STR("Resolve an integer WindowPtr address to a Window object")},
- {"FindWindow", (PyCFunction)Win_FindWindow, 1,
- PyDoc_STR("(Point thePoint) -> (short _rv, WindowPtr theWindow)")},
- {NULL, NULL, 0}
+ {"GetNewCWindow", (PyCFunction)Win_GetNewCWindow, 1,
+ PyDoc_STR("(short windowID, WindowPtr behind) -> (WindowPtr _rv)")},
+ {"NewWindow", (PyCFunction)Win_NewWindow, 1,
+ PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, short theProc, WindowPtr behind, Boolean goAwayFlag, long refCon) -> (WindowPtr _rv)")},
+ {"GetNewWindow", (PyCFunction)Win_GetNewWindow, 1,
+ PyDoc_STR("(short windowID, WindowPtr behind) -> (WindowPtr _rv)")},
+ {"NewCWindow", (PyCFunction)Win_NewCWindow, 1,
+ PyDoc_STR("(Rect boundsRect, Str255 title, Boolean visible, short procID, WindowPtr behind, Boolean goAwayFlag, long refCon) -> (WindowPtr _rv)")},
+ {"CreateNewWindow", (PyCFunction)Win_CreateNewWindow, 1,
+ PyDoc_STR("(WindowClass windowClass, WindowAttributes attributes, Rect contentBounds) -> (WindowPtr outWindow)")},
+ {"CreateWindowFromResource", (PyCFunction)Win_CreateWindowFromResource, 1,
+ PyDoc_STR("(SInt16 resID) -> (WindowPtr outWindow)")},
+ {"ShowFloatingWindows", (PyCFunction)Win_ShowFloatingWindows, 1,
+ PyDoc_STR("() -> None")},
+ {"HideFloatingWindows", (PyCFunction)Win_HideFloatingWindows, 1,
+ PyDoc_STR("() -> None")},
+ {"AreFloatingWindowsVisible", (PyCFunction)Win_AreFloatingWindowsVisible, 1,
+ PyDoc_STR("() -> (Boolean _rv)")},
+ {"CheckUpdate", (PyCFunction)Win_CheckUpdate, 1,
+ PyDoc_STR("() -> (Boolean _rv, EventRecord theEvent)")},
+ {"MacFindWindow", (PyCFunction)Win_MacFindWindow, 1,
+ PyDoc_STR("(Point thePoint) -> (WindowPartCode _rv, WindowPtr window)")},
+ {"FrontWindow", (PyCFunction)Win_FrontWindow, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"FrontNonFloatingWindow", (PyCFunction)Win_FrontNonFloatingWindow, 1,
+ PyDoc_STR("() -> (WindowPtr _rv)")},
+ {"GetFrontWindowOfClass", (PyCFunction)Win_GetFrontWindowOfClass, 1,
+ PyDoc_STR("(WindowClass inWindowClass, Boolean mustBeVisible) -> (WindowPtr _rv)")},
+ {"FindWindowOfClass", (PyCFunction)Win_FindWindowOfClass, 1,
+ PyDoc_STR("(Point where, WindowClass inWindowClass) -> (WindowPtr outWindow, WindowPartCode outWindowPart)")},
+ {"CreateStandardWindowMenu", (PyCFunction)Win_CreateStandardWindowMenu, 1,
+ PyDoc_STR("(OptionBits inOptions) -> (MenuHandle outMenu)")},
+ {"CollapseAllWindows", (PyCFunction)Win_CollapseAllWindows, 1,
+ PyDoc_STR("(Boolean collapse) -> None")},
+ {"GetAvailableWindowPositioningBounds", (PyCFunction)Win_GetAvailableWindowPositioningBounds, 1,
+ PyDoc_STR("(GDHandle inDevice) -> (Rect outAvailableRect)")},
+ {"DisableScreenUpdates", (PyCFunction)Win_DisableScreenUpdates, 1,
+ PyDoc_STR("() -> None")},
+ {"EnableScreenUpdates", (PyCFunction)Win_EnableScreenUpdates, 1,
+ PyDoc_STR("() -> None")},
+ {"PinRect", (PyCFunction)Win_PinRect, 1,
+ PyDoc_STR("(Rect theRect, Point thePt) -> (long _rv)")},
+ {"GetGrayRgn", (PyCFunction)Win_GetGrayRgn, 1,
+ PyDoc_STR("() -> (RgnHandle _rv)")},
+ {"GetWindowFromPort", (PyCFunction)Win_GetWindowFromPort, 1,
+ PyDoc_STR("(CGrafPtr port) -> (WindowPtr _rv)")},
+ {"WhichWindow", (PyCFunction)Win_WhichWindow, 1,
+ PyDoc_STR("Resolve an integer WindowPtr address to a Window object")},
+ {"FindWindow", (PyCFunction)Win_FindWindow, 1,
+ PyDoc_STR("(Point thePoint) -> (short _rv, WindowPtr theWindow)")},
+ {NULL, NULL, 0}
#endif /* __LP64__ */
};
@@ -3213,51 +3213,51 @@ static PyMethodDef Win_methods[] = {
PyObject *
WinObj_WhichWindow(WindowPtr w)
{
- PyObject *it;
+ PyObject *it;
- if (w == NULL) {
- it = Py_None;
- Py_INCREF(it);
+ if (w == NULL) {
+ it = Py_None;
+ Py_INCREF(it);
+ } else {
+ it = (PyObject *) GetWRefCon(w);
+ if (it == NULL || !IsPointerValid((Ptr)it) || ((WindowObject *)it)->ob_itself != w || !WinObj_Check(it)) {
+ it = WinObj_New(w);
+ ((WindowObject *)it)->ob_freeit = NULL;
} else {
- it = (PyObject *) GetWRefCon(w);
- if (it == NULL || !IsPointerValid((Ptr)it) || ((WindowObject *)it)->ob_itself != w || !WinObj_Check(it)) {
- it = WinObj_New(w);
- ((WindowObject *)it)->ob_freeit = NULL;
- } else {
- Py_INCREF(it);
- }
+ Py_INCREF(it);
}
- return it;
+ }
+ return it;
}
#endif /* __LP64__ */
void init_Win(void)
{
- PyObject *m;
+ PyObject *m;
#ifndef __LP64__
- PyObject *d;
+ PyObject *d;
- PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_New);
- PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_WhichWindow);
- PyMac_INIT_TOOLBOX_OBJECT_CONVERT(WindowPtr, WinObj_Convert);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_New);
+ PyMac_INIT_TOOLBOX_OBJECT_NEW(WindowPtr, WinObj_WhichWindow);
+ PyMac_INIT_TOOLBOX_OBJECT_CONVERT(WindowPtr, WinObj_Convert);
#endif /* __LP64__ */
- m = Py_InitModule("_Win", Win_methods);
+ m = Py_InitModule("_Win", Win_methods);
#ifndef __LP64__
- d = PyModule_GetDict(m);
- Win_Error = PyMac_GetOSErrException();
- if (Win_Error == NULL ||
- PyDict_SetItemString(d, "Error", Win_Error) != 0)
- return;
- Window_Type.ob_type = &PyType_Type;
- if (PyType_Ready(&Window_Type) < 0) return;
- Py_INCREF(&Window_Type);
- PyModule_AddObject(m, "Window", (PyObject *)&Window_Type);
- /* Backward-compatible name */
- Py_INCREF(&Window_Type);
- PyModule_AddObject(m, "WindowType", (PyObject *)&Window_Type);
+ d = PyModule_GetDict(m);
+ Win_Error = PyMac_GetOSErrException();
+ if (Win_Error == NULL ||
+ PyDict_SetItemString(d, "Error", Win_Error) != 0)
+ return;
+ Window_Type.ob_type = &PyType_Type;
+ if (PyType_Ready(&Window_Type) < 0) return;
+ Py_INCREF(&Window_Type);
+ PyModule_AddObject(m, "Window", (PyObject *)&Window_Type);
+ /* Backward-compatible name */
+ Py_INCREF(&Window_Type);
+ PyModule_AddObject(m, "WindowType", (PyObject *)&Window_Type);
#endif /* __LP64__ */
}
diff --git a/Mac/Tools/pythonw.c b/Mac/Tools/pythonw.c
index 13df790..7f45ca9 100644
--- a/Mac/Tools/pythonw.c
+++ b/Mac/Tools/pythonw.c
@@ -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;
-
- if (dladdr(Py_Initialize, &info) == 0) {
- return NULL;
- }
-
- len = strlen(info.dli_fname);
-
- 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);
-
- return g_path;
+ size_t len;
+ Dl_info info;
+ char* end;
+ char* g_path;
+
+ if (dladdr(Py_Initialize, &info) == 0) {
+ return NULL;
+ }
+
+ len = strlen(info.dli_fname);
+
+ 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);
+
+ 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 */
- }
-
-
- /*
- * 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 */
- }
+ 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 */
+ }
}
#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 */
}
diff --git a/Misc/setuid-prog.c b/Misc/setuid-prog.c
index d850b47..725749d 100644
--- a/Misc/setuid-prog.c
+++ b/Misc/setuid-prog.c
@@ -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;
-
- 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);
+ 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);
}
int
main(int argc, char **argv)
{
- 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 #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");
-
- clean_environ();
-
- 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);
+ 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 #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");
+
+ clean_environ();
+
+ 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);
}
diff --git a/Modules/_bisectmodule.c b/Modules/_bisectmodule.c
index b78476d..e8976b2 100644
--- a/Modules/_bisectmodule.c
+++ b/Modules/_bisectmodule.c
@@ -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;
-
- 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;
+ 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;
}
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};
-
- 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);
+ 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);
}
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};
-
- 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;
+ 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);
+ }
+
+ 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;
-
- 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;
+ 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;
}
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};
-
- 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);
+ 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);
}
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};
-
- 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;
+ 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);
+ }
+
+ 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);
}
diff --git a/Modules/_bsddb.c b/Modules/_bsddb.c
index 2dd3000..5266a2c 100644
--- a/Modules/_bsddb.c
+++ b/Modules/_bsddb.c
@@ -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;
-
- 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);
-
- MYDB_END_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);
+ }
+
+ Py_XDECREF(args);
+ Py_XDECREF(result);
+
+ 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");
diff --git a/Modules/_codecsmodule.c b/Modules/_codecsmodule.c
index c0c8857..0701fd0 100644
--- a/Modules/_codecsmodule.c
+++ b/Modules/_codecsmodule.c
@@ -15,7 +15,7 @@
The builtin Unicode codecs use the following interface:
<encoding>_encode(Unicode_object[,errors='strict']) ->
- (string object, bytes consumed)
+ (string object, bytes consumed)
<encoding>_decode(char_buffer_obj[,errors='strict']) ->
(Unicode object, bytes consumed)
@@ -96,11 +96,11 @@ codec_encode(PyObject *self, PyObject *args)
#ifdef Py_USING_UNICODE
if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
#else
if (encoding == NULL) {
- PyErr_SetString(PyExc_ValueError, "no encoding specified");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "no encoding specified");
+ return NULL;
}
#endif
@@ -130,11 +130,11 @@ codec_decode(PyObject *self, PyObject *args)
#ifdef Py_USING_UNICODE
if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
#else
if (encoding == NULL) {
- PyErr_SetString(PyExc_ValueError, "no encoding specified");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "no encoding specified");
+ return NULL;
}
#endif
@@ -146,7 +146,7 @@ codec_decode(PyObject *self, PyObject *args)
static
PyObject *codec_tuple(PyObject *unicode,
- Py_ssize_t len)
+ Py_ssize_t len)
{
PyObject *v;
if (unicode == NULL)
@@ -159,45 +159,45 @@ PyObject *codec_tuple(PyObject *unicode,
/* --- String codecs ------------------------------------------------------ */
static PyObject *
escape_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
const char *errors = NULL;
const char *data;
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "s#|z:escape_decode",
- &data, &size, &errors))
- return NULL;
+ &data, &size, &errors))
+ return NULL;
return codec_tuple(PyString_DecodeEscape(data, size, errors, 0, NULL),
- size);
+ size);
}
static PyObject *
escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- PyObject *str;
- const char *errors = NULL;
- char *buf;
- Py_ssize_t consumed, len;
-
- if (!PyArg_ParseTuple(args, "S|z:escape_encode",
- &str, &errors))
- return NULL;
-
- consumed = PyString_GET_SIZE(str);
- str = PyString_Repr(str, 0);
- if (!str)
- return NULL;
-
- /* The string will be quoted. Unquote, similar to unicode-escape. */
- buf = PyString_AS_STRING (str);
- len = PyString_GET_SIZE (str);
- memmove(buf, buf+1, len-2);
- if (_PyString_Resize(&str, len-2) < 0)
- return NULL;
-
- return codec_tuple(str, consumed);
+ PyObject *str;
+ const char *errors = NULL;
+ char *buf;
+ Py_ssize_t consumed, len;
+
+ if (!PyArg_ParseTuple(args, "S|z:escape_encode",
+ &str, &errors))
+ return NULL;
+
+ consumed = PyString_GET_SIZE(str);
+ str = PyString_Repr(str, 0);
+ if (!str)
+ return NULL;
+
+ /* The string will be quoted. Unquote, similar to unicode-escape. */
+ buf = PyString_AS_STRING (str);
+ len = PyString_GET_SIZE (str);
+ memmove(buf, buf+1, len-2);
+ if (_PyString_Resize(&str, len-2) < 0)
+ return NULL;
+
+ return codec_tuple(str, consumed);
}
#ifdef Py_USING_UNICODE
@@ -205,7 +205,7 @@ escape_encode(PyObject *self,
static PyObject *
unicode_internal_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *obj;
const char *errors = NULL;
@@ -213,19 +213,19 @@ unicode_internal_decode(PyObject *self,
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "O|z:unicode_internal_decode",
- &obj, &errors))
- return NULL;
+ &obj, &errors))
+ return NULL;
if (PyUnicode_Check(obj)) {
- Py_INCREF(obj);
- return codec_tuple(obj, PyUnicode_GET_SIZE(obj));
+ Py_INCREF(obj);
+ return codec_tuple(obj, PyUnicode_GET_SIZE(obj));
}
else {
- if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
- return NULL;
+ if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
+ return NULL;
- return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors),
- size);
+ return codec_tuple(_PyUnicode_DecodeUnicodeInternal(data, size, errors),
+ size);
}
}
@@ -233,20 +233,20 @@ static PyObject *
utf_7_decode(PyObject *self,
PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int final = 0;
Py_ssize_t consumed;
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|zi:utf_7_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len;
decoded = PyUnicode_DecodeUTF7Stateful(pbuf.buf, pbuf.len, errors,
- final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
return NULL;
return codec_tuple(decoded, consumed);
@@ -254,32 +254,32 @@ utf_7_decode(PyObject *self,
static PyObject *
utf_8_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int final = 0;
Py_ssize_t consumed;
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|zi:utf_8_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len;
decoded = PyUnicode_DecodeUTF8Stateful(pbuf.buf, pbuf.len, errors,
- final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_16_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
int final = 0;
@@ -287,22 +287,22 @@ utf_16_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|zi:utf_16_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_16_le_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = -1;
int final = 0;
@@ -310,23 +310,23 @@ utf_16_le_decode(PyObject *self,
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|zi:utf_16_le_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_16_be_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 1;
int final = 0;
@@ -334,15 +334,15 @@ utf_16_be_decode(PyObject *self,
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|zi:utf_16_be_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
@@ -356,9 +356,9 @@ utf_16_be_decode(PyObject *self,
static PyObject *
utf_16_ex_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
PyObject *unicode, *tuple;
@@ -366,14 +366,14 @@ utf_16_ex_decode(PyObject *self,
Py_ssize_t consumed;
if (!PyArg_ParseTuple(args, "s*|zii:utf_16_ex_decode",
- &pbuf, &errors, &byteorder, &final))
- return NULL;
+ &pbuf, &errors, &byteorder, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
unicode = PyUnicode_DecodeUTF16Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (unicode == NULL)
- return NULL;
+ return NULL;
tuple = Py_BuildValue("Oni", unicode, consumed, byteorder);
Py_DECREF(unicode);
return tuple;
@@ -381,9 +381,9 @@ utf_16_ex_decode(PyObject *self,
static PyObject *
utf_32_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
int final = 0;
@@ -391,22 +391,22 @@ utf_32_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|zi:utf_32_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_32_le_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = -1;
int final = 0;
@@ -414,22 +414,22 @@ utf_32_le_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|zi:utf_32_le_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
static PyObject *
utf_32_be_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 1;
int final = 0;
@@ -437,14 +437,14 @@ utf_32_be_decode(PyObject *self,
PyObject *decoded;
if (!PyArg_ParseTuple(args, "s*|zi:utf_32_be_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
decoded = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
@@ -458,9 +458,9 @@ utf_32_be_decode(PyObject *self,
static PyObject *
utf_32_ex_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int byteorder = 0;
PyObject *unicode, *tuple;
@@ -468,14 +468,14 @@ utf_32_ex_decode(PyObject *self,
Py_ssize_t consumed;
if (!PyArg_ParseTuple(args, "s*|zii:utf_32_ex_decode",
- &pbuf, &errors, &byteorder, &final))
- return NULL;
+ &pbuf, &errors, &byteorder, &final))
+ return NULL;
consumed = pbuf.len; /* This is overwritten unless final is true. */
unicode = PyUnicode_DecodeUTF32Stateful(pbuf.buf, pbuf.len, errors,
- &byteorder, final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ &byteorder, final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (unicode == NULL)
- return NULL;
+ return NULL;
tuple = Py_BuildValue("Oni", unicode, consumed, byteorder);
Py_DECREF(unicode);
return tuple;
@@ -483,114 +483,114 @@ utf_32_ex_decode(PyObject *self,
static PyObject *
unicode_escape_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
- PyObject *unicode;
+ PyObject *unicode;
if (!PyArg_ParseTuple(args, "s*|z:unicode_escape_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeUnicodeEscape(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
raw_unicode_escape_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
- PyObject *unicode;
+ PyObject *unicode;
if (!PyArg_ParseTuple(args, "s*|z:raw_unicode_escape_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeRawUnicodeEscape(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
latin_1_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
- PyObject *unicode;
+ Py_buffer pbuf;
+ PyObject *unicode;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "s*|z:latin_1_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeLatin1(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
ascii_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
- PyObject *unicode;
+ Py_buffer pbuf;
+ PyObject *unicode;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "s*|z:ascii_decode",
- &pbuf, &errors))
- return NULL;
+ &pbuf, &errors))
+ return NULL;
- unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeASCII(pbuf.buf, pbuf.len, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
static PyObject *
charmap_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
- PyObject *unicode;
+ Py_buffer pbuf;
+ PyObject *unicode;
const char *errors = NULL;
PyObject *mapping = NULL;
if (!PyArg_ParseTuple(args, "s*|zO:charmap_decode",
- &pbuf, &errors, &mapping))
- return NULL;
+ &pbuf, &errors, &mapping))
+ return NULL;
if (mapping == Py_None)
- mapping = NULL;
+ mapping = NULL;
- unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors);
- PyBuffer_Release(&pbuf);
- return codec_tuple(unicode, pbuf.len);
+ unicode = PyUnicode_DecodeCharmap(pbuf.buf, pbuf.len, mapping, errors);
+ PyBuffer_Release(&pbuf);
+ return codec_tuple(unicode, pbuf.len);
}
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
static PyObject *
mbcs_decode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- Py_buffer pbuf;
+ Py_buffer pbuf;
const char *errors = NULL;
int final = 0;
Py_ssize_t consumed;
PyObject *decoded = NULL;
if (!PyArg_ParseTuple(args, "s*|zi:mbcs_decode",
- &pbuf, &errors, &final))
- return NULL;
+ &pbuf, &errors, &final))
+ return NULL;
consumed = pbuf.len;
decoded = PyUnicode_DecodeMBCSStateful(pbuf.buf, pbuf.len, errors,
- final ? NULL : &consumed);
- PyBuffer_Release(&pbuf);
+ final ? NULL : &consumed);
+ PyBuffer_Release(&pbuf);
if (decoded == NULL)
- return NULL;
+ return NULL;
return codec_tuple(decoded, consumed);
}
@@ -600,39 +600,39 @@ mbcs_decode(PyObject *self,
static PyObject *
readbuffer_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
const char *data;
Py_ssize_t size;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "s#|z:readbuffer_encode",
- &data, &size, &errors))
- return NULL;
+ &data, &size, &errors))
+ return NULL;
return codec_tuple(PyString_FromStringAndSize(data, size),
- size);
+ size);
}
static PyObject *
charbuffer_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
const char *data;
Py_ssize_t size;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "t#|z:charbuffer_encode",
- &data, &size, &errors))
- return NULL;
+ &data, &size, &errors))
+ return NULL;
return codec_tuple(PyString_FromStringAndSize(data, size),
- size);
+ size);
}
static PyObject *
unicode_internal_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *obj;
const char *errors = NULL;
@@ -640,65 +640,65 @@ unicode_internal_encode(PyObject *self,
Py_ssize_t size;
if (!PyArg_ParseTuple(args, "O|z:unicode_internal_encode",
- &obj, &errors))
- return NULL;
+ &obj, &errors))
+ return NULL;
if (PyUnicode_Check(obj)) {
- data = PyUnicode_AS_DATA(obj);
- size = PyUnicode_GET_DATA_SIZE(obj);
- return codec_tuple(PyString_FromStringAndSize(data, size),
- PyUnicode_GET_SIZE(obj));
+ data = PyUnicode_AS_DATA(obj);
+ size = PyUnicode_GET_DATA_SIZE(obj);
+ return codec_tuple(PyString_FromStringAndSize(data, size),
+ PyUnicode_GET_SIZE(obj));
}
else {
- if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
- return NULL;
- return codec_tuple(PyString_FromStringAndSize(data, size),
- size);
+ if (PyObject_AsReadBuffer(obj, (const void **)&data, &size))
+ return NULL;
+ return codec_tuple(PyString_FromStringAndSize(data, size),
+ size);
}
}
static PyObject *
utf_7_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_7_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF7(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- 0,
- 0,
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ 0,
+ 0,
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_8_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_8_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF8(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -712,70 +712,70 @@ utf_8_encode(PyObject *self,
static PyObject *
utf_16_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
int byteorder = 0;
if (!PyArg_ParseTuple(args, "O|zi:utf_16_encode",
- &str, &errors, &byteorder))
- return NULL;
+ &str, &errors, &byteorder))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- byteorder),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ byteorder),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_16_le_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_16_le_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- -1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ -1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_16_be_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_16_be_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF16(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- +1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ +1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -789,186 +789,186 @@ utf_16_be_encode(PyObject *self,
static PyObject *
utf_32_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
int byteorder = 0;
if (!PyArg_ParseTuple(args, "O|zi:utf_32_encode",
- &str, &errors, &byteorder))
- return NULL;
+ &str, &errors, &byteorder))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- byteorder),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ byteorder),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_32_le_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_32_le_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- -1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ -1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
utf_32_be_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:utf_32_be_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUTF32(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors,
- +1),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str),
+ errors,
+ +1),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
unicode_escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:unicode_escape_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeUnicodeEscape(PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str)),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_GET_SIZE(str)),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
raw_unicode_escape_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:raw_unicode_escape_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeRawUnicodeEscape(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str)),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str)),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
latin_1_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:latin_1_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeLatin1(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
ascii_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:ascii_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeASCII(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
static PyObject *
charmap_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
PyObject *mapping = NULL;
if (!PyArg_ParseTuple(args, "O|zO:charmap_encode",
- &str, &errors, &mapping))
- return NULL;
+ &str, &errors, &mapping))
+ return NULL;
if (mapping == Py_None)
- mapping = NULL;
+ mapping = NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeCharmap(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- mapping,
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ mapping,
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -986,23 +986,23 @@ charmap_build(PyObject *self, PyObject *args)
static PyObject *
mbcs_encode(PyObject *self,
- PyObject *args)
+ PyObject *args)
{
PyObject *str, *v;
const char *errors = NULL;
if (!PyArg_ParseTuple(args, "O|z:mbcs_encode",
- &str, &errors))
- return NULL;
+ &str, &errors))
+ return NULL;
str = PyUnicode_FromObject(str);
if (str == NULL)
- return NULL;
+ return NULL;
v = codec_tuple(PyUnicode_EncodeMBCS(
- PyUnicode_AS_UNICODE(str),
- PyUnicode_GET_SIZE(str),
- errors),
- PyUnicode_GET_SIZE(str));
+ PyUnicode_AS_UNICODE(str),
+ PyUnicode_GET_SIZE(str),
+ errors),
+ PyUnicode_GET_SIZE(str));
Py_DECREF(str);
return v;
}
@@ -1027,8 +1027,8 @@ static PyObject *register_error(PyObject *self, PyObject *args)
PyObject *handler;
if (!PyArg_ParseTuple(args, "sO:register_error",
- &name, &handler))
- return NULL;
+ &name, &handler))
+ return NULL;
if (PyCodec_RegisterError(name, handler))
return NULL;
Py_RETURN_NONE;
@@ -1045,68 +1045,68 @@ static PyObject *lookup_error(PyObject *self, PyObject *args)
const char *name;
if (!PyArg_ParseTuple(args, "s:lookup_error",
- &name))
- return NULL;
+ &name))
+ return NULL;
return PyCodec_LookupError(name);
}
/* --- Module API --------------------------------------------------------- */
static PyMethodDef _codecs_functions[] = {
- {"register", codec_register, METH_O,
+ {"register", codec_register, METH_O,
register__doc__},
- {"lookup", codec_lookup, METH_VARARGS,
+ {"lookup", codec_lookup, METH_VARARGS,
lookup__doc__},
- {"encode", codec_encode, METH_VARARGS,
- encode__doc__},
- {"decode", codec_decode, METH_VARARGS,
- decode__doc__},
- {"escape_encode", escape_encode, METH_VARARGS},
- {"escape_decode", escape_decode, METH_VARARGS},
+ {"encode", codec_encode, METH_VARARGS,
+ encode__doc__},
+ {"decode", codec_decode, METH_VARARGS,
+ decode__doc__},
+ {"escape_encode", escape_encode, METH_VARARGS},
+ {"escape_decode", escape_decode, METH_VARARGS},
#ifdef Py_USING_UNICODE
- {"utf_8_encode", utf_8_encode, METH_VARARGS},
- {"utf_8_decode", utf_8_decode, METH_VARARGS},
- {"utf_7_encode", utf_7_encode, METH_VARARGS},
- {"utf_7_decode", utf_7_decode, METH_VARARGS},
- {"utf_16_encode", utf_16_encode, METH_VARARGS},
- {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS},
- {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS},
- {"utf_16_decode", utf_16_decode, METH_VARARGS},
- {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS},
- {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS},
- {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS},
- {"utf_32_encode", utf_32_encode, METH_VARARGS},
- {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS},
- {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS},
- {"utf_32_decode", utf_32_decode, METH_VARARGS},
- {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS},
- {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS},
- {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS},
- {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS},
- {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS},
- {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS},
- {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS},
- {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS},
- {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS},
- {"latin_1_encode", latin_1_encode, METH_VARARGS},
- {"latin_1_decode", latin_1_decode, METH_VARARGS},
- {"ascii_encode", ascii_encode, METH_VARARGS},
- {"ascii_decode", ascii_decode, METH_VARARGS},
- {"charmap_encode", charmap_encode, METH_VARARGS},
- {"charmap_decode", charmap_decode, METH_VARARGS},
- {"charmap_build", charmap_build, METH_VARARGS},
- {"readbuffer_encode", readbuffer_encode, METH_VARARGS},
- {"charbuffer_encode", charbuffer_encode, METH_VARARGS},
+ {"utf_8_encode", utf_8_encode, METH_VARARGS},
+ {"utf_8_decode", utf_8_decode, METH_VARARGS},
+ {"utf_7_encode", utf_7_encode, METH_VARARGS},
+ {"utf_7_decode", utf_7_decode, METH_VARARGS},
+ {"utf_16_encode", utf_16_encode, METH_VARARGS},
+ {"utf_16_le_encode", utf_16_le_encode, METH_VARARGS},
+ {"utf_16_be_encode", utf_16_be_encode, METH_VARARGS},
+ {"utf_16_decode", utf_16_decode, METH_VARARGS},
+ {"utf_16_le_decode", utf_16_le_decode, METH_VARARGS},
+ {"utf_16_be_decode", utf_16_be_decode, METH_VARARGS},
+ {"utf_16_ex_decode", utf_16_ex_decode, METH_VARARGS},
+ {"utf_32_encode", utf_32_encode, METH_VARARGS},
+ {"utf_32_le_encode", utf_32_le_encode, METH_VARARGS},
+ {"utf_32_be_encode", utf_32_be_encode, METH_VARARGS},
+ {"utf_32_decode", utf_32_decode, METH_VARARGS},
+ {"utf_32_le_decode", utf_32_le_decode, METH_VARARGS},
+ {"utf_32_be_decode", utf_32_be_decode, METH_VARARGS},
+ {"utf_32_ex_decode", utf_32_ex_decode, METH_VARARGS},
+ {"unicode_escape_encode", unicode_escape_encode, METH_VARARGS},
+ {"unicode_escape_decode", unicode_escape_decode, METH_VARARGS},
+ {"unicode_internal_encode", unicode_internal_encode, METH_VARARGS},
+ {"unicode_internal_decode", unicode_internal_decode, METH_VARARGS},
+ {"raw_unicode_escape_encode", raw_unicode_escape_encode, METH_VARARGS},
+ {"raw_unicode_escape_decode", raw_unicode_escape_decode, METH_VARARGS},
+ {"latin_1_encode", latin_1_encode, METH_VARARGS},
+ {"latin_1_decode", latin_1_decode, METH_VARARGS},
+ {"ascii_encode", ascii_encode, METH_VARARGS},
+ {"ascii_decode", ascii_decode, METH_VARARGS},
+ {"charmap_encode", charmap_encode, METH_VARARGS},
+ {"charmap_decode", charmap_decode, METH_VARARGS},
+ {"charmap_build", charmap_build, METH_VARARGS},
+ {"readbuffer_encode", readbuffer_encode, METH_VARARGS},
+ {"charbuffer_encode", charbuffer_encode, METH_VARARGS},
#if defined(MS_WINDOWS) && defined(HAVE_USABLE_WCHAR_T)
- {"mbcs_encode", mbcs_encode, METH_VARARGS},
- {"mbcs_decode", mbcs_decode, METH_VARARGS},
+ {"mbcs_encode", mbcs_encode, METH_VARARGS},
+ {"mbcs_decode", mbcs_decode, METH_VARARGS},
#endif
#endif /* Py_USING_UNICODE */
- {"register_error", register_error, METH_VARARGS,
+ {"register_error", register_error, METH_VARARGS,
register_error__doc__},
- {"lookup_error", lookup_error, METH_VARARGS,
+ {"lookup_error", lookup_error, METH_VARARGS,
lookup_error__doc__},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
diff --git a/Modules/_collectionsmodule.c b/Modules/_collectionsmodule.c
index 5d3fc6b..c140e97 100644
--- a/Modules/_collectionsmodule.c
+++ b/Modules/_collectionsmodule.c
@@ -46,9 +46,9 @@
*/
typedef struct BLOCK {
- struct BLOCK *leftlink;
- struct BLOCK *rightlink;
- PyObject *data[BLOCKLEN];
+ struct BLOCK *leftlink;
+ struct BLOCK *rightlink;
+ PyObject *data[BLOCKLEN];
} block;
#define MAXFREEBLOCKS 10
@@ -57,71 +57,71 @@ static block *freeblocks[MAXFREEBLOCKS];
static block *
newblock(block *leftlink, block *rightlink, Py_ssize_t len) {
- block *b;
- /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
- * refuse to allocate new blocks if the current len is dangerously
- * close. There is some extra margin to prevent spurious arithmetic
- * overflows at various places. The following check ensures that
- * the blocks allocated to the deque, in the worst case, can only
- * have PY_SSIZE_T_MAX-2 entries in total.
- */
- if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
- PyErr_SetString(PyExc_OverflowError,
- "cannot add more blocks to the deque");
- return NULL;
- }
- if (numfreeblocks) {
- numfreeblocks -= 1;
- b = freeblocks[numfreeblocks];
- } else {
- b = PyMem_Malloc(sizeof(block));
- if (b == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- }
- b->leftlink = leftlink;
- b->rightlink = rightlink;
- return b;
+ block *b;
+ /* To prevent len from overflowing PY_SSIZE_T_MAX on 64-bit machines, we
+ * refuse to allocate new blocks if the current len is dangerously
+ * close. There is some extra margin to prevent spurious arithmetic
+ * overflows at various places. The following check ensures that
+ * the blocks allocated to the deque, in the worst case, can only
+ * have PY_SSIZE_T_MAX-2 entries in total.
+ */
+ if (len >= PY_SSIZE_T_MAX - 2*BLOCKLEN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot add more blocks to the deque");
+ return NULL;
+ }
+ if (numfreeblocks) {
+ numfreeblocks -= 1;
+ b = freeblocks[numfreeblocks];
+ } else {
+ b = PyMem_Malloc(sizeof(block));
+ if (b == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ }
+ b->leftlink = leftlink;
+ b->rightlink = rightlink;
+ return b;
}
static void
freeblock(block *b)
{
- if (numfreeblocks < MAXFREEBLOCKS) {
- freeblocks[numfreeblocks] = b;
- numfreeblocks++;
- } else {
- PyMem_Free(b);
- }
+ if (numfreeblocks < MAXFREEBLOCKS) {
+ freeblocks[numfreeblocks] = b;
+ numfreeblocks++;
+ } else {
+ PyMem_Free(b);
+ }
}
typedef struct {
- PyObject_HEAD
- block *leftblock;
- block *rightblock;
- Py_ssize_t leftindex; /* in range(BLOCKLEN) */
- Py_ssize_t rightindex; /* in range(BLOCKLEN) */
- Py_ssize_t len;
- Py_ssize_t maxlen;
- long state; /* incremented whenever the indices move */
- PyObject *weakreflist; /* List of weak references */
+ PyObject_HEAD
+ block *leftblock;
+ block *rightblock;
+ Py_ssize_t leftindex; /* in range(BLOCKLEN) */
+ Py_ssize_t rightindex; /* in range(BLOCKLEN) */
+ Py_ssize_t len;
+ Py_ssize_t maxlen;
+ long state; /* incremented whenever the indices move */
+ PyObject *weakreflist; /* List of weak references */
} dequeobject;
/* The deque's size limit is d.maxlen. The limit can be zero or positive.
* If there is no limit, then d.maxlen == -1.
- *
+ *
* After an item is added to a deque, we check to see if the size has grown past
* the limit. If it has, we get the size back down to the limit by popping an
* item off of the opposite end. The methods that can trigger this are append(),
* appendleft(), extend(), and extendleft().
*/
-#define TRIM(d, popfunction) \
- if (d->maxlen != -1 && d->len > d->maxlen) { \
- PyObject *rv = popfunction(d, NULL); \
- assert(rv != NULL && d->len <= d->maxlen); \
- Py_DECREF(rv); \
+#define TRIM(d, popfunction) \
+ if (d->maxlen != -1 && d->len > d->maxlen) { \
+ PyObject *rv = popfunction(d, NULL); \
+ assert(rv != NULL && d->len <= d->maxlen); \
+ Py_DECREF(rv); \
}
static PyTypeObject deque_type;
@@ -129,65 +129,65 @@ static PyTypeObject deque_type;
static PyObject *
deque_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- dequeobject *deque;
- block *b;
-
- /* create dequeobject structure */
- deque = (dequeobject *)type->tp_alloc(type, 0);
- if (deque == NULL)
- return NULL;
-
- b = newblock(NULL, NULL, 0);
- if (b == NULL) {
- Py_DECREF(deque);
- return NULL;
- }
-
- assert(BLOCKLEN >= 2);
- deque->leftblock = b;
- deque->rightblock = b;
- deque->leftindex = CENTER + 1;
- deque->rightindex = CENTER;
- deque->len = 0;
- deque->state = 0;
- deque->weakreflist = NULL;
- deque->maxlen = -1;
-
- return (PyObject *)deque;
+ dequeobject *deque;
+ block *b;
+
+ /* create dequeobject structure */
+ deque = (dequeobject *)type->tp_alloc(type, 0);
+ if (deque == NULL)
+ return NULL;
+
+ b = newblock(NULL, NULL, 0);
+ if (b == NULL) {
+ Py_DECREF(deque);
+ return NULL;
+ }
+
+ assert(BLOCKLEN >= 2);
+ deque->leftblock = b;
+ deque->rightblock = b;
+ deque->leftindex = CENTER + 1;
+ deque->rightindex = CENTER;
+ deque->len = 0;
+ deque->state = 0;
+ deque->weakreflist = NULL;
+ deque->maxlen = -1;
+
+ return (PyObject *)deque;
}
static PyObject *
deque_pop(dequeobject *deque, PyObject *unused)
{
- PyObject *item;
- block *prevblock;
-
- if (deque->len == 0) {
- PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
- return NULL;
- }
- item = deque->rightblock->data[deque->rightindex];
- deque->rightindex--;
- deque->len--;
- deque->state++;
-
- if (deque->rightindex == -1) {
- if (deque->len == 0) {
- assert(deque->leftblock == deque->rightblock);
- assert(deque->leftindex == deque->rightindex+1);
- /* re-center instead of freeing a block */
- deque->leftindex = CENTER + 1;
- deque->rightindex = CENTER;
- } else {
- prevblock = deque->rightblock->leftlink;
- assert(deque->leftblock != deque->rightblock);
- freeblock(deque->rightblock);
- prevblock->rightlink = NULL;
- deque->rightblock = prevblock;
- deque->rightindex = BLOCKLEN - 1;
- }
- }
- return item;
+ PyObject *item;
+ block *prevblock;
+
+ if (deque->len == 0) {
+ PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
+ return NULL;
+ }
+ item = deque->rightblock->data[deque->rightindex];
+ deque->rightindex--;
+ deque->len--;
+ deque->state++;
+
+ if (deque->rightindex == -1) {
+ if (deque->len == 0) {
+ assert(deque->leftblock == deque->rightblock);
+ assert(deque->leftindex == deque->rightindex+1);
+ /* re-center instead of freeing a block */
+ deque->leftindex = CENTER + 1;
+ deque->rightindex = CENTER;
+ } else {
+ prevblock = deque->rightblock->leftlink;
+ assert(deque->leftblock != deque->rightblock);
+ freeblock(deque->rightblock);
+ prevblock->rightlink = NULL;
+ deque->rightblock = prevblock;
+ deque->rightindex = BLOCKLEN - 1;
+ }
+ }
+ return item;
}
PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
@@ -195,37 +195,37 @@ PyDoc_STRVAR(pop_doc, "Remove and return the rightmost element.");
static PyObject *
deque_popleft(dequeobject *deque, PyObject *unused)
{
- PyObject *item;
- block *prevblock;
-
- if (deque->len == 0) {
- PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
- return NULL;
- }
- assert(deque->leftblock != NULL);
- item = deque->leftblock->data[deque->leftindex];
- deque->leftindex++;
- deque->len--;
- deque->state++;
-
- if (deque->leftindex == BLOCKLEN) {
- if (deque->len == 0) {
- assert(deque->leftblock == deque->rightblock);
- assert(deque->leftindex == deque->rightindex+1);
- /* re-center instead of freeing a block */
- deque->leftindex = CENTER + 1;
- deque->rightindex = CENTER;
- } else {
- assert(deque->leftblock != deque->rightblock);
- prevblock = deque->leftblock->rightlink;
- freeblock(deque->leftblock);
- assert(prevblock != NULL);
- prevblock->leftlink = NULL;
- deque->leftblock = prevblock;
- deque->leftindex = 0;
- }
- }
- return item;
+ PyObject *item;
+ block *prevblock;
+
+ if (deque->len == 0) {
+ PyErr_SetString(PyExc_IndexError, "pop from an empty deque");
+ return NULL;
+ }
+ assert(deque->leftblock != NULL);
+ item = deque->leftblock->data[deque->leftindex];
+ deque->leftindex++;
+ deque->len--;
+ deque->state++;
+
+ if (deque->leftindex == BLOCKLEN) {
+ if (deque->len == 0) {
+ assert(deque->leftblock == deque->rightblock);
+ assert(deque->leftindex == deque->rightindex+1);
+ /* re-center instead of freeing a block */
+ deque->leftindex = CENTER + 1;
+ deque->rightindex = CENTER;
+ } else {
+ assert(deque->leftblock != deque->rightblock);
+ prevblock = deque->leftblock->rightlink;
+ freeblock(deque->leftblock);
+ assert(prevblock != NULL);
+ prevblock->leftlink = NULL;
+ deque->leftblock = prevblock;
+ deque->leftindex = 0;
+ }
+ }
+ return item;
}
PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
@@ -233,22 +233,22 @@ PyDoc_STRVAR(popleft_doc, "Remove and return the leftmost element.");
static PyObject *
deque_append(dequeobject *deque, PyObject *item)
{
- deque->state++;
- if (deque->rightindex == BLOCKLEN-1) {
- block *b = newblock(deque->rightblock, NULL, deque->len);
- if (b == NULL)
- return NULL;
- assert(deque->rightblock->rightlink == NULL);
- deque->rightblock->rightlink = b;
- deque->rightblock = b;
- deque->rightindex = -1;
- }
- Py_INCREF(item);
- deque->len++;
- deque->rightindex++;
- deque->rightblock->data[deque->rightindex] = item;
- TRIM(deque, deque_popleft);
- Py_RETURN_NONE;
+ deque->state++;
+ if (deque->rightindex == BLOCKLEN-1) {
+ block *b = newblock(deque->rightblock, NULL, deque->len);
+ if (b == NULL)
+ return NULL;
+ assert(deque->rightblock->rightlink == NULL);
+ deque->rightblock->rightlink = b;
+ deque->rightblock = b;
+ deque->rightindex = -1;
+ }
+ Py_INCREF(item);
+ deque->len++;
+ deque->rightindex++;
+ deque->rightblock->data[deque->rightindex] = item;
+ TRIM(deque, deque_popleft);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
@@ -256,90 +256,90 @@ PyDoc_STRVAR(append_doc, "Add an element to the right side of the deque.");
static PyObject *
deque_appendleft(dequeobject *deque, PyObject *item)
{
- deque->state++;
- if (deque->leftindex == 0) {
- block *b = newblock(NULL, deque->leftblock, deque->len);
- if (b == NULL)
- return NULL;
- assert(deque->leftblock->leftlink == NULL);
- deque->leftblock->leftlink = b;
- deque->leftblock = b;
- deque->leftindex = BLOCKLEN;
- }
- Py_INCREF(item);
- deque->len++;
- deque->leftindex--;
- deque->leftblock->data[deque->leftindex] = item;
- TRIM(deque, deque_pop);
- Py_RETURN_NONE;
+ deque->state++;
+ if (deque->leftindex == 0) {
+ block *b = newblock(NULL, deque->leftblock, deque->len);
+ if (b == NULL)
+ return NULL;
+ assert(deque->leftblock->leftlink == NULL);
+ deque->leftblock->leftlink = b;
+ deque->leftblock = b;
+ deque->leftindex = BLOCKLEN;
+ }
+ Py_INCREF(item);
+ deque->len++;
+ deque->leftindex--;
+ deque->leftblock->data[deque->leftindex] = item;
+ TRIM(deque, deque_pop);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(appendleft_doc, "Add an element to the left side of the deque.");
-/* Run an iterator to exhaustion. Shortcut for
+/* Run an iterator to exhaustion. Shortcut for
the extend/extendleft methods when maxlen == 0. */
static PyObject*
consume_iterator(PyObject *it)
{
- PyObject *item;
-
- while ((item = PyIter_Next(it)) != NULL) {
- Py_DECREF(item);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
+ PyObject *item;
+
+ while ((item = PyIter_Next(it)) != NULL) {
+ Py_DECREF(item);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_NONE;
}
static PyObject *
deque_extend(dequeobject *deque, PyObject *iterable)
{
- PyObject *it, *item;
-
- /* Handle case where id(deque) == id(iterable) */
- if ((PyObject *)deque == iterable) {
- PyObject *result;
- PyObject *s = PySequence_List(iterable);
- if (s == NULL)
- return NULL;
- result = deque_extend(deque, s);
- Py_DECREF(s);
- return result;
- }
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- if (deque->maxlen == 0)
- return consume_iterator(it);
-
- while ((item = PyIter_Next(it)) != NULL) {
- deque->state++;
- if (deque->rightindex == BLOCKLEN-1) {
- block *b = newblock(deque->rightblock, NULL,
- deque->len);
- if (b == NULL) {
- Py_DECREF(item);
- Py_DECREF(it);
- return NULL;
- }
- assert(deque->rightblock->rightlink == NULL);
- deque->rightblock->rightlink = b;
- deque->rightblock = b;
- deque->rightindex = -1;
- }
- deque->len++;
- deque->rightindex++;
- deque->rightblock->data[deque->rightindex] = item;
- TRIM(deque, deque_popleft);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
+ PyObject *it, *item;
+
+ /* Handle case where id(deque) == id(iterable) */
+ if ((PyObject *)deque == iterable) {
+ PyObject *result;
+ PyObject *s = PySequence_List(iterable);
+ if (s == NULL)
+ return NULL;
+ result = deque_extend(deque, s);
+ Py_DECREF(s);
+ return result;
+ }
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ if (deque->maxlen == 0)
+ return consume_iterator(it);
+
+ while ((item = PyIter_Next(it)) != NULL) {
+ deque->state++;
+ if (deque->rightindex == BLOCKLEN-1) {
+ block *b = newblock(deque->rightblock, NULL,
+ deque->len);
+ if (b == NULL) {
+ Py_DECREF(item);
+ Py_DECREF(it);
+ return NULL;
+ }
+ assert(deque->rightblock->rightlink == NULL);
+ deque->rightblock->rightlink = b;
+ deque->rightblock = b;
+ deque->rightindex = -1;
+ }
+ deque->len++;
+ deque->rightindex++;
+ deque->rightblock->data[deque->rightindex] = item;
+ TRIM(deque, deque_popleft);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(extend_doc,
@@ -348,50 +348,50 @@ PyDoc_STRVAR(extend_doc,
static PyObject *
deque_extendleft(dequeobject *deque, PyObject *iterable)
{
- PyObject *it, *item;
-
- /* Handle case where id(deque) == id(iterable) */
- if ((PyObject *)deque == iterable) {
- PyObject *result;
- PyObject *s = PySequence_List(iterable);
- if (s == NULL)
- return NULL;
- result = deque_extendleft(deque, s);
- Py_DECREF(s);
- return result;
- }
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- if (deque->maxlen == 0)
- return consume_iterator(it);
-
- while ((item = PyIter_Next(it)) != NULL) {
- deque->state++;
- if (deque->leftindex == 0) {
- block *b = newblock(NULL, deque->leftblock,
- deque->len);
- if (b == NULL) {
- Py_DECREF(item);
- Py_DECREF(it);
- return NULL;
- }
- assert(deque->leftblock->leftlink == NULL);
- deque->leftblock->leftlink = b;
- deque->leftblock = b;
- deque->leftindex = BLOCKLEN;
- }
- deque->len++;
- deque->leftindex--;
- deque->leftblock->data[deque->leftindex] = item;
- TRIM(deque, deque_pop);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_NONE;
+ PyObject *it, *item;
+
+ /* Handle case where id(deque) == id(iterable) */
+ if ((PyObject *)deque == iterable) {
+ PyObject *result;
+ PyObject *s = PySequence_List(iterable);
+ if (s == NULL)
+ return NULL;
+ result = deque_extendleft(deque, s);
+ Py_DECREF(s);
+ return result;
+ }
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ if (deque->maxlen == 0)
+ return consume_iterator(it);
+
+ while ((item = PyIter_Next(it)) != NULL) {
+ deque->state++;
+ if (deque->leftindex == 0) {
+ block *b = newblock(NULL, deque->leftblock,
+ deque->len);
+ if (b == NULL) {
+ Py_DECREF(item);
+ Py_DECREF(it);
+ return NULL;
+ }
+ assert(deque->leftblock->leftlink == NULL);
+ deque->leftblock->leftlink = b;
+ deque->leftblock = b;
+ deque->leftindex = BLOCKLEN;
+ }
+ deque->len++;
+ deque->leftindex--;
+ deque->leftblock->data[deque->leftindex] = item;
+ TRIM(deque, deque_pop);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(extendleft_doc,
@@ -400,63 +400,63 @@ PyDoc_STRVAR(extendleft_doc,
static PyObject *
deque_inplace_concat(dequeobject *deque, PyObject *other)
{
- PyObject *result;
-
- result = deque_extend(deque, other);
- if (result == NULL)
- return result;
- Py_DECREF(result);
- Py_INCREF(deque);
- return (PyObject *)deque;
+ PyObject *result;
+
+ result = deque_extend(deque, other);
+ if (result == NULL)
+ return result;
+ Py_DECREF(result);
+ Py_INCREF(deque);
+ return (PyObject *)deque;
}
static int
_deque_rotate(dequeobject *deque, Py_ssize_t n)
{
- Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
- PyObject *item, *rv;
-
- if (len == 0)
- return 0;
- if (n > halflen || n < -halflen) {
- n %= len;
- if (n > halflen)
- n -= len;
- else if (n < -halflen)
- n += len;
- }
-
- for (i=0 ; i<n ; i++) {
- item = deque_pop(deque, NULL);
- assert (item != NULL);
- rv = deque_appendleft(deque, item);
- Py_DECREF(item);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- for (i=0 ; i>n ; i--) {
- item = deque_popleft(deque, NULL);
- assert (item != NULL);
- rv = deque_append(deque, item);
- Py_DECREF(item);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- return 0;
+ Py_ssize_t i, len=deque->len, halflen=(len+1)>>1;
+ PyObject *item, *rv;
+
+ if (len == 0)
+ return 0;
+ if (n > halflen || n < -halflen) {
+ n %= len;
+ if (n > halflen)
+ n -= len;
+ else if (n < -halflen)
+ n += len;
+ }
+
+ for (i=0 ; i<n ; i++) {
+ item = deque_pop(deque, NULL);
+ assert (item != NULL);
+ rv = deque_appendleft(deque, item);
+ Py_DECREF(item);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ for (i=0 ; i>n ; i--) {
+ item = deque_popleft(deque, NULL);
+ assert (item != NULL);
+ rv = deque_append(deque, item);
+ Py_DECREF(item);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ return 0;
}
static PyObject *
deque_rotate(dequeobject *deque, PyObject *args)
{
- Py_ssize_t n=1;
+ Py_ssize_t n=1;
- if (!PyArg_ParseTuple(args, "|n:rotate", &n))
- return NULL;
- if (_deque_rotate(deque, n) == 0)
- Py_RETURN_NONE;
- return NULL;
+ if (!PyArg_ParseTuple(args, "|n:rotate", &n))
+ return NULL;
+ if (_deque_rotate(deque, n) == 0)
+ Py_RETURN_NONE;
+ return NULL;
}
PyDoc_STRVAR(rotate_doc,
@@ -465,40 +465,40 @@ PyDoc_STRVAR(rotate_doc,
static PyObject *
deque_reverse(dequeobject *deque, PyObject *unused)
{
- block *leftblock = deque->leftblock;
- block *rightblock = deque->rightblock;
- Py_ssize_t leftindex = deque->leftindex;
- Py_ssize_t rightindex = deque->rightindex;
- Py_ssize_t n = (deque->len)/2;
- Py_ssize_t i;
- PyObject *tmp;
-
- for (i=0 ; i<n ; i++) {
- /* Validate that pointers haven't met in the middle */
- assert(leftblock != rightblock || leftindex < rightindex);
-
- /* Swap */
- tmp = leftblock->data[leftindex];
- leftblock->data[leftindex] = rightblock->data[rightindex];
- rightblock->data[rightindex] = tmp;
-
- /* Advance left block/index pair */
- leftindex++;
- if (leftindex == BLOCKLEN) {
- assert (leftblock->rightlink != NULL);
- leftblock = leftblock->rightlink;
- leftindex = 0;
- }
-
- /* Step backwards with the right block/index pair */
- rightindex--;
- if (rightindex == -1) {
- assert (rightblock->leftlink != NULL);
- rightblock = rightblock->leftlink;
- rightindex = BLOCKLEN - 1;
- }
- }
- Py_RETURN_NONE;
+ block *leftblock = deque->leftblock;
+ block *rightblock = deque->rightblock;
+ Py_ssize_t leftindex = deque->leftindex;
+ Py_ssize_t rightindex = deque->rightindex;
+ Py_ssize_t n = (deque->len)/2;
+ Py_ssize_t i;
+ PyObject *tmp;
+
+ for (i=0 ; i<n ; i++) {
+ /* Validate that pointers haven't met in the middle */
+ assert(leftblock != rightblock || leftindex < rightindex);
+
+ /* Swap */
+ tmp = leftblock->data[leftindex];
+ leftblock->data[leftindex] = rightblock->data[rightindex];
+ rightblock->data[rightindex] = tmp;
+
+ /* Advance left block/index pair */
+ leftindex++;
+ if (leftindex == BLOCKLEN) {
+ assert (leftblock->rightlink != NULL);
+ leftblock = leftblock->rightlink;
+ leftindex = 0;
+ }
+
+ /* Step backwards with the right block/index pair */
+ rightindex--;
+ if (rightindex == -1) {
+ assert (rightblock->leftlink != NULL);
+ rightblock = rightblock->leftlink;
+ rightindex = BLOCKLEN - 1;
+ }
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(reverse_doc,
@@ -507,38 +507,38 @@ PyDoc_STRVAR(reverse_doc,
static PyObject *
deque_count(dequeobject *deque, PyObject *v)
{
- block *leftblock = deque->leftblock;
- Py_ssize_t leftindex = deque->leftindex;
- Py_ssize_t n = (deque->len);
- Py_ssize_t i;
- Py_ssize_t count = 0;
- PyObject *item;
- long start_state = deque->state;
- int cmp;
-
- for (i=0 ; i<n ; i++) {
- item = leftblock->data[leftindex];
- cmp = PyObject_RichCompareBool(item, v, Py_EQ);
- if (cmp > 0)
- count++;
- else if (cmp < 0)
- return NULL;
-
- if (start_state != deque->state) {
- PyErr_SetString(PyExc_RuntimeError,
- "deque mutated during iteration");
- return NULL;
- }
-
- /* Advance left block/index pair */
- leftindex++;
- if (leftindex == BLOCKLEN) {
- assert (leftblock->rightlink != NULL);
- leftblock = leftblock->rightlink;
- leftindex = 0;
- }
- }
- return PyInt_FromSsize_t(count);
+ block *leftblock = deque->leftblock;
+ Py_ssize_t leftindex = deque->leftindex;
+ Py_ssize_t n = (deque->len);
+ Py_ssize_t i;
+ Py_ssize_t count = 0;
+ PyObject *item;
+ long start_state = deque->state;
+ int cmp;
+
+ for (i=0 ; i<n ; i++) {
+ item = leftblock->data[leftindex];
+ cmp = PyObject_RichCompareBool(item, v, Py_EQ);
+ if (cmp > 0)
+ count++;
+ else if (cmp < 0)
+ return NULL;
+
+ if (start_state != deque->state) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "deque mutated during iteration");
+ return NULL;
+ }
+
+ /* Advance left block/index pair */
+ leftindex++;
+ if (leftindex == BLOCKLEN) {
+ assert (leftblock->rightlink != NULL);
+ leftblock = leftblock->rightlink;
+ leftindex = 0;
+ }
+ }
+ return PyInt_FromSsize_t(count);
}
PyDoc_STRVAR(count_doc,
@@ -547,39 +547,39 @@ PyDoc_STRVAR(count_doc,
static Py_ssize_t
deque_len(dequeobject *deque)
{
- return deque->len;
+ return deque->len;
}
static PyObject *
deque_remove(dequeobject *deque, PyObject *value)
{
- Py_ssize_t i, n=deque->len;
-
- for (i=0 ; i<n ; i++) {
- PyObject *item = deque->leftblock->data[deque->leftindex];
- int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
-
- if (deque->len != n) {
- PyErr_SetString(PyExc_IndexError,
- "deque mutated during remove().");
- return NULL;
- }
- if (cmp > 0) {
- PyObject *tgt = deque_popleft(deque, NULL);
- assert (tgt != NULL);
- Py_DECREF(tgt);
- if (_deque_rotate(deque, i) == -1)
- return NULL;
- Py_RETURN_NONE;
- }
- else if (cmp < 0) {
- _deque_rotate(deque, i);
- return NULL;
- }
- _deque_rotate(deque, -1);
- }
- PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
- return NULL;
+ Py_ssize_t i, n=deque->len;
+
+ for (i=0 ; i<n ; i++) {
+ PyObject *item = deque->leftblock->data[deque->leftindex];
+ int cmp = PyObject_RichCompareBool(item, value, Py_EQ);
+
+ if (deque->len != n) {
+ PyErr_SetString(PyExc_IndexError,
+ "deque mutated during remove().");
+ return NULL;
+ }
+ if (cmp > 0) {
+ PyObject *tgt = deque_popleft(deque, NULL);
+ assert (tgt != NULL);
+ Py_DECREF(tgt);
+ if (_deque_rotate(deque, i) == -1)
+ return NULL;
+ Py_RETURN_NONE;
+ }
+ else if (cmp < 0) {
+ _deque_rotate(deque, i);
+ return NULL;
+ }
+ _deque_rotate(deque, -1);
+ }
+ PyErr_SetString(PyExc_ValueError, "deque.remove(x): x not in deque");
+ return NULL;
}
PyDoc_STRVAR(remove_doc,
@@ -588,56 +588,56 @@ PyDoc_STRVAR(remove_doc,
static int
deque_clear(dequeobject *deque)
{
- PyObject *item;
-
- while (deque->len) {
- item = deque_pop(deque, NULL);
- assert (item != NULL);
- Py_DECREF(item);
- }
- assert(deque->leftblock == deque->rightblock &&
- deque->leftindex - 1 == deque->rightindex &&
- deque->len == 0);
- return 0;
+ PyObject *item;
+
+ while (deque->len) {
+ item = deque_pop(deque, NULL);
+ assert (item != NULL);
+ Py_DECREF(item);
+ }
+ assert(deque->leftblock == deque->rightblock &&
+ deque->leftindex - 1 == deque->rightindex &&
+ deque->len == 0);
+ return 0;
}
static PyObject *
deque_item(dequeobject *deque, Py_ssize_t i)
{
- block *b;
- PyObject *item;
- Py_ssize_t n, index=i;
-
- if (i < 0 || i >= deque->len) {
- PyErr_SetString(PyExc_IndexError,
- "deque index out of range");
- return NULL;
- }
-
- if (i == 0) {
- i = deque->leftindex;
- b = deque->leftblock;
- } else if (i == deque->len - 1) {
- i = deque->rightindex;
- b = deque->rightblock;
- } else {
- i += deque->leftindex;
- n = i / BLOCKLEN;
- i %= BLOCKLEN;
- if (index < (deque->len >> 1)) {
- b = deque->leftblock;
- while (n--)
- b = b->rightlink;
- } else {
- n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
- b = deque->rightblock;
- while (n--)
- b = b->leftlink;
- }
- }
- item = b->data[i];
- Py_INCREF(item);
- return item;
+ block *b;
+ PyObject *item;
+ Py_ssize_t n, index=i;
+
+ if (i < 0 || i >= deque->len) {
+ PyErr_SetString(PyExc_IndexError,
+ "deque index out of range");
+ return NULL;
+ }
+
+ if (i == 0) {
+ i = deque->leftindex;
+ b = deque->leftblock;
+ } else if (i == deque->len - 1) {
+ i = deque->rightindex;
+ b = deque->rightblock;
+ } else {
+ i += deque->leftindex;
+ n = i / BLOCKLEN;
+ i %= BLOCKLEN;
+ if (index < (deque->len >> 1)) {
+ b = deque->leftblock;
+ while (n--)
+ b = b->rightlink;
+ } else {
+ n = (deque->leftindex + deque->len - 1) / BLOCKLEN - n;
+ b = deque->rightblock;
+ while (n--)
+ b = b->leftlink;
+ }
+ }
+ item = b->data[i];
+ Py_INCREF(item);
+ return item;
}
/* delitem() implemented in terms of rotate for simplicity and reasonable
@@ -650,62 +650,62 @@ deque_item(dequeobject *deque, Py_ssize_t i)
static int
deque_del_item(dequeobject *deque, Py_ssize_t i)
{
- PyObject *item;
+ PyObject *item;
- assert (i >= 0 && i < deque->len);
- if (_deque_rotate(deque, -i) == -1)
- return -1;
+ assert (i >= 0 && i < deque->len);
+ if (_deque_rotate(deque, -i) == -1)
+ return -1;
- item = deque_popleft(deque, NULL);
- assert (item != NULL);
- Py_DECREF(item);
+ item = deque_popleft(deque, NULL);
+ assert (item != NULL);
+ Py_DECREF(item);
- return _deque_rotate(deque, i);
+ return _deque_rotate(deque, i);
}
static int
deque_ass_item(dequeobject *deque, Py_ssize_t i, PyObject *v)
{
- PyObject *old_value;
- block *b;
- Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
-
- if (i < 0 || i >= len) {
- PyErr_SetString(PyExc_IndexError,
- "deque index out of range");
- return -1;
- }
- if (v == NULL)
- return deque_del_item(deque, i);
-
- i += deque->leftindex;
- n = i / BLOCKLEN;
- i %= BLOCKLEN;
- if (index <= halflen) {
- b = deque->leftblock;
- while (n--)
- b = b->rightlink;
- } else {
- n = (deque->leftindex + len - 1) / BLOCKLEN - n;
- b = deque->rightblock;
- while (n--)
- b = b->leftlink;
- }
- Py_INCREF(v);
- old_value = b->data[i];
- b->data[i] = v;
- Py_DECREF(old_value);
- return 0;
+ PyObject *old_value;
+ block *b;
+ Py_ssize_t n, len=deque->len, halflen=(len+1)>>1, index=i;
+
+ if (i < 0 || i >= len) {
+ PyErr_SetString(PyExc_IndexError,
+ "deque index out of range");
+ return -1;
+ }
+ if (v == NULL)
+ return deque_del_item(deque, i);
+
+ i += deque->leftindex;
+ n = i / BLOCKLEN;
+ i %= BLOCKLEN;
+ if (index <= halflen) {
+ b = deque->leftblock;
+ while (n--)
+ b = b->rightlink;
+ } else {
+ n = (deque->leftindex + len - 1) / BLOCKLEN - n;
+ b = deque->rightblock;
+ while (n--)
+ b = b->leftlink;
+ }
+ Py_INCREF(v);
+ old_value = b->data[i];
+ b->data[i] = v;
+ Py_DECREF(old_value);
+ return 0;
}
static PyObject *
deque_clearmethod(dequeobject *deque)
{
- int rv;
+ int rv;
- rv = deque_clear(deque);
- assert (rv != -1);
- Py_RETURN_NONE;
+ rv = deque_clear(deque);
+ assert (rv != -1);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
@@ -713,49 +713,49 @@ PyDoc_STRVAR(clear_doc, "Remove all elements from the deque.");
static void
deque_dealloc(dequeobject *deque)
{
- PyObject_GC_UnTrack(deque);
- if (deque->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) deque);
- if (deque->leftblock != NULL) {
- deque_clear(deque);
- assert(deque->leftblock != NULL);
- freeblock(deque->leftblock);
- }
- deque->leftblock = NULL;
- deque->rightblock = NULL;
- Py_TYPE(deque)->tp_free(deque);
+ PyObject_GC_UnTrack(deque);
+ if (deque->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) deque);
+ if (deque->leftblock != NULL) {
+ deque_clear(deque);
+ assert(deque->leftblock != NULL);
+ freeblock(deque->leftblock);
+ }
+ deque->leftblock = NULL;
+ deque->rightblock = NULL;
+ Py_TYPE(deque)->tp_free(deque);
}
static int
deque_traverse(dequeobject *deque, visitproc visit, void *arg)
{
- block *b;
- PyObject *item;
- Py_ssize_t index;
- Py_ssize_t indexlo = deque->leftindex;
-
- for (b = deque->leftblock; b != NULL; b = b->rightlink) {
- const Py_ssize_t indexhi = b == deque->rightblock ?
- deque->rightindex :
- BLOCKLEN - 1;
-
- for (index = indexlo; index <= indexhi; ++index) {
- item = b->data[index];
- Py_VISIT(item);
- }
- indexlo = 0;
- }
- return 0;
+ block *b;
+ PyObject *item;
+ Py_ssize_t index;
+ Py_ssize_t indexlo = deque->leftindex;
+
+ for (b = deque->leftblock; b != NULL; b = b->rightlink) {
+ const Py_ssize_t indexhi = b == deque->rightblock ?
+ deque->rightindex :
+ BLOCKLEN - 1;
+
+ for (index = indexlo; index <= indexhi; ++index) {
+ item = b->data[index];
+ Py_VISIT(item);
+ }
+ indexlo = 0;
+ }
+ return 0;
}
static PyObject *
deque_copy(PyObject *deque)
{
- if (((dequeobject *)deque)->maxlen == -1)
- return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
- else
- return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
- deque, ((dequeobject *)deque)->maxlen, NULL);
+ if (((dequeobject *)deque)->maxlen == -1)
+ return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "O", deque, NULL);
+ else
+ return PyObject_CallFunction((PyObject *)(Py_TYPE(deque)), "Oi",
+ deque, ((dequeobject *)deque)->maxlen, NULL);
}
PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
@@ -763,30 +763,30 @@ PyDoc_STRVAR(copy_doc, "Return a shallow copy of a deque.");
static PyObject *
deque_reduce(dequeobject *deque)
{
- PyObject *dict, *result, *aslist;
-
- dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
- if (dict == NULL)
- PyErr_Clear();
- aslist = PySequence_List((PyObject *)deque);
- if (aslist == NULL) {
- Py_XDECREF(dict);
- return NULL;
- }
- if (dict == NULL) {
- if (deque->maxlen == -1)
- result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
- else
- result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
- } else {
- if (deque->maxlen == -1)
- result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
- else
- result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
- }
- Py_XDECREF(dict);
- Py_DECREF(aslist);
- return result;
+ PyObject *dict, *result, *aslist;
+
+ dict = PyObject_GetAttrString((PyObject *)deque, "__dict__");
+ if (dict == NULL)
+ PyErr_Clear();
+ aslist = PySequence_List((PyObject *)deque);
+ if (aslist == NULL) {
+ Py_XDECREF(dict);
+ return NULL;
+ }
+ if (dict == NULL) {
+ if (deque->maxlen == -1)
+ result = Py_BuildValue("O(O)", Py_TYPE(deque), aslist);
+ else
+ result = Py_BuildValue("O(On)", Py_TYPE(deque), aslist, deque->maxlen);
+ } else {
+ if (deque->maxlen == -1)
+ result = Py_BuildValue("O(OO)O", Py_TYPE(deque), aslist, Py_None, dict);
+ else
+ result = Py_BuildValue("O(On)O", Py_TYPE(deque), aslist, deque->maxlen, dict);
+ }
+ Py_XDECREF(dict);
+ Py_DECREF(aslist);
+ return result;
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
@@ -794,224 +794,224 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyObject *
deque_repr(PyObject *deque)
{
- PyObject *aslist, *result, *fmt;
- int i;
-
- i = Py_ReprEnter(deque);
- if (i != 0) {
- if (i < 0)
- return NULL;
- return PyString_FromString("[...]");
- }
-
- aslist = PySequence_List(deque);
- if (aslist == NULL) {
- Py_ReprLeave(deque);
- return NULL;
- }
- if (((dequeobject *)deque)->maxlen != -1)
- fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
- ((dequeobject *)deque)->maxlen);
- else
- fmt = PyString_FromString("deque(%r)");
- if (fmt == NULL) {
- Py_DECREF(aslist);
- Py_ReprLeave(deque);
- return NULL;
- }
- result = PyString_Format(fmt, aslist);
- Py_DECREF(fmt);
- Py_DECREF(aslist);
- Py_ReprLeave(deque);
- return result;
+ PyObject *aslist, *result, *fmt;
+ int i;
+
+ i = Py_ReprEnter(deque);
+ if (i != 0) {
+ if (i < 0)
+ return NULL;
+ return PyString_FromString("[...]");
+ }
+
+ aslist = PySequence_List(deque);
+ if (aslist == NULL) {
+ Py_ReprLeave(deque);
+ return NULL;
+ }
+ if (((dequeobject *)deque)->maxlen != -1)
+ fmt = PyString_FromFormat("deque(%%r, maxlen=%zd)",
+ ((dequeobject *)deque)->maxlen);
+ else
+ fmt = PyString_FromString("deque(%r)");
+ if (fmt == NULL) {
+ Py_DECREF(aslist);
+ Py_ReprLeave(deque);
+ return NULL;
+ }
+ result = PyString_Format(fmt, aslist);
+ Py_DECREF(fmt);
+ Py_DECREF(aslist);
+ Py_ReprLeave(deque);
+ return result;
}
static int
deque_tp_print(PyObject *deque, FILE *fp, int flags)
{
- PyObject *it, *item;
- char *emit = ""; /* No separator emitted on first pass */
- char *separator = ", ";
- int i;
-
- i = Py_ReprEnter(deque);
- if (i != 0) {
- if (i < 0)
- return i;
- Py_BEGIN_ALLOW_THREADS
- fputs("[...]", fp);
- Py_END_ALLOW_THREADS
- return 0;
- }
-
- it = PyObject_GetIter(deque);
- if (it == NULL)
- return -1;
-
- Py_BEGIN_ALLOW_THREADS
- fputs("deque([", fp);
- Py_END_ALLOW_THREADS
- while ((item = PyIter_Next(it)) != NULL) {
- Py_BEGIN_ALLOW_THREADS
- fputs(emit, fp);
- Py_END_ALLOW_THREADS
- emit = separator;
- if (PyObject_Print(item, fp, 0) != 0) {
- Py_DECREF(item);
- Py_DECREF(it);
- Py_ReprLeave(deque);
- return -1;
- }
- Py_DECREF(item);
- }
- Py_ReprLeave(deque);
- Py_DECREF(it);
- if (PyErr_Occurred())
- return -1;
-
- Py_BEGIN_ALLOW_THREADS
- if (((dequeobject *)deque)->maxlen == -1)
- fputs("])", fp);
- else
- fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
- Py_END_ALLOW_THREADS
- return 0;
+ PyObject *it, *item;
+ char *emit = ""; /* No separator emitted on first pass */
+ char *separator = ", ";
+ int i;
+
+ i = Py_ReprEnter(deque);
+ if (i != 0) {
+ if (i < 0)
+ return i;
+ Py_BEGIN_ALLOW_THREADS
+ fputs("[...]", fp);
+ Py_END_ALLOW_THREADS
+ return 0;
+ }
+
+ it = PyObject_GetIter(deque);
+ if (it == NULL)
+ return -1;
+
+ Py_BEGIN_ALLOW_THREADS
+ fputs("deque([", fp);
+ Py_END_ALLOW_THREADS
+ while ((item = PyIter_Next(it)) != NULL) {
+ Py_BEGIN_ALLOW_THREADS
+ fputs(emit, fp);
+ Py_END_ALLOW_THREADS
+ emit = separator;
+ if (PyObject_Print(item, fp, 0) != 0) {
+ Py_DECREF(item);
+ Py_DECREF(it);
+ Py_ReprLeave(deque);
+ return -1;
+ }
+ Py_DECREF(item);
+ }
+ Py_ReprLeave(deque);
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return -1;
+
+ Py_BEGIN_ALLOW_THREADS
+ if (((dequeobject *)deque)->maxlen == -1)
+ fputs("])", fp);
+ else
+ fprintf(fp, "], maxlen=%" PY_FORMAT_SIZE_T "d)", ((dequeobject *)deque)->maxlen);
+ Py_END_ALLOW_THREADS
+ return 0;
}
static PyObject *
deque_richcompare(PyObject *v, PyObject *w, int op)
{
- PyObject *it1=NULL, *it2=NULL, *x, *y;
- Py_ssize_t vs, ws;
- int b, cmp=-1;
-
- if (!PyObject_TypeCheck(v, &deque_type) ||
- !PyObject_TypeCheck(w, &deque_type)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- /* Shortcuts */
- vs = ((dequeobject *)v)->len;
- ws = ((dequeobject *)w)->len;
- if (op == Py_EQ) {
- if (v == w)
- Py_RETURN_TRUE;
- if (vs != ws)
- Py_RETURN_FALSE;
- }
- if (op == Py_NE) {
- if (v == w)
- Py_RETURN_FALSE;
- if (vs != ws)
- Py_RETURN_TRUE;
- }
-
- /* Search for the first index where items are different */
- it1 = PyObject_GetIter(v);
- if (it1 == NULL)
- goto done;
- it2 = PyObject_GetIter(w);
- if (it2 == NULL)
- goto done;
- for (;;) {
- x = PyIter_Next(it1);
- if (x == NULL && PyErr_Occurred())
- goto done;
- y = PyIter_Next(it2);
- if (x == NULL || y == NULL)
- break;
- b = PyObject_RichCompareBool(x, y, Py_EQ);
- if (b == 0) {
- cmp = PyObject_RichCompareBool(x, y, op);
- Py_DECREF(x);
- Py_DECREF(y);
- goto done;
- }
- Py_DECREF(x);
- Py_DECREF(y);
- if (b == -1)
- goto done;
- }
- /* We reached the end of one deque or both */
- Py_XDECREF(x);
- Py_XDECREF(y);
- if (PyErr_Occurred())
- goto done;
- switch (op) {
- case Py_LT: cmp = y != NULL; break; /* if w was longer */
- case Py_LE: cmp = x == NULL; break; /* if v was not longer */
- case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
- case Py_NE: cmp = x != y; break; /* if one deque continues */
- case Py_GT: cmp = x != NULL; break; /* if v was longer */
- case Py_GE: cmp = y == NULL; break; /* if w was not longer */
- }
+ PyObject *it1=NULL, *it2=NULL, *x, *y;
+ Py_ssize_t vs, ws;
+ int b, cmp=-1;
+
+ if (!PyObject_TypeCheck(v, &deque_type) ||
+ !PyObject_TypeCheck(w, &deque_type)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ /* Shortcuts */
+ vs = ((dequeobject *)v)->len;
+ ws = ((dequeobject *)w)->len;
+ if (op == Py_EQ) {
+ if (v == w)
+ Py_RETURN_TRUE;
+ if (vs != ws)
+ Py_RETURN_FALSE;
+ }
+ if (op == Py_NE) {
+ if (v == w)
+ Py_RETURN_FALSE;
+ if (vs != ws)
+ Py_RETURN_TRUE;
+ }
+
+ /* Search for the first index where items are different */
+ it1 = PyObject_GetIter(v);
+ if (it1 == NULL)
+ goto done;
+ it2 = PyObject_GetIter(w);
+ if (it2 == NULL)
+ goto done;
+ for (;;) {
+ x = PyIter_Next(it1);
+ if (x == NULL && PyErr_Occurred())
+ goto done;
+ y = PyIter_Next(it2);
+ if (x == NULL || y == NULL)
+ break;
+ b = PyObject_RichCompareBool(x, y, Py_EQ);
+ if (b == 0) {
+ cmp = PyObject_RichCompareBool(x, y, op);
+ Py_DECREF(x);
+ Py_DECREF(y);
+ goto done;
+ }
+ Py_DECREF(x);
+ Py_DECREF(y);
+ if (b == -1)
+ goto done;
+ }
+ /* We reached the end of one deque or both */
+ Py_XDECREF(x);
+ Py_XDECREF(y);
+ if (PyErr_Occurred())
+ goto done;
+ switch (op) {
+ case Py_LT: cmp = y != NULL; break; /* if w was longer */
+ case Py_LE: cmp = x == NULL; break; /* if v was not longer */
+ case Py_EQ: cmp = x == y; break; /* if we reached the end of both */
+ case Py_NE: cmp = x != y; break; /* if one deque continues */
+ case Py_GT: cmp = x != NULL; break; /* if v was longer */
+ case Py_GE: cmp = y == NULL; break; /* if w was not longer */
+ }
done:
- Py_XDECREF(it1);
- Py_XDECREF(it2);
- if (cmp == 1)
- Py_RETURN_TRUE;
- if (cmp == 0)
- Py_RETURN_FALSE;
- return NULL;
+ Py_XDECREF(it1);
+ Py_XDECREF(it2);
+ if (cmp == 1)
+ Py_RETURN_TRUE;
+ if (cmp == 0)
+ Py_RETURN_FALSE;
+ return NULL;
}
static int
deque_init(dequeobject *deque, PyObject *args, PyObject *kwdargs)
{
- PyObject *iterable = NULL;
- PyObject *maxlenobj = NULL;
- Py_ssize_t maxlen = -1;
- char *kwlist[] = {"iterable", "maxlen", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
- return -1;
- if (maxlenobj != NULL && maxlenobj != Py_None) {
- maxlen = PyInt_AsSsize_t(maxlenobj);
- if (maxlen == -1 && PyErr_Occurred())
- return -1;
- if (maxlen < 0) {
- PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
- return -1;
- }
- }
- deque->maxlen = maxlen;
- deque_clear(deque);
- if (iterable != NULL) {
- PyObject *rv = deque_extend(deque, iterable);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- return 0;
+ PyObject *iterable = NULL;
+ PyObject *maxlenobj = NULL;
+ Py_ssize_t maxlen = -1;
+ char *kwlist[] = {"iterable", "maxlen", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdargs, "|OO:deque", kwlist, &iterable, &maxlenobj))
+ return -1;
+ if (maxlenobj != NULL && maxlenobj != Py_None) {
+ maxlen = PyInt_AsSsize_t(maxlenobj);
+ if (maxlen == -1 && PyErr_Occurred())
+ return -1;
+ if (maxlen < 0) {
+ PyErr_SetString(PyExc_ValueError, "maxlen must be non-negative");
+ return -1;
+ }
+ }
+ deque->maxlen = maxlen;
+ deque_clear(deque);
+ if (iterable != NULL) {
+ PyObject *rv = deque_extend(deque, iterable);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ return 0;
}
static PyObject *
deque_get_maxlen(dequeobject *deque)
{
- if (deque->maxlen == -1)
- Py_RETURN_NONE;
- return PyInt_FromSsize_t(deque->maxlen);
+ if (deque->maxlen == -1)
+ Py_RETURN_NONE;
+ return PyInt_FromSsize_t(deque->maxlen);
}
static PyGetSetDef deque_getset[] = {
- {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
- "maximum size of a deque or None if unbounded"},
- {0}
+ {"maxlen", (getter)deque_get_maxlen, (setter)NULL,
+ "maximum size of a deque or None if unbounded"},
+ {0}
};
static PySequenceMethods deque_as_sequence = {
- (lenfunc)deque_len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)deque_item, /* sq_item */
- 0, /* sq_slice */
- (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
- 0, /* sq_ass_slice */
- 0, /* sq_contains */
- (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ (lenfunc)deque_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ (ssizeargfunc)deque_item, /* sq_item */
+ 0, /* sq_slice */
+ (ssizeobjargproc)deque_ass_item, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ 0, /* sq_contains */
+ (binaryfunc)deque_inplace_concat, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
@@ -1020,38 +1020,38 @@ static PySequenceMethods deque_as_sequence = {
static PyObject *deque_iter(dequeobject *deque);
static PyObject *deque_reviter(dequeobject *deque);
PyDoc_STRVAR(reversed_doc,
- "D.__reversed__() -- return a reverse iterator over the deque");
+ "D.__reversed__() -- return a reverse iterator over the deque");
static PyMethodDef deque_methods[] = {
- {"append", (PyCFunction)deque_append,
- METH_O, append_doc},
- {"appendleft", (PyCFunction)deque_appendleft,
- METH_O, appendleft_doc},
- {"clear", (PyCFunction)deque_clearmethod,
- METH_NOARGS, clear_doc},
- {"__copy__", (PyCFunction)deque_copy,
- METH_NOARGS, copy_doc},
- {"count", (PyCFunction)deque_count,
- METH_O, count_doc},
- {"extend", (PyCFunction)deque_extend,
- METH_O, extend_doc},
- {"extendleft", (PyCFunction)deque_extendleft,
- METH_O, extendleft_doc},
- {"pop", (PyCFunction)deque_pop,
- METH_NOARGS, pop_doc},
- {"popleft", (PyCFunction)deque_popleft,
- METH_NOARGS, popleft_doc},
- {"__reduce__", (PyCFunction)deque_reduce,
- METH_NOARGS, reduce_doc},
- {"remove", (PyCFunction)deque_remove,
- METH_O, remove_doc},
- {"__reversed__", (PyCFunction)deque_reviter,
- METH_NOARGS, reversed_doc},
- {"reverse", (PyCFunction)deque_reverse,
- METH_NOARGS, reverse_doc},
- {"rotate", (PyCFunction)deque_rotate,
- METH_VARARGS, rotate_doc},
- {NULL, NULL} /* sentinel */
+ {"append", (PyCFunction)deque_append,
+ METH_O, append_doc},
+ {"appendleft", (PyCFunction)deque_appendleft,
+ METH_O, appendleft_doc},
+ {"clear", (PyCFunction)deque_clearmethod,
+ METH_NOARGS, clear_doc},
+ {"__copy__", (PyCFunction)deque_copy,
+ METH_NOARGS, copy_doc},
+ {"count", (PyCFunction)deque_count,
+ METH_O, count_doc},
+ {"extend", (PyCFunction)deque_extend,
+ METH_O, extend_doc},
+ {"extendleft", (PyCFunction)deque_extendleft,
+ METH_O, extendleft_doc},
+ {"pop", (PyCFunction)deque_pop,
+ METH_NOARGS, pop_doc},
+ {"popleft", (PyCFunction)deque_popleft,
+ METH_NOARGS, popleft_doc},
+ {"__reduce__", (PyCFunction)deque_reduce,
+ METH_NOARGS, reduce_doc},
+ {"remove", (PyCFunction)deque_remove,
+ METH_O, remove_doc},
+ {"__reversed__", (PyCFunction)deque_reviter,
+ METH_NOARGS, reversed_doc},
+ {"reverse", (PyCFunction)deque_reverse,
+ METH_NOARGS, reverse_doc},
+ {"rotate", (PyCFunction)deque_rotate,
+ METH_VARARGS, rotate_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(deque_doc,
@@ -1060,58 +1060,58 @@ PyDoc_STRVAR(deque_doc,
Build an ordered collection accessible from endpoints only.");
static PyTypeObject deque_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "collections.deque", /* tp_name */
- sizeof(dequeobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)deque_dealloc, /* tp_dealloc */
- deque_tp_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- deque_repr, /* tp_repr */
- 0, /* tp_as_number */
- &deque_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)PyObject_HashNotImplemented, /* 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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
- deque_doc, /* tp_doc */
- (traverseproc)deque_traverse, /* tp_traverse */
- (inquiry)deque_clear, /* tp_clear */
- (richcmpfunc)deque_richcompare, /* tp_richcompare */
- offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
- (getiterfunc)deque_iter, /* tp_iter */
- 0, /* tp_iternext */
- deque_methods, /* tp_methods */
- 0, /* tp_members */
- deque_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)deque_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- deque_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "collections.deque", /* tp_name */
+ sizeof(dequeobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)deque_dealloc, /* tp_dealloc */
+ deque_tp_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ deque_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &deque_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)PyObject_HashNotImplemented, /* 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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
+ deque_doc, /* tp_doc */
+ (traverseproc)deque_traverse, /* tp_traverse */
+ (inquiry)deque_clear, /* tp_clear */
+ (richcmpfunc)deque_richcompare, /* tp_richcompare */
+ offsetof(dequeobject, weakreflist), /* tp_weaklistoffset*/
+ (getiterfunc)deque_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ deque_methods, /* tp_methods */
+ 0, /* tp_members */
+ deque_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)deque_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ deque_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/*********************** Deque Iterator **************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t index;
- block *b;
- dequeobject *deque;
- long state; /* state when the iterator is created */
- Py_ssize_t counter; /* number of items remaining for iteration */
+ PyObject_HEAD
+ Py_ssize_t index;
+ block *b;
+ dequeobject *deque;
+ long state; /* state when the iterator is created */
+ Py_ssize_t counter; /* number of items remaining for iteration */
} dequeiterobject;
static PyTypeObject dequeiter_type;
@@ -1119,107 +1119,107 @@ static PyTypeObject dequeiter_type;
static PyObject *
deque_iter(dequeobject *deque)
{
- dequeiterobject *it;
-
- it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
- if (it == NULL)
- return NULL;
- it->b = deque->leftblock;
- it->index = deque->leftindex;
- Py_INCREF(deque);
- it->deque = deque;
- it->state = deque->state;
- it->counter = deque->len;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ dequeiterobject *it;
+
+ it = PyObject_GC_New(dequeiterobject, &dequeiter_type);
+ if (it == NULL)
+ return NULL;
+ it->b = deque->leftblock;
+ it->index = deque->leftindex;
+ Py_INCREF(deque);
+ it->deque = deque;
+ it->state = deque->state;
+ it->counter = deque->len;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static int
dequeiter_traverse(dequeiterobject *dio, visitproc visit, void *arg)
{
- Py_VISIT(dio->deque);
- return 0;
+ Py_VISIT(dio->deque);
+ return 0;
}
static void
dequeiter_dealloc(dequeiterobject *dio)
{
- Py_XDECREF(dio->deque);
- PyObject_GC_Del(dio);
+ Py_XDECREF(dio->deque);
+ PyObject_GC_Del(dio);
}
static PyObject *
dequeiter_next(dequeiterobject *it)
{
- PyObject *item;
-
- if (it->deque->state != it->state) {
- it->counter = 0;
- PyErr_SetString(PyExc_RuntimeError,
- "deque mutated during iteration");
- return NULL;
- }
- if (it->counter == 0)
- return NULL;
- assert (!(it->b == it->deque->rightblock &&
- it->index > it->deque->rightindex));
-
- item = it->b->data[it->index];
- it->index++;
- it->counter--;
- if (it->index == BLOCKLEN && it->counter > 0) {
- assert (it->b->rightlink != NULL);
- it->b = it->b->rightlink;
- it->index = 0;
- }
- Py_INCREF(item);
- return item;
+ PyObject *item;
+
+ if (it->deque->state != it->state) {
+ it->counter = 0;
+ PyErr_SetString(PyExc_RuntimeError,
+ "deque mutated during iteration");
+ return NULL;
+ }
+ if (it->counter == 0)
+ return NULL;
+ assert (!(it->b == it->deque->rightblock &&
+ it->index > it->deque->rightindex));
+
+ item = it->b->data[it->index];
+ it->index++;
+ it->counter--;
+ if (it->index == BLOCKLEN && it->counter > 0) {
+ assert (it->b->rightlink != NULL);
+ it->b = it->b->rightlink;
+ it->index = 0;
+ }
+ Py_INCREF(item);
+ return item;
}
static PyObject *
dequeiter_len(dequeiterobject *it)
{
- return PyInt_FromLong(it->counter);
+ return PyInt_FromLong(it->counter);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef dequeiter_methods[] = {
- {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)dequeiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject dequeiter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "deque_iterator", /* tp_name */
- sizeof(dequeiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dequeiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dequeiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dequeiter_next, /* tp_iternext */
- dequeiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "deque_iterator", /* tp_name */
+ sizeof(dequeiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dequeiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dequeiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dequeiter_next, /* tp_iternext */
+ dequeiter_methods, /* tp_methods */
+ 0,
};
/*********************** Deque Reverse Iterator **************************/
@@ -1229,87 +1229,87 @@ static PyTypeObject dequereviter_type;
static PyObject *
deque_reviter(dequeobject *deque)
{
- dequeiterobject *it;
-
- it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
- if (it == NULL)
- return NULL;
- it->b = deque->rightblock;
- it->index = deque->rightindex;
- Py_INCREF(deque);
- it->deque = deque;
- it->state = deque->state;
- it->counter = deque->len;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ dequeiterobject *it;
+
+ it = PyObject_GC_New(dequeiterobject, &dequereviter_type);
+ if (it == NULL)
+ return NULL;
+ it->b = deque->rightblock;
+ it->index = deque->rightindex;
+ Py_INCREF(deque);
+ it->deque = deque;
+ it->state = deque->state;
+ it->counter = deque->len;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static PyObject *
dequereviter_next(dequeiterobject *it)
{
- PyObject *item;
- if (it->counter == 0)
- return NULL;
-
- if (it->deque->state != it->state) {
- it->counter = 0;
- PyErr_SetString(PyExc_RuntimeError,
- "deque mutated during iteration");
- return NULL;
- }
- assert (!(it->b == it->deque->leftblock &&
- it->index < it->deque->leftindex));
-
- item = it->b->data[it->index];
- it->index--;
- it->counter--;
- if (it->index == -1 && it->counter > 0) {
- assert (it->b->leftlink != NULL);
- it->b = it->b->leftlink;
- it->index = BLOCKLEN - 1;
- }
- Py_INCREF(item);
- return item;
+ PyObject *item;
+ if (it->counter == 0)
+ return NULL;
+
+ if (it->deque->state != it->state) {
+ it->counter = 0;
+ PyErr_SetString(PyExc_RuntimeError,
+ "deque mutated during iteration");
+ return NULL;
+ }
+ assert (!(it->b == it->deque->leftblock &&
+ it->index < it->deque->leftindex));
+
+ item = it->b->data[it->index];
+ it->index--;
+ it->counter--;
+ if (it->index == -1 && it->counter > 0) {
+ assert (it->b->leftlink != NULL);
+ it->b = it->b->leftlink;
+ it->index = BLOCKLEN - 1;
+ }
+ Py_INCREF(item);
+ return item;
}
static PyTypeObject dequereviter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "deque_reverse_iterator", /* tp_name */
- sizeof(dequeiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dequeiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dequeiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dequereviter_next, /* tp_iternext */
- dequeiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "deque_reverse_iterator", /* tp_name */
+ sizeof(dequeiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dequeiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dequeiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dequereviter_next, /* tp_iternext */
+ dequeiter_methods, /* tp_methods */
+ 0,
};
/* defaultdict type *********************************************************/
typedef struct {
- PyDictObject dict;
- PyObject *default_factory;
+ PyDictObject dict;
+ PyObject *default_factory;
} defdictobject;
static PyTypeObject defdict_type; /* Forward */
@@ -1324,25 +1324,25 @@ PyDoc_STRVAR(defdict_missing_doc,
static PyObject *
defdict_missing(defdictobject *dd, PyObject *key)
{
- PyObject *factory = dd->default_factory;
- PyObject *value;
- if (factory == NULL || factory == Py_None) {
- /* XXX Call dict.__missing__(key) */
- PyObject *tup;
- tup = PyTuple_Pack(1, key);
- if (!tup) return NULL;
- PyErr_SetObject(PyExc_KeyError, tup);
- Py_DECREF(tup);
- return NULL;
- }
- value = PyEval_CallObject(factory, NULL);
- if (value == NULL)
- return value;
- if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
- Py_DECREF(value);
- return NULL;
- }
- return value;
+ PyObject *factory = dd->default_factory;
+ PyObject *value;
+ if (factory == NULL || factory == Py_None) {
+ /* XXX Call dict.__missing__(key) */
+ PyObject *tup;
+ tup = PyTuple_Pack(1, key);
+ if (!tup) return NULL;
+ PyErr_SetObject(PyExc_KeyError, tup);
+ Py_DECREF(tup);
+ return NULL;
+ }
+ value = PyEval_CallObject(factory, NULL);
+ if (value == NULL)
+ return value;
+ if (PyObject_SetItem((PyObject *)dd, key, value) < 0) {
+ Py_DECREF(value);
+ return NULL;
+ }
+ return value;
}
PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
@@ -1350,192 +1350,192 @@ PyDoc_STRVAR(defdict_copy_doc, "D.copy() -> a shallow copy of D.");
static PyObject *
defdict_copy(defdictobject *dd)
{
- /* This calls the object's class. That only works for subclasses
- whose class constructor has the same signature. Subclasses that
- define a different constructor signature must override copy().
- */
-
- if (dd->default_factory == NULL)
- return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
- return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
- dd->default_factory, dd, NULL);
+ /* This calls the object's class. That only works for subclasses
+ whose class constructor has the same signature. Subclasses that
+ define a different constructor signature must override copy().
+ */
+
+ if (dd->default_factory == NULL)
+ return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd), Py_None, dd, NULL);
+ return PyObject_CallFunctionObjArgs((PyObject*)Py_TYPE(dd),
+ dd->default_factory, dd, NULL);
}
static PyObject *
defdict_reduce(defdictobject *dd)
{
- /* __reduce__ must return a 5-tuple as follows:
-
- - factory function
- - tuple of args for the factory function
- - additional state (here None)
- - sequence iterator (here None)
- - dictionary iterator (yielding successive (key, value) pairs
-
- This API is used by pickle.py and copy.py.
-
- For this to be useful with pickle.py, the default_factory
- must be picklable; e.g., None, a built-in, or a global
- function in a module or package.
-
- Both shallow and deep copying are supported, but for deep
- copying, the default_factory must be deep-copyable; e.g. None,
- or a built-in (functions are not copyable at this time).
-
- This only works for subclasses as long as their constructor
- signature is compatible; the first argument must be the
- optional default_factory, defaulting to None.
- */
- PyObject *args;
- PyObject *items;
- PyObject *result;
- if (dd->default_factory == NULL || dd->default_factory == Py_None)
- args = PyTuple_New(0);
- else
- args = PyTuple_Pack(1, dd->default_factory);
- if (args == NULL)
- return NULL;
- items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
- if (items == NULL) {
- Py_DECREF(args);
- return NULL;
- }
- result = PyTuple_Pack(5, Py_TYPE(dd), args,
- Py_None, Py_None, items);
- Py_DECREF(items);
- Py_DECREF(args);
- return result;
+ /* __reduce__ must return a 5-tuple as follows:
+
+ - factory function
+ - tuple of args for the factory function
+ - additional state (here None)
+ - sequence iterator (here None)
+ - dictionary iterator (yielding successive (key, value) pairs
+
+ This API is used by pickle.py and copy.py.
+
+ For this to be useful with pickle.py, the default_factory
+ must be picklable; e.g., None, a built-in, or a global
+ function in a module or package.
+
+ Both shallow and deep copying are supported, but for deep
+ copying, the default_factory must be deep-copyable; e.g. None,
+ or a built-in (functions are not copyable at this time).
+
+ This only works for subclasses as long as their constructor
+ signature is compatible; the first argument must be the
+ optional default_factory, defaulting to None.
+ */
+ PyObject *args;
+ PyObject *items;
+ PyObject *result;
+ if (dd->default_factory == NULL || dd->default_factory == Py_None)
+ args = PyTuple_New(0);
+ else
+ args = PyTuple_Pack(1, dd->default_factory);
+ if (args == NULL)
+ return NULL;
+ items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
+ if (items == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ result = PyTuple_Pack(5, Py_TYPE(dd), args,
+ Py_None, Py_None, items);
+ Py_DECREF(items);
+ Py_DECREF(args);
+ return result;
}
static PyMethodDef defdict_methods[] = {
- {"__missing__", (PyCFunction)defdict_missing, METH_O,
- defdict_missing_doc},
- {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
- defdict_copy_doc},
- {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
- defdict_copy_doc},
- {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
- reduce_doc},
- {NULL}
+ {"__missing__", (PyCFunction)defdict_missing, METH_O,
+ defdict_missing_doc},
+ {"copy", (PyCFunction)defdict_copy, METH_NOARGS,
+ defdict_copy_doc},
+ {"__copy__", (PyCFunction)defdict_copy, METH_NOARGS,
+ defdict_copy_doc},
+ {"__reduce__", (PyCFunction)defdict_reduce, METH_NOARGS,
+ reduce_doc},
+ {NULL}
};
static PyMemberDef defdict_members[] = {
- {"default_factory", T_OBJECT,
- offsetof(defdictobject, default_factory), 0,
- PyDoc_STR("Factory for default value called by __missing__().")},
- {NULL}
+ {"default_factory", T_OBJECT,
+ offsetof(defdictobject, default_factory), 0,
+ PyDoc_STR("Factory for default value called by __missing__().")},
+ {NULL}
};
static void
defdict_dealloc(defdictobject *dd)
{
- Py_CLEAR(dd->default_factory);
- PyDict_Type.tp_dealloc((PyObject *)dd);
+ Py_CLEAR(dd->default_factory);
+ PyDict_Type.tp_dealloc((PyObject *)dd);
}
static int
defdict_print(defdictobject *dd, FILE *fp, int flags)
{
- int sts;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "defaultdict(");
- Py_END_ALLOW_THREADS
- if (dd->default_factory == NULL) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "None");
- Py_END_ALLOW_THREADS
- } else {
- PyObject_Print(dd->default_factory, fp, 0);
- }
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ", ");
- Py_END_ALLOW_THREADS
- sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ")");
- Py_END_ALLOW_THREADS
- return sts;
+ int sts;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "defaultdict(");
+ Py_END_ALLOW_THREADS
+ if (dd->default_factory == NULL) {
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "None");
+ Py_END_ALLOW_THREADS
+ } else {
+ PyObject_Print(dd->default_factory, fp, 0);
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ", ");
+ Py_END_ALLOW_THREADS
+ sts = PyDict_Type.tp_print((PyObject *)dd, fp, 0);
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ")");
+ Py_END_ALLOW_THREADS
+ return sts;
}
static PyObject *
defdict_repr(defdictobject *dd)
{
- PyObject *defrepr;
- PyObject *baserepr;
- PyObject *result;
- baserepr = PyDict_Type.tp_repr((PyObject *)dd);
- if (baserepr == NULL)
- return NULL;
- if (dd->default_factory == NULL)
- defrepr = PyString_FromString("None");
- else
- {
- int status = Py_ReprEnter(dd->default_factory);
- if (status != 0) {
- if (status < 0)
- return NULL;
- defrepr = PyString_FromString("...");
- }
- else
- defrepr = PyObject_Repr(dd->default_factory);
- Py_ReprLeave(dd->default_factory);
- }
- if (defrepr == NULL) {
- Py_DECREF(baserepr);
- return NULL;
- }
- result = PyString_FromFormat("defaultdict(%s, %s)",
- PyString_AS_STRING(defrepr),
- PyString_AS_STRING(baserepr));
- Py_DECREF(defrepr);
- Py_DECREF(baserepr);
- return result;
+ PyObject *defrepr;
+ PyObject *baserepr;
+ PyObject *result;
+ baserepr = PyDict_Type.tp_repr((PyObject *)dd);
+ if (baserepr == NULL)
+ return NULL;
+ if (dd->default_factory == NULL)
+ defrepr = PyString_FromString("None");
+ else
+ {
+ int status = Py_ReprEnter(dd->default_factory);
+ if (status != 0) {
+ if (status < 0)
+ return NULL;
+ defrepr = PyString_FromString("...");
+ }
+ else
+ defrepr = PyObject_Repr(dd->default_factory);
+ Py_ReprLeave(dd->default_factory);
+ }
+ if (defrepr == NULL) {
+ Py_DECREF(baserepr);
+ return NULL;
+ }
+ result = PyString_FromFormat("defaultdict(%s, %s)",
+ PyString_AS_STRING(defrepr),
+ PyString_AS_STRING(baserepr));
+ Py_DECREF(defrepr);
+ Py_DECREF(baserepr);
+ return result;
}
static int
defdict_traverse(PyObject *self, visitproc visit, void *arg)
{
- Py_VISIT(((defdictobject *)self)->default_factory);
- return PyDict_Type.tp_traverse(self, visit, arg);
+ Py_VISIT(((defdictobject *)self)->default_factory);
+ return PyDict_Type.tp_traverse(self, visit, arg);
}
static int
defdict_tp_clear(defdictobject *dd)
{
- Py_CLEAR(dd->default_factory);
- return PyDict_Type.tp_clear((PyObject *)dd);
+ Py_CLEAR(dd->default_factory);
+ return PyDict_Type.tp_clear((PyObject *)dd);
}
static int
defdict_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- defdictobject *dd = (defdictobject *)self;
- PyObject *olddefault = dd->default_factory;
- PyObject *newdefault = NULL;
- PyObject *newargs;
- int result;
- if (args == NULL || !PyTuple_Check(args))
- newargs = PyTuple_New(0);
- else {
- Py_ssize_t n = PyTuple_GET_SIZE(args);
- if (n > 0) {
- newdefault = PyTuple_GET_ITEM(args, 0);
- if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be callable");
- return -1;
- }
- }
- newargs = PySequence_GetSlice(args, 1, n);
- }
- if (newargs == NULL)
- return -1;
- Py_XINCREF(newdefault);
- dd->default_factory = newdefault;
- result = PyDict_Type.tp_init(self, newargs, kwds);
- Py_DECREF(newargs);
- Py_XDECREF(olddefault);
- return result;
+ defdictobject *dd = (defdictobject *)self;
+ PyObject *olddefault = dd->default_factory;
+ PyObject *newdefault = NULL;
+ PyObject *newargs;
+ int result;
+ if (args == NULL || !PyTuple_Check(args))
+ newargs = PyTuple_New(0);
+ else {
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+ if (n > 0) {
+ newdefault = PyTuple_GET_ITEM(args, 0);
+ if (!PyCallable_Check(newdefault) && newdefault != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be callable");
+ return -1;
+ }
+ }
+ newargs = PySequence_GetSlice(args, 1, n);
+ }
+ if (newargs == NULL)
+ return -1;
+ Py_XINCREF(newdefault);
+ dd->default_factory = newdefault;
+ result = PyDict_Type.tp_init(self, newargs, kwds);
+ Py_DECREF(newargs);
+ Py_XDECREF(olddefault);
+ return result;
}
PyDoc_STRVAR(defdict_doc,
@@ -1550,47 +1550,47 @@ A defaultdict compares equal to a dict with the same items.\n\
#define DEFERRED_ADDRESS(ADDR) 0
static PyTypeObject defdict_type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "collections.defaultdict", /* tp_name */
- sizeof(defdictobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)defdict_dealloc, /* tp_dealloc */
- (printfunc)defdict_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)defdict_repr, /* 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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
- defdict_doc, /* tp_doc */
- defdict_traverse, /* tp_traverse */
- (inquiry)defdict_tp_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset*/
- 0, /* tp_iter */
- 0, /* tp_iternext */
- defdict_methods, /* tp_methods */
- defdict_members, /* tp_members */
- 0, /* tp_getset */
- DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- defdict_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- 0, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "collections.defaultdict", /* tp_name */
+ sizeof(defdictobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)defdict_dealloc, /* tp_dealloc */
+ (printfunc)defdict_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)defdict_repr, /* 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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
+ defdict_doc, /* tp_doc */
+ defdict_traverse, /* tp_traverse */
+ (inquiry)defdict_tp_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset*/
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ defdict_methods, /* tp_methods */
+ defdict_members, /* tp_members */
+ 0, /* tp_getset */
+ DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ defdict_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ 0, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* module level code ********************************************************/
@@ -1604,28 +1604,28 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
init_collections(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("_collections", NULL, module_doc);
- if (m == NULL)
- return;
+ m = Py_InitModule3("_collections", NULL, module_doc);
+ if (m == NULL)
+ return;
- if (PyType_Ready(&deque_type) < 0)
- return;
- Py_INCREF(&deque_type);
- PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
+ if (PyType_Ready(&deque_type) < 0)
+ return;
+ Py_INCREF(&deque_type);
+ PyModule_AddObject(m, "deque", (PyObject *)&deque_type);
- defdict_type.tp_base = &PyDict_Type;
- if (PyType_Ready(&defdict_type) < 0)
- return;
- Py_INCREF(&defdict_type);
- PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
+ defdict_type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&defdict_type) < 0)
+ return;
+ Py_INCREF(&defdict_type);
+ PyModule_AddObject(m, "defaultdict", (PyObject *)&defdict_type);
- if (PyType_Ready(&dequeiter_type) < 0)
- return;
+ if (PyType_Ready(&dequeiter_type) < 0)
+ return;
- if (PyType_Ready(&dequereviter_type) < 0)
- return;
+ if (PyType_Ready(&dequereviter_type) < 0)
+ return;
- return;
+ return;
}
diff --git a/Modules/_csv.c b/Modules/_csv.c
index a5787d3..983f6a5 100644
--- a/Modules/_csv.c
+++ b/Modules/_csv.c
@@ -31,96 +31,96 @@ module instead.
#endif /* ifndef PyDoc_STRVAR */
#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
#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
-#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)
#endif
/* end 2.2 compatibility macros */
#define IS_BASESTRING(o) \
- PyObject_TypeCheck(o, &PyBaseString_Type)
+ PyObject_TypeCheck(o, &PyBaseString_Type)
-static PyObject *error_obj; /* CSV exception */
+static PyObject *error_obj; /* CSV exception */
static PyObject *dialects; /* Dialect registry */
-static long field_limit = 128 * 1024; /* max parsed field size */
+static long field_limit = 128 * 1024; /* max parsed field size */
typedef enum {
- START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
- IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
- EAT_CRNL
+ START_RECORD, START_FIELD, ESCAPED_CHAR, IN_FIELD,
+ IN_QUOTED_FIELD, ESCAPE_IN_QUOTED_FIELD, QUOTE_IN_QUOTED_FIELD,
+ EAT_CRNL
} ParserState;
typedef enum {
- QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE
+ QUOTE_MINIMAL, QUOTE_ALL, QUOTE_NONNUMERIC, QUOTE_NONE
} QuoteStyle;
typedef struct {
- QuoteStyle style;
- char *name;
+ QuoteStyle style;
+ char *name;
} StyleDesc;
static StyleDesc quote_styles[] = {
- { QUOTE_MINIMAL, "QUOTE_MINIMAL" },
- { QUOTE_ALL, "QUOTE_ALL" },
- { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" },
- { QUOTE_NONE, "QUOTE_NONE" },
- { 0 }
+ { QUOTE_MINIMAL, "QUOTE_MINIMAL" },
+ { QUOTE_ALL, "QUOTE_ALL" },
+ { QUOTE_NONNUMERIC, "QUOTE_NONNUMERIC" },
+ { QUOTE_NONE, "QUOTE_NONE" },
+ { 0 }
};
typedef struct {
- PyObject_HEAD
-
- int doublequote; /* is " represented by ""? */
- char delimiter; /* field separator */
- char quotechar; /* quote character */
- char escapechar; /* escape character */
- int skipinitialspace; /* ignore spaces following delimiter? */
- PyObject *lineterminator; /* string to write between records */
- int quoting; /* style of quoting to write */
-
- int strict; /* raise exception on bad CSV */
+ PyObject_HEAD
+
+ int doublequote; /* is " represented by ""? */
+ char delimiter; /* field separator */
+ char quotechar; /* quote character */
+ char escapechar; /* escape character */
+ int skipinitialspace; /* ignore spaces following delimiter? */
+ PyObject *lineterminator; /* string to write between records */
+ int quoting; /* style of quoting to write */
+
+ int strict; /* raise exception on bad CSV */
} DialectObj;
staticforward PyTypeObject Dialect_Type;
typedef struct {
- PyObject_HEAD
+ PyObject_HEAD
- PyObject *input_iter; /* iterate over this for input lines */
+ PyObject *input_iter; /* iterate over this for input lines */
- DialectObj *dialect; /* parsing dialect */
+ DialectObj *dialect; /* parsing dialect */
- PyObject *fields; /* field list for current record */
- ParserState state; /* current CSV parse state */
- char *field; /* build current field in here */
- int field_size; /* size of allocated buffer */
- int field_len; /* length of current field */
- int numeric_field; /* treat field as numeric */
- unsigned long line_num; /* Source-file line number */
+ PyObject *fields; /* field list for current record */
+ ParserState state; /* current CSV parse state */
+ char *field; /* build current field in here */
+ int field_size; /* size of allocated buffer */
+ int field_len; /* length of current field */
+ int numeric_field; /* treat field as numeric */
+ unsigned long line_num; /* Source-file line number */
} ReaderObj;
staticforward PyTypeObject Reader_Type;
@@ -128,17 +128,17 @@ staticforward PyTypeObject Reader_Type;
#define ReaderObject_Check(v) (Py_TYPE(v) == &Reader_Type)
typedef struct {
- PyObject_HEAD
+ PyObject_HEAD
- PyObject *writeline; /* write output lines to this file */
+ PyObject *writeline; /* write output lines to this file */
- DialectObj *dialect; /* parsing dialect */
+ DialectObj *dialect; /* parsing dialect */
- char *rec; /* buffer for parser.join */
- int rec_size; /* size of allocated record */
- int rec_len; /* length of record */
- int num_fields; /* number of fields in record */
-} WriterObj;
+ char *rec; /* buffer for parser.join */
+ int rec_size; /* size of allocated record */
+ int rec_len; /* length of record */
+ int num_fields; /* number of fields in record */
+} WriterObj;
staticforward PyTypeObject Writer_Type;
@@ -149,357 +149,357 @@ staticforward PyTypeObject Writer_Type;
static PyObject *
get_dialect_from_registry(PyObject * name_obj)
{
- PyObject *dialect_obj;
-
- dialect_obj = PyDict_GetItem(dialects, name_obj);
- if (dialect_obj == NULL) {
- if (!PyErr_Occurred())
- PyErr_Format(error_obj, "unknown dialect");
- }
- else
- Py_INCREF(dialect_obj);
- return dialect_obj;
+ PyObject *dialect_obj;
+
+ dialect_obj = PyDict_GetItem(dialects, name_obj);
+ if (dialect_obj == NULL) {
+ if (!PyErr_Occurred())
+ PyErr_Format(error_obj, "unknown dialect");
+ }
+ else
+ Py_INCREF(dialect_obj);
+ return dialect_obj;
}
static PyObject *
get_string(PyObject *str)
{
- Py_XINCREF(str);
- return str;
+ Py_XINCREF(str);
+ return str;
}
static PyObject *
get_nullchar_as_None(char c)
{
- if (c == '\0') {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyString_FromStringAndSize((char*)&c, 1);
+ if (c == '\0') {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyString_FromStringAndSize((char*)&c, 1);
}
static PyObject *
Dialect_get_lineterminator(DialectObj *self)
{
- return get_string(self->lineterminator);
+ return get_string(self->lineterminator);
}
static PyObject *
Dialect_get_escapechar(DialectObj *self)
{
- return get_nullchar_as_None(self->escapechar);
+ return get_nullchar_as_None(self->escapechar);
}
static PyObject *
Dialect_get_quotechar(DialectObj *self)
{
- return get_nullchar_as_None(self->quotechar);
+ return get_nullchar_as_None(self->quotechar);
}
static PyObject *
Dialect_get_quoting(DialectObj *self)
{
- return PyInt_FromLong(self->quoting);
+ return PyInt_FromLong(self->quoting);
}
static int
_set_bool(const char *name, int *target, PyObject *src, int dflt)
{
- if (src == NULL)
- *target = dflt;
- else
- *target = PyObject_IsTrue(src);
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else
+ *target = PyObject_IsTrue(src);
+ return 0;
}
static int
_set_int(const char *name, int *target, PyObject *src, int dflt)
{
- if (src == NULL)
- *target = dflt;
- else {
- if (!PyInt_Check(src)) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an integer", name);
- return -1;
- }
- *target = PyInt_AsLong(src);
- }
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else {
+ if (!PyInt_Check(src)) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an integer", name);
+ return -1;
+ }
+ *target = PyInt_AsLong(src);
+ }
+ return 0;
}
static int
_set_char(const char *name, char *target, PyObject *src, char dflt)
{
- if (src == NULL)
- *target = dflt;
- else {
- if (src == Py_None || PyString_Size(src) == 0)
- *target = '\0';
- else if (!PyString_Check(src) || PyString_Size(src) != 1) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an 1-character string",
- name);
- return -1;
- }
- else {
- char *s = PyString_AsString(src);
- if (s == NULL)
- return -1;
- *target = s[0];
- }
- }
- return 0;
+ if (src == NULL)
+ *target = dflt;
+ else {
+ if (src == Py_None || PyString_Size(src) == 0)
+ *target = '\0';
+ else if (!PyString_Check(src) || PyString_Size(src) != 1) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an 1-character string",
+ name);
+ return -1;
+ }
+ else {
+ char *s = PyString_AsString(src);
+ if (s == NULL)
+ return -1;
+ *target = s[0];
+ }
+ }
+ return 0;
}
static int
_set_str(const char *name, PyObject **target, PyObject *src, const char *dflt)
{
- if (src == NULL)
- *target = PyString_FromString(dflt);
- else {
- if (src == Py_None)
- *target = NULL;
- else if (!IS_BASESTRING(src)) {
- PyErr_Format(PyExc_TypeError,
- "\"%s\" must be an string", name);
- return -1;
- }
- else {
- Py_XDECREF(*target);
- Py_INCREF(src);
- *target = src;
- }
- }
- return 0;
+ if (src == NULL)
+ *target = PyString_FromString(dflt);
+ else {
+ if (src == Py_None)
+ *target = NULL;
+ else if (!IS_BASESTRING(src)) {
+ PyErr_Format(PyExc_TypeError,
+ "\"%s\" must be an string", name);
+ return -1;
+ }
+ else {
+ Py_XDECREF(*target);
+ Py_INCREF(src);
+ *target = src;
+ }
+ }
+ return 0;
}
static int
dialect_check_quoting(int quoting)
{
- StyleDesc *qs = quote_styles;
-
- for (qs = quote_styles; qs->name; qs++) {
- if (qs->style == quoting)
- return 0;
- }
- PyErr_Format(PyExc_TypeError, "bad \"quoting\" value");
- return -1;
+ StyleDesc *qs = quote_styles;
+
+ for (qs = quote_styles; qs->name; qs++) {
+ if (qs->style == quoting)
+ return 0;
+ }
+ PyErr_Format(PyExc_TypeError, "bad \"quoting\" value");
+ return -1;
}
#define D_OFF(x) offsetof(DialectObj, x)
static struct PyMemberDef Dialect_memberlist[] = {
- { "delimiter", T_CHAR, D_OFF(delimiter), READONLY },
- { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY },
- { "doublequote", T_INT, D_OFF(doublequote), READONLY },
- { "strict", T_INT, D_OFF(strict), READONLY },
- { NULL }
+ { "delimiter", T_CHAR, D_OFF(delimiter), READONLY },
+ { "skipinitialspace", T_INT, D_OFF(skipinitialspace), READONLY },
+ { "doublequote", T_INT, D_OFF(doublequote), READONLY },
+ { "strict", T_INT, D_OFF(strict), READONLY },
+ { NULL }
};
static PyGetSetDef Dialect_getsetlist[] = {
- { "escapechar", (getter)Dialect_get_escapechar},
- { "lineterminator", (getter)Dialect_get_lineterminator},
- { "quotechar", (getter)Dialect_get_quotechar},
- { "quoting", (getter)Dialect_get_quoting},
- {NULL},
+ { "escapechar", (getter)Dialect_get_escapechar},
+ { "lineterminator", (getter)Dialect_get_lineterminator},
+ { "quotechar", (getter)Dialect_get_quotechar},
+ { "quoting", (getter)Dialect_get_quoting},
+ {NULL},
};
static void
Dialect_dealloc(DialectObj *self)
{
- Py_XDECREF(self->lineterminator);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_XDECREF(self->lineterminator);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static char *dialect_kws[] = {
- "dialect",
- "delimiter",
- "doublequote",
- "escapechar",
- "lineterminator",
- "quotechar",
- "quoting",
- "skipinitialspace",
- "strict",
- NULL
+ "dialect",
+ "delimiter",
+ "doublequote",
+ "escapechar",
+ "lineterminator",
+ "quotechar",
+ "quoting",
+ "skipinitialspace",
+ "strict",
+ NULL
};
static PyObject *
dialect_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
- DialectObj *self;
- PyObject *ret = NULL;
- PyObject *dialect = NULL;
- PyObject *delimiter = NULL;
- PyObject *doublequote = NULL;
- PyObject *escapechar = NULL;
- PyObject *lineterminator = NULL;
- PyObject *quotechar = NULL;
- PyObject *quoting = NULL;
- PyObject *skipinitialspace = NULL;
- PyObject *strict = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs,
- "|OOOOOOOOO", dialect_kws,
- &dialect,
- &delimiter,
- &doublequote,
- &escapechar,
- &lineterminator,
- &quotechar,
- &quoting,
- &skipinitialspace,
- &strict))
- return NULL;
-
- if (dialect != NULL) {
- if (IS_BASESTRING(dialect)) {
- dialect = get_dialect_from_registry(dialect);
- if (dialect == NULL)
- return NULL;
- }
- else
- Py_INCREF(dialect);
- /* Can we reuse this instance? */
- if (PyObject_TypeCheck(dialect, &Dialect_Type) &&
- delimiter == 0 &&
- doublequote == 0 &&
- escapechar == 0 &&
- lineterminator == 0 &&
- quotechar == 0 &&
- quoting == 0 &&
- skipinitialspace == 0 &&
- strict == 0)
- return dialect;
- }
-
- self = (DialectObj *)type->tp_alloc(type, 0);
- if (self == NULL) {
- Py_XDECREF(dialect);
- return NULL;
- }
- self->lineterminator = NULL;
-
- Py_XINCREF(delimiter);
- Py_XINCREF(doublequote);
- Py_XINCREF(escapechar);
- Py_XINCREF(lineterminator);
- Py_XINCREF(quotechar);
- Py_XINCREF(quoting);
- Py_XINCREF(skipinitialspace);
- Py_XINCREF(strict);
- if (dialect != NULL) {
+ DialectObj *self;
+ PyObject *ret = NULL;
+ PyObject *dialect = NULL;
+ PyObject *delimiter = NULL;
+ PyObject *doublequote = NULL;
+ PyObject *escapechar = NULL;
+ PyObject *lineterminator = NULL;
+ PyObject *quotechar = NULL;
+ PyObject *quoting = NULL;
+ PyObject *skipinitialspace = NULL;
+ PyObject *strict = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs,
+ "|OOOOOOOOO", dialect_kws,
+ &dialect,
+ &delimiter,
+ &doublequote,
+ &escapechar,
+ &lineterminator,
+ &quotechar,
+ &quoting,
+ &skipinitialspace,
+ &strict))
+ return NULL;
+
+ if (dialect != NULL) {
+ if (IS_BASESTRING(dialect)) {
+ dialect = get_dialect_from_registry(dialect);
+ if (dialect == NULL)
+ return NULL;
+ }
+ else
+ Py_INCREF(dialect);
+ /* Can we reuse this instance? */
+ if (PyObject_TypeCheck(dialect, &Dialect_Type) &&
+ delimiter == 0 &&
+ doublequote == 0 &&
+ escapechar == 0 &&
+ lineterminator == 0 &&
+ quotechar == 0 &&
+ quoting == 0 &&
+ skipinitialspace == 0 &&
+ strict == 0)
+ return dialect;
+ }
+
+ self = (DialectObj *)type->tp_alloc(type, 0);
+ if (self == NULL) {
+ Py_XDECREF(dialect);
+ return NULL;
+ }
+ self->lineterminator = NULL;
+
+ Py_XINCREF(delimiter);
+ Py_XINCREF(doublequote);
+ Py_XINCREF(escapechar);
+ Py_XINCREF(lineterminator);
+ Py_XINCREF(quotechar);
+ Py_XINCREF(quoting);
+ Py_XINCREF(skipinitialspace);
+ Py_XINCREF(strict);
+ if (dialect != NULL) {
#define DIALECT_GETATTR(v, n) \
- if (v == NULL) \
- v = PyObject_GetAttrString(dialect, n)
- DIALECT_GETATTR(delimiter, "delimiter");
- DIALECT_GETATTR(doublequote, "doublequote");
- DIALECT_GETATTR(escapechar, "escapechar");
- DIALECT_GETATTR(lineterminator, "lineterminator");
- DIALECT_GETATTR(quotechar, "quotechar");
- DIALECT_GETATTR(quoting, "quoting");
- DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
- DIALECT_GETATTR(strict, "strict");
- PyErr_Clear();
- }
-
- /* check types and convert to C values */
+ if (v == NULL) \
+ v = PyObject_GetAttrString(dialect, n)
+ DIALECT_GETATTR(delimiter, "delimiter");
+ DIALECT_GETATTR(doublequote, "doublequote");
+ DIALECT_GETATTR(escapechar, "escapechar");
+ DIALECT_GETATTR(lineterminator, "lineterminator");
+ DIALECT_GETATTR(quotechar, "quotechar");
+ DIALECT_GETATTR(quoting, "quoting");
+ DIALECT_GETATTR(skipinitialspace, "skipinitialspace");
+ DIALECT_GETATTR(strict, "strict");
+ PyErr_Clear();
+ }
+
+ /* check types and convert to C values */
#define DIASET(meth, name, target, src, dflt) \
- if (meth(name, target, src, dflt)) \
- goto err
- DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ',');
- DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1);
- DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0);
- DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n");
- DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"');
- DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL);
- DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0);
- DIASET(_set_bool, "strict", &self->strict, strict, 0);
-
- /* validate options */
- if (dialect_check_quoting(self->quoting))
- goto err;
- if (self->delimiter == 0) {
- PyErr_SetString(PyExc_TypeError, "delimiter must be set");
- goto err;
- }
- if (quotechar == Py_None && quoting == NULL)
- self->quoting = QUOTE_NONE;
- if (self->quoting != QUOTE_NONE && self->quotechar == 0) {
- PyErr_SetString(PyExc_TypeError,
- "quotechar must be set if quoting enabled");
- goto err;
- }
- if (self->lineterminator == 0) {
- PyErr_SetString(PyExc_TypeError, "lineterminator must be set");
- goto err;
- }
-
- ret = (PyObject *)self;
- Py_INCREF(self);
+ if (meth(name, target, src, dflt)) \
+ goto err
+ DIASET(_set_char, "delimiter", &self->delimiter, delimiter, ',');
+ DIASET(_set_bool, "doublequote", &self->doublequote, doublequote, 1);
+ DIASET(_set_char, "escapechar", &self->escapechar, escapechar, 0);
+ DIASET(_set_str, "lineterminator", &self->lineterminator, lineterminator, "\r\n");
+ DIASET(_set_char, "quotechar", &self->quotechar, quotechar, '"');
+ DIASET(_set_int, "quoting", &self->quoting, quoting, QUOTE_MINIMAL);
+ DIASET(_set_bool, "skipinitialspace", &self->skipinitialspace, skipinitialspace, 0);
+ DIASET(_set_bool, "strict", &self->strict, strict, 0);
+
+ /* validate options */
+ if (dialect_check_quoting(self->quoting))
+ goto err;
+ if (self->delimiter == 0) {
+ PyErr_SetString(PyExc_TypeError, "delimiter must be set");
+ goto err;
+ }
+ if (quotechar == Py_None && quoting == NULL)
+ self->quoting = QUOTE_NONE;
+ if (self->quoting != QUOTE_NONE && self->quotechar == 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "quotechar must be set if quoting enabled");
+ goto err;
+ }
+ if (self->lineterminator == 0) {
+ PyErr_SetString(PyExc_TypeError, "lineterminator must be set");
+ goto err;
+ }
+
+ ret = (PyObject *)self;
+ Py_INCREF(self);
err:
- Py_XDECREF(self);
- Py_XDECREF(dialect);
- Py_XDECREF(delimiter);
- Py_XDECREF(doublequote);
- Py_XDECREF(escapechar);
- Py_XDECREF(lineterminator);
- Py_XDECREF(quotechar);
- Py_XDECREF(quoting);
- Py_XDECREF(skipinitialspace);
- Py_XDECREF(strict);
- return ret;
+ Py_XDECREF(self);
+ Py_XDECREF(dialect);
+ Py_XDECREF(delimiter);
+ Py_XDECREF(doublequote);
+ Py_XDECREF(escapechar);
+ Py_XDECREF(lineterminator);
+ Py_XDECREF(quotechar);
+ Py_XDECREF(quoting);
+ Py_XDECREF(skipinitialspace);
+ Py_XDECREF(strict);
+ return ret;
}
-PyDoc_STRVAR(Dialect_Type_doc,
+PyDoc_STRVAR(Dialect_Type_doc,
"CSV dialect\n"
"\n"
"The Dialect type records CSV parsing and generation options.\n");
static PyTypeObject Dialect_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_csv.Dialect", /* tp_name */
- sizeof(DialectObj), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)Dialect_dealloc, /* tp_dealloc */
- (printfunc)0, /* tp_print */
- (getattrfunc)0, /* 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 */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- Dialect_Type_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- Dialect_memberlist, /* tp_members */
- Dialect_getsetlist, /* 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 */
- dialect_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_csv.Dialect", /* tp_name */
+ sizeof(DialectObj), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)Dialect_dealloc, /* tp_dealloc */
+ (printfunc)0, /* tp_print */
+ (getattrfunc)0, /* 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 */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ Dialect_Type_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ Dialect_memberlist, /* tp_members */
+ Dialect_getsetlist, /* 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 */
+ dialect_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -509,15 +509,15 @@ static PyTypeObject Dialect_Type = {
static PyObject *
_call_dialect(PyObject *dialect_inst, PyObject *kwargs)
{
- PyObject *ctor_args;
- PyObject *dialect;
-
- ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst);
- if (ctor_args == NULL)
- return NULL;
- dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs);
- Py_DECREF(ctor_args);
- return dialect;
+ PyObject *ctor_args;
+ PyObject *dialect;
+
+ ctor_args = Py_BuildValue(dialect_inst ? "(O)" : "()", dialect_inst);
+ if (ctor_args == NULL)
+ return NULL;
+ dialect = PyObject_Call((PyObject *)&Dialect_Type, ctor_args, kwargs);
+ Py_DECREF(ctor_args);
+ return dialect;
}
/*
@@ -526,330 +526,330 @@ _call_dialect(PyObject *dialect_inst, PyObject *kwargs)
static int
parse_save_field(ReaderObj *self)
{
- PyObject *field;
-
- field = PyString_FromStringAndSize(self->field, self->field_len);
- if (field == NULL)
- return -1;
- self->field_len = 0;
- if (self->numeric_field) {
- PyObject *tmp;
-
- self->numeric_field = 0;
- tmp = PyNumber_Float(field);
- if (tmp == NULL) {
- Py_DECREF(field);
- return -1;
- }
- Py_DECREF(field);
- field = tmp;
- }
- PyList_Append(self->fields, field);
- Py_DECREF(field);
- return 0;
+ PyObject *field;
+
+ field = PyString_FromStringAndSize(self->field, self->field_len);
+ if (field == NULL)
+ return -1;
+ self->field_len = 0;
+ if (self->numeric_field) {
+ PyObject *tmp;
+
+ self->numeric_field = 0;
+ tmp = PyNumber_Float(field);
+ if (tmp == NULL) {
+ Py_DECREF(field);
+ return -1;
+ }
+ Py_DECREF(field);
+ field = tmp;
+ }
+ PyList_Append(self->fields, field);
+ Py_DECREF(field);
+ return 0;
}
static int
parse_grow_buff(ReaderObj *self)
{
- if (self->field_size == 0) {
- self->field_size = 4096;
- if (self->field != NULL)
- PyMem_Free(self->field);
- self->field = PyMem_Malloc(self->field_size);
- }
- else {
- if (self->field_size > INT_MAX / 2) {
- PyErr_NoMemory();
- return 0;
- }
- self->field_size *= 2;
- self->field = PyMem_Realloc(self->field, self->field_size);
- }
- if (self->field == NULL) {
- PyErr_NoMemory();
- return 0;
- }
- return 1;
+ if (self->field_size == 0) {
+ self->field_size = 4096;
+ if (self->field != NULL)
+ PyMem_Free(self->field);
+ self->field = PyMem_Malloc(self->field_size);
+ }
+ else {
+ if (self->field_size > INT_MAX / 2) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ self->field_size *= 2;
+ self->field = PyMem_Realloc(self->field, self->field_size);
+ }
+ if (self->field == NULL) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ return 1;
}
static int
parse_add_char(ReaderObj *self, char c)
{
- if (self->field_len >= field_limit) {
- PyErr_Format(error_obj, "field larger than field limit (%ld)",
- field_limit);
- return -1;
- }
- if (self->field_len == self->field_size && !parse_grow_buff(self))
- return -1;
- self->field[self->field_len++] = c;
- return 0;
+ if (self->field_len >= field_limit) {
+ PyErr_Format(error_obj, "field larger than field limit (%ld)",
+ field_limit);
+ return -1;
+ }
+ if (self->field_len == self->field_size && !parse_grow_buff(self))
+ return -1;
+ self->field[self->field_len++] = c;
+ return 0;
}
static int
parse_process_char(ReaderObj *self, char c)
{
- DialectObj *dialect = self->dialect;
-
- switch (self->state) {
- case START_RECORD:
- /* start of record */
- if (c == '\0')
- /* empty line - return [] */
- break;
- else if (c == '\n' || c == '\r') {
- self->state = EAT_CRNL;
- break;
- }
- /* normal character - handle as START_FIELD */
- self->state = START_FIELD;
- /* fallthru */
- case START_FIELD:
- /* expecting field */
- if (c == '\n' || c == '\r' || c == '\0') {
- /* save empty field - return [fields] */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
- }
- else if (c == dialect->quotechar &&
- dialect->quoting != QUOTE_NONE) {
- /* start quoted field */
- self->state = IN_QUOTED_FIELD;
- }
- else if (c == dialect->escapechar) {
- /* possible escaped character */
- self->state = ESCAPED_CHAR;
- }
- else if (c == ' ' && dialect->skipinitialspace)
- /* ignore space at start of field */
- ;
- else if (c == dialect->delimiter) {
- /* save empty field */
- if (parse_save_field(self) < 0)
- return -1;
- }
- else {
- /* begin new unquoted field */
- if (dialect->quoting == QUOTE_NONNUMERIC)
- self->numeric_field = 1;
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_FIELD;
- }
- break;
-
- case ESCAPED_CHAR:
- if (c == '\0')
- c = '\n';
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_FIELD;
- break;
-
- case IN_FIELD:
- /* in unquoted field */
- if (c == '\n' || c == '\r' || c == '\0') {
- /* end of line - return [fields] */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
- }
- else if (c == dialect->escapechar) {
- /* possible escaped character */
- self->state = ESCAPED_CHAR;
- }
- else if (c == dialect->delimiter) {
- /* save field - wait for new field */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = START_FIELD;
- }
- else {
- /* normal character - save in field */
- if (parse_add_char(self, c) < 0)
- return -1;
- }
- break;
-
- case IN_QUOTED_FIELD:
- /* in quoted field */
- if (c == '\0')
- ;
- else if (c == dialect->escapechar) {
- /* Possible escape character */
- self->state = ESCAPE_IN_QUOTED_FIELD;
- }
- else if (c == dialect->quotechar &&
- dialect->quoting != QUOTE_NONE) {
- if (dialect->doublequote) {
- /* doublequote; " represented by "" */
- self->state = QUOTE_IN_QUOTED_FIELD;
- }
- else {
- /* end of quote part of field */
- self->state = IN_FIELD;
- }
- }
- else {
- /* normal character - save in field */
- if (parse_add_char(self, c) < 0)
- return -1;
- }
- break;
-
- case ESCAPE_IN_QUOTED_FIELD:
- if (c == '\0')
- c = '\n';
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_QUOTED_FIELD;
- break;
-
- case QUOTE_IN_QUOTED_FIELD:
- /* doublequote - seen a quote in an quoted field */
- if (dialect->quoting != QUOTE_NONE &&
- c == dialect->quotechar) {
- /* save "" as " */
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_QUOTED_FIELD;
- }
- else if (c == dialect->delimiter) {
- /* save field - wait for new field */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = START_FIELD;
- }
- else if (c == '\n' || c == '\r' || c == '\0') {
- /* end of line - return [fields] */
- if (parse_save_field(self) < 0)
- return -1;
- self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
- }
- else if (!dialect->strict) {
- if (parse_add_char(self, c) < 0)
- return -1;
- self->state = IN_FIELD;
- }
- else {
- /* illegal */
- PyErr_Format(error_obj, "'%c' expected after '%c'",
- dialect->delimiter,
- dialect->quotechar);
- return -1;
- }
- break;
-
- case EAT_CRNL:
- if (c == '\n' || c == '\r')
- ;
- else if (c == '\0')
- self->state = START_RECORD;
- else {
- PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?");
- return -1;
- }
- break;
-
- }
- return 0;
+ DialectObj *dialect = self->dialect;
+
+ switch (self->state) {
+ case START_RECORD:
+ /* start of record */
+ if (c == '\0')
+ /* empty line - return [] */
+ break;
+ else if (c == '\n' || c == '\r') {
+ self->state = EAT_CRNL;
+ break;
+ }
+ /* normal character - handle as START_FIELD */
+ self->state = START_FIELD;
+ /* fallthru */
+ case START_FIELD:
+ /* expecting field */
+ if (c == '\n' || c == '\r' || c == '\0') {
+ /* save empty field - return [fields] */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
+ }
+ else if (c == dialect->quotechar &&
+ dialect->quoting != QUOTE_NONE) {
+ /* start quoted field */
+ self->state = IN_QUOTED_FIELD;
+ }
+ else if (c == dialect->escapechar) {
+ /* possible escaped character */
+ self->state = ESCAPED_CHAR;
+ }
+ else if (c == ' ' && dialect->skipinitialspace)
+ /* ignore space at start of field */
+ ;
+ else if (c == dialect->delimiter) {
+ /* save empty field */
+ if (parse_save_field(self) < 0)
+ return -1;
+ }
+ else {
+ /* begin new unquoted field */
+ if (dialect->quoting == QUOTE_NONNUMERIC)
+ self->numeric_field = 1;
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_FIELD;
+ }
+ break;
+
+ case ESCAPED_CHAR:
+ if (c == '\0')
+ c = '\n';
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_FIELD;
+ break;
+
+ case IN_FIELD:
+ /* in unquoted field */
+ if (c == '\n' || c == '\r' || c == '\0') {
+ /* end of line - return [fields] */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
+ }
+ else if (c == dialect->escapechar) {
+ /* possible escaped character */
+ self->state = ESCAPED_CHAR;
+ }
+ else if (c == dialect->delimiter) {
+ /* save field - wait for new field */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = START_FIELD;
+ }
+ else {
+ /* normal character - save in field */
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ }
+ break;
+
+ case IN_QUOTED_FIELD:
+ /* in quoted field */
+ if (c == '\0')
+ ;
+ else if (c == dialect->escapechar) {
+ /* Possible escape character */
+ self->state = ESCAPE_IN_QUOTED_FIELD;
+ }
+ else if (c == dialect->quotechar &&
+ dialect->quoting != QUOTE_NONE) {
+ if (dialect->doublequote) {
+ /* doublequote; " represented by "" */
+ self->state = QUOTE_IN_QUOTED_FIELD;
+ }
+ else {
+ /* end of quote part of field */
+ self->state = IN_FIELD;
+ }
+ }
+ else {
+ /* normal character - save in field */
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ }
+ break;
+
+ case ESCAPE_IN_QUOTED_FIELD:
+ if (c == '\0')
+ c = '\n';
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_QUOTED_FIELD;
+ break;
+
+ case QUOTE_IN_QUOTED_FIELD:
+ /* doublequote - seen a quote in an quoted field */
+ if (dialect->quoting != QUOTE_NONE &&
+ c == dialect->quotechar) {
+ /* save "" as " */
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_QUOTED_FIELD;
+ }
+ else if (c == dialect->delimiter) {
+ /* save field - wait for new field */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = START_FIELD;
+ }
+ else if (c == '\n' || c == '\r' || c == '\0') {
+ /* end of line - return [fields] */
+ if (parse_save_field(self) < 0)
+ return -1;
+ self->state = (c == '\0' ? START_RECORD : EAT_CRNL);
+ }
+ else if (!dialect->strict) {
+ if (parse_add_char(self, c) < 0)
+ return -1;
+ self->state = IN_FIELD;
+ }
+ else {
+ /* illegal */
+ PyErr_Format(error_obj, "'%c' expected after '%c'",
+ dialect->delimiter,
+ dialect->quotechar);
+ return -1;
+ }
+ break;
+
+ case EAT_CRNL:
+ if (c == '\n' || c == '\r')
+ ;
+ else if (c == '\0')
+ self->state = START_RECORD;
+ else {
+ PyErr_Format(error_obj, "new-line character seen in unquoted field - do you need to open the file in universal-newline mode?");
+ return -1;
+ }
+ break;
+
+ }
+ return 0;
}
static int
parse_reset(ReaderObj *self)
{
- Py_XDECREF(self->fields);
- self->fields = PyList_New(0);
- if (self->fields == NULL)
- return -1;
- self->field_len = 0;
- self->state = START_RECORD;
- self->numeric_field = 0;
- return 0;
+ Py_XDECREF(self->fields);
+ self->fields = PyList_New(0);
+ if (self->fields == NULL)
+ return -1;
+ self->field_len = 0;
+ self->state = START_RECORD;
+ self->numeric_field = 0;
+ return 0;
}
static PyObject *
Reader_iternext(ReaderObj *self)
{
- PyObject *lineobj;
- PyObject *fields = NULL;
- char *line, c;
- int linelen;
-
- if (parse_reset(self) < 0)
- return NULL;
- do {
- lineobj = PyIter_Next(self->input_iter);
- if (lineobj == NULL) {
- /* End of input OR exception */
- if (!PyErr_Occurred() && self->field_len != 0)
- PyErr_Format(error_obj,
- "newline inside string");
- return NULL;
- }
- ++self->line_num;
+ PyObject *lineobj;
+ PyObject *fields = NULL;
+ char *line, c;
+ int linelen;
+
+ if (parse_reset(self) < 0)
+ return NULL;
+ do {
+ lineobj = PyIter_Next(self->input_iter);
+ if (lineobj == NULL) {
+ /* End of input OR exception */
+ if (!PyErr_Occurred() && self->field_len != 0)
+ PyErr_Format(error_obj,
+ "newline inside string");
+ return NULL;
+ }
+ ++self->line_num;
- line = PyString_AsString(lineobj);
- linelen = PyString_Size(lineobj);
+ line = PyString_AsString(lineobj);
+ linelen = PyString_Size(lineobj);
- if (line == NULL || linelen < 0) {
- Py_DECREF(lineobj);
- return NULL;
- }
- while (linelen--) {
- c = *line++;
- if (c == '\0') {
- Py_DECREF(lineobj);
- PyErr_Format(error_obj,
- "line contains NULL byte");
- goto err;
- }
- if (parse_process_char(self, c) < 0) {
- Py_DECREF(lineobj);
- goto err;
- }
- }
+ if (line == NULL || linelen < 0) {
+ Py_DECREF(lineobj);
+ return NULL;
+ }
+ while (linelen--) {
+ c = *line++;
+ if (c == '\0') {
Py_DECREF(lineobj);
- if (parse_process_char(self, 0) < 0)
- goto err;
- } while (self->state != START_RECORD);
+ PyErr_Format(error_obj,
+ "line contains NULL byte");
+ goto err;
+ }
+ if (parse_process_char(self, c) < 0) {
+ Py_DECREF(lineobj);
+ goto err;
+ }
+ }
+ Py_DECREF(lineobj);
+ if (parse_process_char(self, 0) < 0)
+ goto err;
+ } while (self->state != START_RECORD);
- fields = self->fields;
- self->fields = NULL;
+ fields = self->fields;
+ self->fields = NULL;
err:
- return fields;
+ return fields;
}
static void
Reader_dealloc(ReaderObj *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->dialect);
- Py_XDECREF(self->input_iter);
- Py_XDECREF(self->fields);
- if (self->field != NULL)
- PyMem_Free(self->field);
- PyObject_GC_Del(self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->dialect);
+ Py_XDECREF(self->input_iter);
+ Py_XDECREF(self->fields);
+ if (self->field != NULL)
+ PyMem_Free(self->field);
+ PyObject_GC_Del(self);
}
static int
Reader_traverse(ReaderObj *self, visitproc visit, void *arg)
{
- Py_VISIT(self->dialect);
- Py_VISIT(self->input_iter);
- Py_VISIT(self->fields);
- return 0;
+ Py_VISIT(self->dialect);
+ Py_VISIT(self->input_iter);
+ Py_VISIT(self->fields);
+ return 0;
}
static int
Reader_clear(ReaderObj *self)
{
- Py_CLEAR(self->dialect);
- Py_CLEAR(self->input_iter);
- Py_CLEAR(self->fields);
- return 0;
+ Py_CLEAR(self->dialect);
+ Py_CLEAR(self->input_iter);
+ Py_CLEAR(self->fields);
+ return 0;
}
PyDoc_STRVAR(Reader_Type_doc,
@@ -860,93 +860,93 @@ PyDoc_STRVAR(Reader_Type_doc,
);
static struct PyMethodDef Reader_methods[] = {
- { NULL, NULL }
+ { NULL, NULL }
};
#define R_OFF(x) offsetof(ReaderObj, x)
static struct PyMemberDef Reader_memberlist[] = {
- { "dialect", T_OBJECT, R_OFF(dialect), RO },
- { "line_num", T_ULONG, R_OFF(line_num), RO },
- { NULL }
+ { "dialect", T_OBJECT, R_OFF(dialect), RO },
+ { "line_num", T_ULONG, R_OFF(line_num), RO },
+ { NULL }
};
static PyTypeObject Reader_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_csv.reader", /*tp_name*/
- sizeof(ReaderObj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)Reader_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)0, /*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*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- Reader_Type_doc, /*tp_doc*/
- (traverseproc)Reader_traverse, /*tp_traverse*/
- (inquiry)Reader_clear, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- PyObject_SelfIter, /*tp_iter*/
- (getiterfunc)Reader_iternext, /*tp_iternext*/
- Reader_methods, /*tp_methods*/
- Reader_memberlist, /*tp_members*/
- 0, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_csv.reader", /*tp_name*/
+ sizeof(ReaderObj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)Reader_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)0, /*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*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ Reader_Type_doc, /*tp_doc*/
+ (traverseproc)Reader_traverse, /*tp_traverse*/
+ (inquiry)Reader_clear, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ PyObject_SelfIter, /*tp_iter*/
+ (getiterfunc)Reader_iternext, /*tp_iternext*/
+ Reader_methods, /*tp_methods*/
+ Reader_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
};
static PyObject *
csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
{
- PyObject * iterator, * dialect = NULL;
- ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type);
-
- if (!self)
- return NULL;
-
- self->dialect = NULL;
- self->fields = NULL;
- self->input_iter = NULL;
- self->field = NULL;
- self->field_size = 0;
- self->line_num = 0;
-
- if (parse_reset(self) < 0) {
- Py_DECREF(self);
- return NULL;
- }
-
- if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) {
- Py_DECREF(self);
- return NULL;
- }
- self->input_iter = PyObject_GetIter(iterator);
- if (self->input_iter == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "argument 1 must be an iterator");
- Py_DECREF(self);
- return NULL;
- }
- self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
- if (self->dialect == NULL) {
- Py_DECREF(self);
- return NULL;
- }
-
- PyObject_GC_Track(self);
- return (PyObject *)self;
+ PyObject * iterator, * dialect = NULL;
+ ReaderObj * self = PyObject_GC_New(ReaderObj, &Reader_Type);
+
+ if (!self)
+ return NULL;
+
+ self->dialect = NULL;
+ self->fields = NULL;
+ self->input_iter = NULL;
+ self->field = NULL;
+ self->field_size = 0;
+ self->line_num = 0;
+
+ if (parse_reset(self) < 0) {
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &iterator, &dialect)) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->input_iter = PyObject_GetIter(iterator);
+ if (self->input_iter == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument 1 must be an iterator");
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
+ if (self->dialect == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ PyObject_GC_Track(self);
+ return (PyObject *)self;
}
/*
@@ -956,8 +956,8 @@ csv_reader(PyObject *module, PyObject *args, PyObject *keyword_args)
static void
join_reset(WriterObj *self)
{
- self->rec_len = 0;
- self->num_fields = 0;
+ self->rec_len = 0;
+ self->num_fields = 0;
}
#define MEM_INCR 32768
@@ -967,90 +967,90 @@ join_reset(WriterObj *self)
*/
static int
join_append_data(WriterObj *self, char *field, int quote_empty,
- int *quoted, int copy_phase)
+ int *quoted, int copy_phase)
{
- DialectObj *dialect = self->dialect;
- int i, rec_len;
- char *lineterm;
+ DialectObj *dialect = self->dialect;
+ int i, rec_len;
+ char *lineterm;
#define ADDCH(c) \
- do {\
- if (copy_phase) \
- self->rec[rec_len] = c;\
- rec_len++;\
- } while(0)
-
- lineterm = PyString_AsString(dialect->lineterminator);
- if (lineterm == NULL)
- return -1;
-
- rec_len = self->rec_len;
-
- /* If this is not the first field we need a field separator */
- if (self->num_fields > 0)
- ADDCH(dialect->delimiter);
-
- /* Handle preceding quote */
- if (copy_phase && *quoted)
- ADDCH(dialect->quotechar);
-
- /* Copy/count field data */
- for (i = 0;; i++) {
- char c = field[i];
- int want_escape = 0;
-
- if (c == '\0')
- break;
-
- if (c == dialect->delimiter ||
- c == dialect->escapechar ||
- c == dialect->quotechar ||
- strchr(lineterm, c)) {
- if (dialect->quoting == QUOTE_NONE)
- want_escape = 1;
- else {
- if (c == dialect->quotechar) {
- if (dialect->doublequote)
- ADDCH(dialect->quotechar);
- else
- want_escape = 1;
- }
- if (!want_escape)
- *quoted = 1;
- }
- if (want_escape) {
- if (!dialect->escapechar) {
- PyErr_Format(error_obj,
- "need to escape, but no escapechar set");
- return -1;
- }
- ADDCH(dialect->escapechar);
- }
- }
- /* Copy field character into record buffer.
- */
- ADDCH(c);
- }
-
- /* If field is empty check if it needs to be quoted.
- */
- if (i == 0 && quote_empty) {
- if (dialect->quoting == QUOTE_NONE) {
- PyErr_Format(error_obj,
- "single empty field record must be quoted");
- return -1;
- }
- else
- *quoted = 1;
- }
-
- if (*quoted) {
- if (copy_phase)
- ADDCH(dialect->quotechar);
- else
- rec_len += 2;
- }
- return rec_len;
+ do {\
+ if (copy_phase) \
+ self->rec[rec_len] = c;\
+ rec_len++;\
+ } while(0)
+
+ lineterm = PyString_AsString(dialect->lineterminator);
+ if (lineterm == NULL)
+ return -1;
+
+ rec_len = self->rec_len;
+
+ /* If this is not the first field we need a field separator */
+ if (self->num_fields > 0)
+ ADDCH(dialect->delimiter);
+
+ /* Handle preceding quote */
+ if (copy_phase && *quoted)
+ ADDCH(dialect->quotechar);
+
+ /* Copy/count field data */
+ for (i = 0;; i++) {
+ char c = field[i];
+ int want_escape = 0;
+
+ if (c == '\0')
+ break;
+
+ if (c == dialect->delimiter ||
+ c == dialect->escapechar ||
+ c == dialect->quotechar ||
+ strchr(lineterm, c)) {
+ if (dialect->quoting == QUOTE_NONE)
+ want_escape = 1;
+ else {
+ if (c == dialect->quotechar) {
+ if (dialect->doublequote)
+ ADDCH(dialect->quotechar);
+ else
+ want_escape = 1;
+ }
+ if (!want_escape)
+ *quoted = 1;
+ }
+ if (want_escape) {
+ if (!dialect->escapechar) {
+ PyErr_Format(error_obj,
+ "need to escape, but no escapechar set");
+ return -1;
+ }
+ ADDCH(dialect->escapechar);
+ }
+ }
+ /* Copy field character into record buffer.
+ */
+ ADDCH(c);
+ }
+
+ /* If field is empty check if it needs to be quoted.
+ */
+ if (i == 0 && quote_empty) {
+ if (dialect->quoting == QUOTE_NONE) {
+ PyErr_Format(error_obj,
+ "single empty field record must be quoted");
+ return -1;
+ }
+ else
+ *quoted = 1;
+ }
+
+ if (*quoted) {
+ if (copy_phase)
+ ADDCH(dialect->quotechar);
+ else
+ rec_len += 2;
+ }
+ return rec_len;
#undef ADDCH
}
@@ -1058,74 +1058,74 @@ static int
join_check_rec_size(WriterObj *self, int rec_len)
{
- if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) {
- PyErr_NoMemory();
- return 0;
- }
-
- if (rec_len > self->rec_size) {
- if (self->rec_size == 0) {
- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
- if (self->rec != NULL)
- PyMem_Free(self->rec);
- self->rec = PyMem_Malloc(self->rec_size);
- }
- else {
- char *old_rec = self->rec;
-
- self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
- self->rec = PyMem_Realloc(self->rec, self->rec_size);
- if (self->rec == NULL)
- PyMem_Free(old_rec);
- }
- if (self->rec == NULL) {
- PyErr_NoMemory();
- return 0;
- }
- }
- return 1;
+ if (rec_len < 0 || rec_len > INT_MAX - MEM_INCR) {
+ PyErr_NoMemory();
+ return 0;
+ }
+
+ if (rec_len > self->rec_size) {
+ if (self->rec_size == 0) {
+ self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
+ if (self->rec != NULL)
+ PyMem_Free(self->rec);
+ self->rec = PyMem_Malloc(self->rec_size);
+ }
+ else {
+ char *old_rec = self->rec;
+
+ self->rec_size = (rec_len / MEM_INCR + 1) * MEM_INCR;
+ self->rec = PyMem_Realloc(self->rec, self->rec_size);
+ if (self->rec == NULL)
+ PyMem_Free(old_rec);
+ }
+ if (self->rec == NULL) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ }
+ return 1;
}
static int
join_append(WriterObj *self, char *field, int *quoted, int quote_empty)
{
- int rec_len;
+ int rec_len;
- rec_len = join_append_data(self, field, quote_empty, quoted, 0);
- if (rec_len < 0)
- return 0;
+ rec_len = join_append_data(self, field, quote_empty, quoted, 0);
+ if (rec_len < 0)
+ return 0;
- /* grow record buffer if necessary */
- if (!join_check_rec_size(self, rec_len))
- return 0;
+ /* grow record buffer if necessary */
+ if (!join_check_rec_size(self, rec_len))
+ return 0;
- self->rec_len = join_append_data(self, field, quote_empty, quoted, 1);
- self->num_fields++;
+ self->rec_len = join_append_data(self, field, quote_empty, quoted, 1);
+ self->num_fields++;
- return 1;
+ return 1;
}
static int
join_append_lineterminator(WriterObj *self)
{
- int terminator_len;
- char *terminator;
+ int terminator_len;
+ char *terminator;
- terminator_len = PyString_Size(self->dialect->lineterminator);
- if (terminator_len == -1)
- return 0;
+ terminator_len = PyString_Size(self->dialect->lineterminator);
+ if (terminator_len == -1)
+ return 0;
- /* grow record buffer if necessary */
- if (!join_check_rec_size(self, self->rec_len + terminator_len))
- return 0;
+ /* grow record buffer if necessary */
+ if (!join_check_rec_size(self, self->rec_len + terminator_len))
+ return 0;
- terminator = PyString_AsString(self->dialect->lineterminator);
- if (terminator == NULL)
- return 0;
- memmove(self->rec + self->rec_len, terminator, terminator_len);
- self->rec_len += terminator_len;
+ terminator = PyString_AsString(self->dialect->lineterminator);
+ if (terminator == NULL)
+ return 0;
+ memmove(self->rec + self->rec_len, terminator, terminator_len);
+ self->rec_len += terminator_len;
- return 1;
+ return 1;
}
PyDoc_STRVAR(csv_writerow_doc,
@@ -1137,73 +1137,73 @@ PyDoc_STRVAR(csv_writerow_doc,
static PyObject *
csv_writerow(WriterObj *self, PyObject *seq)
{
- DialectObj *dialect = self->dialect;
- int len, i;
-
- if (!PySequence_Check(seq))
- return PyErr_Format(error_obj, "sequence expected");
-
- len = PySequence_Length(seq);
- if (len < 0)
- return NULL;
-
- /* Join all fields in internal buffer.
- */
- join_reset(self);
- for (i = 0; i < len; i++) {
- PyObject *field;
- int append_ok;
- int quoted;
-
- field = PySequence_GetItem(seq, i);
- if (field == NULL)
- return NULL;
-
- switch (dialect->quoting) {
- case QUOTE_NONNUMERIC:
- quoted = !PyNumber_Check(field);
- break;
- case QUOTE_ALL:
- quoted = 1;
- break;
- default:
- quoted = 0;
- break;
- }
-
- if (PyString_Check(field)) {
- append_ok = join_append(self,
- PyString_AS_STRING(field),
- &quoted, len == 1);
- Py_DECREF(field);
- }
- else if (field == Py_None) {
- append_ok = join_append(self, "", &quoted, len == 1);
- Py_DECREF(field);
- }
- else {
- PyObject *str;
-
- str = PyObject_Str(field);
- Py_DECREF(field);
- if (str == NULL)
- return NULL;
-
- append_ok = join_append(self, PyString_AS_STRING(str),
- &quoted, len == 1);
- Py_DECREF(str);
- }
- if (!append_ok)
- return NULL;
- }
-
- /* Add line terminator.
- */
- if (!join_append_lineterminator(self))
- return 0;
-
- return PyObject_CallFunction(self->writeline,
- "(s#)", self->rec, self->rec_len);
+ DialectObj *dialect = self->dialect;
+ int len, i;
+
+ if (!PySequence_Check(seq))
+ return PyErr_Format(error_obj, "sequence expected");
+
+ len = PySequence_Length(seq);
+ if (len < 0)
+ return NULL;
+
+ /* Join all fields in internal buffer.
+ */
+ join_reset(self);
+ for (i = 0; i < len; i++) {
+ PyObject *field;
+ int append_ok;
+ int quoted;
+
+ field = PySequence_GetItem(seq, i);
+ if (field == NULL)
+ return NULL;
+
+ switch (dialect->quoting) {
+ case QUOTE_NONNUMERIC:
+ quoted = !PyNumber_Check(field);
+ break;
+ case QUOTE_ALL:
+ quoted = 1;
+ break;
+ default:
+ quoted = 0;
+ break;
+ }
+
+ if (PyString_Check(field)) {
+ append_ok = join_append(self,
+ PyString_AS_STRING(field),
+ &quoted, len == 1);
+ Py_DECREF(field);
+ }
+ else if (field == Py_None) {
+ append_ok = join_append(self, "", &quoted, len == 1);
+ Py_DECREF(field);
+ }
+ else {
+ PyObject *str;
+
+ str = PyObject_Str(field);
+ Py_DECREF(field);
+ if (str == NULL)
+ return NULL;
+
+ append_ok = join_append(self, PyString_AS_STRING(str),
+ &quoted, len == 1);
+ Py_DECREF(str);
+ }
+ if (!append_ok)
+ return NULL;
+ }
+
+ /* Add line terminator.
+ */
+ if (!join_append_lineterminator(self))
+ return 0;
+
+ return PyObject_CallFunction(self->writeline,
+ "(s#)", self->rec, self->rec_len);
}
PyDoc_STRVAR(csv_writerows_doc,
@@ -1215,72 +1215,72 @@ PyDoc_STRVAR(csv_writerows_doc,
static PyObject *
csv_writerows(WriterObj *self, PyObject *seqseq)
{
- PyObject *row_iter, *row_obj, *result;
-
- row_iter = PyObject_GetIter(seqseq);
- if (row_iter == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "writerows() argument must be iterable");
- return NULL;
+ PyObject *row_iter, *row_obj, *result;
+
+ row_iter = PyObject_GetIter(seqseq);
+ if (row_iter == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "writerows() argument must be iterable");
+ return NULL;
+ }
+ while ((row_obj = PyIter_Next(row_iter))) {
+ result = csv_writerow(self, row_obj);
+ Py_DECREF(row_obj);
+ if (!result) {
+ Py_DECREF(row_iter);
+ return NULL;
}
- while ((row_obj = PyIter_Next(row_iter))) {
- result = csv_writerow(self, row_obj);
- Py_DECREF(row_obj);
- if (!result) {
- Py_DECREF(row_iter);
- return NULL;
- }
- else
- Py_DECREF(result);
- }
- Py_DECREF(row_iter);
- if (PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ else
+ Py_DECREF(result);
+ }
+ Py_DECREF(row_iter);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef Writer_methods[] = {
- { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc},
- { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc},
- { NULL, NULL }
+ { "writerow", (PyCFunction)csv_writerow, METH_O, csv_writerow_doc},
+ { "writerows", (PyCFunction)csv_writerows, METH_O, csv_writerows_doc},
+ { NULL, NULL }
};
#define W_OFF(x) offsetof(WriterObj, x)
static struct PyMemberDef Writer_memberlist[] = {
- { "dialect", T_OBJECT, W_OFF(dialect), RO },
- { NULL }
+ { "dialect", T_OBJECT, W_OFF(dialect), RO },
+ { NULL }
};
static void
Writer_dealloc(WriterObj *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->dialect);
- Py_XDECREF(self->writeline);
- if (self->rec != NULL)
- PyMem_Free(self->rec);
- PyObject_GC_Del(self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->dialect);
+ Py_XDECREF(self->writeline);
+ if (self->rec != NULL)
+ PyMem_Free(self->rec);
+ PyObject_GC_Del(self);
}
static int
Writer_traverse(WriterObj *self, visitproc visit, void *arg)
{
- Py_VISIT(self->dialect);
- Py_VISIT(self->writeline);
- return 0;
+ Py_VISIT(self->dialect);
+ Py_VISIT(self->writeline);
+ return 0;
}
static int
Writer_clear(WriterObj *self)
{
- Py_CLEAR(self->dialect);
- Py_CLEAR(self->writeline);
- return 0;
+ Py_CLEAR(self->dialect);
+ Py_CLEAR(self->writeline);
+ return 0;
}
-PyDoc_STRVAR(Writer_Type_doc,
+PyDoc_STRVAR(Writer_Type_doc,
"CSV writer\n"
"\n"
"Writer objects are responsible for generating tabular data\n"
@@ -1288,75 +1288,75 @@ PyDoc_STRVAR(Writer_Type_doc,
);
static PyTypeObject Writer_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_csv.writer", /*tp_name*/
- sizeof(WriterObj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)Writer_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)0, /*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*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
- Py_TPFLAGS_HAVE_GC, /*tp_flags*/
- Writer_Type_doc,
- (traverseproc)Writer_traverse, /*tp_traverse*/
- (inquiry)Writer_clear, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- (getiterfunc)0, /*tp_iter*/
- (getiterfunc)0, /*tp_iternext*/
- Writer_methods, /*tp_methods*/
- Writer_memberlist, /*tp_members*/
- 0, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_csv.writer", /*tp_name*/
+ sizeof(WriterObj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)Writer_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)0, /*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*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
+ Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ Writer_Type_doc,
+ (traverseproc)Writer_traverse, /*tp_traverse*/
+ (inquiry)Writer_clear, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ (getiterfunc)0, /*tp_iter*/
+ (getiterfunc)0, /*tp_iternext*/
+ Writer_methods, /*tp_methods*/
+ Writer_memberlist, /*tp_members*/
+ 0, /*tp_getset*/
};
static PyObject *
csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
{
- PyObject * output_file, * dialect = NULL;
- WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type);
-
- if (!self)
- return NULL;
-
- self->dialect = NULL;
- self->writeline = NULL;
-
- self->rec = NULL;
- self->rec_size = 0;
- self->rec_len = 0;
- self->num_fields = 0;
-
- if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) {
- Py_DECREF(self);
- return NULL;
- }
- self->writeline = PyObject_GetAttrString(output_file, "write");
- if (self->writeline == NULL || !PyCallable_Check(self->writeline)) {
- PyErr_SetString(PyExc_TypeError,
- "argument 1 must have a \"write\" method");
- Py_DECREF(self);
- return NULL;
- }
- self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
- if (self->dialect == NULL) {
- Py_DECREF(self);
- return NULL;
- }
- PyObject_GC_Track(self);
- return (PyObject *)self;
+ PyObject * output_file, * dialect = NULL;
+ WriterObj * self = PyObject_GC_New(WriterObj, &Writer_Type);
+
+ if (!self)
+ return NULL;
+
+ self->dialect = NULL;
+ self->writeline = NULL;
+
+ self->rec = NULL;
+ self->rec_size = 0;
+ self->rec_len = 0;
+ self->num_fields = 0;
+
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &output_file, &dialect)) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->writeline = PyObject_GetAttrString(output_file, "write");
+ if (self->writeline == NULL || !PyCallable_Check(self->writeline)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument 1 must have a \"write\" method");
+ Py_DECREF(self);
+ return NULL;
+ }
+ self->dialect = (DialectObj *)_call_dialect(dialect, keyword_args);
+ if (self->dialect == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ PyObject_GC_Track(self);
+ return (PyObject *)self;
}
/*
@@ -1365,66 +1365,66 @@ csv_writer(PyObject *module, PyObject *args, PyObject *keyword_args)
static PyObject *
csv_list_dialects(PyObject *module, PyObject *args)
{
- return PyDict_Keys(dialects);
+ return PyDict_Keys(dialects);
}
static PyObject *
csv_register_dialect(PyObject *module, PyObject *args, PyObject *kwargs)
{
- PyObject *name_obj, *dialect_obj = NULL;
- PyObject *dialect;
-
- if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj))
- return NULL;
- if (!IS_BASESTRING(name_obj)) {
- PyErr_SetString(PyExc_TypeError,
- "dialect name must be a string or unicode");
- return NULL;
- }
- dialect = _call_dialect(dialect_obj, kwargs);
- if (dialect == NULL)
- return NULL;
- if (PyDict_SetItem(dialects, name_obj, dialect) < 0) {
- Py_DECREF(dialect);
- return NULL;
- }
- Py_DECREF(dialect);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *name_obj, *dialect_obj = NULL;
+ PyObject *dialect;
+
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &name_obj, &dialect_obj))
+ return NULL;
+ if (!IS_BASESTRING(name_obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "dialect name must be a string or unicode");
+ return NULL;
+ }
+ dialect = _call_dialect(dialect_obj, kwargs);
+ if (dialect == NULL)
+ return NULL;
+ if (PyDict_SetItem(dialects, name_obj, dialect) < 0) {
+ Py_DECREF(dialect);
+ return NULL;
+ }
+ Py_DECREF(dialect);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
csv_unregister_dialect(PyObject *module, PyObject *name_obj)
{
- if (PyDict_DelItem(dialects, name_obj) < 0)
- return PyErr_Format(error_obj, "unknown dialect");
- Py_INCREF(Py_None);
- return Py_None;
+ if (PyDict_DelItem(dialects, name_obj) < 0)
+ return PyErr_Format(error_obj, "unknown dialect");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
csv_get_dialect(PyObject *module, PyObject *name_obj)
{
- return get_dialect_from_registry(name_obj);
+ return get_dialect_from_registry(name_obj);
}
static PyObject *
csv_field_size_limit(PyObject *module, PyObject *args)
{
- PyObject *new_limit = NULL;
- long old_limit = field_limit;
-
- if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
- return NULL;
- if (new_limit != NULL) {
- if (!PyInt_Check(new_limit)) {
- PyErr_Format(PyExc_TypeError,
- "limit must be an integer");
- return NULL;
- }
- field_limit = PyInt_AsLong(new_limit);
- }
- return PyInt_FromLong(old_limit);
+ PyObject *new_limit = NULL;
+ long old_limit = field_limit;
+
+ if (!PyArg_UnpackTuple(args, "field_size_limit", 0, 1, &new_limit))
+ return NULL;
+ if (new_limit != NULL) {
+ if (!PyInt_Check(new_limit)) {
+ PyErr_Format(PyExc_TypeError,
+ "limit must be an integer");
+ return NULL;
+ }
+ field_limit = PyInt_AsLong(new_limit);
+ }
+ return PyInt_FromLong(old_limit);
}
/*
@@ -1542,70 +1542,70 @@ PyDoc_STRVAR(csv_field_size_limit_doc,
"the old limit is returned");
static struct PyMethodDef csv_methods[] = {
- { "reader", (PyCFunction)csv_reader,
- METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
- { "writer", (PyCFunction)csv_writer,
- METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
- { "list_dialects", (PyCFunction)csv_list_dialects,
- METH_NOARGS, csv_list_dialects_doc},
- { "register_dialect", (PyCFunction)csv_register_dialect,
- METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
- { "unregister_dialect", (PyCFunction)csv_unregister_dialect,
- METH_O, csv_unregister_dialect_doc},
- { "get_dialect", (PyCFunction)csv_get_dialect,
- METH_O, csv_get_dialect_doc},
- { "field_size_limit", (PyCFunction)csv_field_size_limit,
- METH_VARARGS, csv_field_size_limit_doc},
- { NULL, NULL }
+ { "reader", (PyCFunction)csv_reader,
+ METH_VARARGS | METH_KEYWORDS, csv_reader_doc},
+ { "writer", (PyCFunction)csv_writer,
+ METH_VARARGS | METH_KEYWORDS, csv_writer_doc},
+ { "list_dialects", (PyCFunction)csv_list_dialects,
+ METH_NOARGS, csv_list_dialects_doc},
+ { "register_dialect", (PyCFunction)csv_register_dialect,
+ METH_VARARGS | METH_KEYWORDS, csv_register_dialect_doc},
+ { "unregister_dialect", (PyCFunction)csv_unregister_dialect,
+ METH_O, csv_unregister_dialect_doc},
+ { "get_dialect", (PyCFunction)csv_get_dialect,
+ METH_O, csv_get_dialect_doc},
+ { "field_size_limit", (PyCFunction)csv_field_size_limit,
+ METH_VARARGS, csv_field_size_limit_doc},
+ { NULL, NULL }
};
PyMODINIT_FUNC
init_csv(void)
{
- PyObject *module;
- StyleDesc *style;
-
- if (PyType_Ready(&Dialect_Type) < 0)
- return;
-
- if (PyType_Ready(&Reader_Type) < 0)
- return;
-
- if (PyType_Ready(&Writer_Type) < 0)
- return;
-
- /* Create the module and add the functions */
- module = Py_InitModule3("_csv", csv_methods, csv_module_doc);
- if (module == NULL)
- return;
-
- /* Add version to the module. */
- if (PyModule_AddStringConstant(module, "__version__",
- MODULE_VERSION) == -1)
- return;
-
- /* Add _dialects dictionary */
- dialects = PyDict_New();
- if (dialects == NULL)
- return;
- if (PyModule_AddObject(module, "_dialects", dialects))
- return;
-
- /* Add quote styles into dictionary */
- for (style = quote_styles; style->name; style++) {
- if (PyModule_AddIntConstant(module, style->name,
- style->style) == -1)
- return;
- }
-
- /* Add the Dialect type */
- Py_INCREF(&Dialect_Type);
- if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
- return;
-
- /* Add the CSV exception object to the module. */
- error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
- if (error_obj == NULL)
- return;
- PyModule_AddObject(module, "Error", error_obj);
+ PyObject *module;
+ StyleDesc *style;
+
+ if (PyType_Ready(&Dialect_Type) < 0)
+ return;
+
+ if (PyType_Ready(&Reader_Type) < 0)
+ return;
+
+ if (PyType_Ready(&Writer_Type) < 0)
+ return;
+
+ /* Create the module and add the functions */
+ module = Py_InitModule3("_csv", csv_methods, csv_module_doc);
+ if (module == NULL)
+ return;
+
+ /* Add version to the module. */
+ if (PyModule_AddStringConstant(module, "__version__",
+ MODULE_VERSION) == -1)
+ return;
+
+ /* Add _dialects dictionary */
+ dialects = PyDict_New();
+ if (dialects == NULL)
+ return;
+ if (PyModule_AddObject(module, "_dialects", dialects))
+ return;
+
+ /* Add quote styles into dictionary */
+ for (style = quote_styles; style->name; style++) {
+ if (PyModule_AddIntConstant(module, style->name,
+ style->style) == -1)
+ return;
+ }
+
+ /* Add the Dialect type */
+ Py_INCREF(&Dialect_Type);
+ if (PyModule_AddObject(module, "Dialect", (PyObject *)&Dialect_Type))
+ return;
+
+ /* Add the CSV exception object to the module. */
+ error_obj = PyErr_NewException("_csv.Error", NULL, NULL);
+ if (error_obj == NULL)
+ return;
+ PyModule_AddObject(module, "Error", error_obj);
}
diff --git a/Modules/_ctypes/_ctypes.c b/Modules/_ctypes/_ctypes.c
index 465ecdb..af3bb5b 100644
--- a/Modules/_ctypes/_ctypes.c
+++ b/Modules/_ctypes/_ctypes.c
@@ -25,20 +25,20 @@
/*
-Name methods, members, getsets
+Name methods, members, getsets
==============================================================================
-PyCStructType_Type __new__(), from_address(), __mul__(), from_param()
-UnionType_Type __new__(), from_address(), __mul__(), from_param()
-PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
-PyCArrayType_Type __new__(), from_address(), __mul__(), from_param()
-PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param()
+PyCStructType_Type __new__(), from_address(), __mul__(), from_param()
+UnionType_Type __new__(), from_address(), __mul__(), from_param()
+PyCPointerType_Type __new__(), from_address(), __mul__(), from_param(), set_type()
+PyCArrayType_Type __new__(), from_address(), __mul__(), from_param()
+PyCSimpleType_Type __new__(), from_address(), __mul__(), from_param()
PyCData_Type
- Struct_Type __new__(), __init__()
- PyCPointer_Type __new__(), __init__(), _as_parameter_, contents
- PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
- Simple_Type __new__(), __init__(), _as_parameter_
+ Struct_Type __new__(), __init__()
+ PyCPointer_Type __new__(), __init__(), _as_parameter_, contents
+ PyCArray_Type __new__(), __init__(), _as_parameter_, __get/setitem__(), __len__()
+ Simple_Type __new__(), __init__(), _as_parameter_
PyCField_Type
PyCStgDict_Type
@@ -50,28 +50,28 @@ class methods
It has some similarity to the byref() construct compared to pointer()
from_address(addr)
- - construct an instance from a given memory block (sharing this memory block)
+ - construct an instance from a given memory block (sharing this memory block)
from_param(obj)
- - typecheck and convert a Python object into a C function call parameter
- the result may be an instance of the type, or an integer or tuple
- (typecode, value[, obj])
+ - typecheck and convert a Python object into a C function call parameter
+ the result may be an instance of the type, or an integer or tuple
+ (typecode, value[, obj])
instance methods/properties
---------------------------
_as_parameter_
- - convert self into a C function call parameter
- This is either an integer, or a 3-tuple (typecode, value, obj)
+ - convert self into a C function call parameter
+ This is either an integer, or a 3-tuple (typecode, value, obj)
functions
---------
sizeof(cdata)
- - return the number of bytes the buffer contains
+ - return the number of bytes the buffer contains
sizeof(ctype)
- - return the number of bytes the buffer of an instance would contain
+ - return the number of bytes the buffer of an instance would contain
byref(cdata)
@@ -82,7 +82,7 @@ pointer(cdata)
POINTER(ctype)
bytes(cdata)
- - return the buffer contents as a sequence of bytes (which is currently a string)
+ - return the buffer contents as a sequence of bytes (which is currently a string)
*/
@@ -103,7 +103,7 @@ bytes(cdata)
* PyCField_Type
*
*/
-
+
#define PY_SSIZE_T_CLEAN
#include "Python.h"
@@ -140,7 +140,7 @@ static PyObject *_unpickle;
char *_ctypes_conversion_encoding = NULL;
char *_ctypes_conversion_errors = NULL;
-
+
/****************************************************************/
#if (PY_VERSION_HEX < 0x02040000)
@@ -148,148 +148,148 @@ char *_ctypes_conversion_errors = NULL;
static PyObject *
PyTuple_Pack(int n, ...)
{
- int i;
- PyObject *o;
- PyObject *result;
- PyObject **items;
- va_list vargs;
-
- va_start(vargs, n);
- result = PyTuple_New(n);
- if (result == NULL)
- return NULL;
- items = ((PyTupleObject *)result)->ob_item;
- for (i = 0; i < n; i++) {
- o = va_arg(vargs, PyObject *);
- Py_INCREF(o);
- items[i] = o;
- }
- va_end(vargs);
- return result;
+ int i;
+ PyObject *o;
+ PyObject *result;
+ PyObject **items;
+ va_list vargs;
+
+ va_start(vargs, n);
+ result = PyTuple_New(n);
+ if (result == NULL)
+ return NULL;
+ items = ((PyTupleObject *)result)->ob_item;
+ for (i = 0; i < n; i++) {
+ o = va_arg(vargs, PyObject *);
+ Py_INCREF(o);
+ items[i] = o;
+ }
+ va_end(vargs);
+ return result;
}
#endif
/****************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *key;
- PyObject *dict;
+ PyObject_HEAD
+ PyObject *key;
+ PyObject *dict;
} DictRemoverObject;
static void
_DictRemover_dealloc(PyObject *_self)
{
- DictRemoverObject *self = (DictRemoverObject *)_self;
- Py_XDECREF(self->key);
- Py_XDECREF(self->dict);
- Py_TYPE(self)->tp_free(_self);
+ DictRemoverObject *self = (DictRemoverObject *)_self;
+ Py_XDECREF(self->key);
+ Py_XDECREF(self->dict);
+ Py_TYPE(self)->tp_free(_self);
}
static PyObject *
_DictRemover_call(PyObject *_self, PyObject *args, PyObject *kw)
{
- DictRemoverObject *self = (DictRemoverObject *)_self;
- if (self->key && self->dict) {
- if (-1 == PyDict_DelItem(self->dict, self->key))
- /* XXX Error context */
- PyErr_WriteUnraisable(Py_None);
- Py_DECREF(self->key);
- self->key = NULL;
- Py_DECREF(self->dict);
- self->dict = NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ DictRemoverObject *self = (DictRemoverObject *)_self;
+ if (self->key && self->dict) {
+ if (-1 == PyDict_DelItem(self->dict, self->key))
+ /* XXX Error context */
+ PyErr_WriteUnraisable(Py_None);
+ Py_DECREF(self->key);
+ self->key = NULL;
+ Py_DECREF(self->dict);
+ self->dict = NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyTypeObject DictRemover_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.DictRemover", /* tp_name */
- sizeof(DictRemoverObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- _DictRemover_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 */
- _DictRemover_call, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.DictRemover", /* tp_name */
+ sizeof(DictRemoverObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ _DictRemover_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 */
+ _DictRemover_call, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
/* XXX should participate in GC? */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- "deletes a key from a dictionary", /* 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ "deletes a key from a dictionary", /* 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
int
PyDict_SetItemProxy(PyObject *dict, PyObject *key, PyObject *item)
{
- PyObject *obj;
- DictRemoverObject *remover;
- PyObject *proxy;
- int result;
-
- obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
- if (obj == NULL)
- return -1;
-
- remover = (DictRemoverObject *)obj;
- assert(remover->key == NULL);
- assert(remover->dict == NULL);
- Py_INCREF(key);
- remover->key = key;
- Py_INCREF(dict);
- remover->dict = dict;
-
- proxy = PyWeakref_NewProxy(item, obj);
- Py_DECREF(obj);
- if (proxy == NULL)
- return -1;
-
- result = PyDict_SetItem(dict, key, proxy);
- Py_DECREF(proxy);
- return result;
+ PyObject *obj;
+ DictRemoverObject *remover;
+ PyObject *proxy;
+ int result;
+
+ obj = PyObject_CallObject((PyObject *)&DictRemover_Type, NULL);
+ if (obj == NULL)
+ return -1;
+
+ remover = (DictRemoverObject *)obj;
+ assert(remover->key == NULL);
+ assert(remover->dict == NULL);
+ Py_INCREF(key);
+ remover->key = key;
+ Py_INCREF(dict);
+ remover->dict = dict;
+
+ proxy = PyWeakref_NewProxy(item, obj);
+ Py_DECREF(obj);
+ if (proxy == NULL)
+ return -1;
+
+ result = PyDict_SetItem(dict, key, proxy);
+ Py_DECREF(proxy);
+ return result;
}
PyObject *
PyDict_GetItemProxy(PyObject *dict, PyObject *key)
{
- PyObject *result;
- PyObject *item = PyDict_GetItem(dict, key);
-
- if (item == NULL)
- return NULL;
- if (!PyWeakref_CheckProxy(item))
- return item;
- result = PyWeakref_GET_OBJECT(item);
- if (result == Py_None)
- return NULL;
- return result;
+ PyObject *result;
+ PyObject *item = PyDict_GetItem(dict, key);
+
+ if (item == NULL)
+ return NULL;
+ if (!PyWeakref_CheckProxy(item))
+ return item;
+ result = PyWeakref_GET_OBJECT(item);
+ if (result == Py_None)
+ return NULL;
+ return result;
}
/******************************************************************/
@@ -302,25 +302,25 @@ PyDict_GetItemProxy(PyObject *dict, PyObject *key)
char *
_ctypes_alloc_format_string(const char *prefix, const char *suffix)
{
- size_t len;
- char *result;
-
- if (suffix == NULL) {
- assert(PyErr_Occurred());
- return NULL;
- }
- len = strlen(suffix);
- if (prefix)
- len += strlen(prefix);
- result = PyMem_Malloc(len + 1);
- if (result == NULL)
- return NULL;
- if (prefix)
- strcpy(result, prefix);
- else
- result[0] = '\0';
- strcat(result, suffix);
- return result;
+ size_t len;
+ char *result;
+
+ if (suffix == NULL) {
+ assert(PyErr_Occurred());
+ return NULL;
+ }
+ len = strlen(suffix);
+ if (prefix)
+ len += strlen(prefix);
+ result = PyMem_Malloc(len + 1);
+ if (result == NULL)
+ return NULL;
+ if (prefix)
+ strcpy(result, prefix);
+ else
+ result[0] = '\0';
+ strcat(result, suffix);
+ return result;
}
/*
@@ -333,100 +333,100 @@ _ctypes_alloc_format_string(const char *prefix, const char *suffix)
static PyCArgObject *
StructUnionType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
- StgDictObject *stgdict;
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'V';
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for structure/union instances */
- parg->pffi_type = &stgdict->ffi_type_pointer;
- /* For structure parameters (by value), parg->value doesn't contain the structure
- data itself, instead parg->value.p *points* to the structure's data
- See also _ctypes.c, function _call_function_pointer().
- */
- parg->value.p = self->b_ptr;
- parg->size = self->b_size;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- return parg;
+ PyCArgObject *parg;
+ StgDictObject *stgdict;
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'V';
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for structure/union instances */
+ parg->pffi_type = &stgdict->ffi_type_pointer;
+ /* For structure parameters (by value), parg->value doesn't contain the structure
+ data itself, instead parg->value.p *points* to the structure's data
+ See also _ctypes.c, function _call_function_pointer().
+ */
+ parg->value.p = self->b_ptr;
+ parg->size = self->b_size;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ return parg;
}
static PyObject *
StructUnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds, int isStruct)
{
- PyTypeObject *result;
- PyObject *fields;
- StgDictObject *dict;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (!result)
- return NULL;
-
- /* keep this for bw compatibility */
- if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
- return (PyObject *)result;
-
- dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL);
- if (!dict) {
- Py_DECREF(result);
- return NULL;
- }
- /* replace the class dict by our updated stgdict, which holds info
- about storage requirements of the instances */
- if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)dict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)dict;
- dict->format = _ctypes_alloc_format_string(NULL, "B");
- if (dict->format == NULL) {
- Py_DECREF(result);
- return NULL;
- }
-
- dict->paramfunc = StructUnionType_paramfunc;
-
- fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
- if (!fields) {
- StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
-
- if (basedict == NULL)
- return (PyObject *)result;
- /* copy base dict */
- if (-1 == PyCStgDict_clone(dict, basedict)) {
- Py_DECREF(result);
- return NULL;
- }
- dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */
- basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */
- return (PyObject *)result;
- }
-
- if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
- Py_DECREF(result);
- return NULL;
- }
- return (PyObject *)result;
+ PyTypeObject *result;
+ PyObject *fields;
+ StgDictObject *dict;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (!result)
+ return NULL;
+
+ /* keep this for bw compatibility */
+ if (PyDict_GetItemString(result->tp_dict, "_abstract_"))
+ return (PyObject *)result;
+
+ dict = (StgDictObject *)PyObject_CallObject((PyObject *)&PyCStgDict_Type, NULL);
+ if (!dict) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ /* replace the class dict by our updated stgdict, which holds info
+ about storage requirements of the instances */
+ if (-1 == PyDict_Update((PyObject *)dict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)dict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)dict;
+ dict->format = _ctypes_alloc_format_string(NULL, "B");
+ if (dict->format == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ dict->paramfunc = StructUnionType_paramfunc;
+
+ fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
+ if (!fields) {
+ StgDictObject *basedict = PyType_stgdict((PyObject *)result->tp_base);
+
+ if (basedict == NULL)
+ return (PyObject *)result;
+ /* copy base dict */
+ if (-1 == PyCStgDict_clone(dict, basedict)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ dict->flags &= ~DICTFLAG_FINAL; /* clear the 'final' flag in the subclass dict */
+ basedict->flags |= DICTFLAG_FINAL; /* set the 'final' flag in the baseclass dict */
+ return (PyObject *)result;
+ }
+
+ if (-1 == PyObject_SetAttrString((PyObject *)result, "_fields_", fields)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return (PyObject *)result;
}
static PyObject *
PyCStructType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- return StructUnionType_new(type, args, kwds, 1);
+ return StructUnionType_new(type, args, kwds, 1);
}
static PyObject *
UnionType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- return StructUnionType_new(type, args, kwds, 0);
+ return StructUnionType_new(type, args, kwds, 0);
}
static char from_address_doc[] =
@@ -435,16 +435,16 @@ static char from_address_doc[] =
static PyObject *
CDataType_from_address(PyObject *type, PyObject *value)
{
- void *buf;
- if (!PyInt_Check(value) && !PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "integer expected");
- return NULL;
- }
- buf = (void *)PyLong_AsVoidPtr(value);
- if (PyErr_Occurred())
- return NULL;
- return PyCData_AtAddress(type, buf);
+ void *buf;
+ if (!PyInt_Check(value) && !PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "integer expected");
+ return NULL;
+ }
+ buf = (void *)PyLong_AsVoidPtr(value);
+ if (PyErr_Occurred())
+ return NULL;
+ return PyCData_AtAddress(type, buf);
}
static char from_buffer_doc[] =
@@ -456,51 +456,51 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep);
static PyObject *
CDataType_from_buffer(PyObject *type, PyObject *args)
{
- void *buffer;
- Py_ssize_t buffer_len;
- Py_ssize_t offset = 0;
- PyObject *obj, *result;
- StgDictObject *dict = PyType_stgdict(type);
- assert (dict);
-
- if (!PyArg_ParseTuple(args,
+ void *buffer;
+ Py_ssize_t buffer_len;
+ Py_ssize_t offset = 0;
+ PyObject *obj, *result;
+ StgDictObject *dict = PyType_stgdict(type);
+ assert (dict);
+
+ if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
- "O|i:from_buffer",
+ "O|i:from_buffer",
#else
- "O|n:from_buffer",
+ "O|n:from_buffer",
#endif
- &obj, &offset))
- return NULL;
-
- if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
- return NULL;
-
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError,
- "offset cannot be negative");
- return NULL;
- }
- if (dict->size > buffer_len - offset) {
- PyErr_Format(PyExc_ValueError,
+ &obj, &offset))
+ return NULL;
+
+ if (-1 == PyObject_AsWriteBuffer(obj, &buffer, &buffer_len))
+ return NULL;
+
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "offset cannot be negative");
+ return NULL;
+ }
+ if (dict->size > buffer_len - offset) {
+ PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Buffer size too small (%d instead of at least %d bytes)",
+ "Buffer size too small (%d instead of at least %d bytes)",
#else
- "Buffer size too small (%zd instead of at least %zd bytes)",
+ "Buffer size too small (%zd instead of at least %zd bytes)",
#endif
- buffer_len, dict->size + offset);
- return NULL;
- }
-
- result = PyCData_AtAddress(type, (char *)buffer + offset);
- if (result == NULL)
- return NULL;
-
- Py_INCREF(obj);
- if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
- Py_DECREF(result);
- return NULL;
- }
- return result;
+ buffer_len, dict->size + offset);
+ return NULL;
+ }
+
+ result = PyCData_AtAddress(type, (char *)buffer + offset);
+ if (result == NULL)
+ return NULL;
+
+ Py_INCREF(obj);
+ if (-1 == KeepRef((CDataObject *)result, -1, obj)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return result;
}
static char from_buffer_copy_doc[] =
@@ -512,48 +512,48 @@ GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
CDataType_from_buffer_copy(PyObject *type, PyObject *args)
{
- const void *buffer;
- Py_ssize_t buffer_len;
- Py_ssize_t offset = 0;
- PyObject *obj, *result;
- StgDictObject *dict = PyType_stgdict(type);
- assert (dict);
-
- if (!PyArg_ParseTuple(args,
+ const void *buffer;
+ Py_ssize_t buffer_len;
+ Py_ssize_t offset = 0;
+ PyObject *obj, *result;
+ StgDictObject *dict = PyType_stgdict(type);
+ assert (dict);
+
+ if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
- "O|i:from_buffer",
+ "O|i:from_buffer",
#else
- "O|n:from_buffer",
+ "O|n:from_buffer",
#endif
- &obj, &offset))
- return NULL;
+ &obj, &offset))
+ return NULL;
- if (-1 == PyObject_AsReadBuffer(obj, &buffer, &buffer_len))
- return NULL;
+ if (-1 == PyObject_AsReadBuffer(obj, &buffer, &buffer_len))
+ return NULL;
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError,
- "offset cannot be negative");
- return NULL;
- }
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "offset cannot be negative");
+ return NULL;
+ }
- if (dict->size > buffer_len - offset) {
- PyErr_Format(PyExc_ValueError,
+ if (dict->size > buffer_len - offset) {
+ PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Buffer size too small (%d instead of at least %d bytes)",
+ "Buffer size too small (%d instead of at least %d bytes)",
#else
- "Buffer size too small (%zd instead of at least %zd bytes)",
+ "Buffer size too small (%zd instead of at least %zd bytes)",
#endif
- buffer_len, dict->size + offset);
- return NULL;
- }
-
- result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL);
- if (result == NULL)
- return NULL;
- memcpy(((CDataObject *)result)->b_ptr,
- (char *)buffer+offset, dict->size);
- return result;
+ buffer_len, dict->size + offset);
+ return NULL;
+ }
+
+ result = GenericPyCData_new((PyTypeObject *)type, NULL, NULL);
+ if (result == NULL)
+ return NULL;
+ memcpy(((CDataObject *)result)->b_ptr,
+ (char *)buffer+offset, dict->size);
+ return result;
}
static char in_dll_doc[] =
@@ -562,55 +562,55 @@ static char in_dll_doc[] =
static PyObject *
CDataType_in_dll(PyObject *type, PyObject *args)
{
- PyObject *dll;
- char *name;
- PyObject *obj;
- void *handle;
- void *address;
-
- if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
- return NULL;
-
- obj = PyObject_GetAttrString(dll, "_handle");
- if (!obj)
- return NULL;
- if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "the _handle attribute of the second argument must be an integer");
- Py_DECREF(obj);
- return NULL;
- }
- handle = (void *)PyLong_AsVoidPtr(obj);
- Py_DECREF(obj);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert the _handle attribute to a pointer");
- return NULL;
- }
+ PyObject *dll;
+ char *name;
+ PyObject *obj;
+ void *handle;
+ void *address;
+
+ if (!PyArg_ParseTuple(args, "Os:in_dll", &dll, &name))
+ return NULL;
+
+ obj = PyObject_GetAttrString(dll, "_handle");
+ if (!obj)
+ return NULL;
+ if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the _handle attribute of the second argument must be an integer");
+ Py_DECREF(obj);
+ return NULL;
+ }
+ handle = (void *)PyLong_AsVoidPtr(obj);
+ Py_DECREF(obj);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert the _handle attribute to a pointer");
+ return NULL;
+ }
#ifdef MS_WIN32
- address = (void *)GetProcAddress(handle, name);
- if (!address) {
- PyErr_Format(PyExc_ValueError,
- "symbol '%s' not found",
- name);
- return NULL;
- }
+ address = (void *)GetProcAddress(handle, name);
+ if (!address) {
+ PyErr_Format(PyExc_ValueError,
+ "symbol '%s' not found",
+ name);
+ return NULL;
+ }
#else
- address = (void *)ctypes_dlsym(handle, name);
- if (!address) {
+ address = (void *)ctypes_dlsym(handle, name);
+ if (!address) {
#ifdef __CYGWIN__
/* dlerror() isn't very helpful on cygwin */
- PyErr_Format(PyExc_ValueError,
- "symbol '%s' not found (%s) ",
- name);
+ PyErr_Format(PyExc_ValueError,
+ "symbol '%s' not found (%s) ",
+ name);
#else
- PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
+ PyErr_SetString(PyExc_ValueError, ctypes_dlerror());
#endif
- return NULL;
- }
+ return NULL;
+ }
#endif
- return PyCData_AtAddress(type, address);
+ return PyCData_AtAddress(type, address);
}
static char from_param_doc[] =
@@ -619,213 +619,213 @@ static char from_param_doc[] =
static PyObject *
CDataType_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
- if (1 == PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
- if (PyCArg_CheckExact(value)) {
- PyCArgObject *p = (PyCArgObject *)value;
- PyObject *ob = p->obj;
- const char *ob_name;
- StgDictObject *dict;
- dict = PyType_stgdict(type);
-
- /* If we got a PyCArgObject, we must check if the object packed in it
- is an instance of the type's dict->proto */
- if(dict && ob
- && PyObject_IsInstance(ob, dict->proto)) {
- Py_INCREF(value);
- return value;
- }
- ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
- PyErr_Format(PyExc_TypeError,
- "expected %s instance instead of pointer to %s",
- ((PyTypeObject *)type)->tp_name, ob_name);
- return NULL;
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = CDataType_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- PyErr_Format(PyExc_TypeError,
- "expected %s instance instead of %s",
- ((PyTypeObject *)type)->tp_name,
- Py_TYPE(value)->tp_name);
- return NULL;
+ PyObject *as_parameter;
+ if (1 == PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyCArg_CheckExact(value)) {
+ PyCArgObject *p = (PyCArgObject *)value;
+ PyObject *ob = p->obj;
+ const char *ob_name;
+ StgDictObject *dict;
+ dict = PyType_stgdict(type);
+
+ /* If we got a PyCArgObject, we must check if the object packed in it
+ is an instance of the type's dict->proto */
+ if(dict && ob
+ && PyObject_IsInstance(ob, dict->proto)) {
+ Py_INCREF(value);
+ return value;
+ }
+ ob_name = (ob) ? Py_TYPE(ob)->tp_name : "???";
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instance instead of pointer to %s",
+ ((PyTypeObject *)type)->tp_name, ob_name);
+ return NULL;
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = CDataType_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instance instead of %s",
+ ((PyTypeObject *)type)->tp_name,
+ Py_TYPE(value)->tp_name);
+ return NULL;
}
static PyMethodDef CDataType_methods[] = {
- { "from_param", CDataType_from_param, METH_O, from_param_doc },
- { "from_address", CDataType_from_address, METH_O, from_address_doc },
- { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
- { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
- { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
- { NULL, NULL },
+ { "from_param", CDataType_from_param, METH_O, from_param_doc },
+ { "from_address", CDataType_from_address, METH_O, from_address_doc },
+ { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
+ { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
+ { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc },
+ { NULL, NULL },
};
static PyObject *
CDataType_repeat(PyObject *self, Py_ssize_t length)
{
- if (length < 0)
- return PyErr_Format(PyExc_ValueError,
+ if (length < 0)
+ return PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "Array length must be >= 0, not %d",
+ "Array length must be >= 0, not %d",
#else
- "Array length must be >= 0, not %zd",
+ "Array length must be >= 0, not %zd",
#endif
- length);
- return PyCArrayType_from_ctype(self, length);
+ length);
+ return PyCArrayType_from_ctype(self, length);
}
static PySequenceMethods CDataType_as_sequence = {
- 0, /* inquiry sq_length; */
- 0, /* binaryfunc sq_concat; */
- CDataType_repeat, /* intargfunc sq_repeat; */
- 0, /* intargfunc sq_item; */
- 0, /* intintargfunc sq_slice; */
- 0, /* intobjargproc sq_ass_item; */
- 0, /* intintobjargproc sq_ass_slice; */
- 0, /* objobjproc sq_contains; */
-
- 0, /* binaryfunc sq_inplace_concat; */
- 0, /* intargfunc sq_inplace_repeat; */
+ 0, /* inquiry sq_length; */
+ 0, /* binaryfunc sq_concat; */
+ CDataType_repeat, /* intargfunc sq_repeat; */
+ 0, /* intargfunc sq_item; */
+ 0, /* intintargfunc sq_slice; */
+ 0, /* intobjargproc sq_ass_item; */
+ 0, /* intintobjargproc sq_ass_slice; */
+ 0, /* objobjproc sq_contains; */
+
+ 0, /* binaryfunc sq_inplace_concat; */
+ 0, /* intargfunc sq_inplace_repeat; */
};
static int
CDataType_clear(PyTypeObject *self)
{
- StgDictObject *dict = PyType_stgdict((PyObject *)self);
- if (dict)
- Py_CLEAR(dict->proto);
- return PyType_Type.tp_clear((PyObject *)self);
+ StgDictObject *dict = PyType_stgdict((PyObject *)self);
+ if (dict)
+ Py_CLEAR(dict->proto);
+ return PyType_Type.tp_clear((PyObject *)self);
}
static int
CDataType_traverse(PyTypeObject *self, visitproc visit, void *arg)
{
- StgDictObject *dict = PyType_stgdict((PyObject *)self);
- if (dict)
- Py_VISIT(dict->proto);
- return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
+ StgDictObject *dict = PyType_stgdict((PyObject *)self);
+ if (dict)
+ Py_VISIT(dict->proto);
+ return PyType_Type.tp_traverse((PyObject *)self, visit, arg);
}
static int
PyCStructType_setattro(PyObject *self, PyObject *key, PyObject *value)
{
- /* XXX Should we disallow deleting _fields_? */
- if (-1 == PyType_Type.tp_setattro(self, key, value))
- return -1;
-
- if (value && PyString_Check(key) &&
- 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
- return PyCStructUnionType_update_stgdict(self, value, 1);
- return 0;
+ /* XXX Should we disallow deleting _fields_? */
+ if (-1 == PyType_Type.tp_setattro(self, key, value))
+ return -1;
+
+ if (value && PyString_Check(key) &&
+ 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
+ return PyCStructUnionType_update_stgdict(self, value, 1);
+ return 0;
}
static int
UnionType_setattro(PyObject *self, PyObject *key, PyObject *value)
{
- /* XXX Should we disallow deleting _fields_? */
- if (-1 == PyObject_GenericSetAttr(self, key, value))
- return -1;
-
- if (PyString_Check(key) &&
- 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
- return PyCStructUnionType_update_stgdict(self, value, 0);
- return 0;
+ /* XXX Should we disallow deleting _fields_? */
+ if (-1 == PyObject_GenericSetAttr(self, key, value))
+ return -1;
+
+ if (PyString_Check(key) &&
+ 0 == strcmp(PyString_AS_STRING(key), "_fields_"))
+ return PyCStructUnionType_update_stgdict(self, value, 0);
+ return 0;
}
PyTypeObject PyCStructType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCStructType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- PyCStructType_setattro, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for the CData Objects", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_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 */
- PyCStructType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCStructType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ PyCStructType_setattro, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for the CData Objects", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_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 */
+ PyCStructType_new, /* tp_new */
+ 0, /* tp_free */
};
static PyTypeObject UnionType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.UnionType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- UnionType_setattro, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for the CData Objects", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_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 */
- UnionType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.UnionType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ UnionType_setattro, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for the CData Objects", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_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 */
+ UnionType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
@@ -845,124 +845,124 @@ size property/method, and the sequence protocol.
static int
PyCPointerType_SetProto(StgDictObject *stgdict, PyObject *proto)
{
- if (!proto || !PyType_Check(proto)) {
- PyErr_SetString(PyExc_TypeError,
- "_type_ must be a type");
- return -1;
- }
- if (!PyType_stgdict(proto)) {
- PyErr_SetString(PyExc_TypeError,
- "_type_ must have storage info");
- return -1;
- }
- Py_INCREF(proto);
- Py_XDECREF(stgdict->proto);
- stgdict->proto = proto;
- return 0;
+ if (!proto || !PyType_Check(proto)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_type_ must be a type");
+ return -1;
+ }
+ if (!PyType_stgdict(proto)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_type_ must have storage info");
+ return -1;
+ }
+ Py_INCREF(proto);
+ Py_XDECREF(stgdict->proto);
+ stgdict->proto = proto;
+ return 0;
}
static PyCArgObject *
PyCPointerType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- parg->value.p = *(void **)self->b_ptr;
- return parg;
+ PyCArgObject *parg;
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ parg->value.p = *(void **)self->b_ptr;
+ return parg;
}
static PyObject *
PyCPointerType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- PyObject *proto;
- PyObject *typedict;
-
- typedict = PyTuple_GetItem(args, 2);
- if (!typedict)
- return NULL;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ PyObject *proto;
+ PyObject *typedict;
+
+ typedict = PyTuple_GetItem(args, 2);
+ if (!typedict)
+ return NULL;
/*
stgdict items size, align, length contain info about pointers itself,
stgdict->proto has info about the pointed to type!
*/
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- return NULL;
- stgdict->size = sizeof(void *);
- stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
- stgdict->length = 1;
- stgdict->ffi_type_pointer = ffi_type_pointer;
- stgdict->paramfunc = PyCPointerType_paramfunc;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
-
- proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
- if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- if (proto) {
- StgDictObject *itemdict = PyType_stgdict(proto);
- assert(itemdict);
- /* If itemdict->format is NULL, then this is a pointer to an
- incomplete type. We create a generic format string
- 'pointer to bytes' in this case. XXX Better would be to
- fix the format string later...
- */
- stgdict->format = _ctypes_alloc_format_string("&",
- itemdict->format ? itemdict->format : "B");
- if (stgdict->format == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- }
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- return (PyObject *)result;
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+ stgdict->size = sizeof(void *);
+ stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
+ stgdict->length = 1;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+ stgdict->paramfunc = PyCPointerType_paramfunc;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+
+ proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
+ if (proto && -1 == PyCPointerType_SetProto(stgdict, proto)) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ if (proto) {
+ StgDictObject *itemdict = PyType_stgdict(proto);
+ assert(itemdict);
+ /* If itemdict->format is NULL, then this is a pointer to an
+ incomplete type. We create a generic format string
+ 'pointer to bytes' in this case. XXX Better would be to
+ fix the format string later...
+ */
+ stgdict->format = _ctypes_alloc_format_string("&",
+ itemdict->format ? itemdict->format : "B");
+ if (stgdict->format == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ }
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ return (PyObject *)result;
}
static PyObject *
PyCPointerType_set_type(PyTypeObject *self, PyObject *type)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict((PyObject *)self);
- assert(dict);
+ dict = PyType_stgdict((PyObject *)self);
+ assert(dict);
- if (-1 == PyCPointerType_SetProto(dict, type))
- return NULL;
+ if (-1 == PyCPointerType_SetProto(dict, type))
+ return NULL;
- if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
- return NULL;
+ if (-1 == PyDict_SetItemString((PyObject *)dict, "_type_", type))
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
staticforward PyObject *_byref(PyObject *);
@@ -970,98 +970,98 @@ staticforward PyObject *_byref(PyObject *);
static PyObject *
PyCPointerType_from_param(PyObject *type, PyObject *value)
{
- StgDictObject *typedict;
-
- if (value == Py_None) {
- /* ConvParam will convert to a NULL pointer later */
- Py_INCREF(value);
- return value;
- }
-
- typedict = PyType_stgdict(type);
- assert(typedict); /* Cannot be NULL for pointer types */
-
- /* If we expect POINTER(<type>), but receive a <type> instance, accept
- it by calling byref(<type>).
- */
- switch (PyObject_IsInstance(value, typedict->proto)) {
- case 1:
- Py_INCREF(value); /* _byref steals a refcount */
- return _byref(value);
- case -1:
- PyErr_Clear();
- break;
- default:
- break;
- }
-
- if (PointerObject_Check(value) || ArrayObject_Check(value)) {
- /* Array instances are also pointers when
- the item types are the same.
- */
- StgDictObject *v = PyObject_stgdict(value);
- assert(v); /* Cannot be NULL for pointer or array objects */
- if (PyObject_IsSubclass(v->proto, typedict->proto)) {
- Py_INCREF(value);
- return value;
- }
- }
- return CDataType_from_param(type, value);
+ StgDictObject *typedict;
+
+ if (value == Py_None) {
+ /* ConvParam will convert to a NULL pointer later */
+ Py_INCREF(value);
+ return value;
+ }
+
+ typedict = PyType_stgdict(type);
+ assert(typedict); /* Cannot be NULL for pointer types */
+
+ /* If we expect POINTER(<type>), but receive a <type> instance, accept
+ it by calling byref(<type>).
+ */
+ switch (PyObject_IsInstance(value, typedict->proto)) {
+ case 1:
+ Py_INCREF(value); /* _byref steals a refcount */
+ return _byref(value);
+ case -1:
+ PyErr_Clear();
+ break;
+ default:
+ break;
+ }
+
+ if (PointerObject_Check(value) || ArrayObject_Check(value)) {
+ /* Array instances are also pointers when
+ the item types are the same.
+ */
+ StgDictObject *v = PyObject_stgdict(value);
+ assert(v); /* Cannot be NULL for pointer or array objects */
+ if (PyObject_IsSubclass(v->proto, typedict->proto)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+ return CDataType_from_param(type, value);
}
static PyMethodDef PyCPointerType_methods[] = {
- { "from_address", CDataType_from_address, METH_O, from_address_doc },
- { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
- { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
- { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
- { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc},
- { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O },
- { NULL, NULL },
+ { "from_address", CDataType_from_address, METH_O, from_address_doc },
+ { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
+ { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
+ { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
+ { "from_param", (PyCFunction)PyCPointerType_from_param, METH_O, from_param_doc},
+ { "set_type", (PyCFunction)PyCPointerType_set_type, METH_O },
+ { NULL, NULL },
};
PyTypeObject PyCPointerType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCPointerType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for the Pointer Objects", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyCPointerType_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 */
- PyCPointerType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCPointerType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for the Pointer Objects", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyCPointerType_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 */
+ PyCPointerType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCArrayType_Type
@@ -1074,169 +1074,169 @@ PyTypeObject PyCPointerType_Type = {
static int
CharArray_set_raw(CDataObject *self, PyObject *value)
{
- char *ptr;
- Py_ssize_t size;
+ char *ptr;
+ Py_ssize_t size;
#if (PY_VERSION_HEX >= 0x02060000)
- Py_buffer view = { 0 };
+ Py_buffer view = { 0 };
#endif
- if (PyBuffer_Check(value)) {
- size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
- if (size < 0)
- goto fail;
- } else {
+ if (PyBuffer_Check(value)) {
+ size = Py_TYPE(value)->tp_as_buffer->bf_getreadbuffer(value, 0, (void *)&ptr);
+ if (size < 0)
+ goto fail;
+ } else {
#if (PY_VERSION_HEX >= 0x02060000)
- if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
- goto fail;
- size = view.len;
- ptr = view.buf;
+ if (PyObject_GetBuffer(value, &view, PyBUF_SIMPLE) < 0)
+ goto fail;
+ size = view.len;
+ ptr = view.buf;
#else
- if (-1 == PyString_AsStringAndSize(value, &ptr, &size))
- goto fail;
+ if (-1 == PyString_AsStringAndSize(value, &ptr, &size))
+ goto fail;
#endif
- }
- if (size > self->b_size) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- goto fail;
- }
+ }
+ if (size > self->b_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ goto fail;
+ }
- memcpy(self->b_ptr, ptr, size);
+ memcpy(self->b_ptr, ptr, size);
#if (PY_VERSION_HEX >= 0x02060000)
- PyBuffer_Release(&view);
+ PyBuffer_Release(&view);
#endif
- return 0;
+ return 0;
fail:
#if (PY_VERSION_HEX >= 0x02060000)
- PyBuffer_Release(&view);
+ PyBuffer_Release(&view);
#endif
- return -1;
+ return -1;
}
static PyObject *
CharArray_get_raw(CDataObject *self)
{
- return PyString_FromStringAndSize(self->b_ptr, self->b_size);
+ return PyString_FromStringAndSize(self->b_ptr, self->b_size);
}
static PyObject *
CharArray_get_value(CDataObject *self)
{
- int i;
- char *ptr = self->b_ptr;
- for (i = 0; i < self->b_size; ++i)
- if (*ptr++ == '\0')
- break;
- return PyString_FromStringAndSize(self->b_ptr, i);
+ int i;
+ char *ptr = self->b_ptr;
+ for (i = 0; i < self->b_size; ++i)
+ if (*ptr++ == '\0')
+ break;
+ return PyString_FromStringAndSize(self->b_ptr, i);
}
static int
CharArray_set_value(CDataObject *self, PyObject *value)
{
- char *ptr;
- Py_ssize_t size;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
-
- if (PyUnicode_Check(value)) {
- value = PyUnicode_AsEncodedString(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return -1;
- } else if (!PyString_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "string expected instead of %s instance",
- Py_TYPE(value)->tp_name);
- return -1;
- } else
- Py_INCREF(value);
- size = PyString_GET_SIZE(value);
- if (size > self->b_size) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- Py_DECREF(value);
- return -1;
- }
-
- ptr = PyString_AS_STRING(value);
- memcpy(self->b_ptr, ptr, size);
- if (size < self->b_size)
- self->b_ptr[size] = '\0';
- Py_DECREF(value);
-
- return 0;
+ char *ptr;
+ Py_ssize_t size;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+
+ if (PyUnicode_Check(value)) {
+ value = PyUnicode_AsEncodedString(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return -1;
+ } else if (!PyString_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "string expected instead of %s instance",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ } else
+ Py_INCREF(value);
+ size = PyString_GET_SIZE(value);
+ if (size > self->b_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ Py_DECREF(value);
+ return -1;
+ }
+
+ ptr = PyString_AS_STRING(value);
+ memcpy(self->b_ptr, ptr, size);
+ if (size < self->b_size)
+ self->b_ptr[size] = '\0';
+ Py_DECREF(value);
+
+ return 0;
}
static PyGetSetDef CharArray_getsets[] = {
- { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
- "value", NULL },
- { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
- "string value"},
- { NULL, NULL }
+ { "raw", (getter)CharArray_get_raw, (setter)CharArray_set_raw,
+ "value", NULL },
+ { "value", (getter)CharArray_get_value, (setter)CharArray_set_value,
+ "string value"},
+ { NULL, NULL }
};
#ifdef CTYPES_UNICODE
static PyObject *
WCharArray_get_value(CDataObject *self)
{
- unsigned int i;
- wchar_t *ptr = (wchar_t *)self->b_ptr;
- for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
- if (*ptr++ == (wchar_t)0)
- break;
- return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
+ unsigned int i;
+ wchar_t *ptr = (wchar_t *)self->b_ptr;
+ for (i = 0; i < self->b_size/sizeof(wchar_t); ++i)
+ if (*ptr++ == (wchar_t)0)
+ break;
+ return PyUnicode_FromWideChar((wchar_t *)self->b_ptr, i);
}
static int
WCharArray_set_value(CDataObject *self, PyObject *value)
{
- Py_ssize_t result = 0;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
- if (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return -1;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- Py_TYPE(value)->tp_name);
- return -1;
- } else
- Py_INCREF(value);
- if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
- PyErr_SetString(PyExc_ValueError,
- "string too long");
- result = -1;
- goto done;
- }
- result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
- (wchar_t *)self->b_ptr,
- self->b_size/sizeof(wchar_t));
- if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
- ((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
+ Py_ssize_t result = 0;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return -1;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ } else
+ Py_INCREF(value);
+ if ((unsigned)PyUnicode_GET_SIZE(value) > self->b_size/sizeof(wchar_t)) {
+ PyErr_SetString(PyExc_ValueError,
+ "string too long");
+ result = -1;
+ goto done;
+ }
+ result = PyUnicode_AsWideChar((PyUnicodeObject *)value,
+ (wchar_t *)self->b_ptr,
+ self->b_size/sizeof(wchar_t));
+ if (result >= 0 && (size_t)result < self->b_size/sizeof(wchar_t))
+ ((wchar_t *)self->b_ptr)[result] = (wchar_t)0;
done:
- Py_DECREF(value);
+ Py_DECREF(value);
- return result >= 0 ? 0 : -1;
+ return result >= 0 ? 0 : -1;
}
static PyGetSetDef WCharArray_getsets[] = {
- { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
- "string value"},
- { NULL, NULL }
+ { "value", (getter)WCharArray_get_value, (setter)WCharArray_set_value,
+ "string value"},
+ { NULL, NULL }
};
#endif
@@ -1251,231 +1251,231 @@ static PyGetSetDef WCharArray_getsets[] = {
static int
add_methods(PyTypeObject *type, PyMethodDef *meth)
{
- PyObject *dict = type->tp_dict;
- for (; meth->ml_name != NULL; meth++) {
- PyObject *descr;
- descr = PyDescr_NewMethod(type, meth);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ for (; meth->ml_name != NULL; meth++) {
+ PyObject *descr;
+ descr = PyDescr_NewMethod(type, meth);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict,meth->ml_name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
static int
add_members(PyTypeObject *type, PyMemberDef *memb)
{
- PyObject *dict = type->tp_dict;
- for (; memb->name != NULL; memb++) {
- PyObject *descr;
- descr = PyDescr_NewMember(type, memb);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, memb->name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ for (; memb->name != NULL; memb++) {
+ PyObject *descr;
+ descr = PyDescr_NewMember(type, memb);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, memb->name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
*/
static int
add_getset(PyTypeObject *type, PyGetSetDef *gsp)
{
- PyObject *dict = type->tp_dict;
- for (; gsp->name != NULL; gsp++) {
- PyObject *descr;
- descr = PyDescr_NewGetSet(type, gsp);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ for (; gsp->name != NULL; gsp++) {
+ PyObject *descr;
+ descr = PyDescr_NewGetSet(type, gsp);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
static PyCArgObject *
PyCArrayType_paramfunc(CDataObject *self)
{
- PyCArgObject *p = PyCArgObject_new();
- if (p == NULL)
- return NULL;
- p->tag = 'P';
- p->pffi_type = &ffi_type_pointer;
- p->value.p = (char *)self->b_ptr;
- Py_INCREF(self);
- p->obj = (PyObject *)self;
- return p;
+ PyCArgObject *p = PyCArgObject_new();
+ if (p == NULL)
+ return NULL;
+ p->tag = 'P';
+ p->pffi_type = &ffi_type_pointer;
+ p->value.p = (char *)self->b_ptr;
+ Py_INCREF(self);
+ p->obj = (PyObject *)self;
+ return p;
}
static PyObject *
PyCArrayType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- StgDictObject *itemdict;
- PyObject *proto;
- PyObject *typedict;
- long length;
-
- Py_ssize_t itemsize, itemalign;
- char buf[32];
-
- typedict = PyTuple_GetItem(args, 2);
- if (!typedict)
- return NULL;
-
- proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
- if (!proto || !PyInt_Check(proto)) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_length_' attribute, "
- "which must be a positive integer");
- return NULL;
- }
- length = PyInt_AS_LONG(proto);
-
- proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
- if (!proto) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_type_' attribute");
- return NULL;
- }
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- return NULL;
-
- itemdict = PyType_stgdict(proto);
- if (!itemdict) {
- PyErr_SetString(PyExc_TypeError,
- "_type_ must have storage info");
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- assert(itemdict->format);
- if (itemdict->format[0] == '(') {
- sprintf(buf, "(%ld,", length);
- stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1);
- } else {
- sprintf(buf, "(%ld)", length);
- stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format);
- }
- if (stgdict->format == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- stgdict->ndim = itemdict->ndim + 1;
- stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim);
- if (stgdict->shape == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- stgdict->shape[0] = length;
- memmove(&stgdict->shape[1], itemdict->shape,
- sizeof(Py_ssize_t) * (stgdict->ndim - 1));
-
- itemsize = itemdict->size;
- if (length * itemsize < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "array too large");
- return NULL;
- }
-
- itemalign = itemdict->align;
-
- if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
- stgdict->flags |= TYPEFLAG_HASPOINTER;
-
- stgdict->size = itemsize * length;
- stgdict->align = itemalign;
- stgdict->length = length;
- Py_INCREF(proto);
- stgdict->proto = proto;
-
- stgdict->paramfunc = &PyCArrayType_paramfunc;
-
- /* Arrays are passed as pointers to function calls. */
- stgdict->ffi_type_pointer = ffi_type_pointer;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL)
- return NULL;
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- /* Special case for character arrays.
- A permanent annoyance: char arrays are also strings!
- */
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- if (-1 == add_getset(result, CharArray_getsets))
- return NULL;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ StgDictObject *itemdict;
+ PyObject *proto;
+ PyObject *typedict;
+ long length;
+
+ Py_ssize_t itemsize, itemalign;
+ char buf[32];
+
+ typedict = PyTuple_GetItem(args, 2);
+ if (!typedict)
+ return NULL;
+
+ proto = PyDict_GetItemString(typedict, "_length_"); /* Borrowed ref */
+ if (!proto || !PyInt_Check(proto)) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_length_' attribute, "
+ "which must be a positive integer");
+ return NULL;
+ }
+ length = PyInt_AS_LONG(proto);
+
+ proto = PyDict_GetItemString(typedict, "_type_"); /* Borrowed ref */
+ if (!proto) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_type_' attribute");
+ return NULL;
+ }
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+
+ itemdict = PyType_stgdict(proto);
+ if (!itemdict) {
+ PyErr_SetString(PyExc_TypeError,
+ "_type_ must have storage info");
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ assert(itemdict->format);
+ if (itemdict->format[0] == '(') {
+ sprintf(buf, "(%ld,", length);
+ stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format+1);
+ } else {
+ sprintf(buf, "(%ld)", length);
+ stgdict->format = _ctypes_alloc_format_string(buf, itemdict->format);
+ }
+ if (stgdict->format == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ stgdict->ndim = itemdict->ndim + 1;
+ stgdict->shape = PyMem_Malloc(sizeof(Py_ssize_t *) * stgdict->ndim);
+ if (stgdict->shape == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ stgdict->shape[0] = length;
+ memmove(&stgdict->shape[1], itemdict->shape,
+ sizeof(Py_ssize_t) * (stgdict->ndim - 1));
+
+ itemsize = itemdict->size;
+ if (length * itemsize < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "array too large");
+ return NULL;
+ }
+
+ itemalign = itemdict->align;
+
+ if (itemdict->flags & (TYPEFLAG_ISPOINTER | TYPEFLAG_HASPOINTER))
+ stgdict->flags |= TYPEFLAG_HASPOINTER;
+
+ stgdict->size = itemsize * length;
+ stgdict->align = itemalign;
+ stgdict->length = length;
+ Py_INCREF(proto);
+ stgdict->proto = proto;
+
+ stgdict->paramfunc = &PyCArrayType_paramfunc;
+
+ /* Arrays are passed as pointers to function calls. */
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL)
+ return NULL;
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ /* Special case for character arrays.
+ A permanent annoyance: char arrays are also strings!
+ */
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ if (-1 == add_getset(result, CharArray_getsets))
+ return NULL;
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- if (-1 == add_getset(result, WCharArray_getsets))
- return NULL;
+ } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ if (-1 == add_getset(result, WCharArray_getsets))
+ return NULL;
#endif
- }
+ }
- return (PyObject *)result;
+ return (PyObject *)result;
}
PyTypeObject PyCArrayType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCArrayType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 */
- "metatype for the Array Objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_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 */
- PyCArrayType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCArrayType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 */
+ "metatype for the Array Objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_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 */
+ PyCArrayType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCSimpleType_Type
@@ -1492,264 +1492,264 @@ static char *SIMPLE_TYPE_CHARS = "cbBhHiIlLdfuzZqQPXOv?g";
static PyObject *
c_wchar_p_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
+ PyObject *as_parameter;
#if (PYTHON_API_VERSION < 1012)
# error not supported
#endif
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyUnicode_Check(value) || PyString_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("Z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'Z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
- if (PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
- if (ArrayObject_Check(value) || PointerObject_Check(value)) {
- /* c_wchar array instance or pointer(c_wchar(...)) */
- StgDictObject *dt = PyObject_stgdict(value);
- StgDictObject *dict;
- assert(dt); /* Cannot be NULL for pointer or array objects */
- dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
- if (PyCArg_CheckExact(value)) {
- /* byref(c_char(...)) */
- PyCArgObject *a = (PyCArgObject *)value;
- StgDictObject *dict = PyObject_stgdict(a->obj);
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = c_wchar_p_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- /* XXX better message */
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyUnicode_Check(value) || PyString_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("Z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'Z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
+ if (PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ if (ArrayObject_Check(value) || PointerObject_Check(value)) {
+ /* c_wchar array instance or pointer(c_wchar(...)) */
+ StgDictObject *dt = PyObject_stgdict(value);
+ StgDictObject *dict;
+ assert(dt); /* Cannot be NULL for pointer or array objects */
+ dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+ if (PyCArg_CheckExact(value)) {
+ /* byref(c_char(...)) */
+ PyCArgObject *a = (PyCArgObject *)value;
+ StgDictObject *dict = PyObject_stgdict(a->obj);
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("u")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = c_wchar_p_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ /* XXX better message */
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyObject *
c_char_p_from_param(PyObject *type, PyObject *value)
{
- PyObject *as_parameter;
+ PyObject *as_parameter;
#if (PYTHON_API_VERSION < 1012)
# error not supported
#endif
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyString_Check(value) || PyUnicode_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
- if (PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
- if (ArrayObject_Check(value) || PointerObject_Check(value)) {
- /* c_char array instance or pointer(c_char(...)) */
- StgDictObject *dt = PyObject_stgdict(value);
- StgDictObject *dict;
- assert(dt); /* Cannot be NULL for pointer or array objects */
- dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
- if (PyCArg_CheckExact(value)) {
- /* byref(c_char(...)) */
- PyCArgObject *a = (PyCArgObject *)value;
- StgDictObject *dict = PyObject_stgdict(a->obj);
- if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
- Py_INCREF(value);
- return value;
- }
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = c_char_p_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- /* XXX better message */
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyString_Check(value) || PyUnicode_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
+ if (PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+ if (ArrayObject_Check(value) || PointerObject_Check(value)) {
+ /* c_char array instance or pointer(c_char(...)) */
+ StgDictObject *dt = PyObject_stgdict(value);
+ StgDictObject *dict;
+ assert(dt); /* Cannot be NULL for pointer or array objects */
+ dict = dt && dt->proto ? PyType_stgdict(dt->proto) : NULL;
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+ if (PyCArg_CheckExact(value)) {
+ /* byref(c_char(...)) */
+ PyCArgObject *a = (PyCArgObject *)value;
+ StgDictObject *dict = PyObject_stgdict(a->obj);
+ if (dict && (dict->setfunc == _ctypes_get_fielddesc("c")->setfunc)) {
+ Py_INCREF(value);
+ return value;
+ }
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = c_char_p_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ /* XXX better message */
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyObject *
c_void_p_from_param(PyObject *type, PyObject *value)
{
- StgDictObject *stgd;
- PyObject *as_parameter;
+ StgDictObject *stgd;
+ PyObject *as_parameter;
#if (PYTHON_API_VERSION < 1012)
# error not supported
#endif
/* None */
- if (value == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- /* Should probably allow buffer interface as well */
+ if (value == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ /* Should probably allow buffer interface as well */
/* int, long */
- if (PyInt_Check(value) || PyLong_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("P");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'P';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
+ if (PyInt_Check(value) || PyLong_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("P");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'P';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
/* string */
- if (PyString_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
+ if (PyString_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
/* unicode */
- if (PyUnicode_Check(value)) {
- PyCArgObject *parg;
- struct fielddesc *fd = _ctypes_get_fielddesc("Z");
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'Z';
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj == NULL) {
- Py_DECREF(parg);
- return NULL;
- }
- return (PyObject *)parg;
- }
+ if (PyUnicode_Check(value)) {
+ PyCArgObject *parg;
+ struct fielddesc *fd = _ctypes_get_fielddesc("Z");
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'Z';
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj == NULL) {
+ Py_DECREF(parg);
+ return NULL;
+ }
+ return (PyObject *)parg;
+ }
/* c_void_p instance (or subclass) */
- if (PyObject_IsInstance(value, type)) {
- /* c_void_p instances */
- Py_INCREF(value);
- return value;
- }
+ if (PyObject_IsInstance(value, type)) {
+ /* c_void_p instances */
+ Py_INCREF(value);
+ return value;
+ }
/* ctypes array or pointer instance */
- if (ArrayObject_Check(value) || PointerObject_Check(value)) {
- /* Any array or pointer is accepted */
- Py_INCREF(value);
- return value;
- }
+ if (ArrayObject_Check(value) || PointerObject_Check(value)) {
+ /* Any array or pointer is accepted */
+ Py_INCREF(value);
+ return value;
+ }
/* byref(...) */
- if (PyCArg_CheckExact(value)) {
- /* byref(c_xxx()) */
- PyCArgObject *a = (PyCArgObject *)value;
- if (a->tag == 'P') {
- Py_INCREF(value);
- return value;
- }
- }
+ if (PyCArg_CheckExact(value)) {
+ /* byref(c_xxx()) */
+ PyCArgObject *a = (PyCArgObject *)value;
+ if (a->tag == 'P') {
+ Py_INCREF(value);
+ return value;
+ }
+ }
/* function pointer */
- if (PyCFuncPtrObject_Check(value)) {
- PyCArgObject *parg;
- PyCFuncPtrObject *func;
- func = (PyCFuncPtrObject *)value;
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'P';
- Py_INCREF(value);
- parg->value.p = *(void **)func->b_ptr;
- parg->obj = value;
- return (PyObject *)parg;
- }
+ if (PyCFuncPtrObject_Check(value)) {
+ PyCArgObject *parg;
+ PyCFuncPtrObject *func;
+ func = (PyCFuncPtrObject *)value;
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'P';
+ Py_INCREF(value);
+ parg->value.p = *(void **)func->b_ptr;
+ parg->obj = value;
+ return (PyObject *)parg;
+ }
/* c_char_p, c_wchar_p */
- stgd = PyObject_stgdict(value);
- if (stgd && CDataObject_Check(value) && stgd->proto && PyString_Check(stgd->proto)) {
- PyCArgObject *parg;
-
- switch (PyString_AS_STRING(stgd->proto)[0]) {
- case 'z': /* c_char_p */
- case 'Z': /* c_wchar_p */
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
- parg->pffi_type = &ffi_type_pointer;
- parg->tag = 'Z';
- Py_INCREF(value);
- parg->obj = value;
- /* Remember: b_ptr points to where the pointer is stored! */
- parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
- return (PyObject *)parg;
- }
- }
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = c_void_p_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- /* XXX better message */
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ stgd = PyObject_stgdict(value);
+ if (stgd && CDataObject_Check(value) && stgd->proto && PyString_Check(stgd->proto)) {
+ PyCArgObject *parg;
+
+ switch (PyString_AS_STRING(stgd->proto)[0]) {
+ case 'z': /* c_char_p */
+ case 'Z': /* c_wchar_p */
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+ parg->pffi_type = &ffi_type_pointer;
+ parg->tag = 'Z';
+ Py_INCREF(value);
+ parg->obj = value;
+ /* Remember: b_ptr points to where the pointer is stored! */
+ parg->value.p = *(void **)(((CDataObject *)value)->b_ptr);
+ return (PyObject *)parg;
+ }
+ }
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = c_void_p_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ /* XXX better message */
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
#if (PYTHON_API_VERSION >= 1012)
@@ -1766,291 +1766,291 @@ static PyMethodDef c_wchar_p_method = { "from_param", c_wchar_p_from_param, METH
#endif
static PyObject *CreateSwappedType(PyTypeObject *type, PyObject *args, PyObject *kwds,
- PyObject *proto, struct fielddesc *fmt)
+ PyObject *proto, struct fielddesc *fmt)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- PyObject *name = PyTuple_GET_ITEM(args, 0);
- PyObject *swapped_args;
- static PyObject *suffix;
- Py_ssize_t i;
-
- swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
- if (!swapped_args)
- return NULL;
-
- if (suffix == NULL)
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ PyObject *name = PyTuple_GET_ITEM(args, 0);
+ PyObject *swapped_args;
+ static PyObject *suffix;
+ Py_ssize_t i;
+
+ swapped_args = PyTuple_New(PyTuple_GET_SIZE(args));
+ if (!swapped_args)
+ return NULL;
+
+ if (suffix == NULL)
#ifdef WORDS_BIGENDIAN
- suffix = PyString_InternFromString("_le");
+ suffix = PyString_InternFromString("_le");
#else
- suffix = PyString_InternFromString("_be");
+ suffix = PyString_InternFromString("_be");
#endif
- Py_INCREF(name);
- PyString_Concat(&name, suffix);
- if (name == NULL)
- return NULL;
-
- PyTuple_SET_ITEM(swapped_args, 0, name);
- for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
- PyObject *v = PyTuple_GET_ITEM(args, i);
- Py_INCREF(v);
- PyTuple_SET_ITEM(swapped_args, i, v);
- }
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
- Py_DECREF(swapped_args);
- if (result == NULL)
- return NULL;
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict) /* XXX leaks result! */
- return NULL;
-
- stgdict->ffi_type_pointer = *fmt->pffi_type;
- stgdict->align = fmt->pffi_type->alignment;
- stgdict->length = 0;
- stgdict->size = fmt->pffi_type->size;
- stgdict->setfunc = fmt->setfunc_swapped;
- stgdict->getfunc = fmt->getfunc_swapped;
-
- Py_INCREF(proto);
- stgdict->proto = proto;
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- return (PyObject *)result;
+ Py_INCREF(name);
+ PyString_Concat(&name, suffix);
+ if (name == NULL)
+ return NULL;
+
+ PyTuple_SET_ITEM(swapped_args, 0, name);
+ for (i=1; i<PyTuple_GET_SIZE(args); ++i) {
+ PyObject *v = PyTuple_GET_ITEM(args, i);
+ Py_INCREF(v);
+ PyTuple_SET_ITEM(swapped_args, i, v);
+ }
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, swapped_args, kwds);
+ Py_DECREF(swapped_args);
+ if (result == NULL)
+ return NULL;
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict) /* XXX leaks result! */
+ return NULL;
+
+ stgdict->ffi_type_pointer = *fmt->pffi_type;
+ stgdict->align = fmt->pffi_type->alignment;
+ stgdict->length = 0;
+ stgdict->size = fmt->pffi_type->size;
+ stgdict->setfunc = fmt->setfunc_swapped;
+ stgdict->getfunc = fmt->getfunc_swapped;
+
+ Py_INCREF(proto);
+ stgdict->proto = proto;
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ return (PyObject *)result;
}
static PyCArgObject *
PyCSimpleType_paramfunc(CDataObject *self)
{
- StgDictObject *dict;
- char *fmt;
- PyCArgObject *parg;
- struct fielddesc *fd;
-
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CDataObject instances */
- fmt = PyString_AsString(dict->proto);
- assert(fmt);
-
- fd = _ctypes_get_fielddesc(fmt);
- assert(fd);
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = fmt[0];
- parg->pffi_type = fd->pffi_type;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- memcpy(&parg->value, self->b_ptr, self->b_size);
- return parg;
+ StgDictObject *dict;
+ char *fmt;
+ PyCArgObject *parg;
+ struct fielddesc *fd;
+
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ fmt = PyString_AsString(dict->proto);
+ assert(fmt);
+
+ fd = _ctypes_get_fielddesc(fmt);
+ assert(fd);
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = fmt[0];
+ parg->pffi_type = fd->pffi_type;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ memcpy(&parg->value, self->b_ptr, self->b_size);
+ return parg;
}
static PyObject *
PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
- PyObject *proto;
- const char *proto_str;
- Py_ssize_t proto_len;
- PyMethodDef *ml;
- struct fielddesc *fmt;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL)
- return NULL;
-
- proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
- if (!proto) {
- PyErr_SetString(PyExc_AttributeError,
- "class must define a '_type_' attribute");
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+ PyObject *proto;
+ const char *proto_str;
+ Py_ssize_t proto_len;
+ PyMethodDef *ml;
+ struct fielddesc *fmt;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL)
+ return NULL;
+
+ proto = PyObject_GetAttrString((PyObject *)result, "_type_"); /* new ref */
+ if (!proto) {
+ PyErr_SetString(PyExc_AttributeError,
+ "class must define a '_type_' attribute");
error:
- Py_XDECREF(proto);
- Py_XDECREF(result);
- return NULL;
- }
- if (PyString_Check(proto)) {
- proto_str = PyString_AS_STRING(proto);
- proto_len = PyString_GET_SIZE(proto);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "class must define a '_type_' string attribute");
- goto error;
- }
- if (proto_len != 1) {
- PyErr_SetString(PyExc_ValueError,
- "class must define a '_type_' attribute "
- "which must be a string of length 1");
- goto error;
- }
- if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
- PyErr_Format(PyExc_AttributeError,
- "class must define a '_type_' attribute which must be\n"
- "a single character string containing one of '%s'.",
- SIMPLE_TYPE_CHARS);
- goto error;
- }
- fmt = _ctypes_get_fielddesc(PyString_AS_STRING(proto));
- if (fmt == NULL) {
- PyErr_Format(PyExc_ValueError,
- "_type_ '%s' not supported",
- PyString_AS_STRING(proto));
- goto error;
- }
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- goto error;
-
- stgdict->ffi_type_pointer = *fmt->pffi_type;
- stgdict->align = fmt->pffi_type->alignment;
- stgdict->length = 0;
- stgdict->size = fmt->pffi_type->size;
- stgdict->setfunc = fmt->setfunc;
- stgdict->getfunc = fmt->getfunc;
+ Py_XDECREF(proto);
+ Py_XDECREF(result);
+ return NULL;
+ }
+ if (PyString_Check(proto)) {
+ proto_str = PyString_AS_STRING(proto);
+ proto_len = PyString_GET_SIZE(proto);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "class must define a '_type_' string attribute");
+ goto error;
+ }
+ if (proto_len != 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "class must define a '_type_' attribute "
+ "which must be a string of length 1");
+ goto error;
+ }
+ if (!strchr(SIMPLE_TYPE_CHARS, *proto_str)) {
+ PyErr_Format(PyExc_AttributeError,
+ "class must define a '_type_' attribute which must be\n"
+ "a single character string containing one of '%s'.",
+ SIMPLE_TYPE_CHARS);
+ goto error;
+ }
+ fmt = _ctypes_get_fielddesc(PyString_AS_STRING(proto));
+ if (fmt == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "_type_ '%s' not supported",
+ PyString_AS_STRING(proto));
+ goto error;
+ }
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ goto error;
+
+ stgdict->ffi_type_pointer = *fmt->pffi_type;
+ stgdict->align = fmt->pffi_type->alignment;
+ stgdict->length = 0;
+ stgdict->size = fmt->pffi_type->size;
+ stgdict->setfunc = fmt->setfunc;
+ stgdict->getfunc = fmt->getfunc;
#ifdef WORDS_BIGENDIAN
- stgdict->format = _ctypes_alloc_format_string(">", proto_str);
+ stgdict->format = _ctypes_alloc_format_string(">", proto_str);
#else
- stgdict->format = _ctypes_alloc_format_string("<", proto_str);
+ stgdict->format = _ctypes_alloc_format_string("<", proto_str);
#endif
- if (stgdict->format == NULL) {
- Py_DECREF(result);
- Py_DECREF(proto);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- stgdict->paramfunc = PyCSimpleType_paramfunc;
+ if (stgdict->format == NULL) {
+ Py_DECREF(result);
+ Py_DECREF(proto);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ stgdict->paramfunc = PyCSimpleType_paramfunc;
/*
- if (result->tp_base != &Simple_Type) {
- stgdict->setfunc = NULL;
- stgdict->getfunc = NULL;
- }
+ if (result->tp_base != &Simple_Type) {
+ stgdict->setfunc = NULL;
+ stgdict->getfunc = NULL;
+ }
*/
- /* This consumes the refcount on proto which we have */
- stgdict->proto = proto;
-
- /* replace the class dict by our updated spam dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- /* Install from_param class methods in ctypes base classes.
- Overrides the PyCSimpleType_from_param generic method.
- */
- if (result->tp_base == &Simple_Type) {
- switch (PyString_AS_STRING(proto)[0]) {
- case 'z': /* c_char_p */
- ml = &c_char_p_method;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- case 'Z': /* c_wchar_p */
- ml = &c_wchar_p_method;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- case 'P': /* c_void_p */
- ml = &c_void_p_method;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- case 's':
- case 'X':
- case 'O':
- ml = NULL;
- stgdict->flags |= TYPEFLAG_ISPOINTER;
- break;
- default:
- ml = NULL;
- break;
- }
-
- if (ml) {
+ /* This consumes the refcount on proto which we have */
+ stgdict->proto = proto;
+
+ /* replace the class dict by our updated spam dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ /* Install from_param class methods in ctypes base classes.
+ Overrides the PyCSimpleType_from_param generic method.
+ */
+ if (result->tp_base == &Simple_Type) {
+ switch (PyString_AS_STRING(proto)[0]) {
+ case 'z': /* c_char_p */
+ ml = &c_char_p_method;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ case 'Z': /* c_wchar_p */
+ ml = &c_wchar_p_method;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ case 'P': /* c_void_p */
+ ml = &c_void_p_method;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ case 's':
+ case 'X':
+ case 'O':
+ ml = NULL;
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+ break;
+ default:
+ ml = NULL;
+ break;
+ }
+
+ if (ml) {
#if (PYTHON_API_VERSION >= 1012)
- PyObject *meth;
- int x;
- meth = PyDescr_NewClassMethod(result, ml);
- if (!meth)
- return NULL;
+ PyObject *meth;
+ int x;
+ meth = PyDescr_NewClassMethod(result, ml);
+ if (!meth)
+ return NULL;
#else
#error
- PyObject *meth, *func;
- int x;
- func = PyCFunction_New(ml, NULL);
- if (!func)
- return NULL;
- meth = PyObject_CallFunctionObjArgs(
- (PyObject *)&PyClassMethod_Type,
- func, NULL);
- Py_DECREF(func);
- if (!meth) {
- return NULL;
- }
+ PyObject *meth, *func;
+ int x;
+ func = PyCFunction_New(ml, NULL);
+ if (!func)
+ return NULL;
+ meth = PyObject_CallFunctionObjArgs(
+ (PyObject *)&PyClassMethod_Type,
+ func, NULL);
+ Py_DECREF(func);
+ if (!meth) {
+ return NULL;
+ }
#endif
- x = PyDict_SetItemString(result->tp_dict,
- ml->ml_name,
- meth);
- Py_DECREF(meth);
- if (x == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- }
-
- if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) {
- PyObject *swapped = CreateSwappedType(type, args, kwds,
- proto, fmt);
- StgDictObject *sw_dict;
- if (swapped == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- sw_dict = PyType_stgdict(swapped);
+ x = PyDict_SetItemString(result->tp_dict,
+ ml->ml_name,
+ meth);
+ Py_DECREF(meth);
+ if (x == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ }
+
+ if (type == &PyCSimpleType_Type && fmt->setfunc_swapped && fmt->getfunc_swapped) {
+ PyObject *swapped = CreateSwappedType(type, args, kwds,
+ proto, fmt);
+ StgDictObject *sw_dict;
+ if (swapped == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ sw_dict = PyType_stgdict(swapped);
#ifdef WORDS_BIGENDIAN
- PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped);
- PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
- /* We are creating the type for the OTHER endian */
- sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_le__", swapped);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_be__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_be__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_le__", swapped);
+ /* We are creating the type for the OTHER endian */
+ sw_dict->format = _ctypes_alloc_format_string("<", stgdict->format+1);
#else
- PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped);
- PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
- PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
- /* We are creating the type for the OTHER endian */
- sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_be__", swapped);
+ PyObject_SetAttrString((PyObject *)result, "__ctype_le__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_le__", (PyObject *)result);
+ PyObject_SetAttrString(swapped, "__ctype_be__", swapped);
+ /* We are creating the type for the OTHER endian */
+ sw_dict->format = _ctypes_alloc_format_string(">", stgdict->format+1);
#endif
- Py_DECREF(swapped);
- if (PyErr_Occurred()) {
- Py_DECREF(result);
- return NULL;
- }
- };
-
- return (PyObject *)result;
+ Py_DECREF(swapped);
+ if (PyErr_Occurred()) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ };
+
+ return (PyObject *)result;
}
/*
@@ -2060,101 +2060,101 @@ PyCSimpleType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
PyCSimpleType_from_param(PyObject *type, PyObject *value)
{
- StgDictObject *dict;
- char *fmt;
- PyCArgObject *parg;
- struct fielddesc *fd;
- PyObject *as_parameter;
-
- /* If the value is already an instance of the requested type,
- we can use it as is */
- if (1 == PyObject_IsInstance(value, type)) {
- Py_INCREF(value);
- return value;
- }
-
- dict = PyType_stgdict(type);
- assert(dict);
-
- /* I think we can rely on this being a one-character string */
- fmt = PyString_AsString(dict->proto);
- assert(fmt);
-
- fd = _ctypes_get_fielddesc(fmt);
- assert(fd);
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = fmt[0];
- parg->pffi_type = fd->pffi_type;
- parg->obj = fd->setfunc(&parg->value, value, 0);
- if (parg->obj)
- return (PyObject *)parg;
- PyErr_Clear();
- Py_DECREF(parg);
-
- as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
- if (as_parameter) {
- value = PyCSimpleType_from_param(type, as_parameter);
- Py_DECREF(as_parameter);
- return value;
- }
- PyErr_SetString(PyExc_TypeError,
- "wrong type");
- return NULL;
+ StgDictObject *dict;
+ char *fmt;
+ PyCArgObject *parg;
+ struct fielddesc *fd;
+ PyObject *as_parameter;
+
+ /* If the value is already an instance of the requested type,
+ we can use it as is */
+ if (1 == PyObject_IsInstance(value, type)) {
+ Py_INCREF(value);
+ return value;
+ }
+
+ dict = PyType_stgdict(type);
+ assert(dict);
+
+ /* I think we can rely on this being a one-character string */
+ fmt = PyString_AsString(dict->proto);
+ assert(fmt);
+
+ fd = _ctypes_get_fielddesc(fmt);
+ assert(fd);
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = fmt[0];
+ parg->pffi_type = fd->pffi_type;
+ parg->obj = fd->setfunc(&parg->value, value, 0);
+ if (parg->obj)
+ return (PyObject *)parg;
+ PyErr_Clear();
+ Py_DECREF(parg);
+
+ as_parameter = PyObject_GetAttrString(value, "_as_parameter_");
+ if (as_parameter) {
+ value = PyCSimpleType_from_param(type, as_parameter);
+ Py_DECREF(as_parameter);
+ return value;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "wrong type");
+ return NULL;
}
static PyMethodDef PyCSimpleType_methods[] = {
- { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc },
- { "from_address", CDataType_from_address, METH_O, from_address_doc },
- { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
- { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
- { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
- { NULL, NULL },
+ { "from_param", PyCSimpleType_from_param, METH_O, from_param_doc },
+ { "from_address", CDataType_from_address, METH_O, from_address_doc },
+ { "from_buffer", CDataType_from_buffer, METH_VARARGS, from_buffer_doc, },
+ { "from_buffer_copy", CDataType_from_buffer_copy, METH_VARARGS, from_buffer_copy_doc, },
+ { "in_dll", CDataType_in_dll, METH_VARARGS, in_dll_doc},
+ { NULL, NULL },
};
PyTypeObject PyCSimpleType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCSimpleType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 */
- "metatype for the PyCSimpleType Objects", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyCSimpleType_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 */
- PyCSimpleType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCSimpleType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 */
+ "metatype for the PyCSimpleType Objects", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyCSimpleType_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 */
+ PyCSimpleType_new, /* tp_new */
+ 0, /* tp_free */
};
/******************************************************************/
@@ -2165,221 +2165,221 @@ PyTypeObject PyCSimpleType_Type = {
static PyObject *
converters_from_argtypes(PyObject *ob)
{
- PyObject *converters;
- Py_ssize_t i;
- Py_ssize_t nArgs;
-
- ob = PySequence_Tuple(ob); /* new reference */
- if (!ob) {
- PyErr_SetString(PyExc_TypeError,
- "_argtypes_ must be a sequence of types");
- return NULL;
- }
-
- nArgs = PyTuple_GET_SIZE(ob);
- converters = PyTuple_New(nArgs);
- if (!converters)
- return NULL;
-
- /* I have to check if this is correct. Using c_char, which has a size
- of 1, will be assumed to be pushed as only one byte!
- Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
- */
-
- for (i = 0; i < nArgs; ++i) {
- PyObject *tp = PyTuple_GET_ITEM(ob, i);
- PyObject *cnv = PyObject_GetAttrString(tp, "from_param");
- if (!cnv)
- goto argtypes_error_1;
- PyTuple_SET_ITEM(converters, i, cnv);
- }
- Py_DECREF(ob);
- return converters;
+ PyObject *converters;
+ Py_ssize_t i;
+ Py_ssize_t nArgs;
+
+ ob = PySequence_Tuple(ob); /* new reference */
+ if (!ob) {
+ PyErr_SetString(PyExc_TypeError,
+ "_argtypes_ must be a sequence of types");
+ return NULL;
+ }
+
+ nArgs = PyTuple_GET_SIZE(ob);
+ converters = PyTuple_New(nArgs);
+ if (!converters)
+ return NULL;
+
+ /* I have to check if this is correct. Using c_char, which has a size
+ of 1, will be assumed to be pushed as only one byte!
+ Aren't these promoted to integers by the C compiler and pushed as 4 bytes?
+ */
+
+ for (i = 0; i < nArgs; ++i) {
+ PyObject *tp = PyTuple_GET_ITEM(ob, i);
+ PyObject *cnv = PyObject_GetAttrString(tp, "from_param");
+ if (!cnv)
+ goto argtypes_error_1;
+ PyTuple_SET_ITEM(converters, i, cnv);
+ }
+ Py_DECREF(ob);
+ return converters;
argtypes_error_1:
- Py_XDECREF(converters);
- Py_DECREF(ob);
- PyErr_Format(PyExc_TypeError,
+ Py_XDECREF(converters);
+ Py_DECREF(ob);
+ PyErr_Format(PyExc_TypeError,
#if (PY_VERSION_HEX < 0x02050000)
- "item %d in _argtypes_ has no from_param method",
+ "item %d in _argtypes_ has no from_param method",
#else
- "item %zd in _argtypes_ has no from_param method",
+ "item %zd in _argtypes_ has no from_param method",
#endif
- i+1);
- return NULL;
+ i+1);
+ return NULL;
}
static int
make_funcptrtype_dict(StgDictObject *stgdict)
{
- PyObject *ob;
- PyObject *converters = NULL;
-
- stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
- stgdict->length = 1;
- stgdict->size = sizeof(void *);
- stgdict->setfunc = NULL;
- stgdict->getfunc = NULL;
- stgdict->ffi_type_pointer = ffi_type_pointer;
-
- ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
- if (!ob || !PyInt_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "class must define _flags_ which must be an integer");
- return -1;
- }
- stgdict->flags = PyInt_AS_LONG(ob) | TYPEFLAG_ISPOINTER;
-
- /* _argtypes_ is optional... */
- ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_");
- if (ob) {
- converters = converters_from_argtypes(ob);
- if (!converters)
- goto error;
- Py_INCREF(ob);
- stgdict->argtypes = ob;
- stgdict->converters = converters;
- }
-
- ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_");
- if (ob) {
- if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "_restype_ must be a type, a callable, or None");
- return -1;
- }
- Py_INCREF(ob);
- stgdict->restype = ob;
- stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_");
- if (stgdict->checker == NULL)
- PyErr_Clear();
- }
+ PyObject *ob;
+ PyObject *converters = NULL;
+
+ stgdict->align = _ctypes_get_fielddesc("P")->pffi_type->alignment;
+ stgdict->length = 1;
+ stgdict->size = sizeof(void *);
+ stgdict->setfunc = NULL;
+ stgdict->getfunc = NULL;
+ stgdict->ffi_type_pointer = ffi_type_pointer;
+
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_flags_");
+ if (!ob || !PyInt_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "class must define _flags_ which must be an integer");
+ return -1;
+ }
+ stgdict->flags = PyInt_AS_LONG(ob) | TYPEFLAG_ISPOINTER;
+
+ /* _argtypes_ is optional... */
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_argtypes_");
+ if (ob) {
+ converters = converters_from_argtypes(ob);
+ if (!converters)
+ goto error;
+ Py_INCREF(ob);
+ stgdict->argtypes = ob;
+ stgdict->converters = converters;
+ }
+
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_restype_");
+ if (ob) {
+ if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_restype_ must be a type, a callable, or None");
+ return -1;
+ }
+ Py_INCREF(ob);
+ stgdict->restype = ob;
+ stgdict->checker = PyObject_GetAttrString(ob, "_check_retval_");
+ if (stgdict->checker == NULL)
+ PyErr_Clear();
+ }
/* XXX later, maybe.
- ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
- if (ob) {
- if (!PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "_errcheck_ must be callable");
- return -1;
- }
- Py_INCREF(ob);
- stgdict->errcheck = ob;
- }
+ ob = PyDict_GetItemString((PyObject *)stgdict, "_errcheck_");
+ if (ob) {
+ if (!PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "_errcheck_ must be callable");
+ return -1;
+ }
+ Py_INCREF(ob);
+ stgdict->errcheck = ob;
+ }
*/
- return 0;
+ return 0;
error:
- Py_XDECREF(converters);
- return -1;
+ Py_XDECREF(converters);
+ return -1;
}
static PyCArgObject *
PyCFuncPtrType_paramfunc(CDataObject *self)
{
- PyCArgObject *parg;
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- Py_INCREF(self);
- parg->obj = (PyObject *)self;
- parg->value.p = *(void **)self->b_ptr;
- return parg;
+ PyCArgObject *parg;
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ Py_INCREF(self);
+ parg->obj = (PyObject *)self;
+ parg->value.p = *(void **)self->b_ptr;
+ return parg;
}
static PyObject *
PyCFuncPtrType_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyTypeObject *result;
- StgDictObject *stgdict;
-
- stgdict = (StgDictObject *)PyObject_CallObject(
- (PyObject *)&PyCStgDict_Type, NULL);
- if (!stgdict)
- return NULL;
-
- stgdict->paramfunc = PyCFuncPtrType_paramfunc;
- /* We do NOT expose the function signature in the format string. It
- is impossible, generally, because the only requirement for the
- argtypes items is that they have a .from_param method - we do not
- know the types of the arguments (although, in practice, most
- argtypes would be a ctypes type).
- */
- stgdict->format = _ctypes_alloc_format_string(NULL, "X{}");
- stgdict->flags |= TYPEFLAG_ISPOINTER;
-
- /* create the new instance (which is a class,
- since we are a metatype!) */
- result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
- if (result == NULL) {
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
-
- /* replace the class dict by our updated storage dict */
- if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
- Py_DECREF(result);
- Py_DECREF((PyObject *)stgdict);
- return NULL;
- }
- Py_DECREF(result->tp_dict);
- result->tp_dict = (PyObject *)stgdict;
-
- if (-1 == make_funcptrtype_dict(stgdict)) {
- Py_DECREF(result);
- return NULL;
- }
-
- return (PyObject *)result;
+ PyTypeObject *result;
+ StgDictObject *stgdict;
+
+ stgdict = (StgDictObject *)PyObject_CallObject(
+ (PyObject *)&PyCStgDict_Type, NULL);
+ if (!stgdict)
+ return NULL;
+
+ stgdict->paramfunc = PyCFuncPtrType_paramfunc;
+ /* We do NOT expose the function signature in the format string. It
+ is impossible, generally, because the only requirement for the
+ argtypes items is that they have a .from_param method - we do not
+ know the types of the arguments (although, in practice, most
+ argtypes would be a ctypes type).
+ */
+ stgdict->format = _ctypes_alloc_format_string(NULL, "X{}");
+ stgdict->flags |= TYPEFLAG_ISPOINTER;
+
+ /* create the new instance (which is a class,
+ since we are a metatype!) */
+ result = (PyTypeObject *)PyType_Type.tp_new(type, args, kwds);
+ if (result == NULL) {
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+
+ /* replace the class dict by our updated storage dict */
+ if (-1 == PyDict_Update((PyObject *)stgdict, result->tp_dict)) {
+ Py_DECREF(result);
+ Py_DECREF((PyObject *)stgdict);
+ return NULL;
+ }
+ Py_DECREF(result->tp_dict);
+ result->tp_dict = (PyObject *)stgdict;
+
+ if (-1 == make_funcptrtype_dict(stgdict)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return (PyObject *)result;
}
PyTypeObject PyCFuncPtrType_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCFuncPtrType", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- "metatype for C function pointers", /* tp_doc */
- (traverseproc)CDataType_traverse, /* tp_traverse */
- (inquiry)CDataType_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- CDataType_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 */
- PyCFuncPtrType_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCFuncPtrType", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &CDataType_as_sequence, /* 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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ "metatype for C function pointers", /* tp_doc */
+ (traverseproc)CDataType_traverse, /* tp_traverse */
+ (inquiry)CDataType_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ CDataType_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 */
+ PyCFuncPtrType_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/*****************************************************************
* Code to keep needed objects alive
*/
@@ -2387,54 +2387,54 @@ PyTypeObject PyCFuncPtrType_Type = {
static CDataObject *
PyCData_GetContainer(CDataObject *self)
{
- while (self->b_base)
- self = self->b_base;
- if (self->b_objects == NULL) {
- if (self->b_length) {
- self->b_objects = PyDict_New();
- } else {
- Py_INCREF(Py_None);
- self->b_objects = Py_None;
- }
- }
- return self;
+ while (self->b_base)
+ self = self->b_base;
+ if (self->b_objects == NULL) {
+ if (self->b_length) {
+ self->b_objects = PyDict_New();
+ } else {
+ Py_INCREF(Py_None);
+ self->b_objects = Py_None;
+ }
+ }
+ return self;
}
static PyObject *
GetKeepedObjects(CDataObject *target)
{
- return PyCData_GetContainer(target)->b_objects;
+ return PyCData_GetContainer(target)->b_objects;
}
static PyObject *
unique_key(CDataObject *target, Py_ssize_t index)
{
- char string[256];
- char *cp = string;
- size_t bytes_left;
+ char string[256];
+ char *cp = string;
+ size_t bytes_left;
- assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
+ assert(sizeof(string) - 1 > sizeof(Py_ssize_t) * 2);
#if (PY_VERSION_HEX < 0x02050000)
- cp += sprintf(cp, "%x", index);
+ cp += sprintf(cp, "%x", index);
#else
- cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
+ cp += sprintf(cp, "%x", Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
#endif
- while (target->b_base) {
- bytes_left = sizeof(string) - (cp - string) - 1;
- /* Hex format needs 2 characters per byte */
- if (bytes_left < sizeof(Py_ssize_t) * 2) {
- PyErr_SetString(PyExc_ValueError,
- "ctypes object structure too deep");
- return NULL;
- }
+ while (target->b_base) {
+ bytes_left = sizeof(string) - (cp - string) - 1;
+ /* Hex format needs 2 characters per byte */
+ if (bytes_left < sizeof(Py_ssize_t) * 2) {
+ PyErr_SetString(PyExc_ValueError,
+ "ctypes object structure too deep");
+ return NULL;
+ }
#if (PY_VERSION_HEX < 0x02050000)
- cp += sprintf(cp, ":%x", (int)target->b_index);
+ cp += sprintf(cp, ":%x", (int)target->b_index);
#else
- cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
+ cp += sprintf(cp, ":%x", Py_SAFE_DOWNCAST(target->b_index, Py_ssize_t, int));
#endif
- target = target->b_base;
- }
- return PyString_FromStringAndSize(string, cp-string);
+ target = target->b_base;
+ }
+ return PyString_FromStringAndSize(string, cp-string);
}
/*
@@ -2458,30 +2458,30 @@ unique_key(CDataObject *target, Py_ssize_t index)
static int
KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
{
- int result;
- CDataObject *ob;
- PyObject *key;
+ int result;
+ CDataObject *ob;
+ PyObject *key;
/* Optimization: no need to store None */
- if (keep == Py_None) {
- Py_DECREF(Py_None);
- return 0;
- }
- ob = PyCData_GetContainer(target);
- if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
- Py_XDECREF(ob->b_objects);
- ob->b_objects = keep; /* refcount consumed */
- return 0;
- }
- key = unique_key(target, index);
- if (key == NULL) {
- Py_DECREF(keep);
- return -1;
- }
- result = PyDict_SetItem(ob->b_objects, key, keep);
- Py_DECREF(key);
- Py_DECREF(keep);
- return result;
+ if (keep == Py_None) {
+ Py_DECREF(Py_None);
+ return 0;
+ }
+ ob = PyCData_GetContainer(target);
+ if (ob->b_objects == NULL || !PyDict_CheckExact(ob->b_objects)) {
+ Py_XDECREF(ob->b_objects);
+ ob->b_objects = keep; /* refcount consumed */
+ return 0;
+ }
+ key = unique_key(target, index);
+ if (key == NULL) {
+ Py_DECREF(keep);
+ return -1;
+ }
+ result = PyDict_SetItem(ob->b_objects, key, keep);
+ Py_DECREF(key);
+ Py_DECREF(keep);
+ return result;
}
/******************************************************************/
@@ -2491,100 +2491,100 @@ KeepRef(CDataObject *target, Py_ssize_t index, PyObject *keep)
static int
PyCData_traverse(CDataObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->b_objects);
- Py_VISIT((PyObject *)self->b_base);
- return 0;
+ Py_VISIT(self->b_objects);
+ Py_VISIT((PyObject *)self->b_base);
+ return 0;
}
static int
PyCData_clear(CDataObject *self)
{
- StgDictObject *dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CDataObject instances */
- Py_CLEAR(self->b_objects);
- if ((self->b_needsfree)
- && ((size_t)dict->size > sizeof(self->b_value)))
- PyMem_Free(self->b_ptr);
- self->b_ptr = NULL;
- Py_CLEAR(self->b_base);
- return 0;
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ Py_CLEAR(self->b_objects);
+ if ((self->b_needsfree)
+ && ((size_t)dict->size > sizeof(self->b_value)))
+ PyMem_Free(self->b_ptr);
+ self->b_ptr = NULL;
+ Py_CLEAR(self->b_base);
+ return 0;
}
static void
PyCData_dealloc(PyObject *self)
{
- PyCData_clear((CDataObject *)self);
- Py_TYPE(self)->tp_free(self);
+ PyCData_clear((CDataObject *)self);
+ Py_TYPE(self)->tp_free(self);
}
static PyMemberDef PyCData_members[] = {
- { "_b_base_", T_OBJECT,
- offsetof(CDataObject, b_base), READONLY,
- "the base object" },
- { "_b_needsfree_", T_INT,
- offsetof(CDataObject, b_needsfree), READONLY,
- "whether the object owns the memory or not" },
- { "_objects", T_OBJECT,
- offsetof(CDataObject, b_objects), READONLY,
- "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
- { NULL },
+ { "_b_base_", T_OBJECT,
+ offsetof(CDataObject, b_base), READONLY,
+ "the base object" },
+ { "_b_needsfree_", T_INT,
+ offsetof(CDataObject, b_needsfree), READONLY,
+ "whether the object owns the memory or not" },
+ { "_objects", T_OBJECT,
+ offsetof(CDataObject, b_objects), READONLY,
+ "internal objects tree (NEVER CHANGE THIS OBJECT!)"},
+ { NULL },
};
#if (PY_VERSION_HEX >= 0x02060000)
static int PyCData_NewGetBuffer(PyObject *_self, Py_buffer *view, int flags)
{
- CDataObject *self = (CDataObject *)_self;
- StgDictObject *dict = PyObject_stgdict(_self);
- Py_ssize_t i;
-
- if (view == NULL) return 0;
-
- view->buf = self->b_ptr;
- view->obj = _self;
- Py_INCREF(_self);
- view->len = self->b_size;
- view->readonly = 0;
- /* use default format character if not set */
- view->format = dict->format ? dict->format : "B";
- view->ndim = dict->ndim;
- view->shape = dict->shape;
- view->itemsize = self->b_size;
- for (i = 0; i < view->ndim; ++i) {
- view->itemsize /= dict->shape[i];
- }
- view->strides = NULL;
- view->suboffsets = NULL;
- view->internal = NULL;
- return 0;
+ CDataObject *self = (CDataObject *)_self;
+ StgDictObject *dict = PyObject_stgdict(_self);
+ Py_ssize_t i;
+
+ if (view == NULL) return 0;
+
+ view->buf = self->b_ptr;
+ view->obj = _self;
+ Py_INCREF(_self);
+ view->len = self->b_size;
+ view->readonly = 0;
+ /* use default format character if not set */
+ view->format = dict->format ? dict->format : "B";
+ view->ndim = dict->ndim;
+ view->shape = dict->shape;
+ view->itemsize = self->b_size;
+ for (i = 0; i < view->ndim; ++i) {
+ view->itemsize /= dict->shape[i];
+ }
+ view->strides = NULL;
+ view->suboffsets = NULL;
+ view->internal = NULL;
+ return 0;
}
#endif
static Py_ssize_t PyCData_GetSegcount(PyObject *_self, Py_ssize_t *lenp)
{
- if (lenp)
- *lenp = 1;
- return 1;
+ if (lenp)
+ *lenp = 1;
+ return 1;
}
static Py_ssize_t PyCData_GetBuffer(PyObject *_self, Py_ssize_t seg, void **pptr)
{
- CDataObject *self = (CDataObject *)_self;
- if (seg != 0) {
- /* Hm. Must this set an exception? */
- return -1;
- }
- *pptr = self->b_ptr;
- return self->b_size;
+ CDataObject *self = (CDataObject *)_self;
+ if (seg != 0) {
+ /* Hm. Must this set an exception? */
+ return -1;
+ }
+ *pptr = self->b_ptr;
+ return self->b_size;
}
static PyBufferProcs PyCData_as_buffer = {
- (readbufferproc)PyCData_GetBuffer,
- (writebufferproc)PyCData_GetBuffer,
- (segcountproc)PyCData_GetSegcount,
- (charbufferproc)NULL,
+ (readbufferproc)PyCData_GetBuffer,
+ (writebufferproc)PyCData_GetBuffer,
+ (segcountproc)PyCData_GetSegcount,
+ (charbufferproc)NULL,
#if (PY_VERSION_HEX >= 0x02060000)
- (getbufferproc)PyCData_NewGetBuffer,
- (releasebufferproc)NULL,
+ (getbufferproc)PyCData_NewGetBuffer,
+ (releasebufferproc)NULL,
#endif
};
@@ -2594,47 +2594,47 @@ static PyBufferProcs PyCData_as_buffer = {
static long
PyCData_nohash(PyObject *self)
{
- PyErr_SetString(PyExc_TypeError, "unhashable type");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "unhashable type");
+ return -1;
}
static PyObject *
PyCData_reduce(PyObject *_self, PyObject *args)
{
- CDataObject *self = (CDataObject *)_self;
-
- if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
- PyErr_SetString(PyExc_ValueError,
- "ctypes objects containing pointers cannot be pickled");
- return NULL;
- }
- return Py_BuildValue("O(O(NN))",
- _unpickle,
- Py_TYPE(_self),
- PyObject_GetAttrString(_self, "__dict__"),
- PyString_FromStringAndSize(self->b_ptr, self->b_size));
+ CDataObject *self = (CDataObject *)_self;
+
+ if (PyObject_stgdict(_self)->flags & (TYPEFLAG_ISPOINTER|TYPEFLAG_HASPOINTER)) {
+ PyErr_SetString(PyExc_ValueError,
+ "ctypes objects containing pointers cannot be pickled");
+ return NULL;
+ }
+ return Py_BuildValue("O(O(NN))",
+ _unpickle,
+ Py_TYPE(_self),
+ PyObject_GetAttrString(_self, "__dict__"),
+ PyString_FromStringAndSize(self->b_ptr, self->b_size));
}
static PyObject *
PyCData_setstate(PyObject *_self, PyObject *args)
{
- void *data;
- Py_ssize_t len;
- int res;
- PyObject *dict, *mydict;
- CDataObject *self = (CDataObject *)_self;
- if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len))
- return NULL;
- if (len > self->b_size)
- len = self->b_size;
- memmove(self->b_ptr, data, len);
- mydict = PyObject_GetAttrString(_self, "__dict__");
- res = PyDict_Update(mydict, dict);
- Py_DECREF(mydict);
- if (res == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ void *data;
+ Py_ssize_t len;
+ int res;
+ PyObject *dict, *mydict;
+ CDataObject *self = (CDataObject *)_self;
+ if (!PyArg_ParseTuple(args, "Os#", &dict, &data, &len))
+ return NULL;
+ if (len > self->b_size)
+ len = self->b_size;
+ memmove(self->b_ptr, data, len);
+ mydict = PyObject_GetAttrString(_self, "__dict__");
+ res = PyDict_Update(mydict, dict);
+ Py_DECREF(mydict);
+ if (res == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/*
@@ -2643,124 +2643,124 @@ PyCData_setstate(PyObject *_self, PyObject *args)
static PyObject *
PyCData_from_outparam(PyObject *self, PyObject *args)
{
- Py_INCREF(self);
- return self;
+ Py_INCREF(self);
+ return self;
}
static PyMethodDef PyCData_methods[] = {
- { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, },
- { "__reduce__", PyCData_reduce, METH_NOARGS, },
- { "__setstate__", PyCData_setstate, METH_VARARGS, },
- { NULL, NULL },
+ { "__ctypes_from_outparam__", PyCData_from_outparam, METH_NOARGS, },
+ { "__reduce__", PyCData_reduce, METH_NOARGS, },
+ { "__setstate__", PyCData_setstate, METH_VARARGS, },
+ { NULL, NULL },
};
PyTypeObject PyCData_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._CData",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- PyCData_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 */
- PyCData_nohash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyCData_methods, /* tp_methods */
- PyCData_members, /* 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 */
- 0, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes._CData",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ PyCData_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 */
+ PyCData_nohash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyCData_methods, /* tp_methods */
+ PyCData_members, /* 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 */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
static int PyCData_MallocBuffer(CDataObject *obj, StgDictObject *dict)
{
- if ((size_t)dict->size <= sizeof(obj->b_value)) {
- /* No need to call malloc, can use the default buffer */
- obj->b_ptr = (char *)&obj->b_value;
- /* The b_needsfree flag does not mean that we actually did
- call PyMem_Malloc to allocate the memory block; instead it
- means we are the *owner* of the memory and are responsible
- for freeing resources associated with the memory. This is
- also the reason that b_needsfree is exposed to Python.
- */
- obj->b_needsfree = 1;
- } else {
- /* In python 2.4, and ctypes 0.9.6, the malloc call took about
- 33% of the creation time for c_int().
- */
- obj->b_ptr = (char *)PyMem_Malloc(dict->size);
- if (obj->b_ptr == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- obj->b_needsfree = 1;
- memset(obj->b_ptr, 0, dict->size);
- }
- obj->b_size = dict->size;
- return 0;
+ if ((size_t)dict->size <= sizeof(obj->b_value)) {
+ /* No need to call malloc, can use the default buffer */
+ obj->b_ptr = (char *)&obj->b_value;
+ /* The b_needsfree flag does not mean that we actually did
+ call PyMem_Malloc to allocate the memory block; instead it
+ means we are the *owner* of the memory and are responsible
+ for freeing resources associated with the memory. This is
+ also the reason that b_needsfree is exposed to Python.
+ */
+ obj->b_needsfree = 1;
+ } else {
+ /* In python 2.4, and ctypes 0.9.6, the malloc call took about
+ 33% of the creation time for c_int().
+ */
+ obj->b_ptr = (char *)PyMem_Malloc(dict->size);
+ if (obj->b_ptr == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ obj->b_needsfree = 1;
+ memset(obj->b_ptr, 0, dict->size);
+ }
+ obj->b_size = dict->size;
+ return 0;
}
PyObject *
PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
{
- CDataObject *cmem;
- StgDictObject *dict;
-
- assert(PyType_Check(type));
- dict = PyType_stgdict(type);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "abstract class");
- return NULL;
- }
- dict->flags |= DICTFLAG_FINAL;
- cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
- if (cmem == NULL)
- return NULL;
- assert(CDataObject_Check(cmem));
-
- cmem->b_length = dict->length;
- cmem->b_size = dict->size;
- if (base) { /* use base's buffer */
- assert(CDataObject_Check(base));
- cmem->b_ptr = adr;
- cmem->b_needsfree = 0;
- Py_INCREF(base);
- cmem->b_base = (CDataObject *)base;
- cmem->b_index = index;
- } else { /* copy contents of adr */
- if (-1 == PyCData_MallocBuffer(cmem, dict)) {
- return NULL;
- Py_DECREF(cmem);
- }
- memcpy(cmem->b_ptr, adr, dict->size);
- cmem->b_index = index;
- }
- return (PyObject *)cmem;
+ CDataObject *cmem;
+ StgDictObject *dict;
+
+ assert(PyType_Check(type));
+ dict = PyType_stgdict(type);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "abstract class");
+ return NULL;
+ }
+ dict->flags |= DICTFLAG_FINAL;
+ cmem = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
+ if (cmem == NULL)
+ return NULL;
+ assert(CDataObject_Check(cmem));
+
+ cmem->b_length = dict->length;
+ cmem->b_size = dict->size;
+ if (base) { /* use base's buffer */
+ assert(CDataObject_Check(base));
+ cmem->b_ptr = adr;
+ cmem->b_needsfree = 0;
+ Py_INCREF(base);
+ cmem->b_base = (CDataObject *)base;
+ cmem->b_index = index;
+ } else { /* copy contents of adr */
+ if (-1 == PyCData_MallocBuffer(cmem, dict)) {
+ return NULL;
+ Py_DECREF(cmem);
+ }
+ memcpy(cmem->b_ptr, adr, dict->size);
+ cmem->b_index = index;
+ }
+ return (PyObject *)cmem;
}
/*
@@ -2769,26 +2769,26 @@ PyCData_FromBaseObj(PyObject *type, PyObject *base, Py_ssize_t index, char *adr)
PyObject *
PyCData_AtAddress(PyObject *type, void *buf)
{
- CDataObject *pd;
- StgDictObject *dict;
-
- assert(PyType_Check(type));
- dict = PyType_stgdict(type);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "abstract class");
- return NULL;
- }
- dict->flags |= DICTFLAG_FINAL;
-
- pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
- if (!pd)
- return NULL;
- assert(CDataObject_Check(pd));
- pd->b_ptr = (char *)buf;
- pd->b_length = dict->length;
- pd->b_size = dict->size;
- return (PyObject *)pd;
+ CDataObject *pd;
+ StgDictObject *dict;
+
+ assert(PyType_Check(type));
+ dict = PyType_stgdict(type);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "abstract class");
+ return NULL;
+ }
+ dict->flags |= DICTFLAG_FINAL;
+
+ pd = (CDataObject *)((PyTypeObject *)type)->tp_alloc((PyTypeObject *)type, 0);
+ if (!pd)
+ return NULL;
+ assert(CDataObject_Check(pd));
+ pd->b_ptr = (char *)buf;
+ pd->b_length = dict->length;
+ pd->b_size = dict->size;
+ return (PyObject *)pd;
}
/*
@@ -2798,25 +2798,25 @@ PyCData_AtAddress(PyObject *type, void *buf)
*/
int _ctypes_simple_instance(PyObject *obj)
{
- PyTypeObject *type = (PyTypeObject *)obj;
+ PyTypeObject *type = (PyTypeObject *)obj;
- if (PyCSimpleTypeObject_Check(type))
- return type->tp_base != &Simple_Type;
- return 0;
+ if (PyCSimpleTypeObject_Check(type))
+ return type->tp_base != &Simple_Type;
+ return 0;
}
PyObject *
PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
- Py_ssize_t index, Py_ssize_t size, char *adr)
+ Py_ssize_t index, Py_ssize_t size, char *adr)
{
- StgDictObject *dict;
- if (getfunc)
- return getfunc(adr, size);
- assert(type);
- dict = PyType_stgdict(type);
- if (dict && dict->getfunc && !_ctypes_simple_instance(type))
- return dict->getfunc(adr, size);
- return PyCData_FromBaseObj(type, src, index, adr);
+ StgDictObject *dict;
+ if (getfunc)
+ return getfunc(adr, size);
+ assert(type);
+ dict = PyType_stgdict(type);
+ if (dict && dict->getfunc && !_ctypes_simple_instance(type))
+ return dict->getfunc(adr, size);
+ return PyCData_FromBaseObj(type, src, index, adr);
}
/*
@@ -2824,96 +2824,96 @@ PyCData_get(PyObject *type, GETFUNC getfunc, PyObject *src,
*/
static PyObject *
_PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
- Py_ssize_t size, char *ptr)
+ Py_ssize_t size, char *ptr)
{
- CDataObject *src;
-
- if (setfunc)
- return setfunc(ptr, value, size);
-
- if (!CDataObject_Check(value)) {
- StgDictObject *dict = PyType_stgdict(type);
- if (dict && dict->setfunc)
- return dict->setfunc(ptr, value, size);
- /*
- If value is a tuple, we try to call the type with the tuple
- and use the result!
- */
- assert(PyType_Check(type));
- if (PyTuple_Check(value)) {
- PyObject *ob;
- PyObject *result;
- ob = PyObject_CallObject(type, value);
- if (ob == NULL) {
- _ctypes_extend_error(PyExc_RuntimeError, "(%s) ",
- ((PyTypeObject *)type)->tp_name);
- return NULL;
- }
- result = _PyCData_set(dst, type, setfunc, ob,
- size, ptr);
- Py_DECREF(ob);
- return result;
- } else if (value == Py_None && PyCPointerTypeObject_Check(type)) {
- *(void **)ptr = NULL;
- Py_INCREF(Py_None);
- return Py_None;
- } else {
- PyErr_Format(PyExc_TypeError,
- "expected %s instance, got %s",
- ((PyTypeObject *)type)->tp_name,
- Py_TYPE(value)->tp_name);
- return NULL;
- }
- }
- src = (CDataObject *)value;
-
- if (PyObject_IsInstance(value, type)) {
- memcpy(ptr,
- src->b_ptr,
- size);
-
- if (PyCPointerTypeObject_Check(type))
- /* XXX */;
-
- value = GetKeepedObjects(src);
- Py_INCREF(value);
- return value;
- }
-
- if (PyCPointerTypeObject_Check(type)
- && ArrayObject_Check(value)) {
- StgDictObject *p1, *p2;
- PyObject *keep;
- p1 = PyObject_stgdict(value);
- assert(p1); /* Cannot be NULL for array instances */
- p2 = PyType_stgdict(type);
- assert(p2); /* Cannot be NULL for pointer types */
-
- if (p1->proto != p2->proto) {
- PyErr_Format(PyExc_TypeError,
- "incompatible types, %s instance instead of %s instance",
- Py_TYPE(value)->tp_name,
- ((PyTypeObject *)type)->tp_name);
- return NULL;
- }
- *(void **)ptr = src->b_ptr;
-
- keep = GetKeepedObjects(src);
- /*
- We are assigning an array object to a field which represents
- a pointer. This has the same effect as converting an array
- into a pointer. So, again, we have to keep the whole object
- pointed to (which is the array in this case) alive, and not
- only it's object list. So we create a tuple, containing
- b_objects list PLUS the array itself, and return that!
- */
- return PyTuple_Pack(2, keep, value);
- }
- PyErr_Format(PyExc_TypeError,
- "incompatible types, %s instance instead of %s instance",
- Py_TYPE(value)->tp_name,
- ((PyTypeObject *)type)->tp_name);
- return NULL;
+ CDataObject *src;
+
+ if (setfunc)
+ return setfunc(ptr, value, size);
+
+ if (!CDataObject_Check(value)) {
+ StgDictObject *dict = PyType_stgdict(type);
+ if (dict && dict->setfunc)
+ return dict->setfunc(ptr, value, size);
+ /*
+ If value is a tuple, we try to call the type with the tuple
+ and use the result!
+ */
+ assert(PyType_Check(type));
+ if (PyTuple_Check(value)) {
+ PyObject *ob;
+ PyObject *result;
+ ob = PyObject_CallObject(type, value);
+ if (ob == NULL) {
+ _ctypes_extend_error(PyExc_RuntimeError, "(%s) ",
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
+ }
+ result = _PyCData_set(dst, type, setfunc, ob,
+ size, ptr);
+ Py_DECREF(ob);
+ return result;
+ } else if (value == Py_None && PyCPointerTypeObject_Check(type)) {
+ *(void **)ptr = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
+ } else {
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instance, got %s",
+ ((PyTypeObject *)type)->tp_name,
+ Py_TYPE(value)->tp_name);
+ return NULL;
+ }
+ }
+ src = (CDataObject *)value;
+
+ if (PyObject_IsInstance(value, type)) {
+ memcpy(ptr,
+ src->b_ptr,
+ size);
+
+ if (PyCPointerTypeObject_Check(type))
+ /* XXX */;
+
+ value = GetKeepedObjects(src);
+ Py_INCREF(value);
+ return value;
+ }
+
+ if (PyCPointerTypeObject_Check(type)
+ && ArrayObject_Check(value)) {
+ StgDictObject *p1, *p2;
+ PyObject *keep;
+ p1 = PyObject_stgdict(value);
+ assert(p1); /* Cannot be NULL for array instances */
+ p2 = PyType_stgdict(type);
+ assert(p2); /* Cannot be NULL for pointer types */
+
+ if (p1->proto != p2->proto) {
+ PyErr_Format(PyExc_TypeError,
+ "incompatible types, %s instance instead of %s instance",
+ Py_TYPE(value)->tp_name,
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
+ }
+ *(void **)ptr = src->b_ptr;
+
+ keep = GetKeepedObjects(src);
+ /*
+ We are assigning an array object to a field which represents
+ a pointer. This has the same effect as converting an array
+ into a pointer. So, again, we have to keep the whole object
+ pointed to (which is the array in this case) alive, and not
+ only it's object list. So we create a tuple, containing
+ b_objects list PLUS the array itself, and return that!
+ */
+ return PyTuple_Pack(2, keep, value);
+ }
+ PyErr_Format(PyExc_TypeError,
+ "incompatible types, %s instance instead of %s instance",
+ Py_TYPE(value)->tp_name,
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
}
/*
@@ -2922,58 +2922,58 @@ _PyCData_set(CDataObject *dst, PyObject *type, SETFUNC setfunc, PyObject *value,
*/
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)
{
- CDataObject *mem = (CDataObject *)dst;
- PyObject *result;
-
- if (!CDataObject_Check(dst)) {
- PyErr_SetString(PyExc_TypeError,
- "not a ctype instance");
- return -1;
- }
-
- result = _PyCData_set(mem, type, setfunc, value,
- size, ptr);
- if (result == NULL)
- return -1;
-
- /* KeepRef steals a refcount from it's last argument */
- /* If KeepRef fails, we are stumped. The dst memory block has already
- been changed */
- return KeepRef(mem, index, result);
+ CDataObject *mem = (CDataObject *)dst;
+ PyObject *result;
+
+ if (!CDataObject_Check(dst)) {
+ PyErr_SetString(PyExc_TypeError,
+ "not a ctype instance");
+ return -1;
+ }
+
+ result = _PyCData_set(mem, type, setfunc, value,
+ size, ptr);
+ if (result == NULL)
+ return -1;
+
+ /* KeepRef steals a refcount from it's last argument */
+ /* If KeepRef fails, we are stumped. The dst memory block has already
+ been changed */
+ return KeepRef(mem, index, result);
}
-
+
/******************************************************************/
static PyObject *
GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- CDataObject *obj;
- StgDictObject *dict;
-
- dict = PyType_stgdict((PyObject *)type);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "abstract class");
- return NULL;
- }
- dict->flags |= DICTFLAG_FINAL;
-
- obj = (CDataObject *)type->tp_alloc(type, 0);
- if (!obj)
- return NULL;
-
- obj->b_base = NULL;
- obj->b_index = 0;
- obj->b_objects = NULL;
- obj->b_length = dict->length;
-
- if (-1 == PyCData_MallocBuffer(obj, dict)) {
- Py_DECREF(obj);
- return NULL;
- }
- return (PyObject *)obj;
+ CDataObject *obj;
+ StgDictObject *dict;
+
+ dict = PyType_stgdict((PyObject *)type);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "abstract class");
+ return NULL;
+ }
+ dict->flags |= DICTFLAG_FINAL;
+
+ obj = (CDataObject *)type->tp_alloc(type, 0);
+ if (!obj)
+ return NULL;
+
+ obj->b_base = NULL;
+ obj->b_index = 0;
+ obj->b_objects = NULL;
+ obj->b_length = dict->length;
+
+ if (-1 == PyCData_MallocBuffer(obj, dict)) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ return (PyObject *)obj;
}
/*****************************************************************/
/*
@@ -2983,165 +2983,165 @@ GenericPyCData_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
PyCFuncPtr_set_errcheck(PyCFuncPtrObject *self, PyObject *ob)
{
- if (ob && !PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "the errcheck attribute must be callable");
- return -1;
- }
- Py_XDECREF(self->errcheck);
- Py_XINCREF(ob);
- self->errcheck = ob;
- return 0;
+ if (ob && !PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the errcheck attribute must be callable");
+ return -1;
+ }
+ Py_XDECREF(self->errcheck);
+ Py_XINCREF(ob);
+ self->errcheck = ob;
+ return 0;
}
static PyObject *
PyCFuncPtr_get_errcheck(PyCFuncPtrObject *self)
{
- if (self->errcheck) {
- Py_INCREF(self->errcheck);
- return self->errcheck;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (self->errcheck) {
+ Py_INCREF(self->errcheck);
+ return self->errcheck;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static int
PyCFuncPtr_set_restype(PyCFuncPtrObject *self, PyObject *ob)
{
- if (ob == NULL) {
- Py_XDECREF(self->restype);
- self->restype = NULL;
- Py_XDECREF(self->checker);
- self->checker = NULL;
- return 0;
- }
- if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
- PyErr_SetString(PyExc_TypeError,
- "restype must be a type, a callable, or None");
- return -1;
- }
- Py_XDECREF(self->checker);
- Py_XDECREF(self->restype);
- Py_INCREF(ob);
- self->restype = ob;
- self->checker = PyObject_GetAttrString(ob, "_check_retval_");
- if (self->checker == NULL)
- PyErr_Clear();
- return 0;
+ if (ob == NULL) {
+ Py_XDECREF(self->restype);
+ self->restype = NULL;
+ Py_XDECREF(self->checker);
+ self->checker = NULL;
+ return 0;
+ }
+ if (ob != Py_None && !PyType_stgdict(ob) && !PyCallable_Check(ob)) {
+ PyErr_SetString(PyExc_TypeError,
+ "restype must be a type, a callable, or None");
+ return -1;
+ }
+ Py_XDECREF(self->checker);
+ Py_XDECREF(self->restype);
+ Py_INCREF(ob);
+ self->restype = ob;
+ self->checker = PyObject_GetAttrString(ob, "_check_retval_");
+ if (self->checker == NULL)
+ PyErr_Clear();
+ return 0;
}
static PyObject *
PyCFuncPtr_get_restype(PyCFuncPtrObject *self)
{
- StgDictObject *dict;
- if (self->restype) {
- Py_INCREF(self->restype);
- return self->restype;
- }
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
- if (dict->restype) {
- Py_INCREF(dict->restype);
- return dict->restype;
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ StgDictObject *dict;
+ if (self->restype) {
+ Py_INCREF(self->restype);
+ return self->restype;
+ }
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
+ if (dict->restype) {
+ Py_INCREF(dict->restype);
+ return dict->restype;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static int
PyCFuncPtr_set_argtypes(PyCFuncPtrObject *self, PyObject *ob)
{
- PyObject *converters;
-
- if (ob == NULL || ob == Py_None) {
- Py_XDECREF(self->converters);
- self->converters = NULL;
- Py_XDECREF(self->argtypes);
- self->argtypes = NULL;
- } else {
- converters = converters_from_argtypes(ob);
- if (!converters)
- return -1;
- Py_XDECREF(self->converters);
- self->converters = converters;
- Py_XDECREF(self->argtypes);
- Py_INCREF(ob);
- self->argtypes = ob;
- }
- return 0;
+ PyObject *converters;
+
+ if (ob == NULL || ob == Py_None) {
+ Py_XDECREF(self->converters);
+ self->converters = NULL;
+ Py_XDECREF(self->argtypes);
+ self->argtypes = NULL;
+ } else {
+ converters = converters_from_argtypes(ob);
+ if (!converters)
+ return -1;
+ Py_XDECREF(self->converters);
+ self->converters = converters;
+ Py_XDECREF(self->argtypes);
+ Py_INCREF(ob);
+ self->argtypes = ob;
+ }
+ return 0;
}
static PyObject *
PyCFuncPtr_get_argtypes(PyCFuncPtrObject *self)
{
- StgDictObject *dict;
- if (self->argtypes) {
- Py_INCREF(self->argtypes);
- return self->argtypes;
- }
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
- if (dict->argtypes) {
- Py_INCREF(dict->argtypes);
- return dict->argtypes;
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ StgDictObject *dict;
+ if (self->argtypes) {
+ Py_INCREF(self->argtypes);
+ return self->argtypes;
+ }
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
+ if (dict->argtypes) {
+ Py_INCREF(dict->argtypes);
+ return dict->argtypes;
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static PyGetSetDef PyCFuncPtr_getsets[] = {
- { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck,
- "a function to check for errors", NULL },
- { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype,
- "specify the result type", NULL },
- { "argtypes", (getter)PyCFuncPtr_get_argtypes,
- (setter)PyCFuncPtr_set_argtypes,
- "specify the argument types", NULL },
- { NULL, NULL }
+ { "errcheck", (getter)PyCFuncPtr_get_errcheck, (setter)PyCFuncPtr_set_errcheck,
+ "a function to check for errors", NULL },
+ { "restype", (getter)PyCFuncPtr_get_restype, (setter)PyCFuncPtr_set_restype,
+ "specify the result type", NULL },
+ { "argtypes", (getter)PyCFuncPtr_get_argtypes,
+ (setter)PyCFuncPtr_set_argtypes,
+ "specify the argument types", NULL },
+ { NULL, NULL }
};
#ifdef MS_WIN32
static PPROC FindAddress(void *handle, char *name, PyObject *type)
{
#ifdef MS_WIN64
- /* win64 has no stdcall calling conv, so it should
- also not have the name mangling of it.
- */
- return (PPROC)GetProcAddress(handle, name);
+ /* win64 has no stdcall calling conv, so it should
+ also not have the name mangling of it.
+ */
+ return (PPROC)GetProcAddress(handle, name);
#else
- PPROC address;
- char *mangled_name;
- int i;
- StgDictObject *dict;
-
- address = (PPROC)GetProcAddress(handle, name);
- if (address)
- return address;
- if (((size_t)name & ~0xFFFF) == 0) {
- return NULL;
- }
-
- dict = PyType_stgdict((PyObject *)type);
- /* It should not happen that dict is NULL, but better be safe */
- if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
- return address;
-
- /* for stdcall, try mangled names:
- funcname -> _funcname@<n>
- where n is 0, 4, 8, 12, ..., 128
- */
- mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
- if (!mangled_name)
- return NULL;
- for (i = 0; i < 32; ++i) {
- sprintf(mangled_name, "_%s@%d", name, i*4);
- address = (PPROC)GetProcAddress(handle, mangled_name);
- if (address)
- return address;
- }
- return NULL;
+ PPROC address;
+ char *mangled_name;
+ int i;
+ StgDictObject *dict;
+
+ address = (PPROC)GetProcAddress(handle, name);
+ if (address)
+ return address;
+ if (((size_t)name & ~0xFFFF) == 0) {
+ return NULL;
+ }
+
+ dict = PyType_stgdict((PyObject *)type);
+ /* It should not happen that dict is NULL, but better be safe */
+ if (dict==NULL || dict->flags & FUNCFLAG_CDECL)
+ return address;
+
+ /* for stdcall, try mangled names:
+ funcname -> _funcname@<n>
+ where n is 0, 4, 8, 12, ..., 128
+ */
+ mangled_name = alloca(strlen(name) + 1 + 1 + 1 + 3); /* \0 _ @ %d */
+ if (!mangled_name)
+ return NULL;
+ for (i = 0; i < 32; ++i) {
+ sprintf(mangled_name, "_%s@%d", name, i*4);
+ address = (PPROC)GetProcAddress(handle, mangled_name);
+ if (address)
+ return address;
+ }
+ return NULL;
#endif
}
#endif
@@ -3150,223 +3150,223 @@ static PPROC FindAddress(void *handle, char *name, PyObject *type)
static int
_check_outarg_type(PyObject *arg, Py_ssize_t index)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- if (PyCPointerTypeObject_Check(arg))
- return 1;
+ if (PyCPointerTypeObject_Check(arg))
+ return 1;
- if (PyCArrayTypeObject_Check(arg))
- return 1;
+ if (PyCArrayTypeObject_Check(arg))
+ return 1;
- dict = PyType_stgdict(arg);
- if (dict
- /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
- && PyString_Check(dict->proto)
+ dict = PyType_stgdict(arg);
+ if (dict
+ /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
+ && PyString_Check(dict->proto)
/* We only allow c_void_p, c_char_p and c_wchar_p as a simple output parameter type */
- && (strchr("PzZ", PyString_AS_STRING(dict->proto)[0]))) {
- return 1;
- }
-
- PyErr_Format(PyExc_TypeError,
- "'out' parameter %d must be a pointer type, not %s",
- Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
- PyType_Check(arg) ?
- ((PyTypeObject *)arg)->tp_name :
- Py_TYPE(arg)->tp_name);
- return 0;
+ && (strchr("PzZ", PyString_AS_STRING(dict->proto)[0]))) {
+ return 1;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "'out' parameter %d must be a pointer type, not %s",
+ Py_SAFE_DOWNCAST(index, Py_ssize_t, int),
+ PyType_Check(arg) ?
+ ((PyTypeObject *)arg)->tp_name :
+ Py_TYPE(arg)->tp_name);
+ return 0;
}
/* Returns 1 on success, 0 on error */
static int
_validate_paramflags(PyTypeObject *type, PyObject *paramflags)
{
- Py_ssize_t i, len;
- StgDictObject *dict;
- PyObject *argtypes;
-
- dict = PyType_stgdict((PyObject *)type);
- assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */
- argtypes = dict->argtypes;
-
- if (paramflags == NULL || dict->argtypes == NULL)
- return 1;
-
- if (!PyTuple_Check(paramflags)) {
- PyErr_SetString(PyExc_TypeError,
- "paramflags must be a tuple or None");
- return 0;
- }
-
- len = PyTuple_GET_SIZE(paramflags);
- if (len != PyTuple_GET_SIZE(dict->argtypes)) {
- PyErr_SetString(PyExc_ValueError,
- "paramflags must have the same length as argtypes");
- return 0;
- }
-
- for (i = 0; i < len; ++i) {
- PyObject *item = PyTuple_GET_ITEM(paramflags, i);
- int flag;
- char *name;
- PyObject *defval;
- PyObject *typ;
- if (!PyArg_ParseTuple(item, "i|zO", &flag, &name, &defval)) {
- PyErr_SetString(PyExc_TypeError,
- "paramflags must be a sequence of (int [,string [,value]]) tuples");
- return 0;
- }
- typ = PyTuple_GET_ITEM(argtypes, i);
- switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
- case 0:
- case PARAMFLAG_FIN:
- case PARAMFLAG_FIN | PARAMFLAG_FLCID:
- case PARAMFLAG_FIN | PARAMFLAG_FOUT:
- break;
- case PARAMFLAG_FOUT:
- if (!_check_outarg_type(typ, i+1))
- return 0;
- break;
- default:
- PyErr_Format(PyExc_TypeError,
- "paramflag value %d not supported",
- flag);
- return 0;
- }
- }
- return 1;
+ Py_ssize_t i, len;
+ StgDictObject *dict;
+ PyObject *argtypes;
+
+ dict = PyType_stgdict((PyObject *)type);
+ assert(dict); /* Cannot be NULL. 'type' is a PyCFuncPtr type. */
+ argtypes = dict->argtypes;
+
+ if (paramflags == NULL || dict->argtypes == NULL)
+ return 1;
+
+ if (!PyTuple_Check(paramflags)) {
+ PyErr_SetString(PyExc_TypeError,
+ "paramflags must be a tuple or None");
+ return 0;
+ }
+
+ len = PyTuple_GET_SIZE(paramflags);
+ if (len != PyTuple_GET_SIZE(dict->argtypes)) {
+ PyErr_SetString(PyExc_ValueError,
+ "paramflags must have the same length as argtypes");
+ return 0;
+ }
+
+ for (i = 0; i < len; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(paramflags, i);
+ int flag;
+ char *name;
+ PyObject *defval;
+ PyObject *typ;
+ if (!PyArg_ParseTuple(item, "i|zO", &flag, &name, &defval)) {
+ PyErr_SetString(PyExc_TypeError,
+ "paramflags must be a sequence of (int [,string [,value]]) tuples");
+ return 0;
+ }
+ typ = PyTuple_GET_ITEM(argtypes, i);
+ switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
+ case 0:
+ case PARAMFLAG_FIN:
+ case PARAMFLAG_FIN | PARAMFLAG_FLCID:
+ case PARAMFLAG_FIN | PARAMFLAG_FOUT:
+ break;
+ case PARAMFLAG_FOUT:
+ if (!_check_outarg_type(typ, i+1))
+ return 0;
+ break;
+ default:
+ PyErr_Format(PyExc_TypeError,
+ "paramflag value %d not supported",
+ flag);
+ return 0;
+ }
+ }
+ return 1;
}
static int
_get_name(PyObject *obj, char **pname)
{
#ifdef MS_WIN32
- if (PyInt_Check(obj) || PyLong_Check(obj)) {
- /* We have to use MAKEINTRESOURCEA for Windows CE.
- Works on Windows as well, of course.
- */
- *pname = MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj) & 0xFFFF);
- return 1;
- }
+ if (PyInt_Check(obj) || PyLong_Check(obj)) {
+ /* We have to use MAKEINTRESOURCEA for Windows CE.
+ Works on Windows as well, of course.
+ */
+ *pname = MAKEINTRESOURCEA(PyInt_AsUnsignedLongMask(obj) & 0xFFFF);
+ return 1;
+ }
#endif
- if (PyString_Check(obj) || PyUnicode_Check(obj)) {
- *pname = PyString_AsString(obj);
- return *pname ? 1 : 0;
- }
- PyErr_SetString(PyExc_TypeError,
- "function name must be string or integer");
- return 0;
+ if (PyString_Check(obj) || PyUnicode_Check(obj)) {
+ *pname = PyString_AsString(obj);
+ return *pname ? 1 : 0;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "function name must be string or integer");
+ return 0;
}
static PyObject *
PyCFuncPtr_FromDll(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char *name;
- int (* address)(void);
- PyObject *dll;
- PyObject *obj;
- PyCFuncPtrObject *self;
- void *handle;
- PyObject *paramflags = NULL;
-
- if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, &paramflags))
- return NULL;
- if (paramflags == Py_None)
- paramflags = NULL;
-
- obj = PyObject_GetAttrString(dll, "_handle");
- if (!obj)
- return NULL;
- if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "the _handle attribute of the second argument must be an integer");
- Py_DECREF(obj);
- return NULL;
- }
- handle = (void *)PyLong_AsVoidPtr(obj);
- Py_DECREF(obj);
- if (PyErr_Occurred()) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert the _handle attribute to a pointer");
- return NULL;
- }
+ char *name;
+ int (* address)(void);
+ PyObject *dll;
+ PyObject *obj;
+ PyCFuncPtrObject *self;
+ void *handle;
+ PyObject *paramflags = NULL;
+
+ if (!PyArg_ParseTuple(args, "(O&O)|O", _get_name, &name, &dll, &paramflags))
+ return NULL;
+ if (paramflags == Py_None)
+ paramflags = NULL;
+
+ obj = PyObject_GetAttrString(dll, "_handle");
+ if (!obj)
+ return NULL;
+ if (!PyInt_Check(obj) && !PyLong_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "the _handle attribute of the second argument must be an integer");
+ Py_DECREF(obj);
+ return NULL;
+ }
+ handle = (void *)PyLong_AsVoidPtr(obj);
+ Py_DECREF(obj);
+ if (PyErr_Occurred()) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert the _handle attribute to a pointer");
+ return NULL;
+ }
#ifdef MS_WIN32
- address = FindAddress(handle, name, (PyObject *)type);
- if (!address) {
- if (!IS_INTRESOURCE(name))
- PyErr_Format(PyExc_AttributeError,
- "function '%s' not found",
- name);
- else
- PyErr_Format(PyExc_AttributeError,
- "function ordinal %d not found",
- (WORD)(size_t)name);
- return NULL;
- }
+ address = FindAddress(handle, name, (PyObject *)type);
+ if (!address) {
+ if (!IS_INTRESOURCE(name))
+ PyErr_Format(PyExc_AttributeError,
+ "function '%s' not found",
+ name);
+ else
+ PyErr_Format(PyExc_AttributeError,
+ "function ordinal %d not found",
+ (WORD)(size_t)name);
+ return NULL;
+ }
#else
- address = (PPROC)ctypes_dlsym(handle, name);
- if (!address) {
+ address = (PPROC)ctypes_dlsym(handle, name);
+ if (!address) {
#ifdef __CYGWIN__
/* dlerror() isn't very helpful on cygwin */
- PyErr_Format(PyExc_AttributeError,
- "function '%s' not found (%s) ",
- name);
+ PyErr_Format(PyExc_AttributeError,
+ "function '%s' not found (%s) ",
+ name);
#else
- PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
+ PyErr_SetString(PyExc_AttributeError, ctypes_dlerror());
#endif
- return NULL;
- }
+ return NULL;
+ }
#endif
- if (!_validate_paramflags(type, paramflags))
- return NULL;
+ if (!_validate_paramflags(type, paramflags))
+ return NULL;
- self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
- if (!self)
- return NULL;
+ self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
+ if (!self)
+ return NULL;
- Py_XINCREF(paramflags);
- self->paramflags = paramflags;
+ Py_XINCREF(paramflags);
+ self->paramflags = paramflags;
- *(void **)self->b_ptr = address;
+ *(void **)self->b_ptr = address;
- Py_INCREF((PyObject *)dll); /* for KeepRef */
- if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
- Py_DECREF((PyObject *)self);
- return NULL;
- }
+ Py_INCREF((PyObject *)dll); /* for KeepRef */
+ if (-1 == KeepRef((CDataObject *)self, 0, dll)) {
+ Py_DECREF((PyObject *)self);
+ return NULL;
+ }
- Py_INCREF(self);
- self->callable = (PyObject *)self;
- return (PyObject *)self;
+ Py_INCREF(self);
+ self->callable = (PyObject *)self;
+ return (PyObject *)self;
}
#ifdef MS_WIN32
static PyObject *
PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyCFuncPtrObject *self;
- int index;
- char *name = NULL;
- PyObject *paramflags = NULL;
- GUID *iid = NULL;
- Py_ssize_t iid_len = 0;
-
- if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
- return NULL;
- if (paramflags == Py_None)
- paramflags = NULL;
-
- if (!_validate_paramflags(type, paramflags))
- return NULL;
-
- self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
- self->index = index + 0x1000;
- Py_XINCREF(paramflags);
- self->paramflags = paramflags;
- if (iid_len == sizeof(GUID))
- self->iid = iid;
- return (PyObject *)self;
+ PyCFuncPtrObject *self;
+ int index;
+ char *name = NULL;
+ PyObject *paramflags = NULL;
+ GUID *iid = NULL;
+ Py_ssize_t iid_len = 0;
+
+ if (!PyArg_ParseTuple(args, "is|Oz#", &index, &name, &paramflags, &iid, &iid_len))
+ return NULL;
+ if (paramflags == Py_None)
+ paramflags = NULL;
+
+ if (!_validate_paramflags(type, paramflags))
+ return NULL;
+
+ self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
+ self->index = index + 0x1000;
+ Py_XINCREF(paramflags);
+ self->paramflags = paramflags;
+ if (iid_len == sizeof(GUID))
+ self->iid = iid;
+ return (PyObject *)self;
}
#endif
@@ -3386,91 +3386,91 @@ PyCFuncPtr_FromVtblIndex(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyCFuncPtrObject *self;
- PyObject *callable;
- StgDictObject *dict;
- CThunkObject *thunk;
+ PyCFuncPtrObject *self;
+ PyObject *callable;
+ StgDictObject *dict;
+ CThunkObject *thunk;
- if (PyTuple_GET_SIZE(args) == 0)
- return GenericPyCData_new(type, args, kwds);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return GenericPyCData_new(type, args, kwds);
- if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
- return PyCFuncPtr_FromDll(type, args, kwds);
+ if (1 <= PyTuple_GET_SIZE(args) && PyTuple_Check(PyTuple_GET_ITEM(args, 0)))
+ return PyCFuncPtr_FromDll(type, args, kwds);
#ifdef MS_WIN32
- if (2 <= PyTuple_GET_SIZE(args) && PyInt_Check(PyTuple_GET_ITEM(args, 0)))
- return PyCFuncPtr_FromVtblIndex(type, args, kwds);
+ if (2 <= PyTuple_GET_SIZE(args) && PyInt_Check(PyTuple_GET_ITEM(args, 0)))
+ return PyCFuncPtr_FromVtblIndex(type, args, kwds);
#endif
- if (1 == PyTuple_GET_SIZE(args)
- && (PyInt_Check(PyTuple_GET_ITEM(args, 0))
- || PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
- CDataObject *ob;
- void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
- if (ptr == NULL && PyErr_Occurred())
- return NULL;
- ob = (CDataObject *)GenericPyCData_new(type, args, kwds);
- if (ob == NULL)
- return NULL;
- *(void **)ob->b_ptr = ptr;
- return (PyObject *)ob;
- }
-
- if (!PyArg_ParseTuple(args, "O", &callable))
- return NULL;
- if (!PyCallable_Check(callable)) {
- PyErr_SetString(PyExc_TypeError,
- "argument must be callable or integer function address");
- return NULL;
- }
-
- /* XXX XXX This would allow to pass additional options. For COM
- method *implementations*, we would probably want different
- behaviour than in 'normal' callback functions: return a HRESULT if
- an exception occurrs in the callback, and print the traceback not
- only on the console, but also to OutputDebugString() or something
- like that.
- */
+ if (1 == PyTuple_GET_SIZE(args)
+ && (PyInt_Check(PyTuple_GET_ITEM(args, 0))
+ || PyLong_Check(PyTuple_GET_ITEM(args, 0)))) {
+ CDataObject *ob;
+ void *ptr = PyLong_AsVoidPtr(PyTuple_GET_ITEM(args, 0));
+ if (ptr == NULL && PyErr_Occurred())
+ return NULL;
+ ob = (CDataObject *)GenericPyCData_new(type, args, kwds);
+ if (ob == NULL)
+ return NULL;
+ *(void **)ob->b_ptr = ptr;
+ return (PyObject *)ob;
+ }
+
+ if (!PyArg_ParseTuple(args, "O", &callable))
+ return NULL;
+ if (!PyCallable_Check(callable)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument must be callable or integer function address");
+ return NULL;
+ }
+
+ /* XXX XXX This would allow to pass additional options. For COM
+ method *implementations*, we would probably want different
+ behaviour than in 'normal' callback functions: return a HRESULT if
+ an exception occurrs in the callback, and print the traceback not
+ only on the console, but also to OutputDebugString() or something
+ like that.
+ */
/*
- if (kwds && PyDict_GetItemString(kwds, "options")) {
- ...
- }
+ if (kwds && PyDict_GetItemString(kwds, "options")) {
+ ...
+ }
*/
- dict = PyType_stgdict((PyObject *)type);
- /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
- if (!dict || !dict->argtypes) {
- PyErr_SetString(PyExc_TypeError,
- "cannot construct instance of this class:"
- " no argtypes");
- return NULL;
- }
-
- thunk = _ctypes_alloc_callback(callable,
- dict->argtypes,
- dict->restype,
- dict->flags);
- if (!thunk)
- return NULL;
-
- self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
- if (self == NULL) {
- Py_DECREF(thunk);
- return NULL;
- }
-
- Py_INCREF(callable);
- self->callable = callable;
-
- self->thunk = thunk;
- *(void **)self->b_ptr = (void *)thunk->pcl;
-
- Py_INCREF((PyObject *)thunk); /* for KeepRef */
- if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
- Py_DECREF((PyObject *)self);
- return NULL;
- }
- return (PyObject *)self;
+ dict = PyType_stgdict((PyObject *)type);
+ /* XXXX Fails if we do: 'PyCFuncPtr(lambda x: x)' */
+ if (!dict || !dict->argtypes) {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot construct instance of this class:"
+ " no argtypes");
+ return NULL;
+ }
+
+ thunk = _ctypes_alloc_callback(callable,
+ dict->argtypes,
+ dict->restype,
+ dict->flags);
+ if (!thunk)
+ return NULL;
+
+ self = (PyCFuncPtrObject *)GenericPyCData_new(type, args, kwds);
+ if (self == NULL) {
+ Py_DECREF(thunk);
+ return NULL;
+ }
+
+ Py_INCREF(callable);
+ self->callable = callable;
+
+ self->thunk = thunk;
+ *(void **)self->b_ptr = (void *)thunk->pcl;
+
+ Py_INCREF((PyObject *)thunk); /* for KeepRef */
+ if (-1 == KeepRef((CDataObject *)self, 0, (PyObject *)thunk)) {
+ Py_DECREF((PyObject *)self);
+ return NULL;
+ }
+ return (PyObject *)self;
}
@@ -3480,54 +3480,54 @@ PyCFuncPtr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
_byref(PyObject *obj)
{
- PyCArgObject *parg;
- if (!CDataObject_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "expected CData instance");
- return NULL;
- }
-
- parg = PyCArgObject_new();
- if (parg == NULL) {
- Py_DECREF(obj);
- return NULL;
- }
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- parg->obj = obj;
- parg->value.p = ((CDataObject *)obj)->b_ptr;
- return (PyObject *)parg;
+ PyCArgObject *parg;
+ if (!CDataObject_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected CData instance");
+ return NULL;
+ }
+
+ parg = PyCArgObject_new();
+ if (parg == NULL) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ parg->obj = obj;
+ parg->value.p = ((CDataObject *)obj)->b_ptr;
+ return (PyObject *)parg;
}
static PyObject *
_get_arg(int *pindex, char *name, PyObject *defval, PyObject *inargs, PyObject *kwds)
{
- PyObject *v;
-
- if (*pindex < PyTuple_GET_SIZE(inargs)) {
- v = PyTuple_GET_ITEM(inargs, *pindex);
- ++*pindex;
- Py_INCREF(v);
- return v;
- }
- if (kwds && (v = PyDict_GetItemString(kwds, name))) {
- ++*pindex;
- Py_INCREF(v);
- return v;
- }
- if (defval) {
- Py_INCREF(defval);
- return defval;
- }
- /* we can't currently emit a better error message */
- if (name)
- PyErr_Format(PyExc_TypeError,
- "required argument '%s' missing", name);
- else
- PyErr_Format(PyExc_TypeError,
- "not enough arguments");
- return NULL;
+ PyObject *v;
+
+ if (*pindex < PyTuple_GET_SIZE(inargs)) {
+ v = PyTuple_GET_ITEM(inargs, *pindex);
+ ++*pindex;
+ Py_INCREF(v);
+ return v;
+ }
+ if (kwds && (v = PyDict_GetItemString(kwds, name))) {
+ ++*pindex;
+ Py_INCREF(v);
+ return v;
+ }
+ if (defval) {
+ Py_INCREF(defval);
+ return defval;
+ }
+ /* we can't currently emit a better error message */
+ if (name)
+ PyErr_Format(PyExc_TypeError,
+ "required argument '%s' missing", name);
+ else
+ PyErr_Format(PyExc_TypeError,
+ "not enough arguments");
+ return NULL;
}
/*
@@ -3550,170 +3550,170 @@ _get_arg(int *pindex, char *name, PyObject *defval, PyObject *inargs, PyObject *
*/
static PyObject *
_build_callargs(PyCFuncPtrObject *self, PyObject *argtypes,
- PyObject *inargs, PyObject *kwds,
- int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
+ PyObject *inargs, PyObject *kwds,
+ int *poutmask, int *pinoutmask, unsigned int *pnumretvals)
{
- PyObject *paramflags = self->paramflags;
- PyObject *callargs;
- StgDictObject *dict;
- Py_ssize_t i, len;
- int inargs_index = 0;
- /* It's a little bit difficult to determine how many arguments the
- function call requires/accepts. For simplicity, we count the consumed
- args and compare this to the number of supplied args. */
- Py_ssize_t actual_args;
-
- *poutmask = 0;
- *pinoutmask = 0;
- *pnumretvals = 0;
-
- /* Trivial cases, where we either return inargs itself, or a slice of it. */
- if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
+ PyObject *paramflags = self->paramflags;
+ PyObject *callargs;
+ StgDictObject *dict;
+ Py_ssize_t i, len;
+ int inargs_index = 0;
+ /* It's a little bit difficult to determine how many arguments the
+ function call requires/accepts. For simplicity, we count the consumed
+ args and compare this to the number of supplied args. */
+ Py_ssize_t actual_args;
+
+ *poutmask = 0;
+ *pinoutmask = 0;
+ *pnumretvals = 0;
+
+ /* Trivial cases, where we either return inargs itself, or a slice of it. */
+ if (argtypes == NULL || paramflags == NULL || PyTuple_GET_SIZE(argtypes) == 0) {
#ifdef MS_WIN32
- if (self->index)
- return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
+ if (self->index)
+ return PyTuple_GetSlice(inargs, 1, PyTuple_GET_SIZE(inargs));
#endif
- Py_INCREF(inargs);
- return inargs;
- }
+ Py_INCREF(inargs);
+ return inargs;
+ }
- len = PyTuple_GET_SIZE(argtypes);
- callargs = PyTuple_New(len); /* the argument tuple we build */
- if (callargs == NULL)
- return NULL;
+ len = PyTuple_GET_SIZE(argtypes);
+ callargs = PyTuple_New(len); /* the argument tuple we build */
+ if (callargs == NULL)
+ return NULL;
#ifdef MS_WIN32
- /* For a COM method, skip the first arg */
- if (self->index) {
- inargs_index = 1;
- }
+ /* For a COM method, skip the first arg */
+ if (self->index) {
+ inargs_index = 1;
+ }
#endif
- for (i = 0; i < len; ++i) {
- PyObject *item = PyTuple_GET_ITEM(paramflags, i);
- PyObject *ob;
- int flag;
- char *name = NULL;
- PyObject *defval = NULL;
-
- /* This way seems to be ~2 us faster than the PyArg_ParseTuple
- calls below. */
- /* We HAVE already checked that the tuple can be parsed with "i|zO", so... */
- Py_ssize_t tsize = PyTuple_GET_SIZE(item);
- flag = PyInt_AS_LONG(PyTuple_GET_ITEM(item, 0));
- name = tsize > 1 ? PyString_AS_STRING(PyTuple_GET_ITEM(item, 1)) : NULL;
- defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
-
- switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
- case PARAMFLAG_FIN | PARAMFLAG_FLCID:
- /* ['in', 'lcid'] parameter. Always taken from defval,
- if given, else the integer 0. */
- if (defval == NULL) {
- defval = PyInt_FromLong(0);
- if (defval == NULL)
- goto error;
- } else
- Py_INCREF(defval);
- PyTuple_SET_ITEM(callargs, i, defval);
- break;
- case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
- *pinoutmask |= (1 << i); /* mark as inout arg */
- (*pnumretvals)++;
- /* fall through to PARAMFLAG_FIN... */
- case 0:
- case PARAMFLAG_FIN:
- /* 'in' parameter. Copy it from inargs. */
- ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
- if (ob == NULL)
- goto error;
- PyTuple_SET_ITEM(callargs, i, ob);
- break;
- case PARAMFLAG_FOUT:
- /* XXX Refactor this code into a separate function. */
- /* 'out' parameter.
- argtypes[i] must be a POINTER to a c type.
-
- Cannot by supplied in inargs, but a defval will be used
- if available. XXX Should we support getting it from kwds?
- */
- if (defval) {
- /* XXX Using mutable objects as defval will
- make the function non-threadsafe, unless we
- copy the object in each invocation */
- Py_INCREF(defval);
- PyTuple_SET_ITEM(callargs, i, defval);
- *poutmask |= (1 << i); /* mark as out arg */
- (*pnumretvals)++;
- break;
- }
- ob = PyTuple_GET_ITEM(argtypes, i);
- dict = PyType_stgdict(ob);
- if (dict == NULL) {
- /* Cannot happen: _validate_paramflags()
- would not accept such an object */
- PyErr_Format(PyExc_RuntimeError,
- "NULL stgdict unexpected");
- goto error;
- }
- if (PyString_Check(dict->proto)) {
- PyErr_Format(
- PyExc_TypeError,
- "%s 'out' parameter must be passed as default value",
- ((PyTypeObject *)ob)->tp_name);
- goto error;
- }
- if (PyCArrayTypeObject_Check(ob))
- ob = PyObject_CallObject(ob, NULL);
- else
- /* Create an instance of the pointed-to type */
- ob = PyObject_CallObject(dict->proto, NULL);
- /*
- XXX Is the following correct any longer?
- We must not pass a byref() to the array then but
- the array instance itself. Then, we cannot retrive
- the result from the PyCArgObject.
- */
- if (ob == NULL)
- goto error;
- /* The .from_param call that will ocurr later will pass this
- as a byref parameter. */
- PyTuple_SET_ITEM(callargs, i, ob);
- *poutmask |= (1 << i); /* mark as out arg */
- (*pnumretvals)++;
- break;
- default:
- PyErr_Format(PyExc_ValueError,
- "paramflag %d not yet implemented", flag);
- goto error;
- break;
- }
- }
-
- /* We have counted the arguments we have consumed in 'inargs_index'. This
- must be the same as len(inargs) + len(kwds), otherwise we have
- either too much or not enough arguments. */
-
- actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0);
- if (actual_args != inargs_index) {
- /* When we have default values or named parameters, this error
- message is misleading. See unittests/test_paramflags.py
- */
- PyErr_Format(PyExc_TypeError,
+ for (i = 0; i < len; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(paramflags, i);
+ PyObject *ob;
+ int flag;
+ char *name = NULL;
+ PyObject *defval = NULL;
+
+ /* This way seems to be ~2 us faster than the PyArg_ParseTuple
+ calls below. */
+ /* We HAVE already checked that the tuple can be parsed with "i|zO", so... */
+ Py_ssize_t tsize = PyTuple_GET_SIZE(item);
+ flag = PyInt_AS_LONG(PyTuple_GET_ITEM(item, 0));
+ name = tsize > 1 ? PyString_AS_STRING(PyTuple_GET_ITEM(item, 1)) : NULL;
+ defval = tsize > 2 ? PyTuple_GET_ITEM(item, 2) : NULL;
+
+ switch (flag & (PARAMFLAG_FIN | PARAMFLAG_FOUT | PARAMFLAG_FLCID)) {
+ case PARAMFLAG_FIN | PARAMFLAG_FLCID:
+ /* ['in', 'lcid'] parameter. Always taken from defval,
+ if given, else the integer 0. */
+ if (defval == NULL) {
+ defval = PyInt_FromLong(0);
+ if (defval == NULL)
+ goto error;
+ } else
+ Py_INCREF(defval);
+ PyTuple_SET_ITEM(callargs, i, defval);
+ break;
+ case (PARAMFLAG_FIN | PARAMFLAG_FOUT):
+ *pinoutmask |= (1 << i); /* mark as inout arg */
+ (*pnumretvals)++;
+ /* fall through to PARAMFLAG_FIN... */
+ case 0:
+ case PARAMFLAG_FIN:
+ /* 'in' parameter. Copy it from inargs. */
+ ob =_get_arg(&inargs_index, name, defval, inargs, kwds);
+ if (ob == NULL)
+ goto error;
+ PyTuple_SET_ITEM(callargs, i, ob);
+ break;
+ case PARAMFLAG_FOUT:
+ /* XXX Refactor this code into a separate function. */
+ /* 'out' parameter.
+ argtypes[i] must be a POINTER to a c type.
+
+ Cannot by supplied in inargs, but a defval will be used
+ if available. XXX Should we support getting it from kwds?
+ */
+ if (defval) {
+ /* XXX Using mutable objects as defval will
+ make the function non-threadsafe, unless we
+ copy the object in each invocation */
+ Py_INCREF(defval);
+ PyTuple_SET_ITEM(callargs, i, defval);
+ *poutmask |= (1 << i); /* mark as out arg */
+ (*pnumretvals)++;
+ break;
+ }
+ ob = PyTuple_GET_ITEM(argtypes, i);
+ dict = PyType_stgdict(ob);
+ if (dict == NULL) {
+ /* Cannot happen: _validate_paramflags()
+ would not accept such an object */
+ PyErr_Format(PyExc_RuntimeError,
+ "NULL stgdict unexpected");
+ goto error;
+ }
+ if (PyString_Check(dict->proto)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s 'out' parameter must be passed as default value",
+ ((PyTypeObject *)ob)->tp_name);
+ goto error;
+ }
+ if (PyCArrayTypeObject_Check(ob))
+ ob = PyObject_CallObject(ob, NULL);
+ else
+ /* Create an instance of the pointed-to type */
+ ob = PyObject_CallObject(dict->proto, NULL);
+ /*
+ XXX Is the following correct any longer?
+ We must not pass a byref() to the array then but
+ the array instance itself. Then, we cannot retrive
+ the result from the PyCArgObject.
+ */
+ if (ob == NULL)
+ goto error;
+ /* The .from_param call that will ocurr later will pass this
+ as a byref parameter. */
+ PyTuple_SET_ITEM(callargs, i, ob);
+ *poutmask |= (1 << i); /* mark as out arg */
+ (*pnumretvals)++;
+ break;
+ default:
+ PyErr_Format(PyExc_ValueError,
+ "paramflag %d not yet implemented", flag);
+ goto error;
+ break;
+ }
+ }
+
+ /* We have counted the arguments we have consumed in 'inargs_index'. This
+ must be the same as len(inargs) + len(kwds), otherwise we have
+ either too much or not enough arguments. */
+
+ actual_args = PyTuple_GET_SIZE(inargs) + (kwds ? PyDict_Size(kwds) : 0);
+ if (actual_args != inargs_index) {
+ /* When we have default values or named parameters, this error
+ message is misleading. See unittests/test_paramflags.py
+ */
+ PyErr_Format(PyExc_TypeError,
#if (PY_VERSION_HEX < 0x02050000)
- "call takes exactly %d arguments (%d given)",
+ "call takes exactly %d arguments (%d given)",
#else
- "call takes exactly %d arguments (%zd given)",
+ "call takes exactly %d arguments (%zd given)",
#endif
- inargs_index, actual_args);
- goto error;
- }
-
- /* outmask is a bitmask containing indexes into callargs. Items at
- these indexes contain values to return.
- */
- return callargs;
+ inargs_index, actual_args);
+ goto error;
+ }
+
+ /* outmask is a bitmask containing indexes into callargs. Items at
+ these indexes contain values to return.
+ */
+ return callargs;
error:
- Py_DECREF(callargs);
- return NULL;
+ Py_DECREF(callargs);
+ return NULL;
}
/* See also:
@@ -3726,308 +3726,308 @@ _build_callargs(PyCFuncPtrObject *self, PyObject *argtypes,
*/
static PyObject *
_build_result(PyObject *result, PyObject *callargs,
- int outmask, int inoutmask, unsigned int numretvals)
+ int outmask, int inoutmask, unsigned int numretvals)
{
- unsigned int i, index;
- int bit;
- PyObject *tup = NULL;
-
- if (callargs == NULL)
- return result;
- if (result == NULL || numretvals == 0) {
- Py_DECREF(callargs);
- return result;
- }
- Py_DECREF(result);
-
- /* tup will not be allocated if numretvals == 1 */
- /* allocate tuple to hold the result */
- if (numretvals > 1) {
- tup = PyTuple_New(numretvals);
- if (tup == NULL) {
- Py_DECREF(callargs);
- return NULL;
- }
- }
-
- index = 0;
- for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
- PyObject *v;
- if (bit & inoutmask) {
- v = PyTuple_GET_ITEM(callargs, i);
- Py_INCREF(v);
- if (numretvals == 1) {
- Py_DECREF(callargs);
- return v;
- }
- PyTuple_SET_ITEM(tup, index, v);
- index++;
- } else if (bit & outmask) {
- v = PyTuple_GET_ITEM(callargs, i);
- v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL);
- if (v == NULL || numretvals == 1) {
- Py_DECREF(callargs);
- return v;
- }
- PyTuple_SET_ITEM(tup, index, v);
- index++;
- }
- if (index == numretvals)
- break;
- }
-
- Py_DECREF(callargs);
- return tup;
+ unsigned int i, index;
+ int bit;
+ PyObject *tup = NULL;
+
+ if (callargs == NULL)
+ return result;
+ if (result == NULL || numretvals == 0) {
+ Py_DECREF(callargs);
+ return result;
+ }
+ Py_DECREF(result);
+
+ /* tup will not be allocated if numretvals == 1 */
+ /* allocate tuple to hold the result */
+ if (numretvals > 1) {
+ tup = PyTuple_New(numretvals);
+ if (tup == NULL) {
+ Py_DECREF(callargs);
+ return NULL;
+ }
+ }
+
+ index = 0;
+ for (bit = 1, i = 0; i < 32; ++i, bit <<= 1) {
+ PyObject *v;
+ if (bit & inoutmask) {
+ v = PyTuple_GET_ITEM(callargs, i);
+ Py_INCREF(v);
+ if (numretvals == 1) {
+ Py_DECREF(callargs);
+ return v;
+ }
+ PyTuple_SET_ITEM(tup, index, v);
+ index++;
+ } else if (bit & outmask) {
+ v = PyTuple_GET_ITEM(callargs, i);
+ v = PyObject_CallMethod(v, "__ctypes_from_outparam__", NULL);
+ if (v == NULL || numretvals == 1) {
+ Py_DECREF(callargs);
+ return v;
+ }
+ PyTuple_SET_ITEM(tup, index, v);
+ index++;
+ }
+ if (index == numretvals)
+ break;
+ }
+
+ Py_DECREF(callargs);
+ return tup;
}
static PyObject *
PyCFuncPtr_call(PyCFuncPtrObject *self, PyObject *inargs, PyObject *kwds)
{
- PyObject *restype;
- PyObject *converters;
- PyObject *checker;
- PyObject *argtypes;
- StgDictObject *dict = PyObject_stgdict((PyObject *)self);
- PyObject *result;
- PyObject *callargs;
- PyObject *errcheck;
+ PyObject *restype;
+ PyObject *converters;
+ PyObject *checker;
+ PyObject *argtypes;
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+ PyObject *result;
+ PyObject *callargs;
+ PyObject *errcheck;
#ifdef MS_WIN32
- IUnknown *piunk = NULL;
+ IUnknown *piunk = NULL;
#endif
- void *pProc = NULL;
+ void *pProc = NULL;
- int inoutmask;
- int outmask;
- unsigned int numretvals;
+ int inoutmask;
+ int outmask;
+ unsigned int numretvals;
- assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
- restype = self->restype ? self->restype : dict->restype;
- converters = self->converters ? self->converters : dict->converters;
- checker = self->checker ? self->checker : dict->checker;
- argtypes = self->argtypes ? self->argtypes : dict->argtypes;
+ assert(dict); /* Cannot be NULL for PyCFuncPtrObject instances */
+ restype = self->restype ? self->restype : dict->restype;
+ converters = self->converters ? self->converters : dict->converters;
+ checker = self->checker ? self->checker : dict->checker;
+ argtypes = self->argtypes ? self->argtypes : dict->argtypes;
/* later, we probably want to have an errcheck field in stgdict */
- errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */;
+ errcheck = self->errcheck /* ? self->errcheck : dict->errcheck */;
- pProc = *(void **)self->b_ptr;
+ pProc = *(void **)self->b_ptr;
#ifdef MS_WIN32
- if (self->index) {
- /* It's a COM method */
- CDataObject *this;
- this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
- if (!this) {
- PyErr_SetString(PyExc_ValueError,
- "native com method call without 'this' parameter");
- return NULL;
- }
- if (!CDataObject_Check(this)) {
- PyErr_SetString(PyExc_TypeError,
- "Expected a COM this pointer as first argument");
- return NULL;
- }
- /* there should be more checks? No, in Python */
- /* First arg is an pointer to an interface instance */
- if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL COM pointer access");
- return NULL;
- }
- piunk = *(IUnknown **)this->b_ptr;
- if (NULL == piunk->lpVtbl) {
- PyErr_SetString(PyExc_ValueError,
- "COM method call without VTable");
- return NULL;
- }
- pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
- }
+ if (self->index) {
+ /* It's a COM method */
+ CDataObject *this;
+ this = (CDataObject *)PyTuple_GetItem(inargs, 0); /* borrowed ref! */
+ if (!this) {
+ PyErr_SetString(PyExc_ValueError,
+ "native com method call without 'this' parameter");
+ return NULL;
+ }
+ if (!CDataObject_Check(this)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected a COM this pointer as first argument");
+ return NULL;
+ }
+ /* there should be more checks? No, in Python */
+ /* First arg is an pointer to an interface instance */
+ if (!this->b_ptr || *(void **)this->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL COM pointer access");
+ return NULL;
+ }
+ piunk = *(IUnknown **)this->b_ptr;
+ if (NULL == piunk->lpVtbl) {
+ PyErr_SetString(PyExc_ValueError,
+ "COM method call without VTable");
+ return NULL;
+ }
+ pProc = ((void **)piunk->lpVtbl)[self->index - 0x1000];
+ }
#endif
- callargs = _build_callargs(self, argtypes,
- inargs, kwds,
- &outmask, &inoutmask, &numretvals);
- if (callargs == NULL)
- return NULL;
-
- if (converters) {
- int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
- Py_ssize_t, int);
- int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
- Py_ssize_t, int);
-
- if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
- /* For cdecl functions, we allow more actual arguments
- than the length of the argtypes tuple.
- */
- if (required > actual) {
- Py_DECREF(callargs);
- PyErr_Format(PyExc_TypeError,
- "this function takes at least %d argument%s (%d given)",
- required,
- required == 1 ? "" : "s",
- actual);
- return NULL;
- }
- } else if (required != actual) {
- Py_DECREF(callargs);
- PyErr_Format(PyExc_TypeError,
- "this function takes %d argument%s (%d given)",
- required,
- required == 1 ? "" : "s",
- actual);
- return NULL;
- }
- }
-
- result = _ctypes_callproc(pProc,
- callargs,
+ callargs = _build_callargs(self, argtypes,
+ inargs, kwds,
+ &outmask, &inoutmask, &numretvals);
+ if (callargs == NULL)
+ return NULL;
+
+ if (converters) {
+ int required = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(converters),
+ Py_ssize_t, int);
+ int actual = Py_SAFE_DOWNCAST(PyTuple_GET_SIZE(callargs),
+ Py_ssize_t, int);
+
+ if ((dict->flags & FUNCFLAG_CDECL) == FUNCFLAG_CDECL) {
+ /* For cdecl functions, we allow more actual arguments
+ than the length of the argtypes tuple.
+ */
+ if (required > actual) {
+ Py_DECREF(callargs);
+ PyErr_Format(PyExc_TypeError,
+ "this function takes at least %d argument%s (%d given)",
+ required,
+ required == 1 ? "" : "s",
+ actual);
+ return NULL;
+ }
+ } else if (required != actual) {
+ Py_DECREF(callargs);
+ PyErr_Format(PyExc_TypeError,
+ "this function takes %d argument%s (%d given)",
+ required,
+ required == 1 ? "" : "s",
+ actual);
+ return NULL;
+ }
+ }
+
+ result = _ctypes_callproc(pProc,
+ callargs,
#ifdef MS_WIN32
- piunk,
- self->iid,
+ piunk,
+ self->iid,
#endif
- dict->flags,
- converters,
- restype,
- checker);
+ dict->flags,
+ converters,
+ restype,
+ checker);
/* The 'errcheck' protocol */
- if (result != NULL && errcheck) {
- PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
- result,
- self,
- callargs,
- NULL);
- /* If the errcheck funtion failed, return NULL.
- If the errcheck function returned callargs unchanged,
- continue normal processing.
- If the errcheck function returned something else,
- use that as result.
- */
- if (v == NULL || v != callargs) {
- Py_DECREF(result);
- Py_DECREF(callargs);
- return v;
- }
- Py_DECREF(v);
- }
-
- return _build_result(result, callargs,
- outmask, inoutmask, numretvals);
+ if (result != NULL && errcheck) {
+ PyObject *v = PyObject_CallFunctionObjArgs(errcheck,
+ result,
+ self,
+ callargs,
+ NULL);
+ /* If the errcheck funtion failed, return NULL.
+ If the errcheck function returned callargs unchanged,
+ continue normal processing.
+ If the errcheck function returned something else,
+ use that as result.
+ */
+ if (v == NULL || v != callargs) {
+ Py_DECREF(result);
+ Py_DECREF(callargs);
+ return v;
+ }
+ Py_DECREF(v);
+ }
+
+ return _build_result(result, callargs,
+ outmask, inoutmask, numretvals);
}
static int
PyCFuncPtr_traverse(PyCFuncPtrObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->callable);
- Py_VISIT(self->restype);
- Py_VISIT(self->checker);
- Py_VISIT(self->errcheck);
- Py_VISIT(self->argtypes);
- Py_VISIT(self->converters);
- Py_VISIT(self->paramflags);
- Py_VISIT(self->thunk);
- return PyCData_traverse((CDataObject *)self, visit, arg);
+ Py_VISIT(self->callable);
+ Py_VISIT(self->restype);
+ Py_VISIT(self->checker);
+ Py_VISIT(self->errcheck);
+ Py_VISIT(self->argtypes);
+ Py_VISIT(self->converters);
+ Py_VISIT(self->paramflags);
+ Py_VISIT(self->thunk);
+ return PyCData_traverse((CDataObject *)self, visit, arg);
}
static int
PyCFuncPtr_clear(PyCFuncPtrObject *self)
{
- Py_CLEAR(self->callable);
- Py_CLEAR(self->restype);
- Py_CLEAR(self->checker);
- Py_CLEAR(self->errcheck);
- Py_CLEAR(self->argtypes);
- Py_CLEAR(self->converters);
- Py_CLEAR(self->paramflags);
- Py_CLEAR(self->thunk);
- return PyCData_clear((CDataObject *)self);
+ Py_CLEAR(self->callable);
+ Py_CLEAR(self->restype);
+ Py_CLEAR(self->checker);
+ Py_CLEAR(self->errcheck);
+ Py_CLEAR(self->argtypes);
+ Py_CLEAR(self->converters);
+ Py_CLEAR(self->paramflags);
+ Py_CLEAR(self->thunk);
+ return PyCData_clear((CDataObject *)self);
}
static void
PyCFuncPtr_dealloc(PyCFuncPtrObject *self)
{
- PyCFuncPtr_clear(self);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ PyCFuncPtr_clear(self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
PyCFuncPtr_repr(PyCFuncPtrObject *self)
{
#ifdef MS_WIN32
- if (self->index)
- return PyString_FromFormat("<COM method offset %d: %s at %p>",
- self->index - 0x1000,
- Py_TYPE(self)->tp_name,
- self);
+ if (self->index)
+ return PyString_FromFormat("<COM method offset %d: %s at %p>",
+ self->index - 0x1000,
+ Py_TYPE(self)->tp_name,
+ self);
#endif
- return PyString_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name,
- self);
+ return PyString_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name,
+ self);
}
static int
PyCFuncPtr_nonzero(PyCFuncPtrObject *self)
{
- return ((*(void **)self->b_ptr != NULL)
+ return ((*(void **)self->b_ptr != NULL)
#ifdef MS_WIN32
- || (self->index != 0)
+ || (self->index != 0)
#endif
- );
+ );
}
static PyNumberMethods PyCFuncPtr_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)PyCFuncPtr_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)PyCFuncPtr_nonzero, /* nb_nonzero */
};
PyTypeObject PyCFuncPtr_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.PyCFuncPtr",
- sizeof(PyCFuncPtrObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)PyCFuncPtr_repr, /* tp_repr */
- &PyCFuncPtr_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)PyCFuncPtr_call, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Function Pointer", /* tp_doc */
- (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */
- (inquiry)PyCFuncPtr_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- PyCFuncPtr_getsets, /* 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 */
- PyCFuncPtr_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.PyCFuncPtr",
+ sizeof(PyCFuncPtrObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)PyCFuncPtr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)PyCFuncPtr_repr, /* tp_repr */
+ &PyCFuncPtr_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)PyCFuncPtr_call, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Function Pointer", /* tp_doc */
+ (traverseproc)PyCFuncPtr_traverse, /* tp_traverse */
+ (inquiry)PyCFuncPtr_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ PyCFuncPtr_getsets, /* 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 */
+ PyCFuncPtr_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/*****************************************************************/
/*
Struct_Type
@@ -4042,61 +4042,61 @@ PyTypeObject PyCFuncPtr_Type = {
*/
static int
_init_pos_args(PyObject *self, PyTypeObject *type,
- PyObject *args, PyObject *kwds,
- int index)
+ PyObject *args, PyObject *kwds,
+ int index)
{
- StgDictObject *dict;
- PyObject *fields;
- int i;
-
- if (PyType_stgdict((PyObject *)type->tp_base)) {
- index = _init_pos_args(self, type->tp_base,
- args, kwds,
- index);
- if (index == -1)
- return -1;
- }
-
- dict = PyType_stgdict((PyObject *)type);
- fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
- if (fields == NULL)
- return index;
-
- for (i = 0;
- i < dict->length && (i+index) < PyTuple_GET_SIZE(args);
- ++i) {
- PyObject *pair = PySequence_GetItem(fields, i);
- PyObject *name, *val;
- int res;
- if (!pair)
- return -1;
- name = PySequence_GetItem(pair, 0);
- if (!name) {
- Py_DECREF(pair);
- return -1;
- }
- val = PyTuple_GET_ITEM(args, i + index);
- if (kwds && PyDict_GetItem(kwds, name)) {
- char *field = PyString_AsString(name);
- if (field == NULL) {
- PyErr_Clear();
- field = "???";
- }
- PyErr_Format(PyExc_TypeError,
- "duplicate values for field '%s'",
- field);
- Py_DECREF(pair);
- Py_DECREF(name);
- return -1;
- }
-
- res = PyObject_SetAttr(self, name, val);
- Py_DECREF(pair);
- Py_DECREF(name);
- if (res == -1)
- return -1;
- }
- return index + dict->length;
+ StgDictObject *dict;
+ PyObject *fields;
+ int i;
+
+ if (PyType_stgdict((PyObject *)type->tp_base)) {
+ index = _init_pos_args(self, type->tp_base,
+ args, kwds,
+ index);
+ if (index == -1)
+ return -1;
+ }
+
+ dict = PyType_stgdict((PyObject *)type);
+ fields = PyDict_GetItemString((PyObject *)dict, "_fields_");
+ if (fields == NULL)
+ return index;
+
+ for (i = 0;
+ i < dict->length && (i+index) < PyTuple_GET_SIZE(args);
+ ++i) {
+ PyObject *pair = PySequence_GetItem(fields, i);
+ PyObject *name, *val;
+ int res;
+ if (!pair)
+ return -1;
+ name = PySequence_GetItem(pair, 0);
+ if (!name) {
+ Py_DECREF(pair);
+ return -1;
+ }
+ val = PyTuple_GET_ITEM(args, i + index);
+ if (kwds && PyDict_GetItem(kwds, name)) {
+ char *field = PyString_AsString(name);
+ if (field == NULL) {
+ PyErr_Clear();
+ field = "???";
+ }
+ PyErr_Format(PyExc_TypeError,
+ "duplicate values for field '%s'",
+ field);
+ Py_DECREF(pair);
+ Py_DECREF(name);
+ return -1;
+ }
+
+ res = PyObject_SetAttr(self, name, val);
+ Py_DECREF(pair);
+ Py_DECREF(name);
+ if (res == -1)
+ return -1;
+ }
+ return index + dict->length;
}
static int
@@ -4105,119 +4105,119 @@ Struct_init(PyObject *self, PyObject *args, PyObject *kwds)
/* Optimization possible: Store the attribute names _fields_[x][0]
* in C accessible fields somewhere ?
*/
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_TypeError,
- "args not a tuple?");
- return -1;
- }
- if (PyTuple_GET_SIZE(args)) {
- int res = _init_pos_args(self, Py_TYPE(self),
- args, kwds, 0);
- if (res == -1)
- return -1;
- if (res < PyTuple_GET_SIZE(args)) {
- PyErr_SetString(PyExc_TypeError,
- "too many initializers");
- return -1;
- }
- }
-
- if (kwds) {
- PyObject *key, *value;
- Py_ssize_t pos = 0;
- while(PyDict_Next(kwds, &pos, &key, &value)) {
- if (-1 == PyObject_SetAttr(self, key, value))
- return -1;
- }
- }
- return 0;
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "args not a tuple?");
+ return -1;
+ }
+ if (PyTuple_GET_SIZE(args)) {
+ int res = _init_pos_args(self, Py_TYPE(self),
+ args, kwds, 0);
+ if (res == -1)
+ return -1;
+ if (res < PyTuple_GET_SIZE(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "too many initializers");
+ return -1;
+ }
+ }
+
+ if (kwds) {
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+ while(PyDict_Next(kwds, &pos, &key, &value)) {
+ if (-1 == PyObject_SetAttr(self, key, value))
+ return -1;
+ }
+ }
+ return 0;
}
static PyTypeObject Struct_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.Structure",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 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 */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Structure base class", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- Struct_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.Structure",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 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 */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Structure base class", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ Struct_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
static PyTypeObject Union_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.Union",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 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 */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "Union base class", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- Struct_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.Union",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 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 */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "Union base class", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ Struct_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCArray_Type
@@ -4225,463 +4225,463 @@ static PyTypeObject Union_Type = {
static int
Array_init(CDataObject *self, PyObject *args, PyObject *kw)
{
- Py_ssize_t i;
- Py_ssize_t n;
-
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_TypeError,
- "args not a tuple?");
- return -1;
- }
- n = PyTuple_GET_SIZE(args);
- for (i = 0; i < n; ++i) {
- PyObject *v;
- v = PyTuple_GET_ITEM(args, i);
- if (-1 == PySequence_SetItem((PyObject *)self, i, v))
- return -1;
- }
- return 0;
+ Py_ssize_t i;
+ Py_ssize_t n;
+
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "args not a tuple?");
+ return -1;
+ }
+ n = PyTuple_GET_SIZE(args);
+ for (i = 0; i < n; ++i) {
+ PyObject *v;
+ v = PyTuple_GET_ITEM(args, i);
+ if (-1 == PySequence_SetItem((PyObject *)self, i, v))
+ return -1;
+ }
+ return 0;
}
static PyObject *
Array_item(PyObject *_self, Py_ssize_t index)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t offset, size;
- StgDictObject *stgdict;
-
-
- if (index < 0 || index >= self->b_length) {
- PyErr_SetString(PyExc_IndexError,
- "invalid index");
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array instances */
- /* Would it be clearer if we got the item size from
- stgdict->proto's stgdict?
- */
- size = stgdict->size / stgdict->length;
- offset = index * size;
-
- return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
- index, size, self->b_ptr + offset);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t offset, size;
+ StgDictObject *stgdict;
+
+
+ if (index < 0 || index >= self->b_length) {
+ PyErr_SetString(PyExc_IndexError,
+ "invalid index");
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array instances */
+ /* Would it be clearer if we got the item size from
+ stgdict->proto's stgdict?
+ */
+ size = stgdict->size / stgdict->length;
+ offset = index * size;
+
+ return PyCData_get(stgdict->proto, stgdict->getfunc, (PyObject *)self,
+ index, size, self->b_ptr + offset);
}
static PyObject *
Array_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- CDataObject *self = (CDataObject *)_self;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- PyListObject *np;
- Py_ssize_t i, len;
-
- if (ilow < 0)
- ilow = 0;
- else if (ilow > self->b_length)
- ilow = self->b_length;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > self->b_length)
- ihigh = self->b_length;
- len = ihigh - ilow;
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array object instances */
- proto = stgdict->proto;
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* proto is the item type of the array, a ctypes
- type, so this cannot be NULL */
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *ptr = (char *)self->b_ptr;
- return PyString_FromStringAndSize(ptr + ilow, len);
+ CDataObject *self = (CDataObject *)_self;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ PyListObject *np;
+ Py_ssize_t i, len;
+
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > self->b_length)
+ ilow = self->b_length;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > self->b_length)
+ ihigh = self->b_length;
+ len = ihigh - ilow;
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array object instances */
+ proto = stgdict->proto;
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* proto is the item type of the array, a ctypes
+ type, so this cannot be NULL */
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ char *ptr = (char *)self->b_ptr;
+ return PyString_FromStringAndSize(ptr + ilow, len);
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- wchar_t *ptr = (wchar_t *)self->b_ptr;
- return PyUnicode_FromWideChar(ptr + ilow, len);
+ } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ wchar_t *ptr = (wchar_t *)self->b_ptr;
+ return PyUnicode_FromWideChar(ptr + ilow, len);
#endif
- }
+ }
- np = (PyListObject *) PyList_New(len);
- if (np == NULL)
- return NULL;
+ np = (PyListObject *) PyList_New(len);
+ if (np == NULL)
+ return NULL;
- for (i = 0; i < len; i++) {
- PyObject *v = Array_item(_self, i+ilow);
- PyList_SET_ITEM(np, i, v);
- }
- return (PyObject *)np;
+ for (i = 0; i < len; i++) {
+ PyObject *v = Array_item(_self, i+ilow);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return (PyObject *)np;
}
static PyObject *
Array_subscript(PyObject *_self, PyObject *item)
{
- CDataObject *self = (CDataObject *)_self;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += self->b_length;
- return Array_item(_self, i);
- }
- else if PySlice_Check(item) {
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- PyObject *np;
- Py_ssize_t start, stop, step, slicelen, cur, i;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- self->b_length, &start, &stop,
- &step, &slicelen) < 0) {
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array object instances */
- proto = stgdict->proto;
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* proto is the item type of the array, a
- ctypes type, so this cannot be NULL */
-
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *ptr = (char *)self->b_ptr;
- char *dest;
-
- if (slicelen <= 0)
- return PyString_FromString("");
- if (step == 1) {
- return PyString_FromStringAndSize(ptr + start,
- slicelen);
- }
- dest = (char *)PyMem_Malloc(slicelen);
-
- if (dest == NULL)
- return PyErr_NoMemory();
-
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- dest[i] = ptr[cur];
- }
-
- np = PyString_FromStringAndSize(dest, slicelen);
- PyMem_Free(dest);
- return np;
- }
+ CDataObject *self = (CDataObject *)_self;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += self->b_length;
+ return Array_item(_self, i);
+ }
+ else if PySlice_Check(item) {
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ PyObject *np;
+ Py_ssize_t start, stop, step, slicelen, cur, i;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ self->b_length, &start, &stop,
+ &step, &slicelen) < 0) {
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array object instances */
+ proto = stgdict->proto;
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* proto is the item type of the array, a
+ ctypes type, so this cannot be NULL */
+
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ char *ptr = (char *)self->b_ptr;
+ char *dest;
+
+ if (slicelen <= 0)
+ return PyString_FromString("");
+ if (step == 1) {
+ return PyString_FromStringAndSize(ptr + start,
+ slicelen);
+ }
+ dest = (char *)PyMem_Malloc(slicelen);
+
+ if (dest == NULL)
+ return PyErr_NoMemory();
+
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+
+ np = PyString_FromStringAndSize(dest, slicelen);
+ PyMem_Free(dest);
+ return np;
+ }
#ifdef CTYPES_UNICODE
- if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- wchar_t *ptr = (wchar_t *)self->b_ptr;
- wchar_t *dest;
-
- if (slicelen <= 0)
- return PyUnicode_FromUnicode(NULL, 0);
- if (step == 1) {
- return PyUnicode_FromWideChar(ptr + start,
- slicelen);
- }
-
- dest = (wchar_t *)PyMem_Malloc(
- slicelen * sizeof(wchar_t));
-
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- dest[i] = ptr[cur];
- }
-
- np = PyUnicode_FromWideChar(dest, slicelen);
- PyMem_Free(dest);
- return np;
- }
+ if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ wchar_t *ptr = (wchar_t *)self->b_ptr;
+ wchar_t *dest;
+
+ if (slicelen <= 0)
+ return PyUnicode_FromUnicode(NULL, 0);
+ if (step == 1) {
+ return PyUnicode_FromWideChar(ptr + start,
+ slicelen);
+ }
+
+ dest = (wchar_t *)PyMem_Malloc(
+ slicelen * sizeof(wchar_t));
+
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+
+ np = PyUnicode_FromWideChar(dest, slicelen);
+ PyMem_Free(dest);
+ return np;
+ }
#endif
- np = PyList_New(slicelen);
- if (np == NULL)
- return NULL;
-
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- PyObject *v = Array_item(_self, cur);
- PyList_SET_ITEM(np, i, v);
- }
- return np;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "indices must be integers");
- return NULL;
- }
+ np = PyList_New(slicelen);
+ if (np == NULL)
+ return NULL;
+
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ PyObject *v = Array_item(_self, cur);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return np;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "indices must be integers");
+ return NULL;
+ }
}
static int
Array_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t size, offset;
- StgDictObject *stgdict;
- char *ptr;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Array does not support item deletion");
- return -1;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for array object instances */
- if (index < 0 || index >= stgdict->length) {
- PyErr_SetString(PyExc_IndexError,
- "invalid index");
- return -1;
- }
- size = stgdict->size / stgdict->length;
- offset = index * size;
- ptr = self->b_ptr + offset;
-
- return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
- index, size, ptr);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t size, offset;
+ StgDictObject *stgdict;
+ char *ptr;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Array does not support item deletion");
+ return -1;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for array object instances */
+ if (index < 0 || index >= stgdict->length) {
+ PyErr_SetString(PyExc_IndexError,
+ "invalid index");
+ return -1;
+ }
+ size = stgdict->size / stgdict->length;
+ offset = index * size;
+ ptr = self->b_ptr + offset;
+
+ return PyCData_set((PyObject *)self, stgdict->proto, stgdict->setfunc, value,
+ index, size, ptr);
}
static int
Array_ass_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t i, len;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Array does not support item deletion");
- return -1;
- }
-
- if (ilow < 0)
- ilow = 0;
- else if (ilow > self->b_length)
- ilow = self->b_length;
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > self->b_length)
- ihigh = self->b_length;
-
- len = PySequence_Length(value);
- if (len != ihigh - ilow) {
- PyErr_SetString(PyExc_ValueError,
- "Can only assign sequence of same size");
- return -1;
- }
- for (i = 0; i < len; i++) {
- PyObject *item = PySequence_GetItem(value, i);
- int result;
- if (item == NULL)
- return -1;
- result = Array_ass_item(_self, i+ilow, item);
- Py_DECREF(item);
- if (result == -1)
- return -1;
- }
- return 0;
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t i, len;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Array does not support item deletion");
+ return -1;
+ }
+
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > self->b_length)
+ ilow = self->b_length;
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > self->b_length)
+ ihigh = self->b_length;
+
+ len = PySequence_Length(value);
+ if (len != ihigh - ilow) {
+ PyErr_SetString(PyExc_ValueError,
+ "Can only assign sequence of same size");
+ return -1;
+ }
+ for (i = 0; i < len; i++) {
+ PyObject *item = PySequence_GetItem(value, i);
+ int result;
+ if (item == NULL)
+ return -1;
+ result = Array_ass_item(_self, i+ilow, item);
+ Py_DECREF(item);
+ if (result == -1)
+ return -1;
+ }
+ return 0;
}
static int
Array_ass_subscript(PyObject *_self, PyObject *item, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Array does not support item deletion");
- return -1;
- }
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += self->b_length;
- return Array_ass_item(_self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- self->b_length, &start, &stop,
- &step, &slicelen) < 0) {
- return -1;
- }
- if ((step < 0 && start < stop) ||
- (step > 0 && start > stop))
- stop = start;
-
- otherlen = PySequence_Length(value);
- if (otherlen != slicelen) {
- PyErr_SetString(PyExc_ValueError,
- "Can only assign sequence of same size");
- return -1;
- }
- for (cur = start, i = 0; i < otherlen; cur += step, i++) {
- PyObject *item = PySequence_GetItem(value, i);
- int result;
- if (item == NULL)
- return -1;
- result = Array_ass_item(_self, cur, item);
- Py_DECREF(item);
- if (result == -1)
- return -1;
- }
- return 0;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "indices must be integer");
- return -1;
- }
+ CDataObject *self = (CDataObject *)_self;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Array does not support item deletion");
+ return -1;
+ }
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += self->b_length;
+ return Array_ass_item(_self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen, otherlen, i, cur;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ self->b_length, &start, &stop,
+ &step, &slicelen) < 0) {
+ return -1;
+ }
+ if ((step < 0 && start < stop) ||
+ (step > 0 && start > stop))
+ stop = start;
+
+ otherlen = PySequence_Length(value);
+ if (otherlen != slicelen) {
+ PyErr_SetString(PyExc_ValueError,
+ "Can only assign sequence of same size");
+ return -1;
+ }
+ for (cur = start, i = 0; i < otherlen; cur += step, i++) {
+ PyObject *item = PySequence_GetItem(value, i);
+ int result;
+ if (item == NULL)
+ return -1;
+ result = Array_ass_item(_self, cur, item);
+ Py_DECREF(item);
+ if (result == -1)
+ return -1;
+ }
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "indices must be integer");
+ return -1;
+ }
}
static Py_ssize_t
Array_length(PyObject *_self)
{
- CDataObject *self = (CDataObject *)_self;
- return self->b_length;
+ CDataObject *self = (CDataObject *)_self;
+ return self->b_length;
}
static PySequenceMethods Array_as_sequence = {
- Array_length, /* sq_length; */
- 0, /* sq_concat; */
- 0, /* sq_repeat; */
- Array_item, /* sq_item; */
- Array_slice, /* sq_slice; */
- Array_ass_item, /* sq_ass_item; */
- Array_ass_slice, /* sq_ass_slice; */
- 0, /* sq_contains; */
-
- 0, /* sq_inplace_concat; */
- 0, /* sq_inplace_repeat; */
+ Array_length, /* sq_length; */
+ 0, /* sq_concat; */
+ 0, /* sq_repeat; */
+ Array_item, /* sq_item; */
+ Array_slice, /* sq_slice; */
+ Array_ass_item, /* sq_ass_item; */
+ Array_ass_slice, /* sq_ass_slice; */
+ 0, /* sq_contains; */
+
+ 0, /* sq_inplace_concat; */
+ 0, /* sq_inplace_repeat; */
};
static PyMappingMethods Array_as_mapping = {
- Array_length,
- Array_subscript,
- Array_ass_subscript,
+ Array_length,
+ Array_subscript,
+ Array_ass_subscript,
};
PyTypeObject PyCArray_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.Array",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &Array_as_sequence, /* tp_as_sequence */
- &Array_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Array_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.Array",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &Array_as_sequence, /* tp_as_sequence */
+ &Array_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Array_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
PyObject *
PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length)
{
- static PyObject *cache;
- PyObject *key;
- PyObject *result;
- char name[256];
- PyObject *len;
-
- if (cache == NULL) {
- cache = PyDict_New();
- if (cache == NULL)
- return NULL;
- }
- len = PyInt_FromSsize_t(length);
- if (len == NULL)
- return NULL;
- key = PyTuple_Pack(2, itemtype, len);
- Py_DECREF(len);
- if (!key)
- return NULL;
- result = PyDict_GetItemProxy(cache, key);
- if (result) {
- Py_INCREF(result);
- Py_DECREF(key);
- return result;
- }
-
- if (!PyType_Check(itemtype)) {
- PyErr_SetString(PyExc_TypeError,
- "Expected a type object");
- return NULL;
- }
+ static PyObject *cache;
+ PyObject *key;
+ PyObject *result;
+ char name[256];
+ PyObject *len;
+
+ if (cache == NULL) {
+ cache = PyDict_New();
+ if (cache == NULL)
+ return NULL;
+ }
+ len = PyInt_FromSsize_t(length);
+ if (len == NULL)
+ return NULL;
+ key = PyTuple_Pack(2, itemtype, len);
+ Py_DECREF(len);
+ if (!key)
+ return NULL;
+ result = PyDict_GetItemProxy(cache, key);
+ if (result) {
+ Py_INCREF(result);
+ Py_DECREF(key);
+ return result;
+ }
+
+ if (!PyType_Check(itemtype)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected a type object");
+ return NULL;
+ }
#ifdef MS_WIN64
- sprintf(name, "%.200s_Array_%Id",
- ((PyTypeObject *)itemtype)->tp_name, length);
+ sprintf(name, "%.200s_Array_%Id",
+ ((PyTypeObject *)itemtype)->tp_name, length);
#else
- sprintf(name, "%.200s_Array_%ld",
- ((PyTypeObject *)itemtype)->tp_name, (long)length);
+ sprintf(name, "%.200s_Array_%ld",
+ ((PyTypeObject *)itemtype)->tp_name, (long)length);
#endif
- result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type,
+ result = PyObject_CallFunction((PyObject *)&PyCArrayType_Type,
#if (PY_VERSION_HEX < 0x02050000)
- "s(O){s:i,s:O}",
+ "s(O){s:i,s:O}",
#else
- "s(O){s:n,s:O}",
+ "s(O){s:n,s:O}",
#endif
- name,
- &PyCArray_Type,
- "_length_",
- length,
- "_type_",
- itemtype
- );
- if (result == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- if (-1 == PyDict_SetItemProxy(cache, key, result)) {
- Py_DECREF(key);
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(key);
- return result;
+ name,
+ &PyCArray_Type,
+ "_length_",
+ length,
+ "_type_",
+ itemtype
+ );
+ if (result == NULL) {
+ Py_DECREF(key);
+ return NULL;
+ }
+ if (-1 == PyDict_SetItemProxy(cache, key, result)) {
+ Py_DECREF(key);
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(key);
+ return result;
}
-
+
/******************************************************************/
/*
Simple_Type
@@ -4690,167 +4690,167 @@ PyCArrayType_from_ctype(PyObject *itemtype, Py_ssize_t length)
static int
Simple_set_value(CDataObject *self, PyObject *value)
{
- PyObject *result;
- StgDictObject *dict = PyObject_stgdict((PyObject *)self);
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
- assert(dict); /* Cannot be NULL for CDataObject instances */
- assert(dict->setfunc);
- result = dict->setfunc(self->b_ptr, value, dict->size);
- if (!result)
- return -1;
-
- /* consumes the refcount the setfunc returns */
- return KeepRef(self, 0, result);
+ PyObject *result;
+ StgDictObject *dict = PyObject_stgdict((PyObject *)self);
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ assert(dict->setfunc);
+ result = dict->setfunc(self->b_ptr, value, dict->size);
+ if (!result)
+ return -1;
+
+ /* consumes the refcount the setfunc returns */
+ return KeepRef(self, 0, result);
}
static int
Simple_init(CDataObject *self, PyObject *args, PyObject *kw)
{
- PyObject *value = NULL;
- if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
- return -1;
- if (value)
- return Simple_set_value(self, value);
- return 0;
+ PyObject *value = NULL;
+ if (!PyArg_UnpackTuple(args, "__init__", 0, 1, &value))
+ return -1;
+ if (value)
+ return Simple_set_value(self, value);
+ return 0;
}
static PyObject *
Simple_get_value(CDataObject *self)
{
- StgDictObject *dict;
- dict = PyObject_stgdict((PyObject *)self);
- assert(dict); /* Cannot be NULL for CDataObject instances */
- assert(dict->getfunc);
- return dict->getfunc(self->b_ptr, self->b_size);
+ StgDictObject *dict;
+ dict = PyObject_stgdict((PyObject *)self);
+ assert(dict); /* Cannot be NULL for CDataObject instances */
+ assert(dict->getfunc);
+ return dict->getfunc(self->b_ptr, self->b_size);
}
static PyGetSetDef Simple_getsets[] = {
- { "value", (getter)Simple_get_value, (setter)Simple_set_value,
- "current value", NULL },
- { NULL, NULL }
+ { "value", (getter)Simple_get_value, (setter)Simple_set_value,
+ "current value", NULL },
+ { NULL, NULL }
};
static PyObject *
Simple_from_outparm(PyObject *self, PyObject *args)
{
- if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) {
- Py_INCREF(self);
- return self;
- }
- /* call stgdict->getfunc */
- return Simple_get_value((CDataObject *)self);
+ if (_ctypes_simple_instance((PyObject *)Py_TYPE(self))) {
+ Py_INCREF(self);
+ return self;
+ }
+ /* call stgdict->getfunc */
+ return Simple_get_value((CDataObject *)self);
}
static PyMethodDef Simple_methods[] = {
- { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, },
- { NULL, NULL },
+ { "__ctypes_from_outparam__", Simple_from_outparm, METH_NOARGS, },
+ { NULL, NULL },
};
static int Simple_nonzero(CDataObject *self)
{
- return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
+ return memcmp(self->b_ptr, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0", self->b_size);
}
static PyNumberMethods Simple_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)Simple_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)Simple_nonzero, /* nb_nonzero */
};
/* "%s(%s)" % (self.__class__.__name__, self.value) */
static PyObject *
Simple_repr(CDataObject *self)
{
- PyObject *val, *name, *args, *result;
- static PyObject *format;
-
- if (Py_TYPE(self)->tp_base != &Simple_Type) {
- return PyString_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name, self);
- }
-
- if (format == NULL) {
- format = PyString_InternFromString("%s(%r)");
- if (format == NULL)
- return NULL;
- }
-
- val = Simple_get_value(self);
- if (val == NULL)
- return NULL;
-
- name = PyString_FromString(Py_TYPE(self)->tp_name);
- if (name == NULL) {
- Py_DECREF(val);
- return NULL;
- }
-
- args = PyTuple_Pack(2, name, val);
- Py_DECREF(name);
- Py_DECREF(val);
- if (args == NULL)
- return NULL;
-
- result = PyString_Format(format, args);
- Py_DECREF(args);
- return result;
+ PyObject *val, *name, *args, *result;
+ static PyObject *format;
+
+ if (Py_TYPE(self)->tp_base != &Simple_Type) {
+ return PyString_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name, self);
+ }
+
+ if (format == NULL) {
+ format = PyString_InternFromString("%s(%r)");
+ if (format == NULL)
+ return NULL;
+ }
+
+ val = Simple_get_value(self);
+ if (val == NULL)
+ return NULL;
+
+ name = PyString_FromString(Py_TYPE(self)->tp_name);
+ if (name == NULL) {
+ Py_DECREF(val);
+ return NULL;
+ }
+
+ args = PyTuple_Pack(2, name, val);
+ Py_DECREF(name);
+ Py_DECREF(val);
+ if (args == NULL)
+ return NULL;
+
+ result = PyString_Format(format, args);
+ Py_DECREF(args);
+ return result;
}
static PyTypeObject Simple_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._SimpleCData",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)&Simple_repr, /* tp_repr */
- &Simple_as_number, /* 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 */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Simple_methods, /* tp_methods */
- 0, /* tp_members */
- Simple_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Simple_init, /* tp_init */
- 0, /* tp_alloc */
- GenericPyCData_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes._SimpleCData",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)&Simple_repr, /* tp_repr */
+ &Simple_as_number, /* 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 */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Simple_methods, /* tp_methods */
+ 0, /* tp_members */
+ Simple_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Simple_init, /* tp_init */
+ 0, /* tp_alloc */
+ GenericPyCData_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
PyCPointer_Type
@@ -4858,420 +4858,420 @@ static PyTypeObject Simple_Type = {
static PyObject *
Pointer_item(PyObject *_self, Py_ssize_t index)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t size;
- Py_ssize_t offset;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
-
- if (*(void **)self->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL pointer access");
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for pointer object instances */
-
- proto = stgdict->proto;
- assert(proto);
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* proto is the item type of the pointer, a ctypes
- type, so this cannot be NULL */
-
- size = itemdict->size;
- offset = index * itemdict->size;
-
- return PyCData_get(proto, stgdict->getfunc, (PyObject *)self,
- index, size, (*(char **)self->b_ptr) + offset);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t size;
+ Py_ssize_t offset;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+
+ if (*(void **)self->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL pointer access");
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for pointer object instances */
+
+ proto = stgdict->proto;
+ assert(proto);
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* proto is the item type of the pointer, a ctypes
+ type, so this cannot be NULL */
+
+ size = itemdict->size;
+ offset = index * itemdict->size;
+
+ return PyCData_get(proto, stgdict->getfunc, (PyObject *)self,
+ index, size, (*(char **)self->b_ptr) + offset);
}
static int
Pointer_ass_item(PyObject *_self, Py_ssize_t index, PyObject *value)
{
- CDataObject *self = (CDataObject *)_self;
- Py_ssize_t size;
- Py_ssize_t offset;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Pointer does not support item deletion");
- return -1;
- }
-
- if (*(void **)self->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL pointer access");
- return -1;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
-
- proto = stgdict->proto;
- assert(proto);
-
- itemdict = PyType_stgdict(proto);
- assert(itemdict); /* Cannot be NULL because the itemtype of a pointer
- is always a ctypes type */
-
- size = itemdict->size;
- offset = index * itemdict->size;
-
- return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value,
- index, size, (*(char **)self->b_ptr) + offset);
+ CDataObject *self = (CDataObject *)_self;
+ Py_ssize_t size;
+ Py_ssize_t offset;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer does not support item deletion");
+ return -1;
+ }
+
+ if (*(void **)self->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL pointer access");
+ return -1;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+
+ proto = stgdict->proto;
+ assert(proto);
+
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict); /* Cannot be NULL because the itemtype of a pointer
+ is always a ctypes type */
+
+ size = itemdict->size;
+ offset = index * itemdict->size;
+
+ return PyCData_set((PyObject *)self, proto, stgdict->setfunc, value,
+ index, size, (*(char **)self->b_ptr) + offset);
}
static PyObject *
Pointer_get_contents(CDataObject *self, void *closure)
{
- StgDictObject *stgdict;
-
- if (*(void **)self->b_ptr == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "NULL pointer access");
- return NULL;
- }
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
- return PyCData_FromBaseObj(stgdict->proto,
- (PyObject *)self, 0,
- *(void **)self->b_ptr);
+ StgDictObject *stgdict;
+
+ if (*(void **)self->b_ptr == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "NULL pointer access");
+ return NULL;
+ }
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+ return PyCData_FromBaseObj(stgdict->proto,
+ (PyObject *)self, 0,
+ *(void **)self->b_ptr);
}
static int
Pointer_set_contents(CDataObject *self, PyObject *value, void *closure)
{
- StgDictObject *stgdict;
- CDataObject *dst;
- PyObject *keep;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "Pointer does not support item deletion");
- return -1;
- }
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
- assert(stgdict->proto);
- if (!CDataObject_Check(value)
- || 0 == PyObject_IsInstance(value, stgdict->proto)) {
- /* XXX PyObject_IsInstance could return -1! */
- PyErr_Format(PyExc_TypeError,
- "expected %s instead of %s",
- ((PyTypeObject *)(stgdict->proto))->tp_name,
- Py_TYPE(value)->tp_name);
- return -1;
- }
-
- dst = (CDataObject *)value;
- *(void **)self->b_ptr = dst->b_ptr;
-
- /*
- A Pointer instance must keep a the value it points to alive. So, a
- pointer instance has b_length set to 2 instead of 1, and we set
- 'value' itself as the second item of the b_objects list, additionally.
- */
- Py_INCREF(value);
- if (-1 == KeepRef(self, 1, value))
- return -1;
-
- keep = GetKeepedObjects(dst);
- Py_INCREF(keep);
- return KeepRef(self, 0, keep);
+ StgDictObject *stgdict;
+ CDataObject *dst;
+ PyObject *keep;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer does not support item deletion");
+ return -1;
+ }
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+ assert(stgdict->proto);
+ if (!CDataObject_Check(value)
+ || 0 == PyObject_IsInstance(value, stgdict->proto)) {
+ /* XXX PyObject_IsInstance could return -1! */
+ PyErr_Format(PyExc_TypeError,
+ "expected %s instead of %s",
+ ((PyTypeObject *)(stgdict->proto))->tp_name,
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+
+ dst = (CDataObject *)value;
+ *(void **)self->b_ptr = dst->b_ptr;
+
+ /*
+ A Pointer instance must keep a the value it points to alive. So, a
+ pointer instance has b_length set to 2 instead of 1, and we set
+ 'value' itself as the second item of the b_objects list, additionally.
+ */
+ Py_INCREF(value);
+ if (-1 == KeepRef(self, 1, value))
+ return -1;
+
+ keep = GetKeepedObjects(dst);
+ Py_INCREF(keep);
+ return KeepRef(self, 0, keep);
}
static PyGetSetDef Pointer_getsets[] = {
- { "contents", (getter)Pointer_get_contents,
- (setter)Pointer_set_contents,
- "the object this pointer points to (read-write)", NULL },
- { NULL, NULL }
+ { "contents", (getter)Pointer_get_contents,
+ (setter)Pointer_set_contents,
+ "the object this pointer points to (read-write)", NULL },
+ { NULL, NULL }
};
static int
Pointer_init(CDataObject *self, PyObject *args, PyObject *kw)
{
- PyObject *value = NULL;
+ PyObject *value = NULL;
- if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
- return -1;
- if (value == NULL)
- return 0;
- return Pointer_set_contents(self, value, NULL);
+ if (!PyArg_UnpackTuple(args, "POINTER", 0, 1, &value))
+ return -1;
+ if (value == NULL)
+ return 0;
+ return Pointer_set_contents(self, value, NULL);
}
static PyObject *
Pointer_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- StgDictObject *dict = PyType_stgdict((PyObject *)type);
- if (!dict || !dict->proto) {
- PyErr_SetString(PyExc_TypeError,
- "Cannot create instance: has no _type_");
- return NULL;
- }
- return GenericPyCData_new(type, args, kw);
+ StgDictObject *dict = PyType_stgdict((PyObject *)type);
+ if (!dict || !dict->proto) {
+ PyErr_SetString(PyExc_TypeError,
+ "Cannot create instance: has no _type_");
+ return NULL;
+ }
+ return GenericPyCData_new(type, args, kw);
}
static PyObject *
Pointer_slice(PyObject *_self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- CDataObject *self = (CDataObject *)_self;
- PyListObject *np;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- Py_ssize_t i, len;
-
- if (ilow < 0)
- ilow = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- len = ihigh - ilow;
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL fr pointer instances */
- proto = stgdict->proto;
- assert(proto);
- itemdict = PyType_stgdict(proto);
- assert(itemdict);
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *ptr = *(char **)self->b_ptr;
- return PyString_FromStringAndSize(ptr + ilow, len);
+ CDataObject *self = (CDataObject *)_self;
+ PyListObject *np;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ Py_ssize_t i, len;
+
+ if (ilow < 0)
+ ilow = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ len = ihigh - ilow;
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL fr pointer instances */
+ proto = stgdict->proto;
+ assert(proto);
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict);
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ char *ptr = *(char **)self->b_ptr;
+ return PyString_FromStringAndSize(ptr + ilow, len);
#ifdef CTYPES_UNICODE
- } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- wchar_t *ptr = *(wchar_t **)self->b_ptr;
- return PyUnicode_FromWideChar(ptr + ilow, len);
+ } else if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ wchar_t *ptr = *(wchar_t **)self->b_ptr;
+ return PyUnicode_FromWideChar(ptr + ilow, len);
#endif
- }
+ }
- np = (PyListObject *) PyList_New(len);
- if (np == NULL)
- return NULL;
+ np = (PyListObject *) PyList_New(len);
+ if (np == NULL)
+ return NULL;
- for (i = 0; i < len; i++) {
- PyObject *v = Pointer_item(_self, i+ilow);
- PyList_SET_ITEM(np, i, v);
- }
- return (PyObject *)np;
+ for (i = 0; i < len; i++) {
+ PyObject *v = Pointer_item(_self, i+ilow);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return (PyObject *)np;
}
static PyObject *
Pointer_subscript(PyObject *_self, PyObject *item)
{
- CDataObject *self = (CDataObject *)_self;
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- return Pointer_item(_self, i);
- }
- else if (PySlice_Check(item)) {
- PySliceObject *slice = (PySliceObject *)item;
- Py_ssize_t start, stop, step;
- PyObject *np;
- StgDictObject *stgdict, *itemdict;
- PyObject *proto;
- Py_ssize_t i, len, cur;
-
- /* Since pointers have no length, and we want to apply
- different semantics to negative indices than normal
- slicing, we have to dissect the slice object ourselves.*/
- if (slice->step == Py_None) {
- step = 1;
- }
- else {
- step = PyNumber_AsSsize_t(slice->step,
- PyExc_ValueError);
- if (step == -1 && PyErr_Occurred())
- return NULL;
- if (step == 0) {
- PyErr_SetString(PyExc_ValueError,
- "slice step cannot be zero");
- return NULL;
- }
- }
- if (slice->start == Py_None) {
- if (step < 0) {
- PyErr_SetString(PyExc_ValueError,
- "slice start is required "
- "for step < 0");
- return NULL;
- }
- start = 0;
- }
- else {
- start = PyNumber_AsSsize_t(slice->start,
- PyExc_ValueError);
- if (start == -1 && PyErr_Occurred())
- return NULL;
- }
- if (slice->stop == Py_None) {
- PyErr_SetString(PyExc_ValueError,
- "slice stop is required");
- return NULL;
- }
- stop = PyNumber_AsSsize_t(slice->stop,
- PyExc_ValueError);
- if (stop == -1 && PyErr_Occurred())
- return NULL;
- if ((step > 0 && start > stop) ||
- (step < 0 && start < stop))
- len = 0;
- else if (step > 0)
- len = (stop - start - 1) / step + 1;
- else
- len = (stop - start + 1) / step + 1;
-
- stgdict = PyObject_stgdict((PyObject *)self);
- assert(stgdict); /* Cannot be NULL for pointer instances */
- proto = stgdict->proto;
- assert(proto);
- itemdict = PyType_stgdict(proto);
- assert(itemdict);
- if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- char *ptr = *(char **)self->b_ptr;
- char *dest;
-
- if (len <= 0)
- return PyString_FromString("");
- if (step == 1) {
- return PyString_FromStringAndSize(ptr + start,
- len);
- }
- dest = (char *)PyMem_Malloc(len);
- if (dest == NULL)
- return PyErr_NoMemory();
- for (cur = start, i = 0; i < len; cur += step, i++) {
- dest[i] = ptr[cur];
- }
- np = PyString_FromStringAndSize(dest, len);
- PyMem_Free(dest);
- return np;
- }
+ CDataObject *self = (CDataObject *)_self;
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ return Pointer_item(_self, i);
+ }
+ else if (PySlice_Check(item)) {
+ PySliceObject *slice = (PySliceObject *)item;
+ Py_ssize_t start, stop, step;
+ PyObject *np;
+ StgDictObject *stgdict, *itemdict;
+ PyObject *proto;
+ Py_ssize_t i, len, cur;
+
+ /* Since pointers have no length, and we want to apply
+ different semantics to negative indices than normal
+ slicing, we have to dissect the slice object ourselves.*/
+ if (slice->step == Py_None) {
+ step = 1;
+ }
+ else {
+ step = PyNumber_AsSsize_t(slice->step,
+ PyExc_ValueError);
+ if (step == -1 && PyErr_Occurred())
+ return NULL;
+ if (step == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice step cannot be zero");
+ return NULL;
+ }
+ }
+ if (slice->start == Py_None) {
+ if (step < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice start is required "
+ "for step < 0");
+ return NULL;
+ }
+ start = 0;
+ }
+ else {
+ start = PyNumber_AsSsize_t(slice->start,
+ PyExc_ValueError);
+ if (start == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ if (slice->stop == Py_None) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice stop is required");
+ return NULL;
+ }
+ stop = PyNumber_AsSsize_t(slice->stop,
+ PyExc_ValueError);
+ if (stop == -1 && PyErr_Occurred())
+ return NULL;
+ if ((step > 0 && start > stop) ||
+ (step < 0 && start < stop))
+ len = 0;
+ else if (step > 0)
+ len = (stop - start - 1) / step + 1;
+ else
+ len = (stop - start + 1) / step + 1;
+
+ stgdict = PyObject_stgdict((PyObject *)self);
+ assert(stgdict); /* Cannot be NULL for pointer instances */
+ proto = stgdict->proto;
+ assert(proto);
+ itemdict = PyType_stgdict(proto);
+ assert(itemdict);
+ if (itemdict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ char *ptr = *(char **)self->b_ptr;
+ char *dest;
+
+ if (len <= 0)
+ return PyString_FromString("");
+ if (step == 1) {
+ return PyString_FromStringAndSize(ptr + start,
+ len);
+ }
+ dest = (char *)PyMem_Malloc(len);
+ if (dest == NULL)
+ return PyErr_NoMemory();
+ for (cur = start, i = 0; i < len; cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+ np = PyString_FromStringAndSize(dest, len);
+ PyMem_Free(dest);
+ return np;
+ }
#ifdef CTYPES_UNICODE
- if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- wchar_t *ptr = *(wchar_t **)self->b_ptr;
- wchar_t *dest;
-
- if (len <= 0)
- return PyUnicode_FromUnicode(NULL, 0);
- if (step == 1) {
- return PyUnicode_FromWideChar(ptr + start,
- len);
- }
- dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t));
- if (dest == NULL)
- return PyErr_NoMemory();
- for (cur = start, i = 0; i < len; cur += step, i++) {
- dest[i] = ptr[cur];
- }
- np = PyUnicode_FromWideChar(dest, len);
- PyMem_Free(dest);
- return np;
- }
+ if (itemdict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ wchar_t *ptr = *(wchar_t **)self->b_ptr;
+ wchar_t *dest;
+
+ if (len <= 0)
+ return PyUnicode_FromUnicode(NULL, 0);
+ if (step == 1) {
+ return PyUnicode_FromWideChar(ptr + start,
+ len);
+ }
+ dest = (wchar_t *)PyMem_Malloc(len * sizeof(wchar_t));
+ if (dest == NULL)
+ return PyErr_NoMemory();
+ for (cur = start, i = 0; i < len; cur += step, i++) {
+ dest[i] = ptr[cur];
+ }
+ np = PyUnicode_FromWideChar(dest, len);
+ PyMem_Free(dest);
+ return np;
+ }
#endif
- np = PyList_New(len);
- if (np == NULL)
- return NULL;
-
- for (cur = start, i = 0; i < len; cur += step, i++) {
- PyObject *v = Pointer_item(_self, cur);
- PyList_SET_ITEM(np, i, v);
- }
- return np;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "Pointer indices must be integer");
- return NULL;
- }
+ np = PyList_New(len);
+ if (np == NULL)
+ return NULL;
+
+ for (cur = start, i = 0; i < len; cur += step, i++) {
+ PyObject *v = Pointer_item(_self, cur);
+ PyList_SET_ITEM(np, i, v);
+ }
+ return np;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "Pointer indices must be integer");
+ return NULL;
+ }
}
static PySequenceMethods Pointer_as_sequence = {
- 0, /* inquiry sq_length; */
- 0, /* binaryfunc sq_concat; */
- 0, /* intargfunc sq_repeat; */
- Pointer_item, /* intargfunc sq_item; */
- Pointer_slice, /* intintargfunc sq_slice; */
- Pointer_ass_item, /* intobjargproc sq_ass_item; */
- 0, /* intintobjargproc sq_ass_slice; */
- 0, /* objobjproc sq_contains; */
- /* Added in release 2.0 */
- 0, /* binaryfunc sq_inplace_concat; */
- 0, /* intargfunc sq_inplace_repeat; */
+ 0, /* inquiry sq_length; */
+ 0, /* binaryfunc sq_concat; */
+ 0, /* intargfunc sq_repeat; */
+ Pointer_item, /* intargfunc sq_item; */
+ Pointer_slice, /* intintargfunc sq_slice; */
+ Pointer_ass_item, /* intobjargproc sq_ass_item; */
+ 0, /* intintobjargproc sq_ass_slice; */
+ 0, /* objobjproc sq_contains; */
+ /* Added in release 2.0 */
+ 0, /* binaryfunc sq_inplace_concat; */
+ 0, /* intargfunc sq_inplace_repeat; */
};
static PyMappingMethods Pointer_as_mapping = {
- 0,
- Pointer_subscript,
+ 0,
+ Pointer_subscript,
};
static int
Pointer_nonzero(CDataObject *self)
{
- return (*(void **)self->b_ptr != NULL);
+ return (*(void **)self->b_ptr != NULL);
}
static PyNumberMethods Pointer_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)Pointer_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)Pointer_nonzero, /* nb_nonzero */
};
PyTypeObject PyCPointer_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes._Pointer",
- sizeof(CDataObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- &Pointer_as_number, /* tp_as_number */
- &Pointer_as_sequence, /* tp_as_sequence */
- &Pointer_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- &PyCData_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
- "XXX to be provided", /* tp_doc */
- (traverseproc)PyCData_traverse, /* tp_traverse */
- (inquiry)PyCData_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- Pointer_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)Pointer_init, /* tp_init */
- 0, /* tp_alloc */
- Pointer_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes._Pointer",
+ sizeof(CDataObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ &Pointer_as_number, /* tp_as_number */
+ &Pointer_as_sequence, /* tp_as_sequence */
+ &Pointer_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ &PyCData_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ "XXX to be provided", /* tp_doc */
+ (traverseproc)PyCData_traverse, /* tp_traverse */
+ (inquiry)PyCData_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ Pointer_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)Pointer_init, /* tp_init */
+ 0, /* tp_alloc */
+ Pointer_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
* Module initialization.
@@ -5292,78 +5292,78 @@ comerror_init(PyObject *self, PyObject *args)
int status;
if (!PyArg_ParseTuple(args, "OOOO:COMError", &self, &hresult, &text, &details))
- return NULL;
+ return NULL;
a = PySequence_GetSlice(args, 1, PySequence_Size(args));
if (!a)
- return NULL;
+ return NULL;
status = PyObject_SetAttrString(self, "args", a);
Py_DECREF(a);
if (status < 0)
- return NULL;
+ return NULL;
if (PyObject_SetAttrString(self, "hresult", hresult) < 0)
- return NULL;
+ return NULL;
if (PyObject_SetAttrString(self, "text", text) < 0)
- return NULL;
+ return NULL;
if (PyObject_SetAttrString(self, "details", details) < 0)
- return NULL;
+ return NULL;
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef comerror_methods[] = {
- { "__init__", comerror_init, METH_VARARGS },
- { NULL, NULL },
+ { "__init__", comerror_init, METH_VARARGS },
+ { NULL, NULL },
};
static int
create_comerror(void)
{
- PyObject *dict = PyDict_New();
- PyMethodDef *methods = comerror_methods;
- PyObject *s;
- int status;
-
- if (dict == NULL)
- return -1;
-
- while (methods->ml_name) {
- /* get a wrapper for the built-in function */
- PyObject *func = PyCFunction_New(methods, NULL);
- PyObject *meth;
- if (func == NULL)
- goto error;
- meth = PyMethod_New(func, NULL, ComError);
- Py_DECREF(func);
- if (meth == NULL)
- goto error;
- PyDict_SetItemString(dict, methods->ml_name, meth);
- Py_DECREF(meth);
- ++methods;
- }
-
- s = PyString_FromString(comerror_doc);
- if (s == NULL)
- goto error;
- status = PyDict_SetItemString(dict, "__doc__", s);
- Py_DECREF(s);
- if (status == -1)
- goto error;
-
- ComError = PyErr_NewException("_ctypes.COMError",
- NULL,
- dict);
- if (ComError == NULL)
- goto error;
-
- return 0;
+ PyObject *dict = PyDict_New();
+ PyMethodDef *methods = comerror_methods;
+ PyObject *s;
+ int status;
+
+ if (dict == NULL)
+ return -1;
+
+ while (methods->ml_name) {
+ /* get a wrapper for the built-in function */
+ PyObject *func = PyCFunction_New(methods, NULL);
+ PyObject *meth;
+ if (func == NULL)
+ goto error;
+ meth = PyMethod_New(func, NULL, ComError);
+ Py_DECREF(func);
+ if (meth == NULL)
+ goto error;
+ PyDict_SetItemString(dict, methods->ml_name, meth);
+ Py_DECREF(meth);
+ ++methods;
+ }
+
+ s = PyString_FromString(comerror_doc);
+ if (s == NULL)
+ goto error;
+ status = PyDict_SetItemString(dict, "__doc__", s);
+ Py_DECREF(s);
+ if (status == -1)
+ goto error;
+
+ ComError = PyErr_NewException("_ctypes.COMError",
+ NULL,
+ dict);
+ if (ComError == NULL)
+ goto error;
+
+ return 0;
error:
- Py_DECREF(dict);
- return -1;
+ Py_DECREF(dict);
+ return -1;
}
#endif
@@ -5371,246 +5371,246 @@ create_comerror(void)
static PyObject *
string_at(const char *ptr, int size)
{
- if (size == -1)
- return PyString_FromString(ptr);
- return PyString_FromStringAndSize(ptr, size);
+ if (size == -1)
+ return PyString_FromString(ptr);
+ return PyString_FromStringAndSize(ptr, size);
}
static int
cast_check_pointertype(PyObject *arg)
{
- StgDictObject *dict;
-
- if (PyCPointerTypeObject_Check(arg))
- return 1;
- if (PyCFuncPtrTypeObject_Check(arg))
- return 1;
- dict = PyType_stgdict(arg);
- if (dict) {
- if (PyString_Check(dict->proto)
- && (strchr("sPzUZXO", PyString_AS_STRING(dict->proto)[0]))) {
- /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
- return 1;
- }
- }
- PyErr_Format(PyExc_TypeError,
- "cast() argument 2 must be a pointer type, not %s",
- PyType_Check(arg)
- ? ((PyTypeObject *)arg)->tp_name
- : Py_TYPE(arg)->tp_name);
- return 0;
+ StgDictObject *dict;
+
+ if (PyCPointerTypeObject_Check(arg))
+ return 1;
+ if (PyCFuncPtrTypeObject_Check(arg))
+ return 1;
+ dict = PyType_stgdict(arg);
+ if (dict) {
+ if (PyString_Check(dict->proto)
+ && (strchr("sPzUZXO", PyString_AS_STRING(dict->proto)[0]))) {
+ /* simple pointer types, c_void_p, c_wchar_p, BSTR, ... */
+ return 1;
+ }
+ }
+ PyErr_Format(PyExc_TypeError,
+ "cast() argument 2 must be a pointer type, not %s",
+ PyType_Check(arg)
+ ? ((PyTypeObject *)arg)->tp_name
+ : Py_TYPE(arg)->tp_name);
+ return 0;
}
static PyObject *
cast(void *ptr, PyObject *src, PyObject *ctype)
{
- CDataObject *result;
- if (0 == cast_check_pointertype(ctype))
- return NULL;
- result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
- if (result == NULL)
- return NULL;
-
- /*
- The casted objects '_objects' member:
-
- It must certainly contain the source objects one.
- It must contain the source object itself.
- */
- if (CDataObject_Check(src)) {
- CDataObject *obj = (CDataObject *)src;
- /* PyCData_GetContainer will initialize src.b_objects, we need
- this so it can be shared */
- PyCData_GetContainer(obj);
- /* But we need a dictionary! */
- if (obj->b_objects == Py_None) {
- Py_DECREF(Py_None);
- obj->b_objects = PyDict_New();
- if (obj->b_objects == NULL)
- goto failed;
- }
- Py_XINCREF(obj->b_objects);
- result->b_objects = obj->b_objects;
- if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
- PyObject *index;
- int rc;
- index = PyLong_FromVoidPtr((void *)src);
- if (index == NULL)
- goto failed;
- rc = PyDict_SetItem(result->b_objects, index, src);
- Py_DECREF(index);
- if (rc == -1)
- goto failed;
- }
- }
- /* Should we assert that result is a pointer type? */
- memcpy(result->b_ptr, &ptr, sizeof(void *));
- return (PyObject *)result;
+ CDataObject *result;
+ if (0 == cast_check_pointertype(ctype))
+ return NULL;
+ result = (CDataObject *)PyObject_CallFunctionObjArgs(ctype, NULL);
+ if (result == NULL)
+ return NULL;
+
+ /*
+ The casted objects '_objects' member:
+
+ It must certainly contain the source objects one.
+ It must contain the source object itself.
+ */
+ if (CDataObject_Check(src)) {
+ CDataObject *obj = (CDataObject *)src;
+ /* PyCData_GetContainer will initialize src.b_objects, we need
+ this so it can be shared */
+ PyCData_GetContainer(obj);
+ /* But we need a dictionary! */
+ if (obj->b_objects == Py_None) {
+ Py_DECREF(Py_None);
+ obj->b_objects = PyDict_New();
+ if (obj->b_objects == NULL)
+ goto failed;
+ }
+ Py_XINCREF(obj->b_objects);
+ result->b_objects = obj->b_objects;
+ if (result->b_objects && PyDict_CheckExact(result->b_objects)) {
+ PyObject *index;
+ int rc;
+ index = PyLong_FromVoidPtr((void *)src);
+ if (index == NULL)
+ goto failed;
+ rc = PyDict_SetItem(result->b_objects, index, src);
+ Py_DECREF(index);
+ if (rc == -1)
+ goto failed;
+ }
+ }
+ /* Should we assert that result is a pointer type? */
+ memcpy(result->b_ptr, &ptr, sizeof(void *));
+ return (PyObject *)result;
failed:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
#ifdef CTYPES_UNICODE
static PyObject *
wstring_at(const wchar_t *ptr, int size)
{
- Py_ssize_t ssize = size;
- if (ssize == -1)
- ssize = wcslen(ptr);
- return PyUnicode_FromWideChar(ptr, ssize);
+ Py_ssize_t ssize = size;
+ if (ssize == -1)
+ ssize = wcslen(ptr);
+ return PyUnicode_FromWideChar(ptr, ssize);
}
#endif
PyMODINIT_FUNC
init_ctypes(void)
{
- PyObject *m;
+ PyObject *m;
/* Note:
ob_type is the metatype (the 'type'), defaults to PyType_Type,
tp_base is the base type, defaults to 'object' aka PyBaseObject_Type.
*/
#ifdef WITH_THREAD
- PyEval_InitThreads();
+ PyEval_InitThreads();
#endif
- m = Py_InitModule3("_ctypes", _ctypes_module_methods, module_docs);
- if (!m)
- return;
-
- _ctypes_ptrtype_cache = PyDict_New();
- if (_ctypes_ptrtype_cache == NULL)
- return;
-
- PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache);
-
- _unpickle = PyObject_GetAttrString(m, "_unpickle");
- if (_unpickle == NULL)
- return;
-
- if (PyType_Ready(&PyCArg_Type) < 0)
- return;
-
- if (PyType_Ready(&PyCThunk_Type) < 0)
- return;
-
- /* StgDict is derived from PyDict_Type */
- PyCStgDict_Type.tp_base = &PyDict_Type;
- if (PyType_Ready(&PyCStgDict_Type) < 0)
- return;
-
- /*************************************************
- *
- * Metaclasses
- */
-
- PyCStructType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCStructType_Type) < 0)
- return;
-
- UnionType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&UnionType_Type) < 0)
- return;
-
- PyCPointerType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCPointerType_Type) < 0)
- return;
-
- PyCArrayType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCArrayType_Type) < 0)
- return;
-
- PyCSimpleType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCSimpleType_Type) < 0)
- return;
-
- PyCFuncPtrType_Type.tp_base = &PyType_Type;
- if (PyType_Ready(&PyCFuncPtrType_Type) < 0)
- return;
-
- /*************************************************
- *
- * Classes using a custom metaclass
- */
-
- if (PyType_Ready(&PyCData_Type) < 0)
- return;
-
- Py_TYPE(&Struct_Type) = &PyCStructType_Type;
- Struct_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&Struct_Type) < 0)
- return;
- PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
-
- Py_TYPE(&Union_Type) = &UnionType_Type;
- Union_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&Union_Type) < 0)
- return;
- PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
-
- Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type;
- PyCPointer_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&PyCPointer_Type) < 0)
- return;
- PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type);
-
- Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type;
- PyCArray_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&PyCArray_Type) < 0)
- return;
- PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type);
-
- Py_TYPE(&Simple_Type) = &PyCSimpleType_Type;
- Simple_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&Simple_Type) < 0)
- return;
- PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
-
- Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type;
- PyCFuncPtr_Type.tp_base = &PyCData_Type;
- if (PyType_Ready(&PyCFuncPtr_Type) < 0)
- return;
- PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type);
-
- /*************************************************
- *
- * Simple classes
- */
-
- /* PyCField_Type is derived from PyBaseObject_Type */
- if (PyType_Ready(&PyCField_Type) < 0)
- return;
-
- /*************************************************
- *
- * Other stuff
- */
-
- DictRemover_Type.tp_new = PyType_GenericNew;
- if (PyType_Ready(&DictRemover_Type) < 0)
- return;
+ m = Py_InitModule3("_ctypes", _ctypes_module_methods, module_docs);
+ if (!m)
+ return;
+
+ _ctypes_ptrtype_cache = PyDict_New();
+ if (_ctypes_ptrtype_cache == NULL)
+ return;
+
+ PyModule_AddObject(m, "_pointer_type_cache", (PyObject *)_ctypes_ptrtype_cache);
+
+ _unpickle = PyObject_GetAttrString(m, "_unpickle");
+ if (_unpickle == NULL)
+ return;
+
+ if (PyType_Ready(&PyCArg_Type) < 0)
+ return;
+
+ if (PyType_Ready(&PyCThunk_Type) < 0)
+ return;
+
+ /* StgDict is derived from PyDict_Type */
+ PyCStgDict_Type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&PyCStgDict_Type) < 0)
+ return;
+
+ /*************************************************
+ *
+ * Metaclasses
+ */
+
+ PyCStructType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCStructType_Type) < 0)
+ return;
+
+ UnionType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&UnionType_Type) < 0)
+ return;
+
+ PyCPointerType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCPointerType_Type) < 0)
+ return;
+
+ PyCArrayType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCArrayType_Type) < 0)
+ return;
+
+ PyCSimpleType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCSimpleType_Type) < 0)
+ return;
+
+ PyCFuncPtrType_Type.tp_base = &PyType_Type;
+ if (PyType_Ready(&PyCFuncPtrType_Type) < 0)
+ return;
+
+ /*************************************************
+ *
+ * Classes using a custom metaclass
+ */
+
+ if (PyType_Ready(&PyCData_Type) < 0)
+ return;
+
+ Py_TYPE(&Struct_Type) = &PyCStructType_Type;
+ Struct_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&Struct_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Structure", (PyObject *)&Struct_Type);
+
+ Py_TYPE(&Union_Type) = &UnionType_Type;
+ Union_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&Union_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Union", (PyObject *)&Union_Type);
+
+ Py_TYPE(&PyCPointer_Type) = &PyCPointerType_Type;
+ PyCPointer_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&PyCPointer_Type) < 0)
+ return;
+ PyModule_AddObject(m, "_Pointer", (PyObject *)&PyCPointer_Type);
+
+ Py_TYPE(&PyCArray_Type) = &PyCArrayType_Type;
+ PyCArray_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&PyCArray_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Array", (PyObject *)&PyCArray_Type);
+
+ Py_TYPE(&Simple_Type) = &PyCSimpleType_Type;
+ Simple_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&Simple_Type) < 0)
+ return;
+ PyModule_AddObject(m, "_SimpleCData", (PyObject *)&Simple_Type);
+
+ Py_TYPE(&PyCFuncPtr_Type) = &PyCFuncPtrType_Type;
+ PyCFuncPtr_Type.tp_base = &PyCData_Type;
+ if (PyType_Ready(&PyCFuncPtr_Type) < 0)
+ return;
+ PyModule_AddObject(m, "CFuncPtr", (PyObject *)&PyCFuncPtr_Type);
+
+ /*************************************************
+ *
+ * Simple classes
+ */
+
+ /* PyCField_Type is derived from PyBaseObject_Type */
+ if (PyType_Ready(&PyCField_Type) < 0)
+ return;
+
+ /*************************************************
+ *
+ * Other stuff
+ */
+
+ DictRemover_Type.tp_new = PyType_GenericNew;
+ if (PyType_Ready(&DictRemover_Type) < 0)
+ return;
#ifdef MS_WIN32
- if (create_comerror() < 0)
- return;
- PyModule_AddObject(m, "COMError", ComError);
+ if (create_comerror() < 0)
+ return;
+ PyModule_AddObject(m, "COMError", ComError);
- PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyInt_FromLong(FUNCFLAG_HRESULT));
- PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyInt_FromLong(FUNCFLAG_STDCALL));
+ PyModule_AddObject(m, "FUNCFLAG_HRESULT", PyInt_FromLong(FUNCFLAG_HRESULT));
+ PyModule_AddObject(m, "FUNCFLAG_STDCALL", PyInt_FromLong(FUNCFLAG_STDCALL));
#endif
- PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
- PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyInt_FromLong(FUNCFLAG_USE_ERRNO));
- PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyInt_FromLong(FUNCFLAG_USE_LASTERROR));
- PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI));
- PyModule_AddStringConstant(m, "__version__", "1.1.0");
-
- PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
- PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
- PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
- PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
+ PyModule_AddObject(m, "FUNCFLAG_CDECL", PyInt_FromLong(FUNCFLAG_CDECL));
+ PyModule_AddObject(m, "FUNCFLAG_USE_ERRNO", PyInt_FromLong(FUNCFLAG_USE_ERRNO));
+ PyModule_AddObject(m, "FUNCFLAG_USE_LASTERROR", PyInt_FromLong(FUNCFLAG_USE_LASTERROR));
+ PyModule_AddObject(m, "FUNCFLAG_PYTHONAPI", PyInt_FromLong(FUNCFLAG_PYTHONAPI));
+ PyModule_AddStringConstant(m, "__version__", "1.1.0");
+
+ PyModule_AddObject(m, "_memmove_addr", PyLong_FromVoidPtr(memmove));
+ PyModule_AddObject(m, "_memset_addr", PyLong_FromVoidPtr(memset));
+ PyModule_AddObject(m, "_string_at_addr", PyLong_FromVoidPtr(string_at));
+ PyModule_AddObject(m, "_cast_addr", PyLong_FromVoidPtr(cast));
#ifdef CTYPES_UNICODE
- PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
+ PyModule_AddObject(m, "_wstring_at_addr", PyLong_FromVoidPtr(wstring_at));
#endif
/* If RTLD_LOCAL is not defined (Windows!), set it to zero. */
@@ -5625,14 +5625,14 @@ init_ctypes(void)
#define RTLD_GLOBAL RTLD_LOCAL
#endif
- PyModule_AddObject(m, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL));
- PyModule_AddObject(m, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL));
-
- PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
- if (PyExc_ArgError) {
- Py_INCREF(PyExc_ArgError);
- PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
- }
+ PyModule_AddObject(m, "RTLD_LOCAL", PyInt_FromLong(RTLD_LOCAL));
+ PyModule_AddObject(m, "RTLD_GLOBAL", PyInt_FromLong(RTLD_GLOBAL));
+
+ PyExc_ArgError = PyErr_NewException("ctypes.ArgumentError", NULL, NULL);
+ if (PyExc_ArgError) {
+ Py_INCREF(PyExc_ArgError);
+ PyModule_AddObject(m, "ArgumentError", PyExc_ArgError);
+ }
}
/*****************************************************************
@@ -5644,30 +5644,30 @@ init_ctypes(void)
#ifdef HAVE_WCHAR_H
PyObject *My_PyUnicode_FromWideChar(register const wchar_t *w,
- Py_ssize_t size)
+ Py_ssize_t size)
{
PyUnicodeObject *unicode;
if (w == NULL) {
- PyErr_BadInternalCall();
- return NULL;
+ PyErr_BadInternalCall();
+ return NULL;
}
unicode = (PyUnicodeObject *)PyUnicode_FromUnicode(NULL, size);
if (!unicode)
- return NULL;
+ return NULL;
/* Copy the wchar_t data into the new object */
#ifdef HAVE_USABLE_WCHAR_T
memcpy(unicode->str, w, size * sizeof(wchar_t));
#else
{
- register Py_UNICODE *u;
- register int i;
- u = PyUnicode_AS_UNICODE(unicode);
- /* In Python, the following line has a one-off error */
- for (i = size; i > 0; i--)
- *u++ = *w++;
+ register Py_UNICODE *u;
+ register int i;
+ u = PyUnicode_AS_UNICODE(unicode);
+ /* In Python, the following line has a one-off error */
+ for (i = size; i > 0; i--)
+ *u++ = *w++;
}
#endif
@@ -5675,25 +5675,25 @@ PyObject *My_PyUnicode_FromWideChar(register const wchar_t *w,
}
Py_ssize_t My_PyUnicode_AsWideChar(PyUnicodeObject *unicode,
- register wchar_t *w,
- Py_ssize_t size)
+ register wchar_t *w,
+ Py_ssize_t size)
{
if (unicode == NULL) {
- PyErr_BadInternalCall();
- return -1;
+ PyErr_BadInternalCall();
+ return -1;
}
if (size > PyUnicode_GET_SIZE(unicode))
- size = PyUnicode_GET_SIZE(unicode);
+ size = PyUnicode_GET_SIZE(unicode);
#ifdef HAVE_USABLE_WCHAR_T
memcpy(w, unicode->str, size * sizeof(wchar_t));
#else
{
- register Py_UNICODE *u;
- register int i;
- u = PyUnicode_AS_UNICODE(unicode);
- /* In Python, the following line has a one-off error */
- for (i = size; i > 0; i--)
- *w++ = *u++;
+ register Py_UNICODE *u;
+ register int i;
+ u = PyUnicode_AS_UNICODE(unicode);
+ /* In Python, the following line has a one-off error */
+ for (i = size; i > 0; i--)
+ *w++ = *u++;
}
#endif
diff --git a/Modules/_ctypes/_ctypes_test.c b/Modules/_ctypes/_ctypes_test.c
index 3f13180..46406a6 100644
--- a/Modules/_ctypes/_ctypes_test.c
+++ b/Modules/_ctypes/_ctypes_test.c
@@ -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;
-
- 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;
- }
+ 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;
+ }
}
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;
-
- 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;
+ 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;
}
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);
}
diff --git a/Modules/_ctypes/callbacks.c b/Modules/_ctypes/callbacks.c
index afdd947..8fbe6de 100644
--- a/Modules/_ctypes/callbacks.c
+++ b/Modules/_ctypes/callbacks.c
@@ -17,65 +17,65 @@
static void
CThunkObject_dealloc(PyObject *_self)
{
- CThunkObject *self = (CThunkObject *)_self;
- Py_XDECREF(self->converters);
- Py_XDECREF(self->callable);
- Py_XDECREF(self->restype);
- if (self->pcl)
- _ctypes_free_closure(self->pcl);
- PyObject_GC_Del(self);
+ CThunkObject *self = (CThunkObject *)_self;
+ Py_XDECREF(self->converters);
+ Py_XDECREF(self->callable);
+ Py_XDECREF(self->restype);
+ if (self->pcl)
+ _ctypes_free_closure(self->pcl);
+ PyObject_GC_Del(self);
}
static int
CThunkObject_traverse(PyObject *_self, visitproc visit, void *arg)
{
- CThunkObject *self = (CThunkObject *)_self;
- Py_VISIT(self->converters);
- Py_VISIT(self->callable);
- Py_VISIT(self->restype);
- return 0;
+ CThunkObject *self = (CThunkObject *)_self;
+ Py_VISIT(self->converters);
+ Py_VISIT(self->callable);
+ Py_VISIT(self->restype);
+ return 0;
}
static int
CThunkObject_clear(PyObject *_self)
{
- CThunkObject *self = (CThunkObject *)_self;
- Py_CLEAR(self->converters);
- Py_CLEAR(self->callable);
- Py_CLEAR(self->restype);
- return 0;
+ CThunkObject *self = (CThunkObject *)_self;
+ Py_CLEAR(self->converters);
+ Py_CLEAR(self->callable);
+ Py_CLEAR(self->restype);
+ return 0;
}
PyTypeObject PyCThunk_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CThunkObject",
- sizeof(CThunkObject), /* tp_basicsize */
- sizeof(ffi_type), /* tp_itemsize */
- CThunkObject_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_HAVE_GC, /* tp_flags */
- "CThunkObject", /* tp_doc */
- CThunkObject_traverse, /* tp_traverse */
- CThunkObject_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CThunkObject",
+ sizeof(CThunkObject), /* tp_basicsize */
+ sizeof(ffi_type), /* tp_itemsize */
+ CThunkObject_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_HAVE_GC, /* tp_flags */
+ "CThunkObject", /* tp_doc */
+ CThunkObject_traverse, /* tp_traverse */
+ CThunkObject_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
};
/**************************************************************/
@@ -83,64 +83,64 @@ PyTypeObject PyCThunk_Type = {
static void
PrintError(char *msg, ...)
{
- char buf[512];
- PyObject *f = PySys_GetObject("stderr");
- va_list marker;
-
- va_start(marker, msg);
- vsnprintf(buf, sizeof(buf), msg, marker);
- va_end(marker);
- if (f)
- PyFile_WriteString(buf, f);
- PyErr_Print();
+ char buf[512];
+ PyObject *f = PySys_GetObject("stderr");
+ va_list marker;
+
+ va_start(marker, msg);
+ vsnprintf(buf, sizeof(buf), msg, marker);
+ va_end(marker);
+ if (f)
+ PyFile_WriteString(buf, f);
+ PyErr_Print();
}
#if (PY_VERSION_HEX < 0x02070000)
PyCodeObject *
PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
{
- static PyObject *emptystring = NULL;
- static PyObject *nulltuple = NULL;
- PyObject *filename_ob = NULL;
- PyObject *funcname_ob = NULL;
- PyCodeObject *result = NULL;
- if (emptystring == NULL) {
- emptystring = PyString_FromString("");
- if (emptystring == NULL)
- goto failed;
- }
- if (nulltuple == NULL) {
- nulltuple = PyTuple_New(0);
- if (nulltuple == NULL)
- goto failed;
- }
- funcname_ob = PyString_FromString(funcname);
- if (funcname_ob == NULL)
- goto failed;
- filename_ob = PyString_FromString(filename);
- if (filename_ob == NULL)
- goto failed;
-
- result = PyCode_New(0, /* argcount */
- 0, /* nlocals */
- 0, /* stacksize */
- 0, /* flags */
- emptystring, /* code */
- nulltuple, /* consts */
- nulltuple, /* names */
- nulltuple, /* varnames */
- nulltuple, /* freevars */
- nulltuple, /* cellvars */
- filename_ob, /* filename */
- funcname_ob, /* name */
- firstlineno, /* firstlineno */
- emptystring /* lnotab */
- );
+ static PyObject *emptystring = NULL;
+ static PyObject *nulltuple = NULL;
+ PyObject *filename_ob = NULL;
+ PyObject *funcname_ob = NULL;
+ PyCodeObject *result = NULL;
+ if (emptystring == NULL) {
+ emptystring = PyString_FromString("");
+ if (emptystring == NULL)
+ goto failed;
+ }
+ if (nulltuple == NULL) {
+ nulltuple = PyTuple_New(0);
+ if (nulltuple == NULL)
+ goto failed;
+ }
+ funcname_ob = PyString_FromString(funcname);
+ if (funcname_ob == NULL)
+ goto failed;
+ filename_ob = PyString_FromString(filename);
+ if (filename_ob == NULL)
+ goto failed;
+
+ result = PyCode_New(0, /* argcount */
+ 0, /* nlocals */
+ 0, /* stacksize */
+ 0, /* flags */
+ emptystring, /* code */
+ nulltuple, /* consts */
+ nulltuple, /* names */
+ nulltuple, /* varnames */
+ nulltuple, /* freevars */
+ nulltuple, /* cellvars */
+ filename_ob, /* filename */
+ funcname_ob, /* name */
+ firstlineno, /* firstlineno */
+ emptystring /* lnotab */
+ );
failed:
- Py_XDECREF(funcname_ob);
- Py_XDECREF(filename_ob);
- return result;
+ Py_XDECREF(funcname_ob);
+ Py_XDECREF(filename_ob);
+ return result;
}
#endif
@@ -148,27 +148,27 @@ failed:
/* after code that pyrex generates */
void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
{
- PyObject *py_globals = 0;
- PyCodeObject *py_code = 0;
- PyFrameObject *py_frame = 0;
-
- py_globals = PyDict_New();
- if (!py_globals) goto bad;
- py_code = PyCode_NewEmpty(filename, funcname, lineno);
- if (!py_code) goto bad;
- py_frame = PyFrame_New(
- PyThreadState_Get(), /*PyThreadState *tstate,*/
- py_code, /*PyCodeObject *code,*/
- py_globals, /*PyObject *globals,*/
- 0 /*PyObject *locals*/
- );
- if (!py_frame) goto bad;
- py_frame->f_lineno = lineno;
- PyTraceBack_Here(py_frame);
+ PyObject *py_globals = 0;
+ PyCodeObject *py_code = 0;
+ PyFrameObject *py_frame = 0;
+
+ py_globals = PyDict_New();
+ if (!py_globals) goto bad;
+ py_code = PyCode_NewEmpty(filename, funcname, lineno);
+ if (!py_code) goto bad;
+ py_frame = PyFrame_New(
+ PyThreadState_Get(), /*PyThreadState *tstate,*/
+ py_code, /*PyCodeObject *code,*/
+ py_globals, /*PyObject *globals,*/
+ 0 /*PyObject *locals*/
+ );
+ if (!py_frame) goto bad;
+ py_frame->f_lineno = lineno;
+ PyTraceBack_Here(py_frame);
bad:
- Py_XDECREF(py_globals);
- Py_XDECREF(py_code);
- Py_XDECREF(py_frame);
+ Py_XDECREF(py_globals);
+ Py_XDECREF(py_code);
+ Py_XDECREF(py_frame);
}
#ifdef MS_WIN32
@@ -185,15 +185,15 @@ void _ctypes_add_traceback(char *funcname, char *filename, int lineno)
static void
TryAddRef(StgDictObject *dict, CDataObject *obj)
{
- IUnknown *punk;
+ IUnknown *punk;
- if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
- return;
+ if (NULL == PyDict_GetItemString((PyObject *)dict, "_needs_com_addref_"))
+ return;
- punk = *(IUnknown **)obj->b_ptr;
- if (punk)
- punk->lpVtbl->AddRef(punk);
- return;
+ punk = *(IUnknown **)obj->b_ptr;
+ if (punk)
+ punk->lpVtbl->AddRef(punk);
+ return;
}
#endif
@@ -203,420 +203,420 @@ TryAddRef(StgDictObject *dict, CDataObject *obj)
*
*/
static void _CallPythonObject(void *mem,
- ffi_type *restype,
- SETFUNC setfunc,
- PyObject *callable,
- PyObject *converters,
- int flags,
- void **pArgs)
+ ffi_type *restype,
+ SETFUNC setfunc,
+ PyObject *callable,
+ PyObject *converters,
+ int flags,
+ void **pArgs)
{
- Py_ssize_t i;
- PyObject *result;
- PyObject *arglist = NULL;
- Py_ssize_t nArgs;
- PyObject *error_object = NULL;
- int *space;
+ Py_ssize_t i;
+ PyObject *result;
+ PyObject *arglist = NULL;
+ Py_ssize_t nArgs;
+ PyObject *error_object = NULL;
+ int *space;
#ifdef WITH_THREAD
- PyGILState_STATE state = PyGILState_Ensure();
+ PyGILState_STATE state = PyGILState_Ensure();
#endif
- nArgs = PySequence_Length(converters);
- /* Hm. What to return in case of error?
- For COM, 0xFFFFFFFF seems better than 0.
- */
- if (nArgs < 0) {
- PrintError("BUG: PySequence_Length");
- goto Done;
- }
-
- arglist = PyTuple_New(nArgs);
- if (!arglist) {
- PrintError("PyTuple_New()");
- goto Done;
- }
- for (i = 0; i < nArgs; ++i) {
- /* Note: new reference! */
- PyObject *cnv = PySequence_GetItem(converters, i);
- StgDictObject *dict;
- if (cnv)
- dict = PyType_stgdict(cnv);
- else {
- PrintError("Getting argument converter %d\n", i);
- goto Done;
- }
-
- if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
- PyObject *v = dict->getfunc(*pArgs, dict->size);
- if (!v) {
- PrintError("create argument %d:\n", i);
- Py_DECREF(cnv);
- goto Done;
- }
- PyTuple_SET_ITEM(arglist, i, v);
- /* XXX XXX XX
- We have the problem that c_byte or c_short have dict->size of
- 1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
- BTW, the same problem occurrs when they are pushed as parameters
- */
- } else if (dict) {
- /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
- CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
- if (!obj) {
- PrintError("create argument %d:\n", i);
- Py_DECREF(cnv);
- goto Done;
- }
- if (!CDataObject_Check(obj)) {
- Py_DECREF(obj);
- Py_DECREF(cnv);
- PrintError("unexpected result of create argument %d:\n", i);
- goto Done;
- }
- memcpy(obj->b_ptr, *pArgs, dict->size);
- PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
+ nArgs = PySequence_Length(converters);
+ /* Hm. What to return in case of error?
+ For COM, 0xFFFFFFFF seems better than 0.
+ */
+ if (nArgs < 0) {
+ PrintError("BUG: PySequence_Length");
+ goto Done;
+ }
+
+ arglist = PyTuple_New(nArgs);
+ if (!arglist) {
+ PrintError("PyTuple_New()");
+ goto Done;
+ }
+ for (i = 0; i < nArgs; ++i) {
+ /* Note: new reference! */
+ PyObject *cnv = PySequence_GetItem(converters, i);
+ StgDictObject *dict;
+ if (cnv)
+ dict = PyType_stgdict(cnv);
+ else {
+ PrintError("Getting argument converter %d\n", i);
+ goto Done;
+ }
+
+ if (dict && dict->getfunc && !_ctypes_simple_instance(cnv)) {
+ PyObject *v = dict->getfunc(*pArgs, dict->size);
+ if (!v) {
+ PrintError("create argument %d:\n", i);
+ Py_DECREF(cnv);
+ goto Done;
+ }
+ PyTuple_SET_ITEM(arglist, i, v);
+ /* XXX XXX XX
+ We have the problem that c_byte or c_short have dict->size of
+ 1 resp. 4, but these parameters are pushed as sizeof(int) bytes.
+ BTW, the same problem occurrs when they are pushed as parameters
+ */
+ } else if (dict) {
+ /* Hm, shouldn't we use PyCData_AtAddress() or something like that instead? */
+ CDataObject *obj = (CDataObject *)PyObject_CallFunctionObjArgs(cnv, NULL);
+ if (!obj) {
+ PrintError("create argument %d:\n", i);
+ Py_DECREF(cnv);
+ goto Done;
+ }
+ if (!CDataObject_Check(obj)) {
+ Py_DECREF(obj);
+ Py_DECREF(cnv);
+ PrintError("unexpected result of create argument %d:\n", i);
+ goto Done;
+ }
+ memcpy(obj->b_ptr, *pArgs, dict->size);
+ PyTuple_SET_ITEM(arglist, i, (PyObject *)obj);
#ifdef MS_WIN32
- TryAddRef(dict, obj);
+ TryAddRef(dict, obj);
#endif
- } else {
- PyErr_SetString(PyExc_TypeError,
- "cannot build parameter");
- PrintError("Parsing argument %d\n", i);
- Py_DECREF(cnv);
- goto Done;
- }
- Py_DECREF(cnv);
- /* XXX error handling! */
- pArgs++;
- }
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot build parameter");
+ PrintError("Parsing argument %d\n", i);
+ Py_DECREF(cnv);
+ goto Done;
+ }
+ Py_DECREF(cnv);
+ /* XXX error handling! */
+ pArgs++;
+ }
#define CHECK(what, x) \
if (x == NULL) _ctypes_add_traceback(what, "_ctypes/callbacks.c", __LINE__ - 1), PyErr_Print()
- if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
- error_object = _ctypes_get_errobj(&space);
- if (error_object == NULL)
- goto Done;
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
+ if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
+ error_object = _ctypes_get_errobj(&space);
+ if (error_object == NULL)
+ goto Done;
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
#ifdef MS_WIN32
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#endif
- }
+ }
- result = PyObject_CallObject(callable, arglist);
- CHECK("'calling callback function'", result);
+ result = PyObject_CallObject(callable, arglist);
+ CHECK("'calling callback function'", result);
#ifdef MS_WIN32
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#endif
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
- Py_XDECREF(error_object);
-
- if ((restype != &ffi_type_void) && result) {
- PyObject *keep;
- assert(setfunc);
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
+ Py_XDECREF(error_object);
+
+ if ((restype != &ffi_type_void) && result) {
+ PyObject *keep;
+ assert(setfunc);
#ifdef WORDS_BIGENDIAN
- /* See the corresponding code in callproc.c, around line 961 */
- if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
- mem = (char *)mem + sizeof(ffi_arg) - restype->size;
+ /* See the corresponding code in callproc.c, around line 961 */
+ if (restype->type != FFI_TYPE_FLOAT && restype->size < sizeof(ffi_arg))
+ mem = (char *)mem + sizeof(ffi_arg) - restype->size;
#endif
- keep = setfunc(mem, result, 0);
- CHECK("'converting callback result'", keep);
- /* keep is an object we have to keep alive so that the result
- stays valid. If there is no such object, the setfunc will
- have returned Py_None.
-
- If there is such an object, we have no choice than to keep
- it alive forever - but a refcount and/or memory leak will
- be the result. EXCEPT when restype is py_object - Python
- itself knows how to manage the refcount of these objects.
- */
- if (keep == NULL) /* Could not convert callback result. */
- PyErr_WriteUnraisable(callable);
- else if (keep == Py_None) /* Nothing to keep */
- Py_DECREF(keep);
- else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
- if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
- "memory leak in callback function."))
- PyErr_WriteUnraisable(callable);
- }
- }
- Py_XDECREF(result);
+ keep = setfunc(mem, result, 0);
+ CHECK("'converting callback result'", keep);
+ /* keep is an object we have to keep alive so that the result
+ stays valid. If there is no such object, the setfunc will
+ have returned Py_None.
+
+ If there is such an object, we have no choice than to keep
+ it alive forever - but a refcount and/or memory leak will
+ be the result. EXCEPT when restype is py_object - Python
+ itself knows how to manage the refcount of these objects.
+ */
+ if (keep == NULL) /* Could not convert callback result. */
+ PyErr_WriteUnraisable(callable);
+ else if (keep == Py_None) /* Nothing to keep */
+ Py_DECREF(keep);
+ else if (setfunc != _ctypes_get_fielddesc("O")->setfunc) {
+ if (-1 == PyErr_Warn(PyExc_RuntimeWarning,
+ "memory leak in callback function."))
+ PyErr_WriteUnraisable(callable);
+ }
+ }
+ Py_XDECREF(result);
Done:
- Py_XDECREF(arglist);
+ Py_XDECREF(arglist);
#ifdef WITH_THREAD
- PyGILState_Release(state);
+ PyGILState_Release(state);
#endif
}
static void closure_fcn(ffi_cif *cif,
- void *resp,
- void **args,
- void *userdata)
+ void *resp,
+ void **args,
+ void *userdata)
{
- CThunkObject *p = (CThunkObject *)userdata;
-
- _CallPythonObject(resp,
- p->ffi_restype,
- p->setfunc,
- p->callable,
- p->converters,
- p->flags,
- args);
+ CThunkObject *p = (CThunkObject *)userdata;
+
+ _CallPythonObject(resp,
+ p->ffi_restype,
+ p->setfunc,
+ p->callable,
+ p->converters,
+ p->flags,
+ args);
}
static CThunkObject* CThunkObject_new(Py_ssize_t nArgs)
{
- CThunkObject *p;
- int i;
-
- p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
- if (p == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
-
- p->pcl = NULL;
- memset(&p->cif, 0, sizeof(p->cif));
- p->converters = NULL;
- p->callable = NULL;
- p->setfunc = NULL;
- p->ffi_restype = NULL;
-
- for (i = 0; i < nArgs + 1; ++i)
- p->atypes[i] = NULL;
- PyObject_GC_Track((PyObject *)p);
- return p;
+ CThunkObject *p;
+ int i;
+
+ p = PyObject_GC_NewVar(CThunkObject, &PyCThunk_Type, nArgs);
+ if (p == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ p->pcl = NULL;
+ memset(&p->cif, 0, sizeof(p->cif));
+ p->converters = NULL;
+ p->callable = NULL;
+ p->setfunc = NULL;
+ p->ffi_restype = NULL;
+
+ for (i = 0; i < nArgs + 1; ++i)
+ p->atypes[i] = NULL;
+ PyObject_GC_Track((PyObject *)p);
+ return p;
}
CThunkObject *_ctypes_alloc_callback(PyObject *callable,
- PyObject *converters,
- PyObject *restype,
- int flags)
+ PyObject *converters,
+ PyObject *restype,
+ int flags)
{
- int result;
- CThunkObject *p;
- Py_ssize_t nArgs, i;
- ffi_abi cc;
-
- nArgs = PySequence_Size(converters);
- p = CThunkObject_new(nArgs);
- if (p == NULL)
- return NULL;
-
- assert(CThunk_CheckExact(p));
-
- p->pcl = _ctypes_alloc_closure();
- if (p->pcl == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- p->flags = flags;
- for (i = 0; i < nArgs; ++i) {
- PyObject *cnv = PySequence_GetItem(converters, i);
- if (cnv == NULL)
- goto error;
- p->atypes[i] = _ctypes_get_ffi_type(cnv);
- Py_DECREF(cnv);
- }
- p->atypes[i] = NULL;
-
- Py_INCREF(restype);
- p->restype = restype;
- if (restype == Py_None) {
- p->setfunc = NULL;
- p->ffi_restype = &ffi_type_void;
- } else {
- StgDictObject *dict = PyType_stgdict(restype);
- if (dict == NULL || dict->setfunc == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "invalid result type for callback function");
- goto error;
- }
- p->setfunc = dict->setfunc;
- p->ffi_restype = &dict->ffi_type_pointer;
- }
-
- cc = FFI_DEFAULT_ABI;
+ int result;
+ CThunkObject *p;
+ Py_ssize_t nArgs, i;
+ ffi_abi cc;
+
+ nArgs = PySequence_Size(converters);
+ p = CThunkObject_new(nArgs);
+ if (p == NULL)
+ return NULL;
+
+ assert(CThunk_CheckExact(p));
+
+ p->pcl = _ctypes_alloc_closure();
+ if (p->pcl == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ p->flags = flags;
+ for (i = 0; i < nArgs; ++i) {
+ PyObject *cnv = PySequence_GetItem(converters, i);
+ if (cnv == NULL)
+ goto error;
+ p->atypes[i] = _ctypes_get_ffi_type(cnv);
+ Py_DECREF(cnv);
+ }
+ p->atypes[i] = NULL;
+
+ Py_INCREF(restype);
+ p->restype = restype;
+ if (restype == Py_None) {
+ p->setfunc = NULL;
+ p->ffi_restype = &ffi_type_void;
+ } else {
+ StgDictObject *dict = PyType_stgdict(restype);
+ if (dict == NULL || dict->setfunc == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "invalid result type for callback function");
+ goto error;
+ }
+ p->setfunc = dict->setfunc;
+ p->ffi_restype = &dict->ffi_type_pointer;
+ }
+
+ cc = FFI_DEFAULT_ABI;
#if defined(MS_WIN32) && !defined(_WIN32_WCE) && !defined(MS_WIN64)
- if ((flags & FUNCFLAG_CDECL) == 0)
- cc = FFI_STDCALL;
+ if ((flags & FUNCFLAG_CDECL) == 0)
+ cc = FFI_STDCALL;
#endif
- result = ffi_prep_cif(&p->cif, cc,
- Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
- _ctypes_get_ffi_type(restype),
- &p->atypes[0]);
- if (result != FFI_OK) {
- PyErr_Format(PyExc_RuntimeError,
- "ffi_prep_cif failed with %d", result);
- goto error;
- }
- result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
- if (result != FFI_OK) {
- PyErr_Format(PyExc_RuntimeError,
- "ffi_prep_closure failed with %d", result);
- goto error;
- }
-
- Py_INCREF(converters);
- p->converters = converters;
- Py_INCREF(callable);
- p->callable = callable;
- return p;
+ result = ffi_prep_cif(&p->cif, cc,
+ Py_SAFE_DOWNCAST(nArgs, Py_ssize_t, int),
+ _ctypes_get_ffi_type(restype),
+ &p->atypes[0]);
+ if (result != FFI_OK) {
+ PyErr_Format(PyExc_RuntimeError,
+ "ffi_prep_cif failed with %d", result);
+ goto error;
+ }
+ result = ffi_prep_closure(p->pcl, &p->cif, closure_fcn, p);
+ if (result != FFI_OK) {
+ PyErr_Format(PyExc_RuntimeError,
+ "ffi_prep_closure failed with %d", result);
+ goto error;
+ }
+
+ Py_INCREF(converters);
+ p->converters = converters;
+ Py_INCREF(callable);
+ p->callable = callable;
+ return p;
error:
- Py_XDECREF(p);
- return NULL;
+ Py_XDECREF(p);
+ return NULL;
}
#ifdef MS_WIN32
static void LoadPython(void)
{
- if (!Py_IsInitialized()) {
+ if (!Py_IsInitialized()) {
#ifdef WITH_THREAD
- PyEval_InitThreads();
+ PyEval_InitThreads();
#endif
- Py_Initialize();
- }
+ Py_Initialize();
+ }
}
/******************************************************************/
long Call_GetClassObject(REFCLSID rclsid, REFIID riid, LPVOID *ppv)
{
- PyObject *mod, *func, *result;
- long retval;
- static PyObject *context;
-
- if (context == NULL)
- context = PyString_InternFromString("_ctypes.DllGetClassObject");
-
- mod = PyImport_ImportModuleNoBlock("ctypes");
- if (!mod) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- /* There has been a warning before about this already */
- return E_FAIL;
- }
-
- func = PyObject_GetAttrString(mod, "DllGetClassObject");
- Py_DECREF(mod);
- if (!func) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- {
- PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
- PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
- PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
- if (!py_rclsid || !py_riid || !py_ppv) {
- Py_XDECREF(py_rclsid);
- Py_XDECREF(py_riid);
- Py_XDECREF(py_ppv);
- Py_DECREF(func);
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
- result = PyObject_CallFunctionObjArgs(func,
- py_rclsid,
- py_riid,
- py_ppv,
- NULL);
- Py_DECREF(py_rclsid);
- Py_DECREF(py_riid);
- Py_DECREF(py_ppv);
- }
- Py_DECREF(func);
- if (!result) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- retval = PyInt_AsLong(result);
- if (PyErr_Occurred()) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- retval = E_FAIL;
- }
- Py_DECREF(result);
- return retval;
+ PyObject *mod, *func, *result;
+ long retval;
+ static PyObject *context;
+
+ if (context == NULL)
+ context = PyString_InternFromString("_ctypes.DllGetClassObject");
+
+ mod = PyImport_ImportModuleNoBlock("ctypes");
+ if (!mod) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ /* There has been a warning before about this already */
+ return E_FAIL;
+ }
+
+ func = PyObject_GetAttrString(mod, "DllGetClassObject");
+ Py_DECREF(mod);
+ if (!func) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ {
+ PyObject *py_rclsid = PyLong_FromVoidPtr((void *)rclsid);
+ PyObject *py_riid = PyLong_FromVoidPtr((void *)riid);
+ PyObject *py_ppv = PyLong_FromVoidPtr(ppv);
+ if (!py_rclsid || !py_riid || !py_ppv) {
+ Py_XDECREF(py_rclsid);
+ Py_XDECREF(py_riid);
+ Py_XDECREF(py_ppv);
+ Py_DECREF(func);
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+ result = PyObject_CallFunctionObjArgs(func,
+ py_rclsid,
+ py_riid,
+ py_ppv,
+ NULL);
+ Py_DECREF(py_rclsid);
+ Py_DECREF(py_riid);
+ Py_DECREF(py_ppv);
+ }
+ Py_DECREF(func);
+ if (!result) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ retval = PyInt_AsLong(result);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ retval = E_FAIL;
+ }
+ Py_DECREF(result);
+ return retval;
}
STDAPI DllGetClassObject(REFCLSID rclsid,
- REFIID riid,
- LPVOID *ppv)
+ REFIID riid,
+ LPVOID *ppv)
{
- long result;
+ long result;
#ifdef WITH_THREAD
- PyGILState_STATE state;
+ PyGILState_STATE state;
#endif
- LoadPython();
+ LoadPython();
#ifdef WITH_THREAD
- state = PyGILState_Ensure();
+ state = PyGILState_Ensure();
#endif
- result = Call_GetClassObject(rclsid, riid, ppv);
+ result = Call_GetClassObject(rclsid, riid, ppv);
#ifdef WITH_THREAD
- PyGILState_Release(state);
+ PyGILState_Release(state);
#endif
- return result;
+ return result;
}
long Call_CanUnloadNow(void)
{
- PyObject *mod, *func, *result;
- long retval;
- static PyObject *context;
-
- if (context == NULL)
- context = PyString_InternFromString("_ctypes.DllCanUnloadNow");
-
- mod = PyImport_ImportModuleNoBlock("ctypes");
- if (!mod) {
-/* OutputDebugString("Could not import ctypes"); */
- /* We assume that this error can only occur when shutting
- down, so we silently ignore it */
- PyErr_Clear();
- return E_FAIL;
- }
- /* Other errors cannot be raised, but are printed to stderr */
- func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
- Py_DECREF(mod);
- if (!func) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- result = PyObject_CallFunction(func, NULL);
- Py_DECREF(func);
- if (!result) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- return E_FAIL;
- }
-
- retval = PyInt_AsLong(result);
- if (PyErr_Occurred()) {
- PyErr_WriteUnraisable(context ? context : Py_None);
- retval = E_FAIL;
- }
- Py_DECREF(result);
- return retval;
+ PyObject *mod, *func, *result;
+ long retval;
+ static PyObject *context;
+
+ if (context == NULL)
+ context = PyString_InternFromString("_ctypes.DllCanUnloadNow");
+
+ mod = PyImport_ImportModuleNoBlock("ctypes");
+ if (!mod) {
+/* OutputDebugString("Could not import ctypes"); */
+ /* We assume that this error can only occur when shutting
+ down, so we silently ignore it */
+ PyErr_Clear();
+ return E_FAIL;
+ }
+ /* Other errors cannot be raised, but are printed to stderr */
+ func = PyObject_GetAttrString(mod, "DllCanUnloadNow");
+ Py_DECREF(mod);
+ if (!func) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ result = PyObject_CallFunction(func, NULL);
+ Py_DECREF(func);
+ if (!result) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ return E_FAIL;
+ }
+
+ retval = PyInt_AsLong(result);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(context ? context : Py_None);
+ retval = E_FAIL;
+ }
+ Py_DECREF(result);
+ return retval;
}
/*
@@ -625,26 +625,26 @@ long Call_CanUnloadNow(void)
STDAPI DllCanUnloadNow(void)
{
- long result;
+ long result;
#ifdef WITH_THREAD
- PyGILState_STATE state = PyGILState_Ensure();
+ PyGILState_STATE state = PyGILState_Ensure();
#endif
- result = Call_CanUnloadNow();
+ result = Call_CanUnloadNow();
#ifdef WITH_THREAD
- PyGILState_Release(state);
+ PyGILState_Release(state);
#endif
- return result;
+ return result;
}
#ifndef Py_NO_ENABLE_SHARED
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvRes)
{
- switch(fdwReason) {
- case DLL_PROCESS_ATTACH:
- DisableThreadLibraryCalls(hinstDLL);
- break;
- }
- return TRUE;
+ switch(fdwReason) {
+ case DLL_PROCESS_ATTACH:
+ DisableThreadLibraryCalls(hinstDLL);
+ break;
+ }
+ return TRUE;
}
#endif
diff --git a/Modules/_ctypes/callproc.c b/Modules/_ctypes/callproc.c
index a543e48..2671d75 100644
--- a/Modules/_ctypes/callproc.c
+++ b/Modules/_ctypes/callproc.c
@@ -9,9 +9,9 @@
*/
/*
* Related Work:
- * - calldll http://www.nightmare.com/software.html
- * - libffi http://sourceware.cygnus.com/libffi/
- * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
+ * - calldll http://www.nightmare.com/software.html
+ * - libffi http://sourceware.cygnus.com/libffi/
+ * - ffcall http://clisp.cons.org/~haible/packages-ffcall.html
* and, of course, Don Beaudry's MESS package, but this is more ctypes
* related.
*/
@@ -94,7 +94,7 @@ CTYPES_CAPSULE_INSTANTIATE_DESTRUCTOR(CTYPES_CAPSULE_WCHAR_T)
ctypes maintains thread-local storage that has space for two error numbers:
private copies of the system 'errno' value and, on Windows, the system error code
accessed by the GetLastError() and SetLastError() api functions.
-
+
Foreign functions created with CDLL(..., use_errno=True), when called, swap
the system 'errno' value with the private copy just before the actual
function call, and swapped again immediately afterwards. The 'use_errno'
@@ -127,90 +127,90 @@ CTYPES_CAPSULE_INSTANTIATE_DESTRUCTOR(CTYPES_CAPSULE_WCHAR_T)
PyObject *
_ctypes_get_errobj(int **pspace)
{
- PyObject *dict = PyThreadState_GetDict();
- PyObject *errobj;
- static PyObject *error_object_name;
- if (dict == 0) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot get thread state");
- return NULL;
- }
- if (error_object_name == NULL) {
- error_object_name = PyString_InternFromString("ctypes.error_object");
- if (error_object_name == NULL)
- return NULL;
- }
- errobj = PyDict_GetItem(dict, error_object_name);
- if (errobj) {
+ PyObject *dict = PyThreadState_GetDict();
+ PyObject *errobj;
+ static PyObject *error_object_name;
+ if (dict == 0) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot get thread state");
+ return NULL;
+ }
+ if (error_object_name == NULL) {
+ error_object_name = PyString_InternFromString("ctypes.error_object");
+ if (error_object_name == NULL)
+ return NULL;
+ }
+ errobj = PyDict_GetItem(dict, error_object_name);
+ if (errobj) {
#ifdef CTYPES_USING_CAPSULE
- if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_ERROROBJ)) {
- PyErr_SetString(PyExc_RuntimeError,
- "ctypes.error_object is an invalid capsule");
- return NULL;
- }
+ if (!PyCapsule_IsValid(errobj, CTYPES_CAPSULE_ERROROBJ)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "ctypes.error_object is an invalid capsule");
+ return NULL;
+ }
#endif /* CTYPES_USING_CAPSULE */
- Py_INCREF(errobj);
- }
- else {
- void *space = PyMem_Malloc(sizeof(int) * 2);
- if (space == NULL)
- return NULL;
- memset(space, 0, sizeof(int) * 2);
- errobj = CAPSULE_NEW(space, CTYPES_CAPSULE_ERROROBJ);
- if (errobj == NULL)
- return NULL;
- if (-1 == PyDict_SetItem(dict, error_object_name,
- errobj)) {
- Py_DECREF(errobj);
- return NULL;
- }
- }
- *pspace = (int *)CAPSULE_DEREFERENCE(errobj, CTYPES_CAPSULE_ERROROBJ);
- return errobj;
+ Py_INCREF(errobj);
+ }
+ else {
+ void *space = PyMem_Malloc(sizeof(int) * 2);
+ if (space == NULL)
+ return NULL;
+ memset(space, 0, sizeof(int) * 2);
+ errobj = CAPSULE_NEW(space, CTYPES_CAPSULE_ERROROBJ);
+ if (errobj == NULL)
+ return NULL;
+ if (-1 == PyDict_SetItem(dict, error_object_name,
+ errobj)) {
+ Py_DECREF(errobj);
+ return NULL;
+ }
+ }
+ *pspace = (int *)CAPSULE_DEREFERENCE(errobj, CTYPES_CAPSULE_ERROROBJ);
+ return errobj;
}
static PyObject *
get_error_internal(PyObject *self, PyObject *args, int index)
{
- int *space;
- PyObject *errobj = _ctypes_get_errobj(&space);
- PyObject *result;
-
- if (errobj == NULL)
- return NULL;
- result = PyInt_FromLong(space[index]);
- Py_DECREF(errobj);
- return result;
+ int *space;
+ PyObject *errobj = _ctypes_get_errobj(&space);
+ PyObject *result;
+
+ if (errobj == NULL)
+ return NULL;
+ result = PyInt_FromLong(space[index]);
+ Py_DECREF(errobj);
+ return result;
}
static PyObject *
set_error_internal(PyObject *self, PyObject *args, int index)
{
- int new_errno, old_errno;
- PyObject *errobj;
- int *space;
-
- if (!PyArg_ParseTuple(args, "i", &new_errno))
- return NULL;
- errobj = _ctypes_get_errobj(&space);
- if (errobj == NULL)
- return NULL;
- old_errno = space[index];
- space[index] = new_errno;
- Py_DECREF(errobj);
- return PyInt_FromLong(old_errno);
+ int new_errno, old_errno;
+ PyObject *errobj;
+ int *space;
+
+ if (!PyArg_ParseTuple(args, "i", &new_errno))
+ return NULL;
+ errobj = _ctypes_get_errobj(&space);
+ if (errobj == NULL)
+ return NULL;
+ old_errno = space[index];
+ space[index] = new_errno;
+ Py_DECREF(errobj);
+ return PyInt_FromLong(old_errno);
}
static PyObject *
get_errno(PyObject *self, PyObject *args)
{
- return get_error_internal(self, args, 0);
+ return get_error_internal(self, args, 0);
}
static PyObject *
set_errno(PyObject *self, PyObject *args)
{
- return set_error_internal(self, args, 0);
+ return set_error_internal(self, args, 0);
}
#ifdef MS_WIN32
@@ -218,202 +218,202 @@ set_errno(PyObject *self, PyObject *args)
static PyObject *
get_last_error(PyObject *self, PyObject *args)
{
- return get_error_internal(self, args, 1);
+ return get_error_internal(self, args, 1);
}
static PyObject *
set_last_error(PyObject *self, PyObject *args)
{
- return set_error_internal(self, args, 1);
+ return set_error_internal(self, args, 1);
}
PyObject *ComError;
static TCHAR *FormatError(DWORD code)
{
- TCHAR *lpMsgBuf;
- DWORD n;
- n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- code,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL);
- if (n) {
- while (_istspace(lpMsgBuf[n-1]))
- --n;
- lpMsgBuf[n] = _T('\0'); /* rstrip() */
- }
- return lpMsgBuf;
+ TCHAR *lpMsgBuf;
+ DWORD n;
+ n = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL,
+ code,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
+ (LPTSTR) &lpMsgBuf,
+ 0,
+ NULL);
+ if (n) {
+ while (_istspace(lpMsgBuf[n-1]))
+ --n;
+ lpMsgBuf[n] = _T('\0'); /* rstrip() */
+ }
+ return lpMsgBuf;
}
#ifndef DONT_USE_SEH
static void SetException(DWORD code, EXCEPTION_RECORD *pr)
{
- /* The 'code' is a normal win32 error code so it could be handled by
- PyErr_SetFromWindowsErr(). However, for some errors, we have additional
- information not included in the error code. We handle those here and
- delegate all others to the generic function. */
- switch (code) {
- case EXCEPTION_ACCESS_VIOLATION:
- /* The thread attempted to read from or write
- to a virtual address for which it does not
- have the appropriate access. */
- if (pr->ExceptionInformation[0] == 0)
- PyErr_Format(PyExc_WindowsError,
- "exception: access violation reading %p",
- pr->ExceptionInformation[1]);
- else
- PyErr_Format(PyExc_WindowsError,
- "exception: access violation writing %p",
- pr->ExceptionInformation[1]);
- break;
-
- case EXCEPTION_BREAKPOINT:
- /* A breakpoint was encountered. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: breakpoint encountered");
- break;
-
- case EXCEPTION_DATATYPE_MISALIGNMENT:
- /* The thread attempted to read or write data that is
- misaligned on hardware that does not provide
- alignment. For example, 16-bit values must be
- aligned on 2-byte boundaries, 32-bit values on
- 4-byte boundaries, and so on. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: datatype misalignment");
- break;
-
- case EXCEPTION_SINGLE_STEP:
- /* A trace trap or other single-instruction mechanism
- signaled that one instruction has been executed. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: single step");
- break;
-
- case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
- /* The thread attempted to access an array element
- that is out of bounds, and the underlying hardware
- supports bounds checking. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: array bounds exceeded");
- break;
-
- case EXCEPTION_FLT_DENORMAL_OPERAND:
- /* One of the operands in a floating-point operation
- is denormal. A denormal value is one that is too
- small to represent as a standard floating-point
- value. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: floating-point operand denormal");
- break;
-
- case EXCEPTION_FLT_DIVIDE_BY_ZERO:
- /* The thread attempted to divide a floating-point
- value by a floating-point divisor of zero. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float divide by zero");
- break;
-
- case EXCEPTION_FLT_INEXACT_RESULT:
- /* The result of a floating-point operation cannot be
- represented exactly as a decimal fraction. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float inexact");
- break;
-
- case EXCEPTION_FLT_INVALID_OPERATION:
- /* This exception represents any floating-point
- exception not included in this list. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float invalid operation");
- break;
-
- case EXCEPTION_FLT_OVERFLOW:
- /* The exponent of a floating-point operation is
- greater than the magnitude allowed by the
- corresponding type. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float overflow");
- break;
-
- case EXCEPTION_FLT_STACK_CHECK:
- /* The stack overflowed or underflowed as the result
- of a floating-point operation. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: stack over/underflow");
- break;
-
- case EXCEPTION_STACK_OVERFLOW:
- /* The stack overflowed or underflowed as the result
- of a floating-point operation. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: stack overflow");
- break;
-
- case EXCEPTION_FLT_UNDERFLOW:
- /* The exponent of a floating-point operation is less
- than the magnitude allowed by the corresponding
- type. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: float underflow");
- break;
-
- case EXCEPTION_INT_DIVIDE_BY_ZERO:
- /* The thread attempted to divide an integer value by
- an integer divisor of zero. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: integer divide by zero");
- break;
-
- case EXCEPTION_INT_OVERFLOW:
- /* The result of an integer operation caused a carry
- out of the most significant bit of the result. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: integer overflow");
- break;
-
- case EXCEPTION_PRIV_INSTRUCTION:
- /* The thread attempted to execute an instruction
- whose operation is not allowed in the current
- machine mode. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: priviledged instruction");
- break;
-
- case EXCEPTION_NONCONTINUABLE_EXCEPTION:
- /* The thread attempted to continue execution after a
- noncontinuable exception occurred. */
- PyErr_SetString(PyExc_WindowsError,
- "exception: nocontinuable");
- break;
-
- default:
- PyErr_SetFromWindowsErr(code);
- break;
- }
+ /* The 'code' is a normal win32 error code so it could be handled by
+ PyErr_SetFromWindowsErr(). However, for some errors, we have additional
+ information not included in the error code. We handle those here and
+ delegate all others to the generic function. */
+ switch (code) {
+ case EXCEPTION_ACCESS_VIOLATION:
+ /* The thread attempted to read from or write
+ to a virtual address for which it does not
+ have the appropriate access. */
+ if (pr->ExceptionInformation[0] == 0)
+ PyErr_Format(PyExc_WindowsError,
+ "exception: access violation reading %p",
+ pr->ExceptionInformation[1]);
+ else
+ PyErr_Format(PyExc_WindowsError,
+ "exception: access violation writing %p",
+ pr->ExceptionInformation[1]);
+ break;
+
+ case EXCEPTION_BREAKPOINT:
+ /* A breakpoint was encountered. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: breakpoint encountered");
+ break;
+
+ case EXCEPTION_DATATYPE_MISALIGNMENT:
+ /* The thread attempted to read or write data that is
+ misaligned on hardware that does not provide
+ alignment. For example, 16-bit values must be
+ aligned on 2-byte boundaries, 32-bit values on
+ 4-byte boundaries, and so on. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: datatype misalignment");
+ break;
+
+ case EXCEPTION_SINGLE_STEP:
+ /* A trace trap or other single-instruction mechanism
+ signaled that one instruction has been executed. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: single step");
+ break;
+
+ case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
+ /* The thread attempted to access an array element
+ that is out of bounds, and the underlying hardware
+ supports bounds checking. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: array bounds exceeded");
+ break;
+
+ case EXCEPTION_FLT_DENORMAL_OPERAND:
+ /* One of the operands in a floating-point operation
+ is denormal. A denormal value is one that is too
+ small to represent as a standard floating-point
+ value. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: floating-point operand denormal");
+ break;
+
+ case EXCEPTION_FLT_DIVIDE_BY_ZERO:
+ /* The thread attempted to divide a floating-point
+ value by a floating-point divisor of zero. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float divide by zero");
+ break;
+
+ case EXCEPTION_FLT_INEXACT_RESULT:
+ /* The result of a floating-point operation cannot be
+ represented exactly as a decimal fraction. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float inexact");
+ break;
+
+ case EXCEPTION_FLT_INVALID_OPERATION:
+ /* This exception represents any floating-point
+ exception not included in this list. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float invalid operation");
+ break;
+
+ case EXCEPTION_FLT_OVERFLOW:
+ /* The exponent of a floating-point operation is
+ greater than the magnitude allowed by the
+ corresponding type. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float overflow");
+ break;
+
+ case EXCEPTION_FLT_STACK_CHECK:
+ /* The stack overflowed or underflowed as the result
+ of a floating-point operation. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: stack over/underflow");
+ break;
+
+ case EXCEPTION_STACK_OVERFLOW:
+ /* The stack overflowed or underflowed as the result
+ of a floating-point operation. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: stack overflow");
+ break;
+
+ case EXCEPTION_FLT_UNDERFLOW:
+ /* The exponent of a floating-point operation is less
+ than the magnitude allowed by the corresponding
+ type. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: float underflow");
+ break;
+
+ case EXCEPTION_INT_DIVIDE_BY_ZERO:
+ /* The thread attempted to divide an integer value by
+ an integer divisor of zero. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: integer divide by zero");
+ break;
+
+ case EXCEPTION_INT_OVERFLOW:
+ /* The result of an integer operation caused a carry
+ out of the most significant bit of the result. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: integer overflow");
+ break;
+
+ case EXCEPTION_PRIV_INSTRUCTION:
+ /* The thread attempted to execute an instruction
+ whose operation is not allowed in the current
+ machine mode. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: priviledged instruction");
+ break;
+
+ case EXCEPTION_NONCONTINUABLE_EXCEPTION:
+ /* The thread attempted to continue execution after a
+ noncontinuable exception occurred. */
+ PyErr_SetString(PyExc_WindowsError,
+ "exception: nocontinuable");
+ break;
+
+ default:
+ PyErr_SetFromWindowsErr(code);
+ break;
+ }
}
static DWORD HandleException(EXCEPTION_POINTERS *ptrs,
- DWORD *pdw, EXCEPTION_RECORD *record)
+ DWORD *pdw, EXCEPTION_RECORD *record)
{
- *pdw = ptrs->ExceptionRecord->ExceptionCode;
- *record = *ptrs->ExceptionRecord;
- return EXCEPTION_EXECUTE_HANDLER;
+ *pdw = ptrs->ExceptionRecord->ExceptionCode;
+ *record = *ptrs->ExceptionRecord;
+ return EXCEPTION_EXECUTE_HANDLER;
}
#endif
static PyObject *
check_hresult(PyObject *self, PyObject *args)
{
- HRESULT hr;
- if (!PyArg_ParseTuple(args, "i", &hr))
- return NULL;
- if (FAILED(hr))
- return PyErr_SetFromWindowsErr(hr);
- return PyInt_FromLong(hr);
+ HRESULT hr;
+ if (!PyArg_ParseTuple(args, "i", &hr))
+ return NULL;
+ if (FAILED(hr))
+ return PyErr_SetFromWindowsErr(hr);
+ return PyInt_FromLong(hr);
}
#endif
@@ -423,132 +423,132 @@ check_hresult(PyObject *self, PyObject *args)
PyCArgObject *
PyCArgObject_new(void)
{
- PyCArgObject *p;
- p = PyObject_New(PyCArgObject, &PyCArg_Type);
- if (p == NULL)
- return NULL;
- p->pffi_type = NULL;
- p->tag = '\0';
- p->obj = NULL;
- memset(&p->value, 0, sizeof(p->value));
- return p;
+ PyCArgObject *p;
+ p = PyObject_New(PyCArgObject, &PyCArg_Type);
+ if (p == NULL)
+ return NULL;
+ p->pffi_type = NULL;
+ p->tag = '\0';
+ p->obj = NULL;
+ memset(&p->value, 0, sizeof(p->value));
+ return p;
}
static void
PyCArg_dealloc(PyCArgObject *self)
{
- Py_XDECREF(self->obj);
- PyObject_Del(self);
+ Py_XDECREF(self->obj);
+ PyObject_Del(self);
}
static PyObject *
PyCArg_repr(PyCArgObject *self)
{
- char buffer[256];
- switch(self->tag) {
- case 'b':
- case 'B':
- sprintf(buffer, "<cparam '%c' (%d)>",
- self->tag, self->value.b);
- break;
- case 'h':
- case 'H':
- sprintf(buffer, "<cparam '%c' (%d)>",
- self->tag, self->value.h);
- break;
- case 'i':
- case 'I':
- sprintf(buffer, "<cparam '%c' (%d)>",
- self->tag, self->value.i);
- break;
- case 'l':
- case 'L':
- sprintf(buffer, "<cparam '%c' (%ld)>",
- self->tag, self->value.l);
- break;
-
+ char buffer[256];
+ switch(self->tag) {
+ case 'b':
+ case 'B':
+ sprintf(buffer, "<cparam '%c' (%d)>",
+ self->tag, self->value.b);
+ break;
+ case 'h':
+ case 'H':
+ sprintf(buffer, "<cparam '%c' (%d)>",
+ self->tag, self->value.h);
+ break;
+ case 'i':
+ case 'I':
+ sprintf(buffer, "<cparam '%c' (%d)>",
+ self->tag, self->value.i);
+ break;
+ case 'l':
+ case 'L':
+ sprintf(buffer, "<cparam '%c' (%ld)>",
+ self->tag, self->value.l);
+ break;
+
#ifdef HAVE_LONG_LONG
- case 'q':
- case 'Q':
- sprintf(buffer,
+ case 'q':
+ case 'Q':
+ sprintf(buffer,
#ifdef MS_WIN32
- "<cparam '%c' (%I64d)>",
+ "<cparam '%c' (%I64d)>",
#else
- "<cparam '%c' (%qd)>",
+ "<cparam '%c' (%qd)>",
#endif
- self->tag, self->value.q);
- break;
+ self->tag, self->value.q);
+ break;
#endif
- case 'd':
- sprintf(buffer, "<cparam '%c' (%f)>",
- self->tag, self->value.d);
- break;
- case 'f':
- sprintf(buffer, "<cparam '%c' (%f)>",
- self->tag, self->value.f);
- break;
-
- case 'c':
- sprintf(buffer, "<cparam '%c' (%c)>",
- self->tag, self->value.c);
- break;
+ case 'd':
+ sprintf(buffer, "<cparam '%c' (%f)>",
+ self->tag, self->value.d);
+ break;
+ case 'f':
+ sprintf(buffer, "<cparam '%c' (%f)>",
+ self->tag, self->value.f);
+ break;
+
+ case 'c':
+ sprintf(buffer, "<cparam '%c' (%c)>",
+ self->tag, self->value.c);
+ break;
/* Hm, are these 'z' and 'Z' codes useful at all?
Shouldn't they be replaced by the functionality of c_string
and c_wstring ?
*/
- case 'z':
- case 'Z':
- case 'P':
- sprintf(buffer, "<cparam '%c' (%p)>",
- self->tag, self->value.p);
- break;
-
- default:
- sprintf(buffer, "<cparam '%c' at %p>",
- self->tag, self);
- break;
- }
- return PyString_FromString(buffer);
+ case 'z':
+ case 'Z':
+ case 'P':
+ sprintf(buffer, "<cparam '%c' (%p)>",
+ self->tag, self->value.p);
+ break;
+
+ default:
+ sprintf(buffer, "<cparam '%c' at %p>",
+ self->tag, self);
+ break;
+ }
+ return PyString_FromString(buffer);
}
static PyMemberDef PyCArgType_members[] = {
- { "_obj", T_OBJECT,
- offsetof(PyCArgObject, obj), READONLY,
- "the wrapped object" },
- { NULL },
+ { "_obj", T_OBJECT,
+ offsetof(PyCArgObject, obj), READONLY,
+ "the wrapped object" },
+ { NULL },
};
PyTypeObject PyCArg_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "CArgObject",
- sizeof(PyCArgObject),
- 0,
- (destructor)PyCArg_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)PyCArg_repr, /* 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, /* 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 */
- PyCArgType_members, /* tp_members */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "CArgObject",
+ sizeof(PyCArgObject),
+ 0,
+ (destructor)PyCArg_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)PyCArg_repr, /* 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, /* 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 */
+ PyCArgType_members, /* tp_members */
};
/****************************************************************/
@@ -581,24 +581,24 @@ PyTypeObject PyCArg_Type = {
*/
union result {
- char c;
- char b;
- short h;
- int i;
- long l;
+ 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;
+ long double D;
+ double d;
+ float f;
+ void *p;
};
struct argument {
- ffi_type *ffi_type;
- PyObject *keep;
- union result value;
+ ffi_type *ffi_type;
+ PyObject *keep;
+ union result value;
};
/*
@@ -606,140 +606,140 @@ struct argument {
*/
static int ConvParam(PyObject *obj, Py_ssize_t index, struct argument *pa)
{
- StgDictObject *dict;
- pa->keep = NULL; /* so we cannot forget it later */
-
- dict = PyObject_stgdict(obj);
- if (dict) {
- PyCArgObject *carg;
- assert(dict->paramfunc);
- /* If it has an stgdict, it is a CDataObject */
- carg = dict->paramfunc((CDataObject *)obj);
- pa->ffi_type = carg->pffi_type;
- memcpy(&pa->value, &carg->value, sizeof(pa->value));
- pa->keep = (PyObject *)carg;
- return 0;
- }
-
- if (PyCArg_CheckExact(obj)) {
- PyCArgObject *carg = (PyCArgObject *)obj;
- pa->ffi_type = carg->pffi_type;
- Py_INCREF(obj);
- pa->keep = obj;
- memcpy(&pa->value, &carg->value, sizeof(pa->value));
- return 0;
- }
-
- /* check for None, integer, string or unicode and use directly if successful */
- if (obj == Py_None) {
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = NULL;
- return 0;
- }
-
- if (PyInt_Check(obj)) {
- pa->ffi_type = &ffi_type_sint;
- pa->value.i = PyInt_AS_LONG(obj);
- return 0;
- }
-
- if (PyLong_Check(obj)) {
- pa->ffi_type = &ffi_type_sint;
- pa->value.i = (long)PyLong_AsUnsignedLong(obj);
- if (pa->value.i == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- pa->value.i = PyLong_AsLong(obj);
- if (pa->value.i == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_OverflowError,
- "long int too long to convert");
- return -1;
- }
- }
- return 0;
- }
-
- if (PyString_Check(obj)) {
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = PyString_AS_STRING(obj);
- Py_INCREF(obj);
- pa->keep = obj;
- return 0;
- }
+ StgDictObject *dict;
+ pa->keep = NULL; /* so we cannot forget it later */
+
+ dict = PyObject_stgdict(obj);
+ if (dict) {
+ PyCArgObject *carg;
+ assert(dict->paramfunc);
+ /* If it has an stgdict, it is a CDataObject */
+ carg = dict->paramfunc((CDataObject *)obj);
+ pa->ffi_type = carg->pffi_type;
+ memcpy(&pa->value, &carg->value, sizeof(pa->value));
+ pa->keep = (PyObject *)carg;
+ return 0;
+ }
+
+ if (PyCArg_CheckExact(obj)) {
+ PyCArgObject *carg = (PyCArgObject *)obj;
+ pa->ffi_type = carg->pffi_type;
+ Py_INCREF(obj);
+ pa->keep = obj;
+ memcpy(&pa->value, &carg->value, sizeof(pa->value));
+ return 0;
+ }
+
+ /* check for None, integer, string or unicode and use directly if successful */
+ if (obj == Py_None) {
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = NULL;
+ return 0;
+ }
+
+ if (PyInt_Check(obj)) {
+ pa->ffi_type = &ffi_type_sint;
+ pa->value.i = PyInt_AS_LONG(obj);
+ return 0;
+ }
+
+ if (PyLong_Check(obj)) {
+ pa->ffi_type = &ffi_type_sint;
+ pa->value.i = (long)PyLong_AsUnsignedLong(obj);
+ if (pa->value.i == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ pa->value.i = PyLong_AsLong(obj);
+ if (pa->value.i == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_OverflowError,
+ "long int too long to convert");
+ return -1;
+ }
+ }
+ return 0;
+ }
+
+ if (PyString_Check(obj)) {
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = PyString_AS_STRING(obj);
+ Py_INCREF(obj);
+ pa->keep = obj;
+ return 0;
+ }
#ifdef CTYPES_UNICODE
- if (PyUnicode_Check(obj)) {
+ if (PyUnicode_Check(obj)) {
#ifdef HAVE_USABLE_WCHAR_T
- pa->ffi_type = &ffi_type_pointer;
- pa->value.p = PyUnicode_AS_UNICODE(obj);
- Py_INCREF(obj);
- pa->keep = obj;
- return 0;
+ pa->ffi_type = &ffi_type_pointer;
+ pa->value.p = PyUnicode_AS_UNICODE(obj);
+ Py_INCREF(obj);
+ pa->keep = obj;
+ return 0;
#else
- int size = PyUnicode_GET_SIZE(obj);
- pa->ffi_type = &ffi_type_pointer;
- size += 1; /* terminating NUL */
- size *= sizeof(wchar_t);
- pa->value.p = PyMem_Malloc(size);
- if (!pa->value.p) {
- PyErr_NoMemory();
- return -1;
- }
- memset(pa->value.p, 0, size);
- pa->keep = CAPSULE_NEW(pa->value.p, CTYPES_CAPSULE_WCHAR_T);
- if (!pa->keep) {
- PyMem_Free(pa->value.p);
- return -1;
- }
- if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
- pa->value.p, PyUnicode_GET_SIZE(obj)))
- return -1;
- return 0;
+ int size = PyUnicode_GET_SIZE(obj);
+ pa->ffi_type = &ffi_type_pointer;
+ size += 1; /* terminating NUL */
+ size *= sizeof(wchar_t);
+ pa->value.p = PyMem_Malloc(size);
+ if (!pa->value.p) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memset(pa->value.p, 0, size);
+ pa->keep = CAPSULE_NEW(pa->value.p, CTYPES_CAPSULE_WCHAR_T);
+ if (!pa->keep) {
+ PyMem_Free(pa->value.p);
+ return -1;
+ }
+ if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)obj,
+ pa->value.p, PyUnicode_GET_SIZE(obj)))
+ return -1;
+ return 0;
#endif
- }
+ }
#endif
- {
- PyObject *arg;
- arg = PyObject_GetAttrString(obj, "_as_parameter_");
- /* Which types should we exactly allow here?
- integers are required for using Python classes
- as parameters (they have to expose the '_as_parameter_'
- attribute)
- */
- if (arg) {
- int result;
- result = ConvParam(arg, index, pa);
- Py_DECREF(arg);
- return result;
- }
- PyErr_Format(PyExc_TypeError,
- "Don't know how to convert parameter %d",
- Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
- return -1;
- }
+ {
+ PyObject *arg;
+ arg = PyObject_GetAttrString(obj, "_as_parameter_");
+ /* Which types should we exactly allow here?
+ integers are required for using Python classes
+ as parameters (they have to expose the '_as_parameter_'
+ attribute)
+ */
+ if (arg) {
+ int result;
+ result = ConvParam(arg, index, pa);
+ Py_DECREF(arg);
+ return result;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "Don't know how to convert parameter %d",
+ Py_SAFE_DOWNCAST(index, Py_ssize_t, int));
+ return -1;
+ }
}
ffi_type *_ctypes_get_ffi_type(PyObject *obj)
{
- StgDictObject *dict;
- if (obj == NULL)
- return &ffi_type_sint;
- dict = PyType_stgdict(obj);
- if (dict == NULL)
- return &ffi_type_sint;
+ StgDictObject *dict;
+ if (obj == NULL)
+ return &ffi_type_sint;
+ dict = PyType_stgdict(obj);
+ if (dict == NULL)
+ return &ffi_type_sint;
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
- /* This little trick works correctly with MSVC.
- It returns small structures in registers
- */
- if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
- if (dict->ffi_type_pointer.size <= 4)
- return &ffi_type_sint32;
- else if (dict->ffi_type_pointer.size <= 8)
- return &ffi_type_sint64;
- }
+ /* This little trick works correctly with MSVC.
+ It returns small structures in registers
+ */
+ if (dict->ffi_type_pointer.type == FFI_TYPE_STRUCT) {
+ if (dict->ffi_type_pointer.size <= 4)
+ return &ffi_type_sint32;
+ else if (dict->ffi_type_pointer.size <= 8)
+ return &ffi_type_sint64;
+ }
#endif
- return &dict->ffi_type_pointer;
+ return &dict->ffi_type_pointer;
}
@@ -747,7 +747,7 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj)
* libffi uses:
*
* ffi_status ffi_prep_cif(ffi_cif *cif, ffi_abi abi,
- * unsigned int nargs,
+ * unsigned int nargs,
* ffi_type *rtype,
* ffi_type **atypes);
*
@@ -756,108 +756,108 @@ ffi_type *_ctypes_get_ffi_type(PyObject *obj)
* void ffi_call(ffi_cif *cif, void *fn, void *rvalue, void **avalues);
*/
static int _call_function_pointer(int flags,
- PPROC pProc,
- void **avalues,
- ffi_type **atypes,
- ffi_type *restype,
- void *resmem,
- int argcount)
+ PPROC pProc,
+ void **avalues,
+ ffi_type **atypes,
+ ffi_type *restype,
+ void *resmem,
+ int argcount)
{
#ifdef WITH_THREAD
- PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
+ PyThreadState *_save = NULL; /* For Py_BLOCK_THREADS and Py_UNBLOCK_THREADS */
#endif
- PyObject *error_object = NULL;
- int *space;
- ffi_cif cif;
- int cc;
+ PyObject *error_object = NULL;
+ int *space;
+ ffi_cif cif;
+ int cc;
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
- DWORD dwExceptionCode = 0;
- EXCEPTION_RECORD record;
+ DWORD dwExceptionCode = 0;
+ EXCEPTION_RECORD record;
#endif
#endif
- /* XXX check before here */
- if (restype == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "No ffi_type for result");
- return -1;
- }
-
- cc = FFI_DEFAULT_ABI;
+ /* XXX check before here */
+ if (restype == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "No ffi_type for result");
+ return -1;
+ }
+
+ cc = FFI_DEFAULT_ABI;
#if defined(MS_WIN32) && !defined(MS_WIN64) && !defined(_WIN32_WCE)
- if ((flags & FUNCFLAG_CDECL) == 0)
- cc = FFI_STDCALL;
+ if ((flags & FUNCFLAG_CDECL) == 0)
+ cc = FFI_STDCALL;
#endif
- if (FFI_OK != ffi_prep_cif(&cif,
- cc,
- argcount,
- restype,
- atypes)) {
- PyErr_SetString(PyExc_RuntimeError,
- "ffi_prep_cif failed");
- return -1;
- }
-
- if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
- error_object = _ctypes_get_errobj(&space);
- if (error_object == NULL)
- return -1;
- }
+ if (FFI_OK != ffi_prep_cif(&cif,
+ cc,
+ argcount,
+ restype,
+ atypes)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "ffi_prep_cif failed");
+ return -1;
+ }
+
+ if (flags & (FUNCFLAG_USE_ERRNO | FUNCFLAG_USE_LASTERROR)) {
+ error_object = _ctypes_get_errobj(&space);
+ if (error_object == NULL)
+ return -1;
+ }
#ifdef WITH_THREAD
- if ((flags & FUNCFLAG_PYTHONAPI) == 0)
- Py_UNBLOCK_THREADS
+ if ((flags & FUNCFLAG_PYTHONAPI) == 0)
+ Py_UNBLOCK_THREADS
#endif
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
#ifdef MS_WIN32
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#ifndef DONT_USE_SEH
- __try {
+ __try {
#endif
#endif
- ffi_call(&cif, (void *)pProc, resmem, avalues);
+ ffi_call(&cif, (void *)pProc, resmem, avalues);
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
- }
- __except (HandleException(GetExceptionInformation(),
- &dwExceptionCode, &record)) {
- ;
- }
+ }
+ __except (HandleException(GetExceptionInformation(),
+ &dwExceptionCode, &record)) {
+ ;
+ }
#endif
- if (flags & FUNCFLAG_USE_LASTERROR) {
- int temp = space[1];
- space[1] = GetLastError();
- SetLastError(temp);
- }
+ if (flags & FUNCFLAG_USE_LASTERROR) {
+ int temp = space[1];
+ space[1] = GetLastError();
+ SetLastError(temp);
+ }
#endif
- if (flags & FUNCFLAG_USE_ERRNO) {
- int temp = space[0];
- space[0] = errno;
- errno = temp;
- }
- Py_XDECREF(error_object);
+ if (flags & FUNCFLAG_USE_ERRNO) {
+ int temp = space[0];
+ space[0] = errno;
+ errno = temp;
+ }
+ Py_XDECREF(error_object);
#ifdef WITH_THREAD
- if ((flags & FUNCFLAG_PYTHONAPI) == 0)
- Py_BLOCK_THREADS
+ if ((flags & FUNCFLAG_PYTHONAPI) == 0)
+ Py_BLOCK_THREADS
#endif
#ifdef MS_WIN32
#ifndef DONT_USE_SEH
- if (dwExceptionCode) {
- SetException(dwExceptionCode, &record);
- return -1;
- }
+ if (dwExceptionCode) {
+ SetException(dwExceptionCode, &record);
+ return -1;
+ }
#endif
#endif
- if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
- return -1;
- return 0;
+ if ((flags & FUNCFLAG_PYTHONAPI) && PyErr_Occurred())
+ return -1;
+ return 0;
}
/*
@@ -872,41 +872,41 @@ static int _call_function_pointer(int flags,
*/
static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
{
- StgDictObject *dict;
- PyObject *retval, *v;
-
- if (restype == NULL)
- return PyInt_FromLong(*(int *)result);
-
- if (restype == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- dict = PyType_stgdict(restype);
- if (dict == NULL)
- return PyObject_CallFunction(restype, "i", *(int *)result);
-
- if (dict->getfunc && !_ctypes_simple_instance(restype)) {
- retval = dict->getfunc(result, dict->size);
- /* If restype is py_object (detected by comparing getfunc with
- O_get), we have to call Py_DECREF because O_get has already
- called Py_INCREF.
- */
- if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
- Py_DECREF(retval);
- }
- } else
- retval = PyCData_FromBaseObj(restype, NULL, 0, result);
-
- if (!checker || !retval)
- return retval;
-
- v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
- if (v == NULL)
- _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
- Py_DECREF(retval);
- return v;
+ StgDictObject *dict;
+ PyObject *retval, *v;
+
+ if (restype == NULL)
+ return PyInt_FromLong(*(int *)result);
+
+ if (restype == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ dict = PyType_stgdict(restype);
+ if (dict == NULL)
+ return PyObject_CallFunction(restype, "i", *(int *)result);
+
+ if (dict->getfunc && !_ctypes_simple_instance(restype)) {
+ retval = dict->getfunc(result, dict->size);
+ /* If restype is py_object (detected by comparing getfunc with
+ O_get), we have to call Py_DECREF because O_get has already
+ called Py_INCREF.
+ */
+ if (dict->getfunc == _ctypes_get_fielddesc("O")->getfunc) {
+ Py_DECREF(retval);
+ }
+ } else
+ retval = PyCData_FromBaseObj(restype, NULL, 0, result);
+
+ if (!checker || !retval)
+ return retval;
+
+ v = PyObject_CallFunctionObjArgs(checker, retval, NULL);
+ if (v == NULL)
+ _ctypes_add_traceback("GetResult", "_ctypes/callproc.c", __LINE__-2);
+ Py_DECREF(retval);
+ return v;
}
/*
@@ -915,40 +915,40 @@ static PyObject *GetResult(PyObject *restype, void *result, PyObject *checker)
*/
void _ctypes_extend_error(PyObject *exc_class, char *fmt, ...)
{
- va_list vargs;
- PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
-
- va_start(vargs, fmt);
- s = PyString_FromFormatV(fmt, vargs);
- va_end(vargs);
- if (!s)
- return;
-
- PyErr_Fetch(&tp, &v, &tb);
- PyErr_NormalizeException(&tp, &v, &tb);
- cls_str = PyObject_Str(tp);
- if (cls_str) {
- PyString_ConcatAndDel(&s, cls_str);
- PyString_ConcatAndDel(&s, PyString_FromString(": "));
- if (s == NULL)
- goto error;
- } else
- PyErr_Clear();
- msg_str = PyObject_Str(v);
- if (msg_str)
- PyString_ConcatAndDel(&s, msg_str);
- else {
- PyErr_Clear();
- PyString_ConcatAndDel(&s, PyString_FromString("???"));
- if (s == NULL)
- goto error;
- }
- PyErr_SetObject(exc_class, s);
+ va_list vargs;
+ PyObject *tp, *v, *tb, *s, *cls_str, *msg_str;
+
+ va_start(vargs, fmt);
+ s = PyString_FromFormatV(fmt, vargs);
+ va_end(vargs);
+ if (!s)
+ return;
+
+ PyErr_Fetch(&tp, &v, &tb);
+ PyErr_NormalizeException(&tp, &v, &tb);
+ cls_str = PyObject_Str(tp);
+ if (cls_str) {
+ PyString_ConcatAndDel(&s, cls_str);
+ PyString_ConcatAndDel(&s, PyString_FromString(": "));
+ if (s == NULL)
+ goto error;
+ } else
+ PyErr_Clear();
+ msg_str = PyObject_Str(v);
+ if (msg_str)
+ PyString_ConcatAndDel(&s, msg_str);
+ else {
+ PyErr_Clear();
+ PyString_ConcatAndDel(&s, PyString_FromString("???"));
+ if (s == NULL)
+ goto error;
+ }
+ PyErr_SetObject(exc_class, s);
error:
- Py_XDECREF(tp);
- Py_XDECREF(v);
- Py_XDECREF(tb);
- Py_XDECREF(s);
+ Py_XDECREF(tp);
+ Py_XDECREF(v);
+ Py_XDECREF(tb);
+ Py_XDECREF(s);
}
@@ -957,77 +957,77 @@ error:
static PyObject *
GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
{
- HRESULT hr;
- ISupportErrorInfo *psei = NULL;
- IErrorInfo *pei = NULL;
- BSTR descr=NULL, helpfile=NULL, source=NULL;
- GUID guid;
- DWORD helpcontext=0;
- LPOLESTR progid;
- PyObject *obj;
- TCHAR *text;
-
- /* We absolutely have to release the GIL during COM method calls,
- otherwise we may get a deadlock!
- */
+ HRESULT hr;
+ ISupportErrorInfo *psei = NULL;
+ IErrorInfo *pei = NULL;
+ BSTR descr=NULL, helpfile=NULL, source=NULL;
+ GUID guid;
+ DWORD helpcontext=0;
+ LPOLESTR progid;
+ PyObject *obj;
+ TCHAR *text;
+
+ /* We absolutely have to release the GIL during COM method calls,
+ otherwise we may get a deadlock!
+ */
#ifdef WITH_THREAD
- Py_BEGIN_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
#endif
- hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
- if (FAILED(hr))
- goto failed;
+ hr = pIunk->lpVtbl->QueryInterface(pIunk, &IID_ISupportErrorInfo, (void **)&psei);
+ if (FAILED(hr))
+ goto failed;
- hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
- psei->lpVtbl->Release(psei);
- if (FAILED(hr))
- goto failed;
+ hr = psei->lpVtbl->InterfaceSupportsErrorInfo(psei, riid);
+ psei->lpVtbl->Release(psei);
+ if (FAILED(hr))
+ goto failed;
- hr = GetErrorInfo(0, &pei);
- if (hr != S_OK)
- goto failed;
+ hr = GetErrorInfo(0, &pei);
+ if (hr != S_OK)
+ goto failed;
- pei->lpVtbl->GetDescription(pei, &descr);
- pei->lpVtbl->GetGUID(pei, &guid);
- pei->lpVtbl->GetHelpContext(pei, &helpcontext);
- pei->lpVtbl->GetHelpFile(pei, &helpfile);
- pei->lpVtbl->GetSource(pei, &source);
+ pei->lpVtbl->GetDescription(pei, &descr);
+ pei->lpVtbl->GetGUID(pei, &guid);
+ pei->lpVtbl->GetHelpContext(pei, &helpcontext);
+ pei->lpVtbl->GetHelpFile(pei, &helpfile);
+ pei->lpVtbl->GetSource(pei, &source);
- pei->lpVtbl->Release(pei);
+ pei->lpVtbl->Release(pei);
failed:
#ifdef WITH_THREAD
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
#endif
- progid = NULL;
- ProgIDFromCLSID(&guid, &progid);
+ progid = NULL;
+ ProgIDFromCLSID(&guid, &progid);
- text = FormatError(errcode);
- obj = Py_BuildValue(
+ text = FormatError(errcode);
+ obj = Py_BuildValue(
#ifdef _UNICODE
- "iu(uuuiu)",
+ "iu(uuuiu)",
#else
- "is(uuuiu)",
+ "is(uuuiu)",
#endif
- errcode,
- text,
- descr, source, helpfile, helpcontext,
- progid);
- if (obj) {
- PyErr_SetObject(ComError, obj);
- Py_DECREF(obj);
- }
- LocalFree(text);
-
- if (descr)
- SysFreeString(descr);
- if (helpfile)
- SysFreeString(helpfile);
- if (source)
- SysFreeString(source);
-
- return NULL;
+ errcode,
+ text,
+ descr, source, helpfile, helpcontext,
+ progid);
+ if (obj) {
+ PyErr_SetObject(ComError, obj);
+ Py_DECREF(obj);
+ }
+ LocalFree(text);
+
+ if (descr)
+ SysFreeString(descr);
+ if (helpfile)
+ SysFreeString(helpfile);
+ if (source)
+ SysFreeString(source);
+
+ return NULL;
}
#endif
@@ -1039,154 +1039,154 @@ GetComError(HRESULT errcode, GUID *riid, IUnknown *pIunk)
* - XXX various requirements for restype, not yet collected
*/
PyObject *_ctypes_callproc(PPROC pProc,
- PyObject *argtuple,
+ PyObject *argtuple,
#ifdef MS_WIN32
- IUnknown *pIunk,
- GUID *iid,
+ IUnknown *pIunk,
+ GUID *iid,
#endif
- int flags,
- PyObject *argtypes, /* misleading name: This is a tuple of
- methods, not types: the .from_param
- class methods of the types */
- PyObject *restype,
- PyObject *checker)
+ int flags,
+ PyObject *argtypes, /* misleading name: This is a tuple of
+ methods, not types: the .from_param
+ class methods of the types */
+ PyObject *restype,
+ PyObject *checker)
{
- Py_ssize_t i, n, argcount, argtype_count;
- void *resbuf;
- struct argument *args, *pa;
- ffi_type **atypes;
- ffi_type *rtype;
- void **avalues;
- PyObject *retval = NULL;
-
- n = argcount = PyTuple_GET_SIZE(argtuple);
+ Py_ssize_t i, n, argcount, argtype_count;
+ void *resbuf;
+ struct argument *args, *pa;
+ ffi_type **atypes;
+ ffi_type *rtype;
+ void **avalues;
+ PyObject *retval = NULL;
+
+ n = argcount = PyTuple_GET_SIZE(argtuple);
#ifdef MS_WIN32
- /* an optional COM object this pointer */
- if (pIunk)
- ++argcount;
+ /* an optional COM object this pointer */
+ if (pIunk)
+ ++argcount;
#endif
- args = (struct argument *)alloca(sizeof(struct argument) * argcount);
- if (!args) {
- PyErr_NoMemory();
- return NULL;
- }
- memset(args, 0, sizeof(struct argument) * argcount);
- argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
+ args = (struct argument *)alloca(sizeof(struct argument) * argcount);
+ if (!args) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(args, 0, sizeof(struct argument) * argcount);
+ argtype_count = argtypes ? PyTuple_GET_SIZE(argtypes) : 0;
#ifdef MS_WIN32
- if (pIunk) {
- args[0].ffi_type = &ffi_type_pointer;
- args[0].value.p = pIunk;
- pa = &args[1];
- } else
+ if (pIunk) {
+ args[0].ffi_type = &ffi_type_pointer;
+ args[0].value.p = pIunk;
+ pa = &args[1];
+ } else
#endif
- pa = &args[0];
-
- /* Convert the arguments */
- for (i = 0; i < n; ++i, ++pa) {
- PyObject *converter;
- PyObject *arg;
- int err;
-
- arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
- /* For cdecl functions, we allow more actual arguments
- than the length of the argtypes tuple.
- This is checked in _ctypes::PyCFuncPtr_Call
- */
- if (argtypes && argtype_count > i) {
- PyObject *v;
- converter = PyTuple_GET_ITEM(argtypes, i);
- v = PyObject_CallFunctionObjArgs(converter,
- arg,
- NULL);
- if (v == NULL) {
- _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup;
- }
-
- err = ConvParam(v, i+1, pa);
- Py_DECREF(v);
- if (-1 == err) {
- _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup;
- }
- } else {
- err = ConvParam(arg, i+1, pa);
- if (-1 == err) {
- _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
- goto cleanup; /* leaking ? */
- }
- }
- }
-
- rtype = _ctypes_get_ffi_type(restype);
- resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
-
- avalues = (void **)alloca(sizeof(void *) * argcount);
- atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
- if (!resbuf || !avalues || !atypes) {
- PyErr_NoMemory();
- goto cleanup;
- }
- for (i = 0; i < argcount; ++i) {
- atypes[i] = args[i].ffi_type;
- if (atypes[i]->type == FFI_TYPE_STRUCT)
- avalues[i] = (void *)args[i].value.p;
- else
- avalues[i] = (void *)&args[i].value;
- }
-
- if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
- rtype, resbuf,
- Py_SAFE_DOWNCAST(argcount,
- Py_ssize_t,
- int)))
- goto cleanup;
+ pa = &args[0];
+
+ /* Convert the arguments */
+ for (i = 0; i < n; ++i, ++pa) {
+ PyObject *converter;
+ PyObject *arg;
+ int err;
+
+ arg = PyTuple_GET_ITEM(argtuple, i); /* borrowed ref */
+ /* For cdecl functions, we allow more actual arguments
+ than the length of the argtypes tuple.
+ This is checked in _ctypes::PyCFuncPtr_Call
+ */
+ if (argtypes && argtype_count > i) {
+ PyObject *v;
+ converter = PyTuple_GET_ITEM(argtypes, i);
+ v = PyObject_CallFunctionObjArgs(converter,
+ arg,
+ NULL);
+ if (v == NULL) {
+ _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup;
+ }
+
+ err = ConvParam(v, i+1, pa);
+ Py_DECREF(v);
+ if (-1 == err) {
+ _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup;
+ }
+ } else {
+ err = ConvParam(arg, i+1, pa);
+ if (-1 == err) {
+ _ctypes_extend_error(PyExc_ArgError, "argument %d: ", i+1);
+ goto cleanup; /* leaking ? */
+ }
+ }
+ }
+
+ rtype = _ctypes_get_ffi_type(restype);
+ resbuf = alloca(max(rtype->size, sizeof(ffi_arg)));
+
+ avalues = (void **)alloca(sizeof(void *) * argcount);
+ atypes = (ffi_type **)alloca(sizeof(ffi_type *) * argcount);
+ if (!resbuf || !avalues || !atypes) {
+ PyErr_NoMemory();
+ goto cleanup;
+ }
+ for (i = 0; i < argcount; ++i) {
+ atypes[i] = args[i].ffi_type;
+ if (atypes[i]->type == FFI_TYPE_STRUCT)
+ avalues[i] = (void *)args[i].value.p;
+ else
+ avalues[i] = (void *)&args[i].value;
+ }
+
+ if (-1 == _call_function_pointer(flags, pProc, avalues, atypes,
+ rtype, resbuf,
+ Py_SAFE_DOWNCAST(argcount,
+ Py_ssize_t,
+ int)))
+ goto cleanup;
#ifdef WORDS_BIGENDIAN
- /* libffi returns the result in a buffer with sizeof(ffi_arg). This
- causes problems on big endian machines, since the result buffer
- address cannot simply be used as result pointer, instead we must
- adjust the pointer value:
- */
- /*
- XXX I should find out and clarify why this is needed at all,
- especially why adjusting for ffi_type_float must be avoided on
- 64-bit platforms.
- */
- if (rtype->type != FFI_TYPE_FLOAT
- && rtype->type != FFI_TYPE_STRUCT
- && rtype->size < sizeof(ffi_arg))
- resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
+ /* libffi returns the result in a buffer with sizeof(ffi_arg). This
+ causes problems on big endian machines, since the result buffer
+ address cannot simply be used as result pointer, instead we must
+ adjust the pointer value:
+ */
+ /*
+ XXX I should find out and clarify why this is needed at all,
+ especially why adjusting for ffi_type_float must be avoided on
+ 64-bit platforms.
+ */
+ if (rtype->type != FFI_TYPE_FLOAT
+ && rtype->type != FFI_TYPE_STRUCT
+ && rtype->size < sizeof(ffi_arg))
+ resbuf = (char *)resbuf + sizeof(ffi_arg) - rtype->size;
#endif
#ifdef MS_WIN32
- if (iid && pIunk) {
- if (*(int *)resbuf & 0x80000000)
- retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
- else
- retval = PyInt_FromLong(*(int *)resbuf);
- } else if (flags & FUNCFLAG_HRESULT) {
- if (*(int *)resbuf & 0x80000000)
- retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
- else
- retval = PyInt_FromLong(*(int *)resbuf);
- } else
+ if (iid && pIunk) {
+ if (*(int *)resbuf & 0x80000000)
+ retval = GetComError(*(HRESULT *)resbuf, iid, pIunk);
+ else
+ retval = PyInt_FromLong(*(int *)resbuf);
+ } else if (flags & FUNCFLAG_HRESULT) {
+ if (*(int *)resbuf & 0x80000000)
+ retval = PyErr_SetFromWindowsErr(*(int *)resbuf);
+ else
+ retval = PyInt_FromLong(*(int *)resbuf);
+ } else
#endif
- retval = GetResult(restype, resbuf, checker);
+ retval = GetResult(restype, resbuf, checker);
cleanup:
- for (i = 0; i < argcount; ++i)
- Py_XDECREF(args[i].keep);
- return retval;
+ for (i = 0; i < argcount; ++i)
+ Py_XDECREF(args[i].keep);
+ return retval;
}
static int
_parse_voidp(PyObject *obj, void **address)
{
- *address = PyLong_AsVoidPtr(obj);
- if (*address == NULL)
- return 0;
- return 1;
+ *address = PyLong_AsVoidPtr(obj);
+ if (*address == NULL)
+ return 0;
+ return 1;
}
#ifdef MS_WIN32
@@ -1207,21 +1207,21 @@ Convert a win32 error code into a string. If the error code is not\n\
given, the return value of a call to GetLastError() is used.\n";
static PyObject *format_error(PyObject *self, PyObject *args)
{
- PyObject *result;
- TCHAR *lpMsgBuf;
- DWORD code = 0;
- if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
- return NULL;
- if (code == 0)
- code = GetLastError();
- lpMsgBuf = FormatError(code);
- if (lpMsgBuf) {
- result = Py_BuildValue(PYBUILD_TSTR, lpMsgBuf);
- LocalFree(lpMsgBuf);
- } else {
- result = Py_BuildValue("s", "<no description>");
- }
- return result;
+ PyObject *result;
+ TCHAR *lpMsgBuf;
+ DWORD code = 0;
+ if (!PyArg_ParseTuple(args, "|i:FormatError", &code))
+ return NULL;
+ if (code == 0)
+ code = GetLastError();
+ lpMsgBuf = FormatError(code);
+ if (lpMsgBuf) {
+ result = Py_BuildValue(PYBUILD_TSTR, lpMsgBuf);
+ LocalFree(lpMsgBuf);
+ } else {
+ result = Py_BuildValue("s", "<no description>");
+ }
+ return result;
}
static char load_library_doc[] =
@@ -1232,40 +1232,40 @@ The handle may be used to locate exported functions in this\n\
module.\n";
static PyObject *load_library(PyObject *self, PyObject *args)
{
- TCHAR *name;
- PyObject *nameobj;
- PyObject *ignored;
- HMODULE hMod;
- if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
- return NULL;
+ TCHAR *name;
+ PyObject *nameobj;
+ PyObject *ignored;
+ HMODULE hMod;
+ if (!PyArg_ParseTuple(args, "O|O:LoadLibrary", &nameobj, &ignored))
+ return NULL;
#ifdef _UNICODE
- name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
- if (!name) {
- PyErr_NoMemory();
- return NULL;
- }
-
- {
- int r;
- char *aname = PyString_AsString(nameobj);
- if(!aname)
- return NULL;
- r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyString_Size(nameobj) + 1);
- name[r] = 0;
- }
+ name = alloca((PyString_Size(nameobj) + 1) * sizeof(WCHAR));
+ if (!name) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ {
+ int r;
+ char *aname = PyString_AsString(nameobj);
+ if(!aname)
+ return NULL;
+ r = MultiByteToWideChar(CP_ACP, 0, aname, -1, name, PyString_Size(nameobj) + 1);
+ name[r] = 0;
+ }
#else
- name = PyString_AsString(nameobj);
- if(!name)
- return NULL;
+ name = PyString_AsString(nameobj);
+ if(!name)
+ return NULL;
#endif
- hMod = LoadLibrary(name);
- if (!hMod)
- return PyErr_SetFromWindowsErr(GetLastError());
+ hMod = LoadLibrary(name);
+ if (!hMod)
+ return PyErr_SetFromWindowsErr(GetLastError());
#ifdef _WIN64
- return PyLong_FromVoidPtr(hMod);
+ return PyLong_FromVoidPtr(hMod);
#else
- return Py_BuildValue("i", hMod);
+ return Py_BuildValue("i", hMod);
#endif
}
@@ -1275,13 +1275,13 @@ static char free_library_doc[] =
Free the handle of an executable previously loaded by LoadLibrary.\n";
static PyObject *free_library(PyObject *self, PyObject *args)
{
- void *hMod;
- if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
- return NULL;
- if (!FreeLibrary((HMODULE)hMod))
- return PyErr_SetFromWindowsErr(GetLastError());
- Py_INCREF(Py_None);
- return Py_None;
+ void *hMod;
+ if (!PyArg_ParseTuple(args, "O&:FreeLibrary", &_parse_voidp, &hMod))
+ return NULL;
+ if (!FreeLibrary((HMODULE)hMod))
+ return PyErr_SetFromWindowsErr(GetLastError());
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* obsolete, should be removed */
@@ -1289,55 +1289,55 @@ static PyObject *free_library(PyObject *self, PyObject *args)
static PyObject *
call_commethod(PyObject *self, PyObject *args)
{
- IUnknown *pIunk;
- int index;
- PyObject *arguments;
- PPROC *lpVtbl;
- PyObject *result;
- CDataObject *pcom;
- PyObject *argtypes = NULL;
-
- if (!PyArg_ParseTuple(args,
- "OiO!|O!",
- &pcom, &index,
- &PyTuple_Type, &arguments,
- &PyTuple_Type, &argtypes))
- return NULL;
-
- if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
- PyErr_Format(PyExc_TypeError,
- "Method takes %d arguments (%d given)",
- PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
- return NULL;
- }
-
- if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
- PyErr_Format(PyExc_TypeError,
- "COM Pointer expected instead of %s instance",
- Py_TYPE(pcom)->tp_name);
- return NULL;
- }
-
- if ((*(void **)(pcom->b_ptr)) == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "The COM 'this' pointer is NULL");
- return NULL;
- }
-
- pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
- lpVtbl = (PPROC *)(pIunk->lpVtbl);
-
- result = _ctypes_callproc(lpVtbl[index],
- arguments,
+ IUnknown *pIunk;
+ int index;
+ PyObject *arguments;
+ PPROC *lpVtbl;
+ PyObject *result;
+ CDataObject *pcom;
+ PyObject *argtypes = NULL;
+
+ if (!PyArg_ParseTuple(args,
+ "OiO!|O!",
+ &pcom, &index,
+ &PyTuple_Type, &arguments,
+ &PyTuple_Type, &argtypes))
+ return NULL;
+
+ if (argtypes && (PyTuple_GET_SIZE(arguments) != PyTuple_GET_SIZE(argtypes))) {
+ PyErr_Format(PyExc_TypeError,
+ "Method takes %d arguments (%d given)",
+ PyTuple_GET_SIZE(argtypes), PyTuple_GET_SIZE(arguments));
+ return NULL;
+ }
+
+ if (!CDataObject_Check(pcom) || (pcom->b_size != sizeof(void *))) {
+ PyErr_Format(PyExc_TypeError,
+ "COM Pointer expected instead of %s instance",
+ Py_TYPE(pcom)->tp_name);
+ return NULL;
+ }
+
+ if ((*(void **)(pcom->b_ptr)) == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "The COM 'this' pointer is NULL");
+ return NULL;
+ }
+
+ pIunk = (IUnknown *)(*(void **)(pcom->b_ptr));
+ lpVtbl = (PPROC *)(pIunk->lpVtbl);
+
+ result = _ctypes_callproc(lpVtbl[index],
+ arguments,
#ifdef MS_WIN32
- pIunk,
- NULL,
+ pIunk,
+ NULL,
#endif
- FUNCFLAG_HRESULT, /* flags */
- argtypes, /* self->argtypes */
- NULL, /* self->restype */
- NULL); /* checker */
- return result;
+ FUNCFLAG_HRESULT, /* flags */
+ argtypes, /* self->argtypes */
+ NULL, /* self->restype */
+ NULL); /* checker */
+ return result;
}
static char copy_com_pointer_doc[] =
@@ -1346,89 +1346,89 @@ static char copy_com_pointer_doc[] =
static PyObject *
copy_com_pointer(PyObject *self, PyObject *args)
{
- PyObject *p1, *p2, *r = NULL;
- struct argument a, b;
- IUnknown *src, **pdst;
- if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
- return NULL;
- a.keep = b.keep = NULL;
-
- if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
- goto done;
- src = (IUnknown *)a.value.p;
- pdst = (IUnknown **)b.value.p;
-
- if (pdst == NULL)
- r = PyInt_FromLong(E_POINTER);
- else {
- if (src)
- src->lpVtbl->AddRef(src);
- *pdst = src;
- r = PyInt_FromLong(S_OK);
- }
+ PyObject *p1, *p2, *r = NULL;
+ struct argument a, b;
+ IUnknown *src, **pdst;
+ if (!PyArg_ParseTuple(args, "OO:CopyComPointer", &p1, &p2))
+ return NULL;
+ a.keep = b.keep = NULL;
+
+ if (-1 == ConvParam(p1, 0, &a) || -1 == ConvParam(p2, 1, &b))
+ goto done;
+ src = (IUnknown *)a.value.p;
+ pdst = (IUnknown **)b.value.p;
+
+ if (pdst == NULL)
+ r = PyInt_FromLong(E_POINTER);
+ else {
+ if (src)
+ src->lpVtbl->AddRef(src);
+ *pdst = src;
+ r = PyInt_FromLong(S_OK);
+ }
done:
- Py_XDECREF(a.keep);
- Py_XDECREF(b.keep);
- return r;
+ Py_XDECREF(a.keep);
+ Py_XDECREF(b.keep);
+ return r;
}
#else
static PyObject *py_dl_open(PyObject *self, PyObject *args)
{
- char *name;
- void * handle;
-#ifdef RTLD_LOCAL
- int mode = RTLD_NOW | RTLD_LOCAL;
+ char *name;
+ void * handle;
+#ifdef RTLD_LOCAL
+ int mode = RTLD_NOW | RTLD_LOCAL;
#else
- /* cygwin doesn't define RTLD_LOCAL */
- int mode = RTLD_NOW;
+ /* cygwin doesn't define RTLD_LOCAL */
+ int mode = RTLD_NOW;
#endif
- if (!PyArg_ParseTuple(args, "z|i:dlopen", &name, &mode))
- return NULL;
- mode |= RTLD_NOW;
- handle = ctypes_dlopen(name, mode);
- if (!handle) {
- char *errmsg = ctypes_dlerror();
- if (!errmsg)
- errmsg = "dlopen() error";
- PyErr_SetString(PyExc_OSError,
- errmsg);
- return NULL;
- }
- return PyLong_FromVoidPtr(handle);
+ if (!PyArg_ParseTuple(args, "z|i:dlopen", &name, &mode))
+ return NULL;
+ mode |= RTLD_NOW;
+ handle = ctypes_dlopen(name, mode);
+ if (!handle) {
+ char *errmsg = ctypes_dlerror();
+ if (!errmsg)
+ errmsg = "dlopen() error";
+ PyErr_SetString(PyExc_OSError,
+ errmsg);
+ return NULL;
+ }
+ return PyLong_FromVoidPtr(handle);
}
static PyObject *py_dl_close(PyObject *self, PyObject *args)
{
- void *handle;
-
- if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
- return NULL;
- if (dlclose(handle)) {
- PyErr_SetString(PyExc_OSError,
- ctypes_dlerror());
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ void *handle;
+
+ if (!PyArg_ParseTuple(args, "O&:dlclose", &_parse_voidp, &handle))
+ return NULL;
+ if (dlclose(handle)) {
+ PyErr_SetString(PyExc_OSError,
+ ctypes_dlerror());
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *py_dl_sym(PyObject *self, PyObject *args)
{
- char *name;
- void *handle;
- void *ptr;
-
- if (!PyArg_ParseTuple(args, "O&s:dlsym",
- &_parse_voidp, &handle, &name))
- return NULL;
- ptr = ctypes_dlsym((void*)handle, name);
- if (!ptr) {
- PyErr_SetString(PyExc_OSError,
- ctypes_dlerror());
- return NULL;
- }
- return PyLong_FromVoidPtr(ptr);
+ char *name;
+ void *handle;
+ void *ptr;
+
+ if (!PyArg_ParseTuple(args, "O&s:dlsym",
+ &_parse_voidp, &handle, &name))
+ return NULL;
+ ptr = ctypes_dlsym((void*)handle, name);
+ if (!ptr) {
+ PyErr_SetString(PyExc_OSError,
+ ctypes_dlerror());
+ return NULL;
+ }
+ return PyLong_FromVoidPtr(ptr);
}
#endif
@@ -1440,27 +1440,27 @@ static PyObject *py_dl_sym(PyObject *self, PyObject *args)
static PyObject *
call_function(PyObject *self, PyObject *args)
{
- void *func;
- PyObject *arguments;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args,
- "O&O!",
- &_parse_voidp, &func,
- &PyTuple_Type, &arguments))
- return NULL;
-
- result = _ctypes_callproc((PPROC)func,
- arguments,
+ void *func;
+ PyObject *arguments;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args,
+ "O&O!",
+ &_parse_voidp, &func,
+ &PyTuple_Type, &arguments))
+ return NULL;
+
+ result = _ctypes_callproc((PPROC)func,
+ arguments,
#ifdef MS_WIN32
- NULL,
- NULL,
+ NULL,
+ NULL,
#endif
- 0, /* flags */
- NULL, /* self->argtypes */
- NULL, /* self->restype */
- NULL); /* checker */
- return result;
+ 0, /* flags */
+ NULL, /* self->argtypes */
+ NULL, /* self->restype */
+ NULL); /* checker */
+ return result;
}
/*
@@ -1471,27 +1471,27 @@ call_function(PyObject *self, PyObject *args)
static PyObject *
call_cdeclfunction(PyObject *self, PyObject *args)
{
- void *func;
- PyObject *arguments;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args,
- "O&O!",
- &_parse_voidp, &func,
- &PyTuple_Type, &arguments))
- return NULL;
-
- result = _ctypes_callproc((PPROC)func,
- arguments,
+ void *func;
+ PyObject *arguments;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args,
+ "O&O!",
+ &_parse_voidp, &func,
+ &PyTuple_Type, &arguments))
+ return NULL;
+
+ result = _ctypes_callproc((PPROC)func,
+ arguments,
#ifdef MS_WIN32
- NULL,
- NULL,
+ NULL,
+ NULL,
#endif
- FUNCFLAG_CDECL, /* flags */
- NULL, /* self->argtypes */
- NULL, /* self->restype */
- NULL); /* checker */
- return result;
+ FUNCFLAG_CDECL, /* flags */
+ NULL, /* self->argtypes */
+ NULL, /* self->restype */
+ NULL); /* checker */
+ return result;
}
/*****************************************************************
@@ -1505,17 +1505,17 @@ static char sizeof_doc[] =
static PyObject *
sizeof_func(PyObject *self, PyObject *obj)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict(obj);
- if (dict)
- return PyInt_FromSsize_t(dict->size);
+ dict = PyType_stgdict(obj);
+ if (dict)
+ return PyInt_FromSsize_t(dict->size);
- if (CDataObject_Check(obj))
- return PyInt_FromSsize_t(((CDataObject *)obj)->b_size);
- PyErr_SetString(PyExc_TypeError,
- "this type has no size");
- return NULL;
+ if (CDataObject_Check(obj))
+ return PyInt_FromSsize_t(((CDataObject *)obj)->b_size);
+ PyErr_SetString(PyExc_TypeError,
+ "this type has no size");
+ return NULL;
}
static char alignment_doc[] =
@@ -1526,19 +1526,19 @@ static char alignment_doc[] =
static PyObject *
align_func(PyObject *self, PyObject *obj)
{
- StgDictObject *dict;
+ StgDictObject *dict;
- dict = PyType_stgdict(obj);
- if (dict)
- return PyInt_FromSsize_t(dict->align);
+ dict = PyType_stgdict(obj);
+ if (dict)
+ return PyInt_FromSsize_t(dict->align);
- dict = PyObject_stgdict(obj);
- if (dict)
- return PyInt_FromSsize_t(dict->align);
+ dict = PyObject_stgdict(obj);
+ if (dict)
+ return PyInt_FromSsize_t(dict->align);
- PyErr_SetString(PyExc_TypeError,
- "no alignment info");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "no alignment info");
+ return NULL;
}
static char byref_doc[] =
@@ -1553,36 +1553,36 @@ static char byref_doc[] =
static PyObject *
byref(PyObject *self, PyObject *args)
{
- PyCArgObject *parg;
- PyObject *obj;
- PyObject *pyoffset = NULL;
- Py_ssize_t offset = 0;
-
- if (!PyArg_UnpackTuple(args, "byref", 1, 2,
- &obj, &pyoffset))
- return NULL;
- if (pyoffset) {
- offset = PyNumber_AsSsize_t(pyoffset, NULL);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
- }
- if (!CDataObject_Check(obj)) {
- PyErr_Format(PyExc_TypeError,
- "byref() argument must be a ctypes instance, not '%s'",
- Py_TYPE(obj)->tp_name);
- return NULL;
- }
-
- parg = PyCArgObject_new();
- if (parg == NULL)
- return NULL;
-
- parg->tag = 'P';
- parg->pffi_type = &ffi_type_pointer;
- Py_INCREF(obj);
- parg->obj = obj;
- parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
- return (PyObject *)parg;
+ PyCArgObject *parg;
+ PyObject *obj;
+ PyObject *pyoffset = NULL;
+ Py_ssize_t offset = 0;
+
+ if (!PyArg_UnpackTuple(args, "byref", 1, 2,
+ &obj, &pyoffset))
+ return NULL;
+ if (pyoffset) {
+ offset = PyNumber_AsSsize_t(pyoffset, NULL);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ if (!CDataObject_Check(obj)) {
+ PyErr_Format(PyExc_TypeError,
+ "byref() argument must be a ctypes instance, not '%s'",
+ Py_TYPE(obj)->tp_name);
+ return NULL;
+ }
+
+ parg = PyCArgObject_new();
+ if (parg == NULL)
+ return NULL;
+
+ parg->tag = 'P';
+ parg->pffi_type = &ffi_type_pointer;
+ Py_INCREF(obj);
+ parg->obj = obj;
+ parg->value.p = (char *)((CDataObject *)obj)->b_ptr + offset;
+ return (PyObject *)parg;
}
static char addressof_doc[] =
@@ -1592,44 +1592,44 @@ static char addressof_doc[] =
static PyObject *
addressof(PyObject *self, PyObject *obj)
{
- if (CDataObject_Check(obj))
- return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
- PyErr_SetString(PyExc_TypeError,
- "invalid type");
- return NULL;
+ if (CDataObject_Check(obj))
+ return PyLong_FromVoidPtr(((CDataObject *)obj)->b_ptr);
+ PyErr_SetString(PyExc_TypeError,
+ "invalid type");
+ return NULL;
}
static int
converter(PyObject *obj, void **address)
{
- *address = PyLong_AsVoidPtr(obj);
- return *address != NULL;
+ *address = PyLong_AsVoidPtr(obj);
+ return *address != NULL;
}
static PyObject *
My_PyObj_FromPtr(PyObject *self, PyObject *args)
{
- PyObject *ob;
- if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
- return NULL;
- Py_INCREF(ob);
- return ob;
+ PyObject *ob;
+ if (!PyArg_ParseTuple(args, "O&:PyObj_FromPtr", converter, &ob))
+ return NULL;
+ Py_INCREF(ob);
+ return ob;
}
static PyObject *
My_Py_INCREF(PyObject *self, PyObject *arg)
{
- Py_INCREF(arg); /* that's what this function is for */
- Py_INCREF(arg); /* that for returning it */
- return arg;
+ Py_INCREF(arg); /* that's what this function is for */
+ Py_INCREF(arg); /* that for returning it */
+ return arg;
}
static PyObject *
My_Py_DECREF(PyObject *self, PyObject *arg)
{
- Py_DECREF(arg); /* that's what this function is for */
- Py_INCREF(arg); /* that's for returning it */
- return arg;
+ Py_DECREF(arg); /* that's what this function is for */
+ Py_INCREF(arg); /* that's for returning it */
+ return arg;
}
#ifdef CTYPES_UNICODE
@@ -1643,242 +1643,242 @@ between unicode and strings. Returns the previous values.\n";
static PyObject *
set_conversion_mode(PyObject *self, PyObject *args)
{
- char *coding, *mode;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
- return NULL;
- result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
- if (coding) {
- PyMem_Free(_ctypes_conversion_encoding);
- _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
- strcpy(_ctypes_conversion_encoding, coding);
- } else {
- _ctypes_conversion_encoding = NULL;
- }
- PyMem_Free(_ctypes_conversion_errors);
- _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
- strcpy(_ctypes_conversion_errors, mode);
- return result;
+ char *coding, *mode;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "zs:set_conversion_mode", &coding, &mode))
+ return NULL;
+ result = Py_BuildValue("(zz)", _ctypes_conversion_encoding, _ctypes_conversion_errors);
+ if (coding) {
+ PyMem_Free(_ctypes_conversion_encoding);
+ _ctypes_conversion_encoding = PyMem_Malloc(strlen(coding) + 1);
+ strcpy(_ctypes_conversion_encoding, coding);
+ } else {
+ _ctypes_conversion_encoding = NULL;
+ }
+ PyMem_Free(_ctypes_conversion_errors);
+ _ctypes_conversion_errors = PyMem_Malloc(strlen(mode) + 1);
+ strcpy(_ctypes_conversion_errors, mode);
+ return result;
}
#endif
static PyObject *
resize(PyObject *self, PyObject *args)
{
- CDataObject *obj;
- StgDictObject *dict;
- Py_ssize_t size;
+ CDataObject *obj;
+ StgDictObject *dict;
+ Py_ssize_t size;
- if (!PyArg_ParseTuple(args,
+ if (!PyArg_ParseTuple(args,
#if (PY_VERSION_HEX < 0x02050000)
- "Oi:resize",
+ "Oi:resize",
#else
- "On:resize",
+ "On:resize",
#endif
- &obj, &size))
- return NULL;
-
- dict = PyObject_stgdict((PyObject *)obj);
- if (dict == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "excepted ctypes instance");
- return NULL;
- }
- if (size < dict->size) {
- PyErr_Format(PyExc_ValueError,
+ &obj, &size))
+ return NULL;
+
+ dict = PyObject_stgdict((PyObject *)obj);
+ if (dict == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "excepted ctypes instance");
+ return NULL;
+ }
+ if (size < dict->size) {
+ PyErr_Format(PyExc_ValueError,
#if PY_VERSION_HEX < 0x02050000
- "minimum size is %d",
+ "minimum size is %d",
#else
- "minimum size is %zd",
+ "minimum size is %zd",
#endif
- dict->size);
- return NULL;
- }
- if (obj->b_needsfree == 0) {
- PyErr_Format(PyExc_ValueError,
- "Memory cannot be resized because this object doesn't own it");
- return NULL;
- }
- if (size <= sizeof(obj->b_value)) {
- /* internal default buffer is large enough */
- obj->b_size = size;
- goto done;
- }
- if (obj->b_size <= sizeof(obj->b_value)) {
- /* We are currently using the objects default buffer, but it
- isn't large enough any more. */
- void *ptr = PyMem_Malloc(size);
- if (ptr == NULL)
- return PyErr_NoMemory();
- memset(ptr, 0, size);
- memmove(ptr, obj->b_ptr, obj->b_size);
- obj->b_ptr = ptr;
- obj->b_size = size;
- } else {
- void * ptr = PyMem_Realloc(obj->b_ptr, size);
- if (ptr == NULL)
- return PyErr_NoMemory();
- obj->b_ptr = ptr;
- obj->b_size = size;
- }
+ dict->size);
+ return NULL;
+ }
+ if (obj->b_needsfree == 0) {
+ PyErr_Format(PyExc_ValueError,
+ "Memory cannot be resized because this object doesn't own it");
+ return NULL;
+ }
+ if (size <= sizeof(obj->b_value)) {
+ /* internal default buffer is large enough */
+ obj->b_size = size;
+ goto done;
+ }
+ if (obj->b_size <= sizeof(obj->b_value)) {
+ /* We are currently using the objects default buffer, but it
+ isn't large enough any more. */
+ void *ptr = PyMem_Malloc(size);
+ if (ptr == NULL)
+ return PyErr_NoMemory();
+ memset(ptr, 0, size);
+ memmove(ptr, obj->b_ptr, obj->b_size);
+ obj->b_ptr = ptr;
+ obj->b_size = size;
+ } else {
+ void * ptr = PyMem_Realloc(obj->b_ptr, size);
+ if (ptr == NULL)
+ return PyErr_NoMemory();
+ obj->b_ptr = ptr;
+ obj->b_size = size;
+ }
done:
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
unpickle(PyObject *self, PyObject *args)
{
- PyObject *typ;
- PyObject *state;
- PyObject *result;
- PyObject *tmp;
-
- if (!PyArg_ParseTuple(args, "OO", &typ, &state))
- return NULL;
- result = PyObject_CallMethod(typ, "__new__", "O", typ);
- if (result == NULL)
- return NULL;
- tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
- if (tmp == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(tmp);
- return result;
+ PyObject *typ;
+ PyObject *state;
+ PyObject *result;
+ PyObject *tmp;
+
+ if (!PyArg_ParseTuple(args, "OO", &typ, &state))
+ return NULL;
+ result = PyObject_CallMethod(typ, "__new__", "O", typ);
+ if (result == NULL)
+ return NULL;
+ tmp = PyObject_CallMethod(result, "__setstate__", "O", state);
+ if (tmp == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(tmp);
+ return result;
}
static PyObject *
POINTER(PyObject *self, PyObject *cls)
{
- PyObject *result;
- PyTypeObject *typ;
- PyObject *key;
- char *buf;
-
- result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
- if (result) {
- Py_INCREF(result);
- return result;
- }
- if (PyString_CheckExact(cls)) {
- buf = alloca(strlen(PyString_AS_STRING(cls)) + 3 + 1);
- sprintf(buf, "LP_%s", PyString_AS_STRING(cls));
- result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
- "s(O){}",
- buf,
- &PyCPointer_Type);
- if (result == NULL)
- return result;
- key = PyLong_FromVoidPtr(result);
- } else if (PyType_Check(cls)) {
- typ = (PyTypeObject *)cls;
- buf = alloca(strlen(typ->tp_name) + 3 + 1);
- sprintf(buf, "LP_%s", typ->tp_name);
- result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
- "s(O){sO}",
- buf,
- &PyCPointer_Type,
- "_type_", cls);
- if (result == NULL)
- return result;
- Py_INCREF(cls);
- key = cls;
- } else {
- PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
- return NULL;
- }
- if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
- Py_DECREF(result);
- Py_DECREF(key);
- return NULL;
- }
- Py_DECREF(key);
- return result;
+ PyObject *result;
+ PyTypeObject *typ;
+ PyObject *key;
+ char *buf;
+
+ result = PyDict_GetItem(_ctypes_ptrtype_cache, cls);
+ if (result) {
+ Py_INCREF(result);
+ return result;
+ }
+ if (PyString_CheckExact(cls)) {
+ buf = alloca(strlen(PyString_AS_STRING(cls)) + 3 + 1);
+ sprintf(buf, "LP_%s", PyString_AS_STRING(cls));
+ result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
+ "s(O){}",
+ buf,
+ &PyCPointer_Type);
+ if (result == NULL)
+ return result;
+ key = PyLong_FromVoidPtr(result);
+ } else if (PyType_Check(cls)) {
+ typ = (PyTypeObject *)cls;
+ buf = alloca(strlen(typ->tp_name) + 3 + 1);
+ sprintf(buf, "LP_%s", typ->tp_name);
+ result = PyObject_CallFunction((PyObject *)Py_TYPE(&PyCPointer_Type),
+ "s(O){sO}",
+ buf,
+ &PyCPointer_Type,
+ "_type_", cls);
+ if (result == NULL)
+ return result;
+ Py_INCREF(cls);
+ key = cls;
+ } else {
+ PyErr_SetString(PyExc_TypeError, "must be a ctypes type");
+ return NULL;
+ }
+ if (-1 == PyDict_SetItem(_ctypes_ptrtype_cache, key, result)) {
+ Py_DECREF(result);
+ Py_DECREF(key);
+ return NULL;
+ }
+ Py_DECREF(key);
+ return result;
}
static PyObject *
pointer(PyObject *self, PyObject *arg)
{
- PyObject *result;
- PyObject *typ;
-
- typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
- if (typ)
- return PyObject_CallFunctionObjArgs(typ, arg, NULL);
- typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
- if (typ == NULL)
- return NULL;
- result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
- Py_DECREF(typ);
- return result;
+ PyObject *result;
+ PyObject *typ;
+
+ typ = PyDict_GetItem(_ctypes_ptrtype_cache, (PyObject *)Py_TYPE(arg));
+ if (typ)
+ return PyObject_CallFunctionObjArgs(typ, arg, NULL);
+ typ = POINTER(NULL, (PyObject *)Py_TYPE(arg));
+ if (typ == NULL)
+ return NULL;
+ result = PyObject_CallFunctionObjArgs(typ, arg, NULL);
+ Py_DECREF(typ);
+ return result;
}
static PyObject *
buffer_info(PyObject *self, PyObject *arg)
{
- StgDictObject *dict = PyType_stgdict(arg);
- PyObject *shape;
- Py_ssize_t i;
-
- if (dict == NULL)
- dict = PyObject_stgdict(arg);
- if (dict == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "not a ctypes type or object");
- return NULL;
- }
- shape = PyTuple_New(dict->ndim);
- if (shape == NULL)
- return NULL;
- for (i = 0; i < (int)dict->ndim; ++i)
- PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
-
- if (PyErr_Occurred()) {
- Py_DECREF(shape);
- return NULL;
- }
- return Py_BuildValue("siN", dict->format, dict->ndim, shape);
+ StgDictObject *dict = PyType_stgdict(arg);
+ PyObject *shape;
+ Py_ssize_t i;
+
+ if (dict == NULL)
+ dict = PyObject_stgdict(arg);
+ if (dict == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "not a ctypes type or object");
+ return NULL;
+ }
+ shape = PyTuple_New(dict->ndim);
+ if (shape == NULL)
+ return NULL;
+ for (i = 0; i < (int)dict->ndim; ++i)
+ PyTuple_SET_ITEM(shape, i, PyLong_FromSsize_t(dict->shape[i]));
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(shape);
+ return NULL;
+ }
+ return Py_BuildValue("siN", dict->format, dict->ndim, shape);
}
PyMethodDef _ctypes_module_methods[] = {
- {"get_errno", get_errno, METH_NOARGS},
- {"set_errno", set_errno, METH_VARARGS},
- {"POINTER", POINTER, METH_O },
- {"pointer", pointer, METH_O },
- {"_unpickle", unpickle, METH_VARARGS },
- {"_buffer_info", buffer_info, METH_O,
- "Return buffer interface information (for testing only)"},
- {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
+ {"get_errno", get_errno, METH_NOARGS},
+ {"set_errno", set_errno, METH_VARARGS},
+ {"POINTER", POINTER, METH_O },
+ {"pointer", pointer, METH_O },
+ {"_unpickle", unpickle, METH_VARARGS },
+ {"_buffer_info", buffer_info, METH_O,
+ "Return buffer interface information (for testing only)"},
+ {"resize", resize, METH_VARARGS, "Resize the memory buffer of a ctypes instance"},
#ifdef CTYPES_UNICODE
- {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
+ {"set_conversion_mode", set_conversion_mode, METH_VARARGS, set_conversion_mode_doc},
#endif
#ifdef MS_WIN32
- {"get_last_error", get_last_error, METH_NOARGS},
- {"set_last_error", set_last_error, METH_VARARGS},
- {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
- {"FormatError", format_error, METH_VARARGS, format_error_doc},
- {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
- {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
- {"call_commethod", call_commethod, METH_VARARGS },
- {"_check_HRESULT", check_hresult, METH_VARARGS},
+ {"get_last_error", get_last_error, METH_NOARGS},
+ {"set_last_error", set_last_error, METH_VARARGS},
+ {"CopyComPointer", copy_com_pointer, METH_VARARGS, copy_com_pointer_doc},
+ {"FormatError", format_error, METH_VARARGS, format_error_doc},
+ {"LoadLibrary", load_library, METH_VARARGS, load_library_doc},
+ {"FreeLibrary", free_library, METH_VARARGS, free_library_doc},
+ {"call_commethod", call_commethod, METH_VARARGS },
+ {"_check_HRESULT", check_hresult, METH_VARARGS},
#else
- {"dlopen", py_dl_open, METH_VARARGS,
- "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
- {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
- {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
+ {"dlopen", py_dl_open, METH_VARARGS,
+ "dlopen(name, flag={RTLD_GLOBAL|RTLD_LOCAL}) open a shared library"},
+ {"dlclose", py_dl_close, METH_VARARGS, "dlclose a library"},
+ {"dlsym", py_dl_sym, METH_VARARGS, "find symbol in shared library"},
#endif
- {"alignment", align_func, METH_O, alignment_doc},
- {"sizeof", sizeof_func, METH_O, sizeof_doc},
- {"byref", byref, METH_VARARGS, byref_doc},
- {"addressof", addressof, METH_O, addressof_doc},
- {"call_function", call_function, METH_VARARGS },
- {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
- {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
- {"Py_INCREF", My_Py_INCREF, METH_O },
- {"Py_DECREF", My_Py_DECREF, METH_O },
- {NULL, NULL} /* Sentinel */
+ {"alignment", align_func, METH_O, alignment_doc},
+ {"sizeof", sizeof_func, METH_O, sizeof_doc},
+ {"byref", byref, METH_VARARGS, byref_doc},
+ {"addressof", addressof, METH_O, addressof_doc},
+ {"call_function", call_function, METH_VARARGS },
+ {"call_cdeclfunction", call_cdeclfunction, METH_VARARGS },
+ {"PyObj_FromPtr", My_PyObj_FromPtr, METH_VARARGS },
+ {"Py_INCREF", My_Py_INCREF, METH_O },
+ {"Py_DECREF", My_Py_DECREF, METH_O },
+ {NULL, NULL} /* Sentinel */
};
/*
diff --git a/Modules/_ctypes/cfield.c b/Modules/_ctypes/cfield.c
index d7fc5d2..c7053ef 100644
--- a/Modules/_ctypes/cfield.c
+++ b/Modules/_ctypes/cfield.c
@@ -22,9 +22,9 @@ CTYPES_CAPSULE_INSTANTIATE_DESTRUCTOR(CTYPES_CAPSULE_WCHAR_T)
static PyObject *
PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- CFieldObject *obj;
- obj = (CFieldObject *)type->tp_alloc(type, 0);
- return (PyObject *)obj;
+ CFieldObject *obj;
+ obj = (CFieldObject *)type->tp_alloc(type, 0);
+ return (PyObject *)obj;
}
/*
@@ -41,305 +41,305 @@ PyCField_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
*/
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 big_endian)
-{
- CFieldObject *self;
- PyObject *proto;
- Py_ssize_t size, align, length;
- SETFUNC setfunc = NULL;
- GETFUNC getfunc = NULL;
- StgDictObject *dict;
- int fieldtype;
+ Py_ssize_t *pfield_size, int bitsize, int *pbitofs,
+ Py_ssize_t *psize, Py_ssize_t *poffset, Py_ssize_t *palign,
+ int pack, int big_endian)
+{
+ CFieldObject *self;
+ PyObject *proto;
+ Py_ssize_t size, align, length;
+ SETFUNC setfunc = NULL;
+ GETFUNC getfunc = NULL;
+ StgDictObject *dict;
+ int fieldtype;
#define NO_BITFIELD 0
#define NEW_BITFIELD 1
#define CONT_BITFIELD 2
#define EXPAND_BITFIELD 3
- self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type,
- NULL);
- if (self == NULL)
- return NULL;
- dict = PyType_stgdict(desc);
- if (!dict) {
- PyErr_SetString(PyExc_TypeError,
- "has no _stginfo_");
- Py_DECREF(self);
- return NULL;
- }
- if (bitsize /* this is a bitfield request */
- && *pfield_size /* we have a bitfield open */
+ self = (CFieldObject *)PyObject_CallObject((PyObject *)&PyCField_Type,
+ NULL);
+ if (self == NULL)
+ return NULL;
+ dict = PyType_stgdict(desc);
+ if (!dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "has no _stginfo_");
+ Py_DECREF(self);
+ return NULL;
+ }
+ if (bitsize /* this is a bitfield request */
+ && *pfield_size /* we have a bitfield open */
#ifdef MS_WIN32
- /* MSVC, GCC with -mms-bitfields */
- && dict->size * 8 == *pfield_size
+ /* MSVC, GCC with -mms-bitfields */
+ && dict->size * 8 == *pfield_size
#else
- /* GCC */
- && dict->size * 8 <= *pfield_size
+ /* GCC */
+ && dict->size * 8 <= *pfield_size
#endif
- && (*pbitofs + bitsize) <= *pfield_size) {
- /* continue bit field */
- fieldtype = CONT_BITFIELD;
+ && (*pbitofs + bitsize) <= *pfield_size) {
+ /* continue bit field */
+ fieldtype = CONT_BITFIELD;
#ifndef MS_WIN32
- } else if (bitsize /* this is a bitfield request */
- && *pfield_size /* we have a bitfield open */
- && dict->size * 8 >= *pfield_size
- && (*pbitofs + bitsize) <= dict->size * 8) {
- /* expand bit field */
- fieldtype = EXPAND_BITFIELD;
+ } else if (bitsize /* this is a bitfield request */
+ && *pfield_size /* we have a bitfield open */
+ && dict->size * 8 >= *pfield_size
+ && (*pbitofs + bitsize) <= dict->size * 8) {
+ /* expand bit field */
+ fieldtype = EXPAND_BITFIELD;
#endif
- } else if (bitsize) {
- /* start new bitfield */
- fieldtype = NEW_BITFIELD;
- *pbitofs = 0;
- *pfield_size = dict->size * 8;
- } else {
- /* not a bit field */
- fieldtype = NO_BITFIELD;
- *pbitofs = 0;
- *pfield_size = 0;
- }
-
- size = dict->size;
- length = dict->length;
- proto = desc;
-
- /* Field descriptors for 'c_char * n' are be scpecial cased to
- return a Python string instead of an Array object instance...
- */
- if (PyCArrayTypeObject_Check(proto)) {
- StgDictObject *adict = PyType_stgdict(proto);
- StgDictObject *idict;
- if (adict && adict->proto) {
- idict = PyType_stgdict(adict->proto);
- if (!idict) {
- PyErr_SetString(PyExc_TypeError,
- "has no _stginfo_");
- Py_DECREF(self);
- return NULL;
- }
- if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
- struct fielddesc *fd = _ctypes_get_fielddesc("s");
- getfunc = fd->getfunc;
- setfunc = fd->setfunc;
- }
+ } else if (bitsize) {
+ /* start new bitfield */
+ fieldtype = NEW_BITFIELD;
+ *pbitofs = 0;
+ *pfield_size = dict->size * 8;
+ } else {
+ /* not a bit field */
+ fieldtype = NO_BITFIELD;
+ *pbitofs = 0;
+ *pfield_size = 0;
+ }
+
+ size = dict->size;
+ length = dict->length;
+ proto = desc;
+
+ /* Field descriptors for 'c_char * n' are be scpecial cased to
+ return a Python string instead of an Array object instance...
+ */
+ if (PyCArrayTypeObject_Check(proto)) {
+ StgDictObject *adict = PyType_stgdict(proto);
+ StgDictObject *idict;
+ if (adict && adict->proto) {
+ idict = PyType_stgdict(adict->proto);
+ if (!idict) {
+ PyErr_SetString(PyExc_TypeError,
+ "has no _stginfo_");
+ Py_DECREF(self);
+ return NULL;
+ }
+ if (idict->getfunc == _ctypes_get_fielddesc("c")->getfunc) {
+ struct fielddesc *fd = _ctypes_get_fielddesc("s");
+ getfunc = fd->getfunc;
+ setfunc = fd->setfunc;
+ }
#ifdef CTYPES_UNICODE
- if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
- struct fielddesc *fd = _ctypes_get_fielddesc("U");
- getfunc = fd->getfunc;
- setfunc = fd->setfunc;
- }
+ if (idict->getfunc == _ctypes_get_fielddesc("u")->getfunc) {
+ struct fielddesc *fd = _ctypes_get_fielddesc("U");
+ getfunc = fd->getfunc;
+ setfunc = fd->setfunc;
+ }
#endif
- }
- }
-
- self->setfunc = setfunc;
- self->getfunc = getfunc;
- self->index = index;
-
- Py_INCREF(proto);
- self->proto = proto;
-
- switch (fieldtype) {
- case NEW_BITFIELD:
- if (big_endian)
- self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
- else
- self->size = (bitsize << 16) + *pbitofs;
- *pbitofs = bitsize;
- /* fall through */
- case NO_BITFIELD:
- if (pack)
- align = min(pack, dict->align);
- else
- align = dict->align;
- if (align && *poffset % align) {
- Py_ssize_t delta = align - (*poffset % align);
- *psize += delta;
- *poffset += delta;
- }
-
- if (bitsize == 0)
- self->size = size;
- *psize += size;
-
- self->offset = *poffset;
- *poffset += size;
-
- *palign = align;
- break;
-
- case EXPAND_BITFIELD:
- *poffset += dict->size - *pfield_size/8;
- *psize += dict->size - *pfield_size/8;
-
- *pfield_size = dict->size * 8;
-
- if (big_endian)
- self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
- else
- self->size = (bitsize << 16) + *pbitofs;
-
- self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
- *pbitofs += bitsize;
- break;
-
- case CONT_BITFIELD:
- if (big_endian)
- self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
- else
- self->size = (bitsize << 16) + *pbitofs;
-
- self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
- *pbitofs += bitsize;
- break;
- }
-
- return (PyObject *)self;
+ }
+ }
+
+ self->setfunc = setfunc;
+ self->getfunc = getfunc;
+ self->index = index;
+
+ Py_INCREF(proto);
+ self->proto = proto;
+
+ switch (fieldtype) {
+ case NEW_BITFIELD:
+ if (big_endian)
+ self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
+ else
+ self->size = (bitsize << 16) + *pbitofs;
+ *pbitofs = bitsize;
+ /* fall through */
+ case NO_BITFIELD:
+ if (pack)
+ align = min(pack, dict->align);
+ else
+ align = dict->align;
+ if (align && *poffset % align) {
+ Py_ssize_t delta = align - (*poffset % align);
+ *psize += delta;
+ *poffset += delta;
+ }
+
+ if (bitsize == 0)
+ self->size = size;
+ *psize += size;
+
+ self->offset = *poffset;
+ *poffset += size;
+
+ *palign = align;
+ break;
+
+ case EXPAND_BITFIELD:
+ *poffset += dict->size - *pfield_size/8;
+ *psize += dict->size - *pfield_size/8;
+
+ *pfield_size = dict->size * 8;
+
+ if (big_endian)
+ self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
+ else
+ self->size = (bitsize << 16) + *pbitofs;
+
+ self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
+ *pbitofs += bitsize;
+ break;
+
+ case CONT_BITFIELD:
+ if (big_endian)
+ self->size = (bitsize << 16) + *pfield_size - *pbitofs - bitsize;
+ else
+ self->size = (bitsize << 16) + *pbitofs;
+
+ self->offset = *poffset - size; /* poffset is already updated for the NEXT field */
+ *pbitofs += bitsize;
+ break;
+ }
+
+ return (PyObject *)self;
}
static int
PyCField_set(CFieldObject *self, PyObject *inst, PyObject *value)
{
- CDataObject *dst;
- char *ptr;
- assert(CDataObject_Check(inst));
- dst = (CDataObject *)inst;
- ptr = dst->b_ptr + self->offset;
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete attribute");
- return -1;
- }
- return PyCData_set(inst, self->proto, self->setfunc, value,
- self->index, self->size, ptr);
+ CDataObject *dst;
+ char *ptr;
+ assert(CDataObject_Check(inst));
+ dst = (CDataObject *)inst;
+ ptr = dst->b_ptr + self->offset;
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete attribute");
+ return -1;
+ }
+ return PyCData_set(inst, self->proto, self->setfunc, value,
+ self->index, self->size, ptr);
}
static PyObject *
PyCField_get(CFieldObject *self, PyObject *inst, PyTypeObject *type)
{
- CDataObject *src;
- if (inst == NULL) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- assert(CDataObject_Check(inst));
- src = (CDataObject *)inst;
- return PyCData_get(self->proto, self->getfunc, inst,
- self->index, self->size, src->b_ptr + self->offset);
+ CDataObject *src;
+ if (inst == NULL) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ assert(CDataObject_Check(inst));
+ src = (CDataObject *)inst;
+ return PyCData_get(self->proto, self->getfunc, inst,
+ self->index, self->size, src->b_ptr + self->offset);
}
static PyObject *
PyCField_get_offset(PyObject *self, void *data)
{
- return PyInt_FromSsize_t(((CFieldObject *)self)->offset);
+ return PyInt_FromSsize_t(((CFieldObject *)self)->offset);
}
static PyObject *
PyCField_get_size(PyObject *self, void *data)
{
- return PyInt_FromSsize_t(((CFieldObject *)self)->size);
+ return PyInt_FromSsize_t(((CFieldObject *)self)->size);
}
static PyGetSetDef PyCField_getset[] = {
- { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" },
- { "size", PyCField_get_size, NULL, "size in bytes of this field" },
- { NULL, NULL, NULL, NULL },
+ { "offset", PyCField_get_offset, NULL, "offset in bytes of this field" },
+ { "size", PyCField_get_size, NULL, "size in bytes of this field" },
+ { NULL, NULL, NULL, NULL },
};
static int
PyCField_traverse(CFieldObject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->proto);
- return 0;
+ Py_VISIT(self->proto);
+ return 0;
}
static int
PyCField_clear(CFieldObject *self)
{
- Py_CLEAR(self->proto);
- return 0;
+ Py_CLEAR(self->proto);
+ return 0;
}
static void
PyCField_dealloc(PyObject *self)
{
- PyCField_clear((CFieldObject *)self);
- self->ob_type->tp_free((PyObject *)self);
+ PyCField_clear((CFieldObject *)self);
+ self->ob_type->tp_free((PyObject *)self);
}
static PyObject *
PyCField_repr(CFieldObject *self)
{
- PyObject *result;
- Py_ssize_t bits = self->size >> 16;
- Py_ssize_t size = self->size & 0xFFFF;
- const char *name;
+ PyObject *result;
+ Py_ssize_t bits = self->size >> 16;
+ Py_ssize_t size = self->size & 0xFFFF;
+ const char *name;
- name = ((PyTypeObject *)self->proto)->tp_name;
+ name = ((PyTypeObject *)self->proto)->tp_name;
- if (bits)
- result = PyString_FromFormat(
+ if (bits)
+ result = PyString_FromFormat(
#if (PY_VERSION_HEX < 0x02050000)
- "<Field type=%s, ofs=%d:%d, bits=%d>",
+ "<Field type=%s, ofs=%d:%d, bits=%d>",
#else
- "<Field type=%s, ofs=%zd:%zd, bits=%zd>",
+ "<Field type=%s, ofs=%zd:%zd, bits=%zd>",
#endif
- name, self->offset, size, bits);
- else
- result = PyString_FromFormat(
+ name, self->offset, size, bits);
+ else
+ result = PyString_FromFormat(
#if (PY_VERSION_HEX < 0x02050000)
- "<Field type=%s, ofs=%d, size=%d>",
+ "<Field type=%s, ofs=%d, size=%d>",
#else
- "<Field type=%s, ofs=%zd, size=%zd>",
+ "<Field type=%s, ofs=%zd, size=%zd>",
#endif
- name, self->offset, size);
- return result;
+ name, self->offset, size);
+ return result;
}
PyTypeObject PyCField_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_ctypes.CField", /* tp_name */
- sizeof(CFieldObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- PyCField_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)PyCField_repr, /* 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_HAVE_GC, /* tp_flags */
- "Structure/Union member", /* tp_doc */
- (traverseproc)PyCField_traverse, /* tp_traverse */
- (inquiry)PyCField_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- PyCField_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)PyCField_get, /* tp_descr_get */
- (descrsetfunc)PyCField_set, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyCField_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_ctypes.CField", /* tp_name */
+ sizeof(CFieldObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ PyCField_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)PyCField_repr, /* 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_HAVE_GC, /* tp_flags */
+ "Structure/Union member", /* tp_doc */
+ (traverseproc)PyCField_traverse, /* tp_traverse */
+ (inquiry)PyCField_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ PyCField_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)PyCField_get, /* tp_descr_get */
+ (descrsetfunc)PyCField_set, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyCField_new, /* tp_new */
+ 0, /* tp_free */
};
-
+
/******************************************************************/
/*
Accessor functions
@@ -352,17 +352,17 @@ PyTypeObject PyCField_Type = {
static int
get_long(PyObject *v, long *p)
{
- long x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyInt_AsUnsignedLongMask(v);
- if (x == -1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ long x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyInt_AsUnsignedLongMask(v);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling unsigned long */
@@ -370,17 +370,17 @@ get_long(PyObject *v, long *p)
static int
get_ulong(PyObject *v, unsigned long *p)
{
- unsigned long x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyInt_AsUnsignedLongMask(v);
- if (x == (unsigned long)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ unsigned long x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyInt_AsUnsignedLongMask(v);
+ if (x == (unsigned long)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -390,17 +390,17 @@ get_ulong(PyObject *v, unsigned long *p)
static int
get_longlong(PyObject *v, PY_LONG_LONG *p)
{
- PY_LONG_LONG x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyInt_AsUnsignedLongLongMask(v);
- if (x == -1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ PY_LONG_LONG x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyInt_AsUnsignedLongLongMask(v);
+ if (x == -1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling native unsigned long long. */
@@ -408,17 +408,17 @@ get_longlong(PyObject *v, PY_LONG_LONG *p)
static int
get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
{
- unsigned PY_LONG_LONG x;
- if (PyFloat_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "int expected instead of float");
- return -1;
- }
- x = PyInt_AsUnsignedLongLongMask(v);
- if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ unsigned PY_LONG_LONG x;
+ if (PyFloat_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "int expected instead of float");
+ return -1;
+ }
+ x = PyInt_AsUnsignedLongLongMask(v);
+ if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#endif
@@ -441,49 +441,49 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
/* This macro CHANGES the first parameter IN PLACE. For proper sign handling,
we must first shift left, then right.
*/
-#define GET_BITFIELD(v, size) \
- if (NUM_BITS(size)) { \
- v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
- v >>= (sizeof(v)*8 - NUM_BITS(size)); \
- }
+#define GET_BITFIELD(v, size) \
+ if (NUM_BITS(size)) { \
+ v <<= (sizeof(v)*8 - LOW_BIT(size) - NUM_BITS(size)); \
+ v >>= (sizeof(v)*8 - NUM_BITS(size)); \
+ }
/* This macro RETURNS the first parameter with the bit field CHANGED. */
-#define SET(x, v, size) \
- (NUM_BITS(size) ? \
- ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \
- : v)
+#define SET(x, v, size) \
+ (NUM_BITS(size) ? \
+ ( ( x & ~(BIT_MASK(size) << LOW_BIT(size)) ) | ( (v & BIT_MASK(size)) << LOW_BIT(size) ) ) \
+ : v)
/* byte swapping macros */
-#define SWAP_2(v) \
- ( ( (v >> 8) & 0x00FF) | \
- ( (v << 8) & 0xFF00) )
+#define SWAP_2(v) \
+ ( ( (v >> 8) & 0x00FF) | \
+ ( (v << 8) & 0xFF00) )
-#define SWAP_4(v) \
- ( ( (v & 0x000000FF) << 24 ) | \
- ( (v & 0x0000FF00) << 8 ) | \
- ( (v & 0x00FF0000) >> 8 ) | \
- ( ((v >> 24) & 0xFF)) )
+#define SWAP_4(v) \
+ ( ( (v & 0x000000FF) << 24 ) | \
+ ( (v & 0x0000FF00) << 8 ) | \
+ ( (v & 0x00FF0000) >> 8 ) | \
+ ( ((v >> 24) & 0xFF)) )
#ifdef _MSC_VER
-#define SWAP_8(v) \
- ( ( (v & 0x00000000000000FFL) << 56 ) | \
- ( (v & 0x000000000000FF00L) << 40 ) | \
- ( (v & 0x0000000000FF0000L) << 24 ) | \
- ( (v & 0x00000000FF000000L) << 8 ) | \
- ( (v & 0x000000FF00000000L) >> 8 ) | \
- ( (v & 0x0000FF0000000000L) >> 24 ) | \
- ( (v & 0x00FF000000000000L) >> 40 ) | \
- ( ((v >> 56) & 0xFF)) )
+#define SWAP_8(v) \
+ ( ( (v & 0x00000000000000FFL) << 56 ) | \
+ ( (v & 0x000000000000FF00L) << 40 ) | \
+ ( (v & 0x0000000000FF0000L) << 24 ) | \
+ ( (v & 0x00000000FF000000L) << 8 ) | \
+ ( (v & 0x000000FF00000000L) >> 8 ) | \
+ ( (v & 0x0000FF0000000000L) >> 24 ) | \
+ ( (v & 0x00FF000000000000L) >> 40 ) | \
+ ( ((v >> 56) & 0xFF)) )
#else
-#define SWAP_8(v) \
- ( ( (v & 0x00000000000000FFLL) << 56 ) | \
- ( (v & 0x000000000000FF00LL) << 40 ) | \
- ( (v & 0x0000000000FF0000LL) << 24 ) | \
- ( (v & 0x00000000FF000000LL) << 8 ) | \
- ( (v & 0x000000FF00000000LL) >> 8 ) | \
- ( (v & 0x0000FF0000000000LL) >> 24 ) | \
- ( (v & 0x00FF000000000000LL) >> 40 ) | \
- ( ((v >> 56) & 0xFF)) )
+#define SWAP_8(v) \
+ ( ( (v & 0x00000000000000FFLL) << 56 ) | \
+ ( (v & 0x000000000000FF00LL) << 40 ) | \
+ ( (v & 0x0000000000FF0000LL) << 24 ) | \
+ ( (v & 0x00000000FF000000LL) << 8 ) | \
+ ( (v & 0x000000FF00000000LL) >> 8 ) | \
+ ( (v & 0x0000FF0000000000LL) >> 24 ) | \
+ ( (v & 0x00FF000000000000LL) >> 40 ) | \
+ ( ((v >> 56) & 0xFF)) )
#endif
#define SWAP_INT SWAP_4
@@ -520,184 +520,184 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
static PyObject *
b_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- if (get_long(value, &val) < 0)
- return NULL;
- *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size);
- _RET(value);
+ long val;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ *(signed char *)ptr = (signed char)SET(*(signed char *)ptr, (signed char)val, size);
+ _RET(value);
}
static PyObject *
b_get(void *ptr, Py_ssize_t size)
{
- signed char val = *(signed char *)ptr;
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ signed char val = *(signed char *)ptr;
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
B_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- if (get_ulong(value, &val) < 0)
- return NULL;
- *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr,
- (unsigned short)val, size);
- _RET(value);
+ unsigned long val;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ *(unsigned char *)ptr = (unsigned char)SET(*(unsigned char*)ptr,
+ (unsigned short)val, size);
+ _RET(value);
}
static PyObject *
B_get(void *ptr, Py_ssize_t size)
{
- unsigned char val = *(unsigned char *)ptr;
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ unsigned char val = *(unsigned char *)ptr;
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
h_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- short x;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (short)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ long val;
+ short x;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (short)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
h_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- short field;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_2(field);
- field = SET(field, (short)val, size);
- field = SWAP_2(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ long val;
+ short field;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_2(field);
+ field = SET(field, (short)val, size);
+ field = SWAP_2(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
h_get(void *ptr, Py_ssize_t size)
{
- short val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyInt_FromLong((long)val);
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong((long)val);
}
static PyObject *
h_get_sw(void *ptr, Py_ssize_t size)
{
- short val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_2(val);
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
H_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned short x;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (unsigned short)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned long val;
+ unsigned short x;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (unsigned short)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
H_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned short field;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_2(field);
- field = SET(field, (unsigned short)val, size);
- field = SWAP_2(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned long val;
+ unsigned short field;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_2(field);
+ field = SET(field, (unsigned short)val, size);
+ field = SWAP_2(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
H_get(void *ptr, Py_ssize_t size)
{
- unsigned short val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
H_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned short val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_2(val);
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ unsigned short val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_2(val);
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
i_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- int x;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (int)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ long val;
+ int x;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (int)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
i_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- int field;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_INT(field);
- field = SET(field, (int)val, size);
- field = SWAP_INT(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ long val;
+ int field;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_INT(field);
+ field = SET(field, (int)val, size);
+ field = SWAP_INT(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
i_get(void *ptr, Py_ssize_t size)
{
- int val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ int val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
i_get_sw(void *ptr, Py_ssize_t size)
{
- int val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_INT(val);
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ int val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_INT(val);
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
#ifdef MS_WIN32
@@ -705,22 +705,22 @@ i_get_sw(void *ptr, Py_ssize_t size)
static PyObject *
vBOOL_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- switch (PyObject_IsTrue(value)) {
- case -1:
- return NULL;
- case 0:
- *(short int *)ptr = VARIANT_FALSE;
- _RET(value);
- default:
- *(short int *)ptr = VARIANT_TRUE;
- _RET(value);
- }
+ switch (PyObject_IsTrue(value)) {
+ case -1:
+ return NULL;
+ case 0:
+ *(short int *)ptr = VARIANT_FALSE;
+ _RET(value);
+ default:
+ *(short int *)ptr = VARIANT_TRUE;
+ _RET(value);
+ }
}
static PyObject *
vBOOL_get(void *ptr, Py_ssize_t size)
{
- return PyBool_FromLong((long)*(short int *)ptr);
+ return PyBool_FromLong((long)*(short int *)ptr);
}
#endif
@@ -735,260 +735,260 @@ vBOOL_get(void *ptr, Py_ssize_t size)
static PyObject *
bool_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- switch (PyObject_IsTrue(value)) {
- case -1:
- return NULL;
- case 0:
- *(BOOL_TYPE *)ptr = 0;
- _RET(value);
- default:
- *(BOOL_TYPE *)ptr = 1;
- _RET(value);
- }
+ switch (PyObject_IsTrue(value)) {
+ case -1:
+ return NULL;
+ case 0:
+ *(BOOL_TYPE *)ptr = 0;
+ _RET(value);
+ default:
+ *(BOOL_TYPE *)ptr = 1;
+ _RET(value);
+ }
}
static PyObject *
bool_get(void *ptr, Py_ssize_t size)
{
- return PyBool_FromLong((long)*(BOOL_TYPE *)ptr);
+ return PyBool_FromLong((long)*(BOOL_TYPE *)ptr);
}
static PyObject *
I_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned int x;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, (unsigned int)val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned long val;
+ unsigned int x;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, (unsigned int)val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
I_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned int field;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = (unsigned int)SET(field, (unsigned int)val, size);
- field = SWAP_INT(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned long val;
+ unsigned int field;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = (unsigned int)SET(field, (unsigned int)val, size);
+ field = SWAP_INT(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
I_get(void *ptr, Py_ssize_t size)
{
- unsigned int val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned int val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
static PyObject *
I_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned int val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_INT(val);
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned int val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_INT(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
static PyObject *
l_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- long x;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ long val;
+ long x;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
l_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- long val;
- long field;
- if (get_long(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_LONG(field);
- field = (long)SET(field, val, size);
- field = SWAP_LONG(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ long val;
+ long field;
+ if (get_long(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_LONG(field);
+ field = (long)SET(field, val, size);
+ field = SWAP_LONG(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
l_get(void *ptr, Py_ssize_t size)
{
- long val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ long val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
l_get_sw(void *ptr, Py_ssize_t size)
{
- long val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_LONG(val);
- GET_BITFIELD(val, size);
- return PyInt_FromLong(val);
+ long val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_LONG(val);
+ GET_BITFIELD(val, size);
+ return PyInt_FromLong(val);
}
static PyObject *
L_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned long x;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned long val;
+ unsigned long x;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
L_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned long val;
- unsigned long field;
- if (get_ulong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_LONG(field);
- field = (unsigned long)SET(field, val, size);
- field = SWAP_LONG(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned long val;
+ unsigned long field;
+ if (get_ulong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_LONG(field);
+ field = (unsigned long)SET(field, val, size);
+ field = SWAP_LONG(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
L_get(void *ptr, Py_ssize_t size)
{
- unsigned long val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned long val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
static PyObject *
L_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned long val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_LONG(val);
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLong(val);
+ unsigned long val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_LONG(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLong(val);
}
#ifdef HAVE_LONG_LONG
static PyObject *
q_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- PY_LONG_LONG val;
- PY_LONG_LONG x;
- if (get_longlong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ PY_LONG_LONG val;
+ PY_LONG_LONG x;
+ if (get_longlong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- PY_LONG_LONG val;
- PY_LONG_LONG field;
- if (get_longlong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_8(field);
- field = (PY_LONG_LONG)SET(field, val, size);
- field = SWAP_8(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ PY_LONG_LONG val;
+ PY_LONG_LONG field;
+ if (get_longlong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_8(field);
+ field = (PY_LONG_LONG)SET(field, val, size);
+ field = SWAP_8(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
q_get(void *ptr, Py_ssize_t size)
{
- PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromLongLong(val);
+ PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromLongLong(val);
}
static PyObject *
q_get_sw(void *ptr, Py_ssize_t size)
{
- PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_8(val);
- GET_BITFIELD(val, size);
- return PyLong_FromLongLong(val);
+ PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_8(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromLongLong(val);
}
static PyObject *
Q_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- unsigned PY_LONG_LONG x;
- if (get_ulonglong(value, &val) < 0)
- return NULL;
- memcpy(&x, ptr, sizeof(x));
- x = SET(x, val, size);
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ unsigned PY_LONG_LONG val;
+ unsigned PY_LONG_LONG x;
+ if (get_ulonglong(value, &val) < 0)
+ return NULL;
+ memcpy(&x, ptr, sizeof(x));
+ x = SET(x, val, size);
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
Q_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- unsigned PY_LONG_LONG field;
- if (get_ulonglong(value, &val) < 0)
- return NULL;
- memcpy(&field, ptr, sizeof(field));
- field = SWAP_8(field);
- field = (unsigned PY_LONG_LONG)SET(field, val, size);
- field = SWAP_8(field);
- memcpy(ptr, &field, sizeof(field));
- _RET(value);
+ unsigned PY_LONG_LONG val;
+ unsigned PY_LONG_LONG field;
+ if (get_ulonglong(value, &val) < 0)
+ return NULL;
+ memcpy(&field, ptr, sizeof(field));
+ field = SWAP_8(field);
+ field = (unsigned PY_LONG_LONG)SET(field, val, size);
+ field = SWAP_8(field);
+ memcpy(ptr, &field, sizeof(field));
+ _RET(value);
}
static PyObject *
Q_get(void *ptr, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLongLong(val);
+ unsigned PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLongLong(val);
}
static PyObject *
Q_get_sw(void *ptr, Py_ssize_t size)
{
- unsigned PY_LONG_LONG val;
- memcpy(&val, ptr, sizeof(val));
- val = SWAP_8(val);
- GET_BITFIELD(val, size);
- return PyLong_FromUnsignedLongLong(val);
+ unsigned PY_LONG_LONG val;
+ memcpy(&val, ptr, sizeof(val));
+ val = SWAP_8(val);
+ GET_BITFIELD(val, size);
+ return PyLong_FromUnsignedLongLong(val);
}
#endif
@@ -1000,136 +1000,136 @@ Q_get_sw(void *ptr, Py_ssize_t size)
static PyObject *
g_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- long double x;
+ long double x;
- x = PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
- memcpy(ptr, &x, sizeof(long double));
- _RET(value);
+ x = PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+ memcpy(ptr, &x, sizeof(long double));
+ _RET(value);
}
static PyObject *
g_get(void *ptr, Py_ssize_t size)
{
- long double val;
- memcpy(&val, ptr, sizeof(long double));
- return PyFloat_FromDouble(val);
+ long double val;
+ memcpy(&val, ptr, sizeof(long double));
+ return PyFloat_FromDouble(val);
}
static PyObject *
d_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- double x;
+ double x;
- x = PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
- memcpy(ptr, &x, sizeof(double));
- _RET(value);
+ x = PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+ memcpy(ptr, &x, sizeof(double));
+ _RET(value);
}
static PyObject *
d_get(void *ptr, Py_ssize_t size)
{
- double val;
- memcpy(&val, ptr, sizeof(val));
- return PyFloat_FromDouble(val);
+ double val;
+ memcpy(&val, ptr, sizeof(val));
+ return PyFloat_FromDouble(val);
}
static PyObject *
d_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- double x;
+ double x;
- x = PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
+ x = PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
#ifdef WORDS_BIGENDIAN
- if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1))
- return NULL;
+ if (_PyFloat_Pack8(x, (unsigned char *)ptr, 1))
+ return NULL;
#else
- if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0))
- return NULL;
+ if (_PyFloat_Pack8(x, (unsigned char *)ptr, 0))
+ return NULL;
#endif
- _RET(value);
+ _RET(value);
}
static PyObject *
d_get_sw(void *ptr, Py_ssize_t size)
{
#ifdef WORDS_BIGENDIAN
- return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1));
+ return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 1));
#else
- return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0));
+ return PyFloat_FromDouble(_PyFloat_Unpack8(ptr, 0));
#endif
}
static PyObject *
f_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- float x;
+ float x;
- x = (float)PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
- memcpy(ptr, &x, sizeof(x));
- _RET(value);
+ x = (float)PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+ memcpy(ptr, &x, sizeof(x));
+ _RET(value);
}
static PyObject *
f_get(void *ptr, Py_ssize_t size)
{
- float val;
- memcpy(&val, ptr, sizeof(val));
- return PyFloat_FromDouble(val);
+ float val;
+ memcpy(&val, ptr, sizeof(val));
+ return PyFloat_FromDouble(val);
}
static PyObject *
f_set_sw(void *ptr, PyObject *value, Py_ssize_t size)
{
- float x;
+ float x;
- x = (float)PyFloat_AsDouble(value);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError,
- " float expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
+ x = (float)PyFloat_AsDouble(value);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError,
+ " float expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
#ifdef WORDS_BIGENDIAN
- if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1))
- return NULL;
+ if (_PyFloat_Pack4(x, (unsigned char *)ptr, 1))
+ return NULL;
#else
- if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0))
- return NULL;
+ if (_PyFloat_Pack4(x, (unsigned char *)ptr, 0))
+ return NULL;
#endif
- _RET(value);
+ _RET(value);
}
static PyObject *
f_get_sw(void *ptr, Py_ssize_t size)
{
#ifdef WORDS_BIGENDIAN
- return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1));
+ return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 1));
#else
- return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0));
+ return PyFloat_FromDouble(_PyFloat_Unpack4(ptr, 0));
#endif
}
@@ -1146,45 +1146,45 @@ f_get_sw(void *ptr, Py_ssize_t size)
static PyObject *
O_get(void *ptr, Py_ssize_t size)
{
- PyObject *ob = *(PyObject **)ptr;
- if (ob == NULL) {
- if (!PyErr_Occurred())
- /* Set an error if not yet set */
- PyErr_SetString(PyExc_ValueError,
- "PyObject is NULL");
- return NULL;
- }
- Py_INCREF(ob);
- return ob;
+ PyObject *ob = *(PyObject **)ptr;
+ if (ob == NULL) {
+ if (!PyErr_Occurred())
+ /* Set an error if not yet set */
+ PyErr_SetString(PyExc_ValueError,
+ "PyObject is NULL");
+ return NULL;
+ }
+ Py_INCREF(ob);
+ return ob;
}
static PyObject *
O_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- /* Hm, does the memory block need it's own refcount or not? */
- *(PyObject **)ptr = value;
- Py_INCREF(value);
- return value;
+ /* Hm, does the memory block need it's own refcount or not? */
+ *(PyObject **)ptr = value;
+ Py_INCREF(value);
+ return value;
}
static PyObject *
c_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- if (!PyString_Check(value) || (1 != PyString_Size(value))) {
- PyErr_Format(PyExc_TypeError,
- "one character string expected");
- return NULL;
- }
- *(char *)ptr = PyString_AS_STRING(value)[0];
- _RET(value);
+ if (!PyString_Check(value) || (1 != PyString_Size(value))) {
+ PyErr_Format(PyExc_TypeError,
+ "one character string expected");
+ return NULL;
+ }
+ *(char *)ptr = PyString_AS_STRING(value)[0];
+ _RET(value);
}
static PyObject *
c_get(void *ptr, Py_ssize_t size)
{
- return PyString_FromStringAndSize((char *)ptr, 1);
+ return PyString_FromStringAndSize((char *)ptr, 1);
}
#ifdef CTYPES_UNICODE
@@ -1192,112 +1192,112 @@ c_get(void *ptr, Py_ssize_t size)
static PyObject *
u_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- Py_ssize_t len;
+ Py_ssize_t len;
- if (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- } else
- Py_INCREF(value);
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ } else
+ Py_INCREF(value);
- len = PyUnicode_GET_SIZE(value);
- if (len != 1) {
- Py_DECREF(value);
- PyErr_SetString(PyExc_TypeError,
- "one character unicode string expected");
- return NULL;
- }
+ len = PyUnicode_GET_SIZE(value);
+ if (len != 1) {
+ Py_DECREF(value);
+ PyErr_SetString(PyExc_TypeError,
+ "one character unicode string expected");
+ return NULL;
+ }
- *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0];
- Py_DECREF(value);
+ *(wchar_t *)ptr = PyUnicode_AS_UNICODE(value)[0];
+ Py_DECREF(value);
- _RET(value);
+ _RET(value);
}
static PyObject *
u_get(void *ptr, Py_ssize_t size)
{
- return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
+ return PyUnicode_FromWideChar((wchar_t *)ptr, 1);
}
/* U - a unicode string */
static PyObject *
U_get(void *ptr, Py_ssize_t size)
{
- PyObject *result;
- Py_ssize_t len;
- Py_UNICODE *p;
+ PyObject *result;
+ Py_ssize_t len;
+ Py_UNICODE *p;
- size /= sizeof(wchar_t); /* we count character units here, not bytes */
+ size /= sizeof(wchar_t); /* we count character units here, not bytes */
- result = PyUnicode_FromWideChar((wchar_t *)ptr, size);
- if (!result)
- return NULL;
- /* We need 'result' to be able to count the characters with wcslen,
- since ptr may not be NUL terminated. If the length is smaller (if
- it was actually NUL terminated, we construct a new one and throw
- away the result.
- */
- /* chop off at the first NUL character, if any. */
- p = PyUnicode_AS_UNICODE(result);
- for (len = 0; len < size; ++len)
- if (!p[len])
- break;
+ result = PyUnicode_FromWideChar((wchar_t *)ptr, size);
+ if (!result)
+ return NULL;
+ /* We need 'result' to be able to count the characters with wcslen,
+ since ptr may not be NUL terminated. If the length is smaller (if
+ it was actually NUL terminated, we construct a new one and throw
+ away the result.
+ */
+ /* chop off at the first NUL character, if any. */
+ p = PyUnicode_AS_UNICODE(result);
+ for (len = 0; len < size; ++len)
+ if (!p[len])
+ break;
- if (len < size) {
- PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len);
- Py_DECREF(result);
- return ob;
- }
- return result;
+ if (len < size) {
+ PyObject *ob = PyUnicode_FromWideChar((wchar_t *)ptr, len);
+ Py_DECREF(result);
+ return ob;
+ }
+ return result;
}
static PyObject *
U_set(void *ptr, PyObject *value, Py_ssize_t length)
{
- Py_ssize_t size;
-
- /* It's easier to calculate in characters than in bytes */
- length /= sizeof(wchar_t);
-
- if (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- } else
- Py_INCREF(value);
- size = PyUnicode_GET_SIZE(value);
- if (size > length) {
- PyErr_Format(PyExc_ValueError,
+ Py_ssize_t size;
+
+ /* It's easier to calculate in characters than in bytes */
+ length /= sizeof(wchar_t);
+
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ } else
+ Py_INCREF(value);
+ size = PyUnicode_GET_SIZE(value);
+ if (size > length) {
+ PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "string too long (%d, maximum length %d)",
+ "string too long (%d, maximum length %d)",
#else
- "string too long (%zd, maximum length %zd)",
+ "string too long (%zd, maximum length %zd)",
#endif
- size, length);
- Py_DECREF(value);
- return NULL;
- } else if (size < length-1)
- /* copy terminating NUL character if there is space */
- size += 1;
- PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
- return value;
+ size, length);
+ Py_DECREF(value);
+ return NULL;
+ } else if (size < length-1)
+ /* copy terminating NUL character if there is space */
+ size += 1;
+ PyUnicode_AsWideChar((PyUnicodeObject *)value, (wchar_t *)ptr, size);
+ return value;
}
#endif
@@ -1305,201 +1305,201 @@ U_set(void *ptr, PyObject *value, Py_ssize_t length)
static PyObject *
s_get(void *ptr, Py_ssize_t size)
{
- PyObject *result;
- size_t slen;
+ PyObject *result;
+ size_t slen;
- result = PyString_FromString((char *)ptr);
- if (!result)
- return NULL;
- /* chop off at the first NUL character, if any.
- * On error, result will be deallocated and set to NULL.
- */
- slen = strlen(PyString_AS_STRING(result));
- size = min(size, (Py_ssize_t)slen);
- if (result->ob_refcnt == 1) {
- /* shorten the result */
- _PyString_Resize(&result, size);
- return result;
- } else
- /* cannot shorten the result */
- return PyString_FromStringAndSize(ptr, size);
+ result = PyString_FromString((char *)ptr);
+ if (!result)
+ return NULL;
+ /* chop off at the first NUL character, if any.
+ * On error, result will be deallocated and set to NULL.
+ */
+ slen = strlen(PyString_AS_STRING(result));
+ size = min(size, (Py_ssize_t)slen);
+ if (result->ob_refcnt == 1) {
+ /* shorten the result */
+ _PyString_Resize(&result, size);
+ return result;
+ } else
+ /* cannot shorten the result */
+ return PyString_FromStringAndSize(ptr, size);
}
static PyObject *
s_set(void *ptr, PyObject *value, Py_ssize_t length)
{
- char *data;
- Py_ssize_t size;
-
- data = PyString_AsString(value);
- if (!data)
- return NULL;
- size = strlen(data);
- if (size < length) {
- /* This will copy the leading NUL character
- * if there is space for it.
- */
- ++size;
- } else if (size > length) {
- PyErr_Format(PyExc_ValueError,
+ char *data;
+ Py_ssize_t size;
+
+ data = PyString_AsString(value);
+ if (!data)
+ return NULL;
+ size = strlen(data);
+ if (size < length) {
+ /* This will copy the leading NUL character
+ * if there is space for it.
+ */
+ ++size;
+ } else if (size > length) {
+ PyErr_Format(PyExc_ValueError,
#if (PY_VERSION_HEX < 0x02050000)
- "string too long (%d, maximum length %d)",
+ "string too long (%d, maximum length %d)",
#else
- "string too long (%zd, maximum length %zd)",
+ "string too long (%zd, maximum length %zd)",
#endif
- size, length);
- return NULL;
- }
- /* Also copy the terminating NUL character if there is space */
- memcpy((char *)ptr, data, size);
- _RET(value);
+ size, length);
+ return NULL;
+ }
+ /* Also copy the terminating NUL character if there is space */
+ memcpy((char *)ptr, data, size);
+ _RET(value);
}
static PyObject *
z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- if (value == Py_None) {
- *(char **)ptr = NULL;
- Py_INCREF(value);
- return value;
- }
- if (PyString_Check(value)) {
- *(char **)ptr = PyString_AS_STRING(value);
- Py_INCREF(value);
- return value;
- } else if (PyUnicode_Check(value)) {
- PyObject *str = PyUnicode_AsEncodedString(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (str == NULL)
- return NULL;
- *(char **)ptr = PyString_AS_STRING(str);
- return str;
- } else if (PyInt_Check(value) || PyLong_Check(value)) {
+ if (value == Py_None) {
+ *(char **)ptr = NULL;
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyString_Check(value)) {
+ *(char **)ptr = PyString_AS_STRING(value);
+ Py_INCREF(value);
+ return value;
+ } else if (PyUnicode_Check(value)) {
+ PyObject *str = PyUnicode_AsEncodedString(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (str == NULL)
+ return NULL;
+ *(char **)ptr = PyString_AS_STRING(str);
+ return str;
+ } else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
- *(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value);
+ *(char **)ptr = (char *)PyInt_AsUnsignedLongLongMask(value);
#else
- *(char **)ptr = (char *)PyInt_AsUnsignedLongMask(value);
+ *(char **)ptr = (char *)PyInt_AsUnsignedLongMask(value);
#endif
- _RET(value);
- }
- PyErr_Format(PyExc_TypeError,
- "string or integer address expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
+ _RET(value);
+ }
+ PyErr_Format(PyExc_TypeError,
+ "string or integer address expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
}
static PyObject *
z_get(void *ptr, Py_ssize_t size)
{
- /* XXX What about invalid pointers ??? */
- if (*(void **)ptr) {
+ /* XXX What about invalid pointers ??? */
+ if (*(void **)ptr) {
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
- if (IsBadStringPtrA(*(char **)ptr, -1)) {
- PyErr_Format(PyExc_ValueError,
- "invalid string pointer %p",
- *(char **)ptr);
- return NULL;
- }
+ if (IsBadStringPtrA(*(char **)ptr, -1)) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid string pointer %p",
+ *(char **)ptr);
+ return NULL;
+ }
#endif
- return PyString_FromString(*(char **)ptr);
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ return PyString_FromString(*(char **)ptr);
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
#ifdef CTYPES_UNICODE
static PyObject *
Z_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- if (value == Py_None) {
- *(wchar_t **)ptr = NULL;
- Py_INCREF(value);
- return value;
- }
- if (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (PyInt_Check(value) || PyLong_Check(value)) {
+ if (value == Py_None) {
+ *(wchar_t **)ptr = NULL;
+ Py_INCREF(value);
+ return value;
+ }
+ if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (PyInt_Check(value) || PyLong_Check(value)) {
#if SIZEOF_VOID_P == SIZEOF_LONG_LONG
- *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
+ *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongLongMask(value);
#else
- *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
+ *(wchar_t **)ptr = (wchar_t *)PyInt_AsUnsignedLongMask(value);
#endif
- Py_INCREF(Py_None);
- return Py_None;
- } else if (!PyUnicode_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "unicode string or integer address expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- } else
- Py_INCREF(value);
+ Py_INCREF(Py_None);
+ return Py_None;
+ } else if (!PyUnicode_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string or integer address expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ } else
+ Py_INCREF(value);
#ifdef HAVE_USABLE_WCHAR_T
- /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
- type. So we can copy directly. Hm, are unicode objects always NUL
- terminated in Python, internally?
- */
- *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
- return value;
+ /* HAVE_USABLE_WCHAR_T means that Py_UNICODE and wchar_t is the same
+ type. So we can copy directly. Hm, are unicode objects always NUL
+ terminated in Python, internally?
+ */
+ *(wchar_t **)ptr = PyUnicode_AS_UNICODE(value);
+ return value;
#else
- {
- /* We must create a wchar_t* buffer from the unicode object,
- and keep it alive */
- PyObject *keep;
- wchar_t *buffer;
-
- int size = PyUnicode_GET_SIZE(value);
- size += 1; /* terminating NUL */
- size *= sizeof(wchar_t);
- buffer = (wchar_t *)PyMem_Malloc(size);
- if (!buffer) {
- Py_DECREF(value);
- return PyErr_NoMemory();
- }
- memset(buffer, 0, size);
- keep = CAPSULE_NEW(buffer, CTYPES_CAPSULE_WCHAR_T);
- if (!keep) {
- Py_DECREF(value);
- PyMem_Free(buffer);
- return NULL;
- }
- *(wchar_t **)ptr = (wchar_t *)buffer;
- if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
- buffer, PyUnicode_GET_SIZE(value))) {
- Py_DECREF(value);
- Py_DECREF(keep);
- return NULL;
- }
- Py_DECREF(value);
- return keep;
- }
+ {
+ /* We must create a wchar_t* buffer from the unicode object,
+ and keep it alive */
+ PyObject *keep;
+ wchar_t *buffer;
+
+ int size = PyUnicode_GET_SIZE(value);
+ size += 1; /* terminating NUL */
+ size *= sizeof(wchar_t);
+ buffer = (wchar_t *)PyMem_Malloc(size);
+ if (!buffer) {
+ Py_DECREF(value);
+ return PyErr_NoMemory();
+ }
+ memset(buffer, 0, size);
+ keep = CAPSULE_NEW(buffer, CTYPES_CAPSULE_WCHAR_T);
+ if (!keep) {
+ Py_DECREF(value);
+ PyMem_Free(buffer);
+ return NULL;
+ }
+ *(wchar_t **)ptr = (wchar_t *)buffer;
+ if (-1 == PyUnicode_AsWideChar((PyUnicodeObject *)value,
+ buffer, PyUnicode_GET_SIZE(value))) {
+ Py_DECREF(value);
+ Py_DECREF(keep);
+ return NULL;
+ }
+ Py_DECREF(value);
+ return keep;
+ }
#endif
}
static PyObject *
Z_get(void *ptr, Py_ssize_t size)
{
- wchar_t *p;
- p = *(wchar_t **)ptr;
- if (p) {
+ wchar_t *p;
+ p = *(wchar_t **)ptr;
+ if (p) {
#if defined(MS_WIN32) && !defined(_WIN32_WCE)
- if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) {
- PyErr_Format(PyExc_ValueError,
- "invalid string pointer %p",
- *(wchar_t **)ptr);
- return NULL;
- }
+ if (IsBadStringPtrW(*(wchar_t **)ptr, -1)) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid string pointer %p",
+ *(wchar_t **)ptr);
+ return NULL;
+ }
#endif
- return PyUnicode_FromWideChar(p, wcslen(p));
- } else {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ return PyUnicode_FromWideChar(p, wcslen(p));
+ } else {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
#endif
@@ -1507,166 +1507,166 @@ Z_get(void *ptr, Py_ssize_t size)
static PyObject *
BSTR_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- BSTR bstr;
-
- /* convert value into a PyUnicodeObject or NULL */
- if (Py_None == value) {
- value = NULL;
- } else if (PyString_Check(value)) {
- value = PyUnicode_FromEncodedObject(value,
- _ctypes_conversion_encoding,
- _ctypes_conversion_errors);
- if (!value)
- return NULL;
- } else if (PyUnicode_Check(value)) {
- Py_INCREF(value); /* for the descref below */
- } else {
- PyErr_Format(PyExc_TypeError,
- "unicode string expected instead of %s instance",
- value->ob_type->tp_name);
- return NULL;
- }
-
- /* create a BSTR from value */
- if (value) {
- Py_ssize_t size = PyUnicode_GET_SIZE(value);
- if ((unsigned) size != size) {
- PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
- return NULL;
- }
- bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
- (unsigned)size);
- Py_DECREF(value);
- } else
- bstr = NULL;
-
- /* free the previous contents, if any */
- if (*(BSTR *)ptr)
- SysFreeString(*(BSTR *)ptr);
-
- /* and store it */
- *(BSTR *)ptr = bstr;
-
- /* We don't need to keep any other object */
- _RET(value);
+ BSTR bstr;
+
+ /* convert value into a PyUnicodeObject or NULL */
+ if (Py_None == value) {
+ value = NULL;
+ } else if (PyString_Check(value)) {
+ value = PyUnicode_FromEncodedObject(value,
+ _ctypes_conversion_encoding,
+ _ctypes_conversion_errors);
+ if (!value)
+ return NULL;
+ } else if (PyUnicode_Check(value)) {
+ Py_INCREF(value); /* for the descref below */
+ } else {
+ PyErr_Format(PyExc_TypeError,
+ "unicode string expected instead of %s instance",
+ value->ob_type->tp_name);
+ return NULL;
+ }
+
+ /* create a BSTR from value */
+ if (value) {
+ Py_ssize_t size = PyUnicode_GET_SIZE(value);
+ if ((unsigned) size != size) {
+ PyErr_SetString(PyExc_ValueError, "String too long for BSTR");
+ return NULL;
+ }
+ bstr = SysAllocStringLen(PyUnicode_AS_UNICODE(value),
+ (unsigned)size);
+ Py_DECREF(value);
+ } else
+ bstr = NULL;
+
+ /* free the previous contents, if any */
+ if (*(BSTR *)ptr)
+ SysFreeString(*(BSTR *)ptr);
+
+ /* and store it */
+ *(BSTR *)ptr = bstr;
+
+ /* We don't need to keep any other object */
+ _RET(value);
}
static PyObject *
BSTR_get(void *ptr, Py_ssize_t size)
{
- BSTR p;
- p = *(BSTR *)ptr;
- if (p)
- return PyUnicode_FromWideChar(p, SysStringLen(p));
- else {
- /* Hm, it seems NULL pointer and zero length string are the
- same in BSTR, see Don Box, p 81
- */
- Py_INCREF(Py_None);
- return Py_None;
- }
+ BSTR p;
+ p = *(BSTR *)ptr;
+ if (p)
+ return PyUnicode_FromWideChar(p, SysStringLen(p));
+ else {
+ /* Hm, it seems NULL pointer and zero length string are the
+ same in BSTR, see Don Box, p 81
+ */
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
#endif
static PyObject *
P_set(void *ptr, PyObject *value, Py_ssize_t size)
{
- void *v;
- if (value == Py_None) {
- *(void **)ptr = NULL;
- _RET(value);
- }
+ void *v;
+ if (value == Py_None) {
+ *(void **)ptr = NULL;
+ _RET(value);
+ }
- if (!PyInt_Check(value) && !PyLong_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "cannot be converted to pointer");
- return NULL;
- }
+ if (!PyInt_Check(value) && !PyLong_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "cannot be converted to pointer");
+ return NULL;
+ }
#if SIZEOF_VOID_P <= SIZEOF_LONG
- v = (void *)PyInt_AsUnsignedLongMask(value);
+ v = (void *)PyInt_AsUnsignedLongMask(value);
#else
#ifndef HAVE_LONG_LONG
# error "PyLong_AsVoidPtr: sizeof(void*) > sizeof(long), but no long long"
#elif SIZEOF_LONG_LONG < SIZEOF_VOID_P
# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
#endif
- v = (void *)PyInt_AsUnsignedLongLongMask(value);
+ v = (void *)PyInt_AsUnsignedLongLongMask(value);
#endif
- if (PyErr_Occurred())
- return NULL;
+ if (PyErr_Occurred())
+ return NULL;
- *(void **)ptr = v;
- _RET(value);
+ *(void **)ptr = v;
+ _RET(value);
}
static PyObject *
P_get(void *ptr, Py_ssize_t size)
{
- if (*(void **)ptr == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyLong_FromVoidPtr(*(void **)ptr);
+ if (*(void **)ptr == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyLong_FromVoidPtr(*(void **)ptr);
}
static struct fielddesc formattable[] = {
- { 's', s_set, s_get, &ffi_type_pointer},
- { 'b', b_set, b_get, &ffi_type_schar},
- { 'B', B_set, B_get, &ffi_type_uchar},
- { 'c', c_set, c_get, &ffi_type_schar},
- { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw},
- { 'g', g_set, g_get, &ffi_type_longdouble},
- { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw},
- { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw},
- { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw},
- { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw},
- { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw},
+ { 's', s_set, s_get, &ffi_type_pointer},
+ { 'b', b_set, b_get, &ffi_type_schar},
+ { 'B', B_set, B_get, &ffi_type_uchar},
+ { 'c', c_set, c_get, &ffi_type_schar},
+ { 'd', d_set, d_get, &ffi_type_double, d_set_sw, d_get_sw},
+ { 'g', g_set, g_get, &ffi_type_longdouble},
+ { 'f', f_set, f_get, &ffi_type_float, f_set_sw, f_get_sw},
+ { 'h', h_set, h_get, &ffi_type_sshort, h_set_sw, h_get_sw},
+ { 'H', H_set, H_get, &ffi_type_ushort, H_set_sw, H_get_sw},
+ { 'i', i_set, i_get, &ffi_type_sint, i_set_sw, i_get_sw},
+ { 'I', I_set, I_get, &ffi_type_uint, I_set_sw, I_get_sw},
/* XXX Hm, sizeof(int) == sizeof(long) doesn't hold on every platform */
/* As soon as we can get rid of the type codes, this is no longer a problem */
#if SIZEOF_LONG == 4
- { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw},
- { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw},
+ { 'l', l_set, l_get, &ffi_type_sint32, l_set_sw, l_get_sw},
+ { 'L', L_set, L_get, &ffi_type_uint32, L_set_sw, L_get_sw},
#elif SIZEOF_LONG == 8
- { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw},
- { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw},
+ { 'l', l_set, l_get, &ffi_type_sint64, l_set_sw, l_get_sw},
+ { 'L', L_set, L_get, &ffi_type_uint64, L_set_sw, L_get_sw},
#else
# error
#endif
#ifdef HAVE_LONG_LONG
#if SIZEOF_LONG_LONG == 8
- { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw},
- { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw},
+ { 'q', q_set, q_get, &ffi_type_sint64, q_set_sw, q_get_sw},
+ { 'Q', Q_set, Q_get, &ffi_type_uint64, Q_set_sw, Q_get_sw},
#else
# error
#endif
#endif
- { 'P', P_set, P_get, &ffi_type_pointer},
- { 'z', z_set, z_get, &ffi_type_pointer},
+ { 'P', P_set, P_get, &ffi_type_pointer},
+ { 'z', z_set, z_get, &ffi_type_pointer},
#ifdef CTYPES_UNICODE
- { 'u', u_set, u_get, NULL}, /* ffi_type set later */
- { 'U', U_set, U_get, &ffi_type_pointer},
- { 'Z', Z_set, Z_get, &ffi_type_pointer},
+ { 'u', u_set, u_get, NULL}, /* ffi_type set later */
+ { 'U', U_set, U_get, &ffi_type_pointer},
+ { 'Z', Z_set, Z_get, &ffi_type_pointer},
#endif
#ifdef MS_WIN32
- { 'X', BSTR_set, BSTR_get, &ffi_type_pointer},
- { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort},
+ { 'X', BSTR_set, BSTR_get, &ffi_type_pointer},
+ { 'v', vBOOL_set, vBOOL_get, &ffi_type_sshort},
#endif
#if SIZEOF__BOOL == 1
- { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */
+ { '?', bool_set, bool_get, &ffi_type_uchar}, /* Also fallback for no native _Bool support */
#elif SIZEOF__BOOL == SIZEOF_SHORT
- { '?', bool_set, bool_get, &ffi_type_ushort},
+ { '?', bool_set, bool_get, &ffi_type_ushort},
#elif SIZEOF__BOOL == SIZEOF_INT
- { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw},
+ { '?', bool_set, bool_get, &ffi_type_uint, I_set_sw, I_get_sw},
#elif SIZEOF__BOOL == SIZEOF_LONG
- { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw},
+ { '?', bool_set, bool_get, &ffi_type_ulong, L_set_sw, L_get_sw},
#elif SIZEOF__BOOL == SIZEOF_LONG_LONG
- { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw},
+ { '?', bool_set, bool_get, &ffi_type_ulong, Q_set_sw, Q_get_sw},
#endif /* SIZEOF__BOOL */
- { 'O', O_set, O_get, &ffi_type_pointer},
- { 0, NULL, NULL, NULL},
+ { 'O', O_set, O_get, &ffi_type_pointer},
+ { 0, NULL, NULL, NULL},
};
/*
@@ -1677,26 +1677,26 @@ static struct fielddesc formattable[] = {
struct fielddesc *
_ctypes_get_fielddesc(char *fmt)
{
- static int initialized = 0;
- struct fielddesc *table = formattable;
+ static int initialized = 0;
+ struct fielddesc *table = formattable;
- if (!initialized) {
- initialized = 1;
+ if (!initialized) {
+ initialized = 1;
#ifdef CTYPES_UNICODE
- if (sizeof(wchar_t) == sizeof(short))
- _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort;
- else if (sizeof(wchar_t) == sizeof(int))
- _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint;
- else if (sizeof(wchar_t) == sizeof(long))
- _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong;
+ if (sizeof(wchar_t) == sizeof(short))
+ _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sshort;
+ else if (sizeof(wchar_t) == sizeof(int))
+ _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_sint;
+ else if (sizeof(wchar_t) == sizeof(long))
+ _ctypes_get_fielddesc("u")->pffi_type = &ffi_type_slong;
#endif
- }
+ }
- for (; table->code; ++table) {
- if (table->code == fmt[0])
- return table;
- }
- return NULL;
+ for (; table->code; ++table) {
+ if (table->code == fmt[0])
+ return table;
+ }
+ return NULL;
}
typedef struct { char c; char x; } s_char;
@@ -1740,10 +1740,10 @@ typedef struct { char c; PY_LONG_LONG x; } s_long_long;
/* from ffi.h:
typedef struct _ffi_type
{
- size_t size;
- unsigned short alignment;
- unsigned short type;
- struct _ffi_type **elements;
+ size_t size;
+ unsigned short alignment;
+ unsigned short type;
+ struct _ffi_type **elements;
} ffi_type;
*/
@@ -1770,7 +1770,7 @@ ffi_type ffi_type_double = { sizeof(double), DOUBLE_ALIGN, FFI_TYPE_DOUBLE };
#endif
/* This is already defined on OSX */
ffi_type ffi_type_longdouble = { sizeof(long double), LONGDOUBLE_ALIGN,
- FFI_TYPE_LONGDOUBLE };
+ FFI_TYPE_LONGDOUBLE };
ffi_type ffi_type_pointer = { sizeof(void *), VOID_P_ALIGN, FFI_TYPE_POINTER };
diff --git a/Modules/_ctypes/ctypes.h b/Modules/_ctypes/ctypes.h
index 718ee52..7d7ba1f 100644
--- a/Modules/_ctypes/ctypes.h
+++ b/Modules/_ctypes/ctypes.h
@@ -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 */
-
- 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;
+ /* 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;
+
+ /* 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;
-
- /* 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 */
+ 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 */
+
+ /* 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))
diff --git a/Modules/_ctypes/darwin/dlfcn_simple.c b/Modules/_ctypes/darwin/dlfcn_simple.c
index 4b55323..2b293bb 100644
--- a/Modules/_ctypes/darwin/dlfcn_simple.c
+++ b/Modules/_ctypes/darwin/dlfcn_simple.c
@@ -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 */
diff --git a/Modules/_ctypes/malloc_closure.c b/Modules/_ctypes/malloc_closure.c
index 042eba9..a691ab4 100644
--- a/Modules/_ctypes/malloc_closure.c
+++ b/Modules/_ctypes/malloc_closure.c
@@ -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;
}
diff --git a/Modules/_ctypes/stgdict.c b/Modules/_ctypes/stgdict.c
index e48eadc..4e7ea12 100644
--- a/Modules/_ctypes/stgdict.c
+++ b/Modules/_ctypes/stgdict.c
@@ -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;
-
- 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));
-
- 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->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;
+ 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;
+
+ 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);
+
+ 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;
}
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;
-
- 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;
+ 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;
}
/* 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;
-
- 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;
-
- 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_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;
+
+ 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;
}
/* 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;
-
- 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;
-
- /* 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;
+ 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;
+
+ 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);
+ }
+
+ 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;
-
- /* 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;
-
- if (fields == NULL)
- return 0;
+ 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;
+
+ 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_");
-
- 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;
- }
-
- 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->format) {
- PyMem_Free(stgdict->format);
- stgdict->format = NULL;
- }
-
- 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;
- }
-
- 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");
- }
+ 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();
+
+ 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. */
+
+ 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->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;
+ }
+
+ 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;
-
- 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,
+ 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 (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;
-
- case FFI_TYPE_SINT8:
- case FFI_TYPE_SINT16:
- case FFI_TYPE_SINT32:
- if (dict->getfunc != _ctypes_get_fielddesc("c")->getfunc
+ 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
#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);
-
- sprintf(buf, "%s:%s:", fieldfmt, fieldname);
-
- 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 (!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);
- }
+ )
+ 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);
+
+ 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 (!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)
- size = union_size;
-
- /* 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->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;
-
- return MakeAnonFields(type);
+ 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;
+
+ /* 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->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;
+
+ return MakeAnonFields(type);
}
diff --git a/Modules/_curses_panel.c b/Modules/_curses_panel.c
index 74e6bfa..04a0a28 100644
--- a/Modules/_curses_panel.c
+++ b/Modules/_curses_panel.c
@@ -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 */
diff --git a/Modules/_functoolsmodule.c b/Modules/_functoolsmodule.c
index 92fa4cb..572e7ff 100644
--- a/Modules/_functoolsmodule.c
+++ b/Modules/_functoolsmodule.c
@@ -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;
-
- 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;
- }
-
- if ((args = PyTuple_New(2)) == NULL)
- goto Fail;
-
- for (;;) {
- PyObject *op2;
-
- 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;
- }
-
- 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);
-
- if (result == NULL)
- PyErr_SetString(PyExc_TypeError,
- "reduce() of empty sequence with no initial value");
-
- Py_DECREF(it);
- return result;
+ PyObject *seq, *func, *result = NULL, *it;
+
+ 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;
+ }
+
+ if ((args = PyTuple_New(2)) == NULL)
+ goto Fail;
+
+ for (;;) {
+ PyObject *op2;
+
+ 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;
+ }
+
+ 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);
+
+ if (result == NULL)
+ PyErr_SetString(PyExc_TypeError,
+ "reduce() of empty sequence with no initial value");
+
+ 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;
-
- 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;
- }
-
- /* 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->weakreflist = NULL;
- pto->dict = NULL;
-
- return (PyObject *)pto;
+ PyObject *func;
+ partialobject *pto;
+
+ 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;
+ }
+
+ /* 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->weakreflist = NULL;
+ pto->dict = NULL;
+
+ 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;
-
- 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 (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;
+ 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));
+
+ 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;
+ }
+ }
+ }
+
+ 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;
-
- /* 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;
+ 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;
}
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
- };
-
- 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]);
- }
+ int i;
+ PyObject *m;
+ char *name;
+ PyTypeObject *typelist[] = {
+ &partial_type,
+ NULL
+ };
+
+ 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]);
+ }
}
diff --git a/Modules/_hashopenssl.c b/Modules/_hashopenssl.c
index 3e972d1..aa9dd4e 100644
--- a/Modules/_hashopenssl.c
+++ b/Modules/_hashopenssl.c
@@ -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 */
};
diff --git a/Modules/_heapqmodule.c b/Modules/_heapqmodule.c
index 4fd0dd5..f705ec1 100644
--- a/Modules/_heapqmodule.c
+++ b/Modules/_heapqmodule.c
@@ -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çois Pinard, and converted to C by Raymond Hettinger.
static int
cmp_lt(PyObject *x, PyObject *y)
{
- 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;
+ 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;
}
static int
_siftdown(PyListObject *heap, Py_ssize_t startpos, Py_ssize_t pos)
{
- 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;
- }
-
- 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;
+ 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;
+ }
+
+ 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;
-
- 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;
- }
-
- /* 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);
+ 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);
+
+ /* 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);
}
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;
-
- 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;
- }
-
- 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;
+ PyObject *lastelt, *returnitem;
+ Py_ssize_t n;
+
+ 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;
+ }
+
+ 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;
}
PyDoc_STRVAR(heappop_doc,
@@ -183,29 +183,29 @@ PyDoc_STRVAR(heappop_doc,
static PyObject *
heapreplace(PyObject *self, PyObject *args)
{
- PyObject *heap, *item, *returnitem;
-
- 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_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;
+ PyObject *heap, *item, *returnitem;
+
+ 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_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;
}
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;
-
- 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_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;
- }
-
- 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;
+ PyObject *heap, *item, *returnitem;
+ int cmp;
+
+ 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_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;
+ }
+
+ 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;
-
- 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;
+ Py_ssize_t i, n;
+
+ 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;
}
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;
-
- if (!PyArg_ParseTuple(args, "nO:nlargest", &n, &iterable))
- return NULL;
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- 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=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);
- }
+ 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;
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ 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=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);
+ }
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;
-
- 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;
+ 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;
+ }
+
+ 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;
-
- 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;
- }
-
- /* 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);
+ 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);
+
+ /* 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);
}
static PyObject *
nsmallest(PyObject *self, PyObject *args)
{
- 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;
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- 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=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;
- }
-
- 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);
- }
+ 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;
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ 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=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;
+ }
+
+ 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__));
}
diff --git a/Modules/_hotshot.c b/Modules/_hotshot.c
index a36cd50..df8a7f9 100644
--- a/Modules/_hotshot.c
+++ b/Modules/_hotshot.c
@@ -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 @@ restart:
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"
diff --git a/Modules/_localemodule.c b/Modules/_localemodule.c
index f1f4abf..253a4dc 100644
--- a/Modules/_localemodule.c
+++ b/Modules/_localemodule.c
@@ -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
diff --git a/Modules/_lsprof.c b/Modules/_lsprof.c
index 8820fcf..049c94d 100644
--- a/Modules/_lsprof.c
+++ b/Modules/_lsprof.c
@@ -17,19 +17,19 @@
static PY_LONG_LONG
hpTimer(void)
{
- LARGE_INTEGER li;
- QueryPerformanceCounter(&li);
- return li.QuadPart;
+ LARGE_INTEGER li;
+ QueryPerformanceCounter(&li);
+ return li.QuadPart;
}
static double
hpTimerUnit(void)
{
- LARGE_INTEGER li;
- if (QueryPerformanceFrequency(&li))
- return 1.0 / li.QuadPart;
- else
- return 0.000001; /* unlikely */
+ LARGE_INTEGER li;
+ if (QueryPerformanceFrequency(&li))
+ return 1.0 / li.QuadPart;
+ else
+ return 0.000001; /* unlikely */
}
#else /* !MS_WINDOWS */
@@ -48,22 +48,22 @@ hpTimerUnit(void)
static PY_LONG_LONG
hpTimer(void)
{
- struct timeval tv;
- PY_LONG_LONG ret;
+ struct timeval tv;
+ PY_LONG_LONG ret;
#ifdef GETTIMEOFDAY_NO_TZ
- gettimeofday(&tv);
+ gettimeofday(&tv);
#else
- gettimeofday(&tv, (struct timezone *)NULL);
+ gettimeofday(&tv, (struct timezone *)NULL);
#endif
- ret = tv.tv_sec;
- ret = ret * 1000000 + tv.tv_usec;
- return ret;
+ ret = tv.tv_sec;
+ ret = ret * 1000000 + tv.tv_usec;
+ return ret;
}
static double
hpTimerUnit(void)
{
- return 0.000001;
+ return 0.000001;
}
#endif /* MS_WINDOWS */
@@ -75,41 +75,41 @@ struct _ProfilerEntry;
/* represents a function called from another function */
typedef struct _ProfilerSubEntry {
- rotating_node_t header;
- PY_LONG_LONG tt;
- PY_LONG_LONG it;
- long callcount;
- long recursivecallcount;
- long recursionLevel;
+ rotating_node_t header;
+ PY_LONG_LONG tt;
+ PY_LONG_LONG it;
+ long callcount;
+ long recursivecallcount;
+ long recursionLevel;
} ProfilerSubEntry;
/* represents a function or user defined block */
typedef struct _ProfilerEntry {
- rotating_node_t header;
- PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
- PY_LONG_LONG tt; /* total time in this entry */
- PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */
- long callcount; /* how many times this was called */
- long recursivecallcount; /* how many times called recursively */
- long recursionLevel;
- rotating_node_t *calls;
+ rotating_node_t header;
+ PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
+ PY_LONG_LONG tt; /* total time in this entry */
+ PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */
+ long callcount; /* how many times this was called */
+ long recursivecallcount; /* how many times called recursively */
+ long recursionLevel;
+ rotating_node_t *calls;
} ProfilerEntry;
typedef struct _ProfilerContext {
- PY_LONG_LONG t0;
- PY_LONG_LONG subt;
- struct _ProfilerContext *previous;
- ProfilerEntry *ctxEntry;
+ PY_LONG_LONG t0;
+ PY_LONG_LONG subt;
+ struct _ProfilerContext *previous;
+ ProfilerEntry *ctxEntry;
} ProfilerContext;
typedef struct {
- PyObject_HEAD
- rotating_node_t *profilerEntries;
- ProfilerContext *currentProfilerContext;
- ProfilerContext *freelistProfilerContext;
- int flags;
- PyObject *externalTimer;
- double externalTimerUnit;
+ PyObject_HEAD
+ rotating_node_t *profilerEntries;
+ ProfilerContext *currentProfilerContext;
+ ProfilerContext *freelistProfilerContext;
+ int flags;
+ PyObject *externalTimer;
+ double externalTimerUnit;
} ProfilerObject;
#define POF_ENABLED 0x001
@@ -129,407 +129,407 @@ static PyObject *empty_tuple;
static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj)
{
- PY_LONG_LONG result;
- PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL);
- if (o == NULL) {
- PyErr_WriteUnraisable(pObj->externalTimer);
- return 0;
- }
- if (pObj->externalTimerUnit > 0.0) {
- /* interpret the result as an integer that will be scaled
- in profiler_getstats() */
- result = PyLong_AsLongLong(o);
- }
- else {
- /* interpret the result as a double measured in seconds.
- As the profiler works with PY_LONG_LONG internally
- we convert it to a large integer */
- double val = PyFloat_AsDouble(o);
- /* error handling delayed to the code below */
- result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION);
- }
- Py_DECREF(o);
- if (PyErr_Occurred()) {
- PyErr_WriteUnraisable(pObj->externalTimer);
- return 0;
- }
- return result;
+ PY_LONG_LONG result;
+ PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL);
+ if (o == NULL) {
+ PyErr_WriteUnraisable(pObj->externalTimer);
+ return 0;
+ }
+ if (pObj->externalTimerUnit > 0.0) {
+ /* interpret the result as an integer that will be scaled
+ in profiler_getstats() */
+ result = PyLong_AsLongLong(o);
+ }
+ else {
+ /* interpret the result as a double measured in seconds.
+ As the profiler works with PY_LONG_LONG internally
+ we convert it to a large integer */
+ double val = PyFloat_AsDouble(o);
+ /* error handling delayed to the code below */
+ result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION);
+ }
+ Py_DECREF(o);
+ if (PyErr_Occurred()) {
+ PyErr_WriteUnraisable(pObj->externalTimer);
+ return 0;
+ }
+ return result;
}
-#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \
- CallExternalTimer(pObj) : \
- hpTimer())
+#define CALL_TIMER(pObj) ((pObj)->externalTimer ? \
+ CallExternalTimer(pObj) : \
+ hpTimer())
/*** ProfilerObject ***/
static PyObject *
normalizeUserObj(PyObject *obj)
{
- PyCFunctionObject *fn;
- if (!PyCFunction_Check(obj)) {
- Py_INCREF(obj);
- return obj;
- }
- /* Replace built-in function objects with a descriptive string
- because of built-in methods -- keeping a reference to
- __self__ is probably not a good idea. */
- fn = (PyCFunctionObject *)obj;
-
- if (fn->m_self == NULL) {
- /* built-in function: look up the module name */
- PyObject *mod = fn->m_module;
- char *modname;
- if (mod && PyString_Check(mod)) {
- modname = PyString_AS_STRING(mod);
- }
- else if (mod && PyModule_Check(mod)) {
- modname = PyModule_GetName(mod);
- if (modname == NULL) {
- PyErr_Clear();
- modname = "__builtin__";
- }
- }
- else {
- modname = "__builtin__";
- }
- if (strcmp(modname, "__builtin__") != 0)
- return PyString_FromFormat("<%s.%s>",
- modname,
- fn->m_ml->ml_name);
- else
- return PyString_FromFormat("<%s>",
- fn->m_ml->ml_name);
- }
- else {
- /* built-in method: try to return
- repr(getattr(type(__self__), __name__))
- */
- PyObject *self = fn->m_self;
- PyObject *name = PyString_FromString(fn->m_ml->ml_name);
- if (name != NULL) {
- PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
- Py_XINCREF(mo);
- Py_DECREF(name);
- if (mo != NULL) {
- PyObject *res = PyObject_Repr(mo);
- Py_DECREF(mo);
- if (res != NULL)
- return res;
- }
- }
- PyErr_Clear();
- return PyString_FromFormat("<built-in method %s>",
- fn->m_ml->ml_name);
- }
+ PyCFunctionObject *fn;
+ if (!PyCFunction_Check(obj)) {
+ Py_INCREF(obj);
+ return obj;
+ }
+ /* Replace built-in function objects with a descriptive string
+ because of built-in methods -- keeping a reference to
+ __self__ is probably not a good idea. */
+ fn = (PyCFunctionObject *)obj;
+
+ if (fn->m_self == NULL) {
+ /* built-in function: look up the module name */
+ PyObject *mod = fn->m_module;
+ char *modname;
+ if (mod && PyString_Check(mod)) {
+ modname = PyString_AS_STRING(mod);
+ }
+ else if (mod && PyModule_Check(mod)) {
+ modname = PyModule_GetName(mod);
+ if (modname == NULL) {
+ PyErr_Clear();
+ modname = "__builtin__";
+ }
+ }
+ else {
+ modname = "__builtin__";
+ }
+ if (strcmp(modname, "__builtin__") != 0)
+ return PyString_FromFormat("<%s.%s>",
+ modname,
+ fn->m_ml->ml_name);
+ else
+ return PyString_FromFormat("<%s>",
+ fn->m_ml->ml_name);
+ }
+ else {
+ /* built-in method: try to return
+ repr(getattr(type(__self__), __name__))
+ */
+ PyObject *self = fn->m_self;
+ PyObject *name = PyString_FromString(fn->m_ml->ml_name);
+ if (name != NULL) {
+ PyObject *mo = _PyType_Lookup(Py_TYPE(self), name);
+ Py_XINCREF(mo);
+ Py_DECREF(name);
+ if (mo != NULL) {
+ PyObject *res = PyObject_Repr(mo);
+ Py_DECREF(mo);
+ if (res != NULL)
+ return res;
+ }
+ }
+ PyErr_Clear();
+ return PyString_FromFormat("<built-in method %s>",
+ fn->m_ml->ml_name);
+ }
}
static ProfilerEntry*
newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj)
{
- ProfilerEntry *self;
- self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry));
- if (self == NULL) {
- pObj->flags |= POF_NOMEMORY;
- return NULL;
- }
- userObj = normalizeUserObj(userObj);
- if (userObj == NULL) {
- PyErr_Clear();
- free(self);
- pObj->flags |= POF_NOMEMORY;
- return NULL;
- }
- self->header.key = key;
- self->userObj = userObj;
- self->tt = 0;
- self->it = 0;
- self->callcount = 0;
- self->recursivecallcount = 0;
- self->recursionLevel = 0;
- self->calls = EMPTY_ROTATING_TREE;
- RotatingTree_Add(&pObj->profilerEntries, &self->header);
- return self;
+ ProfilerEntry *self;
+ self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry));
+ if (self == NULL) {
+ pObj->flags |= POF_NOMEMORY;
+ return NULL;
+ }
+ userObj = normalizeUserObj(userObj);
+ if (userObj == NULL) {
+ PyErr_Clear();
+ free(self);
+ pObj->flags |= POF_NOMEMORY;
+ return NULL;
+ }
+ self->header.key = key;
+ self->userObj = userObj;
+ self->tt = 0;
+ self->it = 0;
+ self->callcount = 0;
+ self->recursivecallcount = 0;
+ self->recursionLevel = 0;
+ self->calls = EMPTY_ROTATING_TREE;
+ RotatingTree_Add(&pObj->profilerEntries, &self->header);
+ return self;
}
static ProfilerEntry*
getEntry(ProfilerObject *pObj, void *key)
{
- return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
+ return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
}
-static ProfilerSubEntry *
+static ProfilerSubEntry *
getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
- return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
- (void *)entry);
+ return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
+ (void *)entry);
}
static ProfilerSubEntry *
newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
{
- ProfilerSubEntry *self;
- self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry));
- if (self == NULL) {
- pObj->flags |= POF_NOMEMORY;
- return NULL;
- }
- self->header.key = (void *)entry;
- self->tt = 0;
- self->it = 0;
- self->callcount = 0;
- self->recursivecallcount = 0;
- self->recursionLevel = 0;
- RotatingTree_Add(&caller->calls, &self->header);
- return self;
+ ProfilerSubEntry *self;
+ self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry));
+ if (self == NULL) {
+ pObj->flags |= POF_NOMEMORY;
+ return NULL;
+ }
+ self->header.key = (void *)entry;
+ self->tt = 0;
+ self->it = 0;
+ self->callcount = 0;
+ self->recursivecallcount = 0;
+ self->recursionLevel = 0;
+ RotatingTree_Add(&caller->calls, &self->header);
+ return self;
}
static int freeSubEntry(rotating_node_t *header, void *arg)
{
- ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
- free(subentry);
- return 0;
+ ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
+ free(subentry);
+ return 0;
}
static int freeEntry(rotating_node_t *header, void *arg)
{
- ProfilerEntry *entry = (ProfilerEntry*) header;
- RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
- Py_DECREF(entry->userObj);
- free(entry);
- return 0;
+ ProfilerEntry *entry = (ProfilerEntry*) header;
+ RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
+ Py_DECREF(entry->userObj);
+ free(entry);
+ return 0;
}
static void clearEntries(ProfilerObject *pObj)
{
- RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
- pObj->profilerEntries = EMPTY_ROTATING_TREE;
- /* release the memory hold by the ProfilerContexts */
- if (pObj->currentProfilerContext) {
- free(pObj->currentProfilerContext);
- pObj->currentProfilerContext = NULL;
- }
- while (pObj->freelistProfilerContext) {
- ProfilerContext *c = pObj->freelistProfilerContext;
- pObj->freelistProfilerContext = c->previous;
- free(c);
- }
- pObj->freelistProfilerContext = NULL;
+ RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
+ pObj->profilerEntries = EMPTY_ROTATING_TREE;
+ /* release the memory hold by the ProfilerContexts */
+ if (pObj->currentProfilerContext) {
+ free(pObj->currentProfilerContext);
+ pObj->currentProfilerContext = NULL;
+ }
+ while (pObj->freelistProfilerContext) {
+ ProfilerContext *c = pObj->freelistProfilerContext;
+ pObj->freelistProfilerContext = c->previous;
+ free(c);
+ }
+ pObj->freelistProfilerContext = NULL;
}
static void
initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
- self->ctxEntry = entry;
- self->subt = 0;
- self->previous = pObj->currentProfilerContext;
- pObj->currentProfilerContext = self;
- ++entry->recursionLevel;
- if ((pObj->flags & POF_SUBCALLS) && self->previous) {
- /* find or create an entry for me in my caller's entry */
- ProfilerEntry *caller = self->previous->ctxEntry;
- ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
- if (subentry == NULL)
- subentry = newSubEntry(pObj, caller, entry);
- if (subentry)
- ++subentry->recursionLevel;
- }
- self->t0 = CALL_TIMER(pObj);
+ self->ctxEntry = entry;
+ self->subt = 0;
+ self->previous = pObj->currentProfilerContext;
+ pObj->currentProfilerContext = self;
+ ++entry->recursionLevel;
+ if ((pObj->flags & POF_SUBCALLS) && self->previous) {
+ /* find or create an entry for me in my caller's entry */
+ ProfilerEntry *caller = self->previous->ctxEntry;
+ ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
+ if (subentry == NULL)
+ subentry = newSubEntry(pObj, caller, entry);
+ if (subentry)
+ ++subentry->recursionLevel;
+ }
+ self->t0 = CALL_TIMER(pObj);
}
static void
Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
{
- PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0;
- PY_LONG_LONG it = tt - self->subt;
- if (self->previous)
- self->previous->subt += tt;
- pObj->currentProfilerContext = self->previous;
- if (--entry->recursionLevel == 0)
- entry->tt += tt;
- else
- ++entry->recursivecallcount;
- entry->it += it;
- entry->callcount++;
- if ((pObj->flags & POF_SUBCALLS) && self->previous) {
- /* find or create an entry for me in my caller's entry */
- ProfilerEntry *caller = self->previous->ctxEntry;
- ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
- if (subentry) {
- if (--subentry->recursionLevel == 0)
- subentry->tt += tt;
- else
- ++subentry->recursivecallcount;
- subentry->it += it;
- ++subentry->callcount;
- }
- }
+ PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0;
+ PY_LONG_LONG it = tt - self->subt;
+ if (self->previous)
+ self->previous->subt += tt;
+ pObj->currentProfilerContext = self->previous;
+ if (--entry->recursionLevel == 0)
+ entry->tt += tt;
+ else
+ ++entry->recursivecallcount;
+ entry->it += it;
+ entry->callcount++;
+ if ((pObj->flags & POF_SUBCALLS) && self->previous) {
+ /* find or create an entry for me in my caller's entry */
+ ProfilerEntry *caller = self->previous->ctxEntry;
+ ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
+ if (subentry) {
+ if (--subentry->recursionLevel == 0)
+ subentry->tt += tt;
+ else
+ ++subentry->recursivecallcount;
+ subentry->it += it;
+ ++subentry->callcount;
+ }
+ }
}
static void
ptrace_enter_call(PyObject *self, void *key, PyObject *userObj)
{
- /* entering a call to the function identified by 'key'
- (which can be a PyCodeObject or a PyMethodDef pointer) */
- ProfilerObject *pObj = (ProfilerObject*)self;
- ProfilerEntry *profEntry;
- ProfilerContext *pContext;
-
- /* In the case of entering a generator expression frame via a
- * throw (gen_send_ex(.., 1)), we may already have an
- * Exception set here. We must not mess around with this
- * exception, and some of the code under here assumes that
- * PyErr_* is its own to mess around with, so we have to
- * save and restore any current exception. */
- PyObject *last_type, *last_value, *last_tb;
- PyErr_Fetch(&last_type, &last_value, &last_tb);
-
- profEntry = getEntry(pObj, key);
- if (profEntry == NULL) {
- profEntry = newProfilerEntry(pObj, key, userObj);
- if (profEntry == NULL)
- goto restorePyerr;
- }
- /* grab a ProfilerContext out of the free list */
- pContext = pObj->freelistProfilerContext;
- if (pContext) {
- pObj->freelistProfilerContext = pContext->previous;
- }
- else {
- /* free list exhausted, allocate a new one */
- pContext = (ProfilerContext*)
- malloc(sizeof(ProfilerContext));
- if (pContext == NULL) {
- pObj->flags |= POF_NOMEMORY;
- goto restorePyerr;
- }
- }
- initContext(pObj, pContext, profEntry);
+ /* entering a call to the function identified by 'key'
+ (which can be a PyCodeObject or a PyMethodDef pointer) */
+ ProfilerObject *pObj = (ProfilerObject*)self;
+ ProfilerEntry *profEntry;
+ ProfilerContext *pContext;
+
+ /* In the case of entering a generator expression frame via a
+ * throw (gen_send_ex(.., 1)), we may already have an
+ * Exception set here. We must not mess around with this
+ * exception, and some of the code under here assumes that
+ * PyErr_* is its own to mess around with, so we have to
+ * save and restore any current exception. */
+ PyObject *last_type, *last_value, *last_tb;
+ PyErr_Fetch(&last_type, &last_value, &last_tb);
+
+ profEntry = getEntry(pObj, key);
+ if (profEntry == NULL) {
+ profEntry = newProfilerEntry(pObj, key, userObj);
+ if (profEntry == NULL)
+ goto restorePyerr;
+ }
+ /* grab a ProfilerContext out of the free list */
+ pContext = pObj->freelistProfilerContext;
+ if (pContext) {
+ pObj->freelistProfilerContext = pContext->previous;
+ }
+ else {
+ /* free list exhausted, allocate a new one */
+ pContext = (ProfilerContext*)
+ malloc(sizeof(ProfilerContext));
+ if (pContext == NULL) {
+ pObj->flags |= POF_NOMEMORY;
+ goto restorePyerr;
+ }
+ }
+ initContext(pObj, pContext, profEntry);
restorePyerr:
- PyErr_Restore(last_type, last_value, last_tb);
+ PyErr_Restore(last_type, last_value, last_tb);
}
static void
ptrace_leave_call(PyObject *self, void *key)
{
- /* leaving a call to the function identified by 'key' */
- ProfilerObject *pObj = (ProfilerObject*)self;
- ProfilerEntry *profEntry;
- ProfilerContext *pContext;
-
- pContext = pObj->currentProfilerContext;
- if (pContext == NULL)
- return;
- profEntry = getEntry(pObj, key);
- if (profEntry) {
- Stop(pObj, pContext, profEntry);
- }
- else {
- pObj->currentProfilerContext = pContext->previous;
- }
- /* put pContext into the free list */
- pContext->previous = pObj->freelistProfilerContext;
- pObj->freelistProfilerContext = pContext;
+ /* leaving a call to the function identified by 'key' */
+ ProfilerObject *pObj = (ProfilerObject*)self;
+ ProfilerEntry *profEntry;
+ ProfilerContext *pContext;
+
+ pContext = pObj->currentProfilerContext;
+ if (pContext == NULL)
+ return;
+ profEntry = getEntry(pObj, key);
+ if (profEntry) {
+ Stop(pObj, pContext, profEntry);
+ }
+ else {
+ pObj->currentProfilerContext = pContext->previous;
+ }
+ /* put pContext into the free list */
+ pContext->previous = pObj->freelistProfilerContext;
+ pObj->freelistProfilerContext = pContext;
}
static int
profiler_callback(PyObject *self, PyFrameObject *frame, int what,
- PyObject *arg)
+ PyObject *arg)
{
- switch (what) {
-
- /* the 'frame' of a called function is about to start its execution */
- case PyTrace_CALL:
- ptrace_enter_call(self, (void *)frame->f_code,
- (PyObject *)frame->f_code);
- break;
-
- /* the 'frame' of a called function is about to finish
- (either normally or with an exception) */
- case PyTrace_RETURN:
- ptrace_leave_call(self, (void *)frame->f_code);
- break;
-
- /* case PyTrace_EXCEPTION:
- If the exception results in the function exiting, a
- PyTrace_RETURN event will be generated, so we don't need to
- handle it. */
-
-#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
- /* the Python function 'frame' is issuing a call to the built-in
- function 'arg' */
- case PyTrace_C_CALL:
- if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
- && PyCFunction_Check(arg)) {
- ptrace_enter_call(self,
- ((PyCFunctionObject *)arg)->m_ml,
- arg);
- }
- break;
-
- /* the call to the built-in function 'arg' is returning into its
- caller 'frame' */
- case PyTrace_C_RETURN: /* ...normally */
- case PyTrace_C_EXCEPTION: /* ...with an exception set */
- if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
- && PyCFunction_Check(arg)) {
- ptrace_leave_call(self,
- ((PyCFunctionObject *)arg)->m_ml);
- }
- break;
+ switch (what) {
+
+ /* the 'frame' of a called function is about to start its execution */
+ case PyTrace_CALL:
+ ptrace_enter_call(self, (void *)frame->f_code,
+ (PyObject *)frame->f_code);
+ break;
+
+ /* the 'frame' of a called function is about to finish
+ (either normally or with an exception) */
+ case PyTrace_RETURN:
+ ptrace_leave_call(self, (void *)frame->f_code);
+ break;
+
+ /* case PyTrace_EXCEPTION:
+ If the exception results in the function exiting, a
+ PyTrace_RETURN event will be generated, so we don't need to
+ handle it. */
+
+#ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
+ /* the Python function 'frame' is issuing a call to the built-in
+ function 'arg' */
+ case PyTrace_C_CALL:
+ if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
+ && PyCFunction_Check(arg)) {
+ ptrace_enter_call(self,
+ ((PyCFunctionObject *)arg)->m_ml,
+ arg);
+ }
+ break;
+
+ /* the call to the built-in function 'arg' is returning into its
+ caller 'frame' */
+ case PyTrace_C_RETURN: /* ...normally */
+ case PyTrace_C_EXCEPTION: /* ...with an exception set */
+ if ((((ProfilerObject *)self)->flags & POF_BUILTINS)
+ && PyCFunction_Check(arg)) {
+ ptrace_leave_call(self,
+ ((PyCFunctionObject *)arg)->m_ml);
+ }
+ break;
#endif
- default:
- break;
- }
- return 0;
+ default:
+ break;
+ }
+ return 0;
}
static int
pending_exception(ProfilerObject *pObj)
{
- if (pObj->flags & POF_NOMEMORY) {
- pObj->flags -= POF_NOMEMORY;
- PyErr_SetString(PyExc_MemoryError,
- "memory was exhausted while profiling");
- return -1;
- }
- return 0;
+ if (pObj->flags & POF_NOMEMORY) {
+ pObj->flags -= POF_NOMEMORY;
+ PyErr_SetString(PyExc_MemoryError,
+ "memory was exhausted while profiling");
+ return -1;
+ }
+ return 0;
}
/************************************************************/
static PyStructSequence_Field profiler_entry_fields[] = {
- {"code", "code object or built-in function name"},
- {"callcount", "how many times this was called"},
- {"reccallcount", "how many times called recursively"},
- {"totaltime", "total time in this entry"},
- {"inlinetime", "inline time in this entry (not in subcalls)"},
- {"calls", "details of the calls"},
- {0}
+ {"code", "code object or built-in function name"},
+ {"callcount", "how many times this was called"},
+ {"reccallcount", "how many times called recursively"},
+ {"totaltime", "total time in this entry"},
+ {"inlinetime", "inline time in this entry (not in subcalls)"},
+ {"calls", "details of the calls"},
+ {0}
};
static PyStructSequence_Field profiler_subentry_fields[] = {
- {"code", "called code object or built-in function name"},
- {"callcount", "how many times this is called"},
- {"reccallcount", "how many times this is called recursively"},
- {"totaltime", "total time spent in this call"},
- {"inlinetime", "inline time (not in further subcalls)"},
- {0}
+ {"code", "called code object or built-in function name"},
+ {"callcount", "how many times this is called"},
+ {"reccallcount", "how many times this is called recursively"},
+ {"totaltime", "total time spent in this call"},
+ {"inlinetime", "inline time (not in further subcalls)"},
+ {0}
};
static PyStructSequence_Desc profiler_entry_desc = {
- "_lsprof.profiler_entry", /* name */
- NULL, /* doc */
- profiler_entry_fields,
- 6
+ "_lsprof.profiler_entry", /* name */
+ NULL, /* doc */
+ profiler_entry_fields,
+ 6
};
static PyStructSequence_Desc profiler_subentry_desc = {
- "_lsprof.profiler_subentry", /* name */
- NULL, /* doc */
- profiler_subentry_fields,
- 5
+ "_lsprof.profiler_subentry", /* name */
+ NULL, /* doc */
+ profiler_subentry_fields,
+ 5
};
static int initialized;
@@ -538,70 +538,70 @@ static PyTypeObject StatsSubEntryType;
typedef struct {
- PyObject *list;
- PyObject *sublist;
- double factor;
+ PyObject *list;
+ PyObject *sublist;
+ double factor;
} statscollector_t;
static int statsForSubEntry(rotating_node_t *node, void *arg)
{
- ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
- statscollector_t *collect = (statscollector_t*) arg;
- ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
- int err;
- PyObject *sinfo;
- sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType,
- "((Olldd))",
- entry->userObj,
- sentry->callcount,
- sentry->recursivecallcount,
- collect->factor * sentry->tt,
- collect->factor * sentry->it);
- if (sinfo == NULL)
- return -1;
- err = PyList_Append(collect->sublist, sinfo);
- Py_DECREF(sinfo);
- return err;
+ ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
+ statscollector_t *collect = (statscollector_t*) arg;
+ ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
+ int err;
+ PyObject *sinfo;
+ sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType,
+ "((Olldd))",
+ entry->userObj,
+ sentry->callcount,
+ sentry->recursivecallcount,
+ collect->factor * sentry->tt,
+ collect->factor * sentry->it);
+ if (sinfo == NULL)
+ return -1;
+ err = PyList_Append(collect->sublist, sinfo);
+ Py_DECREF(sinfo);
+ return err;
}
static int statsForEntry(rotating_node_t *node, void *arg)
{
- ProfilerEntry *entry = (ProfilerEntry*) node;
- statscollector_t *collect = (statscollector_t*) arg;
- PyObject *info;
- int err;
- if (entry->callcount == 0)
- return 0; /* skip */
-
- if (entry->calls != EMPTY_ROTATING_TREE) {
- collect->sublist = PyList_New(0);
- if (collect->sublist == NULL)
- return -1;
- if (RotatingTree_Enum(entry->calls,
- statsForSubEntry, collect) != 0) {
- Py_DECREF(collect->sublist);
- return -1;
- }
- }
- else {
- Py_INCREF(Py_None);
- collect->sublist = Py_None;
- }
-
- info = PyObject_CallFunction((PyObject*) &StatsEntryType,
- "((OllddO))",
- entry->userObj,
- entry->callcount,
- entry->recursivecallcount,
- collect->factor * entry->tt,
- collect->factor * entry->it,
- collect->sublist);
- Py_DECREF(collect->sublist);
- if (info == NULL)
- return -1;
- err = PyList_Append(collect->list, info);
- Py_DECREF(info);
- return err;
+ ProfilerEntry *entry = (ProfilerEntry*) node;
+ statscollector_t *collect = (statscollector_t*) arg;
+ PyObject *info;
+ int err;
+ if (entry->callcount == 0)
+ return 0; /* skip */
+
+ if (entry->calls != EMPTY_ROTATING_TREE) {
+ collect->sublist = PyList_New(0);
+ if (collect->sublist == NULL)
+ return -1;
+ if (RotatingTree_Enum(entry->calls,
+ statsForSubEntry, collect) != 0) {
+ Py_DECREF(collect->sublist);
+ return -1;
+ }
+ }
+ else {
+ Py_INCREF(Py_None);
+ collect->sublist = Py_None;
+ }
+
+ info = PyObject_CallFunction((PyObject*) &StatsEntryType,
+ "((OllddO))",
+ entry->userObj,
+ entry->callcount,
+ entry->recursivecallcount,
+ collect->factor * entry->tt,
+ collect->factor * entry->it,
+ collect->sublist);
+ Py_DECREF(collect->sublist);
+ if (info == NULL)
+ return -1;
+ err = PyList_Append(collect->list, info);
+ Py_DECREF(info);
+ return err;
}
PyDoc_STRVAR(getstats_doc, "\
@@ -631,51 +631,51 @@ profiler_subentry objects:\n\
static PyObject*
profiler_getstats(ProfilerObject *pObj, PyObject* noarg)
{
- statscollector_t collect;
- if (pending_exception(pObj))
- return NULL;
- if (!pObj->externalTimer)
- collect.factor = hpTimerUnit();
- else if (pObj->externalTimerUnit > 0.0)
- collect.factor = pObj->externalTimerUnit;
- else
- collect.factor = 1.0 / DOUBLE_TIMER_PRECISION;
- collect.list = PyList_New(0);
- if (collect.list == NULL)
- return NULL;
- if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect)
- != 0) {
- Py_DECREF(collect.list);
- return NULL;
- }
- return collect.list;
+ statscollector_t collect;
+ if (pending_exception(pObj))
+ return NULL;
+ if (!pObj->externalTimer)
+ collect.factor = hpTimerUnit();
+ else if (pObj->externalTimerUnit > 0.0)
+ collect.factor = pObj->externalTimerUnit;
+ else
+ collect.factor = 1.0 / DOUBLE_TIMER_PRECISION;
+ collect.list = PyList_New(0);
+ if (collect.list == NULL)
+ return NULL;
+ if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect)
+ != 0) {
+ Py_DECREF(collect.list);
+ return NULL;
+ }
+ return collect.list;
}
static int
setSubcalls(ProfilerObject *pObj, int nvalue)
{
- if (nvalue == 0)
- pObj->flags &= ~POF_SUBCALLS;
- else if (nvalue > 0)
- pObj->flags |= POF_SUBCALLS;
- return 0;
+ if (nvalue == 0)
+ pObj->flags &= ~POF_SUBCALLS;
+ else if (nvalue > 0)
+ pObj->flags |= POF_SUBCALLS;
+ return 0;
}
static int
setBuiltins(ProfilerObject *pObj, int nvalue)
{
- if (nvalue == 0)
- pObj->flags &= ~POF_BUILTINS;
- else if (nvalue > 0) {
+ if (nvalue == 0)
+ pObj->flags &= ~POF_BUILTINS;
+ else if (nvalue > 0) {
#ifndef PyTrace_C_CALL
- PyErr_SetString(PyExc_ValueError,
- "builtins=True requires Python >= 2.4");
- return -1;
+ PyErr_SetString(PyExc_ValueError,
+ "builtins=True requires Python >= 2.4");
+ return -1;
#else
- pObj->flags |= POF_BUILTINS;
+ pObj->flags |= POF_BUILTINS;
#endif
- }
- return 0;
+ }
+ return 0;
}
PyDoc_STRVAR(enable_doc, "\
@@ -691,33 +691,33 @@ built-in functions separately from their caller.\n\
static PyObject*
profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds)
{
- int subcalls = -1;
- int builtins = -1;
- static char *kwlist[] = {"subcalls", "builtins", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable",
- kwlist, &subcalls, &builtins))
- return NULL;
- if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0)
- return NULL;
- PyEval_SetProfile(profiler_callback, (PyObject*)self);
- self->flags |= POF_ENABLED;
- Py_INCREF(Py_None);
- return Py_None;
+ int subcalls = -1;
+ int builtins = -1;
+ static char *kwlist[] = {"subcalls", "builtins", 0};
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable",
+ kwlist, &subcalls, &builtins))
+ return NULL;
+ if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0)
+ return NULL;
+ PyEval_SetProfile(profiler_callback, (PyObject*)self);
+ self->flags |= POF_ENABLED;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
flush_unmatched(ProfilerObject *pObj)
{
- while (pObj->currentProfilerContext) {
- ProfilerContext *pContext = pObj->currentProfilerContext;
- ProfilerEntry *profEntry= pContext->ctxEntry;
- if (profEntry)
- Stop(pObj, pContext, profEntry);
- else
- pObj->currentProfilerContext = pContext->previous;
- if (pContext)
- free(pContext);
- }
+ while (pObj->currentProfilerContext) {
+ ProfilerContext *pContext = pObj->currentProfilerContext;
+ ProfilerEntry *profEntry= pContext->ctxEntry;
+ if (profEntry)
+ Stop(pObj, pContext, profEntry);
+ else
+ pObj->currentProfilerContext = pContext->previous;
+ if (pContext)
+ free(pContext);
+ }
}
@@ -730,13 +730,13 @@ Stop collecting profiling information.\n\
static PyObject*
profiler_disable(ProfilerObject *self, PyObject* noarg)
{
- self->flags &= ~POF_ENABLED;
- PyEval_SetProfile(NULL, NULL);
- flush_unmatched(self);
- if (pending_exception(self))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ self->flags &= ~POF_ENABLED;
+ PyEval_SetProfile(NULL, NULL);
+ flush_unmatched(self);
+ if (pending_exception(self))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(clear_doc, "\
@@ -748,62 +748,62 @@ Clear all profiling information collected so far.\n\
static PyObject*
profiler_clear(ProfilerObject *pObj, PyObject* noarg)
{
- clearEntries(pObj);
- Py_INCREF(Py_None);
- return Py_None;
+ clearEntries(pObj);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
profiler_dealloc(ProfilerObject *op)
{
- if (op->flags & POF_ENABLED)
- PyEval_SetProfile(NULL, NULL);
- flush_unmatched(op);
- clearEntries(op);
- Py_XDECREF(op->externalTimer);
- Py_TYPE(op)->tp_free(op);
+ if (op->flags & POF_ENABLED)
+ PyEval_SetProfile(NULL, NULL);
+ flush_unmatched(op);
+ clearEntries(op);
+ Py_XDECREF(op->externalTimer);
+ Py_TYPE(op)->tp_free(op);
}
static int
profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw)
{
- PyObject *o;
- PyObject *timer = NULL;
- double timeunit = 0.0;
- int subcalls = 1;
+ PyObject *o;
+ PyObject *timer = NULL;
+ double timeunit = 0.0;
+ int subcalls = 1;
#ifdef PyTrace_C_CALL
- int builtins = 1;
+ int builtins = 1;
#else
- int builtins = 0;
+ int builtins = 0;
#endif
- static char *kwlist[] = {"timer", "timeunit",
- "subcalls", "builtins", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist,
- &timer, &timeunit,
- &subcalls, &builtins))
- return -1;
-
- if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
- return -1;
- o = pObj->externalTimer;
- pObj->externalTimer = timer;
- Py_XINCREF(timer);
- Py_XDECREF(o);
- pObj->externalTimerUnit = timeunit;
- return 0;
+ static char *kwlist[] = {"timer", "timeunit",
+ "subcalls", "builtins", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist,
+ &timer, &timeunit,
+ &subcalls, &builtins))
+ return -1;
+
+ if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
+ return -1;
+ o = pObj->externalTimer;
+ pObj->externalTimer = timer;
+ Py_XINCREF(timer);
+ Py_XDECREF(o);
+ pObj->externalTimerUnit = timeunit;
+ return 0;
}
static PyMethodDef profiler_methods[] = {
- {"getstats", (PyCFunction)profiler_getstats,
- METH_NOARGS, getstats_doc},
- {"enable", (PyCFunction)profiler_enable,
- METH_VARARGS | METH_KEYWORDS, enable_doc},
- {"disable", (PyCFunction)profiler_disable,
- METH_NOARGS, disable_doc},
- {"clear", (PyCFunction)profiler_clear,
- METH_NOARGS, clear_doc},
- {NULL, NULL}
+ {"getstats", (PyCFunction)profiler_getstats,
+ METH_NOARGS, getstats_doc},
+ {"enable", (PyCFunction)profiler_enable,
+ METH_VARARGS | METH_KEYWORDS, enable_doc},
+ {"disable", (PyCFunction)profiler_disable,
+ METH_NOARGS, disable_doc},
+ {"clear", (PyCFunction)profiler_clear,
+ METH_NOARGS, clear_doc},
+ {NULL, NULL}
};
PyDoc_STRVAR(profiler_doc, "\
@@ -817,76 +817,76 @@ Profiler(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\n\
");
statichere PyTypeObject PyProfiler_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "_lsprof.Profiler", /* tp_name */
- 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 */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- profiler_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 */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)profiler_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "_lsprof.Profiler", /* tp_name */
+ 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 */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ profiler_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 */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)profiler_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_Del, /* tp_free */
};
static PyMethodDef moduleMethods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
PyMODINIT_FUNC
init_lsprof(void)
{
- PyObject *module, *d;
- module = Py_InitModule3("_lsprof", moduleMethods, "Fast profiler");
- if (module == NULL)
- return;
- d = PyModule_GetDict(module);
- if (PyType_Ready(&PyProfiler_Type) < 0)
- return;
- PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
-
- if (!initialized) {
- PyStructSequence_InitType(&StatsEntryType,
- &profiler_entry_desc);
- PyStructSequence_InitType(&StatsSubEntryType,
- &profiler_subentry_desc);
- }
- Py_INCREF((PyObject*) &StatsEntryType);
- Py_INCREF((PyObject*) &StatsSubEntryType);
- PyModule_AddObject(module, "profiler_entry",
- (PyObject*) &StatsEntryType);
- PyModule_AddObject(module, "profiler_subentry",
- (PyObject*) &StatsSubEntryType);
- empty_tuple = PyTuple_New(0);
- initialized = 1;
+ PyObject *module, *d;
+ module = Py_InitModule3("_lsprof", moduleMethods, "Fast profiler");
+ if (module == NULL)
+ return;
+ d = PyModule_GetDict(module);
+ if (PyType_Ready(&PyProfiler_Type) < 0)
+ return;
+ PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
+
+ if (!initialized) {
+ PyStructSequence_InitType(&StatsEntryType,
+ &profiler_entry_desc);
+ PyStructSequence_InitType(&StatsSubEntryType,
+ &profiler_subentry_desc);
+ }
+ Py_INCREF((PyObject*) &StatsEntryType);
+ Py_INCREF((PyObject*) &StatsSubEntryType);
+ PyModule_AddObject(module, "profiler_entry",
+ (PyObject*) &StatsEntryType);
+ PyModule_AddObject(module, "profiler_subentry",
+ (PyObject*) &StatsSubEntryType);
+ empty_tuple = PyTuple_New(0);
+ initialized = 1;
}
diff --git a/Modules/_math.c b/Modules/_math.c
index 995d1c0..b5d8b45 100644
--- a/Modules/_math.c
+++ b/Modules/_math.c
@@ -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);
-
- 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);
-
+{
+ 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);
+
}
/* 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;
-
- if (Py_IS_NAN(x)) {
- return x+x;
- }
- absx = fabs(x);
- if (absx >= 1.) { /* |x| >= 1 */
- errno = EDOM;
+ double absx;
+ double t;
+
+ 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);
}
}
diff --git a/Modules/_multiprocessing/connection.h b/Modules/_multiprocessing/connection.h
index 4443bdc..1d97bd4 100644
--- a/Modules/_multiprocessing/connection.h
+++ b/Modules/_multiprocessing/connection.h
@@ -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;
-
- static char *kwlist[] = {"handle", "readable", "writable", 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 (!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->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);
-
- return (PyObject*)self;
+ ConnectionObject *self;
+ HANDLE handle;
+ BOOL readable = TRUE, writable = TRUE;
+
+ static char *kwlist[] = {"handle", "readable", "writable", 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 (!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->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);
+
+ return (PyObject*)self;
}
static void
connection_dealloc(ConnectionObject* 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->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);
}
/*
@@ -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;
-
- if (!PyArg_ParseTuple(args, F_RBUFFER "#|" F_PY_SSIZE_T F_PY_SSIZE_T,
- &buffer, &length, &offset, &size))
- return NULL;
-
- 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 (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);
-
- if (res < 0) {
- if (PyErr_Occurred())
- return NULL;
- else
- return mp_SetError(PyExc_IOError, res);
- }
-
- Py_RETURN_NONE;
+ 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;
+
+ 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 (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);
+
+ if (res < 0) {
+ if (PyErr_Occurred())
+ return NULL;
+ else
+ return mp_SetError(PyExc_IOError, res);
+ }
+
+ 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;
-
- if (!PyArg_ParseTuple(args, "|" F_PY_SSIZE_T, &maxlength))
- return NULL;
-
- CHECK_READABLE(self);
-
- if (maxlength < 0) {
- PyErr_SetString(PyExc_ValueError, "maxlength < 0");
- return NULL;
- }
-
- 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);
- }
- }
-
- return result;
+ 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;
+
+ CHECK_READABLE(self);
+
+ if (maxlength < 0) {
+ PyErr_SetString(PyExc_ValueError, "maxlength < 0");
+ return NULL;
+ }
+
+ 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);
+ }
+ }
+
+ 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;
-
- CHECK_READABLE(self);
-
- if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
- &pbuf, &offset))
- return NULL;
-
- buffer = pbuf.buf;
- length = pbuf.len;
-
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError, "negative offset");
- 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);
-
- 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;
- }
- }
+ char *freeme = NULL, *buffer = NULL;
+ Py_ssize_t res, length, offset = 0;
+ PyObject *result = NULL;
+ Py_buffer pbuf;
+
+ CHECK_READABLE(self);
+
+ if (!PyArg_ParseTuple(args, "w*|" F_PY_SSIZE_T,
+ &pbuf, &offset))
+ return NULL;
+
+ buffer = pbuf.buf;
+ length = pbuf.len;
+
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError, "negative offset");
+ 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);
+
+ 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 @@ _error:
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;
-
- CHECK_READABLE(self);
-
- 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 (temp)
- result = PyObject_CallFunctionObjArgs(pickle_loads,
- temp, NULL);
- Py_XDECREF(temp);
- return result;
+ char *freeme = NULL;
+ Py_ssize_t res;
+ PyObject *temp = NULL, *result = NULL;
+
+ CHECK_READABLE(self);
+
+ 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 (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;
-
- CHECK_READABLE(self);
-
- 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;
- }
-
- 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);
- }
+ PyObject *timeout_obj = NULL;
+ double timeout = 0.0;
+ int res;
+
+ CHECK_READABLE(self);
+
+ 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;
+ }
+
+ 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);
+ }
}
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;
- }
-
- Py_RETURN_NONE;
+ 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;
}
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", (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"},
-
- {NULL} /* Sentinel */
+ {"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"},
+
+ {"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 */
};
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 */
diff --git a/Modules/_multiprocessing/multiprocessing.c b/Modules/_multiprocessing/multiprocessing.c
index e867030..fde7c56 100644
--- a/Modules/_multiprocessing/multiprocessing.c
+++ b/Modules/_multiprocessing/multiprocessing.c
@@ -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;
-
- 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;
-
- Py_BEGIN_ALLOW_THREADS
- res = sendmsg(conn, &msg, 0);
- Py_END_ALLOW_THREADS
-
- if (res < 0)
- return PyErr_SetFromErrno(PyExc_OSError);
- Py_RETURN_NONE;
+ 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;
+
+ 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
+
+ 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;
-
- 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;
-
- Py_BEGIN_ALLOW_THREADS
- res = recvmsg(conn, &msg, 0);
- Py_END_ALLOW_THREADS
-
- if (res < 0)
- return PyErr_SetFromErrno(PyExc_OSError);
-
- fd = *(int*)CMSG_DATA(cmsg);
- return Py_BuildValue("i", fd);
+ 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;
+
+ 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
+
+ if (res < 0)
+ return PyErr_SetFromErrno(PyExc_OSError);
+
+ 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;
-
- /* 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 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);
-
-#if defined(MS_WINDOWS) || \
+ PyObject *module, *temp, *value;
+
+ /* 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 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);
+
+#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);
-
- /* 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;
- }
+ /* 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 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;
}
diff --git a/Modules/_multiprocessing/multiprocessing.h b/Modules/_multiprocessing/multiprocessing.h
index 3dd0199..c149634 100644
--- a/Modules/_multiprocessing/multiprocessing.h
+++ b/Modules/_multiprocessing/multiprocessing.h
@@ -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;
/*
diff --git a/Modules/_multiprocessing/pipe_connection.c b/Modules/_multiprocessing/pipe_connection.c
index 980f760..05dde0c 100644
--- a/Modules/_multiprocessing/pipe_connection.c
+++ b/Modules/_multiprocessing/pipe_connection.c
@@ -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;
-
- 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;
- }
-
- 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;
-
- *newbuffer = PyMem_Malloc(full_length);
- if (*newbuffer == NULL)
- return MP_MEMORY_ERROR;
-
- 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;
- }
+ 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;
+
+ 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;
+
+ 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;
+
+ 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;
+ }
}
/*
@@ -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;
-
- if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
- return MP_STANDARD_ERROR;
-
- 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);
-
- 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;
-
- if (!block) {
- difference = deadline - GetTickCount();
- if (difference < 0)
- return FALSE;
- if ((int)delay > difference)
- delay = difference;
- }
-
- if (delay > 20)
- delay = 20;
-
- Sleep(delay);
-
- /* check for signals */
- Py_BLOCK_THREADS
- res = PyErr_CheckSignals();
- Py_UNBLOCK_THREADS
-
- if (res)
- return MP_EXCEPTION_HAS_BEEN_SET;
- }
+ DWORD bytes, deadline, delay;
+ int difference, res;
+ BOOL block = FALSE;
+
+ if (!PeekNamedPipe(conn->handle, NULL, 0, NULL, &bytes, NULL))
+ return MP_STANDARD_ERROR;
+
+ 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);
+
+ 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;
+
+ if (!block) {
+ difference = deadline - GetTickCount();
+ if (difference < 0)
+ return FALSE;
+ if ((int)delay > difference)
+ delay = difference;
+ }
+
+ if (delay > 20)
+ delay = 20;
+
+ Sleep(delay);
+
+ /* check for signals */
+ Py_BLOCK_THREADS
+ res = PyErr_CheckSignals();
+ Py_UNBLOCK_THREADS
+
+ if (res)
+ return MP_EXCEPTION_HAS_BEEN_SET;
+ }
}
/*
diff --git a/Modules/_multiprocessing/semaphore.c b/Modules/_multiprocessing/semaphore.c
index d282b77..1dfd08e 100644
--- a/Modules/_multiprocessing/semaphore.c
+++ b/Modules/_multiprocessing/semaphore.c
@@ -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;
-
- 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;
- }
+ 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;
+ }
}
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;
-
- static char *kwlist[] = {"block", "timeout", 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;
- }
-
- /* 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;
- }
+ int blocking = 1;
+ double timeout;
+ PyObject *timeout_obj = Py_None;
+ DWORD res, full_msecs, msecs, start, ticks;
+
+ static char *kwlist[] = {"block", "timeout", 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;
+ }
+
+ /* 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 (!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;
+ 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);
+ }
+ }
+
+ --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;
-
- 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;
-
- /* 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;
- }
-
- /* 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;
-
- /* 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
-
- if (res) {
- errno = EINTR;
- return MP_EXCEPTION_HAS_BEEN_SET;
- }
- }
+ 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;
+
+ 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;
+
+ /* 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);
+
+ /* 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;
+
+ /* check for signals */
+ Py_BLOCK_THREADS
+ res = PyErr_CheckSignals();
+ Py_UNBLOCK_THREADS
+
+ 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;
-
- static char *kwlist[] = {"block", "timeout", 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 (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;
- }
-
- 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);
- }
-
- ++self->count;
- self->last_tid = PyThread_get_thread_ident();
-
- Py_RETURN_TRUE;
+ 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};
+
+ 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 (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;
+ }
+
+ 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);
+ }
+
+ ++self->count;
+ self->last_tid = PyThread_get_thread_ident();
+
+ 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;
-
- /* 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;
- }
+ 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;
+ }
#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;
-
- 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;
+ 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;
}
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,
};
diff --git a/Modules/_multiprocessing/socket_connection.c b/Modules/_multiprocessing/socket_connection.c
index ad4005b..7ebf338 100644
--- a/Modules/_multiprocessing/socket_connection.c
+++ b/Modules/_multiprocessing/socket_connection.c
@@ -25,45 +25,45 @@
static Py_ssize_t
_conn_sendall(HANDLE h, char *string, size_t length)
{
- 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;
- }
-
- return MP_SUCCESS;
+ 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;
+ }
+
+ 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;
-
- 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;
+ 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;
+ }
+
+ 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;
-
- 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;
-
- 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;
+ 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;
+
+ *(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;
+
+ 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;
-
- *newbuffer = NULL;
-
- 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;
-
- 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;
- }
+ int res;
+ UINT32 ulength;
+
+ *newbuffer = NULL;
+
+ 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;
+
+ 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;
-
- /*
- * 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);
-
- 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;
- }
+ 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
+
+ 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 (res < 0) {
+ return MP_SOCKET_ERROR;
+ } else if (FD_ISSET(conn->handle, &rfds)) {
+ return TRUE;
+ } else {
+ assert(res == 0);
+ return FALSE;
+ }
}
/*
diff --git a/Modules/_multiprocessing/win32_functions.c b/Modules/_multiprocessing/win32_functions.c
index 5c6c817..1666aa9 100644
--- a/Modules/_multiprocessing/win32_functions.c
+++ b/Modules/_multiprocessing/win32_functions.c
@@ -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;
-
- 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
-
- if (handle == INVALID_HANDLE_VALUE)
- return PyErr_SetFromWindowsErr(0);
-
- return Py_BuildValue(F_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;
+
+ 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);
+
+ 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;
-
- 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
-
- if (handle == INVALID_HANDLE_VALUE)
- return PyErr_SetFromWindowsErr(0);
-
- return Py_BuildValue(F_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;
+
+ 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);
+
+ 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;
-
- if (!PyArg_ParseTuple(args, F_HANDLE "OOO",
- &hNamedPipe, &oArgs[0], &oArgs[1], &oArgs[2]))
- return NULL;
-
- 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];
- }
- }
-
- if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
- return PyErr_SetFromWindowsErr(0);
-
- Py_RETURN_NONE;
+ 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;
+
+ 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];
+ }
+ }
+
+ if (!SetNamedPipeHandleState(hNamedPipe, pArgs[0], pArgs[1], pArgs[2]))
+ return PyErr_SetFromWindowsErr(0);
+
+ 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);
-
- 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);
-
- return (PyObject*)&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("i", NULL);
+
+ return (PyObject*)&Win32Type;
}
diff --git a/Modules/_randommodule.c b/Modules/_randommodule.c
index b45f243..2d81daf 100644
--- a/Modules/_randommodule.c
+++ b/Modules/_randommodule.c
@@ -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;
-
- 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];
-
- self->index = 0;
- }
+ 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;
+
+ 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;
+ }
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;
-
- 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;
+ 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;
}
/* 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;
-
- 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; }
- }
+ 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[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 *arg = NULL;
-
- if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
- return NULL;
-
- 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;
-
- /* 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;
-
- 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);
+ 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;
+
+ if (!PyArg_UnpackTuple(args, "seed", 0, 1, &arg))
+ return NULL;
+
+ 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;
+
+ /* 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;
+
+ 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);
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;
-
- 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;
+ 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;
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;
-
- 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 */
- }
-
- 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;
+ 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;
+ }
+
+ 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;
+
+ 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;
-
- 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;
- }
-
- for (i = 0; i < N; i++)
- mt[i] += i+1;
-
- self->index = N;
- Py_INCREF(Py_None);
- return Py_None;
+ 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;
+ }
+
+ 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;
+
+ 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;
-
- 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;
- }
-
- 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);
- }
-
- /* little endian order to match bytearray assignment order */
- result = _PyLong_FromByteArray(bytearray, bytes, 1, 0);
- PyMem_Free(bytearray);
- return result;
+ int k, i, bytes;
+ unsigned long r;
+ unsigned char *bytearray;
+ PyObject *result;
+
+ 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;
+ }
+
+ 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);
+ }
+
+ /* 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;
-
- 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;
+ RandomObject *self;
+ PyObject *tmp;
+
+ 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;
}
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;
-
- 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);
+ 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);
}
diff --git a/Modules/_struct.c b/Modules/_struct.c
index b6be5b6..1904e9e 100644
--- a/Modules/_struct.c
+++ b/Modules/_struct.c
@@ -20,35 +20,35 @@ typedef int Py_ssize_t;
/* warning messages */
#define FLOAT_COERCE_WARN "integer argument expected, got float"
#define NON_INTEGER_WARN "integer argument expected, got non-integer " \
- "(implicit conversion using __int__ is deprecated)"
+ "(implicit conversion using __int__ is deprecated)"
/* The translation function for each format character is table driven */
typedef struct _formatdef {
- char format;
- Py_ssize_t size;
- Py_ssize_t alignment;
- PyObject* (*unpack)(const char *,
- const struct _formatdef *);
- int (*pack)(char *, PyObject *,
- const struct _formatdef *);
+ char format;
+ Py_ssize_t size;
+ Py_ssize_t alignment;
+ PyObject* (*unpack)(const char *,
+ const struct _formatdef *);
+ int (*pack)(char *, PyObject *,
+ const struct _formatdef *);
} formatdef;
typedef struct _formatcode {
- const struct _formatdef *fmtdef;
- Py_ssize_t offset;
- Py_ssize_t size;
+ const struct _formatdef *fmtdef;
+ Py_ssize_t offset;
+ Py_ssize_t size;
} formatcode;
/* Struct object interface */
typedef struct {
- PyObject_HEAD
- Py_ssize_t s_size;
- Py_ssize_t s_len;
- formatcode *s_codes;
- PyObject *s_format;
- PyObject *weakreflist; /* List of weak references */
+ PyObject_HEAD
+ Py_ssize_t s_size;
+ Py_ssize_t s_len;
+ formatcode *s_codes;
+ PyObject *s_format;
+ PyObject *weakreflist; /* List of weak references */
} PyStructObject;
@@ -107,84 +107,84 @@ static char *integer_codes = "bBhHiIlLqQ";
static PyObject *
get_pylong(PyObject *v)
{
- PyObject *r, *w;
- int converted = 0;
- assert(v != NULL);
- if (!PyInt_Check(v) && !PyLong_Check(v)) {
- PyNumberMethods *m;
- /* Not an integer; first try to use __index__ to
- convert to an integer. If the __index__ method
- doesn't exist, or raises a TypeError, try __int__.
- Use of the latter is deprecated, and will fail in
- Python 3.x. */
-
- m = Py_TYPE(v)->tp_as_number;
- if (PyIndex_Check(v)) {
- w = PyNumber_Index(v);
- if (w != NULL) {
- v = w;
- /* successfully converted to an integer */
- converted = 1;
- }
- else if (PyErr_ExceptionMatches(PyExc_TypeError)) {
- PyErr_Clear();
- }
- else
- return NULL;
- }
- if (!converted && m != NULL && m->nb_int != NULL) {
- /* Special case warning message for floats, for
- backwards compatibility. */
- if (PyFloat_Check(v)) {
- if (PyErr_WarnEx(
- PyExc_DeprecationWarning,
- FLOAT_COERCE_WARN, 1))
- return NULL;
- }
- else {
- if (PyErr_WarnEx(
- PyExc_DeprecationWarning,
- NON_INTEGER_WARN, 1))
- return NULL;
- }
- v = m->nb_int(v);
- if (v == NULL)
- return NULL;
- if (!PyInt_Check(v) && !PyLong_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "__int__ method returned "
- "non-integer");
- return NULL;
- }
- converted = 1;
- }
- if (!converted) {
- PyErr_SetString(StructError,
- "cannot convert argument "
- "to integer");
- return NULL;
- }
- }
- else
- /* Ensure we own a reference to v. */
- Py_INCREF(v);
-
- assert(PyInt_Check(v) || PyLong_Check(v));
- if (PyInt_Check(v)) {
- r = PyLong_FromLong(PyInt_AS_LONG(v));
- Py_DECREF(v);
- }
- else if (PyLong_Check(v)) {
- assert(PyLong_Check(v));
- r = v;
- }
- else {
- r = NULL; /* silence compiler warning about
- possibly uninitialized variable */
- assert(0); /* shouldn't ever get here */
- }
-
- return r;
+ PyObject *r, *w;
+ int converted = 0;
+ assert(v != NULL);
+ if (!PyInt_Check(v) && !PyLong_Check(v)) {
+ PyNumberMethods *m;
+ /* Not an integer; first try to use __index__ to
+ convert to an integer. If the __index__ method
+ doesn't exist, or raises a TypeError, try __int__.
+ Use of the latter is deprecated, and will fail in
+ Python 3.x. */
+
+ m = Py_TYPE(v)->tp_as_number;
+ if (PyIndex_Check(v)) {
+ w = PyNumber_Index(v);
+ if (w != NULL) {
+ v = w;
+ /* successfully converted to an integer */
+ converted = 1;
+ }
+ else if (PyErr_ExceptionMatches(PyExc_TypeError)) {
+ PyErr_Clear();
+ }
+ else
+ return NULL;
+ }
+ if (!converted && m != NULL && m->nb_int != NULL) {
+ /* Special case warning message for floats, for
+ backwards compatibility. */
+ if (PyFloat_Check(v)) {
+ if (PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ FLOAT_COERCE_WARN, 1))
+ return NULL;
+ }
+ else {
+ if (PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ NON_INTEGER_WARN, 1))
+ return NULL;
+ }
+ v = m->nb_int(v);
+ if (v == NULL)
+ return NULL;
+ if (!PyInt_Check(v) && !PyLong_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__int__ method returned "
+ "non-integer");
+ return NULL;
+ }
+ converted = 1;
+ }
+ if (!converted) {
+ PyErr_SetString(StructError,
+ "cannot convert argument "
+ "to integer");
+ return NULL;
+ }
+ }
+ else
+ /* Ensure we own a reference to v. */
+ Py_INCREF(v);
+
+ assert(PyInt_Check(v) || PyLong_Check(v));
+ if (PyInt_Check(v)) {
+ r = PyLong_FromLong(PyInt_AS_LONG(v));
+ Py_DECREF(v);
+ }
+ else if (PyLong_Check(v)) {
+ assert(PyLong_Check(v));
+ r = v;
+ }
+ else {
+ r = NULL; /* silence compiler warning about
+ possibly uninitialized variable */
+ assert(0); /* shouldn't ever get here */
+ }
+
+ return r;
}
/* Helper to convert a Python object to a C long. Sets an exception
@@ -194,18 +194,18 @@ get_pylong(PyObject *v)
static int
get_long(PyObject *v, long *p)
{
- long x;
+ long x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsLong(v);
- Py_DECREF(v);
- if (x == (long)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsLong(v);
+ Py_DECREF(v);
+ if (x == (long)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling unsigned long */
@@ -213,18 +213,18 @@ get_long(PyObject *v, long *p)
static int
get_ulong(PyObject *v, unsigned long *p)
{
- unsigned long x;
+ unsigned long x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsUnsignedLong(v);
- Py_DECREF(v);
- if (x == (unsigned long)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsUnsignedLong(v);
+ Py_DECREF(v);
+ if (x == (unsigned long)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -234,18 +234,18 @@ get_ulong(PyObject *v, unsigned long *p)
static int
get_longlong(PyObject *v, PY_LONG_LONG *p)
{
- PY_LONG_LONG x;
+ PY_LONG_LONG x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsLongLong(v);
- Py_DECREF(v);
- if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsLongLong(v);
+ Py_DECREF(v);
+ if (x == (PY_LONG_LONG)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
/* Same, but handling native unsigned long long. */
@@ -253,18 +253,18 @@ get_longlong(PyObject *v, PY_LONG_LONG *p)
static int
get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
{
- unsigned PY_LONG_LONG x;
+ unsigned PY_LONG_LONG x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsUnsignedLongLong(v);
- Py_DECREF(v);
- if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
- return -1;
- *p = x;
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsUnsignedLongLong(v);
+ Py_DECREF(v);
+ if (x == (unsigned PY_LONG_LONG)-1 && PyErr_Occurred())
+ return -1;
+ *p = x;
+ return 0;
}
#endif
@@ -273,56 +273,56 @@ get_ulonglong(PyObject *v, unsigned PY_LONG_LONG *p)
static PyObject *
unpack_float(const char *p, /* start of 4-byte string */
- int le) /* true for little-endian, false for big-endian */
+ int le) /* true for little-endian, false for big-endian */
{
- double x;
+ double x;
- x = _PyFloat_Unpack4((unsigned char *)p, le);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x);
+ x = _PyFloat_Unpack4((unsigned char *)p, le);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x);
}
static PyObject *
unpack_double(const char *p, /* start of 8-byte string */
- int le) /* true for little-endian, false for big-endian */
+ int le) /* true for little-endian, false for big-endian */
{
- double x;
+ double x;
- x = _PyFloat_Unpack8((unsigned char *)p, le);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x);
+ x = _PyFloat_Unpack8((unsigned char *)p, le);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x);
}
/* Helper to format the range error exceptions */
static int
_range_error(const formatdef *f, int is_unsigned)
{
- /* ulargest is the largest unsigned value with f->size bytes.
- * Note that the simpler:
- * ((size_t)1 << (f->size * 8)) - 1
- * doesn't work when f->size == sizeof(size_t) because C doesn't
- * define what happens when a left shift count is >= the number of
- * bits in the integer being shifted; e.g., on some boxes it doesn't
- * shift at all when they're equal.
- */
- const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
- assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
- if (is_unsigned)
- PyErr_Format(StructError,
- "'%c' format requires 0 <= number <= %zu",
- f->format,
- ulargest);
- else {
- const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
- PyErr_Format(StructError,
- "'%c' format requires %zd <= number <= %zd",
- f->format,
- ~ largest,
- largest);
- }
- return -1;
+ /* ulargest is the largest unsigned value with f->size bytes.
+ * Note that the simpler:
+ * ((size_t)1 << (f->size * 8)) - 1
+ * doesn't work when f->size == sizeof(size_t) because C doesn't
+ * define what happens when a left shift count is >= the number of
+ * bits in the integer being shifted; e.g., on some boxes it doesn't
+ * shift at all when they're equal.
+ */
+ const size_t ulargest = (size_t)-1 >> ((SIZEOF_SIZE_T - f->size)*8);
+ assert(f->size >= 1 && f->size <= SIZEOF_SIZE_T);
+ if (is_unsigned)
+ PyErr_Format(StructError,
+ "'%c' format requires 0 <= number <= %zu",
+ f->format,
+ ulargest);
+ else {
+ const Py_ssize_t largest = (Py_ssize_t)(ulargest >> 1);
+ PyErr_Format(StructError,
+ "'%c' format requires %zd <= number <= %zd",
+ f->format,
+ ~ largest,
+ largest);
+ }
+ return -1;
}
@@ -349,75 +349,75 @@ _range_error(const formatdef *f, int is_unsigned)
static PyObject *
nu_char(const char *p, const formatdef *f)
{
- return PyString_FromStringAndSize(p, 1);
+ return PyString_FromStringAndSize(p, 1);
}
static PyObject *
nu_byte(const char *p, const formatdef *f)
{
- return PyInt_FromLong((long) *(signed char *)p);
+ return PyInt_FromLong((long) *(signed char *)p);
}
static PyObject *
nu_ubyte(const char *p, const formatdef *f)
{
- return PyInt_FromLong((long) *(unsigned char *)p);
+ return PyInt_FromLong((long) *(unsigned char *)p);
}
static PyObject *
nu_short(const char *p, const formatdef *f)
{
- short x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong((long)x);
+ short x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_FromLong((long)x);
}
static PyObject *
nu_ushort(const char *p, const formatdef *f)
{
- unsigned short x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong((long)x);
+ unsigned short x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_FromLong((long)x);
}
static PyObject *
nu_int(const char *p, const formatdef *f)
{
- int x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong((long)x);
+ int x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_FromLong((long)x);
}
static PyObject *
nu_uint(const char *p, const formatdef *f)
{
- unsigned int x;
- memcpy((char *)&x, p, sizeof x);
+ unsigned int x;
+ memcpy((char *)&x, p, sizeof x);
#if (SIZEOF_LONG > SIZEOF_INT)
- return PyInt_FromLong((long)x);
+ return PyInt_FromLong((long)x);
#else
- if (x <= ((unsigned int)LONG_MAX))
- return PyInt_FromLong((long)x);
- return PyLong_FromUnsignedLong((unsigned long)x);
+ if (x <= ((unsigned int)LONG_MAX))
+ return PyInt_FromLong((long)x);
+ return PyLong_FromUnsignedLong((unsigned long)x);
#endif
}
static PyObject *
nu_long(const char *p, const formatdef *f)
{
- long x;
- memcpy((char *)&x, p, sizeof x);
- return PyInt_FromLong(x);
+ long x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyInt_FromLong(x);
}
static PyObject *
nu_ulong(const char *p, const formatdef *f)
{
- unsigned long x;
- memcpy((char *)&x, p, sizeof x);
- if (x <= LONG_MAX)
- return PyInt_FromLong((long)x);
- return PyLong_FromUnsignedLong(x);
+ unsigned long x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong((long)x);
+ return PyLong_FromUnsignedLong(x);
}
/* Native mode doesn't support q or Q unless the platform C supports
@@ -428,21 +428,21 @@ nu_ulong(const char *p, const formatdef *f)
static PyObject *
nu_longlong(const char *p, const formatdef *f)
{
- PY_LONG_LONG x;
- memcpy((char *)&x, p, sizeof x);
- if (x >= LONG_MIN && x <= LONG_MAX)
- return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
- return PyLong_FromLongLong(x);
+ PY_LONG_LONG x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x >= LONG_MIN && x <= LONG_MAX)
+ return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
+ return PyLong_FromLongLong(x);
}
static PyObject *
nu_ulonglong(const char *p, const formatdef *f)
{
- unsigned PY_LONG_LONG x;
- memcpy((char *)&x, p, sizeof x);
- if (x <= LONG_MAX)
- return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
- return PyLong_FromUnsignedLongLong(x);
+ unsigned PY_LONG_LONG x;
+ memcpy((char *)&x, p, sizeof x);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
}
#endif
@@ -450,163 +450,163 @@ nu_ulonglong(const char *p, const formatdef *f)
static PyObject *
nu_bool(const char *p, const formatdef *f)
{
- BOOL_TYPE x;
- memcpy((char *)&x, p, sizeof x);
- return PyBool_FromLong(x != 0);
+ BOOL_TYPE x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyBool_FromLong(x != 0);
}
static PyObject *
nu_float(const char *p, const formatdef *f)
{
- float x;
- memcpy((char *)&x, p, sizeof x);
- return PyFloat_FromDouble((double)x);
+ float x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyFloat_FromDouble((double)x);
}
static PyObject *
nu_double(const char *p, const formatdef *f)
{
- double x;
- memcpy((char *)&x, p, sizeof x);
- return PyFloat_FromDouble(x);
+ double x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyFloat_FromDouble(x);
}
static PyObject *
nu_void_p(const char *p, const formatdef *f)
{
- void *x;
- memcpy((char *)&x, p, sizeof x);
- return PyLong_FromVoidPtr(x);
+ void *x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyLong_FromVoidPtr(x);
}
static int
np_byte(char *p, PyObject *v, const formatdef *f)
{
- long x;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < -128 || x > 127){
- PyErr_SetString(StructError,
- "byte format requires -128 <= number <= 127");
- return -1;
- }
- *p = (char)x;
- return 0;
+ long x;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < -128 || x > 127){
+ PyErr_SetString(StructError,
+ "byte format requires -128 <= number <= 127");
+ return -1;
+ }
+ *p = (char)x;
+ return 0;
}
static int
np_ubyte(char *p, PyObject *v, const formatdef *f)
{
- long x;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < 0 || x > 255){
- PyErr_SetString(StructError,
- "ubyte format requires 0 <= number <= 255");
- return -1;
- }
- *p = (char)x;
- return 0;
+ long x;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < 0 || x > 255){
+ PyErr_SetString(StructError,
+ "ubyte format requires 0 <= number <= 255");
+ return -1;
+ }
+ *p = (char)x;
+ return 0;
}
static int
np_char(char *p, PyObject *v, const formatdef *f)
{
- if (!PyString_Check(v) || PyString_Size(v) != 1) {
- PyErr_SetString(StructError,
- "char format require string of length 1");
- return -1;
- }
- *p = *PyString_AsString(v);
- return 0;
+ if (!PyString_Check(v) || PyString_Size(v) != 1) {
+ PyErr_SetString(StructError,
+ "char format require string of length 1");
+ return -1;
+ }
+ *p = *PyString_AsString(v);
+ return 0;
}
static int
np_short(char *p, PyObject *v, const formatdef *f)
{
- long x;
- short y;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < SHRT_MIN || x > SHRT_MAX){
- PyErr_SetString(StructError,
- "short format requires " STRINGIFY(SHRT_MIN)
- " <= number <= " STRINGIFY(SHRT_MAX));
- return -1;
- }
- y = (short)x;
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ long x;
+ short y;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < SHRT_MIN || x > SHRT_MAX){
+ PyErr_SetString(StructError,
+ "short format requires " STRINGIFY(SHRT_MIN)
+ " <= number <= " STRINGIFY(SHRT_MAX));
+ return -1;
+ }
+ y = (short)x;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_ushort(char *p, PyObject *v, const formatdef *f)
{
- long x;
- unsigned short y;
- if (get_long(v, &x) < 0)
- return -1;
- if (x < 0 || x > USHRT_MAX){
- PyErr_SetString(StructError,
- "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
- return -1;
- }
- y = (unsigned short)x;
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ long x;
+ unsigned short y;
+ if (get_long(v, &x) < 0)
+ return -1;
+ if (x < 0 || x > USHRT_MAX){
+ PyErr_SetString(StructError,
+ "ushort format requires 0 <= number <= " STRINGIFY(USHRT_MAX));
+ return -1;
+ }
+ y = (unsigned short)x;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_int(char *p, PyObject *v, const formatdef *f)
{
- long x;
- int y;
- if (get_long(v, &x) < 0)
- return -1;
+ long x;
+ int y;
+ if (get_long(v, &x) < 0)
+ return -1;
#if (SIZEOF_LONG > SIZEOF_INT)
- if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
- return _range_error(f, 0);
+ if ((x < ((long)INT_MIN)) || (x > ((long)INT_MAX)))
+ return _range_error(f, 0);
#endif
- y = (int)x;
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ y = (int)x;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_uint(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- unsigned int y;
- if (get_ulong(v, &x) < 0)
- return -1;
- y = (unsigned int)x;
+ unsigned long x;
+ unsigned int y;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ y = (unsigned int)x;
#if (SIZEOF_LONG > SIZEOF_INT)
- if (x > ((unsigned long)UINT_MAX))
- return _range_error(f, 1);
+ if (x > ((unsigned long)UINT_MAX))
+ return _range_error(f, 1);
#endif
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_long(char *p, PyObject *v, const formatdef *f)
{
- long x;
- if (get_long(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ long x;
+ if (get_long(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static int
np_ulong(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- if (get_ulong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ unsigned long x;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
#ifdef HAVE_LONG_LONG
@@ -614,21 +614,21 @@ np_ulong(char *p, PyObject *v, const formatdef *f)
static int
np_longlong(char *p, PyObject *v, const formatdef *f)
{
- PY_LONG_LONG x;
- if (get_longlong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ PY_LONG_LONG x;
+ if (get_longlong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static int
np_ulonglong(char *p, PyObject *v, const formatdef *f)
{
- unsigned PY_LONG_LONG x;
- if (get_ulonglong(v, &x) < 0)
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ unsigned PY_LONG_LONG x;
+ if (get_ulonglong(v, &x) < 0)
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
#endif
@@ -636,77 +636,77 @@ np_ulonglong(char *p, PyObject *v, const formatdef *f)
static int
np_bool(char *p, PyObject *v, const formatdef *f)
{
- BOOL_TYPE y;
- y = PyObject_IsTrue(v);
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ BOOL_TYPE y;
+ y = PyObject_IsTrue(v);
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static int
np_float(char *p, PyObject *v, const formatdef *f)
{
- float x = (float)PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ float x = (float)PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static int
np_double(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- memcpy(p, (char *)&x, sizeof(double));
- return 0;
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ memcpy(p, (char *)&x, sizeof(double));
+ return 0;
}
static int
np_void_p(char *p, PyObject *v, const formatdef *f)
{
- void *x;
+ void *x;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- assert(PyLong_Check(v));
- x = PyLong_AsVoidPtr(v);
- Py_DECREF(v);
- if (x == NULL && PyErr_Occurred())
- return -1;
- memcpy(p, (char *)&x, sizeof x);
- return 0;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ assert(PyLong_Check(v));
+ x = PyLong_AsVoidPtr(v);
+ Py_DECREF(v);
+ if (x == NULL && PyErr_Occurred())
+ return -1;
+ memcpy(p, (char *)&x, sizeof x);
+ return 0;
}
static formatdef native_table[] = {
- {'x', sizeof(char), 0, NULL},
- {'b', sizeof(char), 0, nu_byte, np_byte},
- {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
- {'c', sizeof(char), 0, nu_char, np_char},
- {'s', sizeof(char), 0, NULL},
- {'p', sizeof(char), 0, NULL},
- {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
- {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
- {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
- {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
- {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
- {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
+ {'x', sizeof(char), 0, NULL},
+ {'b', sizeof(char), 0, nu_byte, np_byte},
+ {'B', sizeof(char), 0, nu_ubyte, np_ubyte},
+ {'c', sizeof(char), 0, nu_char, np_char},
+ {'s', sizeof(char), 0, NULL},
+ {'p', sizeof(char), 0, NULL},
+ {'h', sizeof(short), SHORT_ALIGN, nu_short, np_short},
+ {'H', sizeof(short), SHORT_ALIGN, nu_ushort, np_ushort},
+ {'i', sizeof(int), INT_ALIGN, nu_int, np_int},
+ {'I', sizeof(int), INT_ALIGN, nu_uint, np_uint},
+ {'l', sizeof(long), LONG_ALIGN, nu_long, np_long},
+ {'L', sizeof(long), LONG_ALIGN, nu_ulong, np_ulong},
#ifdef HAVE_LONG_LONG
- {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
- {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
+ {'q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_longlong, np_longlong},
+ {'Q', sizeof(PY_LONG_LONG), LONG_LONG_ALIGN, nu_ulonglong,np_ulonglong},
#endif
- {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
- {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
- {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
- {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
- {0}
+ {'?', sizeof(BOOL_TYPE), BOOL_ALIGN, nu_bool, np_bool},
+ {'f', sizeof(float), FLOAT_ALIGN, nu_float, np_float},
+ {'d', sizeof(double), DOUBLE_ALIGN, nu_double, np_double},
+ {'P', sizeof(void *), VOID_P_ALIGN, nu_void_p, np_void_p},
+ {0}
};
/* Big-endian routines. *****************************************************/
@@ -714,53 +714,53 @@ static formatdef native_table[] = {
static PyObject *
bu_int(const char *p, const formatdef *f)
{
- long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG > f->size)
- x |= -(x & (1L << ((8 * f->size) - 1)));
- return PyInt_FromLong(x);
+ long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG > f->size)
+ x |= -(x & (1L << ((8 * f->size) - 1)));
+ return PyInt_FromLong(x);
}
static PyObject *
bu_uint(const char *p, const formatdef *f)
{
- unsigned long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- if (x <= LONG_MAX)
- return PyInt_FromLong((long)x);
- return PyLong_FromUnsignedLong(x);
+ unsigned long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong((long)x);
+ return PyLong_FromUnsignedLong(x);
}
static PyObject *
bu_longlong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG_LONG > f->size)
- x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
- if (x >= LONG_MIN && x <= LONG_MAX)
- return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
- return PyLong_FromLongLong(x);
+ PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG_LONG > f->size)
+ x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
+ if (x >= LONG_MIN && x <= LONG_MAX)
+ return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
+ return PyLong_FromLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 0, /* little-endian */
- 1 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 0, /* little-endian */
+ 1 /* signed */);
#endif
}
@@ -768,171 +768,171 @@ static PyObject *
bu_ulonglong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- unsigned PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | *bytes++;
- } while (--i > 0);
- if (x <= LONG_MAX)
- return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
- return PyLong_FromUnsignedLongLong(x);
+ unsigned PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | *bytes++;
+ } while (--i > 0);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 0, /* little-endian */
- 0 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 0, /* little-endian */
+ 0 /* signed */);
#endif
}
static PyObject *
bu_float(const char *p, const formatdef *f)
{
- return unpack_float(p, 0);
+ return unpack_float(p, 0);
}
static PyObject *
bu_double(const char *p, const formatdef *f)
{
- return unpack_double(p, 0);
+ return unpack_double(p, 0);
}
static PyObject *
bu_bool(const char *p, const formatdef *f)
{
- char x;
- memcpy((char *)&x, p, sizeof x);
- return PyBool_FromLong(x != 0);
+ char x;
+ memcpy((char *)&x, p, sizeof x);
+ return PyBool_FromLong(x != 0);
}
static int
bp_int(char *p, PyObject *v, const formatdef *f)
{
- long x;
- Py_ssize_t i;
- if (get_long(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- if ((i == 2) && (x < -32768 || x > 32767))
- return _range_error(f, 0);
+ long x;
+ Py_ssize_t i;
+ if (get_long(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ if ((i == 2) && (x < -32768 || x > 32767))
+ return _range_error(f, 0);
#if (SIZEOF_LONG != 4)
- else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
- return _range_error(f, 0);
+ else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
+ return _range_error(f, 0);
#endif
- }
- do {
- p[--i] = (char)x;
- x >>= 8;
- } while (i > 0);
- return 0;
+ }
+ do {
+ p[--i] = (char)x;
+ x >>= 8;
+ } while (i > 0);
+ return 0;
}
static int
bp_uint(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- Py_ssize_t i;
- if (get_ulong(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- unsigned long maxint = 1;
- maxint <<= (unsigned long)(i * 8);
- if (x >= maxint)
- return _range_error(f, 1);
- }
- do {
- p[--i] = (char)x;
- x >>= 8;
- } while (i > 0);
- return 0;
+ unsigned long x;
+ Py_ssize_t i;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ unsigned long maxint = 1;
+ maxint <<= (unsigned long)(i * 8);
+ if (x >= maxint)
+ return _range_error(f, 1);
+ }
+ do {
+ p[--i] = (char)x;
+ x >>= 8;
+ } while (i > 0);
+ return 0;
}
static int
bp_longlong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject *)v,
- (unsigned char *)p,
- 8,
- 0, /* little_endian */
- 1 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject *)v,
+ (unsigned char *)p,
+ 8,
+ 0, /* little_endian */
+ 1 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
bp_ulonglong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject *)v,
- (unsigned char *)p,
- 8,
- 0, /* little_endian */
- 0 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject *)v,
+ (unsigned char *)p,
+ 8,
+ 0, /* little_endian */
+ 0 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
bp_float(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack4(x, (unsigned char *)p, 0);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack4(x, (unsigned char *)p, 0);
}
static int
bp_double(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack8(x, (unsigned char *)p, 0);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack8(x, (unsigned char *)p, 0);
}
static int
bp_bool(char *p, PyObject *v, const formatdef *f)
{
- char y;
- y = PyObject_IsTrue(v);
- memcpy(p, (char *)&y, sizeof y);
- return 0;
+ char y;
+ y = PyObject_IsTrue(v);
+ memcpy(p, (char *)&y, sizeof y);
+ return 0;
}
static formatdef bigendian_table[] = {
- {'x', 1, 0, NULL},
- {'b', 1, 0, nu_byte, np_byte},
- {'B', 1, 0, nu_ubyte, np_ubyte},
- {'c', 1, 0, nu_char, np_char},
- {'s', 1, 0, NULL},
- {'p', 1, 0, NULL},
- {'h', 2, 0, bu_int, bp_int},
- {'H', 2, 0, bu_uint, bp_uint},
- {'i', 4, 0, bu_int, bp_int},
- {'I', 4, 0, bu_uint, bp_uint},
- {'l', 4, 0, bu_int, bp_int},
- {'L', 4, 0, bu_uint, bp_uint},
- {'q', 8, 0, bu_longlong, bp_longlong},
- {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
- {'?', 1, 0, bu_bool, bp_bool},
- {'f', 4, 0, bu_float, bp_float},
- {'d', 8, 0, bu_double, bp_double},
- {0}
+ {'x', 1, 0, NULL},
+ {'b', 1, 0, nu_byte, np_byte},
+ {'B', 1, 0, nu_ubyte, np_ubyte},
+ {'c', 1, 0, nu_char, np_char},
+ {'s', 1, 0, NULL},
+ {'p', 1, 0, NULL},
+ {'h', 2, 0, bu_int, bp_int},
+ {'H', 2, 0, bu_uint, bp_uint},
+ {'i', 4, 0, bu_int, bp_int},
+ {'I', 4, 0, bu_uint, bp_uint},
+ {'l', 4, 0, bu_int, bp_int},
+ {'L', 4, 0, bu_uint, bp_uint},
+ {'q', 8, 0, bu_longlong, bp_longlong},
+ {'Q', 8, 0, bu_ulonglong, bp_ulonglong},
+ {'?', 1, 0, bu_bool, bp_bool},
+ {'f', 4, 0, bu_float, bp_float},
+ {'d', 8, 0, bu_double, bp_double},
+ {0}
};
/* Little-endian routines. *****************************************************/
@@ -940,53 +940,53 @@ static formatdef bigendian_table[] = {
static PyObject *
lu_int(const char *p, const formatdef *f)
{
- long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG > f->size)
- x |= -(x & (1L << ((8 * f->size) - 1)));
- return PyInt_FromLong(x);
+ long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG > f->size)
+ x |= -(x & (1L << ((8 * f->size) - 1)));
+ return PyInt_FromLong(x);
}
static PyObject *
lu_uint(const char *p, const formatdef *f)
{
- unsigned long x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- if (x <= LONG_MAX)
- return PyInt_FromLong((long)x);
- return PyLong_FromUnsignedLong((long)x);
+ unsigned long x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong((long)x);
+ return PyLong_FromUnsignedLong((long)x);
}
static PyObject *
lu_longlong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- /* Extend the sign bit. */
- if (SIZEOF_LONG_LONG > f->size)
- x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
- if (x >= LONG_MIN && x <= LONG_MAX)
- return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
- return PyLong_FromLongLong(x);
+ PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ /* Extend the sign bit. */
+ if (SIZEOF_LONG_LONG > f->size)
+ x |= -(x & ((PY_LONG_LONG)1 << ((8 * f->size) - 1)));
+ if (x >= LONG_MIN && x <= LONG_MAX)
+ return PyInt_FromLong(Py_SAFE_DOWNCAST(x, PY_LONG_LONG, long));
+ return PyLong_FromLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 1, /* little-endian */
- 1 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 1, /* little-endian */
+ 1 /* signed */);
#endif
}
@@ -994,182 +994,182 @@ static PyObject *
lu_ulonglong(const char *p, const formatdef *f)
{
#ifdef HAVE_LONG_LONG
- unsigned PY_LONG_LONG x = 0;
- Py_ssize_t i = f->size;
- const unsigned char *bytes = (const unsigned char *)p;
- do {
- x = (x<<8) | bytes[--i];
- } while (i > 0);
- if (x <= LONG_MAX)
- return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
- return PyLong_FromUnsignedLongLong(x);
+ unsigned PY_LONG_LONG x = 0;
+ Py_ssize_t i = f->size;
+ const unsigned char *bytes = (const unsigned char *)p;
+ do {
+ x = (x<<8) | bytes[--i];
+ } while (i > 0);
+ if (x <= LONG_MAX)
+ return PyInt_FromLong(Py_SAFE_DOWNCAST(x, unsigned PY_LONG_LONG, long));
+ return PyLong_FromUnsignedLongLong(x);
#else
- return _PyLong_FromByteArray((const unsigned char *)p,
- 8,
- 1, /* little-endian */
- 0 /* signed */);
+ return _PyLong_FromByteArray((const unsigned char *)p,
+ 8,
+ 1, /* little-endian */
+ 0 /* signed */);
#endif
}
static PyObject *
lu_float(const char *p, const formatdef *f)
{
- return unpack_float(p, 1);
+ return unpack_float(p, 1);
}
static PyObject *
lu_double(const char *p, const formatdef *f)
{
- return unpack_double(p, 1);
+ return unpack_double(p, 1);
}
static int
lp_int(char *p, PyObject *v, const formatdef *f)
{
- long x;
- Py_ssize_t i;
- if (get_long(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- if ((i == 2) && (x < -32768 || x > 32767))
- return _range_error(f, 0);
+ long x;
+ Py_ssize_t i;
+ if (get_long(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ if ((i == 2) && (x < -32768 || x > 32767))
+ return _range_error(f, 0);
#if (SIZEOF_LONG != 4)
- else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
- return _range_error(f, 0);
+ else if ((i == 4) && (x < -2147483648L || x > 2147483647L))
+ return _range_error(f, 0);
#endif
- }
- do {
- *p++ = (char)x;
- x >>= 8;
- } while (--i > 0);
- return 0;
+ }
+ do {
+ *p++ = (char)x;
+ x >>= 8;
+ } while (--i > 0);
+ return 0;
}
static int
lp_uint(char *p, PyObject *v, const formatdef *f)
{
- unsigned long x;
- Py_ssize_t i;
- if (get_ulong(v, &x) < 0)
- return -1;
- i = f->size;
- if (i != SIZEOF_LONG) {
- unsigned long maxint = 1;
- maxint <<= (unsigned long)(i * 8);
- if (x >= maxint)
- return _range_error(f, 1);
- }
- do {
- *p++ = (char)x;
- x >>= 8;
- } while (--i > 0);
- return 0;
+ unsigned long x;
+ Py_ssize_t i;
+ if (get_ulong(v, &x) < 0)
+ return -1;
+ i = f->size;
+ if (i != SIZEOF_LONG) {
+ unsigned long maxint = 1;
+ maxint <<= (unsigned long)(i * 8);
+ if (x >= maxint)
+ return _range_error(f, 1);
+ }
+ do {
+ *p++ = (char)x;
+ x >>= 8;
+ } while (--i > 0);
+ return 0;
}
static int
lp_longlong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject*)v,
- (unsigned char *)p,
- 8,
- 1, /* little_endian */
- 1 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject*)v,
+ (unsigned char *)p,
+ 8,
+ 1, /* little_endian */
+ 1 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
lp_ulonglong(char *p, PyObject *v, const formatdef *f)
{
- int res;
- v = get_pylong(v);
- if (v == NULL)
- return -1;
- res = _PyLong_AsByteArray((PyLongObject*)v,
- (unsigned char *)p,
- 8,
- 1, /* little_endian */
- 0 /* signed */);
- Py_DECREF(v);
- return res;
+ int res;
+ v = get_pylong(v);
+ if (v == NULL)
+ return -1;
+ res = _PyLong_AsByteArray((PyLongObject*)v,
+ (unsigned char *)p,
+ 8,
+ 1, /* little_endian */
+ 0 /* signed */);
+ Py_DECREF(v);
+ return res;
}
static int
lp_float(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack4(x, (unsigned char *)p, 1);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack4(x, (unsigned char *)p, 1);
}
static int
lp_double(char *p, PyObject *v, const formatdef *f)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_SetString(StructError,
- "required argument is not a float");
- return -1;
- }
- return _PyFloat_Pack8(x, (unsigned char *)p, 1);
+ double x = PyFloat_AsDouble(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_SetString(StructError,
+ "required argument is not a float");
+ return -1;
+ }
+ return _PyFloat_Pack8(x, (unsigned char *)p, 1);
}
static formatdef lilendian_table[] = {
- {'x', 1, 0, NULL},
- {'b', 1, 0, nu_byte, np_byte},
- {'B', 1, 0, nu_ubyte, np_ubyte},
- {'c', 1, 0, nu_char, np_char},
- {'s', 1, 0, NULL},
- {'p', 1, 0, NULL},
- {'h', 2, 0, lu_int, lp_int},
- {'H', 2, 0, lu_uint, lp_uint},
- {'i', 4, 0, lu_int, lp_int},
- {'I', 4, 0, lu_uint, lp_uint},
- {'l', 4, 0, lu_int, lp_int},
- {'L', 4, 0, lu_uint, lp_uint},
- {'q', 8, 0, lu_longlong, lp_longlong},
- {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
- {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
- but potentially different from native rep -- reuse bx_bool funcs. */
- {'f', 4, 0, lu_float, lp_float},
- {'d', 8, 0, lu_double, lp_double},
- {0}
+ {'x', 1, 0, NULL},
+ {'b', 1, 0, nu_byte, np_byte},
+ {'B', 1, 0, nu_ubyte, np_ubyte},
+ {'c', 1, 0, nu_char, np_char},
+ {'s', 1, 0, NULL},
+ {'p', 1, 0, NULL},
+ {'h', 2, 0, lu_int, lp_int},
+ {'H', 2, 0, lu_uint, lp_uint},
+ {'i', 4, 0, lu_int, lp_int},
+ {'I', 4, 0, lu_uint, lp_uint},
+ {'l', 4, 0, lu_int, lp_int},
+ {'L', 4, 0, lu_uint, lp_uint},
+ {'q', 8, 0, lu_longlong, lp_longlong},
+ {'Q', 8, 0, lu_ulonglong, lp_ulonglong},
+ {'?', 1, 0, bu_bool, bp_bool}, /* Std rep not endian dep,
+ but potentially different from native rep -- reuse bx_bool funcs. */
+ {'f', 4, 0, lu_float, lp_float},
+ {'d', 8, 0, lu_double, lp_double},
+ {0}
};
static const formatdef *
whichtable(char **pfmt)
{
- const char *fmt = (*pfmt)++; /* May be backed out of later */
- switch (*fmt) {
- case '<':
- return lilendian_table;
- case '>':
- case '!': /* Network byte order is big-endian */
- return bigendian_table;
- case '=': { /* Host byte order -- different from native in aligment! */
- int n = 1;
- char *p = (char *) &n;
- if (*p == 1)
- return lilendian_table;
- else
- return bigendian_table;
- }
- default:
- --*pfmt; /* Back out of pointer increment */
- /* Fall through */
- case '@':
- return native_table;
- }
+ const char *fmt = (*pfmt)++; /* May be backed out of later */
+ switch (*fmt) {
+ case '<':
+ return lilendian_table;
+ case '>':
+ case '!': /* Network byte order is big-endian */
+ return bigendian_table;
+ case '=': { /* Host byte order -- different from native in aligment! */
+ int n = 1;
+ char *p = (char *) &n;
+ if (*p == 1)
+ return lilendian_table;
+ else
+ return bigendian_table;
+ }
+ default:
+ --*pfmt; /* Back out of pointer increment */
+ /* Fall through */
+ case '@':
+ return native_table;
+ }
}
@@ -1178,13 +1178,13 @@ whichtable(char **pfmt)
static const formatdef *
getentry(int c, const formatdef *f)
{
- for (; f->format != '\0'; f++) {
- if (f->format == c) {
- return f;
- }
- }
- PyErr_SetString(StructError, "bad char in struct format");
- return NULL;
+ for (; f->format != '\0'; f++) {
+ if (f->format == c) {
+ return f;
+ }
+ }
+ PyErr_SetString(StructError, "bad char in struct format");
+ return NULL;
}
@@ -1193,14 +1193,14 @@ getentry(int c, const formatdef *f)
static int
align(Py_ssize_t size, char c, const formatdef *e)
{
- if (e->format == c) {
- if (e->alignment) {
- size = ((size + e->alignment - 1)
- / e->alignment)
- * e->alignment;
- }
- }
- return size;
+ if (e->format == c) {
+ if (e->alignment) {
+ size = ((size + e->alignment - 1)
+ / e->alignment)
+ * e->alignment;
+ }
+ }
+ return size;
}
@@ -1209,207 +1209,207 @@ align(Py_ssize_t size, char c, const formatdef *e)
static int
prepare_s(PyStructObject *self)
{
- const formatdef *f;
- const formatdef *e;
- formatcode *codes;
-
- const char *s;
- const char *fmt;
- char c;
- Py_ssize_t size, len, num, itemsize, x;
-
- fmt = PyString_AS_STRING(self->s_format);
-
- f = whichtable((char **)&fmt);
-
- s = fmt;
- size = 0;
- len = 0;
- while ((c = *s++) != '\0') {
- if (isspace(Py_CHARMASK(c)))
- continue;
- if ('0' <= c && c <= '9') {
- num = c - '0';
- while ('0' <= (c = *s++) && c <= '9') {
- x = num*10 + (c - '0');
- if (x/10 != num) {
- PyErr_SetString(
- StructError,
- "overflow in item count");
- return -1;
- }
- num = x;
- }
- if (c == '\0')
- break;
- }
- else
- num = 1;
-
- e = getentry(c, f);
- if (e == NULL)
- return -1;
-
- switch (c) {
- case 's': /* fall through */
- case 'p': len++; break;
- case 'x': break;
- default: len += num; break;
- }
-
- itemsize = e->size;
- size = align(size, c, e);
- x = num * itemsize;
- size += x;
- if (x/itemsize != num || size < 0) {
- PyErr_SetString(StructError,
- "total struct size too long");
- return -1;
- }
- }
-
- /* check for overflow */
- if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
- PyErr_NoMemory();
- return -1;
- }
-
- self->s_size = size;
- self->s_len = len;
- codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
- if (codes == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- self->s_codes = codes;
-
- s = fmt;
- size = 0;
- while ((c = *s++) != '\0') {
- if (isspace(Py_CHARMASK(c)))
- continue;
- if ('0' <= c && c <= '9') {
- num = c - '0';
- while ('0' <= (c = *s++) && c <= '9')
- num = num*10 + (c - '0');
- if (c == '\0')
- break;
- }
- else
- num = 1;
-
- e = getentry(c, f);
-
- size = align(size, c, e);
- if (c == 's' || c == 'p') {
- codes->offset = size;
- codes->size = num;
- codes->fmtdef = e;
- codes++;
- size += num;
- } else if (c == 'x') {
- size += num;
- } else {
- while (--num >= 0) {
- codes->offset = size;
- codes->size = e->size;
- codes->fmtdef = e;
- codes++;
- size += e->size;
- }
- }
- }
- codes->fmtdef = NULL;
- codes->offset = size;
- codes->size = 0;
-
- return 0;
+ const formatdef *f;
+ const formatdef *e;
+ formatcode *codes;
+
+ const char *s;
+ const char *fmt;
+ char c;
+ Py_ssize_t size, len, num, itemsize, x;
+
+ fmt = PyString_AS_STRING(self->s_format);
+
+ f = whichtable((char **)&fmt);
+
+ s = fmt;
+ size = 0;
+ len = 0;
+ while ((c = *s++) != '\0') {
+ if (isspace(Py_CHARMASK(c)))
+ continue;
+ if ('0' <= c && c <= '9') {
+ num = c - '0';
+ while ('0' <= (c = *s++) && c <= '9') {
+ x = num*10 + (c - '0');
+ if (x/10 != num) {
+ PyErr_SetString(
+ StructError,
+ "overflow in item count");
+ return -1;
+ }
+ num = x;
+ }
+ if (c == '\0')
+ break;
+ }
+ else
+ num = 1;
+
+ e = getentry(c, f);
+ if (e == NULL)
+ return -1;
+
+ switch (c) {
+ case 's': /* fall through */
+ case 'p': len++; break;
+ case 'x': break;
+ default: len += num; break;
+ }
+
+ itemsize = e->size;
+ size = align(size, c, e);
+ x = num * itemsize;
+ size += x;
+ if (x/itemsize != num || size < 0) {
+ PyErr_SetString(StructError,
+ "total struct size too long");
+ return -1;
+ }
+ }
+
+ /* check for overflow */
+ if ((len + 1) > (PY_SSIZE_T_MAX / sizeof(formatcode))) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ self->s_size = size;
+ self->s_len = len;
+ codes = PyMem_MALLOC((len + 1) * sizeof(formatcode));
+ if (codes == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->s_codes = codes;
+
+ s = fmt;
+ size = 0;
+ while ((c = *s++) != '\0') {
+ if (isspace(Py_CHARMASK(c)))
+ continue;
+ if ('0' <= c && c <= '9') {
+ num = c - '0';
+ while ('0' <= (c = *s++) && c <= '9')
+ num = num*10 + (c - '0');
+ if (c == '\0')
+ break;
+ }
+ else
+ num = 1;
+
+ e = getentry(c, f);
+
+ size = align(size, c, e);
+ if (c == 's' || c == 'p') {
+ codes->offset = size;
+ codes->size = num;
+ codes->fmtdef = e;
+ codes++;
+ size += num;
+ } else if (c == 'x') {
+ size += num;
+ } else {
+ while (--num >= 0) {
+ codes->offset = size;
+ codes->size = e->size;
+ codes->fmtdef = e;
+ codes++;
+ size += e->size;
+ }
+ }
+ }
+ codes->fmtdef = NULL;
+ codes->offset = size;
+ codes->size = 0;
+
+ return 0;
}
static PyObject *
s_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *self;
+ PyObject *self;
- assert(type != NULL && type->tp_alloc != NULL);
+ assert(type != NULL && type->tp_alloc != NULL);
- self = type->tp_alloc(type, 0);
- if (self != NULL) {
- PyStructObject *s = (PyStructObject*)self;
- Py_INCREF(Py_None);
- s->s_format = Py_None;
- s->s_codes = NULL;
- s->s_size = -1;
- s->s_len = -1;
- }
- return self;
+ self = type->tp_alloc(type, 0);
+ if (self != NULL) {
+ PyStructObject *s = (PyStructObject*)self;
+ Py_INCREF(Py_None);
+ s->s_format = Py_None;
+ s->s_codes = NULL;
+ s->s_size = -1;
+ s->s_len = -1;
+ }
+ return self;
}
static int
s_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyStructObject *soself = (PyStructObject *)self;
- PyObject *o_format = NULL;
- int ret = 0;
- static char *kwlist[] = {"format", 0};
+ PyStructObject *soself = (PyStructObject *)self;
+ PyObject *o_format = NULL;
+ int ret = 0;
+ static char *kwlist[] = {"format", 0};
- assert(PyStruct_Check(self));
+ assert(PyStruct_Check(self));
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
- &o_format))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "S:Struct", kwlist,
+ &o_format))
+ return -1;
- Py_INCREF(o_format);
- Py_CLEAR(soself->s_format);
- soself->s_format = o_format;
+ Py_INCREF(o_format);
+ Py_CLEAR(soself->s_format);
+ soself->s_format = o_format;
- ret = prepare_s(soself);
- return ret;
+ ret = prepare_s(soself);
+ return ret;
}
static void
s_dealloc(PyStructObject *s)
{
- if (s->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *)s);
- if (s->s_codes != NULL) {
- PyMem_FREE(s->s_codes);
- }
- Py_XDECREF(s->s_format);
- Py_TYPE(s)->tp_free((PyObject *)s);
+ if (s->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *)s);
+ if (s->s_codes != NULL) {
+ PyMem_FREE(s->s_codes);
+ }
+ Py_XDECREF(s->s_format);
+ Py_TYPE(s)->tp_free((PyObject *)s);
}
static PyObject *
s_unpack_internal(PyStructObject *soself, char *startfrom) {
- formatcode *code;
- Py_ssize_t i = 0;
- PyObject *result = PyTuple_New(soself->s_len);
- if (result == NULL)
- return NULL;
-
- for (code = soself->s_codes; code->fmtdef != NULL; code++) {
- PyObject *v;
- const formatdef *e = code->fmtdef;
- const char *res = startfrom + code->offset;
- if (e->format == 's') {
- v = PyString_FromStringAndSize(res, code->size);
- } else if (e->format == 'p') {
- Py_ssize_t n = *(unsigned char*)res;
- if (n >= code->size)
- n = code->size - 1;
- v = PyString_FromStringAndSize(res + 1, n);
- } else {
- v = e->unpack(res, e);
- }
- if (v == NULL)
- goto fail;
- PyTuple_SET_ITEM(result, i++, v);
- }
-
- return result;
+ formatcode *code;
+ Py_ssize_t i = 0;
+ PyObject *result = PyTuple_New(soself->s_len);
+ if (result == NULL)
+ return NULL;
+
+ for (code = soself->s_codes; code->fmtdef != NULL; code++) {
+ PyObject *v;
+ const formatdef *e = code->fmtdef;
+ const char *res = startfrom + code->offset;
+ if (e->format == 's') {
+ v = PyString_FromStringAndSize(res, code->size);
+ } else if (e->format == 'p') {
+ Py_ssize_t n = *(unsigned char*)res;
+ if (n >= code->size)
+ n = code->size - 1;
+ v = PyString_FromStringAndSize(res + 1, n);
+ } else {
+ v = e->unpack(res, e);
+ }
+ if (v == NULL)
+ goto fail;
+ PyTuple_SET_ITEM(result, i++, v);
+ }
+
+ return result;
fail:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
@@ -1423,35 +1423,35 @@ strings.");
static PyObject *
s_unpack(PyObject *self, PyObject *inputstr)
{
- char *start;
- Py_ssize_t len;
- PyObject *args=NULL, *result;
- PyStructObject *soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (inputstr == NULL)
- goto fail;
- if (PyString_Check(inputstr) &&
- PyString_GET_SIZE(inputstr) == soself->s_size) {
- return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
- }
- args = PyTuple_Pack(1, inputstr);
- if (args == NULL)
- return NULL;
- if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
- goto fail;
- if (soself->s_size != len)
- goto fail;
- result = s_unpack_internal(soself, start);
- Py_DECREF(args);
- return result;
+ char *start;
+ Py_ssize_t len;
+ PyObject *args=NULL, *result;
+ PyStructObject *soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (inputstr == NULL)
+ goto fail;
+ if (PyString_Check(inputstr) &&
+ PyString_GET_SIZE(inputstr) == soself->s_size) {
+ return s_unpack_internal(soself, PyString_AS_STRING(inputstr));
+ }
+ args = PyTuple_Pack(1, inputstr);
+ if (args == NULL)
+ return NULL;
+ if (!PyArg_ParseTuple(args, "s#:unpack", &start, &len))
+ goto fail;
+ if (soself->s_size != len)
+ goto fail;
+ result = s_unpack_internal(soself, start);
+ Py_DECREF(args);
+ return result;
fail:
- Py_XDECREF(args);
- PyErr_Format(StructError,
- "unpack requires a string argument of length %zd",
- soself->s_size);
- return NULL;
+ Py_XDECREF(args);
+ PyErr_Format(StructError,
+ "unpack requires a string argument of length %zd",
+ soself->s_size);
+ return NULL;
}
PyDoc_STRVAR(s_unpack_from__doc__,
@@ -1465,38 +1465,38 @@ See struct.__doc__ for more on format strings.");
static PyObject *
s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"buffer", "offset", 0};
+ static char *kwlist[] = {"buffer", "offset", 0};
#if (PY_VERSION_HEX < 0x02050000)
- static char *fmt = "z#|i:unpack_from";
+ static char *fmt = "z#|i:unpack_from";
#else
- static char *fmt = "z#|n:unpack_from";
+ static char *fmt = "z#|n:unpack_from";
#endif
- Py_ssize_t buffer_len = 0, offset = 0;
- char *buffer = NULL;
- PyStructObject *soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
+ Py_ssize_t buffer_len = 0, offset = 0;
+ char *buffer = NULL;
+ PyStructObject *soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
- if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
- &buffer, &buffer_len, &offset))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
+ &buffer, &buffer_len, &offset))
+ return NULL;
- if (buffer == NULL) {
- PyErr_Format(StructError,
- "unpack_from requires a buffer argument");
- return NULL;
- }
+ if (buffer == NULL) {
+ PyErr_Format(StructError,
+ "unpack_from requires a buffer argument");
+ return NULL;
+ }
- if (offset < 0)
- offset += buffer_len;
+ if (offset < 0)
+ offset += buffer_len;
- if (offset < 0 || (buffer_len - offset) < soself->s_size) {
- PyErr_Format(StructError,
- "unpack_from requires a buffer of at least %zd bytes",
- soself->s_size);
- return NULL;
- }
- return s_unpack_internal(soself, buffer + offset);
+ if (offset < 0 || (buffer_len - offset) < soself->s_size) {
+ PyErr_Format(StructError,
+ "unpack_from requires a buffer of at least %zd bytes",
+ soself->s_size);
+ return NULL;
+ }
+ return s_unpack_internal(soself, buffer + offset);
}
@@ -1513,58 +1513,58 @@ s_unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
static int
s_pack_internal(PyStructObject *soself, PyObject *args, int offset, char* buf)
{
- formatcode *code;
- /* XXX(nnorwitz): why does i need to be a local? can we use
- the offset parameter or do we need the wider width? */
- Py_ssize_t i;
-
- memset(buf, '\0', soself->s_size);
- i = offset;
- for (code = soself->s_codes; code->fmtdef != NULL; code++) {
- Py_ssize_t n;
- PyObject *v = PyTuple_GET_ITEM(args, i++);
- const formatdef *e = code->fmtdef;
- char *res = buf + code->offset;
- if (e->format == 's') {
- if (!PyString_Check(v)) {
- PyErr_SetString(StructError,
- "argument for 's' must "
- "be a string");
- return -1;
- }
- n = PyString_GET_SIZE(v);
- if (n > code->size)
- n = code->size;
- if (n > 0)
- memcpy(res, PyString_AS_STRING(v), n);
- } else if (e->format == 'p') {
- if (!PyString_Check(v)) {
- PyErr_SetString(StructError,
- "argument for 'p' must "
- "be a string");
- return -1;
- }
- n = PyString_GET_SIZE(v);
- if (n > (code->size - 1))
- n = code->size - 1;
- if (n > 0)
- memcpy(res + 1, PyString_AS_STRING(v), n);
- if (n > 255)
- n = 255;
- *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
- } else if (e->pack(res, v, e) < 0) {
- if (strchr(integer_codes, e->format) != NULL &&
- PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_Format(StructError,
- "integer out of range for "
- "'%c' format code",
- e->format);
- return -1;
- }
- }
-
- /* Success */
- return 0;
+ formatcode *code;
+ /* XXX(nnorwitz): why does i need to be a local? can we use
+ the offset parameter or do we need the wider width? */
+ Py_ssize_t i;
+
+ memset(buf, '\0', soself->s_size);
+ i = offset;
+ for (code = soself->s_codes; code->fmtdef != NULL; code++) {
+ Py_ssize_t n;
+ PyObject *v = PyTuple_GET_ITEM(args, i++);
+ const formatdef *e = code->fmtdef;
+ char *res = buf + code->offset;
+ if (e->format == 's') {
+ if (!PyString_Check(v)) {
+ PyErr_SetString(StructError,
+ "argument for 's' must "
+ "be a string");
+ return -1;
+ }
+ n = PyString_GET_SIZE(v);
+ if (n > code->size)
+ n = code->size;
+ if (n > 0)
+ memcpy(res, PyString_AS_STRING(v), n);
+ } else if (e->format == 'p') {
+ if (!PyString_Check(v)) {
+ PyErr_SetString(StructError,
+ "argument for 'p' must "
+ "be a string");
+ return -1;
+ }
+ n = PyString_GET_SIZE(v);
+ if (n > (code->size - 1))
+ n = code->size - 1;
+ if (n > 0)
+ memcpy(res + 1, PyString_AS_STRING(v), n);
+ if (n > 255)
+ n = 255;
+ *res = Py_SAFE_DOWNCAST(n, Py_ssize_t, unsigned char);
+ } else if (e->pack(res, v, e) < 0) {
+ if (strchr(integer_codes, e->format) != NULL &&
+ PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_Format(StructError,
+ "integer out of range for "
+ "'%c' format code",
+ e->format);
+ return -1;
+ }
+ }
+
+ /* Success */
+ return 0;
}
@@ -1577,32 +1577,32 @@ Struct's format. See struct.__doc__ for more on format strings.");
static PyObject *
s_pack(PyObject *self, PyObject *args)
{
- PyStructObject *soself;
- PyObject *result;
+ PyStructObject *soself;
+ PyObject *result;
- /* Validate arguments. */
- soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (PyTuple_GET_SIZE(args) != soself->s_len)
- {
- PyErr_Format(StructError,
- "pack requires exactly %zd arguments", soself->s_len);
- return NULL;
- }
+ /* Validate arguments. */
+ soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (PyTuple_GET_SIZE(args) != soself->s_len)
+ {
+ PyErr_Format(StructError,
+ "pack requires exactly %zd arguments", soself->s_len);
+ return NULL;
+ }
- /* Allocate a new string */
- result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
- if (result == NULL)
- return NULL;
+ /* Allocate a new string */
+ result = PyString_FromStringAndSize((char *)NULL, soself->s_size);
+ if (result == NULL)
+ return NULL;
- /* Call the guts */
- if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
- Py_DECREF(result);
- return NULL;
- }
+ /* Call the guts */
+ if ( s_pack_internal(soself, args, 0, PyString_AS_STRING(result)) != 0 ) {
+ Py_DECREF(result);
+ return NULL;
+ }
- return result;
+ return result;
}
PyDoc_STRVAR(s_pack_into__doc__,
@@ -1616,59 +1616,59 @@ more on format strings.");
static PyObject *
s_pack_into(PyObject *self, PyObject *args)
{
- PyStructObject *soself;
- char *buffer;
- Py_ssize_t buffer_len, offset;
-
- /* Validate arguments. +1 is for the first arg as buffer. */
- soself = (PyStructObject *)self;
- assert(PyStruct_Check(self));
- assert(soself->s_codes != NULL);
- if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
- {
- PyErr_Format(StructError,
- "pack_into requires exactly %zd arguments",
- (soself->s_len + 2));
- return NULL;
- }
-
- /* Extract a writable memory buffer from the first argument */
- if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
- (void**)&buffer, &buffer_len) == -1 ) {
- return NULL;
- }
- assert( buffer_len >= 0 );
-
- /* Extract the offset from the first argument */
- offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
- if (offset == -1 && PyErr_Occurred())
- return NULL;
-
- /* Support negative offsets. */
- if (offset < 0)
- offset += buffer_len;
-
- /* Check boundaries */
- if (offset < 0 || (buffer_len - offset) < soself->s_size) {
- PyErr_Format(StructError,
- "pack_into requires a buffer of at least %zd bytes",
- soself->s_size);
- return NULL;
- }
-
- /* Call the guts */
- if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
- return NULL;
- }
-
- Py_RETURN_NONE;
+ PyStructObject *soself;
+ char *buffer;
+ Py_ssize_t buffer_len, offset;
+
+ /* Validate arguments. +1 is for the first arg as buffer. */
+ soself = (PyStructObject *)self;
+ assert(PyStruct_Check(self));
+ assert(soself->s_codes != NULL);
+ if (PyTuple_GET_SIZE(args) != (soself->s_len + 2))
+ {
+ PyErr_Format(StructError,
+ "pack_into requires exactly %zd arguments",
+ (soself->s_len + 2));
+ return NULL;
+ }
+
+ /* Extract a writable memory buffer from the first argument */
+ if ( PyObject_AsWriteBuffer(PyTuple_GET_ITEM(args, 0),
+ (void**)&buffer, &buffer_len) == -1 ) {
+ return NULL;
+ }
+ assert( buffer_len >= 0 );
+
+ /* Extract the offset from the first argument */
+ offset = PyInt_AsSsize_t(PyTuple_GET_ITEM(args, 1));
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+
+ /* Support negative offsets. */
+ if (offset < 0)
+ offset += buffer_len;
+
+ /* Check boundaries */
+ if (offset < 0 || (buffer_len - offset) < soself->s_size) {
+ PyErr_Format(StructError,
+ "pack_into requires a buffer of at least %zd bytes",
+ soself->s_size);
+ return NULL;
+ }
+
+ /* Call the guts */
+ if ( s_pack_internal(soself, args, 2, buffer + offset) != 0 ) {
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
static PyObject *
s_get_format(PyStructObject *self, void *unused)
{
- Py_INCREF(self->s_format);
- return self->s_format;
+ Py_INCREF(self->s_format);
+ return self->s_format;
}
static PyObject *
@@ -1680,12 +1680,12 @@ s_get_size(PyStructObject *self, void *unused)
/* List of functions */
static struct PyMethodDef s_methods[] = {
- {"pack", s_pack, METH_VARARGS, s_pack__doc__},
- {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
- {"unpack", s_unpack, METH_O, s_unpack__doc__},
- {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
- s_unpack_from__doc__},
- {NULL, NULL} /* sentinel */
+ {"pack", s_pack, METH_VARARGS, s_pack__doc__},
+ {"pack_into", s_pack_into, METH_VARARGS, s_pack_into__doc__},
+ {"unpack", s_unpack, METH_O, s_unpack__doc__},
+ {"unpack_from", (PyCFunction)s_unpack_from, METH_VARARGS|METH_KEYWORDS,
+ s_unpack_from__doc__},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(s__doc__, "Compiled struct object");
@@ -1693,52 +1693,52 @@ PyDoc_STRVAR(s__doc__, "Compiled struct object");
#define OFF(x) offsetof(PyStructObject, x)
static PyGetSetDef s_getsetlist[] = {
- {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
- {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
- {NULL} /* sentinel */
+ {"format", (getter)s_get_format, (setter)NULL, "struct format string", NULL},
+ {"size", (getter)s_get_size, (setter)NULL, "struct size in bytes", NULL},
+ {NULL} /* sentinel */
};
static
PyTypeObject PyStructType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "Struct",
- sizeof(PyStructObject),
- 0,
- (destructor)s_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 */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
- s__doc__, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- s_methods, /* tp_methods */
- NULL, /* tp_members */
- s_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- s_init, /* tp_init */
- PyType_GenericAlloc,/* tp_alloc */
- s_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "Struct",
+ sizeof(PyStructObject),
+ 0,
+ (destructor)s_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 */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS,/* tp_flags */
+ s__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyStructObject, weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ s_methods, /* tp_methods */
+ NULL, /* tp_members */
+ s_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ s_init, /* tp_init */
+ PyType_GenericAlloc,/* tp_alloc */
+ s_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -1750,29 +1750,29 @@ static PyObject *cache = NULL;
static PyObject *
cache_struct(PyObject *fmt)
{
- PyObject * s_object;
+ PyObject * s_object;
- if (cache == NULL) {
- cache = PyDict_New();
- if (cache == NULL)
- return NULL;
- }
+ if (cache == NULL) {
+ cache = PyDict_New();
+ if (cache == NULL)
+ return NULL;
+ }
- s_object = PyDict_GetItem(cache, fmt);
- if (s_object != NULL) {
- Py_INCREF(s_object);
- return s_object;
- }
+ s_object = PyDict_GetItem(cache, fmt);
+ if (s_object != NULL) {
+ Py_INCREF(s_object);
+ return s_object;
+ }
- s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
- if (s_object != NULL) {
- if (PyDict_Size(cache) >= MAXCACHE)
- PyDict_Clear(cache);
- /* Attempt to cache the result */
- if (PyDict_SetItem(cache, fmt, s_object) == -1)
- PyErr_Clear();
- }
- return s_object;
+ s_object = PyObject_CallFunctionObjArgs((PyObject *)(&PyStructType), fmt, NULL);
+ if (s_object != NULL) {
+ if (PyDict_Size(cache) >= MAXCACHE)
+ PyDict_Clear(cache);
+ /* Attempt to cache the result */
+ if (PyDict_SetItem(cache, fmt, s_object) == -1)
+ PyErr_Clear();
+ }
+ return s_object;
}
PyDoc_STRVAR(clearcache_doc,
@@ -1781,8 +1781,8 @@ PyDoc_STRVAR(clearcache_doc,
static PyObject *
clearcache(PyObject *self)
{
- Py_CLEAR(cache);
- Py_RETURN_NONE;
+ Py_CLEAR(cache);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(calcsize_doc,
@@ -1791,13 +1791,13 @@ PyDoc_STRVAR(calcsize_doc,
static PyObject *
calcsize(PyObject *self, PyObject *fmt)
{
- Py_ssize_t n;
- PyObject *s_object = cache_struct(fmt);
- if (s_object == NULL)
- return NULL;
- n = ((PyStructObject *)s_object)->s_size;
- Py_DECREF(s_object);
- return PyInt_FromSsize_t(n);
+ Py_ssize_t n;
+ PyObject *s_object = cache_struct(fmt);
+ if (s_object == NULL)
+ return NULL;
+ n = ((PyStructObject *)s_object)->s_size;
+ Py_DECREF(s_object);
+ return PyInt_FromSsize_t(n);
}
PyDoc_STRVAR(pack_doc,
@@ -1806,27 +1806,27 @@ PyDoc_STRVAR(pack_doc,
static PyObject *
pack(PyObject *self, PyObject *args)
{
- PyObject *s_object, *fmt, *newargs, *result;
- Py_ssize_t n = PyTuple_GET_SIZE(args);
-
- if (n == 0) {
- PyErr_SetString(PyExc_TypeError, "missing format argument");
- return NULL;
- }
- fmt = PyTuple_GET_ITEM(args, 0);
- newargs = PyTuple_GetSlice(args, 1, n);
- if (newargs == NULL)
- return NULL;
-
- s_object = cache_struct(fmt);
- if (s_object == NULL) {
- Py_DECREF(newargs);
- return NULL;
- }
- result = s_pack(s_object, newargs);
- Py_DECREF(newargs);
- Py_DECREF(s_object);
- return result;
+ PyObject *s_object, *fmt, *newargs, *result;
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+
+ if (n == 0) {
+ PyErr_SetString(PyExc_TypeError, "missing format argument");
+ return NULL;
+ }
+ fmt = PyTuple_GET_ITEM(args, 0);
+ newargs = PyTuple_GetSlice(args, 1, n);
+ if (newargs == NULL)
+ return NULL;
+
+ s_object = cache_struct(fmt);
+ if (s_object == NULL) {
+ Py_DECREF(newargs);
+ return NULL;
+ }
+ result = s_pack(s_object, newargs);
+ Py_DECREF(newargs);
+ Py_DECREF(s_object);
+ return result;
}
PyDoc_STRVAR(pack_into_doc,
@@ -1836,27 +1836,27 @@ Write the packed bytes into the writable buffer buf starting at offset.");
static PyObject *
pack_into(PyObject *self, PyObject *args)
{
- PyObject *s_object, *fmt, *newargs, *result;
- Py_ssize_t n = PyTuple_GET_SIZE(args);
-
- if (n == 0) {
- PyErr_SetString(PyExc_TypeError, "missing format argument");
- return NULL;
- }
- fmt = PyTuple_GET_ITEM(args, 0);
- newargs = PyTuple_GetSlice(args, 1, n);
- if (newargs == NULL)
- return NULL;
-
- s_object = cache_struct(fmt);
- if (s_object == NULL) {
- Py_DECREF(newargs);
- return NULL;
- }
- result = s_pack_into(s_object, newargs);
- Py_DECREF(newargs);
- Py_DECREF(s_object);
- return result;
+ PyObject *s_object, *fmt, *newargs, *result;
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+
+ if (n == 0) {
+ PyErr_SetString(PyExc_TypeError, "missing format argument");
+ return NULL;
+ }
+ fmt = PyTuple_GET_ITEM(args, 0);
+ newargs = PyTuple_GetSlice(args, 1, n);
+ if (newargs == NULL)
+ return NULL;
+
+ s_object = cache_struct(fmt);
+ if (s_object == NULL) {
+ Py_DECREF(newargs);
+ return NULL;
+ }
+ result = s_pack_into(s_object, newargs);
+ Py_DECREF(newargs);
+ Py_DECREF(s_object);
+ return result;
}
PyDoc_STRVAR(unpack_doc,
@@ -1866,17 +1866,17 @@ Requires len(string) == calcsize(fmt).");
static PyObject *
unpack(PyObject *self, PyObject *args)
{
- PyObject *s_object, *fmt, *inputstr, *result;
+ PyObject *s_object, *fmt, *inputstr, *result;
- if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "unpack", 2, 2, &fmt, &inputstr))
+ return NULL;
- s_object = cache_struct(fmt);
- if (s_object == NULL)
- return NULL;
- result = s_unpack(s_object, inputstr);
- Py_DECREF(s_object);
- return result;
+ s_object = cache_struct(fmt);
+ if (s_object == NULL)
+ return NULL;
+ result = s_unpack(s_object, inputstr);
+ Py_DECREF(s_object);
+ return result;
}
PyDoc_STRVAR(unpack_from_doc,
@@ -1886,38 +1886,38 @@ fmt, starting at offset. Requires len(buffer[offset:]) >= calcsize(fmt).");
static PyObject *
unpack_from(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *s_object, *fmt, *newargs, *result;
- Py_ssize_t n = PyTuple_GET_SIZE(args);
-
- if (n == 0) {
- PyErr_SetString(PyExc_TypeError, "missing format argument");
- return NULL;
- }
- fmt = PyTuple_GET_ITEM(args, 0);
- newargs = PyTuple_GetSlice(args, 1, n);
- if (newargs == NULL)
- return NULL;
-
- s_object = cache_struct(fmt);
- if (s_object == NULL) {
- Py_DECREF(newargs);
- return NULL;
- }
- result = s_unpack_from(s_object, newargs, kwds);
- Py_DECREF(newargs);
- Py_DECREF(s_object);
- return result;
+ PyObject *s_object, *fmt, *newargs, *result;
+ Py_ssize_t n = PyTuple_GET_SIZE(args);
+
+ if (n == 0) {
+ PyErr_SetString(PyExc_TypeError, "missing format argument");
+ return NULL;
+ }
+ fmt = PyTuple_GET_ITEM(args, 0);
+ newargs = PyTuple_GetSlice(args, 1, n);
+ if (newargs == NULL)
+ return NULL;
+
+ s_object = cache_struct(fmt);
+ if (s_object == NULL) {
+ Py_DECREF(newargs);
+ return NULL;
+ }
+ result = s_unpack_from(s_object, newargs, kwds);
+ Py_DECREF(newargs);
+ Py_DECREF(s_object);
+ return result;
}
static struct PyMethodDef module_functions[] = {
- {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
- {"calcsize", calcsize, METH_O, calcsize_doc},
- {"pack", pack, METH_VARARGS, pack_doc},
- {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
- {"unpack", unpack, METH_VARARGS, unpack_doc},
- {"unpack_from", (PyCFunction)unpack_from,
- METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
- {NULL, NULL} /* sentinel */
+ {"_clearcache", (PyCFunction)clearcache, METH_NOARGS, clearcache_doc},
+ {"calcsize", calcsize, METH_O, calcsize_doc},
+ {"pack", pack, METH_VARARGS, pack_doc},
+ {"pack_into", pack_into, METH_VARARGS, pack_into_doc},
+ {"unpack", unpack, METH_VARARGS, unpack_doc},
+ {"unpack_from", (PyCFunction)unpack_from,
+ METH_VARARGS|METH_KEYWORDS, unpack_from_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1955,78 +1955,78 @@ The variable struct.error is an exception raised on errors.\n");
PyMODINIT_FUNC
init_struct(void)
{
- PyObject *ver, *m;
-
- ver = PyString_FromString("0.2");
- if (ver == NULL)
- return;
-
- m = Py_InitModule3("_struct", module_functions, module_doc);
- if (m == NULL)
- return;
-
- Py_TYPE(&PyStructType) = &PyType_Type;
- if (PyType_Ready(&PyStructType) < 0)
- return;
-
- /* This speed trick can't be used until overflow masking goes
- away, because native endian always raises exceptions
- instead of overflow masking. */
-
- /* Check endian and swap in faster functions */
- {
- int one = 1;
- formatdef *native = native_table;
- formatdef *other, *ptr;
- if ((int)*(unsigned char*)&one)
- other = lilendian_table;
- else
- other = bigendian_table;
- /* Scan through the native table, find a matching
- entry in the endian table and swap in the
- native implementations whenever possible
- (64-bit platforms may not have "standard" sizes) */
- while (native->format != '\0' && other->format != '\0') {
- ptr = other;
- while (ptr->format != '\0') {
- if (ptr->format == native->format) {
- /* Match faster when formats are
- listed in the same order */
- if (ptr == other)
- other++;
- /* Only use the trick if the
- size matches */
- if (ptr->size != native->size)
- break;
- /* Skip float and double, could be
- "unknown" float format */
- if (ptr->format == 'd' || ptr->format == 'f')
- break;
- ptr->pack = native->pack;
- ptr->unpack = native->unpack;
- break;
- }
- ptr++;
- }
- native++;
- }
- }
-
- /* Add some symbolic constants to the module */
- if (StructError == NULL) {
- StructError = PyErr_NewException("struct.error", NULL, NULL);
- if (StructError == NULL)
- return;
- }
-
- Py_INCREF(StructError);
- PyModule_AddObject(m, "error", StructError);
-
- Py_INCREF((PyObject*)&PyStructType);
- PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
-
- PyModule_AddObject(m, "__version__", ver);
-
- PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
- PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
+ PyObject *ver, *m;
+
+ ver = PyString_FromString("0.2");
+ if (ver == NULL)
+ return;
+
+ m = Py_InitModule3("_struct", module_functions, module_doc);
+ if (m == NULL)
+ return;
+
+ Py_TYPE(&PyStructType) = &PyType_Type;
+ if (PyType_Ready(&PyStructType) < 0)
+ return;
+
+ /* This speed trick can't be used until overflow masking goes
+ away, because native endian always raises exceptions
+ instead of overflow masking. */
+
+ /* Check endian and swap in faster functions */
+ {
+ int one = 1;
+ formatdef *native = native_table;
+ formatdef *other, *ptr;
+ if ((int)*(unsigned char*)&one)
+ other = lilendian_table;
+ else
+ other = bigendian_table;
+ /* Scan through the native table, find a matching
+ entry in the endian table and swap in the
+ native implementations whenever possible
+ (64-bit platforms may not have "standard" sizes) */
+ while (native->format != '\0' && other->format != '\0') {
+ ptr = other;
+ while (ptr->format != '\0') {
+ if (ptr->format == native->format) {
+ /* Match faster when formats are
+ listed in the same order */
+ if (ptr == other)
+ other++;
+ /* Only use the trick if the
+ size matches */
+ if (ptr->size != native->size)
+ break;
+ /* Skip float and double, could be
+ "unknown" float format */
+ if (ptr->format == 'd' || ptr->format == 'f')
+ break;
+ ptr->pack = native->pack;
+ ptr->unpack = native->unpack;
+ break;
+ }
+ ptr++;
+ }
+ native++;
+ }
+ }
+
+ /* Add some symbolic constants to the module */
+ if (StructError == NULL) {
+ StructError = PyErr_NewException("struct.error", NULL, NULL);
+ if (StructError == NULL)
+ return;
+ }
+
+ Py_INCREF(StructError);
+ PyModule_AddObject(m, "error", StructError);
+
+ Py_INCREF((PyObject*)&PyStructType);
+ PyModule_AddObject(m, "Struct", (PyObject*)&PyStructType);
+
+ PyModule_AddObject(m, "__version__", ver);
+
+ PyModule_AddIntConstant(m, "_PY_STRUCT_RANGE_CHECKING", 1);
+ PyModule_AddIntConstant(m, "_PY_STRUCT_FLOAT_COERCE", 1);
}
diff --git a/Modules/_testcapimodule.c b/Modules/_testcapimodule.c
index 31425d1..23a5691 100644
--- a/Modules/_testcapimodule.c
+++ b/Modules/_testcapimodule.c
@@ -13,22 +13,22 @@
#ifdef WITH_THREAD
#include "pythread.h"
#endif /* WITH_THREAD */
-static PyObject *TestError; /* set to exception object in init */
+static PyObject *TestError; /* set to exception object in init */
/* Raise TestError with test_name + ": " + msg, and return NULL. */
static PyObject *
raiseTestError(const char* test_name, const char* msg)
{
- char buf[2048];
-
- if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
- PyErr_SetString(TestError, "internal error msg too large");
- else {
- PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
- PyErr_SetString(TestError, buf);
- }
- return NULL;
+ char buf[2048];
+
+ if (strlen(test_name) + strlen(msg) > sizeof(buf) - 50)
+ PyErr_SetString(TestError, "internal error msg too large");
+ else {
+ PyOS_snprintf(buf, sizeof(buf), "%s: %s", test_name, msg);
+ PyErr_SetString(TestError, buf);
+ }
+ return NULL;
}
/* Test #defines from pyconfig.h (particularly the SIZEOF_* defines).
@@ -39,138 +39,138 @@ raiseTestError(const char* test_name, const char* msg)
*/
static PyObject*
sizeof_error(const char* fatname, const char* typname,
- int expected, int got)
+ int expected, int got)
{
- char buf[1024];
- PyOS_snprintf(buf, sizeof(buf),
- "%.200s #define == %d but sizeof(%.200s) == %d",
- fatname, expected, typname, got);
- PyErr_SetString(TestError, buf);
- return (PyObject*)NULL;
+ char buf[1024];
+ PyOS_snprintf(buf, sizeof(buf),
+ "%.200s #define == %d but sizeof(%.200s) == %d",
+ fatname, expected, typname, got);
+ PyErr_SetString(TestError, buf);
+ return (PyObject*)NULL;
}
static PyObject*
test_config(PyObject *self)
{
#define CHECK_SIZEOF(FATNAME, TYPE) \
- if (FATNAME != sizeof(TYPE)) \
- return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
-
- CHECK_SIZEOF(SIZEOF_SHORT, short);
- CHECK_SIZEOF(SIZEOF_INT, int);
- CHECK_SIZEOF(SIZEOF_LONG, long);
- CHECK_SIZEOF(SIZEOF_VOID_P, void*);
- CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
+ if (FATNAME != sizeof(TYPE)) \
+ return sizeof_error(#FATNAME, #TYPE, FATNAME, sizeof(TYPE))
+
+ CHECK_SIZEOF(SIZEOF_SHORT, short);
+ CHECK_SIZEOF(SIZEOF_INT, int);
+ CHECK_SIZEOF(SIZEOF_LONG, long);
+ CHECK_SIZEOF(SIZEOF_VOID_P, void*);
+ CHECK_SIZEOF(SIZEOF_TIME_T, time_t);
#ifdef HAVE_LONG_LONG
- CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
+ CHECK_SIZEOF(SIZEOF_LONG_LONG, PY_LONG_LONG);
#endif
#undef CHECK_SIZEOF
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject*
test_list_api(PyObject *self)
{
- PyObject* list;
- int i;
+ PyObject* list;
+ int i;
- /* SF bug 132008: PyList_Reverse segfaults */
+ /* SF bug 132008: PyList_Reverse segfaults */
#define NLIST 30
- list = PyList_New(NLIST);
- if (list == (PyObject*)NULL)
- return (PyObject*)NULL;
- /* list = range(NLIST) */
- for (i = 0; i < NLIST; ++i) {
- PyObject* anint = PyInt_FromLong(i);
- if (anint == (PyObject*)NULL) {
- Py_DECREF(list);
- return (PyObject*)NULL;
- }
- PyList_SET_ITEM(list, i, anint);
- }
- /* list.reverse(), via PyList_Reverse() */
- i = PyList_Reverse(list); /* should not blow up! */
- if (i != 0) {
- Py_DECREF(list);
- return (PyObject*)NULL;
- }
- /* Check that list == range(29, -1, -1) now */
- for (i = 0; i < NLIST; ++i) {
- PyObject* anint = PyList_GET_ITEM(list, i);
- if (PyInt_AS_LONG(anint) != NLIST-1-i) {
- PyErr_SetString(TestError,
- "test_list_api: reverse screwed up");
- Py_DECREF(list);
- return (PyObject*)NULL;
- }
- }
- Py_DECREF(list);
+ list = PyList_New(NLIST);
+ if (list == (PyObject*)NULL)
+ return (PyObject*)NULL;
+ /* list = range(NLIST) */
+ for (i = 0; i < NLIST; ++i) {
+ PyObject* anint = PyInt_FromLong(i);
+ if (anint == (PyObject*)NULL) {
+ Py_DECREF(list);
+ return (PyObject*)NULL;
+ }
+ PyList_SET_ITEM(list, i, anint);
+ }
+ /* list.reverse(), via PyList_Reverse() */
+ i = PyList_Reverse(list); /* should not blow up! */
+ if (i != 0) {
+ Py_DECREF(list);
+ return (PyObject*)NULL;
+ }
+ /* Check that list == range(29, -1, -1) now */
+ for (i = 0; i < NLIST; ++i) {
+ PyObject* anint = PyList_GET_ITEM(list, i);
+ if (PyInt_AS_LONG(anint) != NLIST-1-i) {
+ PyErr_SetString(TestError,
+ "test_list_api: reverse screwed up");
+ Py_DECREF(list);
+ return (PyObject*)NULL;
+ }
+ }
+ Py_DECREF(list);
#undef NLIST
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static int
test_dict_inner(int count)
{
- Py_ssize_t pos = 0, iterations = 0;
- int i;
- PyObject *dict = PyDict_New();
- PyObject *v, *k;
-
- if (dict == NULL)
- return -1;
-
- for (i = 0; i < count; i++) {
- v = PyInt_FromLong(i);
- PyDict_SetItem(dict, v, v);
- Py_DECREF(v);
- }
-
- while (PyDict_Next(dict, &pos, &k, &v)) {
- PyObject *o;
- iterations++;
-
- i = PyInt_AS_LONG(v) + 1;
- o = PyInt_FromLong(i);
- if (o == NULL)
- return -1;
- if (PyDict_SetItem(dict, k, o) < 0) {
- Py_DECREF(o);
- return -1;
- }
- Py_DECREF(o);
- }
-
- Py_DECREF(dict);
-
- if (iterations != count) {
- PyErr_SetString(
- TestError,
- "test_dict_iteration: dict iteration went wrong ");
- return -1;
- } else {
- return 0;
- }
+ Py_ssize_t pos = 0, iterations = 0;
+ int i;
+ PyObject *dict = PyDict_New();
+ PyObject *v, *k;
+
+ if (dict == NULL)
+ return -1;
+
+ for (i = 0; i < count; i++) {
+ v = PyInt_FromLong(i);
+ PyDict_SetItem(dict, v, v);
+ Py_DECREF(v);
+ }
+
+ while (PyDict_Next(dict, &pos, &k, &v)) {
+ PyObject *o;
+ iterations++;
+
+ i = PyInt_AS_LONG(v) + 1;
+ o = PyInt_FromLong(i);
+ if (o == NULL)
+ return -1;
+ if (PyDict_SetItem(dict, k, o) < 0) {
+ Py_DECREF(o);
+ return -1;
+ }
+ Py_DECREF(o);
+ }
+
+ Py_DECREF(dict);
+
+ if (iterations != count) {
+ PyErr_SetString(
+ TestError,
+ "test_dict_iteration: dict iteration went wrong ");
+ return -1;
+ } else {
+ return 0;
+ }
}
static PyObject*
test_dict_iteration(PyObject* self)
{
- int i;
+ int i;
- for (i = 0; i < 200; i++) {
- if (test_dict_inner(i) < 0) {
- return NULL;
- }
- }
+ for (i = 0; i < 200; i++) {
+ if (test_dict_inner(i) < 0) {
+ return NULL;
+ }
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -178,108 +178,108 @@ test_dict_iteration(PyObject* self)
* PyType_Ready if it hasn't already been called
*/
static PyTypeObject _HashInheritanceTester_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* Number of items for varobject */
- "hashinheritancetester", /* Name of this type */
- sizeof(PyObject), /* Basic object size */
- 0, /* Item size for varobject */
- (destructor)PyObject_Del, /* 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 */
- 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* Number of items for varobject */
+ "hashinheritancetester", /* Name of this type */
+ sizeof(PyObject), /* Basic object size */
+ 0, /* Item size for varobject */
+ (destructor)PyObject_Del, /* 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 */
+ 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
};
static PyObject*
test_lazy_hash_inheritance(PyObject* self)
{
- PyTypeObject *type;
- PyObject *obj;
- long hash;
-
- type = &_HashInheritanceTester_Type;
-
- if (type->tp_dict != NULL)
- /* The type has already been initialized. This probably means
- -R is being used. */
- Py_RETURN_NONE;
-
-
- obj = PyObject_New(PyObject, type);
- if (obj == NULL) {
- PyErr_Clear();
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: failed to create object");
- return NULL;
- }
-
- if (type->tp_dict != NULL) {
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: type initialised too soon");
- Py_DECREF(obj);
- return NULL;
- }
-
- hash = PyObject_Hash(obj);
- if ((hash == -1) && PyErr_Occurred()) {
- PyErr_Clear();
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: could not hash object");
- Py_DECREF(obj);
- return NULL;
- }
-
- if (type->tp_dict == NULL) {
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: type not initialised by hash()");
- Py_DECREF(obj);
- return NULL;
- }
-
- if (type->tp_hash != PyType_Type.tp_hash) {
- PyErr_SetString(
- TestError,
- "test_lazy_hash_inheritance: unexpected hash function");
- Py_DECREF(obj);
- return NULL;
- }
-
- Py_DECREF(obj);
-
- Py_RETURN_NONE;
+ PyTypeObject *type;
+ PyObject *obj;
+ long hash;
+
+ type = &_HashInheritanceTester_Type;
+
+ if (type->tp_dict != NULL)
+ /* The type has already been initialized. This probably means
+ -R is being used. */
+ Py_RETURN_NONE;
+
+
+ obj = PyObject_New(PyObject, type);
+ if (obj == NULL) {
+ PyErr_Clear();
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: failed to create object");
+ return NULL;
+ }
+
+ if (type->tp_dict != NULL) {
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: type initialised too soon");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ hash = PyObject_Hash(obj);
+ if ((hash == -1) && PyErr_Occurred()) {
+ PyErr_Clear();
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: could not hash object");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ if (type->tp_dict == NULL) {
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: type not initialised by hash()");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ if (type->tp_hash != PyType_Type.tp_hash) {
+ PyErr_SetString(
+ TestError,
+ "test_lazy_hash_inheritance: unexpected hash function");
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ Py_DECREF(obj);
+
+ Py_RETURN_NONE;
}
@@ -290,90 +290,90 @@ test_lazy_hash_inheritance(PyObject* self)
static int
broken_buffer_getbuffer(PyObject *self, Py_buffer *view, int flags)
{
- PyErr_SetString(
- TestError,
- "test_broken_memoryview: expected error in bf_getbuffer");
- return -1;
+ PyErr_SetString(
+ TestError,
+ "test_broken_memoryview: expected error in bf_getbuffer");
+ return -1;
}
static PyBufferProcs memoryviewtester_as_buffer = {
- 0, /* bf_getreadbuffer */
- 0, /* bf_getwritebuffer */
- 0, /* bf_getsegcount */
- 0, /* bf_getcharbuffer */
- (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
- 0, /* bf_releasebuffer */
+ 0, /* bf_getreadbuffer */
+ 0, /* bf_getwritebuffer */
+ 0, /* bf_getsegcount */
+ 0, /* bf_getcharbuffer */
+ (getbufferproc)broken_buffer_getbuffer, /* bf_getbuffer */
+ 0, /* bf_releasebuffer */
};
static PyTypeObject _MemoryViewTester_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /* Number of items for varobject */
- "memoryviewtester", /* Name of this type */
- sizeof(PyObject), /* Basic object size */
- 0, /* Item size for varobject */
- (destructor)PyObject_Del, /* 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 */
- &memoryviewtester_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER, /* 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* Number of items for varobject */
+ "memoryviewtester", /* Name of this type */
+ sizeof(PyObject), /* Basic object size */
+ 0, /* Item size for varobject */
+ (destructor)PyObject_Del, /* 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 */
+ &memoryviewtester_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_NEWBUFFER, /* 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
};
static PyObject*
test_broken_memoryview(PyObject* self)
{
- PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
- PyObject *res;
-
- if (obj == NULL) {
- PyErr_Clear();
- PyErr_SetString(
- TestError,
- "test_broken_memoryview: failed to create object");
- return NULL;
- }
-
- res = PyMemoryView_FromObject(obj);
- if (res || !PyErr_Occurred()){
- PyErr_SetString(
- TestError,
- "test_broken_memoryview: memoryview() didn't raise an Exception");
- Py_XDECREF(res);
- Py_DECREF(obj);
- return NULL;
- }
-
- PyErr_Clear();
- Py_DECREF(obj);
- Py_RETURN_NONE;
+ PyObject *obj = PyObject_New(PyObject, &_MemoryViewTester_Type);
+ PyObject *res;
+
+ if (obj == NULL) {
+ PyErr_Clear();
+ PyErr_SetString(
+ TestError,
+ "test_broken_memoryview: failed to create object");
+ return NULL;
+ }
+
+ res = PyMemoryView_FromObject(obj);
+ if (res || !PyErr_Occurred()){
+ PyErr_SetString(
+ TestError,
+ "test_broken_memoryview: memoryview() didn't raise an Exception");
+ Py_XDECREF(res);
+ Py_DECREF(obj);
+ return NULL;
+ }
+
+ PyErr_Clear();
+ Py_DECREF(obj);
+ Py_RETURN_NONE;
}
@@ -397,22 +397,22 @@ test_broken_memoryview(PyObject* self)
static PyObject *
raise_test_long_error(const char* msg)
{
- return raiseTestError("test_long_api", msg);
+ return raiseTestError("test_long_api", msg);
}
-#define TESTNAME test_long_api_inner
-#define TYPENAME long
-#define F_S_TO_PY PyLong_FromLong
-#define F_PY_TO_S PyLong_AsLong
-#define F_U_TO_PY PyLong_FromUnsignedLong
-#define F_PY_TO_U PyLong_AsUnsignedLong
+#define TESTNAME test_long_api_inner
+#define TYPENAME long
+#define F_S_TO_PY PyLong_FromLong
+#define F_PY_TO_S PyLong_AsLong
+#define F_U_TO_PY PyLong_FromUnsignedLong
+#define F_PY_TO_U PyLong_AsUnsignedLong
#include "testcapi_long.h"
static PyObject *
test_long_api(PyObject* self)
{
- return TESTNAME(raise_test_long_error);
+ return TESTNAME(raise_test_long_error);
}
#undef TESTNAME
@@ -427,22 +427,22 @@ test_long_api(PyObject* self)
static PyObject *
raise_test_longlong_error(const char* msg)
{
- return raiseTestError("test_longlong_api", msg);
+ return raiseTestError("test_longlong_api", msg);
}
-#define TESTNAME test_longlong_api_inner
-#define TYPENAME PY_LONG_LONG
-#define F_S_TO_PY PyLong_FromLongLong
-#define F_PY_TO_S PyLong_AsLongLong
-#define F_U_TO_PY PyLong_FromUnsignedLongLong
-#define F_PY_TO_U PyLong_AsUnsignedLongLong
+#define TESTNAME test_longlong_api_inner
+#define TYPENAME PY_LONG_LONG
+#define F_S_TO_PY PyLong_FromLongLong
+#define F_PY_TO_S PyLong_AsLongLong
+#define F_U_TO_PY PyLong_FromUnsignedLongLong
+#define F_PY_TO_U PyLong_AsUnsignedLongLong
#include "testcapi_long.h"
static PyObject *
test_longlong_api(PyObject* self, PyObject *args)
{
- return TESTNAME(raise_test_longlong_error);
+ return TESTNAME(raise_test_longlong_error);
}
#undef TESTNAME
@@ -460,161 +460,161 @@ test_longlong_api(PyObject* self, PyObject *args)
static PyObject *
test_long_and_overflow(PyObject *self)
{
- PyObject *num, *one, *temp;
- long value;
- int overflow;
-
- /* Test that overflow is set properly for a large value. */
- /* num is a number larger than LONG_MAX even on 64-bit platforms */
- num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to 1");
-
- /* Same again, with num = LONG_MAX + 1 */
- num = PyLong_FromLong(LONG_MAX);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Add(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to 1");
-
- /* Test that overflow is set properly for a large negative value. */
- /* num is a number smaller than LONG_MIN even on 64-bit platforms */
- num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to -1");
-
- /* Same again, with num = LONG_MIN - 1 */
- num = PyLong_FromLong(LONG_MIN);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Subtract(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_and_overflow",
- "overflow was not set to -1");
-
- /* Test that overflow is cleared properly for small values. */
- num = PyLong_FromString("FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != 0xFF)
- return raiseTestError("test_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromString("-FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -0xFF)
- return raiseTestError("test_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was set incorrectly");
-
- num = PyLong_FromLong(LONG_MAX);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != LONG_MAX)
- return raiseTestError("test_long_and_overflow",
- "expected return value LONG_MAX");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromLong(LONG_MIN);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != LONG_MIN)
- return raiseTestError("test_long_and_overflow",
- "expected return value LONG_MIN");
- if (overflow != 0)
- return raiseTestError("test_long_and_overflow",
- "overflow was not cleared");
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *num, *one, *temp;
+ long value;
+ int overflow;
+
+ /* Test that overflow is set properly for a large value. */
+ /* num is a number larger than LONG_MAX even on 64-bit platforms */
+ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Same again, with num = LONG_MAX + 1 */
+ num = PyLong_FromLong(LONG_MAX);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Add(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Test that overflow is set properly for a large negative value. */
+ /* num is a number smaller than LONG_MIN even on 64-bit platforms */
+ num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Same again, with num = LONG_MIN - 1 */
+ num = PyLong_FromLong(LONG_MIN);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Subtract(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Test that overflow is cleared properly for small values. */
+ num = PyLong_FromString("FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != 0xFF)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromString("-FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -0xFF)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was set incorrectly");
+
+ num = PyLong_FromLong(LONG_MAX);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != LONG_MAX)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value LONG_MAX");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromLong(LONG_MIN);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != LONG_MIN)
+ return raiseTestError("test_long_and_overflow",
+ "expected return value LONG_MIN");
+ if (overflow != 0)
+ return raiseTestError("test_long_and_overflow",
+ "overflow was not cleared");
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test the PyLong_AsLongLongAndOverflow API. General conversion to
@@ -625,161 +625,161 @@ test_long_and_overflow(PyObject *self)
static PyObject *
test_long_long_and_overflow(PyObject *self)
{
- PyObject *num, *one, *temp;
- PY_LONG_LONG value;
- int overflow;
-
- /* Test that overflow is set properly for a large value. */
- /* num is a number larger than PY_LLONG_MAX on a typical machine. */
- num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to 1");
-
- /* Same again, with num = PY_LLONG_MAX + 1 */
- num = PyLong_FromLongLong(PY_LLONG_MAX);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Add(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != 1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to 1");
-
- /* Test that overflow is set properly for a large negative value. */
- /* num is a number smaller than PY_LLONG_MIN on a typical platform */
- num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to -1");
-
- /* Same again, with num = PY_LLONG_MIN - 1 */
- num = PyLong_FromLongLong(PY_LLONG_MIN);
- if (num == NULL)
- return NULL;
- one = PyLong_FromLong(1L);
- if (one == NULL) {
- Py_DECREF(num);
- return NULL;
- }
- temp = PyNumber_Subtract(num, one);
- Py_DECREF(one);
- Py_DECREF(num);
- num = temp;
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -1)
- return raiseTestError("test_long_long_and_overflow",
- "return value was not set to -1");
- if (overflow != -1)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not set to -1");
-
- /* Test that overflow is cleared properly for small values. */
- num = PyLong_FromString("FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != 0xFF)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromString("-FF", NULL, 16);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != -0xFF)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value 0xFF");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was set incorrectly");
-
- num = PyLong_FromLongLong(PY_LLONG_MAX);
- if (num == NULL)
- return NULL;
- overflow = 1234;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != PY_LLONG_MAX)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value PY_LLONG_MAX");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not cleared");
-
- num = PyLong_FromLongLong(PY_LLONG_MIN);
- if (num == NULL)
- return NULL;
- overflow = 0;
- value = PyLong_AsLongLongAndOverflow(num, &overflow);
- Py_DECREF(num);
- if (value == -1 && PyErr_Occurred())
- return NULL;
- if (value != PY_LLONG_MIN)
- return raiseTestError("test_long_long_and_overflow",
- "expected return value PY_LLONG_MIN");
- if (overflow != 0)
- return raiseTestError("test_long_long_and_overflow",
- "overflow was not cleared");
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *num, *one, *temp;
+ PY_LONG_LONG value;
+ int overflow;
+
+ /* Test that overflow is set properly for a large value. */
+ /* num is a number larger than PY_LLONG_MAX on a typical machine. */
+ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Same again, with num = PY_LLONG_MAX + 1 */
+ num = PyLong_FromLongLong(PY_LLONG_MAX);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Add(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != 1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to 1");
+
+ /* Test that overflow is set properly for a large negative value. */
+ /* num is a number smaller than PY_LLONG_MIN on a typical platform */
+ num = PyLong_FromString("-FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Same again, with num = PY_LLONG_MIN - 1 */
+ num = PyLong_FromLongLong(PY_LLONG_MIN);
+ if (num == NULL)
+ return NULL;
+ one = PyLong_FromLong(1L);
+ if (one == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+ temp = PyNumber_Subtract(num, one);
+ Py_DECREF(one);
+ Py_DECREF(num);
+ num = temp;
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "return value was not set to -1");
+ if (overflow != -1)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not set to -1");
+
+ /* Test that overflow is cleared properly for small values. */
+ num = PyLong_FromString("FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != 0xFF)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromString("-FF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != -0xFF)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value 0xFF");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was set incorrectly");
+
+ num = PyLong_FromLongLong(PY_LLONG_MAX);
+ if (num == NULL)
+ return NULL;
+ overflow = 1234;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != PY_LLONG_MAX)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value PY_LLONG_MAX");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not cleared");
+
+ num = PyLong_FromLongLong(PY_LLONG_MIN);
+ if (num == NULL)
+ return NULL;
+ overflow = 0;
+ value = PyLong_AsLongLongAndOverflow(num, &overflow);
+ Py_DECREF(num);
+ if (value == -1 && PyErr_Occurred())
+ return NULL;
+ if (value != PY_LLONG_MIN)
+ return raiseTestError("test_long_long_and_overflow",
+ "expected return value PY_LLONG_MIN");
+ if (overflow != 0)
+ return raiseTestError("test_long_long_and_overflow",
+ "overflow was not cleared");
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test the L code for PyArg_ParseTuple. This should deliver a PY_LONG_LONG
@@ -789,71 +789,71 @@ test_long_long_and_overflow(PyObject *self)
static PyObject *
test_L_code(PyObject *self)
{
- PyObject *tuple, *num;
- PY_LONG_LONG value;
-
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
-
- num = PyLong_FromLong(42);
- if (num == NULL)
- return NULL;
-
- PyTuple_SET_ITEM(tuple, 0, num);
-
- value = -1;
- if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
- return NULL;
- if (value != 42)
- return raiseTestError("test_L_code",
- "L code returned wrong value for long 42");
-
- Py_DECREF(num);
- num = PyInt_FromLong(42);
- if (num == NULL)
- return NULL;
-
- PyTuple_SET_ITEM(tuple, 0, num);
-
- value = -1;
- if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
- return NULL;
- if (value != 42)
- return raiseTestError("test_L_code",
- "L code returned wrong value for int 42");
-
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *tuple, *num;
+ PY_LONG_LONG value;
+
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
+
+ num = PyLong_FromLong(42);
+ if (num == NULL)
+ return NULL;
+
+ PyTuple_SET_ITEM(tuple, 0, num);
+
+ value = -1;
+ if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
+ return NULL;
+ if (value != 42)
+ return raiseTestError("test_L_code",
+ "L code returned wrong value for long 42");
+
+ Py_DECREF(num);
+ num = PyInt_FromLong(42);
+ if (num == NULL)
+ return NULL;
+
+ PyTuple_SET_ITEM(tuple, 0, num);
+
+ value = -1;
+ if (PyArg_ParseTuple(tuple, "L:test_L_code", &value) < 0)
+ return NULL;
+ if (value != 42)
+ return raiseTestError("test_L_code",
+ "L code returned wrong value for int 42");
+
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
-#endif /* ifdef HAVE_LONG_LONG */
+#endif /* ifdef HAVE_LONG_LONG */
/* Test tuple argument processing */
static PyObject *
getargs_tuple(PyObject *self, PyObject *args)
{
- int a, b, c;
- if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
- return NULL;
- return Py_BuildValue("iii", a, b, c);
+ int a, b, c;
+ if (!PyArg_ParseTuple(args, "i(ii)", &a, &b, &c))
+ return NULL;
+ return Py_BuildValue("iii", a, b, c);
}
/* test PyArg_ParseTupleAndKeywords */
static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwargs)
{
- static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
- static char *fmt="(ii)i|(i(ii))(iii)i";
- int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
- &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
- &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
- return NULL;
- return Py_BuildValue("iiiiiiiiii",
- int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
- int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
+ static char *keywords[] = {"arg1","arg2","arg3","arg4","arg5", NULL};
+ static char *fmt="(ii)i|(i(ii))(iii)i";
+ int int_args[10]={-1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
+ &int_args[0], &int_args[1], &int_args[2], &int_args[3], &int_args[4],
+ &int_args[5], &int_args[6], &int_args[7], &int_args[8], &int_args[9]))
+ return NULL;
+ return Py_BuildValue("iiiiiiiiii",
+ int_args[0], int_args[1], int_args[2], int_args[3], int_args[4],
+ int_args[5], int_args[6], int_args[7], int_args[8], int_args[9]);
}
/* Functions to call PyArg_ParseTuple with integer format codes,
@@ -862,101 +862,101 @@ static PyObject *getargs_keywords(PyObject *self, PyObject *args, PyObject *kwar
static PyObject *
getargs_b(PyObject *self, PyObject *args)
{
- unsigned char value;
- if (!PyArg_ParseTuple(args, "b", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned char value;
+ if (!PyArg_ParseTuple(args, "b", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_B(PyObject *self, PyObject *args)
{
- unsigned char value;
- if (!PyArg_ParseTuple(args, "B", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned char value;
+ if (!PyArg_ParseTuple(args, "B", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_h(PyObject *self, PyObject *args)
{
- short value;
- if (!PyArg_ParseTuple(args, "h", &value))
- return NULL;
- return PyLong_FromLong((long)value);
+ short value;
+ if (!PyArg_ParseTuple(args, "h", &value))
+ return NULL;
+ return PyLong_FromLong((long)value);
}
static PyObject *
getargs_H(PyObject *self, PyObject *args)
{
- unsigned short value;
- if (!PyArg_ParseTuple(args, "H", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned short value;
+ if (!PyArg_ParseTuple(args, "H", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_I(PyObject *self, PyObject *args)
{
- unsigned int value;
- if (!PyArg_ParseTuple(args, "I", &value))
- return NULL;
- return PyLong_FromUnsignedLong((unsigned long)value);
+ unsigned int value;
+ if (!PyArg_ParseTuple(args, "I", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong((unsigned long)value);
}
static PyObject *
getargs_k(PyObject *self, PyObject *args)
{
- unsigned long value;
- if (!PyArg_ParseTuple(args, "k", &value))
- return NULL;
- return PyLong_FromUnsignedLong(value);
+ unsigned long value;
+ if (!PyArg_ParseTuple(args, "k", &value))
+ return NULL;
+ return PyLong_FromUnsignedLong(value);
}
static PyObject *
getargs_i(PyObject *self, PyObject *args)
{
- int value;
- if (!PyArg_ParseTuple(args, "i", &value))
- return NULL;
- return PyLong_FromLong((long)value);
+ int value;
+ if (!PyArg_ParseTuple(args, "i", &value))
+ return NULL;
+ return PyLong_FromLong((long)value);
}
static PyObject *
getargs_l(PyObject *self, PyObject *args)
{
- long value;
- if (!PyArg_ParseTuple(args, "l", &value))
- return NULL;
- return PyLong_FromLong(value);
+ long value;
+ if (!PyArg_ParseTuple(args, "l", &value))
+ return NULL;
+ return PyLong_FromLong(value);
}
static PyObject *
getargs_n(PyObject *self, PyObject *args)
{
- Py_ssize_t value;
- if (!PyArg_ParseTuple(args, "n", &value))
- return NULL;
- return PyInt_FromSsize_t(value);
+ Py_ssize_t value;
+ if (!PyArg_ParseTuple(args, "n", &value))
+ return NULL;
+ return PyInt_FromSsize_t(value);
}
#ifdef HAVE_LONG_LONG
static PyObject *
getargs_L(PyObject *self, PyObject *args)
{
- PY_LONG_LONG value;
- if (!PyArg_ParseTuple(args, "L", &value))
- return NULL;
- return PyLong_FromLongLong(value);
+ PY_LONG_LONG value;
+ if (!PyArg_ParseTuple(args, "L", &value))
+ return NULL;
+ return PyLong_FromLongLong(value);
}
static PyObject *
getargs_K(PyObject *self, PyObject *args)
{
- unsigned PY_LONG_LONG value;
- if (!PyArg_ParseTuple(args, "K", &value))
- return NULL;
- return PyLong_FromUnsignedLongLong(value);
+ unsigned PY_LONG_LONG value;
+ if (!PyArg_ParseTuple(args, "K", &value))
+ return NULL;
+ return PyLong_FromUnsignedLongLong(value);
}
#endif
@@ -965,54 +965,54 @@ getargs_K(PyObject *self, PyObject *args)
static PyObject *
test_k_code(PyObject *self)
{
- PyObject *tuple, *num;
- unsigned long value;
-
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
-
- /* a number larger than ULONG_MAX even on 64-bit platforms */
- num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
- if (num == NULL)
- return NULL;
-
- value = PyInt_AsUnsignedLongMask(num);
- if (value != ULONG_MAX)
- return raiseTestError("test_k_code",
- "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
-
- PyTuple_SET_ITEM(tuple, 0, num);
-
- value = 0;
- if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
- return NULL;
- if (value != ULONG_MAX)
- return raiseTestError("test_k_code",
- "k code returned wrong value for long 0xFFF...FFF");
-
- Py_DECREF(num);
- num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
- if (num == NULL)
- return NULL;
-
- value = PyInt_AsUnsignedLongMask(num);
- if (value != (unsigned long)-0x42)
- return raiseTestError("test_k_code",
- "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
-
- PyTuple_SET_ITEM(tuple, 0, num);
-
- value = 0;
- if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
- return NULL;
- if (value != (unsigned long)-0x42)
- return raiseTestError("test_k_code",
- "k code returned wrong value for long -0xFFF..000042");
-
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *tuple, *num;
+ unsigned long value;
+
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
+
+ /* a number larger than ULONG_MAX even on 64-bit platforms */
+ num = PyLong_FromString("FFFFFFFFFFFFFFFFFFFFFFFF", NULL, 16);
+ if (num == NULL)
+ return NULL;
+
+ value = PyInt_AsUnsignedLongMask(num);
+ if (value != ULONG_MAX)
+ return raiseTestError("test_k_code",
+ "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
+
+ PyTuple_SET_ITEM(tuple, 0, num);
+
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
+ return NULL;
+ if (value != ULONG_MAX)
+ return raiseTestError("test_k_code",
+ "k code returned wrong value for long 0xFFF...FFF");
+
+ Py_DECREF(num);
+ num = PyLong_FromString("-FFFFFFFF000000000000000042", NULL, 16);
+ if (num == NULL)
+ return NULL;
+
+ value = PyInt_AsUnsignedLongMask(num);
+ if (value != (unsigned long)-0x42)
+ return raiseTestError("test_k_code",
+ "PyInt_AsUnsignedLongMask() returned wrong value for long 0xFFF...FFF");
+
+ PyTuple_SET_ITEM(tuple, 0, num);
+
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "k:test_k_code", &value) < 0)
+ return NULL;
+ if (value != (unsigned long)-0x42)
+ return raiseTestError("test_k_code",
+ "k code returned wrong value for long -0xFFF..000042");
+
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef Py_USING_UNICODE
@@ -1025,130 +1025,130 @@ static volatile int x;
static PyObject *
test_u_code(PyObject *self)
{
- PyObject *tuple, *obj;
- Py_UNICODE *value;
- int len;
-
- /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
- /* Just use the macro and check that it compiles */
- x = Py_UNICODE_ISSPACE(25);
-
- tuple = PyTuple_New(1);
- if (tuple == NULL)
- return NULL;
-
- obj = PyUnicode_Decode("test", strlen("test"),
- "ascii", NULL);
- if (obj == NULL)
- return NULL;
-
- PyTuple_SET_ITEM(tuple, 0, obj);
-
- value = 0;
- if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
- return NULL;
- if (value != PyUnicode_AS_UNICODE(obj))
- return raiseTestError("test_u_code",
- "u code returned wrong value for u'test'");
- value = 0;
- if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
- return NULL;
- if (value != PyUnicode_AS_UNICODE(obj) ||
- len != PyUnicode_GET_SIZE(obj))
- return raiseTestError("test_u_code",
- "u# code returned wrong values for u'test'");
-
- Py_DECREF(tuple);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *tuple, *obj;
+ Py_UNICODE *value;
+ int len;
+
+ /* issue4122: Undefined reference to _Py_ascii_whitespace on Windows */
+ /* Just use the macro and check that it compiles */
+ x = Py_UNICODE_ISSPACE(25);
+
+ tuple = PyTuple_New(1);
+ if (tuple == NULL)
+ return NULL;
+
+ obj = PyUnicode_Decode("test", strlen("test"),
+ "ascii", NULL);
+ if (obj == NULL)
+ return NULL;
+
+ PyTuple_SET_ITEM(tuple, 0, obj);
+
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "u:test_u_code", &value) < 0)
+ return NULL;
+ if (value != PyUnicode_AS_UNICODE(obj))
+ return raiseTestError("test_u_code",
+ "u code returned wrong value for u'test'");
+ value = 0;
+ if (PyArg_ParseTuple(tuple, "u#:test_u_code", &value, &len) < 0)
+ return NULL;
+ if (value != PyUnicode_AS_UNICODE(obj) ||
+ len != PyUnicode_GET_SIZE(obj))
+ return raiseTestError("test_u_code",
+ "u# code returned wrong values for u'test'");
+
+ Py_DECREF(tuple);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
test_widechar(PyObject *self)
{
#if defined(SIZEOF_WCHAR_T) && (SIZEOF_WCHAR_T == 4)
- const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
- size_t wtextlen = 1;
+ const wchar_t wtext[2] = {(wchar_t)0x10ABCDu};
+ size_t wtextlen = 1;
#else
- const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
- size_t wtextlen = 2;
+ const wchar_t wtext[3] = {(wchar_t)0xDBEAu, (wchar_t)0xDFCDu};
+ size_t wtextlen = 2;
#endif
- PyObject *wide, *utf8;
-
- wide = PyUnicode_FromWideChar(wtext, wtextlen);
- if (wide == NULL)
- return NULL;
-
- utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
- if (utf8 == NULL) {
- Py_DECREF(wide);
- return NULL;
- }
-
- if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
- Py_DECREF(wide);
- Py_DECREF(utf8);
- return raiseTestError("test_widechar",
- "wide string and utf8 string have different length");
- }
- if (PyUnicode_Compare(wide, utf8)) {
- Py_DECREF(wide);
- Py_DECREF(utf8);
- if (PyErr_Occurred())
- return NULL;
- return raiseTestError("test_widechar",
- "wide string and utf8 string are differents");
- }
-
- Py_DECREF(wide);
- Py_DECREF(utf8);
- Py_RETURN_NONE;
+ PyObject *wide, *utf8;
+
+ wide = PyUnicode_FromWideChar(wtext, wtextlen);
+ if (wide == NULL)
+ return NULL;
+
+ utf8 = PyUnicode_FromString("\xf4\x8a\xaf\x8d");
+ if (utf8 == NULL) {
+ Py_DECREF(wide);
+ return NULL;
+ }
+
+ if (PyUnicode_GET_SIZE(wide) != PyUnicode_GET_SIZE(utf8)) {
+ Py_DECREF(wide);
+ Py_DECREF(utf8);
+ return raiseTestError("test_widechar",
+ "wide string and utf8 string have different length");
+ }
+ if (PyUnicode_Compare(wide, utf8)) {
+ Py_DECREF(wide);
+ Py_DECREF(utf8);
+ if (PyErr_Occurred())
+ return NULL;
+ return raiseTestError("test_widechar",
+ "wide string and utf8 string are differents");
+ }
+
+ Py_DECREF(wide);
+ Py_DECREF(utf8);
+ Py_RETURN_NONE;
}
static PyObject *
test_empty_argparse(PyObject *self)
{
- /* Test that formats can begin with '|'. See issue #4720. */
- PyObject *tuple, *dict = NULL;
- static char *kwlist[] = {NULL};
- int result;
- tuple = PyTuple_New(0);
- if (!tuple)
- return NULL;
- if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
- goto done;
- dict = PyDict_New();
- if (!dict)
- goto done;
- result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
+ /* Test that formats can begin with '|'. See issue #4720. */
+ PyObject *tuple, *dict = NULL;
+ static char *kwlist[] = {NULL};
+ int result;
+ tuple = PyTuple_New(0);
+ if (!tuple)
+ return NULL;
+ if ((result = PyArg_ParseTuple(tuple, "|:test_empty_argparse")) < 0)
+ goto done;
+ dict = PyDict_New();
+ if (!dict)
+ goto done;
+ result = PyArg_ParseTupleAndKeywords(tuple, dict, "|:test_empty_argparse", kwlist);
done:
- Py_DECREF(tuple);
- Py_XDECREF(dict);
- if (result < 0)
- return NULL;
- else {
- Py_RETURN_NONE;
- }
+ Py_DECREF(tuple);
+ Py_XDECREF(dict);
+ if (result < 0)
+ return NULL;
+ else {
+ Py_RETURN_NONE;
+ }
}
static PyObject *
codec_incrementalencoder(PyObject *self, PyObject *args)
{
- const char *encoding, *errors = NULL;
- if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
- &encoding, &errors))
- return NULL;
- return PyCodec_IncrementalEncoder(encoding, errors);
+ const char *encoding, *errors = NULL;
+ if (!PyArg_ParseTuple(args, "s|s:test_incrementalencoder",
+ &encoding, &errors))
+ return NULL;
+ return PyCodec_IncrementalEncoder(encoding, errors);
}
static PyObject *
codec_incrementaldecoder(PyObject *self, PyObject *args)
{
- const char *encoding, *errors = NULL;
- if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
- &encoding, &errors))
- return NULL;
- return PyCodec_IncrementalDecoder(encoding, errors);
+ const char *encoding, *errors = NULL;
+ if (!PyArg_ParseTuple(args, "s|s:test_incrementaldecoder",
+ &encoding, &errors))
+ return NULL;
+ return PyCodec_IncrementalDecoder(encoding, errors);
}
#endif
@@ -1157,42 +1157,42 @@ codec_incrementaldecoder(PyObject *self, PyObject *args)
static PyObject *
test_long_numbits(PyObject *self)
{
- struct triple {
- long input;
- size_t nbits;
- int sign;
- } testcases[] = {{0, 0, 0},
- {1L, 1, 1},
- {-1L, 1, -1},
- {2L, 2, 1},
- {-2L, 2, -1},
- {3L, 2, 1},
- {-3L, 2, -1},
- {4L, 3, 1},
- {-4L, 3, -1},
- {0x7fffL, 15, 1}, /* one Python long digit */
- {-0x7fffL, 15, -1},
- {0xffffL, 16, 1},
- {-0xffffL, 16, -1},
- {0xfffffffL, 28, 1},
- {-0xfffffffL, 28, -1}};
- int i;
-
- for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
- PyObject *plong = PyLong_FromLong(testcases[i].input);
- size_t nbits = _PyLong_NumBits(plong);
- int sign = _PyLong_Sign(plong);
-
- Py_DECREF(plong);
- if (nbits != testcases[i].nbits)
- return raiseTestError("test_long_numbits",
- "wrong result for _PyLong_NumBits");
- if (sign != testcases[i].sign)
- return raiseTestError("test_long_numbits",
- "wrong result for _PyLong_Sign");
- }
- Py_INCREF(Py_None);
- return Py_None;
+ struct triple {
+ long input;
+ size_t nbits;
+ int sign;
+ } testcases[] = {{0, 0, 0},
+ {1L, 1, 1},
+ {-1L, 1, -1},
+ {2L, 2, 1},
+ {-2L, 2, -1},
+ {3L, 2, 1},
+ {-3L, 2, -1},
+ {4L, 3, 1},
+ {-4L, 3, -1},
+ {0x7fffL, 15, 1}, /* one Python long digit */
+ {-0x7fffL, 15, -1},
+ {0xffffL, 16, 1},
+ {-0xffffL, 16, -1},
+ {0xfffffffL, 28, 1},
+ {-0xfffffffL, 28, -1}};
+ int i;
+
+ for (i = 0; i < sizeof(testcases) / sizeof(struct triple); ++i) {
+ PyObject *plong = PyLong_FromLong(testcases[i].input);
+ size_t nbits = _PyLong_NumBits(plong);
+ int sign = _PyLong_Sign(plong);
+
+ Py_DECREF(plong);
+ if (nbits != testcases[i].nbits)
+ return raiseTestError("test_long_numbits",
+ "wrong result for _PyLong_NumBits");
+ if (sign != testcases[i].sign)
+ return raiseTestError("test_long_numbits",
+ "wrong result for _PyLong_Sign");
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Example passing NULLs to PyObject_Str(NULL) and PyObject_Unicode(NULL). */
@@ -1200,42 +1200,42 @@ test_long_numbits(PyObject *self)
static PyObject *
test_null_strings(PyObject *self)
{
- PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Unicode(NULL);
- PyObject *tuple = PyTuple_Pack(2, o1, o2);
- Py_XDECREF(o1);
- Py_XDECREF(o2);
- return tuple;
+ PyObject *o1 = PyObject_Str(NULL), *o2 = PyObject_Unicode(NULL);
+ PyObject *tuple = PyTuple_Pack(2, o1, o2);
+ Py_XDECREF(o1);
+ Py_XDECREF(o2);
+ return tuple;
}
static PyObject *
raise_exception(PyObject *self, PyObject *args)
{
- PyObject *exc;
- PyObject *exc_args, *v;
- int num_args, i;
-
- if (!PyArg_ParseTuple(args, "Oi:raise_exception",
- &exc, &num_args))
- return NULL;
- if (!PyExceptionClass_Check(exc)) {
- PyErr_Format(PyExc_TypeError, "an exception class is required");
- return NULL;
- }
-
- exc_args = PyTuple_New(num_args);
- if (exc_args == NULL)
- return NULL;
- for (i = 0; i < num_args; ++i) {
- v = PyInt_FromLong(i);
- if (v == NULL) {
- Py_DECREF(exc_args);
- return NULL;
- }
- PyTuple_SET_ITEM(exc_args, i, v);
- }
- PyErr_SetObject(exc, exc_args);
- Py_DECREF(exc_args);
- return NULL;
+ PyObject *exc;
+ PyObject *exc_args, *v;
+ int num_args, i;
+
+ if (!PyArg_ParseTuple(args, "Oi:raise_exception",
+ &exc, &num_args))
+ return NULL;
+ if (!PyExceptionClass_Check(exc)) {
+ PyErr_Format(PyExc_TypeError, "an exception class is required");
+ return NULL;
+ }
+
+ exc_args = PyTuple_New(num_args);
+ if (exc_args == NULL)
+ return NULL;
+ for (i = 0; i < num_args; ++i) {
+ v = PyInt_FromLong(i);
+ if (v == NULL) {
+ Py_DECREF(exc_args);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(exc_args, i, v);
+ }
+ PyErr_SetObject(exc, exc_args);
+ Py_DECREF(exc_args);
+ return NULL;
}
@@ -1243,23 +1243,23 @@ static int test_run_counter = 0;
static PyObject *
test_datetime_capi(PyObject *self, PyObject *args) {
- if (PyDateTimeAPI) {
- if (test_run_counter) {
- /* Probably regrtest.py -R */
- Py_RETURN_NONE;
- }
- else {
- PyErr_SetString(PyExc_AssertionError,
- "PyDateTime_CAPI somehow initialized");
- return NULL;
- }
- }
- test_run_counter++;
- PyDateTime_IMPORT;
- if (PyDateTimeAPI)
- Py_RETURN_NONE;
- else
- return NULL;
+ if (PyDateTimeAPI) {
+ if (test_run_counter) {
+ /* Probably regrtest.py -R */
+ Py_RETURN_NONE;
+ }
+ else {
+ PyErr_SetString(PyExc_AssertionError,
+ "PyDateTime_CAPI somehow initialized");
+ return NULL;
+ }
+ }
+ test_run_counter++;
+ PyDateTime_IMPORT;
+ if (PyDateTimeAPI)
+ Py_RETURN_NONE;
+ else
+ return NULL;
}
@@ -1277,14 +1277,14 @@ static PyThread_type_lock thread_done = NULL;
static int
_make_call(void *callable)
{
- PyObject *rc;
- int success;
- PyGILState_STATE s = PyGILState_Ensure();
- rc = PyObject_CallFunction((PyObject *)callable, "");
- success = (rc != NULL);
- Py_XDECREF(rc);
- PyGILState_Release(s);
- return success;
+ PyObject *rc;
+ int success;
+ PyGILState_STATE s = PyGILState_Ensure();
+ rc = PyObject_CallFunction((PyObject *)callable, "");
+ success = (rc != NULL);
+ Py_XDECREF(rc);
+ PyGILState_Release(s);
+ return success;
}
/* Same thing, but releases `thread_done` when it returns. This variant
@@ -1293,70 +1293,70 @@ _make_call(void *callable)
static void
_make_call_from_thread(void *callable)
{
- _make_call(callable);
- PyThread_release_lock(thread_done);
+ _make_call(callable);
+ PyThread_release_lock(thread_done);
}
static PyObject *
test_thread_state(PyObject *self, PyObject *args)
{
- PyObject *fn;
- int success = 1;
-
- if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
- return NULL;
-
- if (!PyCallable_Check(fn)) {
- PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
- fn->ob_type->tp_name);
- return NULL;
- }
-
- /* Ensure Python is set up for threading */
- PyEval_InitThreads();
- thread_done = PyThread_allocate_lock();
- if (thread_done == NULL)
- return PyErr_NoMemory();
- PyThread_acquire_lock(thread_done, 1);
-
- /* Start a new thread with our callback. */
- PyThread_start_new_thread(_make_call_from_thread, fn);
- /* Make the callback with the thread lock held by this thread */
- success &= _make_call(fn);
- /* Do it all again, but this time with the thread-lock released */
- Py_BEGIN_ALLOW_THREADS
- success &= _make_call(fn);
- PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
- Py_END_ALLOW_THREADS
-
- /* And once more with and without a thread
- XXX - should use a lock and work out exactly what we are trying
- to test <wink>
- */
- Py_BEGIN_ALLOW_THREADS
- PyThread_start_new_thread(_make_call_from_thread, fn);
- success &= _make_call(fn);
- PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
- Py_END_ALLOW_THREADS
-
- /* Release lock we acquired above. This is required on HP-UX. */
- PyThread_release_lock(thread_done);
-
- PyThread_free_lock(thread_done);
- if (!success)
- return NULL;
- Py_RETURN_NONE;
+ PyObject *fn;
+ int success = 1;
+
+ if (!PyArg_ParseTuple(args, "O:test_thread_state", &fn))
+ return NULL;
+
+ if (!PyCallable_Check(fn)) {
+ PyErr_Format(PyExc_TypeError, "'%s' object is not callable",
+ fn->ob_type->tp_name);
+ return NULL;
+ }
+
+ /* Ensure Python is set up for threading */
+ PyEval_InitThreads();
+ thread_done = PyThread_allocate_lock();
+ if (thread_done == NULL)
+ return PyErr_NoMemory();
+ PyThread_acquire_lock(thread_done, 1);
+
+ /* Start a new thread with our callback. */
+ PyThread_start_new_thread(_make_call_from_thread, fn);
+ /* Make the callback with the thread lock held by this thread */
+ success &= _make_call(fn);
+ /* Do it all again, but this time with the thread-lock released */
+ Py_BEGIN_ALLOW_THREADS
+ success &= _make_call(fn);
+ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
+ Py_END_ALLOW_THREADS
+
+ /* And once more with and without a thread
+ XXX - should use a lock and work out exactly what we are trying
+ to test <wink>
+ */
+ Py_BEGIN_ALLOW_THREADS
+ PyThread_start_new_thread(_make_call_from_thread, fn);
+ success &= _make_call(fn);
+ PyThread_acquire_lock(thread_done, 1); /* wait for thread to finish */
+ Py_END_ALLOW_THREADS
+
+ /* Release lock we acquired above. This is required on HP-UX. */
+ PyThread_release_lock(thread_done);
+
+ PyThread_free_lock(thread_done);
+ if (!success)
+ return NULL;
+ Py_RETURN_NONE;
}
/* test Py_AddPendingCalls using threads */
static int _pending_callback(void *arg)
{
- /* we assume the argument is callable object to which we own a reference */
- PyObject *callable = (PyObject *)arg;
- PyObject *r = PyObject_CallObject(callable, NULL);
- Py_DECREF(callable);
- Py_XDECREF(r);
- return r != NULL ? 0 : -1;
+ /* we assume the argument is callable object to which we own a reference */
+ PyObject *callable = (PyObject *)arg;
+ PyObject *r = PyObject_CallObject(callable, NULL);
+ Py_DECREF(callable);
+ Py_XDECREF(r);
+ return r != NULL ? 0 : -1;
}
/* The following requests n callbacks to _pending_callback. It can be
@@ -1364,25 +1364,25 @@ static int _pending_callback(void *arg)
*/
PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
{
- PyObject *callable;
- int r;
- if (PyArg_ParseTuple(arg, "O", &callable) == 0)
- return NULL;
-
- /* create the reference for the callbackwhile we hold the lock */
- Py_INCREF(callable);
-
- Py_BEGIN_ALLOW_THREADS
- r = Py_AddPendingCall(&_pending_callback, callable);
- Py_END_ALLOW_THREADS
-
- if (r<0) {
- Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
- Py_INCREF(Py_False);
- return Py_False;
- }
- Py_INCREF(Py_True);
- return Py_True;
+ PyObject *callable;
+ int r;
+ if (PyArg_ParseTuple(arg, "O", &callable) == 0)
+ return NULL;
+
+ /* create the reference for the callbackwhile we hold the lock */
+ Py_INCREF(callable);
+
+ Py_BEGIN_ALLOW_THREADS
+ r = Py_AddPendingCall(&_pending_callback, callable);
+ Py_END_ALLOW_THREADS
+
+ if (r<0) {
+ Py_DECREF(callable); /* unsuccessful add, destroy the extra reference */
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ Py_INCREF(Py_True);
+ return Py_True;
}
#endif
@@ -1390,40 +1390,40 @@ PyObject *pending_threadfunc(PyObject *self, PyObject *arg)
static PyObject *
test_string_from_format(PyObject *self, PyObject *args)
{
- PyObject *result;
- char *msg;
-
-#define CHECK_1_FORMAT(FORMAT, TYPE) \
- result = PyString_FromFormat(FORMAT, (TYPE)1); \
- if (result == NULL) \
- return NULL; \
- if (strcmp(PyString_AsString(result), "1")) { \
- msg = FORMAT " failed at 1"; \
- goto Fail; \
- } \
- Py_DECREF(result)
-
- CHECK_1_FORMAT("%d", int);
- CHECK_1_FORMAT("%ld", long);
- /* The z width modifier was added in Python 2.5. */
- CHECK_1_FORMAT("%zd", Py_ssize_t);
-
- /* The u type code was added in Python 2.5. */
- CHECK_1_FORMAT("%u", unsigned int);
- CHECK_1_FORMAT("%lu", unsigned long);
- CHECK_1_FORMAT("%zu", size_t);
-
- /* "%lld" and "%llu" support added in Python 2.7. */
+ PyObject *result;
+ char *msg;
+
+#define CHECK_1_FORMAT(FORMAT, TYPE) \
+ result = PyString_FromFormat(FORMAT, (TYPE)1); \
+ if (result == NULL) \
+ return NULL; \
+ if (strcmp(PyString_AsString(result), "1")) { \
+ msg = FORMAT " failed at 1"; \
+ goto Fail; \
+ } \
+ Py_DECREF(result)
+
+ CHECK_1_FORMAT("%d", int);
+ CHECK_1_FORMAT("%ld", long);
+ /* The z width modifier was added in Python 2.5. */
+ CHECK_1_FORMAT("%zd", Py_ssize_t);
+
+ /* The u type code was added in Python 2.5. */
+ CHECK_1_FORMAT("%u", unsigned int);
+ CHECK_1_FORMAT("%lu", unsigned long);
+ CHECK_1_FORMAT("%zu", size_t);
+
+ /* "%lld" and "%llu" support added in Python 2.7. */
#ifdef HAVE_LONG_LONG
- CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG);
- CHECK_1_FORMAT("%lld", PY_LONG_LONG);
+ CHECK_1_FORMAT("%llu", unsigned PY_LONG_LONG);
+ CHECK_1_FORMAT("%lld", PY_LONG_LONG);
#endif
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
Fail:
- Py_XDECREF(result);
- return raiseTestError("test_string_from_format", msg);
+ Py_XDECREF(result);
+ return raiseTestError("test_string_from_format", msg);
#undef CHECK_1_FORMAT
}
@@ -1439,143 +1439,143 @@ capsule_destructor_call_count = 0;
static void
capsule_destructor(PyObject *o) {
- capsule_destructor_call_count++;
- if (PyCapsule_GetContext(o) != capsule_context) {
- capsule_error = "context did not match in destructor!";
- } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
- capsule_error = "destructor did not match in destructor! (woah!)";
- } else if (PyCapsule_GetName(o) != capsule_name) {
- capsule_error = "name did not match in destructor!";
- } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
- capsule_error = "pointer did not match in destructor!";
- }
+ capsule_destructor_call_count++;
+ if (PyCapsule_GetContext(o) != capsule_context) {
+ capsule_error = "context did not match in destructor!";
+ } else if (PyCapsule_GetDestructor(o) != capsule_destructor) {
+ capsule_error = "destructor did not match in destructor! (woah!)";
+ } else if (PyCapsule_GetName(o) != capsule_name) {
+ capsule_error = "name did not match in destructor!";
+ } else if (PyCapsule_GetPointer(o, capsule_name) != capsule_pointer) {
+ capsule_error = "pointer did not match in destructor!";
+ }
}
typedef struct {
- char *name;
- char *module;
- char *attribute;
+ char *name;
+ char *module;
+ char *attribute;
} known_capsule;
static PyObject *
test_capsule(PyObject *self, PyObject *args)
{
- PyObject *object;
- const char *error = NULL;
- void *pointer;
- void *pointer2;
- known_capsule known_capsules[] = {
- #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
- KNOWN_CAPSULE("_socket", "CAPI"),
- KNOWN_CAPSULE("_curses", "_C_API"),
- KNOWN_CAPSULE("datetime", "datetime_CAPI"),
- { NULL, NULL },
- };
- known_capsule *known = &known_capsules[0];
+ PyObject *object;
+ const char *error = NULL;
+ void *pointer;
+ void *pointer2;
+ known_capsule known_capsules[] = {
+ #define KNOWN_CAPSULE(module, name) { module "." name, module, name }
+ KNOWN_CAPSULE("_socket", "CAPI"),
+ KNOWN_CAPSULE("_curses", "_C_API"),
+ KNOWN_CAPSULE("datetime", "datetime_CAPI"),
+ { NULL, NULL },
+ };
+ known_capsule *known = &known_capsules[0];
#define FAIL(x) { error = (x); goto exit; }
#define CHECK_DESTRUCTOR \
- if (capsule_error) { \
- FAIL(capsule_error); \
- } \
- else if (!capsule_destructor_call_count) { \
- FAIL("destructor not called!"); \
- } \
- capsule_destructor_call_count = 0; \
-
- object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
- PyCapsule_SetContext(object, capsule_context);
- capsule_destructor(object);
- CHECK_DESTRUCTOR;
- Py_DECREF(object);
- CHECK_DESTRUCTOR;
-
- object = PyCapsule_New(known, "ignored", NULL);
- PyCapsule_SetPointer(object, capsule_pointer);
- PyCapsule_SetName(object, capsule_name);
- PyCapsule_SetDestructor(object, capsule_destructor);
- PyCapsule_SetContext(object, capsule_context);
- capsule_destructor(object);
- CHECK_DESTRUCTOR;
- /* intentionally access using the wrong name */
- pointer2 = PyCapsule_GetPointer(object, "the wrong name");
- if (!PyErr_Occurred()) {
- FAIL("PyCapsule_GetPointer should have failed but did not!");
- }
- PyErr_Clear();
- if (pointer2) {
- if (pointer2 == capsule_pointer) {
- FAIL("PyCapsule_GetPointer should not have"
- " returned the internal pointer!");
- } else {
- FAIL("PyCapsule_GetPointer should have "
- "returned NULL pointer but did not!");
- }
- }
- PyCapsule_SetDestructor(object, NULL);
- Py_DECREF(object);
- if (capsule_destructor_call_count) {
- FAIL("destructor called when it should not have been!");
- }
-
- for (known = &known_capsules[0]; known->module != NULL; known++) {
- /* yeah, ordinarily I wouldn't do this either,
- but it's fine for this test harness.
- */
- static char buffer[256];
+ if (capsule_error) { \
+ FAIL(capsule_error); \
+ } \
+ else if (!capsule_destructor_call_count) { \
+ FAIL("destructor not called!"); \
+ } \
+ capsule_destructor_call_count = 0; \
+
+ object = PyCapsule_New(capsule_pointer, capsule_name, capsule_destructor);
+ PyCapsule_SetContext(object, capsule_context);
+ capsule_destructor(object);
+ CHECK_DESTRUCTOR;
+ Py_DECREF(object);
+ CHECK_DESTRUCTOR;
+
+ object = PyCapsule_New(known, "ignored", NULL);
+ PyCapsule_SetPointer(object, capsule_pointer);
+ PyCapsule_SetName(object, capsule_name);
+ PyCapsule_SetDestructor(object, capsule_destructor);
+ PyCapsule_SetContext(object, capsule_context);
+ capsule_destructor(object);
+ CHECK_DESTRUCTOR;
+ /* intentionally access using the wrong name */
+ pointer2 = PyCapsule_GetPointer(object, "the wrong name");
+ if (!PyErr_Occurred()) {
+ FAIL("PyCapsule_GetPointer should have failed but did not!");
+ }
+ PyErr_Clear();
+ if (pointer2) {
+ if (pointer2 == capsule_pointer) {
+ FAIL("PyCapsule_GetPointer should not have"
+ " returned the internal pointer!");
+ } else {
+ FAIL("PyCapsule_GetPointer should have "
+ "returned NULL pointer but did not!");
+ }
+ }
+ PyCapsule_SetDestructor(object, NULL);
+ Py_DECREF(object);
+ if (capsule_destructor_call_count) {
+ FAIL("destructor called when it should not have been!");
+ }
+
+ for (known = &known_capsules[0]; known->module != NULL; known++) {
+ /* yeah, ordinarily I wouldn't do this either,
+ but it's fine for this test harness.
+ */
+ static char buffer[256];
#undef FAIL
#define FAIL(x) \
- { \
- sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
- x, known->module, known->attribute); \
- error = buffer; \
- goto exit; \
- } \
-
- PyObject *module = PyImport_ImportModule(known->module);
- if (module) {
- pointer = PyCapsule_Import(known->name, 0);
- if (!pointer) {
- Py_DECREF(module);
- FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
- }
- object = PyObject_GetAttrString(module, known->attribute);
- if (!object) {
- Py_DECREF(module);
- return NULL;
- }
- pointer2 = PyCapsule_GetPointer(object,
- "weebles wobble but they don't fall down");
- if (!PyErr_Occurred()) {
- Py_DECREF(object);
- Py_DECREF(module);
- FAIL("PyCapsule_GetPointer should have failed but did not!");
- }
- PyErr_Clear();
- if (pointer2) {
- Py_DECREF(module);
- Py_DECREF(object);
- if (pointer2 == pointer) {
- FAIL("PyCapsule_GetPointer should not have"
- " returned its internal pointer!");
- } else {
- FAIL("PyCapsule_GetPointer should have"
- " returned NULL pointer but did not!");
- }
- }
- Py_DECREF(object);
- Py_DECREF(module);
- }
- else
- PyErr_Clear();
- }
+ { \
+ sprintf(buffer, "%s module: \"%s\" attribute: \"%s\"", \
+ x, known->module, known->attribute); \
+ error = buffer; \
+ goto exit; \
+ } \
+
+ PyObject *module = PyImport_ImportModule(known->module);
+ if (module) {
+ pointer = PyCapsule_Import(known->name, 0);
+ if (!pointer) {
+ Py_DECREF(module);
+ FAIL("PyCapsule_GetPointer returned NULL unexpectedly!");
+ }
+ object = PyObject_GetAttrString(module, known->attribute);
+ if (!object) {
+ Py_DECREF(module);
+ return NULL;
+ }
+ pointer2 = PyCapsule_GetPointer(object,
+ "weebles wobble but they don't fall down");
+ if (!PyErr_Occurred()) {
+ Py_DECREF(object);
+ Py_DECREF(module);
+ FAIL("PyCapsule_GetPointer should have failed but did not!");
+ }
+ PyErr_Clear();
+ if (pointer2) {
+ Py_DECREF(module);
+ Py_DECREF(object);
+ if (pointer2 == pointer) {
+ FAIL("PyCapsule_GetPointer should not have"
+ " returned its internal pointer!");
+ } else {
+ FAIL("PyCapsule_GetPointer should have"
+ " returned NULL pointer but did not!");
+ }
+ }
+ Py_DECREF(object);
+ Py_DECREF(module);
+ }
+ else
+ PyErr_Clear();
+ }
exit:
- if (error) {
- return raiseTestError("test_capsule", error);
- }
- Py_RETURN_NONE;
+ if (error) {
+ return raiseTestError("test_capsule", error);
+ }
+ Py_RETURN_NONE;
#undef FAIL
}
@@ -1583,40 +1583,40 @@ test_capsule(PyObject *self, PyObject *args)
static PyObject *
test_with_docstring(PyObject *self)
{
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
/* To test the format of tracebacks as printed out. */
static PyObject *
traceback_print(PyObject *self, PyObject *args)
{
- PyObject *file;
- PyObject *traceback;
- int result;
-
- if (!PyArg_ParseTuple(args, "OO:traceback_print",
- &traceback, &file))
- return NULL;
-
- result = PyTraceBack_Print(traceback, file);
- if (result < 0)
- return NULL;
- Py_RETURN_NONE;
+ PyObject *file;
+ PyObject *traceback;
+ int result;
+
+ if (!PyArg_ParseTuple(args, "OO:traceback_print",
+ &traceback, &file))
+ return NULL;
+
+ result = PyTraceBack_Print(traceback, file);
+ if (result < 0)
+ return NULL;
+ Py_RETURN_NONE;
}
/* To test that the result of PyCode_NewEmpty has the right members. */
static PyObject *
code_newempty(PyObject *self, PyObject *args)
{
- const char *filename;
- const char *funcname;
- int firstlineno;
+ const char *filename;
+ const char *funcname;
+ int firstlineno;
- if (!PyArg_ParseTuple(args, "ssi:code_newempty",
- &filename, &funcname, &firstlineno))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ssi:code_newempty",
+ &filename, &funcname, &firstlineno))
+ return NULL;
- return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
+ return (PyObject *)PyCode_NewEmpty(filename, funcname, firstlineno);
}
/* Test PyErr_NewExceptionWithDoc (also exercise PyErr_NewException).
@@ -1624,274 +1624,274 @@ code_newempty(PyObject *self, PyObject *args)
static PyObject *
make_exception_with_doc(PyObject *self, PyObject *args, PyObject *kwargs)
{
- char *name;
- char *doc = NULL;
- PyObject *base = NULL;
- PyObject *dict = NULL;
+ char *name;
+ char *doc = NULL;
+ PyObject *base = NULL;
+ PyObject *dict = NULL;
- static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
+ static char *kwlist[] = {"name", "doc", "base", "dict", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwargs,
- "s|sOO:make_exception_with_doc", kwlist,
- &name, &doc, &base, &dict))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs,
+ "s|sOO:make_exception_with_doc", kwlist,
+ &name, &doc, &base, &dict))
+ return NULL;
- return PyErr_NewExceptionWithDoc(name, doc, base, dict);
+ return PyErr_NewExceptionWithDoc(name, doc, base, dict);
}
static PyMethodDef TestMethods[] = {
- {"raise_exception", raise_exception, METH_VARARGS},
- {"test_config", (PyCFunction)test_config, METH_NOARGS},
- {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
- {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
- {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
- {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
- {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
- {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
- {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
- METH_NOARGS},
- {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
- {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
- {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
- {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
- {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
- {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
- PyDoc_STR("This is a pretty normal docstring.")},
-
- {"getargs_tuple", getargs_tuple, METH_VARARGS},
- {"getargs_keywords", (PyCFunction)getargs_keywords,
- METH_VARARGS|METH_KEYWORDS},
- {"getargs_b", getargs_b, METH_VARARGS},
- {"getargs_B", getargs_B, METH_VARARGS},
- {"getargs_h", getargs_h, METH_VARARGS},
- {"getargs_H", getargs_H, METH_VARARGS},
- {"getargs_I", getargs_I, METH_VARARGS},
- {"getargs_k", getargs_k, METH_VARARGS},
- {"getargs_i", getargs_i, METH_VARARGS},
- {"getargs_l", getargs_l, METH_VARARGS},
- {"getargs_n", getargs_n, METH_VARARGS},
+ {"raise_exception", raise_exception, METH_VARARGS},
+ {"test_config", (PyCFunction)test_config, METH_NOARGS},
+ {"test_datetime_capi", test_datetime_capi, METH_NOARGS},
+ {"test_list_api", (PyCFunction)test_list_api, METH_NOARGS},
+ {"test_dict_iteration", (PyCFunction)test_dict_iteration,METH_NOARGS},
+ {"test_lazy_hash_inheritance", (PyCFunction)test_lazy_hash_inheritance,METH_NOARGS},
+ {"test_broken_memoryview", (PyCFunction)test_broken_memoryview,METH_NOARGS},
+ {"test_long_api", (PyCFunction)test_long_api, METH_NOARGS},
+ {"test_long_and_overflow", (PyCFunction)test_long_and_overflow,
+ METH_NOARGS},
+ {"test_long_numbits", (PyCFunction)test_long_numbits, METH_NOARGS},
+ {"test_k_code", (PyCFunction)test_k_code, METH_NOARGS},
+ {"test_empty_argparse", (PyCFunction)test_empty_argparse,METH_NOARGS},
+ {"test_null_strings", (PyCFunction)test_null_strings, METH_NOARGS},
+ {"test_string_from_format", (PyCFunction)test_string_from_format, METH_NOARGS},
+ {"test_with_docstring", (PyCFunction)test_with_docstring, METH_NOARGS,
+ PyDoc_STR("This is a pretty normal docstring.")},
+
+ {"getargs_tuple", getargs_tuple, METH_VARARGS},
+ {"getargs_keywords", (PyCFunction)getargs_keywords,
+ METH_VARARGS|METH_KEYWORDS},
+ {"getargs_b", getargs_b, METH_VARARGS},
+ {"getargs_B", getargs_B, METH_VARARGS},
+ {"getargs_h", getargs_h, METH_VARARGS},
+ {"getargs_H", getargs_H, METH_VARARGS},
+ {"getargs_I", getargs_I, METH_VARARGS},
+ {"getargs_k", getargs_k, METH_VARARGS},
+ {"getargs_i", getargs_i, METH_VARARGS},
+ {"getargs_l", getargs_l, METH_VARARGS},
+ {"getargs_n", getargs_n, METH_VARARGS},
#ifdef HAVE_LONG_LONG
- {"getargs_L", getargs_L, METH_VARARGS},
- {"getargs_K", getargs_K, METH_VARARGS},
- {"test_longlong_api", test_longlong_api, METH_NOARGS},
- {"test_long_long_and_overflow",
- (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
- {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
- {"codec_incrementalencoder",
- (PyCFunction)codec_incrementalencoder, METH_VARARGS},
- {"codec_incrementaldecoder",
- (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
+ {"getargs_L", getargs_L, METH_VARARGS},
+ {"getargs_K", getargs_K, METH_VARARGS},
+ {"test_longlong_api", test_longlong_api, METH_NOARGS},
+ {"test_long_long_and_overflow",
+ (PyCFunction)test_long_long_and_overflow, METH_NOARGS},
+ {"test_L_code", (PyCFunction)test_L_code, METH_NOARGS},
+ {"codec_incrementalencoder",
+ (PyCFunction)codec_incrementalencoder, METH_VARARGS},
+ {"codec_incrementaldecoder",
+ (PyCFunction)codec_incrementaldecoder, METH_VARARGS},
#endif
#ifdef Py_USING_UNICODE
- {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
- {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
+ {"test_u_code", (PyCFunction)test_u_code, METH_NOARGS},
+ {"test_widechar", (PyCFunction)test_widechar, METH_NOARGS},
#endif
#ifdef WITH_THREAD
- {"_test_thread_state", test_thread_state, METH_VARARGS},
- {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
+ {"_test_thread_state", test_thread_state, METH_VARARGS},
+ {"_pending_threadfunc", pending_threadfunc, METH_VARARGS},
#endif
- {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
- {"traceback_print", traceback_print, METH_VARARGS},
- {"code_newempty", code_newempty, METH_VARARGS},
- {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
- METH_VARARGS | METH_KEYWORDS},
- {NULL, NULL} /* sentinel */
+ {"test_capsule", (PyCFunction)test_capsule, METH_NOARGS},
+ {"traceback_print", traceback_print, METH_VARARGS},
+ {"code_newempty", code_newempty, METH_VARARGS},
+ {"make_exception_with_doc", (PyCFunction)make_exception_with_doc,
+ METH_VARARGS | METH_KEYWORDS},
+ {NULL, NULL} /* sentinel */
};
#define AddSym(d, n, f, v) {PyObject *o = f(v); PyDict_SetItemString(d, n, o); Py_DECREF(o);}
typedef struct {
- char bool_member;
- char byte_member;
- unsigned char ubyte_member;
- short short_member;
- unsigned short ushort_member;
- int int_member;
- unsigned int uint_member;
- long long_member;
- unsigned long ulong_member;
- float float_member;
- double double_member;
- char inplace_member[6];
+ char bool_member;
+ char byte_member;
+ unsigned char ubyte_member;
+ short short_member;
+ unsigned short ushort_member;
+ int int_member;
+ unsigned int uint_member;
+ long long_member;
+ unsigned long ulong_member;
+ float float_member;
+ double double_member;
+ char inplace_member[6];
#ifdef HAVE_LONG_LONG
- PY_LONG_LONG longlong_member;
- unsigned PY_LONG_LONG ulonglong_member;
+ PY_LONG_LONG longlong_member;
+ unsigned PY_LONG_LONG ulonglong_member;
#endif
} all_structmembers;
typedef struct {
PyObject_HEAD
- all_structmembers structmembers;
+ all_structmembers structmembers;
} test_structmembers;
static struct PyMemberDef test_members[] = {
- {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
- {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
- {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
- {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
- {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
- {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
- {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
- {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
- {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
- {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
- {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
- {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
+ {"T_BOOL", T_BOOL, offsetof(test_structmembers, structmembers.bool_member), 0, NULL},
+ {"T_BYTE", T_BYTE, offsetof(test_structmembers, structmembers.byte_member), 0, NULL},
+ {"T_UBYTE", T_UBYTE, offsetof(test_structmembers, structmembers.ubyte_member), 0, NULL},
+ {"T_SHORT", T_SHORT, offsetof(test_structmembers, structmembers.short_member), 0, NULL},
+ {"T_USHORT", T_USHORT, offsetof(test_structmembers, structmembers.ushort_member), 0, NULL},
+ {"T_INT", T_INT, offsetof(test_structmembers, structmembers.int_member), 0, NULL},
+ {"T_UINT", T_UINT, offsetof(test_structmembers, structmembers.uint_member), 0, NULL},
+ {"T_LONG", T_LONG, offsetof(test_structmembers, structmembers.long_member), 0, NULL},
+ {"T_ULONG", T_ULONG, offsetof(test_structmembers, structmembers.ulong_member), 0, NULL},
+ {"T_FLOAT", T_FLOAT, offsetof(test_structmembers, structmembers.float_member), 0, NULL},
+ {"T_DOUBLE", T_DOUBLE, offsetof(test_structmembers, structmembers.double_member), 0, NULL},
+ {"T_STRING_INPLACE", T_STRING_INPLACE, offsetof(test_structmembers, structmembers.inplace_member), 0, NULL},
#ifdef HAVE_LONG_LONG
- {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
- {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
+ {"T_LONGLONG", T_LONGLONG, offsetof(test_structmembers, structmembers.longlong_member), 0, NULL},
+ {"T_ULONGLONG", T_ULONGLONG, offsetof(test_structmembers, structmembers.ulonglong_member), 0, NULL},
#endif
- {NULL}
+ {NULL}
};
static PyObject *
test_structmembers_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
{
- static char *keywords[] = {
- "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
- "T_INT", "T_UINT", "T_LONG", "T_ULONG",
- "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
-#ifdef HAVE_LONG_LONG
- "T_LONGLONG", "T_ULONGLONG",
+ static char *keywords[] = {
+ "T_BOOL", "T_BYTE", "T_UBYTE", "T_SHORT", "T_USHORT",
+ "T_INT", "T_UINT", "T_LONG", "T_ULONG",
+ "T_FLOAT", "T_DOUBLE", "T_STRING_INPLACE",
+#ifdef HAVE_LONG_LONG
+ "T_LONGLONG", "T_ULONGLONG",
#endif
- NULL};
- static char *fmt = "|bbBhHiIlkfds#"
+ NULL};
+ static char *fmt = "|bbBhHiIlkfds#"
#ifdef HAVE_LONG_LONG
- "LK"
+ "LK"
#endif
- ;
- test_structmembers *ob;
- const char *s = NULL;
- Py_ssize_t string_len = 0;
- ob = PyObject_New(test_structmembers, type);
- if (ob == NULL)
- return NULL;
- memset(&ob->structmembers, 0, sizeof(all_structmembers));
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
- &ob->structmembers.bool_member,
- &ob->structmembers.byte_member,
- &ob->structmembers.ubyte_member,
- &ob->structmembers.short_member,
- &ob->structmembers.ushort_member,
- &ob->structmembers.int_member,
- &ob->structmembers.uint_member,
- &ob->structmembers.long_member,
- &ob->structmembers.ulong_member,
- &ob->structmembers.float_member,
- &ob->structmembers.double_member,
- &s, &string_len
+ ;
+ test_structmembers *ob;
+ const char *s = NULL;
+ Py_ssize_t string_len = 0;
+ ob = PyObject_New(test_structmembers, type);
+ if (ob == NULL)
+ return NULL;
+ memset(&ob->structmembers, 0, sizeof(all_structmembers));
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, fmt, keywords,
+ &ob->structmembers.bool_member,
+ &ob->structmembers.byte_member,
+ &ob->structmembers.ubyte_member,
+ &ob->structmembers.short_member,
+ &ob->structmembers.ushort_member,
+ &ob->structmembers.int_member,
+ &ob->structmembers.uint_member,
+ &ob->structmembers.long_member,
+ &ob->structmembers.ulong_member,
+ &ob->structmembers.float_member,
+ &ob->structmembers.double_member,
+ &s, &string_len
#ifdef HAVE_LONG_LONG
- , &ob->structmembers.longlong_member,
- &ob->structmembers.ulonglong_member
+ , &ob->structmembers.longlong_member,
+ &ob->structmembers.ulonglong_member
#endif
- )) {
- Py_DECREF(ob);
- return NULL;
- }
- if (s != NULL) {
- if (string_len > 5) {
- Py_DECREF(ob);
- PyErr_SetString(PyExc_ValueError, "string too long");
- return NULL;
- }
- strcpy(ob->structmembers.inplace_member, s);
- }
- else {
- strcpy(ob->structmembers.inplace_member, "");
- }
- return (PyObject *)ob;
+ )) {
+ Py_DECREF(ob);
+ return NULL;
+ }
+ if (s != NULL) {
+ if (string_len > 5) {
+ Py_DECREF(ob);
+ PyErr_SetString(PyExc_ValueError, "string too long");
+ return NULL;
+ }
+ strcpy(ob->structmembers.inplace_member, s);
+ }
+ else {
+ strcpy(ob->structmembers.inplace_member, "");
+ }
+ return (PyObject *)ob;
}
static void
test_structmembers_free(PyObject *ob)
{
- PyObject_FREE(ob);
+ PyObject_FREE(ob);
}
static PyTypeObject test_structmembersType = {
PyVarObject_HEAD_INIT(NULL, 0)
- "test_structmembersType",
- sizeof(test_structmembers), /* tp_basicsize */
- 0, /* tp_itemsize */
- test_structmembers_free, /* destructor 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 */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- 0, /* tp_flags */
- "Type containing all structmember types",
- 0, /* traverseproc tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- test_members, /* tp_members */
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- 0,
- test_structmembers_new, /* tp_new */
+ "test_structmembersType",
+ sizeof(test_structmembers), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ test_structmembers_free, /* destructor 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 */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ 0, /* tp_flags */
+ "Type containing all structmember types",
+ 0, /* traverseproc tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ test_members, /* tp_members */
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ test_structmembers_new, /* tp_new */
};
PyMODINIT_FUNC
init_testcapi(void)
{
- PyObject *m;
-
- m = Py_InitModule("_testcapi", TestMethods);
- if (m == NULL)
- return;
-
- Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
-
- Py_TYPE(&test_structmembersType)=&PyType_Type;
- Py_INCREF(&test_structmembersType);
- /* don't use a name starting with "test", since we don't want
- test_capi to automatically call this */
- PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
-
- PyModule_AddObject(m, "CHAR_MAX", PyInt_FromLong(CHAR_MAX));
- PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN));
- PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX));
- PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX));
- PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN));
- PyModule_AddObject(m, "USHRT_MAX", PyInt_FromLong(USHRT_MAX));
- PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
- PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
- PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
- PyModule_AddObject(m, "LONG_MAX", PyInt_FromLong(LONG_MAX));
- PyModule_AddObject(m, "LONG_MIN", PyInt_FromLong(LONG_MIN));
- PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
- PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
- PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
- PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
- PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
- PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
- PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
- PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
- PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
- PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
- PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
-
- TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
- Py_INCREF(TestError);
- PyModule_AddObject(m, "error", TestError);
+ PyObject *m;
+
+ m = Py_InitModule("_testcapi", TestMethods);
+ if (m == NULL)
+ return;
+
+ Py_TYPE(&_HashInheritanceTester_Type)=&PyType_Type;
+
+ Py_TYPE(&test_structmembersType)=&PyType_Type;
+ Py_INCREF(&test_structmembersType);
+ /* don't use a name starting with "test", since we don't want
+ test_capi to automatically call this */
+ PyModule_AddObject(m, "_test_structmembersType", (PyObject *)&test_structmembersType);
+
+ PyModule_AddObject(m, "CHAR_MAX", PyInt_FromLong(CHAR_MAX));
+ PyModule_AddObject(m, "CHAR_MIN", PyInt_FromLong(CHAR_MIN));
+ PyModule_AddObject(m, "UCHAR_MAX", PyInt_FromLong(UCHAR_MAX));
+ PyModule_AddObject(m, "SHRT_MAX", PyInt_FromLong(SHRT_MAX));
+ PyModule_AddObject(m, "SHRT_MIN", PyInt_FromLong(SHRT_MIN));
+ PyModule_AddObject(m, "USHRT_MAX", PyInt_FromLong(USHRT_MAX));
+ PyModule_AddObject(m, "INT_MAX", PyLong_FromLong(INT_MAX));
+ PyModule_AddObject(m, "INT_MIN", PyLong_FromLong(INT_MIN));
+ PyModule_AddObject(m, "UINT_MAX", PyLong_FromUnsignedLong(UINT_MAX));
+ PyModule_AddObject(m, "LONG_MAX", PyInt_FromLong(LONG_MAX));
+ PyModule_AddObject(m, "LONG_MIN", PyInt_FromLong(LONG_MIN));
+ PyModule_AddObject(m, "ULONG_MAX", PyLong_FromUnsignedLong(ULONG_MAX));
+ PyModule_AddObject(m, "FLT_MAX", PyFloat_FromDouble(FLT_MAX));
+ PyModule_AddObject(m, "FLT_MIN", PyFloat_FromDouble(FLT_MIN));
+ PyModule_AddObject(m, "DBL_MAX", PyFloat_FromDouble(DBL_MAX));
+ PyModule_AddObject(m, "DBL_MIN", PyFloat_FromDouble(DBL_MIN));
+ PyModule_AddObject(m, "LLONG_MAX", PyLong_FromLongLong(PY_LLONG_MAX));
+ PyModule_AddObject(m, "LLONG_MIN", PyLong_FromLongLong(PY_LLONG_MIN));
+ PyModule_AddObject(m, "ULLONG_MAX", PyLong_FromUnsignedLongLong(PY_ULLONG_MAX));
+ PyModule_AddObject(m, "PY_SSIZE_T_MAX", PyInt_FromSsize_t(PY_SSIZE_T_MAX));
+ PyModule_AddObject(m, "PY_SSIZE_T_MIN", PyInt_FromSsize_t(PY_SSIZE_T_MIN));
+ PyModule_AddObject(m, "SIZEOF_PYGC_HEAD", PyInt_FromSsize_t(sizeof(PyGC_Head)));
+
+ TestError = PyErr_NewException("_testcapi.error", NULL, NULL);
+ Py_INCREF(TestError);
+ PyModule_AddObject(m, "error", TestError);
}
diff --git a/Modules/_tkinter.c b/Modules/_tkinter.c
index db25f86..01d6284 100644
--- a/Modules/_tkinter.c
+++ b/Modules/_tkinter.c
@@ -9,9 +9,9 @@ Copyright (C) 1994 Steen Lumholt.
/* TCL/TK VERSION INFO:
- Only Tcl/Tk 8.3.1 and later are supported. Older versions are not
- supported. Use Python 2.6 or older if you cannot upgrade your
- Tcl/Tk libraries.
+ Only Tcl/Tk 8.3.1 and later are supported. Older versions are not
+ supported. Use Python 2.6 or older if you cannot upgrade your
+ Tcl/Tk libraries.
*/
/* XXX Further speed-up ideas, involving Tcl 8.0 features:
@@ -83,8 +83,8 @@ Copyright (C) 1994 Steen Lumholt.
/* Unicode conversion assumes that Tcl_UniChar is two bytes.
We cannot test this directly, so we test UTF-8 size instead,
expecting that TCL_UTF_MAX is changed if Tcl ever supports
- either UTF-16 or UCS-4.
- Redhat 8 sets TCL_UTF_MAX to 6, and uses wchar_t for
+ either UTF-16 or UCS-4.
+ Redhat 8 sets TCL_UTF_MAX to 6, and uses wchar_t for
Tcl_Unichar. This is also ok as long as Python uses UCS-4,
as well.
*/
@@ -197,32 +197,32 @@ static PyThreadState *tcl_tstate = NULL;
#endif
#define ENTER_TCL \
- { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
+ { PyThreadState *tstate = PyThreadState_Get(); Py_BEGIN_ALLOW_THREADS \
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate;
#define LEAVE_TCL \
tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); Py_END_ALLOW_THREADS}
#define ENTER_OVERLAP \
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
#define LEAVE_OVERLAP_TCL \
- tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); }
+ tcl_tstate = NULL; if(tcl_lock)PyThread_release_lock(tcl_lock); }
#define ENTER_PYTHON \
- { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
- if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
+ { PyThreadState *tstate = tcl_tstate; tcl_tstate = NULL; \
+ if(tcl_lock)PyThread_release_lock(tcl_lock); PyEval_RestoreThread((tstate)); }
#define LEAVE_PYTHON \
- { PyThreadState *tstate = PyEval_SaveThread(); \
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
+ { PyThreadState *tstate = PyEval_SaveThread(); \
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1); tcl_tstate = tstate; }
#define CHECK_TCL_APPARTMENT \
- if (((TkappObject *)self)->threaded && \
- ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \
- PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \
- return 0; \
- }
+ if (((TkappObject *)self)->threaded && \
+ ((TkappObject *)self)->thread_id != Tcl_GetCurrentThread()) { \
+ PyErr_SetString(PyExc_RuntimeError, "Calling Tcl from different appartment"); \
+ return 0; \
+ }
#else
@@ -245,21 +245,21 @@ static PyThreadState *tcl_tstate = NULL;
static PyTypeObject Tkapp_Type;
typedef struct {
- PyObject_HEAD
- Tcl_Interp *interp;
- int wantobjects;
- int threaded; /* True if tcl_platform[threaded] */
- Tcl_ThreadId thread_id;
- int dispatching;
- /* We cannot include tclInt.h, as this is internal.
- So we cache interesting types here. */
- Tcl_ObjType *BooleanType;
- Tcl_ObjType *ByteArrayType;
- Tcl_ObjType *DoubleType;
- Tcl_ObjType *IntType;
- Tcl_ObjType *ListType;
- Tcl_ObjType *ProcBodyType;
- Tcl_ObjType *StringType;
+ PyObject_HEAD
+ Tcl_Interp *interp;
+ int wantobjects;
+ int threaded; /* True if tcl_platform[threaded] */
+ Tcl_ThreadId thread_id;
+ int dispatching;
+ /* We cannot include tclInt.h, as this is internal.
+ So we cache interesting types here. */
+ Tcl_ObjType *BooleanType;
+ Tcl_ObjType *ByteArrayType;
+ Tcl_ObjType *DoubleType;
+ Tcl_ObjType *IntType;
+ Tcl_ObjType *ListType;
+ Tcl_ObjType *ProcBodyType;
+ Tcl_ObjType *StringType;
} TkappObject;
#define Tkapp_Check(v) (Py_TYPE(v) == &Tkapp_Type)
@@ -270,7 +270,7 @@ typedef struct {
(void *) v, Py_REFCNT(v)))
-
+
/**** Error Handling ****/
static PyObject *Tkinter_TclError;
@@ -284,16 +284,16 @@ static PyObject *trbInCmd;
static int tk_load_failed;
#endif
-
+
static PyObject *
Tkinter_Error(PyObject *v)
{
- PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
- return NULL;
+ PyErr_SetString(Tkinter_TclError, Tkapp_Result(v));
+ return NULL;
}
-
+
/**** Utils ****/
static int Tkinter_busywaitinterval = 20;
@@ -306,11 +306,11 @@ static int Tkinter_busywaitinterval = 20;
static void
Sleep(int milli)
{
- /* XXX Too bad if you don't have select(). */
- struct timeval t;
- t.tv_sec = milli/1000;
- t.tv_usec = (milli%1000) * 1000;
- select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
+ /* XXX Too bad if you don't have select(). */
+ struct timeval t;
+ t.tv_sec = milli/1000;
+ t.tv_usec = (milli%1000) * 1000;
+ select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t);
}
#endif /* MS_WINDOWS */
@@ -319,174 +319,174 @@ Sleep(int milli)
static int
WaitForMainloop(TkappObject* self)
{
- int i;
- for (i = 0; i < 10; i++) {
- if (self->dispatching)
- return 1;
- Py_BEGIN_ALLOW_THREADS
- Sleep(100);
- Py_END_ALLOW_THREADS
- }
- if (self->dispatching)
- return 1;
- PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop");
- return 0;
+ int i;
+ for (i = 0; i < 10; i++) {
+ if (self->dispatching)
+ return 1;
+ Py_BEGIN_ALLOW_THREADS
+ Sleep(100);
+ Py_END_ALLOW_THREADS
+ }
+ if (self->dispatching)
+ return 1;
+ PyErr_SetString(PyExc_RuntimeError, "main thread is not in main loop");
+ return 0;
}
#endif /* WITH_THREAD */
-
+
static char *
AsString(PyObject *value, PyObject *tmp)
{
- if (PyString_Check(value))
- return PyString_AsString(value);
+ if (PyString_Check(value))
+ return PyString_AsString(value);
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(value)) {
- PyObject *v = PyUnicode_AsUTF8String(value);
- if (v == NULL)
- return NULL;
- if (PyList_Append(tmp, v) != 0) {
- Py_DECREF(v);
- return NULL;
- }
- Py_DECREF(v);
- return PyString_AsString(v);
- }
-#endif
- else {
- PyObject *v = PyObject_Str(value);
- if (v == NULL)
- return NULL;
- if (PyList_Append(tmp, v) != 0) {
- Py_DECREF(v);
- return NULL;
- }
- Py_DECREF(v);
- return PyString_AsString(v);
- }
-}
-
-
-
+ else if (PyUnicode_Check(value)) {
+ PyObject *v = PyUnicode_AsUTF8String(value);
+ if (v == NULL)
+ return NULL;
+ if (PyList_Append(tmp, v) != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ Py_DECREF(v);
+ return PyString_AsString(v);
+ }
+#endif
+ else {
+ PyObject *v = PyObject_Str(value);
+ if (v == NULL)
+ return NULL;
+ if (PyList_Append(tmp, v) != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ Py_DECREF(v);
+ return PyString_AsString(v);
+ }
+}
+
+
+
#define ARGSZ 64
static char *
Merge(PyObject *args)
{
- PyObject *tmp = NULL;
- char *argvStore[ARGSZ];
- char **argv = NULL;
- int fvStore[ARGSZ];
- int *fv = NULL;
- int argc = 0, fvc = 0, i;
- char *res = NULL;
-
- if (!(tmp = PyList_New(0)))
- return NULL;
-
- argv = argvStore;
- fv = fvStore;
-
- if (args == NULL)
- argc = 0;
-
- else if (!PyTuple_Check(args)) {
- argc = 1;
- fv[0] = 0;
- if (!(argv[0] = AsString(args, tmp)))
- goto finally;
- }
- else {
- argc = PyTuple_Size(args);
-
- if (argc > ARGSZ) {
- argv = (char **)ckalloc(argc * sizeof(char *));
- fv = (int *)ckalloc(argc * sizeof(int));
- if (argv == NULL || fv == NULL) {
- PyErr_NoMemory();
- goto finally;
- }
- }
-
- for (i = 0; i < argc; i++) {
- PyObject *v = PyTuple_GetItem(args, i);
- if (PyTuple_Check(v)) {
- fv[i] = 1;
- if (!(argv[i] = Merge(v)))
- goto finally;
- fvc++;
- }
- else if (v == Py_None) {
- argc = i;
- break;
- }
- else {
- fv[i] = 0;
- if (!(argv[i] = AsString(v, tmp)))
- goto finally;
- fvc++;
- }
- }
- }
- res = Tcl_Merge(argc, argv);
- if (res == NULL)
- PyErr_SetString(Tkinter_TclError, "merge failed");
+ PyObject *tmp = NULL;
+ char *argvStore[ARGSZ];
+ char **argv = NULL;
+ int fvStore[ARGSZ];
+ int *fv = NULL;
+ int argc = 0, fvc = 0, i;
+ char *res = NULL;
+
+ if (!(tmp = PyList_New(0)))
+ return NULL;
+
+ argv = argvStore;
+ fv = fvStore;
+
+ if (args == NULL)
+ argc = 0;
+
+ else if (!PyTuple_Check(args)) {
+ argc = 1;
+ fv[0] = 0;
+ if (!(argv[0] = AsString(args, tmp)))
+ goto finally;
+ }
+ else {
+ argc = PyTuple_Size(args);
+
+ if (argc > ARGSZ) {
+ argv = (char **)ckalloc(argc * sizeof(char *));
+ fv = (int *)ckalloc(argc * sizeof(int));
+ if (argv == NULL || fv == NULL) {
+ PyErr_NoMemory();
+ goto finally;
+ }
+ }
+
+ for (i = 0; i < argc; i++) {
+ PyObject *v = PyTuple_GetItem(args, i);
+ if (PyTuple_Check(v)) {
+ fv[i] = 1;
+ if (!(argv[i] = Merge(v)))
+ goto finally;
+ fvc++;
+ }
+ else if (v == Py_None) {
+ argc = i;
+ break;
+ }
+ else {
+ fv[i] = 0;
+ if (!(argv[i] = AsString(v, tmp)))
+ goto finally;
+ fvc++;
+ }
+ }
+ }
+ res = Tcl_Merge(argc, argv);
+ if (res == NULL)
+ PyErr_SetString(Tkinter_TclError, "merge failed");
finally:
- for (i = 0; i < fvc; i++)
- if (fv[i]) {
- ckfree(argv[i]);
- }
- if (argv != argvStore)
- ckfree(FREECAST argv);
- if (fv != fvStore)
- ckfree(FREECAST fv);
+ for (i = 0; i < fvc; i++)
+ if (fv[i]) {
+ ckfree(argv[i]);
+ }
+ if (argv != argvStore)
+ ckfree(FREECAST argv);
+ if (fv != fvStore)
+ ckfree(FREECAST fv);
- Py_DECREF(tmp);
- return res;
+ Py_DECREF(tmp);
+ return res;
}
-
+
static PyObject *
Split(char *list)
{
- int argc;
- char **argv;
- PyObject *v;
-
- if (list == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
- /* Not a list.
- * Could be a quoted string containing funnies, e.g. {"}.
- * Return the string itself.
- */
- return PyString_FromString(list);
- }
-
- if (argc == 0)
- v = PyString_FromString("");
- else if (argc == 1)
- v = PyString_FromString(argv[0]);
- else if ((v = PyTuple_New(argc)) != NULL) {
- int i;
- PyObject *w;
-
- for (i = 0; i < argc; i++) {
- if ((w = Split(argv[i])) == NULL) {
- Py_DECREF(v);
- v = NULL;
- break;
- }
- PyTuple_SetItem(v, i, w);
- }
- }
- Tcl_Free(FREECAST argv);
- return v;
+ int argc;
+ char **argv;
+ PyObject *v;
+
+ if (list == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
+ /* Not a list.
+ * Could be a quoted string containing funnies, e.g. {"}.
+ * Return the string itself.
+ */
+ return PyString_FromString(list);
+ }
+
+ if (argc == 0)
+ v = PyString_FromString("");
+ else if (argc == 1)
+ v = PyString_FromString(argv[0]);
+ else if ((v = PyTuple_New(argc)) != NULL) {
+ int i;
+ PyObject *w;
+
+ for (i = 0; i < argc; i++) {
+ if ((w = Split(argv[i])) == NULL) {
+ Py_DECREF(v);
+ v = NULL;
+ break;
+ }
+ PyTuple_SetItem(v, i, w);
+ }
+ }
+ Tcl_Free(FREECAST argv);
+ return v;
}
/* In some cases, Tcl will still return strings that are supposed to be
@@ -496,103 +496,103 @@ Split(char *list)
static PyObject *
SplitObj(PyObject *arg)
{
- if (PyTuple_Check(arg)) {
- int i, size;
- PyObject *elem, *newelem, *result;
-
- size = PyTuple_Size(arg);
- result = NULL;
- /* Recursively invoke SplitObj for all tuple items.
- If this does not return a new object, no action is
- needed. */
- for(i = 0; i < size; i++) {
- elem = PyTuple_GetItem(arg, i);
- newelem = SplitObj(elem);
- if (!newelem) {
- Py_XDECREF(result);
- return NULL;
- }
- if (!result) {
- int k;
- if (newelem == elem) {
- Py_DECREF(newelem);
- continue;
- }
- result = PyTuple_New(size);
- if (!result)
- return NULL;
- for(k = 0; k < i; k++) {
- elem = PyTuple_GetItem(arg, k);
- Py_INCREF(elem);
- PyTuple_SetItem(result, k, elem);
- }
- }
- PyTuple_SetItem(result, i, newelem);
- }
- if (result)
- return result;
- /* Fall through, returning arg. */
- }
- else if (PyString_Check(arg)) {
- int argc;
- char **argv;
- char *list = PyString_AsString(arg);
-
- if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
- Py_INCREF(arg);
- return arg;
- }
- Tcl_Free(FREECAST argv);
- if (argc > 1)
- return Split(PyString_AsString(arg));
- /* Fall through, returning arg. */
- }
- Py_INCREF(arg);
- return arg;
-}
-
-
+ if (PyTuple_Check(arg)) {
+ int i, size;
+ PyObject *elem, *newelem, *result;
+
+ size = PyTuple_Size(arg);
+ result = NULL;
+ /* Recursively invoke SplitObj for all tuple items.
+ If this does not return a new object, no action is
+ needed. */
+ for(i = 0; i < size; i++) {
+ elem = PyTuple_GetItem(arg, i);
+ newelem = SplitObj(elem);
+ if (!newelem) {
+ Py_XDECREF(result);
+ return NULL;
+ }
+ if (!result) {
+ int k;
+ if (newelem == elem) {
+ Py_DECREF(newelem);
+ continue;
+ }
+ result = PyTuple_New(size);
+ if (!result)
+ return NULL;
+ for(k = 0; k < i; k++) {
+ elem = PyTuple_GetItem(arg, k);
+ Py_INCREF(elem);
+ PyTuple_SetItem(result, k, elem);
+ }
+ }
+ PyTuple_SetItem(result, i, newelem);
+ }
+ if (result)
+ return result;
+ /* Fall through, returning arg. */
+ }
+ else if (PyString_Check(arg)) {
+ int argc;
+ char **argv;
+ char *list = PyString_AsString(arg);
+
+ if (Tcl_SplitList((Tcl_Interp *)NULL, list, &argc, &argv) != TCL_OK) {
+ Py_INCREF(arg);
+ return arg;
+ }
+ Tcl_Free(FREECAST argv);
+ if (argc > 1)
+ return Split(PyString_AsString(arg));
+ /* Fall through, returning arg. */
+ }
+ Py_INCREF(arg);
+ return arg;
+}
+
+
/**** Tkapp Object ****/
#ifndef WITH_APPINIT
int
Tcl_AppInit(Tcl_Interp *interp)
{
- const char * _tkinter_skip_tk_init;
+ const char * _tkinter_skip_tk_init;
- if (Tcl_Init(interp) == TCL_ERROR) {
- PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp));
- return TCL_ERROR;
- }
+ if (Tcl_Init(interp) == TCL_ERROR) {
+ PySys_WriteStderr("Tcl_Init error: %s\n", Tcl_GetStringResult(interp));
+ return TCL_ERROR;
+ }
- _tkinter_skip_tk_init = Tcl_GetVar(interp,
- "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
- if (_tkinter_skip_tk_init != NULL &&
- strcmp(_tkinter_skip_tk_init, "1") == 0) {
- return TCL_OK;
- }
+ _tkinter_skip_tk_init = Tcl_GetVar(interp,
+ "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
+ if (_tkinter_skip_tk_init != NULL &&
+ strcmp(_tkinter_skip_tk_init, "1") == 0) {
+ return TCL_OK;
+ }
#ifdef TKINTER_PROTECT_LOADTK
- if (tk_load_failed) {
- PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG);
- return TCL_ERROR;
- }
+ if (tk_load_failed) {
+ PySys_WriteStderr("Tk_Init error: %s\n", TKINTER_LOADTK_ERRMSG);
+ return TCL_ERROR;
+ }
#endif
- if (Tk_Init(interp) == TCL_ERROR) {
+ if (Tk_Init(interp) == TCL_ERROR) {
#ifdef TKINTER_PROTECT_LOADTK
- tk_load_failed = 1;
+ tk_load_failed = 1;
#endif
- PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
- return TCL_ERROR;
- }
+ PySys_WriteStderr("Tk_Init error: %s\n", Tcl_GetStringResult(interp));
+ return TCL_ERROR;
+ }
- return TCL_OK;
+ return TCL_OK;
}
#endif /* !WITH_APPINIT */
-
+
/* Initialize the Tk application; see the `main' function in
* `tkMain.c'.
@@ -603,235 +603,235 @@ static void DisableEventHook(void); /* Forward */
static TkappObject *
Tkapp_New(char *screenName, char *baseName, char *className,
- int interactive, int wantobjects, int wantTk, int sync, char *use)
+ int interactive, int wantobjects, int wantTk, int sync, char *use)
{
- TkappObject *v;
- char *argv0;
+ TkappObject *v;
+ char *argv0;
- v = PyObject_New(TkappObject, &Tkapp_Type);
- if (v == NULL)
- return NULL;
+ v = PyObject_New(TkappObject, &Tkapp_Type);
+ if (v == NULL)
+ return NULL;
- v->interp = Tcl_CreateInterp();
- v->wantobjects = wantobjects;
- v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded",
- TCL_GLOBAL_ONLY) != NULL;
- v->thread_id = Tcl_GetCurrentThread();
- v->dispatching = 0;
+ v->interp = Tcl_CreateInterp();
+ v->wantobjects = wantobjects;
+ v->threaded = Tcl_GetVar2Ex(v->interp, "tcl_platform", "threaded",
+ TCL_GLOBAL_ONLY) != NULL;
+ v->thread_id = Tcl_GetCurrentThread();
+ v->dispatching = 0;
#ifndef TCL_THREADS
- if (v->threaded) {
- PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not");
- Py_DECREF(v);
- return 0;
- }
+ if (v->threaded) {
+ PyErr_SetString(PyExc_RuntimeError, "Tcl is threaded but _tkinter is not");
+ Py_DECREF(v);
+ return 0;
+ }
#endif
#ifdef WITH_THREAD
- if (v->threaded && tcl_lock) {
- /* If Tcl is threaded, we don't need the lock. */
- PyThread_free_lock(tcl_lock);
- tcl_lock = NULL;
- }
-#endif
-
- v->BooleanType = Tcl_GetObjType("boolean");
- v->ByteArrayType = Tcl_GetObjType("bytearray");
- v->DoubleType = Tcl_GetObjType("double");
- v->IntType = Tcl_GetObjType("int");
- v->ListType = Tcl_GetObjType("list");
- v->ProcBodyType = Tcl_GetObjType("procbody");
- v->StringType = Tcl_GetObjType("string");
-
- /* Delete the 'exit' command, which can screw things up */
- Tcl_DeleteCommand(v->interp, "exit");
-
- if (screenName != NULL)
- Tcl_SetVar2(v->interp, "env", "DISPLAY",
- screenName, TCL_GLOBAL_ONLY);
-
- if (interactive)
- Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
- else
- Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
-
- /* This is used to get the application class for Tk 4.1 and up */
- argv0 = (char*)ckalloc(strlen(className) + 1);
- if (!argv0) {
- PyErr_NoMemory();
- Py_DECREF(v);
- return NULL;
- }
-
- strcpy(argv0, className);
- if (isupper(Py_CHARMASK(argv0[0])))
- argv0[0] = tolower(Py_CHARMASK(argv0[0]));
- Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
- ckfree(argv0);
-
- if (! wantTk) {
- Tcl_SetVar(v->interp,
- "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY);
- }
+ if (v->threaded && tcl_lock) {
+ /* If Tcl is threaded, we don't need the lock. */
+ PyThread_free_lock(tcl_lock);
+ tcl_lock = NULL;
+ }
+#endif
+
+ v->BooleanType = Tcl_GetObjType("boolean");
+ v->ByteArrayType = Tcl_GetObjType("bytearray");
+ v->DoubleType = Tcl_GetObjType("double");
+ v->IntType = Tcl_GetObjType("int");
+ v->ListType = Tcl_GetObjType("list");
+ v->ProcBodyType = Tcl_GetObjType("procbody");
+ v->StringType = Tcl_GetObjType("string");
+
+ /* Delete the 'exit' command, which can screw things up */
+ Tcl_DeleteCommand(v->interp, "exit");
+
+ if (screenName != NULL)
+ Tcl_SetVar2(v->interp, "env", "DISPLAY",
+ screenName, TCL_GLOBAL_ONLY);
+
+ if (interactive)
+ Tcl_SetVar(v->interp, "tcl_interactive", "1", TCL_GLOBAL_ONLY);
+ else
+ Tcl_SetVar(v->interp, "tcl_interactive", "0", TCL_GLOBAL_ONLY);
+
+ /* This is used to get the application class for Tk 4.1 and up */
+ argv0 = (char*)ckalloc(strlen(className) + 1);
+ if (!argv0) {
+ PyErr_NoMemory();
+ Py_DECREF(v);
+ return NULL;
+ }
+
+ strcpy(argv0, className);
+ if (isupper(Py_CHARMASK(argv0[0])))
+ argv0[0] = tolower(Py_CHARMASK(argv0[0]));
+ Tcl_SetVar(v->interp, "argv0", argv0, TCL_GLOBAL_ONLY);
+ ckfree(argv0);
+
+ if (! wantTk) {
+ Tcl_SetVar(v->interp,
+ "_tkinter_skip_tk_init", "1", TCL_GLOBAL_ONLY);
+ }
#ifdef TKINTER_PROTECT_LOADTK
- else if (tk_load_failed) {
- Tcl_SetVar(v->interp,
- "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
- }
-#endif
-
- /* some initial arguments need to be in argv */
- if (sync || use) {
- char *args;
- int len = 0;
-
- if (sync)
- len += sizeof "-sync";
- if (use)
- len += strlen(use) + sizeof "-use ";
-
- args = (char*)ckalloc(len);
- if (!args) {
- PyErr_NoMemory();
- Py_DECREF(v);
- return NULL;
- }
-
- args[0] = '\0';
- if (sync)
- strcat(args, "-sync");
- if (use) {
- if (sync)
- strcat(args, " ");
- strcat(args, "-use ");
- strcat(args, use);
- }
-
- Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY);
- ckfree(args);
- }
-
- if (Tcl_AppInit(v->interp) != TCL_OK) {
- PyObject *result = Tkinter_Error((PyObject *)v);
+ else if (tk_load_failed) {
+ Tcl_SetVar(v->interp,
+ "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
+ }
+#endif
+
+ /* some initial arguments need to be in argv */
+ if (sync || use) {
+ char *args;
+ int len = 0;
+
+ if (sync)
+ len += sizeof "-sync";
+ if (use)
+ len += strlen(use) + sizeof "-use ";
+
+ args = (char*)ckalloc(len);
+ if (!args) {
+ PyErr_NoMemory();
+ Py_DECREF(v);
+ return NULL;
+ }
+
+ args[0] = '\0';
+ if (sync)
+ strcat(args, "-sync");
+ if (use) {
+ if (sync)
+ strcat(args, " ");
+ strcat(args, "-use ");
+ strcat(args, use);
+ }
+
+ Tcl_SetVar(v->interp, "argv", args, TCL_GLOBAL_ONLY);
+ ckfree(args);
+ }
+
+ if (Tcl_AppInit(v->interp) != TCL_OK) {
+ PyObject *result = Tkinter_Error((PyObject *)v);
#ifdef TKINTER_PROTECT_LOADTK
- if (wantTk) {
- const char *_tkinter_tk_failed;
- _tkinter_tk_failed = Tcl_GetVar(v->interp,
- "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
+ if (wantTk) {
+ const char *_tkinter_tk_failed;
+ _tkinter_tk_failed = Tcl_GetVar(v->interp,
+ "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
- if ( _tkinter_tk_failed != NULL &&
- strcmp(_tkinter_tk_failed, "1") == 0) {
- tk_load_failed = 1;
- }
- }
+ if ( _tkinter_tk_failed != NULL &&
+ strcmp(_tkinter_tk_failed, "1") == 0) {
+ tk_load_failed = 1;
+ }
+ }
#endif
- Py_DECREF((PyObject *)v);
- return (TkappObject *)result;
- }
+ Py_DECREF((PyObject *)v);
+ return (TkappObject *)result;
+ }
- EnableEventHook();
+ EnableEventHook();
- return v;
+ return v;
}
#ifdef WITH_THREAD
static void
Tkapp_ThreadSend(TkappObject *self, Tcl_Event *ev,
- Tcl_Condition *cond, Tcl_Mutex *mutex)
+ Tcl_Condition *cond, Tcl_Mutex *mutex)
{
- Py_BEGIN_ALLOW_THREADS;
- Tcl_MutexLock(mutex);
- Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
- Tcl_ThreadAlert(self->thread_id);
- Tcl_ConditionWait(cond, mutex, NULL);
- Tcl_MutexUnlock(mutex);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS;
+ Tcl_MutexLock(mutex);
+ Tcl_ThreadQueueEvent(self->thread_id, ev, TCL_QUEUE_TAIL);
+ Tcl_ThreadAlert(self->thread_id);
+ Tcl_ConditionWait(cond, mutex, NULL);
+ Tcl_MutexUnlock(mutex);
+ Py_END_ALLOW_THREADS
}
#endif
-
+
/** Tcl Eval **/
typedef struct {
- PyObject_HEAD
- Tcl_Obj *value;
- PyObject *string; /* This cannot cause cycles. */
+ PyObject_HEAD
+ Tcl_Obj *value;
+ PyObject *string; /* This cannot cause cycles. */
} PyTclObject;
staticforward PyTypeObject PyTclObject_Type;
-#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type)
+#define PyTclObject_Check(v) ((v)->ob_type == &PyTclObject_Type)
static PyObject *
newPyTclObject(Tcl_Obj *arg)
{
- PyTclObject *self;
- self = PyObject_New(PyTclObject, &PyTclObject_Type);
- if (self == NULL)
- return NULL;
- Tcl_IncrRefCount(arg);
- self->value = arg;
- self->string = NULL;
- return (PyObject*)self;
+ PyTclObject *self;
+ self = PyObject_New(PyTclObject, &PyTclObject_Type);
+ if (self == NULL)
+ return NULL;
+ Tcl_IncrRefCount(arg);
+ self->value = arg;
+ self->string = NULL;
+ return (PyObject*)self;
}
static void
PyTclObject_dealloc(PyTclObject *self)
{
- Tcl_DecrRefCount(self->value);
- Py_XDECREF(self->string);
- PyObject_Del(self);
+ Tcl_DecrRefCount(self->value);
+ Py_XDECREF(self->string);
+ PyObject_Del(self);
}
static PyObject *
PyTclObject_str(PyTclObject *self)
{
- if (self->string && PyString_Check(self->string)) {
- Py_INCREF(self->string);
- return self->string;
- }
- /* XXX Could cache value if it is an ASCII string. */
- return PyString_FromString(Tcl_GetString(self->value));
+ if (self->string && PyString_Check(self->string)) {
+ Py_INCREF(self->string);
+ return self->string;
+ }
+ /* XXX Could cache value if it is an ASCII string. */
+ return PyString_FromString(Tcl_GetString(self->value));
}
static char*
PyTclObject_TclString(PyObject *self)
{
- return Tcl_GetString(((PyTclObject*)self)->value);
+ return Tcl_GetString(((PyTclObject*)self)->value);
}
/* Like _str, but create Unicode if necessary. */
-PyDoc_STRVAR(PyTclObject_string__doc__,
+PyDoc_STRVAR(PyTclObject_string__doc__,
"the string representation of this object, either as string or Unicode");
static PyObject *
PyTclObject_string(PyTclObject *self, void *ignored)
{
- char *s;
- int i, len;
- if (!self->string) {
- s = Tcl_GetStringFromObj(self->value, &len);
- for (i = 0; i < len; i++)
- if (s[i] & 0x80)
- break;
+ char *s;
+ int i, len;
+ if (!self->string) {
+ s = Tcl_GetStringFromObj(self->value, &len);
+ for (i = 0; i < len; i++)
+ if (s[i] & 0x80)
+ break;
#ifdef Py_USING_UNICODE
- if (i == len)
- /* It is an ASCII string. */
- self->string = PyString_FromStringAndSize(s, len);
- else {
- self->string = PyUnicode_DecodeUTF8(s, len, "strict");
- if (!self->string) {
- PyErr_Clear();
- self->string = PyString_FromStringAndSize(s, len);
- }
- }
+ if (i == len)
+ /* It is an ASCII string. */
+ self->string = PyString_FromStringAndSize(s, len);
+ else {
+ self->string = PyUnicode_DecodeUTF8(s, len, "strict");
+ if (!self->string) {
+ PyErr_Clear();
+ self->string = PyString_FromStringAndSize(s, len);
+ }
+ }
#else
- self->string = PyString_FromStringAndSize(s, len);
+ self->string = PyString_FromStringAndSize(s, len);
#endif
- if (!self->string)
- return NULL;
- }
- Py_INCREF(self->string);
- return self->string;
+ if (!self->string)
+ return NULL;
+ }
+ Py_INCREF(self->string);
+ return self->string;
}
#ifdef Py_USING_UNICODE
@@ -840,36 +840,36 @@ PyDoc_STRVAR(PyTclObject_unicode__doc__, "convert argument to unicode");
static PyObject *
PyTclObject_unicode(PyTclObject *self, void *ignored)
{
- char *s;
- int len;
- if (self->string && PyUnicode_Check(self->string)) {
- Py_INCREF(self->string);
- return self->string;
- }
- /* XXX Could chache result if it is non-ASCII. */
- s = Tcl_GetStringFromObj(self->value, &len);
- return PyUnicode_DecodeUTF8(s, len, "strict");
+ char *s;
+ int len;
+ if (self->string && PyUnicode_Check(self->string)) {
+ Py_INCREF(self->string);
+ return self->string;
+ }
+ /* XXX Could chache result if it is non-ASCII. */
+ s = Tcl_GetStringFromObj(self->value, &len);
+ return PyUnicode_DecodeUTF8(s, len, "strict");
}
#endif
static PyObject *
PyTclObject_repr(PyTclObject *self)
{
- char buf[50];
- PyOS_snprintf(buf, 50, "<%s object at %p>",
- self->value->typePtr->name, self->value);
- return PyString_FromString(buf);
+ char buf[50];
+ PyOS_snprintf(buf, 50, "<%s object at %p>",
+ self->value->typePtr->name, self->value);
+ return PyString_FromString(buf);
}
static int
PyTclObject_cmp(PyTclObject *self, PyTclObject *other)
{
- int res;
- res = strcmp(Tcl_GetString(self->value),
- Tcl_GetString(other->value));
- if (res < 0) return -1;
- if (res > 0) return 1;
- return 0;
+ int res;
+ res = strcmp(Tcl_GetString(self->value),
+ Tcl_GetString(other->value));
+ if (res < 0) return -1;
+ if (res > 0) return 1;
+ return 0;
}
PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
@@ -877,264 +877,264 @@ PyDoc_STRVAR(get_typename__doc__, "name of the Tcl type");
static PyObject*
get_typename(PyTclObject* obj, void* ignored)
{
- return PyString_FromString(obj->value->typePtr->name);
+ return PyString_FromString(obj->value->typePtr->name);
}
static PyGetSetDef PyTclObject_getsetlist[] = {
- {"typename", (getter)get_typename, NULL, get_typename__doc__},
- {"string", (getter)PyTclObject_string, NULL,
- PyTclObject_string__doc__},
- {0},
+ {"typename", (getter)get_typename, NULL, get_typename__doc__},
+ {"string", (getter)PyTclObject_string, NULL,
+ PyTclObject_string__doc__},
+ {0},
};
static PyMethodDef PyTclObject_methods[] = {
#ifdef Py_USING_UNICODE
- {"__unicode__", (PyCFunction)PyTclObject_unicode, METH_NOARGS,
- PyTclObject_unicode__doc__},
+ {"__unicode__", (PyCFunction)PyTclObject_unicode, METH_NOARGS,
+ PyTclObject_unicode__doc__},
#endif
- {0}
+ {0}
};
statichere PyTypeObject PyTclObject_Type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_tkinter.Tcl_Obj", /*tp_name*/
- sizeof(PyTclObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)PyTclObject_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- (cmpfunc)PyTclObject_cmp, /*tp_compare*/
- (reprfunc)PyTclObject_repr, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- (reprfunc)PyTclObject_str, /*tp_str*/
- PyObject_GenericGetAttr,/*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- PyTclObject_methods, /*tp_methods*/
- 0, /*tp_members*/
- PyTclObject_getsetlist, /*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*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_tkinter.Tcl_Obj", /*tp_name*/
+ sizeof(PyTclObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)PyTclObject_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ (cmpfunc)PyTclObject_cmp, /*tp_compare*/
+ (reprfunc)PyTclObject_repr, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ (reprfunc)PyTclObject_str, /*tp_str*/
+ PyObject_GenericGetAttr,/*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ PyTclObject_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ PyTclObject_getsetlist, /*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*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
static Tcl_Obj*
AsObj(PyObject *value)
{
- Tcl_Obj *result;
-
- if (PyString_Check(value))
- return Tcl_NewStringObj(PyString_AS_STRING(value),
- PyString_GET_SIZE(value));
- else if (PyBool_Check(value))
- return Tcl_NewBooleanObj(PyObject_IsTrue(value));
- else if (PyInt_Check(value))
- return Tcl_NewLongObj(PyInt_AS_LONG(value));
- else if (PyFloat_Check(value))
- return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
- else if (PyTuple_Check(value)) {
- Tcl_Obj **argv = (Tcl_Obj**)
- ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*));
- int i;
- if(!argv)
- return 0;
- for(i=0;i<PyTuple_Size(value);i++)
- argv[i] = AsObj(PyTuple_GetItem(value,i));
- result = Tcl_NewListObj(PyTuple_Size(value), argv);
- ckfree(FREECAST argv);
- return result;
- }
+ Tcl_Obj *result;
+
+ if (PyString_Check(value))
+ return Tcl_NewStringObj(PyString_AS_STRING(value),
+ PyString_GET_SIZE(value));
+ else if (PyBool_Check(value))
+ return Tcl_NewBooleanObj(PyObject_IsTrue(value));
+ else if (PyInt_Check(value))
+ return Tcl_NewLongObj(PyInt_AS_LONG(value));
+ else if (PyFloat_Check(value))
+ return Tcl_NewDoubleObj(PyFloat_AS_DOUBLE(value));
+ else if (PyTuple_Check(value)) {
+ Tcl_Obj **argv = (Tcl_Obj**)
+ ckalloc(PyTuple_Size(value)*sizeof(Tcl_Obj*));
+ int i;
+ if(!argv)
+ return 0;
+ for(i=0;i<PyTuple_Size(value);i++)
+ argv[i] = AsObj(PyTuple_GetItem(value,i));
+ result = Tcl_NewListObj(PyTuple_Size(value), argv);
+ ckfree(FREECAST argv);
+ return result;
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(value)) {
- Py_UNICODE *inbuf = PyUnicode_AS_UNICODE(value);
- Py_ssize_t size = PyUnicode_GET_SIZE(value);
- /* This #ifdef assumes that Tcl uses UCS-2.
- See TCL_UTF_MAX test above. */
+ else if (PyUnicode_Check(value)) {
+ Py_UNICODE *inbuf = PyUnicode_AS_UNICODE(value);
+ Py_ssize_t size = PyUnicode_GET_SIZE(value);
+ /* This #ifdef assumes that Tcl uses UCS-2.
+ See TCL_UTF_MAX test above. */
#if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX == 3
- Tcl_UniChar *outbuf = NULL;
- Py_ssize_t i;
- size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar);
- if (allocsize >= size)
- outbuf = (Tcl_UniChar*)ckalloc(allocsize);
- /* Else overflow occurred, and we take the next exit */
- if (!outbuf) {
- PyErr_NoMemory();
- return NULL;
- }
- for (i = 0; i < size; i++) {
- if (inbuf[i] >= 0x10000) {
- /* Tcl doesn't do UTF-16, yet. */
- PyErr_SetString(PyExc_ValueError,
- "unsupported character");
- ckfree(FREECAST outbuf);
- return NULL;
- }
- outbuf[i] = inbuf[i];
- }
- result = Tcl_NewUnicodeObj(outbuf, size);
- ckfree(FREECAST outbuf);
- return result;
+ Tcl_UniChar *outbuf = NULL;
+ Py_ssize_t i;
+ size_t allocsize = ((size_t)size) * sizeof(Tcl_UniChar);
+ if (allocsize >= size)
+ outbuf = (Tcl_UniChar*)ckalloc(allocsize);
+ /* Else overflow occurred, and we take the next exit */
+ if (!outbuf) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ for (i = 0; i < size; i++) {
+ if (inbuf[i] >= 0x10000) {
+ /* Tcl doesn't do UTF-16, yet. */
+ PyErr_SetString(PyExc_ValueError,
+ "unsupported character");
+ ckfree(FREECAST outbuf);
+ return NULL;
+ }
+ outbuf[i] = inbuf[i];
+ }
+ result = Tcl_NewUnicodeObj(outbuf, size);
+ ckfree(FREECAST outbuf);
+ return result;
#else
- return Tcl_NewUnicodeObj(inbuf, size);
+ return Tcl_NewUnicodeObj(inbuf, size);
#endif
- }
+ }
#endif
- else if(PyTclObject_Check(value)) {
- Tcl_Obj *v = ((PyTclObject*)value)->value;
- Tcl_IncrRefCount(v);
- return v;
- }
- else {
- PyObject *v = PyObject_Str(value);
- if (!v)
- return 0;
- result = AsObj(v);
- Py_DECREF(v);
- return result;
- }
+ else if(PyTclObject_Check(value)) {
+ Tcl_Obj *v = ((PyTclObject*)value)->value;
+ Tcl_IncrRefCount(v);
+ return v;
+ }
+ else {
+ PyObject *v = PyObject_Str(value);
+ if (!v)
+ return 0;
+ result = AsObj(v);
+ Py_DECREF(v);
+ return result;
+ }
}
static PyObject*
FromObj(PyObject* tkapp, Tcl_Obj *value)
{
- PyObject *result = NULL;
- TkappObject *app = (TkappObject*)tkapp;
+ PyObject *result = NULL;
+ TkappObject *app = (TkappObject*)tkapp;
- if (value->typePtr == NULL) {
- /* If the result contains any bytes with the top bit set,
- it's UTF-8 and we should decode it to Unicode */
+ if (value->typePtr == NULL) {
+ /* If the result contains any bytes with the top bit set,
+ it's UTF-8 and we should decode it to Unicode */
#ifdef Py_USING_UNICODE
- int i;
- char *s = value->bytes;
- int len = value->length;
- for (i = 0; i < len; i++) {
- if (value->bytes[i] & 0x80)
- break;
- }
-
- if (i == value->length)
- result = PyString_FromStringAndSize(s, len);
- else {
- /* Convert UTF-8 to Unicode string */
- result = PyUnicode_DecodeUTF8(s, len, "strict");
- if (result == NULL) {
- PyErr_Clear();
- result = PyString_FromStringAndSize(s, len);
- }
- }
+ int i;
+ char *s = value->bytes;
+ int len = value->length;
+ for (i = 0; i < len; i++) {
+ if (value->bytes[i] & 0x80)
+ break;
+ }
+
+ if (i == value->length)
+ result = PyString_FromStringAndSize(s, len);
+ else {
+ /* Convert UTF-8 to Unicode string */
+ result = PyUnicode_DecodeUTF8(s, len, "strict");
+ if (result == NULL) {
+ PyErr_Clear();
+ result = PyString_FromStringAndSize(s, len);
+ }
+ }
#else
- result = PyString_FromStringAndSize(value->bytes, value->length);
-#endif
- return result;
- }
-
- if (value->typePtr == app->BooleanType) {
- result = value->internalRep.longValue ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
- }
-
- if (value->typePtr == app->ByteArrayType) {
- int size;
- char *data = (char*)Tcl_GetByteArrayFromObj(value, &size);
- return PyString_FromStringAndSize(data, size);
- }
-
- if (value->typePtr == app->DoubleType) {
- return PyFloat_FromDouble(value->internalRep.doubleValue);
- }
-
- if (value->typePtr == app->IntType) {
- return PyInt_FromLong(value->internalRep.longValue);
- }
-
- if (value->typePtr == app->ListType) {
- int size;
- int i, status;
- PyObject *elem;
- Tcl_Obj *tcl_elem;
-
- status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size);
- if (status == TCL_ERROR)
- return Tkinter_Error(tkapp);
- result = PyTuple_New(size);
- if (!result)
- return NULL;
- for (i = 0; i < size; i++) {
- status = Tcl_ListObjIndex(Tkapp_Interp(tkapp),
- value, i, &tcl_elem);
- if (status == TCL_ERROR) {
- Py_DECREF(result);
- return Tkinter_Error(tkapp);
- }
- elem = FromObj(tkapp, tcl_elem);
- if (!elem) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SetItem(result, i, elem);
- }
- return result;
- }
-
- if (value->typePtr == app->ProcBodyType) {
- /* fall through: return tcl object. */
- }
-
- if (value->typePtr == app->StringType) {
+ result = PyString_FromStringAndSize(value->bytes, value->length);
+#endif
+ return result;
+ }
+
+ if (value->typePtr == app->BooleanType) {
+ result = value->internalRep.longValue ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
+ }
+
+ if (value->typePtr == app->ByteArrayType) {
+ int size;
+ char *data = (char*)Tcl_GetByteArrayFromObj(value, &size);
+ return PyString_FromStringAndSize(data, size);
+ }
+
+ if (value->typePtr == app->DoubleType) {
+ return PyFloat_FromDouble(value->internalRep.doubleValue);
+ }
+
+ if (value->typePtr == app->IntType) {
+ return PyInt_FromLong(value->internalRep.longValue);
+ }
+
+ if (value->typePtr == app->ListType) {
+ int size;
+ int i, status;
+ PyObject *elem;
+ Tcl_Obj *tcl_elem;
+
+ status = Tcl_ListObjLength(Tkapp_Interp(tkapp), value, &size);
+ if (status == TCL_ERROR)
+ return Tkinter_Error(tkapp);
+ result = PyTuple_New(size);
+ if (!result)
+ return NULL;
+ for (i = 0; i < size; i++) {
+ status = Tcl_ListObjIndex(Tkapp_Interp(tkapp),
+ value, i, &tcl_elem);
+ if (status == TCL_ERROR) {
+ Py_DECREF(result);
+ return Tkinter_Error(tkapp);
+ }
+ elem = FromObj(tkapp, tcl_elem);
+ if (!elem) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SetItem(result, i, elem);
+ }
+ return result;
+ }
+
+ if (value->typePtr == app->ProcBodyType) {
+ /* fall through: return tcl object. */
+ }
+
+ if (value->typePtr == app->StringType) {
#ifdef Py_USING_UNICODE
#if defined(Py_UNICODE_WIDE) && TCL_UTF_MAX==3
- PyObject *result;
- int size;
- Tcl_UniChar *input;
- Py_UNICODE *output;
-
- size = Tcl_GetCharLength(value);
- result = PyUnicode_FromUnicode(NULL, size);
- if (!result)
- return NULL;
- input = Tcl_GetUnicode(value);
- output = PyUnicode_AS_UNICODE(result);
- while (size--)
- *output++ = *input++;
- return result;
+ PyObject *result;
+ int size;
+ Tcl_UniChar *input;
+ Py_UNICODE *output;
+
+ size = Tcl_GetCharLength(value);
+ result = PyUnicode_FromUnicode(NULL, size);
+ if (!result)
+ return NULL;
+ input = Tcl_GetUnicode(value);
+ output = PyUnicode_AS_UNICODE(result);
+ while (size--)
+ *output++ = *input++;
+ return result;
#else
- return PyUnicode_FromUnicode(Tcl_GetUnicode(value),
- Tcl_GetCharLength(value));
+ return PyUnicode_FromUnicode(Tcl_GetUnicode(value),
+ Tcl_GetCharLength(value));
#endif
#else
- int size;
- char *c;
- c = Tcl_GetStringFromObj(value, &size);
- return PyString_FromStringAndSize(c, size);
+ int size;
+ char *c;
+ c = Tcl_GetStringFromObj(value, &size);
+ return PyString_FromStringAndSize(c, size);
#endif
- }
+ }
- return newPyTclObject(value);
+ return newPyTclObject(value);
}
#ifdef WITH_THREAD
@@ -1142,24 +1142,24 @@ FromObj(PyObject* tkapp, Tcl_Obj *value)
TCL_DECLARE_MUTEX(call_mutex)
typedef struct Tkapp_CallEvent {
- Tcl_Event ev; /* Must be first */
- TkappObject *self;
- PyObject *args;
- int flags;
- PyObject **res;
- PyObject **exc_type, **exc_value, **exc_tb;
- Tcl_Condition *done;
+ Tcl_Event ev; /* Must be first */
+ TkappObject *self;
+ PyObject *args;
+ int flags;
+ PyObject **res;
+ PyObject **exc_type, **exc_value, **exc_tb;
+ Tcl_Condition *done;
} Tkapp_CallEvent;
#endif
void
Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc)
{
- int i;
- for (i = 0; i < objc; i++)
- Tcl_DecrRefCount(objv[i]);
- if (objv != objStore)
- ckfree(FREECAST objv);
+ int i;
+ for (i = 0; i < objc; i++)
+ Tcl_DecrRefCount(objv[i]);
+ if (objv != objStore)
+ ckfree(FREECAST objv);
}
/* Convert Python objects to Tcl objects. This must happen in the
@@ -1168,51 +1168,51 @@ Tkapp_CallDeallocArgs(Tcl_Obj** objv, Tcl_Obj** objStore, int objc)
static Tcl_Obj**
Tkapp_CallArgs(PyObject *args, Tcl_Obj** objStore, int *pobjc)
{
- Tcl_Obj **objv = objStore;
- int objc = 0, i;
- if (args == NULL)
- /* do nothing */;
-
- else if (!PyTuple_Check(args)) {
- objv[0] = AsObj(args);
- if (objv[0] == 0)
- goto finally;
- objc = 1;
- Tcl_IncrRefCount(objv[0]);
- }
- else {
- objc = PyTuple_Size(args);
-
- if (objc > ARGSZ) {
- objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
- if (objv == NULL) {
- PyErr_NoMemory();
- objc = 0;
- goto finally;
- }
- }
-
- for (i = 0; i < objc; i++) {
- PyObject *v = PyTuple_GetItem(args, i);
- if (v == Py_None) {
- objc = i;
- break;
- }
- objv[i] = AsObj(v);
- if (!objv[i]) {
- /* Reset objc, so it attempts to clear
- objects only up to i. */
- objc = i;
- goto finally;
- }
- Tcl_IncrRefCount(objv[i]);
- }
- }
- *pobjc = objc;
- return objv;
+ Tcl_Obj **objv = objStore;
+ int objc = 0, i;
+ if (args == NULL)
+ /* do nothing */;
+
+ else if (!PyTuple_Check(args)) {
+ objv[0] = AsObj(args);
+ if (objv[0] == 0)
+ goto finally;
+ objc = 1;
+ Tcl_IncrRefCount(objv[0]);
+ }
+ else {
+ objc = PyTuple_Size(args);
+
+ if (objc > ARGSZ) {
+ objv = (Tcl_Obj **)ckalloc(objc * sizeof(char *));
+ if (objv == NULL) {
+ PyErr_NoMemory();
+ objc = 0;
+ goto finally;
+ }
+ }
+
+ for (i = 0; i < objc; i++) {
+ PyObject *v = PyTuple_GetItem(args, i);
+ if (v == Py_None) {
+ objc = i;
+ break;
+ }
+ objv[i] = AsObj(v);
+ if (!objv[i]) {
+ /* Reset objc, so it attempts to clear
+ objects only up to i. */
+ objc = i;
+ goto finally;
+ }
+ Tcl_IncrRefCount(objv[i]);
+ }
+ }
+ *pobjc = objc;
+ return objv;
finally:
- Tkapp_CallDeallocArgs(objv, objStore, objc);
- return NULL;
+ Tkapp_CallDeallocArgs(objv, objStore, objc);
+ return NULL;
}
/* Convert the results of a command call into a Python objects. */
@@ -1220,45 +1220,45 @@ finally:
static PyObject*
Tkapp_CallResult(TkappObject *self)
{
- PyObject *res = NULL;
- if(self->wantobjects) {
- Tcl_Obj *value = Tcl_GetObjResult(self->interp);
- /* Not sure whether the IncrRef is necessary, but something
- may overwrite the interpreter result while we are
- converting it. */
- Tcl_IncrRefCount(value);
- res = FromObj((PyObject*)self, value);
- Tcl_DecrRefCount(value);
- } else {
- const char *s = Tcl_GetStringResult(self->interp);
- const char *p = s;
-
- /* If the result contains any bytes with the top bit set,
- it's UTF-8 and we should decode it to Unicode */
+ PyObject *res = NULL;
+ if(self->wantobjects) {
+ Tcl_Obj *value = Tcl_GetObjResult(self->interp);
+ /* Not sure whether the IncrRef is necessary, but something
+ may overwrite the interpreter result while we are
+ converting it. */
+ Tcl_IncrRefCount(value);
+ res = FromObj((PyObject*)self, value);
+ Tcl_DecrRefCount(value);
+ } else {
+ const char *s = Tcl_GetStringResult(self->interp);
+ const char *p = s;
+
+ /* If the result contains any bytes with the top bit set,
+ it's UTF-8 and we should decode it to Unicode */
#ifdef Py_USING_UNICODE
- while (*p != '\0') {
- if (*p & 0x80)
- break;
- p++;
- }
-
- if (*p == '\0')
- res = PyString_FromStringAndSize(s, (int)(p-s));
- else {
- /* Convert UTF-8 to Unicode string */
- p = strchr(p, '\0');
- res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
- if (res == NULL) {
- PyErr_Clear();
- res = PyString_FromStringAndSize(s, (int)(p-s));
- }
- }
+ while (*p != '\0') {
+ if (*p & 0x80)
+ break;
+ p++;
+ }
+
+ if (*p == '\0')
+ res = PyString_FromStringAndSize(s, (int)(p-s));
+ else {
+ /* Convert UTF-8 to Unicode string */
+ p = strchr(p, '\0');
+ res = PyUnicode_DecodeUTF8(s, (int)(p-s), "strict");
+ if (res == NULL) {
+ PyErr_Clear();
+ res = PyString_FromStringAndSize(s, (int)(p-s));
+ }
+ }
#else
- p = strchr(p, '\0');
- res = PyString_FromStringAndSize(s, (int)(p-s));
+ p = strchr(p, '\0');
+ res = PyString_FromStringAndSize(s, (int)(p-s));
#endif
- }
- return res;
+ }
+ return res;
}
#ifdef WITH_THREAD
@@ -1270,41 +1270,41 @@ Tkapp_CallResult(TkappObject *self)
static int
Tkapp_CallProc(Tkapp_CallEvent *e, int flags)
{
- Tcl_Obj *objStore[ARGSZ];
- Tcl_Obj **objv;
- int objc;
- int i;
- ENTER_PYTHON
- objv = Tkapp_CallArgs(e->args, objStore, &objc);
- if (!objv) {
- PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb);
- *(e->res) = NULL;
- }
- LEAVE_PYTHON
- if (!objv)
- goto done;
- i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags);
- ENTER_PYTHON
- if (i == TCL_ERROR) {
- *(e->res) = NULL;
- *(e->exc_type) = NULL;
- *(e->exc_tb) = NULL;
- *(e->exc_value) = PyObject_CallFunction(
- Tkinter_TclError, "s",
- Tcl_GetStringResult(e->self->interp));
- }
- else {
- *(e->res) = Tkapp_CallResult(e->self);
- }
- LEAVE_PYTHON
-
- Tkapp_CallDeallocArgs(objv, objStore, objc);
+ Tcl_Obj *objStore[ARGSZ];
+ Tcl_Obj **objv;
+ int objc;
+ int i;
+ ENTER_PYTHON
+ objv = Tkapp_CallArgs(e->args, objStore, &objc);
+ if (!objv) {
+ PyErr_Fetch(e->exc_type, e->exc_value, e->exc_tb);
+ *(e->res) = NULL;
+ }
+ LEAVE_PYTHON
+ if (!objv)
+ goto done;
+ i = Tcl_EvalObjv(e->self->interp, objc, objv, e->flags);
+ ENTER_PYTHON
+ if (i == TCL_ERROR) {
+ *(e->res) = NULL;
+ *(e->exc_type) = NULL;
+ *(e->exc_tb) = NULL;
+ *(e->exc_value) = PyObject_CallFunction(
+ Tkinter_TclError, "s",
+ Tcl_GetStringResult(e->self->interp));
+ }
+ else {
+ *(e->res) = Tkapp_CallResult(e->self);
+ }
+ LEAVE_PYTHON
+
+ Tkapp_CallDeallocArgs(objv, objStore, objc);
done:
- /* Wake up calling thread. */
- Tcl_MutexLock(&call_mutex);
- Tcl_ConditionNotify(e->done);
- Tcl_MutexUnlock(&call_mutex);
- return 1;
+ /* Wake up calling thread. */
+ Tcl_MutexLock(&call_mutex);
+ Tcl_ConditionNotify(e->done);
+ Tcl_MutexUnlock(&call_mutex);
+ return 1;
}
#endif
@@ -1324,218 +1324,218 @@ done:
static PyObject *
Tkapp_Call(PyObject *selfptr, PyObject *args)
{
- Tcl_Obj *objStore[ARGSZ];
- Tcl_Obj **objv = NULL;
- int objc, i;
- PyObject *res = NULL;
- TkappObject *self = (TkappObject*)selfptr;
- int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL;
-
- /* If args is a single tuple, replace with contents of tuple */
- if (1 == PyTuple_Size(args)){
- PyObject* item = PyTuple_GetItem(args, 0);
- if (PyTuple_Check(item))
- args = item;
- }
+ Tcl_Obj *objStore[ARGSZ];
+ Tcl_Obj **objv = NULL;
+ int objc, i;
+ PyObject *res = NULL;
+ TkappObject *self = (TkappObject*)selfptr;
+ int flags = TCL_EVAL_DIRECT | TCL_EVAL_GLOBAL;
+
+ /* If args is a single tuple, replace with contents of tuple */
+ if (1 == PyTuple_Size(args)){
+ PyObject* item = PyTuple_GetItem(args, 0);
+ if (PyTuple_Check(item))
+ args = item;
+ }
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- /* We cannot call the command directly. Instead, we must
- marshal the parameters to the interpreter thread. */
- Tkapp_CallEvent *ev;
- Tcl_Condition cond = NULL;
- PyObject *exc_type, *exc_value, *exc_tb;
- if (!WaitForMainloop(self))
- return NULL;
- ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent));
- ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc;
- ev->self = self;
- ev->args = args;
- ev->res = &res;
- ev->exc_type = &exc_type;
- ev->exc_value = &exc_value;
- ev->exc_tb = &exc_tb;
- ev->done = &cond;
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ /* We cannot call the command directly. Instead, we must
+ marshal the parameters to the interpreter thread. */
+ Tkapp_CallEvent *ev;
+ Tcl_Condition cond = NULL;
+ PyObject *exc_type, *exc_value, *exc_tb;
+ if (!WaitForMainloop(self))
+ return NULL;
+ ev = (Tkapp_CallEvent*)ckalloc(sizeof(Tkapp_CallEvent));
+ ev->ev.proc = (Tcl_EventProc*)Tkapp_CallProc;
+ ev->self = self;
+ ev->args = args;
+ ev->res = &res;
+ ev->exc_type = &exc_type;
+ ev->exc_value = &exc_value;
+ ev->exc_tb = &exc_tb;
+ ev->done = &cond;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex);
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &call_mutex);
- if (res == NULL) {
- if (exc_type)
- PyErr_Restore(exc_type, exc_value, exc_tb);
- else
- PyErr_SetObject(Tkinter_TclError, exc_value);
- }
- Tcl_ConditionFinalize(&cond);
- }
- else
+ if (res == NULL) {
+ if (exc_type)
+ PyErr_Restore(exc_type, exc_value, exc_tb);
+ else
+ PyErr_SetObject(Tkinter_TclError, exc_value);
+ }
+ Tcl_ConditionFinalize(&cond);
+ }
+ else
#endif
- {
+ {
- objv = Tkapp_CallArgs(args, objStore, &objc);
- if (!objv)
- return NULL;
+ objv = Tkapp_CallArgs(args, objStore, &objc);
+ if (!objv)
+ return NULL;
- ENTER_TCL
+ ENTER_TCL
- i = Tcl_EvalObjv(self->interp, objc, objv, flags);
+ i = Tcl_EvalObjv(self->interp, objc, objv, flags);
- ENTER_OVERLAP
+ ENTER_OVERLAP
- if (i == TCL_ERROR)
- Tkinter_Error(selfptr);
- else
- res = Tkapp_CallResult(self);
+ if (i == TCL_ERROR)
+ Tkinter_Error(selfptr);
+ else
+ res = Tkapp_CallResult(self);
- LEAVE_OVERLAP_TCL
+ LEAVE_OVERLAP_TCL
- Tkapp_CallDeallocArgs(objv, objStore, objc);
- }
- return res;
+ Tkapp_CallDeallocArgs(objv, objStore, objc);
+ }
+ return res;
}
static PyObject *
Tkapp_GlobalCall(PyObject *self, PyObject *args)
{
- /* Could do the same here as for Tkapp_Call(), but this is not used
- much, so I can't be bothered. Unfortunately Tcl doesn't export a
- way for the user to do what all its Global* variants do (save and
- reset the scope pointer, call the local version, restore the saved
- scope pointer). */
+ /* Could do the same here as for Tkapp_Call(), but this is not used
+ much, so I can't be bothered. Unfortunately Tcl doesn't export a
+ way for the user to do what all its Global* variants do (save and
+ reset the scope pointer, call the local version, restore the saved
+ scope pointer). */
- char *cmd;
- PyObject *res = NULL;
+ char *cmd;
+ PyObject *res = NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- cmd = Merge(args);
- if (cmd) {
- int err;
- ENTER_TCL
- err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyString_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- ckfree(cmd);
- }
+ cmd = Merge(args);
+ if (cmd) {
+ int err;
+ ENTER_TCL
+ err = Tcl_GlobalEval(Tkapp_Interp(self), cmd);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyString_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ ckfree(cmd);
+ }
- return res;
+ return res;
}
static PyObject *
Tkapp_Eval(PyObject *self, PyObject *args)
{
- char *script;
- PyObject *res = NULL;
- int err;
+ char *script;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s:eval", &script))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:eval", &script))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_Eval(Tkapp_Interp(self), script);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyString_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ err = Tcl_Eval(Tkapp_Interp(self), script);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyString_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_GlobalEval(PyObject *self, PyObject *args)
{
- char *script;
- PyObject *res = NULL;
- int err;
+ char *script;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s:globaleval", &script))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:globaleval", &script))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_GlobalEval(Tkapp_Interp(self), script);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyString_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ err = Tcl_GlobalEval(Tkapp_Interp(self), script);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyString_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_EvalFile(PyObject *self, PyObject *args)
{
- char *fileName;
- PyObject *res = NULL;
- int err;
+ char *fileName;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s:evalfile", &fileName))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:evalfile", &fileName))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
+ ENTER_TCL
+ err = Tcl_EvalFile(Tkapp_Interp(self), fileName);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
- else
- res = PyString_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ else
+ res = PyString_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_Record(PyObject *self, PyObject *args)
{
- char *script;
- PyObject *res = NULL;
- int err;
+ char *script;
+ PyObject *res = NULL;
+ int err;
- if (!PyArg_ParseTuple(args, "s", &script))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s", &script))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
- ENTER_OVERLAP
- if (err == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = PyString_FromString(Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ err = Tcl_RecordAndEval(Tkapp_Interp(self), script, TCL_NO_EVAL);
+ ENTER_OVERLAP
+ if (err == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = PyString_FromString(Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_AddErrorInfo(PyObject *self, PyObject *args)
{
- char *msg;
+ char *msg;
- if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg))
- return NULL;
- CHECK_TCL_APPARTMENT;
+ if (!PyArg_ParseTuple(args, "s:adderrorinfo", &msg))
+ return NULL;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
- LEAVE_TCL
+ ENTER_TCL
+ Tcl_AddErrorInfo(Tkapp_Interp(self), msg);
+ LEAVE_TCL
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
/** Tcl Variable **/
typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags);
@@ -1544,61 +1544,61 @@ typedef PyObject* (*EventFunc)(PyObject*, PyObject *args, int flags);
TCL_DECLARE_MUTEX(var_mutex)
typedef struct VarEvent {
- Tcl_Event ev; /* must be first */
- PyObject *self;
- PyObject *args;
- int flags;
- EventFunc func;
- PyObject **res;
- PyObject **exc_type;
- PyObject **exc_val;
- Tcl_Condition *cond;
+ Tcl_Event ev; /* must be first */
+ PyObject *self;
+ PyObject *args;
+ int flags;
+ EventFunc func;
+ PyObject **res;
+ PyObject **exc_type;
+ PyObject **exc_val;
+ Tcl_Condition *cond;
} VarEvent;
#endif
static int
varname_converter(PyObject *in, void *_out)
{
- char **out = (char**)_out;
- if (PyString_Check(in)) {
- *out = PyString_AsString(in);
- return 1;
- }
- if (PyTclObject_Check(in)) {
- *out = PyTclObject_TclString(in);
- return 1;
- }
- /* XXX: Should give diagnostics. */
- return 0;
-}
+ char **out = (char**)_out;
+ if (PyString_Check(in)) {
+ *out = PyString_AsString(in);
+ return 1;
+ }
+ if (PyTclObject_Check(in)) {
+ *out = PyTclObject_TclString(in);
+ return 1;
+ }
+ /* XXX: Should give diagnostics. */
+ return 0;
+}
#ifdef WITH_THREAD
static void
var_perform(VarEvent *ev)
{
- *(ev->res) = ev->func(ev->self, ev->args, ev->flags);
- if (!*(ev->res)) {
- PyObject *exc, *val, *tb;
- PyErr_Fetch(&exc, &val, &tb);
- PyErr_NormalizeException(&exc, &val, &tb);
- *(ev->exc_type) = exc;
- *(ev->exc_val) = val;
- Py_DECREF(tb);
- }
-
+ *(ev->res) = ev->func(ev->self, ev->args, ev->flags);
+ if (!*(ev->res)) {
+ PyObject *exc, *val, *tb;
+ PyErr_Fetch(&exc, &val, &tb);
+ PyErr_NormalizeException(&exc, &val, &tb);
+ *(ev->exc_type) = exc;
+ *(ev->exc_val) = val;
+ Py_DECREF(tb);
+ }
+
}
static int
var_proc(VarEvent* ev, int flags)
{
- ENTER_PYTHON
- var_perform(ev);
- Tcl_MutexLock(&var_mutex);
- Tcl_ConditionNotify(ev->cond);
- Tcl_MutexUnlock(&var_mutex);
- LEAVE_PYTHON
- return 1;
+ ENTER_PYTHON
+ var_perform(ev);
+ Tcl_MutexLock(&var_mutex);
+ Tcl_ConditionNotify(ev->cond);
+ Tcl_MutexUnlock(&var_mutex);
+ LEAVE_PYTHON
+ return 1;
}
#endif
@@ -1607,439 +1607,439 @@ static PyObject*
var_invoke(EventFunc func, PyObject *selfptr, PyObject *args, int flags)
{
#ifdef WITH_THREAD
- TkappObject *self = (TkappObject*)selfptr;
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- TkappObject *self = (TkappObject*)selfptr;
- VarEvent *ev;
- PyObject *res, *exc_type, *exc_val;
- Tcl_Condition cond = NULL;
-
- /* The current thread is not the interpreter thread. Marshal
- the call to the interpreter thread, then wait for
- completion. */
- if (!WaitForMainloop(self))
- return NULL;
-
- ev = (VarEvent*)ckalloc(sizeof(VarEvent));
-
- ev->self = selfptr;
- ev->args = args;
- ev->flags = flags;
- ev->func = func;
- ev->res = &res;
- ev->exc_type = &exc_type;
- ev->exc_val = &exc_val;
- ev->cond = &cond;
- ev->ev.proc = (Tcl_EventProc*)var_proc;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex);
- Tcl_ConditionFinalize(&cond);
- if (!res) {
- PyErr_SetObject(exc_type, exc_val);
- Py_DECREF(exc_type);
- Py_DECREF(exc_val);
- return NULL;
- }
- return res;
- }
-#endif
- /* Tcl is not threaded, or this is the interpreter thread. */
- return func(selfptr, args, flags);
+ TkappObject *self = (TkappObject*)selfptr;
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ TkappObject *self = (TkappObject*)selfptr;
+ VarEvent *ev;
+ PyObject *res, *exc_type, *exc_val;
+ Tcl_Condition cond = NULL;
+
+ /* The current thread is not the interpreter thread. Marshal
+ the call to the interpreter thread, then wait for
+ completion. */
+ if (!WaitForMainloop(self))
+ return NULL;
+
+ ev = (VarEvent*)ckalloc(sizeof(VarEvent));
+
+ ev->self = selfptr;
+ ev->args = args;
+ ev->flags = flags;
+ ev->func = func;
+ ev->res = &res;
+ ev->exc_type = &exc_type;
+ ev->exc_val = &exc_val;
+ ev->cond = &cond;
+ ev->ev.proc = (Tcl_EventProc*)var_proc;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &var_mutex);
+ Tcl_ConditionFinalize(&cond);
+ if (!res) {
+ PyErr_SetObject(exc_type, exc_val);
+ Py_DECREF(exc_type);
+ Py_DECREF(exc_val);
+ return NULL;
+ }
+ return res;
+ }
+#endif
+ /* Tcl is not threaded, or this is the interpreter thread. */
+ return func(selfptr, args, flags);
}
static PyObject *
SetVar(PyObject *self, PyObject *args, int flags)
{
- char *name1, *name2;
- PyObject *newValue;
- PyObject *res = NULL;
- Tcl_Obj *newval, *ok;
-
- if (PyArg_ParseTuple(args, "O&O:setvar",
- varname_converter, &name1, &newValue)) {
- /* XXX Acquire tcl lock??? */
- newval = AsObj(newValue);
- if (newval == NULL)
- return NULL;
- ENTER_TCL
- ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL,
- newval, flags);
- ENTER_OVERLAP
- if (!ok)
- Tkinter_Error(self);
- else {
- res = Py_None;
- Py_INCREF(res);
- }
- LEAVE_OVERLAP_TCL
- }
- else {
- PyErr_Clear();
- if (PyArg_ParseTuple(args, "ssO:setvar",
- &name1, &name2, &newValue)) {
- /* XXX must hold tcl lock already??? */
- newval = AsObj(newValue);
- ENTER_TCL
- ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags);
- ENTER_OVERLAP
- if (!ok)
- Tkinter_Error(self);
- else {
- res = Py_None;
- Py_INCREF(res);
- }
- LEAVE_OVERLAP_TCL
- }
- else {
- return NULL;
- }
- }
- return res;
+ char *name1, *name2;
+ PyObject *newValue;
+ PyObject *res = NULL;
+ Tcl_Obj *newval, *ok;
+
+ if (PyArg_ParseTuple(args, "O&O:setvar",
+ varname_converter, &name1, &newValue)) {
+ /* XXX Acquire tcl lock??? */
+ newval = AsObj(newValue);
+ if (newval == NULL)
+ return NULL;
+ ENTER_TCL
+ ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, NULL,
+ newval, flags);
+ ENTER_OVERLAP
+ if (!ok)
+ Tkinter_Error(self);
+ else {
+ res = Py_None;
+ Py_INCREF(res);
+ }
+ LEAVE_OVERLAP_TCL
+ }
+ else {
+ PyErr_Clear();
+ if (PyArg_ParseTuple(args, "ssO:setvar",
+ &name1, &name2, &newValue)) {
+ /* XXX must hold tcl lock already??? */
+ newval = AsObj(newValue);
+ ENTER_TCL
+ ok = Tcl_SetVar2Ex(Tkapp_Interp(self), name1, name2, newval, flags);
+ ENTER_OVERLAP
+ if (!ok)
+ Tkinter_Error(self);
+ else {
+ res = Py_None;
+ Py_INCREF(res);
+ }
+ LEAVE_OVERLAP_TCL
+ }
+ else {
+ return NULL;
+ }
+ }
+ return res;
}
static PyObject *
Tkapp_SetVar(PyObject *self, PyObject *args)
{
- return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG);
+ return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG);
}
static PyObject *
Tkapp_GlobalSetVar(PyObject *self, PyObject *args)
{
- return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
+ return var_invoke(SetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
}
-
+
static PyObject *
GetVar(PyObject *self, PyObject *args, int flags)
{
- char *name1, *name2=NULL;
- PyObject *res = NULL;
- Tcl_Obj *tres;
-
- if (!PyArg_ParseTuple(args, "O&|s:getvar",
- varname_converter, &name1, &name2))
- return NULL;
-
- ENTER_TCL
- tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags);
- ENTER_OVERLAP
- if (tres == NULL) {
- PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
- } else {
- if (((TkappObject*)self)->wantobjects) {
- res = FromObj(self, tres);
- }
- else {
- res = PyString_FromString(Tcl_GetString(tres));
- }
- }
- LEAVE_OVERLAP_TCL
- return res;
+ char *name1, *name2=NULL;
+ PyObject *res = NULL;
+ Tcl_Obj *tres;
+
+ if (!PyArg_ParseTuple(args, "O&|s:getvar",
+ varname_converter, &name1, &name2))
+ return NULL;
+
+ ENTER_TCL
+ tres = Tcl_GetVar2Ex(Tkapp_Interp(self), name1, name2, flags);
+ ENTER_OVERLAP
+ if (tres == NULL) {
+ PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
+ } else {
+ if (((TkappObject*)self)->wantobjects) {
+ res = FromObj(self, tres);
+ }
+ else {
+ res = PyString_FromString(Tcl_GetString(tres));
+ }
+ }
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_GetVar(PyObject *self, PyObject *args)
{
- return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG);
+ return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG);
}
static PyObject *
Tkapp_GlobalGetVar(PyObject *self, PyObject *args)
{
- return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
+ return var_invoke(GetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
}
-
+
static PyObject *
UnsetVar(PyObject *self, PyObject *args, int flags)
{
- char *name1, *name2=NULL;
- int code;
- PyObject *res = NULL;
+ char *name1, *name2=NULL;
+ int code;
+ PyObject *res = NULL;
- if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s|s:unsetvar", &name1, &name2))
+ return NULL;
- ENTER_TCL
- code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
- ENTER_OVERLAP
- if (code == TCL_ERROR)
- res = Tkinter_Error(self);
- else {
- Py_INCREF(Py_None);
- res = Py_None;
- }
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ code = Tcl_UnsetVar2(Tkapp_Interp(self), name1, name2, flags);
+ ENTER_OVERLAP
+ if (code == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else {
+ Py_INCREF(Py_None);
+ res = Py_None;
+ }
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_UnsetVar(PyObject *self, PyObject *args)
{
- return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG);
+ return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG);
}
static PyObject *
Tkapp_GlobalUnsetVar(PyObject *self, PyObject *args)
{
- return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
+ return var_invoke(UnsetVar, self, args, TCL_LEAVE_ERR_MSG | TCL_GLOBAL_ONLY);
}
-
+
/** Tcl to Python **/
static PyObject *
Tkapp_GetInt(PyObject *self, PyObject *args)
{
- char *s;
- int v;
+ char *s;
+ int v;
- if (PyTuple_Size(args) == 1) {
- PyObject* o = PyTuple_GetItem(args, 0);
- if (PyInt_Check(o)) {
- Py_INCREF(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "s:getint", &s))
- return NULL;
- if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
- return Tkinter_Error(self);
- return Py_BuildValue("i", v);
+ if (PyTuple_Size(args) == 1) {
+ PyObject* o = PyTuple_GetItem(args, 0);
+ if (PyInt_Check(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "s:getint", &s))
+ return NULL;
+ if (Tcl_GetInt(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+ return Tkinter_Error(self);
+ return Py_BuildValue("i", v);
}
static PyObject *
Tkapp_GetDouble(PyObject *self, PyObject *args)
{
- char *s;
- double v;
+ char *s;
+ double v;
- if (PyTuple_Size(args) == 1) {
- PyObject *o = PyTuple_GetItem(args, 0);
- if (PyFloat_Check(o)) {
- Py_INCREF(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "s:getdouble", &s))
- return NULL;
- if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
- return Tkinter_Error(self);
- return Py_BuildValue("d", v);
+ if (PyTuple_Size(args) == 1) {
+ PyObject *o = PyTuple_GetItem(args, 0);
+ if (PyFloat_Check(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "s:getdouble", &s))
+ return NULL;
+ if (Tcl_GetDouble(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+ return Tkinter_Error(self);
+ return Py_BuildValue("d", v);
}
static PyObject *
Tkapp_GetBoolean(PyObject *self, PyObject *args)
{
- char *s;
- int v;
+ char *s;
+ int v;
- if (PyTuple_Size(args) == 1) {
- PyObject *o = PyTuple_GetItem(args, 0);
- if (PyInt_Check(o)) {
- Py_INCREF(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "s:getboolean", &s))
- return NULL;
- if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
- return Tkinter_Error(self);
- return PyBool_FromLong(v);
+ if (PyTuple_Size(args) == 1) {
+ PyObject *o = PyTuple_GetItem(args, 0);
+ if (PyInt_Check(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "s:getboolean", &s))
+ return NULL;
+ if (Tcl_GetBoolean(Tkapp_Interp(self), s, &v) == TCL_ERROR)
+ return Tkinter_Error(self);
+ return PyBool_FromLong(v);
}
static PyObject *
Tkapp_ExprString(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- int retval;
+ char *s;
+ PyObject *res = NULL;
+ int retval;
+
+ if (!PyArg_ParseTuple(args, "s:exprstring", &s))
+ return NULL;
- if (!PyArg_ParseTuple(args, "s:exprstring", &s))
- return NULL;
-
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- retval = Tcl_ExprString(Tkapp_Interp(self), s);
- ENTER_OVERLAP
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("s", Tkapp_Result(self));
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ retval = Tcl_ExprString(Tkapp_Interp(self), s);
+ ENTER_OVERLAP
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("s", Tkapp_Result(self));
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_ExprLong(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- int retval;
- long v;
+ char *s;
+ PyObject *res = NULL;
+ int retval;
+ long v;
- if (!PyArg_ParseTuple(args, "s:exprlong", &s))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:exprlong", &s))
+ return NULL;
- CHECK_TCL_APPARTMENT;
+ CHECK_TCL_APPARTMENT;
- ENTER_TCL
- retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
- ENTER_OVERLAP
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("l", v);
- LEAVE_OVERLAP_TCL
- return res;
+ ENTER_TCL
+ retval = Tcl_ExprLong(Tkapp_Interp(self), s, &v);
+ ENTER_OVERLAP
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("l", v);
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_ExprDouble(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- double v;
- int retval;
-
- if (!PyArg_ParseTuple(args, "s:exprdouble", &s))
- return NULL;
- CHECK_TCL_APPARTMENT;
- PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
- ENTER_TCL
- retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
- ENTER_OVERLAP
- PyFPE_END_PROTECT(retval)
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("d", v);
- LEAVE_OVERLAP_TCL
- return res;
+ char *s;
+ PyObject *res = NULL;
+ double v;
+ int retval;
+
+ if (!PyArg_ParseTuple(args, "s:exprdouble", &s))
+ return NULL;
+ CHECK_TCL_APPARTMENT;
+ PyFPE_START_PROTECT("Tkapp_ExprDouble", return 0)
+ ENTER_TCL
+ retval = Tcl_ExprDouble(Tkapp_Interp(self), s, &v);
+ ENTER_OVERLAP
+ PyFPE_END_PROTECT(retval)
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("d", v);
+ LEAVE_OVERLAP_TCL
+ return res;
}
static PyObject *
Tkapp_ExprBoolean(PyObject *self, PyObject *args)
{
- char *s;
- PyObject *res = NULL;
- int retval;
- int v;
+ char *s;
+ PyObject *res = NULL;
+ int retval;
+ int v;
- if (!PyArg_ParseTuple(args, "s:exprboolean", &s))
- return NULL;
- CHECK_TCL_APPARTMENT;
- ENTER_TCL
- retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
- ENTER_OVERLAP
- if (retval == TCL_ERROR)
- res = Tkinter_Error(self);
- else
- res = Py_BuildValue("i", v);
- LEAVE_OVERLAP_TCL
- return res;
+ if (!PyArg_ParseTuple(args, "s:exprboolean", &s))
+ return NULL;
+ CHECK_TCL_APPARTMENT;
+ ENTER_TCL
+ retval = Tcl_ExprBoolean(Tkapp_Interp(self), s, &v);
+ ENTER_OVERLAP
+ if (retval == TCL_ERROR)
+ res = Tkinter_Error(self);
+ else
+ res = Py_BuildValue("i", v);
+ LEAVE_OVERLAP_TCL
+ return res;
}
-
+
static PyObject *
Tkapp_SplitList(PyObject *self, PyObject *args)
{
- char *list;
- int argc;
- char **argv;
- PyObject *v;
- int i;
-
- if (PyTuple_Size(args) == 1) {
- v = PyTuple_GetItem(args, 0);
- if (PyTuple_Check(v)) {
- Py_INCREF(v);
- return v;
- }
- }
- if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list))
- return NULL;
-
- if (Tcl_SplitList(Tkapp_Interp(self), list,
- &argc, &argv) == TCL_ERROR) {
- PyMem_Free(list);
- return Tkinter_Error(self);
- }
-
- if (!(v = PyTuple_New(argc)))
- goto finally;
-
- for (i = 0; i < argc; i++) {
- PyObject *s = PyString_FromString(argv[i]);
- if (!s || PyTuple_SetItem(v, i, s)) {
- Py_DECREF(v);
- v = NULL;
- goto finally;
- }
- }
+ char *list;
+ int argc;
+ char **argv;
+ PyObject *v;
+ int i;
+
+ if (PyTuple_Size(args) == 1) {
+ v = PyTuple_GetItem(args, 0);
+ if (PyTuple_Check(v)) {
+ Py_INCREF(v);
+ return v;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "et:splitlist", "utf-8", &list))
+ return NULL;
+
+ if (Tcl_SplitList(Tkapp_Interp(self), list,
+ &argc, &argv) == TCL_ERROR) {
+ PyMem_Free(list);
+ return Tkinter_Error(self);
+ }
+
+ if (!(v = PyTuple_New(argc)))
+ goto finally;
+
+ for (i = 0; i < argc; i++) {
+ PyObject *s = PyString_FromString(argv[i]);
+ if (!s || PyTuple_SetItem(v, i, s)) {
+ Py_DECREF(v);
+ v = NULL;
+ goto finally;
+ }
+ }
finally:
- ckfree(FREECAST argv);
- PyMem_Free(list);
- return v;
+ ckfree(FREECAST argv);
+ PyMem_Free(list);
+ return v;
}
static PyObject *
Tkapp_Split(PyObject *self, PyObject *args)
{
- PyObject *v;
- char *list;
+ PyObject *v;
+ char *list;
- if (PyTuple_Size(args) == 1) {
- PyObject* o = PyTuple_GetItem(args, 0);
- if (PyTuple_Check(o)) {
- o = SplitObj(o);
- return o;
- }
- }
- if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list))
- return NULL;
- v = Split(list);
- PyMem_Free(list);
- return v;
+ if (PyTuple_Size(args) == 1) {
+ PyObject* o = PyTuple_GetItem(args, 0);
+ if (PyTuple_Check(o)) {
+ o = SplitObj(o);
+ return o;
+ }
+ }
+ if (!PyArg_ParseTuple(args, "et:split", "utf-8", &list))
+ return NULL;
+ v = Split(list);
+ PyMem_Free(list);
+ return v;
}
static PyObject *
Tkapp_Merge(PyObject *self, PyObject *args)
{
- char *s = Merge(args);
- PyObject *res = NULL;
+ char *s = Merge(args);
+ PyObject *res = NULL;
- if (s) {
- res = PyString_FromString(s);
- ckfree(s);
- }
+ if (s) {
+ res = PyString_FromString(s);
+ ckfree(s);
+ }
- return res;
+ return res;
}
-
+
/** Tcl Command **/
/* Client data struct */
typedef struct {
- PyObject *self;
- PyObject *func;
+ PyObject *self;
+ PyObject *func;
} PythonCmd_ClientData;
static int
PythonCmd_Error(Tcl_Interp *interp)
{
- errorInCmd = 1;
- PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
- LEAVE_PYTHON
- return TCL_ERROR;
+ errorInCmd = 1;
+ PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
+ LEAVE_PYTHON
+ return TCL_ERROR;
}
/* This is the Tcl command that acts as a wrapper for Python
@@ -2048,211 +2048,211 @@ PythonCmd_Error(Tcl_Interp *interp)
static int
PythonCmd(ClientData clientData, Tcl_Interp *interp, int argc, char *argv[])
{
- PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
- PyObject *func, *arg, *res;
- int i, rv;
- Tcl_Obj *obj_res;
+ PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
+ PyObject *func, *arg, *res;
+ int i, rv;
+ Tcl_Obj *obj_res;
- ENTER_PYTHON
+ ENTER_PYTHON
- /* TBD: no error checking here since we know, via the
- * Tkapp_CreateCommand() that the client data is a two-tuple
- */
- func = data->func;
+ /* TBD: no error checking here since we know, via the
+ * Tkapp_CreateCommand() that the client data is a two-tuple
+ */
+ func = data->func;
- /* Create argument list (argv1, ..., argvN) */
- if (!(arg = PyTuple_New(argc - 1)))
- return PythonCmd_Error(interp);
+ /* Create argument list (argv1, ..., argvN) */
+ if (!(arg = PyTuple_New(argc - 1)))
+ return PythonCmd_Error(interp);
- for (i = 0; i < (argc - 1); i++) {
- PyObject *s = PyString_FromString(argv[i + 1]);
- if (!s || PyTuple_SetItem(arg, i, s)) {
- Py_DECREF(arg);
- return PythonCmd_Error(interp);
- }
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
+ for (i = 0; i < (argc - 1); i++) {
+ PyObject *s = PyString_FromString(argv[i + 1]);
+ if (!s || PyTuple_SetItem(arg, i, s)) {
+ Py_DECREF(arg);
+ return PythonCmd_Error(interp);
+ }
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
- if (res == NULL)
- return PythonCmd_Error(interp);
+ if (res == NULL)
+ return PythonCmd_Error(interp);
- obj_res = AsObj(res);
- if (obj_res == NULL) {
- Py_DECREF(res);
- return PythonCmd_Error(interp);
- }
- else {
- Tcl_SetObjResult(interp, obj_res);
- rv = TCL_OK;
- }
+ obj_res = AsObj(res);
+ if (obj_res == NULL) {
+ Py_DECREF(res);
+ return PythonCmd_Error(interp);
+ }
+ else {
+ Tcl_SetObjResult(interp, obj_res);
+ rv = TCL_OK;
+ }
- Py_DECREF(res);
+ Py_DECREF(res);
- LEAVE_PYTHON
+ LEAVE_PYTHON
- return rv;
+ return rv;
}
static void
PythonCmdDelete(ClientData clientData)
{
- PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
+ PythonCmd_ClientData *data = (PythonCmd_ClientData *)clientData;
- ENTER_PYTHON
- Py_XDECREF(data->self);
- Py_XDECREF(data->func);
- PyMem_DEL(data);
- LEAVE_PYTHON
+ ENTER_PYTHON
+ Py_XDECREF(data->self);
+ Py_XDECREF(data->func);
+ PyMem_DEL(data);
+ LEAVE_PYTHON
}
-
+
#ifdef WITH_THREAD
TCL_DECLARE_MUTEX(command_mutex)
typedef struct CommandEvent{
- Tcl_Event ev;
- Tcl_Interp* interp;
- char *name;
- int create;
- int *status;
- ClientData *data;
- Tcl_Condition *done;
+ Tcl_Event ev;
+ Tcl_Interp* interp;
+ char *name;
+ int create;
+ int *status;
+ ClientData *data;
+ Tcl_Condition *done;
} CommandEvent;
static int
Tkapp_CommandProc(CommandEvent *ev, int flags)
{
- if (ev->create)
- *ev->status = Tcl_CreateCommand(
- ev->interp, ev->name, PythonCmd,
- ev->data, PythonCmdDelete) == NULL;
- else
- *ev->status = Tcl_DeleteCommand(ev->interp, ev->name);
- Tcl_MutexLock(&command_mutex);
- Tcl_ConditionNotify(ev->done);
- Tcl_MutexUnlock(&command_mutex);
- return 1;
+ if (ev->create)
+ *ev->status = Tcl_CreateCommand(
+ ev->interp, ev->name, PythonCmd,
+ ev->data, PythonCmdDelete) == NULL;
+ else
+ *ev->status = Tcl_DeleteCommand(ev->interp, ev->name);
+ Tcl_MutexLock(&command_mutex);
+ Tcl_ConditionNotify(ev->done);
+ Tcl_MutexUnlock(&command_mutex);
+ return 1;
}
#endif
static PyObject *
Tkapp_CreateCommand(PyObject *selfptr, PyObject *args)
{
- TkappObject *self = (TkappObject*)selfptr;
- PythonCmd_ClientData *data;
- char *cmdName;
- PyObject *func;
- int err;
+ TkappObject *self = (TkappObject*)selfptr;
+ PythonCmd_ClientData *data;
+ char *cmdName;
+ PyObject *func;
+ int err;
- if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError, "command not callable");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "sO:createcommand", &cmdName, &func))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError, "command not callable");
+ return NULL;
+ }
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread() &&
- !WaitForMainloop(self))
- return NULL;
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread() &&
+ !WaitForMainloop(self))
+ return NULL;
#endif
- data = PyMem_NEW(PythonCmd_ClientData, 1);
- if (!data)
- return PyErr_NoMemory();
- Py_INCREF(self);
- Py_INCREF(func);
- data->self = selfptr;
- data->func = func;
+ data = PyMem_NEW(PythonCmd_ClientData, 1);
+ if (!data)
+ return PyErr_NoMemory();
+ Py_INCREF(self);
+ Py_INCREF(func);
+ data->self = selfptr;
+ data->func = func;
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- Tcl_Condition cond = NULL;
- CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
- ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
- ev->interp = self->interp;
- ev->create = 1;
- ev->name = cmdName;
- ev->data = (ClientData)data;
- ev->status = &err;
- ev->done = &cond;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex);
- Tcl_ConditionFinalize(&cond);
- }
- else
-#endif
- {
- ENTER_TCL
- err = Tcl_CreateCommand(
- Tkapp_Interp(self), cmdName, PythonCmd,
- (ClientData)data, PythonCmdDelete) == NULL;
- LEAVE_TCL
- }
- if (err) {
- PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
- PyMem_DEL(data);
- return NULL;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
-}
-
-
-
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ Tcl_Condition cond = NULL;
+ CommandEvent *ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
+ ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
+ ev->interp = self->interp;
+ ev->create = 1;
+ ev->name = cmdName;
+ ev->data = (ClientData)data;
+ ev->status = &err;
+ ev->done = &cond;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond, &command_mutex);
+ Tcl_ConditionFinalize(&cond);
+ }
+ else
+#endif
+ {
+ ENTER_TCL
+ err = Tcl_CreateCommand(
+ Tkapp_Interp(self), cmdName, PythonCmd,
+ (ClientData)data, PythonCmdDelete) == NULL;
+ LEAVE_TCL
+ }
+ if (err) {
+ PyErr_SetString(Tkinter_TclError, "can't create Tcl command");
+ PyMem_DEL(data);
+ return NULL;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+
+
static PyObject *
Tkapp_DeleteCommand(PyObject *selfptr, PyObject *args)
{
- TkappObject *self = (TkappObject*)selfptr;
- char *cmdName;
- int err;
+ TkappObject *self = (TkappObject*)selfptr;
+ char *cmdName;
+ int err;
- if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:deletecommand", &cmdName))
+ return NULL;
#ifdef WITH_THREAD
- if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
- Tcl_Condition cond = NULL;
- CommandEvent *ev;
- ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
- ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
- ev->interp = self->interp;
- ev->create = 0;
- ev->name = cmdName;
- ev->status = &err;
- ev->done = &cond;
- Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond,
- &command_mutex);
- Tcl_ConditionFinalize(&cond);
- }
- else
-#endif
- {
- ENTER_TCL
- err = Tcl_DeleteCommand(self->interp, cmdName);
- LEAVE_TCL
- }
- if (err == -1) {
- PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
-}
-
-
-
+ if (self->threaded && self->thread_id != Tcl_GetCurrentThread()) {
+ Tcl_Condition cond = NULL;
+ CommandEvent *ev;
+ ev = (CommandEvent*)ckalloc(sizeof(CommandEvent));
+ ev->ev.proc = (Tcl_EventProc*)Tkapp_CommandProc;
+ ev->interp = self->interp;
+ ev->create = 0;
+ ev->name = cmdName;
+ ev->status = &err;
+ ev->done = &cond;
+ Tkapp_ThreadSend(self, (Tcl_Event*)ev, &cond,
+ &command_mutex);
+ Tcl_ConditionFinalize(&cond);
+ }
+ else
+#endif
+ {
+ ENTER_TCL
+ err = Tcl_DeleteCommand(self->interp, cmdName);
+ LEAVE_TCL
+ }
+ if (err == -1) {
+ PyErr_SetString(Tkinter_TclError, "can't delete Tcl command");
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
+}
+
+
+
#ifdef HAVE_CREATEFILEHANDLER
/** File Handler **/
typedef struct _fhcdata {
- PyObject *func;
- PyObject *file;
- int id;
- struct _fhcdata *next;
+ PyObject *func;
+ PyObject *file;
+ int id;
+ struct _fhcdata *next;
} FileHandler_ClientData;
static FileHandler_ClientData *HeadFHCD;
@@ -2260,786 +2260,786 @@ static FileHandler_ClientData *HeadFHCD;
static FileHandler_ClientData *
NewFHCD(PyObject *func, PyObject *file, int id)
{
- FileHandler_ClientData *p;
- p = PyMem_NEW(FileHandler_ClientData, 1);
- if (p != NULL) {
- Py_XINCREF(func);
- Py_XINCREF(file);
- p->func = func;
- p->file = file;
- p->id = id;
- p->next = HeadFHCD;
- HeadFHCD = p;
- }
- return p;
+ FileHandler_ClientData *p;
+ p = PyMem_NEW(FileHandler_ClientData, 1);
+ if (p != NULL) {
+ Py_XINCREF(func);
+ Py_XINCREF(file);
+ p->func = func;
+ p->file = file;
+ p->id = id;
+ p->next = HeadFHCD;
+ HeadFHCD = p;
+ }
+ return p;
}
static void
DeleteFHCD(int id)
{
- FileHandler_ClientData *p, **pp;
+ FileHandler_ClientData *p, **pp;
- pp = &HeadFHCD;
- while ((p = *pp) != NULL) {
- if (p->id == id) {
- *pp = p->next;
- Py_XDECREF(p->func);
- Py_XDECREF(p->file);
- PyMem_DEL(p);
- }
- else
- pp = &p->next;
- }
+ pp = &HeadFHCD;
+ while ((p = *pp) != NULL) {
+ if (p->id == id) {
+ *pp = p->next;
+ Py_XDECREF(p->func);
+ Py_XDECREF(p->file);
+ PyMem_DEL(p);
+ }
+ else
+ pp = &p->next;
+ }
}
static void
FileHandler(ClientData clientData, int mask)
{
- FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
- PyObject *func, *file, *arg, *res;
+ FileHandler_ClientData *data = (FileHandler_ClientData *)clientData;
+ PyObject *func, *file, *arg, *res;
- ENTER_PYTHON
- func = data->func;
- file = data->file;
+ ENTER_PYTHON
+ func = data->func;
+ file = data->file;
- arg = Py_BuildValue("(Oi)", file, (long) mask);
- res = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
+ arg = Py_BuildValue("(Oi)", file, (long) mask);
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
- if (res == NULL) {
- errorInCmd = 1;
- PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
- }
- Py_XDECREF(res);
- LEAVE_PYTHON
+ if (res == NULL) {
+ errorInCmd = 1;
+ PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
+ }
+ Py_XDECREF(res);
+ LEAVE_PYTHON
}
static PyObject *
Tkapp_CreateFileHandler(PyObject *self, PyObject *args)
/* args is (file, mask, func) */
{
- FileHandler_ClientData *data;
- PyObject *file, *func;
- int mask, tfile;
+ FileHandler_ClientData *data;
+ PyObject *file, *func;
+ int mask, tfile;
- if (!self && Py_Py3kWarningFlag) {
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "_tkinter.createfilehandler is gone in 3.x") < 0)
- return NULL;
- }
+ if (!self && Py_Py3kWarningFlag) {
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "_tkinter.createfilehandler is gone in 3.x") < 0)
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, "OiO:createfilehandler",
- &file, &mask, &func))
- return NULL;
+ if (!PyArg_ParseTuple(args, "OiO:createfilehandler",
+ &file, &mask, &func))
+ return NULL;
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.createfilehandler not supported "
- "for threaded Tcl");
- return NULL;
- }
-#endif
-
- if (self) {
- CHECK_TCL_APPARTMENT;
- }
-
- tfile = PyObject_AsFileDescriptor(file);
- if (tfile < 0)
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError, "bad argument list");
- return NULL;
- }
-
- data = NewFHCD(func, file, tfile);
- if (data == NULL)
- return NULL;
-
- /* Ought to check for null Tcl_File object... */
- ENTER_TCL
- Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
- LEAVE_TCL
- Py_INCREF(Py_None);
- return Py_None;
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.createfilehandler not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
+#endif
+
+ if (self) {
+ CHECK_TCL_APPARTMENT;
+ }
+
+ tfile = PyObject_AsFileDescriptor(file);
+ if (tfile < 0)
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError, "bad argument list");
+ return NULL;
+ }
+
+ data = NewFHCD(func, file, tfile);
+ if (data == NULL)
+ return NULL;
+
+ /* Ought to check for null Tcl_File object... */
+ ENTER_TCL
+ Tcl_CreateFileHandler(tfile, mask, FileHandler, (ClientData) data);
+ LEAVE_TCL
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_DeleteFileHandler(PyObject *self, PyObject *args)
{
- PyObject *file;
- int tfile;
+ PyObject *file;
+ int tfile;
- if (!self && Py_Py3kWarningFlag) {
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "_tkinter.deletefilehandler is gone in 3.x") < 0)
- return NULL;
- }
+ if (!self && Py_Py3kWarningFlag) {
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "_tkinter.deletefilehandler is gone in 3.x") < 0)
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:deletefilehandler", &file))
+ return NULL;
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.deletefilehandler not supported "
- "for threaded Tcl");
- return NULL;
- }
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.deletefilehandler not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
#endif
- if (self) {
- CHECK_TCL_APPARTMENT;
- }
+ if (self) {
+ CHECK_TCL_APPARTMENT;
+ }
- tfile = PyObject_AsFileDescriptor(file);
- if (tfile < 0)
- return NULL;
+ tfile = PyObject_AsFileDescriptor(file);
+ if (tfile < 0)
+ return NULL;
- DeleteFHCD(tfile);
+ DeleteFHCD(tfile);
- /* Ought to check for null Tcl_File object... */
- ENTER_TCL
- Tcl_DeleteFileHandler(tfile);
- LEAVE_TCL
- Py_INCREF(Py_None);
- return Py_None;
+ /* Ought to check for null Tcl_File object... */
+ ENTER_TCL
+ Tcl_DeleteFileHandler(tfile);
+ LEAVE_TCL
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* HAVE_CREATEFILEHANDLER */
-
+
/**** Tktt Object (timer token) ****/
static PyTypeObject Tktt_Type;
typedef struct {
- PyObject_HEAD
- Tcl_TimerToken token;
- PyObject *func;
+ PyObject_HEAD
+ Tcl_TimerToken token;
+ PyObject *func;
} TkttObject;
static PyObject *
Tktt_DeleteTimerHandler(PyObject *self, PyObject *args)
{
- TkttObject *v = (TkttObject *)self;
- PyObject *func = v->func;
+ TkttObject *v = (TkttObject *)self;
+ PyObject *func = v->func;
- if (!PyArg_ParseTuple(args, ":deletetimerhandler"))
- return NULL;
- if (v->token != NULL) {
- Tcl_DeleteTimerHandler(v->token);
- v->token = NULL;
- }
- if (func != NULL) {
- v->func = NULL;
- Py_DECREF(func);
- Py_DECREF(v); /* See Tktt_New() */
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":deletetimerhandler"))
+ return NULL;
+ if (v->token != NULL) {
+ Tcl_DeleteTimerHandler(v->token);
+ v->token = NULL;
+ }
+ if (func != NULL) {
+ v->func = NULL;
+ Py_DECREF(func);
+ Py_DECREF(v); /* See Tktt_New() */
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef Tktt_methods[] =
{
- {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS},
- {NULL, NULL}
+ {"deletetimerhandler", Tktt_DeleteTimerHandler, METH_VARARGS},
+ {NULL, NULL}
};
static TkttObject *
Tktt_New(PyObject *func)
{
- TkttObject *v;
-
- v = PyObject_New(TkttObject, &Tktt_Type);
- if (v == NULL)
- return NULL;
+ TkttObject *v;
+
+ v = PyObject_New(TkttObject, &Tktt_Type);
+ if (v == NULL)
+ return NULL;
- Py_INCREF(func);
- v->token = NULL;
- v->func = func;
+ Py_INCREF(func);
+ v->token = NULL;
+ v->func = func;
- /* Extra reference, deleted when called or when handler is deleted */
- Py_INCREF(v);
- return v;
+ /* Extra reference, deleted when called or when handler is deleted */
+ Py_INCREF(v);
+ return v;
}
static void
Tktt_Dealloc(PyObject *self)
{
- TkttObject *v = (TkttObject *)self;
- PyObject *func = v->func;
+ TkttObject *v = (TkttObject *)self;
+ PyObject *func = v->func;
- Py_XDECREF(func);
+ Py_XDECREF(func);
- PyObject_Del(self);
+ PyObject_Del(self);
}
static PyObject *
Tktt_Repr(PyObject *self)
{
- TkttObject *v = (TkttObject *)self;
- char buf[100];
+ TkttObject *v = (TkttObject *)self;
+ char buf[100];
- PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
- v->func == NULL ? ", handler deleted" : "");
- return PyString_FromString(buf);
+ PyOS_snprintf(buf, sizeof(buf), "<tktimertoken at %p%s>", v,
+ v->func == NULL ? ", handler deleted" : "");
+ return PyString_FromString(buf);
}
static PyObject *
Tktt_GetAttr(PyObject *self, char *name)
{
- return Py_FindMethod(Tktt_methods, self, name);
+ return Py_FindMethod(Tktt_methods, self, name);
}
static PyTypeObject Tktt_Type =
{
- PyVarObject_HEAD_INIT(NULL, 0)
- "tktimertoken", /*tp_name */
- sizeof(TkttObject), /*tp_basicsize */
- 0, /*tp_itemsize */
- Tktt_Dealloc, /*tp_dealloc */
- 0, /*tp_print */
- Tktt_GetAttr, /*tp_getattr */
- 0, /*tp_setattr */
- 0, /*tp_compare */
- Tktt_Repr, /*tp_repr */
- 0, /*tp_as_number */
- 0, /*tp_as_sequence */
- 0, /*tp_as_mapping */
- 0, /*tp_hash */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "tktimertoken", /*tp_name */
+ sizeof(TkttObject), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ Tktt_Dealloc, /*tp_dealloc */
+ 0, /*tp_print */
+ Tktt_GetAttr, /*tp_getattr */
+ 0, /*tp_setattr */
+ 0, /*tp_compare */
+ Tktt_Repr, /*tp_repr */
+ 0, /*tp_as_number */
+ 0, /*tp_as_sequence */
+ 0, /*tp_as_mapping */
+ 0, /*tp_hash */
};
-
+
/** Timer Handler **/
static void
TimerHandler(ClientData clientData)
{
- TkttObject *v = (TkttObject *)clientData;
- PyObject *func = v->func;
- PyObject *res;
+ TkttObject *v = (TkttObject *)clientData;
+ PyObject *func = v->func;
+ PyObject *res;
- if (func == NULL)
- return;
+ if (func == NULL)
+ return;
- v->func = NULL;
+ v->func = NULL;
- ENTER_PYTHON
+ ENTER_PYTHON
- res = PyEval_CallObject(func, NULL);
- Py_DECREF(func);
- Py_DECREF(v); /* See Tktt_New() */
+ res = PyEval_CallObject(func, NULL);
+ Py_DECREF(func);
+ Py_DECREF(v); /* See Tktt_New() */
- if (res == NULL) {
- errorInCmd = 1;
- PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
- }
- else
- Py_DECREF(res);
+ if (res == NULL) {
+ errorInCmd = 1;
+ PyErr_Fetch(&excInCmd, &valInCmd, &trbInCmd);
+ }
+ else
+ Py_DECREF(res);
- LEAVE_PYTHON
+ LEAVE_PYTHON
}
static PyObject *
Tkapp_CreateTimerHandler(PyObject *self, PyObject *args)
{
- int milliseconds;
- PyObject *func;
- TkttObject *v;
+ int milliseconds;
+ PyObject *func;
+ TkttObject *v;
- if (!self && Py_Py3kWarningFlag) {
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "_tkinter.createtimerhandler is gone in 3.x") < 0)
- return NULL;
- }
+ if (!self && Py_Py3kWarningFlag) {
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "_tkinter.createtimerhandler is gone in 3.x") < 0)
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, "iO:createtimerhandler",
- &milliseconds, &func))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError, "bad argument list");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "iO:createtimerhandler",
+ &milliseconds, &func))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError, "bad argument list");
+ return NULL;
+ }
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.createtimerhandler not supported "
- "for threaded Tcl");
- return NULL;
- }
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.createtimerhandler not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
#endif
- if (self) {
- CHECK_TCL_APPARTMENT;
- }
+ if (self) {
+ CHECK_TCL_APPARTMENT;
+ }
- v = Tktt_New(func);
- if (v) {
- v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
- (ClientData)v);
- }
+ v = Tktt_New(func);
+ if (v) {
+ v->token = Tcl_CreateTimerHandler(milliseconds, TimerHandler,
+ (ClientData)v);
+ }
- return (PyObject *) v;
+ return (PyObject *) v;
}
-
+
/** Event Loop **/
static PyObject *
Tkapp_MainLoop(PyObject *selfptr, PyObject *args)
{
- int threshold = 0;
- TkappObject *self = (TkappObject*)selfptr;
+ int threshold = 0;
+ TkappObject *self = (TkappObject*)selfptr;
#ifdef WITH_THREAD
- PyThreadState *tstate = PyThreadState_Get();
+ PyThreadState *tstate = PyThreadState_Get();
#endif
- if (!self && Py_Py3kWarningFlag) {
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "_tkinter.mainloop is gone in 3.x") < 0)
- return NULL;
- }
+ if (!self && Py_Py3kWarningFlag) {
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "_tkinter.mainloop is gone in 3.x") < 0)
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:mainloop", &threshold))
+ return NULL;
#ifdef WITH_THREAD
- if (!self && !tcl_lock) {
- /* We don't have the Tcl lock since Tcl is threaded. */
- PyErr_SetString(PyExc_RuntimeError,
- "_tkinter.mainloop not supported "
- "for threaded Tcl");
- return NULL;
- }
-#endif
-
- if (self) {
- CHECK_TCL_APPARTMENT;
- self->dispatching = 1;
- }
-
- quitMainLoop = 0;
- while (Tk_GetNumMainWindows() > threshold &&
- !quitMainLoop &&
- !errorInCmd)
- {
- int result;
+ if (!self && !tcl_lock) {
+ /* We don't have the Tcl lock since Tcl is threaded. */
+ PyErr_SetString(PyExc_RuntimeError,
+ "_tkinter.mainloop not supported "
+ "for threaded Tcl");
+ return NULL;
+ }
+#endif
+
+ if (self) {
+ CHECK_TCL_APPARTMENT;
+ self->dispatching = 1;
+ }
+
+ quitMainLoop = 0;
+ while (Tk_GetNumMainWindows() > threshold &&
+ !quitMainLoop &&
+ !errorInCmd)
+ {
+ int result;
#ifdef WITH_THREAD
- if (self && self->threaded) {
- /* Allow other Python threads to run. */
- ENTER_TCL
- result = Tcl_DoOneEvent(0);
- LEAVE_TCL
- }
- else {
- Py_BEGIN_ALLOW_THREADS
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
- tcl_tstate = tstate;
- result = Tcl_DoOneEvent(TCL_DONT_WAIT);
- tcl_tstate = NULL;
- if(tcl_lock)PyThread_release_lock(tcl_lock);
- if (result == 0)
- Sleep(Tkinter_busywaitinterval);
- Py_END_ALLOW_THREADS
- }
+ if (self && self->threaded) {
+ /* Allow other Python threads to run. */
+ ENTER_TCL
+ result = Tcl_DoOneEvent(0);
+ LEAVE_TCL
+ }
+ else {
+ Py_BEGIN_ALLOW_THREADS
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
+ tcl_tstate = tstate;
+ result = Tcl_DoOneEvent(TCL_DONT_WAIT);
+ tcl_tstate = NULL;
+ if(tcl_lock)PyThread_release_lock(tcl_lock);
+ if (result == 0)
+ Sleep(Tkinter_busywaitinterval);
+ Py_END_ALLOW_THREADS
+ }
#else
- result = Tcl_DoOneEvent(0);
-#endif
-
- if (PyErr_CheckSignals() != 0) {
- if (self)
- self->dispatching = 0;
- return NULL;
- }
- if (result < 0)
- break;
- }
- if (self)
- self->dispatching = 0;
- quitMainLoop = 0;
-
- if (errorInCmd) {
- errorInCmd = 0;
- PyErr_Restore(excInCmd, valInCmd, trbInCmd);
- excInCmd = valInCmd = trbInCmd = NULL;
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ result = Tcl_DoOneEvent(0);
+#endif
+
+ if (PyErr_CheckSignals() != 0) {
+ if (self)
+ self->dispatching = 0;
+ return NULL;
+ }
+ if (result < 0)
+ break;
+ }
+ if (self)
+ self->dispatching = 0;
+ quitMainLoop = 0;
+
+ if (errorInCmd) {
+ errorInCmd = 0;
+ PyErr_Restore(excInCmd, valInCmd, trbInCmd);
+ excInCmd = valInCmd = trbInCmd = NULL;
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_DoOneEvent(PyObject *self, PyObject *args)
{
- int flags = 0;
- int rv;
+ int flags = 0;
+ int rv;
- if (!self && Py_Py3kWarningFlag) {
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "_tkinter.dooneevent is gone in 3.x") < 0)
- return NULL;
- }
+ if (!self && Py_Py3kWarningFlag) {
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "_tkinter.dooneevent is gone in 3.x") < 0)
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:dooneevent", &flags))
+ return NULL;
- ENTER_TCL
- rv = Tcl_DoOneEvent(flags);
- LEAVE_TCL
- return Py_BuildValue("i", rv);
+ ENTER_TCL
+ rv = Tcl_DoOneEvent(flags);
+ LEAVE_TCL
+ return Py_BuildValue("i", rv);
}
static PyObject *
Tkapp_Quit(PyObject *self, PyObject *args)
{
- if (!self && Py_Py3kWarningFlag) {
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "_tkinter.quit is gone in 3.x") < 0)
- return NULL;
- }
+ if (!self && Py_Py3kWarningFlag) {
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "_tkinter.quit is gone in 3.x") < 0)
+ return NULL;
+ }
- if (!PyArg_ParseTuple(args, ":quit"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":quit"))
+ return NULL;
- quitMainLoop = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ quitMainLoop = 1;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_InterpAddr(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":interpaddr"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":interpaddr"))
+ return NULL;
- return PyInt_FromLong((long)Tkapp_Interp(self));
+ return PyInt_FromLong((long)Tkapp_Interp(self));
}
-static PyObject *
+static PyObject *
Tkapp_TkInit(PyObject *self, PyObject *args)
{
- Tcl_Interp *interp = Tkapp_Interp(self);
- const char * _tk_exists = NULL;
- int err;
+ Tcl_Interp *interp = Tkapp_Interp(self);
+ const char * _tk_exists = NULL;
+ int err;
#ifdef TKINTER_PROTECT_LOADTK
- /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the
- * first call failed.
- * To avoid the deadlock, we just refuse the second call through
- * a static variable.
- */
- if (tk_load_failed) {
- PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG);
- return NULL;
- }
-#endif
-
- /* We want to guard against calling Tk_Init() multiple times */
- CHECK_TCL_APPARTMENT;
- ENTER_TCL
- err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version");
- ENTER_OVERLAP
- if (err == TCL_ERROR) {
- /* This sets an exception, but we cannot return right
- away because we need to exit the overlap first. */
- Tkinter_Error(self);
- } else {
- _tk_exists = Tkapp_Result(self);
- }
- LEAVE_OVERLAP_TCL
- if (err == TCL_ERROR) {
- return NULL;
- }
- if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) {
- if (Tk_Init(interp) == TCL_ERROR) {
- PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
+ /* Up to Tk 8.4.13, Tk_Init deadlocks on the second call when the
+ * first call failed.
+ * To avoid the deadlock, we just refuse the second call through
+ * a static variable.
+ */
+ if (tk_load_failed) {
+ PyErr_SetString(Tkinter_TclError, TKINTER_LOADTK_ERRMSG);
+ return NULL;
+ }
+#endif
+
+ /* We want to guard against calling Tk_Init() multiple times */
+ CHECK_TCL_APPARTMENT;
+ ENTER_TCL
+ err = Tcl_Eval(Tkapp_Interp(self), "info exists tk_version");
+ ENTER_OVERLAP
+ if (err == TCL_ERROR) {
+ /* This sets an exception, but we cannot return right
+ away because we need to exit the overlap first. */
+ Tkinter_Error(self);
+ } else {
+ _tk_exists = Tkapp_Result(self);
+ }
+ LEAVE_OVERLAP_TCL
+ if (err == TCL_ERROR) {
+ return NULL;
+ }
+ if (_tk_exists == NULL || strcmp(_tk_exists, "1") != 0) {
+ if (Tk_Init(interp) == TCL_ERROR) {
+ PyErr_SetString(Tkinter_TclError, Tcl_GetStringResult(Tkapp_Interp(self)));
#ifdef TKINTER_PROTECT_LOADTK
- tk_load_failed = 1;
+ tk_load_failed = 1;
#endif
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_WantObjects(PyObject *self, PyObject *args)
{
- int wantobjects = -1;
- if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects))
- return NULL;
- if (wantobjects == -1)
- return PyBool_FromLong(((TkappObject*)self)->wantobjects);
- ((TkappObject*)self)->wantobjects = wantobjects;
+ int wantobjects = -1;
+ if (!PyArg_ParseTuple(args, "|i:wantobjects", &wantobjects))
+ return NULL;
+ if (wantobjects == -1)
+ return PyBool_FromLong(((TkappObject*)self)->wantobjects);
+ ((TkappObject*)self)->wantobjects = wantobjects;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Tkapp_WillDispatch(PyObject *self, PyObject *args)
{
- ((TkappObject*)self)->dispatching = 1;
+ ((TkappObject*)self)->dispatching = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
/**** Tkapp Method List ****/
static PyMethodDef Tkapp_methods[] =
{
- {"willdispatch", Tkapp_WillDispatch, METH_NOARGS},
- {"wantobjects", Tkapp_WantObjects, METH_VARARGS},
- {"call", Tkapp_Call, METH_VARARGS},
- {"globalcall", Tkapp_GlobalCall, METH_VARARGS},
- {"eval", Tkapp_Eval, METH_VARARGS},
- {"globaleval", Tkapp_GlobalEval, METH_VARARGS},
- {"evalfile", Tkapp_EvalFile, METH_VARARGS},
- {"record", Tkapp_Record, METH_VARARGS},
- {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS},
- {"setvar", Tkapp_SetVar, METH_VARARGS},
- {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS},
- {"getvar", Tkapp_GetVar, METH_VARARGS},
- {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS},
- {"unsetvar", Tkapp_UnsetVar, METH_VARARGS},
- {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS},
- {"getint", Tkapp_GetInt, METH_VARARGS},
- {"getdouble", Tkapp_GetDouble, METH_VARARGS},
- {"getboolean", Tkapp_GetBoolean, METH_VARARGS},
- {"exprstring", Tkapp_ExprString, METH_VARARGS},
- {"exprlong", Tkapp_ExprLong, METH_VARARGS},
- {"exprdouble", Tkapp_ExprDouble, METH_VARARGS},
- {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS},
- {"splitlist", Tkapp_SplitList, METH_VARARGS},
- {"split", Tkapp_Split, METH_VARARGS},
- {"merge", Tkapp_Merge, METH_VARARGS},
- {"createcommand", Tkapp_CreateCommand, METH_VARARGS},
- {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS},
+ {"willdispatch", Tkapp_WillDispatch, METH_NOARGS},
+ {"wantobjects", Tkapp_WantObjects, METH_VARARGS},
+ {"call", Tkapp_Call, METH_VARARGS},
+ {"globalcall", Tkapp_GlobalCall, METH_VARARGS},
+ {"eval", Tkapp_Eval, METH_VARARGS},
+ {"globaleval", Tkapp_GlobalEval, METH_VARARGS},
+ {"evalfile", Tkapp_EvalFile, METH_VARARGS},
+ {"record", Tkapp_Record, METH_VARARGS},
+ {"adderrorinfo", Tkapp_AddErrorInfo, METH_VARARGS},
+ {"setvar", Tkapp_SetVar, METH_VARARGS},
+ {"globalsetvar", Tkapp_GlobalSetVar, METH_VARARGS},
+ {"getvar", Tkapp_GetVar, METH_VARARGS},
+ {"globalgetvar", Tkapp_GlobalGetVar, METH_VARARGS},
+ {"unsetvar", Tkapp_UnsetVar, METH_VARARGS},
+ {"globalunsetvar", Tkapp_GlobalUnsetVar, METH_VARARGS},
+ {"getint", Tkapp_GetInt, METH_VARARGS},
+ {"getdouble", Tkapp_GetDouble, METH_VARARGS},
+ {"getboolean", Tkapp_GetBoolean, METH_VARARGS},
+ {"exprstring", Tkapp_ExprString, METH_VARARGS},
+ {"exprlong", Tkapp_ExprLong, METH_VARARGS},
+ {"exprdouble", Tkapp_ExprDouble, METH_VARARGS},
+ {"exprboolean", Tkapp_ExprBoolean, METH_VARARGS},
+ {"splitlist", Tkapp_SplitList, METH_VARARGS},
+ {"split", Tkapp_Split, METH_VARARGS},
+ {"merge", Tkapp_Merge, METH_VARARGS},
+ {"createcommand", Tkapp_CreateCommand, METH_VARARGS},
+ {"deletecommand", Tkapp_DeleteCommand, METH_VARARGS},
#ifdef HAVE_CREATEFILEHANDLER
- {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
- {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
-#endif
- {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
- {"mainloop", Tkapp_MainLoop, METH_VARARGS},
- {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
- {"quit", Tkapp_Quit, METH_VARARGS},
- {"interpaddr", Tkapp_InterpAddr, METH_VARARGS},
- {"loadtk", Tkapp_TkInit, METH_NOARGS},
- {NULL, NULL}
+ {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
+ {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
+#endif
+ {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
+ {"mainloop", Tkapp_MainLoop, METH_VARARGS},
+ {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
+ {"quit", Tkapp_Quit, METH_VARARGS},
+ {"interpaddr", Tkapp_InterpAddr, METH_VARARGS},
+ {"loadtk", Tkapp_TkInit, METH_NOARGS},
+ {NULL, NULL}
};
-
+
/**** Tkapp Type Methods ****/
static void
Tkapp_Dealloc(PyObject *self)
{
- /*CHECK_TCL_APPARTMENT;*/
- ENTER_TCL
- Tcl_DeleteInterp(Tkapp_Interp(self));
- LEAVE_TCL
- PyObject_Del(self);
- DisableEventHook();
+ /*CHECK_TCL_APPARTMENT;*/
+ ENTER_TCL
+ Tcl_DeleteInterp(Tkapp_Interp(self));
+ LEAVE_TCL
+ PyObject_Del(self);
+ DisableEventHook();
}
static PyObject *
Tkapp_GetAttr(PyObject *self, char *name)
{
- return Py_FindMethod(Tkapp_methods, self, name);
+ return Py_FindMethod(Tkapp_methods, self, name);
}
static PyTypeObject Tkapp_Type =
{
- PyVarObject_HEAD_INIT(NULL, 0)
- "tkapp", /*tp_name */
- sizeof(TkappObject), /*tp_basicsize */
- 0, /*tp_itemsize */
- Tkapp_Dealloc, /*tp_dealloc */
- 0, /*tp_print */
- Tkapp_GetAttr, /*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 */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "tkapp", /*tp_name */
+ sizeof(TkappObject), /*tp_basicsize */
+ 0, /*tp_itemsize */
+ Tkapp_Dealloc, /*tp_dealloc */
+ 0, /*tp_print */
+ Tkapp_GetAttr, /*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 */
};
-
+
/**** Tkinter Module ****/
typedef struct {
- PyObject* tuple;
- int size; /* current size */
- int maxsize; /* allocated size */
+ PyObject* tuple;
+ int size; /* current size */
+ int maxsize; /* allocated size */
} FlattenContext;
static int
_bump(FlattenContext* context, int size)
{
- /* expand tuple to hold (at least) size new items.
- return true if successful, false if an exception was raised */
+ /* expand tuple to hold (at least) size new items.
+ return true if successful, false if an exception was raised */
- int maxsize = context->maxsize * 2;
+ int maxsize = context->maxsize * 2;
- if (maxsize < context->size + size)
- maxsize = context->size + size;
+ if (maxsize < context->size + size)
+ maxsize = context->size + size;
- context->maxsize = maxsize;
+ context->maxsize = maxsize;
- return _PyTuple_Resize(&context->tuple, maxsize) >= 0;
+ return _PyTuple_Resize(&context->tuple, maxsize) >= 0;
}
static int
_flatten1(FlattenContext* context, PyObject* item, int depth)
{
- /* add tuple or list to argument tuple (recursively) */
-
- int i, size;
-
- if (depth > 1000) {
- PyErr_SetString(PyExc_ValueError,
- "nesting too deep in _flatten");
- return 0;
- } else if (PyList_Check(item)) {
- size = PyList_GET_SIZE(item);
- /* preallocate (assume no nesting) */
- if (context->size + size > context->maxsize &&
- !_bump(context, size))
- return 0;
- /* copy items to output tuple */
- for (i = 0; i < size; i++) {
- PyObject *o = PyList_GET_ITEM(item, i);
- if (PyList_Check(o) || PyTuple_Check(o)) {
- if (!_flatten1(context, o, depth + 1))
- return 0;
- } else if (o != Py_None) {
- if (context->size + 1 > context->maxsize &&
- !_bump(context, 1))
- return 0;
- Py_INCREF(o);
- PyTuple_SET_ITEM(context->tuple,
- context->size++, o);
- }
- }
- } else if (PyTuple_Check(item)) {
- /* same, for tuples */
- size = PyTuple_GET_SIZE(item);
- if (context->size + size > context->maxsize &&
- !_bump(context, size))
- return 0;
- for (i = 0; i < size; i++) {
- PyObject *o = PyTuple_GET_ITEM(item, i);
- if (PyList_Check(o) || PyTuple_Check(o)) {
- if (!_flatten1(context, o, depth + 1))
- return 0;
- } else if (o != Py_None) {
- if (context->size + 1 > context->maxsize &&
- !_bump(context, 1))
- return 0;
- Py_INCREF(o);
- PyTuple_SET_ITEM(context->tuple,
- context->size++, o);
- }
- }
- } else {
- PyErr_SetString(PyExc_TypeError, "argument must be sequence");
- return 0;
- }
- return 1;
+ /* add tuple or list to argument tuple (recursively) */
+
+ int i, size;
+
+ if (depth > 1000) {
+ PyErr_SetString(PyExc_ValueError,
+ "nesting too deep in _flatten");
+ return 0;
+ } else if (PyList_Check(item)) {
+ size = PyList_GET_SIZE(item);
+ /* preallocate (assume no nesting) */
+ if (context->size + size > context->maxsize &&
+ !_bump(context, size))
+ return 0;
+ /* copy items to output tuple */
+ for (i = 0; i < size; i++) {
+ PyObject *o = PyList_GET_ITEM(item, i);
+ if (PyList_Check(o) || PyTuple_Check(o)) {
+ if (!_flatten1(context, o, depth + 1))
+ return 0;
+ } else if (o != Py_None) {
+ if (context->size + 1 > context->maxsize &&
+ !_bump(context, 1))
+ return 0;
+ Py_INCREF(o);
+ PyTuple_SET_ITEM(context->tuple,
+ context->size++, o);
+ }
+ }
+ } else if (PyTuple_Check(item)) {
+ /* same, for tuples */
+ size = PyTuple_GET_SIZE(item);
+ if (context->size + size > context->maxsize &&
+ !_bump(context, size))
+ return 0;
+ for (i = 0; i < size; i++) {
+ PyObject *o = PyTuple_GET_ITEM(item, i);
+ if (PyList_Check(o) || PyTuple_Check(o)) {
+ if (!_flatten1(context, o, depth + 1))
+ return 0;
+ } else if (o != Py_None) {
+ if (context->size + 1 > context->maxsize &&
+ !_bump(context, 1))
+ return 0;
+ Py_INCREF(o);
+ PyTuple_SET_ITEM(context->tuple,
+ context->size++, o);
+ }
+ }
+ } else {
+ PyErr_SetString(PyExc_TypeError, "argument must be sequence");
+ return 0;
+ }
+ return 1;
}
static PyObject *
Tkinter_Flatten(PyObject* self, PyObject* args)
{
- FlattenContext context;
- PyObject* item;
+ FlattenContext context;
+ PyObject* item;
+
+ if (!PyArg_ParseTuple(args, "O:_flatten", &item))
+ return NULL;
+
+ context.maxsize = PySequence_Size(item);
+ if (context.maxsize < 0)
+ return NULL;
+ if (context.maxsize == 0)
+ return PyTuple_New(0);
- if (!PyArg_ParseTuple(args, "O:_flatten", &item))
- return NULL;
+ context.tuple = PyTuple_New(context.maxsize);
+ if (!context.tuple)
+ return NULL;
- context.maxsize = PySequence_Size(item);
- if (context.maxsize < 0)
- return NULL;
- if (context.maxsize == 0)
- return PyTuple_New(0);
-
- context.tuple = PyTuple_New(context.maxsize);
- if (!context.tuple)
- return NULL;
-
- context.size = 0;
+ context.size = 0;
- if (!_flatten1(&context, item,0))
- return NULL;
+ if (!_flatten1(&context, item,0))
+ return NULL;
- if (_PyTuple_Resize(&context.tuple, context.size))
- return NULL;
+ if (_PyTuple_Resize(&context.tuple, context.size))
+ return NULL;
- return context.tuple;
+ return context.tuple;
}
static PyObject *
Tkinter_Create(PyObject *self, PyObject *args)
{
- char *screenName = NULL;
- char *baseName = NULL;
- char *className = NULL;
- int interactive = 0;
- int wantobjects = 0;
- int wantTk = 1; /* If false, then Tk_Init() doesn't get called */
- int sync = 0; /* pass -sync to wish */
- char *use = NULL; /* pass -use to wish */
-
- baseName = strrchr(Py_GetProgramName(), '/');
- if (baseName != NULL)
- baseName++;
- else
- baseName = Py_GetProgramName();
- className = "Tk";
-
- if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
- &screenName, &baseName, &className,
- &interactive, &wantobjects, &wantTk,
- &sync, &use))
- return NULL;
-
- return (PyObject *) Tkapp_New(screenName, baseName, className,
- interactive, wantobjects, wantTk,
- sync, use);
+ char *screenName = NULL;
+ char *baseName = NULL;
+ char *className = NULL;
+ int interactive = 0;
+ int wantobjects = 0;
+ int wantTk = 1; /* If false, then Tk_Init() doesn't get called */
+ int sync = 0; /* pass -sync to wish */
+ char *use = NULL; /* pass -use to wish */
+
+ baseName = strrchr(Py_GetProgramName(), '/');
+ if (baseName != NULL)
+ baseName++;
+ else
+ baseName = Py_GetProgramName();
+ className = "Tk";
+
+ if (!PyArg_ParseTuple(args, "|zssiiiiz:create",
+ &screenName, &baseName, &className,
+ &interactive, &wantobjects, &wantTk,
+ &sync, &use))
+ return NULL;
+
+ return (PyObject *) Tkapp_New(screenName, baseName, className,
+ interactive, wantobjects, wantTk,
+ sync, use);
}
static PyObject *
Tkinter_setbusywaitinterval(PyObject *self, PyObject *args)
{
- int new_val;
- if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val))
- return NULL;
- if (new_val < 0) {
- PyErr_SetString(PyExc_ValueError,
- "busywaitinterval must be >= 0");
- return NULL;
- }
- Tkinter_busywaitinterval = new_val;
- Py_INCREF(Py_None);
- return Py_None;
+ int new_val;
+ if (!PyArg_ParseTuple(args, "i:setbusywaitinterval", &new_val))
+ return NULL;
+ if (new_val < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "busywaitinterval must be >= 0");
+ return NULL;
+ }
+ Tkinter_busywaitinterval = new_val;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static char setbusywaitinterval_doc[] =
@@ -3053,7 +3053,7 @@ frames in an animation.";
static PyObject *
Tkinter_getbusywaitinterval(PyObject *self, PyObject *args)
{
- return PyInt_FromLong(Tkinter_busywaitinterval);
+ return PyInt_FromLong(Tkinter_busywaitinterval);
}
static char getbusywaitinterval_doc[] =
@@ -3064,21 +3064,21 @@ calls to Tcl_DoOneEvent in a threaded Python interpreter.";
static PyMethodDef moduleMethods[] =
{
- {"_flatten", Tkinter_Flatten, METH_VARARGS},
- {"create", Tkinter_Create, METH_VARARGS},
+ {"_flatten", Tkinter_Flatten, METH_VARARGS},
+ {"create", Tkinter_Create, METH_VARARGS},
#ifdef HAVE_CREATEFILEHANDLER
- {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
- {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
-#endif
- {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
- {"mainloop", Tkapp_MainLoop, METH_VARARGS},
- {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
- {"quit", Tkapp_Quit, METH_VARARGS},
- {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
- setbusywaitinterval_doc},
- {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
- METH_NOARGS, getbusywaitinterval_doc},
- {NULL, NULL}
+ {"createfilehandler", Tkapp_CreateFileHandler, METH_VARARGS},
+ {"deletefilehandler", Tkapp_DeleteFileHandler, METH_VARARGS},
+#endif
+ {"createtimerhandler", Tkapp_CreateTimerHandler, METH_VARARGS},
+ {"mainloop", Tkapp_MainLoop, METH_VARARGS},
+ {"dooneevent", Tkapp_DoOneEvent, METH_VARARGS},
+ {"quit", Tkapp_Quit, METH_VARARGS},
+ {"setbusywaitinterval",Tkinter_setbusywaitinterval, METH_VARARGS,
+ setbusywaitinterval_doc},
+ {"getbusywaitinterval",(PyCFunction)Tkinter_getbusywaitinterval,
+ METH_NOARGS, getbusywaitinterval_doc},
+ {NULL, NULL}
};
#ifdef WAIT_FOR_STDIN
@@ -3089,7 +3089,7 @@ static int stdin_ready = 0;
static void
MyFileProc(void *clientData, int mask)
{
- stdin_ready = 1;
+ stdin_ready = 1;
}
#endif
@@ -3101,57 +3101,57 @@ static int
EventHook(void)
{
#ifndef MS_WINDOWS
- int tfile;
+ int tfile;
#endif
#ifdef WITH_THREAD
- PyEval_RestoreThread(event_tstate);
+ PyEval_RestoreThread(event_tstate);
#endif
- stdin_ready = 0;
- errorInCmd = 0;
+ stdin_ready = 0;
+ errorInCmd = 0;
#ifndef MS_WINDOWS
- tfile = fileno(stdin);
- Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
+ tfile = fileno(stdin);
+ Tcl_CreateFileHandler(tfile, TCL_READABLE, MyFileProc, NULL);
#endif
- while (!errorInCmd && !stdin_ready) {
- int result;
+ while (!errorInCmd && !stdin_ready) {
+ int result;
#ifdef MS_WINDOWS
- if (_kbhit()) {
- stdin_ready = 1;
- break;
- }
+ if (_kbhit()) {
+ stdin_ready = 1;
+ break;
+ }
#endif
#if defined(WITH_THREAD) || defined(MS_WINDOWS)
- Py_BEGIN_ALLOW_THREADS
- if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
- tcl_tstate = event_tstate;
+ Py_BEGIN_ALLOW_THREADS
+ if(tcl_lock)PyThread_acquire_lock(tcl_lock, 1);
+ tcl_tstate = event_tstate;
- result = Tcl_DoOneEvent(TCL_DONT_WAIT);
+ result = Tcl_DoOneEvent(TCL_DONT_WAIT);
- tcl_tstate = NULL;
- if(tcl_lock)PyThread_release_lock(tcl_lock);
- if (result == 0)
- Sleep(Tkinter_busywaitinterval);
- Py_END_ALLOW_THREADS
+ tcl_tstate = NULL;
+ if(tcl_lock)PyThread_release_lock(tcl_lock);
+ if (result == 0)
+ Sleep(Tkinter_busywaitinterval);
+ Py_END_ALLOW_THREADS
#else
- result = Tcl_DoOneEvent(0);
+ result = Tcl_DoOneEvent(0);
#endif
- if (result < 0)
- break;
- }
+ if (result < 0)
+ break;
+ }
#ifndef MS_WINDOWS
- Tcl_DeleteFileHandler(tfile);
-#endif
- if (errorInCmd) {
- errorInCmd = 0;
- PyErr_Restore(excInCmd, valInCmd, trbInCmd);
- excInCmd = valInCmd = trbInCmd = NULL;
- PyErr_Print();
- }
+ Tcl_DeleteFileHandler(tfile);
+#endif
+ if (errorInCmd) {
+ errorInCmd = 0;
+ PyErr_Restore(excInCmd, valInCmd, trbInCmd);
+ excInCmd = valInCmd = trbInCmd = NULL;
+ PyErr_Print();
+ }
#ifdef WITH_THREAD
- PyEval_SaveThread();
+ PyEval_SaveThread();
#endif
- return 0;
+ return 0;
}
#endif
@@ -3160,12 +3160,12 @@ static void
EnableEventHook(void)
{
#ifdef WAIT_FOR_STDIN
- if (PyOS_InputHook == NULL) {
+ if (PyOS_InputHook == NULL) {
#ifdef WITH_THREAD
- event_tstate = PyThreadState_Get();
+ event_tstate = PyThreadState_Get();
#endif
- PyOS_InputHook = EventHook;
- }
+ PyOS_InputHook = EventHook;
+ }
#endif
}
@@ -3173,9 +3173,9 @@ static void
DisableEventHook(void)
{
#ifdef WAIT_FOR_STDIN
- if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
- PyOS_InputHook = NULL;
- }
+ if (Tk_GetNumMainWindows() == 0 && PyOS_InputHook == EventHook) {
+ PyOS_InputHook = NULL;
+ }
#endif
}
@@ -3184,89 +3184,89 @@ DisableEventHook(void)
static void
ins_long(PyObject *d, char *name, long val)
{
- PyObject *v = PyInt_FromLong(val);
- if (v) {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyInt_FromLong(val);
+ if (v) {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
static void
ins_string(PyObject *d, char *name, char *val)
{
- PyObject *v = PyString_FromString(val);
- if (v) {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyString_FromString(val);
+ if (v) {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
PyMODINIT_FUNC
init_tkinter(void)
{
- PyObject *m, *d;
+ PyObject *m, *d;
- Py_TYPE(&Tkapp_Type) = &PyType_Type;
+ Py_TYPE(&Tkapp_Type) = &PyType_Type;
#ifdef WITH_THREAD
- tcl_lock = PyThread_allocate_lock();
+ tcl_lock = PyThread_allocate_lock();
#endif
- m = Py_InitModule("_tkinter", moduleMethods);
- if (m == NULL)
- return;
+ m = Py_InitModule("_tkinter", moduleMethods);
+ if (m == NULL)
+ return;
- d = PyModule_GetDict(m);
- Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL);
- PyDict_SetItemString(d, "TclError", Tkinter_TclError);
+ d = PyModule_GetDict(m);
+ Tkinter_TclError = PyErr_NewException("_tkinter.TclError", NULL, NULL);
+ PyDict_SetItemString(d, "TclError", Tkinter_TclError);
- ins_long(d, "READABLE", TCL_READABLE);
- ins_long(d, "WRITABLE", TCL_WRITABLE);
- ins_long(d, "EXCEPTION", TCL_EXCEPTION);
- ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
- ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
- ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
- ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
- ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
- ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
- ins_string(d, "TK_VERSION", TK_VERSION);
- ins_string(d, "TCL_VERSION", TCL_VERSION);
+ ins_long(d, "READABLE", TCL_READABLE);
+ ins_long(d, "WRITABLE", TCL_WRITABLE);
+ ins_long(d, "EXCEPTION", TCL_EXCEPTION);
+ ins_long(d, "WINDOW_EVENTS", TCL_WINDOW_EVENTS);
+ ins_long(d, "FILE_EVENTS", TCL_FILE_EVENTS);
+ ins_long(d, "TIMER_EVENTS", TCL_TIMER_EVENTS);
+ ins_long(d, "IDLE_EVENTS", TCL_IDLE_EVENTS);
+ ins_long(d, "ALL_EVENTS", TCL_ALL_EVENTS);
+ ins_long(d, "DONT_WAIT", TCL_DONT_WAIT);
+ ins_string(d, "TK_VERSION", TK_VERSION);
+ ins_string(d, "TCL_VERSION", TCL_VERSION);
- PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
+ PyDict_SetItemString(d, "TkappType", (PyObject *)&Tkapp_Type);
- Py_TYPE(&Tktt_Type) = &PyType_Type;
- PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
+ Py_TYPE(&Tktt_Type) = &PyType_Type;
+ PyDict_SetItemString(d, "TkttType", (PyObject *)&Tktt_Type);
- Py_TYPE(&PyTclObject_Type) = &PyType_Type;
- PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type);
+ Py_TYPE(&PyTclObject_Type) = &PyType_Type;
+ PyDict_SetItemString(d, "Tcl_Obj", (PyObject *)&PyTclObject_Type);
#ifdef TK_AQUA
- /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems
- * start waking up. Note that Tcl_FindExecutable will do this, this
- * code must be above it! The original warning from
- * tkMacOSXAppInit.c is copied below.
- *
- * NB - You have to swap in the Tk Notifier BEFORE you start up the
- * Tcl interpreter for now. It probably should work to do this
- * in the other order, but for now it doesn't seem to.
- *
- */
- Tk_MacOSXSetupTkNotifier();
+ /* Tk_MacOSXSetupTkNotifier must be called before Tcl's subsystems
+ * start waking up. Note that Tcl_FindExecutable will do this, this
+ * code must be above it! The original warning from
+ * tkMacOSXAppInit.c is copied below.
+ *
+ * NB - You have to swap in the Tk Notifier BEFORE you start up the
+ * Tcl interpreter for now. It probably should work to do this
+ * in the other order, but for now it doesn't seem to.
+ *
+ */
+ Tk_MacOSXSetupTkNotifier();
#endif
- /* This helps the dynamic loader; in Unicode aware Tcl versions
- it also helps Tcl find its encodings. */
- Tcl_FindExecutable(Py_GetProgramName());
+ /* This helps the dynamic loader; in Unicode aware Tcl versions
+ it also helps Tcl find its encodings. */
+ Tcl_FindExecutable(Py_GetProgramName());
- if (PyErr_Occurred())
- return;
+ if (PyErr_Occurred())
+ return;
#if 0
- /* This was not a good idea; through <Destroy> bindings,
- Tcl_Finalize() may invoke Python code but at that point the
- interpreter and thread state have already been destroyed! */
- Py_AtExit(Tcl_Finalize);
+ /* This was not a good idea; through <Destroy> bindings,
+ Tcl_Finalize() may invoke Python code but at that point the
+ interpreter and thread state have already been destroyed! */
+ Py_AtExit(Tcl_Finalize);
#endif
}
diff --git a/Modules/addrinfo.h b/Modules/addrinfo.h
index 6f67a2e..670b173 100644
--- a/Modules/addrinfo.h
+++ b/Modules/addrinfo.h
@@ -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 */
diff --git a/Modules/almodule.c b/Modules/almodule.c
index 93f26bd..691175e 100644
--- a/Modules/almodule.c
+++ b/Modules/almodule.c
@@ -1,5 +1,5 @@
-#define OLD_INTERFACE /* define for pre-Irix 6 interface */
+#define OLD_INTERFACE /* define for pre-Irix 6 interface */
#include "Python.h"
#include "stringobject.h"
@@ -19,9 +19,9 @@ static PyObject *ErrorObject;
/* Declarations for objects of type port */
typedef struct {
- PyObject_HEAD
- /* XXXX Add your own stuff here */
- ALport port;
+ PyObject_HEAD
+ /* XXXX Add your own stuff here */
+ ALport port;
} alpobject;
static PyTypeObject Alptype;
@@ -33,9 +33,9 @@ static PyTypeObject Alptype;
/* Declarations for objects of type config */
typedef struct {
- PyObject_HEAD
- /* XXXX Add your own stuff here */
- ALconfig config;
+ PyObject_HEAD
+ /* XXXX Add your own stuff here */
+ ALconfig config;
} alcobject;
static PyTypeObject Alctype;
@@ -44,199 +44,199 @@ static PyTypeObject Alctype;
static void
ErrorHandler(long code, const char *fmt, ...)
{
- va_list args;
- char buf[128];
+ va_list args;
+ char buf[128];
- va_start(args, fmt);
- vsprintf(buf, fmt, args);
- va_end(args);
- PyErr_SetString(ErrorObject, buf);
+ va_start(args, fmt);
+ vsprintf(buf, fmt, args);
+ va_end(args);
+ PyErr_SetString(ErrorObject, buf);
}
-#ifdef AL_NO_ELEM /* IRIX 6 */
+#ifdef AL_NO_ELEM /* IRIX 6 */
static PyObject *
param2python(int resource, int param, ALvalue value, ALparamInfo *pinfo)
{
- ALparamInfo info;
-
- if (pinfo == NULL) {
- pinfo = &info;
- if (alGetParamInfo(resource, param, &info) < 0)
- return NULL;
- }
- switch (pinfo->elementType) {
- case AL_PTR_ELEM:
- /* XXXX don't know how to handle this */
- case AL_NO_ELEM:
- Py_INCREF(Py_None);
- return Py_None;
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- return PyInt_FromLong((long) value.i);
- case AL_INT64_ELEM:
- return PyLong_FromLongLong(value.ll);
- case AL_FIXED_ELEM:
- return PyFloat_FromDouble(alFixedToDouble(value.ll));
- case AL_CHAR_ELEM:
- if (value.ptr == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString((char *) value.ptr);
- default:
- PyErr_SetString(ErrorObject, "unknown element type");
- return NULL;
- }
+ ALparamInfo info;
+
+ if (pinfo == NULL) {
+ pinfo = &info;
+ if (alGetParamInfo(resource, param, &info) < 0)
+ return NULL;
+ }
+ switch (pinfo->elementType) {
+ case AL_PTR_ELEM:
+ /* XXXX don't know how to handle this */
+ case AL_NO_ELEM:
+ Py_INCREF(Py_None);
+ return Py_None;
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ return PyInt_FromLong((long) value.i);
+ case AL_INT64_ELEM:
+ return PyLong_FromLongLong(value.ll);
+ case AL_FIXED_ELEM:
+ return PyFloat_FromDouble(alFixedToDouble(value.ll));
+ case AL_CHAR_ELEM:
+ if (value.ptr == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString((char *) value.ptr);
+ default:
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return NULL;
+ }
}
static int
python2elem(PyObject *item, void *ptr, int elementType)
{
- switch (elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- if (!PyInt_Check(item)) {
- PyErr_BadArgument();
- return -1;
- }
- *((int *) ptr) = PyInt_AsLong(item);
- break;
- case AL_INT64_ELEM:
- if (PyInt_Check(item))
- *((long long *) ptr) = PyInt_AsLong(item);
- else if (PyLong_Check(item))
- *((long long *) ptr) = PyLong_AsLongLong(item);
- else {
- PyErr_BadArgument();
- return -1;
- }
- break;
- case AL_FIXED_ELEM:
- if (PyInt_Check(item))
- *((long long *) ptr) = alDoubleToFixed((double) PyInt_AsLong(item));
- else if (PyFloat_Check(item))
- *((long long *) ptr) = alDoubleToFixed(PyFloat_AsDouble(item));
- else {
- PyErr_BadArgument();
- return -1;
- }
- break;
- default:
- PyErr_SetString(ErrorObject, "unknown element type");
- return -1;
- }
- return 0;
+ switch (elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ if (!PyInt_Check(item)) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ *((int *) ptr) = PyInt_AsLong(item);
+ break;
+ case AL_INT64_ELEM:
+ if (PyInt_Check(item))
+ *((long long *) ptr) = PyInt_AsLong(item);
+ else if (PyLong_Check(item))
+ *((long long *) ptr) = PyLong_AsLongLong(item);
+ else {
+ PyErr_BadArgument();
+ return -1;
+ }
+ break;
+ case AL_FIXED_ELEM:
+ if (PyInt_Check(item))
+ *((long long *) ptr) = alDoubleToFixed((double) PyInt_AsLong(item));
+ else if (PyFloat_Check(item))
+ *((long long *) ptr) = alDoubleToFixed(PyFloat_AsDouble(item));
+ else {
+ PyErr_BadArgument();
+ return -1;
+ }
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return -1;
+ }
+ return 0;
}
static int
python2param(int resource, ALpv *param, PyObject *value, ALparamInfo *pinfo)
{
- ALparamInfo info;
- int i, stepsize;
- PyObject *item;
-
- if (pinfo == NULL) {
- pinfo = &info;
- if (alGetParamInfo(resource, param->param, &info) < 0)
- return -1;
- }
- switch (pinfo->valueType) {
- case AL_STRING_VAL:
- if (pinfo->elementType != AL_CHAR_ELEM) {
- PyErr_SetString(ErrorObject, "unknown element type");
- return -1;
- }
- if (!PyString_Check(value)) {
- PyErr_BadArgument();
- return -1;
- }
- param->value.ptr = PyString_AS_STRING(value);
- param->sizeIn = PyString_GET_SIZE(value)+1; /*account for NUL*/
- break;
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- if (!PyList_Check(value) && !PyTuple_Check(value)) {
- PyErr_BadArgument();
- return -1;
- }
- switch (pinfo->elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- param->sizeIn = PySequence_Size(value);
- param->value.ptr = PyMem_NEW(int, param->sizeIn);
- stepsize = sizeof(int);
- break;
- case AL_INT64_ELEM:
- case AL_FIXED_ELEM:
- param->sizeIn = PySequence_Size(value);
- param->value.ptr = PyMem_NEW(long long, param->sizeIn);
- stepsize = sizeof(long long);
- break;
- }
- for (i = 0; i < param->sizeIn; i++) {
- item = PySequence_GetItem(value, i);
- if (python2elem(item, (void *) ((char *) param->value.ptr + i*stepsize), pinfo->elementType) < 0) {
- PyMem_DEL(param->value.ptr);
- return -1;
- }
- }
- break;
- case AL_SCALAR_VAL:
- switch (pinfo->elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- return python2elem(value, (void *) &param->value.i,
- pinfo->elementType);
- case AL_INT64_ELEM:
- case AL_FIXED_ELEM:
- return python2elem(value, (void *) &param->value.ll,
- pinfo->elementType);
- default:
- PyErr_SetString(ErrorObject, "unknown element type");
- return -1;
- }
- }
- return 0;
+ ALparamInfo info;
+ int i, stepsize;
+ PyObject *item;
+
+ if (pinfo == NULL) {
+ pinfo = &info;
+ if (alGetParamInfo(resource, param->param, &info) < 0)
+ return -1;
+ }
+ switch (pinfo->valueType) {
+ case AL_STRING_VAL:
+ if (pinfo->elementType != AL_CHAR_ELEM) {
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return -1;
+ }
+ if (!PyString_Check(value)) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ param->value.ptr = PyString_AS_STRING(value);
+ param->sizeIn = PyString_GET_SIZE(value)+1; /*account for NUL*/
+ break;
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ if (!PyList_Check(value) && !PyTuple_Check(value)) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ switch (pinfo->elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ param->sizeIn = PySequence_Size(value);
+ param->value.ptr = PyMem_NEW(int, param->sizeIn);
+ stepsize = sizeof(int);
+ break;
+ case AL_INT64_ELEM:
+ case AL_FIXED_ELEM:
+ param->sizeIn = PySequence_Size(value);
+ param->value.ptr = PyMem_NEW(long long, param->sizeIn);
+ stepsize = sizeof(long long);
+ break;
+ }
+ for (i = 0; i < param->sizeIn; i++) {
+ item = PySequence_GetItem(value, i);
+ if (python2elem(item, (void *) ((char *) param->value.ptr + i*stepsize), pinfo->elementType) < 0) {
+ PyMem_DEL(param->value.ptr);
+ return -1;
+ }
+ }
+ break;
+ case AL_SCALAR_VAL:
+ switch (pinfo->elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ return python2elem(value, (void *) &param->value.i,
+ pinfo->elementType);
+ case AL_INT64_ELEM:
+ case AL_FIXED_ELEM:
+ return python2elem(value, (void *) &param->value.ll,
+ pinfo->elementType);
+ default:
+ PyErr_SetString(ErrorObject, "unknown element type");
+ return -1;
+ }
+ }
+ return 0;
}
static int
python2params(int resource1, int resource2, PyObject *list, ALpv **pvsp, ALparamInfo **pinfop)
{
- PyObject *item;
- ALpv *pvs;
- ALparamInfo *pinfo;
- int npvs, i;
-
- npvs = PyList_Size(list);
- pvs = PyMem_NEW(ALpv, npvs);
- pinfo = PyMem_NEW(ALparamInfo, npvs);
- for (i = 0; i < npvs; i++) {
- item = PyList_GetItem(list, i);
- if (!PyArg_ParseTuple(item, "iO", &pvs[i].param, &item))
- goto error;
- if (alGetParamInfo(resource1, pvs[i].param, &pinfo[i]) < 0 &&
- alGetParamInfo(resource2, pvs[i].param, &pinfo[i]) < 0)
- goto error;
- if (python2param(resource1, &pvs[i], item, &pinfo[i]) < 0)
- goto error;
- }
-
- *pvsp = pvs;
- *pinfop = pinfo;
- return npvs;
+ PyObject *item;
+ ALpv *pvs;
+ ALparamInfo *pinfo;
+ int npvs, i;
+
+ npvs = PyList_Size(list);
+ pvs = PyMem_NEW(ALpv, npvs);
+ pinfo = PyMem_NEW(ALparamInfo, npvs);
+ for (i = 0; i < npvs; i++) {
+ item = PyList_GetItem(list, i);
+ if (!PyArg_ParseTuple(item, "iO", &pvs[i].param, &item))
+ goto error;
+ if (alGetParamInfo(resource1, pvs[i].param, &pinfo[i]) < 0 &&
+ alGetParamInfo(resource2, pvs[i].param, &pinfo[i]) < 0)
+ goto error;
+ if (python2param(resource1, &pvs[i], item, &pinfo[i]) < 0)
+ goto error;
+ }
+
+ *pvsp = pvs;
+ *pinfop = pinfo;
+ return npvs;
error:
- /* XXXX we should clean up everything */
- if (pvs)
- PyMem_DEL(pvs);
- if (pinfo)
- PyMem_DEL(pinfo);
- return -1;
+ /* XXXX we should clean up everything */
+ if (pvs)
+ PyMem_DEL(pvs);
+ if (pinfo)
+ PyMem_DEL(pinfo);
+ return -1;
}
/* -------------------------------------------------------- */
@@ -245,30 +245,30 @@ python2params(int resource1, int resource2, PyObject *list, ALpv **pvsp, ALparam
static PyObject *
SetConfig(alcobject *self, PyObject *args, int (*func)(ALconfig, int))
{
- int par;
+ int par;
- if (!PyArg_ParseTuple(args, "i:SetConfig", &par))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:SetConfig", &par))
+ return NULL;
- if ((*func)(self->config, par) == -1)
- return NULL;
+ if ((*func)(self->config, par) == -1)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
GetConfig(alcobject *self, PyObject *args, int (*func)(ALconfig))
-{
- int par;
+{
+ int par;
+
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
-
- if ((par = (*func)(self->config)) == -1)
- return NULL;
+ if ((par = (*func)(self->config)) == -1)
+ return NULL;
- return PyInt_FromLong((long) par);
+ return PyInt_FromLong((long) par);
}
PyDoc_STRVAR(alc_SetWidth__doc__,
@@ -277,7 +277,7 @@ PyDoc_STRVAR(alc_SetWidth__doc__,
static PyObject *
alc_SetWidth(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetWidth);
+ return SetConfig(self, args, alSetWidth);
}
@@ -287,7 +287,7 @@ PyDoc_STRVAR(alc_GetWidth__doc__,
static PyObject *
alc_GetWidth(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetWidth);
+ return GetConfig(self, args, alGetWidth);
}
@@ -298,7 +298,7 @@ PyDoc_STRVAR(alc_SetSampFmt__doc__,
static PyObject *
alc_SetSampFmt(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetSampFmt);
+ return SetConfig(self, args, alSetSampFmt);
}
@@ -309,7 +309,7 @@ PyDoc_STRVAR(alc_GetSampFmt__doc__,
static PyObject *
alc_GetSampFmt(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetSampFmt);
+ return GetConfig(self, args, alGetSampFmt);
}
@@ -319,7 +319,7 @@ PyDoc_STRVAR(alc_SetChannels__doc__,
static PyObject *
alc_SetChannels(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetChannels);
+ return SetConfig(self, args, alSetChannels);
}
@@ -329,7 +329,7 @@ PyDoc_STRVAR(alc_GetChannels__doc__,
static PyObject *
alc_GetChannels(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetChannels);
+ return GetConfig(self, args, alGetChannels);
}
@@ -339,14 +339,14 @@ PyDoc_STRVAR(alc_SetFloatMax__doc__,
static PyObject *
alc_SetFloatMax(alcobject *self, PyObject *args)
{
- double maximum_value;
+ double maximum_value;
- if (!PyArg_ParseTuple(args, "d:SetFloatMax", &maximum_value))
- return NULL;
- if (alSetFloatMax(self->config, maximum_value) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "d:SetFloatMax", &maximum_value))
+ return NULL;
+ if (alSetFloatMax(self->config, maximum_value) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -356,13 +356,13 @@ PyDoc_STRVAR(alc_GetFloatMax__doc__,
static PyObject *
alc_GetFloatMax(alcobject *self, PyObject *args)
{
- double maximum_value;
+ double maximum_value;
- if (!PyArg_ParseTuple(args, ":GetFloatMax"))
- return NULL;
- if ((maximum_value = alGetFloatMax(self->config)) == 0)
- return NULL;
- return PyFloat_FromDouble(maximum_value);
+ if (!PyArg_ParseTuple(args, ":GetFloatMax"))
+ return NULL;
+ if ((maximum_value = alGetFloatMax(self->config)) == 0)
+ return NULL;
+ return PyFloat_FromDouble(maximum_value);
}
@@ -372,7 +372,7 @@ PyDoc_STRVAR(alc_SetDevice__doc__,
static PyObject *
alc_SetDevice(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetDevice);
+ return SetConfig(self, args, alSetDevice);
}
@@ -382,7 +382,7 @@ PyDoc_STRVAR(alc_GetDevice__doc__,
static PyObject *
alc_GetDevice(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetDevice);
+ return GetConfig(self, args, alGetDevice);
}
@@ -392,7 +392,7 @@ PyDoc_STRVAR(alc_SetQueueSize__doc__,
static PyObject *
alc_SetQueueSize(alcobject *self, PyObject *args)
{
- return SetConfig(self, args, alSetQueueSize);
+ return SetConfig(self, args, alSetQueueSize);
}
@@ -402,7 +402,7 @@ PyDoc_STRVAR(alc_GetQueueSize__doc__,
static PyObject *
alc_GetQueueSize(alcobject *self, PyObject *args)
{
- return GetConfig(self, args, alGetQueueSize);
+ return GetConfig(self, args, alGetQueueSize);
}
#endif /* AL_NO_ELEM */
@@ -410,66 +410,66 @@ alc_GetQueueSize(alcobject *self, PyObject *args)
static PyObject *
setconfig(alcobject *self, PyObject *args, int (*func)(ALconfig, long))
{
- long par;
+ long par;
- if (!PyArg_ParseTuple(args, "l:SetConfig", &par))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:SetConfig", &par))
+ return NULL;
- if ((*func)(self->config, par) == -1)
- return NULL;
+ if ((*func)(self->config, par) == -1)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
getconfig(alcobject *self, PyObject *args, long (*func)(ALconfig))
-{
- long par;
+{
+ long par;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
-
- if ((par = (*func)(self->config)) == -1)
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
- return PyInt_FromLong((long) par);
+ if ((par = (*func)(self->config)) == -1)
+ return NULL;
+
+ return PyInt_FromLong((long) par);
}
static PyObject *
alc_setqueuesize (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetqueuesize);
+ return setconfig(self, args, ALsetqueuesize);
}
static PyObject *
alc_getqueuesize (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetqueuesize);
+ return getconfig(self, args, ALgetqueuesize);
}
static PyObject *
alc_setwidth (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetwidth);
+ return setconfig(self, args, ALsetwidth);
}
static PyObject *
alc_getwidth (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetwidth);
+ return getconfig(self, args, ALgetwidth);
}
static PyObject *
alc_getchannels (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetchannels);
+ return getconfig(self, args, ALgetchannels);
}
static PyObject *
alc_setchannels (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetchannels);
+ return setconfig(self, args, ALsetchannels);
}
#ifdef AL_405
@@ -477,70 +477,70 @@ alc_setchannels (alcobject *self, PyObject *args)
static PyObject *
alc_getsampfmt (alcobject *self, PyObject *args)
{
- return getconfig(self, args, ALgetsampfmt);
+ return getconfig(self, args, ALgetsampfmt);
}
static PyObject *
alc_setsampfmt (alcobject *self, PyObject *args)
{
- return setconfig(self, args, ALsetsampfmt);
+ return setconfig(self, args, ALsetsampfmt);
}
static PyObject *
alc_getfloatmax(alcobject *self, PyObject *args)
{
- double arg;
+ double arg;
- if (!PyArg_ParseTuple(args, ":GetFloatMax"))
- return 0;
- if ((arg = ALgetfloatmax(self->config)) == 0)
- return NULL;
- return PyFloat_FromDouble(arg);
+ if (!PyArg_ParseTuple(args, ":GetFloatMax"))
+ return 0;
+ if ((arg = ALgetfloatmax(self->config)) == 0)
+ return NULL;
+ return PyFloat_FromDouble(arg);
}
static PyObject *
alc_setfloatmax(alcobject *self, PyObject *args)
{
- double arg;
+ double arg;
- if (!PyArg_ParseTuple(args, "d:SetFloatMax", &arg))
- return 0;
- if (ALsetfloatmax(self->config, arg) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "d:SetFloatMax", &arg))
+ return 0;
+ if (ALsetfloatmax(self->config, arg) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_405 */
-
+
static struct PyMethodDef alc_methods[] = {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- {"SetWidth", (PyCFunction)alc_SetWidth, METH_VARARGS, alc_SetWidth__doc__},
- {"GetWidth", (PyCFunction)alc_GetWidth, METH_VARARGS, alc_GetWidth__doc__},
- {"SetSampFmt", (PyCFunction)alc_SetSampFmt, METH_VARARGS, alc_SetSampFmt__doc__},
- {"GetSampFmt", (PyCFunction)alc_GetSampFmt, METH_VARARGS, alc_GetSampFmt__doc__},
- {"SetChannels", (PyCFunction)alc_SetChannels, METH_VARARGS, alc_SetChannels__doc__},
- {"GetChannels", (PyCFunction)alc_GetChannels, METH_VARARGS, alc_GetChannels__doc__},
- {"SetFloatMax", (PyCFunction)alc_SetFloatMax, METH_VARARGS, alc_SetFloatMax__doc__},
- {"GetFloatMax", (PyCFunction)alc_GetFloatMax, METH_VARARGS, alc_GetFloatMax__doc__},
- {"SetDevice", (PyCFunction)alc_SetDevice, METH_VARARGS, alc_SetDevice__doc__},
- {"GetDevice", (PyCFunction)alc_GetDevice, METH_VARARGS, alc_GetDevice__doc__},
- {"SetQueueSize", (PyCFunction)alc_SetQueueSize, METH_VARARGS, alc_SetQueueSize__doc__},
- {"GetQueueSize", (PyCFunction)alc_GetQueueSize, METH_VARARGS, alc_GetQueueSize__doc__},
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ {"SetWidth", (PyCFunction)alc_SetWidth, METH_VARARGS, alc_SetWidth__doc__},
+ {"GetWidth", (PyCFunction)alc_GetWidth, METH_VARARGS, alc_GetWidth__doc__},
+ {"SetSampFmt", (PyCFunction)alc_SetSampFmt, METH_VARARGS, alc_SetSampFmt__doc__},
+ {"GetSampFmt", (PyCFunction)alc_GetSampFmt, METH_VARARGS, alc_GetSampFmt__doc__},
+ {"SetChannels", (PyCFunction)alc_SetChannels, METH_VARARGS, alc_SetChannels__doc__},
+ {"GetChannels", (PyCFunction)alc_GetChannels, METH_VARARGS, alc_GetChannels__doc__},
+ {"SetFloatMax", (PyCFunction)alc_SetFloatMax, METH_VARARGS, alc_SetFloatMax__doc__},
+ {"GetFloatMax", (PyCFunction)alc_GetFloatMax, METH_VARARGS, alc_GetFloatMax__doc__},
+ {"SetDevice", (PyCFunction)alc_SetDevice, METH_VARARGS, alc_SetDevice__doc__},
+ {"GetDevice", (PyCFunction)alc_GetDevice, METH_VARARGS, alc_GetDevice__doc__},
+ {"SetQueueSize", (PyCFunction)alc_SetQueueSize, METH_VARARGS, alc_SetQueueSize__doc__},
+ {"GetQueueSize", (PyCFunction)alc_GetQueueSize, METH_VARARGS, alc_GetQueueSize__doc__},
#endif /* AL_NO_ELEM */
- {"getqueuesize", (PyCFunction)alc_getqueuesize, METH_VARARGS},
- {"setqueuesize", (PyCFunction)alc_setqueuesize, METH_VARARGS},
- {"getwidth", (PyCFunction)alc_getwidth, METH_VARARGS},
- {"setwidth", (PyCFunction)alc_setwidth, METH_VARARGS},
- {"getchannels", (PyCFunction)alc_getchannels, METH_VARARGS},
- {"setchannels", (PyCFunction)alc_setchannels, METH_VARARGS},
+ {"getqueuesize", (PyCFunction)alc_getqueuesize, METH_VARARGS},
+ {"setqueuesize", (PyCFunction)alc_setqueuesize, METH_VARARGS},
+ {"getwidth", (PyCFunction)alc_getwidth, METH_VARARGS},
+ {"setwidth", (PyCFunction)alc_setwidth, METH_VARARGS},
+ {"getchannels", (PyCFunction)alc_getchannels, METH_VARARGS},
+ {"setchannels", (PyCFunction)alc_setchannels, METH_VARARGS},
#ifdef AL_405
- {"getsampfmt", (PyCFunction)alc_getsampfmt, METH_VARARGS},
- {"setsampfmt", (PyCFunction)alc_setsampfmt, METH_VARARGS},
- {"getfloatmax", (PyCFunction)alc_getfloatmax, METH_VARARGS},
- {"setfloatmax", (PyCFunction)alc_setfloatmax, METH_VARARGS},
+ {"getsampfmt", (PyCFunction)alc_getsampfmt, METH_VARARGS},
+ {"setsampfmt", (PyCFunction)alc_setsampfmt, METH_VARARGS},
+ {"getfloatmax", (PyCFunction)alc_getfloatmax, METH_VARARGS},
+ {"setfloatmax", (PyCFunction)alc_setfloatmax, METH_VARARGS},
#endif /* AL_405 */
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -549,67 +549,67 @@ static struct PyMethodDef alc_methods[] = {
static PyObject *
newalcobject(ALconfig config)
{
- alcobject *self;
-
- self = PyObject_New(alcobject, &Alctype);
- if (self == NULL)
- return NULL;
- /* XXXX Add your own initializers here */
- self->config = config;
- return (PyObject *) self;
+ alcobject *self;
+
+ self = PyObject_New(alcobject, &Alctype);
+ if (self == NULL)
+ return NULL;
+ /* XXXX Add your own initializers here */
+ self->config = config;
+ return (PyObject *) self;
}
static void
alc_dealloc(alcobject *self)
{
- /* XXXX Add your own cleanup code here */
-#ifdef AL_NO_ELEM /* IRIX 6 */
- (void) alFreeConfig(self->config); /* ignore errors */
+ /* XXXX Add your own cleanup code here */
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ (void) alFreeConfig(self->config); /* ignore errors */
#else
- (void) ALfreeconfig(self->config); /* ignore errors */
+ (void) ALfreeconfig(self->config); /* ignore errors */
#endif
- PyObject_Del(self);
+ PyObject_Del(self);
}
static PyObject *
alc_getattr(alcobject *self, char *name)
{
- /* XXXX Add your own getattr code here */
- return Py_FindMethod(alc_methods, (PyObject *)self, name);
+ /* XXXX Add your own getattr code here */
+ return Py_FindMethod(alc_methods, (PyObject *)self, name);
}
PyDoc_STRVAR(Alctype__doc__, "");
static PyTypeObject Alctype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "al.config", /*tp_name*/
- sizeof(alcobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)alc_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)alc_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,
- Alctype__doc__ /* Documentation string */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "al.config", /*tp_name*/
+ sizeof(alcobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)alc_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)alc_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,
+ Alctype__doc__ /* Documentation string */
};
/* End of code for config objects */
/* ---------------------------------------------------------------- */
-#ifdef AL_NO_ELEM /* IRIX 6 */
+#ifdef AL_NO_ELEM /* IRIX 6 */
PyDoc_STRVAR(alp_SetConfig__doc__,
"alSetConfig: set the ALconfig of an audio ALport.");
@@ -617,13 +617,13 @@ PyDoc_STRVAR(alp_SetConfig__doc__,
static PyObject *
alp_SetConfig(alpobject *self, PyObject *args)
{
- alcobject *config;
- if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
- return NULL;
- if (alSetConfig(self->port, config->config) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ alcobject *config;
+ if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
+ return NULL;
+ if (alSetConfig(self->port, config->config) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -633,12 +633,12 @@ PyDoc_STRVAR(alp_GetConfig__doc__,
static PyObject *
alp_GetConfig(alpobject *self, PyObject *args)
{
- ALconfig config;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
- if ((config = alGetConfig(self->port)) == NULL)
- return NULL;
- return newalcobject(config);
+ ALconfig config;
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
+ if ((config = alGetConfig(self->port)) == NULL)
+ return NULL;
+ return newalcobject(config);
}
@@ -648,13 +648,13 @@ PyDoc_STRVAR(alp_GetResource__doc__,
static PyObject *
alp_GetResource(alpobject *self, PyObject *args)
{
- int resource;
+ int resource;
- if (!PyArg_ParseTuple(args, ":GetResource"))
- return NULL;
- if ((resource = alGetResource(self->port)) == 0)
- return NULL;
- return PyInt_FromLong((long) resource);
+ if (!PyArg_ParseTuple(args, ":GetResource"))
+ return NULL;
+ if ((resource = alGetResource(self->port)) == 0)
+ return NULL;
+ return PyInt_FromLong((long) resource);
}
@@ -664,15 +664,15 @@ PyDoc_STRVAR(alp_GetFD__doc__,
static PyObject *
alp_GetFD(alpobject *self, PyObject *args)
{
- int fd;
+ int fd;
- if (!PyArg_ParseTuple(args, ":GetFD"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetFD"))
+ return NULL;
- if ((fd = alGetFD(self->port)) < 0)
- return NULL;
+ if ((fd = alGetFD(self->port)) < 0)
+ return NULL;
- return PyInt_FromLong((long) fd);
+ return PyInt_FromLong((long) fd);
}
@@ -683,13 +683,13 @@ PyDoc_STRVAR(alp_GetFilled__doc__,
static PyObject *
alp_GetFilled(alpobject *self, PyObject *args)
{
- int filled;
+ int filled;
- if (!PyArg_ParseTuple(args, ":GetFilled"))
- return NULL;
- if ((filled = alGetFilled(self->port)) < 0)
- return NULL;
- return PyInt_FromLong((long) filled);
+ if (!PyArg_ParseTuple(args, ":GetFilled"))
+ return NULL;
+ if ((filled = alGetFilled(self->port)) < 0)
+ return NULL;
+ return PyInt_FromLong((long) filled);
}
@@ -700,13 +700,13 @@ PyDoc_STRVAR(alp_GetFillable__doc__,
static PyObject *
alp_GetFillable(alpobject *self, PyObject *args)
{
- int fillable;
+ int fillable;
- if (!PyArg_ParseTuple(args, ":GetFillable"))
- return NULL;
- if ((fillable = alGetFillable(self->port)) < 0)
- return NULL;
- return PyInt_FromLong((long) fillable);
+ if (!PyArg_ParseTuple(args, ":GetFillable"))
+ return NULL;
+ if ((fillable = alGetFillable(self->port)) < 0)
+ return NULL;
+ return PyInt_FromLong((long) fillable);
}
@@ -716,64 +716,64 @@ PyDoc_STRVAR(alp_ReadFrames__doc__,
static PyObject *
alp_ReadFrames(alpobject *self, PyObject *args)
{
- int framecount;
- PyObject *v;
- int size;
- int ch;
- ALconfig c;
-
- if (!PyArg_ParseTuple(args, "i:ReadFrames", &framecount))
- return NULL;
- if (framecount < 0) {
- PyErr_SetString(ErrorObject, "negative framecount");
- return NULL;
- }
- c = alGetConfig(self->port);
- switch (alGetSampFmt(c)) {
- case AL_SAMPFMT_TWOSCOMP:
- switch (alGetWidth(c)) {
- case AL_SAMPLE_8:
- size = 1;
- break;
- case AL_SAMPLE_16:
- size = 2;
- break;
- case AL_SAMPLE_24:
- size = 4;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine width");
- alFreeConfig(c);
- return NULL;
- }
- break;
- case AL_SAMPFMT_FLOAT:
- size = 4;
- break;
- case AL_SAMPFMT_DOUBLE:
- size = 8;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine format");
- alFreeConfig(c);
- return NULL;
- }
- ch = alGetChannels(c);
- alFreeConfig(c);
- if (ch < 0) {
- PyErr_SetString(ErrorObject, "can't determine # of channels");
- return NULL;
- }
- size *= ch;
- v = PyString_FromStringAndSize((char *) NULL, size * framecount);
- if (v == NULL)
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- alReadFrames(self->port, (void *) PyString_AS_STRING(v), framecount);
- Py_END_ALLOW_THREADS
-
- return v;
+ int framecount;
+ PyObject *v;
+ int size;
+ int ch;
+ ALconfig c;
+
+ if (!PyArg_ParseTuple(args, "i:ReadFrames", &framecount))
+ return NULL;
+ if (framecount < 0) {
+ PyErr_SetString(ErrorObject, "negative framecount");
+ return NULL;
+ }
+ c = alGetConfig(self->port);
+ switch (alGetSampFmt(c)) {
+ case AL_SAMPFMT_TWOSCOMP:
+ switch (alGetWidth(c)) {
+ case AL_SAMPLE_8:
+ size = 1;
+ break;
+ case AL_SAMPLE_16:
+ size = 2;
+ break;
+ case AL_SAMPLE_24:
+ size = 4;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine width");
+ alFreeConfig(c);
+ return NULL;
+ }
+ break;
+ case AL_SAMPFMT_FLOAT:
+ size = 4;
+ break;
+ case AL_SAMPFMT_DOUBLE:
+ size = 8;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine format");
+ alFreeConfig(c);
+ return NULL;
+ }
+ ch = alGetChannels(c);
+ alFreeConfig(c);
+ if (ch < 0) {
+ PyErr_SetString(ErrorObject, "can't determine # of channels");
+ return NULL;
+ }
+ size *= ch;
+ v = PyString_FromStringAndSize((char *) NULL, size * framecount);
+ if (v == NULL)
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ alReadFrames(self->port, (void *) PyString_AS_STRING(v), framecount);
+ Py_END_ALLOW_THREADS
+
+ return v;
}
@@ -783,19 +783,19 @@ PyDoc_STRVAR(alp_DiscardFrames__doc__,
static PyObject *
alp_DiscardFrames(alpobject *self, PyObject *args)
{
- int framecount;
+ int framecount;
- if (!PyArg_ParseTuple(args, "i:DiscardFrames", &framecount))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:DiscardFrames", &framecount))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- framecount = alDiscardFrames(self->port, framecount);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ framecount = alDiscardFrames(self->port, framecount);
+ Py_END_ALLOW_THREADS
- if (framecount < 0)
- return NULL;
+ if (framecount < 0)
+ return NULL;
- return PyInt_FromLong((long) framecount);
+ return PyInt_FromLong((long) framecount);
}
@@ -805,22 +805,22 @@ PyDoc_STRVAR(alp_ZeroFrames__doc__,
static PyObject *
alp_ZeroFrames(alpobject *self, PyObject *args)
{
- int framecount;
+ int framecount;
- if (!PyArg_ParseTuple(args, "i:ZeroFrames", &framecount))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:ZeroFrames", &framecount))
+ return NULL;
- if (framecount < 0) {
- PyErr_SetString(ErrorObject, "negative framecount");
- return NULL;
- }
+ if (framecount < 0) {
+ PyErr_SetString(ErrorObject, "negative framecount");
+ return NULL;
+ }
- Py_BEGIN_ALLOW_THREADS
- alZeroFrames(self->port, framecount);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ alZeroFrames(self->port, framecount);
+ Py_END_ALLOW_THREADS
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -830,16 +830,16 @@ PyDoc_STRVAR(alp_SetFillPoint__doc__,
static PyObject *
alp_SetFillPoint(alpobject *self, PyObject *args)
{
- int fillpoint;
+ int fillpoint;
- if (!PyArg_ParseTuple(args, "i:SetFillPoint", &fillpoint))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:SetFillPoint", &fillpoint))
+ return NULL;
- if (alSetFillPoint(self->port, fillpoint) < 0)
- return NULL;
+ if (alSetFillPoint(self->port, fillpoint) < 0)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -849,15 +849,15 @@ PyDoc_STRVAR(alp_GetFillPoint__doc__,
static PyObject *
alp_GetFillPoint(alpobject *self, PyObject *args)
{
- int fillpoint;
+ int fillpoint;
- if (!PyArg_ParseTuple(args, ":GetFillPoint"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetFillPoint"))
+ return NULL;
- if ((fillpoint = alGetFillPoint(self->port)) < 0)
- return NULL;
+ if ((fillpoint = alGetFillPoint(self->port)) < 0)
+ return NULL;
- return PyInt_FromLong((long) fillpoint);
+ return PyInt_FromLong((long) fillpoint);
}
@@ -868,15 +868,15 @@ PyDoc_STRVAR(alp_GetFrameNumber__doc__,
static PyObject *
alp_GetFrameNumber(alpobject *self, PyObject *args)
{
- stamp_t fnum;
+ stamp_t fnum;
- if (!PyArg_ParseTuple(args, ":GetFrameNumber"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":GetFrameNumber"))
+ return NULL;
- if (alGetFrameNumber(self->port, &fnum) < 0)
- return NULL;
+ if (alGetFrameNumber(self->port, &fnum) < 0)
+ return NULL;
- return PyLong_FromLongLong((long long) fnum);
+ return PyLong_FromLongLong((long long) fnum);
}
@@ -887,24 +887,24 @@ PyDoc_STRVAR(alp_GetFrameTime__doc__,
static PyObject *
alp_GetFrameTime(alpobject *self, PyObject *args)
{
- stamp_t fnum, time;
- PyObject *ret, *v0, *v1;
+ stamp_t fnum, time;
+ PyObject *ret, *v0, *v1;
- if (!PyArg_ParseTuple(args, ":GetFrameTime"))
- return NULL;
- if (alGetFrameTime(self->port, &fnum, &time) < 0)
- return NULL;
- v0 = PyLong_FromLongLong((long long) fnum);
- v1 = PyLong_FromLongLong((long long) time);
- if (PyErr_Occurred()) {
- Py_XDECREF(v0);
- Py_XDECREF(v1);
- return NULL;
- }
- ret = PyTuple_Pack(2, v0, v1);
- Py_DECREF(v0);
- Py_DECREF(v1);
- return ret;
+ if (!PyArg_ParseTuple(args, ":GetFrameTime"))
+ return NULL;
+ if (alGetFrameTime(self->port, &fnum, &time) < 0)
+ return NULL;
+ v0 = PyLong_FromLongLong((long long) fnum);
+ v1 = PyLong_FromLongLong((long long) time);
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v0);
+ Py_XDECREF(v1);
+ return NULL;
+ }
+ ret = PyTuple_Pack(2, v0, v1);
+ Py_DECREF(v0);
+ Py_DECREF(v1);
+ return ret;
}
@@ -914,62 +914,62 @@ PyDoc_STRVAR(alp_WriteFrames__doc__,
static PyObject *
alp_WriteFrames(alpobject *self, PyObject *args)
{
- char *samples;
- int length;
- int size, ch;
- ALconfig c;
-
- if (!PyArg_ParseTuple(args, "s#:WriteFrames", &samples, &length))
- return NULL;
- c = alGetConfig(self->port);
- switch (alGetSampFmt(c)) {
- case AL_SAMPFMT_TWOSCOMP:
- switch (alGetWidth(c)) {
- case AL_SAMPLE_8:
- size = 1;
- break;
- case AL_SAMPLE_16:
- size = 2;
- break;
- case AL_SAMPLE_24:
- size = 4;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine width");
- alFreeConfig(c);
- return NULL;
- }
- break;
- case AL_SAMPFMT_FLOAT:
- size = 4;
- break;
- case AL_SAMPFMT_DOUBLE:
- size = 8;
- break;
- default:
- PyErr_SetString(ErrorObject, "can't determine format");
- alFreeConfig(c);
- return NULL;
- }
- ch = alGetChannels(c);
- alFreeConfig(c);
- if (ch < 0) {
- PyErr_SetString(ErrorObject, "can't determine # of channels");
- return NULL;
- }
- size *= ch;
- if (length % size != 0) {
- PyErr_SetString(ErrorObject,
- "buffer length not whole number of frames");
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- alWriteFrames(self->port, (void *) samples, length / size);
- Py_END_ALLOW_THREADS
-
- Py_INCREF(Py_None);
- return Py_None;
+ char *samples;
+ int length;
+ int size, ch;
+ ALconfig c;
+
+ if (!PyArg_ParseTuple(args, "s#:WriteFrames", &samples, &length))
+ return NULL;
+ c = alGetConfig(self->port);
+ switch (alGetSampFmt(c)) {
+ case AL_SAMPFMT_TWOSCOMP:
+ switch (alGetWidth(c)) {
+ case AL_SAMPLE_8:
+ size = 1;
+ break;
+ case AL_SAMPLE_16:
+ size = 2;
+ break;
+ case AL_SAMPLE_24:
+ size = 4;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine width");
+ alFreeConfig(c);
+ return NULL;
+ }
+ break;
+ case AL_SAMPFMT_FLOAT:
+ size = 4;
+ break;
+ case AL_SAMPFMT_DOUBLE:
+ size = 8;
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "can't determine format");
+ alFreeConfig(c);
+ return NULL;
+ }
+ ch = alGetChannels(c);
+ alFreeConfig(c);
+ if (ch < 0) {
+ PyErr_SetString(ErrorObject, "can't determine # of channels");
+ return NULL;
+ }
+ size *= ch;
+ if (length % size != 0) {
+ PyErr_SetString(ErrorObject,
+ "buffer length not whole number of frames");
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ alWriteFrames(self->port, (void *) samples, length / size);
+ Py_END_ALLOW_THREADS
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -978,13 +978,13 @@ PyDoc_STRVAR(alp_ClosePort__doc__, "alClosePort: close an audio port.");
static PyObject *
alp_ClosePort(alpobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":ClosePort"))
- return NULL;
- if (alClosePort(self->port) < 0)
- return NULL;
- self->port = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":ClosePort"))
+ return NULL;
+ if (alClosePort(self->port) < 0)
+ return NULL;
+ self->port = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_NO_ELEM */
@@ -993,257 +993,257 @@ alp_ClosePort(alpobject *self, PyObject *args)
static PyObject *
alp_closeport(alpobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":ClosePort"))
- return NULL;
- if (ALcloseport(self->port) < 0)
- return NULL;
- self->port = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":ClosePort"))
+ return NULL;
+ if (ALcloseport(self->port) < 0)
+ return NULL;
+ self->port = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_getfd(alpobject *self, PyObject *args)
{
- int fd;
+ int fd;
- if (!PyArg_ParseTuple(args, ":GetFD"))
- return NULL;
- if ((fd = ALgetfd(self-> port)) == -1)
- return NULL;
- return PyInt_FromLong(fd);
+ if (!PyArg_ParseTuple(args, ":GetFD"))
+ return NULL;
+ if ((fd = ALgetfd(self-> port)) == -1)
+ return NULL;
+ return PyInt_FromLong(fd);
}
static PyObject *
alp_getfilled(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, ":GetFilled"))
- return NULL;
- if ((count = ALgetfilled(self-> port)) == -1)
- return NULL;
- return PyInt_FromLong(count);
+ if (!PyArg_ParseTuple(args, ":GetFilled"))
+ return NULL;
+ if ((count = ALgetfilled(self-> port)) == -1)
+ return NULL;
+ return PyInt_FromLong(count);
}
static PyObject *
alp_getfillable(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, ":GetFillable"))
- return NULL;
- if ((count = ALgetfillable(self-> port)) == -1)
- return NULL;
- return PyInt_FromLong (count);
+ if (!PyArg_ParseTuple(args, ":GetFillable"))
+ return NULL;
+ if ((count = ALgetfillable(self-> port)) == -1)
+ return NULL;
+ return PyInt_FromLong (count);
}
static PyObject *
alp_readsamps(alpobject *self, PyObject *args)
{
- long count;
- PyObject *v;
- ALconfig c;
- int width;
- int ret;
+ long count;
+ PyObject *v;
+ ALconfig c;
+ int width;
+ int ret;
- if (!PyArg_ParseTuple(args, "l:readsamps", &count))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:readsamps", &count))
+ return NULL;
- if (count <= 0) {
- PyErr_SetString(ErrorObject, "al.readsamps : arg <= 0");
- return NULL;
- }
+ if (count <= 0) {
+ PyErr_SetString(ErrorObject, "al.readsamps : arg <= 0");
+ return NULL;
+ }
- c = ALgetconfig(self->port);
+ c = ALgetconfig(self->port);
#ifdef AL_405
- width = ALgetsampfmt(c);
- if (width == AL_SAMPFMT_FLOAT)
- width = sizeof(float);
- else if (width == AL_SAMPFMT_DOUBLE)
- width = sizeof(double);
- else
- width = ALgetwidth(c);
+ width = ALgetsampfmt(c);
+ if (width == AL_SAMPFMT_FLOAT)
+ width = sizeof(float);
+ else if (width == AL_SAMPFMT_DOUBLE)
+ width = sizeof(double);
+ else
+ width = ALgetwidth(c);
#else
- width = ALgetwidth(c);
+ width = ALgetwidth(c);
#endif /* AL_405 */
- ALfreeconfig(c);
- v = PyString_FromStringAndSize((char *)NULL, width * count);
- if (v == NULL)
- return NULL;
+ ALfreeconfig(c);
+ v = PyString_FromStringAndSize((char *)NULL, width * count);
+ if (v == NULL)
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- ret = ALreadsamps(self->port, (void *) PyString_AsString(v), count);
- Py_END_ALLOW_THREADS
- if (ret == -1) {
- Py_DECREF(v);
- return NULL;
- }
+ Py_BEGIN_ALLOW_THREADS
+ ret = ALreadsamps(self->port, (void *) PyString_AsString(v), count);
+ Py_END_ALLOW_THREADS
+ if (ret == -1) {
+ Py_DECREF(v);
+ return NULL;
+ }
- return (v);
+ return (v);
}
static PyObject *
alp_writesamps(alpobject *self, PyObject *args)
{
- char *buf;
- int size, width;
- ALconfig c;
- int ret;
+ char *buf;
+ int size, width;
+ ALconfig c;
+ int ret;
- if (!PyArg_ParseTuple(args, "s#:writesamps", &buf, &size))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#:writesamps", &buf, &size))
+ return NULL;
- c = ALgetconfig(self->port);
+ c = ALgetconfig(self->port);
#ifdef AL_405
- width = ALgetsampfmt(c);
- if (width == AL_SAMPFMT_FLOAT)
- width = sizeof(float);
- else if (width == AL_SAMPFMT_DOUBLE)
- width = sizeof(double);
- else
- width = ALgetwidth(c);
+ width = ALgetsampfmt(c);
+ if (width == AL_SAMPFMT_FLOAT)
+ width = sizeof(float);
+ else if (width == AL_SAMPFMT_DOUBLE)
+ width = sizeof(double);
+ else
+ width = ALgetwidth(c);
#else
- width = ALgetwidth(c);
+ width = ALgetwidth(c);
#endif /* AL_405 */
- ALfreeconfig(c);
- Py_BEGIN_ALLOW_THREADS
- ret = ALwritesamps (self->port, (void *) buf, (long) size / width);
- Py_END_ALLOW_THREADS
- if (ret == -1)
- return NULL;
+ ALfreeconfig(c);
+ Py_BEGIN_ALLOW_THREADS
+ ret = ALwritesamps (self->port, (void *) buf, (long) size / width);
+ Py_END_ALLOW_THREADS
+ if (ret == -1)
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_getfillpoint(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, ":GetFillPoint"))
- return NULL;
- if ((count = ALgetfillpoint(self->port)) == -1)
- return NULL;
- return PyInt_FromLong(count);
+ if (!PyArg_ParseTuple(args, ":GetFillPoint"))
+ return NULL;
+ if ((count = ALgetfillpoint(self->port)) == -1)
+ return NULL;
+ return PyInt_FromLong(count);
}
static PyObject *
alp_setfillpoint(alpobject *self, PyObject *args)
{
- long count;
+ long count;
- if (!PyArg_ParseTuple(args, "l:SetFillPoint", &count))
- return NULL;
- if (ALsetfillpoint(self->port, count) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "l:SetFillPoint", &count))
+ return NULL;
+ if (ALsetfillpoint(self->port, count) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_setconfig(alpobject *self, PyObject *args)
{
- alcobject *config;
+ alcobject *config;
- if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
- return NULL;
- if (ALsetconfig(self->port, config->config) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "O!:SetConfig", &Alctype, &config))
+ return NULL;
+ if (ALsetconfig(self->port, config->config) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
alp_getconfig(alpobject *self, PyObject *args)
{
- ALconfig config;
+ ALconfig config;
- if (!PyArg_ParseTuple(args, ":GetConfig"))
- return NULL;
- config = ALgetconfig(self->port);
- if (config == NULL)
- return NULL;
- return newalcobject(config);
+ if (!PyArg_ParseTuple(args, ":GetConfig"))
+ return NULL;
+ config = ALgetconfig(self->port);
+ if (config == NULL)
+ return NULL;
+ return newalcobject(config);
}
#ifdef AL_405
static PyObject *
alp_getstatus(alpobject *self, PyObject *args)
{
- PyObject *list, *v;
- long *PVbuffer;
- long length;
- int i;
-
- if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list))
- return NULL;
- length = PyList_Size(list);
- PVbuffer = PyMem_NEW(long, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
- for (i = 0; i < length; i++) {
- v = PyList_GetItem(list, i);
- if (!PyInt_Check(v)) {
- PyMem_DEL(PVbuffer);
- PyErr_BadArgument();
- return NULL;
- }
- PVbuffer[i] = PyInt_AsLong(v);
- }
-
- if (ALgetstatus(self->port, PVbuffer, length) == -1)
- return NULL;
-
- for (i = 0; i < length; i++)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
-
- PyMem_DEL(PVbuffer);
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *list, *v;
+ long *PVbuffer;
+ long length;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "O!", &PyList_Type, &list))
+ return NULL;
+ length = PyList_Size(list);
+ PVbuffer = PyMem_NEW(long, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+ for (i = 0; i < length; i++) {
+ v = PyList_GetItem(list, i);
+ if (!PyInt_Check(v)) {
+ PyMem_DEL(PVbuffer);
+ PyErr_BadArgument();
+ return NULL;
+ }
+ PVbuffer[i] = PyInt_AsLong(v);
+ }
+
+ if (ALgetstatus(self->port, PVbuffer, length) == -1)
+ return NULL;
+
+ for (i = 0; i < length; i++)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+
+ PyMem_DEL(PVbuffer);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_405 */
#endif /* OLD_INTERFACE */
static struct PyMethodDef alp_methods[] = {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- {"SetConfig", (PyCFunction)alp_SetConfig, METH_VARARGS, alp_SetConfig__doc__},
- {"GetConfig", (PyCFunction)alp_GetConfig, METH_VARARGS, alp_GetConfig__doc__},
- {"GetResource", (PyCFunction)alp_GetResource, METH_VARARGS, alp_GetResource__doc__},
- {"GetFD", (PyCFunction)alp_GetFD, METH_VARARGS, alp_GetFD__doc__},
- {"GetFilled", (PyCFunction)alp_GetFilled, METH_VARARGS, alp_GetFilled__doc__},
- {"GetFillable", (PyCFunction)alp_GetFillable, METH_VARARGS, alp_GetFillable__doc__},
- {"ReadFrames", (PyCFunction)alp_ReadFrames, METH_VARARGS, alp_ReadFrames__doc__},
- {"DiscardFrames", (PyCFunction)alp_DiscardFrames, METH_VARARGS, alp_DiscardFrames__doc__},
- {"ZeroFrames", (PyCFunction)alp_ZeroFrames, METH_VARARGS, alp_ZeroFrames__doc__},
- {"SetFillPoint", (PyCFunction)alp_SetFillPoint, METH_VARARGS, alp_SetFillPoint__doc__},
- {"GetFillPoint", (PyCFunction)alp_GetFillPoint, METH_VARARGS, alp_GetFillPoint__doc__},
- {"GetFrameNumber", (PyCFunction)alp_GetFrameNumber, METH_VARARGS, alp_GetFrameNumber__doc__},
- {"GetFrameTime", (PyCFunction)alp_GetFrameTime, METH_VARARGS, alp_GetFrameTime__doc__},
- {"WriteFrames", (PyCFunction)alp_WriteFrames, METH_VARARGS, alp_WriteFrames__doc__},
- {"ClosePort", (PyCFunction)alp_ClosePort, METH_VARARGS, alp_ClosePort__doc__},
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ {"SetConfig", (PyCFunction)alp_SetConfig, METH_VARARGS, alp_SetConfig__doc__},
+ {"GetConfig", (PyCFunction)alp_GetConfig, METH_VARARGS, alp_GetConfig__doc__},
+ {"GetResource", (PyCFunction)alp_GetResource, METH_VARARGS, alp_GetResource__doc__},
+ {"GetFD", (PyCFunction)alp_GetFD, METH_VARARGS, alp_GetFD__doc__},
+ {"GetFilled", (PyCFunction)alp_GetFilled, METH_VARARGS, alp_GetFilled__doc__},
+ {"GetFillable", (PyCFunction)alp_GetFillable, METH_VARARGS, alp_GetFillable__doc__},
+ {"ReadFrames", (PyCFunction)alp_ReadFrames, METH_VARARGS, alp_ReadFrames__doc__},
+ {"DiscardFrames", (PyCFunction)alp_DiscardFrames, METH_VARARGS, alp_DiscardFrames__doc__},
+ {"ZeroFrames", (PyCFunction)alp_ZeroFrames, METH_VARARGS, alp_ZeroFrames__doc__},
+ {"SetFillPoint", (PyCFunction)alp_SetFillPoint, METH_VARARGS, alp_SetFillPoint__doc__},
+ {"GetFillPoint", (PyCFunction)alp_GetFillPoint, METH_VARARGS, alp_GetFillPoint__doc__},
+ {"GetFrameNumber", (PyCFunction)alp_GetFrameNumber, METH_VARARGS, alp_GetFrameNumber__doc__},
+ {"GetFrameTime", (PyCFunction)alp_GetFrameTime, METH_VARARGS, alp_GetFrameTime__doc__},
+ {"WriteFrames", (PyCFunction)alp_WriteFrames, METH_VARARGS, alp_WriteFrames__doc__},
+ {"ClosePort", (PyCFunction)alp_ClosePort, METH_VARARGS, alp_ClosePort__doc__},
#endif /* AL_NO_ELEM */
#ifdef OLD_INTERFACE
- {"closeport", (PyCFunction)alp_closeport, METH_VARARGS},
- {"getfd", (PyCFunction)alp_getfd, METH_VARARGS},
- {"fileno", (PyCFunction)alp_getfd, METH_VARARGS},
- {"getfilled", (PyCFunction)alp_getfilled, METH_VARARGS},
- {"getfillable", (PyCFunction)alp_getfillable, METH_VARARGS},
- {"readsamps", (PyCFunction)alp_readsamps, METH_VARARGS},
- {"writesamps", (PyCFunction)alp_writesamps, METH_VARARGS},
- {"setfillpoint", (PyCFunction)alp_setfillpoint, METH_VARARGS},
- {"getfillpoint", (PyCFunction)alp_getfillpoint, METH_VARARGS},
- {"setconfig", (PyCFunction)alp_setconfig, METH_VARARGS},
- {"getconfig", (PyCFunction)alp_getconfig, METH_VARARGS},
+ {"closeport", (PyCFunction)alp_closeport, METH_VARARGS},
+ {"getfd", (PyCFunction)alp_getfd, METH_VARARGS},
+ {"fileno", (PyCFunction)alp_getfd, METH_VARARGS},
+ {"getfilled", (PyCFunction)alp_getfilled, METH_VARARGS},
+ {"getfillable", (PyCFunction)alp_getfillable, METH_VARARGS},
+ {"readsamps", (PyCFunction)alp_readsamps, METH_VARARGS},
+ {"writesamps", (PyCFunction)alp_writesamps, METH_VARARGS},
+ {"setfillpoint", (PyCFunction)alp_setfillpoint, METH_VARARGS},
+ {"getfillpoint", (PyCFunction)alp_getfillpoint, METH_VARARGS},
+ {"setconfig", (PyCFunction)alp_setconfig, METH_VARARGS},
+ {"getconfig", (PyCFunction)alp_getconfig, METH_VARARGS},
#ifdef AL_405
- {"getstatus", (PyCFunction)alp_getstatus, METH_VARARGS},
-#endif /* AL_405 */
+ {"getstatus", (PyCFunction)alp_getstatus, METH_VARARGS},
+#endif /* AL_405 */
#endif /* OLD_INTERFACE */
-
- {NULL, NULL} /* sentinel */
+
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -1252,74 +1252,74 @@ static struct PyMethodDef alp_methods[] = {
static PyObject *
newalpobject(ALport port)
{
- alpobject *self;
-
- self = PyObject_New(alpobject, &Alptype);
- if (self == NULL)
- return NULL;
- /* XXXX Add your own initializers here */
- self->port = port;
- return (PyObject *) self;
+ alpobject *self;
+
+ self = PyObject_New(alpobject, &Alptype);
+ if (self == NULL)
+ return NULL;
+ /* XXXX Add your own initializers here */
+ self->port = port;
+ return (PyObject *) self;
}
static void
alp_dealloc(alpobject *self)
{
- /* XXXX Add your own cleanup code here */
- if (self->port) {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- alClosePort(self->port);
+ /* XXXX Add your own cleanup code here */
+ if (self->port) {
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ alClosePort(self->port);
#else
- ALcloseport(self->port);
+ ALcloseport(self->port);
#endif
- }
- PyObject_Del(self);
+ }
+ PyObject_Del(self);
}
static PyObject *
alp_getattr(alpobject *self, char *name)
{
- /* XXXX Add your own getattr code here */
- if (self->port == NULL) {
- PyErr_SetString(ErrorObject, "port already closed");
- return NULL;
- }
- return Py_FindMethod(alp_methods, (PyObject *)self, name);
+ /* XXXX Add your own getattr code here */
+ if (self->port == NULL) {
+ PyErr_SetString(ErrorObject, "port already closed");
+ return NULL;
+ }
+ return Py_FindMethod(alp_methods, (PyObject *)self, name);
}
PyDoc_STRVAR(Alptype__doc__, "");
static PyTypeObject Alptype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "al.port", /*tp_name*/
- sizeof(alpobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)alp_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)alp_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,
- Alptype__doc__ /* Documentation string */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "al.port", /*tp_name*/
+ sizeof(alpobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)alp_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)alp_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,
+ Alptype__doc__ /* Documentation string */
};
/* End of code for port objects */
/* -------------------------------------------------------- */
-#ifdef AL_NO_ELEM /* IRIX 6 */
+#ifdef AL_NO_ELEM /* IRIX 6 */
PyDoc_STRVAR(al_NewConfig__doc__,
"alNewConfig: create and initialize an audio ALconfig structure.");
@@ -1327,13 +1327,13 @@ PyDoc_STRVAR(al_NewConfig__doc__,
static PyObject *
al_NewConfig(PyObject *self, PyObject *args)
{
- ALconfig config;
+ ALconfig config;
- if (!PyArg_ParseTuple(args, ":NewConfig"))
- return NULL;
- if ((config = alNewConfig()) == NULL)
- return NULL;
- return newalcobject(config);
+ if (!PyArg_ParseTuple(args, ":NewConfig"))
+ return NULL;
+ if ((config = alNewConfig()) == NULL)
+ return NULL;
+ return newalcobject(config);
}
PyDoc_STRVAR(al_OpenPort__doc__,
@@ -1342,15 +1342,15 @@ PyDoc_STRVAR(al_OpenPort__doc__,
static PyObject *
al_OpenPort(PyObject *self, PyObject *args)
{
- ALport port;
- char *name, *dir;
- alcobject *config = NULL;
+ ALport port;
+ char *name, *dir;
+ alcobject *config = NULL;
- if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
- return NULL;
- if ((port = alOpenPort(name, dir, config ? config->config : NULL)) == NULL)
- return NULL;
- return newalpobject(port);
+ if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
+ return NULL;
+ if ((port = alOpenPort(name, dir, config ? config->config : NULL)) == NULL)
+ return NULL;
+ return newalpobject(port);
}
PyDoc_STRVAR(al_Connect__doc__,
@@ -1359,37 +1359,37 @@ PyDoc_STRVAR(al_Connect__doc__,
static PyObject *
al_Connect(PyObject *self, PyObject *args)
{
- int source, dest, nprops = 0, id, i;
- ALpv *props = NULL;
- ALparamInfo *propinfo = NULL;
- PyObject *propobj = NULL;
-
- if (!PyArg_ParseTuple(args, "ii|O!:Connect", &source, &dest, &PyList_Type, &propobj))
- return NULL;
- if (propobj != NULL) {
- nprops = python2params(source, dest, propobj, &props, &propinfo);
- if (nprops < 0)
- return NULL;
- }
-
- id = alConnect(source, dest, props, nprops);
-
- if (props) {
- for (i = 0; i < nprops; i++) {
- switch (propinfo[i].valueType) {
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- PyMem_DEL(props[i].value.ptr);
- break;
- }
- }
- PyMem_DEL(props);
- PyMem_DEL(propinfo);
- }
-
- if (id < 0)
- return NULL;
- return PyInt_FromLong((long) id);
+ int source, dest, nprops = 0, id, i;
+ ALpv *props = NULL;
+ ALparamInfo *propinfo = NULL;
+ PyObject *propobj = NULL;
+
+ if (!PyArg_ParseTuple(args, "ii|O!:Connect", &source, &dest, &PyList_Type, &propobj))
+ return NULL;
+ if (propobj != NULL) {
+ nprops = python2params(source, dest, propobj, &props, &propinfo);
+ if (nprops < 0)
+ return NULL;
+ }
+
+ id = alConnect(source, dest, props, nprops);
+
+ if (props) {
+ for (i = 0; i < nprops; i++) {
+ switch (propinfo[i].valueType) {
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ PyMem_DEL(props[i].value.ptr);
+ break;
+ }
+ }
+ PyMem_DEL(props);
+ PyMem_DEL(propinfo);
+ }
+
+ if (id < 0)
+ return NULL;
+ return PyInt_FromLong((long) id);
}
PyDoc_STRVAR(al_Disconnect__doc__,
@@ -1398,14 +1398,14 @@ PyDoc_STRVAR(al_Disconnect__doc__,
static PyObject *
al_Disconnect(PyObject *self, PyObject *args)
{
- int res;
+ int res;
- if (!PyArg_ParseTuple(args, "i:Disconnect", &res))
- return NULL;
- if (alDisconnect(res) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:Disconnect", &res))
+ return NULL;
+ if (alDisconnect(res) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(al_GetParams__doc__,
@@ -1414,143 +1414,143 @@ PyDoc_STRVAR(al_GetParams__doc__,
static PyObject *
al_GetParams(PyObject *self, PyObject *args)
{
- int resource;
- PyObject *pvslist, *item = NULL, *v = NULL;
- ALpv *pvs;
- int i, j, npvs;
- ALparamInfo *pinfo;
-
- if (!PyArg_ParseTuple(args, "iO!:GetParams", &resource, &PyList_Type, &pvslist))
- return NULL;
- npvs = PyList_Size(pvslist);
- pvs = PyMem_NEW(ALpv, npvs);
- pinfo = PyMem_NEW(ALparamInfo, npvs);
- for (i = 0; i < npvs; i++) {
- item = PyList_GetItem(pvslist, i);
- if (!PyInt_Check(item)) {
- item = NULL;
- PyErr_SetString(ErrorObject, "list of integers expected");
- goto error;
- }
- pvs[i].param = (int) PyInt_AsLong(item);
- item = NULL; /* not needed anymore */
- if (alGetParamInfo(resource, pvs[i].param, &pinfo[i]) < 0)
- goto error;
- switch (pinfo[i].valueType) {
- case AL_NO_VAL:
- break;
- case AL_MATRIX_VAL:
- pinfo[i].maxElems *= pinfo[i].maxElems2;
- /* fall through */
- case AL_STRING_VAL:
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- switch (pinfo[i].elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- pvs[i].value.ptr = PyMem_NEW(int, pinfo[i].maxElems);
- pvs[i].sizeIn = pinfo[i].maxElems;
- break;
- case AL_INT64_ELEM:
- case AL_FIXED_ELEM:
- pvs[i].value.ptr = PyMem_NEW(long long, pinfo[i].maxElems);
- pvs[i].sizeIn = pinfo[i].maxElems;
- break;
- case AL_CHAR_ELEM:
- pvs[i].value.ptr = PyMem_NEW(char, 32);
- pvs[i].sizeIn = 32;
- break;
- case AL_NO_ELEM:
- case AL_PTR_ELEM:
- default:
- PyErr_SetString(ErrorObject, "internal error");
- goto error;
- }
- break;
- case AL_SCALAR_VAL:
- break;
- default:
- PyErr_SetString(ErrorObject, "internal error");
- goto error;
- }
- if (pinfo[i].valueType == AL_MATRIX_VAL) {
- pinfo[i].maxElems /= pinfo[i].maxElems2;
- pvs[i].sizeIn /= pinfo[i].maxElems2;
- pvs[i].size2In = pinfo[i].maxElems2;
- }
- }
- if (alGetParams(resource, pvs, npvs) < 0)
- goto error;
- if (!(v = PyList_New(npvs)))
- goto error;
- for (i = 0; i < npvs; i++) {
- if (pvs[i].sizeOut < 0) {
- char buf[32];
- PyOS_snprintf(buf, sizeof(buf),
- "problem with param %d", i);
- PyErr_SetString(ErrorObject, buf);
- goto error;
- }
- switch (pinfo[i].valueType) {
- case AL_NO_VAL:
- item = Py_None;
- Py_INCREF(item);
- break;
- case AL_STRING_VAL:
- item = PyString_FromString(pvs[i].value.ptr);
- PyMem_DEL(pvs[i].value.ptr);
- break;
- case AL_MATRIX_VAL:
- /* XXXX this is not right */
- pvs[i].sizeOut *= pvs[i].size2Out;
- /* fall through */
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- item = PyList_New(pvs[i].sizeOut);
- for (j = 0; j < pvs[i].sizeOut; j++) {
- switch (pinfo[i].elementType) {
- case AL_INT32_ELEM:
- case AL_RESOURCE_ELEM:
- case AL_ENUM_ELEM:
- PyList_SetItem(item, j, PyInt_FromLong((long) ((int *) pvs[i].value.ptr)[j]));
- break;
- case AL_INT64_ELEM:
- PyList_SetItem(item, j, PyLong_FromLongLong(((long long *) pvs[i].value.ptr)[j]));
- break;
- case AL_FIXED_ELEM:
- PyList_SetItem(item, j, PyFloat_FromDouble(alFixedToDouble(((long long *) pvs[i].value.ptr)[j])));
- break;
- default:
- PyErr_SetString(ErrorObject, "internal error");
- goto error;
- }
- }
- PyMem_DEL(pvs[i].value.ptr);
- break;
- case AL_SCALAR_VAL:
- item = param2python(resource, pvs[i].param, pvs[i].value, &pinfo[i]);
- break;
- }
- if (PyErr_Occurred() ||
- PyList_SetItem(v, i, Py_BuildValue("(iO)", pvs[i].param,
- item)) < 0 ||
- PyErr_Occurred())
- goto error;
- Py_DECREF(item);
- }
- PyMem_DEL(pvs);
- PyMem_DEL(pinfo);
- return v;
+ int resource;
+ PyObject *pvslist, *item = NULL, *v = NULL;
+ ALpv *pvs;
+ int i, j, npvs;
+ ALparamInfo *pinfo;
+
+ if (!PyArg_ParseTuple(args, "iO!:GetParams", &resource, &PyList_Type, &pvslist))
+ return NULL;
+ npvs = PyList_Size(pvslist);
+ pvs = PyMem_NEW(ALpv, npvs);
+ pinfo = PyMem_NEW(ALparamInfo, npvs);
+ for (i = 0; i < npvs; i++) {
+ item = PyList_GetItem(pvslist, i);
+ if (!PyInt_Check(item)) {
+ item = NULL;
+ PyErr_SetString(ErrorObject, "list of integers expected");
+ goto error;
+ }
+ pvs[i].param = (int) PyInt_AsLong(item);
+ item = NULL; /* not needed anymore */
+ if (alGetParamInfo(resource, pvs[i].param, &pinfo[i]) < 0)
+ goto error;
+ switch (pinfo[i].valueType) {
+ case AL_NO_VAL:
+ break;
+ case AL_MATRIX_VAL:
+ pinfo[i].maxElems *= pinfo[i].maxElems2;
+ /* fall through */
+ case AL_STRING_VAL:
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ switch (pinfo[i].elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ pvs[i].value.ptr = PyMem_NEW(int, pinfo[i].maxElems);
+ pvs[i].sizeIn = pinfo[i].maxElems;
+ break;
+ case AL_INT64_ELEM:
+ case AL_FIXED_ELEM:
+ pvs[i].value.ptr = PyMem_NEW(long long, pinfo[i].maxElems);
+ pvs[i].sizeIn = pinfo[i].maxElems;
+ break;
+ case AL_CHAR_ELEM:
+ pvs[i].value.ptr = PyMem_NEW(char, 32);
+ pvs[i].sizeIn = 32;
+ break;
+ case AL_NO_ELEM:
+ case AL_PTR_ELEM:
+ default:
+ PyErr_SetString(ErrorObject, "internal error");
+ goto error;
+ }
+ break;
+ case AL_SCALAR_VAL:
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "internal error");
+ goto error;
+ }
+ if (pinfo[i].valueType == AL_MATRIX_VAL) {
+ pinfo[i].maxElems /= pinfo[i].maxElems2;
+ pvs[i].sizeIn /= pinfo[i].maxElems2;
+ pvs[i].size2In = pinfo[i].maxElems2;
+ }
+ }
+ if (alGetParams(resource, pvs, npvs) < 0)
+ goto error;
+ if (!(v = PyList_New(npvs)))
+ goto error;
+ for (i = 0; i < npvs; i++) {
+ if (pvs[i].sizeOut < 0) {
+ char buf[32];
+ PyOS_snprintf(buf, sizeof(buf),
+ "problem with param %d", i);
+ PyErr_SetString(ErrorObject, buf);
+ goto error;
+ }
+ switch (pinfo[i].valueType) {
+ case AL_NO_VAL:
+ item = Py_None;
+ Py_INCREF(item);
+ break;
+ case AL_STRING_VAL:
+ item = PyString_FromString(pvs[i].value.ptr);
+ PyMem_DEL(pvs[i].value.ptr);
+ break;
+ case AL_MATRIX_VAL:
+ /* XXXX this is not right */
+ pvs[i].sizeOut *= pvs[i].size2Out;
+ /* fall through */
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ item = PyList_New(pvs[i].sizeOut);
+ for (j = 0; j < pvs[i].sizeOut; j++) {
+ switch (pinfo[i].elementType) {
+ case AL_INT32_ELEM:
+ case AL_RESOURCE_ELEM:
+ case AL_ENUM_ELEM:
+ PyList_SetItem(item, j, PyInt_FromLong((long) ((int *) pvs[i].value.ptr)[j]));
+ break;
+ case AL_INT64_ELEM:
+ PyList_SetItem(item, j, PyLong_FromLongLong(((long long *) pvs[i].value.ptr)[j]));
+ break;
+ case AL_FIXED_ELEM:
+ PyList_SetItem(item, j, PyFloat_FromDouble(alFixedToDouble(((long long *) pvs[i].value.ptr)[j])));
+ break;
+ default:
+ PyErr_SetString(ErrorObject, "internal error");
+ goto error;
+ }
+ }
+ PyMem_DEL(pvs[i].value.ptr);
+ break;
+ case AL_SCALAR_VAL:
+ item = param2python(resource, pvs[i].param, pvs[i].value, &pinfo[i]);
+ break;
+ }
+ if (PyErr_Occurred() ||
+ PyList_SetItem(v, i, Py_BuildValue("(iO)", pvs[i].param,
+ item)) < 0 ||
+ PyErr_Occurred())
+ goto error;
+ Py_DECREF(item);
+ }
+ PyMem_DEL(pvs);
+ PyMem_DEL(pinfo);
+ return v;
error:
- Py_XDECREF(v);
- Py_XDECREF(item);
- if (pvs)
- PyMem_DEL(pvs);
- if (pinfo)
- PyMem_DEL(pinfo);
- return NULL;
+ Py_XDECREF(v);
+ Py_XDECREF(item);
+ if (pvs)
+ PyMem_DEL(pvs);
+ if (pinfo)
+ PyMem_DEL(pinfo);
+ return NULL;
}
PyDoc_STRVAR(al_SetParams__doc__,
@@ -1559,43 +1559,43 @@ PyDoc_STRVAR(al_SetParams__doc__,
static PyObject *
al_SetParams(PyObject *self, PyObject *args)
{
- int resource;
- PyObject *pvslist;
- ALpv *pvs;
- ALparamInfo *pinfo;
- int npvs, i;
-
- if (!PyArg_ParseTuple(args, "iO!:SetParams", &resource, &PyList_Type, &pvslist))
- return NULL;
- npvs = python2params(resource, -1, pvslist, &pvs, &pinfo);
- if (npvs < 0)
- return NULL;
-
- if (alSetParams(resource, pvs, npvs) < 0)
- goto error;
-
- /* cleanup */
- for (i = 0; i < npvs; i++) {
- switch (pinfo[i].valueType) {
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- PyMem_DEL(pvs[i].value.ptr);
- break;
- }
- }
- PyMem_DEL(pvs);
- PyMem_DEL(pinfo);
-
- Py_INCREF(Py_None);
- return Py_None;
+ int resource;
+ PyObject *pvslist;
+ ALpv *pvs;
+ ALparamInfo *pinfo;
+ int npvs, i;
+
+ if (!PyArg_ParseTuple(args, "iO!:SetParams", &resource, &PyList_Type, &pvslist))
+ return NULL;
+ npvs = python2params(resource, -1, pvslist, &pvs, &pinfo);
+ if (npvs < 0)
+ return NULL;
+
+ if (alSetParams(resource, pvs, npvs) < 0)
+ goto error;
+
+ /* cleanup */
+ for (i = 0; i < npvs; i++) {
+ switch (pinfo[i].valueType) {
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ PyMem_DEL(pvs[i].value.ptr);
+ break;
+ }
+ }
+ PyMem_DEL(pvs);
+ PyMem_DEL(pinfo);
+
+ Py_INCREF(Py_None);
+ return Py_None;
error:
- /* XXXX we should clean up everything */
- if (pvs)
- PyMem_DEL(pvs);
- if (pinfo)
- PyMem_DEL(pinfo);
- return NULL;
+ /* XXXX we should clean up everything */
+ if (pvs)
+ PyMem_DEL(pvs);
+ if (pinfo)
+ PyMem_DEL(pinfo);
+ return NULL;
}
PyDoc_STRVAR(al_QueryValues__doc__,
@@ -1604,79 +1604,79 @@ PyDoc_STRVAR(al_QueryValues__doc__,
static PyObject *
al_QueryValues(PyObject *self, PyObject *args)
{
- int resource, param;
- ALvalue *return_set = NULL;
- int setsize = 32, qualsize = 0, nvals, i;
- ALpv *quals = NULL;
- ALparamInfo pinfo;
- ALparamInfo *qualinfo = NULL;
- PyObject *qualobj = NULL;
- PyObject *res = NULL, *item;
-
- if (!PyArg_ParseTuple(args, "ii|O!:QueryValues", &resource, &param,
- &PyList_Type, &qualobj))
- return NULL;
- if (qualobj != NULL) {
- qualsize = python2params(resource, param, qualobj, &quals, &qualinfo);
- if (qualsize < 0)
- return NULL;
- }
- setsize = 32;
- return_set = PyMem_NEW(ALvalue, setsize);
- if (return_set == NULL) {
- PyErr_NoMemory();
- goto cleanup;
- }
+ int resource, param;
+ ALvalue *return_set = NULL;
+ int setsize = 32, qualsize = 0, nvals, i;
+ ALpv *quals = NULL;
+ ALparamInfo pinfo;
+ ALparamInfo *qualinfo = NULL;
+ PyObject *qualobj = NULL;
+ PyObject *res = NULL, *item;
+
+ if (!PyArg_ParseTuple(args, "ii|O!:QueryValues", &resource, &param,
+ &PyList_Type, &qualobj))
+ return NULL;
+ if (qualobj != NULL) {
+ qualsize = python2params(resource, param, qualobj, &quals, &qualinfo);
+ if (qualsize < 0)
+ return NULL;
+ }
+ setsize = 32;
+ return_set = PyMem_NEW(ALvalue, setsize);
+ if (return_set == NULL) {
+ PyErr_NoMemory();
+ goto cleanup;
+ }
retry:
- nvals = alQueryValues(resource, param, return_set, setsize, quals, qualsize);
- if (nvals < 0)
- goto cleanup;
- if (nvals > setsize) {
- ALvalue *old_return_set = return_set;
- setsize = nvals;
- PyMem_RESIZE(return_set, ALvalue, setsize);
- if (return_set == NULL) {
- return_set = old_return_set;
- PyErr_NoMemory();
- goto cleanup;
- }
- goto retry;
- }
-
- if (alGetParamInfo(resource, param, &pinfo) < 0)
- goto cleanup;
-
- res = PyList_New(nvals);
- if (res == NULL)
- goto cleanup;
- for (i = 0; i < nvals; i++) {
- item = param2python(resource, param, return_set[i], &pinfo);
- if (item == NULL ||
- PyList_SetItem(res, i, item) < 0) {
- Py_DECREF(res);
- res = NULL;
- goto cleanup;
- }
- }
+ nvals = alQueryValues(resource, param, return_set, setsize, quals, qualsize);
+ if (nvals < 0)
+ goto cleanup;
+ if (nvals > setsize) {
+ ALvalue *old_return_set = return_set;
+ setsize = nvals;
+ PyMem_RESIZE(return_set, ALvalue, setsize);
+ if (return_set == NULL) {
+ return_set = old_return_set;
+ PyErr_NoMemory();
+ goto cleanup;
+ }
+ goto retry;
+ }
+
+ if (alGetParamInfo(resource, param, &pinfo) < 0)
+ goto cleanup;
+
+ res = PyList_New(nvals);
+ if (res == NULL)
+ goto cleanup;
+ for (i = 0; i < nvals; i++) {
+ item = param2python(resource, param, return_set[i], &pinfo);
+ if (item == NULL ||
+ PyList_SetItem(res, i, item) < 0) {
+ Py_DECREF(res);
+ res = NULL;
+ goto cleanup;
+ }
+ }
cleanup:
- if (return_set)
- PyMem_DEL(return_set);
- if (quals) {
- for (i = 0; i < qualsize; i++) {
- switch (qualinfo[i].valueType) {
- case AL_SET_VAL:
- case AL_VECTOR_VAL:
- PyMem_DEL(quals[i].value.ptr);
- break;
- }
- }
- PyMem_DEL(quals);
- PyMem_DEL(qualinfo);
- }
-
- return res;
+ if (return_set)
+ PyMem_DEL(return_set);
+ if (quals) {
+ for (i = 0; i < qualsize; i++) {
+ switch (qualinfo[i].valueType) {
+ case AL_SET_VAL:
+ case AL_VECTOR_VAL:
+ PyMem_DEL(quals[i].value.ptr);
+ break;
+ }
+ }
+ PyMem_DEL(quals);
+ PyMem_DEL(qualinfo);
+ }
+
+ return res;
}
PyDoc_STRVAR(al_GetParamInfo__doc__,
@@ -1686,81 +1686,81 @@ PyDoc_STRVAR(al_GetParamInfo__doc__,
static PyObject *
al_GetParamInfo(PyObject *self, PyObject *args)
{
- int res, param;
- ALparamInfo pinfo;
- PyObject *v, *item;
-
- if (!PyArg_ParseTuple(args, "ii:GetParamInfo", &res, &param))
- return NULL;
- if (alGetParamInfo(res, param, &pinfo) < 0)
- return NULL;
- v = PyDict_New();
- if (!v) return NULL;
-
- item = PyInt_FromLong((long) pinfo.resource);
- PyDict_SetItemString(v, "resource", item);
- Py_DECREF(item);
-
- item = PyInt_FromLong((long) pinfo.param);
- PyDict_SetItemString(v, "param", item);
- Py_DECREF(item);
-
- item = PyInt_FromLong((long) pinfo.valueType);
- PyDict_SetItemString(v, "valueType", item);
- Py_DECREF(item);
-
- if (pinfo.valueType != AL_NO_VAL && pinfo.valueType != AL_SCALAR_VAL) {
- /* multiple values */
- item = PyInt_FromLong((long) pinfo.maxElems);
- PyDict_SetItemString(v, "maxElems", item);
- Py_DECREF(item);
-
- if (pinfo.valueType == AL_MATRIX_VAL) {
- /* 2 dimensional */
- item = PyInt_FromLong((long) pinfo.maxElems2);
- PyDict_SetItemString(v, "maxElems2", item);
- Py_DECREF(item);
- }
- }
-
- item = PyInt_FromLong((long) pinfo.elementType);
- PyDict_SetItemString(v, "elementType", item);
- Py_DECREF(item);
-
- item = PyString_FromString(pinfo.name);
- PyDict_SetItemString(v, "name", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.initial, &pinfo);
- PyDict_SetItemString(v, "initial", item);
- Py_DECREF(item);
-
- if (pinfo.elementType != AL_ENUM_ELEM &&
- pinfo.elementType != AL_RESOURCE_ELEM &&
- pinfo.elementType != AL_CHAR_ELEM) {
- /* range param */
- item = param2python(res, param, pinfo.min, &pinfo);
- PyDict_SetItemString(v, "min", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.max, &pinfo);
- PyDict_SetItemString(v, "max", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.minDelta, &pinfo);
- PyDict_SetItemString(v, "minDelta", item);
- Py_DECREF(item);
-
- item = param2python(res, param, pinfo.maxDelta, &pinfo);
- PyDict_SetItemString(v, "maxDelta", item);
- Py_DECREF(item);
-
- item = PyInt_FromLong((long) pinfo.specialVals);
- PyDict_SetItemString(v, "specialVals", item);
- Py_DECREF(item);
- }
-
- return v;
+ int res, param;
+ ALparamInfo pinfo;
+ PyObject *v, *item;
+
+ if (!PyArg_ParseTuple(args, "ii:GetParamInfo", &res, &param))
+ return NULL;
+ if (alGetParamInfo(res, param, &pinfo) < 0)
+ return NULL;
+ v = PyDict_New();
+ if (!v) return NULL;
+
+ item = PyInt_FromLong((long) pinfo.resource);
+ PyDict_SetItemString(v, "resource", item);
+ Py_DECREF(item);
+
+ item = PyInt_FromLong((long) pinfo.param);
+ PyDict_SetItemString(v, "param", item);
+ Py_DECREF(item);
+
+ item = PyInt_FromLong((long) pinfo.valueType);
+ PyDict_SetItemString(v, "valueType", item);
+ Py_DECREF(item);
+
+ if (pinfo.valueType != AL_NO_VAL && pinfo.valueType != AL_SCALAR_VAL) {
+ /* multiple values */
+ item = PyInt_FromLong((long) pinfo.maxElems);
+ PyDict_SetItemString(v, "maxElems", item);
+ Py_DECREF(item);
+
+ if (pinfo.valueType == AL_MATRIX_VAL) {
+ /* 2 dimensional */
+ item = PyInt_FromLong((long) pinfo.maxElems2);
+ PyDict_SetItemString(v, "maxElems2", item);
+ Py_DECREF(item);
+ }
+ }
+
+ item = PyInt_FromLong((long) pinfo.elementType);
+ PyDict_SetItemString(v, "elementType", item);
+ Py_DECREF(item);
+
+ item = PyString_FromString(pinfo.name);
+ PyDict_SetItemString(v, "name", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.initial, &pinfo);
+ PyDict_SetItemString(v, "initial", item);
+ Py_DECREF(item);
+
+ if (pinfo.elementType != AL_ENUM_ELEM &&
+ pinfo.elementType != AL_RESOURCE_ELEM &&
+ pinfo.elementType != AL_CHAR_ELEM) {
+ /* range param */
+ item = param2python(res, param, pinfo.min, &pinfo);
+ PyDict_SetItemString(v, "min", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.max, &pinfo);
+ PyDict_SetItemString(v, "max", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.minDelta, &pinfo);
+ PyDict_SetItemString(v, "minDelta", item);
+ Py_DECREF(item);
+
+ item = param2python(res, param, pinfo.maxDelta, &pinfo);
+ PyDict_SetItemString(v, "maxDelta", item);
+ Py_DECREF(item);
+
+ item = PyInt_FromLong((long) pinfo.specialVals);
+ PyDict_SetItemString(v, "specialVals", item);
+ Py_DECREF(item);
+ }
+
+ return v;
}
PyDoc_STRVAR(al_GetResourceByName__doc__,
@@ -1769,14 +1769,14 @@ PyDoc_STRVAR(al_GetResourceByName__doc__,
static PyObject *
al_GetResourceByName(PyObject *self, PyObject *args)
{
- int res, start_res, type;
- char *name;
+ int res, start_res, type;
+ char *name;
- if (!PyArg_ParseTuple(args, "isi:GetResourceByName", &start_res, &name, &type))
- return NULL;
- if ((res = alGetResourceByName(start_res, name, type)) == 0)
- return NULL;
- return PyInt_FromLong((long) res);
+ if (!PyArg_ParseTuple(args, "isi:GetResourceByName", &start_res, &name, &type))
+ return NULL;
+ if ((res = alGetResourceByName(start_res, name, type)) == 0)
+ return NULL;
+ return PyInt_FromLong((long) res);
}
PyDoc_STRVAR(al_IsSubtype__doc__,
@@ -1785,11 +1785,11 @@ PyDoc_STRVAR(al_IsSubtype__doc__,
static PyObject *
al_IsSubtype(PyObject *self, PyObject *args)
{
- int type, subtype;
+ int type, subtype;
- if (!PyArg_ParseTuple(args, "ii:IsSubtype", &type, &subtype))
- return NULL;
- return PyInt_FromLong((long) alIsSubtype(type, subtype));
+ if (!PyArg_ParseTuple(args, "ii:IsSubtype", &type, &subtype))
+ return NULL;
+ return PyInt_FromLong((long) alIsSubtype(type, subtype));
}
PyDoc_STRVAR(al_SetErrorHandler__doc__, "");
@@ -1798,10 +1798,10 @@ static PyObject *
al_SetErrorHandler(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":SetErrorHandler"))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":SetErrorHandler"))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* AL_NO_ELEM */
@@ -1811,144 +1811,144 @@ al_SetErrorHandler(PyObject *self, PyObject *args)
static PyObject *
al_openport(PyObject *self, PyObject *args)
{
- char *name, *dir;
- ALport port;
- alcobject *config = NULL;
+ char *name, *dir;
+ ALport port;
+ alcobject *config = NULL;
- if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
- return NULL;
- if ((port = ALopenport(name, dir, config ? config->config : NULL)) == NULL)
- return NULL;
- return newalpobject(port);
+ if (!PyArg_ParseTuple(args, "ss|O!:OpenPort", &name, &dir, &Alctype, &config))
+ return NULL;
+ if ((port = ALopenport(name, dir, config ? config->config : NULL)) == NULL)
+ return NULL;
+ return newalpobject(port);
}
static PyObject *
al_newconfig(PyObject *self, PyObject *args)
{
- ALconfig config;
+ ALconfig config;
- if (!PyArg_ParseTuple(args, ":NewConfig"))
- return NULL;
- if ((config = ALnewconfig ()) == NULL)
- return NULL;
- return newalcobject(config);
+ if (!PyArg_ParseTuple(args, ":NewConfig"))
+ return NULL;
+ if ((config = ALnewconfig ()) == NULL)
+ return NULL;
+ return newalcobject(config);
}
static PyObject *
al_queryparams(PyObject *self, PyObject *args)
{
- long device;
- long length;
- long *PVbuffer;
- long PVdummy[2];
- PyObject *v = NULL;
- int i;
-
- if (!PyArg_ParseTuple(args, "l:queryparams", &device))
- return NULL;
- if ((length = ALqueryparams(device, PVdummy, 2L)) == -1)
- return NULL;
- if ((PVbuffer = PyMem_NEW(long, length)) == NULL)
- return PyErr_NoMemory();
- if (ALqueryparams(device, PVbuffer, length) >= 0 &&
- (v = PyList_New((int)length)) != NULL) {
- for (i = 0; i < length; i++)
- PyList_SetItem(v, i, PyInt_FromLong(PVbuffer[i]));
- }
- PyMem_DEL(PVbuffer);
- return v;
+ long device;
+ long length;
+ long *PVbuffer;
+ long PVdummy[2];
+ PyObject *v = NULL;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "l:queryparams", &device))
+ return NULL;
+ if ((length = ALqueryparams(device, PVdummy, 2L)) == -1)
+ return NULL;
+ if ((PVbuffer = PyMem_NEW(long, length)) == NULL)
+ return PyErr_NoMemory();
+ if (ALqueryparams(device, PVbuffer, length) >= 0 &&
+ (v = PyList_New((int)length)) != NULL) {
+ for (i = 0; i < length; i++)
+ PyList_SetItem(v, i, PyInt_FromLong(PVbuffer[i]));
+ }
+ PyMem_DEL(PVbuffer);
+ return v;
}
static PyObject *
doParams(PyObject *args, int (*func)(long, long *, long), int modified)
{
- long device;
- PyObject *list, *v;
- long *PVbuffer;
- long length;
- int i;
-
- if (!PyArg_ParseTuple(args, "lO!", &device, &PyList_Type, &list))
- return NULL;
- length = PyList_Size(list);
- PVbuffer = PyMem_NEW(long, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
- for (i = 0; i < length; i++) {
- v = PyList_GetItem(list, i);
- if (!PyInt_Check(v)) {
- PyMem_DEL(PVbuffer);
- PyErr_BadArgument();
- return NULL;
- }
- PVbuffer[i] = PyInt_AsLong(v);
- }
-
- if ((*func)(device, PVbuffer, length) == -1) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- if (modified) {
- for (i = 0; i < length; i++)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
- }
-
- PyMem_DEL(PVbuffer);
-
- Py_INCREF(Py_None);
- return Py_None;
+ long device;
+ PyObject *list, *v;
+ long *PVbuffer;
+ long length;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "lO!", &device, &PyList_Type, &list))
+ return NULL;
+ length = PyList_Size(list);
+ PVbuffer = PyMem_NEW(long, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+ for (i = 0; i < length; i++) {
+ v = PyList_GetItem(list, i);
+ if (!PyInt_Check(v)) {
+ PyMem_DEL(PVbuffer);
+ PyErr_BadArgument();
+ return NULL;
+ }
+ PVbuffer[i] = PyInt_AsLong(v);
+ }
+
+ if ((*func)(device, PVbuffer, length) == -1) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ if (modified) {
+ for (i = 0; i < length; i++)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
al_getparams(PyObject *self, PyObject *args)
{
- return doParams(args, ALgetparams, 1);
+ return doParams(args, ALgetparams, 1);
}
static PyObject *
al_setparams(PyObject *self, PyObject *args)
{
- return doParams(args, ALsetparams, 0);
+ return doParams(args, ALsetparams, 0);
}
static PyObject *
al_getname(PyObject *self, PyObject *args)
{
- long device, descriptor;
- char *name;
+ long device, descriptor;
+ char *name;
- if (!PyArg_ParseTuple(args, "ll:getname", &device, &descriptor))
- return NULL;
- if ((name = ALgetname(device, descriptor)) == NULL)
- return NULL;
- return PyString_FromString(name);
+ if (!PyArg_ParseTuple(args, "ll:getname", &device, &descriptor))
+ return NULL;
+ if ((name = ALgetname(device, descriptor)) == NULL)
+ return NULL;
+ return PyString_FromString(name);
}
static PyObject *
al_getdefault(PyObject *self, PyObject *args)
{
- long device, descriptor, value;
+ long device, descriptor, value;
- if (!PyArg_ParseTuple(args, "ll:getdefault", &device, &descriptor))
- return NULL;
- if ((value = ALgetdefault(device, descriptor)) == -1)
- return NULL;
- return PyLong_FromLong(value);
+ if (!PyArg_ParseTuple(args, "ll:getdefault", &device, &descriptor))
+ return NULL;
+ if ((value = ALgetdefault(device, descriptor)) == -1)
+ return NULL;
+ return PyLong_FromLong(value);
}
static PyObject *
al_getminmax(PyObject *self, PyObject *args)
{
- long device, descriptor, min, max;
+ long device, descriptor, min, max;
- if (!PyArg_ParseTuple(args, "ll:getminmax", &device, &descriptor))
- return NULL;
- min = -1;
- max = -1;
- if (ALgetminmax(device, descriptor, &min, &max) == -1)
- return NULL;
- return Py_BuildValue("ll", min, max);
+ if (!PyArg_ParseTuple(args, "ll:getminmax", &device, &descriptor))
+ return NULL;
+ min = -1;
+ max = -1;
+ if (ALgetminmax(device, descriptor, &min, &max) == -1)
+ return NULL;
+ return Py_BuildValue("ll", min, max);
}
#endif /* OLD_INTERFACE */
@@ -1956,34 +1956,34 @@ al_getminmax(PyObject *self, PyObject *args)
/* List of methods defined in the module */
static struct PyMethodDef al_methods[] = {
-#ifdef AL_NO_ELEM /* IRIX 6 */
- {"NewConfig", (PyCFunction)al_NewConfig, METH_VARARGS, al_NewConfig__doc__},
- {"OpenPort", (PyCFunction)al_OpenPort, METH_VARARGS, al_OpenPort__doc__},
- {"Connect", (PyCFunction)al_Connect, METH_VARARGS, al_Connect__doc__},
- {"Disconnect", (PyCFunction)al_Disconnect, METH_VARARGS, al_Disconnect__doc__},
- {"GetParams", (PyCFunction)al_GetParams, METH_VARARGS, al_GetParams__doc__},
- {"SetParams", (PyCFunction)al_SetParams, METH_VARARGS, al_SetParams__doc__},
- {"QueryValues", (PyCFunction)al_QueryValues, METH_VARARGS, al_QueryValues__doc__},
- {"GetParamInfo", (PyCFunction)al_GetParamInfo, METH_VARARGS, al_GetParamInfo__doc__},
- {"GetResourceByName", (PyCFunction)al_GetResourceByName, METH_VARARGS, al_GetResourceByName__doc__},
- {"IsSubtype", (PyCFunction)al_IsSubtype, METH_VARARGS, al_IsSubtype__doc__},
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ {"NewConfig", (PyCFunction)al_NewConfig, METH_VARARGS, al_NewConfig__doc__},
+ {"OpenPort", (PyCFunction)al_OpenPort, METH_VARARGS, al_OpenPort__doc__},
+ {"Connect", (PyCFunction)al_Connect, METH_VARARGS, al_Connect__doc__},
+ {"Disconnect", (PyCFunction)al_Disconnect, METH_VARARGS, al_Disconnect__doc__},
+ {"GetParams", (PyCFunction)al_GetParams, METH_VARARGS, al_GetParams__doc__},
+ {"SetParams", (PyCFunction)al_SetParams, METH_VARARGS, al_SetParams__doc__},
+ {"QueryValues", (PyCFunction)al_QueryValues, METH_VARARGS, al_QueryValues__doc__},
+ {"GetParamInfo", (PyCFunction)al_GetParamInfo, METH_VARARGS, al_GetParamInfo__doc__},
+ {"GetResourceByName", (PyCFunction)al_GetResourceByName, METH_VARARGS, al_GetResourceByName__doc__},
+ {"IsSubtype", (PyCFunction)al_IsSubtype, METH_VARARGS, al_IsSubtype__doc__},
#if 0
- /* this one not supported */
- {"SetErrorHandler", (PyCFunction)al_SetErrorHandler, METH_VARARGS, al_SetErrorHandler__doc__},
+ /* this one not supported */
+ {"SetErrorHandler", (PyCFunction)al_SetErrorHandler, METH_VARARGS, al_SetErrorHandler__doc__},
#endif
#endif /* AL_NO_ELEM */
#ifdef OLD_INTERFACE
- {"openport", (PyCFunction)al_openport, METH_VARARGS},
- {"newconfig", (PyCFunction)al_newconfig, METH_VARARGS},
- {"queryparams", (PyCFunction)al_queryparams, METH_VARARGS},
- {"getparams", (PyCFunction)al_getparams, METH_VARARGS},
- {"setparams", (PyCFunction)al_setparams, METH_VARARGS},
- {"getname", (PyCFunction)al_getname, METH_VARARGS},
- {"getdefault", (PyCFunction)al_getdefault, METH_VARARGS},
- {"getminmax", (PyCFunction)al_getminmax, METH_VARARGS},
+ {"openport", (PyCFunction)al_openport, METH_VARARGS},
+ {"newconfig", (PyCFunction)al_newconfig, METH_VARARGS},
+ {"queryparams", (PyCFunction)al_queryparams, METH_VARARGS},
+ {"getparams", (PyCFunction)al_getparams, METH_VARARGS},
+ {"setparams", (PyCFunction)al_setparams, METH_VARARGS},
+ {"getname", (PyCFunction)al_getname, METH_VARARGS},
+ {"getdefault", (PyCFunction)al_getdefault, METH_VARARGS},
+ {"getminmax", (PyCFunction)al_getminmax, METH_VARARGS},
#endif /* OLD_INTERFACE */
- {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
+ {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
@@ -1994,1239 +1994,1239 @@ PyDoc_STRVAR(al_module_documentation, "");
void
inital(void)
{
- PyObject *m, *d, *x;
+ PyObject *m, *d, *x;
- if (PyErr_WarnPy3k("the al module has been removed in "
- "Python 3.0", 2) < 0)
- return;
+ if (PyErr_WarnPy3k("the al module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
- /* Create the module and add the functions */
- m = Py_InitModule4("al", al_methods,
- al_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
- if (m == NULL)
- return;
+ /* Create the module and add the functions */
+ m = Py_InitModule4("al", al_methods,
+ al_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- ErrorObject = PyErr_NewException("al.error", NULL, NULL);
- PyDict_SetItemString(d, "error", ErrorObject);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ ErrorObject = PyErr_NewException("al.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", ErrorObject);
- /* XXXX Add constants here */
+ /* XXXX Add constants here */
#ifdef AL_4CHANNEL
- x = PyInt_FromLong((long) AL_4CHANNEL);
- if (x == NULL || PyDict_SetItemString(d, "FOURCHANNEL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_4CHANNEL);
+ if (x == NULL || PyDict_SetItemString(d, "FOURCHANNEL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ADAT_IF_TYPE
- x = PyInt_FromLong((long) AL_ADAT_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ADAT_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ADAT_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ADAT_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ADAT_MCLK_TYPE
- x = PyInt_FromLong((long) AL_ADAT_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ADAT_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ADAT_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ADAT_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_AES_IF_TYPE
- x = PyInt_FromLong((long) AL_AES_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "AES_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_AES_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "AES_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_AES_MCLK_TYPE
- x = PyInt_FromLong((long) AL_AES_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "AES_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_AES_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "AES_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ANALOG_IF_TYPE
- x = PyInt_FromLong((long) AL_ANALOG_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ANALOG_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ANALOG_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ANALOG_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ASSOCIATE
- x = PyInt_FromLong((long) AL_ASSOCIATE);
- if (x == NULL || PyDict_SetItemString(d, "ASSOCIATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ASSOCIATE);
+ if (x == NULL || PyDict_SetItemString(d, "ASSOCIATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFER_NULL
- x = PyInt_FromLong((long) AL_BAD_BUFFER_NULL);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_NULL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFER_NULL);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_NULL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFERLENGTH
- x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFERLENGTH_NEG
- x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_NEG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_NEG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_BUFFERLENGTH_ODD
- x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_ODD);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_BUFFERLENGTH_ODD);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_CHANNELS
- x = PyInt_FromLong((long) AL_BAD_CHANNELS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_CHANNELS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_CHANNELS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_CHANNELS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_CONFIG
- x = PyInt_FromLong((long) AL_BAD_CONFIG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_CONFIG", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_CONFIG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_CONFIG", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_COUNT_NEG
- x = PyInt_FromLong((long) AL_BAD_COUNT_NEG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COUNT_NEG", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_COUNT_NEG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COUNT_NEG", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_DEVICE
- x = PyInt_FromLong((long) AL_BAD_DEVICE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_DEVICE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_DEVICE_ACCESS
- x = PyInt_FromLong((long) AL_BAD_DEVICE_ACCESS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE_ACCESS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_DEVICE_ACCESS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_DEVICE_ACCESS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_DIRECTION
- x = PyInt_FromLong((long) AL_BAD_DIRECTION);
- if (x == NULL || PyDict_SetItemString(d, "BAD_DIRECTION", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_DIRECTION);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_DIRECTION", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_FILLPOINT
- x = PyInt_FromLong((long) AL_BAD_FILLPOINT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FILLPOINT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_FILLPOINT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FILLPOINT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_FLOATMAX
- x = PyInt_FromLong((long) AL_BAD_FLOATMAX);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FLOATMAX", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_FLOATMAX);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FLOATMAX", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_ILLEGAL_STATE
- x = PyInt_FromLong((long) AL_BAD_ILLEGAL_STATE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_ILLEGAL_STATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_ILLEGAL_STATE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_ILLEGAL_STATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_NO_PORTS
- x = PyInt_FromLong((long) AL_BAD_NO_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NO_PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_NO_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NO_PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_NOT_FOUND
- x = PyInt_FromLong((long) AL_BAD_NOT_FOUND);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_FOUND", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_NOT_FOUND);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_FOUND", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_NOT_IMPLEMENTED
- x = PyInt_FromLong((long) AL_BAD_NOT_IMPLEMENTED);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_IMPLEMENTED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_NOT_IMPLEMENTED);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NOT_IMPLEMENTED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_OUT_OF_MEM
- x = PyInt_FromLong((long) AL_BAD_OUT_OF_MEM);
- if (x == NULL || PyDict_SetItemString(d, "BAD_OUT_OF_MEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_OUT_OF_MEM);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_OUT_OF_MEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PARAM
- x = PyInt_FromLong((long) AL_BAD_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PERMISSIONS
- x = PyInt_FromLong((long) AL_BAD_PERMISSIONS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PERMISSIONS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PERMISSIONS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PERMISSIONS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PORT
- x = PyInt_FromLong((long) AL_BAD_PORT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PORT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PORT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PORT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PORTSTYLE
- x = PyInt_FromLong((long) AL_BAD_PORTSTYLE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PORTSTYLE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PORTSTYLE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PORTSTYLE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_PVBUFFER
- x = PyInt_FromLong((long) AL_BAD_PVBUFFER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_PVBUFFER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_QSIZE
- x = PyInt_FromLong((long) AL_BAD_QSIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_QSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_QSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_QSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_RATE
- x = PyInt_FromLong((long) AL_BAD_RATE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_RESOURCE
- x = PyInt_FromLong((long) AL_BAD_RESOURCE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_RESOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_RESOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_RESOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_SAMPFMT
- x = PyInt_FromLong((long) AL_BAD_SAMPFMT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_SAMPFMT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_SAMPFMT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_SAMPFMT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_TRANSFER_SIZE
- x = PyInt_FromLong((long) AL_BAD_TRANSFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_TRANSFER_SIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_TRANSFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_TRANSFER_SIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_BAD_WIDTH
- x = PyInt_FromLong((long) AL_BAD_WIDTH);
- if (x == NULL || PyDict_SetItemString(d, "BAD_WIDTH", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_BAD_WIDTH);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_WIDTH", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CHANNEL_MODE
- x = PyInt_FromLong((long) AL_CHANNEL_MODE);
- if (x == NULL || PyDict_SetItemString(d, "CHANNEL_MODE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CHANNEL_MODE);
+ if (x == NULL || PyDict_SetItemString(d, "CHANNEL_MODE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CHANNELS
- x = PyInt_FromLong((long) AL_CHANNELS);
- if (x == NULL || PyDict_SetItemString(d, "CHANNELS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CHANNELS);
+ if (x == NULL || PyDict_SetItemString(d, "CHANNELS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CHAR_ELEM
- x = PyInt_FromLong((long) AL_CHAR_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "CHAR_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CHAR_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "CHAR_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CLOCK_GEN
- x = PyInt_FromLong((long) AL_CLOCK_GEN);
- if (x == NULL || PyDict_SetItemString(d, "CLOCK_GEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CLOCK_GEN);
+ if (x == NULL || PyDict_SetItemString(d, "CLOCK_GEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CLOCKGEN_TYPE
- x = PyInt_FromLong((long) AL_CLOCKGEN_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "CLOCKGEN_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CLOCKGEN_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "CLOCKGEN_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CONNECT
- x = PyInt_FromLong((long) AL_CONNECT);
- if (x == NULL || PyDict_SetItemString(d, "CONNECT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CONNECT);
+ if (x == NULL || PyDict_SetItemString(d, "CONNECT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CONNECTION_TYPE
- x = PyInt_FromLong((long) AL_CONNECTION_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "CONNECTION_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CONNECTION_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "CONNECTION_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CONNECTIONS
- x = PyInt_FromLong((long) AL_CONNECTIONS);
- if (x == NULL || PyDict_SetItemString(d, "CONNECTIONS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CONNECTIONS);
+ if (x == NULL || PyDict_SetItemString(d, "CONNECTIONS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_CRYSTAL_MCLK_TYPE
- x = PyInt_FromLong((long) AL_CRYSTAL_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "CRYSTAL_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_CRYSTAL_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "CRYSTAL_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEFAULT_DEVICE
- x = PyInt_FromLong((long) AL_DEFAULT_DEVICE);
- if (x == NULL || PyDict_SetItemString(d, "DEFAULT_DEVICE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEFAULT_DEVICE);
+ if (x == NULL || PyDict_SetItemString(d, "DEFAULT_DEVICE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEFAULT_INPUT
- x = PyInt_FromLong((long) AL_DEFAULT_INPUT);
- if (x == NULL || PyDict_SetItemString(d, "DEFAULT_INPUT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEFAULT_INPUT);
+ if (x == NULL || PyDict_SetItemString(d, "DEFAULT_INPUT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEFAULT_OUTPUT
- x = PyInt_FromLong((long) AL_DEFAULT_OUTPUT);
- if (x == NULL || PyDict_SetItemString(d, "DEFAULT_OUTPUT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEFAULT_OUTPUT);
+ if (x == NULL || PyDict_SetItemString(d, "DEFAULT_OUTPUT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEST
- x = PyInt_FromLong((long) AL_DEST);
- if (x == NULL || PyDict_SetItemString(d, "DEST", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEST);
+ if (x == NULL || PyDict_SetItemString(d, "DEST", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEVICE_TYPE
- x = PyInt_FromLong((long) AL_DEVICE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "DEVICE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEVICE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "DEVICE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DEVICES
- x = PyInt_FromLong((long) AL_DEVICES);
- if (x == NULL || PyDict_SetItemString(d, "DEVICES", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DEVICES);
+ if (x == NULL || PyDict_SetItemString(d, "DEVICES", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DIGITAL_IF_TYPE
- x = PyInt_FromLong((long) AL_DIGITAL_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "DIGITAL_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DIGITAL_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "DIGITAL_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DIGITAL_INPUT_RATE
- x = PyInt_FromLong((long) AL_DIGITAL_INPUT_RATE);
- if (x == NULL || PyDict_SetItemString(d, "DIGITAL_INPUT_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DIGITAL_INPUT_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "DIGITAL_INPUT_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_DISCONNECT
- x = PyInt_FromLong((long) AL_DISCONNECT);
- if (x == NULL || PyDict_SetItemString(d, "DISCONNECT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_DISCONNECT);
+ if (x == NULL || PyDict_SetItemString(d, "DISCONNECT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ENUM_ELEM
- x = PyInt_FromLong((long) AL_ENUM_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "ENUM_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ENUM_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "ENUM_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ENUM_VALUE
- x = PyInt_FromLong((long) AL_ENUM_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ENUM_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_INPUT_OVERFLOW
- x = PyInt_FromLong((long) AL_ERROR_INPUT_OVERFLOW);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_INPUT_OVERFLOW", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_INPUT_OVERFLOW);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_INPUT_OVERFLOW", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_LENGTH
- x = PyInt_FromLong((long) AL_ERROR_LENGTH);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_LENGTH", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_LENGTH);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_LENGTH", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_LOCATION_LSP
- x = PyInt_FromLong((long) AL_ERROR_LOCATION_LSP);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_LSP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_LOCATION_LSP);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_LSP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_LOCATION_MSP
- x = PyInt_FromLong((long) AL_ERROR_LOCATION_MSP);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_MSP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_LOCATION_MSP);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_LOCATION_MSP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_NUMBER
- x = PyInt_FromLong((long) AL_ERROR_NUMBER);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_NUMBER", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_NUMBER);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_NUMBER", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_OUTPUT_UNDERFLOW
- x = PyInt_FromLong((long) AL_ERROR_OUTPUT_UNDERFLOW);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_OUTPUT_UNDERFLOW", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_OUTPUT_UNDERFLOW);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_OUTPUT_UNDERFLOW", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_ERROR_TYPE
- x = PyInt_FromLong((long) AL_ERROR_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "ERROR_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_ERROR_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "ERROR_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_FIXED_ELEM
- x = PyInt_FromLong((long) AL_FIXED_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "FIXED_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_FIXED_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "FIXED_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_FIXED_MCLK_TYPE
- x = PyInt_FromLong((long) AL_FIXED_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "FIXED_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_FIXED_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "FIXED_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_GAIN
- x = PyInt_FromLong((long) AL_GAIN);
- if (x == NULL || PyDict_SetItemString(d, "GAIN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_GAIN);
+ if (x == NULL || PyDict_SetItemString(d, "GAIN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_GAIN_REF
- x = PyInt_FromLong((long) AL_GAIN_REF);
- if (x == NULL || PyDict_SetItemString(d, "GAIN_REF", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_GAIN_REF);
+ if (x == NULL || PyDict_SetItemString(d, "GAIN_REF", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_HRB_TYPE
- x = PyInt_FromLong((long) AL_HRB_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "HRB_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_HRB_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "HRB_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_COUNT
- x = PyInt_FromLong((long) AL_INPUT_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_DEVICE_TYPE
- x = PyInt_FromLong((long) AL_INPUT_DEVICE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_DEVICE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_DEVICE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_DEVICE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_DIGITAL
- x = PyInt_FromLong((long) AL_INPUT_DIGITAL);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_DIGITAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_DIGITAL);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_DIGITAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_HRB_TYPE
- x = PyInt_FromLong((long) AL_INPUT_HRB_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_HRB_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_HRB_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_HRB_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_LINE
- x = PyInt_FromLong((long) AL_INPUT_LINE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_LINE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_LINE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_LINE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_MIC
- x = PyInt_FromLong((long) AL_INPUT_MIC);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_MIC", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_MIC);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_MIC", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_PORT_TYPE
- x = PyInt_FromLong((long) AL_INPUT_PORT_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_PORT_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_PORT_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_PORT_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_RATE
- x = PyInt_FromLong((long) AL_INPUT_RATE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INPUT_SOURCE
- x = PyInt_FromLong((long) AL_INPUT_SOURCE);
- if (x == NULL || PyDict_SetItemString(d, "INPUT_SOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INPUT_SOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "INPUT_SOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INT32_ELEM
- x = PyInt_FromLong((long) AL_INT32_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "INT32_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INT32_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "INT32_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INT64_ELEM
- x = PyInt_FromLong((long) AL_INT64_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "INT64_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INT64_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "INT64_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INTERFACE
- x = PyInt_FromLong((long) AL_INTERFACE);
- if (x == NULL || PyDict_SetItemString(d, "INTERFACE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INTERFACE);
+ if (x == NULL || PyDict_SetItemString(d, "INTERFACE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INTERFACE_TYPE
- x = PyInt_FromLong((long) AL_INTERFACE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "INTERFACE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INTERFACE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "INTERFACE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INVALID_PARAM
- x = PyInt_FromLong((long) AL_INVALID_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "INVALID_PARAM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INVALID_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "INVALID_PARAM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_INVALID_VALUE
- x = PyInt_FromLong((long) AL_INVALID_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "INVALID_VALUE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_INVALID_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "INVALID_VALUE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_JITTER
- x = PyInt_FromLong((long) AL_JITTER);
- if (x == NULL || PyDict_SetItemString(d, "JITTER", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_JITTER);
+ if (x == NULL || PyDict_SetItemString(d, "JITTER", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LABEL
- x = PyInt_FromLong((long) AL_LABEL);
- if (x == NULL || PyDict_SetItemString(d, "LABEL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LABEL);
+ if (x == NULL || PyDict_SetItemString(d, "LABEL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_LEFT_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT_MONITOR_ATTEN
- x = PyInt_FromLong((long) AL_LEFT_MONITOR_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT_MONITOR_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT_MONITOR_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT_MONITOR_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT_SPEAKER_GAIN
- x = PyInt_FromLong((long) AL_LEFT_SPEAKER_GAIN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT_SPEAKER_GAIN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT_SPEAKER_GAIN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT_SPEAKER_GAIN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT1_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_LEFT1_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT1_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT1_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT1_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LEFT2_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_LEFT2_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "LEFT2_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LEFT2_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "LEFT2_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LINE_IF_TYPE
- x = PyInt_FromLong((long) AL_LINE_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "LINE_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LINE_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "LINE_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_LOCKED
- x = PyInt_FromLong((long) AL_LOCKED);
- if (x == NULL || PyDict_SetItemString(d, "LOCKED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_LOCKED);
+ if (x == NULL || PyDict_SetItemString(d, "LOCKED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MASTER_CLOCK
- x = PyInt_FromLong((long) AL_MASTER_CLOCK);
- if (x == NULL || PyDict_SetItemString(d, "MASTER_CLOCK", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MASTER_CLOCK);
+ if (x == NULL || PyDict_SetItemString(d, "MASTER_CLOCK", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MATRIX_VAL
- x = PyInt_FromLong((long) AL_MATRIX_VAL);
- if (x == NULL || PyDict_SetItemString(d, "MATRIX_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MATRIX_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "MATRIX_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_ERROR
- x = PyInt_FromLong((long) AL_MAX_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "MAX_ERROR", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_ERROR", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_EVENT_PARAM
- x = PyInt_FromLong((long) AL_MAX_EVENT_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "MAX_EVENT_PARAM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_EVENT_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_EVENT_PARAM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_PBUFSIZE
- x = PyInt_FromLong((long) AL_MAX_PBUFSIZE);
- if (x == NULL || PyDict_SetItemString(d, "MAX_PBUFSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_PBUFSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_PBUFSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_PORTS
- x = PyInt_FromLong((long) AL_MAX_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_RESOURCE_ID
- x = PyInt_FromLong((long) AL_MAX_RESOURCE_ID);
- if (x == NULL || PyDict_SetItemString(d, "MAX_RESOURCE_ID", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_RESOURCE_ID);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_RESOURCE_ID", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_SETSIZE
- x = PyInt_FromLong((long) AL_MAX_SETSIZE);
- if (x == NULL || PyDict_SetItemString(d, "MAX_SETSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_SETSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_SETSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MAX_STRLEN
- x = PyInt_FromLong((long) AL_MAX_STRLEN);
- if (x == NULL || PyDict_SetItemString(d, "MAX_STRLEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MAX_STRLEN);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_STRLEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MCLK_TYPE
- x = PyInt_FromLong((long) AL_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MIC_IF_TYPE
- x = PyInt_FromLong((long) AL_MIC_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "MIC_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MIC_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "MIC_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONITOR_CTL
- x = PyInt_FromLong((long) AL_MONITOR_CTL);
- if (x == NULL || PyDict_SetItemString(d, "MONITOR_CTL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONITOR_CTL);
+ if (x == NULL || PyDict_SetItemString(d, "MONITOR_CTL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONITOR_OFF
- x = PyInt_FromLong((long) AL_MONITOR_OFF);
- if (x == NULL || PyDict_SetItemString(d, "MONITOR_OFF", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONITOR_OFF);
+ if (x == NULL || PyDict_SetItemString(d, "MONITOR_OFF", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONITOR_ON
- x = PyInt_FromLong((long) AL_MONITOR_ON);
- if (x == NULL || PyDict_SetItemString(d, "MONITOR_ON", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONITOR_ON);
+ if (x == NULL || PyDict_SetItemString(d, "MONITOR_ON", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MONO
- x = PyInt_FromLong((long) AL_MONO);
- if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MONO);
+ if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_MUTE
- x = PyInt_FromLong((long) AL_MUTE);
- if (x == NULL || PyDict_SetItemString(d, "MUTE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_MUTE);
+ if (x == NULL || PyDict_SetItemString(d, "MUTE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NAME
- x = PyInt_FromLong((long) AL_NAME);
- if (x == NULL || PyDict_SetItemString(d, "NAME", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NAME);
+ if (x == NULL || PyDict_SetItemString(d, "NAME", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NEG_INFINITY
- x = PyInt_FromLong((long) AL_NEG_INFINITY);
- if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NEG_INFINITY);
+ if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NEG_INFINITY_BIT
- x = PyInt_FromLong((long) AL_NEG_INFINITY_BIT);
- if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NEG_INFINITY_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "NEG_INFINITY_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_CHANGE
- x = PyInt_FromLong((long) AL_NO_CHANGE);
- if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_CHANGE);
+ if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_CHANGE_BIT
- x = PyInt_FromLong((long) AL_NO_CHANGE_BIT);
- if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_CHANGE_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "NO_CHANGE_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_ELEM
- x = PyInt_FromLong((long) AL_NO_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "NO_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "NO_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_ERRORS
- x = PyInt_FromLong((long) AL_NO_ERRORS);
- if (x == NULL || PyDict_SetItemString(d, "NO_ERRORS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_ERRORS);
+ if (x == NULL || PyDict_SetItemString(d, "NO_ERRORS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_OP
- x = PyInt_FromLong((long) AL_NO_OP);
- if (x == NULL || PyDict_SetItemString(d, "NO_OP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_OP);
+ if (x == NULL || PyDict_SetItemString(d, "NO_OP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NO_VAL
- x = PyInt_FromLong((long) AL_NO_VAL);
- if (x == NULL || PyDict_SetItemString(d, "NO_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NO_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "NO_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NULL_INTERFACE
- x = PyInt_FromLong((long) AL_NULL_INTERFACE);
- if (x == NULL || PyDict_SetItemString(d, "NULL_INTERFACE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NULL_INTERFACE);
+ if (x == NULL || PyDict_SetItemString(d, "NULL_INTERFACE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_NULL_RESOURCE
- x = PyInt_FromLong((long) AL_NULL_RESOURCE);
- if (x == NULL || PyDict_SetItemString(d, "NULL_RESOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_NULL_RESOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "NULL_RESOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OPTICAL_IF_TYPE
- x = PyInt_FromLong((long) AL_OPTICAL_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OPTICAL_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OPTICAL_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OPTICAL_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_COUNT
- x = PyInt_FromLong((long) AL_OUTPUT_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_DEVICE_TYPE
- x = PyInt_FromLong((long) AL_OUTPUT_DEVICE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_DEVICE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_DEVICE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_DEVICE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_HRB_TYPE
- x = PyInt_FromLong((long) AL_OUTPUT_HRB_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_HRB_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_HRB_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_HRB_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_PORT_TYPE
- x = PyInt_FromLong((long) AL_OUTPUT_PORT_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_PORT_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_PORT_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_PORT_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_OUTPUT_RATE
- x = PyInt_FromLong((long) AL_OUTPUT_RATE);
- if (x == NULL || PyDict_SetItemString(d, "OUTPUT_RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_OUTPUT_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "OUTPUT_RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PARAM_BIT
- x = PyInt_FromLong((long) AL_PARAM_BIT);
- if (x == NULL || PyDict_SetItemString(d, "PARAM_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PARAM_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "PARAM_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PARAMS
- x = PyInt_FromLong((long) AL_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "PARAMS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "PARAMS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORT_COUNT
- x = PyInt_FromLong((long) AL_PORT_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "PORT_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORT_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "PORT_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORT_TYPE
- x = PyInt_FromLong((long) AL_PORT_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "PORT_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORT_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "PORT_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORTS
- x = PyInt_FromLong((long) AL_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORTSTYLE_DIRECT
- x = PyInt_FromLong((long) AL_PORTSTYLE_DIRECT);
- if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_DIRECT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORTSTYLE_DIRECT);
+ if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_DIRECT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PORTSTYLE_SERIAL
- x = PyInt_FromLong((long) AL_PORTSTYLE_SERIAL);
- if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_SERIAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PORTSTYLE_SERIAL);
+ if (x == NULL || PyDict_SetItemString(d, "PORTSTYLE_SERIAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PRINT_ERRORS
- x = PyInt_FromLong((long) AL_PRINT_ERRORS);
- if (x == NULL || PyDict_SetItemString(d, "PRINT_ERRORS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PRINT_ERRORS);
+ if (x == NULL || PyDict_SetItemString(d, "PRINT_ERRORS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_PTR_ELEM
- x = PyInt_FromLong((long) AL_PTR_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "PTR_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_PTR_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "PTR_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RANGE_VALUE
- x = PyInt_FromLong((long) AL_RANGE_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RANGE_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE
- x = PyInt_FromLong((long) AL_RATE);
- if (x == NULL || PyDict_SetItemString(d, "RATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "RATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_11025
- x = PyInt_FromLong((long) AL_RATE_11025);
- if (x == NULL || PyDict_SetItemString(d, "RATE_11025", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_11025);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_11025", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_16000
- x = PyInt_FromLong((long) AL_RATE_16000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_16000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_16000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_16000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_22050
- x = PyInt_FromLong((long) AL_RATE_22050);
- if (x == NULL || PyDict_SetItemString(d, "RATE_22050", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_22050);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_22050", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_32000
- x = PyInt_FromLong((long) AL_RATE_32000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_32000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_32000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_32000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_44100
- x = PyInt_FromLong((long) AL_RATE_44100);
- if (x == NULL || PyDict_SetItemString(d, "RATE_44100", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_44100);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_44100", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_48000
- x = PyInt_FromLong((long) AL_RATE_48000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_48000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_48000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_48000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_8000
- x = PyInt_FromLong((long) AL_RATE_8000);
- if (x == NULL || PyDict_SetItemString(d, "RATE_8000", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_8000);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_8000", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_1
- x = PyInt_FromLong((long) AL_RATE_AES_1);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_1);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_1s
- x = PyInt_FromLong((long) AL_RATE_AES_1s);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1s", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_1s);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_1s", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_2
- x = PyInt_FromLong((long) AL_RATE_AES_2);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_2", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_2);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_2", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_3
- x = PyInt_FromLong((long) AL_RATE_AES_3);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_3", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_3);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_3", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_4
- x = PyInt_FromLong((long) AL_RATE_AES_4);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_4", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_4);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_4", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_AES_6
- x = PyInt_FromLong((long) AL_RATE_AES_6);
- if (x == NULL || PyDict_SetItemString(d, "RATE_AES_6", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_AES_6);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_AES_6", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_FRACTION_D
- x = PyInt_FromLong((long) AL_RATE_FRACTION_D);
- if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_D", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_FRACTION_D);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_D", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_FRACTION_N
- x = PyInt_FromLong((long) AL_RATE_FRACTION_N);
- if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_N", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_FRACTION_N);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_FRACTION_N", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_INPUTRATE
- x = PyInt_FromLong((long) AL_RATE_INPUTRATE);
- if (x == NULL || PyDict_SetItemString(d, "RATE_INPUTRATE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_INPUTRATE);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_INPUTRATE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_NO_DIGITAL_INPUT
- x = PyInt_FromLong((long) AL_RATE_NO_DIGITAL_INPUT);
- if (x == NULL || PyDict_SetItemString(d, "RATE_NO_DIGITAL_INPUT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_NO_DIGITAL_INPUT);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_NO_DIGITAL_INPUT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_UNACQUIRED
- x = PyInt_FromLong((long) AL_RATE_UNACQUIRED);
- if (x == NULL || PyDict_SetItemString(d, "RATE_UNACQUIRED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_UNACQUIRED);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_UNACQUIRED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RATE_UNDEFINED
- x = PyInt_FromLong((long) AL_RATE_UNDEFINED);
- if (x == NULL || PyDict_SetItemString(d, "RATE_UNDEFINED", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RATE_UNDEFINED);
+ if (x == NULL || PyDict_SetItemString(d, "RATE_UNDEFINED", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_REF_0DBV
- x = PyInt_FromLong((long) AL_REF_0DBV);
- if (x == NULL || PyDict_SetItemString(d, "REF_0DBV", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_REF_0DBV);
+ if (x == NULL || PyDict_SetItemString(d, "REF_0DBV", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_REF_NONE
- x = PyInt_FromLong((long) AL_REF_NONE);
- if (x == NULL || PyDict_SetItemString(d, "REF_NONE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_REF_NONE);
+ if (x == NULL || PyDict_SetItemString(d, "REF_NONE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED1_TYPE
- x = PyInt_FromLong((long) AL_RESERVED1_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED1_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED1_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED1_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED2_TYPE
- x = PyInt_FromLong((long) AL_RESERVED2_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED2_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED2_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED2_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED3_TYPE
- x = PyInt_FromLong((long) AL_RESERVED3_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED3_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED3_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED3_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESERVED4_TYPE
- x = PyInt_FromLong((long) AL_RESERVED4_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESERVED4_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESERVED4_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESERVED4_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESOURCE
- x = PyInt_FromLong((long) AL_RESOURCE);
- if (x == NULL || PyDict_SetItemString(d, "RESOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "RESOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESOURCE_ELEM
- x = PyInt_FromLong((long) AL_RESOURCE_ELEM);
- if (x == NULL || PyDict_SetItemString(d, "RESOURCE_ELEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESOURCE_ELEM);
+ if (x == NULL || PyDict_SetItemString(d, "RESOURCE_ELEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RESOURCE_TYPE
- x = PyInt_FromLong((long) AL_RESOURCE_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "RESOURCE_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RESOURCE_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "RESOURCE_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT_MONITOR_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT_MONITOR_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT_MONITOR_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT_MONITOR_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT_MONITOR_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT_SPEAKER_GAIN
- x = PyInt_FromLong((long) AL_RIGHT_SPEAKER_GAIN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT_SPEAKER_GAIN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT_SPEAKER_GAIN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT_SPEAKER_GAIN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT1_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT1_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT1_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT1_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT1_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_RIGHT2_INPUT_ATTEN
- x = PyInt_FromLong((long) AL_RIGHT2_INPUT_ATTEN);
- if (x == NULL || PyDict_SetItemString(d, "RIGHT2_INPUT_ATTEN", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_RIGHT2_INPUT_ATTEN);
+ if (x == NULL || PyDict_SetItemString(d, "RIGHT2_INPUT_ATTEN", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPFMT_DOUBLE
- x = PyInt_FromLong((long) AL_SAMPFMT_DOUBLE);
- if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_DOUBLE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPFMT_DOUBLE);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_DOUBLE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPFMT_FLOAT
- x = PyInt_FromLong((long) AL_SAMPFMT_FLOAT);
- if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_FLOAT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPFMT_FLOAT);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_FLOAT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPFMT_TWOSCOMP
- x = PyInt_FromLong((long) AL_SAMPFMT_TWOSCOMP);
- if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_TWOSCOMP", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPFMT_TWOSCOMP);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPFMT_TWOSCOMP", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPLE_16
- x = PyInt_FromLong((long) AL_SAMPLE_16);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLE_16", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPLE_16);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLE_16", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPLE_24
- x = PyInt_FromLong((long) AL_SAMPLE_24);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLE_24", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPLE_24);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLE_24", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SAMPLE_8
- x = PyInt_FromLong((long) AL_SAMPLE_8);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLE_8", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SAMPLE_8);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLE_8", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SCALAR_VAL
- x = PyInt_FromLong((long) AL_SCALAR_VAL);
- if (x == NULL || PyDict_SetItemString(d, "SCALAR_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SCALAR_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "SCALAR_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SET_VAL
- x = PyInt_FromLong((long) AL_SET_VAL);
- if (x == NULL || PyDict_SetItemString(d, "SET_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SET_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "SET_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SHORT_NAME
- x = PyInt_FromLong((long) AL_SHORT_NAME);
- if (x == NULL || PyDict_SetItemString(d, "SHORT_NAME", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SHORT_NAME);
+ if (x == NULL || PyDict_SetItemString(d, "SHORT_NAME", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SMPTE272M_IF_TYPE
- x = PyInt_FromLong((long) AL_SMPTE272M_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SMPTE272M_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SMPTE272M_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SMPTE272M_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SOURCE
- x = PyInt_FromLong((long) AL_SOURCE);
- if (x == NULL || PyDict_SetItemString(d, "SOURCE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SOURCE);
+ if (x == NULL || PyDict_SetItemString(d, "SOURCE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_IF_TYPE
- x = PyInt_FromLong((long) AL_SPEAKER_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_MUTE_CTL
- x = PyInt_FromLong((long) AL_SPEAKER_MUTE_CTL);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_CTL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_MUTE_CTL);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_CTL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_MUTE_OFF
- x = PyInt_FromLong((long) AL_SPEAKER_MUTE_OFF);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_OFF", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_MUTE_OFF);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_OFF", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_MUTE_ON
- x = PyInt_FromLong((long) AL_SPEAKER_MUTE_ON);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_ON", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_MUTE_ON);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_MUTE_ON", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SPEAKER_PLUS_LINE_IF_TYPE
- x = PyInt_FromLong((long) AL_SPEAKER_PLUS_LINE_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SPEAKER_PLUS_LINE_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SPEAKER_PLUS_LINE_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SPEAKER_PLUS_LINE_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_STEREO
- x = PyInt_FromLong((long) AL_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "STEREO", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "STEREO", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_STRING_VAL
- x = PyInt_FromLong((long) AL_STRING_VAL);
- if (x == NULL || PyDict_SetItemString(d, "STRING_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_STRING_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "STRING_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SUBSYSTEM
- x = PyInt_FromLong((long) AL_SUBSYSTEM);
- if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SUBSYSTEM);
+ if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SUBSYSTEM_TYPE
- x = PyInt_FromLong((long) AL_SUBSYSTEM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SUBSYSTEM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SUBSYSTEM_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYNC_INPUT_TO_AES
- x = PyInt_FromLong((long) AL_SYNC_INPUT_TO_AES);
- if (x == NULL || PyDict_SetItemString(d, "SYNC_INPUT_TO_AES", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYNC_INPUT_TO_AES);
+ if (x == NULL || PyDict_SetItemString(d, "SYNC_INPUT_TO_AES", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYNC_OUTPUT_TO_AES
- x = PyInt_FromLong((long) AL_SYNC_OUTPUT_TO_AES);
- if (x == NULL || PyDict_SetItemString(d, "SYNC_OUTPUT_TO_AES", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYNC_OUTPUT_TO_AES);
+ if (x == NULL || PyDict_SetItemString(d, "SYNC_OUTPUT_TO_AES", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYSTEM
- x = PyInt_FromLong((long) AL_SYSTEM);
- if (x == NULL || PyDict_SetItemString(d, "SYSTEM", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYSTEM);
+ if (x == NULL || PyDict_SetItemString(d, "SYSTEM", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_SYSTEM_TYPE
- x = PyInt_FromLong((long) AL_SYSTEM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "SYSTEM_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_SYSTEM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "SYSTEM_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_TEST_IF_TYPE
- x = PyInt_FromLong((long) AL_TEST_IF_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "TEST_IF_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_TEST_IF_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "TEST_IF_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_TYPE
- x = PyInt_FromLong((long) AL_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_TYPE_BIT
- x = PyInt_FromLong((long) AL_TYPE_BIT);
- if (x == NULL || PyDict_SetItemString(d, "TYPE_BIT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_TYPE_BIT);
+ if (x == NULL || PyDict_SetItemString(d, "TYPE_BIT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_UNUSED_COUNT
- x = PyInt_FromLong((long) AL_UNUSED_COUNT);
- if (x == NULL || PyDict_SetItemString(d, "UNUSED_COUNT", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_UNUSED_COUNT);
+ if (x == NULL || PyDict_SetItemString(d, "UNUSED_COUNT", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_UNUSED_PORTS
- x = PyInt_FromLong((long) AL_UNUSED_PORTS);
- if (x == NULL || PyDict_SetItemString(d, "UNUSED_PORTS", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_UNUSED_PORTS);
+ if (x == NULL || PyDict_SetItemString(d, "UNUSED_PORTS", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_VARIABLE_MCLK_TYPE
- x = PyInt_FromLong((long) AL_VARIABLE_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "VARIABLE_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_VARIABLE_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "VARIABLE_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_VECTOR_VAL
- x = PyInt_FromLong((long) AL_VECTOR_VAL);
- if (x == NULL || PyDict_SetItemString(d, "VECTOR_VAL", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_VECTOR_VAL);
+ if (x == NULL || PyDict_SetItemString(d, "VECTOR_VAL", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_VIDEO_MCLK_TYPE
- x = PyInt_FromLong((long) AL_VIDEO_MCLK_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "VIDEO_MCLK_TYPE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_VIDEO_MCLK_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "VIDEO_MCLK_TYPE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
#ifdef AL_WORDSIZE
- x = PyInt_FromLong((long) AL_WORDSIZE);
- if (x == NULL || PyDict_SetItemString(d, "WORDSIZE", x) < 0)
- goto error;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) AL_WORDSIZE);
+ if (x == NULL || PyDict_SetItemString(d, "WORDSIZE", x) < 0)
+ goto error;
+ Py_DECREF(x);
#endif
-#ifdef AL_NO_ELEM /* IRIX 6 */
- (void) alSetErrorHandler(ErrorHandler);
+#ifdef AL_NO_ELEM /* IRIX 6 */
+ (void) alSetErrorHandler(ErrorHandler);
#endif /* AL_NO_ELEM */
#ifdef OLD_INTERFACE
- (void) ALseterrorhandler(ErrorHandler);
+ (void) ALseterrorhandler(ErrorHandler);
#endif /* OLD_INTERFACE */
-
+
error:
- return;
+ return;
}
diff --git a/Modules/arraymodule.c b/Modules/arraymodule.c
index ef6fb87..403f646 100644
--- a/Modules/arraymodule.c
+++ b/Modules/arraymodule.c
@@ -11,7 +11,7 @@
#include <stddef.h>
#else /* !STDC_HEADERS */
#ifdef HAVE_SYS_TYPES_H
-#include <sys/types.h> /* For size_t */
+#include <sys/types.h> /* For size_t */
#endif /* HAVE_SYS_TYPES_H */
#endif /* !STDC_HEADERS */
@@ -22,18 +22,18 @@ struct arrayobject; /* Forward */
* functions aren't visible yet.
*/
struct arraydescr {
- int typecode;
- int itemsize;
- PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
- int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
+ int typecode;
+ int itemsize;
+ PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
+ int (*setitem)(struct arrayobject *, Py_ssize_t, PyObject *);
};
typedef struct arrayobject {
- PyObject_VAR_HEAD
- char *ob_item;
- Py_ssize_t allocated;
- struct arraydescr *ob_descr;
- PyObject *weakreflist; /* List of weak references */
+ PyObject_VAR_HEAD
+ char *ob_item;
+ Py_ssize_t allocated;
+ struct arraydescr *ob_descr;
+ PyObject *weakreflist; /* List of weak references */
} arrayobject;
static PyTypeObject Arraytype;
@@ -44,49 +44,49 @@ static PyTypeObject Arraytype;
static int
array_resize(arrayobject *self, Py_ssize_t newsize)
{
- char *items;
- size_t _new_size;
-
- /* Bypass realloc() when a previous overallocation is large enough
- to accommodate the newsize. If the newsize is 16 smaller than the
- current size, then proceed with the realloc() to shrink the list.
- */
-
- if (self->allocated >= newsize &&
- Py_SIZE(self) < newsize + 16 &&
- self->ob_item != NULL) {
- Py_SIZE(self) = newsize;
- return 0;
- }
-
- /* This over-allocates proportional to the array size, making room
- * for additional growth. The over-allocation is mild, but is
- * enough to give linear-time amortized behavior over a long
- * sequence of appends() in the presence of a poorly-performing
- * system realloc().
- * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
- * Note, the pattern starts out the same as for lists but then
- * grows at a smaller rate so that larger arrays only overallocate
- * by about 1/16th -- this is done because arrays are presumed to be more
- * memory critical.
- */
-
- _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
- items = self->ob_item;
- /* XXX The following multiplication and division does not optimize away
- like it does for lists since the size is not known at compile time */
- if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
- PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
- else
- items = NULL;
- if (items == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- self->ob_item = items;
- Py_SIZE(self) = newsize;
- self->allocated = _new_size;
- return 0;
+ char *items;
+ size_t _new_size;
+
+ /* Bypass realloc() when a previous overallocation is large enough
+ to accommodate the newsize. If the newsize is 16 smaller than the
+ current size, then proceed with the realloc() to shrink the list.
+ */
+
+ if (self->allocated >= newsize &&
+ Py_SIZE(self) < newsize + 16 &&
+ self->ob_item != NULL) {
+ Py_SIZE(self) = newsize;
+ return 0;
+ }
+
+ /* This over-allocates proportional to the array size, making room
+ * for additional growth. The over-allocation is mild, but is
+ * enough to give linear-time amortized behavior over a long
+ * sequence of appends() in the presence of a poorly-performing
+ * system realloc().
+ * The growth pattern is: 0, 4, 8, 16, 25, 34, 46, 56, 67, 79, ...
+ * Note, the pattern starts out the same as for lists but then
+ * grows at a smaller rate so that larger arrays only overallocate
+ * by about 1/16th -- this is done because arrays are presumed to be more
+ * memory critical.
+ */
+
+ _new_size = (newsize >> 4) + (Py_SIZE(self) < 8 ? 3 : 7) + newsize;
+ items = self->ob_item;
+ /* XXX The following multiplication and division does not optimize away
+ like it does for lists since the size is not known at compile time */
+ if (_new_size <= ((~(size_t)0) / self->ob_descr->itemsize))
+ PyMem_RESIZE(items, char, (_new_size * self->ob_descr->itemsize));
+ else
+ items = NULL;
+ if (items == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->ob_item = items;
+ Py_SIZE(self) = newsize;
+ self->allocated = _new_size;
+ return 0;
}
/****************************************************************************
@@ -104,308 +104,308 @@ in bounds; that's the responsibility of the caller.
static PyObject *
c_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyString_FromStringAndSize(&((char *)ap->ob_item)[i], 1);
+ return PyString_FromStringAndSize(&((char *)ap->ob_item)[i], 1);
}
static int
c_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- char x;
- if (!PyArg_Parse(v, "c;array item must be char", &x))
- return -1;
- if (i >= 0)
- ((char *)ap->ob_item)[i] = x;
- return 0;
+ char x;
+ if (!PyArg_Parse(v, "c;array item must be char", &x))
+ return -1;
+ if (i >= 0)
+ ((char *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
b_getitem(arrayobject *ap, Py_ssize_t i)
{
- long x = ((char *)ap->ob_item)[i];
- if (x >= 128)
- x -= 256;
- return PyInt_FromLong(x);
+ long x = ((char *)ap->ob_item)[i];
+ if (x >= 128)
+ x -= 256;
+ return PyInt_FromLong(x);
}
static int
b_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- short x;
- /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
- must use the next size up that is signed ('h') and manually do
- the overflow checking */
- if (!PyArg_Parse(v, "h;array item must be integer", &x))
- return -1;
- else if (x < -128) {
- PyErr_SetString(PyExc_OverflowError,
- "signed char is less than minimum");
- return -1;
- }
- else if (x > 127) {
- PyErr_SetString(PyExc_OverflowError,
- "signed char is greater than maximum");
- return -1;
- }
- if (i >= 0)
- ((char *)ap->ob_item)[i] = (char)x;
- return 0;
+ short x;
+ /* PyArg_Parse's 'b' formatter is for an unsigned char, therefore
+ must use the next size up that is signed ('h') and manually do
+ the overflow checking */
+ if (!PyArg_Parse(v, "h;array item must be integer", &x))
+ return -1;
+ else if (x < -128) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed char is less than minimum");
+ return -1;
+ }
+ else if (x > 127) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed char is greater than maximum");
+ return -1;
+ }
+ if (i >= 0)
+ ((char *)ap->ob_item)[i] = (char)x;
+ return 0;
}
static PyObject *
BB_getitem(arrayobject *ap, Py_ssize_t i)
{
- long x = ((unsigned char *)ap->ob_item)[i];
- return PyInt_FromLong(x);
+ long x = ((unsigned char *)ap->ob_item)[i];
+ return PyInt_FromLong(x);
}
static int
BB_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- unsigned char x;
- /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
- if (!PyArg_Parse(v, "b;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((char *)ap->ob_item)[i] = x;
- return 0;
+ unsigned char x;
+ /* 'B' == unsigned char, maps to PyArg_Parse's 'b' formatter */
+ if (!PyArg_Parse(v, "b;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((char *)ap->ob_item)[i] = x;
+ return 0;
}
#ifdef Py_USING_UNICODE
static PyObject *
u_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
+ return PyUnicode_FromUnicode(&((Py_UNICODE *) ap->ob_item)[i], 1);
}
static int
u_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- Py_UNICODE *p;
- Py_ssize_t len;
+ Py_UNICODE *p;
+ Py_ssize_t len;
- if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
- return -1;
- if (len != 1) {
- PyErr_SetString(PyExc_TypeError,
- "array item must be unicode character");
- return -1;
- }
- if (i >= 0)
- ((Py_UNICODE *)ap->ob_item)[i] = p[0];
- return 0;
+ if (!PyArg_Parse(v, "u#;array item must be unicode character", &p, &len))
+ return -1;
+ if (len != 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "array item must be unicode character");
+ return -1;
+ }
+ if (i >= 0)
+ ((Py_UNICODE *)ap->ob_item)[i] = p[0];
+ return 0;
}
#endif
static PyObject *
h_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyInt_FromLong((long) ((short *)ap->ob_item)[i]);
+ return PyInt_FromLong((long) ((short *)ap->ob_item)[i]);
}
static int
h_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- short x;
- /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
- if (!PyArg_Parse(v, "h;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((short *)ap->ob_item)[i] = x;
- return 0;
+ short x;
+ /* 'h' == signed short, maps to PyArg_Parse's 'h' formatter */
+ if (!PyArg_Parse(v, "h;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((short *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
HH_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyInt_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
+ return PyInt_FromLong((long) ((unsigned short *)ap->ob_item)[i]);
}
static int
HH_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- int x;
- /* PyArg_Parse's 'h' formatter is for a signed short, therefore
- must use the next size up and manually do the overflow checking */
- if (!PyArg_Parse(v, "i;array item must be integer", &x))
- return -1;
- else if (x < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned short is less than minimum");
- return -1;
- }
- else if (x > USHRT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned short is greater than maximum");
- return -1;
- }
- if (i >= 0)
- ((short *)ap->ob_item)[i] = (short)x;
- return 0;
+ int x;
+ /* PyArg_Parse's 'h' formatter is for a signed short, therefore
+ must use the next size up and manually do the overflow checking */
+ if (!PyArg_Parse(v, "i;array item must be integer", &x))
+ return -1;
+ else if (x < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned short is less than minimum");
+ return -1;
+ }
+ else if (x > USHRT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned short is greater than maximum");
+ return -1;
+ }
+ if (i >= 0)
+ ((short *)ap->ob_item)[i] = (short)x;
+ return 0;
}
static PyObject *
i_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyInt_FromLong((long) ((int *)ap->ob_item)[i]);
+ return PyInt_FromLong((long) ((int *)ap->ob_item)[i]);
}
static int
i_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- int x;
- /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
- if (!PyArg_Parse(v, "i;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((int *)ap->ob_item)[i] = x;
- return 0;
+ int x;
+ /* 'i' == signed int, maps to PyArg_Parse's 'i' formatter */
+ if (!PyArg_Parse(v, "i;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((int *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
II_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromUnsignedLong(
- (unsigned long) ((unsigned int *)ap->ob_item)[i]);
+ return PyLong_FromUnsignedLong(
+ (unsigned long) ((unsigned int *)ap->ob_item)[i]);
}
static int
II_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- unsigned long x;
- if (PyLong_Check(v)) {
- x = PyLong_AsUnsignedLong(v);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return -1;
- }
- else {
- long y;
- if (!PyArg_Parse(v, "l;array item must be integer", &y))
- return -1;
- if (y < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned int is less than minimum");
- return -1;
- }
- x = (unsigned long)y;
-
- }
- if (x > UINT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned int is greater than maximum");
- return -1;
- }
-
- if (i >= 0)
- ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
- return 0;
+ unsigned long x;
+ if (PyLong_Check(v)) {
+ x = PyLong_AsUnsignedLong(v);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return -1;
+ }
+ else {
+ long y;
+ if (!PyArg_Parse(v, "l;array item must be integer", &y))
+ return -1;
+ if (y < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned int is less than minimum");
+ return -1;
+ }
+ x = (unsigned long)y;
+
+ }
+ if (x > UINT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned int is greater than maximum");
+ return -1;
+ }
+
+ if (i >= 0)
+ ((unsigned int *)ap->ob_item)[i] = (unsigned int)x;
+ return 0;
}
static PyObject *
l_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyInt_FromLong(((long *)ap->ob_item)[i]);
+ return PyInt_FromLong(((long *)ap->ob_item)[i]);
}
static int
l_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- long x;
- if (!PyArg_Parse(v, "l;array item must be integer", &x))
- return -1;
- if (i >= 0)
- ((long *)ap->ob_item)[i] = x;
- return 0;
+ long x;
+ if (!PyArg_Parse(v, "l;array item must be integer", &x))
+ return -1;
+ if (i >= 0)
+ ((long *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
LL_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
+ return PyLong_FromUnsignedLong(((unsigned long *)ap->ob_item)[i]);
}
static int
LL_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- unsigned long x;
- if (PyLong_Check(v)) {
- x = PyLong_AsUnsignedLong(v);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return -1;
- }
- else {
- long y;
- if (!PyArg_Parse(v, "l;array item must be integer", &y))
- return -1;
- if (y < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned long is less than minimum");
- return -1;
- }
- x = (unsigned long)y;
-
- }
- if (x > ULONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned long is greater than maximum");
- return -1;
- }
-
- if (i >= 0)
- ((unsigned long *)ap->ob_item)[i] = x;
- return 0;
+ unsigned long x;
+ if (PyLong_Check(v)) {
+ x = PyLong_AsUnsignedLong(v);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return -1;
+ }
+ else {
+ long y;
+ if (!PyArg_Parse(v, "l;array item must be integer", &y))
+ return -1;
+ if (y < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned long is less than minimum");
+ return -1;
+ }
+ x = (unsigned long)y;
+
+ }
+ if (x > ULONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned long is greater than maximum");
+ return -1;
+ }
+
+ if (i >= 0)
+ ((unsigned long *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
f_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
+ return PyFloat_FromDouble((double) ((float *)ap->ob_item)[i]);
}
static int
f_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- float x;
- if (!PyArg_Parse(v, "f;array item must be float", &x))
- return -1;
- if (i >= 0)
- ((float *)ap->ob_item)[i] = x;
- return 0;
+ float x;
+ if (!PyArg_Parse(v, "f;array item must be float", &x))
+ return -1;
+ if (i >= 0)
+ ((float *)ap->ob_item)[i] = x;
+ return 0;
}
static PyObject *
d_getitem(arrayobject *ap, Py_ssize_t i)
{
- return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
+ return PyFloat_FromDouble(((double *)ap->ob_item)[i]);
}
static int
d_setitem(arrayobject *ap, Py_ssize_t i, PyObject *v)
{
- double x;
- if (!PyArg_Parse(v, "d;array item must be float", &x))
- return -1;
- if (i >= 0)
- ((double *)ap->ob_item)[i] = x;
- return 0;
+ double x;
+ if (!PyArg_Parse(v, "d;array item must be float", &x))
+ return -1;
+ if (i >= 0)
+ ((double *)ap->ob_item)[i] = x;
+ return 0;
}
/* Description of types */
static struct arraydescr descriptors[] = {
- {'c', sizeof(char), c_getitem, c_setitem},
- {'b', sizeof(char), b_getitem, b_setitem},
- {'B', sizeof(char), BB_getitem, BB_setitem},
+ {'c', sizeof(char), c_getitem, c_setitem},
+ {'b', sizeof(char), b_getitem, b_setitem},
+ {'B', sizeof(char), BB_getitem, BB_setitem},
#ifdef Py_USING_UNICODE
- {'u', sizeof(Py_UNICODE), u_getitem, u_setitem},
+ {'u', sizeof(Py_UNICODE), u_getitem, u_setitem},
#endif
- {'h', sizeof(short), h_getitem, h_setitem},
- {'H', sizeof(short), HH_getitem, HH_setitem},
- {'i', sizeof(int), i_getitem, i_setitem},
- {'I', sizeof(int), II_getitem, II_setitem},
- {'l', sizeof(long), l_getitem, l_setitem},
- {'L', sizeof(long), LL_getitem, LL_setitem},
- {'f', sizeof(float), f_getitem, f_setitem},
- {'d', sizeof(double), d_getitem, d_setitem},
- {'\0', 0, 0, 0} /* Sentinel */
+ {'h', sizeof(short), h_getitem, h_setitem},
+ {'H', sizeof(short), HH_getitem, HH_setitem},
+ {'i', sizeof(int), i_getitem, i_setitem},
+ {'I', sizeof(int), II_getitem, II_setitem},
+ {'l', sizeof(long), l_getitem, l_setitem},
+ {'L', sizeof(long), LL_getitem, LL_setitem},
+ {'f', sizeof(float), f_getitem, f_setitem},
+ {'d', sizeof(double), d_getitem, d_setitem},
+ {'\0', 0, 0, 0} /* Sentinel */
};
/****************************************************************************
@@ -415,78 +415,78 @@ Implementations of array object methods.
static PyObject *
newarrayobject(PyTypeObject *type, Py_ssize_t size, struct arraydescr *descr)
{
- arrayobject *op;
- size_t nbytes;
-
- if (size < 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
-
- nbytes = size * descr->itemsize;
- /* Check for overflow */
- if (nbytes / descr->itemsize != (size_t)size) {
- return PyErr_NoMemory();
- }
- op = (arrayobject *) type->tp_alloc(type, 0);
- if (op == NULL) {
- return NULL;
- }
- op->ob_descr = descr;
- op->allocated = size;
- op->weakreflist = NULL;
- Py_SIZE(op) = size;
- if (size <= 0) {
- op->ob_item = NULL;
- }
- else {
- op->ob_item = PyMem_NEW(char, nbytes);
- if (op->ob_item == NULL) {
- Py_DECREF(op);
- return PyErr_NoMemory();
- }
- }
- return (PyObject *) op;
+ arrayobject *op;
+ size_t nbytes;
+
+ if (size < 0) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ nbytes = size * descr->itemsize;
+ /* Check for overflow */
+ if (nbytes / descr->itemsize != (size_t)size) {
+ return PyErr_NoMemory();
+ }
+ op = (arrayobject *) type->tp_alloc(type, 0);
+ if (op == NULL) {
+ return NULL;
+ }
+ op->ob_descr = descr;
+ op->allocated = size;
+ op->weakreflist = NULL;
+ Py_SIZE(op) = size;
+ if (size <= 0) {
+ op->ob_item = NULL;
+ }
+ else {
+ op->ob_item = PyMem_NEW(char, nbytes);
+ if (op->ob_item == NULL) {
+ Py_DECREF(op);
+ return PyErr_NoMemory();
+ }
+ }
+ return (PyObject *) op;
}
static PyObject *
getarrayitem(PyObject *op, Py_ssize_t i)
{
- register arrayobject *ap;
- assert(array_Check(op));
- ap = (arrayobject *)op;
- assert(i>=0 && i<Py_SIZE(ap));
- return (*ap->ob_descr->getitem)(ap, i);
+ register arrayobject *ap;
+ assert(array_Check(op));
+ ap = (arrayobject *)op;
+ assert(i>=0 && i<Py_SIZE(ap));
+ return (*ap->ob_descr->getitem)(ap, i);
}
static int
ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
{
- char *items;
- Py_ssize_t n = Py_SIZE(self);
- if (v == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
- if ((*self->ob_descr->setitem)(self, -1, v) < 0)
- return -1;
-
- if (array_resize(self, n+1) == -1)
- return -1;
- items = self->ob_item;
- if (where < 0) {
- where += n;
- if (where < 0)
- where = 0;
- }
- if (where > n)
- where = n;
- /* appends don't need to call memmove() */
- if (where != n)
- memmove(items + (where+1)*self->ob_descr->itemsize,
- items + where*self->ob_descr->itemsize,
- (n-where)*self->ob_descr->itemsize);
- return (*self->ob_descr->setitem)(self, where, v);
+ char *items;
+ Py_ssize_t n = Py_SIZE(self);
+ if (v == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if ((*self->ob_descr->setitem)(self, -1, v) < 0)
+ return -1;
+
+ if (array_resize(self, n+1) == -1)
+ return -1;
+ items = self->ob_item;
+ if (where < 0) {
+ where += n;
+ if (where < 0)
+ where = 0;
+ }
+ if (where > n)
+ where = n;
+ /* appends don't need to call memmove() */
+ if (where != n)
+ memmove(items + (where+1)*self->ob_descr->itemsize,
+ items + where*self->ob_descr->itemsize,
+ (n-where)*self->ob_descr->itemsize);
+ return (*self->ob_descr->setitem)(self, where, v);
}
/* Methods */
@@ -494,141 +494,141 @@ ins1(arrayobject *self, Py_ssize_t where, PyObject *v)
static void
array_dealloc(arrayobject *op)
{
- if (op->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) op);
- if (op->ob_item != NULL)
- PyMem_DEL(op->ob_item);
- Py_TYPE(op)->tp_free((PyObject *)op);
+ if (op->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) op);
+ if (op->ob_item != NULL)
+ PyMem_DEL(op->ob_item);
+ Py_TYPE(op)->tp_free((PyObject *)op);
}
static PyObject *
array_richcompare(PyObject *v, PyObject *w, int op)
{
- arrayobject *va, *wa;
- PyObject *vi = NULL;
- PyObject *wi = NULL;
- Py_ssize_t i, k;
- PyObject *res;
-
- if (!array_Check(v) || !array_Check(w)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- va = (arrayobject *)v;
- wa = (arrayobject *)w;
-
- if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
- /* Shortcut: if the lengths differ, the arrays differ */
- if (op == Py_EQ)
- res = Py_False;
- else
- res = Py_True;
- Py_INCREF(res);
- return res;
- }
-
- /* Search for the first index where items are different */
- k = 1;
- for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
- vi = getarrayitem(v, i);
- wi = getarrayitem(w, i);
- if (vi == NULL || wi == NULL) {
- Py_XDECREF(vi);
- Py_XDECREF(wi);
- return NULL;
- }
- k = PyObject_RichCompareBool(vi, wi, Py_EQ);
- if (k == 0)
- break; /* Keeping vi and wi alive! */
- Py_DECREF(vi);
- Py_DECREF(wi);
- if (k < 0)
- return NULL;
- }
-
- if (k) {
- /* No more items to compare -- compare sizes */
- Py_ssize_t vs = Py_SIZE(va);
- Py_ssize_t ws = Py_SIZE(wa);
- int cmp;
- switch (op) {
- case Py_LT: cmp = vs < ws; break;
- case Py_LE: cmp = vs <= ws; break;
- case Py_EQ: cmp = vs == ws; break;
- case Py_NE: cmp = vs != ws; break;
- case Py_GT: cmp = vs > ws; break;
- case Py_GE: cmp = vs >= ws; break;
- default: return NULL; /* cannot happen */
- }
- if (cmp)
- res = Py_True;
- else
- res = Py_False;
- Py_INCREF(res);
- return res;
- }
-
- /* We have an item that differs. First, shortcuts for EQ/NE */
- if (op == Py_EQ) {
- Py_INCREF(Py_False);
- res = Py_False;
- }
- else if (op == Py_NE) {
- Py_INCREF(Py_True);
- res = Py_True;
- }
- else {
- /* Compare the final item again using the proper operator */
- res = PyObject_RichCompare(vi, wi, op);
- }
- Py_DECREF(vi);
- Py_DECREF(wi);
- return res;
+ arrayobject *va, *wa;
+ PyObject *vi = NULL;
+ PyObject *wi = NULL;
+ Py_ssize_t i, k;
+ PyObject *res;
+
+ if (!array_Check(v) || !array_Check(w)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ va = (arrayobject *)v;
+ wa = (arrayobject *)w;
+
+ if (Py_SIZE(va) != Py_SIZE(wa) && (op == Py_EQ || op == Py_NE)) {
+ /* Shortcut: if the lengths differ, the arrays differ */
+ if (op == Py_EQ)
+ res = Py_False;
+ else
+ res = Py_True;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* Search for the first index where items are different */
+ k = 1;
+ for (i = 0; i < Py_SIZE(va) && i < Py_SIZE(wa); i++) {
+ vi = getarrayitem(v, i);
+ wi = getarrayitem(w, i);
+ if (vi == NULL || wi == NULL) {
+ Py_XDECREF(vi);
+ Py_XDECREF(wi);
+ return NULL;
+ }
+ k = PyObject_RichCompareBool(vi, wi, Py_EQ);
+ if (k == 0)
+ break; /* Keeping vi and wi alive! */
+ Py_DECREF(vi);
+ Py_DECREF(wi);
+ if (k < 0)
+ return NULL;
+ }
+
+ if (k) {
+ /* No more items to compare -- compare sizes */
+ Py_ssize_t vs = Py_SIZE(va);
+ Py_ssize_t ws = Py_SIZE(wa);
+ int cmp;
+ switch (op) {
+ case Py_LT: cmp = vs < ws; break;
+ case Py_LE: cmp = vs <= ws; break;
+ case Py_EQ: cmp = vs == ws; break;
+ case Py_NE: cmp = vs != ws; break;
+ case Py_GT: cmp = vs > ws; break;
+ case Py_GE: cmp = vs >= ws; break;
+ default: return NULL; /* cannot happen */
+ }
+ if (cmp)
+ res = Py_True;
+ else
+ res = Py_False;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* We have an item that differs. First, shortcuts for EQ/NE */
+ if (op == Py_EQ) {
+ Py_INCREF(Py_False);
+ res = Py_False;
+ }
+ else if (op == Py_NE) {
+ Py_INCREF(Py_True);
+ res = Py_True;
+ }
+ else {
+ /* Compare the final item again using the proper operator */
+ res = PyObject_RichCompare(vi, wi, op);
+ }
+ Py_DECREF(vi);
+ Py_DECREF(wi);
+ return res;
}
static Py_ssize_t
array_length(arrayobject *a)
{
- return Py_SIZE(a);
+ return Py_SIZE(a);
}
static PyObject *
array_item(arrayobject *a, Py_ssize_t i)
{
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError, "array index out of range");
- return NULL;
- }
- return getarrayitem((PyObject *)a, i);
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError, "array index out of range");
+ return NULL;
+ }
+ return getarrayitem((PyObject *)a, i);
}
static PyObject *
array_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- arrayobject *np;
- if (ilow < 0)
- ilow = 0;
- else if (ilow > Py_SIZE(a))
- ilow = Py_SIZE(a);
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
- np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
- if (np == NULL)
- return NULL;
- memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
- (ihigh-ilow) * a->ob_descr->itemsize);
- return (PyObject *)np;
+ arrayobject *np;
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > Py_SIZE(a))
+ ilow = Py_SIZE(a);
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+ np = (arrayobject *) newarrayobject(&Arraytype, ihigh - ilow, a->ob_descr);
+ if (np == NULL)
+ return NULL;
+ memcpy(np->ob_item, a->ob_item + ilow * a->ob_descr->itemsize,
+ (ihigh-ilow) * a->ob_descr->itemsize);
+ return (PyObject *)np;
}
static PyObject *
array_copy(arrayobject *a, PyObject *unused)
{
- return array_slice(a, 0, Py_SIZE(a));
+ return array_slice(a, 0, Py_SIZE(a));
}
PyDoc_STRVAR(copy_doc,
@@ -639,297 +639,297 @@ PyDoc_STRVAR(copy_doc,
static PyObject *
array_concat(arrayobject *a, PyObject *bb)
{
- Py_ssize_t size;
- arrayobject *np;
- if (!array_Check(bb)) {
- PyErr_Format(PyExc_TypeError,
- "can only append array (not \"%.200s\") to array",
- Py_TYPE(bb)->tp_name);
- return NULL;
- }
+ Py_ssize_t size;
+ arrayobject *np;
+ if (!array_Check(bb)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only append array (not \"%.200s\") to array",
+ Py_TYPE(bb)->tp_name);
+ return NULL;
+ }
#define b ((arrayobject *)bb)
- if (a->ob_descr != b->ob_descr) {
- PyErr_BadArgument();
- return NULL;
- }
- if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
- return PyErr_NoMemory();
- }
- size = Py_SIZE(a) + Py_SIZE(b);
- np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
- if (np == NULL) {
- return NULL;
- }
- memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
- memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
- b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
- return (PyObject *)np;
+ if (a->ob_descr != b->ob_descr) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if (Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
+ return PyErr_NoMemory();
+ }
+ size = Py_SIZE(a) + Py_SIZE(b);
+ np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
+ if (np == NULL) {
+ return NULL;
+ }
+ memcpy(np->ob_item, a->ob_item, Py_SIZE(a)*a->ob_descr->itemsize);
+ memcpy(np->ob_item + Py_SIZE(a)*a->ob_descr->itemsize,
+ b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
+ return (PyObject *)np;
#undef b
}
static PyObject *
array_repeat(arrayobject *a, Py_ssize_t n)
{
- Py_ssize_t i;
- Py_ssize_t size;
- arrayobject *np;
- char *p;
- Py_ssize_t nbytes;
- if (n < 0)
- n = 0;
- if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
- return PyErr_NoMemory();
- }
- size = Py_SIZE(a) * n;
- np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
- if (np == NULL)
- return NULL;
- p = np->ob_item;
- nbytes = Py_SIZE(a) * a->ob_descr->itemsize;
- for (i = 0; i < n; i++) {
- memcpy(p, a->ob_item, nbytes);
- p += nbytes;
- }
- return (PyObject *) np;
+ Py_ssize_t i;
+ Py_ssize_t size;
+ arrayobject *np;
+ char *p;
+ Py_ssize_t nbytes;
+ if (n < 0)
+ n = 0;
+ if ((Py_SIZE(a) != 0) && (n > PY_SSIZE_T_MAX / Py_SIZE(a))) {
+ return PyErr_NoMemory();
+ }
+ size = Py_SIZE(a) * n;
+ np = (arrayobject *) newarrayobject(&Arraytype, size, a->ob_descr);
+ if (np == NULL)
+ return NULL;
+ p = np->ob_item;
+ nbytes = Py_SIZE(a) * a->ob_descr->itemsize;
+ for (i = 0; i < n; i++) {
+ memcpy(p, a->ob_item, nbytes);
+ p += nbytes;
+ }
+ return (PyObject *) np;
}
static int
array_ass_slice(arrayobject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
- char *item;
- Py_ssize_t n; /* Size of replacement array */
- Py_ssize_t d; /* Change in size */
+ char *item;
+ Py_ssize_t n; /* Size of replacement array */
+ Py_ssize_t d; /* Change in size */
#define b ((arrayobject *)v)
- if (v == NULL)
- n = 0;
- else if (array_Check(v)) {
- n = Py_SIZE(b);
- if (a == b) {
- /* Special case "a[i:j] = a" -- copy b first */
- int ret;
- v = array_slice(b, 0, n);
- if (!v)
- return -1;
- ret = array_ass_slice(a, ilow, ihigh, v);
- Py_DECREF(v);
- return ret;
- }
- if (b->ob_descr != a->ob_descr) {
- PyErr_BadArgument();
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "can only assign array (not \"%.200s\") to array slice",
- Py_TYPE(v)->tp_name);
- return -1;
- }
- if (ilow < 0)
- ilow = 0;
- else if (ilow > Py_SIZE(a))
- ilow = Py_SIZE(a);
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
- item = a->ob_item;
- d = n - (ihigh-ilow);
- if (d < 0) { /* Delete -d items */
- memmove(item + (ihigh+d)*a->ob_descr->itemsize,
- item + ihigh*a->ob_descr->itemsize,
- (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
- Py_SIZE(a) += d;
- PyMem_RESIZE(item, char, Py_SIZE(a)*a->ob_descr->itemsize);
- /* Can't fail */
- a->ob_item = item;
- a->allocated = Py_SIZE(a);
- }
- else if (d > 0) { /* Insert d items */
- PyMem_RESIZE(item, char,
- (Py_SIZE(a) + d)*a->ob_descr->itemsize);
- if (item == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- memmove(item + (ihigh+d)*a->ob_descr->itemsize,
- item + ihigh*a->ob_descr->itemsize,
- (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
- a->ob_item = item;
- Py_SIZE(a) += d;
- a->allocated = Py_SIZE(a);
- }
- if (n > 0)
- memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
- n*b->ob_descr->itemsize);
- return 0;
+ if (v == NULL)
+ n = 0;
+ else if (array_Check(v)) {
+ n = Py_SIZE(b);
+ if (a == b) {
+ /* Special case "a[i:j] = a" -- copy b first */
+ int ret;
+ v = array_slice(b, 0, n);
+ if (!v)
+ return -1;
+ ret = array_ass_slice(a, ilow, ihigh, v);
+ Py_DECREF(v);
+ return ret;
+ }
+ if (b->ob_descr != a->ob_descr) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign array (not \"%.200s\") to array slice",
+ Py_TYPE(v)->tp_name);
+ return -1;
+ }
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > Py_SIZE(a))
+ ilow = Py_SIZE(a);
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+ item = a->ob_item;
+ d = n - (ihigh-ilow);
+ if (d < 0) { /* Delete -d items */
+ memmove(item + (ihigh+d)*a->ob_descr->itemsize,
+ item + ihigh*a->ob_descr->itemsize,
+ (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
+ Py_SIZE(a) += d;
+ PyMem_RESIZE(item, char, Py_SIZE(a)*a->ob_descr->itemsize);
+ /* Can't fail */
+ a->ob_item = item;
+ a->allocated = Py_SIZE(a);
+ }
+ else if (d > 0) { /* Insert d items */
+ PyMem_RESIZE(item, char,
+ (Py_SIZE(a) + d)*a->ob_descr->itemsize);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ memmove(item + (ihigh+d)*a->ob_descr->itemsize,
+ item + ihigh*a->ob_descr->itemsize,
+ (Py_SIZE(a)-ihigh)*a->ob_descr->itemsize);
+ a->ob_item = item;
+ Py_SIZE(a) += d;
+ a->allocated = Py_SIZE(a);
+ }
+ if (n > 0)
+ memcpy(item + ilow*a->ob_descr->itemsize, b->ob_item,
+ n*b->ob_descr->itemsize);
+ return 0;
#undef b
}
static int
array_ass_item(arrayobject *a, Py_ssize_t i, PyObject *v)
{
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError,
- "array assignment index out of range");
- return -1;
- }
- if (v == NULL)
- return array_ass_slice(a, i, i+1, v);
- return (*a->ob_descr->setitem)(a, i, v);
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError,
+ "array assignment index out of range");
+ return -1;
+ }
+ if (v == NULL)
+ return array_ass_slice(a, i, i+1, v);
+ return (*a->ob_descr->setitem)(a, i, v);
}
static int
setarrayitem(PyObject *a, Py_ssize_t i, PyObject *v)
{
- assert(array_Check(a));
- return array_ass_item((arrayobject *)a, i, v);
+ assert(array_Check(a));
+ return array_ass_item((arrayobject *)a, i, v);
}
static int
array_iter_extend(arrayobject *self, PyObject *bb)
{
- PyObject *it, *v;
+ PyObject *it, *v;
- it = PyObject_GetIter(bb);
- if (it == NULL)
- return -1;
+ it = PyObject_GetIter(bb);
+ if (it == NULL)
+ return -1;
- while ((v = PyIter_Next(it)) != NULL) {
- if (ins1(self, (int) Py_SIZE(self), v) != 0) {
- Py_DECREF(v);
- Py_DECREF(it);
- return -1;
- }
- Py_DECREF(v);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return -1;
- return 0;
+ while ((v = PyIter_Next(it)) != NULL) {
+ if (ins1(self, (int) Py_SIZE(self), v) != 0) {
+ Py_DECREF(v);
+ Py_DECREF(it);
+ return -1;
+ }
+ Py_DECREF(v);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return -1;
+ return 0;
}
static int
array_do_extend(arrayobject *self, PyObject *bb)
{
- Py_ssize_t size;
- char *old_item;
+ Py_ssize_t size;
+ char *old_item;
- if (!array_Check(bb))
- return array_iter_extend(self, bb);
+ if (!array_Check(bb))
+ return array_iter_extend(self, bb);
#define b ((arrayobject *)bb)
- if (self->ob_descr != b->ob_descr) {
- PyErr_SetString(PyExc_TypeError,
- "can only extend with array of same kind");
- return -1;
- }
- if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
- ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
- PyErr_NoMemory();
- return -1;
- }
- size = Py_SIZE(self) + Py_SIZE(b);
- old_item = self->ob_item;
- PyMem_RESIZE(self->ob_item, char, size*self->ob_descr->itemsize);
- if (self->ob_item == NULL) {
- self->ob_item = old_item;
- PyErr_NoMemory();
- return -1;
- }
- memcpy(self->ob_item + Py_SIZE(self)*self->ob_descr->itemsize,
- b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
- Py_SIZE(self) = size;
- self->allocated = size;
-
- return 0;
+ if (self->ob_descr != b->ob_descr) {
+ PyErr_SetString(PyExc_TypeError,
+ "can only extend with array of same kind");
+ return -1;
+ }
+ if ((Py_SIZE(self) > PY_SSIZE_T_MAX - Py_SIZE(b)) ||
+ ((Py_SIZE(self) + Py_SIZE(b)) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ size = Py_SIZE(self) + Py_SIZE(b);
+ old_item = self->ob_item;
+ PyMem_RESIZE(self->ob_item, char, size*self->ob_descr->itemsize);
+ if (self->ob_item == NULL) {
+ self->ob_item = old_item;
+ PyErr_NoMemory();
+ return -1;
+ }
+ memcpy(self->ob_item + Py_SIZE(self)*self->ob_descr->itemsize,
+ b->ob_item, Py_SIZE(b)*b->ob_descr->itemsize);
+ Py_SIZE(self) = size;
+ self->allocated = size;
+
+ return 0;
#undef b
}
static PyObject *
array_inplace_concat(arrayobject *self, PyObject *bb)
{
- if (!array_Check(bb)) {
- PyErr_Format(PyExc_TypeError,
- "can only extend array with array (not \"%.200s\")",
- Py_TYPE(bb)->tp_name);
- return NULL;
- }
- if (array_do_extend(self, bb) == -1)
- return NULL;
- Py_INCREF(self);
- return (PyObject *)self;
+ if (!array_Check(bb)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only extend array with array (not \"%.200s\")",
+ Py_TYPE(bb)->tp_name);
+ return NULL;
+ }
+ if (array_do_extend(self, bb) == -1)
+ return NULL;
+ Py_INCREF(self);
+ return (PyObject *)self;
}
static PyObject *
array_inplace_repeat(arrayobject *self, Py_ssize_t n)
{
- char *items, *p;
- Py_ssize_t size, i;
-
- if (Py_SIZE(self) > 0) {
- if (n < 0)
- n = 0;
- items = self->ob_item;
- if ((self->ob_descr->itemsize != 0) &&
- (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
- return PyErr_NoMemory();
- }
- size = Py_SIZE(self) * self->ob_descr->itemsize;
- if (n == 0) {
- PyMem_FREE(items);
- self->ob_item = NULL;
- Py_SIZE(self) = 0;
- self->allocated = 0;
- }
- else {
- if (size > PY_SSIZE_T_MAX / n) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(items, char, n * size);
- if (items == NULL)
- return PyErr_NoMemory();
- p = items;
- for (i = 1; i < n; i++) {
- p += size;
- memcpy(p, items, size);
- }
- self->ob_item = items;
- Py_SIZE(self) *= n;
- self->allocated = Py_SIZE(self);
- }
- }
- Py_INCREF(self);
- return (PyObject *)self;
+ char *items, *p;
+ Py_ssize_t size, i;
+
+ if (Py_SIZE(self) > 0) {
+ if (n < 0)
+ n = 0;
+ items = self->ob_item;
+ if ((self->ob_descr->itemsize != 0) &&
+ (Py_SIZE(self) > PY_SSIZE_T_MAX / self->ob_descr->itemsize)) {
+ return PyErr_NoMemory();
+ }
+ size = Py_SIZE(self) * self->ob_descr->itemsize;
+ if (n == 0) {
+ PyMem_FREE(items);
+ self->ob_item = NULL;
+ Py_SIZE(self) = 0;
+ self->allocated = 0;
+ }
+ else {
+ if (size > PY_SSIZE_T_MAX / n) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(items, char, n * size);
+ if (items == NULL)
+ return PyErr_NoMemory();
+ p = items;
+ for (i = 1; i < n; i++) {
+ p += size;
+ memcpy(p, items, size);
+ }
+ self->ob_item = items;
+ Py_SIZE(self) *= n;
+ self->allocated = Py_SIZE(self);
+ }
+ }
+ Py_INCREF(self);
+ return (PyObject *)self;
}
static PyObject *
ins(arrayobject *self, Py_ssize_t where, PyObject *v)
{
- if (ins1(self, where, v) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (ins1(self, where, v) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
array_count(arrayobject *self, PyObject *v)
{
- Py_ssize_t count = 0;
- Py_ssize_t i;
+ Py_ssize_t count = 0;
+ Py_ssize_t i;
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self, i);
- int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- if (cmp > 0)
- count++;
- else if (cmp < 0)
- return NULL;
- }
- return PyInt_FromSsize_t(count);
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self, i);
+ int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ if (cmp > 0)
+ count++;
+ else if (cmp < 0)
+ return NULL;
+ }
+ return PyInt_FromSsize_t(count);
}
PyDoc_STRVAR(count_doc,
@@ -940,20 +940,20 @@ Return number of occurrences of x in the array.");
static PyObject *
array_index(arrayobject *self, PyObject *v)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self, i);
- int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- if (cmp > 0) {
- return PyInt_FromLong((long)i);
- }
- else if (cmp < 0)
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
- return NULL;
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self, i);
+ int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ if (cmp > 0) {
+ return PyInt_FromLong((long)i);
+ }
+ else if (cmp < 0)
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "array.index(x): x not in list");
+ return NULL;
}
PyDoc_STRVAR(index_doc,
@@ -964,38 +964,38 @@ Return index of first occurrence of x in the array.");
static int
array_contains(arrayobject *self, PyObject *v)
{
- Py_ssize_t i;
- int cmp;
+ Py_ssize_t i;
+ int cmp;
- for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self, i);
- cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- }
- return cmp;
+ for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self, i);
+ cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ }
+ return cmp;
}
static PyObject *
array_remove(arrayobject *self, PyObject *v)
{
- int i;
-
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *selfi = getarrayitem((PyObject *)self,i);
- int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
- Py_DECREF(selfi);
- if (cmp > 0) {
- if (array_ass_slice(self, i, i+1,
- (PyObject *)NULL) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
- }
- else if (cmp < 0)
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
- return NULL;
+ int i;
+
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *selfi = getarrayitem((PyObject *)self,i);
+ int cmp = PyObject_RichCompareBool(selfi, v, Py_EQ);
+ Py_DECREF(selfi);
+ if (cmp > 0) {
+ if (array_ass_slice(self, i, i+1,
+ (PyObject *)NULL) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else if (cmp < 0)
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "array.remove(x): x not in list");
+ return NULL;
}
PyDoc_STRVAR(remove_doc,
@@ -1006,27 +1006,27 @@ Remove the first occurrence of x in the array.");
static PyObject *
array_pop(arrayobject *self, PyObject *args)
{
- Py_ssize_t i = -1;
- PyObject *v;
- if (!PyArg_ParseTuple(args, "|n:pop", &i))
- return NULL;
- if (Py_SIZE(self) == 0) {
- /* Special-case most common failure cause */
- PyErr_SetString(PyExc_IndexError, "pop from empty array");
- return NULL;
- }
- if (i < 0)
- i += Py_SIZE(self);
- if (i < 0 || i >= Py_SIZE(self)) {
- PyErr_SetString(PyExc_IndexError, "pop index out of range");
- return NULL;
- }
- v = getarrayitem((PyObject *)self,i);
- if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
- Py_DECREF(v);
- return NULL;
- }
- return v;
+ Py_ssize_t i = -1;
+ PyObject *v;
+ if (!PyArg_ParseTuple(args, "|n:pop", &i))
+ return NULL;
+ if (Py_SIZE(self) == 0) {
+ /* Special-case most common failure cause */
+ PyErr_SetString(PyExc_IndexError, "pop from empty array");
+ return NULL;
+ }
+ if (i < 0)
+ i += Py_SIZE(self);
+ if (i < 0 || i >= Py_SIZE(self)) {
+ PyErr_SetString(PyExc_IndexError, "pop index out of range");
+ return NULL;
+ }
+ v = getarrayitem((PyObject *)self,i);
+ if (array_ass_slice(self, i, i+1, (PyObject *)NULL) != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ return v;
}
PyDoc_STRVAR(pop_doc,
@@ -1037,10 +1037,10 @@ Return the i-th element and delete it from the array. i defaults to -1.");
static PyObject *
array_extend(arrayobject *self, PyObject *bb)
{
- if (array_do_extend(self, bb) == -1)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (array_do_extend(self, bb) == -1)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(extend_doc,
@@ -1051,11 +1051,11 @@ PyDoc_STRVAR(extend_doc,
static PyObject *
array_insert(arrayobject *self, PyObject *args)
{
- Py_ssize_t i;
- PyObject *v;
- if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
- return NULL;
- return ins(self, i, v);
+ Py_ssize_t i;
+ PyObject *v;
+ if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
+ return NULL;
+ return ins(self, i, v);
}
PyDoc_STRVAR(insert_doc,
@@ -1067,15 +1067,15 @@ Insert a new item x into the array before position i.");
static PyObject *
array_buffer_info(arrayobject *self, PyObject *unused)
{
- PyObject* retval = NULL;
- retval = PyTuple_New(2);
- if (!retval)
- return NULL;
+ PyObject* retval = NULL;
+ retval = PyTuple_New(2);
+ if (!retval)
+ return NULL;
- PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
- PyTuple_SET_ITEM(retval, 1, PyInt_FromLong((long)(Py_SIZE(self))));
+ PyTuple_SET_ITEM(retval, 0, PyLong_FromVoidPtr(self->ob_item));
+ PyTuple_SET_ITEM(retval, 1, PyInt_FromLong((long)(Py_SIZE(self))));
- return retval;
+ return retval;
}
PyDoc_STRVAR(buffer_info_doc,
@@ -1090,7 +1090,7 @@ the buffer length in bytes.");
static PyObject *
array_append(arrayobject *self, PyObject *v)
{
- return ins(self, (int) Py_SIZE(self), v);
+ return ins(self, (int) Py_SIZE(self), v);
}
PyDoc_STRVAR(append_doc,
@@ -1102,52 +1102,52 @@ Append new value x to the end of the array.");
static PyObject *
array_byteswap(arrayobject *self, PyObject *unused)
{
- char *p;
- Py_ssize_t i;
-
- switch (self->ob_descr->itemsize) {
- case 1:
- break;
- case 2:
- for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
- char p0 = p[0];
- p[0] = p[1];
- p[1] = p0;
- }
- break;
- case 4:
- for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
- char p0 = p[0];
- char p1 = p[1];
- p[0] = p[3];
- p[1] = p[2];
- p[2] = p1;
- p[3] = p0;
- }
- break;
- case 8:
- for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
- char p0 = p[0];
- char p1 = p[1];
- char p2 = p[2];
- char p3 = p[3];
- p[0] = p[7];
- p[1] = p[6];
- p[2] = p[5];
- p[3] = p[4];
- p[4] = p3;
- p[5] = p2;
- p[6] = p1;
- p[7] = p0;
- }
- break;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "don't know how to byteswap this array type");
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ char *p;
+ Py_ssize_t i;
+
+ switch (self->ob_descr->itemsize) {
+ case 1:
+ break;
+ case 2:
+ for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 2) {
+ char p0 = p[0];
+ p[0] = p[1];
+ p[1] = p0;
+ }
+ break;
+ case 4:
+ for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 4) {
+ char p0 = p[0];
+ char p1 = p[1];
+ p[0] = p[3];
+ p[1] = p[2];
+ p[2] = p1;
+ p[3] = p0;
+ }
+ break;
+ case 8:
+ for (p = self->ob_item, i = Py_SIZE(self); --i >= 0; p += 8) {
+ char p0 = p[0];
+ char p1 = p[1];
+ char p2 = p[2];
+ char p3 = p[3];
+ p[0] = p[7];
+ p[1] = p[6];
+ p[2] = p[5];
+ p[3] = p[4];
+ p[4] = p3;
+ p[5] = p2;
+ p[6] = p1;
+ p[7] = p0;
+ }
+ break;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "don't know how to byteswap this array type");
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(byteswap_doc,
@@ -1159,28 +1159,28 @@ Byteswap all items of the array. If the items in the array are not 1, 2,\n\
static PyObject *
array_reverse(arrayobject *self, PyObject *unused)
{
- register Py_ssize_t itemsize = self->ob_descr->itemsize;
- register char *p, *q;
- /* little buffer to hold items while swapping */
- char tmp[256]; /* 8 is probably enough -- but why skimp */
- assert((size_t)itemsize <= sizeof(tmp));
-
- if (Py_SIZE(self) > 1) {
- for (p = self->ob_item,
- q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
- p < q;
- p += itemsize, q -= itemsize) {
- /* memory areas guaranteed disjoint, so memcpy
- * is safe (& memmove may be slower).
- */
- memcpy(tmp, p, itemsize);
- memcpy(p, q, itemsize);
- memcpy(q, tmp, itemsize);
- }
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ register Py_ssize_t itemsize = self->ob_descr->itemsize;
+ register char *p, *q;
+ /* little buffer to hold items while swapping */
+ char tmp[256]; /* 8 is probably enough -- but why skimp */
+ assert((size_t)itemsize <= sizeof(tmp));
+
+ if (Py_SIZE(self) > 1) {
+ for (p = self->ob_item,
+ q = self->ob_item + (Py_SIZE(self) - 1)*itemsize;
+ p < q;
+ p += itemsize, q -= itemsize) {
+ /* memory areas guaranteed disjoint, so memcpy
+ * is safe (& memmove may be slower).
+ */
+ memcpy(tmp, p, itemsize);
+ memcpy(p, q, itemsize);
+ memcpy(q, tmp, itemsize);
+ }
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(reverse_doc,
@@ -1191,50 +1191,50 @@ Reverse the order of the items in the array.");
static PyObject *
array_fromfile(arrayobject *self, PyObject *args)
{
- PyObject *f;
- Py_ssize_t n;
- FILE *fp;
- if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
- return NULL;
- fp = PyFile_AsFile(f);
- if (fp == NULL) {
- PyErr_SetString(PyExc_TypeError, "arg1 must be open file");
- return NULL;
- }
- if (n > 0) {
- char *item = self->ob_item;
- Py_ssize_t itemsize = self->ob_descr->itemsize;
- size_t nread;
- Py_ssize_t newlength;
- size_t newbytes;
- /* Be careful here about overflow */
- if ((newlength = Py_SIZE(self) + n) <= 0 ||
- (newbytes = newlength * itemsize) / itemsize !=
- (size_t)newlength)
- goto nomem;
- PyMem_RESIZE(item, char, newbytes);
- if (item == NULL) {
- nomem:
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- nread = fread(item + (Py_SIZE(self) - n) * itemsize,
- itemsize, n, fp);
- if (nread < (size_t)n) {
- Py_SIZE(self) -= (n - nread);
- PyMem_RESIZE(item, char, Py_SIZE(self)*itemsize);
- self->ob_item = item;
- self->allocated = Py_SIZE(self);
- PyErr_SetString(PyExc_EOFError,
- "not enough items in file");
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *f;
+ Py_ssize_t n;
+ FILE *fp;
+ if (!PyArg_ParseTuple(args, "On:fromfile", &f, &n))
+ return NULL;
+ fp = PyFile_AsFile(f);
+ if (fp == NULL) {
+ PyErr_SetString(PyExc_TypeError, "arg1 must be open file");
+ return NULL;
+ }
+ if (n > 0) {
+ char *item = self->ob_item;
+ Py_ssize_t itemsize = self->ob_descr->itemsize;
+ size_t nread;
+ Py_ssize_t newlength;
+ size_t newbytes;
+ /* Be careful here about overflow */
+ if ((newlength = Py_SIZE(self) + n) <= 0 ||
+ (newbytes = newlength * itemsize) / itemsize !=
+ (size_t)newlength)
+ goto nomem;
+ PyMem_RESIZE(item, char, newbytes);
+ if (item == NULL) {
+ nomem:
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ nread = fread(item + (Py_SIZE(self) - n) * itemsize,
+ itemsize, n, fp);
+ if (nread < (size_t)n) {
+ Py_SIZE(self) -= (n - nread);
+ PyMem_RESIZE(item, char, Py_SIZE(self)*itemsize);
+ self->ob_item = item;
+ self->allocated = Py_SIZE(self);
+ PyErr_SetString(PyExc_EOFError,
+ "not enough items in file");
+ return NULL;
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromfile_doc,
@@ -1247,33 +1247,33 @@ array. Also called as read.");
static PyObject *
array_fromfile_as_read(arrayobject *self, PyObject *args)
{
- if (PyErr_WarnPy3k("array.read() not supported in 3.x; "
- "use array.fromfile()", 1) < 0)
- return NULL;
- return array_fromfile(self, args);
+ if (PyErr_WarnPy3k("array.read() not supported in 3.x; "
+ "use array.fromfile()", 1) < 0)
+ return NULL;
+ return array_fromfile(self, args);
}
static PyObject *
array_tofile(arrayobject *self, PyObject *f)
{
- FILE *fp;
-
- fp = PyFile_AsFile(f);
- if (fp == NULL) {
- PyErr_SetString(PyExc_TypeError, "arg must be open file");
- return NULL;
- }
- if (self->ob_size > 0) {
- if (fwrite(self->ob_item, self->ob_descr->itemsize,
- self->ob_size, fp) != (size_t)self->ob_size) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(fp);
- return NULL;
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ FILE *fp;
+
+ fp = PyFile_AsFile(f);
+ if (fp == NULL) {
+ PyErr_SetString(PyExc_TypeError, "arg must be open file");
+ return NULL;
+ }
+ if (self->ob_size > 0) {
+ if (fwrite(self->ob_item, self->ob_descr->itemsize,
+ self->ob_size, fp) != (size_t)self->ob_size) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(fp);
+ return NULL;
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(tofile_doc,
@@ -1286,53 +1286,53 @@ write.");
static PyObject *
array_tofile_as_write(arrayobject *self, PyObject *f)
{
- if (PyErr_WarnPy3k("array.write() not supported in 3.x; "
- "use array.tofile()", 1) < 0)
- return NULL;
- return array_tofile(self, f);
+ if (PyErr_WarnPy3k("array.write() not supported in 3.x; "
+ "use array.tofile()", 1) < 0)
+ return NULL;
+ return array_tofile(self, f);
}
static PyObject *
array_fromlist(arrayobject *self, PyObject *list)
{
- Py_ssize_t n;
- Py_ssize_t itemsize = self->ob_descr->itemsize;
-
- if (!PyList_Check(list)) {
- PyErr_SetString(PyExc_TypeError, "arg must be list");
- return NULL;
- }
- n = PyList_Size(list);
- if (n > 0) {
- char *item = self->ob_item;
- Py_ssize_t i;
- PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
- if (item == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- for (i = 0; i < n; i++) {
- PyObject *v = PyList_GetItem(list, i);
- if ((*self->ob_descr->setitem)(self,
- Py_SIZE(self) - n + i, v) != 0) {
- Py_SIZE(self) -= n;
- if (itemsize && (self->ob_size > PY_SSIZE_T_MAX / itemsize)) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(item, char,
- Py_SIZE(self) * itemsize);
- self->ob_item = item;
- self->allocated = Py_SIZE(self);
- return NULL;
- }
- }
- }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t n;
+ Py_ssize_t itemsize = self->ob_descr->itemsize;
+
+ if (!PyList_Check(list)) {
+ PyErr_SetString(PyExc_TypeError, "arg must be list");
+ return NULL;
+ }
+ n = PyList_Size(list);
+ if (n > 0) {
+ char *item = self->ob_item;
+ Py_ssize_t i;
+ PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ for (i = 0; i < n; i++) {
+ PyObject *v = PyList_GetItem(list, i);
+ if ((*self->ob_descr->setitem)(self,
+ Py_SIZE(self) - n + i, v) != 0) {
+ Py_SIZE(self) -= n;
+ if (itemsize && (self->ob_size > PY_SSIZE_T_MAX / itemsize)) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(item, char,
+ Py_SIZE(self) * itemsize);
+ self->ob_item = item;
+ self->allocated = Py_SIZE(self);
+ return NULL;
+ }
+ }
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromlist_doc,
@@ -1344,20 +1344,20 @@ Append items to array from list.");
static PyObject *
array_tolist(arrayobject *self, PyObject *unused)
{
- PyObject *list = PyList_New(Py_SIZE(self));
- Py_ssize_t i;
+ PyObject *list = PyList_New(Py_SIZE(self));
+ Py_ssize_t i;
- if (list == NULL)
- return NULL;
- for (i = 0; i < Py_SIZE(self); i++) {
- PyObject *v = getarrayitem((PyObject *)self, i);
- if (v == NULL) {
- Py_DECREF(list);
- return NULL;
- }
- PyList_SetItem(list, i, v);
- }
- return list;
+ if (list == NULL)
+ return NULL;
+ for (i = 0; i < Py_SIZE(self); i++) {
+ PyObject *v = getarrayitem((PyObject *)self, i);
+ if (v == NULL) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ PyList_SetItem(list, i, v);
+ }
+ return list;
}
PyDoc_STRVAR(tolist_doc,
@@ -1369,36 +1369,36 @@ Convert array to an ordinary list with the same items.");
static PyObject *
array_fromstring(arrayobject *self, PyObject *args)
{
- char *str;
- Py_ssize_t n;
- int itemsize = self->ob_descr->itemsize;
- if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n))
- return NULL;
- if (n % itemsize != 0) {
- PyErr_SetString(PyExc_ValueError,
- "string length not a multiple of item size");
- return NULL;
- }
- n = n / itemsize;
- if (n > 0) {
- char *item = self->ob_item;
- if ((n > PY_SSIZE_T_MAX - Py_SIZE(self)) ||
- ((Py_SIZE(self) + n) > PY_SSIZE_T_MAX / itemsize)) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
- if (item == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- memcpy(item + (Py_SIZE(self) - n) * itemsize,
- str, itemsize*n);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ Py_ssize_t n;
+ int itemsize = self->ob_descr->itemsize;
+ if (!PyArg_ParseTuple(args, "s#:fromstring", &str, &n))
+ return NULL;
+ if (n % itemsize != 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "string length not a multiple of item size");
+ return NULL;
+ }
+ n = n / itemsize;
+ if (n > 0) {
+ char *item = self->ob_item;
+ if ((n > PY_SSIZE_T_MAX - Py_SIZE(self)) ||
+ ((Py_SIZE(self) + n) > PY_SSIZE_T_MAX / itemsize)) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(item, char, (Py_SIZE(self) + n) * itemsize);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ memcpy(item + (Py_SIZE(self) - n) * itemsize,
+ str, itemsize*n);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromstring_doc,
@@ -1411,12 +1411,12 @@ values,as if it had been read from a file using the fromfile() method).");
static PyObject *
array_tostring(arrayobject *self, PyObject *unused)
{
- if (self->ob_size <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
- return PyString_FromStringAndSize(self->ob_item,
- Py_SIZE(self) * self->ob_descr->itemsize);
- } else {
- return PyErr_NoMemory();
- }
+ if (self->ob_size <= PY_SSIZE_T_MAX / self->ob_descr->itemsize) {
+ return PyString_FromStringAndSize(self->ob_item,
+ Py_SIZE(self) * self->ob_descr->itemsize);
+ } else {
+ return PyErr_NoMemory();
+ }
}
PyDoc_STRVAR(tostring_doc,
@@ -1431,36 +1431,36 @@ representation.");
static PyObject *
array_fromunicode(arrayobject *self, PyObject *args)
{
- Py_UNICODE *ustr;
- Py_ssize_t n;
-
- if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
- return NULL;
- if (self->ob_descr->typecode != 'u') {
- PyErr_SetString(PyExc_ValueError,
- "fromunicode() may only be called on "
- "type 'u' arrays");
- return NULL;
- }
- if (n > 0) {
- Py_UNICODE *item = (Py_UNICODE *) self->ob_item;
- if (Py_SIZE(self) > PY_SSIZE_T_MAX - n) {
- return PyErr_NoMemory();
- }
- PyMem_RESIZE(item, Py_UNICODE, Py_SIZE(self) + n);
- if (item == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- self->ob_item = (char *) item;
- Py_SIZE(self) += n;
- self->allocated = Py_SIZE(self);
- memcpy(item + Py_SIZE(self) - n,
- ustr, n * sizeof(Py_UNICODE));
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_UNICODE *ustr;
+ Py_ssize_t n;
+
+ if (!PyArg_ParseTuple(args, "u#:fromunicode", &ustr, &n))
+ return NULL;
+ if (self->ob_descr->typecode != 'u') {
+ PyErr_SetString(PyExc_ValueError,
+ "fromunicode() may only be called on "
+ "type 'u' arrays");
+ return NULL;
+ }
+ if (n > 0) {
+ Py_UNICODE *item = (Py_UNICODE *) self->ob_item;
+ if (Py_SIZE(self) > PY_SSIZE_T_MAX - n) {
+ return PyErr_NoMemory();
+ }
+ PyMem_RESIZE(item, Py_UNICODE, Py_SIZE(self) + n);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ self->ob_item = (char *) item;
+ Py_SIZE(self) += n;
+ self->allocated = Py_SIZE(self);
+ memcpy(item + Py_SIZE(self) - n,
+ ustr, n * sizeof(Py_UNICODE));
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(fromunicode_doc,
@@ -1475,12 +1475,12 @@ append Unicode data to an array of some other type.");
static PyObject *
array_tounicode(arrayobject *self, PyObject *unused)
{
- if (self->ob_descr->typecode != 'u') {
- PyErr_SetString(PyExc_ValueError,
- "tounicode() may only be called on type 'u' arrays");
- return NULL;
- }
- return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
+ if (self->ob_descr->typecode != 'u') {
+ PyErr_SetString(PyExc_ValueError,
+ "tounicode() may only be called on type 'u' arrays");
+ return NULL;
+ }
+ return PyUnicode_FromUnicode((Py_UNICODE *) self->ob_item, Py_SIZE(self));
}
PyDoc_STRVAR(tounicode_doc,
@@ -1496,32 +1496,32 @@ an array of some other type.");
static PyObject *
array_reduce(arrayobject *array)
{
- PyObject *dict, *result, *list;
-
- dict = PyObject_GetAttrString((PyObject *)array, "__dict__");
- if (dict == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- dict = Py_None;
- Py_INCREF(dict);
- }
- /* Unlike in Python 3.x, we never use the more efficient memory
- * representation of an array for pickling. This is unfortunately
- * necessary to allow array objects to be unpickled by Python 3.x,
- * since str objects from 2.x are always decoded to unicode in
- * Python 3.x.
- */
- list = array_tolist(array, NULL);
- if (list == NULL) {
- Py_DECREF(dict);
- return NULL;
- }
- result = Py_BuildValue(
- "O(cO)O", Py_TYPE(array), array->ob_descr->typecode, list, dict);
- Py_DECREF(list);
- Py_DECREF(dict);
- return result;
+ PyObject *dict, *result, *list;
+
+ dict = PyObject_GetAttrString((PyObject *)array, "__dict__");
+ if (dict == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ dict = Py_None;
+ Py_INCREF(dict);
+ }
+ /* Unlike in Python 3.x, we never use the more efficient memory
+ * representation of an array for pickling. This is unfortunately
+ * necessary to allow array objects to be unpickled by Python 3.x,
+ * since str objects from 2.x are always decoded to unicode in
+ * Python 3.x.
+ */
+ list = array_tolist(array, NULL);
+ if (list == NULL) {
+ Py_DECREF(dict);
+ return NULL;
+ }
+ result = Py_BuildValue(
+ "O(cO)O", Py_TYPE(array), array->ob_descr->typecode, list, dict);
+ Py_DECREF(list);
+ Py_DECREF(dict);
+ return result;
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
@@ -1529,321 +1529,321 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyObject *
array_get_typecode(arrayobject *a, void *closure)
{
- char tc = a->ob_descr->typecode;
- return PyString_FromStringAndSize(&tc, 1);
+ char tc = a->ob_descr->typecode;
+ return PyString_FromStringAndSize(&tc, 1);
}
static PyObject *
array_get_itemsize(arrayobject *a, void *closure)
{
- return PyInt_FromLong((long)a->ob_descr->itemsize);
+ return PyInt_FromLong((long)a->ob_descr->itemsize);
}
static PyGetSetDef array_getsets [] = {
- {"typecode", (getter) array_get_typecode, NULL,
- "the typecode character used to create the array"},
- {"itemsize", (getter) array_get_itemsize, NULL,
- "the size, in bytes, of one array item"},
- {NULL}
+ {"typecode", (getter) array_get_typecode, NULL,
+ "the typecode character used to create the array"},
+ {"itemsize", (getter) array_get_itemsize, NULL,
+ "the size, in bytes, of one array item"},
+ {NULL}
};
static PyMethodDef array_methods[] = {
- {"append", (PyCFunction)array_append, METH_O,
- append_doc},
- {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
- buffer_info_doc},
- {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
- byteswap_doc},
- {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
- copy_doc},
- {"count", (PyCFunction)array_count, METH_O,
- count_doc},
- {"__deepcopy__",(PyCFunction)array_copy, METH_O,
- copy_doc},
- {"extend", (PyCFunction)array_extend, METH_O,
- extend_doc},
- {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
- fromfile_doc},
- {"fromlist", (PyCFunction)array_fromlist, METH_O,
- fromlist_doc},
- {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
- fromstring_doc},
+ {"append", (PyCFunction)array_append, METH_O,
+ append_doc},
+ {"buffer_info", (PyCFunction)array_buffer_info, METH_NOARGS,
+ buffer_info_doc},
+ {"byteswap", (PyCFunction)array_byteswap, METH_NOARGS,
+ byteswap_doc},
+ {"__copy__", (PyCFunction)array_copy, METH_NOARGS,
+ copy_doc},
+ {"count", (PyCFunction)array_count, METH_O,
+ count_doc},
+ {"__deepcopy__",(PyCFunction)array_copy, METH_O,
+ copy_doc},
+ {"extend", (PyCFunction)array_extend, METH_O,
+ extend_doc},
+ {"fromfile", (PyCFunction)array_fromfile, METH_VARARGS,
+ fromfile_doc},
+ {"fromlist", (PyCFunction)array_fromlist, METH_O,
+ fromlist_doc},
+ {"fromstring", (PyCFunction)array_fromstring, METH_VARARGS,
+ fromstring_doc},
#ifdef Py_USING_UNICODE
- {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
- fromunicode_doc},
+ {"fromunicode", (PyCFunction)array_fromunicode, METH_VARARGS,
+ fromunicode_doc},
#endif
- {"index", (PyCFunction)array_index, METH_O,
- index_doc},
- {"insert", (PyCFunction)array_insert, METH_VARARGS,
- insert_doc},
- {"pop", (PyCFunction)array_pop, METH_VARARGS,
- pop_doc},
- {"read", (PyCFunction)array_fromfile_as_read, METH_VARARGS,
- fromfile_doc},
- {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS,
- reduce_doc},
- {"remove", (PyCFunction)array_remove, METH_O,
- remove_doc},
- {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
- reverse_doc},
-/* {"sort", (PyCFunction)array_sort, METH_VARARGS,
- sort_doc},*/
- {"tofile", (PyCFunction)array_tofile, METH_O,
- tofile_doc},
- {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
- tolist_doc},
- {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
- tostring_doc},
+ {"index", (PyCFunction)array_index, METH_O,
+ index_doc},
+ {"insert", (PyCFunction)array_insert, METH_VARARGS,
+ insert_doc},
+ {"pop", (PyCFunction)array_pop, METH_VARARGS,
+ pop_doc},
+ {"read", (PyCFunction)array_fromfile_as_read, METH_VARARGS,
+ fromfile_doc},
+ {"__reduce__", (PyCFunction)array_reduce, METH_NOARGS,
+ reduce_doc},
+ {"remove", (PyCFunction)array_remove, METH_O,
+ remove_doc},
+ {"reverse", (PyCFunction)array_reverse, METH_NOARGS,
+ reverse_doc},
+/* {"sort", (PyCFunction)array_sort, METH_VARARGS,
+ sort_doc},*/
+ {"tofile", (PyCFunction)array_tofile, METH_O,
+ tofile_doc},
+ {"tolist", (PyCFunction)array_tolist, METH_NOARGS,
+ tolist_doc},
+ {"tostring", (PyCFunction)array_tostring, METH_NOARGS,
+ tostring_doc},
#ifdef Py_USING_UNICODE
- {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
- tounicode_doc},
+ {"tounicode", (PyCFunction)array_tounicode, METH_NOARGS,
+ tounicode_doc},
#endif
- {"write", (PyCFunction)array_tofile_as_write, METH_O,
- tofile_doc},
- {NULL, NULL} /* sentinel */
+ {"write", (PyCFunction)array_tofile_as_write, METH_O,
+ tofile_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
array_repr(arrayobject *a)
{
- char buf[256], typecode;
- PyObject *s, *t, *v = NULL;
- Py_ssize_t len;
-
- len = Py_SIZE(a);
- typecode = a->ob_descr->typecode;
- if (len == 0) {
- PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode);
- return PyString_FromString(buf);
- }
-
- if (typecode == 'c')
- v = array_tostring(a, NULL);
+ char buf[256], typecode;
+ PyObject *s, *t, *v = NULL;
+ Py_ssize_t len;
+
+ len = Py_SIZE(a);
+ typecode = a->ob_descr->typecode;
+ if (len == 0) {
+ PyOS_snprintf(buf, sizeof(buf), "array('%c')", typecode);
+ return PyString_FromString(buf);
+ }
+
+ if (typecode == 'c')
+ v = array_tostring(a, NULL);
#ifdef Py_USING_UNICODE
- else if (typecode == 'u')
- v = array_tounicode(a, NULL);
+ else if (typecode == 'u')
+ v = array_tounicode(a, NULL);
#endif
- else
- v = array_tolist(a, NULL);
- t = PyObject_Repr(v);
- Py_XDECREF(v);
+ else
+ v = array_tolist(a, NULL);
+ t = PyObject_Repr(v);
+ Py_XDECREF(v);
- PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
- s = PyString_FromString(buf);
- PyString_ConcatAndDel(&s, t);
- PyString_ConcatAndDel(&s, PyString_FromString(")"));
- return s;
+ PyOS_snprintf(buf, sizeof(buf), "array('%c', ", typecode);
+ s = PyString_FromString(buf);
+ PyString_ConcatAndDel(&s, t);
+ PyString_ConcatAndDel(&s, PyString_FromString(")"));
+ return s;
}
static PyObject*
array_subscr(arrayobject* self, PyObject* item)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i==-1 && PyErr_Occurred()) {
- return NULL;
- }
- if (i < 0)
- i += Py_SIZE(self);
- return array_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength, cur, i;
- PyObject* result;
- arrayobject* ar;
- int itemsize = self->ob_descr->itemsize;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
- &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return newarrayobject(&Arraytype, 0, self->ob_descr);
- }
- else if (step == 1) {
- PyObject *result = newarrayobject(&Arraytype,
- slicelength, self->ob_descr);
- if (result == NULL)
- return NULL;
- memcpy(((arrayobject *)result)->ob_item,
- self->ob_item + start * itemsize,
- slicelength * itemsize);
- return result;
- }
- else {
- result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
- if (!result) return NULL;
-
- ar = (arrayobject*)result;
-
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- memcpy(ar->ob_item + i*itemsize,
- self->ob_item + cur*itemsize,
- itemsize);
- }
-
- return result;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "array indices must be integers");
- return NULL;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i==-1 && PyErr_Occurred()) {
+ return NULL;
+ }
+ if (i < 0)
+ i += Py_SIZE(self);
+ return array_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength, cur, i;
+ PyObject* result;
+ arrayobject* ar;
+ int itemsize = self->ob_descr->itemsize;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+ &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return newarrayobject(&Arraytype, 0, self->ob_descr);
+ }
+ else if (step == 1) {
+ PyObject *result = newarrayobject(&Arraytype,
+ slicelength, self->ob_descr);
+ if (result == NULL)
+ return NULL;
+ memcpy(((arrayobject *)result)->ob_item,
+ self->ob_item + start * itemsize,
+ slicelength * itemsize);
+ return result;
+ }
+ else {
+ result = newarrayobject(&Arraytype, slicelength, self->ob_descr);
+ if (!result) return NULL;
+
+ ar = (arrayobject*)result;
+
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ memcpy(ar->ob_item + i*itemsize,
+ self->ob_item + cur*itemsize,
+ itemsize);
+ }
+
+ return result;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "array indices must be integers");
+ return NULL;
+ }
}
static int
array_ass_subscr(arrayobject* self, PyObject* item, PyObject* value)
{
- Py_ssize_t start, stop, step, slicelength, needed;
- arrayobject* other;
- int itemsize;
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
-
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += Py_SIZE(self);
- if (i < 0 || i >= Py_SIZE(self)) {
- PyErr_SetString(PyExc_IndexError,
- "array assignment index out of range");
- return -1;
- }
- if (value == NULL) {
- /* Fall through to slice assignment */
- start = i;
- stop = i + 1;
- step = 1;
- slicelength = 1;
- }
- else
- return (*self->ob_descr->setitem)(self, i, value);
- }
- else if (PySlice_Check(item)) {
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- Py_SIZE(self), &start, &stop,
- &step, &slicelength) < 0) {
- return -1;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "array indices must be integer");
- return -1;
- }
- if (value == NULL) {
- other = NULL;
- needed = 0;
- }
- else if (array_Check(value)) {
- other = (arrayobject *)value;
- needed = Py_SIZE(other);
- if (self == other) {
- /* Special case "self[i:j] = self" -- copy self first */
- int ret;
- value = array_slice(other, 0, needed);
- if (value == NULL)
- return -1;
- ret = array_ass_subscr(self, item, value);
- Py_DECREF(value);
- return ret;
- }
- if (other->ob_descr != self->ob_descr) {
- PyErr_BadArgument();
- return -1;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "can only assign array (not \"%.200s\") to array slice",
- Py_TYPE(value)->tp_name);
- return -1;
- }
- itemsize = self->ob_descr->itemsize;
- /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
- if ((step > 0 && stop < start) ||
- (step < 0 && stop > start))
- stop = start;
- if (step == 1) {
- if (slicelength > needed) {
- memmove(self->ob_item + (start + needed) * itemsize,
- self->ob_item + stop * itemsize,
- (Py_SIZE(self) - stop) * itemsize);
- if (array_resize(self, Py_SIZE(self) +
- needed - slicelength) < 0)
- return -1;
- }
- else if (slicelength < needed) {
- if (array_resize(self, Py_SIZE(self) +
- needed - slicelength) < 0)
- return -1;
- memmove(self->ob_item + (start + needed) * itemsize,
- self->ob_item + stop * itemsize,
- (Py_SIZE(self) - start - needed) * itemsize);
- }
- if (needed > 0)
- memcpy(self->ob_item + start * itemsize,
- other->ob_item, needed * itemsize);
- return 0;
- }
- else if (needed == 0) {
- /* Delete slice */
- size_t cur;
- Py_ssize_t i;
-
- if (step < 0) {
- stop = start + 1;
- start = stop + step * (slicelength - 1) - 1;
- step = -step;
- }
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- Py_ssize_t lim = step - 1;
-
- if (cur + step >= (size_t)Py_SIZE(self))
- lim = Py_SIZE(self) - cur - 1;
- memmove(self->ob_item + (cur - i) * itemsize,
- self->ob_item + (cur + 1) * itemsize,
- lim * itemsize);
- }
- cur = start + slicelength * step;
- if (cur < (size_t)Py_SIZE(self)) {
- memmove(self->ob_item + (cur-slicelength) * itemsize,
- self->ob_item + cur * itemsize,
- (Py_SIZE(self) - cur) * itemsize);
- }
- if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
- return -1;
- return 0;
- }
- else {
- Py_ssize_t cur, i;
-
- if (needed != slicelength) {
- PyErr_Format(PyExc_ValueError,
- "attempt to assign array of size %zd "
- "to extended slice of size %zd",
- needed, slicelength);
- return -1;
- }
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- memcpy(self->ob_item + cur * itemsize,
- other->ob_item + i * itemsize,
- itemsize);
- }
- return 0;
- }
+ Py_ssize_t start, stop, step, slicelength, needed;
+ arrayobject* other;
+ int itemsize;
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += Py_SIZE(self);
+ if (i < 0 || i >= Py_SIZE(self)) {
+ PyErr_SetString(PyExc_IndexError,
+ "array assignment index out of range");
+ return -1;
+ }
+ if (value == NULL) {
+ /* Fall through to slice assignment */
+ start = i;
+ stop = i + 1;
+ step = 1;
+ slicelength = 1;
+ }
+ else
+ return (*self->ob_descr->setitem)(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ Py_SIZE(self), &start, &stop,
+ &step, &slicelength) < 0) {
+ return -1;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "array indices must be integer");
+ return -1;
+ }
+ if (value == NULL) {
+ other = NULL;
+ needed = 0;
+ }
+ else if (array_Check(value)) {
+ other = (arrayobject *)value;
+ needed = Py_SIZE(other);
+ if (self == other) {
+ /* Special case "self[i:j] = self" -- copy self first */
+ int ret;
+ value = array_slice(other, 0, needed);
+ if (value == NULL)
+ return -1;
+ ret = array_ass_subscr(self, item, value);
+ Py_DECREF(value);
+ return ret;
+ }
+ if (other->ob_descr != self->ob_descr) {
+ PyErr_BadArgument();
+ return -1;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign array (not \"%.200s\") to array slice",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ itemsize = self->ob_descr->itemsize;
+ /* for 'a[2:1] = ...', the insertion point is 'start', not 'stop' */
+ if ((step > 0 && stop < start) ||
+ (step < 0 && stop > start))
+ stop = start;
+ if (step == 1) {
+ if (slicelength > needed) {
+ memmove(self->ob_item + (start + needed) * itemsize,
+ self->ob_item + stop * itemsize,
+ (Py_SIZE(self) - stop) * itemsize);
+ if (array_resize(self, Py_SIZE(self) +
+ needed - slicelength) < 0)
+ return -1;
+ }
+ else if (slicelength < needed) {
+ if (array_resize(self, Py_SIZE(self) +
+ needed - slicelength) < 0)
+ return -1;
+ memmove(self->ob_item + (start + needed) * itemsize,
+ self->ob_item + stop * itemsize,
+ (Py_SIZE(self) - start - needed) * itemsize);
+ }
+ if (needed > 0)
+ memcpy(self->ob_item + start * itemsize,
+ other->ob_item, needed * itemsize);
+ return 0;
+ }
+ else if (needed == 0) {
+ /* Delete slice */
+ size_t cur;
+ Py_ssize_t i;
+
+ if (step < 0) {
+ stop = start + 1;
+ start = stop + step * (slicelength - 1) - 1;
+ step = -step;
+ }
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ Py_ssize_t lim = step - 1;
+
+ if (cur + step >= (size_t)Py_SIZE(self))
+ lim = Py_SIZE(self) - cur - 1;
+ memmove(self->ob_item + (cur - i) * itemsize,
+ self->ob_item + (cur + 1) * itemsize,
+ lim * itemsize);
+ }
+ cur = start + slicelength * step;
+ if (cur < (size_t)Py_SIZE(self)) {
+ memmove(self->ob_item + (cur-slicelength) * itemsize,
+ self->ob_item + cur * itemsize,
+ (Py_SIZE(self) - cur) * itemsize);
+ }
+ if (array_resize(self, Py_SIZE(self) - slicelength) < 0)
+ return -1;
+ return 0;
+ }
+ else {
+ Py_ssize_t cur, i;
+
+ if (needed != slicelength) {
+ PyErr_Format(PyExc_ValueError,
+ "attempt to assign array of size %zd "
+ "to extended slice of size %zd",
+ needed, slicelength);
+ return -1;
+ }
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ memcpy(self->ob_item + cur * itemsize,
+ other->ob_item + i * itemsize,
+ itemsize);
+ }
+ return 0;
+ }
}
static PyMappingMethods array_as_mapping = {
- (lenfunc)array_length,
- (binaryfunc)array_subscr,
- (objobjargproc)array_ass_subscr
+ (lenfunc)array_length,
+ (binaryfunc)array_subscr,
+ (objobjargproc)array_ass_subscr
};
static const void *emptybuf = "";
@@ -1851,164 +1851,164 @@ static const void *emptybuf = "";
static Py_ssize_t
array_buffer_getreadbuf(arrayobject *self, Py_ssize_t index, const void **ptr)
{
- if ( index != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent array segment");
- return -1;
- }
- *ptr = (void *)self->ob_item;
- if (*ptr == NULL)
- *ptr = emptybuf;
- return Py_SIZE(self)*self->ob_descr->itemsize;
+ if ( index != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent array segment");
+ return -1;
+ }
+ *ptr = (void *)self->ob_item;
+ if (*ptr == NULL)
+ *ptr = emptybuf;
+ return Py_SIZE(self)*self->ob_descr->itemsize;
}
static Py_ssize_t
array_buffer_getwritebuf(arrayobject *self, Py_ssize_t index, const void **ptr)
{
- if ( index != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent array segment");
- return -1;
- }
- *ptr = (void *)self->ob_item;
- if (*ptr == NULL)
- *ptr = emptybuf;
- return Py_SIZE(self)*self->ob_descr->itemsize;
+ if ( index != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent array segment");
+ return -1;
+ }
+ *ptr = (void *)self->ob_item;
+ if (*ptr == NULL)
+ *ptr = emptybuf;
+ return Py_SIZE(self)*self->ob_descr->itemsize;
}
static Py_ssize_t
array_buffer_getsegcount(arrayobject *self, Py_ssize_t *lenp)
{
- if ( lenp )
- *lenp = Py_SIZE(self)*self->ob_descr->itemsize;
- return 1;
+ if ( lenp )
+ *lenp = Py_SIZE(self)*self->ob_descr->itemsize;
+ return 1;
}
static PySequenceMethods array_as_sequence = {
- (lenfunc)array_length, /*sq_length*/
- (binaryfunc)array_concat, /*sq_concat*/
- (ssizeargfunc)array_repeat, /*sq_repeat*/
- (ssizeargfunc)array_item, /*sq_item*/
- (ssizessizeargfunc)array_slice, /*sq_slice*/
- (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
- (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/
- (objobjproc)array_contains, /*sq_contains*/
- (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
- (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
+ (lenfunc)array_length, /*sq_length*/
+ (binaryfunc)array_concat, /*sq_concat*/
+ (ssizeargfunc)array_repeat, /*sq_repeat*/
+ (ssizeargfunc)array_item, /*sq_item*/
+ (ssizessizeargfunc)array_slice, /*sq_slice*/
+ (ssizeobjargproc)array_ass_item, /*sq_ass_item*/
+ (ssizessizeobjargproc)array_ass_slice, /*sq_ass_slice*/
+ (objobjproc)array_contains, /*sq_contains*/
+ (binaryfunc)array_inplace_concat, /*sq_inplace_concat*/
+ (ssizeargfunc)array_inplace_repeat /*sq_inplace_repeat*/
};
static PyBufferProcs array_as_buffer = {
- (readbufferproc)array_buffer_getreadbuf,
- (writebufferproc)array_buffer_getwritebuf,
- (segcountproc)array_buffer_getsegcount,
- NULL,
+ (readbufferproc)array_buffer_getreadbuf,
+ (writebufferproc)array_buffer_getwritebuf,
+ (segcountproc)array_buffer_getsegcount,
+ NULL,
};
static PyObject *
array_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- char c;
- PyObject *initial = NULL, *it = NULL;
- struct arraydescr *descr;
-
- if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "c|O:array", &c, &initial))
- return NULL;
-
- if (!(initial == NULL || PyList_Check(initial)
- || PyString_Check(initial) || PyTuple_Check(initial)
- || (c == 'u' && PyUnicode_Check(initial)))) {
- it = PyObject_GetIter(initial);
- if (it == NULL)
- return NULL;
- /* We set initial to NULL so that the subsequent code
- will create an empty array of the appropriate type
- and afterwards we can use array_iter_extend to populate
- the array.
- */
- initial = NULL;
- }
- for (descr = descriptors; descr->typecode != '\0'; descr++) {
- if (descr->typecode == c) {
- PyObject *a;
- Py_ssize_t len;
-
- if (initial == NULL || !(PyList_Check(initial)
- || PyTuple_Check(initial)))
- len = 0;
- else
- len = PySequence_Size(initial);
-
- a = newarrayobject(type, len, descr);
- if (a == NULL)
- return NULL;
-
- if (len > 0) {
- Py_ssize_t i;
- for (i = 0; i < len; i++) {
- PyObject *v =
- PySequence_GetItem(initial, i);
- if (v == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- if (setarrayitem(a, i, v) != 0) {
- Py_DECREF(v);
- Py_DECREF(a);
- return NULL;
- }
- Py_DECREF(v);
- }
- } else if (initial != NULL && PyString_Check(initial)) {
- PyObject *t_initial, *v;
- t_initial = PyTuple_Pack(1, initial);
- if (t_initial == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- v = array_fromstring((arrayobject *)a,
- t_initial);
- Py_DECREF(t_initial);
- if (v == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- Py_DECREF(v);
+ char c;
+ PyObject *initial = NULL, *it = NULL;
+ struct arraydescr *descr;
+
+ if (type == &Arraytype && !_PyArg_NoKeywords("array.array()", kwds))
+ return NULL;
+
+ if (!PyArg_ParseTuple(args, "c|O:array", &c, &initial))
+ return NULL;
+
+ if (!(initial == NULL || PyList_Check(initial)
+ || PyString_Check(initial) || PyTuple_Check(initial)
+ || (c == 'u' && PyUnicode_Check(initial)))) {
+ it = PyObject_GetIter(initial);
+ if (it == NULL)
+ return NULL;
+ /* We set initial to NULL so that the subsequent code
+ will create an empty array of the appropriate type
+ and afterwards we can use array_iter_extend to populate
+ the array.
+ */
+ initial = NULL;
+ }
+ for (descr = descriptors; descr->typecode != '\0'; descr++) {
+ if (descr->typecode == c) {
+ PyObject *a;
+ Py_ssize_t len;
+
+ if (initial == NULL || !(PyList_Check(initial)
+ || PyTuple_Check(initial)))
+ len = 0;
+ else
+ len = PySequence_Size(initial);
+
+ a = newarrayobject(type, len, descr);
+ if (a == NULL)
+ return NULL;
+
+ if (len > 0) {
+ Py_ssize_t i;
+ for (i = 0; i < len; i++) {
+ PyObject *v =
+ PySequence_GetItem(initial, i);
+ if (v == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ if (setarrayitem(a, i, v) != 0) {
+ Py_DECREF(v);
+ Py_DECREF(a);
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ } else if (initial != NULL && PyString_Check(initial)) {
+ PyObject *t_initial, *v;
+ t_initial = PyTuple_Pack(1, initial);
+ if (t_initial == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ v = array_fromstring((arrayobject *)a,
+ t_initial);
+ Py_DECREF(t_initial);
+ if (v == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ Py_DECREF(v);
#ifdef Py_USING_UNICODE
- } else if (initial != NULL && PyUnicode_Check(initial)) {
- Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial);
- if (n > 0) {
- arrayobject *self = (arrayobject *)a;
- char *item = self->ob_item;
- item = (char *)PyMem_Realloc(item, n);
- if (item == NULL) {
- PyErr_NoMemory();
- Py_DECREF(a);
- return NULL;
- }
- self->ob_item = item;
- Py_SIZE(self) = n / sizeof(Py_UNICODE);
- memcpy(item, PyUnicode_AS_DATA(initial), n);
- self->allocated = Py_SIZE(self);
- }
+ } else if (initial != NULL && PyUnicode_Check(initial)) {
+ Py_ssize_t n = PyUnicode_GET_DATA_SIZE(initial);
+ if (n > 0) {
+ arrayobject *self = (arrayobject *)a;
+ char *item = self->ob_item;
+ item = (char *)PyMem_Realloc(item, n);
+ if (item == NULL) {
+ PyErr_NoMemory();
+ Py_DECREF(a);
+ return NULL;
+ }
+ self->ob_item = item;
+ Py_SIZE(self) = n / sizeof(Py_UNICODE);
+ memcpy(item, PyUnicode_AS_DATA(initial), n);
+ self->allocated = Py_SIZE(self);
+ }
#endif
- }
- if (it != NULL) {
- if (array_iter_extend((arrayobject *)a, it) == -1) {
- Py_DECREF(it);
- Py_DECREF(a);
- return NULL;
- }
- Py_DECREF(it);
- }
- return a;
- }
- }
- PyErr_SetString(PyExc_ValueError,
- "bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)");
- return NULL;
+ }
+ if (it != NULL) {
+ if (array_iter_extend((arrayobject *)a, it) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(a);
+ return NULL;
+ }
+ Py_DECREF(it);
+ }
+ return a;
+ }
+ }
+ PyErr_SetString(PyExc_ValueError,
+ "bad typecode (must be c, b, B, u, h, H, i, I, l, L, f or d)");
+ return NULL;
}
@@ -2079,55 +2079,55 @@ itemsize -- the length in bytes of one array item\n\
static PyObject *array_iter(arrayobject *ao);
static PyTypeObject Arraytype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "array.array",
- sizeof(arrayobject),
- 0,
- (destructor)array_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)array_repr, /* tp_repr */
- 0, /* tp_as_number*/
- &array_as_sequence, /* tp_as_sequence*/
- &array_as_mapping, /* tp_as_mapping*/
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- &array_as_buffer, /* tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
- arraytype_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- array_richcompare, /* tp_richcompare */
- offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
- (getiterfunc)array_iter, /* tp_iter */
- 0, /* tp_iternext */
- array_methods, /* tp_methods */
- 0, /* tp_members */
- array_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- array_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "array.array",
+ sizeof(arrayobject),
+ 0,
+ (destructor)array_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)array_repr, /* tp_repr */
+ 0, /* tp_as_number*/
+ &array_as_sequence, /* tp_as_sequence*/
+ &array_as_mapping, /* tp_as_mapping*/
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ &array_as_buffer, /* tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
+ arraytype_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ array_richcompare, /* tp_richcompare */
+ offsetof(arrayobject, weakreflist), /* tp_weaklistoffset */
+ (getiterfunc)array_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ array_methods, /* tp_methods */
+ 0, /* tp_members */
+ array_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ array_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
/*********************** Array Iterator **************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t index;
- arrayobject *ao;
- PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
+ PyObject_HEAD
+ Py_ssize_t index;
+ arrayobject *ao;
+ PyObject * (*getitem)(struct arrayobject *, Py_ssize_t);
} arrayiterobject;
static PyTypeObject PyArrayIter_Type;
@@ -2137,79 +2137,79 @@ static PyTypeObject PyArrayIter_Type;
static PyObject *
array_iter(arrayobject *ao)
{
- arrayiterobject *it;
+ arrayiterobject *it;
- if (!array_Check(ao)) {
- PyErr_BadInternalCall();
- return NULL;
- }
+ if (!array_Check(ao)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
- it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
- if (it == NULL)
- return NULL;
+ it = PyObject_GC_New(arrayiterobject, &PyArrayIter_Type);
+ if (it == NULL)
+ return NULL;
- Py_INCREF(ao);
- it->ao = ao;
- it->index = 0;
- it->getitem = ao->ob_descr->getitem;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ Py_INCREF(ao);
+ it->ao = ao;
+ it->index = 0;
+ it->getitem = ao->ob_descr->getitem;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static PyObject *
arrayiter_next(arrayiterobject *it)
{
- assert(PyArrayIter_Check(it));
- if (it->index < Py_SIZE(it->ao))
- return (*it->getitem)(it->ao, it->index++);
- return NULL;
+ assert(PyArrayIter_Check(it));
+ if (it->index < Py_SIZE(it->ao))
+ return (*it->getitem)(it->ao, it->index++);
+ return NULL;
}
static void
arrayiter_dealloc(arrayiterobject *it)
{
- PyObject_GC_UnTrack(it);
- Py_XDECREF(it->ao);
- PyObject_GC_Del(it);
+ PyObject_GC_UnTrack(it);
+ Py_XDECREF(it->ao);
+ PyObject_GC_Del(it);
}
static int
arrayiter_traverse(arrayiterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->ao);
- return 0;
+ Py_VISIT(it->ao);
+ return 0;
}
static PyTypeObject PyArrayIter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "arrayiterator", /* tp_name */
- sizeof(arrayiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)arrayiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)arrayiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)arrayiter_next, /* tp_iternext */
- 0, /* tp_methods */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "arrayiterator", /* tp_name */
+ sizeof(arrayiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)arrayiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)arrayiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)arrayiter_next, /* tp_iternext */
+ 0, /* tp_methods */
};
@@ -2224,17 +2224,17 @@ static PyMethodDef a_methods[] = {
PyMODINIT_FUNC
initarray(void)
{
- PyObject *m;
+ PyObject *m;
- Arraytype.ob_type = &PyType_Type;
- PyArrayIter_Type.ob_type = &PyType_Type;
- m = Py_InitModule3("array", a_methods, module_doc);
- if (m == NULL)
- return;
+ Arraytype.ob_type = &PyType_Type;
+ PyArrayIter_Type.ob_type = &PyType_Type;
+ m = Py_InitModule3("array", a_methods, module_doc);
+ if (m == NULL)
+ return;
- Py_INCREF((PyObject *)&Arraytype);
- PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
- Py_INCREF((PyObject *)&Arraytype);
- PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
- /* No need to check the error here, the caller will do that */
+ Py_INCREF((PyObject *)&Arraytype);
+ PyModule_AddObject(m, "ArrayType", (PyObject *)&Arraytype);
+ Py_INCREF((PyObject *)&Arraytype);
+ PyModule_AddObject(m, "array", (PyObject *)&Arraytype);
+ /* No need to check the error here, the caller will do that */
}
diff --git a/Modules/audioop.c b/Modules/audioop.c
index c1f4463..0b57270 100644
--- a/Modules/audioop.c
+++ b/Modules/audioop.c
@@ -53,13 +53,13 @@ static PyInt16 seg_uend[8] = {0x3F, 0x7F, 0xFF, 0x1FF,
static PyInt16
search(PyInt16 val, PyInt16 *table, int size)
{
- int i;
+ int i;
- for (i = 0; i < size; i++) {
- if (val <= *table++)
- return (i);
- }
- return (size);
+ for (i = 0; i < size; i++) {
+ if (val <= *table++)
+ return (i);
+ }
+ return (size);
}
#define st_ulaw2linear16(uc) (_st_ulaw2linear16[uc])
#define st_alaw2linear16(uc) (_st_alaw2linear16[uc])
@@ -83,7 +83,7 @@ static PyInt16 _st_ulaw2linear16[256] = {
-228, -212, -196, -180, -164, -148, -132,
-120, -112, -104, -96, -88, -80, -72,
-64, -56, -48, -40, -32, -24, -16,
- -8, 0, 32124, 31100, 30076, 29052, 28028,
+ -8, 0, 32124, 31100, 30076, 29052, 28028,
27004, 25980, 24956, 23932, 22908, 21884, 20860,
19836, 18812, 17788, 16764, 15996, 15484, 14972,
14460, 13948, 13436, 12924, 12412, 11900, 11388,
@@ -100,8 +100,8 @@ static PyInt16 _st_ulaw2linear16[256] = {
372, 356, 340, 324, 308, 292, 276,
260, 244, 228, 212, 196, 180, 164,
148, 132, 120, 112, 104, 96, 88,
- 80, 72, 64, 56, 48, 40, 32,
- 24, 16, 8, 0
+ 80, 72, 64, 56, 48, 40, 32,
+ 24, 16, 8, 0
};
/*
@@ -137,39 +137,39 @@ static PyInt16 _st_ulaw2linear16[256] = {
* John Wiley & Sons, pps 98-111 and 472-476.
*/
static unsigned char
-st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */
+st_14linear2ulaw(PyInt16 pcm_val) /* 2's complement (14-bit range) */
{
- PyInt16 mask;
- PyInt16 seg;
- unsigned char uval;
-
- /* The original sox code does this in the calling function, not here */
- pcm_val = pcm_val >> 2;
-
- /* u-law inverts all bits */
- /* Get the sign and the magnitude of the value. */
- if (pcm_val < 0) {
- pcm_val = -pcm_val;
- mask = 0x7F;
- } else {
- mask = 0xFF;
- }
- if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
- pcm_val += (BIAS >> 2);
-
- /* Convert the scaled magnitude to segment number. */
- seg = search(pcm_val, seg_uend, 8);
-
- /*
- * Combine the sign, segment, quantization bits;
- * and complement the code word.
- */
- if (seg >= 8) /* out of range, return maximum value. */
- return (unsigned char) (0x7F ^ mask);
- else {
- uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
- return (uval ^ mask);
- }
+ PyInt16 mask;
+ PyInt16 seg;
+ unsigned char uval;
+
+ /* The original sox code does this in the calling function, not here */
+ pcm_val = pcm_val >> 2;
+
+ /* u-law inverts all bits */
+ /* Get the sign and the magnitude of the value. */
+ if (pcm_val < 0) {
+ pcm_val = -pcm_val;
+ mask = 0x7F;
+ } else {
+ mask = 0xFF;
+ }
+ if ( pcm_val > CLIP ) pcm_val = CLIP; /* clip the magnitude */
+ pcm_val += (BIAS >> 2);
+
+ /* Convert the scaled magnitude to segment number. */
+ seg = search(pcm_val, seg_uend, 8);
+
+ /*
+ * Combine the sign, segment, quantization bits;
+ * and complement the code word.
+ */
+ if (seg >= 8) /* out of range, return maximum value. */
+ return (unsigned char) (0x7F ^ mask);
+ else {
+ uval = (unsigned char) (seg << 4) | ((pcm_val >> (seg + 1)) & 0xF);
+ return (uval ^ mask);
+ }
}
@@ -234,57 +234,57 @@ static PyInt16 _st_alaw2linear16[256] = {
* John Wiley & Sons, pps 98-111 and 472-476.
*/
static unsigned char
-st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */
+st_linear2alaw(PyInt16 pcm_val) /* 2's complement (13-bit range) */
{
- PyInt16 mask;
- short seg;
- unsigned char aval;
-
- /* The original sox code does this in the calling function, not here */
- pcm_val = pcm_val >> 3;
-
- /* A-law using even bit inversion */
- if (pcm_val >= 0) {
- mask = 0xD5; /* sign (7th) bit = 1 */
- } else {
- mask = 0x55; /* sign bit = 0 */
- pcm_val = -pcm_val - 1;
- }
-
- /* Convert the scaled magnitude to segment number. */
- seg = search(pcm_val, seg_aend, 8);
-
- /* Combine the sign, segment, and quantization bits. */
-
- if (seg >= 8) /* out of range, return maximum value. */
- return (unsigned char) (0x7F ^ mask);
- else {
- aval = (unsigned char) seg << SEG_SHIFT;
- if (seg < 2)
- aval |= (pcm_val >> 1) & QUANT_MASK;
- else
- aval |= (pcm_val >> seg) & QUANT_MASK;
- return (aval ^ mask);
- }
+ PyInt16 mask;
+ short seg;
+ unsigned char aval;
+
+ /* The original sox code does this in the calling function, not here */
+ pcm_val = pcm_val >> 3;
+
+ /* A-law using even bit inversion */
+ if (pcm_val >= 0) {
+ mask = 0xD5; /* sign (7th) bit = 1 */
+ } else {
+ mask = 0x55; /* sign bit = 0 */
+ pcm_val = -pcm_val - 1;
+ }
+
+ /* Convert the scaled magnitude to segment number. */
+ seg = search(pcm_val, seg_aend, 8);
+
+ /* Combine the sign, segment, and quantization bits. */
+
+ if (seg >= 8) /* out of range, return maximum value. */
+ return (unsigned char) (0x7F ^ mask);
+ else {
+ aval = (unsigned char) seg << SEG_SHIFT;
+ if (seg < 2)
+ aval |= (pcm_val >> 1) & QUANT_MASK;
+ else
+ aval |= (pcm_val >> seg) & QUANT_MASK;
+ return (aval ^ mask);
+ }
}
/* End of code taken from sox */
/* Intel ADPCM step variation table */
static int indexTable[16] = {
- -1, -1, -1, -1, 2, 4, 6, 8,
- -1, -1, -1, -1, 2, 4, 6, 8,
+ -1, -1, -1, -1, 2, 4, 6, 8,
+ -1, -1, -1, -1, 2, 4, 6, 8,
};
static int stepsizeTable[89] = {
- 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
- 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
- 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
- 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
- 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
- 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
- 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
- 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
- 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
+ 7, 8, 9, 10, 11, 12, 13, 14, 16, 17,
+ 19, 21, 23, 25, 28, 31, 34, 37, 41, 45,
+ 50, 55, 60, 66, 73, 80, 88, 97, 107, 118,
+ 130, 143, 157, 173, 190, 209, 230, 253, 279, 307,
+ 337, 371, 408, 449, 494, 544, 598, 658, 724, 796,
+ 876, 963, 1060, 1166, 1282, 1411, 1552, 1707, 1878, 2066,
+ 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358,
+ 5894, 6484, 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899,
+ 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767
};
#define CHARP(cp, i) ((signed char *)(cp+i))
@@ -298,137 +298,137 @@ static PyObject *AudioopError;
static PyObject *
audioop_getsample(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- if ( i < 0 || i >= len/size ) {
- PyErr_SetString(AudioopError, "Index out of range");
- return 0;
- }
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i*2);
- else if ( size == 4 ) val = (int)*LONGP(cp, i*4);
- return PyInt_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#ii:getsample", &cp, &len, &size, &i) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ if ( i < 0 || i >= len/size ) {
+ PyErr_SetString(AudioopError, "Index out of range");
+ return 0;
+ }
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i*2);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i*4);
+ return PyInt_FromLong(val);
}
static PyObject *
audioop_max(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- int max = 0;
-
- if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- if ( val < 0 ) val = (-val);
- if ( val > max ) max = val;
- }
- return PyInt_FromLong(max);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ int max = 0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:max", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ if ( val < 0 ) val = (-val);
+ if ( val > max ) max = val;
+ }
+ return PyInt_FromLong(max);
}
static PyObject *
audioop_minmax(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- int min = 0x7fffffff, max = -0x7fffffff;
-
- if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size))
- return NULL;
- if (size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return NULL;
- }
- for (i = 0; i < len; i += size) {
- if (size == 1) val = (int) *CHARP(cp, i);
- else if (size == 2) val = (int) *SHORTP(cp, i);
- else if (size == 4) val = (int) *LONGP(cp, i);
- if (val > max) max = val;
- if (val < min) min = val;
- }
- return Py_BuildValue("(ii)", min, max);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ int min = 0x7fffffff, max = -0x7fffffff;
+
+ if (!PyArg_ParseTuple(args, "s#i:minmax", &cp, &len, &size))
+ return NULL;
+ if (size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return NULL;
+ }
+ for (i = 0; i < len; i += size) {
+ if (size == 1) val = (int) *CHARP(cp, i);
+ else if (size == 2) val = (int) *SHORTP(cp, i);
+ else if (size == 4) val = (int) *LONGP(cp, i);
+ if (val > max) max = val;
+ if (val < min) min = val;
+ }
+ return Py_BuildValue("(ii)", min, max);
}
static PyObject *
audioop_avg(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- double avg = 0.0;
-
- if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- avg += val;
- }
- if ( len == 0 )
- val = 0;
- else
- val = (int)(avg / (double)(len/size));
- return PyInt_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ double avg = 0.0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:avg", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ avg += val;
+ }
+ if ( len == 0 )
+ val = 0;
+ else
+ val = (int)(avg / (double)(len/size));
+ return PyInt_FromLong(val);
}
static PyObject *
audioop_rms(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- double sum_squares = 0.0;
-
- if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- sum_squares += (double)val*(double)val;
- }
- if ( len == 0 )
- val = 0;
- else
- val = (int)sqrt(sum_squares / (double)(len/size));
- return PyInt_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ double sum_squares = 0.0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:rms", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ sum_squares += (double)val*(double)val;
+ }
+ if ( len == 0 )
+ val = 0;
+ else
+ val = (int)sqrt(sum_squares / (double)(len/size));
+ return PyInt_FromLong(val);
}
static double _sum2(short *a, short *b, int len)
{
- int i;
- double sum = 0.0;
+ int i;
+ double sum = 0.0;
- for( i=0; i<len; i++) {
- sum = sum + (double)a[i]*(double)b[i];
- }
- return sum;
+ for( i=0; i<len; i++) {
+ sum = sum + (double)a[i]*(double)b[i];
+ }
+ return sum;
}
/*
@@ -466,59 +466,59 @@ static double _sum2(short *a, short *b, int len)
static PyObject *
audioop_findfit(PyObject *self, PyObject *args)
{
- short *cp1, *cp2;
- int len1, len2;
- int j, best_j;
- double aj_m1, aj_lm1;
- double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor;
-
- /* Passing a short** for an 's' argument is correct only
- if the string contents is aligned for interpretation
- as short[]. Due to the definition of PyStringObject,
- this is currently (Python 2.6) the case. */
- if ( !PyArg_ParseTuple(args, "s#s#:findfit",
- (char**)&cp1, &len1, (char**)&cp2, &len2) )
- return 0;
- if ( len1 & 1 || len2 & 1 ) {
- PyErr_SetString(AudioopError, "Strings should be even-sized");
- return 0;
- }
- len1 >>= 1;
- len2 >>= 1;
-
- if ( len1 < len2 ) {
- PyErr_SetString(AudioopError, "First sample should be longer");
- return 0;
- }
- sum_ri_2 = _sum2(cp2, cp2, len2);
- sum_aij_2 = _sum2(cp1, cp1, len2);
- sum_aij_ri = _sum2(cp1, cp2, len2);
-
- result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2;
-
- best_result = result;
- best_j = 0;
-
- for (j=1; j<=len1-len2; j++) {
- aj_m1 = (double)cp1[j-1];
- aj_lm1 = (double)cp1[j+len2-1];
-
- sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1;
- sum_aij_ri = _sum2(cp1+j, cp2, len2);
-
- result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri)
- / sum_aij_2;
-
- if ( result < best_result ) {
- best_result = result;
- best_j = j;
- }
-
- }
-
- factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2;
-
- return Py_BuildValue("(if)", best_j, factor);
+ short *cp1, *cp2;
+ int len1, len2;
+ int j, best_j;
+ double aj_m1, aj_lm1;
+ double sum_ri_2, sum_aij_2, sum_aij_ri, result, best_result, factor;
+
+ /* Passing a short** for an 's' argument is correct only
+ if the string contents is aligned for interpretation
+ as short[]. Due to the definition of PyStringObject,
+ this is currently (Python 2.6) the case. */
+ if ( !PyArg_ParseTuple(args, "s#s#:findfit",
+ (char**)&cp1, &len1, (char**)&cp2, &len2) )
+ return 0;
+ if ( len1 & 1 || len2 & 1 ) {
+ PyErr_SetString(AudioopError, "Strings should be even-sized");
+ return 0;
+ }
+ len1 >>= 1;
+ len2 >>= 1;
+
+ if ( len1 < len2 ) {
+ PyErr_SetString(AudioopError, "First sample should be longer");
+ return 0;
+ }
+ sum_ri_2 = _sum2(cp2, cp2, len2);
+ sum_aij_2 = _sum2(cp1, cp1, len2);
+ sum_aij_ri = _sum2(cp1, cp2, len2);
+
+ result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri) / sum_aij_2;
+
+ best_result = result;
+ best_j = 0;
+
+ for (j=1; j<=len1-len2; j++) {
+ aj_m1 = (double)cp1[j-1];
+ aj_lm1 = (double)cp1[j+len2-1];
+
+ sum_aij_2 = sum_aij_2 + aj_lm1*aj_lm1 - aj_m1*aj_m1;
+ sum_aij_ri = _sum2(cp1+j, cp2, len2);
+
+ result = (sum_ri_2*sum_aij_2 - sum_aij_ri*sum_aij_ri)
+ / sum_aij_2;
+
+ if ( result < best_result ) {
+ best_result = result;
+ best_j = j;
+ }
+
+ }
+
+ factor = _sum2(cp1+best_j, cp2, len2) / sum_ri_2;
+
+ return Py_BuildValue("(if)", best_j, factor);
}
/*
@@ -528,28 +528,28 @@ audioop_findfit(PyObject *self, PyObject *args)
static PyObject *
audioop_findfactor(PyObject *self, PyObject *args)
{
- short *cp1, *cp2;
- int len1, len2;
- double sum_ri_2, sum_aij_ri, result;
-
- if ( !PyArg_ParseTuple(args, "s#s#:findfactor",
- (char**)&cp1, &len1, (char**)&cp2, &len2) )
- return 0;
- if ( len1 & 1 || len2 & 1 ) {
- PyErr_SetString(AudioopError, "Strings should be even-sized");
- return 0;
- }
- if ( len1 != len2 ) {
- PyErr_SetString(AudioopError, "Samples should be same size");
- return 0;
- }
- len2 >>= 1;
- sum_ri_2 = _sum2(cp2, cp2, len2);
- sum_aij_ri = _sum2(cp1, cp2, len2);
-
- result = sum_aij_ri / sum_ri_2;
-
- return PyFloat_FromDouble(result);
+ short *cp1, *cp2;
+ int len1, len2;
+ double sum_ri_2, sum_aij_ri, result;
+
+ if ( !PyArg_ParseTuple(args, "s#s#:findfactor",
+ (char**)&cp1, &len1, (char**)&cp2, &len2) )
+ return 0;
+ if ( len1 & 1 || len2 & 1 ) {
+ PyErr_SetString(AudioopError, "Strings should be even-sized");
+ return 0;
+ }
+ if ( len1 != len2 ) {
+ PyErr_SetString(AudioopError, "Samples should be same size");
+ return 0;
+ }
+ len2 >>= 1;
+ sum_ri_2 = _sum2(cp2, cp2, len2);
+ sum_aij_ri = _sum2(cp1, cp2, len2);
+
+ result = sum_aij_ri / sum_ri_2;
+
+ return PyFloat_FromDouble(result);
}
/*
@@ -559,1093 +559,1093 @@ audioop_findfactor(PyObject *self, PyObject *args)
static PyObject *
audioop_findmax(PyObject *self, PyObject *args)
{
- short *cp1;
- int len1, len2;
- int j, best_j;
- double aj_m1, aj_lm1;
- double result, best_result;
-
- if ( !PyArg_ParseTuple(args, "s#i:findmax",
- (char**)&cp1, &len1, &len2) )
- return 0;
- if ( len1 & 1 ) {
- PyErr_SetString(AudioopError, "Strings should be even-sized");
- return 0;
- }
- len1 >>= 1;
+ short *cp1;
+ int len1, len2;
+ int j, best_j;
+ double aj_m1, aj_lm1;
+ double result, best_result;
- if ( len2 < 0 || len1 < len2 ) {
- PyErr_SetString(AudioopError, "Input sample should be longer");
- return 0;
- }
+ if ( !PyArg_ParseTuple(args, "s#i:findmax",
+ (char**)&cp1, &len1, &len2) )
+ return 0;
+ if ( len1 & 1 ) {
+ PyErr_SetString(AudioopError, "Strings should be even-sized");
+ return 0;
+ }
+ len1 >>= 1;
- result = _sum2(cp1, cp1, len2);
+ if ( len2 < 0 || len1 < len2 ) {
+ PyErr_SetString(AudioopError, "Input sample should be longer");
+ return 0;
+ }
- best_result = result;
- best_j = 0;
+ result = _sum2(cp1, cp1, len2);
- for (j=1; j<=len1-len2; j++) {
- aj_m1 = (double)cp1[j-1];
- aj_lm1 = (double)cp1[j+len2-1];
+ best_result = result;
+ best_j = 0;
- result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1;
+ for (j=1; j<=len1-len2; j++) {
+ aj_m1 = (double)cp1[j-1];
+ aj_lm1 = (double)cp1[j+len2-1];
- if ( result > best_result ) {
- best_result = result;
- best_j = j;
- }
+ result = result + aj_lm1*aj_lm1 - aj_m1*aj_m1;
+ if ( result > best_result ) {
+ best_result = result;
+ best_j = j;
}
- return PyInt_FromLong(best_j);
+ }
+
+ return PyInt_FromLong(best_j);
}
static PyObject *
audioop_avgpp(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0, prevval = 0, prevextremevalid = 0,
- prevextreme = 0;
- int i;
- double avg = 0.0;
- int diff, prevdiff, extremediff, nextreme = 0;
-
- if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- /* Compute first delta value ahead. Also automatically makes us
- ** skip the first extreme value
- */
- if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
- else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
- else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
- if ( size == 1 ) val = (int)*CHARP(cp, size);
- else if ( size == 2 ) val = (int)*SHORTP(cp, size);
- else if ( size == 4 ) val = (int)*LONGP(cp, size);
- prevdiff = val - prevval;
-
- for ( i=size; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- diff = val - prevval;
- if ( diff*prevdiff < 0 ) {
- /* Derivative changed sign. Compute difference to last
- ** extreme value and remember.
- */
- if ( prevextremevalid ) {
- extremediff = prevval - prevextreme;
- if ( extremediff < 0 )
- extremediff = -extremediff;
- avg += extremediff;
- nextreme++;
- }
- prevextremevalid = 1;
- prevextreme = prevval;
- }
- prevval = val;
- if ( diff != 0 )
- prevdiff = diff;
- }
- if ( nextreme == 0 )
- val = 0;
- else
- val = (int)(avg / (double)nextreme);
- return PyInt_FromLong(val);
+ signed char *cp;
+ int len, size, val = 0, prevval = 0, prevextremevalid = 0,
+ prevextreme = 0;
+ int i;
+ double avg = 0.0;
+ int diff, prevdiff, extremediff, nextreme = 0;
+
+ if ( !PyArg_ParseTuple(args, "s#i:avgpp", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ /* Compute first delta value ahead. Also automatically makes us
+ ** skip the first extreme value
+ */
+ if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
+ else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
+ else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
+ if ( size == 1 ) val = (int)*CHARP(cp, size);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, size);
+ else if ( size == 4 ) val = (int)*LONGP(cp, size);
+ prevdiff = val - prevval;
+
+ for ( i=size; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ diff = val - prevval;
+ if ( diff*prevdiff < 0 ) {
+ /* Derivative changed sign. Compute difference to last
+ ** extreme value and remember.
+ */
+ if ( prevextremevalid ) {
+ extremediff = prevval - prevextreme;
+ if ( extremediff < 0 )
+ extremediff = -extremediff;
+ avg += extremediff;
+ nextreme++;
+ }
+ prevextremevalid = 1;
+ prevextreme = prevval;
+ }
+ prevval = val;
+ if ( diff != 0 )
+ prevdiff = diff;
+ }
+ if ( nextreme == 0 )
+ val = 0;
+ else
+ val = (int)(avg / (double)nextreme);
+ return PyInt_FromLong(val);
}
static PyObject *
audioop_maxpp(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0, prevval = 0, prevextremevalid = 0,
- prevextreme = 0;
- int i;
- int max = 0;
- int diff, prevdiff, extremediff;
-
- if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- /* Compute first delta value ahead. Also automatically makes us
- ** skip the first extreme value
- */
- if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
- else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
- else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
- if ( size == 1 ) val = (int)*CHARP(cp, size);
- else if ( size == 2 ) val = (int)*SHORTP(cp, size);
- else if ( size == 4 ) val = (int)*LONGP(cp, size);
- prevdiff = val - prevval;
-
- for ( i=size; i<len; i+= size) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- diff = val - prevval;
- if ( diff*prevdiff < 0 ) {
- /* Derivative changed sign. Compute difference to
- ** last extreme value and remember.
- */
- if ( prevextremevalid ) {
- extremediff = prevval - prevextreme;
- if ( extremediff < 0 )
- extremediff = -extremediff;
- if ( extremediff > max )
- max = extremediff;
- }
- prevextremevalid = 1;
- prevextreme = prevval;
- }
- prevval = val;
- if ( diff != 0 )
- prevdiff = diff;
- }
- return PyInt_FromLong(max);
+ signed char *cp;
+ int len, size, val = 0, prevval = 0, prevextremevalid = 0,
+ prevextreme = 0;
+ int i;
+ int max = 0;
+ int diff, prevdiff, extremediff;
+
+ if ( !PyArg_ParseTuple(args, "s#i:maxpp", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ /* Compute first delta value ahead. Also automatically makes us
+ ** skip the first extreme value
+ */
+ if ( size == 1 ) prevval = (int)*CHARP(cp, 0);
+ else if ( size == 2 ) prevval = (int)*SHORTP(cp, 0);
+ else if ( size == 4 ) prevval = (int)*LONGP(cp, 0);
+ if ( size == 1 ) val = (int)*CHARP(cp, size);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, size);
+ else if ( size == 4 ) val = (int)*LONGP(cp, size);
+ prevdiff = val - prevval;
+
+ for ( i=size; i<len; i+= size) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ diff = val - prevval;
+ if ( diff*prevdiff < 0 ) {
+ /* Derivative changed sign. Compute difference to
+ ** last extreme value and remember.
+ */
+ if ( prevextremevalid ) {
+ extremediff = prevval - prevextreme;
+ if ( extremediff < 0 )
+ extremediff = -extremediff;
+ if ( extremediff > max )
+ max = extremediff;
+ }
+ prevextremevalid = 1;
+ prevextreme = prevval;
+ }
+ prevval = val;
+ if ( diff != 0 )
+ prevdiff = diff;
+ }
+ return PyInt_FromLong(max);
}
static PyObject *
audioop_cross(PyObject *self, PyObject *args)
{
- signed char *cp;
- int len, size, val = 0;
- int i;
- int prevval, ncross;
-
- if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) )
- return 0;
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
- ncross = -1;
- prevval = 17; /* Anything <> 0,1 */
- for ( i=0; i<len; i+= size) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) >> 7;
- else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15;
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31;
- val = val & 1;
- if ( val != prevval ) ncross++;
- prevval = val;
- }
- return PyInt_FromLong(ncross);
+ signed char *cp;
+ int len, size, val = 0;
+ int i;
+ int prevval, ncross;
+
+ if ( !PyArg_ParseTuple(args, "s#i:cross", &cp, &len, &size) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ ncross = -1;
+ prevval = 17; /* Anything <> 0,1 */
+ for ( i=0; i<len; i+= size) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) >> 7;
+ else if ( size == 2 ) val = ((int)*SHORTP(cp, i)) >> 15;
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 31;
+ val = val & 1;
+ if ( val != prevval ) ncross++;
+ prevval = val;
+ }
+ return PyInt_FromLong(ncross);
}
static PyObject *
audioop_mul(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, size, val = 0;
- double factor, fval, maxval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) )
- return 0;
-
- if ( size == 1 ) maxval = (double) 0x7f;
- else if ( size == 2 ) maxval = (double) 0x7fff;
- else if ( size == 4 ) maxval = (double) 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
-
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
- fval = (double)val*factor;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val = (int)fval;
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)val;
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)val;
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)val;
- }
- return rv;
+ signed char *cp, *ncp;
+ int len, size, val = 0;
+ double factor, fval, maxval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#id:mul", &cp, &len, &size, &factor ) )
+ return 0;
+
+ if ( size == 1 ) maxval = (double) 0x7f;
+ else if ( size == 2 ) maxval = (double) 0x7fff;
+ else if ( size == 4 ) maxval = (double) 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
+
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ fval = (double)val*factor;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val = (int)fval;
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)val;
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)val;
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)val;
+ }
+ return rv;
}
static PyObject *
audioop_tomono(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, size, val1 = 0, val2 = 0;
- double fac1, fac2, fval, maxval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#idd:tomono",
- &cp, &len, &size, &fac1, &fac2 ) )
- return 0;
-
- if ( size == 1 ) maxval = (double) 0x7f;
- else if ( size == 2 ) maxval = (double) 0x7fff;
- else if ( size == 4 ) maxval = (double) 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, len/2);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
-
-
- for ( i=0; i < len; i += size*2 ) {
- if ( size == 1 ) val1 = (int)*CHARP(cp, i);
- else if ( size == 2 ) val1 = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val1 = (int)*LONGP(cp, i);
- if ( size == 1 ) val2 = (int)*CHARP(cp, i+1);
- else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2);
- else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4);
- fval = (double)val1*fac1 + (double)val2*fac2;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val1 = (int)fval;
- if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1;
- else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1;
- else if ( size == 4 ) *LONGP(ncp, i/2)= (Py_Int32)val1;
- }
- return rv;
+ signed char *cp, *ncp;
+ int len, size, val1 = 0, val2 = 0;
+ double fac1, fac2, fval, maxval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#idd:tomono",
+ &cp, &len, &size, &fac1, &fac2 ) )
+ return 0;
+
+ if ( size == 1 ) maxval = (double) 0x7f;
+ else if ( size == 2 ) maxval = (double) 0x7fff;
+ else if ( size == 4 ) maxval = (double) 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len/2);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
+
+
+ for ( i=0; i < len; i += size*2 ) {
+ if ( size == 1 ) val1 = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val1 = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val1 = (int)*LONGP(cp, i);
+ if ( size == 1 ) val2 = (int)*CHARP(cp, i+1);
+ else if ( size == 2 ) val2 = (int)*SHORTP(cp, i+2);
+ else if ( size == 4 ) val2 = (int)*LONGP(cp, i+4);
+ fval = (double)val1*fac1 + (double)val2*fac2;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val1 = (int)fval;
+ if ( size == 1 ) *CHARP(ncp, i/2) = (signed char)val1;
+ else if ( size == 2 ) *SHORTP(ncp, i/2) = (short)val1;
+ else if ( size == 4 ) *LONGP(ncp, i/2)= (Py_Int32)val1;
+ }
+ return rv;
}
static PyObject *
audioop_tostereo(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, new_len, size, val1, val2, val = 0;
- double fac1, fac2, fval, maxval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#idd:tostereo",
- &cp, &len, &size, &fac1, &fac2 ) )
- return 0;
-
- if ( size == 1 ) maxval = (double) 0x7f;
- else if ( size == 2 ) maxval = (double) 0x7fff;
- else if ( size == 4 ) maxval = (double) 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = len*2;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
-
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
-
- fval = (double)val*fac1;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val1 = (int)fval;
-
- fval = (double)val*fac2;
- if ( fval > maxval ) fval = maxval;
- else if ( fval < -maxval ) fval = -maxval;
- val2 = (int)fval;
-
- if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1;
- else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1;
- else if ( size == 4 ) *LONGP(ncp, i*2) = (Py_Int32)val1;
-
- if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2;
- else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2;
- else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2;
- }
- return rv;
+ signed char *cp, *ncp;
+ int len, new_len, size, val1, val2, val = 0;
+ double fac1, fac2, fval, maxval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#idd:tostereo",
+ &cp, &len, &size, &fac1, &fac2 ) )
+ return 0;
+
+ if ( size == 1 ) maxval = (double) 0x7f;
+ else if ( size == 2 ) maxval = (double) 0x7fff;
+ else if ( size == 4 ) maxval = (double) 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = len*2;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
+
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+
+ fval = (double)val*fac1;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val1 = (int)fval;
+
+ fval = (double)val*fac2;
+ if ( fval > maxval ) fval = maxval;
+ else if ( fval < -maxval ) fval = -maxval;
+ val2 = (int)fval;
+
+ if ( size == 1 ) *CHARP(ncp, i*2) = (signed char)val1;
+ else if ( size == 2 ) *SHORTP(ncp, i*2) = (short)val1;
+ else if ( size == 4 ) *LONGP(ncp, i*2) = (Py_Int32)val1;
+
+ if ( size == 1 ) *CHARP(ncp, i*2+1) = (signed char)val2;
+ else if ( size == 2 ) *SHORTP(ncp, i*2+2) = (short)val2;
+ else if ( size == 4 ) *LONGP(ncp, i*2+4) = (Py_Int32)val2;
+ }
+ return rv;
}
static PyObject *
audioop_add(PyObject *self, PyObject *args)
{
- signed char *cp1, *cp2, *ncp;
- int len1, len2, size, val1 = 0, val2 = 0, maxval, newval;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#s#i:add",
- &cp1, &len1, &cp2, &len2, &size ) )
- return 0;
-
- if ( len1 != len2 ) {
- PyErr_SetString(AudioopError, "Lengths should be the same");
- return 0;
- }
-
- if ( size == 1 ) maxval = 0x7f;
- else if ( size == 2 ) maxval = 0x7fff;
- else if ( size == 4 ) maxval = 0x7fffffff;
- else {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, len1);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
-
- for ( i=0; i < len1; i += size ) {
- if ( size == 1 ) val1 = (int)*CHARP(cp1, i);
- else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i);
- else if ( size == 4 ) val1 = (int)*LONGP(cp1, i);
-
- if ( size == 1 ) val2 = (int)*CHARP(cp2, i);
- else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i);
- else if ( size == 4 ) val2 = (int)*LONGP(cp2, i);
-
- newval = val1 + val2;
- /* truncate in case of overflow */
- if (newval > maxval) newval = maxval;
- else if (newval < -maxval) newval = -maxval;
- else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0)
- newval = val1 > 0 ? maxval : - maxval;
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval;
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval;
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval;
- }
- return rv;
+ signed char *cp1, *cp2, *ncp;
+ int len1, len2, size, val1 = 0, val2 = 0, maxval, newval;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#s#i:add",
+ &cp1, &len1, &cp2, &len2, &size ) )
+ return 0;
+
+ if ( len1 != len2 ) {
+ PyErr_SetString(AudioopError, "Lengths should be the same");
+ return 0;
+ }
+
+ if ( size == 1 ) maxval = 0x7f;
+ else if ( size == 2 ) maxval = 0x7fff;
+ else if ( size == 4 ) maxval = 0x7fffffff;
+ else {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len1);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
+
+ for ( i=0; i < len1; i += size ) {
+ if ( size == 1 ) val1 = (int)*CHARP(cp1, i);
+ else if ( size == 2 ) val1 = (int)*SHORTP(cp1, i);
+ else if ( size == 4 ) val1 = (int)*LONGP(cp1, i);
+
+ if ( size == 1 ) val2 = (int)*CHARP(cp2, i);
+ else if ( size == 2 ) val2 = (int)*SHORTP(cp2, i);
+ else if ( size == 4 ) val2 = (int)*LONGP(cp2, i);
+
+ newval = val1 + val2;
+ /* truncate in case of overflow */
+ if (newval > maxval) newval = maxval;
+ else if (newval < -maxval) newval = -maxval;
+ else if (size == 4 && (newval^val1) < 0 && (newval^val2) < 0)
+ newval = val1 > 0 ? maxval : - maxval;
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)newval;
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)newval;
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)newval;
+ }
+ return rv;
}
static PyObject *
audioop_bias(PyObject *self, PyObject *args)
{
- signed char *cp, *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i;
- int bias;
-
- if ( !PyArg_ParseTuple(args, "s#ii:bias",
- &cp, &len, &size , &bias) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
+ signed char *cp, *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i;
+ int bias;
- rv = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
+ if ( !PyArg_ParseTuple(args, "s#ii:bias",
+ &cp, &len, &size , &bias) )
+ return 0;
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = (int)*CHARP(cp, i);
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = (int)*LONGP(cp, i);
+ rv = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias);
- }
- return rv;
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = (int)*CHARP(cp, i);
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = (int)*LONGP(cp, i);
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val+bias);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val+bias);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val+bias);
+ }
+ return rv;
}
static PyObject *
audioop_reverse(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i, j;
-
- if ( !PyArg_ParseTuple(args, "s#i:reverse",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- j = len - i - size;
-
- if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
- else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val);
- else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i, j;
+
+ if ( !PyArg_ParseTuple(args, "s#i:reverse",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ j = len - i - size;
+
+ if ( size == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, j) = (short)(val);
+ else if ( size == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static PyObject *
audioop_lin2lin(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, new_len, size, size2, val = 0;
- PyObject *rv;
- int i, j;
-
- if ( !PyArg_ParseTuple(args, "s#ii:lin2lin",
- &cp, &len, &size, &size2) )
- return 0;
-
- if ( (size != 1 && size != 2 && size != 4) ||
- (size2 != 1 && size2 != 2 && size2 != 4)) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = (len/size)*size2;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- rv = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0, j=0; i < len; i += size, j += size2 ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
- else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val);
- else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, new_len, size, size2, val = 0;
+ PyObject *rv;
+ int i, j;
+
+ if ( !PyArg_ParseTuple(args, "s#ii:lin2lin",
+ &cp, &len, &size, &size2) )
+ return 0;
+
+ if ( (size != 1 && size != 2 && size != 4) ||
+ (size2 != 1 && size2 != 2 && size2 != 4)) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = (len/size)*size2;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ rv = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0, j=0; i < len; i += size, j += size2 ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ if ( size2 == 1 ) *CHARP(ncp, j) = (signed char)(val >> 8);
+ else if ( size2 == 2 ) *SHORTP(ncp, j) = (short)(val);
+ else if ( size2 == 4 ) *LONGP(ncp, j) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static int
gcd(int a, int b)
{
- while (b > 0) {
- int tmp = a % b;
- a = b;
- b = tmp;
- }
- return a;
+ while (b > 0) {
+ int tmp = a % b;
+ a = b;
+ b = tmp;
+ }
+ return a;
}
static PyObject *
audioop_ratecv(PyObject *self, PyObject *args)
{
- char *cp, *ncp;
- int len, size, nchannels, inrate, outrate, weightA, weightB;
- int chan, d, *prev_i, *cur_i, cur_o;
- PyObject *state, *samps, *str, *rv = NULL;
- int bytes_per_frame;
- size_t alloc_size;
-
- weightA = 1;
- weightB = 0;
- if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size,
- &nchannels, &inrate, &outrate, &state,
- &weightA, &weightB))
- return NULL;
- if (size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return NULL;
- }
- if (nchannels < 1) {
- PyErr_SetString(AudioopError, "# of channels should be >= 1");
- return NULL;
- }
- bytes_per_frame = size * nchannels;
- if (bytes_per_frame / nchannels != size) {
- /* This overflow test is rigorously correct because
- both multiplicands are >= 1. Use the argument names
- from the docs for the error msg. */
- PyErr_SetString(PyExc_OverflowError,
- "width * nchannels too big for a C int");
- return NULL;
- }
- if (weightA < 1 || weightB < 0) {
- PyErr_SetString(AudioopError,
- "weightA should be >= 1, weightB should be >= 0");
- return NULL;
- }
- if (len % bytes_per_frame != 0) {
- PyErr_SetString(AudioopError, "not a whole number of frames");
- return NULL;
- }
- if (inrate <= 0 || outrate <= 0) {
- PyErr_SetString(AudioopError, "sampling rate not > 0");
- return NULL;
- }
- /* divide inrate and outrate by their greatest common divisor */
- d = gcd(inrate, outrate);
- inrate /= d;
- outrate /= d;
-
- alloc_size = sizeof(int) * (unsigned)nchannels;
- if (alloc_size < (unsigned)nchannels) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- prev_i = (int *) malloc(alloc_size);
- cur_i = (int *) malloc(alloc_size);
- if (prev_i == NULL || cur_i == NULL) {
- (void) PyErr_NoMemory();
+ char *cp, *ncp;
+ int len, size, nchannels, inrate, outrate, weightA, weightB;
+ int chan, d, *prev_i, *cur_i, cur_o;
+ PyObject *state, *samps, *str, *rv = NULL;
+ int bytes_per_frame;
+ size_t alloc_size;
+
+ weightA = 1;
+ weightB = 0;
+ if (!PyArg_ParseTuple(args, "s#iiiiO|ii:ratecv", &cp, &len, &size,
+ &nchannels, &inrate, &outrate, &state,
+ &weightA, &weightB))
+ return NULL;
+ if (size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return NULL;
+ }
+ if (nchannels < 1) {
+ PyErr_SetString(AudioopError, "# of channels should be >= 1");
+ return NULL;
+ }
+ bytes_per_frame = size * nchannels;
+ if (bytes_per_frame / nchannels != size) {
+ /* This overflow test is rigorously correct because
+ both multiplicands are >= 1. Use the argument names
+ from the docs for the error msg. */
+ PyErr_SetString(PyExc_OverflowError,
+ "width * nchannels too big for a C int");
+ return NULL;
+ }
+ if (weightA < 1 || weightB < 0) {
+ PyErr_SetString(AudioopError,
+ "weightA should be >= 1, weightB should be >= 0");
+ return NULL;
+ }
+ if (len % bytes_per_frame != 0) {
+ PyErr_SetString(AudioopError, "not a whole number of frames");
+ return NULL;
+ }
+ if (inrate <= 0 || outrate <= 0) {
+ PyErr_SetString(AudioopError, "sampling rate not > 0");
+ return NULL;
+ }
+ /* divide inrate and outrate by their greatest common divisor */
+ d = gcd(inrate, outrate);
+ inrate /= d;
+ outrate /= d;
+
+ alloc_size = sizeof(int) * (unsigned)nchannels;
+ if (alloc_size < (unsigned)nchannels) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ prev_i = (int *) malloc(alloc_size);
+ cur_i = (int *) malloc(alloc_size);
+ if (prev_i == NULL || cur_i == NULL) {
+ (void) PyErr_NoMemory();
+ goto exit;
+ }
+
+ len /= bytes_per_frame; /* # of frames */
+
+ if (state == Py_None) {
+ d = -outrate;
+ for (chan = 0; chan < nchannels; chan++)
+ prev_i[chan] = cur_i[chan] = 0;
+ }
+ else {
+ if (!PyArg_ParseTuple(state,
+ "iO!;audioop.ratecv: illegal state argument",
+ &d, &PyTuple_Type, &samps))
+ goto exit;
+ if (PyTuple_Size(samps) != nchannels) {
+ PyErr_SetString(AudioopError,
+ "illegal state argument");
+ goto exit;
+ }
+ for (chan = 0; chan < nchannels; chan++) {
+ if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan),
+ "ii:ratecv", &prev_i[chan],
+ &cur_i[chan]))
goto exit;
}
-
- len /= bytes_per_frame; /* # of frames */
-
- if (state == Py_None) {
- d = -outrate;
+ }
+
+ /* str <- Space for the output buffer. */
+ {
+ /* There are len input frames, so we need (mathematically)
+ ceiling(len*outrate/inrate) output frames, and each frame
+ requires bytes_per_frame bytes. Computing this
+ without spurious overflow is the challenge; we can
+ settle for a reasonable upper bound, though. */
+ int ceiling; /* the number of output frames */
+ int nbytes; /* the number of output bytes needed */
+ int q = len / inrate;
+ /* Now len = q * inrate + r exactly (with r = len % inrate),
+ and this is less than q * inrate + inrate = (q+1)*inrate.
+ So a reasonable upper bound on len*outrate/inrate is
+ ((q+1)*inrate)*outrate/inrate =
+ (q+1)*outrate.
+ */
+ ceiling = (q+1) * outrate;
+ nbytes = ceiling * bytes_per_frame;
+ /* See whether anything overflowed; if not, get the space. */
+ if (q+1 < 0 ||
+ ceiling / outrate != q+1 ||
+ nbytes / bytes_per_frame != ceiling)
+ str = NULL;
+ else
+ str = PyString_FromStringAndSize(NULL, nbytes);
+
+ if (str == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ goto exit;
+ }
+ }
+ ncp = PyString_AsString(str);
+
+ for (;;) {
+ while (d < 0) {
+ if (len == 0) {
+ samps = PyTuple_New(nchannels);
+ if (samps == NULL)
+ goto exit;
for (chan = 0; chan < nchannels; chan++)
- prev_i[chan] = cur_i[chan] = 0;
- }
- else {
- if (!PyArg_ParseTuple(state,
- "iO!;audioop.ratecv: illegal state argument",
- &d, &PyTuple_Type, &samps))
- goto exit;
- if (PyTuple_Size(samps) != nchannels) {
- PyErr_SetString(AudioopError,
- "illegal state argument");
- goto exit;
- }
- for (chan = 0; chan < nchannels; chan++) {
- if (!PyArg_ParseTuple(PyTuple_GetItem(samps, chan),
- "ii:ratecv", &prev_i[chan],
- &cur_i[chan]))
- goto exit;
- }
- }
-
- /* str <- Space for the output buffer. */
- {
- /* There are len input frames, so we need (mathematically)
- ceiling(len*outrate/inrate) output frames, and each frame
- requires bytes_per_frame bytes. Computing this
- without spurious overflow is the challenge; we can
- settle for a reasonable upper bound, though. */
- int ceiling; /* the number of output frames */
- int nbytes; /* the number of output bytes needed */
- int q = len / inrate;
- /* Now len = q * inrate + r exactly (with r = len % inrate),
- and this is less than q * inrate + inrate = (q+1)*inrate.
- So a reasonable upper bound on len*outrate/inrate is
- ((q+1)*inrate)*outrate/inrate =
- (q+1)*outrate.
- */
- ceiling = (q+1) * outrate;
- nbytes = ceiling * bytes_per_frame;
- /* See whether anything overflowed; if not, get the space. */
- if (q+1 < 0 ||
- ceiling / outrate != q+1 ||
- nbytes / bytes_per_frame != ceiling)
- str = NULL;
- else
- str = PyString_FromStringAndSize(NULL, nbytes);
-
- if (str == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- goto exit;
- }
- }
- ncp = PyString_AsString(str);
-
- for (;;) {
- while (d < 0) {
- if (len == 0) {
- samps = PyTuple_New(nchannels);
- if (samps == NULL)
- goto exit;
- for (chan = 0; chan < nchannels; chan++)
- PyTuple_SetItem(samps, chan,
- Py_BuildValue("(ii)",
- prev_i[chan],
- cur_i[chan]));
- if (PyErr_Occurred())
- goto exit;
- /* We have checked before that the length
- * of the string fits into int. */
- len = (int)(ncp - PyString_AsString(str));
- if (len == 0) {
- /*don't want to resize to zero length*/
- rv = PyString_FromStringAndSize("", 0);
- Py_DECREF(str);
- str = rv;
- } else if (_PyString_Resize(&str, len) < 0)
- goto exit;
- rv = Py_BuildValue("(O(iO))", str, d, samps);
- Py_DECREF(samps);
- Py_DECREF(str);
- goto exit; /* return rv */
- }
- for (chan = 0; chan < nchannels; chan++) {
- prev_i[chan] = cur_i[chan];
- if (size == 1)
- cur_i[chan] = ((int)*CHARP(cp, 0)) << 8;
- else if (size == 2)
- cur_i[chan] = (int)*SHORTP(cp, 0);
- else if (size == 4)
- cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16;
- cp += size;
- /* implements a simple digital filter */
- cur_i[chan] =
- (weightA * cur_i[chan] +
- weightB * prev_i[chan]) /
- (weightA + weightB);
- }
- len--;
- d += outrate;
- }
- while (d >= 0) {
- for (chan = 0; chan < nchannels; chan++) {
- cur_o = (prev_i[chan] * d +
- cur_i[chan] * (outrate - d)) /
- outrate;
- if (size == 1)
- *CHARP(ncp, 0) = (signed char)(cur_o >> 8);
- else if (size == 2)
- *SHORTP(ncp, 0) = (short)(cur_o);
- else if (size == 4)
- *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16);
- ncp += size;
- }
- d -= inrate;
- }
- }
+ PyTuple_SetItem(samps, chan,
+ Py_BuildValue("(ii)",
+ prev_i[chan],
+ cur_i[chan]));
+ if (PyErr_Occurred())
+ goto exit;
+ /* We have checked before that the length
+ * of the string fits into int. */
+ len = (int)(ncp - PyString_AsString(str));
+ if (len == 0) {
+ /*don't want to resize to zero length*/
+ rv = PyString_FromStringAndSize("", 0);
+ Py_DECREF(str);
+ str = rv;
+ } else if (_PyString_Resize(&str, len) < 0)
+ goto exit;
+ rv = Py_BuildValue("(O(iO))", str, d, samps);
+ Py_DECREF(samps);
+ Py_DECREF(str);
+ goto exit; /* return rv */
+ }
+ for (chan = 0; chan < nchannels; chan++) {
+ prev_i[chan] = cur_i[chan];
+ if (size == 1)
+ cur_i[chan] = ((int)*CHARP(cp, 0)) << 8;
+ else if (size == 2)
+ cur_i[chan] = (int)*SHORTP(cp, 0);
+ else if (size == 4)
+ cur_i[chan] = ((int)*LONGP(cp, 0)) >> 16;
+ cp += size;
+ /* implements a simple digital filter */
+ cur_i[chan] =
+ (weightA * cur_i[chan] +
+ weightB * prev_i[chan]) /
+ (weightA + weightB);
+ }
+ len--;
+ d += outrate;
+ }
+ while (d >= 0) {
+ for (chan = 0; chan < nchannels; chan++) {
+ cur_o = (prev_i[chan] * d +
+ cur_i[chan] * (outrate - d)) /
+ outrate;
+ if (size == 1)
+ *CHARP(ncp, 0) = (signed char)(cur_o >> 8);
+ else if (size == 2)
+ *SHORTP(ncp, 0) = (short)(cur_o);
+ else if (size == 4)
+ *LONGP(ncp, 0) = (Py_Int32)(cur_o<<16);
+ ncp += size;
+ }
+ d -= inrate;
+ }
+ }
exit:
- if (prev_i != NULL)
- free(prev_i);
- if (cur_i != NULL)
- free(cur_i);
- return rv;
+ if (prev_i != NULL)
+ free(prev_i);
+ if (cur_i != NULL)
+ free(cur_i);
+ return rv;
}
static PyObject *
audioop_lin2ulaw(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw",
- &cp, &len, &size) )
- return 0 ;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, len/size);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- *ncp++ = st_14linear2ulaw(val);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:lin2ulaw",
+ &cp, &len, &size) )
+ return 0 ;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len/size);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ *ncp++ = st_14linear2ulaw(val);
+ }
+ return rv;
}
static PyObject *
audioop_ulaw2lin(PyObject *self, PyObject *args)
{
- unsigned char *cp;
- unsigned char cval;
- signed char *ncp;
- int len, new_len, size, val;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = len*size;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- rv = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
-
- for ( i=0; i < new_len; i += size ) {
- cval = *cp++;
- val = st_ulaw2linear16(cval);
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
- }
- return rv;
+ unsigned char *cp;
+ unsigned char cval;
+ signed char *ncp;
+ int len, new_len, size, val;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:ulaw2lin",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = len*size;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ rv = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
+
+ for ( i=0; i < new_len; i += size ) {
+ cval = *cp++;
+ val = st_ulaw2linear16(cval);
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static PyObject *
audioop_lin2alaw(PyObject *self, PyObject *args)
{
- signed char *cp;
- unsigned char *ncp;
- int len, size, val = 0;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:lin2alaw",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, len/size);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- *ncp++ = st_linear2alaw(val);
- }
- return rv;
+ signed char *cp;
+ unsigned char *ncp;
+ int len, size, val = 0;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:lin2alaw",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, len/size);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ *ncp++ = st_linear2alaw(val);
+ }
+ return rv;
}
static PyObject *
audioop_alaw2lin(PyObject *self, PyObject *args)
{
- unsigned char *cp;
- unsigned char cval;
- signed char *ncp;
- int len, new_len, size, val;
- PyObject *rv;
- int i;
-
- if ( !PyArg_ParseTuple(args, "s#i:alaw2lin",
- &cp, &len, &size) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
- }
-
- new_len = len*size;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- rv = PyString_FromStringAndSize(NULL, new_len);
- if ( rv == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(rv);
-
- for ( i=0; i < new_len; i += size ) {
- cval = *cp++;
- val = st_alaw2linear16(cval);
-
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
- }
- return rv;
+ unsigned char *cp;
+ unsigned char cval;
+ signed char *ncp;
+ int len, new_len, size, val;
+ PyObject *rv;
+ int i;
+
+ if ( !PyArg_ParseTuple(args, "s#i:alaw2lin",
+ &cp, &len, &size) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ new_len = len*size;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ rv = PyString_FromStringAndSize(NULL, new_len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(rv);
+
+ for ( i=0; i < new_len; i += size ) {
+ cval = *cp++;
+ val = st_alaw2linear16(cval);
+
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(val >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(val);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(val<<16);
+ }
+ return rv;
}
static PyObject *
audioop_lin2adpcm(PyObject *self, PyObject *args)
{
- signed char *cp;
- signed char *ncp;
- int len, size, val = 0, step, valpred, delta,
- index, sign, vpdiff, diff;
- PyObject *rv, *state, *str;
- int i, outputbuffer = 0, bufferstep;
-
- if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm",
- &cp, &len, &size, &state) )
- return 0;
-
+ signed char *cp;
+ signed char *ncp;
+ int len, size, val = 0, step, valpred, delta,
+ index, sign, vpdiff, diff;
+ PyObject *rv, *state, *str;
+ int i, outputbuffer = 0, bufferstep;
+
+ if ( !PyArg_ParseTuple(args, "s#iO:lin2adpcm",
+ &cp, &len, &size, &state) )
+ return 0;
+
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ str = PyString_FromStringAndSize(NULL, len/(size*2));
+ if ( str == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(str);
+
+ /* Decode state, should have (value, step) */
+ if ( state == Py_None ) {
+ /* First time, it seems. Set defaults */
+ valpred = 0;
+ index = 0;
+ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
+ return 0;
+
+ step = stepsizeTable[index];
+ bufferstep = 1;
+
+ for ( i=0; i < len; i += size ) {
+ if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
+ else if ( size == 2 ) val = (int)*SHORTP(cp, i);
+ else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
+
+ /* Step 1 - compute difference with previous value */
+ diff = val - valpred;
+ sign = (diff < 0) ? 8 : 0;
+ if ( sign ) diff = (-diff);
+
+ /* Step 2 - Divide and clamp */
+ /* Note:
+ ** This code *approximately* computes:
+ ** delta = diff*4/step;
+ ** vpdiff = (delta+0.5)*step/4;
+ ** but in shift step bits are dropped. The net result of this
+ ** is that even if you have fast mul/div hardware you cannot
+ ** put it to good use since the fixup would be too expensive.
+ */
+ delta = 0;
+ vpdiff = (step >> 3);
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
+ if ( diff >= step ) {
+ delta = 4;
+ diff -= step;
+ vpdiff += step;
+ }
+ step >>= 1;
+ if ( diff >= step ) {
+ delta |= 2;
+ diff -= step;
+ vpdiff += step;
+ }
+ step >>= 1;
+ if ( diff >= step ) {
+ delta |= 1;
+ vpdiff += step;
}
- str = PyString_FromStringAndSize(NULL, len/(size*2));
- if ( str == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(str);
+ /* Step 3 - Update previous value */
+ if ( sign )
+ valpred -= vpdiff;
+ else
+ valpred += vpdiff;
+
+ /* Step 4 - Clamp previous value to 16 bits */
+ if ( valpred > 32767 )
+ valpred = 32767;
+ else if ( valpred < -32768 )
+ valpred = -32768;
- /* Decode state, should have (value, step) */
- if ( state == Py_None ) {
- /* First time, it seems. Set defaults */
- valpred = 0;
- index = 0;
- } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
- return 0;
+ /* Step 5 - Assemble value, update index and step values */
+ delta |= sign;
+ index += indexTable[delta];
+ if ( index < 0 ) index = 0;
+ if ( index > 88 ) index = 88;
step = stepsizeTable[index];
- bufferstep = 1;
-
- for ( i=0; i < len; i += size ) {
- if ( size == 1 ) val = ((int)*CHARP(cp, i)) << 8;
- else if ( size == 2 ) val = (int)*SHORTP(cp, i);
- else if ( size == 4 ) val = ((int)*LONGP(cp, i)) >> 16;
-
- /* Step 1 - compute difference with previous value */
- diff = val - valpred;
- sign = (diff < 0) ? 8 : 0;
- if ( sign ) diff = (-diff);
-
- /* Step 2 - Divide and clamp */
- /* Note:
- ** This code *approximately* computes:
- ** delta = diff*4/step;
- ** vpdiff = (delta+0.5)*step/4;
- ** but in shift step bits are dropped. The net result of this
- ** is that even if you have fast mul/div hardware you cannot
- ** put it to good use since the fixup would be too expensive.
- */
- delta = 0;
- vpdiff = (step >> 3);
-
- if ( diff >= step ) {
- delta = 4;
- diff -= step;
- vpdiff += step;
- }
- step >>= 1;
- if ( diff >= step ) {
- delta |= 2;
- diff -= step;
- vpdiff += step;
- }
- step >>= 1;
- if ( diff >= step ) {
- delta |= 1;
- vpdiff += step;
- }
-
- /* Step 3 - Update previous value */
- if ( sign )
- valpred -= vpdiff;
- else
- valpred += vpdiff;
-
- /* Step 4 - Clamp previous value to 16 bits */
- if ( valpred > 32767 )
- valpred = 32767;
- else if ( valpred < -32768 )
- valpred = -32768;
-
- /* Step 5 - Assemble value, update index and step values */
- delta |= sign;
-
- index += indexTable[delta];
- if ( index < 0 ) index = 0;
- if ( index > 88 ) index = 88;
- step = stepsizeTable[index];
-
- /* Step 6 - Output value */
- if ( bufferstep ) {
- outputbuffer = (delta << 4) & 0xf0;
- } else {
- *ncp++ = (delta & 0x0f) | outputbuffer;
- }
- bufferstep = !bufferstep;
+
+ /* Step 6 - Output value */
+ if ( bufferstep ) {
+ outputbuffer = (delta << 4) & 0xf0;
+ } else {
+ *ncp++ = (delta & 0x0f) | outputbuffer;
}
- rv = Py_BuildValue("(O(ii))", str, valpred, index);
- Py_DECREF(str);
- return rv;
+ bufferstep = !bufferstep;
+ }
+ rv = Py_BuildValue("(O(ii))", str, valpred, index);
+ Py_DECREF(str);
+ return rv;
}
static PyObject *
audioop_adpcm2lin(PyObject *self, PyObject *args)
{
- signed char *cp;
- signed char *ncp;
- int len, new_len, size, valpred, step, delta, index, sign, vpdiff;
- PyObject *rv, *str, *state;
- int i, inputbuffer = 0, bufferstep;
-
- if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin",
- &cp, &len, &size, &state) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4) {
- PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
- return 0;
+ signed char *cp;
+ signed char *ncp;
+ int len, new_len, size, valpred, step, delta, index, sign, vpdiff;
+ PyObject *rv, *str, *state;
+ int i, inputbuffer = 0, bufferstep;
+
+ if ( !PyArg_ParseTuple(args, "s#iO:adpcm2lin",
+ &cp, &len, &size, &state) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4) {
+ PyErr_SetString(AudioopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+
+ /* Decode state, should have (value, step) */
+ if ( state == Py_None ) {
+ /* First time, it seems. Set defaults */
+ valpred = 0;
+ index = 0;
+ } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
+ return 0;
+
+ new_len = len*size*2;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_MemoryError,
+ "not enough memory for output buffer");
+ return 0;
+ }
+ str = PyString_FromStringAndSize(NULL, new_len);
+ if ( str == 0 )
+ return 0;
+ ncp = (signed char *)PyString_AsString(str);
+
+ step = stepsizeTable[index];
+ bufferstep = 0;
+
+ for ( i=0; i < new_len; i += size ) {
+ /* Step 1 - get the delta value and compute next index */
+ if ( bufferstep ) {
+ delta = inputbuffer & 0xf;
+ } else {
+ inputbuffer = *cp++;
+ delta = (inputbuffer >> 4) & 0xf;
}
- /* Decode state, should have (value, step) */
- if ( state == Py_None ) {
- /* First time, it seems. Set defaults */
- valpred = 0;
- index = 0;
- } else if ( !PyArg_ParseTuple(state, "ii", &valpred, &index) )
- return 0;
-
- new_len = len*size*2;
- if (new_len < 0) {
- PyErr_SetString(PyExc_MemoryError,
- "not enough memory for output buffer");
- return 0;
- }
- str = PyString_FromStringAndSize(NULL, new_len);
- if ( str == 0 )
- return 0;
- ncp = (signed char *)PyString_AsString(str);
+ bufferstep = !bufferstep;
+
+ /* Step 2 - Find new index value (for later) */
+ index += indexTable[delta];
+ if ( index < 0 ) index = 0;
+ if ( index > 88 ) index = 88;
+ /* Step 3 - Separate sign and magnitude */
+ sign = delta & 8;
+ delta = delta & 7;
+
+ /* Step 4 - Compute difference and new predicted value */
+ /*
+ ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
+ ** in adpcm_coder.
+ */
+ vpdiff = step >> 3;
+ if ( delta & 4 ) vpdiff += step;
+ if ( delta & 2 ) vpdiff += step>>1;
+ if ( delta & 1 ) vpdiff += step>>2;
+
+ if ( sign )
+ valpred -= vpdiff;
+ else
+ valpred += vpdiff;
+
+ /* Step 5 - clamp output value */
+ if ( valpred > 32767 )
+ valpred = 32767;
+ else if ( valpred < -32768 )
+ valpred = -32768;
+
+ /* Step 6 - Update step value */
step = stepsizeTable[index];
- bufferstep = 0;
-
- for ( i=0; i < new_len; i += size ) {
- /* Step 1 - get the delta value and compute next index */
- if ( bufferstep ) {
- delta = inputbuffer & 0xf;
- } else {
- inputbuffer = *cp++;
- delta = (inputbuffer >> 4) & 0xf;
- }
-
- bufferstep = !bufferstep;
-
- /* Step 2 - Find new index value (for later) */
- index += indexTable[delta];
- if ( index < 0 ) index = 0;
- if ( index > 88 ) index = 88;
-
- /* Step 3 - Separate sign and magnitude */
- sign = delta & 8;
- delta = delta & 7;
-
- /* Step 4 - Compute difference and new predicted value */
- /*
- ** Computes 'vpdiff = (delta+0.5)*step/4', but see comment
- ** in adpcm_coder.
- */
- vpdiff = step >> 3;
- if ( delta & 4 ) vpdiff += step;
- if ( delta & 2 ) vpdiff += step>>1;
- if ( delta & 1 ) vpdiff += step>>2;
-
- if ( sign )
- valpred -= vpdiff;
- else
- valpred += vpdiff;
-
- /* Step 5 - clamp output value */
- if ( valpred > 32767 )
- valpred = 32767;
- else if ( valpred < -32768 )
- valpred = -32768;
-
- /* Step 6 - Update step value */
- step = stepsizeTable[index];
-
- /* Step 6 - Output value */
- if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8);
- else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred);
- else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16);
- }
- rv = Py_BuildValue("(O(ii))", str, valpred, index);
- Py_DECREF(str);
- return rv;
+ /* Step 6 - Output value */
+ if ( size == 1 ) *CHARP(ncp, i) = (signed char)(valpred >> 8);
+ else if ( size == 2 ) *SHORTP(ncp, i) = (short)(valpred);
+ else if ( size == 4 ) *LONGP(ncp, i) = (Py_Int32)(valpred<<16);
+ }
+
+ rv = Py_BuildValue("(O(ii))", str, valpred, index);
+ Py_DECREF(str);
+ return rv;
}
static PyMethodDef audioop_methods[] = {
- { "max", audioop_max, METH_VARARGS },
- { "minmax", audioop_minmax, METH_VARARGS },
- { "avg", audioop_avg, METH_VARARGS },
- { "maxpp", audioop_maxpp, METH_VARARGS },
- { "avgpp", audioop_avgpp, METH_VARARGS },
- { "rms", audioop_rms, METH_VARARGS },
- { "findfit", audioop_findfit, METH_VARARGS },
- { "findmax", audioop_findmax, METH_VARARGS },
- { "findfactor", audioop_findfactor, METH_VARARGS },
- { "cross", audioop_cross, METH_VARARGS },
- { "mul", audioop_mul, METH_VARARGS },
- { "add", audioop_add, METH_VARARGS },
- { "bias", audioop_bias, METH_VARARGS },
- { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS },
- { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS },
- { "alaw2lin", audioop_alaw2lin, METH_VARARGS },
- { "lin2alaw", audioop_lin2alaw, METH_VARARGS },
- { "lin2lin", audioop_lin2lin, METH_VARARGS },
- { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS },
- { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS },
- { "tomono", audioop_tomono, METH_VARARGS },
- { "tostereo", audioop_tostereo, METH_VARARGS },
- { "getsample", audioop_getsample, METH_VARARGS },
- { "reverse", audioop_reverse, METH_VARARGS },
- { "ratecv", audioop_ratecv, METH_VARARGS },
- { 0, 0 }
+ { "max", audioop_max, METH_VARARGS },
+ { "minmax", audioop_minmax, METH_VARARGS },
+ { "avg", audioop_avg, METH_VARARGS },
+ { "maxpp", audioop_maxpp, METH_VARARGS },
+ { "avgpp", audioop_avgpp, METH_VARARGS },
+ { "rms", audioop_rms, METH_VARARGS },
+ { "findfit", audioop_findfit, METH_VARARGS },
+ { "findmax", audioop_findmax, METH_VARARGS },
+ { "findfactor", audioop_findfactor, METH_VARARGS },
+ { "cross", audioop_cross, METH_VARARGS },
+ { "mul", audioop_mul, METH_VARARGS },
+ { "add", audioop_add, METH_VARARGS },
+ { "bias", audioop_bias, METH_VARARGS },
+ { "ulaw2lin", audioop_ulaw2lin, METH_VARARGS },
+ { "lin2ulaw", audioop_lin2ulaw, METH_VARARGS },
+ { "alaw2lin", audioop_alaw2lin, METH_VARARGS },
+ { "lin2alaw", audioop_lin2alaw, METH_VARARGS },
+ { "lin2lin", audioop_lin2lin, METH_VARARGS },
+ { "adpcm2lin", audioop_adpcm2lin, METH_VARARGS },
+ { "lin2adpcm", audioop_lin2adpcm, METH_VARARGS },
+ { "tomono", audioop_tomono, METH_VARARGS },
+ { "tostereo", audioop_tostereo, METH_VARARGS },
+ { "getsample", audioop_getsample, METH_VARARGS },
+ { "reverse", audioop_reverse, METH_VARARGS },
+ { "ratecv", audioop_ratecv, METH_VARARGS },
+ { 0, 0 }
};
PyMODINIT_FUNC
initaudioop(void)
{
- PyObject *m, *d;
- m = Py_InitModule("audioop", audioop_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- if (d == NULL)
- return;
- AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
- if (AudioopError != NULL)
- PyDict_SetItemString(d,"error",AudioopError);
+ PyObject *m, *d;
+ m = Py_InitModule("audioop", audioop_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ if (d == NULL)
+ return;
+ AudioopError = PyErr_NewException("audioop.error", NULL, NULL);
+ if (AudioopError != NULL)
+ PyDict_SetItemString(d,"error",AudioopError);
}
diff --git a/Modules/binascii.c b/Modules/binascii.c
index db675f9..2d91b7f 100644
--- a/Modules/binascii.c
+++ b/Modules/binascii.c
@@ -3,40 +3,40 @@
**
** This module currently supports the following encodings:
** uuencode:
-** each line encodes 45 bytes (except possibly the last)
-** First char encodes (binary) length, rest data
-** each char encodes 6 bits, as follows:
-** binary: 01234567 abcdefgh ijklmnop
-** ascii: 012345 67abcd efghij klmnop
-** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc.
-** short binary data is zero-extended (so the bits are always in the
-** right place), this does *not* reflect in the length.
+** each line encodes 45 bytes (except possibly the last)
+** First char encodes (binary) length, rest data
+** each char encodes 6 bits, as follows:
+** binary: 01234567 abcdefgh ijklmnop
+** ascii: 012345 67abcd efghij klmnop
+** ASCII encoding method is "excess-space": 000000 is encoded as ' ', etc.
+** short binary data is zero-extended (so the bits are always in the
+** right place), this does *not* reflect in the length.
** base64:
** Line breaks are insignificant, but lines are at most 76 chars
** each char encodes 6 bits, in similar order as uucode/hqx. Encoding
** is done via a table.
** Short binary data is filled (in ASCII) with '='.
** hqx:
-** File starts with introductory text, real data starts and ends
-** with colons.
-** Data consists of three similar parts: info, datafork, resourcefork.
-** Each part is protected (at the end) with a 16-bit crc
-** The binary data is run-length encoded, and then ascii-fied:
-** binary: 01234567 abcdefgh ijklmnop
-** ascii: 012345 67abcd efghij klmnop
-** ASCII encoding is table-driven, see the code.
-** Short binary data results in the runt ascii-byte being output with
-** the bits in the right place.
+** File starts with introductory text, real data starts and ends
+** with colons.
+** Data consists of three similar parts: info, datafork, resourcefork.
+** Each part is protected (at the end) with a 16-bit crc
+** The binary data is run-length encoded, and then ascii-fied:
+** binary: 01234567 abcdefgh ijklmnop
+** ascii: 012345 67abcd efghij klmnop
+** ASCII encoding is table-driven, see the code.
+** Short binary data results in the runt ascii-byte being output with
+** the bits in the right place.
**
** While I was reading dozens of programs that encode or decode the formats
** here (documentation? hihi:-) I have formulated Jansen's Observation:
**
-** Programs that encode binary data in ASCII are written in
-** such a style that they are as unreadable as possible. Devices used
-** include unnecessary global variables, burying important tables
-** in unrelated sourcefiles, putting functions in include files,
-** using seemingly-descriptive variable names for different purposes,
-** calls to empty subroutines and a host of others.
+** Programs that encode binary data in ASCII are written in
+** such a style that they are as unreadable as possible. Devices used
+** include unnecessary global variables, burying important tables
+** in unrelated sourcefiles, putting functions in include files,
+** using seemingly-descriptive variable names for different purposes,
+** calls to empty subroutines and a host of others.
**
** I have attempted to break with this tradition, but I guess that that
** does make the performance sub-optimal. Oh well, too bad...
@@ -75,67 +75,67 @@ static PyObject *Incomplete;
static unsigned char table_a2b_hqx[256] = {
/* ^@ ^A ^B ^C ^D ^E ^F ^G */
-/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 0*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
/* \b \t \n ^K ^L \r ^N ^O */
-/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL,
+/* 1*/ FAIL, FAIL, SKIP, FAIL, FAIL, SKIP, FAIL, FAIL,
/* ^P ^Q ^R ^S ^T ^U ^V ^W */
-/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 2*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
/* ^X ^Y ^Z ^[ ^\ ^] ^^ ^_ */
-/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 3*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
/* ! " # $ % & ' */
-/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
+/* 4*/ FAIL, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
/* ( ) * + , - . / */
-/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL,
+/* 5*/ 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, FAIL, FAIL,
/* 0 1 2 3 4 5 6 7 */
-/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL,
+/* 6*/ 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, FAIL,
/* 8 9 : ; < = > ? */
-/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL,
+/* 7*/ 0x14, 0x15, DONE, FAIL, FAIL, FAIL, FAIL, FAIL,
/* @ A B C D E F G */
-/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
+/* 8*/ 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D,
/* H I J K L M N O */
-/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL,
+/* 9*/ 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23, 0x24, FAIL,
/* P Q R S T U V W */
-/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL,
+/*10*/ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, FAIL,
/* X Y Z [ \ ] ^ _ */
-/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL,
+/*11*/ 0x2C, 0x2D, 0x2E, 0x2F, FAIL, FAIL, FAIL, FAIL,
/* ` a b c d e f g */
-/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL,
+/*12*/ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, FAIL,
/* h i j k l m n o */
-/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL,
+/*13*/ 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, FAIL, FAIL,
/* p q r s t u v w */
-/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL,
+/*14*/ 0x3D, 0x3E, 0x3F, FAIL, FAIL, FAIL, FAIL, FAIL,
/* x y z { | } ~ ^? */
-/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
-/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
- FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/*15*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+/*16*/ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
+ FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL, FAIL,
};
static unsigned char table_b2a_hqx[] =
"!\"#$%&'()*+,-012345689@ABCDEFGHIJKLMNPQRSTUVXYZ[`abcdefhijklmpqr";
static char table_a2b_base64[] = {
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
- -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
- 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */
- -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
- 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
- -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
- 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
+ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
+ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,-1,
+ -1,-1,-1,-1, -1,-1,-1,-1, -1,-1,-1,62, -1,-1,-1,63,
+ 52,53,54,55, 56,57,58,59, 60,61,-1,-1, -1, 0,-1,-1, /* Note PAD->0 */
+ -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11,12,13,14,
+ 15,16,17,18, 19,20,21,22, 23,24,25,-1, -1,-1,-1,-1,
+ -1,26,27,28, 29,30,31,32, 33,34,35,36, 37,38,39,40,
+ 41,42,43,44, 45,46,47,48, 49,50,51,-1, -1,-1,-1,-1
};
#define BASE64_PAD '='
@@ -149,38 +149,38 @@ static unsigned char table_b2a_base64[] =
static unsigned short crctab_hqx[256] = {
- 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
- 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
- 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
- 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
- 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
- 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
- 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
- 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
- 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
- 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
- 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
- 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
- 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
- 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
- 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
- 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
- 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
- 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
- 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
- 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
- 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
- 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
- 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
- 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
- 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
- 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
- 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
- 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
- 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
- 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
- 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
- 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
+ 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
+ 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
+ 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
+ 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de,
+ 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485,
+ 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d,
+ 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4,
+ 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc,
+ 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823,
+ 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b,
+ 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12,
+ 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a,
+ 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41,
+ 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49,
+ 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70,
+ 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78,
+ 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f,
+ 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067,
+ 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e,
+ 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256,
+ 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d,
+ 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405,
+ 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c,
+ 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634,
+ 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab,
+ 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3,
+ 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a,
+ 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92,
+ 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9,
+ 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1,
+ 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8,
+ 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0,
};
PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data");
@@ -188,85 +188,85 @@ PyDoc_STRVAR(doc_a2b_uu, "(ascii) -> bin. Decode a line of uuencoded data");
static PyObject *
binascii_a2b_uu(PyObject *self, PyObject *args)
{
- Py_buffer pascii;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t ascii_len, bin_len;
-
- if ( !PyArg_ParseTuple(args, "s*:a2b_uu", &pascii) )
- return NULL;
- ascii_data = pascii.buf;
- ascii_len = pascii.len;
-
- assert(ascii_len >= 0);
-
- /* First byte: binary data length (in bytes) */
- bin_len = (*ascii_data++ - ' ') & 077;
- ascii_len--;
-
- /* Allocate the buffer */
- if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL ) {
- PyBuffer_Release(&pascii);
- return NULL;
- }
- bin_data = (unsigned char *)PyString_AS_STRING(rv);
-
- for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) {
- /* XXX is it really best to add NULs if there's no more data */
- this_ch = (ascii_len > 0) ? *ascii_data : 0;
- if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) {
- /*
- ** Whitespace. Assume some spaces got eaten at
- ** end-of-line. (We check this later)
- */
- this_ch = 0;
- } else {
- /* Check the character for legality
- ** The 64 in stead of the expected 63 is because
- ** there are a few uuencodes out there that use
- ** '`' as zero instead of space.
- */
- if ( this_ch < ' ' || this_ch > (' ' + 64)) {
- PyErr_SetString(Error, "Illegal char");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- this_ch = (this_ch - ' ') & 077;
- }
- /*
- ** Shift it in on the low end, and see if there's
- ** a byte ready for output.
- */
- leftchar = (leftchar << 6) | (this_ch);
- leftbits += 6;
- if ( leftbits >= 8 ) {
- leftbits -= 8;
- *bin_data++ = (leftchar >> leftbits) & 0xff;
- leftchar &= ((1 << leftbits) - 1);
- bin_len--;
- }
- }
- /*
- ** Finally, check that if there's anything left on the line
- ** that it's whitespace only.
- */
- while( ascii_len-- > 0 ) {
- this_ch = *ascii_data++;
- /* Extra '`' may be written as padding in some cases */
- if ( this_ch != ' ' && this_ch != ' '+64 &&
- this_ch != '\n' && this_ch != '\r' ) {
- PyErr_SetString(Error, "Trailing garbage");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- }
- PyBuffer_Release(&pascii);
- return rv;
+ Py_buffer pascii;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t ascii_len, bin_len;
+
+ if ( !PyArg_ParseTuple(args, "s*:a2b_uu", &pascii) )
+ return NULL;
+ ascii_data = pascii.buf;
+ ascii_len = pascii.len;
+
+ assert(ascii_len >= 0);
+
+ /* First byte: binary data length (in bytes) */
+ bin_len = (*ascii_data++ - ' ') & 077;
+ ascii_len--;
+
+ /* Allocate the buffer */
+ if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL ) {
+ PyBuffer_Release(&pascii);
+ return NULL;
+ }
+ bin_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ for( ; bin_len > 0 ; ascii_len--, ascii_data++ ) {
+ /* XXX is it really best to add NULs if there's no more data */
+ this_ch = (ascii_len > 0) ? *ascii_data : 0;
+ if ( this_ch == '\n' || this_ch == '\r' || ascii_len <= 0) {
+ /*
+ ** Whitespace. Assume some spaces got eaten at
+ ** end-of-line. (We check this later)
+ */
+ this_ch = 0;
+ } else {
+ /* Check the character for legality
+ ** The 64 in stead of the expected 63 is because
+ ** there are a few uuencodes out there that use
+ ** '`' as zero instead of space.
+ */
+ if ( this_ch < ' ' || this_ch > (' ' + 64)) {
+ PyErr_SetString(Error, "Illegal char");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ this_ch = (this_ch - ' ') & 077;
+ }
+ /*
+ ** Shift it in on the low end, and see if there's
+ ** a byte ready for output.
+ */
+ leftchar = (leftchar << 6) | (this_ch);
+ leftbits += 6;
+ if ( leftbits >= 8 ) {
+ leftbits -= 8;
+ *bin_data++ = (leftchar >> leftbits) & 0xff;
+ leftchar &= ((1 << leftbits) - 1);
+ bin_len--;
+ }
+ }
+ /*
+ ** Finally, check that if there's anything left on the line
+ ** that it's whitespace only.
+ */
+ while( ascii_len-- > 0 ) {
+ this_ch = *ascii_data++;
+ /* Extra '`' may be written as padding in some cases */
+ if ( this_ch != ' ' && this_ch != ' '+64 &&
+ this_ch != '\n' && this_ch != '\r' ) {
+ PyErr_SetString(Error, "Trailing garbage");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ }
+ PyBuffer_Release(&pascii);
+ return rv;
}
PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
@@ -274,86 +274,86 @@ PyDoc_STRVAR(doc_b2a_uu, "(bin) -> ascii. Uuencode line of data");
static PyObject *
binascii_b2a_uu(PyObject *self, PyObject *args)
{
- Py_buffer pbin;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t bin_len;
-
- if ( !PyArg_ParseTuple(args, "s*:b2a_uu", &pbin) )
- return NULL;
- bin_data = pbin.buf;
- bin_len = pbin.len;
- if ( bin_len > 45 ) {
- /* The 45 is a limit that appears in all uuencode's */
- PyErr_SetString(Error, "At most 45 bytes at once");
- PyBuffer_Release(&pbin);
- return NULL;
- }
-
- /* We're lazy and allocate to much (fixed up later) */
- if ( (rv=PyString_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) {
- PyBuffer_Release(&pbin);
- return NULL;
- }
- ascii_data = (unsigned char *)PyString_AS_STRING(rv);
-
- /* Store the length */
- *ascii_data++ = ' ' + (bin_len & 077);
-
- for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) {
- /* Shift the data (or padding) into our buffer */
- if ( bin_len > 0 ) /* Data */
- leftchar = (leftchar << 8) | *bin_data;
- else /* Padding */
- leftchar <<= 8;
- leftbits += 8;
-
- /* See if there are 6-bit groups ready */
- while ( leftbits >= 6 ) {
- this_ch = (leftchar >> (leftbits-6)) & 0x3f;
- leftbits -= 6;
- *ascii_data++ = this_ch + ' ';
- }
- }
- *ascii_data++ = '\n'; /* Append a courtesy newline */
-
- if (_PyString_Resize(&rv,
- (ascii_data -
- (unsigned char *)PyString_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbin);
- return rv;
+ Py_buffer pbin;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t bin_len;
+
+ if ( !PyArg_ParseTuple(args, "s*:b2a_uu", &pbin) )
+ return NULL;
+ bin_data = pbin.buf;
+ bin_len = pbin.len;
+ if ( bin_len > 45 ) {
+ /* The 45 is a limit that appears in all uuencode's */
+ PyErr_SetString(Error, "At most 45 bytes at once");
+ PyBuffer_Release(&pbin);
+ return NULL;
+ }
+
+ /* We're lazy and allocate to much (fixed up later) */
+ if ( (rv=PyString_FromStringAndSize(NULL, 2 + (bin_len+2)/3*4)) == NULL ) {
+ PyBuffer_Release(&pbin);
+ return NULL;
+ }
+ ascii_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ /* Store the length */
+ *ascii_data++ = ' ' + (bin_len & 077);
+
+ for( ; bin_len > 0 || leftbits != 0 ; bin_len--, bin_data++ ) {
+ /* Shift the data (or padding) into our buffer */
+ if ( bin_len > 0 ) /* Data */
+ leftchar = (leftchar << 8) | *bin_data;
+ else /* Padding */
+ leftchar <<= 8;
+ leftbits += 8;
+
+ /* See if there are 6-bit groups ready */
+ while ( leftbits >= 6 ) {
+ this_ch = (leftchar >> (leftbits-6)) & 0x3f;
+ leftbits -= 6;
+ *ascii_data++ = this_ch + ' ';
+ }
+ }
+ *ascii_data++ = '\n'; /* Append a courtesy newline */
+
+ if (_PyString_Resize(&rv,
+ (ascii_data -
+ (unsigned char *)PyString_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbin);
+ return rv;
}
static int
binascii_find_valid(unsigned char *s, Py_ssize_t slen, int num)
{
- /* Finds & returns the (num+1)th
- ** valid character for base64, or -1 if none.
- */
-
- int ret = -1;
- unsigned char c, b64val;
-
- while ((slen > 0) && (ret == -1)) {
- c = *s;
- b64val = table_a2b_base64[c & 0x7f];
- if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) {
- if (num == 0)
- ret = *s;
- num--;
- }
-
- s++;
- slen--;
- }
- return ret;
+ /* Finds & returns the (num+1)th
+ ** valid character for base64, or -1 if none.
+ */
+
+ int ret = -1;
+ unsigned char c, b64val;
+
+ while ((slen > 0) && (ret == -1)) {
+ c = *s;
+ b64val = table_a2b_base64[c & 0x7f];
+ if ( ((c <= 0x7f) && (b64val != (unsigned char)-1)) ) {
+ if (num == 0)
+ ret = *s;
+ num--;
+ }
+
+ s++;
+ slen--;
+ }
+ return ret;
}
PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data");
@@ -361,108 +361,108 @@ PyDoc_STRVAR(doc_a2b_base64, "(ascii) -> bin. Decode a line of base64 data");
static PyObject *
binascii_a2b_base64(PyObject *self, PyObject *args)
{
- Py_buffer pascii;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t ascii_len, bin_len;
- int quad_pos = 0;
-
- if ( !PyArg_ParseTuple(args, "s*:a2b_base64", &pascii) )
- return NULL;
- ascii_data = pascii.buf;
- ascii_len = pascii.len;
-
- assert(ascii_len >= 0);
-
- if (ascii_len > PY_SSIZE_T_MAX - 3) {
- PyBuffer_Release(&pascii);
- return PyErr_NoMemory();
- }
-
- bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
-
- /* Allocate the buffer */
- if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL ) {
- PyBuffer_Release(&pascii);
- return NULL;
- }
- bin_data = (unsigned char *)PyString_AS_STRING(rv);
- bin_len = 0;
-
- for( ; ascii_len > 0; ascii_len--, ascii_data++) {
- this_ch = *ascii_data;
-
- if (this_ch > 0x7f ||
- this_ch == '\r' || this_ch == '\n' || this_ch == ' ')
- continue;
-
- /* Check for pad sequences and ignore
- ** the invalid ones.
- */
- if (this_ch == BASE64_PAD) {
- if ( (quad_pos < 2) ||
- ((quad_pos == 2) &&
- (binascii_find_valid(ascii_data, ascii_len, 1)
- != BASE64_PAD)) )
- {
- continue;
- }
- else {
- /* A pad sequence means no more input.
- ** We've already interpreted the data
- ** from the quad at this point.
- */
- leftbits = 0;
- break;
- }
- }
-
- this_ch = table_a2b_base64[*ascii_data];
- if ( this_ch == (unsigned char) -1 )
- continue;
-
- /*
- ** Shift it in on the low end, and see if there's
- ** a byte ready for output.
- */
- quad_pos = (quad_pos + 1) & 0x03;
- leftchar = (leftchar << 6) | (this_ch);
- leftbits += 6;
-
- if ( leftbits >= 8 ) {
- leftbits -= 8;
- *bin_data++ = (leftchar >> leftbits) & 0xff;
- bin_len++;
- leftchar &= ((1 << leftbits) - 1);
- }
- }
-
- if (leftbits != 0) {
- PyBuffer_Release(&pascii);
- PyErr_SetString(Error, "Incorrect padding");
- Py_DECREF(rv);
- return NULL;
- }
-
- /* And set string size correctly. If the result string is empty
- ** (because the input was all invalid) return the shared empty
- ** string instead; _PyString_Resize() won't do this for us.
- */
- if (bin_len > 0) {
- if (_PyString_Resize(&rv, bin_len) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- }
- else {
- Py_DECREF(rv);
- rv = PyString_FromStringAndSize("", 0);
- }
- PyBuffer_Release(&pascii);
- return rv;
+ Py_buffer pascii;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t ascii_len, bin_len;
+ int quad_pos = 0;
+
+ if ( !PyArg_ParseTuple(args, "s*:a2b_base64", &pascii) )
+ return NULL;
+ ascii_data = pascii.buf;
+ ascii_len = pascii.len;
+
+ assert(ascii_len >= 0);
+
+ if (ascii_len > PY_SSIZE_T_MAX - 3) {
+ PyBuffer_Release(&pascii);
+ return PyErr_NoMemory();
+ }
+
+ bin_len = ((ascii_len+3)/4)*3; /* Upper bound, corrected later */
+
+ /* Allocate the buffer */
+ if ( (rv=PyString_FromStringAndSize(NULL, bin_len)) == NULL ) {
+ PyBuffer_Release(&pascii);
+ return NULL;
+ }
+ bin_data = (unsigned char *)PyString_AS_STRING(rv);
+ bin_len = 0;
+
+ for( ; ascii_len > 0; ascii_len--, ascii_data++) {
+ this_ch = *ascii_data;
+
+ if (this_ch > 0x7f ||
+ this_ch == '\r' || this_ch == '\n' || this_ch == ' ')
+ continue;
+
+ /* Check for pad sequences and ignore
+ ** the invalid ones.
+ */
+ if (this_ch == BASE64_PAD) {
+ if ( (quad_pos < 2) ||
+ ((quad_pos == 2) &&
+ (binascii_find_valid(ascii_data, ascii_len, 1)
+ != BASE64_PAD)) )
+ {
+ continue;
+ }
+ else {
+ /* A pad sequence means no more input.
+ ** We've already interpreted the data
+ ** from the quad at this point.
+ */
+ leftbits = 0;
+ break;
+ }
+ }
+
+ this_ch = table_a2b_base64[*ascii_data];
+ if ( this_ch == (unsigned char) -1 )
+ continue;
+
+ /*
+ ** Shift it in on the low end, and see if there's
+ ** a byte ready for output.
+ */
+ quad_pos = (quad_pos + 1) & 0x03;
+ leftchar = (leftchar << 6) | (this_ch);
+ leftbits += 6;
+
+ if ( leftbits >= 8 ) {
+ leftbits -= 8;
+ *bin_data++ = (leftchar >> leftbits) & 0xff;
+ bin_len++;
+ leftchar &= ((1 << leftbits) - 1);
+ }
+ }
+
+ if (leftbits != 0) {
+ PyBuffer_Release(&pascii);
+ PyErr_SetString(Error, "Incorrect padding");
+ Py_DECREF(rv);
+ return NULL;
+ }
+
+ /* And set string size correctly. If the result string is empty
+ ** (because the input was all invalid) return the shared empty
+ ** string instead; _PyString_Resize() won't do this for us.
+ */
+ if (bin_len > 0) {
+ if (_PyString_Resize(&rv, bin_len) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ }
+ else {
+ Py_DECREF(rv);
+ rv = PyString_FromStringAndSize("", 0);
+ }
+ PyBuffer_Release(&pascii);
+ return rv;
}
PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
@@ -470,66 +470,66 @@ PyDoc_STRVAR(doc_b2a_base64, "(bin) -> ascii. Base64-code line of data");
static PyObject *
binascii_b2a_base64(PyObject *self, PyObject *args)
{
- Py_buffer pbuf;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t bin_len;
-
- if ( !PyArg_ParseTuple(args, "s*:b2a_base64", &pbuf) )
- return NULL;
- bin_data = pbuf.buf;
- bin_len = pbuf.len;
-
- assert(bin_len >= 0);
-
- if ( bin_len > BASE64_MAXBIN ) {
- PyErr_SetString(Error, "Too much data for base64 line");
- PyBuffer_Release(&pbuf);
- return NULL;
- }
-
- /* We're lazy and allocate too much (fixed up later).
- "+3" leaves room for up to two pad characters and a trailing
- newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */
- if ( (rv=PyString_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) {
- PyBuffer_Release(&pbuf);
- return NULL;
- }
- ascii_data = (unsigned char *)PyString_AS_STRING(rv);
-
- for( ; bin_len > 0 ; bin_len--, bin_data++ ) {
- /* Shift the data into our buffer */
- leftchar = (leftchar << 8) | *bin_data;
- leftbits += 8;
-
- /* See if there are 6-bit groups ready */
- while ( leftbits >= 6 ) {
- this_ch = (leftchar >> (leftbits-6)) & 0x3f;
- leftbits -= 6;
- *ascii_data++ = table_b2a_base64[this_ch];
- }
- }
- if ( leftbits == 2 ) {
- *ascii_data++ = table_b2a_base64[(leftchar&3) << 4];
- *ascii_data++ = BASE64_PAD;
- *ascii_data++ = BASE64_PAD;
- } else if ( leftbits == 4 ) {
- *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2];
- *ascii_data++ = BASE64_PAD;
- }
- *ascii_data++ = '\n'; /* Append a courtesy newline */
-
- if (_PyString_Resize(&rv,
- (ascii_data -
- (unsigned char *)PyString_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbuf);
- return rv;
+ Py_buffer pbuf;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t bin_len;
+
+ if ( !PyArg_ParseTuple(args, "s*:b2a_base64", &pbuf) )
+ return NULL;
+ bin_data = pbuf.buf;
+ bin_len = pbuf.len;
+
+ assert(bin_len >= 0);
+
+ if ( bin_len > BASE64_MAXBIN ) {
+ PyErr_SetString(Error, "Too much data for base64 line");
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+
+ /* We're lazy and allocate too much (fixed up later).
+ "+3" leaves room for up to two pad characters and a trailing
+ newline. Note that 'b' gets encoded as 'Yg==\n' (1 in, 5 out). */
+ if ( (rv=PyString_FromStringAndSize(NULL, bin_len*2 + 3)) == NULL ) {
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+ ascii_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ for( ; bin_len > 0 ; bin_len--, bin_data++ ) {
+ /* Shift the data into our buffer */
+ leftchar = (leftchar << 8) | *bin_data;
+ leftbits += 8;
+
+ /* See if there are 6-bit groups ready */
+ while ( leftbits >= 6 ) {
+ this_ch = (leftchar >> (leftbits-6)) & 0x3f;
+ leftbits -= 6;
+ *ascii_data++ = table_b2a_base64[this_ch];
+ }
+ }
+ if ( leftbits == 2 ) {
+ *ascii_data++ = table_b2a_base64[(leftchar&3) << 4];
+ *ascii_data++ = BASE64_PAD;
+ *ascii_data++ = BASE64_PAD;
+ } else if ( leftbits == 4 ) {
+ *ascii_data++ = table_b2a_base64[(leftchar&0xf) << 2];
+ *ascii_data++ = BASE64_PAD;
+ }
+ *ascii_data++ = '\n'; /* Append a courtesy newline */
+
+ if (_PyString_Resize(&rv,
+ (ascii_data -
+ (unsigned char *)PyString_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbuf);
+ return rv;
}
PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
@@ -537,85 +537,85 @@ PyDoc_STRVAR(doc_a2b_hqx, "ascii -> bin, done. Decode .hqx coding");
static PyObject *
binascii_a2b_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pascii;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t len;
- int done = 0;
-
- if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) )
- return NULL;
- ascii_data = pascii.buf;
- len = pascii.len;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX - 2) {
- PyBuffer_Release(&pascii);
- return PyErr_NoMemory();
- }
-
- /* Allocate a string that is too big (fixed later)
- Add two to the initial length to prevent interning which
- would preclude subsequent resizing. */
- if ( (rv=PyString_FromStringAndSize(NULL, len+2)) == NULL ) {
- PyBuffer_Release(&pascii);
- return NULL;
- }
- bin_data = (unsigned char *)PyString_AS_STRING(rv);
-
- for( ; len > 0 ; len--, ascii_data++ ) {
- /* Get the byte and look it up */
- this_ch = table_a2b_hqx[*ascii_data];
- if ( this_ch == SKIP )
- continue;
- if ( this_ch == FAIL ) {
- PyErr_SetString(Error, "Illegal char");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- if ( this_ch == DONE ) {
- /* The terminating colon */
- done = 1;
- break;
- }
-
- /* Shift it into the buffer and see if any bytes are ready */
- leftchar = (leftchar << 6) | (this_ch);
- leftbits += 6;
- if ( leftbits >= 8 ) {
- leftbits -= 8;
- *bin_data++ = (leftchar >> leftbits) & 0xff;
- leftchar &= ((1 << leftbits) - 1);
- }
- }
-
- if ( leftbits && !done ) {
- PyErr_SetString(Incomplete,
- "String has incomplete number of bytes");
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return NULL;
- }
- if (_PyString_Resize(&rv,
- (bin_data -
- (unsigned char *)PyString_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- if (rv) {
- PyObject *rrv = Py_BuildValue("Oi", rv, done);
- PyBuffer_Release(&pascii);
- Py_DECREF(rv);
- return rrv;
- }
-
- PyBuffer_Release(&pascii);
- return NULL;
+ Py_buffer pascii;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t len;
+ int done = 0;
+
+ if ( !PyArg_ParseTuple(args, "s*:a2b_hqx", &pascii) )
+ return NULL;
+ ascii_data = pascii.buf;
+ len = pascii.len;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX - 2) {
+ PyBuffer_Release(&pascii);
+ return PyErr_NoMemory();
+ }
+
+ /* Allocate a string that is too big (fixed later)
+ Add two to the initial length to prevent interning which
+ would preclude subsequent resizing. */
+ if ( (rv=PyString_FromStringAndSize(NULL, len+2)) == NULL ) {
+ PyBuffer_Release(&pascii);
+ return NULL;
+ }
+ bin_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ for( ; len > 0 ; len--, ascii_data++ ) {
+ /* Get the byte and look it up */
+ this_ch = table_a2b_hqx[*ascii_data];
+ if ( this_ch == SKIP )
+ continue;
+ if ( this_ch == FAIL ) {
+ PyErr_SetString(Error, "Illegal char");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ if ( this_ch == DONE ) {
+ /* The terminating colon */
+ done = 1;
+ break;
+ }
+
+ /* Shift it into the buffer and see if any bytes are ready */
+ leftchar = (leftchar << 6) | (this_ch);
+ leftbits += 6;
+ if ( leftbits >= 8 ) {
+ leftbits -= 8;
+ *bin_data++ = (leftchar >> leftbits) & 0xff;
+ leftchar &= ((1 << leftbits) - 1);
+ }
+ }
+
+ if ( leftbits && !done ) {
+ PyErr_SetString(Incomplete,
+ "String has incomplete number of bytes");
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ if (_PyString_Resize(&rv,
+ (bin_data -
+ (unsigned char *)PyString_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ if (rv) {
+ PyObject *rrv = Py_BuildValue("Oi", rv, done);
+ PyBuffer_Release(&pascii);
+ Py_DECREF(rv);
+ return rrv;
+ }
+
+ PyBuffer_Release(&pascii);
+ return NULL;
}
PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
@@ -623,63 +623,63 @@ PyDoc_STRVAR(doc_rlecode_hqx, "Binhex RLE-code binary data");
static PyObject *
binascii_rlecode_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pbuf;
- unsigned char *in_data, *out_data;
- PyObject *rv;
- unsigned char ch;
- Py_ssize_t in, inend, len;
-
- if ( !PyArg_ParseTuple(args, "s*:rlecode_hqx", &pbuf) )
- return NULL;
- in_data = pbuf.buf;
- len = pbuf.len;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX / 2 - 2) {
- PyBuffer_Release(&pbuf);
- return PyErr_NoMemory();
- }
-
- /* Worst case: output is twice as big as input (fixed later) */
- if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL ) {
- PyBuffer_Release(&pbuf);
- return NULL;
- }
- out_data = (unsigned char *)PyString_AS_STRING(rv);
-
- for( in=0; in<len; in++) {
- ch = in_data[in];
- if ( ch == RUNCHAR ) {
- /* RUNCHAR. Escape it. */
- *out_data++ = RUNCHAR;
- *out_data++ = 0;
- } else {
- /* Check how many following are the same */
- for(inend=in+1;
- inend<len && in_data[inend] == ch &&
- inend < in+255;
- inend++) ;
- if ( inend - in > 3 ) {
- /* More than 3 in a row. Output RLE. */
- *out_data++ = ch;
- *out_data++ = RUNCHAR;
- *out_data++ = inend-in;
- in = inend-1;
- } else {
- /* Less than 3. Output the byte itself */
- *out_data++ = ch;
- }
- }
- }
- if (_PyString_Resize(&rv,
- (out_data -
- (unsigned char *)PyString_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbuf);
- return rv;
+ Py_buffer pbuf;
+ unsigned char *in_data, *out_data;
+ PyObject *rv;
+ unsigned char ch;
+ Py_ssize_t in, inend, len;
+
+ if ( !PyArg_ParseTuple(args, "s*:rlecode_hqx", &pbuf) )
+ return NULL;
+ in_data = pbuf.buf;
+ len = pbuf.len;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX / 2 - 2) {
+ PyBuffer_Release(&pbuf);
+ return PyErr_NoMemory();
+ }
+
+ /* Worst case: output is twice as big as input (fixed later) */
+ if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL ) {
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+ out_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ for( in=0; in<len; in++) {
+ ch = in_data[in];
+ if ( ch == RUNCHAR ) {
+ /* RUNCHAR. Escape it. */
+ *out_data++ = RUNCHAR;
+ *out_data++ = 0;
+ } else {
+ /* Check how many following are the same */
+ for(inend=in+1;
+ inend<len && in_data[inend] == ch &&
+ inend < in+255;
+ inend++) ;
+ if ( inend - in > 3 ) {
+ /* More than 3 in a row. Output RLE. */
+ *out_data++ = ch;
+ *out_data++ = RUNCHAR;
+ *out_data++ = inend-in;
+ in = inend-1;
+ } else {
+ /* Less than 3. Output the byte itself */
+ *out_data++ = ch;
+ }
+ }
+ }
+ if (_PyString_Resize(&rv,
+ (out_data -
+ (unsigned char *)PyString_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbuf);
+ return rv;
}
PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
@@ -687,56 +687,56 @@ PyDoc_STRVAR(doc_b2a_hqx, "Encode .hqx data");
static PyObject *
binascii_b2a_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pbin;
- unsigned char *ascii_data, *bin_data;
- int leftbits = 0;
- unsigned char this_ch;
- unsigned int leftchar = 0;
- PyObject *rv;
- Py_ssize_t len;
-
- if ( !PyArg_ParseTuple(args, "s*:b2a_hqx", &pbin) )
- return NULL;
- bin_data = pbin.buf;
- len = pbin.len;
-
- assert(len >= 0);
-
- if (len > PY_SSIZE_T_MAX / 2 - 2) {
- PyBuffer_Release(&pbin);
- return PyErr_NoMemory();
- }
-
- /* Allocate a buffer that is at least large enough */
- if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL ) {
- PyBuffer_Release(&pbin);
- return NULL;
- }
- ascii_data = (unsigned char *)PyString_AS_STRING(rv);
-
- for( ; len > 0 ; len--, bin_data++ ) {
- /* Shift into our buffer, and output any 6bits ready */
- leftchar = (leftchar << 8) | *bin_data;
- leftbits += 8;
- while ( leftbits >= 6 ) {
- this_ch = (leftchar >> (leftbits-6)) & 0x3f;
- leftbits -= 6;
- *ascii_data++ = table_b2a_hqx[this_ch];
- }
- }
- /* Output a possible runt byte */
- if ( leftbits ) {
- leftchar <<= (6-leftbits);
- *ascii_data++ = table_b2a_hqx[leftchar & 0x3f];
- }
- if (_PyString_Resize(&rv,
- (ascii_data -
- (unsigned char *)PyString_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pbin);
- return rv;
+ Py_buffer pbin;
+ unsigned char *ascii_data, *bin_data;
+ int leftbits = 0;
+ unsigned char this_ch;
+ unsigned int leftchar = 0;
+ PyObject *rv;
+ Py_ssize_t len;
+
+ if ( !PyArg_ParseTuple(args, "s*:b2a_hqx", &pbin) )
+ return NULL;
+ bin_data = pbin.buf;
+ len = pbin.len;
+
+ assert(len >= 0);
+
+ if (len > PY_SSIZE_T_MAX / 2 - 2) {
+ PyBuffer_Release(&pbin);
+ return PyErr_NoMemory();
+ }
+
+ /* Allocate a buffer that is at least large enough */
+ if ( (rv=PyString_FromStringAndSize(NULL, len*2+2)) == NULL ) {
+ PyBuffer_Release(&pbin);
+ return NULL;
+ }
+ ascii_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ for( ; len > 0 ; len--, bin_data++ ) {
+ /* Shift into our buffer, and output any 6bits ready */
+ leftchar = (leftchar << 8) | *bin_data;
+ leftbits += 8;
+ while ( leftbits >= 6 ) {
+ this_ch = (leftchar >> (leftbits-6)) & 0x3f;
+ leftbits -= 6;
+ *ascii_data++ = table_b2a_hqx[this_ch];
+ }
+ }
+ /* Output a possible runt byte */
+ if ( leftbits ) {
+ leftchar <<= (6-leftbits);
+ *ascii_data++ = table_b2a_hqx[leftchar & 0x3f];
+ }
+ if (_PyString_Resize(&rv,
+ (ascii_data -
+ (unsigned char *)PyString_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pbin);
+ return rv;
}
PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
@@ -744,116 +744,116 @@ PyDoc_STRVAR(doc_rledecode_hqx, "Decode hexbin RLE-coded string");
static PyObject *
binascii_rledecode_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pin;
- unsigned char *in_data, *out_data;
- unsigned char in_byte, in_repeat;
- PyObject *rv;
- Py_ssize_t in_len, out_len, out_len_left;
-
- if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) )
- return NULL;
- in_data = pin.buf;
- in_len = pin.len;
-
- assert(in_len >= 0);
-
- /* Empty string is a special case */
- if ( in_len == 0 ) {
- PyBuffer_Release(&pin);
- return PyString_FromStringAndSize("", 0);
- }
- else if (in_len > PY_SSIZE_T_MAX / 2) {
- PyBuffer_Release(&pin);
- return PyErr_NoMemory();
- }
-
- /* Allocate a buffer of reasonable size. Resized when needed */
- out_len = in_len*2;
- if ( (rv=PyString_FromStringAndSize(NULL, out_len)) == NULL ) {
- PyBuffer_Release(&pin);
- return NULL;
- }
- out_len_left = out_len;
- out_data = (unsigned char *)PyString_AS_STRING(rv);
-
- /*
- ** We need two macros here to get/put bytes and handle
- ** end-of-buffer for input and output strings.
- */
+ Py_buffer pin;
+ unsigned char *in_data, *out_data;
+ unsigned char in_byte, in_repeat;
+ PyObject *rv;
+ Py_ssize_t in_len, out_len, out_len_left;
+
+ if ( !PyArg_ParseTuple(args, "s*:rledecode_hqx", &pin) )
+ return NULL;
+ in_data = pin.buf;
+ in_len = pin.len;
+
+ assert(in_len >= 0);
+
+ /* Empty string is a special case */
+ if ( in_len == 0 ) {
+ PyBuffer_Release(&pin);
+ return PyString_FromStringAndSize("", 0);
+ }
+ else if (in_len > PY_SSIZE_T_MAX / 2) {
+ PyBuffer_Release(&pin);
+ return PyErr_NoMemory();
+ }
+
+ /* Allocate a buffer of reasonable size. Resized when needed */
+ out_len = in_len*2;
+ if ( (rv=PyString_FromStringAndSize(NULL, out_len)) == NULL ) {
+ PyBuffer_Release(&pin);
+ return NULL;
+ }
+ out_len_left = out_len;
+ out_data = (unsigned char *)PyString_AS_STRING(rv);
+
+ /*
+ ** We need two macros here to get/put bytes and handle
+ ** end-of-buffer for input and output strings.
+ */
#define INBYTE(b) \
- do { \
- if ( --in_len < 0 ) { \
- PyErr_SetString(Incomplete, ""); \
- Py_DECREF(rv); \
- PyBuffer_Release(&pin); \
- return NULL; \
- } \
- b = *in_data++; \
- } while(0)
+ do { \
+ if ( --in_len < 0 ) { \
+ PyErr_SetString(Incomplete, ""); \
+ Py_DECREF(rv); \
+ PyBuffer_Release(&pin); \
+ return NULL; \
+ } \
+ b = *in_data++; \
+ } while(0)
#define OUTBYTE(b) \
- do { \
- if ( --out_len_left < 0 ) { \
- if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \
- if (_PyString_Resize(&rv, 2*out_len) < 0) \
- { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \
- out_data = (unsigned char *)PyString_AS_STRING(rv) \
- + out_len; \
- out_len_left = out_len-1; \
- out_len = out_len * 2; \
- } \
- *out_data++ = b; \
- } while(0)
-
- /*
- ** Handle first byte separately (since we have to get angry
- ** in case of an orphaned RLE code).
- */
- INBYTE(in_byte);
-
- if (in_byte == RUNCHAR) {
- INBYTE(in_repeat);
- if (in_repeat != 0) {
- /* Note Error, not Incomplete (which is at the end
- ** of the string only). This is a programmer error.
- */
- PyErr_SetString(Error, "Orphaned RLE code at start");
- PyBuffer_Release(&pin);
- Py_DECREF(rv);
- return NULL;
- }
- OUTBYTE(RUNCHAR);
- } else {
- OUTBYTE(in_byte);
- }
-
- while( in_len > 0 ) {
- INBYTE(in_byte);
-
- if (in_byte == RUNCHAR) {
- INBYTE(in_repeat);
- if ( in_repeat == 0 ) {
- /* Just an escaped RUNCHAR value */
- OUTBYTE(RUNCHAR);
- } else {
- /* Pick up value and output a sequence of it */
- in_byte = out_data[-1];
- while ( --in_repeat > 0 )
- OUTBYTE(in_byte);
- }
- } else {
- /* Normal byte */
- OUTBYTE(in_byte);
- }
- }
- if (_PyString_Resize(&rv,
- (out_data -
- (unsigned char *)PyString_AS_STRING(rv))) < 0) {
- Py_DECREF(rv);
- rv = NULL;
- }
- PyBuffer_Release(&pin);
- return rv;
+ do { \
+ if ( --out_len_left < 0 ) { \
+ if ( out_len > PY_SSIZE_T_MAX / 2) return PyErr_NoMemory(); \
+ if (_PyString_Resize(&rv, 2*out_len) < 0) \
+ { Py_DECREF(rv); PyBuffer_Release(&pin); return NULL; } \
+ out_data = (unsigned char *)PyString_AS_STRING(rv) \
+ + out_len; \
+ out_len_left = out_len-1; \
+ out_len = out_len * 2; \
+ } \
+ *out_data++ = b; \
+ } while(0)
+
+ /*
+ ** Handle first byte separately (since we have to get angry
+ ** in case of an orphaned RLE code).
+ */
+ INBYTE(in_byte);
+
+ if (in_byte == RUNCHAR) {
+ INBYTE(in_repeat);
+ if (in_repeat != 0) {
+ /* Note Error, not Incomplete (which is at the end
+ ** of the string only). This is a programmer error.
+ */
+ PyErr_SetString(Error, "Orphaned RLE code at start");
+ PyBuffer_Release(&pin);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ OUTBYTE(RUNCHAR);
+ } else {
+ OUTBYTE(in_byte);
+ }
+
+ while( in_len > 0 ) {
+ INBYTE(in_byte);
+
+ if (in_byte == RUNCHAR) {
+ INBYTE(in_repeat);
+ if ( in_repeat == 0 ) {
+ /* Just an escaped RUNCHAR value */
+ OUTBYTE(RUNCHAR);
+ } else {
+ /* Pick up value and output a sequence of it */
+ in_byte = out_data[-1];
+ while ( --in_repeat > 0 )
+ OUTBYTE(in_byte);
+ }
+ } else {
+ /* Normal byte */
+ OUTBYTE(in_byte);
+ }
+ }
+ if (_PyString_Resize(&rv,
+ (out_data -
+ (unsigned char *)PyString_AS_STRING(rv))) < 0) {
+ Py_DECREF(rv);
+ rv = NULL;
+ }
+ PyBuffer_Release(&pin);
+ return rv;
}
PyDoc_STRVAR(doc_crc_hqx,
@@ -862,22 +862,22 @@ PyDoc_STRVAR(doc_crc_hqx,
static PyObject *
binascii_crc_hqx(PyObject *self, PyObject *args)
{
- Py_buffer pin;
- unsigned char *bin_data;
- unsigned int crc;
- Py_ssize_t len;
-
- if ( !PyArg_ParseTuple(args, "s*i:crc_hqx", &pin, &crc) )
- return NULL;
- bin_data = pin.buf;
- len = pin.len;
-
- while(len-- > 0) {
- crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
- }
-
- PyBuffer_Release(&pin);
- return Py_BuildValue("i", crc);
+ Py_buffer pin;
+ unsigned char *bin_data;
+ unsigned int crc;
+ Py_ssize_t len;
+
+ if ( !PyArg_ParseTuple(args, "s*i:crc_hqx", &pin, &crc) )
+ return NULL;
+ bin_data = pin.buf;
+ len = pin.len;
+
+ while(len-- > 0) {
+ crc=((crc<<8)&0xff00)^crctab_hqx[((crc>>8)&0xff)^*bin_data++];
+ }
+
+ PyBuffer_Release(&pin);
+ return Py_BuildValue("i", crc);
}
PyDoc_STRVAR(doc_crc32,
@@ -895,7 +895,7 @@ binascii_crc32(PyObject *self, PyObject *args)
int signed_val;
if (!PyArg_ParseTuple(args, "s*|I:crc32", &pbuf, &crc32val))
- return NULL;
+ return NULL;
/* In Python 2.x we return a signed integer regardless of native platform
* long size (the 32bit unsigned long is treated as 32-bit signed and sign
* extended into a 64-bit long inside the integer object). 3.0 does the
@@ -1028,25 +1028,25 @@ static unsigned int crc_32_tab[256] = {
static PyObject *
binascii_crc32(PyObject *self, PyObject *args)
{ /* By Jim Ahlstrom; All rights transferred to CNRI */
- Py_buffer pbin;
- unsigned char *bin_data;
- unsigned int crc = 0U; /* initial value of CRC */
- Py_ssize_t len;
- int result;
-
- if ( !PyArg_ParseTuple(args, "s*|I:crc32", &pbin, &crc) )
- return NULL;
- bin_data = pbin.buf;
- len = pbin.len;
-
- crc = ~ crc;
- while (len-- > 0)
- crc = crc_32_tab[(crc ^ *bin_data++) & 0xffU] ^ (crc >> 8);
- /* Note: (crc >> 8) MUST zero fill on left */
-
- result = (int)(crc ^ 0xFFFFFFFFU);
- PyBuffer_Release(&pbin);
- return PyInt_FromLong(result);
+ Py_buffer pbin;
+ unsigned char *bin_data;
+ unsigned int crc = 0U; /* initial value of CRC */
+ Py_ssize_t len;
+ int result;
+
+ if ( !PyArg_ParseTuple(args, "s*|I:crc32", &pbin, &crc) )
+ return NULL;
+ bin_data = pbin.buf;
+ len = pbin.len;
+
+ crc = ~ crc;
+ while (len-- > 0)
+ crc = crc_32_tab[(crc ^ *bin_data++) & 0xffU] ^ (crc >> 8);
+ /* Note: (crc >> 8) MUST zero fill on left */
+
+ result = (int)(crc ^ 0xFFFFFFFFU);
+ PyBuffer_Release(&pbin);
+ return PyInt_FromLong(result);
}
#endif /* USE_ZLIB_CRC32 */
@@ -1054,43 +1054,43 @@ binascii_crc32(PyObject *self, PyObject *args)
static PyObject *
binascii_hexlify(PyObject *self, PyObject *args)
{
- Py_buffer parg;
- char* argbuf;
- Py_ssize_t arglen;
- PyObject *retval;
- char* retbuf;
- Py_ssize_t i, j;
-
- if (!PyArg_ParseTuple(args, "s*:b2a_hex", &parg))
- return NULL;
- argbuf = parg.buf;
- arglen = parg.len;
-
- assert(arglen >= 0);
- if (arglen > PY_SSIZE_T_MAX / 2) {
- PyBuffer_Release(&parg);
- return PyErr_NoMemory();
- }
-
- retval = PyString_FromStringAndSize(NULL, arglen*2);
- if (!retval) {
- PyBuffer_Release(&parg);
- return NULL;
- }
- retbuf = PyString_AS_STRING(retval);
-
- /* make hex version of string, taken from shamodule.c */
- for (i=j=0; i < arglen; i++) {
- char c;
- c = (argbuf[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
- retbuf[j++] = c;
- c = argbuf[i] & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
- retbuf[j++] = c;
- }
- PyBuffer_Release(&parg);
- return retval;
+ Py_buffer parg;
+ char* argbuf;
+ Py_ssize_t arglen;
+ PyObject *retval;
+ char* retbuf;
+ Py_ssize_t i, j;
+
+ if (!PyArg_ParseTuple(args, "s*:b2a_hex", &parg))
+ return NULL;
+ argbuf = parg.buf;
+ arglen = parg.len;
+
+ assert(arglen >= 0);
+ if (arglen > PY_SSIZE_T_MAX / 2) {
+ PyBuffer_Release(&parg);
+ return PyErr_NoMemory();
+ }
+
+ retval = PyString_FromStringAndSize(NULL, arglen*2);
+ if (!retval) {
+ PyBuffer_Release(&parg);
+ return NULL;
+ }
+ retbuf = PyString_AS_STRING(retval);
+
+ /* make hex version of string, taken from shamodule.c */
+ for (i=j=0; i < arglen; i++) {
+ char c;
+ c = (argbuf[i] >> 4) & 0xf;
+ c = (c>9) ? c+'a'-10 : c + '0';
+ retbuf[j++] = c;
+ c = argbuf[i] & 0xf;
+ c = (c>9) ? c+'a'-10 : c + '0';
+ retbuf[j++] = c;
+ }
+ PyBuffer_Release(&parg);
+ return retval;
}
PyDoc_STRVAR(doc_hexlify,
@@ -1102,69 +1102,69 @@ This function is also available as \"hexlify()\".");
static int
to_int(int c)
{
- if (isdigit(c))
- return c - '0';
- else {
- if (isupper(c))
- c = tolower(c);
- if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- }
- return -1;
+ if (isdigit(c))
+ return c - '0';
+ else {
+ if (isupper(c))
+ c = tolower(c);
+ if (c >= 'a' && c <= 'f')
+ return c - 'a' + 10;
+ }
+ return -1;
}
static PyObject *
binascii_unhexlify(PyObject *self, PyObject *args)
{
- Py_buffer parg;
- char* argbuf;
- Py_ssize_t arglen;
- PyObject *retval;
- char* retbuf;
- Py_ssize_t i, j;
-
- if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg))
- return NULL;
- argbuf = parg.buf;
- arglen = parg.len;
-
- assert(arglen >= 0);
-
- /* XXX What should we do about strings with an odd length? Should
- * we add an implicit leading zero, or a trailing zero? For now,
- * raise an exception.
- */
- if (arglen % 2) {
- PyBuffer_Release(&parg);
- PyErr_SetString(PyExc_TypeError, "Odd-length string");
- return NULL;
- }
-
- retval = PyString_FromStringAndSize(NULL, (arglen/2));
- if (!retval) {
- PyBuffer_Release(&parg);
- return NULL;
- }
- retbuf = PyString_AS_STRING(retval);
-
- for (i=j=0; i < arglen; i += 2) {
- int top = to_int(Py_CHARMASK(argbuf[i]));
- int bot = to_int(Py_CHARMASK(argbuf[i+1]));
- if (top == -1 || bot == -1) {
- PyErr_SetString(PyExc_TypeError,
- "Non-hexadecimal digit found");
- goto finally;
- }
- retbuf[j++] = (top << 4) + bot;
- }
- PyBuffer_Release(&parg);
- return retval;
+ Py_buffer parg;
+ char* argbuf;
+ Py_ssize_t arglen;
+ PyObject *retval;
+ char* retbuf;
+ Py_ssize_t i, j;
+
+ if (!PyArg_ParseTuple(args, "s*:a2b_hex", &parg))
+ return NULL;
+ argbuf = parg.buf;
+ arglen = parg.len;
+
+ assert(arglen >= 0);
+
+ /* XXX What should we do about strings with an odd length? Should
+ * we add an implicit leading zero, or a trailing zero? For now,
+ * raise an exception.
+ */
+ if (arglen % 2) {
+ PyBuffer_Release(&parg);
+ PyErr_SetString(PyExc_TypeError, "Odd-length string");
+ return NULL;
+ }
+
+ retval = PyString_FromStringAndSize(NULL, (arglen/2));
+ if (!retval) {
+ PyBuffer_Release(&parg);
+ return NULL;
+ }
+ retbuf = PyString_AS_STRING(retval);
+
+ for (i=j=0; i < arglen; i += 2) {
+ int top = to_int(Py_CHARMASK(argbuf[i]));
+ int bot = to_int(Py_CHARMASK(argbuf[i+1]));
+ if (top == -1 || bot == -1) {
+ PyErr_SetString(PyExc_TypeError,
+ "Non-hexadecimal digit found");
+ goto finally;
+ }
+ retbuf[j++] = (top << 4) + bot;
+ }
+ PyBuffer_Release(&parg);
+ return retval;
finally:
- PyBuffer_Release(&parg);
- Py_DECREF(retval);
- return NULL;
+ PyBuffer_Release(&parg);
+ Py_DECREF(retval);
+ return NULL;
}
PyDoc_STRVAR(doc_unhexlify,
@@ -1193,96 +1193,96 @@ PyDoc_STRVAR(doc_a2b_qp, "Decode a string of qp-encoded data");
static PyObject*
binascii_a2b_qp(PyObject *self, PyObject *args, PyObject *kwargs)
{
- Py_ssize_t in, out;
- char ch;
- Py_buffer pdata;
- unsigned char *data, *odata;
- Py_ssize_t datalen = 0;
- PyObject *rv;
- static char *kwlist[] = {"data", "header", NULL};
- int header = 0;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata,
- &header))
- return NULL;
- data = pdata.buf;
- datalen = pdata.len;
-
- /* We allocate the output same size as input, this is overkill.
- * The previous implementation used calloc() so we'll zero out the
- * memory here too, since PyMem_Malloc() does not guarantee that.
- */
- odata = (unsigned char *) PyMem_Malloc(datalen);
- if (odata == NULL) {
- PyBuffer_Release(&pdata);
- PyErr_NoMemory();
- return NULL;
- }
- memset(odata, 0, datalen);
-
- in = out = 0;
- while (in < datalen) {
- if (data[in] == '=') {
- in++;
- if (in >= datalen) break;
- /* Soft line breaks */
- if ((data[in] == '\n') || (data[in] == '\r')) {
- if (data[in] != '\n') {
- while (in < datalen && data[in] != '\n') in++;
- }
- if (in < datalen) in++;
- }
- else if (data[in] == '=') {
- /* broken case from broken python qp */
- odata[out++] = '=';
- in++;
- }
- else if (((data[in] >= 'A' && data[in] <= 'F') ||
- (data[in] >= 'a' && data[in] <= 'f') ||
- (data[in] >= '0' && data[in] <= '9')) &&
- ((data[in+1] >= 'A' && data[in+1] <= 'F') ||
- (data[in+1] >= 'a' && data[in+1] <= 'f') ||
- (data[in+1] >= '0' && data[in+1] <= '9'))) {
- /* hexval */
- ch = hexval(data[in]) << 4;
- in++;
- ch |= hexval(data[in]);
- in++;
- odata[out++] = ch;
- }
- else {
- odata[out++] = '=';
- }
- }
- else if (header && data[in] == '_') {
- odata[out++] = ' ';
- in++;
- }
- else {
- odata[out] = data[in];
- in++;
- out++;
- }
- }
- if ((rv = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return NULL;
- }
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return rv;
+ Py_ssize_t in, out;
+ char ch;
+ Py_buffer pdata;
+ unsigned char *data, *odata;
+ Py_ssize_t datalen = 0;
+ PyObject *rv;
+ static char *kwlist[] = {"data", "header", NULL};
+ int header = 0;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i", kwlist, &pdata,
+ &header))
+ return NULL;
+ data = pdata.buf;
+ datalen = pdata.len;
+
+ /* We allocate the output same size as input, this is overkill.
+ * The previous implementation used calloc() so we'll zero out the
+ * memory here too, since PyMem_Malloc() does not guarantee that.
+ */
+ odata = (unsigned char *) PyMem_Malloc(datalen);
+ if (odata == NULL) {
+ PyBuffer_Release(&pdata);
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(odata, 0, datalen);
+
+ in = out = 0;
+ while (in < datalen) {
+ if (data[in] == '=') {
+ in++;
+ if (in >= datalen) break;
+ /* Soft line breaks */
+ if ((data[in] == '\n') || (data[in] == '\r')) {
+ if (data[in] != '\n') {
+ while (in < datalen && data[in] != '\n') in++;
+ }
+ if (in < datalen) in++;
+ }
+ else if (data[in] == '=') {
+ /* broken case from broken python qp */
+ odata[out++] = '=';
+ in++;
+ }
+ else if (((data[in] >= 'A' && data[in] <= 'F') ||
+ (data[in] >= 'a' && data[in] <= 'f') ||
+ (data[in] >= '0' && data[in] <= '9')) &&
+ ((data[in+1] >= 'A' && data[in+1] <= 'F') ||
+ (data[in+1] >= 'a' && data[in+1] <= 'f') ||
+ (data[in+1] >= '0' && data[in+1] <= '9'))) {
+ /* hexval */
+ ch = hexval(data[in]) << 4;
+ in++;
+ ch |= hexval(data[in]);
+ in++;
+ odata[out++] = ch;
+ }
+ else {
+ odata[out++] = '=';
+ }
+ }
+ else if (header && data[in] == '_') {
+ odata[out++] = ' ';
+ in++;
+ }
+ else {
+ odata[out] = data[in];
+ in++;
+ out++;
+ }
+ }
+ if ((rv = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return NULL;
+ }
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return rv;
}
static int
to_hex (unsigned char ch, unsigned char *s)
{
- unsigned int uvalue = ch;
+ unsigned int uvalue = ch;
- s[1] = "0123456789ABCDEF"[uvalue % 16];
- uvalue = (uvalue / 16);
- s[0] = "0123456789ABCDEF"[uvalue % 16];
- return 0;
+ s[1] = "0123456789ABCDEF"[uvalue % 16];
+ uvalue = (uvalue / 16);
+ s[0] = "0123456789ABCDEF"[uvalue % 16];
+ return 0;
}
PyDoc_STRVAR(doc_b2a_qp,
@@ -1299,210 +1299,210 @@ both encoded. When quotetabs is set, space and tabs are encoded.");
static PyObject*
binascii_b2a_qp (PyObject *self, PyObject *args, PyObject *kwargs)
{
- Py_ssize_t in, out;
- Py_buffer pdata;
- unsigned char *data, *odata;
- Py_ssize_t datalen = 0, odatalen = 0;
- PyObject *rv;
- unsigned int linelen = 0;
- static char *kwlist[] = {"data", "quotetabs", "istext",
- "header", NULL};
- int istext = 1;
- int quotetabs = 0;
- int header = 0;
- unsigned char ch;
- int crlf = 0;
- unsigned char *p;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|iii", kwlist, &pdata,
- &quotetabs, &istext, &header))
- return NULL;
- data = pdata.buf;
- datalen = pdata.len;
-
- /* See if this string is using CRLF line ends */
- /* XXX: this function has the side effect of converting all of
- * the end of lines to be the same depending on this detection
- * here */
- p = (unsigned char *) memchr(data, '\n', datalen);
- if ((p != NULL) && (p > data) && (*(p-1) == '\r'))
- crlf = 1;
-
- /* First, scan to see how many characters need to be encoded */
- in = 0;
- while (in < datalen) {
- if ((data[in] > 126) ||
- (data[in] == '=') ||
- (header && data[in] == '_') ||
- ((data[in] == '.') && (linelen == 0) &&
- (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
- (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
- ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
- ((data[in] < 33) &&
- (data[in] != '\r') && (data[in] != '\n') &&
- (quotetabs ||
- (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
- {
- if ((linelen + 3) >= MAXLINESIZE) {
- linelen = 0;
- if (crlf)
- odatalen += 3;
- else
- odatalen += 2;
- }
- linelen += 3;
- odatalen += 3;
- in++;
- }
- else {
- if (istext &&
- ((data[in] == '\n') ||
- ((in+1 < datalen) && (data[in] == '\r') &&
- (data[in+1] == '\n'))))
- {
- linelen = 0;
- /* Protect against whitespace on end of line */
- if (in && ((data[in-1] == ' ') || (data[in-1] == '\t')))
- odatalen += 2;
- if (crlf)
- odatalen += 2;
- else
- odatalen += 1;
- if (data[in] == '\r')
- in += 2;
- else
- in++;
- }
- else {
- if ((in + 1 != datalen) &&
- (data[in+1] != '\n') &&
- (linelen + 1) >= MAXLINESIZE) {
- linelen = 0;
- if (crlf)
- odatalen += 3;
- else
- odatalen += 2;
- }
- linelen++;
- odatalen++;
- in++;
- }
- }
- }
-
- /* We allocate the output same size as input, this is overkill.
- * The previous implementation used calloc() so we'll zero out the
- * memory here too, since PyMem_Malloc() does not guarantee that.
- */
- odata = (unsigned char *) PyMem_Malloc(odatalen);
- if (odata == NULL) {
- PyBuffer_Release(&pdata);
- PyErr_NoMemory();
- return NULL;
- }
- memset(odata, 0, odatalen);
-
- in = out = linelen = 0;
- while (in < datalen) {
- if ((data[in] > 126) ||
- (data[in] == '=') ||
- (header && data[in] == '_') ||
- ((data[in] == '.') && (linelen == 0) &&
- (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
- (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
- ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
- ((data[in] < 33) &&
- (data[in] != '\r') && (data[in] != '\n') &&
- (quotetabs ||
- (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
- {
- if ((linelen + 3 )>= MAXLINESIZE) {
- odata[out++] = '=';
- if (crlf) odata[out++] = '\r';
- odata[out++] = '\n';
- linelen = 0;
- }
- odata[out++] = '=';
- to_hex(data[in], &odata[out]);
- out += 2;
- in++;
- linelen += 3;
- }
- else {
- if (istext &&
- ((data[in] == '\n') ||
- ((in+1 < datalen) && (data[in] == '\r') &&
- (data[in+1] == '\n'))))
- {
- linelen = 0;
- /* Protect against whitespace on end of line */
- if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) {
- ch = odata[out-1];
- odata[out-1] = '=';
- to_hex(ch, &odata[out]);
- out += 2;
- }
-
- if (crlf) odata[out++] = '\r';
- odata[out++] = '\n';
- if (data[in] == '\r')
- in += 2;
- else
- in++;
- }
- else {
- if ((in + 1 != datalen) &&
- (data[in+1] != '\n') &&
- (linelen + 1) >= MAXLINESIZE) {
- odata[out++] = '=';
- if (crlf) odata[out++] = '\r';
- odata[out++] = '\n';
- linelen = 0;
- }
- linelen++;
- if (header && data[in] == ' ') {
- odata[out++] = '_';
- in++;
- }
- else {
- odata[out++] = data[in++];
- }
- }
- }
- }
- if ((rv = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return NULL;
- }
- PyBuffer_Release(&pdata);
- PyMem_Free(odata);
- return rv;
+ Py_ssize_t in, out;
+ Py_buffer pdata;
+ unsigned char *data, *odata;
+ Py_ssize_t datalen = 0, odatalen = 0;
+ PyObject *rv;
+ unsigned int linelen = 0;
+ static char *kwlist[] = {"data", "quotetabs", "istext",
+ "header", NULL};
+ int istext = 1;
+ int quotetabs = 0;
+ int header = 0;
+ unsigned char ch;
+ int crlf = 0;
+ unsigned char *p;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|iii", kwlist, &pdata,
+ &quotetabs, &istext, &header))
+ return NULL;
+ data = pdata.buf;
+ datalen = pdata.len;
+
+ /* See if this string is using CRLF line ends */
+ /* XXX: this function has the side effect of converting all of
+ * the end of lines to be the same depending on this detection
+ * here */
+ p = (unsigned char *) memchr(data, '\n', datalen);
+ if ((p != NULL) && (p > data) && (*(p-1) == '\r'))
+ crlf = 1;
+
+ /* First, scan to see how many characters need to be encoded */
+ in = 0;
+ while (in < datalen) {
+ if ((data[in] > 126) ||
+ (data[in] == '=') ||
+ (header && data[in] == '_') ||
+ ((data[in] == '.') && (linelen == 0) &&
+ (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
+ (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
+ ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
+ ((data[in] < 33) &&
+ (data[in] != '\r') && (data[in] != '\n') &&
+ (quotetabs ||
+ (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
+ {
+ if ((linelen + 3) >= MAXLINESIZE) {
+ linelen = 0;
+ if (crlf)
+ odatalen += 3;
+ else
+ odatalen += 2;
+ }
+ linelen += 3;
+ odatalen += 3;
+ in++;
+ }
+ else {
+ if (istext &&
+ ((data[in] == '\n') ||
+ ((in+1 < datalen) && (data[in] == '\r') &&
+ (data[in+1] == '\n'))))
+ {
+ linelen = 0;
+ /* Protect against whitespace on end of line */
+ if (in && ((data[in-1] == ' ') || (data[in-1] == '\t')))
+ odatalen += 2;
+ if (crlf)
+ odatalen += 2;
+ else
+ odatalen += 1;
+ if (data[in] == '\r')
+ in += 2;
+ else
+ in++;
+ }
+ else {
+ if ((in + 1 != datalen) &&
+ (data[in+1] != '\n') &&
+ (linelen + 1) >= MAXLINESIZE) {
+ linelen = 0;
+ if (crlf)
+ odatalen += 3;
+ else
+ odatalen += 2;
+ }
+ linelen++;
+ odatalen++;
+ in++;
+ }
+ }
+ }
+
+ /* We allocate the output same size as input, this is overkill.
+ * The previous implementation used calloc() so we'll zero out the
+ * memory here too, since PyMem_Malloc() does not guarantee that.
+ */
+ odata = (unsigned char *) PyMem_Malloc(odatalen);
+ if (odata == NULL) {
+ PyBuffer_Release(&pdata);
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(odata, 0, odatalen);
+
+ in = out = linelen = 0;
+ while (in < datalen) {
+ if ((data[in] > 126) ||
+ (data[in] == '=') ||
+ (header && data[in] == '_') ||
+ ((data[in] == '.') && (linelen == 0) &&
+ (data[in+1] == '\n' || data[in+1] == '\r' || data[in+1] == 0)) ||
+ (!istext && ((data[in] == '\r') || (data[in] == '\n'))) ||
+ ((data[in] == '\t' || data[in] == ' ') && (in + 1 == datalen)) ||
+ ((data[in] < 33) &&
+ (data[in] != '\r') && (data[in] != '\n') &&
+ (quotetabs ||
+ (!quotetabs && ((data[in] != '\t') && (data[in] != ' '))))))
+ {
+ if ((linelen + 3 )>= MAXLINESIZE) {
+ odata[out++] = '=';
+ if (crlf) odata[out++] = '\r';
+ odata[out++] = '\n';
+ linelen = 0;
+ }
+ odata[out++] = '=';
+ to_hex(data[in], &odata[out]);
+ out += 2;
+ in++;
+ linelen += 3;
+ }
+ else {
+ if (istext &&
+ ((data[in] == '\n') ||
+ ((in+1 < datalen) && (data[in] == '\r') &&
+ (data[in+1] == '\n'))))
+ {
+ linelen = 0;
+ /* Protect against whitespace on end of line */
+ if (out && ((odata[out-1] == ' ') || (odata[out-1] == '\t'))) {
+ ch = odata[out-1];
+ odata[out-1] = '=';
+ to_hex(ch, &odata[out]);
+ out += 2;
+ }
+
+ if (crlf) odata[out++] = '\r';
+ odata[out++] = '\n';
+ if (data[in] == '\r')
+ in += 2;
+ else
+ in++;
+ }
+ else {
+ if ((in + 1 != datalen) &&
+ (data[in+1] != '\n') &&
+ (linelen + 1) >= MAXLINESIZE) {
+ odata[out++] = '=';
+ if (crlf) odata[out++] = '\r';
+ odata[out++] = '\n';
+ linelen = 0;
+ }
+ linelen++;
+ if (header && data[in] == ' ') {
+ odata[out++] = '_';
+ in++;
+ }
+ else {
+ odata[out++] = data[in++];
+ }
+ }
+ }
+ }
+ if ((rv = PyString_FromStringAndSize((char *)odata, out)) == NULL) {
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return NULL;
+ }
+ PyBuffer_Release(&pdata);
+ PyMem_Free(odata);
+ return rv;
}
/* List of functions defined in the module */
static struct PyMethodDef binascii_module_methods[] = {
- {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu},
- {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu},
- {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64},
- {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64},
- {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx},
- {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx},
- {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify},
- {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
- {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify},
- {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
- {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx},
- {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS,
- doc_rledecode_hqx},
- {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx},
- {"crc32", binascii_crc32, METH_VARARGS, doc_crc32},
- {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS,
- doc_a2b_qp},
- {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS,
- doc_b2a_qp},
- {NULL, NULL} /* sentinel */
+ {"a2b_uu", binascii_a2b_uu, METH_VARARGS, doc_a2b_uu},
+ {"b2a_uu", binascii_b2a_uu, METH_VARARGS, doc_b2a_uu},
+ {"a2b_base64", binascii_a2b_base64, METH_VARARGS, doc_a2b_base64},
+ {"b2a_base64", binascii_b2a_base64, METH_VARARGS, doc_b2a_base64},
+ {"a2b_hqx", binascii_a2b_hqx, METH_VARARGS, doc_a2b_hqx},
+ {"b2a_hqx", binascii_b2a_hqx, METH_VARARGS, doc_b2a_hqx},
+ {"b2a_hex", binascii_hexlify, METH_VARARGS, doc_hexlify},
+ {"a2b_hex", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
+ {"hexlify", binascii_hexlify, METH_VARARGS, doc_hexlify},
+ {"unhexlify", binascii_unhexlify, METH_VARARGS, doc_unhexlify},
+ {"rlecode_hqx", binascii_rlecode_hqx, METH_VARARGS, doc_rlecode_hqx},
+ {"rledecode_hqx", binascii_rledecode_hqx, METH_VARARGS,
+ doc_rledecode_hqx},
+ {"crc_hqx", binascii_crc_hqx, METH_VARARGS, doc_crc_hqx},
+ {"crc32", binascii_crc32, METH_VARARGS, doc_crc32},
+ {"a2b_qp", (PyCFunction)binascii_a2b_qp, METH_VARARGS | METH_KEYWORDS,
+ doc_a2b_qp},
+ {"b2a_qp", (PyCFunction)binascii_b2a_qp, METH_VARARGS | METH_KEYWORDS,
+ doc_b2a_qp},
+ {NULL, NULL} /* sentinel */
};
@@ -1512,20 +1512,20 @@ PyDoc_STRVAR(doc_binascii, "Conversion between binary data and ASCII");
PyMODINIT_FUNC
initbinascii(void)
{
- PyObject *m, *d, *x;
-
- /* Create the module and add the functions */
- m = Py_InitModule("binascii", binascii_module_methods);
- if (m == NULL)
- return;
-
- d = PyModule_GetDict(m);
- x = PyString_FromString(doc_binascii);
- PyDict_SetItemString(d, "__doc__", x);
- Py_XDECREF(x);
-
- Error = PyErr_NewException("binascii.Error", NULL, NULL);
- PyDict_SetItemString(d, "Error", Error);
- Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
- PyDict_SetItemString(d, "Incomplete", Incomplete);
+ PyObject *m, *d, *x;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule("binascii", binascii_module_methods);
+ if (m == NULL)
+ return;
+
+ d = PyModule_GetDict(m);
+ x = PyString_FromString(doc_binascii);
+ PyDict_SetItemString(d, "__doc__", x);
+ Py_XDECREF(x);
+
+ Error = PyErr_NewException("binascii.Error", NULL, NULL);
+ PyDict_SetItemString(d, "Error", Error);
+ Incomplete = PyErr_NewException("binascii.Incomplete", NULL, NULL);
+ PyDict_SetItemString(d, "Incomplete", Incomplete);
}
diff --git a/Modules/bsddbmodule.c b/Modules/bsddbmodule.c
index c55df11..578cf3d 100644
--- a/Modules/bsddbmodule.c
+++ b/Modules/bsddbmodule.c
@@ -30,12 +30,12 @@
(it messes up the info required in the Setup file) */
typedef struct {
- PyObject_HEAD
- DB *di_bsddb;
- int di_size; /* -1 means recompute */
- int di_type;
+ PyObject_HEAD
+ DB *di_bsddb;
+ int di_size; /* -1 means recompute */
+ int di_type;
#ifdef WITH_THREAD
- PyThread_type_lock di_lock;
+ PyThread_type_lock di_lock;
#endif
} bsddbobject;
@@ -44,821 +44,821 @@ static PyTypeObject Bsddbtype;
#define is_bsddbobject(v) ((v)->ob_type == &Bsddbtype)
#define check_bsddbobject_open(v, r) if ((v)->di_bsddb == NULL) \
{ PyErr_SetString(BsddbError, \
- "BSDDB object has already been closed"); \
+ "BSDDB object has already been closed"); \
return r; }
static PyObject *BsddbError;
static PyObject *
newdbhashobject(char *file, int flags, int mode,
- int bsize, int ffactor, int nelem, int cachesize,
- int hash, int lorder)
+ int bsize, int ffactor, int nelem, int cachesize,
+ int hash, int lorder)
{
- bsddbobject *dp;
- HASHINFO info;
+ bsddbobject *dp;
+ HASHINFO info;
- if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
- return NULL;
+ if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
+ return NULL;
- info.bsize = bsize;
- info.ffactor = ffactor;
- info.nelem = nelem;
- info.cachesize = cachesize;
- info.hash = NULL; /* XXX should derive from hash argument */
- info.lorder = lorder;
+ info.bsize = bsize;
+ info.ffactor = ffactor;
+ info.nelem = nelem;
+ info.cachesize = cachesize;
+ info.hash = NULL; /* XXX should derive from hash argument */
+ info.lorder = lorder;
#ifdef O_BINARY
- flags |= O_BINARY;
+ flags |= O_BINARY;
#endif
- Py_BEGIN_ALLOW_THREADS
- dp->di_bsddb = dbopen(file, flags, mode, DB_HASH, &info);
- Py_END_ALLOW_THREADS
- if (dp->di_bsddb == NULL) {
- PyErr_SetFromErrno(BsddbError);
+ Py_BEGIN_ALLOW_THREADS
+ dp->di_bsddb = dbopen(file, flags, mode, DB_HASH, &info);
+ Py_END_ALLOW_THREADS
+ if (dp->di_bsddb == NULL) {
+ PyErr_SetFromErrno(BsddbError);
#ifdef WITH_THREAD
- dp->di_lock = NULL;
+ dp->di_lock = NULL;
#endif
- Py_DECREF(dp);
- return NULL;
- }
+ Py_DECREF(dp);
+ return NULL;
+ }
- dp->di_size = -1;
- dp->di_type = DB_HASH;
+ dp->di_size = -1;
+ dp->di_type = DB_HASH;
#ifdef WITH_THREAD
- dp->di_lock = PyThread_allocate_lock();
- if (dp->di_lock == NULL) {
- PyErr_SetString(BsddbError, "can't allocate lock");
- Py_DECREF(dp);
- return NULL;
- }
+ dp->di_lock = PyThread_allocate_lock();
+ if (dp->di_lock == NULL) {
+ PyErr_SetString(BsddbError, "can't allocate lock");
+ Py_DECREF(dp);
+ return NULL;
+ }
#endif
- return (PyObject *)dp;
+ return (PyObject *)dp;
}
static PyObject *
newdbbtobject(char *file, int flags, int mode,
- int btflags, int cachesize, int maxkeypage,
- int minkeypage, int psize, int lorder)
+ int btflags, int cachesize, int maxkeypage,
+ int minkeypage, int psize, int lorder)
{
- bsddbobject *dp;
- BTREEINFO info;
+ bsddbobject *dp;
+ BTREEINFO info;
- if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
- return NULL;
+ if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
+ return NULL;
- info.flags = btflags;
- info.cachesize = cachesize;
- info.maxkeypage = maxkeypage;
- info.minkeypage = minkeypage;
- info.psize = psize;
- info.lorder = lorder;
- info.compare = 0; /* Use default comparison functions, for now..*/
- info.prefix = 0;
+ info.flags = btflags;
+ info.cachesize = cachesize;
+ info.maxkeypage = maxkeypage;
+ info.minkeypage = minkeypage;
+ info.psize = psize;
+ info.lorder = lorder;
+ info.compare = 0; /* Use default comparison functions, for now..*/
+ info.prefix = 0;
#ifdef O_BINARY
- flags |= O_BINARY;
+ flags |= O_BINARY;
#endif
- Py_BEGIN_ALLOW_THREADS
- dp->di_bsddb = dbopen(file, flags, mode, DB_BTREE, &info);
- Py_END_ALLOW_THREADS
- if (dp->di_bsddb == NULL) {
- PyErr_SetFromErrno(BsddbError);
+ Py_BEGIN_ALLOW_THREADS
+ dp->di_bsddb = dbopen(file, flags, mode, DB_BTREE, &info);
+ Py_END_ALLOW_THREADS
+ if (dp->di_bsddb == NULL) {
+ PyErr_SetFromErrno(BsddbError);
#ifdef WITH_THREAD
- dp->di_lock = NULL;
+ dp->di_lock = NULL;
#endif
- Py_DECREF(dp);
- return NULL;
- }
+ Py_DECREF(dp);
+ return NULL;
+ }
- dp->di_size = -1;
- dp->di_type = DB_BTREE;
+ dp->di_size = -1;
+ dp->di_type = DB_BTREE;
#ifdef WITH_THREAD
- dp->di_lock = PyThread_allocate_lock();
- if (dp->di_lock == NULL) {
- PyErr_SetString(BsddbError, "can't allocate lock");
- Py_DECREF(dp);
- return NULL;
- }
+ dp->di_lock = PyThread_allocate_lock();
+ if (dp->di_lock == NULL) {
+ PyErr_SetString(BsddbError, "can't allocate lock");
+ Py_DECREF(dp);
+ return NULL;
+ }
#endif
- return (PyObject *)dp;
+ return (PyObject *)dp;
}
static PyObject *
newdbrnobject(char *file, int flags, int mode,
- int rnflags, int cachesize, int psize, int lorder,
- size_t reclen, u_char bval, char *bfname)
+ int rnflags, int cachesize, int psize, int lorder,
+ size_t reclen, u_char bval, char *bfname)
{
- bsddbobject *dp;
- RECNOINFO info;
- int fd;
+ bsddbobject *dp;
+ RECNOINFO info;
+ int fd;
- if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
- return NULL;
+ if ((dp = PyObject_New(bsddbobject, &Bsddbtype)) == NULL)
+ return NULL;
- info.flags = rnflags;
- info.cachesize = cachesize;
- info.psize = psize;
- info.lorder = lorder;
- info.reclen = reclen;
- info.bval = bval;
- info.bfname = bfname;
+ info.flags = rnflags;
+ info.cachesize = cachesize;
+ info.psize = psize;
+ info.lorder = lorder;
+ info.reclen = reclen;
+ info.bval = bval;
+ info.bfname = bfname;
#ifdef O_BINARY
- flags |= O_BINARY;
+ flags |= O_BINARY;
#endif
- /* This is a hack to avoid a dbopen() bug that happens when
- * it fails. */
- fd = open(file, flags);
- if (fd == -1) {
- dp->di_bsddb = NULL;
- }
- else {
- close(fd);
- Py_BEGIN_ALLOW_THREADS
- dp->di_bsddb = dbopen(file, flags, mode, DB_RECNO, &info);
- Py_END_ALLOW_THREADS
- }
- if (dp->di_bsddb == NULL) {
- PyErr_SetFromErrno(BsddbError);
+ /* This is a hack to avoid a dbopen() bug that happens when
+ * it fails. */
+ fd = open(file, flags);
+ if (fd == -1) {
+ dp->di_bsddb = NULL;
+ }
+ else {
+ close(fd);
+ Py_BEGIN_ALLOW_THREADS
+ dp->di_bsddb = dbopen(file, flags, mode, DB_RECNO, &info);
+ Py_END_ALLOW_THREADS
+ }
+ if (dp->di_bsddb == NULL) {
+ PyErr_SetFromErrno(BsddbError);
#ifdef WITH_THREAD
- dp->di_lock = NULL;
+ dp->di_lock = NULL;
#endif
- Py_DECREF(dp);
- return NULL;
- }
+ Py_DECREF(dp);
+ return NULL;
+ }
- dp->di_size = -1;
- dp->di_type = DB_RECNO;
+ dp->di_size = -1;
+ dp->di_type = DB_RECNO;
#ifdef WITH_THREAD
- dp->di_lock = PyThread_allocate_lock();
- if (dp->di_lock == NULL) {
- PyErr_SetString(BsddbError, "can't allocate lock");
- Py_DECREF(dp);
- return NULL;
- }
+ dp->di_lock = PyThread_allocate_lock();
+ if (dp->di_lock == NULL) {
+ PyErr_SetString(BsddbError, "can't allocate lock");
+ Py_DECREF(dp);
+ return NULL;
+ }
#endif
- return (PyObject *)dp;
+ return (PyObject *)dp;
}
static void
bsddb_dealloc(bsddbobject *dp)
{
#ifdef WITH_THREAD
- if (dp->di_lock) {
- PyThread_acquire_lock(dp->di_lock, 0);
- PyThread_release_lock(dp->di_lock);
- PyThread_free_lock(dp->di_lock);
- dp->di_lock = NULL;
- }
+ if (dp->di_lock) {
+ PyThread_acquire_lock(dp->di_lock, 0);
+ PyThread_release_lock(dp->di_lock);
+ PyThread_free_lock(dp->di_lock);
+ dp->di_lock = NULL;
+ }
#endif
- if (dp->di_bsddb != NULL) {
- int status;
- Py_BEGIN_ALLOW_THREADS
- status = (dp->di_bsddb->close)(dp->di_bsddb);
- Py_END_ALLOW_THREADS
- if (status != 0)
- fprintf(stderr,
- "Python bsddb: close errno %d in dealloc\n",
- errno);
- }
- PyObject_Del(dp);
+ if (dp->di_bsddb != NULL) {
+ int status;
+ Py_BEGIN_ALLOW_THREADS
+ status = (dp->di_bsddb->close)(dp->di_bsddb);
+ Py_END_ALLOW_THREADS
+ if (status != 0)
+ fprintf(stderr,
+ "Python bsddb: close errno %d in dealloc\n",
+ errno);
+ }
+ PyObject_Del(dp);
}
#ifdef WITH_THREAD
#define BSDDB_BGN_SAVE(_dp) \
- Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(_dp->di_lock,1);
+ Py_BEGIN_ALLOW_THREADS PyThread_acquire_lock(_dp->di_lock,1);
#define BSDDB_END_SAVE(_dp) \
- PyThread_release_lock(_dp->di_lock); Py_END_ALLOW_THREADS
+ PyThread_release_lock(_dp->di_lock); Py_END_ALLOW_THREADS
#else
-#define BSDDB_BGN_SAVE(_dp) Py_BEGIN_ALLOW_THREADS
+#define BSDDB_BGN_SAVE(_dp) Py_BEGIN_ALLOW_THREADS
#define BSDDB_END_SAVE(_dp) Py_END_ALLOW_THREADS
#endif
static Py_ssize_t
bsddb_length(bsddbobject *dp)
{
- check_bsddbobject_open(dp, -1);
- if (dp->di_size < 0) {
- DBT krec, drec;
- int status;
- int size = 0;
- BSDDB_BGN_SAVE(dp)
- for (status = (dp->di_bsddb->seq)(dp->di_bsddb,
- &krec, &drec,R_FIRST);
- status == 0;
- status = (dp->di_bsddb->seq)(dp->di_bsddb,
- &krec, &drec, R_NEXT))
- size++;
- BSDDB_END_SAVE(dp)
- if (status < 0) {
- PyErr_SetFromErrno(BsddbError);
- return -1;
- }
- dp->di_size = size;
- }
- return dp->di_size;
+ check_bsddbobject_open(dp, -1);
+ if (dp->di_size < 0) {
+ DBT krec, drec;
+ int status;
+ int size = 0;
+ BSDDB_BGN_SAVE(dp)
+ for (status = (dp->di_bsddb->seq)(dp->di_bsddb,
+ &krec, &drec,R_FIRST);
+ status == 0;
+ status = (dp->di_bsddb->seq)(dp->di_bsddb,
+ &krec, &drec, R_NEXT))
+ size++;
+ BSDDB_END_SAVE(dp)
+ if (status < 0) {
+ PyErr_SetFromErrno(BsddbError);
+ return -1;
+ }
+ dp->di_size = size;
+ }
+ return dp->di_size;
}
static PyObject *
bsddb_subscript(bsddbobject *dp, PyObject *key)
{
- int status;
- DBT krec, drec;
- char *data = NULL;
- char buf[4096];
- int size;
- PyObject *result;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_Parse(key, "i", &recno)) {
- PyErr_SetString(PyExc_TypeError,
- "key type must be integer");
- return NULL;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_Parse(key, "s#", &data, &size)) {
- PyErr_SetString(PyExc_TypeError,
- "key type must be string");
- return NULL;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, NULL);
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
- if (status == 0) {
- if (drec.size > sizeof(buf)) data = malloc(drec.size);
- else data = buf;
- if (data!=NULL) memcpy(data,drec.data,drec.size);
- }
- BSDDB_END_SAVE(dp)
- if (data==NULL) return PyErr_NoMemory();
- if (status != 0) {
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetObject(PyExc_KeyError, key);
- return NULL;
- }
-
- result = PyString_FromStringAndSize(data, (int)drec.size);
- if (data != buf) free(data);
- return result;
+ int status;
+ DBT krec, drec;
+ char *data = NULL;
+ char buf[4096];
+ int size;
+ PyObject *result;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_Parse(key, "i", &recno)) {
+ PyErr_SetString(PyExc_TypeError,
+ "key type must be integer");
+ return NULL;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_Parse(key, "s#", &data, &size)) {
+ PyErr_SetString(PyExc_TypeError,
+ "key type must be string");
+ return NULL;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, NULL);
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
+ if (status == 0) {
+ if (drec.size > sizeof(buf)) data = malloc(drec.size);
+ else data = buf;
+ if (data!=NULL) memcpy(data,drec.data,drec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (data==NULL) return PyErr_NoMemory();
+ if (status != 0) {
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetObject(PyExc_KeyError, key);
+ return NULL;
+ }
+
+ result = PyString_FromStringAndSize(data, (int)drec.size);
+ if (data != buf) free(data);
+ return result;
}
static int
bsddb_ass_sub(bsddbobject *dp, PyObject *key, PyObject *value)
{
- int status;
- DBT krec, drec;
- char *data;
- int size;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_Parse(key, "i", &recno)) {
- PyErr_SetString(PyExc_TypeError,
- "bsddb key type must be integer");
- return -1;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_Parse(key, "s#", &data, &size)) {
- PyErr_SetString(PyExc_TypeError,
- "bsddb key type must be string");
- return -1;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, -1);
- dp->di_size = -1;
- if (value == NULL) {
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->del)(dp->di_bsddb, &krec, 0);
- BSDDB_END_SAVE(dp)
- }
- else {
- if (!PyArg_Parse(value, "s#", &data, &size)) {
- PyErr_SetString(PyExc_TypeError,
- "bsddb value type must be string");
- return -1;
- }
- drec.data = data;
- drec.size = size;
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->put)(dp->di_bsddb, &krec, &drec, 0);
- BSDDB_END_SAVE(dp)
- }
- if (status != 0) {
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetObject(PyExc_KeyError, key);
- return -1;
- }
- return 0;
+ int status;
+ DBT krec, drec;
+ char *data;
+ int size;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_Parse(key, "i", &recno)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bsddb key type must be integer");
+ return -1;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_Parse(key, "s#", &data, &size)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bsddb key type must be string");
+ return -1;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, -1);
+ dp->di_size = -1;
+ if (value == NULL) {
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->del)(dp->di_bsddb, &krec, 0);
+ BSDDB_END_SAVE(dp)
+ }
+ else {
+ if (!PyArg_Parse(value, "s#", &data, &size)) {
+ PyErr_SetString(PyExc_TypeError,
+ "bsddb value type must be string");
+ return -1;
+ }
+ drec.data = data;
+ drec.size = size;
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->put)(dp->di_bsddb, &krec, &drec, 0);
+ BSDDB_END_SAVE(dp)
+ }
+ if (status != 0) {
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetObject(PyExc_KeyError, key);
+ return -1;
+ }
+ return 0;
}
static PyMappingMethods bsddb_as_mapping = {
- (lenfunc)bsddb_length, /*mp_length*/
- (binaryfunc)bsddb_subscript, /*mp_subscript*/
- (objobjargproc)bsddb_ass_sub, /*mp_ass_subscript*/
+ (lenfunc)bsddb_length, /*mp_length*/
+ (binaryfunc)bsddb_subscript, /*mp_subscript*/
+ (objobjargproc)bsddb_ass_sub, /*mp_ass_subscript*/
};
static PyObject *
bsddb_close(bsddbobject *dp)
{
- if (dp->di_bsddb != NULL) {
- int status;
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->close)(dp->di_bsddb);
- BSDDB_END_SAVE(dp)
- if (status != 0) {
- dp->di_bsddb = NULL;
- PyErr_SetFromErrno(BsddbError);
- return NULL;
- }
- }
- dp->di_bsddb = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (dp->di_bsddb != NULL) {
+ int status;
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->close)(dp->di_bsddb);
+ BSDDB_END_SAVE(dp)
+ if (status != 0) {
+ dp->di_bsddb = NULL;
+ PyErr_SetFromErrno(BsddbError);
+ return NULL;
+ }
+ }
+ dp->di_bsddb = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
bsddb_keys(bsddbobject *dp)
{
- PyObject *list, *item=NULL;
- DBT krec, drec;
- char *data=NULL,buf[4096];
- int status;
- int err;
-
- check_bsddbobject_open(dp, NULL);
- list = PyList_New(0);
- if (list == NULL)
- return NULL;
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_FIRST);
- if (status == 0) {
- if (krec.size > sizeof(buf)) data = malloc(krec.size);
- else data = buf;
- if (data != NULL) memcpy(data,krec.data,krec.size);
- }
- BSDDB_END_SAVE(dp)
- if (status == 0 && data==NULL) return PyErr_NoMemory();
- while (status == 0) {
- if (dp->di_type == DB_RECNO)
- item = PyInt_FromLong(*((int*)data));
- else
- item = PyString_FromStringAndSize(data,
- (int)krec.size);
- if (data != buf) free(data);
- if (item == NULL) {
- Py_DECREF(list);
- return NULL;
- }
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err != 0) {
- Py_DECREF(list);
- return NULL;
- }
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)
- (dp->di_bsddb, &krec, &drec, R_NEXT);
- if (status == 0) {
- if (krec.size > sizeof(buf))
- data = malloc(krec.size);
- else data = buf;
- if (data != NULL)
- memcpy(data,krec.data,krec.size);
- }
- BSDDB_END_SAVE(dp)
- if (data == NULL) return PyErr_NoMemory();
- }
- if (status < 0) {
- PyErr_SetFromErrno(BsddbError);
- Py_DECREF(list);
- return NULL;
- }
- if (dp->di_size < 0)
- dp->di_size = PyList_Size(list); /* We just did the work */
- return list;
+ PyObject *list, *item=NULL;
+ DBT krec, drec;
+ char *data=NULL,buf[4096];
+ int status;
+ int err;
+
+ check_bsddbobject_open(dp, NULL);
+ list = PyList_New(0);
+ if (list == NULL)
+ return NULL;
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_FIRST);
+ if (status == 0) {
+ if (krec.size > sizeof(buf)) data = malloc(krec.size);
+ else data = buf;
+ if (data != NULL) memcpy(data,krec.data,krec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (status == 0 && data==NULL) return PyErr_NoMemory();
+ while (status == 0) {
+ if (dp->di_type == DB_RECNO)
+ item = PyInt_FromLong(*((int*)data));
+ else
+ item = PyString_FromStringAndSize(data,
+ (int)krec.size);
+ if (data != buf) free(data);
+ if (item == NULL) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err != 0) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)
+ (dp->di_bsddb, &krec, &drec, R_NEXT);
+ if (status == 0) {
+ if (krec.size > sizeof(buf))
+ data = malloc(krec.size);
+ else data = buf;
+ if (data != NULL)
+ memcpy(data,krec.data,krec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (data == NULL) return PyErr_NoMemory();
+ }
+ if (status < 0) {
+ PyErr_SetFromErrno(BsddbError);
+ Py_DECREF(list);
+ return NULL;
+ }
+ if (dp->di_size < 0)
+ dp->di_size = PyList_Size(list); /* We just did the work */
+ return list;
}
static PyObject *
bsddb_has_key(bsddbobject *dp, PyObject *args)
{
- DBT krec, drec;
- int status;
- char *data;
- int size;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_ParseTuple(args, "i;key type must be integer",
- &recno)) {
- return NULL;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_ParseTuple(args, "s#;key type must be string",
- &data, &size)) {
- return NULL;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, NULL);
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
- BSDDB_END_SAVE(dp)
- if (status < 0) {
- PyErr_SetFromErrno(BsddbError);
- return NULL;
- }
-
- return PyInt_FromLong(status == 0);
+ DBT krec, drec;
+ int status;
+ char *data;
+ int size;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_ParseTuple(args, "i;key type must be integer",
+ &recno)) {
+ return NULL;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_ParseTuple(args, "s#;key type must be string",
+ &data, &size)) {
+ return NULL;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, NULL);
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->get)(dp->di_bsddb, &krec, &drec, 0);
+ BSDDB_END_SAVE(dp)
+ if (status < 0) {
+ PyErr_SetFromErrno(BsddbError);
+ return NULL;
+ }
+
+ return PyInt_FromLong(status == 0);
}
static PyObject *
bsddb_set_location(bsddbobject *dp, PyObject *key)
{
- int status;
- DBT krec, drec;
- char *data = NULL;
- char buf[4096];
- int size;
- PyObject *result;
- recno_t recno;
-
- if (dp->di_type == DB_RECNO) {
- if (!PyArg_ParseTuple(key, "i;key type must be integer",
- &recno)) {
- return NULL;
- }
- krec.data = &recno;
- krec.size = sizeof(recno);
- }
- else {
- if (!PyArg_ParseTuple(key, "s#;key type must be string",
- &data, &size)) {
- return NULL;
- }
- krec.data = data;
- krec.size = size;
- }
- check_bsddbobject_open(dp, NULL);
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_CURSOR);
- if (status == 0) {
- if (drec.size > sizeof(buf)) data = malloc(drec.size);
- else data = buf;
- if (data!=NULL) memcpy(data,drec.data,drec.size);
- }
- BSDDB_END_SAVE(dp)
- if (data==NULL) return PyErr_NoMemory();
- if (status != 0) {
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetObject(PyExc_KeyError, key);
- return NULL;
- }
-
- if (dp->di_type == DB_RECNO)
- result = Py_BuildValue("is#", *((int*)krec.data),
- data, drec.size);
- else
- result = Py_BuildValue("s#s#", krec.data, krec.size,
- data, drec.size);
- if (data != buf) free(data);
- return result;
+ int status;
+ DBT krec, drec;
+ char *data = NULL;
+ char buf[4096];
+ int size;
+ PyObject *result;
+ recno_t recno;
+
+ if (dp->di_type == DB_RECNO) {
+ if (!PyArg_ParseTuple(key, "i;key type must be integer",
+ &recno)) {
+ return NULL;
+ }
+ krec.data = &recno;
+ krec.size = sizeof(recno);
+ }
+ else {
+ if (!PyArg_ParseTuple(key, "s#;key type must be string",
+ &data, &size)) {
+ return NULL;
+ }
+ krec.data = data;
+ krec.size = size;
+ }
+ check_bsddbobject_open(dp, NULL);
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec, &drec, R_CURSOR);
+ if (status == 0) {
+ if (drec.size > sizeof(buf)) data = malloc(drec.size);
+ else data = buf;
+ if (data!=NULL) memcpy(data,drec.data,drec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (data==NULL) return PyErr_NoMemory();
+ if (status != 0) {
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetObject(PyExc_KeyError, key);
+ return NULL;
+ }
+
+ if (dp->di_type == DB_RECNO)
+ result = Py_BuildValue("is#", *((int*)krec.data),
+ data, drec.size);
+ else
+ result = Py_BuildValue("s#s#", krec.data, krec.size,
+ data, drec.size);
+ if (data != buf) free(data);
+ return result;
}
static PyObject *
bsddb_seq(bsddbobject *dp, int sequence_request)
{
- int status;
- DBT krec, drec;
- char *kdata=NULL,kbuf[4096];
- char *ddata=NULL,dbuf[4096];
- PyObject *result;
-
- check_bsddbobject_open(dp, NULL);
- krec.data = 0;
- krec.size = 0;
-
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec,
- &drec, sequence_request);
- if (status == 0) {
- if (krec.size > sizeof(kbuf)) kdata = malloc(krec.size);
- else kdata = kbuf;
- if (kdata != NULL) memcpy(kdata,krec.data,krec.size);
- if (drec.size > sizeof(dbuf)) ddata = malloc(drec.size);
- else ddata = dbuf;
- if (ddata != NULL) memcpy(ddata,drec.data,drec.size);
- }
- BSDDB_END_SAVE(dp)
- if (status == 0) {
- if ((kdata == NULL) || (ddata == NULL))
- return PyErr_NoMemory();
- }
- else {
- /* (status != 0) */
- if (status < 0)
- PyErr_SetFromErrno(BsddbError);
- else
- PyErr_SetString(PyExc_KeyError, "no key/data pairs");
- return NULL;
- }
-
- if (dp->di_type == DB_RECNO)
- result = Py_BuildValue("is#", *((int*)kdata),
- ddata, drec.size);
- else
- result = Py_BuildValue("s#s#", kdata, krec.size,
- ddata, drec.size);
- if (kdata != kbuf) free(kdata);
- if (ddata != dbuf) free(ddata);
- return result;
+ int status;
+ DBT krec, drec;
+ char *kdata=NULL,kbuf[4096];
+ char *ddata=NULL,dbuf[4096];
+ PyObject *result;
+
+ check_bsddbobject_open(dp, NULL);
+ krec.data = 0;
+ krec.size = 0;
+
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->seq)(dp->di_bsddb, &krec,
+ &drec, sequence_request);
+ if (status == 0) {
+ if (krec.size > sizeof(kbuf)) kdata = malloc(krec.size);
+ else kdata = kbuf;
+ if (kdata != NULL) memcpy(kdata,krec.data,krec.size);
+ if (drec.size > sizeof(dbuf)) ddata = malloc(drec.size);
+ else ddata = dbuf;
+ if (ddata != NULL) memcpy(ddata,drec.data,drec.size);
+ }
+ BSDDB_END_SAVE(dp)
+ if (status == 0) {
+ if ((kdata == NULL) || (ddata == NULL))
+ return PyErr_NoMemory();
+ }
+ else {
+ /* (status != 0) */
+ if (status < 0)
+ PyErr_SetFromErrno(BsddbError);
+ else
+ PyErr_SetString(PyExc_KeyError, "no key/data pairs");
+ return NULL;
+ }
+
+ if (dp->di_type == DB_RECNO)
+ result = Py_BuildValue("is#", *((int*)kdata),
+ ddata, drec.size);
+ else
+ result = Py_BuildValue("s#s#", kdata, krec.size,
+ ddata, drec.size);
+ if (kdata != kbuf) free(kdata);
+ if (ddata != dbuf) free(ddata);
+ return result;
}
static PyObject *
bsddb_next(bsddbobject *dp)
{
- return bsddb_seq(dp, R_NEXT);
+ return bsddb_seq(dp, R_NEXT);
}
static PyObject *
bsddb_previous(bsddbobject *dp)
{
- return bsddb_seq(dp, R_PREV);
+ return bsddb_seq(dp, R_PREV);
}
static PyObject *
bsddb_first(bsddbobject *dp)
{
- return bsddb_seq(dp, R_FIRST);
+ return bsddb_seq(dp, R_FIRST);
}
static PyObject *
bsddb_last(bsddbobject *dp)
{
- return bsddb_seq(dp, R_LAST);
+ return bsddb_seq(dp, R_LAST);
}
static PyObject *
bsddb_sync(bsddbobject *dp)
{
- int status;
-
- check_bsddbobject_open(dp, NULL);
- BSDDB_BGN_SAVE(dp)
- status = (dp->di_bsddb->sync)(dp->di_bsddb, 0);
- BSDDB_END_SAVE(dp)
- if (status != 0) {
- PyErr_SetFromErrno(BsddbError);
- return NULL;
- }
- return PyInt_FromLong(0);
+ int status;
+
+ check_bsddbobject_open(dp, NULL);
+ BSDDB_BGN_SAVE(dp)
+ status = (dp->di_bsddb->sync)(dp->di_bsddb, 0);
+ BSDDB_END_SAVE(dp)
+ if (status != 0) {
+ PyErr_SetFromErrno(BsddbError);
+ return NULL;
+ }
+ return PyInt_FromLong(0);
}
static PyMethodDef bsddb_methods[] = {
- {"close", (PyCFunction)bsddb_close, METH_NOARGS},
- {"keys", (PyCFunction)bsddb_keys, METH_NOARGS},
- {"has_key", (PyCFunction)bsddb_has_key, METH_VARARGS},
- {"set_location", (PyCFunction)bsddb_set_location, METH_VARARGS},
- {"next", (PyCFunction)bsddb_next, METH_NOARGS},
- {"previous", (PyCFunction)bsddb_previous, METH_NOARGS},
- {"first", (PyCFunction)bsddb_first, METH_NOARGS},
- {"last", (PyCFunction)bsddb_last, METH_NOARGS},
- {"sync", (PyCFunction)bsddb_sync, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"close", (PyCFunction)bsddb_close, METH_NOARGS},
+ {"keys", (PyCFunction)bsddb_keys, METH_NOARGS},
+ {"has_key", (PyCFunction)bsddb_has_key, METH_VARARGS},
+ {"set_location", (PyCFunction)bsddb_set_location, METH_VARARGS},
+ {"next", (PyCFunction)bsddb_next, METH_NOARGS},
+ {"previous", (PyCFunction)bsddb_previous, METH_NOARGS},
+ {"first", (PyCFunction)bsddb_first, METH_NOARGS},
+ {"last", (PyCFunction)bsddb_last, METH_NOARGS},
+ {"sync", (PyCFunction)bsddb_sync, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
bsddb_getattr(PyObject *dp, char *name)
{
- return Py_FindMethod(bsddb_methods, dp, name);
+ return Py_FindMethod(bsddb_methods, dp, name);
}
static PyTypeObject Bsddbtype = {
- PyObject_HEAD_INIT(NULL)
- 0,
- "bsddb.bsddb",
- sizeof(bsddbobject),
- 0,
- (destructor)bsddb_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)bsddb_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- &bsddb_as_mapping, /*tp_as_mapping*/
+ PyObject_HEAD_INIT(NULL)
+ 0,
+ "bsddb.bsddb",
+ sizeof(bsddbobject),
+ 0,
+ (destructor)bsddb_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)bsddb_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ &bsddb_as_mapping, /*tp_as_mapping*/
};
static PyObject *
bsdhashopen(PyObject *self, PyObject *args)
{
- char *file;
- char *flag = NULL;
- int flags = O_RDONLY;
- int mode = 0666;
- int bsize = 0;
- int ffactor = 0;
- int nelem = 0;
- int cachesize = 0;
- int hash = 0; /* XXX currently ignored */
- int lorder = 0;
-
- if (!PyArg_ParseTuple(args, "z|siiiiiii:hashopen",
- &file, &flag, &mode,
- &bsize, &ffactor, &nelem, &cachesize,
- &hash, &lorder))
- return NULL;
- if (flag != NULL) {
- /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
- if (flag[0] == 'r')
- flags = O_RDONLY;
- else if (flag[0] == 'w')
- flags = O_RDWR;
- else if (flag[0] == 'c')
- flags = O_RDWR|O_CREAT;
- else if (flag[0] == 'n')
- flags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(BsddbError,
- "Flag should begin with 'r', 'w', 'c' or 'n'");
- return NULL;
- }
- if (flag[1] == 'l') {
+ char *file;
+ char *flag = NULL;
+ int flags = O_RDONLY;
+ int mode = 0666;
+ int bsize = 0;
+ int ffactor = 0;
+ int nelem = 0;
+ int cachesize = 0;
+ int hash = 0; /* XXX currently ignored */
+ int lorder = 0;
+
+ if (!PyArg_ParseTuple(args, "z|siiiiiii:hashopen",
+ &file, &flag, &mode,
+ &bsize, &ffactor, &nelem, &cachesize,
+ &hash, &lorder))
+ return NULL;
+ if (flag != NULL) {
+ /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
+ if (flag[0] == 'r')
+ flags = O_RDONLY;
+ else if (flag[0] == 'w')
+ flags = O_RDWR;
+ else if (flag[0] == 'c')
+ flags = O_RDWR|O_CREAT;
+ else if (flag[0] == 'n')
+ flags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(BsddbError,
+ "Flag should begin with 'r', 'w', 'c' or 'n'");
+ return NULL;
+ }
+ if (flag[1] == 'l') {
#if defined(O_EXLOCK) && defined(O_SHLOCK)
- if (flag[0] == 'r')
- flags |= O_SHLOCK;
- else
- flags |= O_EXLOCK;
+ if (flag[0] == 'r')
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
#else
- PyErr_SetString(BsddbError,
- "locking not supported on this platform");
- return NULL;
+ PyErr_SetString(BsddbError,
+ "locking not supported on this platform");
+ return NULL;
#endif
- }
- }
- return newdbhashobject(file, flags, mode,
- bsize, ffactor, nelem, cachesize, hash, lorder);
+ }
+ }
+ return newdbhashobject(file, flags, mode,
+ bsize, ffactor, nelem, cachesize, hash, lorder);
}
static PyObject *
bsdbtopen(PyObject *self, PyObject *args)
{
- char *file;
- char *flag = NULL;
- int flags = O_RDONLY;
- int mode = 0666;
- int cachesize = 0;
- int maxkeypage = 0;
- int minkeypage = 0;
- int btflags = 0;
- unsigned int psize = 0;
- int lorder = 0;
-
- if (!PyArg_ParseTuple(args, "z|siiiiiii:btopen",
- &file, &flag, &mode,
- &btflags, &cachesize, &maxkeypage, &minkeypage,
- &psize, &lorder))
- return NULL;
- if (flag != NULL) {
- /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
- if (flag[0] == 'r')
- flags = O_RDONLY;
- else if (flag[0] == 'w')
- flags = O_RDWR;
- else if (flag[0] == 'c')
- flags = O_RDWR|O_CREAT;
- else if (flag[0] == 'n')
- flags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(BsddbError,
- "Flag should begin with 'r', 'w', 'c' or 'n'");
- return NULL;
- }
- if (flag[1] == 'l') {
+ char *file;
+ char *flag = NULL;
+ int flags = O_RDONLY;
+ int mode = 0666;
+ int cachesize = 0;
+ int maxkeypage = 0;
+ int minkeypage = 0;
+ int btflags = 0;
+ unsigned int psize = 0;
+ int lorder = 0;
+
+ if (!PyArg_ParseTuple(args, "z|siiiiiii:btopen",
+ &file, &flag, &mode,
+ &btflags, &cachesize, &maxkeypage, &minkeypage,
+ &psize, &lorder))
+ return NULL;
+ if (flag != NULL) {
+ /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
+ if (flag[0] == 'r')
+ flags = O_RDONLY;
+ else if (flag[0] == 'w')
+ flags = O_RDWR;
+ else if (flag[0] == 'c')
+ flags = O_RDWR|O_CREAT;
+ else if (flag[0] == 'n')
+ flags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(BsddbError,
+ "Flag should begin with 'r', 'w', 'c' or 'n'");
+ return NULL;
+ }
+ if (flag[1] == 'l') {
#if defined(O_EXLOCK) && defined(O_SHLOCK)
- if (flag[0] == 'r')
- flags |= O_SHLOCK;
- else
- flags |= O_EXLOCK;
+ if (flag[0] == 'r')
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
#else
- PyErr_SetString(BsddbError,
- "locking not supported on this platform");
- return NULL;
+ PyErr_SetString(BsddbError,
+ "locking not supported on this platform");
+ return NULL;
#endif
- }
- }
- return newdbbtobject(file, flags, mode,
- btflags, cachesize, maxkeypage, minkeypage,
- psize, lorder);
+ }
+ }
+ return newdbbtobject(file, flags, mode,
+ btflags, cachesize, maxkeypage, minkeypage,
+ psize, lorder);
}
static PyObject *
bsdrnopen(PyObject *self, PyObject *args)
{
- char *file;
- char *flag = NULL;
- int flags = O_RDONLY;
- int mode = 0666;
- int cachesize = 0;
- int rnflags = 0;
- unsigned int psize = 0;
- int lorder = 0;
- size_t reclen = 0;
- char *bval = "";
- char *bfname = NULL;
-
- if (!PyArg_ParseTuple(args, "z|siiiiiiss:rnopen",
- &file, &flag, &mode,
- &rnflags, &cachesize, &psize, &lorder,
- &reclen, &bval, &bfname))
- return NULL;
-
- if (flag != NULL) {
- /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
- if (flag[0] == 'r')
- flags = O_RDONLY;
- else if (flag[0] == 'w')
- flags = O_RDWR;
- else if (flag[0] == 'c')
- flags = O_RDWR|O_CREAT;
- else if (flag[0] == 'n')
- flags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(BsddbError,
- "Flag should begin with 'r', 'w', 'c' or 'n'");
- return NULL;
- }
- if (flag[1] == 'l') {
+ char *file;
+ char *flag = NULL;
+ int flags = O_RDONLY;
+ int mode = 0666;
+ int cachesize = 0;
+ int rnflags = 0;
+ unsigned int psize = 0;
+ int lorder = 0;
+ size_t reclen = 0;
+ char *bval = "";
+ char *bfname = NULL;
+
+ if (!PyArg_ParseTuple(args, "z|siiiiiiss:rnopen",
+ &file, &flag, &mode,
+ &rnflags, &cachesize, &psize, &lorder,
+ &reclen, &bval, &bfname))
+ return NULL;
+
+ if (flag != NULL) {
+ /* XXX need to pass O_EXCL, O_EXLOCK, O_NONBLOCK, O_SHLOCK */
+ if (flag[0] == 'r')
+ flags = O_RDONLY;
+ else if (flag[0] == 'w')
+ flags = O_RDWR;
+ else if (flag[0] == 'c')
+ flags = O_RDWR|O_CREAT;
+ else if (flag[0] == 'n')
+ flags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(BsddbError,
+ "Flag should begin with 'r', 'w', 'c' or 'n'");
+ return NULL;
+ }
+ if (flag[1] == 'l') {
#if defined(O_EXLOCK) && defined(O_SHLOCK)
- if (flag[0] == 'r')
- flags |= O_SHLOCK;
- else
- flags |= O_EXLOCK;
+ if (flag[0] == 'r')
+ flags |= O_SHLOCK;
+ else
+ flags |= O_EXLOCK;
#else
- PyErr_SetString(BsddbError,
- "locking not supported on this platform");
- return NULL;
+ PyErr_SetString(BsddbError,
+ "locking not supported on this platform");
+ return NULL;
#endif
- }
- else if (flag[1] != '\0') {
- PyErr_SetString(BsddbError,
- "Flag char 2 should be 'l' or absent");
- return NULL;
- }
- }
- return newdbrnobject(file, flags, mode, rnflags, cachesize,
- psize, lorder, reclen, bval[0], bfname);
+ }
+ else if (flag[1] != '\0') {
+ PyErr_SetString(BsddbError,
+ "Flag char 2 should be 'l' or absent");
+ return NULL;
+ }
+ }
+ return newdbrnobject(file, flags, mode, rnflags, cachesize,
+ psize, lorder, reclen, bval[0], bfname);
}
static PyMethodDef bsddbmodule_methods[] = {
- {"hashopen", (PyCFunction)bsdhashopen, METH_VARARGS},
- {"btopen", (PyCFunction)bsdbtopen, METH_VARARGS},
- {"rnopen", (PyCFunction)bsdrnopen, METH_VARARGS},
- /* strictly for use by dbhhash!!! */
- {"open", (PyCFunction)bsdhashopen, METH_VARARGS},
- {0, 0},
+ {"hashopen", (PyCFunction)bsdhashopen, METH_VARARGS},
+ {"btopen", (PyCFunction)bsdbtopen, METH_VARARGS},
+ {"rnopen", (PyCFunction)bsdrnopen, METH_VARARGS},
+ /* strictly for use by dbhhash!!! */
+ {"open", (PyCFunction)bsdhashopen, METH_VARARGS},
+ {0, 0},
};
PyMODINIT_FUNC
initbsddb185(void) {
- PyObject *m, *d;
+ PyObject *m, *d;
if (PyErr_WarnPy3k("the bsddb185 module has been removed in "
"Python 3.0", 2) < 0)
- return;
-
- Bsddbtype.ob_type = &PyType_Type;
- m = Py_InitModule("bsddb185", bsddbmodule_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- BsddbError = PyErr_NewException("bsddb.error", NULL, NULL);
- if (BsddbError != NULL)
- PyDict_SetItemString(d, "error", BsddbError);
+ return;
+
+ Bsddbtype.ob_type = &PyType_Type;
+ m = Py_InitModule("bsddb185", bsddbmodule_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ BsddbError = PyErr_NewException("bsddb.error", NULL, NULL);
+ if (BsddbError != NULL)
+ PyDict_SetItemString(d, "error", BsddbError);
}
diff --git a/Modules/bz2module.c b/Modules/bz2module.c
index c3dae7a..8e09766 100644
--- a/Modules/bz2module.c
+++ b/Modules/bz2module.c
@@ -41,20 +41,20 @@ typedef fpos_t Py_off_t;
#define MODE_READ_EOF 2
#define MODE_WRITE 3
-#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type)
+#define BZ2FileObject_Check(v) (Py_TYPE(v) == &BZ2File_Type)
#ifdef BZ_CONFIG_ERROR
#if SIZEOF_LONG >= 8
#define BZS_TOTAL_OUT(bzs) \
- (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
+ (((long)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
#elif SIZEOF_LONG_LONG >= 8
#define BZS_TOTAL_OUT(bzs) \
- (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
+ (((PY_LONG_LONG)bzs->total_out_hi32 << 32) + bzs->total_out_lo32)
#else
#define BZS_TOTAL_OUT(bzs) \
- bzs->total_out_lo32
+ bzs->total_out_lo32
#endif
#else /* ! BZ_CONFIG_ERROR */
@@ -79,11 +79,11 @@ typedef fpos_t Py_off_t;
#ifdef WITH_THREAD
#define ACQUIRE_LOCK(obj) do { \
- if (!PyThread_acquire_lock(obj->lock, 0)) { \
- Py_BEGIN_ALLOW_THREADS \
- PyThread_acquire_lock(obj->lock, 1); \
- Py_END_ALLOW_THREADS \
- } } while(0)
+ if (!PyThread_acquire_lock(obj->lock, 0)) { \
+ Py_BEGIN_ALLOW_THREADS \
+ PyThread_acquire_lock(obj->lock, 1); \
+ Py_END_ALLOW_THREADS \
+ } } while(0)
#define RELEASE_LOCK(obj) PyThread_release_lock(obj->lock)
#else
#define ACQUIRE_LOCK(obj)
@@ -91,53 +91,53 @@ typedef fpos_t Py_off_t;
#endif
/* Bits in f_newlinetypes */
-#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
-#define NEWLINE_CR 1 /* \r newline seen */
-#define NEWLINE_LF 2 /* \n newline seen */
-#define NEWLINE_CRLF 4 /* \r\n newline seen */
+#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
+#define NEWLINE_CR 1 /* \r newline seen */
+#define NEWLINE_LF 2 /* \n newline seen */
+#define NEWLINE_CRLF 4 /* \r\n newline seen */
/* ===================================================================== */
/* Structure definitions. */
typedef struct {
- PyObject_HEAD
- PyObject *file;
+ PyObject_HEAD
+ PyObject *file;
- char* f_buf; /* Allocated readahead buffer */
- char* f_bufend; /* Points after last occupied position */
- char* f_bufptr; /* Current buffer position */
+ char* f_buf; /* Allocated readahead buffer */
+ char* f_bufend; /* Points after last occupied position */
+ char* f_bufptr; /* Current buffer position */
- int f_softspace; /* Flag used by 'print' command */
+ int f_softspace; /* Flag used by 'print' command */
- int f_univ_newline; /* Handle any newline convention */
- int f_newlinetypes; /* Types of newlines seen */
- int f_skipnextlf; /* Skip next \n */
+ int f_univ_newline; /* Handle any newline convention */
+ int f_newlinetypes; /* Types of newlines seen */
+ int f_skipnextlf; /* Skip next \n */
- BZFILE *fp;
- int mode;
- Py_off_t pos;
- Py_off_t size;
+ BZFILE *fp;
+ int mode;
+ Py_off_t pos;
+ Py_off_t size;
#ifdef WITH_THREAD
- PyThread_type_lock lock;
+ PyThread_type_lock lock;
#endif
} BZ2FileObject;
typedef struct {
- PyObject_HEAD
- bz_stream bzs;
- int running;
+ PyObject_HEAD
+ bz_stream bzs;
+ int running;
#ifdef WITH_THREAD
- PyThread_type_lock lock;
+ PyThread_type_lock lock;
#endif
} BZ2CompObject;
typedef struct {
- PyObject_HEAD
- bz_stream bzs;
- int running;
- PyObject *unused_data;
+ PyObject_HEAD
+ bz_stream bzs;
+ int running;
+ PyObject *unused_data;
#ifdef WITH_THREAD
- PyThread_type_lock lock;
+ PyThread_type_lock lock;
#endif
} BZ2DecompObject;
@@ -147,59 +147,59 @@ typedef struct {
static int
Util_CatchBZ2Error(int bzerror)
{
- int ret = 0;
- switch(bzerror) {
- case BZ_OK:
- case BZ_STREAM_END:
- break;
+ int ret = 0;
+ switch(bzerror) {
+ case BZ_OK:
+ case BZ_STREAM_END:
+ break;
#ifdef BZ_CONFIG_ERROR
- case BZ_CONFIG_ERROR:
- PyErr_SetString(PyExc_SystemError,
- "the bz2 library was not compiled "
- "correctly");
- ret = 1;
- break;
+ case BZ_CONFIG_ERROR:
+ PyErr_SetString(PyExc_SystemError,
+ "the bz2 library was not compiled "
+ "correctly");
+ ret = 1;
+ break;
#endif
- case BZ_PARAM_ERROR:
- PyErr_SetString(PyExc_ValueError,
- "the bz2 library has received wrong "
- "parameters");
- ret = 1;
- break;
-
- case BZ_MEM_ERROR:
- PyErr_NoMemory();
- ret = 1;
- break;
-
- case BZ_DATA_ERROR:
- case BZ_DATA_ERROR_MAGIC:
- PyErr_SetString(PyExc_IOError, "invalid data stream");
- ret = 1;
- break;
-
- case BZ_IO_ERROR:
- PyErr_SetString(PyExc_IOError, "unknown IO error");
- ret = 1;
- break;
-
- case BZ_UNEXPECTED_EOF:
- PyErr_SetString(PyExc_EOFError,
- "compressed file ended before the "
- "logical end-of-stream was detected");
- ret = 1;
- break;
-
- case BZ_SEQUENCE_ERROR:
- PyErr_SetString(PyExc_RuntimeError,
- "wrong sequence of bz2 library "
- "commands used");
- ret = 1;
- break;
- }
- return ret;
+ case BZ_PARAM_ERROR:
+ PyErr_SetString(PyExc_ValueError,
+ "the bz2 library has received wrong "
+ "parameters");
+ ret = 1;
+ break;
+
+ case BZ_MEM_ERROR:
+ PyErr_NoMemory();
+ ret = 1;
+ break;
+
+ case BZ_DATA_ERROR:
+ case BZ_DATA_ERROR_MAGIC:
+ PyErr_SetString(PyExc_IOError, "invalid data stream");
+ ret = 1;
+ break;
+
+ case BZ_IO_ERROR:
+ PyErr_SetString(PyExc_IOError, "unknown IO error");
+ ret = 1;
+ break;
+
+ case BZ_UNEXPECTED_EOF:
+ PyErr_SetString(PyExc_EOFError,
+ "compressed file ended before the "
+ "logical end-of-stream was detected");
+ ret = 1;
+ break;
+
+ case BZ_SEQUENCE_ERROR:
+ PyErr_SetString(PyExc_RuntimeError,
+ "wrong sequence of bz2 library "
+ "commands used");
+ ret = 1;
+ break;
+ }
+ return ret;
}
#if BUFSIZ < 8192
@@ -218,228 +218,228 @@ Util_CatchBZ2Error(int bzerror)
static size_t
Util_NewBufferSize(size_t currentsize)
{
- if (currentsize > SMALLCHUNK) {
- /* Keep doubling until we reach BIGCHUNK;
- then keep adding BIGCHUNK. */
- if (currentsize <= BIGCHUNK)
- return currentsize + currentsize;
- else
- return currentsize + BIGCHUNK;
- }
- return currentsize + SMALLCHUNK;
+ if (currentsize > SMALLCHUNK) {
+ /* Keep doubling until we reach BIGCHUNK;
+ then keep adding BIGCHUNK. */
+ if (currentsize <= BIGCHUNK)
+ return currentsize + currentsize;
+ else
+ return currentsize + BIGCHUNK;
+ }
+ return currentsize + SMALLCHUNK;
}
/* This is a hacked version of Python's fileobject.c:get_line(). */
static PyObject *
Util_GetLine(BZ2FileObject *f, int n)
{
- char c;
- char *buf, *end;
- size_t total_v_size; /* total # of slots in buffer */
- size_t used_v_size; /* # used slots in buffer */
- size_t increment; /* amount to increment the buffer */
- PyObject *v;
- int bzerror;
- int bytes_read;
- int newlinetypes = f->f_newlinetypes;
- int skipnextlf = f->f_skipnextlf;
- int univ_newline = f->f_univ_newline;
-
- total_v_size = n > 0 ? n : 100;
- v = PyString_FromStringAndSize((char *)NULL, total_v_size);
- if (v == NULL)
- return NULL;
-
- buf = BUF(v);
- end = buf + total_v_size;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- while (buf != end) {
- bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
- f->pos++;
- if (bytes_read == 0) break;
- if (univ_newline) {
- if (skipnextlf) {
- skipnextlf = 0;
- if (c == '\n') {
- /* Seeing a \n here with skipnextlf true means we
- * saw a \r before.
- */
- newlinetypes |= NEWLINE_CRLF;
- if (bzerror != BZ_OK) break;
- bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
- f->pos++;
- if (bytes_read == 0) break;
- } else {
- newlinetypes |= NEWLINE_CR;
- }
- }
- if (c == '\r') {
- skipnextlf = 1;
- c = '\n';
- } else if (c == '\n')
- newlinetypes |= NEWLINE_LF;
- }
- *buf++ = c;
- if (bzerror != BZ_OK || c == '\n') break;
- }
- if (univ_newline && bzerror == BZ_STREAM_END && skipnextlf)
- newlinetypes |= NEWLINE_CR;
- Py_END_ALLOW_THREADS
- f->f_newlinetypes = newlinetypes;
- f->f_skipnextlf = skipnextlf;
- if (bzerror == BZ_STREAM_END) {
- f->size = f->pos;
- f->mode = MODE_READ_EOF;
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_DECREF(v);
- return NULL;
- }
- if (c == '\n')
- break;
- /* Must be because buf == end */
- if (n > 0)
- break;
- used_v_size = total_v_size;
- increment = total_v_size >> 2; /* mild exponential growth */
- total_v_size += increment;
- if (total_v_size > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- Py_DECREF(v);
- return NULL;
- }
- if (_PyString_Resize(&v, total_v_size) < 0)
- return NULL;
- buf = BUF(v) + used_v_size;
- end = BUF(v) + total_v_size;
- }
-
- used_v_size = buf - BUF(v);
- if (used_v_size != total_v_size)
- _PyString_Resize(&v, used_v_size);
- return v;
+ char c;
+ char *buf, *end;
+ size_t total_v_size; /* total # of slots in buffer */
+ size_t used_v_size; /* # used slots in buffer */
+ size_t increment; /* amount to increment the buffer */
+ PyObject *v;
+ int bzerror;
+ int bytes_read;
+ int newlinetypes = f->f_newlinetypes;
+ int skipnextlf = f->f_skipnextlf;
+ int univ_newline = f->f_univ_newline;
+
+ total_v_size = n > 0 ? n : 100;
+ v = PyString_FromStringAndSize((char *)NULL, total_v_size);
+ if (v == NULL)
+ return NULL;
+
+ buf = BUF(v);
+ end = buf + total_v_size;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ while (buf != end) {
+ bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
+ f->pos++;
+ if (bytes_read == 0) break;
+ if (univ_newline) {
+ if (skipnextlf) {
+ skipnextlf = 0;
+ if (c == '\n') {
+ /* Seeing a \n here with skipnextlf true means we
+ * saw a \r before.
+ */
+ newlinetypes |= NEWLINE_CRLF;
+ if (bzerror != BZ_OK) break;
+ bytes_read = BZ2_bzRead(&bzerror, f->fp, &c, 1);
+ f->pos++;
+ if (bytes_read == 0) break;
+ } else {
+ newlinetypes |= NEWLINE_CR;
+ }
+ }
+ if (c == '\r') {
+ skipnextlf = 1;
+ c = '\n';
+ } else if (c == '\n')
+ newlinetypes |= NEWLINE_LF;
+ }
+ *buf++ = c;
+ if (bzerror != BZ_OK || c == '\n') break;
+ }
+ if (univ_newline && bzerror == BZ_STREAM_END && skipnextlf)
+ newlinetypes |= NEWLINE_CR;
+ Py_END_ALLOW_THREADS
+ f->f_newlinetypes = newlinetypes;
+ f->f_skipnextlf = skipnextlf;
+ if (bzerror == BZ_STREAM_END) {
+ f->size = f->pos;
+ f->mode = MODE_READ_EOF;
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (c == '\n')
+ break;
+ /* Must be because buf == end */
+ if (n > 0)
+ break;
+ used_v_size = total_v_size;
+ increment = total_v_size >> 2; /* mild exponential growth */
+ total_v_size += increment;
+ if (total_v_size > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (_PyString_Resize(&v, total_v_size) < 0)
+ return NULL;
+ buf = BUF(v) + used_v_size;
+ end = BUF(v) + total_v_size;
+ }
+
+ used_v_size = buf - BUF(v);
+ if (used_v_size != total_v_size)
+ _PyString_Resize(&v, used_v_size);
+ return v;
}
/* This is a hacked version of Python's
* fileobject.c:Py_UniversalNewlineFread(). */
size_t
Util_UnivNewlineRead(int *bzerror, BZFILE *stream,
- char* buf, size_t n, BZ2FileObject *f)
+ char* buf, size_t n, BZ2FileObject *f)
{
- char *dst = buf;
- int newlinetypes, skipnextlf;
-
- assert(buf != NULL);
- assert(stream != NULL);
-
- if (!f->f_univ_newline)
- return BZ2_bzRead(bzerror, stream, buf, n);
-
- newlinetypes = f->f_newlinetypes;
- skipnextlf = f->f_skipnextlf;
-
- /* Invariant: n is the number of bytes remaining to be filled
- * in the buffer.
- */
- while (n) {
- size_t nread;
- int shortread;
- char *src = dst;
-
- nread = BZ2_bzRead(bzerror, stream, dst, n);
- assert(nread <= n);
- n -= nread; /* assuming 1 byte out for each in; will adjust */
- shortread = n != 0; /* true iff EOF or error */
- while (nread--) {
- char c = *src++;
- if (c == '\r') {
- /* Save as LF and set flag to skip next LF. */
- *dst++ = '\n';
- skipnextlf = 1;
- }
- else if (skipnextlf && c == '\n') {
- /* Skip LF, and remember we saw CR LF. */
- skipnextlf = 0;
- newlinetypes |= NEWLINE_CRLF;
- ++n;
- }
- else {
- /* Normal char to be stored in buffer. Also
- * update the newlinetypes flag if either this
- * is an LF or the previous char was a CR.
- */
- if (c == '\n')
- newlinetypes |= NEWLINE_LF;
- else if (skipnextlf)
- newlinetypes |= NEWLINE_CR;
- *dst++ = c;
- skipnextlf = 0;
- }
- }
- if (shortread) {
- /* If this is EOF, update type flags. */
- if (skipnextlf && *bzerror == BZ_STREAM_END)
- newlinetypes |= NEWLINE_CR;
- break;
- }
- }
- f->f_newlinetypes = newlinetypes;
- f->f_skipnextlf = skipnextlf;
- return dst - buf;
+ char *dst = buf;
+ int newlinetypes, skipnextlf;
+
+ assert(buf != NULL);
+ assert(stream != NULL);
+
+ if (!f->f_univ_newline)
+ return BZ2_bzRead(bzerror, stream, buf, n);
+
+ newlinetypes = f->f_newlinetypes;
+ skipnextlf = f->f_skipnextlf;
+
+ /* Invariant: n is the number of bytes remaining to be filled
+ * in the buffer.
+ */
+ while (n) {
+ size_t nread;
+ int shortread;
+ char *src = dst;
+
+ nread = BZ2_bzRead(bzerror, stream, dst, n);
+ assert(nread <= n);
+ n -= nread; /* assuming 1 byte out for each in; will adjust */
+ shortread = n != 0; /* true iff EOF or error */
+ while (nread--) {
+ char c = *src++;
+ if (c == '\r') {
+ /* Save as LF and set flag to skip next LF. */
+ *dst++ = '\n';
+ skipnextlf = 1;
+ }
+ else if (skipnextlf && c == '\n') {
+ /* Skip LF, and remember we saw CR LF. */
+ skipnextlf = 0;
+ newlinetypes |= NEWLINE_CRLF;
+ ++n;
+ }
+ else {
+ /* Normal char to be stored in buffer. Also
+ * update the newlinetypes flag if either this
+ * is an LF or the previous char was a CR.
+ */
+ if (c == '\n')
+ newlinetypes |= NEWLINE_LF;
+ else if (skipnextlf)
+ newlinetypes |= NEWLINE_CR;
+ *dst++ = c;
+ skipnextlf = 0;
+ }
+ }
+ if (shortread) {
+ /* If this is EOF, update type flags. */
+ if (skipnextlf && *bzerror == BZ_STREAM_END)
+ newlinetypes |= NEWLINE_CR;
+ break;
+ }
+ }
+ f->f_newlinetypes = newlinetypes;
+ f->f_skipnextlf = skipnextlf;
+ return dst - buf;
}
/* This is a hacked version of Python's fileobject.c:drop_readahead(). */
static void
Util_DropReadAhead(BZ2FileObject *f)
{
- if (f->f_buf != NULL) {
- PyMem_Free(f->f_buf);
- f->f_buf = NULL;
- }
+ if (f->f_buf != NULL) {
+ PyMem_Free(f->f_buf);
+ f->f_buf = NULL;
+ }
}
/* This is a hacked version of Python's fileobject.c:readahead(). */
static int
Util_ReadAhead(BZ2FileObject *f, int bufsize)
{
- int chunksize;
- int bzerror;
-
- if (f->f_buf != NULL) {
- if((f->f_bufend - f->f_bufptr) >= 1)
- return 0;
- else
- Util_DropReadAhead(f);
- }
- if (f->mode == MODE_READ_EOF) {
- f->f_bufptr = f->f_buf;
- f->f_bufend = f->f_buf;
- return 0;
- }
- if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- Py_BEGIN_ALLOW_THREADS
- chunksize = Util_UnivNewlineRead(&bzerror, f->fp, f->f_buf,
- bufsize, f);
- Py_END_ALLOW_THREADS
- f->pos += chunksize;
- if (bzerror == BZ_STREAM_END) {
- f->size = f->pos;
- f->mode = MODE_READ_EOF;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Util_DropReadAhead(f);
- return -1;
- }
- f->f_bufptr = f->f_buf;
- f->f_bufend = f->f_buf + chunksize;
- return 0;
+ int chunksize;
+ int bzerror;
+
+ if (f->f_buf != NULL) {
+ if((f->f_bufend - f->f_bufptr) >= 1)
+ return 0;
+ else
+ Util_DropReadAhead(f);
+ }
+ if (f->mode == MODE_READ_EOF) {
+ f->f_bufptr = f->f_buf;
+ f->f_bufend = f->f_buf;
+ return 0;
+ }
+ if ((f->f_buf = PyMem_Malloc(bufsize)) == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = Util_UnivNewlineRead(&bzerror, f->fp, f->f_buf,
+ bufsize, f);
+ Py_END_ALLOW_THREADS
+ f->pos += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ f->size = f->pos;
+ f->mode = MODE_READ_EOF;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Util_DropReadAhead(f);
+ return -1;
+ }
+ f->f_bufptr = f->f_buf;
+ f->f_bufend = f->f_buf + chunksize;
+ return 0;
}
/* This is a hacked version of Python's
@@ -447,45 +447,45 @@ Util_ReadAhead(BZ2FileObject *f, int bufsize)
static PyStringObject *
Util_ReadAheadGetLineSkip(BZ2FileObject *f, int skip, int bufsize)
{
- PyStringObject* s;
- char *bufptr;
- char *buf;
- int len;
-
- if (f->f_buf == NULL)
- if (Util_ReadAhead(f, bufsize) < 0)
- return NULL;
-
- len = f->f_bufend - f->f_bufptr;
- if (len == 0)
- return (PyStringObject *)
- PyString_FromStringAndSize(NULL, skip);
- bufptr = memchr(f->f_bufptr, '\n', len);
- if (bufptr != NULL) {
- bufptr++; /* Count the '\n' */
- len = bufptr - f->f_bufptr;
- s = (PyStringObject *)
- PyString_FromStringAndSize(NULL, skip+len);
- if (s == NULL)
- return NULL;
- memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
- f->f_bufptr = bufptr;
- if (bufptr == f->f_bufend)
- Util_DropReadAhead(f);
- } else {
- bufptr = f->f_bufptr;
- buf = f->f_buf;
- f->f_buf = NULL; /* Force new readahead buffer */
- s = Util_ReadAheadGetLineSkip(f, skip+len,
- bufsize + (bufsize>>2));
- if (s == NULL) {
- PyMem_Free(buf);
- return NULL;
- }
- memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
- PyMem_Free(buf);
- }
- return s;
+ PyStringObject* s;
+ char *bufptr;
+ char *buf;
+ int len;
+
+ if (f->f_buf == NULL)
+ if (Util_ReadAhead(f, bufsize) < 0)
+ return NULL;
+
+ len = f->f_bufend - f->f_bufptr;
+ if (len == 0)
+ return (PyStringObject *)
+ PyString_FromStringAndSize(NULL, skip);
+ bufptr = memchr(f->f_bufptr, '\n', len);
+ if (bufptr != NULL) {
+ bufptr++; /* Count the '\n' */
+ len = bufptr - f->f_bufptr;
+ s = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, skip+len);
+ if (s == NULL)
+ return NULL;
+ memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
+ f->f_bufptr = bufptr;
+ if (bufptr == f->f_bufend)
+ Util_DropReadAhead(f);
+ } else {
+ bufptr = f->f_bufptr;
+ buf = f->f_buf;
+ f->f_buf = NULL; /* Force new readahead buffer */
+ s = Util_ReadAheadGetLineSkip(f, skip+len,
+ bufsize + (bufsize>>2));
+ if (s == NULL) {
+ PyMem_Free(buf);
+ return NULL;
+ }
+ memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
+ PyMem_Free(buf);
+ }
+ return s;
}
/* ===================================================================== */
@@ -502,79 +502,79 @@ argument is negative or omitted, read until EOF is reached.\n\
static PyObject *
BZ2File_read(BZ2FileObject *self, PyObject *args)
{
- long bytesrequested = -1;
- size_t bytesread, buffersize, chunksize;
- int bzerror;
- PyObject *ret = NULL;
-
- if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
- return NULL;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- break;
- case MODE_READ_EOF:
- ret = PyString_FromString("");
- goto cleanup;
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for reading");
- goto cleanup;
- }
-
- if (bytesrequested < 0)
- buffersize = Util_NewBufferSize((size_t)0);
- else
- buffersize = bytesrequested;
- if (buffersize > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "requested number of bytes is "
- "more than a Python string can hold");
- goto cleanup;
- }
- ret = PyString_FromStringAndSize((char *)NULL, buffersize);
- if (ret == NULL)
- goto cleanup;
- bytesread = 0;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- chunksize = Util_UnivNewlineRead(&bzerror, self->fp,
- BUF(ret)+bytesread,
- buffersize-bytesread,
- self);
- self->pos += chunksize;
- Py_END_ALLOW_THREADS
- bytesread += chunksize;
- if (bzerror == BZ_STREAM_END) {
- self->size = self->pos;
- self->mode = MODE_READ_EOF;
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_DECREF(ret);
- ret = NULL;
- goto cleanup;
- }
- if (bytesrequested < 0) {
- buffersize = Util_NewBufferSize(buffersize);
- if (_PyString_Resize(&ret, buffersize) < 0)
- goto cleanup;
- } else {
- break;
- }
- }
- if (bytesread != buffersize)
- _PyString_Resize(&ret, bytesread);
+ long bytesrequested = -1;
+ size_t bytesread, buffersize, chunksize;
+ int bzerror;
+ PyObject *ret = NULL;
+
+ if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ break;
+ case MODE_READ_EOF:
+ ret = PyString_FromString("");
+ goto cleanup;
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for reading");
+ goto cleanup;
+ }
+
+ if (bytesrequested < 0)
+ buffersize = Util_NewBufferSize((size_t)0);
+ else
+ buffersize = bytesrequested;
+ if (buffersize > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "requested number of bytes is "
+ "more than a Python string can hold");
+ goto cleanup;
+ }
+ ret = PyString_FromStringAndSize((char *)NULL, buffersize);
+ if (ret == NULL)
+ goto cleanup;
+ bytesread = 0;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = Util_UnivNewlineRead(&bzerror, self->fp,
+ BUF(ret)+bytesread,
+ buffersize-bytesread,
+ self);
+ self->pos += chunksize;
+ Py_END_ALLOW_THREADS
+ bytesread += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ self->size = self->pos;
+ self->mode = MODE_READ_EOF;
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_DECREF(ret);
+ ret = NULL;
+ goto cleanup;
+ }
+ if (bytesrequested < 0) {
+ buffersize = Util_NewBufferSize(buffersize);
+ if (_PyString_Resize(&ret, buffersize) < 0)
+ goto cleanup;
+ } else {
+ break;
+ }
+ }
+ if (bytesread != buffersize)
+ _PyString_Resize(&ret, bytesread);
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_readline__doc__,
@@ -589,37 +589,37 @@ string at EOF.\n\
static PyObject *
BZ2File_readline(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = NULL;
- int sizehint = -1;
-
- if (!PyArg_ParseTuple(args, "|i:readline", &sizehint))
- return NULL;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- break;
- case MODE_READ_EOF:
- ret = PyString_FromString("");
- goto cleanup;
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for reading");
- goto cleanup;
- }
-
- if (sizehint == 0)
- ret = PyString_FromString("");
- else
- ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint);
+ PyObject *ret = NULL;
+ int sizehint = -1;
+
+ if (!PyArg_ParseTuple(args, "|i:readline", &sizehint))
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ break;
+ case MODE_READ_EOF:
+ ret = PyString_FromString("");
+ goto cleanup;
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for reading");
+ goto cleanup;
+ }
+
+ if (sizehint == 0)
+ ret = PyString_FromString("");
+ else
+ ret = Util_GetLine(self, (sizehint < 0) ? 0 : sizehint);
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_readlines__doc__,
@@ -634,148 +634,148 @@ total number of bytes in the lines returned.\n\
static PyObject *
BZ2File_readlines(BZ2FileObject *self, PyObject *args)
{
- long sizehint = 0;
- PyObject *list = NULL;
- PyObject *line;
- char small_buffer[SMALLCHUNK];
- char *buffer = small_buffer;
- size_t buffersize = SMALLCHUNK;
- PyObject *big_buffer = NULL;
- size_t nfilled = 0;
- size_t nread;
- size_t totalread = 0;
- char *p, *q, *end;
- int err;
- int shortread = 0;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
- return NULL;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- break;
- case MODE_READ_EOF:
- list = PyList_New(0);
- goto cleanup;
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for reading");
- goto cleanup;
- }
-
- if ((list = PyList_New(0)) == NULL)
- goto cleanup;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- nread = Util_UnivNewlineRead(&bzerror, self->fp,
- buffer+nfilled,
- buffersize-nfilled, self);
- self->pos += nread;
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- self->size = self->pos;
- self->mode = MODE_READ_EOF;
- if (nread == 0) {
- sizehint = 0;
- break;
- }
- shortread = 1;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- error:
- Py_DECREF(list);
- list = NULL;
- goto cleanup;
- }
- totalread += nread;
- p = memchr(buffer+nfilled, '\n', nread);
- if (!shortread && p == NULL) {
- /* Need a larger buffer to fit this line */
- nfilled += nread;
- buffersize *= 2;
- if (buffersize > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- goto error;
- }
- if (big_buffer == NULL) {
- /* Create the big buffer */
- big_buffer = PyString_FromStringAndSize(
- NULL, buffersize);
- if (big_buffer == NULL)
- goto error;
- buffer = PyString_AS_STRING(big_buffer);
- memcpy(buffer, small_buffer, nfilled);
- }
- else {
- /* Grow the big buffer */
- _PyString_Resize(&big_buffer, buffersize);
- buffer = PyString_AS_STRING(big_buffer);
- }
- continue;
- }
- end = buffer+nfilled+nread;
- q = buffer;
- while (p != NULL) {
- /* Process complete lines */
- p++;
- line = PyString_FromStringAndSize(q, p-q);
- if (line == NULL)
- goto error;
- err = PyList_Append(list, line);
- Py_DECREF(line);
- if (err != 0)
- goto error;
- q = p;
- p = memchr(q, '\n', end-q);
- }
- /* Move the remaining incomplete line to the start */
- nfilled = end-q;
- memmove(buffer, q, nfilled);
- if (sizehint > 0)
- if (totalread >= (size_t)sizehint)
- break;
- if (shortread) {
- sizehint = 0;
- break;
- }
- }
- if (nfilled != 0) {
- /* Partial last line */
- line = PyString_FromStringAndSize(buffer, nfilled);
- if (line == NULL)
- goto error;
- if (sizehint > 0) {
- /* Need to complete the last line */
- PyObject *rest = Util_GetLine(self, 0);
- if (rest == NULL) {
- Py_DECREF(line);
- goto error;
- }
- PyString_Concat(&line, rest);
- Py_DECREF(rest);
- if (line == NULL)
- goto error;
- }
- err = PyList_Append(list, line);
- Py_DECREF(line);
- if (err != 0)
- goto error;
- }
+ long sizehint = 0;
+ PyObject *list = NULL;
+ PyObject *line;
+ char small_buffer[SMALLCHUNK];
+ char *buffer = small_buffer;
+ size_t buffersize = SMALLCHUNK;
+ PyObject *big_buffer = NULL;
+ size_t nfilled = 0;
+ size_t nread;
+ size_t totalread = 0;
+ char *p, *q, *end;
+ int err;
+ int shortread = 0;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ break;
+ case MODE_READ_EOF:
+ list = PyList_New(0);
+ goto cleanup;
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for reading");
+ goto cleanup;
+ }
+
+ if ((list = PyList_New(0)) == NULL)
+ goto cleanup;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ nread = Util_UnivNewlineRead(&bzerror, self->fp,
+ buffer+nfilled,
+ buffersize-nfilled, self);
+ self->pos += nread;
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ self->size = self->pos;
+ self->mode = MODE_READ_EOF;
+ if (nread == 0) {
+ sizehint = 0;
+ break;
+ }
+ shortread = 1;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ error:
+ Py_DECREF(list);
+ list = NULL;
+ goto cleanup;
+ }
+ totalread += nread;
+ p = memchr(buffer+nfilled, '\n', nread);
+ if (!shortread && p == NULL) {
+ /* Need a larger buffer to fit this line */
+ nfilled += nread;
+ buffersize *= 2;
+ if (buffersize > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ goto error;
+ }
+ if (big_buffer == NULL) {
+ /* Create the big buffer */
+ big_buffer = PyString_FromStringAndSize(
+ NULL, buffersize);
+ if (big_buffer == NULL)
+ goto error;
+ buffer = PyString_AS_STRING(big_buffer);
+ memcpy(buffer, small_buffer, nfilled);
+ }
+ else {
+ /* Grow the big buffer */
+ _PyString_Resize(&big_buffer, buffersize);
+ buffer = PyString_AS_STRING(big_buffer);
+ }
+ continue;
+ }
+ end = buffer+nfilled+nread;
+ q = buffer;
+ while (p != NULL) {
+ /* Process complete lines */
+ p++;
+ line = PyString_FromStringAndSize(q, p-q);
+ if (line == NULL)
+ goto error;
+ err = PyList_Append(list, line);
+ Py_DECREF(line);
+ if (err != 0)
+ goto error;
+ q = p;
+ p = memchr(q, '\n', end-q);
+ }
+ /* Move the remaining incomplete line to the start */
+ nfilled = end-q;
+ memmove(buffer, q, nfilled);
+ if (sizehint > 0)
+ if (totalread >= (size_t)sizehint)
+ break;
+ if (shortread) {
+ sizehint = 0;
+ break;
+ }
+ }
+ if (nfilled != 0) {
+ /* Partial last line */
+ line = PyString_FromStringAndSize(buffer, nfilled);
+ if (line == NULL)
+ goto error;
+ if (sizehint > 0) {
+ /* Need to complete the last line */
+ PyObject *rest = Util_GetLine(self, 0);
+ if (rest == NULL) {
+ Py_DECREF(line);
+ goto error;
+ }
+ PyString_Concat(&line, rest);
+ Py_DECREF(rest);
+ if (line == NULL)
+ goto error;
+ }
+ err = PyList_Append(list, line);
+ Py_DECREF(line);
+ if (err != 0)
+ goto error;
+ }
cleanup:
- RELEASE_LOCK(self);
- if (big_buffer) {
- Py_DECREF(big_buffer);
- }
- return list;
+ RELEASE_LOCK(self);
+ if (big_buffer) {
+ Py_DECREF(big_buffer);
+ }
+ return list;
}
PyDoc_STRVAR(BZ2File_xreadlines__doc__,
@@ -796,52 +796,52 @@ be needed before the file on disk reflects the data written.\n\
static PyObject *
BZ2File_write(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = NULL;
- Py_buffer pbuf;
- char *buf;
- int len;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "s*:write", &pbuf))
- return NULL;
- buf = pbuf.buf;
- len = pbuf.len;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_WRITE:
- break;
-
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
-
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for writing");
- goto cleanup;
- }
-
- self->f_softspace = 0;
-
- Py_BEGIN_ALLOW_THREADS
- BZ2_bzWrite (&bzerror, self->fp, buf, len);
- self->pos += len;
- Py_END_ALLOW_THREADS
-
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
-
- Py_INCREF(Py_None);
- ret = Py_None;
+ PyObject *ret = NULL;
+ Py_buffer pbuf;
+ char *buf;
+ int len;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "s*:write", &pbuf))
+ return NULL;
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_WRITE:
+ break;
+
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for writing");
+ goto cleanup;
+ }
+
+ self->f_softspace = 0;
+
+ Py_BEGIN_ALLOW_THREADS
+ BZ2_bzWrite (&bzerror, self->fp, buf, len);
+ self->pos += len;
+ Py_END_ALLOW_THREADS
+
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+
+ Py_INCREF(Py_None);
+ ret = Py_None;
cleanup:
- PyBuffer_Release(&pbuf);
- RELEASE_LOCK(self);
- return ret;
+ PyBuffer_Release(&pbuf);
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_writelines__doc__,
@@ -857,124 +857,124 @@ static PyObject *
BZ2File_writelines(BZ2FileObject *self, PyObject *seq)
{
#define CHUNKSIZE 1000
- PyObject *list = NULL;
- PyObject *iter = NULL;
- PyObject *ret = NULL;
- PyObject *line;
- int i, j, index, len, islist;
- int bzerror;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_WRITE:
- break;
-
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto error;
-
- default:
- PyErr_SetString(PyExc_IOError,
- "file is not ready for writing");
- goto error;
- }
-
- islist = PyList_Check(seq);
- if (!islist) {
- iter = PyObject_GetIter(seq);
- if (iter == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "writelines() requires an iterable argument");
- goto error;
- }
- list = PyList_New(CHUNKSIZE);
- if (list == NULL)
- goto error;
- }
-
- /* Strategy: slurp CHUNKSIZE lines into a private list,
- checking that they are all strings, then write that list
- without holding the interpreter lock, then come back for more. */
- for (index = 0; ; index += CHUNKSIZE) {
- if (islist) {
- Py_XDECREF(list);
- list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
- if (list == NULL)
- goto error;
- j = PyList_GET_SIZE(list);
- }
- else {
- for (j = 0; j < CHUNKSIZE; j++) {
- line = PyIter_Next(iter);
- if (line == NULL) {
- if (PyErr_Occurred())
- goto error;
- break;
- }
- PyList_SetItem(list, j, line);
- }
- }
- if (j == 0)
- break;
-
- /* Check that all entries are indeed strings. If not,
- apply the same rules as for file.write() and
- convert the rets to strings. This is slow, but
- seems to be the only way since all conversion APIs
- could potentially execute Python code. */
- for (i = 0; i < j; i++) {
- PyObject *v = PyList_GET_ITEM(list, i);
- if (!PyString_Check(v)) {
- const char *buffer;
- Py_ssize_t len;
- if (PyObject_AsCharBuffer(v, &buffer, &len)) {
- PyErr_SetString(PyExc_TypeError,
- "writelines() "
- "argument must be "
- "a sequence of "
- "strings");
- goto error;
- }
- line = PyString_FromStringAndSize(buffer,
- len);
- if (line == NULL)
- goto error;
- Py_DECREF(v);
- PyList_SET_ITEM(list, i, line);
- }
- }
-
- self->f_softspace = 0;
-
- /* Since we are releasing the global lock, the
- following code may *not* execute Python code. */
- Py_BEGIN_ALLOW_THREADS
- for (i = 0; i < j; i++) {
- line = PyList_GET_ITEM(list, i);
- len = PyString_GET_SIZE(line);
- BZ2_bzWrite (&bzerror, self->fp,
- PyString_AS_STRING(line), len);
- if (bzerror != BZ_OK) {
- Py_BLOCK_THREADS
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- }
- Py_END_ALLOW_THREADS
-
- if (j < CHUNKSIZE)
- break;
- }
-
- Py_INCREF(Py_None);
- ret = Py_None;
+ PyObject *list = NULL;
+ PyObject *iter = NULL;
+ PyObject *ret = NULL;
+ PyObject *line;
+ int i, j, index, len, islist;
+ int bzerror;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_WRITE:
+ break;
+
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto error;
+
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "file is not ready for writing");
+ goto error;
+ }
+
+ islist = PyList_Check(seq);
+ if (!islist) {
+ iter = PyObject_GetIter(seq);
+ if (iter == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "writelines() requires an iterable argument");
+ goto error;
+ }
+ list = PyList_New(CHUNKSIZE);
+ if (list == NULL)
+ goto error;
+ }
+
+ /* Strategy: slurp CHUNKSIZE lines into a private list,
+ checking that they are all strings, then write that list
+ without holding the interpreter lock, then come back for more. */
+ for (index = 0; ; index += CHUNKSIZE) {
+ if (islist) {
+ Py_XDECREF(list);
+ list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
+ if (list == NULL)
+ goto error;
+ j = PyList_GET_SIZE(list);
+ }
+ else {
+ for (j = 0; j < CHUNKSIZE; j++) {
+ line = PyIter_Next(iter);
+ if (line == NULL) {
+ if (PyErr_Occurred())
+ goto error;
+ break;
+ }
+ PyList_SetItem(list, j, line);
+ }
+ }
+ if (j == 0)
+ break;
+
+ /* Check that all entries are indeed strings. If not,
+ apply the same rules as for file.write() and
+ convert the rets to strings. This is slow, but
+ seems to be the only way since all conversion APIs
+ could potentially execute Python code. */
+ for (i = 0; i < j; i++) {
+ PyObject *v = PyList_GET_ITEM(list, i);
+ if (!PyString_Check(v)) {
+ const char *buffer;
+ Py_ssize_t len;
+ if (PyObject_AsCharBuffer(v, &buffer, &len)) {
+ PyErr_SetString(PyExc_TypeError,
+ "writelines() "
+ "argument must be "
+ "a sequence of "
+ "strings");
+ goto error;
+ }
+ line = PyString_FromStringAndSize(buffer,
+ len);
+ if (line == NULL)
+ goto error;
+ Py_DECREF(v);
+ PyList_SET_ITEM(list, i, line);
+ }
+ }
+
+ self->f_softspace = 0;
+
+ /* Since we are releasing the global lock, the
+ following code may *not* execute Python code. */
+ Py_BEGIN_ALLOW_THREADS
+ for (i = 0; i < j; i++) {
+ line = PyList_GET_ITEM(list, i);
+ len = PyString_GET_SIZE(line);
+ BZ2_bzWrite (&bzerror, self->fp,
+ PyString_AS_STRING(line), len);
+ if (bzerror != BZ_OK) {
+ Py_BLOCK_THREADS
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ }
+ Py_END_ALLOW_THREADS
+
+ if (j < CHUNKSIZE)
+ break;
+ }
+
+ Py_INCREF(Py_None);
+ ret = Py_None;
error:
- RELEASE_LOCK(self);
- Py_XDECREF(list);
- Py_XDECREF(iter);
- return ret;
+ RELEASE_LOCK(self);
+ Py_XDECREF(list);
+ Py_XDECREF(iter);
+ return ret;
#undef CHUNKSIZE
}
@@ -994,148 +994,148 @@ the operation may be extremely slow.\n\
static PyObject *
BZ2File_seek(BZ2FileObject *self, PyObject *args)
{
- int where = 0;
- PyObject *offobj;
- Py_off_t offset;
- char small_buffer[SMALLCHUNK];
- char *buffer = small_buffer;
- size_t buffersize = SMALLCHUNK;
- Py_off_t bytesread = 0;
- size_t readsize;
- int chunksize;
- int bzerror;
- PyObject *ret = NULL;
-
- if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where))
- return NULL;
+ int where = 0;
+ PyObject *offobj;
+ Py_off_t offset;
+ char small_buffer[SMALLCHUNK];
+ char *buffer = small_buffer;
+ size_t buffersize = SMALLCHUNK;
+ Py_off_t bytesread = 0;
+ size_t readsize;
+ int chunksize;
+ int bzerror;
+ PyObject *ret = NULL;
+
+ if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &where))
+ return NULL;
#if !defined(HAVE_LARGEFILE_SUPPORT)
- offset = PyInt_AsLong(offobj);
+ offset = PyInt_AsLong(offobj);
#else
- offset = PyLong_Check(offobj) ?
- PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
+ offset = PyLong_Check(offobj) ?
+ PyLong_AsLongLong(offobj) : PyInt_AsLong(offobj);
#endif
- if (PyErr_Occurred())
- return NULL;
-
- ACQUIRE_LOCK(self);
- Util_DropReadAhead(self);
- switch (self->mode) {
- case MODE_READ:
- case MODE_READ_EOF:
- break;
-
- case MODE_CLOSED:
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
-
- default:
- PyErr_SetString(PyExc_IOError,
- "seek works only while reading");
- goto cleanup;
- }
-
- if (where == 2) {
- if (self->size == -1) {
- assert(self->mode != MODE_READ_EOF);
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- chunksize = Util_UnivNewlineRead(
- &bzerror, self->fp,
- buffer, buffersize,
- self);
- self->pos += chunksize;
- Py_END_ALLOW_THREADS
-
- bytesread += chunksize;
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- }
- self->mode = MODE_READ_EOF;
- self->size = self->pos;
- bytesread = 0;
- }
- offset = self->size + offset;
- } else if (where == 1) {
- offset = self->pos + offset;
- }
-
- /* Before getting here, offset must be the absolute position the file
- * pointer should be set to. */
-
- if (offset >= self->pos) {
- /* we can move forward */
- offset -= self->pos;
- } else {
- /* we cannot move back, so rewind the stream */
- BZ2_bzReadClose(&bzerror, self->fp);
- if (self->fp) {
- PyFile_DecUseCount((PyFileObject *)self->file);
- self->fp = NULL;
- }
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- ret = PyObject_CallMethod(self->file, "seek", "(i)", 0);
- if (!ret)
- goto cleanup;
- Py_DECREF(ret);
- ret = NULL;
- self->pos = 0;
- self->fp = BZ2_bzReadOpen(&bzerror, PyFile_AsFile(self->file),
- 0, 0, NULL, 0);
- if (self->fp)
- PyFile_IncUseCount((PyFileObject *)self->file);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- self->mode = MODE_READ;
- }
-
- if (offset <= 0 || self->mode == MODE_READ_EOF)
- goto exit;
-
- /* Before getting here, offset must be set to the number of bytes
- * to walk forward. */
- for (;;) {
- if (offset-bytesread > buffersize)
- readsize = buffersize;
- else
- /* offset might be wider that readsize, but the result
- * of the subtraction is bound by buffersize (see the
- * condition above). buffersize is 8192. */
- readsize = (size_t)(offset-bytesread);
- Py_BEGIN_ALLOW_THREADS
- chunksize = Util_UnivNewlineRead(&bzerror, self->fp,
- buffer, readsize, self);
- self->pos += chunksize;
- Py_END_ALLOW_THREADS
- bytesread += chunksize;
- if (bzerror == BZ_STREAM_END) {
- self->size = self->pos;
- self->mode = MODE_READ_EOF;
- break;
- } else if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto cleanup;
- }
- if (bytesread == offset)
- break;
- }
+ if (PyErr_Occurred())
+ return NULL;
+
+ ACQUIRE_LOCK(self);
+ Util_DropReadAhead(self);
+ switch (self->mode) {
+ case MODE_READ:
+ case MODE_READ_EOF:
+ break;
+
+ case MODE_CLOSED:
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+
+ default:
+ PyErr_SetString(PyExc_IOError,
+ "seek works only while reading");
+ goto cleanup;
+ }
+
+ if (where == 2) {
+ if (self->size == -1) {
+ assert(self->mode != MODE_READ_EOF);
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = Util_UnivNewlineRead(
+ &bzerror, self->fp,
+ buffer, buffersize,
+ self);
+ self->pos += chunksize;
+ Py_END_ALLOW_THREADS
+
+ bytesread += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ }
+ self->mode = MODE_READ_EOF;
+ self->size = self->pos;
+ bytesread = 0;
+ }
+ offset = self->size + offset;
+ } else if (where == 1) {
+ offset = self->pos + offset;
+ }
+
+ /* Before getting here, offset must be the absolute position the file
+ * pointer should be set to. */
+
+ if (offset >= self->pos) {
+ /* we can move forward */
+ offset -= self->pos;
+ } else {
+ /* we cannot move back, so rewind the stream */
+ BZ2_bzReadClose(&bzerror, self->fp);
+ if (self->fp) {
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ self->fp = NULL;
+ }
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ ret = PyObject_CallMethod(self->file, "seek", "(i)", 0);
+ if (!ret)
+ goto cleanup;
+ Py_DECREF(ret);
+ ret = NULL;
+ self->pos = 0;
+ self->fp = BZ2_bzReadOpen(&bzerror, PyFile_AsFile(self->file),
+ 0, 0, NULL, 0);
+ if (self->fp)
+ PyFile_IncUseCount((PyFileObject *)self->file);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ self->mode = MODE_READ;
+ }
+
+ if (offset <= 0 || self->mode == MODE_READ_EOF)
+ goto exit;
+
+ /* Before getting here, offset must be set to the number of bytes
+ * to walk forward. */
+ for (;;) {
+ if (offset-bytesread > buffersize)
+ readsize = buffersize;
+ else
+ /* offset might be wider that readsize, but the result
+ * of the subtraction is bound by buffersize (see the
+ * condition above). buffersize is 8192. */
+ readsize = (size_t)(offset-bytesread);
+ Py_BEGIN_ALLOW_THREADS
+ chunksize = Util_UnivNewlineRead(&bzerror, self->fp,
+ buffer, readsize, self);
+ self->pos += chunksize;
+ Py_END_ALLOW_THREADS
+ bytesread += chunksize;
+ if (bzerror == BZ_STREAM_END) {
+ self->size = self->pos;
+ self->mode = MODE_READ_EOF;
+ break;
+ } else if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto cleanup;
+ }
+ if (bytesread == offset)
+ break;
+ }
exit:
- Py_INCREF(Py_None);
- ret = Py_None;
+ Py_INCREF(Py_None);
+ ret = Py_None;
cleanup:
- RELEASE_LOCK(self);
- return ret;
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_tell__doc__,
@@ -1147,22 +1147,22 @@ Return the current file position, an integer (may be a long integer).\n\
static PyObject *
BZ2File_tell(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = NULL;
+ PyObject *ret = NULL;
- if (self->mode == MODE_CLOSED) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto cleanup;
- }
+ if (self->mode == MODE_CLOSED) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto cleanup;
+ }
#if !defined(HAVE_LARGEFILE_SUPPORT)
- ret = PyInt_FromLong(self->pos);
+ ret = PyInt_FromLong(self->pos);
#else
- ret = PyLong_FromLongLong(self->pos);
+ ret = PyLong_FromLongLong(self->pos);
#endif
cleanup:
- return ret;
+ return ret;
}
PyDoc_STRVAR(BZ2File_close__doc__,
@@ -1176,34 +1176,34 @@ than once without error.\n\
static PyObject *
BZ2File_close(BZ2FileObject *self)
{
- PyObject *ret = NULL;
- int bzerror = BZ_OK;
-
- ACQUIRE_LOCK(self);
- switch (self->mode) {
- case MODE_READ:
- case MODE_READ_EOF:
- BZ2_bzReadClose(&bzerror, self->fp);
- break;
- case MODE_WRITE:
- BZ2_bzWriteClose(&bzerror, self->fp,
- 0, NULL, NULL);
- break;
- }
- if (self->fp) {
- PyFile_DecUseCount((PyFileObject *)self->file);
- self->fp = NULL;
- }
- self->mode = MODE_CLOSED;
- ret = PyObject_CallMethod(self->file, "close", NULL);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_XDECREF(ret);
- ret = NULL;
- }
-
- RELEASE_LOCK(self);
- return ret;
+ PyObject *ret = NULL;
+ int bzerror = BZ_OK;
+
+ ACQUIRE_LOCK(self);
+ switch (self->mode) {
+ case MODE_READ:
+ case MODE_READ_EOF:
+ BZ2_bzReadClose(&bzerror, self->fp);
+ break;
+ case MODE_WRITE:
+ BZ2_bzWriteClose(&bzerror, self->fp,
+ 0, NULL, NULL);
+ break;
+ }
+ if (self->fp) {
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ self->fp = NULL;
+ }
+ self->mode = MODE_CLOSED;
+ ret = PyObject_CallMethod(self->file, "close", NULL);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_XDECREF(ret);
+ ret = NULL;
+ }
+
+ RELEASE_LOCK(self);
+ return ret;
}
PyDoc_STRVAR(BZ2File_enter_doc,
@@ -1212,13 +1212,13 @@ PyDoc_STRVAR(BZ2File_enter_doc,
static PyObject *
BZ2File_enter(BZ2FileObject *self)
{
- if (self->mode == MODE_CLOSED) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return NULL;
- }
- Py_INCREF(self);
- return (PyObject *) self;
+ if (self->mode == MODE_CLOSED) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return NULL;
+ }
+ Py_INCREF(self);
+ return (PyObject *) self;
}
PyDoc_STRVAR(BZ2File_exit_doc,
@@ -1227,30 +1227,30 @@ PyDoc_STRVAR(BZ2File_exit_doc,
static PyObject *
BZ2File_exit(BZ2FileObject *self, PyObject *args)
{
- PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL);
- if (!ret)
- /* If error occurred, pass through */
- return NULL;
- Py_DECREF(ret);
- Py_RETURN_NONE;
+ PyObject *ret = PyObject_CallMethod((PyObject *) self, "close", NULL);
+ if (!ret)
+ /* If error occurred, pass through */
+ return NULL;
+ Py_DECREF(ret);
+ Py_RETURN_NONE;
}
static PyObject *BZ2File_getiter(BZ2FileObject *self);
static PyMethodDef BZ2File_methods[] = {
- {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__},
- {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__},
- {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__},
- {"xreadlines", (PyCFunction)BZ2File_getiter, METH_VARARGS, BZ2File_xreadlines__doc__},
- {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__},
- {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__},
- {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__},
- {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__},
- {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__},
- {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc},
- {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc},
- {NULL, NULL} /* sentinel */
+ {"read", (PyCFunction)BZ2File_read, METH_VARARGS, BZ2File_read__doc__},
+ {"readline", (PyCFunction)BZ2File_readline, METH_VARARGS, BZ2File_readline__doc__},
+ {"readlines", (PyCFunction)BZ2File_readlines, METH_VARARGS, BZ2File_readlines__doc__},
+ {"xreadlines", (PyCFunction)BZ2File_getiter, METH_VARARGS, BZ2File_xreadlines__doc__},
+ {"write", (PyCFunction)BZ2File_write, METH_VARARGS, BZ2File_write__doc__},
+ {"writelines", (PyCFunction)BZ2File_writelines, METH_O, BZ2File_writelines__doc__},
+ {"seek", (PyCFunction)BZ2File_seek, METH_VARARGS, BZ2File_seek__doc__},
+ {"tell", (PyCFunction)BZ2File_tell, METH_NOARGS, BZ2File_tell__doc__},
+ {"close", (PyCFunction)BZ2File_close, METH_NOARGS, BZ2File_close__doc__},
+ {"__enter__", (PyCFunction)BZ2File_enter, METH_NOARGS, BZ2File_enter_doc},
+ {"__exit__", (PyCFunction)BZ2File_exit, METH_VARARGS, BZ2File_exit_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1261,60 +1261,60 @@ static PyMethodDef BZ2File_methods[] = {
static PyObject *
BZ2File_get_newlines(BZ2FileObject *self, void *closure)
{
- switch (self->f_newlinetypes) {
- case NEWLINE_UNKNOWN:
- Py_INCREF(Py_None);
- return Py_None;
- case NEWLINE_CR:
- return PyString_FromString("\r");
- case NEWLINE_LF:
- return PyString_FromString("\n");
- case NEWLINE_CR|NEWLINE_LF:
- return Py_BuildValue("(ss)", "\r", "\n");
- case NEWLINE_CRLF:
- return PyString_FromString("\r\n");
- case NEWLINE_CR|NEWLINE_CRLF:
- return Py_BuildValue("(ss)", "\r", "\r\n");
- case NEWLINE_LF|NEWLINE_CRLF:
- return Py_BuildValue("(ss)", "\n", "\r\n");
- case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
- return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
- default:
- PyErr_Format(PyExc_SystemError,
- "Unknown newlines value 0x%x\n",
- self->f_newlinetypes);
- return NULL;
- }
+ switch (self->f_newlinetypes) {
+ case NEWLINE_UNKNOWN:
+ Py_INCREF(Py_None);
+ return Py_None;
+ case NEWLINE_CR:
+ return PyString_FromString("\r");
+ case NEWLINE_LF:
+ return PyString_FromString("\n");
+ case NEWLINE_CR|NEWLINE_LF:
+ return Py_BuildValue("(ss)", "\r", "\n");
+ case NEWLINE_CRLF:
+ return PyString_FromString("\r\n");
+ case NEWLINE_CR|NEWLINE_CRLF:
+ return Py_BuildValue("(ss)", "\r", "\r\n");
+ case NEWLINE_LF|NEWLINE_CRLF:
+ return Py_BuildValue("(ss)", "\n", "\r\n");
+ case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
+ return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "Unknown newlines value 0x%x\n",
+ self->f_newlinetypes);
+ return NULL;
+ }
}
static PyObject *
BZ2File_get_closed(BZ2FileObject *self, void *closure)
{
- return PyInt_FromLong(self->mode == MODE_CLOSED);
+ return PyInt_FromLong(self->mode == MODE_CLOSED);
}
static PyObject *
BZ2File_get_mode(BZ2FileObject *self, void *closure)
{
- return PyObject_GetAttrString(self->file, "mode");
+ return PyObject_GetAttrString(self->file, "mode");
}
static PyObject *
BZ2File_get_name(BZ2FileObject *self, void *closure)
{
- return PyObject_GetAttrString(self->file, "name");
+ return PyObject_GetAttrString(self->file, "name");
}
static PyGetSetDef BZ2File_getset[] = {
- {"closed", (getter)BZ2File_get_closed, NULL,
- "True if the file is closed"},
- {"newlines", (getter)BZ2File_get_newlines, NULL,
- "end-of-line convention used in this file"},
- {"mode", (getter)BZ2File_get_mode, NULL,
- "file mode ('r', 'w', or 'U')"},
- {"name", (getter)BZ2File_get_name, NULL,
- "file name"},
- {NULL} /* Sentinel */
+ {"closed", (getter)BZ2File_get_closed, NULL,
+ "True if the file is closed"},
+ {"newlines", (getter)BZ2File_get_newlines, NULL,
+ "end-of-line convention used in this file"},
+ {"mode", (getter)BZ2File_get_mode, NULL,
+ "file mode ('r', 'w', or 'U')"},
+ {"name", (getter)BZ2File_get_name, NULL,
+ "file name"},
+ {NULL} /* Sentinel */
};
@@ -1325,9 +1325,9 @@ static PyGetSetDef BZ2File_getset[] = {
#define OFF(x) offsetof(BZ2FileObject, x)
static PyMemberDef BZ2File_members[] = {
- {"softspace", T_INT, OFF(f_softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
- {NULL} /* Sentinel */
+ {"softspace", T_INT, OFF(f_softspace), 0,
+ "flag indicating that a space needs to be printed; used by print"},
+ {NULL} /* Sentinel */
};
/* ===================================================================== */
@@ -1336,153 +1336,153 @@ static PyMemberDef BZ2File_members[] = {
static int
BZ2File_init(BZ2FileObject *self, PyObject *args, PyObject *kwargs)
{
- static char *kwlist[] = {"filename", "mode", "buffering",
- "compresslevel", 0};
- PyObject *name;
- char *mode = "r";
- int buffering = -1;
- int compresslevel = 9;
- int bzerror;
- int mode_char = 0;
-
- self->size = -1;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|sii:BZ2File",
- kwlist, &name, &mode, &buffering,
- &compresslevel))
- return -1;
-
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- return -1;
- }
-
- for (;;) {
- int error = 0;
- switch (*mode) {
- case 'r':
- case 'w':
- if (mode_char)
- error = 1;
- mode_char = *mode;
- break;
-
- case 'b':
- break;
-
- case 'U':
+ static char *kwlist[] = {"filename", "mode", "buffering",
+ "compresslevel", 0};
+ PyObject *name;
+ char *mode = "r";
+ int buffering = -1;
+ int compresslevel = 9;
+ int bzerror;
+ int mode_char = 0;
+
+ self->size = -1;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|sii:BZ2File",
+ kwlist, &name, &mode, &buffering,
+ &compresslevel))
+ return -1;
+
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ return -1;
+ }
+
+ for (;;) {
+ int error = 0;
+ switch (*mode) {
+ case 'r':
+ case 'w':
+ if (mode_char)
+ error = 1;
+ mode_char = *mode;
+ break;
+
+ case 'b':
+ break;
+
+ case 'U':
#ifdef __VMS
- self->f_univ_newline = 0;
+ self->f_univ_newline = 0;
#else
- self->f_univ_newline = 1;
+ self->f_univ_newline = 1;
#endif
- break;
-
- default:
- error = 1;
- break;
- }
- if (error) {
- PyErr_Format(PyExc_ValueError,
- "invalid mode char %c", *mode);
- return -1;
- }
- mode++;
- if (*mode == '\0')
- break;
- }
-
- if (mode_char == 0) {
- mode_char = 'r';
- }
-
- mode = (mode_char == 'r') ? "rb" : "wb";
-
- self->file = PyObject_CallFunction((PyObject*)&PyFile_Type, "(Osi)",
- name, mode, buffering);
- if (self->file == NULL)
- return -1;
-
- /* From now on, we have stuff to dealloc, so jump to error label
- * instead of returning */
+ break;
+
+ default:
+ error = 1;
+ break;
+ }
+ if (error) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid mode char %c", *mode);
+ return -1;
+ }
+ mode++;
+ if (*mode == '\0')
+ break;
+ }
+
+ if (mode_char == 0) {
+ mode_char = 'r';
+ }
+
+ mode = (mode_char == 'r') ? "rb" : "wb";
+
+ self->file = PyObject_CallFunction((PyObject*)&PyFile_Type, "(Osi)",
+ name, mode, buffering);
+ if (self->file == NULL)
+ return -1;
+
+ /* From now on, we have stuff to dealloc, so jump to error label
+ * instead of returning */
#ifdef WITH_THREAD
- self->lock = PyThread_allocate_lock();
- if (!self->lock) {
- PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
- goto error;
- }
+ self->lock = PyThread_allocate_lock();
+ if (!self->lock) {
+ PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
+ goto error;
+ }
#endif
- if (mode_char == 'r')
- self->fp = BZ2_bzReadOpen(&bzerror,
- PyFile_AsFile(self->file),
- 0, 0, NULL, 0);
- else
- self->fp = BZ2_bzWriteOpen(&bzerror,
- PyFile_AsFile(self->file),
- compresslevel, 0, 0);
+ if (mode_char == 'r')
+ self->fp = BZ2_bzReadOpen(&bzerror,
+ PyFile_AsFile(self->file),
+ 0, 0, NULL, 0);
+ else
+ self->fp = BZ2_bzWriteOpen(&bzerror,
+ PyFile_AsFile(self->file),
+ compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- PyFile_IncUseCount((PyFileObject *)self->file);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ PyFile_IncUseCount((PyFileObject *)self->file);
- self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;
+ self->mode = (mode_char == 'r') ? MODE_READ : MODE_WRITE;
- return 0;
+ return 0;
error:
- Py_CLEAR(self->file);
+ Py_CLEAR(self->file);
#ifdef WITH_THREAD
- if (self->lock) {
- PyThread_free_lock(self->lock);
- self->lock = NULL;
- }
+ if (self->lock) {
+ PyThread_free_lock(self->lock);
+ self->lock = NULL;
+ }
#endif
- return -1;
+ return -1;
}
static void
BZ2File_dealloc(BZ2FileObject *self)
{
- int bzerror;
+ int bzerror;
#ifdef WITH_THREAD
- if (self->lock)
- PyThread_free_lock(self->lock);
+ if (self->lock)
+ PyThread_free_lock(self->lock);
#endif
- switch (self->mode) {
- case MODE_READ:
- case MODE_READ_EOF:
- BZ2_bzReadClose(&bzerror, self->fp);
- break;
- case MODE_WRITE:
- BZ2_bzWriteClose(&bzerror, self->fp,
- 0, NULL, NULL);
- break;
- }
- if (self->fp) {
- PyFile_DecUseCount((PyFileObject *)self->file);
- self->fp = NULL;
- }
- Util_DropReadAhead(self);
- Py_XDECREF(self->file);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ switch (self->mode) {
+ case MODE_READ:
+ case MODE_READ_EOF:
+ BZ2_bzReadClose(&bzerror, self->fp);
+ break;
+ case MODE_WRITE:
+ BZ2_bzWriteClose(&bzerror, self->fp,
+ 0, NULL, NULL);
+ break;
+ }
+ if (self->fp) {
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ self->fp = NULL;
+ }
+ Util_DropReadAhead(self);
+ Py_XDECREF(self->file);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
/* This is a hacked version of Python's fileobject.c:file_getiter(). */
static PyObject *
BZ2File_getiter(BZ2FileObject *self)
{
- if (self->mode == MODE_CLOSED) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return NULL;
- }
- Py_INCREF((PyObject*)self);
- return (PyObject *)self;
+ if (self->mode == MODE_CLOSED) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return NULL;
+ }
+ Py_INCREF((PyObject*)self);
+ return (PyObject *)self;
}
/* This is a hacked version of Python's fileobject.c:file_iternext(). */
@@ -1490,21 +1490,21 @@ BZ2File_getiter(BZ2FileObject *self)
static PyObject *
BZ2File_iternext(BZ2FileObject *self)
{
- PyStringObject* ret;
- ACQUIRE_LOCK(self);
- if (self->mode == MODE_CLOSED) {
- RELEASE_LOCK(self);
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return NULL;
- }
- ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE);
- RELEASE_LOCK(self);
- if (ret == NULL || PyString_GET_SIZE(ret) == 0) {
- Py_XDECREF(ret);
- return NULL;
- }
- return (PyObject *)ret;
+ PyStringObject* ret;
+ ACQUIRE_LOCK(self);
+ if (self->mode == MODE_CLOSED) {
+ RELEASE_LOCK(self);
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return NULL;
+ }
+ ret = Util_ReadAheadGetLineSkip(self, 0, READAHEAD_BUFSIZE);
+ RELEASE_LOCK(self);
+ if (ret == NULL || PyString_GET_SIZE(ret) == 0) {
+ Py_XDECREF(ret);
+ return NULL;
+ }
+ return (PyObject *)ret;
}
/* ===================================================================== */
@@ -1532,46 +1532,46 @@ newlines are available only when reading.\n\
;
static PyTypeObject BZ2File_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bz2.BZ2File", /*tp_name*/
- sizeof(BZ2FileObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BZ2File_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
- BZ2File__doc__, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- (getiterfunc)BZ2File_getiter, /*tp_iter*/
- (iternextfunc)BZ2File_iternext, /*tp_iternext*/
- BZ2File_methods, /*tp_methods*/
- BZ2File_members, /*tp_members*/
- BZ2File_getset, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- (initproc)BZ2File_init, /*tp_init*/
- PyType_GenericAlloc, /*tp_alloc*/
- PyType_GenericNew, /*tp_new*/
- _PyObject_Del, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "bz2.BZ2File", /*tp_name*/
+ sizeof(BZ2FileObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BZ2File_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ BZ2File__doc__, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ (getiterfunc)BZ2File_getiter, /*tp_iter*/
+ (iternextfunc)BZ2File_iternext, /*tp_iternext*/
+ BZ2File_methods, /*tp_methods*/
+ BZ2File_members, /*tp_members*/
+ BZ2File_getset, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ (initproc)BZ2File_init, /*tp_init*/
+ PyType_GenericAlloc, /*tp_alloc*/
+ PyType_GenericNew, /*tp_new*/
+ _PyObject_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1590,76 +1590,76 @@ and return what is left in the internal buffers.\n\
static PyObject *
BZ2Comp_compress(BZ2CompObject *self, PyObject *args)
{
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize = SMALLCHUNK;
- PY_LONG_LONG totalout;
- PyObject *ret = NULL;
- bz_stream *bzs = &self->bzs;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "s*:compress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (datasize == 0) {
- PyBuffer_Release(&pdata);
- return PyString_FromString("");
- }
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_ValueError,
- "this object was already flushed");
- goto error;
- }
-
- ret = PyString_FromStringAndSize(NULL, bufsize);
- if (!ret)
- goto error;
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- totalout = BZS_TOTAL_OUT(bzs);
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzCompress(bzs, BZ_RUN);
- Py_END_ALLOW_THREADS
- if (bzerror != BZ_RUN_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- if (bzs->avail_in == 0)
- break; /* no more input data */
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyString_Resize(&ret, bufsize) < 0) {
- BZ2_bzCompressEnd(bzs);
- goto error;
- }
- bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
- - totalout);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
-
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- return ret;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize = SMALLCHUNK;
+ PY_LONG_LONG totalout;
+ PyObject *ret = NULL;
+ bz_stream *bzs = &self->bzs;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "s*:compress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (datasize == 0) {
+ PyBuffer_Release(&pdata);
+ return PyString_FromString("");
+ }
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_ValueError,
+ "this object was already flushed");
+ goto error;
+ }
+
+ ret = PyString_FromStringAndSize(NULL, bufsize);
+ if (!ret)
+ goto error;
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ totalout = BZS_TOTAL_OUT(bzs);
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzCompress(bzs, BZ_RUN);
+ Py_END_ALLOW_THREADS
+ if (bzerror != BZ_RUN_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ if (bzs->avail_in == 0)
+ break; /* no more input data */
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyString_Resize(&ret, bufsize) < 0) {
+ BZ2_bzCompressEnd(bzs);
+ goto error;
+ }
+ bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
+ - totalout);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ return ret;
error:
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- Py_XDECREF(ret);
- return NULL;
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ Py_XDECREF(ret);
+ return NULL;
}
PyDoc_STRVAR(BZ2Comp_flush__doc__,
@@ -1672,68 +1672,68 @@ You must not use the compressor object after calling this method.\n\
static PyObject *
BZ2Comp_flush(BZ2CompObject *self)
{
- int bufsize = SMALLCHUNK;
- PyObject *ret = NULL;
- bz_stream *bzs = &self->bzs;
- PY_LONG_LONG totalout;
- int bzerror;
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_ValueError, "object was already "
- "flushed");
- goto error;
- }
- self->running = 0;
-
- ret = PyString_FromStringAndSize(NULL, bufsize);
- if (!ret)
- goto error;
-
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- totalout = BZS_TOTAL_OUT(bzs);
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_FINISH_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyString_Resize(&ret, bufsize) < 0)
- goto error;
- bzs->next_out = BUF(ret);
- bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
- - totalout);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0)
- _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
-
- RELEASE_LOCK(self);
- return ret;
+ int bufsize = SMALLCHUNK;
+ PyObject *ret = NULL;
+ bz_stream *bzs = &self->bzs;
+ PY_LONG_LONG totalout;
+ int bzerror;
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_ValueError, "object was already "
+ "flushed");
+ goto error;
+ }
+ self->running = 0;
+
+ ret = PyString_FromStringAndSize(NULL, bufsize);
+ if (!ret)
+ goto error;
+
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ totalout = BZS_TOTAL_OUT(bzs);
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_FINISH_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyString_Resize(&ret, bufsize) < 0)
+ goto error;
+ bzs->next_out = BUF(ret);
+ bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
+ - totalout);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0)
+ _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+
+ RELEASE_LOCK(self);
+ return ret;
error:
- RELEASE_LOCK(self);
- Py_XDECREF(ret);
- return NULL;
+ RELEASE_LOCK(self);
+ Py_XDECREF(ret);
+ return NULL;
}
static PyMethodDef BZ2Comp_methods[] = {
- {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS,
- BZ2Comp_compress__doc__},
- {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS,
- BZ2Comp_flush__doc__},
- {NULL, NULL} /* sentinel */
+ {"compress", (PyCFunction)BZ2Comp_compress, METH_VARARGS,
+ BZ2Comp_compress__doc__},
+ {"flush", (PyCFunction)BZ2Comp_flush, METH_NOARGS,
+ BZ2Comp_flush__doc__},
+ {NULL, NULL} /* sentinel */
};
@@ -1743,57 +1743,57 @@ static PyMethodDef BZ2Comp_methods[] = {
static int
BZ2Comp_init(BZ2CompObject *self, PyObject *args, PyObject *kwargs)
{
- int compresslevel = 9;
- int bzerror;
- static char *kwlist[] = {"compresslevel", 0};
+ int compresslevel = 9;
+ int bzerror;
+ static char *kwlist[] = {"compresslevel", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor",
- kwlist, &compresslevel))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i:BZ2Compressor",
+ kwlist, &compresslevel))
+ return -1;
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- goto error;
- }
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ goto error;
+ }
#ifdef WITH_THREAD
- self->lock = PyThread_allocate_lock();
- if (!self->lock) {
- PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
- goto error;
- }
+ self->lock = PyThread_allocate_lock();
+ if (!self->lock) {
+ PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
+ goto error;
+ }
#endif
- memset(&self->bzs, 0, sizeof(bz_stream));
- bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
+ memset(&self->bzs, 0, sizeof(bz_stream));
+ bzerror = BZ2_bzCompressInit(&self->bzs, compresslevel, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
- self->running = 1;
+ self->running = 1;
- return 0;
+ return 0;
error:
#ifdef WITH_THREAD
- if (self->lock) {
- PyThread_free_lock(self->lock);
- self->lock = NULL;
- }
+ if (self->lock) {
+ PyThread_free_lock(self->lock);
+ self->lock = NULL;
+ }
#endif
- return -1;
+ return -1;
}
static void
BZ2Comp_dealloc(BZ2CompObject *self)
{
#ifdef WITH_THREAD
- if (self->lock)
- PyThread_free_lock(self->lock);
+ if (self->lock)
+ PyThread_free_lock(self->lock);
#endif
- BZ2_bzCompressEnd(&self->bzs);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ BZ2_bzCompressEnd(&self->bzs);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
@@ -1810,46 +1810,46 @@ must be a number between 1 and 9.\n\
");
static PyTypeObject BZ2Comp_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bz2.BZ2Compressor", /*tp_name*/
- sizeof(BZ2CompObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BZ2Comp_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
- BZ2Comp__doc__, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- BZ2Comp_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*/
- (initproc)BZ2Comp_init, /*tp_init*/
- PyType_GenericAlloc, /*tp_alloc*/
- PyType_GenericNew, /*tp_new*/
- _PyObject_Del, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "bz2.BZ2Compressor", /*tp_name*/
+ sizeof(BZ2CompObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BZ2Comp_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ BZ2Comp__doc__, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ BZ2Comp_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*/
+ (initproc)BZ2Comp_init, /*tp_init*/
+ PyType_GenericAlloc, /*tp_alloc*/
+ PyType_GenericNew, /*tp_new*/
+ _PyObject_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -1860,8 +1860,8 @@ static PyTypeObject BZ2Comp_Type = {
#define OFF(x) offsetof(BZ2DecompObject, x)
static PyMemberDef BZ2Decomp_members[] = {
- {"unused_data", T_OBJECT, OFF(unused_data), RO},
- {NULL} /* Sentinel */
+ {"unused_data", T_OBJECT, OFF(unused_data), RO},
+ {NULL} /* Sentinel */
};
@@ -1881,88 +1881,88 @@ unused_data attribute.\n\
static PyObject *
BZ2Decomp_decompress(BZ2DecompObject *self, PyObject *args)
{
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize = SMALLCHUNK;
- PY_LONG_LONG totalout;
- PyObject *ret = NULL;
- bz_stream *bzs = &self->bzs;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "s*:decompress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- ACQUIRE_LOCK(self);
- if (!self->running) {
- PyErr_SetString(PyExc_EOFError, "end of stream was "
- "already found");
- goto error;
- }
-
- ret = PyString_FromStringAndSize(NULL, bufsize);
- if (!ret)
- goto error;
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- totalout = BZS_TOTAL_OUT(bzs);
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzDecompress(bzs);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- if (bzs->avail_in != 0) {
- Py_DECREF(self->unused_data);
- self->unused_data =
- PyString_FromStringAndSize(bzs->next_in,
- bzs->avail_in);
- }
- self->running = 0;
- break;
- }
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
- if (bzs->avail_in == 0)
- break; /* no more input data */
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyString_Resize(&ret, bufsize) < 0) {
- BZ2_bzDecompressEnd(bzs);
- goto error;
- }
- bzs->next_out = BUF(ret);
- bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
- - totalout);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0)
- _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
-
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- return ret;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize = SMALLCHUNK;
+ PY_LONG_LONG totalout;
+ PyObject *ret = NULL;
+ bz_stream *bzs = &self->bzs;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "s*:decompress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ ACQUIRE_LOCK(self);
+ if (!self->running) {
+ PyErr_SetString(PyExc_EOFError, "end of stream was "
+ "already found");
+ goto error;
+ }
+
+ ret = PyString_FromStringAndSize(NULL, bufsize);
+ if (!ret)
+ goto error;
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ totalout = BZS_TOTAL_OUT(bzs);
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzDecompress(bzs);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ if (bzs->avail_in != 0) {
+ Py_DECREF(self->unused_data);
+ self->unused_data =
+ PyString_FromStringAndSize(bzs->next_in,
+ bzs->avail_in);
+ }
+ self->running = 0;
+ break;
+ }
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
+ if (bzs->avail_in == 0)
+ break; /* no more input data */
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyString_Resize(&ret, bufsize) < 0) {
+ BZ2_bzDecompressEnd(bzs);
+ goto error;
+ }
+ bzs->next_out = BUF(ret);
+ bzs->next_out = BUF(ret) + (BZS_TOTAL_OUT(bzs)
+ - totalout);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0)
+ _PyString_Resize(&ret, (Py_ssize_t)(BZS_TOTAL_OUT(bzs) - totalout));
+
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ return ret;
error:
- RELEASE_LOCK(self);
- PyBuffer_Release(&pdata);
- Py_XDECREF(ret);
- return NULL;
+ RELEASE_LOCK(self);
+ PyBuffer_Release(&pdata);
+ Py_XDECREF(ret);
+ return NULL;
}
static PyMethodDef BZ2Decomp_methods[] = {
- {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__},
- {NULL, NULL} /* sentinel */
+ {"decompress", (PyCFunction)BZ2Decomp_decompress, METH_VARARGS, BZ2Decomp_decompress__doc__},
+ {NULL, NULL} /* sentinel */
};
@@ -1972,55 +1972,55 @@ static PyMethodDef BZ2Decomp_methods[] = {
static int
BZ2Decomp_init(BZ2DecompObject *self, PyObject *args, PyObject *kwargs)
{
- int bzerror;
+ int bzerror;
- if (!PyArg_ParseTuple(args, ":BZ2Decompressor"))
- return -1;
+ if (!PyArg_ParseTuple(args, ":BZ2Decompressor"))
+ return -1;
#ifdef WITH_THREAD
- self->lock = PyThread_allocate_lock();
- if (!self->lock) {
- PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
- goto error;
- }
+ self->lock = PyThread_allocate_lock();
+ if (!self->lock) {
+ PyErr_SetString(PyExc_MemoryError, "unable to allocate lock");
+ goto error;
+ }
#endif
- self->unused_data = PyString_FromString("");
- if (!self->unused_data)
- goto error;
+ self->unused_data = PyString_FromString("");
+ if (!self->unused_data)
+ goto error;
- memset(&self->bzs, 0, sizeof(bz_stream));
- bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- goto error;
- }
+ memset(&self->bzs, 0, sizeof(bz_stream));
+ bzerror = BZ2_bzDecompressInit(&self->bzs, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ goto error;
+ }
- self->running = 1;
+ self->running = 1;
- return 0;
+ return 0;
error:
#ifdef WITH_THREAD
- if (self->lock) {
- PyThread_free_lock(self->lock);
- self->lock = NULL;
- }
+ if (self->lock) {
+ PyThread_free_lock(self->lock);
+ self->lock = NULL;
+ }
#endif
- Py_CLEAR(self->unused_data);
- return -1;
+ Py_CLEAR(self->unused_data);
+ return -1;
}
static void
BZ2Decomp_dealloc(BZ2DecompObject *self)
{
#ifdef WITH_THREAD
- if (self->lock)
- PyThread_free_lock(self->lock);
+ if (self->lock)
+ PyThread_free_lock(self->lock);
#endif
- Py_XDECREF(self->unused_data);
- BZ2_bzDecompressEnd(&self->bzs);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_XDECREF(self->unused_data);
+ BZ2_bzDecompressEnd(&self->bzs);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
@@ -2036,46 +2036,46 @@ decompress() function instead.\n\
");
static PyTypeObject BZ2Decomp_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "bz2.BZ2Decompressor", /*tp_name*/
- sizeof(BZ2DecompObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- (destructor)BZ2Decomp_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
- BZ2Decomp__doc__, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- BZ2Decomp_methods, /*tp_methods*/
- BZ2Decomp_members, /*tp_members*/
- 0, /*tp_getset*/
- 0, /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- (initproc)BZ2Decomp_init, /*tp_init*/
- PyType_GenericAlloc, /*tp_alloc*/
- PyType_GenericNew, /*tp_new*/
- _PyObject_Del, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "bz2.BZ2Decompressor", /*tp_name*/
+ sizeof(BZ2DecompObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ (destructor)BZ2Decomp_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /*tp_flags*/
+ BZ2Decomp__doc__, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ BZ2Decomp_methods, /*tp_methods*/
+ BZ2Decomp_members, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ (initproc)BZ2Decomp_init, /*tp_init*/
+ PyType_GenericAlloc, /*tp_alloc*/
+ PyType_GenericNew, /*tp_new*/
+ _PyObject_Del, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -2093,88 +2093,88 @@ given, must be a number between 1 and 9.\n\
static PyObject *
bz2_compress(PyObject *self, PyObject *args, PyObject *kwargs)
{
- int compresslevel=9;
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize;
- PyObject *ret = NULL;
- bz_stream _bzs;
- bz_stream *bzs = &_bzs;
- int bzerror;
- static char *kwlist[] = {"data", "compresslevel", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i",
- kwlist, &pdata,
- &compresslevel))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (compresslevel < 1 || compresslevel > 9) {
- PyErr_SetString(PyExc_ValueError,
- "compresslevel must be between 1 and 9");
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- /* Conforming to bz2 manual, this is large enough to fit compressed
- * data in one shot. We will check it later anyway. */
- bufsize = datasize + (datasize/100+1) + 600;
-
- ret = PyString_FromStringAndSize(NULL, bufsize);
- if (!ret) {
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- memset(bzs, 0, sizeof(bz_stream));
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_FINISH_OK) {
- BZ2_bzCompressEnd(bzs);
- Util_CatchBZ2Error(bzerror);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyString_Resize(&ret, bufsize) < 0) {
- BZ2_bzCompressEnd(bzs);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0)
- _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
- BZ2_bzCompressEnd(bzs);
-
- PyBuffer_Release(&pdata);
- return ret;
+ int compresslevel=9;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize;
+ PyObject *ret = NULL;
+ bz_stream _bzs;
+ bz_stream *bzs = &_bzs;
+ int bzerror;
+ static char *kwlist[] = {"data", "compresslevel", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i",
+ kwlist, &pdata,
+ &compresslevel))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (compresslevel < 1 || compresslevel > 9) {
+ PyErr_SetString(PyExc_ValueError,
+ "compresslevel must be between 1 and 9");
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ /* Conforming to bz2 manual, this is large enough to fit compressed
+ * data in one shot. We will check it later anyway. */
+ bufsize = datasize + (datasize/100+1) + 600;
+
+ ret = PyString_FromStringAndSize(NULL, bufsize);
+ if (!ret) {
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ memset(bzs, 0, sizeof(bz_stream));
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ bzerror = BZ2_bzCompressInit(bzs, compresslevel, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzCompress(bzs, BZ_FINISH);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_FINISH_OK) {
+ BZ2_bzCompressEnd(bzs);
+ Util_CatchBZ2Error(bzerror);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyString_Resize(&ret, bufsize) < 0) {
+ BZ2_bzCompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0)
+ _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
+ BZ2_bzCompressEnd(bzs);
+
+ PyBuffer_Release(&pdata);
+ return ret;
}
PyDoc_STRVAR(bz2_decompress__doc__,
@@ -2187,94 +2187,94 @@ use an instance of BZ2Decompressor instead.\n\
static PyObject *
bz2_decompress(PyObject *self, PyObject *args)
{
- Py_buffer pdata;
- char *data;
- int datasize;
- int bufsize = SMALLCHUNK;
- PyObject *ret;
- bz_stream _bzs;
- bz_stream *bzs = &_bzs;
- int bzerror;
-
- if (!PyArg_ParseTuple(args, "s*:decompress", &pdata))
- return NULL;
- data = pdata.buf;
- datasize = pdata.len;
-
- if (datasize == 0) {
- PyBuffer_Release(&pdata);
- return PyString_FromString("");
- }
-
- ret = PyString_FromStringAndSize(NULL, bufsize);
- if (!ret) {
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- memset(bzs, 0, sizeof(bz_stream));
-
- bzs->next_in = data;
- bzs->avail_in = datasize;
- bzs->next_out = BUF(ret);
- bzs->avail_out = bufsize;
-
- bzerror = BZ2_bzDecompressInit(bzs, 0, 0);
- if (bzerror != BZ_OK) {
- Util_CatchBZ2Error(bzerror);
- Py_DECREF(ret);
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- bzerror = BZ2_bzDecompress(bzs);
- Py_END_ALLOW_THREADS
- if (bzerror == BZ_STREAM_END) {
- break;
- } else if (bzerror != BZ_OK) {
- BZ2_bzDecompressEnd(bzs);
- Util_CatchBZ2Error(bzerror);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- if (bzs->avail_in == 0) {
- BZ2_bzDecompressEnd(bzs);
- PyErr_SetString(PyExc_ValueError,
- "couldn't find end of stream");
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- if (bzs->avail_out == 0) {
- bufsize = Util_NewBufferSize(bufsize);
- if (_PyString_Resize(&ret, bufsize) < 0) {
- BZ2_bzDecompressEnd(bzs);
- PyBuffer_Release(&pdata);
- Py_DECREF(ret);
- return NULL;
- }
- bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
- bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
- }
- }
-
- if (bzs->avail_out != 0)
- _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
- BZ2_bzDecompressEnd(bzs);
- PyBuffer_Release(&pdata);
-
- return ret;
+ Py_buffer pdata;
+ char *data;
+ int datasize;
+ int bufsize = SMALLCHUNK;
+ PyObject *ret;
+ bz_stream _bzs;
+ bz_stream *bzs = &_bzs;
+ int bzerror;
+
+ if (!PyArg_ParseTuple(args, "s*:decompress", &pdata))
+ return NULL;
+ data = pdata.buf;
+ datasize = pdata.len;
+
+ if (datasize == 0) {
+ PyBuffer_Release(&pdata);
+ return PyString_FromString("");
+ }
+
+ ret = PyString_FromStringAndSize(NULL, bufsize);
+ if (!ret) {
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ memset(bzs, 0, sizeof(bz_stream));
+
+ bzs->next_in = data;
+ bzs->avail_in = datasize;
+ bzs->next_out = BUF(ret);
+ bzs->avail_out = bufsize;
+
+ bzerror = BZ2_bzDecompressInit(bzs, 0, 0);
+ if (bzerror != BZ_OK) {
+ Util_CatchBZ2Error(bzerror);
+ Py_DECREF(ret);
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ bzerror = BZ2_bzDecompress(bzs);
+ Py_END_ALLOW_THREADS
+ if (bzerror == BZ_STREAM_END) {
+ break;
+ } else if (bzerror != BZ_OK) {
+ BZ2_bzDecompressEnd(bzs);
+ Util_CatchBZ2Error(bzerror);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (bzs->avail_in == 0) {
+ BZ2_bzDecompressEnd(bzs);
+ PyErr_SetString(PyExc_ValueError,
+ "couldn't find end of stream");
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ if (bzs->avail_out == 0) {
+ bufsize = Util_NewBufferSize(bufsize);
+ if (_PyString_Resize(&ret, bufsize) < 0) {
+ BZ2_bzDecompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+ Py_DECREF(ret);
+ return NULL;
+ }
+ bzs->next_out = BUF(ret) + BZS_TOTAL_OUT(bzs);
+ bzs->avail_out = bufsize - (bzs->next_out - BUF(ret));
+ }
+ }
+
+ if (bzs->avail_out != 0)
+ _PyString_Resize(&ret, (Py_ssize_t)BZS_TOTAL_OUT(bzs));
+ BZ2_bzDecompressEnd(bzs);
+ PyBuffer_Release(&pdata);
+
+ return ret;
}
static PyMethodDef bz2_methods[] = {
- {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS,
- bz2_compress__doc__},
- {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS,
- bz2_decompress__doc__},
- {NULL, NULL} /* sentinel */
+ {"compress", (PyCFunction) bz2_compress, METH_VARARGS|METH_KEYWORDS,
+ bz2_compress__doc__},
+ {"decompress", (PyCFunction) bz2_decompress, METH_VARARGS,
+ bz2_decompress__doc__},
+ {NULL, NULL} /* sentinel */
};
/* ===================================================================== */
@@ -2290,24 +2290,24 @@ sequential (de)compression.\n\
PyMODINIT_FUNC
initbz2(void)
{
- PyObject *m;
+ PyObject *m;
- Py_TYPE(&BZ2File_Type) = &PyType_Type;
- Py_TYPE(&BZ2Comp_Type) = &PyType_Type;
- Py_TYPE(&BZ2Decomp_Type) = &PyType_Type;
+ Py_TYPE(&BZ2File_Type) = &PyType_Type;
+ Py_TYPE(&BZ2Comp_Type) = &PyType_Type;
+ Py_TYPE(&BZ2Decomp_Type) = &PyType_Type;
- m = Py_InitModule3("bz2", bz2_methods, bz2__doc__);
- if (m == NULL)
- return;
+ m = Py_InitModule3("bz2", bz2_methods, bz2__doc__);
+ if (m == NULL)
+ return;
- PyModule_AddObject(m, "__author__", PyString_FromString(__author__));
+ PyModule_AddObject(m, "__author__", PyString_FromString(__author__));
- Py_INCREF(&BZ2File_Type);
- PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type);
+ Py_INCREF(&BZ2File_Type);
+ PyModule_AddObject(m, "BZ2File", (PyObject *)&BZ2File_Type);
- Py_INCREF(&BZ2Comp_Type);
- PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type);
+ Py_INCREF(&BZ2Comp_Type);
+ PyModule_AddObject(m, "BZ2Compressor", (PyObject *)&BZ2Comp_Type);
- Py_INCREF(&BZ2Decomp_Type);
- PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type);
+ Py_INCREF(&BZ2Decomp_Type);
+ PyModule_AddObject(m, "BZ2Decompressor", (PyObject *)&BZ2Decomp_Type);
}
diff --git a/Modules/cPickle.c b/Modules/cPickle.c
index 79eebca..bd577ad 100644
--- a/Modules/cPickle.c
+++ b/Modules/cPickle.c
@@ -72,7 +72,7 @@ PyDoc_STRVAR(cPickle_module_documentation,
#define SETITEMS 'u'
/* Protocol 2. */
-#define PROTO '\x80' /* identify pickle protocol */
+#define PROTO '\x80' /* identify pickle protocol */
#define NEWOBJ '\x81' /* build object by applying cls.__new__ to argtuple */
#define EXT1 '\x82' /* push object from extension registry; 1-byte index */
#define EXT2 '\x83' /* ditto, but 2-byte index */
@@ -131,37 +131,37 @@ static PyObject *__class___str, *__getinitargs___str, *__dict___str,
*__getstate___str, *__setstate___str, *__name___str, *__reduce___str,
*__reduce_ex___str,
*write_str, *append_str,
- *read_str, *readline_str, *__main___str,
+ *read_str, *readline_str, *__main___str,
*dispatch_table_str;
/*************************************************************************
Internal Data type for pickle data. */
typedef struct {
- PyObject_HEAD
- int length; /* number of initial slots in data currently used */
- int size; /* number of slots in data allocated */
- PyObject **data;
+ PyObject_HEAD
+ int length; /* number of initial slots in data currently used */
+ int size; /* number of slots in data allocated */
+ PyObject **data;
} Pdata;
static void
Pdata_dealloc(Pdata *self)
{
- int i;
- PyObject **p;
+ int i;
+ PyObject **p;
- for (i = self->length, p = self->data; --i >= 0; p++) {
- Py_DECREF(*p);
- }
- if (self->data)
- free(self->data);
- PyObject_Del(self);
+ for (i = self->length, p = self->data; --i >= 0; p++) {
+ Py_DECREF(*p);
+ }
+ if (self->data)
+ free(self->data);
+ PyObject_Del(self);
}
static PyTypeObject PdataType = {
- PyVarObject_HEAD_INIT(NULL, 0) "cPickle.Pdata", sizeof(Pdata), 0,
- (destructor)Pdata_dealloc,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
+ PyVarObject_HEAD_INIT(NULL, 0) "cPickle.Pdata", sizeof(Pdata), 0,
+ (destructor)Pdata_dealloc,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0L,0L,0L,0L, ""
};
#define Pdata_Check(O) (Py_TYPE(O) == &PdataType)
@@ -169,24 +169,24 @@ static PyTypeObject PdataType = {
static PyObject *
Pdata_New(void)
{
- Pdata *self;
+ Pdata *self;
- if (!(self = PyObject_New(Pdata, &PdataType)))
- return NULL;
- self->size = 8;
- self->length = 0;
- self->data = malloc(self->size * sizeof(PyObject*));
- if (self->data)
- return (PyObject*)self;
- Py_DECREF(self);
- return PyErr_NoMemory();
+ if (!(self = PyObject_New(Pdata, &PdataType)))
+ return NULL;
+ self->size = 8;
+ self->length = 0;
+ self->data = malloc(self->size * sizeof(PyObject*));
+ if (self->data)
+ return (PyObject*)self;
+ Py_DECREF(self);
+ return PyErr_NoMemory();
}
static int
stackUnderflow(void)
{
- PyErr_SetString(UnpicklingError, "unpickling stack underflow");
- return -1;
+ PyErr_SetString(UnpicklingError, "unpickling stack underflow");
+ return -1;
}
/* Retain only the initial clearto items. If clearto >= the current
@@ -195,60 +195,60 @@ stackUnderflow(void)
static int
Pdata_clear(Pdata *self, int clearto)
{
- int i;
- PyObject **p;
+ int i;
+ PyObject **p;
- if (clearto < 0) return stackUnderflow();
- if (clearto >= self->length) return 0;
+ if (clearto < 0) return stackUnderflow();
+ if (clearto >= self->length) return 0;
- for (i = self->length, p = self->data + clearto;
- --i >= clearto;
- p++) {
- Py_CLEAR(*p);
- }
- self->length = clearto;
+ for (i = self->length, p = self->data + clearto;
+ --i >= clearto;
+ p++) {
+ Py_CLEAR(*p);
+ }
+ self->length = clearto;
- return 0;
+ return 0;
}
static int
Pdata_grow(Pdata *self)
{
- int bigger;
- size_t nbytes;
- PyObject **tmp;
-
- bigger = self->size << 1;
- if (bigger <= 0) /* was 0, or new value overflows */
- goto nomemory;
- if ((int)(size_t)bigger != bigger)
- goto nomemory;
- nbytes = (size_t)bigger * sizeof(PyObject *);
- if (nbytes / sizeof(PyObject *) != (size_t)bigger)
- goto nomemory;
- tmp = realloc(self->data, nbytes);
- if (tmp == NULL)
- goto nomemory;
- self->data = tmp;
- self->size = bigger;
- return 0;
+ int bigger;
+ size_t nbytes;
+ PyObject **tmp;
+
+ bigger = self->size << 1;
+ if (bigger <= 0) /* was 0, or new value overflows */
+ goto nomemory;
+ if ((int)(size_t)bigger != bigger)
+ goto nomemory;
+ nbytes = (size_t)bigger * sizeof(PyObject *);
+ if (nbytes / sizeof(PyObject *) != (size_t)bigger)
+ goto nomemory;
+ tmp = realloc(self->data, nbytes);
+ if (tmp == NULL)
+ goto nomemory;
+ self->data = tmp;
+ self->size = bigger;
+ return 0;
nomemory:
- PyErr_NoMemory();
- return -1;
+ PyErr_NoMemory();
+ return -1;
}
/* D is a Pdata*. Pop the topmost element and store it into V, which
* must be an lvalue holding PyObject*. On stack underflow, UnpicklingError
* is raised and V is set to NULL. D and V may be evaluated several times.
*/
-#define PDATA_POP(D, V) { \
- if ((D)->length) \
- (V) = (D)->data[--((D)->length)]; \
- else { \
- PyErr_SetString(UnpicklingError, "bad pickle data"); \
- (V) = NULL; \
- } \
+#define PDATA_POP(D, V) { \
+ if ((D)->length) \
+ (V) = (D)->data[--((D)->length)]; \
+ else { \
+ PyErr_SetString(UnpicklingError, "bad pickle data"); \
+ (V) = NULL; \
+ } \
}
/* PDATA_PUSH and PDATA_APPEND both push rvalue PyObject* O on to Pdata*
@@ -260,55 +260,55 @@ Pdata_grow(Pdata *self)
*/
/* Push O on stack D, giving ownership of O to the stack. */
-#define PDATA_PUSH(D, O, ER) { \
- if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
- Pdata_grow((Pdata*)(D)) < 0) { \
- Py_DECREF(O); \
- return ER; \
- } \
- ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
+#define PDATA_PUSH(D, O, ER) { \
+ if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
+ Pdata_grow((Pdata*)(D)) < 0) { \
+ Py_DECREF(O); \
+ return ER; \
+ } \
+ ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
}
/* Push O on stack D, pushing a new reference. */
-#define PDATA_APPEND(D, O, ER) { \
- if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
- Pdata_grow((Pdata*)(D)) < 0) \
- return ER; \
- Py_INCREF(O); \
- ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
+#define PDATA_APPEND(D, O, ER) { \
+ if (((Pdata*)(D))->length == ((Pdata*)(D))->size && \
+ Pdata_grow((Pdata*)(D)) < 0) \
+ return ER; \
+ Py_INCREF(O); \
+ ((Pdata*)(D))->data[((Pdata*)(D))->length++] = (O); \
}
static PyObject *
Pdata_popTuple(Pdata *self, int start)
{
- PyObject *r;
- int i, j, l;
+ PyObject *r;
+ int i, j, l;
- l = self->length-start;
- r = PyTuple_New(l);
- if (r == NULL)
- return NULL;
- for (i = start, j = 0 ; j < l; i++, j++)
- PyTuple_SET_ITEM(r, j, self->data[i]);
+ l = self->length-start;
+ r = PyTuple_New(l);
+ if (r == NULL)
+ return NULL;
+ for (i = start, j = 0 ; j < l; i++, j++)
+ PyTuple_SET_ITEM(r, j, self->data[i]);
- self->length = start;
- return r;
+ self->length = start;
+ return r;
}
static PyObject *
Pdata_popList(Pdata *self, int start)
{
- PyObject *r;
- int i, j, l;
+ PyObject *r;
+ int i, j, l;
- l=self->length-start;
- if (!( r=PyList_New(l))) return NULL;
- for (i=start, j=0 ; j < l; i++, j++)
- PyList_SET_ITEM(r, j, self->data[i]);
+ l=self->length-start;
+ if (!( r=PyList_New(l))) return NULL;
+ for (i=start, j=0 ; j < l; i++, j++)
+ PyList_SET_ITEM(r, j, self->data[i]);
- self->length=start;
- return r;
+ self->length=start;
+ return r;
}
/*************************************************************************/
@@ -331,28 +331,28 @@ Pdata_popList(Pdata *self, int start)
}
typedef struct Picklerobject {
- PyObject_HEAD
- FILE *fp;
- PyObject *write;
- PyObject *file;
- PyObject *memo;
- PyObject *arg;
- PyObject *pers_func;
- PyObject *inst_pers_func;
-
- /* pickle protocol number, >= 0 */
- int proto;
-
- /* bool, true if proto > 0 */
- int bin;
-
- int fast; /* Fast mode doesn't save in memo, don't use if circ ref */
- int (*write_func)(struct Picklerobject *, const char *, Py_ssize_t);
- char *write_buf;
- int buf_size;
- PyObject *dispatch_table;
- int fast_container; /* count nested container dumps */
- PyObject *fast_memo;
+ PyObject_HEAD
+ FILE *fp;
+ PyObject *write;
+ PyObject *file;
+ PyObject *memo;
+ PyObject *arg;
+ PyObject *pers_func;
+ PyObject *inst_pers_func;
+
+ /* pickle protocol number, >= 0 */
+ int proto;
+
+ /* bool, true if proto > 0 */
+ int bin;
+
+ int fast; /* Fast mode doesn't save in memo, don't use if circ ref */
+ int (*write_func)(struct Picklerobject *, const char *, Py_ssize_t);
+ char *write_buf;
+ int buf_size;
+ PyObject *dispatch_table;
+ int fast_container; /* count nested container dumps */
+ PyObject *fast_memo;
} Picklerobject;
#ifndef PY_CPICKLE_FAST_LIMIT
@@ -362,25 +362,25 @@ typedef struct Picklerobject {
static PyTypeObject Picklertype;
typedef struct Unpicklerobject {
- PyObject_HEAD
- FILE *fp;
- PyObject *file;
- PyObject *readline;
- PyObject *read;
- PyObject *memo;
- PyObject *arg;
- Pdata *stack;
- PyObject *mark;
- PyObject *pers_func;
- PyObject *last_string;
- int *marks;
- int num_marks;
- int marks_size;
- Py_ssize_t (*read_func)(struct Unpicklerobject *, char **, Py_ssize_t);
- Py_ssize_t (*readline_func)(struct Unpicklerobject *, char **);
- int buf_size;
- char *buf;
- PyObject *find_class;
+ PyObject_HEAD
+ FILE *fp;
+ PyObject *file;
+ PyObject *readline;
+ PyObject *read;
+ PyObject *memo;
+ PyObject *arg;
+ Pdata *stack;
+ PyObject *mark;
+ PyObject *pers_func;
+ PyObject *last_string;
+ int *marks;
+ int num_marks;
+ int marks_size;
+ Py_ssize_t (*read_func)(struct Unpicklerobject *, char **, Py_ssize_t);
+ Py_ssize_t (*readline_func)(struct Unpicklerobject *, char **);
+ int buf_size;
+ char *buf;
+ PyObject *find_class;
} Unpicklerobject;
static PyTypeObject Unpicklertype;
@@ -393,306 +393,306 @@ static
PyObject *
cPickle_ErrFormat(PyObject *ErrType, char *stringformat, char *format, ...)
{
- va_list va;
- PyObject *args=0, *retval=0;
- va_start(va, format);
-
- if (format) args = Py_VaBuildValue(format, va);
- va_end(va);
- if (format && ! args) return NULL;
- if (stringformat && !(retval=PyString_FromString(stringformat)))
- return NULL;
-
- if (retval) {
- if (args) {
- PyObject *v;
- v=PyString_Format(retval, args);
- Py_DECREF(retval);
- Py_DECREF(args);
- if (! v) return NULL;
- retval=v;
- }
- }
- else
- if (args) retval=args;
- else {
- PyErr_SetObject(ErrType,Py_None);
- return NULL;
- }
- PyErr_SetObject(ErrType,retval);
- Py_DECREF(retval);
- return NULL;
+ va_list va;
+ PyObject *args=0, *retval=0;
+ va_start(va, format);
+
+ if (format) args = Py_VaBuildValue(format, va);
+ va_end(va);
+ if (format && ! args) return NULL;
+ if (stringformat && !(retval=PyString_FromString(stringformat)))
+ return NULL;
+
+ if (retval) {
+ if (args) {
+ PyObject *v;
+ v=PyString_Format(retval, args);
+ Py_DECREF(retval);
+ Py_DECREF(args);
+ if (! v) return NULL;
+ retval=v;
+ }
+ }
+ else
+ if (args) retval=args;
+ else {
+ PyErr_SetObject(ErrType,Py_None);
+ return NULL;
+ }
+ PyErr_SetObject(ErrType,retval);
+ Py_DECREF(retval);
+ return NULL;
}
static int
write_file(Picklerobject *self, const char *s, Py_ssize_t n)
{
- size_t nbyteswritten;
+ size_t nbyteswritten;
- if (s == NULL) {
- return 0;
- }
+ if (s == NULL) {
+ return 0;
+ }
- if (n > INT_MAX) {
- /* String too large */
- return -1;
- }
+ if (n > INT_MAX) {
+ /* String too large */
+ return -1;
+ }
- PyFile_IncUseCount((PyFileObject *)self->file);
- Py_BEGIN_ALLOW_THREADS
- nbyteswritten = fwrite(s, sizeof(char), n, self->fp);
- Py_END_ALLOW_THREADS
- PyFile_DecUseCount((PyFileObject *)self->file);
- if (nbyteswritten != (size_t)n) {
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
+ PyFile_IncUseCount((PyFileObject *)self->file);
+ Py_BEGIN_ALLOW_THREADS
+ nbyteswritten = fwrite(s, sizeof(char), n, self->fp);
+ Py_END_ALLOW_THREADS
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ if (nbyteswritten != (size_t)n) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
- return (int)n;
+ return (int)n;
}
static int
write_cStringIO(Picklerobject *self, const char *s, Py_ssize_t n)
{
- if (s == NULL) {
- return 0;
- }
+ if (s == NULL) {
+ return 0;
+ }
- if (PycStringIO->cwrite((PyObject *)self->file, s, n) != n) {
- return -1;
- }
+ if (PycStringIO->cwrite((PyObject *)self->file, s, n) != n) {
+ return -1;
+ }
- return (int)n;
+ return (int)n;
}
static int
write_none(Picklerobject *self, const char *s, Py_ssize_t n)
{
- if (s == NULL) return 0;
- if (n > INT_MAX) return -1;
- return (int)n;
+ if (s == NULL) return 0;
+ if (n > INT_MAX) return -1;
+ return (int)n;
}
static int
write_other(Picklerobject *self, const char *s, Py_ssize_t _n)
{
- PyObject *py_str = 0, *junk = 0;
- int n;
-
- if (_n > INT_MAX)
- return -1;
- n = (int)_n;
- if (s == NULL) {
- if (!( self->buf_size )) return 0;
- py_str = PyString_FromStringAndSize(self->write_buf,
- self->buf_size);
- if (!py_str)
- return -1;
- }
- else {
- if (self->buf_size && (n + self->buf_size) > WRITE_BUF_SIZE) {
- if (write_other(self, NULL, 0) < 0)
- return -1;
- }
-
- if (n > WRITE_BUF_SIZE) {
- if (!( py_str =
- PyString_FromStringAndSize(s, n)))
- return -1;
- }
- else {
- memcpy(self->write_buf + self->buf_size, s, n);
- self->buf_size += n;
- return n;
- }
- }
-
- if (self->write) {
- /* object with write method */
- ARG_TUP(self, py_str);
- if (self->arg) {
- junk = PyObject_Call(self->write, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- if (junk) Py_DECREF(junk);
- else return -1;
- }
- else
- PDATA_PUSH(self->file, py_str, -1);
-
- self->buf_size = 0;
- return n;
+ PyObject *py_str = 0, *junk = 0;
+ int n;
+
+ if (_n > INT_MAX)
+ return -1;
+ n = (int)_n;
+ if (s == NULL) {
+ if (!( self->buf_size )) return 0;
+ py_str = PyString_FromStringAndSize(self->write_buf,
+ self->buf_size);
+ if (!py_str)
+ return -1;
+ }
+ else {
+ if (self->buf_size && (n + self->buf_size) > WRITE_BUF_SIZE) {
+ if (write_other(self, NULL, 0) < 0)
+ return -1;
+ }
+
+ if (n > WRITE_BUF_SIZE) {
+ if (!( py_str =
+ PyString_FromStringAndSize(s, n)))
+ return -1;
+ }
+ else {
+ memcpy(self->write_buf + self->buf_size, s, n);
+ self->buf_size += n;
+ return n;
+ }
+ }
+
+ if (self->write) {
+ /* object with write method */
+ ARG_TUP(self, py_str);
+ if (self->arg) {
+ junk = PyObject_Call(self->write, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (junk) Py_DECREF(junk);
+ else return -1;
+ }
+ else
+ PDATA_PUSH(self->file, py_str, -1);
+
+ self->buf_size = 0;
+ return n;
}
static Py_ssize_t
read_file(Unpicklerobject *self, char **s, Py_ssize_t n)
{
- size_t nbytesread;
+ size_t nbytesread;
- if (self->buf_size == 0) {
- int size;
+ if (self->buf_size == 0) {
+ int size;
- size = ((n < 32) ? 32 : n);
- if (!( self->buf = (char *)malloc(size))) {
- PyErr_NoMemory();
- return -1;
- }
+ size = ((n < 32) ? 32 : n);
+ if (!( self->buf = (char *)malloc(size))) {
+ PyErr_NoMemory();
+ return -1;
+ }
- self->buf_size = size;
- }
- else if (n > self->buf_size) {
- char *newbuf = (char *)realloc(self->buf, n);
- if (!newbuf) {
- PyErr_NoMemory();
- return -1;
- }
- self->buf = newbuf;
- self->buf_size = n;
- }
+ self->buf_size = size;
+ }
+ else if (n > self->buf_size) {
+ char *newbuf = (char *)realloc(self->buf, n);
+ if (!newbuf) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->buf = newbuf;
+ self->buf_size = n;
+ }
- PyFile_IncUseCount((PyFileObject *)self->file);
- Py_BEGIN_ALLOW_THREADS
- nbytesread = fread(self->buf, sizeof(char), n, self->fp);
- Py_END_ALLOW_THREADS
- PyFile_DecUseCount((PyFileObject *)self->file);
- if (nbytesread != (size_t)n) {
- if (feof(self->fp)) {
- PyErr_SetNone(PyExc_EOFError);
- return -1;
- }
+ PyFile_IncUseCount((PyFileObject *)self->file);
+ Py_BEGIN_ALLOW_THREADS
+ nbytesread = fread(self->buf, sizeof(char), n, self->fp);
+ Py_END_ALLOW_THREADS
+ PyFile_DecUseCount((PyFileObject *)self->file);
+ if (nbytesread != (size_t)n) {
+ if (feof(self->fp)) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
- *s = self->buf;
+ *s = self->buf;
- return n;
+ return n;
}
static Py_ssize_t
readline_file(Unpicklerobject *self, char **s)
{
- int i;
-
- if (self->buf_size == 0) {
- if (!( self->buf = (char *)malloc(40))) {
- PyErr_NoMemory();
- return -1;
- }
- self->buf_size = 40;
- }
-
- i = 0;
- while (1) {
- int bigger;
- char *newbuf;
- for (; i < (self->buf_size - 1); i++) {
- if (feof(self->fp) ||
- (self->buf[i] = getc(self->fp)) == '\n') {
- self->buf[i + 1] = '\0';
- *s = self->buf;
- return i + 1;
- }
- }
- bigger = self->buf_size << 1;
- if (bigger <= 0) { /* overflow */
- PyErr_NoMemory();
- return -1;
- }
- newbuf = (char *)realloc(self->buf, bigger);
- if (!newbuf) {
- PyErr_NoMemory();
- return -1;
- }
- self->buf = newbuf;
- self->buf_size = bigger;
- }
+ int i;
+
+ if (self->buf_size == 0) {
+ if (!( self->buf = (char *)malloc(40))) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->buf_size = 40;
+ }
+
+ i = 0;
+ while (1) {
+ int bigger;
+ char *newbuf;
+ for (; i < (self->buf_size - 1); i++) {
+ if (feof(self->fp) ||
+ (self->buf[i] = getc(self->fp)) == '\n') {
+ self->buf[i + 1] = '\0';
+ *s = self->buf;
+ return i + 1;
+ }
+ }
+ bigger = self->buf_size << 1;
+ if (bigger <= 0) { /* overflow */
+ PyErr_NoMemory();
+ return -1;
+ }
+ newbuf = (char *)realloc(self->buf, bigger);
+ if (!newbuf) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->buf = newbuf;
+ self->buf_size = bigger;
+ }
}
static Py_ssize_t
read_cStringIO(Unpicklerobject *self, char **s, Py_ssize_t n)
{
- char *ptr;
+ char *ptr;
- if (PycStringIO->cread((PyObject *)self->file, &ptr, n) != n) {
- PyErr_SetNone(PyExc_EOFError);
- return -1;
- }
+ if (PycStringIO->cread((PyObject *)self->file, &ptr, n) != n) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
- *s = ptr;
+ *s = ptr;
- return n;
+ return n;
}
static Py_ssize_t
readline_cStringIO(Unpicklerobject *self, char **s)
{
- Py_ssize_t n;
- char *ptr;
+ Py_ssize_t n;
+ char *ptr;
- if ((n = PycStringIO->creadline((PyObject *)self->file, &ptr)) < 0) {
- return -1;
- }
+ if ((n = PycStringIO->creadline((PyObject *)self->file, &ptr)) < 0) {
+ return -1;
+ }
- *s = ptr;
+ *s = ptr;
- return n;
+ return n;
}
static Py_ssize_t
read_other(Unpicklerobject *self, char **s, Py_ssize_t n)
{
- PyObject *bytes, *str=0;
+ PyObject *bytes, *str=0;
- if (!( bytes = PyInt_FromSsize_t(n))) return -1;
+ if (!( bytes = PyInt_FromSsize_t(n))) return -1;
- ARG_TUP(self, bytes);
- if (self->arg) {
- str = PyObject_Call(self->read, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- if (! str) return -1;
+ ARG_TUP(self, bytes);
+ if (self->arg) {
+ str = PyObject_Call(self->read, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! str) return -1;
- Py_XDECREF(self->last_string);
- self->last_string = str;
+ Py_XDECREF(self->last_string);
+ self->last_string = str;
- if (! (*s = PyString_AsString(str))) return -1;
+ if (! (*s = PyString_AsString(str))) return -1;
- if (PyString_GET_SIZE(str) != n) {
- PyErr_SetNone(PyExc_EOFError);
- return -1;
- }
+ if (PyString_GET_SIZE(str) != n) {
+ PyErr_SetNone(PyExc_EOFError);
+ return -1;
+ }
- return n;
+ return n;
}
static Py_ssize_t
readline_other(Unpicklerobject *self, char **s)
{
- PyObject *str;
- Py_ssize_t str_size;
+ PyObject *str;
+ Py_ssize_t str_size;
- if (!( str = PyObject_CallObject(self->readline, empty_tuple))) {
- return -1;
- }
+ if (!( str = PyObject_CallObject(self->readline, empty_tuple))) {
+ return -1;
+ }
- if ((str_size = PyString_Size(str)) < 0)
- return -1;
+ if ((str_size = PyString_Size(str)) < 0)
+ return -1;
- Py_XDECREF(self->last_string);
- self->last_string = str;
+ Py_XDECREF(self->last_string);
+ self->last_string = str;
- if (! (*s = PyString_AsString(str)))
- return -1;
+ if (! (*s = PyString_AsString(str)))
+ return -1;
- return str_size;
+ return str_size;
}
/* Copy the first n bytes from s into newly malloc'ed memory, plus a
@@ -702,577 +702,577 @@ readline_other(Unpicklerobject *self, char **s)
static char *
pystrndup(const char *s, int n)
{
- char *r = (char *)malloc(n+1);
- if (r == NULL)
- return (char*)PyErr_NoMemory();
- memcpy(r, s, n);
- r[n] = 0;
- return r;
+ char *r = (char *)malloc(n+1);
+ if (r == NULL)
+ return (char*)PyErr_NoMemory();
+ memcpy(r, s, n);
+ r[n] = 0;
+ return r;
}
static int
get(Picklerobject *self, PyObject *id)
{
- PyObject *value, *mv;
- long c_value;
- char s[30];
- size_t len;
-
- if (!( mv = PyDict_GetItem(self->memo, id))) {
- PyErr_SetObject(PyExc_KeyError, id);
- return -1;
- }
-
- if (!( value = PyTuple_GetItem(mv, 0)))
- return -1;
-
- if (!( PyInt_Check(value))) {
- PyErr_SetString(PicklingError, "no int where int expected in memo");
- return -1;
- }
- c_value = PyInt_AS_LONG((PyIntObject*)value);
-
- if (!self->bin) {
- s[0] = GET;
- PyOS_snprintf(s + 1, sizeof(s) - 1, "%ld\n", c_value);
- len = strlen(s);
- }
- else if (Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0) return -1;
- PDATA_APPEND(self->file, mv, -1);
- return 0;
- }
- else {
- if (c_value < 256) {
- s[0] = BINGET;
- s[1] = (int)(c_value & 0xff);
- len = 2;
- }
- else {
- s[0] = LONG_BINGET;
- s[1] = (int)(c_value & 0xff);
- s[2] = (int)((c_value >> 8) & 0xff);
- s[3] = (int)((c_value >> 16) & 0xff);
- s[4] = (int)((c_value >> 24) & 0xff);
- len = 5;
- }
- }
-
- if (self->write_func(self, s, len) < 0)
- return -1;
-
- return 0;
+ PyObject *value, *mv;
+ long c_value;
+ char s[30];
+ size_t len;
+
+ if (!( mv = PyDict_GetItem(self->memo, id))) {
+ PyErr_SetObject(PyExc_KeyError, id);
+ return -1;
+ }
+
+ if (!( value = PyTuple_GetItem(mv, 0)))
+ return -1;
+
+ if (!( PyInt_Check(value))) {
+ PyErr_SetString(PicklingError, "no int where int expected in memo");
+ return -1;
+ }
+ c_value = PyInt_AS_LONG((PyIntObject*)value);
+
+ if (!self->bin) {
+ s[0] = GET;
+ PyOS_snprintf(s + 1, sizeof(s) - 1, "%ld\n", c_value);
+ len = strlen(s);
+ }
+ else if (Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0) return -1;
+ PDATA_APPEND(self->file, mv, -1);
+ return 0;
+ }
+ else {
+ if (c_value < 256) {
+ s[0] = BINGET;
+ s[1] = (int)(c_value & 0xff);
+ len = 2;
+ }
+ else {
+ s[0] = LONG_BINGET;
+ s[1] = (int)(c_value & 0xff);
+ s[2] = (int)((c_value >> 8) & 0xff);
+ s[3] = (int)((c_value >> 16) & 0xff);
+ s[4] = (int)((c_value >> 24) & 0xff);
+ len = 5;
+ }
+ }
+
+ if (self->write_func(self, s, len) < 0)
+ return -1;
+
+ return 0;
}
static int
put(Picklerobject *self, PyObject *ob)
{
- if (Py_REFCNT(ob) < 2 || self->fast)
- return 0;
+ if (Py_REFCNT(ob) < 2 || self->fast)
+ return 0;
- return put2(self, ob);
+ return put2(self, ob);
}
static int
put2(Picklerobject *self, PyObject *ob)
{
- char c_str[30];
- int p;
- size_t len;
- int res = -1;
- PyObject *py_ob_id = 0, *memo_len = 0, *t = 0;
-
- if (self->fast)
- return 0;
-
- if ((p = PyDict_Size(self->memo)) < 0)
- goto finally;
-
- /* Make sure memo keys are positive! */
- /* XXX Why?
- * XXX And does "positive" really mean non-negative?
- * XXX pickle.py starts with PUT index 0, not 1. This makes for
- * XXX gratuitous differences between the pickling modules.
- */
- p++;
-
- if (!( py_ob_id = PyLong_FromVoidPtr(ob)))
- goto finally;
-
- if (!( memo_len = PyInt_FromLong(p)))
- goto finally;
-
- if (!( t = PyTuple_New(2)))
- goto finally;
-
- PyTuple_SET_ITEM(t, 0, memo_len);
- Py_INCREF(memo_len);
- PyTuple_SET_ITEM(t, 1, ob);
- Py_INCREF(ob);
-
- if (PyDict_SetItem(self->memo, py_ob_id, t) < 0)
- goto finally;
-
- if (!self->bin) {
- c_str[0] = PUT;
- PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%d\n", p);
- len = strlen(c_str);
- }
- else if (Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0) return -1;
- PDATA_APPEND(self->file, memo_len, -1);
- res=0; /* Job well done ;) */
- goto finally;
- }
- else {
- if (p >= 256) {
- c_str[0] = LONG_BINPUT;
- c_str[1] = (int)(p & 0xff);
- c_str[2] = (int)((p >> 8) & 0xff);
- c_str[3] = (int)((p >> 16) & 0xff);
- c_str[4] = (int)((p >> 24) & 0xff);
- len = 5;
- }
- else {
- c_str[0] = BINPUT;
- c_str[1] = p;
- len = 2;
- }
- }
-
- if (self->write_func(self, c_str, len) < 0)
- goto finally;
-
- res = 0;
+ char c_str[30];
+ int p;
+ size_t len;
+ int res = -1;
+ PyObject *py_ob_id = 0, *memo_len = 0, *t = 0;
+
+ if (self->fast)
+ return 0;
+
+ if ((p = PyDict_Size(self->memo)) < 0)
+ goto finally;
+
+ /* Make sure memo keys are positive! */
+ /* XXX Why?
+ * XXX And does "positive" really mean non-negative?
+ * XXX pickle.py starts with PUT index 0, not 1. This makes for
+ * XXX gratuitous differences between the pickling modules.
+ */
+ p++;
+
+ if (!( py_ob_id = PyLong_FromVoidPtr(ob)))
+ goto finally;
+
+ if (!( memo_len = PyInt_FromLong(p)))
+ goto finally;
+
+ if (!( t = PyTuple_New(2)))
+ goto finally;
+
+ PyTuple_SET_ITEM(t, 0, memo_len);
+ Py_INCREF(memo_len);
+ PyTuple_SET_ITEM(t, 1, ob);
+ Py_INCREF(ob);
+
+ if (PyDict_SetItem(self->memo, py_ob_id, t) < 0)
+ goto finally;
+
+ if (!self->bin) {
+ c_str[0] = PUT;
+ PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%d\n", p);
+ len = strlen(c_str);
+ }
+ else if (Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0) return -1;
+ PDATA_APPEND(self->file, memo_len, -1);
+ res=0; /* Job well done ;) */
+ goto finally;
+ }
+ else {
+ if (p >= 256) {
+ c_str[0] = LONG_BINPUT;
+ c_str[1] = (int)(p & 0xff);
+ c_str[2] = (int)((p >> 8) & 0xff);
+ c_str[3] = (int)((p >> 16) & 0xff);
+ c_str[4] = (int)((p >> 24) & 0xff);
+ len = 5;
+ }
+ else {
+ c_str[0] = BINPUT;
+ c_str[1] = p;
+ len = 2;
+ }
+ }
+
+ if (self->write_func(self, c_str, len) < 0)
+ goto finally;
+
+ res = 0;
finally:
- Py_XDECREF(py_ob_id);
- Py_XDECREF(memo_len);
- Py_XDECREF(t);
+ Py_XDECREF(py_ob_id);
+ Py_XDECREF(memo_len);
+ Py_XDECREF(t);
- return res;
+ return res;
}
static PyObject *
whichmodule(PyObject *global, PyObject *global_name)
{
- Py_ssize_t i, j;
- PyObject *module = 0, *modules_dict = 0,
- *global_name_attr = 0, *name = 0;
+ Py_ssize_t i, j;
+ PyObject *module = 0, *modules_dict = 0,
+ *global_name_attr = 0, *name = 0;
- module = PyObject_GetAttrString(global, "__module__");
- if (module)
- return module;
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return NULL;
+ module = PyObject_GetAttrString(global, "__module__");
+ if (module)
+ return module;
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
- if (!( modules_dict = PySys_GetObject("modules")))
- return NULL;
+ if (!( modules_dict = PySys_GetObject("modules")))
+ return NULL;
- i = 0;
- while ((j = PyDict_Next(modules_dict, &i, &name, &module))) {
+ i = 0;
+ while ((j = PyDict_Next(modules_dict, &i, &name, &module))) {
- if (PyObject_Compare(name, __main___str)==0) continue;
+ if (PyObject_Compare(name, __main___str)==0) continue;
- global_name_attr = PyObject_GetAttr(module, global_name);
- if (!global_name_attr) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return NULL;
- continue;
- }
+ global_name_attr = PyObject_GetAttr(module, global_name);
+ if (!global_name_attr) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
+ continue;
+ }
- if (global_name_attr != global) {
- Py_DECREF(global_name_attr);
- continue;
- }
+ if (global_name_attr != global) {
+ Py_DECREF(global_name_attr);
+ continue;
+ }
- Py_DECREF(global_name_attr);
+ Py_DECREF(global_name_attr);
- break;
- }
+ break;
+ }
- /* The following implements the rule in pickle.py added in 1.5
- that used __main__ if no module is found. I don't actually
- like this rule. jlf
- */
- if (!j) {
- name=__main___str;
- }
+ /* The following implements the rule in pickle.py added in 1.5
+ that used __main__ if no module is found. I don't actually
+ like this rule. jlf
+ */
+ if (!j) {
+ name=__main___str;
+ }
- Py_INCREF(name);
- return name;
+ Py_INCREF(name);
+ return name;
}
static int
fast_save_enter(Picklerobject *self, PyObject *obj)
{
- /* if fast_container < 0, we're doing an error exit. */
- if (++self->fast_container >= PY_CPICKLE_FAST_LIMIT) {
- PyObject *key = NULL;
- if (self->fast_memo == NULL) {
- self->fast_memo = PyDict_New();
- if (self->fast_memo == NULL) {
- self->fast_container = -1;
- return 0;
- }
- }
- key = PyLong_FromVoidPtr(obj);
- if (key == NULL)
- return 0;
- if (PyDict_GetItem(self->fast_memo, key)) {
- Py_DECREF(key);
- PyErr_Format(PyExc_ValueError,
- "fast mode: can't pickle cyclic objects "
- "including object type %s at %p",
- Py_TYPE(obj)->tp_name, obj);
- self->fast_container = -1;
- return 0;
- }
- if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) {
- Py_DECREF(key);
- self->fast_container = -1;
- return 0;
- }
- Py_DECREF(key);
- }
- return 1;
+ /* if fast_container < 0, we're doing an error exit. */
+ if (++self->fast_container >= PY_CPICKLE_FAST_LIMIT) {
+ PyObject *key = NULL;
+ if (self->fast_memo == NULL) {
+ self->fast_memo = PyDict_New();
+ if (self->fast_memo == NULL) {
+ self->fast_container = -1;
+ return 0;
+ }
+ }
+ key = PyLong_FromVoidPtr(obj);
+ if (key == NULL)
+ return 0;
+ if (PyDict_GetItem(self->fast_memo, key)) {
+ Py_DECREF(key);
+ PyErr_Format(PyExc_ValueError,
+ "fast mode: can't pickle cyclic objects "
+ "including object type %s at %p",
+ Py_TYPE(obj)->tp_name, obj);
+ self->fast_container = -1;
+ return 0;
+ }
+ if (PyDict_SetItem(self->fast_memo, key, Py_None) < 0) {
+ Py_DECREF(key);
+ self->fast_container = -1;
+ return 0;
+ }
+ Py_DECREF(key);
+ }
+ return 1;
}
int
fast_save_leave(Picklerobject *self, PyObject *obj)
{
- if (self->fast_container-- >= PY_CPICKLE_FAST_LIMIT) {
- PyObject *key = PyLong_FromVoidPtr(obj);
- if (key == NULL)
- return 0;
- if (PyDict_DelItem(self->fast_memo, key) < 0) {
- Py_DECREF(key);
- return 0;
- }
- Py_DECREF(key);
- }
- return 1;
+ if (self->fast_container-- >= PY_CPICKLE_FAST_LIMIT) {
+ PyObject *key = PyLong_FromVoidPtr(obj);
+ if (key == NULL)
+ return 0;
+ if (PyDict_DelItem(self->fast_memo, key) < 0) {
+ Py_DECREF(key);
+ return 0;
+ }
+ Py_DECREF(key);
+ }
+ return 1;
}
static int
save_none(Picklerobject *self, PyObject *args)
{
- static char none = NONE;
- if (self->write_func(self, &none, 1) < 0)
- return -1;
+ static char none = NONE;
+ if (self->write_func(self, &none, 1) < 0)
+ return -1;
- return 0;
+ return 0;
}
static int
save_bool(Picklerobject *self, PyObject *args)
{
- static const char *buf[2] = {FALSE, TRUE};
- static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1};
- long l = PyInt_AS_LONG((PyIntObject *)args);
+ static const char *buf[2] = {FALSE, TRUE};
+ static char len[2] = {sizeof(FALSE)-1, sizeof(TRUE)-1};
+ long l = PyInt_AS_LONG((PyIntObject *)args);
- if (self->proto >= 2) {
- char opcode = l ? NEWTRUE : NEWFALSE;
- if (self->write_func(self, &opcode, 1) < 0)
- return -1;
- }
- else if (self->write_func(self, buf[l], len[l]) < 0)
- return -1;
- return 0;
+ if (self->proto >= 2) {
+ char opcode = l ? NEWTRUE : NEWFALSE;
+ if (self->write_func(self, &opcode, 1) < 0)
+ return -1;
+ }
+ else if (self->write_func(self, buf[l], len[l]) < 0)
+ return -1;
+ return 0;
}
static int
save_int(Picklerobject *self, PyObject *args)
{
- char c_str[32];
- long l = PyInt_AS_LONG((PyIntObject *)args);
- int len = 0;
+ char c_str[32];
+ long l = PyInt_AS_LONG((PyIntObject *)args);
+ int len = 0;
- if (!self->bin
+ if (!self->bin
#if SIZEOF_LONG > 4
- || l > 0x7fffffffL
- || l < -0x80000000L
+ || l > 0x7fffffffL
+ || l < -0x80000000L
#endif
- ) {
- /* Text-mode pickle, or long too big to fit in the 4-byte
- * signed BININT format: store as a string.
- */
- c_str[0] = INT;
- PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%ld\n", l);
- if (self->write_func(self, c_str, strlen(c_str)) < 0)
- return -1;
- }
- else {
- /* Binary pickle and l fits in a signed 4-byte int. */
- c_str[1] = (int)( l & 0xff);
- c_str[2] = (int)((l >> 8) & 0xff);
- c_str[3] = (int)((l >> 16) & 0xff);
- c_str[4] = (int)((l >> 24) & 0xff);
-
- if ((c_str[4] == 0) && (c_str[3] == 0)) {
- if (c_str[2] == 0) {
- c_str[0] = BININT1;
- len = 2;
- }
- else {
- c_str[0] = BININT2;
- len = 3;
- }
- }
- else {
- c_str[0] = BININT;
- len = 5;
- }
-
- if (self->write_func(self, c_str, len) < 0)
- return -1;
- }
-
- return 0;
+ ) {
+ /* Text-mode pickle, or long too big to fit in the 4-byte
+ * signed BININT format: store as a string.
+ */
+ c_str[0] = INT;
+ PyOS_snprintf(c_str + 1, sizeof(c_str) - 1, "%ld\n", l);
+ if (self->write_func(self, c_str, strlen(c_str)) < 0)
+ return -1;
+ }
+ else {
+ /* Binary pickle and l fits in a signed 4-byte int. */
+ c_str[1] = (int)( l & 0xff);
+ c_str[2] = (int)((l >> 8) & 0xff);
+ c_str[3] = (int)((l >> 16) & 0xff);
+ c_str[4] = (int)((l >> 24) & 0xff);
+
+ if ((c_str[4] == 0) && (c_str[3] == 0)) {
+ if (c_str[2] == 0) {
+ c_str[0] = BININT1;
+ len = 2;
+ }
+ else {
+ c_str[0] = BININT2;
+ len = 3;
+ }
+ }
+ else {
+ c_str[0] = BININT;
+ len = 5;
+ }
+
+ if (self->write_func(self, c_str, len) < 0)
+ return -1;
+ }
+
+ return 0;
}
static int
save_long(Picklerobject *self, PyObject *args)
{
- Py_ssize_t size;
- int res = -1;
- PyObject *repr = NULL;
-
- static char l = LONG;
-
- if (self->proto >= 2) {
- /* Linear-time pickling. */
- size_t nbits;
- size_t nbytes;
- unsigned char *pdata;
- char c_str[5];
- int i;
- int sign = _PyLong_Sign(args);
-
- if (sign == 0) {
- /* It's 0 -- an empty bytestring. */
- c_str[0] = LONG1;
- c_str[1] = 0;
- i = self->write_func(self, c_str, 2);
- if (i < 0) goto finally;
- res = 0;
- goto finally;
- }
- nbits = _PyLong_NumBits(args);
- if (nbits == (size_t)-1 && PyErr_Occurred())
- goto finally;
- /* How many bytes do we need? There are nbits >> 3 full
- * bytes of data, and nbits & 7 leftover bits. If there
- * are any leftover bits, then we clearly need another
- * byte. Wnat's not so obvious is that we *probably*
- * need another byte even if there aren't any leftovers:
- * the most-significant bit of the most-significant byte
- * acts like a sign bit, and it's usually got a sense
- * opposite of the one we need. The exception is longs
- * of the form -(2**(8*j-1)) for j > 0. Such a long is
- * its own 256's-complement, so has the right sign bit
- * even without the extra byte. That's a pain to check
- * for in advance, though, so we always grab an extra
- * byte at the start, and cut it back later if possible.
- */
- nbytes = (nbits >> 3) + 1;
- if (nbytes > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError, "long too large "
- "to pickle");
- goto finally;
- }
- repr = PyString_FromStringAndSize(NULL, (int)nbytes);
- if (repr == NULL) goto finally;
- pdata = (unsigned char *)PyString_AS_STRING(repr);
- i = _PyLong_AsByteArray((PyLongObject *)args,
- pdata, nbytes,
- 1 /* little endian */, 1 /* signed */);
- if (i < 0) goto finally;
- /* If the long is negative, this may be a byte more than
- * needed. This is so iff the MSB is all redundant sign
- * bits.
- */
- if (sign < 0 && nbytes > 1 && pdata[nbytes - 1] == 0xff &&
- (pdata[nbytes - 2] & 0x80) != 0)
- --nbytes;
-
- if (nbytes < 256) {
- c_str[0] = LONG1;
- c_str[1] = (char)nbytes;
- size = 2;
- }
- else {
- c_str[0] = LONG4;
- size = (int)nbytes;
- for (i = 1; i < 5; i++) {
- c_str[i] = (char)(size & 0xff);
- size >>= 8;
- }
- size = 5;
- }
- i = self->write_func(self, c_str, size);
- if (i < 0) goto finally;
- i = self->write_func(self, (char *)pdata, (int)nbytes);
- if (i < 0) goto finally;
- res = 0;
- goto finally;
- }
-
- /* proto < 2: write the repr and newline. This is quadratic-time
- * (in the number of digits), in both directions.
- */
- if (!( repr = PyObject_Repr(args)))
- goto finally;
-
- if ((size = PyString_Size(repr)) < 0)
- goto finally;
-
- if (self->write_func(self, &l, 1) < 0)
- goto finally;
-
- if (self->write_func(self,
- PyString_AS_STRING((PyStringObject *)repr),
- size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
-
- res = 0;
+ Py_ssize_t size;
+ int res = -1;
+ PyObject *repr = NULL;
+
+ static char l = LONG;
+
+ if (self->proto >= 2) {
+ /* Linear-time pickling. */
+ size_t nbits;
+ size_t nbytes;
+ unsigned char *pdata;
+ char c_str[5];
+ int i;
+ int sign = _PyLong_Sign(args);
+
+ if (sign == 0) {
+ /* It's 0 -- an empty bytestring. */
+ c_str[0] = LONG1;
+ c_str[1] = 0;
+ i = self->write_func(self, c_str, 2);
+ if (i < 0) goto finally;
+ res = 0;
+ goto finally;
+ }
+ nbits = _PyLong_NumBits(args);
+ if (nbits == (size_t)-1 && PyErr_Occurred())
+ goto finally;
+ /* How many bytes do we need? There are nbits >> 3 full
+ * bytes of data, and nbits & 7 leftover bits. If there
+ * are any leftover bits, then we clearly need another
+ * byte. Wnat's not so obvious is that we *probably*
+ * need another byte even if there aren't any leftovers:
+ * the most-significant bit of the most-significant byte
+ * acts like a sign bit, and it's usually got a sense
+ * opposite of the one we need. The exception is longs
+ * of the form -(2**(8*j-1)) for j > 0. Such a long is
+ * its own 256's-complement, so has the right sign bit
+ * even without the extra byte. That's a pain to check
+ * for in advance, though, so we always grab an extra
+ * byte at the start, and cut it back later if possible.
+ */
+ nbytes = (nbits >> 3) + 1;
+ if (nbytes > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError, "long too large "
+ "to pickle");
+ goto finally;
+ }
+ repr = PyString_FromStringAndSize(NULL, (int)nbytes);
+ if (repr == NULL) goto finally;
+ pdata = (unsigned char *)PyString_AS_STRING(repr);
+ i = _PyLong_AsByteArray((PyLongObject *)args,
+ pdata, nbytes,
+ 1 /* little endian */, 1 /* signed */);
+ if (i < 0) goto finally;
+ /* If the long is negative, this may be a byte more than
+ * needed. This is so iff the MSB is all redundant sign
+ * bits.
+ */
+ if (sign < 0 && nbytes > 1 && pdata[nbytes - 1] == 0xff &&
+ (pdata[nbytes - 2] & 0x80) != 0)
+ --nbytes;
+
+ if (nbytes < 256) {
+ c_str[0] = LONG1;
+ c_str[1] = (char)nbytes;
+ size = 2;
+ }
+ else {
+ c_str[0] = LONG4;
+ size = (int)nbytes;
+ for (i = 1; i < 5; i++) {
+ c_str[i] = (char)(size & 0xff);
+ size >>= 8;
+ }
+ size = 5;
+ }
+ i = self->write_func(self, c_str, size);
+ if (i < 0) goto finally;
+ i = self->write_func(self, (char *)pdata, (int)nbytes);
+ if (i < 0) goto finally;
+ res = 0;
+ goto finally;
+ }
+
+ /* proto < 2: write the repr and newline. This is quadratic-time
+ * (in the number of digits), in both directions.
+ */
+ if (!( repr = PyObject_Repr(args)))
+ goto finally;
+
+ if ((size = PyString_Size(repr)) < 0)
+ goto finally;
+
+ if (self->write_func(self, &l, 1) < 0)
+ goto finally;
+
+ if (self->write_func(self,
+ PyString_AS_STRING((PyStringObject *)repr),
+ size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+
+ res = 0;
finally:
- Py_XDECREF(repr);
- return res;
+ Py_XDECREF(repr);
+ return res;
}
static int
save_float(Picklerobject *self, PyObject *args)
{
- double x = PyFloat_AS_DOUBLE((PyFloatObject *)args);
-
- if (self->bin) {
- char str[9];
- str[0] = BINFLOAT;
- if (_PyFloat_Pack8(x, (unsigned char *)&str[1], 0) < 0)
- return -1;
- if (self->write_func(self, str, 9) < 0)
- return -1;
- }
- else {
- int result = -1;
- char *buf = NULL;
- char op = FLOAT;
-
- if (self->write_func(self, &op, 1) < 0)
- goto done;
-
- buf = PyOS_double_to_string(x, 'g', 17, 0, NULL);
- if (!buf) {
- PyErr_NoMemory();
- goto done;
- }
-
- if (self->write_func(self, buf, strlen(buf)) < 0)
- goto done;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto done;
-
- result = 0;
+ double x = PyFloat_AS_DOUBLE((PyFloatObject *)args);
+
+ if (self->bin) {
+ char str[9];
+ str[0] = BINFLOAT;
+ if (_PyFloat_Pack8(x, (unsigned char *)&str[1], 0) < 0)
+ return -1;
+ if (self->write_func(self, str, 9) < 0)
+ return -1;
+ }
+ else {
+ int result = -1;
+ char *buf = NULL;
+ char op = FLOAT;
+
+ if (self->write_func(self, &op, 1) < 0)
+ goto done;
+
+ buf = PyOS_double_to_string(x, 'g', 17, 0, NULL);
+ if (!buf) {
+ PyErr_NoMemory();
+ goto done;
+ }
+
+ if (self->write_func(self, buf, strlen(buf)) < 0)
+ goto done;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto done;
+
+ result = 0;
done:
- PyMem_Free(buf);
- return result;
- }
+ PyMem_Free(buf);
+ return result;
+ }
- return 0;
+ return 0;
}
static int
save_string(Picklerobject *self, PyObject *args, int doput)
{
- int size, len;
- PyObject *repr=0;
-
- if ((size = PyString_Size(args)) < 0)
- return -1;
-
- if (!self->bin) {
- char *repr_str;
-
- static char string = STRING;
-
- if (!( repr = PyObject_Repr(args)))
- return -1;
-
- if ((len = PyString_Size(repr)) < 0)
- goto err;
- repr_str = PyString_AS_STRING((PyStringObject *)repr);
-
- if (self->write_func(self, &string, 1) < 0)
- goto err;
-
- if (self->write_func(self, repr_str, len) < 0)
- goto err;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto err;
-
- Py_XDECREF(repr);
- }
- else {
- int i;
- char c_str[5];
-
- if (size < 256) {
- c_str[0] = SHORT_BINSTRING;
- c_str[1] = size;
- len = 2;
- }
- else if (size <= INT_MAX) {
- c_str[0] = BINSTRING;
- for (i = 1; i < 5; i++)
- c_str[i] = (int)(size >> ((i - 1) * 8));
- len = 5;
- }
- else
- return -1; /* string too large */
-
- if (self->write_func(self, c_str, len) < 0)
- return -1;
-
- if (size > 128 && Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0) return -1;
- PDATA_APPEND(self->file, args, -1);
- }
- else {
- if (self->write_func(self,
- PyString_AS_STRING(
- (PyStringObject *)args),
- size) < 0)
- return -1;
- }
- }
-
- if (doput)
- if (put(self, args) < 0)
- return -1;
-
- return 0;
+ int size, len;
+ PyObject *repr=0;
+
+ if ((size = PyString_Size(args)) < 0)
+ return -1;
+
+ if (!self->bin) {
+ char *repr_str;
+
+ static char string = STRING;
+
+ if (!( repr = PyObject_Repr(args)))
+ return -1;
+
+ if ((len = PyString_Size(repr)) < 0)
+ goto err;
+ repr_str = PyString_AS_STRING((PyStringObject *)repr);
+
+ if (self->write_func(self, &string, 1) < 0)
+ goto err;
+
+ if (self->write_func(self, repr_str, len) < 0)
+ goto err;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto err;
+
+ Py_XDECREF(repr);
+ }
+ else {
+ int i;
+ char c_str[5];
+
+ if (size < 256) {
+ c_str[0] = SHORT_BINSTRING;
+ c_str[1] = size;
+ len = 2;
+ }
+ else if (size <= INT_MAX) {
+ c_str[0] = BINSTRING;
+ for (i = 1; i < 5; i++)
+ c_str[i] = (int)(size >> ((i - 1) * 8));
+ len = 5;
+ }
+ else
+ return -1; /* string too large */
+
+ if (self->write_func(self, c_str, len) < 0)
+ return -1;
+
+ if (size > 128 && Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0) return -1;
+ PDATA_APPEND(self->file, args, -1);
+ }
+ else {
+ if (self->write_func(self,
+ PyString_AS_STRING(
+ (PyStringObject *)args),
+ size) < 0)
+ return -1;
+ }
+ }
+
+ if (doput)
+ if (put(self, args) < 0)
+ return -1;
+
+ return 0;
err:
- Py_XDECREF(repr);
- return -1;
+ Py_XDECREF(repr);
+ return -1;
}
@@ -1294,71 +1294,71 @@ modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
#endif
if (size > PY_SSIZE_T_MAX / expandsize)
- return PyErr_NoMemory();
+ return PyErr_NoMemory();
repr = PyString_FromStringAndSize(NULL, expandsize * size);
if (repr == NULL)
- return NULL;
+ return NULL;
if (size == 0)
- return repr;
+ return repr;
p = q = PyString_AS_STRING(repr);
while (size-- > 0) {
- Py_UNICODE ch = *s++;
+ Py_UNICODE ch = *s++;
#ifdef Py_UNICODE_WIDE
- /* Map 32-bit characters to '\Uxxxxxxxx' */
- if (ch >= 0x10000) {
- *p++ = '\\';
- *p++ = 'U';
- *p++ = hexdigit[(ch >> 28) & 0xf];
- *p++ = hexdigit[(ch >> 24) & 0xf];
- *p++ = hexdigit[(ch >> 20) & 0xf];
- *p++ = hexdigit[(ch >> 16) & 0xf];
- *p++ = hexdigit[(ch >> 12) & 0xf];
- *p++ = hexdigit[(ch >> 8) & 0xf];
- *p++ = hexdigit[(ch >> 4) & 0xf];
- *p++ = hexdigit[ch & 15];
- }
- else
+ /* Map 32-bit characters to '\Uxxxxxxxx' */
+ if (ch >= 0x10000) {
+ *p++ = '\\';
+ *p++ = 'U';
+ *p++ = hexdigit[(ch >> 28) & 0xf];
+ *p++ = hexdigit[(ch >> 24) & 0xf];
+ *p++ = hexdigit[(ch >> 20) & 0xf];
+ *p++ = hexdigit[(ch >> 16) & 0xf];
+ *p++ = hexdigit[(ch >> 12) & 0xf];
+ *p++ = hexdigit[(ch >> 8) & 0xf];
+ *p++ = hexdigit[(ch >> 4) & 0xf];
+ *p++ = hexdigit[ch & 15];
+ }
+ else
#else
- /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
- if (ch >= 0xD800 && ch < 0xDC00) {
- Py_UNICODE ch2;
- Py_UCS4 ucs;
-
- ch2 = *s++;
- size--;
- if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
- ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
- *p++ = '\\';
- *p++ = 'U';
- *p++ = hexdigit[(ucs >> 28) & 0xf];
- *p++ = hexdigit[(ucs >> 24) & 0xf];
- *p++ = hexdigit[(ucs >> 20) & 0xf];
- *p++ = hexdigit[(ucs >> 16) & 0xf];
- *p++ = hexdigit[(ucs >> 12) & 0xf];
- *p++ = hexdigit[(ucs >> 8) & 0xf];
- *p++ = hexdigit[(ucs >> 4) & 0xf];
- *p++ = hexdigit[ucs & 0xf];
- continue;
- }
- /* Fall through: isolated surrogates are copied as-is */
- s--;
- size++;
- }
+ /* Map UTF-16 surrogate pairs to '\U00xxxxxx' */
+ if (ch >= 0xD800 && ch < 0xDC00) {
+ Py_UNICODE ch2;
+ Py_UCS4 ucs;
+
+ ch2 = *s++;
+ size--;
+ if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
+ ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
+ *p++ = '\\';
+ *p++ = 'U';
+ *p++ = hexdigit[(ucs >> 28) & 0xf];
+ *p++ = hexdigit[(ucs >> 24) & 0xf];
+ *p++ = hexdigit[(ucs >> 20) & 0xf];
+ *p++ = hexdigit[(ucs >> 16) & 0xf];
+ *p++ = hexdigit[(ucs >> 12) & 0xf];
+ *p++ = hexdigit[(ucs >> 8) & 0xf];
+ *p++ = hexdigit[(ucs >> 4) & 0xf];
+ *p++ = hexdigit[ucs & 0xf];
+ continue;
+ }
+ /* Fall through: isolated surrogates are copied as-is */
+ s--;
+ size++;
+ }
#endif
- /* Map 16-bit characters to '\uxxxx' */
- if (ch >= 256 || ch == '\\' || ch == '\n') {
- *p++ = '\\';
- *p++ = 'u';
- *p++ = hexdigit[(ch >> 12) & 0xf];
- *p++ = hexdigit[(ch >> 8) & 0xf];
- *p++ = hexdigit[(ch >> 4) & 0xf];
- *p++ = hexdigit[ch & 15];
- }
- /* Copy everything else as-is */
- else
- *p++ = (char) ch;
+ /* Map 16-bit characters to '\uxxxx' */
+ if (ch >= 256 || ch == '\\' || ch == '\n') {
+ *p++ = '\\';
+ *p++ = 'u';
+ *p++ = hexdigit[(ch >> 12) & 0xf];
+ *p++ = hexdigit[(ch >> 8) & 0xf];
+ *p++ = hexdigit[(ch >> 4) & 0xf];
+ *p++ = hexdigit[ch & 15];
+ }
+ /* Copy everything else as-is */
+ else
+ *p++ = (char) ch;
}
*p = '\0';
_PyString_Resize(&repr, p - q);
@@ -1368,79 +1368,79 @@ modified_EncodeRawUnicodeEscape(const Py_UNICODE *s, Py_ssize_t size)
static int
save_unicode(Picklerobject *self, PyObject *args, int doput)
{
- Py_ssize_t size, len;
- PyObject *repr=0;
+ Py_ssize_t size, len;
+ PyObject *repr=0;
- if (!PyUnicode_Check(args))
- return -1;
+ if (!PyUnicode_Check(args))
+ return -1;
- if (!self->bin) {
- char *repr_str;
- static char string = UNICODE;
+ if (!self->bin) {
+ char *repr_str;
+ static char string = UNICODE;
- repr = modified_EncodeRawUnicodeEscape(
- PyUnicode_AS_UNICODE(args), PyUnicode_GET_SIZE(args));
- if (!repr)
- return -1;
+ repr = modified_EncodeRawUnicodeEscape(
+ PyUnicode_AS_UNICODE(args), PyUnicode_GET_SIZE(args));
+ if (!repr)
+ return -1;
- if ((len = PyString_Size(repr)) < 0)
- goto err;
- repr_str = PyString_AS_STRING((PyStringObject *)repr);
+ if ((len = PyString_Size(repr)) < 0)
+ goto err;
+ repr_str = PyString_AS_STRING((PyStringObject *)repr);
- if (self->write_func(self, &string, 1) < 0)
- goto err;
+ if (self->write_func(self, &string, 1) < 0)
+ goto err;
- if (self->write_func(self, repr_str, len) < 0)
- goto err;
+ if (self->write_func(self, repr_str, len) < 0)
+ goto err;
- if (self->write_func(self, "\n", 1) < 0)
- goto err;
+ if (self->write_func(self, "\n", 1) < 0)
+ goto err;
- Py_XDECREF(repr);
- }
- else {
- int i;
- char c_str[5];
-
- if (!( repr = PyUnicode_AsUTF8String(args)))
- return -1;
-
- if ((size = PyString_Size(repr)) < 0)
- goto err;
- if (size > INT_MAX)
- return -1; /* string too large */
-
- c_str[0] = BINUNICODE;
- for (i = 1; i < 5; i++)
- c_str[i] = (int)(size >> ((i - 1) * 8));
- len = 5;
-
- if (self->write_func(self, c_str, len) < 0)
- goto err;
-
- if (size > 128 && Pdata_Check(self->file)) {
- if (write_other(self, NULL, 0) < 0)
- goto err;
- PDATA_APPEND(self->file, repr, -1);
- }
- else {
- if (self->write_func(self, PyString_AS_STRING(repr),
- size) < 0)
- goto err;
- }
+ Py_XDECREF(repr);
+ }
+ else {
+ int i;
+ char c_str[5];
+
+ if (!( repr = PyUnicode_AsUTF8String(args)))
+ return -1;
+
+ if ((size = PyString_Size(repr)) < 0)
+ goto err;
+ if (size > INT_MAX)
+ return -1; /* string too large */
+
+ c_str[0] = BINUNICODE;
+ for (i = 1; i < 5; i++)
+ c_str[i] = (int)(size >> ((i - 1) * 8));
+ len = 5;
+
+ if (self->write_func(self, c_str, len) < 0)
+ goto err;
+
+ if (size > 128 && Pdata_Check(self->file)) {
+ if (write_other(self, NULL, 0) < 0)
+ goto err;
+ PDATA_APPEND(self->file, repr, -1);
+ }
+ else {
+ if (self->write_func(self, PyString_AS_STRING(repr),
+ size) < 0)
+ goto err;
+ }
- Py_DECREF(repr);
- }
+ Py_DECREF(repr);
+ }
- if (doput)
- if (put(self, args) < 0)
- return -1;
+ if (doput)
+ if (put(self, args) < 0)
+ return -1;
- return 0;
+ return 0;
err:
- Py_XDECREF(repr);
- return -1;
+ Py_XDECREF(repr);
+ return -1;
}
#endif
@@ -1448,23 +1448,23 @@ save_unicode(Picklerobject *self, PyObject *args, int doput)
static int
store_tuple_elements(Picklerobject *self, PyObject *t, int len)
{
- int i;
- int res = -1; /* guilty until proved innocent */
+ int i;
+ int res = -1; /* guilty until proved innocent */
- assert(PyTuple_Size(t) == len);
+ assert(PyTuple_Size(t) == len);
- for (i = 0; i < len; i++) {
- PyObject *element = PyTuple_GET_ITEM(t, i);
+ for (i = 0; i < len; i++) {
+ PyObject *element = PyTuple_GET_ITEM(t, i);
- if (element == NULL)
- goto finally;
- if (save(self, element, 0) < 0)
- goto finally;
- }
- res = 0;
+ if (element == NULL)
+ goto finally;
+ if (save(self, element, 0) < 0)
+ goto finally;
+ }
+ res = 0;
finally:
- return res;
+ return res;
}
/* Tuples are ubiquitous in the pickle protocols, so many techniques are
@@ -1476,108 +1476,108 @@ store_tuple_elements(Picklerobject *self, PyObject *t, int len)
static int
save_tuple(Picklerobject *self, PyObject *args)
{
- PyObject *py_tuple_id = NULL;
- int len, i;
- int res = -1;
-
- static char tuple = TUPLE;
- static char pop = POP;
- static char pop_mark = POP_MARK;
- static char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3};
-
- if ((len = PyTuple_Size(args)) < 0)
- goto finally;
-
- if (len == 0) {
- char c_str[2];
-
- if (self->proto) {
- c_str[0] = EMPTY_TUPLE;
- len = 1;
- }
- else {
- c_str[0] = MARK;
- c_str[1] = TUPLE;
- len = 2;
- }
- if (self->write_func(self, c_str, len) >= 0)
- res = 0;
- /* Don't memoize an empty tuple. */
- goto finally;
- }
-
- /* A non-empty tuple. */
-
- /* id(tuple) isn't in the memo now. If it shows up there after
- * saving the tuple elements, the tuple must be recursive, in
- * which case we'll pop everything we put on the stack, and fetch
- * its value from the memo.
- */
- py_tuple_id = PyLong_FromVoidPtr(args);
- if (py_tuple_id == NULL)
- goto finally;
-
- if (len <= 3 && self->proto >= 2) {
- /* Use TUPLE{1,2,3} opcodes. */
- if (store_tuple_elements(self, args, len) < 0)
- goto finally;
- if (PyDict_GetItem(self->memo, py_tuple_id)) {
- /* pop the len elements */
- for (i = 0; i < len; ++i)
- if (self->write_func(self, &pop, 1) < 0)
- goto finally;
- /* fetch from memo */
- if (get(self, py_tuple_id) < 0)
- goto finally;
- res = 0;
- goto finally;
- }
- /* Not recursive. */
- if (self->write_func(self, len2opcode + len, 1) < 0)
- goto finally;
- goto memoize;
- }
-
- /* proto < 2 and len > 0, or proto >= 2 and len > 3.
- * Generate MARK elt1 elt2 ... TUPLE
- */
- if (self->write_func(self, &MARKv, 1) < 0)
- goto finally;
-
- if (store_tuple_elements(self, args, len) < 0)
- goto finally;
-
- if (PyDict_GetItem(self->memo, py_tuple_id)) {
- /* pop the stack stuff we pushed */
- if (self->bin) {
- if (self->write_func(self, &pop_mark, 1) < 0)
- goto finally;
- }
- else {
- /* Note that we pop one more than len, to remove
- * the MARK too.
- */
- for (i = 0; i <= len; i++)
- if (self->write_func(self, &pop, 1) < 0)
- goto finally;
- }
- /* fetch from memo */
- if (get(self, py_tuple_id) >= 0)
- res = 0;
- goto finally;
- }
-
- /* Not recursive. */
- if (self->write_func(self, &tuple, 1) < 0)
- goto finally;
+ PyObject *py_tuple_id = NULL;
+ int len, i;
+ int res = -1;
+
+ static char tuple = TUPLE;
+ static char pop = POP;
+ static char pop_mark = POP_MARK;
+ static char len2opcode[] = {EMPTY_TUPLE, TUPLE1, TUPLE2, TUPLE3};
+
+ if ((len = PyTuple_Size(args)) < 0)
+ goto finally;
+
+ if (len == 0) {
+ char c_str[2];
+
+ if (self->proto) {
+ c_str[0] = EMPTY_TUPLE;
+ len = 1;
+ }
+ else {
+ c_str[0] = MARK;
+ c_str[1] = TUPLE;
+ len = 2;
+ }
+ if (self->write_func(self, c_str, len) >= 0)
+ res = 0;
+ /* Don't memoize an empty tuple. */
+ goto finally;
+ }
+
+ /* A non-empty tuple. */
+
+ /* id(tuple) isn't in the memo now. If it shows up there after
+ * saving the tuple elements, the tuple must be recursive, in
+ * which case we'll pop everything we put on the stack, and fetch
+ * its value from the memo.
+ */
+ py_tuple_id = PyLong_FromVoidPtr(args);
+ if (py_tuple_id == NULL)
+ goto finally;
+
+ if (len <= 3 && self->proto >= 2) {
+ /* Use TUPLE{1,2,3} opcodes. */
+ if (store_tuple_elements(self, args, len) < 0)
+ goto finally;
+ if (PyDict_GetItem(self->memo, py_tuple_id)) {
+ /* pop the len elements */
+ for (i = 0; i < len; ++i)
+ if (self->write_func(self, &pop, 1) < 0)
+ goto finally;
+ /* fetch from memo */
+ if (get(self, py_tuple_id) < 0)
+ goto finally;
+ res = 0;
+ goto finally;
+ }
+ /* Not recursive. */
+ if (self->write_func(self, len2opcode + len, 1) < 0)
+ goto finally;
+ goto memoize;
+ }
+
+ /* proto < 2 and len > 0, or proto >= 2 and len > 3.
+ * Generate MARK elt1 elt2 ... TUPLE
+ */
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto finally;
+
+ if (store_tuple_elements(self, args, len) < 0)
+ goto finally;
+
+ if (PyDict_GetItem(self->memo, py_tuple_id)) {
+ /* pop the stack stuff we pushed */
+ if (self->bin) {
+ if (self->write_func(self, &pop_mark, 1) < 0)
+ goto finally;
+ }
+ else {
+ /* Note that we pop one more than len, to remove
+ * the MARK too.
+ */
+ for (i = 0; i <= len; i++)
+ if (self->write_func(self, &pop, 1) < 0)
+ goto finally;
+ }
+ /* fetch from memo */
+ if (get(self, py_tuple_id) >= 0)
+ res = 0;
+ goto finally;
+ }
+
+ /* Not recursive. */
+ if (self->write_func(self, &tuple, 1) < 0)
+ goto finally;
memoize:
- if (put(self, args) >= 0)
- res = 0;
+ if (put(self, args) >= 0)
+ res = 0;
finally:
- Py_XDECREF(py_tuple_id);
- return res;
+ Py_XDECREF(py_tuple_id);
+ return res;
}
/* iter is an iterator giving items, and we batch up chunks of
@@ -1589,157 +1589,157 @@ save_tuple(Picklerobject *self, PyObject *args)
static int
batch_list(Picklerobject *self, PyObject *iter)
{
- PyObject *obj = NULL;
- PyObject *firstitem = NULL;
- int i, n;
-
- static char append = APPEND;
- static char appends = APPENDS;
-
- assert(iter != NULL);
-
- if (self->proto == 0) {
- /* APPENDS isn't available; do one at a time. */
- for (;;) {
- obj = PyIter_Next(iter);
- if (obj == NULL) {
- if (PyErr_Occurred())
- return -1;
- break;
- }
- i = save(self, obj, 0);
- Py_DECREF(obj);
- if (i < 0)
- return -1;
- if (self->write_func(self, &append, 1) < 0)
- return -1;
- }
- return 0;
- }
-
- /* proto > 0: write in batches of BATCHSIZE. */
- do {
- /* Get first item */
- firstitem = PyIter_Next(iter);
- if (firstitem == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* nothing more to add */
- break;
- }
-
- /* Try to get a second item */
- obj = PyIter_Next(iter);
- if (obj == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* Only one item to write */
- if (save(self, firstitem, 0) < 0)
- goto BatchFailed;
- if (self->write_func(self, &append, 1) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- break;
- }
-
- /* More than one item to write */
-
- /* Pump out MARK, items, APPENDS. */
- if (self->write_func(self, &MARKv, 1) < 0)
- goto BatchFailed;
-
- if (save(self, firstitem, 0) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- n = 1;
-
- /* Fetch and save up to BATCHSIZE items */
- while (obj) {
- if (save(self, obj, 0) < 0)
- goto BatchFailed;
- Py_CLEAR(obj);
- n += 1;
-
- if (n == BATCHSIZE)
- break;
-
- obj = PyIter_Next(iter);
- if (obj == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
- break;
- }
- }
-
- if (self->write_func(self, &appends, 1) < 0)
- goto BatchFailed;
-
- } while (n == BATCHSIZE);
- return 0;
+ PyObject *obj = NULL;
+ PyObject *firstitem = NULL;
+ int i, n;
+
+ static char append = APPEND;
+ static char appends = APPENDS;
+
+ assert(iter != NULL);
+
+ if (self->proto == 0) {
+ /* APPENDS isn't available; do one at a time. */
+ for (;;) {
+ obj = PyIter_Next(iter);
+ if (obj == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ break;
+ }
+ i = save(self, obj, 0);
+ Py_DECREF(obj);
+ if (i < 0)
+ return -1;
+ if (self->write_func(self, &append, 1) < 0)
+ return -1;
+ }
+ return 0;
+ }
+
+ /* proto > 0: write in batches of BATCHSIZE. */
+ do {
+ /* Get first item */
+ firstitem = PyIter_Next(iter);
+ if (firstitem == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* nothing more to add */
+ break;
+ }
+
+ /* Try to get a second item */
+ obj = PyIter_Next(iter);
+ if (obj == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* Only one item to write */
+ if (save(self, firstitem, 0) < 0)
+ goto BatchFailed;
+ if (self->write_func(self, &append, 1) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ break;
+ }
+
+ /* More than one item to write */
+
+ /* Pump out MARK, items, APPENDS. */
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto BatchFailed;
+
+ if (save(self, firstitem, 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ n = 1;
+
+ /* Fetch and save up to BATCHSIZE items */
+ while (obj) {
+ if (save(self, obj, 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(obj);
+ n += 1;
+
+ if (n == BATCHSIZE)
+ break;
+
+ obj = PyIter_Next(iter);
+ if (obj == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+ break;
+ }
+ }
+
+ if (self->write_func(self, &appends, 1) < 0)
+ goto BatchFailed;
+
+ } while (n == BATCHSIZE);
+ return 0;
BatchFailed:
- Py_XDECREF(firstitem);
- Py_XDECREF(obj);
- return -1;
+ Py_XDECREF(firstitem);
+ Py_XDECREF(obj);
+ return -1;
}
static int
save_list(Picklerobject *self, PyObject *args)
{
- int res = -1;
- char s[3];
- int len;
- PyObject *iter;
-
- if (self->fast && !fast_save_enter(self, args))
- goto finally;
-
- /* Create an empty list. */
- if (self->bin) {
- s[0] = EMPTY_LIST;
- len = 1;
- }
- else {
- s[0] = MARK;
- s[1] = LIST;
- len = 2;
- }
-
- if (self->write_func(self, s, len) < 0)
- goto finally;
-
- /* Get list length, and bow out early if empty. */
- if ((len = PyList_Size(args)) < 0)
- goto finally;
-
- /* Memoize. */
- if (len == 0) {
- if (put(self, args) >= 0)
- res = 0;
- goto finally;
- }
- if (put2(self, args) < 0)
- goto finally;
-
- /* Materialize the list elements. */
- iter = PyObject_GetIter(args);
- if (iter == NULL)
- goto finally;
-
- if (Py_EnterRecursiveCall(" while pickling an object") == 0)
- {
- res = batch_list(self, iter);
- Py_LeaveRecursiveCall();
- }
- Py_DECREF(iter);
+ int res = -1;
+ char s[3];
+ int len;
+ PyObject *iter;
+
+ if (self->fast && !fast_save_enter(self, args))
+ goto finally;
+
+ /* Create an empty list. */
+ if (self->bin) {
+ s[0] = EMPTY_LIST;
+ len = 1;
+ }
+ else {
+ s[0] = MARK;
+ s[1] = LIST;
+ len = 2;
+ }
+
+ if (self->write_func(self, s, len) < 0)
+ goto finally;
+
+ /* Get list length, and bow out early if empty. */
+ if ((len = PyList_Size(args)) < 0)
+ goto finally;
+
+ /* Memoize. */
+ if (len == 0) {
+ if (put(self, args) >= 0)
+ res = 0;
+ goto finally;
+ }
+ if (put2(self, args) < 0)
+ goto finally;
+
+ /* Materialize the list elements. */
+ iter = PyObject_GetIter(args);
+ if (iter == NULL)
+ goto finally;
+
+ if (Py_EnterRecursiveCall(" while pickling an object") == 0)
+ {
+ res = batch_list(self, iter);
+ Py_LeaveRecursiveCall();
+ }
+ Py_DECREF(iter);
finally:
- if (self->fast && !fast_save_leave(self, args))
- res = -1;
+ if (self->fast && !fast_save_leave(self, args))
+ res = -1;
- return res;
+ return res;
}
@@ -1757,123 +1757,123 @@ save_list(Picklerobject *self, PyObject *args)
static int
batch_dict(Picklerobject *self, PyObject *iter)
{
- PyObject *p = NULL;
- PyObject *firstitem = NULL;
- int i, n;
-
- static char setitem = SETITEM;
- static char setitems = SETITEMS;
-
- assert(iter != NULL);
-
- if (self->proto == 0) {
- /* SETITEMS isn't available; do one at a time. */
- for (;;) {
- p = PyIter_Next(iter);
- if (p == NULL) {
- if (PyErr_Occurred())
- return -1;
- break;
- }
- if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
- PyErr_SetString(PyExc_TypeError, "dict items "
- "iterator must return 2-tuples");
- return -1;
- }
- i = save(self, PyTuple_GET_ITEM(p, 0), 0);
- if (i >= 0)
- i = save(self, PyTuple_GET_ITEM(p, 1), 0);
- Py_DECREF(p);
- if (i < 0)
- return -1;
- if (self->write_func(self, &setitem, 1) < 0)
- return -1;
- }
- return 0;
- }
-
- /* proto > 0: write in batches of BATCHSIZE. */
- do {
- /* Get first item */
- firstitem = PyIter_Next(iter);
- if (firstitem == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* nothing more to add */
- break;
- }
- if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) {
- PyErr_SetString(PyExc_TypeError, "dict items "
- "iterator must return 2-tuples");
- goto BatchFailed;
- }
-
- /* Try to get a second item */
- p = PyIter_Next(iter);
- if (p == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
-
- /* Only one item to write */
- if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
- goto BatchFailed;
- if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
- goto BatchFailed;
- if (self->write_func(self, &setitem, 1) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- break;
- }
-
- /* More than one item to write */
-
- /* Pump out MARK, items, SETITEMS. */
- if (self->write_func(self, &MARKv, 1) < 0)
- goto BatchFailed;
-
- if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
- goto BatchFailed;
- if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
- goto BatchFailed;
- Py_CLEAR(firstitem);
- n = 1;
-
- /* Fetch and save up to BATCHSIZE items */
- while (p) {
- if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
- PyErr_SetString(PyExc_TypeError, "dict items "
- "iterator must return 2-tuples");
- goto BatchFailed;
- }
- if (save(self, PyTuple_GET_ITEM(p, 0), 0) < 0)
- goto BatchFailed;
- if (save(self, PyTuple_GET_ITEM(p, 1), 0) < 0)
- goto BatchFailed;
- Py_CLEAR(p);
- n += 1;
-
- if (n == BATCHSIZE)
- break;
-
- p = PyIter_Next(iter);
- if (p == NULL) {
- if (PyErr_Occurred())
- goto BatchFailed;
- break;
- }
- }
-
- if (self->write_func(self, &setitems, 1) < 0)
- goto BatchFailed;
-
- } while (n == BATCHSIZE);
- return 0;
+ PyObject *p = NULL;
+ PyObject *firstitem = NULL;
+ int i, n;
+
+ static char setitem = SETITEM;
+ static char setitems = SETITEMS;
+
+ assert(iter != NULL);
+
+ if (self->proto == 0) {
+ /* SETITEMS isn't available; do one at a time. */
+ for (;;) {
+ p = PyIter_Next(iter);
+ if (p == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ break;
+ }
+ if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
+ PyErr_SetString(PyExc_TypeError, "dict items "
+ "iterator must return 2-tuples");
+ return -1;
+ }
+ i = save(self, PyTuple_GET_ITEM(p, 0), 0);
+ if (i >= 0)
+ i = save(self, PyTuple_GET_ITEM(p, 1), 0);
+ Py_DECREF(p);
+ if (i < 0)
+ return -1;
+ if (self->write_func(self, &setitem, 1) < 0)
+ return -1;
+ }
+ return 0;
+ }
+
+ /* proto > 0: write in batches of BATCHSIZE. */
+ do {
+ /* Get first item */
+ firstitem = PyIter_Next(iter);
+ if (firstitem == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* nothing more to add */
+ break;
+ }
+ if (!PyTuple_Check(firstitem) || PyTuple_Size(firstitem) != 2) {
+ PyErr_SetString(PyExc_TypeError, "dict items "
+ "iterator must return 2-tuples");
+ goto BatchFailed;
+ }
+
+ /* Try to get a second item */
+ p = PyIter_Next(iter);
+ if (p == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+
+ /* Only one item to write */
+ if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
+ goto BatchFailed;
+ if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
+ goto BatchFailed;
+ if (self->write_func(self, &setitem, 1) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ break;
+ }
+
+ /* More than one item to write */
+
+ /* Pump out MARK, items, SETITEMS. */
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto BatchFailed;
+
+ if (save(self, PyTuple_GET_ITEM(firstitem, 0), 0) < 0)
+ goto BatchFailed;
+ if (save(self, PyTuple_GET_ITEM(firstitem, 1), 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(firstitem);
+ n = 1;
+
+ /* Fetch and save up to BATCHSIZE items */
+ while (p) {
+ if (!PyTuple_Check(p) || PyTuple_Size(p) != 2) {
+ PyErr_SetString(PyExc_TypeError, "dict items "
+ "iterator must return 2-tuples");
+ goto BatchFailed;
+ }
+ if (save(self, PyTuple_GET_ITEM(p, 0), 0) < 0)
+ goto BatchFailed;
+ if (save(self, PyTuple_GET_ITEM(p, 1), 0) < 0)
+ goto BatchFailed;
+ Py_CLEAR(p);
+ n += 1;
+
+ if (n == BATCHSIZE)
+ break;
+
+ p = PyIter_Next(iter);
+ if (p == NULL) {
+ if (PyErr_Occurred())
+ goto BatchFailed;
+ break;
+ }
+ }
+
+ if (self->write_func(self, &setitems, 1) < 0)
+ goto BatchFailed;
+
+ } while (n == BATCHSIZE);
+ return 0;
BatchFailed:
- Py_XDECREF(firstitem);
- Py_XDECREF(p);
- return -1;
+ Py_XDECREF(firstitem);
+ Py_XDECREF(p);
+ return -1;
}
/* This is a variant of batch_dict() above that specializes for dicts, with no
@@ -1888,461 +1888,461 @@ BatchFailed:
static int
batch_dict_exact(Picklerobject *self, PyObject *obj)
{
- PyObject *key = NULL, *value = NULL;
- int i;
- Py_ssize_t dict_size, ppos = 0;
-
- static char setitem = SETITEM;
- static char setitems = SETITEMS;
-
- assert(obj != NULL);
- assert(self->proto > 0);
-
- dict_size = PyDict_Size(obj);
-
- /* Special-case len(d) == 1 to save space. */
- if (dict_size == 1) {
- PyDict_Next(obj, &ppos, &key, &value);
- if (save(self, key, 0) < 0)
- return -1;
- if (save(self, value, 0) < 0)
- return -1;
- if (self->write_func(self, &setitem, 1) < 0)
- return -1;
- return 0;
- }
-
- /* Write in batches of BATCHSIZE. */
- do {
- i = 0;
- if (self->write_func(self, &MARKv, 1) < 0)
- return -1;
- while (PyDict_Next(obj, &ppos, &key, &value)) {
- if (save(self, key, 0) < 0)
- return -1;
- if (save(self, value, 0) < 0)
- return -1;
- if (++i == BATCHSIZE)
- break;
- }
- if (self->write_func(self, &setitems, 1) < 0)
- return -1;
- if (PyDict_Size(obj) != dict_size) {
- PyErr_Format(
- PyExc_RuntimeError,
- "dictionary changed size during iteration");
- return -1;
- }
-
- } while (i == BATCHSIZE);
- return 0;
+ PyObject *key = NULL, *value = NULL;
+ int i;
+ Py_ssize_t dict_size, ppos = 0;
+
+ static char setitem = SETITEM;
+ static char setitems = SETITEMS;
+
+ assert(obj != NULL);
+ assert(self->proto > 0);
+
+ dict_size = PyDict_Size(obj);
+
+ /* Special-case len(d) == 1 to save space. */
+ if (dict_size == 1) {
+ PyDict_Next(obj, &ppos, &key, &value);
+ if (save(self, key, 0) < 0)
+ return -1;
+ if (save(self, value, 0) < 0)
+ return -1;
+ if (self->write_func(self, &setitem, 1) < 0)
+ return -1;
+ return 0;
+ }
+
+ /* Write in batches of BATCHSIZE. */
+ do {
+ i = 0;
+ if (self->write_func(self, &MARKv, 1) < 0)
+ return -1;
+ while (PyDict_Next(obj, &ppos, &key, &value)) {
+ if (save(self, key, 0) < 0)
+ return -1;
+ if (save(self, value, 0) < 0)
+ return -1;
+ if (++i == BATCHSIZE)
+ break;
+ }
+ if (self->write_func(self, &setitems, 1) < 0)
+ return -1;
+ if (PyDict_Size(obj) != dict_size) {
+ PyErr_Format(
+ PyExc_RuntimeError,
+ "dictionary changed size during iteration");
+ return -1;
+ }
+
+ } while (i == BATCHSIZE);
+ return 0;
}
static int
save_dict(Picklerobject *self, PyObject *args)
{
- int res = -1;
- char s[3];
- int len;
-
- if (self->fast && !fast_save_enter(self, args))
- goto finally;
-
- /* Create an empty dict. */
- if (self->bin) {
- s[0] = EMPTY_DICT;
- len = 1;
- }
- else {
- s[0] = MARK;
- s[1] = DICT;
- len = 2;
- }
-
- if (self->write_func(self, s, len) < 0)
- goto finally;
-
- /* Get dict size, and bow out early if empty. */
- if ((len = PyDict_Size(args)) < 0)
- goto finally;
-
- if (len == 0) {
- if (put(self, args) >= 0)
- res = 0;
- goto finally;
- }
- if (put2(self, args) < 0)
- goto finally;
-
- /* Materialize the dict items. */
- if (PyDict_CheckExact(args) && self->proto > 0) {
- /* We can take certain shortcuts if we know this is a dict and
- not a dict subclass. */
- if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
- res = batch_dict_exact(self, args);
- Py_LeaveRecursiveCall();
- }
- } else {
- PyObject *iter = PyObject_CallMethod(args, "iteritems", "()");
- if (iter == NULL)
- goto finally;
- if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
- res = batch_dict(self, iter);
- Py_LeaveRecursiveCall();
- }
- Py_DECREF(iter);
- }
+ int res = -1;
+ char s[3];
+ int len;
+
+ if (self->fast && !fast_save_enter(self, args))
+ goto finally;
+
+ /* Create an empty dict. */
+ if (self->bin) {
+ s[0] = EMPTY_DICT;
+ len = 1;
+ }
+ else {
+ s[0] = MARK;
+ s[1] = DICT;
+ len = 2;
+ }
+
+ if (self->write_func(self, s, len) < 0)
+ goto finally;
+
+ /* Get dict size, and bow out early if empty. */
+ if ((len = PyDict_Size(args)) < 0)
+ goto finally;
+
+ if (len == 0) {
+ if (put(self, args) >= 0)
+ res = 0;
+ goto finally;
+ }
+ if (put2(self, args) < 0)
+ goto finally;
+
+ /* Materialize the dict items. */
+ if (PyDict_CheckExact(args) && self->proto > 0) {
+ /* We can take certain shortcuts if we know this is a dict and
+ not a dict subclass. */
+ if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
+ res = batch_dict_exact(self, args);
+ Py_LeaveRecursiveCall();
+ }
+ } else {
+ PyObject *iter = PyObject_CallMethod(args, "iteritems", "()");
+ if (iter == NULL)
+ goto finally;
+ if (Py_EnterRecursiveCall(" while pickling an object") == 0) {
+ res = batch_dict(self, iter);
+ Py_LeaveRecursiveCall();
+ }
+ Py_DECREF(iter);
+ }
finally:
- if (self->fast && !fast_save_leave(self, args))
- res = -1;
+ if (self->fast && !fast_save_leave(self, args))
+ res = -1;
- return res;
+ return res;
}
static int
save_inst(Picklerobject *self, PyObject *args)
{
- PyObject *class = 0, *module = 0, *name = 0, *state = 0,
- *getinitargs_func = 0, *getstate_func = 0, *class_args = 0;
- char *module_str, *name_str;
- int module_size, name_size, res = -1;
-
- static char inst = INST, obj = OBJ, build = BUILD;
-
- if (self->fast && !fast_save_enter(self, args))
- goto finally;
-
- if (self->write_func(self, &MARKv, 1) < 0)
- goto finally;
-
- if (!( class = PyObject_GetAttr(args, __class___str)))
- goto finally;
-
- if (self->bin) {
- if (save(self, class, 0) < 0)
- goto finally;
- }
-
- if ((getinitargs_func = PyObject_GetAttr(args, __getinitargs___str))) {
- PyObject *element = 0;
- int i, len;
-
- if (!( class_args =
- PyObject_Call(getinitargs_func, empty_tuple, NULL)))
- goto finally;
-
- if ((len = PyObject_Size(class_args)) < 0)
- goto finally;
-
- for (i = 0; i < len; i++) {
- if (!( element = PySequence_GetItem(class_args, i)))
- goto finally;
-
- if (save(self, element, 0) < 0) {
- Py_DECREF(element);
- goto finally;
- }
-
- Py_DECREF(element);
- }
- }
- else {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
- }
-
- if (!self->bin) {
- if (!( name = ((PyClassObject *)class)->cl_name )) {
- PyErr_SetString(PicklingError, "class has no name");
- goto finally;
- }
-
- if (!( module = whichmodule(class, name)))
- goto finally;
-
-
- if ((module_size = PyString_Size(module)) < 0 ||
- (name_size = PyString_Size(name)) < 0)
- goto finally;
-
- module_str = PyString_AS_STRING((PyStringObject *)module);
- name_str = PyString_AS_STRING((PyStringObject *)name);
-
- if (self->write_func(self, &inst, 1) < 0)
- goto finally;
-
- if (self->write_func(self, module_str, module_size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
-
- if (self->write_func(self, name_str, name_size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
- }
- else if (self->write_func(self, &obj, 1) < 0) {
- goto finally;
- }
-
- if ((getstate_func = PyObject_GetAttr(args, __getstate___str))) {
- state = PyObject_Call(getstate_func, empty_tuple, NULL);
- if (!state)
- goto finally;
- }
- else {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
-
- if (!( state = PyObject_GetAttr(args, __dict___str))) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
- res = 0;
- goto finally;
- }
- }
-
- if (!PyDict_Check(state)) {
- if (put2(self, args) < 0)
- goto finally;
- }
- else {
- if (put(self, args) < 0)
- goto finally;
- }
-
- if (save(self, state, 0) < 0)
- goto finally;
-
- if (self->write_func(self, &build, 1) < 0)
- goto finally;
-
- res = 0;
+ PyObject *class = 0, *module = 0, *name = 0, *state = 0,
+ *getinitargs_func = 0, *getstate_func = 0, *class_args = 0;
+ char *module_str, *name_str;
+ int module_size, name_size, res = -1;
+
+ static char inst = INST, obj = OBJ, build = BUILD;
+
+ if (self->fast && !fast_save_enter(self, args))
+ goto finally;
+
+ if (self->write_func(self, &MARKv, 1) < 0)
+ goto finally;
+
+ if (!( class = PyObject_GetAttr(args, __class___str)))
+ goto finally;
+
+ if (self->bin) {
+ if (save(self, class, 0) < 0)
+ goto finally;
+ }
+
+ if ((getinitargs_func = PyObject_GetAttr(args, __getinitargs___str))) {
+ PyObject *element = 0;
+ int i, len;
+
+ if (!( class_args =
+ PyObject_Call(getinitargs_func, empty_tuple, NULL)))
+ goto finally;
+
+ if ((len = PyObject_Size(class_args)) < 0)
+ goto finally;
+
+ for (i = 0; i < len; i++) {
+ if (!( element = PySequence_GetItem(class_args, i)))
+ goto finally;
+
+ if (save(self, element, 0) < 0) {
+ Py_DECREF(element);
+ goto finally;
+ }
+
+ Py_DECREF(element);
+ }
+ }
+ else {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+ }
+
+ if (!self->bin) {
+ if (!( name = ((PyClassObject *)class)->cl_name )) {
+ PyErr_SetString(PicklingError, "class has no name");
+ goto finally;
+ }
+
+ if (!( module = whichmodule(class, name)))
+ goto finally;
+
+
+ if ((module_size = PyString_Size(module)) < 0 ||
+ (name_size = PyString_Size(name)) < 0)
+ goto finally;
+
+ module_str = PyString_AS_STRING((PyStringObject *)module);
+ name_str = PyString_AS_STRING((PyStringObject *)name);
+
+ if (self->write_func(self, &inst, 1) < 0)
+ goto finally;
+
+ if (self->write_func(self, module_str, module_size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+
+ if (self->write_func(self, name_str, name_size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+ }
+ else if (self->write_func(self, &obj, 1) < 0) {
+ goto finally;
+ }
+
+ if ((getstate_func = PyObject_GetAttr(args, __getstate___str))) {
+ state = PyObject_Call(getstate_func, empty_tuple, NULL);
+ if (!state)
+ goto finally;
+ }
+ else {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+
+ if (!( state = PyObject_GetAttr(args, __dict___str))) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+ res = 0;
+ goto finally;
+ }
+ }
+
+ if (!PyDict_Check(state)) {
+ if (put2(self, args) < 0)
+ goto finally;
+ }
+ else {
+ if (put(self, args) < 0)
+ goto finally;
+ }
+
+ if (save(self, state, 0) < 0)
+ goto finally;
+
+ if (self->write_func(self, &build, 1) < 0)
+ goto finally;
+
+ res = 0;
finally:
- if (self->fast && !fast_save_leave(self, args))
- res = -1;
+ if (self->fast && !fast_save_leave(self, args))
+ res = -1;
- Py_XDECREF(module);
- Py_XDECREF(class);
- Py_XDECREF(state);
- Py_XDECREF(getinitargs_func);
- Py_XDECREF(getstate_func);
- Py_XDECREF(class_args);
+ Py_XDECREF(module);
+ Py_XDECREF(class);
+ Py_XDECREF(state);
+ Py_XDECREF(getinitargs_func);
+ Py_XDECREF(getstate_func);
+ Py_XDECREF(class_args);
- return res;
+ return res;
}
static int
save_global(Picklerobject *self, PyObject *args, PyObject *name)
{
- PyObject *global_name = 0, *module = 0, *mod = 0, *klass = 0;
- char *name_str, *module_str;
- int module_size, name_size, res = -1;
-
- static char global = GLOBAL;
-
- if (name) {
- global_name = name;
- Py_INCREF(global_name);
- }
- else {
- if (!( global_name = PyObject_GetAttr(args, __name___str)))
- goto finally;
- }
-
- if (!( module = whichmodule(args, global_name)))
- goto finally;
-
- if ((module_size = PyString_Size(module)) < 0 ||
- (name_size = PyString_Size(global_name)) < 0)
- goto finally;
-
- module_str = PyString_AS_STRING((PyStringObject *)module);
- name_str = PyString_AS_STRING((PyStringObject *)global_name);
-
- /* XXX This can be doing a relative import. Clearly it shouldn't,
- but I don't know how to stop it. :-( */
- mod = PyImport_ImportModule(module_str);
- if (mod == NULL) {
- cPickle_ErrFormat(PicklingError,
- "Can't pickle %s: import of module %s "
- "failed",
- "OS", args, module);
- goto finally;
- }
- klass = PyObject_GetAttrString(mod, name_str);
- if (klass == NULL) {
- cPickle_ErrFormat(PicklingError,
- "Can't pickle %s: attribute lookup %s.%s "
- "failed",
- "OSS", args, module, global_name);
- goto finally;
- }
- if (klass != args) {
- Py_DECREF(klass);
- cPickle_ErrFormat(PicklingError,
- "Can't pickle %s: it's not the same object "
- "as %s.%s",
- "OSS", args, module, global_name);
- goto finally;
- }
- Py_DECREF(klass);
-
- if (self->proto >= 2) {
- /* See whether this is in the extension registry, and if
- * so generate an EXT opcode.
- */
- PyObject *py_code; /* extension code as Python object */
- long code; /* extension code as C value */
- char c_str[5];
- int n;
-
- PyTuple_SET_ITEM(two_tuple, 0, module);
- PyTuple_SET_ITEM(two_tuple, 1, global_name);
- py_code = PyDict_GetItem(extension_registry, two_tuple);
- if (py_code == NULL)
- goto gen_global; /* not registered */
-
- /* Verify py_code has the right type and value. */
- if (!PyInt_Check(py_code)) {
- cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
- "extension code %s isn't an integer",
- "OO", args, py_code);
- goto finally;
- }
- code = PyInt_AS_LONG(py_code);
- if (code <= 0 || code > 0x7fffffffL) {
- cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
- "extension code %ld is out of range",
- "Ol", args, code);
- goto finally;
- }
-
- /* Generate an EXT opcode. */
- if (code <= 0xff) {
- c_str[0] = EXT1;
- c_str[1] = (char)code;
- n = 2;
- }
- else if (code <= 0xffff) {
- c_str[0] = EXT2;
- c_str[1] = (char)(code & 0xff);
- c_str[2] = (char)((code >> 8) & 0xff);
- n = 3;
- }
- else {
- c_str[0] = EXT4;
- c_str[1] = (char)(code & 0xff);
- c_str[2] = (char)((code >> 8) & 0xff);
- c_str[3] = (char)((code >> 16) & 0xff);
- c_str[4] = (char)((code >> 24) & 0xff);
- n = 5;
- }
-
- if (self->write_func(self, c_str, n) >= 0)
- res = 0;
- goto finally; /* and don't memoize */
- }
+ PyObject *global_name = 0, *module = 0, *mod = 0, *klass = 0;
+ char *name_str, *module_str;
+ int module_size, name_size, res = -1;
+
+ static char global = GLOBAL;
+
+ if (name) {
+ global_name = name;
+ Py_INCREF(global_name);
+ }
+ else {
+ if (!( global_name = PyObject_GetAttr(args, __name___str)))
+ goto finally;
+ }
+
+ if (!( module = whichmodule(args, global_name)))
+ goto finally;
+
+ if ((module_size = PyString_Size(module)) < 0 ||
+ (name_size = PyString_Size(global_name)) < 0)
+ goto finally;
+
+ module_str = PyString_AS_STRING((PyStringObject *)module);
+ name_str = PyString_AS_STRING((PyStringObject *)global_name);
+
+ /* XXX This can be doing a relative import. Clearly it shouldn't,
+ but I don't know how to stop it. :-( */
+ mod = PyImport_ImportModule(module_str);
+ if (mod == NULL) {
+ cPickle_ErrFormat(PicklingError,
+ "Can't pickle %s: import of module %s "
+ "failed",
+ "OS", args, module);
+ goto finally;
+ }
+ klass = PyObject_GetAttrString(mod, name_str);
+ if (klass == NULL) {
+ cPickle_ErrFormat(PicklingError,
+ "Can't pickle %s: attribute lookup %s.%s "
+ "failed",
+ "OSS", args, module, global_name);
+ goto finally;
+ }
+ if (klass != args) {
+ Py_DECREF(klass);
+ cPickle_ErrFormat(PicklingError,
+ "Can't pickle %s: it's not the same object "
+ "as %s.%s",
+ "OSS", args, module, global_name);
+ goto finally;
+ }
+ Py_DECREF(klass);
+
+ if (self->proto >= 2) {
+ /* See whether this is in the extension registry, and if
+ * so generate an EXT opcode.
+ */
+ PyObject *py_code; /* extension code as Python object */
+ long code; /* extension code as C value */
+ char c_str[5];
+ int n;
+
+ PyTuple_SET_ITEM(two_tuple, 0, module);
+ PyTuple_SET_ITEM(two_tuple, 1, global_name);
+ py_code = PyDict_GetItem(extension_registry, two_tuple);
+ if (py_code == NULL)
+ goto gen_global; /* not registered */
+
+ /* Verify py_code has the right type and value. */
+ if (!PyInt_Check(py_code)) {
+ cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
+ "extension code %s isn't an integer",
+ "OO", args, py_code);
+ goto finally;
+ }
+ code = PyInt_AS_LONG(py_code);
+ if (code <= 0 || code > 0x7fffffffL) {
+ cPickle_ErrFormat(PicklingError, "Can't pickle %s: "
+ "extension code %ld is out of range",
+ "Ol", args, code);
+ goto finally;
+ }
+
+ /* Generate an EXT opcode. */
+ if (code <= 0xff) {
+ c_str[0] = EXT1;
+ c_str[1] = (char)code;
+ n = 2;
+ }
+ else if (code <= 0xffff) {
+ c_str[0] = EXT2;
+ c_str[1] = (char)(code & 0xff);
+ c_str[2] = (char)((code >> 8) & 0xff);
+ n = 3;
+ }
+ else {
+ c_str[0] = EXT4;
+ c_str[1] = (char)(code & 0xff);
+ c_str[2] = (char)((code >> 8) & 0xff);
+ c_str[3] = (char)((code >> 16) & 0xff);
+ c_str[4] = (char)((code >> 24) & 0xff);
+ n = 5;
+ }
+
+ if (self->write_func(self, c_str, n) >= 0)
+ res = 0;
+ goto finally; /* and don't memoize */
+ }
gen_global:
- if (self->write_func(self, &global, 1) < 0)
- goto finally;
+ if (self->write_func(self, &global, 1) < 0)
+ goto finally;
- if (self->write_func(self, module_str, module_size) < 0)
- goto finally;
+ if (self->write_func(self, module_str, module_size) < 0)
+ goto finally;
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
- if (self->write_func(self, name_str, name_size) < 0)
- goto finally;
+ if (self->write_func(self, name_str, name_size) < 0)
+ goto finally;
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
- if (put(self, args) < 0)
- goto finally;
+ if (put(self, args) < 0)
+ goto finally;
- res = 0;
+ res = 0;
finally:
- Py_XDECREF(module);
- Py_XDECREF(global_name);
- Py_XDECREF(mod);
+ Py_XDECREF(module);
+ Py_XDECREF(global_name);
+ Py_XDECREF(mod);
- return res;
+ return res;
}
static int
save_pers(Picklerobject *self, PyObject *args, PyObject *f)
{
- PyObject *pid = 0;
- int size, res = -1;
-
- static char persid = PERSID, binpersid = BINPERSID;
-
- Py_INCREF(args);
- ARG_TUP(self, args);
- if (self->arg) {
- pid = PyObject_Call(f, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- if (! pid) return -1;
-
- if (pid != Py_None) {
- if (!self->bin) {
- if (!PyString_Check(pid)) {
- PyErr_SetString(PicklingError,
- "persistent id must be string");
- goto finally;
- }
-
- if (self->write_func(self, &persid, 1) < 0)
- goto finally;
-
- if ((size = PyString_Size(pid)) < 0)
- goto finally;
-
- if (self->write_func(self,
- PyString_AS_STRING(
- (PyStringObject *)pid),
- size) < 0)
- goto finally;
-
- if (self->write_func(self, "\n", 1) < 0)
- goto finally;
-
- res = 1;
- goto finally;
- }
- else if (save(self, pid, 1) >= 0) {
- if (self->write_func(self, &binpersid, 1) < 0)
- res = -1;
- else
- res = 1;
- }
-
- goto finally;
- }
-
- res = 0;
+ PyObject *pid = 0;
+ int size, res = -1;
+
+ static char persid = PERSID, binpersid = BINPERSID;
+
+ Py_INCREF(args);
+ ARG_TUP(self, args);
+ if (self->arg) {
+ pid = PyObject_Call(f, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! pid) return -1;
+
+ if (pid != Py_None) {
+ if (!self->bin) {
+ if (!PyString_Check(pid)) {
+ PyErr_SetString(PicklingError,
+ "persistent id must be string");
+ goto finally;
+ }
+
+ if (self->write_func(self, &persid, 1) < 0)
+ goto finally;
+
+ if ((size = PyString_Size(pid)) < 0)
+ goto finally;
+
+ if (self->write_func(self,
+ PyString_AS_STRING(
+ (PyStringObject *)pid),
+ size) < 0)
+ goto finally;
+
+ if (self->write_func(self, "\n", 1) < 0)
+ goto finally;
+
+ res = 1;
+ goto finally;
+ }
+ else if (save(self, pid, 1) >= 0) {
+ if (self->write_func(self, &binpersid, 1) < 0)
+ res = -1;
+ else
+ res = 1;
+ }
+
+ goto finally;
+ }
+
+ res = 0;
finally:
- Py_XDECREF(pid);
+ Py_XDECREF(pid);
- return res;
+ return res;
}
/* We're saving ob, and args is the 2-thru-5 tuple returned by the
@@ -2351,621 +2351,621 @@ save_pers(Picklerobject *self, PyObject *args, PyObject *f)
static int
save_reduce(Picklerobject *self, PyObject *args, PyObject *fn, PyObject *ob)
{
- PyObject *callable;
- PyObject *argtup;
- PyObject *state = NULL;
- PyObject *listitems = Py_None;
- PyObject *dictitems = Py_None;
- Py_ssize_t size;
-
- int use_newobj = self->proto >= 2;
-
- static char reduce = REDUCE;
- static char build = BUILD;
- static char newobj = NEWOBJ;
-
- size = PyTuple_Size(args);
- if (size < 2 || size > 5) {
- cPickle_ErrFormat(PicklingError, "tuple returned by "
- "%s must contain 2 through 5 elements",
- "O", fn);
- return -1;
- }
-
- if (! PyArg_UnpackTuple(args, "save_reduce", 2, 5,
- &callable,
- &argtup,
- &state,
- &listitems,
- &dictitems))
- return -1;
-
- if (!PyTuple_Check(argtup)) {
- cPickle_ErrFormat(PicklingError, "Second element of "
- "tuple returned by %s must be a tuple",
- "O", fn);
- return -1;
- }
-
- if (state == Py_None)
- state = NULL;
-
- if (listitems == Py_None)
- listitems = NULL;
- else if (!PyIter_Check(listitems)) {
- cPickle_ErrFormat(PicklingError, "Fourth element of "
- "tuple returned by %s must be an iterator, not %s",
- "Os", fn, Py_TYPE(listitems)->tp_name);
- return -1;
- }
-
- if (dictitems == Py_None)
- dictitems = NULL;
- else if (!PyIter_Check(dictitems)) {
- cPickle_ErrFormat(PicklingError, "Fifth element of "
- "tuple returned by %s must be an iterator, not %s",
- "Os", fn, Py_TYPE(dictitems)->tp_name);
- return -1;
- }
-
- /* Protocol 2 special case: if callable's name is __newobj__, use
- * NEWOBJ. This consumes a lot of code.
- */
- if (use_newobj) {
- PyObject *temp = PyObject_GetAttr(callable, __name___str);
-
- if (temp == NULL) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return -1;
- use_newobj = 0;
- }
- else {
- use_newobj = PyString_Check(temp) &&
- strcmp(PyString_AS_STRING(temp),
- "__newobj__") == 0;
- Py_DECREF(temp);
- }
- }
- if (use_newobj) {
- PyObject *cls;
- PyObject *newargtup;
- int n, i;
-
- /* Sanity checks. */
- n = PyTuple_Size(argtup);
- if (n < 1) {
- PyErr_SetString(PicklingError, "__newobj__ arglist "
- "is empty");
- return -1;
- }
-
- cls = PyTuple_GET_ITEM(argtup, 0);
- if (! PyObject_HasAttrString(cls, "__new__")) {
- PyErr_SetString(PicklingError, "args[0] from "
- "__newobj__ args has no __new__");
- return -1;
- }
-
- /* XXX How could ob be NULL? */
- if (ob != NULL) {
- PyObject *ob_dot_class;
-
- ob_dot_class = PyObject_GetAttr(ob, __class___str);
- if (ob_dot_class == NULL) {
- if (PyErr_ExceptionMatches(
- PyExc_AttributeError))
- PyErr_Clear();
- else
- return -1;
- }
- i = ob_dot_class != cls; /* true iff a problem */
- Py_XDECREF(ob_dot_class);
- if (i) {
- PyErr_SetString(PicklingError, "args[0] from "
- "__newobj__ args has the wrong class");
- return -1;
- }
- }
-
- /* Save the class and its __new__ arguments. */
- if (save(self, cls, 0) < 0)
- return -1;
-
- newargtup = PyTuple_New(n-1); /* argtup[1:] */
- if (newargtup == NULL)
- return -1;
- for (i = 1; i < n; ++i) {
- PyObject *temp = PyTuple_GET_ITEM(argtup, i);
- Py_INCREF(temp);
- PyTuple_SET_ITEM(newargtup, i-1, temp);
- }
- i = save(self, newargtup, 0);
- Py_DECREF(newargtup);
- if (i < 0)
- return -1;
-
- /* Add NEWOBJ opcode. */
- if (self->write_func(self, &newobj, 1) < 0)
- return -1;
- }
- else {
- /* Not using NEWOBJ. */
- if (save(self, callable, 0) < 0 ||
- save(self, argtup, 0) < 0 ||
- self->write_func(self, &reduce, 1) < 0)
- return -1;
- }
-
- /* Memoize. */
- /* XXX How can ob be NULL? */
- if (ob != NULL) {
- if (state && !PyDict_Check(state)) {
- if (put2(self, ob) < 0)
- return -1;
- }
- else if (put(self, ob) < 0)
- return -1;
- }
-
-
- if (listitems && batch_list(self, listitems) < 0)
- return -1;
-
- if (dictitems && batch_dict(self, dictitems) < 0)
- return -1;
-
- if (state) {
- if (save(self, state, 0) < 0 ||
- self->write_func(self, &build, 1) < 0)
- return -1;
- }
-
- return 0;
+ PyObject *callable;
+ PyObject *argtup;
+ PyObject *state = NULL;
+ PyObject *listitems = Py_None;
+ PyObject *dictitems = Py_None;
+ Py_ssize_t size;
+
+ int use_newobj = self->proto >= 2;
+
+ static char reduce = REDUCE;
+ static char build = BUILD;
+ static char newobj = NEWOBJ;
+
+ size = PyTuple_Size(args);
+ if (size < 2 || size > 5) {
+ cPickle_ErrFormat(PicklingError, "tuple returned by "
+ "%s must contain 2 through 5 elements",
+ "O", fn);
+ return -1;
+ }
+
+ if (! PyArg_UnpackTuple(args, "save_reduce", 2, 5,
+ &callable,
+ &argtup,
+ &state,
+ &listitems,
+ &dictitems))
+ return -1;
+
+ if (!PyTuple_Check(argtup)) {
+ cPickle_ErrFormat(PicklingError, "Second element of "
+ "tuple returned by %s must be a tuple",
+ "O", fn);
+ return -1;
+ }
+
+ if (state == Py_None)
+ state = NULL;
+
+ if (listitems == Py_None)
+ listitems = NULL;
+ else if (!PyIter_Check(listitems)) {
+ cPickle_ErrFormat(PicklingError, "Fourth element of "
+ "tuple returned by %s must be an iterator, not %s",
+ "Os", fn, Py_TYPE(listitems)->tp_name);
+ return -1;
+ }
+
+ if (dictitems == Py_None)
+ dictitems = NULL;
+ else if (!PyIter_Check(dictitems)) {
+ cPickle_ErrFormat(PicklingError, "Fifth element of "
+ "tuple returned by %s must be an iterator, not %s",
+ "Os", fn, Py_TYPE(dictitems)->tp_name);
+ return -1;
+ }
+
+ /* Protocol 2 special case: if callable's name is __newobj__, use
+ * NEWOBJ. This consumes a lot of code.
+ */
+ if (use_newobj) {
+ PyObject *temp = PyObject_GetAttr(callable, __name___str);
+
+ if (temp == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return -1;
+ use_newobj = 0;
+ }
+ else {
+ use_newobj = PyString_Check(temp) &&
+ strcmp(PyString_AS_STRING(temp),
+ "__newobj__") == 0;
+ Py_DECREF(temp);
+ }
+ }
+ if (use_newobj) {
+ PyObject *cls;
+ PyObject *newargtup;
+ int n, i;
+
+ /* Sanity checks. */
+ n = PyTuple_Size(argtup);
+ if (n < 1) {
+ PyErr_SetString(PicklingError, "__newobj__ arglist "
+ "is empty");
+ return -1;
+ }
+
+ cls = PyTuple_GET_ITEM(argtup, 0);
+ if (! PyObject_HasAttrString(cls, "__new__")) {
+ PyErr_SetString(PicklingError, "args[0] from "
+ "__newobj__ args has no __new__");
+ return -1;
+ }
+
+ /* XXX How could ob be NULL? */
+ if (ob != NULL) {
+ PyObject *ob_dot_class;
+
+ ob_dot_class = PyObject_GetAttr(ob, __class___str);
+ if (ob_dot_class == NULL) {
+ if (PyErr_ExceptionMatches(
+ PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return -1;
+ }
+ i = ob_dot_class != cls; /* true iff a problem */
+ Py_XDECREF(ob_dot_class);
+ if (i) {
+ PyErr_SetString(PicklingError, "args[0] from "
+ "__newobj__ args has the wrong class");
+ return -1;
+ }
+ }
+
+ /* Save the class and its __new__ arguments. */
+ if (save(self, cls, 0) < 0)
+ return -1;
+
+ newargtup = PyTuple_New(n-1); /* argtup[1:] */
+ if (newargtup == NULL)
+ return -1;
+ for (i = 1; i < n; ++i) {
+ PyObject *temp = PyTuple_GET_ITEM(argtup, i);
+ Py_INCREF(temp);
+ PyTuple_SET_ITEM(newargtup, i-1, temp);
+ }
+ i = save(self, newargtup, 0);
+ Py_DECREF(newargtup);
+ if (i < 0)
+ return -1;
+
+ /* Add NEWOBJ opcode. */
+ if (self->write_func(self, &newobj, 1) < 0)
+ return -1;
+ }
+ else {
+ /* Not using NEWOBJ. */
+ if (save(self, callable, 0) < 0 ||
+ save(self, argtup, 0) < 0 ||
+ self->write_func(self, &reduce, 1) < 0)
+ return -1;
+ }
+
+ /* Memoize. */
+ /* XXX How can ob be NULL? */
+ if (ob != NULL) {
+ if (state && !PyDict_Check(state)) {
+ if (put2(self, ob) < 0)
+ return -1;
+ }
+ else if (put(self, ob) < 0)
+ return -1;
+ }
+
+
+ if (listitems && batch_list(self, listitems) < 0)
+ return -1;
+
+ if (dictitems && batch_dict(self, dictitems) < 0)
+ return -1;
+
+ if (state) {
+ if (save(self, state, 0) < 0 ||
+ self->write_func(self, &build, 1) < 0)
+ return -1;
+ }
+
+ return 0;
}
static int
save(Picklerobject *self, PyObject *args, int pers_save)
{
- PyTypeObject *type;
- PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0;
- int res = -1;
- int tmp;
-
- if (Py_EnterRecursiveCall(" while pickling an object"))
- return -1;
-
- if (!pers_save && self->pers_func) {
- if ((tmp = save_pers(self, args, self->pers_func)) != 0) {
- res = tmp;
- goto finally;
- }
- }
-
- if (args == Py_None) {
- res = save_none(self, args);
- goto finally;
- }
-
- type = Py_TYPE(args);
-
- switch (type->tp_name[0]) {
- case 'b':
- if (args == Py_False || args == Py_True) {
- res = save_bool(self, args);
- goto finally;
- }
- break;
- case 'i':
- if (type == &PyInt_Type) {
- res = save_int(self, args);
- goto finally;
- }
- break;
-
- case 'l':
- if (type == &PyLong_Type) {
- res = save_long(self, args);
- goto finally;
- }
- break;
-
- case 'f':
- if (type == &PyFloat_Type) {
- res = save_float(self, args);
- goto finally;
- }
- break;
-
- case 't':
- if (type == &PyTuple_Type && PyTuple_Size(args) == 0) {
- res = save_tuple(self, args);
- goto finally;
- }
- break;
-
- case 's':
- if ((type == &PyString_Type) && (PyString_GET_SIZE(args) < 2)) {
- res = save_string(self, args, 0);
- goto finally;
- }
- break;
+ PyTypeObject *type;
+ PyObject *py_ob_id = 0, *__reduce__ = 0, *t = 0;
+ int res = -1;
+ int tmp;
+
+ if (Py_EnterRecursiveCall(" while pickling an object"))
+ return -1;
+
+ if (!pers_save && self->pers_func) {
+ if ((tmp = save_pers(self, args, self->pers_func)) != 0) {
+ res = tmp;
+ goto finally;
+ }
+ }
+
+ if (args == Py_None) {
+ res = save_none(self, args);
+ goto finally;
+ }
+
+ type = Py_TYPE(args);
+
+ switch (type->tp_name[0]) {
+ case 'b':
+ if (args == Py_False || args == Py_True) {
+ res = save_bool(self, args);
+ goto finally;
+ }
+ break;
+ case 'i':
+ if (type == &PyInt_Type) {
+ res = save_int(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'l':
+ if (type == &PyLong_Type) {
+ res = save_long(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'f':
+ if (type == &PyFloat_Type) {
+ res = save_float(self, args);
+ goto finally;
+ }
+ break;
+
+ case 't':
+ if (type == &PyTuple_Type && PyTuple_Size(args) == 0) {
+ res = save_tuple(self, args);
+ goto finally;
+ }
+ break;
+
+ case 's':
+ if ((type == &PyString_Type) && (PyString_GET_SIZE(args) < 2)) {
+ res = save_string(self, args, 0);
+ goto finally;
+ }
+ break;
#ifdef Py_USING_UNICODE
- case 'u':
- if ((type == &PyUnicode_Type) && (PyString_GET_SIZE(args) < 2)) {
- res = save_unicode(self, args, 0);
- goto finally;
- }
- break;
+ case 'u':
+ if ((type == &PyUnicode_Type) && (PyString_GET_SIZE(args) < 2)) {
+ res = save_unicode(self, args, 0);
+ goto finally;
+ }
+ break;
#endif
- }
+ }
- if (Py_REFCNT(args) > 1) {
- if (!( py_ob_id = PyLong_FromVoidPtr(args)))
- goto finally;
+ if (Py_REFCNT(args) > 1) {
+ if (!( py_ob_id = PyLong_FromVoidPtr(args)))
+ goto finally;
- if (PyDict_GetItem(self->memo, py_ob_id)) {
- if (get(self, py_ob_id) < 0)
- goto finally;
+ if (PyDict_GetItem(self->memo, py_ob_id)) {
+ if (get(self, py_ob_id) < 0)
+ goto finally;
- res = 0;
- goto finally;
- }
- }
+ res = 0;
+ goto finally;
+ }
+ }
- switch (type->tp_name[0]) {
- case 's':
- if (type == &PyString_Type) {
- res = save_string(self, args, 1);
- goto finally;
- }
- break;
+ switch (type->tp_name[0]) {
+ case 's':
+ if (type == &PyString_Type) {
+ res = save_string(self, args, 1);
+ goto finally;
+ }
+ break;
#ifdef Py_USING_UNICODE
- case 'u':
- if (type == &PyUnicode_Type) {
- res = save_unicode(self, args, 1);
- goto finally;
- }
- break;
+ case 'u':
+ if (type == &PyUnicode_Type) {
+ res = save_unicode(self, args, 1);
+ goto finally;
+ }
+ break;
#endif
- case 't':
- if (type == &PyTuple_Type) {
- res = save_tuple(self, args);
- goto finally;
- }
- if (type == &PyType_Type) {
- res = save_global(self, args, NULL);
- goto finally;
- }
- break;
-
- case 'l':
- if (type == &PyList_Type) {
- res = save_list(self, args);
- goto finally;
- }
- break;
-
- case 'd':
- if (type == &PyDict_Type) {
- res = save_dict(self, args);
- goto finally;
- }
- break;
-
- case 'i':
- if (type == &PyInstance_Type) {
- res = save_inst(self, args);
- goto finally;
- }
- break;
-
- case 'c':
- if (type == &PyClass_Type) {
- res = save_global(self, args, NULL);
- goto finally;
- }
- break;
-
- case 'f':
- if (type == &PyFunction_Type) {
- res = save_global(self, args, NULL);
- if (res && PyErr_ExceptionMatches(PickleError)) {
- /* fall back to reduce */
- PyErr_Clear();
- break;
- }
- goto finally;
- }
- break;
-
- case 'b':
- if (type == &PyCFunction_Type) {
- res = save_global(self, args, NULL);
- goto finally;
- }
- }
-
- if (!pers_save && self->inst_pers_func) {
- if ((tmp = save_pers(self, args, self->inst_pers_func)) != 0) {
- res = tmp;
- goto finally;
- }
- }
-
- if (PyType_IsSubtype(type, &PyType_Type)) {
- res = save_global(self, args, NULL);
- goto finally;
- }
-
- /* Get a reduction callable, and call it. This may come from
- * copy_reg.dispatch_table, the object's __reduce_ex__ method,
- * or the object's __reduce__ method.
- */
- __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type);
- if (__reduce__ != NULL) {
- Py_INCREF(__reduce__);
- Py_INCREF(args);
- ARG_TUP(self, args);
- if (self->arg) {
- t = PyObject_Call(__reduce__, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- }
- else {
- /* Check for a __reduce_ex__ method. */
- __reduce__ = PyObject_GetAttr(args, __reduce_ex___str);
- if (__reduce__ != NULL) {
- t = PyInt_FromLong(self->proto);
- if (t != NULL) {
- ARG_TUP(self, t);
- t = NULL;
- if (self->arg) {
- t = PyObject_Call(__reduce__,
- self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- }
- }
- else {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- goto finally;
- /* Check for a __reduce__ method. */
- __reduce__ = PyObject_GetAttr(args, __reduce___str);
- if (__reduce__ != NULL) {
- t = PyObject_Call(__reduce__,
- empty_tuple, NULL);
- }
- else {
- PyErr_SetObject(UnpickleableError, args);
- goto finally;
- }
- }
- }
-
- if (t == NULL)
- goto finally;
-
- if (PyString_Check(t)) {
- res = save_global(self, args, t);
- goto finally;
- }
-
- if (!PyTuple_Check(t)) {
- cPickle_ErrFormat(PicklingError, "Value returned by "
- "%s must be string or tuple",
- "O", __reduce__);
- goto finally;
- }
-
- res = save_reduce(self, t, __reduce__, args);
+ case 't':
+ if (type == &PyTuple_Type) {
+ res = save_tuple(self, args);
+ goto finally;
+ }
+ if (type == &PyType_Type) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+ break;
+
+ case 'l':
+ if (type == &PyList_Type) {
+ res = save_list(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'd':
+ if (type == &PyDict_Type) {
+ res = save_dict(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'i':
+ if (type == &PyInstance_Type) {
+ res = save_inst(self, args);
+ goto finally;
+ }
+ break;
+
+ case 'c':
+ if (type == &PyClass_Type) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+ break;
+
+ case 'f':
+ if (type == &PyFunction_Type) {
+ res = save_global(self, args, NULL);
+ if (res && PyErr_ExceptionMatches(PickleError)) {
+ /* fall back to reduce */
+ PyErr_Clear();
+ break;
+ }
+ goto finally;
+ }
+ break;
+
+ case 'b':
+ if (type == &PyCFunction_Type) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+ }
+
+ if (!pers_save && self->inst_pers_func) {
+ if ((tmp = save_pers(self, args, self->inst_pers_func)) != 0) {
+ res = tmp;
+ goto finally;
+ }
+ }
+
+ if (PyType_IsSubtype(type, &PyType_Type)) {
+ res = save_global(self, args, NULL);
+ goto finally;
+ }
+
+ /* Get a reduction callable, and call it. This may come from
+ * copy_reg.dispatch_table, the object's __reduce_ex__ method,
+ * or the object's __reduce__ method.
+ */
+ __reduce__ = PyDict_GetItem(dispatch_table, (PyObject *)type);
+ if (__reduce__ != NULL) {
+ Py_INCREF(__reduce__);
+ Py_INCREF(args);
+ ARG_TUP(self, args);
+ if (self->arg) {
+ t = PyObject_Call(__reduce__, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ }
+ else {
+ /* Check for a __reduce_ex__ method. */
+ __reduce__ = PyObject_GetAttr(args, __reduce_ex___str);
+ if (__reduce__ != NULL) {
+ t = PyInt_FromLong(self->proto);
+ if (t != NULL) {
+ ARG_TUP(self, t);
+ t = NULL;
+ if (self->arg) {
+ t = PyObject_Call(__reduce__,
+ self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ }
+ }
+ else {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ goto finally;
+ /* Check for a __reduce__ method. */
+ __reduce__ = PyObject_GetAttr(args, __reduce___str);
+ if (__reduce__ != NULL) {
+ t = PyObject_Call(__reduce__,
+ empty_tuple, NULL);
+ }
+ else {
+ PyErr_SetObject(UnpickleableError, args);
+ goto finally;
+ }
+ }
+ }
+
+ if (t == NULL)
+ goto finally;
+
+ if (PyString_Check(t)) {
+ res = save_global(self, args, t);
+ goto finally;
+ }
+
+ if (!PyTuple_Check(t)) {
+ cPickle_ErrFormat(PicklingError, "Value returned by "
+ "%s must be string or tuple",
+ "O", __reduce__);
+ goto finally;
+ }
+
+ res = save_reduce(self, t, __reduce__, args);
finally:
- Py_LeaveRecursiveCall();
- Py_XDECREF(py_ob_id);
- Py_XDECREF(__reduce__);
- Py_XDECREF(t);
+ Py_LeaveRecursiveCall();
+ Py_XDECREF(py_ob_id);
+ Py_XDECREF(__reduce__);
+ Py_XDECREF(t);
- return res;
+ return res;
}
static int
dump(Picklerobject *self, PyObject *args)
{
- static char stop = STOP;
+ static char stop = STOP;
- if (self->proto >= 2) {
- char bytes[2];
+ if (self->proto >= 2) {
+ char bytes[2];
- bytes[0] = PROTO;
- assert(self->proto >= 0 && self->proto < 256);
- bytes[1] = (char)self->proto;
- if (self->write_func(self, bytes, 2) < 0)
- return -1;
- }
+ bytes[0] = PROTO;
+ assert(self->proto >= 0 && self->proto < 256);
+ bytes[1] = (char)self->proto;
+ if (self->write_func(self, bytes, 2) < 0)
+ return -1;
+ }
- if (save(self, args, 0) < 0)
- return -1;
+ if (save(self, args, 0) < 0)
+ return -1;
- if (self->write_func(self, &stop, 1) < 0)
- return -1;
+ if (self->write_func(self, &stop, 1) < 0)
+ return -1;
- if (self->write_func(self, NULL, 0) < 0)
- return -1;
+ if (self->write_func(self, NULL, 0) < 0)
+ return -1;
- return 0;
+ return 0;
}
static PyObject *
Pickle_clear_memo(Picklerobject *self, PyObject *args)
{
- if (self->memo)
- PyDict_Clear(self->memo);
- Py_INCREF(Py_None);
- return Py_None;
+ if (self->memo)
+ PyDict_Clear(self->memo);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
Pickle_getvalue(Picklerobject *self, PyObject *args)
{
- int l, i, rsize, ssize, clear=1, lm;
- long ik;
- PyObject *k, *r;
- char *s, *p, *have_get;
- Pdata *data;
-
- /* Can be called by Python code or C code */
- if (args && !PyArg_ParseTuple(args, "|i:getvalue", &clear))
- return NULL;
-
- /* Check to make sure we are based on a list */
- if (! Pdata_Check(self->file)) {
- PyErr_SetString(PicklingError,
- "Attempt to getvalue() a non-list-based pickler");
- return NULL;
- }
-
- /* flush write buffer */
- if (write_other(self, NULL, 0) < 0) return NULL;
-
- data=(Pdata*)self->file;
- l=data->length;
-
- /* set up an array to hold get/put status */
- lm = PyDict_Size(self->memo);
- if (lm < 0) return NULL;
- lm++;
- have_get = malloc(lm);
- if (have_get == NULL) return PyErr_NoMemory();
- memset(have_get, 0, lm);
-
- /* Scan for gets. */
- for (rsize = 0, i = l; --i >= 0; ) {
- k = data->data[i];
-
- if (PyString_Check(k))
- rsize += PyString_GET_SIZE(k);
-
- else if (PyInt_Check(k)) { /* put */
- ik = PyInt_AS_LONG((PyIntObject*)k);
- if (ik >= lm || ik == 0) {
- PyErr_SetString(PicklingError,
- "Invalid get data");
- goto err;
- }
- if (have_get[ik]) /* with matching get */
- rsize += ik < 256 ? 2 : 5;
- }
-
- else if (! (PyTuple_Check(k) &&
- PyTuple_GET_SIZE(k) == 2 &&
- PyInt_Check((k = PyTuple_GET_ITEM(k, 0))))
- ) {
- PyErr_SetString(PicklingError,
- "Unexpected data in internal list");
- goto err;
- }
-
- else { /* put */
- ik = PyInt_AS_LONG((PyIntObject *)k);
- if (ik >= lm || ik == 0) {
- PyErr_SetString(PicklingError,
- "Invalid get data");
- return NULL;
- }
- have_get[ik] = 1;
- rsize += ik < 256 ? 2 : 5;
- }
- }
-
- /* Now generate the result */
- r = PyString_FromStringAndSize(NULL, rsize);
- if (r == NULL) goto err;
- s = PyString_AS_STRING((PyStringObject *)r);
-
- for (i = 0; i < l; i++) {
- k = data->data[i];
-
- if (PyString_Check(k)) {
- ssize = PyString_GET_SIZE(k);
- if (ssize) {
- p=PyString_AS_STRING((PyStringObject *)k);
- while (--ssize >= 0)
- *s++ = *p++;
- }
- }
-
- else if (PyTuple_Check(k)) { /* get */
- ik = PyInt_AS_LONG((PyIntObject *)
- PyTuple_GET_ITEM(k, 0));
- if (ik < 256) {
- *s++ = BINGET;
- *s++ = (int)(ik & 0xff);
- }
- else {
- *s++ = LONG_BINGET;
- *s++ = (int)(ik & 0xff);
- *s++ = (int)((ik >> 8) & 0xff);
- *s++ = (int)((ik >> 16) & 0xff);
- *s++ = (int)((ik >> 24) & 0xff);
- }
- }
-
- else { /* put */
- ik = PyInt_AS_LONG((PyIntObject*)k);
-
- if (have_get[ik]) { /* with matching get */
- if (ik < 256) {
- *s++ = BINPUT;
- *s++ = (int)(ik & 0xff);
- }
- else {
- *s++ = LONG_BINPUT;
- *s++ = (int)(ik & 0xff);
- *s++ = (int)((ik >> 8) & 0xff);
- *s++ = (int)((ik >> 16) & 0xff);
- *s++ = (int)((ik >> 24) & 0xff);
- }
- }
- }
- }
-
- if (clear) {
- PyDict_Clear(self->memo);
- Pdata_clear(data, 0);
- }
-
- free(have_get);
- return r;
+ int l, i, rsize, ssize, clear=1, lm;
+ long ik;
+ PyObject *k, *r;
+ char *s, *p, *have_get;
+ Pdata *data;
+
+ /* Can be called by Python code or C code */
+ if (args && !PyArg_ParseTuple(args, "|i:getvalue", &clear))
+ return NULL;
+
+ /* Check to make sure we are based on a list */
+ if (! Pdata_Check(self->file)) {
+ PyErr_SetString(PicklingError,
+ "Attempt to getvalue() a non-list-based pickler");
+ return NULL;
+ }
+
+ /* flush write buffer */
+ if (write_other(self, NULL, 0) < 0) return NULL;
+
+ data=(Pdata*)self->file;
+ l=data->length;
+
+ /* set up an array to hold get/put status */
+ lm = PyDict_Size(self->memo);
+ if (lm < 0) return NULL;
+ lm++;
+ have_get = malloc(lm);
+ if (have_get == NULL) return PyErr_NoMemory();
+ memset(have_get, 0, lm);
+
+ /* Scan for gets. */
+ for (rsize = 0, i = l; --i >= 0; ) {
+ k = data->data[i];
+
+ if (PyString_Check(k))
+ rsize += PyString_GET_SIZE(k);
+
+ else if (PyInt_Check(k)) { /* put */
+ ik = PyInt_AS_LONG((PyIntObject*)k);
+ if (ik >= lm || ik == 0) {
+ PyErr_SetString(PicklingError,
+ "Invalid get data");
+ goto err;
+ }
+ if (have_get[ik]) /* with matching get */
+ rsize += ik < 256 ? 2 : 5;
+ }
+
+ else if (! (PyTuple_Check(k) &&
+ PyTuple_GET_SIZE(k) == 2 &&
+ PyInt_Check((k = PyTuple_GET_ITEM(k, 0))))
+ ) {
+ PyErr_SetString(PicklingError,
+ "Unexpected data in internal list");
+ goto err;
+ }
+
+ else { /* put */
+ ik = PyInt_AS_LONG((PyIntObject *)k);
+ if (ik >= lm || ik == 0) {
+ PyErr_SetString(PicklingError,
+ "Invalid get data");
+ return NULL;
+ }
+ have_get[ik] = 1;
+ rsize += ik < 256 ? 2 : 5;
+ }
+ }
+
+ /* Now generate the result */
+ r = PyString_FromStringAndSize(NULL, rsize);
+ if (r == NULL) goto err;
+ s = PyString_AS_STRING((PyStringObject *)r);
+
+ for (i = 0; i < l; i++) {
+ k = data->data[i];
+
+ if (PyString_Check(k)) {
+ ssize = PyString_GET_SIZE(k);
+ if (ssize) {
+ p=PyString_AS_STRING((PyStringObject *)k);
+ while (--ssize >= 0)
+ *s++ = *p++;
+ }
+ }
+
+ else if (PyTuple_Check(k)) { /* get */
+ ik = PyInt_AS_LONG((PyIntObject *)
+ PyTuple_GET_ITEM(k, 0));
+ if (ik < 256) {
+ *s++ = BINGET;
+ *s++ = (int)(ik & 0xff);
+ }
+ else {
+ *s++ = LONG_BINGET;
+ *s++ = (int)(ik & 0xff);
+ *s++ = (int)((ik >> 8) & 0xff);
+ *s++ = (int)((ik >> 16) & 0xff);
+ *s++ = (int)((ik >> 24) & 0xff);
+ }
+ }
+
+ else { /* put */
+ ik = PyInt_AS_LONG((PyIntObject*)k);
+
+ if (have_get[ik]) { /* with matching get */
+ if (ik < 256) {
+ *s++ = BINPUT;
+ *s++ = (int)(ik & 0xff);
+ }
+ else {
+ *s++ = LONG_BINPUT;
+ *s++ = (int)(ik & 0xff);
+ *s++ = (int)((ik >> 8) & 0xff);
+ *s++ = (int)((ik >> 16) & 0xff);
+ *s++ = (int)((ik >> 24) & 0xff);
+ }
+ }
+ }
+ }
+
+ if (clear) {
+ PyDict_Clear(self->memo);
+ Pdata_clear(data, 0);
+ }
+
+ free(have_get);
+ return r;
err:
- free(have_get);
- return NULL;
+ free(have_get);
+ return NULL;
}
static PyObject *
Pickler_dump(Picklerobject *self, PyObject *args)
{
- PyObject *ob;
- int get=0;
+ PyObject *ob;
+ int get=0;
- if (!( PyArg_ParseTuple(args, "O|i:dump", &ob, &get)))
- return NULL;
+ if (!( PyArg_ParseTuple(args, "O|i:dump", &ob, &get)))
+ return NULL;
- if (dump(self, ob) < 0)
- return NULL;
+ if (dump(self, ob) < 0)
+ return NULL;
- if (get) return Pickle_getvalue(self, NULL);
+ if (get) return Pickle_getvalue(self, NULL);
- /* XXX Why does dump() return self? */
- Py_INCREF(self);
- return (PyObject*)self;
+ /* XXX Why does dump() return self? */
+ Py_INCREF(self);
+ return (PyObject*)self;
}
@@ -2985,250 +2985,250 @@ static struct PyMethodDef Pickler_methods[] =
static Picklerobject *
newPicklerobject(PyObject *file, int proto)
{
- Picklerobject *self;
-
- if (proto < 0)
- proto = HIGHEST_PROTOCOL;
- if (proto > HIGHEST_PROTOCOL) {
- PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; "
- "the highest available protocol is %d",
- proto, HIGHEST_PROTOCOL);
- return NULL;
- }
-
- self = PyObject_GC_New(Picklerobject, &Picklertype);
- if (self == NULL)
- return NULL;
- self->proto = proto;
- self->bin = proto > 0;
- self->fp = NULL;
- self->write = NULL;
- self->memo = NULL;
- self->arg = NULL;
- self->pers_func = NULL;
- self->inst_pers_func = NULL;
- self->write_buf = NULL;
- self->fast = 0;
- self->fast_container = 0;
- self->fast_memo = NULL;
- self->buf_size = 0;
- self->dispatch_table = NULL;
-
- self->file = NULL;
- if (file)
- Py_INCREF(file);
- else {
- file = Pdata_New();
- if (file == NULL)
- goto err;
- }
- self->file = file;
-
- if (!( self->memo = PyDict_New()))
- goto err;
-
- if (PyFile_Check(file)) {
- self->fp = PyFile_AsFile(file);
- if (self->fp == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto err;
- }
- self->write_func = write_file;
- }
- else if (PycStringIO_OutputCheck(file)) {
- self->write_func = write_cStringIO;
- }
- else if (file == Py_None) {
- self->write_func = write_none;
- }
- else {
- self->write_func = write_other;
-
- if (! Pdata_Check(file)) {
- self->write = PyObject_GetAttr(file, write_str);
- if (!self->write) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "argument must have 'write' "
- "attribute");
- goto err;
- }
- }
-
- self->write_buf = (char *)PyMem_Malloc(WRITE_BUF_SIZE);
- if (self->write_buf == NULL) {
- PyErr_NoMemory();
- goto err;
- }
- }
-
- if (PyEval_GetRestricted()) {
- /* Restricted execution, get private tables */
- PyObject *m = PyImport_ImportModule("copy_reg");
-
- if (m == NULL)
- goto err;
- self->dispatch_table = PyObject_GetAttr(m, dispatch_table_str);
- Py_DECREF(m);
- if (self->dispatch_table == NULL)
- goto err;
- }
- else {
- self->dispatch_table = dispatch_table;
- Py_INCREF(dispatch_table);
- }
- PyObject_GC_Track(self);
-
- return self;
+ Picklerobject *self;
+
+ if (proto < 0)
+ proto = HIGHEST_PROTOCOL;
+ if (proto > HIGHEST_PROTOCOL) {
+ PyErr_Format(PyExc_ValueError, "pickle protocol %d asked for; "
+ "the highest available protocol is %d",
+ proto, HIGHEST_PROTOCOL);
+ return NULL;
+ }
+
+ self = PyObject_GC_New(Picklerobject, &Picklertype);
+ if (self == NULL)
+ return NULL;
+ self->proto = proto;
+ self->bin = proto > 0;
+ self->fp = NULL;
+ self->write = NULL;
+ self->memo = NULL;
+ self->arg = NULL;
+ self->pers_func = NULL;
+ self->inst_pers_func = NULL;
+ self->write_buf = NULL;
+ self->fast = 0;
+ self->fast_container = 0;
+ self->fast_memo = NULL;
+ self->buf_size = 0;
+ self->dispatch_table = NULL;
+
+ self->file = NULL;
+ if (file)
+ Py_INCREF(file);
+ else {
+ file = Pdata_New();
+ if (file == NULL)
+ goto err;
+ }
+ self->file = file;
+
+ if (!( self->memo = PyDict_New()))
+ goto err;
+
+ if (PyFile_Check(file)) {
+ self->fp = PyFile_AsFile(file);
+ if (self->fp == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto err;
+ }
+ self->write_func = write_file;
+ }
+ else if (PycStringIO_OutputCheck(file)) {
+ self->write_func = write_cStringIO;
+ }
+ else if (file == Py_None) {
+ self->write_func = write_none;
+ }
+ else {
+ self->write_func = write_other;
+
+ if (! Pdata_Check(file)) {
+ self->write = PyObject_GetAttr(file, write_str);
+ if (!self->write) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "argument must have 'write' "
+ "attribute");
+ goto err;
+ }
+ }
+
+ self->write_buf = (char *)PyMem_Malloc(WRITE_BUF_SIZE);
+ if (self->write_buf == NULL) {
+ PyErr_NoMemory();
+ goto err;
+ }
+ }
+
+ if (PyEval_GetRestricted()) {
+ /* Restricted execution, get private tables */
+ PyObject *m = PyImport_ImportModule("copy_reg");
+
+ if (m == NULL)
+ goto err;
+ self->dispatch_table = PyObject_GetAttr(m, dispatch_table_str);
+ Py_DECREF(m);
+ if (self->dispatch_table == NULL)
+ goto err;
+ }
+ else {
+ self->dispatch_table = dispatch_table;
+ Py_INCREF(dispatch_table);
+ }
+ PyObject_GC_Track(self);
+
+ return self;
err:
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
static PyObject *
get_Pickler(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"file", "protocol", NULL};
- PyObject *file = NULL;
- int proto = 0;
-
- /* XXX
- * The documented signature is Pickler(file, protocol=0), but this
- * accepts Pickler() and Pickler(integer) too. The meaning then
- * is clear as mud, undocumented, and not supported by pickle.py.
- * I'm told Zope uses this, but I haven't traced into this code
- * far enough to figure out what it means.
- */
- if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) {
- PyErr_Clear();
- proto = 0;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:Pickler",
- kwlist, &file, &proto))
- return NULL;
- }
- return (PyObject *)newPicklerobject(file, proto);
+ static char *kwlist[] = {"file", "protocol", NULL};
+ PyObject *file = NULL;
+ int proto = 0;
+
+ /* XXX
+ * The documented signature is Pickler(file, protocol=0), but this
+ * accepts Pickler() and Pickler(integer) too. The meaning then
+ * is clear as mud, undocumented, and not supported by pickle.py.
+ * I'm told Zope uses this, but I haven't traced into this code
+ * far enough to figure out what it means.
+ */
+ if (!PyArg_ParseTuple(args, "|i:Pickler", &proto)) {
+ PyErr_Clear();
+ proto = 0;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|i:Pickler",
+ kwlist, &file, &proto))
+ return NULL;
+ }
+ return (PyObject *)newPicklerobject(file, proto);
}
static void
Pickler_dealloc(Picklerobject *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->write);
- Py_XDECREF(self->memo);
- Py_XDECREF(self->fast_memo);
- Py_XDECREF(self->arg);
- Py_XDECREF(self->file);
- Py_XDECREF(self->pers_func);
- Py_XDECREF(self->inst_pers_func);
- Py_XDECREF(self->dispatch_table);
- PyMem_Free(self->write_buf);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->write);
+ Py_XDECREF(self->memo);
+ Py_XDECREF(self->fast_memo);
+ Py_XDECREF(self->arg);
+ Py_XDECREF(self->file);
+ Py_XDECREF(self->pers_func);
+ Py_XDECREF(self->inst_pers_func);
+ Py_XDECREF(self->dispatch_table);
+ PyMem_Free(self->write_buf);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static int
Pickler_traverse(Picklerobject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->write);
- Py_VISIT(self->memo);
- Py_VISIT(self->fast_memo);
- Py_VISIT(self->arg);
- Py_VISIT(self->file);
- Py_VISIT(self->pers_func);
- Py_VISIT(self->inst_pers_func);
- Py_VISIT(self->dispatch_table);
- return 0;
+ Py_VISIT(self->write);
+ Py_VISIT(self->memo);
+ Py_VISIT(self->fast_memo);
+ Py_VISIT(self->arg);
+ Py_VISIT(self->file);
+ Py_VISIT(self->pers_func);
+ Py_VISIT(self->inst_pers_func);
+ Py_VISIT(self->dispatch_table);
+ return 0;
}
static int
Pickler_clear(Picklerobject *self)
{
- Py_CLEAR(self->write);
- Py_CLEAR(self->memo);
- Py_CLEAR(self->fast_memo);
- Py_CLEAR(self->arg);
- Py_CLEAR(self->file);
- Py_CLEAR(self->pers_func);
- Py_CLEAR(self->inst_pers_func);
- Py_CLEAR(self->dispatch_table);
- return 0;
+ Py_CLEAR(self->write);
+ Py_CLEAR(self->memo);
+ Py_CLEAR(self->fast_memo);
+ Py_CLEAR(self->arg);
+ Py_CLEAR(self->file);
+ Py_CLEAR(self->pers_func);
+ Py_CLEAR(self->inst_pers_func);
+ Py_CLEAR(self->dispatch_table);
+ return 0;
}
static PyObject *
Pickler_get_pers_func(Picklerobject *p)
{
- if (p->pers_func == NULL)
- PyErr_SetString(PyExc_AttributeError, "persistent_id");
- else
- Py_INCREF(p->pers_func);
- return p->pers_func;
+ if (p->pers_func == NULL)
+ PyErr_SetString(PyExc_AttributeError, "persistent_id");
+ else
+ Py_INCREF(p->pers_func);
+ return p->pers_func;
}
static int
Pickler_set_pers_func(Picklerobject *p, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
- Py_XDECREF(p->pers_func);
- Py_INCREF(v);
- p->pers_func = v;
- return 0;
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+ Py_XDECREF(p->pers_func);
+ Py_INCREF(v);
+ p->pers_func = v;
+ return 0;
}
static int
Pickler_set_inst_pers_func(Picklerobject *p, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
- Py_XDECREF(p->inst_pers_func);
- Py_INCREF(v);
- p->inst_pers_func = v;
- return 0;
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+ Py_XDECREF(p->inst_pers_func);
+ Py_INCREF(v);
+ p->inst_pers_func = v;
+ return 0;
}
static PyObject *
Pickler_get_memo(Picklerobject *p)
{
- if (p->memo == NULL)
- PyErr_SetString(PyExc_AttributeError, "memo");
- else
- Py_INCREF(p->memo);
- return p->memo;
+ if (p->memo == NULL)
+ PyErr_SetString(PyExc_AttributeError, "memo");
+ else
+ Py_INCREF(p->memo);
+ return p->memo;
}
static int
Pickler_set_memo(Picklerobject *p, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
- if (!PyDict_Check(v)) {
- PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
- return -1;
- }
- Py_XDECREF(p->memo);
- Py_INCREF(v);
- p->memo = v;
- return 0;
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+ if (!PyDict_Check(v)) {
+ PyErr_SetString(PyExc_TypeError, "memo must be a dictionary");
+ return -1;
+ }
+ Py_XDECREF(p->memo);
+ Py_INCREF(v);
+ p->memo = v;
+ return 0;
}
static PyObject *
Pickler_get_error(Picklerobject *p)
{
- /* why is this an attribute on the Pickler? */
- Py_INCREF(PicklingError);
- return PicklingError;
+ /* why is this an attribute on the Pickler? */
+ Py_INCREF(PicklingError);
+ return PicklingError;
}
static PyMemberDef Pickler_members[] = {
@@ -3254,143 +3254,143 @@ static PyTypeObject Picklertype = {
"cPickle.Pickler", /*tp_name*/
sizeof(Picklerobject), /*tp_basicsize*/
0,
- (destructor)Pickler_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 */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
+ (destructor)Pickler_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 */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- Picklertype__doc__, /* tp_doc */
- (traverseproc)Pickler_traverse, /* tp_traverse */
- (inquiry)Pickler_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- Pickler_methods, /* tp_methods */
- Pickler_members, /* tp_members */
- Pickler_getsets, /* tp_getset */
+ Picklertype__doc__, /* tp_doc */
+ (traverseproc)Pickler_traverse, /* tp_traverse */
+ (inquiry)Pickler_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ Pickler_methods, /* tp_methods */
+ Pickler_members, /* tp_members */
+ Pickler_getsets, /* tp_getset */
};
static PyObject *
find_class(PyObject *py_module_name, PyObject *py_global_name, PyObject *fc)
{
- PyObject *global = 0, *module;
-
- if (fc) {
- if (fc==Py_None) {
- PyErr_SetString(UnpicklingError, "Global and instance "
- "pickles are not supported.");
- return NULL;
- }
- return PyObject_CallFunctionObjArgs(fc, py_module_name,
- py_global_name, NULL);
- }
-
- module = PySys_GetObject("modules");
- if (module == NULL)
- return NULL;
-
- module = PyDict_GetItem(module, py_module_name);
- if (module == NULL) {
- module = PyImport_Import(py_module_name);
- if (!module)
- return NULL;
- global = PyObject_GetAttr(module, py_global_name);
- Py_DECREF(module);
- }
- else
- global = PyObject_GetAttr(module, py_global_name);
- return global;
+ PyObject *global = 0, *module;
+
+ if (fc) {
+ if (fc==Py_None) {
+ PyErr_SetString(UnpicklingError, "Global and instance "
+ "pickles are not supported.");
+ return NULL;
+ }
+ return PyObject_CallFunctionObjArgs(fc, py_module_name,
+ py_global_name, NULL);
+ }
+
+ module = PySys_GetObject("modules");
+ if (module == NULL)
+ return NULL;
+
+ module = PyDict_GetItem(module, py_module_name);
+ if (module == NULL) {
+ module = PyImport_Import(py_module_name);
+ if (!module)
+ return NULL;
+ global = PyObject_GetAttr(module, py_global_name);
+ Py_DECREF(module);
+ }
+ else
+ global = PyObject_GetAttr(module, py_global_name);
+ return global;
}
static int
marker(Unpicklerobject *self)
{
- if (self->num_marks < 1) {
- PyErr_SetString(UnpicklingError, "could not find MARK");
- return -1;
- }
+ if (self->num_marks < 1) {
+ PyErr_SetString(UnpicklingError, "could not find MARK");
+ return -1;
+ }
- return self->marks[--self->num_marks];
+ return self->marks[--self->num_marks];
}
static int
load_none(Unpicklerobject *self)
{
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
bad_readline(void)
{
- PyErr_SetString(UnpicklingError, "pickle data was truncated");
- return -1;
+ PyErr_SetString(UnpicklingError, "pickle data was truncated");
+ return -1;
}
static int
load_int(Unpicklerobject *self)
{
- PyObject *py_int = 0;
- char *endptr, *s;
- int len, res = -1;
- long l;
-
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
-
- errno = 0;
- l = strtol(s, &endptr, 0);
-
- if (errno || (*endptr != '\n') || (endptr[1] != '\0')) {
- /* Hm, maybe we've got something long. Let's try reading
- it as a Python long object. */
- errno = 0;
- py_int = PyLong_FromString(s, NULL, 0);
- if (py_int == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert string to int");
- goto finally;
- }
- }
- else {
- if (len == 3 && (l == 0 || l == 1)) {
- if (!( py_int = PyBool_FromLong(l))) goto finally;
- }
- else {
- if (!( py_int = PyInt_FromLong(l))) goto finally;
- }
- }
-
- free(s);
- PDATA_PUSH(self->stack, py_int, -1);
- return 0;
+ PyObject *py_int = 0;
+ char *endptr, *s;
+ int len, res = -1;
+ long l;
+
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
+
+ errno = 0;
+ l = strtol(s, &endptr, 0);
+
+ if (errno || (*endptr != '\n') || (endptr[1] != '\0')) {
+ /* Hm, maybe we've got something long. Let's try reading
+ it as a Python long object. */
+ errno = 0;
+ py_int = PyLong_FromString(s, NULL, 0);
+ if (py_int == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert string to int");
+ goto finally;
+ }
+ }
+ else {
+ if (len == 3 && (l == 0 || l == 1)) {
+ if (!( py_int = PyBool_FromLong(l))) goto finally;
+ }
+ else {
+ if (!( py_int = PyInt_FromLong(l))) goto finally;
+ }
+ }
+
+ free(s);
+ PDATA_PUSH(self->stack, py_int, -1);
+ return 0;
finally:
- free(s);
+ free(s);
- return res;
+ return res;
}
static int
load_bool(Unpicklerobject *self, PyObject *boolean)
{
- assert(boolean == Py_True || boolean == Py_False);
- PDATA_APPEND(self->stack, boolean, -1);
- return 0;
+ assert(boolean == Py_True || boolean == Py_False);
+ PDATA_APPEND(self->stack, boolean, -1);
+ return 0;
}
/* s contains x bytes of a little-endian integer. Return its value as a
@@ -3401,99 +3401,99 @@ load_bool(Unpicklerobject *self, PyObject *boolean)
static long
calc_binint(char *s, int x)
{
- unsigned char c;
- int i;
- long l;
+ unsigned char c;
+ int i;
+ long l;
- for (i = 0, l = 0L; i < x; i++) {
- c = (unsigned char)s[i];
- l |= (long)c << (i * 8);
- }
+ for (i = 0, l = 0L; i < x; i++) {
+ c = (unsigned char)s[i];
+ l |= (long)c << (i * 8);
+ }
#if SIZEOF_LONG > 4
- /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
- * is signed, so on a box with longs bigger than 4 bytes we need
- * to extend a BININT's sign bit to the full width.
- */
- if (x == 4 && l & (1L << 31))
- l |= (~0L) << 32;
+ /* Unlike BININT1 and BININT2, BININT (more accurately BININT4)
+ * is signed, so on a box with longs bigger than 4 bytes we need
+ * to extend a BININT's sign bit to the full width.
+ */
+ if (x == 4 && l & (1L << 31))
+ l |= (~0L) << 32;
#endif
- return l;
+ return l;
}
static int
load_binintx(Unpicklerobject *self, char *s, int x)
{
- PyObject *py_int = 0;
- long l;
+ PyObject *py_int = 0;
+ long l;
- l = calc_binint(s, x);
+ l = calc_binint(s, x);
- if (!( py_int = PyInt_FromLong(l)))
- return -1;
+ if (!( py_int = PyInt_FromLong(l)))
+ return -1;
- PDATA_PUSH(self->stack, py_int, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_int, -1);
+ return 0;
}
static int
load_binint(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->read_func(self, &s, 4) < 0)
- return -1;
+ if (self->read_func(self, &s, 4) < 0)
+ return -1;
- return load_binintx(self, s, 4);
+ return load_binintx(self, s, 4);
}
static int
load_binint1(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->read_func(self, &s, 1) < 0)
- return -1;
+ if (self->read_func(self, &s, 1) < 0)
+ return -1;
- return load_binintx(self, s, 1);
+ return load_binintx(self, s, 1);
}
static int
load_binint2(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->read_func(self, &s, 2) < 0)
- return -1;
+ if (self->read_func(self, &s, 2) < 0)
+ return -1;
- return load_binintx(self, s, 2);
+ return load_binintx(self, s, 2);
}
static int
load_long(Unpicklerobject *self)
{
- PyObject *l = 0;
- char *end, *s;
- int len, res = -1;
+ PyObject *l = 0;
+ char *end, *s;
+ int len, res = -1;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
- if (!( l = PyLong_FromString(s, &end, 0)))
- goto finally;
+ if (!( l = PyLong_FromString(s, &end, 0)))
+ goto finally;
- free(s);
- PDATA_PUSH(self->stack, l, -1);
- return 0;
+ free(s);
+ PDATA_PUSH(self->stack, l, -1);
+ return 0;
finally:
- free(s);
+ free(s);
- return res;
+ return res;
}
/* 'size' bytes contain the # of bytes of little-endian 256's-complement
@@ -3502,187 +3502,187 @@ load_long(Unpicklerobject *self)
static int
load_counted_long(Unpicklerobject *self, int size)
{
- Py_ssize_t i;
- char *nbytes;
- unsigned char *pdata;
- PyObject *along;
-
- assert(size == 1 || size == 4);
- i = self->read_func(self, &nbytes, size);
- if (i < 0) return -1;
-
- size = calc_binint(nbytes, size);
- if (size < 0) {
- /* Corrupt or hostile pickle -- we never write one like
- * this.
- */
- PyErr_SetString(UnpicklingError, "LONG pickle has negative "
- "byte count");
- return -1;
- }
-
- if (size == 0)
- along = PyLong_FromLong(0L);
- else {
- /* Read the raw little-endian bytes & convert. */
- i = self->read_func(self, (char **)&pdata, size);
- if (i < 0) return -1;
- along = _PyLong_FromByteArray(pdata, (size_t)size,
- 1 /* little endian */, 1 /* signed */);
- }
- if (along == NULL)
- return -1;
- PDATA_PUSH(self->stack, along, -1);
- return 0;
+ Py_ssize_t i;
+ char *nbytes;
+ unsigned char *pdata;
+ PyObject *along;
+
+ assert(size == 1 || size == 4);
+ i = self->read_func(self, &nbytes, size);
+ if (i < 0) return -1;
+
+ size = calc_binint(nbytes, size);
+ if (size < 0) {
+ /* Corrupt or hostile pickle -- we never write one like
+ * this.
+ */
+ PyErr_SetString(UnpicklingError, "LONG pickle has negative "
+ "byte count");
+ return -1;
+ }
+
+ if (size == 0)
+ along = PyLong_FromLong(0L);
+ else {
+ /* Read the raw little-endian bytes & convert. */
+ i = self->read_func(self, (char **)&pdata, size);
+ if (i < 0) return -1;
+ along = _PyLong_FromByteArray(pdata, (size_t)size,
+ 1 /* little endian */, 1 /* signed */);
+ }
+ if (along == NULL)
+ return -1;
+ PDATA_PUSH(self->stack, along, -1);
+ return 0;
}
static int
load_float(Unpicklerobject *self)
{
- PyObject *py_float = 0;
- char *endptr, *s;
- int len, res = -1;
- double d;
+ PyObject *py_float = 0;
+ char *endptr, *s;
+ int len, res = -1;
+ double d;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
- d = PyOS_string_to_double(s, &endptr, PyExc_OverflowError);
+ d = PyOS_string_to_double(s, &endptr, PyExc_OverflowError);
- if (d == -1.0 && PyErr_Occurred()) {
- goto finally;
- } else if ((endptr[0] != '\n') || (endptr[1] != '\0')) {
- PyErr_SetString(PyExc_ValueError,
- "could not convert string to float");
- goto finally;
- }
+ if (d == -1.0 && PyErr_Occurred()) {
+ goto finally;
+ } else if ((endptr[0] != '\n') || (endptr[1] != '\0')) {
+ PyErr_SetString(PyExc_ValueError,
+ "could not convert string to float");
+ goto finally;
+ }
- if (!( py_float = PyFloat_FromDouble(d)))
- goto finally;
+ if (!( py_float = PyFloat_FromDouble(d)))
+ goto finally;
- free(s);
- PDATA_PUSH(self->stack, py_float, -1);
- return 0;
+ free(s);
+ PDATA_PUSH(self->stack, py_float, -1);
+ return 0;
finally:
- free(s);
+ free(s);
- return res;
+ return res;
}
static int
load_binfloat(Unpicklerobject *self)
{
- PyObject *py_float;
- double x;
- char *p;
+ PyObject *py_float;
+ double x;
+ char *p;
- if (self->read_func(self, &p, 8) < 0)
- return -1;
+ if (self->read_func(self, &p, 8) < 0)
+ return -1;
- x = _PyFloat_Unpack8((unsigned char *)p, 0);
- if (x == -1.0 && PyErr_Occurred())
- return -1;
+ x = _PyFloat_Unpack8((unsigned char *)p, 0);
+ if (x == -1.0 && PyErr_Occurred())
+ return -1;
- py_float = PyFloat_FromDouble(x);
- if (py_float == NULL)
- return -1;
+ py_float = PyFloat_FromDouble(x);
+ if (py_float == NULL)
+ return -1;
- PDATA_PUSH(self->stack, py_float, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_float, -1);
+ return 0;
}
static int
load_string(Unpicklerobject *self)
{
- PyObject *str = 0;
- int len, res = -1;
- char *s, *p;
-
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- if (!( s=pystrndup(s,len))) return -1;
-
-
- /* Strip outermost quotes */
- while (s[len-1] <= ' ')
- len--;
- if(s[0]=='"' && s[len-1]=='"'){
- s[len-1] = '\0';
- p = s + 1 ;
- len -= 2;
- } else if(s[0]=='\'' && s[len-1]=='\''){
- s[len-1] = '\0';
- p = s + 1 ;
- len -= 2;
- } else
- goto insecure;
- /********************************************/
-
- str = PyString_DecodeEscape(p, len, NULL, 0, NULL);
- free(s);
- if (str) {
- PDATA_PUSH(self->stack, str, -1);
- res = 0;
- }
- return res;
+ PyObject *str = 0;
+ int len, res = -1;
+ char *s, *p;
+
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ if (!( s=pystrndup(s,len))) return -1;
+
+
+ /* Strip outermost quotes */
+ while (s[len-1] <= ' ')
+ len--;
+ if(s[0]=='"' && s[len-1]=='"'){
+ s[len-1] = '\0';
+ p = s + 1 ;
+ len -= 2;
+ } else if(s[0]=='\'' && s[len-1]=='\''){
+ s[len-1] = '\0';
+ p = s + 1 ;
+ len -= 2;
+ } else
+ goto insecure;
+ /********************************************/
+
+ str = PyString_DecodeEscape(p, len, NULL, 0, NULL);
+ free(s);
+ if (str) {
+ PDATA_PUSH(self->stack, str, -1);
+ res = 0;
+ }
+ return res;
insecure:
- free(s);
- PyErr_SetString(PyExc_ValueError,"insecure string pickle");
- return -1;
+ free(s);
+ PyErr_SetString(PyExc_ValueError,"insecure string pickle");
+ return -1;
}
static int
load_binstring(Unpicklerobject *self)
{
- PyObject *py_string = 0;
- long l;
- char *s;
+ PyObject *py_string = 0;
+ long l;
+ char *s;
- if (self->read_func(self, &s, 4) < 0) return -1;
+ if (self->read_func(self, &s, 4) < 0) return -1;
- l = calc_binint(s, 4);
- if (l < 0) {
- /* Corrupt or hostile pickle -- we never write one like
- * this.
- */
- PyErr_SetString(UnpicklingError,
- "BINSTRING pickle has negative byte count");
- return -1;
- }
+ l = calc_binint(s, 4);
+ if (l < 0) {
+ /* Corrupt or hostile pickle -- we never write one like
+ * this.
+ */
+ PyErr_SetString(UnpicklingError,
+ "BINSTRING pickle has negative byte count");
+ return -1;
+ }
- if (self->read_func(self, &s, l) < 0)
- return -1;
+ if (self->read_func(self, &s, l) < 0)
+ return -1;
- if (!( py_string = PyString_FromStringAndSize(s, l)))
- return -1;
+ if (!( py_string = PyString_FromStringAndSize(s, l)))
+ return -1;
- PDATA_PUSH(self->stack, py_string, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_string, -1);
+ return 0;
}
static int
load_short_binstring(Unpicklerobject *self)
{
- PyObject *py_string = 0;
- unsigned char l;
- char *s;
+ PyObject *py_string = 0;
+ unsigned char l;
+ char *s;
- if (self->read_func(self, &s, 1) < 0)
- return -1;
+ if (self->read_func(self, &s, 1) < 0)
+ return -1;
- l = (unsigned char)s[0];
+ l = (unsigned char)s[0];
- if (self->read_func(self, &s, l) < 0) return -1;
+ if (self->read_func(self, &s, l) < 0) return -1;
- if (!( py_string = PyString_FromStringAndSize(s, l))) return -1;
+ if (!( py_string = PyString_FromStringAndSize(s, l))) return -1;
- PDATA_PUSH(self->stack, py_string, -1);
- return 0;
+ PDATA_PUSH(self->stack, py_string, -1);
+ return 0;
}
@@ -3690,21 +3690,21 @@ load_short_binstring(Unpicklerobject *self)
static int
load_unicode(Unpicklerobject *self)
{
- PyObject *str = 0;
- int len, res = -1;
- char *s;
+ PyObject *str = 0;
+ int len, res = -1;
+ char *s;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 1) return bad_readline();
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 1) return bad_readline();
- if (!( str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL)))
- goto finally;
+ if (!( str = PyUnicode_DecodeRawUnicodeEscape(s, len - 1, NULL)))
+ goto finally;
- PDATA_PUSH(self->stack, str, -1);
- return 0;
+ PDATA_PUSH(self->stack, str, -1);
+ return 0;
finally:
- return res;
+ return res;
}
#endif
@@ -3713,30 +3713,30 @@ load_unicode(Unpicklerobject *self)
static int
load_binunicode(Unpicklerobject *self)
{
- PyObject *unicode;
- long l;
- char *s;
+ PyObject *unicode;
+ long l;
+ char *s;
- if (self->read_func(self, &s, 4) < 0) return -1;
+ if (self->read_func(self, &s, 4) < 0) return -1;
- l = calc_binint(s, 4);
- if (l < 0) {
- /* Corrupt or hostile pickle -- we never write one like
- * this.
- */
- PyErr_SetString(UnpicklingError,
- "BINUNICODE pickle has negative byte count");
- return -1;
- }
+ l = calc_binint(s, 4);
+ if (l < 0) {
+ /* Corrupt or hostile pickle -- we never write one like
+ * this.
+ */
+ PyErr_SetString(UnpicklingError,
+ "BINUNICODE pickle has negative byte count");
+ return -1;
+ }
- if (self->read_func(self, &s, l) < 0)
- return -1;
+ if (self->read_func(self, &s, l) < 0)
+ return -1;
- if (!( unicode = PyUnicode_DecodeUTF8(s, l, NULL)))
- return -1;
+ if (!( unicode = PyUnicode_DecodeUTF8(s, l, NULL)))
+ return -1;
- PDATA_PUSH(self->stack, unicode, -1);
- return 0;
+ PDATA_PUSH(self->stack, unicode, -1);
+ return 0;
}
#endif
@@ -3744,504 +3744,504 @@ load_binunicode(Unpicklerobject *self)
static int
load_tuple(Unpicklerobject *self)
{
- PyObject *tup;
- int i;
+ PyObject *tup;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- if (!( tup=Pdata_popTuple(self->stack, i))) return -1;
- PDATA_PUSH(self->stack, tup, -1);
- return 0;
+ if ((i = marker(self)) < 0) return -1;
+ if (!( tup=Pdata_popTuple(self->stack, i))) return -1;
+ PDATA_PUSH(self->stack, tup, -1);
+ return 0;
}
static int
load_counted_tuple(Unpicklerobject *self, int len)
{
- PyObject *tup = PyTuple_New(len);
+ PyObject *tup = PyTuple_New(len);
- if (tup == NULL)
- return -1;
+ if (tup == NULL)
+ return -1;
- while (--len >= 0) {
- PyObject *element;
+ while (--len >= 0) {
+ PyObject *element;
- PDATA_POP(self->stack, element);
- if (element == NULL)
- return -1;
- PyTuple_SET_ITEM(tup, len, element);
- }
- PDATA_PUSH(self->stack, tup, -1);
- return 0;
+ PDATA_POP(self->stack, element);
+ if (element == NULL)
+ return -1;
+ PyTuple_SET_ITEM(tup, len, element);
+ }
+ PDATA_PUSH(self->stack, tup, -1);
+ return 0;
}
static int
load_empty_list(Unpicklerobject *self)
{
- PyObject *list;
+ PyObject *list;
- if (!( list=PyList_New(0))) return -1;
- PDATA_PUSH(self->stack, list, -1);
- return 0;
+ if (!( list=PyList_New(0))) return -1;
+ PDATA_PUSH(self->stack, list, -1);
+ return 0;
}
static int
load_empty_dict(Unpicklerobject *self)
{
- PyObject *dict;
+ PyObject *dict;
- if (!( dict=PyDict_New())) return -1;
- PDATA_PUSH(self->stack, dict, -1);
- return 0;
+ if (!( dict=PyDict_New())) return -1;
+ PDATA_PUSH(self->stack, dict, -1);
+ return 0;
}
static int
load_list(Unpicklerobject *self)
{
- PyObject *list = 0;
- int i;
+ PyObject *list = 0;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- if (!( list=Pdata_popList(self->stack, i))) return -1;
- PDATA_PUSH(self->stack, list, -1);
- return 0;
+ if ((i = marker(self)) < 0) return -1;
+ if (!( list=Pdata_popList(self->stack, i))) return -1;
+ PDATA_PUSH(self->stack, list, -1);
+ return 0;
}
static int
load_dict(Unpicklerobject *self)
{
- PyObject *dict, *key, *value;
- int i, j, k;
+ PyObject *dict, *key, *value;
+ int i, j, k;
- if ((i = marker(self)) < 0) return -1;
- j=self->stack->length;
+ if ((i = marker(self)) < 0) return -1;
+ j=self->stack->length;
- if (!( dict = PyDict_New())) return -1;
+ if (!( dict = PyDict_New())) return -1;
- for (k = i+1; k < j; k += 2) {
- key =self->stack->data[k-1];
- value=self->stack->data[k ];
- if (PyDict_SetItem(dict, key, value) < 0) {
- Py_DECREF(dict);
- return -1;
- }
- }
- Pdata_clear(self->stack, i);
- PDATA_PUSH(self->stack, dict, -1);
- return 0;
+ for (k = i+1; k < j; k += 2) {
+ key =self->stack->data[k-1];
+ value=self->stack->data[k ];
+ if (PyDict_SetItem(dict, key, value) < 0) {
+ Py_DECREF(dict);
+ return -1;
+ }
+ }
+ Pdata_clear(self->stack, i);
+ PDATA_PUSH(self->stack, dict, -1);
+ return 0;
}
static PyObject *
Instance_New(PyObject *cls, PyObject *args)
{
- PyObject *r = 0;
+ PyObject *r = 0;
- if (PyClass_Check(cls)) {
- int l;
+ if (PyClass_Check(cls)) {
+ int l;
- if ((l=PyObject_Size(args)) < 0) goto err;
- if (!( l )) {
- PyObject *__getinitargs__;
+ if ((l=PyObject_Size(args)) < 0) goto err;
+ if (!( l )) {
+ PyObject *__getinitargs__;
- __getinitargs__ = PyObject_GetAttr(cls,
- __getinitargs___str);
- if (!__getinitargs__) {
- /* We have a class with no __getinitargs__,
- so bypass usual construction */
- PyObject *inst;
+ __getinitargs__ = PyObject_GetAttr(cls,
+ __getinitargs___str);
+ if (!__getinitargs__) {
+ /* We have a class with no __getinitargs__,
+ so bypass usual construction */
+ PyObject *inst;
- PyErr_Clear();
- if (!( inst=PyInstance_NewRaw(cls, NULL)))
- goto err;
- return inst;
- }
- Py_DECREF(__getinitargs__);
- }
+ PyErr_Clear();
+ if (!( inst=PyInstance_NewRaw(cls, NULL)))
+ goto err;
+ return inst;
+ }
+ Py_DECREF(__getinitargs__);
+ }
- if ((r=PyInstance_New(cls, args, NULL))) return r;
- else goto err;
- }
+ if ((r=PyInstance_New(cls, args, NULL))) return r;
+ else goto err;
+ }
- if ((r=PyObject_CallObject(cls, args))) return r;
+ if ((r=PyObject_CallObject(cls, args))) return r;
err:
- {
- PyObject *tp, *v, *tb, *tmp_value;
-
- PyErr_Fetch(&tp, &v, &tb);
- tmp_value = v;
- /* NULL occurs when there was a KeyboardInterrupt */
- if (tmp_value == NULL)
- tmp_value = Py_None;
- if ((r = PyTuple_Pack(3, tmp_value, cls, args))) {
- Py_XDECREF(v);
- v=r;
- }
- PyErr_Restore(tp,v,tb);
- }
- return NULL;
+ {
+ PyObject *tp, *v, *tb, *tmp_value;
+
+ PyErr_Fetch(&tp, &v, &tb);
+ tmp_value = v;
+ /* NULL occurs when there was a KeyboardInterrupt */
+ if (tmp_value == NULL)
+ tmp_value = Py_None;
+ if ((r = PyTuple_Pack(3, tmp_value, cls, args))) {
+ Py_XDECREF(v);
+ v=r;
+ }
+ PyErr_Restore(tp,v,tb);
+ }
+ return NULL;
}
static int
load_obj(Unpicklerobject *self)
{
- PyObject *class, *tup, *obj=0;
- int i;
+ PyObject *class, *tup, *obj=0;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1;
- PDATA_POP(self->stack, class);
- if (class) {
- obj = Instance_New(class, tup);
- Py_DECREF(class);
- }
- Py_DECREF(tup);
+ if ((i = marker(self)) < 0) return -1;
+ if (!( tup=Pdata_popTuple(self->stack, i+1))) return -1;
+ PDATA_POP(self->stack, class);
+ if (class) {
+ obj = Instance_New(class, tup);
+ Py_DECREF(class);
+ }
+ Py_DECREF(tup);
- if (! obj) return -1;
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ if (! obj) return -1;
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
}
static int
load_inst(Unpicklerobject *self)
{
- PyObject *tup, *class=0, *obj=0, *module_name, *class_name;
- int i, len;
- char *s;
+ PyObject *tup, *class=0, *obj=0, *module_name, *class_name;
+ int i, len;
+ char *s;
- if ((i = marker(self)) < 0) return -1;
+ if ((i = marker(self)) < 0) return -1;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- module_name = PyString_FromStringAndSize(s, len - 1);
- if (!module_name) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ module_name = PyString_FromStringAndSize(s, len - 1);
+ if (!module_name) return -1;
- if ((len = self->readline_func(self, &s)) >= 0) {
- if (len < 2) return bad_readline();
- if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
- class = find_class(module_name, class_name,
- self->find_class);
- Py_DECREF(class_name);
- }
- }
- Py_DECREF(module_name);
+ if ((len = self->readline_func(self, &s)) >= 0) {
+ if (len < 2) return bad_readline();
+ if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
+ class = find_class(module_name, class_name,
+ self->find_class);
+ Py_DECREF(class_name);
+ }
+ }
+ Py_DECREF(module_name);
- if (! class) return -1;
+ if (! class) return -1;
- if ((tup=Pdata_popTuple(self->stack, i))) {
- obj = Instance_New(class, tup);
- Py_DECREF(tup);
- }
- Py_DECREF(class);
+ if ((tup=Pdata_popTuple(self->stack, i))) {
+ obj = Instance_New(class, tup);
+ Py_DECREF(tup);
+ }
+ Py_DECREF(class);
- if (! obj) return -1;
+ if (! obj) return -1;
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
}
static int
load_newobj(Unpicklerobject *self)
{
- PyObject *args = NULL;
- PyObject *clsraw = NULL;
- PyTypeObject *cls; /* clsraw cast to its true type */
- PyObject *obj;
-
- /* Stack is ... cls argtuple, and we want to call
- * cls.__new__(cls, *argtuple).
- */
- PDATA_POP(self->stack, args);
- if (args == NULL) goto Fail;
- if (! PyTuple_Check(args)) {
- PyErr_SetString(UnpicklingError, "NEWOBJ expected an arg "
- "tuple.");
- goto Fail;
- }
-
- PDATA_POP(self->stack, clsraw);
- cls = (PyTypeObject *)clsraw;
- if (cls == NULL) goto Fail;
- if (! PyType_Check(cls)) {
- PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
- "isn't a type object");
- goto Fail;
- }
- if (cls->tp_new == NULL) {
- PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
- "has NULL tp_new");
- goto Fail;
- }
-
- /* Call __new__. */
- obj = cls->tp_new(cls, args, NULL);
- if (obj == NULL) goto Fail;
-
- Py_DECREF(args);
- Py_DECREF(clsraw);
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ PyObject *args = NULL;
+ PyObject *clsraw = NULL;
+ PyTypeObject *cls; /* clsraw cast to its true type */
+ PyObject *obj;
+
+ /* Stack is ... cls argtuple, and we want to call
+ * cls.__new__(cls, *argtuple).
+ */
+ PDATA_POP(self->stack, args);
+ if (args == NULL) goto Fail;
+ if (! PyTuple_Check(args)) {
+ PyErr_SetString(UnpicklingError, "NEWOBJ expected an arg "
+ "tuple.");
+ goto Fail;
+ }
+
+ PDATA_POP(self->stack, clsraw);
+ cls = (PyTypeObject *)clsraw;
+ if (cls == NULL) goto Fail;
+ if (! PyType_Check(cls)) {
+ PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
+ "isn't a type object");
+ goto Fail;
+ }
+ if (cls->tp_new == NULL) {
+ PyErr_SetString(UnpicklingError, "NEWOBJ class argument "
+ "has NULL tp_new");
+ goto Fail;
+ }
+
+ /* Call __new__. */
+ obj = cls->tp_new(cls, args, NULL);
+ if (obj == NULL) goto Fail;
+
+ Py_DECREF(args);
+ Py_DECREF(clsraw);
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
Fail:
- Py_XDECREF(args);
- Py_XDECREF(clsraw);
- return -1;
+ Py_XDECREF(args);
+ Py_XDECREF(clsraw);
+ return -1;
}
static int
load_global(Unpicklerobject *self)
{
- PyObject *class = 0, *module_name = 0, *class_name = 0;
- int len;
- char *s;
+ PyObject *class = 0, *module_name = 0, *class_name = 0;
+ int len;
+ char *s;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
- module_name = PyString_FromStringAndSize(s, len - 1);
- if (!module_name) return -1;
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+ module_name = PyString_FromStringAndSize(s, len - 1);
+ if (!module_name) return -1;
- if ((len = self->readline_func(self, &s)) >= 0) {
- if (len < 2) {
- Py_DECREF(module_name);
- return bad_readline();
- }
- if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
- class = find_class(module_name, class_name,
- self->find_class);
- Py_DECREF(class_name);
- }
- }
- Py_DECREF(module_name);
+ if ((len = self->readline_func(self, &s)) >= 0) {
+ if (len < 2) {
+ Py_DECREF(module_name);
+ return bad_readline();
+ }
+ if ((class_name = PyString_FromStringAndSize(s, len - 1))) {
+ class = find_class(module_name, class_name,
+ self->find_class);
+ Py_DECREF(class_name);
+ }
+ }
+ Py_DECREF(module_name);
- if (! class) return -1;
- PDATA_PUSH(self->stack, class, -1);
- return 0;
+ if (! class) return -1;
+ PDATA_PUSH(self->stack, class, -1);
+ return 0;
}
static int
load_persid(Unpicklerobject *self)
{
- PyObject *pid = 0;
- int len;
- char *s;
-
- if (self->pers_func) {
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
-
- pid = PyString_FromStringAndSize(s, len - 1);
- if (!pid) return -1;
-
- if (PyList_Check(self->pers_func)) {
- if (PyList_Append(self->pers_func, pid) < 0) {
- Py_DECREF(pid);
- return -1;
- }
- }
- else {
- ARG_TUP(self, pid);
- if (self->arg) {
- pid = PyObject_Call(self->pers_func, self->arg,
- NULL);
- FREE_ARG_TUP(self);
- }
- }
-
- if (! pid) return -1;
-
- PDATA_PUSH(self->stack, pid, -1);
- return 0;
- }
- else {
- PyErr_SetString(UnpicklingError,
- "A load persistent id instruction was encountered,\n"
- "but no persistent_load function was specified.");
- return -1;
- }
+ PyObject *pid = 0;
+ int len;
+ char *s;
+
+ if (self->pers_func) {
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
+
+ pid = PyString_FromStringAndSize(s, len - 1);
+ if (!pid) return -1;
+
+ if (PyList_Check(self->pers_func)) {
+ if (PyList_Append(self->pers_func, pid) < 0) {
+ Py_DECREF(pid);
+ return -1;
+ }
+ }
+ else {
+ ARG_TUP(self, pid);
+ if (self->arg) {
+ pid = PyObject_Call(self->pers_func, self->arg,
+ NULL);
+ FREE_ARG_TUP(self);
+ }
+ }
+
+ if (! pid) return -1;
+
+ PDATA_PUSH(self->stack, pid, -1);
+ return 0;
+ }
+ else {
+ PyErr_SetString(UnpicklingError,
+ "A load persistent id instruction was encountered,\n"
+ "but no persistent_load function was specified.");
+ return -1;
+ }
}
static int
load_binpersid(Unpicklerobject *self)
{
- PyObject *pid = 0;
-
- if (self->pers_func) {
- PDATA_POP(self->stack, pid);
- if (! pid) return -1;
-
- if (PyList_Check(self->pers_func)) {
- if (PyList_Append(self->pers_func, pid) < 0) {
- Py_DECREF(pid);
- return -1;
- }
- }
- else {
- ARG_TUP(self, pid);
- if (self->arg) {
- pid = PyObject_Call(self->pers_func, self->arg,
- NULL);
- FREE_ARG_TUP(self);
- }
- if (! pid) return -1;
- }
-
- PDATA_PUSH(self->stack, pid, -1);
- return 0;
- }
- else {
- PyErr_SetString(UnpicklingError,
- "A load persistent id instruction was encountered,\n"
- "but no persistent_load function was specified.");
- return -1;
- }
+ PyObject *pid = 0;
+
+ if (self->pers_func) {
+ PDATA_POP(self->stack, pid);
+ if (! pid) return -1;
+
+ if (PyList_Check(self->pers_func)) {
+ if (PyList_Append(self->pers_func, pid) < 0) {
+ Py_DECREF(pid);
+ return -1;
+ }
+ }
+ else {
+ ARG_TUP(self, pid);
+ if (self->arg) {
+ pid = PyObject_Call(self->pers_func, self->arg,
+ NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! pid) return -1;
+ }
+
+ PDATA_PUSH(self->stack, pid, -1);
+ return 0;
+ }
+ else {
+ PyErr_SetString(UnpicklingError,
+ "A load persistent id instruction was encountered,\n"
+ "but no persistent_load function was specified.");
+ return -1;
+ }
}
static int
load_pop(Unpicklerobject *self)
{
- int len = self->stack->length;
-
- /* Note that we split the (pickle.py) stack into two stacks,
- an object stack and a mark stack. We have to be clever and
- pop the right one. We do this by looking at the top of the
- mark stack first, and only signalling a stack underflow if
- the object stack is empty and the mark stack doesn't match
- our expectations.
- */
- if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) {
- self->num_marks--;
- } else if (len > 0) {
- len--;
- Py_DECREF(self->stack->data[len]);
- self->stack->length = len;
- } else {
- return stackUnderflow();
- }
- return 0;
+ int len = self->stack->length;
+
+ /* Note that we split the (pickle.py) stack into two stacks,
+ an object stack and a mark stack. We have to be clever and
+ pop the right one. We do this by looking at the top of the
+ mark stack first, and only signalling a stack underflow if
+ the object stack is empty and the mark stack doesn't match
+ our expectations.
+ */
+ if (self->num_marks > 0 && self->marks[self->num_marks - 1] == len) {
+ self->num_marks--;
+ } else if (len > 0) {
+ len--;
+ Py_DECREF(self->stack->data[len]);
+ self->stack->length = len;
+ } else {
+ return stackUnderflow();
+ }
+ return 0;
}
static int
load_pop_mark(Unpicklerobject *self)
{
- int i;
+ int i;
- if ((i = marker(self)) < 0)
- return -1;
+ if ((i = marker(self)) < 0)
+ return -1;
- Pdata_clear(self->stack, i);
+ Pdata_clear(self->stack, i);
- return 0;
+ return 0;
}
static int
load_dup(Unpicklerobject *self)
{
- PyObject *last;
- int len;
+ PyObject *last;
+ int len;
- if ((len = self->stack->length) <= 0) return stackUnderflow();
- last=self->stack->data[len-1];
- Py_INCREF(last);
- PDATA_PUSH(self->stack, last, -1);
- return 0;
+ if ((len = self->stack->length) <= 0) return stackUnderflow();
+ last=self->stack->data[len-1];
+ Py_INCREF(last);
+ PDATA_PUSH(self->stack, last, -1);
+ return 0;
}
static int
load_get(Unpicklerobject *self)
{
- PyObject *py_str = 0, *value = 0;
- int len;
- char *s;
- int rc;
+ PyObject *py_str = 0, *value = 0;
+ int len;
+ char *s;
+ int rc;
- if ((len = self->readline_func(self, &s)) < 0) return -1;
- if (len < 2) return bad_readline();
+ if ((len = self->readline_func(self, &s)) < 0) return -1;
+ if (len < 2) return bad_readline();
- if (!( py_str = PyString_FromStringAndSize(s, len - 1))) return -1;
+ if (!( py_str = PyString_FromStringAndSize(s, len - 1))) return -1;
- value = PyDict_GetItem(self->memo, py_str);
- if (! value) {
- PyErr_SetObject(BadPickleGet, py_str);
- rc = -1;
- }
- else {
- PDATA_APPEND(self->stack, value, -1);
- rc = 0;
- }
+ value = PyDict_GetItem(self->memo, py_str);
+ if (! value) {
+ PyErr_SetObject(BadPickleGet, py_str);
+ rc = -1;
+ }
+ else {
+ PDATA_APPEND(self->stack, value, -1);
+ rc = 0;
+ }
- Py_DECREF(py_str);
- return rc;
+ Py_DECREF(py_str);
+ return rc;
}
static int
load_binget(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- unsigned char key;
- char *s;
- int rc;
+ PyObject *py_key = 0, *value = 0;
+ unsigned char key;
+ char *s;
+ int rc;
- if (self->read_func(self, &s, 1) < 0) return -1;
+ if (self->read_func(self, &s, 1) < 0) return -1;
- key = (unsigned char)s[0];
- if (!( py_key = PyInt_FromLong((long)key))) return -1;
+ key = (unsigned char)s[0];
+ if (!( py_key = PyInt_FromLong((long)key))) return -1;
- value = PyDict_GetItem(self->memo, py_key);
- if (! value) {
- PyErr_SetObject(BadPickleGet, py_key);
- rc = -1;
- }
- else {
- PDATA_APPEND(self->stack, value, -1);
- rc = 0;
- }
+ value = PyDict_GetItem(self->memo, py_key);
+ if (! value) {
+ PyErr_SetObject(BadPickleGet, py_key);
+ rc = -1;
+ }
+ else {
+ PDATA_APPEND(self->stack, value, -1);
+ rc = 0;
+ }
- Py_DECREF(py_key);
- return rc;
+ Py_DECREF(py_key);
+ return rc;
}
static int
load_long_binget(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- unsigned char c;
- char *s;
- long key;
- int rc;
-
- if (self->read_func(self, &s, 4) < 0) return -1;
-
- c = (unsigned char)s[0];
- key = (long)c;
- c = (unsigned char)s[1];
- key |= (long)c << 8;
- c = (unsigned char)s[2];
- key |= (long)c << 16;
- c = (unsigned char)s[3];
- key |= (long)c << 24;
-
- if (!( py_key = PyInt_FromLong((long)key))) return -1;
-
- value = PyDict_GetItem(self->memo, py_key);
- if (! value) {
- PyErr_SetObject(BadPickleGet, py_key);
- rc = -1;
- }
- else {
- PDATA_APPEND(self->stack, value, -1);
- rc = 0;
- }
+ PyObject *py_key = 0, *value = 0;
+ unsigned char c;
+ char *s;
+ long key;
+ int rc;
+
+ if (self->read_func(self, &s, 4) < 0) return -1;
+
+ c = (unsigned char)s[0];
+ key = (long)c;
+ c = (unsigned char)s[1];
+ key |= (long)c << 8;
+ c = (unsigned char)s[2];
+ key |= (long)c << 16;
+ c = (unsigned char)s[3];
+ key |= (long)c << 24;
+
+ if (!( py_key = PyInt_FromLong((long)key))) return -1;
+
+ value = PyDict_GetItem(self->memo, py_key);
+ if (! value) {
+ PyErr_SetObject(BadPickleGet, py_key);
+ rc = -1;
+ }
+ else {
+ PDATA_APPEND(self->stack, value, -1);
+ rc = 0;
+ }
- Py_DECREF(py_key);
- return rc;
+ Py_DECREF(py_key);
+ return rc;
}
/* Push an object from the extension registry (EXT[124]). nbytes is
@@ -4250,399 +4250,399 @@ load_long_binget(Unpicklerobject *self)
static int
load_extension(Unpicklerobject *self, int nbytes)
{
- char *codebytes; /* the nbytes bytes after the opcode */
- long code; /* calc_binint returns long */
- PyObject *py_code; /* code as a Python int */
- PyObject *obj; /* the object to push */
- PyObject *pair; /* (module_name, class_name) */
- PyObject *module_name, *class_name;
-
- assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
- if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
- code = calc_binint(codebytes, nbytes);
- if (code <= 0) { /* note that 0 is forbidden */
- /* Corrupt or hostile pickle. */
- PyErr_SetString(UnpicklingError, "EXT specifies code <= 0");
- return -1;
- }
-
- /* Look for the code in the cache. */
- py_code = PyInt_FromLong(code);
- if (py_code == NULL) return -1;
- obj = PyDict_GetItem(extension_cache, py_code);
- if (obj != NULL) {
- /* Bingo. */
- Py_DECREF(py_code);
- PDATA_APPEND(self->stack, obj, -1);
- return 0;
- }
-
- /* Look up the (module_name, class_name) pair. */
- pair = PyDict_GetItem(inverted_registry, py_code);
- if (pair == NULL) {
- Py_DECREF(py_code);
- PyErr_Format(PyExc_ValueError, "unregistered extension "
- "code %ld", code);
- return -1;
- }
- /* Since the extension registry is manipulable via Python code,
- * confirm that pair is really a 2-tuple of strings.
- */
- if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 ||
- !PyString_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
- !PyString_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
- Py_DECREF(py_code);
- PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
- "isn't a 2-tuple of strings", code);
- return -1;
- }
- /* Load the object. */
- obj = find_class(module_name, class_name, self->find_class);
- if (obj == NULL) {
- Py_DECREF(py_code);
- return -1;
- }
- /* Cache code -> obj. */
- code = PyDict_SetItem(extension_cache, py_code, obj);
- Py_DECREF(py_code);
- if (code < 0) {
- Py_DECREF(obj);
- return -1;
- }
- PDATA_PUSH(self->stack, obj, -1);
- return 0;
+ char *codebytes; /* the nbytes bytes after the opcode */
+ long code; /* calc_binint returns long */
+ PyObject *py_code; /* code as a Python int */
+ PyObject *obj; /* the object to push */
+ PyObject *pair; /* (module_name, class_name) */
+ PyObject *module_name, *class_name;
+
+ assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
+ if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
+ code = calc_binint(codebytes, nbytes);
+ if (code <= 0) { /* note that 0 is forbidden */
+ /* Corrupt or hostile pickle. */
+ PyErr_SetString(UnpicklingError, "EXT specifies code <= 0");
+ return -1;
+ }
+
+ /* Look for the code in the cache. */
+ py_code = PyInt_FromLong(code);
+ if (py_code == NULL) return -1;
+ obj = PyDict_GetItem(extension_cache, py_code);
+ if (obj != NULL) {
+ /* Bingo. */
+ Py_DECREF(py_code);
+ PDATA_APPEND(self->stack, obj, -1);
+ return 0;
+ }
+
+ /* Look up the (module_name, class_name) pair. */
+ pair = PyDict_GetItem(inverted_registry, py_code);
+ if (pair == NULL) {
+ Py_DECREF(py_code);
+ PyErr_Format(PyExc_ValueError, "unregistered extension "
+ "code %ld", code);
+ return -1;
+ }
+ /* Since the extension registry is manipulable via Python code,
+ * confirm that pair is really a 2-tuple of strings.
+ */
+ if (!PyTuple_Check(pair) || PyTuple_Size(pair) != 2 ||
+ !PyString_Check(module_name = PyTuple_GET_ITEM(pair, 0)) ||
+ !PyString_Check(class_name = PyTuple_GET_ITEM(pair, 1))) {
+ Py_DECREF(py_code);
+ PyErr_Format(PyExc_ValueError, "_inverted_registry[%ld] "
+ "isn't a 2-tuple of strings", code);
+ return -1;
+ }
+ /* Load the object. */
+ obj = find_class(module_name, class_name, self->find_class);
+ if (obj == NULL) {
+ Py_DECREF(py_code);
+ return -1;
+ }
+ /* Cache code -> obj. */
+ code = PyDict_SetItem(extension_cache, py_code, obj);
+ Py_DECREF(py_code);
+ if (code < 0) {
+ Py_DECREF(obj);
+ return -1;
+ }
+ PDATA_PUSH(self->stack, obj, -1);
+ return 0;
}
static int
load_put(Unpicklerobject *self)
{
- PyObject *py_str = 0, *value = 0;
- int len, l;
- char *s;
+ PyObject *py_str = 0, *value = 0;
+ int len, l;
+ char *s;
- if ((l = self->readline_func(self, &s)) < 0) return -1;
- if (l < 2) return bad_readline();
- if (!( len=self->stack->length )) return stackUnderflow();
- if (!( py_str = PyString_FromStringAndSize(s, l - 1))) return -1;
- value=self->stack->data[len-1];
- l=PyDict_SetItem(self->memo, py_str, value);
- Py_DECREF(py_str);
- return l;
+ if ((l = self->readline_func(self, &s)) < 0) return -1;
+ if (l < 2) return bad_readline();
+ if (!( len=self->stack->length )) return stackUnderflow();
+ if (!( py_str = PyString_FromStringAndSize(s, l - 1))) return -1;
+ value=self->stack->data[len-1];
+ l=PyDict_SetItem(self->memo, py_str, value);
+ Py_DECREF(py_str);
+ return l;
}
static int
load_binput(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- unsigned char key;
- char *s;
- int len;
+ PyObject *py_key = 0, *value = 0;
+ unsigned char key;
+ char *s;
+ int len;
- if (self->read_func(self, &s, 1) < 0) return -1;
- if (!( (len=self->stack->length) > 0 )) return stackUnderflow();
+ if (self->read_func(self, &s, 1) < 0) return -1;
+ if (!( (len=self->stack->length) > 0 )) return stackUnderflow();
- key = (unsigned char)s[0];
+ key = (unsigned char)s[0];
- if (!( py_key = PyInt_FromLong((long)key))) return -1;
- value=self->stack->data[len-1];
- len=PyDict_SetItem(self->memo, py_key, value);
- Py_DECREF(py_key);
- return len;
+ if (!( py_key = PyInt_FromLong((long)key))) return -1;
+ value=self->stack->data[len-1];
+ len=PyDict_SetItem(self->memo, py_key, value);
+ Py_DECREF(py_key);
+ return len;
}
static int
load_long_binput(Unpicklerobject *self)
{
- PyObject *py_key = 0, *value = 0;
- long key;
- unsigned char c;
- char *s;
- int len;
+ PyObject *py_key = 0, *value = 0;
+ long key;
+ unsigned char c;
+ char *s;
+ int len;
- if (self->read_func(self, &s, 4) < 0) return -1;
- if (!( len=self->stack->length )) return stackUnderflow();
+ if (self->read_func(self, &s, 4) < 0) return -1;
+ if (!( len=self->stack->length )) return stackUnderflow();
- c = (unsigned char)s[0];
- key = (long)c;
- c = (unsigned char)s[1];
- key |= (long)c << 8;
- c = (unsigned char)s[2];
- key |= (long)c << 16;
- c = (unsigned char)s[3];
- key |= (long)c << 24;
+ c = (unsigned char)s[0];
+ key = (long)c;
+ c = (unsigned char)s[1];
+ key |= (long)c << 8;
+ c = (unsigned char)s[2];
+ key |= (long)c << 16;
+ c = (unsigned char)s[3];
+ key |= (long)c << 24;
- if (!( py_key = PyInt_FromLong(key))) return -1;
- value=self->stack->data[len-1];
- len=PyDict_SetItem(self->memo, py_key, value);
- Py_DECREF(py_key);
- return len;
+ if (!( py_key = PyInt_FromLong(key))) return -1;
+ value=self->stack->data[len-1];
+ len=PyDict_SetItem(self->memo, py_key, value);
+ Py_DECREF(py_key);
+ return len;
}
static int
do_append(Unpicklerobject *self, int x)
{
- PyObject *value = 0, *list = 0, *append_method = 0;
- int len, i;
-
- len=self->stack->length;
- if (!( len >= x && x > 0 )) return stackUnderflow();
- /* nothing to do */
- if (len==x) return 0;
-
- list=self->stack->data[x-1];
-
- if (PyList_Check(list)) {
- PyObject *slice;
- int list_len;
-
- slice=Pdata_popList(self->stack, x);
- if (! slice) return -1;
- list_len = PyList_GET_SIZE(list);
- i=PyList_SetSlice(list, list_len, list_len, slice);
- Py_DECREF(slice);
- return i;
- }
- else {
-
- if (!( append_method = PyObject_GetAttr(list, append_str)))
- return -1;
-
- for (i = x; i < len; i++) {
- PyObject *junk;
-
- value=self->stack->data[i];
- junk=0;
- ARG_TUP(self, value);
- if (self->arg) {
- junk = PyObject_Call(append_method, self->arg,
- NULL);
- FREE_ARG_TUP(self);
- }
- if (! junk) {
- Pdata_clear(self->stack, i+1);
- self->stack->length=x;
- Py_DECREF(append_method);
- return -1;
- }
- Py_DECREF(junk);
- }
- self->stack->length=x;
- Py_DECREF(append_method);
- }
-
- return 0;
+ PyObject *value = 0, *list = 0, *append_method = 0;
+ int len, i;
+
+ len=self->stack->length;
+ if (!( len >= x && x > 0 )) return stackUnderflow();
+ /* nothing to do */
+ if (len==x) return 0;
+
+ list=self->stack->data[x-1];
+
+ if (PyList_Check(list)) {
+ PyObject *slice;
+ int list_len;
+
+ slice=Pdata_popList(self->stack, x);
+ if (! slice) return -1;
+ list_len = PyList_GET_SIZE(list);
+ i=PyList_SetSlice(list, list_len, list_len, slice);
+ Py_DECREF(slice);
+ return i;
+ }
+ else {
+
+ if (!( append_method = PyObject_GetAttr(list, append_str)))
+ return -1;
+
+ for (i = x; i < len; i++) {
+ PyObject *junk;
+
+ value=self->stack->data[i];
+ junk=0;
+ ARG_TUP(self, value);
+ if (self->arg) {
+ junk = PyObject_Call(append_method, self->arg,
+ NULL);
+ FREE_ARG_TUP(self);
+ }
+ if (! junk) {
+ Pdata_clear(self->stack, i+1);
+ self->stack->length=x;
+ Py_DECREF(append_method);
+ return -1;
+ }
+ Py_DECREF(junk);
+ }
+ self->stack->length=x;
+ Py_DECREF(append_method);
+ }
+
+ return 0;
}
static int
load_append(Unpicklerobject *self)
{
- return do_append(self, self->stack->length - 1);
+ return do_append(self, self->stack->length - 1);
}
static int
load_appends(Unpicklerobject *self)
{
- return do_append(self, marker(self));
+ return do_append(self, marker(self));
}
static int
do_setitems(Unpicklerobject *self, int x)
{
- PyObject *value = 0, *key = 0, *dict = 0;
- int len, i, r=0;
+ PyObject *value = 0, *key = 0, *dict = 0;
+ int len, i, r=0;
- if (!( (len=self->stack->length) >= x
- && x > 0 )) return stackUnderflow();
+ if (!( (len=self->stack->length) >= x
+ && x > 0 )) return stackUnderflow();
- dict=self->stack->data[x-1];
+ dict=self->stack->data[x-1];
- for (i = x+1; i < len; i += 2) {
- key =self->stack->data[i-1];
- value=self->stack->data[i ];
- if (PyObject_SetItem(dict, key, value) < 0) {
- r=-1;
- break;
- }
- }
+ for (i = x+1; i < len; i += 2) {
+ key =self->stack->data[i-1];
+ value=self->stack->data[i ];
+ if (PyObject_SetItem(dict, key, value) < 0) {
+ r=-1;
+ break;
+ }
+ }
- Pdata_clear(self->stack, x);
+ Pdata_clear(self->stack, x);
- return r;
+ return r;
}
static int
load_setitem(Unpicklerobject *self)
{
- return do_setitems(self, self->stack->length - 2);
+ return do_setitems(self, self->stack->length - 2);
}
static int
load_setitems(Unpicklerobject *self)
{
- return do_setitems(self, marker(self));
+ return do_setitems(self, marker(self));
}
static int
load_build(Unpicklerobject *self)
{
- PyObject *state, *inst, *slotstate;
- PyObject *__setstate__;
- PyObject *d_key, *d_value;
- Py_ssize_t i;
- int res = -1;
-
- /* Stack is ... instance, state. We want to leave instance at
- * the stack top, possibly mutated via instance.__setstate__(state).
- */
- if (self->stack->length < 2)
- return stackUnderflow();
- PDATA_POP(self->stack, state);
- if (state == NULL)
- return -1;
- inst = self->stack->data[self->stack->length - 1];
-
- __setstate__ = PyObject_GetAttr(inst, __setstate___str);
- if (__setstate__ != NULL) {
- PyObject *junk = NULL;
-
- /* The explicit __setstate__ is responsible for everything. */
- ARG_TUP(self, state);
- if (self->arg) {
- junk = PyObject_Call(__setstate__, self->arg, NULL);
- FREE_ARG_TUP(self);
- }
- Py_DECREF(__setstate__);
- if (junk == NULL)
- return -1;
- Py_DECREF(junk);
- return 0;
- }
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
-
- /* A default __setstate__. First see whether state embeds a
- * slot state dict too (a proto 2 addition).
- */
- if (PyTuple_Check(state) && PyTuple_Size(state) == 2) {
- PyObject *temp = state;
- state = PyTuple_GET_ITEM(temp, 0);
- slotstate = PyTuple_GET_ITEM(temp, 1);
- Py_INCREF(state);
- Py_INCREF(slotstate);
- Py_DECREF(temp);
- }
- else
- slotstate = NULL;
-
- /* Set inst.__dict__ from the state dict (if any). */
- if (state != Py_None) {
- PyObject *dict;
- if (! PyDict_Check(state)) {
- PyErr_SetString(UnpicklingError, "state is not a "
- "dictionary");
- goto finally;
- }
- dict = PyObject_GetAttr(inst, __dict___str);
- if (dict == NULL)
- goto finally;
-
- i = 0;
- while (PyDict_Next(state, &i, &d_key, &d_value)) {
- /* normally the keys for instance attributes are
- interned. we should try to do that here. */
- Py_INCREF(d_key);
- if (PyString_CheckExact(d_key))
- PyString_InternInPlace(&d_key);
- if (PyObject_SetItem(dict, d_key, d_value) < 0) {
- Py_DECREF(d_key);
- goto finally;
- }
- Py_DECREF(d_key);
- }
- Py_DECREF(dict);
- }
-
- /* Also set instance attributes from the slotstate dict (if any). */
- if (slotstate != NULL) {
- if (! PyDict_Check(slotstate)) {
- PyErr_SetString(UnpicklingError, "slot state is not "
- "a dictionary");
- goto finally;
- }
- i = 0;
- while (PyDict_Next(slotstate, &i, &d_key, &d_value)) {
- if (PyObject_SetAttr(inst, d_key, d_value) < 0)
- goto finally;
- }
- }
- res = 0;
+ PyObject *state, *inst, *slotstate;
+ PyObject *__setstate__;
+ PyObject *d_key, *d_value;
+ Py_ssize_t i;
+ int res = -1;
+
+ /* Stack is ... instance, state. We want to leave instance at
+ * the stack top, possibly mutated via instance.__setstate__(state).
+ */
+ if (self->stack->length < 2)
+ return stackUnderflow();
+ PDATA_POP(self->stack, state);
+ if (state == NULL)
+ return -1;
+ inst = self->stack->data[self->stack->length - 1];
+
+ __setstate__ = PyObject_GetAttr(inst, __setstate___str);
+ if (__setstate__ != NULL) {
+ PyObject *junk = NULL;
+
+ /* The explicit __setstate__ is responsible for everything. */
+ ARG_TUP(self, state);
+ if (self->arg) {
+ junk = PyObject_Call(__setstate__, self->arg, NULL);
+ FREE_ARG_TUP(self);
+ }
+ Py_DECREF(__setstate__);
+ if (junk == NULL)
+ return -1;
+ Py_DECREF(junk);
+ return 0;
+ }
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+
+ /* A default __setstate__. First see whether state embeds a
+ * slot state dict too (a proto 2 addition).
+ */
+ if (PyTuple_Check(state) && PyTuple_Size(state) == 2) {
+ PyObject *temp = state;
+ state = PyTuple_GET_ITEM(temp, 0);
+ slotstate = PyTuple_GET_ITEM(temp, 1);
+ Py_INCREF(state);
+ Py_INCREF(slotstate);
+ Py_DECREF(temp);
+ }
+ else
+ slotstate = NULL;
+
+ /* Set inst.__dict__ from the state dict (if any). */
+ if (state != Py_None) {
+ PyObject *dict;
+ if (! PyDict_Check(state)) {
+ PyErr_SetString(UnpicklingError, "state is not a "
+ "dictionary");
+ goto finally;
+ }
+ dict = PyObject_GetAttr(inst, __dict___str);
+ if (dict == NULL)
+ goto finally;
+
+ i = 0;
+ while (PyDict_Next(state, &i, &d_key, &d_value)) {
+ /* normally the keys for instance attributes are
+ interned. we should try to do that here. */
+ Py_INCREF(d_key);
+ if (PyString_CheckExact(d_key))
+ PyString_InternInPlace(&d_key);
+ if (PyObject_SetItem(dict, d_key, d_value) < 0) {
+ Py_DECREF(d_key);
+ goto finally;
+ }
+ Py_DECREF(d_key);
+ }
+ Py_DECREF(dict);
+ }
+
+ /* Also set instance attributes from the slotstate dict (if any). */
+ if (slotstate != NULL) {
+ if (! PyDict_Check(slotstate)) {
+ PyErr_SetString(UnpicklingError, "slot state is not "
+ "a dictionary");
+ goto finally;
+ }
+ i = 0;
+ while (PyDict_Next(slotstate, &i, &d_key, &d_value)) {
+ if (PyObject_SetAttr(inst, d_key, d_value) < 0)
+ goto finally;
+ }
+ }
+ res = 0;
finally:
- Py_DECREF(state);
- Py_XDECREF(slotstate);
- return res;
+ Py_DECREF(state);
+ Py_XDECREF(slotstate);
+ return res;
}
static int
load_mark(Unpicklerobject *self)
{
- int s;
+ int s;
- /* Note that we split the (pickle.py) stack into two stacks, an
- object stack and a mark stack. Here we push a mark onto the
- mark stack.
- */
+ /* Note that we split the (pickle.py) stack into two stacks, an
+ object stack and a mark stack. Here we push a mark onto the
+ mark stack.
+ */
- if ((self->num_marks + 1) >= self->marks_size) {
- int *marks;
- s=self->marks_size+20;
- if (s <= self->num_marks) s=self->num_marks + 1;
- if (self->marks == NULL)
- marks=(int *)malloc(s * sizeof(int));
- else
- marks=(int *)realloc(self->marks,
- s * sizeof(int));
- if (!marks) {
- PyErr_NoMemory();
- return -1;
- }
- self->marks = marks;
- self->marks_size = s;
- }
+ if ((self->num_marks + 1) >= self->marks_size) {
+ int *marks;
+ s=self->marks_size+20;
+ if (s <= self->num_marks) s=self->num_marks + 1;
+ if (self->marks == NULL)
+ marks=(int *)malloc(s * sizeof(int));
+ else
+ marks=(int *)realloc(self->marks,
+ s * sizeof(int));
+ if (!marks) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->marks = marks;
+ self->marks_size = s;
+ }
- self->marks[self->num_marks++] = self->stack->length;
+ self->marks[self->num_marks++] = self->stack->length;
- return 0;
+ return 0;
}
static int
load_reduce(Unpicklerobject *self)
{
- PyObject *callable = 0, *arg_tup = 0, *ob = 0;
+ PyObject *callable = 0, *arg_tup = 0, *ob = 0;
- PDATA_POP(self->stack, arg_tup);
- if (! arg_tup) return -1;
- PDATA_POP(self->stack, callable);
- if (callable) {
- ob = Instance_New(callable, arg_tup);
- Py_DECREF(callable);
- }
- Py_DECREF(arg_tup);
+ PDATA_POP(self->stack, arg_tup);
+ if (! arg_tup) return -1;
+ PDATA_POP(self->stack, callable);
+ if (callable) {
+ ob = Instance_New(callable, arg_tup);
+ Py_DECREF(callable);
+ }
+ Py_DECREF(arg_tup);
- if (! ob) return -1;
+ if (! ob) return -1;
- PDATA_PUSH(self->stack, ob, -1);
- return 0;
+ PDATA_PUSH(self->stack, ob, -1);
+ return 0;
}
/* Just raises an error if we don't know the protocol specified. PROTO
@@ -4651,327 +4651,327 @@ load_reduce(Unpicklerobject *self)
static int
load_proto(Unpicklerobject *self)
{
- int i;
- char *protobyte;
+ int i;
+ char *protobyte;
- i = self->read_func(self, &protobyte, 1);
- if (i < 0)
- return -1;
+ i = self->read_func(self, &protobyte, 1);
+ if (i < 0)
+ return -1;
- i = calc_binint(protobyte, 1);
- /* No point checking for < 0, since calc_binint returns an unsigned
- * int when chewing on 1 byte.
- */
- assert(i >= 0);
- if (i <= HIGHEST_PROTOCOL)
- return 0;
+ i = calc_binint(protobyte, 1);
+ /* No point checking for < 0, since calc_binint returns an unsigned
+ * int when chewing on 1 byte.
+ */
+ assert(i >= 0);
+ if (i <= HIGHEST_PROTOCOL)
+ return 0;
- PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i);
- return -1;
+ PyErr_Format(PyExc_ValueError, "unsupported pickle protocol: %d", i);
+ return -1;
}
static PyObject *
load(Unpicklerobject *self)
{
- PyObject *err = 0, *val = 0;
- char *s;
-
- self->num_marks = 0;
- if (self->stack->length) Pdata_clear(self->stack, 0);
-
- while (1) {
- if (self->read_func(self, &s, 1) < 0)
- break;
-
- switch (s[0]) {
- case NONE:
- if (load_none(self) < 0)
- break;
- continue;
-
- case BININT:
- if (load_binint(self) < 0)
- break;
- continue;
-
- case BININT1:
- if (load_binint1(self) < 0)
- break;
- continue;
-
- case BININT2:
- if (load_binint2(self) < 0)
- break;
- continue;
-
- case INT:
- if (load_int(self) < 0)
- break;
- continue;
-
- case LONG:
- if (load_long(self) < 0)
- break;
- continue;
-
- case LONG1:
- if (load_counted_long(self, 1) < 0)
- break;
- continue;
-
- case LONG4:
- if (load_counted_long(self, 4) < 0)
- break;
- continue;
-
- case FLOAT:
- if (load_float(self) < 0)
- break;
- continue;
-
- case BINFLOAT:
- if (load_binfloat(self) < 0)
- break;
- continue;
-
- case BINSTRING:
- if (load_binstring(self) < 0)
- break;
- continue;
-
- case SHORT_BINSTRING:
- if (load_short_binstring(self) < 0)
- break;
- continue;
-
- case STRING:
- if (load_string(self) < 0)
- break;
- continue;
+ PyObject *err = 0, *val = 0;
+ char *s;
+
+ self->num_marks = 0;
+ if (self->stack->length) Pdata_clear(self->stack, 0);
+
+ while (1) {
+ if (self->read_func(self, &s, 1) < 0)
+ break;
+
+ switch (s[0]) {
+ case NONE:
+ if (load_none(self) < 0)
+ break;
+ continue;
+
+ case BININT:
+ if (load_binint(self) < 0)
+ break;
+ continue;
+
+ case BININT1:
+ if (load_binint1(self) < 0)
+ break;
+ continue;
+
+ case BININT2:
+ if (load_binint2(self) < 0)
+ break;
+ continue;
+
+ case INT:
+ if (load_int(self) < 0)
+ break;
+ continue;
+
+ case LONG:
+ if (load_long(self) < 0)
+ break;
+ continue;
+
+ case LONG1:
+ if (load_counted_long(self, 1) < 0)
+ break;
+ continue;
+
+ case LONG4:
+ if (load_counted_long(self, 4) < 0)
+ break;
+ continue;
+
+ case FLOAT:
+ if (load_float(self) < 0)
+ break;
+ continue;
+
+ case BINFLOAT:
+ if (load_binfloat(self) < 0)
+ break;
+ continue;
+
+ case BINSTRING:
+ if (load_binstring(self) < 0)
+ break;
+ continue;
+
+ case SHORT_BINSTRING:
+ if (load_short_binstring(self) < 0)
+ break;
+ continue;
+
+ case STRING:
+ if (load_string(self) < 0)
+ break;
+ continue;
#ifdef Py_USING_UNICODE
- case UNICODE:
- if (load_unicode(self) < 0)
- break;
- continue;
-
- case BINUNICODE:
- if (load_binunicode(self) < 0)
- break;
- continue;
+ case UNICODE:
+ if (load_unicode(self) < 0)
+ break;
+ continue;
+
+ case BINUNICODE:
+ if (load_binunicode(self) < 0)
+ break;
+ continue;
#endif
- case EMPTY_TUPLE:
- if (load_counted_tuple(self, 0) < 0)
- break;
- continue;
-
- case TUPLE1:
- if (load_counted_tuple(self, 1) < 0)
- break;
- continue;
-
- case TUPLE2:
- if (load_counted_tuple(self, 2) < 0)
- break;
- continue;
-
- case TUPLE3:
- if (load_counted_tuple(self, 3) < 0)
- break;
- continue;
-
- case TUPLE:
- if (load_tuple(self) < 0)
- break;
- continue;
-
- case EMPTY_LIST:
- if (load_empty_list(self) < 0)
- break;
- continue;
-
- case LIST:
- if (load_list(self) < 0)
- break;
- continue;
-
- case EMPTY_DICT:
- if (load_empty_dict(self) < 0)
- break;
- continue;
-
- case DICT:
- if (load_dict(self) < 0)
- break;
- continue;
-
- case OBJ:
- if (load_obj(self) < 0)
- break;
- continue;
-
- case INST:
- if (load_inst(self) < 0)
- break;
- continue;
-
- case NEWOBJ:
- if (load_newobj(self) < 0)
- break;
- continue;
-
- case GLOBAL:
- if (load_global(self) < 0)
- break;
- continue;
-
- case APPEND:
- if (load_append(self) < 0)
- break;
- continue;
-
- case APPENDS:
- if (load_appends(self) < 0)
- break;
- continue;
-
- case BUILD:
- if (load_build(self) < 0)
- break;
- continue;
-
- case DUP:
- if (load_dup(self) < 0)
- break;
- continue;
-
- case BINGET:
- if (load_binget(self) < 0)
- break;
- continue;
-
- case LONG_BINGET:
- if (load_long_binget(self) < 0)
- break;
- continue;
-
- case GET:
- if (load_get(self) < 0)
- break;
- continue;
-
- case EXT1:
- if (load_extension(self, 1) < 0)
- break;
- continue;
-
- case EXT2:
- if (load_extension(self, 2) < 0)
- break;
- continue;
-
- case EXT4:
- if (load_extension(self, 4) < 0)
- break;
- continue;
- case MARK:
- if (load_mark(self) < 0)
- break;
- continue;
-
- case BINPUT:
- if (load_binput(self) < 0)
- break;
- continue;
-
- case LONG_BINPUT:
- if (load_long_binput(self) < 0)
- break;
- continue;
-
- case PUT:
- if (load_put(self) < 0)
- break;
- continue;
-
- case POP:
- if (load_pop(self) < 0)
- break;
- continue;
-
- case POP_MARK:
- if (load_pop_mark(self) < 0)
- break;
- continue;
-
- case SETITEM:
- if (load_setitem(self) < 0)
- break;
- continue;
-
- case SETITEMS:
- if (load_setitems(self) < 0)
- break;
- continue;
-
- case STOP:
- break;
-
- case PERSID:
- if (load_persid(self) < 0)
- break;
- continue;
-
- case BINPERSID:
- if (load_binpersid(self) < 0)
- break;
- continue;
-
- case REDUCE:
- if (load_reduce(self) < 0)
- break;
- continue;
-
- case PROTO:
- if (load_proto(self) < 0)
- break;
- continue;
-
- case NEWTRUE:
- if (load_bool(self, Py_True) < 0)
- break;
- continue;
-
- case NEWFALSE:
- if (load_bool(self, Py_False) < 0)
- break;
- continue;
-
- case '\0':
- /* end of file */
- PyErr_SetNone(PyExc_EOFError);
- break;
-
- default:
- cPickle_ErrFormat(UnpicklingError,
- "invalid load key, '%s'.",
- "c", s[0]);
- return NULL;
- }
-
- break;
- }
-
- if ((err = PyErr_Occurred())) {
- if (err == PyExc_EOFError) {
- PyErr_SetNone(PyExc_EOFError);
- }
- return NULL;
- }
-
- PDATA_POP(self->stack, val);
- return val;
+ case EMPTY_TUPLE:
+ if (load_counted_tuple(self, 0) < 0)
+ break;
+ continue;
+
+ case TUPLE1:
+ if (load_counted_tuple(self, 1) < 0)
+ break;
+ continue;
+
+ case TUPLE2:
+ if (load_counted_tuple(self, 2) < 0)
+ break;
+ continue;
+
+ case TUPLE3:
+ if (load_counted_tuple(self, 3) < 0)
+ break;
+ continue;
+
+ case TUPLE:
+ if (load_tuple(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_LIST:
+ if (load_empty_list(self) < 0)
+ break;
+ continue;
+
+ case LIST:
+ if (load_list(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_DICT:
+ if (load_empty_dict(self) < 0)
+ break;
+ continue;
+
+ case DICT:
+ if (load_dict(self) < 0)
+ break;
+ continue;
+
+ case OBJ:
+ if (load_obj(self) < 0)
+ break;
+ continue;
+
+ case INST:
+ if (load_inst(self) < 0)
+ break;
+ continue;
+
+ case NEWOBJ:
+ if (load_newobj(self) < 0)
+ break;
+ continue;
+
+ case GLOBAL:
+ if (load_global(self) < 0)
+ break;
+ continue;
+
+ case APPEND:
+ if (load_append(self) < 0)
+ break;
+ continue;
+
+ case APPENDS:
+ if (load_appends(self) < 0)
+ break;
+ continue;
+
+ case BUILD:
+ if (load_build(self) < 0)
+ break;
+ continue;
+
+ case DUP:
+ if (load_dup(self) < 0)
+ break;
+ continue;
+
+ case BINGET:
+ if (load_binget(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINGET:
+ if (load_long_binget(self) < 0)
+ break;
+ continue;
+
+ case GET:
+ if (load_get(self) < 0)
+ break;
+ continue;
+
+ case EXT1:
+ if (load_extension(self, 1) < 0)
+ break;
+ continue;
+
+ case EXT2:
+ if (load_extension(self, 2) < 0)
+ break;
+ continue;
+
+ case EXT4:
+ if (load_extension(self, 4) < 0)
+ break;
+ continue;
+ case MARK:
+ if (load_mark(self) < 0)
+ break;
+ continue;
+
+ case BINPUT:
+ if (load_binput(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINPUT:
+ if (load_long_binput(self) < 0)
+ break;
+ continue;
+
+ case PUT:
+ if (load_put(self) < 0)
+ break;
+ continue;
+
+ case POP:
+ if (load_pop(self) < 0)
+ break;
+ continue;
+
+ case POP_MARK:
+ if (load_pop_mark(self) < 0)
+ break;
+ continue;
+
+ case SETITEM:
+ if (load_setitem(self) < 0)
+ break;
+ continue;
+
+ case SETITEMS:
+ if (load_setitems(self) < 0)
+ break;
+ continue;
+
+ case STOP:
+ break;
+
+ case PERSID:
+ if (load_persid(self) < 0)
+ break;
+ continue;
+
+ case BINPERSID:
+ if (load_binpersid(self) < 0)
+ break;
+ continue;
+
+ case REDUCE:
+ if (load_reduce(self) < 0)
+ break;
+ continue;
+
+ case PROTO:
+ if (load_proto(self) < 0)
+ break;
+ continue;
+
+ case NEWTRUE:
+ if (load_bool(self, Py_True) < 0)
+ break;
+ continue;
+
+ case NEWFALSE:
+ if (load_bool(self, Py_False) < 0)
+ break;
+ continue;
+
+ case '\0':
+ /* end of file */
+ PyErr_SetNone(PyExc_EOFError);
+ break;
+
+ default:
+ cPickle_ErrFormat(UnpicklingError,
+ "invalid load key, '%s'.",
+ "c", s[0]);
+ return NULL;
+ }
+
+ break;
+ }
+
+ if ((err = PyErr_Occurred())) {
+ if (err == PyExc_EOFError) {
+ PyErr_SetNone(PyExc_EOFError);
+ }
+ return NULL;
+ }
+
+ PDATA_POP(self->stack, val);
+ return val;
}
@@ -4981,63 +4981,63 @@ load(Unpicklerobject *self)
static int
noload_obj(Unpicklerobject *self)
{
- int i;
+ int i;
- if ((i = marker(self)) < 0) return -1;
- return Pdata_clear(self->stack, i+1);
+ if ((i = marker(self)) < 0) return -1;
+ return Pdata_clear(self->stack, i+1);
}
static int
noload_inst(Unpicklerobject *self)
{
- int i;
- char *s;
+ int i;
+ char *s;
- if ((i = marker(self)) < 0) return -1;
- Pdata_clear(self->stack, i);
- if (self->readline_func(self, &s) < 0) return -1;
- if (self->readline_func(self, &s) < 0) return -1;
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ if ((i = marker(self)) < 0) return -1;
+ Pdata_clear(self->stack, i);
+ if (self->readline_func(self, &s) < 0) return -1;
+ if (self->readline_func(self, &s) < 0) return -1;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
noload_newobj(Unpicklerobject *self)
{
- PyObject *obj;
+ PyObject *obj;
- PDATA_POP(self->stack, obj); /* pop argtuple */
- if (obj == NULL) return -1;
- Py_DECREF(obj);
+ PDATA_POP(self->stack, obj); /* pop argtuple */
+ if (obj == NULL) return -1;
+ Py_DECREF(obj);
- PDATA_POP(self->stack, obj); /* pop cls */
- if (obj == NULL) return -1;
- Py_DECREF(obj);
+ PDATA_POP(self->stack, obj); /* pop cls */
+ if (obj == NULL) return -1;
+ Py_DECREF(obj);
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
noload_global(Unpicklerobject *self)
{
- char *s;
+ char *s;
- if (self->readline_func(self, &s) < 0) return -1;
- if (self->readline_func(self, &s) < 0) return -1;
- PDATA_APPEND(self->stack, Py_None,-1);
- return 0;
+ if (self->readline_func(self, &s) < 0) return -1;
+ if (self->readline_func(self, &s) < 0) return -1;
+ PDATA_APPEND(self->stack, Py_None,-1);
+ return 0;
}
static int
noload_reduce(Unpicklerobject *self)
{
- if (self->stack->length < 2) return stackUnderflow();
- Pdata_clear(self->stack, self->stack->length-2);
- PDATA_APPEND(self->stack, Py_None,-1);
- return 0;
+ if (self->stack->length < 2) return stackUnderflow();
+ Pdata_clear(self->stack, self->stack->length-2);
+ PDATA_APPEND(self->stack, Py_None,-1);
+ return 0;
}
static int
@@ -5051,352 +5051,352 @@ noload_build(Unpicklerobject *self) {
static int
noload_extension(Unpicklerobject *self, int nbytes)
{
- char *codebytes;
+ char *codebytes;
- assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
- if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
- PDATA_APPEND(self->stack, Py_None, -1);
- return 0;
+ assert(nbytes == 1 || nbytes == 2 || nbytes == 4);
+ if (self->read_func(self, &codebytes, nbytes) < 0) return -1;
+ PDATA_APPEND(self->stack, Py_None, -1);
+ return 0;
}
static int
noload_append(Unpicklerobject *self)
{
- return Pdata_clear(self->stack, self->stack->length - 1);
+ return Pdata_clear(self->stack, self->stack->length - 1);
}
static int
noload_appends(Unpicklerobject *self)
{
- int i;
- if ((i = marker(self)) < 0) return -1;
- return Pdata_clear(self->stack, i);
+ int i;
+ if ((i = marker(self)) < 0) return -1;
+ return Pdata_clear(self->stack, i);
}
static int
noload_setitem(Unpicklerobject *self)
{
- return Pdata_clear(self->stack, self->stack->length - 2);
+ return Pdata_clear(self->stack, self->stack->length - 2);
}
static int
noload_setitems(Unpicklerobject *self)
{
- int i;
- if ((i = marker(self)) < 0) return -1;
- return Pdata_clear(self->stack, i);
+ int i;
+ if ((i = marker(self)) < 0) return -1;
+ return Pdata_clear(self->stack, i);
}
static PyObject *
noload(Unpicklerobject *self)
{
- PyObject *err = 0, *val = 0;
- char *s;
-
- self->num_marks = 0;
- Pdata_clear(self->stack, 0);
-
- while (1) {
- if (self->read_func(self, &s, 1) < 0)
- break;
-
- switch (s[0]) {
- case NONE:
- if (load_none(self) < 0)
- break;
- continue;
-
- case BININT:
- if (load_binint(self) < 0)
- break;
- continue;
-
- case BININT1:
- if (load_binint1(self) < 0)
- break;
- continue;
-
- case BININT2:
- if (load_binint2(self) < 0)
- break;
- continue;
-
- case INT:
- if (load_int(self) < 0)
- break;
- continue;
-
- case LONG:
- if (load_long(self) < 0)
- break;
- continue;
-
- case LONG1:
- if (load_counted_long(self, 1) < 0)
- break;
- continue;
-
- case LONG4:
- if (load_counted_long(self, 4) < 0)
- break;
- continue;
-
- case FLOAT:
- if (load_float(self) < 0)
- break;
- continue;
-
- case BINFLOAT:
- if (load_binfloat(self) < 0)
- break;
- continue;
-
- case BINSTRING:
- if (load_binstring(self) < 0)
- break;
- continue;
-
- case SHORT_BINSTRING:
- if (load_short_binstring(self) < 0)
- break;
- continue;
-
- case STRING:
- if (load_string(self) < 0)
- break;
- continue;
+ PyObject *err = 0, *val = 0;
+ char *s;
+
+ self->num_marks = 0;
+ Pdata_clear(self->stack, 0);
+
+ while (1) {
+ if (self->read_func(self, &s, 1) < 0)
+ break;
+
+ switch (s[0]) {
+ case NONE:
+ if (load_none(self) < 0)
+ break;
+ continue;
+
+ case BININT:
+ if (load_binint(self) < 0)
+ break;
+ continue;
+
+ case BININT1:
+ if (load_binint1(self) < 0)
+ break;
+ continue;
+
+ case BININT2:
+ if (load_binint2(self) < 0)
+ break;
+ continue;
+
+ case INT:
+ if (load_int(self) < 0)
+ break;
+ continue;
+
+ case LONG:
+ if (load_long(self) < 0)
+ break;
+ continue;
+
+ case LONG1:
+ if (load_counted_long(self, 1) < 0)
+ break;
+ continue;
+
+ case LONG4:
+ if (load_counted_long(self, 4) < 0)
+ break;
+ continue;
+
+ case FLOAT:
+ if (load_float(self) < 0)
+ break;
+ continue;
+
+ case BINFLOAT:
+ if (load_binfloat(self) < 0)
+ break;
+ continue;
+
+ case BINSTRING:
+ if (load_binstring(self) < 0)
+ break;
+ continue;
+
+ case SHORT_BINSTRING:
+ if (load_short_binstring(self) < 0)
+ break;
+ continue;
+
+ case STRING:
+ if (load_string(self) < 0)
+ break;
+ continue;
#ifdef Py_USING_UNICODE
- case UNICODE:
- if (load_unicode(self) < 0)
- break;
- continue;
-
- case BINUNICODE:
- if (load_binunicode(self) < 0)
- break;
- continue;
+ case UNICODE:
+ if (load_unicode(self) < 0)
+ break;
+ continue;
+
+ case BINUNICODE:
+ if (load_binunicode(self) < 0)
+ break;
+ continue;
#endif
- case EMPTY_TUPLE:
- if (load_counted_tuple(self, 0) < 0)
- break;
- continue;
-
- case TUPLE1:
- if (load_counted_tuple(self, 1) < 0)
- break;
- continue;
-
- case TUPLE2:
- if (load_counted_tuple(self, 2) < 0)
- break;
- continue;
-
- case TUPLE3:
- if (load_counted_tuple(self, 3) < 0)
- break;
- continue;
-
- case TUPLE:
- if (load_tuple(self) < 0)
- break;
- continue;
-
- case EMPTY_LIST:
- if (load_empty_list(self) < 0)
- break;
- continue;
-
- case LIST:
- if (load_list(self) < 0)
- break;
- continue;
-
- case EMPTY_DICT:
- if (load_empty_dict(self) < 0)
- break;
- continue;
-
- case DICT:
- if (load_dict(self) < 0)
- break;
- continue;
-
- case OBJ:
- if (noload_obj(self) < 0)
- break;
- continue;
-
- case INST:
- if (noload_inst(self) < 0)
- break;
- continue;
-
- case NEWOBJ:
- if (noload_newobj(self) < 0)
- break;
- continue;
-
- case GLOBAL:
- if (noload_global(self) < 0)
- break;
- continue;
-
- case APPEND:
- if (noload_append(self) < 0)
- break;
- continue;
-
- case APPENDS:
- if (noload_appends(self) < 0)
- break;
- continue;
-
- case BUILD:
- if (noload_build(self) < 0)
- break;
- continue;
-
- case DUP:
- if (load_dup(self) < 0)
- break;
- continue;
-
- case BINGET:
- if (load_binget(self) < 0)
- break;
- continue;
-
- case LONG_BINGET:
- if (load_long_binget(self) < 0)
- break;
- continue;
-
- case GET:
- if (load_get(self) < 0)
- break;
- continue;
-
- case EXT1:
- if (noload_extension(self, 1) < 0)
- break;
- continue;
-
- case EXT2:
- if (noload_extension(self, 2) < 0)
- break;
- continue;
-
- case EXT4:
- if (noload_extension(self, 4) < 0)
- break;
- continue;
-
- case MARK:
- if (load_mark(self) < 0)
- break;
- continue;
-
- case BINPUT:
- if (load_binput(self) < 0)
- break;
- continue;
-
- case LONG_BINPUT:
- if (load_long_binput(self) < 0)
- break;
- continue;
-
- case PUT:
- if (load_put(self) < 0)
- break;
- continue;
-
- case POP:
- if (load_pop(self) < 0)
- break;
- continue;
-
- case POP_MARK:
- if (load_pop_mark(self) < 0)
- break;
- continue;
-
- case SETITEM:
- if (noload_setitem(self) < 0)
- break;
- continue;
-
- case SETITEMS:
- if (noload_setitems(self) < 0)
- break;
- continue;
-
- case STOP:
- break;
-
- case PERSID:
- if (load_persid(self) < 0)
- break;
- continue;
-
- case BINPERSID:
- if (load_binpersid(self) < 0)
- break;
- continue;
-
- case REDUCE:
- if (noload_reduce(self) < 0)
- break;
- continue;
-
- case PROTO:
- if (load_proto(self) < 0)
- break;
- continue;
-
- case NEWTRUE:
- if (load_bool(self, Py_True) < 0)
- break;
- continue;
-
- case NEWFALSE:
- if (load_bool(self, Py_False) < 0)
- break;
- continue;
- default:
- cPickle_ErrFormat(UnpicklingError,
- "invalid load key, '%s'.",
- "c", s[0]);
- return NULL;
- }
-
- break;
- }
-
- if ((err = PyErr_Occurred())) {
- if (err == PyExc_EOFError) {
- PyErr_SetNone(PyExc_EOFError);
- }
- return NULL;
- }
-
- PDATA_POP(self->stack, val);
- return val;
+ case EMPTY_TUPLE:
+ if (load_counted_tuple(self, 0) < 0)
+ break;
+ continue;
+
+ case TUPLE1:
+ if (load_counted_tuple(self, 1) < 0)
+ break;
+ continue;
+
+ case TUPLE2:
+ if (load_counted_tuple(self, 2) < 0)
+ break;
+ continue;
+
+ case TUPLE3:
+ if (load_counted_tuple(self, 3) < 0)
+ break;
+ continue;
+
+ case TUPLE:
+ if (load_tuple(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_LIST:
+ if (load_empty_list(self) < 0)
+ break;
+ continue;
+
+ case LIST:
+ if (load_list(self) < 0)
+ break;
+ continue;
+
+ case EMPTY_DICT:
+ if (load_empty_dict(self) < 0)
+ break;
+ continue;
+
+ case DICT:
+ if (load_dict(self) < 0)
+ break;
+ continue;
+
+ case OBJ:
+ if (noload_obj(self) < 0)
+ break;
+ continue;
+
+ case INST:
+ if (noload_inst(self) < 0)
+ break;
+ continue;
+
+ case NEWOBJ:
+ if (noload_newobj(self) < 0)
+ break;
+ continue;
+
+ case GLOBAL:
+ if (noload_global(self) < 0)
+ break;
+ continue;
+
+ case APPEND:
+ if (noload_append(self) < 0)
+ break;
+ continue;
+
+ case APPENDS:
+ if (noload_appends(self) < 0)
+ break;
+ continue;
+
+ case BUILD:
+ if (noload_build(self) < 0)
+ break;
+ continue;
+
+ case DUP:
+ if (load_dup(self) < 0)
+ break;
+ continue;
+
+ case BINGET:
+ if (load_binget(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINGET:
+ if (load_long_binget(self) < 0)
+ break;
+ continue;
+
+ case GET:
+ if (load_get(self) < 0)
+ break;
+ continue;
+
+ case EXT1:
+ if (noload_extension(self, 1) < 0)
+ break;
+ continue;
+
+ case EXT2:
+ if (noload_extension(self, 2) < 0)
+ break;
+ continue;
+
+ case EXT4:
+ if (noload_extension(self, 4) < 0)
+ break;
+ continue;
+
+ case MARK:
+ if (load_mark(self) < 0)
+ break;
+ continue;
+
+ case BINPUT:
+ if (load_binput(self) < 0)
+ break;
+ continue;
+
+ case LONG_BINPUT:
+ if (load_long_binput(self) < 0)
+ break;
+ continue;
+
+ case PUT:
+ if (load_put(self) < 0)
+ break;
+ continue;
+
+ case POP:
+ if (load_pop(self) < 0)
+ break;
+ continue;
+
+ case POP_MARK:
+ if (load_pop_mark(self) < 0)
+ break;
+ continue;
+
+ case SETITEM:
+ if (noload_setitem(self) < 0)
+ break;
+ continue;
+
+ case SETITEMS:
+ if (noload_setitems(self) < 0)
+ break;
+ continue;
+
+ case STOP:
+ break;
+
+ case PERSID:
+ if (load_persid(self) < 0)
+ break;
+ continue;
+
+ case BINPERSID:
+ if (load_binpersid(self) < 0)
+ break;
+ continue;
+
+ case REDUCE:
+ if (noload_reduce(self) < 0)
+ break;
+ continue;
+
+ case PROTO:
+ if (load_proto(self) < 0)
+ break;
+ continue;
+
+ case NEWTRUE:
+ if (load_bool(self, Py_True) < 0)
+ break;
+ continue;
+
+ case NEWFALSE:
+ if (load_bool(self, Py_False) < 0)
+ break;
+ continue;
+ default:
+ cPickle_ErrFormat(UnpicklingError,
+ "invalid load key, '%s'.",
+ "c", s[0]);
+ return NULL;
+ }
+
+ break;
+ }
+
+ if ((err = PyErr_Occurred())) {
+ if (err == PyExc_EOFError) {
+ PyErr_SetNone(PyExc_EOFError);
+ }
+ return NULL;
+ }
+
+ PDATA_POP(self->stack, val);
+ return val;
}
static PyObject *
Unpickler_load(Unpicklerobject *self, PyObject *unused)
{
- return load(self);
+ return load(self);
}
static PyObject *
Unpickler_noload(Unpicklerobject *self, PyObject *unused)
{
- return noload(self);
+ return noload(self);
}
@@ -5420,175 +5420,175 @@ static struct PyMethodDef Unpickler_methods[] = {
static Unpicklerobject *
newUnpicklerobject(PyObject *f)
{
- Unpicklerobject *self;
-
- if (!( self = PyObject_GC_New(Unpicklerobject, &Unpicklertype)))
- return NULL;
-
- self->file = NULL;
- self->arg = NULL;
- self->stack = (Pdata*)Pdata_New();
- self->pers_func = NULL;
- self->last_string = NULL;
- self->marks = NULL;
- self->num_marks = 0;
- self->marks_size = 0;
- self->buf_size = 0;
- self->read = NULL;
- self->readline = NULL;
- self->find_class = NULL;
-
- if (!( self->memo = PyDict_New()))
- goto err;
-
- if (!self->stack)
- goto err;
-
- Py_INCREF(f);
- self->file = f;
-
- /* Set read, readline based on type of f */
- if (PyFile_Check(f)) {
- self->fp = PyFile_AsFile(f);
- if (self->fp == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- goto err;
- }
- self->read_func = read_file;
- self->readline_func = readline_file;
- }
- else if (PycStringIO_InputCheck(f)) {
- self->fp = NULL;
- self->read_func = read_cStringIO;
- self->readline_func = readline_cStringIO;
- }
- else {
-
- self->fp = NULL;
- self->read_func = read_other;
- self->readline_func = readline_other;
-
- if (!( (self->readline = PyObject_GetAttr(f, readline_str)) &&
- (self->read = PyObject_GetAttr(f, read_str)))) {
- PyErr_Clear();
- PyErr_SetString( PyExc_TypeError,
- "argument must have 'read' and "
- "'readline' attributes" );
- goto err;
- }
- }
- PyObject_GC_Track(self);
-
- return self;
+ Unpicklerobject *self;
+
+ if (!( self = PyObject_GC_New(Unpicklerobject, &Unpicklertype)))
+ return NULL;
+
+ self->file = NULL;
+ self->arg = NULL;
+ self->stack = (Pdata*)Pdata_New();
+ self->pers_func = NULL;
+ self->last_string = NULL;
+ self->marks = NULL;
+ self->num_marks = 0;
+ self->marks_size = 0;
+ self->buf_size = 0;
+ self->read = NULL;
+ self->readline = NULL;
+ self->find_class = NULL;
+
+ if (!( self->memo = PyDict_New()))
+ goto err;
+
+ if (!self->stack)
+ goto err;
+
+ Py_INCREF(f);
+ self->file = f;
+
+ /* Set read, readline based on type of f */
+ if (PyFile_Check(f)) {
+ self->fp = PyFile_AsFile(f);
+ if (self->fp == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ goto err;
+ }
+ self->read_func = read_file;
+ self->readline_func = readline_file;
+ }
+ else if (PycStringIO_InputCheck(f)) {
+ self->fp = NULL;
+ self->read_func = read_cStringIO;
+ self->readline_func = readline_cStringIO;
+ }
+ else {
+
+ self->fp = NULL;
+ self->read_func = read_other;
+ self->readline_func = readline_other;
+
+ if (!( (self->readline = PyObject_GetAttr(f, readline_str)) &&
+ (self->read = PyObject_GetAttr(f, read_str)))) {
+ PyErr_Clear();
+ PyErr_SetString( PyExc_TypeError,
+ "argument must have 'read' and "
+ "'readline' attributes" );
+ goto err;
+ }
+ }
+ PyObject_GC_Track(self);
+
+ return self;
err:
- Py_DECREF((PyObject *)self);
- return NULL;
+ Py_DECREF((PyObject *)self);
+ return NULL;
}
static PyObject *
get_Unpickler(PyObject *self, PyObject *file)
{
- return (PyObject *)newUnpicklerobject(file);
+ return (PyObject *)newUnpicklerobject(file);
}
static void
Unpickler_dealloc(Unpicklerobject *self)
{
- PyObject_GC_UnTrack((PyObject *)self);
- Py_XDECREF(self->readline);
- Py_XDECREF(self->read);
- Py_XDECREF(self->file);
- Py_XDECREF(self->memo);
- Py_XDECREF(self->stack);
- Py_XDECREF(self->pers_func);
- Py_XDECREF(self->arg);
- Py_XDECREF(self->last_string);
- Py_XDECREF(self->find_class);
-
- if (self->marks) {
- free(self->marks);
- }
+ PyObject_GC_UnTrack((PyObject *)self);
+ Py_XDECREF(self->readline);
+ Py_XDECREF(self->read);
+ Py_XDECREF(self->file);
+ Py_XDECREF(self->memo);
+ Py_XDECREF(self->stack);
+ Py_XDECREF(self->pers_func);
+ Py_XDECREF(self->arg);
+ Py_XDECREF(self->last_string);
+ Py_XDECREF(self->find_class);
+
+ if (self->marks) {
+ free(self->marks);
+ }
- if (self->buf_size) {
- free(self->buf);
- }
+ if (self->buf_size) {
+ free(self->buf);
+ }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static int
Unpickler_traverse(Unpicklerobject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->readline);
- Py_VISIT(self->read);
- Py_VISIT(self->file);
- Py_VISIT(self->memo);
- Py_VISIT(self->stack);
- Py_VISIT(self->pers_func);
- Py_VISIT(self->arg);
- Py_VISIT(self->last_string);
- Py_VISIT(self->find_class);
- return 0;
+ Py_VISIT(self->readline);
+ Py_VISIT(self->read);
+ Py_VISIT(self->file);
+ Py_VISIT(self->memo);
+ Py_VISIT(self->stack);
+ Py_VISIT(self->pers_func);
+ Py_VISIT(self->arg);
+ Py_VISIT(self->last_string);
+ Py_VISIT(self->find_class);
+ return 0;
}
static int
Unpickler_clear(Unpicklerobject *self)
{
- Py_CLEAR(self->readline);
- Py_CLEAR(self->read);
- Py_CLEAR(self->file);
- Py_CLEAR(self->memo);
- Py_CLEAR(self->stack);
- Py_CLEAR(self->pers_func);
- Py_CLEAR(self->arg);
- Py_CLEAR(self->last_string);
- Py_CLEAR(self->find_class);
- return 0;
+ Py_CLEAR(self->readline);
+ Py_CLEAR(self->read);
+ Py_CLEAR(self->file);
+ Py_CLEAR(self->memo);
+ Py_CLEAR(self->stack);
+ Py_CLEAR(self->pers_func);
+ Py_CLEAR(self->arg);
+ Py_CLEAR(self->last_string);
+ Py_CLEAR(self->find_class);
+ return 0;
}
static PyObject *
Unpickler_getattr(Unpicklerobject *self, char *name)
{
- if (!strcmp(name, "persistent_load")) {
- if (!self->pers_func) {
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
- }
+ if (!strcmp(name, "persistent_load")) {
+ if (!self->pers_func) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
+ }
- Py_INCREF(self->pers_func);
- return self->pers_func;
- }
+ Py_INCREF(self->pers_func);
+ return self->pers_func;
+ }
- if (!strcmp(name, "find_global")) {
- if (!self->find_class) {
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
- }
+ if (!strcmp(name, "find_global")) {
+ if (!self->find_class) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
+ }
- Py_INCREF(self->find_class);
- return self->find_class;
- }
+ Py_INCREF(self->find_class);
+ return self->find_class;
+ }
- if (!strcmp(name, "memo")) {
- if (!self->memo) {
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
- }
+ if (!strcmp(name, "memo")) {
+ if (!self->memo) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
+ }
- Py_INCREF(self->memo);
- return self->memo;
- }
+ Py_INCREF(self->memo);
+ return self->memo;
+ }
- if (!strcmp(name, "UnpicklingError")) {
- Py_INCREF(UnpicklingError);
- return UnpicklingError;
- }
+ if (!strcmp(name, "UnpicklingError")) {
+ Py_INCREF(UnpicklingError);
+ return UnpicklingError;
+ }
- return Py_FindMethod(Unpickler_methods, (PyObject *)self, name);
+ return Py_FindMethod(Unpickler_methods, (PyObject *)self, name);
}
@@ -5596,40 +5596,40 @@ static int
Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value)
{
- if (!strcmp(name, "persistent_load")) {
- Py_XDECREF(self->pers_func);
- self->pers_func = value;
- Py_XINCREF(value);
- return 0;
- }
-
- if (!strcmp(name, "find_global")) {
- Py_XDECREF(self->find_class);
- self->find_class = value;
- Py_XINCREF(value);
- return 0;
- }
-
- if (! value) {
- PyErr_SetString(PyExc_TypeError,
- "attribute deletion is not supported");
- return -1;
- }
-
- if (strcmp(name, "memo") == 0) {
- if (!PyDict_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "memo must be a dictionary");
- return -1;
- }
- Py_XDECREF(self->memo);
- self->memo = value;
- Py_INCREF(value);
- return 0;
- }
-
- PyErr_SetString(PyExc_AttributeError, name);
- return -1;
+ if (!strcmp(name, "persistent_load")) {
+ Py_XDECREF(self->pers_func);
+ self->pers_func = value;
+ Py_XINCREF(value);
+ return 0;
+ }
+
+ if (!strcmp(name, "find_global")) {
+ Py_XDECREF(self->find_class);
+ self->find_class = value;
+ Py_XINCREF(value);
+ return 0;
+ }
+
+ if (! value) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute deletion is not supported");
+ return -1;
+ }
+
+ if (strcmp(name, "memo") == 0) {
+ if (!PyDict_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "memo must be a dictionary");
+ return -1;
+ }
+ Py_XDECREF(self->memo);
+ self->memo = value;
+ Py_INCREF(value);
+ return 0;
+ }
+
+ PyErr_SetString(PyExc_AttributeError, name);
+ return -1;
}
/* ---------------------------------------------------------------------------
@@ -5640,28 +5640,28 @@ Unpickler_setattr(Unpicklerobject *self, char *name, PyObject *value)
static PyObject *
cpm_dump(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"obj", "file", "protocol", NULL};
- PyObject *ob, *file, *res = NULL;
- Picklerobject *pickler = 0;
- int proto = 0;
+ static char *kwlist[] = {"obj", "file", "protocol", NULL};
+ PyObject *ob, *file, *res = NULL;
+ Picklerobject *pickler = 0;
+ int proto = 0;
- if (!( PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
- &ob, &file, &proto)))
- goto finally;
+ if (!( PyArg_ParseTupleAndKeywords(args, kwds, "OO|i", kwlist,
+ &ob, &file, &proto)))
+ goto finally;
- if (!( pickler = newPicklerobject(file, proto)))
- goto finally;
+ if (!( pickler = newPicklerobject(file, proto)))
+ goto finally;
- if (dump(pickler, ob) < 0)
- goto finally;
+ if (dump(pickler, ob) < 0)
+ goto finally;
- Py_INCREF(Py_None);
- res = Py_None;
+ Py_INCREF(Py_None);
+ res = Py_None;
finally:
- Py_XDECREF(pickler);
+ Py_XDECREF(pickler);
- return res;
+ return res;
}
@@ -5669,31 +5669,31 @@ cpm_dump(PyObject *self, PyObject *args, PyObject *kwds)
static PyObject *
cpm_dumps(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"obj", "protocol", NULL};
- PyObject *ob, *file = 0, *res = NULL;
- Picklerobject *pickler = 0;
- int proto = 0;
+ static char *kwlist[] = {"obj", "protocol", NULL};
+ PyObject *ob, *file = 0, *res = NULL;
+ Picklerobject *pickler = 0;
+ int proto = 0;
- if (!( PyArg_ParseTupleAndKeywords(args, kwds, "O|i:dumps", kwlist,
- &ob, &proto)))
- goto finally;
+ if (!( PyArg_ParseTupleAndKeywords(args, kwds, "O|i:dumps", kwlist,
+ &ob, &proto)))
+ goto finally;
- if (!( file = PycStringIO->NewOutput(128)))
- goto finally;
+ if (!( file = PycStringIO->NewOutput(128)))
+ goto finally;
- if (!( pickler = newPicklerobject(file, proto)))
- goto finally;
+ if (!( pickler = newPicklerobject(file, proto)))
+ goto finally;
- if (dump(pickler, ob) < 0)
- goto finally;
+ if (dump(pickler, ob) < 0)
+ goto finally;
- res = PycStringIO->cgetvalue(file);
+ res = PycStringIO->cgetvalue(file);
finally:
- Py_XDECREF(pickler);
- Py_XDECREF(file);
+ Py_XDECREF(pickler);
+ Py_XDECREF(file);
- return res;
+ return res;
}
@@ -5701,18 +5701,18 @@ cpm_dumps(PyObject *self, PyObject *args, PyObject *kwds)
static PyObject *
cpm_load(PyObject *self, PyObject *ob)
{
- Unpicklerobject *unpickler = 0;
- PyObject *res = NULL;
+ Unpicklerobject *unpickler = 0;
+ PyObject *res = NULL;
- if (!( unpickler = newUnpicklerobject(ob)))
- goto finally;
+ if (!( unpickler = newUnpicklerobject(ob)))
+ goto finally;
- res = load(unpickler);
+ res = load(unpickler);
finally:
- Py_XDECREF(unpickler);
+ Py_XDECREF(unpickler);
- return res;
+ return res;
}
@@ -5720,25 +5720,25 @@ cpm_load(PyObject *self, PyObject *ob)
static PyObject *
cpm_loads(PyObject *self, PyObject *args)
{
- PyObject *ob, *file = 0, *res = NULL;
- Unpicklerobject *unpickler = 0;
+ PyObject *ob, *file = 0, *res = NULL;
+ Unpicklerobject *unpickler = 0;
- if (!( PyArg_ParseTuple(args, "S:loads", &ob)))
- goto finally;
+ if (!( PyArg_ParseTuple(args, "S:loads", &ob)))
+ goto finally;
- if (!( file = PycStringIO->NewInput(ob)))
- goto finally;
+ if (!( file = PycStringIO->NewInput(ob)))
+ goto finally;
- if (!( unpickler = newUnpicklerobject(file)))
- goto finally;
+ if (!( unpickler = newUnpicklerobject(file)))
+ goto finally;
- res = load(unpickler);
+ res = load(unpickler);
finally:
- Py_XDECREF(file);
- Py_XDECREF(unpickler);
+ Py_XDECREF(file);
+ Py_XDECREF(unpickler);
- return res;
+ return res;
}
@@ -5747,28 +5747,28 @@ PyDoc_STRVAR(Unpicklertype__doc__,
static PyTypeObject Unpicklertype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "cPickle.Unpickler", /*tp_name*/
+ "cPickle.Unpickler", /*tp_name*/
sizeof(Unpicklerobject), /*tp_basicsize*/
0,
- (destructor)Unpickler_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- (getattrfunc)Unpickler_getattr, /* tp_getattr */
- (setattrfunc)Unpickler_setattr, /* 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 */
+ (destructor)Unpickler_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ (getattrfunc)Unpickler_getattr, /* tp_getattr */
+ (setattrfunc)Unpickler_setattr, /* 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 | Py_TPFLAGS_HAVE_GC,
- Unpicklertype__doc__, /* tp_doc */
- (traverseproc)Unpickler_traverse, /* tp_traverse */
- (inquiry)Unpickler_clear, /* tp_clear */
+ Unpicklertype__doc__, /* tp_doc */
+ (traverseproc)Unpickler_traverse, /* tp_traverse */
+ (inquiry)Unpickler_clear, /* tp_clear */
};
static struct PyMethodDef cPickle_methods[] = {
@@ -5826,198 +5826,198 @@ static struct PyMethodDef cPickle_methods[] = {
static int
init_stuff(PyObject *module_dict)
{
- PyObject *copyreg, *t, *r;
+ PyObject *copyreg, *t, *r;
#define INIT_STR(S) if (!( S ## _str=PyString_InternFromString(#S))) return -1;
- if (PyType_Ready(&Unpicklertype) < 0)
- return -1;
- if (PyType_Ready(&Picklertype) < 0)
- return -1;
-
- INIT_STR(__class__);
- INIT_STR(__getinitargs__);
- INIT_STR(__dict__);
- INIT_STR(__getstate__);
- INIT_STR(__setstate__);
- INIT_STR(__name__);
- INIT_STR(__main__);
- INIT_STR(__reduce__);
- INIT_STR(__reduce_ex__);
- INIT_STR(write);
- INIT_STR(append);
- INIT_STR(read);
- INIT_STR(readline);
- INIT_STR(dispatch_table);
-
- if (!( copyreg = PyImport_ImportModule("copy_reg")))
- return -1;
-
- /* This is special because we want to use a different
- one in restricted mode. */
- dispatch_table = PyObject_GetAttr(copyreg, dispatch_table_str);
- if (!dispatch_table) return -1;
-
- extension_registry = PyObject_GetAttrString(copyreg,
- "_extension_registry");
- if (!extension_registry) return -1;
-
- inverted_registry = PyObject_GetAttrString(copyreg,
- "_inverted_registry");
- if (!inverted_registry) return -1;
-
- extension_cache = PyObject_GetAttrString(copyreg,
- "_extension_cache");
- if (!extension_cache) return -1;
-
- Py_DECREF(copyreg);
-
- if (!(empty_tuple = PyTuple_New(0)))
- return -1;
-
- two_tuple = PyTuple_New(2);
- if (two_tuple == NULL)
- return -1;
- /* We use this temp container with no regard to refcounts, or to
- * keeping containees alive. Exempt from GC, because we don't
- * want anything looking at two_tuple() by magic.
- */
- PyObject_GC_UnTrack(two_tuple);
-
- /* Ugh */
- if (!( t=PyImport_ImportModule("__builtin__"))) return -1;
- if (PyDict_SetItemString(module_dict, "__builtins__", t) < 0)
- return -1;
-
- if (!( t=PyDict_New())) return -1;
- if (!( r=PyRun_String(
- "def __str__(self):\n"
- " return self.args and ('%s' % self.args[0]) or '(what)'\n",
- Py_file_input,
- module_dict, t) )) return -1;
- Py_DECREF(r);
-
- PickleError = PyErr_NewException("cPickle.PickleError", NULL, t);
- if (!PickleError)
- return -1;
-
- Py_DECREF(t);
-
- PicklingError = PyErr_NewException("cPickle.PicklingError",
- PickleError, NULL);
- if (!PicklingError)
- return -1;
-
- if (!( t=PyDict_New())) return -1;
- if (!( r=PyRun_String(
- "def __str__(self):\n"
- " a=self.args\n"
- " a=a and type(a[0]) or '(what)'\n"
- " return 'Cannot pickle %s objects' % a\n"
- , Py_file_input,
- module_dict, t) )) return -1;
- Py_DECREF(r);
-
- if (!( UnpickleableError = PyErr_NewException(
- "cPickle.UnpickleableError", PicklingError, t)))
- return -1;
-
- Py_DECREF(t);
-
- if (!( UnpicklingError = PyErr_NewException("cPickle.UnpicklingError",
- PickleError, NULL)))
- return -1;
-
- if (!( BadPickleGet = PyErr_NewException("cPickle.BadPickleGet",
- UnpicklingError, NULL)))
- return -1;
-
- if (PyDict_SetItemString(module_dict, "PickleError",
- PickleError) < 0)
- return -1;
-
- if (PyDict_SetItemString(module_dict, "PicklingError",
- PicklingError) < 0)
- return -1;
-
- if (PyDict_SetItemString(module_dict, "UnpicklingError",
- UnpicklingError) < 0)
- return -1;
+ if (PyType_Ready(&Unpicklertype) < 0)
+ return -1;
+ if (PyType_Ready(&Picklertype) < 0)
+ return -1;
+
+ INIT_STR(__class__);
+ INIT_STR(__getinitargs__);
+ INIT_STR(__dict__);
+ INIT_STR(__getstate__);
+ INIT_STR(__setstate__);
+ INIT_STR(__name__);
+ INIT_STR(__main__);
+ INIT_STR(__reduce__);
+ INIT_STR(__reduce_ex__);
+ INIT_STR(write);
+ INIT_STR(append);
+ INIT_STR(read);
+ INIT_STR(readline);
+ INIT_STR(dispatch_table);
+
+ if (!( copyreg = PyImport_ImportModule("copy_reg")))
+ return -1;
+
+ /* This is special because we want to use a different
+ one in restricted mode. */
+ dispatch_table = PyObject_GetAttr(copyreg, dispatch_table_str);
+ if (!dispatch_table) return -1;
+
+ extension_registry = PyObject_GetAttrString(copyreg,
+ "_extension_registry");
+ if (!extension_registry) return -1;
+
+ inverted_registry = PyObject_GetAttrString(copyreg,
+ "_inverted_registry");
+ if (!inverted_registry) return -1;
+
+ extension_cache = PyObject_GetAttrString(copyreg,
+ "_extension_cache");
+ if (!extension_cache) return -1;
+
+ Py_DECREF(copyreg);
+
+ if (!(empty_tuple = PyTuple_New(0)))
+ return -1;
+
+ two_tuple = PyTuple_New(2);
+ if (two_tuple == NULL)
+ return -1;
+ /* We use this temp container with no regard to refcounts, or to
+ * keeping containees alive. Exempt from GC, because we don't
+ * want anything looking at two_tuple() by magic.
+ */
+ PyObject_GC_UnTrack(two_tuple);
+
+ /* Ugh */
+ if (!( t=PyImport_ImportModule("__builtin__"))) return -1;
+ if (PyDict_SetItemString(module_dict, "__builtins__", t) < 0)
+ return -1;
+
+ if (!( t=PyDict_New())) return -1;
+ if (!( r=PyRun_String(
+ "def __str__(self):\n"
+ " return self.args and ('%s' % self.args[0]) or '(what)'\n",
+ Py_file_input,
+ module_dict, t) )) return -1;
+ Py_DECREF(r);
+
+ PickleError = PyErr_NewException("cPickle.PickleError", NULL, t);
+ if (!PickleError)
+ return -1;
+
+ Py_DECREF(t);
+
+ PicklingError = PyErr_NewException("cPickle.PicklingError",
+ PickleError, NULL);
+ if (!PicklingError)
+ return -1;
+
+ if (!( t=PyDict_New())) return -1;
+ if (!( r=PyRun_String(
+ "def __str__(self):\n"
+ " a=self.args\n"
+ " a=a and type(a[0]) or '(what)'\n"
+ " return 'Cannot pickle %s objects' % a\n"
+ , Py_file_input,
+ module_dict, t) )) return -1;
+ Py_DECREF(r);
+
+ if (!( UnpickleableError = PyErr_NewException(
+ "cPickle.UnpickleableError", PicklingError, t)))
+ return -1;
+
+ Py_DECREF(t);
+
+ if (!( UnpicklingError = PyErr_NewException("cPickle.UnpicklingError",
+ PickleError, NULL)))
+ return -1;
+
+ if (!( BadPickleGet = PyErr_NewException("cPickle.BadPickleGet",
+ UnpicklingError, NULL)))
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "PickleError",
+ PickleError) < 0)
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "PicklingError",
+ PicklingError) < 0)
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "UnpicklingError",
+ UnpicklingError) < 0)
+ return -1;
+
+ if (PyDict_SetItemString(module_dict, "UnpickleableError",
+ UnpickleableError) < 0)
+ return -1;
- if (PyDict_SetItemString(module_dict, "UnpickleableError",
- UnpickleableError) < 0)
- return -1;
+ if (PyDict_SetItemString(module_dict, "BadPickleGet",
+ BadPickleGet) < 0)
+ return -1;
- if (PyDict_SetItemString(module_dict, "BadPickleGet",
- BadPickleGet) < 0)
- return -1;
-
- PycString_IMPORT;
-
- return 0;
+ PycString_IMPORT;
+
+ return 0;
}
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
initcPickle(void)
{
- PyObject *m, *d, *di, *v, *k;
- Py_ssize_t i;
- char *rev = "1.71"; /* XXX when does this change? */
- PyObject *format_version;
- PyObject *compatible_formats;
-
- Py_TYPE(&Picklertype) = &PyType_Type;
- Py_TYPE(&Unpicklertype) = &PyType_Type;
- Py_TYPE(&PdataType) = &PyType_Type;
-
- /* Initialize some pieces. We need to do this before module creation,
- * so we're forced to use a temporary dictionary. :(
- */
- di = PyDict_New();
- if (!di) return;
- if (init_stuff(di) < 0) return;
-
- /* Create the module and add the functions */
- m = Py_InitModule4("cPickle", cPickle_methods,
- cPickle_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- v = PyString_FromString(rev);
- PyDict_SetItemString(d, "__version__", v);
- Py_XDECREF(v);
-
- /* Copy data from di. Waaa. */
- for (i=0; PyDict_Next(di, &i, &k, &v); ) {
- if (PyObject_SetItem(d, k, v) < 0) {
- Py_DECREF(di);
- return;
- }
- }
- Py_DECREF(di);
-
- i = PyModule_AddIntConstant(m, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL);
- if (i < 0)
- return;
-
- /* These are purely informational; no code uses them. */
- /* File format version we write. */
- format_version = PyString_FromString("2.0");
- /* Format versions we can read. */
- compatible_formats = Py_BuildValue("[sssss]",
- "1.0", /* Original protocol 0 */
- "1.1", /* Protocol 0 + INST */
- "1.2", /* Original protocol 1 */
- "1.3", /* Protocol 1 + BINFLOAT */
- "2.0"); /* Original protocol 2 */
- PyDict_SetItemString(d, "format_version", format_version);
- PyDict_SetItemString(d, "compatible_formats", compatible_formats);
- Py_XDECREF(format_version);
- Py_XDECREF(compatible_formats);
+ PyObject *m, *d, *di, *v, *k;
+ Py_ssize_t i;
+ char *rev = "1.71"; /* XXX when does this change? */
+ PyObject *format_version;
+ PyObject *compatible_formats;
+
+ Py_TYPE(&Picklertype) = &PyType_Type;
+ Py_TYPE(&Unpicklertype) = &PyType_Type;
+ Py_TYPE(&PdataType) = &PyType_Type;
+
+ /* Initialize some pieces. We need to do this before module creation,
+ * so we're forced to use a temporary dictionary. :(
+ */
+ di = PyDict_New();
+ if (!di) return;
+ if (init_stuff(di) < 0) return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule4("cPickle", cPickle_methods,
+ cPickle_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ v = PyString_FromString(rev);
+ PyDict_SetItemString(d, "__version__", v);
+ Py_XDECREF(v);
+
+ /* Copy data from di. Waaa. */
+ for (i=0; PyDict_Next(di, &i, &k, &v); ) {
+ if (PyObject_SetItem(d, k, v) < 0) {
+ Py_DECREF(di);
+ return;
+ }
+ }
+ Py_DECREF(di);
+
+ i = PyModule_AddIntConstant(m, "HIGHEST_PROTOCOL", HIGHEST_PROTOCOL);
+ if (i < 0)
+ return;
+
+ /* These are purely informational; no code uses them. */
+ /* File format version we write. */
+ format_version = PyString_FromString("2.0");
+ /* Format versions we can read. */
+ compatible_formats = Py_BuildValue("[sssss]",
+ "1.0", /* Original protocol 0 */
+ "1.1", /* Protocol 0 + INST */
+ "1.2", /* Original protocol 1 */
+ "1.3", /* Protocol 1 + BINFLOAT */
+ "2.0"); /* Original protocol 2 */
+ PyDict_SetItemString(d, "format_version", format_version);
+ PyDict_SetItemString(d, "compatible_formats", compatible_formats);
+ Py_XDECREF(format_version);
+ Py_XDECREF(compatible_formats);
}
diff --git a/Modules/cStringIO.c b/Modules/cStringIO.c
index 80588bf..6aa3d5d 100644
--- a/Modules/cStringIO.c
+++ b/Modules/cStringIO.c
@@ -33,7 +33,7 @@ PyDoc_STRVAR(cStringIO_module_documentation,
"\n"
"cStringIO.c,v 1.29 1999/06/15 14:10:27 jim Exp\n");
-/* Declaration for file-like objects that manage data as strings
+/* Declaration for file-like objects that manage data as strings
The IOobject type should be though of as a common base type for
Iobjects, which provide input (read-only) StringIO objects and
@@ -77,37 +77,37 @@ PyDoc_STRVAR(IO_flush__doc__, "flush(): does nothing.");
static int
IO__opencheck(IOobject *self) {
- if (!self->buf) {
- PyErr_SetString(PyExc_ValueError,
- "I/O operation on closed file");
- return 0;
- }
- return 1;
+ if (!self->buf) {
+ PyErr_SetString(PyExc_ValueError,
+ "I/O operation on closed file");
+ return 0;
+ }
+ return 1;
}
static PyObject *
IO_get_closed(IOobject *self, void *closure)
{
- PyObject *result = Py_False;
+ PyObject *result = Py_False;
- if (self->buf == NULL)
- result = Py_True;
- Py_INCREF(result);
- return result;
+ if (self->buf == NULL)
+ result = Py_True;
+ Py_INCREF(result);
+ return result;
}
static PyGetSetDef file_getsetlist[] = {
- {"closed", (getter)IO_get_closed, NULL, "True if the file is closed"},
- {0},
+ {"closed", (getter)IO_get_closed, NULL, "True if the file is closed"},
+ {0},
};
static PyObject *
IO_flush(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
+ if (!IO__opencheck(self)) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(IO_getval__doc__,
@@ -118,37 +118,37 @@ PyDoc_STRVAR(IO_getval__doc__,
static PyObject *
IO_cgetval(PyObject *self) {
- if (!IO__opencheck(IOOOBJECT(self))) return NULL;
- assert(IOOOBJECT(self)->pos >= 0);
- return PyString_FromStringAndSize(((IOobject*)self)->buf,
- ((IOobject*)self)->pos);
+ if (!IO__opencheck(IOOOBJECT(self))) return NULL;
+ assert(IOOOBJECT(self)->pos >= 0);
+ return PyString_FromStringAndSize(((IOobject*)self)->buf,
+ ((IOobject*)self)->pos);
}
static PyObject *
IO_getval(IOobject *self, PyObject *args) {
- PyObject *use_pos=Py_None;
- Py_ssize_t s;
-
- if (!IO__opencheck(self)) return NULL;
- if (!PyArg_UnpackTuple(args,"getval", 0, 1,&use_pos)) return NULL;
-
- if (PyObject_IsTrue(use_pos)) {
- s=self->pos;
- if (s > self->string_size) s=self->string_size;
- }
- else
- s=self->string_size;
- assert(self->pos >= 0);
- return PyString_FromStringAndSize(self->buf, s);
+ PyObject *use_pos=Py_None;
+ Py_ssize_t s;
+
+ if (!IO__opencheck(self)) return NULL;
+ if (!PyArg_UnpackTuple(args,"getval", 0, 1,&use_pos)) return NULL;
+
+ if (PyObject_IsTrue(use_pos)) {
+ s=self->pos;
+ if (s > self->string_size) s=self->string_size;
+ }
+ else
+ s=self->string_size;
+ assert(self->pos >= 0);
+ return PyString_FromStringAndSize(self->buf, s);
}
PyDoc_STRVAR(IO_isatty__doc__, "isatty(): always returns 0");
static PyObject *
IO_isatty(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
- Py_INCREF(Py_False);
- return Py_False;
+ if (!IO__opencheck(self)) return NULL;
+ Py_INCREF(Py_False);
+ return Py_False;
}
PyDoc_STRVAR(IO_read__doc__,
@@ -156,114 +156,114 @@ PyDoc_STRVAR(IO_read__doc__,
static int
IO_cread(PyObject *self, char **output, Py_ssize_t n) {
- Py_ssize_t l;
-
- if (!IO__opencheck(IOOOBJECT(self))) return -1;
- assert(IOOOBJECT(self)->pos >= 0);
- assert(IOOOBJECT(self)->string_size >= 0);
- l = ((IOobject*)self)->string_size - ((IOobject*)self)->pos;
- if (n < 0 || n > l) {
- n = l;
- if (n < 0) n=0;
- }
-
- *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
- ((IOobject*)self)->pos += n;
- return n;
+ Py_ssize_t l;
+
+ if (!IO__opencheck(IOOOBJECT(self))) return -1;
+ assert(IOOOBJECT(self)->pos >= 0);
+ assert(IOOOBJECT(self)->string_size >= 0);
+ l = ((IOobject*)self)->string_size - ((IOobject*)self)->pos;
+ if (n < 0 || n > l) {
+ n = l;
+ if (n < 0) n=0;
+ }
+
+ *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
+ ((IOobject*)self)->pos += n;
+ return n;
}
static PyObject *
IO_read(IOobject *self, PyObject *args) {
- Py_ssize_t n = -1;
- char *output = NULL;
+ Py_ssize_t n = -1;
+ char *output = NULL;
- if (!PyArg_ParseTuple(args, "|n:read", &n)) return NULL;
+ if (!PyArg_ParseTuple(args, "|n:read", &n)) return NULL;
- if ( (n=IO_cread((PyObject*)self,&output,n)) < 0) return NULL;
+ if ( (n=IO_cread((PyObject*)self,&output,n)) < 0) return NULL;
- return PyString_FromStringAndSize(output, n);
+ return PyString_FromStringAndSize(output, n);
}
PyDoc_STRVAR(IO_readline__doc__, "readline() -- Read one line");
static int
IO_creadline(PyObject *self, char **output) {
- char *n, *s;
- Py_ssize_t l;
+ char *n, *s;
+ Py_ssize_t l;
- if (!IO__opencheck(IOOOBJECT(self))) return -1;
+ if (!IO__opencheck(IOOOBJECT(self))) return -1;
- for (n = ((IOobject*)self)->buf + ((IOobject*)self)->pos,
- s = ((IOobject*)self)->buf + ((IOobject*)self)->string_size;
- n < s && *n != '\n'; n++);
+ for (n = ((IOobject*)self)->buf + ((IOobject*)self)->pos,
+ s = ((IOobject*)self)->buf + ((IOobject*)self)->string_size;
+ n < s && *n != '\n'; n++);
- if (n < s) n++;
+ if (n < s) n++;
- *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
- l = n - ((IOobject*)self)->buf - ((IOobject*)self)->pos;
+ *output=((IOobject*)self)->buf + ((IOobject*)self)->pos;
+ l = n - ((IOobject*)self)->buf - ((IOobject*)self)->pos;
- assert(IOOOBJECT(self)->pos <= PY_SSIZE_T_MAX - l);
- assert(IOOOBJECT(self)->pos >= 0);
- assert(IOOOBJECT(self)->string_size >= 0);
+ assert(IOOOBJECT(self)->pos <= PY_SSIZE_T_MAX - l);
+ assert(IOOOBJECT(self)->pos >= 0);
+ assert(IOOOBJECT(self)->string_size >= 0);
- ((IOobject*)self)->pos += l;
- return (int)l;
+ ((IOobject*)self)->pos += l;
+ return (int)l;
}
static PyObject *
IO_readline(IOobject *self, PyObject *args) {
- int n, m=-1;
- char *output;
-
- if (args)
- if (!PyArg_ParseTuple(args, "|i:readline", &m)) return NULL;
-
- if( (n=IO_creadline((PyObject*)self,&output)) < 0) return NULL;
- if (m >= 0 && m < n) {
- m = n - m;
- n -= m;
- self->pos -= m;
- }
- assert(IOOOBJECT(self)->pos >= 0);
- return PyString_FromStringAndSize(output, n);
+ int n, m=-1;
+ char *output;
+
+ if (args)
+ if (!PyArg_ParseTuple(args, "|i:readline", &m)) return NULL;
+
+ if( (n=IO_creadline((PyObject*)self,&output)) < 0) return NULL;
+ if (m >= 0 && m < n) {
+ m = n - m;
+ n -= m;
+ self->pos -= m;
+ }
+ assert(IOOOBJECT(self)->pos >= 0);
+ return PyString_FromStringAndSize(output, n);
}
PyDoc_STRVAR(IO_readlines__doc__, "readlines() -- Read all lines");
static PyObject *
IO_readlines(IOobject *self, PyObject *args) {
- int n;
- char *output;
- PyObject *result, *line;
- int hint = 0, length = 0;
-
- if (!PyArg_ParseTuple(args, "|i:readlines", &hint)) return NULL;
-
- result = PyList_New(0);
- if (!result)
- return NULL;
-
- while (1){
- if ( (n = IO_creadline((PyObject*)self,&output)) < 0)
- goto err;
- if (n == 0)
- break;
- line = PyString_FromStringAndSize (output, n);
- if (!line)
- goto err;
- if (PyList_Append (result, line) == -1) {
- Py_DECREF (line);
- goto err;
- }
- Py_DECREF (line);
- length += n;
- if (hint > 0 && length >= hint)
- break;
- }
- return result;
- err:
- Py_DECREF(result);
+ int n;
+ char *output;
+ PyObject *result, *line;
+ int hint = 0, length = 0;
+
+ if (!PyArg_ParseTuple(args, "|i:readlines", &hint)) return NULL;
+
+ result = PyList_New(0);
+ if (!result)
return NULL;
+
+ while (1){
+ if ( (n = IO_creadline((PyObject*)self,&output)) < 0)
+ goto err;
+ if (n == 0)
+ break;
+ line = PyString_FromStringAndSize (output, n);
+ if (!line)
+ goto err;
+ if (PyList_Append (result, line) == -1) {
+ Py_DECREF (line);
+ goto err;
+ }
+ Py_DECREF (line);
+ length += n;
+ if (hint > 0 && length >= hint)
+ break;
+ }
+ return result;
+ err:
+ Py_DECREF(result);
+ return NULL;
}
PyDoc_STRVAR(IO_reset__doc__,
@@ -272,12 +272,12 @@ PyDoc_STRVAR(IO_reset__doc__,
static PyObject *
IO_reset(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
+ if (!IO__opencheck(self)) return NULL;
- self->pos = 0;
+ self->pos = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(IO_tell__doc__, "tell() -- get the current position.");
@@ -285,10 +285,10 @@ PyDoc_STRVAR(IO_tell__doc__, "tell() -- get the current position.");
static PyObject *
IO_tell(IOobject *self, PyObject *unused) {
- if (!IO__opencheck(self)) return NULL;
+ if (!IO__opencheck(self)) return NULL;
- assert(self->pos >= 0);
- return PyInt_FromSsize_t(self->pos);
+ assert(self->pos >= 0);
+ return PyInt_FromSsize_t(self->pos);
}
PyDoc_STRVAR(IO_truncate__doc__,
@@ -296,42 +296,42 @@ PyDoc_STRVAR(IO_truncate__doc__,
static PyObject *
IO_truncate(IOobject *self, PyObject *args) {
- Py_ssize_t pos = -1;
-
- if (!IO__opencheck(self)) return NULL;
- if (!PyArg_ParseTuple(args, "|n:truncate", &pos)) return NULL;
-
- if (PyTuple_Size(args) == 0) {
- /* No argument passed, truncate to current position */
- pos = self->pos;
- }
-
- if (pos < 0) {
- errno = EINVAL;
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
-
- if (self->string_size > pos) self->string_size = pos;
- self->pos = self->string_size;
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t pos = -1;
+
+ if (!IO__opencheck(self)) return NULL;
+ if (!PyArg_ParseTuple(args, "|n:truncate", &pos)) return NULL;
+
+ if (PyTuple_Size(args) == 0) {
+ /* No argument passed, truncate to current position */
+ pos = self->pos;
+ }
+
+ if (pos < 0) {
+ errno = EINVAL;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+
+ if (self->string_size > pos) self->string_size = pos;
+ self->pos = self->string_size;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
IO_iternext(Iobject *self)
{
- PyObject *next;
- next = IO_readline((IOobject *)self, NULL);
- if (!next)
- return NULL;
- if (!PyString_GET_SIZE(next)) {
- Py_DECREF(next);
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
- return next;
+ PyObject *next;
+ next = IO_readline((IOobject *)self, NULL);
+ if (!next)
+ return NULL;
+ if (!PyString_GET_SIZE(next)) {
+ Py_DECREF(next);
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
+ return next;
}
@@ -345,41 +345,41 @@ PyDoc_STRVAR(O_seek__doc__,
static PyObject *
O_seek(Oobject *self, PyObject *args) {
- Py_ssize_t position;
- int mode = 0;
-
- if (!IO__opencheck(IOOOBJECT(self))) return NULL;
- if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
- return NULL;
-
- if (mode == 2) {
- position += self->string_size;
- }
- else if (mode == 1) {
- position += self->pos;
- }
+ Py_ssize_t position;
+ int mode = 0;
- if (position > self->buf_size) {
- char *newbuf;
- self->buf_size*=2;
- if (self->buf_size <= position) self->buf_size=position+1;
- newbuf = (char*) realloc(self->buf,self->buf_size);
- if (!newbuf) {
- free(self->buf);
- self->buf = 0;
- self->buf_size=self->pos=0;
- return PyErr_NoMemory();
- }
- self->buf = newbuf;
- }
- else if (position < 0) position=0;
-
- self->pos=position;
-
- while (--position >= self->string_size) self->buf[position]=0;
+ if (!IO__opencheck(IOOOBJECT(self))) return NULL;
+ if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (mode == 2) {
+ position += self->string_size;
+ }
+ else if (mode == 1) {
+ position += self->pos;
+ }
+
+ if (position > self->buf_size) {
+ char *newbuf;
+ self->buf_size*=2;
+ if (self->buf_size <= position) self->buf_size=position+1;
+ newbuf = (char*) realloc(self->buf,self->buf_size);
+ if (!newbuf) {
+ free(self->buf);
+ self->buf = 0;
+ self->buf_size=self->pos=0;
+ return PyErr_NoMemory();
+ }
+ self->buf = newbuf;
+ }
+ else if (position < 0) position=0;
+
+ self->pos=position;
+
+ while (--position >= self->string_size) self->buf[position]=0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(O_write__doc__,
@@ -389,67 +389,67 @@ PyDoc_STRVAR(O_write__doc__,
static int
O_cwrite(PyObject *self, const char *c, Py_ssize_t l) {
- Py_ssize_t newl;
- Oobject *oself;
- char *newbuf;
-
- if (!IO__opencheck(IOOOBJECT(self))) return -1;
- oself = (Oobject *)self;
-
- newl = oself->pos+l;
- if (newl >= oself->buf_size) {
- oself->buf_size *= 2;
- if (oself->buf_size <= newl) {
- assert(newl + 1 < INT_MAX);
- oself->buf_size = (int)(newl+1);
- }
- newbuf = (char*)realloc(oself->buf, oself->buf_size);
- if (!newbuf) {
- PyErr_SetString(PyExc_MemoryError,"out of memory");
- free(oself->buf);
- oself->buf = 0;
- oself->buf_size = oself->pos = 0;
- return -1;
- }
- oself->buf = newbuf;
+ Py_ssize_t newl;
+ Oobject *oself;
+ char *newbuf;
+
+ if (!IO__opencheck(IOOOBJECT(self))) return -1;
+ oself = (Oobject *)self;
+
+ newl = oself->pos+l;
+ if (newl >= oself->buf_size) {
+ oself->buf_size *= 2;
+ if (oself->buf_size <= newl) {
+ assert(newl + 1 < INT_MAX);
+ oself->buf_size = (int)(newl+1);
+ }
+ newbuf = (char*)realloc(oself->buf, oself->buf_size);
+ if (!newbuf) {
+ PyErr_SetString(PyExc_MemoryError,"out of memory");
+ free(oself->buf);
+ oself->buf = 0;
+ oself->buf_size = oself->pos = 0;
+ return -1;
}
+ oself->buf = newbuf;
+ }
- memcpy(oself->buf+oself->pos,c,l);
+ memcpy(oself->buf+oself->pos,c,l);
- assert(oself->pos + l < INT_MAX);
- oself->pos += (int)l;
+ assert(oself->pos + l < INT_MAX);
+ oself->pos += (int)l;
- if (oself->string_size < oself->pos) {
- oself->string_size = oself->pos;
- }
+ if (oself->string_size < oself->pos) {
+ oself->string_size = oself->pos;
+ }
- return (int)l;
+ return (int)l;
}
static PyObject *
O_write(Oobject *self, PyObject *args) {
- char *c;
- int l;
+ char *c;
+ int l;
- if (!PyArg_ParseTuple(args, "t#:write", &c, &l)) return NULL;
+ if (!PyArg_ParseTuple(args, "t#:write", &c, &l)) return NULL;
- if (O_cwrite((PyObject*)self,c,l) < 0) return NULL;
+ if (O_cwrite((PyObject*)self,c,l) < 0) return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(O_close__doc__, "close(): explicitly release resources held.");
static PyObject *
O_close(Oobject *self, PyObject *unused) {
- if (self->buf != NULL) free(self->buf);
- self->buf = NULL;
+ if (self->buf != NULL) free(self->buf);
+ self->buf = NULL;
- self->pos = self->string_size = self->buf_size = 0;
+ self->pos = self->string_size = self->buf_size = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(O_writelines__doc__,
@@ -459,32 +459,32 @@ PyDoc_STRVAR(O_writelines__doc__,
"producing strings. This is equivalent to calling write() for each string.");
static PyObject *
O_writelines(Oobject *self, PyObject *args) {
- PyObject *it, *s;
-
- it = PyObject_GetIter(args);
- if (it == NULL)
- return NULL;
- while ((s = PyIter_Next(it)) != NULL) {
- Py_ssize_t n;
- char *c;
- if (PyString_AsStringAndSize(s, &c, &n) == -1) {
- Py_DECREF(it);
- Py_DECREF(s);
- return NULL;
- }
- if (O_cwrite((PyObject *)self, c, n) == -1) {
- Py_DECREF(it);
- Py_DECREF(s);
- return NULL;
- }
- Py_DECREF(s);
+ PyObject *it, *s;
+
+ it = PyObject_GetIter(args);
+ if (it == NULL)
+ return NULL;
+ while ((s = PyIter_Next(it)) != NULL) {
+ Py_ssize_t n;
+ char *c;
+ if (PyString_AsStringAndSize(s, &c, &n) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(s);
+ return NULL;
+ }
+ if (O_cwrite((PyObject *)self, c, n) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(s);
+ return NULL;
+ }
+ Py_DECREF(s);
}
Py_DECREF(it);
/* See if PyIter_Next failed */
if (PyErr_Occurred())
- return NULL;
+ return NULL;
Py_RETURN_NONE;
}
@@ -493,92 +493,92 @@ static struct PyMethodDef O_methods[] = {
{"flush", (PyCFunction)IO_flush, METH_NOARGS, IO_flush__doc__},
{"getvalue", (PyCFunction)IO_getval, METH_VARARGS, IO_getval__doc__},
{"isatty", (PyCFunction)IO_isatty, METH_NOARGS, IO_isatty__doc__},
- {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
- {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
- {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
- {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
+ {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
+ {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
+ {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
+ {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
{"tell", (PyCFunction)IO_tell, METH_NOARGS, IO_tell__doc__},
{"truncate", (PyCFunction)IO_truncate, METH_VARARGS, IO_truncate__doc__},
/* Read-write StringIO specific methods: */
{"close", (PyCFunction)O_close, METH_NOARGS, O_close__doc__},
{"seek", (PyCFunction)O_seek, METH_VARARGS, O_seek__doc__},
- {"write", (PyCFunction)O_write, METH_VARARGS, O_write__doc__},
- {"writelines", (PyCFunction)O_writelines, METH_O, O_writelines__doc__},
- {NULL, NULL} /* sentinel */
+ {"write", (PyCFunction)O_write, METH_VARARGS, O_write__doc__},
+ {"writelines", (PyCFunction)O_writelines, METH_O, O_writelines__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyMemberDef O_memberlist[] = {
- {"softspace", T_INT, offsetof(Oobject, softspace), 0,
- "flag indicating that a space needs to be printed; used by print"},
- /* getattr(f, "closed") is implemented without this table */
- {NULL} /* Sentinel */
+ {"softspace", T_INT, offsetof(Oobject, softspace), 0,
+ "flag indicating that a space needs to be printed; used by print"},
+ /* getattr(f, "closed") is implemented without this table */
+ {NULL} /* Sentinel */
};
static void
O_dealloc(Oobject *self) {
- if (self->buf != NULL)
- free(self->buf);
- PyObject_Del(self);
+ if (self->buf != NULL)
+ free(self->buf);
+ PyObject_Del(self);
}
PyDoc_STRVAR(Otype__doc__, "Simple type for output to strings.");
static PyTypeObject Otype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "cStringIO.StringO", /*tp_name*/
- sizeof(Oobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ "cStringIO.StringO", /*tp_name*/
+ sizeof(Oobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
- (destructor)O_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, /*tp_flags*/
- Otype__doc__, /*tp_doc */
- 0, /*tp_traverse */
- 0, /*tp_clear */
- 0, /*tp_richcompare */
- 0, /*tp_weaklistoffset */
- PyObject_SelfIter, /*tp_iter */
- (iternextfunc)IO_iternext, /*tp_iternext */
- O_methods, /*tp_methods */
- O_memberlist, /*tp_members */
- file_getsetlist, /*tp_getset */
+ (destructor)O_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, /*tp_flags*/
+ Otype__doc__, /*tp_doc */
+ 0, /*tp_traverse */
+ 0, /*tp_clear */
+ 0, /*tp_richcompare */
+ 0, /*tp_weaklistoffset */
+ PyObject_SelfIter, /*tp_iter */
+ (iternextfunc)IO_iternext, /*tp_iternext */
+ O_methods, /*tp_methods */
+ O_memberlist, /*tp_members */
+ file_getsetlist, /*tp_getset */
};
static PyObject *
newOobject(int size) {
- Oobject *self;
-
- self = PyObject_New(Oobject, &Otype);
- if (self == NULL)
- return NULL;
- self->pos=0;
- self->string_size = 0;
- self->softspace = 0;
-
- self->buf = (char *)malloc(size);
- if (!self->buf) {
- PyErr_SetString(PyExc_MemoryError,"out of memory");
- self->buf_size = 0;
- Py_DECREF(self);
- return NULL;
- }
+ Oobject *self;
- self->buf_size=size;
- return (PyObject*)self;
+ self = PyObject_New(Oobject, &Otype);
+ if (self == NULL)
+ return NULL;
+ self->pos=0;
+ self->string_size = 0;
+ self->softspace = 0;
+
+ self->buf = (char *)malloc(size);
+ if (!self->buf) {
+ PyErr_SetString(PyExc_MemoryError,"out of memory");
+ self->buf_size = 0;
+ Py_DECREF(self);
+ return NULL;
+ }
+
+ self->buf_size=size;
+ return (PyObject*)self;
}
/* End of code for StringO objects */
@@ -586,33 +586,33 @@ newOobject(int size) {
static PyObject *
I_close(Iobject *self, PyObject *unused) {
- Py_CLEAR(self->pbuf);
- self->buf = NULL;
+ Py_CLEAR(self->pbuf);
+ self->buf = NULL;
- self->pos = self->string_size = 0;
+ self->pos = self->string_size = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
I_seek(Iobject *self, PyObject *args) {
- Py_ssize_t position;
- int mode = 0;
+ Py_ssize_t position;
+ int mode = 0;
- if (!IO__opencheck(IOOOBJECT(self))) return NULL;
- if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
- return NULL;
+ if (!IO__opencheck(IOOOBJECT(self))) return NULL;
+ if (!PyArg_ParseTuple(args, "n|i:seek", &position, &mode))
+ return NULL;
- if (mode == 2) position += self->string_size;
- else if (mode == 1) position += self->pos;
+ if (mode == 2) position += self->string_size;
+ else if (mode == 1) position += self->pos;
- if (position < 0) position=0;
+ if (position < 0) position=0;
- self->pos=position;
+ self->pos=position;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef I_methods[] = {
@@ -620,17 +620,17 @@ static struct PyMethodDef I_methods[] = {
{"flush", (PyCFunction)IO_flush, METH_NOARGS, IO_flush__doc__},
{"getvalue", (PyCFunction)IO_getval, METH_VARARGS, IO_getval__doc__},
{"isatty", (PyCFunction)IO_isatty, METH_NOARGS, IO_isatty__doc__},
- {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
- {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
- {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
- {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
+ {"read", (PyCFunction)IO_read, METH_VARARGS, IO_read__doc__},
+ {"readline", (PyCFunction)IO_readline, METH_VARARGS, IO_readline__doc__},
+ {"readlines", (PyCFunction)IO_readlines,METH_VARARGS, IO_readlines__doc__},
+ {"reset", (PyCFunction)IO_reset, METH_NOARGS, IO_reset__doc__},
{"tell", (PyCFunction)IO_tell, METH_NOARGS, IO_tell__doc__},
{"truncate", (PyCFunction)IO_truncate, METH_VARARGS, IO_truncate__doc__},
/* Read-only StringIO specific methods: */
{"close", (PyCFunction)I_close, METH_NOARGS, O_close__doc__},
- {"seek", (PyCFunction)I_seek, METH_VARARGS, O_seek__doc__},
- {NULL, NULL}
+ {"seek", (PyCFunction)I_seek, METH_VARARGS, O_seek__doc__},
+ {NULL, NULL}
};
static void
@@ -645,36 +645,36 @@ PyDoc_STRVAR(Itype__doc__,
static PyTypeObject Itype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "cStringIO.StringI", /*tp_name*/
- sizeof(Iobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
+ "cStringIO.StringI", /*tp_name*/
+ sizeof(Iobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
/* methods */
- (destructor)I_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, /* tp_flags */
- Itype__doc__, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)IO_iternext, /* tp_iternext */
- I_methods, /* tp_methods */
- 0, /* tp_members */
- file_getsetlist, /* tp_getset */
+ (destructor)I_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, /* tp_flags */
+ Itype__doc__, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)IO_iternext, /* tp_iternext */
+ I_methods, /* tp_methods */
+ 0, /* tp_members */
+ file_getsetlist, /* tp_getset */
};
static PyObject *
@@ -696,7 +696,7 @@ newIobject(PyObject *s) {
self->string_size=size;
self->pbuf=s;
self->pos=0;
-
+
return (PyObject*)self;
}
@@ -720,9 +720,9 @@ IO_StringIO(PyObject *self, PyObject *args) {
/* List of methods defined in the module */
static struct PyMethodDef IO_methods[] = {
- {"StringIO", (PyCFunction)IO_StringIO,
- METH_VARARGS, IO_StringIO__doc__},
- {NULL, NULL} /* sentinel */
+ {"StringIO", (PyCFunction)IO_StringIO,
+ METH_VARARGS, IO_StringIO__doc__},
+ {NULL, NULL} /* sentinel */
};
@@ -739,7 +739,7 @@ static struct PycStringIO_CAPI CAPI = {
&Otype,
};
-#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
+#ifndef PyMODINIT_FUNC /* declarations for DLL import/export */
#define PyMODINIT_FUNC void
#endif
PyMODINIT_FUNC
@@ -749,13 +749,13 @@ initcStringIO(void) {
/* Create the module and add the functions */
m = Py_InitModule4("cStringIO", IO_methods,
- cStringIO_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
+ cStringIO_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
if (m == NULL) return;
/* Add some symbolic constants to the module */
d = PyModule_GetDict(m);
-
+
/* Export C API */
Py_TYPE(&Itype)=&PyType_Type;
Py_TYPE(&Otype)=&PyType_Type;
diff --git a/Modules/cdmodule.c b/Modules/cdmodule.c
index f09b0a4..8dfb769 100644
--- a/Modules/cdmodule.c
+++ b/Modules/cdmodule.c
@@ -5,796 +5,796 @@
#include <cdaudio.h>
#include "Python.h"
-#define NCALLBACKS 8
+#define NCALLBACKS 8
typedef struct {
- PyObject_HEAD
- CDPLAYER *ob_cdplayer;
+ PyObject_HEAD
+ CDPLAYER *ob_cdplayer;
} cdplayerobject;
-static PyObject *CdError; /* exception cd.error */
+static PyObject *CdError; /* exception cd.error */
static PyObject *
CD_allowremoval(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":allowremoval"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":allowremoval"))
+ return NULL;
- CDallowremoval(self->ob_cdplayer);
+ CDallowremoval(self->ob_cdplayer);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_preventremoval(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":preventremoval"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":preventremoval"))
+ return NULL;
- CDpreventremoval(self->ob_cdplayer);
+ CDpreventremoval(self->ob_cdplayer);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_bestreadsize(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":bestreadsize"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":bestreadsize"))
+ return NULL;
- return PyInt_FromLong((long) CDbestreadsize(self->ob_cdplayer));
+ return PyInt_FromLong((long) CDbestreadsize(self->ob_cdplayer));
}
static PyObject *
CD_close(cdplayerobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":close"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":close"))
+ return NULL;
- if (!CDclose(self->ob_cdplayer)) {
- PyErr_SetFromErrno(CdError); /* XXX - ??? */
- return NULL;
- }
- self->ob_cdplayer = NULL;
+ if (!CDclose(self->ob_cdplayer)) {
+ PyErr_SetFromErrno(CdError); /* XXX - ??? */
+ return NULL;
+ }
+ self->ob_cdplayer = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_eject(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":eject"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":eject"))
+ return NULL;
- if (!CDeject(self->ob_cdplayer)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "eject failed");
- return NULL;
- }
+ if (!CDeject(self->ob_cdplayer)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "eject failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_getstatus(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":getstatus"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":getstatus"))
+ return NULL;
- if (!CDgetstatus(self->ob_cdplayer, &status)) {
- PyErr_SetFromErrno(CdError); /* XXX - ??? */
- return NULL;
- }
+ if (!CDgetstatus(self->ob_cdplayer, &status)) {
+ PyErr_SetFromErrno(CdError); /* XXX - ??? */
+ return NULL;
+ }
- return Py_BuildValue("(ii(iii)(iii)(iii)iiii)", status.state,
- status.track, status.min, status.sec, status.frame,
- status.abs_min, status.abs_sec, status.abs_frame,
- status.total_min, status.total_sec, status.total_frame,
- status.first, status.last, status.scsi_audio,
- status.cur_block);
+ return Py_BuildValue("(ii(iii)(iii)(iii)iiii)", status.state,
+ status.track, status.min, status.sec, status.frame,
+ status.abs_min, status.abs_sec, status.abs_frame,
+ status.total_min, status.total_sec, status.total_frame,
+ status.first, status.last, status.scsi_audio,
+ status.cur_block);
}
-
+
static PyObject *
CD_gettrackinfo(cdplayerobject *self, PyObject *args)
{
- int track;
- CDTRACKINFO info;
- CDSTATUS status;
+ int track;
+ CDTRACKINFO info;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "i:gettrackinfo", &track))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:gettrackinfo", &track))
+ return NULL;
- if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "gettrackinfo failed");
- return NULL;
- }
+ if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "gettrackinfo failed");
+ return NULL;
+ }
- return Py_BuildValue("((iii)(iii))",
- info.start_min, info.start_sec, info.start_frame,
- info.total_min, info.total_sec, info.total_frame);
+ return Py_BuildValue("((iii)(iii))",
+ info.start_min, info.start_sec, info.start_frame,
+ info.total_min, info.total_sec, info.total_frame);
}
-
+
static PyObject *
CD_msftoblock(cdplayerobject *self, PyObject *args)
{
- int min, sec, frame;
+ int min, sec, frame;
- if (!PyArg_ParseTuple(args, "iii:msftoblock", &min, &sec, &frame))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iii:msftoblock", &min, &sec, &frame))
+ return NULL;
- return PyInt_FromLong((long) CDmsftoblock(self->ob_cdplayer,
- min, sec, frame));
+ return PyInt_FromLong((long) CDmsftoblock(self->ob_cdplayer,
+ min, sec, frame));
}
-
+
static PyObject *
CD_play(cdplayerobject *self, PyObject *args)
{
- int start, play;
- CDSTATUS status;
+ int start, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "ii:play", &start, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ii:play", &start, &play))
+ return NULL;
- if (!CDplay(self->ob_cdplayer, start, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "play failed");
- return NULL;
- }
+ if (!CDplay(self->ob_cdplayer, start, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "play failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_playabs(cdplayerobject *self, PyObject *args)
{
- int min, sec, frame, play;
- CDSTATUS status;
+ int min, sec, frame, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "iiii:playabs", &min, &sec, &frame, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iiii:playabs", &min, &sec, &frame, &play))
+ return NULL;
- if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "playabs failed");
- return NULL;
- }
+ if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "playabs failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_playtrack(cdplayerobject *self, PyObject *args)
{
- int start, play;
- CDSTATUS status;
+ int start, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "ii:playtrack", &start, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ii:playtrack", &start, &play))
+ return NULL;
- if (!CDplaytrack(self->ob_cdplayer, start, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "playtrack failed");
- return NULL;
- }
+ if (!CDplaytrack(self->ob_cdplayer, start, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "playtrack failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_playtrackabs(cdplayerobject *self, PyObject *args)
{
- int track, min, sec, frame, play;
- CDSTATUS status;
+ int track, min, sec, frame, play;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, "iiiii:playtrackabs", &track, &min, &sec,
- &frame, &play))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iiiii:playtrackabs", &track, &min, &sec,
+ &frame, &play))
+ return NULL;
- if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "playtrackabs failed");
- return NULL;
- }
+ if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "playtrackabs failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_readda(cdplayerobject *self, PyObject *args)
{
- int numframes, n;
- PyObject *result;
+ int numframes, n;
+ PyObject *result;
- if (!PyArg_ParseTuple(args, "i:readda", &numframes))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:readda", &numframes))
+ return NULL;
- result = PyString_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
- if (result == NULL)
- return NULL;
+ result = PyString_FromStringAndSize(NULL, numframes * sizeof(CDFRAME));
+ if (result == NULL)
+ return NULL;
- n = CDreadda(self->ob_cdplayer,
- (CDFRAME *) PyString_AsString(result), numframes);
- if (n == -1) {
- Py_DECREF(result);
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
- if (n < numframes)
- _PyString_Resize(&result, n * sizeof(CDFRAME));
+ n = CDreadda(self->ob_cdplayer,
+ (CDFRAME *) PyString_AsString(result), numframes);
+ if (n == -1) {
+ Py_DECREF(result);
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
+ if (n < numframes)
+ _PyString_Resize(&result, n * sizeof(CDFRAME));
- return result;
+ return result;
}
static PyObject *
CD_seek(cdplayerobject *self, PyObject *args)
{
- int min, sec, frame;
- long PyTryBlock;
+ int min, sec, frame;
+ long PyTryBlock;
- if (!PyArg_ParseTuple(args, "iii:seek", &min, &sec, &frame))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iii:seek", &min, &sec, &frame))
+ return NULL;
- PyTryBlock = CDseek(self->ob_cdplayer, min, sec, frame);
- if (PyTryBlock == -1) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ PyTryBlock = CDseek(self->ob_cdplayer, min, sec, frame);
+ if (PyTryBlock == -1) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return PyInt_FromLong(PyTryBlock);
+ return PyInt_FromLong(PyTryBlock);
}
-
+
static PyObject *
CD_seektrack(cdplayerobject *self, PyObject *args)
{
- int track;
- long PyTryBlock;
+ int track;
+ long PyTryBlock;
- if (!PyArg_ParseTuple(args, "i:seektrack", &track))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:seektrack", &track))
+ return NULL;
- PyTryBlock = CDseektrack(self->ob_cdplayer, track);
- if (PyTryBlock == -1) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ PyTryBlock = CDseektrack(self->ob_cdplayer, track);
+ if (PyTryBlock == -1) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return PyInt_FromLong(PyTryBlock);
+ return PyInt_FromLong(PyTryBlock);
}
-
+
static PyObject *
CD_seekblock(cdplayerobject *self, PyObject *args)
{
- unsigned long PyTryBlock;
+ unsigned long PyTryBlock;
- if (!PyArg_ParseTuple(args, "l:seekblock", &PyTryBlock))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:seekblock", &PyTryBlock))
+ return NULL;
- PyTryBlock = CDseekblock(self->ob_cdplayer, PyTryBlock);
- if (PyTryBlock == (unsigned long) -1) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ PyTryBlock = CDseekblock(self->ob_cdplayer, PyTryBlock);
+ if (PyTryBlock == (unsigned long) -1) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return PyInt_FromLong(PyTryBlock);
+ return PyInt_FromLong(PyTryBlock);
}
-
+
static PyObject *
CD_stop(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":stop"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":stop"))
+ return NULL;
- if (!CDstop(self->ob_cdplayer)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "stop failed");
- return NULL;
- }
+ if (!CDstop(self->ob_cdplayer)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "stop failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject *
CD_togglepause(cdplayerobject *self, PyObject *args)
{
- CDSTATUS status;
+ CDSTATUS status;
- if (!PyArg_ParseTuple(args, ":togglepause"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":togglepause"))
+ return NULL;
- if (!CDtogglepause(self->ob_cdplayer)) {
- if (CDgetstatus(self->ob_cdplayer, &status) &&
- status.state == CD_NODISC)
- PyErr_SetString(CdError, "no disc in player");
- else
- PyErr_SetString(CdError, "togglepause failed");
- return NULL;
- }
+ if (!CDtogglepause(self->ob_cdplayer)) {
+ if (CDgetstatus(self->ob_cdplayer, &status) &&
+ status.state == CD_NODISC)
+ PyErr_SetString(CdError, "no disc in player");
+ else
+ PyErr_SetString(CdError, "togglepause failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyMethodDef cdplayer_methods[] = {
- {"allowremoval", (PyCFunction)CD_allowremoval, METH_VARARGS},
- {"bestreadsize", (PyCFunction)CD_bestreadsize, METH_VARARGS},
- {"close", (PyCFunction)CD_close, METH_VARARGS},
- {"eject", (PyCFunction)CD_eject, METH_VARARGS},
- {"getstatus", (PyCFunction)CD_getstatus, METH_VARARGS},
- {"gettrackinfo", (PyCFunction)CD_gettrackinfo, METH_VARARGS},
- {"msftoblock", (PyCFunction)CD_msftoblock, METH_VARARGS},
- {"play", (PyCFunction)CD_play, METH_VARARGS},
- {"playabs", (PyCFunction)CD_playabs, METH_VARARGS},
- {"playtrack", (PyCFunction)CD_playtrack, METH_VARARGS},
- {"playtrackabs", (PyCFunction)CD_playtrackabs, METH_VARARGS},
- {"preventremoval", (PyCFunction)CD_preventremoval, METH_VARARGS},
- {"readda", (PyCFunction)CD_readda, METH_VARARGS},
- {"seek", (PyCFunction)CD_seek, METH_VARARGS},
- {"seekblock", (PyCFunction)CD_seekblock, METH_VARARGS},
- {"seektrack", (PyCFunction)CD_seektrack, METH_VARARGS},
- {"stop", (PyCFunction)CD_stop, METH_VARARGS},
- {"togglepause", (PyCFunction)CD_togglepause, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"allowremoval", (PyCFunction)CD_allowremoval, METH_VARARGS},
+ {"bestreadsize", (PyCFunction)CD_bestreadsize, METH_VARARGS},
+ {"close", (PyCFunction)CD_close, METH_VARARGS},
+ {"eject", (PyCFunction)CD_eject, METH_VARARGS},
+ {"getstatus", (PyCFunction)CD_getstatus, METH_VARARGS},
+ {"gettrackinfo", (PyCFunction)CD_gettrackinfo, METH_VARARGS},
+ {"msftoblock", (PyCFunction)CD_msftoblock, METH_VARARGS},
+ {"play", (PyCFunction)CD_play, METH_VARARGS},
+ {"playabs", (PyCFunction)CD_playabs, METH_VARARGS},
+ {"playtrack", (PyCFunction)CD_playtrack, METH_VARARGS},
+ {"playtrackabs", (PyCFunction)CD_playtrackabs, METH_VARARGS},
+ {"preventremoval", (PyCFunction)CD_preventremoval, METH_VARARGS},
+ {"readda", (PyCFunction)CD_readda, METH_VARARGS},
+ {"seek", (PyCFunction)CD_seek, METH_VARARGS},
+ {"seekblock", (PyCFunction)CD_seekblock, METH_VARARGS},
+ {"seektrack", (PyCFunction)CD_seektrack, METH_VARARGS},
+ {"stop", (PyCFunction)CD_stop, METH_VARARGS},
+ {"togglepause", (PyCFunction)CD_togglepause, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static void
cdplayer_dealloc(cdplayerobject *self)
{
- if (self->ob_cdplayer != NULL)
- CDclose(self->ob_cdplayer);
- PyObject_Del(self);
+ if (self->ob_cdplayer != NULL)
+ CDclose(self->ob_cdplayer);
+ PyObject_Del(self);
}
static PyObject *
cdplayer_getattr(cdplayerobject *self, char *name)
{
- if (self->ob_cdplayer == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "no player active");
- return NULL;
- }
- return Py_FindMethod(cdplayer_methods, (PyObject *)self, name);
+ if (self->ob_cdplayer == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "no player active");
+ return NULL;
+ }
+ return Py_FindMethod(cdplayer_methods, (PyObject *)self, name);
}
PyTypeObject CdPlayertype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "cd.cdplayer", /*tp_name*/
- sizeof(cdplayerobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)cdplayer_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)cdplayer_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "cd.cdplayer", /*tp_name*/
+ sizeof(cdplayerobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)cdplayer_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)cdplayer_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newcdplayerobject(CDPLAYER *cdp)
{
- cdplayerobject *p;
+ cdplayerobject *p;
- p = PyObject_New(cdplayerobject, &CdPlayertype);
- if (p == NULL)
- return NULL;
- p->ob_cdplayer = cdp;
- return (PyObject *) p;
+ p = PyObject_New(cdplayerobject, &CdPlayertype);
+ if (p == NULL)
+ return NULL;
+ p->ob_cdplayer = cdp;
+ return (PyObject *) p;
}
static PyObject *
CD_open(PyObject *self, PyObject *args)
{
- char *dev, *direction;
- CDPLAYER *cdp;
+ char *dev, *direction;
+ CDPLAYER *cdp;
- /*
- * Variable number of args.
- * First defaults to "None", second defaults to "r".
- */
- dev = NULL;
- direction = "r";
- if (!PyArg_ParseTuple(args, "|zs:open", &dev, &direction))
- return NULL;
+ /*
+ * Variable number of args.
+ * First defaults to "None", second defaults to "r".
+ */
+ dev = NULL;
+ direction = "r";
+ if (!PyArg_ParseTuple(args, "|zs:open", &dev, &direction))
+ return NULL;
- cdp = CDopen(dev, direction);
- if (cdp == NULL) {
- PyErr_SetFromErrno(CdError);
- return NULL;
- }
+ cdp = CDopen(dev, direction);
+ if (cdp == NULL) {
+ PyErr_SetFromErrno(CdError);
+ return NULL;
+ }
- return newcdplayerobject(cdp);
+ return newcdplayerobject(cdp);
}
typedef struct {
- PyObject_HEAD
- CDPARSER *ob_cdparser;
- struct {
- PyObject *ob_cdcallback;
- PyObject *ob_cdcallbackarg;
- } ob_cdcallbacks[NCALLBACKS];
+ PyObject_HEAD
+ CDPARSER *ob_cdparser;
+ struct {
+ PyObject *ob_cdcallback;
+ PyObject *ob_cdcallbackarg;
+ } ob_cdcallbacks[NCALLBACKS];
} cdparserobject;
static void
CD_callback(void *arg, CDDATATYPES type, void *data)
{
- PyObject *result, *args, *v = NULL;
- char *p;
- int i;
- cdparserobject *self;
-
- self = (cdparserobject *) arg;
- args = PyTuple_New(3);
- if (args == NULL)
- return;
- Py_INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
- PyTuple_SetItem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg);
- PyTuple_SetItem(args, 1, PyInt_FromLong((long) type));
- switch (type) {
- case cd_audio:
- v = PyString_FromStringAndSize(data, CDDA_DATASIZE);
- break;
- case cd_pnum:
- case cd_index:
- v = PyInt_FromLong(((CDPROGNUM *) data)->value);
- break;
- case cd_ptime:
- case cd_atime:
+ PyObject *result, *args, *v = NULL;
+ char *p;
+ int i;
+ cdparserobject *self;
+
+ self = (cdparserobject *) arg;
+ args = PyTuple_New(3);
+ if (args == NULL)
+ return;
+ Py_INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ PyTuple_SetItem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ PyTuple_SetItem(args, 1, PyInt_FromLong((long) type));
+ switch (type) {
+ case cd_audio:
+ v = PyString_FromStringAndSize(data, CDDA_DATASIZE);
+ break;
+ case cd_pnum:
+ case cd_index:
+ v = PyInt_FromLong(((CDPROGNUM *) data)->value);
+ break;
+ case cd_ptime:
+ case cd_atime:
#define ptr ((struct cdtimecode *) data)
- v = Py_BuildValue("(iii)",
- ptr->mhi * 10 + ptr->mlo,
- ptr->shi * 10 + ptr->slo,
- ptr->fhi * 10 + ptr->flo);
+ v = Py_BuildValue("(iii)",
+ ptr->mhi * 10 + ptr->mlo,
+ ptr->shi * 10 + ptr->slo,
+ ptr->fhi * 10 + ptr->flo);
#undef ptr
- break;
- case cd_catalog:
- v = PyString_FromStringAndSize(NULL, 13);
- p = PyString_AsString(v);
- for (i = 0; i < 13; i++)
- *p++ = ((char *) data)[i] + '0';
- break;
- case cd_ident:
+ break;
+ case cd_catalog:
+ v = PyString_FromStringAndSize(NULL, 13);
+ p = PyString_AsString(v);
+ for (i = 0; i < 13; i++)
+ *p++ = ((char *) data)[i] + '0';
+ break;
+ case cd_ident:
#define ptr ((struct cdident *) data)
- v = PyString_FromStringAndSize(NULL, 12);
- p = PyString_AsString(v);
- CDsbtoa(p, ptr->country, 2);
- p += 2;
- CDsbtoa(p, ptr->owner, 3);
- p += 3;
- *p++ = ptr->year[0] + '0';
- *p++ = ptr->year[1] + '0';
- *p++ = ptr->serial[0] + '0';
- *p++ = ptr->serial[1] + '0';
- *p++ = ptr->serial[2] + '0';
- *p++ = ptr->serial[3] + '0';
- *p++ = ptr->serial[4] + '0';
+ v = PyString_FromStringAndSize(NULL, 12);
+ p = PyString_AsString(v);
+ CDsbtoa(p, ptr->country, 2);
+ p += 2;
+ CDsbtoa(p, ptr->owner, 3);
+ p += 3;
+ *p++ = ptr->year[0] + '0';
+ *p++ = ptr->year[1] + '0';
+ *p++ = ptr->serial[0] + '0';
+ *p++ = ptr->serial[1] + '0';
+ *p++ = ptr->serial[2] + '0';
+ *p++ = ptr->serial[3] + '0';
+ *p++ = ptr->serial[4] + '0';
#undef ptr
- break;
- case cd_control:
- v = PyInt_FromLong((long) *((unchar *) data));
- break;
- }
- PyTuple_SetItem(args, 2, v);
- if (PyErr_Occurred()) {
- Py_DECREF(args);
- return;
- }
-
- result = PyEval_CallObject(self->ob_cdcallbacks[type].ob_cdcallback,
- args);
- Py_DECREF(args);
- Py_XDECREF(result);
+ break;
+ case cd_control:
+ v = PyInt_FromLong((long) *((unchar *) data));
+ break;
+ }
+ PyTuple_SetItem(args, 2, v);
+ if (PyErr_Occurred()) {
+ Py_DECREF(args);
+ return;
+ }
+
+ result = PyEval_CallObject(self->ob_cdcallbacks[type].ob_cdcallback,
+ args);
+ Py_DECREF(args);
+ Py_XDECREF(result);
}
static PyObject *
CD_deleteparser(cdparserobject *self, PyObject *args)
{
- int i;
+ int i;
- if (!PyArg_ParseTuple(args, ":deleteparser"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":deleteparser"))
+ return NULL;
- CDdeleteparser(self->ob_cdparser);
- self->ob_cdparser = NULL;
+ CDdeleteparser(self->ob_cdparser);
+ self->ob_cdparser = NULL;
- /* no sense in keeping the callbacks, so remove them */
- for (i = 0; i < NCALLBACKS; i++) {
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
- self->ob_cdcallbacks[i].ob_cdcallback = NULL;
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
- self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
- }
+ /* no sense in keeping the callbacks, so remove them */
+ for (i = 0; i < NCALLBACKS; i++) {
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
+ self->ob_cdcallbacks[i].ob_cdcallback = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
+ self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_parseframe(cdparserobject *self, PyObject *args)
{
- char *cdfp;
- int length;
- CDFRAME *p;
+ char *cdfp;
+ int length;
+ CDFRAME *p;
- if (!PyArg_ParseTuple(args, "s#:parseframe", &cdfp, &length))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#:parseframe", &cdfp, &length))
+ return NULL;
- if (length % sizeof(CDFRAME) != 0) {
- PyErr_SetString(PyExc_TypeError, "bad length");
- return NULL;
- }
+ if (length % sizeof(CDFRAME) != 0) {
+ PyErr_SetString(PyExc_TypeError, "bad length");
+ return NULL;
+ }
- p = (CDFRAME *) cdfp;
- while (length > 0) {
- CDparseframe(self->ob_cdparser, p);
- length -= sizeof(CDFRAME);
- p++;
- if (PyErr_Occurred())
- return NULL;
- }
+ p = (CDFRAME *) cdfp;
+ while (length > 0) {
+ CDparseframe(self->ob_cdparser, p);
+ length -= sizeof(CDFRAME);
+ p++;
+ if (PyErr_Occurred())
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_removecallback(cdparserobject *self, PyObject *args)
{
- int type;
+ int type;
- if (!PyArg_ParseTuple(args, "i:removecallback", &type))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:removecallback", &type))
+ return NULL;
- if (type < 0 || type >= NCALLBACKS) {
- PyErr_SetString(PyExc_TypeError, "bad type");
- return NULL;
- }
+ if (type < 0 || type >= NCALLBACKS) {
+ PyErr_SetString(PyExc_TypeError, "bad type");
+ return NULL;
+ }
- CDremovecallback(self->ob_cdparser, (CDDATATYPES) type);
+ CDremovecallback(self->ob_cdparser, (CDDATATYPES) type);
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
- self->ob_cdcallbacks[type].ob_cdcallback = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
+ self->ob_cdcallbacks[type].ob_cdcallback = NULL;
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
- self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_resetparser(cdparserobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":resetparser"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":resetparser"))
+ return NULL;
- CDresetparser(self->ob_cdparser);
+ CDresetparser(self->ob_cdparser);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
CD_addcallback(cdparserobject *self, PyObject *args)
{
- int type;
- PyObject *func, *funcarg;
+ int type;
+ PyObject *func, *funcarg;
- /* XXX - more work here */
- if (!PyArg_ParseTuple(args, "iOO:addcallback", &type, &func, &funcarg))
- return NULL;
+ /* XXX - more work here */
+ if (!PyArg_ParseTuple(args, "iOO:addcallback", &type, &func, &funcarg))
+ return NULL;
- if (type < 0 || type >= NCALLBACKS) {
- PyErr_SetString(PyExc_TypeError, "argument out of range");
- return NULL;
- }
+ if (type < 0 || type >= NCALLBACKS) {
+ PyErr_SetString(PyExc_TypeError, "argument out of range");
+ return NULL;
+ }
#ifdef CDsetcallback
- CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
- (void *) self);
+ CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
+ (void *) self);
#else
- CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
- (void *) self);
+ CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback,
+ (void *) self);
#endif
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
- Py_INCREF(func);
- self->ob_cdcallbacks[type].ob_cdcallback = func;
- Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
- Py_INCREF(funcarg);
- self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallback);
+ Py_INCREF(func);
+ self->ob_cdcallbacks[type].ob_cdcallback = func;
+ Py_XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg);
+ Py_INCREF(funcarg);
+ self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg;
/*
- if (type == cd_audio) {
- sigfpe_[_UNDERFL].repls = _ZERO;
- handle_sigfpes(_ON, _EN_UNDERFL, NULL,
- _ABORT_ON_ERROR, NULL);
- }
+ if (type == cd_audio) {
+ sigfpe_[_UNDERFL].repls = _ZERO;
+ handle_sigfpes(_ON, _EN_UNDERFL, NULL,
+ _ABORT_ON_ERROR, NULL);
+ }
*/
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef cdparser_methods[] = {
- {"addcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
- {"deleteparser", (PyCFunction)CD_deleteparser, METH_VARARGS},
- {"parseframe", (PyCFunction)CD_parseframe, METH_VARARGS},
- {"removecallback", (PyCFunction)CD_removecallback, METH_VARARGS},
- {"resetparser", (PyCFunction)CD_resetparser, METH_VARARGS},
- /* backward compatibility */
- {"setcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"addcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
+ {"deleteparser", (PyCFunction)CD_deleteparser, METH_VARARGS},
+ {"parseframe", (PyCFunction)CD_parseframe, METH_VARARGS},
+ {"removecallback", (PyCFunction)CD_removecallback, METH_VARARGS},
+ {"resetparser", (PyCFunction)CD_resetparser, METH_VARARGS},
+ /* backward compatibility */
+ {"setcallback", (PyCFunction)CD_addcallback, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static void
cdparser_dealloc(cdparserobject *self)
{
- int i;
+ int i;
- for (i = 0; i < NCALLBACKS; i++) {
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
- self->ob_cdcallbacks[i].ob_cdcallback = NULL;
- Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
- self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
- }
- CDdeleteparser(self->ob_cdparser);
- PyObject_Del(self);
+ for (i = 0; i < NCALLBACKS; i++) {
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallback);
+ self->ob_cdcallbacks[i].ob_cdcallback = NULL;
+ Py_XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg);
+ self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
+ }
+ CDdeleteparser(self->ob_cdparser);
+ PyObject_Del(self);
}
static PyObject *
cdparser_getattr(cdparserobject *self, char *name)
{
- if (self->ob_cdparser == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "no parser active");
- return NULL;
- }
+ if (self->ob_cdparser == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "no parser active");
+ return NULL;
+ }
- return Py_FindMethod(cdparser_methods, (PyObject *)self, name);
+ return Py_FindMethod(cdparser_methods, (PyObject *)self, name);
}
PyTypeObject CdParsertype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "cd.cdparser", /*tp_name*/
- sizeof(cdparserobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)cdparser_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)cdparser_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "cd.cdparser", /*tp_name*/
+ sizeof(cdparserobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)cdparser_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)cdparser_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newcdparserobject(CDPARSER *cdp)
{
- cdparserobject *p;
- int i;
+ cdparserobject *p;
+ int i;
- p = PyObject_New(cdparserobject, &CdParsertype);
- if (p == NULL)
- return NULL;
- p->ob_cdparser = cdp;
- for (i = 0; i < NCALLBACKS; i++) {
- p->ob_cdcallbacks[i].ob_cdcallback = NULL;
- p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
- }
- return (PyObject *) p;
+ p = PyObject_New(cdparserobject, &CdParsertype);
+ if (p == NULL)
+ return NULL;
+ p->ob_cdparser = cdp;
+ for (i = 0; i < NCALLBACKS; i++) {
+ p->ob_cdcallbacks[i].ob_cdcallback = NULL;
+ p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL;
+ }
+ return (PyObject *) p;
}
static PyObject *
CD_createparser(PyObject *self, PyObject *args)
{
- CDPARSER *cdp;
+ CDPARSER *cdp;
- if (!PyArg_ParseTuple(args, ":createparser"))
- return NULL;
- cdp = CDcreateparser();
- if (cdp == NULL) {
- PyErr_SetString(CdError, "createparser failed");
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, ":createparser"))
+ return NULL;
+ cdp = CDcreateparser();
+ if (cdp == NULL) {
+ PyErr_SetString(CdError, "createparser failed");
+ return NULL;
+ }
- return newcdparserobject(cdp);
+ return newcdparserobject(cdp);
}
static PyObject *
CD_msftoframe(PyObject *self, PyObject *args)
{
- int min, sec, frame;
+ int min, sec, frame;
- if (!PyArg_ParseTuple(args, "iii:msftoframe", &min, &sec, &frame))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iii:msftoframe", &min, &sec, &frame))
+ return NULL;
- return PyInt_FromLong((long) CDmsftoframe(min, sec, frame));
+ return PyInt_FromLong((long) CDmsftoframe(min, sec, frame));
}
-
+
static PyMethodDef CD_methods[] = {
- {"open", (PyCFunction)CD_open, METH_VARARGS},
- {"createparser", (PyCFunction)CD_createparser, METH_VARARGS},
- {"msftoframe", (PyCFunction)CD_msftoframe, METH_VARARGS},
- {NULL, NULL} /* Sentinel */
+ {"open", (PyCFunction)CD_open, METH_VARARGS},
+ {"createparser", (PyCFunction)CD_createparser, METH_VARARGS},
+ {"msftoframe", (PyCFunction)CD_msftoframe, METH_VARARGS},
+ {NULL, NULL} /* Sentinel */
};
void
initcd(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the cd module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("cd", CD_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
-
- CdError = PyErr_NewException("cd.error", NULL, NULL);
- PyDict_SetItemString(d, "error", CdError);
-
- /* Identifiers for the different types of callbacks from the parser */
- PyDict_SetItemString(d, "audio", PyInt_FromLong((long) cd_audio));
- PyDict_SetItemString(d, "pnum", PyInt_FromLong((long) cd_pnum));
- PyDict_SetItemString(d, "index", PyInt_FromLong((long) cd_index));
- PyDict_SetItemString(d, "ptime", PyInt_FromLong((long) cd_ptime));
- PyDict_SetItemString(d, "atime", PyInt_FromLong((long) cd_atime));
- PyDict_SetItemString(d, "catalog", PyInt_FromLong((long) cd_catalog));
- PyDict_SetItemString(d, "ident", PyInt_FromLong((long) cd_ident));
- PyDict_SetItemString(d, "control", PyInt_FromLong((long) cd_control));
-
- /* Block size information for digital audio data */
- PyDict_SetItemString(d, "DATASIZE",
- PyInt_FromLong((long) CDDA_DATASIZE));
- PyDict_SetItemString(d, "BLOCKSIZE",
- PyInt_FromLong((long) CDDA_BLOCKSIZE));
-
- /* Possible states for the cd player */
- PyDict_SetItemString(d, "ERROR", PyInt_FromLong((long) CD_ERROR));
- PyDict_SetItemString(d, "NODISC", PyInt_FromLong((long) CD_NODISC));
- PyDict_SetItemString(d, "READY", PyInt_FromLong((long) CD_READY));
- PyDict_SetItemString(d, "PLAYING", PyInt_FromLong((long) CD_PLAYING));
- PyDict_SetItemString(d, "PAUSED", PyInt_FromLong((long) CD_PAUSED));
- PyDict_SetItemString(d, "STILL", PyInt_FromLong((long) CD_STILL));
-#ifdef CD_CDROM /* only newer versions of the library */
- PyDict_SetItemString(d, "CDROM", PyInt_FromLong((long) CD_CDROM));
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the cd module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("cd", CD_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+
+ CdError = PyErr_NewException("cd.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", CdError);
+
+ /* Identifiers for the different types of callbacks from the parser */
+ PyDict_SetItemString(d, "audio", PyInt_FromLong((long) cd_audio));
+ PyDict_SetItemString(d, "pnum", PyInt_FromLong((long) cd_pnum));
+ PyDict_SetItemString(d, "index", PyInt_FromLong((long) cd_index));
+ PyDict_SetItemString(d, "ptime", PyInt_FromLong((long) cd_ptime));
+ PyDict_SetItemString(d, "atime", PyInt_FromLong((long) cd_atime));
+ PyDict_SetItemString(d, "catalog", PyInt_FromLong((long) cd_catalog));
+ PyDict_SetItemString(d, "ident", PyInt_FromLong((long) cd_ident));
+ PyDict_SetItemString(d, "control", PyInt_FromLong((long) cd_control));
+
+ /* Block size information for digital audio data */
+ PyDict_SetItemString(d, "DATASIZE",
+ PyInt_FromLong((long) CDDA_DATASIZE));
+ PyDict_SetItemString(d, "BLOCKSIZE",
+ PyInt_FromLong((long) CDDA_BLOCKSIZE));
+
+ /* Possible states for the cd player */
+ PyDict_SetItemString(d, "ERROR", PyInt_FromLong((long) CD_ERROR));
+ PyDict_SetItemString(d, "NODISC", PyInt_FromLong((long) CD_NODISC));
+ PyDict_SetItemString(d, "READY", PyInt_FromLong((long) CD_READY));
+ PyDict_SetItemString(d, "PLAYING", PyInt_FromLong((long) CD_PLAYING));
+ PyDict_SetItemString(d, "PAUSED", PyInt_FromLong((long) CD_PAUSED));
+ PyDict_SetItemString(d, "STILL", PyInt_FromLong((long) CD_STILL));
+#ifdef CD_CDROM /* only newer versions of the library */
+ PyDict_SetItemString(d, "CDROM", PyInt_FromLong((long) CD_CDROM));
#endif
}
diff --git a/Modules/cgensupport.c b/Modules/cgensupport.c
index 7e7d0ff..aad43a2 100644
--- a/Modules/cgensupport.c
+++ b/Modules/cgensupport.c
@@ -13,158 +13,158 @@
int
PyArg_GetObject(register PyObject *args, int nargs, int i, PyObject **p_arg)
{
- if (nargs != 1) {
- if (args == NULL || !PyTuple_Check(args) ||
- nargs != PyTuple_Size(args) ||
- i < 0 || i >= nargs) {
- return PyErr_BadArgument();
- }
- else {
- args = PyTuple_GetItem(args, i);
- }
- }
- if (args == NULL) {
- return PyErr_BadArgument();
- }
- *p_arg = args;
- return 1;
+ if (nargs != 1) {
+ if (args == NULL || !PyTuple_Check(args) ||
+ nargs != PyTuple_Size(args) ||
+ i < 0 || i >= nargs) {
+ return PyErr_BadArgument();
+ }
+ else {
+ args = PyTuple_GetItem(args, i);
+ }
+ }
+ if (args == NULL) {
+ return PyErr_BadArgument();
+ }
+ *p_arg = args;
+ return 1;
}
int
PyArg_GetLong(register PyObject *args, int nargs, int i, long *p_arg)
{
- if (nargs != 1) {
- if (args == NULL || !PyTuple_Check(args) ||
- nargs != PyTuple_Size(args) ||
- i < 0 || i >= nargs) {
- return PyErr_BadArgument();
- }
- args = PyTuple_GetItem(args, i);
- }
- if (args == NULL || !PyInt_Check(args)) {
- return PyErr_BadArgument();
- }
- *p_arg = PyInt_AsLong(args);
- return 1;
+ if (nargs != 1) {
+ if (args == NULL || !PyTuple_Check(args) ||
+ nargs != PyTuple_Size(args) ||
+ i < 0 || i >= nargs) {
+ return PyErr_BadArgument();
+ }
+ args = PyTuple_GetItem(args, i);
+ }
+ if (args == NULL || !PyInt_Check(args)) {
+ return PyErr_BadArgument();
+ }
+ *p_arg = PyInt_AsLong(args);
+ return 1;
}
int
PyArg_GetShort(register PyObject *args, int nargs, int i, short *p_arg)
{
- long x;
- if (!PyArg_GetLong(args, nargs, i, &x))
- return 0;
- *p_arg = (short) x;
- return 1;
+ long x;
+ if (!PyArg_GetLong(args, nargs, i, &x))
+ return 0;
+ *p_arg = (short) x;
+ return 1;
}
static int
extractdouble(register PyObject *v, double *p_arg)
{
- if (v == NULL) {
- /* Fall through to error return at end of function */
- }
- else if (PyFloat_Check(v)) {
- *p_arg = PyFloat_AS_DOUBLE((PyFloatObject *)v);
- return 1;
- }
- else if (PyInt_Check(v)) {
- *p_arg = PyInt_AS_LONG((PyIntObject *)v);
- return 1;
- }
- else if (PyLong_Check(v)) {
- *p_arg = PyLong_AsDouble(v);
- return 1;
- }
- return PyErr_BadArgument();
+ if (v == NULL) {
+ /* Fall through to error return at end of function */
+ }
+ else if (PyFloat_Check(v)) {
+ *p_arg = PyFloat_AS_DOUBLE((PyFloatObject *)v);
+ return 1;
+ }
+ else if (PyInt_Check(v)) {
+ *p_arg = PyInt_AS_LONG((PyIntObject *)v);
+ return 1;
+ }
+ else if (PyLong_Check(v)) {
+ *p_arg = PyLong_AsDouble(v);
+ return 1;
+ }
+ return PyErr_BadArgument();
}
static int
extractfloat(register PyObject *v, float *p_arg)
{
- if (v == NULL) {
- /* Fall through to error return at end of function */
- }
- else if (PyFloat_Check(v)) {
- *p_arg = (float) PyFloat_AS_DOUBLE((PyFloatObject *)v);
- return 1;
- }
- else if (PyInt_Check(v)) {
- *p_arg = (float) PyInt_AS_LONG((PyIntObject *)v);
- return 1;
- }
- else if (PyLong_Check(v)) {
- *p_arg = (float) PyLong_AsDouble(v);
- return 1;
- }
- return PyErr_BadArgument();
+ if (v == NULL) {
+ /* Fall through to error return at end of function */
+ }
+ else if (PyFloat_Check(v)) {
+ *p_arg = (float) PyFloat_AS_DOUBLE((PyFloatObject *)v);
+ return 1;
+ }
+ else if (PyInt_Check(v)) {
+ *p_arg = (float) PyInt_AS_LONG((PyIntObject *)v);
+ return 1;
+ }
+ else if (PyLong_Check(v)) {
+ *p_arg = (float) PyLong_AsDouble(v);
+ return 1;
+ }
+ return PyErr_BadArgument();
}
int
PyArg_GetFloat(register PyObject *args, int nargs, int i, float *p_arg)
{
- PyObject *v;
- float x;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (!extractfloat(v, &x))
- return 0;
- *p_arg = x;
- return 1;
+ PyObject *v;
+ float x;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (!extractfloat(v, &x))
+ return 0;
+ *p_arg = x;
+ return 1;
}
int
PyArg_GetString(PyObject *args, int nargs, int i, string *p_arg)
{
- PyObject *v;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (!PyString_Check(v)) {
- return PyErr_BadArgument();
- }
- *p_arg = PyString_AsString(v);
- return 1;
+ PyObject *v;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (!PyString_Check(v)) {
+ return PyErr_BadArgument();
+ }
+ *p_arg = PyString_AsString(v);
+ return 1;
}
int
PyArg_GetChar(PyObject *args, int nargs, int i, char *p_arg)
{
- string x;
- if (!PyArg_GetString(args, nargs, i, &x))
- return 0;
- if (x[0] == '\0' || x[1] != '\0') {
- /* Not exactly one char */
- return PyErr_BadArgument();
- }
- *p_arg = x[0];
- return 1;
+ string x;
+ if (!PyArg_GetString(args, nargs, i, &x))
+ return 0;
+ if (x[0] == '\0' || x[1] != '\0') {
+ /* Not exactly one char */
+ return PyErr_BadArgument();
+ }
+ *p_arg = x[0];
+ return 1;
}
int
PyArg_GetLongArraySize(PyObject *args, int nargs, int i, long *p_arg)
{
- PyObject *v;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- *p_arg = PyTuple_Size(v);
- return 1;
- }
- if (PyList_Check(v)) {
- *p_arg = PyList_Size(v);
- return 1;
- }
- return PyErr_BadArgument();
+ PyObject *v;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ *p_arg = PyTuple_Size(v);
+ return 1;
+ }
+ if (PyList_Check(v)) {
+ *p_arg = PyList_Size(v);
+ return 1;
+ }
+ return PyErr_BadArgument();
}
int
PyArg_GetShortArraySize(PyObject *args, int nargs, int i, short *p_arg)
{
- long x;
- if (!PyArg_GetLongArraySize(args, nargs, i, &x))
- return 0;
- *p_arg = (short) x;
- return 1;
+ long x;
+ if (!PyArg_GetLongArraySize(args, nargs, i, &x))
+ return 0;
+ *p_arg = (short) x;
+ return 1;
}
/* XXX The following four are too similar. Should share more code. */
@@ -172,139 +172,139 @@ PyArg_GetShortArraySize(PyObject *args, int nargs, int i, short *p_arg)
int
PyArg_GetLongArray(PyObject *args, int nargs, int i, int n, long *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = PyInt_AsLong(w);
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = PyInt_AsLong(w);
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
int
PyArg_GetShortArray(PyObject *args, int nargs, int i, int n, short *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = (short) PyInt_AsLong(w);
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!PyInt_Check(w)) {
- return PyErr_BadArgument();
- }
- p_arg[i] = (short) PyInt_AsLong(w);
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = (short) PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!PyInt_Check(w)) {
+ return PyErr_BadArgument();
+ }
+ p_arg[i] = (short) PyInt_AsLong(w);
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
int
PyArg_GetDoubleArray(PyObject *args, int nargs, int i, int n, double *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!extractdouble(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!extractdouble(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!extractdouble(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!extractdouble(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
int
PyArg_GetFloatArray(PyObject *args, int nargs, int i, int n, float *p_arg)
{
- PyObject *v, *w;
- if (!PyArg_GetObject(args, nargs, i, &v))
- return 0;
- if (PyTuple_Check(v)) {
- if (PyTuple_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyTuple_GetItem(v, i);
- if (!extractfloat(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else if (PyList_Check(v)) {
- if (PyList_Size(v) != n) {
- return PyErr_BadArgument();
- }
- for (i = 0; i < n; i++) {
- w = PyList_GetItem(v, i);
- if (!extractfloat(w, &p_arg[i]))
- return 0;
- }
- return 1;
- }
- else {
- return PyErr_BadArgument();
- }
+ PyObject *v, *w;
+ if (!PyArg_GetObject(args, nargs, i, &v))
+ return 0;
+ if (PyTuple_Check(v)) {
+ if (PyTuple_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyTuple_GetItem(v, i);
+ if (!extractfloat(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else if (PyList_Check(v)) {
+ if (PyList_Size(v) != n) {
+ return PyErr_BadArgument();
+ }
+ for (i = 0; i < n; i++) {
+ w = PyList_GetItem(v, i);
+ if (!extractfloat(w, &p_arg[i]))
+ return 0;
+ }
+ return 1;
+ }
+ else {
+ return PyErr_BadArgument();
+ }
}
diff --git a/Modules/cgensupport.h b/Modules/cgensupport.h
index bc901f6..27e1261 100644
--- a/Modules/cgensupport.h
+++ b/Modules/cgensupport.h
@@ -30,33 +30,33 @@ typedef char *string;
#define getistringarg PyArg_GetString
extern int PyArg_GetObject(PyObject *args, int nargs,
- int i, PyObject **p_a);
+ int i, PyObject **p_a);
extern int PyArg_GetLong(PyObject *args, int nargs,
- int i, long *p_a);
+ int i, long *p_a);
extern int PyArg_GetShort(PyObject *args, int nargs,
- int i, short *p_a);
+ int i, short *p_a);
extern int PyArg_GetFloat(PyObject *args, int nargs,
- int i, float *p_a);
+ int i, float *p_a);
extern int PyArg_GetString(PyObject *args, int nargs,
- int i, string *p_a);
+ int i, string *p_a);
extern int PyArg_GetChar(PyObject *args, int nargs,
- int i, char *p_a);
+ int i, char *p_a);
extern int PyArg_GetLongArray(PyObject *args, int nargs,
- int i, int n, long *p_a);
+ int i, int n, long *p_a);
extern int PyArg_GetShortArray(PyObject *args, int nargs,
- int i, int n, short *p_a);
+ int i, int n, short *p_a);
extern int PyArg_GetDoubleArray(PyObject *args, int nargs,
- int i, int n, double *p_a);
+ int i, int n, double *p_a);
extern int PyArg_GetFloatArray(PyObject *args, int nargs,
- int i, int n, float *p_a);
+ int i, int n, float *p_a);
extern int PyArg_GetLongArraySize(PyObject *args, int nargs,
- int i, long *p_a);
+ int i, long *p_a);
extern int PyArg_GetShortArraySize(PyObject *args, int nargs,
- int i, short *p_a);
+ int i, short *p_a);
extern int PyArg_GetDoubleArraySize(PyObject *args, int nargs,
- int i, double *p_a);
+ int i, double *p_a);
extern int PyArg_GetFloatArraySize(PyObject *args, int nargs,
- int i, float *p_a);
+ int i, float *p_a);
#ifdef __cplusplus
}
diff --git a/Modules/cjkcodecs/_codecs_cn.c b/Modules/cjkcodecs/_codecs_cn.c
index 4542ce6..ab4e659 100644
--- a/Modules/cjkcodecs/_codecs_cn.c
+++ b/Modules/cjkcodecs/_codecs_cn.c
@@ -17,24 +17,24 @@
/* GBK and GB2312 map differently in few codepoints that are listed below:
*
- * gb2312 gbk
- * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT
- * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH
- * A844 undefined U+2015 HORIZONTAL BAR
+ * gb2312 gbk
+ * A1A4 U+30FB KATAKANA MIDDLE DOT U+00B7 MIDDLE DOT
+ * A1AA U+2015 HORIZONTAL BAR U+2014 EM DASH
+ * A844 undefined U+2015 HORIZONTAL BAR
*/
#define GBK_DECODE(dc1, dc2, assi) \
- if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \
- else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \
- else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \
- else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \
- else TRYMAP_DEC(gbkext, assi, dc1, dc2);
+ if ((dc1) == 0xa1 && (dc2) == 0xaa) (assi) = 0x2014; \
+ else if ((dc1) == 0xa8 && (dc2) == 0x44) (assi) = 0x2015; \
+ else if ((dc1) == 0xa1 && (dc2) == 0xa4) (assi) = 0x00b7; \
+ else TRYMAP_DEC(gb2312, assi, dc1 ^ 0x80, dc2 ^ 0x80); \
+ else TRYMAP_DEC(gbkext, assi, dc1, dc2);
#define GBK_ENCODE(code, assi) \
- if ((code) == 0x2014) (assi) = 0xa1aa; \
- else if ((code) == 0x2015) (assi) = 0xa844; \
- else if ((code) == 0x00b7) (assi) = 0xa1a4; \
- else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code));
+ if ((code) == 0x2014) (assi) = 0xa1aa; \
+ else if ((code) == 0x2015) (assi) = 0xa844; \
+ else if ((code) == 0x00b7) (assi) = 0xa1a4; \
+ else if ((code) != 0x30fb && TRYMAP_ENC_COND(gbcommon, assi, code));
/*
* GB2312 codec
@@ -42,53 +42,53 @@
ENCODER(gb2312)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(gbcommon, code, c);
- else return 1;
-
- if (code & 0x8000) /* MSB set: GBK */
- return 1;
-
- OUT1((code >> 8) | 0x80)
- OUT2((code & 0xFF) | 0x80)
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(gbcommon, code, c);
+ else return 1;
+
+ if (code & 0x8000) /* MSB set: GBK */
+ return 1;
+
+ OUT1((code >> 8) | 0x80)
+ OUT2((code & 0xFF) | 0x80)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(gb2312)
{
- while (inleft > 0) {
- unsigned char c = **inbuf;
+ while (inleft > 0) {
+ unsigned char c = **inbuf;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
- TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
- NEXT(2, 1)
- }
- else return 2;
- }
+ REQUIRE_INBUF(2)
+ TRYMAP_DEC(gb2312, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
+ NEXT(2, 1)
+ }
+ else return 2;
+ }
- return 0;
+ return 0;
}
@@ -98,55 +98,55 @@ DECODER(gb2312)
ENCODER(gbk)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
-
- GBK_ENCODE(c, code)
- else return 1;
-
- OUT1((code >> 8) | 0x80)
- if (code & 0x8000)
- OUT2((code & 0xFF)) /* MSB set: GBK */
- else
- OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+
+ GBK_ENCODE(c, code)
+ else return 1;
+
+ OUT1((code >> 8) | 0x80)
+ if (code & 0x8000)
+ OUT2((code & 0xFF)) /* MSB set: GBK */
+ else
+ OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(gbk)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
+ REQUIRE_INBUF(2)
- GBK_DECODE(c, IN2, **outbuf)
- else return 2;
+ GBK_DECODE(c, IN2, **outbuf)
+ else return 2;
- NEXT(2, 1)
- }
+ NEXT(2, 1)
+ }
- return 0;
+ return 0;
}
@@ -156,153 +156,153 @@ DECODER(gbk)
ENCODER(gb18030)
{
- while (inleft > 0) {
- ucs4_t c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1(c)
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- if (c > 0x10FFFF)
+ while (inleft > 0) {
+ ucs4_t c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ if (c > 0x10FFFF)
#if Py_UNICODE_SIZE == 2
- return 2; /* surrogates pair */
+ return 2; /* surrogates pair */
#else
- return 1;
+ return 1;
#endif
- else if (c >= 0x10000) {
- ucs4_t tc = c - 0x10000;
+ else if (c >= 0x10000) {
+ ucs4_t tc = c - 0x10000;
- REQUIRE_OUTBUF(4)
+ REQUIRE_OUTBUF(4)
- OUT4((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT3((unsigned char)(tc % 126) + 0x81)
- tc /= 126;
- OUT2((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT1((unsigned char)(tc + 0x90))
+ OUT4((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT3((unsigned char)(tc % 126) + 0x81)
+ tc /= 126;
+ OUT2((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT1((unsigned char)(tc + 0x90))
#if Py_UNICODE_SIZE == 2
- NEXT(2, 4) /* surrogates pair */
+ NEXT(2, 4) /* surrogates pair */
#else
- NEXT(1, 4)
+ NEXT(1, 4)
#endif
- continue;
- }
-
- REQUIRE_OUTBUF(2)
-
- GBK_ENCODE(c, code)
- else TRYMAP_ENC(gb18030ext, code, c);
- else {
- const struct _gb18030_to_unibmp_ranges *utrrange;
-
- REQUIRE_OUTBUF(4)
-
- for (utrrange = gb18030_to_unibmp_ranges;
- utrrange->first != 0;
- utrrange++)
- if (utrrange->first <= c &&
- c <= utrrange->last) {
- Py_UNICODE tc;
-
- tc = c - utrrange->first +
- utrrange->base;
-
- OUT4((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT3((unsigned char)(tc % 126) + 0x81)
- tc /= 126;
- OUT2((unsigned char)(tc % 10) + 0x30)
- tc /= 10;
- OUT1((unsigned char)tc + 0x81)
-
- NEXT(1, 4)
- break;
- }
-
- if (utrrange->first == 0)
- return 1;
- continue;
- }
-
- OUT1((code >> 8) | 0x80)
- if (code & 0x8000)
- OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */
- else
- OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
-
- NEXT(1, 2)
- }
-
- return 0;
+ continue;
+ }
+
+ REQUIRE_OUTBUF(2)
+
+ GBK_ENCODE(c, code)
+ else TRYMAP_ENC(gb18030ext, code, c);
+ else {
+ const struct _gb18030_to_unibmp_ranges *utrrange;
+
+ REQUIRE_OUTBUF(4)
+
+ for (utrrange = gb18030_to_unibmp_ranges;
+ utrrange->first != 0;
+ utrrange++)
+ if (utrrange->first <= c &&
+ c <= utrrange->last) {
+ Py_UNICODE tc;
+
+ tc = c - utrrange->first +
+ utrrange->base;
+
+ OUT4((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT3((unsigned char)(tc % 126) + 0x81)
+ tc /= 126;
+ OUT2((unsigned char)(tc % 10) + 0x30)
+ tc /= 10;
+ OUT1((unsigned char)tc + 0x81)
+
+ NEXT(1, 4)
+ break;
+ }
+
+ if (utrrange->first == 0)
+ return 1;
+ continue;
+ }
+
+ OUT1((code >> 8) | 0x80)
+ if (code & 0x8000)
+ OUT2((code & 0xFF)) /* MSB set: GBK or GB18030ext */
+ else
+ OUT2((code & 0xFF) | 0x80) /* MSB unset: GB2312 */
+
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(gb18030)
{
- while (inleft > 0) {
- unsigned char c = IN1, c2;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
-
- c2 = IN2;
- if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */
- const struct _gb18030_to_unibmp_ranges *utr;
- unsigned char c3, c4;
- ucs4_t lseq;
-
- REQUIRE_INBUF(4)
- c3 = IN3;
- c4 = IN4;
- if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39)
- return 4;
- c -= 0x81; c2 -= 0x30;
- c3 -= 0x81; c4 -= 0x30;
-
- if (c < 4) { /* U+0080 - U+FFFF */
- lseq = ((ucs4_t)c * 10 + c2) * 1260 +
- (ucs4_t)c3 * 10 + c4;
- if (lseq < 39420) {
- for (utr = gb18030_to_unibmp_ranges;
- lseq >= (utr + 1)->base;
- utr++) ;
- OUT1(utr->first - utr->base + lseq)
- NEXT(4, 1)
- continue;
- }
- }
- else if (c >= 15) { /* U+10000 - U+10FFFF */
- lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2)
- * 1260 + (ucs4_t)c3 * 10 + c4;
- if (lseq <= 0x10FFFF) {
- WRITEUCS4(lseq);
- NEXT_IN(4)
- continue;
- }
- }
- return 4;
- }
-
- GBK_DECODE(c, c2, **outbuf)
- else TRYMAP_DEC(gb18030ext, **outbuf, c, c2);
- else return 2;
-
- NEXT(2, 1)
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1, c2;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+
+ c2 = IN2;
+ if (c2 >= 0x30 && c2 <= 0x39) { /* 4 bytes seq */
+ const struct _gb18030_to_unibmp_ranges *utr;
+ unsigned char c3, c4;
+ ucs4_t lseq;
+
+ REQUIRE_INBUF(4)
+ c3 = IN3;
+ c4 = IN4;
+ if (c < 0x81 || c3 < 0x81 || c4 < 0x30 || c4 > 0x39)
+ return 4;
+ c -= 0x81; c2 -= 0x30;
+ c3 -= 0x81; c4 -= 0x30;
+
+ if (c < 4) { /* U+0080 - U+FFFF */
+ lseq = ((ucs4_t)c * 10 + c2) * 1260 +
+ (ucs4_t)c3 * 10 + c4;
+ if (lseq < 39420) {
+ for (utr = gb18030_to_unibmp_ranges;
+ lseq >= (utr + 1)->base;
+ utr++) ;
+ OUT1(utr->first - utr->base + lseq)
+ NEXT(4, 1)
+ continue;
+ }
+ }
+ else if (c >= 15) { /* U+10000 - U+10FFFF */
+ lseq = 0x10000 + (((ucs4_t)c-15) * 10 + c2)
+ * 1260 + (ucs4_t)c3 * 10 + c4;
+ if (lseq <= 0x10FFFF) {
+ WRITEUCS4(lseq);
+ NEXT_IN(4)
+ continue;
+ }
+ }
+ return 4;
+ }
+
+ GBK_DECODE(c, c2, **outbuf)
+ else TRYMAP_DEC(gb18030ext, **outbuf, c, c2);
+ else return 2;
+
+ NEXT(2, 1)
+ }
+
+ return 0;
}
@@ -312,118 +312,118 @@ DECODER(gb18030)
ENCODER_INIT(hz)
{
- state->i = 0;
- return 0;
+ state->i = 0;
+ return 0;
}
ENCODER_RESET(hz)
{
- if (state->i != 0) {
- WRITE2('~', '}')
- state->i = 0;
- NEXT_OUT(2)
- }
- return 0;
+ if (state->i != 0) {
+ WRITE2('~', '}')
+ state->i = 0;
+ NEXT_OUT(2)
+ }
+ return 0;
}
ENCODER(hz)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- if (state->i == 0) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- }
- else {
- WRITE3('~', '}', (unsigned char)c)
- NEXT(1, 3)
- state->i = 0;
- }
- continue;
- }
-
- UCS4INVALID(c)
-
- TRYMAP_ENC(gbcommon, code, c);
- else return 1;
-
- if (code & 0x8000) /* MSB set: GBK */
- return 1;
-
- if (state->i == 0) {
- WRITE4('~', '{', code >> 8, code & 0xff)
- NEXT(1, 4)
- state->i = 1;
- }
- else {
- WRITE2(code >> 8, code & 0xff)
- NEXT(1, 2)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ if (state->i == 0) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ }
+ else {
+ WRITE3('~', '}', (unsigned char)c)
+ NEXT(1, 3)
+ state->i = 0;
+ }
+ continue;
+ }
+
+ UCS4INVALID(c)
+
+ TRYMAP_ENC(gbcommon, code, c);
+ else return 1;
+
+ if (code & 0x8000) /* MSB set: GBK */
+ return 1;
+
+ if (state->i == 0) {
+ WRITE4('~', '{', code >> 8, code & 0xff)
+ NEXT(1, 4)
+ state->i = 1;
+ }
+ else {
+ WRITE2(code >> 8, code & 0xff)
+ NEXT(1, 2)
+ }
+ }
+
+ return 0;
}
DECODER_INIT(hz)
{
- state->i = 0;
- return 0;
+ state->i = 0;
+ return 0;
}
DECODER_RESET(hz)
{
- state->i = 0;
- return 0;
+ state->i = 0;
+ return 0;
}
DECODER(hz)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- if (c == '~') {
- unsigned char c2 = IN2;
-
- REQUIRE_INBUF(2)
- if (c2 == '~') {
- WRITE1('~')
- NEXT(2, 1)
- continue;
- }
- else if (c2 == '{' && state->i == 0)
- state->i = 1; /* set GB */
- else if (c2 == '}' && state->i == 1)
- state->i = 0; /* set ASCII */
- else if (c2 == '\n')
- ; /* line-continuation */
- else
- return 2;
- NEXT(2, 0);
- continue;
- }
-
- if (c & 0x80)
- return 1;
-
- if (state->i == 0) { /* ASCII mode */
- WRITE1(c)
- NEXT(1, 1)
- }
- else { /* GB mode */
- REQUIRE_INBUF(2)
- REQUIRE_OUTBUF(1)
- TRYMAP_DEC(gb2312, **outbuf, c, IN2) {
- NEXT(2, 1)
- }
- else
- return 2;
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ if (c == '~') {
+ unsigned char c2 = IN2;
+
+ REQUIRE_INBUF(2)
+ if (c2 == '~') {
+ WRITE1('~')
+ NEXT(2, 1)
+ continue;
+ }
+ else if (c2 == '{' && state->i == 0)
+ state->i = 1; /* set GB */
+ else if (c2 == '}' && state->i == 1)
+ state->i = 0; /* set ASCII */
+ else if (c2 == '\n')
+ ; /* line-continuation */
+ else
+ return 2;
+ NEXT(2, 0);
+ continue;
+ }
+
+ if (c & 0x80)
+ return 1;
+
+ if (state->i == 0) { /* ASCII mode */
+ WRITE1(c)
+ NEXT(1, 1)
+ }
+ else { /* GB mode */
+ REQUIRE_INBUF(2)
+ REQUIRE_OUTBUF(1)
+ TRYMAP_DEC(gb2312, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+ }
+
+ return 0;
}
diff --git a/Modules/cjkcodecs/_codecs_hk.c b/Modules/cjkcodecs/_codecs_hk.c
index 4bbd622..aaf103d 100644
--- a/Modules/cjkcodecs/_codecs_hk.c
+++ b/Modules/cjkcodecs/_codecs_hk.c
@@ -18,12 +18,12 @@ static const decode_map *big5_decmap = NULL;
CODEC_INIT(big5hkscs)
{
- static int initialized = 0;
+ static int initialized = 0;
- if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap))
- return -1;
- initialized = 1;
- return 0;
+ if (!initialized && IMPORT_MAP(tw, big5, &big5_encmap, &big5_decmap))
+ return -1;
+ initialized = 1;
+ return 0;
}
/*
@@ -38,135 +38,135 @@ static const DBCHAR big5hkscs_pairenc_table[4] = {0x8862, 0x8864, 0x88a3, 0x88a5
ENCODER(big5hkscs)
{
- while (inleft > 0) {
- ucs4_t c = **inbuf;
- DBCHAR code;
- Py_ssize_t insize;
-
- if (c < 0x80) {
- REQUIRE_OUTBUF(1)
- **outbuf = (unsigned char)c;
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- insize = GET_INSIZE(c);
-
- REQUIRE_OUTBUF(2)
-
- if (c < 0x10000) {
- TRYMAP_ENC(big5hkscs_bmp, code, c) {
- if (code == MULTIC) {
- if (inleft >= 2 &&
- ((c & 0xffdf) == 0x00ca) &&
- (((*inbuf)[1] & 0xfff7) == 0x0304)) {
- code = big5hkscs_pairenc_table[
- ((c >> 4) |
- ((*inbuf)[1] >> 3)) & 3];
- insize = 2;
- }
- else if (inleft < 2 &&
- !(flags & MBENC_FLUSH))
- return MBERR_TOOFEW;
- else {
- if (c == 0xca)
- code = 0x8866;
- else /* c == 0xea */
- code = 0x88a7;
- }
- }
- }
- else TRYMAP_ENC(big5, code, c);
- else return 1;
- }
- else if (c < 0x20000)
- return insize;
- else if (c < 0x30000) {
- TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff);
- else return insize;
- }
- else
- return insize;
-
- OUT1(code >> 8)
- OUT2(code & 0xFF)
- NEXT(insize, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ ucs4_t c = **inbuf;
+ DBCHAR code;
+ Py_ssize_t insize;
+
+ if (c < 0x80) {
+ REQUIRE_OUTBUF(1)
+ **outbuf = (unsigned char)c;
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ insize = GET_INSIZE(c);
+
+ REQUIRE_OUTBUF(2)
+
+ if (c < 0x10000) {
+ TRYMAP_ENC(big5hkscs_bmp, code, c) {
+ if (code == MULTIC) {
+ if (inleft >= 2 &&
+ ((c & 0xffdf) == 0x00ca) &&
+ (((*inbuf)[1] & 0xfff7) == 0x0304)) {
+ code = big5hkscs_pairenc_table[
+ ((c >> 4) |
+ ((*inbuf)[1] >> 3)) & 3];
+ insize = 2;
+ }
+ else if (inleft < 2 &&
+ !(flags & MBENC_FLUSH))
+ return MBERR_TOOFEW;
+ else {
+ if (c == 0xca)
+ code = 0x8866;
+ else /* c == 0xea */
+ code = 0x88a7;
+ }
+ }
+ }
+ else TRYMAP_ENC(big5, code, c);
+ else return 1;
+ }
+ else if (c < 0x20000)
+ return insize;
+ else if (c < 0x30000) {
+ TRYMAP_ENC(big5hkscs_nonbmp, code, c & 0xffff);
+ else return insize;
+ }
+ else
+ return insize;
+
+ OUT1(code >> 8)
+ OUT2(code & 0xFF)
+ NEXT(insize, 2)
+ }
+
+ return 0;
}
#define BH2S(c1, c2) (((c1) - 0x87) * (0xfe - 0x40 + 1) + ((c2) - 0x40))
DECODER(big5hkscs)
{
- while (inleft > 0) {
- unsigned char c = IN1;
- ucs4_t decoded;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
-
- if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
- goto hkscsdec;
-
- TRYMAP_DEC(big5, **outbuf, c, IN2) {
- NEXT(2, 1)
- }
- else
-hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
- int s = BH2S(c, IN2);
- const unsigned char *hintbase;
-
- assert(0x87 <= c && c <= 0xfe);
- assert(0x40 <= IN2 && IN2 <= 0xfe);
-
- if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
- hintbase = big5hkscs_phint_0;
- s -= BH2S(0x87, 0x40);
- }
- else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
- hintbase = big5hkscs_phint_12130;
- s -= BH2S(0xc6, 0xa1);
- }
- else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
- hintbase = big5hkscs_phint_21924;
- s -= BH2S(0xf9, 0xd6);
- }
- else
- return MBERR_INTERNAL;
-
- if (hintbase[s >> 3] & (1 << (s & 7))) {
- WRITEUCS4(decoded | 0x20000)
- NEXT_IN(2)
- }
- else {
- OUT1(decoded)
- NEXT(2, 1)
- }
- }
- else {
- switch ((c << 8) | IN2) {
- case 0x8862: WRITE2(0x00ca, 0x0304); break;
- case 0x8864: WRITE2(0x00ca, 0x030c); break;
- case 0x88a3: WRITE2(0x00ea, 0x0304); break;
- case 0x88a5: WRITE2(0x00ea, 0x030c); break;
- default: return 2;
- }
-
- NEXT(2, 2) /* all decoded codepoints are pairs, above. */
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+ ucs4_t decoded;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+
+ if (0xc6 <= c && c <= 0xc8 && (c >= 0xc7 || IN2 >= 0xa1))
+ goto hkscsdec;
+
+ TRYMAP_DEC(big5, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ }
+ else
+hkscsdec: TRYMAP_DEC(big5hkscs, decoded, c, IN2) {
+ int s = BH2S(c, IN2);
+ const unsigned char *hintbase;
+
+ assert(0x87 <= c && c <= 0xfe);
+ assert(0x40 <= IN2 && IN2 <= 0xfe);
+
+ if (BH2S(0x87, 0x40) <= s && s <= BH2S(0xa0, 0xfe)) {
+ hintbase = big5hkscs_phint_0;
+ s -= BH2S(0x87, 0x40);
+ }
+ else if (BH2S(0xc6,0xa1) <= s && s <= BH2S(0xc8,0xfe)){
+ hintbase = big5hkscs_phint_12130;
+ s -= BH2S(0xc6, 0xa1);
+ }
+ else if (BH2S(0xf9,0xd6) <= s && s <= BH2S(0xfe,0xfe)){
+ hintbase = big5hkscs_phint_21924;
+ s -= BH2S(0xf9, 0xd6);
+ }
+ else
+ return MBERR_INTERNAL;
+
+ if (hintbase[s >> 3] & (1 << (s & 7))) {
+ WRITEUCS4(decoded | 0x20000)
+ NEXT_IN(2)
+ }
+ else {
+ OUT1(decoded)
+ NEXT(2, 1)
+ }
+ }
+ else {
+ switch ((c << 8) | IN2) {
+ case 0x8862: WRITE2(0x00ca, 0x0304); break;
+ case 0x8864: WRITE2(0x00ca, 0x030c); break;
+ case 0x88a3: WRITE2(0x00ea, 0x0304); break;
+ case 0x88a5: WRITE2(0x00ea, 0x030c); break;
+ default: return 2;
+ }
+
+ NEXT(2, 2) /* all decoded codepoints are pairs, above. */
+ }
+ }
+
+ return 0;
}
diff --git a/Modules/cjkcodecs/_codecs_iso2022.c b/Modules/cjkcodecs/_codecs_iso2022.c
index 9ce7b75..25c1a36 100644
--- a/Modules/cjkcodecs/_codecs_iso2022.c
+++ b/Modules/cjkcodecs/_codecs_iso2022.c
@@ -19,85 +19,85 @@
state->c[0-3]
- 00000000
- ||^^^^^|
- |+-----+---- G0-3 Character Set
- +----------- Is G0-3 double byte?
+ 00000000
+ ||^^^^^|
+ |+-----+---- G0-3 Character Set
+ +----------- Is G0-3 double byte?
state->c[4]
- 00000000
- ||
- |+---- Locked-Shift?
- +----- ESC Throughout
+ 00000000
+ ||
+ |+---- Locked-Shift?
+ +----- ESC Throughout
*/
-#define ESC 0x1B
-#define SO 0x0E
-#define SI 0x0F
-#define LF 0x0A
-
-#define MAX_ESCSEQLEN 16
-
-#define CHARSET_ISO8859_1 'A'
-#define CHARSET_ASCII 'B'
-#define CHARSET_ISO8859_7 'F'
-#define CHARSET_JISX0201_K 'I'
-#define CHARSET_JISX0201_R 'J'
-
-#define CHARSET_GB2312 ('A'|CHARSET_DBCS)
-#define CHARSET_JISX0208 ('B'|CHARSET_DBCS)
-#define CHARSET_KSX1001 ('C'|CHARSET_DBCS)
-#define CHARSET_JISX0212 ('D'|CHARSET_DBCS)
-#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS)
-#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS)
-#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS)
-#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS)
-#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS)
-#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS)
-#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS)
-
-#define CHARSET_DBCS 0x80
-#define ESCMARK(mark) ((mark) & 0x7f)
-
-#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@')
+#define ESC 0x1B
+#define SO 0x0E
+#define SI 0x0F
+#define LF 0x0A
+
+#define MAX_ESCSEQLEN 16
+
+#define CHARSET_ISO8859_1 'A'
+#define CHARSET_ASCII 'B'
+#define CHARSET_ISO8859_7 'F'
+#define CHARSET_JISX0201_K 'I'
+#define CHARSET_JISX0201_R 'J'
+
+#define CHARSET_GB2312 ('A'|CHARSET_DBCS)
+#define CHARSET_JISX0208 ('B'|CHARSET_DBCS)
+#define CHARSET_KSX1001 ('C'|CHARSET_DBCS)
+#define CHARSET_JISX0212 ('D'|CHARSET_DBCS)
+#define CHARSET_GB2312_8565 ('E'|CHARSET_DBCS)
+#define CHARSET_CNS11643_1 ('G'|CHARSET_DBCS)
+#define CHARSET_CNS11643_2 ('H'|CHARSET_DBCS)
+#define CHARSET_JISX0213_2000_1 ('O'|CHARSET_DBCS)
+#define CHARSET_JISX0213_2 ('P'|CHARSET_DBCS)
+#define CHARSET_JISX0213_2004_1 ('Q'|CHARSET_DBCS)
+#define CHARSET_JISX0208_O ('@'|CHARSET_DBCS)
+
+#define CHARSET_DBCS 0x80
+#define ESCMARK(mark) ((mark) & 0x7f)
+
+#define IS_ESCEND(c) (((c) >= 'A' && (c) <= 'Z') || (c) == '@')
#define IS_ISO2022ESC(c2) \
- ((c2) == '(' || (c2) == ')' || (c2) == '$' || \
- (c2) == '.' || (c2) == '&')
- /* this is not a complete list of ISO-2022 escape sequence headers.
- * but, it's enough to implement CJK instances of iso-2022. */
-
-#define MAP_UNMAPPABLE 0xFFFF
-#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */
-
-#define F_SHIFTED 0x01
-#define F_ESCTHROUGHOUT 0x02
-
-#define STATE_SETG(dn, v) ((state)->c[dn]) = (v);
-#define STATE_GETG(dn) ((state)->c[dn])
-
-#define STATE_G0 STATE_GETG(0)
-#define STATE_G1 STATE_GETG(1)
-#define STATE_G2 STATE_GETG(2)
-#define STATE_G3 STATE_GETG(3)
-#define STATE_SETG0(v) STATE_SETG(0, v)
-#define STATE_SETG1(v) STATE_SETG(1, v)
-#define STATE_SETG2(v) STATE_SETG(2, v)
-#define STATE_SETG3(v) STATE_SETG(3, v)
-
-#define STATE_SETFLAG(f) ((state)->c[4]) |= (f);
-#define STATE_GETFLAG(f) ((state)->c[4] & (f))
-#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f);
-#define STATE_CLEARFLAGS() ((state)->c[4]) = 0;
-
-#define ISO2022_CONFIG ((const struct iso2022_config *)config)
-#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag))
-#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations)
+ ((c2) == '(' || (c2) == ')' || (c2) == '$' || \
+ (c2) == '.' || (c2) == '&')
+ /* this is not a complete list of ISO-2022 escape sequence headers.
+ * but, it's enough to implement CJK instances of iso-2022. */
+
+#define MAP_UNMAPPABLE 0xFFFF
+#define MAP_MULTIPLE_AVAIL 0xFFFE /* for JIS X 0213 */
+
+#define F_SHIFTED 0x01
+#define F_ESCTHROUGHOUT 0x02
+
+#define STATE_SETG(dn, v) ((state)->c[dn]) = (v);
+#define STATE_GETG(dn) ((state)->c[dn])
+
+#define STATE_G0 STATE_GETG(0)
+#define STATE_G1 STATE_GETG(1)
+#define STATE_G2 STATE_GETG(2)
+#define STATE_G3 STATE_GETG(3)
+#define STATE_SETG0(v) STATE_SETG(0, v)
+#define STATE_SETG1(v) STATE_SETG(1, v)
+#define STATE_SETG2(v) STATE_SETG(2, v)
+#define STATE_SETG3(v) STATE_SETG(3, v)
+
+#define STATE_SETFLAG(f) ((state)->c[4]) |= (f);
+#define STATE_GETFLAG(f) ((state)->c[4] & (f))
+#define STATE_CLEARFLAG(f) ((state)->c[4]) &= ~(f);
+#define STATE_CLEARFLAGS() ((state)->c[4]) = 0;
+
+#define ISO2022_CONFIG ((const struct iso2022_config *)config)
+#define CONFIG_ISSET(flag) (ISO2022_CONFIG->flags & (flag))
+#define CONFIG_DESIGNATIONS (ISO2022_CONFIG->designations)
/* iso2022_config.flags */
-#define NO_SHIFT 0x01
-#define USE_G2 0x02
-#define USE_JISX0208_EXT 0x04
+#define NO_SHIFT 0x01
+#define USE_G2 0x02
+#define USE_JISX0208_EXT 0x04
/*-*- internal data structures -*-*/
@@ -106,434 +106,434 @@ typedef ucs4_t (*iso2022_decode_func)(const unsigned char *data);
typedef DBCHAR (*iso2022_encode_func)(const ucs4_t *data, Py_ssize_t *length);
struct iso2022_designation {
- unsigned char mark;
- unsigned char plane;
- unsigned char width;
- iso2022_init_func initializer;
- iso2022_decode_func decoder;
- iso2022_encode_func encoder;
+ unsigned char mark;
+ unsigned char plane;
+ unsigned char width;
+ iso2022_init_func initializer;
+ iso2022_decode_func decoder;
+ iso2022_encode_func encoder;
};
struct iso2022_config {
- int flags;
- const struct iso2022_designation *designations; /* non-ascii desigs */
+ int flags;
+ const struct iso2022_designation *designations; /* non-ascii desigs */
};
/*-*- iso-2022 codec implementation -*-*/
CODEC_INIT(iso2022)
{
- const struct iso2022_designation *desig = CONFIG_DESIGNATIONS;
- for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++)
- if (desig->initializer != NULL && desig->initializer() != 0)
- return -1;
- return 0;
+ const struct iso2022_designation *desig = CONFIG_DESIGNATIONS;
+ for (desig = CONFIG_DESIGNATIONS; desig->mark; desig++)
+ if (desig->initializer != NULL && desig->initializer() != 0)
+ return -1;
+ return 0;
}
ENCODER_INIT(iso2022)
{
- STATE_CLEARFLAGS()
- STATE_SETG0(CHARSET_ASCII)
- STATE_SETG1(CHARSET_ASCII)
- return 0;
+ STATE_CLEARFLAGS()
+ STATE_SETG0(CHARSET_ASCII)
+ STATE_SETG1(CHARSET_ASCII)
+ return 0;
}
ENCODER_RESET(iso2022)
{
- if (STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SI)
- NEXT_OUT(1)
- STATE_CLEARFLAG(F_SHIFTED)
- }
- if (STATE_G0 != CHARSET_ASCII) {
- WRITE3(ESC, '(', 'B')
- NEXT_OUT(3)
- STATE_SETG0(CHARSET_ASCII)
- }
- return 0;
+ if (STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SI)
+ NEXT_OUT(1)
+ STATE_CLEARFLAG(F_SHIFTED)
+ }
+ if (STATE_G0 != CHARSET_ASCII) {
+ WRITE3(ESC, '(', 'B')
+ NEXT_OUT(3)
+ STATE_SETG0(CHARSET_ASCII)
+ }
+ return 0;
}
ENCODER(iso2022)
{
- while (inleft > 0) {
- const struct iso2022_designation *dsg;
- DBCHAR encoded;
- ucs4_t c = **inbuf;
- Py_ssize_t insize;
-
- if (c < 0x80) {
- if (STATE_G0 != CHARSET_ASCII) {
- WRITE3(ESC, '(', 'B')
- STATE_SETG0(CHARSET_ASCII)
- NEXT_OUT(3)
- }
- if (STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SI)
- STATE_CLEARFLAG(F_SHIFTED)
- NEXT_OUT(1)
- }
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- insize = GET_INSIZE(c);
-
- encoded = MAP_UNMAPPABLE;
- for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) {
- Py_ssize_t length = 1;
- encoded = dsg->encoder(&c, &length);
- if (encoded == MAP_MULTIPLE_AVAIL) {
- /* this implementation won't work for pair
- * of non-bmp characters. */
- if (inleft < 2) {
- if (!(flags & MBENC_FLUSH))
- return MBERR_TOOFEW;
- length = -1;
- }
- else
- length = 2;
+ while (inleft > 0) {
+ const struct iso2022_designation *dsg;
+ DBCHAR encoded;
+ ucs4_t c = **inbuf;
+ Py_ssize_t insize;
+
+ if (c < 0x80) {
+ if (STATE_G0 != CHARSET_ASCII) {
+ WRITE3(ESC, '(', 'B')
+ STATE_SETG0(CHARSET_ASCII)
+ NEXT_OUT(3)
+ }
+ if (STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SI)
+ STATE_CLEARFLAG(F_SHIFTED)
+ NEXT_OUT(1)
+ }
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ insize = GET_INSIZE(c);
+
+ encoded = MAP_UNMAPPABLE;
+ for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++) {
+ Py_ssize_t length = 1;
+ encoded = dsg->encoder(&c, &length);
+ if (encoded == MAP_MULTIPLE_AVAIL) {
+ /* this implementation won't work for pair
+ * of non-bmp characters. */
+ if (inleft < 2) {
+ if (!(flags & MBENC_FLUSH))
+ return MBERR_TOOFEW;
+ length = -1;
+ }
+ else
+ length = 2;
#if Py_UNICODE_SIZE == 2
- if (length == 2) {
- ucs4_t u4in[2];
- u4in[0] = (ucs4_t)IN1;
- u4in[1] = (ucs4_t)IN2;
- encoded = dsg->encoder(u4in, &length);
- } else
- encoded = dsg->encoder(&c, &length);
+ if (length == 2) {
+ ucs4_t u4in[2];
+ u4in[0] = (ucs4_t)IN1;
+ u4in[1] = (ucs4_t)IN2;
+ encoded = dsg->encoder(u4in, &length);
+ } else
+ encoded = dsg->encoder(&c, &length);
#else
- encoded = dsg->encoder(&c, &length);
+ encoded = dsg->encoder(&c, &length);
#endif
- if (encoded != MAP_UNMAPPABLE) {
- insize = length;
- break;
- }
- }
- else if (encoded != MAP_UNMAPPABLE)
- break;
- }
-
- if (!dsg->mark)
- return 1;
- assert(dsg->width == 1 || dsg->width == 2);
-
- switch (dsg->plane) {
- case 0: /* G0 */
- if (STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SI)
- STATE_CLEARFLAG(F_SHIFTED)
- NEXT_OUT(1)
- }
- if (STATE_G0 != dsg->mark) {
- if (dsg->width == 1) {
- WRITE3(ESC, '(', ESCMARK(dsg->mark))
- STATE_SETG0(dsg->mark)
- NEXT_OUT(3)
- }
- else if (dsg->mark == CHARSET_JISX0208) {
- WRITE3(ESC, '$', ESCMARK(dsg->mark))
- STATE_SETG0(dsg->mark)
- NEXT_OUT(3)
- }
- else {
- WRITE4(ESC, '$', '(',
- ESCMARK(dsg->mark))
- STATE_SETG0(dsg->mark)
- NEXT_OUT(4)
- }
- }
- break;
- case 1: /* G1 */
- if (STATE_G1 != dsg->mark) {
- if (dsg->width == 1) {
- WRITE3(ESC, ')', ESCMARK(dsg->mark))
- STATE_SETG1(dsg->mark)
- NEXT_OUT(3)
- }
- else {
- WRITE4(ESC, '$', ')',
- ESCMARK(dsg->mark))
- STATE_SETG1(dsg->mark)
- NEXT_OUT(4)
- }
- }
- if (!STATE_GETFLAG(F_SHIFTED)) {
- WRITE1(SO)
- STATE_SETFLAG(F_SHIFTED)
- NEXT_OUT(1)
- }
- break;
- default: /* G2 and G3 is not supported: no encoding in
- * CJKCodecs are using them yet */
- return MBERR_INTERNAL;
- }
-
- if (dsg->width == 1) {
- WRITE1((unsigned char)encoded)
- NEXT_OUT(1)
- }
- else {
- WRITE2(encoded >> 8, encoded & 0xff)
- NEXT_OUT(2)
- }
- NEXT_IN(insize)
- }
-
- return 0;
+ if (encoded != MAP_UNMAPPABLE) {
+ insize = length;
+ break;
+ }
+ }
+ else if (encoded != MAP_UNMAPPABLE)
+ break;
+ }
+
+ if (!dsg->mark)
+ return 1;
+ assert(dsg->width == 1 || dsg->width == 2);
+
+ switch (dsg->plane) {
+ case 0: /* G0 */
+ if (STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SI)
+ STATE_CLEARFLAG(F_SHIFTED)
+ NEXT_OUT(1)
+ }
+ if (STATE_G0 != dsg->mark) {
+ if (dsg->width == 1) {
+ WRITE3(ESC, '(', ESCMARK(dsg->mark))
+ STATE_SETG0(dsg->mark)
+ NEXT_OUT(3)
+ }
+ else if (dsg->mark == CHARSET_JISX0208) {
+ WRITE3(ESC, '$', ESCMARK(dsg->mark))
+ STATE_SETG0(dsg->mark)
+ NEXT_OUT(3)
+ }
+ else {
+ WRITE4(ESC, '$', '(',
+ ESCMARK(dsg->mark))
+ STATE_SETG0(dsg->mark)
+ NEXT_OUT(4)
+ }
+ }
+ break;
+ case 1: /* G1 */
+ if (STATE_G1 != dsg->mark) {
+ if (dsg->width == 1) {
+ WRITE3(ESC, ')', ESCMARK(dsg->mark))
+ STATE_SETG1(dsg->mark)
+ NEXT_OUT(3)
+ }
+ else {
+ WRITE4(ESC, '$', ')',
+ ESCMARK(dsg->mark))
+ STATE_SETG1(dsg->mark)
+ NEXT_OUT(4)
+ }
+ }
+ if (!STATE_GETFLAG(F_SHIFTED)) {
+ WRITE1(SO)
+ STATE_SETFLAG(F_SHIFTED)
+ NEXT_OUT(1)
+ }
+ break;
+ default: /* G2 and G3 is not supported: no encoding in
+ * CJKCodecs are using them yet */
+ return MBERR_INTERNAL;
+ }
+
+ if (dsg->width == 1) {
+ WRITE1((unsigned char)encoded)
+ NEXT_OUT(1)
+ }
+ else {
+ WRITE2(encoded >> 8, encoded & 0xff)
+ NEXT_OUT(2)
+ }
+ NEXT_IN(insize)
+ }
+
+ return 0;
}
DECODER_INIT(iso2022)
{
- STATE_CLEARFLAGS()
- STATE_SETG0(CHARSET_ASCII)
- STATE_SETG1(CHARSET_ASCII)
- STATE_SETG2(CHARSET_ASCII)
- return 0;
+ STATE_CLEARFLAGS()
+ STATE_SETG0(CHARSET_ASCII)
+ STATE_SETG1(CHARSET_ASCII)
+ STATE_SETG2(CHARSET_ASCII)
+ return 0;
}
DECODER_RESET(iso2022)
{
- STATE_SETG0(CHARSET_ASCII)
- STATE_CLEARFLAG(F_SHIFTED)
- return 0;
+ STATE_SETG0(CHARSET_ASCII)
+ STATE_CLEARFLAG(F_SHIFTED)
+ return 0;
}
static Py_ssize_t
iso2022processesc(const void *config, MultibyteCodec_State *state,
- const unsigned char **inbuf, Py_ssize_t *inleft)
+ const unsigned char **inbuf, Py_ssize_t *inleft)
{
- unsigned char charset, designation;
- Py_ssize_t i, esclen;
-
- for (i = 1;i < MAX_ESCSEQLEN;i++) {
- if (i >= *inleft)
- return MBERR_TOOFEW;
- if (IS_ESCEND((*inbuf)[i])) {
- esclen = i + 1;
- break;
- }
- else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft &&
- (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@')
- i += 2;
- }
-
- if (i >= MAX_ESCSEQLEN)
- return 1; /* unterminated escape sequence */
-
- switch (esclen) {
- case 3:
- if (IN2 == '$') {
- charset = IN3 | CHARSET_DBCS;
- designation = 0;
- }
- else {
- charset = IN3;
- if (IN2 == '(') designation = 0;
- else if (IN2 == ')') designation = 1;
- else if (CONFIG_ISSET(USE_G2) && IN2 == '.')
- designation = 2;
- else return 3;
- }
- break;
- case 4:
- if (IN2 != '$')
- return 4;
-
- charset = IN4 | CHARSET_DBCS;
- if (IN3 == '(') designation = 0;
- else if (IN3 == ')') designation = 1;
- else return 4;
- break;
- case 6: /* designation with prefix */
- if (CONFIG_ISSET(USE_JISX0208_EXT) &&
- (*inbuf)[3] == ESC && (*inbuf)[4] == '$' &&
- (*inbuf)[5] == 'B') {
- charset = 'B' | CHARSET_DBCS;
- designation = 0;
- }
- else
- return 6;
- break;
- default:
- return esclen;
- }
-
- /* raise error when the charset is not designated for this encoding */
- if (charset != CHARSET_ASCII) {
- const struct iso2022_designation *dsg;
-
- for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++)
- if (dsg->mark == charset)
- break;
- if (!dsg->mark)
- return esclen;
- }
-
- STATE_SETG(designation, charset)
- *inleft -= esclen;
- (*inbuf) += esclen;
- return 0;
+ unsigned char charset, designation;
+ Py_ssize_t i, esclen;
+
+ for (i = 1;i < MAX_ESCSEQLEN;i++) {
+ if (i >= *inleft)
+ return MBERR_TOOFEW;
+ if (IS_ESCEND((*inbuf)[i])) {
+ esclen = i + 1;
+ break;
+ }
+ else if (CONFIG_ISSET(USE_JISX0208_EXT) && i+1 < *inleft &&
+ (*inbuf)[i] == '&' && (*inbuf)[i+1] == '@')
+ i += 2;
+ }
+
+ if (i >= MAX_ESCSEQLEN)
+ return 1; /* unterminated escape sequence */
+
+ switch (esclen) {
+ case 3:
+ if (IN2 == '$') {
+ charset = IN3 | CHARSET_DBCS;
+ designation = 0;
+ }
+ else {
+ charset = IN3;
+ if (IN2 == '(') designation = 0;
+ else if (IN2 == ')') designation = 1;
+ else if (CONFIG_ISSET(USE_G2) && IN2 == '.')
+ designation = 2;
+ else return 3;
+ }
+ break;
+ case 4:
+ if (IN2 != '$')
+ return 4;
+
+ charset = IN4 | CHARSET_DBCS;
+ if (IN3 == '(') designation = 0;
+ else if (IN3 == ')') designation = 1;
+ else return 4;
+ break;
+ case 6: /* designation with prefix */
+ if (CONFIG_ISSET(USE_JISX0208_EXT) &&
+ (*inbuf)[3] == ESC && (*inbuf)[4] == '$' &&
+ (*inbuf)[5] == 'B') {
+ charset = 'B' | CHARSET_DBCS;
+ designation = 0;
+ }
+ else
+ return 6;
+ break;
+ default:
+ return esclen;
+ }
+
+ /* raise error when the charset is not designated for this encoding */
+ if (charset != CHARSET_ASCII) {
+ const struct iso2022_designation *dsg;
+
+ for (dsg = CONFIG_DESIGNATIONS; dsg->mark; dsg++)
+ if (dsg->mark == charset)
+ break;
+ if (!dsg->mark)
+ return esclen;
+ }
+
+ STATE_SETG(designation, charset)
+ *inleft -= esclen;
+ (*inbuf) += esclen;
+ return 0;
}
-#define ISO8859_7_DECODE(c, assi) \
- if ((c) < 0xa0) (assi) = (c); \
- else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \
- (assi) = (c); \
- else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \
- (0xbffffd77L & (1L << ((c)-0xb4))))) \
- (assi) = 0x02d0 + (c); \
- else if ((c) == 0xa1) (assi) = 0x2018; \
- else if ((c) == 0xa2) (assi) = 0x2019; \
- else if ((c) == 0xaf) (assi) = 0x2015;
+#define ISO8859_7_DECODE(c, assi) \
+ if ((c) < 0xa0) (assi) = (c); \
+ else if ((c) < 0xc0 && (0x288f3bc9L & (1L << ((c)-0xa0)))) \
+ (assi) = (c); \
+ else if ((c) >= 0xb4 && (c) <= 0xfe && ((c) >= 0xd4 || \
+ (0xbffffd77L & (1L << ((c)-0xb4))))) \
+ (assi) = 0x02d0 + (c); \
+ else if ((c) == 0xa1) (assi) = 0x2018; \
+ else if ((c) == 0xa2) (assi) = 0x2019; \
+ else if ((c) == 0xaf) (assi) = 0x2015;
static Py_ssize_t
iso2022processg2(const void *config, MultibyteCodec_State *state,
- const unsigned char **inbuf, Py_ssize_t *inleft,
- Py_UNICODE **outbuf, Py_ssize_t *outleft)
+ const unsigned char **inbuf, Py_ssize_t *inleft,
+ Py_UNICODE **outbuf, Py_ssize_t *outleft)
{
- /* not written to use encoder, decoder functions because only few
- * encodings use G2 designations in CJKCodecs */
- if (STATE_G2 == CHARSET_ISO8859_1) {
- if (IN3 < 0x80)
- OUT1(IN3 + 0x80)
- else
- return 3;
- }
- else if (STATE_G2 == CHARSET_ISO8859_7) {
- ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf)
- else return 3;
- }
- else if (STATE_G2 == CHARSET_ASCII) {
- if (IN3 & 0x80) return 3;
- else **outbuf = IN3;
- }
- else
- return MBERR_INTERNAL;
-
- (*inbuf) += 3;
- *inleft -= 3;
- (*outbuf) += 1;
- *outleft -= 1;
- return 0;
+ /* not written to use encoder, decoder functions because only few
+ * encodings use G2 designations in CJKCodecs */
+ if (STATE_G2 == CHARSET_ISO8859_1) {
+ if (IN3 < 0x80)
+ OUT1(IN3 + 0x80)
+ else
+ return 3;
+ }
+ else if (STATE_G2 == CHARSET_ISO8859_7) {
+ ISO8859_7_DECODE(IN3 ^ 0x80, **outbuf)
+ else return 3;
+ }
+ else if (STATE_G2 == CHARSET_ASCII) {
+ if (IN3 & 0x80) return 3;
+ else **outbuf = IN3;
+ }
+ else
+ return MBERR_INTERNAL;
+
+ (*inbuf) += 3;
+ *inleft -= 3;
+ (*outbuf) += 1;
+ *outleft -= 1;
+ return 0;
}
DECODER(iso2022)
{
- const struct iso2022_designation *dsgcache = NULL;
-
- while (inleft > 0) {
- unsigned char c = IN1;
- Py_ssize_t err;
-
- if (STATE_GETFLAG(F_ESCTHROUGHOUT)) {
- /* ESC throughout mode:
- * for non-iso2022 escape sequences */
- WRITE1(c) /* assume as ISO-8859-1 */
- NEXT(1, 1)
- if (IS_ESCEND(c)) {
- STATE_CLEARFLAG(F_ESCTHROUGHOUT)
- }
- continue;
- }
-
- switch (c) {
- case ESC:
- REQUIRE_INBUF(2)
- if (IS_ISO2022ESC(IN2)) {
- err = iso2022processesc(config, state,
- inbuf, &inleft);
- if (err != 0)
- return err;
- }
- else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */
- REQUIRE_INBUF(3)
- err = iso2022processg2(config, state,
- inbuf, &inleft, outbuf, &outleft);
- if (err != 0)
- return err;
- }
- else {
- WRITE1(ESC)
- STATE_SETFLAG(F_ESCTHROUGHOUT)
- NEXT(1, 1)
- }
- break;
- case SI:
- if (CONFIG_ISSET(NO_SHIFT))
- goto bypass;
- STATE_CLEARFLAG(F_SHIFTED)
- NEXT_IN(1)
- break;
- case SO:
- if (CONFIG_ISSET(NO_SHIFT))
- goto bypass;
- STATE_SETFLAG(F_SHIFTED)
- NEXT_IN(1)
- break;
- case LF:
- STATE_CLEARFLAG(F_SHIFTED)
- WRITE1(LF)
- NEXT(1, 1)
- break;
- default:
- if (c < 0x20) /* C0 */
- goto bypass;
- else if (c >= 0x80)
- return 1;
- else {
- const struct iso2022_designation *dsg;
- unsigned char charset;
- ucs4_t decoded;
-
- if (STATE_GETFLAG(F_SHIFTED))
- charset = STATE_G1;
- else
- charset = STATE_G0;
-
- if (charset == CHARSET_ASCII) {
-bypass: WRITE1(c)
- NEXT(1, 1)
- break;
- }
-
- if (dsgcache != NULL &&
- dsgcache->mark == charset)
- dsg = dsgcache;
- else {
- for (dsg = CONFIG_DESIGNATIONS;
- dsg->mark != charset
+ const struct iso2022_designation *dsgcache = NULL;
+
+ while (inleft > 0) {
+ unsigned char c = IN1;
+ Py_ssize_t err;
+
+ if (STATE_GETFLAG(F_ESCTHROUGHOUT)) {
+ /* ESC throughout mode:
+ * for non-iso2022 escape sequences */
+ WRITE1(c) /* assume as ISO-8859-1 */
+ NEXT(1, 1)
+ if (IS_ESCEND(c)) {
+ STATE_CLEARFLAG(F_ESCTHROUGHOUT)
+ }
+ continue;
+ }
+
+ switch (c) {
+ case ESC:
+ REQUIRE_INBUF(2)
+ if (IS_ISO2022ESC(IN2)) {
+ err = iso2022processesc(config, state,
+ inbuf, &inleft);
+ if (err != 0)
+ return err;
+ }
+ else if (CONFIG_ISSET(USE_G2) && IN2 == 'N') {/* SS2 */
+ REQUIRE_INBUF(3)
+ err = iso2022processg2(config, state,
+ inbuf, &inleft, outbuf, &outleft);
+ if (err != 0)
+ return err;
+ }
+ else {
+ WRITE1(ESC)
+ STATE_SETFLAG(F_ESCTHROUGHOUT)
+ NEXT(1, 1)
+ }
+ break;
+ case SI:
+ if (CONFIG_ISSET(NO_SHIFT))
+ goto bypass;
+ STATE_CLEARFLAG(F_SHIFTED)
+ NEXT_IN(1)
+ break;
+ case SO:
+ if (CONFIG_ISSET(NO_SHIFT))
+ goto bypass;
+ STATE_SETFLAG(F_SHIFTED)
+ NEXT_IN(1)
+ break;
+ case LF:
+ STATE_CLEARFLAG(F_SHIFTED)
+ WRITE1(LF)
+ NEXT(1, 1)
+ break;
+ default:
+ if (c < 0x20) /* C0 */
+ goto bypass;
+ else if (c >= 0x80)
+ return 1;
+ else {
+ const struct iso2022_designation *dsg;
+ unsigned char charset;
+ ucs4_t decoded;
+
+ if (STATE_GETFLAG(F_SHIFTED))
+ charset = STATE_G1;
+ else
+ charset = STATE_G0;
+
+ if (charset == CHARSET_ASCII) {
+bypass: WRITE1(c)
+ NEXT(1, 1)
+ break;
+ }
+
+ if (dsgcache != NULL &&
+ dsgcache->mark == charset)
+ dsg = dsgcache;
+ else {
+ for (dsg = CONFIG_DESIGNATIONS;
+ dsg->mark != charset
#ifdef Py_DEBUG
- && dsg->mark != '\0'
+ && dsg->mark != '\0'
#endif
- ;dsg++)
- /* noop */;
- assert(dsg->mark != '\0');
- dsgcache = dsg;
- }
-
- REQUIRE_INBUF(dsg->width)
- decoded = dsg->decoder(*inbuf);
- if (decoded == MAP_UNMAPPABLE)
- return dsg->width;
-
- if (decoded < 0x10000) {
- WRITE1(decoded)
- NEXT_OUT(1)
- }
- else if (decoded < 0x30000) {
- WRITEUCS4(decoded)
- }
- else { /* JIS X 0213 pairs */
- WRITE2(decoded >> 16, decoded & 0xffff)
- NEXT_OUT(2)
- }
- NEXT_IN(dsg->width)
- }
- break;
- }
- }
- return 0;
+ ;dsg++)
+ /* noop */;
+ assert(dsg->mark != '\0');
+ dsgcache = dsg;
+ }
+
+ REQUIRE_INBUF(dsg->width)
+ decoded = dsg->decoder(*inbuf);
+ if (decoded == MAP_UNMAPPABLE)
+ return dsg->width;
+
+ if (decoded < 0x10000) {
+ WRITE1(decoded)
+ NEXT_OUT(1)
+ }
+ else if (decoded < 0x30000) {
+ WRITEUCS4(decoded)
+ }
+ else { /* JIS X 0213 pairs */
+ WRITE2(decoded >> 16, decoded & 0xffff)
+ NEXT_OUT(2)
+ }
+ NEXT_IN(dsg->width)
+ }
+ break;
+ }
+ }
+ return 0;
}
/*-*- mapping table holders -*-*/
@@ -567,542 +567,542 @@ DECMAP(gb2312)
static int
ksx1001_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) ||
- IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(kr, cp949, &cp949_encmap, NULL) ||
+ IMPORT_MAP(kr, ksx1001, NULL, &ksx1001_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
ksx1001_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(ksx1001, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ TRYMAP_DEC(ksx1001, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
ksx1001_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- TRYMAP_ENC(cp949, coded, *data)
- if (!(coded & 0x8000))
- return coded;
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ TRYMAP_ENC(cp949, coded, *data)
+ if (!(coded & 0x8000))
+ return coded;
+ }
+ return MAP_UNMAPPABLE;
}
static int
jisx0208_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0208, NULL, &jisx0208_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
jisx0208_decoder(const unsigned char *data)
{
- ucs4_t u;
- if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
- return 0xff3c;
- else TRYMAP_DEC(jisx0208, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
+ return 0xff3c;
+ else TRYMAP_DEC(jisx0208, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
jisx0208_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */
- return 0x2140;
- else TRYMAP_ENC(jisxcommon, coded, *data) {
- if (!(coded & 0x8000))
- return coded;
- }
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ if (*data == 0xff3c) /* F/W REVERSE SOLIDUS */
+ return 0x2140;
+ else TRYMAP_ENC(jisxcommon, coded, *data) {
+ if (!(coded & 0x8000))
+ return coded;
+ }
+ }
+ return MAP_UNMAPPABLE;
}
static int
jisx0212_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(jp, jisxcommon, &jisxcommon_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0212, NULL, &jisx0212_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
jisx0212_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(jisx0212, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ TRYMAP_DEC(jisx0212, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
jisx0212_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- TRYMAP_ENC(jisxcommon, coded, *data) {
- if (coded & 0x8000)
- return coded & 0x7fff;
- }
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ TRYMAP_ENC(jisxcommon, coded, *data) {
+ if (coded & 0x8000)
+ return coded & 0x7fff;
+ }
+ }
+ return MAP_UNMAPPABLE;
}
static int
jisx0213_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- jisx0208_init() ||
- IMPORT_MAP(jp, jisx0213_bmp,
- &jisx0213_bmp_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0213_1_bmp,
- NULL, &jisx0213_1_bmp_decmap) ||
- IMPORT_MAP(jp, jisx0213_2_bmp,
- NULL, &jisx0213_2_bmp_decmap) ||
- IMPORT_MAP(jp, jisx0213_emp,
- &jisx0213_emp_encmap, NULL) ||
- IMPORT_MAP(jp, jisx0213_1_emp,
- NULL, &jisx0213_1_emp_decmap) ||
- IMPORT_MAP(jp, jisx0213_2_emp,
- NULL, &jisx0213_2_emp_decmap) ||
- IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap,
- &jisx0213_pair_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ jisx0208_init() ||
+ IMPORT_MAP(jp, jisx0213_bmp,
+ &jisx0213_bmp_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0213_1_bmp,
+ NULL, &jisx0213_1_bmp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_2_bmp,
+ NULL, &jisx0213_2_bmp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_emp,
+ &jisx0213_emp_encmap, NULL) ||
+ IMPORT_MAP(jp, jisx0213_1_emp,
+ NULL, &jisx0213_1_emp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_2_emp,
+ NULL, &jisx0213_2_emp_decmap) ||
+ IMPORT_MAP(jp, jisx0213_pair, &jisx0213_pair_encmap,
+ &jisx0213_pair_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
#define config ((void *)2000)
static ucs4_t
jisx0213_2000_1_decoder(const unsigned char *data)
{
- ucs4_t u;
- EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1])
- else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
- return 0xff3c;
- else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
- u |= 0x20000;
- else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ EMULATE_JISX0213_2000_DECODE_PLANE1(u, data[0], data[1])
+ else if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
+ return 0xff3c;
+ else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
static ucs4_t
jisx0213_2000_2_decoder(const unsigned char *data)
{
- ucs4_t u;
- EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1])
- TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
- u |= 0x20000;
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ EMULATE_JISX0213_2000_DECODE_PLANE2(u, data[0], data[1])
+ TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
#undef config
static ucs4_t
jisx0213_2004_1_decoder(const unsigned char *data)
{
- ucs4_t u;
- if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
- return 0xff3c;
- else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
- u |= 0x20000;
- else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ if (data[0] == 0x21 && data[1] == 0x40) /* F/W REVERSE SOLIDUS */
+ return 0xff3c;
+ else TRYMAP_DEC(jisx0208, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_1_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else TRYMAP_DEC(jisx0213_pair, u, data[0], data[1]);
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
static ucs4_t
jisx0213_2004_2_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
- else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
- u |= 0x20000;
- else
- return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ TRYMAP_DEC(jisx0213_2_bmp, u, data[0], data[1]);
+ else TRYMAP_DEC(jisx0213_2_emp, u, data[0], data[1])
+ u |= 0x20000;
+ else
+ return MAP_UNMAPPABLE;
+ return u;
}
static DBCHAR
jisx0213_encoder(const ucs4_t *data, Py_ssize_t *length, void *config)
{
- DBCHAR coded;
-
- switch (*length) {
- case 1: /* first character */
- if (*data >= 0x10000) {
- if ((*data) >> 16 == 0x20000 >> 16) {
- EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data)
- else TRYMAP_ENC(jisx0213_emp, coded,
- (*data) & 0xffff)
- return coded;
- }
- return MAP_UNMAPPABLE;
- }
-
- EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data)
- else TRYMAP_ENC(jisx0213_bmp, coded, *data) {
- if (coded == MULTIC)
- return MAP_MULTIPLE_AVAIL;
- }
- else TRYMAP_ENC(jisxcommon, coded, *data) {
- if (coded & 0x8000)
- return MAP_UNMAPPABLE;
- }
- else
- return MAP_UNMAPPABLE;
- return coded;
- case 2: /* second character of unicode pair */
- coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1],
- jisx0213_pair_encmap, JISX0213_ENCPAIRS);
- if (coded == DBCINV) {
- *length = 1;
- coded = find_pairencmap((ucs2_t)data[0], 0,
- jisx0213_pair_encmap, JISX0213_ENCPAIRS);
- if (coded == DBCINV)
- return MAP_UNMAPPABLE;
- }
- else
- return coded;
- case -1: /* flush unterminated */
- *length = 1;
- coded = find_pairencmap((ucs2_t)data[0], 0,
- jisx0213_pair_encmap, JISX0213_ENCPAIRS);
- if (coded == DBCINV)
- return MAP_UNMAPPABLE;
- else
- return coded;
- default:
- return MAP_UNMAPPABLE;
- }
+ DBCHAR coded;
+
+ switch (*length) {
+ case 1: /* first character */
+ if (*data >= 0x10000) {
+ if ((*data) >> 16 == 0x20000 >> 16) {
+ EMULATE_JISX0213_2000_ENCODE_EMP(coded, *data)
+ else TRYMAP_ENC(jisx0213_emp, coded,
+ (*data) & 0xffff)
+ return coded;
+ }
+ return MAP_UNMAPPABLE;
+ }
+
+ EMULATE_JISX0213_2000_ENCODE_BMP(coded, *data)
+ else TRYMAP_ENC(jisx0213_bmp, coded, *data) {
+ if (coded == MULTIC)
+ return MAP_MULTIPLE_AVAIL;
+ }
+ else TRYMAP_ENC(jisxcommon, coded, *data) {
+ if (coded & 0x8000)
+ return MAP_UNMAPPABLE;
+ }
+ else
+ return MAP_UNMAPPABLE;
+ return coded;
+ case 2: /* second character of unicode pair */
+ coded = find_pairencmap((ucs2_t)data[0], (ucs2_t)data[1],
+ jisx0213_pair_encmap, JISX0213_ENCPAIRS);
+ if (coded == DBCINV) {
+ *length = 1;
+ coded = find_pairencmap((ucs2_t)data[0], 0,
+ jisx0213_pair_encmap, JISX0213_ENCPAIRS);
+ if (coded == DBCINV)
+ return MAP_UNMAPPABLE;
+ }
+ else
+ return coded;
+ case -1: /* flush unterminated */
+ *length = 1;
+ coded = find_pairencmap((ucs2_t)data[0], 0,
+ jisx0213_pair_encmap, JISX0213_ENCPAIRS);
+ if (coded == DBCINV)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
+ default:
+ return MAP_UNMAPPABLE;
+ }
}
static DBCHAR
jisx0213_2000_1_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return MAP_UNMAPPABLE;
- else
- return coded;
+ DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
}
static DBCHAR
jisx0213_2000_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- Py_ssize_t ilength = *length;
-
- coded = jisx0213_encoder(data, length, (void *)2000);
- switch (ilength) {
- case 1:
- if (coded == MAP_MULTIPLE_AVAIL)
- return MAP_MULTIPLE_AVAIL;
- else
- return MAP_UNMAPPABLE;
- case 2:
- if (*length != 2)
- return MAP_UNMAPPABLE;
- else
- return coded;
- default:
- return MAP_UNMAPPABLE;
- }
+ DBCHAR coded;
+ Py_ssize_t ilength = *length;
+
+ coded = jisx0213_encoder(data, length, (void *)2000);
+ switch (ilength) {
+ case 1:
+ if (coded == MAP_MULTIPLE_AVAIL)
+ return MAP_MULTIPLE_AVAIL;
+ else
+ return MAP_UNMAPPABLE;
+ case 2:
+ if (*length != 2)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
+ default:
+ return MAP_UNMAPPABLE;
+ }
}
static DBCHAR
jisx0213_2000_2_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return coded & 0x7fff;
- else
- return MAP_UNMAPPABLE;
+ DBCHAR coded = jisx0213_encoder(data, length, (void *)2000);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return coded & 0x7fff;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
jisx0213_2004_1_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, NULL);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return MAP_UNMAPPABLE;
- else
- return coded;
+ DBCHAR coded = jisx0213_encoder(data, length, NULL);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
}
static DBCHAR
jisx0213_2004_1_encoder_paironly(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- Py_ssize_t ilength = *length;
-
- coded = jisx0213_encoder(data, length, NULL);
- switch (ilength) {
- case 1:
- if (coded == MAP_MULTIPLE_AVAIL)
- return MAP_MULTIPLE_AVAIL;
- else
- return MAP_UNMAPPABLE;
- case 2:
- if (*length != 2)
- return MAP_UNMAPPABLE;
- else
- return coded;
- default:
- return MAP_UNMAPPABLE;
- }
+ DBCHAR coded;
+ Py_ssize_t ilength = *length;
+
+ coded = jisx0213_encoder(data, length, NULL);
+ switch (ilength) {
+ case 1:
+ if (coded == MAP_MULTIPLE_AVAIL)
+ return MAP_MULTIPLE_AVAIL;
+ else
+ return MAP_UNMAPPABLE;
+ case 2:
+ if (*length != 2)
+ return MAP_UNMAPPABLE;
+ else
+ return coded;
+ default:
+ return MAP_UNMAPPABLE;
+ }
}
static DBCHAR
jisx0213_2004_2_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded = jisx0213_encoder(data, length, NULL);
- if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
- return coded;
- else if (coded & 0x8000)
- return coded & 0x7fff;
- else
- return MAP_UNMAPPABLE;
+ DBCHAR coded = jisx0213_encoder(data, length, NULL);
+ if (coded == MAP_UNMAPPABLE || coded == MAP_MULTIPLE_AVAIL)
+ return coded;
+ else if (coded & 0x8000)
+ return coded & 0x7fff;
+ else
+ return MAP_UNMAPPABLE;
}
static ucs4_t
jisx0201_r_decoder(const unsigned char *data)
{
- ucs4_t u;
- JISX0201_R_DECODE(*data, u)
- else return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ JISX0201_R_DECODE(*data, u)
+ else return MAP_UNMAPPABLE;
+ return u;
}
static DBCHAR
jisx0201_r_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- JISX0201_R_ENCODE(*data, coded)
- else return MAP_UNMAPPABLE;
- return coded;
+ DBCHAR coded;
+ JISX0201_R_ENCODE(*data, coded)
+ else return MAP_UNMAPPABLE;
+ return coded;
}
static ucs4_t
jisx0201_k_decoder(const unsigned char *data)
{
- ucs4_t u;
- JISX0201_K_DECODE(*data ^ 0x80, u)
- else return MAP_UNMAPPABLE;
- return u;
+ ucs4_t u;
+ JISX0201_K_DECODE(*data ^ 0x80, u)
+ else return MAP_UNMAPPABLE;
+ return u;
}
static DBCHAR
jisx0201_k_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- JISX0201_K_ENCODE(*data, coded)
- else return MAP_UNMAPPABLE;
- return coded - 0x80;
+ DBCHAR coded;
+ JISX0201_K_ENCODE(*data, coded)
+ else return MAP_UNMAPPABLE;
+ return coded - 0x80;
}
static int
gb2312_init(void)
{
- static int initialized = 0;
-
- if (!initialized && (
- IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) ||
- IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap)))
- return -1;
- initialized = 1;
- return 0;
+ static int initialized = 0;
+
+ if (!initialized && (
+ IMPORT_MAP(cn, gbcommon, &gbcommon_encmap, NULL) ||
+ IMPORT_MAP(cn, gb2312, NULL, &gb2312_decmap)))
+ return -1;
+ initialized = 1;
+ return 0;
}
static ucs4_t
gb2312_decoder(const unsigned char *data)
{
- ucs4_t u;
- TRYMAP_DEC(gb2312, u, data[0], data[1])
- return u;
- else
- return MAP_UNMAPPABLE;
+ ucs4_t u;
+ TRYMAP_DEC(gb2312, u, data[0], data[1])
+ return u;
+ else
+ return MAP_UNMAPPABLE;
}
static DBCHAR
gb2312_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- DBCHAR coded;
- assert(*length == 1);
- if (*data < 0x10000) {
- TRYMAP_ENC(gbcommon, coded, *data) {
- if (!(coded & 0x8000))
- return coded;
- }
- }
- return MAP_UNMAPPABLE;
+ DBCHAR coded;
+ assert(*length == 1);
+ if (*data < 0x10000) {
+ TRYMAP_ENC(gbcommon, coded, *data) {
+ if (!(coded & 0x8000))
+ return coded;
+ }
+ }
+ return MAP_UNMAPPABLE;
}
static ucs4_t
dummy_decoder(const unsigned char *data)
{
- return MAP_UNMAPPABLE;
+ return MAP_UNMAPPABLE;
}
static DBCHAR
dummy_encoder(const ucs4_t *data, Py_ssize_t *length)
{
- return MAP_UNMAPPABLE;
+ return MAP_UNMAPPABLE;
}
/*-*- registry tables -*-*/
-#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \
- ksx1001_init, \
- ksx1001_decoder, ksx1001_encoder }
-#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \
- ksx1001_init, \
- ksx1001_decoder, ksx1001_encoder }
-#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \
- NULL, \
- jisx0201_r_decoder, jisx0201_r_encoder }
-#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \
- NULL, \
- jisx0201_k_decoder, jisx0201_k_encoder }
-#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \
- jisx0208_init, \
- jisx0208_decoder, jisx0208_encoder }
-#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \
- jisx0208_init, \
- jisx0208_decoder, jisx0208_encoder }
-#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \
- jisx0212_init, \
- jisx0212_decoder, jisx0212_encoder }
-#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2000_1_decoder, \
- jisx0213_2000_1_encoder }
+#define REGISTRY_KSX1001_G0 { CHARSET_KSX1001, 0, 2, \
+ ksx1001_init, \
+ ksx1001_decoder, ksx1001_encoder }
+#define REGISTRY_KSX1001_G1 { CHARSET_KSX1001, 1, 2, \
+ ksx1001_init, \
+ ksx1001_decoder, ksx1001_encoder }
+#define REGISTRY_JISX0201_R { CHARSET_JISX0201_R, 0, 1, \
+ NULL, \
+ jisx0201_r_decoder, jisx0201_r_encoder }
+#define REGISTRY_JISX0201_K { CHARSET_JISX0201_K, 0, 1, \
+ NULL, \
+ jisx0201_k_decoder, jisx0201_k_encoder }
+#define REGISTRY_JISX0208 { CHARSET_JISX0208, 0, 2, \
+ jisx0208_init, \
+ jisx0208_decoder, jisx0208_encoder }
+#define REGISTRY_JISX0208_O { CHARSET_JISX0208_O, 0, 2, \
+ jisx0208_init, \
+ jisx0208_decoder, jisx0208_encoder }
+#define REGISTRY_JISX0212 { CHARSET_JISX0212, 0, 2, \
+ jisx0212_init, \
+ jisx0212_decoder, jisx0212_encoder }
+#define REGISTRY_JISX0213_2000_1 { CHARSET_JISX0213_2000_1, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2000_1_decoder, \
+ jisx0213_2000_1_encoder }
#define REGISTRY_JISX0213_2000_1_PAIRONLY { CHARSET_JISX0213_2000_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2000_1_decoder, \
- jisx0213_2000_1_encoder_paironly }
-#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \
- jisx0213_init, \
- jisx0213_2000_2_decoder, \
- jisx0213_2000_2_encoder }
-#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2004_1_decoder, \
- jisx0213_2004_1_encoder }
+ jisx0213_init, \
+ jisx0213_2000_1_decoder, \
+ jisx0213_2000_1_encoder_paironly }
+#define REGISTRY_JISX0213_2000_2 { CHARSET_JISX0213_2, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2000_2_decoder, \
+ jisx0213_2000_2_encoder }
+#define REGISTRY_JISX0213_2004_1 { CHARSET_JISX0213_2004_1, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2004_1_decoder, \
+ jisx0213_2004_1_encoder }
#define REGISTRY_JISX0213_2004_1_PAIRONLY { CHARSET_JISX0213_2004_1, 0, 2, \
- jisx0213_init, \
- jisx0213_2004_1_decoder, \
- jisx0213_2004_1_encoder_paironly }
-#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \
- jisx0213_init, \
- jisx0213_2004_2_decoder, \
- jisx0213_2004_2_encoder }
-#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \
- gb2312_init, \
- gb2312_decoder, gb2312_encoder }
-#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \
- cns11643_init, \
- cns11643_1_decoder, cns11643_1_encoder }
-#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \
- cns11643_init, \
- cns11643_2_decoder, cns11643_2_encoder }
-#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \
- NULL, dummy_decoder, dummy_encoder }
-#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \
- NULL, dummy_decoder, dummy_encoder }
-#define REGISTRY_SENTINEL { 0, }
-#define CONFIGDEF(var, attrs) \
- static const struct iso2022_config iso2022_##var##_config = { \
- attrs, iso2022_##var##_designations \
- };
+ jisx0213_init, \
+ jisx0213_2004_1_decoder, \
+ jisx0213_2004_1_encoder_paironly }
+#define REGISTRY_JISX0213_2004_2 { CHARSET_JISX0213_2, 0, 2, \
+ jisx0213_init, \
+ jisx0213_2004_2_decoder, \
+ jisx0213_2004_2_encoder }
+#define REGISTRY_GB2312 { CHARSET_GB2312, 0, 2, \
+ gb2312_init, \
+ gb2312_decoder, gb2312_encoder }
+#define REGISTRY_CNS11643_1 { CHARSET_CNS11643_1, 1, 2, \
+ cns11643_init, \
+ cns11643_1_decoder, cns11643_1_encoder }
+#define REGISTRY_CNS11643_2 { CHARSET_CNS11643_2, 2, 2, \
+ cns11643_init, \
+ cns11643_2_decoder, cns11643_2_encoder }
+#define REGISTRY_ISO8859_1 { CHARSET_ISO8859_1, 2, 1, \
+ NULL, dummy_decoder, dummy_encoder }
+#define REGISTRY_ISO8859_7 { CHARSET_ISO8859_7, 2, 1, \
+ NULL, dummy_decoder, dummy_encoder }
+#define REGISTRY_SENTINEL { 0, }
+#define CONFIGDEF(var, attrs) \
+ static const struct iso2022_config iso2022_##var##_config = { \
+ attrs, iso2022_##var##_designations \
+ };
static const struct iso2022_designation iso2022_kr_designations[] = {
- REGISTRY_KSX1001_G1, REGISTRY_SENTINEL
+ REGISTRY_KSX1001_G1, REGISTRY_SENTINEL
};
CONFIGDEF(kr, 0)
static const struct iso2022_designation iso2022_jp_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
- REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
+ REGISTRY_SENTINEL
};
CONFIGDEF(jp, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_1_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
- REGISTRY_JISX0208_O, REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
+ REGISTRY_JISX0208_O, REGISTRY_SENTINEL
};
CONFIGDEF(jp_1, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_2_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0,
- REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
- REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_KSX1001_G0,
+ REGISTRY_GB2312, REGISTRY_JISX0201_R, REGISTRY_JISX0208_O,
+ REGISTRY_ISO8859_1, REGISTRY_ISO8859_7, REGISTRY_SENTINEL
};
CONFIGDEF(jp_2, NO_SHIFT | USE_G2 | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_2004_designations[] = {
- REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208,
- REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL
+ REGISTRY_JISX0213_2004_1_PAIRONLY, REGISTRY_JISX0208,
+ REGISTRY_JISX0213_2004_1, REGISTRY_JISX0213_2004_2, REGISTRY_SENTINEL
};
CONFIGDEF(jp_2004, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_3_designations[] = {
- REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208,
- REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL
+ REGISTRY_JISX0213_2000_1_PAIRONLY, REGISTRY_JISX0208,
+ REGISTRY_JISX0213_2000_1, REGISTRY_JISX0213_2000_2, REGISTRY_SENTINEL
};
CONFIGDEF(jp_3, NO_SHIFT | USE_JISX0208_EXT)
static const struct iso2022_designation iso2022_jp_ext_designations[] = {
- REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
- REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL
+ REGISTRY_JISX0208, REGISTRY_JISX0212, REGISTRY_JISX0201_R,
+ REGISTRY_JISX0201_K, REGISTRY_JISX0208_O, REGISTRY_SENTINEL
};
CONFIGDEF(jp_ext, NO_SHIFT | USE_JISX0208_EXT)
@@ -1111,11 +1111,11 @@ BEGIN_MAPPINGS_LIST
/* no mapping table here */
END_MAPPINGS_LIST
-#define ISO2022_CODEC(variation) { \
- "iso2022_" #variation, \
- &iso2022_##variation##_config, \
- iso2022_codec_init, \
- _STATEFUL_METHODS(iso2022) \
+#define ISO2022_CODEC(variation) { \
+ "iso2022_" #variation, \
+ &iso2022_##variation##_config, \
+ iso2022_codec_init, \
+ _STATEFUL_METHODS(iso2022) \
},
BEGIN_CODECS_LIST
diff --git a/Modules/cjkcodecs/_codecs_jp.c b/Modules/cjkcodecs/_codecs_jp.c
index f49a10b..901d3be 100644
--- a/Modules/cjkcodecs/_codecs_jp.c
+++ b/Modules/cjkcodecs/_codecs_jp.c
@@ -19,124 +19,124 @@
ENCODER(cp932)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
- unsigned char c1, c2;
-
- if (c <= 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xff61 && c <= 0xff9f) {
- WRITE1(c - 0xfec0)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xf8f0 && c <= 0xf8f3) {
- /* Windows compatibility */
- REQUIRE_OUTBUF(1)
- if (c == 0xf8f0)
- OUT1(0xa0)
- else
- OUT1(c - 0xfef1 + 0xfd)
- NEXT(1, 1)
- continue;
- }
-
- UCS4INVALID(c)
- REQUIRE_OUTBUF(2)
-
- TRYMAP_ENC(cp932ext, code, c) {
- OUT1(code >> 8)
- OUT2(code & 0xff)
- }
- else TRYMAP_ENC(jisxcommon, code, c) {
- if (code & 0x8000) /* MSB set: JIS X 0212 */
- return 1;
-
- /* JIS X 0208 */
- c1 = code >> 8;
- c2 = code & 0xff;
- c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
- c1 = (c1 - 0x21) >> 1;
- OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
- OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
- }
- else if (c >= 0xe000 && c < 0xe758) {
- /* User-defined area */
- c1 = (Py_UNICODE)(c - 0xe000) / 188;
- c2 = (Py_UNICODE)(c - 0xe000) % 188;
- OUT1(c1 + 0xf0)
- OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
- }
- else
- return 1;
-
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+ unsigned char c1, c2;
+
+ if (c <= 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xff61 && c <= 0xff9f) {
+ WRITE1(c - 0xfec0)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xf8f0 && c <= 0xf8f3) {
+ /* Windows compatibility */
+ REQUIRE_OUTBUF(1)
+ if (c == 0xf8f0)
+ OUT1(0xa0)
+ else
+ OUT1(c - 0xfef1 + 0xfd)
+ NEXT(1, 1)
+ continue;
+ }
+
+ UCS4INVALID(c)
+ REQUIRE_OUTBUF(2)
+
+ TRYMAP_ENC(cp932ext, code, c) {
+ OUT1(code >> 8)
+ OUT2(code & 0xff)
+ }
+ else TRYMAP_ENC(jisxcommon, code, c) {
+ if (code & 0x8000) /* MSB set: JIS X 0212 */
+ return 1;
+
+ /* JIS X 0208 */
+ c1 = code >> 8;
+ c2 = code & 0xff;
+ c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
+ c1 = (c1 - 0x21) >> 1;
+ OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
+ OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
+ }
+ else if (c >= 0xe000 && c < 0xe758) {
+ /* User-defined area */
+ c1 = (Py_UNICODE)(c - 0xe000) / 188;
+ c2 = (Py_UNICODE)(c - 0xe000) % 188;
+ OUT1(c1 + 0xf0)
+ OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
+ }
+ else
+ return 1;
+
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(cp932)
{
- while (inleft > 0) {
- unsigned char c = IN1, c2;
-
- REQUIRE_OUTBUF(1)
- if (c <= 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xa0 && c <= 0xdf) {
- if (c == 0xa0)
- OUT1(0xf8f0) /* half-width katakana */
- else
- OUT1(0xfec0 + c)
- NEXT(1, 1)
- continue;
- }
- else if (c >= 0xfd/* && c <= 0xff*/) {
- /* Windows compatibility */
- OUT1(0xf8f1 - 0xfd + c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
- c2 = IN2;
-
- TRYMAP_DEC(cp932ext, **outbuf, c, c2);
- else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
- if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
- return 2;
-
- c = (c < 0xe0 ? c - 0x81 : c - 0xc1);
- c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
- c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21);
- c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
-
- TRYMAP_DEC(jisx0208, **outbuf, c, c2);
- else return 2;
- }
- else if (c >= 0xf0 && c <= 0xf9) {
- if ((c2 >= 0x40 && c2 <= 0x7e) ||
- (c2 >= 0x80 && c2 <= 0xfc))
- OUT1(0xe000 + 188 * (c - 0xf0) +
- (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41))
- else
- return 2;
- }
- else
- return 2;
-
- NEXT(2, 1)
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1, c2;
+
+ REQUIRE_OUTBUF(1)
+ if (c <= 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xa0 && c <= 0xdf) {
+ if (c == 0xa0)
+ OUT1(0xf8f0) /* half-width katakana */
+ else
+ OUT1(0xfec0 + c)
+ NEXT(1, 1)
+ continue;
+ }
+ else if (c >= 0xfd/* && c <= 0xff*/) {
+ /* Windows compatibility */
+ OUT1(0xf8f1 - 0xfd + c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+
+ TRYMAP_DEC(cp932ext, **outbuf, c, c2);
+ else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
+ if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
+ return 2;
+
+ c = (c < 0xe0 ? c - 0x81 : c - 0xc1);
+ c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
+ c = (2 * c + (c2 < 0x5e ? 0 : 1) + 0x21);
+ c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
+
+ TRYMAP_DEC(jisx0208, **outbuf, c, c2);
+ else return 2;
+ }
+ else if (c >= 0xf0 && c <= 0xf9) {
+ if ((c2 >= 0x40 && c2 <= 0x7e) ||
+ (c2 >= 0x80 && c2 <= 0xfc))
+ OUT1(0xe000 + 188 * (c - 0xf0) +
+ (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41))
+ else
+ return 2;
+ }
+ else
+ return 2;
+
+ NEXT(2, 1)
+ }
+
+ return 0;
}
@@ -146,166 +146,166 @@ DECODER(cp932)
ENCODER(euc_jis_2004)
{
- while (inleft > 0) {
- ucs4_t c = IN1;
- DBCHAR code;
- Py_ssize_t insize;
-
- if (c < 0x80) {
- WRITE1(c)
- NEXT(1, 1)
- continue;
- }
-
- DECODE_SURROGATE(c)
- insize = GET_INSIZE(c);
-
- if (c <= 0xFFFF) {
- EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
- else TRYMAP_ENC(jisx0213_bmp, code, c) {
- if (code == MULTIC) {
- if (inleft < 2) {
- if (flags & MBENC_FLUSH) {
- code = find_pairencmap(
- (ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- }
- else
- return MBERR_TOOFEW;
- }
- else {
- code = find_pairencmap(
- (ucs2_t)c, (*inbuf)[1],
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV) {
- code = find_pairencmap(
- (ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- } else
- insize = 2;
- }
- }
- }
- else TRYMAP_ENC(jisxcommon, code, c);
- else if (c >= 0xff61 && c <= 0xff9f) {
- /* JIS X 0201 half-width katakana */
- WRITE2(0x8e, c - 0xfec0)
- NEXT(1, 2)
- continue;
- }
- else if (c == 0xff3c)
- /* F/W REVERSE SOLIDUS (see NOTES) */
- code = 0x2140;
- else if (c == 0xff5e)
- /* F/W TILDE (see NOTES) */
- code = 0x2232;
- else
- return 1;
- }
- else if (c >> 16 == EMPBASE >> 16) {
- EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
- else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff);
- else return insize;
- }
- else
- return insize;
-
- if (code & 0x8000) {
- /* Codeset 2 */
- WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
- NEXT(insize, 3)
- } else {
- /* Codeset 1 */
- WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
- NEXT(insize, 2)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ ucs4_t c = IN1;
+ DBCHAR code;
+ Py_ssize_t insize;
+
+ if (c < 0x80) {
+ WRITE1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ DECODE_SURROGATE(c)
+ insize = GET_INSIZE(c);
+
+ if (c <= 0xFFFF) {
+ EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
+ else TRYMAP_ENC(jisx0213_bmp, code, c) {
+ if (code == MULTIC) {
+ if (inleft < 2) {
+ if (flags & MBENC_FLUSH) {
+ code = find_pairencmap(
+ (ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ }
+ else
+ return MBERR_TOOFEW;
+ }
+ else {
+ code = find_pairencmap(
+ (ucs2_t)c, (*inbuf)[1],
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV) {
+ code = find_pairencmap(
+ (ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ } else
+ insize = 2;
+ }
+ }
+ }
+ else TRYMAP_ENC(jisxcommon, code, c);
+ else if (c >= 0xff61 && c <= 0xff9f) {
+ /* JIS X 0201 half-width katakana */
+ WRITE2(0x8e, c - 0xfec0)
+ NEXT(1, 2)
+ continue;
+ }
+ else if (c == 0xff3c)
+ /* F/W REVERSE SOLIDUS (see NOTES) */
+ code = 0x2140;
+ else if (c == 0xff5e)
+ /* F/W TILDE (see NOTES) */
+ code = 0x2232;
+ else
+ return 1;
+ }
+ else if (c >> 16 == EMPBASE >> 16) {
+ EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
+ else TRYMAP_ENC(jisx0213_emp, code, c & 0xffff);
+ else return insize;
+ }
+ else
+ return insize;
+
+ if (code & 0x8000) {
+ /* Codeset 2 */
+ WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
+ NEXT(insize, 3)
+ } else {
+ /* Codeset 1 */
+ WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
+ NEXT(insize, 2)
+ }
+ }
+
+ return 0;
}
DECODER(euc_jis_2004)
{
- while (inleft > 0) {
- unsigned char c = IN1;
- ucs4_t code;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- if (c == 0x8e) {
- /* JIS X 0201 half-width katakana */
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 >= 0xa1 && c2 <= 0xdf) {
- OUT1(0xfec0 + c2)
- NEXT(2, 1)
- }
- else
- return 2;
- }
- else if (c == 0x8f) {
- unsigned char c2, c3;
-
- REQUIRE_INBUF(3)
- c2 = IN2 ^ 0x80;
- c3 = IN3 ^ 0x80;
-
- /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */
- EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3)
- else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ;
- else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) {
- WRITEUCS4(EMPBASE | code)
- NEXT_IN(3)
- continue;
- }
- else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ;
- else return 3;
- NEXT(3, 1)
- }
- else {
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c ^= 0x80;
- c2 = IN2 ^ 0x80;
-
- /* JIS X 0213 Plane 1 */
- EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2)
- else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c;
- else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e;
- else TRYMAP_DEC(jisx0208, **outbuf, c, c2);
- else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2);
- else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) {
- WRITEUCS4(EMPBASE | code)
- NEXT_IN(2)
- continue;
- }
- else TRYMAP_DEC(jisx0213_pair, code, c, c2) {
- WRITE2(code >> 16, code & 0xffff)
- NEXT(2, 2)
- continue;
- }
- else return 2;
- NEXT(2, 1)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+ ucs4_t code;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ if (c == 0x8e) {
+ /* JIS X 0201 half-width katakana */
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 >= 0xa1 && c2 <= 0xdf) {
+ OUT1(0xfec0 + c2)
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+ else if (c == 0x8f) {
+ unsigned char c2, c3;
+
+ REQUIRE_INBUF(3)
+ c2 = IN2 ^ 0x80;
+ c3 = IN3 ^ 0x80;
+
+ /* JIS X 0213 Plane 2 or JIS X 0212 (see NOTES) */
+ EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf, c2, c3)
+ else TRYMAP_DEC(jisx0213_2_bmp, **outbuf, c2, c3) ;
+ else TRYMAP_DEC(jisx0213_2_emp, code, c2, c3) {
+ WRITEUCS4(EMPBASE | code)
+ NEXT_IN(3)
+ continue;
+ }
+ else TRYMAP_DEC(jisx0212, **outbuf, c2, c3) ;
+ else return 3;
+ NEXT(3, 1)
+ }
+ else {
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c ^= 0x80;
+ c2 = IN2 ^ 0x80;
+
+ /* JIS X 0213 Plane 1 */
+ EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf, c, c2)
+ else if (c == 0x21 && c2 == 0x40) **outbuf = 0xff3c;
+ else if (c == 0x22 && c2 == 0x32) **outbuf = 0xff5e;
+ else TRYMAP_DEC(jisx0208, **outbuf, c, c2);
+ else TRYMAP_DEC(jisx0213_1_bmp, **outbuf, c, c2);
+ else TRYMAP_DEC(jisx0213_1_emp, code, c, c2) {
+ WRITEUCS4(EMPBASE | code)
+ NEXT_IN(2)
+ continue;
+ }
+ else TRYMAP_DEC(jisx0213_pair, code, c, c2) {
+ WRITE2(code >> 16, code & 0xffff)
+ NEXT(2, 2)
+ continue;
+ }
+ else return 2;
+ NEXT(2, 1)
+ }
+ }
+
+ return 0;
}
@@ -315,114 +315,114 @@ DECODER(euc_jis_2004)
ENCODER(euc_jp)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
-
- UCS4INVALID(c)
-
- TRYMAP_ENC(jisxcommon, code, c);
- else if (c >= 0xff61 && c <= 0xff9f) {
- /* JIS X 0201 half-width katakana */
- WRITE2(0x8e, c - 0xfec0)
- NEXT(1, 2)
- continue;
- }
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ UCS4INVALID(c)
+
+ TRYMAP_ENC(jisxcommon, code, c);
+ else if (c >= 0xff61 && c <= 0xff9f) {
+ /* JIS X 0201 half-width katakana */
+ WRITE2(0x8e, c - 0xfec0)
+ NEXT(1, 2)
+ continue;
+ }
#ifndef STRICT_BUILD
- else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */
- code = 0x2140;
- else if (c == 0xa5) { /* YEN SIGN */
- WRITE1(0x5c);
- NEXT(1, 1)
- continue;
- } else if (c == 0x203e) { /* OVERLINE */
- WRITE1(0x7e);
- NEXT(1, 1)
- continue;
- }
+ else if (c == 0xff3c) /* FULL-WIDTH REVERSE SOLIDUS */
+ code = 0x2140;
+ else if (c == 0xa5) { /* YEN SIGN */
+ WRITE1(0x5c);
+ NEXT(1, 1)
+ continue;
+ } else if (c == 0x203e) { /* OVERLINE */
+ WRITE1(0x7e);
+ NEXT(1, 1)
+ continue;
+ }
#endif
- else
- return 1;
-
- if (code & 0x8000) {
- /* JIS X 0212 */
- WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
- NEXT(1, 3)
- } else {
- /* JIS X 0208 */
- WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
- NEXT(1, 2)
- }
- }
-
- return 0;
+ else
+ return 1;
+
+ if (code & 0x8000) {
+ /* JIS X 0212 */
+ WRITE3(0x8f, code >> 8, (code & 0xFF) | 0x80)
+ NEXT(1, 3)
+ } else {
+ /* JIS X 0208 */
+ WRITE2((code >> 8) | 0x80, (code & 0xFF) | 0x80)
+ NEXT(1, 2)
+ }
+ }
+
+ return 0;
}
DECODER(euc_jp)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- if (c == 0x8e) {
- /* JIS X 0201 half-width katakana */
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 >= 0xa1 && c2 <= 0xdf) {
- OUT1(0xfec0 + c2)
- NEXT(2, 1)
- }
- else
- return 2;
- }
- else if (c == 0x8f) {
- unsigned char c2, c3;
-
- REQUIRE_INBUF(3)
- c2 = IN2;
- c3 = IN3;
- /* JIS X 0212 */
- TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) {
- NEXT(3, 1)
- }
- else
- return 3;
- }
- else {
- unsigned char c2;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- /* JIS X 0208 */
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ if (c == 0x8e) {
+ /* JIS X 0201 half-width katakana */
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 >= 0xa1 && c2 <= 0xdf) {
+ OUT1(0xfec0 + c2)
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+ else if (c == 0x8f) {
+ unsigned char c2, c3;
+
+ REQUIRE_INBUF(3)
+ c2 = IN2;
+ c3 = IN3;
+ /* JIS X 0212 */
+ TRYMAP_DEC(jisx0212, **outbuf, c2 ^ 0x80, c3 ^ 0x80) {
+ NEXT(3, 1)
+ }
+ else
+ return 3;
+ }
+ else {
+ unsigned char c2;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ /* JIS X 0208 */
#ifndef STRICT_BUILD
- if (c == 0xa1 && c2 == 0xc0)
- /* FULL-WIDTH REVERSE SOLIDUS */
- **outbuf = 0xff3c;
- else
+ if (c == 0xa1 && c2 == 0xc0)
+ /* FULL-WIDTH REVERSE SOLIDUS */
+ **outbuf = 0xff3c;
+ else
#endif
- TRYMAP_DEC(jisx0208, **outbuf,
- c ^ 0x80, c2 ^ 0x80) ;
- else return 2;
- NEXT(2, 1)
- }
- }
-
- return 0;
+ TRYMAP_DEC(jisx0208, **outbuf,
+ c ^ 0x80, c2 ^ 0x80) ;
+ else return 2;
+ NEXT(2, 1)
+ }
+ }
+
+ return 0;
}
@@ -432,105 +432,105 @@ DECODER(euc_jp)
ENCODER(shift_jis)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
- unsigned char c1, c2;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+ unsigned char c1, c2;
#ifdef STRICT_BUILD
- JISX0201_R_ENCODE(c, code)
+ JISX0201_R_ENCODE(c, code)
#else
- if (c < 0x80) code = c;
- else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */
- else if (c == 0x203e) code = 0x7e; /* OVERLINE */
+ if (c < 0x80) code = c;
+ else if (c == 0x00a5) code = 0x5c; /* YEN SIGN */
+ else if (c == 0x203e) code = 0x7e; /* OVERLINE */
#endif
- else JISX0201_K_ENCODE(c, code)
- else UCS4INVALID(c)
- else code = NOCHAR;
+ else JISX0201_K_ENCODE(c, code)
+ else UCS4INVALID(c)
+ else code = NOCHAR;
- if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
- REQUIRE_OUTBUF(1)
+ if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
+ REQUIRE_OUTBUF(1)
- OUT1((unsigned char)code)
- NEXT(1, 1)
- continue;
- }
+ OUT1((unsigned char)code)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_OUTBUF(2)
+ REQUIRE_OUTBUF(2)
- if (code == NOCHAR) {
- TRYMAP_ENC(jisxcommon, code, c);
+ if (code == NOCHAR) {
+ TRYMAP_ENC(jisxcommon, code, c);
#ifndef STRICT_BUILD
- else if (c == 0xff3c)
- code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */
+ else if (c == 0xff3c)
+ code = 0x2140; /* FULL-WIDTH REVERSE SOLIDUS */
#endif
- else
- return 1;
-
- if (code & 0x8000) /* MSB set: JIS X 0212 */
- return 1;
- }
-
- c1 = code >> 8;
- c2 = code & 0xff;
- c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
- c1 = (c1 - 0x21) >> 1;
- OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
- OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
- NEXT(1, 2)
- }
-
- return 0;
+ else
+ return 1;
+
+ if (code & 0x8000) /* MSB set: JIS X 0212 */
+ return 1;
+ }
+
+ c1 = code >> 8;
+ c2 = code & 0xff;
+ c2 = (((c1 - 0x21) & 1) ? 0x5e : 0) + (c2 - 0x21);
+ c1 = (c1 - 0x21) >> 1;
+ OUT1(c1 < 0x1f ? c1 + 0x81 : c1 + 0xc1)
+ OUT2(c2 < 0x3f ? c2 + 0x40 : c2 + 0x41)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(shift_jis)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
#ifdef STRICT_BUILD
- JISX0201_R_DECODE(c, **outbuf)
+ JISX0201_R_DECODE(c, **outbuf)
#else
- if (c < 0x80) **outbuf = c;
+ if (c < 0x80) **outbuf = c;
#endif
- else JISX0201_K_DECODE(c, **outbuf)
- else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
- unsigned char c1, c2;
+ else JISX0201_K_DECODE(c, **outbuf)
+ else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xea)){
+ unsigned char c1, c2;
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
- return 2;
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
+ return 2;
- c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
- c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
- c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21);
- c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
+ c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
+ c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
+ c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1) + 0x21);
+ c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
#ifndef STRICT_BUILD
- if (c1 == 0x21 && c2 == 0x40) {
- /* FULL-WIDTH REVERSE SOLIDUS */
- OUT1(0xff3c)
- NEXT(2, 1)
- continue;
- }
+ if (c1 == 0x21 && c2 == 0x40) {
+ /* FULL-WIDTH REVERSE SOLIDUS */
+ OUT1(0xff3c)
+ NEXT(2, 1)
+ continue;
+ }
#endif
- TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
- NEXT(2, 1)
- continue;
- }
- else
- return 2;
- }
- else
- return 2;
-
- NEXT(1, 1) /* JIS X 0201 */
- }
-
- return 0;
+ TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
+ NEXT(2, 1)
+ continue;
+ }
+ else
+ return 2;
+ }
+ else
+ return 2;
+
+ NEXT(1, 1) /* JIS X 0201 */
+ }
+
+ return 0;
}
@@ -540,167 +540,167 @@ DECODER(shift_jis)
ENCODER(shift_jis_2004)
{
- while (inleft > 0) {
- ucs4_t c = IN1;
- DBCHAR code = NOCHAR;
- int c1, c2;
- Py_ssize_t insize;
-
- JISX0201_ENCODE(c, code)
- else DECODE_SURROGATE(c)
-
- if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
- WRITE1((unsigned char)code)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_OUTBUF(2)
- insize = GET_INSIZE(c);
-
- if (code == NOCHAR) {
- if (c <= 0xffff) {
- EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
- else TRYMAP_ENC(jisx0213_bmp, code, c) {
- if (code == MULTIC) {
- if (inleft < 2) {
- if (flags & MBENC_FLUSH) {
- code = find_pairencmap
- ((ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- }
- else
- return MBERR_TOOFEW;
- }
- else {
- code = find_pairencmap(
- (ucs2_t)c, IN2,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV) {
- code = find_pairencmap(
- (ucs2_t)c, 0,
- jisx0213_pair_encmap,
- JISX0213_ENCPAIRS);
- if (code == DBCINV)
- return 1;
- }
- else
- insize = 2;
- }
- }
- }
- else TRYMAP_ENC(jisxcommon, code, c) {
- /* abandon JIS X 0212 codes */
- if (code & 0x8000)
- return 1;
- }
- else return 1;
- }
- else if (c >> 16 == EMPBASE >> 16) {
- EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
- else TRYMAP_ENC(jisx0213_emp, code, c&0xffff);
- else return insize;
- }
- else
- return insize;
- }
-
- c1 = code >> 8;
- c2 = (code & 0xff) - 0x21;
-
- if (c1 & 0x80) { /* Plane 2 */
- if (c1 >= 0xee) c1 -= 0x87;
- else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49;
- else c1 -= 0x43;
- }
- else /* Plane 1 */
- c1 -= 0x21;
-
- if (c1 & 1) c2 += 0x5e;
- c1 >>= 1;
- OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1))
- OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41))
-
- NEXT(insize, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ ucs4_t c = IN1;
+ DBCHAR code = NOCHAR;
+ int c1, c2;
+ Py_ssize_t insize;
+
+ JISX0201_ENCODE(c, code)
+ else DECODE_SURROGATE(c)
+
+ if (code < 0x80 || (code >= 0xa1 && code <= 0xdf)) {
+ WRITE1((unsigned char)code)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_OUTBUF(2)
+ insize = GET_INSIZE(c);
+
+ if (code == NOCHAR) {
+ if (c <= 0xffff) {
+ EMULATE_JISX0213_2000_ENCODE_BMP(code, c)
+ else TRYMAP_ENC(jisx0213_bmp, code, c) {
+ if (code == MULTIC) {
+ if (inleft < 2) {
+ if (flags & MBENC_FLUSH) {
+ code = find_pairencmap
+ ((ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ }
+ else
+ return MBERR_TOOFEW;
+ }
+ else {
+ code = find_pairencmap(
+ (ucs2_t)c, IN2,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV) {
+ code = find_pairencmap(
+ (ucs2_t)c, 0,
+ jisx0213_pair_encmap,
+ JISX0213_ENCPAIRS);
+ if (code == DBCINV)
+ return 1;
+ }
+ else
+ insize = 2;
+ }
+ }
+ }
+ else TRYMAP_ENC(jisxcommon, code, c) {
+ /* abandon JIS X 0212 codes */
+ if (code & 0x8000)
+ return 1;
+ }
+ else return 1;
+ }
+ else if (c >> 16 == EMPBASE >> 16) {
+ EMULATE_JISX0213_2000_ENCODE_EMP(code, c)
+ else TRYMAP_ENC(jisx0213_emp, code, c&0xffff);
+ else return insize;
+ }
+ else
+ return insize;
+ }
+
+ c1 = code >> 8;
+ c2 = (code & 0xff) - 0x21;
+
+ if (c1 & 0x80) { /* Plane 2 */
+ if (c1 >= 0xee) c1 -= 0x87;
+ else if (c1 >= 0xac || c1 == 0xa8) c1 -= 0x49;
+ else c1 -= 0x43;
+ }
+ else /* Plane 1 */
+ c1 -= 0x21;
+
+ if (c1 & 1) c2 += 0x5e;
+ c1 >>= 1;
+ OUT1(c1 + (c1 < 0x1f ? 0x81 : 0xc1))
+ OUT2(c2 + (c2 < 0x3f ? 0x40 : 0x41))
+
+ NEXT(insize, 2)
+ }
+
+ return 0;
}
DECODER(shift_jis_2004)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- REQUIRE_OUTBUF(1)
- JISX0201_DECODE(c, **outbuf)
- else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){
- unsigned char c1, c2;
- ucs4_t code;
-
- REQUIRE_INBUF(2)
- c2 = IN2;
- if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
- return 2;
-
- c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
- c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
- c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1));
- c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
-
- if (c1 < 0x5e) { /* Plane 1 */
- c1 += 0x21;
- EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf,
- c1, c2)
- else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
- NEXT_OUT(1)
- }
- else TRYMAP_DEC(jisx0213_1_bmp, **outbuf,
- c1, c2) {
- NEXT_OUT(1)
- }
- else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) {
- WRITEUCS4(EMPBASE | code)
- }
- else TRYMAP_DEC(jisx0213_pair, code, c1, c2) {
- WRITE2(code >> 16, code & 0xffff)
- NEXT_OUT(2)
- }
- else
- return 2;
- NEXT_IN(2)
- }
- else { /* Plane 2 */
- if (c1 >= 0x67) c1 += 0x07;
- else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37;
- else c1 -= 0x3d;
-
- EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf,
- c1, c2)
- else TRYMAP_DEC(jisx0213_2_bmp, **outbuf,
- c1, c2) ;
- else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) {
- WRITEUCS4(EMPBASE | code)
- NEXT_IN(2)
- continue;
- }
- else
- return 2;
- NEXT(2, 1)
- }
- continue;
- }
- else
- return 2;
-
- NEXT(1, 1) /* JIS X 0201 */
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ REQUIRE_OUTBUF(1)
+ JISX0201_DECODE(c, **outbuf)
+ else if ((c >= 0x81 && c <= 0x9f) || (c >= 0xe0 && c <= 0xfc)){
+ unsigned char c1, c2;
+ ucs4_t code;
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+ if (c2 < 0x40 || (c2 > 0x7e && c2 < 0x80) || c2 > 0xfc)
+ return 2;
+
+ c1 = (c < 0xe0 ? c - 0x81 : c - 0xc1);
+ c2 = (c2 < 0x80 ? c2 - 0x40 : c2 - 0x41);
+ c1 = (2 * c1 + (c2 < 0x5e ? 0 : 1));
+ c2 = (c2 < 0x5e ? c2 : c2 - 0x5e) + 0x21;
+
+ if (c1 < 0x5e) { /* Plane 1 */
+ c1 += 0x21;
+ EMULATE_JISX0213_2000_DECODE_PLANE1(**outbuf,
+ c1, c2)
+ else TRYMAP_DEC(jisx0208, **outbuf, c1, c2) {
+ NEXT_OUT(1)
+ }
+ else TRYMAP_DEC(jisx0213_1_bmp, **outbuf,
+ c1, c2) {
+ NEXT_OUT(1)
+ }
+ else TRYMAP_DEC(jisx0213_1_emp, code, c1, c2) {
+ WRITEUCS4(EMPBASE | code)
+ }
+ else TRYMAP_DEC(jisx0213_pair, code, c1, c2) {
+ WRITE2(code >> 16, code & 0xffff)
+ NEXT_OUT(2)
+ }
+ else
+ return 2;
+ NEXT_IN(2)
+ }
+ else { /* Plane 2 */
+ if (c1 >= 0x67) c1 += 0x07;
+ else if (c1 >= 0x63 || c1 == 0x5f) c1 -= 0x37;
+ else c1 -= 0x3d;
+
+ EMULATE_JISX0213_2000_DECODE_PLANE2(**outbuf,
+ c1, c2)
+ else TRYMAP_DEC(jisx0213_2_bmp, **outbuf,
+ c1, c2) ;
+ else TRYMAP_DEC(jisx0213_2_emp, code, c1, c2) {
+ WRITEUCS4(EMPBASE | code)
+ NEXT_IN(2)
+ continue;
+ }
+ else
+ return 2;
+ NEXT(2, 1)
+ }
+ continue;
+ }
+ else
+ return 2;
+
+ NEXT(1, 1) /* JIS X 0201 */
+ }
+
+ return 0;
}
diff --git a/Modules/cjkcodecs/_codecs_kr.c b/Modules/cjkcodecs/_codecs_kr.c
index 161967e..9272e36 100644
--- a/Modules/cjkcodecs/_codecs_kr.c
+++ b/Modules/cjkcodecs/_codecs_kr.c
@@ -11,151 +11,151 @@
* EUC-KR codec
*/
-#define EUCKR_JAMO_FIRSTBYTE 0xA4
-#define EUCKR_JAMO_FILLER 0xD4
+#define EUCKR_JAMO_FIRSTBYTE 0xA4
+#define EUCKR_JAMO_FILLER 0xD4
static const unsigned char u2cgk_choseong[19] = {
- 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2,
- 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,
- 0xbc, 0xbd, 0xbe
+ 0xa1, 0xa2, 0xa4, 0xa7, 0xa8, 0xa9, 0xb1, 0xb2,
+ 0xb3, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xbb,
+ 0xbc, 0xbd, 0xbe
};
static const unsigned char u2cgk_jungseong[21] = {
- 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
- 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
- 0xcf, 0xd0, 0xd1, 0xd2, 0xd3
+ 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6,
+ 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce,
+ 0xcf, 0xd0, 0xd1, 0xd2, 0xd3
};
static const unsigned char u2cgk_jongseong[28] = {
- 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
- 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0,
- 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba,
- 0xbb, 0xbc, 0xbd, 0xbe
+ 0xd4, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
+ 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb0,
+ 0xb1, 0xb2, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xba,
+ 0xbb, 0xbc, 0xbd, 0xbe
};
ENCODER(euc_kr)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(cp949, code, c);
- else return 1;
-
- if ((code & 0x8000) == 0) {
- /* KS X 1001 coded character */
- OUT1((code >> 8) | 0x80)
- OUT2((code & 0xFF) | 0x80)
- NEXT(1, 2)
- }
- else { /* Mapping is found in CP949 extension,
- * but we encode it in KS X 1001:1998 Annex 3,
- * make-up sequence for EUC-KR. */
-
- REQUIRE_OUTBUF(8)
-
- /* syllable composition precedence */
- OUT1(EUCKR_JAMO_FIRSTBYTE)
- OUT2(EUCKR_JAMO_FILLER)
-
- /* All codepoints in CP949 extension are in unicode
- * Hangul Syllable area. */
- assert(0xac00 <= c && c <= 0xd7a3);
- c -= 0xac00;
-
- OUT3(EUCKR_JAMO_FIRSTBYTE)
- OUT4(u2cgk_choseong[c / 588])
- NEXT_OUT(4)
-
- OUT1(EUCKR_JAMO_FIRSTBYTE)
- OUT2(u2cgk_jungseong[(c / 28) % 21])
- OUT3(EUCKR_JAMO_FIRSTBYTE)
- OUT4(u2cgk_jongseong[c % 28])
- NEXT(1, 4)
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(cp949, code, c);
+ else return 1;
+
+ if ((code & 0x8000) == 0) {
+ /* KS X 1001 coded character */
+ OUT1((code >> 8) | 0x80)
+ OUT2((code & 0xFF) | 0x80)
+ NEXT(1, 2)
+ }
+ else { /* Mapping is found in CP949 extension,
+ * but we encode it in KS X 1001:1998 Annex 3,
+ * make-up sequence for EUC-KR. */
+
+ REQUIRE_OUTBUF(8)
+
+ /* syllable composition precedence */
+ OUT1(EUCKR_JAMO_FIRSTBYTE)
+ OUT2(EUCKR_JAMO_FILLER)
+
+ /* All codepoints in CP949 extension are in unicode
+ * Hangul Syllable area. */
+ assert(0xac00 <= c && c <= 0xd7a3);
+ c -= 0xac00;
+
+ OUT3(EUCKR_JAMO_FIRSTBYTE)
+ OUT4(u2cgk_choseong[c / 588])
+ NEXT_OUT(4)
+
+ OUT1(EUCKR_JAMO_FIRSTBYTE)
+ OUT2(u2cgk_jungseong[(c / 28) % 21])
+ OUT3(EUCKR_JAMO_FIRSTBYTE)
+ OUT4(u2cgk_jongseong[c % 28])
+ NEXT(1, 4)
+ }
+ }
+
+ return 0;
}
-#define NONE 127
+#define NONE 127
static const unsigned char cgk2u_choseong[] = { /* [A1, BE] */
- 0, 1, NONE, 2, NONE, NONE, 3, 4,
- 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
- 6, 7, 8, NONE, 9, 10, 11, 12,
- 13, 14, 15, 16, 17, 18
+ 0, 1, NONE, 2, NONE, NONE, 3, 4,
+ 5, NONE, NONE, NONE, NONE, NONE, NONE, NONE,
+ 6, 7, 8, NONE, 9, 10, 11, 12,
+ 13, 14, 15, 16, 17, 18
};
static const unsigned char cgk2u_jongseong[] = { /* [A1, BE] */
- 1, 2, 3, 4, 5, 6, 7, NONE,
- 8, 9, 10, 11, 12, 13, 14, 15,
- 16, 17, NONE, 18, 19, 20, 21, 22,
- NONE, 23, 24, 25, 26, 27
+ 1, 2, 3, 4, 5, 6, 7, NONE,
+ 8, 9, 10, 11, 12, 13, 14, 15,
+ 16, 17, NONE, 18, 19, 20, 21, 22,
+ NONE, 23, 24, 25, 26, 27
};
DECODER(euc_kr)
{
- while (inleft > 0) {
- unsigned char c = IN1;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
-
- if (c == EUCKR_JAMO_FIRSTBYTE &&
- IN2 == EUCKR_JAMO_FILLER) {
- /* KS X 1001:1998 Annex 3 make-up sequence */
- DBCHAR cho, jung, jong;
-
- REQUIRE_INBUF(8)
- if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE ||
- (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE ||
- (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE)
- return 8;
-
- c = (*inbuf)[3];
- if (0xa1 <= c && c <= 0xbe)
- cho = cgk2u_choseong[c - 0xa1];
- else
- cho = NONE;
-
- c = (*inbuf)[5];
- jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE;
-
- c = (*inbuf)[7];
- if (c == EUCKR_JAMO_FILLER)
- jong = 0;
- else if (0xa1 <= c && c <= 0xbe)
- jong = cgk2u_jongseong[c - 0xa1];
- else
- jong = NONE;
-
- if (cho == NONE || jung == NONE || jong == NONE)
- return 8;
-
- OUT1(0xac00 + cho*588 + jung*28 + jong);
- NEXT(8, 1)
- }
- else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
- NEXT(2, 1)
- }
- else
- return 2;
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+
+ if (c == EUCKR_JAMO_FIRSTBYTE &&
+ IN2 == EUCKR_JAMO_FILLER) {
+ /* KS X 1001:1998 Annex 3 make-up sequence */
+ DBCHAR cho, jung, jong;
+
+ REQUIRE_INBUF(8)
+ if ((*inbuf)[2] != EUCKR_JAMO_FIRSTBYTE ||
+ (*inbuf)[4] != EUCKR_JAMO_FIRSTBYTE ||
+ (*inbuf)[6] != EUCKR_JAMO_FIRSTBYTE)
+ return 8;
+
+ c = (*inbuf)[3];
+ if (0xa1 <= c && c <= 0xbe)
+ cho = cgk2u_choseong[c - 0xa1];
+ else
+ cho = NONE;
+
+ c = (*inbuf)[5];
+ jung = (0xbf <= c && c <= 0xd3) ? c - 0xbf : NONE;
+
+ c = (*inbuf)[7];
+ if (c == EUCKR_JAMO_FILLER)
+ jong = 0;
+ else if (0xa1 <= c && c <= 0xbe)
+ jong = cgk2u_jongseong[c - 0xa1];
+ else
+ jong = NONE;
+
+ if (cho == NONE || jung == NONE || jong == NONE)
+ return 8;
+
+ OUT1(0xac00 + cho*588 + jung*28 + jong);
+ NEXT(8, 1)
+ }
+ else TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80) {
+ NEXT(2, 1)
+ }
+ else
+ return 2;
+ }
+
+ return 0;
}
#undef NONE
@@ -166,54 +166,54 @@ DECODER(euc_kr)
ENCODER(cp949)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(cp949, code, c);
- else return 1;
-
- OUT1((code >> 8) | 0x80)
- if (code & 0x8000)
- OUT2(code & 0xFF) /* MSB set: CP949 */
- else
- OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(cp949, code, c);
+ else return 1;
+
+ OUT1((code >> 8) | 0x80)
+ if (code & 0x8000)
+ OUT2(code & 0xFF) /* MSB set: CP949 */
+ else
+ OUT2((code & 0xFF) | 0x80) /* MSB unset: ks x 1001 */
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(cp949)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
- TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80);
- else TRYMAP_DEC(cp949ext, **outbuf, c, IN2);
- else return 2;
+ REQUIRE_INBUF(2)
+ TRYMAP_DEC(ksx1001, **outbuf, c ^ 0x80, IN2 ^ 0x80);
+ else TRYMAP_DEC(cp949ext, **outbuf, c, IN2);
+ else return 2;
- NEXT(2, 1)
- }
+ NEXT(2, 1)
+ }
- return 0;
+ return 0;
}
@@ -250,58 +250,58 @@ static const DBCHAR u2johabjamo[] = {
ENCODER(johab)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
-
- if (c >= 0xac00 && c <= 0xd7a3) {
- c -= 0xac00;
- code = 0x8000 |
- (u2johabidx_choseong[c / 588] << 10) |
- (u2johabidx_jungseong[(c / 28) % 21] << 5) |
- u2johabidx_jongseong[c % 28];
- }
- else if (c >= 0x3131 && c <= 0x3163)
- code = u2johabjamo[c - 0x3131];
- else TRYMAP_ENC(cp949, code, c) {
- unsigned char c1, c2, t2;
- unsigned short t1;
-
- assert((code & 0x8000) == 0);
- c1 = code >> 8;
- c2 = code & 0xff;
- if (((c1 >= 0x21 && c1 <= 0x2c) ||
- (c1 >= 0x4a && c1 <= 0x7d)) &&
- (c2 >= 0x21 && c2 <= 0x7e)) {
- t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) :
- (c1 - 0x21 + 0x197));
- t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21);
- OUT1(t1 >> 1)
- OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43)
- NEXT(1, 2)
- continue;
- }
- else
- return 1;
- }
- else
- return 1;
-
- OUT1(code >> 8)
- OUT2(code & 0xff)
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+
+ if (c >= 0xac00 && c <= 0xd7a3) {
+ c -= 0xac00;
+ code = 0x8000 |
+ (u2johabidx_choseong[c / 588] << 10) |
+ (u2johabidx_jungseong[(c / 28) % 21] << 5) |
+ u2johabidx_jongseong[c % 28];
+ }
+ else if (c >= 0x3131 && c <= 0x3163)
+ code = u2johabjamo[c - 0x3131];
+ else TRYMAP_ENC(cp949, code, c) {
+ unsigned char c1, c2, t2;
+ unsigned short t1;
+
+ assert((code & 0x8000) == 0);
+ c1 = code >> 8;
+ c2 = code & 0xff;
+ if (((c1 >= 0x21 && c1 <= 0x2c) ||
+ (c1 >= 0x4a && c1 <= 0x7d)) &&
+ (c2 >= 0x21 && c2 <= 0x7e)) {
+ t1 = (c1 < 0x4a ? (c1 - 0x21 + 0x1b2) :
+ (c1 - 0x21 + 0x197));
+ t2 = ((t1 & 1) ? 0x5e : 0) + (c2 - 0x21);
+ OUT1(t1 >> 1)
+ OUT2(t2 < 0x4e ? t2 + 0x31 : t2 + 0x43)
+ NEXT(1, 2)
+ continue;
+ }
+ else
+ return 1;
+ }
+ else
+ return 1;
+
+ OUT1(code >> 8)
+ OUT2(code & 0xff)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
#define FILL 0xfd
@@ -347,91 +347,91 @@ static const unsigned char johabjamo_jongseong[32] = {
DECODER(johab)
{
- while (inleft > 0) {
- unsigned char c = IN1, c2;
-
- REQUIRE_OUTBUF(1)
-
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
-
- REQUIRE_INBUF(2)
- c2 = IN2;
-
- if (c < 0xd8) {
- /* johab hangul */
- unsigned char c_cho, c_jung, c_jong;
- unsigned char i_cho, i_jung, i_jong;
-
- c_cho = (c >> 2) & 0x1f;
- c_jung = ((c << 3) | c2 >> 5) & 0x1f;
- c_jong = c2 & 0x1f;
-
- i_cho = johabidx_choseong[c_cho];
- i_jung = johabidx_jungseong[c_jung];
- i_jong = johabidx_jongseong[c_jong];
-
- if (i_cho == NONE || i_jung == NONE || i_jong == NONE)
- return 2;
-
- /* we don't use U+1100 hangul jamo yet. */
- if (i_cho == FILL) {
- if (i_jung == FILL) {
- if (i_jong == FILL)
- OUT1(0x3000)
- else
- OUT1(0x3100 |
- johabjamo_jongseong[c_jong])
- }
- else {
- if (i_jong == FILL)
- OUT1(0x3100 |
- johabjamo_jungseong[c_jung])
- else
- return 2;
- }
- } else {
- if (i_jung == FILL) {
- if (i_jong == FILL)
- OUT1(0x3100 |
- johabjamo_choseong[c_cho])
- else
- return 2;
- }
- else
- OUT1(0xac00 +
- i_cho * 588 +
- i_jung * 28 +
- (i_jong == FILL ? 0 : i_jong))
- }
- NEXT(2, 1)
- } else {
- /* KS X 1001 except hangul jamos and syllables */
- if (c == 0xdf || c > 0xf9 ||
- c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) ||
- (c2 & 0x7f) == 0x7f ||
- (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3)))
- return 2;
- else {
- unsigned char t1, t2;
-
- t1 = (c < 0xe0 ? 2 * (c - 0xd9) :
- 2 * c - 0x197);
- t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43);
- t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21;
- t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21;
-
- TRYMAP_DEC(ksx1001, **outbuf, t1, t2);
- else return 2;
- NEXT(2, 1)
- }
- }
- }
-
- return 0;
+ while (inleft > 0) {
+ unsigned char c = IN1, c2;
+
+ REQUIRE_OUTBUF(1)
+
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
+
+ REQUIRE_INBUF(2)
+ c2 = IN2;
+
+ if (c < 0xd8) {
+ /* johab hangul */
+ unsigned char c_cho, c_jung, c_jong;
+ unsigned char i_cho, i_jung, i_jong;
+
+ c_cho = (c >> 2) & 0x1f;
+ c_jung = ((c << 3) | c2 >> 5) & 0x1f;
+ c_jong = c2 & 0x1f;
+
+ i_cho = johabidx_choseong[c_cho];
+ i_jung = johabidx_jungseong[c_jung];
+ i_jong = johabidx_jongseong[c_jong];
+
+ if (i_cho == NONE || i_jung == NONE || i_jong == NONE)
+ return 2;
+
+ /* we don't use U+1100 hangul jamo yet. */
+ if (i_cho == FILL) {
+ if (i_jung == FILL) {
+ if (i_jong == FILL)
+ OUT1(0x3000)
+ else
+ OUT1(0x3100 |
+ johabjamo_jongseong[c_jong])
+ }
+ else {
+ if (i_jong == FILL)
+ OUT1(0x3100 |
+ johabjamo_jungseong[c_jung])
+ else
+ return 2;
+ }
+ } else {
+ if (i_jung == FILL) {
+ if (i_jong == FILL)
+ OUT1(0x3100 |
+ johabjamo_choseong[c_cho])
+ else
+ return 2;
+ }
+ else
+ OUT1(0xac00 +
+ i_cho * 588 +
+ i_jung * 28 +
+ (i_jong == FILL ? 0 : i_jong))
+ }
+ NEXT(2, 1)
+ } else {
+ /* KS X 1001 except hangul jamos and syllables */
+ if (c == 0xdf || c > 0xf9 ||
+ c2 < 0x31 || (c2 >= 0x80 && c2 < 0x91) ||
+ (c2 & 0x7f) == 0x7f ||
+ (c == 0xda && (c2 >= 0xa1 && c2 <= 0xd3)))
+ return 2;
+ else {
+ unsigned char t1, t2;
+
+ t1 = (c < 0xe0 ? 2 * (c - 0xd9) :
+ 2 * c - 0x197);
+ t2 = (c2 < 0x91 ? c2 - 0x31 : c2 - 0x43);
+ t1 = t1 + (t2 < 0x5e ? 0 : 1) + 0x21;
+ t2 = (t2 < 0x5e ? t2 : t2 - 0x5e) + 0x21;
+
+ TRYMAP_DEC(ksx1001, **outbuf, t1, t2);
+ else return 2;
+ NEXT(2, 1)
+ }
+ }
+ }
+
+ return 0;
}
#undef NONE
#undef FILL
diff --git a/Modules/cjkcodecs/_codecs_tw.c b/Modules/cjkcodecs/_codecs_tw.c
index 8ccbca1..38cf723 100644
--- a/Modules/cjkcodecs/_codecs_tw.c
+++ b/Modules/cjkcodecs/_codecs_tw.c
@@ -13,52 +13,52 @@
ENCODER(big5)
{
- while (inleft > 0) {
- Py_UNICODE c = **inbuf;
- DBCHAR code;
+ while (inleft > 0) {
+ Py_UNICODE c = **inbuf;
+ DBCHAR code;
- if (c < 0x80) {
- REQUIRE_OUTBUF(1)
- **outbuf = (unsigned char)c;
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
+ if (c < 0x80) {
+ REQUIRE_OUTBUF(1)
+ **outbuf = (unsigned char)c;
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
- REQUIRE_OUTBUF(2)
+ REQUIRE_OUTBUF(2)
- TRYMAP_ENC(big5, code, c);
- else return 1;
+ TRYMAP_ENC(big5, code, c);
+ else return 1;
- OUT1(code >> 8)
- OUT2(code & 0xFF)
- NEXT(1, 2)
- }
+ OUT1(code >> 8)
+ OUT2(code & 0xFF)
+ NEXT(1, 2)
+ }
- return 0;
+ return 0;
}
DECODER(big5)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
- TRYMAP_DEC(big5, **outbuf, c, IN2) {
- NEXT(2, 1)
- }
- else return 2;
- }
+ REQUIRE_INBUF(2)
+ TRYMAP_DEC(big5, **outbuf, c, IN2) {
+ NEXT(2, 1)
+ }
+ else return 2;
+ }
- return 0;
+ return 0;
}
@@ -68,53 +68,53 @@ DECODER(big5)
ENCODER(cp950)
{
- while (inleft > 0) {
- Py_UNICODE c = IN1;
- DBCHAR code;
-
- if (c < 0x80) {
- WRITE1((unsigned char)c)
- NEXT(1, 1)
- continue;
- }
- UCS4INVALID(c)
-
- REQUIRE_OUTBUF(2)
- TRYMAP_ENC(cp950ext, code, c);
- else TRYMAP_ENC(big5, code, c);
- else return 1;
-
- OUT1(code >> 8)
- OUT2(code & 0xFF)
- NEXT(1, 2)
- }
-
- return 0;
+ while (inleft > 0) {
+ Py_UNICODE c = IN1;
+ DBCHAR code;
+
+ if (c < 0x80) {
+ WRITE1((unsigned char)c)
+ NEXT(1, 1)
+ continue;
+ }
+ UCS4INVALID(c)
+
+ REQUIRE_OUTBUF(2)
+ TRYMAP_ENC(cp950ext, code, c);
+ else TRYMAP_ENC(big5, code, c);
+ else return 1;
+
+ OUT1(code >> 8)
+ OUT2(code & 0xFF)
+ NEXT(1, 2)
+ }
+
+ return 0;
}
DECODER(cp950)
{
- while (inleft > 0) {
- unsigned char c = IN1;
+ while (inleft > 0) {
+ unsigned char c = IN1;
- REQUIRE_OUTBUF(1)
+ REQUIRE_OUTBUF(1)
- if (c < 0x80) {
- OUT1(c)
- NEXT(1, 1)
- continue;
- }
+ if (c < 0x80) {
+ OUT1(c)
+ NEXT(1, 1)
+ continue;
+ }
- REQUIRE_INBUF(2)
+ REQUIRE_INBUF(2)
- TRYMAP_DEC(cp950ext, **outbuf, c, IN2);
- else TRYMAP_DEC(big5, **outbuf, c, IN2);
- else return 2;
+ TRYMAP_DEC(cp950ext, **outbuf, c, IN2);
+ else TRYMAP_DEC(big5, **outbuf, c, IN2);
+ else return 2;
- NEXT(2, 1)
- }
+ NEXT(2, 1)
+ }
- return 0;
+ return 0;
}
diff --git a/Modules/cjkcodecs/alg_jisx0201.h b/Modules/cjkcodecs/alg_jisx0201.h
index 1fca06b..0bc7db5 100644
--- a/Modules/cjkcodecs/alg_jisx0201.h
+++ b/Modules/cjkcodecs/alg_jisx0201.h
@@ -1,24 +1,24 @@
-#define JISX0201_R_ENCODE(c, assi) \
- if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \
- (assi) = (c); \
- else if ((c) == 0x00a5) (assi) = 0x5c; \
- else if ((c) == 0x203e) (assi) = 0x7e;
-#define JISX0201_K_ENCODE(c, assi) \
- if ((c) >= 0xff61 && (c) <= 0xff9f) \
- (assi) = (c) - 0xfec0;
-#define JISX0201_ENCODE(c, assi) \
- JISX0201_R_ENCODE(c, assi) \
- else JISX0201_K_ENCODE(c, assi)
+#define JISX0201_R_ENCODE(c, assi) \
+ if ((c) < 0x80 && (c) != 0x5c && (c) != 0x7e) \
+ (assi) = (c); \
+ else if ((c) == 0x00a5) (assi) = 0x5c; \
+ else if ((c) == 0x203e) (assi) = 0x7e;
+#define JISX0201_K_ENCODE(c, assi) \
+ if ((c) >= 0xff61 && (c) <= 0xff9f) \
+ (assi) = (c) - 0xfec0;
+#define JISX0201_ENCODE(c, assi) \
+ JISX0201_R_ENCODE(c, assi) \
+ else JISX0201_K_ENCODE(c, assi)
-#define JISX0201_R_DECODE(c, assi) \
- if ((c) < 0x5c) (assi) = (c); \
- else if ((c) == 0x5c) (assi) = 0x00a5; \
- else if ((c) < 0x7e) (assi) = (c); \
- else if ((c) == 0x7e) (assi) = 0x203e; \
- else if ((c) == 0x7f) (assi) = 0x7f;
-#define JISX0201_K_DECODE(c, assi) \
- if ((c) >= 0xa1 && (c) <= 0xdf) \
- (assi) = 0xfec0 + (c);
-#define JISX0201_DECODE(c, assi) \
- JISX0201_R_DECODE(c, assi) \
- else JISX0201_K_DECODE(c, assi)
+#define JISX0201_R_DECODE(c, assi) \
+ if ((c) < 0x5c) (assi) = (c); \
+ else if ((c) == 0x5c) (assi) = 0x00a5; \
+ else if ((c) < 0x7e) (assi) = (c); \
+ else if ((c) == 0x7e) (assi) = 0x203e; \
+ else if ((c) == 0x7f) (assi) = 0x7f;
+#define JISX0201_K_DECODE(c, assi) \
+ if ((c) >= 0xa1 && (c) <= 0xdf) \
+ (assi) = 0xfec0 + (c);
+#define JISX0201_DECODE(c, assi) \
+ JISX0201_R_DECODE(c, assi) \
+ else JISX0201_K_DECODE(c, assi)
diff --git a/Modules/cjkcodecs/cjkcodecs.h b/Modules/cjkcodecs/cjkcodecs.h
index 236c3fe..7e8390a 100644
--- a/Modules/cjkcodecs/cjkcodecs.h
+++ b/Modules/cjkcodecs/cjkcodecs.h
@@ -13,12 +13,12 @@
/* a unicode "undefined" codepoint */
-#define UNIINV 0xFFFE
+#define UNIINV 0xFFFE
/* internal-use DBCS codepoints which aren't used by any charsets */
-#define NOCHAR 0xFFFF
-#define MULTIC 0xFFFE
-#define DBCINV 0xFFFD
+#define NOCHAR 0xFFFF
+#define MULTIC 0xFFFE
+#define DBCINV 0xFFFD
/* shorter macros to save source size of mapping tables */
#define U UNIINV
@@ -27,94 +27,94 @@
#define D DBCINV
struct dbcs_index {
- const ucs2_t *map;
- unsigned char bottom, top;
+ const ucs2_t *map;
+ unsigned char bottom, top;
};
typedef struct dbcs_index decode_map;
struct widedbcs_index {
- const ucs4_t *map;
- unsigned char bottom, top;
+ const ucs4_t *map;
+ unsigned char bottom, top;
};
typedef struct widedbcs_index widedecode_map;
struct unim_index {
- const DBCHAR *map;
- unsigned char bottom, top;
+ const DBCHAR *map;
+ unsigned char bottom, top;
};
typedef struct unim_index encode_map;
struct unim_index_bytebased {
- const unsigned char *map;
- unsigned char bottom, top;
+ const unsigned char *map;
+ unsigned char bottom, top;
};
struct dbcs_map {
- const char *charset;
- const struct unim_index *encmap;
- const struct dbcs_index *decmap;
+ const char *charset;
+ const struct unim_index *encmap;
+ const struct dbcs_index *decmap;
};
struct pair_encodemap {
- ucs4_t uniseq;
- DBCHAR code;
+ ucs4_t uniseq;
+ DBCHAR code;
};
static const MultibyteCodec *codec_list;
static const struct dbcs_map *mapping_list;
-#define CODEC_INIT(encoding) \
- static int encoding##_codec_init(const void *config)
-
-#define ENCODER_INIT(encoding) \
- static int encoding##_encode_init( \
- MultibyteCodec_State *state, const void *config)
-#define ENCODER(encoding) \
- static Py_ssize_t encoding##_encode( \
- MultibyteCodec_State *state, const void *config, \
- const Py_UNICODE **inbuf, Py_ssize_t inleft, \
- unsigned char **outbuf, Py_ssize_t outleft, int flags)
-#define ENCODER_RESET(encoding) \
- static Py_ssize_t encoding##_encode_reset( \
- MultibyteCodec_State *state, const void *config, \
- unsigned char **outbuf, Py_ssize_t outleft)
-
-#define DECODER_INIT(encoding) \
- static int encoding##_decode_init( \
- MultibyteCodec_State *state, const void *config)
-#define DECODER(encoding) \
- static Py_ssize_t encoding##_decode( \
- MultibyteCodec_State *state, const void *config, \
- const unsigned char **inbuf, Py_ssize_t inleft, \
- Py_UNICODE **outbuf, Py_ssize_t outleft)
-#define DECODER_RESET(encoding) \
- static Py_ssize_t encoding##_decode_reset( \
- MultibyteCodec_State *state, const void *config)
+#define CODEC_INIT(encoding) \
+ static int encoding##_codec_init(const void *config)
+
+#define ENCODER_INIT(encoding) \
+ static int encoding##_encode_init( \
+ MultibyteCodec_State *state, const void *config)
+#define ENCODER(encoding) \
+ static Py_ssize_t encoding##_encode( \
+ MultibyteCodec_State *state, const void *config, \
+ const Py_UNICODE **inbuf, Py_ssize_t inleft, \
+ unsigned char **outbuf, Py_ssize_t outleft, int flags)
+#define ENCODER_RESET(encoding) \
+ static Py_ssize_t encoding##_encode_reset( \
+ MultibyteCodec_State *state, const void *config, \
+ unsigned char **outbuf, Py_ssize_t outleft)
+
+#define DECODER_INIT(encoding) \
+ static int encoding##_decode_init( \
+ MultibyteCodec_State *state, const void *config)
+#define DECODER(encoding) \
+ static Py_ssize_t encoding##_decode( \
+ MultibyteCodec_State *state, const void *config, \
+ const unsigned char **inbuf, Py_ssize_t inleft, \
+ Py_UNICODE **outbuf, Py_ssize_t outleft)
+#define DECODER_RESET(encoding) \
+ static Py_ssize_t encoding##_decode_reset( \
+ MultibyteCodec_State *state, const void *config)
#if Py_UNICODE_SIZE == 4
-#define UCS4INVALID(code) \
- if ((code) > 0xFFFF) \
- return 1;
+#define UCS4INVALID(code) \
+ if ((code) > 0xFFFF) \
+ return 1;
#else
-#define UCS4INVALID(code) \
- if (0) ;
+#define UCS4INVALID(code) \
+ if (0) ;
#endif
-#define NEXT_IN(i) \
- (*inbuf) += (i); \
- (inleft) -= (i);
-#define NEXT_OUT(o) \
- (*outbuf) += (o); \
- (outleft) -= (o);
-#define NEXT(i, o) \
- NEXT_IN(i) NEXT_OUT(o)
-
-#define REQUIRE_INBUF(n) \
- if (inleft < (n)) \
- return MBERR_TOOFEW;
-#define REQUIRE_OUTBUF(n) \
- if (outleft < (n)) \
- return MBERR_TOOSMALL;
+#define NEXT_IN(i) \
+ (*inbuf) += (i); \
+ (inleft) -= (i);
+#define NEXT_OUT(o) \
+ (*outbuf) += (o); \
+ (outleft) -= (o);
+#define NEXT(i, o) \
+ NEXT_IN(i) NEXT_OUT(o)
+
+#define REQUIRE_INBUF(n) \
+ if (inleft < (n)) \
+ return MBERR_TOOFEW;
+#define REQUIRE_OUTBUF(n) \
+ if (outleft < (n)) \
+ return MBERR_TOOSMALL;
#define IN1 ((*inbuf)[0])
#define IN2 ((*inbuf)[1])
@@ -126,273 +126,273 @@ static const struct dbcs_map *mapping_list;
#define OUT3(c) ((*outbuf)[2]) = (c);
#define OUT4(c) ((*outbuf)[3]) = (c);
-#define WRITE1(c1) \
- REQUIRE_OUTBUF(1) \
- (*outbuf)[0] = (c1);
-#define WRITE2(c1, c2) \
- REQUIRE_OUTBUF(2) \
- (*outbuf)[0] = (c1); \
- (*outbuf)[1] = (c2);
-#define WRITE3(c1, c2, c3) \
- REQUIRE_OUTBUF(3) \
- (*outbuf)[0] = (c1); \
- (*outbuf)[1] = (c2); \
- (*outbuf)[2] = (c3);
-#define WRITE4(c1, c2, c3, c4) \
- REQUIRE_OUTBUF(4) \
- (*outbuf)[0] = (c1); \
- (*outbuf)[1] = (c2); \
- (*outbuf)[2] = (c3); \
- (*outbuf)[3] = (c4);
+#define WRITE1(c1) \
+ REQUIRE_OUTBUF(1) \
+ (*outbuf)[0] = (c1);
+#define WRITE2(c1, c2) \
+ REQUIRE_OUTBUF(2) \
+ (*outbuf)[0] = (c1); \
+ (*outbuf)[1] = (c2);
+#define WRITE3(c1, c2, c3) \
+ REQUIRE_OUTBUF(3) \
+ (*outbuf)[0] = (c1); \
+ (*outbuf)[1] = (c2); \
+ (*outbuf)[2] = (c3);
+#define WRITE4(c1, c2, c3, c4) \
+ REQUIRE_OUTBUF(4) \
+ (*outbuf)[0] = (c1); \
+ (*outbuf)[1] = (c2); \
+ (*outbuf)[2] = (c3); \
+ (*outbuf)[3] = (c4);
#if Py_UNICODE_SIZE == 2
-# define WRITEUCS4(c) \
- REQUIRE_OUTBUF(2) \
- (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \
- (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \
- NEXT_OUT(2)
+# define WRITEUCS4(c) \
+ REQUIRE_OUTBUF(2) \
+ (*outbuf)[0] = 0xd800 + (((c) - 0x10000) >> 10); \
+ (*outbuf)[1] = 0xdc00 + (((c) - 0x10000) & 0x3ff); \
+ NEXT_OUT(2)
#else
-# define WRITEUCS4(c) \
- REQUIRE_OUTBUF(1) \
- **outbuf = (Py_UNICODE)(c); \
- NEXT_OUT(1)
+# define WRITEUCS4(c) \
+ REQUIRE_OUTBUF(1) \
+ **outbuf = (Py_UNICODE)(c); \
+ NEXT_OUT(1)
#endif
-#define _TRYMAP_ENC(m, assi, val) \
- ((m)->map != NULL && (val) >= (m)->bottom && \
- (val)<= (m)->top && ((assi) = (m)->map[(val) - \
- (m)->bottom]) != NOCHAR)
-#define TRYMAP_ENC_COND(charset, assi, uni) \
- _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff)
-#define TRYMAP_ENC(charset, assi, uni) \
- if TRYMAP_ENC_COND(charset, assi, uni)
-
-#define _TRYMAP_DEC(m, assi, val) \
- ((m)->map != NULL && (val) >= (m)->bottom && \
- (val)<= (m)->top && ((assi) = (m)->map[(val) - \
- (m)->bottom]) != UNIINV)
-#define TRYMAP_DEC(charset, assi, c1, c2) \
- if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2)
-
-#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \
- ((m)->map != NULL && (val) >= (m)->bottom && \
- (val)<= (m)->top && \
- ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \
- (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \
- (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1))
-#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \
- if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \
- assplane, asshi, asslo, (uni) & 0xff)
-#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \
- if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2)
+#define _TRYMAP_ENC(m, assi, val) \
+ ((m)->map != NULL && (val) >= (m)->bottom && \
+ (val)<= (m)->top && ((assi) = (m)->map[(val) - \
+ (m)->bottom]) != NOCHAR)
+#define TRYMAP_ENC_COND(charset, assi, uni) \
+ _TRYMAP_ENC(&charset##_encmap[(uni) >> 8], assi, (uni) & 0xff)
+#define TRYMAP_ENC(charset, assi, uni) \
+ if TRYMAP_ENC_COND(charset, assi, uni)
+
+#define _TRYMAP_DEC(m, assi, val) \
+ ((m)->map != NULL && (val) >= (m)->bottom && \
+ (val)<= (m)->top && ((assi) = (m)->map[(val) - \
+ (m)->bottom]) != UNIINV)
+#define TRYMAP_DEC(charset, assi, c1, c2) \
+ if _TRYMAP_DEC(&charset##_decmap[c1], assi, c2)
+
+#define _TRYMAP_ENC_MPLANE(m, assplane, asshi, asslo, val) \
+ ((m)->map != NULL && (val) >= (m)->bottom && \
+ (val)<= (m)->top && \
+ ((assplane) = (m)->map[((val) - (m)->bottom)*3]) != 0 && \
+ (((asshi) = (m)->map[((val) - (m)->bottom)*3 + 1]), 1) && \
+ (((asslo) = (m)->map[((val) - (m)->bottom)*3 + 2]), 1))
+#define TRYMAP_ENC_MPLANE(charset, assplane, asshi, asslo, uni) \
+ if _TRYMAP_ENC_MPLANE(&charset##_encmap[(uni) >> 8], \
+ assplane, asshi, asslo, (uni) & 0xff)
+#define TRYMAP_DEC_MPLANE(charset, assi, plane, c1, c2) \
+ if _TRYMAP_DEC(&charset##_decmap[plane][c1], assi, c2)
#if Py_UNICODE_SIZE == 2
-#define DECODE_SURROGATE(c) \
- if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \
- REQUIRE_INBUF(2) \
- if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \
- c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \
- ((ucs4_t)(IN2) - 0xdc00); \
- } \
- }
-#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1)
+#define DECODE_SURROGATE(c) \
+ if (c >> 10 == 0xd800 >> 10) { /* high surrogate */ \
+ REQUIRE_INBUF(2) \
+ if (IN2 >> 10 == 0xdc00 >> 10) { /* low surrogate */ \
+ c = 0x10000 + ((ucs4_t)(c - 0xd800) << 10) + \
+ ((ucs4_t)(IN2) - 0xdc00); \
+ } \
+ }
+#define GET_INSIZE(c) ((c) > 0xffff ? 2 : 1)
#else
#define DECODE_SURROGATE(c) {;}
-#define GET_INSIZE(c) 1
+#define GET_INSIZE(c) 1
#endif
#define BEGIN_MAPPINGS_LIST static const struct dbcs_map _mapping_list[] = {
#define MAPPING_ENCONLY(enc) {#enc, (void*)enc##_encmap, NULL},
#define MAPPING_DECONLY(enc) {#enc, NULL, (void*)enc##_decmap},
#define MAPPING_ENCDEC(enc) {#enc, (void*)enc##_encmap, (void*)enc##_decmap},
-#define END_MAPPINGS_LIST \
- {"", NULL, NULL} }; \
- static const struct dbcs_map *mapping_list = \
- (const struct dbcs_map *)_mapping_list;
+#define END_MAPPINGS_LIST \
+ {"", NULL, NULL} }; \
+ static const struct dbcs_map *mapping_list = \
+ (const struct dbcs_map *)_mapping_list;
#define BEGIN_CODECS_LIST static const MultibyteCodec _codec_list[] = {
-#define _STATEFUL_METHODS(enc) \
- enc##_encode, \
- enc##_encode_init, \
- enc##_encode_reset, \
- enc##_decode, \
- enc##_decode_init, \
- enc##_decode_reset,
-#define _STATELESS_METHODS(enc) \
- enc##_encode, NULL, NULL, \
- enc##_decode, NULL, NULL,
-#define CODEC_STATEFUL(enc) { \
- #enc, NULL, NULL, \
- _STATEFUL_METHODS(enc) \
+#define _STATEFUL_METHODS(enc) \
+ enc##_encode, \
+ enc##_encode_init, \
+ enc##_encode_reset, \
+ enc##_decode, \
+ enc##_decode_init, \
+ enc##_decode_reset,
+#define _STATELESS_METHODS(enc) \
+ enc##_encode, NULL, NULL, \
+ enc##_decode, NULL, NULL,
+#define CODEC_STATEFUL(enc) { \
+ #enc, NULL, NULL, \
+ _STATEFUL_METHODS(enc) \
},
-#define CODEC_STATELESS(enc) { \
- #enc, NULL, NULL, \
- _STATELESS_METHODS(enc) \
+#define CODEC_STATELESS(enc) { \
+ #enc, NULL, NULL, \
+ _STATELESS_METHODS(enc) \
},
-#define CODEC_STATELESS_WINIT(enc) { \
- #enc, NULL, \
- enc##_codec_init, \
- _STATELESS_METHODS(enc) \
+#define CODEC_STATELESS_WINIT(enc) { \
+ #enc, NULL, \
+ enc##_codec_init, \
+ _STATELESS_METHODS(enc) \
},
-#define END_CODECS_LIST \
- {"", NULL,} }; \
- static const MultibyteCodec *codec_list = \
- (const MultibyteCodec *)_codec_list;
+#define END_CODECS_LIST \
+ {"", NULL,} }; \
+ static const MultibyteCodec *codec_list = \
+ (const MultibyteCodec *)_codec_list;
static PyObject *
getmultibytecodec(void)
{
- static PyObject *cofunc = NULL;
-
- if (cofunc == NULL) {
- PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec");
- if (mod == NULL)
- return NULL;
- cofunc = PyObject_GetAttrString(mod, "__create_codec");
- Py_DECREF(mod);
- }
- return cofunc;
+ static PyObject *cofunc = NULL;
+
+ if (cofunc == NULL) {
+ PyObject *mod = PyImport_ImportModuleNoBlock("_multibytecodec");
+ if (mod == NULL)
+ return NULL;
+ cofunc = PyObject_GetAttrString(mod, "__create_codec");
+ Py_DECREF(mod);
+ }
+ return cofunc;
}
static PyObject *
getcodec(PyObject *self, PyObject *encoding)
{
- PyObject *codecobj, *r, *cofunc;
- const MultibyteCodec *codec;
- const char *enc;
-
- if (!PyString_Check(encoding)) {
- PyErr_SetString(PyExc_TypeError,
- "encoding name must be a string.");
- return NULL;
- }
-
- cofunc = getmultibytecodec();
- if (cofunc == NULL)
- return NULL;
-
- enc = PyString_AS_STRING(encoding);
- for (codec = codec_list; codec->encoding[0]; codec++)
- if (strcmp(codec->encoding, enc) == 0)
- break;
-
- if (codec->encoding[0] == '\0') {
- PyErr_SetString(PyExc_LookupError,
- "no such codec is supported.");
- return NULL;
- }
-
- codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
- if (codecobj == NULL)
- return NULL;
-
- r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL);
- Py_DECREF(codecobj);
-
- return r;
+ PyObject *codecobj, *r, *cofunc;
+ const MultibyteCodec *codec;
+ const char *enc;
+
+ if (!PyString_Check(encoding)) {
+ PyErr_SetString(PyExc_TypeError,
+ "encoding name must be a string.");
+ return NULL;
+ }
+
+ cofunc = getmultibytecodec();
+ if (cofunc == NULL)
+ return NULL;
+
+ enc = PyString_AS_STRING(encoding);
+ for (codec = codec_list; codec->encoding[0]; codec++)
+ if (strcmp(codec->encoding, enc) == 0)
+ break;
+
+ if (codec->encoding[0] == '\0') {
+ PyErr_SetString(PyExc_LookupError,
+ "no such codec is supported.");
+ return NULL;
+ }
+
+ codecobj = PyCapsule_New((void *)codec, PyMultibyteCodec_CAPSULE_NAME, NULL);
+ if (codecobj == NULL)
+ return NULL;
+
+ r = PyObject_CallFunctionObjArgs(cofunc, codecobj, NULL);
+ Py_DECREF(codecobj);
+
+ return r;
}
static struct PyMethodDef __methods[] = {
- {"getcodec", (PyCFunction)getcodec, METH_O, ""},
- {NULL, NULL},
+ {"getcodec", (PyCFunction)getcodec, METH_O, ""},
+ {NULL, NULL},
};
static int
register_maps(PyObject *module)
{
- const struct dbcs_map *h;
-
- for (h = mapping_list; h->charset[0] != '\0'; h++) {
- char mhname[256] = "__map_";
- int r;
- strcpy(mhname + sizeof("__map_") - 1, h->charset);
- r = PyModule_AddObject(module, mhname,
- PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL));
- if (r == -1)
- return -1;
- }
- return 0;
+ const struct dbcs_map *h;
+
+ for (h = mapping_list; h->charset[0] != '\0'; h++) {
+ char mhname[256] = "__map_";
+ int r;
+ strcpy(mhname + sizeof("__map_") - 1, h->charset);
+ r = PyModule_AddObject(module, mhname,
+ PyCapsule_New((void *)h, PyMultibyteCodec_CAPSULE_NAME, NULL));
+ if (r == -1)
+ return -1;
+ }
+ return 0;
}
#ifdef USING_BINARY_PAIR_SEARCH
static DBCHAR
find_pairencmap(ucs2_t body, ucs2_t modifier,
- const struct pair_encodemap *haystack, int haystacksize)
+ const struct pair_encodemap *haystack, int haystacksize)
{
- int pos, min, max;
- ucs4_t value = body << 16 | modifier;
-
- min = 0;
- max = haystacksize;
-
- for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
- if (value < haystack[pos].uniseq) {
- if (max == pos) break;
- else max = pos;
- }
- else if (value > haystack[pos].uniseq) {
- if (min == pos) break;
- else min = pos;
- }
- else
- break;
-
- if (value == haystack[pos].uniseq)
- return haystack[pos].code;
- else
- return DBCINV;
+ int pos, min, max;
+ ucs4_t value = body << 16 | modifier;
+
+ min = 0;
+ max = haystacksize;
+
+ for (pos = haystacksize >> 1; min != max; pos = (min + max) >> 1)
+ if (value < haystack[pos].uniseq) {
+ if (max == pos) break;
+ else max = pos;
+ }
+ else if (value > haystack[pos].uniseq) {
+ if (min == pos) break;
+ else min = pos;
+ }
+ else
+ break;
+
+ if (value == haystack[pos].uniseq)
+ return haystack[pos].code;
+ else
+ return DBCINV;
}
#endif
#ifdef USING_IMPORTED_MAPS
#define IMPORT_MAP(locale, charset, encmap, decmap) \
- importmap("_codecs_" #locale, "__map_" #charset, \
- (const void**)encmap, (const void**)decmap)
+ importmap("_codecs_" #locale, "__map_" #charset, \
+ (const void**)encmap, (const void**)decmap)
static int
importmap(const char *modname, const char *symbol,
- const void **encmap, const void **decmap)
+ const void **encmap, const void **decmap)
{
- PyObject *o, *mod;
-
- mod = PyImport_ImportModule((char *)modname);
- if (mod == NULL)
- return -1;
-
- o = PyObject_GetAttrString(mod, (char*)symbol);
- if (o == NULL)
- goto errorexit;
- else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) {
- PyErr_SetString(PyExc_ValueError,
- "map data must be a Capsule.");
- goto errorexit;
- }
- else {
- struct dbcs_map *map;
- map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME);
- if (encmap != NULL)
- *encmap = map->encmap;
- if (decmap != NULL)
- *decmap = map->decmap;
- Py_DECREF(o);
- }
-
- Py_DECREF(mod);
- return 0;
+ PyObject *o, *mod;
+
+ mod = PyImport_ImportModule((char *)modname);
+ if (mod == NULL)
+ return -1;
+
+ o = PyObject_GetAttrString(mod, (char*)symbol);
+ if (o == NULL)
+ goto errorexit;
+ else if (!PyCapsule_IsValid(o, PyMultibyteCodec_CAPSULE_NAME)) {
+ PyErr_SetString(PyExc_ValueError,
+ "map data must be a Capsule.");
+ goto errorexit;
+ }
+ else {
+ struct dbcs_map *map;
+ map = PyCapsule_GetPointer(o, PyMultibyteCodec_CAPSULE_NAME);
+ if (encmap != NULL)
+ *encmap = map->encmap;
+ if (decmap != NULL)
+ *decmap = map->decmap;
+ Py_DECREF(o);
+ }
+
+ Py_DECREF(mod);
+ return 0;
errorexit:
- Py_DECREF(mod);
- return -1;
+ Py_DECREF(mod);
+ return -1;
}
#endif
-#define I_AM_A_MODULE_FOR(loc) \
- void \
- init_codecs_##loc(void) \
- { \
- PyObject *m = Py_InitModule("_codecs_" #loc, __methods);\
- if (m != NULL) \
- (void)register_maps(m); \
- }
+#define I_AM_A_MODULE_FOR(loc) \
+ void \
+ init_codecs_##loc(void) \
+ { \
+ PyObject *m = Py_InitModule("_codecs_" #loc, __methods);\
+ if (m != NULL) \
+ (void)register_maps(m); \
+ }
#endif
diff --git a/Modules/cjkcodecs/emu_jisx0213_2000.h b/Modules/cjkcodecs/emu_jisx0213_2000.h
index 250c673..4227fb2 100644
--- a/Modules/cjkcodecs/emu_jisx0213_2000.h
+++ b/Modules/cjkcodecs/emu_jisx0213_2000.h
@@ -5,39 +5,39 @@
#define EMULATE_JISX0213_2000_ENCODE_INVALID 1
#endif
-#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \
- if (config == (void *)2000 && ( \
- (c) == 0x9B1C || (c) == 0x4FF1 || \
- (c) == 0x525D || (c) == 0x541E || \
- (c) == 0x5653 || (c) == 0x59F8 || \
- (c) == 0x5C5B || (c) == 0x5E77 || \
- (c) == 0x7626 || (c) == 0x7E6B)) \
- return EMULATE_JISX0213_2000_ENCODE_INVALID; \
- else if (config == (void *)2000 && (c) == 0x9B1D) \
- (assi) = 0x8000 | 0x7d3b; \
+#define EMULATE_JISX0213_2000_ENCODE_BMP(assi, c) \
+ if (config == (void *)2000 && ( \
+ (c) == 0x9B1C || (c) == 0x4FF1 || \
+ (c) == 0x525D || (c) == 0x541E || \
+ (c) == 0x5653 || (c) == 0x59F8 || \
+ (c) == 0x5C5B || (c) == 0x5E77 || \
+ (c) == 0x7626 || (c) == 0x7E6B)) \
+ return EMULATE_JISX0213_2000_ENCODE_INVALID; \
+ else if (config == (void *)2000 && (c) == 0x9B1D) \
+ (assi) = 0x8000 | 0x7d3b; \
-#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \
- if (config == (void *)2000 && (c) == 0x20B9F) \
- return EMULATE_JISX0213_2000_ENCODE_INVALID;
+#define EMULATE_JISX0213_2000_ENCODE_EMP(assi, c) \
+ if (config == (void *)2000 && (c) == 0x20B9F) \
+ return EMULATE_JISX0213_2000_ENCODE_INVALID;
#ifndef EMULATE_JISX0213_2000_DECODE_INVALID
#define EMULATE_JISX0213_2000_DECODE_INVALID 2
#endif
-#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \
- if (config == (void *)2000 && \
- (((c1) == 0x2E && (c2) == 0x21) || \
- ((c1) == 0x2F && (c2) == 0x7E) || \
- ((c1) == 0x4F && (c2) == 0x54) || \
- ((c1) == 0x4F && (c2) == 0x7E) || \
- ((c1) == 0x74 && (c2) == 0x27) || \
- ((c1) == 0x7E && (c2) == 0x7A) || \
- ((c1) == 0x7E && (c2) == 0x7B) || \
- ((c1) == 0x7E && (c2) == 0x7C) || \
- ((c1) == 0x7E && (c2) == 0x7D) || \
- ((c1) == 0x7E && (c2) == 0x7E))) \
- return EMULATE_JISX0213_2000_DECODE_INVALID;
+#define EMULATE_JISX0213_2000_DECODE_PLANE1(assi, c1, c2) \
+ if (config == (void *)2000 && \
+ (((c1) == 0x2E && (c2) == 0x21) || \
+ ((c1) == 0x2F && (c2) == 0x7E) || \
+ ((c1) == 0x4F && (c2) == 0x54) || \
+ ((c1) == 0x4F && (c2) == 0x7E) || \
+ ((c1) == 0x74 && (c2) == 0x27) || \
+ ((c1) == 0x7E && (c2) == 0x7A) || \
+ ((c1) == 0x7E && (c2) == 0x7B) || \
+ ((c1) == 0x7E && (c2) == 0x7C) || \
+ ((c1) == 0x7E && (c2) == 0x7D) || \
+ ((c1) == 0x7E && (c2) == 0x7E))) \
+ return EMULATE_JISX0213_2000_DECODE_INVALID;
-#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \
- if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \
- (assi) = 0x9B1D;
+#define EMULATE_JISX0213_2000_DECODE_PLANE2(assi, c1, c2) \
+ if (config == (void *)2000 && (c1) == 0x7D && (c2) == 0x3B) \
+ (assi) = 0x9B1D;
diff --git a/Modules/cjkcodecs/multibytecodec.c b/Modules/cjkcodecs/multibytecodec.c
index 794774b..56251f3 100644
--- a/Modules/cjkcodecs/multibytecodec.c
+++ b/Modules/cjkcodecs/multibytecodec.c
@@ -45,170 +45,170 @@ static char *incrementalkwarglist[] = {"input", "final", NULL};
static char *streamkwarglist[] = {"stream", "errors", NULL};
static PyObject *multibytecodec_encode(MultibyteCodec *,
- MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t,
- PyObject *, int);
+ MultibyteCodec_State *, const Py_UNICODE **, Py_ssize_t,
+ PyObject *, int);
-#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */
+#define MBENC_RESET MBENC_MAX<<1 /* reset after an encoding session */
static PyObject *
make_tuple(PyObject *object, Py_ssize_t len)
{
- PyObject *v, *w;
-
- if (object == NULL)
- return NULL;
-
- v = PyTuple_New(2);
- if (v == NULL) {
- Py_DECREF(object);
- return NULL;
- }
- PyTuple_SET_ITEM(v, 0, object);
-
- w = PyInt_FromSsize_t(len);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyTuple_SET_ITEM(v, 1, w);
-
- return v;
+ PyObject *v, *w;
+
+ if (object == NULL)
+ return NULL;
+
+ v = PyTuple_New(2);
+ if (v == NULL) {
+ Py_DECREF(object);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(v, 0, object);
+
+ w = PyInt_FromSsize_t(len);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(v, 1, w);
+
+ return v;
}
static PyObject *
internal_error_callback(const char *errors)
{
- if (errors == NULL || strcmp(errors, "strict") == 0)
- return ERROR_STRICT;
- else if (strcmp(errors, "ignore") == 0)
- return ERROR_IGNORE;
- else if (strcmp(errors, "replace") == 0)
- return ERROR_REPLACE;
- else
- return PyString_FromString(errors);
+ if (errors == NULL || strcmp(errors, "strict") == 0)
+ return ERROR_STRICT;
+ else if (strcmp(errors, "ignore") == 0)
+ return ERROR_IGNORE;
+ else if (strcmp(errors, "replace") == 0)
+ return ERROR_REPLACE;
+ else
+ return PyString_FromString(errors);
}
static PyObject *
call_error_callback(PyObject *errors, PyObject *exc)
{
- PyObject *args, *cb, *r;
-
- assert(PyString_Check(errors));
- cb = PyCodec_LookupError(PyString_AS_STRING(errors));
- if (cb == NULL)
- return NULL;
-
- args = PyTuple_New(1);
- if (args == NULL) {
- Py_DECREF(cb);
- return NULL;
- }
-
- PyTuple_SET_ITEM(args, 0, exc);
- Py_INCREF(exc);
-
- r = PyObject_CallObject(cb, args);
- Py_DECREF(args);
- Py_DECREF(cb);
- return r;
+ PyObject *args, *cb, *r;
+
+ assert(PyString_Check(errors));
+ cb = PyCodec_LookupError(PyString_AS_STRING(errors));
+ if (cb == NULL)
+ return NULL;
+
+ args = PyTuple_New(1);
+ if (args == NULL) {
+ Py_DECREF(cb);
+ return NULL;
+ }
+
+ PyTuple_SET_ITEM(args, 0, exc);
+ Py_INCREF(exc);
+
+ r = PyObject_CallObject(cb, args);
+ Py_DECREF(args);
+ Py_DECREF(cb);
+ return r;
}
static PyObject *
codecctx_errors_get(MultibyteStatefulCodecContext *self)
{
- const char *errors;
-
- if (self->errors == ERROR_STRICT)
- errors = "strict";
- else if (self->errors == ERROR_IGNORE)
- errors = "ignore";
- else if (self->errors == ERROR_REPLACE)
- errors = "replace";
- else {
- Py_INCREF(self->errors);
- return self->errors;
- }
-
- return PyString_FromString(errors);
+ const char *errors;
+
+ if (self->errors == ERROR_STRICT)
+ errors = "strict";
+ else if (self->errors == ERROR_IGNORE)
+ errors = "ignore";
+ else if (self->errors == ERROR_REPLACE)
+ errors = "replace";
+ else {
+ Py_INCREF(self->errors);
+ return self->errors;
+ }
+
+ return PyString_FromString(errors);
}
static int
codecctx_errors_set(MultibyteStatefulCodecContext *self, PyObject *value,
- void *closure)
+ void *closure)
{
- PyObject *cb;
+ PyObject *cb;
- if (!PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError, "errors must be a string");
- return -1;
- }
+ if (!PyString_Check(value)) {
+ PyErr_SetString(PyExc_TypeError, "errors must be a string");
+ return -1;
+ }
- cb = internal_error_callback(PyString_AS_STRING(value));
- if (cb == NULL)
- return -1;
+ cb = internal_error_callback(PyString_AS_STRING(value));
+ if (cb == NULL)
+ return -1;
- ERROR_DECREF(self->errors);
- self->errors = cb;
- return 0;
+ ERROR_DECREF(self->errors);
+ self->errors = cb;
+ return 0;
}
/* This getset handlers list is used by all the stateful codec objects */
static PyGetSetDef codecctx_getsets[] = {
- {"errors", (getter)codecctx_errors_get,
- (setter)codecctx_errors_set,
- PyDoc_STR("how to treat errors")},
- {NULL,}
+ {"errors", (getter)codecctx_errors_get,
+ (setter)codecctx_errors_set,
+ PyDoc_STR("how to treat errors")},
+ {NULL,}
};
static int
expand_encodebuffer(MultibyteEncodeBuffer *buf, Py_ssize_t esize)
{
- Py_ssize_t orgpos, orgsize, incsize;
+ Py_ssize_t orgpos, orgsize, incsize;
- orgpos = (Py_ssize_t)((char *)buf->outbuf -
- PyString_AS_STRING(buf->outobj));
- orgsize = PyString_GET_SIZE(buf->outobj);
- incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
+ orgpos = (Py_ssize_t)((char *)buf->outbuf -
+ PyString_AS_STRING(buf->outobj));
+ orgsize = PyString_GET_SIZE(buf->outobj);
+ incsize = (esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize);
- if (orgsize > PY_SSIZE_T_MAX - incsize)
- return -1;
+ if (orgsize > PY_SSIZE_T_MAX - incsize)
+ return -1;
- if (_PyString_Resize(&buf->outobj, orgsize + incsize) == -1)
- return -1;
+ if (_PyString_Resize(&buf->outobj, orgsize + incsize) == -1)
+ return -1;
- buf->outbuf = (unsigned char *)PyString_AS_STRING(buf->outobj) +orgpos;
- buf->outbuf_end = (unsigned char *)PyString_AS_STRING(buf->outobj)
- + PyString_GET_SIZE(buf->outobj);
+ buf->outbuf = (unsigned char *)PyString_AS_STRING(buf->outobj) +orgpos;
+ buf->outbuf_end = (unsigned char *)PyString_AS_STRING(buf->outobj)
+ + PyString_GET_SIZE(buf->outobj);
- return 0;
+ return 0;
}
-#define REQUIRE_ENCODEBUFFER(buf, s) { \
- if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
- if (expand_encodebuffer(buf, s) == -1) \
- goto errorexit; \
+#define REQUIRE_ENCODEBUFFER(buf, s) { \
+ if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
+ if (expand_encodebuffer(buf, s) == -1) \
+ goto errorexit; \
}
static int
expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
{
- Py_ssize_t orgpos, orgsize;
+ Py_ssize_t orgpos, orgsize;
- orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj));
- orgsize = PyUnicode_GET_SIZE(buf->outobj);
- if (PyUnicode_Resize(&buf->outobj, orgsize + (
- esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1)
- return -1;
+ orgpos = (Py_ssize_t)(buf->outbuf - PyUnicode_AS_UNICODE(buf->outobj));
+ orgsize = PyUnicode_GET_SIZE(buf->outobj);
+ if (PyUnicode_Resize(&buf->outobj, orgsize + (
+ esize < (orgsize >> 1) ? (orgsize >> 1) | 1 : esize)) == -1)
+ return -1;
- buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos;
- buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj)
- + PyUnicode_GET_SIZE(buf->outobj);
+ buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj) + orgpos;
+ buf->outbuf_end = PyUnicode_AS_UNICODE(buf->outobj)
+ + PyUnicode_GET_SIZE(buf->outobj);
- return 0;
+ return 0;
}
-#define REQUIRE_DECODEBUFFER(buf, s) { \
- if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
- if (expand_decodebuffer(buf, s) == -1) \
- goto errorexit; \
+#define REQUIRE_DECODEBUFFER(buf, s) { \
+ if ((s) < 1 || (buf)->outbuf + (s) > (buf)->outbuf_end) \
+ if (expand_decodebuffer(buf, s) == -1) \
+ goto errorexit; \
}
@@ -218,505 +218,505 @@ expand_decodebuffer(MultibyteDecodeBuffer *buf, Py_ssize_t esize)
static int
multibytecodec_encerror(MultibyteCodec *codec,
- MultibyteCodec_State *state,
- MultibyteEncodeBuffer *buf,
- PyObject *errors, Py_ssize_t e)
+ MultibyteCodec_State *state,
+ MultibyteEncodeBuffer *buf,
+ PyObject *errors, Py_ssize_t e)
{
- PyObject *retobj = NULL, *retstr = NULL, *tobj;
- Py_ssize_t retstrsize, newpos;
- Py_ssize_t esize, start, end;
- const char *reason;
-
- if (e > 0) {
- reason = "illegal multibyte sequence";
- esize = e;
- }
- else {
- switch (e) {
- case MBERR_TOOSMALL:
- REQUIRE_ENCODEBUFFER(buf, -1);
- return 0; /* retry it */
- case MBERR_TOOFEW:
- reason = "incomplete multibyte sequence";
- esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- break;
- case MBERR_INTERNAL:
- PyErr_SetString(PyExc_RuntimeError,
- "internal codec error");
- return -1;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "unknown runtime error");
- return -1;
- }
- }
-
- if (errors == ERROR_REPLACE) {
- const Py_UNICODE replchar = '?', *inbuf = &replchar;
- Py_ssize_t r;
-
- for (;;) {
- Py_ssize_t outleft;
-
- outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
- r = codec->encode(state, codec->config, &inbuf, 1,
- &buf->outbuf, outleft, 0);
- if (r == MBERR_TOOSMALL) {
- REQUIRE_ENCODEBUFFER(buf, -1);
- continue;
- }
- else
- break;
- }
-
- if (r != 0) {
- REQUIRE_ENCODEBUFFER(buf, 1);
- *buf->outbuf++ = '?';
- }
- }
- if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
- buf->inbuf += esize;
- return 0;
- }
-
- start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
- end = start + esize;
-
- /* use cached exception object if available */
- if (buf->excobj == NULL) {
- buf->excobj = PyUnicodeEncodeError_Create(codec->encoding,
- buf->inbuf_top,
- buf->inbuf_end - buf->inbuf_top,
- start, end, reason);
- if (buf->excobj == NULL)
- goto errorexit;
- }
- else
- if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 ||
- PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 ||
- PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0)
- goto errorexit;
-
- if (errors == ERROR_STRICT) {
- PyCodec_StrictErrors(buf->excobj);
- goto errorexit;
- }
-
- retobj = call_error_callback(errors, buf->excobj);
- if (retobj == NULL)
- goto errorexit;
-
- if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
- !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) ||
- !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
- PyLong_Check(PyTuple_GET_ITEM(retobj, 1)))) {
- PyErr_SetString(PyExc_TypeError,
- "encoding error handler must return "
- "(unicode, int) tuple");
- goto errorexit;
- }
-
- {
- const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj);
-
- retstr = multibytecodec_encode(codec, state, &uraw,
- PyUnicode_GET_SIZE(tobj), ERROR_STRICT,
- MBENC_FLUSH);
- if (retstr == NULL)
- goto errorexit;
- }
-
- retstrsize = PyString_GET_SIZE(retstr);
- REQUIRE_ENCODEBUFFER(buf, retstrsize);
-
- memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
- buf->outbuf += retstrsize;
-
- newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
- if (newpos < 0 && !PyErr_Occurred())
- newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
- if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
- PyErr_Clear();
- PyErr_Format(PyExc_IndexError,
- "position %zd from error handler out of bounds",
- newpos);
- goto errorexit;
- }
- buf->inbuf = buf->inbuf_top + newpos;
-
- Py_DECREF(retobj);
- Py_DECREF(retstr);
- return 0;
+ PyObject *retobj = NULL, *retstr = NULL, *tobj;
+ Py_ssize_t retstrsize, newpos;
+ Py_ssize_t esize, start, end;
+ const char *reason;
+
+ if (e > 0) {
+ reason = "illegal multibyte sequence";
+ esize = e;
+ }
+ else {
+ switch (e) {
+ case MBERR_TOOSMALL:
+ REQUIRE_ENCODEBUFFER(buf, -1);
+ return 0; /* retry it */
+ case MBERR_TOOFEW:
+ reason = "incomplete multibyte sequence";
+ esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ break;
+ case MBERR_INTERNAL:
+ PyErr_SetString(PyExc_RuntimeError,
+ "internal codec error");
+ return -1;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "unknown runtime error");
+ return -1;
+ }
+ }
+
+ if (errors == ERROR_REPLACE) {
+ const Py_UNICODE replchar = '?', *inbuf = &replchar;
+ Py_ssize_t r;
+
+ for (;;) {
+ Py_ssize_t outleft;
+
+ outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
+ r = codec->encode(state, codec->config, &inbuf, 1,
+ &buf->outbuf, outleft, 0);
+ if (r == MBERR_TOOSMALL) {
+ REQUIRE_ENCODEBUFFER(buf, -1);
+ continue;
+ }
+ else
+ break;
+ }
+
+ if (r != 0) {
+ REQUIRE_ENCODEBUFFER(buf, 1);
+ *buf->outbuf++ = '?';
+ }
+ }
+ if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
+ buf->inbuf += esize;
+ return 0;
+ }
+
+ start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
+ end = start + esize;
+
+ /* use cached exception object if available */
+ if (buf->excobj == NULL) {
+ buf->excobj = PyUnicodeEncodeError_Create(codec->encoding,
+ buf->inbuf_top,
+ buf->inbuf_end - buf->inbuf_top,
+ start, end, reason);
+ if (buf->excobj == NULL)
+ goto errorexit;
+ }
+ else
+ if (PyUnicodeEncodeError_SetStart(buf->excobj, start) != 0 ||
+ PyUnicodeEncodeError_SetEnd(buf->excobj, end) != 0 ||
+ PyUnicodeEncodeError_SetReason(buf->excobj, reason) != 0)
+ goto errorexit;
+
+ if (errors == ERROR_STRICT) {
+ PyCodec_StrictErrors(buf->excobj);
+ goto errorexit;
+ }
+
+ retobj = call_error_callback(errors, buf->excobj);
+ if (retobj == NULL)
+ goto errorexit;
+
+ if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
+ !PyUnicode_Check((tobj = PyTuple_GET_ITEM(retobj, 0))) ||
+ !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
+ PyLong_Check(PyTuple_GET_ITEM(retobj, 1)))) {
+ PyErr_SetString(PyExc_TypeError,
+ "encoding error handler must return "
+ "(unicode, int) tuple");
+ goto errorexit;
+ }
+
+ {
+ const Py_UNICODE *uraw = PyUnicode_AS_UNICODE(tobj);
+
+ retstr = multibytecodec_encode(codec, state, &uraw,
+ PyUnicode_GET_SIZE(tobj), ERROR_STRICT,
+ MBENC_FLUSH);
+ if (retstr == NULL)
+ goto errorexit;
+ }
+
+ retstrsize = PyString_GET_SIZE(retstr);
+ REQUIRE_ENCODEBUFFER(buf, retstrsize);
+
+ memcpy(buf->outbuf, PyString_AS_STRING(retstr), retstrsize);
+ buf->outbuf += retstrsize;
+
+ newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
+ if (newpos < 0 && !PyErr_Occurred())
+ newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
+ if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
+ PyErr_Clear();
+ PyErr_Format(PyExc_IndexError,
+ "position %zd from error handler out of bounds",
+ newpos);
+ goto errorexit;
+ }
+ buf->inbuf = buf->inbuf_top + newpos;
+
+ Py_DECREF(retobj);
+ Py_DECREF(retstr);
+ return 0;
errorexit:
- Py_XDECREF(retobj);
- Py_XDECREF(retstr);
- return -1;
+ Py_XDECREF(retobj);
+ Py_XDECREF(retstr);
+ return -1;
}
static int
multibytecodec_decerror(MultibyteCodec *codec,
- MultibyteCodec_State *state,
- MultibyteDecodeBuffer *buf,
- PyObject *errors, Py_ssize_t e)
+ MultibyteCodec_State *state,
+ MultibyteDecodeBuffer *buf,
+ PyObject *errors, Py_ssize_t e)
{
- PyObject *retobj = NULL, *retuni = NULL;
- Py_ssize_t retunisize, newpos;
- const char *reason;
- Py_ssize_t esize, start, end;
-
- if (e > 0) {
- reason = "illegal multibyte sequence";
- esize = e;
- }
- else {
- switch (e) {
- case MBERR_TOOSMALL:
- REQUIRE_DECODEBUFFER(buf, -1);
- return 0; /* retry it */
- case MBERR_TOOFEW:
- reason = "incomplete multibyte sequence";
- esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- break;
- case MBERR_INTERNAL:
- PyErr_SetString(PyExc_RuntimeError,
- "internal codec error");
- return -1;
- default:
- PyErr_SetString(PyExc_RuntimeError,
- "unknown runtime error");
- return -1;
- }
- }
-
- if (errors == ERROR_REPLACE) {
- REQUIRE_DECODEBUFFER(buf, 1);
- *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER;
- }
- if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
- buf->inbuf += esize;
- return 0;
- }
-
- start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
- end = start + esize;
-
- /* use cached exception object if available */
- if (buf->excobj == NULL) {
- buf->excobj = PyUnicodeDecodeError_Create(codec->encoding,
- (const char *)buf->inbuf_top,
- (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top),
- start, end, reason);
- if (buf->excobj == NULL)
- goto errorexit;
- }
- else
- if (PyUnicodeDecodeError_SetStart(buf->excobj, start) ||
- PyUnicodeDecodeError_SetEnd(buf->excobj, end) ||
- PyUnicodeDecodeError_SetReason(buf->excobj, reason))
- goto errorexit;
-
- if (errors == ERROR_STRICT) {
- PyCodec_StrictErrors(buf->excobj);
- goto errorexit;
- }
-
- retobj = call_error_callback(errors, buf->excobj);
- if (retobj == NULL)
- goto errorexit;
-
- if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
- !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) ||
- !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
- PyLong_Check(PyTuple_GET_ITEM(retobj, 1)))) {
- PyErr_SetString(PyExc_TypeError,
- "decoding error handler must return "
- "(unicode, int) tuple");
- goto errorexit;
- }
-
- retunisize = PyUnicode_GET_SIZE(retuni);
- if (retunisize > 0) {
- REQUIRE_DECODEBUFFER(buf, retunisize);
- memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni),
- retunisize * Py_UNICODE_SIZE);
- buf->outbuf += retunisize;
- }
-
- newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
- if (newpos < 0 && !PyErr_Occurred())
- newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
- if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
- PyErr_Clear();
- PyErr_Format(PyExc_IndexError,
- "position %zd from error handler out of bounds",
- newpos);
- goto errorexit;
- }
- buf->inbuf = buf->inbuf_top + newpos;
- Py_DECREF(retobj);
- return 0;
+ PyObject *retobj = NULL, *retuni = NULL;
+ Py_ssize_t retunisize, newpos;
+ const char *reason;
+ Py_ssize_t esize, start, end;
+
+ if (e > 0) {
+ reason = "illegal multibyte sequence";
+ esize = e;
+ }
+ else {
+ switch (e) {
+ case MBERR_TOOSMALL:
+ REQUIRE_DECODEBUFFER(buf, -1);
+ return 0; /* retry it */
+ case MBERR_TOOFEW:
+ reason = "incomplete multibyte sequence";
+ esize = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ break;
+ case MBERR_INTERNAL:
+ PyErr_SetString(PyExc_RuntimeError,
+ "internal codec error");
+ return -1;
+ default:
+ PyErr_SetString(PyExc_RuntimeError,
+ "unknown runtime error");
+ return -1;
+ }
+ }
+
+ if (errors == ERROR_REPLACE) {
+ REQUIRE_DECODEBUFFER(buf, 1);
+ *buf->outbuf++ = Py_UNICODE_REPLACEMENT_CHARACTER;
+ }
+ if (errors == ERROR_IGNORE || errors == ERROR_REPLACE) {
+ buf->inbuf += esize;
+ return 0;
+ }
+
+ start = (Py_ssize_t)(buf->inbuf - buf->inbuf_top);
+ end = start + esize;
+
+ /* use cached exception object if available */
+ if (buf->excobj == NULL) {
+ buf->excobj = PyUnicodeDecodeError_Create(codec->encoding,
+ (const char *)buf->inbuf_top,
+ (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top),
+ start, end, reason);
+ if (buf->excobj == NULL)
+ goto errorexit;
+ }
+ else
+ if (PyUnicodeDecodeError_SetStart(buf->excobj, start) ||
+ PyUnicodeDecodeError_SetEnd(buf->excobj, end) ||
+ PyUnicodeDecodeError_SetReason(buf->excobj, reason))
+ goto errorexit;
+
+ if (errors == ERROR_STRICT) {
+ PyCodec_StrictErrors(buf->excobj);
+ goto errorexit;
+ }
+
+ retobj = call_error_callback(errors, buf->excobj);
+ if (retobj == NULL)
+ goto errorexit;
+
+ if (!PyTuple_Check(retobj) || PyTuple_GET_SIZE(retobj) != 2 ||
+ !PyUnicode_Check((retuni = PyTuple_GET_ITEM(retobj, 0))) ||
+ !(PyInt_Check(PyTuple_GET_ITEM(retobj, 1)) ||
+ PyLong_Check(PyTuple_GET_ITEM(retobj, 1)))) {
+ PyErr_SetString(PyExc_TypeError,
+ "decoding error handler must return "
+ "(unicode, int) tuple");
+ goto errorexit;
+ }
+
+ retunisize = PyUnicode_GET_SIZE(retuni);
+ if (retunisize > 0) {
+ REQUIRE_DECODEBUFFER(buf, retunisize);
+ memcpy((char *)buf->outbuf, PyUnicode_AS_DATA(retuni),
+ retunisize * Py_UNICODE_SIZE);
+ buf->outbuf += retunisize;
+ }
+
+ newpos = PyInt_AsSsize_t(PyTuple_GET_ITEM(retobj, 1));
+ if (newpos < 0 && !PyErr_Occurred())
+ newpos += (Py_ssize_t)(buf->inbuf_end - buf->inbuf_top);
+ if (newpos < 0 || buf->inbuf_top + newpos > buf->inbuf_end) {
+ PyErr_Clear();
+ PyErr_Format(PyExc_IndexError,
+ "position %zd from error handler out of bounds",
+ newpos);
+ goto errorexit;
+ }
+ buf->inbuf = buf->inbuf_top + newpos;
+ Py_DECREF(retobj);
+ return 0;
errorexit:
- Py_XDECREF(retobj);
- return -1;
+ Py_XDECREF(retobj);
+ return -1;
}
static PyObject *
multibytecodec_encode(MultibyteCodec *codec,
- MultibyteCodec_State *state,
- const Py_UNICODE **data, Py_ssize_t datalen,
- PyObject *errors, int flags)
+ MultibyteCodec_State *state,
+ const Py_UNICODE **data, Py_ssize_t datalen,
+ PyObject *errors, int flags)
{
- MultibyteEncodeBuffer buf;
- Py_ssize_t finalsize, r = 0;
-
- if (datalen == 0)
- return PyString_FromString("");
-
- buf.excobj = NULL;
- buf.inbuf = buf.inbuf_top = *data;
- buf.inbuf_end = buf.inbuf_top + datalen;
-
- if (datalen > (PY_SSIZE_T_MAX - 16) / 2) {
- PyErr_NoMemory();
- goto errorexit;
- }
-
- buf.outobj = PyString_FromStringAndSize(NULL, datalen * 2 + 16);
- if (buf.outobj == NULL)
- goto errorexit;
- buf.outbuf = (unsigned char *)PyString_AS_STRING(buf.outobj);
- buf.outbuf_end = buf.outbuf + PyString_GET_SIZE(buf.outobj);
-
- while (buf.inbuf < buf.inbuf_end) {
- Py_ssize_t inleft, outleft;
-
- /* we don't reuse inleft and outleft here.
- * error callbacks can relocate the cursor anywhere on buffer*/
- inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
- outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
- r = codec->encode(state, codec->config, &buf.inbuf, inleft,
- &buf.outbuf, outleft, flags);
- *data = buf.inbuf;
- if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH)))
- break;
- else if (multibytecodec_encerror(codec, state, &buf, errors,r))
- goto errorexit;
- else if (r == MBERR_TOOFEW)
- break;
- }
-
- if (codec->encreset != NULL)
- for (;;) {
- Py_ssize_t outleft;
-
- outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
- r = codec->encreset(state, codec->config, &buf.outbuf,
- outleft);
- if (r == 0)
- break;
- else if (multibytecodec_encerror(codec, state,
- &buf, errors, r))
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)((char *)buf.outbuf -
- PyString_AS_STRING(buf.outobj));
-
- if (finalsize != PyString_GET_SIZE(buf.outobj))
- if (_PyString_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteEncodeBuffer buf;
+ Py_ssize_t finalsize, r = 0;
+
+ if (datalen == 0)
+ return PyString_FromString("");
+
+ buf.excobj = NULL;
+ buf.inbuf = buf.inbuf_top = *data;
+ buf.inbuf_end = buf.inbuf_top + datalen;
+
+ if (datalen > (PY_SSIZE_T_MAX - 16) / 2) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+
+ buf.outobj = PyString_FromStringAndSize(NULL, datalen * 2 + 16);
+ if (buf.outobj == NULL)
+ goto errorexit;
+ buf.outbuf = (unsigned char *)PyString_AS_STRING(buf.outobj);
+ buf.outbuf_end = buf.outbuf + PyString_GET_SIZE(buf.outobj);
+
+ while (buf.inbuf < buf.inbuf_end) {
+ Py_ssize_t inleft, outleft;
+
+ /* we don't reuse inleft and outleft here.
+ * error callbacks can relocate the cursor anywhere on buffer*/
+ inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
+ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
+ r = codec->encode(state, codec->config, &buf.inbuf, inleft,
+ &buf.outbuf, outleft, flags);
+ *data = buf.inbuf;
+ if ((r == 0) || (r == MBERR_TOOFEW && !(flags & MBENC_FLUSH)))
+ break;
+ else if (multibytecodec_encerror(codec, state, &buf, errors,r))
+ goto errorexit;
+ else if (r == MBERR_TOOFEW)
+ break;
+ }
+
+ if (codec->encreset != NULL)
+ for (;;) {
+ Py_ssize_t outleft;
+
+ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
+ r = codec->encreset(state, codec->config, &buf.outbuf,
+ outleft);
+ if (r == 0)
+ break;
+ else if (multibytecodec_encerror(codec, state,
+ &buf, errors, r))
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)((char *)buf.outbuf -
+ PyString_AS_STRING(buf.outobj));
+
+ if (finalsize != PyString_GET_SIZE(buf.outobj))
+ if (_PyString_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ Py_XDECREF(buf.excobj);
+ return buf.outobj;
errorexit:
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
- return NULL;
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
+ return NULL;
}
static PyObject *
MultibyteCodec_Encode(MultibyteCodecObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- MultibyteCodec_State state;
- Py_UNICODE *data;
- PyObject *errorcb, *r, *arg, *ucvt;
- const char *errors = NULL;
- Py_ssize_t datalen;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode",
- codeckwarglist, &arg, &errors))
- return NULL;
-
- if (PyUnicode_Check(arg))
- ucvt = NULL;
- else {
- arg = ucvt = PyObject_Unicode(arg);
- if (arg == NULL)
- return NULL;
- else if (!PyUnicode_Check(arg)) {
- PyErr_SetString(PyExc_TypeError,
- "couldn't convert the object to unicode.");
- Py_DECREF(ucvt);
- return NULL;
- }
- }
-
- data = PyUnicode_AS_UNICODE(arg);
- datalen = PyUnicode_GET_SIZE(arg);
-
- errorcb = internal_error_callback(errors);
- if (errorcb == NULL) {
- Py_XDECREF(ucvt);
- return NULL;
- }
-
- if (self->codec->encinit != NULL &&
- self->codec->encinit(&state, self->codec->config) != 0)
- goto errorexit;
- r = multibytecodec_encode(self->codec, &state,
- (const Py_UNICODE **)&data, datalen, errorcb,
- MBENC_FLUSH | MBENC_RESET);
- if (r == NULL)
- goto errorexit;
-
- ERROR_DECREF(errorcb);
- Py_XDECREF(ucvt);
- return make_tuple(r, datalen);
+ MultibyteCodec_State state;
+ Py_UNICODE *data;
+ PyObject *errorcb, *r, *arg, *ucvt;
+ const char *errors = NULL;
+ Py_ssize_t datalen;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|z:encode",
+ codeckwarglist, &arg, &errors))
+ return NULL;
+
+ if (PyUnicode_Check(arg))
+ ucvt = NULL;
+ else {
+ arg = ucvt = PyObject_Unicode(arg);
+ if (arg == NULL)
+ return NULL;
+ else if (!PyUnicode_Check(arg)) {
+ PyErr_SetString(PyExc_TypeError,
+ "couldn't convert the object to unicode.");
+ Py_DECREF(ucvt);
+ return NULL;
+ }
+ }
+
+ data = PyUnicode_AS_UNICODE(arg);
+ datalen = PyUnicode_GET_SIZE(arg);
+
+ errorcb = internal_error_callback(errors);
+ if (errorcb == NULL) {
+ Py_XDECREF(ucvt);
+ return NULL;
+ }
+
+ if (self->codec->encinit != NULL &&
+ self->codec->encinit(&state, self->codec->config) != 0)
+ goto errorexit;
+ r = multibytecodec_encode(self->codec, &state,
+ (const Py_UNICODE **)&data, datalen, errorcb,
+ MBENC_FLUSH | MBENC_RESET);
+ if (r == NULL)
+ goto errorexit;
+
+ ERROR_DECREF(errorcb);
+ Py_XDECREF(ucvt);
+ return make_tuple(r, datalen);
errorexit:
- ERROR_DECREF(errorcb);
- Py_XDECREF(ucvt);
- return NULL;
+ ERROR_DECREF(errorcb);
+ Py_XDECREF(ucvt);
+ return NULL;
}
static PyObject *
MultibyteCodec_Decode(MultibyteCodecObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- MultibyteCodec_State state;
- MultibyteDecodeBuffer buf;
- PyObject *errorcb;
- Py_buffer pdata;
- const char *data, *errors = NULL;
- Py_ssize_t datalen, finalsize;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|z:decode",
- codeckwarglist, &pdata, &errors))
- return NULL;
- data = pdata.buf;
- datalen = pdata.len;
-
- errorcb = internal_error_callback(errors);
- if (errorcb == NULL) {
- PyBuffer_Release(&pdata);
- return NULL;
- }
-
- if (datalen == 0) {
- PyBuffer_Release(&pdata);
- ERROR_DECREF(errorcb);
- return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0);
- }
-
- buf.excobj = NULL;
- buf.inbuf = buf.inbuf_top = (unsigned char *)data;
- buf.inbuf_end = buf.inbuf_top + datalen;
- buf.outobj = PyUnicode_FromUnicode(NULL, datalen);
- if (buf.outobj == NULL)
- goto errorexit;
- buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj);
- buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj);
-
- if (self->codec->decinit != NULL &&
- self->codec->decinit(&state, self->codec->config) != 0)
- goto errorexit;
-
- while (buf.inbuf < buf.inbuf_end) {
- Py_ssize_t inleft, outleft, r;
-
- inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
- outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
-
- r = self->codec->decode(&state, self->codec->config,
- &buf.inbuf, inleft, &buf.outbuf, outleft);
- if (r == 0)
- break;
- else if (multibytecodec_decerror(self->codec, &state,
- &buf, errorcb, r))
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)(buf.outbuf -
- PyUnicode_AS_UNICODE(buf.outobj));
-
- if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
- if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- PyBuffer_Release(&pdata);
- Py_XDECREF(buf.excobj);
- ERROR_DECREF(errorcb);
- return make_tuple(buf.outobj, datalen);
+ MultibyteCodec_State state;
+ MultibyteDecodeBuffer buf;
+ PyObject *errorcb;
+ Py_buffer pdata;
+ const char *data, *errors = NULL;
+ Py_ssize_t datalen, finalsize;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|z:decode",
+ codeckwarglist, &pdata, &errors))
+ return NULL;
+ data = pdata.buf;
+ datalen = pdata.len;
+
+ errorcb = internal_error_callback(errors);
+ if (errorcb == NULL) {
+ PyBuffer_Release(&pdata);
+ return NULL;
+ }
+
+ if (datalen == 0) {
+ PyBuffer_Release(&pdata);
+ ERROR_DECREF(errorcb);
+ return make_tuple(PyUnicode_FromUnicode(NULL, 0), 0);
+ }
+
+ buf.excobj = NULL;
+ buf.inbuf = buf.inbuf_top = (unsigned char *)data;
+ buf.inbuf_end = buf.inbuf_top + datalen;
+ buf.outobj = PyUnicode_FromUnicode(NULL, datalen);
+ if (buf.outobj == NULL)
+ goto errorexit;
+ buf.outbuf = PyUnicode_AS_UNICODE(buf.outobj);
+ buf.outbuf_end = buf.outbuf + PyUnicode_GET_SIZE(buf.outobj);
+
+ if (self->codec->decinit != NULL &&
+ self->codec->decinit(&state, self->codec->config) != 0)
+ goto errorexit;
+
+ while (buf.inbuf < buf.inbuf_end) {
+ Py_ssize_t inleft, outleft, r;
+
+ inleft = (Py_ssize_t)(buf.inbuf_end - buf.inbuf);
+ outleft = (Py_ssize_t)(buf.outbuf_end - buf.outbuf);
+
+ r = self->codec->decode(&state, self->codec->config,
+ &buf.inbuf, inleft, &buf.outbuf, outleft);
+ if (r == 0)
+ break;
+ else if (multibytecodec_decerror(self->codec, &state,
+ &buf, errorcb, r))
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)(buf.outbuf -
+ PyUnicode_AS_UNICODE(buf.outobj));
+
+ if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
+ if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ PyBuffer_Release(&pdata);
+ Py_XDECREF(buf.excobj);
+ ERROR_DECREF(errorcb);
+ return make_tuple(buf.outobj, datalen);
errorexit:
- PyBuffer_Release(&pdata);
- ERROR_DECREF(errorcb);
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
+ PyBuffer_Release(&pdata);
+ ERROR_DECREF(errorcb);
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
- return NULL;
+ return NULL;
}
static struct PyMethodDef multibytecodec_methods[] = {
- {"encode", (PyCFunction)MultibyteCodec_Encode,
- METH_VARARGS | METH_KEYWORDS,
- MultibyteCodec_Encode__doc__},
- {"decode", (PyCFunction)MultibyteCodec_Decode,
- METH_VARARGS | METH_KEYWORDS,
- MultibyteCodec_Decode__doc__},
- {NULL, NULL},
+ {"encode", (PyCFunction)MultibyteCodec_Encode,
+ METH_VARARGS | METH_KEYWORDS,
+ MultibyteCodec_Encode__doc__},
+ {"decode", (PyCFunction)MultibyteCodec_Decode,
+ METH_VARARGS | METH_KEYWORDS,
+ MultibyteCodec_Decode__doc__},
+ {NULL, NULL},
};
static void
multibytecodec_dealloc(MultibyteCodecObject *self)
{
- PyObject_Del(self);
+ PyObject_Del(self);
}
static PyTypeObject MultibyteCodec_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteCodec", /* tp_name */
- sizeof(MultibyteCodecObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)multibytecodec_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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- multibytecodec_methods, /* tp_methods */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteCodec", /* tp_name */
+ sizeof(MultibyteCodecObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)multibytecodec_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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ multibytecodec_methods, /* tp_methods */
};
@@ -724,150 +724,150 @@ static PyTypeObject MultibyteCodec_Type = {
* Utility functions for stateful codec mechanism
*/
-#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o))
-#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o))
+#define STATEFUL_DCTX(o) ((MultibyteStatefulDecoderContext *)(o))
+#define STATEFUL_ECTX(o) ((MultibyteStatefulEncoderContext *)(o))
static PyObject *
encoder_encode_stateful(MultibyteStatefulEncoderContext *ctx,
- PyObject *unistr, int final)
+ PyObject *unistr, int final)
{
- PyObject *ucvt, *r = NULL;
- Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL;
- Py_ssize_t datalen, origpending;
-
- if (PyUnicode_Check(unistr))
- ucvt = NULL;
- else {
- unistr = ucvt = PyObject_Unicode(unistr);
- if (unistr == NULL)
- return NULL;
- else if (!PyUnicode_Check(unistr)) {
- PyErr_SetString(PyExc_TypeError,
- "couldn't convert the object to unicode.");
- Py_DECREF(ucvt);
- return NULL;
- }
- }
-
- datalen = PyUnicode_GET_SIZE(unistr);
- origpending = ctx->pendingsize;
-
- if (origpending > 0) {
- if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) {
- PyErr_NoMemory();
- /* inbuf_tmp == NULL */
- goto errorexit;
- }
- inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize);
- if (inbuf_tmp == NULL)
- goto errorexit;
- memcpy(inbuf_tmp, ctx->pending,
- Py_UNICODE_SIZE * ctx->pendingsize);
- memcpy(inbuf_tmp + ctx->pendingsize,
- PyUnicode_AS_UNICODE(unistr),
- Py_UNICODE_SIZE * datalen);
- datalen += ctx->pendingsize;
- ctx->pendingsize = 0;
- inbuf = inbuf_tmp;
- }
- else
- inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr);
-
- inbuf_end = inbuf + datalen;
-
- r = multibytecodec_encode(ctx->codec, &ctx->state,
- (const Py_UNICODE **)&inbuf,
- datalen, ctx->errors, final ? MBENC_FLUSH : 0);
- if (r == NULL) {
- /* recover the original pending buffer */
- if (origpending > 0)
- memcpy(ctx->pending, inbuf_tmp,
- Py_UNICODE_SIZE * origpending);
- ctx->pendingsize = origpending;
- goto errorexit;
- }
-
- if (inbuf < inbuf_end) {
- ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf);
- if (ctx->pendingsize > MAXENCPENDING) {
- /* normal codecs can't reach here */
- ctx->pendingsize = 0;
- PyErr_SetString(PyExc_UnicodeError,
- "pending buffer overflow");
- goto errorexit;
- }
- memcpy(ctx->pending, inbuf,
- ctx->pendingsize * Py_UNICODE_SIZE);
- }
-
- if (inbuf_tmp != NULL)
- PyMem_Del(inbuf_tmp);
- Py_XDECREF(ucvt);
- return r;
+ PyObject *ucvt, *r = NULL;
+ Py_UNICODE *inbuf, *inbuf_end, *inbuf_tmp = NULL;
+ Py_ssize_t datalen, origpending;
+
+ if (PyUnicode_Check(unistr))
+ ucvt = NULL;
+ else {
+ unistr = ucvt = PyObject_Unicode(unistr);
+ if (unistr == NULL)
+ return NULL;
+ else if (!PyUnicode_Check(unistr)) {
+ PyErr_SetString(PyExc_TypeError,
+ "couldn't convert the object to unicode.");
+ Py_DECREF(ucvt);
+ return NULL;
+ }
+ }
+
+ datalen = PyUnicode_GET_SIZE(unistr);
+ origpending = ctx->pendingsize;
+
+ if (origpending > 0) {
+ if (datalen > PY_SSIZE_T_MAX - ctx->pendingsize) {
+ PyErr_NoMemory();
+ /* inbuf_tmp == NULL */
+ goto errorexit;
+ }
+ inbuf_tmp = PyMem_New(Py_UNICODE, datalen + ctx->pendingsize);
+ if (inbuf_tmp == NULL)
+ goto errorexit;
+ memcpy(inbuf_tmp, ctx->pending,
+ Py_UNICODE_SIZE * ctx->pendingsize);
+ memcpy(inbuf_tmp + ctx->pendingsize,
+ PyUnicode_AS_UNICODE(unistr),
+ Py_UNICODE_SIZE * datalen);
+ datalen += ctx->pendingsize;
+ ctx->pendingsize = 0;
+ inbuf = inbuf_tmp;
+ }
+ else
+ inbuf = (Py_UNICODE *)PyUnicode_AS_UNICODE(unistr);
+
+ inbuf_end = inbuf + datalen;
+
+ r = multibytecodec_encode(ctx->codec, &ctx->state,
+ (const Py_UNICODE **)&inbuf,
+ datalen, ctx->errors, final ? MBENC_FLUSH : 0);
+ if (r == NULL) {
+ /* recover the original pending buffer */
+ if (origpending > 0)
+ memcpy(ctx->pending, inbuf_tmp,
+ Py_UNICODE_SIZE * origpending);
+ ctx->pendingsize = origpending;
+ goto errorexit;
+ }
+
+ if (inbuf < inbuf_end) {
+ ctx->pendingsize = (Py_ssize_t)(inbuf_end - inbuf);
+ if (ctx->pendingsize > MAXENCPENDING) {
+ /* normal codecs can't reach here */
+ ctx->pendingsize = 0;
+ PyErr_SetString(PyExc_UnicodeError,
+ "pending buffer overflow");
+ goto errorexit;
+ }
+ memcpy(ctx->pending, inbuf,
+ ctx->pendingsize * Py_UNICODE_SIZE);
+ }
+
+ if (inbuf_tmp != NULL)
+ PyMem_Del(inbuf_tmp);
+ Py_XDECREF(ucvt);
+ return r;
errorexit:
- if (inbuf_tmp != NULL)
- PyMem_Del(inbuf_tmp);
- Py_XDECREF(r);
- Py_XDECREF(ucvt);
- return NULL;
+ if (inbuf_tmp != NULL)
+ PyMem_Del(inbuf_tmp);
+ Py_XDECREF(r);
+ Py_XDECREF(ucvt);
+ return NULL;
}
static int
decoder_append_pending(MultibyteStatefulDecoderContext *ctx,
- MultibyteDecodeBuffer *buf)
+ MultibyteDecodeBuffer *buf)
{
- Py_ssize_t npendings;
-
- npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- if (npendings + ctx->pendingsize > MAXDECPENDING ||
- npendings > PY_SSIZE_T_MAX - ctx->pendingsize) {
- PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow");
- return -1;
- }
- memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings);
- ctx->pendingsize += npendings;
- return 0;
+ Py_ssize_t npendings;
+
+ npendings = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ if (npendings + ctx->pendingsize > MAXDECPENDING ||
+ npendings > PY_SSIZE_T_MAX - ctx->pendingsize) {
+ PyErr_SetString(PyExc_UnicodeError, "pending buffer overflow");
+ return -1;
+ }
+ memcpy(ctx->pending + ctx->pendingsize, buf->inbuf, npendings);
+ ctx->pendingsize += npendings;
+ return 0;
}
static int
decoder_prepare_buffer(MultibyteDecodeBuffer *buf, const char *data,
- Py_ssize_t size)
+ Py_ssize_t size)
{
- buf->inbuf = buf->inbuf_top = (const unsigned char *)data;
- buf->inbuf_end = buf->inbuf_top + size;
- if (buf->outobj == NULL) { /* only if outobj is not allocated yet */
- buf->outobj = PyUnicode_FromUnicode(NULL, size);
- if (buf->outobj == NULL)
- return -1;
- buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj);
- buf->outbuf_end = buf->outbuf +
- PyUnicode_GET_SIZE(buf->outobj);
- }
-
- return 0;
+ buf->inbuf = buf->inbuf_top = (const unsigned char *)data;
+ buf->inbuf_end = buf->inbuf_top + size;
+ if (buf->outobj == NULL) { /* only if outobj is not allocated yet */
+ buf->outobj = PyUnicode_FromUnicode(NULL, size);
+ if (buf->outobj == NULL)
+ return -1;
+ buf->outbuf = PyUnicode_AS_UNICODE(buf->outobj);
+ buf->outbuf_end = buf->outbuf +
+ PyUnicode_GET_SIZE(buf->outobj);
+ }
+
+ return 0;
}
static int
decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx,
- MultibyteDecodeBuffer *buf)
+ MultibyteDecodeBuffer *buf)
{
- while (buf->inbuf < buf->inbuf_end) {
- Py_ssize_t inleft, outleft;
- Py_ssize_t r;
-
- inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
- outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
-
- r = ctx->codec->decode(&ctx->state, ctx->codec->config,
- &buf->inbuf, inleft, &buf->outbuf, outleft);
- if (r == 0 || r == MBERR_TOOFEW)
- break;
- else if (multibytecodec_decerror(ctx->codec, &ctx->state,
- buf, ctx->errors, r))
- return -1;
- }
- return 0;
+ while (buf->inbuf < buf->inbuf_end) {
+ Py_ssize_t inleft, outleft;
+ Py_ssize_t r;
+
+ inleft = (Py_ssize_t)(buf->inbuf_end - buf->inbuf);
+ outleft = (Py_ssize_t)(buf->outbuf_end - buf->outbuf);
+
+ r = ctx->codec->decode(&ctx->state, ctx->codec->config,
+ &buf->inbuf, inleft, &buf->outbuf, outleft);
+ if (r == 0 || r == MBERR_TOOFEW)
+ break;
+ else if (multibytecodec_decerror(ctx->codec, &ctx->state,
+ buf, ctx->errors, r))
+ return -1;
+ }
+ return 0;
}
@@ -877,142 +877,142 @@ decoder_feed_buffer(MultibyteStatefulDecoderContext *ctx,
static PyObject *
mbiencoder_encode(MultibyteIncrementalEncoderObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- PyObject *data;
- int final = 0;
+ PyObject *data;
+ int final = 0;
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode",
- incrementalkwarglist, &data, &final))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "O|i:encode",
+ incrementalkwarglist, &data, &final))
+ return NULL;
- return encoder_encode_stateful(STATEFUL_ECTX(self), data, final);
+ return encoder_encode_stateful(STATEFUL_ECTX(self), data, final);
}
static PyObject *
mbiencoder_reset(MultibyteIncrementalEncoderObject *self)
{
- if (self->codec->decreset != NULL &&
- self->codec->decreset(&self->state, self->codec->config) != 0)
- return NULL;
- self->pendingsize = 0;
+ if (self->codec->decreset != NULL &&
+ self->codec->decreset(&self->state, self->codec->config) != 0)
+ return NULL;
+ self->pendingsize = 0;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef mbiencoder_methods[] = {
- {"encode", (PyCFunction)mbiencoder_encode,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"reset", (PyCFunction)mbiencoder_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"encode", (PyCFunction)mbiencoder_encode,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"reset", (PyCFunction)mbiencoder_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyObject *
mbiencoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteIncrementalEncoderObject *self;
- PyObject *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder",
- incnewkwarglist, &errors))
- return NULL;
-
- self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->encinit != NULL &&
- self->codec->encinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteIncrementalEncoderObject *self;
+ PyObject *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalEncoder",
+ incnewkwarglist, &errors))
+ return NULL;
+
+ self = (MultibyteIncrementalEncoderObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->encinit != NULL &&
+ self->codec->encinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbiencoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbiencoder_traverse(MultibyteIncrementalEncoderObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ return 0;
}
static void
mbiencoder_dealloc(MultibyteIncrementalEncoderObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_TYPE(self)->tp_free(self);
}
static PyTypeObject MultibyteIncrementalEncoder_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteIncrementalEncoder", /* tp_name */
- sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbiencoder_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 | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbiencoder_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbiencoder_methods, /* tp_methods */
- 0, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbiencoder_init, /* tp_init */
- 0, /* tp_alloc */
- mbiencoder_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteIncrementalEncoder", /* tp_name */
+ sizeof(MultibyteIncrementalEncoderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbiencoder_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 | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbiencoder_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbiencoder_methods, /* tp_methods */
+ 0, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbiencoder_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbiencoder_new, /* tp_new */
};
@@ -1022,206 +1022,206 @@ static PyTypeObject MultibyteIncrementalEncoder_Type = {
static PyObject *
mbidecoder_decode(MultibyteIncrementalDecoderObject *self,
- PyObject *args, PyObject *kwargs)
+ PyObject *args, PyObject *kwargs)
{
- MultibyteDecodeBuffer buf;
- char *data, *wdata = NULL;
- Py_buffer pdata;
- Py_ssize_t wsize, finalsize = 0, size, origpending;
- int final = 0;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i:decode",
- incrementalkwarglist, &pdata, &final))
- return NULL;
- data = pdata.buf;
- size = pdata.len;
-
- buf.outobj = buf.excobj = NULL;
- origpending = self->pendingsize;
-
- if (self->pendingsize == 0) {
- wsize = size;
- wdata = data;
- }
- else {
- if (size > PY_SSIZE_T_MAX - self->pendingsize) {
- PyErr_NoMemory();
- goto errorexit;
- }
- wsize = size + self->pendingsize;
- wdata = PyMem_Malloc(wsize);
- if (wdata == NULL)
- goto errorexit;
- memcpy(wdata, self->pending, self->pendingsize);
- memcpy(wdata + self->pendingsize, data, size);
- self->pendingsize = 0;
- }
-
- if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)
- goto errorexit;
-
- if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf))
- goto errorexit;
-
- if (final && buf.inbuf < buf.inbuf_end) {
- if (multibytecodec_decerror(self->codec, &self->state,
- &buf, self->errors, MBERR_TOOFEW)) {
- /* recover the original pending buffer */
- memcpy(self->pending, wdata, origpending);
- self->pendingsize = origpending;
- goto errorexit;
- }
- }
-
- if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */
- if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0)
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj));
- if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
- if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- PyBuffer_Release(&pdata);
- if (wdata != data)
- PyMem_Del(wdata);
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteDecodeBuffer buf;
+ char *data, *wdata = NULL;
+ Py_buffer pdata;
+ Py_ssize_t wsize, finalsize = 0, size, origpending;
+ int final = 0;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwargs, "s*|i:decode",
+ incrementalkwarglist, &pdata, &final))
+ return NULL;
+ data = pdata.buf;
+ size = pdata.len;
+
+ buf.outobj = buf.excobj = NULL;
+ origpending = self->pendingsize;
+
+ if (self->pendingsize == 0) {
+ wsize = size;
+ wdata = data;
+ }
+ else {
+ if (size > PY_SSIZE_T_MAX - self->pendingsize) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+ wsize = size + self->pendingsize;
+ wdata = PyMem_Malloc(wsize);
+ if (wdata == NULL)
+ goto errorexit;
+ memcpy(wdata, self->pending, self->pendingsize);
+ memcpy(wdata + self->pendingsize, data, size);
+ self->pendingsize = 0;
+ }
+
+ if (decoder_prepare_buffer(&buf, wdata, wsize) != 0)
+ goto errorexit;
+
+ if (decoder_feed_buffer(STATEFUL_DCTX(self), &buf))
+ goto errorexit;
+
+ if (final && buf.inbuf < buf.inbuf_end) {
+ if (multibytecodec_decerror(self->codec, &self->state,
+ &buf, self->errors, MBERR_TOOFEW)) {
+ /* recover the original pending buffer */
+ memcpy(self->pending, wdata, origpending);
+ self->pendingsize = origpending;
+ goto errorexit;
+ }
+ }
+
+ if (buf.inbuf < buf.inbuf_end) { /* pending sequence still exists */
+ if (decoder_append_pending(STATEFUL_DCTX(self), &buf) != 0)
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)(buf.outbuf - PyUnicode_AS_UNICODE(buf.outobj));
+ if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
+ if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ PyBuffer_Release(&pdata);
+ if (wdata != data)
+ PyMem_Del(wdata);
+ Py_XDECREF(buf.excobj);
+ return buf.outobj;
errorexit:
- PyBuffer_Release(&pdata);
- if (wdata != NULL && wdata != data)
- PyMem_Del(wdata);
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
- return NULL;
+ PyBuffer_Release(&pdata);
+ if (wdata != NULL && wdata != data)
+ PyMem_Del(wdata);
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
+ return NULL;
}
static PyObject *
mbidecoder_reset(MultibyteIncrementalDecoderObject *self)
{
- if (self->codec->decreset != NULL &&
- self->codec->decreset(&self->state, self->codec->config) != 0)
- return NULL;
- self->pendingsize = 0;
+ if (self->codec->decreset != NULL &&
+ self->codec->decreset(&self->state, self->codec->config) != 0)
+ return NULL;
+ self->pendingsize = 0;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef mbidecoder_methods[] = {
- {"decode", (PyCFunction)mbidecoder_decode,
- METH_VARARGS | METH_KEYWORDS, NULL},
- {"reset", (PyCFunction)mbidecoder_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"decode", (PyCFunction)mbidecoder_decode,
+ METH_VARARGS | METH_KEYWORDS, NULL},
+ {"reset", (PyCFunction)mbidecoder_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyObject *
mbidecoder_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteIncrementalDecoderObject *self;
- PyObject *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder",
- incnewkwarglist, &errors))
- return NULL;
-
- self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->decinit != NULL &&
- self->codec->decinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteIncrementalDecoderObject *self;
+ PyObject *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|s:IncrementalDecoder",
+ incnewkwarglist, &errors))
+ return NULL;
+
+ self = (MultibyteIncrementalDecoderObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->decinit != NULL &&
+ self->codec->decinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbidecoder_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbidecoder_traverse(MultibyteIncrementalDecoderObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ return 0;
}
static void
mbidecoder_dealloc(MultibyteIncrementalDecoderObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_TYPE(self)->tp_free(self);
}
static PyTypeObject MultibyteIncrementalDecoder_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteIncrementalDecoder", /* tp_name */
- sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbidecoder_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 | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbidecoder_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbidecoder_methods, /* tp_methods */
- 0, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbidecoder_init, /* tp_init */
- 0, /* tp_alloc */
- mbidecoder_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteIncrementalDecoder", /* tp_name */
+ sizeof(MultibyteIncrementalDecoderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbidecoder_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 | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbidecoder_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbidecoder_methods, /* tp_methods */
+ 0, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbidecoder_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbidecoder_new, /* tp_new */
};
@@ -1231,317 +1231,317 @@ static PyTypeObject MultibyteIncrementalDecoder_Type = {
static PyObject *
mbstreamreader_iread(MultibyteStreamReaderObject *self,
- const char *method, Py_ssize_t sizehint)
+ const char *method, Py_ssize_t sizehint)
{
- MultibyteDecodeBuffer buf;
- PyObject *cres;
- Py_ssize_t rsize, finalsize = 0;
-
- if (sizehint == 0)
- return PyUnicode_FromUnicode(NULL, 0);
-
- buf.outobj = buf.excobj = NULL;
- cres = NULL;
-
- for (;;) {
- int endoffile;
-
- if (sizehint < 0)
- cres = PyObject_CallMethod(self->stream,
- (char *)method, NULL);
- else
- cres = PyObject_CallMethod(self->stream,
- (char *)method, "i", sizehint);
- if (cres == NULL)
- goto errorexit;
-
- if (!PyString_Check(cres)) {
- PyErr_SetString(PyExc_TypeError,
- "stream function returned a "
- "non-string object");
- goto errorexit;
- }
-
- endoffile = (PyString_GET_SIZE(cres) == 0);
-
- if (self->pendingsize > 0) {
- PyObject *ctr;
- char *ctrdata;
-
- if (PyString_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
- PyErr_NoMemory();
- goto errorexit;
- }
- rsize = PyString_GET_SIZE(cres) + self->pendingsize;
- ctr = PyString_FromStringAndSize(NULL, rsize);
- if (ctr == NULL)
- goto errorexit;
- ctrdata = PyString_AS_STRING(ctr);
- memcpy(ctrdata, self->pending, self->pendingsize);
- memcpy(ctrdata + self->pendingsize,
- PyString_AS_STRING(cres),
- PyString_GET_SIZE(cres));
- Py_DECREF(cres);
- cres = ctr;
- self->pendingsize = 0;
- }
-
- rsize = PyString_GET_SIZE(cres);
- if (decoder_prepare_buffer(&buf, PyString_AS_STRING(cres),
- rsize) != 0)
- goto errorexit;
-
- if (rsize > 0 && decoder_feed_buffer(
- (MultibyteStatefulDecoderContext *)self, &buf))
- goto errorexit;
-
- if (endoffile || sizehint < 0) {
- if (buf.inbuf < buf.inbuf_end &&
- multibytecodec_decerror(self->codec, &self->state,
- &buf, self->errors, MBERR_TOOFEW))
- goto errorexit;
- }
-
- if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */
- if (decoder_append_pending(STATEFUL_DCTX(self),
- &buf) != 0)
- goto errorexit;
- }
-
- finalsize = (Py_ssize_t)(buf.outbuf -
- PyUnicode_AS_UNICODE(buf.outobj));
- Py_DECREF(cres);
- cres = NULL;
-
- if (sizehint < 0 || finalsize != 0 || rsize == 0)
- break;
-
- sizehint = 1; /* read 1 more byte and retry */
- }
-
- if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
- if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
- goto errorexit;
-
- Py_XDECREF(cres);
- Py_XDECREF(buf.excobj);
- return buf.outobj;
+ MultibyteDecodeBuffer buf;
+ PyObject *cres;
+ Py_ssize_t rsize, finalsize = 0;
+
+ if (sizehint == 0)
+ return PyUnicode_FromUnicode(NULL, 0);
+
+ buf.outobj = buf.excobj = NULL;
+ cres = NULL;
+
+ for (;;) {
+ int endoffile;
+
+ if (sizehint < 0)
+ cres = PyObject_CallMethod(self->stream,
+ (char *)method, NULL);
+ else
+ cres = PyObject_CallMethod(self->stream,
+ (char *)method, "i", sizehint);
+ if (cres == NULL)
+ goto errorexit;
+
+ if (!PyString_Check(cres)) {
+ PyErr_SetString(PyExc_TypeError,
+ "stream function returned a "
+ "non-string object");
+ goto errorexit;
+ }
+
+ endoffile = (PyString_GET_SIZE(cres) == 0);
+
+ if (self->pendingsize > 0) {
+ PyObject *ctr;
+ char *ctrdata;
+
+ if (PyString_GET_SIZE(cres) > PY_SSIZE_T_MAX - self->pendingsize) {
+ PyErr_NoMemory();
+ goto errorexit;
+ }
+ rsize = PyString_GET_SIZE(cres) + self->pendingsize;
+ ctr = PyString_FromStringAndSize(NULL, rsize);
+ if (ctr == NULL)
+ goto errorexit;
+ ctrdata = PyString_AS_STRING(ctr);
+ memcpy(ctrdata, self->pending, self->pendingsize);
+ memcpy(ctrdata + self->pendingsize,
+ PyString_AS_STRING(cres),
+ PyString_GET_SIZE(cres));
+ Py_DECREF(cres);
+ cres = ctr;
+ self->pendingsize = 0;
+ }
+
+ rsize = PyString_GET_SIZE(cres);
+ if (decoder_prepare_buffer(&buf, PyString_AS_STRING(cres),
+ rsize) != 0)
+ goto errorexit;
+
+ if (rsize > 0 && decoder_feed_buffer(
+ (MultibyteStatefulDecoderContext *)self, &buf))
+ goto errorexit;
+
+ if (endoffile || sizehint < 0) {
+ if (buf.inbuf < buf.inbuf_end &&
+ multibytecodec_decerror(self->codec, &self->state,
+ &buf, self->errors, MBERR_TOOFEW))
+ goto errorexit;
+ }
+
+ if (buf.inbuf < buf.inbuf_end) { /* pending sequence exists */
+ if (decoder_append_pending(STATEFUL_DCTX(self),
+ &buf) != 0)
+ goto errorexit;
+ }
+
+ finalsize = (Py_ssize_t)(buf.outbuf -
+ PyUnicode_AS_UNICODE(buf.outobj));
+ Py_DECREF(cres);
+ cres = NULL;
+
+ if (sizehint < 0 || finalsize != 0 || rsize == 0)
+ break;
+
+ sizehint = 1; /* read 1 more byte and retry */
+ }
+
+ if (finalsize != PyUnicode_GET_SIZE(buf.outobj))
+ if (PyUnicode_Resize(&buf.outobj, finalsize) == -1)
+ goto errorexit;
+
+ Py_XDECREF(cres);
+ Py_XDECREF(buf.excobj);
+ return buf.outobj;
errorexit:
- Py_XDECREF(cres);
- Py_XDECREF(buf.excobj);
- Py_XDECREF(buf.outobj);
- return NULL;
+ Py_XDECREF(cres);
+ Py_XDECREF(buf.excobj);
+ Py_XDECREF(buf.outobj);
+ return NULL;
}
static PyObject *
mbstreamreader_read(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizeobj = NULL;
- Py_ssize_t size;
-
- if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
- return NULL;
-
- if (sizeobj == Py_None || sizeobj == NULL)
- size = -1;
- else if (PyInt_Check(sizeobj))
- size = PyInt_AsSsize_t(sizeobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
-
- return mbstreamreader_iread(self, "read", size);
+ PyObject *sizeobj = NULL;
+ Py_ssize_t size;
+
+ if (!PyArg_UnpackTuple(args, "read", 0, 1, &sizeobj))
+ return NULL;
+
+ if (sizeobj == Py_None || sizeobj == NULL)
+ size = -1;
+ else if (PyInt_Check(sizeobj))
+ size = PyInt_AsSsize_t(sizeobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
+
+ return mbstreamreader_iread(self, "read", size);
}
static PyObject *
mbstreamreader_readline(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizeobj = NULL;
- Py_ssize_t size;
-
- if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
- return NULL;
-
- if (sizeobj == Py_None || sizeobj == NULL)
- size = -1;
- else if (PyInt_Check(sizeobj))
- size = PyInt_AsSsize_t(sizeobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
-
- return mbstreamreader_iread(self, "readline", size);
+ PyObject *sizeobj = NULL;
+ Py_ssize_t size;
+
+ if (!PyArg_UnpackTuple(args, "readline", 0, 1, &sizeobj))
+ return NULL;
+
+ if (sizeobj == Py_None || sizeobj == NULL)
+ size = -1;
+ else if (PyInt_Check(sizeobj))
+ size = PyInt_AsSsize_t(sizeobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
+
+ return mbstreamreader_iread(self, "readline", size);
}
static PyObject *
mbstreamreader_readlines(MultibyteStreamReaderObject *self, PyObject *args)
{
- PyObject *sizehintobj = NULL, *r, *sr;
- Py_ssize_t sizehint;
-
- if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj))
- return NULL;
-
- if (sizehintobj == Py_None || sizehintobj == NULL)
- sizehint = -1;
- else if (PyInt_Check(sizehintobj))
- sizehint = PyInt_AsSsize_t(sizehintobj);
- else {
- PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
- return NULL;
- }
-
- r = mbstreamreader_iread(self, "read", sizehint);
- if (r == NULL)
- return NULL;
-
- sr = PyUnicode_Splitlines(r, 1);
- Py_DECREF(r);
- return sr;
+ PyObject *sizehintobj = NULL, *r, *sr;
+ Py_ssize_t sizehint;
+
+ if (!PyArg_UnpackTuple(args, "readlines", 0, 1, &sizehintobj))
+ return NULL;
+
+ if (sizehintobj == Py_None || sizehintobj == NULL)
+ sizehint = -1;
+ else if (PyInt_Check(sizehintobj))
+ sizehint = PyInt_AsSsize_t(sizehintobj);
+ else {
+ PyErr_SetString(PyExc_TypeError, "arg 1 must be an integer");
+ return NULL;
+ }
+
+ r = mbstreamreader_iread(self, "read", sizehint);
+ if (r == NULL)
+ return NULL;
+
+ sr = PyUnicode_Splitlines(r, 1);
+ Py_DECREF(r);
+ return sr;
}
static PyObject *
mbstreamreader_reset(MultibyteStreamReaderObject *self)
{
- if (self->codec->decreset != NULL &&
- self->codec->decreset(&self->state, self->codec->config) != 0)
- return NULL;
- self->pendingsize = 0;
+ if (self->codec->decreset != NULL &&
+ self->codec->decreset(&self->state, self->codec->config) != 0)
+ return NULL;
+ self->pendingsize = 0;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static struct PyMethodDef mbstreamreader_methods[] = {
- {"read", (PyCFunction)mbstreamreader_read,
- METH_VARARGS, NULL},
- {"readline", (PyCFunction)mbstreamreader_readline,
- METH_VARARGS, NULL},
- {"readlines", (PyCFunction)mbstreamreader_readlines,
- METH_VARARGS, NULL},
- {"reset", (PyCFunction)mbstreamreader_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"read", (PyCFunction)mbstreamreader_read,
+ METH_VARARGS, NULL},
+ {"readline", (PyCFunction)mbstreamreader_readline,
+ METH_VARARGS, NULL},
+ {"readlines", (PyCFunction)mbstreamreader_readlines,
+ METH_VARARGS, NULL},
+ {"reset", (PyCFunction)mbstreamreader_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyMemberDef mbstreamreader_members[] = {
- {"stream", T_OBJECT,
- offsetof(MultibyteStreamReaderObject, stream),
- READONLY, NULL},
- {NULL,}
+ {"stream", T_OBJECT,
+ offsetof(MultibyteStreamReaderObject, stream),
+ READONLY, NULL},
+ {NULL,}
};
static PyObject *
mbstreamreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteStreamReaderObject *self;
- PyObject *stream, *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader",
- streamkwarglist, &stream, &errors))
- return NULL;
-
- self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->stream = stream;
- Py_INCREF(stream);
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->decinit != NULL &&
- self->codec->decinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteStreamReaderObject *self;
+ PyObject *stream, *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamReader",
+ streamkwarglist, &stream, &errors))
+ return NULL;
+
+ self = (MultibyteStreamReaderObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->stream = stream;
+ Py_INCREF(stream);
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->decinit != NULL &&
+ self->codec->decinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbstreamreader_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbstreamreader_traverse(MultibyteStreamReaderObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- Py_VISIT(self->stream);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ Py_VISIT(self->stream);
+ return 0;
}
static void
mbstreamreader_dealloc(MultibyteStreamReaderObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_XDECREF(self->stream);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_XDECREF(self->stream);
+ Py_TYPE(self)->tp_free(self);
}
static PyTypeObject MultibyteStreamReader_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteStreamReader", /* tp_name */
- sizeof(MultibyteStreamReaderObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbstreamreader_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 | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbstreamreader_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbstreamreader_methods, /* tp_methods */
- mbstreamreader_members, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbstreamreader_init, /* tp_init */
- 0, /* tp_alloc */
- mbstreamreader_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteStreamReader", /* tp_name */
+ sizeof(MultibyteStreamReaderObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbstreamreader_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 | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbstreamreader_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbstreamreader_methods, /* tp_methods */
+ mbstreamreader_members, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbstreamreader_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbstreamreader_new, /* tp_new */
};
@@ -1551,216 +1551,216 @@ static PyTypeObject MultibyteStreamReader_Type = {
static int
mbstreamwriter_iwrite(MultibyteStreamWriterObject *self,
- PyObject *unistr)
+ PyObject *unistr)
{
- PyObject *str, *wr;
+ PyObject *str, *wr;
- str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0);
- if (str == NULL)
- return -1;
+ str = encoder_encode_stateful(STATEFUL_ECTX(self), unistr, 0);
+ if (str == NULL)
+ return -1;
- wr = PyObject_CallMethod(self->stream, "write", "O", str);
- Py_DECREF(str);
- if (wr == NULL)
- return -1;
+ wr = PyObject_CallMethod(self->stream, "write", "O", str);
+ Py_DECREF(str);
+ if (wr == NULL)
+ return -1;
- Py_DECREF(wr);
- return 0;
+ Py_DECREF(wr);
+ return 0;
}
static PyObject *
mbstreamwriter_write(MultibyteStreamWriterObject *self, PyObject *strobj)
{
- if (mbstreamwriter_iwrite(self, strobj))
- return NULL;
- else
- Py_RETURN_NONE;
+ if (mbstreamwriter_iwrite(self, strobj))
+ return NULL;
+ else
+ Py_RETURN_NONE;
}
static PyObject *
mbstreamwriter_writelines(MultibyteStreamWriterObject *self, PyObject *lines)
{
- PyObject *strobj;
- int i, r;
-
- if (!PySequence_Check(lines)) {
- PyErr_SetString(PyExc_TypeError,
- "arg must be a sequence object");
- return NULL;
- }
-
- for (i = 0; i < PySequence_Length(lines); i++) {
- /* length can be changed even within this loop */
- strobj = PySequence_GetItem(lines, i);
- if (strobj == NULL)
- return NULL;
-
- r = mbstreamwriter_iwrite(self, strobj);
- Py_DECREF(strobj);
- if (r == -1)
- return NULL;
- }
-
- Py_RETURN_NONE;
+ PyObject *strobj;
+ int i, r;
+
+ if (!PySequence_Check(lines)) {
+ PyErr_SetString(PyExc_TypeError,
+ "arg must be a sequence object");
+ return NULL;
+ }
+
+ for (i = 0; i < PySequence_Length(lines); i++) {
+ /* length can be changed even within this loop */
+ strobj = PySequence_GetItem(lines, i);
+ if (strobj == NULL)
+ return NULL;
+
+ r = mbstreamwriter_iwrite(self, strobj);
+ Py_DECREF(strobj);
+ if (r == -1)
+ return NULL;
+ }
+
+ Py_RETURN_NONE;
}
static PyObject *
mbstreamwriter_reset(MultibyteStreamWriterObject *self)
{
- const Py_UNICODE *pending;
- PyObject *pwrt;
-
- pending = self->pending;
- pwrt = multibytecodec_encode(self->codec, &self->state,
- &pending, self->pendingsize, self->errors,
- MBENC_FLUSH | MBENC_RESET);
- /* some pending buffer can be truncated when UnicodeEncodeError is
- * raised on 'strict' mode. but, 'reset' method is designed to
- * reset the pending buffer or states so failed string sequence
- * ought to be missed */
- self->pendingsize = 0;
- if (pwrt == NULL)
- return NULL;
-
- if (PyString_Size(pwrt) > 0) {
- PyObject *wr;
- wr = PyObject_CallMethod(self->stream, "write", "O", pwrt);
- if (wr == NULL) {
- Py_DECREF(pwrt);
- return NULL;
- }
- }
- Py_DECREF(pwrt);
-
- Py_RETURN_NONE;
+ const Py_UNICODE *pending;
+ PyObject *pwrt;
+
+ pending = self->pending;
+ pwrt = multibytecodec_encode(self->codec, &self->state,
+ &pending, self->pendingsize, self->errors,
+ MBENC_FLUSH | MBENC_RESET);
+ /* some pending buffer can be truncated when UnicodeEncodeError is
+ * raised on 'strict' mode. but, 'reset' method is designed to
+ * reset the pending buffer or states so failed string sequence
+ * ought to be missed */
+ self->pendingsize = 0;
+ if (pwrt == NULL)
+ return NULL;
+
+ if (PyString_Size(pwrt) > 0) {
+ PyObject *wr;
+ wr = PyObject_CallMethod(self->stream, "write", "O", pwrt);
+ if (wr == NULL) {
+ Py_DECREF(pwrt);
+ return NULL;
+ }
+ }
+ Py_DECREF(pwrt);
+
+ Py_RETURN_NONE;
}
static PyObject *
mbstreamwriter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- MultibyteStreamWriterObject *self;
- PyObject *stream, *codec = NULL;
- char *errors = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter",
- streamkwarglist, &stream, &errors))
- return NULL;
-
- self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- codec = PyObject_GetAttrString((PyObject *)type, "codec");
- if (codec == NULL)
- goto errorexit;
- if (!MultibyteCodec_Check(codec)) {
- PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
- goto errorexit;
- }
-
- self->codec = ((MultibyteCodecObject *)codec)->codec;
- self->stream = stream;
- Py_INCREF(stream);
- self->pendingsize = 0;
- self->errors = internal_error_callback(errors);
- if (self->errors == NULL)
- goto errorexit;
- if (self->codec->encinit != NULL &&
- self->codec->encinit(&self->state, self->codec->config) != 0)
- goto errorexit;
-
- Py_DECREF(codec);
- return (PyObject *)self;
+ MultibyteStreamWriterObject *self;
+ PyObject *stream, *codec = NULL;
+ char *errors = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|s:StreamWriter",
+ streamkwarglist, &stream, &errors))
+ return NULL;
+
+ self = (MultibyteStreamWriterObject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ codec = PyObject_GetAttrString((PyObject *)type, "codec");
+ if (codec == NULL)
+ goto errorexit;
+ if (!MultibyteCodec_Check(codec)) {
+ PyErr_SetString(PyExc_TypeError, "codec is unexpected type");
+ goto errorexit;
+ }
+
+ self->codec = ((MultibyteCodecObject *)codec)->codec;
+ self->stream = stream;
+ Py_INCREF(stream);
+ self->pendingsize = 0;
+ self->errors = internal_error_callback(errors);
+ if (self->errors == NULL)
+ goto errorexit;
+ if (self->codec->encinit != NULL &&
+ self->codec->encinit(&self->state, self->codec->config) != 0)
+ goto errorexit;
+
+ Py_DECREF(codec);
+ return (PyObject *)self;
errorexit:
- Py_XDECREF(self);
- Py_XDECREF(codec);
- return NULL;
+ Py_XDECREF(self);
+ Py_XDECREF(codec);
+ return NULL;
}
static int
mbstreamwriter_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return 0;
+ return 0;
}
static int
mbstreamwriter_traverse(MultibyteStreamWriterObject *self,
- visitproc visit, void *arg)
+ visitproc visit, void *arg)
{
- if (ERROR_ISCUSTOM(self->errors))
- Py_VISIT(self->errors);
- Py_VISIT(self->stream);
- return 0;
+ if (ERROR_ISCUSTOM(self->errors))
+ Py_VISIT(self->errors);
+ Py_VISIT(self->stream);
+ return 0;
}
static void
mbstreamwriter_dealloc(MultibyteStreamWriterObject *self)
{
- PyObject_GC_UnTrack(self);
- ERROR_DECREF(self->errors);
- Py_XDECREF(self->stream);
- Py_TYPE(self)->tp_free(self);
+ PyObject_GC_UnTrack(self);
+ ERROR_DECREF(self->errors);
+ Py_XDECREF(self->stream);
+ Py_TYPE(self)->tp_free(self);
}
static struct PyMethodDef mbstreamwriter_methods[] = {
- {"write", (PyCFunction)mbstreamwriter_write,
- METH_O, NULL},
- {"writelines", (PyCFunction)mbstreamwriter_writelines,
- METH_O, NULL},
- {"reset", (PyCFunction)mbstreamwriter_reset,
- METH_NOARGS, NULL},
- {NULL, NULL},
+ {"write", (PyCFunction)mbstreamwriter_write,
+ METH_O, NULL},
+ {"writelines", (PyCFunction)mbstreamwriter_writelines,
+ METH_O, NULL},
+ {"reset", (PyCFunction)mbstreamwriter_reset,
+ METH_NOARGS, NULL},
+ {NULL, NULL},
};
static PyMemberDef mbstreamwriter_members[] = {
- {"stream", T_OBJECT,
- offsetof(MultibyteStreamWriterObject, stream),
- READONLY, NULL},
- {NULL,}
+ {"stream", T_OBJECT,
+ offsetof(MultibyteStreamWriterObject, stream),
+ READONLY, NULL},
+ {NULL,}
};
static PyTypeObject MultibyteStreamWriter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "MultibyteStreamWriter", /* tp_name */
- sizeof(MultibyteStreamWriterObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)mbstreamwriter_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 | Py_TPFLAGS_HAVE_GC
- | Py_TPFLAGS_BASETYPE, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)mbstreamwriter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iterext */
- mbstreamwriter_methods, /* tp_methods */
- mbstreamwriter_members, /* tp_members */
- codecctx_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- mbstreamwriter_init, /* tp_init */
- 0, /* tp_alloc */
- mbstreamwriter_new, /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "MultibyteStreamWriter", /* tp_name */
+ sizeof(MultibyteStreamWriterObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)mbstreamwriter_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 | Py_TPFLAGS_HAVE_GC
+ | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)mbstreamwriter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iterext */
+ mbstreamwriter_methods, /* tp_methods */
+ mbstreamwriter_members, /* tp_members */
+ codecctx_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ mbstreamwriter_init, /* tp_init */
+ 0, /* tp_alloc */
+ mbstreamwriter_new, /* tp_new */
};
@@ -1771,59 +1771,59 @@ static PyTypeObject MultibyteStreamWriter_Type = {
static PyObject *
__create_codec(PyObject *ignore, PyObject *arg)
{
- MultibyteCodecObject *self;
- MultibyteCodec *codec;
+ MultibyteCodecObject *self;
+ MultibyteCodec *codec;
- if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) {
- PyErr_SetString(PyExc_ValueError, "argument type invalid");
- return NULL;
- }
+ if (!PyCapsule_IsValid(arg, PyMultibyteCodec_CAPSULE_NAME)) {
+ PyErr_SetString(PyExc_ValueError, "argument type invalid");
+ return NULL;
+ }
- codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME);
- if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0)
- return NULL;
+ codec = PyCapsule_GetPointer(arg, PyMultibyteCodec_CAPSULE_NAME);
+ if (codec->codecinit != NULL && codec->codecinit(codec->config) != 0)
+ return NULL;
- self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type);
- if (self == NULL)
- return NULL;
- self->codec = codec;
+ self = PyObject_New(MultibyteCodecObject, &MultibyteCodec_Type);
+ if (self == NULL)
+ return NULL;
+ self->codec = codec;
- return (PyObject *)self;
+ return (PyObject *)self;
}
static struct PyMethodDef __methods[] = {
- {"__create_codec", (PyCFunction)__create_codec, METH_O},
- {NULL, NULL},
+ {"__create_codec", (PyCFunction)__create_codec, METH_O},
+ {NULL, NULL},
};
PyMODINIT_FUNC
init_multibytecodec(void)
{
- int i;
- PyObject *m;
- PyTypeObject *typelist[] = {
- &MultibyteIncrementalEncoder_Type,
- &MultibyteIncrementalDecoder_Type,
- &MultibyteStreamReader_Type,
- &MultibyteStreamWriter_Type,
- NULL
- };
-
- if (PyType_Ready(&MultibyteCodec_Type) < 0)
- return;
-
- m = Py_InitModule("_multibytecodec", __methods);
- if (m == NULL)
- return;
-
- for (i = 0; typelist[i] != NULL; i++) {
- if (PyType_Ready(typelist[i]) < 0)
- return;
- Py_INCREF(typelist[i]);
- PyModule_AddObject(m, typelist[i]->tp_name,
- (PyObject *)typelist[i]);
- }
-
- if (PyErr_Occurred())
- Py_FatalError("can't initialize the _multibytecodec module");
+ int i;
+ PyObject *m;
+ PyTypeObject *typelist[] = {
+ &MultibyteIncrementalEncoder_Type,
+ &MultibyteIncrementalDecoder_Type,
+ &MultibyteStreamReader_Type,
+ &MultibyteStreamWriter_Type,
+ NULL
+ };
+
+ if (PyType_Ready(&MultibyteCodec_Type) < 0)
+ return;
+
+ m = Py_InitModule("_multibytecodec", __methods);
+ if (m == NULL)
+ return;
+
+ for (i = 0; typelist[i] != NULL; i++) {
+ if (PyType_Ready(typelist[i]) < 0)
+ return;
+ Py_INCREF(typelist[i]);
+ PyModule_AddObject(m, typelist[i]->tp_name,
+ (PyObject *)typelist[i]);
+ }
+
+ if (PyErr_Occurred())
+ Py_FatalError("can't initialize the _multibytecodec module");
}
diff --git a/Modules/cjkcodecs/multibytecodec.h b/Modules/cjkcodecs/multibytecodec.h
index 71c02cc..1b6ef55 100644
--- a/Modules/cjkcodecs/multibytecodec.h
+++ b/Modules/cjkcodecs/multibytecodec.h
@@ -23,114 +23,114 @@ typedef unsigned short ucs2_t, DBCHAR;
#endif
typedef union {
- void *p;
- int i;
- unsigned char c[8];
- ucs2_t u2[4];
- ucs4_t u4[2];
+ void *p;
+ int i;
+ unsigned char c[8];
+ ucs2_t u2[4];
+ ucs4_t u4[2];
} MultibyteCodec_State;
typedef int (*mbcodec_init)(const void *config);
typedef Py_ssize_t (*mbencode_func)(MultibyteCodec_State *state,
- const void *config,
- const Py_UNICODE **inbuf, Py_ssize_t inleft,
- unsigned char **outbuf, Py_ssize_t outleft,
- int flags);
+ const void *config,
+ const Py_UNICODE **inbuf, Py_ssize_t inleft,
+ unsigned char **outbuf, Py_ssize_t outleft,
+ int flags);
typedef int (*mbencodeinit_func)(MultibyteCodec_State *state,
- const void *config);
+ const void *config);
typedef Py_ssize_t (*mbencodereset_func)(MultibyteCodec_State *state,
- const void *config,
- unsigned char **outbuf, Py_ssize_t outleft);
+ const void *config,
+ unsigned char **outbuf, Py_ssize_t outleft);
typedef Py_ssize_t (*mbdecode_func)(MultibyteCodec_State *state,
- const void *config,
- const unsigned char **inbuf, Py_ssize_t inleft,
- Py_UNICODE **outbuf, Py_ssize_t outleft);
+ const void *config,
+ const unsigned char **inbuf, Py_ssize_t inleft,
+ Py_UNICODE **outbuf, Py_ssize_t outleft);
typedef int (*mbdecodeinit_func)(MultibyteCodec_State *state,
- const void *config);
+ const void *config);
typedef Py_ssize_t (*mbdecodereset_func)(MultibyteCodec_State *state,
- const void *config);
+ const void *config);
typedef struct {
- const char *encoding;
- const void *config;
- mbcodec_init codecinit;
- mbencode_func encode;
- mbencodeinit_func encinit;
- mbencodereset_func encreset;
- mbdecode_func decode;
- mbdecodeinit_func decinit;
- mbdecodereset_func decreset;
+ const char *encoding;
+ const void *config;
+ mbcodec_init codecinit;
+ mbencode_func encode;
+ mbencodeinit_func encinit;
+ mbencodereset_func encreset;
+ mbdecode_func decode;
+ mbdecodeinit_func decinit;
+ mbdecodereset_func decreset;
} MultibyteCodec;
typedef struct {
- PyObject_HEAD
- MultibyteCodec *codec;
+ PyObject_HEAD
+ MultibyteCodec *codec;
} MultibyteCodecObject;
#define MultibyteCodec_Check(op) ((op)->ob_type == &MultibyteCodec_Type)
-#define _MultibyteStatefulCodec_HEAD \
- PyObject_HEAD \
- MultibyteCodec *codec; \
- MultibyteCodec_State state; \
- PyObject *errors;
+#define _MultibyteStatefulCodec_HEAD \
+ PyObject_HEAD \
+ MultibyteCodec *codec; \
+ MultibyteCodec_State state; \
+ PyObject *errors;
typedef struct {
- _MultibyteStatefulCodec_HEAD
+ _MultibyteStatefulCodec_HEAD
} MultibyteStatefulCodecContext;
-#define MAXENCPENDING 2
-#define _MultibyteStatefulEncoder_HEAD \
- _MultibyteStatefulCodec_HEAD \
- Py_UNICODE pending[MAXENCPENDING]; \
- Py_ssize_t pendingsize;
+#define MAXENCPENDING 2
+#define _MultibyteStatefulEncoder_HEAD \
+ _MultibyteStatefulCodec_HEAD \
+ Py_UNICODE pending[MAXENCPENDING]; \
+ Py_ssize_t pendingsize;
typedef struct {
- _MultibyteStatefulEncoder_HEAD
+ _MultibyteStatefulEncoder_HEAD
} MultibyteStatefulEncoderContext;
-#define MAXDECPENDING 8
-#define _MultibyteStatefulDecoder_HEAD \
- _MultibyteStatefulCodec_HEAD \
- unsigned char pending[MAXDECPENDING]; \
- Py_ssize_t pendingsize;
+#define MAXDECPENDING 8
+#define _MultibyteStatefulDecoder_HEAD \
+ _MultibyteStatefulCodec_HEAD \
+ unsigned char pending[MAXDECPENDING]; \
+ Py_ssize_t pendingsize;
typedef struct {
- _MultibyteStatefulDecoder_HEAD
+ _MultibyteStatefulDecoder_HEAD
} MultibyteStatefulDecoderContext;
typedef struct {
- _MultibyteStatefulEncoder_HEAD
+ _MultibyteStatefulEncoder_HEAD
} MultibyteIncrementalEncoderObject;
typedef struct {
- _MultibyteStatefulDecoder_HEAD
+ _MultibyteStatefulDecoder_HEAD
} MultibyteIncrementalDecoderObject;
typedef struct {
- _MultibyteStatefulDecoder_HEAD
- PyObject *stream;
+ _MultibyteStatefulDecoder_HEAD
+ PyObject *stream;
} MultibyteStreamReaderObject;
typedef struct {
- _MultibyteStatefulEncoder_HEAD
- PyObject *stream;
+ _MultibyteStatefulEncoder_HEAD
+ PyObject *stream;
} MultibyteStreamWriterObject;
/* positive values for illegal sequences */
-#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
-#define MBERR_TOOFEW (-2) /* incomplete input buffer */
-#define MBERR_INTERNAL (-3) /* internal runtime error */
-
-#define ERROR_STRICT (PyObject *)(1)
-#define ERROR_IGNORE (PyObject *)(2)
-#define ERROR_REPLACE (PyObject *)(3)
-#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
-#define ERROR_DECREF(p) do { \
- if (p != NULL && ERROR_ISCUSTOM(p)) { \
- Py_DECREF(p); \
- } \
+#define MBERR_TOOSMALL (-1) /* insufficient output buffer space */
+#define MBERR_TOOFEW (-2) /* incomplete input buffer */
+#define MBERR_INTERNAL (-3) /* internal runtime error */
+
+#define ERROR_STRICT (PyObject *)(1)
+#define ERROR_IGNORE (PyObject *)(2)
+#define ERROR_REPLACE (PyObject *)(3)
+#define ERROR_ISCUSTOM(p) ((p) < ERROR_STRICT || ERROR_REPLACE < (p))
+#define ERROR_DECREF(p) do { \
+ if (p != NULL && ERROR_ISCUSTOM(p)) { \
+ Py_DECREF(p); \
+ } \
} while (0);
-#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
-#define MBENC_MAX MBENC_FLUSH
+#define MBENC_FLUSH 0x0001 /* encode all characters encodable */
+#define MBENC_MAX MBENC_FLUSH
#define PyMultibyteCodec_CAPSULE_NAME "multibytecodec.__map_*"
diff --git a/Modules/clmodule.c b/Modules/clmodule.c
index d3e0edf..e5d568f 100644
--- a/Modules/clmodule.c
+++ b/Modules/clmodule.c
@@ -12,14 +12,14 @@
#include "Python.h"
typedef struct {
- PyObject_HEAD
- int ob_isCompressor; /* Compressor or Decompressor */
- CL_Handle ob_compressorHdl;
- int *ob_paramtypes;
- int ob_nparams;
+ PyObject_HEAD
+ int ob_isCompressor; /* Compressor or Decompressor */
+ CL_Handle ob_compressorHdl;
+ int *ob_paramtypes;
+ int ob_nparams;
} clobject;
-static PyObject *ClError; /* exception cl.error */
+static PyObject *ClError; /* exception cl.error */
static int error_handler_called = 0;
@@ -30,28 +30,28 @@ static int error_handler_called = 0;
* even though they are really "clobject *". Therefore we cast the
* argument to the proper type using this macro.
*/
-#define SELF ((clobject *) self)
+#define SELF ((clobject *) self)
/********************************************************************
- Utility routines.
+ Utility routines.
********************************************************************/
static void
cl_ErrorHandler(CL_Handle handle, int code, const char *fmt, ...)
{
- va_list ap;
- char errbuf[BUFSIZ]; /* hopefully big enough */
- char *p;
-
- if (PyErr_Occurred()) /* don't change existing error */
- return;
- error_handler_called = 1;
- va_start(ap, fmt);
- vsprintf(errbuf, fmt, ap);
- va_end(ap);
- p = &errbuf[strlen(errbuf) - 1]; /* swat the line feed */
- if (*p == '\n')
- *p = 0;
- PyErr_SetString(ClError, errbuf);
+ va_list ap;
+ char errbuf[BUFSIZ]; /* hopefully big enough */
+ char *p;
+
+ if (PyErr_Occurred()) /* don't change existing error */
+ return;
+ error_handler_called = 1;
+ va_start(ap, fmt);
+ vsprintf(errbuf, fmt, ap);
+ va_end(ap);
+ p = &errbuf[strlen(errbuf) - 1]; /* swat the line feed */
+ if (*p == '\n')
+ *p = 0;
+ PyErr_SetString(ClError, errbuf);
}
/*
@@ -60,839 +60,839 @@ cl_ErrorHandler(CL_Handle handle, int code, const char *fmt, ...)
static int
param_type_is_float(clobject *self, int param)
{
- int bufferlength;
-
- if (self->ob_paramtypes == NULL) {
- error_handler_called = 0;
- bufferlength = clQueryParams(self->ob_compressorHdl, 0, 0);
- if (error_handler_called)
- return -1;
-
- self->ob_paramtypes = PyMem_NEW(int, bufferlength);
- if (self->ob_paramtypes == NULL)
- return -1;
- self->ob_nparams = bufferlength / 2;
-
- (void) clQueryParams(self->ob_compressorHdl,
- self->ob_paramtypes, bufferlength);
- if (error_handler_called) {
- PyMem_DEL(self->ob_paramtypes);
- self->ob_paramtypes = NULL;
- return -1;
- }
- }
-
- if (param < 0 || param >= self->ob_nparams)
- return -1;
-
- if (self->ob_paramtypes[param*2 + 1] == CL_FLOATING_ENUM_VALUE ||
- self->ob_paramtypes[param*2 + 1] == CL_FLOATING_RANGE_VALUE)
- return 1;
- else
- return 0;
+ int bufferlength;
+
+ if (self->ob_paramtypes == NULL) {
+ error_handler_called = 0;
+ bufferlength = clQueryParams(self->ob_compressorHdl, 0, 0);
+ if (error_handler_called)
+ return -1;
+
+ self->ob_paramtypes = PyMem_NEW(int, bufferlength);
+ if (self->ob_paramtypes == NULL)
+ return -1;
+ self->ob_nparams = bufferlength / 2;
+
+ (void) clQueryParams(self->ob_compressorHdl,
+ self->ob_paramtypes, bufferlength);
+ if (error_handler_called) {
+ PyMem_DEL(self->ob_paramtypes);
+ self->ob_paramtypes = NULL;
+ return -1;
+ }
+ }
+
+ if (param < 0 || param >= self->ob_nparams)
+ return -1;
+
+ if (self->ob_paramtypes[param*2 + 1] == CL_FLOATING_ENUM_VALUE ||
+ self->ob_paramtypes[param*2 + 1] == CL_FLOATING_RANGE_VALUE)
+ return 1;
+ else
+ return 0;
}
/********************************************************************
- Single image compression/decompression.
+ Single image compression/decompression.
********************************************************************/
static PyObject *
cl_CompressImage(PyObject *self, PyObject *args)
{
- int compressionScheme, width, height, originalFormat;
- float compressionRatio;
- int frameBufferSize, compressedBufferSize;
- char *frameBuffer;
- PyObject *compressedBuffer;
-
- if (!PyArg_ParseTuple(args, "iiiifs#", &compressionScheme,
- &width, &height,
- &originalFormat, &compressionRatio, &frameBuffer,
- &frameBufferSize))
- return NULL;
+ int compressionScheme, width, height, originalFormat;
+ float compressionRatio;
+ int frameBufferSize, compressedBufferSize;
+ char *frameBuffer;
+ PyObject *compressedBuffer;
+
+ if (!PyArg_ParseTuple(args, "iiiifs#", &compressionScheme,
+ &width, &height,
+ &originalFormat, &compressionRatio, &frameBuffer,
+ &frameBufferSize))
+ return NULL;
retry:
- compressedBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
- if (compressedBuffer == NULL)
- return NULL;
-
- compressedBufferSize = frameBufferSize;
- error_handler_called = 0;
- if (clCompressImage(compressionScheme, width, height, originalFormat,
- compressionRatio, (void *) frameBuffer,
- &compressedBufferSize,
- (void *) PyString_AsString(compressedBuffer))
- == FAILURE || error_handler_called) {
- Py_DECREF(compressedBuffer);
- if (!error_handler_called)
- PyErr_SetString(ClError, "clCompressImage failed");
- return NULL;
- }
-
- if (compressedBufferSize > frameBufferSize) {
- frameBufferSize = compressedBufferSize;
- Py_DECREF(compressedBuffer);
- goto retry;
- }
-
- if (compressedBufferSize < frameBufferSize)
- _PyString_Resize(&compressedBuffer, compressedBufferSize);
-
- return compressedBuffer;
+ compressedBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
+ if (compressedBuffer == NULL)
+ return NULL;
+
+ compressedBufferSize = frameBufferSize;
+ error_handler_called = 0;
+ if (clCompressImage(compressionScheme, width, height, originalFormat,
+ compressionRatio, (void *) frameBuffer,
+ &compressedBufferSize,
+ (void *) PyString_AsString(compressedBuffer))
+ == FAILURE || error_handler_called) {
+ Py_DECREF(compressedBuffer);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "clCompressImage failed");
+ return NULL;
+ }
+
+ if (compressedBufferSize > frameBufferSize) {
+ frameBufferSize = compressedBufferSize;
+ Py_DECREF(compressedBuffer);
+ goto retry;
+ }
+
+ if (compressedBufferSize < frameBufferSize)
+ _PyString_Resize(&compressedBuffer, compressedBufferSize);
+
+ return compressedBuffer;
}
static PyObject *
cl_DecompressImage(PyObject *self, PyObject *args)
{
- int compressionScheme, width, height, originalFormat;
- char *compressedBuffer;
- int compressedBufferSize, frameBufferSize;
- PyObject *frameBuffer;
-
- if (!PyArg_ParseTuple(args, "iiiis#", &compressionScheme, &width, &height,
- &originalFormat, &compressedBuffer,
- &compressedBufferSize))
- return NULL;
-
- frameBufferSize = width * height * CL_BytesPerPixel(originalFormat);
-
- frameBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
- if (frameBuffer == NULL)
- return NULL;
-
- error_handler_called = 0;
- if (clDecompressImage(compressionScheme, width, height, originalFormat,
- compressedBufferSize, compressedBuffer,
- (void *) PyString_AsString(frameBuffer))
- == FAILURE || error_handler_called) {
- Py_DECREF(frameBuffer);
- if (!error_handler_called)
- PyErr_SetString(ClError, "clDecompressImage failed");
- return NULL;
- }
-
- return frameBuffer;
+ int compressionScheme, width, height, originalFormat;
+ char *compressedBuffer;
+ int compressedBufferSize, frameBufferSize;
+ PyObject *frameBuffer;
+
+ if (!PyArg_ParseTuple(args, "iiiis#", &compressionScheme, &width, &height,
+ &originalFormat, &compressedBuffer,
+ &compressedBufferSize))
+ return NULL;
+
+ frameBufferSize = width * height * CL_BytesPerPixel(originalFormat);
+
+ frameBuffer = PyString_FromStringAndSize(NULL, frameBufferSize);
+ if (frameBuffer == NULL)
+ return NULL;
+
+ error_handler_called = 0;
+ if (clDecompressImage(compressionScheme, width, height, originalFormat,
+ compressedBufferSize, compressedBuffer,
+ (void *) PyString_AsString(frameBuffer))
+ == FAILURE || error_handler_called) {
+ Py_DECREF(frameBuffer);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "clDecompressImage failed");
+ return NULL;
+ }
+
+ return frameBuffer;
}
/********************************************************************
- Sequential compression/decompression.
+ Sequential compression/decompression.
********************************************************************/
-#define CheckCompressor(self) if ((self)->ob_compressorHdl == NULL) { \
- PyErr_SetString(PyExc_RuntimeError, "(de)compressor not active"); \
- return NULL; \
+#define CheckCompressor(self) if ((self)->ob_compressorHdl == NULL) { \
+ PyErr_SetString(PyExc_RuntimeError, "(de)compressor not active"); \
+ return NULL; \
}
static PyObject *
doClose(clobject *self, int (*close_func)(CL_Handle))
{
- CheckCompressor(self);
+ CheckCompressor(self);
- error_handler_called = 0;
- if ((*close_func)(self->ob_compressorHdl) == FAILURE ||
- error_handler_called) {
- if (!error_handler_called)
- PyErr_SetString(ClError, "close failed");
- return NULL;
- }
+ error_handler_called = 0;
+ if ((*close_func)(self->ob_compressorHdl) == FAILURE ||
+ error_handler_called) {
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "close failed");
+ return NULL;
+ }
- self->ob_compressorHdl = NULL;
+ self->ob_compressorHdl = NULL;
- if (self->ob_paramtypes)
- PyMem_DEL(self->ob_paramtypes);
- self->ob_paramtypes = NULL;
+ if (self->ob_paramtypes)
+ PyMem_DEL(self->ob_paramtypes);
+ self->ob_paramtypes = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
clm_CloseCompressor(PyObject *self)
{
- return doClose(SELF, clCloseCompressor);
+ return doClose(SELF, clCloseCompressor);
}
static PyObject *
clm_CloseDecompressor(PyObject *self)
{
- return doClose(SELF, clCloseDecompressor);
+ return doClose(SELF, clCloseDecompressor);
}
static PyObject *
clm_Compress(PyObject *self, PyObject *args)
{
- int numberOfFrames;
- int frameBufferSize, compressedBufferSize, size;
- char *frameBuffer;
- PyObject *data;
-
- CheckCompressor(SELF);
-
- if (!PyArg_Parse(args, "(is#)", &numberOfFrames,
- &frameBuffer, &frameBufferSize))
- return NULL;
-
- error_handler_called = 0;
- size = clGetParam(SELF->ob_compressorHdl, CL_COMPRESSED_BUFFER_SIZE);
- compressedBufferSize = size;
- if (error_handler_called)
- return NULL;
-
- data = PyString_FromStringAndSize(NULL, size);
- if (data == NULL)
- return NULL;
-
- error_handler_called = 0;
- if (clCompress(SELF->ob_compressorHdl, numberOfFrames,
- (void *) frameBuffer, &compressedBufferSize,
- (void *) PyString_AsString(data)) == FAILURE ||
- error_handler_called) {
- Py_DECREF(data);
- if (!error_handler_called)
- PyErr_SetString(ClError, "compress failed");
- return NULL;
- }
-
- if (compressedBufferSize < size)
- if (_PyString_Resize(&data, compressedBufferSize))
- return NULL;
-
- if (compressedBufferSize > size) {
- /* we didn't get all "compressed" data */
- Py_DECREF(data);
- PyErr_SetString(ClError,
- "compressed data is more than fitted");
- return NULL;
- }
-
- return data;
+ int numberOfFrames;
+ int frameBufferSize, compressedBufferSize, size;
+ char *frameBuffer;
+ PyObject *data;
+
+ CheckCompressor(SELF);
+
+ if (!PyArg_Parse(args, "(is#)", &numberOfFrames,
+ &frameBuffer, &frameBufferSize))
+ return NULL;
+
+ error_handler_called = 0;
+ size = clGetParam(SELF->ob_compressorHdl, CL_COMPRESSED_BUFFER_SIZE);
+ compressedBufferSize = size;
+ if (error_handler_called)
+ return NULL;
+
+ data = PyString_FromStringAndSize(NULL, size);
+ if (data == NULL)
+ return NULL;
+
+ error_handler_called = 0;
+ if (clCompress(SELF->ob_compressorHdl, numberOfFrames,
+ (void *) frameBuffer, &compressedBufferSize,
+ (void *) PyString_AsString(data)) == FAILURE ||
+ error_handler_called) {
+ Py_DECREF(data);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "compress failed");
+ return NULL;
+ }
+
+ if (compressedBufferSize < size)
+ if (_PyString_Resize(&data, compressedBufferSize))
+ return NULL;
+
+ if (compressedBufferSize > size) {
+ /* we didn't get all "compressed" data */
+ Py_DECREF(data);
+ PyErr_SetString(ClError,
+ "compressed data is more than fitted");
+ return NULL;
+ }
+
+ return data;
}
static PyObject *
clm_Decompress(PyObject *self, PyObject *args)
{
- PyObject *data;
- int numberOfFrames;
- char *compressedData;
- int compressedDataSize, dataSize;
-
- CheckCompressor(SELF);
-
- if (!PyArg_Parse(args, "(is#)", &numberOfFrames, &compressedData,
- &compressedDataSize))
- return NULL;
-
- error_handler_called = 0;
- dataSize = clGetParam(SELF->ob_compressorHdl, CL_FRAME_BUFFER_SIZE);
- if (error_handler_called)
- return NULL;
-
- data = PyString_FromStringAndSize(NULL, dataSize);
- if (data == NULL)
- return NULL;
-
- error_handler_called = 0;
- if (clDecompress(SELF->ob_compressorHdl, numberOfFrames,
- compressedDataSize, (void *) compressedData,
- (void *) PyString_AsString(data)) == FAILURE ||
- error_handler_called) {
- Py_DECREF(data);
- if (!error_handler_called)
- PyErr_SetString(ClError, "decompress failed");
- return NULL;
- }
-
- return data;
+ PyObject *data;
+ int numberOfFrames;
+ char *compressedData;
+ int compressedDataSize, dataSize;
+
+ CheckCompressor(SELF);
+
+ if (!PyArg_Parse(args, "(is#)", &numberOfFrames, &compressedData,
+ &compressedDataSize))
+ return NULL;
+
+ error_handler_called = 0;
+ dataSize = clGetParam(SELF->ob_compressorHdl, CL_FRAME_BUFFER_SIZE);
+ if (error_handler_called)
+ return NULL;
+
+ data = PyString_FromStringAndSize(NULL, dataSize);
+ if (data == NULL)
+ return NULL;
+
+ error_handler_called = 0;
+ if (clDecompress(SELF->ob_compressorHdl, numberOfFrames,
+ compressedDataSize, (void *) compressedData,
+ (void *) PyString_AsString(data)) == FAILURE ||
+ error_handler_called) {
+ Py_DECREF(data);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "decompress failed");
+ return NULL;
+ }
+
+ return data;
}
static PyObject *
doParams(clobject *self, PyObject *args, int (*func)(CL_Handle, int *, int),
- int modified)
+ int modified)
{
- PyObject *list, *v;
- int *PVbuffer;
- int length;
- int i;
- float number;
-
- CheckCompressor(self);
-
- if (!PyArg_Parse(args, "O", &list))
- return NULL;
- if (!PyList_Check(list)) {
- PyErr_BadArgument();
- return NULL;
- }
- length = PyList_Size(list);
- PVbuffer = PyMem_NEW(int, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
- for (i = 0; i < length; i++) {
- v = PyList_GetItem(list, i);
- if (PyFloat_Check(v)) {
- number = PyFloat_AsDouble(v);
- PVbuffer[i] = CL_TypeIsInt(number);
- } else if (PyInt_Check(v)) {
- PVbuffer[i] = PyInt_AsLong(v);
- if ((i & 1) &&
- param_type_is_float(self, PVbuffer[i-1]) > 0) {
- number = PVbuffer[i];
- PVbuffer[i] = CL_TypeIsInt(number);
- }
- } else {
- PyMem_DEL(PVbuffer);
- PyErr_BadArgument();
- return NULL;
- }
- }
-
- error_handler_called = 0;
- (*func)(self->ob_compressorHdl, PVbuffer, length);
- if (error_handler_called) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- if (modified) {
- for (i = 0; i < length; i++) {
- if ((i & 1) &&
- param_type_is_float(self, PVbuffer[i-1]) > 0) {
- number = CL_TypeIsFloat(PVbuffer[i]);
- v = PyFloat_FromDouble(number);
- } else
- v = PyInt_FromLong(PVbuffer[i]);
- PyList_SetItem(list, i, v);
- }
- }
-
- PyMem_DEL(PVbuffer);
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *list, *v;
+ int *PVbuffer;
+ int length;
+ int i;
+ float number;
+
+ CheckCompressor(self);
+
+ if (!PyArg_Parse(args, "O", &list))
+ return NULL;
+ if (!PyList_Check(list)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ length = PyList_Size(list);
+ PVbuffer = PyMem_NEW(int, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+ for (i = 0; i < length; i++) {
+ v = PyList_GetItem(list, i);
+ if (PyFloat_Check(v)) {
+ number = PyFloat_AsDouble(v);
+ PVbuffer[i] = CL_TypeIsInt(number);
+ } else if (PyInt_Check(v)) {
+ PVbuffer[i] = PyInt_AsLong(v);
+ if ((i & 1) &&
+ param_type_is_float(self, PVbuffer[i-1]) > 0) {
+ number = PVbuffer[i];
+ PVbuffer[i] = CL_TypeIsInt(number);
+ }
+ } else {
+ PyMem_DEL(PVbuffer);
+ PyErr_BadArgument();
+ return NULL;
+ }
+ }
+
+ error_handler_called = 0;
+ (*func)(self->ob_compressorHdl, PVbuffer, length);
+ if (error_handler_called) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ if (modified) {
+ for (i = 0; i < length; i++) {
+ if ((i & 1) &&
+ param_type_is_float(self, PVbuffer[i-1]) > 0) {
+ number = CL_TypeIsFloat(PVbuffer[i]);
+ v = PyFloat_FromDouble(number);
+ } else
+ v = PyInt_FromLong(PVbuffer[i]);
+ PyList_SetItem(list, i, v);
+ }
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
clm_GetParams(PyObject *self, PyObject *args)
{
- return doParams(SELF, args, clGetParams, 1);
+ return doParams(SELF, args, clGetParams, 1);
}
static PyObject *
clm_SetParams(PyObject *self, PyObject *args)
{
- return doParams(SELF, args, clSetParams, 0);
+ return doParams(SELF, args, clSetParams, 0);
}
static PyObject *
do_get(clobject *self, PyObject *args, int (*func)(CL_Handle, int))
{
- int paramID, value;
- float fvalue;
+ int paramID, value;
+ float fvalue;
- CheckCompressor(self);
+ CheckCompressor(self);
- if (!PyArg_Parse(args, "i", &paramID))
- return NULL;
+ if (!PyArg_Parse(args, "i", &paramID))
+ return NULL;
- error_handler_called = 0;
- value = (*func)(self->ob_compressorHdl, paramID);
- if (error_handler_called)
- return NULL;
+ error_handler_called = 0;
+ value = (*func)(self->ob_compressorHdl, paramID);
+ if (error_handler_called)
+ return NULL;
- if (param_type_is_float(self, paramID) > 0) {
- fvalue = CL_TypeIsFloat(value);
- return PyFloat_FromDouble(fvalue);
- }
+ if (param_type_is_float(self, paramID) > 0) {
+ fvalue = CL_TypeIsFloat(value);
+ return PyFloat_FromDouble(fvalue);
+ }
- return PyInt_FromLong(value);
+ return PyInt_FromLong(value);
}
static PyObject *
clm_GetParam(PyObject *self, PyObject *args)
{
- return do_get(SELF, args, clGetParam);
+ return do_get(SELF, args, clGetParam);
}
static PyObject *
clm_GetDefault(PyObject *self, PyObject *args)
{
- return do_get(SELF, args, clGetDefault);
+ return do_get(SELF, args, clGetDefault);
}
static PyObject *
clm_SetParam(PyObject *self, PyObject *args)
{
- int paramID, value;
- float fvalue;
-
- CheckCompressor(SELF);
-
- if (!PyArg_Parse(args, "(ii)", &paramID, &value)) {
- PyErr_Clear();
- if (!PyArg_Parse(args, "(if)", &paramID, &fvalue)) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "bad argument list (format '(ii)' or '(if)')");
- return NULL;
- }
- value = CL_TypeIsInt(fvalue);
- } else {
- if (param_type_is_float(SELF, paramID) > 0) {
- fvalue = value;
- value = CL_TypeIsInt(fvalue);
- }
- }
-
- error_handler_called = 0;
- value = clSetParam(SELF->ob_compressorHdl, paramID, value);
- if (error_handler_called)
- return NULL;
-
- if (param_type_is_float(SELF, paramID) > 0)
- return PyFloat_FromDouble(CL_TypeIsFloat(value));
- else
- return PyInt_FromLong(value);
+ int paramID, value;
+ float fvalue;
+
+ CheckCompressor(SELF);
+
+ if (!PyArg_Parse(args, "(ii)", &paramID, &value)) {
+ PyErr_Clear();
+ if (!PyArg_Parse(args, "(if)", &paramID, &fvalue)) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "bad argument list (format '(ii)' or '(if)')");
+ return NULL;
+ }
+ value = CL_TypeIsInt(fvalue);
+ } else {
+ if (param_type_is_float(SELF, paramID) > 0) {
+ fvalue = value;
+ value = CL_TypeIsInt(fvalue);
+ }
+ }
+
+ error_handler_called = 0;
+ value = clSetParam(SELF->ob_compressorHdl, paramID, value);
+ if (error_handler_called)
+ return NULL;
+
+ if (param_type_is_float(SELF, paramID) > 0)
+ return PyFloat_FromDouble(CL_TypeIsFloat(value));
+ else
+ return PyInt_FromLong(value);
}
static PyObject *
clm_GetParamID(PyObject *self, PyObject *args)
{
- char *name;
- int value;
+ char *name;
+ int value;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "s", &name))
- return NULL;
+ if (!PyArg_Parse(args, "s", &name))
+ return NULL;
- error_handler_called = 0;
- value = clGetParamID(SELF->ob_compressorHdl, name);
- if (value == FAILURE || error_handler_called) {
- if (!error_handler_called)
- PyErr_SetString(ClError, "getparamid failed");
- return NULL;
- }
+ error_handler_called = 0;
+ value = clGetParamID(SELF->ob_compressorHdl, name);
+ if (value == FAILURE || error_handler_called) {
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "getparamid failed");
+ return NULL;
+ }
- return PyInt_FromLong(value);
+ return PyInt_FromLong(value);
}
static PyObject *
clm_QueryParams(PyObject *self)
{
- int bufferlength;
- int *PVbuffer;
- PyObject *list;
- int i;
-
- CheckCompressor(SELF);
-
- error_handler_called = 0;
- bufferlength = clQueryParams(SELF->ob_compressorHdl, 0, 0);
- if (error_handler_called)
- return NULL;
-
- PVbuffer = PyMem_NEW(int, bufferlength);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
-
- bufferlength = clQueryParams(SELF->ob_compressorHdl, PVbuffer,
- bufferlength);
- if (error_handler_called) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- list = PyList_New(bufferlength);
- if (list == NULL) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- for (i = 0; i < bufferlength; i++) {
- if (i & 1)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
- else if (PVbuffer[i] == 0) {
- Py_INCREF(Py_None);
- PyList_SetItem(list, i, Py_None);
- } else
- PyList_SetItem(list, i,
- PyString_FromString((char *) PVbuffer[i]));
- }
-
- PyMem_DEL(PVbuffer);
-
- return list;
+ int bufferlength;
+ int *PVbuffer;
+ PyObject *list;
+ int i;
+
+ CheckCompressor(SELF);
+
+ error_handler_called = 0;
+ bufferlength = clQueryParams(SELF->ob_compressorHdl, 0, 0);
+ if (error_handler_called)
+ return NULL;
+
+ PVbuffer = PyMem_NEW(int, bufferlength);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+
+ bufferlength = clQueryParams(SELF->ob_compressorHdl, PVbuffer,
+ bufferlength);
+ if (error_handler_called) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ list = PyList_New(bufferlength);
+ if (list == NULL) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ for (i = 0; i < bufferlength; i++) {
+ if (i & 1)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+ else if (PVbuffer[i] == 0) {
+ Py_INCREF(Py_None);
+ PyList_SetItem(list, i, Py_None);
+ } else
+ PyList_SetItem(list, i,
+ PyString_FromString((char *) PVbuffer[i]));
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ return list;
}
static PyObject *
clm_GetMinMax(PyObject *self, PyObject *args)
{
- int param, min, max;
- float fmin, fmax;
+ int param, min, max;
+ float fmin, fmax;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "i", &param))
- return NULL;
+ if (!PyArg_Parse(args, "i", &param))
+ return NULL;
- clGetMinMax(SELF->ob_compressorHdl, param, &min, &max);
+ clGetMinMax(SELF->ob_compressorHdl, param, &min, &max);
- if (param_type_is_float(SELF, param) > 0) {
- fmin = CL_TypeIsFloat(min);
- fmax = CL_TypeIsFloat(max);
- return Py_BuildValue("(ff)", fmin, fmax);
- }
+ if (param_type_is_float(SELF, param) > 0) {
+ fmin = CL_TypeIsFloat(min);
+ fmax = CL_TypeIsFloat(max);
+ return Py_BuildValue("(ff)", fmin, fmax);
+ }
- return Py_BuildValue("(ii)", min, max);
+ return Py_BuildValue("(ii)", min, max);
}
static PyObject *
clm_GetName(PyObject *self, PyObject *args)
{
- int param;
- char *name;
+ int param;
+ char *name;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "i", &param))
- return NULL;
+ if (!PyArg_Parse(args, "i", &param))
+ return NULL;
- error_handler_called = 0;
- name = clGetName(SELF->ob_compressorHdl, param);
- if (name == NULL || error_handler_called) {
- if (!error_handler_called)
- PyErr_SetString(ClError, "getname failed");
- return NULL;
- }
+ error_handler_called = 0;
+ name = clGetName(SELF->ob_compressorHdl, param);
+ if (name == NULL || error_handler_called) {
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "getname failed");
+ return NULL;
+ }
- return PyString_FromString(name);
+ return PyString_FromString(name);
}
static PyObject *
clm_QuerySchemeFromHandle(PyObject *self)
{
- CheckCompressor(SELF);
- return PyInt_FromLong(clQuerySchemeFromHandle(SELF->ob_compressorHdl));
+ CheckCompressor(SELF);
+ return PyInt_FromLong(clQuerySchemeFromHandle(SELF->ob_compressorHdl));
}
static PyObject *
clm_ReadHeader(PyObject *self, PyObject *args)
{
- char *header;
- int headerSize;
+ char *header;
+ int headerSize;
- CheckCompressor(SELF);
+ CheckCompressor(SELF);
- if (!PyArg_Parse(args, "s#", &header, &headerSize))
- return NULL;
+ if (!PyArg_Parse(args, "s#", &header, &headerSize))
+ return NULL;
- return PyInt_FromLong(clReadHeader(SELF->ob_compressorHdl,
- headerSize, header));
+ return PyInt_FromLong(clReadHeader(SELF->ob_compressorHdl,
+ headerSize, header));
}
static PyMethodDef compressor_methods[] = {
- {"close", clm_CloseCompressor, METH_NOARGS}, /* alias */
- {"CloseCompressor", clm_CloseCompressor, METH_NOARGS},
- {"Compress", clm_Compress, METH_OLDARGS},
- {"GetDefault", clm_GetDefault, METH_OLDARGS},
- {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
- {"GetName", clm_GetName, METH_OLDARGS},
- {"GetParam", clm_GetParam, METH_OLDARGS},
- {"GetParamID", clm_GetParamID, METH_OLDARGS},
- {"GetParams", clm_GetParams, METH_OLDARGS},
- {"QueryParams", clm_QueryParams, METH_NOARGS},
- {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
- {"SetParam", clm_SetParam, METH_OLDARGS},
- {"SetParams", clm_SetParams, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"close", clm_CloseCompressor, METH_NOARGS}, /* alias */
+ {"CloseCompressor", clm_CloseCompressor, METH_NOARGS},
+ {"Compress", clm_Compress, METH_OLDARGS},
+ {"GetDefault", clm_GetDefault, METH_OLDARGS},
+ {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
+ {"GetName", clm_GetName, METH_OLDARGS},
+ {"GetParam", clm_GetParam, METH_OLDARGS},
+ {"GetParamID", clm_GetParamID, METH_OLDARGS},
+ {"GetParams", clm_GetParams, METH_OLDARGS},
+ {"QueryParams", clm_QueryParams, METH_NOARGS},
+ {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
+ {"SetParam", clm_SetParam, METH_OLDARGS},
+ {"SetParams", clm_SetParams, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static PyMethodDef decompressor_methods[] = {
- {"close", clm_CloseDecompressor, METH_NOARGS}, /* alias */
- {"CloseDecompressor", clm_CloseDecompressor, METH_NOARGS},
- {"Decompress", clm_Decompress, METH_OLDARGS},
- {"GetDefault", clm_GetDefault, METH_OLDARGS},
- {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
- {"GetName", clm_GetName, METH_OLDARGS},
- {"GetParam", clm_GetParam, METH_OLDARGS},
- {"GetParamID", clm_GetParamID, METH_OLDARGS},
- {"GetParams", clm_GetParams, METH_OLDARGS},
- {"ReadHeader", clm_ReadHeader, METH_OLDARGS},
- {"QueryParams", clm_QueryParams, METH_NOARGS},
- {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
- {"SetParam", clm_SetParam, METH_OLDARGS},
- {"SetParams", clm_SetParams, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"close", clm_CloseDecompressor, METH_NOARGS}, /* alias */
+ {"CloseDecompressor", clm_CloseDecompressor, METH_NOARGS},
+ {"Decompress", clm_Decompress, METH_OLDARGS},
+ {"GetDefault", clm_GetDefault, METH_OLDARGS},
+ {"GetMinMax", clm_GetMinMax, METH_OLDARGS},
+ {"GetName", clm_GetName, METH_OLDARGS},
+ {"GetParam", clm_GetParam, METH_OLDARGS},
+ {"GetParamID", clm_GetParamID, METH_OLDARGS},
+ {"GetParams", clm_GetParams, METH_OLDARGS},
+ {"ReadHeader", clm_ReadHeader, METH_OLDARGS},
+ {"QueryParams", clm_QueryParams, METH_NOARGS},
+ {"QuerySchemeFromHandle",clm_QuerySchemeFromHandle, METH_NOARGS},
+ {"SetParam", clm_SetParam, METH_OLDARGS},
+ {"SetParams", clm_SetParams, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static void
cl_dealloc(PyObject *self)
{
- if (SELF->ob_compressorHdl) {
- if (SELF->ob_isCompressor)
- clCloseCompressor(SELF->ob_compressorHdl);
- else
- clCloseDecompressor(SELF->ob_compressorHdl);
- }
- PyObject_Del(self);
+ if (SELF->ob_compressorHdl) {
+ if (SELF->ob_isCompressor)
+ clCloseCompressor(SELF->ob_compressorHdl);
+ else
+ clCloseDecompressor(SELF->ob_compressorHdl);
+ }
+ PyObject_Del(self);
}
static PyObject *
cl_getattr(PyObject *self, char *name)
{
- if (SELF->ob_isCompressor)
- return Py_FindMethod(compressor_methods, self, name);
- else
- return Py_FindMethod(decompressor_methods, self, name);
+ if (SELF->ob_isCompressor)
+ return Py_FindMethod(compressor_methods, self, name);
+ else
+ return Py_FindMethod(decompressor_methods, self, name);
}
static PyTypeObject Cltype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "cl.cl", /*tp_name*/
- sizeof(clobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)cl_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)cl_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "cl.cl", /*tp_name*/
+ sizeof(clobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)cl_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)cl_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
};
static PyObject *
doOpen(PyObject *self, PyObject *args, int (*open_func)(int, CL_Handle *),
int iscompressor)
{
- int scheme;
- clobject *new;
-
- if (!PyArg_ParseTuple(args, "i", &scheme))
- return NULL;
-
- new = PyObject_New(clobject, &Cltype);
- if (new == NULL)
- return NULL;
-
- new->ob_compressorHdl = NULL;
- new->ob_isCompressor = iscompressor;
- new->ob_paramtypes = NULL;
-
- error_handler_called = 0;
- if ((*open_func)(scheme, &new->ob_compressorHdl) == FAILURE ||
- error_handler_called) {
- Py_DECREF(new);
- if (!error_handler_called)
- PyErr_SetString(ClError, "Open(De)Compressor failed");
- return NULL;
- }
- return (PyObject *)new;
+ int scheme;
+ clobject *new;
+
+ if (!PyArg_ParseTuple(args, "i", &scheme))
+ return NULL;
+
+ new = PyObject_New(clobject, &Cltype);
+ if (new == NULL)
+ return NULL;
+
+ new->ob_compressorHdl = NULL;
+ new->ob_isCompressor = iscompressor;
+ new->ob_paramtypes = NULL;
+
+ error_handler_called = 0;
+ if ((*open_func)(scheme, &new->ob_compressorHdl) == FAILURE ||
+ error_handler_called) {
+ Py_DECREF(new);
+ if (!error_handler_called)
+ PyErr_SetString(ClError, "Open(De)Compressor failed");
+ return NULL;
+ }
+ return (PyObject *)new;
}
static PyObject *
cl_OpenCompressor(PyObject *self, PyObject *args)
{
- return doOpen(self, args, clOpenCompressor, 1);
+ return doOpen(self, args, clOpenCompressor, 1);
}
static PyObject *
cl_OpenDecompressor(PyObject *self, PyObject *args)
{
- return doOpen(self, args, clOpenDecompressor, 0);
+ return doOpen(self, args, clOpenDecompressor, 0);
}
static PyObject *
cl_QueryScheme(PyObject *self, PyObject *args)
{
- char *header;
- int headerlen;
- int scheme;
+ char *header;
+ int headerlen;
+ int scheme;
- if (!PyArg_ParseTuple(args, "s#", &header, &headerlen))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s#", &header, &headerlen))
+ return NULL;
- scheme = clQueryScheme(header);
- if (scheme < 0) {
- PyErr_SetString(ClError, "unknown compression scheme");
- return NULL;
- }
+ scheme = clQueryScheme(header);
+ if (scheme < 0) {
+ PyErr_SetString(ClError, "unknown compression scheme");
+ return NULL;
+ }
- return PyInt_FromLong(scheme);
+ return PyInt_FromLong(scheme);
}
static PyObject *
cl_QueryMaxHeaderSize(PyObject *self, PyObject *args)
{
- int scheme;
+ int scheme;
- if (!PyArg_ParseTuple(args, "i", &scheme))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i", &scheme))
+ return NULL;
- return PyInt_FromLong(clQueryMaxHeaderSize(scheme));
+ return PyInt_FromLong(clQueryMaxHeaderSize(scheme));
}
static PyObject *
cl_QueryAlgorithms(PyObject *self, PyObject *args)
{
- int algorithmMediaType;
- int bufferlength;
- int *PVbuffer;
- PyObject *list;
- int i;
-
- if (!PyArg_ParseTuple(args, "i", &algorithmMediaType))
- return NULL;
-
- error_handler_called = 0;
- bufferlength = clQueryAlgorithms(algorithmMediaType, 0, 0);
- if (error_handler_called)
- return NULL;
-
- PVbuffer = PyMem_NEW(int, bufferlength);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
-
- bufferlength = clQueryAlgorithms(algorithmMediaType, PVbuffer,
- bufferlength);
- if (error_handler_called) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- list = PyList_New(bufferlength);
- if (list == NULL) {
- PyMem_DEL(PVbuffer);
- return NULL;
- }
-
- for (i = 0; i < bufferlength; i++) {
- if (i & 1)
- PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
- else if (PVbuffer[i] == 0) {
- Py_INCREF(Py_None);
- PyList_SetItem(list, i, Py_None);
- } else
- PyList_SetItem(list, i,
- PyString_FromString((char *) PVbuffer[i]));
- }
-
- PyMem_DEL(PVbuffer);
-
- return list;
+ int algorithmMediaType;
+ int bufferlength;
+ int *PVbuffer;
+ PyObject *list;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "i", &algorithmMediaType))
+ return NULL;
+
+ error_handler_called = 0;
+ bufferlength = clQueryAlgorithms(algorithmMediaType, 0, 0);
+ if (error_handler_called)
+ return NULL;
+
+ PVbuffer = PyMem_NEW(int, bufferlength);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+
+ bufferlength = clQueryAlgorithms(algorithmMediaType, PVbuffer,
+ bufferlength);
+ if (error_handler_called) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ list = PyList_New(bufferlength);
+ if (list == NULL) {
+ PyMem_DEL(PVbuffer);
+ return NULL;
+ }
+
+ for (i = 0; i < bufferlength; i++) {
+ if (i & 1)
+ PyList_SetItem(list, i, PyInt_FromLong(PVbuffer[i]));
+ else if (PVbuffer[i] == 0) {
+ Py_INCREF(Py_None);
+ PyList_SetItem(list, i, Py_None);
+ } else
+ PyList_SetItem(list, i,
+ PyString_FromString((char *) PVbuffer[i]));
+ }
+
+ PyMem_DEL(PVbuffer);
+
+ return list;
}
static PyObject *
cl_QuerySchemeFromName(PyObject *self, PyObject *args)
{
- int algorithmMediaType;
- char *name;
- int scheme;
+ int algorithmMediaType;
+ char *name;
+ int scheme;
- if (!PyArg_ParseTuple(args, "is", &algorithmMediaType, &name))
- return NULL;
+ if (!PyArg_ParseTuple(args, "is", &algorithmMediaType, &name))
+ return NULL;
- error_handler_called = 0;
- scheme = clQuerySchemeFromName(algorithmMediaType, name);
- if (error_handler_called) {
- PyErr_SetString(ClError, "unknown compression scheme");
- return NULL;
- }
+ error_handler_called = 0;
+ scheme = clQuerySchemeFromName(algorithmMediaType, name);
+ if (error_handler_called) {
+ PyErr_SetString(ClError, "unknown compression scheme");
+ return NULL;
+ }
- return PyInt_FromLong(scheme);
+ return PyInt_FromLong(scheme);
}
static PyObject *
cl_GetAlgorithmName(PyObject *self, PyObject *args)
{
- int scheme;
- char *name;
+ int scheme;
+ char *name;
- if (!PyArg_ParseTuple(args, "i", &scheme))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i", &scheme))
+ return NULL;
- name = clGetAlgorithmName(scheme);
- if (name == 0) {
- PyErr_SetString(ClError, "unknown compression scheme");
- return NULL;
- }
+ name = clGetAlgorithmName(scheme);
+ if (name == 0) {
+ PyErr_SetString(ClError, "unknown compression scheme");
+ return NULL;
+ }
- return PyString_FromString(name);
+ return PyString_FromString(name);
}
static PyObject *
do_set(PyObject *self, PyObject *args, int (*func)(int, int, int))
{
- int scheme, paramID, value;
- float fvalue;
- int is_float = 0;
-
- if (!PyArg_ParseTuple(args, "iii", &scheme, &paramID, &value)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "iif", &scheme, &paramID, &fvalue)) {
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "bad argument list (format '(iii)' or '(iif)')");
- return NULL;
- }
- value = CL_TypeIsInt(fvalue);
- is_float = 1;
- } else {
- /* check some parameters which we know to be floats */
- switch (scheme) {
- case CL_COMPRESSION_RATIO:
- case CL_SPEED:
- fvalue = value;
- value = CL_TypeIsInt(fvalue);
- is_float = 1;
- break;
- }
- }
-
- error_handler_called = 0;
- value = (*func)(scheme, paramID, value);
- if (error_handler_called)
- return NULL;
-
- if (is_float)
- return PyFloat_FromDouble(CL_TypeIsFloat(value));
- else
- return PyInt_FromLong(value);
+ int scheme, paramID, value;
+ float fvalue;
+ int is_float = 0;
+
+ if (!PyArg_ParseTuple(args, "iii", &scheme, &paramID, &value)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "iif", &scheme, &paramID, &fvalue)) {
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "bad argument list (format '(iii)' or '(iif)')");
+ return NULL;
+ }
+ value = CL_TypeIsInt(fvalue);
+ is_float = 1;
+ } else {
+ /* check some parameters which we know to be floats */
+ switch (scheme) {
+ case CL_COMPRESSION_RATIO:
+ case CL_SPEED:
+ fvalue = value;
+ value = CL_TypeIsInt(fvalue);
+ is_float = 1;
+ break;
+ }
+ }
+
+ error_handler_called = 0;
+ value = (*func)(scheme, paramID, value);
+ if (error_handler_called)
+ return NULL;
+
+ if (is_float)
+ return PyFloat_FromDouble(CL_TypeIsFloat(value));
+ else
+ return PyInt_FromLong(value);
}
static PyObject *
cl_SetDefault(PyObject *self, PyObject *args)
{
- return do_set(self, args, clSetDefault);
+ return do_set(self, args, clSetDefault);
}
static PyObject *
cl_SetMin(PyObject *self, PyObject *args)
{
- return do_set(self, args, clSetMin);
+ return do_set(self, args, clSetMin);
}
static PyObject *
cl_SetMax(PyObject *self, PyObject *args)
{
- return do_set(self, args, clSetMax);
+ return do_set(self, args, clSetMax);
}
-#define func(name, handler) \
+#define func(name, handler) \
static PyObject *cl_##name(PyObject *self, PyObject *args) \
{ \
- int x; \
- if (!PyArg_ParseTuple(args, "i", &x)) return NULL; \
- return Py##handler(CL_##name(x)); \
+ int x; \
+ if (!PyArg_ParseTuple(args, "i", &x)) return NULL; \
+ return Py##handler(CL_##name(x)); \
}
-#define func2(name, handler) \
+#define func2(name, handler) \
static PyObject *cl_##name(PyObject *self, PyObject *args) \
{ \
- int a1, a2; \
- if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL; \
- return Py##handler(CL_##name(a1, a2)); \
+ int a1, a2; \
+ if (!PyArg_ParseTuple(args, "ii", &a1, &a2)) return NULL; \
+ return Py##handler(CL_##name(a1, a2)); \
}
func(BytesPerSample, Int_FromLong)
@@ -907,50 +907,50 @@ func(ParamType, Int_FromLong)
func2(ParamID, Int_FromLong)
#ifdef CLDEBUG
- static PyObject *
+ static PyObject *
cvt_type(PyObject *self, PyObject *args)
{
- int number;
- float fnumber;
-
- if (PyArg_Parse(args, "i", &number))
- return PyFloat_FromDouble(CL_TypeIsFloat(number));
- else {
- PyErr_Clear();
- if (PyArg_Parse(args, "f", &fnumber))
- return PyInt_FromLong(CL_TypeIsInt(fnumber));
- return NULL;
- }
+ int number;
+ float fnumber;
+
+ if (PyArg_Parse(args, "i", &number))
+ return PyFloat_FromDouble(CL_TypeIsFloat(number));
+ else {
+ PyErr_Clear();
+ if (PyArg_Parse(args, "f", &fnumber))
+ return PyInt_FromLong(CL_TypeIsInt(fnumber));
+ return NULL;
+ }
}
#endif
static PyMethodDef cl_methods[] = {
- {"CompressImage", cl_CompressImage, METH_VARARGS},
- {"DecompressImage", cl_DecompressImage, METH_VARARGS},
- {"GetAlgorithmName", cl_GetAlgorithmName, METH_VARARGS},
- {"OpenCompressor", cl_OpenCompressor, METH_VARARGS},
- {"OpenDecompressor", cl_OpenDecompressor, METH_VARARGS},
- {"QueryAlgorithms", cl_QueryAlgorithms, METH_VARARGS},
- {"QueryMaxHeaderSize", cl_QueryMaxHeaderSize, METH_VARARGS},
- {"QueryScheme", cl_QueryScheme, METH_VARARGS},
- {"QuerySchemeFromName", cl_QuerySchemeFromName, METH_VARARGS},
- {"SetDefault", cl_SetDefault, METH_VARARGS},
- {"SetMax", cl_SetMax, METH_VARARGS},
- {"SetMin", cl_SetMin, METH_VARARGS},
- {"BytesPerSample", cl_BytesPerSample, METH_VARARGS},
- {"BytesPerPixel", cl_BytesPerPixel, METH_VARARGS},
- {"AudioFormatName", cl_AudioFormatName, METH_VARARGS},
- {"VideoFormatName", cl_VideoFormatName, METH_VARARGS},
- {"AlgorithmNumber", cl_AlgorithmNumber, METH_VARARGS},
- {"AlgorithmType", cl_AlgorithmType, METH_VARARGS},
- {"Algorithm", cl_Algorithm, METH_VARARGS},
- {"ParamNumber", cl_ParamNumber, METH_VARARGS},
- {"ParamType", cl_ParamType, METH_VARARGS},
- {"ParamID", cl_ParamID, METH_VARARGS},
+ {"CompressImage", cl_CompressImage, METH_VARARGS},
+ {"DecompressImage", cl_DecompressImage, METH_VARARGS},
+ {"GetAlgorithmName", cl_GetAlgorithmName, METH_VARARGS},
+ {"OpenCompressor", cl_OpenCompressor, METH_VARARGS},
+ {"OpenDecompressor", cl_OpenDecompressor, METH_VARARGS},
+ {"QueryAlgorithms", cl_QueryAlgorithms, METH_VARARGS},
+ {"QueryMaxHeaderSize", cl_QueryMaxHeaderSize, METH_VARARGS},
+ {"QueryScheme", cl_QueryScheme, METH_VARARGS},
+ {"QuerySchemeFromName", cl_QuerySchemeFromName, METH_VARARGS},
+ {"SetDefault", cl_SetDefault, METH_VARARGS},
+ {"SetMax", cl_SetMax, METH_VARARGS},
+ {"SetMin", cl_SetMin, METH_VARARGS},
+ {"BytesPerSample", cl_BytesPerSample, METH_VARARGS},
+ {"BytesPerPixel", cl_BytesPerPixel, METH_VARARGS},
+ {"AudioFormatName", cl_AudioFormatName, METH_VARARGS},
+ {"VideoFormatName", cl_VideoFormatName, METH_VARARGS},
+ {"AlgorithmNumber", cl_AlgorithmNumber, METH_VARARGS},
+ {"AlgorithmType", cl_AlgorithmType, METH_VARARGS},
+ {"Algorithm", cl_Algorithm, METH_VARARGS},
+ {"ParamNumber", cl_ParamNumber, METH_VARARGS},
+ {"ParamType", cl_ParamType, METH_VARARGS},
+ {"ParamID", cl_ParamID, METH_VARARGS},
#ifdef CLDEBUG
- {"cvt_type", cvt_type, METH_VARARGS},
+ {"cvt_type", cvt_type, METH_VARARGS},
#endif
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
#ifdef CL_JPEG_SOFTWARE
@@ -960,1604 +960,1604 @@ static PyMethodDef cl_methods[] = {
void
initcl(void)
{
- PyObject *m, *d, *x;
-
+ PyObject *m, *d, *x;
+
if (PyErr_WarnPy3k("the cl module has been removed in "
"Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("cl", cl_methods);
+ if (m == NULL)
return;
-
- m = Py_InitModule("cl", cl_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
+ d = PyModule_GetDict(m);
- ClError = PyErr_NewException("cl.error", NULL, NULL);
- (void) PyDict_SetItemString(d, "error", ClError);
+ ClError = PyErr_NewException("cl.error", NULL, NULL);
+ (void) PyDict_SetItemString(d, "error", ClError);
#ifdef CL_ADDED_ALGORITHM_ERROR
- x = PyInt_FromLong(CL_ADDED_ALGORITHM_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "ADDED_ALGORITHM_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ADDED_ALGORITHM_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "ADDED_ALGORITHM_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALAW
- x = PyInt_FromLong(CL_ALAW);
- if (x == NULL || PyDict_SetItemString(d, "ALAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALAW);
+ if (x == NULL || PyDict_SetItemString(d, "ALAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALGORITHM_ID
- x = PyInt_FromLong(CL_ALGORITHM_ID);
- if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_ID", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALGORITHM_ID);
+ if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_ID", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALGORITHM_TABLE_FULL
- x = PyInt_FromLong(CL_ALGORITHM_TABLE_FULL);
- if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_TABLE_FULL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALGORITHM_TABLE_FULL);
+ if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_TABLE_FULL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALGORITHM_VERSION
- x = PyInt_FromLong(CL_ALGORITHM_VERSION);
- if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_VERSION", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALGORITHM_VERSION);
+ if (x == NULL || PyDict_SetItemString(d, "ALGORITHM_VERSION", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALG_AUDIO
- x = PyInt_FromLong(CL_ALG_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "ALG_AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALG_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "ALG_AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ALG_VIDEO
- x = PyInt_FromLong(CL_ALG_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "ALG_VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ALG_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "ALG_VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AUDIO
- x = PyInt_FromLong(CL_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_BITRATE_POLICY
- x = PyInt_FromLong(CL_AWARE_BITRATE_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_BITRATE_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_BITRATE_TARGET
- x = PyInt_FromLong(CL_AWARE_BITRATE_TARGET);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_TARGET", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_BITRATE_TARGET);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_BITRATE_TARGET", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_CHANNEL_POLICY
- x = PyInt_FromLong(CL_AWARE_CHANNEL_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_CHANNEL_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_CHANNEL_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_CHANNEL_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_CONST_QUAL
- x = PyInt_FromLong(CL_AWARE_CONST_QUAL);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_CONST_QUAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_CONST_QUAL);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_CONST_QUAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_ERROR
- x = PyInt_FromLong(CL_AWARE_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_FIXED_RATE
- x = PyInt_FromLong(CL_AWARE_FIXED_RATE);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_FIXED_RATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_FIXED_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_FIXED_RATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_INDEPENDENT
- x = PyInt_FromLong(CL_AWARE_INDEPENDENT);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_INDEPENDENT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_INDEPENDENT);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_INDEPENDENT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_JOINT_STEREO
- x = PyInt_FromLong(CL_AWARE_JOINT_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_JOINT_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_JOINT_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_JOINT_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_LAYER
- x = PyInt_FromLong(CL_AWARE_LAYER);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_LAYER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_LAYER);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_LAYER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_LOSSLESS
- x = PyInt_FromLong(CL_AWARE_LOSSLESS);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_LOSSLESS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_LOSSLESS);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_LOSSLESS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MPEG_AUDIO
- x = PyInt_FromLong(CL_AWARE_MPEG_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MPEG_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MPEG_LAYER_I
- x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_I);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_I", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_I);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_I", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MPEG_LAYER_II
- x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_II);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_II", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MPEG_LAYER_II);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MPEG_LAYER_II", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_MULTIRATE
- x = PyInt_FromLong(CL_AWARE_MULTIRATE);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_MULTIRATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_MULTIRATE);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_MULTIRATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_NOISE_MARGIN
- x = PyInt_FromLong(CL_AWARE_NOISE_MARGIN);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_NOISE_MARGIN", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_NOISE_MARGIN);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_NOISE_MARGIN", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_AWARE_STEREO
- x = PyInt_FromLong(CL_AWARE_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWARE_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_AWARE_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWARE_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_ALGORITHM_NAME
- x = PyInt_FromLong(CL_BAD_ALGORITHM_NAME);
- if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_NAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_ALGORITHM_NAME);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_NAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_ALGORITHM_TYPE
- x = PyInt_FromLong(CL_BAD_ALGORITHM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_ALGORITHM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_ALGORITHM_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BLOCK_SIZE
- x = PyInt_FromLong(CL_BAD_BLOCK_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BLOCK_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BLOCK_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BLOCK_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BOARD
- x = PyInt_FromLong(CL_BAD_BOARD);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BOARD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BOARD);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BOARD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFERING
- x = PyInt_FromLong(CL_BAD_BUFFERING);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERING", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFERING);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERING", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFERLENGTH_NEG
- x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_NEG);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_NEG);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_NEG", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFERLENGTH_ODD
- x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_ODD);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFERLENGTH_ODD);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFERLENGTH_ODD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_EXISTS
- x = PyInt_FromLong(CL_BAD_BUFFER_EXISTS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_EXISTS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_EXISTS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_EXISTS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_HANDLE
- x = PyInt_FromLong(CL_BAD_BUFFER_HANDLE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_HANDLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_HANDLE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_HANDLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_POINTER
- x = PyInt_FromLong(CL_BAD_BUFFER_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_QUERY_SIZE
- x = PyInt_FromLong(CL_BAD_BUFFER_QUERY_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_QUERY_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_QUERY_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_QUERY_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_SIZE
- x = PyInt_FromLong(CL_BAD_BUFFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_SIZE_POINTER
- x = PyInt_FromLong(CL_BAD_BUFFER_SIZE_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_SIZE_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_SIZE_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_BUFFER_TYPE
- x = PyInt_FromLong(CL_BAD_BUFFER_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_BUFFER_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_BUFFER_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_COMPRESSION_SCHEME
- x = PyInt_FromLong(CL_BAD_COMPRESSION_SCHEME);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSION_SCHEME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_COMPRESSION_SCHEME);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSION_SCHEME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_COMPRESSOR_HANDLE
- x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_COMPRESSOR_HANDLE_POINTER
- x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_COMPRESSOR_HANDLE_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_COMPRESSOR_HANDLE_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_FRAME_SIZE
- x = PyInt_FromLong(CL_BAD_FRAME_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FRAME_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_FRAME_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FRAME_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_FUNCTIONALITY
- x = PyInt_FromLong(CL_BAD_FUNCTIONALITY);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTIONALITY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_FUNCTIONALITY);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTIONALITY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_FUNCTION_POINTER
- x = PyInt_FromLong(CL_BAD_FUNCTION_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTION_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_FUNCTION_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_FUNCTION_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_HEADER_SIZE
- x = PyInt_FromLong(CL_BAD_HEADER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_HEADER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_HEADER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_HEADER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_INITIAL_VALUE
- x = PyInt_FromLong(CL_BAD_INITIAL_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_INITIAL_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_INITIAL_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_INITIAL_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_INTERNAL_FORMAT
- x = PyInt_FromLong(CL_BAD_INTERNAL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "BAD_INTERNAL_FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_INTERNAL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_INTERNAL_FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_LICENSE
- x = PyInt_FromLong(CL_BAD_LICENSE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_LICENSE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_LICENSE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_LICENSE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_MIN_GT_MAX
- x = PyInt_FromLong(CL_BAD_MIN_GT_MAX);
- if (x == NULL || PyDict_SetItemString(d, "BAD_MIN_GT_MAX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_MIN_GT_MAX);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_MIN_GT_MAX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_NO_BUFFERSPACE
- x = PyInt_FromLong(CL_BAD_NO_BUFFERSPACE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NO_BUFFERSPACE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_NO_BUFFERSPACE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NO_BUFFERSPACE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_NUMBER_OF_BLOCKS
- x = PyInt_FromLong(CL_BAD_NUMBER_OF_BLOCKS);
- if (x == NULL || PyDict_SetItemString(d, "BAD_NUMBER_OF_BLOCKS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_NUMBER_OF_BLOCKS);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_NUMBER_OF_BLOCKS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PARAM
- x = PyInt_FromLong(CL_BAD_PARAM);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PARAM);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PARAM_ID_POINTER
- x = PyInt_FromLong(CL_BAD_PARAM_ID_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_ID_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PARAM_ID_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_ID_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PARAM_TYPE
- x = PyInt_FromLong(CL_BAD_PARAM_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PARAM_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PARAM_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_POINTER
- x = PyInt_FromLong(CL_BAD_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_PVBUFFER
- x = PyInt_FromLong(CL_BAD_PVBUFFER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_PVBUFFER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_PVBUFFER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_SCHEME_POINTER
- x = PyInt_FromLong(CL_BAD_SCHEME_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_SCHEME_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_SCHEME_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_SCHEME_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_STREAM_HEADER
- x = PyInt_FromLong(CL_BAD_STREAM_HEADER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_STREAM_HEADER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_STREAM_HEADER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_STREAM_HEADER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_STRING_POINTER
- x = PyInt_FromLong(CL_BAD_STRING_POINTER);
- if (x == NULL || PyDict_SetItemString(d, "BAD_STRING_POINTER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_STRING_POINTER);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_STRING_POINTER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BAD_TEXT_STRING_PTR
- x = PyInt_FromLong(CL_BAD_TEXT_STRING_PTR);
- if (x == NULL || PyDict_SetItemString(d, "BAD_TEXT_STRING_PTR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BAD_TEXT_STRING_PTR);
+ if (x == NULL || PyDict_SetItemString(d, "BAD_TEXT_STRING_PTR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BEST_FIT
- x = PyInt_FromLong(CL_BEST_FIT);
- if (x == NULL || PyDict_SetItemString(d, "BEST_FIT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BEST_FIT);
+ if (x == NULL || PyDict_SetItemString(d, "BEST_FIT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BIDIRECTIONAL
- x = PyInt_FromLong(CL_BIDIRECTIONAL);
- if (x == NULL || PyDict_SetItemString(d, "BIDIRECTIONAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BIDIRECTIONAL);
+ if (x == NULL || PyDict_SetItemString(d, "BIDIRECTIONAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITRATE
- x = PyInt_FromLong(CL_BITRATE);
- if (x == NULL || PyDict_SetItemString(d, "BITRATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITRATE);
+ if (x == NULL || PyDict_SetItemString(d, "BITRATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITRATE_POLICY
- x = PyInt_FromLong(CL_BITRATE_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "BITRATE_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITRATE_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "BITRATE_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITRATE_TARGET
- x = PyInt_FromLong(CL_BITRATE_TARGET);
- if (x == NULL || PyDict_SetItemString(d, "BITRATE_TARGET", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITRATE_TARGET);
+ if (x == NULL || PyDict_SetItemString(d, "BITRATE_TARGET", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BITS_PER_COMPONENT
- x = PyInt_FromLong(CL_BITS_PER_COMPONENT);
- if (x == NULL || PyDict_SetItemString(d, "BITS_PER_COMPONENT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BITS_PER_COMPONENT);
+ if (x == NULL || PyDict_SetItemString(d, "BITS_PER_COMPONENT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BLENDING
- x = PyInt_FromLong(CL_BLENDING);
- if (x == NULL || PyDict_SetItemString(d, "BLENDING", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BLENDING);
+ if (x == NULL || PyDict_SetItemString(d, "BLENDING", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BLOCK_SIZE
- x = PyInt_FromLong(CL_BLOCK_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "BLOCK_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BLOCK_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "BLOCK_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BOTTOM_UP
- x = PyInt_FromLong(CL_BOTTOM_UP);
- if (x == NULL || PyDict_SetItemString(d, "BOTTOM_UP", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BOTTOM_UP);
+ if (x == NULL || PyDict_SetItemString(d, "BOTTOM_UP", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUFFER_NOT_CREATED
- x = PyInt_FromLong(CL_BUFFER_NOT_CREATED);
- if (x == NULL || PyDict_SetItemString(d, "BUFFER_NOT_CREATED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUFFER_NOT_CREATED);
+ if (x == NULL || PyDict_SetItemString(d, "BUFFER_NOT_CREATED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUF_COMPRESSED
- x = PyInt_FromLong(CL_BUF_COMPRESSED);
- if (x == NULL || PyDict_SetItemString(d, "BUF_COMPRESSED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUF_COMPRESSED);
+ if (x == NULL || PyDict_SetItemString(d, "BUF_COMPRESSED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUF_DATA
- x = PyInt_FromLong(CL_BUF_DATA);
- if (x == NULL || PyDict_SetItemString(d, "BUF_DATA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUF_DATA);
+ if (x == NULL || PyDict_SetItemString(d, "BUF_DATA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_BUF_FRAME
- x = PyInt_FromLong(CL_BUF_FRAME);
- if (x == NULL || PyDict_SetItemString(d, "BUF_FRAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_BUF_FRAME);
+ if (x == NULL || PyDict_SetItemString(d, "BUF_FRAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CHANNEL_POLICY
- x = PyInt_FromLong(CL_CHANNEL_POLICY);
- if (x == NULL || PyDict_SetItemString(d, "CHANNEL_POLICY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CHANNEL_POLICY);
+ if (x == NULL || PyDict_SetItemString(d, "CHANNEL_POLICY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CHROMA_THRESHOLD
- x = PyInt_FromLong(CL_CHROMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "CHROMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CHROMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "CHROMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CODEC
- x = PyInt_FromLong(CL_CODEC);
- if (x == NULL || PyDict_SetItemString(d, "CODEC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CODEC);
+ if (x == NULL || PyDict_SetItemString(d, "CODEC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPONENTS
- x = PyInt_FromLong(CL_COMPONENTS);
- if (x == NULL || PyDict_SetItemString(d, "COMPONENTS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPONENTS);
+ if (x == NULL || PyDict_SetItemString(d, "COMPONENTS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPRESSED_BUFFER_SIZE
- x = PyInt_FromLong(CL_COMPRESSED_BUFFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "COMPRESSED_BUFFER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPRESSED_BUFFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "COMPRESSED_BUFFER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPRESSION_RATIO
- x = PyInt_FromLong(CL_COMPRESSION_RATIO);
- if (x == NULL || PyDict_SetItemString(d, "COMPRESSION_RATIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPRESSION_RATIO);
+ if (x == NULL || PyDict_SetItemString(d, "COMPRESSION_RATIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COMPRESSOR
- x = PyInt_FromLong(CL_COMPRESSOR);
- if (x == NULL || PyDict_SetItemString(d, "COMPRESSOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COMPRESSOR);
+ if (x == NULL || PyDict_SetItemString(d, "COMPRESSOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CONTINUOUS_BLOCK
- x = PyInt_FromLong(CL_CONTINUOUS_BLOCK);
- if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_BLOCK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CONTINUOUS_BLOCK);
+ if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_BLOCK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_CONTINUOUS_NONBLOCK
- x = PyInt_FromLong(CL_CONTINUOUS_NONBLOCK);
- if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_NONBLOCK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_CONTINUOUS_NONBLOCK);
+ if (x == NULL || PyDict_SetItemString(d, "CONTINUOUS_NONBLOCK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_CODEC_CONTROL
- x = PyInt_FromLong(CL_COSMO_CODEC_CONTROL);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_CODEC_CONTROL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_CODEC_CONTROL);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_CODEC_CONTROL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_NUM_PARAMS
- x = PyInt_FromLong(CL_COSMO_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_VALUE_BASE
- x = PyInt_FromLong(CL_COSMO_VALUE_BASE);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_VALUE_BASE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_VALUE_BASE);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_VALUE_BASE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_VIDEO_MANUAL_CONTROL
- x = PyInt_FromLong(CL_COSMO_VIDEO_MANUAL_CONTROL);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_MANUAL_CONTROL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_VIDEO_MANUAL_CONTROL);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_MANUAL_CONTROL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_COSMO_VIDEO_TRANSFER_MODE
- x = PyInt_FromLong(CL_COSMO_VIDEO_TRANSFER_MODE);
- if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_TRANSFER_MODE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_COSMO_VIDEO_TRANSFER_MODE);
+ if (x == NULL || PyDict_SetItemString(d, "COSMO_VIDEO_TRANSFER_MODE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_DATA
- x = PyInt_FromLong(CL_DATA);
- if (x == NULL || PyDict_SetItemString(d, "DATA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_DATA);
+ if (x == NULL || PyDict_SetItemString(d, "DATA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_DECOMPRESSOR
- x = PyInt_FromLong(CL_DECOMPRESSOR);
- if (x == NULL || PyDict_SetItemString(d, "DECOMPRESSOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_DECOMPRESSOR);
+ if (x == NULL || PyDict_SetItemString(d, "DECOMPRESSOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_DSO_ERROR
- x = PyInt_FromLong(CL_DSO_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "DSO_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_DSO_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "DSO_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_EDGE_THRESHOLD
- x = PyInt_FromLong(CL_EDGE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "EDGE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_EDGE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "EDGE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ENABLE_IMAGEINFO
- x = PyInt_FromLong(CL_ENABLE_IMAGEINFO);
- if (x == NULL || PyDict_SetItemString(d, "ENABLE_IMAGEINFO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ENABLE_IMAGEINFO);
+ if (x == NULL || PyDict_SetItemString(d, "ENABLE_IMAGEINFO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_END_OF_SEQUENCE
- x = PyInt_FromLong(CL_END_OF_SEQUENCE);
- if (x == NULL || PyDict_SetItemString(d, "END_OF_SEQUENCE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_END_OF_SEQUENCE);
+ if (x == NULL || PyDict_SetItemString(d, "END_OF_SEQUENCE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ENUM_VALUE
- x = PyInt_FromLong(CL_ENUM_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ENUM_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "ENUM_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_EXACT_COMPRESSION_RATIO
- x = PyInt_FromLong(CL_EXACT_COMPRESSION_RATIO);
- if (x == NULL || PyDict_SetItemString(d, "EXACT_COMPRESSION_RATIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_EXACT_COMPRESSION_RATIO);
+ if (x == NULL || PyDict_SetItemString(d, "EXACT_COMPRESSION_RATIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_EXTERNAL_DEVICE
- x = PyInt_FromLong((long) CL_EXTERNAL_DEVICE);
- if (x == NULL || PyDict_SetItemString(d, "EXTERNAL_DEVICE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong((long) CL_EXTERNAL_DEVICE);
+ if (x == NULL || PyDict_SetItemString(d, "EXTERNAL_DEVICE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FLOATING_ENUM_VALUE
- x = PyInt_FromLong(CL_FLOATING_ENUM_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "FLOATING_ENUM_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FLOATING_ENUM_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "FLOATING_ENUM_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FLOATING_RANGE_VALUE
- x = PyInt_FromLong(CL_FLOATING_RANGE_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "FLOATING_RANGE_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FLOATING_RANGE_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "FLOATING_RANGE_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT
- x = PyInt_FromLong(CL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_ABGR
- x = PyInt_FromLong(CL_FORMAT_ABGR);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_ABGR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_ABGR);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_ABGR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_BGR
- x = PyInt_FromLong(CL_FORMAT_BGR);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_BGR);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_BGR233
- x = PyInt_FromLong(CL_FORMAT_BGR233);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR233", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_BGR233);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_BGR233", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_GRAYSCALE
- x = PyInt_FromLong(CL_FORMAT_GRAYSCALE);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_GRAYSCALE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_GRAYSCALE);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_GRAYSCALE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_MONO
- x = PyInt_FromLong(CL_FORMAT_MONO);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_MONO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_MONO);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_MONO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_RBG323
- x = PyInt_FromLong(CL_FORMAT_RBG323);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_RBG323", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_RBG323);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_RBG323", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_STEREO_INTERLEAVED
- x = PyInt_FromLong(CL_FORMAT_STEREO_INTERLEAVED);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_STEREO_INTERLEAVED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_STEREO_INTERLEAVED);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_STEREO_INTERLEAVED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_XBGR
- x = PyInt_FromLong(CL_FORMAT_XBGR);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_XBGR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_XBGR);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_XBGR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_YCbCr
- x = PyInt_FromLong(CL_FORMAT_YCbCr);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_YCbCr);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_YCbCr422
- x = PyInt_FromLong(CL_FORMAT_YCbCr422);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_YCbCr422);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FORMAT_YCbCr422DC
- x = PyInt_FromLong(CL_FORMAT_YCbCr422DC);
- if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422DC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FORMAT_YCbCr422DC);
+ if (x == NULL || PyDict_SetItemString(d, "FORMAT_YCbCr422DC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME
- x = PyInt_FromLong(CL_FRAME);
- if (x == NULL || PyDict_SetItemString(d, "FRAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAMES_PER_CHUNK
- x = PyInt_FromLong(CL_FRAMES_PER_CHUNK);
- if (x == NULL || PyDict_SetItemString(d, "FRAMES_PER_CHUNK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAMES_PER_CHUNK);
+ if (x == NULL || PyDict_SetItemString(d, "FRAMES_PER_CHUNK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_BUFFER_SIZE
- x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_BUFFER_SIZE_ZERO
- x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE_ZERO);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE_ZERO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_BUFFER_SIZE_ZERO);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_BUFFER_SIZE_ZERO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_INDEX
- x = PyInt_FromLong(CL_FRAME_INDEX);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_INDEX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_INDEX);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_INDEX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_RATE
- x = PyInt_FromLong(CL_FRAME_RATE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_RATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_RATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_SIZE
- x = PyInt_FromLong(CL_FRAME_SIZE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_SIZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_SIZE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_SIZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_FRAME_TYPE
- x = PyInt_FromLong(CL_FRAME_TYPE);
- if (x == NULL || PyDict_SetItemString(d, "FRAME_TYPE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_FRAME_TYPE);
+ if (x == NULL || PyDict_SetItemString(d, "FRAME_TYPE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ALAW
- x = PyInt_FromLong(CL_G711_ALAW);
- if (x == NULL || PyDict_SetItemString(d, "G711_ALAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ALAW);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ALAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ALAW_SOFTWARE
- x = PyInt_FromLong(CL_G711_ALAW_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "G711_ALAW_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ALAW_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ALAW_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ULAW
- x = PyInt_FromLong(CL_G711_ULAW);
- if (x == NULL || PyDict_SetItemString(d, "G711_ULAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ULAW);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ULAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_G711_ULAW_SOFTWARE
- x = PyInt_FromLong(CL_G711_ULAW_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "G711_ULAW_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_G711_ULAW_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "G711_ULAW_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_GRAYSCALE
- x = PyInt_FromLong(CL_GRAYSCALE);
- if (x == NULL || PyDict_SetItemString(d, "GRAYSCALE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_GRAYSCALE);
+ if (x == NULL || PyDict_SetItemString(d, "GRAYSCALE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC
- x = PyInt_FromLong(CL_HDCC);
- if (x == NULL || PyDict_SetItemString(d, "HDCC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC_SAMPLES_PER_TILE
- x = PyInt_FromLong(CL_HDCC_SAMPLES_PER_TILE);
- if (x == NULL || PyDict_SetItemString(d, "HDCC_SAMPLES_PER_TILE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC_SAMPLES_PER_TILE);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC_SAMPLES_PER_TILE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC_SOFTWARE
- x = PyInt_FromLong(CL_HDCC_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "HDCC_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HDCC_TILE_THRESHOLD
- x = PyInt_FromLong(CL_HDCC_TILE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "HDCC_TILE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HDCC_TILE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "HDCC_TILE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_HEADER_START_CODE
- x = PyInt_FromLong(CL_HEADER_START_CODE);
- if (x == NULL || PyDict_SetItemString(d, "HEADER_START_CODE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_HEADER_START_CODE);
+ if (x == NULL || PyDict_SetItemString(d, "HEADER_START_CODE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGEINFO_FIELDMASK
- x = PyInt_FromLong(CL_IMAGEINFO_FIELDMASK);
- if (x == NULL || PyDict_SetItemString(d, "IMAGEINFO_FIELDMASK", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGEINFO_FIELDMASK);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGEINFO_FIELDMASK", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_BOTTOM
- x = PyInt_FromLong(CL_IMAGE_CROP_BOTTOM);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_BOTTOM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_BOTTOM);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_BOTTOM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_LEFT
- x = PyInt_FromLong(CL_IMAGE_CROP_LEFT);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_LEFT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_LEFT);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_LEFT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_RIGHT
- x = PyInt_FromLong(CL_IMAGE_CROP_RIGHT);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_RIGHT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_RIGHT);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_RIGHT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_CROP_TOP
- x = PyInt_FromLong(CL_IMAGE_CROP_TOP);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_TOP", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_CROP_TOP);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_CROP_TOP", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_HEIGHT
- x = PyInt_FromLong(CL_IMAGE_HEIGHT);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_HEIGHT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_HEIGHT);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_HEIGHT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMAGE_WIDTH
- x = PyInt_FromLong(CL_IMAGE_WIDTH);
- if (x == NULL || PyDict_SetItemString(d, "IMAGE_WIDTH", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMAGE_WIDTH);
+ if (x == NULL || PyDict_SetItemString(d, "IMAGE_WIDTH", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMPACT_CODEC_CONTROL
- x = PyInt_FromLong(CL_IMPACT_CODEC_CONTROL);
- if (x == NULL || PyDict_SetItemString(d, "IMPACT_CODEC_CONTROL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMPACT_CODEC_CONTROL);
+ if (x == NULL || PyDict_SetItemString(d, "IMPACT_CODEC_CONTROL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMPACT_FRAME_INTERLEAVE
- x = PyInt_FromLong(CL_IMPACT_FRAME_INTERLEAVE);
- if (x == NULL || PyDict_SetItemString(d, "IMPACT_FRAME_INTERLEAVE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMPACT_FRAME_INTERLEAVE);
+ if (x == NULL || PyDict_SetItemString(d, "IMPACT_FRAME_INTERLEAVE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_IMPACT_NUM_PARAMS
- x = PyInt_FromLong(CL_IMPACT_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "IMPACT_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_IMPACT_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "IMPACT_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTERNAL_FORMAT
- x = PyInt_FromLong(CL_INTERNAL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "INTERNAL_FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTERNAL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "INTERNAL_FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTERNAL_IMAGE_HEIGHT
- x = PyInt_FromLong(CL_INTERNAL_IMAGE_HEIGHT);
- if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_HEIGHT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTERNAL_IMAGE_HEIGHT);
+ if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_HEIGHT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTERNAL_IMAGE_WIDTH
- x = PyInt_FromLong(CL_INTERNAL_IMAGE_WIDTH);
- if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_WIDTH", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTERNAL_IMAGE_WIDTH);
+ if (x == NULL || PyDict_SetItemString(d, "INTERNAL_IMAGE_WIDTH", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_INTRA
- x = PyInt_FromLong(CL_INTRA);
- if (x == NULL || PyDict_SetItemString(d, "INTRA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_INTRA);
+ if (x == NULL || PyDict_SetItemString(d, "INTRA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG
- x = PyInt_FromLong(CL_JPEG);
- if (x == NULL || PyDict_SetItemString(d, "JPEG", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_COSMO
- x = PyInt_FromLong(CL_JPEG_COSMO);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_COSMO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_COSMO);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_COSMO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_ERROR
- x = PyInt_FromLong(CL_JPEG_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_IMPACT
- x = PyInt_FromLong(CL_JPEG_IMPACT);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_IMPACT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_IMPACT);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_IMPACT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_NUM_PARAMS
- x = PyInt_FromLong(CL_JPEG_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_QUALITY_FACTOR
- x = PyInt_FromLong(CL_JPEG_QUALITY_FACTOR);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_QUALITY_FACTOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_QUALITY_FACTOR);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_QUALITY_FACTOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_QUANTIZATION_TABLES
- x = PyInt_FromLong(CL_JPEG_QUANTIZATION_TABLES);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_QUANTIZATION_TABLES", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_QUANTIZATION_TABLES);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_QUANTIZATION_TABLES", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_SOFTWARE
- x = PyInt_FromLong(CL_JPEG_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_JPEG_STREAM_HEADERS
- x = PyInt_FromLong(CL_JPEG_STREAM_HEADERS);
- if (x == NULL || PyDict_SetItemString(d, "JPEG_STREAM_HEADERS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_JPEG_STREAM_HEADERS);
+ if (x == NULL || PyDict_SetItemString(d, "JPEG_STREAM_HEADERS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_KEYFRAME
- x = PyInt_FromLong(CL_KEYFRAME);
- if (x == NULL || PyDict_SetItemString(d, "KEYFRAME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_KEYFRAME);
+ if (x == NULL || PyDict_SetItemString(d, "KEYFRAME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_KEYFRAME_DISTANCE
- x = PyInt_FromLong(CL_KEYFRAME_DISTANCE);
- if (x == NULL || PyDict_SetItemString(d, "KEYFRAME_DISTANCE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_KEYFRAME_DISTANCE);
+ if (x == NULL || PyDict_SetItemString(d, "KEYFRAME_DISTANCE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_LAST_FRAME_INDEX
- x = PyInt_FromLong(CL_LAST_FRAME_INDEX);
- if (x == NULL || PyDict_SetItemString(d, "LAST_FRAME_INDEX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_LAST_FRAME_INDEX);
+ if (x == NULL || PyDict_SetItemString(d, "LAST_FRAME_INDEX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_LAYER
- x = PyInt_FromLong(CL_LAYER);
- if (x == NULL || PyDict_SetItemString(d, "LAYER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_LAYER);
+ if (x == NULL || PyDict_SetItemString(d, "LAYER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_LUMA_THRESHOLD
- x = PyInt_FromLong(CL_LUMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "LUMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_LUMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "LUMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_AUDIO_ALGORITHMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_AUDIO_ALGORITHMS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_AUDIO_ALGORITHMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_FORMATS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_ORIGINAL_FORMATS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_ORIGINAL_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_ORIGINAL_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_ORIGINAL_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_ORIGINAL_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_PARAMS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS
- x = PyInt_FromLong(CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS);
- if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_VIDEO_ALGORITHMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MAX_NUMBER_OF_VIDEO_ALGORITHMS);
+ if (x == NULL || PyDict_SetItemString(d, "MAX_NUMBER_OF_VIDEO_ALGORITHMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MONO
- x = PyInt_FromLong(CL_MONO);
- if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MONO);
+ if (x == NULL || PyDict_SetItemString(d, "MONO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_AWARE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_AWARE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_AWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_AWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_AWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_LAYER
- x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_LAYER_I
- x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_I);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_I", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_I);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_I", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_LAYER_II
- x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_II);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_II", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_LAYER_II);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_LAYER_II", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_DUAL
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_DUAL);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_DUAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_DUAL);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_DUAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_JOINT
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_JOINT);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_JOINT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_JOINT);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_JOINT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_SINGLE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_SINGLE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_SINGLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_SINGLE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_SINGLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_MODE_STEREO
- x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_MODE_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_MODE_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_AUDIO_SOFTWARE
- x = PyInt_FromLong(CL_MPEG1_AUDIO_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_AUDIO_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_AUDIO_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_END_OF_STREAM
- x = PyInt_FromLong(CL_MPEG1_END_OF_STREAM);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_END_OF_STREAM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_END_OF_STREAM);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_END_OF_STREAM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_ERROR
- x = PyInt_FromLong(CL_MPEG1_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_NUM_PARAMS
- x = PyInt_FromLong(CL_MPEG1_NUM_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_NUM_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_NUM_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_NUM_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_M
- x = PyInt_FromLong(CL_MPEG1_VIDEO_M);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_M", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_M);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_M", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_X", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_B_Y", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_X", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y
- x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_MAX_MOTION_VECTOR_LENGTH_P_Y", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_N
- x = PyInt_FromLong(CL_MPEG1_VIDEO_N);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_N", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_N);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_N", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MAXIMUM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MAXIMUM);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MAXIMUM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS_MEDIUM
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MEDIUM);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MEDIUM", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_MEDIUM);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_MEDIUM", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTNESS_NONE
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_NONE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_NONE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTNESS_NONE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTNESS_NONE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG1_VIDEO_SOFTWARE
- x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG1_VIDEO_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG1_VIDEO_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MPEG_VIDEO
- x = PyInt_FromLong(CL_MPEG_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "MPEG_VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MPEG_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "MPEG_VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MULTIRATE_AWARE
- x = PyInt_FromLong(CL_MULTIRATE_AWARE);
- if (x == NULL || PyDict_SetItemString(d, "MULTIRATE_AWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MULTIRATE_AWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MULTIRATE_AWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC1
- x = PyInt_FromLong(CL_MVC1);
- if (x == NULL || PyDict_SetItemString(d, "MVC1", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC1);
+ if (x == NULL || PyDict_SetItemString(d, "MVC1", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC1_SOFTWARE
- x = PyInt_FromLong(CL_MVC1_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MVC1_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC1_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MVC1_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2
- x = PyInt_FromLong(CL_MVC2);
- if (x == NULL || PyDict_SetItemString(d, "MVC2", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_BLENDING
- x = PyInt_FromLong(CL_MVC2_BLENDING);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_BLENDING);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_BLENDING_OFF
- x = PyInt_FromLong(CL_MVC2_BLENDING_OFF);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_OFF", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_BLENDING_OFF);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_OFF", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_BLENDING_ON
- x = PyInt_FromLong(CL_MVC2_BLENDING_ON);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_ON", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_BLENDING_ON);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_BLENDING_ON", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_CHROMA_THRESHOLD
- x = PyInt_FromLong(CL_MVC2_CHROMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_CHROMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_CHROMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_CHROMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_EDGE_THRESHOLD
- x = PyInt_FromLong(CL_MVC2_EDGE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_EDGE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_EDGE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_EDGE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_ERROR
- x = PyInt_FromLong(CL_MVC2_ERROR);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_ERROR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_ERROR);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_ERROR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_LUMA_THRESHOLD
- x = PyInt_FromLong(CL_MVC2_LUMA_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_LUMA_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_LUMA_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_LUMA_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC2_SOFTWARE
- x = PyInt_FromLong(CL_MVC2_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MVC2_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC2_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MVC2_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC3_QUALITY_LEVEL
- x = PyInt_FromLong(CL_MVC3_QUALITY_LEVEL);
- if (x == NULL || PyDict_SetItemString(d, "MVC3_QUALITY_LEVEL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC3_QUALITY_LEVEL);
+ if (x == NULL || PyDict_SetItemString(d, "MVC3_QUALITY_LEVEL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_MVC3_SOFTWARE
- x = PyInt_FromLong(CL_MVC3_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "MVC3_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_MVC3_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "MVC3_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NEXT_NOT_AVAILABLE
- x = PyInt_FromLong(CL_NEXT_NOT_AVAILABLE);
- if (x == NULL || PyDict_SetItemString(d, "NEXT_NOT_AVAILABLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NEXT_NOT_AVAILABLE);
+ if (x == NULL || PyDict_SetItemString(d, "NEXT_NOT_AVAILABLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NOISE_MARGIN
- x = PyInt_FromLong(CL_NOISE_MARGIN);
- if (x == NULL || PyDict_SetItemString(d, "NOISE_MARGIN", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NOISE_MARGIN);
+ if (x == NULL || PyDict_SetItemString(d, "NOISE_MARGIN", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NONE
- x = PyInt_FromLong(CL_NONE);
- if (x == NULL || PyDict_SetItemString(d, "NONE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NONE);
+ if (x == NULL || PyDict_SetItemString(d, "NONE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_FORMATS
- x = PyInt_FromLong(CL_NUMBER_OF_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_FRAMES
- x = PyInt_FromLong(CL_NUMBER_OF_FRAMES);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FRAMES", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_FRAMES);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_FRAMES", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_PARAMS
- x = PyInt_FromLong(CL_NUMBER_OF_PARAMS);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_PARAMS);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_PARAMS_FREEZE
- x = PyInt_FromLong(CL_NUMBER_OF_PARAMS_FREEZE);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS_FREEZE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_PARAMS_FREEZE);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_PARAMS_FREEZE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_NUMBER_OF_VIDEO_FORMATS
- x = PyInt_FromLong(CL_NUMBER_OF_VIDEO_FORMATS);
- if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_VIDEO_FORMATS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_NUMBER_OF_VIDEO_FORMATS);
+ if (x == NULL || PyDict_SetItemString(d, "NUMBER_OF_VIDEO_FORMATS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ORIENTATION
- x = PyInt_FromLong(CL_ORIENTATION);
- if (x == NULL || PyDict_SetItemString(d, "ORIENTATION", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ORIENTATION);
+ if (x == NULL || PyDict_SetItemString(d, "ORIENTATION", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ORIGINAL_FORMAT
- x = PyInt_FromLong(CL_ORIGINAL_FORMAT);
- if (x == NULL || PyDict_SetItemString(d, "ORIGINAL_FORMAT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ORIGINAL_FORMAT);
+ if (x == NULL || PyDict_SetItemString(d, "ORIGINAL_FORMAT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PARAM_OUT_OF_RANGE
- x = PyInt_FromLong(CL_PARAM_OUT_OF_RANGE);
- if (x == NULL || PyDict_SetItemString(d, "PARAM_OUT_OF_RANGE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PARAM_OUT_OF_RANGE);
+ if (x == NULL || PyDict_SetItemString(d, "PARAM_OUT_OF_RANGE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PIXEL_ASPECT
- x = PyInt_FromLong(CL_PIXEL_ASPECT);
- if (x == NULL || PyDict_SetItemString(d, "PIXEL_ASPECT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PIXEL_ASPECT);
+ if (x == NULL || PyDict_SetItemString(d, "PIXEL_ASPECT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PREDICTED
- x = PyInt_FromLong(CL_PREDICTED);
- if (x == NULL || PyDict_SetItemString(d, "PREDICTED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PREDICTED);
+ if (x == NULL || PyDict_SetItemString(d, "PREDICTED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_PREROLL
- x = PyInt_FromLong(CL_PREROLL);
- if (x == NULL || PyDict_SetItemString(d, "PREROLL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_PREROLL);
+ if (x == NULL || PyDict_SetItemString(d, "PREROLL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_FACTOR
- x = PyInt_FromLong(CL_QUALITY_FACTOR);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_FACTOR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_FACTOR);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_FACTOR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_LEVEL
- x = PyInt_FromLong(CL_QUALITY_LEVEL);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_LEVEL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_LEVEL);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_LEVEL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_SPATIAL
- x = PyInt_FromLong(CL_QUALITY_SPATIAL);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_SPATIAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_SPATIAL);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_SPATIAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUALITY_TEMPORAL
- x = PyInt_FromLong(CL_QUALITY_TEMPORAL);
- if (x == NULL || PyDict_SetItemString(d, "QUALITY_TEMPORAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUALITY_TEMPORAL);
+ if (x == NULL || PyDict_SetItemString(d, "QUALITY_TEMPORAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_QUANTIZATION_TABLES
- x = PyInt_FromLong(CL_QUANTIZATION_TABLES);
- if (x == NULL || PyDict_SetItemString(d, "QUANTIZATION_TABLES", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_QUANTIZATION_TABLES);
+ if (x == NULL || PyDict_SetItemString(d, "QUANTIZATION_TABLES", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RANGE_VALUE
- x = PyInt_FromLong(CL_RANGE_VALUE);
- if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RANGE_VALUE);
+ if (x == NULL || PyDict_SetItemString(d, "RANGE_VALUE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGB
- x = PyInt_FromLong(CL_RGB);
- if (x == NULL || PyDict_SetItemString(d, "RGB", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGB);
+ if (x == NULL || PyDict_SetItemString(d, "RGB", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGB332
- x = PyInt_FromLong(CL_RGB332);
- if (x == NULL || PyDict_SetItemString(d, "RGB332", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGB332);
+ if (x == NULL || PyDict_SetItemString(d, "RGB332", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGB8
- x = PyInt_FromLong(CL_RGB8);
- if (x == NULL || PyDict_SetItemString(d, "RGB8", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGB8);
+ if (x == NULL || PyDict_SetItemString(d, "RGB8", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGBA
- x = PyInt_FromLong(CL_RGBA);
- if (x == NULL || PyDict_SetItemString(d, "RGBA", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGBA);
+ if (x == NULL || PyDict_SetItemString(d, "RGBA", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RGBX
- x = PyInt_FromLong(CL_RGBX);
- if (x == NULL || PyDict_SetItemString(d, "RGBX", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RGBX);
+ if (x == NULL || PyDict_SetItemString(d, "RGBX", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE
- x = PyInt_FromLong(CL_RLE);
- if (x == NULL || PyDict_SetItemString(d, "RLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE);
+ if (x == NULL || PyDict_SetItemString(d, "RLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE24
- x = PyInt_FromLong(CL_RLE24);
- if (x == NULL || PyDict_SetItemString(d, "RLE24", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE24);
+ if (x == NULL || PyDict_SetItemString(d, "RLE24", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE24_SOFTWARE
- x = PyInt_FromLong(CL_RLE24_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "RLE24_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE24_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "RLE24_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RLE_SOFTWARE
- x = PyInt_FromLong(CL_RLE_SOFTWARE);
- if (x == NULL || PyDict_SetItemString(d, "RLE_SOFTWARE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RLE_SOFTWARE);
+ if (x == NULL || PyDict_SetItemString(d, "RLE_SOFTWARE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RTR
- x = PyInt_FromLong(CL_RTR);
- if (x == NULL || PyDict_SetItemString(d, "RTR", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RTR);
+ if (x == NULL || PyDict_SetItemString(d, "RTR", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RTR1
- x = PyInt_FromLong(CL_RTR1);
- if (x == NULL || PyDict_SetItemString(d, "RTR1", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RTR1);
+ if (x == NULL || PyDict_SetItemString(d, "RTR1", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_RTR_QUALITY_LEVEL
- x = PyInt_FromLong(CL_RTR_QUALITY_LEVEL);
- if (x == NULL || PyDict_SetItemString(d, "RTR_QUALITY_LEVEL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_RTR_QUALITY_LEVEL);
+ if (x == NULL || PyDict_SetItemString(d, "RTR_QUALITY_LEVEL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SAMPLES_PER_TILE
- x = PyInt_FromLong(CL_SAMPLES_PER_TILE);
- if (x == NULL || PyDict_SetItemString(d, "SAMPLES_PER_TILE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SAMPLES_PER_TILE);
+ if (x == NULL || PyDict_SetItemString(d, "SAMPLES_PER_TILE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SCHEME_BUSY
- x = PyInt_FromLong(CL_SCHEME_BUSY);
- if (x == NULL || PyDict_SetItemString(d, "SCHEME_BUSY", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SCHEME_BUSY);
+ if (x == NULL || PyDict_SetItemString(d, "SCHEME_BUSY", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SCHEME_NOT_AVAILABLE
- x = PyInt_FromLong(CL_SCHEME_NOT_AVAILABLE);
- if (x == NULL || PyDict_SetItemString(d, "SCHEME_NOT_AVAILABLE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SCHEME_NOT_AVAILABLE);
+ if (x == NULL || PyDict_SetItemString(d, "SCHEME_NOT_AVAILABLE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_SPEED
- x = PyInt_FromLong(CL_SPEED);
- if (x == NULL || PyDict_SetItemString(d, "SPEED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_SPEED);
+ if (x == NULL || PyDict_SetItemString(d, "SPEED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_STEREO_INTERLEAVED
- x = PyInt_FromLong(CL_STEREO_INTERLEAVED);
- if (x == NULL || PyDict_SetItemString(d, "STEREO_INTERLEAVED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_STEREO_INTERLEAVED);
+ if (x == NULL || PyDict_SetItemString(d, "STEREO_INTERLEAVED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_STREAM_HEADERS
- x = PyInt_FromLong(CL_STREAM_HEADERS);
- if (x == NULL || PyDict_SetItemString(d, "STREAM_HEADERS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_STREAM_HEADERS);
+ if (x == NULL || PyDict_SetItemString(d, "STREAM_HEADERS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_TILE_THRESHOLD
- x = PyInt_FromLong(CL_TILE_THRESHOLD);
- if (x == NULL || PyDict_SetItemString(d, "TILE_THRESHOLD", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_TILE_THRESHOLD);
+ if (x == NULL || PyDict_SetItemString(d, "TILE_THRESHOLD", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_TOP_DOWN
- x = PyInt_FromLong(CL_TOP_DOWN);
- if (x == NULL || PyDict_SetItemString(d, "TOP_DOWN", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_TOP_DOWN);
+ if (x == NULL || PyDict_SetItemString(d, "TOP_DOWN", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_ULAW
- x = PyInt_FromLong(CL_ULAW);
- if (x == NULL || PyDict_SetItemString(d, "ULAW", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_ULAW);
+ if (x == NULL || PyDict_SetItemString(d, "ULAW", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNCOMPRESSED
- x = PyInt_FromLong(CL_UNCOMPRESSED);
- if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNCOMPRESSED);
+ if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNCOMPRESSED_AUDIO
- x = PyInt_FromLong(CL_UNCOMPRESSED_AUDIO);
- if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_AUDIO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNCOMPRESSED_AUDIO);
+ if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_AUDIO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNCOMPRESSED_VIDEO
- x = PyInt_FromLong(CL_UNCOMPRESSED_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNCOMPRESSED_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "UNCOMPRESSED_VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_UNKNOWN_SCHEME
- x = PyInt_FromLong(CL_UNKNOWN_SCHEME);
- if (x == NULL || PyDict_SetItemString(d, "UNKNOWN_SCHEME", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_UNKNOWN_SCHEME);
+ if (x == NULL || PyDict_SetItemString(d, "UNKNOWN_SCHEME", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_VIDEO
- x = PyInt_FromLong(CL_VIDEO);
- if (x == NULL || PyDict_SetItemString(d, "VIDEO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_VIDEO);
+ if (x == NULL || PyDict_SetItemString(d, "VIDEO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_Y
- x = PyInt_FromLong(CL_Y);
- if (x == NULL || PyDict_SetItemString(d, "Y", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_Y);
+ if (x == NULL || PyDict_SetItemString(d, "Y", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr
- x = PyInt_FromLong(CL_YCbCr);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr422
- x = PyInt_FromLong(CL_YCbCr422);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr422", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr422);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr422", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr422DC
- x = PyInt_FromLong(CL_YCbCr422DC);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr422DC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr422DC);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr422DC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YCbCr422HC
- x = PyInt_FromLong(CL_YCbCr422HC);
- if (x == NULL || PyDict_SetItemString(d, "YCbCr422HC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YCbCr422HC);
+ if (x == NULL || PyDict_SetItemString(d, "YCbCr422HC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV
- x = PyInt_FromLong(CL_YUV);
- if (x == NULL || PyDict_SetItemString(d, "YUV", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV);
+ if (x == NULL || PyDict_SetItemString(d, "YUV", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV422
- x = PyInt_FromLong(CL_YUV422);
- if (x == NULL || PyDict_SetItemString(d, "YUV422", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV422);
+ if (x == NULL || PyDict_SetItemString(d, "YUV422", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV422DC
- x = PyInt_FromLong(CL_YUV422DC);
- if (x == NULL || PyDict_SetItemString(d, "YUV422DC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV422DC);
+ if (x == NULL || PyDict_SetItemString(d, "YUV422DC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef CL_YUV422HC
- x = PyInt_FromLong(CL_YUV422HC);
- if (x == NULL || PyDict_SetItemString(d, "YUV422HC", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(CL_YUV422HC);
+ if (x == NULL || PyDict_SetItemString(d, "YUV422HC", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_STEREO
- x = PyInt_FromLong(AWCMP_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_JOINT_STEREO
- x = PyInt_FromLong(AWCMP_JOINT_STEREO);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_JOINT_STEREO", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_JOINT_STEREO);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_JOINT_STEREO", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_INDEPENDENT
- x = PyInt_FromLong(AWCMP_INDEPENDENT);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_INDEPENDENT", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_INDEPENDENT);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_INDEPENDENT", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_FIXED_RATE
- x = PyInt_FromLong(AWCMP_FIXED_RATE);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_FIXED_RATE", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_FIXED_RATE);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_FIXED_RATE", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_CONST_QUAL
- x = PyInt_FromLong(AWCMP_CONST_QUAL);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_CONST_QUAL", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_CONST_QUAL);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_CONST_QUAL", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_LOSSLESS
- x = PyInt_FromLong(AWCMP_LOSSLESS);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_LOSSLESS", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_LOSSLESS);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_LOSSLESS", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_MPEG_LAYER_I
- x = PyInt_FromLong(AWCMP_MPEG_LAYER_I);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_I", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_MPEG_LAYER_I);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_I", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
#ifdef AWCMP_MPEG_LAYER_II
- x = PyInt_FromLong(AWCMP_MPEG_LAYER_II);
- if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_II", x) < 0)
- return;
- Py_DECREF(x);
+ x = PyInt_FromLong(AWCMP_MPEG_LAYER_II);
+ if (x == NULL || PyDict_SetItemString(d, "AWCMP_MPEG_LAYER_II", x) < 0)
+ return;
+ Py_DECREF(x);
#endif
- (void) clSetErrorHandler(cl_ErrorHandler);
+ (void) clSetErrorHandler(cl_ErrorHandler);
}
diff --git a/Modules/cmathmodule.c b/Modules/cmathmodule.c
index 788a19d..825f7ad 100644
--- a/Modules/cmathmodule.c
+++ b/Modules/cmathmodule.c
@@ -32,7 +32,7 @@
#define CM_LOG_LARGE_DOUBLE (log(CM_LARGE_DOUBLE))
#define CM_SQRT_DBL_MIN (sqrt(DBL_MIN))
-/*
+/*
CM_SCALE_UP is an odd integer chosen such that multiplication by
2**CM_SCALE_UP is sufficient to turn a subnormal into a normal.
CM_SCALE_DOWN is (-(CM_SCALE_UP+1)/2). These scalings are used to compute
@@ -63,46 +63,46 @@ static PyObject * math_error(void);
*/
enum special_types {
- ST_NINF, /* 0, negative infinity */
- ST_NEG, /* 1, negative finite number (nonzero) */
- ST_NZERO, /* 2, -0. */
- ST_PZERO, /* 3, +0. */
- ST_POS, /* 4, positive finite number (nonzero) */
- ST_PINF, /* 5, positive infinity */
- ST_NAN /* 6, Not a Number */
+ ST_NINF, /* 0, negative infinity */
+ ST_NEG, /* 1, negative finite number (nonzero) */
+ ST_NZERO, /* 2, -0. */
+ ST_PZERO, /* 3, +0. */
+ ST_POS, /* 4, positive finite number (nonzero) */
+ ST_PINF, /* 5, positive infinity */
+ ST_NAN /* 6, Not a Number */
};
static enum special_types
special_type(double d)
{
- if (Py_IS_FINITE(d)) {
- if (d != 0) {
- if (copysign(1., d) == 1.)
- return ST_POS;
- else
- return ST_NEG;
- }
- else {
- if (copysign(1., d) == 1.)
- return ST_PZERO;
- else
- return ST_NZERO;
- }
- }
- if (Py_IS_NAN(d))
- return ST_NAN;
- if (copysign(1., d) == 1.)
- return ST_PINF;
- else
- return ST_NINF;
+ if (Py_IS_FINITE(d)) {
+ if (d != 0) {
+ if (copysign(1., d) == 1.)
+ return ST_POS;
+ else
+ return ST_NEG;
+ }
+ else {
+ if (copysign(1., d) == 1.)
+ return ST_PZERO;
+ else
+ return ST_NZERO;
+ }
+ }
+ if (Py_IS_NAN(d))
+ return ST_NAN;
+ if (copysign(1., d) == 1.)
+ return ST_PINF;
+ else
+ return ST_NINF;
}
-#define SPECIAL_VALUE(z, table) \
- if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \
- errno = 0; \
- return table[special_type((z).real)] \
- [special_type((z).imag)]; \
- }
+#define SPECIAL_VALUE(z, table) \
+ if (!Py_IS_FINITE((z).real) || !Py_IS_FINITE((z).imag)) { \
+ errno = 0; \
+ return table[special_type((z).real)] \
+ [special_type((z).imag)]; \
+ }
#define P Py_MATH_PI
#define P14 0.25*Py_MATH_PI
@@ -126,34 +126,34 @@ static Py_complex acos_special_values[7][7];
static Py_complex
c_acos(Py_complex z)
{
- Py_complex s1, s2, r;
-
- SPECIAL_VALUE(z, acos_special_values);
-
- if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
- /* avoid unnecessary overflow for large arguments */
- r.real = atan2(fabs(z.imag), z.real);
- /* split into cases to make sure that the branch cut has the
- correct continuity on systems with unsigned zeros */
- if (z.real < 0.) {
- r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., z.imag);
- } else {
- r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., -z.imag);
- }
- } else {
- s1.real = 1.-z.real;
- s1.imag = -z.imag;
- s1 = c_sqrt(s1);
- s2.real = 1.+z.real;
- s2.imag = z.imag;
- s2 = c_sqrt(s2);
- r.real = 2.*atan2(s1.real, s2.real);
- r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real);
- }
- errno = 0;
- return r;
+ Py_complex s1, s2, r;
+
+ SPECIAL_VALUE(z, acos_special_values);
+
+ if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
+ /* avoid unnecessary overflow for large arguments */
+ r.real = atan2(fabs(z.imag), z.real);
+ /* split into cases to make sure that the branch cut has the
+ correct continuity on systems with unsigned zeros */
+ if (z.real < 0.) {
+ r.imag = -copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., z.imag);
+ } else {
+ r.imag = copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., -z.imag);
+ }
+ } else {
+ s1.real = 1.-z.real;
+ s1.imag = -z.imag;
+ s1 = c_sqrt(s1);
+ s2.real = 1.+z.real;
+ s2.imag = z.imag;
+ s2 = c_sqrt(s2);
+ r.real = 2.*atan2(s1.real, s2.real);
+ r.imag = m_asinh(s2.real*s1.imag - s2.imag*s1.real);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_acos_doc,
@@ -167,26 +167,26 @@ static Py_complex acosh_special_values[7][7];
static Py_complex
c_acosh(Py_complex z)
{
- Py_complex s1, s2, r;
-
- SPECIAL_VALUE(z, acosh_special_values);
-
- if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
- /* avoid unnecessary overflow for large arguments */
- r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.;
- r.imag = atan2(z.imag, z.real);
- } else {
- s1.real = z.real - 1.;
- s1.imag = z.imag;
- s1 = c_sqrt(s1);
- s2.real = z.real + 1.;
- s2.imag = z.imag;
- s2 = c_sqrt(s2);
- r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag);
- r.imag = 2.*atan2(s1.imag, s2.real);
- }
- errno = 0;
- return r;
+ Py_complex s1, s2, r;
+
+ SPECIAL_VALUE(z, acosh_special_values);
+
+ if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
+ /* avoid unnecessary overflow for large arguments */
+ r.real = log(hypot(z.real/2., z.imag/2.)) + M_LN2*2.;
+ r.imag = atan2(z.imag, z.real);
+ } else {
+ s1.real = z.real - 1.;
+ s1.imag = z.imag;
+ s1 = c_sqrt(s1);
+ s2.real = z.real + 1.;
+ s2.imag = z.imag;
+ s2 = c_sqrt(s2);
+ r.real = m_asinh(s1.real*s2.real + s1.imag*s2.imag);
+ r.imag = 2.*atan2(s1.imag, s2.real);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_acosh_doc,
@@ -198,14 +198,14 @@ PyDoc_STRVAR(c_acosh_doc,
static Py_complex
c_asin(Py_complex z)
{
- /* asin(z) = -i asinh(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_asinh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* asin(z) = -i asinh(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_asinh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
PyDoc_STRVAR(c_asin_doc,
@@ -219,31 +219,31 @@ static Py_complex asinh_special_values[7][7];
static Py_complex
c_asinh(Py_complex z)
{
- Py_complex s1, s2, r;
-
- SPECIAL_VALUE(z, asinh_special_values);
-
- if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
- if (z.imag >= 0.) {
- r.real = copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., z.real);
- } else {
- r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) +
- M_LN2*2., -z.real);
- }
- r.imag = atan2(z.imag, fabs(z.real));
- } else {
- s1.real = 1.+z.imag;
- s1.imag = -z.real;
- s1 = c_sqrt(s1);
- s2.real = 1.-z.imag;
- s2.imag = z.real;
- s2 = c_sqrt(s2);
- r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag);
- r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag);
- }
- errno = 0;
- return r;
+ Py_complex s1, s2, r;
+
+ SPECIAL_VALUE(z, asinh_special_values);
+
+ if (fabs(z.real) > CM_LARGE_DOUBLE || fabs(z.imag) > CM_LARGE_DOUBLE) {
+ if (z.imag >= 0.) {
+ r.real = copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., z.real);
+ } else {
+ r.real = -copysign(log(hypot(z.real/2., z.imag/2.)) +
+ M_LN2*2., -z.real);
+ }
+ r.imag = atan2(z.imag, fabs(z.real));
+ } else {
+ s1.real = 1.+z.imag;
+ s1.imag = -z.real;
+ s1 = c_sqrt(s1);
+ s2.real = 1.-z.imag;
+ s2.imag = z.real;
+ s2 = c_sqrt(s2);
+ r.real = m_asinh(s1.real*s2.imag-s2.real*s1.imag);
+ r.imag = atan2(z.imag, s1.real*s2.real-s1.imag*s2.imag);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_asinh_doc,
@@ -255,14 +255,14 @@ PyDoc_STRVAR(c_asinh_doc,
static Py_complex
c_atan(Py_complex z)
{
- /* atan(z) = -i atanh(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_atanh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* atan(z) = -i atanh(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_atanh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
/* Windows screws up atan2 for inf and nan, and alpha Tru64 5.1 doesn't follow
@@ -270,29 +270,29 @@ c_atan(Py_complex z)
static double
c_atan2(Py_complex z)
{
- if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag))
- return Py_NAN;
- if (Py_IS_INFINITY(z.imag)) {
- if (Py_IS_INFINITY(z.real)) {
- if (copysign(1., z.real) == 1.)
- /* atan2(+-inf, +inf) == +-pi/4 */
- return copysign(0.25*Py_MATH_PI, z.imag);
- else
- /* atan2(+-inf, -inf) == +-pi*3/4 */
- return copysign(0.75*Py_MATH_PI, z.imag);
- }
- /* atan2(+-inf, x) == +-pi/2 for finite x */
- return copysign(0.5*Py_MATH_PI, z.imag);
- }
- if (Py_IS_INFINITY(z.real) || z.imag == 0.) {
- if (copysign(1., z.real) == 1.)
- /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
- return copysign(0., z.imag);
- else
- /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
- return copysign(Py_MATH_PI, z.imag);
- }
- return atan2(z.imag, z.real);
+ if (Py_IS_NAN(z.real) || Py_IS_NAN(z.imag))
+ return Py_NAN;
+ if (Py_IS_INFINITY(z.imag)) {
+ if (Py_IS_INFINITY(z.real)) {
+ if (copysign(1., z.real) == 1.)
+ /* atan2(+-inf, +inf) == +-pi/4 */
+ return copysign(0.25*Py_MATH_PI, z.imag);
+ else
+ /* atan2(+-inf, -inf) == +-pi*3/4 */
+ return copysign(0.75*Py_MATH_PI, z.imag);
+ }
+ /* atan2(+-inf, x) == +-pi/2 for finite x */
+ return copysign(0.5*Py_MATH_PI, z.imag);
+ }
+ if (Py_IS_INFINITY(z.real) || z.imag == 0.) {
+ if (copysign(1., z.real) == 1.)
+ /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
+ return copysign(0., z.imag);
+ else
+ /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
+ return copysign(Py_MATH_PI, z.imag);
+ }
+ return atan2(z.imag, z.real);
}
PyDoc_STRVAR(c_atan_doc,
@@ -306,48 +306,48 @@ static Py_complex atanh_special_values[7][7];
static Py_complex
c_atanh(Py_complex z)
{
- Py_complex r;
- double ay, h;
-
- SPECIAL_VALUE(z, atanh_special_values);
-
- /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */
- if (z.real < 0.) {
- return c_neg(c_atanh(c_neg(z)));
- }
-
- ay = fabs(z.imag);
- if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) {
- /*
- if abs(z) is large then we use the approximation
- atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign
- of z.imag)
- */
- h = hypot(z.real/2., z.imag/2.); /* safe from overflow */
- r.real = z.real/4./h/h;
- /* the two negations in the next line cancel each other out
- except when working with unsigned zeros: they're there to
- ensure that the branch cut has the correct continuity on
- systems that don't support signed zeros */
- r.imag = -copysign(Py_MATH_PI/2., -z.imag);
- errno = 0;
- } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) {
- /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */
- if (ay == 0.) {
- r.real = INF;
- r.imag = z.imag;
- errno = EDOM;
- } else {
- r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.)));
- r.imag = copysign(atan2(2., -ay)/2, z.imag);
- errno = 0;
- }
- } else {
- r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.;
- r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.;
- errno = 0;
- }
- return r;
+ Py_complex r;
+ double ay, h;
+
+ SPECIAL_VALUE(z, atanh_special_values);
+
+ /* Reduce to case where z.real >= 0., using atanh(z) = -atanh(-z). */
+ if (z.real < 0.) {
+ return c_neg(c_atanh(c_neg(z)));
+ }
+
+ ay = fabs(z.imag);
+ if (z.real > CM_SQRT_LARGE_DOUBLE || ay > CM_SQRT_LARGE_DOUBLE) {
+ /*
+ if abs(z) is large then we use the approximation
+ atanh(z) ~ 1/z +/- i*pi/2 (+/- depending on the sign
+ of z.imag)
+ */
+ h = hypot(z.real/2., z.imag/2.); /* safe from overflow */
+ r.real = z.real/4./h/h;
+ /* the two negations in the next line cancel each other out
+ except when working with unsigned zeros: they're there to
+ ensure that the branch cut has the correct continuity on
+ systems that don't support signed zeros */
+ r.imag = -copysign(Py_MATH_PI/2., -z.imag);
+ errno = 0;
+ } else if (z.real == 1. && ay < CM_SQRT_DBL_MIN) {
+ /* C99 standard says: atanh(1+/-0.) should be inf +/- 0i */
+ if (ay == 0.) {
+ r.real = INF;
+ r.imag = z.imag;
+ errno = EDOM;
+ } else {
+ r.real = -log(sqrt(ay)/sqrt(hypot(ay, 2.)));
+ r.imag = copysign(atan2(2., -ay)/2, z.imag);
+ errno = 0;
+ }
+ } else {
+ r.real = m_log1p(4.*z.real/((1-z.real)*(1-z.real) + ay*ay))/4.;
+ r.imag = -atan2(-2.*z.imag, (1-z.real)*(1+z.real) - ay*ay)/2.;
+ errno = 0;
+ }
+ return r;
}
PyDoc_STRVAR(c_atanh_doc,
@@ -359,12 +359,12 @@ PyDoc_STRVAR(c_atanh_doc,
static Py_complex
c_cos(Py_complex z)
{
- /* cos(z) = cosh(iz) */
- Py_complex r;
- r.real = -z.imag;
- r.imag = z.real;
- r = c_cosh(r);
- return r;
+ /* cos(z) = cosh(iz) */
+ Py_complex r;
+ r.real = -z.imag;
+ r.imag = z.real;
+ r = c_cosh(r);
+ return r;
}
PyDoc_STRVAR(c_cos_doc,
@@ -379,51 +379,51 @@ static Py_complex cosh_special_values[7][7];
static Py_complex
c_cosh(Py_complex z)
{
- Py_complex r;
- double x_minus_one;
-
- /* special treatment for cosh(+/-inf + iy) if y is not a NaN */
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) &&
- (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- else {
- r.real = copysign(INF, cos(z.imag));
- r.imag = -copysign(INF, sin(z.imag));
- }
- }
- else {
- r = cosh_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if y is +/- infinity and x is not
- a NaN */
- if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
- /* deal correctly with cases where cosh(z.real) overflows but
- cosh(z) does not. */
- x_minus_one = z.real - copysign(1., z.real);
- r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E;
- r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E;
- } else {
- r.real = cos(z.imag) * cosh(z.real);
- r.imag = sin(z.imag) * sinh(z.real);
- }
- /* detect overflow, and set errno accordingly */
- if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
- errno = ERANGE;
- else
- errno = 0;
- return r;
+ Py_complex r;
+ double x_minus_one;
+
+ /* special treatment for cosh(+/-inf + iy) if y is not a NaN */
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag) &&
+ (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ else {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = -copysign(INF, sin(z.imag));
+ }
+ }
+ else {
+ r = cosh_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if y is +/- infinity and x is not
+ a NaN */
+ if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
+ /* deal correctly with cases where cosh(z.real) overflows but
+ cosh(z) does not. */
+ x_minus_one = z.real - copysign(1., z.real);
+ r.real = cos(z.imag) * cosh(x_minus_one) * Py_MATH_E;
+ r.imag = sin(z.imag) * sinh(x_minus_one) * Py_MATH_E;
+ } else {
+ r.real = cos(z.imag) * cosh(z.real);
+ r.imag = sin(z.imag) * sinh(z.real);
+ }
+ /* detect overflow, and set errno accordingly */
+ if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_cosh_doc,
@@ -439,51 +439,51 @@ static Py_complex exp_special_values[7][7];
static Py_complex
c_exp(Py_complex z)
{
- Py_complex r;
- double l;
-
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
- && (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- else {
- r.real = copysign(0., cos(z.imag));
- r.imag = copysign(0., sin(z.imag));
- }
- }
- else {
- r = exp_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if y is +/- infinity and x is not
- a NaN and not -infinity */
- if (Py_IS_INFINITY(z.imag) &&
- (Py_IS_FINITE(z.real) ||
- (Py_IS_INFINITY(z.real) && z.real > 0)))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- if (z.real > CM_LOG_LARGE_DOUBLE) {
- l = exp(z.real-1.);
- r.real = l*cos(z.imag)*Py_MATH_E;
- r.imag = l*sin(z.imag)*Py_MATH_E;
- } else {
- l = exp(z.real);
- r.real = l*cos(z.imag);
- r.imag = l*sin(z.imag);
- }
- /* detect overflow, and set errno accordingly */
- if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
- errno = ERANGE;
- else
- errno = 0;
- return r;
+ Py_complex r;
+ double l;
+
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
+ && (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ else {
+ r.real = copysign(0., cos(z.imag));
+ r.imag = copysign(0., sin(z.imag));
+ }
+ }
+ else {
+ r = exp_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if y is +/- infinity and x is not
+ a NaN and not -infinity */
+ if (Py_IS_INFINITY(z.imag) &&
+ (Py_IS_FINITE(z.real) ||
+ (Py_IS_INFINITY(z.real) && z.real > 0)))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ if (z.real > CM_LOG_LARGE_DOUBLE) {
+ l = exp(z.real-1.);
+ r.real = l*cos(z.imag)*Py_MATH_E;
+ r.imag = l*sin(z.imag)*Py_MATH_E;
+ } else {
+ l = exp(z.real);
+ r.real = l*cos(z.imag);
+ r.imag = l*sin(z.imag);
+ }
+ /* detect overflow, and set errno accordingly */
+ if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_exp_doc,
@@ -497,85 +497,85 @@ static Py_complex log_special_values[7][7];
static Py_complex
c_log(Py_complex z)
{
- /*
- The usual formula for the real part is log(hypot(z.real, z.imag)).
- There are four situations where this formula is potentially
- problematic:
-
- (1) the absolute value of z is subnormal. Then hypot is subnormal,
- so has fewer than the usual number of bits of accuracy, hence may
- have large relative error. This then gives a large absolute error
- in the log. This can be solved by rescaling z by a suitable power
- of 2.
-
- (2) the absolute value of z is greater than DBL_MAX (e.g. when both
- z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
- Again, rescaling solves this.
-
- (3) the absolute value of z is close to 1. In this case it's
- difficult to achieve good accuracy, at least in part because a
- change of 1ulp in the real or imaginary part of z can result in a
- change of billions of ulps in the correctly rounded answer.
-
- (4) z = 0. The simplest thing to do here is to call the
- floating-point log with an argument of 0, and let its behaviour
- (returning -infinity, signaling a floating-point exception, setting
- errno, or whatever) determine that of c_log. So the usual formula
- is fine here.
-
- */
-
- Py_complex r;
- double ax, ay, am, an, h;
-
- SPECIAL_VALUE(z, log_special_values);
-
- ax = fabs(z.real);
- ay = fabs(z.imag);
-
- if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) {
- r.real = log(hypot(ax/2., ay/2.)) + M_LN2;
- } else if (ax < DBL_MIN && ay < DBL_MIN) {
- if (ax > 0. || ay > 0.) {
- /* catch cases where hypot(ax, ay) is subnormal */
- r.real = log(hypot(ldexp(ax, DBL_MANT_DIG),
- ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2;
- }
- else {
- /* log(+/-0. +/- 0i) */
- r.real = -INF;
- r.imag = atan2(z.imag, z.real);
- errno = EDOM;
- return r;
- }
- } else {
- h = hypot(ax, ay);
- if (0.71 <= h && h <= 1.73) {
- am = ax > ay ? ax : ay; /* max(ax, ay) */
- an = ax > ay ? ay : ax; /* min(ax, ay) */
- r.real = m_log1p((am-1)*(am+1)+an*an)/2.;
- } else {
- r.real = log(h);
- }
- }
- r.imag = atan2(z.imag, z.real);
- errno = 0;
- return r;
+ /*
+ The usual formula for the real part is log(hypot(z.real, z.imag)).
+ There are four situations where this formula is potentially
+ problematic:
+
+ (1) the absolute value of z is subnormal. Then hypot is subnormal,
+ so has fewer than the usual number of bits of accuracy, hence may
+ have large relative error. This then gives a large absolute error
+ in the log. This can be solved by rescaling z by a suitable power
+ of 2.
+
+ (2) the absolute value of z is greater than DBL_MAX (e.g. when both
+ z.real and z.imag are within a factor of 1/sqrt(2) of DBL_MAX)
+ Again, rescaling solves this.
+
+ (3) the absolute value of z is close to 1. In this case it's
+ difficult to achieve good accuracy, at least in part because a
+ change of 1ulp in the real or imaginary part of z can result in a
+ change of billions of ulps in the correctly rounded answer.
+
+ (4) z = 0. The simplest thing to do here is to call the
+ floating-point log with an argument of 0, and let its behaviour
+ (returning -infinity, signaling a floating-point exception, setting
+ errno, or whatever) determine that of c_log. So the usual formula
+ is fine here.
+
+ */
+
+ Py_complex r;
+ double ax, ay, am, an, h;
+
+ SPECIAL_VALUE(z, log_special_values);
+
+ ax = fabs(z.real);
+ ay = fabs(z.imag);
+
+ if (ax > CM_LARGE_DOUBLE || ay > CM_LARGE_DOUBLE) {
+ r.real = log(hypot(ax/2., ay/2.)) + M_LN2;
+ } else if (ax < DBL_MIN && ay < DBL_MIN) {
+ if (ax > 0. || ay > 0.) {
+ /* catch cases where hypot(ax, ay) is subnormal */
+ r.real = log(hypot(ldexp(ax, DBL_MANT_DIG),
+ ldexp(ay, DBL_MANT_DIG))) - DBL_MANT_DIG*M_LN2;
+ }
+ else {
+ /* log(+/-0. +/- 0i) */
+ r.real = -INF;
+ r.imag = atan2(z.imag, z.real);
+ errno = EDOM;
+ return r;
+ }
+ } else {
+ h = hypot(ax, ay);
+ if (0.71 <= h && h <= 1.73) {
+ am = ax > ay ? ax : ay; /* max(ax, ay) */
+ an = ax > ay ? ay : ax; /* min(ax, ay) */
+ r.real = m_log1p((am-1)*(am+1)+an*an)/2.;
+ } else {
+ r.real = log(h);
+ }
+ }
+ r.imag = atan2(z.imag, z.real);
+ errno = 0;
+ return r;
}
static Py_complex
c_log10(Py_complex z)
{
- Py_complex r;
- int errno_save;
-
- r = c_log(z);
- errno_save = errno; /* just in case the divisions affect errno */
- r.real = r.real / M_LN10;
- r.imag = r.imag / M_LN10;
- errno = errno_save;
- return r;
+ Py_complex r;
+ int errno_save;
+
+ r = c_log(z);
+ errno_save = errno; /* just in case the divisions affect errno */
+ r.real = r.real / M_LN10;
+ r.imag = r.imag / M_LN10;
+ errno = errno_save;
+ return r;
}
PyDoc_STRVAR(c_log10_doc,
@@ -587,14 +587,14 @@ PyDoc_STRVAR(c_log10_doc,
static Py_complex
c_sin(Py_complex z)
{
- /* sin(z) = -i sin(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_sinh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* sin(z) = -i sin(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_sinh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
PyDoc_STRVAR(c_sin_doc,
@@ -609,50 +609,50 @@ static Py_complex sinh_special_values[7][7];
static Py_complex
c_sinh(Py_complex z)
{
- Py_complex r;
- double x_minus_one;
-
- /* special treatment for sinh(+/-inf + iy) if y is finite and
- nonzero */
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
- && (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- else {
- r.real = -copysign(INF, cos(z.imag));
- r.imag = copysign(INF, sin(z.imag));
- }
- }
- else {
- r = sinh_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if y is +/- infinity and x is not
- a NaN */
- if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
- x_minus_one = z.real - copysign(1., z.real);
- r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E;
- r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E;
- } else {
- r.real = cos(z.imag) * sinh(z.real);
- r.imag = sin(z.imag) * cosh(z.real);
- }
- /* detect overflow, and set errno accordingly */
- if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
- errno = ERANGE;
- else
- errno = 0;
- return r;
+ Py_complex r;
+ double x_minus_one;
+
+ /* special treatment for sinh(+/-inf + iy) if y is finite and
+ nonzero */
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
+ && (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ else {
+ r.real = -copysign(INF, cos(z.imag));
+ r.imag = copysign(INF, sin(z.imag));
+ }
+ }
+ else {
+ r = sinh_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if y is +/- infinity and x is not
+ a NaN */
+ if (Py_IS_INFINITY(z.imag) && !Py_IS_NAN(z.real))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
+ x_minus_one = z.real - copysign(1., z.real);
+ r.real = cos(z.imag) * sinh(x_minus_one) * Py_MATH_E;
+ r.imag = sin(z.imag) * cosh(x_minus_one) * Py_MATH_E;
+ } else {
+ r.real = cos(z.imag) * sinh(z.real);
+ r.imag = sin(z.imag) * cosh(z.real);
+ }
+ /* detect overflow, and set errno accordingly */
+ if (Py_IS_INFINITY(r.real) || Py_IS_INFINITY(r.imag))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_sinh_doc,
@@ -666,68 +666,68 @@ static Py_complex sqrt_special_values[7][7];
static Py_complex
c_sqrt(Py_complex z)
{
- /*
- Method: use symmetries to reduce to the case when x = z.real and y
- = z.imag are nonnegative. Then the real part of the result is
- given by
-
- s = sqrt((x + hypot(x, y))/2)
-
- and the imaginary part is
-
- d = (y/2)/s
-
- If either x or y is very large then there's a risk of overflow in
- computation of the expression x + hypot(x, y). We can avoid this
- by rewriting the formula for s as:
-
- s = 2*sqrt(x/8 + hypot(x/8, y/8))
-
- This costs us two extra multiplications/divisions, but avoids the
- overhead of checking for x and y large.
-
- If both x and y are subnormal then hypot(x, y) may also be
- subnormal, so will lack full precision. We solve this by rescaling
- x and y by a sufficiently large power of 2 to ensure that x and y
- are normal.
- */
-
-
- Py_complex r;
- double s,d;
- double ax, ay;
-
- SPECIAL_VALUE(z, sqrt_special_values);
-
- if (z.real == 0. && z.imag == 0.) {
- r.real = 0.;
- r.imag = z.imag;
- return r;
- }
-
- ax = fabs(z.real);
- ay = fabs(z.imag);
-
- if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) {
- /* here we catch cases where hypot(ax, ay) is subnormal */
- ax = ldexp(ax, CM_SCALE_UP);
- s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))),
- CM_SCALE_DOWN);
- } else {
- ax /= 8.;
- s = 2.*sqrt(ax + hypot(ax, ay/8.));
- }
- d = ay/(2.*s);
-
- if (z.real >= 0.) {
- r.real = s;
- r.imag = copysign(d, z.imag);
- } else {
- r.real = d;
- r.imag = copysign(s, z.imag);
- }
- errno = 0;
- return r;
+ /*
+ Method: use symmetries to reduce to the case when x = z.real and y
+ = z.imag are nonnegative. Then the real part of the result is
+ given by
+
+ s = sqrt((x + hypot(x, y))/2)
+
+ and the imaginary part is
+
+ d = (y/2)/s
+
+ If either x or y is very large then there's a risk of overflow in
+ computation of the expression x + hypot(x, y). We can avoid this
+ by rewriting the formula for s as:
+
+ s = 2*sqrt(x/8 + hypot(x/8, y/8))
+
+ This costs us two extra multiplications/divisions, but avoids the
+ overhead of checking for x and y large.
+
+ If both x and y are subnormal then hypot(x, y) may also be
+ subnormal, so will lack full precision. We solve this by rescaling
+ x and y by a sufficiently large power of 2 to ensure that x and y
+ are normal.
+ */
+
+
+ Py_complex r;
+ double s,d;
+ double ax, ay;
+
+ SPECIAL_VALUE(z, sqrt_special_values);
+
+ if (z.real == 0. && z.imag == 0.) {
+ r.real = 0.;
+ r.imag = z.imag;
+ return r;
+ }
+
+ ax = fabs(z.real);
+ ay = fabs(z.imag);
+
+ if (ax < DBL_MIN && ay < DBL_MIN && (ax > 0. || ay > 0.)) {
+ /* here we catch cases where hypot(ax, ay) is subnormal */
+ ax = ldexp(ax, CM_SCALE_UP);
+ s = ldexp(sqrt(ax + hypot(ax, ldexp(ay, CM_SCALE_UP))),
+ CM_SCALE_DOWN);
+ } else {
+ ax /= 8.;
+ s = 2.*sqrt(ax + hypot(ax, ay/8.));
+ }
+ d = ay/(2.*s);
+
+ if (z.real >= 0.) {
+ r.real = s;
+ r.imag = copysign(d, z.imag);
+ } else {
+ r.real = d;
+ r.imag = copysign(s, z.imag);
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_sqrt_doc,
@@ -739,14 +739,14 @@ PyDoc_STRVAR(c_sqrt_doc,
static Py_complex
c_tan(Py_complex z)
{
- /* tan(z) = -i tanh(iz) */
- Py_complex s, r;
- s.real = -z.imag;
- s.imag = z.real;
- s = c_tanh(s);
- r.real = s.imag;
- r.imag = -s.real;
- return r;
+ /* tan(z) = -i tanh(iz) */
+ Py_complex s, r;
+ s.real = -z.imag;
+ s.imag = z.real;
+ s = c_tanh(s);
+ r.real = s.imag;
+ r.imag = -s.real;
+ return r;
}
PyDoc_STRVAR(c_tan_doc,
@@ -761,65 +761,65 @@ static Py_complex tanh_special_values[7][7];
static Py_complex
c_tanh(Py_complex z)
{
- /* Formula:
-
- tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) /
- (1+tan(y)^2 tanh(x)^2)
-
- To avoid excessive roundoff error, 1-tanh(x)^2 is better computed
- as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2
- by 4 exp(-2*x) instead, to avoid possible overflow in the
- computation of cosh(x).
-
- */
-
- Py_complex r;
- double tx, ty, cx, txty, denom;
-
- /* special treatment for tanh(+/-inf + iy) if y is finite and
- nonzero */
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
- && (z.imag != 0.)) {
- if (z.real > 0) {
- r.real = 1.0;
- r.imag = copysign(0.,
- 2.*sin(z.imag)*cos(z.imag));
- }
- else {
- r.real = -1.0;
- r.imag = copysign(0.,
- 2.*sin(z.imag)*cos(z.imag));
- }
- }
- else {
- r = tanh_special_values[special_type(z.real)]
- [special_type(z.imag)];
- }
- /* need to set errno = EDOM if z.imag is +/-infinity and
- z.real is finite */
- if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real))
- errno = EDOM;
- else
- errno = 0;
- return r;
- }
-
- /* danger of overflow in 2.*z.imag !*/
- if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
- r.real = copysign(1., z.real);
- r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real));
- } else {
- tx = tanh(z.real);
- ty = tan(z.imag);
- cx = 1./cosh(z.real);
- txty = tx*ty;
- denom = 1. + txty*txty;
- r.real = tx*(1.+ty*ty)/denom;
- r.imag = ((ty/denom)*cx)*cx;
- }
- errno = 0;
- return r;
+ /* Formula:
+
+ tanh(x+iy) = (tanh(x)(1+tan(y)^2) + i tan(y)(1-tanh(x))^2) /
+ (1+tan(y)^2 tanh(x)^2)
+
+ To avoid excessive roundoff error, 1-tanh(x)^2 is better computed
+ as 1/cosh(x)^2. When abs(x) is large, we approximate 1-tanh(x)^2
+ by 4 exp(-2*x) instead, to avoid possible overflow in the
+ computation of cosh(x).
+
+ */
+
+ Py_complex r;
+ double tx, ty, cx, txty, denom;
+
+ /* special treatment for tanh(+/-inf + iy) if y is finite and
+ nonzero */
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ if (Py_IS_INFINITY(z.real) && Py_IS_FINITE(z.imag)
+ && (z.imag != 0.)) {
+ if (z.real > 0) {
+ r.real = 1.0;
+ r.imag = copysign(0.,
+ 2.*sin(z.imag)*cos(z.imag));
+ }
+ else {
+ r.real = -1.0;
+ r.imag = copysign(0.,
+ 2.*sin(z.imag)*cos(z.imag));
+ }
+ }
+ else {
+ r = tanh_special_values[special_type(z.real)]
+ [special_type(z.imag)];
+ }
+ /* need to set errno = EDOM if z.imag is +/-infinity and
+ z.real is finite */
+ if (Py_IS_INFINITY(z.imag) && Py_IS_FINITE(z.real))
+ errno = EDOM;
+ else
+ errno = 0;
+ return r;
+ }
+
+ /* danger of overflow in 2.*z.imag !*/
+ if (fabs(z.real) > CM_LOG_LARGE_DOUBLE) {
+ r.real = copysign(1., z.real);
+ r.imag = 4.*sin(z.imag)*cos(z.imag)*exp(-2.*fabs(z.real));
+ } else {
+ tx = tanh(z.real);
+ ty = tan(z.imag);
+ cx = 1./cosh(z.real);
+ txty = tx*ty;
+ denom = 1. + txty*txty;
+ r.real = tx*(1.+ty*ty)/denom;
+ r.imag = ((ty/denom)*cx)*cx;
+ }
+ errno = 0;
+ return r;
}
PyDoc_STRVAR(c_tanh_doc,
@@ -831,23 +831,23 @@ PyDoc_STRVAR(c_tanh_doc,
static PyObject *
cmath_log(PyObject *self, PyObject *args)
{
- Py_complex x;
- Py_complex y;
-
- if (!PyArg_ParseTuple(args, "D|D", &x, &y))
- return NULL;
-
- errno = 0;
- PyFPE_START_PROTECT("complex function", return 0)
- x = c_log(x);
- if (PyTuple_GET_SIZE(args) == 2) {
- y = c_log(y);
- x = c_quot(x, y);
- }
- PyFPE_END_PROTECT(x)
- if (errno != 0)
- return math_error();
- return PyComplex_FromCComplex(x);
+ Py_complex x;
+ Py_complex y;
+
+ if (!PyArg_ParseTuple(args, "D|D", &x, &y))
+ return NULL;
+
+ errno = 0;
+ PyFPE_START_PROTECT("complex function", return 0)
+ x = c_log(x);
+ if (PyTuple_GET_SIZE(args) == 2) {
+ y = c_log(y);
+ x = c_quot(x, y);
+ }
+ PyFPE_END_PROTECT(x)
+ if (errno != 0)
+ return math_error();
+ return PyComplex_FromCComplex(x);
}
PyDoc_STRVAR(cmath_log_doc,
@@ -860,42 +860,42 @@ If the base not specified, returns the natural logarithm (base e) of x.");
static PyObject *
math_error(void)
{
- if (errno == EDOM)
- PyErr_SetString(PyExc_ValueError, "math domain error");
- else if (errno == ERANGE)
- PyErr_SetString(PyExc_OverflowError, "math range error");
- else /* Unexpected math error */
- PyErr_SetFromErrno(PyExc_ValueError);
- return NULL;
+ if (errno == EDOM)
+ PyErr_SetString(PyExc_ValueError, "math domain error");
+ else if (errno == ERANGE)
+ PyErr_SetString(PyExc_OverflowError, "math range error");
+ else /* Unexpected math error */
+ PyErr_SetFromErrno(PyExc_ValueError);
+ return NULL;
}
static PyObject *
math_1(PyObject *args, Py_complex (*func)(Py_complex))
{
- Py_complex x,r ;
- if (!PyArg_ParseTuple(args, "D", &x))
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("complex function", return 0);
- r = (*func)(x);
- PyFPE_END_PROTECT(r);
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ValueError, "math domain error");
- return NULL;
- }
- else if (errno == ERANGE) {
- PyErr_SetString(PyExc_OverflowError, "math range error");
- return NULL;
- }
- else {
- return PyComplex_FromCComplex(r);
- }
+ Py_complex x,r ;
+ if (!PyArg_ParseTuple(args, "D", &x))
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("complex function", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ValueError, "math domain error");
+ return NULL;
+ }
+ else if (errno == ERANGE) {
+ PyErr_SetString(PyExc_OverflowError, "math range error");
+ return NULL;
+ }
+ else {
+ return PyComplex_FromCComplex(r);
+ }
}
#define FUNC1(stubname, func) \
- static PyObject * stubname(PyObject *self, PyObject *args) { \
- return math_1(args, func); \
- }
+ static PyObject * stubname(PyObject *self, PyObject *args) { \
+ return math_1(args, func); \
+ }
FUNC1(cmath_acos, c_acos)
FUNC1(cmath_acosh, c_acosh)
@@ -916,18 +916,18 @@ FUNC1(cmath_tanh, c_tanh)
static PyObject *
cmath_phase(PyObject *self, PyObject *args)
{
- Py_complex z;
- double phi;
- if (!PyArg_ParseTuple(args, "D:phase", &z))
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("arg function", return 0)
- phi = c_atan2(z);
- PyFPE_END_PROTECT(phi)
- if (errno != 0)
- return math_error();
- else
- return PyFloat_FromDouble(phi);
+ Py_complex z;
+ double phi;
+ if (!PyArg_ParseTuple(args, "D:phase", &z))
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("arg function", return 0)
+ phi = c_atan2(z);
+ PyFPE_END_PROTECT(phi)
+ if (errno != 0)
+ return math_error();
+ else
+ return PyFloat_FromDouble(phi);
}
PyDoc_STRVAR(cmath_phase_doc,
@@ -937,18 +937,18 @@ Return argument, also known as the phase angle, of a complex.");
static PyObject *
cmath_polar(PyObject *self, PyObject *args)
{
- Py_complex z;
- double r, phi;
- if (!PyArg_ParseTuple(args, "D:polar", &z))
- return NULL;
- PyFPE_START_PROTECT("polar function", return 0)
- phi = c_atan2(z); /* should not cause any exception */
- r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */
- PyFPE_END_PROTECT(r)
- if (errno != 0)
- return math_error();
- else
- return Py_BuildValue("dd", r, phi);
+ Py_complex z;
+ double r, phi;
+ if (!PyArg_ParseTuple(args, "D:polar", &z))
+ return NULL;
+ PyFPE_START_PROTECT("polar function", return 0)
+ phi = c_atan2(z); /* should not cause any exception */
+ r = c_abs(z); /* sets errno to ERANGE on overflow; otherwise 0 */
+ PyFPE_END_PROTECT(r)
+ if (errno != 0)
+ return math_error();
+ else
+ return Py_BuildValue("dd", r, phi);
}
PyDoc_STRVAR(cmath_polar_doc,
@@ -972,51 +972,51 @@ static Py_complex rect_special_values[7][7];
static PyObject *
cmath_rect(PyObject *self, PyObject *args)
{
- Py_complex z;
- double r, phi;
- if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi))
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("rect function", return 0)
-
- /* deal with special values */
- if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) {
- /* if r is +/-infinity and phi is finite but nonzero then
- result is (+-INF +-INF i), but we need to compute cos(phi)
- and sin(phi) to figure out the signs. */
- if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi)
- && (phi != 0.))) {
- if (r > 0) {
- z.real = copysign(INF, cos(phi));
- z.imag = copysign(INF, sin(phi));
- }
- else {
- z.real = -copysign(INF, cos(phi));
- z.imag = -copysign(INF, sin(phi));
- }
- }
- else {
- z = rect_special_values[special_type(r)]
- [special_type(phi)];
- }
- /* need to set errno = EDOM if r is a nonzero number and phi
- is infinite */
- if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi))
- errno = EDOM;
- else
- errno = 0;
- }
- else {
- z.real = r * cos(phi);
- z.imag = r * sin(phi);
- errno = 0;
- }
-
- PyFPE_END_PROTECT(z)
- if (errno != 0)
- return math_error();
- else
- return PyComplex_FromCComplex(z);
+ Py_complex z;
+ double r, phi;
+ if (!PyArg_ParseTuple(args, "dd:rect", &r, &phi))
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("rect function", return 0)
+
+ /* deal with special values */
+ if (!Py_IS_FINITE(r) || !Py_IS_FINITE(phi)) {
+ /* if r is +/-infinity and phi is finite but nonzero then
+ result is (+-INF +-INF i), but we need to compute cos(phi)
+ and sin(phi) to figure out the signs. */
+ if (Py_IS_INFINITY(r) && (Py_IS_FINITE(phi)
+ && (phi != 0.))) {
+ if (r > 0) {
+ z.real = copysign(INF, cos(phi));
+ z.imag = copysign(INF, sin(phi));
+ }
+ else {
+ z.real = -copysign(INF, cos(phi));
+ z.imag = -copysign(INF, sin(phi));
+ }
+ }
+ else {
+ z = rect_special_values[special_type(r)]
+ [special_type(phi)];
+ }
+ /* need to set errno = EDOM if r is a nonzero number and phi
+ is infinite */
+ if (r != 0. && !Py_IS_NAN(r) && Py_IS_INFINITY(phi))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else {
+ z.real = r * cos(phi);
+ z.imag = r * sin(phi);
+ errno = 0;
+ }
+
+ PyFPE_END_PROTECT(z)
+ if (errno != 0)
+ return math_error();
+ else
+ return PyComplex_FromCComplex(z);
}
PyDoc_STRVAR(cmath_rect_doc,
@@ -1026,10 +1026,10 @@ Convert from polar coordinates to rectangular coordinates.");
static PyObject *
cmath_isnan(PyObject *self, PyObject *args)
{
- Py_complex z;
- if (!PyArg_ParseTuple(args, "D:isnan", &z))
- return NULL;
- return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag));
+ Py_complex z;
+ if (!PyArg_ParseTuple(args, "D:isnan", &z))
+ return NULL;
+ return PyBool_FromLong(Py_IS_NAN(z.real) || Py_IS_NAN(z.imag));
}
PyDoc_STRVAR(cmath_isnan_doc,
@@ -1039,11 +1039,11 @@ Checks if the real or imaginary part of z not a number (NaN)");
static PyObject *
cmath_isinf(PyObject *self, PyObject *args)
{
- Py_complex z;
- if (!PyArg_ParseTuple(args, "D:isnan", &z))
- return NULL;
- return PyBool_FromLong(Py_IS_INFINITY(z.real) ||
- Py_IS_INFINITY(z.imag));
+ Py_complex z;
+ if (!PyArg_ParseTuple(args, "D:isnan", &z))
+ return NULL;
+ return PyBool_FromLong(Py_IS_INFINITY(z.real) ||
+ Py_IS_INFINITY(z.imag));
}
PyDoc_STRVAR(cmath_isinf_doc,
@@ -1056,155 +1056,155 @@ PyDoc_STRVAR(module_doc,
"functions for complex numbers.");
static PyMethodDef cmath_methods[] = {
- {"acos", cmath_acos, METH_VARARGS, c_acos_doc},
- {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc},
- {"asin", cmath_asin, METH_VARARGS, c_asin_doc},
- {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc},
- {"atan", cmath_atan, METH_VARARGS, c_atan_doc},
- {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc},
- {"cos", cmath_cos, METH_VARARGS, c_cos_doc},
- {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc},
- {"exp", cmath_exp, METH_VARARGS, c_exp_doc},
- {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc},
- {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc},
- {"log", cmath_log, METH_VARARGS, cmath_log_doc},
- {"log10", cmath_log10, METH_VARARGS, c_log10_doc},
- {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc},
- {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc},
- {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc},
- {"sin", cmath_sin, METH_VARARGS, c_sin_doc},
- {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc},
- {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc},
- {"tan", cmath_tan, METH_VARARGS, c_tan_doc},
- {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc},
- {NULL, NULL} /* sentinel */
+ {"acos", cmath_acos, METH_VARARGS, c_acos_doc},
+ {"acosh", cmath_acosh, METH_VARARGS, c_acosh_doc},
+ {"asin", cmath_asin, METH_VARARGS, c_asin_doc},
+ {"asinh", cmath_asinh, METH_VARARGS, c_asinh_doc},
+ {"atan", cmath_atan, METH_VARARGS, c_atan_doc},
+ {"atanh", cmath_atanh, METH_VARARGS, c_atanh_doc},
+ {"cos", cmath_cos, METH_VARARGS, c_cos_doc},
+ {"cosh", cmath_cosh, METH_VARARGS, c_cosh_doc},
+ {"exp", cmath_exp, METH_VARARGS, c_exp_doc},
+ {"isinf", cmath_isinf, METH_VARARGS, cmath_isinf_doc},
+ {"isnan", cmath_isnan, METH_VARARGS, cmath_isnan_doc},
+ {"log", cmath_log, METH_VARARGS, cmath_log_doc},
+ {"log10", cmath_log10, METH_VARARGS, c_log10_doc},
+ {"phase", cmath_phase, METH_VARARGS, cmath_phase_doc},
+ {"polar", cmath_polar, METH_VARARGS, cmath_polar_doc},
+ {"rect", cmath_rect, METH_VARARGS, cmath_rect_doc},
+ {"sin", cmath_sin, METH_VARARGS, c_sin_doc},
+ {"sinh", cmath_sinh, METH_VARARGS, c_sinh_doc},
+ {"sqrt", cmath_sqrt, METH_VARARGS, c_sqrt_doc},
+ {"tan", cmath_tan, METH_VARARGS, c_tan_doc},
+ {"tanh", cmath_tanh, METH_VARARGS, c_tanh_doc},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initcmath(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("cmath", cmath_methods, module_doc);
- if (m == NULL)
- return;
+ m = Py_InitModule3("cmath", cmath_methods, module_doc);
+ if (m == NULL)
+ return;
- PyModule_AddObject(m, "pi",
- PyFloat_FromDouble(Py_MATH_PI));
- PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
+ PyModule_AddObject(m, "pi",
+ PyFloat_FromDouble(Py_MATH_PI));
+ PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
- /* initialize special value tables */
+ /* initialize special value tables */
#define INIT_SPECIAL_VALUES(NAME, BODY) { Py_complex* p = (Py_complex*)NAME; BODY }
#define C(REAL, IMAG) p->real = REAL; p->imag = IMAG; ++p;
- INIT_SPECIAL_VALUES(acos_special_values, {
- C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF)
- C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
- C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
- C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
- C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
- C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF)
- C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(acosh_special_values, {
- C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
- C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(asinh_special_values, {
- C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N)
- C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N)
- C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
- C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(atanh_special_values, {
- C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N)
- C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N)
- C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N)
- C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N)
- C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N)
- C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N)
- C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(cosh_special_values, {
- C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.)
- C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(exp_special_values, {
- C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(log_special_values, {
- C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
- C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
- C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(sinh_special_values, {
- C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N)
- C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(sqrt_special_values, {
- C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF)
- C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
- C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N)
- C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(tanh_special_values, {
- C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.)
- C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
-
- INIT_SPECIAL_VALUES(rect_special_values, {
- C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.)
- C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
- C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
- C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
- C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
- })
+ INIT_SPECIAL_VALUES(acos_special_values, {
+ C(P34,INF) C(P,INF) C(P,INF) C(P,-INF) C(P,-INF) C(P34,-INF) C(N,INF)
+ C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
+ C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
+ C(P12,INF) C(U,U) C(P12,0.) C(P12,-0.) C(U,U) C(P12,-INF) C(P12,N)
+ C(P12,INF) C(U,U) C(U,U) C(U,U) C(U,U) C(P12,-INF) C(N,N)
+ C(P14,INF) C(0.,INF) C(0.,INF) C(0.,-INF) C(0.,-INF) C(P14,-INF) C(N,INF)
+ C(N,INF) C(N,N) C(N,N) C(N,N) C(N,N) C(N,-INF) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(acosh_special_values, {
+ C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(0.,-P12) C(0.,P12) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
+ C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(asinh_special_values, {
+ C(-INF,-P14) C(-INF,-0.) C(-INF,-0.) C(-INF,0.) C(-INF,0.) C(-INF,P14) C(-INF,N)
+ C(-INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-INF,P12) C(N,N)
+ C(-INF,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
+ C(INF,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(INF,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(atanh_special_values, {
+ C(-0.,-P12) C(-0.,-P12) C(-0.,-P12) C(-0.,P12) C(-0.,P12) C(-0.,P12) C(-0.,N)
+ C(-0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(-0.,P12) C(N,N)
+ C(-0.,-P12) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(-0.,P12) C(-0.,N)
+ C(0.,-P12) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,P12) C(0.,N)
+ C(0.,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(0.,P12) C(N,N)
+ C(0.,-P12) C(0.,-P12) C(0.,-P12) C(0.,P12) C(0.,P12) C(0.,P12) C(0.,N)
+ C(0.,-P12) C(N,N) C(N,N) C(N,N) C(N,N) C(0.,P12) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(cosh_special_values, {
+ C(INF,N) C(U,U) C(INF,0.) C(INF,-0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(N,0.) C(U,U) C(1.,0.) C(1.,-0.) C(U,U) C(N,0.) C(N,0.)
+ C(N,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,0.) C(N,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(exp_special_values, {
+ C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(log_special_values, {
+ C(INF,-P34) C(INF,-P) C(INF,-P) C(INF,P) C(INF,P) C(INF,P34) C(INF,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(-INF,-P) C(-INF,P) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P12) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,P12) C(N,N)
+ C(INF,-P14) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,P14) C(INF,N)
+ C(INF,N) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(sinh_special_values, {
+ C(INF,N) C(U,U) C(-INF,-0.) C(-INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(0.,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(0.,N) C(0.,N)
+ C(0.,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,N) C(0.,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(sqrt_special_values, {
+ C(INF,-INF) C(0.,-INF) C(0.,-INF) C(0.,INF) C(0.,INF) C(INF,INF) C(N,INF)
+ C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(U,U) C(U,U) C(U,U) C(U,U) C(INF,INF) C(N,N)
+ C(INF,-INF) C(INF,-0.) C(INF,-0.) C(INF,0.) C(INF,0.) C(INF,INF) C(INF,N)
+ C(INF,-INF) C(N,N) C(N,N) C(N,N) C(N,N) C(INF,INF) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(tanh_special_values, {
+ C(-1.,0.) C(U,U) C(-1.,-0.) C(-1.,0.) C(U,U) C(-1.,0.) C(-1.,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(-0.,-0.) C(-0.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(N,N) C(N,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(1.,0.) C(U,U) C(1.,-0.) C(1.,0.) C(U,U) C(1.,0.) C(1.,0.)
+ C(N,N) C(N,N) C(N,-0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
+
+ INIT_SPECIAL_VALUES(rect_special_values, {
+ C(INF,N) C(U,U) C(-INF,0.) C(-INF,-0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(0.,0.) C(U,U) C(-0.,0.) C(-0.,-0.) C(U,U) C(0.,0.) C(0.,0.)
+ C(0.,0.) C(U,U) C(0.,-0.) C(0.,0.) C(U,U) C(0.,0.) C(0.,0.)
+ C(N,N) C(U,U) C(U,U) C(U,U) C(U,U) C(N,N) C(N,N)
+ C(INF,N) C(U,U) C(INF,-0.) C(INF,0.) C(U,U) C(INF,N) C(INF,N)
+ C(N,N) C(N,N) C(N,0.) C(N,0.) C(N,N) C(N,N) C(N,N)
+ })
}
diff --git a/Modules/cryptmodule.c b/Modules/cryptmodule.c
index 6377f84..76de54f 100644
--- a/Modules/cryptmodule.c
+++ b/Modules/cryptmodule.c
@@ -14,17 +14,17 @@
static PyObject *crypt_crypt(PyObject *self, PyObject *args)
{
- char *word, *salt;
+ char *word, *salt;
#ifndef __VMS
- extern char * crypt(const char *, const char *);
+ extern char * crypt(const char *, const char *);
#endif
- if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
- return NULL;
- }
- /* On some platforms (AtheOS) crypt returns NULL for an invalid
- salt. Return None in that case. XXX Maybe raise an exception? */
- return Py_BuildValue("s", crypt(word, salt));
+ if (!PyArg_ParseTuple(args, "ss:crypt", &word, &salt)) {
+ return NULL;
+ }
+ /* On some platforms (AtheOS) crypt returns NULL for an invalid
+ salt. Return None in that case. XXX Maybe raise an exception? */
+ return Py_BuildValue("s", crypt(word, salt));
}
@@ -38,12 +38,12 @@ the same alphabet as the salt.");
static PyMethodDef crypt_methods[] = {
- {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
- {NULL, NULL} /* sentinel */
+ {"crypt", crypt_crypt, METH_VARARGS, crypt_crypt__doc__},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initcrypt(void)
{
- Py_InitModule("crypt", crypt_methods);
+ Py_InitModule("crypt", crypt_methods);
}
diff --git a/Modules/datetimemodule.c b/Modules/datetimemodule.c
index 7105c69..c81f6bb 100644
--- a/Modules/datetimemodule.c
+++ b/Modules/datetimemodule.c
@@ -27,7 +27,7 @@
* final result fits in a C int (this can be an issue on 64-bit boxes).
*/
#if SIZEOF_INT < 4
-# error "datetime.c requires that C int have at least 32 bits"
+# error "datetime.c requires that C int have at least 32 bits"
#endif
#define MINYEAR 1
@@ -41,59 +41,59 @@
#define MAX_DELTA_DAYS 999999999
/* Rename the long macros in datetime.h to more reasonable short names. */
-#define GET_YEAR PyDateTime_GET_YEAR
-#define GET_MONTH PyDateTime_GET_MONTH
-#define GET_DAY PyDateTime_GET_DAY
-#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
-#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
-#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
-#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
+#define GET_YEAR PyDateTime_GET_YEAR
+#define GET_MONTH PyDateTime_GET_MONTH
+#define GET_DAY PyDateTime_GET_DAY
+#define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
+#define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
+#define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
+#define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
/* Date accessors for date and datetime. */
-#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
- ((o)->data[1] = ((v) & 0x00ff)))
-#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
-#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
+#define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
+ ((o)->data[1] = ((v) & 0x00ff)))
+#define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
+#define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
/* Date/Time accessors for datetime. */
-#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
-#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
-#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
-#define DATE_SET_MICROSECOND(o, v) \
- (((o)->data[7] = ((v) & 0xff0000) >> 16), \
- ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
- ((o)->data[9] = ((v) & 0x0000ff)))
+#define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
+#define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
+#define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
+#define DATE_SET_MICROSECOND(o, v) \
+ (((o)->data[7] = ((v) & 0xff0000) >> 16), \
+ ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
+ ((o)->data[9] = ((v) & 0x0000ff)))
/* Time accessors for time. */
-#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
-#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
-#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
-#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
-#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
-#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
-#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
-#define TIME_SET_MICROSECOND(o, v) \
- (((o)->data[3] = ((v) & 0xff0000) >> 16), \
- ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
- ((o)->data[5] = ((v) & 0x0000ff)))
+#define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
+#define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
+#define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
+#define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
+#define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
+#define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
+#define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
+#define TIME_SET_MICROSECOND(o, v) \
+ (((o)->data[3] = ((v) & 0xff0000) >> 16), \
+ ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
+ ((o)->data[5] = ((v) & 0x0000ff)))
/* Delta accessors for timedelta. */
-#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
-#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
-#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
+#define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
+#define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
+#define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
-#define SET_TD_DAYS(o, v) ((o)->days = (v))
-#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
+#define SET_TD_DAYS(o, v) ((o)->days = (v))
+#define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
* p->hastzinfo.
*/
-#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
+#define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
/* M is a char or int claiming to be a valid month. The macro is equivalent
* to the two-sided Python test
- * 1 <= M <= 12
+ * 1 <= M <= 12
*/
#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
@@ -113,7 +113,7 @@ static PyTypeObject PyDateTime_TZInfoType;
* iff (k^i)&(k^j) has sign bit set.
*/
#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
- ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
+ ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
/* Compute Python divmod(x, y), returning the quotient and storing the
* remainder into *r. The quotient is the floor of x/y, and that's
@@ -127,17 +127,17 @@ static PyTypeObject PyDateTime_TZInfoType;
static int
divmod(int x, int y, int *r)
{
- int quo;
+ int quo;
- assert(y > 0);
- quo = x / y;
- *r = x - quo * y;
- if (*r < 0) {
- --quo;
- *r += y;
- }
- assert(0 <= *r && *r < y);
- return quo;
+ assert(y > 0);
+ quo = x / y;
+ *r = x - quo * y;
+ if (*r < 0) {
+ --quo;
+ *r += y;
+ }
+ assert(0 <= *r && *r < y);
+ return quo;
}
/* Round a double to the nearest long. |x| must be small enough to fit
@@ -146,11 +146,11 @@ divmod(int x, int y, int *r)
static long
round_to_long(double x)
{
- if (x >= 0.0)
- x = floor(x + 0.5);
- else
- x = ceil(x - 0.5);
- return (long)x;
+ if (x >= 0.0)
+ x = floor(x + 0.5);
+ else
+ x = ceil(x - 0.5);
+ return (long)x;
}
/* ---------------------------------------------------------------------------
@@ -162,52 +162,52 @@ round_to_long(double x)
* are correct for non-leap years only.
*/
static int _days_in_month[] = {
- 0, /* unused; this vector uses 1-based indexing */
- 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
+ 0, /* unused; this vector uses 1-based indexing */
+ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
};
static int _days_before_month[] = {
- 0, /* unused; this vector uses 1-based indexing */
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
+ 0, /* unused; this vector uses 1-based indexing */
+ 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
};
/* year -> 1 if leap year, else 0. */
static int
is_leap(int year)
{
- /* Cast year to unsigned. The result is the same either way, but
- * C can generate faster code for unsigned mod than for signed
- * mod (especially for % 4 -- a good compiler should just grab
- * the last 2 bits when the LHS is unsigned).
- */
- const unsigned int ayear = (unsigned int)year;
- return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
+ /* Cast year to unsigned. The result is the same either way, but
+ * C can generate faster code for unsigned mod than for signed
+ * mod (especially for % 4 -- a good compiler should just grab
+ * the last 2 bits when the LHS is unsigned).
+ */
+ const unsigned int ayear = (unsigned int)year;
+ return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
}
/* year, month -> number of days in that month in that year */
static int
days_in_month(int year, int month)
{
- assert(month >= 1);
- assert(month <= 12);
- if (month == 2 && is_leap(year))
- return 29;
- else
- return _days_in_month[month];
+ assert(month >= 1);
+ assert(month <= 12);
+ if (month == 2 && is_leap(year))
+ return 29;
+ else
+ return _days_in_month[month];
}
/* year, month -> number of days in year preceeding first day of month */
static int
days_before_month(int year, int month)
{
- int days;
+ int days;
- assert(month >= 1);
- assert(month <= 12);
- days = _days_before_month[month];
- if (month > 2 && is_leap(year))
- ++days;
- return days;
+ assert(month >= 1);
+ assert(month <= 12);
+ days = _days_before_month[month];
+ if (month > 2 && is_leap(year))
+ ++days;
+ return days;
}
/* year -> number of days before January 1st of year. Remember that we
@@ -216,124 +216,124 @@ days_before_month(int year, int month)
static int
days_before_year(int year)
{
- int y = year - 1;
- /* This is incorrect if year <= 0; we really want the floor
- * here. But so long as MINYEAR is 1, the smallest year this
- * can see is 0 (this can happen in some normalization endcases),
- * so we'll just special-case that.
- */
- assert (year >= 0);
- if (y >= 0)
- return y*365 + y/4 - y/100 + y/400;
- else {
- assert(y == -1);
- return -366;
- }
+ int y = year - 1;
+ /* This is incorrect if year <= 0; we really want the floor
+ * here. But so long as MINYEAR is 1, the smallest year this
+ * can see is 0 (this can happen in some normalization endcases),
+ * so we'll just special-case that.
+ */
+ assert (year >= 0);
+ if (y >= 0)
+ return y*365 + y/4 - y/100 + y/400;
+ else {
+ assert(y == -1);
+ return -366;
+ }
}
/* Number of days in 4, 100, and 400 year cycles. That these have
* the correct values is asserted in the module init function.
*/
-#define DI4Y 1461 /* days_before_year(5); days in 4 years */
-#define DI100Y 36524 /* days_before_year(101); days in 100 years */
-#define DI400Y 146097 /* days_before_year(401); days in 400 years */
+#define DI4Y 1461 /* days_before_year(5); days in 4 years */
+#define DI100Y 36524 /* days_before_year(101); days in 100 years */
+#define DI400Y 146097 /* days_before_year(401); days in 400 years */
/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
static void
ord_to_ymd(int ordinal, int *year, int *month, int *day)
{
- int n, n1, n4, n100, n400, leapyear, preceding;
-
- /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
- * leap years repeats exactly every 400 years. The basic strategy is
- * to find the closest 400-year boundary at or before ordinal, then
- * work with the offset from that boundary to ordinal. Life is much
- * clearer if we subtract 1 from ordinal first -- then the values
- * of ordinal at 400-year boundaries are exactly those divisible
- * by DI400Y:
- *
- * D M Y n n-1
- * -- --- ---- ---------- ----------------
- * 31 Dec -400 -DI400Y -DI400Y -1
- * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
- * ...
- * 30 Dec 000 -1 -2
- * 31 Dec 000 0 -1
- * 1 Jan 001 1 0 400-year boundary
- * 2 Jan 001 2 1
- * 3 Jan 001 3 2
- * ...
- * 31 Dec 400 DI400Y DI400Y -1
- * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
- */
- assert(ordinal >= 1);
- --ordinal;
- n400 = ordinal / DI400Y;
- n = ordinal % DI400Y;
- *year = n400 * 400 + 1;
-
- /* Now n is the (non-negative) offset, in days, from January 1 of
- * year, to the desired date. Now compute how many 100-year cycles
- * precede n.
- * Note that it's possible for n100 to equal 4! In that case 4 full
- * 100-year cycles precede the desired day, which implies the
- * desired day is December 31 at the end of a 400-year cycle.
- */
- n100 = n / DI100Y;
- n = n % DI100Y;
-
- /* Now compute how many 4-year cycles precede it. */
- n4 = n / DI4Y;
- n = n % DI4Y;
-
- /* And now how many single years. Again n1 can be 4, and again
- * meaning that the desired day is December 31 at the end of the
- * 4-year cycle.
- */
- n1 = n / 365;
- n = n % 365;
-
- *year += n100 * 100 + n4 * 4 + n1;
- if (n1 == 4 || n100 == 4) {
- assert(n == 0);
- *year -= 1;
- *month = 12;
- *day = 31;
- return;
- }
-
- /* Now the year is correct, and n is the offset from January 1. We
- * find the month via an estimate that's either exact or one too
- * large.
- */
- leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
- assert(leapyear == is_leap(*year));
- *month = (n + 50) >> 5;
- preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
- if (preceding > n) {
- /* estimate is too large */
- *month -= 1;
- preceding -= days_in_month(*year, *month);
- }
- n -= preceding;
- assert(0 <= n);
- assert(n < days_in_month(*year, *month));
-
- *day = n + 1;
+ int n, n1, n4, n100, n400, leapyear, preceding;
+
+ /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
+ * leap years repeats exactly every 400 years. The basic strategy is
+ * to find the closest 400-year boundary at or before ordinal, then
+ * work with the offset from that boundary to ordinal. Life is much
+ * clearer if we subtract 1 from ordinal first -- then the values
+ * of ordinal at 400-year boundaries are exactly those divisible
+ * by DI400Y:
+ *
+ * D M Y n n-1
+ * -- --- ---- ---------- ----------------
+ * 31 Dec -400 -DI400Y -DI400Y -1
+ * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
+ * ...
+ * 30 Dec 000 -1 -2
+ * 31 Dec 000 0 -1
+ * 1 Jan 001 1 0 400-year boundary
+ * 2 Jan 001 2 1
+ * 3 Jan 001 3 2
+ * ...
+ * 31 Dec 400 DI400Y DI400Y -1
+ * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
+ */
+ assert(ordinal >= 1);
+ --ordinal;
+ n400 = ordinal / DI400Y;
+ n = ordinal % DI400Y;
+ *year = n400 * 400 + 1;
+
+ /* Now n is the (non-negative) offset, in days, from January 1 of
+ * year, to the desired date. Now compute how many 100-year cycles
+ * precede n.
+ * Note that it's possible for n100 to equal 4! In that case 4 full
+ * 100-year cycles precede the desired day, which implies the
+ * desired day is December 31 at the end of a 400-year cycle.
+ */
+ n100 = n / DI100Y;
+ n = n % DI100Y;
+
+ /* Now compute how many 4-year cycles precede it. */
+ n4 = n / DI4Y;
+ n = n % DI4Y;
+
+ /* And now how many single years. Again n1 can be 4, and again
+ * meaning that the desired day is December 31 at the end of the
+ * 4-year cycle.
+ */
+ n1 = n / 365;
+ n = n % 365;
+
+ *year += n100 * 100 + n4 * 4 + n1;
+ if (n1 == 4 || n100 == 4) {
+ assert(n == 0);
+ *year -= 1;
+ *month = 12;
+ *day = 31;
+ return;
+ }
+
+ /* Now the year is correct, and n is the offset from January 1. We
+ * find the month via an estimate that's either exact or one too
+ * large.
+ */
+ leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
+ assert(leapyear == is_leap(*year));
+ *month = (n + 50) >> 5;
+ preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
+ if (preceding > n) {
+ /* estimate is too large */
+ *month -= 1;
+ preceding -= days_in_month(*year, *month);
+ }
+ n -= preceding;
+ assert(0 <= n);
+ assert(n < days_in_month(*year, *month));
+
+ *day = n + 1;
}
/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
static int
ymd_to_ord(int year, int month, int day)
{
- return days_before_year(year) + days_before_month(year, month) + day;
+ return days_before_year(year) + days_before_month(year, month) + day;
}
/* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
static int
weekday(int year, int month, int day)
{
- return (ymd_to_ord(year, month, day) + 6) % 7;
+ return (ymd_to_ord(year, month, day) + 6) % 7;
}
/* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
@@ -342,15 +342,15 @@ weekday(int year, int month, int day)
static int
iso_week1_monday(int year)
{
- int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
- /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
- int first_weekday = (first_day + 6) % 7;
- /* ordinal of closest Monday at or before 1/1 */
- int week1_monday = first_day - first_weekday;
+ int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
+ /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
+ int first_weekday = (first_day + 6) % 7;
+ /* ordinal of closest Monday at or before 1/1 */
+ int week1_monday = first_day - first_weekday;
- if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
- week1_monday += 7;
- return week1_monday;
+ if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
+ week1_monday += 7;
+ return week1_monday;
}
/* ---------------------------------------------------------------------------
@@ -363,12 +363,12 @@ iso_week1_monday(int year)
static int
check_delta_day_range(int days)
{
- if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
- return 0;
- PyErr_Format(PyExc_OverflowError,
- "days=%d; must have magnitude <= %d",
- days, MAX_DELTA_DAYS);
- return -1;
+ if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
+ return 0;
+ PyErr_Format(PyExc_OverflowError,
+ "days=%d; must have magnitude <= %d",
+ days, MAX_DELTA_DAYS);
+ return -1;
}
/* Check that date arguments are in range. Return 0 if they are. If they
@@ -378,22 +378,22 @@ static int
check_date_args(int year, int month, int day)
{
- if (year < MINYEAR || year > MAXYEAR) {
- PyErr_SetString(PyExc_ValueError,
- "year is out of range");
- return -1;
- }
- if (month < 1 || month > 12) {
- PyErr_SetString(PyExc_ValueError,
- "month must be in 1..12");
- return -1;
- }
- if (day < 1 || day > days_in_month(year, month)) {
- PyErr_SetString(PyExc_ValueError,
- "day is out of range for month");
- return -1;
- }
- return 0;
+ if (year < MINYEAR || year > MAXYEAR) {
+ PyErr_SetString(PyExc_ValueError,
+ "year is out of range");
+ return -1;
+ }
+ if (month < 1 || month > 12) {
+ PyErr_SetString(PyExc_ValueError,
+ "month must be in 1..12");
+ return -1;
+ }
+ if (day < 1 || day > days_in_month(year, month)) {
+ PyErr_SetString(PyExc_ValueError,
+ "day is out of range for month");
+ return -1;
+ }
+ return 0;
}
/* Check that time arguments are in range. Return 0 if they are. If they
@@ -402,27 +402,27 @@ check_date_args(int year, int month, int day)
static int
check_time_args(int h, int m, int s, int us)
{
- if (h < 0 || h > 23) {
- PyErr_SetString(PyExc_ValueError,
- "hour must be in 0..23");
- return -1;
- }
- if (m < 0 || m > 59) {
- PyErr_SetString(PyExc_ValueError,
- "minute must be in 0..59");
- return -1;
- }
- if (s < 0 || s > 59) {
- PyErr_SetString(PyExc_ValueError,
- "second must be in 0..59");
- return -1;
- }
- if (us < 0 || us > 999999) {
- PyErr_SetString(PyExc_ValueError,
- "microsecond must be in 0..999999");
- return -1;
- }
- return 0;
+ if (h < 0 || h > 23) {
+ PyErr_SetString(PyExc_ValueError,
+ "hour must be in 0..23");
+ return -1;
+ }
+ if (m < 0 || m > 59) {
+ PyErr_SetString(PyExc_ValueError,
+ "minute must be in 0..59");
+ return -1;
+ }
+ if (s < 0 || s > 59) {
+ PyErr_SetString(PyExc_ValueError,
+ "second must be in 0..59");
+ return -1;
+ }
+ if (us < 0 || us > 999999) {
+ PyErr_SetString(PyExc_ValueError,
+ "microsecond must be in 0..999999");
+ return -1;
+ }
+ return 0;
}
/* ---------------------------------------------------------------------------
@@ -438,109 +438,109 @@ check_time_args(int h, int m, int s, int us)
static void
normalize_pair(int *hi, int *lo, int factor)
{
- assert(factor > 0);
- assert(lo != hi);
- if (*lo < 0 || *lo >= factor) {
- const int num_hi = divmod(*lo, factor, lo);
- const int new_hi = *hi + num_hi;
- assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
- *hi = new_hi;
- }
- assert(0 <= *lo && *lo < factor);
+ assert(factor > 0);
+ assert(lo != hi);
+ if (*lo < 0 || *lo >= factor) {
+ const int num_hi = divmod(*lo, factor, lo);
+ const int new_hi = *hi + num_hi;
+ assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
+ *hi = new_hi;
+ }
+ assert(0 <= *lo && *lo < factor);
}
/* Fiddle days (d), seconds (s), and microseconds (us) so that
- * 0 <= *s < 24*3600
- * 0 <= *us < 1000000
+ * 0 <= *s < 24*3600
+ * 0 <= *us < 1000000
* The input values must be such that the internals don't overflow.
* The way this routine is used, we don't get close.
*/
static void
normalize_d_s_us(int *d, int *s, int *us)
{
- if (*us < 0 || *us >= 1000000) {
- normalize_pair(s, us, 1000000);
- /* |s| can't be bigger than about
- * |original s| + |original us|/1000000 now.
- */
+ if (*us < 0 || *us >= 1000000) {
+ normalize_pair(s, us, 1000000);
+ /* |s| can't be bigger than about
+ * |original s| + |original us|/1000000 now.
+ */
- }
- if (*s < 0 || *s >= 24*3600) {
- normalize_pair(d, s, 24*3600);
- /* |d| can't be bigger than about
- * |original d| +
- * (|original s| + |original us|/1000000) / (24*3600) now.
- */
- }
- assert(0 <= *s && *s < 24*3600);
- assert(0 <= *us && *us < 1000000);
+ }
+ if (*s < 0 || *s >= 24*3600) {
+ normalize_pair(d, s, 24*3600);
+ /* |d| can't be bigger than about
+ * |original d| +
+ * (|original s| + |original us|/1000000) / (24*3600) now.
+ */
+ }
+ assert(0 <= *s && *s < 24*3600);
+ assert(0 <= *us && *us < 1000000);
}
/* Fiddle years (y), months (m), and days (d) so that
- * 1 <= *m <= 12
- * 1 <= *d <= days_in_month(*y, *m)
+ * 1 <= *m <= 12
+ * 1 <= *d <= days_in_month(*y, *m)
* The input values must be such that the internals don't overflow.
* The way this routine is used, we don't get close.
*/
static void
normalize_y_m_d(int *y, int *m, int *d)
{
- int dim; /* # of days in month */
-
- /* This gets muddy: the proper range for day can't be determined
- * without knowing the correct month and year, but if day is, e.g.,
- * plus or minus a million, the current month and year values make
- * no sense (and may also be out of bounds themselves).
- * Saying 12 months == 1 year should be non-controversial.
- */
- if (*m < 1 || *m > 12) {
- --*m;
- normalize_pair(y, m, 12);
- ++*m;
- /* |y| can't be bigger than about
- * |original y| + |original m|/12 now.
- */
- }
- assert(1 <= *m && *m <= 12);
-
- /* Now only day can be out of bounds (year may also be out of bounds
- * for a datetime object, but we don't care about that here).
- * If day is out of bounds, what to do is arguable, but at least the
- * method here is principled and explainable.
- */
- dim = days_in_month(*y, *m);
- if (*d < 1 || *d > dim) {
- /* Move day-1 days from the first of the month. First try to
- * get off cheap if we're only one day out of range
- * (adjustments for timezone alone can't be worse than that).
- */
- if (*d == 0) {
- --*m;
- if (*m > 0)
- *d = days_in_month(*y, *m);
- else {
- --*y;
- *m = 12;
- *d = 31;
- }
- }
- else if (*d == dim + 1) {
- /* move forward a day */
- ++*m;
- *d = 1;
- if (*m > 12) {
- *m = 1;
- ++*y;
- }
- }
- else {
- int ordinal = ymd_to_ord(*y, *m, 1) +
- *d - 1;
- ord_to_ymd(ordinal, y, m, d);
- }
- }
- assert(*m > 0);
- assert(*d > 0);
+ int dim; /* # of days in month */
+
+ /* This gets muddy: the proper range for day can't be determined
+ * without knowing the correct month and year, but if day is, e.g.,
+ * plus or minus a million, the current month and year values make
+ * no sense (and may also be out of bounds themselves).
+ * Saying 12 months == 1 year should be non-controversial.
+ */
+ if (*m < 1 || *m > 12) {
+ --*m;
+ normalize_pair(y, m, 12);
+ ++*m;
+ /* |y| can't be bigger than about
+ * |original y| + |original m|/12 now.
+ */
+ }
+ assert(1 <= *m && *m <= 12);
+
+ /* Now only day can be out of bounds (year may also be out of bounds
+ * for a datetime object, but we don't care about that here).
+ * If day is out of bounds, what to do is arguable, but at least the
+ * method here is principled and explainable.
+ */
+ dim = days_in_month(*y, *m);
+ if (*d < 1 || *d > dim) {
+ /* Move day-1 days from the first of the month. First try to
+ * get off cheap if we're only one day out of range
+ * (adjustments for timezone alone can't be worse than that).
+ */
+ if (*d == 0) {
+ --*m;
+ if (*m > 0)
+ *d = days_in_month(*y, *m);
+ else {
+ --*y;
+ *m = 12;
+ *d = 31;
+ }
+ }
+ else if (*d == dim + 1) {
+ /* move forward a day */
+ ++*m;
+ *d = 1;
+ if (*m > 12) {
+ *m = 1;
+ ++*y;
+ }
+ }
+ else {
+ int ordinal = ymd_to_ord(*y, *m, 1) +
+ *d - 1;
+ ord_to_ymd(ordinal, y, m, d);
+ }
+ }
+ assert(*m > 0);
+ assert(*d > 0);
}
/* Fiddle out-of-bounds months and days so that the result makes some kind
@@ -550,17 +550,17 @@ normalize_y_m_d(int *y, int *m, int *d)
static int
normalize_date(int *year, int *month, int *day)
{
- int result;
+ int result;
- normalize_y_m_d(year, month, day);
- if (MINYEAR <= *year && *year <= MAXYEAR)
- result = 0;
- else {
- PyErr_SetString(PyExc_OverflowError,
- "date value out of range");
- result = -1;
- }
- return result;
+ normalize_y_m_d(year, month, day);
+ if (MINYEAR <= *year && *year <= MAXYEAR)
+ result = 0;
+ else {
+ PyErr_SetString(PyExc_OverflowError,
+ "date value out of range");
+ result = -1;
+ }
+ return result;
}
/* Force all the datetime fields into range. The parameters are both
@@ -571,11 +571,11 @@ normalize_datetime(int *year, int *month, int *day,
int *hour, int *minute, int *second,
int *microsecond)
{
- normalize_pair(second, microsecond, 1000000);
- normalize_pair(minute, second, 60);
- normalize_pair(hour, minute, 60);
- normalize_pair(day, hour, 24);
- return normalize_date(year, month, day);
+ normalize_pair(second, microsecond, 1000000);
+ normalize_pair(minute, second, 60);
+ normalize_pair(hour, minute, 60);
+ normalize_pair(day, hour, 24);
+ return normalize_date(year, month, day);
}
/* ---------------------------------------------------------------------------
@@ -602,31 +602,31 @@ normalize_datetime(int *year, int *month, int *day,
static PyObject *
time_alloc(PyTypeObject *type, Py_ssize_t aware)
{
- PyObject *self;
+ PyObject *self;
- self = (PyObject *)
- PyObject_MALLOC(aware ?
- sizeof(PyDateTime_Time) :
- sizeof(_PyDateTime_BaseTime));
- if (self == NULL)
- return (PyObject *)PyErr_NoMemory();
- PyObject_INIT(self, type);
- return self;
+ self = (PyObject *)
+ PyObject_MALLOC(aware ?
+ sizeof(PyDateTime_Time) :
+ sizeof(_PyDateTime_BaseTime));
+ if (self == NULL)
+ return (PyObject *)PyErr_NoMemory();
+ PyObject_INIT(self, type);
+ return self;
}
static PyObject *
datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
{
- PyObject *self;
+ PyObject *self;
- self = (PyObject *)
- PyObject_MALLOC(aware ?
- sizeof(PyDateTime_DateTime) :
- sizeof(_PyDateTime_BaseDateTime));
- if (self == NULL)
- return (PyObject *)PyErr_NoMemory();
- PyObject_INIT(self, type);
- return self;
+ self = (PyObject *)
+ PyObject_MALLOC(aware ?
+ sizeof(PyDateTime_DateTime) :
+ sizeof(_PyDateTime_BaseDateTime));
+ if (self == NULL)
+ return (PyObject *)PyErr_NoMemory();
+ PyObject_INIT(self, type);
+ return self;
}
/* ---------------------------------------------------------------------------
@@ -638,10 +638,10 @@ datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
static void
set_date_fields(PyDateTime_Date *self, int y, int m, int d)
{
- self->hashcode = -1;
- SET_YEAR(self, y);
- SET_MONTH(self, m);
- SET_DAY(self, d);
+ self->hashcode = -1;
+ SET_YEAR(self, y);
+ SET_MONTH(self, m);
+ SET_DAY(self, d);
}
/* ---------------------------------------------------------------------------
@@ -652,71 +652,71 @@ set_date_fields(PyDateTime_Date *self, int y, int m, int d)
static PyObject *
new_date_ex(int year, int month, int day, PyTypeObject *type)
{
- PyDateTime_Date *self;
+ PyDateTime_Date *self;
- self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
- if (self != NULL)
- set_date_fields(self, year, month, day);
- return (PyObject *) self;
+ self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
+ if (self != NULL)
+ set_date_fields(self, year, month, day);
+ return (PyObject *) self;
}
#define new_date(year, month, day) \
- new_date_ex(year, month, day, &PyDateTime_DateType)
+ new_date_ex(year, month, day, &PyDateTime_DateType)
/* Create a datetime instance with no range checking. */
static PyObject *
new_datetime_ex(int year, int month, int day, int hour, int minute,
- int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
-{
- PyDateTime_DateTime *self;
- char aware = tzinfo != Py_None;
-
- self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
- if (self != NULL) {
- self->hastzinfo = aware;
- set_date_fields((PyDateTime_Date *)self, year, month, day);
- DATE_SET_HOUR(self, hour);
- DATE_SET_MINUTE(self, minute);
- DATE_SET_SECOND(self, second);
- DATE_SET_MICROSECOND(self, usecond);
- if (aware) {
- Py_INCREF(tzinfo);
- self->tzinfo = tzinfo;
- }
- }
- return (PyObject *)self;
-}
-
-#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
- new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
- &PyDateTime_DateTimeType)
+ int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
+{
+ PyDateTime_DateTime *self;
+ char aware = tzinfo != Py_None;
+
+ self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
+ if (self != NULL) {
+ self->hastzinfo = aware;
+ set_date_fields((PyDateTime_Date *)self, year, month, day);
+ DATE_SET_HOUR(self, hour);
+ DATE_SET_MINUTE(self, minute);
+ DATE_SET_SECOND(self, second);
+ DATE_SET_MICROSECOND(self, usecond);
+ if (aware) {
+ Py_INCREF(tzinfo);
+ self->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)self;
+}
+
+#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
+ new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
+ &PyDateTime_DateTimeType)
/* Create a time instance with no range checking. */
static PyObject *
new_time_ex(int hour, int minute, int second, int usecond,
- PyObject *tzinfo, PyTypeObject *type)
-{
- PyDateTime_Time *self;
- char aware = tzinfo != Py_None;
-
- self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
- if (self != NULL) {
- self->hastzinfo = aware;
- self->hashcode = -1;
- TIME_SET_HOUR(self, hour);
- TIME_SET_MINUTE(self, minute);
- TIME_SET_SECOND(self, second);
- TIME_SET_MICROSECOND(self, usecond);
- if (aware) {
- Py_INCREF(tzinfo);
- self->tzinfo = tzinfo;
- }
- }
- return (PyObject *)self;
-}
-
-#define new_time(hh, mm, ss, us, tzinfo) \
- new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
+ PyObject *tzinfo, PyTypeObject *type)
+{
+ PyDateTime_Time *self;
+ char aware = tzinfo != Py_None;
+
+ self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
+ if (self != NULL) {
+ self->hastzinfo = aware;
+ self->hashcode = -1;
+ TIME_SET_HOUR(self, hour);
+ TIME_SET_MINUTE(self, minute);
+ TIME_SET_SECOND(self, second);
+ TIME_SET_MICROSECOND(self, usecond);
+ if (aware) {
+ Py_INCREF(tzinfo);
+ self->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)self;
+}
+
+#define new_time(hh, mm, ss, us, tzinfo) \
+ new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
/* Create a timedelta instance. Normalize the members iff normalize is
* true. Passing false is a speed optimization, if you know for sure
@@ -726,30 +726,30 @@ new_time_ex(int hour, int minute, int second, int usecond,
*/
static PyObject *
new_delta_ex(int days, int seconds, int microseconds, int normalize,
- PyTypeObject *type)
+ PyTypeObject *type)
{
- PyDateTime_Delta *self;
+ PyDateTime_Delta *self;
- if (normalize)
- normalize_d_s_us(&days, &seconds, &microseconds);
- assert(0 <= seconds && seconds < 24*3600);
- assert(0 <= microseconds && microseconds < 1000000);
+ if (normalize)
+ normalize_d_s_us(&days, &seconds, &microseconds);
+ assert(0 <= seconds && seconds < 24*3600);
+ assert(0 <= microseconds && microseconds < 1000000);
- if (check_delta_day_range(days) < 0)
- return NULL;
+ if (check_delta_day_range(days) < 0)
+ return NULL;
- self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
- if (self != NULL) {
- self->hashcode = -1;
- SET_TD_DAYS(self, days);
- SET_TD_SECONDS(self, seconds);
- SET_TD_MICROSECONDS(self, microseconds);
- }
- return (PyObject *) self;
+ self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
+ if (self != NULL) {
+ self->hashcode = -1;
+ SET_TD_DAYS(self, days);
+ SET_TD_SECONDS(self, seconds);
+ SET_TD_MICROSECONDS(self, microseconds);
+ }
+ return (PyObject *) self;
}
-#define new_delta(d, s, us, normalize) \
- new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
+#define new_delta(d, s, us, normalize) \
+ new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
/* ---------------------------------------------------------------------------
* tzinfo helpers.
@@ -761,13 +761,13 @@ new_delta_ex(int days, int seconds, int microseconds, int normalize,
static int
check_tzinfo_subclass(PyObject *p)
{
- if (p == Py_None || PyTZInfo_Check(p))
- return 0;
- PyErr_Format(PyExc_TypeError,
- "tzinfo argument must be None or of a tzinfo subclass, "
- "not type '%s'",
- Py_TYPE(p)->tp_name);
- return -1;
+ if (p == Py_None || PyTZInfo_Check(p))
+ return 0;
+ PyErr_Format(PyExc_TypeError,
+ "tzinfo argument must be None or of a tzinfo subclass, "
+ "not type '%s'",
+ Py_TYPE(p)->tp_name);
+ return -1;
}
/* Return tzinfo.methname(tzinfoarg), without any checking of results.
@@ -776,17 +776,17 @@ check_tzinfo_subclass(PyObject *p)
static PyObject *
call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
{
- PyObject *result;
+ PyObject *result;
- assert(tzinfo && methname && tzinfoarg);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
- return result;
+ assert(tzinfo && methname && tzinfoarg);
+ assert(check_tzinfo_subclass(tzinfo) >= 0);
+ if (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
+ return result;
}
/* If self has a tzinfo member, return a BORROWED reference to it. Else
@@ -796,14 +796,14 @@ call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
static PyObject *
get_tzinfo_member(PyObject *self)
{
- PyObject *tzinfo = NULL;
+ PyObject *tzinfo = NULL;
- if (PyDateTime_Check(self) && HASTZINFO(self))
- tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
- else if (PyTime_Check(self) && HASTZINFO(self))
- tzinfo = ((PyDateTime_Time *)self)->tzinfo;
+ if (PyDateTime_Check(self) && HASTZINFO(self))
+ tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
+ else if (PyTime_Check(self) && HASTZINFO(self))
+ tzinfo = ((PyDateTime_Time *)self)->tzinfo;
- return tzinfo;
+ return tzinfo;
}
/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
@@ -816,59 +816,59 @@ get_tzinfo_member(PyObject *self)
*/
static int
call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
- int *none)
-{
- PyObject *u;
- int result = -1;
-
- assert(tzinfo != NULL);
- assert(PyTZInfo_Check(tzinfo));
- assert(tzinfoarg != NULL);
-
- *none = 0;
- u = call_tzinfo_method(tzinfo, name, tzinfoarg);
- if (u == NULL)
- return -1;
-
- else if (u == Py_None) {
- result = 0;
- *none = 1;
- }
- else if (PyDelta_Check(u)) {
- const int days = GET_TD_DAYS(u);
- if (days < -1 || days > 0)
- result = 24*60; /* trigger ValueError below */
- else {
- /* next line can't overflow because we know days
- * is -1 or 0 now
- */
- int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
- result = divmod(ss, 60, &ss);
- if (ss || GET_TD_MICROSECONDS(u)) {
- PyErr_Format(PyExc_ValueError,
- "tzinfo.%s() must return a "
- "whole number of minutes",
- name);
- result = -1;
- }
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "tzinfo.%s() must return None or "
- "timedelta, not '%s'",
- name, Py_TYPE(u)->tp_name);
- }
-
- Py_DECREF(u);
- if (result < -1439 || result > 1439) {
- PyErr_Format(PyExc_ValueError,
- "tzinfo.%s() returned %d; must be in "
- "-1439 .. 1439",
- name, result);
- result = -1;
- }
- return result;
+ int *none)
+{
+ PyObject *u;
+ int result = -1;
+
+ assert(tzinfo != NULL);
+ assert(PyTZInfo_Check(tzinfo));
+ assert(tzinfoarg != NULL);
+
+ *none = 0;
+ u = call_tzinfo_method(tzinfo, name, tzinfoarg);
+ if (u == NULL)
+ return -1;
+
+ else if (u == Py_None) {
+ result = 0;
+ *none = 1;
+ }
+ else if (PyDelta_Check(u)) {
+ const int days = GET_TD_DAYS(u);
+ if (days < -1 || days > 0)
+ result = 24*60; /* trigger ValueError below */
+ else {
+ /* next line can't overflow because we know days
+ * is -1 or 0 now
+ */
+ int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
+ result = divmod(ss, 60, &ss);
+ if (ss || GET_TD_MICROSECONDS(u)) {
+ PyErr_Format(PyExc_ValueError,
+ "tzinfo.%s() must return a "
+ "whole number of minutes",
+ name);
+ result = -1;
+ }
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "tzinfo.%s() must return None or "
+ "timedelta, not '%s'",
+ name, Py_TYPE(u)->tp_name);
+ }
+
+ Py_DECREF(u);
+ if (result < -1439 || result > 1439) {
+ PyErr_Format(PyExc_ValueError,
+ "tzinfo.%s() returned %d; must be in "
+ "-1439 .. 1439",
+ name, result);
+ result = -1;
+ }
+ return result;
}
/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
@@ -882,34 +882,34 @@ call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
static int
call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
{
- return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
+ return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
}
/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
*/
static PyObject *
offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
- PyObject *result;
-
- assert(tzinfo && name && tzinfoarg);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else {
- int none;
- int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
- &none);
- if (offset < 0 && PyErr_Occurred())
- return NULL;
- if (none) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = new_delta(0, offset * 60, 0, 1);
- }
- return result;
+ PyObject *result;
+
+ assert(tzinfo && name && tzinfoarg);
+ if (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else {
+ int none;
+ int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
+ &none);
+ if (offset < 0 && PyErr_Occurred())
+ return NULL;
+ if (none) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = new_delta(0, offset * 60, 0, 1);
+ }
+ return result;
}
/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
@@ -923,7 +923,7 @@ offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
static int
call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
{
- return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
+ return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
}
/* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
@@ -934,48 +934,48 @@ call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
static PyObject *
call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
{
- PyObject *result;
+ PyObject *result;
- assert(tzinfo != NULL);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- assert(tzinfoarg != NULL);
+ assert(tzinfo != NULL);
+ assert(check_tzinfo_subclass(tzinfo) >= 0);
+ assert(tzinfoarg != NULL);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
+ if (tzinfo == Py_None) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else
+ result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
- if (result != NULL && result != Py_None && ! PyString_Check(result)) {
- PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
- "return None or a string, not '%s'",
- Py_TYPE(result)->tp_name);
- Py_DECREF(result);
- result = NULL;
- }
- return result;
+ if (result != NULL && result != Py_None && ! PyString_Check(result)) {
+ PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
+ "return None or a string, not '%s'",
+ Py_TYPE(result)->tp_name);
+ Py_DECREF(result);
+ result = NULL;
+ }
+ return result;
}
typedef enum {
- /* an exception has been set; the caller should pass it on */
- OFFSET_ERROR,
-
- /* type isn't date, datetime, or time subclass */
- OFFSET_UNKNOWN,
-
- /* date,
- * datetime with !hastzinfo
- * datetime with None tzinfo,
- * datetime where utcoffset() returns None
- * time with !hastzinfo
- * time with None tzinfo,
- * time where utcoffset() returns None
- */
- OFFSET_NAIVE,
-
- /* time or datetime where utcoffset() doesn't return None */
- OFFSET_AWARE
+ /* an exception has been set; the caller should pass it on */
+ OFFSET_ERROR,
+
+ /* type isn't date, datetime, or time subclass */
+ OFFSET_UNKNOWN,
+
+ /* date,
+ * datetime with !hastzinfo
+ * datetime with None tzinfo,
+ * datetime where utcoffset() returns None
+ * time with !hastzinfo
+ * time with None tzinfo,
+ * time where utcoffset() returns None
+ */
+ OFFSET_NAIVE,
+
+ /* time or datetime where utcoffset() doesn't return None */
+ OFFSET_AWARE
} naivety;
/* Classify an object as to whether it's naive or offset-aware. See
@@ -987,23 +987,23 @@ typedef enum {
static naivety
classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
{
- int none;
- PyObject *tzinfo;
-
- assert(tzinfoarg != NULL);
- *offset = 0;
- tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
- if (tzinfo == Py_None)
- return OFFSET_NAIVE;
- if (tzinfo == NULL) {
- /* note that a datetime passes the PyDate_Check test */
- return (PyTime_Check(op) || PyDate_Check(op)) ?
- OFFSET_NAIVE : OFFSET_UNKNOWN;
- }
- *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
- if (*offset == -1 && PyErr_Occurred())
- return OFFSET_ERROR;
- return none ? OFFSET_NAIVE : OFFSET_AWARE;
+ int none;
+ PyObject *tzinfo;
+
+ assert(tzinfoarg != NULL);
+ *offset = 0;
+ tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
+ if (tzinfo == Py_None)
+ return OFFSET_NAIVE;
+ if (tzinfo == NULL) {
+ /* note that a datetime passes the PyDate_Check test */
+ return (PyTime_Check(op) || PyDate_Check(op)) ?
+ OFFSET_NAIVE : OFFSET_UNKNOWN;
+ }
+ *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
+ if (*offset == -1 && PyErr_Occurred())
+ return OFFSET_ERROR;
+ return none ? OFFSET_NAIVE : OFFSET_AWARE;
}
/* Classify two objects as to whether they're naive or offset-aware.
@@ -1017,23 +1017,23 @@ classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
*/
static int
classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
- PyObject *tzinfoarg1,
- PyObject *o2, int *offset2, naivety *n2,
- PyObject *tzinfoarg2)
-{
- if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
- *offset1 = *offset2 = 0;
- *n1 = *n2 = OFFSET_NAIVE;
- }
- else {
- *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
- if (*n1 == OFFSET_ERROR)
- return -1;
- *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
- if (*n2 == OFFSET_ERROR)
- return -1;
- }
- return 0;
+ PyObject *tzinfoarg1,
+ PyObject *o2, int *offset2, naivety *n2,
+ PyObject *tzinfoarg2)
+{
+ if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
+ *offset1 = *offset2 = 0;
+ *n1 = *n2 = OFFSET_NAIVE;
+ }
+ else {
+ *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
+ if (*n1 == OFFSET_ERROR)
+ return -1;
+ *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
+ if (*n2 == OFFSET_ERROR)
+ return -1;
+ }
+ return 0;
}
/* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
@@ -1044,30 +1044,30 @@ classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
static PyObject *
append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
{
- PyObject *temp;
+ PyObject *temp;
- assert(PyString_Check(repr));
- assert(tzinfo);
- if (tzinfo == Py_None)
- return repr;
- /* Get rid of the trailing ')'. */
- assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
- temp = PyString_FromStringAndSize(PyString_AsString(repr),
- PyString_Size(repr) - 1);
- Py_DECREF(repr);
- if (temp == NULL)
- return NULL;
- repr = temp;
+ assert(PyString_Check(repr));
+ assert(tzinfo);
+ if (tzinfo == Py_None)
+ return repr;
+ /* Get rid of the trailing ')'. */
+ assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
+ temp = PyString_FromStringAndSize(PyString_AsString(repr),
+ PyString_Size(repr) - 1);
+ Py_DECREF(repr);
+ if (temp == NULL)
+ return NULL;
+ repr = temp;
- /* Append ", tzinfo=". */
- PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
+ /* Append ", tzinfo=". */
+ PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
- /* Append repr(tzinfo). */
- PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
+ /* Append repr(tzinfo). */
+ PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
- /* Add a closing paren. */
- PyString_ConcatAndDel(&repr, PyString_FromString(")"));
- return repr;
+ /* Add a closing paren. */
+ PyString_ConcatAndDel(&repr, PyString_FromString(")"));
+ return repr;
}
/* ---------------------------------------------------------------------------
@@ -1077,22 +1077,22 @@ append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
static PyObject *
format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
{
- static const char *DayNames[] = {
- "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
- };
- static const char *MonthNames[] = {
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
- };
+ static const char *DayNames[] = {
+ "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
+ };
+ static const char *MonthNames[] = {
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
+ };
- char buffer[128];
- int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
+ char buffer[128];
+ int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
- PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
- DayNames[wday], MonthNames[GET_MONTH(date) - 1],
- GET_DAY(date), hours, minutes, seconds,
- GET_YEAR(date));
- return PyString_FromString(buffer);
+ PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
+ DayNames[wday], MonthNames[GET_MONTH(date) - 1],
+ GET_DAY(date), hours, minutes, seconds,
+ GET_YEAR(date));
+ return PyString_FromString(buffer);
}
/* Add an hours & minutes UTC offset string to buf. buf has no more than
@@ -1107,45 +1107,45 @@ format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
*/
static int
format_utcoffset(char *buf, size_t buflen, const char *sep,
- PyObject *tzinfo, PyObject *tzinfoarg)
-{
- int offset;
- int hours;
- int minutes;
- char sign;
- int none;
-
- assert(buflen >= 1);
-
- offset = call_utcoffset(tzinfo, tzinfoarg, &none);
- if (offset == -1 && PyErr_Occurred())
- return -1;
- if (none) {
- *buf = '\0';
- return 0;
- }
- sign = '+';
- if (offset < 0) {
- sign = '-';
- offset = - offset;
- }
- hours = divmod(offset, 60, &minutes);
- PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
- return 0;
+ PyObject *tzinfo, PyObject *tzinfoarg)
+{
+ int offset;
+ int hours;
+ int minutes;
+ char sign;
+ int none;
+
+ assert(buflen >= 1);
+
+ offset = call_utcoffset(tzinfo, tzinfoarg, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return -1;
+ if (none) {
+ *buf = '\0';
+ return 0;
+ }
+ sign = '+';
+ if (offset < 0) {
+ sign = '-';
+ offset = - offset;
+ }
+ hours = divmod(offset, 60, &minutes);
+ PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
+ return 0;
}
static PyObject *
make_freplacement(PyObject *object)
{
- char freplacement[64];
- if (PyTime_Check(object))
- sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
- else if (PyDateTime_Check(object))
- sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
- else
- sprintf(freplacement, "%06d", 0);
+ char freplacement[64];
+ if (PyTime_Check(object))
+ sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
+ else if (PyDateTime_Check(object))
+ sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
+ else
+ sprintf(freplacement, "%06d", 0);
- return PyString_FromStringAndSize(freplacement, strlen(freplacement));
+ return PyString_FromStringAndSize(freplacement, strlen(freplacement));
}
/* I sure don't want to reproduce the strftime code from the time module,
@@ -1157,231 +1157,231 @@ make_freplacement(PyObject *object)
*/
static PyObject *
wrap_strftime(PyObject *object, const char *format, size_t format_len,
- PyObject *timetuple, PyObject *tzinfoarg)
-{
- PyObject *result = NULL; /* guilty until proved innocent */
-
- PyObject *zreplacement = NULL; /* py string, replacement for %z */
- PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
- PyObject *freplacement = NULL; /* py string, replacement for %f */
-
- const char *pin; /* pointer to next char in input format */
- char ch; /* next char in input format */
-
- PyObject *newfmt = NULL; /* py string, the output format */
- char *pnew; /* pointer to available byte in output format */
- size_t totalnew; /* number bytes total in output format buffer,
- exclusive of trailing \0 */
- size_t usednew; /* number bytes used so far in output format buffer */
-
- const char *ptoappend; /* ptr to string to append to output buffer */
- size_t ntoappend; /* # of bytes to append to output buffer */
-
- assert(object && format && timetuple);
-
- /* Give up if the year is before 1900.
- * Python strftime() plays games with the year, and different
- * games depending on whether envar PYTHON2K is set. This makes
- * years before 1900 a nightmare, even if the platform strftime
- * supports them (and not all do).
- * We could get a lot farther here by avoiding Python's strftime
- * wrapper and calling the C strftime() directly, but that isn't
- * an option in the Python implementation of this module.
- */
- {
- long year;
- PyObject *pyyear = PySequence_GetItem(timetuple, 0);
- if (pyyear == NULL) return NULL;
- assert(PyInt_Check(pyyear));
- year = PyInt_AsLong(pyyear);
- Py_DECREF(pyyear);
- if (year < 1900) {
- PyErr_Format(PyExc_ValueError, "year=%ld is before "
- "1900; the datetime strftime() "
- "methods require year >= 1900",
- year);
- return NULL;
- }
- }
-
- /* Scan the input format, looking for %z/%Z/%f escapes, building
- * a new format. Since computing the replacements for those codes
- * is expensive, don't unless they're actually used.
- */
- if (format_len > INT_MAX - 1) {
- PyErr_NoMemory();
- goto Done;
- }
-
- totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
- newfmt = PyString_FromStringAndSize(NULL, totalnew);
- if (newfmt == NULL) goto Done;
- pnew = PyString_AsString(newfmt);
- usednew = 0;
-
- pin = format;
- while ((ch = *pin++) != '\0') {
- if (ch != '%') {
- ptoappend = pin - 1;
- ntoappend = 1;
- }
- else if ((ch = *pin++) == '\0') {
- /* There's a lone trailing %; doesn't make sense. */
- PyErr_SetString(PyExc_ValueError, "strftime format "
- "ends with raw %");
- goto Done;
- }
- /* A % has been seen and ch is the character after it. */
- else if (ch == 'z') {
- if (zreplacement == NULL) {
- /* format utcoffset */
- char buf[100];
- PyObject *tzinfo = get_tzinfo_member(object);
- zreplacement = PyString_FromString("");
- if (zreplacement == NULL) goto Done;
- if (tzinfo != Py_None && tzinfo != NULL) {
- assert(tzinfoarg != NULL);
- if (format_utcoffset(buf,
- sizeof(buf),
- "",
- tzinfo,
- tzinfoarg) < 0)
- goto Done;
- Py_DECREF(zreplacement);
- zreplacement = PyString_FromString(buf);
- if (zreplacement == NULL) goto Done;
- }
- }
- assert(zreplacement != NULL);
- ptoappend = PyString_AS_STRING(zreplacement);
- ntoappend = PyString_GET_SIZE(zreplacement);
- }
- else if (ch == 'Z') {
- /* format tzname */
- if (Zreplacement == NULL) {
- PyObject *tzinfo = get_tzinfo_member(object);
- Zreplacement = PyString_FromString("");
- if (Zreplacement == NULL) goto Done;
- if (tzinfo != Py_None && tzinfo != NULL) {
- PyObject *temp;
- assert(tzinfoarg != NULL);
- temp = call_tzname(tzinfo, tzinfoarg);
- if (temp == NULL) goto Done;
- if (temp != Py_None) {
- assert(PyString_Check(temp));
- /* Since the tzname is getting
- * stuffed into the format, we
- * have to double any % signs
- * so that strftime doesn't
- * treat them as format codes.
- */
- Py_DECREF(Zreplacement);
- Zreplacement = PyObject_CallMethod(
- temp, "replace",
- "ss", "%", "%%");
- Py_DECREF(temp);
- if (Zreplacement == NULL)
- goto Done;
- if (!PyString_Check(Zreplacement)) {
- PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
- goto Done;
- }
- }
- else
- Py_DECREF(temp);
- }
- }
- assert(Zreplacement != NULL);
- ptoappend = PyString_AS_STRING(Zreplacement);
- ntoappend = PyString_GET_SIZE(Zreplacement);
- }
- else if (ch == 'f') {
- /* format microseconds */
- if (freplacement == NULL) {
- freplacement = make_freplacement(object);
- if (freplacement == NULL)
- goto Done;
- }
- assert(freplacement != NULL);
- assert(PyString_Check(freplacement));
- ptoappend = PyString_AS_STRING(freplacement);
- ntoappend = PyString_GET_SIZE(freplacement);
- }
- else {
- /* percent followed by neither z nor Z */
- ptoappend = pin - 2;
- ntoappend = 2;
- }
-
- /* Append the ntoappend chars starting at ptoappend to
- * the new format.
- */
- assert(ptoappend != NULL);
- assert(ntoappend >= 0);
- if (ntoappend == 0)
- continue;
- while (usednew + ntoappend > totalnew) {
- size_t bigger = totalnew << 1;
- if ((bigger >> 1) != totalnew) { /* overflow */
- PyErr_NoMemory();
- goto Done;
- }
- if (_PyString_Resize(&newfmt, bigger) < 0)
- goto Done;
- totalnew = bigger;
- pnew = PyString_AsString(newfmt) + usednew;
- }
- memcpy(pnew, ptoappend, ntoappend);
- pnew += ntoappend;
- usednew += ntoappend;
- assert(usednew <= totalnew);
- } /* end while() */
-
- if (_PyString_Resize(&newfmt, usednew) < 0)
- goto Done;
- {
- PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time == NULL)
- goto Done;
- result = PyObject_CallMethod(time, "strftime", "OO",
- newfmt, timetuple);
- Py_DECREF(time);
- }
+ PyObject *timetuple, PyObject *tzinfoarg)
+{
+ PyObject *result = NULL; /* guilty until proved innocent */
+
+ PyObject *zreplacement = NULL; /* py string, replacement for %z */
+ PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
+ PyObject *freplacement = NULL; /* py string, replacement for %f */
+
+ const char *pin; /* pointer to next char in input format */
+ char ch; /* next char in input format */
+
+ PyObject *newfmt = NULL; /* py string, the output format */
+ char *pnew; /* pointer to available byte in output format */
+ size_t totalnew; /* number bytes total in output format buffer,
+ exclusive of trailing \0 */
+ size_t usednew; /* number bytes used so far in output format buffer */
+
+ const char *ptoappend; /* ptr to string to append to output buffer */
+ size_t ntoappend; /* # of bytes to append to output buffer */
+
+ assert(object && format && timetuple);
+
+ /* Give up if the year is before 1900.
+ * Python strftime() plays games with the year, and different
+ * games depending on whether envar PYTHON2K is set. This makes
+ * years before 1900 a nightmare, even if the platform strftime
+ * supports them (and not all do).
+ * We could get a lot farther here by avoiding Python's strftime
+ * wrapper and calling the C strftime() directly, but that isn't
+ * an option in the Python implementation of this module.
+ */
+ {
+ long year;
+ PyObject *pyyear = PySequence_GetItem(timetuple, 0);
+ if (pyyear == NULL) return NULL;
+ assert(PyInt_Check(pyyear));
+ year = PyInt_AsLong(pyyear);
+ Py_DECREF(pyyear);
+ if (year < 1900) {
+ PyErr_Format(PyExc_ValueError, "year=%ld is before "
+ "1900; the datetime strftime() "
+ "methods require year >= 1900",
+ year);
+ return NULL;
+ }
+ }
+
+ /* Scan the input format, looking for %z/%Z/%f escapes, building
+ * a new format. Since computing the replacements for those codes
+ * is expensive, don't unless they're actually used.
+ */
+ if (format_len > INT_MAX - 1) {
+ PyErr_NoMemory();
+ goto Done;
+ }
+
+ totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
+ newfmt = PyString_FromStringAndSize(NULL, totalnew);
+ if (newfmt == NULL) goto Done;
+ pnew = PyString_AsString(newfmt);
+ usednew = 0;
+
+ pin = format;
+ while ((ch = *pin++) != '\0') {
+ if (ch != '%') {
+ ptoappend = pin - 1;
+ ntoappend = 1;
+ }
+ else if ((ch = *pin++) == '\0') {
+ /* There's a lone trailing %; doesn't make sense. */
+ PyErr_SetString(PyExc_ValueError, "strftime format "
+ "ends with raw %");
+ goto Done;
+ }
+ /* A % has been seen and ch is the character after it. */
+ else if (ch == 'z') {
+ if (zreplacement == NULL) {
+ /* format utcoffset */
+ char buf[100];
+ PyObject *tzinfo = get_tzinfo_member(object);
+ zreplacement = PyString_FromString("");
+ if (zreplacement == NULL) goto Done;
+ if (tzinfo != Py_None && tzinfo != NULL) {
+ assert(tzinfoarg != NULL);
+ if (format_utcoffset(buf,
+ sizeof(buf),
+ "",
+ tzinfo,
+ tzinfoarg) < 0)
+ goto Done;
+ Py_DECREF(zreplacement);
+ zreplacement = PyString_FromString(buf);
+ if (zreplacement == NULL) goto Done;
+ }
+ }
+ assert(zreplacement != NULL);
+ ptoappend = PyString_AS_STRING(zreplacement);
+ ntoappend = PyString_GET_SIZE(zreplacement);
+ }
+ else if (ch == 'Z') {
+ /* format tzname */
+ if (Zreplacement == NULL) {
+ PyObject *tzinfo = get_tzinfo_member(object);
+ Zreplacement = PyString_FromString("");
+ if (Zreplacement == NULL) goto Done;
+ if (tzinfo != Py_None && tzinfo != NULL) {
+ PyObject *temp;
+ assert(tzinfoarg != NULL);
+ temp = call_tzname(tzinfo, tzinfoarg);
+ if (temp == NULL) goto Done;
+ if (temp != Py_None) {
+ assert(PyString_Check(temp));
+ /* Since the tzname is getting
+ * stuffed into the format, we
+ * have to double any % signs
+ * so that strftime doesn't
+ * treat them as format codes.
+ */
+ Py_DECREF(Zreplacement);
+ Zreplacement = PyObject_CallMethod(
+ temp, "replace",
+ "ss", "%", "%%");
+ Py_DECREF(temp);
+ if (Zreplacement == NULL)
+ goto Done;
+ if (!PyString_Check(Zreplacement)) {
+ PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
+ goto Done;
+ }
+ }
+ else
+ Py_DECREF(temp);
+ }
+ }
+ assert(Zreplacement != NULL);
+ ptoappend = PyString_AS_STRING(Zreplacement);
+ ntoappend = PyString_GET_SIZE(Zreplacement);
+ }
+ else if (ch == 'f') {
+ /* format microseconds */
+ if (freplacement == NULL) {
+ freplacement = make_freplacement(object);
+ if (freplacement == NULL)
+ goto Done;
+ }
+ assert(freplacement != NULL);
+ assert(PyString_Check(freplacement));
+ ptoappend = PyString_AS_STRING(freplacement);
+ ntoappend = PyString_GET_SIZE(freplacement);
+ }
+ else {
+ /* percent followed by neither z nor Z */
+ ptoappend = pin - 2;
+ ntoappend = 2;
+ }
+
+ /* Append the ntoappend chars starting at ptoappend to
+ * the new format.
+ */
+ assert(ptoappend != NULL);
+ assert(ntoappend >= 0);
+ if (ntoappend == 0)
+ continue;
+ while (usednew + ntoappend > totalnew) {
+ size_t bigger = totalnew << 1;
+ if ((bigger >> 1) != totalnew) { /* overflow */
+ PyErr_NoMemory();
+ goto Done;
+ }
+ if (_PyString_Resize(&newfmt, bigger) < 0)
+ goto Done;
+ totalnew = bigger;
+ pnew = PyString_AsString(newfmt) + usednew;
+ }
+ memcpy(pnew, ptoappend, ntoappend);
+ pnew += ntoappend;
+ usednew += ntoappend;
+ assert(usednew <= totalnew);
+ } /* end while() */
+
+ if (_PyString_Resize(&newfmt, usednew) < 0)
+ goto Done;
+ {
+ PyObject *time = PyImport_ImportModuleNoBlock("time");
+ if (time == NULL)
+ goto Done;
+ result = PyObject_CallMethod(time, "strftime", "OO",
+ newfmt, timetuple);
+ Py_DECREF(time);
+ }
Done:
- Py_XDECREF(freplacement);
- Py_XDECREF(zreplacement);
- Py_XDECREF(Zreplacement);
- Py_XDECREF(newfmt);
- return result;
+ Py_XDECREF(freplacement);
+ Py_XDECREF(zreplacement);
+ Py_XDECREF(Zreplacement);
+ Py_XDECREF(newfmt);
+ return result;
}
static char *
isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
{
- int x;
- x = PyOS_snprintf(buffer, bufflen,
- "%04d-%02d-%02d",
- GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
- assert(bufflen >= x);
- return buffer + x;
+ int x;
+ x = PyOS_snprintf(buffer, bufflen,
+ "%04d-%02d-%02d",
+ GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
+ assert(bufflen >= x);
+ return buffer + x;
}
static char *
isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
{
- int x;
- int us = DATE_GET_MICROSECOND(dt);
+ int x;
+ int us = DATE_GET_MICROSECOND(dt);
- x = PyOS_snprintf(buffer, bufflen,
- "%02d:%02d:%02d",
- DATE_GET_HOUR(dt),
- DATE_GET_MINUTE(dt),
- DATE_GET_SECOND(dt));
- assert(bufflen >= x);
- if (us)
- x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
- assert(bufflen >= x);
- return buffer + x;
+ x = PyOS_snprintf(buffer, bufflen,
+ "%02d:%02d:%02d",
+ DATE_GET_HOUR(dt),
+ DATE_GET_MINUTE(dt),
+ DATE_GET_SECOND(dt));
+ assert(bufflen >= x);
+ if (us)
+ x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
+ assert(bufflen >= x);
+ return buffer + x;
}
/* ---------------------------------------------------------------------------
@@ -1393,14 +1393,14 @@ isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
static PyObject *
time_time(void)
{
- PyObject *result = NULL;
- PyObject *time = PyImport_ImportModuleNoBlock("time");
+ PyObject *result = NULL;
+ PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time != NULL) {
- result = PyObject_CallMethod(time, "time", "()");
- Py_DECREF(time);
- }
- return result;
+ if (time != NULL) {
+ result = PyObject_CallMethod(time, "time", "()");
+ Py_DECREF(time);
+ }
+ return result;
}
/* Build a time.struct_time. The weekday and day number are automatically
@@ -1409,21 +1409,21 @@ time_time(void)
static PyObject *
build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
{
- PyObject *time;
- PyObject *result = NULL;
+ PyObject *time;
+ PyObject *result = NULL;
- time = PyImport_ImportModuleNoBlock("time");
- if (time != NULL) {
- result = PyObject_CallMethod(time, "struct_time",
- "((iiiiiiiii))",
- y, m, d,
- hh, mm, ss,
- weekday(y, m, d),
- days_before_month(y, m) + d,
- dstflag);
- Py_DECREF(time);
- }
- return result;
+ time = PyImport_ImportModuleNoBlock("time");
+ if (time != NULL) {
+ result = PyObject_CallMethod(time, "struct_time",
+ "((iiiiiiiii))",
+ y, m, d,
+ hh, mm, ss,
+ weekday(y, m, d),
+ days_before_month(y, m) + d,
+ dstflag);
+ Py_DECREF(time);
+ }
+ return result;
}
/* ---------------------------------------------------------------------------
@@ -1437,33 +1437,33 @@ build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
static PyObject *
diff_to_bool(int diff, int op)
{
- PyObject *result;
- int istrue;
-
- switch (op) {
- case Py_EQ: istrue = diff == 0; break;
- case Py_NE: istrue = diff != 0; break;
- case Py_LE: istrue = diff <= 0; break;
- case Py_GE: istrue = diff >= 0; break;
- case Py_LT: istrue = diff < 0; break;
- case Py_GT: istrue = diff > 0; break;
- default:
- assert(! "op unknown");
- istrue = 0; /* To shut up compiler */
- }
- result = istrue ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
+ PyObject *result;
+ int istrue;
+
+ switch (op) {
+ case Py_EQ: istrue = diff == 0; break;
+ case Py_NE: istrue = diff != 0; break;
+ case Py_LE: istrue = diff <= 0; break;
+ case Py_GE: istrue = diff >= 0; break;
+ case Py_LT: istrue = diff < 0; break;
+ case Py_GT: istrue = diff > 0; break;
+ default:
+ assert(! "op unknown");
+ istrue = 0; /* To shut up compiler */
+ }
+ result = istrue ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
}
/* Raises a "can't compare" TypeError and returns NULL. */
static PyObject *
cmperror(PyObject *a, PyObject *b)
{
- PyErr_Format(PyExc_TypeError,
- "can't compare %s to %s",
- Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "can't compare %s to %s",
+ Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
+ return NULL;
}
/* ---------------------------------------------------------------------------
@@ -1471,13 +1471,13 @@ cmperror(PyObject *a, PyObject *b)
*/
/* Conversion factors. */
-static PyObject *us_per_us = NULL; /* 1 */
-static PyObject *us_per_ms = NULL; /* 1000 */
-static PyObject *us_per_second = NULL; /* 1000000 */
-static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
-static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
-static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
-static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
+static PyObject *us_per_us = NULL; /* 1 */
+static PyObject *us_per_ms = NULL; /* 1000 */
+static PyObject *us_per_second = NULL; /* 1000000 */
+static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
+static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
+static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
+static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
/* ---------------------------------------------------------------------------
@@ -1489,7 +1489,7 @@ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
*/
/* Convert a timedelta to a number of us,
- * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
+ * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
* as a Python int or long.
* Doing mixed-radix arithmetic by hand instead is excruciating in C,
* due to ubiquitous overflow possibilities.
@@ -1497,49 +1497,49 @@ static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
static PyObject *
delta_to_microseconds(PyDateTime_Delta *self)
{
- PyObject *x1 = NULL;
- PyObject *x2 = NULL;
- PyObject *x3 = NULL;
- PyObject *result = NULL;
-
- x1 = PyInt_FromLong(GET_TD_DAYS(self));
- if (x1 == NULL)
- goto Done;
- x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
- if (x2 == NULL)
- goto Done;
- Py_DECREF(x1);
- x1 = NULL;
-
- /* x2 has days in seconds */
- x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
- if (x1 == NULL)
- goto Done;
- x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
- if (x3 == NULL)
- goto Done;
- Py_DECREF(x1);
- Py_DECREF(x2);
- x2 = NULL;
-
- /* x3 has days+seconds in seconds */
- x1 = PyNumber_Multiply(x3, us_per_second); /* us */
- if (x1 == NULL)
- goto Done;
- Py_DECREF(x3);
- x3 = NULL;
-
- /* x1 has days+seconds in us */
- x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
- if (x2 == NULL)
- goto Done;
- result = PyNumber_Add(x1, x2);
+ PyObject *x1 = NULL;
+ PyObject *x2 = NULL;
+ PyObject *x3 = NULL;
+ PyObject *result = NULL;
+
+ x1 = PyInt_FromLong(GET_TD_DAYS(self));
+ if (x1 == NULL)
+ goto Done;
+ x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
+ if (x2 == NULL)
+ goto Done;
+ Py_DECREF(x1);
+ x1 = NULL;
+
+ /* x2 has days in seconds */
+ x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
+ if (x1 == NULL)
+ goto Done;
+ x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
+ if (x3 == NULL)
+ goto Done;
+ Py_DECREF(x1);
+ Py_DECREF(x2);
+ x2 = NULL;
+
+ /* x3 has days+seconds in seconds */
+ x1 = PyNumber_Multiply(x3, us_per_second); /* us */
+ if (x1 == NULL)
+ goto Done;
+ Py_DECREF(x3);
+ x3 = NULL;
+
+ /* x1 has days+seconds in us */
+ x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
+ if (x2 == NULL)
+ goto Done;
+ result = PyNumber_Add(x1, x2);
Done:
- Py_XDECREF(x1);
- Py_XDECREF(x2);
- Py_XDECREF(x3);
- return result;
+ Py_XDECREF(x1);
+ Py_XDECREF(x2);
+ Py_XDECREF(x3);
+ return result;
}
/* Convert a number of us (as a Python int or long) to a timedelta.
@@ -1547,205 +1547,205 @@ Done:
static PyObject *
microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
{
- int us;
- int s;
- int d;
- long temp;
-
- PyObject *tuple = NULL;
- PyObject *num = NULL;
- PyObject *result = NULL;
-
- tuple = PyNumber_Divmod(pyus, us_per_second);
- if (tuple == NULL)
- goto Done;
-
- num = PyTuple_GetItem(tuple, 1); /* us */
- if (num == NULL)
- goto Done;
- temp = PyLong_AsLong(num);
- num = NULL;
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- assert(0 <= temp && temp < 1000000);
- us = (int)temp;
- if (us < 0) {
- /* The divisor was positive, so this must be an error. */
- assert(PyErr_Occurred());
- goto Done;
- }
-
- num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
- if (num == NULL)
- goto Done;
- Py_INCREF(num);
- Py_DECREF(tuple);
-
- tuple = PyNumber_Divmod(num, seconds_per_day);
- if (tuple == NULL)
- goto Done;
- Py_DECREF(num);
-
- num = PyTuple_GetItem(tuple, 1); /* seconds */
- if (num == NULL)
- goto Done;
- temp = PyLong_AsLong(num);
- num = NULL;
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- assert(0 <= temp && temp < 24*3600);
- s = (int)temp;
-
- if (s < 0) {
- /* The divisor was positive, so this must be an error. */
- assert(PyErr_Occurred());
- goto Done;
- }
-
- num = PyTuple_GetItem(tuple, 0); /* leftover days */
- if (num == NULL)
- goto Done;
- Py_INCREF(num);
- temp = PyLong_AsLong(num);
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- d = (int)temp;
- if ((long)d != temp) {
- PyErr_SetString(PyExc_OverflowError, "normalized days too "
- "large to fit in a C int");
- goto Done;
- }
- result = new_delta_ex(d, s, us, 0, type);
+ int us;
+ int s;
+ int d;
+ long temp;
+
+ PyObject *tuple = NULL;
+ PyObject *num = NULL;
+ PyObject *result = NULL;
+
+ tuple = PyNumber_Divmod(pyus, us_per_second);
+ if (tuple == NULL)
+ goto Done;
+
+ num = PyTuple_GetItem(tuple, 1); /* us */
+ if (num == NULL)
+ goto Done;
+ temp = PyLong_AsLong(num);
+ num = NULL;
+ if (temp == -1 && PyErr_Occurred())
+ goto Done;
+ assert(0 <= temp && temp < 1000000);
+ us = (int)temp;
+ if (us < 0) {
+ /* The divisor was positive, so this must be an error. */
+ assert(PyErr_Occurred());
+ goto Done;
+ }
+
+ num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
+ if (num == NULL)
+ goto Done;
+ Py_INCREF(num);
+ Py_DECREF(tuple);
+
+ tuple = PyNumber_Divmod(num, seconds_per_day);
+ if (tuple == NULL)
+ goto Done;
+ Py_DECREF(num);
+
+ num = PyTuple_GetItem(tuple, 1); /* seconds */
+ if (num == NULL)
+ goto Done;
+ temp = PyLong_AsLong(num);
+ num = NULL;
+ if (temp == -1 && PyErr_Occurred())
+ goto Done;
+ assert(0 <= temp && temp < 24*3600);
+ s = (int)temp;
+
+ if (s < 0) {
+ /* The divisor was positive, so this must be an error. */
+ assert(PyErr_Occurred());
+ goto Done;
+ }
+
+ num = PyTuple_GetItem(tuple, 0); /* leftover days */
+ if (num == NULL)
+ goto Done;
+ Py_INCREF(num);
+ temp = PyLong_AsLong(num);
+ if (temp == -1 && PyErr_Occurred())
+ goto Done;
+ d = (int)temp;
+ if ((long)d != temp) {
+ PyErr_SetString(PyExc_OverflowError, "normalized days too "
+ "large to fit in a C int");
+ goto Done;
+ }
+ result = new_delta_ex(d, s, us, 0, type);
Done:
- Py_XDECREF(tuple);
- Py_XDECREF(num);
- return result;
+ Py_XDECREF(tuple);
+ Py_XDECREF(num);
+ return result;
}
-#define microseconds_to_delta(pymicros) \
- microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
+#define microseconds_to_delta(pymicros) \
+ microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
static PyObject *
multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
{
- PyObject *pyus_in;
- PyObject *pyus_out;
- PyObject *result;
+ PyObject *pyus_in;
+ PyObject *pyus_out;
+ PyObject *result;
- pyus_in = delta_to_microseconds(delta);
- if (pyus_in == NULL)
- return NULL;
+ pyus_in = delta_to_microseconds(delta);
+ if (pyus_in == NULL)
+ return NULL;
- pyus_out = PyNumber_Multiply(pyus_in, intobj);
- Py_DECREF(pyus_in);
- if (pyus_out == NULL)
- return NULL;
+ pyus_out = PyNumber_Multiply(pyus_in, intobj);
+ Py_DECREF(pyus_in);
+ if (pyus_out == NULL)
+ return NULL;
- result = microseconds_to_delta(pyus_out);
- Py_DECREF(pyus_out);
- return result;
+ result = microseconds_to_delta(pyus_out);
+ Py_DECREF(pyus_out);
+ return result;
}
static PyObject *
divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
{
- PyObject *pyus_in;
- PyObject *pyus_out;
- PyObject *result;
+ PyObject *pyus_in;
+ PyObject *pyus_out;
+ PyObject *result;
- pyus_in = delta_to_microseconds(delta);
- if (pyus_in == NULL)
- return NULL;
+ pyus_in = delta_to_microseconds(delta);
+ if (pyus_in == NULL)
+ return NULL;
- pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
- Py_DECREF(pyus_in);
- if (pyus_out == NULL)
- return NULL;
+ pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
+ Py_DECREF(pyus_in);
+ if (pyus_out == NULL)
+ return NULL;
- result = microseconds_to_delta(pyus_out);
- Py_DECREF(pyus_out);
- return result;
+ result = microseconds_to_delta(pyus_out);
+ Py_DECREF(pyus_out);
+ return result;
}
static PyObject *
delta_add(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left) && PyDelta_Check(right)) {
- /* delta + delta */
- /* The C-level additions can't overflow because of the
- * invariant bounds.
- */
- int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
- int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
- int microseconds = GET_TD_MICROSECONDS(left) +
- GET_TD_MICROSECONDS(right);
- result = new_delta(days, seconds, microseconds, 1);
- }
+ if (PyDelta_Check(left) && PyDelta_Check(right)) {
+ /* delta + delta */
+ /* The C-level additions can't overflow because of the
+ * invariant bounds.
+ */
+ int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
+ int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
+ int microseconds = GET_TD_MICROSECONDS(left) +
+ GET_TD_MICROSECONDS(right);
+ result = new_delta(days, seconds, microseconds, 1);
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_negative(PyDateTime_Delta *self)
{
- return new_delta(-GET_TD_DAYS(self),
- -GET_TD_SECONDS(self),
- -GET_TD_MICROSECONDS(self),
- 1);
+ return new_delta(-GET_TD_DAYS(self),
+ -GET_TD_SECONDS(self),
+ -GET_TD_MICROSECONDS(self),
+ 1);
}
static PyObject *
delta_positive(PyDateTime_Delta *self)
{
- /* Could optimize this (by returning self) if this isn't a
- * subclass -- but who uses unary + ? Approximately nobody.
- */
- return new_delta(GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self),
- 0);
+ /* Could optimize this (by returning self) if this isn't a
+ * subclass -- but who uses unary + ? Approximately nobody.
+ */
+ return new_delta(GET_TD_DAYS(self),
+ GET_TD_SECONDS(self),
+ GET_TD_MICROSECONDS(self),
+ 0);
}
static PyObject *
delta_abs(PyDateTime_Delta *self)
{
- PyObject *result;
+ PyObject *result;
- assert(GET_TD_MICROSECONDS(self) >= 0);
- assert(GET_TD_SECONDS(self) >= 0);
+ assert(GET_TD_MICROSECONDS(self) >= 0);
+ assert(GET_TD_SECONDS(self) >= 0);
- if (GET_TD_DAYS(self) < 0)
- result = delta_negative(self);
- else
- result = delta_positive(self);
+ if (GET_TD_DAYS(self) < 0)
+ result = delta_negative(self);
+ else
+ result = delta_positive(self);
- return result;
+ return result;
}
static PyObject *
delta_subtract(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left) && PyDelta_Check(right)) {
- /* delta - delta */
- PyObject *minus_right = PyNumber_Negative(right);
- if (minus_right) {
- result = delta_add(left, minus_right);
- Py_DECREF(minus_right);
- }
- else
- result = NULL;
- }
+ if (PyDelta_Check(left) && PyDelta_Check(right)) {
+ /* delta - delta */
+ PyObject *minus_right = PyNumber_Negative(right);
+ if (minus_right) {
+ result = delta_add(left, minus_right);
+ Py_DECREF(minus_right);
+ }
+ else
+ result = NULL;
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
/* This is more natural as a tp_compare, but doesn't work then: for whatever
@@ -1755,24 +1755,24 @@ delta_subtract(PyObject *left, PyObject *right)
static PyObject *
delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
{
- int diff = 42; /* nonsense */
+ int diff = 42; /* nonsense */
- if (PyDelta_Check(other)) {
- diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
- if (diff == 0) {
- diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
- if (diff == 0)
- diff = GET_TD_MICROSECONDS(self) -
- GET_TD_MICROSECONDS(other);
- }
- }
- else if (op == Py_EQ || op == Py_NE)
- diff = 1; /* any non-zero value will do */
+ if (PyDelta_Check(other)) {
+ diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
+ if (diff == 0) {
+ diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
+ if (diff == 0)
+ diff = GET_TD_MICROSECONDS(self) -
+ GET_TD_MICROSECONDS(other);
+ }
+ }
+ else if (op == Py_EQ || op == Py_NE)
+ diff = 1; /* any non-zero value will do */
- else /* stop this from falling back to address comparison */
- return cmperror((PyObject *)self, other);
+ else /* stop this from falling back to address comparison */
+ return cmperror((PyObject *)self, other);
- return diff_to_bool(diff, op);
+ return diff_to_bool(diff, op);
}
static PyObject *delta_getstate(PyDateTime_Delta *self);
@@ -1780,52 +1780,52 @@ static PyObject *delta_getstate(PyDateTime_Delta *self);
static long
delta_hash(PyDateTime_Delta *self)
{
- if (self->hashcode == -1) {
- PyObject *temp = delta_getstate(self);
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ PyObject *temp = delta_getstate(self);
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
delta_multiply(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left)) {
- /* delta * ??? */
- if (PyInt_Check(right) || PyLong_Check(right))
- result = multiply_int_timedelta(right,
- (PyDateTime_Delta *) left);
- }
- else if (PyInt_Check(left) || PyLong_Check(left))
- result = multiply_int_timedelta(left,
- (PyDateTime_Delta *) right);
+ if (PyDelta_Check(left)) {
+ /* delta * ??? */
+ if (PyInt_Check(right) || PyLong_Check(right))
+ result = multiply_int_timedelta(right,
+ (PyDateTime_Delta *) left);
+ }
+ else if (PyInt_Check(left) || PyLong_Check(left))
+ result = multiply_int_timedelta(left,
+ (PyDateTime_Delta *) right);
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
static PyObject *
delta_divide(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
+ PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left)) {
- /* delta * ??? */
- if (PyInt_Check(right) || PyLong_Check(right))
- result = divide_timedelta_int(
- (PyDateTime_Delta *)left,
- right);
- }
+ if (PyDelta_Check(left)) {
+ /* delta * ??? */
+ if (PyInt_Check(right) || PyLong_Check(right))
+ result = divide_timedelta_int(
+ (PyDateTime_Delta *)left,
+ right);
+ }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
/* Fold in the value of the tag ("seconds", "weeks", etc) component of a
@@ -1841,169 +1841,169 @@ static PyObject *
accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
double *leftover)
{
- PyObject *prod;
- PyObject *sum;
-
- assert(num != NULL);
-
- if (PyInt_Check(num) || PyLong_Check(num)) {
- prod = PyNumber_Multiply(num, factor);
- if (prod == NULL)
- return NULL;
- sum = PyNumber_Add(sofar, prod);
- Py_DECREF(prod);
- return sum;
- }
-
- if (PyFloat_Check(num)) {
- double dnum;
- double fracpart;
- double intpart;
- PyObject *x;
- PyObject *y;
-
- /* The Plan: decompose num into an integer part and a
- * fractional part, num = intpart + fracpart.
- * Then num * factor ==
- * intpart * factor + fracpart * factor
- * and the LHS can be computed exactly in long arithmetic.
- * The RHS is again broken into an int part and frac part.
- * and the frac part is added into *leftover.
- */
- dnum = PyFloat_AsDouble(num);
- if (dnum == -1.0 && PyErr_Occurred())
- return NULL;
- fracpart = modf(dnum, &intpart);
- x = PyLong_FromDouble(intpart);
- if (x == NULL)
- return NULL;
-
- prod = PyNumber_Multiply(x, factor);
- Py_DECREF(x);
- if (prod == NULL)
- return NULL;
-
- sum = PyNumber_Add(sofar, prod);
- Py_DECREF(prod);
- if (sum == NULL)
- return NULL;
-
- if (fracpart == 0.0)
- return sum;
- /* So far we've lost no information. Dealing with the
- * fractional part requires float arithmetic, and may
- * lose a little info.
- */
- assert(PyInt_Check(factor) || PyLong_Check(factor));
- if (PyInt_Check(factor))
- dnum = (double)PyInt_AsLong(factor);
- else
- dnum = PyLong_AsDouble(factor);
-
- dnum *= fracpart;
- fracpart = modf(dnum, &intpart);
- x = PyLong_FromDouble(intpart);
- if (x == NULL) {
- Py_DECREF(sum);
- return NULL;
- }
-
- y = PyNumber_Add(sum, x);
- Py_DECREF(sum);
- Py_DECREF(x);
- *leftover += fracpart;
- return y;
- }
-
- PyErr_Format(PyExc_TypeError,
- "unsupported type for timedelta %s component: %s",
- tag, Py_TYPE(num)->tp_name);
- return NULL;
+ PyObject *prod;
+ PyObject *sum;
+
+ assert(num != NULL);
+
+ if (PyInt_Check(num) || PyLong_Check(num)) {
+ prod = PyNumber_Multiply(num, factor);
+ if (prod == NULL)
+ return NULL;
+ sum = PyNumber_Add(sofar, prod);
+ Py_DECREF(prod);
+ return sum;
+ }
+
+ if (PyFloat_Check(num)) {
+ double dnum;
+ double fracpart;
+ double intpart;
+ PyObject *x;
+ PyObject *y;
+
+ /* The Plan: decompose num into an integer part and a
+ * fractional part, num = intpart + fracpart.
+ * Then num * factor ==
+ * intpart * factor + fracpart * factor
+ * and the LHS can be computed exactly in long arithmetic.
+ * The RHS is again broken into an int part and frac part.
+ * and the frac part is added into *leftover.
+ */
+ dnum = PyFloat_AsDouble(num);
+ if (dnum == -1.0 && PyErr_Occurred())
+ return NULL;
+ fracpart = modf(dnum, &intpart);
+ x = PyLong_FromDouble(intpart);
+ if (x == NULL)
+ return NULL;
+
+ prod = PyNumber_Multiply(x, factor);
+ Py_DECREF(x);
+ if (prod == NULL)
+ return NULL;
+
+ sum = PyNumber_Add(sofar, prod);
+ Py_DECREF(prod);
+ if (sum == NULL)
+ return NULL;
+
+ if (fracpart == 0.0)
+ return sum;
+ /* So far we've lost no information. Dealing with the
+ * fractional part requires float arithmetic, and may
+ * lose a little info.
+ */
+ assert(PyInt_Check(factor) || PyLong_Check(factor));
+ if (PyInt_Check(factor))
+ dnum = (double)PyInt_AsLong(factor);
+ else
+ dnum = PyLong_AsDouble(factor);
+
+ dnum *= fracpart;
+ fracpart = modf(dnum, &intpart);
+ x = PyLong_FromDouble(intpart);
+ if (x == NULL) {
+ Py_DECREF(sum);
+ return NULL;
+ }
+
+ y = PyNumber_Add(sum, x);
+ Py_DECREF(sum);
+ Py_DECREF(x);
+ *leftover += fracpart;
+ return y;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "unsupported type for timedelta %s component: %s",
+ tag, Py_TYPE(num)->tp_name);
+ return NULL;
}
static PyObject *
delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
-
- /* Argument objects. */
- PyObject *day = NULL;
- PyObject *second = NULL;
- PyObject *us = NULL;
- PyObject *ms = NULL;
- PyObject *minute = NULL;
- PyObject *hour = NULL;
- PyObject *week = NULL;
-
- PyObject *x = NULL; /* running sum of microseconds */
- PyObject *y = NULL; /* temp sum of microseconds */
- double leftover_us = 0.0;
-
- static char *keywords[] = {
- "days", "seconds", "microseconds", "milliseconds",
- "minutes", "hours", "weeks", NULL
- };
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
- keywords,
- &day, &second, &us,
- &ms, &minute, &hour, &week) == 0)
- goto Done;
-
- x = PyInt_FromLong(0);
- if (x == NULL)
- goto Done;
-
-#define CLEANUP \
- Py_DECREF(x); \
- x = y; \
- if (x == NULL) \
- goto Done
-
- if (us) {
- y = accum("microseconds", x, us, us_per_us, &leftover_us);
- CLEANUP;
- }
- if (ms) {
- y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
- CLEANUP;
- }
- if (second) {
- y = accum("seconds", x, second, us_per_second, &leftover_us);
- CLEANUP;
- }
- if (minute) {
- y = accum("minutes", x, minute, us_per_minute, &leftover_us);
- CLEANUP;
- }
- if (hour) {
- y = accum("hours", x, hour, us_per_hour, &leftover_us);
- CLEANUP;
- }
- if (day) {
- y = accum("days", x, day, us_per_day, &leftover_us);
- CLEANUP;
- }
- if (week) {
- y = accum("weeks", x, week, us_per_week, &leftover_us);
- CLEANUP;
- }
- if (leftover_us) {
- /* Round to nearest whole # of us, and add into x. */
- PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
- if (temp == NULL) {
- Py_DECREF(x);
- goto Done;
- }
- y = PyNumber_Add(x, temp);
- Py_DECREF(temp);
- CLEANUP;
- }
-
- self = microseconds_to_delta_ex(x, type);
- Py_DECREF(x);
+ PyObject *self = NULL;
+
+ /* Argument objects. */
+ PyObject *day = NULL;
+ PyObject *second = NULL;
+ PyObject *us = NULL;
+ PyObject *ms = NULL;
+ PyObject *minute = NULL;
+ PyObject *hour = NULL;
+ PyObject *week = NULL;
+
+ PyObject *x = NULL; /* running sum of microseconds */
+ PyObject *y = NULL; /* temp sum of microseconds */
+ double leftover_us = 0.0;
+
+ static char *keywords[] = {
+ "days", "seconds", "microseconds", "milliseconds",
+ "minutes", "hours", "weeks", NULL
+ };
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
+ keywords,
+ &day, &second, &us,
+ &ms, &minute, &hour, &week) == 0)
+ goto Done;
+
+ x = PyInt_FromLong(0);
+ if (x == NULL)
+ goto Done;
+
+#define CLEANUP \
+ Py_DECREF(x); \
+ x = y; \
+ if (x == NULL) \
+ goto Done
+
+ if (us) {
+ y = accum("microseconds", x, us, us_per_us, &leftover_us);
+ CLEANUP;
+ }
+ if (ms) {
+ y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
+ CLEANUP;
+ }
+ if (second) {
+ y = accum("seconds", x, second, us_per_second, &leftover_us);
+ CLEANUP;
+ }
+ if (minute) {
+ y = accum("minutes", x, minute, us_per_minute, &leftover_us);
+ CLEANUP;
+ }
+ if (hour) {
+ y = accum("hours", x, hour, us_per_hour, &leftover_us);
+ CLEANUP;
+ }
+ if (day) {
+ y = accum("days", x, day, us_per_day, &leftover_us);
+ CLEANUP;
+ }
+ if (week) {
+ y = accum("weeks", x, week, us_per_week, &leftover_us);
+ CLEANUP;
+ }
+ if (leftover_us) {
+ /* Round to nearest whole # of us, and add into x. */
+ PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
+ if (temp == NULL) {
+ Py_DECREF(x);
+ goto Done;
+ }
+ y = PyNumber_Add(x, temp);
+ Py_DECREF(temp);
+ CLEANUP;
+ }
+
+ self = microseconds_to_delta_ex(x, type);
+ Py_DECREF(x);
Done:
- return self;
+ return self;
#undef CLEANUP
}
@@ -2011,75 +2011,75 @@ Done:
static int
delta_nonzero(PyDateTime_Delta *self)
{
- return (GET_TD_DAYS(self) != 0
- || GET_TD_SECONDS(self) != 0
- || GET_TD_MICROSECONDS(self) != 0);
+ return (GET_TD_DAYS(self) != 0
+ || GET_TD_SECONDS(self) != 0
+ || GET_TD_MICROSECONDS(self) != 0);
}
static PyObject *
delta_repr(PyDateTime_Delta *self)
{
- if (GET_TD_MICROSECONDS(self) != 0)
- return PyString_FromFormat("%s(%d, %d, %d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self));
- if (GET_TD_SECONDS(self) != 0)
- return PyString_FromFormat("%s(%d, %d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self),
- GET_TD_SECONDS(self));
+ if (GET_TD_MICROSECONDS(self) != 0)
+ return PyString_FromFormat("%s(%d, %d, %d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self),
+ GET_TD_SECONDS(self),
+ GET_TD_MICROSECONDS(self));
+ if (GET_TD_SECONDS(self) != 0)
+ return PyString_FromFormat("%s(%d, %d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self),
+ GET_TD_SECONDS(self));
- return PyString_FromFormat("%s(%d)",
- Py_TYPE(self)->tp_name,
- GET_TD_DAYS(self));
+ return PyString_FromFormat("%s(%d)",
+ Py_TYPE(self)->tp_name,
+ GET_TD_DAYS(self));
}
static PyObject *
delta_str(PyDateTime_Delta *self)
{
- int days = GET_TD_DAYS(self);
- int seconds = GET_TD_SECONDS(self);
- int us = GET_TD_MICROSECONDS(self);
- int hours;
- int minutes;
- char buf[100];
- char *pbuf = buf;
- size_t buflen = sizeof(buf);
- int n;
-
- minutes = divmod(seconds, 60, &seconds);
- hours = divmod(minutes, 60, &minutes);
-
- if (days) {
- n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
- (days == 1 || days == -1) ? "" : "s");
- if (n < 0 || (size_t)n >= buflen)
- goto Fail;
- pbuf += n;
- buflen -= (size_t)n;
- }
-
- n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
- hours, minutes, seconds);
- if (n < 0 || (size_t)n >= buflen)
- goto Fail;
- pbuf += n;
- buflen -= (size_t)n;
-
- if (us) {
- n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
- if (n < 0 || (size_t)n >= buflen)
- goto Fail;
- pbuf += n;
- }
-
- return PyString_FromStringAndSize(buf, pbuf - buf);
+ int days = GET_TD_DAYS(self);
+ int seconds = GET_TD_SECONDS(self);
+ int us = GET_TD_MICROSECONDS(self);
+ int hours;
+ int minutes;
+ char buf[100];
+ char *pbuf = buf;
+ size_t buflen = sizeof(buf);
+ int n;
+
+ minutes = divmod(seconds, 60, &seconds);
+ hours = divmod(minutes, 60, &minutes);
+
+ if (days) {
+ n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
+ (days == 1 || days == -1) ? "" : "s");
+ if (n < 0 || (size_t)n >= buflen)
+ goto Fail;
+ pbuf += n;
+ buflen -= (size_t)n;
+ }
+
+ n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
+ hours, minutes, seconds);
+ if (n < 0 || (size_t)n >= buflen)
+ goto Fail;
+ pbuf += n;
+ buflen -= (size_t)n;
+
+ if (us) {
+ n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
+ if (n < 0 || (size_t)n >= buflen)
+ goto Fail;
+ pbuf += n;
+ }
+
+ return PyString_FromStringAndSize(buf, pbuf - buf);
Fail:
- PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
- return NULL;
+ PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
+ return NULL;
}
/* Pickle support, a simple use of __reduce__. */
@@ -2088,151 +2088,151 @@ delta_str(PyDateTime_Delta *self)
static PyObject *
delta_getstate(PyDateTime_Delta *self)
{
- return Py_BuildValue("iii", GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self));
+ return Py_BuildValue("iii", GET_TD_DAYS(self),
+ GET_TD_SECONDS(self),
+ GET_TD_MICROSECONDS(self));
}
static PyObject *
delta_total_seconds(PyObject *self)
{
- PyObject *total_seconds;
- PyObject *total_microseconds;
- PyObject *one_million;
+ PyObject *total_seconds;
+ PyObject *total_microseconds;
+ PyObject *one_million;
- total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
- if (total_microseconds == NULL)
- return NULL;
+ total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
+ if (total_microseconds == NULL)
+ return NULL;
- one_million = PyLong_FromLong(1000000L);
- if (one_million == NULL) {
- Py_DECREF(total_microseconds);
- return NULL;
- }
+ one_million = PyLong_FromLong(1000000L);
+ if (one_million == NULL) {
+ Py_DECREF(total_microseconds);
+ return NULL;
+ }
- total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
+ total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
- Py_DECREF(total_microseconds);
- Py_DECREF(one_million);
- return total_seconds;
+ Py_DECREF(total_microseconds);
+ Py_DECREF(one_million);
+ return total_seconds;
}
static PyObject *
delta_reduce(PyDateTime_Delta* self)
{
- return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
+ return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
}
#define OFFSET(field) offsetof(PyDateTime_Delta, field)
static PyMemberDef delta_members[] = {
- {"days", T_INT, OFFSET(days), READONLY,
- PyDoc_STR("Number of days.")},
+ {"days", T_INT, OFFSET(days), READONLY,
+ PyDoc_STR("Number of days.")},
- {"seconds", T_INT, OFFSET(seconds), READONLY,
- PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
+ {"seconds", T_INT, OFFSET(seconds), READONLY,
+ PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
- {"microseconds", T_INT, OFFSET(microseconds), READONLY,
- PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
- {NULL}
+ {"microseconds", T_INT, OFFSET(microseconds), READONLY,
+ PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
+ {NULL}
};
static PyMethodDef delta_methods[] = {
- {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
- PyDoc_STR("Total seconds in the duration.")},
+ {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
+ PyDoc_STR("Total seconds in the duration.")},
- {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL},
+ {NULL, NULL},
};
static char delta_doc[] =
PyDoc_STR("Difference between two datetime values.");
static PyNumberMethods delta_as_number = {
- delta_add, /* nb_add */
- delta_subtract, /* nb_subtract */
- delta_multiply, /* nb_multiply */
- delta_divide, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- (unaryfunc)delta_negative, /* nb_negative */
- (unaryfunc)delta_positive, /* nb_positive */
- (unaryfunc)delta_abs, /* nb_absolute */
- (inquiry)delta_nonzero, /* nb_nonzero */
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- delta_divide, /* nb_floor_divide */
- 0, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
+ delta_add, /* nb_add */
+ delta_subtract, /* nb_subtract */
+ delta_multiply, /* nb_multiply */
+ delta_divide, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ (unaryfunc)delta_negative, /* nb_negative */
+ (unaryfunc)delta_positive, /* nb_positive */
+ (unaryfunc)delta_abs, /* nb_absolute */
+ (inquiry)delta_nonzero, /* nb_nonzero */
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ 0, /*nb_and*/
+ 0, /*nb_xor*/
+ 0, /*nb_or*/
+ 0, /*nb_coerce*/
+ 0, /*nb_int*/
+ 0, /*nb_long*/
+ 0, /*nb_float*/
+ 0, /*nb_oct*/
+ 0, /*nb_hex*/
+ 0, /*nb_inplace_add*/
+ 0, /*nb_inplace_subtract*/
+ 0, /*nb_inplace_multiply*/
+ 0, /*nb_inplace_divide*/
+ 0, /*nb_inplace_remainder*/
+ 0, /*nb_inplace_power*/
+ 0, /*nb_inplace_lshift*/
+ 0, /*nb_inplace_rshift*/
+ 0, /*nb_inplace_and*/
+ 0, /*nb_inplace_xor*/
+ 0, /*nb_inplace_or*/
+ delta_divide, /* nb_floor_divide */
+ 0, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
};
static PyTypeObject PyDateTime_DeltaType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.timedelta", /* tp_name */
- sizeof(PyDateTime_Delta), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)delta_repr, /* tp_repr */
- &delta_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)delta_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)delta_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- delta_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)delta_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- delta_methods, /* tp_methods */
- delta_members, /* 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 */
- delta_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.timedelta", /* tp_name */
+ sizeof(PyDateTime_Delta), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)delta_repr, /* tp_repr */
+ &delta_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)delta_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)delta_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ delta_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)delta_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ delta_methods, /* tp_methods */
+ delta_members, /* 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 */
+ delta_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -2244,26 +2244,26 @@ static PyTypeObject PyDateTime_DeltaType = {
static PyObject *
date_year(PyDateTime_Date *self, void *unused)
{
- return PyInt_FromLong(GET_YEAR(self));
+ return PyInt_FromLong(GET_YEAR(self));
}
static PyObject *
date_month(PyDateTime_Date *self, void *unused)
{
- return PyInt_FromLong(GET_MONTH(self));
+ return PyInt_FromLong(GET_MONTH(self));
}
static PyObject *
date_day(PyDateTime_Date *self, void *unused)
{
- return PyInt_FromLong(GET_DAY(self));
+ return PyInt_FromLong(GET_DAY(self));
}
static PyGetSetDef date_getset[] = {
- {"year", (getter)date_year},
- {"month", (getter)date_month},
- {"day", (getter)date_day},
- {NULL}
+ {"year", (getter)date_year},
+ {"month", (getter)date_month},
+ {"day", (getter)date_day},
+ {NULL}
};
/* Constructors. */
@@ -2273,60 +2273,60 @@ static char *date_kws[] = {"year", "month", "day", NULL};
static PyObject *
date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
- PyObject *state;
- int year;
- int month;
- int day;
-
- /* Check for invocation from pickle with __getstate__ state */
- if (PyTuple_GET_SIZE(args) == 1 &&
- PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
- MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
- {
- PyDateTime_Date *me;
-
- me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
- if (me != NULL) {
- char *pdata = PyString_AS_STRING(state);
- memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
- me->hashcode = -1;
- }
- return (PyObject *)me;
- }
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
- &year, &month, &day)) {
- if (check_date_args(year, month, day) < 0)
- return NULL;
- self = new_date_ex(year, month, day, type);
- }
- return self;
+ PyObject *self = NULL;
+ PyObject *state;
+ int year;
+ int month;
+ int day;
+
+ /* Check for invocation from pickle with __getstate__ state */
+ if (PyTuple_GET_SIZE(args) == 1 &&
+ PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
+ MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
+ {
+ PyDateTime_Date *me;
+
+ me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
+ if (me != NULL) {
+ char *pdata = PyString_AS_STRING(state);
+ memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
+ me->hashcode = -1;
+ }
+ return (PyObject *)me;
+ }
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
+ &year, &month, &day)) {
+ if (check_date_args(year, month, day) < 0)
+ return NULL;
+ self = new_date_ex(year, month, day, type);
+ }
+ return self;
}
/* Return new date from localtime(t). */
static PyObject *
date_local_from_time_t(PyObject *cls, double ts)
{
- struct tm *tm;
- time_t t;
- PyObject *result = NULL;
-
- t = _PyTime_DoubleToTimet(ts);
- if (t == (time_t)-1 && PyErr_Occurred())
- return NULL;
- tm = localtime(&t);
- if (tm)
- result = PyObject_CallFunction(cls, "iii",
- tm->tm_year + 1900,
- tm->tm_mon + 1,
- tm->tm_mday);
- else
- PyErr_SetString(PyExc_ValueError,
- "timestamp out of range for "
- "platform localtime() function");
- return result;
+ struct tm *tm;
+ time_t t;
+ PyObject *result = NULL;
+
+ t = _PyTime_DoubleToTimet(ts);
+ if (t == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ tm = localtime(&t);
+ if (tm)
+ result = PyObject_CallFunction(cls, "iii",
+ tm->tm_year + 1900,
+ tm->tm_mon + 1,
+ tm->tm_mday);
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "timestamp out of range for "
+ "platform localtime() function");
+ return result;
}
/* Return new date from current time.
@@ -2337,34 +2337,34 @@ date_local_from_time_t(PyObject *cls, double ts)
static PyObject *
date_today(PyObject *cls, PyObject *dummy)
{
- PyObject *time;
- PyObject *result;
+ PyObject *time;
+ PyObject *result;
- time = time_time();
- if (time == NULL)
- return NULL;
+ time = time_time();
+ if (time == NULL)
+ return NULL;
- /* Note well: today() is a class method, so this may not call
- * date.fromtimestamp. For example, it may call
- * datetime.fromtimestamp. That's why we need all the accuracy
- * time.time() delivers; if someone were gonzo about optimization,
- * date.today() could get away with plain C time().
- */
- result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
- Py_DECREF(time);
- return result;
+ /* Note well: today() is a class method, so this may not call
+ * date.fromtimestamp. For example, it may call
+ * datetime.fromtimestamp. That's why we need all the accuracy
+ * time.time() delivers; if someone were gonzo about optimization,
+ * date.today() could get away with plain C time().
+ */
+ result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
+ Py_DECREF(time);
+ return result;
}
/* Return new date from given timestamp (Python timestamp -- a double). */
static PyObject *
date_fromtimestamp(PyObject *cls, PyObject *args)
{
- double timestamp;
- PyObject *result = NULL;
+ double timestamp;
+ PyObject *result = NULL;
- if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
- result = date_local_from_time_t(cls, timestamp);
- return result;
+ if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
+ result = date_local_from_time_t(cls, timestamp);
+ return result;
}
/* Return new date from proleptic Gregorian ordinal. Raises ValueError if
@@ -2373,24 +2373,24 @@ date_fromtimestamp(PyObject *cls, PyObject *args)
static PyObject *
date_fromordinal(PyObject *cls, PyObject *args)
{
- PyObject *result = NULL;
- int ordinal;
+ PyObject *result = NULL;
+ int ordinal;
- if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
- int year;
- int month;
- int day;
+ if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
+ int year;
+ int month;
+ int day;
- if (ordinal < 1)
- PyErr_SetString(PyExc_ValueError, "ordinal must be "
- ">= 1");
- else {
- ord_to_ymd(ordinal, &year, &month, &day);
- result = PyObject_CallFunction(cls, "iii",
- year, month, day);
- }
- }
- return result;
+ if (ordinal < 1)
+ PyErr_SetString(PyExc_ValueError, "ordinal must be "
+ ">= 1");
+ else {
+ ord_to_ymd(ordinal, &year, &month, &day);
+ result = PyObject_CallFunction(cls, "iii",
+ year, month, day);
+ }
+ }
+ return result;
}
/*
@@ -2403,74 +2403,74 @@ date_fromordinal(PyObject *cls, PyObject *args)
static PyObject *
add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
{
- PyObject *result = NULL;
- int year = GET_YEAR(date);
- int month = GET_MONTH(date);
- int deltadays = GET_TD_DAYS(delta);
- /* C-level overflow is impossible because |deltadays| < 1e9. */
- int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
+ PyObject *result = NULL;
+ int year = GET_YEAR(date);
+ int month = GET_MONTH(date);
+ int deltadays = GET_TD_DAYS(delta);
+ /* C-level overflow is impossible because |deltadays| < 1e9. */
+ int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
- if (normalize_date(&year, &month, &day) >= 0)
- result = new_date(year, month, day);
- return result;
+ if (normalize_date(&year, &month, &day) >= 0)
+ result = new_date(year, month, day);
+ return result;
}
static PyObject *
date_add(PyObject *left, PyObject *right)
{
- if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (PyDate_Check(left)) {
- /* date + ??? */
- if (PyDelta_Check(right))
- /* date + delta */
- return add_date_timedelta((PyDateTime_Date *) left,
- (PyDateTime_Delta *) right,
- 0);
- }
- else {
- /* ??? + date
- * 'right' must be one of us, or we wouldn't have been called
- */
- if (PyDelta_Check(left))
- /* delta + date */
- return add_date_timedelta((PyDateTime_Date *) right,
- (PyDateTime_Delta *) left,
- 0);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (PyDate_Check(left)) {
+ /* date + ??? */
+ if (PyDelta_Check(right))
+ /* date + delta */
+ return add_date_timedelta((PyDateTime_Date *) left,
+ (PyDateTime_Delta *) right,
+ 0);
+ }
+ else {
+ /* ??? + date
+ * 'right' must be one of us, or we wouldn't have been called
+ */
+ if (PyDelta_Check(left))
+ /* delta + date */
+ return add_date_timedelta((PyDateTime_Date *) right,
+ (PyDateTime_Delta *) left,
+ 0);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyObject *
date_subtract(PyObject *left, PyObject *right)
{
- if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (PyDate_Check(left)) {
- if (PyDate_Check(right)) {
- /* date - date */
- int left_ord = ymd_to_ord(GET_YEAR(left),
- GET_MONTH(left),
- GET_DAY(left));
- int right_ord = ymd_to_ord(GET_YEAR(right),
- GET_MONTH(right),
- GET_DAY(right));
- return new_delta(left_ord - right_ord, 0, 0, 0);
- }
- if (PyDelta_Check(right)) {
- /* date - delta */
- return add_date_timedelta((PyDateTime_Date *) left,
- (PyDateTime_Delta *) right,
- 1);
- }
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (PyDate_Check(left)) {
+ if (PyDate_Check(right)) {
+ /* date - date */
+ int left_ord = ymd_to_ord(GET_YEAR(left),
+ GET_MONTH(left),
+ GET_DAY(left));
+ int right_ord = ymd_to_ord(GET_YEAR(right),
+ GET_MONTH(right),
+ GET_DAY(right));
+ return new_delta(left_ord - right_ord, 0, 0, 0);
+ }
+ if (PyDelta_Check(right)) {
+ /* date - delta */
+ return add_date_timedelta((PyDateTime_Date *) left,
+ (PyDateTime_Delta *) right,
+ 1);
+ }
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
@@ -2479,89 +2479,89 @@ date_subtract(PyObject *left, PyObject *right)
static PyObject *
date_repr(PyDateTime_Date *self)
{
- char buffer[1028];
- const char *type_name;
+ char buffer[1028];
+ const char *type_name;
- type_name = Py_TYPE(self)->tp_name;
- PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ type_name = Py_TYPE(self)->tp_name;
+ PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
- return PyString_FromString(buffer);
+ return PyString_FromString(buffer);
}
static PyObject *
date_isoformat(PyDateTime_Date *self)
{
- char buffer[128];
+ char buffer[128];
- isoformat_date(self, buffer, sizeof(buffer));
- return PyString_FromString(buffer);
+ isoformat_date(self, buffer, sizeof(buffer));
+ return PyString_FromString(buffer);
}
/* str() calls the appropriate isoformat() method. */
static PyObject *
date_str(PyDateTime_Date *self)
{
- return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
+ return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
}
static PyObject *
date_ctime(PyDateTime_Date *self)
{
- return format_ctime(self, 0, 0, 0);
+ return format_ctime(self, 0, 0, 0);
}
static PyObject *
date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
{
- /* This method can be inherited, and needs to call the
- * timetuple() method appropriate to self's class.
- */
- PyObject *result;
- PyObject *tuple;
- const char *format;
- Py_ssize_t format_len;
- static char *keywords[] = {"format", NULL};
+ /* This method can be inherited, and needs to call the
+ * timetuple() method appropriate to self's class.
+ */
+ PyObject *result;
+ PyObject *tuple;
+ const char *format;
+ Py_ssize_t format_len;
+ static char *keywords[] = {"format", NULL};
- if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
- &format, &format_len))
- return NULL;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
+ &format, &format_len))
+ return NULL;
- tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
- if (tuple == NULL)
- return NULL;
- result = wrap_strftime((PyObject *)self, format, format_len, tuple,
- (PyObject *)self);
- Py_DECREF(tuple);
- return result;
+ tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
+ if (tuple == NULL)
+ return NULL;
+ result = wrap_strftime((PyObject *)self, format, format_len, tuple,
+ (PyObject *)self);
+ Py_DECREF(tuple);
+ return result;
}
static PyObject *
date_format(PyDateTime_Date *self, PyObject *args)
{
- PyObject *format;
-
- if (!PyArg_ParseTuple(args, "O:__format__", &format))
- return NULL;
-
- /* Check for str or unicode */
- if (PyString_Check(format)) {
- /* If format is zero length, return str(self) */
- if (PyString_GET_SIZE(format) == 0)
- return PyObject_Str((PyObject *)self);
- } else if (PyUnicode_Check(format)) {
- /* If format is zero length, return str(self) */
- if (PyUnicode_GET_SIZE(format) == 0)
- return PyObject_Unicode((PyObject *)self);
- } else {
- PyErr_Format(PyExc_ValueError,
- "__format__ expects str or unicode, not %.200s",
- Py_TYPE(format)->tp_name);
- return NULL;
- }
- return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
+ PyObject *format;
+
+ if (!PyArg_ParseTuple(args, "O:__format__", &format))
+ return NULL;
+
+ /* Check for str or unicode */
+ if (PyString_Check(format)) {
+ /* If format is zero length, return str(self) */
+ if (PyString_GET_SIZE(format) == 0)
+ return PyObject_Str((PyObject *)self);
+ } else if (PyUnicode_Check(format)) {
+ /* If format is zero length, return str(self) */
+ if (PyUnicode_GET_SIZE(format) == 0)
+ return PyObject_Unicode((PyObject *)self);
+ } else {
+ PyErr_Format(PyExc_ValueError,
+ "__format__ expects str or unicode, not %.200s",
+ Py_TYPE(format)->tp_name);
+ return NULL;
+ }
+ return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
}
/* ISO methods. */
@@ -2569,31 +2569,31 @@ date_format(PyDateTime_Date *self, PyObject *args)
static PyObject *
date_isoweekday(PyDateTime_Date *self)
{
- int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
- return PyInt_FromLong(dow + 1);
+ return PyInt_FromLong(dow + 1);
}
static PyObject *
date_isocalendar(PyDateTime_Date *self)
{
- int year = GET_YEAR(self);
- int week1_monday = iso_week1_monday(year);
- int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
- int week;
- int day;
-
- week = divmod(today - week1_monday, 7, &day);
- if (week < 0) {
- --year;
- week1_monday = iso_week1_monday(year);
- week = divmod(today - week1_monday, 7, &day);
- }
- else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
- ++year;
- week = 0;
- }
- return Py_BuildValue("iii", year, week + 1, day + 1);
+ int year = GET_YEAR(self);
+ int week1_monday = iso_week1_monday(year);
+ int today = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
+ int week;
+ int day;
+
+ week = divmod(today - week1_monday, 7, &day);
+ if (week < 0) {
+ --year;
+ week1_monday = iso_week1_monday(year);
+ week = divmod(today - week1_monday, 7, &day);
+ }
+ else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
+ ++year;
+ week = 0;
+ }
+ return Py_BuildValue("iii", year, week + 1, day + 1);
}
/* Miscellaneous methods. */
@@ -2605,53 +2605,53 @@ date_isocalendar(PyDateTime_Date *self)
static PyObject *
date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
{
- int diff = 42; /* nonsense */
+ int diff = 42; /* nonsense */
- if (PyDate_Check(other))
- diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
- _PyDateTime_DATE_DATASIZE);
+ if (PyDate_Check(other))
+ diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
+ _PyDateTime_DATE_DATASIZE);
- else if (PyObject_HasAttrString(other, "timetuple")) {
- /* A hook for other kinds of date objects. */
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- else if (op == Py_EQ || op == Py_NE)
- diff = 1; /* any non-zero value will do */
+ else if (PyObject_HasAttrString(other, "timetuple")) {
+ /* A hook for other kinds of date objects. */
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ else if (op == Py_EQ || op == Py_NE)
+ diff = 1; /* any non-zero value will do */
- else /* stop this from falling back to address comparison */
- return cmperror((PyObject *)self, other);
+ else /* stop this from falling back to address comparison */
+ return cmperror((PyObject *)self, other);
- return diff_to_bool(diff, op);
+ return diff_to_bool(diff, op);
}
static PyObject *
date_timetuple(PyDateTime_Date *self)
{
- return build_struct_time(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self),
- 0, 0, 0, -1);
+ return build_struct_time(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self),
+ 0, 0, 0, -1);
}
static PyObject *
date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
{
- PyObject *clone;
- PyObject *tuple;
- int year = GET_YEAR(self);
- int month = GET_MONTH(self);
- int day = GET_DAY(self);
+ PyObject *clone;
+ PyObject *tuple;
+ int year = GET_YEAR(self);
+ int month = GET_MONTH(self);
+ int day = GET_DAY(self);
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
- &year, &month, &day))
- return NULL;
- tuple = Py_BuildValue("iii", year, month, day);
- if (tuple == NULL)
- return NULL;
- clone = date_new(Py_TYPE(self), tuple, NULL);
- Py_DECREF(tuple);
- return clone;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
+ &year, &month, &day))
+ return NULL;
+ tuple = Py_BuildValue("iii", year, month, day);
+ if (tuple == NULL)
+ return NULL;
+ clone = date_new(Py_TYPE(self), tuple, NULL);
+ Py_DECREF(tuple);
+ return clone;
}
static PyObject *date_getstate(PyDateTime_Date *self);
@@ -2659,29 +2659,29 @@ static PyObject *date_getstate(PyDateTime_Date *self);
static long
date_hash(PyDateTime_Date *self)
{
- if (self->hashcode == -1) {
- PyObject *temp = date_getstate(self);
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ PyObject *temp = date_getstate(self);
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
date_toordinal(PyDateTime_Date *self)
{
- return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
- GET_DAY(self)));
+ return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
+ GET_DAY(self)));
}
static PyObject *
date_weekday(PyDateTime_Date *self)
{
- int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
+ int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
- return PyInt_FromLong(dow);
+ return PyInt_FromLong(dow);
}
/* Pickle support, a simple use of __reduce__. */
@@ -2690,136 +2690,136 @@ date_weekday(PyDateTime_Date *self)
static PyObject *
date_getstate(PyDateTime_Date *self)
{
- return Py_BuildValue(
- "(N)",
- PyString_FromStringAndSize((char *)self->data,
- _PyDateTime_DATE_DATASIZE));
+ return Py_BuildValue(
+ "(N)",
+ PyString_FromStringAndSize((char *)self->data,
+ _PyDateTime_DATE_DATASIZE));
}
static PyObject *
date_reduce(PyDateTime_Date *self, PyObject *arg)
{
- return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
+ return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
}
static PyMethodDef date_methods[] = {
- /* Class methods: */
+ /* Class methods: */
- {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
- METH_CLASS,
- PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
- "time.time()).")},
+ {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
+ METH_CLASS,
+ PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
+ "time.time()).")},
- {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
- METH_CLASS,
- PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
- "ordinal.")},
+ {"fromordinal", (PyCFunction)date_fromordinal, METH_VARARGS |
+ METH_CLASS,
+ PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
+ "ordinal.")},
- {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
- PyDoc_STR("Current date or datetime: same as "
- "self.__class__.fromtimestamp(time.time()).")},
+ {"today", (PyCFunction)date_today, METH_NOARGS | METH_CLASS,
+ PyDoc_STR("Current date or datetime: same as "
+ "self.__class__.fromtimestamp(time.time()).")},
- /* Instance methods: */
+ /* Instance methods: */
- {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
- PyDoc_STR("Return ctime() style string.")},
+ {"ctime", (PyCFunction)date_ctime, METH_NOARGS,
+ PyDoc_STR("Return ctime() style string.")},
- {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("format -> strftime() style string.")},
+ {"strftime", (PyCFunction)date_strftime, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("format -> strftime() style string.")},
- {"__format__", (PyCFunction)date_format, METH_VARARGS,
- PyDoc_STR("Formats self with strftime.")},
+ {"__format__", (PyCFunction)date_format, METH_VARARGS,
+ PyDoc_STR("Formats self with strftime.")},
- {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
- PyDoc_STR("Return time tuple, compatible with time.localtime().")},
+ {"timetuple", (PyCFunction)date_timetuple, METH_NOARGS,
+ PyDoc_STR("Return time tuple, compatible with time.localtime().")},
- {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
- PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
- "weekday.")},
+ {"isocalendar", (PyCFunction)date_isocalendar, METH_NOARGS,
+ PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
+ "weekday.")},
- {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
- PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
+ {"isoformat", (PyCFunction)date_isoformat, METH_NOARGS,
+ PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
- {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
- PyDoc_STR("Return the day of the week represented by the date.\n"
- "Monday == 1 ... Sunday == 7")},
+ {"isoweekday", (PyCFunction)date_isoweekday, METH_NOARGS,
+ PyDoc_STR("Return the day of the week represented by the date.\n"
+ "Monday == 1 ... Sunday == 7")},
- {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
- PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
- "1 is day 1.")},
+ {"toordinal", (PyCFunction)date_toordinal, METH_NOARGS,
+ PyDoc_STR("Return proleptic Gregorian ordinal. January 1 of year "
+ "1 is day 1.")},
- {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
- PyDoc_STR("Return the day of the week represented by the date.\n"
- "Monday == 0 ... Sunday == 6")},
+ {"weekday", (PyCFunction)date_weekday, METH_NOARGS,
+ PyDoc_STR("Return the day of the week represented by the date.\n"
+ "Monday == 0 ... Sunday == 6")},
- {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("Return date with new specified fields.")},
+ {"replace", (PyCFunction)date_replace, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("Return date with new specified fields.")},
- {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)date_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char date_doc[] =
PyDoc_STR("date(year, month, day) --> date object");
static PyNumberMethods date_as_number = {
- date_add, /* nb_add */
- date_subtract, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_nonzero */
+ date_add, /* nb_add */
+ date_subtract, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_nonzero */
};
static PyTypeObject PyDateTime_DateType = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "datetime.date", /* tp_name */
- sizeof(PyDateTime_Date), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)date_repr, /* tp_repr */
- &date_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)date_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)date_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- date_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)date_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- date_methods, /* tp_methods */
- 0, /* tp_members */
- date_getset, /* 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 */
- date_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "datetime.date", /* tp_name */
+ sizeof(PyDateTime_Date), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)date_repr, /* tp_repr */
+ &date_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)date_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)date_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ date_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)date_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ date_methods, /* tp_methods */
+ 0, /* tp_members */
+ date_getset, /* 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 */
+ date_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -2842,10 +2842,10 @@ static PyTypeObject PyDateTime_DateType = {
static PyObject *
tzinfo_nogo(const char* methodname)
{
- PyErr_Format(PyExc_NotImplementedError,
- "a tzinfo subclass must implement %s()",
- methodname);
- return NULL;
+ PyErr_Format(PyExc_NotImplementedError,
+ "a tzinfo subclass must implement %s()",
+ methodname);
+ return NULL;
}
/* Methods. A subclass must implement these. */
@@ -2853,101 +2853,101 @@ tzinfo_nogo(const char* methodname)
static PyObject *
tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
{
- return tzinfo_nogo("tzname");
+ return tzinfo_nogo("tzname");
}
static PyObject *
tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
{
- return tzinfo_nogo("utcoffset");
+ return tzinfo_nogo("utcoffset");
}
static PyObject *
tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
{
- return tzinfo_nogo("dst");
+ return tzinfo_nogo("dst");
}
static PyObject *
tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
{
- int y, m, d, hh, mm, ss, us;
-
- PyObject *result;
- int off, dst;
- int none;
- int delta;
-
- if (! PyDateTime_Check(dt)) {
- PyErr_SetString(PyExc_TypeError,
- "fromutc: argument must be a datetime");
- return NULL;
- }
- if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
- PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
- "is not self");
- return NULL;
- }
-
- off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
- if (off == -1 && PyErr_Occurred())
- return NULL;
- if (none) {
- PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
- "utcoffset() result required");
- return NULL;
- }
-
- dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
- if (dst == -1 && PyErr_Occurred())
- return NULL;
- if (none) {
- PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
- "dst() result required");
- return NULL;
- }
-
- y = GET_YEAR(dt);
- m = GET_MONTH(dt);
- d = GET_DAY(dt);
- hh = DATE_GET_HOUR(dt);
- mm = DATE_GET_MINUTE(dt);
- ss = DATE_GET_SECOND(dt);
- us = DATE_GET_MICROSECOND(dt);
-
- delta = off - dst;
- mm += delta;
- if ((mm < 0 || mm >= 60) &&
- normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
- return NULL;
- result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
- if (result == NULL)
- return result;
-
- dst = call_dst(dt->tzinfo, result, &none);
- if (dst == -1 && PyErr_Occurred())
- goto Fail;
- if (none)
- goto Inconsistent;
- if (dst == 0)
- return result;
-
- mm += dst;
- if ((mm < 0 || mm >= 60) &&
- normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
- goto Fail;
- Py_DECREF(result);
- result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
- return result;
+ int y, m, d, hh, mm, ss, us;
+
+ PyObject *result;
+ int off, dst;
+ int none;
+ int delta;
+
+ if (! PyDateTime_Check(dt)) {
+ PyErr_SetString(PyExc_TypeError,
+ "fromutc: argument must be a datetime");
+ return NULL;
+ }
+ if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
+ PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
+ "is not self");
+ return NULL;
+ }
+
+ off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
+ if (off == -1 && PyErr_Occurred())
+ return NULL;
+ if (none) {
+ PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
+ "utcoffset() result required");
+ return NULL;
+ }
+
+ dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
+ if (dst == -1 && PyErr_Occurred())
+ return NULL;
+ if (none) {
+ PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
+ "dst() result required");
+ return NULL;
+ }
+
+ y = GET_YEAR(dt);
+ m = GET_MONTH(dt);
+ d = GET_DAY(dt);
+ hh = DATE_GET_HOUR(dt);
+ mm = DATE_GET_MINUTE(dt);
+ ss = DATE_GET_SECOND(dt);
+ us = DATE_GET_MICROSECOND(dt);
+
+ delta = off - dst;
+ mm += delta;
+ if ((mm < 0 || mm >= 60) &&
+ normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+ return NULL;
+ result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
+ if (result == NULL)
+ return result;
+
+ dst = call_dst(dt->tzinfo, result, &none);
+ if (dst == -1 && PyErr_Occurred())
+ goto Fail;
+ if (none)
+ goto Inconsistent;
+ if (dst == 0)
+ return result;
+
+ mm += dst;
+ if ((mm < 0 || mm >= 60) &&
+ normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+ goto Fail;
+ Py_DECREF(result);
+ result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
+ return result;
Inconsistent:
- PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
- "inconsistent results; cannot convert");
+ PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
+ "inconsistent results; cannot convert");
- /* fall thru to failure */
+ /* fall thru to failure */
Fail:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
/*
@@ -2958,124 +2958,124 @@ Fail:
static PyObject *
tzinfo_reduce(PyObject *self)
{
- PyObject *args, *state, *tmp;
- PyObject *getinitargs, *getstate;
-
- tmp = PyTuple_New(0);
- if (tmp == NULL)
- return NULL;
-
- getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
- if (getinitargs != NULL) {
- args = PyObject_CallObject(getinitargs, tmp);
- Py_DECREF(getinitargs);
- if (args == NULL) {
- Py_DECREF(tmp);
- return NULL;
- }
- }
- else {
- PyErr_Clear();
- args = tmp;
- Py_INCREF(args);
- }
-
- getstate = PyObject_GetAttrString(self, "__getstate__");
- if (getstate != NULL) {
- state = PyObject_CallObject(getstate, tmp);
- Py_DECREF(getstate);
- if (state == NULL) {
- Py_DECREF(args);
- Py_DECREF(tmp);
- return NULL;
- }
- }
- else {
- PyObject **dictptr;
- PyErr_Clear();
- state = Py_None;
- dictptr = _PyObject_GetDictPtr(self);
- if (dictptr && *dictptr && PyDict_Size(*dictptr))
- state = *dictptr;
- Py_INCREF(state);
- }
-
- Py_DECREF(tmp);
-
- if (state == Py_None) {
- Py_DECREF(state);
- return Py_BuildValue("(ON)", Py_TYPE(self), args);
- }
- else
- return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
+ PyObject *args, *state, *tmp;
+ PyObject *getinitargs, *getstate;
+
+ tmp = PyTuple_New(0);
+ if (tmp == NULL)
+ return NULL;
+
+ getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
+ if (getinitargs != NULL) {
+ args = PyObject_CallObject(getinitargs, tmp);
+ Py_DECREF(getinitargs);
+ if (args == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Clear();
+ args = tmp;
+ Py_INCREF(args);
+ }
+
+ getstate = PyObject_GetAttrString(self, "__getstate__");
+ if (getstate != NULL) {
+ state = PyObject_CallObject(getstate, tmp);
+ Py_DECREF(getstate);
+ if (state == NULL) {
+ Py_DECREF(args);
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ }
+ else {
+ PyObject **dictptr;
+ PyErr_Clear();
+ state = Py_None;
+ dictptr = _PyObject_GetDictPtr(self);
+ if (dictptr && *dictptr && PyDict_Size(*dictptr))
+ state = *dictptr;
+ Py_INCREF(state);
+ }
+
+ Py_DECREF(tmp);
+
+ if (state == Py_None) {
+ Py_DECREF(state);
+ return Py_BuildValue("(ON)", Py_TYPE(self), args);
+ }
+ else
+ return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
}
static PyMethodDef tzinfo_methods[] = {
- {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
- PyDoc_STR("datetime -> string name of time zone.")},
+ {"tzname", (PyCFunction)tzinfo_tzname, METH_O,
+ PyDoc_STR("datetime -> string name of time zone.")},
- {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
- PyDoc_STR("datetime -> minutes east of UTC (negative for "
- "west of UTC).")},
+ {"utcoffset", (PyCFunction)tzinfo_utcoffset, METH_O,
+ PyDoc_STR("datetime -> minutes east of UTC (negative for "
+ "west of UTC).")},
- {"dst", (PyCFunction)tzinfo_dst, METH_O,
- PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
+ {"dst", (PyCFunction)tzinfo_dst, METH_O,
+ PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
- {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
- PyDoc_STR("datetime in UTC -> datetime in local time.")},
+ {"fromutc", (PyCFunction)tzinfo_fromutc, METH_O,
+ PyDoc_STR("datetime in UTC -> datetime in local time.")},
- {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
- PyDoc_STR("-> (cls, state)")},
+ {"__reduce__", (PyCFunction)tzinfo_reduce, METH_NOARGS,
+ PyDoc_STR("-> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char tzinfo_doc[] =
PyDoc_STR("Abstract base class for time zone info objects.");
statichere PyTypeObject PyDateTime_TZInfoType = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "datetime.tzinfo", /* tp_name */
- sizeof(PyDateTime_TZInfo), /* tp_basicsize */
- 0, /* tp_itemsize */
- 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_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- tzinfo_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- tzinfo_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 */
- PyType_GenericNew, /* tp_new */
- 0, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "datetime.tzinfo", /* tp_name */
+ sizeof(PyDateTime_TZInfo), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 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_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ tzinfo_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ tzinfo_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 */
+ PyType_GenericNew, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -3088,43 +3088,43 @@ statichere PyTypeObject PyDateTime_TZInfoType = {
static PyObject *
time_hour(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_HOUR(self));
+ return PyInt_FromLong(TIME_GET_HOUR(self));
}
static PyObject *
time_minute(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_MINUTE(self));
+ return PyInt_FromLong(TIME_GET_MINUTE(self));
}
/* The name time_second conflicted with some platform header file. */
static PyObject *
py_time_second(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_SECOND(self));
+ return PyInt_FromLong(TIME_GET_SECOND(self));
}
static PyObject *
time_microsecond(PyDateTime_Time *self, void *unused)
{
- return PyInt_FromLong(TIME_GET_MICROSECOND(self));
+ return PyInt_FromLong(TIME_GET_MICROSECOND(self));
}
static PyObject *
time_tzinfo(PyDateTime_Time *self, void *unused)
{
- PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
- Py_INCREF(result);
- return result;
+ PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
+ Py_INCREF(result);
+ return result;
}
static PyGetSetDef time_getset[] = {
- {"hour", (getter)time_hour},
- {"minute", (getter)time_minute},
- {"second", (getter)py_time_second},
- {"microsecond", (getter)time_microsecond},
- {"tzinfo", (getter)time_tzinfo},
- {NULL}
+ {"hour", (getter)time_hour},
+ {"minute", (getter)time_minute},
+ {"second", (getter)py_time_second},
+ {"microsecond", (getter)time_microsecond},
+ {"tzinfo", (getter)time_tzinfo},
+ {NULL}
};
/*
@@ -3132,64 +3132,64 @@ static PyGetSetDef time_getset[] = {
*/
static char *time_kws[] = {"hour", "minute", "second", "microsecond",
- "tzinfo", NULL};
+ "tzinfo", NULL};
static PyObject *
time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
- PyObject *state;
- int hour = 0;
- int minute = 0;
- int second = 0;
- int usecond = 0;
- PyObject *tzinfo = Py_None;
-
- /* Check for invocation from pickle with __getstate__ state */
- if (PyTuple_GET_SIZE(args) >= 1 &&
- PyTuple_GET_SIZE(args) <= 2 &&
- PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
- ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
- {
- PyDateTime_Time *me;
- char aware;
-
- if (PyTuple_GET_SIZE(args) == 2) {
- tzinfo = PyTuple_GET_ITEM(args, 1);
- if (check_tzinfo_subclass(tzinfo) < 0) {
- PyErr_SetString(PyExc_TypeError, "bad "
- "tzinfo state arg");
- return NULL;
- }
- }
- aware = (char)(tzinfo != Py_None);
- me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
- if (me != NULL) {
- char *pdata = PyString_AS_STRING(state);
-
- memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
- me->hashcode = -1;
- me->hastzinfo = aware;
- if (aware) {
- Py_INCREF(tzinfo);
- me->tzinfo = tzinfo;
- }
- }
- return (PyObject *)me;
- }
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
- &hour, &minute, &second, &usecond,
- &tzinfo)) {
- if (check_time_args(hour, minute, second, usecond) < 0)
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
- self = new_time_ex(hour, minute, second, usecond, tzinfo,
- type);
- }
- return self;
+ PyObject *self = NULL;
+ PyObject *state;
+ int hour = 0;
+ int minute = 0;
+ int second = 0;
+ int usecond = 0;
+ PyObject *tzinfo = Py_None;
+
+ /* Check for invocation from pickle with __getstate__ state */
+ if (PyTuple_GET_SIZE(args) >= 1 &&
+ PyTuple_GET_SIZE(args) <= 2 &&
+ PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
+ ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
+ {
+ PyDateTime_Time *me;
+ char aware;
+
+ if (PyTuple_GET_SIZE(args) == 2) {
+ tzinfo = PyTuple_GET_ITEM(args, 1);
+ if (check_tzinfo_subclass(tzinfo) < 0) {
+ PyErr_SetString(PyExc_TypeError, "bad "
+ "tzinfo state arg");
+ return NULL;
+ }
+ }
+ aware = (char)(tzinfo != Py_None);
+ me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
+ if (me != NULL) {
+ char *pdata = PyString_AS_STRING(state);
+
+ memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
+ me->hashcode = -1;
+ me->hastzinfo = aware;
+ if (aware) {
+ Py_INCREF(tzinfo);
+ me->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)me;
+ }
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
+ &hour, &minute, &second, &usecond,
+ &tzinfo)) {
+ if (check_time_args(hour, minute, second, usecond) < 0)
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
+ self = new_time_ex(hour, minute, second, usecond, tzinfo,
+ type);
+ }
+ return self;
}
/*
@@ -3199,10 +3199,10 @@ time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
static void
time_dealloc(PyDateTime_Time *self)
{
- if (HASTZINFO(self)) {
- Py_XDECREF(self->tzinfo);
- }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ if (HASTZINFO(self)) {
+ Py_XDECREF(self->tzinfo);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
/*
@@ -3212,20 +3212,20 @@ time_dealloc(PyDateTime_Time *self)
/* These are all METH_NOARGS, so don't need to check the arglist. */
static PyObject *
time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "utcoffset", Py_None);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "utcoffset", Py_None);
}
static PyObject *
time_dst(PyDateTime_Time *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "dst", Py_None);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "dst", Py_None);
}
static PyObject *
time_tzname(PyDateTime_Time *self, PyObject *unused) {
- return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
- Py_None);
+ return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
+ Py_None);
}
/*
@@ -3235,94 +3235,94 @@ time_tzname(PyDateTime_Time *self, PyObject *unused) {
static PyObject *
time_repr(PyDateTime_Time *self)
{
- char buffer[100];
- const char *type_name = Py_TYPE(self)->tp_name;
- int h = TIME_GET_HOUR(self);
- int m = TIME_GET_MINUTE(self);
- int s = TIME_GET_SECOND(self);
- int us = TIME_GET_MICROSECOND(self);
- PyObject *result = NULL;
-
- if (us)
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
- else if (s)
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d)", type_name, h, m, s);
- else
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d)", type_name, h, m);
- result = PyString_FromString(buffer);
- if (result != NULL && HASTZINFO(self))
- result = append_keyword_tzinfo(result, self->tzinfo);
- return result;
+ char buffer[100];
+ const char *type_name = Py_TYPE(self)->tp_name;
+ int h = TIME_GET_HOUR(self);
+ int m = TIME_GET_MINUTE(self);
+ int s = TIME_GET_SECOND(self);
+ int us = TIME_GET_MICROSECOND(self);
+ PyObject *result = NULL;
+
+ if (us)
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
+ else if (s)
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d)", type_name, h, m, s);
+ else
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d)", type_name, h, m);
+ result = PyString_FromString(buffer);
+ if (result != NULL && HASTZINFO(self))
+ result = append_keyword_tzinfo(result, self->tzinfo);
+ return result;
}
static PyObject *
time_str(PyDateTime_Time *self)
{
- return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
+ return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
}
static PyObject *
time_isoformat(PyDateTime_Time *self, PyObject *unused)
{
- char buf[100];
- PyObject *result;
- /* Reuse the time format code from the datetime type. */
- PyDateTime_DateTime datetime;
- PyDateTime_DateTime *pdatetime = &datetime;
+ char buf[100];
+ PyObject *result;
+ /* Reuse the time format code from the datetime type. */
+ PyDateTime_DateTime datetime;
+ PyDateTime_DateTime *pdatetime = &datetime;
- /* Copy over just the time bytes. */
- memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
- self->data,
- _PyDateTime_TIME_DATASIZE);
+ /* Copy over just the time bytes. */
+ memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
+ self->data,
+ _PyDateTime_TIME_DATASIZE);
- isoformat_time(pdatetime, buf, sizeof(buf));
- result = PyString_FromString(buf);
- if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
- return result;
+ isoformat_time(pdatetime, buf, sizeof(buf));
+ result = PyString_FromString(buf);
+ if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
+ return result;
- /* We need to append the UTC offset. */
- if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
- Py_None) < 0) {
- Py_DECREF(result);
- return NULL;
- }
- PyString_ConcatAndDel(&result, PyString_FromString(buf));
- return result;
+ /* We need to append the UTC offset. */
+ if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
+ Py_None) < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyString_ConcatAndDel(&result, PyString_FromString(buf));
+ return result;
}
static PyObject *
time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
{
- PyObject *result;
- PyObject *tuple;
- const char *format;
- Py_ssize_t format_len;
- static char *keywords[] = {"format", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
- &format, &format_len))
- return NULL;
-
- /* Python's strftime does insane things with the year part of the
- * timetuple. The year is forced to (the otherwise nonsensical)
- * 1900 to worm around that.
- */
- tuple = Py_BuildValue("iiiiiiiii",
- 1900, 1, 1, /* year, month, day */
- TIME_GET_HOUR(self),
- TIME_GET_MINUTE(self),
- TIME_GET_SECOND(self),
- 0, 1, -1); /* weekday, daynum, dst */
- if (tuple == NULL)
- return NULL;
- assert(PyTuple_Size(tuple) == 9);
- result = wrap_strftime((PyObject *)self, format, format_len, tuple,
- Py_None);
- Py_DECREF(tuple);
- return result;
+ PyObject *result;
+ PyObject *tuple;
+ const char *format;
+ Py_ssize_t format_len;
+ static char *keywords[] = {"format", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
+ &format, &format_len))
+ return NULL;
+
+ /* Python's strftime does insane things with the year part of the
+ * timetuple. The year is forced to (the otherwise nonsensical)
+ * 1900 to worm around that.
+ */
+ tuple = Py_BuildValue("iiiiiiiii",
+ 1900, 1, 1, /* year, month, day */
+ TIME_GET_HOUR(self),
+ TIME_GET_MINUTE(self),
+ TIME_GET_SECOND(self),
+ 0, 1, -1); /* weekday, daynum, dst */
+ if (tuple == NULL)
+ return NULL;
+ assert(PyTuple_Size(tuple) == 9);
+ result = wrap_strftime((PyObject *)self, format, format_len, tuple,
+ Py_None);
+ Py_DECREF(tuple);
+ return result;
}
/*
@@ -3336,146 +3336,146 @@ time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
static PyObject *
time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
{
- int diff;
- naivety n1, n2;
- int offset1, offset2;
-
- if (! PyTime_Check(other)) {
- if (op == Py_EQ || op == Py_NE) {
- PyObject *result = op == Py_EQ ? Py_False : Py_True;
- Py_INCREF(result);
- return result;
- }
- /* Stop this from falling back to address comparison. */
- return cmperror((PyObject *)self, other);
- }
- if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
- other, &offset2, &n2, Py_None) < 0)
- return NULL;
- assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
- /* If they're both naive, or both aware and have the same offsets,
- * we get off cheap. Note that if they're both naive, offset1 ==
- * offset2 == 0 at this point.
- */
- if (n1 == n2 && offset1 == offset2) {
- diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
- _PyDateTime_TIME_DATASIZE);
- return diff_to_bool(diff, op);
- }
-
- if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
- assert(offset1 != offset2); /* else last "if" handled it */
- /* Convert everything except microseconds to seconds. These
- * can't overflow (no more than the # of seconds in 2 days).
- */
- offset1 = TIME_GET_HOUR(self) * 3600 +
- (TIME_GET_MINUTE(self) - offset1) * 60 +
- TIME_GET_SECOND(self);
- offset2 = TIME_GET_HOUR(other) * 3600 +
- (TIME_GET_MINUTE(other) - offset2) * 60 +
- TIME_GET_SECOND(other);
- diff = offset1 - offset2;
- if (diff == 0)
- diff = TIME_GET_MICROSECOND(self) -
- TIME_GET_MICROSECOND(other);
- return diff_to_bool(diff, op);
- }
-
- assert(n1 != n2);
- PyErr_SetString(PyExc_TypeError,
- "can't compare offset-naive and "
- "offset-aware times");
- return NULL;
+ int diff;
+ naivety n1, n2;
+ int offset1, offset2;
+
+ if (! PyTime_Check(other)) {
+ if (op == Py_EQ || op == Py_NE) {
+ PyObject *result = op == Py_EQ ? Py_False : Py_True;
+ Py_INCREF(result);
+ return result;
+ }
+ /* Stop this from falling back to address comparison. */
+ return cmperror((PyObject *)self, other);
+ }
+ if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
+ other, &offset2, &n2, Py_None) < 0)
+ return NULL;
+ assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+ /* If they're both naive, or both aware and have the same offsets,
+ * we get off cheap. Note that if they're both naive, offset1 ==
+ * offset2 == 0 at this point.
+ */
+ if (n1 == n2 && offset1 == offset2) {
+ diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
+ _PyDateTime_TIME_DATASIZE);
+ return diff_to_bool(diff, op);
+ }
+
+ if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
+ assert(offset1 != offset2); /* else last "if" handled it */
+ /* Convert everything except microseconds to seconds. These
+ * can't overflow (no more than the # of seconds in 2 days).
+ */
+ offset1 = TIME_GET_HOUR(self) * 3600 +
+ (TIME_GET_MINUTE(self) - offset1) * 60 +
+ TIME_GET_SECOND(self);
+ offset2 = TIME_GET_HOUR(other) * 3600 +
+ (TIME_GET_MINUTE(other) - offset2) * 60 +
+ TIME_GET_SECOND(other);
+ diff = offset1 - offset2;
+ if (diff == 0)
+ diff = TIME_GET_MICROSECOND(self) -
+ TIME_GET_MICROSECOND(other);
+ return diff_to_bool(diff, op);
+ }
+
+ assert(n1 != n2);
+ PyErr_SetString(PyExc_TypeError,
+ "can't compare offset-naive and "
+ "offset-aware times");
+ return NULL;
}
static long
time_hash(PyDateTime_Time *self)
{
- if (self->hashcode == -1) {
- naivety n;
- int offset;
- PyObject *temp;
-
- n = classify_utcoffset((PyObject *)self, Py_None, &offset);
- assert(n != OFFSET_UNKNOWN);
- if (n == OFFSET_ERROR)
- return -1;
-
- /* Reduce this to a hash of another object. */
- if (offset == 0)
- temp = PyString_FromStringAndSize((char *)self->data,
- _PyDateTime_TIME_DATASIZE);
- else {
- int hour;
- int minute;
-
- assert(n == OFFSET_AWARE);
- assert(HASTZINFO(self));
- hour = divmod(TIME_GET_HOUR(self) * 60 +
- TIME_GET_MINUTE(self) - offset,
- 60,
- &minute);
- if (0 <= hour && hour < 24)
- temp = new_time(hour, minute,
- TIME_GET_SECOND(self),
- TIME_GET_MICROSECOND(self),
- Py_None);
- else
- temp = Py_BuildValue("iiii",
- hour, minute,
- TIME_GET_SECOND(self),
- TIME_GET_MICROSECOND(self));
- }
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ naivety n;
+ int offset;
+ PyObject *temp;
+
+ n = classify_utcoffset((PyObject *)self, Py_None, &offset);
+ assert(n != OFFSET_UNKNOWN);
+ if (n == OFFSET_ERROR)
+ return -1;
+
+ /* Reduce this to a hash of another object. */
+ if (offset == 0)
+ temp = PyString_FromStringAndSize((char *)self->data,
+ _PyDateTime_TIME_DATASIZE);
+ else {
+ int hour;
+ int minute;
+
+ assert(n == OFFSET_AWARE);
+ assert(HASTZINFO(self));
+ hour = divmod(TIME_GET_HOUR(self) * 60 +
+ TIME_GET_MINUTE(self) - offset,
+ 60,
+ &minute);
+ if (0 <= hour && hour < 24)
+ temp = new_time(hour, minute,
+ TIME_GET_SECOND(self),
+ TIME_GET_MICROSECOND(self),
+ Py_None);
+ else
+ temp = Py_BuildValue("iiii",
+ hour, minute,
+ TIME_GET_SECOND(self),
+ TIME_GET_MICROSECOND(self));
+ }
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
{
- PyObject *clone;
- PyObject *tuple;
- int hh = TIME_GET_HOUR(self);
- int mm = TIME_GET_MINUTE(self);
- int ss = TIME_GET_SECOND(self);
- int us = TIME_GET_MICROSECOND(self);
- PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
- time_kws,
- &hh, &mm, &ss, &us, &tzinfo))
- return NULL;
- tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
- if (tuple == NULL)
- return NULL;
- clone = time_new(Py_TYPE(self), tuple, NULL);
- Py_DECREF(tuple);
- return clone;
+ PyObject *clone;
+ PyObject *tuple;
+ int hh = TIME_GET_HOUR(self);
+ int mm = TIME_GET_MINUTE(self);
+ int ss = TIME_GET_SECOND(self);
+ int us = TIME_GET_MICROSECOND(self);
+ PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
+ time_kws,
+ &hh, &mm, &ss, &us, &tzinfo))
+ return NULL;
+ tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
+ if (tuple == NULL)
+ return NULL;
+ clone = time_new(Py_TYPE(self), tuple, NULL);
+ Py_DECREF(tuple);
+ return clone;
}
static int
time_nonzero(PyDateTime_Time *self)
{
- int offset;
- int none;
-
- if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
- /* Since utcoffset is in whole minutes, nothing can
- * alter the conclusion that this is nonzero.
- */
- return 1;
- }
- offset = 0;
- if (HASTZINFO(self) && self->tzinfo != Py_None) {
- offset = call_utcoffset(self->tzinfo, Py_None, &none);
- if (offset == -1 && PyErr_Occurred())
- return -1;
- }
- return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
+ int offset;
+ int none;
+
+ if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
+ /* Since utcoffset is in whole minutes, nothing can
+ * alter the conclusion that this is nonzero.
+ */
+ return 1;
+ }
+ offset = 0;
+ if (HASTZINFO(self) && self->tzinfo != Py_None) {
+ offset = call_utcoffset(self->tzinfo, Py_None, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return -1;
+ }
+ return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
}
/* Pickle support, a simple use of __reduce__. */
@@ -3488,55 +3488,55 @@ time_nonzero(PyDateTime_Time *self)
static PyObject *
time_getstate(PyDateTime_Time *self)
{
- PyObject *basestate;
- PyObject *result = NULL;
+ PyObject *basestate;
+ PyObject *result = NULL;
- basestate = PyString_FromStringAndSize((char *)self->data,
- _PyDateTime_TIME_DATASIZE);
- if (basestate != NULL) {
- if (! HASTZINFO(self) || self->tzinfo == Py_None)
- result = PyTuple_Pack(1, basestate);
- else
- result = PyTuple_Pack(2, basestate, self->tzinfo);
- Py_DECREF(basestate);
- }
- return result;
+ basestate = PyString_FromStringAndSize((char *)self->data,
+ _PyDateTime_TIME_DATASIZE);
+ if (basestate != NULL) {
+ if (! HASTZINFO(self) || self->tzinfo == Py_None)
+ result = PyTuple_Pack(1, basestate);
+ else
+ result = PyTuple_Pack(2, basestate, self->tzinfo);
+ Py_DECREF(basestate);
+ }
+ return result;
}
static PyObject *
time_reduce(PyDateTime_Time *self, PyObject *arg)
{
- return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
+ return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
}
static PyMethodDef time_methods[] = {
- {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
- PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
- "[+HH:MM].")},
+ {"isoformat", (PyCFunction)time_isoformat, METH_NOARGS,
+ PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
+ "[+HH:MM].")},
- {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("format -> strftime() style string.")},
+ {"strftime", (PyCFunction)time_strftime, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("format -> strftime() style string.")},
- {"__format__", (PyCFunction)date_format, METH_VARARGS,
- PyDoc_STR("Formats self with strftime.")},
+ {"__format__", (PyCFunction)date_format, METH_VARARGS,
+ PyDoc_STR("Formats self with strftime.")},
- {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
+ {"utcoffset", (PyCFunction)time_utcoffset, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
- {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.tzname(self).")},
+ {"tzname", (PyCFunction)time_tzname, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.tzname(self).")},
- {"dst", (PyCFunction)time_dst, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.dst(self).")},
+ {"dst", (PyCFunction)time_dst, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.dst(self).")},
- {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("Return time with new specified fields.")},
+ {"replace", (PyCFunction)time_replace, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("Return time with new specified fields.")},
- {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)time_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char time_doc[] =
@@ -3546,61 +3546,61 @@ All arguments are optional. tzinfo may be None, or an instance of\n\
a tzinfo subclass. The remaining arguments may be ints or longs.\n");
static PyNumberMethods time_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- (inquiry)time_nonzero, /* nb_nonzero */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ (inquiry)time_nonzero, /* nb_nonzero */
};
statichere PyTypeObject PyDateTime_TimeType = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "datetime.time", /* tp_name */
- sizeof(PyDateTime_Time), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)time_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)time_repr, /* tp_repr */
- &time_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)time_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)time_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- time_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)time_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- time_methods, /* tp_methods */
- 0, /* tp_members */
- time_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- time_alloc, /* tp_alloc */
- time_new, /* tp_new */
- 0, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "datetime.time", /* tp_name */
+ sizeof(PyDateTime_Time), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)time_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)time_repr, /* tp_repr */
+ &time_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)time_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)time_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ time_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)time_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ time_methods, /* tp_methods */
+ 0, /* tp_members */
+ time_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ time_alloc, /* tp_alloc */
+ time_new, /* tp_new */
+ 0, /* tp_free */
};
/*
@@ -3614,42 +3614,42 @@ statichere PyTypeObject PyDateTime_TimeType = {
static PyObject *
datetime_hour(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_HOUR(self));
+ return PyInt_FromLong(DATE_GET_HOUR(self));
}
static PyObject *
datetime_minute(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_MINUTE(self));
+ return PyInt_FromLong(DATE_GET_MINUTE(self));
}
static PyObject *
datetime_second(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_SECOND(self));
+ return PyInt_FromLong(DATE_GET_SECOND(self));
}
static PyObject *
datetime_microsecond(PyDateTime_DateTime *self, void *unused)
{
- return PyInt_FromLong(DATE_GET_MICROSECOND(self));
+ return PyInt_FromLong(DATE_GET_MICROSECOND(self));
}
static PyObject *
datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
{
- PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
- Py_INCREF(result);
- return result;
+ PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
+ Py_INCREF(result);
+ return result;
}
static PyGetSetDef datetime_getset[] = {
- {"hour", (getter)datetime_hour},
- {"minute", (getter)datetime_minute},
- {"second", (getter)datetime_second},
- {"microsecond", (getter)datetime_microsecond},
- {"tzinfo", (getter)datetime_tzinfo},
- {NULL}
+ {"hour", (getter)datetime_hour},
+ {"minute", (getter)datetime_minute},
+ {"second", (getter)datetime_second},
+ {"microsecond", (getter)datetime_microsecond},
+ {"tzinfo", (getter)datetime_tzinfo},
+ {NULL}
};
/*
@@ -3657,72 +3657,72 @@ static PyGetSetDef datetime_getset[] = {
*/
static char *datetime_kws[] = {
- "year", "month", "day", "hour", "minute", "second",
- "microsecond", "tzinfo", NULL
+ "year", "month", "day", "hour", "minute", "second",
+ "microsecond", "tzinfo", NULL
};
static PyObject *
datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *self = NULL;
- PyObject *state;
- int year;
- int month;
- int day;
- int hour = 0;
- int minute = 0;
- int second = 0;
- int usecond = 0;
- PyObject *tzinfo = Py_None;
-
- /* Check for invocation from pickle with __getstate__ state */
- if (PyTuple_GET_SIZE(args) >= 1 &&
- PyTuple_GET_SIZE(args) <= 2 &&
- PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
- PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
- MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
- {
- PyDateTime_DateTime *me;
- char aware;
-
- if (PyTuple_GET_SIZE(args) == 2) {
- tzinfo = PyTuple_GET_ITEM(args, 1);
- if (check_tzinfo_subclass(tzinfo) < 0) {
- PyErr_SetString(PyExc_TypeError, "bad "
- "tzinfo state arg");
- return NULL;
- }
- }
- aware = (char)(tzinfo != Py_None);
- me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
- if (me != NULL) {
- char *pdata = PyString_AS_STRING(state);
-
- memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
- me->hashcode = -1;
- me->hastzinfo = aware;
- if (aware) {
- Py_INCREF(tzinfo);
- me->tzinfo = tzinfo;
- }
- }
- return (PyObject *)me;
- }
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
- &year, &month, &day, &hour, &minute,
- &second, &usecond, &tzinfo)) {
- if (check_date_args(year, month, day) < 0)
- return NULL;
- if (check_time_args(hour, minute, second, usecond) < 0)
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
- self = new_datetime_ex(year, month, day,
- hour, minute, second, usecond,
- tzinfo, type);
- }
- return self;
+ PyObject *self = NULL;
+ PyObject *state;
+ int year;
+ int month;
+ int day;
+ int hour = 0;
+ int minute = 0;
+ int second = 0;
+ int usecond = 0;
+ PyObject *tzinfo = Py_None;
+
+ /* Check for invocation from pickle with __getstate__ state */
+ if (PyTuple_GET_SIZE(args) >= 1 &&
+ PyTuple_GET_SIZE(args) <= 2 &&
+ PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
+ PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
+ MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
+ {
+ PyDateTime_DateTime *me;
+ char aware;
+
+ if (PyTuple_GET_SIZE(args) == 2) {
+ tzinfo = PyTuple_GET_ITEM(args, 1);
+ if (check_tzinfo_subclass(tzinfo) < 0) {
+ PyErr_SetString(PyExc_TypeError, "bad "
+ "tzinfo state arg");
+ return NULL;
+ }
+ }
+ aware = (char)(tzinfo != Py_None);
+ me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
+ if (me != NULL) {
+ char *pdata = PyString_AS_STRING(state);
+
+ memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
+ me->hashcode = -1;
+ me->hastzinfo = aware;
+ if (aware) {
+ Py_INCREF(tzinfo);
+ me->tzinfo = tzinfo;
+ }
+ }
+ return (PyObject *)me;
+ }
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
+ &year, &month, &day, &hour, &minute,
+ &second, &usecond, &tzinfo)) {
+ if (check_date_args(year, month, day) < 0)
+ return NULL;
+ if (check_time_args(hour, minute, second, usecond) < 0)
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
+ self = new_datetime_ex(year, month, day,
+ hour, minute, second, usecond,
+ tzinfo, type);
+ }
+ return self;
}
/* TM_FUNC is the shared type of localtime() and gmtime(). */
@@ -3734,36 +3734,36 @@ typedef struct tm *(*TM_FUNC)(const time_t *timer);
*/
static PyObject *
datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
- PyObject *tzinfo)
-{
- struct tm *tm;
- PyObject *result = NULL;
-
- tm = f(&timet);
- if (tm) {
- /* The platform localtime/gmtime may insert leap seconds,
- * indicated by tm->tm_sec > 59. We don't care about them,
- * except to the extent that passing them on to the datetime
- * constructor would raise ValueError for a reason that
- * made no sense to the user.
- */
- if (tm->tm_sec > 59)
- tm->tm_sec = 59;
- result = PyObject_CallFunction(cls, "iiiiiiiO",
- tm->tm_year + 1900,
- tm->tm_mon + 1,
- tm->tm_mday,
- tm->tm_hour,
- tm->tm_min,
- tm->tm_sec,
- us,
- tzinfo);
- }
- else
- PyErr_SetString(PyExc_ValueError,
- "timestamp out of range for "
- "platform localtime()/gmtime() function");
- return result;
+ PyObject *tzinfo)
+{
+ struct tm *tm;
+ PyObject *result = NULL;
+
+ tm = f(&timet);
+ if (tm) {
+ /* The platform localtime/gmtime may insert leap seconds,
+ * indicated by tm->tm_sec > 59. We don't care about them,
+ * except to the extent that passing them on to the datetime
+ * constructor would raise ValueError for a reason that
+ * made no sense to the user.
+ */
+ if (tm->tm_sec > 59)
+ tm->tm_sec = 59;
+ result = PyObject_CallFunction(cls, "iiiiiiiO",
+ tm->tm_year + 1900,
+ tm->tm_mon + 1,
+ tm->tm_mday,
+ tm->tm_hour,
+ tm->tm_min,
+ tm->tm_sec,
+ us,
+ tzinfo);
+ }
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "timestamp out of range for "
+ "platform localtime()/gmtime() function");
+ return result;
}
/* Internal helper.
@@ -3775,31 +3775,31 @@ datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
*/
static PyObject *
datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
- PyObject *tzinfo)
-{
- time_t timet;
- double fraction;
- int us;
-
- timet = _PyTime_DoubleToTimet(timestamp);
- if (timet == (time_t)-1 && PyErr_Occurred())
- return NULL;
- fraction = timestamp - (double)timet;
- us = (int)round_to_long(fraction * 1e6);
- if (us < 0) {
- /* Truncation towards zero is not what we wanted
- for negative numbers (Python's mod semantics) */
- timet -= 1;
- us += 1000000;
- }
- /* If timestamp is less than one microsecond smaller than a
- * full second, round up. Otherwise, ValueErrors are raised
- * for some floats. */
- if (us == 1000000) {
- timet += 1;
- us = 0;
- }
- return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
+ PyObject *tzinfo)
+{
+ time_t timet;
+ double fraction;
+ int us;
+
+ timet = _PyTime_DoubleToTimet(timestamp);
+ if (timet == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ fraction = timestamp - (double)timet;
+ us = (int)round_to_long(fraction * 1e6);
+ if (us < 0) {
+ /* Truncation towards zero is not what we wanted
+ for negative numbers (Python's mod semantics) */
+ timet -= 1;
+ us += 1000000;
+ }
+ /* If timestamp is less than one microsecond smaller than a
+ * full second, round up. Otherwise, ValueErrors are raised
+ * for some floats. */
+ if (us == 1000000) {
+ timet += 1;
+ us = 0;
+ }
+ return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
}
/* Internal helper.
@@ -3810,36 +3810,36 @@ static PyObject *
datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
{
#ifdef HAVE_GETTIMEOFDAY
- struct timeval t;
+ struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
- gettimeofday(&t);
+ gettimeofday(&t);
#else
- gettimeofday(&t, (struct timezone *)NULL);
+ gettimeofday(&t, (struct timezone *)NULL);
#endif
- return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
- tzinfo);
-
-#else /* ! HAVE_GETTIMEOFDAY */
- /* No flavor of gettimeofday exists on this platform. Python's
- * time.time() does a lot of other platform tricks to get the
- * best time it can on the platform, and we're not going to do
- * better than that (if we could, the better code would belong
- * in time.time()!) We're limited by the precision of a double,
- * though.
- */
- PyObject *time;
- double dtime;
-
- time = time_time();
- if (time == NULL)
- return NULL;
- dtime = PyFloat_AsDouble(time);
- Py_DECREF(time);
- if (dtime == -1.0 && PyErr_Occurred())
- return NULL;
- return datetime_from_timestamp(cls, f, dtime, tzinfo);
-#endif /* ! HAVE_GETTIMEOFDAY */
+ return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
+ tzinfo);
+
+#else /* ! HAVE_GETTIMEOFDAY */
+ /* No flavor of gettimeofday exists on this platform. Python's
+ * time.time() does a lot of other platform tricks to get the
+ * best time it can on the platform, and we're not going to do
+ * better than that (if we could, the better code would belong
+ * in time.time()!) We're limited by the precision of a double,
+ * though.
+ */
+ PyObject *time;
+ double dtime;
+
+ time = time_time();
+ if (time == NULL)
+ return NULL;
+ dtime = PyFloat_AsDouble(time);
+ Py_DECREF(time);
+ if (dtime == -1.0 && PyErr_Occurred())
+ return NULL;
+ return datetime_from_timestamp(cls, f, dtime, tzinfo);
+#endif /* ! HAVE_GETTIMEOFDAY */
}
/* Return best possible local time -- this isn't constrained by the
@@ -3848,26 +3848,26 @@ datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
static PyObject *
datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
{
- PyObject *self;
- PyObject *tzinfo = Py_None;
- static char *keywords[] = {"tz", NULL};
+ PyObject *self;
+ PyObject *tzinfo = Py_None;
+ static char *keywords[] = {"tz", NULL};
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
- &tzinfo))
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
+ &tzinfo))
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
- self = datetime_best_possible(cls,
- tzinfo == Py_None ? localtime : gmtime,
- tzinfo);
- if (self != NULL && tzinfo != Py_None) {
- /* Convert UTC to tzinfo's zone. */
- PyObject *temp = self;
- self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
- Py_DECREF(temp);
- }
- return self;
+ self = datetime_best_possible(cls,
+ tzinfo == Py_None ? localtime : gmtime,
+ tzinfo);
+ if (self != NULL && tzinfo != Py_None) {
+ /* Convert UTC to tzinfo's zone. */
+ PyObject *temp = self;
+ self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
+ Py_DECREF(temp);
+ }
+ return self;
}
/* Return best possible UTC time -- this isn't constrained by the
@@ -3876,147 +3876,147 @@ datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
static PyObject *
datetime_utcnow(PyObject *cls, PyObject *dummy)
{
- return datetime_best_possible(cls, gmtime, Py_None);
+ return datetime_best_possible(cls, gmtime, Py_None);
}
/* Return new local datetime from timestamp (Python timestamp -- a double). */
static PyObject *
datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
{
- PyObject *self;
- double timestamp;
- PyObject *tzinfo = Py_None;
- static char *keywords[] = {"timestamp", "tz", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
- keywords, &timestamp, &tzinfo))
- return NULL;
- if (check_tzinfo_subclass(tzinfo) < 0)
- return NULL;
-
- self = datetime_from_timestamp(cls,
- tzinfo == Py_None ? localtime : gmtime,
- timestamp,
- tzinfo);
- if (self != NULL && tzinfo != Py_None) {
- /* Convert UTC to tzinfo's zone. */
- PyObject *temp = self;
- self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
- Py_DECREF(temp);
- }
- return self;
+ PyObject *self;
+ double timestamp;
+ PyObject *tzinfo = Py_None;
+ static char *keywords[] = {"timestamp", "tz", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
+ keywords, &timestamp, &tzinfo))
+ return NULL;
+ if (check_tzinfo_subclass(tzinfo) < 0)
+ return NULL;
+
+ self = datetime_from_timestamp(cls,
+ tzinfo == Py_None ? localtime : gmtime,
+ timestamp,
+ tzinfo);
+ if (self != NULL && tzinfo != Py_None) {
+ /* Convert UTC to tzinfo's zone. */
+ PyObject *temp = self;
+ self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
+ Py_DECREF(temp);
+ }
+ return self;
}
/* Return new UTC datetime from timestamp (Python timestamp -- a double). */
static PyObject *
datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
{
- double timestamp;
- PyObject *result = NULL;
+ double timestamp;
+ PyObject *result = NULL;
- if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
- result = datetime_from_timestamp(cls, gmtime, timestamp,
- Py_None);
- return result;
+ if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
+ result = datetime_from_timestamp(cls, gmtime, timestamp,
+ Py_None);
+ return result;
}
/* Return new datetime from time.strptime(). */
static PyObject *
datetime_strptime(PyObject *cls, PyObject *args)
{
- static PyObject *module = NULL;
- PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
- const char *string, *format;
-
- if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
- return NULL;
-
- if (module == NULL &&
- (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
- return NULL;
-
- /* _strptime._strptime returns a two-element tuple. The first
- element is a time.struct_time object. The second is the
- microseconds (which are not defined for time.struct_time). */
- obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
- if (obj != NULL) {
- int i, good_timetuple = 1;
- long int ia[7];
- if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
- st = PySequence_GetItem(obj, 0);
- frac = PySequence_GetItem(obj, 1);
- if (st == NULL || frac == NULL)
- good_timetuple = 0;
- /* copy y/m/d/h/m/s values out of the
- time.struct_time */
- if (good_timetuple &&
- PySequence_Check(st) &&
- PySequence_Size(st) >= 6) {
- for (i=0; i < 6; i++) {
- PyObject *p = PySequence_GetItem(st, i);
- if (p == NULL) {
- good_timetuple = 0;
- break;
- }
- if (PyInt_Check(p))
- ia[i] = PyInt_AsLong(p);
- else
- good_timetuple = 0;
- Py_DECREF(p);
- }
- }
- else
- good_timetuple = 0;
- /* follow that up with a little dose of microseconds */
- if (good_timetuple && PyInt_Check(frac))
- ia[6] = PyInt_AsLong(frac);
- else
- good_timetuple = 0;
- }
- else
- good_timetuple = 0;
- if (good_timetuple)
- result = PyObject_CallFunction(cls, "iiiiiii",
- ia[0], ia[1], ia[2],
- ia[3], ia[4], ia[5],
- ia[6]);
- else
- PyErr_SetString(PyExc_ValueError,
- "unexpected value from _strptime._strptime");
- }
- Py_XDECREF(obj);
- Py_XDECREF(st);
- Py_XDECREF(frac);
- return result;
+ static PyObject *module = NULL;
+ PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
+ const char *string, *format;
+
+ if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
+ return NULL;
+
+ if (module == NULL &&
+ (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
+ return NULL;
+
+ /* _strptime._strptime returns a two-element tuple. The first
+ element is a time.struct_time object. The second is the
+ microseconds (which are not defined for time.struct_time). */
+ obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
+ if (obj != NULL) {
+ int i, good_timetuple = 1;
+ long int ia[7];
+ if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
+ st = PySequence_GetItem(obj, 0);
+ frac = PySequence_GetItem(obj, 1);
+ if (st == NULL || frac == NULL)
+ good_timetuple = 0;
+ /* copy y/m/d/h/m/s values out of the
+ time.struct_time */
+ if (good_timetuple &&
+ PySequence_Check(st) &&
+ PySequence_Size(st) >= 6) {
+ for (i=0; i < 6; i++) {
+ PyObject *p = PySequence_GetItem(st, i);
+ if (p == NULL) {
+ good_timetuple = 0;
+ break;
+ }
+ if (PyInt_Check(p))
+ ia[i] = PyInt_AsLong(p);
+ else
+ good_timetuple = 0;
+ Py_DECREF(p);
+ }
+ }
+ else
+ good_timetuple = 0;
+ /* follow that up with a little dose of microseconds */
+ if (good_timetuple && PyInt_Check(frac))
+ ia[6] = PyInt_AsLong(frac);
+ else
+ good_timetuple = 0;
+ }
+ else
+ good_timetuple = 0;
+ if (good_timetuple)
+ result = PyObject_CallFunction(cls, "iiiiiii",
+ ia[0], ia[1], ia[2],
+ ia[3], ia[4], ia[5],
+ ia[6]);
+ else
+ PyErr_SetString(PyExc_ValueError,
+ "unexpected value from _strptime._strptime");
+ }
+ Py_XDECREF(obj);
+ Py_XDECREF(st);
+ Py_XDECREF(frac);
+ return result;
}
/* Return new datetime from date/datetime and time arguments. */
static PyObject *
datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
{
- static char *keywords[] = {"date", "time", NULL};
- PyObject *date;
- PyObject *time;
- PyObject *result = NULL;
-
- if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
- &PyDateTime_DateType, &date,
- &PyDateTime_TimeType, &time)) {
- PyObject *tzinfo = Py_None;
-
- if (HASTZINFO(time))
- tzinfo = ((PyDateTime_Time *)time)->tzinfo;
- result = PyObject_CallFunction(cls, "iiiiiiiO",
- GET_YEAR(date),
- GET_MONTH(date),
- GET_DAY(date),
- TIME_GET_HOUR(time),
- TIME_GET_MINUTE(time),
- TIME_GET_SECOND(time),
- TIME_GET_MICROSECOND(time),
- tzinfo);
- }
- return result;
+ static char *keywords[] = {"date", "time", NULL};
+ PyObject *date;
+ PyObject *time;
+ PyObject *result = NULL;
+
+ if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
+ &PyDateTime_DateType, &date,
+ &PyDateTime_TimeType, &time)) {
+ PyObject *tzinfo = Py_None;
+
+ if (HASTZINFO(time))
+ tzinfo = ((PyDateTime_Time *)time)->tzinfo;
+ result = PyObject_CallFunction(cls, "iiiiiiiO",
+ GET_YEAR(date),
+ GET_MONTH(date),
+ GET_DAY(date),
+ TIME_GET_HOUR(time),
+ TIME_GET_MINUTE(time),
+ TIME_GET_SECOND(time),
+ TIME_GET_MICROSECOND(time),
+ tzinfo);
+ }
+ return result;
}
/*
@@ -4026,10 +4026,10 @@ datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
static void
datetime_dealloc(PyDateTime_DateTime *self)
{
- if (HASTZINFO(self)) {
- Py_XDECREF(self->tzinfo);
- }
- Py_TYPE(self)->tp_free((PyObject *)self);
+ if (HASTZINFO(self)) {
+ Py_XDECREF(self->tzinfo);
+ }
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
/*
@@ -4039,20 +4039,20 @@ datetime_dealloc(PyDateTime_DateTime *self)
/* These are all METH_NOARGS, so don't need to check the arglist. */
static PyObject *
datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "utcoffset", (PyObject *)self);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "utcoffset", (PyObject *)self);
}
static PyObject *
datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
- return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
- "dst", (PyObject *)self);
+ return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
+ "dst", (PyObject *)self);
}
static PyObject *
datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
- return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
- (PyObject *)self);
+ return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
+ (PyObject *)self);
}
/*
@@ -4064,112 +4064,112 @@ datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
*/
static PyObject *
add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
- int factor)
-{
- /* Note that the C-level additions can't overflow, because of
- * invariant bounds on the member values.
- */
- int year = GET_YEAR(date);
- int month = GET_MONTH(date);
- int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
- int hour = DATE_GET_HOUR(date);
- int minute = DATE_GET_MINUTE(date);
- int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
- int microsecond = DATE_GET_MICROSECOND(date) +
- GET_TD_MICROSECONDS(delta) * factor;
-
- assert(factor == 1 || factor == -1);
- if (normalize_datetime(&year, &month, &day,
- &hour, &minute, &second, &microsecond) < 0)
- return NULL;
- else
- return new_datetime(year, month, day,
- hour, minute, second, microsecond,
- HASTZINFO(date) ? date->tzinfo : Py_None);
+ int factor)
+{
+ /* Note that the C-level additions can't overflow, because of
+ * invariant bounds on the member values.
+ */
+ int year = GET_YEAR(date);
+ int month = GET_MONTH(date);
+ int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
+ int hour = DATE_GET_HOUR(date);
+ int minute = DATE_GET_MINUTE(date);
+ int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
+ int microsecond = DATE_GET_MICROSECOND(date) +
+ GET_TD_MICROSECONDS(delta) * factor;
+
+ assert(factor == 1 || factor == -1);
+ if (normalize_datetime(&year, &month, &day,
+ &hour, &minute, &second, &microsecond) < 0)
+ return NULL;
+ else
+ return new_datetime(year, month, day,
+ hour, minute, second, microsecond,
+ HASTZINFO(date) ? date->tzinfo : Py_None);
}
static PyObject *
datetime_add(PyObject *left, PyObject *right)
{
- if (PyDateTime_Check(left)) {
- /* datetime + ??? */
- if (PyDelta_Check(right))
- /* datetime + delta */
- return add_datetime_timedelta(
- (PyDateTime_DateTime *)left,
- (PyDateTime_Delta *)right,
- 1);
- }
- else if (PyDelta_Check(left)) {
- /* delta + datetime */
- return add_datetime_timedelta((PyDateTime_DateTime *) right,
- (PyDateTime_Delta *) left,
- 1);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (PyDateTime_Check(left)) {
+ /* datetime + ??? */
+ if (PyDelta_Check(right))
+ /* datetime + delta */
+ return add_datetime_timedelta(
+ (PyDateTime_DateTime *)left,
+ (PyDateTime_Delta *)right,
+ 1);
+ }
+ else if (PyDelta_Check(left)) {
+ /* delta + datetime */
+ return add_datetime_timedelta((PyDateTime_DateTime *) right,
+ (PyDateTime_Delta *) left,
+ 1);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyObject *
datetime_subtract(PyObject *left, PyObject *right)
{
- PyObject *result = Py_NotImplemented;
-
- if (PyDateTime_Check(left)) {
- /* datetime - ??? */
- if (PyDateTime_Check(right)) {
- /* datetime - datetime */
- naivety n1, n2;
- int offset1, offset2;
- int delta_d, delta_s, delta_us;
-
- if (classify_two_utcoffsets(left, &offset1, &n1, left,
- right, &offset2, &n2,
- right) < 0)
- return NULL;
- assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
- if (n1 != n2) {
- PyErr_SetString(PyExc_TypeError,
- "can't subtract offset-naive and "
- "offset-aware datetimes");
- return NULL;
- }
- delta_d = ymd_to_ord(GET_YEAR(left),
- GET_MONTH(left),
- GET_DAY(left)) -
- ymd_to_ord(GET_YEAR(right),
- GET_MONTH(right),
- GET_DAY(right));
- /* These can't overflow, since the values are
- * normalized. At most this gives the number of
- * seconds in one day.
- */
- delta_s = (DATE_GET_HOUR(left) -
- DATE_GET_HOUR(right)) * 3600 +
- (DATE_GET_MINUTE(left) -
- DATE_GET_MINUTE(right)) * 60 +
- (DATE_GET_SECOND(left) -
- DATE_GET_SECOND(right));
- delta_us = DATE_GET_MICROSECOND(left) -
- DATE_GET_MICROSECOND(right);
- /* (left - offset1) - (right - offset2) =
- * (left - right) + (offset2 - offset1)
- */
- delta_s += (offset2 - offset1) * 60;
- result = new_delta(delta_d, delta_s, delta_us, 1);
- }
- else if (PyDelta_Check(right)) {
- /* datetime - delta */
- result = add_datetime_timedelta(
- (PyDateTime_DateTime *)left,
- (PyDateTime_Delta *)right,
- -1);
- }
- }
-
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
+ PyObject *result = Py_NotImplemented;
+
+ if (PyDateTime_Check(left)) {
+ /* datetime - ??? */
+ if (PyDateTime_Check(right)) {
+ /* datetime - datetime */
+ naivety n1, n2;
+ int offset1, offset2;
+ int delta_d, delta_s, delta_us;
+
+ if (classify_two_utcoffsets(left, &offset1, &n1, left,
+ right, &offset2, &n2,
+ right) < 0)
+ return NULL;
+ assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+ if (n1 != n2) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't subtract offset-naive and "
+ "offset-aware datetimes");
+ return NULL;
+ }
+ delta_d = ymd_to_ord(GET_YEAR(left),
+ GET_MONTH(left),
+ GET_DAY(left)) -
+ ymd_to_ord(GET_YEAR(right),
+ GET_MONTH(right),
+ GET_DAY(right));
+ /* These can't overflow, since the values are
+ * normalized. At most this gives the number of
+ * seconds in one day.
+ */
+ delta_s = (DATE_GET_HOUR(left) -
+ DATE_GET_HOUR(right)) * 3600 +
+ (DATE_GET_MINUTE(left) -
+ DATE_GET_MINUTE(right)) * 60 +
+ (DATE_GET_SECOND(left) -
+ DATE_GET_SECOND(right));
+ delta_us = DATE_GET_MICROSECOND(left) -
+ DATE_GET_MICROSECOND(right);
+ /* (left - offset1) - (right - offset2) =
+ * (left - right) + (offset2 - offset1)
+ */
+ delta_s += (offset2 - offset1) * 60;
+ result = new_delta(delta_d, delta_s, delta_us, 1);
+ }
+ else if (PyDelta_Check(right)) {
+ /* datetime - delta */
+ result = add_datetime_timedelta(
+ (PyDateTime_DateTime *)left,
+ (PyDateTime_Delta *)right,
+ -1);
+ }
+ }
+
+ if (result == Py_NotImplemented)
+ Py_INCREF(result);
+ return result;
}
/* Various ways to turn a datetime into a string. */
@@ -4177,83 +4177,83 @@ datetime_subtract(PyObject *left, PyObject *right)
static PyObject *
datetime_repr(PyDateTime_DateTime *self)
{
- char buffer[1000];
- const char *type_name = Py_TYPE(self)->tp_name;
- PyObject *baserepr;
-
- if (DATE_GET_MICROSECOND(self)) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d, %d, %d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- DATE_GET_MICROSECOND(self));
- }
- else if (DATE_GET_SECOND(self)) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d, %d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self));
- }
- else {
- PyOS_snprintf(buffer, sizeof(buffer),
- "%s(%d, %d, %d, %d, %d)",
- type_name,
- GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
- DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
- }
- baserepr = PyString_FromString(buffer);
- if (baserepr == NULL || ! HASTZINFO(self))
- return baserepr;
- return append_keyword_tzinfo(baserepr, self->tzinfo);
+ char buffer[1000];
+ const char *type_name = Py_TYPE(self)->tp_name;
+ PyObject *baserepr;
+
+ if (DATE_GET_MICROSECOND(self)) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d, %d, %d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ DATE_GET_MICROSECOND(self));
+ }
+ else if (DATE_GET_SECOND(self)) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d, %d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self));
+ }
+ else {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "%s(%d, %d, %d, %d, %d)",
+ type_name,
+ GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
+ DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
+ }
+ baserepr = PyString_FromString(buffer);
+ if (baserepr == NULL || ! HASTZINFO(self))
+ return baserepr;
+ return append_keyword_tzinfo(baserepr, self->tzinfo);
}
static PyObject *
datetime_str(PyDateTime_DateTime *self)
{
- return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
+ return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
}
static PyObject *
datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
{
- char sep = 'T';
- static char *keywords[] = {"sep", NULL};
- char buffer[100];
- char *cp;
- PyObject *result;
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
- &sep))
- return NULL;
- cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
- assert(cp != NULL);
- *cp++ = sep;
- cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
- result = PyString_FromStringAndSize(buffer, cp - buffer);
- if (result == NULL || ! HASTZINFO(self))
- return result;
-
- /* We need to append the UTC offset. */
- if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
- (PyObject *)self) < 0) {
- Py_DECREF(result);
- return NULL;
- }
- PyString_ConcatAndDel(&result, PyString_FromString(buffer));
- return result;
+ char sep = 'T';
+ static char *keywords[] = {"sep", NULL};
+ char buffer[100];
+ char *cp;
+ PyObject *result;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
+ &sep))
+ return NULL;
+ cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
+ assert(cp != NULL);
+ *cp++ = sep;
+ cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
+ result = PyString_FromStringAndSize(buffer, cp - buffer);
+ if (result == NULL || ! HASTZINFO(self))
+ return result;
+
+ /* We need to append the UTC offset. */
+ if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
+ (PyObject *)self) < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyString_ConcatAndDel(&result, PyString_FromString(buffer));
+ return result;
}
static PyObject *
datetime_ctime(PyDateTime_DateTime *self)
{
- return format_ctime((PyDateTime_Date *)self,
- DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self));
+ return format_ctime((PyDateTime_Date *)self,
+ DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self));
}
/* Miscellaneous methods. */
@@ -4265,298 +4265,298 @@ datetime_ctime(PyDateTime_DateTime *self)
static PyObject *
datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
{
- int diff;
- naivety n1, n2;
- int offset1, offset2;
-
- if (! PyDateTime_Check(other)) {
- /* If other has a "timetuple" attr, that's an advertised
- * hook for other classes to ask to get comparison control.
- * However, date instances have a timetuple attr, and we
- * don't want to allow that comparison. Because datetime
- * is a subclass of date, when mixing date and datetime
- * in a comparison, Python gives datetime the first shot
- * (it's the more specific subtype). So we can stop that
- * combination here reliably.
- */
- if (PyObject_HasAttrString(other, "timetuple") &&
- ! PyDate_Check(other)) {
- /* A hook for other kinds of datetime objects. */
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (op == Py_EQ || op == Py_NE) {
- PyObject *result = op == Py_EQ ? Py_False : Py_True;
- Py_INCREF(result);
- return result;
- }
- /* Stop this from falling back to address comparison. */
- return cmperror((PyObject *)self, other);
- }
-
- if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
- (PyObject *)self,
- other, &offset2, &n2,
- other) < 0)
- return NULL;
- assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
- /* If they're both naive, or both aware and have the same offsets,
- * we get off cheap. Note that if they're both naive, offset1 ==
- * offset2 == 0 at this point.
- */
- if (n1 == n2 && offset1 == offset2) {
- diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
- _PyDateTime_DATETIME_DATASIZE);
- return diff_to_bool(diff, op);
- }
-
- if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
- PyDateTime_Delta *delta;
-
- assert(offset1 != offset2); /* else last "if" handled it */
- delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
- other);
- if (delta == NULL)
- return NULL;
- diff = GET_TD_DAYS(delta);
- if (diff == 0)
- diff = GET_TD_SECONDS(delta) |
- GET_TD_MICROSECONDS(delta);
- Py_DECREF(delta);
- return diff_to_bool(diff, op);
- }
-
- assert(n1 != n2);
- PyErr_SetString(PyExc_TypeError,
- "can't compare offset-naive and "
- "offset-aware datetimes");
- return NULL;
+ int diff;
+ naivety n1, n2;
+ int offset1, offset2;
+
+ if (! PyDateTime_Check(other)) {
+ /* If other has a "timetuple" attr, that's an advertised
+ * hook for other classes to ask to get comparison control.
+ * However, date instances have a timetuple attr, and we
+ * don't want to allow that comparison. Because datetime
+ * is a subclass of date, when mixing date and datetime
+ * in a comparison, Python gives datetime the first shot
+ * (it's the more specific subtype). So we can stop that
+ * combination here reliably.
+ */
+ if (PyObject_HasAttrString(other, "timetuple") &&
+ ! PyDate_Check(other)) {
+ /* A hook for other kinds of datetime objects. */
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (op == Py_EQ || op == Py_NE) {
+ PyObject *result = op == Py_EQ ? Py_False : Py_True;
+ Py_INCREF(result);
+ return result;
+ }
+ /* Stop this from falling back to address comparison. */
+ return cmperror((PyObject *)self, other);
+ }
+
+ if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
+ (PyObject *)self,
+ other, &offset2, &n2,
+ other) < 0)
+ return NULL;
+ assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
+ /* If they're both naive, or both aware and have the same offsets,
+ * we get off cheap. Note that if they're both naive, offset1 ==
+ * offset2 == 0 at this point.
+ */
+ if (n1 == n2 && offset1 == offset2) {
+ diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
+ _PyDateTime_DATETIME_DATASIZE);
+ return diff_to_bool(diff, op);
+ }
+
+ if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
+ PyDateTime_Delta *delta;
+
+ assert(offset1 != offset2); /* else last "if" handled it */
+ delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
+ other);
+ if (delta == NULL)
+ return NULL;
+ diff = GET_TD_DAYS(delta);
+ if (diff == 0)
+ diff = GET_TD_SECONDS(delta) |
+ GET_TD_MICROSECONDS(delta);
+ Py_DECREF(delta);
+ return diff_to_bool(diff, op);
+ }
+
+ assert(n1 != n2);
+ PyErr_SetString(PyExc_TypeError,
+ "can't compare offset-naive and "
+ "offset-aware datetimes");
+ return NULL;
}
static long
datetime_hash(PyDateTime_DateTime *self)
{
- if (self->hashcode == -1) {
- naivety n;
- int offset;
- PyObject *temp;
-
- n = classify_utcoffset((PyObject *)self, (PyObject *)self,
- &offset);
- assert(n != OFFSET_UNKNOWN);
- if (n == OFFSET_ERROR)
- return -1;
-
- /* Reduce this to a hash of another object. */
- if (n == OFFSET_NAIVE)
- temp = PyString_FromStringAndSize(
- (char *)self->data,
- _PyDateTime_DATETIME_DATASIZE);
- else {
- int days;
- int seconds;
-
- assert(n == OFFSET_AWARE);
- assert(HASTZINFO(self));
- days = ymd_to_ord(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self));
- seconds = DATE_GET_HOUR(self) * 3600 +
- (DATE_GET_MINUTE(self) - offset) * 60 +
- DATE_GET_SECOND(self);
- temp = new_delta(days,
- seconds,
- DATE_GET_MICROSECOND(self),
- 1);
- }
- if (temp != NULL) {
- self->hashcode = PyObject_Hash(temp);
- Py_DECREF(temp);
- }
- }
- return self->hashcode;
+ if (self->hashcode == -1) {
+ naivety n;
+ int offset;
+ PyObject *temp;
+
+ n = classify_utcoffset((PyObject *)self, (PyObject *)self,
+ &offset);
+ assert(n != OFFSET_UNKNOWN);
+ if (n == OFFSET_ERROR)
+ return -1;
+
+ /* Reduce this to a hash of another object. */
+ if (n == OFFSET_NAIVE)
+ temp = PyString_FromStringAndSize(
+ (char *)self->data,
+ _PyDateTime_DATETIME_DATASIZE);
+ else {
+ int days;
+ int seconds;
+
+ assert(n == OFFSET_AWARE);
+ assert(HASTZINFO(self));
+ days = ymd_to_ord(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self));
+ seconds = DATE_GET_HOUR(self) * 3600 +
+ (DATE_GET_MINUTE(self) - offset) * 60 +
+ DATE_GET_SECOND(self);
+ temp = new_delta(days,
+ seconds,
+ DATE_GET_MICROSECOND(self),
+ 1);
+ }
+ if (temp != NULL) {
+ self->hashcode = PyObject_Hash(temp);
+ Py_DECREF(temp);
+ }
+ }
+ return self->hashcode;
}
static PyObject *
datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
{
- PyObject *clone;
- PyObject *tuple;
- int y = GET_YEAR(self);
- int m = GET_MONTH(self);
- int d = GET_DAY(self);
- int hh = DATE_GET_HOUR(self);
- int mm = DATE_GET_MINUTE(self);
- int ss = DATE_GET_SECOND(self);
- int us = DATE_GET_MICROSECOND(self);
- PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
- datetime_kws,
- &y, &m, &d, &hh, &mm, &ss, &us,
- &tzinfo))
- return NULL;
- tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
- if (tuple == NULL)
- return NULL;
- clone = datetime_new(Py_TYPE(self), tuple, NULL);
- Py_DECREF(tuple);
- return clone;
+ PyObject *clone;
+ PyObject *tuple;
+ int y = GET_YEAR(self);
+ int m = GET_MONTH(self);
+ int d = GET_DAY(self);
+ int hh = DATE_GET_HOUR(self);
+ int mm = DATE_GET_MINUTE(self);
+ int ss = DATE_GET_SECOND(self);
+ int us = DATE_GET_MICROSECOND(self);
+ PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
+ datetime_kws,
+ &y, &m, &d, &hh, &mm, &ss, &us,
+ &tzinfo))
+ return NULL;
+ tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
+ if (tuple == NULL)
+ return NULL;
+ clone = datetime_new(Py_TYPE(self), tuple, NULL);
+ Py_DECREF(tuple);
+ return clone;
}
static PyObject *
datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
{
- int y, m, d, hh, mm, ss, us;
- PyObject *result;
- int offset, none;
-
- PyObject *tzinfo;
- static char *keywords[] = {"tz", NULL};
-
- if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
- &PyDateTime_TZInfoType, &tzinfo))
- return NULL;
-
- if (!HASTZINFO(self) || self->tzinfo == Py_None)
- goto NeedAware;
-
- /* Conversion to self's own time zone is a NOP. */
- if (self->tzinfo == tzinfo) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
-
- /* Convert self to UTC. */
- offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
- if (none)
- goto NeedAware;
-
- y = GET_YEAR(self);
- m = GET_MONTH(self);
- d = GET_DAY(self);
- hh = DATE_GET_HOUR(self);
- mm = DATE_GET_MINUTE(self);
- ss = DATE_GET_SECOND(self);
- us = DATE_GET_MICROSECOND(self);
-
- mm -= offset;
- if ((mm < 0 || mm >= 60) &&
- normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
- return NULL;
-
- /* Attach new tzinfo and let fromutc() do the rest. */
- result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
- if (result != NULL) {
- PyObject *temp = result;
-
- result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
- Py_DECREF(temp);
- }
- return result;
+ int y, m, d, hh, mm, ss, us;
+ PyObject *result;
+ int offset, none;
+
+ PyObject *tzinfo;
+ static char *keywords[] = {"tz", NULL};
+
+ if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
+ &PyDateTime_TZInfoType, &tzinfo))
+ return NULL;
+
+ if (!HASTZINFO(self) || self->tzinfo == Py_None)
+ goto NeedAware;
+
+ /* Conversion to self's own time zone is a NOP. */
+ if (self->tzinfo == tzinfo) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+
+ /* Convert self to UTC. */
+ offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+ if (none)
+ goto NeedAware;
+
+ y = GET_YEAR(self);
+ m = GET_MONTH(self);
+ d = GET_DAY(self);
+ hh = DATE_GET_HOUR(self);
+ mm = DATE_GET_MINUTE(self);
+ ss = DATE_GET_SECOND(self);
+ us = DATE_GET_MICROSECOND(self);
+
+ mm -= offset;
+ if ((mm < 0 || mm >= 60) &&
+ normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
+ return NULL;
+
+ /* Attach new tzinfo and let fromutc() do the rest. */
+ result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
+ if (result != NULL) {
+ PyObject *temp = result;
+
+ result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
+ Py_DECREF(temp);
+ }
+ return result;
NeedAware:
- PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
- "a naive datetime");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
+ "a naive datetime");
+ return NULL;
}
static PyObject *
datetime_timetuple(PyDateTime_DateTime *self)
{
- int dstflag = -1;
+ int dstflag = -1;
- if (HASTZINFO(self) && self->tzinfo != Py_None) {
- int none;
+ if (HASTZINFO(self) && self->tzinfo != Py_None) {
+ int none;
- dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
- if (dstflag == -1 && PyErr_Occurred())
- return NULL;
+ dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
+ if (dstflag == -1 && PyErr_Occurred())
+ return NULL;
- if (none)
- dstflag = -1;
- else if (dstflag != 0)
- dstflag = 1;
+ if (none)
+ dstflag = -1;
+ else if (dstflag != 0)
+ dstflag = 1;
- }
- return build_struct_time(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self),
- DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- dstflag);
+ }
+ return build_struct_time(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self),
+ DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ dstflag);
}
static PyObject *
datetime_getdate(PyDateTime_DateTime *self)
{
- return new_date(GET_YEAR(self),
- GET_MONTH(self),
- GET_DAY(self));
+ return new_date(GET_YEAR(self),
+ GET_MONTH(self),
+ GET_DAY(self));
}
static PyObject *
datetime_gettime(PyDateTime_DateTime *self)
{
- return new_time(DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- DATE_GET_MICROSECOND(self),
- Py_None);
+ return new_time(DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ DATE_GET_MICROSECOND(self),
+ Py_None);
}
static PyObject *
datetime_gettimetz(PyDateTime_DateTime *self)
{
- return new_time(DATE_GET_HOUR(self),
- DATE_GET_MINUTE(self),
- DATE_GET_SECOND(self),
- DATE_GET_MICROSECOND(self),
- HASTZINFO(self) ? self->tzinfo : Py_None);
+ return new_time(DATE_GET_HOUR(self),
+ DATE_GET_MINUTE(self),
+ DATE_GET_SECOND(self),
+ DATE_GET_MICROSECOND(self),
+ HASTZINFO(self) ? self->tzinfo : Py_None);
}
static PyObject *
datetime_utctimetuple(PyDateTime_DateTime *self)
{
- int y = GET_YEAR(self);
- int m = GET_MONTH(self);
- int d = GET_DAY(self);
- int hh = DATE_GET_HOUR(self);
- int mm = DATE_GET_MINUTE(self);
- int ss = DATE_GET_SECOND(self);
- int us = 0; /* microseconds are ignored in a timetuple */
- int offset = 0;
-
- if (HASTZINFO(self) && self->tzinfo != Py_None) {
- int none;
-
- offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
- if (offset == -1 && PyErr_Occurred())
- return NULL;
- }
- /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
- * 0 in a UTC timetuple regardless of what dst() says.
- */
- if (offset) {
- /* Subtract offset minutes & normalize. */
- int stat;
-
- mm -= offset;
- stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
- if (stat < 0) {
- /* At the edges, it's possible we overflowed
- * beyond MINYEAR or MAXYEAR.
- */
- if (PyErr_ExceptionMatches(PyExc_OverflowError))
- PyErr_Clear();
- else
- return NULL;
- }
- }
- return build_struct_time(y, m, d, hh, mm, ss, 0);
+ int y = GET_YEAR(self);
+ int m = GET_MONTH(self);
+ int d = GET_DAY(self);
+ int hh = DATE_GET_HOUR(self);
+ int mm = DATE_GET_MINUTE(self);
+ int ss = DATE_GET_SECOND(self);
+ int us = 0; /* microseconds are ignored in a timetuple */
+ int offset = 0;
+
+ if (HASTZINFO(self) && self->tzinfo != Py_None) {
+ int none;
+
+ offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
+ if (offset == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
+ * 0 in a UTC timetuple regardless of what dst() says.
+ */
+ if (offset) {
+ /* Subtract offset minutes & normalize. */
+ int stat;
+
+ mm -= offset;
+ stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
+ if (stat < 0) {
+ /* At the edges, it's possible we overflowed
+ * beyond MINYEAR or MAXYEAR.
+ */
+ if (PyErr_ExceptionMatches(PyExc_OverflowError))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ }
+ return build_struct_time(y, m, d, hh, mm, ss, 0);
}
/* Pickle support, a simple use of __reduce__. */
@@ -4569,102 +4569,102 @@ datetime_utctimetuple(PyDateTime_DateTime *self)
static PyObject *
datetime_getstate(PyDateTime_DateTime *self)
{
- PyObject *basestate;
- PyObject *result = NULL;
+ PyObject *basestate;
+ PyObject *result = NULL;
- basestate = PyString_FromStringAndSize((char *)self->data,
- _PyDateTime_DATETIME_DATASIZE);
- if (basestate != NULL) {
- if (! HASTZINFO(self) || self->tzinfo == Py_None)
- result = PyTuple_Pack(1, basestate);
- else
- result = PyTuple_Pack(2, basestate, self->tzinfo);
- Py_DECREF(basestate);
- }
- return result;
+ basestate = PyString_FromStringAndSize((char *)self->data,
+ _PyDateTime_DATETIME_DATASIZE);
+ if (basestate != NULL) {
+ if (! HASTZINFO(self) || self->tzinfo == Py_None)
+ result = PyTuple_Pack(1, basestate);
+ else
+ result = PyTuple_Pack(2, basestate, self->tzinfo);
+ Py_DECREF(basestate);
+ }
+ return result;
}
static PyObject *
datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
{
- return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
+ return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
}
static PyMethodDef datetime_methods[] = {
- /* Class methods: */
+ /* Class methods: */
- {"now", (PyCFunction)datetime_now,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
+ {"now", (PyCFunction)datetime_now,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
- {"utcnow", (PyCFunction)datetime_utcnow,
- METH_NOARGS | METH_CLASS,
- PyDoc_STR("Return a new datetime representing UTC day and time.")},
+ {"utcnow", (PyCFunction)datetime_utcnow,
+ METH_NOARGS | METH_CLASS,
+ PyDoc_STR("Return a new datetime representing UTC day and time.")},
- {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
+ {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
- {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
- METH_VARARGS | METH_CLASS,
- PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
- "(like time.time()).")},
+ {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
+ METH_VARARGS | METH_CLASS,
+ PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
+ "(like time.time()).")},
- {"strptime", (PyCFunction)datetime_strptime,
- METH_VARARGS | METH_CLASS,
- PyDoc_STR("string, format -> new datetime parsed from a string "
- "(like time.strptime()).")},
+ {"strptime", (PyCFunction)datetime_strptime,
+ METH_VARARGS | METH_CLASS,
+ PyDoc_STR("string, format -> new datetime parsed from a string "
+ "(like time.strptime()).")},
- {"combine", (PyCFunction)datetime_combine,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("date, time -> datetime with same date and time fields")},
+ {"combine", (PyCFunction)datetime_combine,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("date, time -> datetime with same date and time fields")},
- /* Instance methods: */
+ /* Instance methods: */
- {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
- PyDoc_STR("Return date object with same year, month and day.")},
+ {"date", (PyCFunction)datetime_getdate, METH_NOARGS,
+ PyDoc_STR("Return date object with same year, month and day.")},
- {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
- PyDoc_STR("Return time object with same time but with tzinfo=None.")},
+ {"time", (PyCFunction)datetime_gettime, METH_NOARGS,
+ PyDoc_STR("Return time object with same time but with tzinfo=None.")},
- {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
- PyDoc_STR("Return time object with same time and tzinfo.")},
+ {"timetz", (PyCFunction)datetime_gettimetz, METH_NOARGS,
+ PyDoc_STR("Return time object with same time and tzinfo.")},
- {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
- PyDoc_STR("Return ctime() style string.")},
+ {"ctime", (PyCFunction)datetime_ctime, METH_NOARGS,
+ PyDoc_STR("Return ctime() style string.")},
- {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
- PyDoc_STR("Return time tuple, compatible with time.localtime().")},
+ {"timetuple", (PyCFunction)datetime_timetuple, METH_NOARGS,
+ PyDoc_STR("Return time tuple, compatible with time.localtime().")},
- {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
- PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
+ {"utctimetuple", (PyCFunction)datetime_utctimetuple, METH_NOARGS,
+ PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
- {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("[sep] -> string in ISO 8601 format, "
- "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
- "sep is used to separate the year from the time, and "
- "defaults to 'T'.")},
+ {"isoformat", (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("[sep] -> string in ISO 8601 format, "
+ "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
+ "sep is used to separate the year from the time, and "
+ "defaults to 'T'.")},
- {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
+ {"utcoffset", (PyCFunction)datetime_utcoffset, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
- {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.tzname(self).")},
+ {"tzname", (PyCFunction)datetime_tzname, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.tzname(self).")},
- {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
- PyDoc_STR("Return self.tzinfo.dst(self).")},
+ {"dst", (PyCFunction)datetime_dst, METH_NOARGS,
+ PyDoc_STR("Return self.tzinfo.dst(self).")},
- {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("Return datetime with new specified fields.")},
+ {"replace", (PyCFunction)datetime_replace, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("Return datetime with new specified fields.")},
- {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
- PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
+ {"astimezone", (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
+ PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
- {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
- PyDoc_STR("__reduce__() -> (cls, state)")},
+ {"__reduce__", (PyCFunction)datetime_reduce, METH_NOARGS,
+ PyDoc_STR("__reduce__() -> (cls, state)")},
- {NULL, NULL}
+ {NULL, NULL}
};
static char datetime_doc[] =
@@ -4674,61 +4674,61 @@ The year, month and day arguments are required. tzinfo may be None, or an\n\
instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
static PyNumberMethods datetime_as_number = {
- datetime_add, /* nb_add */
- datetime_subtract, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_nonzero */
+ datetime_add, /* nb_add */
+ datetime_subtract, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_nonzero */
};
statichere PyTypeObject PyDateTime_DateTimeType = {
- PyObject_HEAD_INIT(NULL)
- 0, /* ob_size */
- "datetime.datetime", /* tp_name */
- sizeof(PyDateTime_DateTime), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)datetime_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)datetime_repr, /* tp_repr */
- &datetime_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)datetime_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)datetime_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- datetime_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)datetime_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- datetime_methods, /* tp_methods */
- 0, /* tp_members */
- datetime_getset, /* tp_getset */
- &PyDateTime_DateType, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- datetime_alloc, /* tp_alloc */
- datetime_new, /* tp_new */
- 0, /* tp_free */
+ PyObject_HEAD_INIT(NULL)
+ 0, /* ob_size */
+ "datetime.datetime", /* tp_name */
+ sizeof(PyDateTime_DateTime), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)datetime_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)datetime_repr, /* tp_repr */
+ &datetime_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)datetime_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)datetime_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ datetime_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)datetime_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ datetime_methods, /* tp_methods */
+ 0, /* tp_members */
+ datetime_getset, /* tp_getset */
+ &PyDateTime_DateType, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ datetime_alloc, /* tp_alloc */
+ datetime_new, /* tp_new */
+ 0, /* tp_free */
};
/* ---------------------------------------------------------------------------
@@ -4736,191 +4736,191 @@ statichere PyTypeObject PyDateTime_DateTimeType = {
*/
static PyMethodDef module_methods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
/* C API. Clients get at this via PyDateTime_IMPORT, defined in
* datetime.h.
*/
static PyDateTime_CAPI CAPI = {
- &PyDateTime_DateType,
- &PyDateTime_DateTimeType,
- &PyDateTime_TimeType,
- &PyDateTime_DeltaType,
- &PyDateTime_TZInfoType,
- new_date_ex,
- new_datetime_ex,
- new_time_ex,
- new_delta_ex,
- datetime_fromtimestamp,
- date_fromtimestamp
+ &PyDateTime_DateType,
+ &PyDateTime_DateTimeType,
+ &PyDateTime_TimeType,
+ &PyDateTime_DeltaType,
+ &PyDateTime_TZInfoType,
+ new_date_ex,
+ new_datetime_ex,
+ new_time_ex,
+ new_delta_ex,
+ datetime_fromtimestamp,
+ date_fromtimestamp
};
PyMODINIT_FUNC
initdatetime(void)
{
- PyObject *m; /* a module object */
- PyObject *d; /* its dict */
- PyObject *x;
-
- m = Py_InitModule3("datetime", module_methods,
- "Fast implementation of the datetime type.");
- if (m == NULL)
- return;
-
- if (PyType_Ready(&PyDateTime_DateType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_DeltaType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_TimeType) < 0)
- return;
- if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
- return;
-
- /* timedelta values */
- d = PyDateTime_DeltaType.tp_dict;
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return;
- Py_DECREF(x);
-
- /* date values */
- d = PyDateTime_DateType.tp_dict;
-
- x = new_date(1, 1, 1);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_date(MAXYEAR, 12, 31);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(1, 0, 0, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- Py_DECREF(x);
-
- /* time values */
- d = PyDateTime_TimeType.tp_dict;
-
- x = new_time(0, 0, 0, 0, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_time(23, 59, 59, 999999, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- Py_DECREF(x);
-
- /* datetime values */
- d = PyDateTime_DateTimeType.tp_dict;
-
- x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
- if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
- return;
- Py_DECREF(x);
-
- x = new_delta(0, 0, 1, 0);
- if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
- return;
- Py_DECREF(x);
-
- /* module initialization */
- PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
- PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
-
- Py_INCREF(&PyDateTime_DateType);
- PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
-
- Py_INCREF(&PyDateTime_DateTimeType);
- PyModule_AddObject(m, "datetime",
- (PyObject *)&PyDateTime_DateTimeType);
-
- Py_INCREF(&PyDateTime_TimeType);
- PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
-
- Py_INCREF(&PyDateTime_DeltaType);
- PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
-
- Py_INCREF(&PyDateTime_TZInfoType);
- PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
-
- x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
- if (x == NULL)
- return;
- PyModule_AddObject(m, "datetime_CAPI", x);
-
- /* A 4-year cycle has an extra leap day over what we'd get from
- * pasting together 4 single years.
- */
- assert(DI4Y == 4 * 365 + 1);
- assert(DI4Y == days_before_year(4+1));
-
- /* Similarly, a 400-year cycle has an extra leap day over what we'd
- * get from pasting together 4 100-year cycles.
- */
- assert(DI400Y == 4 * DI100Y + 1);
- assert(DI400Y == days_before_year(400+1));
-
- /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
- * pasting together 25 4-year cycles.
- */
- assert(DI100Y == 25 * DI4Y - 1);
- assert(DI100Y == days_before_year(100+1));
-
- us_per_us = PyInt_FromLong(1);
- us_per_ms = PyInt_FromLong(1000);
- us_per_second = PyInt_FromLong(1000000);
- us_per_minute = PyInt_FromLong(60000000);
- seconds_per_day = PyInt_FromLong(24 * 3600);
- if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
- us_per_minute == NULL || seconds_per_day == NULL)
- return;
-
- /* The rest are too big for 32-bit ints, but even
- * us_per_week fits in 40 bits, so doubles should be exact.
- */
- us_per_hour = PyLong_FromDouble(3600000000.0);
- us_per_day = PyLong_FromDouble(86400000000.0);
- us_per_week = PyLong_FromDouble(604800000000.0);
- if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
- return;
+ PyObject *m; /* a module object */
+ PyObject *d; /* its dict */
+ PyObject *x;
+
+ m = Py_InitModule3("datetime", module_methods,
+ "Fast implementation of the datetime type.");
+ if (m == NULL)
+ return;
+
+ if (PyType_Ready(&PyDateTime_DateType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_DeltaType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_TimeType) < 0)
+ return;
+ if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
+ return;
+
+ /* timedelta values */
+ d = PyDateTime_DeltaType.tp_dict;
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ /* date values */
+ d = PyDateTime_DateType.tp_dict;
+
+ x = new_date(1, 1, 1);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_date(MAXYEAR, 12, 31);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(1, 0, 0, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ /* time values */
+ d = PyDateTime_TimeType.tp_dict;
+
+ x = new_time(0, 0, 0, 0, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_time(23, 59, 59, 999999, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ /* datetime values */
+ d = PyDateTime_DateTimeType.tp_dict;
+
+ x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
+ if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ x = new_delta(0, 0, 1, 0);
+ if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
+ return;
+ Py_DECREF(x);
+
+ /* module initialization */
+ PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
+ PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
+
+ Py_INCREF(&PyDateTime_DateType);
+ PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
+
+ Py_INCREF(&PyDateTime_DateTimeType);
+ PyModule_AddObject(m, "datetime",
+ (PyObject *)&PyDateTime_DateTimeType);
+
+ Py_INCREF(&PyDateTime_TimeType);
+ PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
+
+ Py_INCREF(&PyDateTime_DeltaType);
+ PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
+
+ Py_INCREF(&PyDateTime_TZInfoType);
+ PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
+
+ x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
+ if (x == NULL)
+ return;
+ PyModule_AddObject(m, "datetime_CAPI", x);
+
+ /* A 4-year cycle has an extra leap day over what we'd get from
+ * pasting together 4 single years.
+ */
+ assert(DI4Y == 4 * 365 + 1);
+ assert(DI4Y == days_before_year(4+1));
+
+ /* Similarly, a 400-year cycle has an extra leap day over what we'd
+ * get from pasting together 4 100-year cycles.
+ */
+ assert(DI400Y == 4 * DI100Y + 1);
+ assert(DI400Y == days_before_year(400+1));
+
+ /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
+ * pasting together 25 4-year cycles.
+ */
+ assert(DI100Y == 25 * DI4Y - 1);
+ assert(DI100Y == days_before_year(100+1));
+
+ us_per_us = PyInt_FromLong(1);
+ us_per_ms = PyInt_FromLong(1000);
+ us_per_second = PyInt_FromLong(1000000);
+ us_per_minute = PyInt_FromLong(60000000);
+ seconds_per_day = PyInt_FromLong(24 * 3600);
+ if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
+ us_per_minute == NULL || seconds_per_day == NULL)
+ return;
+
+ /* The rest are too big for 32-bit ints, but even
+ * us_per_week fits in 40 bits, so doubles should be exact.
+ */
+ us_per_hour = PyLong_FromDouble(3600000000.0);
+ us_per_day = PyLong_FromDouble(86400000000.0);
+ us_per_week = PyLong_FromDouble(604800000000.0);
+ if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
+ return;
}
/* ---------------------------------------------------------------------------
Some time zone algebra. For a datetime x, let
x.n = x stripped of its timezone -- its naive time.
x.o = x.utcoffset(), and assuming that doesn't raise an exception or
- return None
+ return None
x.d = x.dst(), and assuming that doesn't raise an exception or
- return None
+ return None
x.s = x's standard offset, x.o - x.d
Now some derived rules, where k is a duration (timedelta).
@@ -5042,13 +5042,13 @@ the justifications for the kinds of substitutions we've done several times
already):
diff' = x.n - (z'.n - z'.o) = replacing z'.n via [7]
- x.n - (z.n + diff - z'.o) = replacing diff via [6]
- x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
- x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
- - z.n + z.n - z.o + z'.o = cancel z.n
- - z.o + z'.o = #1 twice
- -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
- z'.d - z.d
+ x.n - (z.n + diff - z'.o) = replacing diff via [6]
+ x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
+ x.n - z.n - x.n + z.n - z.o + z'.o = cancel x.n
+ - z.n + z.n - z.o + z'.o = cancel z.n
+ - z.o + z'.o = #1 twice
+ -z.s - z.d + z'.s + z'.d = z and z' have same tzinfo
+ z'.d - z.d
So z' is UTC-equivalent to x iff z'.d = z.d at this point. If they are equal,
we've found the UTC-equivalent so are done. In fact, we stop with [7] and
diff --git a/Modules/dbmmodule.c b/Modules/dbmmodule.c
index 0c50b54..f9c99a8 100644
--- a/Modules/dbmmodule.c
+++ b/Modules/dbmmodule.c
@@ -32,9 +32,9 @@ static char *which_dbm = "Berkeley DB";
#endif
typedef struct {
- PyObject_HEAD
- int di_size; /* -1 means recompute */
- DBM *di_dbm;
+ PyObject_HEAD
+ int di_size; /* -1 means recompute */
+ DBM *di_dbm;
} dbmobject;
static PyTypeObject Dbmtype;
@@ -49,18 +49,18 @@ static PyObject *DbmError;
static PyObject *
newdbmobject(char *file, int flags, int mode)
{
- dbmobject *dp;
-
- dp = PyObject_New(dbmobject, &Dbmtype);
- if (dp == NULL)
- return NULL;
- dp->di_size = -1;
- if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) {
- PyErr_SetFromErrno(DbmError);
- Py_DECREF(dp);
- return NULL;
- }
- return (PyObject *)dp;
+ dbmobject *dp;
+
+ dp = PyObject_New(dbmobject, &Dbmtype);
+ if (dp == NULL)
+ return NULL;
+ dp->di_size = -1;
+ if ( (dp->di_dbm = dbm_open(file, flags, mode)) == 0 ) {
+ PyErr_SetFromErrno(DbmError);
+ Py_DECREF(dp);
+ return NULL;
+ }
+ return (PyObject *)dp;
}
/* Methods */
@@ -68,119 +68,119 @@ newdbmobject(char *file, int flags, int mode)
static void
dbm_dealloc(register dbmobject *dp)
{
- if ( dp->di_dbm )
- dbm_close(dp->di_dbm);
- PyObject_Del(dp);
+ if ( dp->di_dbm )
+ dbm_close(dp->di_dbm);
+ PyObject_Del(dp);
}
static Py_ssize_t
dbm_length(dbmobject *dp)
{
- if (dp->di_dbm == NULL) {
- PyErr_SetString(DbmError, "DBM object has already been closed");
- return -1;
- }
- if ( dp->di_size < 0 ) {
- datum key;
- int size;
-
- size = 0;
- for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
- key = dbm_nextkey(dp->di_dbm))
- size++;
- dp->di_size = size;
- }
- return dp->di_size;
+ if (dp->di_dbm == NULL) {
+ PyErr_SetString(DbmError, "DBM object has already been closed");
+ return -1;
+ }
+ if ( dp->di_size < 0 ) {
+ datum key;
+ int size;
+
+ size = 0;
+ for ( key=dbm_firstkey(dp->di_dbm); key.dptr;
+ key = dbm_nextkey(dp->di_dbm))
+ size++;
+ dp->di_size = size;
+ }
+ return dp->di_size;
}
static PyObject *
dbm_subscript(dbmobject *dp, register PyObject *key)
{
- datum drec, krec;
- int tmp_size;
-
- if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
- return NULL;
-
- krec.dsize = tmp_size;
- check_dbmobject_open(dp);
- drec = dbm_fetch(dp->di_dbm, krec);
- if ( drec.dptr == 0 ) {
- PyErr_SetString(PyExc_KeyError,
- PyString_AS_STRING((PyStringObject *)key));
- return NULL;
- }
- if ( dbm_error(dp->di_dbm) ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "");
- return NULL;
- }
- return PyString_FromStringAndSize(drec.dptr, drec.dsize);
+ datum drec, krec;
+ int tmp_size;
+
+ if (!PyArg_Parse(key, "s#", &krec.dptr, &tmp_size) )
+ return NULL;
+
+ krec.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ drec = dbm_fetch(dp->di_dbm, krec);
+ if ( drec.dptr == 0 ) {
+ PyErr_SetString(PyExc_KeyError,
+ PyString_AS_STRING((PyStringObject *)key));
+ return NULL;
+ }
+ if ( dbm_error(dp->di_dbm) ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(drec.dptr, drec.dsize);
}
static int
dbm_ass_sub(dbmobject *dp, PyObject *v, PyObject *w)
{
- datum krec, drec;
- int tmp_size;
-
- if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have string indices only");
- return -1;
- }
- krec.dsize = tmp_size;
- if (dp->di_dbm == NULL) {
- PyErr_SetString(DbmError, "DBM object has already been closed");
- return -1;
+ datum krec, drec;
+ int tmp_size;
+
+ if ( !PyArg_Parse(v, "s#", &krec.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have string indices only");
+ return -1;
+ }
+ krec.dsize = tmp_size;
+ if (dp->di_dbm == NULL) {
+ PyErr_SetString(DbmError, "DBM object has already been closed");
+ return -1;
+ }
+ dp->di_size = -1;
+ if (w == NULL) {
+ if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(PyExc_KeyError,
+ PyString_AS_STRING((PyStringObject *)v));
+ return -1;
+ }
+ } else {
+ if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
+ PyErr_SetString(PyExc_TypeError,
+ "dbm mappings have string elements only");
+ return -1;
+ }
+ drec.dsize = tmp_size;
+ if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError,
+ "cannot add item to database");
+ return -1;
}
- dp->di_size = -1;
- if (w == NULL) {
- if ( dbm_delete(dp->di_dbm, krec) < 0 ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(PyExc_KeyError,
- PyString_AS_STRING((PyStringObject *)v));
- return -1;
- }
- } else {
- if ( !PyArg_Parse(w, "s#", &drec.dptr, &tmp_size) ) {
- PyErr_SetString(PyExc_TypeError,
- "dbm mappings have string elements only");
- return -1;
- }
- drec.dsize = tmp_size;
- if ( dbm_store(dp->di_dbm, krec, drec, DBM_REPLACE) < 0 ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError,
- "cannot add item to database");
- return -1;
- }
- }
- if ( dbm_error(dp->di_dbm) ) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "");
- return -1;
- }
- return 0;
+ }
+ if ( dbm_error(dp->di_dbm) ) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "");
+ return -1;
+ }
+ return 0;
}
static int
dbm_contains(register dbmobject *dp, PyObject *v)
{
- datum key, val;
-
- if (PyString_AsStringAndSize(v, (char **)&key.dptr,
- (Py_ssize_t *)&key.dsize)) {
- return -1;
- }
-
- /* Expand check_dbmobject_open to return -1 */
- if (dp->di_dbm == NULL) {
- PyErr_SetString(DbmError, "DBM object has already been closed");
- return -1;
- }
- val = dbm_fetch(dp->di_dbm, key);
- return val.dptr != NULL;
+ datum key, val;
+
+ if (PyString_AsStringAndSize(v, (char **)&key.dptr,
+ (Py_ssize_t *)&key.dsize)) {
+ return -1;
+ }
+
+ /* Expand check_dbmobject_open to return -1 */
+ if (dp->di_dbm == NULL) {
+ PyErr_SetString(DbmError, "DBM object has already been closed");
+ return -1;
+ }
+ val = dbm_fetch(dp->di_dbm, key);
+ return val.dptr != NULL;
}
static PySequenceMethods dbm_as_sequence = {
@@ -197,159 +197,159 @@ static PySequenceMethods dbm_as_sequence = {
};
static PyMappingMethods dbm_as_mapping = {
- (lenfunc)dbm_length, /*mp_length*/
- (binaryfunc)dbm_subscript, /*mp_subscript*/
- (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
+ (lenfunc)dbm_length, /*mp_length*/
+ (binaryfunc)dbm_subscript, /*mp_subscript*/
+ (objobjargproc)dbm_ass_sub, /*mp_ass_subscript*/
};
static PyObject *
dbm__close(register dbmobject *dp, PyObject *unused)
{
- if (dp->di_dbm)
- dbm_close(dp->di_dbm);
- dp->di_dbm = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (dp->di_dbm)
+ dbm_close(dp->di_dbm);
+ dp->di_dbm = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
dbm_keys(register dbmobject *dp, PyObject *unused)
{
- register PyObject *v, *item;
- datum key;
- int err;
-
- check_dbmobject_open(dp);
- v = PyList_New(0);
- if (v == NULL)
- return NULL;
- for (key = dbm_firstkey(dp->di_dbm); key.dptr;
- key = dbm_nextkey(dp->di_dbm)) {
- item = PyString_FromStringAndSize(key.dptr, key.dsize);
- if (item == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- err = PyList_Append(v, item);
- Py_DECREF(item);
- if (err != 0) {
- Py_DECREF(v);
- return NULL;
- }
- }
- return v;
+ register PyObject *v, *item;
+ datum key;
+ int err;
+
+ check_dbmobject_open(dp);
+ v = PyList_New(0);
+ if (v == NULL)
+ return NULL;
+ for (key = dbm_firstkey(dp->di_dbm); key.dptr;
+ key = dbm_nextkey(dp->di_dbm)) {
+ item = PyString_FromStringAndSize(key.dptr, key.dsize);
+ if (item == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ err = PyList_Append(v, item);
+ Py_DECREF(item);
+ if (err != 0) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ }
+ return v;
}
static PyObject *
dbm_has_key(register dbmobject *dp, PyObject *args)
{
- char *tmp_ptr;
- datum key, val;
- int tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#:has_key", &tmp_ptr, &tmp_size))
- return NULL;
- key.dptr = tmp_ptr;
- key.dsize = tmp_size;
- check_dbmobject_open(dp);
- val = dbm_fetch(dp->di_dbm, key);
- return PyInt_FromLong(val.dptr != NULL);
+ char *tmp_ptr;
+ datum key, val;
+ int tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#:has_key", &tmp_ptr, &tmp_size))
+ return NULL;
+ key.dptr = tmp_ptr;
+ key.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ val = dbm_fetch(dp->di_dbm, key);
+ return PyInt_FromLong(val.dptr != NULL);
}
static PyObject *
dbm_get(register dbmobject *dp, PyObject *args)
{
- datum key, val;
- PyObject *defvalue = Py_None;
- char *tmp_ptr;
- int tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#|O:get",
- &tmp_ptr, &tmp_size, &defvalue))
- return NULL;
- key.dptr = tmp_ptr;
- key.dsize = tmp_size;
- check_dbmobject_open(dp);
- val = dbm_fetch(dp->di_dbm, key);
- if (val.dptr != NULL)
- return PyString_FromStringAndSize(val.dptr, val.dsize);
- else {
- Py_INCREF(defvalue);
- return defvalue;
- }
+ datum key, val;
+ PyObject *defvalue = Py_None;
+ char *tmp_ptr;
+ int tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#|O:get",
+ &tmp_ptr, &tmp_size, &defvalue))
+ return NULL;
+ key.dptr = tmp_ptr;
+ key.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ val = dbm_fetch(dp->di_dbm, key);
+ if (val.dptr != NULL)
+ return PyString_FromStringAndSize(val.dptr, val.dsize);
+ else {
+ Py_INCREF(defvalue);
+ return defvalue;
+ }
}
static PyObject *
dbm_setdefault(register dbmobject *dp, PyObject *args)
{
- datum key, val;
- PyObject *defvalue = NULL;
- char *tmp_ptr;
- int tmp_size;
-
- if (!PyArg_ParseTuple(args, "s#|S:setdefault",
- &tmp_ptr, &tmp_size, &defvalue))
- return NULL;
- key.dptr = tmp_ptr;
- key.dsize = tmp_size;
- check_dbmobject_open(dp);
- val = dbm_fetch(dp->di_dbm, key);
- if (val.dptr != NULL)
- return PyString_FromStringAndSize(val.dptr, val.dsize);
- if (defvalue == NULL) {
- defvalue = PyString_FromStringAndSize(NULL, 0);
- if (defvalue == NULL)
- return NULL;
- }
- else
- Py_INCREF(defvalue);
- val.dptr = PyString_AS_STRING(defvalue);
- val.dsize = PyString_GET_SIZE(defvalue);
- if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
- dbm_clearerr(dp->di_dbm);
- PyErr_SetString(DbmError, "cannot add item to database");
- return NULL;
- }
- return defvalue;
+ datum key, val;
+ PyObject *defvalue = NULL;
+ char *tmp_ptr;
+ int tmp_size;
+
+ if (!PyArg_ParseTuple(args, "s#|S:setdefault",
+ &tmp_ptr, &tmp_size, &defvalue))
+ return NULL;
+ key.dptr = tmp_ptr;
+ key.dsize = tmp_size;
+ check_dbmobject_open(dp);
+ val = dbm_fetch(dp->di_dbm, key);
+ if (val.dptr != NULL)
+ return PyString_FromStringAndSize(val.dptr, val.dsize);
+ if (defvalue == NULL) {
+ defvalue = PyString_FromStringAndSize(NULL, 0);
+ if (defvalue == NULL)
+ return NULL;
+ }
+ else
+ Py_INCREF(defvalue);
+ val.dptr = PyString_AS_STRING(defvalue);
+ val.dsize = PyString_GET_SIZE(defvalue);
+ if (dbm_store(dp->di_dbm, key, val, DBM_INSERT) < 0) {
+ dbm_clearerr(dp->di_dbm);
+ PyErr_SetString(DbmError, "cannot add item to database");
+ return NULL;
+ }
+ return defvalue;
}
static PyMethodDef dbm_methods[] = {
- {"close", (PyCFunction)dbm__close, METH_NOARGS,
- "close()\nClose the database."},
- {"keys", (PyCFunction)dbm_keys, METH_NOARGS,
- "keys() -> list\nReturn a list of all keys in the database."},
- {"has_key", (PyCFunction)dbm_has_key, METH_VARARGS,
- "has_key(key} -> boolean\nReturn true iff key is in the database."},
- {"get", (PyCFunction)dbm_get, METH_VARARGS,
- "get(key[, default]) -> value\n"
- "Return the value for key if present, otherwise default."},
- {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS,
- "setdefault(key[, default]) -> value\n"
- "Return the value for key if present, otherwise default. If key\n"
- "is not in the database, it is inserted with default as the value."},
- {NULL, NULL} /* sentinel */
+ {"close", (PyCFunction)dbm__close, METH_NOARGS,
+ "close()\nClose the database."},
+ {"keys", (PyCFunction)dbm_keys, METH_NOARGS,
+ "keys() -> list\nReturn a list of all keys in the database."},
+ {"has_key", (PyCFunction)dbm_has_key, METH_VARARGS,
+ "has_key(key} -> boolean\nReturn true iff key is in the database."},
+ {"get", (PyCFunction)dbm_get, METH_VARARGS,
+ "get(key[, default]) -> value\n"
+ "Return the value for key if present, otherwise default."},
+ {"setdefault", (PyCFunction)dbm_setdefault, METH_VARARGS,
+ "setdefault(key[, default]) -> value\n"
+ "Return the value for key if present, otherwise default. If key\n"
+ "is not in the database, it is inserted with default as the value."},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
dbm_getattr(dbmobject *dp, char *name)
{
- return Py_FindMethod(dbm_methods, (PyObject *)dp, name);
+ return Py_FindMethod(dbm_methods, (PyObject *)dp, name);
}
static PyTypeObject Dbmtype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "dbm.dbm",
- sizeof(dbmobject),
- 0,
- (destructor)dbm_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)dbm_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- 0, /*tp_as_number*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "dbm.dbm",
+ sizeof(dbmobject),
+ 0,
+ (destructor)dbm_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)dbm_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ 0, /*tp_as_number*/
&dbm_as_sequence, /*tp_as_sequence*/
- &dbm_as_mapping, /*tp_as_mapping*/
+ &dbm_as_mapping, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
@@ -364,54 +364,54 @@ static PyTypeObject Dbmtype = {
static PyObject *
dbmopen(PyObject *self, PyObject *args)
{
- char *name;
- char *flags = "r";
- int iflags;
- int mode = 0666;
-
- if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) )
- return NULL;
- if ( strcmp(flags, "r") == 0 )
- iflags = O_RDONLY;
- else if ( strcmp(flags, "w") == 0 )
- iflags = O_RDWR;
- else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
- iflags = O_RDWR|O_CREAT;
- else if ( strcmp(flags, "c") == 0 )
- iflags = O_RDWR|O_CREAT;
- else if ( strcmp(flags, "n") == 0 )
- iflags = O_RDWR|O_CREAT|O_TRUNC;
- else {
- PyErr_SetString(DbmError,
- "arg 2 to open should be 'r', 'w', 'c', or 'n'");
- return NULL;
- }
- return newdbmobject(name, iflags, mode);
+ char *name;
+ char *flags = "r";
+ int iflags;
+ int mode = 0666;
+
+ if ( !PyArg_ParseTuple(args, "s|si:open", &name, &flags, &mode) )
+ return NULL;
+ if ( strcmp(flags, "r") == 0 )
+ iflags = O_RDONLY;
+ else if ( strcmp(flags, "w") == 0 )
+ iflags = O_RDWR;
+ else if ( strcmp(flags, "rw") == 0 ) /* B/W compat */
+ iflags = O_RDWR|O_CREAT;
+ else if ( strcmp(flags, "c") == 0 )
+ iflags = O_RDWR|O_CREAT;
+ else if ( strcmp(flags, "n") == 0 )
+ iflags = O_RDWR|O_CREAT|O_TRUNC;
+ else {
+ PyErr_SetString(DbmError,
+ "arg 2 to open should be 'r', 'w', 'c', or 'n'");
+ return NULL;
+ }
+ return newdbmobject(name, iflags, mode);
}
static PyMethodDef dbmmodule_methods[] = {
- { "open", (PyCFunction)dbmopen, METH_VARARGS,
- "open(path[, flag[, mode]]) -> mapping\n"
- "Return a database object."},
- { 0, 0 },
+ { "open", (PyCFunction)dbmopen, METH_VARARGS,
+ "open(path[, flag[, mode]]) -> mapping\n"
+ "Return a database object."},
+ { 0, 0 },
};
PyMODINIT_FUNC
initdbm(void) {
- PyObject *m, *d, *s;
-
- Dbmtype.ob_type = &PyType_Type;
- m = Py_InitModule("dbm", dbmmodule_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- if (DbmError == NULL)
- DbmError = PyErr_NewException("dbm.error", NULL, NULL);
- s = PyString_FromString(which_dbm);
- if (s != NULL) {
- PyDict_SetItemString(d, "library", s);
- Py_DECREF(s);
- }
- if (DbmError != NULL)
- PyDict_SetItemString(d, "error", DbmError);
+ PyObject *m, *d, *s;
+
+ Dbmtype.ob_type = &PyType_Type;
+ m = Py_InitModule("dbm", dbmmodule_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ if (DbmError == NULL)
+ DbmError = PyErr_NewException("dbm.error", NULL, NULL);
+ s = PyString_FromString(which_dbm);
+ if (s != NULL) {
+ PyDict_SetItemString(d, "library", s);
+ Py_DECREF(s);
+ }
+ if (DbmError != NULL)
+ PyDict_SetItemString(d, "error", DbmError);
}
diff --git a/Modules/dlmodule.c b/Modules/dlmodule.c
index b2ea4f5..c349ad0 100644
--- a/Modules/dlmodule.c
+++ b/Modules/dlmodule.c
@@ -15,8 +15,8 @@
typedef void *PyUnivPtr;
typedef struct {
- PyObject_HEAD
- PyUnivPtr *dl_handle;
+ PyObject_HEAD
+ PyUnivPtr *dl_handle;
} dlobject;
static PyTypeObject Dltype;
@@ -26,196 +26,196 @@ static PyObject *Dlerror;
static PyObject *
newdlobject(PyUnivPtr *handle)
{
- dlobject *xp;
- xp = PyObject_New(dlobject, &Dltype);
- if (xp == NULL)
- return NULL;
- xp->dl_handle = handle;
- return (PyObject *)xp;
+ dlobject *xp;
+ xp = PyObject_New(dlobject, &Dltype);
+ if (xp == NULL)
+ return NULL;
+ xp->dl_handle = handle;
+ return (PyObject *)xp;
}
static void
dl_dealloc(dlobject *xp)
{
- if (xp->dl_handle != NULL)
- dlclose(xp->dl_handle);
- PyObject_Del(xp);
+ if (xp->dl_handle != NULL)
+ dlclose(xp->dl_handle);
+ PyObject_Del(xp);
}
static PyObject *
dl_close(dlobject *xp)
{
- if (xp->dl_handle != NULL) {
- dlclose(xp->dl_handle);
- xp->dl_handle = NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (xp->dl_handle != NULL) {
+ dlclose(xp->dl_handle);
+ xp->dl_handle = NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
dl_sym(dlobject *xp, PyObject *args)
{
- char *name;
- PyUnivPtr *func;
- if (PyString_Check(args)) {
- name = PyString_AS_STRING(args);
- } else {
- PyErr_Format(PyExc_TypeError, "expected string, found %.200s",
- Py_TYPE(args)->tp_name);
- return NULL;
- }
- func = dlsym(xp->dl_handle, name);
- if (func == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyInt_FromLong((long)func);
+ char *name;
+ PyUnivPtr *func;
+ if (PyString_Check(args)) {
+ name = PyString_AS_STRING(args);
+ } else {
+ PyErr_Format(PyExc_TypeError, "expected string, found %.200s",
+ Py_TYPE(args)->tp_name);
+ return NULL;
+ }
+ func = dlsym(xp->dl_handle, name);
+ if (func == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyInt_FromLong((long)func);
}
static PyObject *
dl_call(dlobject *xp, PyObject *args)
{
- PyObject *name;
- long (*func)(long, long, long, long, long,
- long, long, long, long, long);
- long alist[10];
- long res;
- Py_ssize_t i;
- Py_ssize_t n = PyTuple_Size(args);
- if (n < 1) {
- PyErr_SetString(PyExc_TypeError, "at least a name is needed");
- return NULL;
- }
- name = PyTuple_GetItem(args, 0);
- if (!PyString_Check(name)) {
- PyErr_SetString(PyExc_TypeError,
- "function name must be a string");
- return NULL;
- }
- func = (long (*)(long, long, long, long, long,
- long, long, long, long, long))
- dlsym(xp->dl_handle, PyString_AsString(name));
- if (func == NULL) {
- PyErr_SetString(PyExc_ValueError, dlerror());
- return NULL;
- }
- if (n-1 > 10) {
- PyErr_SetString(PyExc_TypeError,
- "too many arguments (max 10)");
- return NULL;
- }
- for (i = 1; i < n; i++) {
- PyObject *v = PyTuple_GetItem(args, i);
- if (PyInt_Check(v))
- alist[i-1] = PyInt_AsLong(v);
- else if (PyString_Check(v))
- alist[i-1] = (long)PyString_AsString(v);
- else if (v == Py_None)
- alist[i-1] = (long) ((char *)NULL);
- else {
- PyErr_SetString(PyExc_TypeError,
- "arguments must be int, string or None");
- return NULL;
- }
- }
- for (; i <= 10; i++)
- alist[i-1] = 0;
- res = (*func)(alist[0], alist[1], alist[2], alist[3], alist[4],
- alist[5], alist[6], alist[7], alist[8], alist[9]);
- return PyInt_FromLong(res);
+ PyObject *name;
+ long (*func)(long, long, long, long, long,
+ long, long, long, long, long);
+ long alist[10];
+ long res;
+ Py_ssize_t i;
+ Py_ssize_t n = PyTuple_Size(args);
+ if (n < 1) {
+ PyErr_SetString(PyExc_TypeError, "at least a name is needed");
+ return NULL;
+ }
+ name = PyTuple_GetItem(args, 0);
+ if (!PyString_Check(name)) {
+ PyErr_SetString(PyExc_TypeError,
+ "function name must be a string");
+ return NULL;
+ }
+ func = (long (*)(long, long, long, long, long,
+ long, long, long, long, long))
+ dlsym(xp->dl_handle, PyString_AsString(name));
+ if (func == NULL) {
+ PyErr_SetString(PyExc_ValueError, dlerror());
+ return NULL;
+ }
+ if (n-1 > 10) {
+ PyErr_SetString(PyExc_TypeError,
+ "too many arguments (max 10)");
+ return NULL;
+ }
+ for (i = 1; i < n; i++) {
+ PyObject *v = PyTuple_GetItem(args, i);
+ if (PyInt_Check(v))
+ alist[i-1] = PyInt_AsLong(v);
+ else if (PyString_Check(v))
+ alist[i-1] = (long)PyString_AsString(v);
+ else if (v == Py_None)
+ alist[i-1] = (long) ((char *)NULL);
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "arguments must be int, string or None");
+ return NULL;
+ }
+ }
+ for (; i <= 10; i++)
+ alist[i-1] = 0;
+ res = (*func)(alist[0], alist[1], alist[2], alist[3], alist[4],
+ alist[5], alist[6], alist[7], alist[8], alist[9]);
+ return PyInt_FromLong(res);
}
static PyMethodDef dlobject_methods[] = {
- {"call", (PyCFunction)dl_call, METH_VARARGS},
- {"sym", (PyCFunction)dl_sym, METH_O},
- {"close", (PyCFunction)dl_close, METH_NOARGS},
- {NULL, NULL} /* Sentinel */
+ {"call", (PyCFunction)dl_call, METH_VARARGS},
+ {"sym", (PyCFunction)dl_sym, METH_O},
+ {"close", (PyCFunction)dl_close, METH_NOARGS},
+ {NULL, NULL} /* Sentinel */
};
static PyObject *
dl_getattr(dlobject *xp, char *name)
{
- return Py_FindMethod(dlobject_methods, (PyObject *)xp, name);
+ return Py_FindMethod(dlobject_methods, (PyObject *)xp, name);
}
static PyTypeObject Dltype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "dl.dl", /*tp_name*/
- sizeof(dlobject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)dl_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)dl_getattr,/*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*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "dl.dl", /*tp_name*/
+ sizeof(dlobject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)dl_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)dl_getattr,/*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*/
};
static PyObject *
dl_open(PyObject *self, PyObject *args)
{
- char *name;
- int mode;
- PyUnivPtr *handle;
- if (sizeof(int) != sizeof(long) ||
- sizeof(long) != sizeof(char *)) {
- PyErr_SetString(PyExc_SystemError,
+ char *name;
+ int mode;
+ PyUnivPtr *handle;
+ if (sizeof(int) != sizeof(long) ||
+ sizeof(long) != sizeof(char *)) {
+ PyErr_SetString(PyExc_SystemError,
"module dl requires sizeof(int) == sizeof(long) == sizeof(char*)");
- return NULL;
- }
+ return NULL;
+ }
- if (PyArg_ParseTuple(args, "z:open", &name))
- mode = RTLD_LAZY;
- else {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "zi:open", &name, &mode))
- return NULL;
+ if (PyArg_ParseTuple(args, "z:open", &name))
+ mode = RTLD_LAZY;
+ else {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "zi:open", &name, &mode))
+ return NULL;
#ifndef RTLD_NOW
- if (mode != RTLD_LAZY) {
- PyErr_SetString(PyExc_ValueError, "mode must be 1");
- return NULL;
- }
+ if (mode != RTLD_LAZY) {
+ PyErr_SetString(PyExc_ValueError, "mode must be 1");
+ return NULL;
+ }
#endif
- }
- handle = dlopen(name, mode);
- if (handle == NULL) {
- char *errmsg = dlerror();
- if (!errmsg)
- errmsg = "dlopen() error";
- PyErr_SetString(Dlerror, errmsg);
- return NULL;
- }
+ }
+ handle = dlopen(name, mode);
+ if (handle == NULL) {
+ char *errmsg = dlerror();
+ if (!errmsg)
+ errmsg = "dlopen() error";
+ PyErr_SetString(Dlerror, errmsg);
+ return NULL;
+ }
#ifdef __VMS
- /* Under OpenVMS dlopen doesn't do any check, just save the name
- * for later use, so we have to check if the file is readable,
- * the name can be a logical or a file from SYS$SHARE.
- */
- if (access(name, R_OK)) {
- char fname[strlen(name) + 20];
- strcpy(fname, "SYS$SHARE:");
- strcat(fname, name);
- strcat(fname, ".EXE");
- if (access(fname, R_OK)) {
- dlclose(handle);
- PyErr_SetString(Dlerror,
- "File not found or protection violation");
- return NULL;
- }
- }
+ /* Under OpenVMS dlopen doesn't do any check, just save the name
+ * for later use, so we have to check if the file is readable,
+ * the name can be a logical or a file from SYS$SHARE.
+ */
+ if (access(name, R_OK)) {
+ char fname[strlen(name) + 20];
+ strcpy(fname, "SYS$SHARE:");
+ strcat(fname, name);
+ strcat(fname, ".EXE");
+ if (access(fname, R_OK)) {
+ dlclose(handle);
+ PyErr_SetString(Dlerror,
+ "File not found or protection violation");
+ return NULL;
+ }
+ }
#endif
- return newdlobject(handle);
+ return newdlobject(handle);
}
static PyMethodDef dl_methods[] = {
- {"open", dl_open, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"open", dl_open, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
/* From socketmodule.c
@@ -226,59 +226,59 @@ static PyMethodDef dl_methods[] = {
static void
insint(PyObject *d, char *name, int value)
{
- PyObject *v = PyInt_FromLong((long) value);
- if (!v || PyDict_SetItemString(d, name, v))
- PyErr_Clear();
+ PyObject *v = PyInt_FromLong((long) value);
+ if (!v || PyDict_SetItemString(d, name, v))
+ PyErr_Clear();
- Py_XDECREF(v);
+ Py_XDECREF(v);
}
PyMODINIT_FUNC
initdl(void)
{
- PyObject *m, *d, *x;
+ PyObject *m, *d, *x;
if (PyErr_WarnPy3k("the dl module has been removed in "
"Python 3.0; use the ctypes module instead", 2) < 0)
- return;
+ return;
- /* Initialize object type */
- Py_TYPE(&Dltype) = &PyType_Type;
+ /* Initialize object type */
+ Py_TYPE(&Dltype) = &PyType_Type;
- /* Create the module and add the functions */
- m = Py_InitModule("dl", dl_methods);
- if (m == NULL)
- return;
+ /* Create the module and add the functions */
+ m = Py_InitModule("dl", dl_methods);
+ if (m == NULL)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- Dlerror = x = PyErr_NewException("dl.error", NULL, NULL);
- PyDict_SetItemString(d, "error", x);
- x = PyInt_FromLong((long)RTLD_LAZY);
- PyDict_SetItemString(d, "RTLD_LAZY", x);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ Dlerror = x = PyErr_NewException("dl.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", x);
+ x = PyInt_FromLong((long)RTLD_LAZY);
+ PyDict_SetItemString(d, "RTLD_LAZY", x);
#define INSINT(X) insint(d,#X,X)
#ifdef RTLD_NOW
- INSINT(RTLD_NOW);
+ INSINT(RTLD_NOW);
#endif
#ifdef RTLD_NOLOAD
- INSINT(RTLD_NOLOAD);
+ INSINT(RTLD_NOLOAD);
#endif
#ifdef RTLD_GLOBAL
- INSINT(RTLD_GLOBAL);
+ INSINT(RTLD_GLOBAL);
#endif
#ifdef RTLD_LOCAL
- INSINT(RTLD_LOCAL);
+ INSINT(RTLD_LOCAL);
#endif
#ifdef RTLD_PARENT
- INSINT(RTLD_PARENT);
+ INSINT(RTLD_PARENT);
#endif
#ifdef RTLD_GROUP
- INSINT(RTLD_GROUP);
+ INSINT(RTLD_GROUP);
#endif
#ifdef RTLD_WORLD
- INSINT(RTLD_WORLD);
+ INSINT(RTLD_WORLD);
#endif
#ifdef RTLD_NODELETE
- INSINT(RTLD_NODELETE);
+ INSINT(RTLD_NODELETE);
#endif
}
diff --git a/Modules/errnomodule.c b/Modules/errnomodule.c
index 642d721..68c3c49 100644
--- a/Modules/errnomodule.c
+++ b/Modules/errnomodule.c
@@ -10,10 +10,10 @@
/*
* Pull in the system error definitions
- */
+ */
static PyMethodDef errno_methods[] = {
- {NULL, NULL}
+ {NULL, NULL}
};
/* Helper function doing the dictionary inserting */
@@ -21,21 +21,21 @@ static PyMethodDef errno_methods[] = {
static void
_inscode(PyObject *d, PyObject *de, char *name, int code)
{
- PyObject *u = PyString_FromString(name);
- PyObject *v = PyInt_FromLong((long) code);
+ PyObject *u = PyString_FromString(name);
+ PyObject *v = PyInt_FromLong((long) code);
- /* Don't bother checking for errors; they'll be caught at the end
- * of the module initialization function by the caller of
- * initerrno().
- */
- if (u && v) {
- /* insert in modules dict */
- PyDict_SetItem(d, u, v);
- /* insert in errorcode dict */
- PyDict_SetItem(de, v, u);
- }
- Py_XDECREF(u);
- Py_XDECREF(v);
+ /* Don't bother checking for errors; they'll be caught at the end
+ * of the module initialization function by the caller of
+ * initerrno().
+ */
+ if (u && v) {
+ /* insert in modules dict */
+ PyDict_SetItem(d, u, v);
+ /* insert in errorcode dict */
+ PyDict_SetItem(de, v, u);
+ }
+ Py_XDECREF(u);
+ Py_XDECREF(v);
}
PyDoc_STRVAR(errno__doc__,
@@ -55,734 +55,734 @@ e.g. os.strerror(2) could return 'No such file or directory'.");
PyMODINIT_FUNC
initerrno(void)
{
- PyObject *m, *d, *de;
- m = Py_InitModule3("errno", errno_methods, errno__doc__);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- de = PyDict_New();
- if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
- return;
+ PyObject *m, *d, *de;
+ m = Py_InitModule3("errno", errno_methods, errno__doc__);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ de = PyDict_New();
+ if (!d || !de || PyDict_SetItemString(d, "errorcode", de) < 0)
+ return;
/* Macro so I don't have to edit each and every line below... */
#define inscode(d, ds, de, name, code, comment) _inscode(d, de, name, code)
- /*
- * The names and comments are borrowed from linux/include/errno.h,
- * which should be pretty all-inclusive
- */
+ /*
+ * The names and comments are borrowed from linux/include/errno.h,
+ * which should be pretty all-inclusive
+ */
#ifdef ENODEV
- inscode(d, ds, de, "ENODEV", ENODEV, "No such device");
+ inscode(d, ds, de, "ENODEV", ENODEV, "No such device");
#endif
#ifdef ENOCSI
- inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available");
+ inscode(d, ds, de, "ENOCSI", ENOCSI, "No CSI structure available");
#endif
#ifdef EHOSTUNREACH
- inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host");
+ inscode(d, ds, de, "EHOSTUNREACH", EHOSTUNREACH, "No route to host");
#else
#ifdef WSAEHOSTUNREACH
- inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
+ inscode(d, ds, de, "EHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
#endif
#endif
#ifdef ENOMSG
- inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type");
+ inscode(d, ds, de, "ENOMSG", ENOMSG, "No message of desired type");
#endif
#ifdef EUCLEAN
- inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning");
+ inscode(d, ds, de, "EUCLEAN", EUCLEAN, "Structure needs cleaning");
#endif
#ifdef EL2NSYNC
- inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized");
+ inscode(d, ds, de, "EL2NSYNC", EL2NSYNC, "Level 2 not synchronized");
#endif
#ifdef EL2HLT
- inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted");
+ inscode(d, ds, de, "EL2HLT", EL2HLT, "Level 2 halted");
#endif
#ifdef ENODATA
- inscode(d, ds, de, "ENODATA", ENODATA, "No data available");
+ inscode(d, ds, de, "ENODATA", ENODATA, "No data available");
#endif
#ifdef ENOTBLK
- inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required");
+ inscode(d, ds, de, "ENOTBLK", ENOTBLK, "Block device required");
#endif
#ifdef ENOSYS
- inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented");
+ inscode(d, ds, de, "ENOSYS", ENOSYS, "Function not implemented");
#endif
#ifdef EPIPE
- inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe");
+ inscode(d, ds, de, "EPIPE", EPIPE, "Broken pipe");
#endif
#ifdef EINVAL
- inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument");
+ inscode(d, ds, de, "EINVAL", EINVAL, "Invalid argument");
#else
#ifdef WSAEINVAL
- inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument");
+ inscode(d, ds, de, "EINVAL", WSAEINVAL, "Invalid argument");
#endif
#endif
#ifdef EOVERFLOW
- inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type");
+ inscode(d, ds, de, "EOVERFLOW", EOVERFLOW, "Value too large for defined data type");
#endif
#ifdef EADV
- inscode(d, ds, de, "EADV", EADV, "Advertise error");
+ inscode(d, ds, de, "EADV", EADV, "Advertise error");
#endif
#ifdef EINTR
- inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call");
+ inscode(d, ds, de, "EINTR", EINTR, "Interrupted system call");
#else
#ifdef WSAEINTR
- inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call");
+ inscode(d, ds, de, "EINTR", WSAEINTR, "Interrupted system call");
#endif
#endif
#ifdef EUSERS
- inscode(d, ds, de, "EUSERS", EUSERS, "Too many users");
+ inscode(d, ds, de, "EUSERS", EUSERS, "Too many users");
#else
#ifdef WSAEUSERS
- inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users");
+ inscode(d, ds, de, "EUSERS", WSAEUSERS, "Too many users");
#endif
#endif
#ifdef ENOTEMPTY
- inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty");
+ inscode(d, ds, de, "ENOTEMPTY", ENOTEMPTY, "Directory not empty");
#else
#ifdef WSAENOTEMPTY
- inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
+ inscode(d, ds, de, "ENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
#endif
#endif
#ifdef ENOBUFS
- inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available");
+ inscode(d, ds, de, "ENOBUFS", ENOBUFS, "No buffer space available");
#else
#ifdef WSAENOBUFS
- inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available");
+ inscode(d, ds, de, "ENOBUFS", WSAENOBUFS, "No buffer space available");
#endif
#endif
#ifdef EPROTO
- inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error");
+ inscode(d, ds, de, "EPROTO", EPROTO, "Protocol error");
#endif
#ifdef EREMOTE
- inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote");
+ inscode(d, ds, de, "EREMOTE", EREMOTE, "Object is remote");
#else
#ifdef WSAEREMOTE
- inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote");
+ inscode(d, ds, de, "EREMOTE", WSAEREMOTE, "Object is remote");
#endif
#endif
#ifdef ENAVAIL
- inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available");
+ inscode(d, ds, de, "ENAVAIL", ENAVAIL, "No XENIX semaphores available");
#endif
#ifdef ECHILD
- inscode(d, ds, de, "ECHILD", ECHILD, "No child processes");
+ inscode(d, ds, de, "ECHILD", ECHILD, "No child processes");
#endif
#ifdef ELOOP
- inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered");
+ inscode(d, ds, de, "ELOOP", ELOOP, "Too many symbolic links encountered");
#else
#ifdef WSAELOOP
- inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered");
+ inscode(d, ds, de, "ELOOP", WSAELOOP, "Too many symbolic links encountered");
#endif
#endif
#ifdef EXDEV
- inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link");
+ inscode(d, ds, de, "EXDEV", EXDEV, "Cross-device link");
#endif
#ifdef E2BIG
- inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long");
+ inscode(d, ds, de, "E2BIG", E2BIG, "Arg list too long");
#endif
#ifdef ESRCH
- inscode(d, ds, de, "ESRCH", ESRCH, "No such process");
+ inscode(d, ds, de, "ESRCH", ESRCH, "No such process");
#endif
#ifdef EMSGSIZE
- inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long");
+ inscode(d, ds, de, "EMSGSIZE", EMSGSIZE, "Message too long");
#else
#ifdef WSAEMSGSIZE
- inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long");
+ inscode(d, ds, de, "EMSGSIZE", WSAEMSGSIZE, "Message too long");
#endif
#endif
#ifdef EAFNOSUPPORT
- inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol");
+ inscode(d, ds, de, "EAFNOSUPPORT", EAFNOSUPPORT, "Address family not supported by protocol");
#else
#ifdef WSAEAFNOSUPPORT
- inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
+ inscode(d, ds, de, "EAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
#endif
#endif
#ifdef EBADR
- inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor");
+ inscode(d, ds, de, "EBADR", EBADR, "Invalid request descriptor");
#endif
#ifdef EHOSTDOWN
- inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down");
+ inscode(d, ds, de, "EHOSTDOWN", EHOSTDOWN, "Host is down");
#else
#ifdef WSAEHOSTDOWN
- inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down");
+ inscode(d, ds, de, "EHOSTDOWN", WSAEHOSTDOWN, "Host is down");
#endif
#endif
#ifdef EPFNOSUPPORT
- inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported");
+ inscode(d, ds, de, "EPFNOSUPPORT", EPFNOSUPPORT, "Protocol family not supported");
#else
#ifdef WSAEPFNOSUPPORT
- inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
+ inscode(d, ds, de, "EPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
#endif
#endif
#ifdef ENOPROTOOPT
- inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available");
+ inscode(d, ds, de, "ENOPROTOOPT", ENOPROTOOPT, "Protocol not available");
#else
#ifdef WSAENOPROTOOPT
- inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
+ inscode(d, ds, de, "ENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
#endif
#endif
#ifdef EBUSY
- inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy");
+ inscode(d, ds, de, "EBUSY", EBUSY, "Device or resource busy");
#endif
#ifdef EWOULDBLOCK
- inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block");
+ inscode(d, ds, de, "EWOULDBLOCK", EWOULDBLOCK, "Operation would block");
#else
#ifdef WSAEWOULDBLOCK
- inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
+ inscode(d, ds, de, "EWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
#endif
#endif
#ifdef EBADFD
- inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state");
+ inscode(d, ds, de, "EBADFD", EBADFD, "File descriptor in bad state");
#endif
#ifdef EDOTDOT
- inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error");
+ inscode(d, ds, de, "EDOTDOT", EDOTDOT, "RFS specific error");
#endif
#ifdef EISCONN
- inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected");
+ inscode(d, ds, de, "EISCONN", EISCONN, "Transport endpoint is already connected");
#else
#ifdef WSAEISCONN
- inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected");
+ inscode(d, ds, de, "EISCONN", WSAEISCONN, "Transport endpoint is already connected");
#endif
#endif
#ifdef ENOANO
- inscode(d, ds, de, "ENOANO", ENOANO, "No anode");
+ inscode(d, ds, de, "ENOANO", ENOANO, "No anode");
#endif
#ifdef ESHUTDOWN
- inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown");
+ inscode(d, ds, de, "ESHUTDOWN", ESHUTDOWN, "Cannot send after transport endpoint shutdown");
#else
#ifdef WSAESHUTDOWN
- inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
+ inscode(d, ds, de, "ESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
#endif
#endif
#ifdef ECHRNG
- inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range");
+ inscode(d, ds, de, "ECHRNG", ECHRNG, "Channel number out of range");
#endif
#ifdef ELIBBAD
- inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library");
+ inscode(d, ds, de, "ELIBBAD", ELIBBAD, "Accessing a corrupted shared library");
#endif
#ifdef ENONET
- inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network");
+ inscode(d, ds, de, "ENONET", ENONET, "Machine is not on the network");
#endif
#ifdef EBADE
- inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange");
+ inscode(d, ds, de, "EBADE", EBADE, "Invalid exchange");
#endif
#ifdef EBADF
- inscode(d, ds, de, "EBADF", EBADF, "Bad file number");
+ inscode(d, ds, de, "EBADF", EBADF, "Bad file number");
#else
#ifdef WSAEBADF
- inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number");
+ inscode(d, ds, de, "EBADF", WSAEBADF, "Bad file number");
#endif
#endif
#ifdef EMULTIHOP
- inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted");
+ inscode(d, ds, de, "EMULTIHOP", EMULTIHOP, "Multihop attempted");
#endif
#ifdef EIO
- inscode(d, ds, de, "EIO", EIO, "I/O error");
+ inscode(d, ds, de, "EIO", EIO, "I/O error");
#endif
#ifdef EUNATCH
- inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached");
+ inscode(d, ds, de, "EUNATCH", EUNATCH, "Protocol driver not attached");
#endif
#ifdef EPROTOTYPE
- inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket");
+ inscode(d, ds, de, "EPROTOTYPE", EPROTOTYPE, "Protocol wrong type for socket");
#else
#ifdef WSAEPROTOTYPE
- inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
+ inscode(d, ds, de, "EPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
#endif
#endif
#ifdef ENOSPC
- inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device");
+ inscode(d, ds, de, "ENOSPC", ENOSPC, "No space left on device");
#endif
#ifdef ENOEXEC
- inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error");
+ inscode(d, ds, de, "ENOEXEC", ENOEXEC, "Exec format error");
#endif
#ifdef EALREADY
- inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress");
+ inscode(d, ds, de, "EALREADY", EALREADY, "Operation already in progress");
#else
#ifdef WSAEALREADY
- inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress");
+ inscode(d, ds, de, "EALREADY", WSAEALREADY, "Operation already in progress");
#endif
#endif
#ifdef ENETDOWN
- inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down");
+ inscode(d, ds, de, "ENETDOWN", ENETDOWN, "Network is down");
#else
#ifdef WSAENETDOWN
- inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down");
+ inscode(d, ds, de, "ENETDOWN", WSAENETDOWN, "Network is down");
#endif
#endif
#ifdef ENOTNAM
- inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file");
+ inscode(d, ds, de, "ENOTNAM", ENOTNAM, "Not a XENIX named type file");
#endif
#ifdef EACCES
- inscode(d, ds, de, "EACCES", EACCES, "Permission denied");
+ inscode(d, ds, de, "EACCES", EACCES, "Permission denied");
#else
#ifdef WSAEACCES
- inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied");
+ inscode(d, ds, de, "EACCES", WSAEACCES, "Permission denied");
#endif
#endif
#ifdef ELNRNG
- inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range");
+ inscode(d, ds, de, "ELNRNG", ELNRNG, "Link number out of range");
#endif
#ifdef EILSEQ
- inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence");
+ inscode(d, ds, de, "EILSEQ", EILSEQ, "Illegal byte sequence");
#endif
#ifdef ENOTDIR
- inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory");
+ inscode(d, ds, de, "ENOTDIR", ENOTDIR, "Not a directory");
#endif
#ifdef ENOTUNIQ
- inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network");
+ inscode(d, ds, de, "ENOTUNIQ", ENOTUNIQ, "Name not unique on network");
#endif
#ifdef EPERM
- inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted");
+ inscode(d, ds, de, "EPERM", EPERM, "Operation not permitted");
#endif
#ifdef EDOM
- inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func");
+ inscode(d, ds, de, "EDOM", EDOM, "Math argument out of domain of func");
#endif
#ifdef EXFULL
- inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full");
+ inscode(d, ds, de, "EXFULL", EXFULL, "Exchange full");
#endif
#ifdef ECONNREFUSED
- inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused");
+ inscode(d, ds, de, "ECONNREFUSED", ECONNREFUSED, "Connection refused");
#else
#ifdef WSAECONNREFUSED
- inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused");
+ inscode(d, ds, de, "ECONNREFUSED", WSAECONNREFUSED, "Connection refused");
#endif
#endif
#ifdef EISDIR
- inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory");
+ inscode(d, ds, de, "EISDIR", EISDIR, "Is a directory");
#endif
#ifdef EPROTONOSUPPORT
- inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported");
+ inscode(d, ds, de, "EPROTONOSUPPORT", EPROTONOSUPPORT, "Protocol not supported");
#else
#ifdef WSAEPROTONOSUPPORT
- inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
+ inscode(d, ds, de, "EPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
#endif
#endif
#ifdef EROFS
- inscode(d, ds, de, "EROFS", EROFS, "Read-only file system");
+ inscode(d, ds, de, "EROFS", EROFS, "Read-only file system");
#endif
#ifdef EADDRNOTAVAIL
- inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address");
+ inscode(d, ds, de, "EADDRNOTAVAIL", EADDRNOTAVAIL, "Cannot assign requested address");
#else
#ifdef WSAEADDRNOTAVAIL
- inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
+ inscode(d, ds, de, "EADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
#endif
#endif
#ifdef EIDRM
- inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed");
+ inscode(d, ds, de, "EIDRM", EIDRM, "Identifier removed");
#endif
#ifdef ECOMM
- inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send");
+ inscode(d, ds, de, "ECOMM", ECOMM, "Communication error on send");
#endif
#ifdef ESRMNT
- inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error");
+ inscode(d, ds, de, "ESRMNT", ESRMNT, "Srmount error");
#endif
#ifdef EREMOTEIO
- inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error");
+ inscode(d, ds, de, "EREMOTEIO", EREMOTEIO, "Remote I/O error");
#endif
#ifdef EL3RST
- inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset");
+ inscode(d, ds, de, "EL3RST", EL3RST, "Level 3 reset");
#endif
#ifdef EBADMSG
- inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message");
+ inscode(d, ds, de, "EBADMSG", EBADMSG, "Not a data message");
#endif
#ifdef ENFILE
- inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow");
+ inscode(d, ds, de, "ENFILE", ENFILE, "File table overflow");
#endif
#ifdef ELIBMAX
- inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries");
+ inscode(d, ds, de, "ELIBMAX", ELIBMAX, "Attempting to link in too many shared libraries");
#endif
#ifdef ESPIPE
- inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek");
+ inscode(d, ds, de, "ESPIPE", ESPIPE, "Illegal seek");
#endif
#ifdef ENOLINK
- inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed");
+ inscode(d, ds, de, "ENOLINK", ENOLINK, "Link has been severed");
#endif
#ifdef ENETRESET
- inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset");
+ inscode(d, ds, de, "ENETRESET", ENETRESET, "Network dropped connection because of reset");
#else
#ifdef WSAENETRESET
- inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset");
+ inscode(d, ds, de, "ENETRESET", WSAENETRESET, "Network dropped connection because of reset");
#endif
#endif
#ifdef ETIMEDOUT
- inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out");
+ inscode(d, ds, de, "ETIMEDOUT", ETIMEDOUT, "Connection timed out");
#else
#ifdef WSAETIMEDOUT
- inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
+ inscode(d, ds, de, "ETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
#endif
#endif
#ifdef ENOENT
- inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");
+ inscode(d, ds, de, "ENOENT", ENOENT, "No such file or directory");
#endif
#ifdef EEXIST
- inscode(d, ds, de, "EEXIST", EEXIST, "File exists");
+ inscode(d, ds, de, "EEXIST", EEXIST, "File exists");
#endif
#ifdef EDQUOT
- inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded");
+ inscode(d, ds, de, "EDQUOT", EDQUOT, "Quota exceeded");
#else
#ifdef WSAEDQUOT
- inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded");
+ inscode(d, ds, de, "EDQUOT", WSAEDQUOT, "Quota exceeded");
#endif
#endif
#ifdef ENOSTR
- inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream");
+ inscode(d, ds, de, "ENOSTR", ENOSTR, "Device not a stream");
#endif
#ifdef EBADSLT
- inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot");
+ inscode(d, ds, de, "EBADSLT", EBADSLT, "Invalid slot");
#endif
#ifdef EBADRQC
- inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code");
+ inscode(d, ds, de, "EBADRQC", EBADRQC, "Invalid request code");
#endif
#ifdef ELIBACC
- inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library");
+ inscode(d, ds, de, "ELIBACC", ELIBACC, "Can not access a needed shared library");
#endif
#ifdef EFAULT
- inscode(d, ds, de, "EFAULT", EFAULT, "Bad address");
+ inscode(d, ds, de, "EFAULT", EFAULT, "Bad address");
#else
#ifdef WSAEFAULT
- inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address");
+ inscode(d, ds, de, "EFAULT", WSAEFAULT, "Bad address");
#endif
#endif
#ifdef EFBIG
- inscode(d, ds, de, "EFBIG", EFBIG, "File too large");
+ inscode(d, ds, de, "EFBIG", EFBIG, "File too large");
#endif
#ifdef EDEADLK
- inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur");
+ inscode(d, ds, de, "EDEADLK", EDEADLK, "Resource deadlock would occur");
#endif
#ifdef ENOTCONN
- inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected");
+ inscode(d, ds, de, "ENOTCONN", ENOTCONN, "Transport endpoint is not connected");
#else
#ifdef WSAENOTCONN
- inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
+ inscode(d, ds, de, "ENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
#endif
#endif
#ifdef EDESTADDRREQ
- inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required");
+ inscode(d, ds, de, "EDESTADDRREQ", EDESTADDRREQ, "Destination address required");
#else
#ifdef WSAEDESTADDRREQ
- inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
+ inscode(d, ds, de, "EDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
#endif
#endif
#ifdef ELIBSCN
- inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted");
+ inscode(d, ds, de, "ELIBSCN", ELIBSCN, ".lib section in a.out corrupted");
#endif
#ifdef ENOLCK
- inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available");
+ inscode(d, ds, de, "ENOLCK", ENOLCK, "No record locks available");
#endif
#ifdef EISNAM
- inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file");
+ inscode(d, ds, de, "EISNAM", EISNAM, "Is a named type file");
#endif
#ifdef ECONNABORTED
- inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort");
+ inscode(d, ds, de, "ECONNABORTED", ECONNABORTED, "Software caused connection abort");
#else
#ifdef WSAECONNABORTED
- inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
+ inscode(d, ds, de, "ECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
#endif
#endif
#ifdef ENETUNREACH
- inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable");
+ inscode(d, ds, de, "ENETUNREACH", ENETUNREACH, "Network is unreachable");
#else
#ifdef WSAENETUNREACH
- inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable");
+ inscode(d, ds, de, "ENETUNREACH", WSAENETUNREACH, "Network is unreachable");
#endif
#endif
#ifdef ESTALE
- inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle");
+ inscode(d, ds, de, "ESTALE", ESTALE, "Stale NFS file handle");
#else
#ifdef WSAESTALE
- inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle");
+ inscode(d, ds, de, "ESTALE", WSAESTALE, "Stale NFS file handle");
#endif
#endif
#ifdef ENOSR
- inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources");
+ inscode(d, ds, de, "ENOSR", ENOSR, "Out of streams resources");
#endif
#ifdef ENOMEM
- inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory");
+ inscode(d, ds, de, "ENOMEM", ENOMEM, "Out of memory");
#endif
#ifdef ENOTSOCK
- inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket");
+ inscode(d, ds, de, "ENOTSOCK", ENOTSOCK, "Socket operation on non-socket");
#else
#ifdef WSAENOTSOCK
- inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
+ inscode(d, ds, de, "ENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
#endif
#endif
#ifdef ESTRPIPE
- inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error");
+ inscode(d, ds, de, "ESTRPIPE", ESTRPIPE, "Streams pipe error");
#endif
#ifdef EMLINK
- inscode(d, ds, de, "EMLINK", EMLINK, "Too many links");
+ inscode(d, ds, de, "EMLINK", EMLINK, "Too many links");
#endif
#ifdef ERANGE
- inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable");
+ inscode(d, ds, de, "ERANGE", ERANGE, "Math result not representable");
#endif
#ifdef ELIBEXEC
- inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly");
+ inscode(d, ds, de, "ELIBEXEC", ELIBEXEC, "Cannot exec a shared library directly");
#endif
#ifdef EL3HLT
- inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted");
+ inscode(d, ds, de, "EL3HLT", EL3HLT, "Level 3 halted");
#endif
#ifdef ECONNRESET
- inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer");
+ inscode(d, ds, de, "ECONNRESET", ECONNRESET, "Connection reset by peer");
#else
#ifdef WSAECONNRESET
- inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer");
+ inscode(d, ds, de, "ECONNRESET", WSAECONNRESET, "Connection reset by peer");
#endif
#endif
#ifdef EADDRINUSE
- inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use");
+ inscode(d, ds, de, "EADDRINUSE", EADDRINUSE, "Address already in use");
#else
#ifdef WSAEADDRINUSE
- inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use");
+ inscode(d, ds, de, "EADDRINUSE", WSAEADDRINUSE, "Address already in use");
#endif
#endif
#ifdef EOPNOTSUPP
- inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint");
+ inscode(d, ds, de, "EOPNOTSUPP", EOPNOTSUPP, "Operation not supported on transport endpoint");
#else
#ifdef WSAEOPNOTSUPP
- inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
+ inscode(d, ds, de, "EOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
#endif
#endif
#ifdef EREMCHG
- inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed");
+ inscode(d, ds, de, "EREMCHG", EREMCHG, "Remote address changed");
#endif
#ifdef EAGAIN
- inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again");
+ inscode(d, ds, de, "EAGAIN", EAGAIN, "Try again");
#endif
#ifdef ENAMETOOLONG
- inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long");
+ inscode(d, ds, de, "ENAMETOOLONG", ENAMETOOLONG, "File name too long");
#else
#ifdef WSAENAMETOOLONG
- inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
+ inscode(d, ds, de, "ENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
#endif
#endif
#ifdef ENOTTY
- inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter");
+ inscode(d, ds, de, "ENOTTY", ENOTTY, "Not a typewriter");
#endif
#ifdef ERESTART
- inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted");
+ inscode(d, ds, de, "ERESTART", ERESTART, "Interrupted system call should be restarted");
#endif
#ifdef ESOCKTNOSUPPORT
- inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported");
+ inscode(d, ds, de, "ESOCKTNOSUPPORT", ESOCKTNOSUPPORT, "Socket type not supported");
#else
#ifdef WSAESOCKTNOSUPPORT
- inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
+ inscode(d, ds, de, "ESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
#endif
#endif
#ifdef ETIME
- inscode(d, ds, de, "ETIME", ETIME, "Timer expired");
+ inscode(d, ds, de, "ETIME", ETIME, "Timer expired");
#endif
#ifdef EBFONT
- inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format");
+ inscode(d, ds, de, "EBFONT", EBFONT, "Bad font file format");
#endif
#ifdef EDEADLOCK
- inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK");
+ inscode(d, ds, de, "EDEADLOCK", EDEADLOCK, "Error EDEADLOCK");
#endif
#ifdef ETOOMANYREFS
- inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice");
+ inscode(d, ds, de, "ETOOMANYREFS", ETOOMANYREFS, "Too many references: cannot splice");
#else
#ifdef WSAETOOMANYREFS
- inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
+ inscode(d, ds, de, "ETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
#endif
#endif
#ifdef EMFILE
- inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files");
+ inscode(d, ds, de, "EMFILE", EMFILE, "Too many open files");
#else
#ifdef WSAEMFILE
- inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files");
+ inscode(d, ds, de, "EMFILE", WSAEMFILE, "Too many open files");
#endif
#endif
#ifdef ETXTBSY
- inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy");
+ inscode(d, ds, de, "ETXTBSY", ETXTBSY, "Text file busy");
#endif
#ifdef EINPROGRESS
- inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress");
+ inscode(d, ds, de, "EINPROGRESS", EINPROGRESS, "Operation now in progress");
#else
#ifdef WSAEINPROGRESS
- inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
+ inscode(d, ds, de, "EINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
#endif
#endif
#ifdef ENXIO
- inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address");
+ inscode(d, ds, de, "ENXIO", ENXIO, "No such device or address");
#endif
#ifdef ENOPKG
- inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed");
+ inscode(d, ds, de, "ENOPKG", ENOPKG, "Package not installed");
#endif
#ifdef WSASY
- inscode(d, ds, de, "WSASY", WSASY, "Error WSASY");
+ inscode(d, ds, de, "WSASY", WSASY, "Error WSASY");
#endif
#ifdef WSAEHOSTDOWN
- inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down");
+ inscode(d, ds, de, "WSAEHOSTDOWN", WSAEHOSTDOWN, "Host is down");
#endif
#ifdef WSAENETDOWN
- inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down");
+ inscode(d, ds, de, "WSAENETDOWN", WSAENETDOWN, "Network is down");
#endif
#ifdef WSAENOTSOCK
- inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
+ inscode(d, ds, de, "WSAENOTSOCK", WSAENOTSOCK, "Socket operation on non-socket");
#endif
#ifdef WSAEHOSTUNREACH
- inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
+ inscode(d, ds, de, "WSAEHOSTUNREACH", WSAEHOSTUNREACH, "No route to host");
#endif
#ifdef WSAELOOP
- inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered");
+ inscode(d, ds, de, "WSAELOOP", WSAELOOP, "Too many symbolic links encountered");
#endif
#ifdef WSAEMFILE
- inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files");
+ inscode(d, ds, de, "WSAEMFILE", WSAEMFILE, "Too many open files");
#endif
#ifdef WSAESTALE
- inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle");
+ inscode(d, ds, de, "WSAESTALE", WSAESTALE, "Stale NFS file handle");
#endif
#ifdef WSAVERNOTSUPPORTED
- inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED");
+ inscode(d, ds, de, "WSAVERNOTSUPPORTED", WSAVERNOTSUPPORTED, "Error WSAVERNOTSUPPORTED");
#endif
#ifdef WSAENETUNREACH
- inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable");
+ inscode(d, ds, de, "WSAENETUNREACH", WSAENETUNREACH, "Network is unreachable");
#endif
#ifdef WSAEPROCLIM
- inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM");
+ inscode(d, ds, de, "WSAEPROCLIM", WSAEPROCLIM, "Error WSAEPROCLIM");
#endif
#ifdef WSAEFAULT
- inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address");
+ inscode(d, ds, de, "WSAEFAULT", WSAEFAULT, "Bad address");
#endif
#ifdef WSANOTINITIALISED
- inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED");
+ inscode(d, ds, de, "WSANOTINITIALISED", WSANOTINITIALISED, "Error WSANOTINITIALISED");
#endif
#ifdef WSAEUSERS
- inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users");
+ inscode(d, ds, de, "WSAEUSERS", WSAEUSERS, "Too many users");
#endif
#ifdef WSAMAKEASYNCREPL
- inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL");
+ inscode(d, ds, de, "WSAMAKEASYNCREPL", WSAMAKEASYNCREPL, "Error WSAMAKEASYNCREPL");
#endif
#ifdef WSAENOPROTOOPT
- inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
+ inscode(d, ds, de, "WSAENOPROTOOPT", WSAENOPROTOOPT, "Protocol not available");
#endif
#ifdef WSAECONNABORTED
- inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
+ inscode(d, ds, de, "WSAECONNABORTED", WSAECONNABORTED, "Software caused connection abort");
#endif
#ifdef WSAENAMETOOLONG
- inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
+ inscode(d, ds, de, "WSAENAMETOOLONG", WSAENAMETOOLONG, "File name too long");
#endif
#ifdef WSAENOTEMPTY
- inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
+ inscode(d, ds, de, "WSAENOTEMPTY", WSAENOTEMPTY, "Directory not empty");
#endif
#ifdef WSAESHUTDOWN
- inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
+ inscode(d, ds, de, "WSAESHUTDOWN", WSAESHUTDOWN, "Cannot send after transport endpoint shutdown");
#endif
#ifdef WSAEAFNOSUPPORT
- inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
+ inscode(d, ds, de, "WSAEAFNOSUPPORT", WSAEAFNOSUPPORT, "Address family not supported by protocol");
#endif
#ifdef WSAETOOMANYREFS
- inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
+ inscode(d, ds, de, "WSAETOOMANYREFS", WSAETOOMANYREFS, "Too many references: cannot splice");
#endif
#ifdef WSAEACCES
- inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied");
+ inscode(d, ds, de, "WSAEACCES", WSAEACCES, "Permission denied");
#endif
#ifdef WSATR
- inscode(d, ds, de, "WSATR", WSATR, "Error WSATR");
+ inscode(d, ds, de, "WSATR", WSATR, "Error WSATR");
#endif
#ifdef WSABASEERR
- inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR");
+ inscode(d, ds, de, "WSABASEERR", WSABASEERR, "Error WSABASEERR");
#endif
#ifdef WSADESCRIPTIO
- inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO");
+ inscode(d, ds, de, "WSADESCRIPTIO", WSADESCRIPTIO, "Error WSADESCRIPTIO");
#endif
#ifdef WSAEMSGSIZE
- inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long");
+ inscode(d, ds, de, "WSAEMSGSIZE", WSAEMSGSIZE, "Message too long");
#endif
#ifdef WSAEBADF
- inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number");
+ inscode(d, ds, de, "WSAEBADF", WSAEBADF, "Bad file number");
#endif
#ifdef WSAECONNRESET
- inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer");
+ inscode(d, ds, de, "WSAECONNRESET", WSAECONNRESET, "Connection reset by peer");
#endif
#ifdef WSAGETSELECTERRO
- inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO");
+ inscode(d, ds, de, "WSAGETSELECTERRO", WSAGETSELECTERRO, "Error WSAGETSELECTERRO");
#endif
#ifdef WSAETIMEDOUT
- inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
+ inscode(d, ds, de, "WSAETIMEDOUT", WSAETIMEDOUT, "Connection timed out");
#endif
#ifdef WSAENOBUFS
- inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available");
+ inscode(d, ds, de, "WSAENOBUFS", WSAENOBUFS, "No buffer space available");
#endif
#ifdef WSAEDISCON
- inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON");
+ inscode(d, ds, de, "WSAEDISCON", WSAEDISCON, "Error WSAEDISCON");
#endif
#ifdef WSAEINTR
- inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call");
+ inscode(d, ds, de, "WSAEINTR", WSAEINTR, "Interrupted system call");
#endif
#ifdef WSAEPROTOTYPE
- inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
+ inscode(d, ds, de, "WSAEPROTOTYPE", WSAEPROTOTYPE, "Protocol wrong type for socket");
#endif
#ifdef WSAHOS
- inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS");
+ inscode(d, ds, de, "WSAHOS", WSAHOS, "Error WSAHOS");
#endif
#ifdef WSAEADDRINUSE
- inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use");
+ inscode(d, ds, de, "WSAEADDRINUSE", WSAEADDRINUSE, "Address already in use");
#endif
#ifdef WSAEADDRNOTAVAIL
- inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
+ inscode(d, ds, de, "WSAEADDRNOTAVAIL", WSAEADDRNOTAVAIL, "Cannot assign requested address");
#endif
#ifdef WSAEALREADY
- inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress");
+ inscode(d, ds, de, "WSAEALREADY", WSAEALREADY, "Operation already in progress");
#endif
#ifdef WSAEPROTONOSUPPORT
- inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
+ inscode(d, ds, de, "WSAEPROTONOSUPPORT", WSAEPROTONOSUPPORT, "Protocol not supported");
#endif
#ifdef WSASYSNOTREADY
- inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY");
+ inscode(d, ds, de, "WSASYSNOTREADY", WSASYSNOTREADY, "Error WSASYSNOTREADY");
#endif
#ifdef WSAEWOULDBLOCK
- inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
+ inscode(d, ds, de, "WSAEWOULDBLOCK", WSAEWOULDBLOCK, "Operation would block");
#endif
#ifdef WSAEPFNOSUPPORT
- inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
+ inscode(d, ds, de, "WSAEPFNOSUPPORT", WSAEPFNOSUPPORT, "Protocol family not supported");
#endif
#ifdef WSAEOPNOTSUPP
- inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
+ inscode(d, ds, de, "WSAEOPNOTSUPP", WSAEOPNOTSUPP, "Operation not supported on transport endpoint");
#endif
#ifdef WSAEISCONN
- inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected");
+ inscode(d, ds, de, "WSAEISCONN", WSAEISCONN, "Transport endpoint is already connected");
#endif
#ifdef WSAEDQUOT
- inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded");
+ inscode(d, ds, de, "WSAEDQUOT", WSAEDQUOT, "Quota exceeded");
#endif
#ifdef WSAENOTCONN
- inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
+ inscode(d, ds, de, "WSAENOTCONN", WSAENOTCONN, "Transport endpoint is not connected");
#endif
#ifdef WSAEREMOTE
- inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote");
+ inscode(d, ds, de, "WSAEREMOTE", WSAEREMOTE, "Object is remote");
#endif
#ifdef WSAEINVAL
- inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument");
+ inscode(d, ds, de, "WSAEINVAL", WSAEINVAL, "Invalid argument");
#endif
#ifdef WSAEINPROGRESS
- inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
+ inscode(d, ds, de, "WSAEINPROGRESS", WSAEINPROGRESS, "Operation now in progress");
#endif
#ifdef WSAGETSELECTEVEN
- inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN");
+ inscode(d, ds, de, "WSAGETSELECTEVEN", WSAGETSELECTEVEN, "Error WSAGETSELECTEVEN");
#endif
#ifdef WSAESOCKTNOSUPPORT
- inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
+ inscode(d, ds, de, "WSAESOCKTNOSUPPORT", WSAESOCKTNOSUPPORT, "Socket type not supported");
#endif
#ifdef WSAGETASYNCERRO
- inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO");
+ inscode(d, ds, de, "WSAGETASYNCERRO", WSAGETASYNCERRO, "Error WSAGETASYNCERRO");
#endif
#ifdef WSAMAKESELECTREPL
- inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL");
+ inscode(d, ds, de, "WSAMAKESELECTREPL", WSAMAKESELECTREPL, "Error WSAMAKESELECTREPL");
#endif
#ifdef WSAGETASYNCBUFLE
- inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE");
+ inscode(d, ds, de, "WSAGETASYNCBUFLE", WSAGETASYNCBUFLE, "Error WSAGETASYNCBUFLE");
#endif
#ifdef WSAEDESTADDRREQ
- inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
+ inscode(d, ds, de, "WSAEDESTADDRREQ", WSAEDESTADDRREQ, "Destination address required");
#endif
#ifdef WSAECONNREFUSED
- inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused");
+ inscode(d, ds, de, "WSAECONNREFUSED", WSAECONNREFUSED, "Connection refused");
#endif
#ifdef WSAENETRESET
- inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset");
+ inscode(d, ds, de, "WSAENETRESET", WSAENETRESET, "Network dropped connection because of reset");
#endif
#ifdef WSAN
- inscode(d, ds, de, "WSAN", WSAN, "Error WSAN");
+ inscode(d, ds, de, "WSAN", WSAN, "Error WSAN");
#endif
- Py_DECREF(de);
+ Py_DECREF(de);
}
diff --git a/Modules/fcntlmodule.c b/Modules/fcntlmodule.c
index a333a34..63d06d3 100644
--- a/Modules/fcntlmodule.c
+++ b/Modules/fcntlmodule.c
@@ -21,7 +21,7 @@ conv_descriptor(PyObject *object, int *target)
int fd = PyObject_AsFileDescriptor(object);
if (fd < 0)
- return 0;
+ return 0;
*target = fd;
return 1;
}
@@ -32,48 +32,48 @@ conv_descriptor(PyObject *object, int *target)
static PyObject *
fcntl_fcntl(PyObject *self, PyObject *args)
{
- int fd;
- int code;
- long arg;
- int ret;
- char *str;
- Py_ssize_t len;
- char buf[1024];
-
- if (PyArg_ParseTuple(args, "O&is#:fcntl",
- conv_descriptor, &fd, &code, &str, &len)) {
- if (len > sizeof buf) {
- PyErr_SetString(PyExc_ValueError,
- "fcntl string arg too long");
- return NULL;
- }
- memcpy(buf, str, len);
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, code, buf);
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyString_FromStringAndSize(buf, len);
- }
-
- PyErr_Clear();
- arg = 0;
- if (!PyArg_ParseTuple(args,
- "O&i|l;fcntl requires a file or file descriptor,"
- " an integer and optionally a third integer or a string",
- conv_descriptor, &fd, &code, &arg)) {
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, code, arg);
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyInt_FromLong((long)ret);
+ int fd;
+ int code;
+ long arg;
+ int ret;
+ char *str;
+ Py_ssize_t len;
+ char buf[1024];
+
+ if (PyArg_ParseTuple(args, "O&is#:fcntl",
+ conv_descriptor, &fd, &code, &str, &len)) {
+ if (len > sizeof buf) {
+ PyErr_SetString(PyExc_ValueError,
+ "fcntl string arg too long");
+ return NULL;
+ }
+ memcpy(buf, str, len);
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, code, buf);
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyString_FromStringAndSize(buf, len);
+ }
+
+ PyErr_Clear();
+ arg = 0;
+ if (!PyArg_ParseTuple(args,
+ "O&i|l;fcntl requires a file or file descriptor,"
+ " an integer and optionally a third integer or a string",
+ conv_descriptor, &fd, &code, &arg)) {
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, code, arg);
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyInt_FromLong((long)ret);
}
PyDoc_STRVAR(fcntl_doc,
@@ -96,118 +96,118 @@ static PyObject *
fcntl_ioctl(PyObject *self, PyObject *args)
{
#define IOCTL_BUFSZ 1024
- int fd;
- /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I'
- format for the 'code' parameter because Python turns 0x8000000
- into either a large positive number (PyLong or PyInt on 64-bit
- platforms) or a negative number on others (32-bit PyInt)
- whereas the system expects it to be a 32bit bit field value
- regardless of it being passed as an int or unsigned long on
- various platforms. See the termios.TIOCSWINSZ constant across
- platforms for an example of thise.
-
- If any of the 64bit platforms ever decide to use more than 32bits
- in their unsigned long ioctl codes this will break and need
- special casing based on the platform being built on.
- */
- unsigned int code;
- int arg;
- int ret;
- char *str;
- Py_ssize_t len;
- int mutate_arg = 1;
- char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */
-
- if (PyArg_ParseTuple(args, "O&Iw#|i:ioctl",
- conv_descriptor, &fd, &code,
- &str, &len, &mutate_arg)) {
- char *arg;
-
- if (mutate_arg) {
- if (len <= IOCTL_BUFSZ) {
- memcpy(buf, str, len);
- buf[len] = '\0';
- arg = buf;
- }
- else {
- arg = str;
- }
- }
- else {
- if (len > IOCTL_BUFSZ) {
- PyErr_SetString(PyExc_ValueError,
- "ioctl string arg too long");
- return NULL;
- }
- else {
- memcpy(buf, str, len);
- buf[len] = '\0';
- arg = buf;
- }
- }
- if (buf == arg) {
- Py_BEGIN_ALLOW_THREADS /* think array.resize() */
- ret = ioctl(fd, code, arg);
- Py_END_ALLOW_THREADS
- }
- else {
- ret = ioctl(fd, code, arg);
- }
- if (mutate_arg && (len < IOCTL_BUFSZ)) {
- memcpy(str, buf, len);
- }
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- if (mutate_arg) {
- return PyInt_FromLong(ret);
- }
- else {
- return PyString_FromStringAndSize(buf, len);
- }
- }
-
- PyErr_Clear();
- if (PyArg_ParseTuple(args, "O&Is#:ioctl",
- conv_descriptor, &fd, &code, &str, &len)) {
- if (len > IOCTL_BUFSZ) {
- PyErr_SetString(PyExc_ValueError,
- "ioctl string arg too long");
- return NULL;
- }
- memcpy(buf, str, len);
- buf[len] = '\0';
- Py_BEGIN_ALLOW_THREADS
- ret = ioctl(fd, code, buf);
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyString_FromStringAndSize(buf, len);
- }
-
- PyErr_Clear();
- arg = 0;
- if (!PyArg_ParseTuple(args,
- "O&I|i;ioctl requires a file or file descriptor,"
- " an integer and optionally an integer or buffer argument",
- conv_descriptor, &fd, &code, &arg)) {
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
+ int fd;
+ /* In PyArg_ParseTuple below, we use the unsigned non-checked 'I'
+ format for the 'code' parameter because Python turns 0x8000000
+ into either a large positive number (PyLong or PyInt on 64-bit
+ platforms) or a negative number on others (32-bit PyInt)
+ whereas the system expects it to be a 32bit bit field value
+ regardless of it being passed as an int or unsigned long on
+ various platforms. See the termios.TIOCSWINSZ constant across
+ platforms for an example of thise.
+
+ If any of the 64bit platforms ever decide to use more than 32bits
+ in their unsigned long ioctl codes this will break and need
+ special casing based on the platform being built on.
+ */
+ unsigned int code;
+ int arg;
+ int ret;
+ char *str;
+ Py_ssize_t len;
+ int mutate_arg = 1;
+ char buf[IOCTL_BUFSZ+1]; /* argument plus NUL byte */
+
+ if (PyArg_ParseTuple(args, "O&Iw#|i:ioctl",
+ conv_descriptor, &fd, &code,
+ &str, &len, &mutate_arg)) {
+ char *arg;
+
+ if (mutate_arg) {
+ if (len <= IOCTL_BUFSZ) {
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ arg = buf;
+ }
+ else {
+ arg = str;
+ }
+ }
+ else {
+ if (len > IOCTL_BUFSZ) {
+ PyErr_SetString(PyExc_ValueError,
+ "ioctl string arg too long");
+ return NULL;
+ }
+ else {
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ arg = buf;
+ }
+ }
+ if (buf == arg) {
+ Py_BEGIN_ALLOW_THREADS /* think array.resize() */
+ ret = ioctl(fd, code, arg);
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ ret = ioctl(fd, code, arg);
+ }
+ if (mutate_arg && (len < IOCTL_BUFSZ)) {
+ memcpy(str, buf, len);
+ }
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ if (mutate_arg) {
+ return PyInt_FromLong(ret);
+ }
+ else {
+ return PyString_FromStringAndSize(buf, len);
+ }
+ }
+
+ PyErr_Clear();
+ if (PyArg_ParseTuple(args, "O&Is#:ioctl",
+ conv_descriptor, &fd, &code, &str, &len)) {
+ if (len > IOCTL_BUFSZ) {
+ PyErr_SetString(PyExc_ValueError,
+ "ioctl string arg too long");
+ return NULL;
+ }
+ memcpy(buf, str, len);
+ buf[len] = '\0';
+ Py_BEGIN_ALLOW_THREADS
+ ret = ioctl(fd, code, buf);
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyString_FromStringAndSize(buf, len);
+ }
+
+ PyErr_Clear();
+ arg = 0;
+ if (!PyArg_ParseTuple(args,
+ "O&I|i;ioctl requires a file or file descriptor,"
+ " an integer and optionally an integer or buffer argument",
+ conv_descriptor, &fd, &code, &arg)) {
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
#ifdef __VMS
- ret = ioctl(fd, code, (void *)arg);
+ ret = ioctl(fd, code, (void *)arg);
#else
- ret = ioctl(fd, code, arg);
-#endif
- Py_END_ALLOW_THREADS
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyInt_FromLong((long)ret);
+ ret = ioctl(fd, code, arg);
+#endif
+ Py_END_ALLOW_THREADS
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyInt_FromLong((long)ret);
#undef IOCTL_BUFSZ
}
@@ -248,51 +248,51 @@ code.");
static PyObject *
fcntl_flock(PyObject *self, PyObject *args)
{
- int fd;
- int code;
- int ret;
+ int fd;
+ int code;
+ int ret;
- if (!PyArg_ParseTuple(args, "O&i:flock",
- conv_descriptor, &fd, &code))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O&i:flock",
+ conv_descriptor, &fd, &code))
+ return NULL;
#ifdef HAVE_FLOCK
- Py_BEGIN_ALLOW_THREADS
- ret = flock(fd, code);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ ret = flock(fd, code);
+ Py_END_ALLOW_THREADS
#else
#ifndef LOCK_SH
-#define LOCK_SH 1 /* shared lock */
-#define LOCK_EX 2 /* exclusive lock */
-#define LOCK_NB 4 /* don't block when locking */
-#define LOCK_UN 8 /* unlock */
-#endif
- {
- struct flock l;
- if (code == LOCK_UN)
- l.l_type = F_UNLCK;
- else if (code & LOCK_SH)
- l.l_type = F_RDLCK;
- else if (code & LOCK_EX)
- l.l_type = F_WRLCK;
- else {
- PyErr_SetString(PyExc_ValueError,
- "unrecognized flock argument");
- return NULL;
- }
- l.l_whence = l.l_start = l.l_len = 0;
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
- Py_END_ALLOW_THREADS
- }
+#define LOCK_SH 1 /* shared lock */
+#define LOCK_EX 2 /* exclusive lock */
+#define LOCK_NB 4 /* don't block when locking */
+#define LOCK_UN 8 /* unlock */
+#endif
+ {
+ struct flock l;
+ if (code == LOCK_UN)
+ l.l_type = F_UNLCK;
+ else if (code & LOCK_SH)
+ l.l_type = F_RDLCK;
+ else if (code & LOCK_EX)
+ l.l_type = F_WRLCK;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "unrecognized flock argument");
+ return NULL;
+ }
+ l.l_whence = l.l_start = l.l_len = 0;
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
+ Py_END_ALLOW_THREADS
+ }
#endif /* HAVE_FLOCK */
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(flock_doc,
@@ -307,72 +307,72 @@ emulated using fcntl().)");
static PyObject *
fcntl_lockf(PyObject *self, PyObject *args)
{
- int fd, code, ret, whence = 0;
- PyObject *lenobj = NULL, *startobj = NULL;
+ int fd, code, ret, whence = 0;
+ PyObject *lenobj = NULL, *startobj = NULL;
- if (!PyArg_ParseTuple(args, "O&i|OOi:lockf",
- conv_descriptor, &fd, &code,
- &lenobj, &startobj, &whence))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O&i|OOi:lockf",
+ conv_descriptor, &fd, &code,
+ &lenobj, &startobj, &whence))
+ return NULL;
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- PyErr_SetString(PyExc_NotImplementedError,
- "lockf not supported on OS/2 (EMX)");
- return NULL;
+ PyErr_SetString(PyExc_NotImplementedError,
+ "lockf not supported on OS/2 (EMX)");
+ return NULL;
#else
#ifndef LOCK_SH
-#define LOCK_SH 1 /* shared lock */
-#define LOCK_EX 2 /* exclusive lock */
-#define LOCK_NB 4 /* don't block when locking */
-#define LOCK_UN 8 /* unlock */
+#define LOCK_SH 1 /* shared lock */
+#define LOCK_EX 2 /* exclusive lock */
+#define LOCK_NB 4 /* don't block when locking */
+#define LOCK_UN 8 /* unlock */
#endif /* LOCK_SH */
- {
- struct flock l;
- if (code == LOCK_UN)
- l.l_type = F_UNLCK;
- else if (code & LOCK_SH)
- l.l_type = F_RDLCK;
- else if (code & LOCK_EX)
- l.l_type = F_WRLCK;
- else {
- PyErr_SetString(PyExc_ValueError,
- "unrecognized lockf argument");
- return NULL;
- }
- l.l_start = l.l_len = 0;
- if (startobj != NULL) {
+ {
+ struct flock l;
+ if (code == LOCK_UN)
+ l.l_type = F_UNLCK;
+ else if (code & LOCK_SH)
+ l.l_type = F_RDLCK;
+ else if (code & LOCK_EX)
+ l.l_type = F_WRLCK;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "unrecognized lockf argument");
+ return NULL;
+ }
+ l.l_start = l.l_len = 0;
+ if (startobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
- l.l_start = PyInt_AsLong(startobj);
+ l.l_start = PyInt_AsLong(startobj);
#else
- l.l_start = PyLong_Check(startobj) ?
- PyLong_AsLongLong(startobj) :
- PyInt_AsLong(startobj);
-#endif
- if (PyErr_Occurred())
- return NULL;
- }
- if (lenobj != NULL) {
+ l.l_start = PyLong_Check(startobj) ?
+ PyLong_AsLongLong(startobj) :
+ PyInt_AsLong(startobj);
+#endif
+ if (PyErr_Occurred())
+ return NULL;
+ }
+ if (lenobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
- l.l_len = PyInt_AsLong(lenobj);
+ l.l_len = PyInt_AsLong(lenobj);
#else
- l.l_len = PyLong_Check(lenobj) ?
- PyLong_AsLongLong(lenobj) :
- PyInt_AsLong(lenobj);
-#endif
- if (PyErr_Occurred())
- return NULL;
- }
- l.l_whence = whence;
- Py_BEGIN_ALLOW_THREADS
- ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
- Py_END_ALLOW_THREADS
- }
- if (ret < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ l.l_len = PyLong_Check(lenobj) ?
+ PyLong_AsLongLong(lenobj) :
+ PyInt_AsLong(lenobj);
+#endif
+ if (PyErr_Occurred())
+ return NULL;
+ }
+ l.l_whence = whence;
+ Py_BEGIN_ALLOW_THREADS
+ ret = fcntl(fd, (code & LOCK_NB) ? F_SETLK : F_SETLKW, &l);
+ Py_END_ALLOW_THREADS
+ }
+ if (ret < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
#endif /* defined(PYOS_OS2) && defined(PYCC_GCC) */
}
@@ -404,11 +404,11 @@ starts. whence is as with fileobj.seek(), specifically:\n\
/* List of functions */
static PyMethodDef fcntl_methods[] = {
- {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc},
- {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc},
- {"flock", fcntl_flock, METH_VARARGS, flock_doc},
- {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc},
- {NULL, NULL} /* sentinel */
+ {"fcntl", fcntl_fcntl, METH_VARARGS, fcntl_doc},
+ {"ioctl", fcntl_ioctl, METH_VARARGS, ioctl_doc},
+ {"flock", fcntl_flock, METH_VARARGS, flock_doc},
+ {"lockf", fcntl_lockf, METH_VARARGS, lockf_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -423,12 +423,12 @@ a file or socket object.");
static int
ins(PyObject* d, char* symbol, long value)
{
- PyObject* v = PyInt_FromLong(value);
- if (!v || PyDict_SetItemString(d, symbol, v) < 0)
- return -1;
+ PyObject* v = PyInt_FromLong(value);
+ if (!v || PyDict_SetItemString(d, symbol, v) < 0)
+ return -1;
- Py_DECREF(v);
- return 0;
+ Py_DECREF(v);
+ return 0;
}
#define INS(x) if (ins(d, #x, (long)x)) return -1
@@ -436,185 +436,185 @@ ins(PyObject* d, char* symbol, long value)
static int
all_ins(PyObject* d)
{
- if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1;
- if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1;
- if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1;
- if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1;
+ if (ins(d, "LOCK_SH", (long)LOCK_SH)) return -1;
+ if (ins(d, "LOCK_EX", (long)LOCK_EX)) return -1;
+ if (ins(d, "LOCK_NB", (long)LOCK_NB)) return -1;
+ if (ins(d, "LOCK_UN", (long)LOCK_UN)) return -1;
/* GNU extensions, as of glibc 2.2.4 */
#ifdef LOCK_MAND
- if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1;
+ if (ins(d, "LOCK_MAND", (long)LOCK_MAND)) return -1;
#endif
#ifdef LOCK_READ
- if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1;
+ if (ins(d, "LOCK_READ", (long)LOCK_READ)) return -1;
#endif
#ifdef LOCK_WRITE
- if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1;
+ if (ins(d, "LOCK_WRITE", (long)LOCK_WRITE)) return -1;
#endif
#ifdef LOCK_RW
- if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1;
+ if (ins(d, "LOCK_RW", (long)LOCK_RW)) return -1;
#endif
#ifdef F_DUPFD
- if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1;
+ if (ins(d, "F_DUPFD", (long)F_DUPFD)) return -1;
#endif
#ifdef F_GETFD
- if (ins(d, "F_GETFD", (long)F_GETFD)) return -1;
+ if (ins(d, "F_GETFD", (long)F_GETFD)) return -1;
#endif
#ifdef F_SETFD
- if (ins(d, "F_SETFD", (long)F_SETFD)) return -1;
+ if (ins(d, "F_SETFD", (long)F_SETFD)) return -1;
#endif
#ifdef F_GETFL
- if (ins(d, "F_GETFL", (long)F_GETFL)) return -1;
+ if (ins(d, "F_GETFL", (long)F_GETFL)) return -1;
#endif
#ifdef F_SETFL
- if (ins(d, "F_SETFL", (long)F_SETFL)) return -1;
+ if (ins(d, "F_SETFL", (long)F_SETFL)) return -1;
#endif
#ifdef F_GETLK
- if (ins(d, "F_GETLK", (long)F_GETLK)) return -1;
+ if (ins(d, "F_GETLK", (long)F_GETLK)) return -1;
#endif
#ifdef F_SETLK
- if (ins(d, "F_SETLK", (long)F_SETLK)) return -1;
+ if (ins(d, "F_SETLK", (long)F_SETLK)) return -1;
#endif
#ifdef F_SETLKW
- if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1;
+ if (ins(d, "F_SETLKW", (long)F_SETLKW)) return -1;
#endif
#ifdef F_GETOWN
- if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1;
+ if (ins(d, "F_GETOWN", (long)F_GETOWN)) return -1;
#endif
#ifdef F_SETOWN
- if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1;
+ if (ins(d, "F_SETOWN", (long)F_SETOWN)) return -1;
#endif
#ifdef F_GETSIG
- if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1;
+ if (ins(d, "F_GETSIG", (long)F_GETSIG)) return -1;
#endif
#ifdef F_SETSIG
- if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1;
+ if (ins(d, "F_SETSIG", (long)F_SETSIG)) return -1;
#endif
#ifdef F_RDLCK
- if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1;
+ if (ins(d, "F_RDLCK", (long)F_RDLCK)) return -1;
#endif
#ifdef F_WRLCK
- if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1;
+ if (ins(d, "F_WRLCK", (long)F_WRLCK)) return -1;
#endif
#ifdef F_UNLCK
- if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1;
+ if (ins(d, "F_UNLCK", (long)F_UNLCK)) return -1;
#endif
/* LFS constants */
#ifdef F_GETLK64
- if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1;
+ if (ins(d, "F_GETLK64", (long)F_GETLK64)) return -1;
#endif
#ifdef F_SETLK64
- if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1;
+ if (ins(d, "F_SETLK64", (long)F_SETLK64)) return -1;
#endif
#ifdef F_SETLKW64
- if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
+ if (ins(d, "F_SETLKW64", (long)F_SETLKW64)) return -1;
#endif
/* GNU extensions, as of glibc 2.2.4. */
#ifdef FASYNC
- if (ins(d, "FASYNC", (long)FASYNC)) return -1;
+ if (ins(d, "FASYNC", (long)FASYNC)) return -1;
#endif
#ifdef F_SETLEASE
- if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
+ if (ins(d, "F_SETLEASE", (long)F_SETLEASE)) return -1;
#endif
#ifdef F_GETLEASE
- if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1;
+ if (ins(d, "F_GETLEASE", (long)F_GETLEASE)) return -1;
#endif
#ifdef F_NOTIFY
- if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1;
+ if (ins(d, "F_NOTIFY", (long)F_NOTIFY)) return -1;
#endif
/* Old BSD flock(). */
#ifdef F_EXLCK
- if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1;
+ if (ins(d, "F_EXLCK", (long)F_EXLCK)) return -1;
#endif
#ifdef F_SHLCK
- if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1;
+ if (ins(d, "F_SHLCK", (long)F_SHLCK)) return -1;
#endif
/* OS X (and maybe others) let you tell the storage device to flush to physical media */
#ifdef F_FULLFSYNC
- if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1;
+ if (ins(d, "F_FULLFSYNC", (long)F_FULLFSYNC)) return -1;
#endif
/* For F_{GET|SET}FL */
#ifdef FD_CLOEXEC
- if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1;
+ if (ins(d, "FD_CLOEXEC", (long)FD_CLOEXEC)) return -1;
#endif
/* For F_NOTIFY */
#ifdef DN_ACCESS
- if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1;
+ if (ins(d, "DN_ACCESS", (long)DN_ACCESS)) return -1;
#endif
#ifdef DN_MODIFY
- if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1;
+ if (ins(d, "DN_MODIFY", (long)DN_MODIFY)) return -1;
#endif
#ifdef DN_CREATE
- if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1;
+ if (ins(d, "DN_CREATE", (long)DN_CREATE)) return -1;
#endif
#ifdef DN_DELETE
- if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1;
+ if (ins(d, "DN_DELETE", (long)DN_DELETE)) return -1;
#endif
#ifdef DN_RENAME
- if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1;
+ if (ins(d, "DN_RENAME", (long)DN_RENAME)) return -1;
#endif
#ifdef DN_ATTRIB
- if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1;
+ if (ins(d, "DN_ATTRIB", (long)DN_ATTRIB)) return -1;
#endif
#ifdef DN_MULTISHOT
- if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1;
+ if (ins(d, "DN_MULTISHOT", (long)DN_MULTISHOT)) return -1;
#endif
#ifdef HAVE_STROPTS_H
- /* Unix 98 guarantees that these are in stropts.h. */
- INS(I_PUSH);
- INS(I_POP);
- INS(I_LOOK);
- INS(I_FLUSH);
- INS(I_FLUSHBAND);
- INS(I_SETSIG);
- INS(I_GETSIG);
- INS(I_FIND);
- INS(I_PEEK);
- INS(I_SRDOPT);
- INS(I_GRDOPT);
- INS(I_NREAD);
- INS(I_FDINSERT);
- INS(I_STR);
- INS(I_SWROPT);
+ /* Unix 98 guarantees that these are in stropts.h. */
+ INS(I_PUSH);
+ INS(I_POP);
+ INS(I_LOOK);
+ INS(I_FLUSH);
+ INS(I_FLUSHBAND);
+ INS(I_SETSIG);
+ INS(I_GETSIG);
+ INS(I_FIND);
+ INS(I_PEEK);
+ INS(I_SRDOPT);
+ INS(I_GRDOPT);
+ INS(I_NREAD);
+ INS(I_FDINSERT);
+ INS(I_STR);
+ INS(I_SWROPT);
#ifdef I_GWROPT
- /* despite the comment above, old-ish glibcs miss a couple... */
- INS(I_GWROPT);
-#endif
- INS(I_SENDFD);
- INS(I_RECVFD);
- INS(I_LIST);
- INS(I_ATMARK);
- INS(I_CKBAND);
- INS(I_GETBAND);
- INS(I_CANPUT);
- INS(I_SETCLTIME);
+ /* despite the comment above, old-ish glibcs miss a couple... */
+ INS(I_GWROPT);
+#endif
+ INS(I_SENDFD);
+ INS(I_RECVFD);
+ INS(I_LIST);
+ INS(I_ATMARK);
+ INS(I_CKBAND);
+ INS(I_GETBAND);
+ INS(I_CANPUT);
+ INS(I_SETCLTIME);
#ifdef I_GETCLTIME
- INS(I_GETCLTIME);
+ INS(I_GETCLTIME);
#endif
- INS(I_LINK);
- INS(I_UNLINK);
- INS(I_PLINK);
- INS(I_PUNLINK);
+ INS(I_LINK);
+ INS(I_UNLINK);
+ INS(I_PLINK);
+ INS(I_PUNLINK);
#endif
-
- return 0;
+
+ return 0;
}
PyMODINIT_FUNC
initfcntl(void)
{
- PyObject *m, *d;
+ PyObject *m, *d;
- /* Create the module and add the functions and documentation */
- m = Py_InitModule3("fcntl", fcntl_methods, module_doc);
- if (m == NULL)
- return;
+ /* Create the module and add the functions and documentation */
+ m = Py_InitModule3("fcntl", fcntl_methods, module_doc);
+ if (m == NULL)
+ return;
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
- all_ins(d);
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+ all_ins(d);
}
diff --git a/Modules/flmodule.c b/Modules/flmodule.c
index d2c2506..b5a78cf 100644
--- a/Modules/flmodule.c
+++ b/Modules/flmodule.c
@@ -22,11 +22,11 @@
/* Generic Forms Objects */
typedef struct {
- PyObject_HEAD
- FL_OBJECT *ob_generic;
- PyMethodDef *ob_methods;
- PyObject *ob_callback;
- PyObject *ob_callback_arg;
+ PyObject_HEAD
+ FL_OBJECT *ob_generic;
+ PyMethodDef *ob_methods;
+ PyObject *ob_callback;
+ PyObject *ob_callback_arg;
} genericobject;
static PyTypeObject GenericObjecttype;
@@ -43,32 +43,32 @@ static int nfreeslots = 0;
static void
knowgeneric(genericobject *g)
{
- int i, n;
- /* Create the list if it doesn't already exist */
- if (allgenerics == NULL) {
- allgenerics = PyList_New(0);
- if (allgenerics == NULL) {
- PyErr_Clear();
- return; /* Too bad, live without allgenerics... */
- }
- }
- if (nfreeslots > 0) {
- /* Search the list for reusable slots (NULL items) */
- /* XXX This can be made faster! */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- if (PyList_GetItem(allgenerics, i) == NULL) {
- Py_INCREF(g);
- PyList_SetItem(allgenerics, i, (PyObject *)g);
- nfreeslots--;
- return;
- }
- }
- /* Strange... no free slots found... */
- nfreeslots = 0;
- }
- /* No free entries, append new item to the end */
- PyList_Append(allgenerics, (PyObject *)g);
+ int i, n;
+ /* Create the list if it doesn't already exist */
+ if (allgenerics == NULL) {
+ allgenerics = PyList_New(0);
+ if (allgenerics == NULL) {
+ PyErr_Clear();
+ return; /* Too bad, live without allgenerics... */
+ }
+ }
+ if (nfreeslots > 0) {
+ /* Search the list for reusable slots (NULL items) */
+ /* XXX This can be made faster! */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ if (PyList_GetItem(allgenerics, i) == NULL) {
+ Py_INCREF(g);
+ PyList_SetItem(allgenerics, i, (PyObject *)g);
+ nfreeslots--;
+ return;
+ }
+ }
+ /* Strange... no free slots found... */
+ nfreeslots = 0;
+ }
+ /* No free entries, append new item to the end */
+ PyList_Append(allgenerics, (PyObject *)g);
}
/* Find an object in the list of known objects */
@@ -76,18 +76,18 @@ knowgeneric(genericobject *g)
static genericobject *
findgeneric(FL_OBJECT *generic)
{
- int i, n;
- genericobject *g;
-
- if (allgenerics == NULL)
- return NULL; /* No objects known yet */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- g = (genericobject *)PyList_GetItem(allgenerics, i);
- if (g != NULL && g->ob_generic == generic)
- return g;
- }
- return NULL; /* Unknown object */
+ int i, n;
+ genericobject *g;
+
+ if (allgenerics == NULL)
+ return NULL; /* No objects known yet */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ g = (genericobject *)PyList_GetItem(allgenerics, i);
+ if (g != NULL && g->ob_generic == generic)
+ return g;
+ }
+ return NULL; /* Unknown object */
}
/* Remove an object from the list of known objects */
@@ -95,22 +95,22 @@ findgeneric(FL_OBJECT *generic)
static void
forgetgeneric(genericobject *g)
{
- int i, n;
-
- Py_XDECREF(g->ob_callback);
- g->ob_callback = NULL;
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback_arg = NULL;
- if (allgenerics == NULL)
- return; /* No objects known yet */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- if (g == (genericobject *)PyList_GetItem(allgenerics, i)) {
- PyList_SetItem(allgenerics, i, (PyObject *)NULL);
- nfreeslots++;
- break;
- }
- }
+ int i, n;
+
+ Py_XDECREF(g->ob_callback);
+ g->ob_callback = NULL;
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback_arg = NULL;
+ if (allgenerics == NULL)
+ return; /* No objects known yet */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ if (g == (genericobject *)PyList_GetItem(allgenerics, i)) {
+ PyList_SetItem(allgenerics, i, (PyObject *)NULL);
+ nfreeslots++;
+ break;
+ }
+ }
}
/* Called when a form is about to be freed --
@@ -119,27 +119,27 @@ forgetgeneric(genericobject *g)
static void
releaseobjects(FL_FORM *form)
{
- int i, n;
- genericobject *g;
-
- if (allgenerics == NULL)
- return; /* No objects known yet */
- n = PyList_Size(allgenerics);
- for (i = 0; i < n; i++) {
- g = (genericobject *)PyList_GetItem(allgenerics, i);
- if (g != NULL && g->ob_generic->form == form) {
- fl_delete_object(g->ob_generic);
- /* The object is now unreachable for
- do_forms and check_forms, so
- delete it from the list of known objects */
- Py_XDECREF(g->ob_callback);
- g->ob_callback = NULL;
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback_arg = NULL;
- PyList_SetItem(allgenerics, i, (PyObject *)NULL);
- nfreeslots++;
- }
- }
+ int i, n;
+ genericobject *g;
+
+ if (allgenerics == NULL)
+ return; /* No objects known yet */
+ n = PyList_Size(allgenerics);
+ for (i = 0; i < n; i++) {
+ g = (genericobject *)PyList_GetItem(allgenerics, i);
+ if (g != NULL && g->ob_generic->form == form) {
+ fl_delete_object(g->ob_generic);
+ /* The object is now unreachable for
+ do_forms and check_forms, so
+ delete it from the list of known objects */
+ Py_XDECREF(g->ob_callback);
+ g->ob_callback = NULL;
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback_arg = NULL;
+ PyList_SetItem(allgenerics, i, (PyObject *)NULL);
+ nfreeslots++;
+ }
+ }
}
@@ -148,79 +148,79 @@ releaseobjects(FL_FORM *form)
static PyObject *
generic_set_call_back(genericobject *g, PyObject *args)
{
- if (PyTuple_GET_SIZE(args) == 0) {
- Py_XDECREF(g->ob_callback);
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback = NULL;
- g->ob_callback_arg = NULL;
- }
- else {
- PyObject *a, *b;
- if (!PyArg_UnpackTuple(args, "set_call_back", 2, 2, &a, &b))
- return NULL;
- Py_XDECREF(g->ob_callback);
- Py_XDECREF(g->ob_callback_arg);
- g->ob_callback = a;
- Py_INCREF(g->ob_callback);
- g->ob_callback_arg = b;
- Py_INCREF(g->ob_callback_arg);
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (PyTuple_GET_SIZE(args) == 0) {
+ Py_XDECREF(g->ob_callback);
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback = NULL;
+ g->ob_callback_arg = NULL;
+ }
+ else {
+ PyObject *a, *b;
+ if (!PyArg_UnpackTuple(args, "set_call_back", 2, 2, &a, &b))
+ return NULL;
+ Py_XDECREF(g->ob_callback);
+ Py_XDECREF(g->ob_callback_arg);
+ g->ob_callback = a;
+ Py_INCREF(g->ob_callback);
+ g->ob_callback_arg = b;
+ Py_INCREF(g->ob_callback_arg);
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
generic_call(genericobject *g, void (*func)(FL_OBJECT *))
{
- (*func)(g->ob_generic);
- Py_INCREF(Py_None);
- return Py_None;
+ (*func)(g->ob_generic);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
generic_delete_object(genericobject *g)
{
- PyObject *res;
- res = generic_call(g, fl_delete_object);
- if (res != NULL)
- forgetgeneric(g);
- return res;
+ PyObject *res;
+ res = generic_call(g, fl_delete_object);
+ if (res != NULL)
+ forgetgeneric(g);
+ return res;
}
static PyObject *
generic_show_object(genericobject *g)
{
- return generic_call(g, fl_show_object);
+ return generic_call(g, fl_show_object);
}
static PyObject *
generic_hide_object(genericobject *g)
{
- return generic_call(g, fl_hide_object);
+ return generic_call(g, fl_hide_object);
}
static PyObject *
generic_redraw_object(genericobject *g)
{
- return generic_call(g, fl_redraw_object);
+ return generic_call(g, fl_redraw_object);
}
#ifdef OBSOLETE_FORMS_CALLS
-
+
/* (un)freeze_object() are obsolete in FORMS 2.2 and unsupported
in 2.3. Since there's no foolproof way to tell which version we're
using, we omit them unconditionally. */
-
+
static PyObject *
generic_freeze_object(genericobject *g)
{
- return generic_call(g, fl_freeze_object);
+ return generic_call(g, fl_freeze_object);
}
static PyObject *
generic_unfreeze_object(genericobject *g)
{
- return generic_call(g, fl_unfreeze_object);
+ return generic_call(g, fl_unfreeze_object);
}
#endif /* OBSOLETE_FORMS_CALLS */
@@ -228,78 +228,78 @@ generic_unfreeze_object(genericobject *g)
static PyObject *
generic_activate_object(genericobject *g)
{
- return generic_call(g, fl_activate_object);
+ return generic_call(g, fl_activate_object);
}
static PyObject *
generic_deactivate_object(genericobject *g)
{
- return generic_call(g, fl_deactivate_object);
+ return generic_call(g, fl_deactivate_object);
}
static PyObject *
generic_set_object_shortcut(genericobject *g, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s:set_object_shortcut", &str))
- return NULL;
- fl_set_object_shortcut(g->ob_generic, str);
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ if (!PyArg_ParseTuple(args, "s:set_object_shortcut", &str))
+ return NULL;
+ fl_set_object_shortcut(g->ob_generic, str);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef generic_methods[] = {
- {"set_call_back", (PyCFunction)generic_set_call_back, METH_VARARGS},
- {"delete_object", (PyCFunction)generic_delete_object, METH_NOARGS},
- {"show_object", (PyCFunction)generic_show_object, METH_NOARGS},
- {"hide_object", (PyCFunction)generic_hide_object, METH_NOARGS},
- {"redraw_object", (PyCFunction)generic_redraw_object, METH_NOARGS},
+ {"set_call_back", (PyCFunction)generic_set_call_back, METH_VARARGS},
+ {"delete_object", (PyCFunction)generic_delete_object, METH_NOARGS},
+ {"show_object", (PyCFunction)generic_show_object, METH_NOARGS},
+ {"hide_object", (PyCFunction)generic_hide_object, METH_NOARGS},
+ {"redraw_object", (PyCFunction)generic_redraw_object, METH_NOARGS},
#ifdef OBSOLETE_FORMS_CALLS
- {"freeze_object", (PyCFunction)generic_freeze_object, METH_NOARGS},
- {"unfreeze_object", (PyCFunction)generic_unfreeze_object, METH_NOARGS},
+ {"freeze_object", (PyCFunction)generic_freeze_object, METH_NOARGS},
+ {"unfreeze_object", (PyCFunction)generic_unfreeze_object, METH_NOARGS},
#endif
- {"activate_object", (PyCFunction)generic_activate_object, METH_NOARGS},
- {"deactivate_object", (PyCFunction)generic_deactivate_object, METH_NOARGS},
- {"set_object_shortcut", (PyCFunction)generic_set_object_shortcut, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"activate_object", (PyCFunction)generic_activate_object, METH_NOARGS},
+ {"deactivate_object", (PyCFunction)generic_deactivate_object, METH_NOARGS},
+ {"set_object_shortcut", (PyCFunction)generic_set_object_shortcut, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static void
generic_dealloc(genericobject *g)
{
- fl_free_object(g->ob_generic);
- Py_XDECREF(g->ob_callback);
- Py_XDECREF(g->ob_callback_arg);
- PyObject_Del(g);
+ fl_free_object(g->ob_generic);
+ Py_XDECREF(g->ob_callback);
+ Py_XDECREF(g->ob_callback_arg);
+ PyObject_Del(g);
}
#define OFF(x) offsetof(FL_OBJECT, x)
static struct memberlist generic_memberlist[] = {
- {"objclass", T_INT, OFF(objclass), RO},
- {"type", T_INT, OFF(type), RO},
- {"boxtype", T_INT, OFF(boxtype)},
- {"x", T_FLOAT, OFF(x)},
- {"y", T_FLOAT, OFF(y)},
- {"w", T_FLOAT, OFF(w)},
- {"h", T_FLOAT, OFF(h)},
- {"col1", T_INT, OFF(col1)},
- {"col2", T_INT, OFF(col2)},
- {"align", T_INT, OFF(align)},
- {"lcol", T_INT, OFF(lcol)},
- {"lsize", T_FLOAT, OFF(lsize)},
- /* "label" is treated specially! */
- {"lstyle", T_INT, OFF(lstyle)},
- {"pushed", T_INT, OFF(pushed), RO},
- {"focus", T_INT, OFF(focus), RO},
- {"belowmouse", T_INT, OFF(belowmouse),RO},
-/* {"frozen", T_INT, OFF(frozen), RO}, */
- {"active", T_INT, OFF(active)},
- {"input", T_INT, OFF(input)},
- {"visible", T_INT, OFF(visible), RO},
- {"radio", T_INT, OFF(radio)},
- {"automatic", T_INT, OFF(automatic)},
- {NULL} /* Sentinel */
+ {"objclass", T_INT, OFF(objclass), RO},
+ {"type", T_INT, OFF(type), RO},
+ {"boxtype", T_INT, OFF(boxtype)},
+ {"x", T_FLOAT, OFF(x)},
+ {"y", T_FLOAT, OFF(y)},
+ {"w", T_FLOAT, OFF(w)},
+ {"h", T_FLOAT, OFF(h)},
+ {"col1", T_INT, OFF(col1)},
+ {"col2", T_INT, OFF(col2)},
+ {"align", T_INT, OFF(align)},
+ {"lcol", T_INT, OFF(lcol)},
+ {"lsize", T_FLOAT, OFF(lsize)},
+ /* "label" is treated specially! */
+ {"lstyle", T_INT, OFF(lstyle)},
+ {"pushed", T_INT, OFF(pushed), RO},
+ {"focus", T_INT, OFF(focus), RO},
+ {"belowmouse", T_INT, OFF(belowmouse),RO},
+/* {"frozen", T_INT, OFF(frozen), RO}, */
+ {"active", T_INT, OFF(active)},
+ {"input", T_INT, OFF(input)},
+ {"visible", T_INT, OFF(visible), RO},
+ {"radio", T_INT, OFF(radio)},
+ {"automatic", T_INT, OFF(automatic)},
+ {NULL} /* Sentinel */
};
#undef OFF
@@ -307,99 +307,99 @@ static struct memberlist generic_memberlist[] = {
static PyObject *
generic_getattr(genericobject *g, char *name)
{
- PyObject *meth;
+ PyObject *meth;
- /* XXX Ought to special-case name "__methods__" */
- if (g-> ob_methods) {
- meth = Py_FindMethod(g->ob_methods, (PyObject *)g, name);
- if (meth != NULL) return meth;
- PyErr_Clear();
- }
+ /* XXX Ought to special-case name "__methods__" */
+ if (g-> ob_methods) {
+ meth = Py_FindMethod(g->ob_methods, (PyObject *)g, name);
+ if (meth != NULL) return meth;
+ PyErr_Clear();
+ }
- meth = Py_FindMethod(generic_methods, (PyObject *)g, name);
- if (meth != NULL)
- return meth;
- PyErr_Clear();
+ meth = Py_FindMethod(generic_methods, (PyObject *)g, name);
+ if (meth != NULL)
+ return meth;
+ PyErr_Clear();
- /* "label" is an exception, getmember only works for char pointers,
- not for char arrays */
- if (strcmp(name, "label") == 0)
- return PyString_FromString(g->ob_generic->label);
+ /* "label" is an exception, getmember only works for char pointers,
+ not for char arrays */
+ if (strcmp(name, "label") == 0)
+ return PyString_FromString(g->ob_generic->label);
- return PyMember_Get((char *)g->ob_generic, generic_memberlist, name);
+ return PyMember_Get((char *)g->ob_generic, generic_memberlist, name);
}
static int
generic_setattr(genericobject *g, char *name, PyObject *v)
{
- int ret;
+ int ret;
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete forms object attributes");
- return -1;
- }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete forms object attributes");
+ return -1;
+ }
- /* "label" is an exception: setmember doesn't set strings;
- and FORMS wants you to call a function to set the label */
- if (strcmp(name, "label") == 0) {
- if (!PyString_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "label attr must be string");
- return -1;
- }
- fl_set_object_label(g->ob_generic, PyString_AsString(v));
- return 0;
- }
+ /* "label" is an exception: setmember doesn't set strings;
+ and FORMS wants you to call a function to set the label */
+ if (strcmp(name, "label") == 0) {
+ if (!PyString_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "label attr must be string");
+ return -1;
+ }
+ fl_set_object_label(g->ob_generic, PyString_AsString(v));
+ return 0;
+ }
- ret = PyMember_Set((char *)g->ob_generic, generic_memberlist, name, v);
+ ret = PyMember_Set((char *)g->ob_generic, generic_memberlist, name, v);
- /* Rather than calling all the various set_object_* functions,
- we call fl_redraw_object here. This is sometimes redundant
- but I doubt that's a big problem */
- if (ret == 0)
- fl_redraw_object(g->ob_generic);
+ /* Rather than calling all the various set_object_* functions,
+ we call fl_redraw_object here. This is sometimes redundant
+ but I doubt that's a big problem */
+ if (ret == 0)
+ fl_redraw_object(g->ob_generic);
- return ret;
+ return ret;
}
static PyObject *
generic_repr(genericobject *g)
{
- char buf[100];
- PyOS_snprintf(buf, sizeof(buf), "<FORMS_object at %p, objclass=%d>",
- g, g->ob_generic->objclass);
- return PyString_FromString(buf);
+ char buf[100];
+ PyOS_snprintf(buf, sizeof(buf), "<FORMS_object at %p, objclass=%d>",
+ g, g->ob_generic->objclass);
+ return PyString_FromString(buf);
}
static PyTypeObject GenericObjecttype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "fl.FORMS_object", /*tp_name*/
- sizeof(genericobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)generic_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)generic_getattr, /*tp_getattr*/
- (setattrfunc)generic_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- (reprfunc)generic_repr, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "fl.FORMS_object", /*tp_name*/
+ sizeof(genericobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)generic_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)generic_getattr, /*tp_getattr*/
+ (setattrfunc)generic_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ (reprfunc)generic_repr, /*tp_repr*/
};
static PyObject *
newgenericobject(FL_OBJECT *generic, PyMethodDef *methods)
{
- genericobject *g;
- g = PyObject_New(genericobject, &GenericObjecttype);
- if (g == NULL)
- return NULL;
- g-> ob_generic = generic;
- g->ob_methods = methods;
- g->ob_callback = NULL;
- g->ob_callback_arg = NULL;
- knowgeneric(g);
- return (PyObject *)g;
+ genericobject *g;
+ g = PyObject_New(genericobject, &GenericObjecttype);
+ if (g == NULL)
+ return NULL;
+ g-> ob_generic = generic;
+ g->ob_methods = methods;
+ g->ob_callback = NULL;
+ g->ob_callback_arg = NULL;
+ knowgeneric(g);
+ return (PyObject *)g;
}
/**********************************************************************/
@@ -409,70 +409,70 @@ newgenericobject(FL_OBJECT *generic, PyMethodDef *methods)
static PyObject *
call_forms_INf (void (*func)(FL_OBJECT *, float), FL_OBJECT *obj, PyObject *args)
{
- float parameter;
+ float parameter;
- if (!PyArg_Parse(args, "f", &parameter)) return NULL;
+ if (!PyArg_Parse(args, "f", &parameter)) return NULL;
- (*func) (obj, parameter);
+ (*func) (obj, parameter);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, float) */
static PyObject *
call_forms_INfINf (void (*func)(FL_OBJECT *, float, float), FL_OBJECT *obj, PyObject *args)
{
- float par1, par2;
+ float par1, par2;
- if (!PyArg_Parse(args, "(ff)", &par1, &par2)) return NULL;
+ if (!PyArg_Parse(args, "(ff)", &par1, &par2)) return NULL;
- (*func) (obj, par1, par2);
+ (*func) (obj, par1, par2);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, int) */
static PyObject *
call_forms_INi (void (*func)(FL_OBJECT *, int), FL_OBJECT *obj, PyObject *args)
{
- int parameter;
+ int parameter;
- if (!PyArg_Parse(args, "i", &parameter)) return NULL;
+ if (!PyArg_Parse(args, "i", &parameter)) return NULL;
- (*func) (obj, parameter);
+ (*func) (obj, parameter);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, char) */
static PyObject *
call_forms_INc (void (*func)(FL_OBJECT *, int), FL_OBJECT *obj, PyObject *args)
{
- char *a;
+ char *a;
- if (!PyArg_Parse(args, "s", &a)) return NULL;
+ if (!PyArg_Parse(args, "s", &a)) return NULL;
- (*func) (obj, a[0]);
+ (*func) (obj, a[0]);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void func (object, string) */
static PyObject *
call_forms_INstr (void (*func)(FL_OBJECT *, char *), FL_OBJECT *obj, PyObject *args)
{
- char *a;
+ char *a;
- if (!PyArg_Parse(args, "s", &a)) return NULL;
+ if (!PyArg_Parse(args, "s", &a)) return NULL;
- (*func) (obj, a);
+ (*func) (obj, a);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -480,15 +480,15 @@ call_forms_INstr (void (*func)(FL_OBJECT *, char *), FL_OBJECT *obj, PyObject *a
static PyObject *
call_forms_INiINstr (void (*func)(FL_OBJECT *, int, char *), FL_OBJECT *obj, PyObject *args)
{
- char *b;
- int a;
-
- if (!PyArg_Parse(args, "(is)", &a, &b)) return NULL;
-
- (*func) (obj, a, b);
-
- Py_INCREF(Py_None);
- return Py_None;
+ char *b;
+ int a;
+
+ if (!PyArg_Parse(args, "(is)", &a, &b)) return NULL;
+
+ (*func) (obj, a, b);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef UNUSED
@@ -496,14 +496,14 @@ call_forms_INiINstr (void (*func)(FL_OBJECT *, int, char *), FL_OBJECT *obj, PyO
static PyObject *
call_forms_INiINi (void (*func)(FL_OBJECT *, int, int), FL_OBJECT *obj, PyObject *args)
{
- int par1, par2;
-
- if (!PyArg_Parse(args, "(ii)", &par1, &par2)) return NULL;
-
- (*func) (obj, par1, par2);
-
- Py_INCREF(Py_None);
- return Py_None;
+ int par1, par2;
+
+ if (!PyArg_Parse(args, "(ii)", &par1, &par2)) return NULL;
+
+ (*func) (obj, par1, par2);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -511,58 +511,58 @@ call_forms_INiINi (void (*func)(FL_OBJECT *, int, int), FL_OBJECT *obj, PyObject
static PyObject *
call_forms_Ri (int (*func)(FL_OBJECT *), FL_OBJECT *obj)
{
- int retval;
+ int retval;
- retval = (*func) (obj);
+ retval = (*func) (obj);
- return PyInt_FromLong ((long) retval);
+ return PyInt_FromLong ((long) retval);
}
/* char * func (object) */
static PyObject *
call_forms_Rstr (char * (*func)(FL_OBJECT *), FL_OBJECT *obj)
{
- char *str;
+ char *str;
- str = (*func) (obj);
+ str = (*func) (obj);
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString (str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString (str);
}
/* int func (object) */
static PyObject *
call_forms_Rf (float (*func)(FL_OBJECT *), FL_OBJECT *obj)
{
- float retval;
+ float retval;
- retval = (*func) (obj);
+ retval = (*func) (obj);
- return PyFloat_FromDouble (retval);
+ return PyFloat_FromDouble (retval);
}
static PyObject *
call_forms_OUTfOUTf (void (*func)(FL_OBJECT *, float *, float *), FL_OBJECT *obj)
{
- float f1, f2;
+ float f1, f2;
- (*func) (obj, &f1, &f2);
+ (*func) (obj, &f1, &f2);
- return Py_BuildValue("(ff)", f1, f2);
+ return Py_BuildValue("(ff)", f1, f2);
}
#ifdef UNUSED
static PyObject *
call_forms_OUTf (void (*func)(FL_OBJECT *, float *), FL_OBJECT *obj)
{
- float f;
+ float f;
- (*func) (obj, &f);
+ (*func) (obj, &f);
- return PyFloat_FromDouble (f);
+ return PyFloat_FromDouble (f);
}
#endif
@@ -572,172 +572,172 @@ call_forms_OUTf (void (*func)(FL_OBJECT *, float *), FL_OBJECT *obj)
static PyObject *
set_browser_topline(genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_browser_topline, g-> ob_generic, args);
+ return call_forms_INi (fl_set_browser_topline, g-> ob_generic, args);
}
static PyObject *
clear_browser(genericobject *g)
{
- return generic_call (g, fl_clear_browser);
+ return generic_call (g, fl_clear_browser);
}
static PyObject *
add_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_add_browser_line, g-> ob_generic, args);
+ return call_forms_INstr (fl_add_browser_line, g-> ob_generic, args);
}
static PyObject *
addto_browser (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_addto_browser, g-> ob_generic, args);
+ return call_forms_INstr (fl_addto_browser, g-> ob_generic, args);
}
static PyObject *
insert_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INiINstr (fl_insert_browser_line,
- g-> ob_generic, args);
+ return call_forms_INiINstr (fl_insert_browser_line,
+ g-> ob_generic, args);
}
static PyObject *
delete_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_delete_browser_line, g-> ob_generic, args);
+ return call_forms_INi (fl_delete_browser_line, g-> ob_generic, args);
}
static PyObject *
replace_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INiINstr (fl_replace_browser_line,
- g-> ob_generic, args);
+ return call_forms_INiINstr (fl_replace_browser_line,
+ g-> ob_generic, args);
}
static PyObject *
get_browser_line(genericobject *g, PyObject *args)
{
- int i;
- char *str;
+ int i;
+ char *str;
- if (!PyArg_Parse(args, "i", &i))
- return NULL;
+ if (!PyArg_Parse(args, "i", &i))
+ return NULL;
- str = fl_get_browser_line (g->ob_generic, i);
+ str = fl_get_browser_line (g->ob_generic, i);
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString (str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString (str);
}
static PyObject *
load_browser (genericobject *g, PyObject *args)
{
- /* XXX strictly speaking this is wrong since fl_load_browser
- XXX returns int, not void */
- return call_forms_INstr (fl_load_browser, g-> ob_generic, args);
+ /* XXX strictly speaking this is wrong since fl_load_browser
+ XXX returns int, not void */
+ return call_forms_INstr (fl_load_browser, g-> ob_generic, args);
}
static PyObject *
get_browser_maxline(genericobject *g)
{
- return call_forms_Ri (fl_get_browser_maxline, g-> ob_generic);
+ return call_forms_Ri (fl_get_browser_maxline, g-> ob_generic);
}
static PyObject *
select_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_select_browser_line, g-> ob_generic, args);
+ return call_forms_INi (fl_select_browser_line, g-> ob_generic, args);
}
static PyObject *
deselect_browser_line (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_deselect_browser_line, g-> ob_generic, args);
+ return call_forms_INi (fl_deselect_browser_line, g-> ob_generic, args);
}
static PyObject *
deselect_browser (genericobject *g)
{
- return generic_call (g, fl_deselect_browser);
+ return generic_call (g, fl_deselect_browser);
}
static PyObject *
isselected_browser_line (genericobject *g, PyObject *args)
{
- int i, j;
-
- if (!PyArg_Parse(args, "i", &i))
- return NULL;
-
- j = fl_isselected_browser_line (g->ob_generic, i);
-
- return PyInt_FromLong (j);
+ int i, j;
+
+ if (!PyArg_Parse(args, "i", &i))
+ return NULL;
+
+ j = fl_isselected_browser_line (g->ob_generic, i);
+
+ return PyInt_FromLong (j);
}
static PyObject *
get_browser (genericobject *g)
{
- return call_forms_Ri (fl_get_browser, g-> ob_generic);
+ return call_forms_Ri (fl_get_browser, g-> ob_generic);
}
static PyObject *
set_browser_fontsize (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_browser_fontsize, g-> ob_generic, args);
+ return call_forms_INf (fl_set_browser_fontsize, g-> ob_generic, args);
}
static PyObject *
set_browser_fontstyle (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_browser_fontstyle, g-> ob_generic, args);
+ return call_forms_INi (fl_set_browser_fontstyle, g-> ob_generic, args);
}
static PyObject *
set_browser_specialkey (genericobject *g, PyObject *args)
{
- return call_forms_INc(fl_set_browser_specialkey, g-> ob_generic, args);
+ return call_forms_INc(fl_set_browser_specialkey, g-> ob_generic, args);
}
static PyMethodDef browser_methods[] = {
- {"set_browser_topline", (PyCFunction)set_browser_topline,
- METH_OLDARGS},
- {"clear_browser", (PyCFunction)clear_browser,
- METH_NOARGS},
- {"add_browser_line", (PyCFunction)add_browser_line,
- METH_OLDARGS},
- {"addto_browser", (PyCFunction)addto_browser,
- METH_OLDARGS},
- {"insert_browser_line", (PyCFunction)insert_browser_line,
- METH_OLDARGS},
- {"delete_browser_line", (PyCFunction)delete_browser_line,
- METH_OLDARGS},
- {"replace_browser_line", (PyCFunction)replace_browser_line,
- METH_OLDARGS},
- {"get_browser_line", (PyCFunction)get_browser_line,
- METH_OLDARGS},
- {"load_browser", (PyCFunction)load_browser,
- METH_OLDARGS},
- {"get_browser_maxline", (PyCFunction)get_browser_maxline,
- METH_NOARGS,}
- {"select_browser_line", (PyCFunction)select_browser_line,
- METH_OLDARGS},
- {"deselect_browser_line", (PyCFunction)deselect_browser_line,
- METH_OLDARGS},
- {"deselect_browser", (PyCFunction)deselect_browser,
- METH_NOARGS,}
- {"isselected_browser_line", (PyCFunction)isselected_browser_line,
- METH_OLDARGS},
- {"get_browser", (PyCFunction)get_browser,
- METH_NOARGS,}
- {"set_browser_fontsize", (PyCFunction)set_browser_fontsize,
- METH_OLDARGS},
- {"set_browser_fontstyle", (PyCFunction)set_browser_fontstyle,
- METH_OLDARGS},
- {"set_browser_specialkey", (PyCFunction)set_browser_specialkey,
- METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_browser_topline", (PyCFunction)set_browser_topline,
+ METH_OLDARGS},
+ {"clear_browser", (PyCFunction)clear_browser,
+ METH_NOARGS},
+ {"add_browser_line", (PyCFunction)add_browser_line,
+ METH_OLDARGS},
+ {"addto_browser", (PyCFunction)addto_browser,
+ METH_OLDARGS},
+ {"insert_browser_line", (PyCFunction)insert_browser_line,
+ METH_OLDARGS},
+ {"delete_browser_line", (PyCFunction)delete_browser_line,
+ METH_OLDARGS},
+ {"replace_browser_line", (PyCFunction)replace_browser_line,
+ METH_OLDARGS},
+ {"get_browser_line", (PyCFunction)get_browser_line,
+ METH_OLDARGS},
+ {"load_browser", (PyCFunction)load_browser,
+ METH_OLDARGS},
+ {"get_browser_maxline", (PyCFunction)get_browser_maxline,
+ METH_NOARGS,}
+ {"select_browser_line", (PyCFunction)select_browser_line,
+ METH_OLDARGS},
+ {"deselect_browser_line", (PyCFunction)deselect_browser_line,
+ METH_OLDARGS},
+ {"deselect_browser", (PyCFunction)deselect_browser,
+ METH_NOARGS,}
+ {"isselected_browser_line", (PyCFunction)isselected_browser_line,
+ METH_OLDARGS},
+ {"get_browser", (PyCFunction)get_browser,
+ METH_NOARGS,}
+ {"set_browser_fontsize", (PyCFunction)set_browser_fontsize,
+ METH_OLDARGS},
+ {"set_browser_fontstyle", (PyCFunction)set_browser_fontstyle,
+ METH_OLDARGS},
+ {"set_browser_specialkey", (PyCFunction)set_browser_specialkey,
+ METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class: button */
@@ -745,33 +745,33 @@ static PyMethodDef browser_methods[] = {
static PyObject *
set_button(genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_button, g-> ob_generic, args);
+ return call_forms_INi (fl_set_button, g-> ob_generic, args);
}
static PyObject *
get_button(genericobject *g)
{
- return call_forms_Ri (fl_get_button, g-> ob_generic);
+ return call_forms_Ri (fl_get_button, g-> ob_generic);
}
static PyObject *
get_button_numb(genericobject *g)
{
- return call_forms_Ri (fl_get_button_numb, g-> ob_generic);
+ return call_forms_Ri (fl_get_button_numb, g-> ob_generic);
}
static PyObject *
set_button_shortcut(genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_set_button_shortcut, g-> ob_generic, args);
+ return call_forms_INstr (fl_set_button_shortcut, g-> ob_generic, args);
}
static PyMethodDef button_methods[] = {
- {"set_button", (PyCFunction)set_button, METH_OLDARGS},
- {"get_button", (PyCFunction)get_button, METH_NOARGS},
- {"get_button_numb", (PyCFunction)get_button_numb, METH_NOARGS},
- {"set_button_shortcut", (PyCFunction)set_button_shortcut, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_button", (PyCFunction)set_button, METH_OLDARGS},
+ {"get_button", (PyCFunction)get_button, METH_NOARGS},
+ {"get_button_numb", (PyCFunction)get_button_numb, METH_NOARGS},
+ {"set_button_shortcut", (PyCFunction)set_button_shortcut, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class: choice */
@@ -779,68 +779,68 @@ static PyMethodDef button_methods[] = {
static PyObject *
set_choice(genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_choice, g-> ob_generic, args);
+ return call_forms_INi (fl_set_choice, g-> ob_generic, args);
}
static PyObject *
get_choice(genericobject *g)
{
- return call_forms_Ri (fl_get_choice, g-> ob_generic);
+ return call_forms_Ri (fl_get_choice, g-> ob_generic);
}
static PyObject *
clear_choice (genericobject *g)
{
- return generic_call (g, fl_clear_choice);
+ return generic_call (g, fl_clear_choice);
}
static PyObject *
addto_choice (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_addto_choice, g-> ob_generic, args);
+ return call_forms_INstr (fl_addto_choice, g-> ob_generic, args);
}
static PyObject *
replace_choice (genericobject *g, PyObject *args)
{
- return call_forms_INiINstr (fl_replace_choice, g-> ob_generic, args);
+ return call_forms_INiINstr (fl_replace_choice, g-> ob_generic, args);
}
static PyObject *
delete_choice (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_delete_choice, g-> ob_generic, args);
+ return call_forms_INi (fl_delete_choice, g-> ob_generic, args);
}
static PyObject *
get_choice_text (genericobject *g)
{
- return call_forms_Rstr (fl_get_choice_text, g-> ob_generic);
+ return call_forms_Rstr (fl_get_choice_text, g-> ob_generic);
}
static PyObject *
set_choice_fontsize (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_choice_fontsize, g-> ob_generic, args);
+ return call_forms_INf (fl_set_choice_fontsize, g-> ob_generic, args);
}
static PyObject *
set_choice_fontstyle (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_choice_fontstyle, g-> ob_generic, args);
+ return call_forms_INi (fl_set_choice_fontstyle, g-> ob_generic, args);
}
static PyMethodDef choice_methods[] = {
- {"set_choice", (PyCFunction)set_choice, METH_OLDARGS},
- {"get_choice", (PyCFunction)get_choice, METH_NOARGS},
- {"clear_choice", (PyCFunction)clear_choice, METH_NOARGS},
- {"addto_choice", (PyCFunction)addto_choice, METH_OLDARGS},
- {"replace_choice", (PyCFunction)replace_choice, METH_OLDARGS},
- {"delete_choice", (PyCFunction)delete_choice, METH_OLDARGS},
- {"get_choice_text", (PyCFunction)get_choice_text, METH_NOARGS},
- {"set_choice_fontsize", (PyCFunction)set_choice_fontsize, METH_OLDARGS},
- {"set_choice_fontstyle",(PyCFunction)set_choice_fontstyle, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_choice", (PyCFunction)set_choice, METH_OLDARGS},
+ {"get_choice", (PyCFunction)get_choice, METH_NOARGS},
+ {"clear_choice", (PyCFunction)clear_choice, METH_NOARGS},
+ {"addto_choice", (PyCFunction)addto_choice, METH_OLDARGS},
+ {"replace_choice", (PyCFunction)replace_choice, METH_OLDARGS},
+ {"delete_choice", (PyCFunction)delete_choice, METH_OLDARGS},
+ {"get_choice_text", (PyCFunction)get_choice_text, METH_NOARGS},
+ {"set_choice_fontsize", (PyCFunction)set_choice_fontsize, METH_OLDARGS},
+ {"set_choice_fontstyle",(PyCFunction)set_choice_fontstyle, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class : Clock */
@@ -848,16 +848,16 @@ static PyMethodDef choice_methods[] = {
static PyObject *
get_clock(genericobject *g)
{
- int i0, i1, i2;
+ int i0, i1, i2;
- fl_get_clock (g->ob_generic, &i0, &i1, &i2);
+ fl_get_clock (g->ob_generic, &i0, &i1, &i2);
- return Py_BuildValue("(iii)", i0, i1, i2);
+ return Py_BuildValue("(iii)", i0, i1, i2);
}
static PyMethodDef clock_methods[] = {
- {"get_clock", (PyCFunction)get_clock, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"get_clock", (PyCFunction)get_clock, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
/* CLass : Counters */
@@ -865,53 +865,53 @@ static PyMethodDef clock_methods[] = {
static PyObject *
get_counter_value(genericobject *g)
{
- return call_forms_Rf (fl_get_counter_value, g-> ob_generic);
+ return call_forms_Rf (fl_get_counter_value, g-> ob_generic);
}
static PyObject *
set_counter_value (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_counter_value, g-> ob_generic, args);
+ return call_forms_INf (fl_set_counter_value, g-> ob_generic, args);
}
static PyObject *
set_counter_precision (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_counter_precision, g-> ob_generic, args);
+ return call_forms_INi (fl_set_counter_precision, g-> ob_generic, args);
}
static PyObject *
set_counter_bounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_counter_bounds, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_counter_bounds, g-> ob_generic, args);
}
static PyObject *
set_counter_step (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_counter_step, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_counter_step, g-> ob_generic, args);
}
static PyObject *
set_counter_return (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_counter_return, g-> ob_generic, args);
+ return call_forms_INi (fl_set_counter_return, g-> ob_generic, args);
}
static PyMethodDef counter_methods[] = {
- {"set_counter_value", (PyCFunction)set_counter_value,
- METH_OLDARGS},
- {"get_counter_value", (PyCFunction)get_counter_value,
- METH_NOARGS},
- {"set_counter_bounds", (PyCFunction)set_counter_bounds,
- METH_OLDARGS},
- {"set_counter_step", (PyCFunction)set_counter_step,
- METH_OLDARGS},
- {"set_counter_precision", (PyCFunction)set_counter_precision,
- METH_OLDARGS},
- {"set_counter_return", (PyCFunction)set_counter_return,
- METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_counter_value", (PyCFunction)set_counter_value,
+ METH_OLDARGS},
+ {"get_counter_value", (PyCFunction)get_counter_value,
+ METH_NOARGS},
+ {"set_counter_bounds", (PyCFunction)set_counter_bounds,
+ METH_OLDARGS},
+ {"set_counter_step", (PyCFunction)set_counter_step,
+ METH_OLDARGS},
+ {"set_counter_precision", (PyCFunction)set_counter_precision,
+ METH_OLDARGS},
+ {"set_counter_return", (PyCFunction)set_counter_return,
+ METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -920,40 +920,40 @@ static PyMethodDef counter_methods[] = {
static PyObject *
get_dial_value(genericobject *g)
{
- return call_forms_Rf (fl_get_dial_value, g-> ob_generic);
+ return call_forms_Rf (fl_get_dial_value, g-> ob_generic);
}
static PyObject *
set_dial_value (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_dial_value, g-> ob_generic, args);
+ return call_forms_INf (fl_set_dial_value, g-> ob_generic, args);
}
static PyObject *
set_dial_bounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_dial_bounds, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_dial_bounds, g-> ob_generic, args);
}
static PyObject *
get_dial_bounds (genericobject *g)
{
- return call_forms_OUTfOUTf (fl_get_dial_bounds, g-> ob_generic);
+ return call_forms_OUTfOUTf (fl_get_dial_bounds, g-> ob_generic);
}
static PyObject *
set_dial_step (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_dial_step, g-> ob_generic, args);
+ return call_forms_INf (fl_set_dial_step, g-> ob_generic, args);
}
static PyMethodDef dial_methods[] = {
- {"set_dial_value", (PyCFunction)set_dial_value, METH_OLDARGS},
- {"get_dial_value", (PyCFunction)get_dial_value, METH_NOARGS},
- {"set_dial_bounds", (PyCFunction)set_dial_bounds, METH_OLDARGS},
- {"get_dial_bounds", (PyCFunction)get_dial_bounds, METH_NOARGS},
- {"set_dial_step", (PyCFunction)set_dial_step, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_dial_value", (PyCFunction)set_dial_value, METH_OLDARGS},
+ {"get_dial_value", (PyCFunction)get_dial_value, METH_NOARGS},
+ {"set_dial_bounds", (PyCFunction)set_dial_bounds, METH_OLDARGS},
+ {"get_dial_bounds", (PyCFunction)get_dial_bounds, METH_NOARGS},
+ {"set_dial_step", (PyCFunction)set_dial_step, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class : Input */
@@ -961,33 +961,33 @@ static PyMethodDef dial_methods[] = {
static PyObject *
set_input (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_set_input, g-> ob_generic, args);
+ return call_forms_INstr (fl_set_input, g-> ob_generic, args);
}
static PyObject *
get_input (genericobject *g)
{
- return call_forms_Rstr (fl_get_input, g-> ob_generic);
+ return call_forms_Rstr (fl_get_input, g-> ob_generic);
}
static PyObject *
set_input_color (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_input_color, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_input_color, g-> ob_generic, args);
}
static PyObject *
set_input_return (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_input_return, g-> ob_generic, args);
+ return call_forms_INi (fl_set_input_return, g-> ob_generic, args);
}
static PyMethodDef input_methods[] = {
- {"set_input", (PyCFunction)set_input, METH_OLDARGS},
- {"get_input", (PyCFunction)get_input, METH_NOARGS},
- {"set_input_color", (PyCFunction)set_input_color, METH_OLDARGS},
- {"set_input_return", (PyCFunction)set_input_return, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_input", (PyCFunction)set_input, METH_OLDARGS},
+ {"get_input", (PyCFunction)get_input, METH_NOARGS},
+ {"set_input_color", (PyCFunction)set_input_color, METH_OLDARGS},
+ {"set_input_return", (PyCFunction)set_input_return, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -996,35 +996,35 @@ static PyMethodDef input_methods[] = {
static PyObject *
set_menu (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_set_menu, g-> ob_generic, args);
+ return call_forms_INstr (fl_set_menu, g-> ob_generic, args);
}
static PyObject *
get_menu (genericobject *g)
{
- /* XXX strictly speaking this is wrong since fl_get_menu
- XXX returns long, not int */
- return call_forms_Ri (fl_get_menu, g-> ob_generic);
+ /* XXX strictly speaking this is wrong since fl_get_menu
+ XXX returns long, not int */
+ return call_forms_Ri (fl_get_menu, g-> ob_generic);
}
static PyObject *
get_menu_text (genericobject *g)
{
- return call_forms_Rstr (fl_get_menu_text, g-> ob_generic);
+ return call_forms_Rstr (fl_get_menu_text, g-> ob_generic);
}
static PyObject *
addto_menu (genericobject *g, PyObject *args)
{
- return call_forms_INstr (fl_addto_menu, g-> ob_generic, args);
+ return call_forms_INstr (fl_addto_menu, g-> ob_generic, args);
}
static PyMethodDef menu_methods[] = {
- {"set_menu", (PyCFunction)set_menu, METH_OLDARGS},
- {"get_menu", (PyCFunction)get_menu, METH_NOARGS},
- {"get_menu_text", (PyCFunction)get_menu_text, METH_NOARGS},
- {"addto_menu", (PyCFunction)addto_menu, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_menu", (PyCFunction)set_menu, METH_OLDARGS},
+ {"get_menu", (PyCFunction)get_menu, METH_NOARGS},
+ {"get_menu_text", (PyCFunction)get_menu_text, METH_NOARGS},
+ {"addto_menu", (PyCFunction)addto_menu, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -1033,132 +1033,132 @@ static PyMethodDef menu_methods[] = {
static PyObject *
get_slider_value(genericobject *g)
{
- return call_forms_Rf (fl_get_slider_value, g-> ob_generic);
+ return call_forms_Rf (fl_get_slider_value, g-> ob_generic);
}
static PyObject *
set_slider_value (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_value, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_value, g-> ob_generic, args);
}
static PyObject *
set_slider_bounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_slider_bounds, g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_slider_bounds, g-> ob_generic, args);
}
static PyObject *
get_slider_bounds (genericobject *g)
{
- return call_forms_OUTfOUTf(fl_get_slider_bounds, g-> ob_generic);
+ return call_forms_OUTfOUTf(fl_get_slider_bounds, g-> ob_generic);
}
static PyObject *
set_slider_return (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_return, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_return, g-> ob_generic, args);
}
static PyObject *
set_slider_size (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_size, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_size, g-> ob_generic, args);
}
static PyObject *
set_slider_precision (genericobject *g, PyObject *args)
{
- return call_forms_INi (fl_set_slider_precision, g-> ob_generic, args);
+ return call_forms_INi (fl_set_slider_precision, g-> ob_generic, args);
}
static PyObject *
set_slider_step (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_slider_step, g-> ob_generic, args);
+ return call_forms_INf (fl_set_slider_step, g-> ob_generic, args);
}
static PyMethodDef slider_methods[] = {
- {"set_slider_value", (PyCFunction)set_slider_value, METH_OLDARGS},
- {"get_slider_value", (PyCFunction)get_slider_value, METH_NOARGS},
- {"set_slider_bounds", (PyCFunction)set_slider_bounds, METH_OLDARGS},
- {"get_slider_bounds", (PyCFunction)get_slider_bounds, METH_NOARGS},
- {"set_slider_return", (PyCFunction)set_slider_return, METH_OLDARGS},
- {"set_slider_size", (PyCFunction)set_slider_size, METH_OLDARGS},
- {"set_slider_precision",(PyCFunction)set_slider_precision, METH_OLDARGS},
- {"set_slider_step", (PyCFunction)set_slider_step, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"set_slider_value", (PyCFunction)set_slider_value, METH_OLDARGS},
+ {"get_slider_value", (PyCFunction)get_slider_value, METH_NOARGS},
+ {"set_slider_bounds", (PyCFunction)set_slider_bounds, METH_OLDARGS},
+ {"get_slider_bounds", (PyCFunction)get_slider_bounds, METH_NOARGS},
+ {"set_slider_return", (PyCFunction)set_slider_return, METH_OLDARGS},
+ {"set_slider_size", (PyCFunction)set_slider_size, METH_OLDARGS},
+ {"set_slider_precision",(PyCFunction)set_slider_precision, METH_OLDARGS},
+ {"set_slider_step", (PyCFunction)set_slider_step, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
set_positioner_xvalue (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_positioner_xvalue, g-> ob_generic, args);
+ return call_forms_INf (fl_set_positioner_xvalue, g-> ob_generic, args);
}
static PyObject *
set_positioner_xbounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_positioner_xbounds,
- g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_positioner_xbounds,
+ g-> ob_generic, args);
}
static PyObject *
set_positioner_yvalue (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_positioner_yvalue, g-> ob_generic, args);
+ return call_forms_INf (fl_set_positioner_yvalue, g-> ob_generic, args);
}
static PyObject *
set_positioner_ybounds (genericobject *g, PyObject *args)
{
- return call_forms_INfINf (fl_set_positioner_ybounds,
- g-> ob_generic, args);
+ return call_forms_INfINf (fl_set_positioner_ybounds,
+ g-> ob_generic, args);
}
static PyObject *
get_positioner_xvalue (genericobject *g)
{
- return call_forms_Rf (fl_get_positioner_xvalue, g-> ob_generic);
+ return call_forms_Rf (fl_get_positioner_xvalue, g-> ob_generic);
}
static PyObject *
get_positioner_xbounds (genericobject *g)
{
- return call_forms_OUTfOUTf (fl_get_positioner_xbounds, g-> ob_generic);
+ return call_forms_OUTfOUTf (fl_get_positioner_xbounds, g-> ob_generic);
}
static PyObject *
get_positioner_yvalue (genericobject *g)
{
- return call_forms_Rf (fl_get_positioner_yvalue, g-> ob_generic);
+ return call_forms_Rf (fl_get_positioner_yvalue, g-> ob_generic);
}
static PyObject *
get_positioner_ybounds (genericobject *g)
{
- return call_forms_OUTfOUTf (fl_get_positioner_ybounds, g-> ob_generic);
+ return call_forms_OUTfOUTf (fl_get_positioner_ybounds, g-> ob_generic);
}
static PyMethodDef positioner_methods[] = {
- {"set_positioner_xvalue", (PyCFunction)set_positioner_xvalue,
- METH_OLDARGS},
- {"set_positioner_yvalue", (PyCFunction)set_positioner_yvalue,
- METH_OLDARGS},
- {"set_positioner_xbounds", (PyCFunction)set_positioner_xbounds,
- METH_OLDARGS},
- {"set_positioner_ybounds", (PyCFunction)set_positioner_ybounds,
- METH_OLDARGS},
- {"get_positioner_xvalue", (PyCFunction)get_positioner_xvalue,
- METH_NOARGS},
- {"get_positioner_yvalue", (PyCFunction)get_positioner_yvalue,
- METH_NOARGS},
- {"get_positioner_xbounds", (PyCFunction)get_positioner_xbounds,
- METH_NOARGS},
- {"get_positioner_ybounds", (PyCFunction)get_positioner_ybounds,
- METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"set_positioner_xvalue", (PyCFunction)set_positioner_xvalue,
+ METH_OLDARGS},
+ {"set_positioner_yvalue", (PyCFunction)set_positioner_yvalue,
+ METH_OLDARGS},
+ {"set_positioner_xbounds", (PyCFunction)set_positioner_xbounds,
+ METH_OLDARGS},
+ {"set_positioner_ybounds", (PyCFunction)set_positioner_ybounds,
+ METH_OLDARGS},
+ {"get_positioner_xvalue", (PyCFunction)get_positioner_xvalue,
+ METH_NOARGS},
+ {"get_positioner_yvalue", (PyCFunction)get_positioner_yvalue,
+ METH_NOARGS},
+ {"get_positioner_xbounds", (PyCFunction)get_positioner_xbounds,
+ METH_NOARGS},
+ {"get_positioner_ybounds", (PyCFunction)get_positioner_ybounds,
+ METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
/* Class timer */
@@ -1166,26 +1166,26 @@ static PyMethodDef positioner_methods[] = {
static PyObject *
set_timer (genericobject *g, PyObject *args)
{
- return call_forms_INf (fl_set_timer, g-> ob_generic, args);
+ return call_forms_INf (fl_set_timer, g-> ob_generic, args);
}
static PyObject *
get_timer (genericobject *g)
{
- return call_forms_Rf (fl_get_timer, g-> ob_generic);
+ return call_forms_Rf (fl_get_timer, g-> ob_generic);
}
static PyMethodDef timer_methods[] = {
- {"set_timer", (PyCFunction)set_timer, METH_OLDARGS},
- {"get_timer", (PyCFunction)get_timer, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"set_timer", (PyCFunction)set_timer, METH_OLDARGS},
+ {"get_timer", (PyCFunction)get_timer, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
/* Form objects */
typedef struct {
- PyObject_HEAD
- FL_FORM *ob_form;
+ PyObject_HEAD
+ FL_FORM *ob_form;
} formobject;
static PyTypeObject Formtype;
@@ -1195,371 +1195,371 @@ static PyTypeObject Formtype;
static PyObject *
form_show_form(formobject *f, PyObject *args)
{
- int place, border;
- char *name;
- if (!PyArg_Parse(args, "(iis)", &place, &border, &name))
- return NULL;
- fl_show_form(f->ob_form, place, border, name);
- Py_INCREF(Py_None);
- return Py_None;
+ int place, border;
+ char *name;
+ if (!PyArg_Parse(args, "(iis)", &place, &border, &name))
+ return NULL;
+ fl_show_form(f->ob_form, place, border, name);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_call(void (*func)(FL_FORM *), FL_FORM *f)
{
- (*func)(f);
+ (*func)(f);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_call_INiINi(void (*func)(FL_FORM *, int, int), FL_FORM *f, PyObject *args)
{
- int a, b;
+ int a, b;
- if (!PyArg_Parse(args, "(ii)", &a, &b)) return NULL;
+ if (!PyArg_Parse(args, "(ii)", &a, &b)) return NULL;
- (*func)(f, a, b);
+ (*func)(f, a, b);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_call_INfINf(void (*func)(FL_FORM *, float, float), FL_FORM *f, PyObject *args)
{
- float a, b;
+ float a, b;
- if (!PyArg_Parse(args, "(ff)", &a, &b)) return NULL;
+ if (!PyArg_Parse(args, "(ff)", &a, &b)) return NULL;
- (*func)(f, a, b);
+ (*func)(f, a, b);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
form_hide_form(formobject *f)
{
- return form_call(fl_hide_form, f-> ob_form);
+ return form_call(fl_hide_form, f-> ob_form);
}
static PyObject *
form_redraw_form(formobject *f)
{
- return form_call(fl_redraw_form, f-> ob_form);
+ return form_call(fl_redraw_form, f-> ob_form);
}
static PyObject *
form_set_form_position(formobject *f, PyObject *args)
{
- return form_call_INiINi(fl_set_form_position, f-> ob_form, args);
+ return form_call_INiINi(fl_set_form_position, f-> ob_form, args);
}
static PyObject *
form_set_form_size(formobject *f, PyObject *args)
{
- return form_call_INiINi(fl_set_form_size, f-> ob_form, args);
+ return form_call_INiINi(fl_set_form_size, f-> ob_form, args);
}
static PyObject *
form_scale_form(formobject *f, PyObject *args)
{
- return form_call_INfINf(fl_scale_form, f-> ob_form, args);
+ return form_call_INfINf(fl_scale_form, f-> ob_form, args);
}
static PyObject *
generic_add_object(formobject *f, PyObject *args, FL_OBJECT *(*func)(int, float, float, float, float, char*), PyMethodDef *internal_methods)
{
- int type;
- float x, y, w, h;
- char *name;
- FL_OBJECT *obj;
+ int type;
+ float x, y, w, h;
+ char *name;
+ FL_OBJECT *obj;
- if (!PyArg_Parse(args,"(iffffs)", &type,&x,&y,&w,&h,&name))
- return NULL;
+ if (!PyArg_Parse(args,"(iffffs)", &type,&x,&y,&w,&h,&name))
+ return NULL;
- fl_addto_form (f-> ob_form);
+ fl_addto_form (f-> ob_form);
- obj = (*func) (type, x, y, w, h, name);
+ obj = (*func) (type, x, y, w, h, name);
- fl_end_form();
+ fl_end_form();
- if (obj == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
+ if (obj == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- return newgenericobject (obj, internal_methods);
+ return newgenericobject (obj, internal_methods);
}
static PyObject *
form_add_button(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_button, button_methods);
+ return generic_add_object(f, args, fl_add_button, button_methods);
}
static PyObject *
form_add_lightbutton(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_lightbutton, button_methods);
+ return generic_add_object(f, args, fl_add_lightbutton, button_methods);
}
static PyObject *
form_add_roundbutton(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_roundbutton, button_methods);
+ return generic_add_object(f, args, fl_add_roundbutton, button_methods);
}
static PyObject *
form_add_menu (formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_menu, menu_methods);
+ return generic_add_object(f, args, fl_add_menu, menu_methods);
}
static PyObject *
form_add_slider(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_slider, slider_methods);
+ return generic_add_object(f, args, fl_add_slider, slider_methods);
}
static PyObject *
form_add_valslider(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_valslider, slider_methods);
+ return generic_add_object(f, args, fl_add_valslider, slider_methods);
}
static PyObject *
form_add_dial(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_dial, dial_methods);
+ return generic_add_object(f, args, fl_add_dial, dial_methods);
}
static PyObject *
form_add_counter(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_counter, counter_methods);
+ return generic_add_object(f, args, fl_add_counter, counter_methods);
}
static PyObject *
form_add_clock(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_clock, clock_methods);
+ return generic_add_object(f, args, fl_add_clock, clock_methods);
}
static PyObject *
form_add_box(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_box,
- (PyMethodDef *)NULL);
+ return generic_add_object(f, args, fl_add_box,
+ (PyMethodDef *)NULL);
}
static PyObject *
form_add_choice(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_choice, choice_methods);
+ return generic_add_object(f, args, fl_add_choice, choice_methods);
}
static PyObject *
form_add_browser(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_browser, browser_methods);
+ return generic_add_object(f, args, fl_add_browser, browser_methods);
}
static PyObject *
form_add_positioner(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_positioner,
- positioner_methods);
+ return generic_add_object(f, args, fl_add_positioner,
+ positioner_methods);
}
static PyObject *
form_add_input(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_input, input_methods);
+ return generic_add_object(f, args, fl_add_input, input_methods);
}
static PyObject *
form_add_text(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_text,
- (PyMethodDef *)NULL);
+ return generic_add_object(f, args, fl_add_text,
+ (PyMethodDef *)NULL);
}
static PyObject *
form_add_timer(formobject *f, PyObject *args)
{
- return generic_add_object(f, args, fl_add_timer, timer_methods);
+ return generic_add_object(f, args, fl_add_timer, timer_methods);
}
static PyObject *
form_freeze_form(formobject *f)
{
- return form_call(fl_freeze_form, f-> ob_form);
+ return form_call(fl_freeze_form, f-> ob_form);
}
static PyObject *
form_unfreeze_form(formobject *f)
{
- return form_call(fl_unfreeze_form, f-> ob_form);
+ return form_call(fl_unfreeze_form, f-> ob_form);
}
static PyObject *
form_activate_form(formobject *f)
{
- return form_call(fl_activate_form, f-> ob_form);
+ return form_call(fl_activate_form, f-> ob_form);
}
static PyObject *
form_deactivate_form(formobject *f)
{
- return form_call(fl_deactivate_form, f-> ob_form);
+ return form_call(fl_deactivate_form, f-> ob_form);
}
static PyObject *
form_bgn_group(formobject *f, PyObject *args)
{
- FL_OBJECT *obj;
+ FL_OBJECT *obj;
- fl_addto_form(f-> ob_form);
- obj = fl_bgn_group();
- fl_end_form();
+ fl_addto_form(f-> ob_form);
+ obj = fl_bgn_group();
+ fl_end_form();
- if (obj == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
+ if (obj == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- return newgenericobject (obj, (PyMethodDef *) NULL);
+ return newgenericobject (obj, (PyMethodDef *) NULL);
}
static PyObject *
form_end_group(formobject *f, PyObject *args)
{
- fl_addto_form(f-> ob_form);
- fl_end_group();
- fl_end_form();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_addto_form(f-> ob_form);
+ fl_end_group();
+ fl_end_form();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_find_first_or_last(FL_OBJECT *(*func)(FL_FORM *, int, float, float), formobject *f, PyObject *args)
{
- int type;
- float mx, my;
- FL_OBJECT *generic;
- genericobject *g;
-
- if (!PyArg_Parse(args, "(iff)", &type, &mx, &my)) return NULL;
+ int type;
+ float mx, my;
+ FL_OBJECT *generic;
+ genericobject *g;
- generic = (*func) (f-> ob_form, type, mx, my);
+ if (!PyArg_Parse(args, "(iff)", &type, &mx, &my)) return NULL;
- if (generic == NULL)
- {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ generic = (*func) (f-> ob_form, type, mx, my);
- g = findgeneric(generic);
- if (g == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "forms_find_{first|last} returns unknown object");
- return NULL;
- }
- Py_INCREF(g);
- return (PyObject *) g;
+ if (generic == NULL)
+ {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ g = findgeneric(generic);
+ if (g == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "forms_find_{first|last} returns unknown object");
+ return NULL;
+ }
+ Py_INCREF(g);
+ return (PyObject *) g;
}
static PyObject *
form_find_first(formobject *f, PyObject *args)
{
- return forms_find_first_or_last(fl_find_first, f, args);
+ return forms_find_first_or_last(fl_find_first, f, args);
}
static PyObject *
form_find_last(formobject *f, PyObject *args)
{
- return forms_find_first_or_last(fl_find_last, f, args);
+ return forms_find_first_or_last(fl_find_last, f, args);
}
static PyObject *
form_set_object_focus(formobject *f, PyObject *args)
{
- genericobject *g;
- if (args == NULL || !is_genericobject(args)) {
- PyErr_BadArgument();
- return NULL;
- }
- g = (genericobject *)args;
- fl_set_object_focus(f->ob_form, g->ob_generic);
- Py_INCREF(Py_None);
- return Py_None;
+ genericobject *g;
+ if (args == NULL || !is_genericobject(args)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ g = (genericobject *)args;
+ fl_set_object_focus(f->ob_form, g->ob_generic);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef form_methods[] = {
/* adm */
- {"show_form", (PyCFunction)form_show_form, METH_OLDARGS},
- {"hide_form", (PyCFunction)form_hide_form, METH_NOARGS},
- {"redraw_form", (PyCFunction)form_redraw_form, METH_NOARGS},
- {"set_form_position", (PyCFunction)form_set_form_position, METH_OLDARGS},
- {"set_form_size", (PyCFunction)form_set_form_size, METH_OLDARGS},
- {"scale_form", (PyCFunction)form_scale_form, METH_OLDARGS},
- {"freeze_form", (PyCFunction)form_freeze_form, METH_NOARGS},
- {"unfreeze_form", (PyCFunction)form_unfreeze_form, METH_NOARGS},
- {"activate_form", (PyCFunction)form_activate_form, METH_NOARGS},
- {"deactivate_form", (PyCFunction)form_deactivate_form, METH_NOARGS},
- {"bgn_group", (PyCFunction)form_bgn_group, METH_OLDARGS},
- {"end_group", (PyCFunction)form_end_group, METH_OLDARGS},
- {"find_first", (PyCFunction)form_find_first, METH_OLDARGS},
- {"find_last", (PyCFunction)form_find_last, METH_OLDARGS},
- {"set_object_focus", (PyCFunction)form_set_object_focus, METH_OLDARGS},
+ {"show_form", (PyCFunction)form_show_form, METH_OLDARGS},
+ {"hide_form", (PyCFunction)form_hide_form, METH_NOARGS},
+ {"redraw_form", (PyCFunction)form_redraw_form, METH_NOARGS},
+ {"set_form_position", (PyCFunction)form_set_form_position, METH_OLDARGS},
+ {"set_form_size", (PyCFunction)form_set_form_size, METH_OLDARGS},
+ {"scale_form", (PyCFunction)form_scale_form, METH_OLDARGS},
+ {"freeze_form", (PyCFunction)form_freeze_form, METH_NOARGS},
+ {"unfreeze_form", (PyCFunction)form_unfreeze_form, METH_NOARGS},
+ {"activate_form", (PyCFunction)form_activate_form, METH_NOARGS},
+ {"deactivate_form", (PyCFunction)form_deactivate_form, METH_NOARGS},
+ {"bgn_group", (PyCFunction)form_bgn_group, METH_OLDARGS},
+ {"end_group", (PyCFunction)form_end_group, METH_OLDARGS},
+ {"find_first", (PyCFunction)form_find_first, METH_OLDARGS},
+ {"find_last", (PyCFunction)form_find_last, METH_OLDARGS},
+ {"set_object_focus", (PyCFunction)form_set_object_focus, METH_OLDARGS},
/* basic objects */
- {"add_button", (PyCFunction)form_add_button, METH_OLDARGS},
-/* {"add_bitmap", (method)form_add_bitmap, METH_OLDARGS}, */
- {"add_lightbutton", (PyCFunction)form_add_lightbutton, METH_OLDARGS},
- {"add_roundbutton", (PyCFunction)form_add_roundbutton, METH_OLDARGS},
- {"add_menu", (PyCFunction)form_add_menu, METH_OLDARGS},
- {"add_slider", (PyCFunction)form_add_slider, METH_OLDARGS},
- {"add_positioner", (PyCFunction)form_add_positioner, METH_OLDARGS},
- {"add_valslider", (PyCFunction)form_add_valslider, METH_OLDARGS},
- {"add_dial", (PyCFunction)form_add_dial, METH_OLDARGS},
- {"add_counter", (PyCFunction)form_add_counter, METH_OLDARGS},
- {"add_box", (PyCFunction)form_add_box, METH_OLDARGS},
- {"add_clock", (PyCFunction)form_add_clock, METH_OLDARGS},
- {"add_choice", (PyCFunction)form_add_choice, METH_OLDARGS},
- {"add_browser", (PyCFunction)form_add_browser, METH_OLDARGS},
- {"add_input", (PyCFunction)form_add_input, METH_OLDARGS},
- {"add_timer", (PyCFunction)form_add_timer, METH_OLDARGS},
- {"add_text", (PyCFunction)form_add_text, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"add_button", (PyCFunction)form_add_button, METH_OLDARGS},
+/* {"add_bitmap", (method)form_add_bitmap, METH_OLDARGS}, */
+ {"add_lightbutton", (PyCFunction)form_add_lightbutton, METH_OLDARGS},
+ {"add_roundbutton", (PyCFunction)form_add_roundbutton, METH_OLDARGS},
+ {"add_menu", (PyCFunction)form_add_menu, METH_OLDARGS},
+ {"add_slider", (PyCFunction)form_add_slider, METH_OLDARGS},
+ {"add_positioner", (PyCFunction)form_add_positioner, METH_OLDARGS},
+ {"add_valslider", (PyCFunction)form_add_valslider, METH_OLDARGS},
+ {"add_dial", (PyCFunction)form_add_dial, METH_OLDARGS},
+ {"add_counter", (PyCFunction)form_add_counter, METH_OLDARGS},
+ {"add_box", (PyCFunction)form_add_box, METH_OLDARGS},
+ {"add_clock", (PyCFunction)form_add_clock, METH_OLDARGS},
+ {"add_choice", (PyCFunction)form_add_choice, METH_OLDARGS},
+ {"add_browser", (PyCFunction)form_add_browser, METH_OLDARGS},
+ {"add_input", (PyCFunction)form_add_input, METH_OLDARGS},
+ {"add_timer", (PyCFunction)form_add_timer, METH_OLDARGS},
+ {"add_text", (PyCFunction)form_add_text, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static void
form_dealloc(formobject *f)
{
- releaseobjects(f->ob_form);
- if (f->ob_form->visible)
- fl_hide_form(f->ob_form);
- fl_free_form(f->ob_form);
- PyObject_Del(f);
+ releaseobjects(f->ob_form);
+ if (f->ob_form->visible)
+ fl_hide_form(f->ob_form);
+ fl_free_form(f->ob_form);
+ PyObject_Del(f);
}
#define OFF(x) offsetof(FL_FORM, x)
static struct memberlist form_memberlist[] = {
- {"window", T_LONG, OFF(window), RO},
- {"w", T_FLOAT, OFF(w)},
- {"h", T_FLOAT, OFF(h)},
- {"x", T_FLOAT, OFF(x), RO},
- {"y", T_FLOAT, OFF(y), RO},
- {"deactivated", T_INT, OFF(deactivated)},
- {"visible", T_INT, OFF(visible), RO},
- {"frozen", T_INT, OFF(frozen), RO},
- {"doublebuf", T_INT, OFF(doublebuf)},
- {NULL} /* Sentinel */
+ {"window", T_LONG, OFF(window), RO},
+ {"w", T_FLOAT, OFF(w)},
+ {"h", T_FLOAT, OFF(h)},
+ {"x", T_FLOAT, OFF(x), RO},
+ {"y", T_FLOAT, OFF(y), RO},
+ {"deactivated", T_INT, OFF(deactivated)},
+ {"visible", T_INT, OFF(visible), RO},
+ {"frozen", T_INT, OFF(frozen), RO},
+ {"doublebuf", T_INT, OFF(doublebuf)},
+ {NULL} /* Sentinel */
};
#undef OFF
@@ -1567,60 +1567,60 @@ static struct memberlist form_memberlist[] = {
static PyObject *
form_getattr(formobject *f, char *name)
{
- PyObject *meth;
+ PyObject *meth;
- meth = Py_FindMethod(form_methods, (PyObject *)f, name);
- if (meth != NULL)
- return meth;
- PyErr_Clear();
- return PyMember_Get((char *)f->ob_form, form_memberlist, name);
+ meth = Py_FindMethod(form_methods, (PyObject *)f, name);
+ if (meth != NULL)
+ return meth;
+ PyErr_Clear();
+ return PyMember_Get((char *)f->ob_form, form_memberlist, name);
}
static int
form_setattr(formobject *f, char *name, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete form attributes");
- return -1;
- }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete form attributes");
+ return -1;
+ }
- return PyMember_Set((char *)f->ob_form, form_memberlist, name, v);
+ return PyMember_Set((char *)f->ob_form, form_memberlist, name, v);
}
static PyObject *
form_repr(formobject *f)
{
- char buf[100];
- PyOS_snprintf(buf, sizeof(buf), "<FORMS_form at %p, window=%ld>",
- f, f->ob_form->window);
- return PyString_FromString(buf);
+ char buf[100];
+ PyOS_snprintf(buf, sizeof(buf), "<FORMS_form at %p, window=%ld>",
+ f, f->ob_form->window);
+ return PyString_FromString(buf);
}
static PyTypeObject Formtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "fl.FORMS_form", /*tp_name*/
- sizeof(formobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)form_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)form_getattr, /*tp_getattr*/
- (setattrfunc)form_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- (reprfunc)form_repr, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "fl.FORMS_form", /*tp_name*/
+ sizeof(formobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)form_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)form_getattr, /*tp_getattr*/
+ (setattrfunc)form_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ (reprfunc)form_repr, /*tp_repr*/
};
static PyObject *
newformobject(FL_FORM *form)
{
- formobject *f;
- f = PyObject_New(formobject, &Formtype);
- if (f == NULL)
- return NULL;
- f->ob_form = form;
- return (PyObject *)f;
+ formobject *f;
+ f = PyObject_New(formobject, &Formtype);
+ if (f == NULL)
+ return NULL;
+ f->ob_form = form;
+ return (PyObject *)f;
}
@@ -1629,35 +1629,35 @@ newformobject(FL_FORM *form)
static PyObject *
forms_make_form(PyObject *dummy, PyObject *args)
{
- int type;
- float w, h;
- FL_FORM *form;
- if (!PyArg_Parse(args, "(iff)", &type, &w, &h))
- return NULL;
- form = fl_bgn_form(type, w, h);
- if (form == NULL) {
- /* XXX Actually, cannot happen! */
- PyErr_NoMemory();
- return NULL;
- }
- fl_end_form();
- return newformobject(form);
+ int type;
+ float w, h;
+ FL_FORM *form;
+ if (!PyArg_Parse(args, "(iff)", &type, &w, &h))
+ return NULL;
+ form = fl_bgn_form(type, w, h);
+ if (form == NULL) {
+ /* XXX Actually, cannot happen! */
+ PyErr_NoMemory();
+ return NULL;
+ }
+ fl_end_form();
+ return newformobject(form);
}
static PyObject *
forms_activate_all_forms(PyObject *f, PyObject *args)
{
- fl_activate_all_forms();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_activate_all_forms();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_deactivate_all_forms(PyObject *f, PyObject *args)
{
- fl_deactivate_all_forms();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_deactivate_all_forms();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *my_event_callback = NULL;
@@ -1665,479 +1665,479 @@ static PyObject *my_event_callback = NULL;
static PyObject *
forms_set_event_call_back(PyObject *dummy, PyObject *args)
{
- if (args == Py_None)
- args = NULL;
- my_event_callback = args;
- Py_XINCREF(args);
- Py_INCREF(Py_None);
- return Py_None;
+ if (args == Py_None)
+ args = NULL;
+ my_event_callback = args;
+ Py_XINCREF(args);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_do_or_check_forms(PyObject *dummy, FL_OBJECT *(*func)(void))
{
- FL_OBJECT *generic;
- genericobject *g;
- PyObject *arg, *res;
-
- for (;;) {
- Py_BEGIN_ALLOW_THREADS
- generic = (*func)();
- Py_END_ALLOW_THREADS
- if (generic == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (generic == FL_EVENT) {
- int dev;
- short val;
- if (my_event_callback == NULL)
- return PyInt_FromLong(-1L);
- dev = fl_qread(&val);
- arg = Py_BuildValue("(ih)", dev, val);
- if (arg == NULL)
- return NULL;
- res = PyEval_CallObject(my_event_callback, arg);
- Py_XDECREF(res);
- Py_DECREF(arg);
- if (res == NULL)
- return NULL; /* Callback raised exception */
- continue;
- }
- g = findgeneric(generic);
- if (g == NULL) {
- /* Object not known to us (some dialogs cause this) */
- continue; /* Ignore it */
- }
- if (g->ob_callback == NULL) {
- Py_INCREF(g);
- return ((PyObject *) g);
- }
- arg = PyTuple_Pack(2, (PyObject *)g, g->ob_callback_arg);
- if (arg == NULL)
- return NULL;
- res = PyEval_CallObject(g->ob_callback, arg);
- Py_XDECREF(res);
- Py_DECREF(arg);
- if (res == NULL)
- return NULL; /* Callback raised exception */
- }
+ FL_OBJECT *generic;
+ genericobject *g;
+ PyObject *arg, *res;
+
+ for (;;) {
+ Py_BEGIN_ALLOW_THREADS
+ generic = (*func)();
+ Py_END_ALLOW_THREADS
+ if (generic == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (generic == FL_EVENT) {
+ int dev;
+ short val;
+ if (my_event_callback == NULL)
+ return PyInt_FromLong(-1L);
+ dev = fl_qread(&val);
+ arg = Py_BuildValue("(ih)", dev, val);
+ if (arg == NULL)
+ return NULL;
+ res = PyEval_CallObject(my_event_callback, arg);
+ Py_XDECREF(res);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return NULL; /* Callback raised exception */
+ continue;
+ }
+ g = findgeneric(generic);
+ if (g == NULL) {
+ /* Object not known to us (some dialogs cause this) */
+ continue; /* Ignore it */
+ }
+ if (g->ob_callback == NULL) {
+ Py_INCREF(g);
+ return ((PyObject *) g);
+ }
+ arg = PyTuple_Pack(2, (PyObject *)g, g->ob_callback_arg);
+ if (arg == NULL)
+ return NULL;
+ res = PyEval_CallObject(g->ob_callback, arg);
+ Py_XDECREF(res);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return NULL; /* Callback raised exception */
+ }
}
static PyObject *
forms_do_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_do_forms);
+ return forms_do_or_check_forms(dummy, fl_do_forms);
}
static PyObject *
forms_check_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_check_forms);
+ return forms_do_or_check_forms(dummy, fl_check_forms);
}
static PyObject *
forms_do_only_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_do_only_forms);
+ return forms_do_or_check_forms(dummy, fl_do_only_forms);
}
static PyObject *
forms_check_only_forms(PyObject *dummy)
{
- return forms_do_or_check_forms(dummy, fl_check_only_forms);
+ return forms_do_or_check_forms(dummy, fl_check_only_forms);
}
#ifdef UNUSED
static PyObject *
fl_call(void (*func)(void))
{
- (*func)();
- Py_INCREF(Py_None);
- return Py_None;
+ (*func)();
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
static PyObject *
forms_set_graphics_mode(PyObject *dummy, PyObject *args)
{
- int rgbmode, doublebuf;
+ int rgbmode, doublebuf;
- if (!PyArg_Parse(args, "(ii)", &rgbmode, &doublebuf))
- return NULL;
- fl_set_graphics_mode(rgbmode,doublebuf);
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_Parse(args, "(ii)", &rgbmode, &doublebuf))
+ return NULL;
+ fl_set_graphics_mode(rgbmode,doublebuf);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_get_rgbmode(PyObject *dummy, PyObject *args)
{
- extern int fl_rgbmode;
+ extern int fl_rgbmode;
- if (args != NULL) {
- PyErr_BadArgument();
- return NULL;
- }
- return PyInt_FromLong((long)fl_rgbmode);
+ if (args != NULL) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ return PyInt_FromLong((long)fl_rgbmode);
}
static PyObject *
forms_show_errors(PyObject *dummy, PyObject *args)
{
- int show;
- if (!PyArg_Parse(args, "i", &show))
- return NULL;
- fl_show_errors(show);
- Py_INCREF(Py_None);
- return Py_None;
+ int show;
+ if (!PyArg_Parse(args, "i", &show))
+ return NULL;
+ fl_show_errors(show);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_set_font_name(PyObject *dummy, PyObject *args)
{
- int numb;
- char *name;
- if (!PyArg_Parse(args, "(is)", &numb, &name))
- return NULL;
- fl_set_font_name(numb, name);
- Py_INCREF(Py_None);
- return Py_None;
+ int numb;
+ char *name;
+ if (!PyArg_Parse(args, "(is)", &numb, &name))
+ return NULL;
+ fl_set_font_name(numb, name);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_qdevice(PyObject *self, PyObject *args)
{
- short arg1;
- if (!PyArg_Parse(args, "h", &arg1))
- return NULL;
- fl_qdevice(arg1);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1;
+ if (!PyArg_Parse(args, "h", &arg1))
+ return NULL;
+ fl_qdevice(arg1);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_unqdevice(PyObject *self, PyObject *args)
{
- short arg1;
- if (!PyArg_Parse(args, "h", &arg1))
- return NULL;
- fl_unqdevice(arg1);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1;
+ if (!PyArg_Parse(args, "h", &arg1))
+ return NULL;
+ fl_unqdevice(arg1);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_isqueued(PyObject *self, PyObject *args)
{
- long retval;
- short arg1;
- if (!PyArg_Parse(args, "h", &arg1))
- return NULL;
- retval = fl_isqueued(arg1);
+ long retval;
+ short arg1;
+ if (!PyArg_Parse(args, "h", &arg1))
+ return NULL;
+ retval = fl_isqueued(arg1);
- return PyInt_FromLong(retval);
+ return PyInt_FromLong(retval);
}
static PyObject *
forms_qtest(PyObject *self, PyObject *args)
{
- long retval;
- retval = fl_qtest();
- return PyInt_FromLong(retval);
+ long retval;
+ retval = fl_qtest();
+ return PyInt_FromLong(retval);
}
static PyObject *
forms_qread(PyObject *self, PyObject *args)
{
- int dev;
- short val;
- Py_BEGIN_ALLOW_THREADS
- dev = fl_qread(&val);
- Py_END_ALLOW_THREADS
- return Py_BuildValue("(ih)", dev, val);
+ int dev;
+ short val;
+ Py_BEGIN_ALLOW_THREADS
+ dev = fl_qread(&val);
+ Py_END_ALLOW_THREADS
+ return Py_BuildValue("(ih)", dev, val);
}
static PyObject *
forms_qreset(PyObject *self)
{
- fl_qreset();
- Py_INCREF(Py_None);
- return Py_None;
+ fl_qreset();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_qenter(PyObject *self, PyObject *args)
{
- short arg1, arg2;
- if (!PyArg_Parse(args, "(hh)", &arg1, &arg2))
- return NULL;
- fl_qenter(arg1, arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1, arg2;
+ if (!PyArg_Parse(args, "(hh)", &arg1, &arg2))
+ return NULL;
+ fl_qenter(arg1, arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_color(PyObject *self, PyObject *args)
{
- int arg;
+ int arg;
- if (!PyArg_Parse(args, "i", &arg)) return NULL;
+ if (!PyArg_Parse(args, "i", &arg)) return NULL;
- fl_color((short) arg);
+ fl_color((short) arg);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_mapcolor(PyObject *self, PyObject *args)
{
- int arg0, arg1, arg2, arg3;
+ int arg0, arg1, arg2, arg3;
- if (!PyArg_Parse(args, "(iiii)", &arg0, &arg1, &arg2, &arg3))
- return NULL;
+ if (!PyArg_Parse(args, "(iiii)", &arg0, &arg1, &arg2, &arg3))
+ return NULL;
- fl_mapcolor(arg0, (short) arg1, (short) arg2, (short) arg3);
+ fl_mapcolor(arg0, (short) arg1, (short) arg2, (short) arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_getmcolor(PyObject *self, PyObject *args)
{
- int arg;
- short r, g, b;
+ int arg;
+ short r, g, b;
- if (!PyArg_Parse(args, "i", &arg)) return NULL;
+ if (!PyArg_Parse(args, "i", &arg)) return NULL;
- fl_getmcolor(arg, &r, &g, &b);
+ fl_getmcolor(arg, &r, &g, &b);
- return Py_BuildValue("(hhh)", r, g, b);
+ return Py_BuildValue("(hhh)", r, g, b);
}
static PyObject *
forms_get_mouse(PyObject *self)
{
- float x, y;
+ float x, y;
- fl_get_mouse(&x, &y);
+ fl_get_mouse(&x, &y);
- return Py_BuildValue("(ff)", x, y);
+ return Py_BuildValue("(ff)", x, y);
}
static PyObject *
forms_tie(PyObject *self, PyObject *args)
{
- short arg1, arg2, arg3;
- if (!PyArg_Parse(args, "(hhh)", &arg1, &arg2, &arg3))
- return NULL;
- fl_tie(arg1, arg2, arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1, arg2, arg3;
+ if (!PyArg_Parse(args, "(hhh)", &arg1, &arg2, &arg3))
+ return NULL;
+ fl_tie(arg1, arg2, arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_show_message(PyObject *f, PyObject *args)
{
- char *a, *b, *c;
+ char *a, *b, *c;
- if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
+ if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- fl_show_message(a, b, c);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ fl_show_message(a, b, c);
+ Py_END_ALLOW_THREADS
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
forms_show_choice(PyObject *f, PyObject *args)
{
- char *m1, *m2, *m3, *b1, *b2, *b3;
- int nb;
- char *format;
- long rv;
-
- if (args == NULL || !PyTuple_Check(args)) {
- PyErr_BadArgument();
- return NULL;
- }
- nb = PyTuple_Size(args) - 3;
- if (nb <= 0) {
- PyErr_SetString(PyExc_TypeError,
- "need at least one button label");
- return NULL;
- }
- if (PyInt_Check(PyTuple_GetItem(args, 3))) {
- PyErr_SetString(PyExc_TypeError,
- "'number-of-buttons' argument not needed");
- return NULL;
- }
- switch (nb) {
- case 1: format = "(ssss)"; break;
- case 2: format = "(sssss)"; break;
- case 3: format = "(ssssss)"; break;
- default:
- PyErr_SetString(PyExc_TypeError, "too many button labels");
- return NULL;
- }
-
- if (!PyArg_Parse(args, format, &m1, &m2, &m3, &b1, &b2, &b3))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- rv = fl_show_choice(m1, m2, m3, nb, b1, b2, b3);
- Py_END_ALLOW_THREADS
- return PyInt_FromLong(rv);
+ char *m1, *m2, *m3, *b1, *b2, *b3;
+ int nb;
+ char *format;
+ long rv;
+
+ if (args == NULL || !PyTuple_Check(args)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ nb = PyTuple_Size(args) - 3;
+ if (nb <= 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "need at least one button label");
+ return NULL;
+ }
+ if (PyInt_Check(PyTuple_GetItem(args, 3))) {
+ PyErr_SetString(PyExc_TypeError,
+ "'number-of-buttons' argument not needed");
+ return NULL;
+ }
+ switch (nb) {
+ case 1: format = "(ssss)"; break;
+ case 2: format = "(sssss)"; break;
+ case 3: format = "(ssssss)"; break;
+ default:
+ PyErr_SetString(PyExc_TypeError, "too many button labels");
+ return NULL;
+ }
+
+ if (!PyArg_Parse(args, format, &m1, &m2, &m3, &b1, &b2, &b3))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ rv = fl_show_choice(m1, m2, m3, nb, b1, b2, b3);
+ Py_END_ALLOW_THREADS
+ return PyInt_FromLong(rv);
}
static PyObject *
forms_show_question(PyObject *f, PyObject *args)
{
- int ret;
- char *a, *b, *c;
+ int ret;
+ char *a, *b, *c;
- if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
+ if (!PyArg_Parse(args, "(sss)", &a, &b, &c)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- ret = fl_show_question(a, b, c);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ ret = fl_show_question(a, b, c);
+ Py_END_ALLOW_THREADS
- return PyInt_FromLong((long) ret);
+ return PyInt_FromLong((long) ret);
}
static PyObject *
forms_show_input(PyObject *f, PyObject *args)
{
- char *str;
- char *a, *b;
+ char *str;
+ char *a, *b;
- if (!PyArg_Parse(args, "(ss)", &a, &b)) return NULL;
+ if (!PyArg_Parse(args, "(ss)", &a, &b)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- str = fl_show_input(a, b);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ str = fl_show_input(a, b);
+ Py_END_ALLOW_THREADS
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(str);
}
static PyObject *
forms_file_selector(PyObject *f, PyObject *args)
{
- char *str;
- char *a, *b, *c, *d;
+ char *str;
+ char *a, *b, *c, *d;
- if (!PyArg_Parse(args, "(ssss)", &a, &b, &c, &d)) return NULL;
+ if (!PyArg_Parse(args, "(ssss)", &a, &b, &c, &d)) return NULL;
- Py_BEGIN_ALLOW_THREADS
- str = fl_show_file_selector(a, b, c, d);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ str = fl_show_file_selector(a, b, c, d);
+ Py_END_ALLOW_THREADS
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(str);
}
static PyObject *
forms_file_selector_func(PyObject *args, char *(*func)(void))
{
- char *str;
+ char *str;
- str = (*func) ();
+ str = (*func) ();
- if (str == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(str);
+ if (str == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(str);
}
static PyObject *
forms_get_directory(PyObject *f, PyObject *args)
{
- return forms_file_selector_func(args, fl_get_directory);
+ return forms_file_selector_func(args, fl_get_directory);
}
static PyObject *
forms_get_pattern(PyObject *f, PyObject *args)
{
- return forms_file_selector_func(args, fl_get_pattern);
+ return forms_file_selector_func(args, fl_get_pattern);
}
static PyObject *
forms_get_filename(PyObject *f, PyObject *args)
{
- return forms_file_selector_func(args, fl_get_filename);
+ return forms_file_selector_func(args, fl_get_filename);
}
static PyMethodDef forms_methods[] = {
/* adm */
- {"make_form", forms_make_form, METH_OLDARGS},
- {"activate_all_forms", forms_activate_all_forms, METH_OLDARGS},
- {"deactivate_all_forms",forms_deactivate_all_forms, METH_OLDARGS},
+ {"make_form", forms_make_form, METH_OLDARGS},
+ {"activate_all_forms", forms_activate_all_forms, METH_OLDARGS},
+ {"deactivate_all_forms",forms_deactivate_all_forms, METH_OLDARGS},
/* gl support wrappers */
- {"qdevice", forms_qdevice, METH_OLDARGS},
- {"unqdevice", forms_unqdevice, METH_OLDARGS},
- {"isqueued", forms_isqueued, METH_OLDARGS},
- {"qtest", forms_qtest, METH_OLDARGS},
- {"qread", forms_qread, METH_OLDARGS},
-/* {"blkqread", forms_blkqread, METH_OLDARGS}, */
- {"qreset", forms_qreset, METH_NOARGS},
- {"qenter", forms_qenter, METH_OLDARGS},
- {"get_mouse", forms_get_mouse, METH_NOARGS},
- {"tie", forms_tie, METH_OLDARGS},
-/* {"new_events", forms_new_events, METH_OLDARGS}, */
- {"color", forms_color, METH_OLDARGS},
- {"mapcolor", forms_mapcolor, METH_OLDARGS},
- {"getmcolor", forms_getmcolor, METH_OLDARGS},
+ {"qdevice", forms_qdevice, METH_OLDARGS},
+ {"unqdevice", forms_unqdevice, METH_OLDARGS},
+ {"isqueued", forms_isqueued, METH_OLDARGS},
+ {"qtest", forms_qtest, METH_OLDARGS},
+ {"qread", forms_qread, METH_OLDARGS},
+/* {"blkqread", forms_blkqread, METH_OLDARGS}, */
+ {"qreset", forms_qreset, METH_NOARGS},
+ {"qenter", forms_qenter, METH_OLDARGS},
+ {"get_mouse", forms_get_mouse, METH_NOARGS},
+ {"tie", forms_tie, METH_OLDARGS},
+/* {"new_events", forms_new_events, METH_OLDARGS}, */
+ {"color", forms_color, METH_OLDARGS},
+ {"mapcolor", forms_mapcolor, METH_OLDARGS},
+ {"getmcolor", forms_getmcolor, METH_OLDARGS},
/* interaction */
- {"do_forms", forms_do_forms, METH_NOARGS},
- {"do_only_forms", forms_do_only_forms, METH_NOARGS},
- {"check_forms", forms_check_forms, METH_NOARGS},
- {"check_only_forms", forms_check_only_forms, METH_NOARGS},
- {"set_event_call_back", forms_set_event_call_back, METH_OLDARGS},
+ {"do_forms", forms_do_forms, METH_NOARGS},
+ {"do_only_forms", forms_do_only_forms, METH_NOARGS},
+ {"check_forms", forms_check_forms, METH_NOARGS},
+ {"check_only_forms", forms_check_only_forms, METH_NOARGS},
+ {"set_event_call_back", forms_set_event_call_back, METH_OLDARGS},
/* goodies */
- {"show_message", forms_show_message, METH_OLDARGS},
- {"show_question", forms_show_question, METH_OLDARGS},
- {"show_choice", forms_show_choice, METH_OLDARGS},
- {"show_input", forms_show_input, METH_OLDARGS},
- {"show_file_selector", forms_file_selector, METH_OLDARGS},
- {"file_selector", forms_file_selector, METH_OLDARGS}, /* BW compat */
- {"get_directory", forms_get_directory, METH_OLDARGS},
- {"get_pattern", forms_get_pattern, METH_OLDARGS},
- {"get_filename", forms_get_filename, METH_OLDARGS},
- {"set_graphics_mode", forms_set_graphics_mode, METH_OLDARGS},
- {"get_rgbmode", forms_get_rgbmode, METH_OLDARGS},
- {"show_errors", forms_show_errors, METH_OLDARGS},
- {"set_font_name", forms_set_font_name, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"show_message", forms_show_message, METH_OLDARGS},
+ {"show_question", forms_show_question, METH_OLDARGS},
+ {"show_choice", forms_show_choice, METH_OLDARGS},
+ {"show_input", forms_show_input, METH_OLDARGS},
+ {"show_file_selector", forms_file_selector, METH_OLDARGS},
+ {"file_selector", forms_file_selector, METH_OLDARGS}, /* BW compat */
+ {"get_directory", forms_get_directory, METH_OLDARGS},
+ {"get_pattern", forms_get_pattern, METH_OLDARGS},
+ {"get_filename", forms_get_filename, METH_OLDARGS},
+ {"set_graphics_mode", forms_set_graphics_mode, METH_OLDARGS},
+ {"get_rgbmode", forms_get_rgbmode, METH_OLDARGS},
+ {"show_errors", forms_show_errors, METH_OLDARGS},
+ {"set_font_name", forms_set_font_name, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initfl(void)
{
-
+
if (PyErr_WarnPy3k("the fl module has been removed in "
"Python 3.0", 2) < 0)
+ return;
+
+ Py_InitModule("fl", forms_methods);
+ if (m == NULL)
return;
-
- Py_InitModule("fl", forms_methods);
- if (m == NULL)
- return;
- foreground();
- fl_init();
+ foreground();
+ fl_init();
}
diff --git a/Modules/fmmodule.c b/Modules/fmmodule.c
index f3f0dc5..3a74107 100644
--- a/Modules/fmmodule.c
+++ b/Modules/fmmodule.c
@@ -11,28 +11,28 @@
/* Font Handle object implementation */
typedef struct {
- PyObject_HEAD
- fmfonthandle fh_fh;
+ PyObject_HEAD
+ fmfonthandle fh_fh;
} fhobject;
static PyTypeObject Fhtype;
-#define is_fhobject(v) ((v)->ob_type == &Fhtype)
+#define is_fhobject(v) ((v)->ob_type == &Fhtype)
static PyObject *
newfhobject(fmfonthandle fh)
{
- fhobject *fhp;
- if (fh == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "error creating new font handle");
- return NULL;
- }
- fhp = PyObject_New(fhobject, &Fhtype);
- if (fhp == NULL)
- return NULL;
- fhp->fh_fh = fh;
- return (PyObject *)fhp;
+ fhobject *fhp;
+ if (fh == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "error creating new font handle");
+ return NULL;
+ }
+ fhp = PyObject_New(fhobject, &Fhtype);
+ if (fhp == NULL)
+ return NULL;
+ fhp->fh_fh = fh;
+ return (PyObject *)fhp;
}
/* Font Handle methods */
@@ -40,10 +40,10 @@ newfhobject(fmfonthandle fh)
static PyObject *
fh_scalefont(fhobject *self, PyObject *args)
{
- double size;
- if (!PyArg_ParseTuple(args, "d", &size))
- return NULL;
- return newfhobject(fmscalefont(self->fh_fh, size));
+ double size;
+ if (!PyArg_ParseTuple(args, "d", &size))
+ return NULL;
+ return newfhobject(fmscalefont(self->fh_fh, size));
}
/* XXX fmmakefont */
@@ -51,54 +51,54 @@ fh_scalefont(fhobject *self, PyObject *args)
static PyObject *
fh_setfont(fhobject *self)
{
- fmsetfont(self->fh_fh);
- Py_INCREF(Py_None);
- return Py_None;
+ fmsetfont(self->fh_fh);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
fh_getfontname(fhobject *self)
{
- char fontname[256];
- int len;
- len = fmgetfontname(self->fh_fh, sizeof fontname, fontname);
- if (len < 0) {
- PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontname");
- return NULL;
- }
- return PyString_FromStringAndSize(fontname, len);
+ char fontname[256];
+ int len;
+ len = fmgetfontname(self->fh_fh, sizeof fontname, fontname);
+ if (len < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontname");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(fontname, len);
}
static PyObject *
fh_getcomment(fhobject *self)
{
- char comment[256];
- int len;
- len = fmgetcomment(self->fh_fh, sizeof comment, comment);
- if (len < 0) {
- PyErr_SetString(PyExc_RuntimeError, "error in fmgetcomment");
- return NULL;
- }
- return PyString_FromStringAndSize(comment, len);
+ char comment[256];
+ int len;
+ len = fmgetcomment(self->fh_fh, sizeof comment, comment);
+ if (len < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "error in fmgetcomment");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(comment, len);
}
static PyObject *
fh_getfontinfo(fhobject *self)
{
- fmfontinfo info;
- if (fmgetfontinfo(self->fh_fh, &info) < 0) {
- PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontinfo");
- return NULL;
- }
- return Py_BuildValue("(llllllll)",
- info.printermatched,
- info.fixed_width,
- info.xorig,
- info.yorig,
- info.xsize,
- info.ysize,
- info.height,
- info.nglyphs);
+ fmfontinfo info;
+ if (fmgetfontinfo(self->fh_fh, &info) < 0) {
+ PyErr_SetString(PyExc_RuntimeError, "error in fmgetfontinfo");
+ return NULL;
+ }
+ return Py_BuildValue("(llllllll)",
+ info.printermatched,
+ info.fixed_width,
+ info.xorig,
+ info.yorig,
+ info.xsize,
+ info.ysize,
+ info.height,
+ info.nglyphs);
}
#if 0
@@ -111,51 +111,51 @@ fh_getwholemetrics(fhobject *self, PyObject *args)
static PyObject *
fh_getstrwidth(fhobject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- return PyInt_FromLong(fmgetstrwidth(self->fh_fh, str));
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ return PyInt_FromLong(fmgetstrwidth(self->fh_fh, str));
}
static PyMethodDef fh_methods[] = {
- {"scalefont", (PyCFunction)fh_scalefont, METH_VARARGS},
- {"setfont", (PyCFunction)fh_setfont, METH_NOARGS},
- {"getfontname", (PyCFunction)fh_getfontname, METH_NOARGS},
- {"getcomment", (PyCFunction)fh_getcomment, METH_NOARGS},
- {"getfontinfo", (PyCFunction)fh_getfontinfo, METH_NOARGS},
+ {"scalefont", (PyCFunction)fh_scalefont, METH_VARARGS},
+ {"setfont", (PyCFunction)fh_setfont, METH_NOARGS},
+ {"getfontname", (PyCFunction)fh_getfontname, METH_NOARGS},
+ {"getcomment", (PyCFunction)fh_getcomment, METH_NOARGS},
+ {"getfontinfo", (PyCFunction)fh_getfontinfo, METH_NOARGS},
#if 0
- {"getwholemetrics", (PyCFunction)fh_getwholemetrics, METH_VARARGS},
+ {"getwholemetrics", (PyCFunction)fh_getwholemetrics, METH_VARARGS},
#endif
- {"getstrwidth", (PyCFunction)fh_getstrwidth, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"getstrwidth", (PyCFunction)fh_getstrwidth, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
fh_getattr(fhobject *fhp, char *name)
{
- return Py_FindMethod(fh_methods, (PyObject *)fhp, name);
+ return Py_FindMethod(fh_methods, (PyObject *)fhp, name);
}
static void
fh_dealloc(fhobject *fhp)
{
- fmfreefont(fhp->fh_fh);
- PyObject_Del(fhp);
+ fmfreefont(fhp->fh_fh);
+ PyObject_Del(fhp);
}
static PyTypeObject Fhtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "fm.font handle", /*tp_name*/
- sizeof(fhobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)fh_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)fh_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "fm.font handle", /*tp_name*/
+ sizeof(fhobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)fh_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)fh_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
@@ -164,29 +164,29 @@ static PyTypeObject Fhtype = {
static PyObject *
fm_init(PyObject *self)
{
- fminit();
- Py_INCREF(Py_None);
- return Py_None;
+ fminit();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
fm_findfont(PyObject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- return newfhobject(fmfindfont(str));
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ return newfhobject(fmfindfont(str));
}
static PyObject *
fm_prstr(PyObject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- fmprstr(str);
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ fmprstr(str);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* XXX This uses a global variable as temporary! Not re-entrant! */
@@ -196,74 +196,74 @@ static PyObject *fontlist;
static void
clientproc(char *fontname)
{
- int err;
- PyObject *v;
- if (fontlist == NULL)
- return;
- v = PyString_FromString(fontname);
- if (v == NULL)
- err = -1;
- else {
- err = PyList_Append(fontlist, v);
- Py_DECREF(v);
- }
- if (err != 0) {
- Py_DECREF(fontlist);
- fontlist = NULL;
- }
+ int err;
+ PyObject *v;
+ if (fontlist == NULL)
+ return;
+ v = PyString_FromString(fontname);
+ if (v == NULL)
+ err = -1;
+ else {
+ err = PyList_Append(fontlist, v);
+ Py_DECREF(v);
+ }
+ if (err != 0) {
+ Py_DECREF(fontlist);
+ fontlist = NULL;
+ }
}
static PyObject *
fm_enumerate(PyObject *self)
{
- PyObject *res;
- fontlist = PyList_New(0);
- if (fontlist == NULL)
- return NULL;
- fmenumerate(clientproc);
- res = fontlist;
- fontlist = NULL;
- return res;
+ PyObject *res;
+ fontlist = PyList_New(0);
+ if (fontlist == NULL)
+ return NULL;
+ fmenumerate(clientproc);
+ res = fontlist;
+ fontlist = NULL;
+ return res;
}
static PyObject *
fm_setpath(PyObject *self, PyObject *args)
{
- char *str;
- if (!PyArg_ParseTuple(args, "s", &str))
- return NULL;
- fmsetpath(str);
- Py_INCREF(Py_None);
- return Py_None;
+ char *str;
+ if (!PyArg_ParseTuple(args, "s", &str))
+ return NULL;
+ fmsetpath(str);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
fm_fontpath(PyObject *self)
{
- return PyString_FromString(fmfontpath());
+ return PyString_FromString(fmfontpath());
}
static PyMethodDef fm_methods[] = {
- {"init", fm_init, METH_NOARGS},
- {"findfont", fm_findfont, METH_VARARGS},
- {"enumerate", fm_enumerate, METH_NOARGS},
- {"prstr", fm_prstr, METH_VARARGS},
- {"setpath", fm_setpath, METH_VARARGS},
- {"fontpath", fm_fontpath, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"init", fm_init, METH_NOARGS},
+ {"findfont", fm_findfont, METH_VARARGS},
+ {"enumerate", fm_enumerate, METH_NOARGS},
+ {"prstr", fm_prstr, METH_VARARGS},
+ {"setpath", fm_setpath, METH_VARARGS},
+ {"fontpath", fm_fontpath, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
void
initfm(void)
{
-
+
if (PyErr_WarnPy3k("the fm module has been removed in "
"Python 3.0", 2) < 0)
+ return;
+
+ Py_InitModule("fm", fm_methods);
+ if (m == NULL)
return;
-
- Py_InitModule("fm", fm_methods);
- if (m == NULL)
- return;
- fminit();
+ fminit();
}
diff --git a/Modules/fpectlmodule.c b/Modules/fpectlmodule.c
index 74354ba..faa279b 100644
--- a/Modules/fpectlmodule.c
+++ b/Modules/fpectlmodule.c
@@ -1,6 +1,6 @@
/*
- ---------------------------------------------------------------------
- / Copyright (c) 1996. \
+ ---------------------------------------------------------------------
+ / Copyright (c) 1996. \
| The Regents of the University of California. |
| All rights reserved. |
| |
@@ -32,12 +32,12 @@
| opinions of authors expressed herein do not necessarily state or |
| reflect those of the United States Government or the University |
| of California, and shall not be used for advertising or product |
- \ endorsement purposes. /
- ---------------------------------------------------------------------
+ \ endorsement purposes. /
+ ---------------------------------------------------------------------
*/
/*
- Floating point exception control module.
+ Floating point exception control module.
This Python module provides bare-bones control over floating point
units from several hardware manufacturers. Specifically, it allows
@@ -95,8 +95,8 @@ static PyObject *turnon_sigfpe (PyObject *self,PyObject *args);
static PyObject *turnoff_sigfpe (PyObject *self,PyObject *args);
static PyMethodDef fpectl_methods[] = {
- {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS},
- {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS},
+ {"turnon_sigfpe", (PyCFunction) turnon_sigfpe, METH_VARARGS},
+ {"turnoff_sigfpe", (PyCFunction) turnoff_sigfpe, METH_VARARGS},
{0,0}
};
@@ -121,19 +121,19 @@ static void fpe_reset(Sigfunc *handler)
* My usage doesn't follow the man page exactly. Maybe somebody
* else can explain handle_sigfpes to me....
* cc -c -I/usr/local/python/include fpectlmodule.c
- * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe
+ * ld -shared -o fpectlmodule.so fpectlmodule.o -lfpe
*/
#include <sigfpe.h>
typedef void user_routine (unsigned[5], int[2]);
typedef void abort_routine (unsigned long);
handle_sigfpes(_OFF, 0,
- (user_routine *)0,
- _TURN_OFF_HANDLER_ON_ERROR,
- NULL);
+ (user_routine *)0,
+ _TURN_OFF_HANDLER_ON_ERROR,
+ NULL);
handle_sigfpes(_ON, _EN_OVERFL | _EN_DIVZERO | _EN_INVALID,
- (user_routine *)0,
- _ABORT_ON_ERROR,
- NULL);
+ (user_routine *)0,
+ _ABORT_ON_ERROR,
+ NULL);
PyOS_setsig(SIGFPE, handler);
/*-- SunOS and Solaris ----------------------------------------------------*/
@@ -194,16 +194,16 @@ static void fpe_reset(Sigfunc *handler)
/*-- DEC ALPHA VMS --------------------------------------------------------*/
#elif defined(__ALPHA) && defined(__VMS)
- IEEE clrmsk;
- IEEE setmsk;
- clrmsk.ieee$q_flags =
- IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
- IEEE$M_MAP_UMZ;
- setmsk.ieee$q_flags =
- IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE |
- IEEE$M_TRAP_ENABLE_OVF;
- sys$ieee_set_fp_control(&clrmsk, &setmsk, 0);
- PyOS_setsig(SIGFPE, handler);
+ IEEE clrmsk;
+ IEEE setmsk;
+ clrmsk.ieee$q_flags =
+ IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
+ IEEE$M_MAP_UMZ;
+ setmsk.ieee$q_flags =
+ IEEE$M_TRAP_ENABLE_INV | IEEE$M_TRAP_ENABLE_DZE |
+ IEEE$M_TRAP_ENABLE_OVF;
+ sys$ieee_set_fp_control(&clrmsk, &setmsk, 0);
+ PyOS_setsig(SIGFPE, handler);
/*-- HP IA64 VMS --------------------------------------------------------*/
#elif defined(__ia64) && defined(__VMS)
@@ -262,13 +262,13 @@ static PyObject *turnoff_sigfpe(PyObject *self,PyObject *args)
fpresetsticky(fpgetsticky());
fpsetmask(0);
#elif defined(__VMS)
- IEEE clrmsk;
- clrmsk.ieee$q_flags =
- IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
- IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV |
- IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF |
- IEEE$M_INHERIT;
- sys$ieee_set_fp_control(&clrmsk, 0, 0);
+ IEEE clrmsk;
+ clrmsk.ieee$q_flags =
+ IEEE$M_TRAP_ENABLE_UNF | IEEE$M_TRAP_ENABLE_INE |
+ IEEE$M_MAP_UMZ | IEEE$M_TRAP_ENABLE_INV |
+ IEEE$M_TRAP_ENABLE_DZE | IEEE$M_TRAP_ENABLE_OVF |
+ IEEE$M_INHERIT;
+ sys$ieee_set_fp_control(&clrmsk, 0, 0);
#else
fputs("Operation not implemented\n", stderr);
#endif
@@ -291,11 +291,11 @@ PyMODINIT_FUNC initfpectl(void)
PyObject *m, *d;
m = Py_InitModule("fpectl", fpectl_methods);
if (m == NULL)
- return;
+ return;
d = PyModule_GetDict(m);
fpe_error = PyErr_NewException("fpectl.error", NULL, NULL);
if (fpe_error != NULL)
- PyDict_SetItemString(d, "error", fpe_error);
+ PyDict_SetItemString(d, "error", fpe_error);
}
#ifdef __cplusplus
diff --git a/Modules/future_builtins.c b/Modules/future_builtins.c
index bcd42ef..3deece6 100644
--- a/Modules/future_builtins.c
+++ b/Modules/future_builtins.c
@@ -24,7 +24,7 @@ from future_builtins import hex, oct\n");
static PyObject *
builtin_hex(PyObject *self, PyObject *v)
{
- return PyNumber_ToBase(v, 16);
+ return PyNumber_ToBase(v, 16);
}
PyDoc_STRVAR(hex_doc,
@@ -36,7 +36,7 @@ Return the hexadecimal representation of an integer or long integer.");
static PyObject *
builtin_oct(PyObject *self, PyObject *v)
{
- return PyNumber_ToBase(v, 8);
+ return PyNumber_ToBase(v, 8);
}
PyDoc_STRVAR(oct_doc,
@@ -48,7 +48,7 @@ Return the octal representation of an integer or long integer.");
static PyObject *
builtin_ascii(PyObject *self, PyObject *v)
{
- return PyObject_Repr(v);
+ return PyObject_Repr(v);
}
PyDoc_STRVAR(ascii_doc,
@@ -61,10 +61,10 @@ will have such characters backslash-escaped.");
/* List of functions exported by this module */
static PyMethodDef module_functions[] = {
- {"hex", builtin_hex, METH_O, hex_doc},
- {"oct", builtin_oct, METH_O, oct_doc},
- {"ascii", builtin_ascii, METH_O, ascii_doc},
- {NULL, NULL} /* Sentinel */
+ {"hex", builtin_hex, METH_O, hex_doc},
+ {"oct", builtin_oct, METH_O, oct_doc},
+ {"ascii", builtin_ascii, METH_O, ascii_doc},
+ {NULL, NULL} /* Sentinel */
};
@@ -73,25 +73,25 @@ static PyMethodDef module_functions[] = {
PyMODINIT_FUNC
initfuture_builtins(void)
{
- PyObject *m, *itertools, *iter_func;
- char *it_funcs[] = {"imap", "ifilter", "izip", NULL};
- char **cur_func;
-
- m = Py_InitModule3("future_builtins", module_functions, module_doc);
- if (m == NULL)
- return;
-
- itertools = PyImport_ImportModuleNoBlock("itertools");
- if (itertools == NULL)
- return;
-
- /* If anything in the following loop fails, we fall through. */
- for (cur_func = it_funcs; *cur_func; ++cur_func){
- iter_func = PyObject_GetAttrString(itertools, *cur_func);
- if (iter_func == NULL ||
- PyModule_AddObject(m, *cur_func+1, iter_func) < 0)
- break;
- }
- Py_DECREF(itertools);
- /* any other initialization needed */
+ PyObject *m, *itertools, *iter_func;
+ char *it_funcs[] = {"imap", "ifilter", "izip", NULL};
+ char **cur_func;
+
+ m = Py_InitModule3("future_builtins", module_functions, module_doc);
+ if (m == NULL)
+ return;
+
+ itertools = PyImport_ImportModuleNoBlock("itertools");
+ if (itertools == NULL)
+ return;
+
+ /* If anything in the following loop fails, we fall through. */
+ for (cur_func = it_funcs; *cur_func; ++cur_func){
+ iter_func = PyObject_GetAttrString(itertools, *cur_func);
+ if (iter_func == NULL ||
+ PyModule_AddObject(m, *cur_func+1, iter_func) < 0)
+ break;
+ }
+ Py_DECREF(itertools);
+ /* any other initialization needed */
}
diff --git a/Modules/gcmodule.c b/Modules/gcmodule.c
index fd33996..384c47d 100644
--- a/Modules/gcmodule.c
+++ b/Modules/gcmodule.c
@@ -19,7 +19,7 @@
*/
#include "Python.h"
-#include "frameobject.h" /* for PyFrame_ClearFreeList */
+#include "frameobject.h" /* for PyFrame_ClearFreeList */
/* Get an object's GC head */
#define AS_GC(o) ((PyGC_Head *)(o)-1)
@@ -30,10 +30,10 @@
/*** Global GC state ***/
struct gc_generation {
- PyGC_Head head;
- int threshold; /* collection threshold */
- int count; /* count of allocations or collections of younger
- generations */
+ PyGC_Head head;
+ int threshold; /* collection threshold */
+ int count; /* count of allocations or collections of younger
+ generations */
};
#define NUM_GENERATIONS 3
@@ -41,10 +41,10 @@ struct gc_generation {
/* linked lists of container objects */
static struct gc_generation generations[NUM_GENERATIONS] = {
- /* PyGC_Head, threshold, count */
- {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},
- {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},
- {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},
+ /* PyGC_Head, threshold, count */
+ {{{GEN_HEAD(0), GEN_HEAD(0), 0}}, 700, 0},
+ {{{GEN_HEAD(1), GEN_HEAD(1), 0}}, 10, 0},
+ {{{GEN_HEAD(2), GEN_HEAD(2), 0}}, 10, 0},
};
PyGC_Head *_PyGC_generation0 = GEN_HEAD(0);
@@ -86,7 +86,7 @@ static Py_ssize_t long_lived_pending = 0;
In addition to the various configurable thresholds, we only trigger a
full collection if the ratio
- long_lived_pending / long_lived_total
+ long_lived_pending / long_lived_total
is above a given value (hardwired to 25%).
The reason is that, while "non-full" collections (i.e., collections of
@@ -108,22 +108,22 @@ static Py_ssize_t long_lived_pending = 0;
This heuristic was suggested by Martin von Löwis on python-dev in
June 2008. His original analysis and proposal can be found at:
- http://mail.python.org/pipermail/python-dev/2008-June/080579.html
+ http://mail.python.org/pipermail/python-dev/2008-June/080579.html
*/
/* set for debugging information */
-#define DEBUG_STATS (1<<0) /* print collection statistics */
-#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
-#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
-#define DEBUG_INSTANCES (1<<3) /* print instances */
-#define DEBUG_OBJECTS (1<<4) /* print other objects */
-#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
-#define DEBUG_LEAK DEBUG_COLLECTABLE | \
- DEBUG_UNCOLLECTABLE | \
- DEBUG_INSTANCES | \
- DEBUG_OBJECTS | \
- DEBUG_SAVEALL
+#define DEBUG_STATS (1<<0) /* print collection statistics */
+#define DEBUG_COLLECTABLE (1<<1) /* print collectable objects */
+#define DEBUG_UNCOLLECTABLE (1<<2) /* print uncollectable objects */
+#define DEBUG_INSTANCES (1<<3) /* print instances */
+#define DEBUG_OBJECTS (1<<4) /* print other objects */
+#define DEBUG_SAVEALL (1<<5) /* save all garbage in gc.garbage */
+#define DEBUG_LEAK DEBUG_COLLECTABLE | \
+ DEBUG_UNCOLLECTABLE | \
+ DEBUG_INSTANCES | \
+ DEBUG_OBJECTS | \
+ DEBUG_SAVEALL
static int debug;
static PyObject *tmod = NULL;
@@ -166,28 +166,28 @@ GC_TENTATIVELY_UNREACHABLE
it has a __del__ method), its gc_refs is restored to GC_REACHABLE again.
----------------------------------------------------------------------------
*/
-#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
-#define GC_REACHABLE _PyGC_REFS_REACHABLE
-#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
+#define GC_UNTRACKED _PyGC_REFS_UNTRACKED
+#define GC_REACHABLE _PyGC_REFS_REACHABLE
+#define GC_TENTATIVELY_UNREACHABLE _PyGC_REFS_TENTATIVELY_UNREACHABLE
#define IS_TRACKED(o) ((AS_GC(o))->gc.gc_refs != GC_UNTRACKED)
#define IS_REACHABLE(o) ((AS_GC(o))->gc.gc_refs == GC_REACHABLE)
#define IS_TENTATIVELY_UNREACHABLE(o) ( \
- (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
+ (AS_GC(o))->gc.gc_refs == GC_TENTATIVELY_UNREACHABLE)
/*** list functions ***/
static void
gc_list_init(PyGC_Head *list)
{
- list->gc.gc_prev = list;
- list->gc.gc_next = list;
+ list->gc.gc_prev = list;
+ list->gc.gc_next = list;
}
static int
gc_list_is_empty(PyGC_Head *list)
{
- return (list->gc.gc_next == list);
+ return (list->gc.gc_next == list);
}
#if 0
@@ -196,10 +196,10 @@ gc_list_is_empty(PyGC_Head *list)
static void
gc_list_append(PyGC_Head *node, PyGC_Head *list)
{
- node->gc.gc_next = list;
- node->gc.gc_prev = list->gc.gc_prev;
- node->gc.gc_prev->gc.gc_next = node;
- list->gc.gc_prev = node;
+ node->gc.gc_next = list;
+ node->gc.gc_prev = list->gc.gc_prev;
+ node->gc.gc_prev->gc.gc_next = node;
+ list->gc.gc_prev = node;
}
#endif
@@ -207,9 +207,9 @@ gc_list_append(PyGC_Head *node, PyGC_Head *list)
static void
gc_list_remove(PyGC_Head *node)
{
- node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
- node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
- node->gc.gc_next = NULL; /* object is not currently tracked */
+ node->gc.gc_prev->gc.gc_next = node->gc.gc_next;
+ node->gc.gc_next->gc.gc_prev = node->gc.gc_prev;
+ node->gc.gc_next = NULL; /* object is not currently tracked */
}
/* Move `node` from the gc list it's currently in (which is not explicitly
@@ -219,43 +219,43 @@ gc_list_remove(PyGC_Head *node)
static void
gc_list_move(PyGC_Head *node, PyGC_Head *list)
{
- PyGC_Head *new_prev;
- PyGC_Head *current_prev = node->gc.gc_prev;
- PyGC_Head *current_next = node->gc.gc_next;
- /* Unlink from current list. */
- current_prev->gc.gc_next = current_next;
- current_next->gc.gc_prev = current_prev;
- /* Relink at end of new list. */
- new_prev = node->gc.gc_prev = list->gc.gc_prev;
- new_prev->gc.gc_next = list->gc.gc_prev = node;
- node->gc.gc_next = list;
+ PyGC_Head *new_prev;
+ PyGC_Head *current_prev = node->gc.gc_prev;
+ PyGC_Head *current_next = node->gc.gc_next;
+ /* Unlink from current list. */
+ current_prev->gc.gc_next = current_next;
+ current_next->gc.gc_prev = current_prev;
+ /* Relink at end of new list. */
+ new_prev = node->gc.gc_prev = list->gc.gc_prev;
+ new_prev->gc.gc_next = list->gc.gc_prev = node;
+ node->gc.gc_next = list;
}
/* append list `from` onto list `to`; `from` becomes an empty list */
static void
gc_list_merge(PyGC_Head *from, PyGC_Head *to)
{
- PyGC_Head *tail;
- assert(from != to);
- if (!gc_list_is_empty(from)) {
- tail = to->gc.gc_prev;
- tail->gc.gc_next = from->gc.gc_next;
- tail->gc.gc_next->gc.gc_prev = tail;
- to->gc.gc_prev = from->gc.gc_prev;
- to->gc.gc_prev->gc.gc_next = to;
- }
- gc_list_init(from);
+ PyGC_Head *tail;
+ assert(from != to);
+ if (!gc_list_is_empty(from)) {
+ tail = to->gc.gc_prev;
+ tail->gc.gc_next = from->gc.gc_next;
+ tail->gc.gc_next->gc.gc_prev = tail;
+ to->gc.gc_prev = from->gc.gc_prev;
+ to->gc.gc_prev->gc.gc_next = to;
+ }
+ gc_list_init(from);
}
static Py_ssize_t
gc_list_size(PyGC_Head *list)
{
- PyGC_Head *gc;
- Py_ssize_t n = 0;
- for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
- n++;
- }
- return n;
+ PyGC_Head *gc;
+ Py_ssize_t n = 0;
+ for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
+ n++;
+ }
+ return n;
}
/* Append objects in a GC list to a Python list.
@@ -264,16 +264,16 @@ gc_list_size(PyGC_Head *list)
static int
append_objects(PyObject *py_list, PyGC_Head *gc_list)
{
- PyGC_Head *gc;
- for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
- PyObject *op = FROM_GC(gc);
- if (op != py_list) {
- if (PyList_Append(py_list, op)) {
- return -1; /* exception */
- }
- }
- }
- return 0;
+ PyGC_Head *gc;
+ for (gc = gc_list->gc.gc_next; gc != gc_list; gc = gc->gc.gc_next) {
+ PyObject *op = FROM_GC(gc);
+ if (op != py_list) {
+ if (PyList_Append(py_list, op)) {
+ return -1; /* exception */
+ }
+ }
+ }
+ return 0;
}
/*** end of list stuff ***/
@@ -286,48 +286,48 @@ append_objects(PyObject *py_list, PyGC_Head *gc_list)
static void
update_refs(PyGC_Head *containers)
{
- PyGC_Head *gc = containers->gc.gc_next;
- for (; gc != containers; gc = gc->gc.gc_next) {
- assert(gc->gc.gc_refs == GC_REACHABLE);
- gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
- /* Python's cyclic gc should never see an incoming refcount
- * of 0: if something decref'ed to 0, it should have been
- * deallocated immediately at that time.
- * Possible cause (if the assert triggers): a tp_dealloc
- * routine left a gc-aware object tracked during its teardown
- * phase, and did something-- or allowed something to happen --
- * that called back into Python. gc can trigger then, and may
- * see the still-tracked dying object. Before this assert
- * was added, such mistakes went on to allow gc to try to
- * delete the object again. In a debug build, that caused
- * a mysterious segfault, when _Py_ForgetReference tried
- * to remove the object from the doubly-linked list of all
- * objects a second time. In a release build, an actual
- * double deallocation occurred, which leads to corruption
- * of the allocator's internal bookkeeping pointers. That's
- * so serious that maybe this should be a release-build
- * check instead of an assert?
- */
- assert(gc->gc.gc_refs != 0);
- }
+ PyGC_Head *gc = containers->gc.gc_next;
+ for (; gc != containers; gc = gc->gc.gc_next) {
+ assert(gc->gc.gc_refs == GC_REACHABLE);
+ gc->gc.gc_refs = Py_REFCNT(FROM_GC(gc));
+ /* Python's cyclic gc should never see an incoming refcount
+ * of 0: if something decref'ed to 0, it should have been
+ * deallocated immediately at that time.
+ * Possible cause (if the assert triggers): a tp_dealloc
+ * routine left a gc-aware object tracked during its teardown
+ * phase, and did something-- or allowed something to happen --
+ * that called back into Python. gc can trigger then, and may
+ * see the still-tracked dying object. Before this assert
+ * was added, such mistakes went on to allow gc to try to
+ * delete the object again. In a debug build, that caused
+ * a mysterious segfault, when _Py_ForgetReference tried
+ * to remove the object from the doubly-linked list of all
+ * objects a second time. In a release build, an actual
+ * double deallocation occurred, which leads to corruption
+ * of the allocator's internal bookkeeping pointers. That's
+ * so serious that maybe this should be a release-build
+ * check instead of an assert?
+ */
+ assert(gc->gc.gc_refs != 0);
+ }
}
/* A traversal callback for subtract_refs. */
static int
visit_decref(PyObject *op, void *data)
{
- assert(op != NULL);
- if (PyObject_IS_GC(op)) {
- PyGC_Head *gc = AS_GC(op);
- /* We're only interested in gc_refs for objects in the
- * generation being collected, which can be recognized
- * because only they have positive gc_refs.
- */
- assert(gc->gc.gc_refs != 0); /* else refcount was too small */
- if (gc->gc.gc_refs > 0)
- gc->gc.gc_refs--;
- }
- return 0;
+ assert(op != NULL);
+ if (PyObject_IS_GC(op)) {
+ PyGC_Head *gc = AS_GC(op);
+ /* We're only interested in gc_refs for objects in the
+ * generation being collected, which can be recognized
+ * because only they have positive gc_refs.
+ */
+ assert(gc->gc.gc_refs != 0); /* else refcount was too small */
+ if (gc->gc.gc_refs > 0)
+ gc->gc.gc_refs--;
+ }
+ return 0;
}
/* Subtract internal references from gc_refs. After this, gc_refs is >= 0
@@ -338,57 +338,57 @@ visit_decref(PyObject *op, void *data)
static void
subtract_refs(PyGC_Head *containers)
{
- traverseproc traverse;
- PyGC_Head *gc = containers->gc.gc_next;
- for (; gc != containers; gc=gc->gc.gc_next) {
- traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
- (void) traverse(FROM_GC(gc),
- (visitproc)visit_decref,
- NULL);
- }
+ traverseproc traverse;
+ PyGC_Head *gc = containers->gc.gc_next;
+ for (; gc != containers; gc=gc->gc.gc_next) {
+ traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
+ (void) traverse(FROM_GC(gc),
+ (visitproc)visit_decref,
+ NULL);
+ }
}
/* A traversal callback for move_unreachable. */
static int
visit_reachable(PyObject *op, PyGC_Head *reachable)
{
- if (PyObject_IS_GC(op)) {
- PyGC_Head *gc = AS_GC(op);
- const Py_ssize_t gc_refs = gc->gc.gc_refs;
-
- if (gc_refs == 0) {
- /* This is in move_unreachable's 'young' list, but
- * the traversal hasn't yet gotten to it. All
- * we need to do is tell move_unreachable that it's
- * reachable.
- */
- gc->gc.gc_refs = 1;
- }
- else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
- /* This had gc_refs = 0 when move_unreachable got
- * to it, but turns out it's reachable after all.
- * Move it back to move_unreachable's 'young' list,
- * and move_unreachable will eventually get to it
- * again.
- */
- gc_list_move(gc, reachable);
- gc->gc.gc_refs = 1;
- }
- /* Else there's nothing to do.
- * If gc_refs > 0, it must be in move_unreachable's 'young'
- * list, and move_unreachable will eventually get to it.
- * If gc_refs == GC_REACHABLE, it's either in some other
- * generation so we don't care about it, or move_unreachable
- * already dealt with it.
- * If gc_refs == GC_UNTRACKED, it must be ignored.
- */
- else {
- assert(gc_refs > 0
- || gc_refs == GC_REACHABLE
- || gc_refs == GC_UNTRACKED);
- }
- }
- return 0;
+ if (PyObject_IS_GC(op)) {
+ PyGC_Head *gc = AS_GC(op);
+ const Py_ssize_t gc_refs = gc->gc.gc_refs;
+
+ if (gc_refs == 0) {
+ /* This is in move_unreachable's 'young' list, but
+ * the traversal hasn't yet gotten to it. All
+ * we need to do is tell move_unreachable that it's
+ * reachable.
+ */
+ gc->gc.gc_refs = 1;
+ }
+ else if (gc_refs == GC_TENTATIVELY_UNREACHABLE) {
+ /* This had gc_refs = 0 when move_unreachable got
+ * to it, but turns out it's reachable after all.
+ * Move it back to move_unreachable's 'young' list,
+ * and move_unreachable will eventually get to it
+ * again.
+ */
+ gc_list_move(gc, reachable);
+ gc->gc.gc_refs = 1;
+ }
+ /* Else there's nothing to do.
+ * If gc_refs > 0, it must be in move_unreachable's 'young'
+ * list, and move_unreachable will eventually get to it.
+ * If gc_refs == GC_REACHABLE, it's either in some other
+ * generation so we don't care about it, or move_unreachable
+ * already dealt with it.
+ * If gc_refs == GC_UNTRACKED, it must be ignored.
+ */
+ else {
+ assert(gc_refs > 0
+ || gc_refs == GC_REACHABLE
+ || gc_refs == GC_UNTRACKED);
+ }
+ }
+ return 0;
}
/* Move the unreachable objects from young to unreachable. After this,
@@ -402,58 +402,58 @@ visit_reachable(PyObject *op, PyGC_Head *reachable)
static void
move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
{
- PyGC_Head *gc = young->gc.gc_next;
-
- /* Invariants: all objects "to the left" of us in young have gc_refs
- * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
- * from outside the young list as it was at entry. All other objects
- * from the original young "to the left" of us are in unreachable now,
- * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
- * left of us in 'young' now have been scanned, and no objects here
- * or to the right have been scanned yet.
- */
-
- while (gc != young) {
- PyGC_Head *next;
-
- if (gc->gc.gc_refs) {
- /* gc is definitely reachable from outside the
- * original 'young'. Mark it as such, and traverse
- * its pointers to find any other objects that may
- * be directly reachable from it. Note that the
- * call to tp_traverse may append objects to young,
- * so we have to wait until it returns to determine
- * the next object to visit.
- */
- PyObject *op = FROM_GC(gc);
- traverseproc traverse = Py_TYPE(op)->tp_traverse;
- assert(gc->gc.gc_refs > 0);
- gc->gc.gc_refs = GC_REACHABLE;
- (void) traverse(op,
- (visitproc)visit_reachable,
- (void *)young);
- next = gc->gc.gc_next;
- if (PyTuple_CheckExact(op)) {
- _PyTuple_MaybeUntrack(op);
- }
- else if (PyDict_CheckExact(op)) {
- _PyDict_MaybeUntrack(op);
- }
- }
- else {
- /* This *may* be unreachable. To make progress,
- * assume it is. gc isn't directly reachable from
- * any object we've already traversed, but may be
- * reachable from an object we haven't gotten to yet.
- * visit_reachable will eventually move gc back into
- * young if that's so, and we'll see it again.
- */
- next = gc->gc.gc_next;
- gc_list_move(gc, unreachable);
- gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
- }
- gc = next;
- }
+ PyGC_Head *gc = young->gc.gc_next;
+
+ /* Invariants: all objects "to the left" of us in young have gc_refs
+ * = GC_REACHABLE, and are indeed reachable (directly or indirectly)
+ * from outside the young list as it was at entry. All other objects
+ * from the original young "to the left" of us are in unreachable now,
+ * and have gc_refs = GC_TENTATIVELY_UNREACHABLE. All objects to the
+ * left of us in 'young' now have been scanned, and no objects here
+ * or to the right have been scanned yet.
+ */
+
+ while (gc != young) {
+ PyGC_Head *next;
+
+ if (gc->gc.gc_refs) {
+ /* gc is definitely reachable from outside the
+ * original 'young'. Mark it as such, and traverse
+ * its pointers to find any other objects that may
+ * be directly reachable from it. Note that the
+ * call to tp_traverse may append objects to young,
+ * so we have to wait until it returns to determine
+ * the next object to visit.
+ */
+ PyObject *op = FROM_GC(gc);
+ traverseproc traverse = Py_TYPE(op)->tp_traverse;
+ assert(gc->gc.gc_refs > 0);
+ gc->gc.gc_refs = GC_REACHABLE;
+ (void) traverse(op,
+ (visitproc)visit_reachable,
+ (void *)young);
+ next = gc->gc.gc_next;
+ if (PyTuple_CheckExact(op)) {
+ _PyTuple_MaybeUntrack(op);
+ }
+ else if (PyDict_CheckExact(op)) {
+ _PyDict_MaybeUntrack(op);
+ }
+ }
+ else {
+ /* This *may* be unreachable. To make progress,
+ * assume it is. gc isn't directly reachable from
+ * any object we've already traversed, but may be
+ * reachable from an object we haven't gotten to yet.
+ * visit_reachable will eventually move gc back into
+ * young if that's so, and we'll see it again.
+ */
+ next = gc->gc.gc_next;
+ gc_list_move(gc, unreachable);
+ gc->gc.gc_refs = GC_TENTATIVELY_UNREACHABLE;
+ }
+ gc = next;
+ }
}
/* Return true if object has a finalization method.
@@ -466,16 +466,16 @@ move_unreachable(PyGC_Head *young, PyGC_Head *unreachable)
static int
has_finalizer(PyObject *op)
{
- if (PyInstance_Check(op)) {
- assert(delstr != NULL);
- return _PyInstance_Lookup(op, delstr) != NULL;
- }
- else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
- return op->ob_type->tp_del != NULL;
- else if (PyGen_CheckExact(op))
- return PyGen_NeedsFinalizing((PyGenObject *)op);
- else
- return 0;
+ if (PyInstance_Check(op)) {
+ assert(delstr != NULL);
+ return _PyInstance_Lookup(op, delstr) != NULL;
+ }
+ else if (PyType_HasFeature(op->ob_type, Py_TPFLAGS_HEAPTYPE))
+ return op->ob_type->tp_del != NULL;
+ else if (PyGen_CheckExact(op))
+ return PyGen_NeedsFinalizing((PyGenObject *)op);
+ else
+ return 0;
}
/* Move the objects in unreachable with __del__ methods into `finalizers`.
@@ -485,37 +485,37 @@ has_finalizer(PyObject *op)
static void
move_finalizers(PyGC_Head *unreachable, PyGC_Head *finalizers)
{
- PyGC_Head *gc;
- PyGC_Head *next;
-
- /* March over unreachable. Move objects with finalizers into
- * `finalizers`.
- */
- for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
- PyObject *op = FROM_GC(gc);
-
- assert(IS_TENTATIVELY_UNREACHABLE(op));
- next = gc->gc.gc_next;
-
- if (has_finalizer(op)) {
- gc_list_move(gc, finalizers);
- gc->gc.gc_refs = GC_REACHABLE;
- }
- }
+ PyGC_Head *gc;
+ PyGC_Head *next;
+
+ /* March over unreachable. Move objects with finalizers into
+ * `finalizers`.
+ */
+ for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
+ PyObject *op = FROM_GC(gc);
+
+ assert(IS_TENTATIVELY_UNREACHABLE(op));
+ next = gc->gc.gc_next;
+
+ if (has_finalizer(op)) {
+ gc_list_move(gc, finalizers);
+ gc->gc.gc_refs = GC_REACHABLE;
+ }
+ }
}
/* A traversal callback for move_finalizer_reachable. */
static int
visit_move(PyObject *op, PyGC_Head *tolist)
{
- if (PyObject_IS_GC(op)) {
- if (IS_TENTATIVELY_UNREACHABLE(op)) {
- PyGC_Head *gc = AS_GC(op);
- gc_list_move(gc, tolist);
- gc->gc.gc_refs = GC_REACHABLE;
- }
- }
- return 0;
+ if (PyObject_IS_GC(op)) {
+ if (IS_TENTATIVELY_UNREACHABLE(op)) {
+ PyGC_Head *gc = AS_GC(op);
+ gc_list_move(gc, tolist);
+ gc->gc.gc_refs = GC_REACHABLE;
+ }
+ }
+ return 0;
}
/* Move objects that are reachable from finalizers, from the unreachable set
@@ -524,15 +524,15 @@ visit_move(PyObject *op, PyGC_Head *tolist)
static void
move_finalizer_reachable(PyGC_Head *finalizers)
{
- traverseproc traverse;
- PyGC_Head *gc = finalizers->gc.gc_next;
- for (; gc != finalizers; gc = gc->gc.gc_next) {
- /* Note that the finalizers list may grow during this. */
- traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
- (void) traverse(FROM_GC(gc),
- (visitproc)visit_move,
- (void *)finalizers);
- }
+ traverseproc traverse;
+ PyGC_Head *gc = finalizers->gc.gc_next;
+ for (; gc != finalizers; gc = gc->gc.gc_next) {
+ /* Note that the finalizers list may grow during this. */
+ traverse = Py_TYPE(FROM_GC(gc))->tp_traverse;
+ (void) traverse(FROM_GC(gc),
+ (visitproc)visit_move,
+ (void *)finalizers);
+ }
}
/* Clear all weakrefs to unreachable objects, and if such a weakref has a
@@ -549,169 +549,169 @@ move_finalizer_reachable(PyGC_Head *finalizers)
static int
handle_weakrefs(PyGC_Head *unreachable, PyGC_Head *old)
{
- PyGC_Head *gc;
- PyObject *op; /* generally FROM_GC(gc) */
- PyWeakReference *wr; /* generally a cast of op */
- PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
- PyGC_Head *next;
- int num_freed = 0;
-
- gc_list_init(&wrcb_to_call);
-
- /* Clear all weakrefs to the objects in unreachable. If such a weakref
- * also has a callback, move it into `wrcb_to_call` if the callback
- * needs to be invoked. Note that we cannot invoke any callbacks until
- * all weakrefs to unreachable objects are cleared, lest the callback
- * resurrect an unreachable object via a still-active weakref. We
- * make another pass over wrcb_to_call, invoking callbacks, after this
- * pass completes.
- */
- for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
- PyWeakReference **wrlist;
-
- op = FROM_GC(gc);
- assert(IS_TENTATIVELY_UNREACHABLE(op));
- next = gc->gc.gc_next;
-
- if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
- continue;
-
- /* It supports weakrefs. Does it have any? */
- wrlist = (PyWeakReference **)
- PyObject_GET_WEAKREFS_LISTPTR(op);
-
- /* `op` may have some weakrefs. March over the list, clear
- * all the weakrefs, and move the weakrefs with callbacks
- * that must be called into wrcb_to_call.
- */
- for (wr = *wrlist; wr != NULL; wr = *wrlist) {
- PyGC_Head *wrasgc; /* AS_GC(wr) */
-
- /* _PyWeakref_ClearRef clears the weakref but leaves
- * the callback pointer intact. Obscure: it also
- * changes *wrlist.
- */
- assert(wr->wr_object == op);
- _PyWeakref_ClearRef(wr);
- assert(wr->wr_object == Py_None);
- if (wr->wr_callback == NULL)
- continue; /* no callback */
-
- /* Headache time. `op` is going away, and is weakly referenced by
- * `wr`, which has a callback. Should the callback be invoked? If wr
- * is also trash, no:
- *
- * 1. There's no need to call it. The object and the weakref are
- * both going away, so it's legitimate to pretend the weakref is
- * going away first. The user has to ensure a weakref outlives its
- * referent if they want a guarantee that the wr callback will get
- * invoked.
- *
- * 2. It may be catastrophic to call it. If the callback is also in
- * cyclic trash (CT), then although the CT is unreachable from
- * outside the current generation, CT may be reachable from the
- * callback. Then the callback could resurrect insane objects.
- *
- * Since the callback is never needed and may be unsafe in this case,
- * wr is simply left in the unreachable set. Note that because we
- * already called _PyWeakref_ClearRef(wr), its callback will never
- * trigger.
- *
- * OTOH, if wr isn't part of CT, we should invoke the callback: the
- * weakref outlived the trash. Note that since wr isn't CT in this
- * case, its callback can't be CT either -- wr acted as an external
- * root to this generation, and therefore its callback did too. So
- * nothing in CT is reachable from the callback either, so it's hard
- * to imagine how calling it later could create a problem for us. wr
- * is moved to wrcb_to_call in this case.
- */
- if (IS_TENTATIVELY_UNREACHABLE(wr))
- continue;
- assert(IS_REACHABLE(wr));
-
- /* Create a new reference so that wr can't go away
- * before we can process it again.
- */
- Py_INCREF(wr);
-
- /* Move wr to wrcb_to_call, for the next pass. */
- wrasgc = AS_GC(wr);
- assert(wrasgc != next); /* wrasgc is reachable, but
- next isn't, so they can't
- be the same */
- gc_list_move(wrasgc, &wrcb_to_call);
- }
- }
-
- /* Invoke the callbacks we decided to honor. It's safe to invoke them
- * because they can't reference unreachable objects.
- */
- while (! gc_list_is_empty(&wrcb_to_call)) {
- PyObject *temp;
- PyObject *callback;
-
- gc = wrcb_to_call.gc.gc_next;
- op = FROM_GC(gc);
- assert(IS_REACHABLE(op));
- assert(PyWeakref_Check(op));
- wr = (PyWeakReference *)op;
- callback = wr->wr_callback;
- assert(callback != NULL);
-
- /* copy-paste of weakrefobject.c's handle_callback() */
- temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
- if (temp == NULL)
- PyErr_WriteUnraisable(callback);
- else
- Py_DECREF(temp);
-
- /* Give up the reference we created in the first pass. When
- * op's refcount hits 0 (which it may or may not do right now),
- * op's tp_dealloc will decref op->wr_callback too. Note
- * that the refcount probably will hit 0 now, and because this
- * weakref was reachable to begin with, gc didn't already
- * add it to its count of freed objects. Example: a reachable
- * weak value dict maps some key to this reachable weakref.
- * The callback removes this key->weakref mapping from the
- * dict, leaving no other references to the weakref (excepting
- * ours).
- */
- Py_DECREF(op);
- if (wrcb_to_call.gc.gc_next == gc) {
- /* object is still alive -- move it */
- gc_list_move(gc, old);
- }
- else
- ++num_freed;
- }
-
- return num_freed;
+ PyGC_Head *gc;
+ PyObject *op; /* generally FROM_GC(gc) */
+ PyWeakReference *wr; /* generally a cast of op */
+ PyGC_Head wrcb_to_call; /* weakrefs with callbacks to call */
+ PyGC_Head *next;
+ int num_freed = 0;
+
+ gc_list_init(&wrcb_to_call);
+
+ /* Clear all weakrefs to the objects in unreachable. If such a weakref
+ * also has a callback, move it into `wrcb_to_call` if the callback
+ * needs to be invoked. Note that we cannot invoke any callbacks until
+ * all weakrefs to unreachable objects are cleared, lest the callback
+ * resurrect an unreachable object via a still-active weakref. We
+ * make another pass over wrcb_to_call, invoking callbacks, after this
+ * pass completes.
+ */
+ for (gc = unreachable->gc.gc_next; gc != unreachable; gc = next) {
+ PyWeakReference **wrlist;
+
+ op = FROM_GC(gc);
+ assert(IS_TENTATIVELY_UNREACHABLE(op));
+ next = gc->gc.gc_next;
+
+ if (! PyType_SUPPORTS_WEAKREFS(Py_TYPE(op)))
+ continue;
+
+ /* It supports weakrefs. Does it have any? */
+ wrlist = (PyWeakReference **)
+ PyObject_GET_WEAKREFS_LISTPTR(op);
+
+ /* `op` may have some weakrefs. March over the list, clear
+ * all the weakrefs, and move the weakrefs with callbacks
+ * that must be called into wrcb_to_call.
+ */
+ for (wr = *wrlist; wr != NULL; wr = *wrlist) {
+ PyGC_Head *wrasgc; /* AS_GC(wr) */
+
+ /* _PyWeakref_ClearRef clears the weakref but leaves
+ * the callback pointer intact. Obscure: it also
+ * changes *wrlist.
+ */
+ assert(wr->wr_object == op);
+ _PyWeakref_ClearRef(wr);
+ assert(wr->wr_object == Py_None);
+ if (wr->wr_callback == NULL)
+ continue; /* no callback */
+
+ /* Headache time. `op` is going away, and is weakly referenced by
+ * `wr`, which has a callback. Should the callback be invoked? If wr
+ * is also trash, no:
+ *
+ * 1. There's no need to call it. The object and the weakref are
+ * both going away, so it's legitimate to pretend the weakref is
+ * going away first. The user has to ensure a weakref outlives its
+ * referent if they want a guarantee that the wr callback will get
+ * invoked.
+ *
+ * 2. It may be catastrophic to call it. If the callback is also in
+ * cyclic trash (CT), then although the CT is unreachable from
+ * outside the current generation, CT may be reachable from the
+ * callback. Then the callback could resurrect insane objects.
+ *
+ * Since the callback is never needed and may be unsafe in this case,
+ * wr is simply left in the unreachable set. Note that because we
+ * already called _PyWeakref_ClearRef(wr), its callback will never
+ * trigger.
+ *
+ * OTOH, if wr isn't part of CT, we should invoke the callback: the
+ * weakref outlived the trash. Note that since wr isn't CT in this
+ * case, its callback can't be CT either -- wr acted as an external
+ * root to this generation, and therefore its callback did too. So
+ * nothing in CT is reachable from the callback either, so it's hard
+ * to imagine how calling it later could create a problem for us. wr
+ * is moved to wrcb_to_call in this case.
+ */
+ if (IS_TENTATIVELY_UNREACHABLE(wr))
+ continue;
+ assert(IS_REACHABLE(wr));
+
+ /* Create a new reference so that wr can't go away
+ * before we can process it again.
+ */
+ Py_INCREF(wr);
+
+ /* Move wr to wrcb_to_call, for the next pass. */
+ wrasgc = AS_GC(wr);
+ assert(wrasgc != next); /* wrasgc is reachable, but
+ next isn't, so they can't
+ be the same */
+ gc_list_move(wrasgc, &wrcb_to_call);
+ }
+ }
+
+ /* Invoke the callbacks we decided to honor. It's safe to invoke them
+ * because they can't reference unreachable objects.
+ */
+ while (! gc_list_is_empty(&wrcb_to_call)) {
+ PyObject *temp;
+ PyObject *callback;
+
+ gc = wrcb_to_call.gc.gc_next;
+ op = FROM_GC(gc);
+ assert(IS_REACHABLE(op));
+ assert(PyWeakref_Check(op));
+ wr = (PyWeakReference *)op;
+ callback = wr->wr_callback;
+ assert(callback != NULL);
+
+ /* copy-paste of weakrefobject.c's handle_callback() */
+ temp = PyObject_CallFunctionObjArgs(callback, wr, NULL);
+ if (temp == NULL)
+ PyErr_WriteUnraisable(callback);
+ else
+ Py_DECREF(temp);
+
+ /* Give up the reference we created in the first pass. When
+ * op's refcount hits 0 (which it may or may not do right now),
+ * op's tp_dealloc will decref op->wr_callback too. Note
+ * that the refcount probably will hit 0 now, and because this
+ * weakref was reachable to begin with, gc didn't already
+ * add it to its count of freed objects. Example: a reachable
+ * weak value dict maps some key to this reachable weakref.
+ * The callback removes this key->weakref mapping from the
+ * dict, leaving no other references to the weakref (excepting
+ * ours).
+ */
+ Py_DECREF(op);
+ if (wrcb_to_call.gc.gc_next == gc) {
+ /* object is still alive -- move it */
+ gc_list_move(gc, old);
+ }
+ else
+ ++num_freed;
+ }
+
+ return num_freed;
}
static void
debug_instance(char *msg, PyInstanceObject *inst)
{
- char *cname;
- /* simple version of instance_repr */
- PyObject *classname = inst->in_class->cl_name;
- if (classname != NULL && PyString_Check(classname))
- cname = PyString_AsString(classname);
- else
- cname = "?";
- PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
- msg, cname, inst);
+ char *cname;
+ /* simple version of instance_repr */
+ PyObject *classname = inst->in_class->cl_name;
+ if (classname != NULL && PyString_Check(classname))
+ cname = PyString_AsString(classname);
+ else
+ cname = "?";
+ PySys_WriteStderr("gc: %.100s <%.100s instance at %p>\n",
+ msg, cname, inst);
}
static void
debug_cycle(char *msg, PyObject *op)
{
- if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
- debug_instance(msg, (PyInstanceObject *)op);
- }
- else if (debug & DEBUG_OBJECTS) {
- PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
- msg, Py_TYPE(op)->tp_name, op);
- }
+ if ((debug & DEBUG_INSTANCES) && PyInstance_Check(op)) {
+ debug_instance(msg, (PyInstanceObject *)op);
+ }
+ else if (debug & DEBUG_OBJECTS) {
+ PySys_WriteStderr("gc: %.100s <%.100s %p>\n",
+ msg, Py_TYPE(op)->tp_name, op);
+ }
}
/* Handle uncollectable garbage (cycles with finalizers, and stuff reachable
@@ -726,56 +726,56 @@ debug_cycle(char *msg, PyObject *op)
static int
handle_finalizers(PyGC_Head *finalizers, PyGC_Head *old)
{
- PyGC_Head *gc = finalizers->gc.gc_next;
-
- if (garbage == NULL) {
- garbage = PyList_New(0);
- if (garbage == NULL)
- Py_FatalError("gc couldn't create gc.garbage list");
- }
- for (; gc != finalizers; gc = gc->gc.gc_next) {
- PyObject *op = FROM_GC(gc);
-
- if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {
- if (PyList_Append(garbage, op) < 0)
- return -1;
- }
- }
-
- gc_list_merge(finalizers, old);
- return 0;
+ PyGC_Head *gc = finalizers->gc.gc_next;
+
+ if (garbage == NULL) {
+ garbage = PyList_New(0);
+ if (garbage == NULL)
+ Py_FatalError("gc couldn't create gc.garbage list");
+ }
+ for (; gc != finalizers; gc = gc->gc.gc_next) {
+ PyObject *op = FROM_GC(gc);
+
+ if ((debug & DEBUG_SAVEALL) || has_finalizer(op)) {
+ if (PyList_Append(garbage, op) < 0)
+ return -1;
+ }
+ }
+
+ gc_list_merge(finalizers, old);
+ return 0;
}
-/* Break reference cycles by clearing the containers involved. This is
+/* Break reference cycles by clearing the containers involved. This is
* tricky business as the lists can be changing and we don't know which
* objects may be freed. It is possible I screwed something up here.
*/
static void
delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
{
- inquiry clear;
-
- while (!gc_list_is_empty(collectable)) {
- PyGC_Head *gc = collectable->gc.gc_next;
- PyObject *op = FROM_GC(gc);
-
- assert(IS_TENTATIVELY_UNREACHABLE(op));
- if (debug & DEBUG_SAVEALL) {
- PyList_Append(garbage, op);
- }
- else {
- if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
- Py_INCREF(op);
- clear(op);
- Py_DECREF(op);
- }
- }
- if (collectable->gc.gc_next == gc) {
- /* object is still alive, move it, it may die later */
- gc_list_move(gc, old);
- gc->gc.gc_refs = GC_REACHABLE;
- }
- }
+ inquiry clear;
+
+ while (!gc_list_is_empty(collectable)) {
+ PyGC_Head *gc = collectable->gc.gc_next;
+ PyObject *op = FROM_GC(gc);
+
+ assert(IS_TENTATIVELY_UNREACHABLE(op));
+ if (debug & DEBUG_SAVEALL) {
+ PyList_Append(garbage, op);
+ }
+ else {
+ if ((clear = Py_TYPE(op)->tp_clear) != NULL) {
+ Py_INCREF(op);
+ clear(op);
+ Py_DECREF(op);
+ }
+ }
+ if (collectable->gc.gc_next == gc) {
+ /* object is still alive, move it, it may die later */
+ gc_list_move(gc, old);
+ gc->gc.gc_refs = GC_REACHABLE;
+ }
+ }
}
/* Clear all free lists
@@ -786,33 +786,33 @@ delete_garbage(PyGC_Head *collectable, PyGC_Head *old)
static void
clear_freelists(void)
{
- (void)PyMethod_ClearFreeList();
- (void)PyFrame_ClearFreeList();
- (void)PyCFunction_ClearFreeList();
- (void)PyTuple_ClearFreeList();
+ (void)PyMethod_ClearFreeList();
+ (void)PyFrame_ClearFreeList();
+ (void)PyCFunction_ClearFreeList();
+ (void)PyTuple_ClearFreeList();
#ifdef Py_USING_UNICODE
- (void)PyUnicode_ClearFreeList();
+ (void)PyUnicode_ClearFreeList();
#endif
- (void)PyInt_ClearFreeList();
- (void)PyFloat_ClearFreeList();
+ (void)PyInt_ClearFreeList();
+ (void)PyFloat_ClearFreeList();
}
static double
get_time(void)
{
- double result = 0;
- if (tmod != NULL) {
- PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
- if (f == NULL) {
- PyErr_Clear();
- }
- else {
- if (PyFloat_Check(f))
- result = PyFloat_AsDouble(f);
- Py_DECREF(f);
- }
- }
- return result;
+ double result = 0;
+ if (tmod != NULL) {
+ PyObject *f = PyObject_CallMethod(tmod, "time", NULL);
+ if (f == NULL) {
+ PyErr_Clear();
+ }
+ else {
+ if (PyFloat_Check(f))
+ result = PyFloat_AsDouble(f);
+ Py_DECREF(f);
+ }
+ }
+ return result;
}
/* This is the main function. Read this to understand how the
@@ -820,184 +820,184 @@ get_time(void)
static Py_ssize_t
collect(int generation)
{
- int i;
- Py_ssize_t m = 0; /* # objects collected */
- Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
- PyGC_Head *young; /* the generation we are examining */
- PyGC_Head *old; /* next older generation */
- PyGC_Head unreachable; /* non-problematic unreachable trash */
- PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
- PyGC_Head *gc;
- double t1 = 0.0;
-
- if (delstr == NULL) {
- delstr = PyString_InternFromString("__del__");
- if (delstr == NULL)
- Py_FatalError("gc couldn't allocate \"__del__\"");
- }
-
- if (debug & DEBUG_STATS) {
- PySys_WriteStderr("gc: collecting generation %d...\n",
- generation);
- PySys_WriteStderr("gc: objects in each generation:");
- for (i = 0; i < NUM_GENERATIONS; i++)
- PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
- gc_list_size(GEN_HEAD(i)));
- t1 = get_time();
- PySys_WriteStderr("\n");
- }
-
- /* update collection and allocation counters */
- if (generation+1 < NUM_GENERATIONS)
- generations[generation+1].count += 1;
- for (i = 0; i <= generation; i++)
- generations[i].count = 0;
-
- /* merge younger generations with one we are currently collecting */
- for (i = 0; i < generation; i++) {
- gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
- }
-
- /* handy references */
- young = GEN_HEAD(generation);
- if (generation < NUM_GENERATIONS-1)
- old = GEN_HEAD(generation+1);
- else
- old = young;
-
- /* Using ob_refcnt and gc_refs, calculate which objects in the
- * container set are reachable from outside the set (i.e., have a
- * refcount greater than 0 when all the references within the
- * set are taken into account).
- */
- update_refs(young);
- subtract_refs(young);
-
- /* Leave everything reachable from outside young in young, and move
- * everything else (in young) to unreachable.
- * NOTE: This used to move the reachable objects into a reachable
- * set instead. But most things usually turn out to be reachable,
- * so it's more efficient to move the unreachable things.
- */
- gc_list_init(&unreachable);
- move_unreachable(young, &unreachable);
-
- /* Move reachable objects to next generation. */
- if (young != old) {
- if (generation == NUM_GENERATIONS - 2) {
- long_lived_pending += gc_list_size(young);
- }
- gc_list_merge(young, old);
- }
- else {
- long_lived_pending = 0;
- long_lived_total = gc_list_size(young);
- }
-
- /* All objects in unreachable are trash, but objects reachable from
- * finalizers can't safely be deleted. Python programmers should take
- * care not to create such things. For Python, finalizers means
- * instance objects with __del__ methods. Weakrefs with callbacks
- * can also call arbitrary Python code but they will be dealt with by
- * handle_weakrefs().
- */
- gc_list_init(&finalizers);
- move_finalizers(&unreachable, &finalizers);
- /* finalizers contains the unreachable objects with a finalizer;
- * unreachable objects reachable *from* those are also uncollectable,
- * and we move those into the finalizers list too.
- */
- move_finalizer_reachable(&finalizers);
-
- /* Collect statistics on collectable objects found and print
- * debugging information.
- */
- for (gc = unreachable.gc.gc_next; gc != &unreachable;
- gc = gc->gc.gc_next) {
- m++;
- if (debug & DEBUG_COLLECTABLE) {
- debug_cycle("collectable", FROM_GC(gc));
- }
- }
-
- /* Clear weakrefs and invoke callbacks as necessary. */
- m += handle_weakrefs(&unreachable, old);
-
- /* Call tp_clear on objects in the unreachable set. This will cause
- * the reference cycles to be broken. It may also cause some objects
- * in finalizers to be freed.
- */
- delete_garbage(&unreachable, old);
-
- /* Collect statistics on uncollectable objects found and print
- * debugging information. */
- for (gc = finalizers.gc.gc_next;
- gc != &finalizers;
- gc = gc->gc.gc_next) {
- n++;
- if (debug & DEBUG_UNCOLLECTABLE)
- debug_cycle("uncollectable", FROM_GC(gc));
- }
- if (debug & DEBUG_STATS) {
- double t2 = get_time();
- if (m == 0 && n == 0)
- PySys_WriteStderr("gc: done");
- else
- PySys_WriteStderr(
- "gc: done, "
- "%" PY_FORMAT_SIZE_T "d unreachable, "
- "%" PY_FORMAT_SIZE_T "d uncollectable",
- n+m, n);
- if (t1 && t2) {
- PySys_WriteStderr(", %.4fs elapsed", t2-t1);
- }
- PySys_WriteStderr(".\n");
- }
-
- /* Append instances in the uncollectable set to a Python
- * reachable list of garbage. The programmer has to deal with
- * this if they insist on creating this type of structure.
- */
- (void)handle_finalizers(&finalizers, old);
-
- /* Clear free list only during the collection of the highest
- * generation */
- if (generation == NUM_GENERATIONS-1) {
- clear_freelists();
- }
-
- if (PyErr_Occurred()) {
- if (gc_str == NULL)
- gc_str = PyString_FromString("garbage collection");
- PyErr_WriteUnraisable(gc_str);
- Py_FatalError("unexpected exception during garbage collection");
- }
- return n+m;
+ int i;
+ Py_ssize_t m = 0; /* # objects collected */
+ Py_ssize_t n = 0; /* # unreachable objects that couldn't be collected */
+ PyGC_Head *young; /* the generation we are examining */
+ PyGC_Head *old; /* next older generation */
+ PyGC_Head unreachable; /* non-problematic unreachable trash */
+ PyGC_Head finalizers; /* objects with, & reachable from, __del__ */
+ PyGC_Head *gc;
+ double t1 = 0.0;
+
+ if (delstr == NULL) {
+ delstr = PyString_InternFromString("__del__");
+ if (delstr == NULL)
+ Py_FatalError("gc couldn't allocate \"__del__\"");
+ }
+
+ if (debug & DEBUG_STATS) {
+ PySys_WriteStderr("gc: collecting generation %d...\n",
+ generation);
+ PySys_WriteStderr("gc: objects in each generation:");
+ for (i = 0; i < NUM_GENERATIONS; i++)
+ PySys_WriteStderr(" %" PY_FORMAT_SIZE_T "d",
+ gc_list_size(GEN_HEAD(i)));
+ t1 = get_time();
+ PySys_WriteStderr("\n");
+ }
+
+ /* update collection and allocation counters */
+ if (generation+1 < NUM_GENERATIONS)
+ generations[generation+1].count += 1;
+ for (i = 0; i <= generation; i++)
+ generations[i].count = 0;
+
+ /* merge younger generations with one we are currently collecting */
+ for (i = 0; i < generation; i++) {
+ gc_list_merge(GEN_HEAD(i), GEN_HEAD(generation));
+ }
+
+ /* handy references */
+ young = GEN_HEAD(generation);
+ if (generation < NUM_GENERATIONS-1)
+ old = GEN_HEAD(generation+1);
+ else
+ old = young;
+
+ /* Using ob_refcnt and gc_refs, calculate which objects in the
+ * container set are reachable from outside the set (i.e., have a
+ * refcount greater than 0 when all the references within the
+ * set are taken into account).
+ */
+ update_refs(young);
+ subtract_refs(young);
+
+ /* Leave everything reachable from outside young in young, and move
+ * everything else (in young) to unreachable.
+ * NOTE: This used to move the reachable objects into a reachable
+ * set instead. But most things usually turn out to be reachable,
+ * so it's more efficient to move the unreachable things.
+ */
+ gc_list_init(&unreachable);
+ move_unreachable(young, &unreachable);
+
+ /* Move reachable objects to next generation. */
+ if (young != old) {
+ if (generation == NUM_GENERATIONS - 2) {
+ long_lived_pending += gc_list_size(young);
+ }
+ gc_list_merge(young, old);
+ }
+ else {
+ long_lived_pending = 0;
+ long_lived_total = gc_list_size(young);
+ }
+
+ /* All objects in unreachable are trash, but objects reachable from
+ * finalizers can't safely be deleted. Python programmers should take
+ * care not to create such things. For Python, finalizers means
+ * instance objects with __del__ methods. Weakrefs with callbacks
+ * can also call arbitrary Python code but they will be dealt with by
+ * handle_weakrefs().
+ */
+ gc_list_init(&finalizers);
+ move_finalizers(&unreachable, &finalizers);
+ /* finalizers contains the unreachable objects with a finalizer;
+ * unreachable objects reachable *from* those are also uncollectable,
+ * and we move those into the finalizers list too.
+ */
+ move_finalizer_reachable(&finalizers);
+
+ /* Collect statistics on collectable objects found and print
+ * debugging information.
+ */
+ for (gc = unreachable.gc.gc_next; gc != &unreachable;
+ gc = gc->gc.gc_next) {
+ m++;
+ if (debug & DEBUG_COLLECTABLE) {
+ debug_cycle("collectable", FROM_GC(gc));
+ }
+ }
+
+ /* Clear weakrefs and invoke callbacks as necessary. */
+ m += handle_weakrefs(&unreachable, old);
+
+ /* Call tp_clear on objects in the unreachable set. This will cause
+ * the reference cycles to be broken. It may also cause some objects
+ * in finalizers to be freed.
+ */
+ delete_garbage(&unreachable, old);
+
+ /* Collect statistics on uncollectable objects found and print
+ * debugging information. */
+ for (gc = finalizers.gc.gc_next;
+ gc != &finalizers;
+ gc = gc->gc.gc_next) {
+ n++;
+ if (debug & DEBUG_UNCOLLECTABLE)
+ debug_cycle("uncollectable", FROM_GC(gc));
+ }
+ if (debug & DEBUG_STATS) {
+ double t2 = get_time();
+ if (m == 0 && n == 0)
+ PySys_WriteStderr("gc: done");
+ else
+ PySys_WriteStderr(
+ "gc: done, "
+ "%" PY_FORMAT_SIZE_T "d unreachable, "
+ "%" PY_FORMAT_SIZE_T "d uncollectable",
+ n+m, n);
+ if (t1 && t2) {
+ PySys_WriteStderr(", %.4fs elapsed", t2-t1);
+ }
+ PySys_WriteStderr(".\n");
+ }
+
+ /* Append instances in the uncollectable set to a Python
+ * reachable list of garbage. The programmer has to deal with
+ * this if they insist on creating this type of structure.
+ */
+ (void)handle_finalizers(&finalizers, old);
+
+ /* Clear free list only during the collection of the highest
+ * generation */
+ if (generation == NUM_GENERATIONS-1) {
+ clear_freelists();
+ }
+
+ if (PyErr_Occurred()) {
+ if (gc_str == NULL)
+ gc_str = PyString_FromString("garbage collection");
+ PyErr_WriteUnraisable(gc_str);
+ Py_FatalError("unexpected exception during garbage collection");
+ }
+ return n+m;
}
static Py_ssize_t
collect_generations(void)
{
- int i;
- Py_ssize_t n = 0;
-
- /* Find the oldest generation (highest numbered) where the count
- * exceeds the threshold. Objects in the that generation and
- * generations younger than it will be collected. */
- for (i = NUM_GENERATIONS-1; i >= 0; i--) {
- if (generations[i].count > generations[i].threshold) {
- /* Avoid quadratic performance degradation in number
- of tracked objects. See comments at the beginning
- of this file, and issue #4074.
- */
- if (i == NUM_GENERATIONS - 1
- && long_lived_pending < long_lived_total / 4)
- continue;
- n = collect(i);
- break;
- }
- }
- return n;
+ int i;
+ Py_ssize_t n = 0;
+
+ /* Find the oldest generation (highest numbered) where the count
+ * exceeds the threshold. Objects in the that generation and
+ * generations younger than it will be collected. */
+ for (i = NUM_GENERATIONS-1; i >= 0; i--) {
+ if (generations[i].count > generations[i].threshold) {
+ /* Avoid quadratic performance degradation in number
+ of tracked objects. See comments at the beginning
+ of this file, and issue #4074.
+ */
+ if (i == NUM_GENERATIONS - 1
+ && long_lived_pending < long_lived_total / 4)
+ continue;
+ n = collect(i);
+ break;
+ }
+ }
+ return n;
}
PyDoc_STRVAR(gc_enable__doc__,
@@ -1008,9 +1008,9 @@ PyDoc_STRVAR(gc_enable__doc__,
static PyObject *
gc_enable(PyObject *self, PyObject *noargs)
{
- enabled = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ enabled = 1;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_disable__doc__,
@@ -1021,9 +1021,9 @@ PyDoc_STRVAR(gc_disable__doc__,
static PyObject *
gc_disable(PyObject *self, PyObject *noargs)
{
- enabled = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ enabled = 0;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_isenabled__doc__,
@@ -1034,7 +1034,7 @@ PyDoc_STRVAR(gc_isenabled__doc__,
static PyObject *
gc_isenabled(PyObject *self, PyObject *noargs)
{
- return PyBool_FromLong((long)enabled);
+ return PyBool_FromLong((long)enabled);
}
PyDoc_STRVAR(gc_collect__doc__,
@@ -1048,27 +1048,27 @@ PyDoc_STRVAR(gc_collect__doc__,
static PyObject *
gc_collect(PyObject *self, PyObject *args, PyObject *kws)
{
- static char *keywords[] = {"generation", NULL};
- int genarg = NUM_GENERATIONS - 1;
- Py_ssize_t n;
-
- if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))
- return NULL;
-
- else if (genarg < 0 || genarg >= NUM_GENERATIONS) {
- PyErr_SetString(PyExc_ValueError, "invalid generation");
- return NULL;
- }
-
- if (collecting)
- n = 0; /* already collecting, don't do anything */
- else {
- collecting = 1;
- n = collect(genarg);
- collecting = 0;
- }
-
- return PyInt_FromSsize_t(n);
+ static char *keywords[] = {"generation", NULL};
+ int genarg = NUM_GENERATIONS - 1;
+ Py_ssize_t n;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kws, "|i", keywords, &genarg))
+ return NULL;
+
+ else if (genarg < 0 || genarg >= NUM_GENERATIONS) {
+ PyErr_SetString(PyExc_ValueError, "invalid generation");
+ return NULL;
+ }
+
+ if (collecting)
+ n = 0; /* already collecting, don't do anything */
+ else {
+ collecting = 1;
+ n = collect(genarg);
+ collecting = 0;
+ }
+
+ return PyInt_FromSsize_t(n);
}
PyDoc_STRVAR(gc_set_debug__doc__,
@@ -1090,11 +1090,11 @@ PyDoc_STRVAR(gc_set_debug__doc__,
static PyObject *
gc_set_debug(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:set_debug", &debug))
+ return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_get_debug__doc__,
@@ -1105,7 +1105,7 @@ PyDoc_STRVAR(gc_get_debug__doc__,
static PyObject *
gc_get_debug(PyObject *self, PyObject *noargs)
{
- return Py_BuildValue("i", debug);
+ return Py_BuildValue("i", debug);
}
PyDoc_STRVAR(gc_set_thresh__doc__,
@@ -1117,19 +1117,19 @@ PyDoc_STRVAR(gc_set_thresh__doc__,
static PyObject *
gc_set_thresh(PyObject *self, PyObject *args)
{
- int i;
- if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
- &generations[0].threshold,
- &generations[1].threshold,
- &generations[2].threshold))
- return NULL;
- for (i = 2; i < NUM_GENERATIONS; i++) {
- /* generations higher than 2 get the same threshold */
- generations[i].threshold = generations[2].threshold;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ int i;
+ if (!PyArg_ParseTuple(args, "i|ii:set_threshold",
+ &generations[0].threshold,
+ &generations[1].threshold,
+ &generations[2].threshold))
+ return NULL;
+ for (i = 2; i < NUM_GENERATIONS; i++) {
+ /* generations higher than 2 get the same threshold */
+ generations[i].threshold = generations[2].threshold;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(gc_get_thresh__doc__,
@@ -1140,10 +1140,10 @@ PyDoc_STRVAR(gc_get_thresh__doc__,
static PyObject *
gc_get_thresh(PyObject *self, PyObject *noargs)
{
- return Py_BuildValue("(iii)",
- generations[0].threshold,
- generations[1].threshold,
- generations[2].threshold);
+ return Py_BuildValue("(iii)",
+ generations[0].threshold,
+ generations[1].threshold,
+ generations[2].threshold);
}
PyDoc_STRVAR(gc_get_count__doc__,
@@ -1154,39 +1154,39 @@ PyDoc_STRVAR(gc_get_count__doc__,
static PyObject *
gc_get_count(PyObject *self, PyObject *noargs)
{
- return Py_BuildValue("(iii)",
- generations[0].count,
- generations[1].count,
- generations[2].count);
+ return Py_BuildValue("(iii)",
+ generations[0].count,
+ generations[1].count,
+ generations[2].count);
}
static int
referrersvisit(PyObject* obj, PyObject *objs)
{
- Py_ssize_t i;
- for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
- if (PyTuple_GET_ITEM(objs, i) == obj)
- return 1;
- return 0;
+ Py_ssize_t i;
+ for (i = 0; i < PyTuple_GET_SIZE(objs); i++)
+ if (PyTuple_GET_ITEM(objs, i) == obj)
+ return 1;
+ return 0;
}
static int
gc_referrers_for(PyObject *objs, PyGC_Head *list, PyObject *resultlist)
{
- PyGC_Head *gc;
- PyObject *obj;
- traverseproc traverse;
- for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
- obj = FROM_GC(gc);
- traverse = Py_TYPE(obj)->tp_traverse;
- if (obj == objs || obj == resultlist)
- continue;
- if (traverse(obj, (visitproc)referrersvisit, objs)) {
- if (PyList_Append(resultlist, obj) < 0)
- return 0; /* error */
- }
- }
- return 1; /* no error */
+ PyGC_Head *gc;
+ PyObject *obj;
+ traverseproc traverse;
+ for (gc = list->gc.gc_next; gc != list; gc = gc->gc.gc_next) {
+ obj = FROM_GC(gc);
+ traverse = Py_TYPE(obj)->tp_traverse;
+ if (obj == objs || obj == resultlist)
+ continue;
+ if (traverse(obj, (visitproc)referrersvisit, objs)) {
+ if (PyList_Append(resultlist, obj) < 0)
+ return 0; /* error */
+ }
+ }
+ return 1; /* no error */
}
PyDoc_STRVAR(gc_get_referrers__doc__,
@@ -1196,24 +1196,24 @@ Return the list of objects that directly refer to any of objs.");
static PyObject *
gc_get_referrers(PyObject *self, PyObject *args)
{
- int i;
- PyObject *result = PyList_New(0);
- if (!result) return NULL;
-
- for (i = 0; i < NUM_GENERATIONS; i++) {
- if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ int i;
+ PyObject *result = PyList_New(0);
+ if (!result) return NULL;
+
+ for (i = 0; i < NUM_GENERATIONS; i++) {
+ if (!(gc_referrers_for(args, GEN_HEAD(i), result))) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
/* Append obj to list; return true if error (out of memory), false if OK. */
static int
referentsvisit(PyObject *obj, PyObject *list)
{
- return PyList_Append(list, obj) < 0;
+ return PyList_Append(list, obj) < 0;
}
PyDoc_STRVAR(gc_get_referents__doc__,
@@ -1223,27 +1223,27 @@ Return the list of objects that are directly referred to by objs.");
static PyObject *
gc_get_referents(PyObject *self, PyObject *args)
{
- Py_ssize_t i;
- PyObject *result = PyList_New(0);
-
- if (result == NULL)
- return NULL;
-
- for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
- traverseproc traverse;
- PyObject *obj = PyTuple_GET_ITEM(args, i);
-
- if (! PyObject_IS_GC(obj))
- continue;
- traverse = Py_TYPE(obj)->tp_traverse;
- if (! traverse)
- continue;
- if (traverse(obj, (visitproc)referentsvisit, result)) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ Py_ssize_t i;
+ PyObject *result = PyList_New(0);
+
+ if (result == NULL)
+ return NULL;
+
+ for (i = 0; i < PyTuple_GET_SIZE(args); i++) {
+ traverseproc traverse;
+ PyObject *obj = PyTuple_GET_ITEM(args, i);
+
+ if (! PyObject_IS_GC(obj))
+ continue;
+ traverse = Py_TYPE(obj)->tp_traverse;
+ if (! traverse)
+ continue;
+ if (traverse(obj, (visitproc)referentsvisit, result)) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
PyDoc_STRVAR(gc_get_objects__doc__,
@@ -1255,19 +1255,19 @@ PyDoc_STRVAR(gc_get_objects__doc__,
static PyObject *
gc_get_objects(PyObject *self, PyObject *noargs)
{
- int i;
- PyObject* result;
-
- result = PyList_New(0);
- if (result == NULL)
- return NULL;
- for (i = 0; i < NUM_GENERATIONS; i++) {
- if (append_objects(result, GEN_HEAD(i))) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ int i;
+ PyObject* result;
+
+ result = PyList_New(0);
+ if (result == NULL)
+ return NULL;
+ for (i = 0; i < NUM_GENERATIONS; i++) {
+ if (append_objects(result, GEN_HEAD(i))) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
PyDoc_STRVAR(gc_is_tracked__doc__,
@@ -1280,14 +1280,14 @@ PyDoc_STRVAR(gc_is_tracked__doc__,
static PyObject *
gc_is_tracked(PyObject *self, PyObject *obj)
{
- PyObject *result;
-
- if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
- result = Py_True;
- else
- result = Py_False;
- Py_INCREF(result);
- return result;
+ PyObject *result;
+
+ if (PyObject_IS_GC(obj) && IS_TRACKED(obj))
+ result = Py_True;
+ else
+ result = Py_False;
+ Py_INCREF(result);
+ return result;
}
@@ -1309,67 +1309,67 @@ PyDoc_STRVAR(gc__doc__,
"get_referents() -- Return the list of objects that an object refers to.\n");
static PyMethodDef GcMethods[] = {
- {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
- {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
- {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
- {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
- {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
- {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},
- {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
- {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
- {"collect", (PyCFunction)gc_collect,
- METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},
- {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
- {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__},
- {"get_referrers", gc_get_referrers, METH_VARARGS,
- gc_get_referrers__doc__},
- {"get_referents", gc_get_referents, METH_VARARGS,
- gc_get_referents__doc__},
- {NULL, NULL} /* Sentinel */
+ {"enable", gc_enable, METH_NOARGS, gc_enable__doc__},
+ {"disable", gc_disable, METH_NOARGS, gc_disable__doc__},
+ {"isenabled", gc_isenabled, METH_NOARGS, gc_isenabled__doc__},
+ {"set_debug", gc_set_debug, METH_VARARGS, gc_set_debug__doc__},
+ {"get_debug", gc_get_debug, METH_NOARGS, gc_get_debug__doc__},
+ {"get_count", gc_get_count, METH_NOARGS, gc_get_count__doc__},
+ {"set_threshold", gc_set_thresh, METH_VARARGS, gc_set_thresh__doc__},
+ {"get_threshold", gc_get_thresh, METH_NOARGS, gc_get_thresh__doc__},
+ {"collect", (PyCFunction)gc_collect,
+ METH_VARARGS | METH_KEYWORDS, gc_collect__doc__},
+ {"get_objects", gc_get_objects,METH_NOARGS, gc_get_objects__doc__},
+ {"is_tracked", gc_is_tracked, METH_O, gc_is_tracked__doc__},
+ {"get_referrers", gc_get_referrers, METH_VARARGS,
+ gc_get_referrers__doc__},
+ {"get_referents", gc_get_referents, METH_VARARGS,
+ gc_get_referents__doc__},
+ {NULL, NULL} /* Sentinel */
};
PyMODINIT_FUNC
initgc(void)
{
- PyObject *m;
-
- m = Py_InitModule4("gc",
- GcMethods,
- gc__doc__,
- NULL,
- PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- if (garbage == NULL) {
- garbage = PyList_New(0);
- if (garbage == NULL)
- return;
- }
- Py_INCREF(garbage);
- if (PyModule_AddObject(m, "garbage", garbage) < 0)
- return;
-
- /* Importing can't be done in collect() because collect()
- * can be called via PyGC_Collect() in Py_Finalize().
- * This wouldn't be a problem, except that <initialized> is
- * reset to 0 before calling collect which trips up
- * the import and triggers an assertion.
- */
- if (tmod == NULL) {
- tmod = PyImport_ImportModuleNoBlock("time");
- if (tmod == NULL)
- PyErr_Clear();
- }
+ PyObject *m;
+
+ m = Py_InitModule4("gc",
+ GcMethods,
+ gc__doc__,
+ NULL,
+ PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ if (garbage == NULL) {
+ garbage = PyList_New(0);
+ if (garbage == NULL)
+ return;
+ }
+ Py_INCREF(garbage);
+ if (PyModule_AddObject(m, "garbage", garbage) < 0)
+ return;
+
+ /* Importing can't be done in collect() because collect()
+ * can be called via PyGC_Collect() in Py_Finalize().
+ * This wouldn't be a problem, except that <initialized> is
+ * reset to 0 before calling collect which trips up
+ * the import and triggers an assertion.
+ */
+ if (tmod == NULL) {
+ tmod = PyImport_ImportModuleNoBlock("time");
+ if (tmod == NULL)
+ PyErr_Clear();
+ }
#define ADD_INT(NAME) if (PyModule_AddIntConstant(m, #NAME, NAME) < 0) return
- ADD_INT(DEBUG_STATS);
- ADD_INT(DEBUG_COLLECTABLE);
- ADD_INT(DEBUG_UNCOLLECTABLE);
- ADD_INT(DEBUG_INSTANCES);
- ADD_INT(DEBUG_OBJECTS);
- ADD_INT(DEBUG_SAVEALL);
- ADD_INT(DEBUG_LEAK);
+ ADD_INT(DEBUG_STATS);
+ ADD_INT(DEBUG_COLLECTABLE);
+ ADD_INT(DEBUG_UNCOLLECTABLE);
+ ADD_INT(DEBUG_INSTANCES);
+ ADD_INT(DEBUG_OBJECTS);
+ ADD_INT(DEBUG_SAVEALL);
+ ADD_INT(DEBUG_LEAK);
#undef ADD_INT
}
@@ -1377,24 +1377,24 @@ initgc(void)
Py_ssize_t
PyGC_Collect(void)
{
- Py_ssize_t n;
+ Py_ssize_t n;
- if (collecting)
- n = 0; /* already collecting, don't do anything */
- else {
- collecting = 1;
- n = collect(NUM_GENERATIONS - 1);
- collecting = 0;
- }
+ if (collecting)
+ n = 0; /* already collecting, don't do anything */
+ else {
+ collecting = 1;
+ n = collect(NUM_GENERATIONS - 1);
+ collecting = 0;
+ }
- return n;
+ return n;
}
/* for debugging */
void
_PyGC_Dump(PyGC_Head *g)
{
- _PyObject_Dump(FROM_GC(g));
+ _PyObject_Dump(FROM_GC(g));
}
/* extension modules might be compiled with GC support so these
@@ -1408,7 +1408,7 @@ _PyGC_Dump(PyGC_Head *g)
void
PyObject_GC_Track(void *op)
{
- _PyObject_GC_TRACK(op);
+ _PyObject_GC_TRACK(op);
}
/* for binary compatibility with 2.2 */
@@ -1421,11 +1421,11 @@ _PyObject_GC_Track(PyObject *op)
void
PyObject_GC_UnTrack(void *op)
{
- /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
- * call PyObject_GC_UnTrack twice on an object.
- */
- if (IS_TRACKED(op))
- _PyObject_GC_UNTRACK(op);
+ /* Obscure: the Py_TRASHCAN mechanism requires that we be able to
+ * call PyObject_GC_UnTrack twice on an object.
+ */
+ if (IS_TRACKED(op))
+ _PyObject_GC_UNTRACK(op);
}
/* for binary compatibility with 2.2 */
@@ -1438,73 +1438,73 @@ _PyObject_GC_UnTrack(PyObject *op)
PyObject *
_PyObject_GC_Malloc(size_t basicsize)
{
- PyObject *op;
- PyGC_Head *g;
- if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
- return PyErr_NoMemory();
- g = (PyGC_Head *)PyObject_MALLOC(
- sizeof(PyGC_Head) + basicsize);
- if (g == NULL)
- return PyErr_NoMemory();
- g->gc.gc_refs = GC_UNTRACKED;
- generations[0].count++; /* number of allocated GC objects */
- if (generations[0].count > generations[0].threshold &&
- enabled &&
- generations[0].threshold &&
- !collecting &&
- !PyErr_Occurred()) {
- collecting = 1;
- collect_generations();
- collecting = 0;
- }
- op = FROM_GC(g);
- return op;
+ PyObject *op;
+ PyGC_Head *g;
+ if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
+ return PyErr_NoMemory();
+ g = (PyGC_Head *)PyObject_MALLOC(
+ sizeof(PyGC_Head) + basicsize);
+ if (g == NULL)
+ return PyErr_NoMemory();
+ g->gc.gc_refs = GC_UNTRACKED;
+ generations[0].count++; /* number of allocated GC objects */
+ if (generations[0].count > generations[0].threshold &&
+ enabled &&
+ generations[0].threshold &&
+ !collecting &&
+ !PyErr_Occurred()) {
+ collecting = 1;
+ collect_generations();
+ collecting = 0;
+ }
+ op = FROM_GC(g);
+ return op;
}
PyObject *
_PyObject_GC_New(PyTypeObject *tp)
{
- PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
- if (op != NULL)
- op = PyObject_INIT(op, tp);
- return op;
+ PyObject *op = _PyObject_GC_Malloc(_PyObject_SIZE(tp));
+ if (op != NULL)
+ op = PyObject_INIT(op, tp);
+ return op;
}
PyVarObject *
_PyObject_GC_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
{
- const size_t size = _PyObject_VAR_SIZE(tp, nitems);
- PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
- if (op != NULL)
- op = PyObject_INIT_VAR(op, tp, nitems);
- return op;
+ const size_t size = _PyObject_VAR_SIZE(tp, nitems);
+ PyVarObject *op = (PyVarObject *) _PyObject_GC_Malloc(size);
+ if (op != NULL)
+ op = PyObject_INIT_VAR(op, tp, nitems);
+ return op;
}
PyVarObject *
_PyObject_GC_Resize(PyVarObject *op, Py_ssize_t nitems)
{
- const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
- PyGC_Head *g = AS_GC(op);
- if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
- return (PyVarObject *)PyErr_NoMemory();
- g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
- if (g == NULL)
- return (PyVarObject *)PyErr_NoMemory();
- op = (PyVarObject *) FROM_GC(g);
- Py_SIZE(op) = nitems;
- return op;
+ const size_t basicsize = _PyObject_VAR_SIZE(Py_TYPE(op), nitems);
+ PyGC_Head *g = AS_GC(op);
+ if (basicsize > PY_SSIZE_T_MAX - sizeof(PyGC_Head))
+ return (PyVarObject *)PyErr_NoMemory();
+ g = (PyGC_Head *)PyObject_REALLOC(g, sizeof(PyGC_Head) + basicsize);
+ if (g == NULL)
+ return (PyVarObject *)PyErr_NoMemory();
+ op = (PyVarObject *) FROM_GC(g);
+ Py_SIZE(op) = nitems;
+ return op;
}
void
PyObject_GC_Del(void *op)
{
- PyGC_Head *g = AS_GC(op);
- if (IS_TRACKED(op))
- gc_list_remove(g);
- if (generations[0].count > 0) {
- generations[0].count--;
- }
- PyObject_FREE(g);
+ PyGC_Head *g = AS_GC(op);
+ if (IS_TRACKED(op))
+ gc_list_remove(g);
+ if (generations[0].count > 0) {
+ generations[0].count--;
+ }
+ PyObject_FREE(g);
}
/* for binary compatibility with 2.2 */
diff --git a/Modules/getaddrinfo.c b/Modules/getaddrinfo.c
index 4d19c34..1d0bfbb 100644
--- a/Modules/getaddrinfo.c
+++ b/Modules/getaddrinfo.c
@@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, and 1998 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
* GAI_ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
@@ -73,52 +73,52 @@ static struct in6_addr faith_prefix = IN6ADDR_GAI_ANY_INIT;
static const char in_addrany[] = { 0, 0, 0, 0 };
static const char in6_addrany[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
-static const char in_loopback[] = { 127, 0, 0, 1 };
+static const char in_loopback[] = { 127, 0, 0, 1 };
static const char in6_loopback[] = {
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
};
struct sockinet {
- u_char si_len;
- u_char si_family;
- u_short si_port;
+ u_char si_len;
+ u_char si_family;
+ u_short si_port;
};
static struct gai_afd {
- int a_af;
- int a_addrlen;
- int a_socklen;
- int a_off;
- const char *a_addrany;
- const char *a_loopback;
+ int a_af;
+ int a_addrlen;
+ int a_socklen;
+ int a_off;
+ const char *a_addrany;
+ const char *a_loopback;
} gai_afdl [] = {
#ifdef ENABLE_IPV6
#define N_INET6 0
- {PF_INET6, sizeof(struct in6_addr),
- sizeof(struct sockaddr_in6),
- offsetof(struct sockaddr_in6, sin6_addr),
- in6_addrany, in6_loopback},
+ {PF_INET6, sizeof(struct in6_addr),
+ sizeof(struct sockaddr_in6),
+ offsetof(struct sockaddr_in6, sin6_addr),
+ in6_addrany, in6_loopback},
#define N_INET 1
#else
#define N_INET 0
#endif
- {PF_INET, sizeof(struct in_addr),
- sizeof(struct sockaddr_in),
- offsetof(struct sockaddr_in, sin_addr),
- in_addrany, in_loopback},
- {0, 0, 0, 0, NULL, NULL},
+ {PF_INET, sizeof(struct in_addr),
+ sizeof(struct sockaddr_in),
+ offsetof(struct sockaddr_in, sin_addr),
+ in_addrany, in_loopback},
+ {0, 0, 0, 0, NULL, NULL},
};
#ifdef ENABLE_IPV6
-#define PTON_MAX 16
+#define PTON_MAX 16
#else
-#define PTON_MAX 4
+#define PTON_MAX 4
#endif
#ifndef IN_MULTICAST
-#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U)
+#define IN_MULTICAST(i) (((i) & 0xf0000000U) == 0xe0000000U)
#endif
#ifndef IN_EXPERIMENTAL
@@ -126,73 +126,73 @@ static struct gai_afd {
#endif
#ifndef IN_LOOPBACKNET
-#define IN_LOOPBACKNET 127
+#define IN_LOOPBACKNET 127
#endif
static int get_name Py_PROTO((const char *, struct gai_afd *,
- struct addrinfo **, char *, struct addrinfo *,
- int));
+ struct addrinfo **, char *, struct addrinfo *,
+ int));
static int get_addr Py_PROTO((const char *, int, struct addrinfo **,
- struct addrinfo *, int));
+ struct addrinfo *, int));
static int str_isnumber Py_PROTO((const char *));
-
+
static char *ai_errlist[] = {
- "success.",
- "address family for hostname not supported.", /* EAI_ADDRFAMILY */
- "temporary failure in name resolution.", /* EAI_AGAIN */
- "invalid value for ai_flags.", /* EAI_BADFLAGS */
- "non-recoverable failure in name resolution.", /* EAI_FAIL */
- "ai_family not supported.", /* EAI_FAMILY */
- "memory allocation failure.", /* EAI_MEMORY */
- "no address associated with hostname.", /* EAI_NODATA */
- "hostname nor servname provided, or not known.",/* EAI_NONAME */
- "servname not supported for ai_socktype.", /* EAI_SERVICE */
- "ai_socktype not supported.", /* EAI_SOCKTYPE */
- "system error returned in errno.", /* EAI_SYSTEM */
- "invalid value for hints.", /* EAI_BADHINTS */
- "resolved protocol is unknown.", /* EAI_PROTOCOL */
- "unknown error.", /* EAI_MAX */
+ "success.",
+ "address family for hostname not supported.", /* EAI_ADDRFAMILY */
+ "temporary failure in name resolution.", /* EAI_AGAIN */
+ "invalid value for ai_flags.", /* EAI_BADFLAGS */
+ "non-recoverable failure in name resolution.", /* EAI_FAIL */
+ "ai_family not supported.", /* EAI_FAMILY */
+ "memory allocation failure.", /* EAI_MEMORY */
+ "no address associated with hostname.", /* EAI_NODATA */
+ "hostname nor servname provided, or not known.",/* EAI_NONAME */
+ "servname not supported for ai_socktype.", /* EAI_SERVICE */
+ "ai_socktype not supported.", /* EAI_SOCKTYPE */
+ "system error returned in errno.", /* EAI_SYSTEM */
+ "invalid value for hints.", /* EAI_BADHINTS */
+ "resolved protocol is unknown.", /* EAI_PROTOCOL */
+ "unknown error.", /* EAI_MAX */
};
#define GET_CANONNAME(ai, str) \
if (pai->ai_flags & AI_CANONNAME) {\
- if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\
- strcpy((ai)->ai_canonname, (str));\
- } else {\
- error = EAI_MEMORY;\
- goto free;\
- }\
+ if (((ai)->ai_canonname = (char *)malloc(strlen(str) + 1)) != NULL) {\
+ strcpy((ai)->ai_canonname, (str));\
+ } else {\
+ error = EAI_MEMORY;\
+ goto free;\
+ }\
}
#ifdef HAVE_SOCKADDR_SA_LEN
#define GET_AI(ai, gai_afd, addr, port) {\
- char *p;\
- if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
- ((gai_afd)->a_socklen)))\
- == NULL) goto free;\
- memcpy(ai, pai, sizeof(struct addrinfo));\
- (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
- memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
- (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\
- (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
- ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
- p = (char *)((ai)->ai_addr);\
- memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
+ char *p;\
+ if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
+ ((gai_afd)->a_socklen)))\
+ == NULL) goto free;\
+ memcpy(ai, pai, sizeof(struct addrinfo));\
+ (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
+ memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
+ (ai)->ai_addr->sa_len = (ai)->ai_addrlen = (gai_afd)->a_socklen;\
+ (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
+ ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
+ p = (char *)((ai)->ai_addr);\
+ memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
}
#else
#define GET_AI(ai, gai_afd, addr, port) {\
- char *p;\
- if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
- ((gai_afd)->a_socklen)))\
- == NULL) goto free;\
- memcpy(ai, pai, sizeof(struct addrinfo));\
- (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
- memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
- (ai)->ai_addrlen = (gai_afd)->a_socklen;\
- (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
- ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
- p = (char *)((ai)->ai_addr);\
- memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
+ char *p;\
+ if (((ai) = (struct addrinfo *)malloc(sizeof(struct addrinfo) +\
+ ((gai_afd)->a_socklen)))\
+ == NULL) goto free;\
+ memcpy(ai, pai, sizeof(struct addrinfo));\
+ (ai)->ai_addr = (struct sockaddr *)((ai) + 1);\
+ memset((ai)->ai_addr, 0, (gai_afd)->a_socklen);\
+ (ai)->ai_addrlen = (gai_afd)->a_socklen;\
+ (ai)->ai_addr->sa_family = (ai)->ai_family = (gai_afd)->a_af;\
+ ((struct sockinet *)(ai)->ai_addr)->si_port = port;\
+ p = (char *)((ai)->ai_addr);\
+ memcpy(p + (gai_afd)->a_off, (addr), (gai_afd)->a_addrlen);\
}
#endif
@@ -201,438 +201,438 @@ if (pai->ai_flags & AI_CANONNAME) {\
char *
gai_strerror(int ecode)
{
- if (ecode < 0 || ecode > EAI_MAX)
- ecode = EAI_MAX;
- return ai_errlist[ecode];
+ if (ecode < 0 || ecode > EAI_MAX)
+ ecode = EAI_MAX;
+ return ai_errlist[ecode];
}
void
freeaddrinfo(struct addrinfo *ai)
{
- struct addrinfo *next;
-
- do {
- next = ai->ai_next;
- if (ai->ai_canonname)
- free(ai->ai_canonname);
- /* no need to free(ai->ai_addr) */
- free(ai);
- } while ((ai = next) != NULL);
+ struct addrinfo *next;
+
+ do {
+ next = ai->ai_next;
+ if (ai->ai_canonname)
+ free(ai->ai_canonname);
+ /* no need to free(ai->ai_addr) */
+ free(ai);
+ } while ((ai = next) != NULL);
}
static int
str_isnumber(const char *p)
{
- unsigned char *q = (unsigned char *)p;
- while (*q) {
- if (! isdigit(*q))
- return NO;
- q++;
- }
- return YES;
+ unsigned char *q = (unsigned char *)p;
+ while (*q) {
+ if (! isdigit(*q))
+ return NO;
+ q++;
+ }
+ return YES;
}
int
getaddrinfo(const char*hostname, const char*servname,
const struct addrinfo *hints, struct addrinfo **res)
{
- struct addrinfo sentinel;
- struct addrinfo *top = NULL;
- struct addrinfo *cur;
- int i, error = 0;
- char pton[PTON_MAX];
- struct addrinfo ai;
- struct addrinfo *pai;
- u_short port;
+ struct addrinfo sentinel;
+ struct addrinfo *top = NULL;
+ struct addrinfo *cur;
+ int i, error = 0;
+ char pton[PTON_MAX];
+ struct addrinfo ai;
+ struct addrinfo *pai;
+ u_short port;
#ifdef FAITH
- static int firsttime = 1;
-
- if (firsttime) {
- /* translator hack */
- {
- char *q = getenv("GAI");
- if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1)
- translate = YES;
- }
- firsttime = 0;
- }
+ static int firsttime = 1;
+
+ if (firsttime) {
+ /* translator hack */
+ {
+ char *q = getenv("GAI");
+ if (q && inet_pton(AF_INET6, q, &faith_prefix) == 1)
+ translate = YES;
+ }
+ firsttime = 0;
+ }
#endif
- /* initialize file static vars */
- sentinel.ai_next = NULL;
- cur = &sentinel;
- pai = &ai;
- pai->ai_flags = 0;
- pai->ai_family = PF_UNSPEC;
- pai->ai_socktype = GAI_ANY;
- pai->ai_protocol = GAI_ANY;
- pai->ai_addrlen = 0;
- pai->ai_canonname = NULL;
- pai->ai_addr = NULL;
- pai->ai_next = NULL;
- port = GAI_ANY;
-
- if (hostname == NULL && servname == NULL)
- return EAI_NONAME;
- if (hints) {
- /* error check for hints */
- if (hints->ai_addrlen || hints->ai_canonname ||
- hints->ai_addr || hints->ai_next)
- ERR(EAI_BADHINTS); /* xxx */
- if (hints->ai_flags & ~AI_MASK)
- ERR(EAI_BADFLAGS);
- switch (hints->ai_family) {
- case PF_UNSPEC:
- case PF_INET:
+ /* initialize file static vars */
+ sentinel.ai_next = NULL;
+ cur = &sentinel;
+ pai = &ai;
+ pai->ai_flags = 0;
+ pai->ai_family = PF_UNSPEC;
+ pai->ai_socktype = GAI_ANY;
+ pai->ai_protocol = GAI_ANY;
+ pai->ai_addrlen = 0;
+ pai->ai_canonname = NULL;
+ pai->ai_addr = NULL;
+ pai->ai_next = NULL;
+ port = GAI_ANY;
+
+ if (hostname == NULL && servname == NULL)
+ return EAI_NONAME;
+ if (hints) {
+ /* error check for hints */
+ if (hints->ai_addrlen || hints->ai_canonname ||
+ hints->ai_addr || hints->ai_next)
+ ERR(EAI_BADHINTS); /* xxx */
+ if (hints->ai_flags & ~AI_MASK)
+ ERR(EAI_BADFLAGS);
+ switch (hints->ai_family) {
+ case PF_UNSPEC:
+ case PF_INET:
#ifdef ENABLE_IPV6
- case PF_INET6:
+ case PF_INET6:
#endif
- break;
- default:
- ERR(EAI_FAMILY);
- }
- memcpy(pai, hints, sizeof(*pai));
- switch (pai->ai_socktype) {
- case GAI_ANY:
- switch (pai->ai_protocol) {
- case GAI_ANY:
- break;
- case IPPROTO_UDP:
- pai->ai_socktype = SOCK_DGRAM;
- break;
- case IPPROTO_TCP:
- pai->ai_socktype = SOCK_STREAM;
- break;
- default:
- pai->ai_socktype = SOCK_RAW;
- break;
- }
- break;
- case SOCK_RAW:
- break;
- case SOCK_DGRAM:
- if (pai->ai_protocol != IPPROTO_UDP &&
- pai->ai_protocol != GAI_ANY)
- ERR(EAI_BADHINTS); /*xxx*/
- pai->ai_protocol = IPPROTO_UDP;
- break;
- case SOCK_STREAM:
- if (pai->ai_protocol != IPPROTO_TCP &&
- pai->ai_protocol != GAI_ANY)
- ERR(EAI_BADHINTS); /*xxx*/
- pai->ai_protocol = IPPROTO_TCP;
- break;
- default:
- ERR(EAI_SOCKTYPE);
- /* unreachable */
- }
- }
-
- /*
- * service port
- */
- if (servname) {
- if (str_isnumber(servname)) {
- if (pai->ai_socktype == GAI_ANY) {
- /* caller accept *GAI_ANY* socktype */
- pai->ai_socktype = SOCK_DGRAM;
- pai->ai_protocol = IPPROTO_UDP;
- }
- port = htons((u_short)atoi(servname));
- } else {
- struct servent *sp;
- char *proto;
-
- proto = NULL;
- switch (pai->ai_socktype) {
- case GAI_ANY:
- proto = NULL;
- break;
- case SOCK_DGRAM:
- proto = "udp";
- break;
- case SOCK_STREAM:
- proto = "tcp";
- break;
- default:
- fprintf(stderr, "panic!\n");
- break;
- }
- if ((sp = getservbyname(servname, proto)) == NULL)
- ERR(EAI_SERVICE);
- port = sp->s_port;
- if (pai->ai_socktype == GAI_ANY) {
- if (strcmp(sp->s_proto, "udp") == 0) {
- pai->ai_socktype = SOCK_DGRAM;
- pai->ai_protocol = IPPROTO_UDP;
- } else if (strcmp(sp->s_proto, "tcp") == 0) {
- pai->ai_socktype = SOCK_STREAM;
- pai->ai_protocol = IPPROTO_TCP;
- } else
- ERR(EAI_PROTOCOL); /*xxx*/
- }
- }
- }
-
- /*
- * hostname == NULL.
- * passive socket -> anyaddr (0.0.0.0 or ::)
- * non-passive socket -> localhost (127.0.0.1 or ::1)
- */
- if (hostname == NULL) {
- struct gai_afd *gai_afd;
-
- for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) {
- if (!(pai->ai_family == PF_UNSPEC
- || pai->ai_family == gai_afd->a_af)) {
- continue;
- }
-
- if (pai->ai_flags & AI_PASSIVE) {
- GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port);
- /* xxx meaningless?
- * GET_CANONNAME(cur->ai_next, "anyaddr");
- */
- } else {
- GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback,
- port);
- /* xxx meaningless?
- * GET_CANONNAME(cur->ai_next, "localhost");
- */
- }
- cur = cur->ai_next;
- }
- top = sentinel.ai_next;
- if (top)
- goto good;
- else
- ERR(EAI_FAMILY);
- }
-
- /* hostname as numeric name */
- for (i = 0; gai_afdl[i].a_af; i++) {
- if (inet_pton(gai_afdl[i].a_af, hostname, pton)) {
- u_long v4a;
+ break;
+ default:
+ ERR(EAI_FAMILY);
+ }
+ memcpy(pai, hints, sizeof(*pai));
+ switch (pai->ai_socktype) {
+ case GAI_ANY:
+ switch (pai->ai_protocol) {
+ case GAI_ANY:
+ break;
+ case IPPROTO_UDP:
+ pai->ai_socktype = SOCK_DGRAM;
+ break;
+ case IPPROTO_TCP:
+ pai->ai_socktype = SOCK_STREAM;
+ break;
+ default:
+ pai->ai_socktype = SOCK_RAW;
+ break;
+ }
+ break;
+ case SOCK_RAW:
+ break;
+ case SOCK_DGRAM:
+ if (pai->ai_protocol != IPPROTO_UDP &&
+ pai->ai_protocol != GAI_ANY)
+ ERR(EAI_BADHINTS); /*xxx*/
+ pai->ai_protocol = IPPROTO_UDP;
+ break;
+ case SOCK_STREAM:
+ if (pai->ai_protocol != IPPROTO_TCP &&
+ pai->ai_protocol != GAI_ANY)
+ ERR(EAI_BADHINTS); /*xxx*/
+ pai->ai_protocol = IPPROTO_TCP;
+ break;
+ default:
+ ERR(EAI_SOCKTYPE);
+ /* unreachable */
+ }
+ }
+
+ /*
+ * service port
+ */
+ if (servname) {
+ if (str_isnumber(servname)) {
+ if (pai->ai_socktype == GAI_ANY) {
+ /* caller accept *GAI_ANY* socktype */
+ pai->ai_socktype = SOCK_DGRAM;
+ pai->ai_protocol = IPPROTO_UDP;
+ }
+ port = htons((u_short)atoi(servname));
+ } else {
+ struct servent *sp;
+ char *proto;
+
+ proto = NULL;
+ switch (pai->ai_socktype) {
+ case GAI_ANY:
+ proto = NULL;
+ break;
+ case SOCK_DGRAM:
+ proto = "udp";
+ break;
+ case SOCK_STREAM:
+ proto = "tcp";
+ break;
+ default:
+ fprintf(stderr, "panic!\n");
+ break;
+ }
+ if ((sp = getservbyname(servname, proto)) == NULL)
+ ERR(EAI_SERVICE);
+ port = sp->s_port;
+ if (pai->ai_socktype == GAI_ANY) {
+ if (strcmp(sp->s_proto, "udp") == 0) {
+ pai->ai_socktype = SOCK_DGRAM;
+ pai->ai_protocol = IPPROTO_UDP;
+ } else if (strcmp(sp->s_proto, "tcp") == 0) {
+ pai->ai_socktype = SOCK_STREAM;
+ pai->ai_protocol = IPPROTO_TCP;
+ } else
+ ERR(EAI_PROTOCOL); /*xxx*/
+ }
+ }
+ }
+
+ /*
+ * hostname == NULL.
+ * passive socket -> anyaddr (0.0.0.0 or ::)
+ * non-passive socket -> localhost (127.0.0.1 or ::1)
+ */
+ if (hostname == NULL) {
+ struct gai_afd *gai_afd;
+
+ for (gai_afd = &gai_afdl[0]; gai_afd->a_af; gai_afd++) {
+ if (!(pai->ai_family == PF_UNSPEC
+ || pai->ai_family == gai_afd->a_af)) {
+ continue;
+ }
+
+ if (pai->ai_flags & AI_PASSIVE) {
+ GET_AI(cur->ai_next, gai_afd, gai_afd->a_addrany, port);
+ /* xxx meaningless?
+ * GET_CANONNAME(cur->ai_next, "anyaddr");
+ */
+ } else {
+ GET_AI(cur->ai_next, gai_afd, gai_afd->a_loopback,
+ port);
+ /* xxx meaningless?
+ * GET_CANONNAME(cur->ai_next, "localhost");
+ */
+ }
+ cur = cur->ai_next;
+ }
+ top = sentinel.ai_next;
+ if (top)
+ goto good;
+ else
+ ERR(EAI_FAMILY);
+ }
+
+ /* hostname as numeric name */
+ for (i = 0; gai_afdl[i].a_af; i++) {
+ if (inet_pton(gai_afdl[i].a_af, hostname, pton)) {
+ u_long v4a;
#ifdef ENABLE_IPV6
- u_char pfx;
+ u_char pfx;
#endif
- switch (gai_afdl[i].a_af) {
- case AF_INET:
- v4a = ((struct in_addr *)pton)->s_addr;
- v4a = ntohl(v4a);
- if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
- pai->ai_flags &= ~AI_CANONNAME;
- v4a >>= IN_CLASSA_NSHIFT;
- if (v4a == 0 || v4a == IN_LOOPBACKNET)
- pai->ai_flags &= ~AI_CANONNAME;
- break;
+ switch (gai_afdl[i].a_af) {
+ case AF_INET:
+ v4a = ((struct in_addr *)pton)->s_addr;
+ v4a = ntohl(v4a);
+ if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
+ pai->ai_flags &= ~AI_CANONNAME;
+ v4a >>= IN_CLASSA_NSHIFT;
+ if (v4a == 0 || v4a == IN_LOOPBACKNET)
+ pai->ai_flags &= ~AI_CANONNAME;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- pfx = ((struct in6_addr *)pton)->s6_addr8[0];
- if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
- pai->ai_flags &= ~AI_CANONNAME;
- break;
+ case AF_INET6:
+ pfx = ((struct in6_addr *)pton)->s6_addr8[0];
+ if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
+ pai->ai_flags &= ~AI_CANONNAME;
+ break;
#endif
- }
-
- if (pai->ai_family == gai_afdl[i].a_af ||
- pai->ai_family == PF_UNSPEC) {
- if (! (pai->ai_flags & AI_CANONNAME)) {
- GET_AI(top, &gai_afdl[i], pton, port);
- goto good;
- }
- /*
- * if AI_CANONNAME and if reverse lookup
- * fail, return ai anyway to pacify
- * calling application.
- *
- * XXX getaddrinfo() is a name->address
- * translation function, and it looks strange
- * that we do addr->name translation here.
- */
- get_name(pton, &gai_afdl[i], &top, pton, pai, port);
- goto good;
- } else
- ERR(EAI_FAMILY); /*xxx*/
- }
- }
-
- if (pai->ai_flags & AI_NUMERICHOST)
- ERR(EAI_NONAME);
-
- /* hostname as alphabetical name */
- error = get_addr(hostname, pai->ai_family, &top, pai, port);
- if (error == 0) {
- if (top) {
+ }
+
+ if (pai->ai_family == gai_afdl[i].a_af ||
+ pai->ai_family == PF_UNSPEC) {
+ if (! (pai->ai_flags & AI_CANONNAME)) {
+ GET_AI(top, &gai_afdl[i], pton, port);
+ goto good;
+ }
+ /*
+ * if AI_CANONNAME and if reverse lookup
+ * fail, return ai anyway to pacify
+ * calling application.
+ *
+ * XXX getaddrinfo() is a name->address
+ * translation function, and it looks strange
+ * that we do addr->name translation here.
+ */
+ get_name(pton, &gai_afdl[i], &top, pton, pai, port);
+ goto good;
+ } else
+ ERR(EAI_FAMILY); /*xxx*/
+ }
+ }
+
+ if (pai->ai_flags & AI_NUMERICHOST)
+ ERR(EAI_NONAME);
+
+ /* hostname as alphabetical name */
+ error = get_addr(hostname, pai->ai_family, &top, pai, port);
+ if (error == 0) {
+ if (top) {
good:
- *res = top;
- return SUCCESS;
- } else
- error = EAI_FAIL;
- }
+ *res = top;
+ return SUCCESS;
+ } else
+ error = EAI_FAIL;
+ }
free:
- if (top)
- freeaddrinfo(top);
+ if (top)
+ freeaddrinfo(top);
bad:
- *res = NULL;
- return error;
+ *res = NULL;
+ return error;
}
static int
get_name(addr, gai_afd, res, numaddr, pai, port0)
- const char *addr;
- struct gai_afd *gai_afd;
- struct addrinfo **res;
- char *numaddr;
- struct addrinfo *pai;
- int port0;
+ const char *addr;
+ struct gai_afd *gai_afd;
+ struct addrinfo **res;
+ char *numaddr;
+ struct addrinfo *pai;
+ int port0;
{
- u_short port = port0 & 0xffff;
- struct hostent *hp;
- struct addrinfo *cur;
- int error = 0;
+ u_short port = port0 & 0xffff;
+ struct hostent *hp;
+ struct addrinfo *cur;
+ int error = 0;
#ifdef ENABLE_IPV6
- int h_error;
+ int h_error;
#endif
-
+
#ifdef ENABLE_IPV6
- hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error);
+ hp = getipnodebyaddr(addr, gai_afd->a_addrlen, gai_afd->a_af, &h_error);
#else
- hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET);
+ hp = gethostbyaddr(addr, gai_afd->a_addrlen, AF_INET);
#endif
- if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
- GET_AI(cur, gai_afd, hp->h_addr_list[0], port);
- GET_CANONNAME(cur, hp->h_name);
- } else
- GET_AI(cur, gai_afd, numaddr, port);
-
+ if (hp && hp->h_name && hp->h_name[0] && hp->h_addr_list[0]) {
+ GET_AI(cur, gai_afd, hp->h_addr_list[0], port);
+ GET_CANONNAME(cur, hp->h_name);
+ } else
+ GET_AI(cur, gai_afd, numaddr, port);
+
#ifdef ENABLE_IPV6
- if (hp)
- freehostent(hp);
+ if (hp)
+ freehostent(hp);
#endif
- *res = cur;
- return SUCCESS;
+ *res = cur;
+ return SUCCESS;
free:
- if (cur)
- freeaddrinfo(cur);
+ if (cur)
+ freeaddrinfo(cur);
#ifdef ENABLE_IPV6
- if (hp)
- freehostent(hp);
+ if (hp)
+ freehostent(hp);
#endif
/* bad: */
- *res = NULL;
- return error;
+ *res = NULL;
+ return error;
}
static int
get_addr(hostname, af, res, pai, port0)
- const char *hostname;
- int af;
- struct addrinfo **res;
- struct addrinfo *pai;
- int port0;
+ const char *hostname;
+ int af;
+ struct addrinfo **res;
+ struct addrinfo *pai;
+ int port0;
{
- u_short port = port0 & 0xffff;
- struct addrinfo sentinel;
- struct hostent *hp;
- struct addrinfo *top, *cur;
- struct gai_afd *gai_afd;
- int i, error = 0, h_error;
- char *ap;
-
- top = NULL;
- sentinel.ai_next = NULL;
- cur = &sentinel;
+ u_short port = port0 & 0xffff;
+ struct addrinfo sentinel;
+ struct hostent *hp;
+ struct addrinfo *top, *cur;
+ struct gai_afd *gai_afd;
+ int i, error = 0, h_error;
+ char *ap;
+
+ top = NULL;
+ sentinel.ai_next = NULL;
+ cur = &sentinel;
#ifdef ENABLE_IPV6
- if (af == AF_UNSPEC) {
- hp = getipnodebyname(hostname, AF_INET6,
- AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error);
- } else
- hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error);
+ if (af == AF_UNSPEC) {
+ hp = getipnodebyname(hostname, AF_INET6,
+ AI_ADDRCONFIG|AI_ALL|AI_V4MAPPED, &h_error);
+ } else
+ hp = getipnodebyname(hostname, af, AI_ADDRCONFIG, &h_error);
#else
- hp = gethostbyname(hostname);
- h_error = h_errno;
+ hp = gethostbyname(hostname);
+ h_error = h_errno;
#endif
- if (hp == NULL) {
- switch (h_error) {
- case HOST_NOT_FOUND:
- case NO_DATA:
- error = EAI_NODATA;
- break;
- case TRY_AGAIN:
- error = EAI_AGAIN;
- break;
- case NO_RECOVERY:
- default:
- error = EAI_FAIL;
- break;
- }
- goto free;
- }
-
- if ((hp->h_name == NULL) || (hp->h_name[0] == 0) ||
- (hp->h_addr_list[0] == NULL)) {
- error = EAI_FAIL;
- goto free;
- }
-
- for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) {
- switch (af) {
+ if (hp == NULL) {
+ switch (h_error) {
+ case HOST_NOT_FOUND:
+ case NO_DATA:
+ error = EAI_NODATA;
+ break;
+ case TRY_AGAIN:
+ error = EAI_AGAIN;
+ break;
+ case NO_RECOVERY:
+ default:
+ error = EAI_FAIL;
+ break;
+ }
+ goto free;
+ }
+
+ if ((hp->h_name == NULL) || (hp->h_name[0] == 0) ||
+ (hp->h_addr_list[0] == NULL)) {
+ error = EAI_FAIL;
+ goto free;
+ }
+
+ for (i = 0; (ap = hp->h_addr_list[i]) != NULL; i++) {
+ switch (af) {
#ifdef ENABLE_IPV6
- case AF_INET6:
- gai_afd = &gai_afdl[N_INET6];
- break;
+ case AF_INET6:
+ gai_afd = &gai_afdl[N_INET6];
+ break;
#endif
#ifndef ENABLE_IPV6
- default: /* AF_UNSPEC */
+ default: /* AF_UNSPEC */
#endif
- case AF_INET:
- gai_afd = &gai_afdl[N_INET];
- break;
+ case AF_INET:
+ gai_afd = &gai_afdl[N_INET];
+ break;
#ifdef ENABLE_IPV6
- default: /* AF_UNSPEC */
- if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
- ap += sizeof(struct in6_addr) -
- sizeof(struct in_addr);
- gai_afd = &gai_afdl[N_INET];
- } else
- gai_afd = &gai_afdl[N_INET6];
- break;
+ default: /* AF_UNSPEC */
+ if (IN6_IS_ADDR_V4MAPPED((struct in6_addr *)ap)) {
+ ap += sizeof(struct in6_addr) -
+ sizeof(struct in_addr);
+ gai_afd = &gai_afdl[N_INET];
+ } else
+ gai_afd = &gai_afdl[N_INET6];
+ break;
#endif
- }
+ }
#ifdef FAITH
- if (translate && gai_afd->a_af == AF_INET) {
- struct in6_addr *in6;
-
- GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port);
- in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr;
- memcpy(&in6->s6_addr32[0], &faith_prefix,
- sizeof(struct in6_addr) - sizeof(struct in_addr));
- memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr));
- } else
+ if (translate && gai_afd->a_af == AF_INET) {
+ struct in6_addr *in6;
+
+ GET_AI(cur->ai_next, &gai_afdl[N_INET6], ap, port);
+ in6 = &((struct sockaddr_in6 *)cur->ai_next->ai_addr)->sin6_addr;
+ memcpy(&in6->s6_addr32[0], &faith_prefix,
+ sizeof(struct in6_addr) - sizeof(struct in_addr));
+ memcpy(&in6->s6_addr32[3], ap, sizeof(struct in_addr));
+ } else
#endif /* FAITH */
- GET_AI(cur->ai_next, gai_afd, ap, port);
- if (cur == &sentinel) {
- top = cur->ai_next;
- GET_CANONNAME(top, hp->h_name);
- }
- cur = cur->ai_next;
- }
+ GET_AI(cur->ai_next, gai_afd, ap, port);
+ if (cur == &sentinel) {
+ top = cur->ai_next;
+ GET_CANONNAME(top, hp->h_name);
+ }
+ cur = cur->ai_next;
+ }
#ifdef ENABLE_IPV6
- freehostent(hp);
+ freehostent(hp);
#endif
- *res = top;
- return SUCCESS;
+ *res = top;
+ return SUCCESS;
free:
- if (top)
- freeaddrinfo(top);
+ if (top)
+ freeaddrinfo(top);
#ifdef ENABLE_IPV6
- if (hp)
- freehostent(hp);
+ if (hp)
+ freehostent(hp);
#endif
/* bad: */
- *res = NULL;
- return error;
+ *res = NULL;
+ return error;
}
diff --git a/Modules/getbuildinfo.c b/Modules/getbuildinfo.c
index f4bd14a..3bac1c5 100644
--- a/Modules/getbuildinfo.c
+++ b/Modules/getbuildinfo.c
@@ -31,22 +31,22 @@
const char *
Py_GetBuildInfo(void)
{
- static char buildinfo[50];
- const char *revision = Py_SubversionRevision();
- const char *sep = *revision ? ":" : "";
- const char *branch = Py_SubversionShortBranch();
- PyOS_snprintf(buildinfo, sizeof(buildinfo),
- "%s%s%s, %.20s, %.9s", branch, sep, revision,
- DATE, TIME);
- return buildinfo;
+ static char buildinfo[50];
+ const char *revision = Py_SubversionRevision();
+ const char *sep = *revision ? ":" : "";
+ const char *branch = Py_SubversionShortBranch();
+ PyOS_snprintf(buildinfo, sizeof(buildinfo),
+ "%s%s%s, %.20s, %.9s", branch, sep, revision,
+ DATE, TIME);
+ return buildinfo;
}
const char *
_Py_svnversion(void)
{
- /* the following string can be modified by subwcrev.exe */
- static const char svnversion[] = SVNVERSION;
- if (svnversion[0] != '$')
- return svnversion; /* it was interpolated, or passed on command line */
- return "Unversioned directory";
+ /* the following string can be modified by subwcrev.exe */
+ static const char svnversion[] = SVNVERSION;
+ if (svnversion[0] != '$')
+ return svnversion; /* it was interpolated, or passed on command line */
+ return "Unversioned directory";
}
diff --git a/Modules/getnameinfo.c b/Modules/getnameinfo.c
index d3c0ac5..7892ae9 100644
--- a/Modules/getnameinfo.c
+++ b/Modules/getnameinfo.c
@@ -1,7 +1,7 @@
/*
* Copyright (C) 1995, 1996, 1997, and 1998 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
@@ -53,162 +53,162 @@
#define NO 0
static struct gni_afd {
- int a_af;
- int a_addrlen;
- int a_socklen;
- int a_off;
+ int a_af;
+ int a_addrlen;
+ int a_socklen;
+ int a_off;
} gni_afdl [] = {
#ifdef ENABLE_IPV6
- {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
- offsetof(struct sockaddr_in6, sin6_addr)},
+ {PF_INET6, sizeof(struct in6_addr), sizeof(struct sockaddr_in6),
+ offsetof(struct sockaddr_in6, sin6_addr)},
#endif
- {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
- offsetof(struct sockaddr_in, sin_addr)},
- {0, 0, 0},
+ {PF_INET, sizeof(struct in_addr), sizeof(struct sockaddr_in),
+ offsetof(struct sockaddr_in, sin_addr)},
+ {0, 0, 0},
};
struct gni_sockinet {
- u_char si_len;
- u_char si_family;
- u_short si_port;
+ u_char si_len;
+ u_char si_family;
+ u_short si_port;
};
-#define ENI_NOSOCKET 0
-#define ENI_NOSERVNAME 1
-#define ENI_NOHOSTNAME 2
-#define ENI_MEMORY 3
-#define ENI_SYSTEM 4
-#define ENI_FAMILY 5
-#define ENI_SALEN 6
+#define ENI_NOSOCKET 0
+#define ENI_NOSERVNAME 1
+#define ENI_NOHOSTNAME 2
+#define ENI_MEMORY 3
+#define ENI_SYSTEM 4
+#define ENI_FAMILY 5
+#define ENI_SALEN 6
/* forward declaration to make gcc happy */
int getnameinfo Py_PROTO((const struct sockaddr *, size_t, char *, size_t,
- char *, size_t, int));
+ char *, size_t, int));
int
getnameinfo(sa, salen, host, hostlen, serv, servlen, flags)
- const struct sockaddr *sa;
- size_t salen;
- char *host;
- size_t hostlen;
- char *serv;
- size_t servlen;
- int flags;
+ const struct sockaddr *sa;
+ size_t salen;
+ char *host;
+ size_t hostlen;
+ char *serv;
+ size_t servlen;
+ int flags;
{
- struct gni_afd *gni_afd;
- struct servent *sp;
- struct hostent *hp;
- u_short port;
- int family, len, i;
- char *addr, *p;
- u_long v4a;
+ struct gni_afd *gni_afd;
+ struct servent *sp;
+ struct hostent *hp;
+ u_short port;
+ int family, len, i;
+ char *addr, *p;
+ u_long v4a;
#ifdef ENABLE_IPV6
- u_char pfx;
+ u_char pfx;
#endif
- int h_error;
- char numserv[512];
- char numaddr[512];
+ int h_error;
+ char numserv[512];
+ char numaddr[512];
- if (sa == NULL)
- return ENI_NOSOCKET;
+ if (sa == NULL)
+ return ENI_NOSOCKET;
#ifdef HAVE_SOCKADDR_SA_LEN
- len = sa->sa_len;
- if (len != salen) return ENI_SALEN;
+ len = sa->sa_len;
+ if (len != salen) return ENI_SALEN;
#else
- len = salen;
+ len = salen;
#endif
-
- family = sa->sa_family;
- for (i = 0; gni_afdl[i].a_af; i++)
- if (gni_afdl[i].a_af == family) {
- gni_afd = &gni_afdl[i];
- goto found;
- }
- return ENI_FAMILY;
-
+
+ family = sa->sa_family;
+ for (i = 0; gni_afdl[i].a_af; i++)
+ if (gni_afdl[i].a_af == family) {
+ gni_afd = &gni_afdl[i];
+ goto found;
+ }
+ return ENI_FAMILY;
+
found:
- if (len != gni_afd->a_socklen) return ENI_SALEN;
-
- port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */
- addr = (char *)sa + gni_afd->a_off;
-
- if (serv == NULL || servlen == 0) {
- /* what we should do? */
- } else if (flags & NI_NUMERICSERV) {
- sprintf(numserv, "%d", ntohs(port));
- if (strlen(numserv) > servlen)
- return ENI_MEMORY;
- strcpy(serv, numserv);
- } else {
- sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
- if (sp) {
- if (strlen(sp->s_name) > servlen)
- return ENI_MEMORY;
- strcpy(serv, sp->s_name);
- } else
- return ENI_NOSERVNAME;
- }
-
- switch (sa->sa_family) {
- case AF_INET:
- v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
- if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
- flags |= NI_NUMERICHOST;
- v4a >>= IN_CLASSA_NSHIFT;
- if (v4a == 0 || v4a == IN_LOOPBACKNET)
- flags |= NI_NUMERICHOST;
- break;
+ if (len != gni_afd->a_socklen) return ENI_SALEN;
+
+ port = ((struct gni_sockinet *)sa)->si_port; /* network byte order */
+ addr = (char *)sa + gni_afd->a_off;
+
+ if (serv == NULL || servlen == 0) {
+ /* what we should do? */
+ } else if (flags & NI_NUMERICSERV) {
+ sprintf(numserv, "%d", ntohs(port));
+ if (strlen(numserv) > servlen)
+ return ENI_MEMORY;
+ strcpy(serv, numserv);
+ } else {
+ sp = getservbyport(port, (flags & NI_DGRAM) ? "udp" : "tcp");
+ if (sp) {
+ if (strlen(sp->s_name) > servlen)
+ return ENI_MEMORY;
+ strcpy(serv, sp->s_name);
+ } else
+ return ENI_NOSERVNAME;
+ }
+
+ switch (sa->sa_family) {
+ case AF_INET:
+ v4a = ((struct sockaddr_in *)sa)->sin_addr.s_addr;
+ if (IN_MULTICAST(v4a) || IN_EXPERIMENTAL(v4a))
+ flags |= NI_NUMERICHOST;
+ v4a >>= IN_CLASSA_NSHIFT;
+ if (v4a == 0 || v4a == IN_LOOPBACKNET)
+ flags |= NI_NUMERICHOST;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
- if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
- flags |= NI_NUMERICHOST;
- break;
+ case AF_INET6:
+ pfx = ((struct sockaddr_in6 *)sa)->sin6_addr.s6_addr8[0];
+ if (pfx == 0 || pfx == 0xfe || pfx == 0xff)
+ flags |= NI_NUMERICHOST;
+ break;
#endif
- }
- if (host == NULL || hostlen == 0) {
- /* what should we do? */
- } else if (flags & NI_NUMERICHOST) {
- if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
- == NULL)
- return ENI_SYSTEM;
- if (strlen(numaddr) > hostlen)
- return ENI_MEMORY;
- strcpy(host, numaddr);
- } else {
+ }
+ if (host == NULL || hostlen == 0) {
+ /* what should we do? */
+ } else if (flags & NI_NUMERICHOST) {
+ if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
+ == NULL)
+ return ENI_SYSTEM;
+ if (strlen(numaddr) > hostlen)
+ return ENI_MEMORY;
+ strcpy(host, numaddr);
+ } else {
#ifdef ENABLE_IPV6
- hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error);
+ hp = getipnodebyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af, &h_error);
#else
- hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af);
- h_error = h_errno;
+ hp = gethostbyaddr(addr, gni_afd->a_addrlen, gni_afd->a_af);
+ h_error = h_errno;
#endif
- if (hp) {
- if (flags & NI_NOFQDN) {
- p = strchr(hp->h_name, '.');
- if (p) *p = '\0';
- }
- if (strlen(hp->h_name) > hostlen) {
+ if (hp) {
+ if (flags & NI_NOFQDN) {
+ p = strchr(hp->h_name, '.');
+ if (p) *p = '\0';
+ }
+ if (strlen(hp->h_name) > hostlen) {
#ifdef ENABLE_IPV6
- freehostent(hp);
+ freehostent(hp);
#endif
- return ENI_MEMORY;
- }
- strcpy(host, hp->h_name);
+ return ENI_MEMORY;
+ }
+ strcpy(host, hp->h_name);
#ifdef ENABLE_IPV6
- freehostent(hp);
+ freehostent(hp);
#endif
- } else {
- if (flags & NI_NAMEREQD)
- return ENI_NOHOSTNAME;
- if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
- == NULL)
- return ENI_NOHOSTNAME;
- if (strlen(numaddr) > hostlen)
- return ENI_MEMORY;
- strcpy(host, numaddr);
- }
- }
- return SUCCESS;
+ } else {
+ if (flags & NI_NAMEREQD)
+ return ENI_NOHOSTNAME;
+ if (inet_ntop(gni_afd->a_af, addr, numaddr, sizeof(numaddr))
+ == NULL)
+ return ENI_NOHOSTNAME;
+ if (strlen(numaddr) > hostlen)
+ return ENI_MEMORY;
+ strcpy(host, numaddr);
+ }
+ }
+ return SUCCESS;
}
diff --git a/Modules/getpath.c b/Modules/getpath.c
index 682ad3e..9653d3e 100644
--- a/Modules/getpath.c
+++ b/Modules/getpath.c
@@ -216,7 +216,7 @@ joinpath(char *buffer, char *stuff)
buffer[n++] = SEP;
}
if (n > MAXPATHLEN)
- Py_FatalError("buffer overflow in getpath.c's joinpath()");
+ Py_FatalError("buffer overflow in getpath.c's joinpath()");
k = strlen(stuff);
if (n + k > MAXPATHLEN)
k = MAXPATHLEN - n;
@@ -393,13 +393,13 @@ calculate_path(void)
#endif
#endif
- /* If there is no slash in the argv0 path, then we have to
- * assume python is on the user's $PATH, since there's no
- * other way to find a directory to start the search from. If
- * $PATH isn't exported, you lose.
- */
- if (strchr(prog, SEP))
- strncpy(progpath, prog, MAXPATHLEN);
+ /* If there is no slash in the argv0 path, then we have to
+ * assume python is on the user's $PATH, since there's no
+ * other way to find a directory to start the search from. If
+ * $PATH isn't exported, you lose.
+ */
+ if (strchr(prog, SEP))
+ strncpy(progpath, prog, MAXPATHLEN);
#ifdef __APPLE__
/* On Mac OS X, if a script uses an interpreter of the form
* "#!/opt/python2.3/bin/python", the kernel only passes "python"
@@ -414,44 +414,44 @@ calculate_path(void)
else if(0 == _NSGetExecutablePath(progpath, &nsexeclength) && progpath[0] == SEP)
;
#endif /* __APPLE__ */
- else if (path) {
- while (1) {
- char *delim = strchr(path, DELIM);
-
- if (delim) {
- size_t len = delim - path;
- if (len > MAXPATHLEN)
- len = MAXPATHLEN;
- strncpy(progpath, path, len);
- *(progpath + len) = '\0';
- }
- else
- strncpy(progpath, path, MAXPATHLEN);
-
- joinpath(progpath, prog);
- if (isxfile(progpath))
- break;
-
- if (!delim) {
- progpath[0] = '\0';
- break;
- }
- path = delim + 1;
- }
- }
- else
- progpath[0] = '\0';
- if (progpath[0] != SEP && progpath[0] != '\0')
- absolutize(progpath);
- strncpy(argv0_path, progpath, MAXPATHLEN);
- argv0_path[MAXPATHLEN] = '\0';
+ else if (path) {
+ while (1) {
+ char *delim = strchr(path, DELIM);
+
+ if (delim) {
+ size_t len = delim - path;
+ if (len > MAXPATHLEN)
+ len = MAXPATHLEN;
+ strncpy(progpath, path, len);
+ *(progpath + len) = '\0';
+ }
+ else
+ strncpy(progpath, path, MAXPATHLEN);
+
+ joinpath(progpath, prog);
+ if (isxfile(progpath))
+ break;
+
+ if (!delim) {
+ progpath[0] = '\0';
+ break;
+ }
+ path = delim + 1;
+ }
+ }
+ else
+ progpath[0] = '\0';
+ if (progpath[0] != SEP && progpath[0] != '\0')
+ absolutize(progpath);
+ strncpy(argv0_path, progpath, MAXPATHLEN);
+ argv0_path[MAXPATHLEN] = '\0';
#ifdef WITH_NEXT_FRAMEWORK
- /* On Mac OS X we have a special case if we're running from a framework.
- ** This is because the python home should be set relative to the library,
- ** which is in the framework, not relative to the executable, which may
- ** be outside of the framework. Except when we're in the build directory...
- */
+ /* On Mac OS X we have a special case if we're running from a framework.
+ ** This is because the python home should be set relative to the library,
+ ** which is in the framework, not relative to the executable, which may
+ ** be outside of the framework. Except when we're in the build directory...
+ */
pythonModule = NSModuleForSymbol(NSLookupAndBindSymbol("_Py_Initialize"));
/* Use dylib functions to find out where the framework was loaded from */
buf = (char *)NSLibraryNameForModule(pythonModule);
@@ -525,7 +525,7 @@ calculate_path(void)
else
strncpy(zip_path, PREFIX, MAXPATHLEN);
joinpath(zip_path, "lib/python00.zip");
- bufsz = strlen(zip_path); /* Replace "00" with version */
+ bufsz = strlen(zip_path); /* Replace "00" with version */
zip_path[bufsz - 6] = VERSION[0];
zip_path[bufsz - 5] = VERSION[2];
@@ -633,10 +633,10 @@ calculate_path(void)
if (pfound > 0) {
reduce(prefix);
reduce(prefix);
- /* The prefix is the root directory, but reduce() chopped
- * off the "/". */
- if (!prefix[0])
- strcpy(prefix, separator);
+ /* The prefix is the root directory, but reduce() chopped
+ * off the "/". */
+ if (!prefix[0])
+ strcpy(prefix, separator);
}
else
strncpy(prefix, PREFIX, MAXPATHLEN);
@@ -645,8 +645,8 @@ calculate_path(void)
reduce(exec_prefix);
reduce(exec_prefix);
reduce(exec_prefix);
- if (!exec_prefix[0])
- strcpy(exec_prefix, separator);
+ if (!exec_prefix[0])
+ strcpy(exec_prefix, separator);
}
else
strncpy(exec_prefix, EXEC_PREFIX, MAXPATHLEN);
diff --git a/Modules/glmodule.c b/Modules/glmodule.c
index 01db9fc..b9c64fb 100644
--- a/Modules/glmodule.c
+++ b/Modules/glmodule.c
@@ -10,26 +10,26 @@ Each definition must be contained on one line:
<returntype> can be: void, short, long (XXX maybe others?)
<type> can be: char, string, short, float, long, or double
- string indicates a null terminated string;
- if <type> is char and <arg> begins with a *, the * is stripped
- and <type> is changed into string
+ string indicates a null terminated string;
+ if <type> is char and <arg> begins with a *, the * is stripped
+ and <type> is changed into string
<arg> has the form <mode> or <mode>[<subscript>]
- where <mode> can be
- s: arg is sent
- r: arg is received (arg is a pointer)
- and <subscript> can be (N and I are numbers):
- N
- argI
- retval
- N*argI
- N*I
- N*retval
- In the case where the subscript consists of two parts
- separated by *, the first part is the width of the matrix, and
- the second part is the length of the matrix. This order is
- opposite from the order used in C to declare a two-dimensional
- matrix.
+ where <mode> can be
+ s: arg is sent
+ r: arg is received (arg is a pointer)
+ and <subscript> can be (N and I are numbers):
+ N
+ argI
+ retval
+ N*argI
+ N*I
+ N*retval
+ In the case where the subscript consists of two parts
+ separated by *, the first part is the width of the matrix, and
+ the second part is the length of the matrix. This order is
+ opposite from the order used in C to declare a two-dimensional
+ matrix.
*/
/*
@@ -62,17 +62,17 @@ generator can include it in the table of functions.
static PyObject *
gl_qread(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- Py_BEGIN_ALLOW_THREADS
- retval = qread( & arg1 );
- Py_END_ALLOW_THREADS
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewlongobject(retval));
- PyTuple_SetItem(v, 1, mknewshortobject(arg1));
- return v;
- }
+ long retval;
+ short arg1 ;
+ Py_BEGIN_ALLOW_THREADS
+ retval = qread( & arg1 );
+ Py_END_ALLOW_THREADS
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewlongobject(retval));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg1));
+ return v;
+ }
}
@@ -91,64 +91,64 @@ and for each point v3d() is called.
static PyObject *
gl_varray(PyObject *self, PyObject *args)
{
- PyObject *v, *w=NULL;
- int i, n, width;
- double vec[3];
- PyObject * (*getitem)(PyObject *, int);
-
- if (!PyArg_GetObject(args, 1, 0, &v))
- return NULL;
-
- if (PyList_Check(v)) {
- n = PyList_Size(v);
- getitem = PyList_GetItem;
- }
- else if (PyTuple_Check(v)) {
- n = PyTuple_Size(v);
- getitem = PyTuple_GetItem;
- }
- else {
- PyErr_BadArgument();
- return NULL;
- }
-
- if (n == 0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (n > 0)
- w = (*getitem)(v, 0);
-
- width = 0;
- if (w == NULL) {
- }
- else if (PyList_Check(w)) {
- width = PyList_Size(w);
- }
- else if (PyTuple_Check(w)) {
- width = PyTuple_Size(w);
- }
-
- switch (width) {
- case 2:
- vec[2] = 0.0;
- /* Fall through */
- case 3:
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- for (i = 0; i < n; i++) {
- w = (*getitem)(v, i);
- if (!PyArg_GetDoubleArray(w, 1, 0, width, vec))
- return NULL;
- v3d(vec);
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v, *w=NULL;
+ int i, n, width;
+ double vec[3];
+ PyObject * (*getitem)(PyObject *, int);
+
+ if (!PyArg_GetObject(args, 1, 0, &v))
+ return NULL;
+
+ if (PyList_Check(v)) {
+ n = PyList_Size(v);
+ getitem = PyList_GetItem;
+ }
+ else if (PyTuple_Check(v)) {
+ n = PyTuple_Size(v);
+ getitem = PyTuple_GetItem;
+ }
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ if (n == 0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (n > 0)
+ w = (*getitem)(v, 0);
+
+ width = 0;
+ if (w == NULL) {
+ }
+ else if (PyList_Check(w)) {
+ width = PyList_Size(w);
+ }
+ else if (PyTuple_Check(w)) {
+ width = PyTuple_Size(w);
+ }
+
+ switch (width) {
+ case 2:
+ vec[2] = 0.0;
+ /* Fall through */
+ case 3:
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ for (i = 0; i < n; i++) {
+ w = (*getitem)(v, i);
+ if (!PyArg_GetDoubleArray(w, 1, 0, width, vec))
+ return NULL;
+ v3d(vec);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/*
@@ -170,14 +170,14 @@ static PyObject *gen_nvarray(); /* Forward */
static PyObject *
gl_nvarray(PyObject *self, PyObject *args)
{
- return gen_nvarray(args, 0);
+ return gen_nvarray(args, 0);
}
static PyObject *
gl_vnarray(PyObject *self, PyObject *args)
{
- return gen_nvarray(args, 1);
+ return gen_nvarray(args, 1);
}
/* Generic, internal version of {nv,nv}array: inorm indicates the
@@ -186,44 +186,44 @@ gl_vnarray(PyObject *self, PyObject *args)
static PyObject *
gen_nvarray(PyObject *args, int inorm)
{
- PyObject *v, *w, *wnorm, *wvec;
- int i, n;
- float norm[3], vec[3];
- PyObject * (*getitem)(PyObject *, int);
-
- if (!PyArg_GetObject(args, 1, 0, &v))
- return NULL;
-
- if (PyList_Check(v)) {
- n = PyList_Size(v);
- getitem = PyList_GetItem;
- }
- else if (PyTuple_Check(v)) {
- n = PyTuple_Size(v);
- getitem = PyTuple_GetItem;
- }
- else {
- PyErr_BadArgument();
- return NULL;
- }
-
- for (i = 0; i < n; i++) {
- w = (*getitem)(v, i);
- if (!PyTuple_Check(w) || PyTuple_Size(w) != 2) {
- PyErr_BadArgument();
- return NULL;
- }
- wnorm = PyTuple_GetItem(w, inorm);
- wvec = PyTuple_GetItem(w, 1 - inorm);
- if (!PyArg_GetFloatArray(wnorm, 1, 0, 3, norm) ||
- !PyArg_GetFloatArray(wvec, 1, 0, 3, vec))
- return NULL;
- n3f(norm);
- v3f(vec);
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v, *w, *wnorm, *wvec;
+ int i, n;
+ float norm[3], vec[3];
+ PyObject * (*getitem)(PyObject *, int);
+
+ if (!PyArg_GetObject(args, 1, 0, &v))
+ return NULL;
+
+ if (PyList_Check(v)) {
+ n = PyList_Size(v);
+ getitem = PyList_GetItem;
+ }
+ else if (PyTuple_Check(v)) {
+ n = PyTuple_Size(v);
+ getitem = PyTuple_GetItem;
+ }
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ for (i = 0; i < n; i++) {
+ w = (*getitem)(v, i);
+ if (!PyTuple_Check(w) || PyTuple_Size(w) != 2) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ wnorm = PyTuple_GetItem(w, inorm);
+ wvec = PyTuple_GetItem(w, 1 - inorm);
+ if (!PyArg_GetFloatArray(wnorm, 1, 0, 3, norm) ||
+ !PyArg_GetFloatArray(wvec, 1, 0, 3, vec))
+ return NULL;
+ n3f(norm);
+ v3f(vec);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* nurbssurface(s_knots[], t_knots[], ctl[][], s_order, t_order, type).
@@ -235,83 +235,83 @@ gen_nvarray(PyObject *args, int inorm)
static PyObject *
gl_nurbssurface(PyObject *self, PyObject *args)
{
- long arg1 ;
- double * arg2 ;
- long arg3 ;
- double * arg4 ;
- double *arg5 ;
- long arg6 ;
- long arg7 ;
- long arg8 ;
- long ncoords;
- long s_byte_stride, t_byte_stride;
- long s_nctl, t_nctl;
- long s, t;
- PyObject *v, *w, *pt;
- double *pnext;
- if (!PyArg_GetLongArraySize(args, 6, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
- return PyErr_NoMemory();
- }
- if (!PyArg_GetDoubleArray(args, 6, 0, arg1 , arg2))
- return NULL;
- if (!PyArg_GetLongArraySize(args, 6, 1, &arg3))
- return NULL;
- if ((arg4 = PyMem_NEW(double, arg3 )) == NULL) {
- return PyErr_NoMemory();
- }
- if (!PyArg_GetDoubleArray(args, 6, 1, arg3 , arg4))
- return NULL;
- if (!PyArg_GetLong(args, 6, 3, &arg6))
- return NULL;
- if (!PyArg_GetLong(args, 6, 4, &arg7))
- return NULL;
- if (!PyArg_GetLong(args, 6, 5, &arg8))
- return NULL;
- if (arg8 == N_XYZ)
- ncoords = 3;
- else if (arg8 == N_XYZW)
- ncoords = 4;
- else {
- PyErr_BadArgument();
- return NULL;
- }
- s_nctl = arg1 - arg6;
- t_nctl = arg3 - arg7;
- if (!PyArg_GetObject(args, 6, 2, &v))
- return NULL;
- if (!PyList_Check(v) || PyList_Size(v) != s_nctl) {
- PyErr_BadArgument();
- return NULL;
- }
- if ((arg5 = PyMem_NEW(double, s_nctl*t_nctl*ncoords )) == NULL) {
- return PyErr_NoMemory();
- }
- pnext = arg5;
- for (s = 0; s < s_nctl; s++) {
- w = PyList_GetItem(v, s);
- if (w == NULL || !PyList_Check(w) ||
- PyList_Size(w) != t_nctl) {
- PyErr_BadArgument();
- return NULL;
- }
- for (t = 0; t < t_nctl; t++) {
- pt = PyList_GetItem(w, t);
- if (!PyArg_GetDoubleArray(pt, 1, 0, ncoords, pnext))
- return NULL;
- pnext += ncoords;
- }
- }
- s_byte_stride = sizeof(double) * ncoords;
- t_byte_stride = s_byte_stride * s_nctl;
- nurbssurface( arg1 , arg2 , arg3 , arg4 ,
- s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg4);
- PyMem_DEL(arg5);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ double * arg2 ;
+ long arg3 ;
+ double * arg4 ;
+ double *arg5 ;
+ long arg6 ;
+ long arg7 ;
+ long arg8 ;
+ long ncoords;
+ long s_byte_stride, t_byte_stride;
+ long s_nctl, t_nctl;
+ long s, t;
+ PyObject *v, *w, *pt;
+ double *pnext;
+ if (!PyArg_GetLongArraySize(args, 6, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ if (!PyArg_GetDoubleArray(args, 6, 0, arg1 , arg2))
+ return NULL;
+ if (!PyArg_GetLongArraySize(args, 6, 1, &arg3))
+ return NULL;
+ if ((arg4 = PyMem_NEW(double, arg3 )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ if (!PyArg_GetDoubleArray(args, 6, 1, arg3 , arg4))
+ return NULL;
+ if (!PyArg_GetLong(args, 6, 3, &arg6))
+ return NULL;
+ if (!PyArg_GetLong(args, 6, 4, &arg7))
+ return NULL;
+ if (!PyArg_GetLong(args, 6, 5, &arg8))
+ return NULL;
+ if (arg8 == N_XYZ)
+ ncoords = 3;
+ else if (arg8 == N_XYZW)
+ ncoords = 4;
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ s_nctl = arg1 - arg6;
+ t_nctl = arg3 - arg7;
+ if (!PyArg_GetObject(args, 6, 2, &v))
+ return NULL;
+ if (!PyList_Check(v) || PyList_Size(v) != s_nctl) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ((arg5 = PyMem_NEW(double, s_nctl*t_nctl*ncoords )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ pnext = arg5;
+ for (s = 0; s < s_nctl; s++) {
+ w = PyList_GetItem(v, s);
+ if (w == NULL || !PyList_Check(w) ||
+ PyList_Size(w) != t_nctl) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ for (t = 0; t < t_nctl; t++) {
+ pt = PyList_GetItem(w, t);
+ if (!PyArg_GetDoubleArray(pt, 1, 0, ncoords, pnext))
+ return NULL;
+ pnext += ncoords;
+ }
+ }
+ s_byte_stride = sizeof(double) * ncoords;
+ t_byte_stride = s_byte_stride * s_nctl;
+ nurbssurface( arg1 , arg2 , arg3 , arg4 ,
+ s_byte_stride , t_byte_stride , arg5 , arg6 , arg7 , arg8 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg4);
+ PyMem_DEL(arg5);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* nurbscurve(knots, ctlpoints, order, type).
@@ -321,57 +321,57 @@ gl_nurbssurface(PyObject *self, PyObject *args)
static PyObject *
gl_nurbscurve(PyObject *self, PyObject *args)
{
- long arg1 ;
- double * arg2 ;
- long arg3 ;
- double * arg4 ;
- long arg5 ;
- long arg6 ;
- int ncoords, npoints;
- int i;
- PyObject *v;
- double *pnext;
- if (!PyArg_GetLongArraySize(args, 4, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
- return PyErr_NoMemory();
- }
- if (!PyArg_GetDoubleArray(args, 4, 0, arg1 , arg2))
- return NULL;
- if (!PyArg_GetLong(args, 4, 2, &arg5))
- return NULL;
- if (!PyArg_GetLong(args, 4, 3, &arg6))
- return NULL;
- if (arg6 == N_ST)
- ncoords = 2;
- else if (arg6 == N_STW)
- ncoords = 3;
- else {
- PyErr_BadArgument();
- return NULL;
- }
- npoints = arg1 - arg5;
- if (!PyArg_GetObject(args, 4, 1, &v))
- return NULL;
- if (!PyList_Check(v) || PyList_Size(v) != npoints) {
- PyErr_BadArgument();
- return NULL;
- }
- if ((arg4 = PyMem_NEW(double, npoints*ncoords )) == NULL) {
- return PyErr_NoMemory();
- }
- pnext = arg4;
- for (i = 0; i < npoints; i++) {
- if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
- return NULL;
- pnext += ncoords;
- }
- arg3 = (sizeof(double)) * ncoords;
- nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg4);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ double * arg2 ;
+ long arg3 ;
+ double * arg4 ;
+ long arg5 ;
+ long arg6 ;
+ int ncoords, npoints;
+ int i;
+ PyObject *v;
+ double *pnext;
+ if (!PyArg_GetLongArraySize(args, 4, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(double, arg1 )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ if (!PyArg_GetDoubleArray(args, 4, 0, arg1 , arg2))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 2, &arg5))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 3, &arg6))
+ return NULL;
+ if (arg6 == N_ST)
+ ncoords = 2;
+ else if (arg6 == N_STW)
+ ncoords = 3;
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ npoints = arg1 - arg5;
+ if (!PyArg_GetObject(args, 4, 1, &v))
+ return NULL;
+ if (!PyList_Check(v) || PyList_Size(v) != npoints) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ((arg4 = PyMem_NEW(double, npoints*ncoords )) == NULL) {
+ return PyErr_NoMemory();
+ }
+ pnext = arg4;
+ for (i = 0; i < npoints; i++) {
+ if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
+ return NULL;
+ pnext += ncoords;
+ }
+ arg3 = (sizeof(double)) * ncoords;
+ nurbscurve( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg4);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* pwlcurve(points, type).
@@ -381,39 +381,39 @@ gl_nurbscurve(PyObject *self, PyObject *args)
static PyObject *
gl_pwlcurve(PyObject *self, PyObject *args)
{
- PyObject *v;
- long type;
- double *data, *pnext;
- long npoints, ncoords;
- int i;
- if (!PyArg_GetObject(args, 2, 0, &v))
- return NULL;
- if (!PyArg_GetLong(args, 2, 1, &type))
- return NULL;
- if (!PyList_Check(v)) {
- PyErr_BadArgument();
- return NULL;
- }
- npoints = PyList_Size(v);
- if (type == N_ST)
- ncoords = 2;
- else {
- PyErr_BadArgument();
- return NULL;
- }
- if ((data = PyMem_NEW(double, npoints*ncoords)) == NULL) {
- return PyErr_NoMemory();
- }
- pnext = data;
- for (i = 0; i < npoints; i++) {
- if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
- return NULL;
- pnext += ncoords;
- }
- pwlcurve(npoints, data, sizeof(double)*ncoords, type);
- PyMem_DEL(data);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v;
+ long type;
+ double *data, *pnext;
+ long npoints, ncoords;
+ int i;
+ if (!PyArg_GetObject(args, 2, 0, &v))
+ return NULL;
+ if (!PyArg_GetLong(args, 2, 1, &type))
+ return NULL;
+ if (!PyList_Check(v)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ npoints = PyList_Size(v);
+ if (type == N_ST)
+ ncoords = 2;
+ else {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ((data = PyMem_NEW(double, npoints*ncoords)) == NULL) {
+ return PyErr_NoMemory();
+ }
+ pnext = data;
+ for (i = 0; i < npoints; i++) {
+ if (!PyArg_GetDoubleArray(PyList_GetItem(v, i), 1, 0, ncoords, pnext))
+ return NULL;
+ pnext += ncoords;
+ }
+ pwlcurve(npoints, data, sizeof(double)*ncoords, type);
+ PyMem_DEL(data);
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -425,56 +425,56 @@ static long pickbuffersize;
static PyObject *
pick_select(PyObject *args, void (*func)())
{
- if (!PyArg_GetLong(args, 1, 0, &pickbuffersize))
- return NULL;
- if (pickbuffer != NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "pick/gselect: already picking/selecting");
- return NULL;
- }
- if ((pickbuffer = PyMem_NEW(short, pickbuffersize)) == NULL) {
- return PyErr_NoMemory();
- }
- (*func)(pickbuffer, pickbuffersize);
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_GetLong(args, 1, 0, &pickbuffersize))
+ return NULL;
+ if (pickbuffer != NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "pick/gselect: already picking/selecting");
+ return NULL;
+ }
+ if ((pickbuffer = PyMem_NEW(short, pickbuffersize)) == NULL) {
+ return PyErr_NoMemory();
+ }
+ (*func)(pickbuffer, pickbuffersize);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
endpick_select(long (*func)())
{
- PyObject *v, *w;
- int i, nhits, n;
- if (pickbuffer == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "endpick/endselect: not in pick/select mode");
- return NULL;
- }
- nhits = (*func)(pickbuffer);
- if (nhits < 0) {
- nhits = -nhits; /* How to report buffer overflow otherwise? */
- }
- /* Scan the buffer to see how many integers */
- n = 0;
- for (; nhits > 0; nhits--) {
- n += 1 + pickbuffer[n];
- }
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- /* XXX Could do it nicer and interpret the data structure here,
- returning a list of lists. But this can be done in Python... */
- for (i = 0; i < n; i++) {
- w = PyInt_FromLong((long)pickbuffer[i]);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i, w);
- }
- PyMem_DEL(pickbuffer);
- pickbuffer = NULL;
- return v;
+ PyObject *v, *w;
+ int i, nhits, n;
+ if (pickbuffer == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "endpick/endselect: not in pick/select mode");
+ return NULL;
+ }
+ nhits = (*func)(pickbuffer);
+ if (nhits < 0) {
+ nhits = -nhits; /* How to report buffer overflow otherwise? */
+ }
+ /* Scan the buffer to see how many integers */
+ n = 0;
+ for (; nhits > 0; nhits--) {
+ n += 1 + pickbuffer[n];
+ }
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ /* XXX Could do it nicer and interpret the data structure here,
+ returning a list of lists. But this can be done in Python... */
+ for (i = 0; i < n; i++) {
+ w = PyInt_FromLong((long)pickbuffer[i]);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i, w);
+ }
+ PyMem_DEL(pickbuffer);
+ pickbuffer = NULL;
+ return v;
}
extern void pick(), gselect();
@@ -482,22 +482,22 @@ extern long endpick(), endselect();
static PyObject *gl_pick(PyObject *self, PyObject *args)
{
- return pick_select(args, pick);
+ return pick_select(args, pick);
}
static PyObject *gl_endpick(PyObject *self)
{
- return endpick_select(endpick);
+ return endpick_select(endpick);
}
static PyObject *gl_gselect(PyObject *self, PyObject *args)
{
- return pick_select(args, gselect);
+ return pick_select(args, gselect);
}
static PyObject *gl_endselect(PyObject *self)
{
- return endpick_select(endselect);
+ return endpick_select(endselect);
}
@@ -509,23 +509,23 @@ static PyObject *gl_endselect(PyObject *self)
static PyObject *
gl_getmatrix(PyObject *self, PyObject *args)
{
- Matrix arg1;
- PyObject *v, *w;
- int i, j;
- getmatrix( arg1 );
- v = PyList_New(16);
- if (v == NULL) {
- return PyErr_NoMemory();
- }
- for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
- w = mknewfloatobject(arg1[i][j]);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i*4+j, w);
- }
- return v;
+ Matrix arg1;
+ PyObject *v, *w;
+ int i, j;
+ getmatrix( arg1 );
+ v = PyList_New(16);
+ if (v == NULL) {
+ return PyErr_NoMemory();
+ }
+ for (i = 0; i < 4; i++) for (j = 0; j < 4; j++) {
+ w = mknewfloatobject(arg1[i][j]);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i*4+j, w);
+ }
+ return v;
}
/* Here's an alternate version that returns a 4x4 matrix instead of
@@ -536,137 +536,137 @@ gl_getmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_altgetmatrix(PyObject *self, PyObject *args)
{
- Matrix arg1;
- PyObject *v, *w;
- int i, j;
- getmatrix( arg1 );
- v = PyList_New(4);
- if (v == NULL) {
- return NULL;
- }
- for (i = 0; i < 4; i++) {
- w = PyList_New(4);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i, w);
- }
- for (i = 0; i < 4; i++) {
- for (j = 0; j < 4; j++) {
- w = mknewfloatobject(arg1[i][j]);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(PyList_GetItem(v, i), j, w);
- }
- }
- return v;
+ Matrix arg1;
+ PyObject *v, *w;
+ int i, j;
+ getmatrix( arg1 );
+ v = PyList_New(4);
+ if (v == NULL) {
+ return NULL;
+ }
+ for (i = 0; i < 4; i++) {
+ w = PyList_New(4);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i, w);
+ }
+ for (i = 0; i < 4; i++) {
+ for (j = 0; j < 4; j++) {
+ w = mknewfloatobject(arg1[i][j]);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(PyList_GetItem(v, i), j, w);
+ }
+ }
+ return v;
}
static PyObject *
gl_lrectwrite(PyObject *self, PyObject *args)
{
- short x1 ;
- short y1 ;
- short x2 ;
- short y2 ;
- string parray ;
- PyObject *s;
+ short x1 ;
+ short y1 ;
+ short x2 ;
+ short y2 ;
+ string parray ;
+ PyObject *s;
#if 0
- int pixcount;
+ int pixcount;
#endif
- if (!PyArg_GetShort(args, 5, 0, &x1))
- return NULL;
- if (!PyArg_GetShort(args, 5, 1, &y1))
- return NULL;
- if (!PyArg_GetShort(args, 5, 2, &x2))
- return NULL;
- if (!PyArg_GetShort(args, 5, 3, &y2))
- return NULL;
- if (!PyArg_GetString(args, 5, 4, &parray))
- return NULL;
- if (!PyArg_GetObject(args, 5, 4, &s))
- return NULL;
+ if (!PyArg_GetShort(args, 5, 0, &x1))
+ return NULL;
+ if (!PyArg_GetShort(args, 5, 1, &y1))
+ return NULL;
+ if (!PyArg_GetShort(args, 5, 2, &x2))
+ return NULL;
+ if (!PyArg_GetShort(args, 5, 3, &y2))
+ return NULL;
+ if (!PyArg_GetString(args, 5, 4, &parray))
+ return NULL;
+ if (!PyArg_GetObject(args, 5, 4, &s))
+ return NULL;
#if 0
/* Don't check this, it breaks experiments with pixmode(PM_SIZE, ...) */
- pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
- if (!PyString_Check(s) || PyString_Size(s) != pixcount*sizeof(long)) {
- PyErr_SetString(PyExc_RuntimeError,
- "string arg to lrectwrite has wrong size");
- return NULL;
- }
+ pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
+ if (!PyString_Check(s) || PyString_Size(s) != pixcount*sizeof(long)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "string arg to lrectwrite has wrong size");
+ return NULL;
+ }
#endif
- lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray );
- Py_INCREF(Py_None);
- return Py_None;
+ lrectwrite( x1 , y1 , x2 , y2 , (unsigned long *) parray );
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
gl_lrectread(PyObject *self, PyObject *args)
{
- short x1 ;
- short y1 ;
- short x2 ;
- short y2 ;
- PyObject *parray;
- int pixcount;
- if (!PyArg_GetShort(args, 4, 0, &x1))
- return NULL;
- if (!PyArg_GetShort(args, 4, 1, &y1))
- return NULL;
- if (!PyArg_GetShort(args, 4, 2, &x2))
- return NULL;
- if (!PyArg_GetShort(args, 4, 3, &y2))
- return NULL;
- pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
- parray = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
- if (parray == NULL)
- return NULL; /* No memory */
- lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
- return parray;
+ short x1 ;
+ short y1 ;
+ short x2 ;
+ short y2 ;
+ PyObject *parray;
+ int pixcount;
+ if (!PyArg_GetShort(args, 4, 0, &x1))
+ return NULL;
+ if (!PyArg_GetShort(args, 4, 1, &y1))
+ return NULL;
+ if (!PyArg_GetShort(args, 4, 2, &x2))
+ return NULL;
+ if (!PyArg_GetShort(args, 4, 3, &y2))
+ return NULL;
+ pixcount = (long)(x2+1-x1) * (long)(y2+1-y1);
+ parray = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
+ if (parray == NULL)
+ return NULL; /* No memory */
+ lrectread(x1, y1, x2, y2, (unsigned long *) PyString_AsString(parray));
+ return parray;
}
static PyObject *
gl_readdisplay(PyObject *self, PyObject *args)
{
- short x1, y1, x2, y2;
- unsigned long *parray, hints;
- long size, size_ret;
- PyObject *rv;
-
- if ( !PyArg_Parse(args, "hhhhl", &x1, &y1, &x2, &y2, &hints) )
- return 0;
- size = (long)(x2+1-x1) * (long)(y2+1-y1);
- rv = PyString_FromStringAndSize((char *)NULL, size*sizeof(long));
- if ( rv == NULL )
- return NULL;
- parray = (unsigned long *)PyString_AsString(rv);
- size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
- if ( size_ret != size ) {
- printf("gl_readdisplay: got %ld pixels, expected %ld\n",
- size_ret, size);
- PyErr_SetString(PyExc_RuntimeError, "readdisplay returned unexpected length");
- return NULL;
- }
- return rv;
+ short x1, y1, x2, y2;
+ unsigned long *parray, hints;
+ long size, size_ret;
+ PyObject *rv;
+
+ if ( !PyArg_Parse(args, "hhhhl", &x1, &y1, &x2, &y2, &hints) )
+ return 0;
+ size = (long)(x2+1-x1) * (long)(y2+1-y1);
+ rv = PyString_FromStringAndSize((char *)NULL, size*sizeof(long));
+ if ( rv == NULL )
+ return NULL;
+ parray = (unsigned long *)PyString_AsString(rv);
+ size_ret = readdisplay(x1, y1, x2, y2, parray, hints);
+ if ( size_ret != size ) {
+ printf("gl_readdisplay: got %ld pixels, expected %ld\n",
+ size_ret, size);
+ PyErr_SetString(PyExc_RuntimeError, "readdisplay returned unexpected length");
+ return NULL;
+ }
+ return rv;
}
/* Desperately needed, here are tools to compress and decompress
the data manipulated by lrectread/lrectwrite.
gl.packrect(width, height, packfactor, bigdata) --> smalldata
- makes 'bigdata' 4*(packfactor**2) times smaller by:
- - turning it into B/W (a factor 4)
- - replacing squares of size pacfactor by one
- representative
+ makes 'bigdata' 4*(packfactor**2) times smaller by:
+ - turning it into B/W (a factor 4)
+ - replacing squares of size pacfactor by one
+ representative
gl.unpackrect(width, height, packfactor, smalldata) --> bigdata
- is the inverse; the numeric arguments must be *the same*.
+ is the inverse; the numeric arguments must be *the same*.
Both work best if width and height are multiples of packfactor
(in fact unpackrect will leave garbage bytes).
@@ -676,50 +676,50 @@ gl_readdisplay(PyObject *self, PyObject *args)
static PyObject *
gl_packrect(PyObject *self, PyObject *args)
{
- long width, height, packfactor;
- char *s;
- PyObject *unpacked, *packed;
- int pixcount, packedcount, x, y, r, g, b;
- unsigned long pixel;
- unsigned char *p;
- unsigned long *parray;
- if (!PyArg_GetLong(args, 4, 0, &width))
- return NULL;
- if (!PyArg_GetLong(args, 4, 1, &height))
- return NULL;
- if (!PyArg_GetLong(args, 4, 2, &packfactor))
- return NULL;
- if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
- return NULL;
- if (!PyArg_GetObject(args, 4, 3, &unpacked))
- return NULL;
- if (width <= 0 || height <= 0 || packfactor <= 0) {
- PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
- return NULL;
- }
- pixcount = width*height;
- packedcount = ((width+packfactor-1)/packfactor) *
- ((height+packfactor-1)/packfactor);
- if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
- PyErr_SetString(PyExc_RuntimeError,
- "string arg to packrect has wrong size");
- return NULL;
- }
- packed = PyString_FromStringAndSize((char *)NULL, packedcount);
- if (packed == NULL)
- return NULL;
- parray = (unsigned long *) PyString_AsString(unpacked);
- p = (unsigned char *) PyString_AsString(packed);
- for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
- for (x = 0; x < width; x += packfactor) {
- pixel = parray[x];
- r = pixel & 0xff;
- g = (pixel >> 8) & 0xff;
- b = (pixel >> 16) & 0xff;
- *p++ = (30*r+59*g+11*b) / 100;
- }
- }
- return packed;
+ long width, height, packfactor;
+ char *s;
+ PyObject *unpacked, *packed;
+ int pixcount, packedcount, x, y, r, g, b;
+ unsigned long pixel;
+ unsigned char *p;
+ unsigned long *parray;
+ if (!PyArg_GetLong(args, 4, 0, &width))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 1, &height))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 2, &packfactor))
+ return NULL;
+ if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
+ return NULL;
+ if (!PyArg_GetObject(args, 4, 3, &unpacked))
+ return NULL;
+ if (width <= 0 || height <= 0 || packfactor <= 0) {
+ PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
+ return NULL;
+ }
+ pixcount = width*height;
+ packedcount = ((width+packfactor-1)/packfactor) *
+ ((height+packfactor-1)/packfactor);
+ if (PyString_Size(unpacked) != pixcount*sizeof(long)) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "string arg to packrect has wrong size");
+ return NULL;
+ }
+ packed = PyString_FromStringAndSize((char *)NULL, packedcount);
+ if (packed == NULL)
+ return NULL;
+ parray = (unsigned long *) PyString_AsString(unpacked);
+ p = (unsigned char *) PyString_AsString(packed);
+ for (y = 0; y < height; y += packfactor, parray += packfactor*width) {
+ for (x = 0; x < width; x += packfactor) {
+ pixel = parray[x];
+ r = pixel & 0xff;
+ g = (pixel >> 8) & 0xff;
+ b = (pixel >> 16) & 0xff;
+ *p++ = (30*r+59*g+11*b) / 100;
+ }
+ }
+ return packed;
}
@@ -729,77 +729,77 @@ static int unpacktab_inited = 0;
static PyObject *
gl_unpackrect(PyObject *self, PyObject *args)
{
- long width, height, packfactor;
- char *s;
- PyObject *unpacked, *packed;
- int pixcount, packedcount;
- register unsigned char *p;
- register unsigned long *parray;
- if (!unpacktab_inited) {
- register int white;
- for (white = 256; --white >= 0; )
- unpacktab[white] = white * 0x010101L;
- unpacktab_inited++;
- }
- if (!PyArg_GetLong(args, 4, 0, &width))
- return NULL;
- if (!PyArg_GetLong(args, 4, 1, &height))
- return NULL;
- if (!PyArg_GetLong(args, 4, 2, &packfactor))
- return NULL;
- if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
- return NULL;
- if (!PyArg_GetObject(args, 4, 3, &packed))
- return NULL;
- if (width <= 0 || height <= 0 || packfactor <= 0) {
- PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
- return NULL;
- }
- pixcount = width*height;
- packedcount = ((width+packfactor-1)/packfactor) *
- ((height+packfactor-1)/packfactor);
- if (PyString_Size(packed) != packedcount) {
- PyErr_SetString(PyExc_RuntimeError,
- "string arg to unpackrect has wrong size");
- return NULL;
- }
- unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
- if (unpacked == NULL)
- return NULL;
- parray = (unsigned long *) PyString_AsString(unpacked);
- p = (unsigned char *) PyString_AsString(packed);
- if (packfactor == 1 && width*height > 0) {
- /* Just expand bytes to longs */
- register int x = width * height;
- do {
- *parray++ = unpacktab[*p++];
- } while (--x >= 0);
- }
- else {
- register int y;
- for (y = 0; y < height-packfactor+1;
- y += packfactor, parray += packfactor*width) {
- register int x;
- for (x = 0; x < width-packfactor+1; x += packfactor) {
- register unsigned long pixel = unpacktab[*p++];
- register int i;
- for (i = packfactor*width; (i-=width) >= 0;) {
- register int j;
- for (j = packfactor; --j >= 0; )
- parray[i+x+j] = pixel;
- }
- }
- }
- }
- return unpacked;
+ long width, height, packfactor;
+ char *s;
+ PyObject *unpacked, *packed;
+ int pixcount, packedcount;
+ register unsigned char *p;
+ register unsigned long *parray;
+ if (!unpacktab_inited) {
+ register int white;
+ for (white = 256; --white >= 0; )
+ unpacktab[white] = white * 0x010101L;
+ unpacktab_inited++;
+ }
+ if (!PyArg_GetLong(args, 4, 0, &width))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 1, &height))
+ return NULL;
+ if (!PyArg_GetLong(args, 4, 2, &packfactor))
+ return NULL;
+ if (!PyArg_GetString(args, 4, 3, &s)) /* For type checking only */
+ return NULL;
+ if (!PyArg_GetObject(args, 4, 3, &packed))
+ return NULL;
+ if (width <= 0 || height <= 0 || packfactor <= 0) {
+ PyErr_SetString(PyExc_RuntimeError, "packrect args must be > 0");
+ return NULL;
+ }
+ pixcount = width*height;
+ packedcount = ((width+packfactor-1)/packfactor) *
+ ((height+packfactor-1)/packfactor);
+ if (PyString_Size(packed) != packedcount) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "string arg to unpackrect has wrong size");
+ return NULL;
+ }
+ unpacked = PyString_FromStringAndSize((char *)NULL, pixcount*sizeof(long));
+ if (unpacked == NULL)
+ return NULL;
+ parray = (unsigned long *) PyString_AsString(unpacked);
+ p = (unsigned char *) PyString_AsString(packed);
+ if (packfactor == 1 && width*height > 0) {
+ /* Just expand bytes to longs */
+ register int x = width * height;
+ do {
+ *parray++ = unpacktab[*p++];
+ } while (--x >= 0);
+ }
+ else {
+ register int y;
+ for (y = 0; y < height-packfactor+1;
+ y += packfactor, parray += packfactor*width) {
+ register int x;
+ for (x = 0; x < width-packfactor+1; x += packfactor) {
+ register unsigned long pixel = unpacktab[*p++];
+ register int i;
+ for (i = packfactor*width; (i-=width) >= 0;) {
+ register int j;
+ for (j = packfactor; --j >= 0; )
+ parray[i+x+j] = pixel;
+ }
+ }
+ }
+ }
+ return unpacked;
}
static PyObject *
gl_gversion(PyObject *self, PyObject *args)
{
- char buf[20];
- gversion(buf);
- return PyString_FromString(buf);
+ char buf[20];
+ gversion(buf);
+ return PyString_FromString(buf);
}
@@ -807,9 +807,9 @@ gl_gversion(PyObject *self, PyObject *args)
static PyObject *
gl_clear(PyObject *self, PyObject *args)
{
- __GLclear( );
- Py_INCREF(Py_None);
- return Py_None;
+ __GLclear( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* End of manually written stubs */
@@ -820,9 +820,9 @@ gl_clear(PyObject *self, PyObject *args)
static PyObject *
gl_getshade(PyObject *self, PyObject *args)
{
- long retval;
- retval = getshade( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getshade( );
+ return mknewlongobject(retval);
}
/* void devport short s long s */
@@ -830,15 +830,15 @@ gl_getshade(PyObject *self, PyObject *args)
static PyObject *
gl_devport(PyObject *self, PyObject *args)
{
- short arg1 ;
- long arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- devport( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ long arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ devport( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr2i long s long s */
@@ -846,15 +846,15 @@ gl_devport(PyObject *self, PyObject *args)
static PyObject *
gl_rdr2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rdr2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rdr2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectfs short s short s short s short s */
@@ -862,21 +862,21 @@ gl_rdr2i(PyObject *self, PyObject *args)
static PyObject *
gl_rectfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- rectfs( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ rectfs( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rects short s short s short s short s */
@@ -884,21 +884,21 @@ gl_rectfs(PyObject *self, PyObject *args)
static PyObject *
gl_rects(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- rects( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ rects( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv2i long s long s */
@@ -906,15 +906,15 @@ gl_rects(PyObject *self, PyObject *args)
static PyObject *
gl_rmv2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rmv2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rmv2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void noport */
@@ -922,9 +922,9 @@ gl_rmv2i(PyObject *self, PyObject *args)
static PyObject *
gl_noport(PyObject *self, PyObject *args)
{
- noport( );
- Py_INCREF(Py_None);
- return Py_None;
+ noport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popviewport */
@@ -932,9 +932,9 @@ gl_noport(PyObject *self, PyObject *args)
static PyObject *
gl_popviewport(PyObject *self, PyObject *args)
{
- popviewport( );
- Py_INCREF(Py_None);
- return Py_None;
+ popviewport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void clearhitcode */
@@ -942,9 +942,9 @@ gl_popviewport(PyObject *self, PyObject *args)
static PyObject *
gl_clearhitcode(PyObject *self, PyObject *args)
{
- clearhitcode( );
- Py_INCREF(Py_None);
- return Py_None;
+ clearhitcode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void closeobj */
@@ -952,9 +952,9 @@ gl_clearhitcode(PyObject *self, PyObject *args)
static PyObject *
gl_closeobj(PyObject *self, PyObject *args)
{
- closeobj( );
- Py_INCREF(Py_None);
- return Py_None;
+ closeobj( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cursoff */
@@ -962,9 +962,9 @@ gl_closeobj(PyObject *self, PyObject *args)
static PyObject *
gl_cursoff(PyObject *self, PyObject *args)
{
- cursoff( );
- Py_INCREF(Py_None);
- return Py_None;
+ cursoff( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curson */
@@ -972,9 +972,9 @@ gl_cursoff(PyObject *self, PyObject *args)
static PyObject *
gl_curson(PyObject *self, PyObject *args)
{
- curson( );
- Py_INCREF(Py_None);
- return Py_None;
+ curson( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void doublebuffer */
@@ -982,9 +982,9 @@ gl_curson(PyObject *self, PyObject *args)
static PyObject *
gl_doublebuffer(PyObject *self, PyObject *args)
{
- doublebuffer( );
- Py_INCREF(Py_None);
- return Py_None;
+ doublebuffer( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void finish */
@@ -992,9 +992,9 @@ gl_doublebuffer(PyObject *self, PyObject *args)
static PyObject *
gl_finish(PyObject *self, PyObject *args)
{
- finish( );
- Py_INCREF(Py_None);
- return Py_None;
+ finish( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gconfig */
@@ -1002,9 +1002,9 @@ gl_finish(PyObject *self, PyObject *args)
static PyObject *
gl_gconfig(PyObject *self, PyObject *args)
{
- gconfig( );
- Py_INCREF(Py_None);
- return Py_None;
+ gconfig( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ginit */
@@ -1012,9 +1012,9 @@ gl_gconfig(PyObject *self, PyObject *args)
static PyObject *
gl_ginit(PyObject *self, PyObject *args)
{
- ginit( );
- Py_INCREF(Py_None);
- return Py_None;
+ ginit( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void greset */
@@ -1022,9 +1022,9 @@ gl_ginit(PyObject *self, PyObject *args)
static PyObject *
gl_greset(PyObject *self, PyObject *args)
{
- greset( );
- Py_INCREF(Py_None);
- return Py_None;
+ greset( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void multimap */
@@ -1032,9 +1032,9 @@ gl_greset(PyObject *self, PyObject *args)
static PyObject *
gl_multimap(PyObject *self, PyObject *args)
{
- multimap( );
- Py_INCREF(Py_None);
- return Py_None;
+ multimap( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void onemap */
@@ -1042,9 +1042,9 @@ gl_multimap(PyObject *self, PyObject *args)
static PyObject *
gl_onemap(PyObject *self, PyObject *args)
{
- onemap( );
- Py_INCREF(Py_None);
- return Py_None;
+ onemap( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popattributes */
@@ -1052,9 +1052,9 @@ gl_onemap(PyObject *self, PyObject *args)
static PyObject *
gl_popattributes(PyObject *self, PyObject *args)
{
- popattributes( );
- Py_INCREF(Py_None);
- return Py_None;
+ popattributes( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popmatrix */
@@ -1062,9 +1062,9 @@ gl_popattributes(PyObject *self, PyObject *args)
static PyObject *
gl_popmatrix(PyObject *self, PyObject *args)
{
- popmatrix( );
- Py_INCREF(Py_None);
- return Py_None;
+ popmatrix( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushattributes */
@@ -1072,9 +1072,9 @@ gl_popmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_pushattributes(PyObject *self, PyObject *args)
{
- pushattributes( );
- Py_INCREF(Py_None);
- return Py_None;
+ pushattributes( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushmatrix */
@@ -1082,9 +1082,9 @@ gl_pushattributes(PyObject *self, PyObject *args)
static PyObject *
gl_pushmatrix(PyObject *self, PyObject *args)
{
- pushmatrix( );
- Py_INCREF(Py_None);
- return Py_None;
+ pushmatrix( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushviewport */
@@ -1092,9 +1092,9 @@ gl_pushmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_pushviewport(PyObject *self, PyObject *args)
{
- pushviewport( );
- Py_INCREF(Py_None);
- return Py_None;
+ pushviewport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void qreset */
@@ -1102,9 +1102,9 @@ gl_pushviewport(PyObject *self, PyObject *args)
static PyObject *
gl_qreset(PyObject *self, PyObject *args)
{
- qreset( );
- Py_INCREF(Py_None);
- return Py_None;
+ qreset( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBmode */
@@ -1112,9 +1112,9 @@ gl_qreset(PyObject *self, PyObject *args)
static PyObject *
gl_RGBmode(PyObject *self, PyObject *args)
{
- RGBmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ RGBmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void singlebuffer */
@@ -1122,9 +1122,9 @@ gl_RGBmode(PyObject *self, PyObject *args)
static PyObject *
gl_singlebuffer(PyObject *self, PyObject *args)
{
- singlebuffer( );
- Py_INCREF(Py_None);
- return Py_None;
+ singlebuffer( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void swapbuffers */
@@ -1132,9 +1132,9 @@ gl_singlebuffer(PyObject *self, PyObject *args)
static PyObject *
gl_swapbuffers(PyObject *self, PyObject *args)
{
- swapbuffers( );
- Py_INCREF(Py_None);
- return Py_None;
+ swapbuffers( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gsync */
@@ -1142,9 +1142,9 @@ gl_swapbuffers(PyObject *self, PyObject *args)
static PyObject *
gl_gsync(PyObject *self, PyObject *args)
{
- gsync( );
- Py_INCREF(Py_None);
- return Py_None;
+ gsync( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gflush */
@@ -1152,9 +1152,9 @@ gl_gsync(PyObject *self, PyObject *args)
static PyObject *
gl_gflush(PyObject *self, PyObject *args)
{
- gflush( );
- Py_INCREF(Py_None);
- return Py_None;
+ gflush( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void tpon */
@@ -1162,9 +1162,9 @@ gl_gflush(PyObject *self, PyObject *args)
static PyObject *
gl_tpon(PyObject *self, PyObject *args)
{
- tpon( );
- Py_INCREF(Py_None);
- return Py_None;
+ tpon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void tpoff */
@@ -1172,9 +1172,9 @@ gl_tpon(PyObject *self, PyObject *args)
static PyObject *
gl_tpoff(PyObject *self, PyObject *args)
{
- tpoff( );
- Py_INCREF(Py_None);
- return Py_None;
+ tpoff( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void clkon */
@@ -1182,9 +1182,9 @@ gl_tpoff(PyObject *self, PyObject *args)
static PyObject *
gl_clkon(PyObject *self, PyObject *args)
{
- clkon( );
- Py_INCREF(Py_None);
- return Py_None;
+ clkon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void clkoff */
@@ -1192,9 +1192,9 @@ gl_clkon(PyObject *self, PyObject *args)
static PyObject *
gl_clkoff(PyObject *self, PyObject *args)
{
- clkoff( );
- Py_INCREF(Py_None);
- return Py_None;
+ clkoff( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ringbell */
@@ -1202,9 +1202,9 @@ gl_clkoff(PyObject *self, PyObject *args)
static PyObject *
gl_ringbell(PyObject *self, PyObject *args)
{
- ringbell( );
- Py_INCREF(Py_None);
- return Py_None;
+ ringbell( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gbegin */
@@ -1212,9 +1212,9 @@ gl_ringbell(PyObject *self, PyObject *args)
static PyObject *
gl_gbegin(PyObject *self, PyObject *args)
{
- gbegin( );
- Py_INCREF(Py_None);
- return Py_None;
+ gbegin( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textinit */
@@ -1222,9 +1222,9 @@ gl_gbegin(PyObject *self, PyObject *args)
static PyObject *
gl_textinit(PyObject *self, PyObject *args)
{
- textinit( );
- Py_INCREF(Py_None);
- return Py_None;
+ textinit( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void initnames */
@@ -1232,9 +1232,9 @@ gl_textinit(PyObject *self, PyObject *args)
static PyObject *
gl_initnames(PyObject *self, PyObject *args)
{
- initnames( );
- Py_INCREF(Py_None);
- return Py_None;
+ initnames( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pclos */
@@ -1242,9 +1242,9 @@ gl_initnames(PyObject *self, PyObject *args)
static PyObject *
gl_pclos(PyObject *self, PyObject *args)
{
- pclos( );
- Py_INCREF(Py_None);
- return Py_None;
+ pclos( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void popname */
@@ -1252,9 +1252,9 @@ gl_pclos(PyObject *self, PyObject *args)
static PyObject *
gl_popname(PyObject *self, PyObject *args)
{
- popname( );
- Py_INCREF(Py_None);
- return Py_None;
+ popname( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void spclos */
@@ -1262,9 +1262,9 @@ gl_popname(PyObject *self, PyObject *args)
static PyObject *
gl_spclos(PyObject *self, PyObject *args)
{
- spclos( );
- Py_INCREF(Py_None);
- return Py_None;
+ spclos( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zclear */
@@ -1272,9 +1272,9 @@ gl_spclos(PyObject *self, PyObject *args)
static PyObject *
gl_zclear(PyObject *self, PyObject *args)
{
- zclear( );
- Py_INCREF(Py_None);
- return Py_None;
+ zclear( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void screenspace */
@@ -1282,9 +1282,9 @@ gl_zclear(PyObject *self, PyObject *args)
static PyObject *
gl_screenspace(PyObject *self, PyObject *args)
{
- screenspace( );
- Py_INCREF(Py_None);
- return Py_None;
+ screenspace( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void reshapeviewport */
@@ -1292,9 +1292,9 @@ gl_screenspace(PyObject *self, PyObject *args)
static PyObject *
gl_reshapeviewport(PyObject *self, PyObject *args)
{
- reshapeviewport( );
- Py_INCREF(Py_None);
- return Py_None;
+ reshapeviewport( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winpush */
@@ -1302,9 +1302,9 @@ gl_reshapeviewport(PyObject *self, PyObject *args)
static PyObject *
gl_winpush(PyObject *self, PyObject *args)
{
- winpush( );
- Py_INCREF(Py_None);
- return Py_None;
+ winpush( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winpop */
@@ -1312,9 +1312,9 @@ gl_winpush(PyObject *self, PyObject *args)
static PyObject *
gl_winpop(PyObject *self, PyObject *args)
{
- winpop( );
- Py_INCREF(Py_None);
- return Py_None;
+ winpop( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void foreground */
@@ -1322,9 +1322,9 @@ gl_winpop(PyObject *self, PyObject *args)
static PyObject *
gl_foreground(PyObject *self, PyObject *args)
{
- foreground( );
- Py_INCREF(Py_None);
- return Py_None;
+ foreground( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endfullscrn */
@@ -1332,9 +1332,9 @@ gl_foreground(PyObject *self, PyObject *args)
static PyObject *
gl_endfullscrn(PyObject *self, PyObject *args)
{
- endfullscrn( );
- Py_INCREF(Py_None);
- return Py_None;
+ endfullscrn( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endpupmode */
@@ -1342,9 +1342,9 @@ gl_endfullscrn(PyObject *self, PyObject *args)
static PyObject *
gl_endpupmode(PyObject *self, PyObject *args)
{
- endpupmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ endpupmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void fullscrn */
@@ -1352,9 +1352,9 @@ gl_endpupmode(PyObject *self, PyObject *args)
static PyObject *
gl_fullscrn(PyObject *self, PyObject *args)
{
- fullscrn( );
- Py_INCREF(Py_None);
- return Py_None;
+ fullscrn( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pupmode */
@@ -1362,9 +1362,9 @@ gl_fullscrn(PyObject *self, PyObject *args)
static PyObject *
gl_pupmode(PyObject *self, PyObject *args)
{
- pupmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ pupmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winconstraints */
@@ -1372,9 +1372,9 @@ gl_pupmode(PyObject *self, PyObject *args)
static PyObject *
gl_winconstraints(PyObject *self, PyObject *args)
{
- winconstraints( );
- Py_INCREF(Py_None);
- return Py_None;
+ winconstraints( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pagecolor short s */
@@ -1382,12 +1382,12 @@ gl_winconstraints(PyObject *self, PyObject *args)
static PyObject *
gl_pagecolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- pagecolor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ pagecolor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textcolor short s */
@@ -1395,12 +1395,12 @@ gl_pagecolor(PyObject *self, PyObject *args)
static PyObject *
gl_textcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- textcolor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ textcolor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void color short s */
@@ -1408,12 +1408,12 @@ gl_textcolor(PyObject *self, PyObject *args)
static PyObject *
gl_color(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- color( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ color( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curveit short s */
@@ -1421,12 +1421,12 @@ gl_color(PyObject *self, PyObject *args)
static PyObject *
gl_curveit(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- curveit( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ curveit( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void font short s */
@@ -1434,12 +1434,12 @@ gl_curveit(PyObject *self, PyObject *args)
static PyObject *
gl_font(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- font( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ font( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void linewidth short s */
@@ -1447,12 +1447,12 @@ gl_font(PyObject *self, PyObject *args)
static PyObject *
gl_linewidth(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- linewidth( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ linewidth( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setlinestyle short s */
@@ -1460,12 +1460,12 @@ gl_linewidth(PyObject *self, PyObject *args)
static PyObject *
gl_setlinestyle(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setlinestyle( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setlinestyle( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setmap short s */
@@ -1473,12 +1473,12 @@ gl_setlinestyle(PyObject *self, PyObject *args)
static PyObject *
gl_setmap(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setmap( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setmap( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void swapinterval short s */
@@ -1486,12 +1486,12 @@ gl_setmap(PyObject *self, PyObject *args)
static PyObject *
gl_swapinterval(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- swapinterval( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ swapinterval( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void writemask short s */
@@ -1499,12 +1499,12 @@ gl_swapinterval(PyObject *self, PyObject *args)
static PyObject *
gl_writemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- writemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ writemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textwritemask short s */
@@ -1512,12 +1512,12 @@ gl_writemask(PyObject *self, PyObject *args)
static PyObject *
gl_textwritemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- textwritemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ textwritemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void qdevice short s */
@@ -1525,12 +1525,12 @@ gl_textwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_qdevice(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- qdevice( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ qdevice( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void unqdevice short s */
@@ -1538,12 +1538,12 @@ gl_qdevice(PyObject *self, PyObject *args)
static PyObject *
gl_unqdevice(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- unqdevice( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ unqdevice( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curvebasis short s */
@@ -1551,12 +1551,12 @@ gl_unqdevice(PyObject *self, PyObject *args)
static PyObject *
gl_curvebasis(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- curvebasis( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ curvebasis( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curveprecision short s */
@@ -1564,12 +1564,12 @@ gl_curvebasis(PyObject *self, PyObject *args)
static PyObject *
gl_curveprecision(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- curveprecision( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ curveprecision( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void loadname short s */
@@ -1577,12 +1577,12 @@ gl_curveprecision(PyObject *self, PyObject *args)
static PyObject *
gl_loadname(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- loadname( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ loadname( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void passthrough short s */
@@ -1590,12 +1590,12 @@ gl_loadname(PyObject *self, PyObject *args)
static PyObject *
gl_passthrough(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- passthrough( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ passthrough( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pushname short s */
@@ -1603,12 +1603,12 @@ gl_passthrough(PyObject *self, PyObject *args)
static PyObject *
gl_pushname(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- pushname( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ pushname( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setmonitor short s */
@@ -1616,12 +1616,12 @@ gl_pushname(PyObject *self, PyObject *args)
static PyObject *
gl_setmonitor(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setmonitor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setmonitor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setshade short s */
@@ -1629,12 +1629,12 @@ gl_setmonitor(PyObject *self, PyObject *args)
static PyObject *
gl_setshade(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setshade( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setshade( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setpattern short s */
@@ -1642,12 +1642,12 @@ gl_setshade(PyObject *self, PyObject *args)
static PyObject *
gl_setpattern(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- setpattern( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ setpattern( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pagewritemask short s */
@@ -1655,12 +1655,12 @@ gl_setpattern(PyObject *self, PyObject *args)
static PyObject *
gl_pagewritemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- pagewritemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ pagewritemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void callobj long s */
@@ -1668,12 +1668,12 @@ gl_pagewritemask(PyObject *self, PyObject *args)
static PyObject *
gl_callobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- callobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ callobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void delobj long s */
@@ -1681,12 +1681,12 @@ gl_callobj(PyObject *self, PyObject *args)
static PyObject *
gl_delobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- delobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ delobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void editobj long s */
@@ -1694,12 +1694,12 @@ gl_delobj(PyObject *self, PyObject *args)
static PyObject *
gl_editobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- editobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ editobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void makeobj long s */
@@ -1707,12 +1707,12 @@ gl_editobj(PyObject *self, PyObject *args)
static PyObject *
gl_makeobj(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- makeobj( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ makeobj( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void maketag long s */
@@ -1720,12 +1720,12 @@ gl_makeobj(PyObject *self, PyObject *args)
static PyObject *
gl_maketag(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- maketag( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ maketag( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void chunksize long s */
@@ -1733,12 +1733,12 @@ gl_maketag(PyObject *self, PyObject *args)
static PyObject *
gl_chunksize(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- chunksize( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ chunksize( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void compactify long s */
@@ -1746,12 +1746,12 @@ gl_chunksize(PyObject *self, PyObject *args)
static PyObject *
gl_compactify(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- compactify( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ compactify( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void deltag long s */
@@ -1759,12 +1759,12 @@ gl_compactify(PyObject *self, PyObject *args)
static PyObject *
gl_deltag(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- deltag( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ deltag( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lsrepeat long s */
@@ -1772,12 +1772,12 @@ gl_deltag(PyObject *self, PyObject *args)
static PyObject *
gl_lsrepeat(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lsrepeat( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lsrepeat( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void objinsert long s */
@@ -1785,12 +1785,12 @@ gl_lsrepeat(PyObject *self, PyObject *args)
static PyObject *
gl_objinsert(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- objinsert( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ objinsert( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void objreplace long s */
@@ -1798,12 +1798,12 @@ gl_objinsert(PyObject *self, PyObject *args)
static PyObject *
gl_objreplace(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- objreplace( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ objreplace( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winclose long s */
@@ -1811,12 +1811,12 @@ gl_objreplace(PyObject *self, PyObject *args)
static PyObject *
gl_winclose(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- winclose( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ winclose( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blanktime long s */
@@ -1824,12 +1824,12 @@ gl_winclose(PyObject *self, PyObject *args)
static PyObject *
gl_blanktime(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- blanktime( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ blanktime( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void freepup long s */
@@ -1837,12 +1837,12 @@ gl_blanktime(PyObject *self, PyObject *args)
static PyObject *
gl_freepup(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- freepup( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ freepup( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void backbuffer long s */
@@ -1850,12 +1850,12 @@ gl_freepup(PyObject *self, PyObject *args)
static PyObject *
gl_backbuffer(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- backbuffer( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ backbuffer( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void frontbuffer long s */
@@ -1863,12 +1863,12 @@ gl_backbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_frontbuffer(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- frontbuffer( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ frontbuffer( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lsbackup long s */
@@ -1876,12 +1876,12 @@ gl_frontbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_lsbackup(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lsbackup( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lsbackup( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void resetls long s */
@@ -1889,12 +1889,12 @@ gl_lsbackup(PyObject *self, PyObject *args)
static PyObject *
gl_resetls(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- resetls( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ resetls( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lampon long s */
@@ -1902,12 +1902,12 @@ gl_resetls(PyObject *self, PyObject *args)
static PyObject *
gl_lampon(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lampon( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lampon( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lampoff long s */
@@ -1915,12 +1915,12 @@ gl_lampon(PyObject *self, PyObject *args)
static PyObject *
gl_lampoff(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lampoff( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lampoff( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setbell long s */
@@ -1928,12 +1928,12 @@ gl_lampoff(PyObject *self, PyObject *args)
static PyObject *
gl_setbell(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- setbell( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ setbell( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blankscreen long s */
@@ -1941,12 +1941,12 @@ gl_setbell(PyObject *self, PyObject *args)
static PyObject *
gl_blankscreen(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- blankscreen( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ blankscreen( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void depthcue long s */
@@ -1954,12 +1954,12 @@ gl_blankscreen(PyObject *self, PyObject *args)
static PyObject *
gl_depthcue(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- depthcue( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ depthcue( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zbuffer long s */
@@ -1967,12 +1967,12 @@ gl_depthcue(PyObject *self, PyObject *args)
static PyObject *
gl_zbuffer(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zbuffer( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zbuffer( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void backface long s */
@@ -1980,12 +1980,12 @@ gl_zbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_backface(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- backface( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ backface( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov2i long s long s */
@@ -1993,15 +1993,15 @@ gl_backface(PyObject *self, PyObject *args)
static PyObject *
gl_cmov2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- cmov2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ cmov2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw2i long s long s */
@@ -2009,15 +2009,15 @@ gl_cmov2i(PyObject *self, PyObject *args)
static PyObject *
gl_draw2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- draw2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ draw2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move2i long s long s */
@@ -2025,15 +2025,15 @@ gl_draw2i(PyObject *self, PyObject *args)
static PyObject *
gl_move2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- move2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ move2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt2i long s long s */
@@ -2041,15 +2041,15 @@ gl_move2i(PyObject *self, PyObject *args)
static PyObject *
gl_pnt2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pnt2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pnt2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patchbasis long s long s */
@@ -2057,15 +2057,15 @@ gl_pnt2i(PyObject *self, PyObject *args)
static PyObject *
gl_patchbasis(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- patchbasis( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ patchbasis( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patchprecision long s long s */
@@ -2073,15 +2073,15 @@ gl_patchbasis(PyObject *self, PyObject *args)
static PyObject *
gl_patchprecision(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- patchprecision( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ patchprecision( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr2i long s long s */
@@ -2089,15 +2089,15 @@ gl_patchprecision(PyObject *self, PyObject *args)
static PyObject *
gl_pdr2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pdr2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pdr2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv2i long s long s */
@@ -2105,15 +2105,15 @@ gl_pdr2i(PyObject *self, PyObject *args)
static PyObject *
gl_pmv2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pmv2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pmv2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr2i long s long s */
@@ -2121,15 +2121,15 @@ gl_pmv2i(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rpdr2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rpdr2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv2i long s long s */
@@ -2137,15 +2137,15 @@ gl_rpdr2i(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- rpmv2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ rpmv2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt2i long s long s */
@@ -2153,15 +2153,15 @@ gl_rpmv2i(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- xfpt2i( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ xfpt2i( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void objdelete long s long s */
@@ -2169,15 +2169,15 @@ gl_xfpt2i(PyObject *self, PyObject *args)
static PyObject *
gl_objdelete(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- objdelete( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ objdelete( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patchcurves long s long s */
@@ -2185,15 +2185,15 @@ gl_objdelete(PyObject *self, PyObject *args)
static PyObject *
gl_patchcurves(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- patchcurves( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ patchcurves( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void minsize long s long s */
@@ -2201,15 +2201,15 @@ gl_patchcurves(PyObject *self, PyObject *args)
static PyObject *
gl_minsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- minsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ minsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void maxsize long s long s */
@@ -2217,15 +2217,15 @@ gl_minsize(PyObject *self, PyObject *args)
static PyObject *
gl_maxsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- maxsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ maxsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void keepaspect long s long s */
@@ -2233,15 +2233,15 @@ gl_maxsize(PyObject *self, PyObject *args)
static PyObject *
gl_keepaspect(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- keepaspect( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ keepaspect( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void prefsize long s long s */
@@ -2249,15 +2249,15 @@ gl_keepaspect(PyObject *self, PyObject *args)
static PyObject *
gl_prefsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- prefsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ prefsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void stepunit long s long s */
@@ -2265,15 +2265,15 @@ gl_prefsize(PyObject *self, PyObject *args)
static PyObject *
gl_stepunit(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- stepunit( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ stepunit( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void fudge long s long s */
@@ -2281,15 +2281,15 @@ gl_stepunit(PyObject *self, PyObject *args)
static PyObject *
gl_fudge(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- fudge( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ fudge( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void winmove long s long s */
@@ -2297,15 +2297,15 @@ gl_fudge(PyObject *self, PyObject *args)
static PyObject *
gl_winmove(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- winmove( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ winmove( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void attachcursor short s short s */
@@ -2313,15 +2313,15 @@ gl_winmove(PyObject *self, PyObject *args)
static PyObject *
gl_attachcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- attachcursor( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ attachcursor( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void deflinestyle short s short s */
@@ -2329,15 +2329,15 @@ gl_attachcursor(PyObject *self, PyObject *args)
static PyObject *
gl_deflinestyle(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- deflinestyle( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ deflinestyle( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void noise short s short s */
@@ -2345,15 +2345,15 @@ gl_deflinestyle(PyObject *self, PyObject *args)
static PyObject *
gl_noise(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- noise( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ noise( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void picksize short s short s */
@@ -2361,15 +2361,15 @@ gl_noise(PyObject *self, PyObject *args)
static PyObject *
gl_picksize(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- picksize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ picksize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void qenter short s short s */
@@ -2377,15 +2377,15 @@ gl_picksize(PyObject *self, PyObject *args)
static PyObject *
gl_qenter(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- qenter( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ qenter( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setdepth short s short s */
@@ -2393,15 +2393,15 @@ gl_qenter(PyObject *self, PyObject *args)
static PyObject *
gl_setdepth(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- setdepth( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ setdepth( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov2s short s short s */
@@ -2409,15 +2409,15 @@ gl_setdepth(PyObject *self, PyObject *args)
static PyObject *
gl_cmov2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- cmov2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ cmov2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw2s short s short s */
@@ -2425,15 +2425,15 @@ gl_cmov2s(PyObject *self, PyObject *args)
static PyObject *
gl_draw2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- draw2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ draw2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move2s short s short s */
@@ -2441,15 +2441,15 @@ gl_draw2s(PyObject *self, PyObject *args)
static PyObject *
gl_move2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- move2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ move2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr2s short s short s */
@@ -2457,15 +2457,15 @@ gl_move2s(PyObject *self, PyObject *args)
static PyObject *
gl_pdr2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- pdr2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ pdr2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv2s short s short s */
@@ -2473,15 +2473,15 @@ gl_pdr2s(PyObject *self, PyObject *args)
static PyObject *
gl_pmv2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- pmv2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ pmv2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt2s short s short s */
@@ -2489,15 +2489,15 @@ gl_pmv2s(PyObject *self, PyObject *args)
static PyObject *
gl_pnt2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- pnt2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ pnt2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr2s short s short s */
@@ -2505,15 +2505,15 @@ gl_pnt2s(PyObject *self, PyObject *args)
static PyObject *
gl_rdr2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rdr2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rdr2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv2s short s short s */
@@ -2521,15 +2521,15 @@ gl_rdr2s(PyObject *self, PyObject *args)
static PyObject *
gl_rmv2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rmv2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rmv2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr2s short s short s */
@@ -2537,15 +2537,15 @@ gl_rmv2s(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rpdr2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rpdr2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv2s short s short s */
@@ -2553,15 +2553,15 @@ gl_rpdr2s(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- rpmv2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ rpmv2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt2s short s short s */
@@ -2569,15 +2569,15 @@ gl_rpmv2s(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- xfpt2s( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ xfpt2s( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov2 float s float s */
@@ -2585,15 +2585,15 @@ gl_xfpt2s(PyObject *self, PyObject *args)
static PyObject *
gl_cmov2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- cmov2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ cmov2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw2 float s float s */
@@ -2601,15 +2601,15 @@ gl_cmov2(PyObject *self, PyObject *args)
static PyObject *
gl_draw2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- draw2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ draw2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move2 float s float s */
@@ -2617,15 +2617,15 @@ gl_draw2(PyObject *self, PyObject *args)
static PyObject *
gl_move2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- move2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ move2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt2 float s float s */
@@ -2633,15 +2633,15 @@ gl_move2(PyObject *self, PyObject *args)
static PyObject *
gl_pnt2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- pnt2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ pnt2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr2 float s float s */
@@ -2649,15 +2649,15 @@ gl_pnt2(PyObject *self, PyObject *args)
static PyObject *
gl_pdr2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- pdr2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ pdr2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv2 float s float s */
@@ -2665,15 +2665,15 @@ gl_pdr2(PyObject *self, PyObject *args)
static PyObject *
gl_pmv2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- pmv2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ pmv2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr2 float s float s */
@@ -2681,15 +2681,15 @@ gl_pmv2(PyObject *self, PyObject *args)
static PyObject *
gl_rdr2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rdr2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rdr2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv2 float s float s */
@@ -2697,15 +2697,15 @@ gl_rdr2(PyObject *self, PyObject *args)
static PyObject *
gl_rmv2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rmv2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rmv2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr2 float s float s */
@@ -2713,15 +2713,15 @@ gl_rmv2(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rpdr2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rpdr2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv2 float s float s */
@@ -2729,15 +2729,15 @@ gl_rpdr2(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rpmv2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rpmv2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt2 float s float s */
@@ -2745,15 +2745,15 @@ gl_rpmv2(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- xfpt2( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ xfpt2( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void loadmatrix float s[4*4] */
@@ -2761,12 +2761,12 @@ gl_xfpt2(PyObject *self, PyObject *args)
static PyObject *
gl_loadmatrix(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
- return NULL;
- loadmatrix( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ loadmatrix( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void multmatrix float s[4*4] */
@@ -2774,12 +2774,12 @@ gl_loadmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_multmatrix(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
- return NULL;
- multmatrix( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ multmatrix( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void crv float s[3*4] */
@@ -2787,12 +2787,12 @@ gl_multmatrix(PyObject *self, PyObject *args)
static PyObject *
gl_crv(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 * 4 , (float *) arg1))
- return NULL;
- crv( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 * 4 , (float *) arg1))
+ return NULL;
+ crv( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rcrv float s[4*4] */
@@ -2800,12 +2800,12 @@ gl_crv(PyObject *self, PyObject *args)
static PyObject *
gl_rcrv(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
- return NULL;
- rcrv( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ rcrv( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void addtopup long s char *s long s */
@@ -2813,18 +2813,18 @@ gl_rcrv(PyObject *self, PyObject *args)
static PyObject *
gl_addtopup(PyObject *self, PyObject *args)
{
- long arg1 ;
- string arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getistringarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- addtopup( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ string arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getistringarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ addtopup( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void charstr char *s */
@@ -2832,12 +2832,12 @@ gl_addtopup(PyObject *self, PyObject *args)
static PyObject *
gl_charstr(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- charstr( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ charstr( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void getport char *s */
@@ -2845,12 +2845,12 @@ gl_charstr(PyObject *self, PyObject *args)
static PyObject *
gl_getport(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- getport( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ getport( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long strwidth char *s */
@@ -2858,12 +2858,12 @@ gl_getport(PyObject *self, PyObject *args)
static PyObject *
gl_strwidth(PyObject *self, PyObject *args)
{
- long retval;
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- retval = strwidth( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = strwidth( arg1 );
+ return mknewlongobject(retval);
}
/* long winopen char *s */
@@ -2871,12 +2871,12 @@ gl_strwidth(PyObject *self, PyObject *args)
static PyObject *
gl_winopen(PyObject *self, PyObject *args)
{
- long retval;
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- retval = winopen( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = winopen( arg1 );
+ return mknewlongobject(retval);
}
/* void wintitle char *s */
@@ -2884,12 +2884,12 @@ gl_winopen(PyObject *self, PyObject *args)
static PyObject *
gl_wintitle(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- wintitle( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ wintitle( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf long s float s[3*arg1] */
@@ -2897,19 +2897,19 @@ gl_wintitle(PyObject *self, PyObject *args)
static PyObject *
gl_polf(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- polf( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ polf( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf2 long s float s[2*arg1] */
@@ -2917,19 +2917,19 @@ gl_polf(PyObject *self, PyObject *args)
static PyObject *
gl_polf2(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
- return NULL;
- polf2( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
+ return NULL;
+ polf2( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly long s float s[3*arg1] */
@@ -2937,19 +2937,19 @@ gl_polf2(PyObject *self, PyObject *args)
static PyObject *
gl_poly(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- poly( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ poly( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly2 long s float s[2*arg1] */
@@ -2957,19 +2957,19 @@ gl_poly(PyObject *self, PyObject *args)
static PyObject *
gl_poly2(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
- return NULL;
- poly2( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 2 * arg1 , (float *) arg2))
+ return NULL;
+ poly2( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void crvn long s float s[3*arg1] */
@@ -2977,19 +2977,19 @@ gl_poly2(PyObject *self, PyObject *args)
static PyObject *
gl_crvn(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- crvn( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ crvn( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rcrvn long s float s[4*arg1] */
@@ -2997,19 +2997,19 @@ gl_crvn(PyObject *self, PyObject *args)
static PyObject *
gl_rcrvn(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 4 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 4;
- if ((arg2 = (float(*)[4]) PyMem_NEW(float , 4 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 1, 0, 4 * arg1 , (float *) arg2))
- return NULL;
- rcrvn( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 4 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 4;
+ if ((arg2 = (float(*)[4]) PyMem_NEW(float , 4 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 1, 0, 4 * arg1 , (float *) arg2))
+ return NULL;
+ rcrvn( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf2i long s long s[2*arg1] */
@@ -3017,19 +3017,19 @@ gl_rcrvn(PyObject *self, PyObject *args)
static PyObject *
gl_polf2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
- return NULL;
- polf2i( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
+ return NULL;
+ polf2i( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polfi long s long s[3*arg1] */
@@ -3037,19 +3037,19 @@ gl_polf2i(PyObject *self, PyObject *args)
static PyObject *
gl_polfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
- return NULL;
- polfi( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
+ return NULL;
+ polfi( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly2i long s long s[2*arg1] */
@@ -3057,19 +3057,19 @@ gl_polfi(PyObject *self, PyObject *args)
static PyObject *
gl_poly2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
- return NULL;
- poly2i( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 2 * arg1 , (long *) arg2))
+ return NULL;
+ poly2i( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polyi long s long s[3*arg1] */
@@ -3077,19 +3077,19 @@ gl_poly2i(PyObject *self, PyObject *args)
static PyObject *
gl_polyi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
- return NULL;
- polyi( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 1, 0, 3 * arg1 , (long *) arg2))
+ return NULL;
+ polyi( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polf2s long s short s[2*arg1] */
@@ -3097,19 +3097,19 @@ gl_polyi(PyObject *self, PyObject *args)
static PyObject *
gl_polf2s(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
- return NULL;
- polf2s( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
+ return NULL;
+ polf2s( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polfs long s short s[3*arg1] */
@@ -3117,19 +3117,19 @@ gl_polf2s(PyObject *self, PyObject *args)
static PyObject *
gl_polfs(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
- return NULL;
- polfs( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
+ return NULL;
+ polfs( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polys long s short s[3*arg1] */
@@ -3137,19 +3137,19 @@ gl_polfs(PyObject *self, PyObject *args)
static PyObject *
gl_polys(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 3 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
- return NULL;
- polys( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 3 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 3 * arg1 , (short *) arg2))
+ return NULL;
+ polys( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void poly2s long s short s[2*arg1] */
@@ -3157,19 +3157,19 @@ gl_polys(PyObject *self, PyObject *args)
static PyObject *
gl_poly2s(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 2 ] ;
- if (!getilongarraysize(args, 1, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
- return NULL;
- poly2s( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 2 ] ;
+ if (!getilongarraysize(args, 1, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, 2 * arg1 , (short *) arg2))
+ return NULL;
+ poly2s( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void defcursor short s u_short s[128] */
@@ -3177,15 +3177,15 @@ gl_poly2s(PyObject *self, PyObject *args)
static PyObject *
gl_defcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- unsigned short arg2 [ 128 ] ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarray(args, 2, 1, 128 , (short *) arg2))
- return NULL;
- defcursor( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ unsigned short arg2 [ 128 ] ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarray(args, 2, 1, 128 , (short *) arg2))
+ return NULL;
+ defcursor( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void writepixels short s u_short s[arg1] */
@@ -3193,18 +3193,18 @@ gl_defcursor(PyObject *self, PyObject *args)
static PyObject *
gl_writepixels(PyObject *self, PyObject *args)
{
- short arg1 ;
- unsigned short * arg2 ;
- if (!getishortarraysize(args, 1, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, arg1 , (short *) arg2))
- return NULL;
- writepixels( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ unsigned short * arg2 ;
+ if (!getishortarraysize(args, 1, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, arg1 , (short *) arg2))
+ return NULL;
+ writepixels( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void defbasis long s float s[4*4] */
@@ -3212,15 +3212,15 @@ gl_writepixels(PyObject *self, PyObject *args)
static PyObject *
gl_defbasis(PyObject *self, PyObject *args)
{
- long arg1 ;
- float arg2 [ 4 ] [ 4 ] ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarray(args, 2, 1, 4 * 4 , (float *) arg2))
- return NULL;
- defbasis( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float arg2 [ 4 ] [ 4 ] ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarray(args, 2, 1, 4 * 4 , (float *) arg2))
+ return NULL;
+ defbasis( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gewrite short s short s[arg1] */
@@ -3228,18 +3228,18 @@ gl_defbasis(PyObject *self, PyObject *args)
static PyObject *
gl_gewrite(PyObject *self, PyObject *args)
{
- short arg1 ;
- short * arg2 ;
- if (!getishortarraysize(args, 1, 0, &arg1))
- return NULL;
- if ((arg2 = PyMem_NEW(short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 1, 0, arg1 , arg2))
- return NULL;
- gewrite( arg1 , arg2 );
- PyMem_DEL(arg2);
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short * arg2 ;
+ if (!getishortarraysize(args, 1, 0, &arg1))
+ return NULL;
+ if ((arg2 = PyMem_NEW(short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 1, 0, arg1 , arg2))
+ return NULL;
+ gewrite( arg1 , arg2 );
+ PyMem_DEL(arg2);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rotate short s char s */
@@ -3247,15 +3247,15 @@ gl_gewrite(PyObject *self, PyObject *args)
static PyObject *
gl_rotate(PyObject *self, PyObject *args)
{
- short arg1 ;
- char arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getichararg(args, 2, 1, &arg2))
- return NULL;
- rotate( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ char arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getichararg(args, 2, 1, &arg2))
+ return NULL;
+ rotate( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rot float s char s */
@@ -3263,15 +3263,15 @@ gl_rotate(PyObject *self, PyObject *args)
static PyObject *
gl_rot(PyObject *self, PyObject *args)
{
- float arg1 ;
- char arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getichararg(args, 2, 1, &arg2))
- return NULL;
- rot( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ char arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getichararg(args, 2, 1, &arg2))
+ return NULL;
+ rot( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circfi long s long s long s */
@@ -3279,18 +3279,18 @@ gl_rot(PyObject *self, PyObject *args)
static PyObject *
gl_circfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- circfi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ circfi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circi long s long s long s */
@@ -3298,18 +3298,18 @@ gl_circfi(PyObject *self, PyObject *args)
static PyObject *
gl_circi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- circi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ circi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmovi long s long s long s */
@@ -3317,18 +3317,18 @@ gl_circi(PyObject *self, PyObject *args)
static PyObject *
gl_cmovi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- cmovi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ cmovi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void drawi long s long s long s */
@@ -3336,18 +3336,18 @@ gl_cmovi(PyObject *self, PyObject *args)
static PyObject *
gl_drawi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- drawi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ drawi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void movei long s long s long s */
@@ -3355,18 +3355,18 @@ gl_drawi(PyObject *self, PyObject *args)
static PyObject *
gl_movei(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- movei( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ movei( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnti long s long s long s */
@@ -3374,18 +3374,18 @@ gl_movei(PyObject *self, PyObject *args)
static PyObject *
gl_pnti(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- pnti( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ pnti( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void newtag long s long s long s */
@@ -3393,18 +3393,18 @@ gl_pnti(PyObject *self, PyObject *args)
static PyObject *
gl_newtag(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- newtag( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ newtag( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdri long s long s long s */
@@ -3412,18 +3412,18 @@ gl_newtag(PyObject *self, PyObject *args)
static PyObject *
gl_pdri(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- pdri( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ pdri( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmvi long s long s long s */
@@ -3431,18 +3431,18 @@ gl_pdri(PyObject *self, PyObject *args)
static PyObject *
gl_pmvi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- pmvi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ pmvi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdri long s long s long s */
@@ -3450,18 +3450,18 @@ gl_pmvi(PyObject *self, PyObject *args)
static PyObject *
gl_rdri(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rdri( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rdri( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmvi long s long s long s */
@@ -3469,18 +3469,18 @@ gl_rdri(PyObject *self, PyObject *args)
static PyObject *
gl_rmvi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rmvi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rmvi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdri long s long s long s */
@@ -3488,18 +3488,18 @@ gl_rmvi(PyObject *self, PyObject *args)
static PyObject *
gl_rpdri(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rpdri( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rpdri( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmvi long s long s long s */
@@ -3507,18 +3507,18 @@ gl_rpdri(PyObject *self, PyObject *args)
static PyObject *
gl_rpmvi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- rpmvi( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ rpmvi( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpti long s long s long s */
@@ -3526,18 +3526,18 @@ gl_rpmvi(PyObject *self, PyObject *args)
static PyObject *
gl_xfpti(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- xfpti( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ xfpti( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circ float s float s float s */
@@ -3545,18 +3545,18 @@ gl_xfpti(PyObject *self, PyObject *args)
static PyObject *
gl_circ(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- circ( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ circ( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circf float s float s float s */
@@ -3564,18 +3564,18 @@ gl_circ(PyObject *self, PyObject *args)
static PyObject *
gl_circf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- circf( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ circf( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmov float s float s float s */
@@ -3583,18 +3583,18 @@ gl_circf(PyObject *self, PyObject *args)
static PyObject *
gl_cmov(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- cmov( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ cmov( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draw float s float s float s */
@@ -3602,18 +3602,18 @@ gl_cmov(PyObject *self, PyObject *args)
static PyObject *
gl_draw(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- draw( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ draw( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void move float s float s float s */
@@ -3621,18 +3621,18 @@ gl_draw(PyObject *self, PyObject *args)
static PyObject *
gl_move(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- move( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ move( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnt float s float s float s */
@@ -3640,18 +3640,18 @@ gl_move(PyObject *self, PyObject *args)
static PyObject *
gl_pnt(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- pnt( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ pnt( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void scale float s float s float s */
@@ -3659,18 +3659,18 @@ gl_pnt(PyObject *self, PyObject *args)
static PyObject *
gl_scale(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- scale( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ scale( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void translate float s float s float s */
@@ -3678,18 +3678,18 @@ gl_scale(PyObject *self, PyObject *args)
static PyObject *
gl_translate(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- translate( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ translate( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdr float s float s float s */
@@ -3697,18 +3697,18 @@ gl_translate(PyObject *self, PyObject *args)
static PyObject *
gl_pdr(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- pdr( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ pdr( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmv float s float s float s */
@@ -3716,18 +3716,18 @@ gl_pdr(PyObject *self, PyObject *args)
static PyObject *
gl_pmv(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- pmv( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ pmv( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdr float s float s float s */
@@ -3735,18 +3735,18 @@ gl_pmv(PyObject *self, PyObject *args)
static PyObject *
gl_rdr(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rdr( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rdr( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmv float s float s float s */
@@ -3754,18 +3754,18 @@ gl_rdr(PyObject *self, PyObject *args)
static PyObject *
gl_rmv(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rmv( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rmv( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdr float s float s float s */
@@ -3773,18 +3773,18 @@ gl_rmv(PyObject *self, PyObject *args)
static PyObject *
gl_rpdr(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rpdr( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rpdr( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmv float s float s float s */
@@ -3792,18 +3792,18 @@ gl_rpdr(PyObject *self, PyObject *args)
static PyObject *
gl_rpmv(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- rpmv( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ rpmv( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt float s float s float s */
@@ -3811,18 +3811,18 @@ gl_rpmv(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- if (!getifloatarg(args, 3, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 3, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 3, 2, &arg3))
- return NULL;
- xfpt( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ if (!getifloatarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 3, 2, &arg3))
+ return NULL;
+ xfpt( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBcolor short s short s short s */
@@ -3830,18 +3830,18 @@ gl_xfpt(PyObject *self, PyObject *args)
static PyObject *
gl_RGBcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- RGBcolor( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ RGBcolor( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBwritemask short s short s short s */
@@ -3849,18 +3849,18 @@ gl_RGBcolor(PyObject *self, PyObject *args)
static PyObject *
gl_RGBwritemask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- RGBwritemask( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ RGBwritemask( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setcursor short s short s short s */
@@ -3868,18 +3868,18 @@ gl_RGBwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_setcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- setcursor( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ setcursor( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void tie short s short s short s */
@@ -3887,18 +3887,18 @@ gl_setcursor(PyObject *self, PyObject *args)
static PyObject *
gl_tie(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- tie( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ tie( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circfs short s short s short s */
@@ -3906,18 +3906,18 @@ gl_tie(PyObject *self, PyObject *args)
static PyObject *
gl_circfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- circfs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ circfs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void circs short s short s short s */
@@ -3925,18 +3925,18 @@ gl_circfs(PyObject *self, PyObject *args)
static PyObject *
gl_circs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- circs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ circs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cmovs short s short s short s */
@@ -3944,18 +3944,18 @@ gl_circs(PyObject *self, PyObject *args)
static PyObject *
gl_cmovs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- cmovs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ cmovs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void draws short s short s short s */
@@ -3963,18 +3963,18 @@ gl_cmovs(PyObject *self, PyObject *args)
static PyObject *
gl_draws(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- draws( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ draws( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void moves short s short s short s */
@@ -3982,18 +3982,18 @@ gl_draws(PyObject *self, PyObject *args)
static PyObject *
gl_moves(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- moves( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ moves( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pdrs short s short s short s */
@@ -4001,18 +4001,18 @@ gl_moves(PyObject *self, PyObject *args)
static PyObject *
gl_pdrs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- pdrs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ pdrs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pmvs short s short s short s */
@@ -4020,18 +4020,18 @@ gl_pdrs(PyObject *self, PyObject *args)
static PyObject *
gl_pmvs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- pmvs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ pmvs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pnts short s short s short s */
@@ -4039,18 +4039,18 @@ gl_pmvs(PyObject *self, PyObject *args)
static PyObject *
gl_pnts(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- pnts( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ pnts( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rdrs short s short s short s */
@@ -4058,18 +4058,18 @@ gl_pnts(PyObject *self, PyObject *args)
static PyObject *
gl_rdrs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rdrs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rdrs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rmvs short s short s short s */
@@ -4077,18 +4077,18 @@ gl_rdrs(PyObject *self, PyObject *args)
static PyObject *
gl_rmvs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rmvs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rmvs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpdrs short s short s short s */
@@ -4096,18 +4096,18 @@ gl_rmvs(PyObject *self, PyObject *args)
static PyObject *
gl_rpdrs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rpdrs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rpdrs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpmvs short s short s short s */
@@ -4115,18 +4115,18 @@ gl_rpdrs(PyObject *self, PyObject *args)
static PyObject *
gl_rpmvs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- rpmvs( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ rpmvs( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpts short s short s short s */
@@ -4134,18 +4134,18 @@ gl_rpmvs(PyObject *self, PyObject *args)
static PyObject *
gl_xfpts(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- xfpts( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ xfpts( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curorigin short s short s short s */
@@ -4153,18 +4153,18 @@ gl_xfpts(PyObject *self, PyObject *args)
static PyObject *
gl_curorigin(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- curorigin( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ curorigin( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cyclemap short s short s short s */
@@ -4172,18 +4172,18 @@ gl_curorigin(PyObject *self, PyObject *args)
static PyObject *
gl_cyclemap(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- if (!getishortarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- cyclemap( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ if (!getishortarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ cyclemap( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void patch float s[4*4] float s[4*4] float s[4*4] */
@@ -4191,18 +4191,18 @@ gl_cyclemap(PyObject *self, PyObject *args)
static PyObject *
gl_patch(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- float arg2 [ 4 ] [ 4 ] ;
- float arg3 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 3, 0, 4 * 4 , (float *) arg1))
- return NULL;
- if (!getifloatarray(args, 3, 1, 4 * 4 , (float *) arg2))
- return NULL;
- if (!getifloatarray(args, 3, 2, 4 * 4 , (float *) arg3))
- return NULL;
- patch( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ float arg2 [ 4 ] [ 4 ] ;
+ float arg3 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 3, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ if (!getifloatarray(args, 3, 1, 4 * 4 , (float *) arg2))
+ return NULL;
+ if (!getifloatarray(args, 3, 2, 4 * 4 , (float *) arg3))
+ return NULL;
+ patch( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf long s float s[3*arg1] u_short s[arg1] */
@@ -4210,25 +4210,25 @@ gl_patch(PyObject *self, PyObject *args)
static PyObject *
gl_splf(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 3 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 2, 0, 3 * arg1 , (float *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 3 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (float(*)[3]) PyMem_NEW(float , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 2, 0, 3 * arg1 , (float *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf2 long s float s[2*arg1] u_short s[arg1] */
@@ -4236,25 +4236,25 @@ gl_splf(PyObject *self, PyObject *args)
static PyObject *
gl_splf2(PyObject *self, PyObject *args)
{
- long arg1 ;
- float (* arg2) [ 2 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 2, 0, 2 * arg1 , (float *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf2( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float (* arg2) [ 2 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (float(*)[2]) PyMem_NEW(float , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 2, 0, 2 * arg1 , (float *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf2( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splfi long s long s[3*arg1] u_short s[arg1] */
@@ -4262,25 +4262,25 @@ gl_splf2(PyObject *self, PyObject *args)
static PyObject *
gl_splfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 3 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 2, 0, 3 * arg1 , (long *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splfi( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 3 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (long(*)[3]) PyMem_NEW(long , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 2, 0, 3 * arg1 , (long *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splfi( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf2i long s long s[2*arg1] u_short s[arg1] */
@@ -4288,25 +4288,25 @@ gl_splfi(PyObject *self, PyObject *args)
static PyObject *
gl_splf2i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long (* arg2) [ 2 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getilongarray(args, 2, 0, 2 * arg1 , (long *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf2i( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long (* arg2) [ 2 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (long(*)[2]) PyMem_NEW(long , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getilongarray(args, 2, 0, 2 * arg1 , (long *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf2i( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splfs long s short s[3*arg1] u_short s[arg1] */
@@ -4314,25 +4314,25 @@ gl_splf2i(PyObject *self, PyObject *args)
static PyObject *
gl_splfs(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 3 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 3;
- if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 0, 3 * arg1 , (short *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splfs( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 3 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 3;
+ if ((arg2 = (short(*)[3]) PyMem_NEW(short , 3 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 0, 3 * arg1 , (short *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splfs( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void splf2s long s short s[2*arg1] u_short s[arg1] */
@@ -4340,25 +4340,25 @@ gl_splfs(PyObject *self, PyObject *args)
static PyObject *
gl_splf2s(PyObject *self, PyObject *args)
{
- long arg1 ;
- short (* arg2) [ 2 ] ;
- unsigned short * arg3 ;
- if (!getilongarraysize(args, 2, 0, &arg1))
- return NULL;
- arg1 = arg1 / 2;
- if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 0, 2 * arg1 , (short *) arg2))
- return NULL;
- if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
- return PyErr_NoMemory();
- if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
- return NULL;
- splf2s( arg1 , arg2 , arg3 );
- PyMem_DEL(arg2);
- PyMem_DEL(arg3);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ short (* arg2) [ 2 ] ;
+ unsigned short * arg3 ;
+ if (!getilongarraysize(args, 2, 0, &arg1))
+ return NULL;
+ arg1 = arg1 / 2;
+ if ((arg2 = (short(*)[2]) PyMem_NEW(short , 2 * arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 0, 2 * arg1 , (short *) arg2))
+ return NULL;
+ if ((arg3 = PyMem_NEW(unsigned short , arg1 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getishortarray(args, 2, 1, arg1 , (short *) arg3))
+ return NULL;
+ splf2s( arg1 , arg2 , arg3 );
+ PyMem_DEL(arg2);
+ PyMem_DEL(arg3);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rpatch float s[4*4] float s[4*4] float s[4*4] float s[4*4] */
@@ -4366,21 +4366,21 @@ gl_splf2s(PyObject *self, PyObject *args)
static PyObject *
gl_rpatch(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] [ 4 ] ;
- float arg2 [ 4 ] [ 4 ] ;
- float arg3 [ 4 ] [ 4 ] ;
- float arg4 [ 4 ] [ 4 ] ;
- if (!getifloatarray(args, 4, 0, 4 * 4 , (float *) arg1))
- return NULL;
- if (!getifloatarray(args, 4, 1, 4 * 4 , (float *) arg2))
- return NULL;
- if (!getifloatarray(args, 4, 2, 4 * 4 , (float *) arg3))
- return NULL;
- if (!getifloatarray(args, 4, 3, 4 * 4 , (float *) arg4))
- return NULL;
- rpatch( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] [ 4 ] ;
+ float arg2 [ 4 ] [ 4 ] ;
+ float arg3 [ 4 ] [ 4 ] ;
+ float arg4 [ 4 ] [ 4 ] ;
+ if (!getifloatarray(args, 4, 0, 4 * 4 , (float *) arg1))
+ return NULL;
+ if (!getifloatarray(args, 4, 1, 4 * 4 , (float *) arg2))
+ return NULL;
+ if (!getifloatarray(args, 4, 2, 4 * 4 , (float *) arg3))
+ return NULL;
+ if (!getifloatarray(args, 4, 3, 4 * 4 , (float *) arg4))
+ return NULL;
+ rpatch( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ortho2 float s float s float s float s */
@@ -4388,21 +4388,21 @@ gl_rpatch(PyObject *self, PyObject *args)
static PyObject *
gl_ortho2(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- ortho2( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ ortho2( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rect float s float s float s float s */
@@ -4410,21 +4410,21 @@ gl_ortho2(PyObject *self, PyObject *args)
static PyObject *
gl_rect(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- rect( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ rect( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectf float s float s float s float s */
@@ -4432,21 +4432,21 @@ gl_rect(PyObject *self, PyObject *args)
static PyObject *
gl_rectf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- rectf( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ rectf( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt4 float s float s float s float s */
@@ -4454,21 +4454,21 @@ gl_rectf(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt4(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- xfpt4( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ xfpt4( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void textport short s short s short s short s */
@@ -4476,21 +4476,21 @@ gl_xfpt4(PyObject *self, PyObject *args)
static PyObject *
gl_textport(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- textport( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ textport( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void mapcolor short s short s short s short s */
@@ -4498,21 +4498,21 @@ gl_textport(PyObject *self, PyObject *args)
static PyObject *
gl_mapcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- mapcolor( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ mapcolor( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void scrmask short s short s short s short s */
@@ -4520,21 +4520,21 @@ gl_mapcolor(PyObject *self, PyObject *args)
static PyObject *
gl_scrmask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- scrmask( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ scrmask( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setvaluator short s short s short s short s */
@@ -4542,21 +4542,21 @@ gl_scrmask(PyObject *self, PyObject *args)
static PyObject *
gl_setvaluator(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- setvaluator( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ setvaluator( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void viewport short s short s short s short s */
@@ -4564,21 +4564,21 @@ gl_setvaluator(PyObject *self, PyObject *args)
static PyObject *
gl_viewport(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- viewport( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ viewport( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void shaderange short s short s short s short s */
@@ -4586,21 +4586,21 @@ gl_viewport(PyObject *self, PyObject *args)
static PyObject *
gl_shaderange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- shaderange( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ shaderange( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt4s short s short s short s short s */
@@ -4608,21 +4608,21 @@ gl_shaderange(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt4s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- xfpt4s( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ xfpt4s( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectfi long s long s long s long s */
@@ -4630,21 +4630,21 @@ gl_xfpt4s(PyObject *self, PyObject *args)
static PyObject *
gl_rectfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- rectfi( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ rectfi( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void recti long s long s long s long s */
@@ -4652,21 +4652,21 @@ gl_rectfi(PyObject *self, PyObject *args)
static PyObject *
gl_recti(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- recti( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ recti( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void xfpt4i long s long s long s long s */
@@ -4674,21 +4674,21 @@ gl_recti(PyObject *self, PyObject *args)
static PyObject *
gl_xfpt4i(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- xfpt4i( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ xfpt4i( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void prefposition long s long s long s long s */
@@ -4696,21 +4696,21 @@ gl_xfpt4i(PyObject *self, PyObject *args)
static PyObject *
gl_prefposition(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- prefposition( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ prefposition( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arc float s float s float s short s short s */
@@ -4718,24 +4718,24 @@ gl_prefposition(PyObject *self, PyObject *args)
static PyObject *
gl_arc(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getifloatarg(args, 5, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 5, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arc( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getifloatarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arc( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcf float s float s float s short s short s */
@@ -4743,24 +4743,24 @@ gl_arc(PyObject *self, PyObject *args)
static PyObject *
gl_arcf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getifloatarg(args, 5, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 5, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcf( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getifloatarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcf( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcfi long s long s long s short s short s */
@@ -4768,24 +4768,24 @@ gl_arcf(PyObject *self, PyObject *args)
static PyObject *
gl_arcfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getilongarg(args, 5, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 5, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcfi( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getilongarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcfi( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arci long s long s long s short s short s */
@@ -4793,24 +4793,24 @@ gl_arcfi(PyObject *self, PyObject *args)
static PyObject *
gl_arci(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getilongarg(args, 5, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 5, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arci( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getilongarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arci( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bbox2 short s short s float s float s float s float s */
@@ -4818,27 +4818,27 @@ gl_arci(PyObject *self, PyObject *args)
static PyObject *
gl_bbox2(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 6, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 6, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 6, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 6, 5, &arg6))
- return NULL;
- bbox2( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 6, 5, &arg6))
+ return NULL;
+ bbox2( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bbox2i short s short s long s long s long s long s */
@@ -4846,27 +4846,27 @@ gl_bbox2(PyObject *self, PyObject *args)
static PyObject *
gl_bbox2i(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- long arg3 ;
- long arg4 ;
- long arg5 ;
- long arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 6, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 6, 3, &arg4))
- return NULL;
- if (!getilongarg(args, 6, 4, &arg5))
- return NULL;
- if (!getilongarg(args, 6, 5, &arg6))
- return NULL;
- bbox2i( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ long arg3 ;
+ long arg4 ;
+ long arg5 ;
+ long arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getilongarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getilongarg(args, 6, 5, &arg6))
+ return NULL;
+ bbox2i( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bbox2s short s short s short s short s short s short s */
@@ -4874,27 +4874,27 @@ gl_bbox2i(PyObject *self, PyObject *args)
static PyObject *
gl_bbox2s(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 6, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 6, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 6, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 6, 5, &arg6))
- return NULL;
- bbox2s( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 6, 5, &arg6))
+ return NULL;
+ bbox2s( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blink short s short s short s short s short s */
@@ -4902,24 +4902,24 @@ gl_bbox2s(PyObject *self, PyObject *args)
static PyObject *
gl_blink(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getishortarg(args, 5, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 5, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- blink( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getishortarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ blink( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void ortho float s float s float s float s float s float s */
@@ -4927,27 +4927,27 @@ gl_blink(PyObject *self, PyObject *args)
static PyObject *
gl_ortho(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- if (!getifloatarg(args, 6, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 6, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 6, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 6, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 6, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 6, 5, &arg6))
- return NULL;
- ortho( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ if (!getifloatarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 6, 5, &arg6))
+ return NULL;
+ ortho( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void window float s float s float s float s float s float s */
@@ -4955,27 +4955,27 @@ gl_ortho(PyObject *self, PyObject *args)
static PyObject *
gl_window(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- if (!getifloatarg(args, 6, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 6, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 6, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 6, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 6, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 6, 5, &arg6))
- return NULL;
- window( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ if (!getifloatarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 6, 5, &arg6))
+ return NULL;
+ window( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lookat float s float s float s float s float s float s short s */
@@ -4983,30 +4983,30 @@ gl_window(PyObject *self, PyObject *args)
static PyObject *
gl_lookat(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- short arg7 ;
- if (!getifloatarg(args, 7, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 7, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 7, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 7, 3, &arg4))
- return NULL;
- if (!getifloatarg(args, 7, 4, &arg5))
- return NULL;
- if (!getifloatarg(args, 7, 5, &arg6))
- return NULL;
- if (!getishortarg(args, 7, 6, &arg7))
- return NULL;
- lookat( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ short arg7 ;
+ if (!getifloatarg(args, 7, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 7, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 7, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 7, 3, &arg4))
+ return NULL;
+ if (!getifloatarg(args, 7, 4, &arg5))
+ return NULL;
+ if (!getifloatarg(args, 7, 5, &arg6))
+ return NULL;
+ if (!getishortarg(args, 7, 6, &arg7))
+ return NULL;
+ lookat( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void perspective short s float s float s float s */
@@ -5014,21 +5014,21 @@ gl_lookat(PyObject *self, PyObject *args)
static PyObject *
gl_perspective(PyObject *self, PyObject *args)
{
- short arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- perspective( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ perspective( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void polarview float s short s short s short s */
@@ -5036,21 +5036,21 @@ gl_perspective(PyObject *self, PyObject *args)
static PyObject *
gl_polarview(PyObject *self, PyObject *args)
{
- float arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- polarview( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ polarview( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcfs short s short s short s short s short s */
@@ -5058,24 +5058,24 @@ gl_polarview(PyObject *self, PyObject *args)
static PyObject *
gl_arcfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getishortarg(args, 5, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 5, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcfs( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getishortarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcfs( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void arcs short s short s short s short s short s */
@@ -5083,24 +5083,24 @@ gl_arcfs(PyObject *self, PyObject *args)
static PyObject *
gl_arcs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- if (!getishortarg(args, 5, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 5, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 5, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 5, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 5, 4, &arg5))
- return NULL;
- arcs( arg1 , arg2 , arg3 , arg4 , arg5 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ if (!getishortarg(args, 5, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 5, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 5, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 5, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 5, 4, &arg5))
+ return NULL;
+ arcs( arg1 , arg2 , arg3 , arg4 , arg5 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectcopy short s short s short s short s short s short s */
@@ -5108,27 +5108,27 @@ gl_arcs(PyObject *self, PyObject *args)
static PyObject *
gl_rectcopy(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- if (!getishortarg(args, 6, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 6, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 6, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 6, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 6, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 6, 5, &arg6))
- return NULL;
- rectcopy( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ if (!getishortarg(args, 6, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 6, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 6, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 6, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 6, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 6, 5, &arg6))
+ return NULL;
+ rectcopy( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBcursor short s short s short s short s short s short s short s */
@@ -5136,30 +5136,30 @@ gl_rectcopy(PyObject *self, PyObject *args)
static PyObject *
gl_RGBcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- short arg7 ;
- if (!getishortarg(args, 7, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 7, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 7, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 7, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 7, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 7, 5, &arg6))
- return NULL;
- if (!getishortarg(args, 7, 6, &arg7))
- return NULL;
- RGBcursor( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ short arg7 ;
+ if (!getishortarg(args, 7, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 7, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 7, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 7, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 7, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 7, 5, &arg6))
+ return NULL;
+ if (!getishortarg(args, 7, 6, &arg7))
+ return NULL;
+ RGBcursor( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long getbutton short s */
@@ -5167,12 +5167,12 @@ gl_RGBcursor(PyObject *self, PyObject *args)
static PyObject *
gl_getbutton(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- retval = getbutton( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getbutton( arg1 );
+ return mknewlongobject(retval);
}
/* long getcmmode */
@@ -5180,9 +5180,9 @@ gl_getbutton(PyObject *self, PyObject *args)
static PyObject *
gl_getcmmode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getcmmode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getcmmode( );
+ return mknewlongobject(retval);
}
/* long getlsbackup */
@@ -5190,9 +5190,9 @@ gl_getcmmode(PyObject *self, PyObject *args)
static PyObject *
gl_getlsbackup(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlsbackup( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlsbackup( );
+ return mknewlongobject(retval);
}
/* long getresetls */
@@ -5200,9 +5200,9 @@ gl_getlsbackup(PyObject *self, PyObject *args)
static PyObject *
gl_getresetls(PyObject *self, PyObject *args)
{
- long retval;
- retval = getresetls( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getresetls( );
+ return mknewlongobject(retval);
}
/* long getdcm */
@@ -5210,9 +5210,9 @@ gl_getresetls(PyObject *self, PyObject *args)
static PyObject *
gl_getdcm(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdcm( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdcm( );
+ return mknewlongobject(retval);
}
/* long getzbuffer */
@@ -5220,9 +5220,9 @@ gl_getdcm(PyObject *self, PyObject *args)
static PyObject *
gl_getzbuffer(PyObject *self, PyObject *args)
{
- long retval;
- retval = getzbuffer( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getzbuffer( );
+ return mknewlongobject(retval);
}
/* long ismex */
@@ -5230,9 +5230,9 @@ gl_getzbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_ismex(PyObject *self, PyObject *args)
{
- long retval;
- retval = ismex( );
- return mknewlongobject(retval);
+ long retval;
+ retval = ismex( );
+ return mknewlongobject(retval);
}
/* long isobj long s */
@@ -5240,12 +5240,12 @@ gl_ismex(PyObject *self, PyObject *args)
static PyObject *
gl_isobj(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = isobj( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = isobj( arg1 );
+ return mknewlongobject(retval);
}
/* long isqueued short s */
@@ -5253,12 +5253,12 @@ gl_isobj(PyObject *self, PyObject *args)
static PyObject *
gl_isqueued(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- retval = isqueued( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = isqueued( arg1 );
+ return mknewlongobject(retval);
}
/* long istag long s */
@@ -5266,12 +5266,12 @@ gl_isqueued(PyObject *self, PyObject *args)
static PyObject *
gl_istag(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = istag( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = istag( arg1 );
+ return mknewlongobject(retval);
}
/* long genobj */
@@ -5279,9 +5279,9 @@ gl_istag(PyObject *self, PyObject *args)
static PyObject *
gl_genobj(PyObject *self, PyObject *args)
{
- long retval;
- retval = genobj( );
- return mknewlongobject(retval);
+ long retval;
+ retval = genobj( );
+ return mknewlongobject(retval);
}
/* long gentag */
@@ -5289,9 +5289,9 @@ gl_genobj(PyObject *self, PyObject *args)
static PyObject *
gl_gentag(PyObject *self, PyObject *args)
{
- long retval;
- retval = gentag( );
- return mknewlongobject(retval);
+ long retval;
+ retval = gentag( );
+ return mknewlongobject(retval);
}
/* long getbuffer */
@@ -5299,9 +5299,9 @@ gl_gentag(PyObject *self, PyObject *args)
static PyObject *
gl_getbuffer(PyObject *self, PyObject *args)
{
- long retval;
- retval = getbuffer( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getbuffer( );
+ return mknewlongobject(retval);
}
/* long getcolor */
@@ -5309,9 +5309,9 @@ gl_getbuffer(PyObject *self, PyObject *args)
static PyObject *
gl_getcolor(PyObject *self, PyObject *args)
{
- long retval;
- retval = getcolor( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getcolor( );
+ return mknewlongobject(retval);
}
/* long getdisplaymode */
@@ -5319,9 +5319,9 @@ gl_getcolor(PyObject *self, PyObject *args)
static PyObject *
gl_getdisplaymode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdisplaymode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdisplaymode( );
+ return mknewlongobject(retval);
}
/* long getfont */
@@ -5329,9 +5329,9 @@ gl_getdisplaymode(PyObject *self, PyObject *args)
static PyObject *
gl_getfont(PyObject *self, PyObject *args)
{
- long retval;
- retval = getfont( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getfont( );
+ return mknewlongobject(retval);
}
/* long getheight */
@@ -5339,9 +5339,9 @@ gl_getfont(PyObject *self, PyObject *args)
static PyObject *
gl_getheight(PyObject *self, PyObject *args)
{
- long retval;
- retval = getheight( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getheight( );
+ return mknewlongobject(retval);
}
/* long gethitcode */
@@ -5349,9 +5349,9 @@ gl_getheight(PyObject *self, PyObject *args)
static PyObject *
gl_gethitcode(PyObject *self, PyObject *args)
{
- long retval;
- retval = gethitcode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = gethitcode( );
+ return mknewlongobject(retval);
}
/* long getlstyle */
@@ -5359,9 +5359,9 @@ gl_gethitcode(PyObject *self, PyObject *args)
static PyObject *
gl_getlstyle(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlstyle( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlstyle( );
+ return mknewlongobject(retval);
}
/* long getlwidth */
@@ -5369,9 +5369,9 @@ gl_getlstyle(PyObject *self, PyObject *args)
static PyObject *
gl_getlwidth(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlwidth( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlwidth( );
+ return mknewlongobject(retval);
}
/* long getmap */
@@ -5379,9 +5379,9 @@ gl_getlwidth(PyObject *self, PyObject *args)
static PyObject *
gl_getmap(PyObject *self, PyObject *args)
{
- long retval;
- retval = getmap( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getmap( );
+ return mknewlongobject(retval);
}
/* long getplanes */
@@ -5389,9 +5389,9 @@ gl_getmap(PyObject *self, PyObject *args)
static PyObject *
gl_getplanes(PyObject *self, PyObject *args)
{
- long retval;
- retval = getplanes( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getplanes( );
+ return mknewlongobject(retval);
}
/* long getwritemask */
@@ -5399,9 +5399,9 @@ gl_getplanes(PyObject *self, PyObject *args)
static PyObject *
gl_getwritemask(PyObject *self, PyObject *args)
{
- long retval;
- retval = getwritemask( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getwritemask( );
+ return mknewlongobject(retval);
}
/* long qtest */
@@ -5409,9 +5409,9 @@ gl_getwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_qtest(PyObject *self, PyObject *args)
{
- long retval;
- retval = qtest( );
- return mknewlongobject(retval);
+ long retval;
+ retval = qtest( );
+ return mknewlongobject(retval);
}
/* long getlsrepeat */
@@ -5419,9 +5419,9 @@ gl_qtest(PyObject *self, PyObject *args)
static PyObject *
gl_getlsrepeat(PyObject *self, PyObject *args)
{
- long retval;
- retval = getlsrepeat( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getlsrepeat( );
+ return mknewlongobject(retval);
}
/* long getmonitor */
@@ -5429,9 +5429,9 @@ gl_getlsrepeat(PyObject *self, PyObject *args)
static PyObject *
gl_getmonitor(PyObject *self, PyObject *args)
{
- long retval;
- retval = getmonitor( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getmonitor( );
+ return mknewlongobject(retval);
}
/* long getopenobj */
@@ -5439,9 +5439,9 @@ gl_getmonitor(PyObject *self, PyObject *args)
static PyObject *
gl_getopenobj(PyObject *self, PyObject *args)
{
- long retval;
- retval = getopenobj( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getopenobj( );
+ return mknewlongobject(retval);
}
/* long getpattern */
@@ -5449,9 +5449,9 @@ gl_getopenobj(PyObject *self, PyObject *args)
static PyObject *
gl_getpattern(PyObject *self, PyObject *args)
{
- long retval;
- retval = getpattern( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getpattern( );
+ return mknewlongobject(retval);
}
/* long winget */
@@ -5459,9 +5459,9 @@ gl_getpattern(PyObject *self, PyObject *args)
static PyObject *
gl_winget(PyObject *self, PyObject *args)
{
- long retval;
- retval = winget( );
- return mknewlongobject(retval);
+ long retval;
+ retval = winget( );
+ return mknewlongobject(retval);
}
/* long winattach */
@@ -5469,9 +5469,9 @@ gl_winget(PyObject *self, PyObject *args)
static PyObject *
gl_winattach(PyObject *self, PyObject *args)
{
- long retval;
- retval = winattach( );
- return mknewlongobject(retval);
+ long retval;
+ retval = winattach( );
+ return mknewlongobject(retval);
}
/* long getothermonitor */
@@ -5479,9 +5479,9 @@ gl_winattach(PyObject *self, PyObject *args)
static PyObject *
gl_getothermonitor(PyObject *self, PyObject *args)
{
- long retval;
- retval = getothermonitor( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getothermonitor( );
+ return mknewlongobject(retval);
}
/* long newpup */
@@ -5489,9 +5489,9 @@ gl_getothermonitor(PyObject *self, PyObject *args)
static PyObject *
gl_newpup(PyObject *self, PyObject *args)
{
- long retval;
- retval = newpup( );
- return mknewlongobject(retval);
+ long retval;
+ retval = newpup( );
+ return mknewlongobject(retval);
}
/* long getvaluator short s */
@@ -5499,12 +5499,12 @@ gl_newpup(PyObject *self, PyObject *args)
static PyObject *
gl_getvaluator(PyObject *self, PyObject *args)
{
- long retval;
- short arg1 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- retval = getvaluator( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ short arg1 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getvaluator( arg1 );
+ return mknewlongobject(retval);
}
/* void winset long s */
@@ -5512,12 +5512,12 @@ gl_getvaluator(PyObject *self, PyObject *args)
static PyObject *
gl_winset(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- winset( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ winset( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long dopup long s */
@@ -5525,12 +5525,12 @@ gl_winset(PyObject *self, PyObject *args)
static PyObject *
gl_dopup(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = dopup( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = dopup( arg1 );
+ return mknewlongobject(retval);
}
/* void getdepth short r short r */
@@ -5538,15 +5538,15 @@ gl_dopup(PyObject *self, PyObject *args)
static PyObject *
gl_getdepth(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- getdepth( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ getdepth( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ return v;
+ }
}
/* void getcpos short r short r */
@@ -5554,15 +5554,15 @@ gl_getdepth(PyObject *self, PyObject *args)
static PyObject *
gl_getcpos(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- getcpos( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ getcpos( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ return v;
+ }
}
/* void getsize long r long r */
@@ -5570,15 +5570,15 @@ gl_getcpos(PyObject *self, PyObject *args)
static PyObject *
gl_getsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- getsize( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewlongobject(arg1));
- PyTuple_SetItem(v, 1, mknewlongobject(arg2));
- return v;
- }
+ long arg1 ;
+ long arg2 ;
+ getsize( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewlongobject(arg1));
+ PyTuple_SetItem(v, 1, mknewlongobject(arg2));
+ return v;
+ }
}
/* void getorigin long r long r */
@@ -5586,15 +5586,15 @@ gl_getsize(PyObject *self, PyObject *args)
static PyObject *
gl_getorigin(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- getorigin( & arg1 , & arg2 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewlongobject(arg1));
- PyTuple_SetItem(v, 1, mknewlongobject(arg2));
- return v;
- }
+ long arg1 ;
+ long arg2 ;
+ getorigin( & arg1 , & arg2 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewlongobject(arg1));
+ PyTuple_SetItem(v, 1, mknewlongobject(arg2));
+ return v;
+ }
}
/* void getviewport short r short r short r short r */
@@ -5602,19 +5602,19 @@ gl_getorigin(PyObject *self, PyObject *args)
static PyObject *
gl_getviewport(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- getviewport( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- PyTuple_SetItem(v, 3, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ getviewport( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 3, mknewshortobject(arg4));
+ return v;
+ }
}
/* void gettp short r short r short r short r */
@@ -5622,19 +5622,19 @@ gl_getviewport(PyObject *self, PyObject *args)
static PyObject *
gl_gettp(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- gettp( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- PyTuple_SetItem(v, 3, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ gettp( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 3, mknewshortobject(arg4));
+ return v;
+ }
}
/* void getgpos float r float r float r float r */
@@ -5642,19 +5642,19 @@ gl_gettp(PyObject *self, PyObject *args)
static PyObject *
gl_getgpos(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- getgpos( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewfloatobject(arg1));
- PyTuple_SetItem(v, 1, mknewfloatobject(arg2));
- PyTuple_SetItem(v, 2, mknewfloatobject(arg3));
- PyTuple_SetItem(v, 3, mknewfloatobject(arg4));
- return v;
- }
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ getgpos( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewfloatobject(arg1));
+ PyTuple_SetItem(v, 1, mknewfloatobject(arg2));
+ PyTuple_SetItem(v, 2, mknewfloatobject(arg3));
+ PyTuple_SetItem(v, 3, mknewfloatobject(arg4));
+ return v;
+ }
}
/* void winposition long s long s long s long s */
@@ -5662,21 +5662,21 @@ gl_getgpos(PyObject *self, PyObject *args)
static PyObject *
gl_winposition(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- winposition( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ winposition( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gRGBcolor short r short r short r */
@@ -5684,17 +5684,17 @@ gl_winposition(PyObject *self, PyObject *args)
static PyObject *
gl_gRGBcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- gRGBcolor( & arg1 , & arg2 , & arg3 );
- { PyObject *v = PyTuple_New( 3 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ gRGBcolor( & arg1 , & arg2 , & arg3 );
+ { PyObject *v = PyTuple_New( 3 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ return v;
+ }
}
/* void gRGBmask short r short r short r */
@@ -5702,17 +5702,17 @@ gl_gRGBcolor(PyObject *self, PyObject *args)
static PyObject *
gl_gRGBmask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- gRGBmask( & arg1 , & arg2 , & arg3 );
- { PyObject *v = PyTuple_New( 3 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ gRGBmask( & arg1 , & arg2 , & arg3 );
+ { PyObject *v = PyTuple_New( 3 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ return v;
+ }
}
/* void getscrmask short r short r short r short r */
@@ -5720,19 +5720,19 @@ gl_gRGBmask(PyObject *self, PyObject *args)
static PyObject *
gl_getscrmask(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- getscrmask( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject(arg2));
- PyTuple_SetItem(v, 2, mknewshortobject(arg3));
- PyTuple_SetItem(v, 3, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ getscrmask( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 3, mknewshortobject(arg4));
+ return v;
+ }
}
/* void getmcolor short s short r short r short r */
@@ -5740,20 +5740,20 @@ gl_getscrmask(PyObject *self, PyObject *args)
static PyObject *
gl_getmcolor(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 1, 0, &arg1))
- return NULL;
- getmcolor( arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 3 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg2));
- PyTuple_SetItem(v, 1, mknewshortobject(arg3));
- PyTuple_SetItem(v, 2, mknewshortobject(arg4));
- return v;
- }
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 1, 0, &arg1))
+ return NULL;
+ getmcolor( arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 3 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg2));
+ PyTuple_SetItem(v, 1, mknewshortobject(arg3));
+ PyTuple_SetItem(v, 2, mknewshortobject(arg4));
+ return v;
+ }
}
/* void mapw long s short s short s float r float r float r float r float r float r */
@@ -5761,32 +5761,32 @@ gl_getmcolor(PyObject *self, PyObject *args)
static PyObject *
gl_mapw(PyObject *self, PyObject *args)
{
- long arg1 ;
- short arg2 ;
- short arg3 ;
- float arg4 ;
- float arg5 ;
- float arg6 ;
- float arg7 ;
- float arg8 ;
- float arg9 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- mapw( arg1 , arg2 , arg3 , & arg4 , & arg5 , & arg6 , & arg7 , & arg8 , & arg9 );
- { PyObject *v = PyTuple_New( 6 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
- PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
- PyTuple_SetItem(v, 2, mknewfloatobject(arg6));
- PyTuple_SetItem(v, 3, mknewfloatobject(arg7));
- PyTuple_SetItem(v, 4, mknewfloatobject(arg8));
- PyTuple_SetItem(v, 5, mknewfloatobject(arg9));
- return v;
- }
+ long arg1 ;
+ short arg2 ;
+ short arg3 ;
+ float arg4 ;
+ float arg5 ;
+ float arg6 ;
+ float arg7 ;
+ float arg8 ;
+ float arg9 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ mapw( arg1 , arg2 , arg3 , & arg4 , & arg5 , & arg6 , & arg7 , & arg8 , & arg9 );
+ { PyObject *v = PyTuple_New( 6 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
+ PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
+ PyTuple_SetItem(v, 2, mknewfloatobject(arg6));
+ PyTuple_SetItem(v, 3, mknewfloatobject(arg7));
+ PyTuple_SetItem(v, 4, mknewfloatobject(arg8));
+ PyTuple_SetItem(v, 5, mknewfloatobject(arg9));
+ return v;
+ }
}
/* void mapw2 long s short s short s float r float r */
@@ -5794,24 +5794,24 @@ gl_mapw(PyObject *self, PyObject *args)
static PyObject *
gl_mapw2(PyObject *self, PyObject *args)
{
- long arg1 ;
- short arg2 ;
- short arg3 ;
- float arg4 ;
- float arg5 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 3, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 3, 2, &arg3))
- return NULL;
- mapw2( arg1 , arg2 , arg3 , & arg4 , & arg5 );
- { PyObject *v = PyTuple_New( 2 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
- PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
- return v;
- }
+ long arg1 ;
+ short arg2 ;
+ short arg3 ;
+ float arg4 ;
+ float arg5 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 3, 2, &arg3))
+ return NULL;
+ mapw2( arg1 , arg2 , arg3 , & arg4 , & arg5 );
+ { PyObject *v = PyTuple_New( 2 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewfloatobject(arg4));
+ PyTuple_SetItem(v, 1, mknewfloatobject(arg5));
+ return v;
+ }
}
/* void getcursor short r u_short r u_short r long r */
@@ -5819,19 +5819,19 @@ gl_mapw2(PyObject *self, PyObject *args)
static PyObject *
gl_getcursor(PyObject *self, PyObject *args)
{
- short arg1 ;
- unsigned short arg2 ;
- unsigned short arg3 ;
- long arg4 ;
- getcursor( & arg1 , & arg2 , & arg3 , & arg4 );
- { PyObject *v = PyTuple_New( 4 );
- if (v == NULL) return NULL;
- PyTuple_SetItem(v, 0, mknewshortobject(arg1));
- PyTuple_SetItem(v, 1, mknewshortobject((short) arg2));
- PyTuple_SetItem(v, 2, mknewshortobject((short) arg3));
- PyTuple_SetItem(v, 3, mknewlongobject(arg4));
- return v;
- }
+ short arg1 ;
+ unsigned short arg2 ;
+ unsigned short arg3 ;
+ long arg4 ;
+ getcursor( & arg1 , & arg2 , & arg3 , & arg4 );
+ { PyObject *v = PyTuple_New( 4 );
+ if (v == NULL) return NULL;
+ PyTuple_SetItem(v, 0, mknewshortobject(arg1));
+ PyTuple_SetItem(v, 1, mknewshortobject((short) arg2));
+ PyTuple_SetItem(v, 2, mknewshortobject((short) arg3));
+ PyTuple_SetItem(v, 3, mknewlongobject(arg4));
+ return v;
+ }
}
/* void cmode */
@@ -5839,9 +5839,9 @@ gl_getcursor(PyObject *self, PyObject *args)
static PyObject *
gl_cmode(PyObject *self, PyObject *args)
{
- cmode( );
- Py_INCREF(Py_None);
- return Py_None;
+ cmode( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void concave long s */
@@ -5849,12 +5849,12 @@ gl_cmode(PyObject *self, PyObject *args)
static PyObject *
gl_concave(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- concave( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ concave( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void curstype long s */
@@ -5862,12 +5862,12 @@ gl_concave(PyObject *self, PyObject *args)
static PyObject *
gl_curstype(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- curstype( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ curstype( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void drawmode long s */
@@ -5875,12 +5875,12 @@ gl_curstype(PyObject *self, PyObject *args)
static PyObject *
gl_drawmode(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- drawmode( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ drawmode( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void gammaramp short s[256] short s[256] short s[256] */
@@ -5888,18 +5888,18 @@ gl_drawmode(PyObject *self, PyObject *args)
static PyObject *
gl_gammaramp(PyObject *self, PyObject *args)
{
- short arg1 [ 256 ] ;
- short arg2 [ 256 ] ;
- short arg3 [ 256 ] ;
- if (!getishortarray(args, 3, 0, 256 , arg1))
- return NULL;
- if (!getishortarray(args, 3, 1, 256 , arg2))
- return NULL;
- if (!getishortarray(args, 3, 2, 256 , arg3))
- return NULL;
- gammaramp( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 256 ] ;
+ short arg2 [ 256 ] ;
+ short arg3 [ 256 ] ;
+ if (!getishortarray(args, 3, 0, 256 , arg1))
+ return NULL;
+ if (!getishortarray(args, 3, 1, 256 , arg2))
+ return NULL;
+ if (!getishortarray(args, 3, 2, 256 , arg3))
+ return NULL;
+ gammaramp( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long getbackface */
@@ -5907,9 +5907,9 @@ gl_gammaramp(PyObject *self, PyObject *args)
static PyObject *
gl_getbackface(PyObject *self, PyObject *args)
{
- long retval;
- retval = getbackface( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getbackface( );
+ return mknewlongobject(retval);
}
/* long getdescender */
@@ -5917,9 +5917,9 @@ gl_getbackface(PyObject *self, PyObject *args)
static PyObject *
gl_getdescender(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdescender( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdescender( );
+ return mknewlongobject(retval);
}
/* long getdrawmode */
@@ -5927,9 +5927,9 @@ gl_getdescender(PyObject *self, PyObject *args)
static PyObject *
gl_getdrawmode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getdrawmode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getdrawmode( );
+ return mknewlongobject(retval);
}
/* long getmmode */
@@ -5937,9 +5937,9 @@ gl_getdrawmode(PyObject *self, PyObject *args)
static PyObject *
gl_getmmode(PyObject *self, PyObject *args)
{
- long retval;
- retval = getmmode( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getmmode( );
+ return mknewlongobject(retval);
}
/* long getsm */
@@ -5947,9 +5947,9 @@ gl_getmmode(PyObject *self, PyObject *args)
static PyObject *
gl_getsm(PyObject *self, PyObject *args)
{
- long retval;
- retval = getsm( );
- return mknewlongobject(retval);
+ long retval;
+ retval = getsm( );
+ return mknewlongobject(retval);
}
/* long getvideo long s */
@@ -5957,12 +5957,12 @@ gl_getsm(PyObject *self, PyObject *args)
static PyObject *
gl_getvideo(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = getvideo( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getvideo( arg1 );
+ return mknewlongobject(retval);
}
/* void imakebackground */
@@ -5970,9 +5970,9 @@ gl_getvideo(PyObject *self, PyObject *args)
static PyObject *
gl_imakebackground(PyObject *self, PyObject *args)
{
- imakebackground( );
- Py_INCREF(Py_None);
- return Py_None;
+ imakebackground( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lmbind short s short s */
@@ -5980,15 +5980,15 @@ gl_imakebackground(PyObject *self, PyObject *args)
static PyObject *
gl_lmbind(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- if (!getishortarg(args, 2, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 2, 1, &arg2))
- return NULL;
- lmbind( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ if (!getishortarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 2, 1, &arg2))
+ return NULL;
+ lmbind( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lmdef long s long s long s float s[arg3] */
@@ -5996,24 +5996,24 @@ gl_lmbind(PyObject *self, PyObject *args)
static PyObject *
gl_lmdef(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- float * arg4 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarraysize(args, 3, 2, &arg3))
- return NULL;
- if ((arg4 = PyMem_NEW(float , arg3 )) == NULL)
- return PyErr_NoMemory();
- if (!getifloatarray(args, 3, 2, arg3 , arg4))
- return NULL;
- lmdef( arg1 , arg2 , arg3 , arg4 );
- PyMem_DEL(arg4);
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ float * arg4 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarraysize(args, 3, 2, &arg3))
+ return NULL;
+ if ((arg4 = PyMem_NEW(float , arg3 )) == NULL)
+ return PyErr_NoMemory();
+ if (!getifloatarray(args, 3, 2, arg3 , arg4))
+ return NULL;
+ lmdef( arg1 , arg2 , arg3 , arg4 );
+ PyMem_DEL(arg4);
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void mmode long s */
@@ -6021,12 +6021,12 @@ gl_lmdef(PyObject *self, PyObject *args)
static PyObject *
gl_mmode(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- mmode( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ mmode( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void normal float s[3] */
@@ -6034,12 +6034,12 @@ gl_mmode(PyObject *self, PyObject *args)
static PyObject *
gl_normal(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- normal( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ normal( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void overlay long s */
@@ -6047,12 +6047,12 @@ gl_normal(PyObject *self, PyObject *args)
static PyObject *
gl_overlay(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- overlay( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ overlay( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void RGBrange short s short s short s short s short s short s short s short s */
@@ -6060,33 +6060,33 @@ gl_overlay(PyObject *self, PyObject *args)
static PyObject *
gl_RGBrange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- short arg7 ;
- short arg8 ;
- if (!getishortarg(args, 8, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 8, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 8, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 8, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 8, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 8, 5, &arg6))
- return NULL;
- if (!getishortarg(args, 8, 6, &arg7))
- return NULL;
- if (!getishortarg(args, 8, 7, &arg8))
- return NULL;
- RGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ short arg7 ;
+ short arg8 ;
+ if (!getishortarg(args, 8, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 8, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 8, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 8, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 8, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 8, 5, &arg6))
+ return NULL;
+ if (!getishortarg(args, 8, 6, &arg7))
+ return NULL;
+ if (!getishortarg(args, 8, 7, &arg8))
+ return NULL;
+ RGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setvideo long s long s */
@@ -6094,15 +6094,15 @@ gl_RGBrange(PyObject *self, PyObject *args)
static PyObject *
gl_setvideo(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- setvideo( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ setvideo( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void shademodel long s */
@@ -6110,12 +6110,12 @@ gl_setvideo(PyObject *self, PyObject *args)
static PyObject *
gl_shademodel(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- shademodel( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ shademodel( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void underlay long s */
@@ -6123,12 +6123,12 @@ gl_shademodel(PyObject *self, PyObject *args)
static PyObject *
gl_underlay(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- underlay( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ underlay( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnclosedline */
@@ -6136,9 +6136,9 @@ gl_underlay(PyObject *self, PyObject *args)
static PyObject *
gl_bgnclosedline(PyObject *self, PyObject *args)
{
- bgnclosedline( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnclosedline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnline */
@@ -6146,9 +6146,9 @@ gl_bgnclosedline(PyObject *self, PyObject *args)
static PyObject *
gl_bgnline(PyObject *self, PyObject *args)
{
- bgnline( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnpoint */
@@ -6156,9 +6156,9 @@ gl_bgnline(PyObject *self, PyObject *args)
static PyObject *
gl_bgnpoint(PyObject *self, PyObject *args)
{
- bgnpoint( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnpoint( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnpolygon */
@@ -6166,9 +6166,9 @@ gl_bgnpoint(PyObject *self, PyObject *args)
static PyObject *
gl_bgnpolygon(PyObject *self, PyObject *args)
{
- bgnpolygon( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnpolygon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgnsurface */
@@ -6176,9 +6176,9 @@ gl_bgnpolygon(PyObject *self, PyObject *args)
static PyObject *
gl_bgnsurface(PyObject *self, PyObject *args)
{
- bgnsurface( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgnsurface( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgntmesh */
@@ -6186,9 +6186,9 @@ gl_bgnsurface(PyObject *self, PyObject *args)
static PyObject *
gl_bgntmesh(PyObject *self, PyObject *args)
{
- bgntmesh( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgntmesh( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void bgntrim */
@@ -6196,9 +6196,9 @@ gl_bgntmesh(PyObject *self, PyObject *args)
static PyObject *
gl_bgntrim(PyObject *self, PyObject *args)
{
- bgntrim( );
- Py_INCREF(Py_None);
- return Py_None;
+ bgntrim( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endclosedline */
@@ -6206,9 +6206,9 @@ gl_bgntrim(PyObject *self, PyObject *args)
static PyObject *
gl_endclosedline(PyObject *self, PyObject *args)
{
- endclosedline( );
- Py_INCREF(Py_None);
- return Py_None;
+ endclosedline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endline */
@@ -6216,9 +6216,9 @@ gl_endclosedline(PyObject *self, PyObject *args)
static PyObject *
gl_endline(PyObject *self, PyObject *args)
{
- endline( );
- Py_INCREF(Py_None);
- return Py_None;
+ endline( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endpoint */
@@ -6226,9 +6226,9 @@ gl_endline(PyObject *self, PyObject *args)
static PyObject *
gl_endpoint(PyObject *self, PyObject *args)
{
- endpoint( );
- Py_INCREF(Py_None);
- return Py_None;
+ endpoint( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endpolygon */
@@ -6236,9 +6236,9 @@ gl_endpoint(PyObject *self, PyObject *args)
static PyObject *
gl_endpolygon(PyObject *self, PyObject *args)
{
- endpolygon( );
- Py_INCREF(Py_None);
- return Py_None;
+ endpolygon( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endsurface */
@@ -6246,9 +6246,9 @@ gl_endpolygon(PyObject *self, PyObject *args)
static PyObject *
gl_endsurface(PyObject *self, PyObject *args)
{
- endsurface( );
- Py_INCREF(Py_None);
- return Py_None;
+ endsurface( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endtmesh */
@@ -6256,9 +6256,9 @@ gl_endsurface(PyObject *self, PyObject *args)
static PyObject *
gl_endtmesh(PyObject *self, PyObject *args)
{
- endtmesh( );
- Py_INCREF(Py_None);
- return Py_None;
+ endtmesh( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void endtrim */
@@ -6266,9 +6266,9 @@ gl_endtmesh(PyObject *self, PyObject *args)
static PyObject *
gl_endtrim(PyObject *self, PyObject *args)
{
- endtrim( );
- Py_INCREF(Py_None);
- return Py_None;
+ endtrim( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void blendfunction long s long s */
@@ -6276,15 +6276,15 @@ gl_endtrim(PyObject *self, PyObject *args)
static PyObject *
gl_blendfunction(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- blendfunction( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ blendfunction( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c3f float s[3] */
@@ -6292,12 +6292,12 @@ gl_blendfunction(PyObject *self, PyObject *args)
static PyObject *
gl_c3f(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- c3f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ c3f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c3i long s[3] */
@@ -6305,12 +6305,12 @@ gl_c3f(PyObject *self, PyObject *args)
static PyObject *
gl_c3i(PyObject *self, PyObject *args)
{
- long arg1 [ 3 ] ;
- if (!getilongarray(args, 1, 0, 3 , arg1))
- return NULL;
- c3i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 3 ] ;
+ if (!getilongarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ c3i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c3s short s[3] */
@@ -6318,12 +6318,12 @@ gl_c3i(PyObject *self, PyObject *args)
static PyObject *
gl_c3s(PyObject *self, PyObject *args)
{
- short arg1 [ 3 ] ;
- if (!getishortarray(args, 1, 0, 3 , arg1))
- return NULL;
- c3s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 3 ] ;
+ if (!getishortarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ c3s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c4f float s[4] */
@@ -6331,12 +6331,12 @@ gl_c3s(PyObject *self, PyObject *args)
static PyObject *
gl_c4f(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 , arg1))
- return NULL;
- c4f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ c4f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c4i long s[4] */
@@ -6344,12 +6344,12 @@ gl_c4f(PyObject *self, PyObject *args)
static PyObject *
gl_c4i(PyObject *self, PyObject *args)
{
- long arg1 [ 4 ] ;
- if (!getilongarray(args, 1, 0, 4 , arg1))
- return NULL;
- c4i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 4 ] ;
+ if (!getilongarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ c4i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void c4s short s[4] */
@@ -6357,12 +6357,12 @@ gl_c4i(PyObject *self, PyObject *args)
static PyObject *
gl_c4s(PyObject *self, PyObject *args)
{
- short arg1 [ 4 ] ;
- if (!getishortarray(args, 1, 0, 4 , arg1))
- return NULL;
- c4s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 4 ] ;
+ if (!getishortarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ c4s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void colorf float s */
@@ -6370,12 +6370,12 @@ gl_c4s(PyObject *self, PyObject *args)
static PyObject *
gl_colorf(PyObject *self, PyObject *args)
{
- float arg1 ;
- if (!getifloatarg(args, 1, 0, &arg1))
- return NULL;
- colorf( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ if (!getifloatarg(args, 1, 0, &arg1))
+ return NULL;
+ colorf( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void cpack long s */
@@ -6383,12 +6383,12 @@ gl_colorf(PyObject *self, PyObject *args)
static PyObject *
gl_cpack(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- cpack( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ cpack( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void czclear long s long s */
@@ -6396,15 +6396,15 @@ gl_cpack(PyObject *self, PyObject *args)
static PyObject *
gl_czclear(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- czclear( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ czclear( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void dglclose long s */
@@ -6412,12 +6412,12 @@ gl_czclear(PyObject *self, PyObject *args)
static PyObject *
gl_dglclose(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- dglclose( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ dglclose( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long dglopen char *s long s */
@@ -6425,15 +6425,15 @@ gl_dglclose(PyObject *self, PyObject *args)
static PyObject *
gl_dglopen(PyObject *self, PyObject *args)
{
- long retval;
- string arg1 ;
- long arg2 ;
- if (!getistringarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- retval = dglopen( arg1 , arg2 );
- return mknewlongobject(retval);
+ long retval;
+ string arg1 ;
+ long arg2 ;
+ if (!getistringarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ retval = dglopen( arg1 , arg2 );
+ return mknewlongobject(retval);
}
/* long getgdesc long s */
@@ -6441,12 +6441,12 @@ gl_dglopen(PyObject *self, PyObject *args)
static PyObject *
gl_getgdesc(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = getgdesc( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = getgdesc( arg1 );
+ return mknewlongobject(retval);
}
/* void getnurbsproperty long s float r */
@@ -6454,12 +6454,12 @@ gl_getgdesc(PyObject *self, PyObject *args)
static PyObject *
gl_getnurbsproperty(PyObject *self, PyObject *args)
{
- long arg1 ;
- float arg2 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- getnurbsproperty( arg1 , & arg2 );
- return mknewfloatobject(arg2);
+ long arg1 ;
+ float arg2 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ getnurbsproperty( arg1 , & arg2 );
+ return mknewfloatobject(arg2);
}
/* void glcompat long s long s */
@@ -6467,15 +6467,15 @@ gl_getnurbsproperty(PyObject *self, PyObject *args)
static PyObject *
gl_glcompat(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- glcompat( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ glcompat( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void iconsize long s long s */
@@ -6483,15 +6483,15 @@ gl_glcompat(PyObject *self, PyObject *args)
static PyObject *
gl_iconsize(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- iconsize( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ iconsize( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void icontitle char *s */
@@ -6499,12 +6499,12 @@ gl_iconsize(PyObject *self, PyObject *args)
static PyObject *
gl_icontitle(PyObject *self, PyObject *args)
{
- string arg1 ;
- if (!getistringarg(args, 1, 0, &arg1))
- return NULL;
- icontitle( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ string arg1 ;
+ if (!getistringarg(args, 1, 0, &arg1))
+ return NULL;
+ icontitle( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lRGBrange short s short s short s short s short s short s long s long s */
@@ -6512,33 +6512,33 @@ gl_icontitle(PyObject *self, PyObject *args)
static PyObject *
gl_lRGBrange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- short arg5 ;
- short arg6 ;
- long arg7 ;
- long arg8 ;
- if (!getishortarg(args, 8, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 8, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 8, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 8, 3, &arg4))
- return NULL;
- if (!getishortarg(args, 8, 4, &arg5))
- return NULL;
- if (!getishortarg(args, 8, 5, &arg6))
- return NULL;
- if (!getilongarg(args, 8, 6, &arg7))
- return NULL;
- if (!getilongarg(args, 8, 7, &arg8))
- return NULL;
- lRGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ short arg5 ;
+ short arg6 ;
+ long arg7 ;
+ long arg8 ;
+ if (!getishortarg(args, 8, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 8, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 8, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 8, 3, &arg4))
+ return NULL;
+ if (!getishortarg(args, 8, 4, &arg5))
+ return NULL;
+ if (!getishortarg(args, 8, 5, &arg6))
+ return NULL;
+ if (!getilongarg(args, 8, 6, &arg7))
+ return NULL;
+ if (!getilongarg(args, 8, 7, &arg8))
+ return NULL;
+ lRGBrange( arg1 , arg2 , arg3 , arg4 , arg5 , arg6 , arg7 , arg8 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void linesmooth long s */
@@ -6546,12 +6546,12 @@ gl_lRGBrange(PyObject *self, PyObject *args)
static PyObject *
gl_linesmooth(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- linesmooth( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ linesmooth( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lmcolor long s */
@@ -6559,12 +6559,12 @@ gl_linesmooth(PyObject *self, PyObject *args)
static PyObject *
gl_lmcolor(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- lmcolor( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ lmcolor( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void logicop long s */
@@ -6572,12 +6572,12 @@ gl_lmcolor(PyObject *self, PyObject *args)
static PyObject *
gl_logicop(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- logicop( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ logicop( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lsetdepth long s long s */
@@ -6585,15 +6585,15 @@ gl_logicop(PyObject *self, PyObject *args)
static PyObject *
gl_lsetdepth(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- lsetdepth( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ lsetdepth( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void lshaderange short s short s long s long s */
@@ -6601,21 +6601,21 @@ gl_lsetdepth(PyObject *self, PyObject *args)
static PyObject *
gl_lshaderange(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- lshaderange( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ lshaderange( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void n3f float s[3] */
@@ -6623,12 +6623,12 @@ gl_lshaderange(PyObject *self, PyObject *args)
static PyObject *
gl_n3f(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- n3f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ n3f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void noborder */
@@ -6636,9 +6636,9 @@ gl_n3f(PyObject *self, PyObject *args)
static PyObject *
gl_noborder(PyObject *self, PyObject *args)
{
- noborder( );
- Py_INCREF(Py_None);
- return Py_None;
+ noborder( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pntsmooth long s */
@@ -6646,12 +6646,12 @@ gl_noborder(PyObject *self, PyObject *args)
static PyObject *
gl_pntsmooth(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- pntsmooth( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ pntsmooth( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void readsource long s */
@@ -6659,12 +6659,12 @@ gl_pntsmooth(PyObject *self, PyObject *args)
static PyObject *
gl_readsource(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- readsource( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ readsource( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void rectzoom float s float s */
@@ -6672,15 +6672,15 @@ gl_readsource(PyObject *self, PyObject *args)
static PyObject *
gl_rectzoom(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- if (!getifloatarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- rectzoom( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ if (!getifloatarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ rectzoom( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sbox float s float s float s float s */
@@ -6688,21 +6688,21 @@ gl_rectzoom(PyObject *self, PyObject *args)
static PyObject *
gl_sbox(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- sbox( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ sbox( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxi long s long s long s long s */
@@ -6710,21 +6710,21 @@ gl_sbox(PyObject *self, PyObject *args)
static PyObject *
gl_sboxi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- sboxi( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxi( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxs short s short s short s short s */
@@ -6732,21 +6732,21 @@ gl_sboxi(PyObject *self, PyObject *args)
static PyObject *
gl_sboxs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- sboxs( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxs( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxf float s float s float s float s */
@@ -6754,21 +6754,21 @@ gl_sboxs(PyObject *self, PyObject *args)
static PyObject *
gl_sboxf(PyObject *self, PyObject *args)
{
- float arg1 ;
- float arg2 ;
- float arg3 ;
- float arg4 ;
- if (!getifloatarg(args, 4, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 4, 1, &arg2))
- return NULL;
- if (!getifloatarg(args, 4, 2, &arg3))
- return NULL;
- if (!getifloatarg(args, 4, 3, &arg4))
- return NULL;
- sboxf( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 ;
+ float arg2 ;
+ float arg3 ;
+ float arg4 ;
+ if (!getifloatarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getifloatarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getifloatarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxf( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxfi long s long s long s long s */
@@ -6776,21 +6776,21 @@ gl_sboxf(PyObject *self, PyObject *args)
static PyObject *
gl_sboxfi(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- long arg4 ;
- if (!getilongarg(args, 4, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 4, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 4, 2, &arg3))
- return NULL;
- if (!getilongarg(args, 4, 3, &arg4))
- return NULL;
- sboxfi( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ long arg4 ;
+ if (!getilongarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getilongarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxfi( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void sboxfs short s short s short s short s */
@@ -6798,21 +6798,21 @@ gl_sboxfi(PyObject *self, PyObject *args)
static PyObject *
gl_sboxfs(PyObject *self, PyObject *args)
{
- short arg1 ;
- short arg2 ;
- short arg3 ;
- short arg4 ;
- if (!getishortarg(args, 4, 0, &arg1))
- return NULL;
- if (!getishortarg(args, 4, 1, &arg2))
- return NULL;
- if (!getishortarg(args, 4, 2, &arg3))
- return NULL;
- if (!getishortarg(args, 4, 3, &arg4))
- return NULL;
- sboxfs( arg1 , arg2 , arg3 , arg4 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 ;
+ short arg2 ;
+ short arg3 ;
+ short arg4 ;
+ if (!getishortarg(args, 4, 0, &arg1))
+ return NULL;
+ if (!getishortarg(args, 4, 1, &arg2))
+ return NULL;
+ if (!getishortarg(args, 4, 2, &arg3))
+ return NULL;
+ if (!getishortarg(args, 4, 3, &arg4))
+ return NULL;
+ sboxfs( arg1 , arg2 , arg3 , arg4 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setnurbsproperty long s float s */
@@ -6820,15 +6820,15 @@ gl_sboxfs(PyObject *self, PyObject *args)
static PyObject *
gl_setnurbsproperty(PyObject *self, PyObject *args)
{
- long arg1 ;
- float arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getifloatarg(args, 2, 1, &arg2))
- return NULL;
- setnurbsproperty( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ float arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getifloatarg(args, 2, 1, &arg2))
+ return NULL;
+ setnurbsproperty( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void setpup long s long s long s */
@@ -6836,18 +6836,18 @@ gl_setnurbsproperty(PyObject *self, PyObject *args)
static PyObject *
gl_setpup(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- long arg3 ;
- if (!getilongarg(args, 3, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 3, 1, &arg2))
- return NULL;
- if (!getilongarg(args, 3, 2, &arg3))
- return NULL;
- setpup( arg1 , arg2 , arg3 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ long arg3 ;
+ if (!getilongarg(args, 3, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 3, 1, &arg2))
+ return NULL;
+ if (!getilongarg(args, 3, 2, &arg3))
+ return NULL;
+ setpup( arg1 , arg2 , arg3 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void smoothline long s */
@@ -6855,12 +6855,12 @@ gl_setpup(PyObject *self, PyObject *args)
static PyObject *
gl_smoothline(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- smoothline( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ smoothline( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void subpixel long s */
@@ -6868,12 +6868,12 @@ gl_smoothline(PyObject *self, PyObject *args)
static PyObject *
gl_subpixel(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- subpixel( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ subpixel( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void swaptmesh */
@@ -6881,9 +6881,9 @@ gl_subpixel(PyObject *self, PyObject *args)
static PyObject *
gl_swaptmesh(PyObject *self, PyObject *args)
{
- swaptmesh( );
- Py_INCREF(Py_None);
- return Py_None;
+ swaptmesh( );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long swinopen long s */
@@ -6891,12 +6891,12 @@ gl_swaptmesh(PyObject *self, PyObject *args)
static PyObject *
gl_swinopen(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = swinopen( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = swinopen( arg1 );
+ return mknewlongobject(retval);
}
/* void v2f float s[2] */
@@ -6904,12 +6904,12 @@ gl_swinopen(PyObject *self, PyObject *args)
static PyObject *
gl_v2f(PyObject *self, PyObject *args)
{
- float arg1 [ 2 ] ;
- if (!getifloatarray(args, 1, 0, 2 , arg1))
- return NULL;
- v2f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 2 ] ;
+ if (!getifloatarray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v2i long s[2] */
@@ -6917,12 +6917,12 @@ gl_v2f(PyObject *self, PyObject *args)
static PyObject *
gl_v2i(PyObject *self, PyObject *args)
{
- long arg1 [ 2 ] ;
- if (!getilongarray(args, 1, 0, 2 , arg1))
- return NULL;
- v2i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 2 ] ;
+ if (!getilongarray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v2s short s[2] */
@@ -6930,12 +6930,12 @@ gl_v2i(PyObject *self, PyObject *args)
static PyObject *
gl_v2s(PyObject *self, PyObject *args)
{
- short arg1 [ 2 ] ;
- if (!getishortarray(args, 1, 0, 2 , arg1))
- return NULL;
- v2s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 2 ] ;
+ if (!getishortarray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3f float s[3] */
@@ -6943,12 +6943,12 @@ gl_v2s(PyObject *self, PyObject *args)
static PyObject *
gl_v3f(PyObject *self, PyObject *args)
{
- float arg1 [ 3 ] ;
- if (!getifloatarray(args, 1, 0, 3 , arg1))
- return NULL;
- v3f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 3 ] ;
+ if (!getifloatarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3i long s[3] */
@@ -6956,12 +6956,12 @@ gl_v3f(PyObject *self, PyObject *args)
static PyObject *
gl_v3i(PyObject *self, PyObject *args)
{
- long arg1 [ 3 ] ;
- if (!getilongarray(args, 1, 0, 3 , arg1))
- return NULL;
- v3i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 3 ] ;
+ if (!getilongarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3s short s[3] */
@@ -6969,12 +6969,12 @@ gl_v3i(PyObject *self, PyObject *args)
static PyObject *
gl_v3s(PyObject *self, PyObject *args)
{
- short arg1 [ 3 ] ;
- if (!getishortarray(args, 1, 0, 3 , arg1))
- return NULL;
- v3s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 3 ] ;
+ if (!getishortarray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4f float s[4] */
@@ -6982,12 +6982,12 @@ gl_v3s(PyObject *self, PyObject *args)
static PyObject *
gl_v4f(PyObject *self, PyObject *args)
{
- float arg1 [ 4 ] ;
- if (!getifloatarray(args, 1, 0, 4 , arg1))
- return NULL;
- v4f( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ float arg1 [ 4 ] ;
+ if (!getifloatarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4f( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4i long s[4] */
@@ -6995,12 +6995,12 @@ gl_v4f(PyObject *self, PyObject *args)
static PyObject *
gl_v4i(PyObject *self, PyObject *args)
{
- long arg1 [ 4 ] ;
- if (!getilongarray(args, 1, 0, 4 , arg1))
- return NULL;
- v4i( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 [ 4 ] ;
+ if (!getilongarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4i( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4s short s[4] */
@@ -7008,12 +7008,12 @@ gl_v4i(PyObject *self, PyObject *args)
static PyObject *
gl_v4s(PyObject *self, PyObject *args)
{
- short arg1 [ 4 ] ;
- if (!getishortarray(args, 1, 0, 4 , arg1))
- return NULL;
- v4s( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ short arg1 [ 4 ] ;
+ if (!getishortarray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4s( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void videocmd long s */
@@ -7021,12 +7021,12 @@ gl_v4s(PyObject *self, PyObject *args)
static PyObject *
gl_videocmd(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- videocmd( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ videocmd( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long windepth long s */
@@ -7034,12 +7034,12 @@ gl_videocmd(PyObject *self, PyObject *args)
static PyObject *
gl_windepth(PyObject *self, PyObject *args)
{
- long retval;
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- retval = windepth( arg1 );
- return mknewlongobject(retval);
+ long retval;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ retval = windepth( arg1 );
+ return mknewlongobject(retval);
}
/* void wmpack long s */
@@ -7047,12 +7047,12 @@ gl_windepth(PyObject *self, PyObject *args)
static PyObject *
gl_wmpack(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- wmpack( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ wmpack( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zdraw long s */
@@ -7060,12 +7060,12 @@ gl_wmpack(PyObject *self, PyObject *args)
static PyObject *
gl_zdraw(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zdraw( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zdraw( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zfunction long s */
@@ -7073,12 +7073,12 @@ gl_zdraw(PyObject *self, PyObject *args)
static PyObject *
gl_zfunction(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zfunction( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zfunction( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zsource long s */
@@ -7086,12 +7086,12 @@ gl_zfunction(PyObject *self, PyObject *args)
static PyObject *
gl_zsource(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zsource( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zsource( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void zwritemask long s */
@@ -7099,12 +7099,12 @@ gl_zsource(PyObject *self, PyObject *args)
static PyObject *
gl_zwritemask(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- zwritemask( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ zwritemask( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v2d double s[2] */
@@ -7112,12 +7112,12 @@ gl_zwritemask(PyObject *self, PyObject *args)
static PyObject *
gl_v2d(PyObject *self, PyObject *args)
{
- double arg1 [ 2 ] ;
- if (!getidoublearray(args, 1, 0, 2 , arg1))
- return NULL;
- v2d( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ double arg1 [ 2 ] ;
+ if (!getidoublearray(args, 1, 0, 2 , arg1))
+ return NULL;
+ v2d( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v3d double s[3] */
@@ -7125,12 +7125,12 @@ gl_v2d(PyObject *self, PyObject *args)
static PyObject *
gl_v3d(PyObject *self, PyObject *args)
{
- double arg1 [ 3 ] ;
- if (!getidoublearray(args, 1, 0, 3 , arg1))
- return NULL;
- v3d( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ double arg1 [ 3 ] ;
+ if (!getidoublearray(args, 1, 0, 3 , arg1))
+ return NULL;
+ v3d( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void v4d double s[4] */
@@ -7138,12 +7138,12 @@ gl_v3d(PyObject *self, PyObject *args)
static PyObject *
gl_v4d(PyObject *self, PyObject *args)
{
- double arg1 [ 4 ] ;
- if (!getidoublearray(args, 1, 0, 4 , arg1))
- return NULL;
- v4d( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ double arg1 [ 4 ] ;
+ if (!getidoublearray(args, 1, 0, 4 , arg1))
+ return NULL;
+ v4d( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* void pixmode long s long s */
@@ -7151,15 +7151,15 @@ gl_v4d(PyObject *self, PyObject *args)
static PyObject *
gl_pixmode(PyObject *self, PyObject *args)
{
- long arg1 ;
- long arg2 ;
- if (!getilongarg(args, 2, 0, &arg1))
- return NULL;
- if (!getilongarg(args, 2, 1, &arg2))
- return NULL;
- pixmode( arg1 , arg2 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ long arg2 ;
+ if (!getilongarg(args, 2, 0, &arg1))
+ return NULL;
+ if (!getilongarg(args, 2, 1, &arg2))
+ return NULL;
+ pixmode( arg1 , arg2 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* long qgetfd */
@@ -7167,9 +7167,9 @@ gl_pixmode(PyObject *self, PyObject *args)
static PyObject *
gl_qgetfd(PyObject *self, PyObject *args)
{
- long retval;
- retval = qgetfd( );
- return mknewlongobject(retval);
+ long retval;
+ retval = qgetfd( );
+ return mknewlongobject(retval);
}
/* void dither long s */
@@ -7177,457 +7177,457 @@ gl_qgetfd(PyObject *self, PyObject *args)
static PyObject *
gl_dither(PyObject *self, PyObject *args)
{
- long arg1 ;
- if (!getilongarg(args, 1, 0, &arg1))
- return NULL;
- dither( arg1 );
- Py_INCREF(Py_None);
- return Py_None;
+ long arg1 ;
+ if (!getilongarg(args, 1, 0, &arg1))
+ return NULL;
+ dither( arg1 );
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef gl_methods[] = {
- {"qread", gl_qread, METH_OLDARGS},
- {"varray", gl_varray, METH_OLDARGS},
- {"nvarray", gl_nvarray, METH_OLDARGS},
- {"vnarray", gl_vnarray, METH_OLDARGS},
- {"nurbssurface", gl_nurbssurface, METH_OLDARGS},
- {"nurbscurve", gl_nurbscurve, METH_OLDARGS},
- {"pwlcurve", gl_pwlcurve, METH_OLDARGS},
- {"pick", gl_pick, METH_OLDARGS},
- {"endpick", gl_endpick, METH_NOARGS},
- {"gselect", gl_gselect, METH_OLDARGS},
- {"endselect", gl_endselect, METH_NOARGS},
- {"getmatrix", gl_getmatrix, METH_OLDARGS},
- {"altgetmatrix", gl_altgetmatrix, METH_OLDARGS},
- {"lrectwrite", gl_lrectwrite, METH_OLDARGS},
- {"lrectread", gl_lrectread, METH_OLDARGS},
- {"readdisplay", gl_readdisplay, METH_OLDARGS},
- {"packrect", gl_packrect, METH_OLDARGS},
- {"unpackrect", gl_unpackrect, METH_OLDARGS},
- {"gversion", gl_gversion, METH_OLDARGS},
- {"clear", gl_clear, METH_OLDARGS},
- {"getshade", gl_getshade, METH_OLDARGS},
- {"devport", gl_devport, METH_OLDARGS},
- {"rdr2i", gl_rdr2i, METH_OLDARGS},
- {"rectfs", gl_rectfs, METH_OLDARGS},
- {"rects", gl_rects, METH_OLDARGS},
- {"rmv2i", gl_rmv2i, METH_OLDARGS},
- {"noport", gl_noport, METH_OLDARGS},
- {"popviewport", gl_popviewport, METH_OLDARGS},
- {"clearhitcode", gl_clearhitcode, METH_OLDARGS},
- {"closeobj", gl_closeobj, METH_OLDARGS},
- {"cursoff", gl_cursoff, METH_OLDARGS},
- {"curson", gl_curson, METH_OLDARGS},
- {"doublebuffer", gl_doublebuffer, METH_OLDARGS},
- {"finish", gl_finish, METH_OLDARGS},
- {"gconfig", gl_gconfig, METH_OLDARGS},
- {"ginit", gl_ginit, METH_OLDARGS},
- {"greset", gl_greset, METH_OLDARGS},
- {"multimap", gl_multimap, METH_OLDARGS},
- {"onemap", gl_onemap, METH_OLDARGS},
- {"popattributes", gl_popattributes, METH_OLDARGS},
- {"popmatrix", gl_popmatrix, METH_OLDARGS},
- {"pushattributes", gl_pushattributes,METH_OLDARGS},
- {"pushmatrix", gl_pushmatrix, METH_OLDARGS},
- {"pushviewport", gl_pushviewport, METH_OLDARGS},
- {"qreset", gl_qreset, METH_OLDARGS},
- {"RGBmode", gl_RGBmode, METH_OLDARGS},
- {"singlebuffer", gl_singlebuffer, METH_OLDARGS},
- {"swapbuffers", gl_swapbuffers, METH_OLDARGS},
- {"gsync", gl_gsync, METH_OLDARGS},
- {"gflush", gl_gflush, METH_OLDARGS},
- {"tpon", gl_tpon, METH_OLDARGS},
- {"tpoff", gl_tpoff, METH_OLDARGS},
- {"clkon", gl_clkon, METH_OLDARGS},
- {"clkoff", gl_clkoff, METH_OLDARGS},
- {"ringbell", gl_ringbell, METH_OLDARGS},
- {"gbegin", gl_gbegin, METH_OLDARGS},
- {"textinit", gl_textinit, METH_OLDARGS},
- {"initnames", gl_initnames, METH_OLDARGS},
- {"pclos", gl_pclos, METH_OLDARGS},
- {"popname", gl_popname, METH_OLDARGS},
- {"spclos", gl_spclos, METH_OLDARGS},
- {"zclear", gl_zclear, METH_OLDARGS},
- {"screenspace", gl_screenspace, METH_OLDARGS},
- {"reshapeviewport", gl_reshapeviewport, METH_OLDARGS},
- {"winpush", gl_winpush, METH_OLDARGS},
- {"winpop", gl_winpop, METH_OLDARGS},
- {"foreground", gl_foreground, METH_OLDARGS},
- {"endfullscrn", gl_endfullscrn, METH_OLDARGS},
- {"endpupmode", gl_endpupmode, METH_OLDARGS},
- {"fullscrn", gl_fullscrn, METH_OLDARGS},
- {"pupmode", gl_pupmode, METH_OLDARGS},
- {"winconstraints", gl_winconstraints, METH_OLDARGS},
- {"pagecolor", gl_pagecolor, METH_OLDARGS},
- {"textcolor", gl_textcolor, METH_OLDARGS},
- {"color", gl_color, METH_OLDARGS},
- {"curveit", gl_curveit, METH_OLDARGS},
- {"font", gl_font, METH_OLDARGS},
- {"linewidth", gl_linewidth, METH_OLDARGS},
- {"setlinestyle", gl_setlinestyle, METH_OLDARGS},
- {"setmap", gl_setmap, METH_OLDARGS},
- {"swapinterval", gl_swapinterval, METH_OLDARGS},
- {"writemask", gl_writemask, METH_OLDARGS},
- {"textwritemask", gl_textwritemask, METH_OLDARGS},
- {"qdevice", gl_qdevice, METH_OLDARGS},
- {"unqdevice", gl_unqdevice, METH_OLDARGS},
- {"curvebasis", gl_curvebasis, METH_OLDARGS},
- {"curveprecision", gl_curveprecision,METH_OLDARGS},
- {"loadname", gl_loadname, METH_OLDARGS},
- {"passthrough", gl_passthrough, METH_OLDARGS},
- {"pushname", gl_pushname, METH_OLDARGS},
- {"setmonitor", gl_setmonitor, METH_OLDARGS},
- {"setshade", gl_setshade, METH_OLDARGS},
- {"setpattern", gl_setpattern, METH_OLDARGS},
- {"pagewritemask", gl_pagewritemask, METH_OLDARGS},
- {"callobj", gl_callobj, METH_OLDARGS},
- {"delobj", gl_delobj, METH_OLDARGS},
- {"editobj", gl_editobj, METH_OLDARGS},
- {"makeobj", gl_makeobj, METH_OLDARGS},
- {"maketag", gl_maketag, METH_OLDARGS},
- {"chunksize", gl_chunksize, METH_OLDARGS},
- {"compactify", gl_compactify, METH_OLDARGS},
- {"deltag", gl_deltag, METH_OLDARGS},
- {"lsrepeat", gl_lsrepeat, METH_OLDARGS},
- {"objinsert", gl_objinsert, METH_OLDARGS},
- {"objreplace", gl_objreplace, METH_OLDARGS},
- {"winclose", gl_winclose, METH_OLDARGS},
- {"blanktime", gl_blanktime, METH_OLDARGS},
- {"freepup", gl_freepup, METH_OLDARGS},
- {"backbuffer", gl_backbuffer, METH_OLDARGS},
- {"frontbuffer", gl_frontbuffer, METH_OLDARGS},
- {"lsbackup", gl_lsbackup, METH_OLDARGS},
- {"resetls", gl_resetls, METH_OLDARGS},
- {"lampon", gl_lampon, METH_OLDARGS},
- {"lampoff", gl_lampoff, METH_OLDARGS},
- {"setbell", gl_setbell, METH_OLDARGS},
- {"blankscreen", gl_blankscreen, METH_OLDARGS},
- {"depthcue", gl_depthcue, METH_OLDARGS},
- {"zbuffer", gl_zbuffer, METH_OLDARGS},
- {"backface", gl_backface, METH_OLDARGS},
- {"cmov2i", gl_cmov2i, METH_OLDARGS},
- {"draw2i", gl_draw2i, METH_OLDARGS},
- {"move2i", gl_move2i, METH_OLDARGS},
- {"pnt2i", gl_pnt2i, METH_OLDARGS},
- {"patchbasis", gl_patchbasis, METH_OLDARGS},
- {"patchprecision", gl_patchprecision, METH_OLDARGS},
- {"pdr2i", gl_pdr2i, METH_OLDARGS},
- {"pmv2i", gl_pmv2i, METH_OLDARGS},
- {"rpdr2i", gl_rpdr2i, METH_OLDARGS},
- {"rpmv2i", gl_rpmv2i, METH_OLDARGS},
- {"xfpt2i", gl_xfpt2i, METH_OLDARGS},
- {"objdelete", gl_objdelete, METH_OLDARGS},
- {"patchcurves", gl_patchcurves, METH_OLDARGS},
- {"minsize", gl_minsize, METH_OLDARGS},
- {"maxsize", gl_maxsize, METH_OLDARGS},
- {"keepaspect", gl_keepaspect, METH_OLDARGS},
- {"prefsize", gl_prefsize, METH_OLDARGS},
- {"stepunit", gl_stepunit, METH_OLDARGS},
- {"fudge", gl_fudge, METH_OLDARGS},
- {"winmove", gl_winmove, METH_OLDARGS},
- {"attachcursor", gl_attachcursor, METH_OLDARGS},
- {"deflinestyle", gl_deflinestyle, METH_OLDARGS},
- {"noise", gl_noise, METH_OLDARGS},
- {"picksize", gl_picksize, METH_OLDARGS},
- {"qenter", gl_qenter, METH_OLDARGS},
- {"setdepth", gl_setdepth, METH_OLDARGS},
- {"cmov2s", gl_cmov2s, METH_OLDARGS},
- {"draw2s", gl_draw2s, METH_OLDARGS},
- {"move2s", gl_move2s, METH_OLDARGS},
- {"pdr2s", gl_pdr2s, METH_OLDARGS},
- {"pmv2s", gl_pmv2s, METH_OLDARGS},
- {"pnt2s", gl_pnt2s, METH_OLDARGS},
- {"rdr2s", gl_rdr2s, METH_OLDARGS},
- {"rmv2s", gl_rmv2s, METH_OLDARGS},
- {"rpdr2s", gl_rpdr2s, METH_OLDARGS},
- {"rpmv2s", gl_rpmv2s, METH_OLDARGS},
- {"xfpt2s", gl_xfpt2s, METH_OLDARGS},
- {"cmov2", gl_cmov2, METH_OLDARGS},
- {"draw2", gl_draw2, METH_OLDARGS},
- {"move2", gl_move2, METH_OLDARGS},
- {"pnt2", gl_pnt2, METH_OLDARGS},
- {"pdr2", gl_pdr2, METH_OLDARGS},
- {"pmv2", gl_pmv2, METH_OLDARGS},
- {"rdr2", gl_rdr2, METH_OLDARGS},
- {"rmv2", gl_rmv2, METH_OLDARGS},
- {"rpdr2", gl_rpdr2, METH_OLDARGS},
- {"rpmv2", gl_rpmv2, METH_OLDARGS},
- {"xfpt2", gl_xfpt2, METH_OLDARGS},
- {"loadmatrix", gl_loadmatrix, METH_OLDARGS},
- {"multmatrix", gl_multmatrix, METH_OLDARGS},
- {"crv", gl_crv, METH_OLDARGS},
- {"rcrv", gl_rcrv, METH_OLDARGS},
- {"addtopup", gl_addtopup, METH_OLDARGS},
- {"charstr", gl_charstr, METH_OLDARGS},
- {"getport", gl_getport, METH_OLDARGS},
- {"strwidth", gl_strwidth, METH_OLDARGS},
- {"winopen", gl_winopen, METH_OLDARGS},
- {"wintitle", gl_wintitle, METH_OLDARGS},
- {"polf", gl_polf, METH_OLDARGS},
- {"polf2", gl_polf2, METH_OLDARGS},
- {"poly", gl_poly, METH_OLDARGS},
- {"poly2", gl_poly2, METH_OLDARGS},
- {"crvn", gl_crvn, METH_OLDARGS},
- {"rcrvn", gl_rcrvn, METH_OLDARGS},
- {"polf2i", gl_polf2i, METH_OLDARGS},
- {"polfi", gl_polfi, METH_OLDARGS},
- {"poly2i", gl_poly2i, METH_OLDARGS},
- {"polyi", gl_polyi, METH_OLDARGS},
- {"polf2s", gl_polf2s, METH_OLDARGS},
- {"polfs", gl_polfs, METH_OLDARGS},
- {"polys", gl_polys, METH_OLDARGS},
- {"poly2s", gl_poly2s, METH_OLDARGS},
- {"defcursor", gl_defcursor, METH_OLDARGS},
- {"writepixels", gl_writepixels, METH_OLDARGS},
- {"defbasis", gl_defbasis, METH_OLDARGS},
- {"gewrite", gl_gewrite, METH_OLDARGS},
- {"rotate", gl_rotate, METH_OLDARGS},
- {"rot", gl_rot, METH_OLDARGS},
- {"circfi", gl_circfi, METH_OLDARGS},
- {"circi", gl_circi, METH_OLDARGS},
- {"cmovi", gl_cmovi, METH_OLDARGS},
- {"drawi", gl_drawi, METH_OLDARGS},
- {"movei", gl_movei, METH_OLDARGS},
- {"pnti", gl_pnti, METH_OLDARGS},
- {"newtag", gl_newtag, METH_OLDARGS},
- {"pdri", gl_pdri, METH_OLDARGS},
- {"pmvi", gl_pmvi, METH_OLDARGS},
- {"rdri", gl_rdri, METH_OLDARGS},
- {"rmvi", gl_rmvi, METH_OLDARGS},
- {"rpdri", gl_rpdri, METH_OLDARGS},
- {"rpmvi", gl_rpmvi, METH_OLDARGS},
- {"xfpti", gl_xfpti, METH_OLDARGS},
- {"circ", gl_circ, METH_OLDARGS},
- {"circf", gl_circf, METH_OLDARGS},
- {"cmov", gl_cmov, METH_OLDARGS},
- {"draw", gl_draw, METH_OLDARGS},
- {"move", gl_move, METH_OLDARGS},
- {"pnt", gl_pnt, METH_OLDARGS},
- {"scale", gl_scale, METH_OLDARGS},
- {"translate", gl_translate, METH_OLDARGS},
- {"pdr", gl_pdr, METH_OLDARGS},
- {"pmv", gl_pmv, METH_OLDARGS},
- {"rdr", gl_rdr, METH_OLDARGS},
- {"rmv", gl_rmv, METH_OLDARGS},
- {"rpdr", gl_rpdr, METH_OLDARGS},
- {"rpmv", gl_rpmv, METH_OLDARGS},
- {"xfpt", gl_xfpt, METH_OLDARGS},
- {"RGBcolor", gl_RGBcolor, METH_OLDARGS},
- {"RGBwritemask", gl_RGBwritemask, METH_OLDARGS},
- {"setcursor", gl_setcursor, METH_OLDARGS},
- {"tie", gl_tie, METH_OLDARGS},
- {"circfs", gl_circfs, METH_OLDARGS},
- {"circs", gl_circs, METH_OLDARGS},
- {"cmovs", gl_cmovs, METH_OLDARGS},
- {"draws", gl_draws, METH_OLDARGS},
- {"moves", gl_moves, METH_OLDARGS},
- {"pdrs", gl_pdrs, METH_OLDARGS},
- {"pmvs", gl_pmvs, METH_OLDARGS},
- {"pnts", gl_pnts, METH_OLDARGS},
- {"rdrs", gl_rdrs, METH_OLDARGS},
- {"rmvs", gl_rmvs, METH_OLDARGS},
- {"rpdrs", gl_rpdrs, METH_OLDARGS},
- {"rpmvs", gl_rpmvs, METH_OLDARGS},
- {"xfpts", gl_xfpts, METH_OLDARGS},
- {"curorigin", gl_curorigin, METH_OLDARGS},
- {"cyclemap", gl_cyclemap, METH_OLDARGS},
- {"patch", gl_patch, METH_OLDARGS},
- {"splf", gl_splf, METH_OLDARGS},
- {"splf2", gl_splf2, METH_OLDARGS},
- {"splfi", gl_splfi, METH_OLDARGS},
- {"splf2i", gl_splf2i, METH_OLDARGS},
- {"splfs", gl_splfs, METH_OLDARGS},
- {"splf2s", gl_splf2s, METH_OLDARGS},
- {"rpatch", gl_rpatch, METH_OLDARGS},
- {"ortho2", gl_ortho2, METH_OLDARGS},
- {"rect", gl_rect, METH_OLDARGS},
- {"rectf", gl_rectf, METH_OLDARGS},
- {"xfpt4", gl_xfpt4, METH_OLDARGS},
- {"textport", gl_textport, METH_OLDARGS},
- {"mapcolor", gl_mapcolor, METH_OLDARGS},
- {"scrmask", gl_scrmask, METH_OLDARGS},
- {"setvaluator", gl_setvaluator, METH_OLDARGS},
- {"viewport", gl_viewport, METH_OLDARGS},
- {"shaderange", gl_shaderange, METH_OLDARGS},
- {"xfpt4s", gl_xfpt4s, METH_OLDARGS},
- {"rectfi", gl_rectfi, METH_OLDARGS},
- {"recti", gl_recti, METH_OLDARGS},
- {"xfpt4i", gl_xfpt4i, METH_OLDARGS},
- {"prefposition", gl_prefposition, METH_OLDARGS},
- {"arc", gl_arc, METH_OLDARGS},
- {"arcf", gl_arcf, METH_OLDARGS},
- {"arcfi", gl_arcfi, METH_OLDARGS},
- {"arci", gl_arci, METH_OLDARGS},
- {"bbox2", gl_bbox2, METH_OLDARGS},
- {"bbox2i", gl_bbox2i, METH_OLDARGS},
- {"bbox2s", gl_bbox2s, METH_OLDARGS},
- {"blink", gl_blink, METH_OLDARGS},
- {"ortho", gl_ortho, METH_OLDARGS},
- {"window", gl_window, METH_OLDARGS},
- {"lookat", gl_lookat, METH_OLDARGS},
- {"perspective", gl_perspective, METH_OLDARGS},
- {"polarview", gl_polarview, METH_OLDARGS},
- {"arcfs", gl_arcfs, METH_OLDARGS},
- {"arcs", gl_arcs, METH_OLDARGS},
- {"rectcopy", gl_rectcopy, METH_OLDARGS},
- {"RGBcursor", gl_RGBcursor, METH_OLDARGS},
- {"getbutton", gl_getbutton, METH_OLDARGS},
- {"getcmmode", gl_getcmmode, METH_OLDARGS},
- {"getlsbackup", gl_getlsbackup, METH_OLDARGS},
- {"getresetls", gl_getresetls, METH_OLDARGS},
- {"getdcm", gl_getdcm, METH_OLDARGS},
- {"getzbuffer", gl_getzbuffer, METH_OLDARGS},
- {"ismex", gl_ismex, METH_OLDARGS},
- {"isobj", gl_isobj, METH_OLDARGS},
- {"isqueued", gl_isqueued, METH_OLDARGS},
- {"istag", gl_istag, METH_OLDARGS},
- {"genobj", gl_genobj, METH_OLDARGS},
- {"gentag", gl_gentag, METH_OLDARGS},
- {"getbuffer", gl_getbuffer, METH_OLDARGS},
- {"getcolor", gl_getcolor, METH_OLDARGS},
- {"getdisplaymode", gl_getdisplaymode, METH_OLDARGS},
- {"getfont", gl_getfont, METH_OLDARGS},
- {"getheight", gl_getheight, METH_OLDARGS},
- {"gethitcode", gl_gethitcode, METH_OLDARGS},
- {"getlstyle", gl_getlstyle, METH_OLDARGS},
- {"getlwidth", gl_getlwidth, METH_OLDARGS},
- {"getmap", gl_getmap, METH_OLDARGS},
- {"getplanes", gl_getplanes, METH_OLDARGS},
- {"getwritemask", gl_getwritemask, METH_OLDARGS},
- {"qtest", gl_qtest, METH_OLDARGS},
- {"getlsrepeat", gl_getlsrepeat, METH_OLDARGS},
- {"getmonitor", gl_getmonitor, METH_OLDARGS},
- {"getopenobj", gl_getopenobj, METH_OLDARGS},
- {"getpattern", gl_getpattern, METH_OLDARGS},
- {"winget", gl_winget, METH_OLDARGS},
- {"winattach", gl_winattach, METH_OLDARGS},
- {"getothermonitor", gl_getothermonitor, METH_OLDARGS},
- {"newpup", gl_newpup, METH_OLDARGS},
- {"getvaluator", gl_getvaluator, METH_OLDARGS},
- {"winset", gl_winset, METH_OLDARGS},
- {"dopup", gl_dopup, METH_OLDARGS},
- {"getdepth", gl_getdepth, METH_OLDARGS},
- {"getcpos", gl_getcpos, METH_OLDARGS},
- {"getsize", gl_getsize, METH_OLDARGS},
- {"getorigin", gl_getorigin, METH_OLDARGS},
- {"getviewport", gl_getviewport, METH_OLDARGS},
- {"gettp", gl_gettp, METH_OLDARGS},
- {"getgpos", gl_getgpos, METH_OLDARGS},
- {"winposition", gl_winposition, METH_OLDARGS},
- {"gRGBcolor", gl_gRGBcolor, METH_OLDARGS},
- {"gRGBmask", gl_gRGBmask, METH_OLDARGS},
- {"getscrmask", gl_getscrmask, METH_OLDARGS},
- {"getmcolor", gl_getmcolor, METH_OLDARGS},
- {"mapw", gl_mapw, METH_OLDARGS},
- {"mapw2", gl_mapw2, METH_OLDARGS},
- {"getcursor", gl_getcursor, METH_OLDARGS},
- {"cmode", gl_cmode, METH_OLDARGS},
- {"concave", gl_concave, METH_OLDARGS},
- {"curstype", gl_curstype, METH_OLDARGS},
- {"drawmode", gl_drawmode, METH_OLDARGS},
- {"gammaramp", gl_gammaramp, METH_OLDARGS},
- {"getbackface", gl_getbackface, METH_OLDARGS},
- {"getdescender", gl_getdescender, METH_OLDARGS},
- {"getdrawmode", gl_getdrawmode, METH_OLDARGS},
- {"getmmode", gl_getmmode, METH_OLDARGS},
- {"getsm", gl_getsm, METH_OLDARGS},
- {"getvideo", gl_getvideo, METH_OLDARGS},
- {"imakebackground", gl_imakebackground, METH_OLDARGS},
- {"lmbind", gl_lmbind, METH_OLDARGS},
- {"lmdef", gl_lmdef, METH_OLDARGS},
- {"mmode", gl_mmode, METH_OLDARGS},
- {"normal", gl_normal, METH_OLDARGS},
- {"overlay", gl_overlay, METH_OLDARGS},
- {"RGBrange", gl_RGBrange, METH_OLDARGS},
- {"setvideo", gl_setvideo, METH_OLDARGS},
- {"shademodel", gl_shademodel, METH_OLDARGS},
- {"underlay", gl_underlay, METH_OLDARGS},
- {"bgnclosedline", gl_bgnclosedline, METH_OLDARGS},
- {"bgnline", gl_bgnline, METH_OLDARGS},
- {"bgnpoint", gl_bgnpoint, METH_OLDARGS},
- {"bgnpolygon", gl_bgnpolygon, METH_OLDARGS},
- {"bgnsurface", gl_bgnsurface, METH_OLDARGS},
- {"bgntmesh", gl_bgntmesh, METH_OLDARGS},
- {"bgntrim", gl_bgntrim, METH_OLDARGS},
- {"endclosedline", gl_endclosedline, METH_OLDARGS},
- {"endline", gl_endline, METH_OLDARGS},
- {"endpoint", gl_endpoint, METH_OLDARGS},
- {"endpolygon", gl_endpolygon, METH_OLDARGS},
- {"endsurface", gl_endsurface, METH_OLDARGS},
- {"endtmesh", gl_endtmesh, METH_OLDARGS},
- {"endtrim", gl_endtrim, METH_OLDARGS},
- {"blendfunction", gl_blendfunction, METH_OLDARGS},
- {"c3f", gl_c3f, METH_OLDARGS},
- {"c3i", gl_c3i, METH_OLDARGS},
- {"c3s", gl_c3s, METH_OLDARGS},
- {"c4f", gl_c4f, METH_OLDARGS},
- {"c4i", gl_c4i, METH_OLDARGS},
- {"c4s", gl_c4s, METH_OLDARGS},
- {"colorf", gl_colorf, METH_OLDARGS},
- {"cpack", gl_cpack, METH_OLDARGS},
- {"czclear", gl_czclear, METH_OLDARGS},
- {"dglclose", gl_dglclose, METH_OLDARGS},
- {"dglopen", gl_dglopen, METH_OLDARGS},
- {"getgdesc", gl_getgdesc, METH_OLDARGS},
- {"getnurbsproperty", gl_getnurbsproperty, METH_OLDARGS},
- {"glcompat", gl_glcompat, METH_OLDARGS},
- {"iconsize", gl_iconsize, METH_OLDARGS},
- {"icontitle", gl_icontitle, METH_OLDARGS},
- {"lRGBrange", gl_lRGBrange, METH_OLDARGS},
- {"linesmooth", gl_linesmooth, METH_OLDARGS},
- {"lmcolor", gl_lmcolor, METH_OLDARGS},
- {"logicop", gl_logicop, METH_OLDARGS},
- {"lsetdepth", gl_lsetdepth, METH_OLDARGS},
- {"lshaderange", gl_lshaderange, METH_OLDARGS},
- {"n3f", gl_n3f, METH_OLDARGS},
- {"noborder", gl_noborder, METH_OLDARGS},
- {"pntsmooth", gl_pntsmooth, METH_OLDARGS},
- {"readsource", gl_readsource, METH_OLDARGS},
- {"rectzoom", gl_rectzoom, METH_OLDARGS},
- {"sbox", gl_sbox, METH_OLDARGS},
- {"sboxi", gl_sboxi, METH_OLDARGS},
- {"sboxs", gl_sboxs, METH_OLDARGS},
- {"sboxf", gl_sboxf, METH_OLDARGS},
- {"sboxfi", gl_sboxfi, METH_OLDARGS},
- {"sboxfs", gl_sboxfs, METH_OLDARGS},
- {"setnurbsproperty", gl_setnurbsproperty, METH_OLDARGS},
- {"setpup", gl_setpup, METH_OLDARGS},
- {"smoothline", gl_smoothline, METH_OLDARGS},
- {"subpixel", gl_subpixel, METH_OLDARGS},
- {"swaptmesh", gl_swaptmesh, METH_OLDARGS},
- {"swinopen", gl_swinopen, METH_OLDARGS},
- {"v2f", gl_v2f, METH_OLDARGS},
- {"v2i", gl_v2i, METH_OLDARGS},
- {"v2s", gl_v2s, METH_OLDARGS},
- {"v3f", gl_v3f, METH_OLDARGS},
- {"v3i", gl_v3i, METH_OLDARGS},
- {"v3s", gl_v3s, METH_OLDARGS},
- {"v4f", gl_v4f, METH_OLDARGS},
- {"v4i", gl_v4i, METH_OLDARGS},
- {"v4s", gl_v4s, METH_OLDARGS},
- {"videocmd", gl_videocmd, METH_OLDARGS},
- {"windepth", gl_windepth, METH_OLDARGS},
- {"wmpack", gl_wmpack, METH_OLDARGS},
- {"zdraw", gl_zdraw, METH_OLDARGS},
- {"zfunction", gl_zfunction, METH_OLDARGS},
- {"zsource", gl_zsource, METH_OLDARGS},
- {"zwritemask", gl_zwritemask, METH_OLDARGS},
- {"v2d", gl_v2d, METH_OLDARGS},
- {"v3d", gl_v3d, METH_OLDARGS},
- {"v4d", gl_v4d, METH_OLDARGS},
- {"pixmode", gl_pixmode, METH_OLDARGS},
- {"qgetfd", gl_qgetfd, METH_OLDARGS},
- {"dither", gl_dither, METH_OLDARGS},
- {NULL, NULL} /* Sentinel */
+ {"qread", gl_qread, METH_OLDARGS},
+ {"varray", gl_varray, METH_OLDARGS},
+ {"nvarray", gl_nvarray, METH_OLDARGS},
+ {"vnarray", gl_vnarray, METH_OLDARGS},
+ {"nurbssurface", gl_nurbssurface, METH_OLDARGS},
+ {"nurbscurve", gl_nurbscurve, METH_OLDARGS},
+ {"pwlcurve", gl_pwlcurve, METH_OLDARGS},
+ {"pick", gl_pick, METH_OLDARGS},
+ {"endpick", gl_endpick, METH_NOARGS},
+ {"gselect", gl_gselect, METH_OLDARGS},
+ {"endselect", gl_endselect, METH_NOARGS},
+ {"getmatrix", gl_getmatrix, METH_OLDARGS},
+ {"altgetmatrix", gl_altgetmatrix, METH_OLDARGS},
+ {"lrectwrite", gl_lrectwrite, METH_OLDARGS},
+ {"lrectread", gl_lrectread, METH_OLDARGS},
+ {"readdisplay", gl_readdisplay, METH_OLDARGS},
+ {"packrect", gl_packrect, METH_OLDARGS},
+ {"unpackrect", gl_unpackrect, METH_OLDARGS},
+ {"gversion", gl_gversion, METH_OLDARGS},
+ {"clear", gl_clear, METH_OLDARGS},
+ {"getshade", gl_getshade, METH_OLDARGS},
+ {"devport", gl_devport, METH_OLDARGS},
+ {"rdr2i", gl_rdr2i, METH_OLDARGS},
+ {"rectfs", gl_rectfs, METH_OLDARGS},
+ {"rects", gl_rects, METH_OLDARGS},
+ {"rmv2i", gl_rmv2i, METH_OLDARGS},
+ {"noport", gl_noport, METH_OLDARGS},
+ {"popviewport", gl_popviewport, METH_OLDARGS},
+ {"clearhitcode", gl_clearhitcode, METH_OLDARGS},
+ {"closeobj", gl_closeobj, METH_OLDARGS},
+ {"cursoff", gl_cursoff, METH_OLDARGS},
+ {"curson", gl_curson, METH_OLDARGS},
+ {"doublebuffer", gl_doublebuffer, METH_OLDARGS},
+ {"finish", gl_finish, METH_OLDARGS},
+ {"gconfig", gl_gconfig, METH_OLDARGS},
+ {"ginit", gl_ginit, METH_OLDARGS},
+ {"greset", gl_greset, METH_OLDARGS},
+ {"multimap", gl_multimap, METH_OLDARGS},
+ {"onemap", gl_onemap, METH_OLDARGS},
+ {"popattributes", gl_popattributes, METH_OLDARGS},
+ {"popmatrix", gl_popmatrix, METH_OLDARGS},
+ {"pushattributes", gl_pushattributes,METH_OLDARGS},
+ {"pushmatrix", gl_pushmatrix, METH_OLDARGS},
+ {"pushviewport", gl_pushviewport, METH_OLDARGS},
+ {"qreset", gl_qreset, METH_OLDARGS},
+ {"RGBmode", gl_RGBmode, METH_OLDARGS},
+ {"singlebuffer", gl_singlebuffer, METH_OLDARGS},
+ {"swapbuffers", gl_swapbuffers, METH_OLDARGS},
+ {"gsync", gl_gsync, METH_OLDARGS},
+ {"gflush", gl_gflush, METH_OLDARGS},
+ {"tpon", gl_tpon, METH_OLDARGS},
+ {"tpoff", gl_tpoff, METH_OLDARGS},
+ {"clkon", gl_clkon, METH_OLDARGS},
+ {"clkoff", gl_clkoff, METH_OLDARGS},
+ {"ringbell", gl_ringbell, METH_OLDARGS},
+ {"gbegin", gl_gbegin, METH_OLDARGS},
+ {"textinit", gl_textinit, METH_OLDARGS},
+ {"initnames", gl_initnames, METH_OLDARGS},
+ {"pclos", gl_pclos, METH_OLDARGS},
+ {"popname", gl_popname, METH_OLDARGS},
+ {"spclos", gl_spclos, METH_OLDARGS},
+ {"zclear", gl_zclear, METH_OLDARGS},
+ {"screenspace", gl_screenspace, METH_OLDARGS},
+ {"reshapeviewport", gl_reshapeviewport, METH_OLDARGS},
+ {"winpush", gl_winpush, METH_OLDARGS},
+ {"winpop", gl_winpop, METH_OLDARGS},
+ {"foreground", gl_foreground, METH_OLDARGS},
+ {"endfullscrn", gl_endfullscrn, METH_OLDARGS},
+ {"endpupmode", gl_endpupmode, METH_OLDARGS},
+ {"fullscrn", gl_fullscrn, METH_OLDARGS},
+ {"pupmode", gl_pupmode, METH_OLDARGS},
+ {"winconstraints", gl_winconstraints, METH_OLDARGS},
+ {"pagecolor", gl_pagecolor, METH_OLDARGS},
+ {"textcolor", gl_textcolor, METH_OLDARGS},
+ {"color", gl_color, METH_OLDARGS},
+ {"curveit", gl_curveit, METH_OLDARGS},
+ {"font", gl_font, METH_OLDARGS},
+ {"linewidth", gl_linewidth, METH_OLDARGS},
+ {"setlinestyle", gl_setlinestyle, METH_OLDARGS},
+ {"setmap", gl_setmap, METH_OLDARGS},
+ {"swapinterval", gl_swapinterval, METH_OLDARGS},
+ {"writemask", gl_writemask, METH_OLDARGS},
+ {"textwritemask", gl_textwritemask, METH_OLDARGS},
+ {"qdevice", gl_qdevice, METH_OLDARGS},
+ {"unqdevice", gl_unqdevice, METH_OLDARGS},
+ {"curvebasis", gl_curvebasis, METH_OLDARGS},
+ {"curveprecision", gl_curveprecision,METH_OLDARGS},
+ {"loadname", gl_loadname, METH_OLDARGS},
+ {"passthrough", gl_passthrough, METH_OLDARGS},
+ {"pushname", gl_pushname, METH_OLDARGS},
+ {"setmonitor", gl_setmonitor, METH_OLDARGS},
+ {"setshade", gl_setshade, METH_OLDARGS},
+ {"setpattern", gl_setpattern, METH_OLDARGS},
+ {"pagewritemask", gl_pagewritemask, METH_OLDARGS},
+ {"callobj", gl_callobj, METH_OLDARGS},
+ {"delobj", gl_delobj, METH_OLDARGS},
+ {"editobj", gl_editobj, METH_OLDARGS},
+ {"makeobj", gl_makeobj, METH_OLDARGS},
+ {"maketag", gl_maketag, METH_OLDARGS},
+ {"chunksize", gl_chunksize, METH_OLDARGS},
+ {"compactify", gl_compactify, METH_OLDARGS},
+ {"deltag", gl_deltag, METH_OLDARGS},
+ {"lsrepeat", gl_lsrepeat, METH_OLDARGS},
+ {"objinsert", gl_objinsert, METH_OLDARGS},
+ {"objreplace", gl_objreplace, METH_OLDARGS},
+ {"winclose", gl_winclose, METH_OLDARGS},
+ {"blanktime", gl_blanktime, METH_OLDARGS},
+ {"freepup", gl_freepup, METH_OLDARGS},
+ {"backbuffer", gl_backbuffer, METH_OLDARGS},
+ {"frontbuffer", gl_frontbuffer, METH_OLDARGS},
+ {"lsbackup", gl_lsbackup, METH_OLDARGS},
+ {"resetls", gl_resetls, METH_OLDARGS},
+ {"lampon", gl_lampon, METH_OLDARGS},
+ {"lampoff", gl_lampoff, METH_OLDARGS},
+ {"setbell", gl_setbell, METH_OLDARGS},
+ {"blankscreen", gl_blankscreen, METH_OLDARGS},
+ {"depthcue", gl_depthcue, METH_OLDARGS},
+ {"zbuffer", gl_zbuffer, METH_OLDARGS},
+ {"backface", gl_backface, METH_OLDARGS},
+ {"cmov2i", gl_cmov2i, METH_OLDARGS},
+ {"draw2i", gl_draw2i, METH_OLDARGS},
+ {"move2i", gl_move2i, METH_OLDARGS},
+ {"pnt2i", gl_pnt2i, METH_OLDARGS},
+ {"patchbasis", gl_patchbasis, METH_OLDARGS},
+ {"patchprecision", gl_patchprecision, METH_OLDARGS},
+ {"pdr2i", gl_pdr2i, METH_OLDARGS},
+ {"pmv2i", gl_pmv2i, METH_OLDARGS},
+ {"rpdr2i", gl_rpdr2i, METH_OLDARGS},
+ {"rpmv2i", gl_rpmv2i, METH_OLDARGS},
+ {"xfpt2i", gl_xfpt2i, METH_OLDARGS},
+ {"objdelete", gl_objdelete, METH_OLDARGS},
+ {"patchcurves", gl_patchcurves, METH_OLDARGS},
+ {"minsize", gl_minsize, METH_OLDARGS},
+ {"maxsize", gl_maxsize, METH_OLDARGS},
+ {"keepaspect", gl_keepaspect, METH_OLDARGS},
+ {"prefsize", gl_prefsize, METH_OLDARGS},
+ {"stepunit", gl_stepunit, METH_OLDARGS},
+ {"fudge", gl_fudge, METH_OLDARGS},
+ {"winmove", gl_winmove, METH_OLDARGS},
+ {"attachcursor", gl_attachcursor, METH_OLDARGS},
+ {"deflinestyle", gl_deflinestyle, METH_OLDARGS},
+ {"noise", gl_noise, METH_OLDARGS},
+ {"picksize", gl_picksize, METH_OLDARGS},
+ {"qenter", gl_qenter, METH_OLDARGS},
+ {"setdepth", gl_setdepth, METH_OLDARGS},
+ {"cmov2s", gl_cmov2s, METH_OLDARGS},
+ {"draw2s", gl_draw2s, METH_OLDARGS},
+ {"move2s", gl_move2s, METH_OLDARGS},
+ {"pdr2s", gl_pdr2s, METH_OLDARGS},
+ {"pmv2s", gl_pmv2s, METH_OLDARGS},
+ {"pnt2s", gl_pnt2s, METH_OLDARGS},
+ {"rdr2s", gl_rdr2s, METH_OLDARGS},
+ {"rmv2s", gl_rmv2s, METH_OLDARGS},
+ {"rpdr2s", gl_rpdr2s, METH_OLDARGS},
+ {"rpmv2s", gl_rpmv2s, METH_OLDARGS},
+ {"xfpt2s", gl_xfpt2s, METH_OLDARGS},
+ {"cmov2", gl_cmov2, METH_OLDARGS},
+ {"draw2", gl_draw2, METH_OLDARGS},
+ {"move2", gl_move2, METH_OLDARGS},
+ {"pnt2", gl_pnt2, METH_OLDARGS},
+ {"pdr2", gl_pdr2, METH_OLDARGS},
+ {"pmv2", gl_pmv2, METH_OLDARGS},
+ {"rdr2", gl_rdr2, METH_OLDARGS},
+ {"rmv2", gl_rmv2, METH_OLDARGS},
+ {"rpdr2", gl_rpdr2, METH_OLDARGS},
+ {"rpmv2", gl_rpmv2, METH_OLDARGS},
+ {"xfpt2", gl_xfpt2, METH_OLDARGS},
+ {"loadmatrix", gl_loadmatrix, METH_OLDARGS},
+ {"multmatrix", gl_multmatrix, METH_OLDARGS},
+ {"crv", gl_crv, METH_OLDARGS},
+ {"rcrv", gl_rcrv, METH_OLDARGS},
+ {"addtopup", gl_addtopup, METH_OLDARGS},
+ {"charstr", gl_charstr, METH_OLDARGS},
+ {"getport", gl_getport, METH_OLDARGS},
+ {"strwidth", gl_strwidth, METH_OLDARGS},
+ {"winopen", gl_winopen, METH_OLDARGS},
+ {"wintitle", gl_wintitle, METH_OLDARGS},
+ {"polf", gl_polf, METH_OLDARGS},
+ {"polf2", gl_polf2, METH_OLDARGS},
+ {"poly", gl_poly, METH_OLDARGS},
+ {"poly2", gl_poly2, METH_OLDARGS},
+ {"crvn", gl_crvn, METH_OLDARGS},
+ {"rcrvn", gl_rcrvn, METH_OLDARGS},
+ {"polf2i", gl_polf2i, METH_OLDARGS},
+ {"polfi", gl_polfi, METH_OLDARGS},
+ {"poly2i", gl_poly2i, METH_OLDARGS},
+ {"polyi", gl_polyi, METH_OLDARGS},
+ {"polf2s", gl_polf2s, METH_OLDARGS},
+ {"polfs", gl_polfs, METH_OLDARGS},
+ {"polys", gl_polys, METH_OLDARGS},
+ {"poly2s", gl_poly2s, METH_OLDARGS},
+ {"defcursor", gl_defcursor, METH_OLDARGS},
+ {"writepixels", gl_writepixels, METH_OLDARGS},
+ {"defbasis", gl_defbasis, METH_OLDARGS},
+ {"gewrite", gl_gewrite, METH_OLDARGS},
+ {"rotate", gl_rotate, METH_OLDARGS},
+ {"rot", gl_rot, METH_OLDARGS},
+ {"circfi", gl_circfi, METH_OLDARGS},
+ {"circi", gl_circi, METH_OLDARGS},
+ {"cmovi", gl_cmovi, METH_OLDARGS},
+ {"drawi", gl_drawi, METH_OLDARGS},
+ {"movei", gl_movei, METH_OLDARGS},
+ {"pnti", gl_pnti, METH_OLDARGS},
+ {"newtag", gl_newtag, METH_OLDARGS},
+ {"pdri", gl_pdri, METH_OLDARGS},
+ {"pmvi", gl_pmvi, METH_OLDARGS},
+ {"rdri", gl_rdri, METH_OLDARGS},
+ {"rmvi", gl_rmvi, METH_OLDARGS},
+ {"rpdri", gl_rpdri, METH_OLDARGS},
+ {"rpmvi", gl_rpmvi, METH_OLDARGS},
+ {"xfpti", gl_xfpti, METH_OLDARGS},
+ {"circ", gl_circ, METH_OLDARGS},
+ {"circf", gl_circf, METH_OLDARGS},
+ {"cmov", gl_cmov, METH_OLDARGS},
+ {"draw", gl_draw, METH_OLDARGS},
+ {"move", gl_move, METH_OLDARGS},
+ {"pnt", gl_pnt, METH_OLDARGS},
+ {"scale", gl_scale, METH_OLDARGS},
+ {"translate", gl_translate, METH_OLDARGS},
+ {"pdr", gl_pdr, METH_OLDARGS},
+ {"pmv", gl_pmv, METH_OLDARGS},
+ {"rdr", gl_rdr, METH_OLDARGS},
+ {"rmv", gl_rmv, METH_OLDARGS},
+ {"rpdr", gl_rpdr, METH_OLDARGS},
+ {"rpmv", gl_rpmv, METH_OLDARGS},
+ {"xfpt", gl_xfpt, METH_OLDARGS},
+ {"RGBcolor", gl_RGBcolor, METH_OLDARGS},
+ {"RGBwritemask", gl_RGBwritemask, METH_OLDARGS},
+ {"setcursor", gl_setcursor, METH_OLDARGS},
+ {"tie", gl_tie, METH_OLDARGS},
+ {"circfs", gl_circfs, METH_OLDARGS},
+ {"circs", gl_circs, METH_OLDARGS},
+ {"cmovs", gl_cmovs, METH_OLDARGS},
+ {"draws", gl_draws, METH_OLDARGS},
+ {"moves", gl_moves, METH_OLDARGS},
+ {"pdrs", gl_pdrs, METH_OLDARGS},
+ {"pmvs", gl_pmvs, METH_OLDARGS},
+ {"pnts", gl_pnts, METH_OLDARGS},
+ {"rdrs", gl_rdrs, METH_OLDARGS},
+ {"rmvs", gl_rmvs, METH_OLDARGS},
+ {"rpdrs", gl_rpdrs, METH_OLDARGS},
+ {"rpmvs", gl_rpmvs, METH_OLDARGS},
+ {"xfpts", gl_xfpts, METH_OLDARGS},
+ {"curorigin", gl_curorigin, METH_OLDARGS},
+ {"cyclemap", gl_cyclemap, METH_OLDARGS},
+ {"patch", gl_patch, METH_OLDARGS},
+ {"splf", gl_splf, METH_OLDARGS},
+ {"splf2", gl_splf2, METH_OLDARGS},
+ {"splfi", gl_splfi, METH_OLDARGS},
+ {"splf2i", gl_splf2i, METH_OLDARGS},
+ {"splfs", gl_splfs, METH_OLDARGS},
+ {"splf2s", gl_splf2s, METH_OLDARGS},
+ {"rpatch", gl_rpatch, METH_OLDARGS},
+ {"ortho2", gl_ortho2, METH_OLDARGS},
+ {"rect", gl_rect, METH_OLDARGS},
+ {"rectf", gl_rectf, METH_OLDARGS},
+ {"xfpt4", gl_xfpt4, METH_OLDARGS},
+ {"textport", gl_textport, METH_OLDARGS},
+ {"mapcolor", gl_mapcolor, METH_OLDARGS},
+ {"scrmask", gl_scrmask, METH_OLDARGS},
+ {"setvaluator", gl_setvaluator, METH_OLDARGS},
+ {"viewport", gl_viewport, METH_OLDARGS},
+ {"shaderange", gl_shaderange, METH_OLDARGS},
+ {"xfpt4s", gl_xfpt4s, METH_OLDARGS},
+ {"rectfi", gl_rectfi, METH_OLDARGS},
+ {"recti", gl_recti, METH_OLDARGS},
+ {"xfpt4i", gl_xfpt4i, METH_OLDARGS},
+ {"prefposition", gl_prefposition, METH_OLDARGS},
+ {"arc", gl_arc, METH_OLDARGS},
+ {"arcf", gl_arcf, METH_OLDARGS},
+ {"arcfi", gl_arcfi, METH_OLDARGS},
+ {"arci", gl_arci, METH_OLDARGS},
+ {"bbox2", gl_bbox2, METH_OLDARGS},
+ {"bbox2i", gl_bbox2i, METH_OLDARGS},
+ {"bbox2s", gl_bbox2s, METH_OLDARGS},
+ {"blink", gl_blink, METH_OLDARGS},
+ {"ortho", gl_ortho, METH_OLDARGS},
+ {"window", gl_window, METH_OLDARGS},
+ {"lookat", gl_lookat, METH_OLDARGS},
+ {"perspective", gl_perspective, METH_OLDARGS},
+ {"polarview", gl_polarview, METH_OLDARGS},
+ {"arcfs", gl_arcfs, METH_OLDARGS},
+ {"arcs", gl_arcs, METH_OLDARGS},
+ {"rectcopy", gl_rectcopy, METH_OLDARGS},
+ {"RGBcursor", gl_RGBcursor, METH_OLDARGS},
+ {"getbutton", gl_getbutton, METH_OLDARGS},
+ {"getcmmode", gl_getcmmode, METH_OLDARGS},
+ {"getlsbackup", gl_getlsbackup, METH_OLDARGS},
+ {"getresetls", gl_getresetls, METH_OLDARGS},
+ {"getdcm", gl_getdcm, METH_OLDARGS},
+ {"getzbuffer", gl_getzbuffer, METH_OLDARGS},
+ {"ismex", gl_ismex, METH_OLDARGS},
+ {"isobj", gl_isobj, METH_OLDARGS},
+ {"isqueued", gl_isqueued, METH_OLDARGS},
+ {"istag", gl_istag, METH_OLDARGS},
+ {"genobj", gl_genobj, METH_OLDARGS},
+ {"gentag", gl_gentag, METH_OLDARGS},
+ {"getbuffer", gl_getbuffer, METH_OLDARGS},
+ {"getcolor", gl_getcolor, METH_OLDARGS},
+ {"getdisplaymode", gl_getdisplaymode, METH_OLDARGS},
+ {"getfont", gl_getfont, METH_OLDARGS},
+ {"getheight", gl_getheight, METH_OLDARGS},
+ {"gethitcode", gl_gethitcode, METH_OLDARGS},
+ {"getlstyle", gl_getlstyle, METH_OLDARGS},
+ {"getlwidth", gl_getlwidth, METH_OLDARGS},
+ {"getmap", gl_getmap, METH_OLDARGS},
+ {"getplanes", gl_getplanes, METH_OLDARGS},
+ {"getwritemask", gl_getwritemask, METH_OLDARGS},
+ {"qtest", gl_qtest, METH_OLDARGS},
+ {"getlsrepeat", gl_getlsrepeat, METH_OLDARGS},
+ {"getmonitor", gl_getmonitor, METH_OLDARGS},
+ {"getopenobj", gl_getopenobj, METH_OLDARGS},
+ {"getpattern", gl_getpattern, METH_OLDARGS},
+ {"winget", gl_winget, METH_OLDARGS},
+ {"winattach", gl_winattach, METH_OLDARGS},
+ {"getothermonitor", gl_getothermonitor, METH_OLDARGS},
+ {"newpup", gl_newpup, METH_OLDARGS},
+ {"getvaluator", gl_getvaluator, METH_OLDARGS},
+ {"winset", gl_winset, METH_OLDARGS},
+ {"dopup", gl_dopup, METH_OLDARGS},
+ {"getdepth", gl_getdepth, METH_OLDARGS},
+ {"getcpos", gl_getcpos, METH_OLDARGS},
+ {"getsize", gl_getsize, METH_OLDARGS},
+ {"getorigin", gl_getorigin, METH_OLDARGS},
+ {"getviewport", gl_getviewport, METH_OLDARGS},
+ {"gettp", gl_gettp, METH_OLDARGS},
+ {"getgpos", gl_getgpos, METH_OLDARGS},
+ {"winposition", gl_winposition, METH_OLDARGS},
+ {"gRGBcolor", gl_gRGBcolor, METH_OLDARGS},
+ {"gRGBmask", gl_gRGBmask, METH_OLDARGS},
+ {"getscrmask", gl_getscrmask, METH_OLDARGS},
+ {"getmcolor", gl_getmcolor, METH_OLDARGS},
+ {"mapw", gl_mapw, METH_OLDARGS},
+ {"mapw2", gl_mapw2, METH_OLDARGS},
+ {"getcursor", gl_getcursor, METH_OLDARGS},
+ {"cmode", gl_cmode, METH_OLDARGS},
+ {"concave", gl_concave, METH_OLDARGS},
+ {"curstype", gl_curstype, METH_OLDARGS},
+ {"drawmode", gl_drawmode, METH_OLDARGS},
+ {"gammaramp", gl_gammaramp, METH_OLDARGS},
+ {"getbackface", gl_getbackface, METH_OLDARGS},
+ {"getdescender", gl_getdescender, METH_OLDARGS},
+ {"getdrawmode", gl_getdrawmode, METH_OLDARGS},
+ {"getmmode", gl_getmmode, METH_OLDARGS},
+ {"getsm", gl_getsm, METH_OLDARGS},
+ {"getvideo", gl_getvideo, METH_OLDARGS},
+ {"imakebackground", gl_imakebackground, METH_OLDARGS},
+ {"lmbind", gl_lmbind, METH_OLDARGS},
+ {"lmdef", gl_lmdef, METH_OLDARGS},
+ {"mmode", gl_mmode, METH_OLDARGS},
+ {"normal", gl_normal, METH_OLDARGS},
+ {"overlay", gl_overlay, METH_OLDARGS},
+ {"RGBrange", gl_RGBrange, METH_OLDARGS},
+ {"setvideo", gl_setvideo, METH_OLDARGS},
+ {"shademodel", gl_shademodel, METH_OLDARGS},
+ {"underlay", gl_underlay, METH_OLDARGS},
+ {"bgnclosedline", gl_bgnclosedline, METH_OLDARGS},
+ {"bgnline", gl_bgnline, METH_OLDARGS},
+ {"bgnpoint", gl_bgnpoint, METH_OLDARGS},
+ {"bgnpolygon", gl_bgnpolygon, METH_OLDARGS},
+ {"bgnsurface", gl_bgnsurface, METH_OLDARGS},
+ {"bgntmesh", gl_bgntmesh, METH_OLDARGS},
+ {"bgntrim", gl_bgntrim, METH_OLDARGS},
+ {"endclosedline", gl_endclosedline, METH_OLDARGS},
+ {"endline", gl_endline, METH_OLDARGS},
+ {"endpoint", gl_endpoint, METH_OLDARGS},
+ {"endpolygon", gl_endpolygon, METH_OLDARGS},
+ {"endsurface", gl_endsurface, METH_OLDARGS},
+ {"endtmesh", gl_endtmesh, METH_OLDARGS},
+ {"endtrim", gl_endtrim, METH_OLDARGS},
+ {"blendfunction", gl_blendfunction, METH_OLDARGS},
+ {"c3f", gl_c3f, METH_OLDARGS},
+ {"c3i", gl_c3i, METH_OLDARGS},
+ {"c3s", gl_c3s, METH_OLDARGS},
+ {"c4f", gl_c4f, METH_OLDARGS},
+ {"c4i", gl_c4i, METH_OLDARGS},
+ {"c4s", gl_c4s, METH_OLDARGS},
+ {"colorf", gl_colorf, METH_OLDARGS},
+ {"cpack", gl_cpack, METH_OLDARGS},
+ {"czclear", gl_czclear, METH_OLDARGS},
+ {"dglclose", gl_dglclose, METH_OLDARGS},
+ {"dglopen", gl_dglopen, METH_OLDARGS},
+ {"getgdesc", gl_getgdesc, METH_OLDARGS},
+ {"getnurbsproperty", gl_getnurbsproperty, METH_OLDARGS},
+ {"glcompat", gl_glcompat, METH_OLDARGS},
+ {"iconsize", gl_iconsize, METH_OLDARGS},
+ {"icontitle", gl_icontitle, METH_OLDARGS},
+ {"lRGBrange", gl_lRGBrange, METH_OLDARGS},
+ {"linesmooth", gl_linesmooth, METH_OLDARGS},
+ {"lmcolor", gl_lmcolor, METH_OLDARGS},
+ {"logicop", gl_logicop, METH_OLDARGS},
+ {"lsetdepth", gl_lsetdepth, METH_OLDARGS},
+ {"lshaderange", gl_lshaderange, METH_OLDARGS},
+ {"n3f", gl_n3f, METH_OLDARGS},
+ {"noborder", gl_noborder, METH_OLDARGS},
+ {"pntsmooth", gl_pntsmooth, METH_OLDARGS},
+ {"readsource", gl_readsource, METH_OLDARGS},
+ {"rectzoom", gl_rectzoom, METH_OLDARGS},
+ {"sbox", gl_sbox, METH_OLDARGS},
+ {"sboxi", gl_sboxi, METH_OLDARGS},
+ {"sboxs", gl_sboxs, METH_OLDARGS},
+ {"sboxf", gl_sboxf, METH_OLDARGS},
+ {"sboxfi", gl_sboxfi, METH_OLDARGS},
+ {"sboxfs", gl_sboxfs, METH_OLDARGS},
+ {"setnurbsproperty", gl_setnurbsproperty, METH_OLDARGS},
+ {"setpup", gl_setpup, METH_OLDARGS},
+ {"smoothline", gl_smoothline, METH_OLDARGS},
+ {"subpixel", gl_subpixel, METH_OLDARGS},
+ {"swaptmesh", gl_swaptmesh, METH_OLDARGS},
+ {"swinopen", gl_swinopen, METH_OLDARGS},
+ {"v2f", gl_v2f, METH_OLDARGS},
+ {"v2i", gl_v2i, METH_OLDARGS},
+ {"v2s", gl_v2s, METH_OLDARGS},
+ {"v3f", gl_v3f, METH_OLDARGS},
+ {"v3i", gl_v3i, METH_OLDARGS},
+ {"v3s", gl_v3s, METH_OLDARGS},
+ {"v4f", gl_v4f, METH_OLDARGS},
+ {"v4i", gl_v4i, METH_OLDARGS},
+ {"v4s", gl_v4s, METH_OLDARGS},
+ {"videocmd", gl_videocmd, METH_OLDARGS},
+ {"windepth", gl_windepth, METH_OLDARGS},
+ {"wmpack", gl_wmpack, METH_OLDARGS},
+ {"zdraw", gl_zdraw, METH_OLDARGS},
+ {"zfunction", gl_zfunction, METH_OLDARGS},
+ {"zsource", gl_zsource, METH_OLDARGS},
+ {"zwritemask", gl_zwritemask, METH_OLDARGS},
+ {"v2d", gl_v2d, METH_OLDARGS},
+ {"v3d", gl_v3d, METH_OLDARGS},
+ {"v4d", gl_v4d, METH_OLDARGS},
+ {"pixmode", gl_pixmode, METH_OLDARGS},
+ {"qgetfd", gl_qgetfd, METH_OLDARGS},
+ {"dither", gl_dither, METH_OLDARGS},
+ {NULL, NULL} /* Sentinel */
};
void
initgl(void)
{
-
+
if (PyErr_WarnPy3k("the gl module has been removed in "
"Python 3.0", 2) < 0)
- return;
-
- (void) Py_InitModule("gl", gl_methods);
+ return;
+
+ (void) Py_InitModule("gl", gl_methods);
}
diff --git a/Modules/imageop.c b/Modules/imageop.c
index 8d0d68f..8bd11b2 100644
--- a/Modules/imageop.c
+++ b/Modules/imageop.c
@@ -33,10 +33,10 @@ static PyObject *ImageopDict;
static int
check_coordonnate(int value, const char* name)
{
- if ( 0 < value)
- return 1;
- PyErr_Format(PyExc_ValueError, "%s value is negative or nul", name);
- return 0;
+ if ( 0 < value)
+ return 1;
+ PyErr_Format(PyExc_ValueError, "%s value is negative or nul", name);
+ return 0;
}
/**
@@ -46,14 +46,14 @@ check_coordonnate(int value, const char* name)
static int
check_multiply_size(int product, int x, const char* xname, int y, const char* yname, int size)
{
- if ( !check_coordonnate(x, xname) )
- return 0;
- if ( !check_coordonnate(y, yname) )
- return 0;
- if ( size == (product / y) / x )
- return 1;
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
+ if ( !check_coordonnate(x, xname) )
+ return 0;
+ if ( !check_coordonnate(y, yname) )
+ return 0;
+ if ( size == (product / y) / x )
+ return 1;
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
}
/**
@@ -63,7 +63,7 @@ check_multiply_size(int product, int x, const char* xname, int y, const char* yn
static int
check_multiply(int product, int x, int y)
{
- return check_multiply_size(product, x, "x", y, "y", 1);
+ return check_multiply_size(product, x, "x", y, "y", 1);
}
/* If this function returns true (the default if anything goes wrong), we're
@@ -86,131 +86,131 @@ check_multiply(int product, int x, int y)
static int
imageop_backward_compatible(void)
{
- static PyObject *bcos;
- PyObject *bco;
- long rc;
-
- if (ImageopDict == NULL) /* "cannot happen" */
- return 1;
- if (bcos == NULL) {
- /* cache string object for future use */
- bcos = PyString_FromString("backward_compatible");
- if (bcos == NULL)
- return 1;
- }
- bco = PyDict_GetItem(ImageopDict, bcos);
- if (bco == NULL)
- return 1;
- if (!PyInt_Check(bco))
- return 1;
- rc = PyInt_AsLong(bco);
- if (PyErr_Occurred()) {
- /* not an integer, or too large, or something */
- PyErr_Clear();
- rc = 1;
- }
- return rc != 0; /* convert to values 0, 1 */
+ static PyObject *bcos;
+ PyObject *bco;
+ long rc;
+
+ if (ImageopDict == NULL) /* "cannot happen" */
+ return 1;
+ if (bcos == NULL) {
+ /* cache string object for future use */
+ bcos = PyString_FromString("backward_compatible");
+ if (bcos == NULL)
+ return 1;
+ }
+ bco = PyDict_GetItem(ImageopDict, bcos);
+ if (bco == NULL)
+ return 1;
+ if (!PyInt_Check(bco))
+ return 1;
+ rc = PyInt_AsLong(bco);
+ if (PyErr_Occurred()) {
+ /* not an integer, or too large, or something */
+ PyErr_Clear();
+ rc = 1;
+ }
+ return rc != 0; /* convert to values 0, 1 */
}
static PyObject *
imageop_crop(PyObject *self, PyObject *args)
{
- char *cp, *ncp;
- short *nsp;
- Py_Int32 *nlp;
- int len, size, x, y, newx1, newx2, newy1, newy2, nlen;
- int ix, iy, xstep, ystep;
- PyObject *rv;
-
- if ( !PyArg_ParseTuple(args, "s#iiiiiii", &cp, &len, &size, &x, &y,
- &newx1, &newy1, &newx2, &newy2) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
- return 0;
- }
- if ( !check_multiply_size(len, x, "x", y, "y", size) )
- return 0;
-
- xstep = (newx1 < newx2)? 1 : -1;
- ystep = (newy1 < newy2)? 1 : -1;
-
- nlen = (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size;
- if ( !check_multiply_size(nlen, abs(newx2-newx1)+1, "abs(newx2-newx1)+1", abs(newy2-newy1)+1, "abs(newy2-newy1)+1", size) )
- return 0;
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (char *)PyString_AsString(rv);
- nsp = (short *)ncp;
- nlp = (Py_Int32 *)ncp;
- newy2 += ystep;
- newx2 += xstep;
- for( iy = newy1; iy != newy2; iy+=ystep ) {
- for ( ix = newx1; ix != newx2; ix+=xstep ) {
- if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) {
- if ( size == 1 )
- *ncp++ = 0;
- else
- *nlp++ = 0;
- } else {
- if ( size == 1 )
- *ncp++ = *CHARP(cp, x, ix, iy);
- else if ( size == 2 )
- *nsp++ = *SHORTP(cp, x, ix, iy);
- else
- *nlp++ = *LONGP(cp, x, ix, iy);
- }
- }
- }
- return rv;
+ char *cp, *ncp;
+ short *nsp;
+ Py_Int32 *nlp;
+ int len, size, x, y, newx1, newx2, newy1, newy2, nlen;
+ int ix, iy, xstep, ystep;
+ PyObject *rv;
+
+ if ( !PyArg_ParseTuple(args, "s#iiiiiii", &cp, &len, &size, &x, &y,
+ &newx1, &newy1, &newx2, &newy2) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ if ( !check_multiply_size(len, x, "x", y, "y", size) )
+ return 0;
+
+ xstep = (newx1 < newx2)? 1 : -1;
+ ystep = (newy1 < newy2)? 1 : -1;
+
+ nlen = (abs(newx2-newx1)+1)*(abs(newy2-newy1)+1)*size;
+ if ( !check_multiply_size(nlen, abs(newx2-newx1)+1, "abs(newx2-newx1)+1", abs(newy2-newy1)+1, "abs(newy2-newy1)+1", size) )
+ return 0;
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (char *)PyString_AsString(rv);
+ nsp = (short *)ncp;
+ nlp = (Py_Int32 *)ncp;
+ newy2 += ystep;
+ newx2 += xstep;
+ for( iy = newy1; iy != newy2; iy+=ystep ) {
+ for ( ix = newx1; ix != newx2; ix+=xstep ) {
+ if ( iy < 0 || iy >= y || ix < 0 || ix >= x ) {
+ if ( size == 1 )
+ *ncp++ = 0;
+ else
+ *nlp++ = 0;
+ } else {
+ if ( size == 1 )
+ *ncp++ = *CHARP(cp, x, ix, iy);
+ else if ( size == 2 )
+ *nsp++ = *SHORTP(cp, x, ix, iy);
+ else
+ *nlp++ = *LONGP(cp, x, ix, iy);
+ }
+ }
+ }
+ return rv;
}
static PyObject *
imageop_scale(PyObject *self, PyObject *args)
{
- char *cp, *ncp;
- short *nsp;
- Py_Int32 *nlp;
- int len, size, x, y, newx, newy, nlen;
- int ix, iy;
- int oix, oiy;
- PyObject *rv;
-
- if ( !PyArg_ParseTuple(args, "s#iiiii",
- &cp, &len, &size, &x, &y, &newx, &newy) )
- return 0;
-
- if ( size != 1 && size != 2 && size != 4 ) {
- PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
- return 0;
- }
- if ( !check_multiply_size(len, x, "x", y, "y", size) )
- return 0;
- nlen = newx*newy*size;
- if ( !check_multiply_size(nlen, newx, "newx", newy, "newy", size) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (char *)PyString_AsString(rv);
- nsp = (short *)ncp;
- nlp = (Py_Int32 *)ncp;
- for( iy = 0; iy < newy; iy++ ) {
- for ( ix = 0; ix < newx; ix++ ) {
- oix = ix * x / newx;
- oiy = iy * y / newy;
- if ( size == 1 )
- *ncp++ = *CHARP(cp, x, oix, oiy);
- else if ( size == 2 )
- *nsp++ = *SHORTP(cp, x, oix, oiy);
- else
- *nlp++ = *LONGP(cp, x, oix, oiy);
- }
- }
- return rv;
+ char *cp, *ncp;
+ short *nsp;
+ Py_Int32 *nlp;
+ int len, size, x, y, newx, newy, nlen;
+ int ix, iy;
+ int oix, oiy;
+ PyObject *rv;
+
+ if ( !PyArg_ParseTuple(args, "s#iiiii",
+ &cp, &len, &size, &x, &y, &newx, &newy) )
+ return 0;
+
+ if ( size != 1 && size != 2 && size != 4 ) {
+ PyErr_SetString(ImageopError, "Size should be 1, 2 or 4");
+ return 0;
+ }
+ if ( !check_multiply_size(len, x, "x", y, "y", size) )
+ return 0;
+ nlen = newx*newy*size;
+ if ( !check_multiply_size(nlen, newx, "newx", newy, "newy", size) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (char *)PyString_AsString(rv);
+ nsp = (short *)ncp;
+ nlp = (Py_Int32 *)ncp;
+ for( iy = 0; iy < newy; iy++ ) {
+ for ( ix = 0; ix < newx; ix++ ) {
+ oix = ix * x / newx;
+ oiy = iy * y / newy;
+ if ( size == 1 )
+ *ncp++ = *CHARP(cp, x, oix, oiy);
+ else if ( size == 2 )
+ *nsp++ = *SHORTP(cp, x, oix, oiy);
+ else
+ *nlp++ = *LONGP(cp, x, oix, oiy);
+ }
+ }
+ return rv;
}
/* Note: this routine can use a bit of optimizing */
@@ -218,577 +218,577 @@ imageop_scale(PyObject *self, PyObject *args)
static PyObject *
imageop_tovideo(PyObject *self, PyObject *args)
{
- int maxx, maxy, x, y, len;
- int i;
- unsigned char *cp, *ncp;
- int width;
- PyObject *rv;
-
-
- if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &width, &maxx, &maxy) )
- return 0;
-
- if ( width != 1 && width != 4 ) {
- PyErr_SetString(ImageopError, "Size should be 1 or 4");
- return 0;
- }
- if ( !check_multiply_size(len, maxx, "max", maxy, "maxy", width) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, len);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- if ( width == 1 ) {
- memcpy(ncp, cp, maxx); /* Copy first line */
- ncp += maxx;
- for (y=1; y<maxy; y++) { /* Interpolate other lines */
- for(x=0; x<maxx; x++) {
- i = y*maxx + x;
- *ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1;
- }
- }
- } else {
- memcpy(ncp, cp, maxx*4); /* Copy first line */
- ncp += maxx*4;
- for (y=1; y<maxy; y++) { /* Interpolate other lines */
- for(x=0; x<maxx; x++) {
- i = (y*maxx + x)*4 + 1;
- *ncp++ = 0; /* Skip alfa comp */
- *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
- i++;
- *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
- i++;
- *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
- }
- }
- }
- return rv;
+ int maxx, maxy, x, y, len;
+ int i;
+ unsigned char *cp, *ncp;
+ int width;
+ PyObject *rv;
+
+
+ if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &width, &maxx, &maxy) )
+ return 0;
+
+ if ( width != 1 && width != 4 ) {
+ PyErr_SetString(ImageopError, "Size should be 1 or 4");
+ return 0;
+ }
+ if ( !check_multiply_size(len, maxx, "max", maxy, "maxy", width) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, len);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ if ( width == 1 ) {
+ memcpy(ncp, cp, maxx); /* Copy first line */
+ ncp += maxx;
+ for (y=1; y<maxy; y++) { /* Interpolate other lines */
+ for(x=0; x<maxx; x++) {
+ i = y*maxx + x;
+ *ncp++ = ((int)cp[i] + (int)cp[i-maxx]) >> 1;
+ }
+ }
+ } else {
+ memcpy(ncp, cp, maxx*4); /* Copy first line */
+ ncp += maxx*4;
+ for (y=1; y<maxy; y++) { /* Interpolate other lines */
+ for(x=0; x<maxx; x++) {
+ i = (y*maxx + x)*4 + 1;
+ *ncp++ = 0; /* Skip alfa comp */
+ *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
+ i++;
+ *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
+ i++;
+ *ncp++ = ((int)cp[i] + (int)cp[i-4*maxx]) >> 1;
+ }
+ }
+ }
+ return rv;
}
static PyObject *
imageop_grey2mono(PyObject *self, PyObject *args)
{
- int tres, x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i, bit;
-
-
- if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &x, &y, &tres) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+7)/8);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- bit = 0x80;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- if ( (int)cp[i] > tres )
- ovalue |= bit;
- bit >>= 1;
- if ( bit == 0 ) {
- *ncp++ = ovalue;
- bit = 0x80;
- ovalue = 0;
- }
- }
- if ( bit != 0x80 )
- *ncp++ = ovalue;
- return rv;
+ int tres, x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i, bit;
+
+
+ if ( !PyArg_ParseTuple(args, "s#iii", &cp, &len, &x, &y, &tres) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+7)/8);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ bit = 0x80;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ if ( (int)cp[i] > tres )
+ ovalue |= bit;
+ bit >>= 1;
+ if ( bit == 0 ) {
+ *ncp++ = ovalue;
+ bit = 0x80;
+ ovalue = 0;
+ }
+ }
+ if ( bit != 0x80 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_grey2grey4(PyObject *self, PyObject *args)
{
- int x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i;
- int pos;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+1)/2);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
- pos = 0;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- ovalue |= ((int)cp[i] & 0xf0) >> pos;
- pos += 4;
- if ( pos == 8 ) {
- *ncp++ = ovalue;
- ovalue = 0;
- pos = 0;
- }
- }
- if ( pos != 0 )
- *ncp++ = ovalue;
- return rv;
+ int x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i;
+ int pos;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+1)/2);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+ pos = 0;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ ovalue |= ((int)cp[i] & 0xf0) >> pos;
+ pos += 4;
+ if ( pos == 8 ) {
+ *ncp++ = ovalue;
+ ovalue = 0;
+ pos = 0;
+ }
+ }
+ if ( pos != 0 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_grey2grey2(PyObject *self, PyObject *args)
{
- int x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i;
- int pos;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+3)/4);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
- pos = 0;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- ovalue |= ((int)cp[i] & 0xc0) >> pos;
- pos += 2;
- if ( pos == 8 ) {
- *ncp++ = ovalue;
- ovalue = 0;
- pos = 0;
- }
- }
- if ( pos != 0 )
- *ncp++ = ovalue;
- return rv;
+ int x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i;
+ int pos;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+3)/4);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+ pos = 0;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ ovalue |= ((int)cp[i] & 0xc0) >> pos;
+ pos += 2;
+ if ( pos == 8 ) {
+ *ncp++ = ovalue;
+ ovalue = 0;
+ pos = 0;
+ }
+ }
+ if ( pos != 0 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_dither2mono(PyObject *self, PyObject *args)
{
- int sum, x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i, bit;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+7)/8);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- bit = 0x80;
- ovalue = 0;
- sum = 0;
- for ( i=0; i < len; i++ ) {
- sum += cp[i];
- if ( sum >= 256 ) {
- sum -= 256;
- ovalue |= bit;
- }
- bit >>= 1;
- if ( bit == 0 ) {
- *ncp++ = ovalue;
- bit = 0x80;
- ovalue = 0;
- }
- }
- if ( bit != 0x80 )
- *ncp++ = ovalue;
- return rv;
+ int sum, x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i, bit;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+7)/8);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ bit = 0x80;
+ ovalue = 0;
+ sum = 0;
+ for ( i=0; i < len; i++ ) {
+ sum += cp[i];
+ if ( sum >= 256 ) {
+ sum -= 256;
+ ovalue |= bit;
+ }
+ bit >>= 1;
+ if ( bit == 0 ) {
+ *ncp++ = ovalue;
+ bit = 0x80;
+ ovalue = 0;
+ }
+ }
+ if ( bit != 0x80 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_dither2grey2(PyObject *self, PyObject *args)
{
- int x, y, len;
- unsigned char *cp, *ncp;
- unsigned char ovalue;
- PyObject *rv;
- int i;
- int pos;
- int sum = 0, nvalue;
-
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, (len+3)/4);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
- pos = 1;
- ovalue = 0;
- for ( i=0; i < len; i++ ) {
- sum += cp[i];
- nvalue = sum & 0x180;
- sum -= nvalue;
- ovalue |= nvalue >> pos;
- pos += 2;
- if ( pos == 9 ) {
- *ncp++ = ovalue;
- ovalue = 0;
- pos = 1;
- }
- }
- if ( pos != 0 )
- *ncp++ = ovalue;
- return rv;
+ int x, y, len;
+ unsigned char *cp, *ncp;
+ unsigned char ovalue;
+ PyObject *rv;
+ int i;
+ int pos;
+ int sum = 0, nvalue;
+
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, (len+3)/4);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+ pos = 1;
+ ovalue = 0;
+ for ( i=0; i < len; i++ ) {
+ sum += cp[i];
+ nvalue = sum & 0x180;
+ sum -= nvalue;
+ ovalue |= nvalue >> pos;
+ pos += 2;
+ if ( pos == 9 ) {
+ *ncp++ = ovalue;
+ ovalue = 0;
+ pos = 1;
+ }
+ }
+ if ( pos != 0 )
+ *ncp++ = ovalue;
+ return rv;
}
static PyObject *
imageop_mono2grey(PyObject *self, PyObject *args)
{
- int v0, v1, x, y, len, nlen;
- unsigned char *cp, *ncp;
- PyObject *rv;
- int i, bit;
-
- if ( !PyArg_ParseTuple(args, "s#iiii", &cp, &len, &x, &y, &v0, &v1) )
- return 0;
-
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
- if ( (nlen+7)/8 != len ) {
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- bit = 0x80;
- for ( i=0; i < nlen; i++ ) {
- if ( *cp & bit )
- *ncp++ = v1;
- else
- *ncp++ = v0;
- bit >>= 1;
- if ( bit == 0 ) {
- bit = 0x80;
- cp++;
- }
- }
- return rv;
+ int v0, v1, x, y, len, nlen;
+ unsigned char *cp, *ncp;
+ PyObject *rv;
+ int i, bit;
+
+ if ( !PyArg_ParseTuple(args, "s#iiii", &cp, &len, &x, &y, &v0, &v1) )
+ return 0;
+
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+ if ( (nlen+7)/8 != len ) {
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ bit = 0x80;
+ for ( i=0; i < nlen; i++ ) {
+ if ( *cp & bit )
+ *ncp++ = v1;
+ else
+ *ncp++ = v0;
+ bit >>= 1;
+ if ( bit == 0 ) {
+ bit = 0x80;
+ cp++;
+ }
+ }
+ return rv;
}
static PyObject *
imageop_grey22grey(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp, *ncp;
- PyObject *rv;
- int i, pos, value = 0, nvalue;
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) ) {
- return 0;
- }
- if ( (nlen+3)/4 != len ) {
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- pos = 0;
- for ( i=0; i < nlen; i++ ) {
- if ( pos == 0 ) {
- value = *cp++;
- pos = 8;
- }
- pos -= 2;
- nvalue = (value >> pos) & 0x03;
- *ncp++ = nvalue | (nvalue << 2) |
- (nvalue << 4) | (nvalue << 6);
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp, *ncp;
+ PyObject *rv;
+ int i, pos, value = 0, nvalue;
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) ) {
+ return 0;
+ }
+ if ( (nlen+3)/4 != len ) {
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ pos = 0;
+ for ( i=0; i < nlen; i++ ) {
+ if ( pos == 0 ) {
+ value = *cp++;
+ pos = 8;
+ }
+ pos -= 2;
+ nvalue = (value >> pos) & 0x03;
+ *ncp++ = nvalue | (nvalue << 2) |
+ (nvalue << 4) | (nvalue << 6);
+ }
+ return rv;
}
static PyObject *
imageop_grey42grey(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp, *ncp;
- PyObject *rv;
- int i, pos, value = 0, nvalue;
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
- if ( (nlen+1)/2 != len ) {
- PyErr_SetString(ImageopError, "String has incorrect length");
- return 0;
- }
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- pos = 0;
- for ( i=0; i < nlen; i++ ) {
- if ( pos == 0 ) {
- value = *cp++;
- pos = 8;
- }
- pos -= 4;
- nvalue = (value >> pos) & 0x0f;
- *ncp++ = nvalue | (nvalue << 4);
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp, *ncp;
+ PyObject *rv;
+ int i, pos, value = 0, nvalue;
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+ if ( (nlen+1)/2 != len ) {
+ PyErr_SetString(ImageopError, "String has incorrect length");
+ return 0;
+ }
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ pos = 0;
+ for ( i=0; i < nlen; i++ ) {
+ if ( pos == 0 ) {
+ value = *cp++;
+ pos = 8;
+ }
+ pos -= 4;
+ nvalue = (value >> pos) & 0x0f;
+ *ncp++ = nvalue | (nvalue << 4);
+ }
+ return rv;
}
static PyObject *
imageop_rgb2rgb8(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i, r, g, b;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply_size(len, x, "x", y, "y", 4) )
- return 0;
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < nlen; i++ ) {
- /* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
- if (backward_compatible) {
- Py_UInt32 value = * (Py_UInt32 *) cp;
- cp += 4;
- r = (int) ((value & 0xff) / 255. * 7. + .5);
- g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
- b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
- } else {
- cp++; /* skip alpha channel */
- b = (int) (*cp++ / 255. * 3. + .5);
- g = (int) (*cp++ / 255. * 7. + .5);
- r = (int) (*cp++ / 255. * 7. + .5);
- }
- *ncp++ = (unsigned char)((r<<5) | (b<<3) | g);
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i, r, g, b;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply_size(len, x, "x", y, "y", 4) )
+ return 0;
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < nlen; i++ ) {
+ /* Bits in source: aaaaaaaa BBbbbbbb GGGggggg RRRrrrrr */
+ if (backward_compatible) {
+ Py_UInt32 value = * (Py_UInt32 *) cp;
+ cp += 4;
+ r = (int) ((value & 0xff) / 255. * 7. + .5);
+ g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
+ b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
+ } else {
+ cp++; /* skip alpha channel */
+ b = (int) (*cp++ / 255. * 3. + .5);
+ g = (int) (*cp++ / 255. * 7. + .5);
+ r = (int) (*cp++ / 255. * 7. + .5);
+ }
+ *ncp++ = (unsigned char)((r<<5) | (b<<3) | g);
+ }
+ return rv;
}
static PyObject *
imageop_rgb82rgb(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i, r, g, b;
- unsigned char value;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
- nlen = x*y*4;
- if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i++ ) {
- /* Bits in source: RRRBBGGG
- ** Red and Green are multiplied by 36.5, Blue by 85
- */
- value = *cp++;
- r = (value >> 5) & 7;
- g = (value ) & 7;
- b = (value >> 3) & 3;
- r = (r<<5) | (r<<3) | (r>>1);
- g = (g<<5) | (g<<3) | (g>>1);
- b = (b<<6) | (b<<4) | (b<<2) | b;
- if (backward_compatible) {
- Py_UInt32 nvalue = r | (g<<8) | (b<<16);
- * (Py_UInt32 *) ncp = nvalue;
- ncp += 4;
- } else {
- *ncp++ = 0;
- *ncp++ = b;
- *ncp++ = g;
- *ncp++ = r;
- }
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i, r, g, b;
+ unsigned char value;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+ nlen = x*y*4;
+ if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i++ ) {
+ /* Bits in source: RRRBBGGG
+ ** Red and Green are multiplied by 36.5, Blue by 85
+ */
+ value = *cp++;
+ r = (value >> 5) & 7;
+ g = (value ) & 7;
+ b = (value >> 3) & 3;
+ r = (r<<5) | (r<<3) | (r>>1);
+ g = (g<<5) | (g<<3) | (g>>1);
+ b = (b<<6) | (b<<4) | (b<<2) | b;
+ if (backward_compatible) {
+ Py_UInt32 nvalue = r | (g<<8) | (b<<16);
+ * (Py_UInt32 *) ncp = nvalue;
+ ncp += 4;
+ } else {
+ *ncp++ = 0;
+ *ncp++ = b;
+ *ncp++ = g;
+ *ncp++ = r;
+ }
+ }
+ return rv;
}
static PyObject *
imageop_rgb2grey(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i, r, g, b;
- int nvalue;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply_size(len, x, "x", y, "y", 4) )
- return 0;
- nlen = x*y;
- if ( !check_multiply(nlen, x, y) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < nlen; i++ ) {
- if (backward_compatible) {
- Py_UInt32 value = * (Py_UInt32 *) cp;
- cp += 4;
- r = (int) ((value & 0xff) / 255. * 7. + .5);
- g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
- b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
- } else {
- cp++; /* skip alpha channel */
- b = *cp++;
- g = *cp++;
- r = *cp++;
- }
- nvalue = (int)(0.30*r + 0.59*g + 0.11*b);
- if ( nvalue > 255 ) nvalue = 255;
- *ncp++ = (unsigned char)nvalue;
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i, r, g, b;
+ int nvalue;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply_size(len, x, "x", y, "y", 4) )
+ return 0;
+ nlen = x*y;
+ if ( !check_multiply(nlen, x, y) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < nlen; i++ ) {
+ if (backward_compatible) {
+ Py_UInt32 value = * (Py_UInt32 *) cp;
+ cp += 4;
+ r = (int) ((value & 0xff) / 255. * 7. + .5);
+ g = (int) (((value >> 8) & 0xff) / 255. * 7. + .5);
+ b = (int) (((value >> 16) & 0xff) / 255. * 3. + .5);
+ } else {
+ cp++; /* skip alpha channel */
+ b = *cp++;
+ g = *cp++;
+ r = *cp++;
+ }
+ nvalue = (int)(0.30*r + 0.59*g + 0.11*b);
+ if ( nvalue > 255 ) nvalue = 255;
+ *ncp++ = (unsigned char)nvalue;
+ }
+ return rv;
}
static PyObject *
imageop_grey2rgb(PyObject *self, PyObject *args)
{
- int x, y, len, nlen;
- unsigned char *cp;
- unsigned char *ncp;
- PyObject *rv;
- int i;
- unsigned char value;
- int backward_compatible = imageop_backward_compatible();
-
- if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
- return 0;
-
- if ( !check_multiply(len, x, y) )
- return 0;
- nlen = x*y*4;
- if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
- return 0;
-
- rv = PyString_FromStringAndSize(NULL, nlen);
- if ( rv == 0 )
- return 0;
- ncp = (unsigned char *)PyString_AsString(rv);
-
- for ( i=0; i < len; i++ ) {
- value = *cp++;
- if (backward_compatible) {
- * (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
- ncp += 4;
- } else {
- *ncp++ = 0;
- *ncp++ = value;
- *ncp++ = value;
- *ncp++ = value;
- }
- }
- return rv;
+ int x, y, len, nlen;
+ unsigned char *cp;
+ unsigned char *ncp;
+ PyObject *rv;
+ int i;
+ unsigned char value;
+ int backward_compatible = imageop_backward_compatible();
+
+ if ( !PyArg_ParseTuple(args, "s#ii", &cp, &len, &x, &y) )
+ return 0;
+
+ if ( !check_multiply(len, x, y) )
+ return 0;
+ nlen = x*y*4;
+ if ( !check_multiply_size(nlen, x, "x", y, "y", 4) )
+ return 0;
+
+ rv = PyString_FromStringAndSize(NULL, nlen);
+ if ( rv == 0 )
+ return 0;
+ ncp = (unsigned char *)PyString_AsString(rv);
+
+ for ( i=0; i < len; i++ ) {
+ value = *cp++;
+ if (backward_compatible) {
+ * (Py_UInt32 *) ncp = (Py_UInt32) value | ((Py_UInt32) value << 8 ) | ((Py_UInt32) value << 16);
+ ncp += 4;
+ } else {
+ *ncp++ = 0;
+ *ncp++ = value;
+ *ncp++ = value;
+ *ncp++ = value;
+ }
+ }
+ return rv;
}
static PyMethodDef imageop_methods[] = {
- { "crop", imageop_crop, METH_VARARGS },
- { "scale", imageop_scale, METH_VARARGS },
- { "grey2mono", imageop_grey2mono, METH_VARARGS },
- { "grey2grey2", imageop_grey2grey2, METH_VARARGS },
- { "grey2grey4", imageop_grey2grey4, METH_VARARGS },
- { "dither2mono", imageop_dither2mono, METH_VARARGS },
- { "dither2grey2", imageop_dither2grey2, METH_VARARGS },
- { "mono2grey", imageop_mono2grey, METH_VARARGS },
- { "grey22grey", imageop_grey22grey, METH_VARARGS },
- { "grey42grey", imageop_grey42grey, METH_VARARGS },
- { "tovideo", imageop_tovideo, METH_VARARGS },
- { "rgb2rgb8", imageop_rgb2rgb8, METH_VARARGS },
- { "rgb82rgb", imageop_rgb82rgb, METH_VARARGS },
- { "rgb2grey", imageop_rgb2grey, METH_VARARGS },
- { "grey2rgb", imageop_grey2rgb, METH_VARARGS },
- { 0, 0 }
+ { "crop", imageop_crop, METH_VARARGS },
+ { "scale", imageop_scale, METH_VARARGS },
+ { "grey2mono", imageop_grey2mono, METH_VARARGS },
+ { "grey2grey2", imageop_grey2grey2, METH_VARARGS },
+ { "grey2grey4", imageop_grey2grey4, METH_VARARGS },
+ { "dither2mono", imageop_dither2mono, METH_VARARGS },
+ { "dither2grey2", imageop_dither2grey2, METH_VARARGS },
+ { "mono2grey", imageop_mono2grey, METH_VARARGS },
+ { "grey22grey", imageop_grey22grey, METH_VARARGS },
+ { "grey42grey", imageop_grey42grey, METH_VARARGS },
+ { "tovideo", imageop_tovideo, METH_VARARGS },
+ { "rgb2rgb8", imageop_rgb2rgb8, METH_VARARGS },
+ { "rgb82rgb", imageop_rgb82rgb, METH_VARARGS },
+ { "rgb2grey", imageop_rgb2grey, METH_VARARGS },
+ { "grey2rgb", imageop_grey2rgb, METH_VARARGS },
+ { 0, 0 }
};
PyMODINIT_FUNC
initimageop(void)
{
- PyObject *m;
-
- if (PyErr_WarnPy3k("the imageop module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("imageop", imageop_methods);
- if (m == NULL)
- return;
- ImageopDict = PyModule_GetDict(m);
- ImageopError = PyErr_NewException("imageop.error", NULL, NULL);
- if (ImageopError != NULL)
- PyDict_SetItemString(ImageopDict, "error", ImageopError);
+ PyObject *m;
+
+ if (PyErr_WarnPy3k("the imageop module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("imageop", imageop_methods);
+ if (m == NULL)
+ return;
+ ImageopDict = PyModule_GetDict(m);
+ ImageopError = PyErr_NewException("imageop.error", NULL, NULL);
+ if (ImageopError != NULL)
+ PyDict_SetItemString(ImageopDict, "error", ImageopError);
}
diff --git a/Modules/imgfile.c b/Modules/imgfile.c
index baa6ead..70d307b 100644
--- a/Modules/imgfile.c
+++ b/Modules/imgfile.c
@@ -25,7 +25,7 @@ extern void getrow();
static PyObject * ImgfileError; /* Exception we raise for various trouble */
-static int top_to_bottom; /* True if we want top-to-bottom images */
+static int top_to_bottom; /* True if we want top-to-bottom images */
/* The image library does not always call the error hander :-(,
therefore we have a global variable indicating that it was called.
@@ -39,9 +39,9 @@ static int error_called;
static void
imgfile_error(char *str)
{
- PyErr_SetString(ImgfileError, str);
- error_called = 1;
- return; /* To imglib, which will return a failure indicator */
+ PyErr_SetString(ImgfileError, str);
+ error_called = 1;
+ return; /* To imglib, which will return a failure indicator */
}
@@ -51,123 +51,123 @@ imgfile_error(char *str)
static IMAGE *
imgfile_open(char *fname)
{
- IMAGE *image;
- i_seterror(imgfile_error);
- error_called = 0;
- errno = 0;
- if ( (image = iopen(fname, "r")) == NULL ) {
- /* Error may already be set by imgfile_error */
- if ( !error_called ) {
- if (errno)
- PyErr_SetFromErrno(ImgfileError);
- else
- PyErr_SetString(ImgfileError,
- "Can't open image file");
- }
- return NULL;
- }
- return image;
+ IMAGE *image;
+ i_seterror(imgfile_error);
+ error_called = 0;
+ errno = 0;
+ if ( (image = iopen(fname, "r")) == NULL ) {
+ /* Error may already be set by imgfile_error */
+ if ( !error_called ) {
+ if (errno)
+ PyErr_SetFromErrno(ImgfileError);
+ else
+ PyErr_SetString(ImgfileError,
+ "Can't open image file");
+ }
+ return NULL;
+ }
+ return image;
}
static PyObject *
imgfile_ttob(PyObject *self, PyObject *args)
{
- int newval;
- PyObject *rv;
-
- if (!PyArg_ParseTuple(args, "i:ttob", &newval))
- return NULL;
- rv = PyInt_FromLong(top_to_bottom);
- top_to_bottom = newval;
- return rv;
+ int newval;
+ PyObject *rv;
+
+ if (!PyArg_ParseTuple(args, "i:ttob", &newval))
+ return NULL;
+ rv = PyInt_FromLong(top_to_bottom);
+ top_to_bottom = newval;
+ return rv;
}
static PyObject *
imgfile_read(PyObject *self, PyObject *args)
{
- char *fname;
- PyObject *rv;
- int xsize, ysize, zsize;
- char *cdatap;
- long *idatap;
- static short rs[8192], gs[8192], bs[8192];
- int x, y;
- IMAGE *image;
- int yfirst, ylast, ystep;
-
- if ( !PyArg_ParseTuple(args, "s:read", &fname) )
- return NULL;
-
- if ( (image = imgfile_open(fname)) == NULL )
- return NULL;
-
- if ( image->colormap != CM_NORMAL ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle CM_NORMAL images");
- return NULL;
- }
- if ( BPP(image->type) != 1 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle imgfiles with bpp!=1");
- return NULL;
- }
- xsize = image->xsize;
- ysize = image->ysize;
- zsize = image->zsize;
- if ( zsize != 1 && zsize != 3) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle 1 or 3 byte pixels");
- return NULL;
- }
- if ( xsize > 8192 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle image with > 8192 columns");
- return NULL;
- }
-
- if ( zsize == 3 ) zsize = 4;
- rv = PyString_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
- if ( rv == NULL ) {
- iclose(image);
- return NULL;
- }
- cdatap = PyString_AsString(rv);
- idatap = (long *)cdatap;
-
- if (top_to_bottom) {
- yfirst = ysize-1;
- ylast = -1;
- ystep = -1;
- } else {
- yfirst = 0;
- ylast = ysize;
- ystep = 1;
- }
- for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
- if ( zsize == 1 ) {
- getrow(image, rs, y, 0);
- for(x=0; x<xsize; x++ )
- *cdatap++ = rs[x];
- } else {
- getrow(image, rs, y, 0);
- getrow(image, gs, y, 1);
- getrow(image, bs, y, 2);
- for(x=0; x<xsize; x++ )
- *idatap++ = (rs[x] & 0xff) |
- ((gs[x] & 0xff)<<8) |
- ((bs[x] & 0xff)<<16);
- }
- }
- iclose(image);
- if ( error_called ) {
- Py_DECREF(rv);
- return NULL;
- }
- return rv;
+ char *fname;
+ PyObject *rv;
+ int xsize, ysize, zsize;
+ char *cdatap;
+ long *idatap;
+ static short rs[8192], gs[8192], bs[8192];
+ int x, y;
+ IMAGE *image;
+ int yfirst, ylast, ystep;
+
+ if ( !PyArg_ParseTuple(args, "s:read", &fname) )
+ return NULL;
+
+ if ( (image = imgfile_open(fname)) == NULL )
+ return NULL;
+
+ if ( image->colormap != CM_NORMAL ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle CM_NORMAL images");
+ return NULL;
+ }
+ if ( BPP(image->type) != 1 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle imgfiles with bpp!=1");
+ return NULL;
+ }
+ xsize = image->xsize;
+ ysize = image->ysize;
+ zsize = image->zsize;
+ if ( zsize != 1 && zsize != 3) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle 1 or 3 byte pixels");
+ return NULL;
+ }
+ if ( xsize > 8192 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle image with > 8192 columns");
+ return NULL;
+ }
+
+ if ( zsize == 3 ) zsize = 4;
+ rv = PyString_FromStringAndSize((char *)NULL, xsize*ysize*zsize);
+ if ( rv == NULL ) {
+ iclose(image);
+ return NULL;
+ }
+ cdatap = PyString_AsString(rv);
+ idatap = (long *)cdatap;
+
+ if (top_to_bottom) {
+ yfirst = ysize-1;
+ ylast = -1;
+ ystep = -1;
+ } else {
+ yfirst = 0;
+ ylast = ysize;
+ ystep = 1;
+ }
+ for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
+ if ( zsize == 1 ) {
+ getrow(image, rs, y, 0);
+ for(x=0; x<xsize; x++ )
+ *cdatap++ = rs[x];
+ } else {
+ getrow(image, rs, y, 0);
+ getrow(image, gs, y, 1);
+ getrow(image, bs, y, 2);
+ for(x=0; x<xsize; x++ )
+ *idatap++ = (rs[x] & 0xff) |
+ ((gs[x] & 0xff)<<8) |
+ ((bs[x] & 0xff)<<16);
+ }
+ }
+ iclose(image);
+ if ( error_called ) {
+ Py_DECREF(rv);
+ return NULL;
+ }
+ return rv;
}
static IMAGE *glob_image;
@@ -177,332 +177,332 @@ static int glob_width, glob_z, glob_ysize;
static void
xs_get(short *buf, int y)
{
- if (top_to_bottom)
- getrow(glob_image, buf, (glob_ysize-1-y), glob_z);
- else
- getrow(glob_image, buf, y, glob_z);
+ if (top_to_bottom)
+ getrow(glob_image, buf, (glob_ysize-1-y), glob_z);
+ else
+ getrow(glob_image, buf, y, glob_z);
}
static void
xs_put_c(short *buf, int y)
{
- char *datap = (char *)glob_datap + y*glob_width;
- int width = glob_width;
+ char *datap = (char *)glob_datap + y*glob_width;
+ int width = glob_width;
- while ( width-- )
- *datap++ = (*buf++) & 0xff;
+ while ( width-- )
+ *datap++ = (*buf++) & 0xff;
}
static void
xs_put_0(short *buf, int y)
{
- long *datap = glob_datap + y*glob_width;
- int width = glob_width;
+ long *datap = glob_datap + y*glob_width;
+ int width = glob_width;
- while ( width-- )
- *datap++ = (*buf++) & 0xff;
+ while ( width-- )
+ *datap++ = (*buf++) & 0xff;
}
static void
xs_put_12(short *buf, int y)
{
- long *datap = glob_datap + y*glob_width;
- int width = glob_width;
+ long *datap = glob_datap + y*glob_width;
+ int width = glob_width;
- while ( width-- )
- *datap++ |= ((*buf++) & 0xff) << (glob_z*8);
+ while ( width-- )
+ *datap++ |= ((*buf++) & 0xff) << (glob_z*8);
}
static void
xscale(IMAGE *image, int xsize, int ysize, int zsize,
long *datap, int xnew, int ynew, int fmode, double blur)
{
- glob_image = image;
- glob_datap = datap;
- glob_width = xnew;
- glob_ysize = ysize;
- if ( zsize == 1 ) {
- glob_z = 0;
- filterzoom(xs_get, xs_put_c, xsize, ysize,
- xnew, ynew, fmode, blur);
- } else {
- glob_z = 0;
- filterzoom(xs_get, xs_put_0, xsize, ysize,
- xnew, ynew, fmode, blur);
- glob_z = 1;
- filterzoom(xs_get, xs_put_12, xsize, ysize,
- xnew, ynew, fmode, blur);
- glob_z = 2;
- filterzoom(xs_get, xs_put_12, xsize, ysize,
- xnew, ynew, fmode, blur);
- }
+ glob_image = image;
+ glob_datap = datap;
+ glob_width = xnew;
+ glob_ysize = ysize;
+ if ( zsize == 1 ) {
+ glob_z = 0;
+ filterzoom(xs_get, xs_put_c, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ } else {
+ glob_z = 0;
+ filterzoom(xs_get, xs_put_0, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ glob_z = 1;
+ filterzoom(xs_get, xs_put_12, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ glob_z = 2;
+ filterzoom(xs_get, xs_put_12, xsize, ysize,
+ xnew, ynew, fmode, blur);
+ }
}
static PyObject *
imgfile_readscaled(PyObject *self, PyObject *args)
{
- char *fname;
- PyObject *rv;
- int xsize, ysize, zsize;
- char *cdatap;
- long *idatap;
- static short rs[8192], gs[8192], bs[8192];
- int x, y;
- int xwtd, ywtd, xorig, yorig;
- float xfac, yfac;
- IMAGE *image;
- char *filter;
- double blur = 1.0;
- int extended;
- int fmode = 0;
- int yfirst, ylast, ystep;
-
- /*
- ** Parse args. Funny, since arg 4 and 5 are optional
- ** (filter name and blur factor). Also, 4 or 5 arguments indicates
- ** extended scale algorithm in stead of simple-minded pixel drop/dup.
- */
- extended = PyTuple_Size(args) >= 4;
- if ( !PyArg_ParseTuple(args, "sii|sd",
- &fname, &xwtd, &ywtd, &filter, &blur) )
- return NULL;
-
- /*
- ** Check parameters, open file and check type, rows, etc.
- */
- if ( extended ) {
- if ( strcmp(filter, "impulse") == 0 )
- fmode = IMPULSE;
- else if ( strcmp( filter, "box") == 0 )
- fmode = BOX;
- else if ( strcmp( filter, "triangle") == 0 )
- fmode = TRIANGLE;
- else if ( strcmp( filter, "quadratic") == 0 )
- fmode = QUADRATIC;
- else if ( strcmp( filter, "gaussian") == 0 )
- fmode = GAUSSIAN;
- else {
- PyErr_SetString(ImgfileError, "Unknown filter type");
- return NULL;
- }
- }
-
- if ( (image = imgfile_open(fname)) == NULL )
- return NULL;
-
- if ( image->colormap != CM_NORMAL ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle CM_NORMAL images");
- return NULL;
- }
- if ( BPP(image->type) != 1 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle imgfiles with bpp!=1");
- return NULL;
- }
- xsize = image->xsize;
- ysize = image->ysize;
- zsize = image->zsize;
- if ( zsize != 1 && zsize != 3) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can only handle 1 or 3 byte pixels");
- return NULL;
- }
- if ( xsize > 8192 ) {
- iclose(image);
- PyErr_SetString(ImgfileError,
- "Can't handle image with > 8192 columns");
- return NULL;
- }
-
- if ( zsize == 3 ) zsize = 4;
- rv = PyString_FromStringAndSize(NULL, xwtd*ywtd*zsize);
- if ( rv == NULL ) {
- iclose(image);
- return NULL;
- }
- PyFPE_START_PROTECT("readscaled", return 0)
- xfac = (float)xsize/(float)xwtd;
- yfac = (float)ysize/(float)ywtd;
- PyFPE_END_PROTECT(yfac)
- cdatap = PyString_AsString(rv);
- idatap = (long *)cdatap;
-
- if ( extended ) {
- xscale(image, xsize, ysize, zsize,
- idatap, xwtd, ywtd, fmode, blur);
- } else {
- if (top_to_bottom) {
- yfirst = ywtd-1;
- ylast = -1;
- ystep = -1;
- } else {
- yfirst = 0;
- ylast = ywtd;
- ystep = 1;
- }
- for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
- yorig = (int)(y*yfac);
- if ( zsize == 1 ) {
- getrow(image, rs, yorig, 0);
- for(x=0; x<xwtd; x++ ) {
- *cdatap++ = rs[(int)(x*xfac)];
- }
- } else {
- getrow(image, rs, yorig, 0);
- getrow(image, gs, yorig, 1);
- getrow(image, bs, yorig, 2);
- for(x=0; x<xwtd; x++ ) {
- xorig = (int)(x*xfac);
- *idatap++ = (rs[xorig] & 0xff) |
- ((gs[xorig] & 0xff)<<8) |
- ((bs[xorig] & 0xff)<<16);
- }
- }
- }
- }
- iclose(image);
- if ( error_called ) {
- Py_DECREF(rv);
- return NULL;
- }
- return rv;
+ char *fname;
+ PyObject *rv;
+ int xsize, ysize, zsize;
+ char *cdatap;
+ long *idatap;
+ static short rs[8192], gs[8192], bs[8192];
+ int x, y;
+ int xwtd, ywtd, xorig, yorig;
+ float xfac, yfac;
+ IMAGE *image;
+ char *filter;
+ double blur = 1.0;
+ int extended;
+ int fmode = 0;
+ int yfirst, ylast, ystep;
+
+ /*
+ ** Parse args. Funny, since arg 4 and 5 are optional
+ ** (filter name and blur factor). Also, 4 or 5 arguments indicates
+ ** extended scale algorithm in stead of simple-minded pixel drop/dup.
+ */
+ extended = PyTuple_Size(args) >= 4;
+ if ( !PyArg_ParseTuple(args, "sii|sd",
+ &fname, &xwtd, &ywtd, &filter, &blur) )
+ return NULL;
+
+ /*
+ ** Check parameters, open file and check type, rows, etc.
+ */
+ if ( extended ) {
+ if ( strcmp(filter, "impulse") == 0 )
+ fmode = IMPULSE;
+ else if ( strcmp( filter, "box") == 0 )
+ fmode = BOX;
+ else if ( strcmp( filter, "triangle") == 0 )
+ fmode = TRIANGLE;
+ else if ( strcmp( filter, "quadratic") == 0 )
+ fmode = QUADRATIC;
+ else if ( strcmp( filter, "gaussian") == 0 )
+ fmode = GAUSSIAN;
+ else {
+ PyErr_SetString(ImgfileError, "Unknown filter type");
+ return NULL;
+ }
+ }
+
+ if ( (image = imgfile_open(fname)) == NULL )
+ return NULL;
+
+ if ( image->colormap != CM_NORMAL ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle CM_NORMAL images");
+ return NULL;
+ }
+ if ( BPP(image->type) != 1 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle imgfiles with bpp!=1");
+ return NULL;
+ }
+ xsize = image->xsize;
+ ysize = image->ysize;
+ zsize = image->zsize;
+ if ( zsize != 1 && zsize != 3) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can only handle 1 or 3 byte pixels");
+ return NULL;
+ }
+ if ( xsize > 8192 ) {
+ iclose(image);
+ PyErr_SetString(ImgfileError,
+ "Can't handle image with > 8192 columns");
+ return NULL;
+ }
+
+ if ( zsize == 3 ) zsize = 4;
+ rv = PyString_FromStringAndSize(NULL, xwtd*ywtd*zsize);
+ if ( rv == NULL ) {
+ iclose(image);
+ return NULL;
+ }
+ PyFPE_START_PROTECT("readscaled", return 0)
+ xfac = (float)xsize/(float)xwtd;
+ yfac = (float)ysize/(float)ywtd;
+ PyFPE_END_PROTECT(yfac)
+ cdatap = PyString_AsString(rv);
+ idatap = (long *)cdatap;
+
+ if ( extended ) {
+ xscale(image, xsize, ysize, zsize,
+ idatap, xwtd, ywtd, fmode, blur);
+ } else {
+ if (top_to_bottom) {
+ yfirst = ywtd-1;
+ ylast = -1;
+ ystep = -1;
+ } else {
+ yfirst = 0;
+ ylast = ywtd;
+ ystep = 1;
+ }
+ for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
+ yorig = (int)(y*yfac);
+ if ( zsize == 1 ) {
+ getrow(image, rs, yorig, 0);
+ for(x=0; x<xwtd; x++ ) {
+ *cdatap++ = rs[(int)(x*xfac)];
+ }
+ } else {
+ getrow(image, rs, yorig, 0);
+ getrow(image, gs, yorig, 1);
+ getrow(image, bs, yorig, 2);
+ for(x=0; x<xwtd; x++ ) {
+ xorig = (int)(x*xfac);
+ *idatap++ = (rs[xorig] & 0xff) |
+ ((gs[xorig] & 0xff)<<8) |
+ ((bs[xorig] & 0xff)<<16);
+ }
+ }
+ }
+ }
+ iclose(image);
+ if ( error_called ) {
+ Py_DECREF(rv);
+ return NULL;
+ }
+ return rv;
}
static PyObject *
imgfile_getsizes(PyObject *self, PyObject *args)
{
- char *fname;
- PyObject *rv;
- IMAGE *image;
-
- if ( !PyArg_ParseTuple(args, "s:getsizes", &fname) )
- return NULL;
-
- if ( (image = imgfile_open(fname)) == NULL )
- return NULL;
- rv = Py_BuildValue("(iii)", image->xsize, image->ysize, image->zsize);
- iclose(image);
- return rv;
+ char *fname;
+ PyObject *rv;
+ IMAGE *image;
+
+ if ( !PyArg_ParseTuple(args, "s:getsizes", &fname) )
+ return NULL;
+
+ if ( (image = imgfile_open(fname)) == NULL )
+ return NULL;
+ rv = Py_BuildValue("(iii)", image->xsize, image->ysize, image->zsize);
+ iclose(image);
+ return rv;
}
static PyObject *
imgfile_write(PyObject *self, PyObject *args)
{
- IMAGE *image;
- char *fname;
- int xsize, ysize, zsize, len;
- char *cdatap;
- long *idatap;
- short rs[8192], gs[8192], bs[8192];
- short r, g, b;
- long rgb;
- int x, y;
- int yfirst, ylast, ystep;
-
-
- if ( !PyArg_ParseTuple(args, "ss#iii:write",
- &fname, &cdatap, &len, &xsize, &ysize, &zsize) )
- return NULL;
-
- if ( zsize != 1 && zsize != 3 ) {
- PyErr_SetString(ImgfileError,
- "Can only handle 1 or 3 byte pixels");
- return NULL;
- }
- if ( len != xsize * ysize * (zsize == 1 ? 1 : 4) ) {
- PyErr_SetString(ImgfileError, "Data does not match sizes");
- return NULL;
- }
- if ( xsize > 8192 ) {
- PyErr_SetString(ImgfileError,
- "Can't handle image with > 8192 columns");
- return NULL;
- }
-
- error_called = 0;
- errno = 0;
- image =iopen(fname, "w", RLE(1), 3, xsize, ysize, zsize);
- if ( image == 0 ) {
- if ( ! error_called ) {
- if (errno)
- PyErr_SetFromErrno(ImgfileError);
- else
- PyErr_SetString(ImgfileError,
- "Can't create image file");
- }
- return NULL;
- }
-
- idatap = (long *)cdatap;
-
- if (top_to_bottom) {
- yfirst = ysize-1;
- ylast = -1;
- ystep = -1;
- } else {
- yfirst = 0;
- ylast = ysize;
- ystep = 1;
- }
- for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
- if ( zsize == 1 ) {
- for( x=0; x<xsize; x++ )
- rs[x] = *cdatap++;
- putrow(image, rs, y, 0);
- } else {
- for( x=0; x<xsize; x++ ) {
- rgb = *idatap++;
- r = rgb & 0xff;
- g = (rgb >> 8 ) & 0xff;
- b = (rgb >> 16 ) & 0xff;
- rs[x] = r;
- gs[x] = g;
- bs[x] = b;
- }
- putrow(image, rs, y, 0);
- putrow(image, gs, y, 1);
- putrow(image, bs, y, 2);
- }
- }
- iclose(image);
- if ( error_called )
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
-
+ IMAGE *image;
+ char *fname;
+ int xsize, ysize, zsize, len;
+ char *cdatap;
+ long *idatap;
+ short rs[8192], gs[8192], bs[8192];
+ short r, g, b;
+ long rgb;
+ int x, y;
+ int yfirst, ylast, ystep;
+
+
+ if ( !PyArg_ParseTuple(args, "ss#iii:write",
+ &fname, &cdatap, &len, &xsize, &ysize, &zsize) )
+ return NULL;
+
+ if ( zsize != 1 && zsize != 3 ) {
+ PyErr_SetString(ImgfileError,
+ "Can only handle 1 or 3 byte pixels");
+ return NULL;
+ }
+ if ( len != xsize * ysize * (zsize == 1 ? 1 : 4) ) {
+ PyErr_SetString(ImgfileError, "Data does not match sizes");
+ return NULL;
+ }
+ if ( xsize > 8192 ) {
+ PyErr_SetString(ImgfileError,
+ "Can't handle image with > 8192 columns");
+ return NULL;
+ }
+
+ error_called = 0;
+ errno = 0;
+ image =iopen(fname, "w", RLE(1), 3, xsize, ysize, zsize);
+ if ( image == 0 ) {
+ if ( ! error_called ) {
+ if (errno)
+ PyErr_SetFromErrno(ImgfileError);
+ else
+ PyErr_SetString(ImgfileError,
+ "Can't create image file");
+ }
+ return NULL;
+ }
+
+ idatap = (long *)cdatap;
+
+ if (top_to_bottom) {
+ yfirst = ysize-1;
+ ylast = -1;
+ ystep = -1;
+ } else {
+ yfirst = 0;
+ ylast = ysize;
+ ystep = 1;
+ }
+ for ( y=yfirst; y != ylast && !error_called; y += ystep ) {
+ if ( zsize == 1 ) {
+ for( x=0; x<xsize; x++ )
+ rs[x] = *cdatap++;
+ putrow(image, rs, y, 0);
+ } else {
+ for( x=0; x<xsize; x++ ) {
+ rgb = *idatap++;
+ r = rgb & 0xff;
+ g = (rgb >> 8 ) & 0xff;
+ b = (rgb >> 16 ) & 0xff;
+ rs[x] = r;
+ gs[x] = g;
+ bs[x] = b;
+ }
+ putrow(image, rs, y, 0);
+ putrow(image, gs, y, 1);
+ putrow(image, bs, y, 2);
+ }
+ }
+ iclose(image);
+ if ( error_called )
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
+
}
static PyMethodDef imgfile_methods[] = {
- { "getsizes", imgfile_getsizes, METH_VARARGS },
- { "read", imgfile_read, METH_VARARGS },
- { "readscaled", imgfile_readscaled, METH_VARARGS},
- { "write", imgfile_write, METH_VARARGS },
- { "ttob", imgfile_ttob, METH_VARARGS },
- { NULL, NULL } /* Sentinel */
+ { "getsizes", imgfile_getsizes, METH_VARARGS },
+ { "read", imgfile_read, METH_VARARGS },
+ { "readscaled", imgfile_readscaled, METH_VARARGS},
+ { "write", imgfile_write, METH_VARARGS },
+ { "ttob", imgfile_ttob, METH_VARARGS },
+ { NULL, NULL } /* Sentinel */
};
void
initimgfile(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the imgfile module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("imgfile", imgfile_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- ImgfileError = PyErr_NewException("imgfile.error", NULL, NULL);
- if (ImgfileError != NULL)
- PyDict_SetItemString(d, "error", ImgfileError);
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the imgfile module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("imgfile", imgfile_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ ImgfileError = PyErr_NewException("imgfile.error", NULL, NULL);
+ if (ImgfileError != NULL)
+ PyDict_SetItemString(d, "error", ImgfileError);
}
diff --git a/Modules/itertoolsmodule.c b/Modules/itertoolsmodule.c
index 633d0a7..79385be 100644
--- a/Modules/itertoolsmodule.c
+++ b/Modules/itertoolsmodule.c
@@ -2,7 +2,7 @@
#include "Python.h"
#include "structmember.h"
-/* Itertools module written and maintained
+/* Itertools module written and maintained
by Raymond D. Hettinger <python@rcn.com>
Copyright (c) 2003 Python Software Foundation.
All rights reserved.
@@ -12,12 +12,12 @@
/* groupby object ***********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *it;
- PyObject *keyfunc;
- PyObject *tgtkey;
- PyObject *currkey;
- PyObject *currvalue;
+ PyObject_HEAD
+ PyObject *it;
+ PyObject *keyfunc;
+ PyObject *tgtkey;
+ PyObject *currkey;
+ PyObject *currvalue;
} groupbyobject;
static PyTypeObject groupby_type;
@@ -26,112 +26,112 @@ static PyObject *_grouper_create(groupbyobject *, PyObject *);
static PyObject *
groupby_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- static char *kwargs[] = {"iterable", "key", NULL};
- groupbyobject *gbo;
- PyObject *it, *keyfunc = Py_None;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs,
- &it, &keyfunc))
- return NULL;
-
- gbo = (groupbyobject *)type->tp_alloc(type, 0);
- if (gbo == NULL)
- return NULL;
- gbo->tgtkey = NULL;
- gbo->currkey = NULL;
- gbo->currvalue = NULL;
- gbo->keyfunc = keyfunc;
- Py_INCREF(keyfunc);
- gbo->it = PyObject_GetIter(it);
- if (gbo->it == NULL) {
- Py_DECREF(gbo);
- return NULL;
- }
- return (PyObject *)gbo;
+ static char *kwargs[] = {"iterable", "key", NULL};
+ groupbyobject *gbo;
+ PyObject *it, *keyfunc = Py_None;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:groupby", kwargs,
+ &it, &keyfunc))
+ return NULL;
+
+ gbo = (groupbyobject *)type->tp_alloc(type, 0);
+ if (gbo == NULL)
+ return NULL;
+ gbo->tgtkey = NULL;
+ gbo->currkey = NULL;
+ gbo->currvalue = NULL;
+ gbo->keyfunc = keyfunc;
+ Py_INCREF(keyfunc);
+ gbo->it = PyObject_GetIter(it);
+ if (gbo->it == NULL) {
+ Py_DECREF(gbo);
+ return NULL;
+ }
+ return (PyObject *)gbo;
}
static void
groupby_dealloc(groupbyobject *gbo)
{
- PyObject_GC_UnTrack(gbo);
- Py_XDECREF(gbo->it);
- Py_XDECREF(gbo->keyfunc);
- Py_XDECREF(gbo->tgtkey);
- Py_XDECREF(gbo->currkey);
- Py_XDECREF(gbo->currvalue);
- Py_TYPE(gbo)->tp_free(gbo);
+ PyObject_GC_UnTrack(gbo);
+ Py_XDECREF(gbo->it);
+ Py_XDECREF(gbo->keyfunc);
+ Py_XDECREF(gbo->tgtkey);
+ Py_XDECREF(gbo->currkey);
+ Py_XDECREF(gbo->currvalue);
+ Py_TYPE(gbo)->tp_free(gbo);
}
static int
groupby_traverse(groupbyobject *gbo, visitproc visit, void *arg)
{
- Py_VISIT(gbo->it);
- Py_VISIT(gbo->keyfunc);
- Py_VISIT(gbo->tgtkey);
- Py_VISIT(gbo->currkey);
- Py_VISIT(gbo->currvalue);
- return 0;
+ Py_VISIT(gbo->it);
+ Py_VISIT(gbo->keyfunc);
+ Py_VISIT(gbo->tgtkey);
+ Py_VISIT(gbo->currkey);
+ Py_VISIT(gbo->currvalue);
+ return 0;
}
static PyObject *
groupby_next(groupbyobject *gbo)
{
- PyObject *newvalue, *newkey, *r, *grouper, *tmp;
-
- /* skip to next iteration group */
- for (;;) {
- if (gbo->currkey == NULL)
- /* pass */;
- else if (gbo->tgtkey == NULL)
- break;
- else {
- int rcmp;
-
- rcmp = PyObject_RichCompareBool(gbo->tgtkey,
- gbo->currkey, Py_EQ);
- if (rcmp == -1)
- return NULL;
- else if (rcmp == 0)
- break;
- }
-
- newvalue = PyIter_Next(gbo->it);
- if (newvalue == NULL)
- return NULL;
-
- if (gbo->keyfunc == Py_None) {
- newkey = newvalue;
- Py_INCREF(newvalue);
- } else {
- newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
- newvalue, NULL);
- if (newkey == NULL) {
- Py_DECREF(newvalue);
- return NULL;
- }
- }
-
- tmp = gbo->currkey;
- gbo->currkey = newkey;
- Py_XDECREF(tmp);
-
- tmp = gbo->currvalue;
- gbo->currvalue = newvalue;
- Py_XDECREF(tmp);
- }
-
- Py_INCREF(gbo->currkey);
- tmp = gbo->tgtkey;
- gbo->tgtkey = gbo->currkey;
- Py_XDECREF(tmp);
-
- grouper = _grouper_create(gbo, gbo->tgtkey);
- if (grouper == NULL)
- return NULL;
-
- r = PyTuple_Pack(2, gbo->currkey, grouper);
- Py_DECREF(grouper);
- return r;
+ PyObject *newvalue, *newkey, *r, *grouper, *tmp;
+
+ /* skip to next iteration group */
+ for (;;) {
+ if (gbo->currkey == NULL)
+ /* pass */;
+ else if (gbo->tgtkey == NULL)
+ break;
+ else {
+ int rcmp;
+
+ rcmp = PyObject_RichCompareBool(gbo->tgtkey,
+ gbo->currkey, Py_EQ);
+ if (rcmp == -1)
+ return NULL;
+ else if (rcmp == 0)
+ break;
+ }
+
+ newvalue = PyIter_Next(gbo->it);
+ if (newvalue == NULL)
+ return NULL;
+
+ if (gbo->keyfunc == Py_None) {
+ newkey = newvalue;
+ Py_INCREF(newvalue);
+ } else {
+ newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
+ newvalue, NULL);
+ if (newkey == NULL) {
+ Py_DECREF(newvalue);
+ return NULL;
+ }
+ }
+
+ tmp = gbo->currkey;
+ gbo->currkey = newkey;
+ Py_XDECREF(tmp);
+
+ tmp = gbo->currvalue;
+ gbo->currvalue = newvalue;
+ Py_XDECREF(tmp);
+ }
+
+ Py_INCREF(gbo->currkey);
+ tmp = gbo->tgtkey;
+ gbo->tgtkey = gbo->currkey;
+ Py_XDECREF(tmp);
+
+ grouper = _grouper_create(gbo, gbo->tgtkey);
+ if (grouper == NULL)
+ return NULL;
+
+ r = PyTuple_Pack(2, gbo->currkey, grouper);
+ Py_DECREF(grouper);
+ return r;
}
PyDoc_STRVAR(groupby_doc,
@@ -139,56 +139,56 @@ PyDoc_STRVAR(groupby_doc,
(key, sub-iterator) grouped by each value of key(value).\n");
static PyTypeObject groupby_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.groupby", /* tp_name */
- sizeof(groupbyobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)groupby_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- groupby_doc, /* tp_doc */
- (traverseproc)groupby_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)groupby_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- groupby_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.groupby", /* tp_name */
+ sizeof(groupbyobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)groupby_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ groupby_doc, /* tp_doc */
+ (traverseproc)groupby_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)groupby_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ groupby_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* _grouper object (internal) ************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *parent;
- PyObject *tgtkey;
+ PyObject_HEAD
+ PyObject *parent;
+ PyObject *tgtkey;
} _grouperobject;
static PyTypeObject _grouper_type;
@@ -196,129 +196,129 @@ static PyTypeObject _grouper_type;
static PyObject *
_grouper_create(groupbyobject *parent, PyObject *tgtkey)
{
- _grouperobject *igo;
-
- igo = PyObject_GC_New(_grouperobject, &_grouper_type);
- if (igo == NULL)
- return NULL;
- igo->parent = (PyObject *)parent;
- Py_INCREF(parent);
- igo->tgtkey = tgtkey;
- Py_INCREF(tgtkey);
-
- PyObject_GC_Track(igo);
- return (PyObject *)igo;
+ _grouperobject *igo;
+
+ igo = PyObject_GC_New(_grouperobject, &_grouper_type);
+ if (igo == NULL)
+ return NULL;
+ igo->parent = (PyObject *)parent;
+ Py_INCREF(parent);
+ igo->tgtkey = tgtkey;
+ Py_INCREF(tgtkey);
+
+ PyObject_GC_Track(igo);
+ return (PyObject *)igo;
}
static void
_grouper_dealloc(_grouperobject *igo)
{
- PyObject_GC_UnTrack(igo);
- Py_DECREF(igo->parent);
- Py_DECREF(igo->tgtkey);
- PyObject_GC_Del(igo);
+ PyObject_GC_UnTrack(igo);
+ Py_DECREF(igo->parent);
+ Py_DECREF(igo->tgtkey);
+ PyObject_GC_Del(igo);
}
static int
_grouper_traverse(_grouperobject *igo, visitproc visit, void *arg)
{
- Py_VISIT(igo->parent);
- Py_VISIT(igo->tgtkey);
- return 0;
+ Py_VISIT(igo->parent);
+ Py_VISIT(igo->tgtkey);
+ return 0;
}
static PyObject *
_grouper_next(_grouperobject *igo)
{
- groupbyobject *gbo = (groupbyobject *)igo->parent;
- PyObject *newvalue, *newkey, *r;
- int rcmp;
-
- if (gbo->currvalue == NULL) {
- newvalue = PyIter_Next(gbo->it);
- if (newvalue == NULL)
- return NULL;
-
- if (gbo->keyfunc == Py_None) {
- newkey = newvalue;
- Py_INCREF(newvalue);
- } else {
- newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
- newvalue, NULL);
- if (newkey == NULL) {
- Py_DECREF(newvalue);
- return NULL;
- }
- }
-
- assert(gbo->currkey == NULL);
- gbo->currkey = newkey;
- gbo->currvalue = newvalue;
- }
-
- assert(gbo->currkey != NULL);
- rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ);
- if (rcmp <= 0)
- /* got any error or current group is end */
- return NULL;
-
- r = gbo->currvalue;
- gbo->currvalue = NULL;
- Py_CLEAR(gbo->currkey);
-
- return r;
+ groupbyobject *gbo = (groupbyobject *)igo->parent;
+ PyObject *newvalue, *newkey, *r;
+ int rcmp;
+
+ if (gbo->currvalue == NULL) {
+ newvalue = PyIter_Next(gbo->it);
+ if (newvalue == NULL)
+ return NULL;
+
+ if (gbo->keyfunc == Py_None) {
+ newkey = newvalue;
+ Py_INCREF(newvalue);
+ } else {
+ newkey = PyObject_CallFunctionObjArgs(gbo->keyfunc,
+ newvalue, NULL);
+ if (newkey == NULL) {
+ Py_DECREF(newvalue);
+ return NULL;
+ }
+ }
+
+ assert(gbo->currkey == NULL);
+ gbo->currkey = newkey;
+ gbo->currvalue = newvalue;
+ }
+
+ assert(gbo->currkey != NULL);
+ rcmp = PyObject_RichCompareBool(igo->tgtkey, gbo->currkey, Py_EQ);
+ if (rcmp <= 0)
+ /* got any error or current group is end */
+ return NULL;
+
+ r = gbo->currvalue;
+ gbo->currvalue = NULL;
+ Py_CLEAR(gbo->currkey);
+
+ return r;
}
static PyTypeObject _grouper_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools._grouper", /* tp_name */
- sizeof(_grouperobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)_grouper_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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)_grouper_traverse,/* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)_grouper_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools._grouper", /* tp_name */
+ sizeof(_grouperobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)_grouper_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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)_grouper_traverse,/* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)_grouper_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
-
+
/* tee object and with supporting function and objects ***************/
/* The teedataobject pre-allocates space for LINKCELLS number of objects.
To help the object fit neatly inside cache lines (space for 16 to 32
- pointers), the value should be a multiple of 16 minus space for
+ pointers), the value should be a multiple of 16 minus space for
the other structure members including PyHEAD overhead. The larger the
value, the less memory overhead per object and the less time spent
allocating/deallocating new links. The smaller the number, the less
@@ -327,18 +327,18 @@ static PyTypeObject _grouper_type = {
#define LINKCELLS 57
typedef struct {
- PyObject_HEAD
- PyObject *it;
- int numread;
- PyObject *nextlink;
- PyObject *(values[LINKCELLS]);
+ PyObject_HEAD
+ PyObject *it;
+ int numread;
+ PyObject *nextlink;
+ PyObject *(values[LINKCELLS]);
} teedataobject;
typedef struct {
- PyObject_HEAD
- teedataobject *dataobj;
- int index;
- PyObject *weakreflist;
+ PyObject_HEAD
+ teedataobject *dataobj;
+ int index;
+ PyObject *weakreflist;
} teeobject;
static PyTypeObject teedataobject_type;
@@ -346,123 +346,123 @@ static PyTypeObject teedataobject_type;
static PyObject *
teedataobject_new(PyObject *it)
{
- teedataobject *tdo;
-
- tdo = PyObject_GC_New(teedataobject, &teedataobject_type);
- if (tdo == NULL)
- return NULL;
-
- tdo->numread = 0;
- tdo->nextlink = NULL;
- Py_INCREF(it);
- tdo->it = it;
- PyObject_GC_Track(tdo);
- return (PyObject *)tdo;
+ teedataobject *tdo;
+
+ tdo = PyObject_GC_New(teedataobject, &teedataobject_type);
+ if (tdo == NULL)
+ return NULL;
+
+ tdo->numread = 0;
+ tdo->nextlink = NULL;
+ Py_INCREF(it);
+ tdo->it = it;
+ PyObject_GC_Track(tdo);
+ return (PyObject *)tdo;
}
static PyObject *
teedataobject_jumplink(teedataobject *tdo)
{
- if (tdo->nextlink == NULL)
- tdo->nextlink = teedataobject_new(tdo->it);
- Py_XINCREF(tdo->nextlink);
- return tdo->nextlink;
+ if (tdo->nextlink == NULL)
+ tdo->nextlink = teedataobject_new(tdo->it);
+ Py_XINCREF(tdo->nextlink);
+ return tdo->nextlink;
}
static PyObject *
teedataobject_getitem(teedataobject *tdo, int i)
{
- PyObject *value;
-
- assert(i < LINKCELLS);
- if (i < tdo->numread)
- value = tdo->values[i];
- else {
- /* this is the lead iterator, so fetch more data */
- assert(i == tdo->numread);
- value = PyIter_Next(tdo->it);
- if (value == NULL)
- return NULL;
- tdo->numread++;
- tdo->values[i] = value;
- }
- Py_INCREF(value);
- return value;
+ PyObject *value;
+
+ assert(i < LINKCELLS);
+ if (i < tdo->numread)
+ value = tdo->values[i];
+ else {
+ /* this is the lead iterator, so fetch more data */
+ assert(i == tdo->numread);
+ value = PyIter_Next(tdo->it);
+ if (value == NULL)
+ return NULL;
+ tdo->numread++;
+ tdo->values[i] = value;
+ }
+ Py_INCREF(value);
+ return value;
}
static int
teedataobject_traverse(teedataobject *tdo, visitproc visit, void * arg)
{
- int i;
- Py_VISIT(tdo->it);
- for (i = 0; i < tdo->numread; i++)
- Py_VISIT(tdo->values[i]);
- Py_VISIT(tdo->nextlink);
- return 0;
+ int i;
+ Py_VISIT(tdo->it);
+ for (i = 0; i < tdo->numread; i++)
+ Py_VISIT(tdo->values[i]);
+ Py_VISIT(tdo->nextlink);
+ return 0;
}
static int
teedataobject_clear(teedataobject *tdo)
{
- int i;
- Py_CLEAR(tdo->it);
- for (i=0 ; i<tdo->numread ; i++)
- Py_CLEAR(tdo->values[i]);
- Py_CLEAR(tdo->nextlink);
- return 0;
+ int i;
+ Py_CLEAR(tdo->it);
+ for (i=0 ; i<tdo->numread ; i++)
+ Py_CLEAR(tdo->values[i]);
+ Py_CLEAR(tdo->nextlink);
+ return 0;
}
static void
teedataobject_dealloc(teedataobject *tdo)
{
- PyObject_GC_UnTrack(tdo);
- teedataobject_clear(tdo);
- PyObject_GC_Del(tdo);
+ PyObject_GC_UnTrack(tdo);
+ teedataobject_clear(tdo);
+ PyObject_GC_Del(tdo);
}
PyDoc_STRVAR(teedataobject_doc, "Data container common to multiple tee objects.");
static PyTypeObject teedataobject_type = {
- PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
- "itertools.tee_dataobject", /* tp_name */
- sizeof(teedataobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)teedataobject_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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- teedataobject_doc, /* tp_doc */
- (traverseproc)teedataobject_traverse, /* tp_traverse */
- (inquiry)teedataobject_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
+ "itertools.tee_dataobject", /* tp_name */
+ sizeof(teedataobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)teedataobject_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 | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ teedataobject_doc, /* tp_doc */
+ (traverseproc)teedataobject_traverse, /* tp_traverse */
+ (inquiry)teedataobject_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -471,42 +471,42 @@ static PyTypeObject tee_type;
static PyObject *
tee_next(teeobject *to)
{
- PyObject *value, *link;
-
- if (to->index >= LINKCELLS) {
- link = teedataobject_jumplink(to->dataobj);
- Py_DECREF(to->dataobj);
- to->dataobj = (teedataobject *)link;
- to->index = 0;
- }
- value = teedataobject_getitem(to->dataobj, to->index);
- if (value == NULL)
- return NULL;
- to->index++;
- return value;
+ PyObject *value, *link;
+
+ if (to->index >= LINKCELLS) {
+ link = teedataobject_jumplink(to->dataobj);
+ Py_DECREF(to->dataobj);
+ to->dataobj = (teedataobject *)link;
+ to->index = 0;
+ }
+ value = teedataobject_getitem(to->dataobj, to->index);
+ if (value == NULL)
+ return NULL;
+ to->index++;
+ return value;
}
static int
tee_traverse(teeobject *to, visitproc visit, void *arg)
{
- Py_VISIT((PyObject *)to->dataobj);
- return 0;
+ Py_VISIT((PyObject *)to->dataobj);
+ return 0;
}
static PyObject *
tee_copy(teeobject *to)
{
- teeobject *newto;
-
- newto = PyObject_GC_New(teeobject, &tee_type);
- if (newto == NULL)
- return NULL;
- Py_INCREF(to->dataobj);
- newto->dataobj = to->dataobj;
- newto->index = to->index;
- newto->weakreflist = NULL;
- PyObject_GC_Track(newto);
- return (PyObject *)newto;
+ teeobject *newto;
+
+ newto = PyObject_GC_New(teeobject, &tee_type);
+ if (newto == NULL)
+ return NULL;
+ Py_INCREF(to->dataobj);
+ newto->dataobj = to->dataobj;
+ newto->index = to->index;
+ newto->weakreflist = NULL;
+ PyObject_GC_Track(newto);
+ return (PyObject *)newto;
}
PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator.");
@@ -514,154 +514,154 @@ PyDoc_STRVAR(teecopy_doc, "Returns an independent iterator.");
static PyObject *
tee_fromiterable(PyObject *iterable)
{
- teeobject *to;
- PyObject *it = NULL;
-
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
- if (PyObject_TypeCheck(it, &tee_type)) {
- to = (teeobject *)tee_copy((teeobject *)it);
- goto done;
- }
-
- to = PyObject_GC_New(teeobject, &tee_type);
- if (to == NULL)
- goto done;
- to->dataobj = (teedataobject *)teedataobject_new(it);
- if (!to->dataobj) {
- PyObject_GC_Del(to);
- to = NULL;
- goto done;
- }
-
- to->index = 0;
- to->weakreflist = NULL;
- PyObject_GC_Track(to);
+ teeobject *to;
+ PyObject *it = NULL;
+
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+ if (PyObject_TypeCheck(it, &tee_type)) {
+ to = (teeobject *)tee_copy((teeobject *)it);
+ goto done;
+ }
+
+ to = PyObject_GC_New(teeobject, &tee_type);
+ if (to == NULL)
+ goto done;
+ to->dataobj = (teedataobject *)teedataobject_new(it);
+ if (!to->dataobj) {
+ PyObject_GC_Del(to);
+ to = NULL;
+ goto done;
+ }
+
+ to->index = 0;
+ to->weakreflist = NULL;
+ PyObject_GC_Track(to);
done:
- Py_XDECREF(it);
- return (PyObject *)to;
+ Py_XDECREF(it);
+ return (PyObject *)to;
}
static PyObject *
tee_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *iterable;
+ PyObject *iterable;
- if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable))
- return NULL;
- return tee_fromiterable(iterable);
+ if (!PyArg_UnpackTuple(args, "tee", 1, 1, &iterable))
+ return NULL;
+ return tee_fromiterable(iterable);
}
static int
tee_clear(teeobject *to)
{
- if (to->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) to);
- Py_CLEAR(to->dataobj);
- return 0;
+ if (to->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) to);
+ Py_CLEAR(to->dataobj);
+ return 0;
}
static void
tee_dealloc(teeobject *to)
{
- PyObject_GC_UnTrack(to);
- tee_clear(to);
- PyObject_GC_Del(to);
+ PyObject_GC_UnTrack(to);
+ tee_clear(to);
+ PyObject_GC_Del(to);
}
PyDoc_STRVAR(teeobject_doc,
"Iterator wrapped to make it copyable");
static PyMethodDef tee_methods[] = {
- {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc},
- {NULL, NULL} /* sentinel */
+ {"__copy__", (PyCFunction)tee_copy, METH_NOARGS, teecopy_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject tee_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.tee", /* tp_name */
- sizeof(teeobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)tee_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_HAVE_GC, /* tp_flags */
- teeobject_doc, /* tp_doc */
- (traverseproc)tee_traverse, /* tp_traverse */
- (inquiry)tee_clear, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(teeobject, weakreflist), /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)tee_next, /* tp_iternext */
- tee_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 */
- tee_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.tee", /* tp_name */
+ sizeof(teeobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)tee_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_HAVE_GC, /* tp_flags */
+ teeobject_doc, /* tp_doc */
+ (traverseproc)tee_traverse, /* tp_traverse */
+ (inquiry)tee_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(teeobject, weakreflist), /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)tee_next, /* tp_iternext */
+ tee_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 */
+ tee_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
static PyObject *
tee(PyObject *self, PyObject *args)
{
- Py_ssize_t i, n=2;
- PyObject *it, *iterable, *copyable, *result;
-
- if (!PyArg_ParseTuple(args, "O|n", &iterable, &n))
- return NULL;
- if (n < 0) {
- PyErr_SetString(PyExc_ValueError, "n must be >= 0");
- return NULL;
- }
- result = PyTuple_New(n);
- if (result == NULL)
- return NULL;
- if (n == 0)
- return result;
- it = PyObject_GetIter(iterable);
- if (it == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- if (!PyObject_HasAttrString(it, "__copy__")) {
- copyable = tee_fromiterable(it);
- Py_DECREF(it);
- if (copyable == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- } else
- copyable = it;
- PyTuple_SET_ITEM(result, 0, copyable);
- for (i=1 ; i<n ; i++) {
- copyable = PyObject_CallMethod(copyable, "__copy__", NULL);
- if (copyable == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, copyable);
- }
- return result;
+ Py_ssize_t i, n=2;
+ PyObject *it, *iterable, *copyable, *result;
+
+ if (!PyArg_ParseTuple(args, "O|n", &iterable, &n))
+ return NULL;
+ if (n < 0) {
+ PyErr_SetString(PyExc_ValueError, "n must be >= 0");
+ return NULL;
+ }
+ result = PyTuple_New(n);
+ if (result == NULL)
+ return NULL;
+ if (n == 0)
+ return result;
+ it = PyObject_GetIter(iterable);
+ if (it == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ if (!PyObject_HasAttrString(it, "__copy__")) {
+ copyable = tee_fromiterable(it);
+ Py_DECREF(it);
+ if (copyable == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ } else
+ copyable = it;
+ PyTuple_SET_ITEM(result, 0, copyable);
+ for (i=1 ; i<n ; i++) {
+ copyable = PyObject_CallMethod(copyable, "__copy__", NULL);
+ if (copyable == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, copyable);
+ }
+ return result;
}
PyDoc_STRVAR(tee_doc,
@@ -671,10 +671,10 @@ PyDoc_STRVAR(tee_doc,
/* cycle object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *it;
- PyObject *saved;
- int firstpass;
+ PyObject_HEAD
+ PyObject *it;
+ PyObject *saved;
+ int firstpass;
} cycleobject;
static PyTypeObject cycle_type;
@@ -682,91 +682,91 @@ static PyTypeObject cycle_type;
static PyObject *
cycle_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *it;
- PyObject *iterable;
- PyObject *saved;
- cycleobject *lz;
-
- if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(iterable);
- if (it == NULL)
- return NULL;
-
- saved = PyList_New(0);
- if (saved == NULL) {
- Py_DECREF(it);
- return NULL;
- }
-
- /* create cycleobject structure */
- lz = (cycleobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- Py_DECREF(saved);
- return NULL;
- }
- lz->it = it;
- lz->saved = saved;
- lz->firstpass = 0;
-
- return (PyObject *)lz;
+ PyObject *it;
+ PyObject *iterable;
+ PyObject *saved;
+ cycleobject *lz;
+
+ if (type == &cycle_type && !_PyArg_NoKeywords("cycle()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "cycle", 1, 1, &iterable))
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(iterable);
+ if (it == NULL)
+ return NULL;
+
+ saved = PyList_New(0);
+ if (saved == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+
+ /* create cycleobject structure */
+ lz = (cycleobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ Py_DECREF(saved);
+ return NULL;
+ }
+ lz->it = it;
+ lz->saved = saved;
+ lz->firstpass = 0;
+
+ return (PyObject *)lz;
}
static void
cycle_dealloc(cycleobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->saved);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->saved);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
cycle_traverse(cycleobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->saved);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->saved);
+ return 0;
}
static PyObject *
cycle_next(cycleobject *lz)
{
- PyObject *item;
- PyObject *it;
- PyObject *tmp;
-
- while (1) {
- item = PyIter_Next(lz->it);
- if (item != NULL) {
- if (!lz->firstpass && PyList_Append(lz->saved, item)) {
- Py_DECREF(item);
- return NULL;
- }
- return item;
- }
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- return NULL;
- }
- if (PyList_Size(lz->saved) == 0)
- return NULL;
- it = PyObject_GetIter(lz->saved);
- if (it == NULL)
- return NULL;
- tmp = lz->it;
- lz->it = it;
- lz->firstpass = 1;
- Py_DECREF(tmp);
- }
+ PyObject *item;
+ PyObject *it;
+ PyObject *tmp;
+
+ while (1) {
+ item = PyIter_Next(lz->it);
+ if (item != NULL) {
+ if (!lz->firstpass && PyList_Append(lz->saved, item)) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ return item;
+ }
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ if (PyList_Size(lz->saved) == 0)
+ return NULL;
+ it = PyObject_GetIter(lz->saved);
+ if (it == NULL)
+ return NULL;
+ tmp = lz->it;
+ lz->it = it;
+ lz->firstpass = 1;
+ Py_DECREF(tmp);
+ }
}
PyDoc_STRVAR(cycle_doc,
@@ -776,57 +776,57 @@ Return elements from the iterable until it is exhausted.\n\
Then repeat the sequence indefinitely.");
static PyTypeObject cycle_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.cycle", /* tp_name */
- sizeof(cycleobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)cycle_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- cycle_doc, /* tp_doc */
- (traverseproc)cycle_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)cycle_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- cycle_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.cycle", /* tp_name */
+ sizeof(cycleobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)cycle_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ cycle_doc, /* tp_doc */
+ (traverseproc)cycle_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)cycle_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ cycle_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* dropwhile object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
- long start;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
+ long start;
} dropwhileobject;
static PyTypeObject dropwhile_type;
@@ -834,81 +834,81 @@ static PyTypeObject dropwhile_type;
static PyObject *
dropwhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- dropwhileobject *lz;
-
- if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq))
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create dropwhileobject structure */
- lz = (dropwhileobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
- lz->start = 0;
-
- return (PyObject *)lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ dropwhileobject *lz;
+
+ if (type == &dropwhile_type && !_PyArg_NoKeywords("dropwhile()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "dropwhile", 2, 2, &func, &seq))
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create dropwhileobject structure */
+ lz = (dropwhileobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+ lz->start = 0;
+
+ return (PyObject *)lz;
}
static void
dropwhile_dealloc(dropwhileobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
dropwhile_traverse(dropwhileobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
dropwhile_next(dropwhileobject *lz)
{
- PyObject *item, *good;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
- if (lz->start == 1)
- return item;
-
- good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- if (!ok) {
- lz->start = 1;
- return item;
- }
- Py_DECREF(item);
- }
+ PyObject *item, *good;
+ PyObject *it = lz->it;
+ long ok;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+ if (lz->start == 1)
+ return item;
+
+ good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ if (!ok) {
+ lz->start = 1;
+ return item;
+ }
+ Py_DECREF(item);
+ }
}
PyDoc_STRVAR(dropwhile_doc,
@@ -918,57 +918,57 @@ Drop items from the iterable while predicate(item) is true.\n\
Afterwards, return every element until the iterable is exhausted.");
static PyTypeObject dropwhile_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.dropwhile", /* tp_name */
- sizeof(dropwhileobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dropwhile_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- dropwhile_doc, /* tp_doc */
- (traverseproc)dropwhile_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dropwhile_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- dropwhile_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.dropwhile", /* tp_name */
+ sizeof(dropwhileobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dropwhile_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ dropwhile_doc, /* tp_doc */
+ (traverseproc)dropwhile_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dropwhile_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ dropwhile_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* takewhile object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
- long stop;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
+ long stop;
} takewhileobject;
static PyTypeObject takewhile_type;
@@ -976,78 +976,78 @@ static PyTypeObject takewhile_type;
static PyObject *
takewhile_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- takewhileobject *lz;
-
- if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq))
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create takewhileobject structure */
- lz = (takewhileobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
- lz->stop = 0;
-
- return (PyObject *)lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ takewhileobject *lz;
+
+ if (type == &takewhile_type && !_PyArg_NoKeywords("takewhile()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "takewhile", 2, 2, &func, &seq))
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create takewhileobject structure */
+ lz = (takewhileobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+ lz->stop = 0;
+
+ return (PyObject *)lz;
}
static void
takewhile_dealloc(takewhileobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
takewhile_traverse(takewhileobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
takewhile_next(takewhileobject *lz)
{
- PyObject *item, *good;
- PyObject *it = lz->it;
- long ok;
-
- if (lz->stop == 1)
- return NULL;
-
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL)
- return NULL;
-
- good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- if (ok)
- return item;
- Py_DECREF(item);
- lz->stop = 1;
- return NULL;
+ PyObject *item, *good;
+ PyObject *it = lz->it;
+ long ok;
+
+ if (lz->stop == 1)
+ return NULL;
+
+ item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (item == NULL)
+ return NULL;
+
+ good = PyObject_CallFunctionObjArgs(lz->func, item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ if (ok)
+ return item;
+ Py_DECREF(item);
+ lz->stop = 1;
+ return NULL;
}
PyDoc_STRVAR(takewhile_doc,
@@ -1057,59 +1057,59 @@ Return successive entries from an iterable as long as the \n\
predicate evaluates to true for each entry.");
static PyTypeObject takewhile_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.takewhile", /* tp_name */
- sizeof(takewhileobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)takewhile_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- takewhile_doc, /* tp_doc */
- (traverseproc)takewhile_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)takewhile_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- takewhile_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.takewhile", /* tp_name */
+ sizeof(takewhileobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)takewhile_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ takewhile_doc, /* tp_doc */
+ (traverseproc)takewhile_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)takewhile_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ takewhile_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* islice object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *it;
- Py_ssize_t next;
- Py_ssize_t stop;
- Py_ssize_t step;
- Py_ssize_t cnt;
+ PyObject_HEAD
+ PyObject *it;
+ Py_ssize_t next;
+ Py_ssize_t stop;
+ Py_ssize_t step;
+ Py_ssize_t cnt;
} isliceobject;
static PyTypeObject islice_type;
@@ -1117,126 +1117,126 @@ static PyTypeObject islice_type;
static PyObject *
islice_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *seq;
- Py_ssize_t start=0, stop=-1, step=1;
- PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL;
- Py_ssize_t numargs;
- isliceobject *lz;
-
- if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3))
- return NULL;
-
- numargs = PyTuple_Size(args);
- if (numargs == 2) {
- if (a1 != Py_None) {
- stop = PyInt_AsSsize_t(a1);
- if (stop == -1) {
- if (PyErr_Occurred())
- PyErr_Clear();
- PyErr_SetString(PyExc_ValueError,
- "Stop argument for islice() must be None or an integer: 0 <= x <= maxint.");
- return NULL;
- }
- }
- } else {
- if (a1 != Py_None)
- start = PyInt_AsSsize_t(a1);
- if (start == -1 && PyErr_Occurred())
- PyErr_Clear();
- if (a2 != Py_None) {
- stop = PyInt_AsSsize_t(a2);
- if (stop == -1) {
- if (PyErr_Occurred())
- PyErr_Clear();
- PyErr_SetString(PyExc_ValueError,
- "Stop argument for islice() must be None or an integer: 0 <= x <= maxint.");
- return NULL;
- }
- }
- }
- if (start<0 || stop<-1) {
- PyErr_SetString(PyExc_ValueError,
- "Indices for islice() must be None or an integer: 0 <= x <= maxint.");
- return NULL;
- }
-
- if (a3 != NULL) {
- if (a3 != Py_None)
- step = PyInt_AsSsize_t(a3);
- if (step == -1 && PyErr_Occurred())
- PyErr_Clear();
- }
- if (step<1) {
- PyErr_SetString(PyExc_ValueError,
- "Step for islice() must be a positive integer or None.");
- return NULL;
- }
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create isliceobject structure */
- lz = (isliceobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- lz->it = it;
- lz->next = start;
- lz->stop = stop;
- lz->step = step;
- lz->cnt = 0L;
-
- return (PyObject *)lz;
+ PyObject *seq;
+ Py_ssize_t start=0, stop=-1, step=1;
+ PyObject *it, *a1=NULL, *a2=NULL, *a3=NULL;
+ Py_ssize_t numargs;
+ isliceobject *lz;
+
+ if (type == &islice_type && !_PyArg_NoKeywords("islice()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "islice", 2, 4, &seq, &a1, &a2, &a3))
+ return NULL;
+
+ numargs = PyTuple_Size(args);
+ if (numargs == 2) {
+ if (a1 != Py_None) {
+ stop = PyInt_AsSsize_t(a1);
+ if (stop == -1) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ PyErr_SetString(PyExc_ValueError,
+ "Stop argument for islice() must be None or an integer: 0 <= x <= maxint.");
+ return NULL;
+ }
+ }
+ } else {
+ if (a1 != Py_None)
+ start = PyInt_AsSsize_t(a1);
+ if (start == -1 && PyErr_Occurred())
+ PyErr_Clear();
+ if (a2 != Py_None) {
+ stop = PyInt_AsSsize_t(a2);
+ if (stop == -1) {
+ if (PyErr_Occurred())
+ PyErr_Clear();
+ PyErr_SetString(PyExc_ValueError,
+ "Stop argument for islice() must be None or an integer: 0 <= x <= maxint.");
+ return NULL;
+ }
+ }
+ }
+ if (start<0 || stop<-1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Indices for islice() must be None or an integer: 0 <= x <= maxint.");
+ return NULL;
+ }
+
+ if (a3 != NULL) {
+ if (a3 != Py_None)
+ step = PyInt_AsSsize_t(a3);
+ if (step == -1 && PyErr_Occurred())
+ PyErr_Clear();
+ }
+ if (step<1) {
+ PyErr_SetString(PyExc_ValueError,
+ "Step for islice() must be a positive integer or None.");
+ return NULL;
+ }
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create isliceobject structure */
+ lz = (isliceobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ lz->it = it;
+ lz->next = start;
+ lz->stop = stop;
+ lz->step = step;
+ lz->cnt = 0L;
+
+ return (PyObject *)lz;
}
static void
islice_dealloc(isliceobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
islice_traverse(isliceobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- return 0;
+ Py_VISIT(lz->it);
+ return 0;
}
static PyObject *
islice_next(isliceobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- Py_ssize_t oldnext;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- while (lz->cnt < lz->next) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
- Py_DECREF(item);
- lz->cnt++;
- }
- if (lz->stop != -1 && lz->cnt >= lz->stop)
- return NULL;
- item = iternext(it);
- if (item == NULL)
- return NULL;
- lz->cnt++;
- oldnext = lz->next;
- lz->next += lz->step;
- if (lz->next < oldnext) /* Check for overflow */
- lz->next = lz->stop;
- return item;
+ PyObject *item;
+ PyObject *it = lz->it;
+ Py_ssize_t oldnext;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ while (lz->cnt < lz->next) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+ Py_DECREF(item);
+ lz->cnt++;
+ }
+ if (lz->stop != -1 && lz->cnt >= lz->stop)
+ return NULL;
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+ lz->cnt++;
+ oldnext = lz->next;
+ lz->next += lz->step;
+ if (lz->next < oldnext) /* Check for overflow */
+ lz->next = lz->stop;
+ return item;
}
PyDoc_STRVAR(islice_doc,
@@ -1250,56 +1250,56 @@ skipped between successive calls. Works like a slice() on a list\n\
but returns an iterator.");
static PyTypeObject islice_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.islice", /* tp_name */
- sizeof(isliceobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)islice_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- islice_doc, /* tp_doc */
- (traverseproc)islice_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)islice_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- islice_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.islice", /* tp_name */
+ sizeof(isliceobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)islice_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ islice_doc, /* tp_doc */
+ (traverseproc)islice_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)islice_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ islice_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* starmap object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} starmapobject;
static PyTypeObject starmap_type;
@@ -1307,71 +1307,71 @@ static PyTypeObject starmap_type;
static PyObject *
starmap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- starmapobject *lz;
-
- if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq))
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create starmapobject structure */
- lz = (starmapobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
-
- return (PyObject *)lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ starmapobject *lz;
+
+ if (type == &starmap_type && !_PyArg_NoKeywords("starmap()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "starmap", 2, 2, &func, &seq))
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create starmapobject structure */
+ lz = (starmapobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+
+ return (PyObject *)lz;
}
static void
starmap_dealloc(starmapobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
starmap_traverse(starmapobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
starmap_next(starmapobject *lz)
{
- PyObject *args;
- PyObject *result;
- PyObject *it = lz->it;
-
- args = (*Py_TYPE(it)->tp_iternext)(it);
- if (args == NULL)
- return NULL;
- if (!PyTuple_CheckExact(args)) {
- PyObject *newargs = PySequence_Tuple(args);
- Py_DECREF(args);
- if (newargs == NULL)
- return NULL;
- args = newargs;
- }
- result = PyObject_Call(lz->func, args, NULL);
- Py_DECREF(args);
- return result;
+ PyObject *args;
+ PyObject *result;
+ PyObject *it = lz->it;
+
+ args = (*Py_TYPE(it)->tp_iternext)(it);
+ if (args == NULL)
+ return NULL;
+ if (!PyTuple_CheckExact(args)) {
+ PyObject *newargs = PySequence_Tuple(args);
+ Py_DECREF(args);
+ if (newargs == NULL)
+ return NULL;
+ args = newargs;
+ }
+ result = PyObject_Call(lz->func, args, NULL);
+ Py_DECREF(args);
+ return result;
}
PyDoc_STRVAR(starmap_doc,
@@ -1381,56 +1381,56 @@ Return an iterator whose values are returned from the function evaluated\n\
with a argument tuple taken from the given sequence.");
static PyTypeObject starmap_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.starmap", /* tp_name */
- sizeof(starmapobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)starmap_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- starmap_doc, /* tp_doc */
- (traverseproc)starmap_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)starmap_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- starmap_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.starmap", /* tp_name */
+ sizeof(starmapobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)starmap_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ starmap_doc, /* tp_doc */
+ (traverseproc)starmap_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)starmap_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ starmap_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* imap object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *iters;
- PyObject *func;
+ PyObject_HEAD
+ PyObject *iters;
+ PyObject *func;
} imapobject;
static PyTypeObject imap_type;
@@ -1438,66 +1438,66 @@ static PyTypeObject imap_type;
static PyObject *
imap_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *it, *iters, *func;
- imapobject *lz;
- Py_ssize_t numargs, i;
-
- if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds))
- return NULL;
-
- numargs = PyTuple_Size(args);
- if (numargs < 2) {
- PyErr_SetString(PyExc_TypeError,
- "imap() must have at least two arguments.");
- return NULL;
- }
-
- iters = PyTuple_New(numargs-1);
- if (iters == NULL)
- return NULL;
-
- for (i=1 ; i<numargs ; i++) {
- /* Get iterator. */
- it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
- if (it == NULL) {
- Py_DECREF(iters);
- return NULL;
- }
- PyTuple_SET_ITEM(iters, i-1, it);
- }
-
- /* create imapobject structure */
- lz = (imapobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(iters);
- return NULL;
- }
- lz->iters = iters;
- func = PyTuple_GET_ITEM(args, 0);
- Py_INCREF(func);
- lz->func = func;
-
- return (PyObject *)lz;
+ PyObject *it, *iters, *func;
+ imapobject *lz;
+ Py_ssize_t numargs, i;
+
+ if (type == &imap_type && !_PyArg_NoKeywords("imap()", kwds))
+ return NULL;
+
+ numargs = PyTuple_Size(args);
+ if (numargs < 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "imap() must have at least two arguments.");
+ return NULL;
+ }
+
+ iters = PyTuple_New(numargs-1);
+ if (iters == NULL)
+ return NULL;
+
+ for (i=1 ; i<numargs ; i++) {
+ /* Get iterator. */
+ it = PyObject_GetIter(PyTuple_GET_ITEM(args, i));
+ if (it == NULL) {
+ Py_DECREF(iters);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(iters, i-1, it);
+ }
+
+ /* create imapobject structure */
+ lz = (imapobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(iters);
+ return NULL;
+ }
+ lz->iters = iters;
+ func = PyTuple_GET_ITEM(args, 0);
+ Py_INCREF(func);
+ lz->func = func;
+
+ return (PyObject *)lz;
}
static void
imap_dealloc(imapobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->iters);
- Py_XDECREF(lz->func);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->iters);
+ Py_XDECREF(lz->func);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
imap_traverse(imapobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->iters);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->iters);
+ Py_VISIT(lz->func);
+ return 0;
}
-/*
+/*
imap() is an iterator version of __builtins__.map() except that it does
not have the None fill-in feature. That was intentionally left out for
the following reasons:
@@ -1508,15 +1508,15 @@ the following reasons:
infinite iterators like count() and repeat() (for supplying sequential
or constant arguments to a function).
- 2) In typical use cases for combining itertools, having one finite data
+ 2) In typical use cases for combining itertools, having one finite data
supplier run out before another is likely to be an error condition which
should not pass silently by automatically supplying None.
3) The use cases for automatic None fill-in are rare -- not many functions
do something useful when a parameter suddenly switches type and becomes
- None.
+ None.
- 4) If a need does arise, it can be met by __builtins__.map() or by
+ 4) If a need does arise, it can be met by __builtins__.map() or by
writing: chain(iterable, repeat(None)).
5) Similar toolsets in Haskell and SML do not have automatic None fill-in.
@@ -1525,187 +1525,187 @@ the following reasons:
static PyObject *
imap_next(imapobject *lz)
{
- PyObject *val;
- PyObject *argtuple;
- PyObject *result;
- Py_ssize_t numargs, i;
-
- numargs = PyTuple_Size(lz->iters);
- argtuple = PyTuple_New(numargs);
- if (argtuple == NULL)
- return NULL;
-
- for (i=0 ; i<numargs ; i++) {
- val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
- if (val == NULL) {
- Py_DECREF(argtuple);
- return NULL;
- }
- PyTuple_SET_ITEM(argtuple, i, val);
- }
- if (lz->func == Py_None)
- return argtuple;
- result = PyObject_Call(lz->func, argtuple, NULL);
- Py_DECREF(argtuple);
- return result;
+ PyObject *val;
+ PyObject *argtuple;
+ PyObject *result;
+ Py_ssize_t numargs, i;
+
+ numargs = PyTuple_Size(lz->iters);
+ argtuple = PyTuple_New(numargs);
+ if (argtuple == NULL)
+ return NULL;
+
+ for (i=0 ; i<numargs ; i++) {
+ val = PyIter_Next(PyTuple_GET_ITEM(lz->iters, i));
+ if (val == NULL) {
+ Py_DECREF(argtuple);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(argtuple, i, val);
+ }
+ if (lz->func == Py_None)
+ return argtuple;
+ result = PyObject_Call(lz->func, argtuple, NULL);
+ Py_DECREF(argtuple);
+ return result;
}
PyDoc_STRVAR(imap_doc,
"imap(func, *iterables) --> imap object\n\
\n\
Make an iterator that computes the function using arguments from\n\
-each of the iterables. Like map() except that it returns\n\
+each of the iterables. Like map() except that it returns\n\
an iterator instead of a list and that it stops when the shortest\n\
iterable is exhausted instead of filling in None for shorter\n\
iterables.");
static PyTypeObject imap_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.imap", /* tp_name */
- sizeof(imapobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)imap_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- imap_doc, /* tp_doc */
- (traverseproc)imap_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)imap_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- imap_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.imap", /* tp_name */
+ sizeof(imapobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)imap_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ imap_doc, /* tp_doc */
+ (traverseproc)imap_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)imap_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ imap_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* chain object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *source; /* Iterator over input iterables */
- PyObject *active; /* Currently running input iterator */
+ PyObject_HEAD
+ PyObject *source; /* Iterator over input iterables */
+ PyObject *active; /* Currently running input iterator */
} chainobject;
static PyTypeObject chain_type;
-static PyObject *
+static PyObject *
chain_new_internal(PyTypeObject *type, PyObject *source)
{
- chainobject *lz;
-
- lz = (chainobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(source);
- return NULL;
- }
-
- lz->source = source;
- lz->active = NULL;
- return (PyObject *)lz;
+ chainobject *lz;
+
+ lz = (chainobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(source);
+ return NULL;
+ }
+
+ lz->source = source;
+ lz->active = NULL;
+ return (PyObject *)lz;
}
static PyObject *
chain_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *source;
+ PyObject *source;
+
+ if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
+ return NULL;
- if (type == &chain_type && !_PyArg_NoKeywords("chain()", kwds))
- return NULL;
-
- source = PyObject_GetIter(args);
- if (source == NULL)
- return NULL;
+ source = PyObject_GetIter(args);
+ if (source == NULL)
+ return NULL;
- return chain_new_internal(type, source);
+ return chain_new_internal(type, source);
}
static PyObject *
chain_new_from_iterable(PyTypeObject *type, PyObject *arg)
{
- PyObject *source;
-
- source = PyObject_GetIter(arg);
- if (source == NULL)
- return NULL;
+ PyObject *source;
- return chain_new_internal(type, source);
+ source = PyObject_GetIter(arg);
+ if (source == NULL)
+ return NULL;
+
+ return chain_new_internal(type, source);
}
static void
chain_dealloc(chainobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->active);
- Py_XDECREF(lz->source);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->active);
+ Py_XDECREF(lz->source);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
chain_traverse(chainobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->source);
- Py_VISIT(lz->active);
- return 0;
+ Py_VISIT(lz->source);
+ Py_VISIT(lz->active);
+ return 0;
}
static PyObject *
chain_next(chainobject *lz)
{
- PyObject *item;
-
- if (lz->source == NULL)
- return NULL; /* already stopped */
-
- if (lz->active == NULL) {
- PyObject *iterable = PyIter_Next(lz->source);
- if (iterable == NULL) {
- Py_CLEAR(lz->source);
- return NULL; /* no more input sources */
- }
- lz->active = PyObject_GetIter(iterable);
- Py_DECREF(iterable);
- if (lz->active == NULL) {
- Py_CLEAR(lz->source);
- return NULL; /* input not iterable */
- }
- }
- item = PyIter_Next(lz->active);
- if (item != NULL)
- return item;
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- return NULL; /* input raised an exception */
- }
- Py_CLEAR(lz->active);
- return chain_next(lz); /* recurse and use next active */
+ PyObject *item;
+
+ if (lz->source == NULL)
+ return NULL; /* already stopped */
+
+ if (lz->active == NULL) {
+ PyObject *iterable = PyIter_Next(lz->source);
+ if (iterable == NULL) {
+ Py_CLEAR(lz->source);
+ return NULL; /* no more input sources */
+ }
+ lz->active = PyObject_GetIter(iterable);
+ Py_DECREF(iterable);
+ if (lz->active == NULL) {
+ Py_CLEAR(lz->source);
+ return NULL; /* input not iterable */
+ }
+ }
+ item = PyIter_Next(lz->active);
+ if (item != NULL)
+ return item;
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ return NULL; /* input raised an exception */
+ }
+ Py_CLEAR(lz->active);
+ return chain_next(lz); /* recurse and use next active */
}
PyDoc_STRVAR(chain_doc,
@@ -1722,64 +1722,64 @@ Alternate chain() contructor taking a single iterable argument\n\
that evaluates lazily.");
static PyMethodDef chain_methods[] = {
- {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS,
- chain_from_iterable_doc},
- {NULL, NULL} /* sentinel */
+ {"from_iterable", (PyCFunction) chain_new_from_iterable, METH_O | METH_CLASS,
+ chain_from_iterable_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject chain_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.chain", /* tp_name */
- sizeof(chainobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)chain_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- chain_doc, /* tp_doc */
- (traverseproc)chain_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)chain_next, /* tp_iternext */
- chain_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 */
- chain_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.chain", /* tp_name */
+ sizeof(chainobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)chain_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ chain_doc, /* tp_doc */
+ (traverseproc)chain_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)chain_next, /* tp_iternext */
+ chain_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 */
+ chain_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* product object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *pools; /* tuple of pool tuples */
- Py_ssize_t *indices; /* one index per pool */
- PyObject *result; /* most recently returned result tuple */
- int stopped; /* set to 1 when the product iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pools; /* tuple of pool tuples */
+ Py_ssize_t *indices; /* one index per pool */
+ PyObject *result; /* most recently returned result tuple */
+ int stopped; /* set to 1 when the product iterator is exhausted */
} productobject;
static PyTypeObject product_type;
@@ -1787,181 +1787,181 @@ static PyTypeObject product_type;
static PyObject *
product_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- productobject *lz;
- Py_ssize_t nargs, npools, repeat=1;
- PyObject *pools = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t i;
-
- if (kwds != NULL) {
- char *kwlist[] = {"repeat", 0};
- PyObject *tmpargs = PyTuple_New(0);
- if (tmpargs == NULL)
- return NULL;
- if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) {
- Py_DECREF(tmpargs);
- return NULL;
- }
- Py_DECREF(tmpargs);
- if (repeat < 0) {
- PyErr_SetString(PyExc_ValueError,
- "repeat argument cannot be negative");
- return NULL;
- }
- }
-
- assert(PyTuple_Check(args));
- nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args);
- npools = nargs * repeat;
-
- indices = PyMem_Malloc(npools * sizeof(Py_ssize_t));
- if (indices == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- pools = PyTuple_New(npools);
- if (pools == NULL)
- goto error;
-
- for (i=0; i < nargs ; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- PyObject *pool = PySequence_Tuple(item);
- if (pool == NULL)
- goto error;
- PyTuple_SET_ITEM(pools, i, pool);
- indices[i] = 0;
- }
- for ( ; i < npools; ++i) {
- PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs);
- Py_INCREF(pool);
- PyTuple_SET_ITEM(pools, i, pool);
- indices[i] = 0;
- }
-
- /* create productobject structure */
- lz = (productobject *)type->tp_alloc(type, 0);
- if (lz == NULL)
- goto error;
-
- lz->pools = pools;
- lz->indices = indices;
- lz->result = NULL;
- lz->stopped = 0;
-
- return (PyObject *)lz;
+ productobject *lz;
+ Py_ssize_t nargs, npools, repeat=1;
+ PyObject *pools = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t i;
+
+ if (kwds != NULL) {
+ char *kwlist[] = {"repeat", 0};
+ PyObject *tmpargs = PyTuple_New(0);
+ if (tmpargs == NULL)
+ return NULL;
+ if (!PyArg_ParseTupleAndKeywords(tmpargs, kwds, "|n:product", kwlist, &repeat)) {
+ Py_DECREF(tmpargs);
+ return NULL;
+ }
+ Py_DECREF(tmpargs);
+ if (repeat < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "repeat argument cannot be negative");
+ return NULL;
+ }
+ }
+
+ assert(PyTuple_Check(args));
+ nargs = (repeat == 0) ? 0 : PyTuple_GET_SIZE(args);
+ npools = nargs * repeat;
+
+ indices = PyMem_Malloc(npools * sizeof(Py_ssize_t));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ pools = PyTuple_New(npools);
+ if (pools == NULL)
+ goto error;
+
+ for (i=0; i < nargs ; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *pool = PySequence_Tuple(item);
+ if (pool == NULL)
+ goto error;
+ PyTuple_SET_ITEM(pools, i, pool);
+ indices[i] = 0;
+ }
+ for ( ; i < npools; ++i) {
+ PyObject *pool = PyTuple_GET_ITEM(pools, i - nargs);
+ Py_INCREF(pool);
+ PyTuple_SET_ITEM(pools, i, pool);
+ indices[i] = 0;
+ }
+
+ /* create productobject structure */
+ lz = (productobject *)type->tp_alloc(type, 0);
+ if (lz == NULL)
+ goto error;
+
+ lz->pools = pools;
+ lz->indices = indices;
+ lz->result = NULL;
+ lz->stopped = 0;
+
+ return (PyObject *)lz;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- Py_XDECREF(pools);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ Py_XDECREF(pools);
+ return NULL;
}
static void
product_dealloc(productobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->pools);
- Py_XDECREF(lz->result);
- if (lz->indices != NULL)
- PyMem_Free(lz->indices);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->pools);
+ Py_XDECREF(lz->result);
+ if (lz->indices != NULL)
+ PyMem_Free(lz->indices);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
product_traverse(productobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->pools);
- Py_VISIT(lz->result);
- return 0;
+ Py_VISIT(lz->pools);
+ Py_VISIT(lz->result);
+ return 0;
}
static PyObject *
product_next(productobject *lz)
{
- PyObject *pool;
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pools = lz->pools;
- PyObject *result = lz->result;
- Py_ssize_t npools = PyTuple_GET_SIZE(pools);
- Py_ssize_t i;
-
- if (lz->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, return an initial tuple filled with the
- first element from each pool. */
- result = PyTuple_New(npools);
- if (result == NULL)
- goto empty;
- lz->result = result;
- for (i=0; i < npools; i++) {
- pool = PyTuple_GET_ITEM(pools, i);
- if (PyTuple_GET_SIZE(pool) == 0)
- goto empty;
- elem = PyTuple_GET_ITEM(pool, 0);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- Py_ssize_t *indices = lz->indices;
-
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(npools);
- if (result == NULL)
- goto empty;
- lz->result = result;
- for (i=0; i < npools; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place */
- assert (npools==0 || Py_REFCNT(result) == 1);
-
- /* Update the pool indices right-to-left. Only advance to the
- next pool when the previous one rolls-over */
- for (i=npools-1 ; i >= 0 ; i--) {
- pool = PyTuple_GET_ITEM(pools, i);
- indices[i]++;
- if (indices[i] == PyTuple_GET_SIZE(pool)) {
- /* Roll-over and advance to next pool */
- indices[i] = 0;
- elem = PyTuple_GET_ITEM(pool, 0);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- } else {
- /* No rollover. Just increment and stop here. */
- elem = PyTuple_GET_ITEM(pool, indices[i]);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- break;
- }
- }
-
- /* If i is negative, then the indices have all rolled-over
- and we're done. */
- if (i < 0)
- goto empty;
- }
-
- Py_INCREF(result);
- return result;
+ PyObject *pool;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pools = lz->pools;
+ PyObject *result = lz->result;
+ Py_ssize_t npools = PyTuple_GET_SIZE(pools);
+ Py_ssize_t i;
+
+ if (lz->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, return an initial tuple filled with the
+ first element from each pool. */
+ result = PyTuple_New(npools);
+ if (result == NULL)
+ goto empty;
+ lz->result = result;
+ for (i=0; i < npools; i++) {
+ pool = PyTuple_GET_ITEM(pools, i);
+ if (PyTuple_GET_SIZE(pool) == 0)
+ goto empty;
+ elem = PyTuple_GET_ITEM(pool, 0);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ Py_ssize_t *indices = lz->indices;
+
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(npools);
+ if (result == NULL)
+ goto empty;
+ lz->result = result;
+ for (i=0; i < npools; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place */
+ assert (npools==0 || Py_REFCNT(result) == 1);
+
+ /* Update the pool indices right-to-left. Only advance to the
+ next pool when the previous one rolls-over */
+ for (i=npools-1 ; i >= 0 ; i--) {
+ pool = PyTuple_GET_ITEM(pools, i);
+ indices[i]++;
+ if (indices[i] == PyTuple_GET_SIZE(pool)) {
+ /* Roll-over and advance to next pool */
+ indices[i] = 0;
+ elem = PyTuple_GET_ITEM(pool, 0);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ } else {
+ /* No rollover. Just increment and stop here. */
+ elem = PyTuple_GET_ITEM(pool, indices[i]);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ break;
+ }
+ }
+
+ /* If i is negative, then the indices have all rolled-over
+ and we're done. */
+ if (i < 0)
+ goto empty;
+ }
+
+ Py_INCREF(result);
+ return result;
empty:
- lz->stopped = 1;
- return NULL;
+ lz->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(product_doc,
@@ -1979,59 +1979,59 @@ product('ab', range(3)) --> ('a',0) ('a',1) ('a',2) ('b',0) ('b',1) ('b',2)\n\
product((0,1), (0,1), (0,1)) --> (0,0,0) (0,0,1) (0,1,0) (0,1,1) (1,0,0) ...");
static PyTypeObject product_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.product", /* tp_name */
- sizeof(productobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)product_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- product_doc, /* tp_doc */
- (traverseproc)product_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)product_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- product_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.product", /* tp_name */
+ sizeof(productobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)product_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ product_doc, /* tp_doc */
+ (traverseproc)product_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)product_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ product_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* combinations object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *pool; /* input converted to a tuple */
- Py_ssize_t *indices; /* one index per result element */
- PyObject *result; /* most recently returned result tuple */
- Py_ssize_t r; /* size of result tuple */
- int stopped; /* set to 1 when the combinations iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pool; /* input converted to a tuple */
+ Py_ssize_t *indices; /* one index per result element */
+ PyObject *result; /* most recently returned result tuple */
+ Py_ssize_t r; /* size of result tuple */
+ int stopped; /* set to 1 when the combinations iterator is exhausted */
} combinationsobject;
static PyTypeObject combinations_type;
@@ -2039,160 +2039,160 @@ static PyTypeObject combinations_type;
static PyObject *
combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- combinationsobject *co;
- Py_ssize_t n;
- Py_ssize_t r;
- PyObject *pool = NULL;
- PyObject *iterable = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t i;
- static char *kwargs[] = {"iterable", "r", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
- &iterable, &r))
- return NULL;
-
- pool = PySequence_Tuple(iterable);
- if (pool == NULL)
- goto error;
- n = PyTuple_GET_SIZE(pool);
- if (r < 0) {
- PyErr_SetString(PyExc_ValueError, "r must be non-negative");
- goto error;
- }
-
- indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
- if (indices == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- for (i=0 ; i<r ; i++)
- indices[i] = i;
-
- /* create combinationsobject structure */
- co = (combinationsobject *)type->tp_alloc(type, 0);
- if (co == NULL)
- goto error;
-
- co->pool = pool;
- co->indices = indices;
- co->result = NULL;
- co->r = r;
- co->stopped = r > n ? 1 : 0;
-
- return (PyObject *)co;
+ combinationsobject *co;
+ Py_ssize_t n;
+ Py_ssize_t r;
+ PyObject *pool = NULL;
+ PyObject *iterable = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t i;
+ static char *kwargs[] = {"iterable", "r", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
+ &iterable, &r))
+ return NULL;
+
+ pool = PySequence_Tuple(iterable);
+ if (pool == NULL)
+ goto error;
+ n = PyTuple_GET_SIZE(pool);
+ if (r < 0) {
+ PyErr_SetString(PyExc_ValueError, "r must be non-negative");
+ goto error;
+ }
+
+ indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ for (i=0 ; i<r ; i++)
+ indices[i] = i;
+
+ /* create combinationsobject structure */
+ co = (combinationsobject *)type->tp_alloc(type, 0);
+ if (co == NULL)
+ goto error;
+
+ co->pool = pool;
+ co->indices = indices;
+ co->result = NULL;
+ co->r = r;
+ co->stopped = r > n ? 1 : 0;
+
+ return (PyObject *)co;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- Py_XDECREF(pool);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ Py_XDECREF(pool);
+ return NULL;
}
static void
combinations_dealloc(combinationsobject *co)
{
- PyObject_GC_UnTrack(co);
- Py_XDECREF(co->pool);
- Py_XDECREF(co->result);
- if (co->indices != NULL)
- PyMem_Free(co->indices);
- Py_TYPE(co)->tp_free(co);
+ PyObject_GC_UnTrack(co);
+ Py_XDECREF(co->pool);
+ Py_XDECREF(co->result);
+ if (co->indices != NULL)
+ PyMem_Free(co->indices);
+ Py_TYPE(co)->tp_free(co);
}
static int
combinations_traverse(combinationsobject *co, visitproc visit, void *arg)
{
- Py_VISIT(co->pool);
- Py_VISIT(co->result);
- return 0;
+ Py_VISIT(co->pool);
+ Py_VISIT(co->result);
+ return 0;
}
static PyObject *
combinations_next(combinationsobject *co)
{
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pool = co->pool;
- Py_ssize_t *indices = co->indices;
- PyObject *result = co->result;
- Py_ssize_t n = PyTuple_GET_SIZE(pool);
- Py_ssize_t r = co->r;
- Py_ssize_t i, j, index;
-
- if (co->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, initialize result tuple using the indices */
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place
- * CPython's empty tuple is a singleton and cached in
- * PyTuple's freelist.
- */
- assert(r == 0 || Py_REFCNT(result) == 1);
-
- /* Scan indices right-to-left until finding one that is not
- at its maximum (i + n - r). */
- for (i=r-1 ; i >= 0 && indices[i] == i+n-r ; i--)
- ;
-
- /* If i is negative, then the indices are all at
- their maximum value and we're done. */
- if (i < 0)
- goto empty;
-
- /* Increment the current index which we know is not at its
- maximum. Then move back to the right setting each index
- to its lowest possible value (one higher than the index
- to its left -- this maintains the sort order invariant). */
- indices[i]++;
- for (j=i+1 ; j<r ; j++)
- indices[j] = indices[j-1] + 1;
-
- /* Update the result tuple for the new indices
- starting with i, the leftmost index that changed */
- for ( ; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- }
- }
-
- Py_INCREF(result);
- return result;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pool = co->pool;
+ Py_ssize_t *indices = co->indices;
+ PyObject *result = co->result;
+ Py_ssize_t n = PyTuple_GET_SIZE(pool);
+ Py_ssize_t r = co->r;
+ Py_ssize_t i, j, index;
+
+ if (co->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, initialize result tuple using the indices */
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place
+ * CPython's empty tuple is a singleton and cached in
+ * PyTuple's freelist.
+ */
+ assert(r == 0 || Py_REFCNT(result) == 1);
+
+ /* Scan indices right-to-left until finding one that is not
+ at its maximum (i + n - r). */
+ for (i=r-1 ; i >= 0 && indices[i] == i+n-r ; i--)
+ ;
+
+ /* If i is negative, then the indices are all at
+ their maximum value and we're done. */
+ if (i < 0)
+ goto empty;
+
+ /* Increment the current index which we know is not at its
+ maximum. Then move back to the right setting each index
+ to its lowest possible value (one higher than the index
+ to its left -- this maintains the sort order invariant). */
+ indices[i]++;
+ for (j=i+1 ; j<r ; j++)
+ indices[j] = indices[j-1] + 1;
+
+ /* Update the result tuple for the new indices
+ starting with i, the leftmost index that changed */
+ for ( ; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ }
+ }
+
+ Py_INCREF(result);
+ return result;
empty:
- co->stopped = 1;
- return NULL;
+ co->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(combinations_doc,
@@ -2202,47 +2202,47 @@ Return successive r-length combinations of elements in the iterable.\n\n\
combinations(range(4), 3) --> (0,1,2), (0,1,3), (0,2,3), (1,2,3)");
static PyTypeObject combinations_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.combinations", /* tp_name */
- sizeof(combinationsobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)combinations_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- combinations_doc, /* tp_doc */
- (traverseproc)combinations_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)combinations_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- combinations_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.combinations", /* tp_name */
+ sizeof(combinationsobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)combinations_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ combinations_doc, /* tp_doc */
+ (traverseproc)combinations_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)combinations_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ combinations_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -2250,37 +2250,37 @@ static PyTypeObject combinations_type = {
/* Equivalent to:
- def combinations_with_replacement(iterable, r):
- "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
- # number items returned: (n+r-1)! / r! / (n-1)!
- pool = tuple(iterable)
- n = len(pool)
- indices = [0] * r
- yield tuple(pool[i] for i in indices)
- while 1:
- for i in reversed(range(r)):
- if indices[i] != n - 1:
- break
- else:
- return
- indices[i:] = [indices[i] + 1] * (r - i)
- yield tuple(pool[i] for i in indices)
-
- def combinations_with_replacement2(iterable, r):
- 'Alternate version that filters from product()'
- pool = tuple(iterable)
- n = len(pool)
- for indices in product(range(n), repeat=r):
- if sorted(indices) == list(indices):
- yield tuple(pool[i] for i in indices)
+ def combinations_with_replacement(iterable, r):
+ "combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC"
+ # number items returned: (n+r-1)! / r! / (n-1)!
+ pool = tuple(iterable)
+ n = len(pool)
+ indices = [0] * r
+ yield tuple(pool[i] for i in indices)
+ while 1:
+ for i in reversed(range(r)):
+ if indices[i] != n - 1:
+ break
+ else:
+ return
+ indices[i:] = [indices[i] + 1] * (r - i)
+ yield tuple(pool[i] for i in indices)
+
+ def combinations_with_replacement2(iterable, r):
+ 'Alternate version that filters from product()'
+ pool = tuple(iterable)
+ n = len(pool)
+ for indices in product(range(n), repeat=r):
+ if sorted(indices) == list(indices):
+ yield tuple(pool[i] for i in indices)
*/
typedef struct {
- PyObject_HEAD
- PyObject *pool; /* input converted to a tuple */
- Py_ssize_t *indices; /* one index per result element */
- PyObject *result; /* most recently returned result tuple */
- Py_ssize_t r; /* size of result tuple */
- int stopped; /* set to 1 when the cwr iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pool; /* input converted to a tuple */
+ Py_ssize_t *indices; /* one index per result element */
+ PyObject *result; /* most recently returned result tuple */
+ Py_ssize_t r; /* size of result tuple */
+ int stopped; /* set to 1 when the cwr iterator is exhausted */
} cwrobject;
static PyTypeObject cwr_type;
@@ -2288,156 +2288,156 @@ static PyTypeObject cwr_type;
static PyObject *
cwr_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- cwrobject *co;
- Py_ssize_t n;
- Py_ssize_t r;
- PyObject *pool = NULL;
- PyObject *iterable = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t i;
- static char *kwargs[] = {"iterable", "r", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs,
- &iterable, &r))
- return NULL;
-
- pool = PySequence_Tuple(iterable);
- if (pool == NULL)
- goto error;
- n = PyTuple_GET_SIZE(pool);
- if (r < 0) {
- PyErr_SetString(PyExc_ValueError, "r must be non-negative");
- goto error;
- }
-
- indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
- if (indices == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- for (i=0 ; i<r ; i++)
- indices[i] = 0;
-
- /* create cwrobject structure */
- co = (cwrobject *)type->tp_alloc(type, 0);
- if (co == NULL)
- goto error;
-
- co->pool = pool;
- co->indices = indices;
- co->result = NULL;
- co->r = r;
- co->stopped = !n && r;
-
- return (PyObject *)co;
+ cwrobject *co;
+ Py_ssize_t n;
+ Py_ssize_t r;
+ PyObject *pool = NULL;
+ PyObject *iterable = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t i;
+ static char *kwargs[] = {"iterable", "r", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations_with_replacement", kwargs,
+ &iterable, &r))
+ return NULL;
+
+ pool = PySequence_Tuple(iterable);
+ if (pool == NULL)
+ goto error;
+ n = PyTuple_GET_SIZE(pool);
+ if (r < 0) {
+ PyErr_SetString(PyExc_ValueError, "r must be non-negative");
+ goto error;
+ }
+
+ indices = PyMem_Malloc(r * sizeof(Py_ssize_t));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ for (i=0 ; i<r ; i++)
+ indices[i] = 0;
+
+ /* create cwrobject structure */
+ co = (cwrobject *)type->tp_alloc(type, 0);
+ if (co == NULL)
+ goto error;
+
+ co->pool = pool;
+ co->indices = indices;
+ co->result = NULL;
+ co->r = r;
+ co->stopped = !n && r;
+
+ return (PyObject *)co;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- Py_XDECREF(pool);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ Py_XDECREF(pool);
+ return NULL;
}
static void
cwr_dealloc(cwrobject *co)
{
- PyObject_GC_UnTrack(co);
- Py_XDECREF(co->pool);
- Py_XDECREF(co->result);
- if (co->indices != NULL)
- PyMem_Free(co->indices);
- Py_TYPE(co)->tp_free(co);
+ PyObject_GC_UnTrack(co);
+ Py_XDECREF(co->pool);
+ Py_XDECREF(co->result);
+ if (co->indices != NULL)
+ PyMem_Free(co->indices);
+ Py_TYPE(co)->tp_free(co);
}
static int
cwr_traverse(cwrobject *co, visitproc visit, void *arg)
{
- Py_VISIT(co->pool);
- Py_VISIT(co->result);
- return 0;
+ Py_VISIT(co->pool);
+ Py_VISIT(co->result);
+ return 0;
}
static PyObject *
cwr_next(cwrobject *co)
{
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pool = co->pool;
- Py_ssize_t *indices = co->indices;
- PyObject *result = co->result;
- Py_ssize_t n = PyTuple_GET_SIZE(pool);
- Py_ssize_t r = co->r;
- Py_ssize_t i, j, index;
-
- if (co->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, initialize result tuple using the indices */
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- co->result = result;
- for (i=0; i<r ; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place CPython's
- empty tuple is a singleton and cached in PyTuple's freelist. */
- assert(r == 0 || Py_REFCNT(result) == 1);
-
- /* Scan indices right-to-left until finding one that is not
- * at its maximum (n-1). */
- for (i=r-1 ; i >= 0 && indices[i] == n-1; i--)
- ;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pool = co->pool;
+ Py_ssize_t *indices = co->indices;
+ PyObject *result = co->result;
+ Py_ssize_t n = PyTuple_GET_SIZE(pool);
+ Py_ssize_t r = co->r;
+ Py_ssize_t i, j, index;
+
+ if (co->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, initialize result tuple using the indices */
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ co->result = result;
+ for (i=0; i<r ; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place CPython's
+ empty tuple is a singleton and cached in PyTuple's freelist. */
+ assert(r == 0 || Py_REFCNT(result) == 1);
+
+ /* Scan indices right-to-left until finding one that is not
+ * at its maximum (n-1). */
+ for (i=r-1 ; i >= 0 && indices[i] == n-1; i--)
+ ;
+
+ /* If i is negative, then the indices are all at
+ their maximum value and we're done. */
+ if (i < 0)
+ goto empty;
+
+ /* Increment the current index which we know is not at its
+ maximum. Then set all to the right to the same value. */
+ indices[i]++;
+ for (j=i+1 ; j<r ; j++)
+ indices[j] = indices[j-1];
+
+ /* Update the result tuple for the new indices
+ starting with i, the leftmost index that changed */
+ for ( ; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, elem);
+ Py_DECREF(oldelem);
+ }
+ }
- /* If i is negative, then the indices are all at
- their maximum value and we're done. */
- if (i < 0)
- goto empty;
-
- /* Increment the current index which we know is not at its
- maximum. Then set all to the right to the same value. */
- indices[i]++;
- for (j=i+1 ; j<r ; j++)
- indices[j] = indices[j-1];
-
- /* Update the result tuple for the new indices
- starting with i, the leftmost index that changed */
- for ( ; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, elem);
- Py_DECREF(oldelem);
- }
- }
-
- Py_INCREF(result);
- return result;
+ Py_INCREF(result);
+ return result;
empty:
- co->stopped = 1;
- return NULL;
+ co->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(cwr_doc,
@@ -2448,52 +2448,52 @@ allowing individual elements to have successive repeats.\n\
combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC");
static PyTypeObject cwr_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.combinations_with_replacement", /* tp_name */
- sizeof(cwrobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)cwr_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- cwr_doc, /* tp_doc */
- (traverseproc)cwr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)cwr_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- cwr_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.combinations_with_replacement", /* tp_name */
+ sizeof(cwrobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)cwr_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ cwr_doc, /* tp_doc */
+ (traverseproc)cwr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)cwr_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ cwr_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* permutations object ************************************************************
-
+
def permutations(iterable, r=None):
'permutations(range(3), 2) --> (0,1) (0,2) (1,0) (1,2) (2,0) (2,1)'
pool = tuple(iterable)
@@ -2503,28 +2503,28 @@ def permutations(iterable, r=None):
cycles = range(n-r+1, n+1)[::-1]
yield tuple(pool[i] for i in indices[:r])
while n:
- for i in reversed(range(r)):
- cycles[i] -= 1
- if cycles[i] == 0:
- indices[i:] = indices[i+1:] + indices[i:i+1]
- cycles[i] = n - i
- else:
- j = cycles[i]
- indices[i], indices[-j] = indices[-j], indices[i]
- yield tuple(pool[i] for i in indices[:r])
- break
+ for i in reversed(range(r)):
+ cycles[i] -= 1
+ if cycles[i] == 0:
+ indices[i:] = indices[i+1:] + indices[i:i+1]
+ cycles[i] = n - i
else:
- return
+ j = cycles[i]
+ indices[i], indices[-j] = indices[-j], indices[i]
+ yield tuple(pool[i] for i in indices[:r])
+ break
+ else:
+ return
*/
typedef struct {
- PyObject_HEAD
- PyObject *pool; /* input converted to a tuple */
- Py_ssize_t *indices; /* one index per element in the pool */
- Py_ssize_t *cycles; /* one rollover counter per element in the result */
- PyObject *result; /* most recently returned result tuple */
- Py_ssize_t r; /* size of result tuple */
- int stopped; /* set to 1 when the permutations iterator is exhausted */
+ PyObject_HEAD
+ PyObject *pool; /* input converted to a tuple */
+ Py_ssize_t *indices; /* one index per element in the pool */
+ Py_ssize_t *cycles; /* one rollover counter per element in the result */
+ PyObject *result; /* most recently returned result tuple */
+ Py_ssize_t r; /* size of result tuple */
+ int stopped; /* set to 1 when the permutations iterator is exhausted */
} permutationsobject;
static PyTypeObject permutations_type;
@@ -2532,180 +2532,180 @@ static PyTypeObject permutations_type;
static PyObject *
permutations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- permutationsobject *po;
- Py_ssize_t n;
- Py_ssize_t r;
- PyObject *robj = Py_None;
- PyObject *pool = NULL;
- PyObject *iterable = NULL;
- Py_ssize_t *indices = NULL;
- Py_ssize_t *cycles = NULL;
- Py_ssize_t i;
- static char *kwargs[] = {"iterable", "r", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs,
- &iterable, &robj))
- return NULL;
-
- pool = PySequence_Tuple(iterable);
- if (pool == NULL)
- goto error;
- n = PyTuple_GET_SIZE(pool);
-
- r = n;
- if (robj != Py_None) {
- r = PyInt_AsSsize_t(robj);
- if (r == -1 && PyErr_Occurred())
- goto error;
- }
- if (r < 0) {
- PyErr_SetString(PyExc_ValueError, "r must be non-negative");
- goto error;
- }
-
- indices = PyMem_Malloc(n * sizeof(Py_ssize_t));
- cycles = PyMem_Malloc(r * sizeof(Py_ssize_t));
- if (indices == NULL || cycles == NULL) {
- PyErr_NoMemory();
- goto error;
- }
-
- for (i=0 ; i<n ; i++)
- indices[i] = i;
- for (i=0 ; i<r ; i++)
- cycles[i] = n - i;
-
- /* create permutationsobject structure */
- po = (permutationsobject *)type->tp_alloc(type, 0);
- if (po == NULL)
- goto error;
-
- po->pool = pool;
- po->indices = indices;
- po->cycles = cycles;
- po->result = NULL;
- po->r = r;
- po->stopped = r > n ? 1 : 0;
-
- return (PyObject *)po;
+ permutationsobject *po;
+ Py_ssize_t n;
+ Py_ssize_t r;
+ PyObject *robj = Py_None;
+ PyObject *pool = NULL;
+ PyObject *iterable = NULL;
+ Py_ssize_t *indices = NULL;
+ Py_ssize_t *cycles = NULL;
+ Py_ssize_t i;
+ static char *kwargs[] = {"iterable", "r", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:permutations", kwargs,
+ &iterable, &robj))
+ return NULL;
+
+ pool = PySequence_Tuple(iterable);
+ if (pool == NULL)
+ goto error;
+ n = PyTuple_GET_SIZE(pool);
+
+ r = n;
+ if (robj != Py_None) {
+ r = PyInt_AsSsize_t(robj);
+ if (r == -1 && PyErr_Occurred())
+ goto error;
+ }
+ if (r < 0) {
+ PyErr_SetString(PyExc_ValueError, "r must be non-negative");
+ goto error;
+ }
+
+ indices = PyMem_Malloc(n * sizeof(Py_ssize_t));
+ cycles = PyMem_Malloc(r * sizeof(Py_ssize_t));
+ if (indices == NULL || cycles == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+
+ for (i=0 ; i<n ; i++)
+ indices[i] = i;
+ for (i=0 ; i<r ; i++)
+ cycles[i] = n - i;
+
+ /* create permutationsobject structure */
+ po = (permutationsobject *)type->tp_alloc(type, 0);
+ if (po == NULL)
+ goto error;
+
+ po->pool = pool;
+ po->indices = indices;
+ po->cycles = cycles;
+ po->result = NULL;
+ po->r = r;
+ po->stopped = r > n ? 1 : 0;
+
+ return (PyObject *)po;
error:
- if (indices != NULL)
- PyMem_Free(indices);
- if (cycles != NULL)
- PyMem_Free(cycles);
- Py_XDECREF(pool);
- return NULL;
+ if (indices != NULL)
+ PyMem_Free(indices);
+ if (cycles != NULL)
+ PyMem_Free(cycles);
+ Py_XDECREF(pool);
+ return NULL;
}
static void
permutations_dealloc(permutationsobject *po)
{
- PyObject_GC_UnTrack(po);
- Py_XDECREF(po->pool);
- Py_XDECREF(po->result);
- PyMem_Free(po->indices);
- PyMem_Free(po->cycles);
- Py_TYPE(po)->tp_free(po);
+ PyObject_GC_UnTrack(po);
+ Py_XDECREF(po->pool);
+ Py_XDECREF(po->result);
+ PyMem_Free(po->indices);
+ PyMem_Free(po->cycles);
+ Py_TYPE(po)->tp_free(po);
}
static int
permutations_traverse(permutationsobject *po, visitproc visit, void *arg)
{
- Py_VISIT(po->pool);
- Py_VISIT(po->result);
- return 0;
+ Py_VISIT(po->pool);
+ Py_VISIT(po->result);
+ return 0;
}
static PyObject *
permutations_next(permutationsobject *po)
{
- PyObject *elem;
- PyObject *oldelem;
- PyObject *pool = po->pool;
- Py_ssize_t *indices = po->indices;
- Py_ssize_t *cycles = po->cycles;
- PyObject *result = po->result;
- Py_ssize_t n = PyTuple_GET_SIZE(pool);
- Py_ssize_t r = po->r;
- Py_ssize_t i, j, k, index;
-
- if (po->stopped)
- return NULL;
-
- if (result == NULL) {
- /* On the first pass, initialize result tuple using the indices */
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- po->result = result;
- for (i=0; i<r ; i++) {
- index = indices[i];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- } else {
- if (n == 0)
- goto empty;
-
- /* Copy the previous result tuple or re-use it if available */
- if (Py_REFCNT(result) > 1) {
- PyObject *old_result = result;
- result = PyTuple_New(r);
- if (result == NULL)
- goto empty;
- po->result = result;
- for (i=0; i<r ; i++) {
- elem = PyTuple_GET_ITEM(old_result, i);
- Py_INCREF(elem);
- PyTuple_SET_ITEM(result, i, elem);
- }
- Py_DECREF(old_result);
- }
- /* Now, we've got the only copy so we can update it in-place */
- assert(r == 0 || Py_REFCNT(result) == 1);
-
- /* Decrement rightmost cycle, moving leftward upon zero rollover */
- for (i=r-1 ; i>=0 ; i--) {
- cycles[i] -= 1;
- if (cycles[i] == 0) {
- /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */
- index = indices[i];
- for (j=i ; j<n-1 ; j++)
- indices[j] = indices[j+1];
- indices[n-1] = index;
- cycles[i] = n - i;
- } else {
- j = cycles[i];
- index = indices[i];
- indices[i] = indices[n-j];
- indices[n-j] = index;
-
- for (k=i; k<r ; k++) {
- /* start with i, the leftmost element that changed */
- /* yield tuple(pool[k] for k in indices[:r]) */
- index = indices[k];
- elem = PyTuple_GET_ITEM(pool, index);
- Py_INCREF(elem);
- oldelem = PyTuple_GET_ITEM(result, k);
- PyTuple_SET_ITEM(result, k, elem);
- Py_DECREF(oldelem);
- }
- break;
- }
- }
- /* If i is negative, then the cycles have all
- rolled-over and we're done. */
- if (i < 0)
- goto empty;
- }
- Py_INCREF(result);
- return result;
+ PyObject *elem;
+ PyObject *oldelem;
+ PyObject *pool = po->pool;
+ Py_ssize_t *indices = po->indices;
+ Py_ssize_t *cycles = po->cycles;
+ PyObject *result = po->result;
+ Py_ssize_t n = PyTuple_GET_SIZE(pool);
+ Py_ssize_t r = po->r;
+ Py_ssize_t i, j, k, index;
+
+ if (po->stopped)
+ return NULL;
+
+ if (result == NULL) {
+ /* On the first pass, initialize result tuple using the indices */
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ po->result = result;
+ for (i=0; i<r ; i++) {
+ index = indices[i];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ } else {
+ if (n == 0)
+ goto empty;
+
+ /* Copy the previous result tuple or re-use it if available */
+ if (Py_REFCNT(result) > 1) {
+ PyObject *old_result = result;
+ result = PyTuple_New(r);
+ if (result == NULL)
+ goto empty;
+ po->result = result;
+ for (i=0; i<r ; i++) {
+ elem = PyTuple_GET_ITEM(old_result, i);
+ Py_INCREF(elem);
+ PyTuple_SET_ITEM(result, i, elem);
+ }
+ Py_DECREF(old_result);
+ }
+ /* Now, we've got the only copy so we can update it in-place */
+ assert(r == 0 || Py_REFCNT(result) == 1);
+
+ /* Decrement rightmost cycle, moving leftward upon zero rollover */
+ for (i=r-1 ; i>=0 ; i--) {
+ cycles[i] -= 1;
+ if (cycles[i] == 0) {
+ /* rotatation: indices[i:] = indices[i+1:] + indices[i:i+1] */
+ index = indices[i];
+ for (j=i ; j<n-1 ; j++)
+ indices[j] = indices[j+1];
+ indices[n-1] = index;
+ cycles[i] = n - i;
+ } else {
+ j = cycles[i];
+ index = indices[i];
+ indices[i] = indices[n-j];
+ indices[n-j] = index;
+
+ for (k=i; k<r ; k++) {
+ /* start with i, the leftmost element that changed */
+ /* yield tuple(pool[k] for k in indices[:r]) */
+ index = indices[k];
+ elem = PyTuple_GET_ITEM(pool, index);
+ Py_INCREF(elem);
+ oldelem = PyTuple_GET_ITEM(result, k);
+ PyTuple_SET_ITEM(result, k, elem);
+ Py_DECREF(oldelem);
+ }
+ break;
+ }
+ }
+ /* If i is negative, then the cycles have all
+ rolled-over and we're done. */
+ if (i < 0)
+ goto empty;
+ }
+ Py_INCREF(result);
+ return result;
empty:
- po->stopped = 1;
- return NULL;
+ po->stopped = 1;
+ return NULL;
}
PyDoc_STRVAR(permutations_doc,
@@ -2715,47 +2715,47 @@ Return successive r-length permutations of elements in the iterable.\n\n\
permutations(range(3), 2) --> (0,1), (0,2), (1,0), (1,2), (2,0), (2,1)");
static PyTypeObject permutations_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.permutations", /* tp_name */
- sizeof(permutationsobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)permutations_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- permutations_doc, /* tp_doc */
- (traverseproc)permutations_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)permutations_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- permutations_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.permutations", /* tp_name */
+ sizeof(permutationsobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)permutations_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ permutations_doc, /* tp_doc */
+ (traverseproc)permutations_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)permutations_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ permutations_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -2763,15 +2763,15 @@ static PyTypeObject permutations_type = {
/* Equivalent to:
- def compress(data, selectors):
- "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
- return (d for d, s in izip(data, selectors) if s)
+ def compress(data, selectors):
+ "compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F"
+ return (d for d, s in izip(data, selectors) if s)
*/
typedef struct {
- PyObject_HEAD
- PyObject *data;
- PyObject *selectors;
+ PyObject_HEAD
+ PyObject *data;
+ PyObject *selectors;
} compressobject;
static PyTypeObject compress_type;
@@ -2779,86 +2779,86 @@ static PyTypeObject compress_type;
static PyObject *
compress_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *seq1, *seq2;
- PyObject *data=NULL, *selectors=NULL;
- compressobject *lz;
- static char *kwargs[] = {"data", "selectors", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2))
- return NULL;
-
- data = PyObject_GetIter(seq1);
- if (data == NULL)
- goto fail;
- selectors = PyObject_GetIter(seq2);
- if (selectors == NULL)
- goto fail;
-
- /* create compressobject structure */
- lz = (compressobject *)type->tp_alloc(type, 0);
- if (lz == NULL)
- goto fail;
- lz->data = data;
- lz->selectors = selectors;
- return (PyObject *)lz;
+ PyObject *seq1, *seq2;
+ PyObject *data=NULL, *selectors=NULL;
+ compressobject *lz;
+ static char *kwargs[] = {"data", "selectors", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OO:compress", kwargs, &seq1, &seq2))
+ return NULL;
+
+ data = PyObject_GetIter(seq1);
+ if (data == NULL)
+ goto fail;
+ selectors = PyObject_GetIter(seq2);
+ if (selectors == NULL)
+ goto fail;
+
+ /* create compressobject structure */
+ lz = (compressobject *)type->tp_alloc(type, 0);
+ if (lz == NULL)
+ goto fail;
+ lz->data = data;
+ lz->selectors = selectors;
+ return (PyObject *)lz;
fail:
- Py_XDECREF(data);
- Py_XDECREF(selectors);
- return NULL;
+ Py_XDECREF(data);
+ Py_XDECREF(selectors);
+ return NULL;
}
static void
compress_dealloc(compressobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->data);
- Py_XDECREF(lz->selectors);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->data);
+ Py_XDECREF(lz->selectors);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
compress_traverse(compressobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->data);
- Py_VISIT(lz->selectors);
- return 0;
+ Py_VISIT(lz->data);
+ Py_VISIT(lz->selectors);
+ return 0;
}
static PyObject *
compress_next(compressobject *lz)
{
- PyObject *data = lz->data, *selectors = lz->selectors;
- PyObject *datum, *selector;
- PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext;
- PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext;
- int ok;
-
- while (1) {
- /* Steps: get datum, get selector, evaluate selector.
- Order is important (to match the pure python version
- in terms of which input gets a chance to raise an
- exception first).
- */
-
- datum = datanext(data);
- if (datum == NULL)
- return NULL;
-
- selector = selectornext(selectors);
- if (selector == NULL) {
- Py_DECREF(datum);
- return NULL;
- }
-
- ok = PyObject_IsTrue(selector);
- Py_DECREF(selector);
- if (ok == 1)
- return datum;
- Py_DECREF(datum);
- if (ok == -1)
- return NULL;
- }
+ PyObject *data = lz->data, *selectors = lz->selectors;
+ PyObject *datum, *selector;
+ PyObject *(*datanext)(PyObject *) = *Py_TYPE(data)->tp_iternext;
+ PyObject *(*selectornext)(PyObject *) = *Py_TYPE(selectors)->tp_iternext;
+ int ok;
+
+ while (1) {
+ /* Steps: get datum, get selector, evaluate selector.
+ Order is important (to match the pure python version
+ in terms of which input gets a chance to raise an
+ exception first).
+ */
+
+ datum = datanext(data);
+ if (datum == NULL)
+ return NULL;
+
+ selector = selectornext(selectors);
+ if (selector == NULL) {
+ Py_DECREF(datum);
+ return NULL;
+ }
+
+ ok = PyObject_IsTrue(selector);
+ Py_DECREF(selector);
+ if (ok == 1)
+ return datum;
+ Py_DECREF(datum);
+ if (ok == -1)
+ return NULL;
+ }
}
PyDoc_STRVAR(compress_doc,
@@ -2869,56 +2869,56 @@ Forms a shorter iterator from selected data elements using the\n\
selectors to choose the data elements.");
static PyTypeObject compress_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.compress", /* tp_name */
- sizeof(compressobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)compress_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- compress_doc, /* tp_doc */
- (traverseproc)compress_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)compress_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- compress_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.compress", /* tp_name */
+ sizeof(compressobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)compress_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ compress_doc, /* tp_doc */
+ (traverseproc)compress_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)compress_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ compress_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* ifilter object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} ifilterobject;
static PyTypeObject ifilter_type;
@@ -2926,82 +2926,82 @@ static PyTypeObject ifilter_type;
static PyObject *
ifilter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- ifilterobject *lz;
-
- if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq))
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create ifilterobject structure */
- lz = (ifilterobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
-
- return (PyObject *)lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ ifilterobject *lz;
+
+ if (type == &ifilter_type && !_PyArg_NoKeywords("ifilter()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "ifilter", 2, 2, &func, &seq))
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create ifilterobject structure */
+ lz = (ifilterobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+
+ return (PyObject *)lz;
}
static void
ifilter_dealloc(ifilterobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
ifilter_traverse(ifilterobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
ifilter_next(ifilterobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
-
- if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
- ok = PyObject_IsTrue(item);
- } else {
- PyObject *good;
- good = PyObject_CallFunctionObjArgs(lz->func,
- item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- }
- if (ok)
- return item;
- Py_DECREF(item);
- }
+ PyObject *item;
+ PyObject *it = lz->it;
+ long ok;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+
+ if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
+ ok = PyObject_IsTrue(item);
+ } else {
+ PyObject *good;
+ good = PyObject_CallFunctionObjArgs(lz->func,
+ item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ }
+ if (ok)
+ return item;
+ Py_DECREF(item);
+ }
}
PyDoc_STRVAR(ifilter_doc,
@@ -3011,56 +3011,56 @@ Return those items of sequence for which function(item) is true.\n\
If function is None, return the items that are true.");
static PyTypeObject ifilter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.ifilter", /* tp_name */
- sizeof(ifilterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)ifilter_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- ifilter_doc, /* tp_doc */
- (traverseproc)ifilter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)ifilter_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- ifilter_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.ifilter", /* tp_name */
+ sizeof(ifilterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)ifilter_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ ifilter_doc, /* tp_doc */
+ (traverseproc)ifilter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)ifilter_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ ifilter_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* ifilterfalse object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *func;
- PyObject *it;
+ PyObject_HEAD
+ PyObject *func;
+ PyObject *it;
} ifilterfalseobject;
static PyTypeObject ifilterfalse_type;
@@ -3068,83 +3068,83 @@ static PyTypeObject ifilterfalse_type;
static PyObject *
ifilterfalse_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *func, *seq;
- PyObject *it;
- ifilterfalseobject *lz;
-
- if (type == &ifilterfalse_type &&
- !_PyArg_NoKeywords("ifilterfalse()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq))
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- return NULL;
-
- /* create ifilterfalseobject structure */
- lz = (ifilterfalseobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(it);
- return NULL;
- }
- Py_INCREF(func);
- lz->func = func;
- lz->it = it;
-
- return (PyObject *)lz;
+ PyObject *func, *seq;
+ PyObject *it;
+ ifilterfalseobject *lz;
+
+ if (type == &ifilterfalse_type &&
+ !_PyArg_NoKeywords("ifilterfalse()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "ifilterfalse", 2, 2, &func, &seq))
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ return NULL;
+
+ /* create ifilterfalseobject structure */
+ lz = (ifilterfalseobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ Py_INCREF(func);
+ lz->func = func;
+ lz->it = it;
+
+ return (PyObject *)lz;
}
static void
ifilterfalse_dealloc(ifilterfalseobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->func);
- Py_XDECREF(lz->it);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->func);
+ Py_XDECREF(lz->it);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
ifilterfalse_traverse(ifilterfalseobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->it);
- Py_VISIT(lz->func);
- return 0;
+ Py_VISIT(lz->it);
+ Py_VISIT(lz->func);
+ return 0;
}
static PyObject *
ifilterfalse_next(ifilterfalseobject *lz)
{
- PyObject *item;
- PyObject *it = lz->it;
- long ok;
- PyObject *(*iternext)(PyObject *);
-
- iternext = *Py_TYPE(it)->tp_iternext;
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- return NULL;
-
- if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
- ok = PyObject_IsTrue(item);
- } else {
- PyObject *good;
- good = PyObject_CallFunctionObjArgs(lz->func,
- item, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- return NULL;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- }
- if (!ok)
- return item;
- Py_DECREF(item);
- }
+ PyObject *item;
+ PyObject *it = lz->it;
+ long ok;
+ PyObject *(*iternext)(PyObject *);
+
+ iternext = *Py_TYPE(it)->tp_iternext;
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ return NULL;
+
+ if (lz->func == Py_None || lz->func == (PyObject *)&PyBool_Type) {
+ ok = PyObject_IsTrue(item);
+ } else {
+ PyObject *good;
+ good = PyObject_CallFunctionObjArgs(lz->func,
+ item, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ }
+ if (!ok)
+ return item;
+ Py_DECREF(item);
+ }
}
PyDoc_STRVAR(ifilterfalse_doc,
@@ -3154,74 +3154,74 @@ Return those items of sequence for which function(item) is false.\n\
If function is None, return the items that are false.");
static PyTypeObject ifilterfalse_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.ifilterfalse", /* tp_name */
- sizeof(ifilterfalseobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)ifilterfalse_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- ifilterfalse_doc, /* tp_doc */
- (traverseproc)ifilterfalse_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)ifilterfalse_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- ifilterfalse_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.ifilterfalse", /* tp_name */
+ sizeof(ifilterfalseobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)ifilterfalse_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ ifilterfalse_doc, /* tp_doc */
+ (traverseproc)ifilterfalse_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)ifilterfalse_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ ifilterfalse_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* count object ************************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t cnt;
- PyObject *long_cnt;
- PyObject *long_step;
+ PyObject_HEAD
+ Py_ssize_t cnt;
+ PyObject *long_cnt;
+ PyObject *long_step;
} countobject;
/* Counting logic and invariants:
fast_mode: when cnt an integer < PY_SSIZE_T_MAX and no step is specified.
- assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1));
- Advances with: cnt += 1
- When count hits Y_SSIZE_T_MAX, switch to slow_mode.
+ assert(cnt != PY_SSIZE_T_MAX && long_cnt == NULL && long_step==PyInt(1));
+ Advances with: cnt += 1
+ When count hits Y_SSIZE_T_MAX, switch to slow_mode.
slow_mode: when cnt == PY_SSIZE_T_MAX, step is not int(1), or cnt is a float.
- assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL);
- All counting is done with python objects (no overflows or underflows).
- Advances with: long_cnt += long_step
- Step may be zero -- effectively a slow version of repeat(cnt).
- Either long_cnt or long_step may be a float, Fraction, or Decimal.
+ assert(cnt == PY_SSIZE_T_MAX && long_cnt != NULL && long_step != NULL);
+ All counting is done with python objects (no overflows or underflows).
+ Advances with: long_cnt += long_step
+ Step may be zero -- effectively a slow version of repeat(cnt).
+ Either long_cnt or long_step may be a float, Fraction, or Decimal.
*/
static PyTypeObject count_type;
@@ -3229,221 +3229,221 @@ static PyTypeObject count_type;
static PyObject *
count_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- countobject *lz;
- int slow_mode = 0;
- Py_ssize_t cnt = 0;
- PyObject *long_cnt = NULL;
- PyObject *long_step = NULL;
- static char *kwlist[] = {"start", "step", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count",
- kwlist, &long_cnt, &long_step))
- return NULL;
-
- if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) ||
- (long_step != NULL && !PyNumber_Check(long_step))) {
- PyErr_SetString(PyExc_TypeError, "a number is required");
- return NULL;
- }
-
- if (long_cnt != NULL) {
- cnt = PyInt_AsSsize_t(long_cnt);
- if ((cnt == -1 && PyErr_Occurred()) || !PyInt_Check(long_cnt)) {
- PyErr_Clear();
- slow_mode = 1;
- }
- Py_INCREF(long_cnt);
- } else {
- cnt = 0;
- long_cnt = PyInt_FromLong(0);
- }
-
- /* If not specified, step defaults to 1 */
- if (long_step == NULL) {
- long_step = PyInt_FromLong(1);
- if (long_step == NULL) {
- Py_DECREF(long_cnt);
- return NULL;
- }
- } else
- Py_INCREF(long_step);
-
- assert(long_cnt != NULL && long_step != NULL);
-
- /* Fast mode only works when the step is 1 */
- if (!PyInt_Check(long_step) ||
- PyInt_AS_LONG(long_step) != 1) {
- slow_mode = 1;
- }
-
- if (slow_mode)
- cnt = PY_SSIZE_T_MAX;
- else
- Py_CLEAR(long_cnt);
-
- assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) ||
- (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode));
- assert(slow_mode ||
- (PyInt_Check(long_step) && PyInt_AS_LONG(long_step) == 1));
-
- /* create countobject structure */
- lz = (countobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_XDECREF(long_cnt);
- return NULL;
- }
- lz->cnt = cnt;
- lz->long_cnt = long_cnt;
- lz->long_step = long_step;
-
- return (PyObject *)lz;
+ countobject *lz;
+ int slow_mode = 0;
+ Py_ssize_t cnt = 0;
+ PyObject *long_cnt = NULL;
+ PyObject *long_step = NULL;
+ static char *kwlist[] = {"start", "step", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:count",
+ kwlist, &long_cnt, &long_step))
+ return NULL;
+
+ if ((long_cnt != NULL && !PyNumber_Check(long_cnt)) ||
+ (long_step != NULL && !PyNumber_Check(long_step))) {
+ PyErr_SetString(PyExc_TypeError, "a number is required");
+ return NULL;
+ }
+
+ if (long_cnt != NULL) {
+ cnt = PyInt_AsSsize_t(long_cnt);
+ if ((cnt == -1 && PyErr_Occurred()) || !PyInt_Check(long_cnt)) {
+ PyErr_Clear();
+ slow_mode = 1;
+ }
+ Py_INCREF(long_cnt);
+ } else {
+ cnt = 0;
+ long_cnt = PyInt_FromLong(0);
+ }
+
+ /* If not specified, step defaults to 1 */
+ if (long_step == NULL) {
+ long_step = PyInt_FromLong(1);
+ if (long_step == NULL) {
+ Py_DECREF(long_cnt);
+ return NULL;
+ }
+ } else
+ Py_INCREF(long_step);
+
+ assert(long_cnt != NULL && long_step != NULL);
+
+ /* Fast mode only works when the step is 1 */
+ if (!PyInt_Check(long_step) ||
+ PyInt_AS_LONG(long_step) != 1) {
+ slow_mode = 1;
+ }
+
+ if (slow_mode)
+ cnt = PY_SSIZE_T_MAX;
+ else
+ Py_CLEAR(long_cnt);
+
+ assert((cnt != PY_SSIZE_T_MAX && long_cnt == NULL && !slow_mode) ||
+ (cnt == PY_SSIZE_T_MAX && long_cnt != NULL && slow_mode));
+ assert(slow_mode ||
+ (PyInt_Check(long_step) && PyInt_AS_LONG(long_step) == 1));
+
+ /* create countobject structure */
+ lz = (countobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_XDECREF(long_cnt);
+ return NULL;
+ }
+ lz->cnt = cnt;
+ lz->long_cnt = long_cnt;
+ lz->long_step = long_step;
+
+ return (PyObject *)lz;
}
static void
count_dealloc(countobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->long_cnt);
- Py_XDECREF(lz->long_step);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->long_cnt);
+ Py_XDECREF(lz->long_step);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
count_traverse(countobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->long_cnt);
- Py_VISIT(lz->long_step);
- return 0;
+ Py_VISIT(lz->long_cnt);
+ Py_VISIT(lz->long_step);
+ return 0;
}
static PyObject *
count_nextlong(countobject *lz)
{
- PyObject *long_cnt;
- PyObject *stepped_up;
-
- long_cnt = lz->long_cnt;
- if (long_cnt == NULL) {
- /* Switch to slow_mode */
- long_cnt = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
- if (long_cnt == NULL)
- return NULL;
- }
- assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL);
-
- stepped_up = PyNumber_Add(long_cnt, lz->long_step);
- if (stepped_up == NULL)
- return NULL;
- lz->long_cnt = stepped_up;
- return long_cnt;
+ PyObject *long_cnt;
+ PyObject *stepped_up;
+
+ long_cnt = lz->long_cnt;
+ if (long_cnt == NULL) {
+ /* Switch to slow_mode */
+ long_cnt = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
+ if (long_cnt == NULL)
+ return NULL;
+ }
+ assert(lz->cnt == PY_SSIZE_T_MAX && long_cnt != NULL);
+
+ stepped_up = PyNumber_Add(long_cnt, lz->long_step);
+ if (stepped_up == NULL)
+ return NULL;
+ lz->long_cnt = stepped_up;
+ return long_cnt;
}
static PyObject *
count_next(countobject *lz)
{
- if (lz->cnt == PY_SSIZE_T_MAX)
- return count_nextlong(lz);
- return PyInt_FromSsize_t(lz->cnt++);
+ if (lz->cnt == PY_SSIZE_T_MAX)
+ return count_nextlong(lz);
+ return PyInt_FromSsize_t(lz->cnt++);
}
static PyObject *
count_repr(countobject *lz)
{
- PyObject *cnt_repr, *step_repr = NULL;
- PyObject *result = NULL;
+ PyObject *cnt_repr, *step_repr = NULL;
+ PyObject *result = NULL;
if (lz->cnt != PY_SSIZE_T_MAX)
- return PyString_FromFormat("count(%zd)", lz->cnt);
-
- cnt_repr = PyObject_Repr(lz->long_cnt);
- if (cnt_repr == NULL)
- return NULL;
-
- if (PyInt_Check(lz->long_step) && PyInt_AS_LONG(lz->long_step) == 1) {
- /* Don't display step when it is an integer equal to 1 */
- result = PyString_FromFormat("count(%s)",
- PyString_AS_STRING(cnt_repr));
- } else {
- step_repr = PyObject_Repr(lz->long_step);
- if (step_repr != NULL)
- result = PyString_FromFormat("count(%s, %s)",
- PyString_AS_STRING(cnt_repr),
- PyString_AS_STRING(step_repr));
- }
- Py_DECREF(cnt_repr);
- Py_XDECREF(step_repr);
- return result;
+ return PyString_FromFormat("count(%zd)", lz->cnt);
+
+ cnt_repr = PyObject_Repr(lz->long_cnt);
+ if (cnt_repr == NULL)
+ return NULL;
+
+ if (PyInt_Check(lz->long_step) && PyInt_AS_LONG(lz->long_step) == 1) {
+ /* Don't display step when it is an integer equal to 1 */
+ result = PyString_FromFormat("count(%s)",
+ PyString_AS_STRING(cnt_repr));
+ } else {
+ step_repr = PyObject_Repr(lz->long_step);
+ if (step_repr != NULL)
+ result = PyString_FromFormat("count(%s, %s)",
+ PyString_AS_STRING(cnt_repr),
+ PyString_AS_STRING(step_repr));
+ }
+ Py_DECREF(cnt_repr);
+ Py_XDECREF(step_repr);
+ return result;
}
static PyObject *
count_reduce(countobject *lz)
{
- if (lz->cnt == PY_SSIZE_T_MAX)
- return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step);
- return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt);
+ if (lz->cnt == PY_SSIZE_T_MAX)
+ return Py_BuildValue("O(OO)", Py_TYPE(lz), lz->long_cnt, lz->long_step);
+ return Py_BuildValue("O(n)", Py_TYPE(lz), lz->cnt);
}
PyDoc_STRVAR(count_reduce_doc, "Return state information for pickling.");
static PyMethodDef count_methods[] = {
- {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS,
- count_reduce_doc},
- {NULL, NULL} /* sentinel */
+ {"__reduce__", (PyCFunction)count_reduce, METH_NOARGS,
+ count_reduce_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(count_doc,
- "count(start=0, step=1]) --> count object\n\
+ "count(start=0, step=1]) --> count object\n\
\n\
Return a count object whose .next() method returns consecutive values.\n\
Equivalent to:\n\n\
def count(firstval=0, step=1):\n\
- x = firstval\n\
- while 1:\n\
- yield x\n\
- x += step\n");
+ x = firstval\n\
+ while 1:\n\
+ yield x\n\
+ x += step\n");
static PyTypeObject count_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.count", /* tp_name */
- sizeof(countobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)count_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)count_repr, /* 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_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- count_doc, /* tp_doc */
- (traverseproc)count_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)count_next, /* tp_iternext */
- count_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 */
- count_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.count", /* tp_name */
+ sizeof(countobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)count_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)count_repr, /* 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_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ count_doc, /* tp_doc */
+ (traverseproc)count_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)count_next, /* tp_iternext */
+ count_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 */
+ count_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -3452,10 +3452,10 @@ static PyTypeObject count_type = {
#include "Python.h"
typedef struct {
- PyObject_HEAD
- Py_ssize_t tuplesize;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
+ PyObject_HEAD
+ Py_ssize_t tuplesize;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
} izipobject;
static PyTypeObject izip_type;
@@ -3463,118 +3463,118 @@ static PyTypeObject izip_type;
static PyObject *
izip_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- izipobject *lz;
- Py_ssize_t i;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
- Py_ssize_t tuplesize = PySequence_Length(args);
-
- if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds))
- return NULL;
-
- /* args must be a tuple */
- assert(PyTuple_Check(args));
-
- /* obtain iterators */
- ittuple = PyTuple_New(tuplesize);
- if (ittuple == NULL)
- return NULL;
- for (i=0; i < tuplesize; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- PyObject *it = PyObject_GetIter(item);
- if (it == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_Format(PyExc_TypeError,
- "izip argument #%zd must support iteration",
- i+1);
- Py_DECREF(ittuple);
- return NULL;
- }
- PyTuple_SET_ITEM(ittuple, i, it);
- }
-
- /* create a result holder */
- result = PyTuple_New(tuplesize);
- if (result == NULL) {
- Py_DECREF(ittuple);
- return NULL;
- }
- for (i=0 ; i < tuplesize ; i++) {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(result, i, Py_None);
- }
-
- /* create izipobject structure */
- lz = (izipobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(ittuple);
- Py_DECREF(result);
- return NULL;
- }
- lz->ittuple = ittuple;
- lz->tuplesize = tuplesize;
- lz->result = result;
-
- return (PyObject *)lz;
+ izipobject *lz;
+ Py_ssize_t i;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ Py_ssize_t tuplesize = PySequence_Length(args);
+
+ if (type == &izip_type && !_PyArg_NoKeywords("izip()", kwds))
+ return NULL;
+
+ /* args must be a tuple */
+ assert(PyTuple_Check(args));
+
+ /* obtain iterators */
+ ittuple = PyTuple_New(tuplesize);
+ if (ittuple == NULL)
+ return NULL;
+ for (i=0; i < tuplesize; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *it = PyObject_GetIter(item);
+ if (it == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_Format(PyExc_TypeError,
+ "izip argument #%zd must support iteration",
+ i+1);
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(ittuple, i, it);
+ }
+
+ /* create a result holder */
+ result = PyTuple_New(tuplesize);
+ if (result == NULL) {
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ for (i=0 ; i < tuplesize ; i++) {
+ Py_INCREF(Py_None);
+ PyTuple_SET_ITEM(result, i, Py_None);
+ }
+
+ /* create izipobject structure */
+ lz = (izipobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(ittuple);
+ Py_DECREF(result);
+ return NULL;
+ }
+ lz->ittuple = ittuple;
+ lz->tuplesize = tuplesize;
+ lz->result = result;
+
+ return (PyObject *)lz;
}
static void
izip_dealloc(izipobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->ittuple);
- Py_XDECREF(lz->result);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->ittuple);
+ Py_XDECREF(lz->result);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
izip_traverse(izipobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->ittuple);
- Py_VISIT(lz->result);
- return 0;
+ Py_VISIT(lz->ittuple);
+ Py_VISIT(lz->result);
+ return 0;
}
static PyObject *
izip_next(izipobject *lz)
{
- Py_ssize_t i;
- Py_ssize_t tuplesize = lz->tuplesize;
- PyObject *result = lz->result;
- PyObject *it;
- PyObject *item;
- PyObject *olditem;
-
- if (tuplesize == 0)
- return NULL;
- if (Py_REFCNT(result) == 1) {
- Py_INCREF(result);
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- olditem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, item);
- Py_DECREF(olditem);
- }
- } else {
- result = PyTuple_New(tuplesize);
- if (result == NULL)
- return NULL;
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- item = (*Py_TYPE(it)->tp_iternext)(it);
- if (item == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, item);
- }
- }
- return result;
+ Py_ssize_t i;
+ Py_ssize_t tuplesize = lz->tuplesize;
+ PyObject *result = lz->result;
+ PyObject *it;
+ PyObject *item;
+ PyObject *olditem;
+
+ if (tuplesize == 0)
+ return NULL;
+ if (Py_REFCNT(result) == 1) {
+ Py_INCREF(result);
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (item == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ olditem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, item);
+ Py_DECREF(olditem);
+ }
+ } else {
+ result = PyTuple_New(tuplesize);
+ if (result == NULL)
+ return NULL;
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (item == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, item);
+ }
+ }
+ return result;
}
PyDoc_STRVAR(izip_doc,
@@ -3588,56 +3588,56 @@ function but consumes less memory by returning an iterator instead of\n\
a list.");
static PyTypeObject izip_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.izip", /* tp_name */
- sizeof(izipobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)izip_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- izip_doc, /* tp_doc */
- (traverseproc)izip_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)izip_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- izip_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.izip", /* tp_name */
+ sizeof(izipobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)izip_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ izip_doc, /* tp_doc */
+ (traverseproc)izip_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)izip_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ izip_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* repeat object ************************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *element;
- Py_ssize_t cnt;
+ PyObject_HEAD
+ PyObject *element;
+ Py_ssize_t cnt;
} repeatobject;
static PyTypeObject repeat_type;
@@ -3645,87 +3645,87 @@ static PyTypeObject repeat_type;
static PyObject *
repeat_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- repeatobject *ro;
- PyObject *element;
- Py_ssize_t cnt = -1;
- static char *kwargs[] = {"object", "times", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs,
- &element, &cnt))
- return NULL;
-
- if (PyTuple_Size(args) == 2 && cnt < 0)
- cnt = 0;
-
- ro = (repeatobject *)type->tp_alloc(type, 0);
- if (ro == NULL)
- return NULL;
- Py_INCREF(element);
- ro->element = element;
- ro->cnt = cnt;
- return (PyObject *)ro;
+ repeatobject *ro;
+ PyObject *element;
+ Py_ssize_t cnt = -1;
+ static char *kwargs[] = {"object", "times", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|n:repeat", kwargs,
+ &element, &cnt))
+ return NULL;
+
+ if (PyTuple_Size(args) == 2 && cnt < 0)
+ cnt = 0;
+
+ ro = (repeatobject *)type->tp_alloc(type, 0);
+ if (ro == NULL)
+ return NULL;
+ Py_INCREF(element);
+ ro->element = element;
+ ro->cnt = cnt;
+ return (PyObject *)ro;
}
static void
repeat_dealloc(repeatobject *ro)
{
- PyObject_GC_UnTrack(ro);
- Py_XDECREF(ro->element);
- Py_TYPE(ro)->tp_free(ro);
+ PyObject_GC_UnTrack(ro);
+ Py_XDECREF(ro->element);
+ Py_TYPE(ro)->tp_free(ro);
}
static int
repeat_traverse(repeatobject *ro, visitproc visit, void *arg)
{
- Py_VISIT(ro->element);
- return 0;
+ Py_VISIT(ro->element);
+ return 0;
}
static PyObject *
repeat_next(repeatobject *ro)
{
- if (ro->cnt == 0)
- return NULL;
- if (ro->cnt > 0)
- ro->cnt--;
- Py_INCREF(ro->element);
- return ro->element;
+ if (ro->cnt == 0)
+ return NULL;
+ if (ro->cnt > 0)
+ ro->cnt--;
+ Py_INCREF(ro->element);
+ return ro->element;
}
static PyObject *
repeat_repr(repeatobject *ro)
{
- PyObject *result, *objrepr;
-
- objrepr = PyObject_Repr(ro->element);
- if (objrepr == NULL)
- return NULL;
-
- if (ro->cnt == -1)
- result = PyString_FromFormat("repeat(%s)",
- PyString_AS_STRING(objrepr));
- else
- result = PyString_FromFormat("repeat(%s, %zd)",
- PyString_AS_STRING(objrepr), ro->cnt);
- Py_DECREF(objrepr);
- return result;
-}
+ PyObject *result, *objrepr;
+
+ objrepr = PyObject_Repr(ro->element);
+ if (objrepr == NULL)
+ return NULL;
+
+ if (ro->cnt == -1)
+ result = PyString_FromFormat("repeat(%s)",
+ PyString_AS_STRING(objrepr));
+ else
+ result = PyString_FromFormat("repeat(%s, %zd)",
+ PyString_AS_STRING(objrepr), ro->cnt);
+ Py_DECREF(objrepr);
+ return result;
+}
static PyObject *
repeat_len(repeatobject *ro)
{
- if (ro->cnt == -1) {
- PyErr_SetString(PyExc_TypeError, "len() of unsized object");
- return NULL;
- }
- return PyInt_FromSize_t(ro->cnt);
+ if (ro->cnt == -1) {
+ PyErr_SetString(PyExc_TypeError, "len() of unsized object");
+ return NULL;
+ }
+ return PyInt_FromSize_t(ro->cnt);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef repeat_methods[] = {
- {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)repeat_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(repeat_doc,
@@ -3734,47 +3734,47 @@ for the specified number of times. If not specified, returns the object\n\
endlessly.");
static PyTypeObject repeat_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.repeat", /* tp_name */
- sizeof(repeatobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)repeat_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)repeat_repr, /* 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_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- repeat_doc, /* tp_doc */
- (traverseproc)repeat_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)repeat_next, /* tp_iternext */
- repeat_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 */
- repeat_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.repeat", /* tp_name */
+ sizeof(repeatobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)repeat_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)repeat_repr, /* 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_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ repeat_doc, /* tp_doc */
+ (traverseproc)repeat_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)repeat_next, /* tp_iternext */
+ repeat_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 */
+ repeat_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* iziplongest object ************************************************************/
@@ -3782,12 +3782,12 @@ static PyTypeObject repeat_type = {
#include "Python.h"
typedef struct {
- PyObject_HEAD
- Py_ssize_t tuplesize;
- Py_ssize_t numactive;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
- PyObject *fillvalue;
+ PyObject_HEAD
+ Py_ssize_t tuplesize;
+ Py_ssize_t numactive;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ PyObject *fillvalue;
} iziplongestobject;
static PyTypeObject iziplongest_type;
@@ -3795,159 +3795,159 @@ static PyTypeObject iziplongest_type;
static PyObject *
izip_longest_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- iziplongestobject *lz;
- Py_ssize_t i;
- PyObject *ittuple; /* tuple of iterators */
- PyObject *result;
- PyObject *fillvalue = Py_None;
- Py_ssize_t tuplesize = PySequence_Length(args);
-
- if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) {
- fillvalue = PyDict_GetItemString(kwds, "fillvalue");
- if (fillvalue == NULL || PyDict_Size(kwds) > 1) {
- PyErr_SetString(PyExc_TypeError,
- "izip_longest() got an unexpected keyword argument");
- return NULL;
- }
+ iziplongestobject *lz;
+ Py_ssize_t i;
+ PyObject *ittuple; /* tuple of iterators */
+ PyObject *result;
+ PyObject *fillvalue = Py_None;
+ Py_ssize_t tuplesize = PySequence_Length(args);
+
+ if (kwds != NULL && PyDict_CheckExact(kwds) && PyDict_Size(kwds) > 0) {
+ fillvalue = PyDict_GetItemString(kwds, "fillvalue");
+ if (fillvalue == NULL || PyDict_Size(kwds) > 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "izip_longest() got an unexpected keyword argument");
+ return NULL;
}
-
- /* args must be a tuple */
- assert(PyTuple_Check(args));
-
- /* obtain iterators */
- ittuple = PyTuple_New(tuplesize);
- if (ittuple == NULL)
- return NULL;
- for (i=0; i < tuplesize; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- PyObject *it = PyObject_GetIter(item);
- if (it == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_Format(PyExc_TypeError,
- "izip_longest argument #%zd must support iteration",
- i+1);
- Py_DECREF(ittuple);
- return NULL;
- }
- PyTuple_SET_ITEM(ittuple, i, it);
- }
-
- /* create a result holder */
- result = PyTuple_New(tuplesize);
- if (result == NULL) {
- Py_DECREF(ittuple);
- return NULL;
- }
- for (i=0 ; i < tuplesize ; i++) {
- Py_INCREF(Py_None);
- PyTuple_SET_ITEM(result, i, Py_None);
- }
-
- /* create iziplongestobject structure */
- lz = (iziplongestobject *)type->tp_alloc(type, 0);
- if (lz == NULL) {
- Py_DECREF(ittuple);
- Py_DECREF(result);
- return NULL;
- }
- lz->ittuple = ittuple;
- lz->tuplesize = tuplesize;
- lz->numactive = tuplesize;
- lz->result = result;
- Py_INCREF(fillvalue);
- lz->fillvalue = fillvalue;
- return (PyObject *)lz;
+ }
+
+ /* args must be a tuple */
+ assert(PyTuple_Check(args));
+
+ /* obtain iterators */
+ ittuple = PyTuple_New(tuplesize);
+ if (ittuple == NULL)
+ return NULL;
+ for (i=0; i < tuplesize; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *it = PyObject_GetIter(item);
+ if (it == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_Format(PyExc_TypeError,
+ "izip_longest argument #%zd must support iteration",
+ i+1);
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(ittuple, i, it);
+ }
+
+ /* create a result holder */
+ result = PyTuple_New(tuplesize);
+ if (result == NULL) {
+ Py_DECREF(ittuple);
+ return NULL;
+ }
+ for (i=0 ; i < tuplesize ; i++) {
+ Py_INCREF(Py_None);
+ PyTuple_SET_ITEM(result, i, Py_None);
+ }
+
+ /* create iziplongestobject structure */
+ lz = (iziplongestobject *)type->tp_alloc(type, 0);
+ if (lz == NULL) {
+ Py_DECREF(ittuple);
+ Py_DECREF(result);
+ return NULL;
+ }
+ lz->ittuple = ittuple;
+ lz->tuplesize = tuplesize;
+ lz->numactive = tuplesize;
+ lz->result = result;
+ Py_INCREF(fillvalue);
+ lz->fillvalue = fillvalue;
+ return (PyObject *)lz;
}
static void
izip_longest_dealloc(iziplongestobject *lz)
{
- PyObject_GC_UnTrack(lz);
- Py_XDECREF(lz->ittuple);
- Py_XDECREF(lz->result);
- Py_XDECREF(lz->fillvalue);
- Py_TYPE(lz)->tp_free(lz);
+ PyObject_GC_UnTrack(lz);
+ Py_XDECREF(lz->ittuple);
+ Py_XDECREF(lz->result);
+ Py_XDECREF(lz->fillvalue);
+ Py_TYPE(lz)->tp_free(lz);
}
static int
izip_longest_traverse(iziplongestobject *lz, visitproc visit, void *arg)
{
- Py_VISIT(lz->ittuple);
- Py_VISIT(lz->result);
- Py_VISIT(lz->fillvalue);
- return 0;
+ Py_VISIT(lz->ittuple);
+ Py_VISIT(lz->result);
+ Py_VISIT(lz->fillvalue);
+ return 0;
}
static PyObject *
izip_longest_next(iziplongestobject *lz)
{
- Py_ssize_t i;
- Py_ssize_t tuplesize = lz->tuplesize;
- PyObject *result = lz->result;
- PyObject *it;
- PyObject *item;
- PyObject *olditem;
-
- if (tuplesize == 0)
- return NULL;
- if (lz->numactive == 0)
- return NULL;
- if (Py_REFCNT(result) == 1) {
- Py_INCREF(result);
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- if (it == NULL) {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- } else {
- item = PyIter_Next(it);
- if (item == NULL) {
- lz->numactive -= 1;
- if (lz->numactive == 0 || PyErr_Occurred()) {
- lz->numactive = 0;
- Py_DECREF(result);
- return NULL;
- } else {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- PyTuple_SET_ITEM(lz->ittuple, i, NULL);
- Py_DECREF(it);
- }
- }
- }
- olditem = PyTuple_GET_ITEM(result, i);
- PyTuple_SET_ITEM(result, i, item);
- Py_DECREF(olditem);
+ Py_ssize_t i;
+ Py_ssize_t tuplesize = lz->tuplesize;
+ PyObject *result = lz->result;
+ PyObject *it;
+ PyObject *item;
+ PyObject *olditem;
+
+ if (tuplesize == 0)
+ return NULL;
+ if (lz->numactive == 0)
+ return NULL;
+ if (Py_REFCNT(result) == 1) {
+ Py_INCREF(result);
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ if (it == NULL) {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ } else {
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ lz->numactive -= 1;
+ if (lz->numactive == 0 || PyErr_Occurred()) {
+ lz->numactive = 0;
+ Py_DECREF(result);
+ return NULL;
+ } else {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ PyTuple_SET_ITEM(lz->ittuple, i, NULL);
+ Py_DECREF(it);
+ }
}
- } else {
- result = PyTuple_New(tuplesize);
- if (result == NULL)
+ }
+ olditem = PyTuple_GET_ITEM(result, i);
+ PyTuple_SET_ITEM(result, i, item);
+ Py_DECREF(olditem);
+ }
+ } else {
+ result = PyTuple_New(tuplesize);
+ if (result == NULL)
+ return NULL;
+ for (i=0 ; i < tuplesize ; i++) {
+ it = PyTuple_GET_ITEM(lz->ittuple, i);
+ if (it == NULL) {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ } else {
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ lz->numactive -= 1;
+ if (lz->numactive == 0 || PyErr_Occurred()) {
+ lz->numactive = 0;
+ Py_DECREF(result);
return NULL;
- for (i=0 ; i < tuplesize ; i++) {
- it = PyTuple_GET_ITEM(lz->ittuple, i);
- if (it == NULL) {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- } else {
- item = PyIter_Next(it);
- if (item == NULL) {
- lz->numactive -= 1;
- if (lz->numactive == 0 || PyErr_Occurred()) {
- lz->numactive = 0;
- Py_DECREF(result);
- return NULL;
- } else {
- Py_INCREF(lz->fillvalue);
- item = lz->fillvalue;
- PyTuple_SET_ITEM(lz->ittuple, i, NULL);
- Py_DECREF(it);
- }
- }
- }
- PyTuple_SET_ITEM(result, i, item);
+ } else {
+ Py_INCREF(lz->fillvalue);
+ item = lz->fillvalue;
+ PyTuple_SET_ITEM(lz->ittuple, i, NULL);
+ Py_DECREF(it);
+ }
}
+ }
+ PyTuple_SET_ITEM(result, i, item);
}
- return result;
+ }
+ return result;
}
PyDoc_STRVAR(izip_longest_doc,
@@ -3962,47 +3962,47 @@ defaults to None or can be specified by a keyword argument.\n\
");
static PyTypeObject iziplongest_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "itertools.izip_longest", /* tp_name */
- sizeof(iziplongestobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)izip_longest_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- izip_longest_doc, /* tp_doc */
- (traverseproc)izip_longest_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)izip_longest_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- izip_longest_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "itertools.izip_longest", /* tp_name */
+ sizeof(iziplongestobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)izip_longest_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ izip_longest_doc, /* tp_doc */
+ (traverseproc)izip_longest_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)izip_longest_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ izip_longest_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* module level code ********************************************************/
@@ -4040,57 +4040,57 @@ combinations_with_replacement(p, r)\n\
static PyMethodDef module_methods[] = {
- {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc},
- {NULL, NULL} /* sentinel */
+ {"tee", (PyCFunction)tee, METH_VARARGS, tee_doc},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
inititertools(void)
{
- int i;
- PyObject *m;
- char *name;
- PyTypeObject *typelist[] = {
- &combinations_type,
- &cwr_type,
- &cycle_type,
- &dropwhile_type,
- &takewhile_type,
- &islice_type,
- &starmap_type,
- &imap_type,
- &chain_type,
- &compress_type,
- &ifilter_type,
- &ifilterfalse_type,
- &count_type,
- &izip_type,
- &iziplongest_type,
- &permutations_type,
- &product_type,
- &repeat_type,
- &groupby_type,
- NULL
- };
-
- Py_TYPE(&teedataobject_type) = &PyType_Type;
- m = Py_InitModule3("itertools", 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]);
- }
-
- if (PyType_Ready(&teedataobject_type) < 0)
- return;
- if (PyType_Ready(&tee_type) < 0)
- return;
- if (PyType_Ready(&_grouper_type) < 0)
- return;
+ int i;
+ PyObject *m;
+ char *name;
+ PyTypeObject *typelist[] = {
+ &combinations_type,
+ &cwr_type,
+ &cycle_type,
+ &dropwhile_type,
+ &takewhile_type,
+ &islice_type,
+ &starmap_type,
+ &imap_type,
+ &chain_type,
+ &compress_type,
+ &ifilter_type,
+ &ifilterfalse_type,
+ &count_type,
+ &izip_type,
+ &iziplongest_type,
+ &permutations_type,
+ &product_type,
+ &repeat_type,
+ &groupby_type,
+ NULL
+ };
+
+ Py_TYPE(&teedataobject_type) = &PyType_Type;
+ m = Py_InitModule3("itertools", 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]);
+ }
+
+ if (PyType_Ready(&teedataobject_type) < 0)
+ return;
+ if (PyType_Ready(&tee_type) < 0)
+ return;
+ if (PyType_Ready(&_grouper_type) < 0)
+ return;
}
diff --git a/Modules/linuxaudiodev.c b/Modules/linuxaudiodev.c
index 80077c6..7fe20ae 100644
--- a/Modules/linuxaudiodev.c
+++ b/Modules/linuxaudiodev.c
@@ -1,14 +1,14 @@
-/* Hey Emacs, this is -*-C-*-
+/* Hey Emacs, this is -*-C-*-
******************************************************************************
* linuxaudiodev.c -- Linux audio device for python.
- *
+ *
* Author : Peter Bosch
* Created On : Thu Mar 2 21:10:33 2000
* Status : Unknown, Use with caution!
- *
+ *
* Unless other notices are present in any part of this file
- * explicitly claiming copyrights for other people and/or
- * organizations, the contents of this file is fully copyright
+ * explicitly claiming copyrights for other people and/or
+ * organizations, the contents of this file is fully copyright
* (C) 2000 Peter Bosch, all rights reserved.
******************************************************************************
*/
@@ -43,11 +43,11 @@ typedef unsigned long uint32_t;
typedef struct {
PyObject_HEAD
- int x_fd; /* The open file */
+ int x_fd; /* The open file */
int x_mode; /* file mode */
- int x_icount; /* Input count */
- int x_ocount; /* Output count */
- uint32_t x_afmts; /* Audio formats supported by hardware*/
+ int x_icount; /* Input count */
+ int x_ocount; /* Output count */
+ uint32_t x_afmts; /* Audio formats supported by hardware*/
} lad_t;
/* XXX several format defined in soundcard.h are not supported,
@@ -55,19 +55,19 @@ typedef struct {
*/
static struct {
- int a_bps;
- uint32_t a_fmt;
+ int a_bps;
+ uint32_t a_fmt;
char *a_name;
} audio_types[] = {
- { 8, AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
- { 8, AFMT_A_LAW, "logarithmic A-law 8-bit audio" },
- { 8, AFMT_U8, "linear unsigned 8-bit audio" },
- { 8, AFMT_S8, "linear signed 8-bit audio" },
- { 16, AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
- { 16, AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
- { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
- { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
- { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
+ { 8, AFMT_MU_LAW, "logarithmic mu-law 8-bit audio" },
+ { 8, AFMT_A_LAW, "logarithmic A-law 8-bit audio" },
+ { 8, AFMT_U8, "linear unsigned 8-bit audio" },
+ { 8, AFMT_S8, "linear signed 8-bit audio" },
+ { 16, AFMT_U16_BE, "linear unsigned 16-bit big-endian audio" },
+ { 16, AFMT_U16_LE, "linear unsigned 16-bit little-endian audio" },
+ { 16, AFMT_S16_BE, "linear signed 16-bit big-endian audio" },
+ { 16, AFMT_S16_LE, "linear signed 16-bit little-endian audio" },
+ { 16, AFMT_S16_NE, "linear signed 16-bit native-endian audio" },
};
static int n_audio_types = sizeof(audio_types) / sizeof(audio_types[0]);
@@ -108,7 +108,7 @@ newladobject(PyObject *arg)
/* Open the correct device. The base device name comes from the
* AUDIODEV environment variable first, then /dev/dsp. The
* control device tacks "ctl" onto the base device name.
- *
+ *
* Note that the only difference between /dev/audio and /dev/dsp
* is that the former uses logarithmic mu-law encoding and the
* latter uses 8-bit unsigned encoding.
@@ -149,7 +149,7 @@ lad_dealloc(lad_t *xp)
{
/* if already closed, don't reclose it */
if (xp->x_fd != -1)
- close(xp->x_fd);
+ close(xp->x_fd);
PyObject_Del(xp);
}
@@ -159,7 +159,7 @@ lad_read(lad_t *self, PyObject *args)
int size, count;
char *cp;
PyObject *rv;
-
+
if (!PyArg_ParseTuple(args, "i:read", &size))
return NULL;
rv = PyString_FromStringAndSize(NULL, size);
@@ -184,36 +184,36 @@ lad_write(lad_t *self, PyObject *args)
fd_set write_set_fds;
struct timeval tv;
int select_retval;
-
- if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
- return NULL;
+
+ if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
+ return NULL;
/* use select to wait for audio device to be available */
FD_ZERO(&write_set_fds);
FD_SET(self->x_fd, &write_set_fds);
tv.tv_sec = 4; /* timeout values */
- tv.tv_usec = 0;
+ tv.tv_usec = 0;
while (size > 0) {
select_retval = select(self->x_fd+1, NULL, &write_set_fds, NULL, &tv);
tv.tv_sec = 1; tv.tv_usec = 0; /* willing to wait this long next time*/
if (select_retval) {
if ((rv = write(self->x_fd, cp, size)) == -1) {
- if (errno != EAGAIN) {
- PyErr_SetFromErrno(LinuxAudioError);
- return NULL;
- } else {
- errno = 0; /* EAGAIN: buffer is full, try again */
- }
+ if (errno != EAGAIN) {
+ PyErr_SetFromErrno(LinuxAudioError);
+ return NULL;
+ } else {
+ errno = 0; /* EAGAIN: buffer is full, try again */
+ }
} else {
- self->x_ocount += rv;
- size -= rv;
- cp += rv;
- }
+ self->x_ocount += rv;
+ size -= rv;
+ cp += rv;
+ }
} else {
- /* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
- PyErr_SetFromErrno(LinuxAudioError);
- return NULL;
+ /* printf("Not able to write to linux audio device within %ld seconds\n", tv.tv_sec); */
+ PyErr_SetFromErrno(LinuxAudioError);
+ return NULL;
}
}
Py_INCREF(Py_None);
@@ -244,47 +244,47 @@ lad_setparameters(lad_t *self, PyObject *args)
if (!PyArg_ParseTuple(args, "iiii|i:setparameters",
&rate, &ssize, &nchannels, &fmt, &emulate))
return NULL;
-
+
if (rate < 0) {
- PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
- rate);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "expected rate >= 0, not %d",
+ rate);
+ return NULL;
}
if (ssize < 0) {
- PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
- ssize);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "expected sample size >= 0, not %d",
+ ssize);
+ return NULL;
}
if (nchannels != 1 && nchannels != 2) {
- PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
- nchannels);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "nchannels must be 1 or 2, not %d",
+ nchannels);
+ return NULL;
}
for (n = 0; n < n_audio_types; n++)
if (fmt == audio_types[n].a_fmt)
break;
if (n == n_audio_types) {
- PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "unknown audio encoding: %d", fmt);
+ return NULL;
}
if (audio_types[n].a_bps != ssize) {
- PyErr_Format(PyExc_ValueError,
- "for %s, expected sample size %d, not %d",
- audio_types[n].a_name, audio_types[n].a_bps, ssize);
- return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "for %s, expected sample size %d, not %d",
+ audio_types[n].a_name, audio_types[n].a_bps, ssize);
+ return NULL;
}
if (emulate == 0) {
- if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
- PyErr_Format(PyExc_ValueError,
- "%s format not supported by device",
- audio_types[n].a_name);
- return NULL;
- }
+ if ((self->x_afmts & audio_types[n].a_fmt) == 0) {
+ PyErr_Format(PyExc_ValueError,
+ "%s format not supported by device",
+ audio_types[n].a_name);
+ return NULL;
+ }
}
- if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT,
- &audio_types[n].a_fmt) == -1) {
+ if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT,
+ &audio_types[n].a_fmt) == -1) {
PyErr_SetFromErrno(LinuxAudioError);
return NULL;
}
@@ -307,7 +307,7 @@ _ssize(lad_t *self, int *nchannels, int *ssize)
int fmt;
fmt = 0;
- if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
+ if (ioctl(self->x_fd, SNDCTL_DSP_SETFMT, &fmt) < 0)
return -errno;
switch (fmt) {
@@ -334,7 +334,7 @@ _ssize(lad_t *self, int *nchannels, int *ssize)
}
-/* bufsize returns the size of the hardware audio buffer in number
+/* bufsize returns the size of the hardware audio buffer in number
of samples */
static PyObject *
lad_bufsize(lad_t *self, PyObject *unused)
@@ -353,7 +353,7 @@ lad_bufsize(lad_t *self, PyObject *unused)
return PyInt_FromLong((ai.fragstotal * ai.fragsize) / (nchannels * ssize));
}
-/* obufcount returns the number of samples that are available in the
+/* obufcount returns the number of samples that are available in the
hardware for playing */
static PyObject *
lad_obufcount(lad_t *self, PyObject *unused)
@@ -369,7 +369,7 @@ lad_obufcount(lad_t *self, PyObject *unused)
PyErr_SetFromErrno(LinuxAudioError);
return NULL;
}
- return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
+ return PyInt_FromLong((ai.fragstotal * ai.fragsize - ai.bytes) /
(ssize * nchannels));
}
@@ -410,9 +410,9 @@ lad_getptr(lad_t *self, PyObject *unused)
int req;
if (self->x_mode == O_RDONLY)
- req = SNDCTL_DSP_GETIPTR;
+ req = SNDCTL_DSP_GETIPTR;
else
- req = SNDCTL_DSP_GETOPTR;
+ req = SNDCTL_DSP_GETOPTR;
if (ioctl(self->x_fd, req, &info) == -1) {
PyErr_SetFromErrno(LinuxAudioError);
return NULL;
@@ -421,17 +421,17 @@ lad_getptr(lad_t *self, PyObject *unused)
}
static PyMethodDef lad_methods[] = {
- { "read", (PyCFunction)lad_read, METH_VARARGS },
- { "write", (PyCFunction)lad_write, METH_VARARGS },
- { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS },
- { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS },
- { "obufcount", (PyCFunction)lad_obufcount, METH_NOARGS },
- { "obuffree", (PyCFunction)lad_obuffree, METH_NOARGS },
- { "flush", (PyCFunction)lad_flush, METH_NOARGS },
- { "close", (PyCFunction)lad_close, METH_NOARGS },
- { "fileno", (PyCFunction)lad_fileno, METH_NOARGS },
+ { "read", (PyCFunction)lad_read, METH_VARARGS },
+ { "write", (PyCFunction)lad_write, METH_VARARGS },
+ { "setparameters", (PyCFunction)lad_setparameters, METH_VARARGS },
+ { "bufsize", (PyCFunction)lad_bufsize, METH_VARARGS },
+ { "obufcount", (PyCFunction)lad_obufcount, METH_NOARGS },
+ { "obuffree", (PyCFunction)lad_obuffree, METH_NOARGS },
+ { "flush", (PyCFunction)lad_flush, METH_NOARGS },
+ { "close", (PyCFunction)lad_close, METH_NOARGS },
+ { "fileno", (PyCFunction)lad_fileno, METH_NOARGS },
{ "getptr", (PyCFunction)lad_getptr, METH_NOARGS },
- { NULL, NULL} /* sentinel */
+ { NULL, NULL} /* sentinel */
};
static PyObject *
@@ -443,15 +443,15 @@ lad_getattr(lad_t *xp, char *name)
static PyTypeObject Ladtype = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
"linuxaudiodev.linux_audio_device", /*tp_name*/
- sizeof(lad_t), /*tp_size*/
- 0, /*tp_itemsize*/
+ sizeof(lad_t), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- (destructor)lad_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)lad_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ (destructor)lad_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)lad_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
@@ -469,37 +469,37 @@ void
initlinuxaudiodev(void)
{
PyObject *m;
-
+
if (PyErr_WarnPy3k("the linuxaudiodev module has been removed in "
"Python 3.0; use the ossaudiodev module instead", 2) < 0)
return;
-
+
m = Py_InitModule("linuxaudiodev", linuxaudiodev_methods);
if (m == NULL)
- return;
+ return;
LinuxAudioError = PyErr_NewException("linuxaudiodev.error", NULL, NULL);
if (LinuxAudioError)
- PyModule_AddObject(m, "error", LinuxAudioError);
+ PyModule_AddObject(m, "error", LinuxAudioError);
if (PyModule_AddIntConstant(m, "AFMT_MU_LAW", (long)AFMT_MU_LAW) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_A_LAW", (long)AFMT_A_LAW) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_U8", (long)AFMT_U8) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S8", (long)AFMT_S8) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_U16_BE", (long)AFMT_U16_BE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_U16_LE", (long)AFMT_U16_LE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S16_BE", (long)AFMT_S16_BE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S16_LE", (long)AFMT_S16_LE) == -1)
- return;
+ return;
if (PyModule_AddIntConstant(m, "AFMT_S16_NE", (long)AFMT_S16_NE) == -1)
- return;
+ return;
return;
}
diff --git a/Modules/main.c b/Modules/main.c
index 2f5dc57..7d735a8 100644
--- a/Modules/main.c
+++ b/Modules/main.c
@@ -107,119 +107,119 @@ PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.\n\
static int
usage(int exitcode, char* program)
{
- FILE *f = exitcode ? stderr : stdout;
-
- fprintf(f, usage_line, program);
- if (exitcode)
- fprintf(f, "Try `python -h' for more information.\n");
- else {
- fputs(usage_1, f);
- fputs(usage_2, f);
- fputs(usage_3, f);
- fprintf(f, usage_4, DELIM);
- fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
- }
+ FILE *f = exitcode ? stderr : stdout;
+
+ fprintf(f, usage_line, program);
+ if (exitcode)
+ fprintf(f, "Try `python -h' for more information.\n");
+ else {
+ fputs(usage_1, f);
+ fputs(usage_2, f);
+ fputs(usage_3, f);
+ fprintf(f, usage_4, DELIM);
+ fprintf(f, usage_5, DELIM, PYTHONHOMEHELP);
+ }
#if defined(__VMS)
- if (exitcode == 0) {
- /* suppress 'error' message */
- return 1;
- }
- else {
- /* STS$M_INHIB_MSG + SS$_ABORT */
- return 0x1000002c;
- }
+ if (exitcode == 0) {
+ /* suppress 'error' message */
+ return 1;
+ }
+ else {
+ /* STS$M_INHIB_MSG + SS$_ABORT */
+ return 0x1000002c;
+ }
#else
- return exitcode;
+ return exitcode;
#endif
- /*NOTREACHED*/
+ /*NOTREACHED*/
}
static void RunStartupFile(PyCompilerFlags *cf)
{
- char *startup = Py_GETENV("PYTHONSTARTUP");
- if (startup != NULL && startup[0] != '\0') {
- FILE *fp = fopen(startup, "r");
- if (fp != NULL) {
- (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
- PyErr_Clear();
- fclose(fp);
- } else {
- int save_errno;
- save_errno = errno;
- PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
- errno = save_errno;
- PyErr_SetFromErrnoWithFilename(PyExc_IOError,
- startup);
- PyErr_Print();
- PyErr_Clear();
- }
- }
+ char *startup = Py_GETENV("PYTHONSTARTUP");
+ if (startup != NULL && startup[0] != '\0') {
+ FILE *fp = fopen(startup, "r");
+ if (fp != NULL) {
+ (void) PyRun_SimpleFileExFlags(fp, startup, 0, cf);
+ PyErr_Clear();
+ fclose(fp);
+ } else {
+ int save_errno;
+ save_errno = errno;
+ PySys_WriteStderr("Could not open PYTHONSTARTUP\n");
+ errno = save_errno;
+ PyErr_SetFromErrnoWithFilename(PyExc_IOError,
+ startup);
+ PyErr_Print();
+ PyErr_Clear();
+ }
+ }
}
static int RunModule(char *module, int set_argv0)
{
- PyObject *runpy, *runmodule, *runargs, *result;
- runpy = PyImport_ImportModule("runpy");
- if (runpy == NULL) {
- fprintf(stderr, "Could not import runpy module\n");
- return -1;
- }
- runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
- if (runmodule == NULL) {
- fprintf(stderr, "Could not access runpy._run_module_as_main\n");
- Py_DECREF(runpy);
- return -1;
- }
- runargs = Py_BuildValue("(si)", module, set_argv0);
- if (runargs == NULL) {
- fprintf(stderr,
- "Could not create arguments for runpy._run_module_as_main\n");
- Py_DECREF(runpy);
- Py_DECREF(runmodule);
- return -1;
- }
- result = PyObject_Call(runmodule, runargs, NULL);
- if (result == NULL) {
- PyErr_Print();
- }
- Py_DECREF(runpy);
- Py_DECREF(runmodule);
- Py_DECREF(runargs);
- if (result == NULL) {
- return -1;
- }
- Py_DECREF(result);
- return 0;
+ PyObject *runpy, *runmodule, *runargs, *result;
+ runpy = PyImport_ImportModule("runpy");
+ if (runpy == NULL) {
+ fprintf(stderr, "Could not import runpy module\n");
+ return -1;
+ }
+ runmodule = PyObject_GetAttrString(runpy, "_run_module_as_main");
+ if (runmodule == NULL) {
+ fprintf(stderr, "Could not access runpy._run_module_as_main\n");
+ Py_DECREF(runpy);
+ return -1;
+ }
+ runargs = Py_BuildValue("(si)", module, set_argv0);
+ if (runargs == NULL) {
+ fprintf(stderr,
+ "Could not create arguments for runpy._run_module_as_main\n");
+ Py_DECREF(runpy);
+ Py_DECREF(runmodule);
+ return -1;
+ }
+ result = PyObject_Call(runmodule, runargs, NULL);
+ if (result == NULL) {
+ PyErr_Print();
+ }
+ Py_DECREF(runpy);
+ Py_DECREF(runmodule);
+ Py_DECREF(runargs);
+ if (result == NULL) {
+ return -1;
+ }
+ Py_DECREF(result);
+ return 0;
}
static int RunMainFromImporter(char *filename)
{
- PyObject *argv0 = NULL, *importer = NULL;
-
- if ((argv0 = PyString_FromString(filename)) &&
- (importer = PyImport_GetImporter(argv0)) &&
- (importer->ob_type != &PyNullImporter_Type))
- {
- /* argv0 is usable as an import source, so
- put it in sys.path[0] and import __main__ */
- PyObject *sys_path = NULL;
- if ((sys_path = PySys_GetObject("path")) &&
- !PyList_SetItem(sys_path, 0, argv0))
- {
- Py_INCREF(argv0);
- Py_DECREF(importer);
- sys_path = NULL;
- return RunModule("__main__", 0) != 0;
- }
- }
- Py_XDECREF(argv0);
- Py_XDECREF(importer);
- if (PyErr_Occurred()) {
- PyErr_Print();
- return 1;
- }
- return -1;
+ PyObject *argv0 = NULL, *importer = NULL;
+
+ if ((argv0 = PyString_FromString(filename)) &&
+ (importer = PyImport_GetImporter(argv0)) &&
+ (importer->ob_type != &PyNullImporter_Type))
+ {
+ /* argv0 is usable as an import source, so
+ put it in sys.path[0] and import __main__ */
+ PyObject *sys_path = NULL;
+ if ((sys_path = PySys_GetObject("path")) &&
+ !PyList_SetItem(sys_path, 0, argv0))
+ {
+ Py_INCREF(argv0);
+ Py_DECREF(importer);
+ sys_path = NULL;
+ return RunModule("__main__", 0) != 0;
+ }
+ }
+ Py_XDECREF(argv0);
+ Py_XDECREF(importer);
+ if (PyErr_Occurred()) {
+ PyErr_Print();
+ return 1;
+ }
+ return -1;
}
@@ -228,417 +228,417 @@ static int RunMainFromImporter(char *filename)
int
Py_Main(int argc, char **argv)
{
- int c;
- int sts;
- char *command = NULL;
- char *filename = NULL;
- char *module = NULL;
- FILE *fp = stdin;
- char *p;
- int unbuffered = 0;
- int skipfirstline = 0;
- int stdin_is_interactive = 0;
- int help = 0;
- int version = 0;
- int saw_unbuffered_flag = 0;
- PyCompilerFlags cf;
-
- cf.cf_flags = 0;
-
- orig_argc = argc; /* For Py_GetArgcArgv() */
- orig_argv = argv;
+ int c;
+ int sts;
+ char *command = NULL;
+ char *filename = NULL;
+ char *module = NULL;
+ FILE *fp = stdin;
+ char *p;
+ int unbuffered = 0;
+ int skipfirstline = 0;
+ int stdin_is_interactive = 0;
+ int help = 0;
+ int version = 0;
+ int saw_unbuffered_flag = 0;
+ PyCompilerFlags cf;
+
+ cf.cf_flags = 0;
+
+ orig_argc = argc; /* For Py_GetArgcArgv() */
+ orig_argv = argv;
#ifdef RISCOS
- Py_RISCOSWimpFlag = 0;
+ Py_RISCOSWimpFlag = 0;
#endif
- PySys_ResetWarnOptions();
-
- while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
- if (c == 'c') {
- /* -c is the last option; following arguments
- that look like options are left for the
- command to interpret. */
- command = (char *)malloc(strlen(_PyOS_optarg) + 2);
- if (command == NULL)
- Py_FatalError(
- "not enough memory to copy -c argument");
- strcpy(command, _PyOS_optarg);
- strcat(command, "\n");
- break;
- }
-
- if (c == 'm') {
- /* -m is the last option; following arguments
- that look like options are left for the
- module to interpret. */
- module = (char *)malloc(strlen(_PyOS_optarg) + 2);
- if (module == NULL)
- Py_FatalError(
- "not enough memory to copy -m argument");
- strcpy(module, _PyOS_optarg);
- break;
- }
-
- switch (c) {
- case 'b':
- Py_BytesWarningFlag++;
- break;
-
- case 'd':
- Py_DebugFlag++;
- break;
-
- case '3':
- Py_Py3kWarningFlag++;
- if (!Py_DivisionWarningFlag)
- Py_DivisionWarningFlag = 1;
- break;
-
- case 'Q':
- if (strcmp(_PyOS_optarg, "old") == 0) {
- Py_DivisionWarningFlag = 0;
- break;
- }
- if (strcmp(_PyOS_optarg, "warn") == 0) {
- Py_DivisionWarningFlag = 1;
- break;
- }
- if (strcmp(_PyOS_optarg, "warnall") == 0) {
- Py_DivisionWarningFlag = 2;
- break;
- }
- if (strcmp(_PyOS_optarg, "new") == 0) {
- /* This only affects __main__ */
- cf.cf_flags |= CO_FUTURE_DIVISION;
- /* And this tells the eval loop to treat
- BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
- _Py_QnewFlag = 1;
- break;
- }
- fprintf(stderr,
- "-Q option should be `-Qold', "
- "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
- return usage(2, argv[0]);
- /* NOTREACHED */
-
- case 'i':
- Py_InspectFlag++;
- Py_InteractiveFlag++;
- break;
-
- /* case 'J': reserved for Jython */
-
- case 'O':
- Py_OptimizeFlag++;
- break;
-
- case 'B':
- Py_DontWriteBytecodeFlag++;
- break;
-
- case 's':
- Py_NoUserSiteDirectory++;
- break;
-
- case 'S':
- Py_NoSiteFlag++;
- break;
-
- case 'E':
- Py_IgnoreEnvironmentFlag++;
- break;
-
- case 't':
- Py_TabcheckFlag++;
- break;
-
- case 'u':
- unbuffered++;
- saw_unbuffered_flag = 1;
- break;
-
- case 'v':
- Py_VerboseFlag++;
- break;
+ PySys_ResetWarnOptions();
+
+ while ((c = _PyOS_GetOpt(argc, argv, PROGRAM_OPTS)) != EOF) {
+ if (c == 'c') {
+ /* -c is the last option; following arguments
+ that look like options are left for the
+ command to interpret. */
+ command = (char *)malloc(strlen(_PyOS_optarg) + 2);
+ if (command == NULL)
+ Py_FatalError(
+ "not enough memory to copy -c argument");
+ strcpy(command, _PyOS_optarg);
+ strcat(command, "\n");
+ break;
+ }
+
+ if (c == 'm') {
+ /* -m is the last option; following arguments
+ that look like options are left for the
+ module to interpret. */
+ module = (char *)malloc(strlen(_PyOS_optarg) + 2);
+ if (module == NULL)
+ Py_FatalError(
+ "not enough memory to copy -m argument");
+ strcpy(module, _PyOS_optarg);
+ break;
+ }
+
+ switch (c) {
+ case 'b':
+ Py_BytesWarningFlag++;
+ break;
+
+ case 'd':
+ Py_DebugFlag++;
+ break;
+
+ case '3':
+ Py_Py3kWarningFlag++;
+ if (!Py_DivisionWarningFlag)
+ Py_DivisionWarningFlag = 1;
+ break;
+
+ case 'Q':
+ if (strcmp(_PyOS_optarg, "old") == 0) {
+ Py_DivisionWarningFlag = 0;
+ break;
+ }
+ if (strcmp(_PyOS_optarg, "warn") == 0) {
+ Py_DivisionWarningFlag = 1;
+ break;
+ }
+ if (strcmp(_PyOS_optarg, "warnall") == 0) {
+ Py_DivisionWarningFlag = 2;
+ break;
+ }
+ if (strcmp(_PyOS_optarg, "new") == 0) {
+ /* This only affects __main__ */
+ cf.cf_flags |= CO_FUTURE_DIVISION;
+ /* And this tells the eval loop to treat
+ BINARY_DIVIDE as BINARY_TRUE_DIVIDE */
+ _Py_QnewFlag = 1;
+ break;
+ }
+ fprintf(stderr,
+ "-Q option should be `-Qold', "
+ "`-Qwarn', `-Qwarnall', or `-Qnew' only\n");
+ return usage(2, argv[0]);
+ /* NOTREACHED */
+
+ case 'i':
+ Py_InspectFlag++;
+ Py_InteractiveFlag++;
+ break;
+
+ /* case 'J': reserved for Jython */
+
+ case 'O':
+ Py_OptimizeFlag++;
+ break;
+
+ case 'B':
+ Py_DontWriteBytecodeFlag++;
+ break;
+
+ case 's':
+ Py_NoUserSiteDirectory++;
+ break;
+
+ case 'S':
+ Py_NoSiteFlag++;
+ break;
+
+ case 'E':
+ Py_IgnoreEnvironmentFlag++;
+ break;
+
+ case 't':
+ Py_TabcheckFlag++;
+ break;
+
+ case 'u':
+ unbuffered++;
+ saw_unbuffered_flag = 1;
+ break;
+
+ case 'v':
+ Py_VerboseFlag++;
+ break;
#ifdef RISCOS
- case 'w':
- Py_RISCOSWimpFlag = 1;
- break;
+ case 'w':
+ Py_RISCOSWimpFlag = 1;
+ break;
#endif
- case 'x':
- skipfirstline = 1;
- break;
-
- /* case 'X': reserved for implementation-specific arguments */
-
- case 'U':
- Py_UnicodeFlag++;
- break;
- case 'h':
- case '?':
- help++;
- break;
- case 'V':
- version++;
- break;
-
- case 'W':
- PySys_AddWarnOption(_PyOS_optarg);
- break;
-
- /* This space reserved for other options */
-
- default:
- return usage(2, argv[0]);
- /*NOTREACHED*/
-
- }
- }
-
- if (help)
- return usage(0, argv[0]);
-
- if (version) {
- fprintf(stderr, "Python %s\n", PY_VERSION);
- return 0;
- }
-
- if (Py_Py3kWarningFlag && !Py_TabcheckFlag)
- /* -3 implies -t (but not -tt) */
- Py_TabcheckFlag = 1;
-
- if (!Py_InspectFlag &&
- (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
- Py_InspectFlag = 1;
- if (!saw_unbuffered_flag &&
- (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
- unbuffered = 1;
-
- if (!Py_NoUserSiteDirectory &&
- (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
- Py_NoUserSiteDirectory = 1;
-
- if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
- char *buf, *warning;
-
- buf = (char *)malloc(strlen(p) + 1);
- if (buf == NULL)
- Py_FatalError(
- "not enough memory to copy PYTHONWARNINGS");
- strcpy(buf, p);
- for (warning = strtok(buf, ",");
- warning != NULL;
- warning = strtok(NULL, ","))
- PySys_AddWarnOption(warning);
- free(buf);
- }
-
- if (command == NULL && module == NULL && _PyOS_optind < argc &&
- strcmp(argv[_PyOS_optind], "-") != 0)
- {
+ case 'x':
+ skipfirstline = 1;
+ break;
+
+ /* case 'X': reserved for implementation-specific arguments */
+
+ case 'U':
+ Py_UnicodeFlag++;
+ break;
+ case 'h':
+ case '?':
+ help++;
+ break;
+ case 'V':
+ version++;
+ break;
+
+ case 'W':
+ PySys_AddWarnOption(_PyOS_optarg);
+ break;
+
+ /* This space reserved for other options */
+
+ default:
+ return usage(2, argv[0]);
+ /*NOTREACHED*/
+
+ }
+ }
+
+ if (help)
+ return usage(0, argv[0]);
+
+ if (version) {
+ fprintf(stderr, "Python %s\n", PY_VERSION);
+ return 0;
+ }
+
+ if (Py_Py3kWarningFlag && !Py_TabcheckFlag)
+ /* -3 implies -t (but not -tt) */
+ Py_TabcheckFlag = 1;
+
+ if (!Py_InspectFlag &&
+ (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
+ Py_InspectFlag = 1;
+ if (!saw_unbuffered_flag &&
+ (p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
+ unbuffered = 1;
+
+ if (!Py_NoUserSiteDirectory &&
+ (p = Py_GETENV("PYTHONNOUSERSITE")) && *p != '\0')
+ Py_NoUserSiteDirectory = 1;
+
+ if ((p = Py_GETENV("PYTHONWARNINGS")) && *p != '\0') {
+ char *buf, *warning;
+
+ buf = (char *)malloc(strlen(p) + 1);
+ if (buf == NULL)
+ Py_FatalError(
+ "not enough memory to copy PYTHONWARNINGS");
+ strcpy(buf, p);
+ for (warning = strtok(buf, ",");
+ warning != NULL;
+ warning = strtok(NULL, ","))
+ PySys_AddWarnOption(warning);
+ free(buf);
+ }
+
+ if (command == NULL && module == NULL && _PyOS_optind < argc &&
+ strcmp(argv[_PyOS_optind], "-") != 0)
+ {
#ifdef __VMS
- filename = decc$translate_vms(argv[_PyOS_optind]);
- if (filename == (char *)0 || filename == (char *)-1)
- filename = argv[_PyOS_optind];
+ filename = decc$translate_vms(argv[_PyOS_optind]);
+ if (filename == (char *)0 || filename == (char *)-1)
+ filename = argv[_PyOS_optind];
#else
- filename = argv[_PyOS_optind];
+ filename = argv[_PyOS_optind];
#endif
- }
+ }
- stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
+ stdin_is_interactive = Py_FdIsInteractive(stdin, (char *)0);
- if (unbuffered) {
+ if (unbuffered) {
#if defined(MS_WINDOWS) || defined(__CYGWIN__)
- _setmode(fileno(stdin), O_BINARY);
- _setmode(fileno(stdout), O_BINARY);
+ _setmode(fileno(stdin), O_BINARY);
+ _setmode(fileno(stdout), O_BINARY);
#endif
#ifdef HAVE_SETVBUF
- setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
- setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
- setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
+ setvbuf(stdin, (char *)NULL, _IONBF, BUFSIZ);
+ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
+ setvbuf(stderr, (char *)NULL, _IONBF, BUFSIZ);
#else /* !HAVE_SETVBUF */
- setbuf(stdin, (char *)NULL);
- setbuf(stdout, (char *)NULL);
- setbuf(stderr, (char *)NULL);
+ setbuf(stdin, (char *)NULL);
+ setbuf(stdout, (char *)NULL);
+ setbuf(stderr, (char *)NULL);
#endif /* !HAVE_SETVBUF */
- }
- else if (Py_InteractiveFlag) {
+ }
+ else if (Py_InteractiveFlag) {
#ifdef MS_WINDOWS
- /* Doesn't have to have line-buffered -- use unbuffered */
- /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
- setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
+ /* Doesn't have to have line-buffered -- use unbuffered */
+ /* Any set[v]buf(stdin, ...) screws up Tkinter :-( */
+ setvbuf(stdout, (char *)NULL, _IONBF, BUFSIZ);
#else /* !MS_WINDOWS */
#ifdef HAVE_SETVBUF
- setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
- setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
+ setvbuf(stdin, (char *)NULL, _IOLBF, BUFSIZ);
+ setvbuf(stdout, (char *)NULL, _IOLBF, BUFSIZ);
#endif /* HAVE_SETVBUF */
#endif /* !MS_WINDOWS */
- /* Leave stderr alone - it should be unbuffered anyway. */
- }
+ /* Leave stderr alone - it should be unbuffered anyway. */
+ }
#ifdef __VMS
- else {
- setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
- }
+ else {
+ setvbuf (stdout, (char *)NULL, _IOLBF, BUFSIZ);
+ }
#endif /* __VMS */
#ifdef __APPLE__
- /* On MacOS X, when the Python interpreter is embedded in an
- application bundle, it gets executed by a bootstrapping script
- that does os.execve() with an argv[0] that's different from the
- actual Python executable. This is needed to keep the Finder happy,
- or rather, to work around Apple's overly strict requirements of
- the process name. However, we still need a usable sys.executable,
- so the actual executable path is passed in an environment variable.
- See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
- script. */
- if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
- Py_SetProgramName(p);
- else
- Py_SetProgramName(argv[0]);
+ /* On MacOS X, when the Python interpreter is embedded in an
+ application bundle, it gets executed by a bootstrapping script
+ that does os.execve() with an argv[0] that's different from the
+ actual Python executable. This is needed to keep the Finder happy,
+ or rather, to work around Apple's overly strict requirements of
+ the process name. However, we still need a usable sys.executable,
+ so the actual executable path is passed in an environment variable.
+ See Lib/plat-mac/bundlebuiler.py for details about the bootstrap
+ script. */
+ if ((p = Py_GETENV("PYTHONEXECUTABLE")) && *p != '\0')
+ Py_SetProgramName(p);
+ else
+ Py_SetProgramName(argv[0]);
#else
- Py_SetProgramName(argv[0]);
+ Py_SetProgramName(argv[0]);
#endif
- Py_Initialize();
-
- if (Py_VerboseFlag ||
- (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
- fprintf(stderr, "Python %s on %s\n",
- Py_GetVersion(), Py_GetPlatform());
- if (!Py_NoSiteFlag)
- fprintf(stderr, "%s\n", COPYRIGHT);
- }
-
- if (command != NULL) {
- /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
- _PyOS_optind--;
- argv[_PyOS_optind] = "-c";
- }
-
- if (module != NULL) {
- /* Backup _PyOS_optind and force sys.argv[0] = '-m'
- so that PySys_SetArgv correctly sets sys.path[0] to ''*/
- _PyOS_optind--;
- argv[_PyOS_optind] = "-m";
- }
-
- PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
-
- if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
- isatty(fileno(stdin))) {
- PyObject *v;
- v = PyImport_ImportModule("readline");
- if (v == NULL)
- PyErr_Clear();
- else
- Py_DECREF(v);
- }
-
- if (command) {
- sts = PyRun_SimpleStringFlags(command, &cf) != 0;
- free(command);
- } else if (module) {
- sts = RunModule(module, 1);
- free(module);
- }
- else {
-
- if (filename == NULL && stdin_is_interactive) {
- Py_InspectFlag = 0; /* do exit on SystemExit */
- RunStartupFile(&cf);
- }
- /* XXX */
-
- sts = -1; /* keep track of whether we've already run __main__ */
-
- if (filename != NULL) {
- sts = RunMainFromImporter(filename);
- }
-
- if (sts==-1 && filename!=NULL) {
- if ((fp = fopen(filename, "r")) == NULL) {
- fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
- argv[0], filename, errno, strerror(errno));
-
- return 2;
- }
- else if (skipfirstline) {
- int ch;
- /* Push back first newline so line numbers
- remain the same */
- while ((ch = getc(fp)) != EOF) {
- if (ch == '\n') {
- (void)ungetc(ch, fp);
- break;
- }
- }
- }
- {
- /* XXX: does this work on Win/Win64? (see posix_fstat) */
- struct stat sb;
- if (fstat(fileno(fp), &sb) == 0 &&
- S_ISDIR(sb.st_mode)) {
- fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
- fclose(fp);
- return 1;
- }
- }
- }
-
- if (sts==-1) {
- /* call pending calls like signal handlers (SIGINT) */
- if (Py_MakePendingCalls() == -1) {
- PyErr_Print();
- sts = 1;
- } else {
- sts = PyRun_AnyFileExFlags(
- fp,
- filename == NULL ? "<stdin>" : filename,
- filename != NULL, &cf) != 0;
- }
- }
-
- }
-
- /* Check this environment variable at the end, to give programs the
- * opportunity to set it from Python.
- */
- if (!Py_InspectFlag &&
- (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
- {
- Py_InspectFlag = 1;
- }
-
- if (Py_InspectFlag && stdin_is_interactive &&
- (filename != NULL || command != NULL || module != NULL)) {
- Py_InspectFlag = 0;
- /* XXX */
- sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
- }
-
- Py_Finalize();
+ Py_Initialize();
+
+ if (Py_VerboseFlag ||
+ (command == NULL && filename == NULL && module == NULL && stdin_is_interactive)) {
+ fprintf(stderr, "Python %s on %s\n",
+ Py_GetVersion(), Py_GetPlatform());
+ if (!Py_NoSiteFlag)
+ fprintf(stderr, "%s\n", COPYRIGHT);
+ }
+
+ if (command != NULL) {
+ /* Backup _PyOS_optind and force sys.argv[0] = '-c' */
+ _PyOS_optind--;
+ argv[_PyOS_optind] = "-c";
+ }
+
+ if (module != NULL) {
+ /* Backup _PyOS_optind and force sys.argv[0] = '-m'
+ so that PySys_SetArgv correctly sets sys.path[0] to ''*/
+ _PyOS_optind--;
+ argv[_PyOS_optind] = "-m";
+ }
+
+ PySys_SetArgv(argc-_PyOS_optind, argv+_PyOS_optind);
+
+ if ((Py_InspectFlag || (command == NULL && filename == NULL && module == NULL)) &&
+ isatty(fileno(stdin))) {
+ PyObject *v;
+ v = PyImport_ImportModule("readline");
+ if (v == NULL)
+ PyErr_Clear();
+ else
+ Py_DECREF(v);
+ }
+
+ if (command) {
+ sts = PyRun_SimpleStringFlags(command, &cf) != 0;
+ free(command);
+ } else if (module) {
+ sts = RunModule(module, 1);
+ free(module);
+ }
+ else {
+
+ if (filename == NULL && stdin_is_interactive) {
+ Py_InspectFlag = 0; /* do exit on SystemExit */
+ RunStartupFile(&cf);
+ }
+ /* XXX */
+
+ sts = -1; /* keep track of whether we've already run __main__ */
+
+ if (filename != NULL) {
+ sts = RunMainFromImporter(filename);
+ }
+
+ if (sts==-1 && filename!=NULL) {
+ if ((fp = fopen(filename, "r")) == NULL) {
+ fprintf(stderr, "%s: can't open file '%s': [Errno %d] %s\n",
+ argv[0], filename, errno, strerror(errno));
+
+ return 2;
+ }
+ else if (skipfirstline) {
+ int ch;
+ /* Push back first newline so line numbers
+ remain the same */
+ while ((ch = getc(fp)) != EOF) {
+ if (ch == '\n') {
+ (void)ungetc(ch, fp);
+ break;
+ }
+ }
+ }
+ {
+ /* XXX: does this work on Win/Win64? (see posix_fstat) */
+ struct stat sb;
+ if (fstat(fileno(fp), &sb) == 0 &&
+ S_ISDIR(sb.st_mode)) {
+ fprintf(stderr, "%s: '%s' is a directory, cannot continue\n", argv[0], filename);
+ fclose(fp);
+ return 1;
+ }
+ }
+ }
+
+ if (sts==-1) {
+ /* call pending calls like signal handlers (SIGINT) */
+ if (Py_MakePendingCalls() == -1) {
+ PyErr_Print();
+ sts = 1;
+ } else {
+ sts = PyRun_AnyFileExFlags(
+ fp,
+ filename == NULL ? "<stdin>" : filename,
+ filename != NULL, &cf) != 0;
+ }
+ }
+
+ }
+
+ /* Check this environment variable at the end, to give programs the
+ * opportunity to set it from Python.
+ */
+ if (!Py_InspectFlag &&
+ (p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
+ {
+ Py_InspectFlag = 1;
+ }
+
+ if (Py_InspectFlag && stdin_is_interactive &&
+ (filename != NULL || command != NULL || module != NULL)) {
+ Py_InspectFlag = 0;
+ /* XXX */
+ sts = PyRun_AnyFileFlags(stdin, "<stdin>", &cf) != 0;
+ }
+
+ Py_Finalize();
#ifdef RISCOS
- if (Py_RISCOSWimpFlag)
- fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
+ if (Py_RISCOSWimpFlag)
+ fprintf(stderr, "\x0cq\x0c"); /* make frontend quit */
#endif
#ifdef __INSURE__
- /* Insure++ is a memory analysis tool that aids in discovering
- * memory leaks and other memory problems. On Python exit, the
- * interned string dictionary is flagged as being in use at exit
- * (which it is). Under normal circumstances, this is fine because
- * the memory will be automatically reclaimed by the system. Under
- * memory debugging, it's a huge source of useless noise, so we
- * trade off slower shutdown for less distraction in the memory
- * reports. -baw
- */
- _Py_ReleaseInternedStrings();
+ /* Insure++ is a memory analysis tool that aids in discovering
+ * memory leaks and other memory problems. On Python exit, the
+ * interned string dictionary is flagged as being in use at exit
+ * (which it is). Under normal circumstances, this is fine because
+ * the memory will be automatically reclaimed by the system. Under
+ * memory debugging, it's a huge source of useless noise, so we
+ * trade off slower shutdown for less distraction in the memory
+ * reports. -baw
+ */
+ _Py_ReleaseInternedStrings();
#endif /* __INSURE__ */
- return sts;
+ return sts;
}
/* this is gonna seem *real weird*, but if you put some other code between
@@ -651,8 +651,8 @@ Py_Main(int argc, char **argv)
void
Py_GetArgcArgv(int *argc, char ***argv)
{
- *argc = orig_argc;
- *argv = orig_argv;
+ *argc = orig_argc;
+ *argv = orig_argv;
}
#ifdef __cplusplus
diff --git a/Modules/mathmodule.c b/Modules/mathmodule.c
index 2dd7a66..77b56a0 100644
--- a/Modules/mathmodule.c
+++ b/Modules/mathmodule.c
@@ -73,36 +73,36 @@ static const double sqrtpi = 1.772453850905516027298167483341145182798;
static double
sinpi(double x)
{
- double y, r;
- int n;
- /* this function should only ever be called for finite arguments */
- assert(Py_IS_FINITE(x));
- y = fmod(fabs(x), 2.0);
- n = (int)round(2.0*y);
- assert(0 <= n && n <= 4);
- switch (n) {
- case 0:
- r = sin(pi*y);
- break;
- case 1:
- r = cos(pi*(y-0.5));
- break;
- case 2:
- /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
- -0.0 instead of 0.0 when y == 1.0. */
- r = sin(pi*(1.0-y));
- break;
- case 3:
- r = -cos(pi*(y-1.5));
- break;
- case 4:
- r = sin(pi*(y-2.0));
- break;
- default:
- assert(0); /* should never get here */
- r = -1.23e200; /* silence gcc warning */
- }
- return copysign(1.0, x)*r;
+ double y, r;
+ int n;
+ /* this function should only ever be called for finite arguments */
+ assert(Py_IS_FINITE(x));
+ y = fmod(fabs(x), 2.0);
+ n = (int)round(2.0*y);
+ assert(0 <= n && n <= 4);
+ switch (n) {
+ case 0:
+ r = sin(pi*y);
+ break;
+ case 1:
+ r = cos(pi*(y-0.5));
+ break;
+ case 2:
+ /* N.B. -sin(pi*(y-1.0)) is *not* equivalent: it would give
+ -0.0 instead of 0.0 when y == 1.0. */
+ r = sin(pi*(1.0-y));
+ break;
+ case 3:
+ r = -cos(pi*(y-1.5));
+ break;
+ case 4:
+ r = sin(pi*(y-2.0));
+ break;
+ default:
+ assert(0); /* should never get here */
+ r = -1.23e200; /* silence gcc warning */
+ }
+ return copysign(1.0, x)*r;
}
/* Implementation of the real gamma function. In extensive but non-exhaustive
@@ -166,34 +166,34 @@ sinpi(double x)
static const double lanczos_g = 6.024680040776729583740234375;
static const double lanczos_g_minus_half = 5.524680040776729583740234375;
static const double lanczos_num_coeffs[LANCZOS_N] = {
- 23531376880.410759688572007674451636754734846804940,
- 42919803642.649098768957899047001988850926355848959,
- 35711959237.355668049440185451547166705960488635843,
- 17921034426.037209699919755754458931112671403265390,
- 6039542586.3520280050642916443072979210699388420708,
- 1439720407.3117216736632230727949123939715485786772,
- 248874557.86205415651146038641322942321632125127801,
- 31426415.585400194380614231628318205362874684987640,
- 2876370.6289353724412254090516208496135991145378768,
- 186056.26539522349504029498971604569928220784236328,
- 8071.6720023658162106380029022722506138218516325024,
- 210.82427775157934587250973392071336271166969580291,
- 2.5066282746310002701649081771338373386264310793408
+ 23531376880.410759688572007674451636754734846804940,
+ 42919803642.649098768957899047001988850926355848959,
+ 35711959237.355668049440185451547166705960488635843,
+ 17921034426.037209699919755754458931112671403265390,
+ 6039542586.3520280050642916443072979210699388420708,
+ 1439720407.3117216736632230727949123939715485786772,
+ 248874557.86205415651146038641322942321632125127801,
+ 31426415.585400194380614231628318205362874684987640,
+ 2876370.6289353724412254090516208496135991145378768,
+ 186056.26539522349504029498971604569928220784236328,
+ 8071.6720023658162106380029022722506138218516325024,
+ 210.82427775157934587250973392071336271166969580291,
+ 2.5066282746310002701649081771338373386264310793408
};
/* denominator is x*(x+1)*...*(x+LANCZOS_N-2) */
static const double lanczos_den_coeffs[LANCZOS_N] = {
- 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
- 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
+ 0.0, 39916800.0, 120543840.0, 150917976.0, 105258076.0, 45995730.0,
+ 13339535.0, 2637558.0, 357423.0, 32670.0, 1925.0, 66.0, 1.0};
/* gamma values for small positive integers, 1 though NGAMMA_INTEGRAL */
#define NGAMMA_INTEGRAL 23
static const double gamma_integral[NGAMMA_INTEGRAL] = {
- 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
- 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
- 1307674368000.0, 20922789888000.0, 355687428096000.0,
- 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
- 51090942171709440000.0, 1124000727777607680000.0,
+ 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0, 362880.0,
+ 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
+ 1307674368000.0, 20922789888000.0, 355687428096000.0,
+ 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0,
+ 51090942171709440000.0, 1124000727777607680000.0,
};
/* Lanczos' sum L_g(x), for positive x */
@@ -201,125 +201,125 @@ static const double gamma_integral[NGAMMA_INTEGRAL] = {
static double
lanczos_sum(double x)
{
- double num = 0.0, den = 0.0;
- int i;
- assert(x > 0.0);
- /* evaluate the rational function lanczos_sum(x). For large
- x, the obvious algorithm risks overflow, so we instead
- rescale the denominator and numerator of the rational
- function by x**(1-LANCZOS_N) and treat this as a
- rational function in 1/x. This also reduces the error for
- larger x values. The choice of cutoff point (5.0 below) is
- somewhat arbitrary; in tests, smaller cutoff values than
- this resulted in lower accuracy. */
- if (x < 5.0) {
- for (i = LANCZOS_N; --i >= 0; ) {
- num = num * x + lanczos_num_coeffs[i];
- den = den * x + lanczos_den_coeffs[i];
- }
- }
- else {
- for (i = 0; i < LANCZOS_N; i++) {
- num = num / x + lanczos_num_coeffs[i];
- den = den / x + lanczos_den_coeffs[i];
- }
- }
- return num/den;
+ double num = 0.0, den = 0.0;
+ int i;
+ assert(x > 0.0);
+ /* evaluate the rational function lanczos_sum(x). For large
+ x, the obvious algorithm risks overflow, so we instead
+ rescale the denominator and numerator of the rational
+ function by x**(1-LANCZOS_N) and treat this as a
+ rational function in 1/x. This also reduces the error for
+ larger x values. The choice of cutoff point (5.0 below) is
+ somewhat arbitrary; in tests, smaller cutoff values than
+ this resulted in lower accuracy. */
+ if (x < 5.0) {
+ for (i = LANCZOS_N; --i >= 0; ) {
+ num = num * x + lanczos_num_coeffs[i];
+ den = den * x + lanczos_den_coeffs[i];
+ }
+ }
+ else {
+ for (i = 0; i < LANCZOS_N; i++) {
+ num = num / x + lanczos_num_coeffs[i];
+ den = den / x + lanczos_den_coeffs[i];
+ }
+ }
+ return num/den;
}
static double
m_tgamma(double x)
{
- double absx, r, y, z, sqrtpow;
-
- /* special cases */
- if (!Py_IS_FINITE(x)) {
- if (Py_IS_NAN(x) || x > 0.0)
- return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
- else {
- errno = EDOM;
- return Py_NAN; /* tgamma(-inf) = nan, invalid */
- }
- }
- if (x == 0.0) {
- errno = EDOM;
- return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
- }
-
- /* integer arguments */
- if (x == floor(x)) {
- if (x < 0.0) {
- errno = EDOM; /* tgamma(n) = nan, invalid for */
- return Py_NAN; /* negative integers n */
- }
- if (x <= NGAMMA_INTEGRAL)
- return gamma_integral[(int)x - 1];
- }
- absx = fabs(x);
-
- /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
- if (absx < 1e-20) {
- r = 1.0/x;
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- return r;
- }
-
- /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
- x > 200, and underflows to +-0.0 for x < -200, not a negative
- integer. */
- if (absx > 200.0) {
- if (x < 0.0) {
- return 0.0/sinpi(x);
- }
- else {
- errno = ERANGE;
- return Py_HUGE_VAL;
- }
- }
-
- y = absx + lanczos_g_minus_half;
- /* compute error in sum */
- if (absx > lanczos_g_minus_half) {
- /* note: the correction can be foiled by an optimizing
- compiler that (incorrectly) thinks that an expression like
- a + b - a - b can be optimized to 0.0. This shouldn't
- happen in a standards-conforming compiler. */
- double q = y - absx;
- z = q - lanczos_g_minus_half;
- }
- else {
- double q = y - lanczos_g_minus_half;
- z = q - absx;
- }
- z = z * lanczos_g / y;
- if (x < 0.0) {
- r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
- r -= z * r;
- if (absx < 140.0) {
- r /= pow(y, absx - 0.5);
- }
- else {
- sqrtpow = pow(y, absx / 2.0 - 0.25);
- r /= sqrtpow;
- r /= sqrtpow;
- }
- }
- else {
- r = lanczos_sum(absx) / exp(y);
- r += z * r;
- if (absx < 140.0) {
- r *= pow(y, absx - 0.5);
- }
- else {
- sqrtpow = pow(y, absx / 2.0 - 0.25);
- r *= sqrtpow;
- r *= sqrtpow;
- }
- }
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- return r;
+ double absx, r, y, z, sqrtpow;
+
+ /* special cases */
+ if (!Py_IS_FINITE(x)) {
+ if (Py_IS_NAN(x) || x > 0.0)
+ return x; /* tgamma(nan) = nan, tgamma(inf) = inf */
+ else {
+ errno = EDOM;
+ return Py_NAN; /* tgamma(-inf) = nan, invalid */
+ }
+ }
+ if (x == 0.0) {
+ errno = EDOM;
+ return 1.0/x; /* tgamma(+-0.0) = +-inf, divide-by-zero */
+ }
+
+ /* integer arguments */
+ if (x == floor(x)) {
+ if (x < 0.0) {
+ errno = EDOM; /* tgamma(n) = nan, invalid for */
+ return Py_NAN; /* negative integers n */
+ }
+ if (x <= NGAMMA_INTEGRAL)
+ return gamma_integral[(int)x - 1];
+ }
+ absx = fabs(x);
+
+ /* tiny arguments: tgamma(x) ~ 1/x for x near 0 */
+ if (absx < 1e-20) {
+ r = 1.0/x;
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ return r;
+ }
+
+ /* large arguments: assuming IEEE 754 doubles, tgamma(x) overflows for
+ x > 200, and underflows to +-0.0 for x < -200, not a negative
+ integer. */
+ if (absx > 200.0) {
+ if (x < 0.0) {
+ return 0.0/sinpi(x);
+ }
+ else {
+ errno = ERANGE;
+ return Py_HUGE_VAL;
+ }
+ }
+
+ y = absx + lanczos_g_minus_half;
+ /* compute error in sum */
+ if (absx > lanczos_g_minus_half) {
+ /* note: the correction can be foiled by an optimizing
+ compiler that (incorrectly) thinks that an expression like
+ a + b - a - b can be optimized to 0.0. This shouldn't
+ happen in a standards-conforming compiler. */
+ double q = y - absx;
+ z = q - lanczos_g_minus_half;
+ }
+ else {
+ double q = y - lanczos_g_minus_half;
+ z = q - absx;
+ }
+ z = z * lanczos_g / y;
+ if (x < 0.0) {
+ r = -pi / sinpi(absx) / absx * exp(y) / lanczos_sum(absx);
+ r -= z * r;
+ if (absx < 140.0) {
+ r /= pow(y, absx - 0.5);
+ }
+ else {
+ sqrtpow = pow(y, absx / 2.0 - 0.25);
+ r /= sqrtpow;
+ r /= sqrtpow;
+ }
+ }
+ else {
+ r = lanczos_sum(absx) / exp(y);
+ r += z * r;
+ if (absx < 140.0) {
+ r *= pow(y, absx - 0.5);
+ }
+ else {
+ sqrtpow = pow(y, absx / 2.0 - 0.25);
+ r *= sqrtpow;
+ r *= sqrtpow;
+ }
+ }
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ return r;
}
/*
@@ -330,49 +330,49 @@ m_tgamma(double x)
static double
m_lgamma(double x)
{
- double r, absx;
-
- /* special cases */
- if (!Py_IS_FINITE(x)) {
- if (Py_IS_NAN(x))
- return x; /* lgamma(nan) = nan */
- else
- return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
- }
-
- /* integer arguments */
- if (x == floor(x) && x <= 2.0) {
- if (x <= 0.0) {
- errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
- return Py_HUGE_VAL; /* integers n <= 0 */
- }
- else {
- return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
- }
- }
-
- absx = fabs(x);
- /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
- if (absx < 1e-20)
- return -log(absx);
-
- /* Lanczos' formula */
- if (x > 0.0) {
- /* we could save a fraction of a ulp in accuracy by having a
- second set of numerator coefficients for lanczos_sum that
- absorbed the exp(-lanczos_g) term, and throwing out the
- lanczos_g subtraction below; it's probably not worth it. */
- r = log(lanczos_sum(x)) - lanczos_g +
- (x-0.5)*(log(x+lanczos_g-0.5)-1);
- }
- else {
- r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
- (log(lanczos_sum(absx)) - lanczos_g +
- (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
- }
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- return r;
+ double r, absx;
+
+ /* special cases */
+ if (!Py_IS_FINITE(x)) {
+ if (Py_IS_NAN(x))
+ return x; /* lgamma(nan) = nan */
+ else
+ return Py_HUGE_VAL; /* lgamma(+-inf) = +inf */
+ }
+
+ /* integer arguments */
+ if (x == floor(x) && x <= 2.0) {
+ if (x <= 0.0) {
+ errno = EDOM; /* lgamma(n) = inf, divide-by-zero for */
+ return Py_HUGE_VAL; /* integers n <= 0 */
+ }
+ else {
+ return 0.0; /* lgamma(1) = lgamma(2) = 0.0 */
+ }
+ }
+
+ absx = fabs(x);
+ /* tiny arguments: lgamma(x) ~ -log(fabs(x)) for small x */
+ if (absx < 1e-20)
+ return -log(absx);
+
+ /* Lanczos' formula */
+ if (x > 0.0) {
+ /* we could save a fraction of a ulp in accuracy by having a
+ second set of numerator coefficients for lanczos_sum that
+ absorbed the exp(-lanczos_g) term, and throwing out the
+ lanczos_g subtraction below; it's probably not worth it. */
+ r = log(lanczos_sum(x)) - lanczos_g +
+ (x-0.5)*(log(x+lanczos_g-0.5)-1);
+ }
+ else {
+ r = log(pi) - log(fabs(sinpi(absx))) - log(absx) -
+ (log(lanczos_sum(absx)) - lanczos_g +
+ (absx-0.5)*(log(absx+lanczos_g-0.5)-1));
+ }
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ return r;
}
/*
@@ -428,17 +428,17 @@ m_lgamma(double x)
static double
m_erf_series(double x)
{
- double x2, acc, fk;
- int i;
-
- x2 = x * x;
- acc = 0.0;
- fk = (double)ERF_SERIES_TERMS + 0.5;
- for (i = 0; i < ERF_SERIES_TERMS; i++) {
- acc = 2.0 + x2 * acc / fk;
- fk -= 1.0;
- }
- return acc * x * exp(-x2) / sqrtpi;
+ double x2, acc, fk;
+ int i;
+
+ x2 = x * x;
+ acc = 0.0;
+ fk = (double)ERF_SERIES_TERMS + 0.5;
+ for (i = 0; i < ERF_SERIES_TERMS; i++) {
+ acc = 2.0 + x2 * acc / fk;
+ fk -= 1.0;
+ }
+ return acc * x * exp(-x2) / sqrtpi;
}
/*
@@ -453,26 +453,26 @@ m_erf_series(double x)
static double
m_erfc_contfrac(double x)
{
- double x2, a, da, p, p_last, q, q_last, b;
- int i;
-
- if (x >= ERFC_CONTFRAC_CUTOFF)
- return 0.0;
-
- x2 = x*x;
- a = 0.0;
- da = 0.5;
- p = 1.0; p_last = 0.0;
- q = da + x2; q_last = 1.0;
- for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
- double temp;
- a += da;
- da += 2.0;
- b = da + x2;
- temp = p; p = b*p - a*p_last; p_last = temp;
- temp = q; q = b*q - a*q_last; q_last = temp;
- }
- return p / q * x * exp(-x2) / sqrtpi;
+ double x2, a, da, p, p_last, q, q_last, b;
+ int i;
+
+ if (x >= ERFC_CONTFRAC_CUTOFF)
+ return 0.0;
+
+ x2 = x*x;
+ a = 0.0;
+ da = 0.5;
+ p = 1.0; p_last = 0.0;
+ q = da + x2; q_last = 1.0;
+ for (i = 0; i < ERFC_CONTFRAC_TERMS; i++) {
+ double temp;
+ a += da;
+ da += 2.0;
+ b = da + x2;
+ temp = p; p = b*p - a*p_last; p_last = temp;
+ temp = q; q = b*q - a*q_last; q_last = temp;
+ }
+ return p / q * x * exp(-x2) / sqrtpi;
}
/* Error function erf(x), for general x */
@@ -480,17 +480,17 @@ m_erfc_contfrac(double x)
static double
m_erf(double x)
{
- double absx, cf;
-
- if (Py_IS_NAN(x))
- return x;
- absx = fabs(x);
- if (absx < ERF_SERIES_CUTOFF)
- return m_erf_series(x);
- else {
- cf = m_erfc_contfrac(absx);
- return x > 0.0 ? 1.0 - cf : cf - 1.0;
- }
+ double absx, cf;
+
+ if (Py_IS_NAN(x))
+ return x;
+ absx = fabs(x);
+ if (absx < ERF_SERIES_CUTOFF)
+ return m_erf_series(x);
+ else {
+ cf = m_erfc_contfrac(absx);
+ return x > 0.0 ? 1.0 - cf : cf - 1.0;
+ }
}
/* Complementary error function erfc(x), for general x. */
@@ -498,17 +498,17 @@ m_erf(double x)
static double
m_erfc(double x)
{
- double absx, cf;
-
- if (Py_IS_NAN(x))
- return x;
- absx = fabs(x);
- if (absx < ERF_SERIES_CUTOFF)
- return 1.0 - m_erf_series(x);
- else {
- cf = m_erfc_contfrac(absx);
- return x > 0.0 ? cf : 2.0 - cf;
- }
+ double absx, cf;
+
+ if (Py_IS_NAN(x))
+ return x;
+ absx = fabs(x);
+ if (absx < ERF_SERIES_CUTOFF)
+ return 1.0 - m_erf_series(x);
+ else {
+ cf = m_erfc_contfrac(absx);
+ return x > 0.0 ? cf : 2.0 - cf;
+ }
}
/*
@@ -522,29 +522,29 @@ m_erfc(double x)
static double
m_atan2(double y, double x)
{
- if (Py_IS_NAN(x) || Py_IS_NAN(y))
- return Py_NAN;
- if (Py_IS_INFINITY(y)) {
- if (Py_IS_INFINITY(x)) {
- if (copysign(1., x) == 1.)
- /* atan2(+-inf, +inf) == +-pi/4 */
- return copysign(0.25*Py_MATH_PI, y);
- else
- /* atan2(+-inf, -inf) == +-pi*3/4 */
- return copysign(0.75*Py_MATH_PI, y);
- }
- /* atan2(+-inf, x) == +-pi/2 for finite x */
- return copysign(0.5*Py_MATH_PI, y);
- }
- if (Py_IS_INFINITY(x) || y == 0.) {
- if (copysign(1., x) == 1.)
- /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
- return copysign(0., y);
- else
- /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
- return copysign(Py_MATH_PI, y);
- }
- return atan2(y, x);
+ if (Py_IS_NAN(x) || Py_IS_NAN(y))
+ return Py_NAN;
+ if (Py_IS_INFINITY(y)) {
+ if (Py_IS_INFINITY(x)) {
+ if (copysign(1., x) == 1.)
+ /* atan2(+-inf, +inf) == +-pi/4 */
+ return copysign(0.25*Py_MATH_PI, y);
+ else
+ /* atan2(+-inf, -inf) == +-pi*3/4 */
+ return copysign(0.75*Py_MATH_PI, y);
+ }
+ /* atan2(+-inf, x) == +-pi/2 for finite x */
+ return copysign(0.5*Py_MATH_PI, y);
+ }
+ if (Py_IS_INFINITY(x) || y == 0.) {
+ if (copysign(1., x) == 1.)
+ /* atan2(+-y, +inf) = atan2(+-0, +x) = +-0. */
+ return copysign(0., y);
+ else
+ /* atan2(+-y, -inf) = atan2(+-0., -x) = +-pi. */
+ return copysign(Py_MATH_PI, y);
+ }
+ return atan2(y, x);
}
/*
@@ -557,45 +557,45 @@ m_atan2(double y, double x)
static double
m_log(double x)
{
- if (Py_IS_FINITE(x)) {
- if (x > 0.0)
- return log(x);
- errno = EDOM;
- if (x == 0.0)
- return -Py_HUGE_VAL; /* log(0) = -inf */
- else
- return Py_NAN; /* log(-ve) = nan */
- }
- else if (Py_IS_NAN(x))
- return x; /* log(nan) = nan */
- else if (x > 0.0)
- return x; /* log(inf) = inf */
- else {
- errno = EDOM;
- return Py_NAN; /* log(-inf) = nan */
- }
+ if (Py_IS_FINITE(x)) {
+ if (x > 0.0)
+ return log(x);
+ errno = EDOM;
+ if (x == 0.0)
+ return -Py_HUGE_VAL; /* log(0) = -inf */
+ else
+ return Py_NAN; /* log(-ve) = nan */
+ }
+ else if (Py_IS_NAN(x))
+ return x; /* log(nan) = nan */
+ else if (x > 0.0)
+ return x; /* log(inf) = inf */
+ else {
+ errno = EDOM;
+ return Py_NAN; /* log(-inf) = nan */
+ }
}
static double
m_log10(double x)
{
- if (Py_IS_FINITE(x)) {
- if (x > 0.0)
- return log10(x);
- errno = EDOM;
- if (x == 0.0)
- return -Py_HUGE_VAL; /* log10(0) = -inf */
- else
- return Py_NAN; /* log10(-ve) = nan */
- }
- else if (Py_IS_NAN(x))
- return x; /* log10(nan) = nan */
- else if (x > 0.0)
- return x; /* log10(inf) = inf */
- else {
- errno = EDOM;
- return Py_NAN; /* log10(-inf) = nan */
- }
+ if (Py_IS_FINITE(x)) {
+ if (x > 0.0)
+ return log10(x);
+ errno = EDOM;
+ if (x == 0.0)
+ return -Py_HUGE_VAL; /* log10(0) = -inf */
+ else
+ return Py_NAN; /* log10(-ve) = nan */
+ }
+ else if (Py_IS_NAN(x))
+ return x; /* log10(nan) = nan */
+ else if (x > 0.0)
+ return x; /* log10(inf) = inf */
+ else {
+ errno = EDOM;
+ return Py_NAN; /* log10(-inf) = nan */
+ }
}
@@ -606,37 +606,37 @@ m_log10(double x)
static int
is_error(double x)
{
- int result = 1; /* presumption of guilt */
- assert(errno); /* non-zero errno is a precondition for calling */
- if (errno == EDOM)
- PyErr_SetString(PyExc_ValueError, "math domain error");
-
- else if (errno == ERANGE) {
- /* ANSI C generally requires libm functions to set ERANGE
- * on overflow, but also generally *allows* them to set
- * ERANGE on underflow too. There's no consistency about
- * the latter across platforms.
- * Alas, C99 never requires that errno be set.
- * Here we suppress the underflow errors (libm functions
- * should return a zero on underflow, and +- HUGE_VAL on
- * overflow, so testing the result for zero suffices to
- * distinguish the cases).
- *
- * On some platforms (Ubuntu/ia64) it seems that errno can be
- * set to ERANGE for subnormal results that do *not* underflow
- * to zero. So to be safe, we'll ignore ERANGE whenever the
- * function result is less than one in absolute value.
- */
- if (fabs(x) < 1.0)
- result = 0;
- else
- PyErr_SetString(PyExc_OverflowError,
- "math range error");
- }
- else
- /* Unexpected math error */
- PyErr_SetFromErrno(PyExc_ValueError);
- return result;
+ int result = 1; /* presumption of guilt */
+ assert(errno); /* non-zero errno is a precondition for calling */
+ if (errno == EDOM)
+ PyErr_SetString(PyExc_ValueError, "math domain error");
+
+ else if (errno == ERANGE) {
+ /* ANSI C generally requires libm functions to set ERANGE
+ * on overflow, but also generally *allows* them to set
+ * ERANGE on underflow too. There's no consistency about
+ * the latter across platforms.
+ * Alas, C99 never requires that errno be set.
+ * Here we suppress the underflow errors (libm functions
+ * should return a zero on underflow, and +- HUGE_VAL on
+ * overflow, so testing the result for zero suffices to
+ * distinguish the cases).
+ *
+ * On some platforms (Ubuntu/ia64) it seems that errno can be
+ * set to ERANGE for subnormal results that do *not* underflow
+ * to zero. So to be safe, we'll ignore ERANGE whenever the
+ * function result is less than one in absolute value.
+ */
+ if (fabs(x) < 1.0)
+ result = 0;
+ else
+ PyErr_SetString(PyExc_OverflowError,
+ "math range error");
+ }
+ else
+ /* Unexpected math error */
+ PyErr_SetFromErrno(PyExc_ValueError);
+ return result;
}
/*
@@ -672,30 +672,30 @@ is_error(double x)
static PyObject *
math_1(PyObject *arg, double (*func) (double), int can_overflow)
{
- double x, r;
- x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("in math_1", return 0);
- r = (*func)(x);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x))
- errno = EDOM;
- else
- errno = 0;
- }
- else if (Py_IS_INFINITY(r)) {
- if (Py_IS_FINITE(x))
- errno = can_overflow ? ERANGE : EDOM;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ double x, r;
+ x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("in math_1", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else if (Py_IS_INFINITY(r)) {
+ if (Py_IS_FINITE(x))
+ errno = can_overflow ? ERANGE : EDOM;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
/* variant of math_1, to be used when the function being wrapped is known to
@@ -705,17 +705,17 @@ math_1(PyObject *arg, double (*func) (double), int can_overflow)
static PyObject *
math_1a(PyObject *arg, double (*func) (double))
{
- double x, r;
- x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("in math_1a", return 0);
- r = (*func)(x);
- PyFPE_END_PROTECT(r);
- if (errno && is_error(r))
- return NULL;
- return PyFloat_FromDouble(r);
+ double x, r;
+ x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("in math_1a", return 0);
+ r = (*func)(x);
+ PyFPE_END_PROTECT(r);
+ if (errno && is_error(r))
+ return NULL;
+ return PyFloat_FromDouble(r);
}
/*
@@ -748,53 +748,53 @@ math_1a(PyObject *arg, double (*func) (double))
static PyObject *
math_2(PyObject *args, double (*func) (double, double), char *funcname)
{
- PyObject *ox, *oy;
- double x, y, r;
- if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
- errno = 0;
- PyFPE_START_PROTECT("in math_2", return 0);
- r = (*func)(x, y);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
- errno = EDOM;
- else
- errno = 0;
- }
- else if (Py_IS_INFINITY(r)) {
- if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
- errno = ERANGE;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double x, y, r;
+ if (! PyArg_UnpackTuple(args, funcname, 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ PyFPE_START_PROTECT("in math_2", return 0);
+ r = (*func)(x, y);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else if (Py_IS_INFINITY(r)) {
+ if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
+ errno = ERANGE;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
-#define FUNC1(funcname, func, can_overflow, docstring) \
- static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
- return math_1(args, func, can_overflow); \
- }\
- PyDoc_STRVAR(math_##funcname##_doc, docstring);
+#define FUNC1(funcname, func, can_overflow, docstring) \
+ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
+ return math_1(args, func, can_overflow); \
+ }\
+ PyDoc_STRVAR(math_##funcname##_doc, docstring);
-#define FUNC1A(funcname, func, docstring) \
- static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
- return math_1a(args, func); \
- }\
- PyDoc_STRVAR(math_##funcname##_doc, docstring);
+#define FUNC1A(funcname, func, docstring) \
+ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
+ return math_1a(args, func); \
+ }\
+ PyDoc_STRVAR(math_##funcname##_doc, docstring);
#define FUNC2(funcname, func, docstring) \
- static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
- return math_2(args, func, #funcname); \
- }\
- PyDoc_STRVAR(math_##funcname##_doc, docstring);
+ static PyObject * math_##funcname(PyObject *self, PyObject *args) { \
+ return math_2(args, func, #funcname); \
+ }\
+ PyDoc_STRVAR(math_##funcname##_doc, docstring);
FUNC1(acos, acos, 0,
"acos(x)\n\nReturn the arc cosine (measured in radians) of x.")
@@ -873,7 +873,7 @@ FUNC1(tanh, tanh, 0,
Also, the volatile declaration forces the values to be stored in memory as
regular doubles instead of extended long precision (80-bit) values. This
prevents double rounding because any addition or subtraction of two doubles
- can be resolved exactly into double-sized hi and lo values. As long as the
+ can be resolved exactly into double-sized hi and lo values. As long as the
hi value gets forced into a double before yr and lo are computed, the extra
bits in downstream extended precision operations (x87 for example) will be
exactly zero and therefore can be losslessly stored back into a double,
@@ -896,27 +896,27 @@ static int /* non-zero on error */
_fsum_realloc(double **p_ptr, Py_ssize_t n,
double *ps, Py_ssize_t *m_ptr)
{
- void *v = NULL;
- Py_ssize_t m = *m_ptr;
-
- m += m; /* double */
- if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
- double *p = *p_ptr;
- if (p == ps) {
- v = PyMem_Malloc(sizeof(double) * m);
- if (v != NULL)
- memcpy(v, ps, sizeof(double) * n);
- }
- else
- v = PyMem_Realloc(p, sizeof(double) * m);
- }
- if (v == NULL) { /* size overflow or no memory */
- PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
- return 1;
- }
- *p_ptr = (double*) v;
- *m_ptr = m;
- return 0;
+ void *v = NULL;
+ Py_ssize_t m = *m_ptr;
+
+ m += m; /* double */
+ if (n < m && m < (PY_SSIZE_T_MAX / sizeof(double))) {
+ double *p = *p_ptr;
+ if (p == ps) {
+ v = PyMem_Malloc(sizeof(double) * m);
+ if (v != NULL)
+ memcpy(v, ps, sizeof(double) * n);
+ }
+ else
+ v = PyMem_Realloc(p, sizeof(double) * m);
+ }
+ if (v == NULL) { /* size overflow or no memory */
+ PyErr_SetString(PyExc_MemoryError, "math.fsum partials");
+ return 1;
+ }
+ *p_ptr = (double*) v;
+ *m_ptr = m;
+ return 0;
}
/* Full precision summation of a sequence of floats.
@@ -924,17 +924,17 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n,
def msum(iterable):
partials = [] # sorted, non-overlapping partial sums
for x in iterable:
- i = 0
- for y in partials:
- if abs(x) < abs(y):
- x, y = y, x
- hi = x + y
- lo = y - (hi - x)
- if lo:
- partials[i] = lo
- i += 1
- x = hi
- partials[i:] = [x]
+ i = 0
+ for y in partials:
+ if abs(x) < abs(y):
+ x, y = y, x
+ hi = x + y
+ lo = y - (hi - x)
+ if lo:
+ partials[i] = lo
+ i += 1
+ x = hi
+ partials[i:] = [x]
return sum_exact(partials)
Rounded x+y stored in hi with the roundoff stored in lo. Together hi+lo
@@ -952,119 +952,119 @@ _fsum_realloc(double **p_ptr, Py_ssize_t n,
static PyObject*
math_fsum(PyObject *self, PyObject *seq)
{
- PyObject *item, *iter, *sum = NULL;
- Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
- double x, y, t, ps[NUM_PARTIALS], *p = ps;
- double xsave, special_sum = 0.0, inf_sum = 0.0;
- volatile double hi, yr, lo;
-
- iter = PyObject_GetIter(seq);
- if (iter == NULL)
- return NULL;
-
- PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
-
- for(;;) { /* for x in iterable */
- assert(0 <= n && n <= m);
- assert((m == NUM_PARTIALS && p == ps) ||
- (m > NUM_PARTIALS && p != NULL));
-
- item = PyIter_Next(iter);
- if (item == NULL) {
- if (PyErr_Occurred())
- goto _fsum_error;
- break;
- }
- x = PyFloat_AsDouble(item);
- Py_DECREF(item);
- if (PyErr_Occurred())
- goto _fsum_error;
-
- xsave = x;
- for (i = j = 0; j < n; j++) { /* for y in partials */
- y = p[j];
- if (fabs(x) < fabs(y)) {
- t = x; x = y; y = t;
- }
- hi = x + y;
- yr = hi - x;
- lo = y - yr;
- if (lo != 0.0)
- p[i++] = lo;
- x = hi;
- }
-
- n = i; /* ps[i:] = [x] */
- if (x != 0.0) {
- if (! Py_IS_FINITE(x)) {
- /* a nonfinite x could arise either as
- a result of intermediate overflow, or
- as a result of a nan or inf in the
- summands */
- if (Py_IS_FINITE(xsave)) {
- PyErr_SetString(PyExc_OverflowError,
- "intermediate overflow in fsum");
- goto _fsum_error;
- }
- if (Py_IS_INFINITY(xsave))
- inf_sum += xsave;
- special_sum += xsave;
- /* reset partials */
- n = 0;
- }
- else if (n >= m && _fsum_realloc(&p, n, ps, &m))
- goto _fsum_error;
- else
- p[n++] = x;
- }
- }
-
- if (special_sum != 0.0) {
- if (Py_IS_NAN(inf_sum))
- PyErr_SetString(PyExc_ValueError,
- "-inf + inf in fsum");
- else
- sum = PyFloat_FromDouble(special_sum);
- goto _fsum_error;
- }
-
- hi = 0.0;
- if (n > 0) {
- hi = p[--n];
- /* sum_exact(ps, hi) from the top, stop when the sum becomes
- inexact. */
- while (n > 0) {
- x = hi;
- y = p[--n];
- assert(fabs(y) < fabs(x));
- hi = x + y;
- yr = hi - x;
- lo = y - yr;
- if (lo != 0.0)
- break;
- }
- /* Make half-even rounding work across multiple partials.
- Needed so that sum([1e-16, 1, 1e16]) will round-up the last
- digit to two instead of down to zero (the 1e-16 makes the 1
- slightly closer to two). With a potential 1 ULP rounding
- error fixed-up, math.fsum() can guarantee commutativity. */
- if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
- (lo > 0.0 && p[n-1] > 0.0))) {
- y = lo * 2.0;
- x = hi + y;
- yr = x - hi;
- if (y == yr)
- hi = x;
- }
- }
- sum = PyFloat_FromDouble(hi);
+ PyObject *item, *iter, *sum = NULL;
+ Py_ssize_t i, j, n = 0, m = NUM_PARTIALS;
+ double x, y, t, ps[NUM_PARTIALS], *p = ps;
+ double xsave, special_sum = 0.0, inf_sum = 0.0;
+ volatile double hi, yr, lo;
+
+ iter = PyObject_GetIter(seq);
+ if (iter == NULL)
+ return NULL;
+
+ PyFPE_START_PROTECT("fsum", Py_DECREF(iter); return NULL)
+
+ for(;;) { /* for x in iterable */
+ assert(0 <= n && n <= m);
+ assert((m == NUM_PARTIALS && p == ps) ||
+ (m > NUM_PARTIALS && p != NULL));
+
+ item = PyIter_Next(iter);
+ if (item == NULL) {
+ if (PyErr_Occurred())
+ goto _fsum_error;
+ break;
+ }
+ x = PyFloat_AsDouble(item);
+ Py_DECREF(item);
+ if (PyErr_Occurred())
+ goto _fsum_error;
+
+ xsave = x;
+ for (i = j = 0; j < n; j++) { /* for y in partials */
+ y = p[j];
+ if (fabs(x) < fabs(y)) {
+ t = x; x = y; y = t;
+ }
+ hi = x + y;
+ yr = hi - x;
+ lo = y - yr;
+ if (lo != 0.0)
+ p[i++] = lo;
+ x = hi;
+ }
+
+ n = i; /* ps[i:] = [x] */
+ if (x != 0.0) {
+ if (! Py_IS_FINITE(x)) {
+ /* a nonfinite x could arise either as
+ a result of intermediate overflow, or
+ as a result of a nan or inf in the
+ summands */
+ if (Py_IS_FINITE(xsave)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "intermediate overflow in fsum");
+ goto _fsum_error;
+ }
+ if (Py_IS_INFINITY(xsave))
+ inf_sum += xsave;
+ special_sum += xsave;
+ /* reset partials */
+ n = 0;
+ }
+ else if (n >= m && _fsum_realloc(&p, n, ps, &m))
+ goto _fsum_error;
+ else
+ p[n++] = x;
+ }
+ }
+
+ if (special_sum != 0.0) {
+ if (Py_IS_NAN(inf_sum))
+ PyErr_SetString(PyExc_ValueError,
+ "-inf + inf in fsum");
+ else
+ sum = PyFloat_FromDouble(special_sum);
+ goto _fsum_error;
+ }
+
+ hi = 0.0;
+ if (n > 0) {
+ hi = p[--n];
+ /* sum_exact(ps, hi) from the top, stop when the sum becomes
+ inexact. */
+ while (n > 0) {
+ x = hi;
+ y = p[--n];
+ assert(fabs(y) < fabs(x));
+ hi = x + y;
+ yr = hi - x;
+ lo = y - yr;
+ if (lo != 0.0)
+ break;
+ }
+ /* Make half-even rounding work across multiple partials.
+ Needed so that sum([1e-16, 1, 1e16]) will round-up the last
+ digit to two instead of down to zero (the 1e-16 makes the 1
+ slightly closer to two). With a potential 1 ULP rounding
+ error fixed-up, math.fsum() can guarantee commutativity. */
+ if (n > 0 && ((lo < 0.0 && p[n-1] < 0.0) ||
+ (lo > 0.0 && p[n-1] > 0.0))) {
+ y = lo * 2.0;
+ x = hi + y;
+ yr = x - hi;
+ if (y == yr)
+ hi = x;
+ }
+ }
+ sum = PyFloat_FromDouble(hi);
_fsum_error:
- PyFPE_END_PROTECT(hi)
- Py_DECREF(iter);
- if (p != ps)
- PyMem_Free(p);
- return sum;
+ PyFPE_END_PROTECT(hi)
+ Py_DECREF(iter);
+ if (p != ps)
+ PyMem_Free(p);
+ return sum;
}
#undef NUM_PARTIALS
@@ -1077,53 +1077,53 @@ Assumes IEEE-754 floating point arithmetic.");
static PyObject *
math_factorial(PyObject *self, PyObject *arg)
{
- long i, x;
- PyObject *result, *iobj, *newresult;
-
- if (PyFloat_Check(arg)) {
- PyObject *lx;
- double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
- if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
- PyErr_SetString(PyExc_ValueError,
- "factorial() only accepts integral values");
- return NULL;
- }
- lx = PyLong_FromDouble(dx);
- if (lx == NULL)
- return NULL;
- x = PyLong_AsLong(lx);
- Py_DECREF(lx);
- }
- else
- x = PyInt_AsLong(arg);
-
- if (x == -1 && PyErr_Occurred())
- return NULL;
- if (x < 0) {
- PyErr_SetString(PyExc_ValueError,
- "factorial() not defined for negative values");
- return NULL;
- }
-
- result = (PyObject *)PyInt_FromLong(1);
- if (result == NULL)
- return NULL;
- for (i=1 ; i<=x ; i++) {
- iobj = (PyObject *)PyInt_FromLong(i);
- if (iobj == NULL)
- goto error;
- newresult = PyNumber_Multiply(result, iobj);
- Py_DECREF(iobj);
- if (newresult == NULL)
- goto error;
- Py_DECREF(result);
- result = newresult;
- }
- return result;
+ long i, x;
+ PyObject *result, *iobj, *newresult;
+
+ if (PyFloat_Check(arg)) {
+ PyObject *lx;
+ double dx = PyFloat_AS_DOUBLE((PyFloatObject *)arg);
+ if (!(Py_IS_FINITE(dx) && dx == floor(dx))) {
+ PyErr_SetString(PyExc_ValueError,
+ "factorial() only accepts integral values");
+ return NULL;
+ }
+ lx = PyLong_FromDouble(dx);
+ if (lx == NULL)
+ return NULL;
+ x = PyLong_AsLong(lx);
+ Py_DECREF(lx);
+ }
+ else
+ x = PyInt_AsLong(arg);
+
+ if (x == -1 && PyErr_Occurred())
+ return NULL;
+ if (x < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "factorial() not defined for negative values");
+ return NULL;
+ }
+
+ result = (PyObject *)PyInt_FromLong(1);
+ if (result == NULL)
+ return NULL;
+ for (i=1 ; i<=x ; i++) {
+ iobj = (PyObject *)PyInt_FromLong(i);
+ if (iobj == NULL)
+ goto error;
+ newresult = PyNumber_Multiply(result, iobj);
+ Py_DECREF(iobj);
+ if (newresult == NULL)
+ goto error;
+ Py_DECREF(result);
+ result = newresult;
+ }
+ return result;
error:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
PyDoc_STRVAR(math_factorial_doc,
@@ -1134,7 +1134,7 @@ PyDoc_STRVAR(math_factorial_doc,
static PyObject *
math_trunc(PyObject *self, PyObject *number)
{
- return PyObject_CallMethod(number, "__trunc__", NULL);
+ return PyObject_CallMethod(number, "__trunc__", NULL);
}
PyDoc_STRVAR(math_trunc_doc,
@@ -1145,21 +1145,21 @@ PyDoc_STRVAR(math_trunc_doc,
static PyObject *
math_frexp(PyObject *self, PyObject *arg)
{
- int i;
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- /* deal with special cases directly, to sidestep platform
- differences */
- if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
- i = 0;
- }
- else {
- PyFPE_START_PROTECT("in math_frexp", return 0);
- x = frexp(x, &i);
- PyFPE_END_PROTECT(x);
- }
- return Py_BuildValue("(di)", x, i);
+ int i;
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ /* deal with special cases directly, to sidestep platform
+ differences */
+ if (Py_IS_NAN(x) || Py_IS_INFINITY(x) || !x) {
+ i = 0;
+ }
+ else {
+ PyFPE_START_PROTECT("in math_frexp", return 0);
+ x = frexp(x, &i);
+ PyFPE_END_PROTECT(x);
+ }
+ return Py_BuildValue("(di)", x, i);
}
PyDoc_STRVAR(math_frexp_doc,
@@ -1172,53 +1172,53 @@ PyDoc_STRVAR(math_frexp_doc,
static PyObject *
math_ldexp(PyObject *self, PyObject *args)
{
- double x, r;
- PyObject *oexp;
- long exp;
- int overflow;
- if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
- return NULL;
-
- if (PyLong_Check(oexp) || PyInt_Check(oexp)) {
- /* on overflow, replace exponent with either LONG_MAX
- or LONG_MIN, depending on the sign. */
- exp = PyLong_AsLongAndOverflow(oexp, &overflow);
- if (exp == -1 && PyErr_Occurred())
- return NULL;
- if (overflow)
- exp = overflow < 0 ? LONG_MIN : LONG_MAX;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "Expected an int or long as second argument "
- "to ldexp.");
- return NULL;
- }
-
- if (x == 0. || !Py_IS_FINITE(x)) {
- /* NaNs, zeros and infinities are returned unchanged */
- r = x;
- errno = 0;
- } else if (exp > INT_MAX) {
- /* overflow */
- r = copysign(Py_HUGE_VAL, x);
- errno = ERANGE;
- } else if (exp < INT_MIN) {
- /* underflow to +-0 */
- r = copysign(0., x);
- errno = 0;
- } else {
- errno = 0;
- PyFPE_START_PROTECT("in math_ldexp", return 0);
- r = ldexp(x, (int)exp);
- PyFPE_END_PROTECT(r);
- if (Py_IS_INFINITY(r))
- errno = ERANGE;
- }
-
- if (errno && is_error(r))
- return NULL;
- return PyFloat_FromDouble(r);
+ double x, r;
+ PyObject *oexp;
+ long exp;
+ int overflow;
+ if (! PyArg_ParseTuple(args, "dO:ldexp", &x, &oexp))
+ return NULL;
+
+ if (PyLong_Check(oexp) || PyInt_Check(oexp)) {
+ /* on overflow, replace exponent with either LONG_MAX
+ or LONG_MIN, depending on the sign. */
+ exp = PyLong_AsLongAndOverflow(oexp, &overflow);
+ if (exp == -1 && PyErr_Occurred())
+ return NULL;
+ if (overflow)
+ exp = overflow < 0 ? LONG_MIN : LONG_MAX;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "Expected an int or long as second argument "
+ "to ldexp.");
+ return NULL;
+ }
+
+ if (x == 0. || !Py_IS_FINITE(x)) {
+ /* NaNs, zeros and infinities are returned unchanged */
+ r = x;
+ errno = 0;
+ } else if (exp > INT_MAX) {
+ /* overflow */
+ r = copysign(Py_HUGE_VAL, x);
+ errno = ERANGE;
+ } else if (exp < INT_MIN) {
+ /* underflow to +-0 */
+ r = copysign(0., x);
+ errno = 0;
+ } else {
+ errno = 0;
+ PyFPE_START_PROTECT("in math_ldexp", return 0);
+ r = ldexp(x, (int)exp);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_INFINITY(r))
+ errno = ERANGE;
+ }
+
+ if (errno && is_error(r))
+ return NULL;
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_ldexp_doc,
@@ -1228,23 +1228,23 @@ Return x * (2**i).");
static PyObject *
math_modf(PyObject *self, PyObject *arg)
{
- double y, x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- /* some platforms don't do the right thing for NaNs and
- infinities, so we take care of special cases directly. */
- if (!Py_IS_FINITE(x)) {
- if (Py_IS_INFINITY(x))
- return Py_BuildValue("(dd)", copysign(0., x), x);
- else if (Py_IS_NAN(x))
- return Py_BuildValue("(dd)", x, x);
- }
-
- errno = 0;
- PyFPE_START_PROTECT("in math_modf", return 0);
- x = modf(x, &y);
- PyFPE_END_PROTECT(x);
- return Py_BuildValue("(dd)", x, y);
+ double y, x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ /* some platforms don't do the right thing for NaNs and
+ infinities, so we take care of special cases directly. */
+ if (!Py_IS_FINITE(x)) {
+ if (Py_IS_INFINITY(x))
+ return Py_BuildValue("(dd)", copysign(0., x), x);
+ else if (Py_IS_NAN(x))
+ return Py_BuildValue("(dd)", x, x);
+ }
+
+ errno = 0;
+ PyFPE_START_PROTECT("in math_modf", return 0);
+ x = modf(x, &y);
+ PyFPE_END_PROTECT(x);
+ return Py_BuildValue("(dd)", x, y);
}
PyDoc_STRVAR(math_modf_doc,
@@ -1265,56 +1265,56 @@ PyDoc_STRVAR(math_modf_doc,
static PyObject*
loghelper(PyObject* arg, double (*func)(double), char *funcname)
{
- /* If it is long, do it ourselves. */
- if (PyLong_Check(arg)) {
- double x;
- Py_ssize_t e;
- x = _PyLong_Frexp((PyLongObject *)arg, &e);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- if (x <= 0.0) {
- PyErr_SetString(PyExc_ValueError,
- "math domain error");
- return NULL;
- }
- /* Special case for log(1), to make sure we get an
- exact result there. */
- if (e == 1 && x == 0.5)
- return PyFloat_FromDouble(0.0);
- /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
- x = func(x) + func(2.0) * e;
- return PyFloat_FromDouble(x);
- }
-
- /* Else let libm handle it by itself. */
- return math_1(arg, func, 0);
+ /* If it is long, do it ourselves. */
+ if (PyLong_Check(arg)) {
+ double x;
+ Py_ssize_t e;
+ x = _PyLong_Frexp((PyLongObject *)arg, &e);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ if (x <= 0.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "math domain error");
+ return NULL;
+ }
+ /* Special case for log(1), to make sure we get an
+ exact result there. */
+ if (e == 1 && x == 0.5)
+ return PyFloat_FromDouble(0.0);
+ /* Value is ~= x * 2**e, so the log ~= log(x) + log(2) * e. */
+ x = func(x) + func(2.0) * e;
+ return PyFloat_FromDouble(x);
+ }
+
+ /* Else let libm handle it by itself. */
+ return math_1(arg, func, 0);
}
static PyObject *
math_log(PyObject *self, PyObject *args)
{
- PyObject *arg;
- PyObject *base = NULL;
- PyObject *num, *den;
- PyObject *ans;
-
- if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
- return NULL;
-
- num = loghelper(arg, m_log, "log");
- if (num == NULL || base == NULL)
- return num;
-
- den = loghelper(base, m_log, "log");
- if (den == NULL) {
- Py_DECREF(num);
- return NULL;
- }
-
- ans = PyNumber_Divide(num, den);
- Py_DECREF(num);
- Py_DECREF(den);
- return ans;
+ PyObject *arg;
+ PyObject *base = NULL;
+ PyObject *num, *den;
+ PyObject *ans;
+
+ if (!PyArg_UnpackTuple(args, "log", 1, 2, &arg, &base))
+ return NULL;
+
+ num = loghelper(arg, m_log, "log");
+ if (num == NULL || base == NULL)
+ return num;
+
+ den = loghelper(base, m_log, "log");
+ if (den == NULL) {
+ Py_DECREF(num);
+ return NULL;
+ }
+
+ ans = PyNumber_Divide(num, den);
+ Py_DECREF(num);
+ Py_DECREF(den);
+ return ans;
}
PyDoc_STRVAR(math_log_doc,
@@ -1325,7 +1325,7 @@ If the base not specified, returns the natural logarithm (base e) of x.");
static PyObject *
math_log10(PyObject *self, PyObject *arg)
{
- return loghelper(arg, m_log10, "log10");
+ return loghelper(arg, m_log10, "log10");
}
PyDoc_STRVAR(math_log10_doc,
@@ -1334,31 +1334,31 @@ PyDoc_STRVAR(math_log10_doc,
static PyObject *
math_fmod(PyObject *self, PyObject *args)
{
- PyObject *ox, *oy;
- double r, x, y;
- if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
- /* fmod(x, +/-Inf) returns x for finite x. */
- if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
- return PyFloat_FromDouble(x);
- errno = 0;
- PyFPE_START_PROTECT("in math_fmod", return 0);
- r = fmod(x, y);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
- errno = EDOM;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double r, x, y;
+ if (! PyArg_UnpackTuple(args, "fmod", 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+ /* fmod(x, +/-Inf) returns x for finite x. */
+ if (Py_IS_INFINITY(y) && Py_IS_FINITE(x))
+ return PyFloat_FromDouble(x);
+ errno = 0;
+ PyFPE_START_PROTECT("in math_fmod", return 0);
+ r = fmod(x, y);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_fmod_doc,
@@ -1368,39 +1368,39 @@ PyDoc_STRVAR(math_fmod_doc,
static PyObject *
math_hypot(PyObject *self, PyObject *args)
{
- PyObject *ox, *oy;
- double r, x, y;
- if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
- /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
- if (Py_IS_INFINITY(x))
- return PyFloat_FromDouble(fabs(x));
- if (Py_IS_INFINITY(y))
- return PyFloat_FromDouble(fabs(y));
- errno = 0;
- PyFPE_START_PROTECT("in math_hypot", return 0);
- r = hypot(x, y);
- PyFPE_END_PROTECT(r);
- if (Py_IS_NAN(r)) {
- if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
- errno = EDOM;
- else
- errno = 0;
- }
- else if (Py_IS_INFINITY(r)) {
- if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
- errno = ERANGE;
- else
- errno = 0;
- }
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double r, x, y;
+ if (! PyArg_UnpackTuple(args, "hypot", 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+ /* hypot(x, +/-Inf) returns Inf, even if x is a NaN. */
+ if (Py_IS_INFINITY(x))
+ return PyFloat_FromDouble(fabs(x));
+ if (Py_IS_INFINITY(y))
+ return PyFloat_FromDouble(fabs(y));
+ errno = 0;
+ PyFPE_START_PROTECT("in math_hypot", return 0);
+ r = hypot(x, y);
+ PyFPE_END_PROTECT(r);
+ if (Py_IS_NAN(r)) {
+ if (!Py_IS_NAN(x) && !Py_IS_NAN(y))
+ errno = EDOM;
+ else
+ errno = 0;
+ }
+ else if (Py_IS_INFINITY(r)) {
+ if (Py_IS_FINITE(x) && Py_IS_FINITE(y))
+ errno = ERANGE;
+ else
+ errno = 0;
+ }
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_hypot_doc,
@@ -1415,79 +1415,79 @@ PyDoc_STRVAR(math_hypot_doc,
static PyObject *
math_pow(PyObject *self, PyObject *args)
{
- PyObject *ox, *oy;
- double r, x, y;
- int odd_y;
-
- if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
- return NULL;
- x = PyFloat_AsDouble(ox);
- y = PyFloat_AsDouble(oy);
- if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
- return NULL;
-
- /* deal directly with IEEE specials, to cope with problems on various
- platforms whose semantics don't exactly match C99 */
- r = 0.; /* silence compiler warning */
- if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
- errno = 0;
- if (Py_IS_NAN(x))
- r = y == 0. ? 1. : x; /* NaN**0 = 1 */
- else if (Py_IS_NAN(y))
- r = x == 1. ? 1. : y; /* 1**NaN = 1 */
- else if (Py_IS_INFINITY(x)) {
- odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
- if (y > 0.)
- r = odd_y ? x : fabs(x);
- else if (y == 0.)
- r = 1.;
- else /* y < 0. */
- r = odd_y ? copysign(0., x) : 0.;
- }
- else if (Py_IS_INFINITY(y)) {
- if (fabs(x) == 1.0)
- r = 1.;
- else if (y > 0. && fabs(x) > 1.0)
- r = y;
- else if (y < 0. && fabs(x) < 1.0) {
- r = -y; /* result is +inf */
- if (x == 0.) /* 0**-inf: divide-by-zero */
- errno = EDOM;
- }
- else
- r = 0.;
- }
- }
- else {
- /* let libm handle finite**finite */
- errno = 0;
- PyFPE_START_PROTECT("in math_pow", return 0);
- r = pow(x, y);
- PyFPE_END_PROTECT(r);
- /* a NaN result should arise only from (-ve)**(finite
- non-integer); in this case we want to raise ValueError. */
- if (!Py_IS_FINITE(r)) {
- if (Py_IS_NAN(r)) {
- errno = EDOM;
- }
- /*
- an infinite result here arises either from:
- (A) (+/-0.)**negative (-> divide-by-zero)
- (B) overflow of x**y with x and y finite
- */
- else if (Py_IS_INFINITY(r)) {
- if (x == 0.)
- errno = EDOM;
- else
- errno = ERANGE;
- }
- }
- }
-
- if (errno && is_error(r))
- return NULL;
- else
- return PyFloat_FromDouble(r);
+ PyObject *ox, *oy;
+ double r, x, y;
+ int odd_y;
+
+ if (! PyArg_UnpackTuple(args, "pow", 2, 2, &ox, &oy))
+ return NULL;
+ x = PyFloat_AsDouble(ox);
+ y = PyFloat_AsDouble(oy);
+ if ((x == -1.0 || y == -1.0) && PyErr_Occurred())
+ return NULL;
+
+ /* deal directly with IEEE specials, to cope with problems on various
+ platforms whose semantics don't exactly match C99 */
+ r = 0.; /* silence compiler warning */
+ if (!Py_IS_FINITE(x) || !Py_IS_FINITE(y)) {
+ errno = 0;
+ if (Py_IS_NAN(x))
+ r = y == 0. ? 1. : x; /* NaN**0 = 1 */
+ else if (Py_IS_NAN(y))
+ r = x == 1. ? 1. : y; /* 1**NaN = 1 */
+ else if (Py_IS_INFINITY(x)) {
+ odd_y = Py_IS_FINITE(y) && fmod(fabs(y), 2.0) == 1.0;
+ if (y > 0.)
+ r = odd_y ? x : fabs(x);
+ else if (y == 0.)
+ r = 1.;
+ else /* y < 0. */
+ r = odd_y ? copysign(0., x) : 0.;
+ }
+ else if (Py_IS_INFINITY(y)) {
+ if (fabs(x) == 1.0)
+ r = 1.;
+ else if (y > 0. && fabs(x) > 1.0)
+ r = y;
+ else if (y < 0. && fabs(x) < 1.0) {
+ r = -y; /* result is +inf */
+ if (x == 0.) /* 0**-inf: divide-by-zero */
+ errno = EDOM;
+ }
+ else
+ r = 0.;
+ }
+ }
+ else {
+ /* let libm handle finite**finite */
+ errno = 0;
+ PyFPE_START_PROTECT("in math_pow", return 0);
+ r = pow(x, y);
+ PyFPE_END_PROTECT(r);
+ /* a NaN result should arise only from (-ve)**(finite
+ non-integer); in this case we want to raise ValueError. */
+ if (!Py_IS_FINITE(r)) {
+ if (Py_IS_NAN(r)) {
+ errno = EDOM;
+ }
+ /*
+ an infinite result here arises either from:
+ (A) (+/-0.)**negative (-> divide-by-zero)
+ (B) overflow of x**y with x and y finite
+ */
+ else if (Py_IS_INFINITY(r)) {
+ if (x == 0.)
+ errno = EDOM;
+ else
+ errno = ERANGE;
+ }
+ }
+ }
+
+ if (errno && is_error(r))
+ return NULL;
+ else
+ return PyFloat_FromDouble(r);
}
PyDoc_STRVAR(math_pow_doc,
@@ -1499,10 +1499,10 @@ static const double radToDeg = 180.0 / Py_MATH_PI;
static PyObject *
math_degrees(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x * radToDeg);
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x * radToDeg);
}
PyDoc_STRVAR(math_degrees_doc,
@@ -1512,10 +1512,10 @@ Convert angle x from radians to degrees.");
static PyObject *
math_radians(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(x * degToRad);
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(x * degToRad);
}
PyDoc_STRVAR(math_radians_doc,
@@ -1525,10 +1525,10 @@ Convert angle x from degrees to radians.");
static PyObject *
math_isnan(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_NAN(x));
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_NAN(x));
}
PyDoc_STRVAR(math_isnan_doc,
@@ -1538,10 +1538,10 @@ Check if float x is not a number (NaN).");
static PyObject *
math_isinf(PyObject *self, PyObject *arg)
{
- double x = PyFloat_AsDouble(arg);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_INFINITY(x));
+ double x = PyFloat_AsDouble(arg);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_INFINITY(x));
}
PyDoc_STRVAR(math_isinf_doc,
@@ -1549,47 +1549,47 @@ PyDoc_STRVAR(math_isinf_doc,
Check if float x is infinite (positive or negative).");
static PyMethodDef math_methods[] = {
- {"acos", math_acos, METH_O, math_acos_doc},
- {"acosh", math_acosh, METH_O, math_acosh_doc},
- {"asin", math_asin, METH_O, math_asin_doc},
- {"asinh", math_asinh, METH_O, math_asinh_doc},
- {"atan", math_atan, METH_O, math_atan_doc},
- {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
- {"atanh", math_atanh, METH_O, math_atanh_doc},
- {"ceil", math_ceil, METH_O, math_ceil_doc},
- {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
- {"cos", math_cos, METH_O, math_cos_doc},
- {"cosh", math_cosh, METH_O, math_cosh_doc},
- {"degrees", math_degrees, METH_O, math_degrees_doc},
- {"erf", math_erf, METH_O, math_erf_doc},
- {"erfc", math_erfc, METH_O, math_erfc_doc},
- {"exp", math_exp, METH_O, math_exp_doc},
- {"expm1", math_expm1, METH_O, math_expm1_doc},
- {"fabs", math_fabs, METH_O, math_fabs_doc},
- {"factorial", math_factorial, METH_O, math_factorial_doc},
- {"floor", math_floor, METH_O, math_floor_doc},
- {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
- {"frexp", math_frexp, METH_O, math_frexp_doc},
- {"fsum", math_fsum, METH_O, math_fsum_doc},
- {"gamma", math_gamma, METH_O, math_gamma_doc},
- {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
- {"isinf", math_isinf, METH_O, math_isinf_doc},
- {"isnan", math_isnan, METH_O, math_isnan_doc},
- {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
- {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
- {"log", math_log, METH_VARARGS, math_log_doc},
- {"log1p", math_log1p, METH_O, math_log1p_doc},
- {"log10", math_log10, METH_O, math_log10_doc},
- {"modf", math_modf, METH_O, math_modf_doc},
- {"pow", math_pow, METH_VARARGS, math_pow_doc},
- {"radians", math_radians, METH_O, math_radians_doc},
- {"sin", math_sin, METH_O, math_sin_doc},
- {"sinh", math_sinh, METH_O, math_sinh_doc},
- {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
- {"tan", math_tan, METH_O, math_tan_doc},
- {"tanh", math_tanh, METH_O, math_tanh_doc},
- {"trunc", math_trunc, METH_O, math_trunc_doc},
- {NULL, NULL} /* sentinel */
+ {"acos", math_acos, METH_O, math_acos_doc},
+ {"acosh", math_acosh, METH_O, math_acosh_doc},
+ {"asin", math_asin, METH_O, math_asin_doc},
+ {"asinh", math_asinh, METH_O, math_asinh_doc},
+ {"atan", math_atan, METH_O, math_atan_doc},
+ {"atan2", math_atan2, METH_VARARGS, math_atan2_doc},
+ {"atanh", math_atanh, METH_O, math_atanh_doc},
+ {"ceil", math_ceil, METH_O, math_ceil_doc},
+ {"copysign", math_copysign, METH_VARARGS, math_copysign_doc},
+ {"cos", math_cos, METH_O, math_cos_doc},
+ {"cosh", math_cosh, METH_O, math_cosh_doc},
+ {"degrees", math_degrees, METH_O, math_degrees_doc},
+ {"erf", math_erf, METH_O, math_erf_doc},
+ {"erfc", math_erfc, METH_O, math_erfc_doc},
+ {"exp", math_exp, METH_O, math_exp_doc},
+ {"expm1", math_expm1, METH_O, math_expm1_doc},
+ {"fabs", math_fabs, METH_O, math_fabs_doc},
+ {"factorial", math_factorial, METH_O, math_factorial_doc},
+ {"floor", math_floor, METH_O, math_floor_doc},
+ {"fmod", math_fmod, METH_VARARGS, math_fmod_doc},
+ {"frexp", math_frexp, METH_O, math_frexp_doc},
+ {"fsum", math_fsum, METH_O, math_fsum_doc},
+ {"gamma", math_gamma, METH_O, math_gamma_doc},
+ {"hypot", math_hypot, METH_VARARGS, math_hypot_doc},
+ {"isinf", math_isinf, METH_O, math_isinf_doc},
+ {"isnan", math_isnan, METH_O, math_isnan_doc},
+ {"ldexp", math_ldexp, METH_VARARGS, math_ldexp_doc},
+ {"lgamma", math_lgamma, METH_O, math_lgamma_doc},
+ {"log", math_log, METH_VARARGS, math_log_doc},
+ {"log1p", math_log1p, METH_O, math_log1p_doc},
+ {"log10", math_log10, METH_O, math_log10_doc},
+ {"modf", math_modf, METH_O, math_modf_doc},
+ {"pow", math_pow, METH_VARARGS, math_pow_doc},
+ {"radians", math_radians, METH_O, math_radians_doc},
+ {"sin", math_sin, METH_O, math_sin_doc},
+ {"sinh", math_sinh, METH_O, math_sinh_doc},
+ {"sqrt", math_sqrt, METH_O, math_sqrt_doc},
+ {"tan", math_tan, METH_O, math_tan_doc},
+ {"tanh", math_tanh, METH_O, math_tanh_doc},
+ {"trunc", math_trunc, METH_O, math_trunc_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -1600,15 +1600,15 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
initmath(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule3("math", math_methods, module_doc);
- if (m == NULL)
- goto finally;
+ m = Py_InitModule3("math", math_methods, module_doc);
+ if (m == NULL)
+ goto finally;
- PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
- PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
+ PyModule_AddObject(m, "pi", PyFloat_FromDouble(Py_MATH_PI));
+ PyModule_AddObject(m, "e", PyFloat_FromDouble(Py_MATH_E));
finally:
- return;
+ return;
}
diff --git a/Modules/md5.c b/Modules/md5.c
index 642f0bd..8fdc600 100644
--- a/Modules/md5.c
+++ b/Modules/md5.c
@@ -27,7 +27,7 @@
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
- http://www.ietf.org/rfc/rfc1321.txt
+ http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
@@ -38,14 +38,14 @@
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
- either statically or dynamically; added missing #include <string.h>
- in library.
+ either statically or dynamically; added missing #include <string.h>
+ in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
- type, in test program and T value program.
+ type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
- unsigned in ANSI C, signed in traditional"; made test program
- self-checking.
+ unsigned in ANSI C, signed in traditional"; made test program
+ self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
@@ -55,7 +55,7 @@
#include <string.h>
#include <limits.h>
-#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
+#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
@@ -133,8 +133,8 @@ static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
- a = pms->abcd[0], b = pms->abcd[1],
- c = pms->abcd[2], d = pms->abcd[3];
+ a = pms->abcd[0], b = pms->abcd[1],
+ c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
@@ -147,51 +147,51 @@ md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
#if BYTE_ORDER == 0
- /*
- * Determine dynamically whether this is a big-endian or
- * little-endian machine, since we can use a more efficient
- * algorithm on the latter.
- */
- static const int w = 1;
-
- if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
+ /*
+ * Determine dynamically whether this is a big-endian or
+ * little-endian machine, since we can use a more efficient
+ * algorithm on the latter.
+ */
+ static const int w = 1;
+
+ if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
#endif
-#if BYTE_ORDER <= 0 /* little-endian */
- {
- /*
- * On little-endian machines, we can process properly aligned
- * data without copying it.
- */
- if (!((data - (const md5_byte_t *)0) & 3)) {
- /* data are properly aligned */
- X = (const md5_word_t *)data;
- } else {
- /* not aligned */
- memcpy(xbuf, data, 64);
- X = xbuf;
- }
- }
+#if BYTE_ORDER <= 0 /* little-endian */
+ {
+ /*
+ * On little-endian machines, we can process properly aligned
+ * data without copying it.
+ */
+ if (!((data - (const md5_byte_t *)0) & 3)) {
+ /* data are properly aligned */
+ X = (const md5_word_t *)data;
+ } else {
+ /* not aligned */
+ memcpy(xbuf, data, 64);
+ X = xbuf;
+ }
+ }
#endif
#if BYTE_ORDER == 0
- else /* dynamic big-endian */
+ else /* dynamic big-endian */
#endif
-#if BYTE_ORDER >= 0 /* big-endian */
- {
- /*
- * On big-endian machines, we must arrange the bytes in the
- * right order.
- */
- const md5_byte_t *xp = data;
- int i;
+#if BYTE_ORDER >= 0 /* big-endian */
+ {
+ /*
+ * On big-endian machines, we must arrange the bytes in the
+ * right order.
+ */
+ const md5_byte_t *xp = data;
+ int i;
# if BYTE_ORDER == 0
- X = xbuf; /* (dynamic only) */
+ X = xbuf; /* (dynamic only) */
# else
-# define xbuf X /* (static only) */
+# define xbuf X /* (static only) */
# endif
- for (i = 0; i < 16; ++i, xp += 4)
- xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
- }
+ for (i = 0; i < 16; ++i, xp += 4)
+ xbuf[i] = xp[0] + (xp[1] << 8) + (xp[2] << 16) + (xp[3] << 24);
+ }
#endif
}
@@ -329,7 +329,7 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes)
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
- return;
+ return;
/* this special case is handled recursively */
if (nbytes > INT_MAX - offset) {
@@ -339,7 +339,7 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes)
overlap = 64 - offset;
md5_append(pms, data, overlap);
- md5_append(pms, data + overlap, nbytes - overlap);
+ md5_append(pms, data + overlap, nbytes - overlap);
return;
}
@@ -347,48 +347,48 @@ md5_append(md5_state_t *pms, const md5_byte_t *data, unsigned int nbytes)
pms->count[1] += nbytes >> 29;
pms->count[0] += nbits;
if (pms->count[0] < nbits)
- pms->count[1]++;
+ pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
- unsigned int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
-
- memcpy(pms->buf + offset, p, copy);
- if (offset + copy < 64)
- return;
- p += copy;
- left -= copy;
- md5_process(pms, pms->buf);
+ unsigned int copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
+
+ memcpy(pms->buf + offset, p, copy);
+ if (offset + copy < 64)
+ return;
+ p += copy;
+ left -= copy;
+ md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
- md5_process(pms, p);
+ md5_process(pms, p);
/* Process a final partial block. */
if (left)
- memcpy(pms->buf, p, left);
+ memcpy(pms->buf, p, left);
}
void
md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
- 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
+ 0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
- data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
+ data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
- digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
+ digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
diff --git a/Modules/md5module.c b/Modules/md5module.c
index 9d7e3fd..0683ef5 100644
--- a/Modules/md5module.c
+++ b/Modules/md5module.c
@@ -14,25 +14,25 @@
#include "md5.h"
typedef struct {
- PyObject_HEAD
- md5_state_t md5; /* the context holder */
+ PyObject_HEAD
+ md5_state_t md5; /* the context holder */
} md5object;
static PyTypeObject MD5type;
-#define is_md5object(v) ((v)->ob_type == &MD5type)
+#define is_md5object(v) ((v)->ob_type == &MD5type)
static md5object *
newmd5object(void)
{
- md5object *md5p;
+ md5object *md5p;
- md5p = PyObject_New(md5object, &MD5type);
- if (md5p == NULL)
- return NULL;
+ md5p = PyObject_New(md5object, &MD5type);
+ if (md5p == NULL)
+ return NULL;
- md5_init(&md5p->md5); /* actual initialisation */
- return md5p;
+ md5_init(&md5p->md5); /* actual initialisation */
+ return md5p;
}
@@ -41,7 +41,7 @@ newmd5object(void)
static void
md5_dealloc(md5object *md5p)
{
- PyObject_Del(md5p);
+ PyObject_Del(md5p);
}
@@ -50,16 +50,16 @@ md5_dealloc(md5object *md5p)
static PyObject *
md5_update(md5object *self, PyObject *args)
{
- Py_buffer view;
+ Py_buffer view;
- if (!PyArg_ParseTuple(args, "s*:update", &view))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s*:update", &view))
+ return NULL;
- md5_append(&self->md5, (unsigned char*)view.buf,
- Py_SAFE_DOWNCAST(view.len, Py_ssize_t, unsigned int));
+ md5_append(&self->md5, (unsigned char*)view.buf,
+ Py_SAFE_DOWNCAST(view.len, Py_ssize_t, unsigned int));
- PyBuffer_Release(&view);
- Py_RETURN_NONE;
+ PyBuffer_Release(&view);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(update_doc,
@@ -73,14 +73,14 @@ arguments.");
static PyObject *
md5_digest(md5object *self)
{
- md5_state_t mdContext;
- unsigned char aDigest[16];
+ md5_state_t mdContext;
+ unsigned char aDigest[16];
- /* make a temporary copy, and perform the final */
- mdContext = self->md5;
- md5_finish(&mdContext, aDigest);
+ /* make a temporary copy, and perform the final */
+ mdContext = self->md5;
+ md5_finish(&mdContext, aDigest);
- return PyString_FromStringAndSize((char *)aDigest, 16);
+ return PyString_FromStringAndSize((char *)aDigest, 16);
}
PyDoc_STRVAR(digest_doc,
@@ -94,26 +94,26 @@ including null bytes.");
static PyObject *
md5_hexdigest(md5object *self)
{
- md5_state_t mdContext;
- unsigned char digest[16];
- unsigned char hexdigest[32];
- int i, j;
-
- /* make a temporary copy, and perform the final */
- mdContext = self->md5;
- md5_finish(&mdContext, digest);
-
- /* Make hex version of the digest */
- for(i=j=0; i<16; i++) {
- char c;
- c = (digest[i] >> 4) & 0xf;
- c = (c>9) ? c+'a'-10 : c + '0';
- hexdigest[j++] = c;
- c = (digest[i] & 0xf);
- c = (c>9) ? c+'a'-10 : c + '0';
- hexdigest[j++] = c;
- }
- return PyString_FromStringAndSize((char*)hexdigest, 32);
+ md5_state_t mdContext;
+ unsigned char digest[16];
+ unsigned char hexdigest[32];
+ int i, j;
+
+ /* make a temporary copy, and perform the final */
+ mdContext = self->md5;
+ md5_finish(&mdContext, digest);
+
+ /* Make hex version of the digest */
+ for(i=j=0; i<16; i++) {
+ char c;
+ c = (digest[i] >> 4) & 0xf;
+ c = (c>9) ? c+'a'-10 : c + '0';
+ hexdigest[j++] = c;
+ c = (digest[i] & 0xf);
+ c = (c>9) ? c+'a'-10 : c + '0';
+ hexdigest[j++] = c;
+ }
+ return PyString_FromStringAndSize((char*)hexdigest, 32);
}
@@ -126,14 +126,14 @@ Like digest(), but returns the digest as a string of hexadecimal digits.");
static PyObject *
md5_copy(md5object *self)
{
- md5object *md5p;
+ md5object *md5p;
- if ((md5p = newmd5object()) == NULL)
- return NULL;
+ if ((md5p = newmd5object()) == NULL)
+ return NULL;
- md5p->md5 = self->md5;
+ md5p->md5 = self->md5;
- return (PyObject *)md5p;
+ return (PyObject *)md5p;
}
PyDoc_STRVAR(copy_doc,
@@ -143,11 +143,11 @@ Return a copy (``clone'') of the md5 object.");
static PyMethodDef md5_methods[] = {
- {"update", (PyCFunction)md5_update, METH_VARARGS, update_doc},
- {"digest", (PyCFunction)md5_digest, METH_NOARGS, digest_doc},
- {"hexdigest", (PyCFunction)md5_hexdigest, METH_NOARGS, hexdigest_doc},
- {"copy", (PyCFunction)md5_copy, METH_NOARGS, copy_doc},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)md5_update, METH_VARARGS, update_doc},
+ {"digest", (PyCFunction)md5_digest, METH_NOARGS, digest_doc},
+ {"hexdigest", (PyCFunction)md5_hexdigest, METH_NOARGS, hexdigest_doc},
+ {"copy", (PyCFunction)md5_copy, METH_NOARGS, copy_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -221,37 +221,37 @@ hexdigest() -- return the current digest as a string of hexadecimal digits\n\
copy() -- return a copy of the current md5 object");
static PyTypeObject MD5type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_md5.md5", /*tp_name*/
- sizeof(md5object), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)md5_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, /*tp_flags*/
- md5type_doc, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- md5_methods, /*tp_methods*/
- 0, /*tp_members*/
- md5_getseters, /*tp_getset*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_md5.md5", /*tp_name*/
+ sizeof(md5object), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)md5_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, /*tp_flags*/
+ md5type_doc, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ md5_methods, /*tp_methods*/
+ 0, /*tp_members*/
+ md5_getseters, /*tp_getset*/
};
@@ -260,24 +260,24 @@ static PyTypeObject MD5type = {
static PyObject *
MD5_new(PyObject *self, PyObject *args)
{
- md5object *md5p;
- Py_buffer view = { 0 };
-
- if (!PyArg_ParseTuple(args, "|s*:new", &view))
- return NULL;
-
- if ((md5p = newmd5object()) == NULL) {
- PyBuffer_Release(&view);
- return NULL;
- }
-
- if (view.len > 0) {
- md5_append(&md5p->md5, (unsigned char*)view.buf,
- Py_SAFE_DOWNCAST(view.len, Py_ssize_t, unsigned int));
- }
- PyBuffer_Release(&view);
-
- return (PyObject *)md5p;
+ md5object *md5p;
+ Py_buffer view = { 0 };
+
+ if (!PyArg_ParseTuple(args, "|s*:new", &view))
+ return NULL;
+
+ if ((md5p = newmd5object()) == NULL) {
+ PyBuffer_Release(&view);
+ return NULL;
+ }
+
+ if (view.len > 0) {
+ md5_append(&md5p->md5, (unsigned char*)view.buf,
+ Py_SAFE_DOWNCAST(view.len, Py_ssize_t, unsigned int));
+ }
+ PyBuffer_Release(&view);
+
+ return (PyObject *)md5p;
}
PyDoc_STRVAR(new_doc,
@@ -290,8 +290,8 @@ is made.");
/* List of functions exported by this module */
static PyMethodDef md5_functions[] = {
- {"new", (PyCFunction)MD5_new, METH_VARARGS, new_doc},
- {NULL, NULL} /* Sentinel */
+ {"new", (PyCFunction)MD5_new, METH_VARARGS, new_doc},
+ {NULL, NULL} /* Sentinel */
};
@@ -300,16 +300,16 @@ static PyMethodDef md5_functions[] = {
PyMODINIT_FUNC
init_md5(void)
{
- PyObject *m, *d;
-
- Py_TYPE(&MD5type) = &PyType_Type;
- if (PyType_Ready(&MD5type) < 0)
- return;
- m = Py_InitModule3("_md5", md5_functions, module_doc);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- PyDict_SetItemString(d, "MD5Type", (PyObject *)&MD5type);
- PyModule_AddIntConstant(m, "digest_size", 16);
- /* No need to check the error here, the caller will do that */
+ PyObject *m, *d;
+
+ Py_TYPE(&MD5type) = &PyType_Type;
+ if (PyType_Ready(&MD5type) < 0)
+ return;
+ m = Py_InitModule3("_md5", md5_functions, module_doc);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ PyDict_SetItemString(d, "MD5Type", (PyObject *)&MD5type);
+ PyModule_AddIntConstant(m, "digest_size", 16);
+ /* No need to check the error here, the caller will do that */
}
diff --git a/Modules/mmapmodule.c b/Modules/mmapmodule.c
index 5e0b3ad..1acd1d8 100644
--- a/Modules/mmapmodule.c
+++ b/Modules/mmapmodule.c
@@ -30,18 +30,18 @@
static int
my_getpagesize(void)
{
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- return si.dwPageSize;
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwPageSize;
}
static int
my_getallocationgranularity (void)
{
- SYSTEM_INFO si;
- GetSystemInfo(&si);
- return si.dwAllocationGranularity;
+ SYSTEM_INFO si;
+ GetSystemInfo(&si);
+ return si.dwAllocationGranularity;
}
#endif
@@ -54,7 +54,7 @@ my_getallocationgranularity (void)
static int
my_getpagesize(void)
{
- return sysconf(_SC_PAGESIZE);
+ return sysconf(_SC_PAGESIZE);
}
#define my_getallocationgranularity my_getpagesize
@@ -79,30 +79,30 @@ static PyObject *mmap_module_error;
typedef enum
{
- ACCESS_DEFAULT,
- ACCESS_READ,
- ACCESS_WRITE,
- ACCESS_COPY
+ ACCESS_DEFAULT,
+ ACCESS_READ,
+ ACCESS_WRITE,
+ ACCESS_COPY
} access_mode;
typedef struct {
- PyObject_HEAD
- char * data;
- size_t size;
- size_t pos; /* relative to offset */
- size_t offset;
+ PyObject_HEAD
+ char * data;
+ size_t size;
+ size_t pos; /* relative to offset */
+ size_t offset;
#ifdef MS_WINDOWS
- HANDLE map_handle;
- HANDLE file_handle;
- char * tagname;
+ HANDLE map_handle;
+ HANDLE file_handle;
+ char * tagname;
#endif
#ifdef UNIX
- int fd;
+ int fd;
#endif
- access_mode access;
+ access_mode access;
} mmap_object;
@@ -110,321 +110,321 @@ static void
mmap_object_dealloc(mmap_object *m_obj)
{
#ifdef MS_WINDOWS
- if (m_obj->data != NULL)
- UnmapViewOfFile (m_obj->data);
- if (m_obj->map_handle != NULL)
- CloseHandle (m_obj->map_handle);
- if (m_obj->file_handle != INVALID_HANDLE_VALUE)
- CloseHandle (m_obj->file_handle);
- if (m_obj->tagname)
- PyMem_Free(m_obj->tagname);
+ if (m_obj->data != NULL)
+ UnmapViewOfFile (m_obj->data);
+ if (m_obj->map_handle != NULL)
+ CloseHandle (m_obj->map_handle);
+ if (m_obj->file_handle != INVALID_HANDLE_VALUE)
+ CloseHandle (m_obj->file_handle);
+ if (m_obj->tagname)
+ PyMem_Free(m_obj->tagname);
#endif /* MS_WINDOWS */
#ifdef UNIX
- if (m_obj->fd >= 0)
- (void) close(m_obj->fd);
- if (m_obj->data!=NULL) {
- msync(m_obj->data, m_obj->size, MS_SYNC);
- munmap(m_obj->data, m_obj->size);
- }
+ if (m_obj->fd >= 0)
+ (void) close(m_obj->fd);
+ if (m_obj->data!=NULL) {
+ msync(m_obj->data, m_obj->size, MS_SYNC);
+ munmap(m_obj->data, m_obj->size);
+ }
#endif /* UNIX */
- Py_TYPE(m_obj)->tp_free((PyObject*)m_obj);
+ Py_TYPE(m_obj)->tp_free((PyObject*)m_obj);
}
static PyObject *
mmap_close_method(mmap_object *self, PyObject *unused)
{
#ifdef MS_WINDOWS
- /* For each resource we maintain, we need to check
- the value is valid, and if so, free the resource
- and set the member value to an invalid value so
- the dealloc does not attempt to resource clearing
- again.
- TODO - should we check for errors in the close operations???
- */
- if (self->data != NULL) {
- UnmapViewOfFile(self->data);
- self->data = NULL;
- }
- if (self->map_handle != NULL) {
- CloseHandle(self->map_handle);
- self->map_handle = NULL;
- }
- if (self->file_handle != INVALID_HANDLE_VALUE) {
- CloseHandle(self->file_handle);
- self->file_handle = INVALID_HANDLE_VALUE;
- }
+ /* For each resource we maintain, we need to check
+ the value is valid, and if so, free the resource
+ and set the member value to an invalid value so
+ the dealloc does not attempt to resource clearing
+ again.
+ TODO - should we check for errors in the close operations???
+ */
+ if (self->data != NULL) {
+ UnmapViewOfFile(self->data);
+ self->data = NULL;
+ }
+ if (self->map_handle != NULL) {
+ CloseHandle(self->map_handle);
+ self->map_handle = NULL;
+ }
+ if (self->file_handle != INVALID_HANDLE_VALUE) {
+ CloseHandle(self->file_handle);
+ self->file_handle = INVALID_HANDLE_VALUE;
+ }
#endif /* MS_WINDOWS */
#ifdef UNIX
- if (0 <= self->fd)
- (void) close(self->fd);
- self->fd = -1;
- if (self->data != NULL) {
- munmap(self->data, self->size);
- self->data = NULL;
- }
+ if (0 <= self->fd)
+ (void) close(self->fd);
+ self->fd = -1;
+ if (self->data != NULL) {
+ munmap(self->data, self->size);
+ self->data = NULL;
+ }
#endif
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef MS_WINDOWS
-#define CHECK_VALID(err) \
-do { \
- if (self->map_handle == NULL) { \
- PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
- return err; \
- } \
+#define CHECK_VALID(err) \
+do { \
+ if (self->map_handle == NULL) { \
+ PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
+ return err; \
+ } \
} while (0)
#endif /* MS_WINDOWS */
#ifdef UNIX
-#define CHECK_VALID(err) \
-do { \
- if (self->data == NULL) { \
- PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
- return err; \
- } \
+#define CHECK_VALID(err) \
+do { \
+ if (self->data == NULL) { \
+ PyErr_SetString(PyExc_ValueError, "mmap closed or invalid"); \
+ return err; \
+ } \
} while (0)
#endif /* UNIX */
static PyObject *
mmap_read_byte_method(mmap_object *self,
- PyObject *unused)
+ PyObject *unused)
{
- CHECK_VALID(NULL);
- if (self->pos < self->size) {
- char value = self->data[self->pos];
- self->pos += 1;
- return Py_BuildValue("c", value);
- } else {
- PyErr_SetString(PyExc_ValueError, "read byte out of range");
- return NULL;
- }
+ CHECK_VALID(NULL);
+ if (self->pos < self->size) {
+ char value = self->data[self->pos];
+ self->pos += 1;
+ return Py_BuildValue("c", value);
+ } else {
+ PyErr_SetString(PyExc_ValueError, "read byte out of range");
+ return NULL;
+ }
}
static PyObject *
mmap_read_line_method(mmap_object *self,
- PyObject *unused)
+ PyObject *unused)
{
- char *start = self->data+self->pos;
- char *eof = self->data+self->size;
- char *eol;
- PyObject *result;
-
- CHECK_VALID(NULL);
-
- eol = memchr(start, '\n', self->size - self->pos);
- if (!eol)
- eol = eof;
- else
- ++eol; /* we're interested in the position after the
- newline. */
- result = PyString_FromStringAndSize(start, (eol - start));
- self->pos += (eol - start);
- return result;
+ char *start = self->data+self->pos;
+ char *eof = self->data+self->size;
+ char *eol;
+ PyObject *result;
+
+ CHECK_VALID(NULL);
+
+ eol = memchr(start, '\n', self->size - self->pos);
+ if (!eol)
+ eol = eof;
+ else
+ ++eol; /* we're interested in the position after the
+ newline. */
+ result = PyString_FromStringAndSize(start, (eol - start));
+ self->pos += (eol - start);
+ return result;
}
static PyObject *
mmap_read_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- Py_ssize_t num_bytes, n;
- PyObject *result;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "n:read", &num_bytes))
- return(NULL);
-
- /* silently 'adjust' out-of-range requests */
- assert(self->size >= self->pos);
- n = self->size - self->pos;
- /* The difference can overflow, only if self->size is greater than
- * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed,
- * because the mapped area and the returned string each need more
- * than half of the addressable memory. So we clip the size, and let
- * the code below raise MemoryError.
- */
- if (n < 0)
- n = PY_SSIZE_T_MAX;
- if (num_bytes < 0 || num_bytes > n) {
- num_bytes = n;
- }
- result = Py_BuildValue("s#", self->data+self->pos, num_bytes);
- self->pos += num_bytes;
- return result;
+ Py_ssize_t num_bytes, n;
+ PyObject *result;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "n:read", &num_bytes))
+ return(NULL);
+
+ /* silently 'adjust' out-of-range requests */
+ assert(self->size >= self->pos);
+ n = self->size - self->pos;
+ /* The difference can overflow, only if self->size is greater than
+ * PY_SSIZE_T_MAX. But then the operation cannot possibly succeed,
+ * because the mapped area and the returned string each need more
+ * than half of the addressable memory. So we clip the size, and let
+ * the code below raise MemoryError.
+ */
+ if (n < 0)
+ n = PY_SSIZE_T_MAX;
+ if (num_bytes < 0 || num_bytes > n) {
+ num_bytes = n;
+ }
+ result = Py_BuildValue("s#", self->data+self->pos, num_bytes);
+ self->pos += num_bytes;
+ return result;
}
static PyObject *
mmap_gfind(mmap_object *self,
- PyObject *args,
- int reverse)
+ PyObject *args,
+ int reverse)
{
- Py_ssize_t start = self->pos;
- Py_ssize_t end = self->size;
- const char *needle;
- Py_ssize_t len;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, reverse ? "s#|nn:rfind" : "s#|nn:find",
- &needle, &len, &start, &end)) {
- return NULL;
- } else {
- const char *p, *start_p, *end_p;
- int sign = reverse ? -1 : 1;
-
- if (start < 0)
- start += self->size;
- if (start < 0)
- start = 0;
- else if ((size_t)start > self->size)
- start = self->size;
-
- if (end < 0)
- end += self->size;
- if (end < 0)
- end = 0;
- else if ((size_t)end > self->size)
- end = self->size;
-
- start_p = self->data + start;
- end_p = self->data + end;
-
- for (p = (reverse ? end_p - len : start_p);
- (p >= start_p) && (p + len <= end_p); p += sign) {
- Py_ssize_t i;
- for (i = 0; i < len && needle[i] == p[i]; ++i)
- /* nothing */;
- if (i == len) {
- return PyInt_FromSsize_t(p - self->data);
- }
- }
- return PyInt_FromLong(-1);
- }
+ Py_ssize_t start = self->pos;
+ Py_ssize_t end = self->size;
+ const char *needle;
+ Py_ssize_t len;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, reverse ? "s#|nn:rfind" : "s#|nn:find",
+ &needle, &len, &start, &end)) {
+ return NULL;
+ } else {
+ const char *p, *start_p, *end_p;
+ int sign = reverse ? -1 : 1;
+
+ if (start < 0)
+ start += self->size;
+ if (start < 0)
+ start = 0;
+ else if ((size_t)start > self->size)
+ start = self->size;
+
+ if (end < 0)
+ end += self->size;
+ if (end < 0)
+ end = 0;
+ else if ((size_t)end > self->size)
+ end = self->size;
+
+ start_p = self->data + start;
+ end_p = self->data + end;
+
+ for (p = (reverse ? end_p - len : start_p);
+ (p >= start_p) && (p + len <= end_p); p += sign) {
+ Py_ssize_t i;
+ for (i = 0; i < len && needle[i] == p[i]; ++i)
+ /* nothing */;
+ if (i == len) {
+ return PyInt_FromSsize_t(p - self->data);
+ }
+ }
+ return PyInt_FromLong(-1);
+ }
}
static PyObject *
mmap_find_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- return mmap_gfind(self, args, 0);
+ return mmap_gfind(self, args, 0);
}
static PyObject *
mmap_rfind_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- return mmap_gfind(self, args, 1);
+ return mmap_gfind(self, args, 1);
}
static int
is_writeable(mmap_object *self)
{
- if (self->access != ACCESS_READ)
- return 1;
- PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
- return 0;
+ if (self->access != ACCESS_READ)
+ return 1;
+ PyErr_Format(PyExc_TypeError, "mmap can't modify a readonly memory map.");
+ return 0;
}
static int
is_resizeable(mmap_object *self)
{
- if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
- return 1;
- PyErr_Format(PyExc_TypeError,
- "mmap can't resize a readonly or copy-on-write memory map.");
- return 0;
+ if ((self->access == ACCESS_WRITE) || (self->access == ACCESS_DEFAULT))
+ return 1;
+ PyErr_Format(PyExc_TypeError,
+ "mmap can't resize a readonly or copy-on-write memory map.");
+ return 0;
}
static PyObject *
mmap_write_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- Py_ssize_t length;
- char *data;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "s#:write", &data, &length))
- return(NULL);
-
- if (!is_writeable(self))
- return NULL;
-
- if ((self->pos + length) > self->size) {
- PyErr_SetString(PyExc_ValueError, "data out of range");
- return NULL;
- }
- memcpy(self->data+self->pos, data, length);
- self->pos = self->pos+length;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_ssize_t length;
+ char *data;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "s#:write", &data, &length))
+ return(NULL);
+
+ if (!is_writeable(self))
+ return NULL;
+
+ if ((self->pos + length) > self->size) {
+ PyErr_SetString(PyExc_ValueError, "data out of range");
+ return NULL;
+ }
+ memcpy(self->data+self->pos, data, length);
+ self->pos = self->pos+length;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
mmap_write_byte_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- char value;
-
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "c:write_byte", &value))
- return(NULL);
-
- if (!is_writeable(self))
- return NULL;
-
- if (self->pos < self->size) {
- *(self->data+self->pos) = value;
- self->pos += 1;
- Py_INCREF(Py_None);
- return Py_None;
- }
- else {
- PyErr_SetString(PyExc_ValueError, "write byte out of range");
- return NULL;
- }
+ char value;
+
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "c:write_byte", &value))
+ return(NULL);
+
+ if (!is_writeable(self))
+ return NULL;
+
+ if (self->pos < self->size) {
+ *(self->data+self->pos) = value;
+ self->pos += 1;
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError, "write byte out of range");
+ return NULL;
+ }
}
static PyObject *
mmap_size_method(mmap_object *self,
- PyObject *unused)
+ PyObject *unused)
{
- CHECK_VALID(NULL);
+ CHECK_VALID(NULL);
#ifdef MS_WINDOWS
- if (self->file_handle != INVALID_HANDLE_VALUE) {
- DWORD low,high;
- PY_LONG_LONG size;
- low = GetFileSize(self->file_handle, &high);
- if (low == INVALID_FILE_SIZE) {
- /* It might be that the function appears to have failed,
- when indeed its size equals INVALID_FILE_SIZE */
- DWORD error = GetLastError();
- if (error != NO_ERROR)
- return PyErr_SetFromWindowsErr(error);
- }
- if (!high && low < LONG_MAX)
- return PyInt_FromLong((long)low);
- size = (((PY_LONG_LONG)high)<<32) + low;
- return PyLong_FromLongLong(size);
- } else {
- return PyInt_FromSsize_t(self->size);
- }
+ if (self->file_handle != INVALID_HANDLE_VALUE) {
+ DWORD low,high;
+ PY_LONG_LONG size;
+ low = GetFileSize(self->file_handle, &high);
+ if (low == INVALID_FILE_SIZE) {
+ /* It might be that the function appears to have failed,
+ when indeed its size equals INVALID_FILE_SIZE */
+ DWORD error = GetLastError();
+ if (error != NO_ERROR)
+ return PyErr_SetFromWindowsErr(error);
+ }
+ if (!high && low < LONG_MAX)
+ return PyInt_FromLong((long)low);
+ size = (((PY_LONG_LONG)high)<<32) + low;
+ return PyLong_FromLongLong(size);
+ } else {
+ return PyInt_FromSsize_t(self->size);
+ }
#endif /* MS_WINDOWS */
#ifdef UNIX
- {
- struct stat buf;
- if (-1 == fstat(self->fd, &buf)) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- return PyInt_FromSsize_t(buf.st_size);
- }
+ {
+ struct stat buf;
+ if (-1 == fstat(self->fd, &buf)) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ return PyInt_FromSsize_t(buf.st_size);
+ }
#endif /* UNIX */
}
@@ -439,223 +439,223 @@ mmap_size_method(mmap_object *self,
static PyObject *
mmap_resize_method(mmap_object *self,
- PyObject *args)
+ PyObject *args)
{
- Py_ssize_t new_size;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
- !is_resizeable(self)) {
- return NULL;
+ Py_ssize_t new_size;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "n:resize", &new_size) ||
+ !is_resizeable(self)) {
+ return NULL;
#ifdef MS_WINDOWS
- } else {
- DWORD dwErrCode = 0;
- DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
- /* First, unmap the file view */
- UnmapViewOfFile(self->data);
- self->data = NULL;
- /* Close the mapping object */
- CloseHandle(self->map_handle);
- self->map_handle = NULL;
- /* Move to the desired EOF position */
+ } else {
+ DWORD dwErrCode = 0;
+ DWORD off_hi, off_lo, newSizeLow, newSizeHigh;
+ /* First, unmap the file view */
+ UnmapViewOfFile(self->data);
+ self->data = NULL;
+ /* Close the mapping object */
+ CloseHandle(self->map_handle);
+ self->map_handle = NULL;
+ /* Move to the desired EOF position */
#if SIZEOF_SIZE_T > 4
- newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
- newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
- off_hi = (DWORD)(self->offset >> 32);
- off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
+ newSizeHigh = (DWORD)((self->offset + new_size) >> 32);
+ newSizeLow = (DWORD)((self->offset + new_size) & 0xFFFFFFFF);
+ off_hi = (DWORD)(self->offset >> 32);
+ off_lo = (DWORD)(self->offset & 0xFFFFFFFF);
#else
- newSizeHigh = 0;
- newSizeLow = (DWORD)(self->offset + new_size);
- off_hi = 0;
- off_lo = (DWORD)self->offset;
+ newSizeHigh = 0;
+ newSizeLow = (DWORD)(self->offset + new_size);
+ off_hi = 0;
+ off_lo = (DWORD)self->offset;
#endif
- SetFilePointer(self->file_handle,
- newSizeLow, &newSizeHigh, FILE_BEGIN);
- /* Change the size of the file */
- SetEndOfFile(self->file_handle);
- /* Create another mapping object and remap the file view */
- self->map_handle = CreateFileMapping(
- self->file_handle,
- NULL,
- PAGE_READWRITE,
- 0,
- 0,
- self->tagname);
- if (self->map_handle != NULL) {
- self->data = (char *) MapViewOfFile(self->map_handle,
- FILE_MAP_WRITE,
- off_hi,
- off_lo,
- new_size);
- if (self->data != NULL) {
- self->size = new_size;
- Py_INCREF(Py_None);
- return Py_None;
- } else {
- dwErrCode = GetLastError();
- CloseHandle(self->map_handle);
- self->map_handle = NULL;
- }
- } else {
- dwErrCode = GetLastError();
- }
- PyErr_SetFromWindowsErr(dwErrCode);
- return NULL;
+ SetFilePointer(self->file_handle,
+ newSizeLow, &newSizeHigh, FILE_BEGIN);
+ /* Change the size of the file */
+ SetEndOfFile(self->file_handle);
+ /* Create another mapping object and remap the file view */
+ self->map_handle = CreateFileMapping(
+ self->file_handle,
+ NULL,
+ PAGE_READWRITE,
+ 0,
+ 0,
+ self->tagname);
+ if (self->map_handle != NULL) {
+ self->data = (char *) MapViewOfFile(self->map_handle,
+ FILE_MAP_WRITE,
+ off_hi,
+ off_lo,
+ new_size);
+ if (self->data != NULL) {
+ self->size = new_size;
+ Py_INCREF(Py_None);
+ return Py_None;
+ } else {
+ dwErrCode = GetLastError();
+ CloseHandle(self->map_handle);
+ self->map_handle = NULL;
+ }
+ } else {
+ dwErrCode = GetLastError();
+ }
+ PyErr_SetFromWindowsErr(dwErrCode);
+ return NULL;
#endif /* MS_WINDOWS */
#ifdef UNIX
#ifndef HAVE_MREMAP
- } else {
- PyErr_SetString(PyExc_SystemError,
- "mmap: resizing not available--no mremap()");
- return NULL;
+ } else {
+ PyErr_SetString(PyExc_SystemError,
+ "mmap: resizing not available--no mremap()");
+ return NULL;
#else
- } else {
- void *newmap;
+ } else {
+ void *newmap;
- if (ftruncate(self->fd, self->offset + new_size) == -1) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
+ if (ftruncate(self->fd, self->offset + new_size) == -1) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
#ifdef MREMAP_MAYMOVE
- newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
+ newmap = mremap(self->data, self->size, new_size, MREMAP_MAYMOVE);
#else
- #if defined(__NetBSD__)
- newmap = mremap(self->data, self->size, self->data, new_size, 0);
- #else
- newmap = mremap(self->data, self->size, new_size, 0);
- #endif /* __NetBSD__ */
+ #if defined(__NetBSD__)
+ newmap = mremap(self->data, self->size, self->data, new_size, 0);
+ #else
+ newmap = mremap(self->data, self->size, new_size, 0);
+ #endif /* __NetBSD__ */
#endif
- if (newmap == (void *)-1)
- {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- self->data = newmap;
- self->size = new_size;
- Py_INCREF(Py_None);
- return Py_None;
+ if (newmap == (void *)-1)
+ {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ self->data = newmap;
+ self->size = new_size;
+ Py_INCREF(Py_None);
+ return Py_None;
#endif /* HAVE_MREMAP */
#endif /* UNIX */
- }
+ }
}
static PyObject *
mmap_tell_method(mmap_object *self, PyObject *unused)
{
- CHECK_VALID(NULL);
- return PyInt_FromSize_t(self->pos);
+ CHECK_VALID(NULL);
+ return PyInt_FromSize_t(self->pos);
}
static PyObject *
mmap_flush_method(mmap_object *self, PyObject *args)
{
- Py_ssize_t offset = 0;
- Py_ssize_t size = self->size;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
- return NULL;
- if ((size_t)(offset + size) > self->size) {
- PyErr_SetString(PyExc_ValueError, "flush values out of range");
- return NULL;
- }
+ Py_ssize_t offset = 0;
+ Py_ssize_t size = self->size;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "|nn:flush", &offset, &size))
+ return NULL;
+ if ((size_t)(offset + size) > self->size) {
+ PyErr_SetString(PyExc_ValueError, "flush values out of range");
+ return NULL;
+ }
#ifdef MS_WINDOWS
- return PyInt_FromLong((long) FlushViewOfFile(self->data+offset, size));
+ return PyInt_FromLong((long) FlushViewOfFile(self->data+offset, size));
#elif defined(UNIX)
- /* XXX semantics of return value? */
- /* XXX flags for msync? */
- if (-1 == msync(self->data + offset, size, MS_SYNC)) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- return PyInt_FromLong(0);
+ /* XXX semantics of return value? */
+ /* XXX flags for msync? */
+ if (-1 == msync(self->data + offset, size, MS_SYNC)) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ return PyInt_FromLong(0);
#else
- PyErr_SetString(PyExc_ValueError, "flush not supported on this system");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "flush not supported on this system");
+ return NULL;
#endif
}
static PyObject *
mmap_seek_method(mmap_object *self, PyObject *args)
{
- Py_ssize_t dist;
- int how=0;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
- return NULL;
- else {
- size_t where;
- switch (how) {
- case 0: /* relative to start */
- if (dist < 0)
- goto onoutofrange;
- where = dist;
- break;
- case 1: /* relative to current position */
- if ((Py_ssize_t)self->pos + dist < 0)
- goto onoutofrange;
- where = self->pos + dist;
- break;
- case 2: /* relative to end */
- if ((Py_ssize_t)self->size + dist < 0)
- goto onoutofrange;
- where = self->size + dist;
- break;
- default:
- PyErr_SetString(PyExc_ValueError, "unknown seek type");
- return NULL;
- }
- if (where > self->size)
- goto onoutofrange;
- self->pos = where;
- Py_INCREF(Py_None);
- return Py_None;
- }
+ Py_ssize_t dist;
+ int how=0;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "n|i:seek", &dist, &how))
+ return NULL;
+ else {
+ size_t where;
+ switch (how) {
+ case 0: /* relative to start */
+ if (dist < 0)
+ goto onoutofrange;
+ where = dist;
+ break;
+ case 1: /* relative to current position */
+ if ((Py_ssize_t)self->pos + dist < 0)
+ goto onoutofrange;
+ where = self->pos + dist;
+ break;
+ case 2: /* relative to end */
+ if ((Py_ssize_t)self->size + dist < 0)
+ goto onoutofrange;
+ where = self->size + dist;
+ break;
+ default:
+ PyErr_SetString(PyExc_ValueError, "unknown seek type");
+ return NULL;
+ }
+ if (where > self->size)
+ goto onoutofrange;
+ self->pos = where;
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
onoutofrange:
- PyErr_SetString(PyExc_ValueError, "seek out of range");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "seek out of range");
+ return NULL;
}
static PyObject *
mmap_move_method(mmap_object *self, PyObject *args)
{
- unsigned long dest, src, cnt;
- CHECK_VALID(NULL);
- if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) ||
- !is_writeable(self)) {
- return NULL;
- } else {
- /* bounds check the values */
- if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt ||
- src < 0 || src > self->size || (src + cnt) > self->size ||
- dest < 0 || dest > self->size || (dest + cnt) > self->size) {
- PyErr_SetString(PyExc_ValueError,
- "source, destination, or count out of range");
- return NULL;
- }
- memmove(self->data+dest, self->data+src, cnt);
- Py_INCREF(Py_None);
- return Py_None;
- }
+ unsigned long dest, src, cnt;
+ CHECK_VALID(NULL);
+ if (!PyArg_ParseTuple(args, "kkk:move", &dest, &src, &cnt) ||
+ !is_writeable(self)) {
+ return NULL;
+ } else {
+ /* bounds check the values */
+ if (cnt < 0 || (cnt + dest) < cnt || (cnt + src) < cnt ||
+ src < 0 || src > self->size || (src + cnt) > self->size ||
+ dest < 0 || dest > self->size || (dest + cnt) > self->size) {
+ PyErr_SetString(PyExc_ValueError,
+ "source, destination, or count out of range");
+ return NULL;
+ }
+ memmove(self->data+dest, self->data+src, cnt);
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
}
static struct PyMethodDef mmap_object_methods[] = {
- {"close", (PyCFunction) mmap_close_method, METH_NOARGS},
- {"find", (PyCFunction) mmap_find_method, METH_VARARGS},
- {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS},
- {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS},
- {"move", (PyCFunction) mmap_move_method, METH_VARARGS},
- {"read", (PyCFunction) mmap_read_method, METH_VARARGS},
- {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS},
- {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS},
- {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS},
- {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS},
- {"size", (PyCFunction) mmap_size_method, METH_NOARGS},
- {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS},
- {"write", (PyCFunction) mmap_write_method, METH_VARARGS},
- {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"close", (PyCFunction) mmap_close_method, METH_NOARGS},
+ {"find", (PyCFunction) mmap_find_method, METH_VARARGS},
+ {"rfind", (PyCFunction) mmap_rfind_method, METH_VARARGS},
+ {"flush", (PyCFunction) mmap_flush_method, METH_VARARGS},
+ {"move", (PyCFunction) mmap_move_method, METH_VARARGS},
+ {"read", (PyCFunction) mmap_read_method, METH_VARARGS},
+ {"read_byte", (PyCFunction) mmap_read_byte_method, METH_NOARGS},
+ {"readline", (PyCFunction) mmap_read_line_method, METH_NOARGS},
+ {"resize", (PyCFunction) mmap_resize_method, METH_VARARGS},
+ {"seek", (PyCFunction) mmap_seek_method, METH_VARARGS},
+ {"size", (PyCFunction) mmap_size_method, METH_NOARGS},
+ {"tell", (PyCFunction) mmap_tell_method, METH_NOARGS},
+ {"write", (PyCFunction) mmap_write_method, METH_VARARGS},
+ {"write_byte", (PyCFunction) mmap_write_byte_method, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
/* Functions for treating an mmap'ed file as a buffer */
@@ -663,337 +663,337 @@ static struct PyMethodDef mmap_object_methods[] = {
static Py_ssize_t
mmap_buffer_getreadbuf(mmap_object *self, Py_ssize_t index, const void **ptr)
{
- CHECK_VALID(-1);
- if (index != 0) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent mmap segment");
- return -1;
- }
- *ptr = self->data;
- return self->size;
+ CHECK_VALID(-1);
+ if (index != 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent mmap segment");
+ return -1;
+ }
+ *ptr = self->data;
+ return self->size;
}
static Py_ssize_t
mmap_buffer_getwritebuf(mmap_object *self, Py_ssize_t index, const void **ptr)
{
- CHECK_VALID(-1);
- if (index != 0) {
- PyErr_SetString(PyExc_SystemError,
- "Accessing non-existent mmap segment");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- *ptr = self->data;
- return self->size;
+ CHECK_VALID(-1);
+ if (index != 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "Accessing non-existent mmap segment");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ *ptr = self->data;
+ return self->size;
}
static Py_ssize_t
mmap_buffer_getsegcount(mmap_object *self, Py_ssize_t *lenp)
{
- CHECK_VALID(-1);
- if (lenp)
- *lenp = self->size;
- return 1;
+ CHECK_VALID(-1);
+ if (lenp)
+ *lenp = self->size;
+ return 1;
}
static Py_ssize_t
mmap_buffer_getcharbuffer(mmap_object *self, Py_ssize_t index, const void **ptr)
{
- if (index != 0) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent buffer segment");
- return -1;
- }
- *ptr = (const char *)self->data;
- return self->size;
+ if (index != 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent buffer segment");
+ return -1;
+ }
+ *ptr = (const char *)self->data;
+ return self->size;
}
static Py_ssize_t
mmap_length(mmap_object *self)
{
- CHECK_VALID(-1);
- return self->size;
+ CHECK_VALID(-1);
+ return self->size;
}
static PyObject *
mmap_item(mmap_object *self, Py_ssize_t i)
{
- CHECK_VALID(NULL);
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError, "mmap index out of range");
- return NULL;
- }
- return PyString_FromStringAndSize(self->data + i, 1);
+ CHECK_VALID(NULL);
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError, "mmap index out of range");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(self->data + i, 1);
}
static PyObject *
mmap_slice(mmap_object *self, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- CHECK_VALID(NULL);
- if (ilow < 0)
- ilow = 0;
- else if ((size_t)ilow > self->size)
- ilow = self->size;
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if ((size_t)ihigh > self->size)
- ihigh = self->size;
-
- return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
+ CHECK_VALID(NULL);
+ if (ilow < 0)
+ ilow = 0;
+ else if ((size_t)ilow > self->size)
+ ilow = self->size;
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if ((size_t)ihigh > self->size)
+ ihigh = self->size;
+
+ return PyString_FromStringAndSize(self->data + ilow, ihigh-ilow);
}
static PyObject *
mmap_subscript(mmap_object *self, PyObject *item)
{
- CHECK_VALID(NULL);
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += self->size;
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError,
- "mmap index out of range");
- return NULL;
- }
- return PyString_FromStringAndSize(self->data + i, 1);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item, self->size,
- &start, &stop, &step, &slicelen) < 0) {
- return NULL;
- }
-
- if (slicelen <= 0)
- return PyString_FromStringAndSize("", 0);
- else if (step == 1)
- return PyString_FromStringAndSize(self->data + start,
- slicelen);
- else {
- char *result_buf = (char *)PyMem_Malloc(slicelen);
- Py_ssize_t cur, i;
- PyObject *result;
-
- if (result_buf == NULL)
- return PyErr_NoMemory();
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- result_buf[i] = self->data[cur];
- }
- result = PyString_FromStringAndSize(result_buf,
- slicelen);
- PyMem_Free(result_buf);
- return result;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "mmap indices must be integers");
- return NULL;
- }
+ CHECK_VALID(NULL);
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += self->size;
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap index out of range");
+ return NULL;
+ }
+ return PyString_FromStringAndSize(self->data + i, 1);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item, self->size,
+ &start, &stop, &step, &slicelen) < 0) {
+ return NULL;
+ }
+
+ if (slicelen <= 0)
+ return PyString_FromStringAndSize("", 0);
+ else if (step == 1)
+ return PyString_FromStringAndSize(self->data + start,
+ slicelen);
+ else {
+ char *result_buf = (char *)PyMem_Malloc(slicelen);
+ Py_ssize_t cur, i;
+ PyObject *result;
+
+ if (result_buf == NULL)
+ return PyErr_NoMemory();
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ result_buf[i] = self->data[cur];
+ }
+ result = PyString_FromStringAndSize(result_buf,
+ slicelen);
+ PyMem_Free(result_buf);
+ return result;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap indices must be integers");
+ return NULL;
+ }
}
static PyObject *
mmap_concat(mmap_object *self, PyObject *bb)
{
- CHECK_VALID(NULL);
- PyErr_SetString(PyExc_SystemError,
- "mmaps don't support concatenation");
- return NULL;
+ CHECK_VALID(NULL);
+ PyErr_SetString(PyExc_SystemError,
+ "mmaps don't support concatenation");
+ return NULL;
}
static PyObject *
mmap_repeat(mmap_object *self, Py_ssize_t n)
{
- CHECK_VALID(NULL);
- PyErr_SetString(PyExc_SystemError,
- "mmaps don't support repeat operation");
- return NULL;
+ CHECK_VALID(NULL);
+ PyErr_SetString(PyExc_SystemError,
+ "mmaps don't support repeat operation");
+ return NULL;
}
static int
mmap_ass_slice(mmap_object *self, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
- const char *buf;
-
- CHECK_VALID(-1);
- if (ilow < 0)
- ilow = 0;
- else if ((size_t)ilow > self->size)
- ilow = self->size;
- if (ihigh < 0)
- ihigh = 0;
- if (ihigh < ilow)
- ihigh = ilow;
- else if ((size_t)ihigh > self->size)
- ihigh = self->size;
-
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support slice deletion");
- return -1;
- }
- if (! (PyString_Check(v)) ) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment must be a string");
- return -1;
- }
- if (PyString_Size(v) != (ihigh - ilow)) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment is wrong size");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- buf = PyString_AsString(v);
- memcpy(self->data + ilow, buf, ihigh-ilow);
- return 0;
+ const char *buf;
+
+ CHECK_VALID(-1);
+ if (ilow < 0)
+ ilow = 0;
+ else if ((size_t)ilow > self->size)
+ ilow = self->size;
+ if (ihigh < 0)
+ ihigh = 0;
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if ((size_t)ihigh > self->size)
+ ihigh = self->size;
+
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support slice deletion");
+ return -1;
+ }
+ if (! (PyString_Check(v)) ) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment must be a string");
+ return -1;
+ }
+ if (PyString_Size(v) != (ihigh - ilow)) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment is wrong size");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ buf = PyString_AsString(v);
+ memcpy(self->data + ilow, buf, ihigh-ilow);
+ return 0;
}
static int
mmap_ass_item(mmap_object *self, Py_ssize_t i, PyObject *v)
{
- const char *buf;
-
- CHECK_VALID(-1);
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError, "mmap index out of range");
- return -1;
- }
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support item deletion");
- return -1;
- }
- if (! (PyString_Check(v) && PyString_Size(v)==1) ) {
- PyErr_SetString(PyExc_IndexError,
- "mmap assignment must be single-character string");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- buf = PyString_AsString(v);
- self->data[i] = buf[0];
- return 0;
+ const char *buf;
+
+ CHECK_VALID(-1);
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError, "mmap index out of range");
+ return -1;
+ }
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support item deletion");
+ return -1;
+ }
+ if (! (PyString_Check(v) && PyString_Size(v)==1) ) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap assignment must be single-character string");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ buf = PyString_AsString(v);
+ self->data[i] = buf[0];
+ return 0;
}
static int
mmap_ass_subscript(mmap_object *self, PyObject *item, PyObject *value)
{
- CHECK_VALID(-1);
-
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- const char *buf;
-
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += self->size;
- if (i < 0 || (size_t)i >= self->size) {
- PyErr_SetString(PyExc_IndexError,
- "mmap index out of range");
- return -1;
- }
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support item deletion");
- return -1;
- }
- if (!PyString_Check(value) || PyString_Size(value) != 1) {
- PyErr_SetString(PyExc_IndexError,
- "mmap assignment must be single-character string");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
- buf = PyString_AsString(value);
- self->data[i] = buf[0];
- return 0;
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- self->size, &start, &stop,
- &step, &slicelen) < 0) {
- return -1;
- }
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "mmap object doesn't support slice deletion");
- return -1;
- }
- if (!PyString_Check(value)) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment must be a string");
- return -1;
- }
- if (PyString_Size(value) != slicelen) {
- PyErr_SetString(PyExc_IndexError,
- "mmap slice assignment is wrong size");
- return -1;
- }
- if (!is_writeable(self))
- return -1;
-
- if (slicelen == 0)
- return 0;
- else if (step == 1) {
- const char *buf = PyString_AsString(value);
-
- if (buf == NULL)
- return -1;
- memcpy(self->data + start, buf, slicelen);
- return 0;
- }
- else {
- Py_ssize_t cur, i;
- const char *buf = PyString_AsString(value);
-
- if (buf == NULL)
- return -1;
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- self->data[cur] = buf[i];
- }
- return 0;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "mmap indices must be integer");
- return -1;
- }
+ CHECK_VALID(-1);
+
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ const char *buf;
+
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += self->size;
+ if (i < 0 || (size_t)i >= self->size) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap index out of range");
+ return -1;
+ }
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support item deletion");
+ return -1;
+ }
+ if (!PyString_Check(value) || PyString_Size(value) != 1) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap assignment must be single-character string");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+ buf = PyString_AsString(value);
+ self->data[i] = buf[0];
+ return 0;
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ self->size, &start, &stop,
+ &step, &slicelen) < 0) {
+ return -1;
+ }
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap object doesn't support slice deletion");
+ return -1;
+ }
+ if (!PyString_Check(value)) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment must be a string");
+ return -1;
+ }
+ if (PyString_Size(value) != slicelen) {
+ PyErr_SetString(PyExc_IndexError,
+ "mmap slice assignment is wrong size");
+ return -1;
+ }
+ if (!is_writeable(self))
+ return -1;
+
+ if (slicelen == 0)
+ return 0;
+ else if (step == 1) {
+ const char *buf = PyString_AsString(value);
+
+ if (buf == NULL)
+ return -1;
+ memcpy(self->data + start, buf, slicelen);
+ return 0;
+ }
+ else {
+ Py_ssize_t cur, i;
+ const char *buf = PyString_AsString(value);
+
+ if (buf == NULL)
+ return -1;
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ self->data[cur] = buf[i];
+ }
+ return 0;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "mmap indices must be integer");
+ return -1;
+ }
}
static PySequenceMethods mmap_as_sequence = {
- (lenfunc)mmap_length, /*sq_length*/
- (binaryfunc)mmap_concat, /*sq_concat*/
- (ssizeargfunc)mmap_repeat, /*sq_repeat*/
- (ssizeargfunc)mmap_item, /*sq_item*/
- (ssizessizeargfunc)mmap_slice, /*sq_slice*/
- (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
- (ssizessizeobjargproc)mmap_ass_slice, /*sq_ass_slice*/
+ (lenfunc)mmap_length, /*sq_length*/
+ (binaryfunc)mmap_concat, /*sq_concat*/
+ (ssizeargfunc)mmap_repeat, /*sq_repeat*/
+ (ssizeargfunc)mmap_item, /*sq_item*/
+ (ssizessizeargfunc)mmap_slice, /*sq_slice*/
+ (ssizeobjargproc)mmap_ass_item, /*sq_ass_item*/
+ (ssizessizeobjargproc)mmap_ass_slice, /*sq_ass_slice*/
};
static PyMappingMethods mmap_as_mapping = {
- (lenfunc)mmap_length,
- (binaryfunc)mmap_subscript,
- (objobjargproc)mmap_ass_subscript,
+ (lenfunc)mmap_length,
+ (binaryfunc)mmap_subscript,
+ (objobjargproc)mmap_ass_subscript,
};
static PyBufferProcs mmap_as_buffer = {
- (readbufferproc)mmap_buffer_getreadbuf,
- (writebufferproc)mmap_buffer_getwritebuf,
- (segcountproc)mmap_buffer_getsegcount,
- (charbufferproc)mmap_buffer_getcharbuffer,
+ (readbufferproc)mmap_buffer_getreadbuf,
+ (writebufferproc)mmap_buffer_getwritebuf,
+ (segcountproc)mmap_buffer_getsegcount,
+ (charbufferproc)mmap_buffer_getcharbuffer,
};
static PyObject *
@@ -1024,46 +1024,46 @@ To map anonymous memory, pass -1 as the fileno (both versions).");
static PyTypeObject mmap_object_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "mmap.mmap", /* tp_name */
- sizeof(mmap_object), /* tp_size */
- 0, /* tp_itemsize */
- /* methods */
- (destructor) mmap_object_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &mmap_as_sequence, /*tp_as_sequence*/
- &mmap_as_mapping, /*tp_as_mapping*/
- 0, /*tp_hash*/
- 0, /*tp_call*/
- 0, /*tp_str*/
- PyObject_GenericGetAttr, /*tp_getattro*/
- 0, /*tp_setattro*/
- &mmap_as_buffer, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GETCHARBUFFER, /*tp_flags*/
- mmap_doc, /*tp_doc*/
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- mmap_object_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 */
- PyType_GenericAlloc, /* tp_alloc */
- new_mmap_object, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "mmap.mmap", /* tp_name */
+ sizeof(mmap_object), /* tp_size */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor) mmap_object_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &mmap_as_sequence, /*tp_as_sequence*/
+ &mmap_as_mapping, /*tp_as_mapping*/
+ 0, /*tp_hash*/
+ 0, /*tp_call*/
+ 0, /*tp_str*/
+ PyObject_GenericGetAttr, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ &mmap_as_buffer, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GETCHARBUFFER, /*tp_flags*/
+ mmap_doc, /*tp_doc*/
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ mmap_object_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 */
+ PyType_GenericAlloc, /* tp_alloc */
+ new_mmap_object, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -1074,23 +1074,23 @@ static PyTypeObject mmap_object_type = {
static Py_ssize_t
_GetMapSize(PyObject *o, const char* param)
{
- if (o == NULL)
- return 0;
- if (PyIndex_Check(o)) {
- Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
- if (i==-1 && PyErr_Occurred())
- return -1;
- if (i < 0) {
- PyErr_Format(PyExc_OverflowError,
- "memory mapped %s must be positive",
- param);
- return -1;
- }
- return i;
- }
-
- PyErr_SetString(PyExc_TypeError, "map size must be an integral value");
- return -1;
+ if (o == NULL)
+ return 0;
+ if (PyIndex_Check(o)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
+ if (i==-1 && PyErr_Occurred())
+ return -1;
+ if (i < 0) {
+ PyErr_Format(PyExc_OverflowError,
+ "memory mapped %s must be positive",
+ param);
+ return -1;
+ }
+ return i;
+ }
+
+ PyErr_SetString(PyExc_TypeError, "map size must be an integral value");
+ return -1;
}
#ifdef UNIX
@@ -1098,124 +1098,124 @@ static PyObject *
new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
{
#ifdef HAVE_FSTAT
- struct stat st;
+ struct stat st;
#endif
- mmap_object *m_obj;
- PyObject *map_size_obj = NULL, *offset_obj = NULL;
- Py_ssize_t map_size, offset;
- int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
- int devzero = -1;
- int access = (int)ACCESS_DEFAULT;
- static char *keywords[] = {"fileno", "length",
- "flags", "prot",
- "access", "offset", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords,
- &fd, &map_size_obj, &flags, &prot,
- &access, &offset_obj))
- return NULL;
- map_size = _GetMapSize(map_size_obj, "size");
- if (map_size < 0)
- return NULL;
- offset = _GetMapSize(offset_obj, "offset");
- if (offset < 0)
- return NULL;
-
- if ((access != (int)ACCESS_DEFAULT) &&
- ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
- return PyErr_Format(PyExc_ValueError,
- "mmap can't specify both access and flags, prot.");
- switch ((access_mode)access) {
- case ACCESS_READ:
- flags = MAP_SHARED;
- prot = PROT_READ;
- break;
- case ACCESS_WRITE:
- flags = MAP_SHARED;
- prot = PROT_READ | PROT_WRITE;
- break;
- case ACCESS_COPY:
- flags = MAP_PRIVATE;
- prot = PROT_READ | PROT_WRITE;
- break;
- case ACCESS_DEFAULT:
- /* use the specified or default values of flags and prot */
- break;
- default:
- return PyErr_Format(PyExc_ValueError,
- "mmap invalid access parameter.");
- }
+ mmap_object *m_obj;
+ PyObject *map_size_obj = NULL, *offset_obj = NULL;
+ Py_ssize_t map_size, offset;
+ int fd, flags = MAP_SHARED, prot = PROT_WRITE | PROT_READ;
+ int devzero = -1;
+ int access = (int)ACCESS_DEFAULT;
+ static char *keywords[] = {"fileno", "length",
+ "flags", "prot",
+ "access", "offset", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|iiiO", keywords,
+ &fd, &map_size_obj, &flags, &prot,
+ &access, &offset_obj))
+ return NULL;
+ map_size = _GetMapSize(map_size_obj, "size");
+ if (map_size < 0)
+ return NULL;
+ offset = _GetMapSize(offset_obj, "offset");
+ if (offset < 0)
+ return NULL;
+
+ if ((access != (int)ACCESS_DEFAULT) &&
+ ((flags != MAP_SHARED) || (prot != (PROT_WRITE | PROT_READ))))
+ return PyErr_Format(PyExc_ValueError,
+ "mmap can't specify both access and flags, prot.");
+ switch ((access_mode)access) {
+ case ACCESS_READ:
+ flags = MAP_SHARED;
+ prot = PROT_READ;
+ break;
+ case ACCESS_WRITE:
+ flags = MAP_SHARED;
+ prot = PROT_READ | PROT_WRITE;
+ break;
+ case ACCESS_COPY:
+ flags = MAP_PRIVATE;
+ prot = PROT_READ | PROT_WRITE;
+ break;
+ case ACCESS_DEFAULT:
+ /* use the specified or default values of flags and prot */
+ break;
+ default:
+ return PyErr_Format(PyExc_ValueError,
+ "mmap invalid access parameter.");
+ }
if (prot == PROT_READ) {
- access = ACCESS_READ;
+ access = ACCESS_READ;
}
#ifdef HAVE_FSTAT
# ifdef __VMS
- /* on OpenVMS we must ensure that all bytes are written to the file */
- if (fd != -1) {
- fsync(fd);
- }
+ /* on OpenVMS we must ensure that all bytes are written to the file */
+ if (fd != -1) {
+ fsync(fd);
+ }
# endif
- if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
- if (map_size == 0) {
- map_size = st.st_size;
- } else if ((size_t)offset + (size_t)map_size > st.st_size) {
- PyErr_SetString(PyExc_ValueError,
- "mmap length is greater than file size");
- return NULL;
- }
- }
+ if (fd != -1 && fstat(fd, &st) == 0 && S_ISREG(st.st_mode)) {
+ if (map_size == 0) {
+ map_size = st.st_size;
+ } else if ((size_t)offset + (size_t)map_size > st.st_size) {
+ PyErr_SetString(PyExc_ValueError,
+ "mmap length is greater than file size");
+ return NULL;
+ }
+ }
#endif
- m_obj = (mmap_object *)type->tp_alloc(type, 0);
- if (m_obj == NULL) {return NULL;}
- m_obj->data = NULL;
- m_obj->size = (size_t) map_size;
- m_obj->pos = (size_t) 0;
- m_obj->offset = offset;
- if (fd == -1) {
- m_obj->fd = -1;
- /* Assume the caller wants to map anonymous memory.
- This is the same behaviour as Windows. mmap.mmap(-1, size)
- on both Windows and Unix map anonymous memory.
- */
+ m_obj = (mmap_object *)type->tp_alloc(type, 0);
+ if (m_obj == NULL) {return NULL;}
+ m_obj->data = NULL;
+ m_obj->size = (size_t) map_size;
+ m_obj->pos = (size_t) 0;
+ m_obj->offset = offset;
+ if (fd == -1) {
+ m_obj->fd = -1;
+ /* Assume the caller wants to map anonymous memory.
+ This is the same behaviour as Windows. mmap.mmap(-1, size)
+ on both Windows and Unix map anonymous memory.
+ */
#ifdef MAP_ANONYMOUS
- /* BSD way to map anonymous memory */
- flags |= MAP_ANONYMOUS;
+ /* BSD way to map anonymous memory */
+ flags |= MAP_ANONYMOUS;
#else
- /* SVR4 method to map anonymous memory is to open /dev/zero */
- fd = devzero = open("/dev/zero", O_RDWR);
- if (devzero == -1) {
- Py_DECREF(m_obj);
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
+ /* SVR4 method to map anonymous memory is to open /dev/zero */
+ fd = devzero = open("/dev/zero", O_RDWR);
+ if (devzero == -1) {
+ Py_DECREF(m_obj);
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
#endif
- } else {
- m_obj->fd = dup(fd);
- if (m_obj->fd == -1) {
- Py_DECREF(m_obj);
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- }
-
- m_obj->data = mmap(NULL, map_size,
- prot, flags,
- fd, offset);
-
- if (devzero != -1) {
- close(devzero);
- }
-
- if (m_obj->data == (char *)-1) {
- m_obj->data = NULL;
- Py_DECREF(m_obj);
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- m_obj->access = (access_mode)access;
- return (PyObject *)m_obj;
+ } else {
+ m_obj->fd = dup(fd);
+ if (m_obj->fd == -1) {
+ Py_DECREF(m_obj);
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ }
+
+ m_obj->data = mmap(NULL, map_size,
+ prot, flags,
+ fd, offset);
+
+ if (devzero != -1) {
+ close(devzero);
+ }
+
+ if (m_obj->data == (char *)-1) {
+ m_obj->data = NULL;
+ Py_DECREF(m_obj);
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ m_obj->access = (access_mode)access;
+ return (PyObject *)m_obj;
}
#endif /* UNIX */
@@ -1223,250 +1223,250 @@ new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
static PyObject *
new_mmap_object(PyTypeObject *type, PyObject *args, PyObject *kwdict)
{
- mmap_object *m_obj;
- PyObject *map_size_obj = NULL, *offset_obj = NULL;
- Py_ssize_t map_size, offset;
- DWORD off_hi; /* upper 32 bits of offset */
- DWORD off_lo; /* lower 32 bits of offset */
- DWORD size_hi; /* upper 32 bits of size */
- DWORD size_lo; /* lower 32 bits of size */
- char *tagname = "";
- DWORD dwErr = 0;
- int fileno;
- HANDLE fh = 0;
- int access = (access_mode)ACCESS_DEFAULT;
- DWORD flProtect, dwDesiredAccess;
- static char *keywords[] = { "fileno", "length",
- "tagname",
- "access", "offset", NULL };
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords,
- &fileno, &map_size_obj,
- &tagname, &access, &offset_obj)) {
- return NULL;
- }
-
- switch((access_mode)access) {
- case ACCESS_READ:
- flProtect = PAGE_READONLY;
- dwDesiredAccess = FILE_MAP_READ;
- break;
- case ACCESS_DEFAULT: case ACCESS_WRITE:
- flProtect = PAGE_READWRITE;
- dwDesiredAccess = FILE_MAP_WRITE;
- break;
- case ACCESS_COPY:
- flProtect = PAGE_WRITECOPY;
- dwDesiredAccess = FILE_MAP_COPY;
- break;
- default:
- return PyErr_Format(PyExc_ValueError,
- "mmap invalid access parameter.");
- }
-
- map_size = _GetMapSize(map_size_obj, "size");
- if (map_size < 0)
- return NULL;
- offset = _GetMapSize(offset_obj, "offset");
- if (offset < 0)
- return NULL;
-
- /* assume -1 and 0 both mean invalid filedescriptor
- to 'anonymously' map memory.
- XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5.
- XXX: Should this code be added?
- if (fileno == 0)
- PyErr_Warn(PyExc_DeprecationWarning,
- "don't use 0 for anonymous memory");
- */
- if (fileno != -1 && fileno != 0) {
- fh = (HANDLE)_get_osfhandle(fileno);
- if (fh==(HANDLE)-1) {
- PyErr_SetFromErrno(mmap_module_error);
- return NULL;
- }
- /* Win9x appears to need us seeked to zero */
- lseek(fileno, 0, SEEK_SET);
- }
-
- m_obj = (mmap_object *)type->tp_alloc(type, 0);
- if (m_obj == NULL)
- return NULL;
- /* Set every field to an invalid marker, so we can safely
- destruct the object in the face of failure */
- m_obj->data = NULL;
- m_obj->file_handle = INVALID_HANDLE_VALUE;
- m_obj->map_handle = NULL;
- m_obj->tagname = NULL;
- m_obj->offset = offset;
-
- if (fh) {
- /* It is necessary to duplicate the handle, so the
- Python code can close it on us */
- if (!DuplicateHandle(
- GetCurrentProcess(), /* source process handle */
- fh, /* handle to be duplicated */
- GetCurrentProcess(), /* target proc handle */
- (LPHANDLE)&m_obj->file_handle, /* result */
- 0, /* access - ignored due to options value */
- FALSE, /* inherited by child processes? */
- DUPLICATE_SAME_ACCESS)) { /* options */
- dwErr = GetLastError();
- Py_DECREF(m_obj);
- PyErr_SetFromWindowsErr(dwErr);
- return NULL;
- }
- if (!map_size) {
- DWORD low,high;
- low = GetFileSize(fh, &high);
- /* low might just happen to have the value INVALID_FILE_SIZE;
- so we need to check the last error also. */
- if (low == INVALID_FILE_SIZE &&
- (dwErr = GetLastError()) != NO_ERROR) {
- Py_DECREF(m_obj);
- return PyErr_SetFromWindowsErr(dwErr);
- }
-
+ mmap_object *m_obj;
+ PyObject *map_size_obj = NULL, *offset_obj = NULL;
+ Py_ssize_t map_size, offset;
+ DWORD off_hi; /* upper 32 bits of offset */
+ DWORD off_lo; /* lower 32 bits of offset */
+ DWORD size_hi; /* upper 32 bits of size */
+ DWORD size_lo; /* lower 32 bits of size */
+ char *tagname = "";
+ DWORD dwErr = 0;
+ int fileno;
+ HANDLE fh = 0;
+ int access = (access_mode)ACCESS_DEFAULT;
+ DWORD flProtect, dwDesiredAccess;
+ static char *keywords[] = { "fileno", "length",
+ "tagname",
+ "access", "offset", NULL };
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "iO|ziO", keywords,
+ &fileno, &map_size_obj,
+ &tagname, &access, &offset_obj)) {
+ return NULL;
+ }
+
+ switch((access_mode)access) {
+ case ACCESS_READ:
+ flProtect = PAGE_READONLY;
+ dwDesiredAccess = FILE_MAP_READ;
+ break;
+ case ACCESS_DEFAULT: case ACCESS_WRITE:
+ flProtect = PAGE_READWRITE;
+ dwDesiredAccess = FILE_MAP_WRITE;
+ break;
+ case ACCESS_COPY:
+ flProtect = PAGE_WRITECOPY;
+ dwDesiredAccess = FILE_MAP_COPY;
+ break;
+ default:
+ return PyErr_Format(PyExc_ValueError,
+ "mmap invalid access parameter.");
+ }
+
+ map_size = _GetMapSize(map_size_obj, "size");
+ if (map_size < 0)
+ return NULL;
+ offset = _GetMapSize(offset_obj, "offset");
+ if (offset < 0)
+ return NULL;
+
+ /* assume -1 and 0 both mean invalid filedescriptor
+ to 'anonymously' map memory.
+ XXX: fileno == 0 is a valid fd, but was accepted prior to 2.5.
+ XXX: Should this code be added?
+ if (fileno == 0)
+ PyErr_Warn(PyExc_DeprecationWarning,
+ "don't use 0 for anonymous memory");
+ */
+ if (fileno != -1 && fileno != 0) {
+ fh = (HANDLE)_get_osfhandle(fileno);
+ if (fh==(HANDLE)-1) {
+ PyErr_SetFromErrno(mmap_module_error);
+ return NULL;
+ }
+ /* Win9x appears to need us seeked to zero */
+ lseek(fileno, 0, SEEK_SET);
+ }
+
+ m_obj = (mmap_object *)type->tp_alloc(type, 0);
+ if (m_obj == NULL)
+ return NULL;
+ /* Set every field to an invalid marker, so we can safely
+ destruct the object in the face of failure */
+ m_obj->data = NULL;
+ m_obj->file_handle = INVALID_HANDLE_VALUE;
+ m_obj->map_handle = NULL;
+ m_obj->tagname = NULL;
+ m_obj->offset = offset;
+
+ if (fh) {
+ /* It is necessary to duplicate the handle, so the
+ Python code can close it on us */
+ if (!DuplicateHandle(
+ GetCurrentProcess(), /* source process handle */
+ fh, /* handle to be duplicated */
+ GetCurrentProcess(), /* target proc handle */
+ (LPHANDLE)&m_obj->file_handle, /* result */
+ 0, /* access - ignored due to options value */
+ FALSE, /* inherited by child processes? */
+ DUPLICATE_SAME_ACCESS)) { /* options */
+ dwErr = GetLastError();
+ Py_DECREF(m_obj);
+ PyErr_SetFromWindowsErr(dwErr);
+ return NULL;
+ }
+ if (!map_size) {
+ DWORD low,high;
+ low = GetFileSize(fh, &high);
+ /* low might just happen to have the value INVALID_FILE_SIZE;
+ so we need to check the last error also. */
+ if (low == INVALID_FILE_SIZE &&
+ (dwErr = GetLastError()) != NO_ERROR) {
+ Py_DECREF(m_obj);
+ return PyErr_SetFromWindowsErr(dwErr);
+ }
+
#if SIZEOF_SIZE_T > 4
- m_obj->size = (((size_t)high)<<32) + low;
+ m_obj->size = (((size_t)high)<<32) + low;
#else
- if (high)
- /* File is too large to map completely */
- m_obj->size = (size_t)-1;
- else
- m_obj->size = low;
+ if (high)
+ /* File is too large to map completely */
+ m_obj->size = (size_t)-1;
+ else
+ m_obj->size = low;
#endif
- } else {
- m_obj->size = map_size;
- }
- }
- else {
- m_obj->size = map_size;
- }
-
- /* set the initial position */
- m_obj->pos = (size_t) 0;
-
- /* set the tag name */
- if (tagname != NULL && *tagname != '\0') {
- m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
- if (m_obj->tagname == NULL) {
- PyErr_NoMemory();
- Py_DECREF(m_obj);
- return NULL;
- }
- strcpy(m_obj->tagname, tagname);
- }
- else
- m_obj->tagname = NULL;
-
- m_obj->access = (access_mode)access;
- /* DWORD is a 4-byte int. If we're on a box where size_t consumes
- * more than 4 bytes, we need to break it apart. Else (size_t
- * consumes 4 bytes), C doesn't define what happens if we shift
- * right by 32, so we need different code.
- */
+ } else {
+ m_obj->size = map_size;
+ }
+ }
+ else {
+ m_obj->size = map_size;
+ }
+
+ /* set the initial position */
+ m_obj->pos = (size_t) 0;
+
+ /* set the tag name */
+ if (tagname != NULL && *tagname != '\0') {
+ m_obj->tagname = PyMem_Malloc(strlen(tagname)+1);
+ if (m_obj->tagname == NULL) {
+ PyErr_NoMemory();
+ Py_DECREF(m_obj);
+ return NULL;
+ }
+ strcpy(m_obj->tagname, tagname);
+ }
+ else
+ m_obj->tagname = NULL;
+
+ m_obj->access = (access_mode)access;
+ /* DWORD is a 4-byte int. If we're on a box where size_t consumes
+ * more than 4 bytes, we need to break it apart. Else (size_t
+ * consumes 4 bytes), C doesn't define what happens if we shift
+ * right by 32, so we need different code.
+ */
#if SIZEOF_SIZE_T > 4
- size_hi = (DWORD)((offset + m_obj->size) >> 32);
- size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF);
- off_hi = (DWORD)(offset >> 32);
- off_lo = (DWORD)(offset & 0xFFFFFFFF);
+ size_hi = (DWORD)((offset + m_obj->size) >> 32);
+ size_lo = (DWORD)((offset + m_obj->size) & 0xFFFFFFFF);
+ off_hi = (DWORD)(offset >> 32);
+ off_lo = (DWORD)(offset & 0xFFFFFFFF);
#else
- size_hi = 0;
- size_lo = (DWORD)(offset + m_obj->size);
- off_hi = 0;
- off_lo = (DWORD)offset;
+ size_hi = 0;
+ size_lo = (DWORD)(offset + m_obj->size);
+ off_hi = 0;
+ off_lo = (DWORD)offset;
#endif
- /* For files, it would be sufficient to pass 0 as size.
- For anonymous maps, we have to pass the size explicitly. */
- m_obj->map_handle = CreateFileMapping(m_obj->file_handle,
- NULL,
- flProtect,
- size_hi,
- size_lo,
- m_obj->tagname);
- if (m_obj->map_handle != NULL) {
- m_obj->data = (char *) MapViewOfFile(m_obj->map_handle,
- dwDesiredAccess,
- off_hi,
- off_lo,
- m_obj->size);
- if (m_obj->data != NULL)
- return (PyObject *)m_obj;
- else {
- dwErr = GetLastError();
- CloseHandle(m_obj->map_handle);
- m_obj->map_handle = NULL;
- }
- } else
- dwErr = GetLastError();
- Py_DECREF(m_obj);
- PyErr_SetFromWindowsErr(dwErr);
- return NULL;
+ /* For files, it would be sufficient to pass 0 as size.
+ For anonymous maps, we have to pass the size explicitly. */
+ m_obj->map_handle = CreateFileMapping(m_obj->file_handle,
+ NULL,
+ flProtect,
+ size_hi,
+ size_lo,
+ m_obj->tagname);
+ if (m_obj->map_handle != NULL) {
+ m_obj->data = (char *) MapViewOfFile(m_obj->map_handle,
+ dwDesiredAccess,
+ off_hi,
+ off_lo,
+ m_obj->size);
+ if (m_obj->data != NULL)
+ return (PyObject *)m_obj;
+ else {
+ dwErr = GetLastError();
+ CloseHandle(m_obj->map_handle);
+ m_obj->map_handle = NULL;
+ }
+ } else
+ dwErr = GetLastError();
+ Py_DECREF(m_obj);
+ PyErr_SetFromWindowsErr(dwErr);
+ return NULL;
}
#endif /* MS_WINDOWS */
static void
setint(PyObject *d, const char *name, long value)
{
- PyObject *o = PyInt_FromLong(value);
- if (o && PyDict_SetItemString(d, name, o) == 0) {
- Py_DECREF(o);
- }
+ PyObject *o = PyInt_FromLong(value);
+ if (o && PyDict_SetItemString(d, name, o) == 0) {
+ Py_DECREF(o);
+ }
}
PyMODINIT_FUNC
initmmap(void)
{
- PyObject *dict, *module;
-
- if (PyType_Ready(&mmap_object_type) < 0)
- return;
-
- module = Py_InitModule("mmap", NULL);
- if (module == NULL)
- return;
- dict = PyModule_GetDict(module);
- if (!dict)
- return;
- mmap_module_error = PyErr_NewException("mmap.error",
- PyExc_EnvironmentError , NULL);
- if (mmap_module_error == NULL)
- return;
- PyDict_SetItemString(dict, "error", mmap_module_error);
- PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type);
+ PyObject *dict, *module;
+
+ if (PyType_Ready(&mmap_object_type) < 0)
+ return;
+
+ module = Py_InitModule("mmap", NULL);
+ if (module == NULL)
+ return;
+ dict = PyModule_GetDict(module);
+ if (!dict)
+ return;
+ mmap_module_error = PyErr_NewException("mmap.error",
+ PyExc_EnvironmentError , NULL);
+ if (mmap_module_error == NULL)
+ return;
+ PyDict_SetItemString(dict, "error", mmap_module_error);
+ PyDict_SetItemString(dict, "mmap", (PyObject*) &mmap_object_type);
#ifdef PROT_EXEC
- setint(dict, "PROT_EXEC", PROT_EXEC);
+ setint(dict, "PROT_EXEC", PROT_EXEC);
#endif
#ifdef PROT_READ
- setint(dict, "PROT_READ", PROT_READ);
+ setint(dict, "PROT_READ", PROT_READ);
#endif
#ifdef PROT_WRITE
- setint(dict, "PROT_WRITE", PROT_WRITE);
+ setint(dict, "PROT_WRITE", PROT_WRITE);
#endif
#ifdef MAP_SHARED
- setint(dict, "MAP_SHARED", MAP_SHARED);
+ setint(dict, "MAP_SHARED", MAP_SHARED);
#endif
#ifdef MAP_PRIVATE
- setint(dict, "MAP_PRIVATE", MAP_PRIVATE);
+ setint(dict, "MAP_PRIVATE", MAP_PRIVATE);
#endif
#ifdef MAP_DENYWRITE
- setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE);
+ setint(dict, "MAP_DENYWRITE", MAP_DENYWRITE);
#endif
#ifdef MAP_EXECUTABLE
- setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE);
+ setint(dict, "MAP_EXECUTABLE", MAP_EXECUTABLE);
#endif
#ifdef MAP_ANONYMOUS
- setint(dict, "MAP_ANON", MAP_ANONYMOUS);
- setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS);
+ setint(dict, "MAP_ANON", MAP_ANONYMOUS);
+ setint(dict, "MAP_ANONYMOUS", MAP_ANONYMOUS);
#endif
- setint(dict, "PAGESIZE", (long)my_getpagesize());
+ setint(dict, "PAGESIZE", (long)my_getpagesize());
- setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity());
+ setint(dict, "ALLOCATIONGRANULARITY", (long)my_getallocationgranularity());
- setint(dict, "ACCESS_READ", ACCESS_READ);
- setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
- setint(dict, "ACCESS_COPY", ACCESS_COPY);
+ setint(dict, "ACCESS_READ", ACCESS_READ);
+ setint(dict, "ACCESS_WRITE", ACCESS_WRITE);
+ setint(dict, "ACCESS_COPY", ACCESS_COPY);
}
diff --git a/Modules/nismodule.c b/Modules/nismodule.c
index 9fbab5a..04d8570 100644
--- a/Modules/nismodule.c
+++ b/Modules/nismodule.c
@@ -1,11 +1,11 @@
/***********************************************************
Written by:
- Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
- B&O group,
- Faculteit der Informatica,
- Universiteit Twente,
- Enschede,
- the Netherlands.
+ Fred Gansevles <Fred.Gansevles@cs.utwente.nl>
+ B&O group,
+ Faculteit der Informatica,
+ Universiteit Twente,
+ Enschede,
+ the Netherlands.
******************************************************************/
/* NIS module implementation */
@@ -23,7 +23,7 @@
extern int yp_get_default_domain(char **);
#endif
-PyDoc_STRVAR(get_default_domain__doc__,
+PyDoc_STRVAR(get_default_domain__doc__,
"get_default_domain() -> str\n\
Corresponds to the C library yp_get_default_domain() call, returning\n\
the default NIS domain.\n");
@@ -49,44 +49,44 @@ static PyObject *NisError;
static PyObject *
nis_error (int err)
{
- PyErr_SetString(NisError, yperr_string(err));
- return NULL;
+ PyErr_SetString(NisError, yperr_string(err));
+ return NULL;
}
static struct nis_map {
- char *alias;
- char *map;
- int fix;
+ char *alias;
+ char *map;
+ int fix;
} aliases [] = {
- {"passwd", "passwd.byname", 0},
- {"group", "group.byname", 0},
- {"networks", "networks.byaddr", 0},
- {"hosts", "hosts.byname", 0},
- {"protocols", "protocols.bynumber", 0},
- {"services", "services.byname", 0},
- {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */
- {"ethers", "ethers.byname", 0},
- {0L, 0L, 0}
+ {"passwd", "passwd.byname", 0},
+ {"group", "group.byname", 0},
+ {"networks", "networks.byaddr", 0},
+ {"hosts", "hosts.byname", 0},
+ {"protocols", "protocols.bynumber", 0},
+ {"services", "services.byname", 0},
+ {"aliases", "mail.aliases", 1}, /* created with 'makedbm -a' */
+ {"ethers", "ethers.byname", 0},
+ {0L, 0L, 0}
};
static char *
nis_mapname (char *map, int *pfix)
{
- int i;
-
- *pfix = 0;
- for (i=0; aliases[i].alias != 0L; i++) {
- if (!strcmp (aliases[i].alias, map)) {
- *pfix = aliases[i].fix;
- return aliases[i].map;
- }
- if (!strcmp (aliases[i].map, map)) {
- *pfix = aliases[i].fix;
- return aliases[i].map;
- }
- }
-
- return map;
+ int i;
+
+ *pfix = 0;
+ for (i=0; aliases[i].alias != 0L; i++) {
+ if (!strcmp (aliases[i].alias, map)) {
+ *pfix = aliases[i].fix;
+ return aliases[i].map;
+ }
+ if (!strcmp (aliases[i].map, map)) {
+ *pfix = aliases[i].fix;
+ return aliases[i].map;
+ }
+ }
+
+ return map;
}
#if defined(__APPLE__) || defined(__OpenBSD__) || defined(__FreeBSD__)
@@ -96,168 +96,168 @@ typedef int (*foreachfunc)(int, char *, int, char *, int, char *);
#endif
struct ypcallback_data {
- PyObject *dict;
- int fix;
- PyThreadState *state;
+ PyObject *dict;
+ int fix;
+ PyThreadState *state;
};
static int
nis_foreach (int instatus, char *inkey, int inkeylen, char *inval,
int invallen, struct ypcallback_data *indata)
{
- if (instatus == YP_TRUE) {
- PyObject *key;
- PyObject *val;
- int err;
-
- PyEval_RestoreThread(indata->state);
- if (indata->fix) {
- if (inkeylen > 0 && inkey[inkeylen-1] == '\0')
- inkeylen--;
- if (invallen > 0 && inval[invallen-1] == '\0')
- invallen--;
- }
- key = PyString_FromStringAndSize(inkey, inkeylen);
- val = PyString_FromStringAndSize(inval, invallen);
- if (key == NULL || val == NULL) {
- /* XXX error -- don't know how to handle */
- PyErr_Clear();
- Py_XDECREF(key);
- Py_XDECREF(val);
- return 1;
- }
- err = PyDict_SetItem(indata->dict, key, val);
- Py_DECREF(key);
- Py_DECREF(val);
- if (err != 0)
- PyErr_Clear();
- indata->state = PyEval_SaveThread();
- if (err != 0)
- return 1;
- return 0;
- }
- return 1;
+ if (instatus == YP_TRUE) {
+ PyObject *key;
+ PyObject *val;
+ int err;
+
+ PyEval_RestoreThread(indata->state);
+ if (indata->fix) {
+ if (inkeylen > 0 && inkey[inkeylen-1] == '\0')
+ inkeylen--;
+ if (invallen > 0 && inval[invallen-1] == '\0')
+ invallen--;
+ }
+ key = PyString_FromStringAndSize(inkey, inkeylen);
+ val = PyString_FromStringAndSize(inval, invallen);
+ if (key == NULL || val == NULL) {
+ /* XXX error -- don't know how to handle */
+ PyErr_Clear();
+ Py_XDECREF(key);
+ Py_XDECREF(val);
+ return 1;
+ }
+ err = PyDict_SetItem(indata->dict, key, val);
+ Py_DECREF(key);
+ Py_DECREF(val);
+ if (err != 0)
+ PyErr_Clear();
+ indata->state = PyEval_SaveThread();
+ if (err != 0)
+ return 1;
+ return 0;
+ }
+ return 1;
}
static PyObject *
nis_get_default_domain (PyObject *self)
{
- char *domain;
- int err;
- PyObject *res;
+ char *domain;
+ int err;
+ PyObject *res;
- if ((err = yp_get_default_domain(&domain)) != 0)
- return nis_error(err);
+ if ((err = yp_get_default_domain(&domain)) != 0)
+ return nis_error(err);
- res = PyString_FromStringAndSize (domain, strlen(domain));
- return res;
+ res = PyString_FromStringAndSize (domain, strlen(domain));
+ return res;
}
static PyObject *
nis_match (PyObject *self, PyObject *args, PyObject *kwdict)
{
- char *match;
- char *domain = NULL;
- int keylen, len;
- char *key, *map;
- int err;
- PyObject *res;
- int fix;
- static char *kwlist[] = {"key", "map", "domain", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict,
- "t#s|s:match", kwlist,
- &key, &keylen, &map, &domain))
- return NULL;
- if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
- return nis_error(err);
- map = nis_mapname (map, &fix);
- if (fix)
- keylen++;
- Py_BEGIN_ALLOW_THREADS
- err = yp_match (domain, map, key, keylen, &match, &len);
- Py_END_ALLOW_THREADS
- if (fix)
- len--;
- if (err != 0)
- return nis_error(err);
- res = PyString_FromStringAndSize (match, len);
- free (match);
- return res;
+ char *match;
+ char *domain = NULL;
+ int keylen, len;
+ char *key, *map;
+ int err;
+ PyObject *res;
+ int fix;
+ static char *kwlist[] = {"key", "map", "domain", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict,
+ "t#s|s:match", kwlist,
+ &key, &keylen, &map, &domain))
+ return NULL;
+ if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
+ return nis_error(err);
+ map = nis_mapname (map, &fix);
+ if (fix)
+ keylen++;
+ Py_BEGIN_ALLOW_THREADS
+ err = yp_match (domain, map, key, keylen, &match, &len);
+ Py_END_ALLOW_THREADS
+ if (fix)
+ len--;
+ if (err != 0)
+ return nis_error(err);
+ res = PyString_FromStringAndSize (match, len);
+ free (match);
+ return res;
}
static PyObject *
nis_cat (PyObject *self, PyObject *args, PyObject *kwdict)
{
- char *domain = NULL;
- char *map;
- struct ypall_callback cb;
- struct ypcallback_data data;
- PyObject *dict;
- int err;
- static char *kwlist[] = {"map", "domain", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
- kwlist, &map, &domain))
- return NULL;
- if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
- return nis_error(err);
- dict = PyDict_New ();
- if (dict == NULL)
- return NULL;
- cb.foreach = (foreachfunc)nis_foreach;
- data.dict = dict;
- map = nis_mapname (map, &data.fix);
- cb.data = (char *)&data;
- data.state = PyEval_SaveThread();
- err = yp_all (domain, map, &cb);
- PyEval_RestoreThread(data.state);
- if (err != 0) {
- Py_DECREF(dict);
- return nis_error(err);
- }
- return dict;
+ char *domain = NULL;
+ char *map;
+ struct ypall_callback cb;
+ struct ypcallback_data data;
+ PyObject *dict;
+ int err;
+ static char *kwlist[] = {"map", "domain", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict, "s|s:cat",
+ kwlist, &map, &domain))
+ return NULL;
+ if (!domain && ((err = yp_get_default_domain(&domain)) != 0))
+ return nis_error(err);
+ dict = PyDict_New ();
+ if (dict == NULL)
+ return NULL;
+ cb.foreach = (foreachfunc)nis_foreach;
+ data.dict = dict;
+ map = nis_mapname (map, &data.fix);
+ cb.data = (char *)&data;
+ data.state = PyEval_SaveThread();
+ err = yp_all (domain, map, &cb);
+ PyEval_RestoreThread(data.state);
+ if (err != 0) {
+ Py_DECREF(dict);
+ return nis_error(err);
+ }
+ return dict;
}
/* These should be u_long on Sun h/w but not on 64-bit h/w.
This is not portable to machines with 16-bit ints and no prototypes */
#ifndef YPPROC_MAPLIST
-#define YPPROC_MAPLIST 11
+#define YPPROC_MAPLIST 11
#endif
#ifndef YPPROG
-#define YPPROG 100004
+#define YPPROG 100004
#endif
#ifndef YPVERS
-#define YPVERS 2
+#define YPVERS 2
#endif
typedef char *domainname;
typedef char *mapname;
enum nisstat {
- NIS_TRUE = 1,
- NIS_NOMORE = 2,
- NIS_FALSE = 0,
- NIS_NOMAP = -1,
- NIS_NODOM = -2,
- NIS_NOKEY = -3,
- NIS_BADOP = -4,
- NIS_BADDB = -5,
- NIS_YPERR = -6,
- NIS_BADARGS = -7,
- NIS_VERS = -8
+ NIS_TRUE = 1,
+ NIS_NOMORE = 2,
+ NIS_FALSE = 0,
+ NIS_NOMAP = -1,
+ NIS_NODOM = -2,
+ NIS_NOKEY = -3,
+ NIS_BADOP = -4,
+ NIS_BADDB = -5,
+ NIS_YPERR = -6,
+ NIS_BADARGS = -7,
+ NIS_VERS = -8
};
typedef enum nisstat nisstat;
struct nismaplist {
- mapname map;
- struct nismaplist *next;
+ mapname map;
+ struct nismaplist *next;
};
typedef struct nismaplist nismaplist;
struct nisresp_maplist {
- nisstat stat;
- nismaplist *maps;
+ nisstat stat;
+ nismaplist *maps;
};
typedef struct nisresp_maplist nisresp_maplist;
@@ -267,45 +267,45 @@ static
bool_t
nis_xdr_domainname(XDR *xdrs, domainname *objp)
{
- if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) {
- return (FALSE);
- }
- return (TRUE);
+ if (!xdr_string(xdrs, objp, YPMAXDOMAIN)) {
+ return (FALSE);
+ }
+ return (TRUE);
}
static
bool_t
nis_xdr_mapname(XDR *xdrs, mapname *objp)
{
- if (!xdr_string(xdrs, objp, YPMAXMAP)) {
- return (FALSE);
- }
- return (TRUE);
+ if (!xdr_string(xdrs, objp, YPMAXMAP)) {
+ return (FALSE);
+ }
+ return (TRUE);
}
static
bool_t
nis_xdr_ypmaplist(XDR *xdrs, nismaplist *objp)
{
- if (!nis_xdr_mapname(xdrs, &objp->map)) {
- return (FALSE);
- }
- if (!xdr_pointer(xdrs, (char **)&objp->next,
- sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
- {
- return (FALSE);
- }
- return (TRUE);
+ if (!nis_xdr_mapname(xdrs, &objp->map)) {
+ return (FALSE);
+ }
+ if (!xdr_pointer(xdrs, (char **)&objp->next,
+ sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
+ {
+ return (FALSE);
+ }
+ return (TRUE);
}
static
bool_t
nis_xdr_ypstat(XDR *xdrs, nisstat *objp)
{
- if (!xdr_enum(xdrs, (enum_t *)objp)) {
- return (FALSE);
- }
- return (TRUE);
+ if (!xdr_enum(xdrs, (enum_t *)objp)) {
+ return (FALSE);
+ }
+ return (TRUE);
}
@@ -313,15 +313,15 @@ static
bool_t
nis_xdr_ypresp_maplist(XDR *xdrs, nisresp_maplist *objp)
{
- if (!nis_xdr_ypstat(xdrs, &objp->stat)) {
- return (FALSE);
- }
- if (!xdr_pointer(xdrs, (char **)&objp->maps,
- sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
- {
- return (FALSE);
- }
- return (TRUE);
+ if (!nis_xdr_ypstat(xdrs, &objp->stat)) {
+ return (FALSE);
+ }
+ if (!xdr_pointer(xdrs, (char **)&objp->maps,
+ sizeof(nismaplist), (xdrproc_t)nis_xdr_ypmaplist))
+ {
+ return (FALSE);
+ }
+ return (TRUE);
}
@@ -329,105 +329,105 @@ static
nisresp_maplist *
nisproc_maplist_2(domainname *argp, CLIENT *clnt)
{
- static nisresp_maplist res;
-
- memset(&res, 0, sizeof(res));
- if (clnt_call(clnt, YPPROC_MAPLIST,
- (xdrproc_t)nis_xdr_domainname, (caddr_t)argp,
- (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res,
- TIMEOUT) != RPC_SUCCESS)
- {
- return (NULL);
- }
- return (&res);
+ static nisresp_maplist res;
+
+ memset(&res, 0, sizeof(res));
+ if (clnt_call(clnt, YPPROC_MAPLIST,
+ (xdrproc_t)nis_xdr_domainname, (caddr_t)argp,
+ (xdrproc_t)nis_xdr_ypresp_maplist, (caddr_t)&res,
+ TIMEOUT) != RPC_SUCCESS)
+ {
+ return (NULL);
+ }
+ return (&res);
}
static
nismaplist *
nis_maplist (char *dom)
{
- nisresp_maplist *list;
- CLIENT *cl;
- char *server = NULL;
- int mapi = 0;
-
- while (!server && aliases[mapi].map != 0L) {
- yp_master (dom, aliases[mapi].map, &server);
- mapi++;
- }
- if (!server) {
- PyErr_SetString(NisError, "No NIS master found for any map");
- return NULL;
- }
- cl = clnt_create(server, YPPROG, YPVERS, "tcp");
- if (cl == NULL) {
- PyErr_SetString(NisError, clnt_spcreateerror(server));
- goto finally;
- }
- list = nisproc_maplist_2 (&dom, cl);
- clnt_destroy(cl);
- if (list == NULL)
- goto finally;
- if (list->stat != NIS_TRUE)
- goto finally;
-
- free(server);
- return list->maps;
+ nisresp_maplist *list;
+ CLIENT *cl;
+ char *server = NULL;
+ int mapi = 0;
+
+ while (!server && aliases[mapi].map != 0L) {
+ yp_master (dom, aliases[mapi].map, &server);
+ mapi++;
+ }
+ if (!server) {
+ PyErr_SetString(NisError, "No NIS master found for any map");
+ return NULL;
+ }
+ cl = clnt_create(server, YPPROG, YPVERS, "tcp");
+ if (cl == NULL) {
+ PyErr_SetString(NisError, clnt_spcreateerror(server));
+ goto finally;
+ }
+ list = nisproc_maplist_2 (&dom, cl);
+ clnt_destroy(cl);
+ if (list == NULL)
+ goto finally;
+ if (list->stat != NIS_TRUE)
+ goto finally;
+
+ free(server);
+ return list->maps;
finally:
- free(server);
- return NULL;
+ free(server);
+ return NULL;
}
static PyObject *
nis_maps (PyObject *self, PyObject *args, PyObject *kwdict)
{
- char *domain = NULL;
- nismaplist *maps;
- PyObject *list;
- int err;
- static char *kwlist[] = {"domain", NULL};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwdict,
- "|s:maps", kwlist, &domain))
- return NULL;
- if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) {
- nis_error(err);
- return NULL;
- }
-
- if ((maps = nis_maplist (domain)) == NULL)
- return NULL;
- if ((list = PyList_New(0)) == NULL)
- return NULL;
- for (maps = maps; maps; maps = maps->next) {
- PyObject *str = PyString_FromString(maps->map);
- if (!str || PyList_Append(list, str) < 0)
- {
- Py_DECREF(list);
- list = NULL;
- break;
- }
- Py_DECREF(str);
- }
- /* XXX Shouldn't we free the list of maps now? */
- return list;
+ char *domain = NULL;
+ nismaplist *maps;
+ PyObject *list;
+ int err;
+ static char *kwlist[] = {"domain", NULL};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwdict,
+ "|s:maps", kwlist, &domain))
+ return NULL;
+ if (!domain && ((err = yp_get_default_domain (&domain)) != 0)) {
+ nis_error(err);
+ return NULL;
+ }
+
+ if ((maps = nis_maplist (domain)) == NULL)
+ return NULL;
+ if ((list = PyList_New(0)) == NULL)
+ return NULL;
+ for (maps = maps; maps; maps = maps->next) {
+ PyObject *str = PyString_FromString(maps->map);
+ if (!str || PyList_Append(list, str) < 0)
+ {
+ Py_DECREF(list);
+ list = NULL;
+ break;
+ }
+ Py_DECREF(str);
+ }
+ /* XXX Shouldn't we free the list of maps now? */
+ return list;
}
static PyMethodDef nis_methods[] = {
- {"match", (PyCFunction)nis_match,
- METH_VARARGS | METH_KEYWORDS,
- match__doc__},
- {"cat", (PyCFunction)nis_cat,
- METH_VARARGS | METH_KEYWORDS,
- cat__doc__},
- {"maps", (PyCFunction)nis_maps,
- METH_VARARGS | METH_KEYWORDS,
- maps__doc__},
- {"get_default_domain", (PyCFunction)nis_get_default_domain,
- METH_NOARGS,
- get_default_domain__doc__},
- {NULL, NULL} /* Sentinel */
+ {"match", (PyCFunction)nis_match,
+ METH_VARARGS | METH_KEYWORDS,
+ match__doc__},
+ {"cat", (PyCFunction)nis_cat,
+ METH_VARARGS | METH_KEYWORDS,
+ cat__doc__},
+ {"maps", (PyCFunction)nis_maps,
+ METH_VARARGS | METH_KEYWORDS,
+ maps__doc__},
+ {"get_default_domain", (PyCFunction)nis_get_default_domain,
+ METH_NOARGS,
+ get_default_domain__doc__},
+ {NULL, NULL} /* Sentinel */
};
PyDoc_STRVAR(nis__doc__,
@@ -436,12 +436,12 @@ PyDoc_STRVAR(nis__doc__,
void
initnis (void)
{
- PyObject *m, *d;
- m = Py_InitModule3("nis", nis_methods, nis__doc__);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- NisError = PyErr_NewException("nis.error", NULL, NULL);
- if (NisError != NULL)
- PyDict_SetItemString(d, "error", NisError);
+ PyObject *m, *d;
+ m = Py_InitModule3("nis", nis_methods, nis__doc__);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ NisError = PyErr_NewException("nis.error", NULL, NULL);
+ if (NisError != NULL)
+ PyDict_SetItemString(d, "error", NisError);
}
diff --git a/Modules/operator.c b/Modules/operator.c
index f0181de..274d8aa 100644
--- a/Modules/operator.c
+++ b/Modules/operator.c
@@ -69,19 +69,19 @@ used for special methods; variants without leading and trailing\n\
static int
op_isCallable(PyObject *x)
{
- if (PyErr_WarnPy3k("operator.isCallable() is not supported in 3.x. "
- "Use hasattr(obj, '__call__').", 1) < 0)
- return -1;
- return PyCallable_Check(x);
+ if (PyErr_WarnPy3k("operator.isCallable() is not supported in 3.x. "
+ "Use hasattr(obj, '__call__').", 1) < 0)
+ return -1;
+ return PyCallable_Check(x);
}
static int
op_sequenceIncludes(PyObject *seq, PyObject* ob)
{
- if (PyErr_WarnPy3k("operator.sequenceIncludes() is not supported "
- "in 3.x. Use operator.contains().", 1) < 0)
- return -1;
- return PySequence_Contains(seq, ob);
+ if (PyErr_WarnPy3k("operator.sequenceIncludes() is not supported "
+ "in 3.x. Use operator.contains().", 1) < 0)
+ return -1;
+ return PySequence_Contains(seq, ob);
}
spami(isCallable , op_isCallable)
@@ -140,88 +140,88 @@ spamrc(op_ge , Py_GE)
static PyObject*
op_pow(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2;
- if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2))
- return PyNumber_Power(a1, a2, Py_None);
- return NULL;
+ PyObject *a1, *a2;
+ if (PyArg_UnpackTuple(a,"pow", 2, 2, &a1, &a2))
+ return PyNumber_Power(a1, a2, Py_None);
+ return NULL;
}
static PyObject*
op_ipow(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2;
- if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2))
- return PyNumber_InPlacePower(a1, a2, Py_None);
- return NULL;
+ PyObject *a1, *a2;
+ if (PyArg_UnpackTuple(a,"ipow", 2, 2, &a1, &a2))
+ return PyNumber_InPlacePower(a1, a2, Py_None);
+ return NULL;
}
static PyObject *
op_index(PyObject *s, PyObject *a)
{
- return PyNumber_Index(a);
+ return PyNumber_Index(a);
}
static PyObject*
is_(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2, *result = NULL;
- if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) {
- result = (a1 == a2) ? Py_True : Py_False;
- Py_INCREF(result);
- }
- return result;
+ PyObject *a1, *a2, *result = NULL;
+ if (PyArg_UnpackTuple(a,"is_", 2, 2, &a1, &a2)) {
+ result = (a1 == a2) ? Py_True : Py_False;
+ Py_INCREF(result);
+ }
+ return result;
}
static PyObject*
is_not(PyObject *s, PyObject *a)
{
- PyObject *a1, *a2, *result = NULL;
- if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) {
- result = (a1 != a2) ? Py_True : Py_False;
- Py_INCREF(result);
- }
- return result;
+ PyObject *a1, *a2, *result = NULL;
+ if (PyArg_UnpackTuple(a,"is_not", 2, 2, &a1, &a2)) {
+ result = (a1 != a2) ? Py_True : Py_False;
+ Py_INCREF(result);
+ }
+ return result;
}
static PyObject*
op_getslice(PyObject *s, PyObject *a)
{
- PyObject *a1;
- Py_ssize_t a2, a3;
+ PyObject *a1;
+ Py_ssize_t a2, a3;
- if (!PyArg_ParseTuple(a, "Onn:getslice", &a1, &a2, &a3))
- return NULL;
- return PySequence_GetSlice(a1, a2, a3);
+ if (!PyArg_ParseTuple(a, "Onn:getslice", &a1, &a2, &a3))
+ return NULL;
+ return PySequence_GetSlice(a1, a2, a3);
}
static PyObject*
op_setslice(PyObject *s, PyObject *a)
{
- PyObject *a1, *a4;
- Py_ssize_t a2, a3;
+ PyObject *a1, *a4;
+ Py_ssize_t a2, a3;
- if (!PyArg_ParseTuple(a, "OnnO:setslice", &a1, &a2, &a3, &a4))
- return NULL;
+ if (!PyArg_ParseTuple(a, "OnnO:setslice", &a1, &a2, &a3, &a4))
+ return NULL;
- if (-1 == PySequence_SetSlice(a1, a2, a3, a4))
- return NULL;
+ if (-1 == PySequence_SetSlice(a1, a2, a3, a4))
+ return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyObject*
op_delslice(PyObject *s, PyObject *a)
{
- PyObject *a1;
- Py_ssize_t a2, a3;
+ PyObject *a1;
+ Py_ssize_t a2, a3;
- if (!PyArg_ParseTuple(a, "Onn:delslice", &a1, &a2, &a3))
- return NULL;
+ if (!PyArg_ParseTuple(a, "Onn:delslice", &a1, &a2, &a3))
+ return NULL;
- if (-1 == PySequence_DelSlice(a1, a2, a3))
- return NULL;
+ if (-1 == PySequence_DelSlice(a1, a2, a3))
+ return NULL;
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
#undef spam1
@@ -230,10 +230,10 @@ op_delslice(PyObject *s, PyObject *a)
#undef spam1o
#define spam1(OP,DOC) {#OP, OP, METH_VARARGS, PyDoc_STR(DOC)},
#define spam2(OP,ALTOP,DOC) {#OP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)}, \
- {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
+ {#ALTOP, op_##OP, METH_VARARGS, PyDoc_STR(DOC)},
#define spam1o(OP,DOC) {#OP, OP, METH_O, PyDoc_STR(DOC)},
#define spam2o(OP,ALTOP,DOC) {#OP, op_##OP, METH_O, PyDoc_STR(DOC)}, \
- {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)},
+ {#ALTOP, op_##OP, METH_O, PyDoc_STR(DOC)},
static struct PyMethodDef operator_methods[] = {
@@ -318,16 +318,16 @@ spam2(ne,__ne__, "ne(a, b) -- Same as a!=b.")
spam2(gt,__gt__, "gt(a, b) -- Same as a>b.")
spam2(ge,__ge__, "ge(a, b) -- Same as a>=b.")
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* itemgetter object **********************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t nitems;
- PyObject *item;
+ PyObject_HEAD
+ Py_ssize_t nitems;
+ PyObject *item;
} itemgetterobject;
static PyTypeObject itemgetter_type;
@@ -335,77 +335,77 @@ static PyTypeObject itemgetter_type;
static PyObject *
itemgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- itemgetterobject *ig;
- PyObject *item;
- Py_ssize_t nitems;
-
- if (!_PyArg_NoKeywords("itemgetter()", kwds))
- return NULL;
-
- nitems = PyTuple_GET_SIZE(args);
- if (nitems <= 1) {
- if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
- return NULL;
- } else
- item = args;
-
- /* create itemgetterobject structure */
- ig = PyObject_GC_New(itemgetterobject, &itemgetter_type);
- if (ig == NULL)
- return NULL;
-
- Py_INCREF(item);
- ig->item = item;
- ig->nitems = nitems;
-
- PyObject_GC_Track(ig);
- return (PyObject *)ig;
+ itemgetterobject *ig;
+ PyObject *item;
+ Py_ssize_t nitems;
+
+ if (!_PyArg_NoKeywords("itemgetter()", kwds))
+ return NULL;
+
+ nitems = PyTuple_GET_SIZE(args);
+ if (nitems <= 1) {
+ if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &item))
+ return NULL;
+ } else
+ item = args;
+
+ /* create itemgetterobject structure */
+ ig = PyObject_GC_New(itemgetterobject, &itemgetter_type);
+ if (ig == NULL)
+ return NULL;
+
+ Py_INCREF(item);
+ ig->item = item;
+ ig->nitems = nitems;
+
+ PyObject_GC_Track(ig);
+ return (PyObject *)ig;
}
static void
itemgetter_dealloc(itemgetterobject *ig)
{
- PyObject_GC_UnTrack(ig);
- Py_XDECREF(ig->item);
- PyObject_GC_Del(ig);
+ PyObject_GC_UnTrack(ig);
+ Py_XDECREF(ig->item);
+ PyObject_GC_Del(ig);
}
static int
itemgetter_traverse(itemgetterobject *ig, visitproc visit, void *arg)
{
- Py_VISIT(ig->item);
- return 0;
+ Py_VISIT(ig->item);
+ return 0;
}
static PyObject *
itemgetter_call(itemgetterobject *ig, PyObject *args, PyObject *kw)
{
- PyObject *obj, *result;
- Py_ssize_t i, nitems=ig->nitems;
-
- if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
- return NULL;
- if (nitems == 1)
- return PyObject_GetItem(obj, ig->item);
-
- assert(PyTuple_Check(ig->item));
- assert(PyTuple_GET_SIZE(ig->item) == nitems);
-
- result = PyTuple_New(nitems);
- if (result == NULL)
- return NULL;
-
- for (i=0 ; i < nitems ; i++) {
- PyObject *item, *val;
- item = PyTuple_GET_ITEM(ig->item, i);
- val = PyObject_GetItem(obj, item);
- if (val == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, val);
- }
- return result;
+ PyObject *obj, *result;
+ Py_ssize_t i, nitems=ig->nitems;
+
+ if (!PyArg_UnpackTuple(args, "itemgetter", 1, 1, &obj))
+ return NULL;
+ if (nitems == 1)
+ return PyObject_GetItem(obj, ig->item);
+
+ assert(PyTuple_Check(ig->item));
+ assert(PyTuple_GET_SIZE(ig->item) == nitems);
+
+ result = PyTuple_New(nitems);
+ if (result == NULL)
+ return NULL;
+
+ for (i=0 ; i < nitems ; i++) {
+ PyObject *item, *val;
+ item = PyTuple_GET_ITEM(ig->item, i);
+ val = PyObject_GetItem(obj, item);
+ if (val == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, val);
+ }
+ return result;
}
PyDoc_STRVAR(itemgetter_doc,
@@ -416,55 +416,55 @@ After, f=itemgetter(2), the call f(r) returns r[2].\n\
After, g=itemgetter(2,5,3), the call g(r) returns (r[2], r[5], r[3])");
static PyTypeObject itemgetter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "operator.itemgetter", /* tp_name */
- sizeof(itemgetterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)itemgetter_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)itemgetter_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- itemgetter_doc, /* tp_doc */
- (traverseproc)itemgetter_traverse, /* 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- itemgetter_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "operator.itemgetter", /* tp_name */
+ sizeof(itemgetterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)itemgetter_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)itemgetter_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ itemgetter_doc, /* tp_doc */
+ (traverseproc)itemgetter_traverse, /* 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ itemgetter_new, /* tp_new */
+ 0, /* tp_free */
};
/* attrgetter object **********************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t nattrs;
- PyObject *attr;
+ PyObject_HEAD
+ Py_ssize_t nattrs;
+ PyObject *attr;
} attrgetterobject;
static PyTypeObject attrgetter_type;
@@ -472,120 +472,120 @@ static PyTypeObject attrgetter_type;
static PyObject *
attrgetter_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- attrgetterobject *ag;
- PyObject *attr;
- Py_ssize_t nattrs;
-
- if (!_PyArg_NoKeywords("attrgetter()", kwds))
- return NULL;
-
- nattrs = PyTuple_GET_SIZE(args);
- if (nattrs <= 1) {
- if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
- return NULL;
- } else
- attr = args;
-
- /* create attrgetterobject structure */
- ag = PyObject_GC_New(attrgetterobject, &attrgetter_type);
- if (ag == NULL)
- return NULL;
-
- Py_INCREF(attr);
- ag->attr = attr;
- ag->nattrs = nattrs;
-
- PyObject_GC_Track(ag);
- return (PyObject *)ag;
+ attrgetterobject *ag;
+ PyObject *attr;
+ Py_ssize_t nattrs;
+
+ if (!_PyArg_NoKeywords("attrgetter()", kwds))
+ return NULL;
+
+ nattrs = PyTuple_GET_SIZE(args);
+ if (nattrs <= 1) {
+ if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &attr))
+ return NULL;
+ } else
+ attr = args;
+
+ /* create attrgetterobject structure */
+ ag = PyObject_GC_New(attrgetterobject, &attrgetter_type);
+ if (ag == NULL)
+ return NULL;
+
+ Py_INCREF(attr);
+ ag->attr = attr;
+ ag->nattrs = nattrs;
+
+ PyObject_GC_Track(ag);
+ return (PyObject *)ag;
}
static void
attrgetter_dealloc(attrgetterobject *ag)
{
- PyObject_GC_UnTrack(ag);
- Py_XDECREF(ag->attr);
- PyObject_GC_Del(ag);
+ PyObject_GC_UnTrack(ag);
+ Py_XDECREF(ag->attr);
+ PyObject_GC_Del(ag);
}
static int
attrgetter_traverse(attrgetterobject *ag, visitproc visit, void *arg)
{
- Py_VISIT(ag->attr);
- return 0;
+ Py_VISIT(ag->attr);
+ return 0;
}
static PyObject *
dotted_getattr(PyObject *obj, PyObject *attr)
{
- char *s, *p;
+ char *s, *p;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(attr)) {
- attr = _PyUnicode_AsDefaultEncodedString(attr, NULL);
- if (attr == NULL)
- return NULL;
- }
+ if (PyUnicode_Check(attr)) {
+ attr = _PyUnicode_AsDefaultEncodedString(attr, NULL);
+ if (attr == NULL)
+ return NULL;
+ }
#endif
-
- if (!PyString_Check(attr)) {
- PyErr_SetString(PyExc_TypeError,
- "attribute name must be a string");
- return NULL;
- }
-
- s = PyString_AS_STRING(attr);
- Py_INCREF(obj);
- for (;;) {
- PyObject *newobj, *str;
- p = strchr(s, '.');
- str = p ? PyString_FromStringAndSize(s, (p-s)) :
- PyString_FromString(s);
- if (str == NULL) {
- Py_DECREF(obj);
- return NULL;
- }
- newobj = PyObject_GetAttr(obj, str);
- Py_DECREF(str);
- Py_DECREF(obj);
- if (newobj == NULL)
- return NULL;
- obj = newobj;
- if (p == NULL) break;
- s = p+1;
- }
-
- return obj;
+
+ if (!PyString_Check(attr)) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute name must be a string");
+ return NULL;
+ }
+
+ s = PyString_AS_STRING(attr);
+ Py_INCREF(obj);
+ for (;;) {
+ PyObject *newobj, *str;
+ p = strchr(s, '.');
+ str = p ? PyString_FromStringAndSize(s, (p-s)) :
+ PyString_FromString(s);
+ if (str == NULL) {
+ Py_DECREF(obj);
+ return NULL;
+ }
+ newobj = PyObject_GetAttr(obj, str);
+ Py_DECREF(str);
+ Py_DECREF(obj);
+ if (newobj == NULL)
+ return NULL;
+ obj = newobj;
+ if (p == NULL) break;
+ s = p+1;
+ }
+
+ return obj;
}
static PyObject *
attrgetter_call(attrgetterobject *ag, PyObject *args, PyObject *kw)
{
- PyObject *obj, *result;
- Py_ssize_t i, nattrs=ag->nattrs;
-
- if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
- return NULL;
- if (ag->nattrs == 1)
- return dotted_getattr(obj, ag->attr);
-
- assert(PyTuple_Check(ag->attr));
- assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
-
- result = PyTuple_New(nattrs);
- if (result == NULL)
- return NULL;
-
- for (i=0 ; i < nattrs ; i++) {
- PyObject *attr, *val;
- attr = PyTuple_GET_ITEM(ag->attr, i);
- val = dotted_getattr(obj, attr);
- if (val == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- PyTuple_SET_ITEM(result, i, val);
- }
- return result;
+ PyObject *obj, *result;
+ Py_ssize_t i, nattrs=ag->nattrs;
+
+ if (!PyArg_UnpackTuple(args, "attrgetter", 1, 1, &obj))
+ return NULL;
+ if (ag->nattrs == 1)
+ return dotted_getattr(obj, ag->attr);
+
+ assert(PyTuple_Check(ag->attr));
+ assert(PyTuple_GET_SIZE(ag->attr) == nattrs);
+
+ result = PyTuple_New(nattrs);
+ if (result == NULL)
+ return NULL;
+
+ for (i=0 ; i < nattrs ; i++) {
+ PyObject *attr, *val;
+ attr = PyTuple_GET_ITEM(ag->attr, i);
+ val = dotted_getattr(obj, attr);
+ if (val == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(result, i, val);
+ }
+ return result;
}
PyDoc_STRVAR(attrgetter_doc,
@@ -598,56 +598,56 @@ After, h=attrgetter('name.first', 'name.last'), the call h(r) returns\n\
(r.name.first, r.name.last).");
static PyTypeObject attrgetter_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "operator.attrgetter", /* tp_name */
- sizeof(attrgetterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)attrgetter_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)attrgetter_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- attrgetter_doc, /* tp_doc */
- (traverseproc)attrgetter_traverse, /* 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- attrgetter_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "operator.attrgetter", /* tp_name */
+ sizeof(attrgetterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)attrgetter_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)attrgetter_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ attrgetter_doc, /* tp_doc */
+ (traverseproc)attrgetter_traverse, /* 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ attrgetter_new, /* tp_new */
+ 0, /* tp_free */
};
/* methodcaller object **********************************************************/
typedef struct {
- PyObject_HEAD
- PyObject *name;
- PyObject *args;
- PyObject *kwds;
+ PyObject_HEAD
+ PyObject *name;
+ PyObject *args;
+ PyObject *kwds;
} methodcallerobject;
static PyTypeObject methodcaller_type;
@@ -655,69 +655,69 @@ static PyTypeObject methodcaller_type;
static PyObject *
methodcaller_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- methodcallerobject *mc;
- PyObject *name, *newargs;
-
- if (PyTuple_GET_SIZE(args) < 1) {
- PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
- "one argument, the method name");
- return NULL;
- }
-
- /* create methodcallerobject structure */
- mc = PyObject_GC_New(methodcallerobject, &methodcaller_type);
- if (mc == NULL)
- return NULL;
-
- newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
- if (newargs == NULL) {
- Py_DECREF(mc);
- return NULL;
- }
- mc->args = newargs;
-
- name = PyTuple_GET_ITEM(args, 0);
- Py_INCREF(name);
- mc->name = name;
-
- Py_XINCREF(kwds);
- mc->kwds = kwds;
-
- PyObject_GC_Track(mc);
- return (PyObject *)mc;
+ methodcallerobject *mc;
+ PyObject *name, *newargs;
+
+ if (PyTuple_GET_SIZE(args) < 1) {
+ PyErr_SetString(PyExc_TypeError, "methodcaller needs at least "
+ "one argument, the method name");
+ return NULL;
+ }
+
+ /* create methodcallerobject structure */
+ mc = PyObject_GC_New(methodcallerobject, &methodcaller_type);
+ if (mc == NULL)
+ return NULL;
+
+ newargs = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
+ if (newargs == NULL) {
+ Py_DECREF(mc);
+ return NULL;
+ }
+ mc->args = newargs;
+
+ name = PyTuple_GET_ITEM(args, 0);
+ Py_INCREF(name);
+ mc->name = name;
+
+ Py_XINCREF(kwds);
+ mc->kwds = kwds;
+
+ PyObject_GC_Track(mc);
+ return (PyObject *)mc;
}
static void
methodcaller_dealloc(methodcallerobject *mc)
{
- PyObject_GC_UnTrack(mc);
- Py_XDECREF(mc->name);
- Py_XDECREF(mc->args);
- Py_XDECREF(mc->kwds);
- PyObject_GC_Del(mc);
+ PyObject_GC_UnTrack(mc);
+ Py_XDECREF(mc->name);
+ Py_XDECREF(mc->args);
+ Py_XDECREF(mc->kwds);
+ PyObject_GC_Del(mc);
}
static int
methodcaller_traverse(methodcallerobject *mc, visitproc visit, void *arg)
{
- Py_VISIT(mc->args);
- Py_VISIT(mc->kwds);
- return 0;
+ Py_VISIT(mc->args);
+ Py_VISIT(mc->kwds);
+ return 0;
}
static PyObject *
methodcaller_call(methodcallerobject *mc, PyObject *args, PyObject *kw)
{
- PyObject *method, *obj, *result;
-
- if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
- return NULL;
- method = PyObject_GetAttr(obj, mc->name);
- if (method == NULL)
- return NULL;
- result = PyObject_Call(method, mc->args, mc->kwds);
- Py_DECREF(method);
- return result;
+ PyObject *method, *obj, *result;
+
+ if (!PyArg_UnpackTuple(args, "methodcaller", 1, 1, &obj))
+ return NULL;
+ method = PyObject_GetAttr(obj, mc->name);
+ if (method == NULL)
+ return NULL;
+ result = PyObject_Call(method, mc->args, mc->kwds);
+ Py_DECREF(method);
+ return result;
}
PyDoc_STRVAR(methodcaller_doc,
@@ -729,46 +729,46 @@ After, g = methodcaller('name', 'date', foo=1), the call g(r) returns\n\
r.name('date', foo=1).");
static PyTypeObject methodcaller_type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "operator.methodcaller", /* tp_name */
- sizeof(methodcallerobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)methodcaller_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)methodcaller_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- methodcaller_doc, /* tp_doc */
- (traverseproc)methodcaller_traverse, /* 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- methodcaller_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "operator.methodcaller", /* tp_name */
+ sizeof(methodcallerobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)methodcaller_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)methodcaller_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ methodcaller_doc, /* tp_doc */
+ (traverseproc)methodcaller_traverse, /* 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ methodcaller_new, /* tp_new */
+ 0, /* tp_free */
};
@@ -777,26 +777,26 @@ static PyTypeObject methodcaller_type = {
PyMODINIT_FUNC
initoperator(void)
{
- PyObject *m;
-
- /* Create the module and add the functions */
- m = Py_InitModule4("operator", operator_methods, operator_doc,
- (PyObject*)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- if (PyType_Ready(&itemgetter_type) < 0)
- return;
- Py_INCREF(&itemgetter_type);
- PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
-
- if (PyType_Ready(&attrgetter_type) < 0)
- return;
- Py_INCREF(&attrgetter_type);
- PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
-
- if (PyType_Ready(&methodcaller_type) < 0)
- return;
- Py_INCREF(&methodcaller_type);
- PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
+ PyObject *m;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule4("operator", operator_methods, operator_doc,
+ (PyObject*)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ if (PyType_Ready(&itemgetter_type) < 0)
+ return;
+ Py_INCREF(&itemgetter_type);
+ PyModule_AddObject(m, "itemgetter", (PyObject *)&itemgetter_type);
+
+ if (PyType_Ready(&attrgetter_type) < 0)
+ return;
+ Py_INCREF(&attrgetter_type);
+ PyModule_AddObject(m, "attrgetter", (PyObject *)&attrgetter_type);
+
+ if (PyType_Ready(&methodcaller_type) < 0)
+ return;
+ Py_INCREF(&methodcaller_type);
+ PyModule_AddObject(m, "methodcaller", (PyObject *)&methodcaller_type);
}
diff --git a/Modules/parsermodule.c b/Modules/parsermodule.c
index af331ee..c36fcb0 100644
--- a/Modules/parsermodule.c
+++ b/Modules/parsermodule.c
@@ -555,8 +555,8 @@ parser_do_parse(PyObject *args, PyObject *kw, char *argspec, int type)
? eval_input : file_input,
&err, &flags);
- if (n) {
- res = parser_newstobject(n, type);
+ if (n) {
+ res = parser_newstobject(n, type);
if (res)
((PyST_Object *)res)->st_flags.cf_flags = flags & PyCF_MASK;
}
@@ -767,7 +767,7 @@ build_node_children(PyObject *tuple, node *root, int *line_num)
PyErr_Format(parser_error,
"third item in terminal node must be an"
" integer, found %s",
- Py_TYPE(temp)->tp_name);
+ Py_TYPE(temp)->tp_name);
Py_DECREF(o);
Py_DECREF(temp);
return 0;
@@ -941,8 +941,8 @@ VALIDATER(listmaker); VALIDATER(yield_stmt);
VALIDATER(testlist1); VALIDATER(comp_for);
VALIDATER(comp_iter); VALIDATER(comp_if);
VALIDATER(testlist_comp); VALIDATER(yield_expr);
-VALIDATER(yield_or_testlist); VALIDATER(or_test);
-VALIDATER(old_test); VALIDATER(old_lambdef);
+VALIDATER(yield_or_testlist); VALIDATER(or_test);
+VALIDATER(old_test); VALIDATER(old_lambdef);
#undef VALIDATER
@@ -1031,7 +1031,7 @@ validate_class(node *tree)
{
int nch = NCH(tree);
int res = (validate_ntype(tree, classdef) &&
- ((nch == 4) || (nch == 6) || (nch == 7)));
+ ((nch == 4) || (nch == 6) || (nch == 7)));
if (res) {
res = (validate_name(CHILD(tree, 0), "class")
@@ -1042,17 +1042,17 @@ validate_class(node *tree)
else {
(void) validate_numnodes(tree, 4, "class");
}
-
+
if (res) {
- if (nch == 7) {
- res = ((validate_lparen(CHILD(tree, 2)) &&
- validate_testlist(CHILD(tree, 3)) &&
- validate_rparen(CHILD(tree, 4))));
- }
- else if (nch == 6) {
- res = (validate_lparen(CHILD(tree,2)) &&
- validate_rparen(CHILD(tree,3)));
- }
+ if (nch == 7) {
+ res = ((validate_lparen(CHILD(tree, 2)) &&
+ validate_testlist(CHILD(tree, 3)) &&
+ validate_rparen(CHILD(tree, 4))));
+ }
+ else if (nch == 6) {
+ res = (validate_lparen(CHILD(tree,2)) &&
+ validate_rparen(CHILD(tree,3)));
+ }
}
return (res);
}
@@ -1433,7 +1433,7 @@ validate_comp_if(node *tree)
res = validate_comp_iter(CHILD(tree, 2));
else
res = validate_numnodes(tree, 2, "comp_if");
-
+
if (res)
res = (validate_name(CHILD(tree, 0), "if")
&& validate_old_test(CHILD(tree, 1)));
@@ -1593,10 +1593,10 @@ validate_compound_stmt(node *tree)
static int
validate_yield_or_testlist(node *tree)
{
- if (TYPE(tree) == yield_expr)
- return validate_yield_expr(tree);
- else
- return validate_testlist(tree);
+ if (TYPE(tree) == yield_expr)
+ return validate_yield_expr(tree);
+ else
+ return validate_testlist(tree);
}
static int
@@ -1611,7 +1611,7 @@ validate_expr_stmt(node *tree)
if (res && nch == 3
&& TYPE(CHILD(tree, 1)) == augassign) {
res = validate_numnodes(CHILD(tree, 1), 1, "augassign")
- && validate_yield_or_testlist(CHILD(tree, 2));
+ && validate_yield_or_testlist(CHILD(tree, 2));
if (res) {
char *s = STR(CHILD(CHILD(tree, 1), 0));
@@ -1837,14 +1837,14 @@ validate_dotted_as_name(node *tree)
static int
validate_dotted_as_names(node *tree)
{
- int nch = NCH(tree);
- int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
- int i;
+ int nch = NCH(tree);
+ int res = is_odd(nch) && validate_dotted_as_name(CHILD(tree, 0));
+ int i;
- for (i = 1; res && (i < nch); i += 2)
- res = (validate_comma(CHILD(tree, i))
- && validate_dotted_as_name(CHILD(tree, i + 1)));
- return (res);
+ for (i = 1; res && (i < nch); i += 2)
+ res = (validate_comma(CHILD(tree, i))
+ && validate_dotted_as_name(CHILD(tree, i + 1)));
+ return (res);
}
@@ -1857,8 +1857,8 @@ validate_import_as_names(node *tree)
int i;
for (i = 1; res && (i + 1 < nch); i += 2)
- res = (validate_comma(CHILD(tree, i))
- && validate_import_as_name(CHILD(tree, i + 1)));
+ res = (validate_comma(CHILD(tree, i))
+ && validate_import_as_name(CHILD(tree, i + 1)));
return (res);
}
@@ -1867,13 +1867,13 @@ validate_import_as_names(node *tree)
static int
validate_import_name(node *tree)
{
- return (validate_ntype(tree, import_name)
- && validate_numnodes(tree, 2, "import_name")
- && validate_name(CHILD(tree, 0), "import")
- && validate_dotted_as_names(CHILD(tree, 1)));
+ return (validate_ntype(tree, import_name)
+ && validate_numnodes(tree, 2, "import_name")
+ && validate_name(CHILD(tree, 0), "import")
+ && validate_dotted_as_names(CHILD(tree, 1)));
}
-/* Helper function to count the number of leading dots in
+/* Helper function to count the number of leading dots in
* 'from ...module import name'
*/
static int
@@ -1881,8 +1881,8 @@ count_from_dots(node *tree)
{
int i;
for (i = 1; i < NCH(tree); i++)
- if (TYPE(CHILD(tree, i)) != DOT)
- break;
+ if (TYPE(CHILD(tree, i)) != DOT)
+ break;
return i-1;
}
@@ -1892,24 +1892,24 @@ count_from_dots(node *tree)
static int
validate_import_from(node *tree)
{
- int nch = NCH(tree);
- int ndots = count_from_dots(tree);
- int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
- int offset = ndots + havename;
- int res = validate_ntype(tree, import_from)
- && (nch >= 4 + ndots)
- && validate_name(CHILD(tree, 0), "from")
- && (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
- && validate_name(CHILD(tree, offset + 1), "import");
-
- if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
- res = ((nch == offset + 5)
- && validate_lparen(CHILD(tree, offset + 2))
- && validate_import_as_names(CHILD(tree, offset + 3))
- && validate_rparen(CHILD(tree, offset + 4)));
- else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
- res = validate_import_as_names(CHILD(tree, offset + 2));
- return (res);
+ int nch = NCH(tree);
+ int ndots = count_from_dots(tree);
+ int havename = (TYPE(CHILD(tree, ndots + 1)) == dotted_name);
+ int offset = ndots + havename;
+ int res = validate_ntype(tree, import_from)
+ && (nch >= 4 + ndots)
+ && validate_name(CHILD(tree, 0), "from")
+ && (!havename || validate_dotted_name(CHILD(tree, ndots + 1)))
+ && validate_name(CHILD(tree, offset + 1), "import");
+
+ if (res && TYPE(CHILD(tree, offset + 2)) == LPAR)
+ res = ((nch == offset + 5)
+ && validate_lparen(CHILD(tree, offset + 2))
+ && validate_import_as_names(CHILD(tree, offset + 3))
+ && validate_rparen(CHILD(tree, offset + 4)));
+ else if (res && TYPE(CHILD(tree, offset + 2)) != STAR)
+ res = validate_import_as_names(CHILD(tree, offset + 2));
+ return (res);
}
@@ -1921,9 +1921,9 @@ validate_import_stmt(node *tree)
int res = validate_numnodes(tree, 1, "import_stmt");
if (res) {
- int ntype = TYPE(CHILD(tree, 0));
+ int ntype = TYPE(CHILD(tree, 0));
- if (ntype == import_name || ntype == import_from)
+ if (ntype == import_name || ntype == import_from)
res = validate_node(CHILD(tree, 0));
else {
res = 0;
@@ -2456,11 +2456,11 @@ validate_atom(node *tree)
&& (validate_rparen(CHILD(tree, nch - 1))));
if (res && (nch == 3)) {
- if (TYPE(CHILD(tree, 1))==yield_expr)
- res = validate_yield_expr(CHILD(tree, 1));
- else
- res = validate_testlist_comp(CHILD(tree, 1));
- }
+ if (TYPE(CHILD(tree, 1))==yield_expr)
+ res = validate_yield_expr(CHILD(tree, 1));
+ else
+ res = validate_testlist_comp(CHILD(tree, 1));
+ }
break;
case LSQB:
if (nch == 2)
@@ -2586,17 +2586,17 @@ validate_decorator(node *tree)
int ok;
int nch = NCH(tree);
ok = (validate_ntype(tree, decorator) &&
- (nch == 3 || nch == 5 || nch == 6) &&
- validate_at(CHILD(tree, 0)) &&
- validate_dotted_name(CHILD(tree, 1)) &&
- validate_newline(RCHILD(tree, -1)));
+ (nch == 3 || nch == 5 || nch == 6) &&
+ validate_at(CHILD(tree, 0)) &&
+ validate_dotted_name(CHILD(tree, 1)) &&
+ validate_newline(RCHILD(tree, -1)));
if (ok && nch != 3) {
- ok = (validate_lparen(CHILD(tree, 2)) &&
- validate_rparen(RCHILD(tree, -2)));
+ ok = (validate_lparen(CHILD(tree, 2)) &&
+ validate_rparen(RCHILD(tree, -2)));
- if (ok && nch == 6)
- ok = validate_arglist(CHILD(tree, 3));
+ if (ok && nch == 6)
+ ok = validate_arglist(CHILD(tree, 3));
}
return ok;
@@ -2608,12 +2608,12 @@ validate_decorator(node *tree)
static int
validate_decorators(node *tree)
{
- int i, nch, ok;
+ int i, nch, ok;
nch = NCH(tree);
ok = validate_ntype(tree, decorators) && nch >= 1;
for (i = 0; ok && i < nch; ++i)
- ok = validate_decorator(CHILD(tree, i));
+ ok = validate_decorator(CHILD(tree, i));
return ok;
}
@@ -2628,7 +2628,7 @@ validate_with_item(node *tree)
int ok = (validate_ntype(tree, with_item)
&& (nch == 1 || nch == 3)
&& validate_test(CHILD(tree, 0)));
- if (ok && nch == 3)
+ if (ok && nch == 3)
ok = (validate_name(CHILD(tree, 1), "as")
&& validate_expr(CHILD(tree, 2)));
return ok;
@@ -2654,7 +2654,7 @@ validate_with_stmt(node *tree)
}
/* funcdef:
- *
+ *
* -5 -4 -3 -2 -1
* 'def' NAME parameters ':' suite
*/
@@ -2663,12 +2663,12 @@ validate_funcdef(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, funcdef)
- && (nch == 5)
- && validate_name(RCHILD(tree, -5), "def")
- && validate_ntype(RCHILD(tree, -4), NAME)
- && validate_colon(RCHILD(tree, -2))
- && validate_parameters(RCHILD(tree, -3))
- && validate_suite(RCHILD(tree, -1)));
+ && (nch == 5)
+ && validate_name(RCHILD(tree, -5), "def")
+ && validate_ntype(RCHILD(tree, -4), NAME)
+ && validate_colon(RCHILD(tree, -2))
+ && validate_parameters(RCHILD(tree, -3))
+ && validate_suite(RCHILD(tree, -1)));
return ok;
}
@@ -2681,11 +2681,11 @@ validate_decorated(node *tree)
{
int nch = NCH(tree);
int ok = (validate_ntype(tree, decorated)
- && (nch == 2)
- && validate_decorators(RCHILD(tree, -2))
- && (validate_funcdef(RCHILD(tree, -1))
- || validate_class(RCHILD(tree, -1)))
- );
+ && (nch == 2)
+ && validate_decorators(RCHILD(tree, -2))
+ && (validate_funcdef(RCHILD(tree, -1))
+ || validate_class(RCHILD(tree, -1)))
+ );
return ok;
}
@@ -2965,8 +2965,8 @@ validate_exprlist(node *tree)
}
-/*
- * dictorsetmaker:
+/*
+ * dictorsetmaker:
*
* (test ':' test (comp_for | (',' test ':' test)* [','])) |
* (test (comp_for | (',' test)* [',']))
@@ -2983,7 +2983,7 @@ validate_dictorsetmaker(node *tree)
if (ok && (nch == 1 || TYPE(CHILD(tree, 1)) == COMMA)) {
/* We got a set:
- * test (',' test)* [',']
+ * test (',' test)* [',']
*/
ok = validate_test(CHILD(tree, i++));
while (ok && nch - i >= 2) {
@@ -3086,9 +3086,9 @@ validate_node(node *tree)
case classdef:
res = validate_class(tree);
break;
- case decorated:
- res = validate_decorated(tree);
- break;
+ case decorated:
+ res = validate_decorated(tree);
+ break;
/*
* "Trivial" parse tree nodes.
* (Why did I call these trivial?)
@@ -3160,12 +3160,12 @@ validate_node(node *tree)
case import_stmt:
res = validate_import_stmt(tree);
break;
- case import_name:
- res = validate_import_name(tree);
- break;
- case import_from:
- res = validate_import_from(tree);
- break;
+ case import_name:
+ res = validate_import_name(tree);
+ break;
+ case import_from:
+ res = validate_import_from(tree);
+ break;
case global_stmt:
res = validate_global_stmt(tree);
break;
@@ -3401,7 +3401,7 @@ initparser(void)
Py_TYPE(&PyST_Type) = &PyType_Type;
module = Py_InitModule("parser", parser_functions);
if (module == NULL)
- return;
+ return;
if (parser_error == 0)
parser_error = PyErr_NewException("parser.ParserError", NULL, NULL);
diff --git a/Modules/puremodule.c b/Modules/puremodule.c
index ede63ab..b89f172 100644
--- a/Modules/puremodule.c
+++ b/Modules/puremodule.c
@@ -58,107 +58,107 @@ typedef int (*PrintfishFunc)(const char*, ...);
typedef int (*StringIntArgFunc)(const char*, int);
-
+
static PyObject*
call_voidarg_function(VoidArgFunc func, PyObject *self, PyObject *args)
{
- int status;
+ int status;
- if (!PyArg_ParseTuple(args, ""))
- return NULL;
+ if (!PyArg_ParseTuple(args, ""))
+ return NULL;
- status = func();
- return Py_BuildValue("i", status);
+ status = func();
+ return Py_BuildValue("i", status);
}
static PyObject*
call_stringarg_function(StringArgFunc func, PyObject *self, PyObject *args)
{
- int status;
- char* stringarg;
+ int status;
+ char* stringarg;
- if (!PyArg_ParseTuple(args, "s", &stringarg))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s", &stringarg))
+ return NULL;
- status = func(stringarg);
- return Py_BuildValue("i", status);
+ status = func(stringarg);
+ return Py_BuildValue("i", status);
}
static PyObject*
call_stringorint_function(StringArgFunc func, PyObject *self, PyObject *args)
{
- int status;
- int intarg;
- char* stringarg;
+ int status;
+ int intarg;
+ char* stringarg;
- /* according to the quantify.h file, the argument to
- * quantify_*_recording_system_call can be an integer or a string,
- * but the functions are prototyped as taking a single char*
- * argument. Yikes!
+ /* according to the quantify.h file, the argument to
+ * quantify_*_recording_system_call can be an integer or a string,
+ * but the functions are prototyped as taking a single char*
+ * argument. Yikes!
+ */
+ if (PyArg_ParseTuple(args, "i", &intarg))
+ /* func is prototyped as int(*)(char*)
+ * better shut up the compiler
*/
- if (PyArg_ParseTuple(args, "i", &intarg))
- /* func is prototyped as int(*)(char*)
- * better shut up the compiler
- */
- status = func((char*)intarg);
+ status = func((char*)intarg);
- else {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s", &stringarg))
- return NULL;
- else
- status = func(stringarg);
- }
- return Py_BuildValue("i", status);
+ else {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "s", &stringarg))
+ return NULL;
+ else
+ status = func(stringarg);
+ }
+ return Py_BuildValue("i", status);
}
static PyObject*
call_printfish_function(PrintfishFunc func, PyObject *self, PyObject *args)
{
- /* we support the printf() style vararg functions by requiring the
- * formatting be done in Python. At the C level we pass just a string
- * to the printf() style function.
- */
- int status;
- char* argstring;
+ /* we support the printf() style vararg functions by requiring the
+ * formatting be done in Python. At the C level we pass just a string
+ * to the printf() style function.
+ */
+ int status;
+ char* argstring;
- if (!PyArg_ParseTuple(args, "s", &argstring))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s", &argstring))
+ return NULL;
- status = func("%s", argstring);
- return Py_BuildValue("i", status);
+ status = func("%s", argstring);
+ return Py_BuildValue("i", status);
}
static PyObject*
call_intasaddr_function(StringArgFunc func, PyObject *self, PyObject *args)
{
- long memrep;
- int id;
+ long memrep;
+ int id;
- if (!PyArg_ParseTuple(args, "l", &memrep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l", &memrep))
+ return NULL;
- id = func((char*)memrep);
- return Py_BuildValue("i", id);
+ id = func((char*)memrep);
+ return Py_BuildValue("i", id);
}
static PyObject*
call_stringandint_function(StringIntArgFunc func, PyObject *self,
- PyObject *args)
+ PyObject *args)
{
- long srcrep;
- int size;
- int status;
+ long srcrep;
+ int size;
+ int status;
- if (!PyArg_ParseTuple(args, "li", &srcrep, &size))
- return NULL;
+ if (!PyArg_ParseTuple(args, "li", &srcrep, &size))
+ return NULL;
- status = func((char*)srcrep, size);
- return Py_BuildValue("i", status);
+ status = func((char*)srcrep, size);
+ return Py_BuildValue("i", status);
}
-
+
/* functions common to all products
*
* N.B. These printf() style functions are a bit of a kludge. Since the
@@ -174,26 +174,26 @@ call_stringandint_function(StringIntArgFunc func, PyObject *self,
static PyObject*
pure_pure_logfile_printf(PyObject* self, PyObject* args)
{
- return call_printfish_function(pure_logfile_printf, self, args);
+ return call_printfish_function(pure_logfile_printf, self, args);
}
static PyObject*
pure_pure_printf(PyObject* self, PyObject* args)
{
- return call_printfish_function(pure_printf, self, args);
+ return call_printfish_function(pure_printf, self, args);
}
static PyObject*
pure_pure_printf_with_banner(PyObject* self, PyObject* args)
{
- return call_printfish_function(pure_printf_with_banner, self, args);
+ return call_printfish_function(pure_printf_with_banner, self, args);
}
#endif /* COMMON_PURE_FUNCTIONS */
-
+
/* Purify functions
*
* N.B. There are some interfaces described in the purify.h file that are
@@ -235,97 +235,97 @@ pure_pure_printf_with_banner(PyObject* self, PyObject* args)
static PyObject*
pure_purify_all_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_inuse, self, args);
+ return call_voidarg_function(purify_all_inuse, self, args);
}
static PyObject*
pure_purify_all_leaks(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_leaks, self, args);
+ return call_voidarg_function(purify_all_leaks, self, args);
}
static PyObject*
pure_purify_new_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_inuse, self, args);
+ return call_voidarg_function(purify_new_inuse, self, args);
}
static PyObject*
pure_purify_new_leaks(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_leaks, self, args);
+ return call_voidarg_function(purify_new_leaks, self, args);
}
static PyObject*
pure_purify_clear_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_inuse, self, args);
+ return call_voidarg_function(purify_clear_inuse, self, args);
}
static PyObject*
pure_purify_clear_leaks(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_leaks, self, args);
+ return call_voidarg_function(purify_clear_leaks, self, args);
}
static PyObject*
pure_purify_all_fds_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_fds_inuse, self, args);
+ return call_voidarg_function(purify_all_fds_inuse, self, args);
}
static PyObject*
pure_purify_new_fds_inuse(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_fds_inuse, self, args);
+ return call_voidarg_function(purify_new_fds_inuse, self, args);
}
static PyObject*
pure_purify_printf_with_call_chain(PyObject *self, PyObject *args)
{
- return call_printfish_function(purify_printf_with_call_chain,
- self, args);
+ return call_printfish_function(purify_printf_with_call_chain,
+ self, args);
}
static PyObject*
pure_purify_set_pool_id(PyObject *self, PyObject *args)
{
- long memrep;
- int id;
+ long memrep;
+ int id;
- if (!PyArg_ParseTuple(args, "li:purify_set_pool_id", &memrep, &id))
- return NULL;
+ if (!PyArg_ParseTuple(args, "li:purify_set_pool_id", &memrep, &id))
+ return NULL;
- purify_set_pool_id((char*)memrep, id);
- Py_INCREF(Py_None);
- return Py_None;
+ purify_set_pool_id((char*)memrep, id);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject*
pure_purify_get_pool_id(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_get_pool_id, self, args);
+ return call_intasaddr_function(purify_get_pool_id, self, args);
}
static PyObject*
pure_purify_set_user_data(PyObject *self, PyObject *args)
{
- long memrep;
- long datarep;
+ long memrep;
+ long datarep;
- if (!PyArg_ParseTuple(args, "ll:purify_set_user_data", &memrep, &datarep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "ll:purify_set_user_data", &memrep, &datarep))
+ return NULL;
- purify_set_user_data((char*)memrep, (void*)datarep);
- Py_INCREF(Py_None);
- return Py_None;
+ purify_set_user_data((char*)memrep, (void*)datarep);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject*
pure_purify_get_user_data(PyObject *self, PyObject *args)
{
- /* can't use call_intasaddr_function() since purify_get_user_data()
- * returns a void*
- */
- long memrep;
- void* data;
+ /* can't use call_intasaddr_function() since purify_get_user_data()
+ * returns a void*
+ */
+ long memrep;
+ void* data;
- if (!PyArg_ParseTuple(args, "l:purify_get_user_data", &memrep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:purify_get_user_data", &memrep))
+ return NULL;
- data = purify_get_user_data((char*)memrep);
- return Py_BuildValue("l", (long)data);
+ data = purify_get_user_data((char*)memrep);
+ return Py_BuildValue("l", (long)data);
}
-
+
/* this global variable is shared by both mapping functions:
* pure_purify_map_pool() and pure_purify_map_pool_id(). Since they cache
* this variable it should be safe in the face of recursion or cross
@@ -341,303 +341,303 @@ static PyObject* MapCallable = NULL;
static void
map_pool_callback(char* mem, int user_size, void *user_aux_data)
{
- long memrep = (long)mem;
- long user_aux_data_rep = (long)user_aux_data;
- PyObject* result;
- PyObject* memobj = Py_BuildValue("lil", memrep, user_size,
- user_aux_data_rep);
+ long memrep = (long)mem;
+ long user_aux_data_rep = (long)user_aux_data;
+ PyObject* result;
+ PyObject* memobj = Py_BuildValue("lil", memrep, user_size,
+ user_aux_data_rep);
- if (memobj == NULL)
- return;
+ if (memobj == NULL)
+ return;
- result = PyEval_CallObject(MapCallable, memobj);
- Py_DECREF(result);
- Py_DECREF(memobj);
+ result = PyEval_CallObject(MapCallable, memobj);
+ Py_DECREF(result);
+ Py_DECREF(memobj);
}
static PyObject*
pure_purify_map_pool(PyObject *self, PyObject *args)
{
- /* cache global variable in case of recursion */
- PyObject* saved_callable = MapCallable;
- PyObject* arg_callable;
- int id;
+ /* cache global variable in case of recursion */
+ PyObject* saved_callable = MapCallable;
+ PyObject* arg_callable;
+ int id;
- if (!PyArg_ParseTuple(args, "iO:purify_map_pool", &id, &arg_callable))
- return NULL;
+ if (!PyArg_ParseTuple(args, "iO:purify_map_pool", &id, &arg_callable))
+ return NULL;
- if (!PyCallable_Check(arg_callable)) {
- PyErr_SetString(PyExc_TypeError,
- "Second argument must be callable");
- return NULL;
- }
- MapCallable = arg_callable;
- purify_map_pool(id, map_pool_callback);
- MapCallable = saved_callable;
+ if (!PyCallable_Check(arg_callable)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Second argument must be callable");
+ return NULL;
+ }
+ MapCallable = arg_callable;
+ purify_map_pool(id, map_pool_callback);
+ MapCallable = saved_callable;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
PurifyMapPoolIdCallback(int id)
{
- PyObject* result;
- PyObject* intobj = Py_BuildValue("i", id);
+ PyObject* result;
+ PyObject* intobj = Py_BuildValue("i", id);
- if (intobj == NULL)
- return;
+ if (intobj == NULL)
+ return;
- result = PyEval_CallObject(MapCallable, intobj);
- Py_DECREF(result);
- Py_DECREF(intobj);
+ result = PyEval_CallObject(MapCallable, intobj);
+ Py_DECREF(result);
+ Py_DECREF(intobj);
}
static PyObject*
pure_purify_map_pool_id(PyObject *self, PyObject *args)
{
- /* cache global variable in case of recursion */
- PyObject* saved_callable = MapCallable;
- PyObject* arg_callable;
+ /* cache global variable in case of recursion */
+ PyObject* saved_callable = MapCallable;
+ PyObject* arg_callable;
- if (!PyArg_ParseTuple(args, "O:purify_map_pool_id", &arg_callable))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:purify_map_pool_id", &arg_callable))
+ return NULL;
- if (!PyCallable_Check(arg_callable)) {
- PyErr_SetString(PyExc_TypeError, "Argument must be callable.");
- return NULL;
- }
+ if (!PyCallable_Check(arg_callable)) {
+ PyErr_SetString(PyExc_TypeError, "Argument must be callable.");
+ return NULL;
+ }
- MapCallable = arg_callable;
- purify_map_pool_id(PurifyMapPoolIdCallback);
- MapCallable = saved_callable;
+ MapCallable = arg_callable;
+ purify_map_pool_id(PurifyMapPoolIdCallback);
+ MapCallable = saved_callable;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-
+
static PyObject*
pure_purify_new_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_new_messages, self, args);
+ return call_voidarg_function(purify_new_messages, self, args);
}
static PyObject*
pure_purify_all_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_all_messages, self, args);
+ return call_voidarg_function(purify_all_messages, self, args);
}
static PyObject*
pure_purify_clear_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_messages, self, args);
+ return call_voidarg_function(purify_clear_messages, self, args);
}
static PyObject*
pure_purify_clear_new_messages(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_clear_new_messages, self, args);
+ return call_voidarg_function(purify_clear_new_messages, self, args);
}
static PyObject*
pure_purify_start_batch(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_start_batch, self, args);
+ return call_voidarg_function(purify_start_batch, self, args);
}
static PyObject*
pure_purify_start_batch_show_first(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_start_batch_show_first,
- self, args);
+ return call_voidarg_function(purify_start_batch_show_first,
+ self, args);
}
static PyObject*
pure_purify_stop_batch(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_stop_batch, self, args);
+ return call_voidarg_function(purify_stop_batch, self, args);
}
static PyObject*
pure_purify_name_thread(PyObject *self, PyObject *args)
{
- /* can't strictly use call_stringarg_function since
- * purify_name_thread takes a const char*, not a char*
- */
- int status;
- char* stringarg;
+ /* can't strictly use call_stringarg_function since
+ * purify_name_thread takes a const char*, not a char*
+ */
+ int status;
+ char* stringarg;
- if (!PyArg_ParseTuple(args, "s:purify_name_thread", &stringarg))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:purify_name_thread", &stringarg))
+ return NULL;
- status = purify_name_thread(stringarg);
- return Py_BuildValue("i", status);
+ status = purify_name_thread(stringarg);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_watch(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch, self, args);
+ return call_intasaddr_function(purify_watch, self, args);
}
static PyObject*
pure_purify_watch_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_1, self, args);
+ return call_intasaddr_function(purify_watch_1, self, args);
}
static PyObject*
pure_purify_watch_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_2, self, args);
+ return call_intasaddr_function(purify_watch_2, self, args);
}
static PyObject*
pure_purify_watch_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_4, self, args);
+ return call_intasaddr_function(purify_watch_4, self, args);
}
static PyObject*
pure_purify_watch_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_8, self, args);
+ return call_intasaddr_function(purify_watch_8, self, args);
}
static PyObject*
pure_purify_watch_w_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_1, self, args);
+ return call_intasaddr_function(purify_watch_w_1, self, args);
}
static PyObject*
pure_purify_watch_w_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_2, self, args);
+ return call_intasaddr_function(purify_watch_w_2, self, args);
}
static PyObject*
pure_purify_watch_w_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_4, self, args);
+ return call_intasaddr_function(purify_watch_w_4, self, args);
}
static PyObject*
pure_purify_watch_w_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_w_8, self, args);
+ return call_intasaddr_function(purify_watch_w_8, self, args);
}
static PyObject*
pure_purify_watch_r_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_1, self, args);
+ return call_intasaddr_function(purify_watch_r_1, self, args);
}
static PyObject*
pure_purify_watch_r_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_2, self, args);
+ return call_intasaddr_function(purify_watch_r_2, self, args);
}
static PyObject*
pure_purify_watch_r_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_4, self, args);
+ return call_intasaddr_function(purify_watch_r_4, self, args);
}
static PyObject*
pure_purify_watch_r_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_r_8, self, args);
+ return call_intasaddr_function(purify_watch_r_8, self, args);
}
static PyObject*
pure_purify_watch_rw_1(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_1, self, args);
+ return call_intasaddr_function(purify_watch_rw_1, self, args);
}
static PyObject*
pure_purify_watch_rw_2(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_2, self, args);
+ return call_intasaddr_function(purify_watch_rw_2, self, args);
}
static PyObject*
pure_purify_watch_rw_4(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_4, self, args);
+ return call_intasaddr_function(purify_watch_rw_4, self, args);
}
static PyObject*
pure_purify_watch_rw_8(PyObject *self, PyObject *args)
{
- return call_intasaddr_function(purify_watch_rw_8, self, args);
+ return call_intasaddr_function(purify_watch_rw_8, self, args);
}
static PyObject*
pure_purify_watch_n(PyObject *self, PyObject *args)
{
- long addrrep;
- unsigned int size;
- char* type;
- int status;
+ long addrrep;
+ unsigned int size;
+ char* type;
+ int status;
- if (!PyArg_ParseTuple(args, "lis:purify_watch_n", &addrrep, &size, &type))
- return NULL;
+ if (!PyArg_ParseTuple(args, "lis:purify_watch_n", &addrrep, &size, &type))
+ return NULL;
- status = purify_watch_n((char*)addrrep, size, type);
- return Py_BuildValue("i", status);
+ status = purify_watch_n((char*)addrrep, size, type);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_watch_info(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_watch_info, self, args);
+ return call_voidarg_function(purify_watch_info, self, args);
}
static PyObject*
pure_purify_watch_remove(PyObject *self, PyObject *args)
{
- int watchno;
- int status;
+ int watchno;
+ int status;
- if (!PyArg_ParseTuple(args, "i:purify_watch_remove", &watchno))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:purify_watch_remove", &watchno))
+ return NULL;
- status = purify_watch_remove(watchno);
- return Py_BuildValue("i", status);
+ status = purify_watch_remove(watchno);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_watch_remove_all(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_watch_remove_all, self, args);
+ return call_voidarg_function(purify_watch_remove_all, self, args);
}
static PyObject*
pure_purify_describe(PyObject *self, PyObject *args)
{
- long addrrep;
- char* rtn;
+ long addrrep;
+ char* rtn;
- if (!PyArg_ParseTuple(args, "l:purify_describe", &addrrep))
- return NULL;
+ if (!PyArg_ParseTuple(args, "l:purify_describe", &addrrep))
+ return NULL;
- rtn = purify_describe((char*)addrrep);
- return Py_BuildValue("l", (long)rtn);
+ rtn = purify_describe((char*)addrrep);
+ return Py_BuildValue("l", (long)rtn);
}
static PyObject*
pure_purify_what_colors(PyObject *self, PyObject *args)
{
- long addrrep;
- unsigned int size;
- int status;
-
- if (!PyArg_ParseTuple(args, "li:purify_what_colors", &addrrep, &size))
- return NULL;
+ long addrrep;
+ unsigned int size;
+ int status;
+
+ if (!PyArg_ParseTuple(args, "li:purify_what_colors", &addrrep, &size))
+ return NULL;
- status = purify_what_colors((char*)addrrep, size);
- return Py_BuildValue("i", status);
+ status = purify_what_colors((char*)addrrep, size);
+ return Py_BuildValue("i", status);
}
static PyObject*
pure_purify_is_running(PyObject *self, PyObject *args)
{
- return call_voidarg_function(purify_is_running, self, args);
+ return call_voidarg_function(purify_is_running, self, args);
}
static PyObject*
pure_purify_assert_is_readable(PyObject *self, PyObject *args)
{
- return call_stringandint_function(purify_assert_is_readable,
- self, args);
+ return call_stringandint_function(purify_assert_is_readable,
+ self, args);
}
static PyObject*
pure_purify_assert_is_writable(PyObject *self, PyObject *args)
{
- return call_stringandint_function(purify_assert_is_writable,
- self, args);
+ return call_stringandint_function(purify_assert_is_writable,
+ self, args);
}
#if HAS_PURIFY_EXIT
@@ -649,22 +649,22 @@ pure_purify_assert_is_writable(PyObject *self, PyObject *args)
static PyObject*
pure_purify_exit(PyObject *self, PyObject *args)
{
- int status;
+ int status;
- if (!PyArg_ParseTuple(args, "i:purify_exit", &status))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:purify_exit", &status))
+ return NULL;
- /* purify_exit doesn't always act like exit(). See the manual */
- purify_exit(status);
- Py_INCREF(Py_None);
- return Py_None;
+ /* purify_exit doesn't always act like exit(). See the manual */
+ purify_exit(status);
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* HAS_PURIFY_EXIT */
#endif /* PURIFY_H */
-
+
/* Quantify functions
*
* N.B. Some of these functions are only described in the quantify.h file,
@@ -680,144 +680,144 @@ pure_purify_exit(PyObject *self, PyObject *args)
static PyObject*
pure_quantify_is_running(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_is_running, self, args);
+ return call_voidarg_function(quantify_is_running, self, args);
}
static PyObject*
pure_quantify_help(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_help, self, args);
+ return call_voidarg_function(quantify_help, self, args);
}
static PyObject*
pure_quantify_print_recording_state(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_print_recording_state,
- self, args);
+ return call_voidarg_function(quantify_print_recording_state,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_start_recording_data,
- self, args);
+ return call_voidarg_function(quantify_start_recording_data,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_stop_recording_data, self, args);
+ return call_voidarg_function(quantify_stop_recording_data, self, args);
}
static PyObject*
pure_quantify_is_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_is_recording_data, self, args);
+ return call_voidarg_function(quantify_is_recording_data, self, args);
}
static PyObject*
pure_quantify_start_recording_system_calls(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_start_recording_system_calls,
- self, args);
+ return call_voidarg_function(quantify_start_recording_system_calls,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_system_calls(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_stop_recording_system_calls,
- self, args);
+ return call_voidarg_function(quantify_stop_recording_system_calls,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_system_calls(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_is_recording_system_calls,
- self, args);
+ return call_voidarg_function(quantify_is_recording_system_calls,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_system_call(PyObject *self, PyObject *args)
{
- return call_stringorint_function(quantify_start_recording_system_call,
- self, args);
+ return call_stringorint_function(quantify_start_recording_system_call,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_system_call(PyObject *self, PyObject *args)
{
- return call_stringorint_function(quantify_stop_recording_system_call,
- self, args);
+ return call_stringorint_function(quantify_stop_recording_system_call,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_system_call(PyObject *self, PyObject *args)
{
- return call_stringorint_function(quantify_is_recording_system_call,
- self, args);
+ return call_stringorint_function(quantify_is_recording_system_call,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_dynamic_library_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_start_recording_dynamic_library_data,
- self, args);
+ return call_voidarg_function(
+ quantify_start_recording_dynamic_library_data,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_dynamic_library_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_stop_recording_dynamic_library_data,
- self, args);
+ return call_voidarg_function(
+ quantify_stop_recording_dynamic_library_data,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_dynamic_library_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_is_recording_dynamic_library_data,
- self, args);
+ return call_voidarg_function(
+ quantify_is_recording_dynamic_library_data,
+ self, args);
}
static PyObject*
pure_quantify_start_recording_register_window_traps(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_start_recording_register_window_traps,
- self, args);
+ return call_voidarg_function(
+ quantify_start_recording_register_window_traps,
+ self, args);
}
static PyObject*
pure_quantify_stop_recording_register_window_traps(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_stop_recording_register_window_traps,
- self, args);
+ return call_voidarg_function(
+ quantify_stop_recording_register_window_traps,
+ self, args);
}
static PyObject*
pure_quantify_is_recording_register_window_traps(PyObject *self, PyObject *args)
{
- return call_voidarg_function(
- quantify_is_recording_register_window_traps,
- self, args);
+ return call_voidarg_function(
+ quantify_is_recording_register_window_traps,
+ self, args);
}
static PyObject*
pure_quantify_disable_recording_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_disable_recording_data,
- self, args);
+ return call_voidarg_function(quantify_disable_recording_data,
+ self, args);
}
static PyObject*
pure_quantify_clear_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_clear_data, self, args);
+ return call_voidarg_function(quantify_clear_data, self, args);
}
static PyObject*
pure_quantify_save_data(PyObject *self, PyObject *args)
{
- return call_voidarg_function(quantify_save_data, self, args);
+ return call_voidarg_function(quantify_save_data, self, args);
}
static PyObject*
pure_quantify_save_data_to_file(PyObject *self, PyObject *args)
{
- return call_stringarg_function(quantify_save_data_to_file, self, args);
+ return call_stringarg_function(quantify_save_data_to_file, self, args);
}
static PyObject*
pure_quantify_add_annotation(PyObject *self, PyObject *args)
{
- return call_stringarg_function(quantify_add_annotation, self, args);
+ return call_stringarg_function(quantify_add_annotation, self, args);
}
#endif /* QUANTIFY_H */
-
+
/* external interface
*/
static struct PyMethodDef
@@ -927,66 +927,66 @@ pure_methods[] = {
{"quantify_save_data_to_file", pure_quantify_save_data_to_file, METH_VARARGS},
{"quantify_add_annotation", pure_quantify_add_annotation, METH_VARARGS},
#endif /* QUANTIFY_H */
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
-
+
static void
ins(d, name, val)
- PyObject *d;
- char* name;
- long val;
+ PyObject *d;
+ char* name;
+ long val;
{
- PyObject *v = PyInt_FromLong(val);
- if (v) {
- (void)PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyInt_FromLong(val);
+ if (v) {
+ (void)PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
void
initpure()
{
- PyObject *m, *d;
+ PyObject *m, *d;
- if (PyErr_WarnPy3k("the pure module has been removed in "
- "Python 3.0", 2) < 0)
- return;
+ if (PyErr_WarnPy3k("the pure module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
- m = Py_InitModule("pure", pure_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
+ m = Py_InitModule("pure", pure_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
- /* this is bogus because we should be able to find this information
- * out from the header files. Pure's current versions don't
- * include this information!
- */
+ /* this is bogus because we should be able to find this information
+ * out from the header files. Pure's current versions don't
+ * include this information!
+ */
#ifdef PURE_PURIFY_VERSION
- ins(d, "PURIFY_VERSION", PURE_PURIFY_VERSION);
+ ins(d, "PURIFY_VERSION", PURE_PURIFY_VERSION);
#else
- PyDict_SetItemString(d, "PURIFY_VERSION", Py_None);
+ PyDict_SetItemString(d, "PURIFY_VERSION", Py_None);
#endif
- /* these aren't terribly useful because purify_exit() isn't
- * exported correctly. See the note at the top of the file.
- */
+ /* these aren't terribly useful because purify_exit() isn't
+ * exported correctly. See the note at the top of the file.
+ */
#ifdef PURIFY_EXIT_ERRORS
- ins(d, "PURIFY_EXIT_ERRORS", PURIFY_EXIT_ERRORS);
+ ins(d, "PURIFY_EXIT_ERRORS", PURIFY_EXIT_ERRORS);
#endif
#ifdef PURIFY_EXIT_LEAKS
- ins(d, "PURIFY_EXIT_LEAKS", PURIFY_EXIT_LEAKS);
+ ins(d, "PURIFY_EXIT_LEAKS", PURIFY_EXIT_LEAKS);
#endif
#ifdef PURIFY_EXIT_PLEAKS
- ins(d, "PURIFY_EXIT_PLEAKS", PURIFY_EXIT_PLEAKS);
+ ins(d, "PURIFY_EXIT_PLEAKS", PURIFY_EXIT_PLEAKS);
#endif
#ifdef PURE_QUANTIFY_VERSION
- ins(d, "QUANTIFY_VERSION", PURE_QUANTIFY_VERSION);
+ ins(d, "QUANTIFY_VERSION", PURE_QUANTIFY_VERSION);
#else
- PyDict_SetItemString(d, "QUANTIFY_VERSION", Py_None);
+ PyDict_SetItemString(d, "QUANTIFY_VERSION", Py_None);
#endif
}
diff --git a/Modules/pwdmodule.c b/Modules/pwdmodule.c
index d1ce394..ae358e0 100644
--- a/Modules/pwdmodule.c
+++ b/Modules/pwdmodule.c
@@ -8,14 +8,14 @@
#include <pwd.h>
static PyStructSequence_Field struct_pwd_type_fields[] = {
- {"pw_name", "user name"},
- {"pw_passwd", "password"},
- {"pw_uid", "user id"},
- {"pw_gid", "group id"},
- {"pw_gecos", "real name"},
- {"pw_dir", "home directory"},
- {"pw_shell", "shell program"},
- {0}
+ {"pw_name", "user name"},
+ {"pw_passwd", "password"},
+ {"pw_uid", "user id"},
+ {"pw_gid", "group id"},
+ {"pw_gecos", "real name"},
+ {"pw_dir", "home directory"},
+ {"pw_shell", "shell program"},
+ {0}
};
PyDoc_STRVAR(struct_passwd__doc__,
@@ -25,10 +25,10 @@ This object may be accessed either as a tuple of\n\
or via the object attributes as named in the above tuple.");
static PyStructSequence_Desc struct_pwd_type_desc = {
- "pwd.struct_passwd",
- struct_passwd__doc__,
- struct_pwd_type_fields,
- 7,
+ "pwd.struct_passwd",
+ struct_passwd__doc__,
+ struct_pwd_type_fields,
+ 7,
};
PyDoc_STRVAR(pwd__doc__,
@@ -41,7 +41,7 @@ pw_name, pw_passwd, pw_uid, pw_gid, pw_gecos, pw_dir, pw_shell.\n\
The uid and gid items are integers, all others are strings. An\n\
exception is raised if the entry asked for cannot be found.");
-
+
static int initialized;
static PyTypeObject StructPwdType;
@@ -49,49 +49,49 @@ static void
sets(PyObject *v, int i, char* val)
{
if (val)
- PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
+ PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
else {
- PyStructSequence_SET_ITEM(v, i, Py_None);
- Py_INCREF(Py_None);
+ PyStructSequence_SET_ITEM(v, i, Py_None);
+ Py_INCREF(Py_None);
}
}
static PyObject *
mkpwent(struct passwd *p)
{
- int setIndex = 0;
- PyObject *v = PyStructSequence_New(&StructPwdType);
- if (v == NULL)
- return NULL;
+ int setIndex = 0;
+ PyObject *v = PyStructSequence_New(&StructPwdType);
+ if (v == NULL)
+ return NULL;
#define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
#define SETS(i,val) sets(v, i, val)
- SETS(setIndex++, p->pw_name);
+ SETS(setIndex++, p->pw_name);
#ifdef __VMS
- SETS(setIndex++, "");
+ SETS(setIndex++, "");
#else
- SETS(setIndex++, p->pw_passwd);
+ SETS(setIndex++, p->pw_passwd);
#endif
- SETI(setIndex++, p->pw_uid);
- SETI(setIndex++, p->pw_gid);
+ SETI(setIndex++, p->pw_uid);
+ SETI(setIndex++, p->pw_gid);
#ifdef __VMS
- SETS(setIndex++, "");
+ SETS(setIndex++, "");
#else
- SETS(setIndex++, p->pw_gecos);
+ SETS(setIndex++, p->pw_gecos);
#endif
- SETS(setIndex++, p->pw_dir);
- SETS(setIndex++, p->pw_shell);
+ SETS(setIndex++, p->pw_dir);
+ SETS(setIndex++, p->pw_shell);
#undef SETS
#undef SETI
- if (PyErr_Occurred()) {
- Py_XDECREF(v);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v);
+ return NULL;
+ }
- return v;
+ return v;
}
PyDoc_STRVAR(pwd_getpwuid__doc__,
@@ -103,16 +103,16 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwuid(PyObject *self, PyObject *args)
{
- unsigned int uid;
- struct passwd *p;
- if (!PyArg_ParseTuple(args, "I:getpwuid", &uid))
- return NULL;
- if ((p = getpwuid(uid)) == NULL) {
- PyErr_Format(PyExc_KeyError,
- "getpwuid(): uid not found: %d", uid);
- return NULL;
- }
- return mkpwent(p);
+ unsigned int uid;
+ struct passwd *p;
+ if (!PyArg_ParseTuple(args, "I:getpwuid", &uid))
+ return NULL;
+ if ((p = getpwuid(uid)) == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "getpwuid(): uid not found: %d", uid);
+ return NULL;
+ }
+ return mkpwent(p);
}
PyDoc_STRVAR(pwd_getpwnam__doc__,
@@ -124,16 +124,16 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwnam(PyObject *self, PyObject *args)
{
- char *name;
- struct passwd *p;
- if (!PyArg_ParseTuple(args, "s:getpwnam", &name))
- return NULL;
- if ((p = getpwnam(name)) == NULL) {
- PyErr_Format(PyExc_KeyError,
- "getpwnam(): name not found: %s", name);
- return NULL;
- }
- return mkpwent(p);
+ char *name;
+ struct passwd *p;
+ if (!PyArg_ParseTuple(args, "s:getpwnam", &name))
+ return NULL;
+ if ((p = getpwnam(name)) == NULL) {
+ PyErr_Format(PyExc_KeyError,
+ "getpwnam(): name not found: %s", name);
+ return NULL;
+ }
+ return mkpwent(p);
}
#ifdef HAVE_GETPWENT
@@ -146,55 +146,55 @@ See pwd.__doc__ for more on password database entries.");
static PyObject *
pwd_getpwall(PyObject *self)
{
- PyObject *d;
- struct passwd *p;
- if ((d = PyList_New(0)) == NULL)
- return NULL;
+ PyObject *d;
+ struct passwd *p;
+ if ((d = PyList_New(0)) == NULL)
+ return NULL;
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- if ((p = getpwuid(0)) != NULL) {
+ if ((p = getpwuid(0)) != NULL) {
#else
- setpwent();
- while ((p = getpwent()) != NULL) {
+ setpwent();
+ while ((p = getpwent()) != NULL) {
#endif
- PyObject *v = mkpwent(p);
- if (v == NULL || PyList_Append(d, v) != 0) {
- Py_XDECREF(v);
- Py_DECREF(d);
- endpwent();
- return NULL;
- }
- Py_DECREF(v);
- }
- endpwent();
- return d;
+ PyObject *v = mkpwent(p);
+ if (v == NULL || PyList_Append(d, v) != 0) {
+ Py_XDECREF(v);
+ Py_DECREF(d);
+ endpwent();
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ endpwent();
+ return d;
}
#endif
static PyMethodDef pwd_methods[] = {
- {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__},
- {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__},
+ {"getpwuid", pwd_getpwuid, METH_VARARGS, pwd_getpwuid__doc__},
+ {"getpwnam", pwd_getpwnam, METH_VARARGS, pwd_getpwnam__doc__},
#ifdef HAVE_GETPWENT
- {"getpwall", (PyCFunction)pwd_getpwall,
- METH_NOARGS, pwd_getpwall__doc__},
+ {"getpwall", (PyCFunction)pwd_getpwall,
+ METH_NOARGS, pwd_getpwall__doc__},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initpwd(void)
{
- PyObject *m;
- m = Py_InitModule3("pwd", pwd_methods, pwd__doc__);
- if (m == NULL)
- return;
-
- if (!initialized)
- PyStructSequence_InitType(&StructPwdType,
- &struct_pwd_type_desc);
- Py_INCREF((PyObject *) &StructPwdType);
- PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
- /* And for b/w compatibility (this was defined by mistake): */
- Py_INCREF((PyObject *) &StructPwdType);
- PyModule_AddObject(m, "struct_pwent", (PyObject *) &StructPwdType);
- initialized = 1;
+ PyObject *m;
+ m = Py_InitModule3("pwd", pwd_methods, pwd__doc__);
+ if (m == NULL)
+ return;
+
+ if (!initialized)
+ PyStructSequence_InitType(&StructPwdType,
+ &struct_pwd_type_desc);
+ Py_INCREF((PyObject *) &StructPwdType);
+ PyModule_AddObject(m, "struct_passwd", (PyObject *) &StructPwdType);
+ /* And for b/w compatibility (this was defined by mistake): */
+ Py_INCREF((PyObject *) &StructPwdType);
+ PyModule_AddObject(m, "struct_pwent", (PyObject *) &StructPwdType);
+ initialized = 1;
}
diff --git a/Modules/pyexpat.c b/Modules/pyexpat.c
index 3b4ccfd..e05b3ad 100644
--- a/Modules/pyexpat.c
+++ b/Modules/pyexpat.c
@@ -245,7 +245,7 @@ error_external_entity_ref_handler(XML_Parser parser,
used only from the character data handler trampoline, and must be
used right after `flag_error()` is called. */
static void
-noop_character_data_handler(void *userData, const XML_Char *data, int len)
+noop_character_data_handler(void *userData, const XML_Char *data, int len)
{
/* Do nothing. */
}
@@ -274,25 +274,25 @@ trace_frame(PyThreadState *tstate, PyFrameObject *f, int code, PyObject *val)
{
int result = 0;
if (!tstate->use_tracing || tstate->tracing)
- return 0;
+ return 0;
if (tstate->c_profilefunc != NULL) {
- tstate->tracing++;
- result = tstate->c_profilefunc(tstate->c_profileobj,
- f, code , val);
- tstate->use_tracing = ((tstate->c_tracefunc != NULL)
- || (tstate->c_profilefunc != NULL));
- tstate->tracing--;
- if (result)
- return result;
+ tstate->tracing++;
+ result = tstate->c_profilefunc(tstate->c_profileobj,
+ f, code , val);
+ tstate->use_tracing = ((tstate->c_tracefunc != NULL)
+ || (tstate->c_profilefunc != NULL));
+ tstate->tracing--;
+ if (result)
+ return result;
}
if (tstate->c_tracefunc != NULL) {
- tstate->tracing++;
- result = tstate->c_tracefunc(tstate->c_traceobj,
- f, code , val);
- tstate->use_tracing = ((tstate->c_tracefunc != NULL)
- || (tstate->c_profilefunc != NULL));
- tstate->tracing--;
- }
+ tstate->tracing++;
+ result = tstate->c_tracefunc(tstate->c_traceobj,
+ f, code , val);
+ tstate->use_tracing = ((tstate->c_tracefunc != NULL)
+ || (tstate->c_profilefunc != NULL));
+ tstate->tracing--;
+ }
return result;
}
@@ -303,12 +303,12 @@ trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
int err;
if (tstate->c_tracefunc == NULL)
- return 0;
+ return 0;
PyErr_Fetch(&type, &value, &traceback);
if (value == NULL) {
- value = Py_None;
- Py_INCREF(value);
+ value = Py_None;
+ Py_INCREF(value);
}
#if PY_VERSION_HEX < 0x02040000
arg = Py_BuildValue("(OOO)", type, value, traceback);
@@ -316,17 +316,17 @@ trace_frame_exc(PyThreadState *tstate, PyFrameObject *f)
arg = PyTuple_Pack(3, type, value, traceback);
#endif
if (arg == NULL) {
- PyErr_Restore(type, value, traceback);
- return 0;
+ PyErr_Restore(type, value, traceback);
+ return 0;
}
err = trace_frame(tstate, f, PyTrace_EXCEPTION, arg);
Py_DECREF(arg);
if (err == 0)
- PyErr_Restore(type, value, traceback);
+ PyErr_Restore(type, value, traceback);
else {
- Py_XDECREF(type);
- Py_XDECREF(value);
- Py_XDECREF(traceback);
+ Py_XDECREF(type);
+ Py_XDECREF(value);
+ Py_XDECREF(traceback);
}
return err;
}
@@ -342,31 +342,31 @@ call_with_frame(PyCodeObject *c, PyObject* func, PyObject* args,
if (c == NULL)
return NULL;
-
+
f = PyFrame_New(tstate, c, PyEval_GetGlobals(), NULL);
if (f == NULL)
return NULL;
tstate->frame = f;
#ifdef FIX_TRACE
if (trace_frame(tstate, f, PyTrace_CALL, Py_None) < 0) {
- return NULL;
+ return NULL;
}
#endif
res = PyEval_CallObject(func, args);
if (res == NULL) {
- if (tstate->curexc_traceback == NULL)
- PyTraceBack_Here(f);
+ if (tstate->curexc_traceback == NULL)
+ PyTraceBack_Here(f);
XML_StopParser(self->itself, XML_FALSE);
#ifdef FIX_TRACE
- if (trace_frame_exc(tstate, f) < 0) {
- return NULL;
- }
+ if (trace_frame_exc(tstate, f) < 0) {
+ return NULL;
+ }
}
else {
- if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
- Py_XDECREF(res);
- res = NULL;
- }
+ if (trace_frame(tstate, f, PyTrace_RETURN, res) < 0) {
+ Py_XDECREF(res);
+ res = NULL;
+ }
}
#else
}
@@ -391,12 +391,12 @@ string_intern(xmlparseobject *self, const char* str)
PyObject *value;
/* result can be NULL if the unicode conversion failed. */
if (!result)
- return result;
+ return result;
if (!self->intern)
- return result;
+ return result;
value = PyDict_GetItem(self->intern, result);
if (!value) {
- if (PyDict_SetItem(self->intern, result, result) == 0)
+ if (PyDict_SetItem(self->intern, result, result) == 0)
return result;
else
return NULL;
@@ -419,8 +419,8 @@ call_character_handler(xmlparseobject *self, const XML_Char *buffer, int len)
if (args == NULL)
return -1;
#ifdef Py_USING_UNICODE
- temp = (self->returns_unicode
- ? conv_string_len_to_unicode(buffer, len)
+ temp = (self->returns_unicode
+ ? conv_string_len_to_unicode(buffer, len)
: conv_string_len_to_utf8(buffer, len));
#else
temp = conv_string_len_to_utf8(buffer, len);
@@ -462,7 +462,7 @@ flush_character_buffer(xmlparseobject *self)
}
static void
-my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
+my_CharacterDataHandler(void *userData, const XML_Char *data, int len)
{
xmlparseobject *self = (xmlparseobject *) userData;
if (self->buffer == NULL)
@@ -602,13 +602,13 @@ my_##NAME##Handler PARAMS {\
}
#define VOID_HANDLER(NAME, PARAMS, PARAM_FORMAT) \
- RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
- (xmlparseobject *)userData)
+ RC_HANDLER(void, NAME, PARAMS, ;, PARAM_FORMAT, ;, ;,\
+ (xmlparseobject *)userData)
#define INT_HANDLER(NAME, PARAMS, PARAM_FORMAT)\
- RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
- rc = PyInt_AsLong(rv);, rc, \
- (xmlparseobject *)userData)
+ RC_HANDLER(int, NAME, PARAMS, int rc=0;, PARAM_FORMAT, \
+ rc = PyInt_AsLong(rv);, rc, \
+ (xmlparseobject *)userData)
VOID_HANDLER(EndElement,
(void *userData, const XML_Char *name),
@@ -781,25 +781,25 @@ VOID_HANDLER(SkippedEntity,
#endif
VOID_HANDLER(NotationDecl,
- (void *userData,
- const XML_Char *notationName,
- const XML_Char *base,
- const XML_Char *systemId,
- const XML_Char *publicId),
+ (void *userData,
+ const XML_Char *notationName,
+ const XML_Char *base,
+ const XML_Char *systemId,
+ const XML_Char *publicId),
("(NNNN)",
- string_intern(self, notationName), string_intern(self, base),
- string_intern(self, systemId), string_intern(self, publicId)))
+ string_intern(self, notationName), string_intern(self, base),
+ string_intern(self, systemId), string_intern(self, publicId)))
VOID_HANDLER(StartNamespaceDecl,
- (void *userData,
- const XML_Char *prefix,
- const XML_Char *uri),
+ (void *userData,
+ const XML_Char *prefix,
+ const XML_Char *uri),
("(NN)",
string_intern(self, prefix), string_intern(self, uri)))
VOID_HANDLER(EndNamespaceDecl,
- (void *userData,
- const XML_Char *prefix),
+ (void *userData,
+ const XML_Char *prefix),
("(N)", string_intern(self, prefix)))
VOID_HANDLER(Comment,
@@ -808,50 +808,50 @@ VOID_HANDLER(Comment,
VOID_HANDLER(StartCdataSection,
(void *userData),
- ("()"))
+ ("()"))
VOID_HANDLER(EndCdataSection,
(void *userData),
- ("()"))
+ ("()"))
#ifndef Py_USING_UNICODE
VOID_HANDLER(Default,
- (void *userData, const XML_Char *s, int len),
- ("(N)", conv_string_len_to_utf8(s,len)))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", conv_string_len_to_utf8(s,len)))
VOID_HANDLER(DefaultHandlerExpand,
- (void *userData, const XML_Char *s, int len),
- ("(N)", conv_string_len_to_utf8(s,len)))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", conv_string_len_to_utf8(s,len)))
#else
VOID_HANDLER(Default,
- (void *userData, const XML_Char *s, int len),
- ("(N)", (self->returns_unicode
- ? conv_string_len_to_unicode(s,len)
- : conv_string_len_to_utf8(s,len))))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", (self->returns_unicode
+ ? conv_string_len_to_unicode(s,len)
+ : conv_string_len_to_utf8(s,len))))
VOID_HANDLER(DefaultHandlerExpand,
- (void *userData, const XML_Char *s, int len),
- ("(N)", (self->returns_unicode
- ? conv_string_len_to_unicode(s,len)
- : conv_string_len_to_utf8(s,len))))
+ (void *userData, const XML_Char *s, int len),
+ ("(N)", (self->returns_unicode
+ ? conv_string_len_to_unicode(s,len)
+ : conv_string_len_to_utf8(s,len))))
#endif
INT_HANDLER(NotStandalone,
- (void *userData),
- ("()"))
+ (void *userData),
+ ("()"))
RC_HANDLER(int, ExternalEntityRef,
- (XML_Parser parser,
- const XML_Char *context,
- const XML_Char *base,
- const XML_Char *systemId,
- const XML_Char *publicId),
- int rc=0;,
+ (XML_Parser parser,
+ const XML_Char *context,
+ const XML_Char *base,
+ const XML_Char *systemId,
+ const XML_Char *publicId),
+ int rc=0;,
("(O&NNN)",
- STRING_CONV_FUNC,context, string_intern(self, base),
- string_intern(self, systemId), string_intern(self, publicId)),
- rc = PyInt_AsLong(rv);, rc,
- XML_GetUserData(parser))
+ STRING_CONV_FUNC,context, string_intern(self, base),
+ string_intern(self, systemId), string_intern(self, publicId)),
+ rc = PyInt_AsLong(rv);, rc,
+ XML_GetUserData(parser))
/* XXX UnknownEncodingHandler */
@@ -1022,7 +1022,7 @@ xmlparse_SetBase(xmlparseobject *self, PyObject *args)
if (!PyArg_ParseTuple(args, "s:SetBase", &base))
return NULL;
if (!XML_SetBase(self->itself, base)) {
- return PyErr_NoMemory();
+ return PyErr_NoMemory();
}
Py_INCREF(Py_None);
return Py_None;
@@ -1113,7 +1113,7 @@ xmlparse_ExternalEntityParserCreate(xmlparseobject *self, PyObject *args)
new_parser->in_callback = 0;
new_parser->ns_prefixes = self->ns_prefixes;
new_parser->itself = XML_ExternalEntityParserCreate(self->itself, context,
- encoding);
+ encoding);
new_parser->handlers = 0;
new_parser->intern = self->intern;
Py_XINCREF(new_parser->intern);
@@ -1202,25 +1202,25 @@ xmlparse_UseForeignDTD(xmlparseobject *self, PyObject *args)
#endif
static struct PyMethodDef xmlparse_methods[] = {
- {"Parse", (PyCFunction)xmlparse_Parse,
- METH_VARARGS, xmlparse_Parse__doc__},
+ {"Parse", (PyCFunction)xmlparse_Parse,
+ METH_VARARGS, xmlparse_Parse__doc__},
{"ParseFile", (PyCFunction)xmlparse_ParseFile,
- METH_O, xmlparse_ParseFile__doc__},
+ METH_O, xmlparse_ParseFile__doc__},
{"SetBase", (PyCFunction)xmlparse_SetBase,
- METH_VARARGS, xmlparse_SetBase__doc__},
+ METH_VARARGS, xmlparse_SetBase__doc__},
{"GetBase", (PyCFunction)xmlparse_GetBase,
- METH_NOARGS, xmlparse_GetBase__doc__},
+ METH_NOARGS, xmlparse_GetBase__doc__},
{"ExternalEntityParserCreate", (PyCFunction)xmlparse_ExternalEntityParserCreate,
- METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
+ METH_VARARGS, xmlparse_ExternalEntityParserCreate__doc__},
{"SetParamEntityParsing", (PyCFunction)xmlparse_SetParamEntityParsing,
- METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
+ METH_VARARGS, xmlparse_SetParamEntityParsing__doc__},
{"GetInputContext", (PyCFunction)xmlparse_GetInputContext,
- METH_NOARGS, xmlparse_GetInputContext__doc__},
+ METH_NOARGS, xmlparse_GetInputContext__doc__},
#if XML_COMBINED_VERSION >= 19505
{"UseForeignDTD", (PyCFunction)xmlparse_UseForeignDTD,
- METH_VARARGS, xmlparse_UseForeignDTD__doc__},
+ METH_VARARGS, xmlparse_UseForeignDTD__doc__},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* ---------- */
@@ -1240,7 +1240,7 @@ init_template_buffer(void)
{
int i;
for (i = 0; i < 256; i++) {
- template_buffer[i] = i;
+ template_buffer[i] = i;
}
template_buffer[256] = 0;
}
@@ -1259,15 +1259,15 @@ PyUnknownEncodingHandler(void *encodingHandlerData,
PyUnicode_Decode(template_buffer, 256, name, "replace");
if (_u_string == NULL)
- return result;
+ return result;
for (i = 0; i < 256; i++) {
- /* Stupid to access directly, but fast */
- Py_UNICODE c = _u_string->str[i];
- if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
- info->map[i] = -1;
- else
- info->map[i] = c;
+ /* Stupid to access directly, but fast */
+ Py_UNICODE c = _u_string->str[i];
+ if (c == Py_UNICODE_REPLACEMENT_CHARACTER)
+ info->map[i] = -1;
+ else
+ info->map[i] = c;
}
info->data = NULL;
info->convert = NULL;
@@ -1468,19 +1468,19 @@ xmlparse_getattr(xmlparseobject *self, char *name)
}
}
-#define APPEND(list, str) \
- do { \
- PyObject *o = PyString_FromString(str); \
- if (o != NULL) \
- PyList_Append(list, o); \
- Py_XDECREF(o); \
+#define APPEND(list, str) \
+ do { \
+ PyObject *o = PyString_FromString(str); \
+ if (o != NULL) \
+ PyList_Append(list, o); \
+ Py_XDECREF(o); \
} while (0)
if (strcmp(name, "__members__") == 0) {
int i;
PyObject *rc = PyList_New(0);
- if (!rc)
- return NULL;
+ if (!rc)
+ return NULL;
for (i = 0; handler_info[i].name != NULL; i++) {
PyObject *o = get_handler_name(&handler_info[i]);
if (o != NULL)
@@ -1612,42 +1612,42 @@ xmlparse_setattr(xmlparseobject *self, char *name, PyObject *v)
if (strcmp(name, "buffer_size") == 0) {
long new_buffer_size;
if (!PyInt_Check(v)) {
- PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "buffer_size must be an integer");
+ return -1;
}
new_buffer_size=PyInt_AS_LONG(v);
/* trivial case -- no change */
if (new_buffer_size == self->buffer_size) {
- return 0;
+ return 0;
}
if (new_buffer_size <= 0) {
- PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
- return -1;
+ PyErr_SetString(PyExc_ValueError, "buffer_size must be greater than zero");
+ return -1;
}
/* check maximum */
if (new_buffer_size > INT_MAX) {
- char errmsg[100];
- sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
- PyErr_SetString(PyExc_ValueError, errmsg);
- return -1;
+ char errmsg[100];
+ sprintf(errmsg, "buffer_size must not be greater than %i", INT_MAX);
+ PyErr_SetString(PyExc_ValueError, errmsg);
+ return -1;
}
if (self->buffer != NULL) {
- /* there is already a buffer */
- if (self->buffer_used != 0) {
- flush_character_buffer(self);
- }
- /* free existing buffer */
- free(self->buffer);
+ /* there is already a buffer */
+ if (self->buffer_used != 0) {
+ flush_character_buffer(self);
+ }
+ /* free existing buffer */
+ free(self->buffer);
}
self->buffer = malloc(new_buffer_size);
if (self->buffer == NULL) {
- PyErr_NoMemory();
- return -1;
- }
+ PyErr_NoMemory();
+ return -1;
+ }
self->buffer_size = new_buffer_size;
return 0;
}
@@ -1690,37 +1690,37 @@ xmlparse_clear(xmlparseobject *op)
PyDoc_STRVAR(Xmlparsetype__doc__, "XML parser");
static PyTypeObject Xmlparsetype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "pyexpat.xmlparser", /*tp_name*/
- sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)xmlparse_dealloc, /*tp_dealloc*/
- (printfunc)0, /*tp_print*/
- (getattrfunc)xmlparse_getattr, /*tp_getattr*/
- (setattrfunc)xmlparse_setattr, /*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*/
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "pyexpat.xmlparser", /*tp_name*/
+ sizeof(xmlparseobject) + PyGC_HEAD_SIZE,/*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)xmlparse_dealloc, /*tp_dealloc*/
+ (printfunc)0, /*tp_print*/
+ (getattrfunc)xmlparse_getattr, /*tp_getattr*/
+ (setattrfunc)xmlparse_setattr, /*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*/
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
#ifdef Py_TPFLAGS_HAVE_GC
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
#else
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_GC, /*tp_flags*/
#endif
- Xmlparsetype__doc__, /* tp_doc - Documentation string */
+ Xmlparsetype__doc__, /* tp_doc - Documentation string */
#ifdef WITH_CYCLE_GC
- (traverseproc)xmlparse_traverse, /* tp_traverse */
- (inquiry)xmlparse_clear /* tp_clear */
+ (traverseproc)xmlparse_traverse, /* tp_traverse */
+ (inquiry)xmlparse_clear /* tp_clear */
#else
- 0, 0
+ 0, 0
#endif
};
@@ -1755,21 +1755,21 @@ pyexpat_ParserCreate(PyObject *notused, PyObject *args, PyObject *kw)
/* Explicitly passing None means no interning is desired.
Not passing anything means that a new dictionary is used. */
if (intern == Py_None)
- intern = NULL;
+ intern = NULL;
else if (intern == NULL) {
- intern = PyDict_New();
- if (!intern)
- return NULL;
- intern_decref = 1;
+ intern = PyDict_New();
+ if (!intern)
+ return NULL;
+ intern_decref = 1;
}
else if (!PyDict_Check(intern)) {
- PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
- return NULL;
+ PyErr_SetString(PyExc_TypeError, "intern must be a dictionary");
+ return NULL;
}
result = newxmlparseobject(encoding, namespace_separator, intern);
if (intern_decref) {
- Py_DECREF(intern);
+ Py_DECREF(intern);
}
return result;
}
@@ -1791,12 +1791,12 @@ pyexpat_ErrorString(PyObject *self, PyObject *args)
/* List of methods defined in the module */
static struct PyMethodDef pyexpat_methods[] = {
- {"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
+ {"ParserCreate", (PyCFunction)pyexpat_ParserCreate,
METH_VARARGS|METH_KEYWORDS, pyexpat_ParserCreate__doc__},
- {"ErrorString", (PyCFunction)pyexpat_ErrorString,
- METH_VARARGS, pyexpat_ErrorString__doc__},
+ {"ErrorString", (PyCFunction)pyexpat_ErrorString,
+ METH_VARARGS, pyexpat_ErrorString__doc__},
- {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
+ {NULL, (PyCFunction)NULL, 0, NULL} /* sentinel */
};
/* Module docstring */
@@ -1868,7 +1868,7 @@ MODULE_INITFUNC(void)
m = Py_InitModule3(MODULE_NAME, pyexpat_methods,
pyexpat_module_documentation);
if (m == NULL)
- return;
+ return;
/* Add some symbolic constants to the module */
if (ErrorObject == NULL) {
@@ -1927,7 +1927,7 @@ MODULE_INITFUNC(void)
if (errors_module == NULL || model_module == NULL)
/* Don't core dump later! */
return;
-
+
#if XML_COMBINED_VERSION > 19505
{
const XML_Feature *features = XML_GetFeatureList();
@@ -2052,7 +2052,7 @@ MODULE_INITFUNC(void)
capi.SetProcessingInstructionHandler = XML_SetProcessingInstructionHandler;
capi.SetUnknownEncodingHandler = XML_SetUnknownEncodingHandler;
capi.SetUserData = XML_SetUserData;
-
+
/* export using capsule */
capi_object = PyCapsule_New(&capi, PyExpat_CAPSULE_NAME, NULL);
if (capi_object)
@@ -2067,12 +2067,12 @@ clear_handlers(xmlparseobject *self, int initial)
for (; handler_info[i].name != NULL; i++) {
if (initial)
- self->handlers[i] = NULL;
- else {
+ self->handlers[i] = NULL;
+ else {
temp = self->handlers[i];
self->handlers[i] = NULL;
Py_XDECREF(temp);
- handler_info[i].setter(self->itself, NULL);
+ handler_info[i].setter(self->itself, NULL);
}
}
}
diff --git a/Modules/readline.c b/Modules/readline.c
index 0657713..4a5d089 100644
--- a/Modules/readline.c
+++ b/Modules/readline.c
@@ -33,7 +33,7 @@
#ifdef HAVE_RL_COMPLETION_MATCHES
#define completion_matches(x, y) \
- rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
+ rl_completion_matches((x), ((rl_compentry_func_t *)(y)))
#else
#if defined(_RL_FUNCTION_TYPEDEF)
extern char **completion_matches(char *, rl_compentry_func_t *);
@@ -66,7 +66,7 @@ static const char libedit_version_tag[] = "EditLine wrapper";
static void
on_completion_display_matches_hook(char **matches,
- int num_matches, int max_length);
+ int num_matches, int max_length);
/* Exported function to send one line to readline's init file parser */
@@ -74,18 +74,18 @@ on_completion_display_matches_hook(char **matches,
static PyObject *
parse_and_bind(PyObject *self, PyObject *args)
{
- char *s, *copy;
- if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
- return NULL;
- /* Make a copy -- rl_parse_and_bind() modifies its argument */
- /* Bernard Herzog */
- copy = malloc(1 + strlen(s));
- if (copy == NULL)
- return PyErr_NoMemory();
- strcpy(copy, s);
- rl_parse_and_bind(copy);
- free(copy); /* Free the copy */
- Py_RETURN_NONE;
+ char *s, *copy;
+ if (!PyArg_ParseTuple(args, "s:parse_and_bind", &s))
+ return NULL;
+ /* Make a copy -- rl_parse_and_bind() modifies its argument */
+ /* Bernard Herzog */
+ copy = malloc(1 + strlen(s));
+ if (copy == NULL)
+ return PyErr_NoMemory();
+ strcpy(copy, s);
+ rl_parse_and_bind(copy);
+ free(copy); /* Free the copy */
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_parse_and_bind,
@@ -98,13 +98,13 @@ Parse and execute single line of a readline init file.");
static PyObject *
read_init_file(PyObject *self, PyObject *args)
{
- char *s = NULL;
- if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
- return NULL;
- errno = rl_read_init_file(s);
- if (errno)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_RETURN_NONE;
+ char *s = NULL;
+ if (!PyArg_ParseTuple(args, "|z:read_init_file", &s))
+ return NULL;
+ errno = rl_read_init_file(s);
+ if (errno)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_read_init_file,
@@ -118,13 +118,13 @@ The default filename is the last filename used.");
static PyObject *
read_history_file(PyObject *self, PyObject *args)
{
- char *s = NULL;
- if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
- return NULL;
- errno = read_history(s);
- if (errno)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_RETURN_NONE;
+ char *s = NULL;
+ if (!PyArg_ParseTuple(args, "|z:read_history_file", &s))
+ return NULL;
+ errno = read_history(s);
+ if (errno)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_RETURN_NONE;
}
static int _history_length = -1; /* do not truncate history by default */
@@ -139,15 +139,15 @@ The default filename is ~/.history.");
static PyObject *
write_history_file(PyObject *self, PyObject *args)
{
- char *s = NULL;
- if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
- return NULL;
- errno = write_history(s);
- if (!errno && _history_length >= 0)
- history_truncate_file(s, _history_length);
- if (errno)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_RETURN_NONE;
+ char *s = NULL;
+ if (!PyArg_ParseTuple(args, "|z:write_history_file", &s))
+ return NULL;
+ errno = write_history(s);
+ if (!errno && _history_length >= 0)
+ history_truncate_file(s, _history_length);
+ if (errno)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_write_history_file,
@@ -161,11 +161,11 @@ The default filename is ~/.history.");
static PyObject*
set_history_length(PyObject *self, PyObject *args)
{
- int length = _history_length;
- if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
- return NULL;
- _history_length = length;
- Py_RETURN_NONE;
+ int length = _history_length;
+ if (!PyArg_ParseTuple(args, "i:set_history_length", &length))
+ return NULL;
+ _history_length = length;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(set_history_length_doc,
@@ -180,7 +180,7 @@ history truncation.");
static PyObject*
get_history_length(PyObject *self, PyObject *noarg)
{
- return PyInt_FromLong(_history_length);
+ return PyInt_FromLong(_history_length);
}
PyDoc_STRVAR(get_history_length_doc,
@@ -194,29 +194,29 @@ the history file.");
static PyObject *
set_hook(const char *funcname, PyObject **hook_var, PyObject *args)
{
- PyObject *function = Py_None;
- char buf[80];
- PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
- if (!PyArg_ParseTuple(args, buf, &function))
- return NULL;
- if (function == Py_None) {
- Py_XDECREF(*hook_var);
- *hook_var = NULL;
- }
- else if (PyCallable_Check(function)) {
- PyObject *tmp = *hook_var;
- Py_INCREF(function);
- *hook_var = function;
- Py_XDECREF(tmp);
- }
- else {
- PyOS_snprintf(buf, sizeof(buf),
- "set_%.50s(func): argument not callable",
- funcname);
- PyErr_SetString(PyExc_TypeError, buf);
- return NULL;
- }
- Py_RETURN_NONE;
+ PyObject *function = Py_None;
+ char buf[80];
+ PyOS_snprintf(buf, sizeof(buf), "|O:set_%.50s", funcname);
+ if (!PyArg_ParseTuple(args, buf, &function))
+ return NULL;
+ if (function == Py_None) {
+ Py_XDECREF(*hook_var);
+ *hook_var = NULL;
+ }
+ else if (PyCallable_Check(function)) {
+ PyObject *tmp = *hook_var;
+ Py_INCREF(function);
+ *hook_var = function;
+ Py_XDECREF(tmp);
+ }
+ else {
+ PyOS_snprintf(buf, sizeof(buf),
+ "set_%.50s(func): argument not callable",
+ funcname);
+ PyErr_SetString(PyExc_TypeError, buf);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
@@ -232,20 +232,20 @@ static PyObject *pre_input_hook = NULL;
static PyObject *
set_completion_display_matches_hook(PyObject *self, PyObject *args)
{
- PyObject *result = set_hook("completion_display_matches_hook",
- &completion_display_matches_hook, args);
+ PyObject *result = set_hook("completion_display_matches_hook",
+ &completion_display_matches_hook, args);
#ifdef HAVE_RL_COMPLETION_DISPLAY_MATCHES_HOOK
- /* We cannot set this hook globally, since it replaces the
- default completion display. */
- rl_completion_display_matches_hook =
- completion_display_matches_hook ?
+ /* We cannot set this hook globally, since it replaces the
+ default completion display. */
+ rl_completion_display_matches_hook =
+ completion_display_matches_hook ?
#if defined(_RL_FUNCTION_TYPEDEF)
- (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
+ (rl_compdisp_func_t *)on_completion_display_matches_hook : 0;
#else
- (VFunction *)on_completion_display_matches_hook : 0;
+ (VFunction *)on_completion_display_matches_hook : 0;
#endif
#endif
- return result;
+ return result;
}
@@ -259,7 +259,7 @@ once each time matches need to be displayed.");
static PyObject *
set_startup_hook(PyObject *self, PyObject *args)
{
- return set_hook("startup_hook", &startup_hook, args);
+ return set_hook("startup_hook", &startup_hook, args);
}
PyDoc_STRVAR(doc_set_startup_hook,
@@ -276,7 +276,7 @@ before readline prints the first prompt.");
static PyObject *
set_pre_input_hook(PyObject *self, PyObject *args)
{
- return set_hook("pre_input_hook", &pre_input_hook, args);
+ return set_hook("pre_input_hook", &pre_input_hook, args);
}
PyDoc_STRVAR(doc_set_pre_input_hook,
@@ -314,8 +314,8 @@ Get the type of completion being attempted.");
static PyObject *
get_begidx(PyObject *self, PyObject *noarg)
{
- Py_INCREF(begidx);
- return begidx;
+ Py_INCREF(begidx);
+ return begidx;
}
PyDoc_STRVAR(doc_get_begidx,
@@ -328,8 +328,8 @@ get the beginning index of the readline tab-completion scope");
static PyObject *
get_endidx(PyObject *self, PyObject *noarg)
{
- Py_INCREF(endidx);
- return endidx;
+ Py_INCREF(endidx);
+ return endidx;
}
PyDoc_STRVAR(doc_get_endidx,
@@ -342,14 +342,14 @@ get the ending index of the readline tab-completion scope");
static PyObject *
set_completer_delims(PyObject *self, PyObject *args)
{
- char *break_chars;
-
- if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
- return NULL;
- }
- free((void*)rl_completer_word_break_characters);
- rl_completer_word_break_characters = strdup(break_chars);
- Py_RETURN_NONE;
+ char *break_chars;
+
+ if(!PyArg_ParseTuple(args, "s:set_completer_delims", &break_chars)) {
+ return NULL;
+ }
+ free((void*)rl_completer_word_break_characters);
+ rl_completer_word_break_characters = strdup(break_chars);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_set_completer_delims,
@@ -359,31 +359,31 @@ set the readline word delimiters for tab-completion");
static PyObject *
py_remove_history(PyObject *self, PyObject *args)
{
- int entry_number;
- HIST_ENTRY *entry;
-
- if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
- return NULL;
- if (entry_number < 0) {
- PyErr_SetString(PyExc_ValueError,
- "History index cannot be negative");
- return NULL;
- }
- entry = remove_history(entry_number);
- if (!entry) {
- PyErr_Format(PyExc_ValueError,
- "No history item at position %d",
- entry_number);
- return NULL;
- }
- /* free memory allocated for the history entry */
- if (entry->line)
- free((void *)entry->line);
- if (entry->data)
- free(entry->data);
- free(entry);
-
- Py_RETURN_NONE;
+ int entry_number;
+ HIST_ENTRY *entry;
+
+ if (!PyArg_ParseTuple(args, "i:remove_history", &entry_number))
+ return NULL;
+ if (entry_number < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "History index cannot be negative");
+ return NULL;
+ }
+ entry = remove_history(entry_number);
+ if (!entry) {
+ PyErr_Format(PyExc_ValueError,
+ "No history item at position %d",
+ entry_number);
+ return NULL;
+ }
+ /* free memory allocated for the history entry */
+ if (entry->line)
+ free((void *)entry->line);
+ if (entry->data)
+ free(entry->data);
+ free(entry);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_remove_history,
@@ -393,34 +393,34 @@ remove history item given by its position");
static PyObject *
py_replace_history(PyObject *self, PyObject *args)
{
- int entry_number;
- char *line;
- HIST_ENTRY *old_entry;
-
- if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
- &line)) {
- return NULL;
- }
- if (entry_number < 0) {
- PyErr_SetString(PyExc_ValueError,
- "History index cannot be negative");
- return NULL;
- }
- old_entry = replace_history_entry(entry_number, line, (void *)NULL);
- if (!old_entry) {
- PyErr_Format(PyExc_ValueError,
- "No history item at position %d",
- entry_number);
- return NULL;
- }
- /* free memory allocated for the old history entry */
- if (old_entry->line)
- free((void *)old_entry->line);
- if (old_entry->data)
- free(old_entry->data);
- free(old_entry);
-
- Py_RETURN_NONE;
+ int entry_number;
+ char *line;
+ HIST_ENTRY *old_entry;
+
+ if (!PyArg_ParseTuple(args, "is:replace_history", &entry_number,
+ &line)) {
+ return NULL;
+ }
+ if (entry_number < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "History index cannot be negative");
+ return NULL;
+ }
+ old_entry = replace_history_entry(entry_number, line, (void *)NULL);
+ if (!old_entry) {
+ PyErr_Format(PyExc_ValueError,
+ "No history item at position %d",
+ entry_number);
+ return NULL;
+ }
+ /* free memory allocated for the old history entry */
+ if (old_entry->line)
+ free((void *)old_entry->line);
+ if (old_entry->data)
+ free(old_entry->data);
+ free(old_entry);
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_replace_history,
@@ -432,13 +432,13 @@ replaces history item given by its position with contents of line");
static PyObject *
py_add_history(PyObject *self, PyObject *args)
{
- char *line;
+ char *line;
- if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
- return NULL;
- }
- add_history(line);
- Py_RETURN_NONE;
+ if(!PyArg_ParseTuple(args, "s:add_history", &line)) {
+ return NULL;
+ }
+ add_history(line);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_add_history,
@@ -451,7 +451,7 @@ add a line to the history buffer");
static PyObject *
get_completer_delims(PyObject *self, PyObject *noarg)
{
- return PyString_FromString(rl_completer_word_break_characters);
+ return PyString_FromString(rl_completer_word_break_characters);
}
PyDoc_STRVAR(doc_get_completer_delims,
@@ -464,7 +464,7 @@ get the readline word delimiters for tab-completion");
static PyObject *
set_completer(PyObject *self, PyObject *args)
{
- return set_hook("completer", &completer, args);
+ return set_hook("completer", &completer, args);
}
PyDoc_STRVAR(doc_set_completer,
@@ -478,11 +478,11 @@ It should return the next possible completion starting with 'text'.");
static PyObject *
get_completer(PyObject *self, PyObject *noargs)
{
- if (completer == NULL) {
- Py_RETURN_NONE;
- }
- Py_INCREF(completer);
- return completer;
+ if (completer == NULL) {
+ Py_RETURN_NONE;
+ }
+ Py_INCREF(completer);
+ return completer;
}
PyDoc_STRVAR(doc_get_completer,
@@ -495,39 +495,39 @@ Returns current completer function.");
static PyObject *
get_history_item(PyObject *self, PyObject *args)
{
- int idx = 0;
- HIST_ENTRY *hist_ent;
+ int idx = 0;
+ HIST_ENTRY *hist_ent;
- if (!PyArg_ParseTuple(args, "i:index", &idx))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:index", &idx))
+ return NULL;
#ifdef __APPLE__
- if (using_libedit_emulation) {
- /* Libedit emulation uses 0-based indexes,
- * the real one uses 1-based indexes,
- * adjust the index to ensure that Python
- * code doesn't have to worry about the
- * difference.
- */
- HISTORY_STATE *hist_st;
- hist_st = history_get_history_state();
-
- idx --;
-
- /*
- * Apple's readline emulation crashes when
- * the index is out of range, therefore
- * test for that and fail gracefully.
- */
- if (idx < 0 || idx >= hist_st->length) {
- Py_RETURN_NONE;
- }
- }
+ if (using_libedit_emulation) {
+ /* Libedit emulation uses 0-based indexes,
+ * the real one uses 1-based indexes,
+ * adjust the index to ensure that Python
+ * code doesn't have to worry about the
+ * difference.
+ */
+ HISTORY_STATE *hist_st;
+ hist_st = history_get_history_state();
+
+ idx --;
+
+ /*
+ * Apple's readline emulation crashes when
+ * the index is out of range, therefore
+ * test for that and fail gracefully.
+ */
+ if (idx < 0 || idx >= hist_st->length) {
+ Py_RETURN_NONE;
+ }
+ }
#endif /* __APPLE__ */
- if ((hist_ent = history_get(idx)))
- return PyString_FromString(hist_ent->line);
- else {
- Py_RETURN_NONE;
- }
+ if ((hist_ent = history_get(idx)))
+ return PyString_FromString(hist_ent->line);
+ else {
+ Py_RETURN_NONE;
+ }
}
PyDoc_STRVAR(doc_get_history_item,
@@ -540,10 +540,10 @@ return the current contents of history item at index.");
static PyObject *
get_current_history_length(PyObject *self, PyObject *noarg)
{
- HISTORY_STATE *hist_st;
+ HISTORY_STATE *hist_st;
- hist_st = history_get_history_state();
- return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
+ hist_st = history_get_history_state();
+ return PyInt_FromLong(hist_st ? (long) hist_st->length : (long) 0);
}
PyDoc_STRVAR(doc_get_current_history_length,
@@ -556,7 +556,7 @@ return the current (not the maximum) length of history.");
static PyObject *
get_line_buffer(PyObject *self, PyObject *noarg)
{
- return PyString_FromString(rl_line_buffer);
+ return PyString_FromString(rl_line_buffer);
}
PyDoc_STRVAR(doc_get_line_buffer,
@@ -571,8 +571,8 @@ return the current contents of the line buffer.");
static PyObject *
py_clear_history(PyObject *self, PyObject *noarg)
{
- clear_history();
- Py_RETURN_NONE;
+ clear_history();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_clear_history,
@@ -586,11 +586,11 @@ Clear the current readline history.");
static PyObject *
insert_text(PyObject *self, PyObject *args)
{
- char *s;
- if (!PyArg_ParseTuple(args, "s:insert_text", &s))
- return NULL;
- rl_insert_text(s);
- Py_RETURN_NONE;
+ char *s;
+ if (!PyArg_ParseTuple(args, "s:insert_text", &s))
+ return NULL;
+ rl_insert_text(s);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_insert_text,
@@ -603,8 +603,8 @@ Insert text into the command line.");
static PyObject *
redisplay(PyObject *self, PyObject *noarg)
{
- rl_redisplay();
- Py_RETURN_NONE;
+ rl_redisplay();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(doc_redisplay,
@@ -617,50 +617,50 @@ contents of the line buffer.");
static struct PyMethodDef readline_methods[] =
{
- {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
- {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
- {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
- {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
- {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
- {"read_history_file", read_history_file,
- METH_VARARGS, doc_read_history_file},
- {"write_history_file", write_history_file,
- METH_VARARGS, doc_write_history_file},
- {"get_history_item", get_history_item,
- METH_VARARGS, doc_get_history_item},
- {"get_current_history_length", (PyCFunction)get_current_history_length,
- METH_NOARGS, doc_get_current_history_length},
- {"set_history_length", set_history_length,
- METH_VARARGS, set_history_length_doc},
- {"get_history_length", get_history_length,
- METH_NOARGS, get_history_length_doc},
- {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
- {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
- {"get_completion_type", get_completion_type,
- METH_NOARGS, doc_get_completion_type},
- {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
- {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
-
- {"set_completer_delims", set_completer_delims,
- METH_VARARGS, doc_set_completer_delims},
- {"add_history", py_add_history, METH_VARARGS, doc_add_history},
- {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
- {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
- {"get_completer_delims", get_completer_delims,
- METH_NOARGS, doc_get_completer_delims},
-
- {"set_completion_display_matches_hook", set_completion_display_matches_hook,
- METH_VARARGS, doc_set_completion_display_matches_hook},
- {"set_startup_hook", set_startup_hook,
- METH_VARARGS, doc_set_startup_hook},
+ {"parse_and_bind", parse_and_bind, METH_VARARGS, doc_parse_and_bind},
+ {"get_line_buffer", get_line_buffer, METH_NOARGS, doc_get_line_buffer},
+ {"insert_text", insert_text, METH_VARARGS, doc_insert_text},
+ {"redisplay", redisplay, METH_NOARGS, doc_redisplay},
+ {"read_init_file", read_init_file, METH_VARARGS, doc_read_init_file},
+ {"read_history_file", read_history_file,
+ METH_VARARGS, doc_read_history_file},
+ {"write_history_file", write_history_file,
+ METH_VARARGS, doc_write_history_file},
+ {"get_history_item", get_history_item,
+ METH_VARARGS, doc_get_history_item},
+ {"get_current_history_length", (PyCFunction)get_current_history_length,
+ METH_NOARGS, doc_get_current_history_length},
+ {"set_history_length", set_history_length,
+ METH_VARARGS, set_history_length_doc},
+ {"get_history_length", get_history_length,
+ METH_NOARGS, get_history_length_doc},
+ {"set_completer", set_completer, METH_VARARGS, doc_set_completer},
+ {"get_completer", get_completer, METH_NOARGS, doc_get_completer},
+ {"get_completion_type", get_completion_type,
+ METH_NOARGS, doc_get_completion_type},
+ {"get_begidx", get_begidx, METH_NOARGS, doc_get_begidx},
+ {"get_endidx", get_endidx, METH_NOARGS, doc_get_endidx},
+
+ {"set_completer_delims", set_completer_delims,
+ METH_VARARGS, doc_set_completer_delims},
+ {"add_history", py_add_history, METH_VARARGS, doc_add_history},
+ {"remove_history_item", py_remove_history, METH_VARARGS, doc_remove_history},
+ {"replace_history_item", py_replace_history, METH_VARARGS, doc_replace_history},
+ {"get_completer_delims", get_completer_delims,
+ METH_NOARGS, doc_get_completer_delims},
+
+ {"set_completion_display_matches_hook", set_completion_display_matches_hook,
+ METH_VARARGS, doc_set_completion_display_matches_hook},
+ {"set_startup_hook", set_startup_hook,
+ METH_VARARGS, doc_set_startup_hook},
#ifdef HAVE_RL_PRE_INPUT_HOOK
- {"set_pre_input_hook", set_pre_input_hook,
- METH_VARARGS, doc_set_pre_input_hook},
+ {"set_pre_input_hook", set_pre_input_hook,
+ METH_VARARGS, doc_set_pre_input_hook},
#endif
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
+ {"clear_history", py_clear_history, METH_NOARGS, doc_clear_history},
#endif
- {0, 0}
+ {0, 0}
};
@@ -669,47 +669,47 @@ static struct PyMethodDef readline_methods[] =
static int
on_hook(PyObject *func)
{
- int result = 0;
- if (func != NULL) {
- PyObject *r;
+ int result = 0;
+ if (func != NULL) {
+ PyObject *r;
#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
- r = PyObject_CallFunction(func, NULL);
- if (r == NULL)
- goto error;
- if (r == Py_None)
- result = 0;
- else {
- result = PyInt_AsLong(r);
- if (result == -1 && PyErr_Occurred())
- goto error;
- }
- Py_DECREF(r);
- goto done;
- error:
- PyErr_Clear();
- Py_XDECREF(r);
- done:
+ r = PyObject_CallFunction(func, NULL);
+ if (r == NULL)
+ goto error;
+ if (r == Py_None)
+ result = 0;
+ else {
+ result = PyInt_AsLong(r);
+ if (result == -1 && PyErr_Occurred())
+ goto error;
+ }
+ Py_DECREF(r);
+ goto done;
+ error:
+ PyErr_Clear();
+ Py_XDECREF(r);
+ done:
#ifdef WITH_THREAD
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
- return result;
- }
- return result;
+ return result;
+ }
+ return result;
}
static int
on_startup_hook(void)
{
- return on_hook(startup_hook);
+ return on_hook(startup_hook);
}
#ifdef HAVE_RL_PRE_INPUT_HOOK
static int
on_pre_input_hook(void)
{
- return on_hook(pre_input_hook);
+ return on_hook(pre_input_hook);
}
#endif
@@ -718,43 +718,43 @@ on_pre_input_hook(void)
static void
on_completion_display_matches_hook(char **matches,
- int num_matches, int max_length)
+ int num_matches, int max_length)
{
- int i;
- PyObject *m=NULL, *s=NULL, *r=NULL;
+ int i;
+ PyObject *m=NULL, *s=NULL, *r=NULL;
#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
- m = PyList_New(num_matches);
- if (m == NULL)
- goto error;
- for (i = 0; i < num_matches; i++) {
- s = PyString_FromString(matches[i+1]);
- if (s == NULL)
- goto error;
- if (PyList_SetItem(m, i, s) == -1)
- goto error;
- }
-
- r = PyObject_CallFunction(completion_display_matches_hook,
- "sOi", matches[0], m, max_length);
-
- Py_DECREF(m); m=NULL;
-
- if (r == NULL ||
- (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
- goto error;
- }
- Py_XDECREF(r); r=NULL;
-
- if (0) {
- error:
- PyErr_Clear();
- Py_XDECREF(m);
- Py_XDECREF(r);
- }
+ m = PyList_New(num_matches);
+ if (m == NULL)
+ goto error;
+ for (i = 0; i < num_matches; i++) {
+ s = PyString_FromString(matches[i+1]);
+ if (s == NULL)
+ goto error;
+ if (PyList_SetItem(m, i, s) == -1)
+ goto error;
+ }
+
+ r = PyObject_CallFunction(completion_display_matches_hook,
+ "sOi", matches[0], m, max_length);
+
+ Py_DECREF(m); m=NULL;
+
+ if (r == NULL ||
+ (r != Py_None && PyInt_AsLong(r) == -1 && PyErr_Occurred())) {
+ goto error;
+ }
+ Py_XDECREF(r); r=NULL;
+
+ if (0) {
+ error:
+ PyErr_Clear();
+ Py_XDECREF(m);
+ Py_XDECREF(r);
+ }
#ifdef WITH_THREAD
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
}
@@ -764,37 +764,37 @@ on_completion_display_matches_hook(char **matches,
static char *
on_completion(const char *text, int state)
{
- char *result = NULL;
- if (completer != NULL) {
- PyObject *r;
+ char *result = NULL;
+ if (completer != NULL) {
+ PyObject *r;
#ifdef WITH_THREAD
- PyGILState_STATE gilstate = PyGILState_Ensure();
+ PyGILState_STATE gilstate = PyGILState_Ensure();
#endif
- rl_attempted_completion_over = 1;
- r = PyObject_CallFunction(completer, "si", text, state);
- if (r == NULL)
- goto error;
- if (r == Py_None) {
- result = NULL;
- }
- else {
- char *s = PyString_AsString(r);
- if (s == NULL)
- goto error;
- result = strdup(s);
- }
- Py_DECREF(r);
- goto done;
- error:
- PyErr_Clear();
- Py_XDECREF(r);
- done:
+ rl_attempted_completion_over = 1;
+ r = PyObject_CallFunction(completer, "si", text, state);
+ if (r == NULL)
+ goto error;
+ if (r == Py_None) {
+ result = NULL;
+ }
+ else {
+ char *s = PyString_AsString(r);
+ if (s == NULL)
+ goto error;
+ result = strdup(s);
+ }
+ Py_DECREF(r);
+ goto done;
+ error:
+ PyErr_Clear();
+ Py_XDECREF(r);
+ done:
#ifdef WITH_THREAD
- PyGILState_Release(gilstate);
+ PyGILState_Release(gilstate);
#endif
- return result;
- }
- return result;
+ return result;
+ }
+ return result;
}
@@ -805,16 +805,16 @@ static char **
flex_complete(char *text, int start, int end)
{
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- rl_completion_append_character ='\0';
+ rl_completion_append_character ='\0';
#endif
#ifdef HAVE_RL_COMPLETION_SUPPRESS_APPEND
- rl_completion_suppress_append = 0;
+ rl_completion_suppress_append = 0;
#endif
- Py_XDECREF(begidx);
- Py_XDECREF(endidx);
- begidx = PyInt_FromLong((long) start);
- endidx = PyInt_FromLong((long) end);
- return completion_matches(text, *on_completion);
+ Py_XDECREF(begidx);
+ Py_XDECREF(endidx);
+ begidx = PyInt_FromLong((long) start);
+ endidx = PyInt_FromLong((long) end);
+ return completion_matches(text, *on_completion);
}
@@ -824,45 +824,45 @@ static void
setup_readline(void)
{
#ifdef SAVE_LOCALE
- char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
- if (!saved_locale)
- Py_FatalError("not enough memory to save locale");
+ char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
+ if (!saved_locale)
+ Py_FatalError("not enough memory to save locale");
#endif
- using_history();
+ using_history();
- rl_readline_name = "python";
+ rl_readline_name = "python";
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- /* Allow $if term= in .inputrc to work */
- rl_terminal_name = getenv("TERM");
+ /* Allow $if term= in .inputrc to work */
+ rl_terminal_name = getenv("TERM");
#endif
- /* Force rebind of TAB to insert-tab */
- rl_bind_key('\t', rl_insert);
- /* Bind both ESC-TAB and ESC-ESC to the completion function */
- rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
- rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
- /* Set our hook functions */
- rl_startup_hook = (Function *)on_startup_hook;
+ /* Force rebind of TAB to insert-tab */
+ rl_bind_key('\t', rl_insert);
+ /* Bind both ESC-TAB and ESC-ESC to the completion function */
+ rl_bind_key_in_map ('\t', rl_complete, emacs_meta_keymap);
+ rl_bind_key_in_map ('\033', rl_complete, emacs_meta_keymap);
+ /* Set our hook functions */
+ rl_startup_hook = (Function *)on_startup_hook;
#ifdef HAVE_RL_PRE_INPUT_HOOK
- rl_pre_input_hook = (Function *)on_pre_input_hook;
+ rl_pre_input_hook = (Function *)on_pre_input_hook;
#endif
- /* Set our completion function */
- rl_attempted_completion_function = (CPPFunction *)flex_complete;
- /* Set Python word break characters */
- rl_completer_word_break_characters =
- strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
- /* All nonalphanums except '.' */
-
- begidx = PyInt_FromLong(0L);
- endidx = PyInt_FromLong(0L);
- /* Initialize (allows .inputrc to override)
- *
- * XXX: A bug in the readline-2.2 library causes a memory leak
- * inside this function. Nothing we can do about it.
- */
- rl_initialize();
-
- RESTORE_LOCALE(saved_locale)
+ /* Set our completion function */
+ rl_attempted_completion_function = (CPPFunction *)flex_complete;
+ /* Set Python word break characters */
+ rl_completer_word_break_characters =
+ strdup(" \t\n`~!@#$%^&*()-=+[{]}\\|;:'\",<>/?");
+ /* All nonalphanums except '.' */
+
+ begidx = PyInt_FromLong(0L);
+ endidx = PyInt_FromLong(0L);
+ /* Initialize (allows .inputrc to override)
+ *
+ * XXX: A bug in the readline-2.2 library causes a memory leak
+ * inside this function. Nothing we can do about it.
+ */
+ rl_initialize();
+
+ RESTORE_LOCALE(saved_locale)
}
/* Wrapper around GNU readline that handles signals differently. */
@@ -870,12 +870,12 @@ setup_readline(void)
#if defined(HAVE_RL_CALLBACK) && defined(HAVE_SELECT)
-static char *completed_input_string;
+static char *completed_input_string;
static void
rlhandler(char *text)
{
- completed_input_string = text;
- rl_callback_handler_remove();
+ completed_input_string = text;
+ rl_callback_handler_remove();
}
extern PyThreadState* _PyOS_ReadlineTState;
@@ -883,60 +883,60 @@ extern PyThreadState* _PyOS_ReadlineTState;
static char *
readline_until_enter_or_signal(char *prompt, int *signal)
{
- char * not_done_reading = "";
- fd_set selectset;
+ char * not_done_reading = "";
+ fd_set selectset;
- *signal = 0;
+ *signal = 0;
#ifdef HAVE_RL_CATCH_SIGNAL
- rl_catch_signals = 0;
+ rl_catch_signals = 0;
#endif
- rl_callback_handler_install (prompt, rlhandler);
- FD_ZERO(&selectset);
-
- completed_input_string = not_done_reading;
-
- while (completed_input_string == not_done_reading) {
- int has_input = 0;
-
- while (!has_input)
- { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
-
- /* [Bug #1552726] Only limit the pause if an input hook has been
- defined. */
- struct timeval *timeoutp = NULL;
- if (PyOS_InputHook)
- timeoutp = &timeout;
- FD_SET(fileno(rl_instream), &selectset);
- /* select resets selectset if no input was available */
- has_input = select(fileno(rl_instream) + 1, &selectset,
- NULL, NULL, timeoutp);
- if(PyOS_InputHook) PyOS_InputHook();
- }
-
- if(has_input > 0) {
- rl_callback_read_char();
- }
- else if (errno == EINTR) {
- int s;
+ rl_callback_handler_install (prompt, rlhandler);
+ FD_ZERO(&selectset);
+
+ completed_input_string = not_done_reading;
+
+ while (completed_input_string == not_done_reading) {
+ int has_input = 0;
+
+ while (!has_input)
+ { struct timeval timeout = {0, 100000}; /* 0.1 seconds */
+
+ /* [Bug #1552726] Only limit the pause if an input hook has been
+ defined. */
+ struct timeval *timeoutp = NULL;
+ if (PyOS_InputHook)
+ timeoutp = &timeout;
+ FD_SET(fileno(rl_instream), &selectset);
+ /* select resets selectset if no input was available */
+ has_input = select(fileno(rl_instream) + 1, &selectset,
+ NULL, NULL, timeoutp);
+ if(PyOS_InputHook) PyOS_InputHook();
+ }
+
+ if(has_input > 0) {
+ rl_callback_read_char();
+ }
+ else if (errno == EINTR) {
+ int s;
#ifdef WITH_THREAD
- PyEval_RestoreThread(_PyOS_ReadlineTState);
+ PyEval_RestoreThread(_PyOS_ReadlineTState);
#endif
- s = PyErr_CheckSignals();
+ s = PyErr_CheckSignals();
#ifdef WITH_THREAD
- PyEval_SaveThread();
+ PyEval_SaveThread();
#endif
- if (s < 0) {
- rl_free_line_state();
- rl_cleanup_after_signal();
- rl_callback_handler_remove();
- *signal = 1;
- completed_input_string = NULL;
- }
- }
- }
-
- return completed_input_string;
+ if (s < 0) {
+ rl_free_line_state();
+ rl_cleanup_after_signal();
+ rl_callback_handler_remove();
+ *signal = 1;
+ completed_input_string = NULL;
+ }
+ }
+ }
+
+ return completed_input_string;
}
@@ -950,31 +950,31 @@ static jmp_buf jbuf;
static void
onintr(int sig)
{
- longjmp(jbuf, 1);
+ longjmp(jbuf, 1);
}
static char *
readline_until_enter_or_signal(char *prompt, int *signal)
{
- PyOS_sighandler_t old_inthandler;
- char *p;
+ PyOS_sighandler_t old_inthandler;
+ char *p;
- *signal = 0;
+ *signal = 0;
- old_inthandler = PyOS_setsig(SIGINT, onintr);
- if (setjmp(jbuf)) {
+ old_inthandler = PyOS_setsig(SIGINT, onintr);
+ if (setjmp(jbuf)) {
#ifdef HAVE_SIGRELSE
- /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
- sigrelse(SIGINT);
+ /* This seems necessary on SunOS 4.1 (Rasmus Hahn) */
+ sigrelse(SIGINT);
#endif
- PyOS_setsig(SIGINT, old_inthandler);
- *signal = 1;
- return NULL;
- }
- rl_event_hook = PyOS_InputHook;
- p = readline(prompt);
- PyOS_setsig(SIGINT, old_inthandler);
+ PyOS_setsig(SIGINT, old_inthandler);
+ *signal = 1;
+ return NULL;
+ }
+ rl_event_hook = PyOS_InputHook;
+ p = readline(prompt);
+ PyOS_setsig(SIGINT, old_inthandler);
return p;
}
@@ -984,82 +984,82 @@ readline_until_enter_or_signal(char *prompt, int *signal)
static char *
call_readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
- size_t n;
- char *p, *q;
- int signal;
+ size_t n;
+ char *p, *q;
+ int signal;
#ifdef SAVE_LOCALE
- char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
- if (!saved_locale)
- Py_FatalError("not enough memory to save locale");
- setlocale(LC_CTYPE, "");
+ char *saved_locale = strdup(setlocale(LC_CTYPE, NULL));
+ if (!saved_locale)
+ Py_FatalError("not enough memory to save locale");
+ setlocale(LC_CTYPE, "");
#endif
- if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
- rl_instream = sys_stdin;
- rl_outstream = sys_stdout;
+ if (sys_stdin != rl_instream || sys_stdout != rl_outstream) {
+ rl_instream = sys_stdin;
+ rl_outstream = sys_stdout;
#ifdef HAVE_RL_COMPLETION_APPEND_CHARACTER
- rl_prep_terminal (1);
+ rl_prep_terminal (1);
#endif
- }
-
- p = readline_until_enter_or_signal(prompt, &signal);
-
- /* we got an interrupt signal */
- if (signal) {
- RESTORE_LOCALE(saved_locale)
- return NULL;
- }
-
- /* We got an EOF, return a empty string. */
- if (p == NULL) {
- p = PyMem_Malloc(1);
- if (p != NULL)
- *p = '\0';
- RESTORE_LOCALE(saved_locale)
- return p;
- }
-
- /* we have a valid line */
- n = strlen(p);
- if (n > 0) {
- const char *line;
- HISTORY_STATE *state = history_get_history_state();
- if (state->length > 0)
+ }
+
+ p = readline_until_enter_or_signal(prompt, &signal);
+
+ /* we got an interrupt signal */
+ if (signal) {
+ RESTORE_LOCALE(saved_locale)
+ return NULL;
+ }
+
+ /* We got an EOF, return a empty string. */
+ if (p == NULL) {
+ p = PyMem_Malloc(1);
+ if (p != NULL)
+ *p = '\0';
+ RESTORE_LOCALE(saved_locale)
+ return p;
+ }
+
+ /* we have a valid line */
+ n = strlen(p);
+ if (n > 0) {
+ const char *line;
+ HISTORY_STATE *state = history_get_history_state();
+ if (state->length > 0)
#ifdef __APPLE__
- if (using_libedit_emulation) {
- /*
- * Libedit's emulation uses 0-based indexes,
- * the real readline uses 1-based indexes.
- */
- line = history_get(state->length - 1)->line;
- } else
+ if (using_libedit_emulation) {
+ /*
+ * Libedit's emulation uses 0-based indexes,
+ * the real readline uses 1-based indexes.
+ */
+ line = history_get(state->length - 1)->line;
+ } else
#endif /* __APPLE__ */
- line = history_get(state->length)->line;
- else
- line = "";
- if (strcmp(p, line))
- add_history(p);
- /* the history docs don't say so, but the address of state
- changes each time history_get_history_state is called
- which makes me think it's freshly malloc'd memory...
- on the other hand, the address of the last line stays the
- same as long as history isn't extended, so it appears to
- be malloc'd but managed by the history package... */
- free(state);
- }
- /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
- release the original. */
- q = p;
- p = PyMem_Malloc(n+2);
- if (p != NULL) {
- strncpy(p, q, n);
- p[n] = '\n';
- p[n+1] = '\0';
- }
- free(q);
- RESTORE_LOCALE(saved_locale)
- return p;
+ line = history_get(state->length)->line;
+ else
+ line = "";
+ if (strcmp(p, line))
+ add_history(p);
+ /* the history docs don't say so, but the address of state
+ changes each time history_get_history_state is called
+ which makes me think it's freshly malloc'd memory...
+ on the other hand, the address of the last line stays the
+ same as long as history isn't extended, so it appears to
+ be malloc'd but managed by the history package... */
+ free(state);
+ }
+ /* Copy the malloc'ed buffer into a PyMem_Malloc'ed one and
+ release the original. */
+ q = p;
+ p = PyMem_Malloc(n+2);
+ if (p != NULL) {
+ strncpy(p, q, n);
+ p[n] = '\n';
+ p[n+1] = '\0';
+ }
+ free(q);
+ RESTORE_LOCALE(saved_locale)
+ return p;
}
@@ -1076,27 +1076,27 @@ PyDoc_STRVAR(doc_module_le,
PyMODINIT_FUNC
initreadline(void)
{
- PyObject *m;
+ PyObject *m;
#ifdef __APPLE__
- if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
- using_libedit_emulation = 1;
- }
+ if (strncmp(rl_library_version, libedit_version_tag, strlen(libedit_version_tag)) == 0) {
+ using_libedit_emulation = 1;
+ }
- if (using_libedit_emulation)
- m = Py_InitModule4("readline", readline_methods, doc_module_le,
- (PyObject *)NULL, PYTHON_API_VERSION);
- else
+ if (using_libedit_emulation)
+ m = Py_InitModule4("readline", readline_methods, doc_module_le,
+ (PyObject *)NULL, PYTHON_API_VERSION);
+ else
#endif /* __APPLE__ */
- m = Py_InitModule4("readline", readline_methods, doc_module,
- (PyObject *)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
+ m = Py_InitModule4("readline", readline_methods, doc_module,
+ (PyObject *)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
- PyOS_ReadlineFunctionPointer = call_readline;
- setup_readline();
+ PyOS_ReadlineFunctionPointer = call_readline;
+ setup_readline();
}
diff --git a/Modules/resource.c b/Modules/resource.c
index 38974f9..9993b93 100644
--- a/Modules/resource.c
+++ b/Modules/resource.c
@@ -29,30 +29,30 @@ PyDoc_STRVAR(struct_rusage__doc__,
"or via the attributes ru_utime, ru_stime, ru_maxrss, and so on.");
static PyStructSequence_Field struct_rusage_fields[] = {
- {"ru_utime", "user time used"},
- {"ru_stime", "system time used"},
- {"ru_maxrss", "max. resident set size"},
- {"ru_ixrss", "shared memory size"},
- {"ru_idrss", "unshared data size"},
- {"ru_isrss", "unshared stack size"},
- {"ru_minflt", "page faults not requiring I/O"},
- {"ru_majflt", "page faults requiring I/O"},
- {"ru_nswap", "number of swap outs"},
- {"ru_inblock", "block input operations"},
- {"ru_oublock", "block output operations"},
- {"ru_msgsnd", "IPC messages sent"},
- {"ru_msgrcv", "IPC messages received"},
- {"ru_nsignals", "signals received"},
- {"ru_nvcsw", "voluntary context switches"},
- {"ru_nivcsw", "involuntary context switches"},
- {0}
+ {"ru_utime", "user time used"},
+ {"ru_stime", "system time used"},
+ {"ru_maxrss", "max. resident set size"},
+ {"ru_ixrss", "shared memory size"},
+ {"ru_idrss", "unshared data size"},
+ {"ru_isrss", "unshared stack size"},
+ {"ru_minflt", "page faults not requiring I/O"},
+ {"ru_majflt", "page faults requiring I/O"},
+ {"ru_nswap", "number of swap outs"},
+ {"ru_inblock", "block input operations"},
+ {"ru_oublock", "block output operations"},
+ {"ru_msgsnd", "IPC messages sent"},
+ {"ru_msgrcv", "IPC messages received"},
+ {"ru_nsignals", "signals received"},
+ {"ru_nvcsw", "voluntary context switches"},
+ {"ru_nivcsw", "involuntary context switches"},
+ {0}
};
static PyStructSequence_Desc struct_rusage_desc = {
- "resource.struct_rusage", /* name */
- struct_rusage__doc__, /* doc */
- struct_rusage_fields, /* fields */
- 16 /* n_in_sequence */
+ "resource.struct_rusage", /* name */
+ struct_rusage__doc__, /* doc */
+ struct_rusage_fields, /* fields */
+ 16 /* n_in_sequence */
};
static int initialized;
@@ -61,153 +61,153 @@ static PyTypeObject StructRUsageType;
static PyObject *
resource_getrusage(PyObject *self, PyObject *args)
{
- int who;
- struct rusage ru;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "i:getrusage", &who))
- return NULL;
-
- if (getrusage(who, &ru) == -1) {
- if (errno == EINVAL) {
- PyErr_SetString(PyExc_ValueError,
- "invalid who parameter");
- return NULL;
- }
- PyErr_SetFromErrno(ResourceError);
- return NULL;
- }
-
- result = PyStructSequence_New(&StructRUsageType);
- if (!result)
- return NULL;
-
- PyStructSequence_SET_ITEM(result, 0,
- PyFloat_FromDouble(doubletime(ru.ru_utime)));
- PyStructSequence_SET_ITEM(result, 1,
- PyFloat_FromDouble(doubletime(ru.ru_stime)));
- PyStructSequence_SET_ITEM(result, 2, PyInt_FromLong(ru.ru_maxrss));
- PyStructSequence_SET_ITEM(result, 3, PyInt_FromLong(ru.ru_ixrss));
- PyStructSequence_SET_ITEM(result, 4, PyInt_FromLong(ru.ru_idrss));
- PyStructSequence_SET_ITEM(result, 5, PyInt_FromLong(ru.ru_isrss));
- PyStructSequence_SET_ITEM(result, 6, PyInt_FromLong(ru.ru_minflt));
- PyStructSequence_SET_ITEM(result, 7, PyInt_FromLong(ru.ru_majflt));
- PyStructSequence_SET_ITEM(result, 8, PyInt_FromLong(ru.ru_nswap));
- PyStructSequence_SET_ITEM(result, 9, PyInt_FromLong(ru.ru_inblock));
- PyStructSequence_SET_ITEM(result, 10, PyInt_FromLong(ru.ru_oublock));
- PyStructSequence_SET_ITEM(result, 11, PyInt_FromLong(ru.ru_msgsnd));
- PyStructSequence_SET_ITEM(result, 12, PyInt_FromLong(ru.ru_msgrcv));
- PyStructSequence_SET_ITEM(result, 13, PyInt_FromLong(ru.ru_nsignals));
- PyStructSequence_SET_ITEM(result, 14, PyInt_FromLong(ru.ru_nvcsw));
- PyStructSequence_SET_ITEM(result, 15, PyInt_FromLong(ru.ru_nivcsw));
-
- if (PyErr_Occurred()) {
- Py_DECREF(result);
- return NULL;
- }
-
- return result;
+ int who;
+ struct rusage ru;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "i:getrusage", &who))
+ return NULL;
+
+ if (getrusage(who, &ru) == -1) {
+ if (errno == EINVAL) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid who parameter");
+ return NULL;
+ }
+ PyErr_SetFromErrno(ResourceError);
+ return NULL;
+ }
+
+ result = PyStructSequence_New(&StructRUsageType);
+ if (!result)
+ return NULL;
+
+ PyStructSequence_SET_ITEM(result, 0,
+ PyFloat_FromDouble(doubletime(ru.ru_utime)));
+ PyStructSequence_SET_ITEM(result, 1,
+ PyFloat_FromDouble(doubletime(ru.ru_stime)));
+ PyStructSequence_SET_ITEM(result, 2, PyInt_FromLong(ru.ru_maxrss));
+ PyStructSequence_SET_ITEM(result, 3, PyInt_FromLong(ru.ru_ixrss));
+ PyStructSequence_SET_ITEM(result, 4, PyInt_FromLong(ru.ru_idrss));
+ PyStructSequence_SET_ITEM(result, 5, PyInt_FromLong(ru.ru_isrss));
+ PyStructSequence_SET_ITEM(result, 6, PyInt_FromLong(ru.ru_minflt));
+ PyStructSequence_SET_ITEM(result, 7, PyInt_FromLong(ru.ru_majflt));
+ PyStructSequence_SET_ITEM(result, 8, PyInt_FromLong(ru.ru_nswap));
+ PyStructSequence_SET_ITEM(result, 9, PyInt_FromLong(ru.ru_inblock));
+ PyStructSequence_SET_ITEM(result, 10, PyInt_FromLong(ru.ru_oublock));
+ PyStructSequence_SET_ITEM(result, 11, PyInt_FromLong(ru.ru_msgsnd));
+ PyStructSequence_SET_ITEM(result, 12, PyInt_FromLong(ru.ru_msgrcv));
+ PyStructSequence_SET_ITEM(result, 13, PyInt_FromLong(ru.ru_nsignals));
+ PyStructSequence_SET_ITEM(result, 14, PyInt_FromLong(ru.ru_nvcsw));
+ PyStructSequence_SET_ITEM(result, 15, PyInt_FromLong(ru.ru_nivcsw));
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return result;
}
static PyObject *
resource_getrlimit(PyObject *self, PyObject *args)
{
- struct rlimit rl;
- int resource;
+ struct rlimit rl;
+ int resource;
- if (!PyArg_ParseTuple(args, "i:getrlimit", &resource))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:getrlimit", &resource))
+ return NULL;
- if (resource < 0 || resource >= RLIM_NLIMITS) {
- PyErr_SetString(PyExc_ValueError,
- "invalid resource specified");
- return NULL;
- }
+ if (resource < 0 || resource >= RLIM_NLIMITS) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid resource specified");
+ return NULL;
+ }
- if (getrlimit(resource, &rl) == -1) {
- PyErr_SetFromErrno(ResourceError);
- return NULL;
- }
+ if (getrlimit(resource, &rl) == -1) {
+ PyErr_SetFromErrno(ResourceError);
+ return NULL;
+ }
#if defined(HAVE_LONG_LONG)
- if (sizeof(rl.rlim_cur) > sizeof(long)) {
- return Py_BuildValue("LL",
- (PY_LONG_LONG) rl.rlim_cur,
- (PY_LONG_LONG) rl.rlim_max);
- }
+ if (sizeof(rl.rlim_cur) > sizeof(long)) {
+ return Py_BuildValue("LL",
+ (PY_LONG_LONG) rl.rlim_cur,
+ (PY_LONG_LONG) rl.rlim_max);
+ }
#endif
- return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
+ return Py_BuildValue("ll", (long) rl.rlim_cur, (long) rl.rlim_max);
}
static PyObject *
resource_setrlimit(PyObject *self, PyObject *args)
{
- struct rlimit rl;
- int resource;
- PyObject *curobj, *maxobj;
+ struct rlimit rl;
+ int resource;
+ PyObject *curobj, *maxobj;
- if (!PyArg_ParseTuple(args, "i(OO):setrlimit",
- &resource, &curobj, &maxobj))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i(OO):setrlimit",
+ &resource, &curobj, &maxobj))
+ return NULL;
- if (resource < 0 || resource >= RLIM_NLIMITS) {
- PyErr_SetString(PyExc_ValueError,
- "invalid resource specified");
- return NULL;
- }
+ if (resource < 0 || resource >= RLIM_NLIMITS) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid resource specified");
+ return NULL;
+ }
#if !defined(HAVE_LARGEFILE_SUPPORT)
- rl.rlim_cur = PyInt_AsLong(curobj);
- if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
- rl.rlim_max = PyInt_AsLong(maxobj);
- if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
+ rl.rlim_cur = PyInt_AsLong(curobj);
+ if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
+ rl.rlim_max = PyInt_AsLong(maxobj);
+ if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
#else
- /* The limits are probably bigger than a long */
- rl.rlim_cur = PyLong_Check(curobj) ?
- PyLong_AsLongLong(curobj) : PyInt_AsLong(curobj);
- if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
- rl.rlim_max = PyLong_Check(maxobj) ?
- PyLong_AsLongLong(maxobj) : PyInt_AsLong(maxobj);
- if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
- return NULL;
+ /* The limits are probably bigger than a long */
+ rl.rlim_cur = PyLong_Check(curobj) ?
+ PyLong_AsLongLong(curobj) : PyInt_AsLong(curobj);
+ if (rl.rlim_cur == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
+ rl.rlim_max = PyLong_Check(maxobj) ?
+ PyLong_AsLongLong(maxobj) : PyInt_AsLong(maxobj);
+ if (rl.rlim_max == (rlim_t)-1 && PyErr_Occurred())
+ return NULL;
#endif
- rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY;
- rl.rlim_max = rl.rlim_max & RLIM_INFINITY;
- if (setrlimit(resource, &rl) == -1) {
- if (errno == EINVAL)
- PyErr_SetString(PyExc_ValueError,
- "current limit exceeds maximum limit");
- else if (errno == EPERM)
- PyErr_SetString(PyExc_ValueError,
- "not allowed to raise maximum limit");
- else
- PyErr_SetFromErrno(ResourceError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ rl.rlim_cur = rl.rlim_cur & RLIM_INFINITY;
+ rl.rlim_max = rl.rlim_max & RLIM_INFINITY;
+ if (setrlimit(resource, &rl) == -1) {
+ if (errno == EINVAL)
+ PyErr_SetString(PyExc_ValueError,
+ "current limit exceeds maximum limit");
+ else if (errno == EPERM)
+ PyErr_SetString(PyExc_ValueError,
+ "not allowed to raise maximum limit");
+ else
+ PyErr_SetFromErrno(ResourceError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
resource_getpagesize(PyObject *self, PyObject *unused)
{
- long pagesize = 0;
+ long pagesize = 0;
#if defined(HAVE_GETPAGESIZE)
- pagesize = getpagesize();
+ pagesize = getpagesize();
#elif defined(HAVE_SYSCONF)
#if defined(_SC_PAGE_SIZE)
- pagesize = sysconf(_SC_PAGE_SIZE);
+ pagesize = sysconf(_SC_PAGE_SIZE);
#else
- /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
- pagesize = sysconf(_SC_PAGESIZE);
+ /* Irix 5.3 has _SC_PAGESIZE, but not _SC_PAGE_SIZE */
+ pagesize = sysconf(_SC_PAGESIZE);
#endif
#endif
- return Py_BuildValue("i", pagesize);
+ return Py_BuildValue("i", pagesize);
}
@@ -215,11 +215,11 @@ resource_getpagesize(PyObject *self, PyObject *unused)
static struct PyMethodDef
resource_methods[] = {
- {"getrusage", resource_getrusage, METH_VARARGS},
- {"getrlimit", resource_getrlimit, METH_VARARGS},
- {"setrlimit", resource_setrlimit, METH_VARARGS},
- {"getpagesize", resource_getpagesize, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ {"getrusage", resource_getrusage, METH_VARARGS},
+ {"getrlimit", resource_getrlimit, METH_VARARGS},
+ {"setrlimit", resource_setrlimit, METH_VARARGS},
+ {"getpagesize", resource_getpagesize, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
@@ -228,102 +228,102 @@ resource_methods[] = {
PyMODINIT_FUNC
initresource(void)
{
- PyObject *m, *v;
-
- /* Create the module and add the functions */
- m = Py_InitModule("resource", resource_methods);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
- if (ResourceError == NULL) {
- ResourceError = PyErr_NewException("resource.error",
- NULL, NULL);
- }
- Py_INCREF(ResourceError);
- PyModule_AddObject(m, "error", ResourceError);
- if (!initialized)
- PyStructSequence_InitType(&StructRUsageType,
- &struct_rusage_desc);
- Py_INCREF(&StructRUsageType);
- PyModule_AddObject(m, "struct_rusage",
- (PyObject*) &StructRUsageType);
-
- /* insert constants */
+ PyObject *m, *v;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule("resource", resource_methods);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+ if (ResourceError == NULL) {
+ ResourceError = PyErr_NewException("resource.error",
+ NULL, NULL);
+ }
+ Py_INCREF(ResourceError);
+ PyModule_AddObject(m, "error", ResourceError);
+ if (!initialized)
+ PyStructSequence_InitType(&StructRUsageType,
+ &struct_rusage_desc);
+ Py_INCREF(&StructRUsageType);
+ PyModule_AddObject(m, "struct_rusage",
+ (PyObject*) &StructRUsageType);
+
+ /* insert constants */
#ifdef RLIMIT_CPU
- PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU);
+ PyModule_AddIntConstant(m, "RLIMIT_CPU", RLIMIT_CPU);
#endif
#ifdef RLIMIT_FSIZE
- PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE);
+ PyModule_AddIntConstant(m, "RLIMIT_FSIZE", RLIMIT_FSIZE);
#endif
#ifdef RLIMIT_DATA
- PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA);
+ PyModule_AddIntConstant(m, "RLIMIT_DATA", RLIMIT_DATA);
#endif
#ifdef RLIMIT_STACK
- PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK);
+ PyModule_AddIntConstant(m, "RLIMIT_STACK", RLIMIT_STACK);
#endif
#ifdef RLIMIT_CORE
- PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE);
+ PyModule_AddIntConstant(m, "RLIMIT_CORE", RLIMIT_CORE);
#endif
#ifdef RLIMIT_NOFILE
- PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE);
+ PyModule_AddIntConstant(m, "RLIMIT_NOFILE", RLIMIT_NOFILE);
#endif
#ifdef RLIMIT_OFILE
- PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE);
+ PyModule_AddIntConstant(m, "RLIMIT_OFILE", RLIMIT_OFILE);
#endif
#ifdef RLIMIT_VMEM
- PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM);
+ PyModule_AddIntConstant(m, "RLIMIT_VMEM", RLIMIT_VMEM);
#endif
#ifdef RLIMIT_AS
- PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS);
+ PyModule_AddIntConstant(m, "RLIMIT_AS", RLIMIT_AS);
#endif
#ifdef RLIMIT_RSS
- PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS);
+ PyModule_AddIntConstant(m, "RLIMIT_RSS", RLIMIT_RSS);
#endif
#ifdef RLIMIT_NPROC
- PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC);
+ PyModule_AddIntConstant(m, "RLIMIT_NPROC", RLIMIT_NPROC);
#endif
#ifdef RLIMIT_MEMLOCK
- PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK);
+ PyModule_AddIntConstant(m, "RLIMIT_MEMLOCK", RLIMIT_MEMLOCK);
#endif
#ifdef RLIMIT_SBSIZE
- PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE);
+ PyModule_AddIntConstant(m, "RLIMIT_SBSIZE", RLIMIT_SBSIZE);
#endif
#ifdef RUSAGE_SELF
- PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF);
+ PyModule_AddIntConstant(m, "RUSAGE_SELF", RUSAGE_SELF);
#endif
#ifdef RUSAGE_CHILDREN
- PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN);
+ PyModule_AddIntConstant(m, "RUSAGE_CHILDREN", RUSAGE_CHILDREN);
#endif
#ifdef RUSAGE_BOTH
- PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
+ PyModule_AddIntConstant(m, "RUSAGE_BOTH", RUSAGE_BOTH);
#endif
#if defined(HAVE_LONG_LONG)
- if (sizeof(RLIM_INFINITY) > sizeof(long)) {
- v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
- } else
+ if (sizeof(RLIM_INFINITY) > sizeof(long)) {
+ v = PyLong_FromLongLong((PY_LONG_LONG) RLIM_INFINITY);
+ } else
#endif
- {
- v = PyInt_FromLong((long) RLIM_INFINITY);
- }
- if (v) {
- PyModule_AddObject(m, "RLIM_INFINITY", v);
- }
- initialized = 1;
+ {
+ v = PyInt_FromLong((long) RLIM_INFINITY);
+ }
+ if (v) {
+ PyModule_AddObject(m, "RLIM_INFINITY", v);
+ }
+ initialized = 1;
}
diff --git a/Modules/rotatingtree.c b/Modules/rotatingtree.c
index 39c6dd5..07e08bc 100644
--- a/Modules/rotatingtree.c
+++ b/Modules/rotatingtree.c
@@ -14,14 +14,14 @@ static unsigned int random_stream = 0;
static int
randombits(int bits)
{
- int result;
- if (random_stream < (1U << bits)) {
- random_value *= 1082527;
- random_stream = random_value;
- }
- result = random_stream & ((1<<bits)-1);
- random_stream >>= bits;
- return result;
+ int result;
+ if (random_stream < (1U << bits)) {
+ random_value *= 1082527;
+ random_stream = random_value;
+ }
+ result = random_stream & ((1<<bits)-1);
+ random_stream >>= bits;
+ return result;
}
@@ -30,15 +30,15 @@ randombits(int bits)
void
RotatingTree_Add(rotating_node_t **root, rotating_node_t *node)
{
- while (*root != NULL) {
- if (KEY_LOWER_THAN(node->key, (*root)->key))
- root = &((*root)->left);
- else
- root = &((*root)->right);
- }
- node->left = NULL;
- node->right = NULL;
- *root = node;
+ while (*root != NULL) {
+ if (KEY_LOWER_THAN(node->key, (*root)->key))
+ root = &((*root)->left);
+ else
+ root = &((*root)->right);
+ }
+ node->left = NULL;
+ node->right = NULL;
+ *root = node;
}
/* Locate the node with the given key. This is the most complicated
@@ -47,57 +47,57 @@ RotatingTree_Add(rotating_node_t **root, rotating_node_t *node)
rotating_node_t *
RotatingTree_Get(rotating_node_t **root, void *key)
{
- if (randombits(3) != 4) {
- /* Fast path, no rebalancing */
- rotating_node_t *node = *root;
- while (node != NULL) {
- if (node->key == key)
- return node;
- if (KEY_LOWER_THAN(key, node->key))
- node = node->left;
- else
- node = node->right;
- }
- return NULL;
- }
- else {
- rotating_node_t **pnode = root;
- rotating_node_t *node = *pnode;
- rotating_node_t *next;
- int rotate;
- if (node == NULL)
- return NULL;
- while (1) {
- if (node->key == key)
- return node;
- rotate = !randombits(1);
- if (KEY_LOWER_THAN(key, node->key)) {
- next = node->left;
- if (next == NULL)
- return NULL;
- if (rotate) {
- node->left = next->right;
- next->right = node;
- *pnode = next;
- }
- else
- pnode = &(node->left);
- }
- else {
- next = node->right;
- if (next == NULL)
- return NULL;
- if (rotate) {
- node->right = next->left;
- next->left = node;
- *pnode = next;
- }
- else
- pnode = &(node->right);
- }
- node = next;
- }
- }
+ if (randombits(3) != 4) {
+ /* Fast path, no rebalancing */
+ rotating_node_t *node = *root;
+ while (node != NULL) {
+ if (node->key == key)
+ return node;
+ if (KEY_LOWER_THAN(key, node->key))
+ node = node->left;
+ else
+ node = node->right;
+ }
+ return NULL;
+ }
+ else {
+ rotating_node_t **pnode = root;
+ rotating_node_t *node = *pnode;
+ rotating_node_t *next;
+ int rotate;
+ if (node == NULL)
+ return NULL;
+ while (1) {
+ if (node->key == key)
+ return node;
+ rotate = !randombits(1);
+ if (KEY_LOWER_THAN(key, node->key)) {
+ next = node->left;
+ if (next == NULL)
+ return NULL;
+ if (rotate) {
+ node->left = next->right;
+ next->right = node;
+ *pnode = next;
+ }
+ else
+ pnode = &(node->left);
+ }
+ else {
+ next = node->right;
+ if (next == NULL)
+ return NULL;
+ if (rotate) {
+ node->right = next->left;
+ next->left = node;
+ *pnode = next;
+ }
+ else
+ pnode = &(node->right);
+ }
+ node = next;
+ }
+ }
}
/* Enumerate all nodes in the tree. The callback enumfn() should return
@@ -105,17 +105,17 @@ RotatingTree_Get(rotating_node_t **root, void *key)
A non-zero value is directly returned by RotatingTree_Enum(). */
int
RotatingTree_Enum(rotating_node_t *root, rotating_tree_enum_fn enumfn,
- void *arg)
+ void *arg)
{
- int result;
- rotating_node_t *node;
- while (root != NULL) {
- result = RotatingTree_Enum(root->left, enumfn, arg);
- if (result != 0) return result;
- node = root->right;
- result = enumfn(root, arg);
- if (result != 0) return result;
- root = node;
- }
- return 0;
+ int result;
+ rotating_node_t *node;
+ while (root != NULL) {
+ result = RotatingTree_Enum(root->left, enumfn, arg);
+ if (result != 0) return result;
+ node = root->right;
+ result = enumfn(root, arg);
+ if (result != 0) return result;
+ root = node;
+ }
+ return 0;
}
diff --git a/Modules/selectmodule.c b/Modules/selectmodule.c
index 5960544..c49c7b7 100644
--- a/Modules/selectmodule.c
+++ b/Modules/selectmodule.c
@@ -24,7 +24,7 @@
*/
#if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
#define FD_SETSIZE 512
-#endif
+#endif
#if defined(HAVE_POLL_H)
#include <poll.h>
@@ -61,20 +61,20 @@ static PyObject *SelectError;
/* list of Python objects and their file descriptor */
typedef struct {
- PyObject *obj; /* owned reference */
- SOCKET fd;
- int sentinel; /* -1 == sentinel */
+ PyObject *obj; /* owned reference */
+ SOCKET fd;
+ int sentinel; /* -1 == sentinel */
} pylist;
static void
reap_obj(pylist fd2obj[FD_SETSIZE + 1])
{
- int i;
- for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
- Py_XDECREF(fd2obj[i].obj);
- fd2obj[i].obj = NULL;
- }
- fd2obj[0].sentinel = -1;
+ int i;
+ for (i = 0; i < FD_SETSIZE + 1 && fd2obj[i].sentinel >= 0; i++) {
+ Py_XDECREF(fd2obj[i].obj);
+ fd2obj[i].obj = NULL;
+ }
+ fd2obj[0].sentinel = -1;
}
@@ -84,106 +84,106 @@ reap_obj(pylist fd2obj[FD_SETSIZE + 1])
static int
seq2set(PyObject *seq, fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
- int i;
- int max = -1;
- int index = 0;
- int len = -1;
- PyObject* fast_seq = NULL;
- PyObject* o = NULL;
-
- fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
- FD_ZERO(set);
-
- fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
- if (!fast_seq)
- return -1;
+ int i;
+ int max = -1;
+ int index = 0;
+ int len = -1;
+ PyObject* fast_seq = NULL;
+ PyObject* o = NULL;
+
+ fd2obj[0].obj = (PyObject*)0; /* set list to zero size */
+ FD_ZERO(set);
+
+ fast_seq = PySequence_Fast(seq, "arguments 1-3 must be sequences");
+ if (!fast_seq)
+ return -1;
- len = PySequence_Fast_GET_SIZE(fast_seq);
+ len = PySequence_Fast_GET_SIZE(fast_seq);
- for (i = 0; i < len; i++) {
- SOCKET v;
+ for (i = 0; i < len; i++) {
+ SOCKET v;
- /* any intervening fileno() calls could decr this refcnt */
- if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
- return -1;
+ /* any intervening fileno() calls could decr this refcnt */
+ if (!(o = PySequence_Fast_GET_ITEM(fast_seq, i)))
+ return -1;
- Py_INCREF(o);
- v = PyObject_AsFileDescriptor( o );
- if (v == -1) goto finally;
+ Py_INCREF(o);
+ v = PyObject_AsFileDescriptor( o );
+ if (v == -1) goto finally;
#if defined(_MSC_VER)
- max = 0; /* not used for Win32 */
+ max = 0; /* not used for Win32 */
#else /* !_MSC_VER */
- if (v < 0 || v >= FD_SETSIZE) {
- PyErr_SetString(PyExc_ValueError,
- "filedescriptor out of range in select()");
- goto finally;
- }
- if (v > max)
- max = v;
+ if (v < 0 || v >= FD_SETSIZE) {
+ PyErr_SetString(PyExc_ValueError,
+ "filedescriptor out of range in select()");
+ goto finally;
+ }
+ if (v > max)
+ max = v;
#endif /* _MSC_VER */
- FD_SET(v, set);
-
- /* add object and its file descriptor to the list */
- if (index >= FD_SETSIZE) {
- PyErr_SetString(PyExc_ValueError,
- "too many file descriptors in select()");
- goto finally;
- }
- fd2obj[index].obj = o;
- fd2obj[index].fd = v;
- fd2obj[index].sentinel = 0;
- fd2obj[++index].sentinel = -1;
- }
- Py_DECREF(fast_seq);
- return max+1;
+ FD_SET(v, set);
+
+ /* add object and its file descriptor to the list */
+ if (index >= FD_SETSIZE) {
+ PyErr_SetString(PyExc_ValueError,
+ "too many file descriptors in select()");
+ goto finally;
+ }
+ fd2obj[index].obj = o;
+ fd2obj[index].fd = v;
+ fd2obj[index].sentinel = 0;
+ fd2obj[++index].sentinel = -1;
+ }
+ Py_DECREF(fast_seq);
+ return max+1;
finally:
- Py_XDECREF(o);
- Py_DECREF(fast_seq);
- return -1;
+ Py_XDECREF(o);
+ Py_DECREF(fast_seq);
+ return -1;
}
/* returns NULL and sets the Python exception if an error occurred */
static PyObject *
set2list(fd_set *set, pylist fd2obj[FD_SETSIZE + 1])
{
- int i, j, count=0;
- PyObject *list, *o;
- SOCKET fd;
-
- for (j = 0; fd2obj[j].sentinel >= 0; j++) {
- if (FD_ISSET(fd2obj[j].fd, set))
- count++;
- }
- list = PyList_New(count);
- if (!list)
- return NULL;
-
- i = 0;
- for (j = 0; fd2obj[j].sentinel >= 0; j++) {
- fd = fd2obj[j].fd;
- if (FD_ISSET(fd, set)) {
+ int i, j, count=0;
+ PyObject *list, *o;
+ SOCKET fd;
+
+ for (j = 0; fd2obj[j].sentinel >= 0; j++) {
+ if (FD_ISSET(fd2obj[j].fd, set))
+ count++;
+ }
+ list = PyList_New(count);
+ if (!list)
+ return NULL;
+
+ i = 0;
+ for (j = 0; fd2obj[j].sentinel >= 0; j++) {
+ fd = fd2obj[j].fd;
+ if (FD_ISSET(fd, set)) {
#ifndef _MSC_VER
- if (fd > FD_SETSIZE) {
- PyErr_SetString(PyExc_SystemError,
- "filedescriptor out of range returned in select()");
- goto finally;
- }
+ if (fd > FD_SETSIZE) {
+ PyErr_SetString(PyExc_SystemError,
+ "filedescriptor out of range returned in select()");
+ goto finally;
+ }
#endif
- o = fd2obj[j].obj;
- fd2obj[j].obj = NULL;
- /* transfer ownership */
- if (PyList_SetItem(list, i, o) < 0)
- goto finally;
-
- i++;
- }
- }
- return list;
+ o = fd2obj[j].obj;
+ fd2obj[j].obj = NULL;
+ /* transfer ownership */
+ if (PyList_SetItem(list, i, o) < 0)
+ goto finally;
+
+ i++;
+ }
+ }
+ return list;
finally:
- Py_DECREF(list);
- return NULL;
+ Py_DECREF(list);
+ return NULL;
}
#undef SELECT_USES_HEAP
@@ -195,170 +195,170 @@ static PyObject *
select_select(PyObject *self, PyObject *args)
{
#ifdef SELECT_USES_HEAP
- pylist *rfd2obj, *wfd2obj, *efd2obj;
+ pylist *rfd2obj, *wfd2obj, *efd2obj;
#else /* !SELECT_USES_HEAP */
- /* XXX: All this should probably be implemented as follows:
- * - find the highest descriptor we're interested in
- * - add one
- * - that's the size
- * See: Stevens, APitUE, $12.5.1
- */
- pylist rfd2obj[FD_SETSIZE + 1];
- pylist wfd2obj[FD_SETSIZE + 1];
- pylist efd2obj[FD_SETSIZE + 1];
+ /* XXX: All this should probably be implemented as follows:
+ * - find the highest descriptor we're interested in
+ * - add one
+ * - that's the size
+ * See: Stevens, APitUE, $12.5.1
+ */
+ pylist rfd2obj[FD_SETSIZE + 1];
+ pylist wfd2obj[FD_SETSIZE + 1];
+ pylist efd2obj[FD_SETSIZE + 1];
#endif /* SELECT_USES_HEAP */
- PyObject *ifdlist, *ofdlist, *efdlist;
- PyObject *ret = NULL;
- PyObject *tout = Py_None;
- fd_set ifdset, ofdset, efdset;
- double timeout;
- struct timeval tv, *tvp;
- long seconds;
- int imax, omax, emax, max;
- int n;
-
- /* convert arguments */
- if (!PyArg_UnpackTuple(args, "select", 3, 4,
- &ifdlist, &ofdlist, &efdlist, &tout))
- return NULL;
-
- if (tout == Py_None)
- tvp = (struct timeval *)0;
- else if (!PyNumber_Check(tout)) {
- PyErr_SetString(PyExc_TypeError,
- "timeout must be a float or None");
- return NULL;
- }
- else {
- timeout = PyFloat_AsDouble(tout);
- if (timeout == -1 && PyErr_Occurred())
- return NULL;
- if (timeout > (double)LONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout period too long");
- return NULL;
- }
- seconds = (long)timeout;
- timeout = timeout - (double)seconds;
- tv.tv_sec = seconds;
- tv.tv_usec = (long)(timeout * 1E6);
- tvp = &tv;
- }
+ PyObject *ifdlist, *ofdlist, *efdlist;
+ PyObject *ret = NULL;
+ PyObject *tout = Py_None;
+ fd_set ifdset, ofdset, efdset;
+ double timeout;
+ struct timeval tv, *tvp;
+ long seconds;
+ int imax, omax, emax, max;
+ int n;
+
+ /* convert arguments */
+ if (!PyArg_UnpackTuple(args, "select", 3, 4,
+ &ifdlist, &ofdlist, &efdlist, &tout))
+ return NULL;
+
+ if (tout == Py_None)
+ tvp = (struct timeval *)0;
+ else if (!PyNumber_Check(tout)) {
+ PyErr_SetString(PyExc_TypeError,
+ "timeout must be a float or None");
+ return NULL;
+ }
+ else {
+ timeout = PyFloat_AsDouble(tout);
+ if (timeout == -1 && PyErr_Occurred())
+ return NULL;
+ if (timeout > (double)LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout period too long");
+ return NULL;
+ }
+ seconds = (long)timeout;
+ timeout = timeout - (double)seconds;
+ tv.tv_sec = seconds;
+ tv.tv_usec = (long)(timeout * 1E6);
+ tvp = &tv;
+ }
#ifdef SELECT_USES_HEAP
- /* Allocate memory for the lists */
- rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
- wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
- efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
- if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
- if (rfd2obj) PyMem_DEL(rfd2obj);
- if (wfd2obj) PyMem_DEL(wfd2obj);
- if (efd2obj) PyMem_DEL(efd2obj);
- return PyErr_NoMemory();
- }
+ /* Allocate memory for the lists */
+ rfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
+ wfd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
+ efd2obj = PyMem_NEW(pylist, FD_SETSIZE + 1);
+ if (rfd2obj == NULL || wfd2obj == NULL || efd2obj == NULL) {
+ if (rfd2obj) PyMem_DEL(rfd2obj);
+ if (wfd2obj) PyMem_DEL(wfd2obj);
+ if (efd2obj) PyMem_DEL(efd2obj);
+ return PyErr_NoMemory();
+ }
#endif /* SELECT_USES_HEAP */
- /* Convert sequences to fd_sets, and get maximum fd number
- * propagates the Python exception set in seq2set()
- */
- rfd2obj[0].sentinel = -1;
- wfd2obj[0].sentinel = -1;
- efd2obj[0].sentinel = -1;
- if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
- goto finally;
- if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
- goto finally;
- if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
- goto finally;
- max = imax;
- if (omax > max) max = omax;
- if (emax > max) max = emax;
-
- Py_BEGIN_ALLOW_THREADS
- n = select(max, &ifdset, &ofdset, &efdset, tvp);
- Py_END_ALLOW_THREADS
+ /* Convert sequences to fd_sets, and get maximum fd number
+ * propagates the Python exception set in seq2set()
+ */
+ rfd2obj[0].sentinel = -1;
+ wfd2obj[0].sentinel = -1;
+ efd2obj[0].sentinel = -1;
+ if ((imax=seq2set(ifdlist, &ifdset, rfd2obj)) < 0)
+ goto finally;
+ if ((omax=seq2set(ofdlist, &ofdset, wfd2obj)) < 0)
+ goto finally;
+ if ((emax=seq2set(efdlist, &efdset, efd2obj)) < 0)
+ goto finally;
+ max = imax;
+ if (omax > max) max = omax;
+ if (emax > max) max = emax;
+
+ Py_BEGIN_ALLOW_THREADS
+ n = select(max, &ifdset, &ofdset, &efdset, tvp);
+ Py_END_ALLOW_THREADS
#ifdef MS_WINDOWS
- if (n == SOCKET_ERROR) {
- PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
- }
+ if (n == SOCKET_ERROR) {
+ PyErr_SetExcFromWindowsErr(SelectError, WSAGetLastError());
+ }
#else
- if (n < 0) {
- PyErr_SetFromErrno(SelectError);
- }
+ if (n < 0) {
+ PyErr_SetFromErrno(SelectError);
+ }
#endif
- else {
- /* any of these three calls can raise an exception. it's more
- convenient to test for this after all three calls... but
- is that acceptable?
- */
- ifdlist = set2list(&ifdset, rfd2obj);
- ofdlist = set2list(&ofdset, wfd2obj);
- efdlist = set2list(&efdset, efd2obj);
- if (PyErr_Occurred())
- ret = NULL;
- else
- ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
-
- Py_DECREF(ifdlist);
- Py_DECREF(ofdlist);
- Py_DECREF(efdlist);
- }
-
+ else {
+ /* any of these three calls can raise an exception. it's more
+ convenient to test for this after all three calls... but
+ is that acceptable?
+ */
+ ifdlist = set2list(&ifdset, rfd2obj);
+ ofdlist = set2list(&ofdset, wfd2obj);
+ efdlist = set2list(&efdset, efd2obj);
+ if (PyErr_Occurred())
+ ret = NULL;
+ else
+ ret = PyTuple_Pack(3, ifdlist, ofdlist, efdlist);
+
+ Py_DECREF(ifdlist);
+ Py_DECREF(ofdlist);
+ Py_DECREF(efdlist);
+ }
+
finally:
- reap_obj(rfd2obj);
- reap_obj(wfd2obj);
- reap_obj(efd2obj);
+ reap_obj(rfd2obj);
+ reap_obj(wfd2obj);
+ reap_obj(efd2obj);
#ifdef SELECT_USES_HEAP
- PyMem_DEL(rfd2obj);
- PyMem_DEL(wfd2obj);
- PyMem_DEL(efd2obj);
+ PyMem_DEL(rfd2obj);
+ PyMem_DEL(wfd2obj);
+ PyMem_DEL(efd2obj);
#endif /* SELECT_USES_HEAP */
- return ret;
+ return ret;
}
#if defined(HAVE_POLL) && !defined(HAVE_BROKEN_POLL)
-/*
+/*
* poll() support
*/
typedef struct {
- PyObject_HEAD
- PyObject *dict;
- int ufd_uptodate;
- int ufd_len;
- struct pollfd *ufds;
+ PyObject_HEAD
+ PyObject *dict;
+ int ufd_uptodate;
+ int ufd_len;
+ struct pollfd *ufds;
} pollObject;
static PyTypeObject poll_Type;
-/* Update the malloc'ed array of pollfds to match the dictionary
+/* Update the malloc'ed array of pollfds to match the dictionary
contained within a pollObject. Return 1 on success, 0 on an error.
*/
static int
update_ufd_array(pollObject *self)
{
- Py_ssize_t i, pos;
- PyObject *key, *value;
- struct pollfd *old_ufds = self->ufds;
-
- self->ufd_len = PyDict_Size(self->dict);
- PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
- if (self->ufds == NULL) {
- self->ufds = old_ufds;
- PyErr_NoMemory();
- return 0;
- }
-
- i = pos = 0;
- while (PyDict_Next(self->dict, &pos, &key, &value)) {
- self->ufds[i].fd = PyInt_AsLong(key);
- self->ufds[i].events = (short)PyInt_AsLong(value);
- i++;
- }
- self->ufd_uptodate = 1;
- return 1;
+ Py_ssize_t i, pos;
+ PyObject *key, *value;
+ struct pollfd *old_ufds = self->ufds;
+
+ self->ufd_len = PyDict_Size(self->dict);
+ PyMem_RESIZE(self->ufds, struct pollfd, self->ufd_len);
+ if (self->ufds == NULL) {
+ self->ufds = old_ufds;
+ PyErr_NoMemory();
+ return 0;
+ }
+
+ i = pos = 0;
+ while (PyDict_Next(self->dict, &pos, &key, &value)) {
+ self->ufds[i].fd = PyInt_AsLong(key);
+ self->ufds[i].events = (short)PyInt_AsLong(value);
+ i++;
+ }
+ self->ufd_uptodate = 1;
+ return 1;
}
PyDoc_STRVAR(poll_register_doc,
@@ -369,39 +369,39 @@ fd -- either an integer, or an object with a fileno() method returning an\n\
events -- an optional bitmask describing the type of events to check for");
static PyObject *
-poll_register(pollObject *self, PyObject *args)
+poll_register(pollObject *self, PyObject *args)
{
- PyObject *o, *key, *value;
- int fd, events = POLLIN | POLLPRI | POLLOUT;
- int err;
-
- if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
- return NULL;
- }
-
- fd = PyObject_AsFileDescriptor(o);
- if (fd == -1) return NULL;
-
- /* Add entry to the internal dictionary: the key is the
- file descriptor, and the value is the event mask. */
- key = PyInt_FromLong(fd);
- if (key == NULL)
- return NULL;
- value = PyInt_FromLong(events);
- if (value == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- err = PyDict_SetItem(self->dict, key, value);
- Py_DECREF(key);
- Py_DECREF(value);
- if (err < 0)
- return NULL;
-
- self->ufd_uptodate = 0;
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *o, *key, *value;
+ int fd, events = POLLIN | POLLPRI | POLLOUT;
+ int err;
+
+ if (!PyArg_ParseTuple(args, "O|i:register", &o, &events)) {
+ return NULL;
+ }
+
+ fd = PyObject_AsFileDescriptor(o);
+ if (fd == -1) return NULL;
+
+ /* Add entry to the internal dictionary: the key is the
+ file descriptor, and the value is the event mask. */
+ key = PyInt_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+ value = PyInt_FromLong(events);
+ if (value == NULL) {
+ Py_DECREF(key);
+ return NULL;
+ }
+ err = PyDict_SetItem(self->dict, key, value);
+ Py_DECREF(key);
+ Py_DECREF(value);
+ if (err < 0)
+ return NULL;
+
+ self->ufd_uptodate = 0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(poll_modify_doc,
@@ -414,41 +414,41 @@ events -- an optional bitmask describing the type of events to check for");
static PyObject *
poll_modify(pollObject *self, PyObject *args)
{
- PyObject *o, *key, *value;
- int fd, events;
- int err;
-
- if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {
- return NULL;
- }
-
- fd = PyObject_AsFileDescriptor(o);
- if (fd == -1) return NULL;
-
- /* Modify registered fd */
- key = PyInt_FromLong(fd);
- if (key == NULL)
- return NULL;
- if (PyDict_GetItem(self->dict, key) == NULL) {
- errno = ENOENT;
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- value = PyInt_FromLong(events);
- if (value == NULL) {
- Py_DECREF(key);
- return NULL;
- }
- err = PyDict_SetItem(self->dict, key, value);
- Py_DECREF(key);
- Py_DECREF(value);
- if (err < 0)
- return NULL;
-
- self->ufd_uptodate = 0;
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *o, *key, *value;
+ int fd, events;
+ int err;
+
+ if (!PyArg_ParseTuple(args, "Oi:modify", &o, &events)) {
+ return NULL;
+ }
+
+ fd = PyObject_AsFileDescriptor(o);
+ if (fd == -1) return NULL;
+
+ /* Modify registered fd */
+ key = PyInt_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+ if (PyDict_GetItem(self->dict, key) == NULL) {
+ errno = ENOENT;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ value = PyInt_FromLong(events);
+ if (value == NULL) {
+ Py_DECREF(key);
+ return NULL;
+ }
+ err = PyDict_SetItem(self->dict, key, value);
+ Py_DECREF(key);
+ Py_DECREF(value);
+ if (err < 0)
+ return NULL;
+
+ self->ufd_uptodate = 0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -457,32 +457,32 @@ PyDoc_STRVAR(poll_unregister_doc,
Remove a file descriptor being tracked by the polling object.");
static PyObject *
-poll_unregister(pollObject *self, PyObject *o)
+poll_unregister(pollObject *self, PyObject *o)
{
- PyObject *key;
- int fd;
-
- fd = PyObject_AsFileDescriptor( o );
- if (fd == -1)
- return NULL;
-
- /* Check whether the fd is already in the array */
- key = PyInt_FromLong(fd);
- if (key == NULL)
- return NULL;
-
- if (PyDict_DelItem(self->dict, key) == -1) {
- Py_DECREF(key);
- /* This will simply raise the KeyError set by PyDict_DelItem
- if the file descriptor isn't registered. */
- return NULL;
- }
-
- Py_DECREF(key);
- self->ufd_uptodate = 0;
-
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *key;
+ int fd;
+
+ fd = PyObject_AsFileDescriptor( o );
+ if (fd == -1)
+ return NULL;
+
+ /* Check whether the fd is already in the array */
+ key = PyInt_FromLong(fd);
+ if (key == NULL)
+ return NULL;
+
+ if (PyDict_DelItem(self->dict, key) == -1) {
+ Py_DECREF(key);
+ /* This will simply raise the KeyError set by PyDict_DelItem
+ if the file descriptor isn't registered. */
+ return NULL;
+ }
+
+ Py_DECREF(key);
+ self->ufd_uptodate = 0;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(poll_poll_doc,
@@ -491,161 +491,161 @@ Polls the set of registered file descriptors, returning a list containing \n\
any descriptors that have events or errors to report.");
static PyObject *
-poll_poll(pollObject *self, PyObject *args)
+poll_poll(pollObject *self, PyObject *args)
{
- PyObject *result_list = NULL, *tout = NULL;
- int timeout = 0, poll_result, i, j;
- PyObject *value = NULL, *num = NULL;
-
- if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
- return NULL;
- }
-
- /* Check values for timeout */
- if (tout == NULL || tout == Py_None)
- timeout = -1;
- else if (!PyNumber_Check(tout)) {
- PyErr_SetString(PyExc_TypeError,
- "timeout must be an integer or None");
- return NULL;
- }
- else {
- tout = PyNumber_Int(tout);
- if (!tout)
- return NULL;
- timeout = PyInt_AsLong(tout);
- Py_DECREF(tout);
- if (timeout == -1 && PyErr_Occurred())
- return NULL;
- }
-
- /* Ensure the ufd array is up to date */
- if (!self->ufd_uptodate)
- if (update_ufd_array(self) == 0)
- return NULL;
-
- /* call poll() */
- Py_BEGIN_ALLOW_THREADS
- poll_result = poll(self->ufds, self->ufd_len, timeout);
- Py_END_ALLOW_THREADS
-
- if (poll_result < 0) {
- PyErr_SetFromErrno(SelectError);
- return NULL;
- }
-
- /* build the result list */
-
- result_list = PyList_New(poll_result);
- if (!result_list)
- return NULL;
- else {
- for (i = 0, j = 0; j < poll_result; j++) {
- /* skip to the next fired descriptor */
- while (!self->ufds[i].revents) {
- i++;
- }
- /* if we hit a NULL return, set value to NULL
- and break out of loop; code at end will
- clean up result_list */
- value = PyTuple_New(2);
- if (value == NULL)
- goto error;
- num = PyInt_FromLong(self->ufds[i].fd);
- if (num == NULL) {
- Py_DECREF(value);
- goto error;
- }
- PyTuple_SET_ITEM(value, 0, num);
-
- /* The &0xffff is a workaround for AIX. 'revents'
- is a 16-bit short, and IBM assigned POLLNVAL
- to be 0x8000, so the conversion to int results
- in a negative number. See SF bug #923315. */
- num = PyInt_FromLong(self->ufds[i].revents & 0xffff);
- if (num == NULL) {
- Py_DECREF(value);
- goto error;
- }
- PyTuple_SET_ITEM(value, 1, num);
- if ((PyList_SetItem(result_list, j, value)) == -1) {
- Py_DECREF(value);
- goto error;
- }
- i++;
- }
- }
- return result_list;
+ PyObject *result_list = NULL, *tout = NULL;
+ int timeout = 0, poll_result, i, j;
+ PyObject *value = NULL, *num = NULL;
+
+ if (!PyArg_UnpackTuple(args, "poll", 0, 1, &tout)) {
+ return NULL;
+ }
+
+ /* Check values for timeout */
+ if (tout == NULL || tout == Py_None)
+ timeout = -1;
+ else if (!PyNumber_Check(tout)) {
+ PyErr_SetString(PyExc_TypeError,
+ "timeout must be an integer or None");
+ return NULL;
+ }
+ else {
+ tout = PyNumber_Int(tout);
+ if (!tout)
+ return NULL;
+ timeout = PyInt_AsLong(tout);
+ Py_DECREF(tout);
+ if (timeout == -1 && PyErr_Occurred())
+ return NULL;
+ }
+
+ /* Ensure the ufd array is up to date */
+ if (!self->ufd_uptodate)
+ if (update_ufd_array(self) == 0)
+ return NULL;
+
+ /* call poll() */
+ Py_BEGIN_ALLOW_THREADS
+ poll_result = poll(self->ufds, self->ufd_len, timeout);
+ Py_END_ALLOW_THREADS
+
+ if (poll_result < 0) {
+ PyErr_SetFromErrno(SelectError);
+ return NULL;
+ }
+
+ /* build the result list */
+
+ result_list = PyList_New(poll_result);
+ if (!result_list)
+ return NULL;
+ else {
+ for (i = 0, j = 0; j < poll_result; j++) {
+ /* skip to the next fired descriptor */
+ while (!self->ufds[i].revents) {
+ i++;
+ }
+ /* if we hit a NULL return, set value to NULL
+ and break out of loop; code at end will
+ clean up result_list */
+ value = PyTuple_New(2);
+ if (value == NULL)
+ goto error;
+ num = PyInt_FromLong(self->ufds[i].fd);
+ if (num == NULL) {
+ Py_DECREF(value);
+ goto error;
+ }
+ PyTuple_SET_ITEM(value, 0, num);
+
+ /* The &0xffff is a workaround for AIX. 'revents'
+ is a 16-bit short, and IBM assigned POLLNVAL
+ to be 0x8000, so the conversion to int results
+ in a negative number. See SF bug #923315. */
+ num = PyInt_FromLong(self->ufds[i].revents & 0xffff);
+ if (num == NULL) {
+ Py_DECREF(value);
+ goto error;
+ }
+ PyTuple_SET_ITEM(value, 1, num);
+ if ((PyList_SetItem(result_list, j, value)) == -1) {
+ Py_DECREF(value);
+ goto error;
+ }
+ i++;
+ }
+ }
+ return result_list;
error:
- Py_DECREF(result_list);
- return NULL;
+ Py_DECREF(result_list);
+ return NULL;
}
static PyMethodDef poll_methods[] = {
- {"register", (PyCFunction)poll_register,
- METH_VARARGS, poll_register_doc},
- {"modify", (PyCFunction)poll_modify,
- METH_VARARGS, poll_modify_doc},
- {"unregister", (PyCFunction)poll_unregister,
- METH_O, poll_unregister_doc},
- {"poll", (PyCFunction)poll_poll,
- METH_VARARGS, poll_poll_doc},
- {NULL, NULL} /* sentinel */
+ {"register", (PyCFunction)poll_register,
+ METH_VARARGS, poll_register_doc},
+ {"modify", (PyCFunction)poll_modify,
+ METH_VARARGS, poll_modify_doc},
+ {"unregister", (PyCFunction)poll_unregister,
+ METH_O, poll_unregister_doc},
+ {"poll", (PyCFunction)poll_poll,
+ METH_VARARGS, poll_poll_doc},
+ {NULL, NULL} /* sentinel */
};
static pollObject *
newPollObject(void)
{
- pollObject *self;
- self = PyObject_New(pollObject, &poll_Type);
- if (self == NULL)
- return NULL;
- /* ufd_uptodate is a Boolean, denoting whether the
- array pointed to by ufds matches the contents of the dictionary. */
- self->ufd_uptodate = 0;
- self->ufds = NULL;
- self->dict = PyDict_New();
- if (self->dict == NULL) {
- Py_DECREF(self);
- return NULL;
- }
- return self;
+ pollObject *self;
+ self = PyObject_New(pollObject, &poll_Type);
+ if (self == NULL)
+ return NULL;
+ /* ufd_uptodate is a Boolean, denoting whether the
+ array pointed to by ufds matches the contents of the dictionary. */
+ self->ufd_uptodate = 0;
+ self->ufds = NULL;
+ self->dict = PyDict_New();
+ if (self->dict == NULL) {
+ Py_DECREF(self);
+ return NULL;
+ }
+ return self;
}
static void
poll_dealloc(pollObject *self)
{
- if (self->ufds != NULL)
- PyMem_DEL(self->ufds);
- Py_XDECREF(self->dict);
- PyObject_Del(self);
+ if (self->ufds != NULL)
+ PyMem_DEL(self->ufds);
+ Py_XDECREF(self->dict);
+ PyObject_Del(self);
}
static PyObject *
poll_getattr(pollObject *self, char *name)
{
- return Py_FindMethod(poll_methods, (PyObject *)self, name);
+ return Py_FindMethod(poll_methods, (PyObject *)self, name);
}
static PyTypeObject poll_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.poll", /*tp_name*/
- sizeof(pollObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)poll_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)poll_getattr, /*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*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.poll", /*tp_name*/
+ sizeof(pollObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)poll_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)poll_getattr, /*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*/
};
PyDoc_STRVAR(poll_doc,
@@ -655,36 +655,36 @@ unregistering file descriptors, and then polling them for I/O events.");
static PyObject *
select_poll(PyObject *self, PyObject *unused)
{
- return (PyObject *)newPollObject();
+ return (PyObject *)newPollObject();
}
#ifdef __APPLE__
-/*
+/*
* On some systems poll() sets errno on invalid file descriptors. We test
* for this at runtime because this bug may be fixed or introduced between
* OS releases.
*/
static int select_have_broken_poll(void)
{
- int poll_test;
- int filedes[2];
-
- struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
-
- /* Create a file descriptor to make invalid */
- if (pipe(filedes) < 0) {
- return 1;
- }
- poll_struct.fd = filedes[0];
- close(filedes[0]);
- close(filedes[1]);
- poll_test = poll(&poll_struct, 1, 0);
- if (poll_test < 0) {
- return 1;
- } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
- return 1;
- }
- return 0;
+ int poll_test;
+ int filedes[2];
+
+ struct pollfd poll_struct = { 0, POLLIN|POLLPRI|POLLOUT, 0 };
+
+ /* Create a file descriptor to make invalid */
+ if (pipe(filedes) < 0) {
+ return 1;
+ }
+ poll_struct.fd = filedes[0];
+ close(filedes[0]);
+ close(filedes[1]);
+ poll_test = poll(&poll_struct, 1, 0);
+ if (poll_test < 0) {
+ return 1;
+ } else if (poll_test == 0 && poll_struct.revents != POLLNVAL) {
+ return 1;
+ }
+ return 0;
}
#endif /* __APPLE__ */
@@ -703,8 +703,8 @@ static int select_have_broken_poll(void)
#endif
typedef struct {
- PyObject_HEAD
- SOCKET epfd; /* epoll control file descriptor */
+ PyObject_HEAD
+ SOCKET epfd; /* epoll control file descriptor */
} pyEpoll_Object;
static PyTypeObject pyEpoll_Type;
@@ -713,92 +713,92 @@ static PyTypeObject pyEpoll_Type;
static PyObject *
pyepoll_err_closed(void)
{
- PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "I/O operation on closed epoll fd");
+ return NULL;
}
static int
pyepoll_internal_close(pyEpoll_Object *self)
{
- int save_errno = 0;
- if (self->epfd >= 0) {
- int epfd = self->epfd;
- self->epfd = -1;
- Py_BEGIN_ALLOW_THREADS
- if (close(epfd) < 0)
- save_errno = errno;
- Py_END_ALLOW_THREADS
- }
- return save_errno;
+ int save_errno = 0;
+ if (self->epfd >= 0) {
+ int epfd = self->epfd;
+ self->epfd = -1;
+ Py_BEGIN_ALLOW_THREADS
+ if (close(epfd) < 0)
+ save_errno = errno;
+ Py_END_ALLOW_THREADS
+ }
+ return save_errno;
}
static PyObject *
newPyEpoll_Object(PyTypeObject *type, int sizehint, SOCKET fd)
{
- pyEpoll_Object *self;
-
- if (sizehint == -1) {
- sizehint = FD_SETSIZE-1;
- }
- else if (sizehint < 1) {
- PyErr_Format(PyExc_ValueError,
- "sizehint must be greater zero, got %d",
- sizehint);
- return NULL;
- }
-
- assert(type != NULL && type->tp_alloc != NULL);
- self = (pyEpoll_Object *) type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- if (fd == -1) {
- Py_BEGIN_ALLOW_THREADS
- self->epfd = epoll_create(sizehint);
- Py_END_ALLOW_THREADS
- }
- else {
- self->epfd = fd;
- }
- if (self->epfd < 0) {
- Py_DECREF(self);
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return (PyObject *)self;
+ pyEpoll_Object *self;
+
+ if (sizehint == -1) {
+ sizehint = FD_SETSIZE-1;
+ }
+ else if (sizehint < 1) {
+ PyErr_Format(PyExc_ValueError,
+ "sizehint must be greater zero, got %d",
+ sizehint);
+ return NULL;
+ }
+
+ assert(type != NULL && type->tp_alloc != NULL);
+ self = (pyEpoll_Object *) type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ if (fd == -1) {
+ Py_BEGIN_ALLOW_THREADS
+ self->epfd = epoll_create(sizehint);
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ self->epfd = fd;
+ }
+ if (self->epfd < 0) {
+ Py_DECREF(self);
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return (PyObject *)self;
}
static PyObject *
pyepoll_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- int sizehint = -1;
- static char *kwlist[] = {"sizehint", NULL};
+ int sizehint = -1;
+ static char *kwlist[] = {"sizehint", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist,
- &sizehint))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|i:epoll", kwlist,
+ &sizehint))
+ return NULL;
- return newPyEpoll_Object(type, sizehint, -1);
+ return newPyEpoll_Object(type, sizehint, -1);
}
static void
pyepoll_dealloc(pyEpoll_Object *self)
{
- (void)pyepoll_internal_close(self);
- Py_TYPE(self)->tp_free(self);
+ (void)pyepoll_internal_close(self);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject*
pyepoll_close(pyEpoll_Object *self)
{
- errno = pyepoll_internal_close(self);
- if (errno < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_RETURN_NONE;
+ errno = pyepoll_internal_close(self);
+ if (errno < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(pyepoll_close_doc,
@@ -810,18 +810,18 @@ object will raise an exception.");
static PyObject*
pyepoll_get_closed(pyEpoll_Object *self)
{
- if (self->epfd < 0)
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
+ if (self->epfd < 0)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
}
static PyObject*
pyepoll_fileno(pyEpoll_Object *self)
{
- if (self->epfd < 0)
- return pyepoll_err_closed();
- return PyInt_FromLong(self->epfd);
+ if (self->epfd < 0)
+ return pyepoll_err_closed();
+ return PyInt_FromLong(self->epfd);
}
PyDoc_STRVAR(pyepoll_fileno_doc,
@@ -832,12 +832,12 @@ Return the epoll control file descriptor.");
static PyObject*
pyepoll_fromfd(PyObject *cls, PyObject *args)
{
- SOCKET fd;
+ SOCKET fd;
- if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
+ return NULL;
- return newPyEpoll_Object((PyTypeObject*)cls, -1, fd);
+ return newPyEpoll_Object((PyTypeObject*)cls, -1, fd);
}
PyDoc_STRVAR(pyepoll_fromfd_doc,
@@ -848,65 +848,65 @@ Create an epoll object from a given control fd.");
static PyObject *
pyepoll_internal_ctl(int epfd, int op, PyObject *pfd, unsigned int events)
{
- struct epoll_event ev;
- int result;
- int fd;
-
- if (epfd < 0)
- return pyepoll_err_closed();
-
- fd = PyObject_AsFileDescriptor(pfd);
- if (fd == -1) {
- return NULL;
- }
-
- switch(op) {
- case EPOLL_CTL_ADD:
- case EPOLL_CTL_MOD:
- ev.events = events;
- ev.data.fd = fd;
- Py_BEGIN_ALLOW_THREADS
- result = epoll_ctl(epfd, op, fd, &ev);
- Py_END_ALLOW_THREADS
- break;
- case EPOLL_CTL_DEL:
- /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
- * operation required a non-NULL pointer in event, even
- * though this argument is ignored. */
- Py_BEGIN_ALLOW_THREADS
- result = epoll_ctl(epfd, op, fd, &ev);
- if (errno == EBADF) {
- /* fd already closed */
- result = 0;
- errno = 0;
- }
- Py_END_ALLOW_THREADS
- break;
- default:
- result = -1;
- errno = EINVAL;
- }
-
- if (result < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_RETURN_NONE;
+ struct epoll_event ev;
+ int result;
+ int fd;
+
+ if (epfd < 0)
+ return pyepoll_err_closed();
+
+ fd = PyObject_AsFileDescriptor(pfd);
+ if (fd == -1) {
+ return NULL;
+ }
+
+ switch(op) {
+ case EPOLL_CTL_ADD:
+ case EPOLL_CTL_MOD:
+ ev.events = events;
+ ev.data.fd = fd;
+ Py_BEGIN_ALLOW_THREADS
+ result = epoll_ctl(epfd, op, fd, &ev);
+ Py_END_ALLOW_THREADS
+ break;
+ case EPOLL_CTL_DEL:
+ /* In kernel versions before 2.6.9, the EPOLL_CTL_DEL
+ * operation required a non-NULL pointer in event, even
+ * though this argument is ignored. */
+ Py_BEGIN_ALLOW_THREADS
+ result = epoll_ctl(epfd, op, fd, &ev);
+ if (errno == EBADF) {
+ /* fd already closed */
+ result = 0;
+ errno = 0;
+ }
+ Py_END_ALLOW_THREADS
+ break;
+ default:
+ result = -1;
+ errno = EINVAL;
+ }
+
+ if (result < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
static PyObject *
pyepoll_register(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
- static char *kwlist[] = {"fd", "eventmask", NULL};
+ PyObject *pfd;
+ unsigned int events = EPOLLIN | EPOLLOUT | EPOLLPRI;
+ static char *kwlist[] = {"fd", "eventmask", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
- &pfd, &events)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|I:register", kwlist,
+ &pfd, &events)) {
+ return NULL;
+ }
- return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
+ return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_ADD, pfd, events);
}
PyDoc_STRVAR(pyepoll_register_doc,
@@ -923,16 +923,16 @@ The epoll interface supports all file descriptors that support poll.");
static PyObject *
pyepoll_modify(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- unsigned int events;
- static char *kwlist[] = {"fd", "eventmask", NULL};
+ PyObject *pfd;
+ unsigned int events;
+ static char *kwlist[] = {"fd", "eventmask", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
- &pfd, &events)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "OI:modify", kwlist,
+ &pfd, &events)) {
+ return NULL;
+ }
- return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
+ return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_MOD, pfd, events);
}
PyDoc_STRVAR(pyepoll_modify_doc,
@@ -944,15 +944,15 @@ events is a bit set composed of the various EPOLL constants");
static PyObject *
pyepoll_unregister(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- static char *kwlist[] = {"fd", NULL};
+ PyObject *pfd;
+ static char *kwlist[] = {"fd", NULL};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
- &pfd)) {
- return NULL;
- }
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O:unregister", kwlist,
+ &pfd)) {
+ return NULL;
+ }
- return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
+ return pyepoll_internal_ctl(self->epfd, EPOLL_CTL_DEL, pfd, 0);
}
PyDoc_STRVAR(pyepoll_unregister_doc,
@@ -963,76 +963,76 @@ fd is the target file descriptor of the operation.");
static PyObject *
pyepoll_poll(pyEpoll_Object *self, PyObject *args, PyObject *kwds)
{
- double dtimeout = -1.;
- int timeout;
- int maxevents = -1;
- int nfds, i;
- PyObject *elist = NULL, *etuple = NULL;
- struct epoll_event *evs = NULL;
- static char *kwlist[] = {"timeout", "maxevents", NULL};
-
- if (self->epfd < 0)
- return pyepoll_err_closed();
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
- &dtimeout, &maxevents)) {
- return NULL;
- }
-
- if (dtimeout < 0) {
- timeout = -1;
- }
- else if (dtimeout * 1000.0 > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout is too large");
- return NULL;
- }
- else {
- timeout = (int)(dtimeout * 1000.0);
- }
-
- if (maxevents == -1) {
- maxevents = FD_SETSIZE-1;
- }
- else if (maxevents < 1) {
- PyErr_Format(PyExc_ValueError,
- "maxevents must be greater than 0, got %d",
- maxevents);
- return NULL;
- }
-
- evs = PyMem_New(struct epoll_event, maxevents);
- if (evs == NULL) {
- Py_DECREF(self);
- PyErr_NoMemory();
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
- Py_END_ALLOW_THREADS
- if (nfds < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- goto error;
- }
-
- elist = PyList_New(nfds);
- if (elist == NULL) {
- goto error;
- }
-
- for (i = 0; i < nfds; i++) {
- etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
- if (etuple == NULL) {
- Py_CLEAR(elist);
- goto error;
- }
- PyList_SET_ITEM(elist, i, etuple);
- }
+ double dtimeout = -1.;
+ int timeout;
+ int maxevents = -1;
+ int nfds, i;
+ PyObject *elist = NULL, *etuple = NULL;
+ struct epoll_event *evs = NULL;
+ static char *kwlist[] = {"timeout", "maxevents", NULL};
+
+ if (self->epfd < 0)
+ return pyepoll_err_closed();
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|di:poll", kwlist,
+ &dtimeout, &maxevents)) {
+ return NULL;
+ }
+
+ if (dtimeout < 0) {
+ timeout = -1;
+ }
+ else if (dtimeout * 1000.0 > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout is too large");
+ return NULL;
+ }
+ else {
+ timeout = (int)(dtimeout * 1000.0);
+ }
+
+ if (maxevents == -1) {
+ maxevents = FD_SETSIZE-1;
+ }
+ else if (maxevents < 1) {
+ PyErr_Format(PyExc_ValueError,
+ "maxevents must be greater than 0, got %d",
+ maxevents);
+ return NULL;
+ }
+
+ evs = PyMem_New(struct epoll_event, maxevents);
+ if (evs == NULL) {
+ Py_DECREF(self);
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ nfds = epoll_wait(self->epfd, evs, maxevents, timeout);
+ Py_END_ALLOW_THREADS
+ if (nfds < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ goto error;
+ }
+
+ elist = PyList_New(nfds);
+ if (elist == NULL) {
+ goto error;
+ }
+
+ for (i = 0; i < nfds; i++) {
+ etuple = Py_BuildValue("iI", evs[i].data.fd, evs[i].events);
+ if (etuple == NULL) {
+ Py_CLEAR(elist);
+ goto error;
+ }
+ PyList_SET_ITEM(elist, i, etuple);
+ }
error:
- PyMem_Free(evs);
- return elist;
+ PyMem_Free(evs);
+ return elist;
}
PyDoc_STRVAR(pyepoll_poll_doc,
@@ -1043,27 +1043,27 @@ in seconds (as float). -1 makes poll wait indefinitely.\n\
Up to maxevents are returned to the caller.");
static PyMethodDef pyepoll_methods[] = {
- {"fromfd", (PyCFunction)pyepoll_fromfd,
- METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
- {"close", (PyCFunction)pyepoll_close, METH_NOARGS,
- pyepoll_close_doc},
- {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS,
- pyepoll_fileno_doc},
- {"modify", (PyCFunction)pyepoll_modify,
- METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc},
- {"register", (PyCFunction)pyepoll_register,
- METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc},
- {"unregister", (PyCFunction)pyepoll_unregister,
- METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc},
- {"poll", (PyCFunction)pyepoll_poll,
- METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc},
- {NULL, NULL},
+ {"fromfd", (PyCFunction)pyepoll_fromfd,
+ METH_VARARGS | METH_CLASS, pyepoll_fromfd_doc},
+ {"close", (PyCFunction)pyepoll_close, METH_NOARGS,
+ pyepoll_close_doc},
+ {"fileno", (PyCFunction)pyepoll_fileno, METH_NOARGS,
+ pyepoll_fileno_doc},
+ {"modify", (PyCFunction)pyepoll_modify,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_modify_doc},
+ {"register", (PyCFunction)pyepoll_register,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_register_doc},
+ {"unregister", (PyCFunction)pyepoll_unregister,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_unregister_doc},
+ {"poll", (PyCFunction)pyepoll_poll,
+ METH_VARARGS | METH_KEYWORDS, pyepoll_poll_doc},
+ {NULL, NULL},
};
static PyGetSetDef pyepoll_getsetlist[] = {
- {"closed", (getter)pyepoll_get_closed, NULL,
- "True if the epoll handler is closed"},
- {0},
+ {"closed", (getter)pyepoll_get_closed, NULL,
+ "True if the epoll handler is closed"},
+ {0},
};
PyDoc_STRVAR(pyepoll_doc,
@@ -1076,45 +1076,45 @@ sizehint is used to optimize internal data structures. It doesn't limit\n\
the maximum number of monitored events.");
static PyTypeObject pyEpoll_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.epoll", /* tp_name */
- sizeof(pyEpoll_Object), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)pyepoll_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 */
- pyepoll_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- pyepoll_methods, /* tp_methods */
- 0, /* tp_members */
- pyepoll_getsetlist, /* 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 */
- pyepoll_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.epoll", /* tp_name */
+ sizeof(pyEpoll_Object), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)pyepoll_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 */
+ pyepoll_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ pyepoll_methods, /* tp_methods */
+ 0, /* tp_members */
+ pyepoll_getsetlist, /* 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 */
+ pyepoll_new, /* tp_new */
+ 0, /* tp_free */
};
#endif /* HAVE_EPOLL */
@@ -1169,8 +1169,8 @@ of. You could also set up a dictionary on the python side to store a\n\
udata->object mapping.");
typedef struct {
- PyObject_HEAD
- struct kevent e;
+ PyObject_HEAD
+ struct kevent e;
} kqueue_event_Object;
static PyTypeObject kqueue_event_Type;
@@ -1178,8 +1178,8 @@ static PyTypeObject kqueue_event_Type;
#define kqueue_event_Check(op) (PyObject_TypeCheck((op), &kqueue_event_Type))
typedef struct {
- PyObject_HEAD
- SOCKET kqfd; /* kqueue control fd */
+ PyObject_HEAD
+ SOCKET kqfd; /* kqueue control fd */
} kqueue_queue_Object;
static PyTypeObject kqueue_queue_Type;
@@ -1217,13 +1217,13 @@ static PyTypeObject kqueue_queue_Type;
#define KQ_OFF(x) offsetof(kqueue_event_Object, x)
static struct PyMemberDef kqueue_event_members[] = {
- {"ident", T_UINTPTRT, KQ_OFF(e.ident)},
- {"filter", T_SHORT, KQ_OFF(e.filter)},
- {"flags", T_USHORT, KQ_OFF(e.flags)},
- {"fflags", T_UINT, KQ_OFF(e.fflags)},
- {"data", T_INTPTRT, KQ_OFF(e.data)},
- {"udata", T_UINTPTRT, KQ_OFF(e.udata)},
- {NULL} /* Sentinel */
+ {"ident", T_UINTPTRT, KQ_OFF(e.ident)},
+ {"filter", T_SHORT, KQ_OFF(e.filter)},
+ {"flags", T_USHORT, KQ_OFF(e.flags)},
+ {"fflags", T_UINT, KQ_OFF(e.fflags)},
+ {"data", T_INTPTRT, KQ_OFF(e.data)},
+ {"udata", T_UINTPTRT, KQ_OFF(e.udata)},
+ {NULL} /* Sentinel */
};
#undef KQ_OFF
@@ -1231,214 +1231,214 @@ static PyObject *
kqueue_event_repr(kqueue_event_Object *s)
{
- char buf[1024];
- PyOS_snprintf(
- buf, sizeof(buf),
- "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
- "data=0x%zd udata=%p>",
- (size_t)(s->e.ident), s->e.filter, s->e.flags,
- s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);
- return PyString_FromString(buf);
+ char buf[1024];
+ PyOS_snprintf(
+ buf, sizeof(buf),
+ "<select.kevent ident=%zu filter=%d flags=0x%x fflags=0x%x "
+ "data=0x%zd udata=%p>",
+ (size_t)(s->e.ident), s->e.filter, s->e.flags,
+ s->e.fflags, (Py_ssize_t)(s->e.data), s->e.udata);
+ return PyString_FromString(buf);
}
static int
kqueue_event_init(kqueue_event_Object *self, PyObject *args, PyObject *kwds)
{
- PyObject *pfd;
- static char *kwlist[] = {"ident", "filter", "flags", "fflags",
- "data", "udata", NULL};
- static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";
-
- EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
- &pfd, &(self->e.filter), &(self->e.flags),
- &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
- return -1;
- }
-
- if (PyLong_Check(pfd)) {
- self->e.ident = PyLong_AsUintptr_t(pfd);
- }
- else {
- self->e.ident = PyObject_AsFileDescriptor(pfd);
- }
- if (PyErr_Occurred()) {
- return -1;
- }
- return 0;
+ PyObject *pfd;
+ static char *kwlist[] = {"ident", "filter", "flags", "fflags",
+ "data", "udata", NULL};
+ static char *fmt = "O|hhi" INTPTRT_FMT_UNIT UINTPTRT_FMT_UNIT ":kevent";
+
+ EV_SET(&(self->e), 0, EVFILT_READ, EV_ADD, 0, 0, 0); /* defaults */
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, fmt, kwlist,
+ &pfd, &(self->e.filter), &(self->e.flags),
+ &(self->e.fflags), &(self->e.data), &(self->e.udata))) {
+ return -1;
+ }
+
+ if (PyLong_Check(pfd)) {
+ self->e.ident = PyLong_AsUintptr_t(pfd);
+ }
+ else {
+ self->e.ident = PyObject_AsFileDescriptor(pfd);
+ }
+ if (PyErr_Occurred()) {
+ return -1;
+ }
+ return 0;
}
static PyObject *
kqueue_event_richcompare(kqueue_event_Object *s, kqueue_event_Object *o,
- int op)
+ int op)
{
- Py_intptr_t result = 0;
-
- if (!kqueue_event_Check(o)) {
- if (op == Py_EQ || op == Py_NE) {
- PyObject *res = op == Py_EQ ? Py_False : Py_True;
- Py_INCREF(res);
- return res;
- }
- PyErr_Format(PyExc_TypeError,
- "can't compare %.200s to %.200s",
- Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);
- return NULL;
- }
- if (((result = s->e.ident - o->e.ident) == 0) &&
- ((result = s->e.filter - o->e.filter) == 0) &&
- ((result = s->e.flags - o->e.flags) == 0) &&
- ((result = s->e.fflags - o->e.fflags) == 0) &&
- ((result = s->e.data - o->e.data) == 0) &&
- ((result = s->e.udata - o->e.udata) == 0)
- ) {
- result = 0;
- }
-
- switch (op) {
- case Py_EQ:
- result = (result == 0);
- break;
- case Py_NE:
- result = (result != 0);
- break;
- case Py_LE:
- result = (result <= 0);
- break;
- case Py_GE:
- result = (result >= 0);
- break;
- case Py_LT:
- result = (result < 0);
- break;
- case Py_GT:
- result = (result > 0);
- break;
- }
- return PyBool_FromLong((long)result);
+ Py_intptr_t result = 0;
+
+ if (!kqueue_event_Check(o)) {
+ if (op == Py_EQ || op == Py_NE) {
+ PyObject *res = op == Py_EQ ? Py_False : Py_True;
+ Py_INCREF(res);
+ return res;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "can't compare %.200s to %.200s",
+ Py_TYPE(s)->tp_name, Py_TYPE(o)->tp_name);
+ return NULL;
+ }
+ if (((result = s->e.ident - o->e.ident) == 0) &&
+ ((result = s->e.filter - o->e.filter) == 0) &&
+ ((result = s->e.flags - o->e.flags) == 0) &&
+ ((result = s->e.fflags - o->e.fflags) == 0) &&
+ ((result = s->e.data - o->e.data) == 0) &&
+ ((result = s->e.udata - o->e.udata) == 0)
+ ) {
+ result = 0;
+ }
+
+ switch (op) {
+ case Py_EQ:
+ result = (result == 0);
+ break;
+ case Py_NE:
+ result = (result != 0);
+ break;
+ case Py_LE:
+ result = (result <= 0);
+ break;
+ case Py_GE:
+ result = (result >= 0);
+ break;
+ case Py_LT:
+ result = (result < 0);
+ break;
+ case Py_GT:
+ result = (result > 0);
+ break;
+ }
+ return PyBool_FromLong((long)result);
}
static PyTypeObject kqueue_event_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.kevent", /* tp_name */
- sizeof(kqueue_event_Object), /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)kqueue_event_repr, /* 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, /* tp_flags */
- kqueue_event_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- kqueue_event_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)kqueue_event_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.kevent", /* tp_name */
+ sizeof(kqueue_event_Object), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)kqueue_event_repr, /* 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, /* tp_flags */
+ kqueue_event_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)kqueue_event_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ kqueue_event_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)kqueue_event_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
+ 0, /* tp_free */
};
static PyObject *
kqueue_queue_err_closed(void)
{
- PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "I/O operation on closed kqueue fd");
+ return NULL;
}
static int
kqueue_queue_internal_close(kqueue_queue_Object *self)
{
- int save_errno = 0;
- if (self->kqfd >= 0) {
- int kqfd = self->kqfd;
- self->kqfd = -1;
- Py_BEGIN_ALLOW_THREADS
- if (close(kqfd) < 0)
- save_errno = errno;
- Py_END_ALLOW_THREADS
- }
- return save_errno;
+ int save_errno = 0;
+ if (self->kqfd >= 0) {
+ int kqfd = self->kqfd;
+ self->kqfd = -1;
+ Py_BEGIN_ALLOW_THREADS
+ if (close(kqfd) < 0)
+ save_errno = errno;
+ Py_END_ALLOW_THREADS
+ }
+ return save_errno;
}
static PyObject *
newKqueue_Object(PyTypeObject *type, SOCKET fd)
{
- kqueue_queue_Object *self;
- assert(type != NULL && type->tp_alloc != NULL);
- self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
- if (self == NULL) {
- return NULL;
- }
-
- if (fd == -1) {
- Py_BEGIN_ALLOW_THREADS
- self->kqfd = kqueue();
- Py_END_ALLOW_THREADS
- }
- else {
- self->kqfd = fd;
- }
- if (self->kqfd < 0) {
- Py_DECREF(self);
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return (PyObject *)self;
+ kqueue_queue_Object *self;
+ assert(type != NULL && type->tp_alloc != NULL);
+ self = (kqueue_queue_Object *) type->tp_alloc(type, 0);
+ if (self == NULL) {
+ return NULL;
+ }
+
+ if (fd == -1) {
+ Py_BEGIN_ALLOW_THREADS
+ self->kqfd = kqueue();
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ self->kqfd = fd;
+ }
+ if (self->kqfd < 0) {
+ Py_DECREF(self);
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return (PyObject *)self;
}
static PyObject *
kqueue_queue_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- if ((args != NULL && PyObject_Size(args)) ||
- (kwds != NULL && PyObject_Size(kwds))) {
- PyErr_SetString(PyExc_ValueError,
- "select.kqueue doesn't accept arguments");
- return NULL;
- }
+ if ((args != NULL && PyObject_Size(args)) ||
+ (kwds != NULL && PyObject_Size(kwds))) {
+ PyErr_SetString(PyExc_ValueError,
+ "select.kqueue doesn't accept arguments");
+ return NULL;
+ }
- return newKqueue_Object(type, -1);
+ return newKqueue_Object(type, -1);
}
static void
kqueue_queue_dealloc(kqueue_queue_Object *self)
{
- kqueue_queue_internal_close(self);
- Py_TYPE(self)->tp_free(self);
+ kqueue_queue_internal_close(self);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject*
kqueue_queue_close(kqueue_queue_Object *self)
{
- errno = kqueue_queue_internal_close(self);
- if (errno < 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- Py_RETURN_NONE;
+ errno = kqueue_queue_internal_close(self);
+ if (errno < 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(kqueue_queue_close_doc,
@@ -1450,18 +1450,18 @@ object will raise an exception.");
static PyObject*
kqueue_queue_get_closed(kqueue_queue_Object *self)
{
- if (self->kqfd < 0)
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
+ if (self->kqfd < 0)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
}
static PyObject*
kqueue_queue_fileno(kqueue_queue_Object *self)
{
- if (self->kqfd < 0)
- return kqueue_queue_err_closed();
- return PyInt_FromLong(self->kqfd);
+ if (self->kqfd < 0)
+ return kqueue_queue_err_closed();
+ return PyInt_FromLong(self->kqfd);
}
PyDoc_STRVAR(kqueue_queue_fileno_doc,
@@ -1472,12 +1472,12 @@ Return the kqueue control file descriptor.");
static PyObject*
kqueue_queue_fromfd(PyObject *cls, PyObject *args)
{
- SOCKET fd;
+ SOCKET fd;
- if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:fromfd", &fd))
+ return NULL;
- return newKqueue_Object((PyTypeObject*)cls, fd);
+ return newKqueue_Object((PyTypeObject*)cls, fd);
}
PyDoc_STRVAR(kqueue_queue_fromfd_doc,
@@ -1488,144 +1488,144 @@ Create a kqueue object from a given control fd.");
static PyObject *
kqueue_queue_control(kqueue_queue_Object *self, PyObject *args)
{
- int nevents = 0;
- int gotevents = 0;
- int nchanges = 0;
- int i = 0;
- PyObject *otimeout = NULL;
- PyObject *ch = NULL;
- PyObject *it = NULL, *ei = NULL;
- PyObject *result = NULL;
- struct kevent *evl = NULL;
- struct kevent *chl = NULL;
- struct timespec timeoutspec;
- struct timespec *ptimeoutspec;
-
- if (self->kqfd < 0)
- return kqueue_queue_err_closed();
-
- if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
- return NULL;
-
- if (nevents < 0) {
- PyErr_Format(PyExc_ValueError,
- "Length of eventlist must be 0 or positive, got %d",
- nevents);
- return NULL;
- }
-
- if (otimeout == Py_None || otimeout == NULL) {
- ptimeoutspec = NULL;
- }
- else if (PyNumber_Check(otimeout)) {
- double timeout;
- long seconds;
-
- timeout = PyFloat_AsDouble(otimeout);
- if (timeout == -1 && PyErr_Occurred())
- return NULL;
- if (timeout > (double)LONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "timeout period too long");
- return NULL;
- }
- if (timeout < 0) {
- PyErr_SetString(PyExc_ValueError,
- "timeout must be positive or None");
- return NULL;
- }
-
- seconds = (long)timeout;
- timeout = timeout - (double)seconds;
- timeoutspec.tv_sec = seconds;
- timeoutspec.tv_nsec = (long)(timeout * 1E9);
- ptimeoutspec = &timeoutspec;
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "timeout argument must be an number "
- "or None, got %.200s",
- Py_TYPE(otimeout)->tp_name);
- return NULL;
- }
-
- if (ch != NULL && ch != Py_None) {
- it = PyObject_GetIter(ch);
- if (it == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "changelist is not iterable");
- return NULL;
- }
- nchanges = PyObject_Size(ch);
- if (nchanges < 0) {
- goto error;
- }
-
- chl = PyMem_New(struct kevent, nchanges);
- if (chl == NULL) {
- PyErr_NoMemory();
- goto error;
- }
- i = 0;
- while ((ei = PyIter_Next(it)) != NULL) {
- if (!kqueue_event_Check(ei)) {
- Py_DECREF(ei);
- PyErr_SetString(PyExc_TypeError,
- "changelist must be an iterable of "
- "select.kevent objects");
- goto error;
- } else {
- chl[i++] = ((kqueue_event_Object *)ei)->e;
- }
- Py_DECREF(ei);
- }
- }
- Py_CLEAR(it);
-
- /* event list */
- if (nevents) {
- evl = PyMem_New(struct kevent, nevents);
- if (evl == NULL) {
- PyErr_NoMemory();
- goto error;
- }
- }
-
- Py_BEGIN_ALLOW_THREADS
- gotevents = kevent(self->kqfd, chl, nchanges,
- evl, nevents, ptimeoutspec);
- Py_END_ALLOW_THREADS
-
- if (gotevents == -1) {
- PyErr_SetFromErrno(PyExc_OSError);
- goto error;
- }
-
- result = PyList_New(gotevents);
- if (result == NULL) {
- goto error;
- }
-
- for (i = 0; i < gotevents; i++) {
- kqueue_event_Object *ch;
-
- ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
- if (ch == NULL) {
- goto error;
- }
- ch->e = evl[i];
- PyList_SET_ITEM(result, i, (PyObject *)ch);
- }
- PyMem_Free(chl);
- PyMem_Free(evl);
- return result;
+ int nevents = 0;
+ int gotevents = 0;
+ int nchanges = 0;
+ int i = 0;
+ PyObject *otimeout = NULL;
+ PyObject *ch = NULL;
+ PyObject *it = NULL, *ei = NULL;
+ PyObject *result = NULL;
+ struct kevent *evl = NULL;
+ struct kevent *chl = NULL;
+ struct timespec timeoutspec;
+ struct timespec *ptimeoutspec;
+
+ if (self->kqfd < 0)
+ return kqueue_queue_err_closed();
+
+ if (!PyArg_ParseTuple(args, "Oi|O:control", &ch, &nevents, &otimeout))
+ return NULL;
+
+ if (nevents < 0) {
+ PyErr_Format(PyExc_ValueError,
+ "Length of eventlist must be 0 or positive, got %d",
+ nevents);
+ return NULL;
+ }
+
+ if (otimeout == Py_None || otimeout == NULL) {
+ ptimeoutspec = NULL;
+ }
+ else if (PyNumber_Check(otimeout)) {
+ double timeout;
+ long seconds;
+
+ timeout = PyFloat_AsDouble(otimeout);
+ if (timeout == -1 && PyErr_Occurred())
+ return NULL;
+ if (timeout > (double)LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "timeout period too long");
+ return NULL;
+ }
+ if (timeout < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "timeout must be positive or None");
+ return NULL;
+ }
+
+ seconds = (long)timeout;
+ timeout = timeout - (double)seconds;
+ timeoutspec.tv_sec = seconds;
+ timeoutspec.tv_nsec = (long)(timeout * 1E9);
+ ptimeoutspec = &timeoutspec;
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "timeout argument must be an number "
+ "or None, got %.200s",
+ Py_TYPE(otimeout)->tp_name);
+ return NULL;
+ }
+
+ if (ch != NULL && ch != Py_None) {
+ it = PyObject_GetIter(ch);
+ if (it == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "changelist is not iterable");
+ return NULL;
+ }
+ nchanges = PyObject_Size(ch);
+ if (nchanges < 0) {
+ goto error;
+ }
+
+ chl = PyMem_New(struct kevent, nchanges);
+ if (chl == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+ i = 0;
+ while ((ei = PyIter_Next(it)) != NULL) {
+ if (!kqueue_event_Check(ei)) {
+ Py_DECREF(ei);
+ PyErr_SetString(PyExc_TypeError,
+ "changelist must be an iterable of "
+ "select.kevent objects");
+ goto error;
+ } else {
+ chl[i++] = ((kqueue_event_Object *)ei)->e;
+ }
+ Py_DECREF(ei);
+ }
+ }
+ Py_CLEAR(it);
+
+ /* event list */
+ if (nevents) {
+ evl = PyMem_New(struct kevent, nevents);
+ if (evl == NULL) {
+ PyErr_NoMemory();
+ goto error;
+ }
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ gotevents = kevent(self->kqfd, chl, nchanges,
+ evl, nevents, ptimeoutspec);
+ Py_END_ALLOW_THREADS
+
+ if (gotevents == -1) {
+ PyErr_SetFromErrno(PyExc_OSError);
+ goto error;
+ }
+
+ result = PyList_New(gotevents);
+ if (result == NULL) {
+ goto error;
+ }
+
+ for (i = 0; i < gotevents; i++) {
+ kqueue_event_Object *ch;
+
+ ch = PyObject_New(kqueue_event_Object, &kqueue_event_Type);
+ if (ch == NULL) {
+ goto error;
+ }
+ ch->e = evl[i];
+ PyList_SET_ITEM(result, i, (PyObject *)ch);
+ }
+ PyMem_Free(chl);
+ PyMem_Free(evl);
+ return result;
error:
- PyMem_Free(chl);
- PyMem_Free(evl);
- Py_XDECREF(result);
- Py_XDECREF(it);
- return NULL;
+ PyMem_Free(chl);
+ PyMem_Free(evl);
+ Py_XDECREF(result);
+ Py_XDECREF(it);
+ return NULL;
}
PyDoc_STRVAR(kqueue_queue_control_doc,
@@ -1641,21 +1641,21 @@ Calls the kernel kevent function.\n\
static PyMethodDef kqueue_queue_methods[] = {
- {"fromfd", (PyCFunction)kqueue_queue_fromfd,
- METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
- {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS,
- kqueue_queue_close_doc},
- {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS,
- kqueue_queue_fileno_doc},
- {"control", (PyCFunction)kqueue_queue_control,
- METH_VARARGS , kqueue_queue_control_doc},
- {NULL, NULL},
+ {"fromfd", (PyCFunction)kqueue_queue_fromfd,
+ METH_VARARGS | METH_CLASS, kqueue_queue_fromfd_doc},
+ {"close", (PyCFunction)kqueue_queue_close, METH_NOARGS,
+ kqueue_queue_close_doc},
+ {"fileno", (PyCFunction)kqueue_queue_fileno, METH_NOARGS,
+ kqueue_queue_fileno_doc},
+ {"control", (PyCFunction)kqueue_queue_control,
+ METH_VARARGS , kqueue_queue_control_doc},
+ {NULL, NULL},
};
static PyGetSetDef kqueue_queue_getsetlist[] = {
- {"closed", (getter)kqueue_queue_get_closed, NULL,
- "True if the kqueue handler is closed"},
- {0},
+ {"closed", (getter)kqueue_queue_get_closed, NULL,
+ "True if the kqueue handler is closed"},
+ {0},
};
PyDoc_STRVAR(kqueue_queue_doc,
@@ -1674,45 +1674,45 @@ To stop listening:\n\
>>> kq.control([kevent(sock, KQ_FILTER_WRITE, KQ_EV_DELETE)], 0)");
static PyTypeObject kqueue_queue_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "select.kqueue", /* tp_name */
- sizeof(kqueue_queue_Object), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)kqueue_queue_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, /* tp_flags */
- kqueue_queue_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- kqueue_queue_methods, /* tp_methods */
- 0, /* tp_members */
- kqueue_queue_getsetlist, /* 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 */
- kqueue_queue_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "select.kqueue", /* tp_name */
+ sizeof(kqueue_queue_Object), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)kqueue_queue_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, /* tp_flags */
+ kqueue_queue_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ kqueue_queue_methods, /* tp_methods */
+ 0, /* tp_members */
+ kqueue_queue_getsetlist, /* 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 */
+ kqueue_queue_new, /* tp_new */
+ 0, /* tp_free */
};
#endif /* HAVE_KQUEUE */
@@ -1743,11 +1743,11 @@ On Windows and OpenVMS, only sockets are supported; on Unix, all file\n\
descriptors can be used.");
static PyMethodDef select_methods[] = {
- {"select", select_select, METH_VARARGS, select_doc},
+ {"select", select_select, METH_VARARGS, select_doc},
#ifdef HAVE_POLL
- {"poll", select_poll, METH_NOARGS, poll_doc},
+ {"poll", select_poll, METH_NOARGS, poll_doc},
#endif /* HAVE_POLL */
- {0, 0}, /* sentinel */
+ {0, 0}, /* sentinel */
};
PyDoc_STRVAR(module_doc,
@@ -1759,150 +1759,150 @@ On Windows and OpenVMS, only sockets are supported; on Unix, all file descriptor
PyMODINIT_FUNC
initselect(void)
{
- PyObject *m;
- m = Py_InitModule3("select", select_methods, module_doc);
- if (m == NULL)
- return;
+ PyObject *m;
+ m = Py_InitModule3("select", select_methods, module_doc);
+ if (m == NULL)
+ return;
- SelectError = PyErr_NewException("select.error", NULL, NULL);
- Py_INCREF(SelectError);
- PyModule_AddObject(m, "error", SelectError);
+ SelectError = PyErr_NewException("select.error", NULL, NULL);
+ Py_INCREF(SelectError);
+ PyModule_AddObject(m, "error", SelectError);
#ifdef PIPE_BUF
- PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
+ PyModule_AddIntConstant(m, "PIPE_BUF", PIPE_BUF);
#endif
#if defined(HAVE_POLL)
#ifdef __APPLE__
- if (select_have_broken_poll()) {
- if (PyObject_DelAttrString(m, "poll") == -1) {
- PyErr_Clear();
- }
- } else {
+ if (select_have_broken_poll()) {
+ if (PyObject_DelAttrString(m, "poll") == -1) {
+ PyErr_Clear();
+ }
+ } else {
#else
- {
+ {
#endif
- Py_TYPE(&poll_Type) = &PyType_Type;
- PyModule_AddIntConstant(m, "POLLIN", POLLIN);
- PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
- PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
- PyModule_AddIntConstant(m, "POLLERR", POLLERR);
- PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
- PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
+ Py_TYPE(&poll_Type) = &PyType_Type;
+ PyModule_AddIntConstant(m, "POLLIN", POLLIN);
+ PyModule_AddIntConstant(m, "POLLPRI", POLLPRI);
+ PyModule_AddIntConstant(m, "POLLOUT", POLLOUT);
+ PyModule_AddIntConstant(m, "POLLERR", POLLERR);
+ PyModule_AddIntConstant(m, "POLLHUP", POLLHUP);
+ PyModule_AddIntConstant(m, "POLLNVAL", POLLNVAL);
#ifdef POLLRDNORM
- PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
+ PyModule_AddIntConstant(m, "POLLRDNORM", POLLRDNORM);
#endif
#ifdef POLLRDBAND
- PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
+ PyModule_AddIntConstant(m, "POLLRDBAND", POLLRDBAND);
#endif
#ifdef POLLWRNORM
- PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
+ PyModule_AddIntConstant(m, "POLLWRNORM", POLLWRNORM);
#endif
#ifdef POLLWRBAND
- PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
+ PyModule_AddIntConstant(m, "POLLWRBAND", POLLWRBAND);
#endif
#ifdef POLLMSG
- PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
+ PyModule_AddIntConstant(m, "POLLMSG", POLLMSG);
#endif
- }
+ }
#endif /* HAVE_POLL */
#ifdef HAVE_EPOLL
- Py_TYPE(&pyEpoll_Type) = &PyType_Type;
- if (PyType_Ready(&pyEpoll_Type) < 0)
- return;
-
- Py_INCREF(&pyEpoll_Type);
- PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
-
- PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
- PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
- PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
- PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
- PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
- PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
+ Py_TYPE(&pyEpoll_Type) = &PyType_Type;
+ if (PyType_Ready(&pyEpoll_Type) < 0)
+ return;
+
+ Py_INCREF(&pyEpoll_Type);
+ PyModule_AddObject(m, "epoll", (PyObject *) &pyEpoll_Type);
+
+ PyModule_AddIntConstant(m, "EPOLLIN", EPOLLIN);
+ PyModule_AddIntConstant(m, "EPOLLOUT", EPOLLOUT);
+ PyModule_AddIntConstant(m, "EPOLLPRI", EPOLLPRI);
+ PyModule_AddIntConstant(m, "EPOLLERR", EPOLLERR);
+ PyModule_AddIntConstant(m, "EPOLLHUP", EPOLLHUP);
+ PyModule_AddIntConstant(m, "EPOLLET", EPOLLET);
#ifdef EPOLLONESHOT
- /* Kernel 2.6.2+ */
- PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
+ /* Kernel 2.6.2+ */
+ PyModule_AddIntConstant(m, "EPOLLONESHOT", EPOLLONESHOT);
#endif
- /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
- PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
- PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
- PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
- PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
- PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
+ /* PyModule_AddIntConstant(m, "EPOLL_RDHUP", EPOLLRDHUP); */
+ PyModule_AddIntConstant(m, "EPOLLRDNORM", EPOLLRDNORM);
+ PyModule_AddIntConstant(m, "EPOLLRDBAND", EPOLLRDBAND);
+ PyModule_AddIntConstant(m, "EPOLLWRNORM", EPOLLWRNORM);
+ PyModule_AddIntConstant(m, "EPOLLWRBAND", EPOLLWRBAND);
+ PyModule_AddIntConstant(m, "EPOLLMSG", EPOLLMSG);
#endif /* HAVE_EPOLL */
#ifdef HAVE_KQUEUE
- kqueue_event_Type.tp_new = PyType_GenericNew;
- Py_TYPE(&kqueue_event_Type) = &PyType_Type;
- if(PyType_Ready(&kqueue_event_Type) < 0)
- return;
-
- Py_INCREF(&kqueue_event_Type);
- PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
-
- Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
- if(PyType_Ready(&kqueue_queue_Type) < 0)
- return;
- Py_INCREF(&kqueue_queue_Type);
- PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
-
- /* event filters */
- PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
- PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
- PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
- PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
- PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
+ kqueue_event_Type.tp_new = PyType_GenericNew;
+ Py_TYPE(&kqueue_event_Type) = &PyType_Type;
+ if(PyType_Ready(&kqueue_event_Type) < 0)
+ return;
+
+ Py_INCREF(&kqueue_event_Type);
+ PyModule_AddObject(m, "kevent", (PyObject *)&kqueue_event_Type);
+
+ Py_TYPE(&kqueue_queue_Type) = &PyType_Type;
+ if(PyType_Ready(&kqueue_queue_Type) < 0)
+ return;
+ Py_INCREF(&kqueue_queue_Type);
+ PyModule_AddObject(m, "kqueue", (PyObject *)&kqueue_queue_Type);
+
+ /* event filters */
+ PyModule_AddIntConstant(m, "KQ_FILTER_READ", EVFILT_READ);
+ PyModule_AddIntConstant(m, "KQ_FILTER_WRITE", EVFILT_WRITE);
+ PyModule_AddIntConstant(m, "KQ_FILTER_AIO", EVFILT_AIO);
+ PyModule_AddIntConstant(m, "KQ_FILTER_VNODE", EVFILT_VNODE);
+ PyModule_AddIntConstant(m, "KQ_FILTER_PROC", EVFILT_PROC);
#ifdef EVFILT_NETDEV
- PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
+ PyModule_AddIntConstant(m, "KQ_FILTER_NETDEV", EVFILT_NETDEV);
#endif
- PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
- PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
-
- /* event flags */
- PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
- PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
- PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
- PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
- PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
- PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
-
- PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
- PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
-
- PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
- PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
-
- /* READ WRITE filter flag */
- PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
-
- /* VNODE filter flags */
- PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
- PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
- PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
- PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
- PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
- PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
- PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
-
- /* PROC filter flags */
- PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
- PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
- PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
- PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
- PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
-
- PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
- PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
- PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
-
- /* NETDEV filter flags */
+ PyModule_AddIntConstant(m, "KQ_FILTER_SIGNAL", EVFILT_SIGNAL);
+ PyModule_AddIntConstant(m, "KQ_FILTER_TIMER", EVFILT_TIMER);
+
+ /* event flags */
+ PyModule_AddIntConstant(m, "KQ_EV_ADD", EV_ADD);
+ PyModule_AddIntConstant(m, "KQ_EV_DELETE", EV_DELETE);
+ PyModule_AddIntConstant(m, "KQ_EV_ENABLE", EV_ENABLE);
+ PyModule_AddIntConstant(m, "KQ_EV_DISABLE", EV_DISABLE);
+ PyModule_AddIntConstant(m, "KQ_EV_ONESHOT", EV_ONESHOT);
+ PyModule_AddIntConstant(m, "KQ_EV_CLEAR", EV_CLEAR);
+
+ PyModule_AddIntConstant(m, "KQ_EV_SYSFLAGS", EV_SYSFLAGS);
+ PyModule_AddIntConstant(m, "KQ_EV_FLAG1", EV_FLAG1);
+
+ PyModule_AddIntConstant(m, "KQ_EV_EOF", EV_EOF);
+ PyModule_AddIntConstant(m, "KQ_EV_ERROR", EV_ERROR);
+
+ /* READ WRITE filter flag */
+ PyModule_AddIntConstant(m, "KQ_NOTE_LOWAT", NOTE_LOWAT);
+
+ /* VNODE filter flags */
+ PyModule_AddIntConstant(m, "KQ_NOTE_DELETE", NOTE_DELETE);
+ PyModule_AddIntConstant(m, "KQ_NOTE_WRITE", NOTE_WRITE);
+ PyModule_AddIntConstant(m, "KQ_NOTE_EXTEND", NOTE_EXTEND);
+ PyModule_AddIntConstant(m, "KQ_NOTE_ATTRIB", NOTE_ATTRIB);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINK", NOTE_LINK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_RENAME", NOTE_RENAME);
+ PyModule_AddIntConstant(m, "KQ_NOTE_REVOKE", NOTE_REVOKE);
+
+ /* PROC filter flags */
+ PyModule_AddIntConstant(m, "KQ_NOTE_EXIT", NOTE_EXIT);
+ PyModule_AddIntConstant(m, "KQ_NOTE_FORK", NOTE_FORK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_EXEC", NOTE_EXEC);
+ PyModule_AddIntConstant(m, "KQ_NOTE_PCTRLMASK", NOTE_PCTRLMASK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_PDATAMASK", NOTE_PDATAMASK);
+
+ PyModule_AddIntConstant(m, "KQ_NOTE_TRACK", NOTE_TRACK);
+ PyModule_AddIntConstant(m, "KQ_NOTE_CHILD", NOTE_CHILD);
+ PyModule_AddIntConstant(m, "KQ_NOTE_TRACKERR", NOTE_TRACKERR);
+
+ /* NETDEV filter flags */
#ifdef EVFILT_NETDEV
- PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
- PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
- PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINKUP", NOTE_LINKUP);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINKDOWN", NOTE_LINKDOWN);
+ PyModule_AddIntConstant(m, "KQ_NOTE_LINKINV", NOTE_LINKINV);
#endif
#endif /* HAVE_KQUEUE */
diff --git a/Modules/sgimodule.c b/Modules/sgimodule.c
index f7e1263..0d13248 100644
--- a/Modules/sgimodule.c
+++ b/Modules/sgimodule.c
@@ -10,14 +10,14 @@
static PyObject *
sgi_nap(PyObject *self, PyObject *args)
{
- long ticks;
- if (!PyArg_ParseTuple(args, "l:nap", &ticks))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sginap(ticks);
- Py_END_ALLOW_THREADS
- Py_INCREF(Py_None);
- return Py_None;
+ long ticks;
+ if (!PyArg_ParseTuple(args, "l:nap", &ticks))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sginap(ticks);
+ Py_END_ALLOW_THREADS
+ Py_INCREF(Py_None);
+ return Py_None;
}
extern char *_getpty(int *, int, mode_t, int);
@@ -25,31 +25,31 @@ extern char *_getpty(int *, int, mode_t, int);
static PyObject *
sgi__getpty(PyObject *self, PyObject *args)
{
- int oflag;
- int mode;
- int nofork;
- char *name;
- int fildes;
- if (!PyArg_ParseTuple(args, "iii:_getpty", &oflag, &mode, &nofork))
- return NULL;
- errno = 0;
- name = _getpty(&fildes, oflag, (mode_t)mode, nofork);
- if (name == NULL) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return Py_BuildValue("(si)", name, fildes);
+ int oflag;
+ int mode;
+ int nofork;
+ char *name;
+ int fildes;
+ if (!PyArg_ParseTuple(args, "iii:_getpty", &oflag, &mode, &nofork))
+ return NULL;
+ errno = 0;
+ name = _getpty(&fildes, oflag, (mode_t)mode, nofork);
+ if (name == NULL) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return Py_BuildValue("(si)", name, fildes);
}
static PyMethodDef sgi_methods[] = {
- {"nap", sgi_nap, METH_VARARGS},
- {"_getpty", sgi__getpty, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"nap", sgi_nap, METH_VARARGS},
+ {"_getpty", sgi__getpty, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
void
initsgi(void)
{
- Py_InitModule("sgi", sgi_methods);
+ Py_InitModule("sgi", sgi_methods);
}
diff --git a/Modules/sha256module.c b/Modules/sha256module.c
index b53d2ff..2ce8d92 100644
--- a/Modules/sha256module.c
+++ b/Modules/sha256module.c
@@ -22,7 +22,7 @@
/* Endianness testing and definitions */
#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
- if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
+ if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
#define PCT_LITTLE_ENDIAN 1
#define PCT_BIG_ENDIAN 0
@@ -32,7 +32,7 @@
typedef unsigned char SHA_BYTE;
#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
+typedef unsigned int SHA_INT32; /* 32-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -46,11 +46,11 @@ typedef unsigned int SHA_INT32; /* 32-bit integer */
typedef struct {
PyObject_HEAD
- SHA_INT32 digest[8]; /* Message digest */
- SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
- SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
+ SHA_INT32 digest[8]; /* Message digest */
+ SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
+ SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
int Endianness;
- int local; /* unprocessed amount in data */
+ int local; /* unprocessed amount in data */
int digestsize;
} SHAobject;
@@ -62,7 +62,7 @@ static void longReverse(SHA_INT32 *buffer, int byteCount, int Endianness)
SHA_INT32 value;
if ( Endianness == PCT_BIG_ENDIAN )
- return;
+ return;
byteCount /= sizeof(*buffer);
while (byteCount--) {
@@ -114,7 +114,7 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
( ((((unsigned long)(x)&0xFFFFFFFFUL)>>(unsigned long)((y)&31)) | \
((unsigned long)(x)<<(unsigned long)(32-((y)&31)))) & 0xFFFFFFFFUL)
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
-#define Maj(x,y,z) (((x | y) & z) | (x & y))
+#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) ROR((x),(n))
#define R(x, n) (((x)&0xFFFFFFFFUL)>>(n))
#define Sigma0(x) (S(x, 2) ^ S(x, 13) ^ S(x, 22))
@@ -127,13 +127,13 @@ static void
sha_transform(SHAobject *sha_info)
{
int i;
- SHA_INT32 S[8], W[64], t0, t1;
+ SHA_INT32 S[8], W[64], t0, t1;
memcpy(W, sha_info->data, sizeof(sha_info->data));
longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
for (i = 16; i < 64; ++i) {
- W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
+ W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
}
for (i = 0; i < 8; ++i) {
S[i] = sha_info->digest[i];
@@ -211,8 +211,8 @@ sha_transform(SHAobject *sha_info)
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],62,0xbef9a3f7);
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],63,0xc67178f2);
-#undef RND
-
+#undef RND
+
/* feedback */
for (i = 0; i < 8; i++) {
sha_info->digest[i] = sha_info->digest[i] + S[i];
@@ -314,14 +314,14 @@ sha_final(unsigned char digest[SHA_DIGESTSIZE], SHAobject *sha_info)
count = (int) ((lo_bit_count >> 3) & 0x3f);
((SHA_BYTE *) sha_info->data)[count++] = 0x80;
if (count > SHA_BLOCKSIZE - 8) {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - count);
- sha_transform(sha_info);
- memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - count);
+ sha_transform(sha_info);
+ memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
}
else {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - 8 - count);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - 8 - count);
}
/* GJS: note that we add the hi/lo in big-endian. sha_transform will
@@ -454,21 +454,21 @@ SHA256_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyString_FromStringAndSize(NULL, self->digestsize * 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<self->digestsize; 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;
@@ -492,11 +492,11 @@ SHA256_update(SHAobject *self, PyObject *args)
}
static PyMethodDef SHA_methods[] = {
- {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__},
- {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__},
+ {"copy", (PyCFunction)SHA256_copy, METH_NOARGS, SHA256_copy__doc__},
+ {"digest", (PyCFunction)SHA256_digest, METH_NOARGS, SHA256_digest__doc__},
{"hexdigest", (PyCFunction)SHA256_hexdigest, METH_NOARGS, SHA256_hexdigest__doc__},
- {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA256_update, METH_VARARGS, SHA256_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -536,13 +536,13 @@ static PyMemberDef SHA_members[] = {
static PyTypeObject SHA224type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha256.sha224", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha256.sha224", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
@@ -558,25 +558,25 @@ static PyTypeObject SHA224type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
static PyTypeObject SHA256type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha256.sha256", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha256.sha256", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
@@ -592,13 +592,13 @@ static PyTypeObject SHA256type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
@@ -621,7 +621,7 @@ SHA256_new(PyObject *self, PyObject *args, PyObject *kwdict)
}
if ((new = newSHA256object()) == NULL) {
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
@@ -629,7 +629,7 @@ SHA256_new(PyObject *self, PyObject *args, PyObject *kwdict)
if (PyErr_Occurred()) {
Py_DECREF(new);
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
if (buf.len > 0) {
@@ -656,7 +656,7 @@ SHA224_new(PyObject *self, PyObject *args, PyObject *kwdict)
}
if ((new = newSHA224object()) == NULL) {
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
@@ -664,7 +664,7 @@ SHA224_new(PyObject *self, PyObject *args, PyObject *kwdict)
if (PyErr_Occurred()) {
Py_DECREF(new);
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
if (buf.len > 0) {
@@ -681,7 +681,7 @@ SHA224_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA_functions[] = {
{"sha256", (PyCFunction)SHA256_new, METH_VARARGS|METH_KEYWORDS, SHA256_new__doc__},
{"sha224", (PyCFunction)SHA224_new, METH_VARARGS|METH_KEYWORDS, SHA224_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -702,5 +702,5 @@ init_sha256(void)
return;
m = Py_InitModule("_sha256", SHA_functions);
if (m == NULL)
- return;
+ return;
}
diff --git a/Modules/sha512module.c b/Modules/sha512module.c
index 4e8368b..d7b3699 100644
--- a/Modules/sha512module.c
+++ b/Modules/sha512module.c
@@ -23,7 +23,7 @@
/* Endianness testing and definitions */
#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
- if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
+ if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
#define PCT_LITTLE_ENDIAN 1
#define PCT_BIG_ENDIAN 0
@@ -33,8 +33,8 @@
typedef unsigned char SHA_BYTE;
#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
-typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */
+typedef unsigned int SHA_INT32; /* 32-bit integer */
+typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -48,11 +48,11 @@ typedef unsigned PY_LONG_LONG SHA_INT64; /* 64-bit integer */
typedef struct {
PyObject_HEAD
- SHA_INT64 digest[8]; /* Message digest */
- SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
- SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
+ SHA_INT64 digest[8]; /* Message digest */
+ SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
+ SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
int Endianness;
- int local; /* unprocessed amount in data */
+ int local; /* unprocessed amount in data */
int digestsize;
} SHAobject;
@@ -64,22 +64,22 @@ static void longReverse(SHA_INT64 *buffer, int byteCount, int Endianness)
SHA_INT64 value;
if ( Endianness == PCT_BIG_ENDIAN )
- return;
+ return;
byteCount /= sizeof(*buffer);
while (byteCount--) {
value = *buffer;
- ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff;
- ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff;
- ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff;
- ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff;
- ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff;
- ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff;
- ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff;
- ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff;
-
- buffer++;
+ ((unsigned char*)buffer)[0] = (unsigned char)(value >> 56) & 0xff;
+ ((unsigned char*)buffer)[1] = (unsigned char)(value >> 48) & 0xff;
+ ((unsigned char*)buffer)[2] = (unsigned char)(value >> 40) & 0xff;
+ ((unsigned char*)buffer)[3] = (unsigned char)(value >> 32) & 0xff;
+ ((unsigned char*)buffer)[4] = (unsigned char)(value >> 24) & 0xff;
+ ((unsigned char*)buffer)[5] = (unsigned char)(value >> 16) & 0xff;
+ ((unsigned char*)buffer)[6] = (unsigned char)(value >> 8) & 0xff;
+ ((unsigned char*)buffer)[7] = (unsigned char)(value ) & 0xff;
+
+ buffer++;
}
}
@@ -124,7 +124,7 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
( ((((x) & Py_ULL(0xFFFFFFFFFFFFFFFF))>>((unsigned PY_LONG_LONG)(y) & 63)) | \
((x)<<((unsigned PY_LONG_LONG)(64-((y) & 63))))) & Py_ULL(0xFFFFFFFFFFFFFFFF))
#define Ch(x,y,z) (z ^ (x & (y ^ z)))
-#define Maj(x,y,z) (((x | y) & z) | (x & y))
+#define Maj(x,y,z) (((x | y) & z) | (x & y))
#define S(x, n) ROR64((x),(n))
#define R(x, n) (((x) & Py_ULL(0xFFFFFFFFFFFFFFFF)) >> ((unsigned PY_LONG_LONG)n))
#define Sigma0(x) (S(x, 28) ^ S(x, 34) ^ S(x, 39))
@@ -143,7 +143,7 @@ sha512_transform(SHAobject *sha_info)
longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
for (i = 16; i < 80; ++i) {
- W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
+ W[i] = Gamma1(W[i - 2]) + W[i - 7] + Gamma0(W[i - 15]) + W[i - 16];
}
for (i = 0; i < 8; ++i) {
S[i] = sha_info->digest[i];
@@ -237,8 +237,8 @@ sha512_transform(SHAobject *sha_info)
RND(S[2],S[3],S[4],S[5],S[6],S[7],S[0],S[1],78,Py_ULL(0x5fcb6fab3ad6faec));
RND(S[1],S[2],S[3],S[4],S[5],S[6],S[7],S[0],79,Py_ULL(0x6c44198c4a475817));
-#undef RND
-
+#undef RND
+
/* feedback */
for (i = 0; i < 8; i++) {
sha_info->digest[i] = sha_info->digest[i] + S[i];
@@ -340,14 +340,14 @@ sha512_final(unsigned char digest[SHA_DIGESTSIZE], SHAobject *sha_info)
count = (int) ((lo_bit_count >> 3) & 0x7f);
((SHA_BYTE *) sha_info->data)[count++] = 0x80;
if (count > SHA_BLOCKSIZE - 16) {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - count);
- sha512_transform(sha_info);
- memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - count);
+ sha512_transform(sha_info);
+ memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 16);
}
else {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - 16 - count);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - 16 - count);
}
/* GJS: note that we add the hi/lo in big-endian. sha512_transform will
@@ -520,21 +520,21 @@ SHA512_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyString_FromStringAndSize(NULL, self->digestsize * 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<self->digestsize; 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;
@@ -558,11 +558,11 @@ SHA512_update(SHAobject *self, PyObject *args)
}
static PyMethodDef SHA_methods[] = {
- {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__},
- {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__},
+ {"copy", (PyCFunction)SHA512_copy, METH_NOARGS, SHA512_copy__doc__},
+ {"digest", (PyCFunction)SHA512_digest, METH_NOARGS, SHA512_digest__doc__},
{"hexdigest", (PyCFunction)SHA512_hexdigest, METH_NOARGS, SHA512_hexdigest__doc__},
- {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA512_update, METH_VARARGS, SHA512_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -602,13 +602,13 @@ static PyMemberDef SHA_members[] = {
static PyTypeObject SHA384type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha512.sha384", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha512.sha384", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA512_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA512_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
@@ -624,25 +624,25 @@ static PyTypeObject SHA384type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
static PyTypeObject SHA512type = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha512.sha512", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha512.sha512", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA512_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
+ SHA512_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
0, /*tp_repr*/
@@ -658,13 +658,13 @@ static PyTypeObject SHA512type = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
- SHA_members, /* tp_members */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
+ SHA_members, /* tp_members */
SHA_getseters, /* tp_getset */
};
@@ -687,7 +687,7 @@ SHA512_new(PyObject *self, PyObject *args, PyObject *kwdict)
}
if ((new = newSHA512object()) == NULL) {
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
@@ -695,7 +695,7 @@ SHA512_new(PyObject *self, PyObject *args, PyObject *kwdict)
if (PyErr_Occurred()) {
Py_DECREF(new);
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
if (buf.len > 0) {
@@ -722,7 +722,7 @@ SHA384_new(PyObject *self, PyObject *args, PyObject *kwdict)
}
if ((new = newSHA384object()) == NULL) {
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
@@ -730,7 +730,7 @@ SHA384_new(PyObject *self, PyObject *args, PyObject *kwdict)
if (PyErr_Occurred()) {
Py_DECREF(new);
- PyBuffer_Release(&buf);
+ PyBuffer_Release(&buf);
return NULL;
}
if (buf.len > 0) {
@@ -747,7 +747,7 @@ SHA384_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA_functions[] = {
{"sha512", (PyCFunction)SHA512_new, METH_VARARGS|METH_KEYWORDS, SHA512_new__doc__},
{"sha384", (PyCFunction)SHA384_new, METH_VARARGS|METH_KEYWORDS, SHA384_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -768,7 +768,7 @@ init_sha512(void)
return;
m = Py_InitModule("_sha512", SHA_functions);
if (m == NULL)
- return;
+ return;
}
#endif
diff --git a/Modules/shamodule.c b/Modules/shamodule.c
index 6e7b69e..a86e722 100644
--- a/Modules/shamodule.c
+++ b/Modules/shamodule.c
@@ -21,7 +21,7 @@
/* Endianness testing and definitions */
#define TestEndianness(variable) {int i=1; variable=PCT_BIG_ENDIAN;\
- if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
+ if (*((char*)&i)==1) variable=PCT_LITTLE_ENDIAN;}
#define PCT_LITTLE_ENDIAN 1
#define PCT_BIG_ENDIAN 0
@@ -31,7 +31,7 @@
typedef unsigned char SHA_BYTE;
#if SIZEOF_INT == 4
-typedef unsigned int SHA_INT32; /* 32-bit integer */
+typedef unsigned int SHA_INT32; /* 32-bit integer */
#else
/* not defined. compilation will die. */
#endif
@@ -45,11 +45,11 @@ typedef unsigned int SHA_INT32; /* 32-bit integer */
typedef struct {
PyObject_HEAD
- SHA_INT32 digest[5]; /* Message digest */
- SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
- SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
+ SHA_INT32 digest[5]; /* Message digest */
+ SHA_INT32 count_lo, count_hi; /* 64-bit bit count */
+ SHA_BYTE data[SHA_BLOCKSIZE]; /* SHA data buffer */
int Endianness;
- int local; /* unprocessed amount in data */
+ int local; /* unprocessed amount in data */
} SHAobject;
/* When run on a little-endian CPU we need to perform byte reversal on an
@@ -60,7 +60,7 @@ static void longReverse(SHA_INT32 *buffer, int byteCount, int Endianness)
SHA_INT32 value;
if ( Endianness == PCT_BIG_ENDIAN )
- return;
+ return;
byteCount /= sizeof(*buffer);
while (byteCount--) {
@@ -111,48 +111,48 @@ static void SHAcopy(SHAobject *src, SHAobject *dest)
save one boolean operation each - thanks to Rich Schroeppel,
rcs@cs.arizona.edu for discovering this */
-/*#define f1(x,y,z) ((x & y) | (~x & z)) // Rounds 0-19 */
-#define f1(x,y,z) (z ^ (x & (y ^ z))) /* Rounds 0-19 */
-#define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39 */
-/*#define f3(x,y,z) ((x & y) | (x & z) | (y & z)) // Rounds 40-59 */
-#define f3(x,y,z) ((x & y) | (z & (x | y))) /* Rounds 40-59 */
-#define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79 */
+/*#define f1(x,y,z) ((x & y) | (~x & z)) // Rounds 0-19 */
+#define f1(x,y,z) (z ^ (x & (y ^ z))) /* Rounds 0-19 */
+#define f2(x,y,z) (x ^ y ^ z) /* Rounds 20-39 */
+/*#define f3(x,y,z) ((x & y) | (x & z) | (y & z)) // Rounds 40-59 */
+#define f3(x,y,z) ((x & y) | (z & (x | y))) /* Rounds 40-59 */
+#define f4(x,y,z) (x ^ y ^ z) /* Rounds 60-79 */
/* SHA constants */
-#define CONST1 0x5a827999L /* Rounds 0-19 */
-#define CONST2 0x6ed9eba1L /* Rounds 20-39 */
-#define CONST3 0x8f1bbcdcL /* Rounds 40-59 */
-#define CONST4 0xca62c1d6L /* Rounds 60-79 */
+#define CONST1 0x5a827999L /* Rounds 0-19 */
+#define CONST2 0x6ed9eba1L /* Rounds 20-39 */
+#define CONST3 0x8f1bbcdcL /* Rounds 40-59 */
+#define CONST4 0xca62c1d6L /* Rounds 60-79 */
/* 32-bit rotate */
-#define R32(x,n) ((x << n) | (x >> (32 - n)))
+#define R32(x,n) ((x << n) | (x >> (32 - n)))
/* the generic case, for when the overall rotation is not unraveled */
-#define FG(n) \
- T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; \
+#define FG(n) \
+ T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; \
E = D; D = C; C = R32(B,30); B = A; A = T
/* specific cases, for when the overall rotation is unraveled */
-#define FA(n) \
+#define FA(n) \
T = R32(A,5) + f##n(B,C,D) + E + *WP++ + CONST##n; B = R32(B,30)
-#define FB(n) \
+#define FB(n) \
E = R32(T,5) + f##n(A,B,C) + D + *WP++ + CONST##n; A = R32(A,30)
-#define FC(n) \
+#define FC(n) \
D = R32(E,5) + f##n(T,A,B) + C + *WP++ + CONST##n; T = R32(T,30)
-#define FD(n) \
+#define FD(n) \
C = R32(D,5) + f##n(E,T,A) + B + *WP++ + CONST##n; E = R32(E,30)
-#define FE(n) \
+#define FE(n) \
B = R32(C,5) + f##n(D,E,T) + A + *WP++ + CONST##n; D = R32(D,30)
-#define FT(n) \
+#define FT(n) \
A = R32(B,5) + f##n(C,D,E) + T + *WP++ + CONST##n; C = R32(C,30)
/* do SHA transformation */
@@ -167,10 +167,10 @@ sha_transform(SHAobject *sha_info)
longReverse(W, (int)sizeof(sha_info->data), sha_info->Endianness);
for (i = 16; i < 80; ++i) {
- W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
+ W[i] = W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16];
- /* extra rotation fix */
- W[i] = R32(W[i], 1);
+ /* extra rotation fix */
+ W[i] = R32(W[i], 1);
}
A = sha_info->digest[0];
B = sha_info->digest[1];
@@ -286,14 +286,14 @@ sha_final(unsigned char digest[20], SHAobject *sha_info)
count = (int) ((lo_bit_count >> 3) & 0x3f);
((SHA_BYTE *) sha_info->data)[count++] = 0x80;
if (count > SHA_BLOCKSIZE - 8) {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - count);
- sha_transform(sha_info);
- memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - count);
+ sha_transform(sha_info);
+ memset((SHA_BYTE *) sha_info->data, 0, SHA_BLOCKSIZE - 8);
}
else {
- memset(((SHA_BYTE *) sha_info->data) + count, 0,
- SHA_BLOCKSIZE - 8 - count);
+ memset(((SHA_BYTE *) sha_info->data) + count, 0,
+ SHA_BLOCKSIZE - 8 - count);
}
/* GJS: note that we add the hi/lo in big-endian. sha_transform will
@@ -402,21 +402,21 @@ SHA_hexdigest(SHAobject *self, PyObject *unused)
/* Create a new string */
retval = PyString_FromStringAndSize(NULL, sizeof(digest) * 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<sizeof(digest); 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;
@@ -441,11 +441,11 @@ SHA_update(SHAobject *self, PyObject *args)
}
static PyMethodDef SHA_methods[] = {
- {"copy", (PyCFunction)SHA_copy, METH_NOARGS, SHA_copy__doc__},
- {"digest", (PyCFunction)SHA_digest, METH_NOARGS, SHA_digest__doc__},
+ {"copy", (PyCFunction)SHA_copy, METH_NOARGS, SHA_copy__doc__},
+ {"digest", (PyCFunction)SHA_digest, METH_NOARGS, SHA_digest__doc__},
{"hexdigest", (PyCFunction)SHA_hexdigest, METH_NOARGS, SHA_hexdigest__doc__},
- {"update", (PyCFunction)SHA_update, METH_VARARGS, SHA_update__doc__},
- {NULL, NULL} /* sentinel */
+ {"update", (PyCFunction)SHA_update, METH_VARARGS, SHA_update__doc__},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -490,12 +490,12 @@ static PyGetSetDef SHA_getseters[] = {
static PyTypeObject SHAtype = {
PyVarObject_HEAD_INIT(NULL, 0)
- "_sha.sha", /*tp_name*/
- sizeof(SHAobject), /*tp_size*/
- 0, /*tp_itemsize*/
+ "_sha.sha", /*tp_name*/
+ sizeof(SHAobject), /*tp_size*/
+ 0, /*tp_itemsize*/
/* methods */
- SHA_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
+ SHA_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
0, /*tp_compare*/
@@ -512,12 +512,12 @@ static PyTypeObject SHAtype = {
Py_TPFLAGS_DEFAULT, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- SHA_methods, /* tp_methods */
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ SHA_methods, /* tp_methods */
0, /* tp_members */
SHA_getseters, /* tp_getset */
};
@@ -543,7 +543,7 @@ SHA_new(PyObject *self, PyObject *args, PyObject *kwdict)
}
if ((new = newSHAobject()) == NULL) {
- PyBuffer_Release(&view);
+ PyBuffer_Release(&view);
return NULL;
}
@@ -551,7 +551,7 @@ SHA_new(PyObject *self, PyObject *args, PyObject *kwdict)
if (PyErr_Occurred()) {
Py_DECREF(new);
- PyBuffer_Release(&view);
+ PyBuffer_Release(&view);
return NULL;
}
if (view.len > 0) {
@@ -568,7 +568,7 @@ SHA_new(PyObject *self, PyObject *args, PyObject *kwdict)
static struct PyMethodDef SHA_functions[] = {
{"new", (PyCFunction)SHA_new, METH_VARARGS|METH_KEYWORDS, SHA_new__doc__},
- {NULL, NULL} /* Sentinel */
+ {NULL, NULL} /* Sentinel */
};
@@ -586,12 +586,12 @@ init_sha(void)
return;
m = Py_InitModule("_sha", SHA_functions);
if (m == NULL)
- return;
+ return;
/* Add some symbolic constants to the module */
insint("blocksize", 1); /* For future use, in case some hash
functions require an integral number of
- blocks */
+ blocks */
insint("digestsize", 20);
insint("digest_size", 20);
}
diff --git a/Modules/signalmodule.c b/Modules/signalmodule.c
index b1ee890..9dc781d 100644
--- a/Modules/signalmodule.c
+++ b/Modules/signalmodule.c
@@ -34,13 +34,13 @@
#ifndef NSIG
# if defined(_NSIG)
-# define NSIG _NSIG /* For BSD/SysV */
+# define NSIG _NSIG /* For BSD/SysV */
# elif defined(_SIGMAX)
-# define NSIG (_SIGMAX + 1) /* For QNX */
+# define NSIG (_SIGMAX + 1) /* For QNX */
# elif defined(SIGMAX)
-# define NSIG (SIGMAX + 1) /* For djgpp */
+# define NSIG (SIGMAX + 1) /* For djgpp */
# else
-# define NSIG 64 /* Use a reasonable default value */
+# define NSIG 64 /* Use a reasonable default value */
# endif
#endif
@@ -82,8 +82,8 @@ static pid_t main_pid;
#endif
static struct {
- int tripped;
- PyObject *func;
+ int tripped;
+ PyObject *func;
} Handlers[NSIG];
static sig_atomic_t wakeup_fd = -1;
@@ -126,18 +126,18 @@ itimer_retval(struct itimerval *iv)
r = PyTuple_New(2);
if (r == NULL)
- return NULL;
+ return NULL;
if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_value)))) {
- Py_DECREF(r);
- return NULL;
+ Py_DECREF(r);
+ return NULL;
}
PyTuple_SET_ITEM(r, 0, v);
if(!(v = PyFloat_FromDouble(double_from_timeval(&iv->it_interval)))) {
- Py_DECREF(r);
- return NULL;
+ Py_DECREF(r);
+ return NULL;
}
PyTuple_SET_ITEM(r, 1, v);
@@ -149,8 +149,8 @@ itimer_retval(struct itimerval *iv)
static PyObject *
signal_default_int_handler(PyObject *self, PyObject *args)
{
- PyErr_SetNone(PyExc_KeyboardInterrupt);
- return NULL;
+ PyErr_SetNone(PyExc_KeyboardInterrupt);
+ return NULL;
}
PyDoc_STRVAR(default_int_handler_doc,
@@ -163,7 +163,7 @@ It raises KeyboardInterrupt.");
static int
checksignals_witharg(void * unused)
{
- return PyErr_CheckSignals();
+ return PyErr_CheckSignals();
}
static void
@@ -171,38 +171,38 @@ signal_handler(int sig_num)
{
#ifdef WITH_THREAD
#ifdef WITH_PTH
- if (PyThread_get_thread_ident() != main_thread) {
- pth_raise(*(pth_t *) main_thread, sig_num);
- return;
- }
-#endif
- /* See NOTES section above */
- if (getpid() == main_pid) {
-#endif
- Handlers[sig_num].tripped = 1;
- /* Set is_tripped after setting .tripped, as it gets
- cleared in PyErr_CheckSignals() before .tripped. */
- is_tripped = 1;
- Py_AddPendingCall(checksignals_witharg, NULL);
- if (wakeup_fd != -1)
- write(wakeup_fd, "\0", 1);
+ if (PyThread_get_thread_ident() != main_thread) {
+ pth_raise(*(pth_t *) main_thread, sig_num);
+ return;
+ }
+#endif
+ /* See NOTES section above */
+ if (getpid() == main_pid) {
+#endif
+ Handlers[sig_num].tripped = 1;
+ /* Set is_tripped after setting .tripped, as it gets
+ cleared in PyErr_CheckSignals() before .tripped. */
+ is_tripped = 1;
+ Py_AddPendingCall(checksignals_witharg, NULL);
+ if (wakeup_fd != -1)
+ write(wakeup_fd, "\0", 1);
#ifdef WITH_THREAD
- }
+ }
#endif
#ifdef SIGCHLD
- if (sig_num == SIGCHLD) {
- /* To avoid infinite recursion, this signal remains
- reset until explicit re-instated.
- Don't clear the 'func' field as it is our pointer
- to the Python handler... */
- return;
- }
+ if (sig_num == SIGCHLD) {
+ /* To avoid infinite recursion, this signal remains
+ reset until explicit re-instated.
+ Don't clear the 'func' field as it is our pointer
+ to the Python handler... */
+ return;
+ }
#endif
#ifndef HAVE_SIGACTION
- /* If the handler was not set up with sigaction, reinstall it. See
- * Python/pythonrun.c for the implementation of PyOS_setsig which
- * makes this true. See also issue8354. */
- PyOS_setsig(sig_num, signal_handler);
+ /* If the handler was not set up with sigaction, reinstall it. See
+ * Python/pythonrun.c for the implementation of PyOS_setsig which
+ * makes this true. See also issue8354. */
+ PyOS_setsig(sig_num, signal_handler);
#endif
}
@@ -211,11 +211,11 @@ signal_handler(int sig_num)
static PyObject *
signal_alarm(PyObject *self, PyObject *args)
{
- int t;
- if (!PyArg_ParseTuple(args, "i:alarm", &t))
- return NULL;
- /* alarm() returns the number of seconds remaining */
- return PyInt_FromLong((long)alarm(t));
+ int t;
+ if (!PyArg_ParseTuple(args, "i:alarm", &t))
+ return NULL;
+ /* alarm() returns the number of seconds remaining */
+ return PyInt_FromLong((long)alarm(t));
}
PyDoc_STRVAR(alarm_doc,
@@ -228,17 +228,17 @@ Arrange for SIGALRM to arrive after the given number of seconds.");
static PyObject *
signal_pause(PyObject *self)
{
- Py_BEGIN_ALLOW_THREADS
- (void)pause();
- Py_END_ALLOW_THREADS
- /* make sure that any exceptions that got raised are propagated
- * back into Python
- */
- if (PyErr_CheckSignals())
- return NULL;
-
- Py_INCREF(Py_None);
- return Py_None;
+ Py_BEGIN_ALLOW_THREADS
+ (void)pause();
+ Py_END_ALLOW_THREADS
+ /* make sure that any exceptions that got raised are propagated
+ * back into Python
+ */
+ if (PyErr_CheckSignals())
+ return NULL;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(pause_doc,
"pause()\n\
@@ -251,44 +251,44 @@ Wait until a signal arrives.");
static PyObject *
signal_signal(PyObject *self, PyObject *args)
{
- PyObject *obj;
- int sig_num;
- PyObject *old_handler;
- void (*func)(int);
- if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj))
- return NULL;
+ PyObject *obj;
+ int sig_num;
+ PyObject *old_handler;
+ void (*func)(int);
+ if (!PyArg_ParseTuple(args, "iO:signal", &sig_num, &obj))
+ return NULL;
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread) {
- PyErr_SetString(PyExc_ValueError,
- "signal only works in main thread");
- return NULL;
- }
-#endif
- if (sig_num < 1 || sig_num >= NSIG) {
- PyErr_SetString(PyExc_ValueError,
- "signal number out of range");
- return NULL;
- }
- if (obj == IgnoreHandler)
- func = SIG_IGN;
- else if (obj == DefaultHandler)
- func = SIG_DFL;
- else if (!PyCallable_Check(obj)) {
- PyErr_SetString(PyExc_TypeError,
+ if (PyThread_get_thread_ident() != main_thread) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal only works in main thread");
+ return NULL;
+ }
+#endif
+ if (sig_num < 1 || sig_num >= NSIG) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal number out of range");
+ return NULL;
+ }
+ if (obj == IgnoreHandler)
+ func = SIG_IGN;
+ else if (obj == DefaultHandler)
+ func = SIG_DFL;
+ else if (!PyCallable_Check(obj)) {
+ PyErr_SetString(PyExc_TypeError,
"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");
- return NULL;
- }
- else
- func = signal_handler;
- if (PyOS_setsig(sig_num, func) == SIG_ERR) {
- PyErr_SetFromErrno(PyExc_RuntimeError);
- return NULL;
- }
- old_handler = Handlers[sig_num].func;
- Handlers[sig_num].tripped = 0;
- Py_INCREF(obj);
- Handlers[sig_num].func = obj;
- return old_handler;
+ return NULL;
+ }
+ else
+ func = signal_handler;
+ if (PyOS_setsig(sig_num, func) == SIG_ERR) {
+ PyErr_SetFromErrno(PyExc_RuntimeError);
+ return NULL;
+ }
+ old_handler = Handlers[sig_num].func;
+ Handlers[sig_num].tripped = 0;
+ Py_INCREF(obj);
+ Handlers[sig_num].func = obj;
+ return old_handler;
}
PyDoc_STRVAR(signal_doc,
@@ -306,18 +306,18 @@ the first is the signal number, the second is the interrupted stack frame.");
static PyObject *
signal_getsignal(PyObject *self, PyObject *args)
{
- int sig_num;
- PyObject *old_handler;
- if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num))
- return NULL;
- if (sig_num < 1 || sig_num >= NSIG) {
- PyErr_SetString(PyExc_ValueError,
- "signal number out of range");
- return NULL;
- }
- old_handler = Handlers[sig_num].func;
- Py_INCREF(old_handler);
- return old_handler;
+ int sig_num;
+ PyObject *old_handler;
+ if (!PyArg_ParseTuple(args, "i:getsignal", &sig_num))
+ return NULL;
+ if (sig_num < 1 || sig_num >= NSIG) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal number out of range");
+ return NULL;
+ }
+ old_handler = Handlers[sig_num].func;
+ Py_INCREF(old_handler);
+ return old_handler;
}
PyDoc_STRVAR(getsignal_doc,
@@ -339,23 +339,23 @@ will be interrupted.");
static PyObject *
signal_siginterrupt(PyObject *self, PyObject *args)
{
- int sig_num;
- int flag;
-
- if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag))
- return NULL;
- if (sig_num < 1 || sig_num >= NSIG) {
- PyErr_SetString(PyExc_ValueError,
- "signal number out of range");
- return NULL;
- }
- if (siginterrupt(sig_num, flag)<0) {
- PyErr_SetFromErrno(PyExc_RuntimeError);
- return NULL;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ int sig_num;
+ int flag;
+
+ if (!PyArg_ParseTuple(args, "ii:siginterrupt", &sig_num, &flag))
+ return NULL;
+ if (sig_num < 1 || sig_num >= NSIG) {
+ PyErr_SetString(PyExc_ValueError,
+ "signal number out of range");
+ return NULL;
+ }
+ if (siginterrupt(sig_num, flag)<0) {
+ PyErr_SetFromErrno(PyExc_RuntimeError);
+ return NULL;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -363,24 +363,24 @@ signal_siginterrupt(PyObject *self, PyObject *args)
static PyObject *
signal_set_wakeup_fd(PyObject *self, PyObject *args)
{
- struct stat buf;
- int fd, old_fd;
- if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd))
- return NULL;
+ struct stat buf;
+ int fd, old_fd;
+ if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd))
+ return NULL;
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread) {
- PyErr_SetString(PyExc_ValueError,
- "set_wakeup_fd only works in main thread");
- return NULL;
- }
-#endif
- if (fd != -1 && fstat(fd, &buf) != 0) {
- PyErr_SetString(PyExc_ValueError, "invalid fd");
- return NULL;
- }
- old_fd = wakeup_fd;
- wakeup_fd = fd;
- return PyLong_FromLong(old_fd);
+ if (PyThread_get_thread_ident() != main_thread) {
+ PyErr_SetString(PyExc_ValueError,
+ "set_wakeup_fd only works in main thread");
+ return NULL;
+ }
+#endif
+ if (fd != -1 && fstat(fd, &buf) != 0) {
+ PyErr_SetString(PyExc_ValueError, "invalid fd");
+ return NULL;
+ }
+ old_fd = wakeup_fd;
+ wakeup_fd = fd;
+ return PyLong_FromLong(old_fd);
}
PyDoc_STRVAR(set_wakeup_fd_doc,
@@ -396,11 +396,11 @@ The fd must be non-blocking.");
int
PySignal_SetWakeupFd(int fd)
{
- int old_fd = wakeup_fd;
- if (fd < 0)
- fd = -1;
- wakeup_fd = fd;
- return old_fd;
+ int old_fd = wakeup_fd;
+ if (fd < 0)
+ fd = -1;
+ wakeup_fd = fd;
+ return old_fd;
}
@@ -414,14 +414,14 @@ signal_setitimer(PyObject *self, PyObject *args)
struct itimerval new, old;
if(!PyArg_ParseTuple(args, "id|d:setitimer", &which, &first, &interval))
- return NULL;
+ return NULL;
timeval_from_double(first, &new.it_value);
timeval_from_double(interval, &new.it_interval);
/* Let OS check "which" value */
if (setitimer(which, &new, &old) != 0) {
- PyErr_SetFromErrno(ItimerError);
- return NULL;
+ PyErr_SetFromErrno(ItimerError);
+ return NULL;
}
return itimer_retval(&old);
@@ -447,11 +447,11 @@ signal_getitimer(PyObject *self, PyObject *args)
struct itimerval old;
if (!PyArg_ParseTuple(args, "i:getitimer", &which))
- return NULL;
+ return NULL;
if (getitimer(which, &old) != 0) {
- PyErr_SetFromErrno(ItimerError);
- return NULL;
+ PyErr_SetFromErrno(ItimerError);
+ return NULL;
}
return itimer_retval(&old);
@@ -467,27 +467,27 @@ Returns current value of given itimer.");
/* List of functions defined in the module */
static PyMethodDef signal_methods[] = {
#ifdef HAVE_ALARM
- {"alarm", signal_alarm, METH_VARARGS, alarm_doc},
+ {"alarm", signal_alarm, METH_VARARGS, alarm_doc},
#endif
#ifdef HAVE_SETITIMER
{"setitimer", signal_setitimer, METH_VARARGS, setitimer_doc},
#endif
#ifdef HAVE_GETITIMER
- {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc},
+ {"getitimer", signal_getitimer, METH_VARARGS, getitimer_doc},
#endif
- {"signal", signal_signal, METH_VARARGS, signal_doc},
- {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc},
- {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc},
+ {"signal", signal_signal, METH_VARARGS, signal_doc},
+ {"getsignal", signal_getsignal, METH_VARARGS, getsignal_doc},
+ {"set_wakeup_fd", signal_set_wakeup_fd, METH_VARARGS, set_wakeup_fd_doc},
#ifdef HAVE_SIGINTERRUPT
- {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc},
+ {"siginterrupt", signal_siginterrupt, METH_VARARGS, siginterrupt_doc},
#endif
#ifdef HAVE_PAUSE
- {"pause", (PyCFunction)signal_pause,
- METH_NOARGS,pause_doc},
+ {"pause", (PyCFunction)signal_pause,
+ METH_NOARGS,pause_doc},
#endif
- {"default_int_handler", signal_default_int_handler,
- METH_VARARGS, default_int_handler_doc},
- {NULL, NULL} /* sentinel */
+ {"default_int_handler", signal_default_int_handler,
+ METH_VARARGS, default_int_handler_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -530,250 +530,250 @@ the first is the signal number, the second is the interrupted stack frame.");
PyMODINIT_FUNC
initsignal(void)
{
- PyObject *m, *d, *x;
- int i;
+ PyObject *m, *d, *x;
+ int i;
#ifdef WITH_THREAD
- main_thread = PyThread_get_thread_ident();
- main_pid = getpid();
-#endif
-
- /* Create the module and add the functions */
- m = Py_InitModule3("signal", signal_methods, module_doc);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
- d = PyModule_GetDict(m);
-
- x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
- if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0)
- goto finally;
-
- x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
- if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0)
- goto finally;
-
- x = PyInt_FromLong((long)NSIG);
- if (!x || PyDict_SetItemString(d, "NSIG", x) < 0)
- goto finally;
- Py_DECREF(x);
-
- x = IntHandler = PyDict_GetItemString(d, "default_int_handler");
- if (!x)
- goto finally;
- Py_INCREF(IntHandler);
-
- Handlers[0].tripped = 0;
- for (i = 1; i < NSIG; i++) {
- void (*t)(int);
- t = PyOS_getsig(i);
- Handlers[i].tripped = 0;
- if (t == SIG_DFL)
- Handlers[i].func = DefaultHandler;
- else if (t == SIG_IGN)
- Handlers[i].func = IgnoreHandler;
- else
- Handlers[i].func = Py_None; /* None of our business */
- Py_INCREF(Handlers[i].func);
- }
- if (Handlers[SIGINT].func == DefaultHandler) {
- /* Install default int handler */
- Py_INCREF(IntHandler);
- Py_DECREF(Handlers[SIGINT].func);
- Handlers[SIGINT].func = IntHandler;
- old_siginthandler = PyOS_setsig(SIGINT, signal_handler);
- }
+ main_thread = PyThread_get_thread_ident();
+ main_pid = getpid();
+#endif
+
+ /* Create the module and add the functions */
+ m = Py_InitModule3("signal", signal_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+ d = PyModule_GetDict(m);
+
+ x = DefaultHandler = PyLong_FromVoidPtr((void *)SIG_DFL);
+ if (!x || PyDict_SetItemString(d, "SIG_DFL", x) < 0)
+ goto finally;
+
+ x = IgnoreHandler = PyLong_FromVoidPtr((void *)SIG_IGN);
+ if (!x || PyDict_SetItemString(d, "SIG_IGN", x) < 0)
+ goto finally;
+
+ x = PyInt_FromLong((long)NSIG);
+ if (!x || PyDict_SetItemString(d, "NSIG", x) < 0)
+ goto finally;
+ Py_DECREF(x);
+
+ x = IntHandler = PyDict_GetItemString(d, "default_int_handler");
+ if (!x)
+ goto finally;
+ Py_INCREF(IntHandler);
+
+ Handlers[0].tripped = 0;
+ for (i = 1; i < NSIG; i++) {
+ void (*t)(int);
+ t = PyOS_getsig(i);
+ Handlers[i].tripped = 0;
+ if (t == SIG_DFL)
+ Handlers[i].func = DefaultHandler;
+ else if (t == SIG_IGN)
+ Handlers[i].func = IgnoreHandler;
+ else
+ Handlers[i].func = Py_None; /* None of our business */
+ Py_INCREF(Handlers[i].func);
+ }
+ if (Handlers[SIGINT].func == DefaultHandler) {
+ /* Install default int handler */
+ Py_INCREF(IntHandler);
+ Py_DECREF(Handlers[SIGINT].func);
+ Handlers[SIGINT].func = IntHandler;
+ old_siginthandler = PyOS_setsig(SIGINT, signal_handler);
+ }
#ifdef SIGHUP
- x = PyInt_FromLong(SIGHUP);
- PyDict_SetItemString(d, "SIGHUP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGHUP);
+ PyDict_SetItemString(d, "SIGHUP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGINT
- x = PyInt_FromLong(SIGINT);
- PyDict_SetItemString(d, "SIGINT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGINT);
+ PyDict_SetItemString(d, "SIGINT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGBREAK
- x = PyInt_FromLong(SIGBREAK);
- PyDict_SetItemString(d, "SIGBREAK", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGBREAK);
+ PyDict_SetItemString(d, "SIGBREAK", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGQUIT
- x = PyInt_FromLong(SIGQUIT);
- PyDict_SetItemString(d, "SIGQUIT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGQUIT);
+ PyDict_SetItemString(d, "SIGQUIT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGILL
- x = PyInt_FromLong(SIGILL);
- PyDict_SetItemString(d, "SIGILL", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGILL);
+ PyDict_SetItemString(d, "SIGILL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTRAP
- x = PyInt_FromLong(SIGTRAP);
- PyDict_SetItemString(d, "SIGTRAP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTRAP);
+ PyDict_SetItemString(d, "SIGTRAP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGIOT
- x = PyInt_FromLong(SIGIOT);
- PyDict_SetItemString(d, "SIGIOT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGIOT);
+ PyDict_SetItemString(d, "SIGIOT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGABRT
- x = PyInt_FromLong(SIGABRT);
- PyDict_SetItemString(d, "SIGABRT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGABRT);
+ PyDict_SetItemString(d, "SIGABRT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGEMT
- x = PyInt_FromLong(SIGEMT);
- PyDict_SetItemString(d, "SIGEMT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGEMT);
+ PyDict_SetItemString(d, "SIGEMT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGFPE
- x = PyInt_FromLong(SIGFPE);
- PyDict_SetItemString(d, "SIGFPE", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGFPE);
+ PyDict_SetItemString(d, "SIGFPE", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGKILL
- x = PyInt_FromLong(SIGKILL);
- PyDict_SetItemString(d, "SIGKILL", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGKILL);
+ PyDict_SetItemString(d, "SIGKILL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGBUS
- x = PyInt_FromLong(SIGBUS);
- PyDict_SetItemString(d, "SIGBUS", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGBUS);
+ PyDict_SetItemString(d, "SIGBUS", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSEGV
- x = PyInt_FromLong(SIGSEGV);
- PyDict_SetItemString(d, "SIGSEGV", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGSEGV);
+ PyDict_SetItemString(d, "SIGSEGV", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSYS
- x = PyInt_FromLong(SIGSYS);
- PyDict_SetItemString(d, "SIGSYS", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGSYS);
+ PyDict_SetItemString(d, "SIGSYS", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPIPE
- x = PyInt_FromLong(SIGPIPE);
- PyDict_SetItemString(d, "SIGPIPE", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPIPE);
+ PyDict_SetItemString(d, "SIGPIPE", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGALRM
- x = PyInt_FromLong(SIGALRM);
- PyDict_SetItemString(d, "SIGALRM", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGALRM);
+ PyDict_SetItemString(d, "SIGALRM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTERM
- x = PyInt_FromLong(SIGTERM);
- PyDict_SetItemString(d, "SIGTERM", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTERM);
+ PyDict_SetItemString(d, "SIGTERM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGUSR1
- x = PyInt_FromLong(SIGUSR1);
- PyDict_SetItemString(d, "SIGUSR1", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGUSR1);
+ PyDict_SetItemString(d, "SIGUSR1", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGUSR2
- x = PyInt_FromLong(SIGUSR2);
- PyDict_SetItemString(d, "SIGUSR2", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGUSR2);
+ PyDict_SetItemString(d, "SIGUSR2", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCLD
- x = PyInt_FromLong(SIGCLD);
- PyDict_SetItemString(d, "SIGCLD", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGCLD);
+ PyDict_SetItemString(d, "SIGCLD", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCHLD
- x = PyInt_FromLong(SIGCHLD);
- PyDict_SetItemString(d, "SIGCHLD", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGCHLD);
+ PyDict_SetItemString(d, "SIGCHLD", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPWR
- x = PyInt_FromLong(SIGPWR);
- PyDict_SetItemString(d, "SIGPWR", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPWR);
+ PyDict_SetItemString(d, "SIGPWR", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGIO
- x = PyInt_FromLong(SIGIO);
- PyDict_SetItemString(d, "SIGIO", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGIO);
+ PyDict_SetItemString(d, "SIGIO", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGURG
- x = PyInt_FromLong(SIGURG);
- PyDict_SetItemString(d, "SIGURG", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGURG);
+ PyDict_SetItemString(d, "SIGURG", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGWINCH
- x = PyInt_FromLong(SIGWINCH);
- PyDict_SetItemString(d, "SIGWINCH", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGWINCH);
+ PyDict_SetItemString(d, "SIGWINCH", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPOLL
- x = PyInt_FromLong(SIGPOLL);
- PyDict_SetItemString(d, "SIGPOLL", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPOLL);
+ PyDict_SetItemString(d, "SIGPOLL", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGSTOP
- x = PyInt_FromLong(SIGSTOP);
- PyDict_SetItemString(d, "SIGSTOP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGSTOP);
+ PyDict_SetItemString(d, "SIGSTOP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTSTP
- x = PyInt_FromLong(SIGTSTP);
- PyDict_SetItemString(d, "SIGTSTP", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTSTP);
+ PyDict_SetItemString(d, "SIGTSTP", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGCONT
- x = PyInt_FromLong(SIGCONT);
- PyDict_SetItemString(d, "SIGCONT", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGCONT);
+ PyDict_SetItemString(d, "SIGCONT", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTTIN
- x = PyInt_FromLong(SIGTTIN);
- PyDict_SetItemString(d, "SIGTTIN", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTTIN);
+ PyDict_SetItemString(d, "SIGTTIN", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGTTOU
- x = PyInt_FromLong(SIGTTOU);
- PyDict_SetItemString(d, "SIGTTOU", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGTTOU);
+ PyDict_SetItemString(d, "SIGTTOU", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGVTALRM
- x = PyInt_FromLong(SIGVTALRM);
- PyDict_SetItemString(d, "SIGVTALRM", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGVTALRM);
+ PyDict_SetItemString(d, "SIGVTALRM", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGPROF
- x = PyInt_FromLong(SIGPROF);
- PyDict_SetItemString(d, "SIGPROF", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGPROF);
+ PyDict_SetItemString(d, "SIGPROF", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGXCPU
- x = PyInt_FromLong(SIGXCPU);
- PyDict_SetItemString(d, "SIGXCPU", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGXCPU);
+ PyDict_SetItemString(d, "SIGXCPU", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGXFSZ
- x = PyInt_FromLong(SIGXFSZ);
- PyDict_SetItemString(d, "SIGXFSZ", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGXFSZ);
+ PyDict_SetItemString(d, "SIGXFSZ", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGRTMIN
- x = PyInt_FromLong(SIGRTMIN);
- PyDict_SetItemString(d, "SIGRTMIN", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGRTMIN);
+ PyDict_SetItemString(d, "SIGRTMIN", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGRTMAX
- x = PyInt_FromLong(SIGRTMAX);
- PyDict_SetItemString(d, "SIGRTMAX", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGRTMAX);
+ PyDict_SetItemString(d, "SIGRTMAX", x);
+ Py_XDECREF(x);
#endif
#ifdef SIGINFO
- x = PyInt_FromLong(SIGINFO);
- PyDict_SetItemString(d, "SIGINFO", x);
- Py_XDECREF(x);
+ x = PyInt_FromLong(SIGINFO);
+ PyDict_SetItemString(d, "SIGINFO", x);
+ Py_XDECREF(x);
#endif
#ifdef ITIMER_REAL
@@ -793,10 +793,10 @@ initsignal(void)
#endif
#if defined (HAVE_SETITIMER) || defined (HAVE_GETITIMER)
- ItimerError = PyErr_NewException("signal.ItimerError",
- PyExc_IOError, NULL);
+ ItimerError = PyErr_NewException("signal.ItimerError",
+ PyExc_IOError, NULL);
if (ItimerError != NULL)
- PyDict_SetItemString(d, "ItimerError", ItimerError);
+ PyDict_SetItemString(d, "ItimerError", ItimerError);
#endif
#ifdef CTRL_C_EVENT
@@ -811,39 +811,39 @@ initsignal(void)
Py_DECREF(x);
#endif
- if (!PyErr_Occurred())
- return;
+ if (!PyErr_Occurred())
+ return;
- /* Check for errors */
+ /* Check for errors */
finally:
- return;
+ return;
}
static void
finisignal(void)
{
- int i;
- PyObject *func;
-
- PyOS_setsig(SIGINT, old_siginthandler);
- old_siginthandler = SIG_DFL;
-
- for (i = 1; i < NSIG; i++) {
- func = Handlers[i].func;
- Handlers[i].tripped = 0;
- Handlers[i].func = NULL;
- if (i != SIGINT && func != NULL && func != Py_None &&
- func != DefaultHandler && func != IgnoreHandler)
- PyOS_setsig(i, SIG_DFL);
- Py_XDECREF(func);
- }
-
- Py_XDECREF(IntHandler);
- IntHandler = NULL;
- Py_XDECREF(DefaultHandler);
- DefaultHandler = NULL;
- Py_XDECREF(IgnoreHandler);
- IgnoreHandler = NULL;
+ int i;
+ PyObject *func;
+
+ PyOS_setsig(SIGINT, old_siginthandler);
+ old_siginthandler = SIG_DFL;
+
+ for (i = 1; i < NSIG; i++) {
+ func = Handlers[i].func;
+ Handlers[i].tripped = 0;
+ Handlers[i].func = NULL;
+ if (i != SIGINT && func != NULL && func != Py_None &&
+ func != DefaultHandler && func != IgnoreHandler)
+ PyOS_setsig(i, SIG_DFL);
+ Py_XDECREF(func);
+ }
+
+ Py_XDECREF(IntHandler);
+ IntHandler = NULL;
+ Py_XDECREF(DefaultHandler);
+ DefaultHandler = NULL;
+ Py_XDECREF(IgnoreHandler);
+ IgnoreHandler = NULL;
}
@@ -851,55 +851,55 @@ finisignal(void)
int
PyErr_CheckSignals(void)
{
- int i;
- PyObject *f;
+ int i;
+ PyObject *f;
- if (!is_tripped)
- return 0;
+ if (!is_tripped)
+ return 0;
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread)
- return 0;
-#endif
-
- /*
- * The is_tripped variable is meant to speed up the calls to
- * PyErr_CheckSignals (both directly or via pending calls) when no
- * signal has arrived. This variable is set to 1 when a signal arrives
- * and it is set to 0 here, when we know some signals arrived. This way
- * we can run the registered handlers with no signals blocked.
- *
- * NOTE: with this approach we can have a situation where is_tripped is
- * 1 but we have no more signals to handle (Handlers[i].tripped
- * is 0 for every signal i). This won't do us any harm (except
- * we're gonna spent some cycles for nothing). This happens when
- * we receive a signal i after we zero is_tripped and before we
- * check Handlers[i].tripped.
- */
- is_tripped = 0;
-
- if (!(f = (PyObject *)PyEval_GetFrame()))
- f = Py_None;
-
- for (i = 1; i < NSIG; i++) {
- if (Handlers[i].tripped) {
- PyObject *result = NULL;
- PyObject *arglist = Py_BuildValue("(iO)", i, f);
- Handlers[i].tripped = 0;
-
- if (arglist) {
- result = PyEval_CallObject(Handlers[i].func,
- arglist);
- Py_DECREF(arglist);
- }
- if (!result)
- return -1;
-
- Py_DECREF(result);
- }
- }
-
- return 0;
+ if (PyThread_get_thread_ident() != main_thread)
+ return 0;
+#endif
+
+ /*
+ * The is_tripped variable is meant to speed up the calls to
+ * PyErr_CheckSignals (both directly or via pending calls) when no
+ * signal has arrived. This variable is set to 1 when a signal arrives
+ * and it is set to 0 here, when we know some signals arrived. This way
+ * we can run the registered handlers with no signals blocked.
+ *
+ * NOTE: with this approach we can have a situation where is_tripped is
+ * 1 but we have no more signals to handle (Handlers[i].tripped
+ * is 0 for every signal i). This won't do us any harm (except
+ * we're gonna spent some cycles for nothing). This happens when
+ * we receive a signal i after we zero is_tripped and before we
+ * check Handlers[i].tripped.
+ */
+ is_tripped = 0;
+
+ if (!(f = (PyObject *)PyEval_GetFrame()))
+ f = Py_None;
+
+ for (i = 1; i < NSIG; i++) {
+ if (Handlers[i].tripped) {
+ PyObject *result = NULL;
+ PyObject *arglist = Py_BuildValue("(iO)", i, f);
+ Handlers[i].tripped = 0;
+
+ if (arglist) {
+ result = PyEval_CallObject(Handlers[i].func,
+ arglist);
+ Py_DECREF(arglist);
+ }
+ if (!result)
+ return -1;
+
+ Py_DECREF(result);
+ }
+ }
+
+ return 0;
}
@@ -909,46 +909,46 @@ PyErr_CheckSignals(void)
void
PyErr_SetInterrupt(void)
{
- is_tripped = 1;
- Handlers[SIGINT].tripped = 1;
- Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL);
+ is_tripped = 1;
+ Handlers[SIGINT].tripped = 1;
+ Py_AddPendingCall((int (*)(void *))PyErr_CheckSignals, NULL);
}
void
PyOS_InitInterrupts(void)
{
- initsignal();
- _PyImport_FixupExtension("signal", "signal");
+ initsignal();
+ _PyImport_FixupExtension("signal", "signal");
}
void
PyOS_FiniInterrupts(void)
{
- finisignal();
+ finisignal();
}
int
PyOS_InterruptOccurred(void)
{
- if (Handlers[SIGINT].tripped) {
+ if (Handlers[SIGINT].tripped) {
#ifdef WITH_THREAD
- if (PyThread_get_thread_ident() != main_thread)
- return 0;
+ if (PyThread_get_thread_ident() != main_thread)
+ return 0;
#endif
- Handlers[SIGINT].tripped = 0;
- return 1;
- }
- return 0;
+ Handlers[SIGINT].tripped = 0;
+ return 1;
+ }
+ return 0;
}
void
PyOS_AfterFork(void)
{
#ifdef WITH_THREAD
- PyEval_ReInitThreads();
- main_thread = PyThread_get_thread_ident();
- main_pid = getpid();
- _PyImport_ReInitLock();
- PyThread_ReInitTLS();
+ PyEval_ReInitThreads();
+ main_thread = PyThread_get_thread_ident();
+ main_pid = getpid();
+ _PyImport_ReInitLock();
+ PyThread_ReInitTLS();
#endif
}
diff --git a/Modules/socketmodule.c b/Modules/socketmodule.c
index 6b163f4..5da7809 100644
--- a/Modules/socketmodule.c
+++ b/Modules/socketmodule.c
@@ -17,11 +17,11 @@ Module interface:
- socket.error: exception raised for socket specific errors
- socket.gaierror: exception raised for getaddrinfo/getnameinfo errors,
- a subclass of socket.error
+ a subclass of socket.error
- socket.herror: exception raised for gethostby* errors,
- a subclass of socket.error
+ a subclass of socket.error
- socket.fromfd(fd, family, type[, proto]) --> new socket object (created
- from an existing file descriptor)
+ from an existing file descriptor)
- socket.gethostbyname(hostname) --> host IP address (string: 'dd.dd.dd.dd')
- socket.gethostbyaddr(IP address) --> (hostname, [alias, ...], [IP addr, ...])
- socket.gethostname() --> host name (string: 'spam' or 'spam.domain.com')
@@ -35,7 +35,7 @@ Module interface:
- socket.htons(16 bit value) --> new int object
- socket.htonl(32 bit value) --> new int object
- socket.getaddrinfo(host, port [, family, socktype, proto, flags])
- --> List of (family, socktype, proto, canonname, sockaddr)
+ --> List of (family, socktype, proto, canonname, sockaddr)
- socket.getnameinfo(sockaddr, flags) --> (host, port)
- socket.AF_INET, socket.SOCK_STREAM, etc.: constants from <socket.h>
- socket.has_ipv6: boolean value indicating if IPv6 is supported
@@ -55,22 +55,22 @@ Module interface:
specify packet-type and ha-type/addr.
- an AF_TIPC socket address is expressed as
(addr_type, v1, v2, v3 [, scope]); where addr_type can be one of:
- TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
+ TIPC_ADDR_NAMESEQ, TIPC_ADDR_NAME, and TIPC_ADDR_ID;
and scope can be one of:
- TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
+ TIPC_ZONE_SCOPE, TIPC_CLUSTER_SCOPE, and TIPC_NODE_SCOPE.
The meaning of v1, v2 and v3 depends on the value of addr_type:
- if addr_type is TIPC_ADDR_NAME:
- v1 is the server type
- v2 is the port identifier
- v3 is ignored
- if addr_type is TIPC_ADDR_NAMESEQ:
- v1 is the server type
- v2 is the lower port number
- v3 is the upper port number
- if addr_type is TIPC_ADDR_ID:
- v1 is the node
- v2 is the ref
- v3 is ignored
+ if addr_type is TIPC_ADDR_NAME:
+ v1 is the server type
+ v2 is the port identifier
+ v3 is ignored
+ if addr_type is TIPC_ADDR_NAMESEQ:
+ v1 is the server type
+ v2 is the lower port number
+ v3 is the upper port number
+ if addr_type is TIPC_ADDR_ID:
+ v1 is the node
+ v2 is the ref
+ v3 is ignored
Local naming conventions:
@@ -295,7 +295,7 @@ int h_errno; /* not used */
#include <stddef.h>
#ifndef offsetof
-# define offsetof(type, member) ((size_t)(&((type *)0)->member))
+# define offsetof(type, member) ((size_t)(&((type *)0)->member))
#endif
#ifndef O_NONBLOCK
@@ -415,7 +415,7 @@ const char *inet_ntop(int af, const void *src, char *dst, socklen_t size);
#define SEGMENT_SIZE (32 * 1024 -1)
#endif
-#define SAS2SA(x) ((struct sockaddr *)(x))
+#define SAS2SA(x) ((struct sockaddr *)(x))
/*
* Constants for getnameinfo()
@@ -471,8 +471,8 @@ static PyTypeObject sock_type;
static PyObject*
select_error(void)
{
- PyErr_SetString(socket_error, "unable to select on socket");
- return NULL;
+ PyErr_SetString(socket_error, "unable to select on socket");
+ return NULL;
}
/* Convenience function to raise an error according to errno
@@ -482,107 +482,107 @@ static PyObject *
set_error(void)
{
#ifdef MS_WINDOWS
- int err_no = WSAGetLastError();
- /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
- recognizes the error codes used by both GetLastError() and
- WSAGetLastError */
- if (err_no)
- return PyErr_SetExcFromWindowsErr(socket_error, err_no);
+ int err_no = WSAGetLastError();
+ /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which
+ recognizes the error codes used by both GetLastError() and
+ WSAGetLastError */
+ if (err_no)
+ return PyErr_SetExcFromWindowsErr(socket_error, err_no);
#endif
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
- if (sock_errno() != NO_ERROR) {
- APIRET rc;
- ULONG msglen;
- char outbuf[100];
- int myerrorcode = sock_errno();
-
- /* Retrieve socket-related error message from MPTN.MSG file */
- rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
- myerrorcode - SOCBASEERR + 26,
- "mptn.msg",
- &msglen);
- if (rc == NO_ERROR) {
- PyObject *v;
-
- /* OS/2 doesn't guarantee a terminator */
- outbuf[msglen] = '\0';
- if (strlen(outbuf) > 0) {
- /* If non-empty msg, trim CRLF */
- char *lastc = &outbuf[ strlen(outbuf)-1 ];
- while (lastc > outbuf &&
- isspace(Py_CHARMASK(*lastc))) {
- /* Trim trailing whitespace (CRLF) */
- *lastc-- = '\0';
- }
- }
- v = Py_BuildValue("(is)", myerrorcode, outbuf);
- if (v != NULL) {
- PyErr_SetObject(socket_error, v);
- Py_DECREF(v);
- }
- return NULL;
- }
- }
+ if (sock_errno() != NO_ERROR) {
+ APIRET rc;
+ ULONG msglen;
+ char outbuf[100];
+ int myerrorcode = sock_errno();
+
+ /* Retrieve socket-related error message from MPTN.MSG file */
+ rc = DosGetMessage(NULL, 0, outbuf, sizeof(outbuf),
+ myerrorcode - SOCBASEERR + 26,
+ "mptn.msg",
+ &msglen);
+ if (rc == NO_ERROR) {
+ PyObject *v;
+
+ /* OS/2 doesn't guarantee a terminator */
+ outbuf[msglen] = '\0';
+ if (strlen(outbuf) > 0) {
+ /* If non-empty msg, trim CRLF */
+ char *lastc = &outbuf[ strlen(outbuf)-1 ];
+ while (lastc > outbuf &&
+ isspace(Py_CHARMASK(*lastc))) {
+ /* Trim trailing whitespace (CRLF) */
+ *lastc-- = '\0';
+ }
+ }
+ v = Py_BuildValue("(is)", myerrorcode, outbuf);
+ if (v != NULL) {
+ PyErr_SetObject(socket_error, v);
+ Py_DECREF(v);
+ }
+ return NULL;
+ }
+ }
#endif
#if defined(RISCOS)
- if (_inet_error.errnum != NULL) {
- PyObject *v;
- v = Py_BuildValue("(is)", errno, _inet_err());
- if (v != NULL) {
- PyErr_SetObject(socket_error, v);
- Py_DECREF(v);
- }
- return NULL;
- }
-#endif
-
- return PyErr_SetFromErrno(socket_error);
+ if (_inet_error.errnum != NULL) {
+ PyObject *v;
+ v = Py_BuildValue("(is)", errno, _inet_err());
+ if (v != NULL) {
+ PyErr_SetObject(socket_error, v);
+ Py_DECREF(v);
+ }
+ return NULL;
+ }
+#endif
+
+ return PyErr_SetFromErrno(socket_error);
}
static PyObject *
set_herror(int h_error)
{
- PyObject *v;
+ PyObject *v;
#ifdef HAVE_HSTRERROR
- v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
+ v = Py_BuildValue("(is)", h_error, (char *)hstrerror(h_error));
#else
- v = Py_BuildValue("(is)", h_error, "host not found");
+ v = Py_BuildValue("(is)", h_error, "host not found");
#endif
- if (v != NULL) {
- PyErr_SetObject(socket_herror, v);
- Py_DECREF(v);
- }
+ if (v != NULL) {
+ PyErr_SetObject(socket_herror, v);
+ Py_DECREF(v);
+ }
- return NULL;
+ return NULL;
}
static PyObject *
set_gaierror(int error)
{
- PyObject *v;
+ PyObject *v;
#ifdef EAI_SYSTEM
- /* EAI_SYSTEM is not available on Windows XP. */
- if (error == EAI_SYSTEM)
- return set_error();
+ /* EAI_SYSTEM is not available on Windows XP. */
+ if (error == EAI_SYSTEM)
+ return set_error();
#endif
#ifdef HAVE_GAI_STRERROR
- v = Py_BuildValue("(is)", error, gai_strerror(error));
+ v = Py_BuildValue("(is)", error, gai_strerror(error));
#else
- v = Py_BuildValue("(is)", error, "getaddrinfo failed");
+ v = Py_BuildValue("(is)", error, "getaddrinfo failed");
#endif
- if (v != NULL) {
- PyErr_SetObject(socket_gaierror, v);
- Py_DECREF(v);
- }
+ if (v != NULL) {
+ PyErr_SetObject(socket_gaierror, v);
+ Py_DECREF(v);
+ }
- return NULL;
+ return NULL;
}
#ifdef __VMS
@@ -590,22 +590,22 @@ set_gaierror(int error)
static int
sendsegmented(int sock_fd, char *buf, int len, int flags)
{
- int n = 0;
- int remaining = len;
-
- while (remaining > 0) {
- unsigned int segment;
-
- segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
- n = send(sock_fd, buf, segment, flags);
- if (n < 0) {
- return n;
- }
- remaining -= segment;
- buf += segment;
- } /* end while */
-
- return len;
+ int n = 0;
+ int remaining = len;
+
+ while (remaining > 0) {
+ unsigned int segment;
+
+ segment = (remaining >= SEGMENT_SIZE ? SEGMENT_SIZE : remaining);
+ n = send(sock_fd, buf, segment, flags);
+ if (n < 0) {
+ return n;
+ }
+ remaining -= segment;
+ buf += segment;
+ } /* end while */
+
+ return len;
}
#endif
@@ -616,45 +616,45 @@ internal_setblocking(PySocketSockObject *s, int block)
{
#ifndef RISCOS
#ifndef MS_WINDOWS
- int delay_flag;
+ int delay_flag;
#endif
#endif
- Py_BEGIN_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
#ifdef __BEOS__
- block = !block;
- setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
- (void *)(&block), sizeof(int));
+ block = !block;
+ setsockopt(s->sock_fd, SOL_SOCKET, SO_NONBLOCK,
+ (void *)(&block), sizeof(int));
#else
#ifndef RISCOS
#ifndef MS_WINDOWS
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
- block = !block;
- ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
+ block = !block;
+ ioctl(s->sock_fd, FIONBIO, (caddr_t)&block, sizeof(block));
#elif defined(__VMS)
- block = !block;
- ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
+ block = !block;
+ ioctl(s->sock_fd, FIONBIO, (unsigned int *)&block);
#else /* !PYOS_OS2 && !__VMS */
- delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
- if (block)
- delay_flag &= (~O_NONBLOCK);
- else
- delay_flag |= O_NONBLOCK;
- fcntl(s->sock_fd, F_SETFL, delay_flag);
+ delay_flag = fcntl(s->sock_fd, F_GETFL, 0);
+ if (block)
+ delay_flag &= (~O_NONBLOCK);
+ else
+ delay_flag |= O_NONBLOCK;
+ fcntl(s->sock_fd, F_SETFL, delay_flag);
#endif /* !PYOS_OS2 */
#else /* MS_WINDOWS */
- block = !block;
- ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
+ block = !block;
+ ioctlsocket(s->sock_fd, FIONBIO, (u_long*)&block);
#endif /* MS_WINDOWS */
#else /* RISCOS */
- block = !block;
- socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
+ block = !block;
+ socketioctl(s->sock_fd, FIONBIO, (u_long*)&block);
#endif /* RISCOS */
#endif /* __BEOS__ */
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
- /* Since these don't return anything */
- return 1;
+ /* Since these don't return anything */
+ return 1;
}
/* Do a select()/poll() on the socket, if necessary (sock_timeout > 0).
@@ -665,53 +665,53 @@ internal_setblocking(PySocketSockObject *s, int block)
static int
internal_select(PySocketSockObject *s, int writing)
{
- int n;
+ int n;
- /* Nothing to do unless we're in timeout mode (not non-blocking) */
- if (s->sock_timeout <= 0.0)
- return 0;
+ /* Nothing to do unless we're in timeout mode (not non-blocking) */
+ if (s->sock_timeout <= 0.0)
+ return 0;
- /* Guard against closed socket */
- if (s->sock_fd < 0)
- return 0;
+ /* Guard against closed socket */
+ if (s->sock_fd < 0)
+ return 0;
- /* Prefer poll, if available, since you can poll() any fd
- * which can't be done with select(). */
+ /* Prefer poll, if available, since you can poll() any fd
+ * which can't be done with select(). */
#ifdef HAVE_POLL
- {
- struct pollfd pollfd;
- int timeout;
+ {
+ struct pollfd pollfd;
+ int timeout;
- pollfd.fd = s->sock_fd;
- pollfd.events = writing ? POLLOUT : POLLIN;
+ pollfd.fd = s->sock_fd;
+ pollfd.events = writing ? POLLOUT : POLLIN;
- /* s->sock_timeout is in seconds, timeout in ms */
- timeout = (int)(s->sock_timeout * 1000 + 0.5);
- n = poll(&pollfd, 1, timeout);
- }
+ /* s->sock_timeout is in seconds, timeout in ms */
+ timeout = (int)(s->sock_timeout * 1000 + 0.5);
+ n = poll(&pollfd, 1, timeout);
+ }
#else
- {
- /* Construct the arguments to select */
- fd_set fds;
- struct timeval tv;
- tv.tv_sec = (int)s->sock_timeout;
- tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
- FD_ZERO(&fds);
- FD_SET(s->sock_fd, &fds);
-
- /* See if the socket is ready */
- if (writing)
- n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
- else
- n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
- }
-#endif
-
- if (n < 0)
- return -1;
- if (n == 0)
- return 1;
- return 0;
+ {
+ /* Construct the arguments to select */
+ fd_set fds;
+ struct timeval tv;
+ tv.tv_sec = (int)s->sock_timeout;
+ tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
+ FD_ZERO(&fds);
+ FD_SET(s->sock_fd, &fds);
+
+ /* See if the socket is ready */
+ if (writing)
+ n = select(s->sock_fd+1, NULL, &fds, NULL, &tv);
+ else
+ n = select(s->sock_fd+1, &fds, NULL, NULL, &tv);
+ }
+#endif
+
+ if (n < 0)
+ return -1;
+ if (n == 0)
+ return 1;
+ return 0;
}
/* Initialize a new socket object. */
@@ -720,25 +720,25 @@ static double defaulttimeout = -1.0; /* Default timeout for new sockets */
PyMODINIT_FUNC
init_sockobject(PySocketSockObject *s,
- SOCKET_T fd, int family, int type, int proto)
+ SOCKET_T fd, int family, int type, int proto)
{
#ifdef RISCOS
- int block = 1;
+ int block = 1;
#endif
- s->sock_fd = fd;
- s->sock_family = family;
- s->sock_type = type;
- s->sock_proto = proto;
- s->sock_timeout = defaulttimeout;
+ s->sock_fd = fd;
+ s->sock_family = family;
+ s->sock_type = type;
+ s->sock_proto = proto;
+ s->sock_timeout = defaulttimeout;
- s->errorhandler = &set_error;
+ s->errorhandler = &set_error;
- if (defaulttimeout >= 0.0)
- internal_setblocking(s, 0);
+ if (defaulttimeout >= 0.0)
+ internal_setblocking(s, 0);
#ifdef RISCOS
- if (taskwindow)
- socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
+ if (taskwindow)
+ socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
#endif
}
@@ -751,12 +751,12 @@ init_sockobject(PySocketSockObject *s,
static PySocketSockObject *
new_sockobject(SOCKET_T fd, int family, int type, int proto)
{
- PySocketSockObject *s;
- s = (PySocketSockObject *)
- PyType_GenericNew(&sock_type, NULL, NULL);
- if (s != NULL)
- init_sockobject(s, fd, family, type, proto);
- return s;
+ PySocketSockObject *s;
+ s = (PySocketSockObject *)
+ PyType_GenericNew(&sock_type, NULL, NULL);
+ if (s != NULL)
+ init_sockobject(s, fd, family, type, proto);
+ return s;
}
@@ -776,122 +776,122 @@ PyThread_type_lock netdb_lock;
static int
setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
{
- struct addrinfo hints, *res;
- int error;
- int d1, d2, d3, d4;
- char ch;
-
- memset((void *) addr_ret, '\0', sizeof(*addr_ret));
- if (name[0] == '\0') {
- int siz;
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
- hints.ai_socktype = SOCK_DGRAM; /*dummy*/
- hints.ai_flags = AI_PASSIVE;
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(NULL, "0", &hints, &res);
- Py_END_ALLOW_THREADS
- /* We assume that those thread-unsafe getaddrinfo() versions
- *are* safe regarding their return value, ie. that a
- subsequent call to getaddrinfo() does not destroy the
- outcome of the first call. */
- RELEASE_GETADDRINFO_LOCK
- if (error) {
- set_gaierror(error);
- return -1;
- }
- switch (res->ai_family) {
- case AF_INET:
- siz = 4;
- break;
+ struct addrinfo hints, *res;
+ int error;
+ int d1, d2, d3, d4;
+ char ch;
+
+ memset((void *) addr_ret, '\0', sizeof(*addr_ret));
+ if (name[0] == '\0') {
+ int siz;
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = af;
+ hints.ai_socktype = SOCK_DGRAM; /*dummy*/
+ hints.ai_flags = AI_PASSIVE;
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(NULL, "0", &hints, &res);
+ Py_END_ALLOW_THREADS
+ /* We assume that those thread-unsafe getaddrinfo() versions
+ *are* safe regarding their return value, ie. that a
+ subsequent call to getaddrinfo() does not destroy the
+ outcome of the first call. */
+ RELEASE_GETADDRINFO_LOCK
+ if (error) {
+ set_gaierror(error);
+ return -1;
+ }
+ switch (res->ai_family) {
+ case AF_INET:
+ siz = 4;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- siz = 16;
- break;
-#endif
- default:
- freeaddrinfo(res);
- PyErr_SetString(socket_error,
- "unsupported address family");
- return -1;
- }
- if (res->ai_next) {
- freeaddrinfo(res);
- PyErr_SetString(socket_error,
- "wildcard resolved to multiple address");
- return -1;
- }
- if (res->ai_addrlen < addr_ret_size)
- addr_ret_size = res->ai_addrlen;
- memcpy(addr_ret, res->ai_addr, addr_ret_size);
- freeaddrinfo(res);
- return siz;
- }
- if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
- struct sockaddr_in *sin;
- if (af != AF_INET && af != AF_UNSPEC) {
- PyErr_SetString(socket_error,
- "address family mismatched");
- return -1;
- }
- sin = (struct sockaddr_in *)addr_ret;
- memset((void *) sin, '\0', sizeof(*sin));
- sin->sin_family = AF_INET;
+ case AF_INET6:
+ siz = 16;
+ break;
+#endif
+ default:
+ freeaddrinfo(res);
+ PyErr_SetString(socket_error,
+ "unsupported address family");
+ return -1;
+ }
+ if (res->ai_next) {
+ freeaddrinfo(res);
+ PyErr_SetString(socket_error,
+ "wildcard resolved to multiple address");
+ return -1;
+ }
+ if (res->ai_addrlen < addr_ret_size)
+ addr_ret_size = res->ai_addrlen;
+ memcpy(addr_ret, res->ai_addr, addr_ret_size);
+ freeaddrinfo(res);
+ return siz;
+ }
+ if (name[0] == '<' && strcmp(name, "<broadcast>") == 0) {
+ struct sockaddr_in *sin;
+ if (af != AF_INET && af != AF_UNSPEC) {
+ PyErr_SetString(socket_error,
+ "address family mismatched");
+ return -1;
+ }
+ sin = (struct sockaddr_in *)addr_ret;
+ memset((void *) sin, '\0', sizeof(*sin));
+ sin->sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin->sin_len = sizeof(*sin);
-#endif
- sin->sin_addr.s_addr = INADDR_BROADCAST;
- return sizeof(sin->sin_addr);
- }
- if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
- 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
- 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
- struct sockaddr_in *sin;
- sin = (struct sockaddr_in *)addr_ret;
- sin->sin_addr.s_addr = htonl(
- ((long) d1 << 24) | ((long) d2 << 16) |
- ((long) d3 << 8) | ((long) d4 << 0));
- sin->sin_family = AF_INET;
+ sin->sin_len = sizeof(*sin);
+#endif
+ sin->sin_addr.s_addr = INADDR_BROADCAST;
+ return sizeof(sin->sin_addr);
+ }
+ if (sscanf(name, "%d.%d.%d.%d%c", &d1, &d2, &d3, &d4, &ch) == 4 &&
+ 0 <= d1 && d1 <= 255 && 0 <= d2 && d2 <= 255 &&
+ 0 <= d3 && d3 <= 255 && 0 <= d4 && d4 <= 255) {
+ struct sockaddr_in *sin;
+ sin = (struct sockaddr_in *)addr_ret;
+ sin->sin_addr.s_addr = htonl(
+ ((long) d1 << 24) | ((long) d2 << 16) |
+ ((long) d3 << 8) | ((long) d4 << 0));
+ sin->sin_family = AF_INET;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin->sin_len = sizeof(*sin);
-#endif
- return 4;
- }
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = af;
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(name, NULL, &hints, &res);
+ sin->sin_len = sizeof(*sin);
+#endif
+ return 4;
+ }
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = af;
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(name, NULL, &hints, &res);
#if defined(__digital__) && defined(__unix__)
- if (error == EAI_NONAME && af == AF_UNSPEC) {
- /* On Tru64 V5.1, numeric-to-addr conversion fails
- if no address family is given. Assume IPv4 for now.*/
- hints.ai_family = AF_INET;
- error = getaddrinfo(name, NULL, &hints, &res);
- }
-#endif
- Py_END_ALLOW_THREADS
- RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
- if (error) {
- set_gaierror(error);
- return -1;
- }
- if (res->ai_addrlen < addr_ret_size)
- addr_ret_size = res->ai_addrlen;
- memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
- freeaddrinfo(res);
- switch (addr_ret->sa_family) {
- case AF_INET:
- return 4;
+ if (error == EAI_NONAME && af == AF_UNSPEC) {
+ /* On Tru64 V5.1, numeric-to-addr conversion fails
+ if no address family is given. Assume IPv4 for now.*/
+ hints.ai_family = AF_INET;
+ error = getaddrinfo(name, NULL, &hints, &res);
+ }
+#endif
+ Py_END_ALLOW_THREADS
+ RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
+ if (error) {
+ set_gaierror(error);
+ return -1;
+ }
+ if (res->ai_addrlen < addr_ret_size)
+ addr_ret_size = res->ai_addrlen;
+ memcpy((char *) addr_ret, res->ai_addr, addr_ret_size);
+ freeaddrinfo(res);
+ switch (addr_ret->sa_family) {
+ case AF_INET:
+ return 4;
#ifdef ENABLE_IPV6
- case AF_INET6:
- return 16;
+ case AF_INET6:
+ return 16;
#endif
- default:
- PyErr_SetString(socket_error, "unknown address family");
- return -1;
- }
+ default:
+ PyErr_SetString(socket_error, "unknown address family");
+ return -1;
+ }
}
@@ -902,16 +902,16 @@ setipaddr(char *name, struct sockaddr *addr_ret, size_t addr_ret_size, int af)
static PyObject *
makeipaddr(struct sockaddr *addr, int addrlen)
{
- char buf[NI_MAXHOST];
- int error;
-
- error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
- NI_NUMERICHOST);
- if (error) {
- set_gaierror(error);
- return NULL;
- }
- return PyString_FromString(buf);
+ char buf[NI_MAXHOST];
+ int error;
+
+ error = getnameinfo(addr, addrlen, buf, sizeof(buf), NULL, 0,
+ NI_NUMERICHOST);
+ if (error) {
+ set_gaierror(error);
+ return NULL;
+ }
+ return PyString_FromString(buf);
}
@@ -923,24 +923,24 @@ makeipaddr(struct sockaddr *addr, int addrlen)
static int
setbdaddr(char *name, bdaddr_t *bdaddr)
{
- unsigned int b0, b1, b2, b3, b4, b5;
- char ch;
- int n;
-
- n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
- &b5, &b4, &b3, &b2, &b1, &b0, &ch);
- if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
- bdaddr->b[0] = b0;
- bdaddr->b[1] = b1;
- bdaddr->b[2] = b2;
- bdaddr->b[3] = b3;
- bdaddr->b[4] = b4;
- bdaddr->b[5] = b5;
- return 6;
- } else {
- PyErr_SetString(socket_error, "bad bluetooth address");
- return -1;
- }
+ unsigned int b0, b1, b2, b3, b4, b5;
+ char ch;
+ int n;
+
+ n = sscanf(name, "%X:%X:%X:%X:%X:%X%c",
+ &b5, &b4, &b3, &b2, &b1, &b0, &ch);
+ if (n == 6 && (b0 | b1 | b2 | b3 | b4 | b5) < 256) {
+ bdaddr->b[0] = b0;
+ bdaddr->b[1] = b1;
+ bdaddr->b[2] = b2;
+ bdaddr->b[3] = b3;
+ bdaddr->b[4] = b4;
+ bdaddr->b[5] = b5;
+ return 6;
+ } else {
+ PyErr_SetString(socket_error, "bad bluetooth address");
+ return -1;
+ }
}
/* Create a string representation of the Bluetooth address. This is always a
@@ -950,12 +950,12 @@ setbdaddr(char *name, bdaddr_t *bdaddr)
static PyObject *
makebdaddr(bdaddr_t *bdaddr)
{
- char buf[(6 * 2) + 5 + 1];
+ char buf[(6 * 2) + 5 + 1];
- sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
- bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
- bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
- return PyString_FromString(buf);
+ sprintf(buf, "%02X:%02X:%02X:%02X:%02X:%02X",
+ bdaddr->b[5], bdaddr->b[4], bdaddr->b[3],
+ bdaddr->b[2], bdaddr->b[1], bdaddr->b[0]);
+ return PyString_FromString(buf);
}
#endif
@@ -969,199 +969,199 @@ makebdaddr(bdaddr_t *bdaddr)
static PyObject *
makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
{
- if (addrlen == 0) {
- /* No address -- may be recvfrom() from known socket */
- Py_INCREF(Py_None);
- return Py_None;
- }
+ if (addrlen == 0) {
+ /* No address -- may be recvfrom() from known socket */
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
#ifdef __BEOS__
- /* XXX: BeOS version of accept() doesn't set family correctly */
- addr->sa_family = AF_INET;
+ /* XXX: BeOS version of accept() doesn't set family correctly */
+ addr->sa_family = AF_INET;
#endif
- switch (addr->sa_family) {
+ switch (addr->sa_family) {
- case AF_INET:
- {
- struct sockaddr_in *a;
- PyObject *addrobj = makeipaddr(addr, sizeof(*a));
- PyObject *ret = NULL;
- if (addrobj) {
- a = (struct sockaddr_in *)addr;
- ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
- Py_DECREF(addrobj);
- }
- return ret;
- }
+ case AF_INET:
+ {
+ struct sockaddr_in *a;
+ PyObject *addrobj = makeipaddr(addr, sizeof(*a));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ a = (struct sockaddr_in *)addr;
+ ret = Py_BuildValue("Oi", addrobj, ntohs(a->sin_port));
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
#if defined(AF_UNIX)
- case AF_UNIX:
- {
- struct sockaddr_un *a = (struct sockaddr_un *) addr;
+ case AF_UNIX:
+ {
+ struct sockaddr_un *a = (struct sockaddr_un *) addr;
#ifdef linux
- if (a->sun_path[0] == 0) { /* Linux abstract namespace */
- addrlen -= offsetof(struct sockaddr_un, sun_path);
- return PyString_FromStringAndSize(a->sun_path,
- addrlen);
- }
- else
+ if (a->sun_path[0] == 0) { /* Linux abstract namespace */
+ addrlen -= offsetof(struct sockaddr_un, sun_path);
+ return PyString_FromStringAndSize(a->sun_path,
+ addrlen);
+ }
+ else
#endif /* linux */
- {
- /* regular NULL-terminated string */
- return PyString_FromString(a->sun_path);
- }
- }
+ {
+ /* regular NULL-terminated string */
+ return PyString_FromString(a->sun_path);
+ }
+ }
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
case AF_NETLINK:
{
- struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
- return Py_BuildValue("II", a->nl_pid, a->nl_groups);
+ struct sockaddr_nl *a = (struct sockaddr_nl *) addr;
+ return Py_BuildValue("II", a->nl_pid, a->nl_groups);
}
#endif /* AF_NETLINK */
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6 *a;
- PyObject *addrobj = makeipaddr(addr, sizeof(*a));
- PyObject *ret = NULL;
- if (addrobj) {
- a = (struct sockaddr_in6 *)addr;
- ret = Py_BuildValue("Oiii",
- addrobj,
- ntohs(a->sin6_port),
- a->sin6_flowinfo,
- a->sin6_scope_id);
- Py_DECREF(addrobj);
- }
- return ret;
- }
+ case AF_INET6:
+ {
+ struct sockaddr_in6 *a;
+ PyObject *addrobj = makeipaddr(addr, sizeof(*a));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ a = (struct sockaddr_in6 *)addr;
+ ret = Py_BuildValue("Oiii",
+ addrobj,
+ ntohs(a->sin6_port),
+ a->sin6_flowinfo,
+ a->sin6_scope_id);
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
#endif
#ifdef USE_BLUETOOTH
- case AF_BLUETOOTH:
- switch (proto) {
-
- case BTPROTO_L2CAP:
- {
- struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
- PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
- PyObject *ret = NULL;
- if (addrobj) {
- ret = Py_BuildValue("Oi",
- addrobj,
- _BT_L2_MEMB(a, psm));
- Py_DECREF(addrobj);
- }
- return ret;
- }
-
- case BTPROTO_RFCOMM:
- {
- struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
- PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
- PyObject *ret = NULL;
- if (addrobj) {
- ret = Py_BuildValue("Oi",
- addrobj,
- _BT_RC_MEMB(a, channel));
- Py_DECREF(addrobj);
- }
- return ret;
- }
-
- case BTPROTO_HCI:
- {
- struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
- PyObject *ret = NULL;
- ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
- return ret;
- }
+ case AF_BLUETOOTH:
+ switch (proto) {
+
+ case BTPROTO_L2CAP:
+ {
+ struct sockaddr_l2 *a = (struct sockaddr_l2 *) addr;
+ PyObject *addrobj = makebdaddr(&_BT_L2_MEMB(a, bdaddr));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ ret = Py_BuildValue("Oi",
+ addrobj,
+ _BT_L2_MEMB(a, psm));
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
+
+ case BTPROTO_RFCOMM:
+ {
+ struct sockaddr_rc *a = (struct sockaddr_rc *) addr;
+ PyObject *addrobj = makebdaddr(&_BT_RC_MEMB(a, bdaddr));
+ PyObject *ret = NULL;
+ if (addrobj) {
+ ret = Py_BuildValue("Oi",
+ addrobj,
+ _BT_RC_MEMB(a, channel));
+ Py_DECREF(addrobj);
+ }
+ return ret;
+ }
+
+ case BTPROTO_HCI:
+ {
+ struct sockaddr_hci *a = (struct sockaddr_hci *) addr;
+ PyObject *ret = NULL;
+ ret = Py_BuildValue("i", _BT_HCI_MEMB(a, dev));
+ return ret;
+ }
#if !defined(__FreeBSD__)
- case BTPROTO_SCO:
- {
- struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
- return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
- }
+ case BTPROTO_SCO:
+ {
+ struct sockaddr_sco *a = (struct sockaddr_sco *) addr;
+ return makebdaddr(&_BT_SCO_MEMB(a, bdaddr));
+ }
#endif
- default:
- PyErr_SetString(PyExc_ValueError,
- "Unknown Bluetooth protocol");
- return NULL;
- }
+ default:
+ PyErr_SetString(PyExc_ValueError,
+ "Unknown Bluetooth protocol");
+ return NULL;
+ }
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- case AF_PACKET:
- {
- struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
- char *ifname = "";
- struct ifreq ifr;
- /* need to look up interface name give index */
- if (a->sll_ifindex) {
- ifr.ifr_ifindex = a->sll_ifindex;
- if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
- ifname = ifr.ifr_name;
- }
- return Py_BuildValue("shbhs#",
- ifname,
- ntohs(a->sll_protocol),
- a->sll_pkttype,
- a->sll_hatype,
- a->sll_addr,
- a->sll_halen);
- }
+ case AF_PACKET:
+ {
+ struct sockaddr_ll *a = (struct sockaddr_ll *)addr;
+ char *ifname = "";
+ struct ifreq ifr;
+ /* need to look up interface name give index */
+ if (a->sll_ifindex) {
+ ifr.ifr_ifindex = a->sll_ifindex;
+ if (ioctl(sockfd, SIOCGIFNAME, &ifr) == 0)
+ ifname = ifr.ifr_name;
+ }
+ return Py_BuildValue("shbhs#",
+ ifname,
+ ntohs(a->sll_protocol),
+ a->sll_pkttype,
+ a->sll_hatype,
+ a->sll_addr,
+ a->sll_halen);
+ }
#endif
#ifdef HAVE_LINUX_TIPC_H
- case AF_TIPC:
- {
- struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
- if (a->addrtype == TIPC_ADDR_NAMESEQ) {
- return Py_BuildValue("IIIII",
- a->addrtype,
- a->addr.nameseq.type,
- a->addr.nameseq.lower,
- a->addr.nameseq.upper,
- a->scope);
- } else if (a->addrtype == TIPC_ADDR_NAME) {
- return Py_BuildValue("IIIII",
- a->addrtype,
- a->addr.name.name.type,
- a->addr.name.name.instance,
- a->addr.name.name.instance,
- a->scope);
- } else if (a->addrtype == TIPC_ADDR_ID) {
- return Py_BuildValue("IIIII",
- a->addrtype,
- a->addr.id.node,
- a->addr.id.ref,
- 0,
- a->scope);
- } else {
- PyErr_SetString(PyExc_ValueError,
- "Invalid address type");
- return NULL;
- }
- }
-#endif
-
- /* More cases here... */
-
- default:
- /* If we don't know the address family, don't raise an
- exception -- return it as a tuple. */
- return Py_BuildValue("is#",
- addr->sa_family,
- addr->sa_data,
- sizeof(addr->sa_data));
-
- }
+ case AF_TIPC:
+ {
+ struct sockaddr_tipc *a = (struct sockaddr_tipc *) addr;
+ if (a->addrtype == TIPC_ADDR_NAMESEQ) {
+ return Py_BuildValue("IIIII",
+ a->addrtype,
+ a->addr.nameseq.type,
+ a->addr.nameseq.lower,
+ a->addr.nameseq.upper,
+ a->scope);
+ } else if (a->addrtype == TIPC_ADDR_NAME) {
+ return Py_BuildValue("IIIII",
+ a->addrtype,
+ a->addr.name.name.type,
+ a->addr.name.name.instance,
+ a->addr.name.name.instance,
+ a->scope);
+ } else if (a->addrtype == TIPC_ADDR_ID) {
+ return Py_BuildValue("IIIII",
+ a->addrtype,
+ a->addr.id.node,
+ a->addr.id.ref,
+ 0,
+ a->scope);
+ } else {
+ PyErr_SetString(PyExc_ValueError,
+ "Invalid address type");
+ return NULL;
+ }
+ }
+#endif
+
+ /* More cases here... */
+
+ default:
+ /* If we don't know the address family, don't raise an
+ exception -- return it as a tuple. */
+ return Py_BuildValue("is#",
+ addr->sa_family,
+ addr->sa_data,
+ sizeof(addr->sa_data));
+
+ }
}
@@ -1172,346 +1172,346 @@ makesockaddr(int sockfd, struct sockaddr *addr, int addrlen, int proto)
static int
getsockaddrarg(PySocketSockObject *s, PyObject *args,
- struct sockaddr *addr_ret, int *len_ret)
+ struct sockaddr *addr_ret, int *len_ret)
{
- switch (s->sock_family) {
+ switch (s->sock_family) {
#if defined(AF_UNIX)
- case AF_UNIX:
- {
- struct sockaddr_un* addr;
- char *path;
- int len;
- if (!PyArg_Parse(args, "t#", &path, &len))
- return 0;
-
- addr = (struct sockaddr_un*)addr_ret;
+ case AF_UNIX:
+ {
+ struct sockaddr_un* addr;
+ char *path;
+ int len;
+ if (!PyArg_Parse(args, "t#", &path, &len))
+ return 0;
+
+ addr = (struct sockaddr_un*)addr_ret;
#ifdef linux
- if (len > 0 && path[0] == 0) {
- /* Linux abstract namespace extension */
- if (len > sizeof addr->sun_path) {
- PyErr_SetString(socket_error,
- "AF_UNIX path too long");
- return 0;
- }
- }
- else
+ if (len > 0 && path[0] == 0) {
+ /* Linux abstract namespace extension */
+ if (len > sizeof addr->sun_path) {
+ PyErr_SetString(socket_error,
+ "AF_UNIX path too long");
+ return 0;
+ }
+ }
+ else
#endif /* linux */
- {
- /* regular NULL-terminated string */
- if (len >= sizeof addr->sun_path) {
- PyErr_SetString(socket_error,
- "AF_UNIX path too long");
- return 0;
- }
- addr->sun_path[len] = 0;
- }
- addr->sun_family = s->sock_family;
- memcpy(addr->sun_path, path, len);
+ {
+ /* regular NULL-terminated string */
+ if (len >= sizeof addr->sun_path) {
+ PyErr_SetString(socket_error,
+ "AF_UNIX path too long");
+ return 0;
+ }
+ addr->sun_path[len] = 0;
+ }
+ addr->sun_family = s->sock_family;
+ memcpy(addr->sun_path, path, len);
#if defined(PYOS_OS2)
- *len_ret = sizeof(*addr);
+ *len_ret = sizeof(*addr);
#else
- *len_ret = len + offsetof(struct sockaddr_un, sun_path);
+ *len_ret = len + offsetof(struct sockaddr_un, sun_path);
#endif
- return 1;
- }
+ return 1;
+ }
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
- case AF_NETLINK:
- {
- struct sockaddr_nl* addr;
- int pid, groups;
- addr = (struct sockaddr_nl *)addr_ret;
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_NETLINK address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
- return 0;
- addr->nl_family = AF_NETLINK;
- addr->nl_pid = pid;
- addr->nl_groups = groups;
- *len_ret = sizeof(*addr);
- return 1;
- }
-#endif
-
- case AF_INET:
- {
- struct sockaddr_in* addr;
- char *host;
- int port, result;
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_INET address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
- "idna", &host, &port))
- return 0;
- addr=(struct sockaddr_in*)addr_ret;
- result = setipaddr(host, (struct sockaddr *)addr,
- sizeof(*addr), AF_INET);
- PyMem_Free(host);
- if (result < 0)
- return 0;
- if (port < 0 || port > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getsockaddrarg: port must be 0-65535.");
- return 0;
- }
- addr->sin_family = AF_INET;
- addr->sin_port = htons((short)port);
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_NETLINK:
+ {
+ struct sockaddr_nl* addr;
+ int pid, groups;
+ addr = (struct sockaddr_nl *)addr_ret;
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_NETLINK address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "II:getsockaddrarg", &pid, &groups))
+ return 0;
+ addr->nl_family = AF_NETLINK;
+ addr->nl_pid = pid;
+ addr->nl_groups = groups;
+ *len_ret = sizeof(*addr);
+ return 1;
+ }
+#endif
+
+ case AF_INET:
+ {
+ struct sockaddr_in* addr;
+ char *host;
+ int port, result;
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_INET address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "eti:getsockaddrarg",
+ "idna", &host, &port))
+ return 0;
+ addr=(struct sockaddr_in*)addr_ret;
+ result = setipaddr(host, (struct sockaddr *)addr,
+ sizeof(*addr), AF_INET);
+ PyMem_Free(host);
+ if (result < 0)
+ return 0;
+ if (port < 0 || port > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getsockaddrarg: port must be 0-65535.");
+ return 0;
+ }
+ addr->sin_family = AF_INET;
+ addr->sin_port = htons((short)port);
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6* addr;
- char *host;
- int port, flowinfo, scope_id, result;
- flowinfo = scope_id = 0;
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_INET6 address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "eti|ii",
- "idna", &host, &port, &flowinfo,
- &scope_id)) {
- return 0;
- }
- addr = (struct sockaddr_in6*)addr_ret;
- result = setipaddr(host, (struct sockaddr *)addr,
- sizeof(*addr), AF_INET6);
- PyMem_Free(host);
- if (result < 0)
- return 0;
- if (port < 0 || port > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getsockaddrarg: port must be 0-65535.");
- return 0;
- }
- addr->sin6_family = s->sock_family;
- addr->sin6_port = htons((short)port);
- addr->sin6_flowinfo = flowinfo;
- addr->sin6_scope_id = scope_id;
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_INET6:
+ {
+ struct sockaddr_in6* addr;
+ char *host;
+ int port, flowinfo, scope_id, result;
+ flowinfo = scope_id = 0;
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_INET6 address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "eti|ii",
+ "idna", &host, &port, &flowinfo,
+ &scope_id)) {
+ return 0;
+ }
+ addr = (struct sockaddr_in6*)addr_ret;
+ result = setipaddr(host, (struct sockaddr *)addr,
+ sizeof(*addr), AF_INET6);
+ PyMem_Free(host);
+ if (result < 0)
+ return 0;
+ if (port < 0 || port > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getsockaddrarg: port must be 0-65535.");
+ return 0;
+ }
+ addr->sin6_family = s->sock_family;
+ addr->sin6_port = htons((short)port);
+ addr->sin6_flowinfo = flowinfo;
+ addr->sin6_scope_id = scope_id;
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#endif
#ifdef USE_BLUETOOTH
- case AF_BLUETOOTH:
- {
- switch (s->sock_proto) {
- case BTPROTO_L2CAP:
- {
- struct sockaddr_l2 *addr;
- char *straddr;
-
- addr = (struct sockaddr_l2 *)addr_ret;
- memset(addr, 0, sizeof(struct sockaddr_l2));
- _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyArg_ParseTuple(args, "si", &straddr,
- &_BT_L2_MEMB(addr, psm))) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
- return 0;
-
- *len_ret = sizeof *addr;
- return 1;
- }
- case BTPROTO_RFCOMM:
- {
- struct sockaddr_rc *addr;
- char *straddr;
-
- addr = (struct sockaddr_rc *)addr_ret;
- _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyArg_ParseTuple(args, "si", &straddr,
- &_BT_RC_MEMB(addr, channel))) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
- return 0;
-
- *len_ret = sizeof *addr;
- return 1;
- }
- case BTPROTO_HCI:
- {
- struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
- _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
- if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_BLUETOOTH:
+ {
+ switch (s->sock_proto) {
+ case BTPROTO_L2CAP:
+ {
+ struct sockaddr_l2 *addr;
+ char *straddr;
+
+ addr = (struct sockaddr_l2 *)addr_ret;
+ memset(addr, 0, sizeof(struct sockaddr_l2));
+ _BT_L2_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "si", &straddr,
+ &_BT_L2_MEMB(addr, psm))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ if (setbdaddr(straddr, &_BT_L2_MEMB(addr, bdaddr)) < 0)
+ return 0;
+
+ *len_ret = sizeof *addr;
+ return 1;
+ }
+ case BTPROTO_RFCOMM:
+ {
+ struct sockaddr_rc *addr;
+ char *straddr;
+
+ addr = (struct sockaddr_rc *)addr_ret;
+ _BT_RC_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "si", &straddr,
+ &_BT_RC_MEMB(addr, channel))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ if (setbdaddr(straddr, &_BT_RC_MEMB(addr, bdaddr)) < 0)
+ return 0;
+
+ *len_ret = sizeof *addr;
+ return 1;
+ }
+ case BTPROTO_HCI:
+ {
+ struct sockaddr_hci *addr = (struct sockaddr_hci *)addr_ret;
+ _BT_HCI_MEMB(addr, family) = AF_BLUETOOTH;
+ if (!PyArg_ParseTuple(args, "i", &_BT_HCI_MEMB(addr, dev))) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#if !defined(__FreeBSD__)
- case BTPROTO_SCO:
- {
- struct sockaddr_sco *addr;
- char *straddr;
-
- addr = (struct sockaddr_sco *)addr_ret;
- _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
- straddr = PyString_AsString(args);
- if (straddr == NULL) {
- PyErr_SetString(socket_error, "getsockaddrarg: "
- "wrong format");
- return 0;
- }
- if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
- return 0;
-
- *len_ret = sizeof *addr;
- return 1;
- }
-#endif
- default:
- PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
- return 0;
- }
- }
+ case BTPROTO_SCO:
+ {
+ struct sockaddr_sco *addr;
+ char *straddr;
+
+ addr = (struct sockaddr_sco *)addr_ret;
+ _BT_SCO_MEMB(addr, family) = AF_BLUETOOTH;
+ straddr = PyString_AsString(args);
+ if (straddr == NULL) {
+ PyErr_SetString(socket_error, "getsockaddrarg: "
+ "wrong format");
+ return 0;
+ }
+ if (setbdaddr(straddr, &_BT_SCO_MEMB(addr, bdaddr)) < 0)
+ return 0;
+
+ *len_ret = sizeof *addr;
+ return 1;
+ }
+#endif
+ default:
+ PyErr_SetString(socket_error, "getsockaddrarg: unknown Bluetooth protocol");
+ return 0;
+ }
+ }
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- case AF_PACKET:
- {
- struct sockaddr_ll* addr;
- struct ifreq ifr;
- char *interfaceName;
- int protoNumber;
- int hatype = 0;
- int pkttype = 0;
- char *haddr = NULL;
- unsigned int halen = 0;
-
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_PACKET address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
- if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
- &protoNumber, &pkttype, &hatype,
- &haddr, &halen))
- return 0;
- strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
- ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
- if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
- s->errorhandler();
- return 0;
- }
- if (halen > 8) {
- PyErr_SetString(PyExc_ValueError,
- "Hardware address must be 8 bytes or less");
- return 0;
- }
- if (protoNumber < 0 || protoNumber > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getsockaddrarg: protoNumber must be 0-65535.");
- return 0;
- }
- addr = (struct sockaddr_ll*)addr_ret;
- addr->sll_family = AF_PACKET;
- addr->sll_protocol = htons((short)protoNumber);
- addr->sll_ifindex = ifr.ifr_ifindex;
- addr->sll_pkttype = pkttype;
- addr->sll_hatype = hatype;
- if (halen != 0) {
- memcpy(&addr->sll_addr, haddr, halen);
- }
- addr->sll_halen = halen;
- *len_ret = sizeof *addr;
- return 1;
- }
+ case AF_PACKET:
+ {
+ struct sockaddr_ll* addr;
+ struct ifreq ifr;
+ char *interfaceName;
+ int protoNumber;
+ int hatype = 0;
+ int pkttype = 0;
+ char *haddr = NULL;
+ unsigned int halen = 0;
+
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_PACKET address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+ if (!PyArg_ParseTuple(args, "si|iis#", &interfaceName,
+ &protoNumber, &pkttype, &hatype,
+ &haddr, &halen))
+ return 0;
+ strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
+ ifr.ifr_name[(sizeof(ifr.ifr_name))-1] = '\0';
+ if (ioctl(s->sock_fd, SIOCGIFINDEX, &ifr) < 0) {
+ s->errorhandler();
+ return 0;
+ }
+ if (halen > 8) {
+ PyErr_SetString(PyExc_ValueError,
+ "Hardware address must be 8 bytes or less");
+ return 0;
+ }
+ if (protoNumber < 0 || protoNumber > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getsockaddrarg: protoNumber must be 0-65535.");
+ return 0;
+ }
+ addr = (struct sockaddr_ll*)addr_ret;
+ addr->sll_family = AF_PACKET;
+ addr->sll_protocol = htons((short)protoNumber);
+ addr->sll_ifindex = ifr.ifr_ifindex;
+ addr->sll_pkttype = pkttype;
+ addr->sll_hatype = hatype;
+ if (halen != 0) {
+ memcpy(&addr->sll_addr, haddr, halen);
+ }
+ addr->sll_halen = halen;
+ *len_ret = sizeof *addr;
+ return 1;
+ }
#endif
#ifdef HAVE_LINUX_TIPC_H
- case AF_TIPC:
- {
- unsigned int atype, v1, v2, v3;
- unsigned int scope = TIPC_CLUSTER_SCOPE;
- struct sockaddr_tipc *addr;
-
- if (!PyTuple_Check(args)) {
- PyErr_Format(
- PyExc_TypeError,
- "getsockaddrarg: "
- "AF_TIPC address must be tuple, not %.500s",
- Py_TYPE(args)->tp_name);
- return 0;
- }
-
- if (!PyArg_ParseTuple(args,
- "IIII|I;Invalid TIPC address format",
- &atype, &v1, &v2, &v3, &scope))
- return 0;
-
- addr = (struct sockaddr_tipc *) addr_ret;
- memset(addr, 0, sizeof(struct sockaddr_tipc));
-
- addr->family = AF_TIPC;
- addr->scope = scope;
- addr->addrtype = atype;
-
- if (atype == TIPC_ADDR_NAMESEQ) {
- addr->addr.nameseq.type = v1;
- addr->addr.nameseq.lower = v2;
- addr->addr.nameseq.upper = v3;
- } else if (atype == TIPC_ADDR_NAME) {
- addr->addr.name.name.type = v1;
- addr->addr.name.name.instance = v2;
- } else if (atype == TIPC_ADDR_ID) {
- addr->addr.id.node = v1;
- addr->addr.id.ref = v2;
- } else {
- /* Shouldn't happen */
- PyErr_SetString(PyExc_TypeError, "Invalid address type");
- return 0;
- }
-
- *len_ret = sizeof(*addr);
-
- return 1;
- }
-#endif
-
- /* More cases here... */
-
- default:
- PyErr_SetString(socket_error, "getsockaddrarg: bad family");
- return 0;
-
- }
+ case AF_TIPC:
+ {
+ unsigned int atype, v1, v2, v3;
+ unsigned int scope = TIPC_CLUSTER_SCOPE;
+ struct sockaddr_tipc *addr;
+
+ if (!PyTuple_Check(args)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "getsockaddrarg: "
+ "AF_TIPC address must be tuple, not %.500s",
+ Py_TYPE(args)->tp_name);
+ return 0;
+ }
+
+ if (!PyArg_ParseTuple(args,
+ "IIII|I;Invalid TIPC address format",
+ &atype, &v1, &v2, &v3, &scope))
+ return 0;
+
+ addr = (struct sockaddr_tipc *) addr_ret;
+ memset(addr, 0, sizeof(struct sockaddr_tipc));
+
+ addr->family = AF_TIPC;
+ addr->scope = scope;
+ addr->addrtype = atype;
+
+ if (atype == TIPC_ADDR_NAMESEQ) {
+ addr->addr.nameseq.type = v1;
+ addr->addr.nameseq.lower = v2;
+ addr->addr.nameseq.upper = v3;
+ } else if (atype == TIPC_ADDR_NAME) {
+ addr->addr.name.name.type = v1;
+ addr->addr.name.name.instance = v2;
+ } else if (atype == TIPC_ADDR_ID) {
+ addr->addr.id.node = v1;
+ addr->addr.id.ref = v2;
+ } else {
+ /* Shouldn't happen */
+ PyErr_SetString(PyExc_TypeError, "Invalid address type");
+ return 0;
+ }
+
+ *len_ret = sizeof(*addr);
+
+ return 1;
+ }
+#endif
+
+ /* More cases here... */
+
+ default:
+ PyErr_SetString(socket_error, "getsockaddrarg: bad family");
+ return 0;
+
+ }
}
@@ -1522,89 +1522,89 @@ getsockaddrarg(PySocketSockObject *s, PyObject *args,
static int
getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
{
- switch (s->sock_family) {
+ switch (s->sock_family) {
#if defined(AF_UNIX)
- case AF_UNIX:
- {
- *len_ret = sizeof (struct sockaddr_un);
- return 1;
- }
+ case AF_UNIX:
+ {
+ *len_ret = sizeof (struct sockaddr_un);
+ return 1;
+ }
#endif /* AF_UNIX */
#if defined(AF_NETLINK)
case AF_NETLINK:
{
- *len_ret = sizeof (struct sockaddr_nl);
- return 1;
+ *len_ret = sizeof (struct sockaddr_nl);
+ return 1;
}
#endif
- case AF_INET:
- {
- *len_ret = sizeof (struct sockaddr_in);
- return 1;
- }
+ case AF_INET:
+ {
+ *len_ret = sizeof (struct sockaddr_in);
+ return 1;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- *len_ret = sizeof (struct sockaddr_in6);
- return 1;
- }
+ case AF_INET6:
+ {
+ *len_ret = sizeof (struct sockaddr_in6);
+ return 1;
+ }
#endif
#ifdef USE_BLUETOOTH
- case AF_BLUETOOTH:
- {
- switch(s->sock_proto)
- {
-
- case BTPROTO_L2CAP:
- *len_ret = sizeof (struct sockaddr_l2);
- return 1;
- case BTPROTO_RFCOMM:
- *len_ret = sizeof (struct sockaddr_rc);
- return 1;
- case BTPROTO_HCI:
- *len_ret = sizeof (struct sockaddr_hci);
- return 1;
+ case AF_BLUETOOTH:
+ {
+ switch(s->sock_proto)
+ {
+
+ case BTPROTO_L2CAP:
+ *len_ret = sizeof (struct sockaddr_l2);
+ return 1;
+ case BTPROTO_RFCOMM:
+ *len_ret = sizeof (struct sockaddr_rc);
+ return 1;
+ case BTPROTO_HCI:
+ *len_ret = sizeof (struct sockaddr_hci);
+ return 1;
#if !defined(__FreeBSD__)
- case BTPROTO_SCO:
- *len_ret = sizeof (struct sockaddr_sco);
- return 1;
+ case BTPROTO_SCO:
+ *len_ret = sizeof (struct sockaddr_sco);
+ return 1;
#endif
- default:
- PyErr_SetString(socket_error, "getsockaddrlen: "
- "unknown BT protocol");
- return 0;
+ default:
+ PyErr_SetString(socket_error, "getsockaddrlen: "
+ "unknown BT protocol");
+ return 0;
- }
- }
+ }
+ }
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- case AF_PACKET:
- {
- *len_ret = sizeof (struct sockaddr_ll);
- return 1;
- }
+ case AF_PACKET:
+ {
+ *len_ret = sizeof (struct sockaddr_ll);
+ return 1;
+ }
#endif
#ifdef HAVE_LINUX_TIPC_H
- case AF_TIPC:
- {
- *len_ret = sizeof (struct sockaddr_tipc);
- return 1;
- }
+ case AF_TIPC:
+ {
+ *len_ret = sizeof (struct sockaddr_tipc);
+ return 1;
+ }
#endif
- /* More cases here... */
+ /* More cases here... */
- default:
- PyErr_SetString(socket_error, "getsockaddrlen: bad family");
- return 0;
+ default:
+ PyErr_SetString(socket_error, "getsockaddrlen: bad family");
+ return 0;
- }
+ }
}
@@ -1613,67 +1613,67 @@ getsockaddrlen(PySocketSockObject *s, socklen_t *len_ret)
static PyObject *
sock_accept(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- SOCKET_T newfd;
- socklen_t addrlen;
- PyObject *sock = NULL;
- PyObject *addr = NULL;
- PyObject *res = NULL;
- int timeout;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
+ sock_addr_t addrbuf;
+ SOCKET_T newfd;
+ socklen_t addrlen;
+ PyObject *sock = NULL;
+ PyObject *addr = NULL;
+ PyObject *res = NULL;
+ int timeout;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
#ifdef MS_WINDOWS
- newfd = INVALID_SOCKET;
+ newfd = INVALID_SOCKET;
#else
- newfd = -1;
+ newfd = -1;
#endif
- if (!IS_SELECTABLE(s))
- return select_error();
+ if (!IS_SELECTABLE(s))
+ return select_error();
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 0);
- if (!timeout)
- newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 0);
+ if (!timeout)
+ newfd = accept(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
+ Py_END_ALLOW_THREADS
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
#ifdef MS_WINDOWS
- if (newfd == INVALID_SOCKET)
+ if (newfd == INVALID_SOCKET)
#else
- if (newfd < 0)
+ if (newfd < 0)
#endif
- return s->errorhandler();
+ return s->errorhandler();
- /* Create the new object with unspecified family,
- to avoid calls to bind() etc. on it. */
- sock = (PyObject *) new_sockobject(newfd,
- s->sock_family,
- s->sock_type,
- s->sock_proto);
+ /* Create the new object with unspecified family,
+ to avoid calls to bind() etc. on it. */
+ sock = (PyObject *) new_sockobject(newfd,
+ s->sock_family,
+ s->sock_type,
+ s->sock_proto);
- if (sock == NULL) {
- SOCKETCLOSE(newfd);
- goto finally;
- }
- addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
- addrlen, s->sock_proto);
- if (addr == NULL)
- goto finally;
+ if (sock == NULL) {
+ SOCKETCLOSE(newfd);
+ goto finally;
+ }
+ addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
+ addrlen, s->sock_proto);
+ if (addr == NULL)
+ goto finally;
- res = PyTuple_Pack(2, sock, addr);
+ res = PyTuple_Pack(2, sock, addr);
finally:
- Py_XDECREF(sock);
- Py_XDECREF(addr);
- return res;
+ Py_XDECREF(sock);
+ Py_XDECREF(addr);
+ return res;
}
PyDoc_STRVAR(accept_doc,
@@ -1691,17 +1691,17 @@ info is a pair (hostaddr, port).");
static PyObject *
sock_setblocking(PySocketSockObject *s, PyObject *arg)
{
- int block;
+ int block;
- block = PyInt_AsLong(arg);
- if (block == -1 && PyErr_Occurred())
- return NULL;
+ block = PyInt_AsLong(arg);
+ if (block == -1 && PyErr_Occurred())
+ return NULL;
- s->sock_timeout = block ? -1.0 : 0.0;
- internal_setblocking(s, block);
+ s->sock_timeout = block ? -1.0 : 0.0;
+ internal_setblocking(s, block);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setblocking_doc,
@@ -1720,25 +1720,25 @@ setblocking(False) is equivalent to settimeout(0.0).");
static PyObject *
sock_settimeout(PySocketSockObject *s, PyObject *arg)
{
- double timeout;
-
- if (arg == Py_None)
- timeout = -1.0;
- else {
- timeout = PyFloat_AsDouble(arg);
- if (timeout < 0.0) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_ValueError,
- "Timeout value out of range");
- return NULL;
- }
- }
-
- s->sock_timeout = timeout;
- internal_setblocking(s, timeout < 0.0);
-
- Py_INCREF(Py_None);
- return Py_None;
+ double timeout;
+
+ if (arg == Py_None)
+ timeout = -1.0;
+ else {
+ timeout = PyFloat_AsDouble(arg);
+ if (timeout < 0.0) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_ValueError,
+ "Timeout value out of range");
+ return NULL;
+ }
+ }
+
+ s->sock_timeout = timeout;
+ internal_setblocking(s, timeout < 0.0);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(settimeout_doc,
@@ -1754,12 +1754,12 @@ Setting a timeout of zero is the same as setblocking(0).");
static PyObject *
sock_gettimeout(PySocketSockObject *s)
{
- if (s->sock_timeout < 0.0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyFloat_FromDouble(s->sock_timeout);
+ if (s->sock_timeout < 0.0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyFloat_FromDouble(s->sock_timeout);
}
PyDoc_STRVAR(gettimeout_doc,
@@ -1775,16 +1775,16 @@ operations are disabled.");
static PyObject *
sock_sleeptaskw(PySocketSockObject *s,PyObject *arg)
{
- int block;
- block = PyInt_AsLong(arg);
- if (block == -1 && PyErr_Occurred())
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
- Py_END_ALLOW_THREADS
-
- Py_INCREF(Py_None);
- return Py_None;
+ int block;
+ block = PyInt_AsLong(arg);
+ if (block == -1 && PyErr_Occurred())
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ socketioctl(s->sock_fd, 0x80046679, (u_long*)&block);
+ Py_END_ALLOW_THREADS
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(sleeptaskw_doc,
"sleeptaskw(flag)\n\
@@ -1801,29 +1801,29 @@ Allow sleeps in taskwindows.");
static PyObject *
sock_setsockopt(PySocketSockObject *s, PyObject *args)
{
- int level;
- int optname;
- int res;
- char *buf;
- int buflen;
- int flag;
-
- if (PyArg_ParseTuple(args, "iii:setsockopt",
- &level, &optname, &flag)) {
- buf = (char *) &flag;
- buflen = sizeof flag;
- }
- else {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "iis#:setsockopt",
- &level, &optname, &buf, &buflen))
- return NULL;
- }
- res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ int level;
+ int optname;
+ int res;
+ char *buf;
+ int buflen;
+ int flag;
+
+ if (PyArg_ParseTuple(args, "iii:setsockopt",
+ &level, &optname, &flag)) {
+ buf = (char *) &flag;
+ buflen = sizeof flag;
+ }
+ else {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "iis#:setsockopt",
+ &level, &optname, &buf, &buflen))
+ return NULL;
+ }
+ res = setsockopt(s->sock_fd, level, optname, (void *)buf, buflen);
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setsockopt_doc,
@@ -1841,53 +1841,53 @@ The value argument can either be an integer or a string.");
static PyObject *
sock_getsockopt(PySocketSockObject *s, PyObject *args)
{
- int level;
- int optname;
- int res;
- PyObject *buf;
- socklen_t buflen = 0;
+ int level;
+ int optname;
+ int res;
+ PyObject *buf;
+ socklen_t buflen = 0;
#ifdef __BEOS__
- /* We have incomplete socket support. */
- PyErr_SetString(socket_error, "getsockopt not supported");
- return NULL;
+ /* We have incomplete socket support. */
+ PyErr_SetString(socket_error, "getsockopt not supported");
+ return NULL;
#else
- if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
- &level, &optname, &buflen))
- return NULL;
-
- if (buflen == 0) {
- int flag = 0;
- socklen_t flagsize = sizeof flag;
- res = getsockopt(s->sock_fd, level, optname,
- (void *)&flag, &flagsize);
- if (res < 0)
- return s->errorhandler();
- return PyInt_FromLong(flag);
- }
+ if (!PyArg_ParseTuple(args, "ii|i:getsockopt",
+ &level, &optname, &buflen))
+ return NULL;
+
+ if (buflen == 0) {
+ int flag = 0;
+ socklen_t flagsize = sizeof flag;
+ res = getsockopt(s->sock_fd, level, optname,
+ (void *)&flag, &flagsize);
+ if (res < 0)
+ return s->errorhandler();
+ return PyInt_FromLong(flag);
+ }
#ifdef __VMS
- /* socklen_t is unsigned so no negative test is needed,
- test buflen == 0 is previously done */
- if (buflen > 1024) {
+ /* socklen_t is unsigned so no negative test is needed,
+ test buflen == 0 is previously done */
+ if (buflen > 1024) {
#else
- if (buflen <= 0 || buflen > 1024) {
-#endif
- PyErr_SetString(socket_error,
- "getsockopt buflen out of range");
- return NULL;
- }
- buf = PyString_FromStringAndSize((char *)NULL, buflen);
- if (buf == NULL)
- return NULL;
- res = getsockopt(s->sock_fd, level, optname,
- (void *)PyString_AS_STRING(buf), &buflen);
- if (res < 0) {
- Py_DECREF(buf);
- return s->errorhandler();
- }
- _PyString_Resize(&buf, buflen);
- return buf;
+ if (buflen <= 0 || buflen > 1024) {
+#endif
+ PyErr_SetString(socket_error,
+ "getsockopt buflen out of range");
+ return NULL;
+ }
+ buf = PyString_FromStringAndSize((char *)NULL, buflen);
+ if (buf == NULL)
+ return NULL;
+ res = getsockopt(s->sock_fd, level, optname,
+ (void *)PyString_AS_STRING(buf), &buflen);
+ if (res < 0) {
+ Py_DECREF(buf);
+ return s->errorhandler();
+ }
+ _PyString_Resize(&buf, buflen);
+ return buf;
#endif /* __BEOS__ */
}
@@ -1904,19 +1904,19 @@ string of that length; otherwise it is an integer.");
static PyObject *
sock_bind(PySocketSockObject *s, PyObject *addro)
{
- sock_addr_t addrbuf;
- int addrlen;
- int res;
-
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ sock_addr_t addrbuf;
+ int addrlen;
+ int res;
+
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ res = bind(s->sock_fd, SAS2SA(&addrbuf), addrlen);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(bind_doc,
@@ -1934,16 +1934,16 @@ sockets the address is a tuple (ifname, proto [,pkttype [,hatype]])");
static PyObject *
sock_close(PySocketSockObject *s)
{
- SOCKET_T fd;
-
- if ((fd = s->sock_fd) != -1) {
- s->sock_fd = -1;
- Py_BEGIN_ALLOW_THREADS
- (void) SOCKETCLOSE(fd);
- Py_END_ALLOW_THREADS
- }
- Py_INCREF(Py_None);
- return Py_None;
+ SOCKET_T fd;
+
+ if ((fd = s->sock_fd) != -1) {
+ s->sock_fd = -1;
+ Py_BEGIN_ALLOW_THREADS
+ (void) SOCKETCLOSE(fd);
+ Py_END_ALLOW_THREADS
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(close_doc,
@@ -1953,90 +1953,90 @@ Close the socket. It cannot be used after this call.");
static int
internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
- int *timeoutp)
+ int *timeoutp)
{
- int res, timeout;
+ int res, timeout;
- timeout = 0;
- res = connect(s->sock_fd, addr, addrlen);
+ timeout = 0;
+ res = connect(s->sock_fd, addr, addrlen);
#ifdef MS_WINDOWS
- if (s->sock_timeout > 0.0) {
- if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
- IS_SELECTABLE(s)) {
- /* This is a mess. Best solution: trust select */
- fd_set fds;
- fd_set fds_exc;
- struct timeval tv;
- tv.tv_sec = (int)s->sock_timeout;
- tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
- FD_ZERO(&fds);
- FD_SET(s->sock_fd, &fds);
- FD_ZERO(&fds_exc);
- FD_SET(s->sock_fd, &fds_exc);
- res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
- if (res == 0) {
- res = WSAEWOULDBLOCK;
- timeout = 1;
- } else if (res > 0) {
- if (FD_ISSET(s->sock_fd, &fds))
- /* The socket is in the writeable set - this
- means connected */
- res = 0;
- else {
- /* As per MS docs, we need to call getsockopt()
- to get the underlying error */
- int res_size = sizeof res;
- /* It must be in the exception set */
- assert(FD_ISSET(s->sock_fd, &fds_exc));
- if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
- (char *)&res, &res_size))
- /* getsockopt also clears WSAGetLastError,
- so reset it back. */
- WSASetLastError(res);
- else
- res = WSAGetLastError();
- }
- }
- /* else if (res < 0) an error occurred */
- }
- }
-
- if (res < 0)
- res = WSAGetLastError();
+ if (s->sock_timeout > 0.0) {
+ if (res < 0 && WSAGetLastError() == WSAEWOULDBLOCK &&
+ IS_SELECTABLE(s)) {
+ /* This is a mess. Best solution: trust select */
+ fd_set fds;
+ fd_set fds_exc;
+ struct timeval tv;
+ tv.tv_sec = (int)s->sock_timeout;
+ tv.tv_usec = (int)((s->sock_timeout - tv.tv_sec) * 1e6);
+ FD_ZERO(&fds);
+ FD_SET(s->sock_fd, &fds);
+ FD_ZERO(&fds_exc);
+ FD_SET(s->sock_fd, &fds_exc);
+ res = select(s->sock_fd+1, NULL, &fds, &fds_exc, &tv);
+ if (res == 0) {
+ res = WSAEWOULDBLOCK;
+ timeout = 1;
+ } else if (res > 0) {
+ if (FD_ISSET(s->sock_fd, &fds))
+ /* The socket is in the writeable set - this
+ means connected */
+ res = 0;
+ else {
+ /* As per MS docs, we need to call getsockopt()
+ to get the underlying error */
+ int res_size = sizeof res;
+ /* It must be in the exception set */
+ assert(FD_ISSET(s->sock_fd, &fds_exc));
+ if (0 == getsockopt(s->sock_fd, SOL_SOCKET, SO_ERROR,
+ (char *)&res, &res_size))
+ /* getsockopt also clears WSAGetLastError,
+ so reset it back. */
+ WSASetLastError(res);
+ else
+ res = WSAGetLastError();
+ }
+ }
+ /* else if (res < 0) an error occurred */
+ }
+ }
+
+ if (res < 0)
+ res = WSAGetLastError();
#else
- if (s->sock_timeout > 0.0) {
- if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
- timeout = internal_select(s, 1);
- if (timeout == 0) {
- /* Bug #1019808: in case of an EINPROGRESS,
- use getsockopt(SO_ERROR) to get the real
- error. */
- socklen_t res_size = sizeof res;
- (void)getsockopt(s->sock_fd, SOL_SOCKET,
- SO_ERROR, &res, &res_size);
- if (res == EISCONN)
- res = 0;
- errno = res;
- }
- else if (timeout == -1) {
- res = errno; /* had error */
- }
- else
- res = EWOULDBLOCK; /* timed out */
- }
- }
-
- if (res < 0)
- res = errno;
-
-#endif
- *timeoutp = timeout;
-
- return res;
+ if (s->sock_timeout > 0.0) {
+ if (res < 0 && errno == EINPROGRESS && IS_SELECTABLE(s)) {
+ timeout = internal_select(s, 1);
+ if (timeout == 0) {
+ /* Bug #1019808: in case of an EINPROGRESS,
+ use getsockopt(SO_ERROR) to get the real
+ error. */
+ socklen_t res_size = sizeof res;
+ (void)getsockopt(s->sock_fd, SOL_SOCKET,
+ SO_ERROR, &res, &res_size);
+ if (res == EISCONN)
+ res = 0;
+ errno = res;
+ }
+ else if (timeout == -1) {
+ res = errno; /* had error */
+ }
+ else
+ res = EWOULDBLOCK; /* timed out */
+ }
+ }
+
+ if (res < 0)
+ res = errno;
+
+#endif
+ *timeoutp = timeout;
+
+ return res;
}
/* s.connect(sockaddr) method */
@@ -2044,26 +2044,26 @@ internal_connect(PySocketSockObject *s, struct sockaddr *addr, int addrlen,
static PyObject *
sock_connect(PySocketSockObject *s, PyObject *addro)
{
- sock_addr_t addrbuf;
- int addrlen;
- int res;
- int timeout;
-
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (res != 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ sock_addr_t addrbuf;
+ int addrlen;
+ int res;
+ int timeout;
+
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (res != 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(connect_doc,
@@ -2078,26 +2078,26 @@ is a pair (host, port).");
static PyObject *
sock_connect_ex(PySocketSockObject *s, PyObject *addro)
{
- sock_addr_t addrbuf;
- int addrlen;
- int res;
- int timeout;
+ sock_addr_t addrbuf;
+ int addrlen;
+ int res;
+ int timeout;
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
- return NULL;
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ res = internal_connect(s, SAS2SA(&addrbuf), addrlen, &timeout);
+ Py_END_ALLOW_THREADS
- /* Signals are not errors (though they may raise exceptions). Adapted
- from PyErr_SetFromErrnoWithFilenameObject(). */
+ /* Signals are not errors (though they may raise exceptions). Adapted
+ from PyErr_SetFromErrnoWithFilenameObject(). */
#ifdef EINTR
- if (res == EINTR && PyErr_CheckSignals())
- return NULL;
+ if (res == EINTR && PyErr_CheckSignals())
+ return NULL;
#endif
- return PyInt_FromLong((long) res);
+ return PyInt_FromLong((long) res);
}
PyDoc_STRVAR(connect_ex_doc,
@@ -2113,9 +2113,9 @@ static PyObject *
sock_fileno(PySocketSockObject *s)
{
#if SIZEOF_SOCKET_T <= SIZEOF_LONG
- return PyInt_FromLong((long) s->sock_fd);
+ return PyInt_FromLong((long) s->sock_fd);
#else
- return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
+ return PyLong_FromLongLong((PY_LONG_LONG)s->sock_fd);
#endif
}
@@ -2131,19 +2131,19 @@ Return the integer file descriptor of the socket.");
static PyObject *
sock_dup(PySocketSockObject *s)
{
- SOCKET_T newfd;
- PyObject *sock;
-
- newfd = dup(s->sock_fd);
- if (newfd < 0)
- return s->errorhandler();
- sock = (PyObject *) new_sockobject(newfd,
- s->sock_family,
- s->sock_type,
- s->sock_proto);
- if (sock == NULL)
- SOCKETCLOSE(newfd);
- return sock;
+ SOCKET_T newfd;
+ PyObject *sock;
+
+ newfd = dup(s->sock_fd);
+ if (newfd < 0)
+ return s->errorhandler();
+ sock = (PyObject *) new_sockobject(newfd,
+ s->sock_family,
+ s->sock_type,
+ s->sock_proto);
+ if (sock == NULL)
+ SOCKETCLOSE(newfd);
+ return sock;
}
PyDoc_STRVAR(dup_doc,
@@ -2159,20 +2159,20 @@ Return a new socket object connected to the same system resource.");
static PyObject *
sock_getsockname(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- int res;
- socklen_t addrlen;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
- Py_BEGIN_ALLOW_THREADS
- res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
- s->sock_proto);
+ sock_addr_t addrbuf;
+ int res;
+ socklen_t addrlen;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
+ Py_BEGIN_ALLOW_THREADS
+ res = getsockname(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
+ s->sock_proto);
}
PyDoc_STRVAR(getsockname_doc,
@@ -2182,26 +2182,26 @@ Return the address of the local endpoint. For IP sockets, the address\n\
info is a pair (hostaddr, port).");
-#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
+#ifdef HAVE_GETPEERNAME /* Cray APP doesn't have this :-( */
/* s.getpeername() method */
static PyObject *
sock_getpeername(PySocketSockObject *s)
{
- sock_addr_t addrbuf;
- int res;
- socklen_t addrlen;
-
- if (!getsockaddrlen(s, &addrlen))
- return NULL;
- memset(&addrbuf, 0, addrlen);
- Py_BEGIN_ALLOW_THREADS
- res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
- s->sock_proto);
+ sock_addr_t addrbuf;
+ int res;
+ socklen_t addrlen;
+
+ if (!getsockaddrlen(s, &addrlen))
+ return NULL;
+ memset(&addrbuf, 0, addrlen);
+ Py_BEGIN_ALLOW_THREADS
+ res = getpeername(s->sock_fd, SAS2SA(&addrbuf), &addrlen);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ return makesockaddr(s->sock_fd, SAS2SA(&addrbuf), addrlen,
+ s->sock_proto);
}
PyDoc_STRVAR(getpeername_doc,
@@ -2218,21 +2218,21 @@ info is a pair (hostaddr, port).");
static PyObject *
sock_listen(PySocketSockObject *s, PyObject *arg)
{
- int backlog;
- int res;
-
- backlog = PyInt_AsLong(arg);
- if (backlog == -1 && PyErr_Occurred())
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- if (backlog < 1)
- backlog = 1;
- res = listen(s->sock_fd, backlog);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ int backlog;
+ int res;
+
+ backlog = PyInt_AsLong(arg);
+ if (backlog == -1 && PyErr_Occurred())
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ if (backlog < 1)
+ backlog = 1;
+ res = listen(s->sock_fd, backlog);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(listen_doc,
@@ -2254,48 +2254,48 @@ will allow before refusing new connections.");
static PyObject *
sock_makefile(PySocketSockObject *s, PyObject *args)
{
- extern int fclose(FILE *);
- char *mode = "r";
- int bufsize = -1;
+ extern int fclose(FILE *);
+ char *mode = "r";
+ int bufsize = -1;
#ifdef MS_WIN32
- Py_intptr_t fd;
+ Py_intptr_t fd;
#else
- int fd;
+ int fd;
#endif
- FILE *fp;
- PyObject *f;
+ FILE *fp;
+ PyObject *f;
#ifdef __VMS
- char *mode_r = "r";
- char *mode_w = "w";
+ char *mode_r = "r";
+ char *mode_w = "w";
#endif
- if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|si:makefile", &mode, &bufsize))
+ return NULL;
#ifdef __VMS
- if (strcmp(mode,"rb") == 0) {
- mode = mode_r;
- }
- else {
- if (strcmp(mode,"wb") == 0) {
- mode = mode_w;
- }
- }
+ if (strcmp(mode,"rb") == 0) {
+ mode = mode_r;
+ }
+ else {
+ if (strcmp(mode,"wb") == 0) {
+ mode = mode_w;
+ }
+ }
#endif
#ifdef MS_WIN32
- if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
- ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
+ if (((fd = _open_osfhandle(s->sock_fd, _O_BINARY)) < 0) ||
+ ((fd = dup(fd)) < 0) || ((fp = fdopen(fd, mode)) == NULL))
#else
- if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
-#endif
- {
- if (fd >= 0)
- SOCKETCLOSE(fd);
- return s->errorhandler();
- }
- f = PyFile_FromFile(fp, "<socket>", mode, fclose);
- if (f != NULL)
- PyFile_SetBufSize(f, bufsize);
- return f;
+ if ((fd = dup(s->sock_fd)) < 0 || (fp = fdopen(fd, mode)) == NULL)
+#endif
+ {
+ if (fd >= 0)
+ SOCKETCLOSE(fd);
+ return s->errorhandler();
+ }
+ f = PyFile_FromFile(fp, "<socket>", mode, fclose);
+ if (f != NULL)
+ PyFile_SetBufSize(f, bufsize);
+ return f;
}
PyDoc_STRVAR(makefile_doc,
@@ -2317,76 +2317,76 @@ The mode and buffersize arguments are as for the built-in open() function.");
static ssize_t
sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
{
- ssize_t outlen = -1;
- int timeout;
+ ssize_t outlen = -1;
+ int timeout;
#ifdef __VMS
- int remaining;
- char *read_buf;
+ int remaining;
+ char *read_buf;
#endif
- if (!IS_SELECTABLE(s)) {
- select_error();
- return -1;
- }
+ if (!IS_SELECTABLE(s)) {
+ select_error();
+ return -1;
+ }
#ifndef __VMS
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 0);
- if (!timeout)
- outlen = recv(s->sock_fd, cbuf, len, flags);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return -1;
- }
- if (outlen < 0) {
- /* Note: the call to errorhandler() ALWAYS indirectly returned
- NULL, so ignore its return value */
- s->errorhandler();
- return -1;
- }
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 0);
+ if (!timeout)
+ outlen = recv(s->sock_fd, cbuf, len, flags);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return -1;
+ }
+ if (outlen < 0) {
+ /* Note: the call to errorhandler() ALWAYS indirectly returned
+ NULL, so ignore its return value */
+ s->errorhandler();
+ return -1;
+ }
#else
- read_buf = cbuf;
- remaining = len;
- while (remaining != 0) {
- unsigned int segment;
- int nread = -1;
-
- segment = remaining /SEGMENT_SIZE;
- if (segment != 0) {
- segment = SEGMENT_SIZE;
- }
- else {
- segment = remaining;
- }
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 0);
- if (!timeout)
- nread = recv(s->sock_fd, read_buf, segment, flags);
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return -1;
- }
- if (nread < 0) {
- s->errorhandler();
- return -1;
- }
- if (nread != remaining) {
- read_buf += nread;
- break;
- }
-
- remaining -= segment;
- read_buf += segment;
- }
- outlen = read_buf - cbuf;
+ read_buf = cbuf;
+ remaining = len;
+ while (remaining != 0) {
+ unsigned int segment;
+ int nread = -1;
+
+ segment = remaining /SEGMENT_SIZE;
+ if (segment != 0) {
+ segment = SEGMENT_SIZE;
+ }
+ else {
+ segment = remaining;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 0);
+ if (!timeout)
+ nread = recv(s->sock_fd, read_buf, segment, flags);
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return -1;
+ }
+ if (nread < 0) {
+ s->errorhandler();
+ return -1;
+ }
+ if (nread != remaining) {
+ read_buf += nread;
+ break;
+ }
+
+ remaining -= segment;
+ read_buf += segment;
+ }
+ outlen = read_buf - cbuf;
#endif /* !__VMS */
- return outlen;
+ return outlen;
}
@@ -2395,41 +2395,41 @@ sock_recv_guts(PySocketSockObject *s, char* cbuf, int len, int flags)
static PyObject *
sock_recv(PySocketSockObject *s, PyObject *args)
{
- int recvlen, flags = 0;
- ssize_t outlen;
- PyObject *buf;
-
- if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
- return NULL;
-
- if (recvlen < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recv");
- return NULL;
- }
-
- /* Allocate a new string. */
- buf = PyString_FromStringAndSize((char *) 0, recvlen);
- if (buf == NULL)
- return NULL;
-
- /* Call the guts */
- outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
- if (outlen < 0) {
- /* An error occurred, release the string and return an
- error. */
- Py_DECREF(buf);
- return NULL;
- }
- if (outlen != recvlen) {
- /* We did not read as many bytes as we anticipated, resize the
- string if possible and be succesful. */
- if (_PyString_Resize(&buf, outlen) < 0)
- /* Oopsy, not so succesful after all. */
- return NULL;
- }
-
- return buf;
+ int recvlen, flags = 0;
+ ssize_t outlen;
+ PyObject *buf;
+
+ if (!PyArg_ParseTuple(args, "i|i:recv", &recvlen, &flags))
+ return NULL;
+
+ if (recvlen < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recv");
+ return NULL;
+ }
+
+ /* Allocate a new string. */
+ buf = PyString_FromStringAndSize((char *) 0, recvlen);
+ if (buf == NULL)
+ return NULL;
+
+ /* Call the guts */
+ outlen = sock_recv_guts(s, PyString_AS_STRING(buf), recvlen, flags);
+ if (outlen < 0) {
+ /* An error occurred, release the string and return an
+ error. */
+ Py_DECREF(buf);
+ return NULL;
+ }
+ if (outlen != recvlen) {
+ /* We did not read as many bytes as we anticipated, resize the
+ string if possible and be succesful. */
+ if (_PyString_Resize(&buf, outlen) < 0)
+ /* Oopsy, not so succesful after all. */
+ return NULL;
+ }
+
+ return buf;
}
PyDoc_STRVAR(recv_doc,
@@ -2446,52 +2446,52 @@ the remote end is closed and all data is read, return the empty string.");
static PyObject*
sock_recv_into(PySocketSockObject *s, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
-
- int recvlen = 0, flags = 0;
- ssize_t readlen;
- Py_buffer buf;
- Py_ssize_t buflen;
-
- /* Get the buffer's memory */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
- &buf, &recvlen, &flags))
- return NULL;
- buflen = buf.len;
- assert(buf.buf != 0 && buflen > 0);
-
- if (recvlen < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recv_into");
- goto error;
- }
- if (recvlen == 0) {
- /* If nbytes was not specified, use the buffer's length */
- recvlen = buflen;
- }
-
- /* Check if the buffer is large enough */
- if (buflen < recvlen) {
- PyErr_SetString(PyExc_ValueError,
- "buffer too small for requested bytes");
- goto error;
- }
-
- /* Call the guts */
- readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
- if (readlen < 0) {
- /* Return an error. */
- goto error;
- }
-
- PyBuffer_Release(&buf);
- /* Return the number of bytes read. Note that we do not do anything
- special here in the case that readlen < recvlen. */
- return PyInt_FromSsize_t(readlen);
+ static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
+
+ int recvlen = 0, flags = 0;
+ ssize_t readlen;
+ Py_buffer buf;
+ Py_ssize_t buflen;
+
+ /* Get the buffer's memory */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recv_into", kwlist,
+ &buf, &recvlen, &flags))
+ return NULL;
+ buflen = buf.len;
+ assert(buf.buf != 0 && buflen > 0);
+
+ if (recvlen < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recv_into");
+ goto error;
+ }
+ if (recvlen == 0) {
+ /* If nbytes was not specified, use the buffer's length */
+ recvlen = buflen;
+ }
+
+ /* Check if the buffer is large enough */
+ if (buflen < recvlen) {
+ PyErr_SetString(PyExc_ValueError,
+ "buffer too small for requested bytes");
+ goto error;
+ }
+
+ /* Call the guts */
+ readlen = sock_recv_guts(s, buf.buf, recvlen, flags);
+ if (readlen < 0) {
+ /* Return an error. */
+ goto error;
+ }
+
+ PyBuffer_Release(&buf);
+ /* Return the number of bytes read. Note that we do not do anything
+ special here in the case that readlen < recvlen. */
+ return PyInt_FromSsize_t(readlen);
error:
- PyBuffer_Release(&buf);
- return NULL;
+ PyBuffer_Release(&buf);
+ return NULL;
}
PyDoc_STRVAR(recv_into_doc,
@@ -2517,56 +2517,56 @@ See recv() for documentation about the flags.");
*/
static ssize_t
sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
- PyObject** addr)
+ PyObject** addr)
{
- sock_addr_t addrbuf;
- int timeout;
- ssize_t n = -1;
- socklen_t addrlen;
+ sock_addr_t addrbuf;
+ int timeout;
+ ssize_t n = -1;
+ socklen_t addrlen;
- *addr = NULL;
+ *addr = NULL;
- if (!getsockaddrlen(s, &addrlen))
- return -1;
+ if (!getsockaddrlen(s, &addrlen))
+ return -1;
- if (!IS_SELECTABLE(s)) {
- select_error();
- return -1;
- }
+ if (!IS_SELECTABLE(s)) {
+ select_error();
+ return -1;
+ }
- Py_BEGIN_ALLOW_THREADS
- memset(&addrbuf, 0, addrlen);
- timeout = internal_select(s, 0);
- if (!timeout) {
+ Py_BEGIN_ALLOW_THREADS
+ memset(&addrbuf, 0, addrlen);
+ timeout = internal_select(s, 0);
+ if (!timeout) {
#ifndef MS_WINDOWS
#if defined(PYOS_OS2) && !defined(PYCC_GCC)
- n = recvfrom(s->sock_fd, cbuf, len, flags,
- SAS2SA(&addrbuf), &addrlen);
+ n = recvfrom(s->sock_fd, cbuf, len, flags,
+ SAS2SA(&addrbuf), &addrlen);
#else
- n = recvfrom(s->sock_fd, cbuf, len, flags,
- (void *) &addrbuf, &addrlen);
+ n = recvfrom(s->sock_fd, cbuf, len, flags,
+ (void *) &addrbuf, &addrlen);
#endif
#else
- n = recvfrom(s->sock_fd, cbuf, len, flags,
- SAS2SA(&addrbuf), &addrlen);
-#endif
- }
- Py_END_ALLOW_THREADS
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return -1;
- }
- if (n < 0) {
- s->errorhandler();
- return -1;
- }
-
- if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
- addrlen, s->sock_proto)))
- return -1;
-
- return n;
+ n = recvfrom(s->sock_fd, cbuf, len, flags,
+ SAS2SA(&addrbuf), &addrlen);
+#endif
+ }
+ Py_END_ALLOW_THREADS
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return -1;
+ }
+ if (n < 0) {
+ s->errorhandler();
+ return -1;
+ }
+
+ if (!(*addr = makesockaddr(s->sock_fd, SAS2SA(&addrbuf),
+ addrlen, s->sock_proto)))
+ return -1;
+
+ return n;
}
/* s.recvfrom(nbytes [,flags]) method */
@@ -2574,45 +2574,45 @@ sock_recvfrom_guts(PySocketSockObject *s, char* cbuf, int len, int flags,
static PyObject *
sock_recvfrom(PySocketSockObject *s, PyObject *args)
{
- PyObject *buf = NULL;
- PyObject *addr = NULL;
- PyObject *ret = NULL;
- int recvlen, flags = 0;
- ssize_t outlen;
-
- if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
- return NULL;
-
- if (recvlen < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recvfrom");
- return NULL;
- }
-
- buf = PyString_FromStringAndSize((char *) 0, recvlen);
- if (buf == NULL)
- return NULL;
-
- outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
- recvlen, flags, &addr);
- if (outlen < 0) {
- goto finally;
- }
-
- if (outlen != recvlen) {
- /* We did not read as many bytes as we anticipated, resize the
- string if possible and be succesful. */
- if (_PyString_Resize(&buf, outlen) < 0)
- /* Oopsy, not so succesful after all. */
- goto finally;
- }
-
- ret = PyTuple_Pack(2, buf, addr);
+ PyObject *buf = NULL;
+ PyObject *addr = NULL;
+ PyObject *ret = NULL;
+ int recvlen, flags = 0;
+ ssize_t outlen;
+
+ if (!PyArg_ParseTuple(args, "i|i:recvfrom", &recvlen, &flags))
+ return NULL;
+
+ if (recvlen < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recvfrom");
+ return NULL;
+ }
+
+ buf = PyString_FromStringAndSize((char *) 0, recvlen);
+ if (buf == NULL)
+ return NULL;
+
+ outlen = sock_recvfrom_guts(s, PyString_AS_STRING(buf),
+ recvlen, flags, &addr);
+ if (outlen < 0) {
+ goto finally;
+ }
+
+ if (outlen != recvlen) {
+ /* We did not read as many bytes as we anticipated, resize the
+ string if possible and be succesful. */
+ if (_PyString_Resize(&buf, outlen) < 0)
+ /* Oopsy, not so succesful after all. */
+ goto finally;
+ }
+
+ ret = PyTuple_Pack(2, buf, addr);
finally:
- Py_XDECREF(buf);
- Py_XDECREF(addr);
- return ret;
+ Py_XDECREF(buf);
+ Py_XDECREF(addr);
+ return ret;
}
PyDoc_STRVAR(recvfrom_doc,
@@ -2626,47 +2626,47 @@ Like recv(buffersize, flags) but also return the sender's address info.");
static PyObject *
sock_recvfrom_into(PySocketSockObject *s, PyObject *args, PyObject* kwds)
{
- static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
-
- int recvlen = 0, flags = 0;
- ssize_t readlen;
- Py_buffer buf;
- int buflen;
-
- PyObject *addr = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
- kwlist, &buf,
- &recvlen, &flags))
- return NULL;
- buflen = buf.len;
- assert(buf.buf != 0 && buflen > 0);
-
- if (recvlen < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative buffersize in recvfrom_into");
- goto error;
- }
- if (recvlen == 0) {
- /* If nbytes was not specified, use the buffer's length */
- recvlen = buflen;
- }
-
- readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
- if (readlen < 0) {
- /* Return an error */
- goto error;
- }
-
- PyBuffer_Release(&buf);
- /* Return the number of bytes read and the address. Note that we do
- not do anything special here in the case that readlen < recvlen. */
- return Py_BuildValue("lN", readlen, addr);
+ static char *kwlist[] = {"buffer", "nbytes", "flags", 0};
+
+ int recvlen = 0, flags = 0;
+ ssize_t readlen;
+ Py_buffer buf;
+ int buflen;
+
+ PyObject *addr = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "w*|ii:recvfrom_into",
+ kwlist, &buf,
+ &recvlen, &flags))
+ return NULL;
+ buflen = buf.len;
+ assert(buf.buf != 0 && buflen > 0);
+
+ if (recvlen < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative buffersize in recvfrom_into");
+ goto error;
+ }
+ if (recvlen == 0) {
+ /* If nbytes was not specified, use the buffer's length */
+ recvlen = buflen;
+ }
+
+ readlen = sock_recvfrom_guts(s, buf.buf, recvlen, flags, &addr);
+ if (readlen < 0) {
+ /* Return an error */
+ goto error;
+ }
+
+ PyBuffer_Release(&buf);
+ /* Return the number of bytes read and the address. Note that we do
+ not do anything special here in the case that readlen < recvlen. */
+ return Py_BuildValue("lN", readlen, addr);
error:
- Py_XDECREF(addr);
- PyBuffer_Release(&buf);
- return NULL;
+ Py_XDECREF(addr);
+ PyBuffer_Release(&buf);
+ return NULL;
}
PyDoc_STRVAR(recvfrom_into_doc,
@@ -2680,39 +2680,39 @@ Like recv_into(buffer[, nbytes[, flags]]) but also return the sender's address i
static PyObject *
sock_send(PySocketSockObject *s, PyObject *args)
{
- char *buf;
- int len, n = -1, flags = 0, timeout;
- Py_buffer pbuf;
-
- if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
- return NULL;
-
- if (!IS_SELECTABLE(s)) {
- PyBuffer_Release(&pbuf);
- return select_error();
- }
- buf = pbuf.buf;
- len = pbuf.len;
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 1);
- if (!timeout)
+ char *buf;
+ int len, n = -1, flags = 0, timeout;
+ Py_buffer pbuf;
+
+ if (!PyArg_ParseTuple(args, "s*|i:send", &pbuf, &flags))
+ return NULL;
+
+ if (!IS_SELECTABLE(s)) {
+ PyBuffer_Release(&pbuf);
+ return select_error();
+ }
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 1);
+ if (!timeout)
#ifdef __VMS
- n = sendsegmented(s->sock_fd, buf, len, flags);
+ n = sendsegmented(s->sock_fd, buf, len, flags);
#else
- n = send(s->sock_fd, buf, len, flags);
+ n = send(s->sock_fd, buf, len, flags);
#endif
- Py_END_ALLOW_THREADS
+ Py_END_ALLOW_THREADS
- PyBuffer_Release(&pbuf);
+ PyBuffer_Release(&pbuf);
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (n < 0)
- return s->errorhandler();
- return PyInt_FromLong((long)n);
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+ return PyInt_FromLong((long)n);
}
PyDoc_STRVAR(send_doc,
@@ -2728,61 +2728,61 @@ sent; this may be less than len(data) if the network is busy.");
static PyObject *
sock_sendall(PySocketSockObject *s, PyObject *args)
{
- char *buf;
- int len, n = -1, flags = 0, timeout;
- Py_buffer pbuf;
-
- if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
- return NULL;
- buf = pbuf.buf;
- len = pbuf.len;
-
- if (!IS_SELECTABLE(s)) {
- PyBuffer_Release(&pbuf);
- return select_error();
- }
-
- Py_BEGIN_ALLOW_THREADS
- do {
- timeout = internal_select(s, 1);
- n = -1;
- if (timeout)
- break;
+ char *buf;
+ int len, n = -1, flags = 0, timeout;
+ Py_buffer pbuf;
+
+ if (!PyArg_ParseTuple(args, "s*|i:sendall", &pbuf, &flags))
+ return NULL;
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ if (!IS_SELECTABLE(s)) {
+ PyBuffer_Release(&pbuf);
+ return select_error();
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ do {
+ timeout = internal_select(s, 1);
+ n = -1;
+ if (timeout)
+ break;
#ifdef __VMS
- n = sendsegmented(s->sock_fd, buf, len, flags);
+ n = sendsegmented(s->sock_fd, buf, len, flags);
#else
- n = send(s->sock_fd, buf, len, flags);
+ n = send(s->sock_fd, buf, len, flags);
#endif
- if (n < 0) {
+ if (n < 0) {
#ifdef EINTR
- /* We must handle EINTR here as there is no way for
- * the caller to know how much was sent otherwise. */
- if (errno == EINTR) {
- /* Run signal handlers. If an exception was
- * raised, abort and leave this socket in
- * an unknown state. */
- if (PyErr_CheckSignals())
- return NULL;
- continue;
- }
-#endif
- break;
- }
- buf += n;
- len -= n;
- } while (len > 0);
- Py_END_ALLOW_THREADS
- PyBuffer_Release(&pbuf);
-
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (n < 0)
- return s->errorhandler();
-
- Py_INCREF(Py_None);
- return Py_None;
+ /* We must handle EINTR here as there is no way for
+ * the caller to know how much was sent otherwise. */
+ if (errno == EINTR) {
+ /* Run signal handlers. If an exception was
+ * raised, abort and leave this socket in
+ * an unknown state. */
+ if (PyErr_CheckSignals())
+ return NULL;
+ continue;
+ }
+#endif
+ break;
+ }
+ buf += n;
+ len -= n;
+ } while (len > 0);
+ Py_END_ALLOW_THREADS
+ PyBuffer_Release(&pbuf);
+
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(sendall_doc,
@@ -2799,47 +2799,47 @@ to tell how much data has been sent.");
static PyObject *
sock_sendto(PySocketSockObject *s, PyObject *args)
{
- Py_buffer pbuf;
- PyObject *addro;
- char *buf;
- Py_ssize_t len;
- sock_addr_t addrbuf;
- int addrlen, n = -1, flags, timeout;
-
- flags = 0;
- if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s*iO:sendto",
- &pbuf, &flags, &addro))
- return NULL;
- }
- buf = pbuf.buf;
- len = pbuf.len;
-
- if (!IS_SELECTABLE(s)) {
- PyBuffer_Release(&pbuf);
- return select_error();
- }
-
- if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
- PyBuffer_Release(&pbuf);
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- timeout = internal_select(s, 1);
- if (!timeout)
- n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
- Py_END_ALLOW_THREADS
-
- PyBuffer_Release(&pbuf);
- if (timeout == 1) {
- PyErr_SetString(socket_timeout, "timed out");
- return NULL;
- }
- if (n < 0)
- return s->errorhandler();
- return PyInt_FromLong((long)n);
+ Py_buffer pbuf;
+ PyObject *addro;
+ char *buf;
+ Py_ssize_t len;
+ sock_addr_t addrbuf;
+ int addrlen, n = -1, flags, timeout;
+
+ flags = 0;
+ if (!PyArg_ParseTuple(args, "s*O:sendto", &pbuf, &addro)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "s*iO:sendto",
+ &pbuf, &flags, &addro))
+ return NULL;
+ }
+ buf = pbuf.buf;
+ len = pbuf.len;
+
+ if (!IS_SELECTABLE(s)) {
+ PyBuffer_Release(&pbuf);
+ return select_error();
+ }
+
+ if (!getsockaddrarg(s, addro, SAS2SA(&addrbuf), &addrlen)) {
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ timeout = internal_select(s, 1);
+ if (!timeout)
+ n = sendto(s->sock_fd, buf, len, flags, SAS2SA(&addrbuf), addrlen);
+ Py_END_ALLOW_THREADS
+
+ PyBuffer_Release(&pbuf);
+ if (timeout == 1) {
+ PyErr_SetString(socket_timeout, "timed out");
+ return NULL;
+ }
+ if (n < 0)
+ return s->errorhandler();
+ return PyInt_FromLong((long)n);
}
PyDoc_STRVAR(sendto_doc,
@@ -2854,19 +2854,19 @@ For IP sockets, the address is a pair (hostaddr, port).");
static PyObject *
sock_shutdown(PySocketSockObject *s, PyObject *arg)
{
- int how;
- int res;
-
- how = PyInt_AsLong(arg);
- if (how == -1 && PyErr_Occurred())
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- res = shutdown(s->sock_fd, how);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return s->errorhandler();
- Py_INCREF(Py_None);
- return Py_None;
+ int how;
+ int res;
+
+ how = PyInt_AsLong(arg);
+ if (how == -1 && PyErr_Occurred())
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ res = shutdown(s->sock_fd, how);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return s->errorhandler();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(shutdown_doc,
@@ -2879,37 +2879,37 @@ of the socket (flag == SHUT_WR), or both ends (flag == SHUT_RDWR).");
static PyObject*
sock_ioctl(PySocketSockObject *s, PyObject *arg)
{
- unsigned long cmd = SIO_RCVALL;
- PyObject *argO;
- DWORD recv;
-
- if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
- return NULL;
-
- switch (cmd) {
- case SIO_RCVALL: {
- unsigned int option = RCVALL_ON;
- if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
- return NULL;
- if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
- NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
- return set_error();
- }
- return PyLong_FromUnsignedLong(recv); }
- case SIO_KEEPALIVE_VALS: {
- struct tcp_keepalive ka;
- if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
- &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
- return NULL;
- if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
- NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
- return set_error();
- }
- return PyLong_FromUnsignedLong(recv); }
- default:
- PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
- return NULL;
- }
+ unsigned long cmd = SIO_RCVALL;
+ PyObject *argO;
+ DWORD recv;
+
+ if (!PyArg_ParseTuple(arg, "kO:ioctl", &cmd, &argO))
+ return NULL;
+
+ switch (cmd) {
+ case SIO_RCVALL: {
+ unsigned int option = RCVALL_ON;
+ if (!PyArg_ParseTuple(arg, "kI:ioctl", &cmd, &option))
+ return NULL;
+ if (WSAIoctl(s->sock_fd, cmd, &option, sizeof(option),
+ NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
+ return set_error();
+ }
+ return PyLong_FromUnsignedLong(recv); }
+ case SIO_KEEPALIVE_VALS: {
+ struct tcp_keepalive ka;
+ if (!PyArg_ParseTuple(arg, "k(kkk):ioctl", &cmd,
+ &ka.onoff, &ka.keepalivetime, &ka.keepaliveinterval))
+ return NULL;
+ if (WSAIoctl(s->sock_fd, cmd, &ka, sizeof(ka),
+ NULL, 0, &recv, NULL, NULL) == SOCKET_ERROR) {
+ return set_error();
+ }
+ return PyLong_FromUnsignedLong(recv); }
+ default:
+ PyErr_Format(PyExc_ValueError, "invalid ioctl command %d", cmd);
+ return NULL;
+ }
}
PyDoc_STRVAR(sock_ioctl_doc,
"ioctl(cmd, option) -> long\n\
@@ -2923,69 +2923,69 @@ SIO_KEEPALIVE_VALS: 'option' is a tuple of (onoff, timeout, interval).");
/* List of methods for socket objects */
static PyMethodDef sock_methods[] = {
- {"accept", (PyCFunction)sock_accept, METH_NOARGS,
- accept_doc},
- {"bind", (PyCFunction)sock_bind, METH_O,
- bind_doc},
- {"close", (PyCFunction)sock_close, METH_NOARGS,
- close_doc},
- {"connect", (PyCFunction)sock_connect, METH_O,
- connect_doc},
- {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
- connect_ex_doc},
+ {"accept", (PyCFunction)sock_accept, METH_NOARGS,
+ accept_doc},
+ {"bind", (PyCFunction)sock_bind, METH_O,
+ bind_doc},
+ {"close", (PyCFunction)sock_close, METH_NOARGS,
+ close_doc},
+ {"connect", (PyCFunction)sock_connect, METH_O,
+ connect_doc},
+ {"connect_ex", (PyCFunction)sock_connect_ex, METH_O,
+ connect_ex_doc},
#ifndef NO_DUP
- {"dup", (PyCFunction)sock_dup, METH_NOARGS,
- dup_doc},
+ {"dup", (PyCFunction)sock_dup, METH_NOARGS,
+ dup_doc},
#endif
- {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
- fileno_doc},
+ {"fileno", (PyCFunction)sock_fileno, METH_NOARGS,
+ fileno_doc},
#ifdef HAVE_GETPEERNAME
- {"getpeername", (PyCFunction)sock_getpeername,
- METH_NOARGS, getpeername_doc},
+ {"getpeername", (PyCFunction)sock_getpeername,
+ METH_NOARGS, getpeername_doc},
#endif
- {"getsockname", (PyCFunction)sock_getsockname,
- METH_NOARGS, getsockname_doc},
- {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
- getsockopt_doc},
+ {"getsockname", (PyCFunction)sock_getsockname,
+ METH_NOARGS, getsockname_doc},
+ {"getsockopt", (PyCFunction)sock_getsockopt, METH_VARARGS,
+ getsockopt_doc},
#if defined(MS_WINDOWS) && defined(SIO_RCVALL)
- {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
- sock_ioctl_doc},
+ {"ioctl", (PyCFunction)sock_ioctl, METH_VARARGS,
+ sock_ioctl_doc},
#endif
- {"listen", (PyCFunction)sock_listen, METH_O,
- listen_doc},
+ {"listen", (PyCFunction)sock_listen, METH_O,
+ listen_doc},
#ifndef NO_DUP
- {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
- makefile_doc},
-#endif
- {"recv", (PyCFunction)sock_recv, METH_VARARGS,
- recv_doc},
- {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
- recv_into_doc},
- {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
- recvfrom_doc},
- {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
- recvfrom_into_doc},
- {"send", (PyCFunction)sock_send, METH_VARARGS,
- send_doc},
- {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
- sendall_doc},
- {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
- sendto_doc},
- {"setblocking", (PyCFunction)sock_setblocking, METH_O,
- setblocking_doc},
- {"settimeout", (PyCFunction)sock_settimeout, METH_O,
- settimeout_doc},
- {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
- gettimeout_doc},
- {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
- setsockopt_doc},
- {"shutdown", (PyCFunction)sock_shutdown, METH_O,
- shutdown_doc},
+ {"makefile", (PyCFunction)sock_makefile, METH_VARARGS,
+ makefile_doc},
+#endif
+ {"recv", (PyCFunction)sock_recv, METH_VARARGS,
+ recv_doc},
+ {"recv_into", (PyCFunction)sock_recv_into, METH_VARARGS | METH_KEYWORDS,
+ recv_into_doc},
+ {"recvfrom", (PyCFunction)sock_recvfrom, METH_VARARGS,
+ recvfrom_doc},
+ {"recvfrom_into", (PyCFunction)sock_recvfrom_into, METH_VARARGS | METH_KEYWORDS,
+ recvfrom_into_doc},
+ {"send", (PyCFunction)sock_send, METH_VARARGS,
+ send_doc},
+ {"sendall", (PyCFunction)sock_sendall, METH_VARARGS,
+ sendall_doc},
+ {"sendto", (PyCFunction)sock_sendto, METH_VARARGS,
+ sendto_doc},
+ {"setblocking", (PyCFunction)sock_setblocking, METH_O,
+ setblocking_doc},
+ {"settimeout", (PyCFunction)sock_settimeout, METH_O,
+ settimeout_doc},
+ {"gettimeout", (PyCFunction)sock_gettimeout, METH_NOARGS,
+ gettimeout_doc},
+ {"setsockopt", (PyCFunction)sock_setsockopt, METH_VARARGS,
+ setsockopt_doc},
+ {"shutdown", (PyCFunction)sock_shutdown, METH_O,
+ shutdown_doc},
#ifdef RISCOS
- {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
- sleeptaskw_doc},
+ {"sleeptaskw", (PyCFunction)sock_sleeptaskw, METH_O,
+ sleeptaskw_doc},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
/* SockObject members */
@@ -3003,34 +3003,34 @@ static PyMemberDef sock_memberlist[] = {
static void
sock_dealloc(PySocketSockObject *s)
{
- if (s->sock_fd != -1)
- (void) SOCKETCLOSE(s->sock_fd);
- Py_TYPE(s)->tp_free((PyObject *)s);
+ if (s->sock_fd != -1)
+ (void) SOCKETCLOSE(s->sock_fd);
+ Py_TYPE(s)->tp_free((PyObject *)s);
}
static PyObject *
sock_repr(PySocketSockObject *s)
{
- char buf[512];
+ char buf[512];
#if SIZEOF_SOCKET_T > SIZEOF_LONG
- if (s->sock_fd > LONG_MAX) {
- /* this can occur on Win64, and actually there is a special
- ugly printf formatter for decimal pointer length integer
- printing, only bother if necessary*/
- PyErr_SetString(PyExc_OverflowError,
- "no printf formatter to display "
- "the socket descriptor in decimal");
- return NULL;
- }
-#endif
- PyOS_snprintf(
- buf, sizeof(buf),
- "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
- (long)s->sock_fd, s->sock_family,
- s->sock_type,
- s->sock_proto);
- return PyString_FromString(buf);
+ if (s->sock_fd > LONG_MAX) {
+ /* this can occur on Win64, and actually there is a special
+ ugly printf formatter for decimal pointer length integer
+ printing, only bother if necessary*/
+ PyErr_SetString(PyExc_OverflowError,
+ "no printf formatter to display "
+ "the socket descriptor in decimal");
+ return NULL;
+ }
+#endif
+ PyOS_snprintf(
+ buf, sizeof(buf),
+ "<socket object, fd=%ld, family=%d, type=%d, protocol=%d>",
+ (long)s->sock_fd, s->sock_family,
+ s->sock_type,
+ s->sock_proto);
+ return PyString_FromString(buf);
}
@@ -3039,15 +3039,15 @@ sock_repr(PySocketSockObject *s)
static PyObject *
sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *new;
-
- new = type->tp_alloc(type, 0);
- if (new != NULL) {
- ((PySocketSockObject *)new)->sock_fd = -1;
- ((PySocketSockObject *)new)->sock_timeout = -1.0;
- ((PySocketSockObject *)new)->errorhandler = &set_error;
- }
- return new;
+ PyObject *new;
+
+ new = type->tp_alloc(type, 0);
+ if (new != NULL) {
+ ((PySocketSockObject *)new)->sock_fd = -1;
+ ((PySocketSockObject *)new)->sock_timeout = -1.0;
+ ((PySocketSockObject *)new)->errorhandler = &set_error;
+ }
+ return new;
}
@@ -3057,32 +3057,32 @@ sock_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
{
- PySocketSockObject *s = (PySocketSockObject *)self;
- SOCKET_T fd;
- int family = AF_INET, type = SOCK_STREAM, proto = 0;
- static char *keywords[] = {"family", "type", "proto", 0};
+ PySocketSockObject *s = (PySocketSockObject *)self;
+ SOCKET_T fd;
+ int family = AF_INET, type = SOCK_STREAM, proto = 0;
+ static char *keywords[] = {"family", "type", "proto", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds,
- "|iii:socket", keywords,
- &family, &type, &proto))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds,
+ "|iii:socket", keywords,
+ &family, &type, &proto))
+ return -1;
- Py_BEGIN_ALLOW_THREADS
- fd = socket(family, type, proto);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ fd = socket(family, type, proto);
+ Py_END_ALLOW_THREADS
#ifdef MS_WINDOWS
- if (fd == INVALID_SOCKET)
+ if (fd == INVALID_SOCKET)
#else
- if (fd < 0)
+ if (fd < 0)
#endif
- {
- set_error();
- return -1;
- }
- init_sockobject(s, fd, family, type, proto);
+ {
+ set_error();
+ return -1;
+ }
+ init_sockobject(s, fd, family, type, proto);
- return 0;
+ return 0;
}
@@ -3090,45 +3090,45 @@ sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
/* Type object for socket objects. */
static PyTypeObject sock_type = {
- PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
- "_socket.socket", /* tp_name */
- sizeof(PySocketSockObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)sock_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)sock_repr, /* 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 */
- sock_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- sock_methods, /* tp_methods */
- sock_memberlist, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- sock_initobj, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- sock_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(0, 0) /* Must fill in type value later */
+ "_socket.socket", /* tp_name */
+ sizeof(PySocketSockObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)sock_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)sock_repr, /* 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 */
+ sock_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ sock_methods, /* tp_methods */
+ sock_memberlist, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ sock_initobj, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ sock_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -3138,15 +3138,15 @@ static PyTypeObject sock_type = {
static PyObject *
socket_gethostname(PyObject *self, PyObject *unused)
{
- char buf[1024];
- int res;
- Py_BEGIN_ALLOW_THREADS
- res = gethostname(buf, (int) sizeof buf - 1);
- Py_END_ALLOW_THREADS
- if (res < 0)
- return set_error();
- buf[sizeof buf - 1] = '\0';
- return PyString_FromString(buf);
+ char buf[1024];
+ int res;
+ Py_BEGIN_ALLOW_THREADS
+ res = gethostname(buf, (int) sizeof buf - 1);
+ Py_END_ALLOW_THREADS
+ if (res < 0)
+ return set_error();
+ buf[sizeof buf - 1] = '\0';
+ return PyString_FromString(buf);
}
PyDoc_STRVAR(gethostname_doc,
@@ -3161,14 +3161,14 @@ Return the current host name.");
static PyObject *
socket_gethostbyname(PyObject *self, PyObject *args)
{
- char *name;
- sock_addr_t addrbuf;
-
- if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
- return NULL;
- if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
- return NULL;
- return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
+ char *name;
+ sock_addr_t addrbuf;
+
+ if (!PyArg_ParseTuple(args, "s:gethostbyname", &name))
+ return NULL;
+ if (setipaddr(name, SAS2SA(&addrbuf), sizeof(addrbuf), AF_INET) < 0)
+ return NULL;
+ return makeipaddr(SAS2SA(&addrbuf), sizeof(struct sockaddr_in));
}
PyDoc_STRVAR(gethostbyname_doc,
@@ -3182,130 +3182,130 @@ Return the IP address (a string of the form '255.255.255.255') for a host.");
static PyObject *
gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
{
- char **pch;
- PyObject *rtn_tuple = (PyObject *)NULL;
- PyObject *name_list = (PyObject *)NULL;
- PyObject *addr_list = (PyObject *)NULL;
- PyObject *tmp;
-
- if (h == NULL) {
- /* Let's get real error message to return */
+ char **pch;
+ PyObject *rtn_tuple = (PyObject *)NULL;
+ PyObject *name_list = (PyObject *)NULL;
+ PyObject *addr_list = (PyObject *)NULL;
+ PyObject *tmp;
+
+ if (h == NULL) {
+ /* Let's get real error message to return */
#ifndef RISCOS
- set_herror(h_errno);
+ set_herror(h_errno);
#else
- PyErr_SetString(socket_error, "host not found");
+ PyErr_SetString(socket_error, "host not found");
#endif
- return NULL;
- }
+ return NULL;
+ }
- if (h->h_addrtype != af) {
- /* Let's get real error message to return */
- PyErr_SetString(socket_error,
- (char *)strerror(EAFNOSUPPORT));
+ if (h->h_addrtype != af) {
+ /* Let's get real error message to return */
+ PyErr_SetString(socket_error,
+ (char *)strerror(EAFNOSUPPORT));
- return NULL;
- }
+ return NULL;
+ }
- switch (af) {
+ switch (af) {
- case AF_INET:
- if (alen < sizeof(struct sockaddr_in))
- return NULL;
- break;
+ case AF_INET:
+ if (alen < sizeof(struct sockaddr_in))
+ return NULL;
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- if (alen < sizeof(struct sockaddr_in6))
- return NULL;
- break;
+ case AF_INET6:
+ if (alen < sizeof(struct sockaddr_in6))
+ return NULL;
+ break;
#endif
- }
+ }
- if ((name_list = PyList_New(0)) == NULL)
- goto err;
+ if ((name_list = PyList_New(0)) == NULL)
+ goto err;
- if ((addr_list = PyList_New(0)) == NULL)
- goto err;
+ if ((addr_list = PyList_New(0)) == NULL)
+ goto err;
- /* SF #1511317: h_aliases can be NULL */
- if (h->h_aliases) {
- for (pch = h->h_aliases; *pch != NULL; pch++) {
- int status;
- tmp = PyString_FromString(*pch);
- if (tmp == NULL)
- goto err;
+ /* SF #1511317: h_aliases can be NULL */
+ if (h->h_aliases) {
+ for (pch = h->h_aliases; *pch != NULL; pch++) {
+ int status;
+ tmp = PyString_FromString(*pch);
+ if (tmp == NULL)
+ goto err;
- status = PyList_Append(name_list, tmp);
- Py_DECREF(tmp);
+ status = PyList_Append(name_list, tmp);
+ Py_DECREF(tmp);
- if (status)
- goto err;
- }
- }
+ if (status)
+ goto err;
+ }
+ }
- for (pch = h->h_addr_list; *pch != NULL; pch++) {
- int status;
+ for (pch = h->h_addr_list; *pch != NULL; pch++) {
+ int status;
- switch (af) {
+ switch (af) {
- case AF_INET:
- {
- struct sockaddr_in sin;
- memset(&sin, 0, sizeof(sin));
- sin.sin_family = af;
+ case AF_INET:
+ {
+ struct sockaddr_in sin;
+ memset(&sin, 0, sizeof(sin));
+ sin.sin_family = af;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin.sin_len = sizeof(sin);
+ sin.sin_len = sizeof(sin);
#endif
- memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
- tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
+ memcpy(&sin.sin_addr, *pch, sizeof(sin.sin_addr));
+ tmp = makeipaddr((struct sockaddr *)&sin, sizeof(sin));
- if (pch == h->h_addr_list && alen >= sizeof(sin))
- memcpy((char *) addr, &sin, sizeof(sin));
- break;
- }
+ if (pch == h->h_addr_list && alen >= sizeof(sin))
+ memcpy((char *) addr, &sin, sizeof(sin));
+ break;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6 sin6;
- memset(&sin6, 0, sizeof(sin6));
- sin6.sin6_family = af;
+ case AF_INET6:
+ {
+ struct sockaddr_in6 sin6;
+ memset(&sin6, 0, sizeof(sin6));
+ sin6.sin6_family = af;
#ifdef HAVE_SOCKADDR_SA_LEN
- sin6.sin6_len = sizeof(sin6);
+ sin6.sin6_len = sizeof(sin6);
#endif
- memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
- tmp = makeipaddr((struct sockaddr *)&sin6,
- sizeof(sin6));
+ memcpy(&sin6.sin6_addr, *pch, sizeof(sin6.sin6_addr));
+ tmp = makeipaddr((struct sockaddr *)&sin6,
+ sizeof(sin6));
- if (pch == h->h_addr_list && alen >= sizeof(sin6))
- memcpy((char *) addr, &sin6, sizeof(sin6));
- break;
- }
+ if (pch == h->h_addr_list && alen >= sizeof(sin6))
+ memcpy((char *) addr, &sin6, sizeof(sin6));
+ break;
+ }
#endif
- default: /* can't happen */
- PyErr_SetString(socket_error,
- "unsupported address family");
- return NULL;
- }
+ default: /* can't happen */
+ PyErr_SetString(socket_error,
+ "unsupported address family");
+ return NULL;
+ }
- if (tmp == NULL)
- goto err;
+ if (tmp == NULL)
+ goto err;
- status = PyList_Append(addr_list, tmp);
- Py_DECREF(tmp);
+ status = PyList_Append(addr_list, tmp);
+ Py_DECREF(tmp);
- if (status)
- goto err;
- }
+ if (status)
+ goto err;
+ }
- rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
+ rtn_tuple = Py_BuildValue("sOO", h->h_name, name_list, addr_list);
err:
- Py_XDECREF(name_list);
- Py_XDECREF(addr_list);
- return rtn_tuple;
+ Py_XDECREF(name_list);
+ Py_XDECREF(addr_list);
+ return rtn_tuple;
}
@@ -3315,63 +3315,63 @@ gethost_common(struct hostent *h, struct sockaddr *addr, int alen, int af)
static PyObject *
socket_gethostbyname_ex(PyObject *self, PyObject *args)
{
- char *name;
- struct hostent *h;
+ char *name;
+ struct hostent *h;
#ifdef ENABLE_IPV6
- struct sockaddr_storage addr;
+ struct sockaddr_storage addr;
#else
- struct sockaddr_in addr;
+ struct sockaddr_in addr;
#endif
- struct sockaddr *sa;
- PyObject *ret;
+ struct sockaddr *sa;
+ PyObject *ret;
#ifdef HAVE_GETHOSTBYNAME_R
- struct hostent hp_allocated;
+ struct hostent hp_allocated;
#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
- struct hostent_data data;
+ struct hostent_data data;
#else
- char buf[16384];
- int buf_len = (sizeof buf) - 1;
- int errnop;
+ char buf[16384];
+ int buf_len = (sizeof buf) - 1;
+ int errnop;
#endif
#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- int result;
+ int result;
#endif
#endif /* HAVE_GETHOSTBYNAME_R */
- if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
- return NULL;
- if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
- return NULL;
- Py_BEGIN_ALLOW_THREADS
+ if (!PyArg_ParseTuple(args, "s:gethostbyname_ex", &name))
+ return NULL;
+ if (setipaddr(name, (struct sockaddr *)&addr, sizeof(addr), AF_INET) < 0)
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_GETHOSTBYNAME_R
#if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
- &h, &errnop);
+ result = gethostbyname_r(name, &hp_allocated, buf, buf_len,
+ &h, &errnop);
#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
- h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
+ h = gethostbyname_r(name, &hp_allocated, buf, buf_len, &errnop);
#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
- memset((void *) &data, '\0', sizeof(data));
- result = gethostbyname_r(name, &hp_allocated, &data);
- h = (result != 0) ? NULL : &hp_allocated;
+ memset((void *) &data, '\0', sizeof(data));
+ result = gethostbyname_r(name, &hp_allocated, &data);
+ h = (result != 0) ? NULL : &hp_allocated;
#endif
#else /* not HAVE_GETHOSTBYNAME_R */
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_acquire_lock(netdb_lock, 1);
+ PyThread_acquire_lock(netdb_lock, 1);
#endif
- h = gethostbyname(name);
+ h = gethostbyname(name);
#endif /* HAVE_GETHOSTBYNAME_R */
- Py_END_ALLOW_THREADS
- /* Some C libraries would require addr.__ss_family instead of
- addr.ss_family.
- Therefore, we cast the sockaddr_storage into sockaddr to
- access sa_family. */
- sa = (struct sockaddr*)&addr;
- ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
- sa->sa_family);
+ Py_END_ALLOW_THREADS
+ /* Some C libraries would require addr.__ss_family instead of
+ addr.ss_family.
+ Therefore, we cast the sockaddr_storage into sockaddr to
+ access sa_family. */
+ sa = (struct sockaddr*)&addr;
+ ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr),
+ sa->sa_family);
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_release_lock(netdb_lock);
+ PyThread_release_lock(netdb_lock);
#endif
- return ret;
+ return ret;
}
PyDoc_STRVAR(ghbn_ex_doc,
@@ -3388,83 +3388,83 @@ static PyObject *
socket_gethostbyaddr(PyObject *self, PyObject *args)
{
#ifdef ENABLE_IPV6
- struct sockaddr_storage addr;
+ struct sockaddr_storage addr;
#else
- struct sockaddr_in addr;
+ struct sockaddr_in addr;
#endif
- struct sockaddr *sa = (struct sockaddr *)&addr;
- char *ip_num;
- struct hostent *h;
- PyObject *ret;
+ struct sockaddr *sa = (struct sockaddr *)&addr;
+ char *ip_num;
+ struct hostent *h;
+ PyObject *ret;
#ifdef HAVE_GETHOSTBYNAME_R
- struct hostent hp_allocated;
+ struct hostent hp_allocated;
#ifdef HAVE_GETHOSTBYNAME_R_3_ARG
- struct hostent_data data;
+ struct hostent_data data;
#else
- /* glibcs up to 2.10 assume that the buf argument to
- gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
- does not ensure. The attribute below instructs the compiler
- to maintain this alignment. */
- char buf[16384] Py_ALIGNED(8);
- int buf_len = (sizeof buf) - 1;
- int errnop;
+ /* glibcs up to 2.10 assume that the buf argument to
+ gethostbyaddr_r is 8-byte aligned, which at least llvm-gcc
+ does not ensure. The attribute below instructs the compiler
+ to maintain this alignment. */
+ char buf[16384] Py_ALIGNED(8);
+ int buf_len = (sizeof buf) - 1;
+ int errnop;
#endif
#if defined(HAVE_GETHOSTBYNAME_R_3_ARG) || defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- int result;
+ int result;
#endif
#endif /* HAVE_GETHOSTBYNAME_R */
- char *ap;
- int al;
- int af;
-
- if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
- return NULL;
- af = AF_UNSPEC;
- if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
- return NULL;
- af = sa->sa_family;
- ap = NULL;
- switch (af) {
- case AF_INET:
- ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
- al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
- break;
+ char *ap;
+ int al;
+ int af;
+
+ if (!PyArg_ParseTuple(args, "s:gethostbyaddr", &ip_num))
+ return NULL;
+ af = AF_UNSPEC;
+ if (setipaddr(ip_num, sa, sizeof(addr), af) < 0)
+ return NULL;
+ af = sa->sa_family;
+ ap = NULL;
+ switch (af) {
+ case AF_INET:
+ ap = (char *)&((struct sockaddr_in *)sa)->sin_addr;
+ al = sizeof(((struct sockaddr_in *)sa)->sin_addr);
+ break;
#ifdef ENABLE_IPV6
- case AF_INET6:
- ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
- al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
- break;
-#endif
- default:
- PyErr_SetString(socket_error, "unsupported address family");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
+ case AF_INET6:
+ ap = (char *)&((struct sockaddr_in6 *)sa)->sin6_addr;
+ al = sizeof(((struct sockaddr_in6 *)sa)->sin6_addr);
+ break;
+#endif
+ default:
+ PyErr_SetString(socket_error, "unsupported address family");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
#ifdef HAVE_GETHOSTBYNAME_R
#if defined(HAVE_GETHOSTBYNAME_R_6_ARG)
- result = gethostbyaddr_r(ap, al, af,
- &hp_allocated, buf, buf_len,
- &h, &errnop);
+ result = gethostbyaddr_r(ap, al, af,
+ &hp_allocated, buf, buf_len,
+ &h, &errnop);
#elif defined(HAVE_GETHOSTBYNAME_R_5_ARG)
- h = gethostbyaddr_r(ap, al, af,
- &hp_allocated, buf, buf_len, &errnop);
+ h = gethostbyaddr_r(ap, al, af,
+ &hp_allocated, buf, buf_len, &errnop);
#else /* HAVE_GETHOSTBYNAME_R_3_ARG */
- memset((void *) &data, '\0', sizeof(data));
- result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
- h = (result != 0) ? NULL : &hp_allocated;
+ memset((void *) &data, '\0', sizeof(data));
+ result = gethostbyaddr_r(ap, al, af, &hp_allocated, &data);
+ h = (result != 0) ? NULL : &hp_allocated;
#endif
#else /* not HAVE_GETHOSTBYNAME_R */
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_acquire_lock(netdb_lock, 1);
+ PyThread_acquire_lock(netdb_lock, 1);
#endif
- h = gethostbyaddr(ap, al, af);
+ h = gethostbyaddr(ap, al, af);
#endif /* HAVE_GETHOSTBYNAME_R */
- Py_END_ALLOW_THREADS
- ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
+ Py_END_ALLOW_THREADS
+ ret = gethost_common(h, (struct sockaddr *)&addr, sizeof(addr), af);
#ifdef USE_GETHOSTBYNAME_LOCK
- PyThread_release_lock(netdb_lock);
+ PyThread_release_lock(netdb_lock);
#endif
- return ret;
+ return ret;
}
PyDoc_STRVAR(gethostbyaddr_doc,
@@ -3482,18 +3482,18 @@ for a host. The host argument is a string giving a host name or IP number.");
static PyObject *
socket_getservbyname(PyObject *self, PyObject *args)
{
- char *name, *proto=NULL;
- struct servent *sp;
- if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sp = getservbyname(name, proto);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "service/proto not found");
- return NULL;
- }
- return PyInt_FromLong((long) ntohs(sp->s_port));
+ char *name, *proto=NULL;
+ struct servent *sp;
+ if (!PyArg_ParseTuple(args, "s|s:getservbyname", &name, &proto))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sp = getservbyname(name, proto);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "service/proto not found");
+ return NULL;
+ }
+ return PyInt_FromLong((long) ntohs(sp->s_port));
}
PyDoc_STRVAR(getservbyname_doc,
@@ -3512,25 +3512,25 @@ otherwise any protocol will match.");
static PyObject *
socket_getservbyport(PyObject *self, PyObject *args)
{
- int port;
- char *proto=NULL;
- struct servent *sp;
- if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
- return NULL;
- if (port < 0 || port > 0xffff) {
- PyErr_SetString(
- PyExc_OverflowError,
- "getservbyport: port must be 0-65535.");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- sp = getservbyport(htons((short)port), proto);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "port/proto not found");
- return NULL;
- }
- return PyString_FromString(sp->s_name);
+ int port;
+ char *proto=NULL;
+ struct servent *sp;
+ if (!PyArg_ParseTuple(args, "i|s:getservbyport", &port, &proto))
+ return NULL;
+ if (port < 0 || port > 0xffff) {
+ PyErr_SetString(
+ PyExc_OverflowError,
+ "getservbyport: port must be 0-65535.");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ sp = getservbyport(htons((short)port), proto);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "port/proto not found");
+ return NULL;
+ }
+ return PyString_FromString(sp->s_name);
}
PyDoc_STRVAR(getservbyport_doc,
@@ -3548,23 +3548,23 @@ otherwise any protocol will match.");
static PyObject *
socket_getprotobyname(PyObject *self, PyObject *args)
{
- char *name;
- struct protoent *sp;
+ char *name;
+ struct protoent *sp;
#ifdef __BEOS__
/* Not available in BeOS yet. - [cjh] */
- PyErr_SetString(socket_error, "getprotobyname not supported");
- return NULL;
+ PyErr_SetString(socket_error, "getprotobyname not supported");
+ return NULL;
#else
- if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- sp = getprotobyname(name);
- Py_END_ALLOW_THREADS
- if (sp == NULL) {
- PyErr_SetString(socket_error, "protocol not found");
- return NULL;
- }
- return PyInt_FromLong((long) sp->p_proto);
+ if (!PyArg_ParseTuple(args, "s:getprotobyname", &name))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ sp = getprotobyname(name);
+ Py_END_ALLOW_THREADS
+ if (sp == NULL) {
+ PyErr_SetString(socket_error, "protocol not found");
+ return NULL;
+ }
+ return PyInt_FromLong((long) sp->p_proto);
#endif
}
@@ -3583,40 +3583,40 @@ Return the protocol number for the named protocol. (Rarely used.)");
static PyObject *
socket_socketpair(PyObject *self, PyObject *args)
{
- PySocketSockObject *s0 = NULL, *s1 = NULL;
- SOCKET_T sv[2];
- int family, type = SOCK_STREAM, proto = 0;
- PyObject *res = NULL;
+ PySocketSockObject *s0 = NULL, *s1 = NULL;
+ SOCKET_T sv[2];
+ int family, type = SOCK_STREAM, proto = 0;
+ PyObject *res = NULL;
#if defined(AF_UNIX)
- family = AF_UNIX;
+ family = AF_UNIX;
#else
- family = AF_INET;
-#endif
- if (!PyArg_ParseTuple(args, "|iii:socketpair",
- &family, &type, &proto))
- return NULL;
- /* Create a pair of socket fds */
- if (socketpair(family, type, proto, sv) < 0)
- return set_error();
- s0 = new_sockobject(sv[0], family, type, proto);
- if (s0 == NULL)
- goto finally;
- s1 = new_sockobject(sv[1], family, type, proto);
- if (s1 == NULL)
- goto finally;
- res = PyTuple_Pack(2, s0, s1);
+ family = AF_INET;
+#endif
+ if (!PyArg_ParseTuple(args, "|iii:socketpair",
+ &family, &type, &proto))
+ return NULL;
+ /* Create a pair of socket fds */
+ if (socketpair(family, type, proto, sv) < 0)
+ return set_error();
+ s0 = new_sockobject(sv[0], family, type, proto);
+ if (s0 == NULL)
+ goto finally;
+ s1 = new_sockobject(sv[1], family, type, proto);
+ if (s1 == NULL)
+ goto finally;
+ res = PyTuple_Pack(2, s0, s1);
finally:
- if (res == NULL) {
- if (s0 == NULL)
- SOCKETCLOSE(sv[0]);
- if (s1 == NULL)
- SOCKETCLOSE(sv[1]);
- }
- Py_XDECREF(s0);
- Py_XDECREF(s1);
- return res;
+ if (res == NULL) {
+ if (s0 == NULL)
+ SOCKETCLOSE(sv[0]);
+ if (s1 == NULL)
+ SOCKETCLOSE(sv[1]);
+ }
+ Py_XDECREF(s0);
+ Py_XDECREF(s1);
+ return res;
}
PyDoc_STRVAR(socketpair_doc,
@@ -3639,18 +3639,18 @@ AF_UNIX if defined on the platform; otherwise, the default is AF_INET.");
static PyObject *
socket_fromfd(PyObject *self, PyObject *args)
{
- PySocketSockObject *s;
- SOCKET_T fd;
- int family, type, proto = 0;
- if (!PyArg_ParseTuple(args, "iii|i:fromfd",
- &fd, &family, &type, &proto))
- return NULL;
- /* Dup the fd so it and the socket can be closed independently */
- fd = dup(fd);
- if (fd < 0)
- return set_error();
- s = new_sockobject(fd, family, type, proto);
- return (PyObject *) s;
+ PySocketSockObject *s;
+ SOCKET_T fd;
+ int family, type, proto = 0;
+ if (!PyArg_ParseTuple(args, "iii|i:fromfd",
+ &fd, &family, &type, &proto))
+ return NULL;
+ /* Dup the fd so it and the socket can be closed independently */
+ fd = dup(fd);
+ if (fd < 0)
+ return set_error();
+ s = new_sockobject(fd, family, type, proto);
+ return (PyObject *) s;
}
PyDoc_STRVAR(fromfd_doc,
@@ -3666,18 +3666,18 @@ The remaining arguments are the same as for socket().");
static PyObject *
socket_ntohs(PyObject *self, PyObject *args)
{
- int x1, x2;
-
- if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
- return NULL;
- }
- if (x1 < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- x2 = (unsigned int)ntohs((unsigned short)x1);
- return PyInt_FromLong(x2);
+ int x1, x2;
+
+ if (!PyArg_ParseTuple(args, "i:ntohs", &x1)) {
+ return NULL;
+ }
+ if (x1 < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ x2 = (unsigned int)ntohs((unsigned short)x1);
+ return PyInt_FromLong(x2);
}
PyDoc_STRVAR(ntohs_doc,
@@ -3689,41 +3689,41 @@ Convert a 16-bit integer from network to host byte order.");
static PyObject *
socket_ntohl(PyObject *self, PyObject *arg)
{
- unsigned long x;
-
- if (PyInt_Check(arg)) {
- x = PyInt_AS_LONG(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- if ((long)x < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- }
- else if (PyLong_Check(arg)) {
- x = PyLong_AsUnsignedLong(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
+ unsigned long x;
+
+ if (PyInt_Check(arg)) {
+ x = PyInt_AS_LONG(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
+ if ((long)x < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ }
+ else if (PyLong_Check(arg)) {
+ x = PyLong_AsUnsignedLong(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
#if SIZEOF_LONG > 4
- {
- unsigned long y;
- /* only want the trailing 32 bits */
- y = x & 0xFFFFFFFFUL;
- if (y ^ x)
- return PyErr_Format(PyExc_OverflowError,
- "long int larger than 32 bits");
- x = y;
- }
-#endif
- }
- else
- return PyErr_Format(PyExc_TypeError,
- "expected int/long, %s found",
- Py_TYPE(arg)->tp_name);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- return PyLong_FromUnsignedLong(ntohl(x));
+ {
+ unsigned long y;
+ /* only want the trailing 32 bits */
+ y = x & 0xFFFFFFFFUL;
+ if (y ^ x)
+ return PyErr_Format(PyExc_OverflowError,
+ "long int larger than 32 bits");
+ x = y;
+ }
+#endif
+ }
+ else
+ return PyErr_Format(PyExc_TypeError,
+ "expected int/long, %s found",
+ Py_TYPE(arg)->tp_name);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
+ return PyLong_FromUnsignedLong(ntohl(x));
}
PyDoc_STRVAR(ntohl_doc,
@@ -3735,18 +3735,18 @@ Convert a 32-bit integer from network to host byte order.");
static PyObject *
socket_htons(PyObject *self, PyObject *args)
{
- int x1, x2;
-
- if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
- return NULL;
- }
- if (x1 < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- x2 = (unsigned int)htons((unsigned short)x1);
- return PyInt_FromLong(x2);
+ int x1, x2;
+
+ if (!PyArg_ParseTuple(args, "i:htons", &x1)) {
+ return NULL;
+ }
+ if (x1 < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ x2 = (unsigned int)htons((unsigned short)x1);
+ return PyInt_FromLong(x2);
}
PyDoc_STRVAR(htons_doc,
@@ -3758,39 +3758,39 @@ Convert a 16-bit integer from host to network byte order.");
static PyObject *
socket_htonl(PyObject *self, PyObject *arg)
{
- unsigned long x;
-
- if (PyInt_Check(arg)) {
- x = PyInt_AS_LONG(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
- if ((long)x < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative number to unsigned long");
- return NULL;
- }
- }
- else if (PyLong_Check(arg)) {
- x = PyLong_AsUnsignedLong(arg);
- if (x == (unsigned long) -1 && PyErr_Occurred())
- return NULL;
+ unsigned long x;
+
+ if (PyInt_Check(arg)) {
+ x = PyInt_AS_LONG(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
+ if ((long)x < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative number to unsigned long");
+ return NULL;
+ }
+ }
+ else if (PyLong_Check(arg)) {
+ x = PyLong_AsUnsignedLong(arg);
+ if (x == (unsigned long) -1 && PyErr_Occurred())
+ return NULL;
#if SIZEOF_LONG > 4
- {
- unsigned long y;
- /* only want the trailing 32 bits */
- y = x & 0xFFFFFFFFUL;
- if (y ^ x)
- return PyErr_Format(PyExc_OverflowError,
- "long int larger than 32 bits");
- x = y;
- }
-#endif
- }
- else
- return PyErr_Format(PyExc_TypeError,
- "expected int/long, %s found",
- Py_TYPE(arg)->tp_name);
- return PyLong_FromUnsignedLong(htonl((unsigned long)x));
+ {
+ unsigned long y;
+ /* only want the trailing 32 bits */
+ y = x & 0xFFFFFFFFUL;
+ if (y ^ x)
+ return PyErr_Format(PyExc_OverflowError,
+ "long int larger than 32 bits");
+ x = y;
+ }
+#endif
+ }
+ else
+ return PyErr_Format(PyExc_TypeError,
+ "expected int/long, %s found",
+ Py_TYPE(arg)->tp_name);
+ return PyLong_FromUnsignedLong(htonl((unsigned long)x));
}
PyDoc_STRVAR(htonl_doc,
@@ -3813,20 +3813,20 @@ socket_inet_aton(PyObject *self, PyObject *args)
#define INADDR_NONE (-1)
#endif
#ifdef HAVE_INET_ATON
- struct in_addr buf;
+ struct in_addr buf;
#endif
#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
#if (SIZEOF_INT != 4)
#error "Not sure if in_addr_t exists and int is not 32-bits."
#endif
- /* Have to use inet_addr() instead */
- unsigned int packed_addr;
+ /* Have to use inet_addr() instead */
+ unsigned int packed_addr;
#endif
- char *ip_addr;
+ char *ip_addr;
- if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:inet_aton", &ip_addr))
+ return NULL;
#ifdef HAVE_INET_ATON
@@ -3834,13 +3834,13 @@ socket_inet_aton(PyObject *self, PyObject *args)
#ifdef USE_INET_ATON_WEAKLINK
if (inet_aton != NULL) {
#endif
- if (inet_aton(ip_addr, &buf))
- return PyString_FromStringAndSize((char *)(&buf),
- sizeof(buf));
+ if (inet_aton(ip_addr, &buf))
+ return PyString_FromStringAndSize((char *)(&buf),
+ sizeof(buf));
- PyErr_SetString(socket_error,
- "illegal IP address string passed to inet_aton");
- return NULL;
+ PyErr_SetString(socket_error,
+ "illegal IP address string passed to inet_aton");
+ return NULL;
#ifdef USE_INET_ATON_WEAKLINK
} else {
@@ -3850,22 +3850,22 @@ socket_inet_aton(PyObject *self, PyObject *args)
#if !defined(HAVE_INET_ATON) || defined(USE_INET_ATON_WEAKLINK)
- /* special-case this address as inet_addr might return INADDR_NONE
- * for this */
- if (strcmp(ip_addr, "255.255.255.255") == 0) {
- packed_addr = 0xFFFFFFFF;
- } else {
+ /* special-case this address as inet_addr might return INADDR_NONE
+ * for this */
+ if (strcmp(ip_addr, "255.255.255.255") == 0) {
+ packed_addr = 0xFFFFFFFF;
+ } else {
- packed_addr = inet_addr(ip_addr);
+ packed_addr = inet_addr(ip_addr);
- if (packed_addr == INADDR_NONE) { /* invalid address */
- PyErr_SetString(socket_error,
- "illegal IP address string passed to inet_aton");
- return NULL;
- }
- }
- return PyString_FromStringAndSize((char *) &packed_addr,
- sizeof(packed_addr));
+ if (packed_addr == INADDR_NONE) { /* invalid address */
+ PyErr_SetString(socket_error,
+ "illegal IP address string passed to inet_aton");
+ return NULL;
+ }
+ }
+ return PyString_FromStringAndSize((char *) &packed_addr,
+ sizeof(packed_addr));
#ifdef USE_INET_ATON_WEAKLINK
}
@@ -3882,23 +3882,23 @@ Convert an IP address from 32-bit packed binary format to string format");
static PyObject*
socket_inet_ntoa(PyObject *self, PyObject *args)
{
- char *packed_str;
- int addr_len;
- struct in_addr packed_addr;
+ char *packed_str;
+ int addr_len;
+ struct in_addr packed_addr;
- if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "s#:inet_ntoa", &packed_str, &addr_len)) {
+ return NULL;
+ }
- if (addr_len != sizeof(packed_addr)) {
- PyErr_SetString(socket_error,
- "packed IP wrong length for inet_ntoa");
- return NULL;
- }
+ if (addr_len != sizeof(packed_addr)) {
+ PyErr_SetString(socket_error,
+ "packed IP wrong length for inet_ntoa");
+ return NULL;
+ }
- memcpy(&packed_addr, packed_str, addr_len);
+ memcpy(&packed_addr, packed_str, addr_len);
- return PyString_FromString(inet_ntoa(packed_addr));
+ return PyString_FromString(inet_ntoa(packed_addr));
}
#ifdef HAVE_INET_PTON
@@ -3912,46 +3912,46 @@ for use with low-level network functions.");
static PyObject *
socket_inet_pton(PyObject *self, PyObject *args)
{
- int af;
- char* ip;
- int retval;
+ int af;
+ char* ip;
+ int retval;
#ifdef ENABLE_IPV6
- char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
+ char packed[MAX(sizeof(struct in_addr), sizeof(struct in6_addr))];
#else
- char packed[sizeof(struct in_addr)];
+ char packed[sizeof(struct in_addr)];
#endif
- if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "is:inet_pton", &af, &ip)) {
+ return NULL;
+ }
#if !defined(ENABLE_IPV6) && defined(AF_INET6)
- if(af == AF_INET6) {
- PyErr_SetString(socket_error,
- "can't use AF_INET6, IPv6 is disabled");
- return NULL;
- }
-#endif
-
- retval = inet_pton(af, ip, packed);
- if (retval < 0) {
- PyErr_SetFromErrno(socket_error);
- return NULL;
- } else if (retval == 0) {
- PyErr_SetString(socket_error,
- "illegal IP address string passed to inet_pton");
- return NULL;
- } else if (af == AF_INET) {
- return PyString_FromStringAndSize(packed,
- sizeof(struct in_addr));
+ if(af == AF_INET6) {
+ PyErr_SetString(socket_error,
+ "can't use AF_INET6, IPv6 is disabled");
+ return NULL;
+ }
+#endif
+
+ retval = inet_pton(af, ip, packed);
+ if (retval < 0) {
+ PyErr_SetFromErrno(socket_error);
+ return NULL;
+ } else if (retval == 0) {
+ PyErr_SetString(socket_error,
+ "illegal IP address string passed to inet_pton");
+ return NULL;
+ } else if (af == AF_INET) {
+ return PyString_FromStringAndSize(packed,
+ sizeof(struct in_addr));
#ifdef ENABLE_IPV6
- } else if (af == AF_INET6) {
- return PyString_FromStringAndSize(packed,
- sizeof(struct in6_addr));
-#endif
- } else {
- PyErr_SetString(socket_error, "unknown address family");
- return NULL;
- }
+ } else if (af == AF_INET6) {
+ return PyString_FromStringAndSize(packed,
+ sizeof(struct in6_addr));
+#endif
+ } else {
+ PyErr_SetString(socket_error, "unknown address family");
+ return NULL;
+ }
}
PyDoc_STRVAR(inet_ntop_doc,
@@ -3962,54 +3962,54 @@ Convert a packed IP address of the given family to string format.");
static PyObject *
socket_inet_ntop(PyObject *self, PyObject *args)
{
- int af;
- char* packed;
- int len;
- const char* retval;
+ int af;
+ char* packed;
+ int len;
+ const char* retval;
#ifdef ENABLE_IPV6
- char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
+ char ip[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN) + 1];
#else
- char ip[INET_ADDRSTRLEN + 1];
+ char ip[INET_ADDRSTRLEN + 1];
#endif
- /* Guarantee NUL-termination for PyString_FromString() below */
- memset((void *) &ip[0], '\0', sizeof(ip));
+ /* Guarantee NUL-termination for PyString_FromString() below */
+ memset((void *) &ip[0], '\0', sizeof(ip));
- if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
- return NULL;
- }
+ if (!PyArg_ParseTuple(args, "is#:inet_ntop", &af, &packed, &len)) {
+ return NULL;
+ }
- if (af == AF_INET) {
- if (len != sizeof(struct in_addr)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid length of packed IP address string");
- return NULL;
- }
+ if (af == AF_INET) {
+ if (len != sizeof(struct in_addr)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid length of packed IP address string");
+ return NULL;
+ }
#ifdef ENABLE_IPV6
- } else if (af == AF_INET6) {
- if (len != sizeof(struct in6_addr)) {
- PyErr_SetString(PyExc_ValueError,
- "invalid length of packed IP address string");
- return NULL;
- }
-#endif
- } else {
- PyErr_Format(PyExc_ValueError,
- "unknown address family %d", af);
- return NULL;
- }
-
- retval = inet_ntop(af, packed, ip, sizeof(ip));
- if (!retval) {
- PyErr_SetFromErrno(socket_error);
- return NULL;
- } else {
- return PyString_FromString(retval);
- }
-
- /* NOTREACHED */
- PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
- return NULL;
+ } else if (af == AF_INET6) {
+ if (len != sizeof(struct in6_addr)) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid length of packed IP address string");
+ return NULL;
+ }
+#endif
+ } else {
+ PyErr_Format(PyExc_ValueError,
+ "unknown address family %d", af);
+ return NULL;
+ }
+
+ retval = inet_ntop(af, packed, ip, sizeof(ip));
+ if (!retval) {
+ PyErr_SetFromErrno(socket_error);
+ return NULL;
+ } else {
+ return PyString_FromString(retval);
+ }
+
+ /* NOTREACHED */
+ PyErr_SetString(PyExc_RuntimeError, "invalid handling of inet_ntop");
+ return NULL;
}
#endif /* HAVE_INET_PTON */
@@ -4020,95 +4020,95 @@ socket_inet_ntop(PyObject *self, PyObject *args)
static PyObject *
socket_getaddrinfo(PyObject *self, PyObject *args)
{
- struct addrinfo hints, *res;
- struct addrinfo *res0 = NULL;
- PyObject *hobj = NULL;
- PyObject *pobj = (PyObject *)NULL;
- char pbuf[30];
- char *hptr, *pptr;
- int family, socktype, protocol, flags;
- int error;
- PyObject *all = (PyObject *)NULL;
- PyObject *single = (PyObject *)NULL;
- PyObject *idna = NULL;
-
- family = socktype = protocol = flags = 0;
- family = AF_UNSPEC;
- if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
- &hobj, &pobj, &family, &socktype,
- &protocol, &flags)) {
- return NULL;
- }
- if (hobj == Py_None) {
- hptr = NULL;
- } else if (PyUnicode_Check(hobj)) {
- idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
- if (!idna)
- return NULL;
- hptr = PyString_AsString(idna);
- } else if (PyString_Check(hobj)) {
- hptr = PyString_AsString(hobj);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "getaddrinfo() argument 1 must be string or None");
- return NULL;
- }
- if (PyInt_Check(pobj)) {
- PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
- pptr = pbuf;
- } else if (PyString_Check(pobj)) {
- pptr = PyString_AsString(pobj);
- } else if (pobj == Py_None) {
- pptr = (char *)NULL;
- } else {
- PyErr_SetString(socket_error, "Int or String expected");
- goto err;
- }
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = family;
- hints.ai_socktype = socktype;
- hints.ai_protocol = protocol;
- hints.ai_flags = flags;
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(hptr, pptr, &hints, &res0);
- Py_END_ALLOW_THREADS
- RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
- if (error) {
- set_gaierror(error);
- goto err;
- }
-
- if ((all = PyList_New(0)) == NULL)
- goto err;
- for (res = res0; res; res = res->ai_next) {
- PyObject *addr =
- makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
- if (addr == NULL)
- goto err;
- single = Py_BuildValue("iiisO", res->ai_family,
- res->ai_socktype, res->ai_protocol,
- res->ai_canonname ? res->ai_canonname : "",
- addr);
- Py_DECREF(addr);
- if (single == NULL)
- goto err;
-
- if (PyList_Append(all, single))
- goto err;
- Py_XDECREF(single);
- }
- Py_XDECREF(idna);
- if (res0)
- freeaddrinfo(res0);
- return all;
+ struct addrinfo hints, *res;
+ struct addrinfo *res0 = NULL;
+ PyObject *hobj = NULL;
+ PyObject *pobj = (PyObject *)NULL;
+ char pbuf[30];
+ char *hptr, *pptr;
+ int family, socktype, protocol, flags;
+ int error;
+ PyObject *all = (PyObject *)NULL;
+ PyObject *single = (PyObject *)NULL;
+ PyObject *idna = NULL;
+
+ family = socktype = protocol = flags = 0;
+ family = AF_UNSPEC;
+ if (!PyArg_ParseTuple(args, "OO|iiii:getaddrinfo",
+ &hobj, &pobj, &family, &socktype,
+ &protocol, &flags)) {
+ return NULL;
+ }
+ if (hobj == Py_None) {
+ hptr = NULL;
+ } else if (PyUnicode_Check(hobj)) {
+ idna = PyObject_CallMethod(hobj, "encode", "s", "idna");
+ if (!idna)
+ return NULL;
+ hptr = PyString_AsString(idna);
+ } else if (PyString_Check(hobj)) {
+ hptr = PyString_AsString(hobj);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "getaddrinfo() argument 1 must be string or None");
+ return NULL;
+ }
+ if (PyInt_Check(pobj)) {
+ PyOS_snprintf(pbuf, sizeof(pbuf), "%ld", PyInt_AsLong(pobj));
+ pptr = pbuf;
+ } else if (PyString_Check(pobj)) {
+ pptr = PyString_AsString(pobj);
+ } else if (pobj == Py_None) {
+ pptr = (char *)NULL;
+ } else {
+ PyErr_SetString(socket_error, "Int or String expected");
+ goto err;
+ }
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = family;
+ hints.ai_socktype = socktype;
+ hints.ai_protocol = protocol;
+ hints.ai_flags = flags;
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(hptr, pptr, &hints, &res0);
+ Py_END_ALLOW_THREADS
+ RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
+ if (error) {
+ set_gaierror(error);
+ goto err;
+ }
+
+ if ((all = PyList_New(0)) == NULL)
+ goto err;
+ for (res = res0; res; res = res->ai_next) {
+ PyObject *addr =
+ makesockaddr(-1, res->ai_addr, res->ai_addrlen, protocol);
+ if (addr == NULL)
+ goto err;
+ single = Py_BuildValue("iiisO", res->ai_family,
+ res->ai_socktype, res->ai_protocol,
+ res->ai_canonname ? res->ai_canonname : "",
+ addr);
+ Py_DECREF(addr);
+ if (single == NULL)
+ goto err;
+
+ if (PyList_Append(all, single))
+ goto err;
+ Py_XDECREF(single);
+ }
+ Py_XDECREF(idna);
+ if (res0)
+ freeaddrinfo(res0);
+ return all;
err:
- Py_XDECREF(single);
- Py_XDECREF(all);
- Py_XDECREF(idna);
- if (res0)
- freeaddrinfo(res0);
- return (PyObject *)NULL;
+ Py_XDECREF(single);
+ Py_XDECREF(all);
+ Py_XDECREF(idna);
+ if (res0)
+ freeaddrinfo(res0);
+ return (PyObject *)NULL;
}
PyDoc_STRVAR(getaddrinfo_doc,
@@ -4123,77 +4123,77 @@ Resolve host and port into addrinfo struct.");
static PyObject *
socket_getnameinfo(PyObject *self, PyObject *args)
{
- PyObject *sa = (PyObject *)NULL;
- int flags;
- char *hostp;
- int port, flowinfo, scope_id;
- char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
- struct addrinfo hints, *res = NULL;
- int error;
- PyObject *ret = (PyObject *)NULL;
-
- flags = flowinfo = scope_id = 0;
- if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
- return NULL;
- if (!PyTuple_Check(sa)) {
- PyErr_SetString(PyExc_TypeError,
- "getnameinfo() argument 1 must be a tuple");
- return NULL;
- }
- if (!PyArg_ParseTuple(sa, "si|ii",
- &hostp, &port, &flowinfo, &scope_id))
- return NULL;
- PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
- memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC;
- hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
- Py_BEGIN_ALLOW_THREADS
- ACQUIRE_GETADDRINFO_LOCK
- error = getaddrinfo(hostp, pbuf, &hints, &res);
- Py_END_ALLOW_THREADS
- RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
- if (error) {
- set_gaierror(error);
- goto fail;
- }
- if (res->ai_next) {
- PyErr_SetString(socket_error,
- "sockaddr resolved to multiple addresses");
- goto fail;
- }
- switch (res->ai_family) {
- case AF_INET:
- {
- if (PyTuple_GET_SIZE(sa) != 2) {
- PyErr_SetString(socket_error,
- "IPv4 sockaddr must be 2 tuple");
- goto fail;
- }
- break;
- }
+ PyObject *sa = (PyObject *)NULL;
+ int flags;
+ char *hostp;
+ int port, flowinfo, scope_id;
+ char hbuf[NI_MAXHOST], pbuf[NI_MAXSERV];
+ struct addrinfo hints, *res = NULL;
+ int error;
+ PyObject *ret = (PyObject *)NULL;
+
+ flags = flowinfo = scope_id = 0;
+ if (!PyArg_ParseTuple(args, "Oi:getnameinfo", &sa, &flags))
+ return NULL;
+ if (!PyTuple_Check(sa)) {
+ PyErr_SetString(PyExc_TypeError,
+ "getnameinfo() argument 1 must be a tuple");
+ return NULL;
+ }
+ if (!PyArg_ParseTuple(sa, "si|ii",
+ &hostp, &port, &flowinfo, &scope_id))
+ return NULL;
+ PyOS_snprintf(pbuf, sizeof(pbuf), "%d", port);
+ memset(&hints, 0, sizeof(hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_DGRAM; /* make numeric port happy */
+ Py_BEGIN_ALLOW_THREADS
+ ACQUIRE_GETADDRINFO_LOCK
+ error = getaddrinfo(hostp, pbuf, &hints, &res);
+ Py_END_ALLOW_THREADS
+ RELEASE_GETADDRINFO_LOCK /* see comment in setipaddr() */
+ if (error) {
+ set_gaierror(error);
+ goto fail;
+ }
+ if (res->ai_next) {
+ PyErr_SetString(socket_error,
+ "sockaddr resolved to multiple addresses");
+ goto fail;
+ }
+ switch (res->ai_family) {
+ case AF_INET:
+ {
+ if (PyTuple_GET_SIZE(sa) != 2) {
+ PyErr_SetString(socket_error,
+ "IPv4 sockaddr must be 2 tuple");
+ goto fail;
+ }
+ break;
+ }
#ifdef ENABLE_IPV6
- case AF_INET6:
- {
- struct sockaddr_in6 *sin6;
- sin6 = (struct sockaddr_in6 *)res->ai_addr;
- sin6->sin6_flowinfo = flowinfo;
- sin6->sin6_scope_id = scope_id;
- break;
- }
-#endif
- }
- error = getnameinfo(res->ai_addr, res->ai_addrlen,
- hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
- if (error) {
- set_gaierror(error);
- goto fail;
- }
- ret = Py_BuildValue("ss", hbuf, pbuf);
+ case AF_INET6:
+ {
+ struct sockaddr_in6 *sin6;
+ sin6 = (struct sockaddr_in6 *)res->ai_addr;
+ sin6->sin6_flowinfo = flowinfo;
+ sin6->sin6_scope_id = scope_id;
+ break;
+ }
+#endif
+ }
+ error = getnameinfo(res->ai_addr, res->ai_addrlen,
+ hbuf, sizeof(hbuf), pbuf, sizeof(pbuf), flags);
+ if (error) {
+ set_gaierror(error);
+ goto fail;
+ }
+ ret = Py_BuildValue("ss", hbuf, pbuf);
fail:
- if (res)
- freeaddrinfo(res);
- return ret;
+ if (res)
+ freeaddrinfo(res);
+ return ret;
}
PyDoc_STRVAR(getnameinfo_doc,
@@ -4207,12 +4207,12 @@ Get host and port for a sockaddr.");
static PyObject *
socket_getdefaulttimeout(PyObject *self)
{
- if (defaulttimeout < 0.0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else
- return PyFloat_FromDouble(defaulttimeout);
+ if (defaulttimeout < 0.0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else
+ return PyFloat_FromDouble(defaulttimeout);
}
PyDoc_STRVAR(getdefaulttimeout_doc,
@@ -4225,24 +4225,24 @@ When the socket module is first imported, the default is None.");
static PyObject *
socket_setdefaulttimeout(PyObject *self, PyObject *arg)
{
- double timeout;
-
- if (arg == Py_None)
- timeout = -1.0;
- else {
- timeout = PyFloat_AsDouble(arg);
- if (timeout < 0.0) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_ValueError,
- "Timeout value out of range");
- return NULL;
- }
- }
-
- defaulttimeout = timeout;
-
- Py_INCREF(Py_None);
- return Py_None;
+ double timeout;
+
+ if (arg == Py_None)
+ timeout = -1.0;
+ else {
+ timeout = PyFloat_AsDouble(arg);
+ if (timeout < 0.0) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_ValueError,
+ "Timeout value out of range");
+ return NULL;
+ }
+ }
+
+ defaulttimeout = timeout;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setdefaulttimeout_doc,
@@ -4256,55 +4256,55 @@ When the socket module is first imported, the default is None.");
/* List of functions exported by this module. */
static PyMethodDef socket_methods[] = {
- {"gethostbyname", socket_gethostbyname,
- METH_VARARGS, gethostbyname_doc},
- {"gethostbyname_ex", socket_gethostbyname_ex,
- METH_VARARGS, ghbn_ex_doc},
- {"gethostbyaddr", socket_gethostbyaddr,
- METH_VARARGS, gethostbyaddr_doc},
- {"gethostname", socket_gethostname,
- METH_NOARGS, gethostname_doc},
- {"getservbyname", socket_getservbyname,
- METH_VARARGS, getservbyname_doc},
- {"getservbyport", socket_getservbyport,
- METH_VARARGS, getservbyport_doc},
- {"getprotobyname", socket_getprotobyname,
- METH_VARARGS, getprotobyname_doc},
+ {"gethostbyname", socket_gethostbyname,
+ METH_VARARGS, gethostbyname_doc},
+ {"gethostbyname_ex", socket_gethostbyname_ex,
+ METH_VARARGS, ghbn_ex_doc},
+ {"gethostbyaddr", socket_gethostbyaddr,
+ METH_VARARGS, gethostbyaddr_doc},
+ {"gethostname", socket_gethostname,
+ METH_NOARGS, gethostname_doc},
+ {"getservbyname", socket_getservbyname,
+ METH_VARARGS, getservbyname_doc},
+ {"getservbyport", socket_getservbyport,
+ METH_VARARGS, getservbyport_doc},
+ {"getprotobyname", socket_getprotobyname,
+ METH_VARARGS, getprotobyname_doc},
#ifndef NO_DUP
- {"fromfd", socket_fromfd,
- METH_VARARGS, fromfd_doc},
+ {"fromfd", socket_fromfd,
+ METH_VARARGS, fromfd_doc},
#endif
#ifdef HAVE_SOCKETPAIR
- {"socketpair", socket_socketpair,
- METH_VARARGS, socketpair_doc},
-#endif
- {"ntohs", socket_ntohs,
- METH_VARARGS, ntohs_doc},
- {"ntohl", socket_ntohl,
- METH_O, ntohl_doc},
- {"htons", socket_htons,
- METH_VARARGS, htons_doc},
- {"htonl", socket_htonl,
- METH_O, htonl_doc},
- {"inet_aton", socket_inet_aton,
- METH_VARARGS, inet_aton_doc},
- {"inet_ntoa", socket_inet_ntoa,
- METH_VARARGS, inet_ntoa_doc},
+ {"socketpair", socket_socketpair,
+ METH_VARARGS, socketpair_doc},
+#endif
+ {"ntohs", socket_ntohs,
+ METH_VARARGS, ntohs_doc},
+ {"ntohl", socket_ntohl,
+ METH_O, ntohl_doc},
+ {"htons", socket_htons,
+ METH_VARARGS, htons_doc},
+ {"htonl", socket_htonl,
+ METH_O, htonl_doc},
+ {"inet_aton", socket_inet_aton,
+ METH_VARARGS, inet_aton_doc},
+ {"inet_ntoa", socket_inet_ntoa,
+ METH_VARARGS, inet_ntoa_doc},
#ifdef HAVE_INET_PTON
- {"inet_pton", socket_inet_pton,
- METH_VARARGS, inet_pton_doc},
- {"inet_ntop", socket_inet_ntop,
- METH_VARARGS, inet_ntop_doc},
-#endif
- {"getaddrinfo", socket_getaddrinfo,
- METH_VARARGS, getaddrinfo_doc},
- {"getnameinfo", socket_getnameinfo,
- METH_VARARGS, getnameinfo_doc},
- {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
- METH_NOARGS, getdefaulttimeout_doc},
- {"setdefaulttimeout", socket_setdefaulttimeout,
- METH_O, setdefaulttimeout_doc},
- {NULL, NULL} /* Sentinel */
+ {"inet_pton", socket_inet_pton,
+ METH_VARARGS, inet_pton_doc},
+ {"inet_ntop", socket_inet_ntop,
+ METH_VARARGS, inet_ntop_doc},
+#endif
+ {"getaddrinfo", socket_getaddrinfo,
+ METH_VARARGS, getaddrinfo_doc},
+ {"getnameinfo", socket_getnameinfo,
+ METH_VARARGS, getnameinfo_doc},
+ {"getdefaulttimeout", (PyCFunction)socket_getdefaulttimeout,
+ METH_NOARGS, getdefaulttimeout_doc},
+ {"setdefaulttimeout", socket_setdefaulttimeout,
+ METH_O, setdefaulttimeout_doc},
+ {NULL, NULL} /* Sentinel */
};
@@ -4314,13 +4314,13 @@ static PyMethodDef socket_methods[] = {
static int
os_init(void)
{
- _kernel_swi_regs r;
+ _kernel_swi_regs r;
- r.r[0] = 0;
- _kernel_swi(0x43380, &r, &r);
- taskwindow = r.r[0];
+ r.r[0] = 0;
+ _kernel_swi(0x43380, &r, &r);
+ taskwindow = r.r[0];
- return 1;
+ return 1;
}
#endif /* RISCOS */
@@ -4334,37 +4334,37 @@ os_init(void)
static void
os_cleanup(void)
{
- WSACleanup();
+ WSACleanup();
}
static int
os_init(void)
{
- WSADATA WSAData;
- int ret;
- char buf[100];
- ret = WSAStartup(0x0101, &WSAData);
- switch (ret) {
- case 0: /* No error */
- Py_AtExit(os_cleanup);
- return 1; /* Success */
- case WSASYSNOTREADY:
- PyErr_SetString(PyExc_ImportError,
- "WSAStartup failed: network not ready");
- break;
- case WSAVERNOTSUPPORTED:
- case WSAEINVAL:
- PyErr_SetString(
- PyExc_ImportError,
- "WSAStartup failed: requested version not supported");
- break;
- default:
- PyOS_snprintf(buf, sizeof(buf),
- "WSAStartup failed: error code %d", ret);
- PyErr_SetString(PyExc_ImportError, buf);
- break;
- }
- return 0; /* Failure */
+ WSADATA WSAData;
+ int ret;
+ char buf[100];
+ ret = WSAStartup(0x0101, &WSAData);
+ switch (ret) {
+ case 0: /* No error */
+ Py_AtExit(os_cleanup);
+ return 1; /* Success */
+ case WSASYSNOTREADY:
+ PyErr_SetString(PyExc_ImportError,
+ "WSAStartup failed: network not ready");
+ break;
+ case WSAVERNOTSUPPORTED:
+ case WSAEINVAL:
+ PyErr_SetString(
+ PyExc_ImportError,
+ "WSAStartup failed: requested version not supported");
+ break;
+ default:
+ PyOS_snprintf(buf, sizeof(buf),
+ "WSAStartup failed: error code %d", ret);
+ PyErr_SetString(PyExc_ImportError, buf);
+ break;
+ }
+ return 0; /* Failure */
}
#endif /* MS_WINDOWS */
@@ -4379,21 +4379,21 @@ static int
os_init(void)
{
#ifndef PYCC_GCC
- char reason[64];
- int rc = sock_init();
+ char reason[64];
+ int rc = sock_init();
- if (rc == 0) {
- return 1; /* Success */
- }
+ if (rc == 0) {
+ return 1; /* Success */
+ }
- PyOS_snprintf(reason, sizeof(reason),
- "OS/2 TCP/IP Error# %d", sock_errno());
- PyErr_SetString(PyExc_ImportError, reason);
+ PyOS_snprintf(reason, sizeof(reason),
+ "OS/2 TCP/IP Error# %d", sock_errno());
+ PyErr_SetString(PyExc_ImportError, reason);
- return 0; /* Failure */
+ return 0; /* Failure */
#else
- /* No need to initialise sockets with GCC/EMX */
- return 1; /* Success */
+ /* No need to initialise sockets with GCC/EMX */
+ return 1; /* Success */
#endif
}
@@ -4404,7 +4404,7 @@ os_init(void)
static int
os_init(void)
{
- return 1; /* Success */
+ return 1; /* Success */
}
#endif
@@ -4414,8 +4414,8 @@ os_init(void)
static
PySocketModule_APIObject PySocketModuleAPI =
{
- &sock_type,
- NULL
+ &sock_type,
+ NULL
};
@@ -4440,919 +4440,919 @@ See the socket module for documentation.");
PyMODINIT_FUNC
init_socket(void)
{
- PyObject *m, *has_ipv6;
-
- if (!os_init())
- return;
-
- Py_TYPE(&sock_type) = &PyType_Type;
- m = Py_InitModule3(PySocket_MODULE_NAME,
- socket_methods,
- socket_doc);
- if (m == NULL)
- return;
-
- socket_error = PyErr_NewException("socket.error",
- PyExc_IOError, NULL);
- if (socket_error == NULL)
- return;
- PySocketModuleAPI.error = socket_error;
- Py_INCREF(socket_error);
- PyModule_AddObject(m, "error", socket_error);
- socket_herror = PyErr_NewException("socket.herror",
- socket_error, NULL);
- if (socket_herror == NULL)
- return;
- Py_INCREF(socket_herror);
- PyModule_AddObject(m, "herror", socket_herror);
- socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
- NULL);
- if (socket_gaierror == NULL)
- return;
- Py_INCREF(socket_gaierror);
- PyModule_AddObject(m, "gaierror", socket_gaierror);
- socket_timeout = PyErr_NewException("socket.timeout",
- socket_error, NULL);
- if (socket_timeout == NULL)
- return;
- Py_INCREF(socket_timeout);
- PyModule_AddObject(m, "timeout", socket_timeout);
- Py_INCREF((PyObject *)&sock_type);
- if (PyModule_AddObject(m, "SocketType",
- (PyObject *)&sock_type) != 0)
- return;
- Py_INCREF((PyObject *)&sock_type);
- if (PyModule_AddObject(m, "socket",
- (PyObject *)&sock_type) != 0)
- return;
+ PyObject *m, *has_ipv6;
+
+ if (!os_init())
+ return;
+
+ Py_TYPE(&sock_type) = &PyType_Type;
+ m = Py_InitModule3(PySocket_MODULE_NAME,
+ socket_methods,
+ socket_doc);
+ if (m == NULL)
+ return;
+
+ socket_error = PyErr_NewException("socket.error",
+ PyExc_IOError, NULL);
+ if (socket_error == NULL)
+ return;
+ PySocketModuleAPI.error = socket_error;
+ Py_INCREF(socket_error);
+ PyModule_AddObject(m, "error", socket_error);
+ socket_herror = PyErr_NewException("socket.herror",
+ socket_error, NULL);
+ if (socket_herror == NULL)
+ return;
+ Py_INCREF(socket_herror);
+ PyModule_AddObject(m, "herror", socket_herror);
+ socket_gaierror = PyErr_NewException("socket.gaierror", socket_error,
+ NULL);
+ if (socket_gaierror == NULL)
+ return;
+ Py_INCREF(socket_gaierror);
+ PyModule_AddObject(m, "gaierror", socket_gaierror);
+ socket_timeout = PyErr_NewException("socket.timeout",
+ socket_error, NULL);
+ if (socket_timeout == NULL)
+ return;
+ Py_INCREF(socket_timeout);
+ PyModule_AddObject(m, "timeout", socket_timeout);
+ Py_INCREF((PyObject *)&sock_type);
+ if (PyModule_AddObject(m, "SocketType",
+ (PyObject *)&sock_type) != 0)
+ return;
+ Py_INCREF((PyObject *)&sock_type);
+ if (PyModule_AddObject(m, "socket",
+ (PyObject *)&sock_type) != 0)
+ return;
#ifdef ENABLE_IPV6
- has_ipv6 = Py_True;
+ has_ipv6 = Py_True;
#else
- has_ipv6 = Py_False;
+ has_ipv6 = Py_False;
#endif
- Py_INCREF(has_ipv6);
- PyModule_AddObject(m, "has_ipv6", has_ipv6);
+ Py_INCREF(has_ipv6);
+ PyModule_AddObject(m, "has_ipv6", has_ipv6);
- /* Export C API */
- if (PyModule_AddObject(m, PySocket_CAPI_NAME,
- PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
- ) != 0)
- return;
+ /* Export C API */
+ if (PyModule_AddObject(m, PySocket_CAPI_NAME,
+ PyCapsule_New(&PySocketModuleAPI, PySocket_CAPSULE_NAME, NULL)
+ ) != 0)
+ return;
- /* Address families (we only support AF_INET and AF_UNIX) */
+ /* Address families (we only support AF_INET and AF_UNIX) */
#ifdef AF_UNSPEC
- PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
+ PyModule_AddIntConstant(m, "AF_UNSPEC", AF_UNSPEC);
#endif
- PyModule_AddIntConstant(m, "AF_INET", AF_INET);
+ PyModule_AddIntConstant(m, "AF_INET", AF_INET);
#ifdef AF_INET6
- PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
+ PyModule_AddIntConstant(m, "AF_INET6", AF_INET6);
#endif /* AF_INET6 */
#if defined(AF_UNIX)
- PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
+ PyModule_AddIntConstant(m, "AF_UNIX", AF_UNIX);
#endif /* AF_UNIX */
#ifdef AF_AX25
- /* Amateur Radio AX.25 */
- PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
+ /* Amateur Radio AX.25 */
+ PyModule_AddIntConstant(m, "AF_AX25", AF_AX25);
#endif
#ifdef AF_IPX
- PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
+ PyModule_AddIntConstant(m, "AF_IPX", AF_IPX); /* Novell IPX */
#endif
#ifdef AF_APPLETALK
- /* Appletalk DDP */
- PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
+ /* Appletalk DDP */
+ PyModule_AddIntConstant(m, "AF_APPLETALK", AF_APPLETALK);
#endif
#ifdef AF_NETROM
- /* Amateur radio NetROM */
- PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
+ /* Amateur radio NetROM */
+ PyModule_AddIntConstant(m, "AF_NETROM", AF_NETROM);
#endif
#ifdef AF_BRIDGE
- /* Multiprotocol bridge */
- PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
+ /* Multiprotocol bridge */
+ PyModule_AddIntConstant(m, "AF_BRIDGE", AF_BRIDGE);
#endif
#ifdef AF_ATMPVC
- /* ATM PVCs */
- PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
+ /* ATM PVCs */
+ PyModule_AddIntConstant(m, "AF_ATMPVC", AF_ATMPVC);
#endif
#ifdef AF_AAL5
- /* Reserved for Werner's ATM */
- PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
+ /* Reserved for Werner's ATM */
+ PyModule_AddIntConstant(m, "AF_AAL5", AF_AAL5);
#endif
#ifdef AF_X25
- /* Reserved for X.25 project */
- PyModule_AddIntConstant(m, "AF_X25", AF_X25);
+ /* Reserved for X.25 project */
+ PyModule_AddIntConstant(m, "AF_X25", AF_X25);
#endif
#ifdef AF_INET6
- PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
+ PyModule_AddIntConstant(m, "AF_INET6", AF_INET6); /* IP version 6 */
#endif
#ifdef AF_ROSE
- /* Amateur Radio X.25 PLP */
- PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
+ /* Amateur Radio X.25 PLP */
+ PyModule_AddIntConstant(m, "AF_ROSE", AF_ROSE);
#endif
#ifdef AF_DECnet
- /* Reserved for DECnet project */
- PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
+ /* Reserved for DECnet project */
+ PyModule_AddIntConstant(m, "AF_DECnet", AF_DECnet);
#endif
#ifdef AF_NETBEUI
- /* Reserved for 802.2LLC project */
- PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
+ /* Reserved for 802.2LLC project */
+ PyModule_AddIntConstant(m, "AF_NETBEUI", AF_NETBEUI);
#endif
#ifdef AF_SECURITY
- /* Security callback pseudo AF */
- PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
+ /* Security callback pseudo AF */
+ PyModule_AddIntConstant(m, "AF_SECURITY", AF_SECURITY);
#endif
#ifdef AF_KEY
- /* PF_KEY key management API */
- PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
+ /* PF_KEY key management API */
+ PyModule_AddIntConstant(m, "AF_KEY", AF_KEY);
#endif
#ifdef AF_NETLINK
- /* */
- PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
- PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
+ /* */
+ PyModule_AddIntConstant(m, "AF_NETLINK", AF_NETLINK);
+ PyModule_AddIntConstant(m, "NETLINK_ROUTE", NETLINK_ROUTE);
#ifdef NETLINK_SKIP
- PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
+ PyModule_AddIntConstant(m, "NETLINK_SKIP", NETLINK_SKIP);
#endif
#ifdef NETLINK_W1
- PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
+ PyModule_AddIntConstant(m, "NETLINK_W1", NETLINK_W1);
#endif
- PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
- PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
+ PyModule_AddIntConstant(m, "NETLINK_USERSOCK", NETLINK_USERSOCK);
+ PyModule_AddIntConstant(m, "NETLINK_FIREWALL", NETLINK_FIREWALL);
#ifdef NETLINK_TCPDIAG
- PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
+ PyModule_AddIntConstant(m, "NETLINK_TCPDIAG", NETLINK_TCPDIAG);
#endif
#ifdef NETLINK_NFLOG
- PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
+ PyModule_AddIntConstant(m, "NETLINK_NFLOG", NETLINK_NFLOG);
#endif
#ifdef NETLINK_XFRM
- PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
+ PyModule_AddIntConstant(m, "NETLINK_XFRM", NETLINK_XFRM);
#endif
#ifdef NETLINK_ARPD
- PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
+ PyModule_AddIntConstant(m, "NETLINK_ARPD", NETLINK_ARPD);
#endif
#ifdef NETLINK_ROUTE6
- PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
+ PyModule_AddIntConstant(m, "NETLINK_ROUTE6", NETLINK_ROUTE6);
#endif
- PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
+ PyModule_AddIntConstant(m, "NETLINK_IP6_FW", NETLINK_IP6_FW);
#ifdef NETLINK_DNRTMSG
- PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
-#endif
+ PyModule_AddIntConstant(m, "NETLINK_DNRTMSG", NETLINK_DNRTMSG);
+#endif
#ifdef NETLINK_TAPBASE
- PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
+ PyModule_AddIntConstant(m, "NETLINK_TAPBASE", NETLINK_TAPBASE);
#endif
#endif /* AF_NETLINK */
#ifdef AF_ROUTE
- /* Alias to emulate 4.4BSD */
- PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
+ /* Alias to emulate 4.4BSD */
+ PyModule_AddIntConstant(m, "AF_ROUTE", AF_ROUTE);
#endif
#ifdef AF_ASH
- /* Ash */
- PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
+ /* Ash */
+ PyModule_AddIntConstant(m, "AF_ASH", AF_ASH);
#endif
#ifdef AF_ECONET
- /* Acorn Econet */
- PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
+ /* Acorn Econet */
+ PyModule_AddIntConstant(m, "AF_ECONET", AF_ECONET);
#endif
#ifdef AF_ATMSVC
- /* ATM SVCs */
- PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
+ /* ATM SVCs */
+ PyModule_AddIntConstant(m, "AF_ATMSVC", AF_ATMSVC);
#endif
#ifdef AF_SNA
- /* Linux SNA Project (nutters!) */
- PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
+ /* Linux SNA Project (nutters!) */
+ PyModule_AddIntConstant(m, "AF_SNA", AF_SNA);
#endif
#ifdef AF_IRDA
- /* IRDA sockets */
- PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
+ /* IRDA sockets */
+ PyModule_AddIntConstant(m, "AF_IRDA", AF_IRDA);
#endif
#ifdef AF_PPPOX
- /* PPPoX sockets */
- PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
+ /* PPPoX sockets */
+ PyModule_AddIntConstant(m, "AF_PPPOX", AF_PPPOX);
#endif
#ifdef AF_WANPIPE
- /* Wanpipe API Sockets */
- PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
+ /* Wanpipe API Sockets */
+ PyModule_AddIntConstant(m, "AF_WANPIPE", AF_WANPIPE);
#endif
#ifdef AF_LLC
- /* Linux LLC */
- PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
+ /* Linux LLC */
+ PyModule_AddIntConstant(m, "AF_LLC", AF_LLC);
#endif
#ifdef USE_BLUETOOTH
- PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
- PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
- PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
- PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
- PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
+ PyModule_AddIntConstant(m, "AF_BLUETOOTH", AF_BLUETOOTH);
+ PyModule_AddIntConstant(m, "BTPROTO_L2CAP", BTPROTO_L2CAP);
+ PyModule_AddIntConstant(m, "BTPROTO_HCI", BTPROTO_HCI);
+ PyModule_AddIntConstant(m, "SOL_HCI", SOL_HCI);
+ PyModule_AddIntConstant(m, "HCI_FILTER", HCI_FILTER);
#if !defined(__FreeBSD__)
- PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
- PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
- PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
+ PyModule_AddIntConstant(m, "HCI_TIME_STAMP", HCI_TIME_STAMP);
+ PyModule_AddIntConstant(m, "HCI_DATA_DIR", HCI_DATA_DIR);
+ PyModule_AddIntConstant(m, "BTPROTO_SCO", BTPROTO_SCO);
#endif
- PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
- PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
- PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
+ PyModule_AddIntConstant(m, "BTPROTO_RFCOMM", BTPROTO_RFCOMM);
+ PyModule_AddStringConstant(m, "BDADDR_ANY", "00:00:00:00:00:00");
+ PyModule_AddStringConstant(m, "BDADDR_LOCAL", "00:00:00:FF:FF:FF");
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
- PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
- PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
- PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
- PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
- PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
- PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
- PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
- PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
+ PyModule_AddIntConstant(m, "AF_PACKET", AF_PACKET);
+ PyModule_AddIntConstant(m, "PF_PACKET", PF_PACKET);
+ PyModule_AddIntConstant(m, "PACKET_HOST", PACKET_HOST);
+ PyModule_AddIntConstant(m, "PACKET_BROADCAST", PACKET_BROADCAST);
+ PyModule_AddIntConstant(m, "PACKET_MULTICAST", PACKET_MULTICAST);
+ PyModule_AddIntConstant(m, "PACKET_OTHERHOST", PACKET_OTHERHOST);
+ PyModule_AddIntConstant(m, "PACKET_OUTGOING", PACKET_OUTGOING);
+ PyModule_AddIntConstant(m, "PACKET_LOOPBACK", PACKET_LOOPBACK);
+ PyModule_AddIntConstant(m, "PACKET_FASTROUTE", PACKET_FASTROUTE);
#endif
#ifdef HAVE_LINUX_TIPC_H
- PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
-
- /* for addresses */
- PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
- PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
- PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
-
- PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
- PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
- PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
-
- /* for setsockopt() */
- PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
- PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
- PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
- TIPC_DEST_DROPPABLE);
- PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
-
- PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
- TIPC_LOW_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
- TIPC_MEDIUM_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
- TIPC_HIGH_IMPORTANCE);
- PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
- TIPC_CRITICAL_IMPORTANCE);
-
- /* for subscriptions */
- PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
- PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
+ PyModule_AddIntConstant(m, "AF_TIPC", AF_TIPC);
+
+ /* for addresses */
+ PyModule_AddIntConstant(m, "TIPC_ADDR_NAMESEQ", TIPC_ADDR_NAMESEQ);
+ PyModule_AddIntConstant(m, "TIPC_ADDR_NAME", TIPC_ADDR_NAME);
+ PyModule_AddIntConstant(m, "TIPC_ADDR_ID", TIPC_ADDR_ID);
+
+ PyModule_AddIntConstant(m, "TIPC_ZONE_SCOPE", TIPC_ZONE_SCOPE);
+ PyModule_AddIntConstant(m, "TIPC_CLUSTER_SCOPE", TIPC_CLUSTER_SCOPE);
+ PyModule_AddIntConstant(m, "TIPC_NODE_SCOPE", TIPC_NODE_SCOPE);
+
+ /* for setsockopt() */
+ PyModule_AddIntConstant(m, "SOL_TIPC", SOL_TIPC);
+ PyModule_AddIntConstant(m, "TIPC_IMPORTANCE", TIPC_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_SRC_DROPPABLE", TIPC_SRC_DROPPABLE);
+ PyModule_AddIntConstant(m, "TIPC_DEST_DROPPABLE",
+ TIPC_DEST_DROPPABLE);
+ PyModule_AddIntConstant(m, "TIPC_CONN_TIMEOUT", TIPC_CONN_TIMEOUT);
+
+ PyModule_AddIntConstant(m, "TIPC_LOW_IMPORTANCE",
+ TIPC_LOW_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_MEDIUM_IMPORTANCE",
+ TIPC_MEDIUM_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_HIGH_IMPORTANCE",
+ TIPC_HIGH_IMPORTANCE);
+ PyModule_AddIntConstant(m, "TIPC_CRITICAL_IMPORTANCE",
+ TIPC_CRITICAL_IMPORTANCE);
+
+ /* for subscriptions */
+ PyModule_AddIntConstant(m, "TIPC_SUB_PORTS", TIPC_SUB_PORTS);
+ PyModule_AddIntConstant(m, "TIPC_SUB_SERVICE", TIPC_SUB_SERVICE);
#ifdef TIPC_SUB_CANCEL
- /* doesn't seem to be available everywhere */
- PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
+ /* doesn't seem to be available everywhere */
+ PyModule_AddIntConstant(m, "TIPC_SUB_CANCEL", TIPC_SUB_CANCEL);
#endif
- PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
- PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
- PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
- PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
- PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
- PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
+ PyModule_AddIntConstant(m, "TIPC_WAIT_FOREVER", TIPC_WAIT_FOREVER);
+ PyModule_AddIntConstant(m, "TIPC_PUBLISHED", TIPC_PUBLISHED);
+ PyModule_AddIntConstant(m, "TIPC_WITHDRAWN", TIPC_WITHDRAWN);
+ PyModule_AddIntConstant(m, "TIPC_SUBSCR_TIMEOUT", TIPC_SUBSCR_TIMEOUT);
+ PyModule_AddIntConstant(m, "TIPC_CFG_SRV", TIPC_CFG_SRV);
+ PyModule_AddIntConstant(m, "TIPC_TOP_SRV", TIPC_TOP_SRV);
#endif
- /* Socket types */
- PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
- PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
+ /* Socket types */
+ PyModule_AddIntConstant(m, "SOCK_STREAM", SOCK_STREAM);
+ PyModule_AddIntConstant(m, "SOCK_DGRAM", SOCK_DGRAM);
#ifndef __BEOS__
/* We have incomplete socket support. */
- PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
- PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
+ PyModule_AddIntConstant(m, "SOCK_RAW", SOCK_RAW);
+ PyModule_AddIntConstant(m, "SOCK_SEQPACKET", SOCK_SEQPACKET);
#if defined(SOCK_RDM)
- PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
+ PyModule_AddIntConstant(m, "SOCK_RDM", SOCK_RDM);
#endif
#endif
-#ifdef SO_DEBUG
- PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
+#ifdef SO_DEBUG
+ PyModule_AddIntConstant(m, "SO_DEBUG", SO_DEBUG);
#endif
-#ifdef SO_ACCEPTCONN
- PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
+#ifdef SO_ACCEPTCONN
+ PyModule_AddIntConstant(m, "SO_ACCEPTCONN", SO_ACCEPTCONN);
#endif
-#ifdef SO_REUSEADDR
- PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
+#ifdef SO_REUSEADDR
+ PyModule_AddIntConstant(m, "SO_REUSEADDR", SO_REUSEADDR);
#endif
#ifdef SO_EXCLUSIVEADDRUSE
- PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
+ PyModule_AddIntConstant(m, "SO_EXCLUSIVEADDRUSE", SO_EXCLUSIVEADDRUSE);
#endif
-#ifdef SO_KEEPALIVE
- PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
+#ifdef SO_KEEPALIVE
+ PyModule_AddIntConstant(m, "SO_KEEPALIVE", SO_KEEPALIVE);
#endif
-#ifdef SO_DONTROUTE
- PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
+#ifdef SO_DONTROUTE
+ PyModule_AddIntConstant(m, "SO_DONTROUTE", SO_DONTROUTE);
#endif
-#ifdef SO_BROADCAST
- PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
+#ifdef SO_BROADCAST
+ PyModule_AddIntConstant(m, "SO_BROADCAST", SO_BROADCAST);
#endif
-#ifdef SO_USELOOPBACK
- PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
+#ifdef SO_USELOOPBACK
+ PyModule_AddIntConstant(m, "SO_USELOOPBACK", SO_USELOOPBACK);
#endif
-#ifdef SO_LINGER
- PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
+#ifdef SO_LINGER
+ PyModule_AddIntConstant(m, "SO_LINGER", SO_LINGER);
#endif
-#ifdef SO_OOBINLINE
- PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
+#ifdef SO_OOBINLINE
+ PyModule_AddIntConstant(m, "SO_OOBINLINE", SO_OOBINLINE);
#endif
-#ifdef SO_REUSEPORT
- PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
+#ifdef SO_REUSEPORT
+ PyModule_AddIntConstant(m, "SO_REUSEPORT", SO_REUSEPORT);
#endif
-#ifdef SO_SNDBUF
- PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
+#ifdef SO_SNDBUF
+ PyModule_AddIntConstant(m, "SO_SNDBUF", SO_SNDBUF);
#endif
-#ifdef SO_RCVBUF
- PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
+#ifdef SO_RCVBUF
+ PyModule_AddIntConstant(m, "SO_RCVBUF", SO_RCVBUF);
#endif
-#ifdef SO_SNDLOWAT
- PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
+#ifdef SO_SNDLOWAT
+ PyModule_AddIntConstant(m, "SO_SNDLOWAT", SO_SNDLOWAT);
#endif
-#ifdef SO_RCVLOWAT
- PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
+#ifdef SO_RCVLOWAT
+ PyModule_AddIntConstant(m, "SO_RCVLOWAT", SO_RCVLOWAT);
#endif
-#ifdef SO_SNDTIMEO
- PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
+#ifdef SO_SNDTIMEO
+ PyModule_AddIntConstant(m, "SO_SNDTIMEO", SO_SNDTIMEO);
#endif
-#ifdef SO_RCVTIMEO
- PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
+#ifdef SO_RCVTIMEO
+ PyModule_AddIntConstant(m, "SO_RCVTIMEO", SO_RCVTIMEO);
#endif
-#ifdef SO_ERROR
- PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
+#ifdef SO_ERROR
+ PyModule_AddIntConstant(m, "SO_ERROR", SO_ERROR);
#endif
-#ifdef SO_TYPE
- PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
+#ifdef SO_TYPE
+ PyModule_AddIntConstant(m, "SO_TYPE", SO_TYPE);
#endif
#ifdef SO_SETFIB
PyModule_AddIntConstant(m, "SO_SETFIB", SO_SETFIB);
#endif
- /* Maximum number of connections for "listen" */
-#ifdef SOMAXCONN
- PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
+ /* Maximum number of connections for "listen" */
+#ifdef SOMAXCONN
+ PyModule_AddIntConstant(m, "SOMAXCONN", SOMAXCONN);
#else
- PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
+ PyModule_AddIntConstant(m, "SOMAXCONN", 5); /* Common value */
#endif
- /* Flags for send, recv */
-#ifdef MSG_OOB
- PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
+ /* Flags for send, recv */
+#ifdef MSG_OOB
+ PyModule_AddIntConstant(m, "MSG_OOB", MSG_OOB);
#endif
-#ifdef MSG_PEEK
- PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
+#ifdef MSG_PEEK
+ PyModule_AddIntConstant(m, "MSG_PEEK", MSG_PEEK);
#endif
-#ifdef MSG_DONTROUTE
- PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
+#ifdef MSG_DONTROUTE
+ PyModule_AddIntConstant(m, "MSG_DONTROUTE", MSG_DONTROUTE);
#endif
-#ifdef MSG_DONTWAIT
- PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
+#ifdef MSG_DONTWAIT
+ PyModule_AddIntConstant(m, "MSG_DONTWAIT", MSG_DONTWAIT);
#endif
-#ifdef MSG_EOR
- PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
+#ifdef MSG_EOR
+ PyModule_AddIntConstant(m, "MSG_EOR", MSG_EOR);
#endif
-#ifdef MSG_TRUNC
- PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
+#ifdef MSG_TRUNC
+ PyModule_AddIntConstant(m, "MSG_TRUNC", MSG_TRUNC);
#endif
-#ifdef MSG_CTRUNC
- PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
+#ifdef MSG_CTRUNC
+ PyModule_AddIntConstant(m, "MSG_CTRUNC", MSG_CTRUNC);
#endif
-#ifdef MSG_WAITALL
- PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
+#ifdef MSG_WAITALL
+ PyModule_AddIntConstant(m, "MSG_WAITALL", MSG_WAITALL);
#endif
-#ifdef MSG_BTAG
- PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
+#ifdef MSG_BTAG
+ PyModule_AddIntConstant(m, "MSG_BTAG", MSG_BTAG);
#endif
-#ifdef MSG_ETAG
- PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
+#ifdef MSG_ETAG
+ PyModule_AddIntConstant(m, "MSG_ETAG", MSG_ETAG);
#endif
- /* Protocol level and numbers, usable for [gs]etsockopt */
-#ifdef SOL_SOCKET
- PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
+ /* Protocol level and numbers, usable for [gs]etsockopt */
+#ifdef SOL_SOCKET
+ PyModule_AddIntConstant(m, "SOL_SOCKET", SOL_SOCKET);
#endif
-#ifdef SOL_IP
- PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
+#ifdef SOL_IP
+ PyModule_AddIntConstant(m, "SOL_IP", SOL_IP);
#else
- PyModule_AddIntConstant(m, "SOL_IP", 0);
+ PyModule_AddIntConstant(m, "SOL_IP", 0);
#endif
-#ifdef SOL_IPX
- PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
+#ifdef SOL_IPX
+ PyModule_AddIntConstant(m, "SOL_IPX", SOL_IPX);
#endif
-#ifdef SOL_AX25
- PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
+#ifdef SOL_AX25
+ PyModule_AddIntConstant(m, "SOL_AX25", SOL_AX25);
#endif
-#ifdef SOL_ATALK
- PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
+#ifdef SOL_ATALK
+ PyModule_AddIntConstant(m, "SOL_ATALK", SOL_ATALK);
#endif
-#ifdef SOL_NETROM
- PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
+#ifdef SOL_NETROM
+ PyModule_AddIntConstant(m, "SOL_NETROM", SOL_NETROM);
#endif
-#ifdef SOL_ROSE
- PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
+#ifdef SOL_ROSE
+ PyModule_AddIntConstant(m, "SOL_ROSE", SOL_ROSE);
#endif
-#ifdef SOL_TCP
- PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
+#ifdef SOL_TCP
+ PyModule_AddIntConstant(m, "SOL_TCP", SOL_TCP);
#else
- PyModule_AddIntConstant(m, "SOL_TCP", 6);
+ PyModule_AddIntConstant(m, "SOL_TCP", 6);
#endif
-#ifdef SOL_UDP
- PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
+#ifdef SOL_UDP
+ PyModule_AddIntConstant(m, "SOL_UDP", SOL_UDP);
#else
- PyModule_AddIntConstant(m, "SOL_UDP", 17);
+ PyModule_AddIntConstant(m, "SOL_UDP", 17);
#endif
-#ifdef IPPROTO_IP
- PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
+#ifdef IPPROTO_IP
+ PyModule_AddIntConstant(m, "IPPROTO_IP", IPPROTO_IP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
+ PyModule_AddIntConstant(m, "IPPROTO_IP", 0);
#endif
-#ifdef IPPROTO_HOPOPTS
- PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
+#ifdef IPPROTO_HOPOPTS
+ PyModule_AddIntConstant(m, "IPPROTO_HOPOPTS", IPPROTO_HOPOPTS);
#endif
-#ifdef IPPROTO_ICMP
- PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
+#ifdef IPPROTO_ICMP
+ PyModule_AddIntConstant(m, "IPPROTO_ICMP", IPPROTO_ICMP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
+ PyModule_AddIntConstant(m, "IPPROTO_ICMP", 1);
#endif
-#ifdef IPPROTO_IGMP
- PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
+#ifdef IPPROTO_IGMP
+ PyModule_AddIntConstant(m, "IPPROTO_IGMP", IPPROTO_IGMP);
#endif
-#ifdef IPPROTO_GGP
- PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
+#ifdef IPPROTO_GGP
+ PyModule_AddIntConstant(m, "IPPROTO_GGP", IPPROTO_GGP);
#endif
-#ifdef IPPROTO_IPV4
- PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
+#ifdef IPPROTO_IPV4
+ PyModule_AddIntConstant(m, "IPPROTO_IPV4", IPPROTO_IPV4);
#endif
-#ifdef IPPROTO_IPV6
- PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
+#ifdef IPPROTO_IPV6
+ PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
#endif
-#ifdef IPPROTO_IPIP
- PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
+#ifdef IPPROTO_IPIP
+ PyModule_AddIntConstant(m, "IPPROTO_IPIP", IPPROTO_IPIP);
#endif
-#ifdef IPPROTO_TCP
- PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
+#ifdef IPPROTO_TCP
+ PyModule_AddIntConstant(m, "IPPROTO_TCP", IPPROTO_TCP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
+ PyModule_AddIntConstant(m, "IPPROTO_TCP", 6);
#endif
-#ifdef IPPROTO_EGP
- PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
+#ifdef IPPROTO_EGP
+ PyModule_AddIntConstant(m, "IPPROTO_EGP", IPPROTO_EGP);
#endif
-#ifdef IPPROTO_PUP
- PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
+#ifdef IPPROTO_PUP
+ PyModule_AddIntConstant(m, "IPPROTO_PUP", IPPROTO_PUP);
#endif
-#ifdef IPPROTO_UDP
- PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
+#ifdef IPPROTO_UDP
+ PyModule_AddIntConstant(m, "IPPROTO_UDP", IPPROTO_UDP);
#else
- PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
+ PyModule_AddIntConstant(m, "IPPROTO_UDP", 17);
#endif
-#ifdef IPPROTO_IDP
- PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
+#ifdef IPPROTO_IDP
+ PyModule_AddIntConstant(m, "IPPROTO_IDP", IPPROTO_IDP);
#endif
-#ifdef IPPROTO_HELLO
- PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
+#ifdef IPPROTO_HELLO
+ PyModule_AddIntConstant(m, "IPPROTO_HELLO", IPPROTO_HELLO);
#endif
-#ifdef IPPROTO_ND
- PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
+#ifdef IPPROTO_ND
+ PyModule_AddIntConstant(m, "IPPROTO_ND", IPPROTO_ND);
#endif
-#ifdef IPPROTO_TP
- PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
+#ifdef IPPROTO_TP
+ PyModule_AddIntConstant(m, "IPPROTO_TP", IPPROTO_TP);
#endif
-#ifdef IPPROTO_IPV6
- PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
+#ifdef IPPROTO_IPV6
+ PyModule_AddIntConstant(m, "IPPROTO_IPV6", IPPROTO_IPV6);
#endif
-#ifdef IPPROTO_ROUTING
- PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
+#ifdef IPPROTO_ROUTING
+ PyModule_AddIntConstant(m, "IPPROTO_ROUTING", IPPROTO_ROUTING);
#endif
-#ifdef IPPROTO_FRAGMENT
- PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
+#ifdef IPPROTO_FRAGMENT
+ PyModule_AddIntConstant(m, "IPPROTO_FRAGMENT", IPPROTO_FRAGMENT);
#endif
-#ifdef IPPROTO_RSVP
- PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
+#ifdef IPPROTO_RSVP
+ PyModule_AddIntConstant(m, "IPPROTO_RSVP", IPPROTO_RSVP);
#endif
-#ifdef IPPROTO_GRE
- PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
+#ifdef IPPROTO_GRE
+ PyModule_AddIntConstant(m, "IPPROTO_GRE", IPPROTO_GRE);
#endif
-#ifdef IPPROTO_ESP
- PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
+#ifdef IPPROTO_ESP
+ PyModule_AddIntConstant(m, "IPPROTO_ESP", IPPROTO_ESP);
#endif
-#ifdef IPPROTO_AH
- PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
+#ifdef IPPROTO_AH
+ PyModule_AddIntConstant(m, "IPPROTO_AH", IPPROTO_AH);
#endif
-#ifdef IPPROTO_MOBILE
- PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
+#ifdef IPPROTO_MOBILE
+ PyModule_AddIntConstant(m, "IPPROTO_MOBILE", IPPROTO_MOBILE);
#endif
-#ifdef IPPROTO_ICMPV6
- PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
+#ifdef IPPROTO_ICMPV6
+ PyModule_AddIntConstant(m, "IPPROTO_ICMPV6", IPPROTO_ICMPV6);
#endif
-#ifdef IPPROTO_NONE
- PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
+#ifdef IPPROTO_NONE
+ PyModule_AddIntConstant(m, "IPPROTO_NONE", IPPROTO_NONE);
#endif
-#ifdef IPPROTO_DSTOPTS
- PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
+#ifdef IPPROTO_DSTOPTS
+ PyModule_AddIntConstant(m, "IPPROTO_DSTOPTS", IPPROTO_DSTOPTS);
#endif
-#ifdef IPPROTO_XTP
- PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
+#ifdef IPPROTO_XTP
+ PyModule_AddIntConstant(m, "IPPROTO_XTP", IPPROTO_XTP);
#endif
-#ifdef IPPROTO_EON
- PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
+#ifdef IPPROTO_EON
+ PyModule_AddIntConstant(m, "IPPROTO_EON", IPPROTO_EON);
#endif
-#ifdef IPPROTO_PIM
- PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
+#ifdef IPPROTO_PIM
+ PyModule_AddIntConstant(m, "IPPROTO_PIM", IPPROTO_PIM);
#endif
-#ifdef IPPROTO_IPCOMP
- PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
+#ifdef IPPROTO_IPCOMP
+ PyModule_AddIntConstant(m, "IPPROTO_IPCOMP", IPPROTO_IPCOMP);
#endif
-#ifdef IPPROTO_VRRP
- PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
+#ifdef IPPROTO_VRRP
+ PyModule_AddIntConstant(m, "IPPROTO_VRRP", IPPROTO_VRRP);
#endif
-#ifdef IPPROTO_BIP
- PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
+#ifdef IPPROTO_BIP
+ PyModule_AddIntConstant(m, "IPPROTO_BIP", IPPROTO_BIP);
#endif
/**/
-#ifdef IPPROTO_RAW
- PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
+#ifdef IPPROTO_RAW
+ PyModule_AddIntConstant(m, "IPPROTO_RAW", IPPROTO_RAW);
#else
- PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
+ PyModule_AddIntConstant(m, "IPPROTO_RAW", 255);
#endif
-#ifdef IPPROTO_MAX
- PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
+#ifdef IPPROTO_MAX
+ PyModule_AddIntConstant(m, "IPPROTO_MAX", IPPROTO_MAX);
#endif
- /* Some port configuration */
-#ifdef IPPORT_RESERVED
- PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
+ /* Some port configuration */
+#ifdef IPPORT_RESERVED
+ PyModule_AddIntConstant(m, "IPPORT_RESERVED", IPPORT_RESERVED);
#else
- PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
+ PyModule_AddIntConstant(m, "IPPORT_RESERVED", 1024);
#endif
-#ifdef IPPORT_USERRESERVED
- PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
+#ifdef IPPORT_USERRESERVED
+ PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", IPPORT_USERRESERVED);
#else
- PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
+ PyModule_AddIntConstant(m, "IPPORT_USERRESERVED", 5000);
#endif
- /* Some reserved IP v.4 addresses */
-#ifdef INADDR_ANY
- PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
+ /* Some reserved IP v.4 addresses */
+#ifdef INADDR_ANY
+ PyModule_AddIntConstant(m, "INADDR_ANY", INADDR_ANY);
#else
- PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
+ PyModule_AddIntConstant(m, "INADDR_ANY", 0x00000000);
#endif
-#ifdef INADDR_BROADCAST
- PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
+#ifdef INADDR_BROADCAST
+ PyModule_AddIntConstant(m, "INADDR_BROADCAST", INADDR_BROADCAST);
#else
- PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
+ PyModule_AddIntConstant(m, "INADDR_BROADCAST", 0xffffffff);
#endif
-#ifdef INADDR_LOOPBACK
- PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
+#ifdef INADDR_LOOPBACK
+ PyModule_AddIntConstant(m, "INADDR_LOOPBACK", INADDR_LOOPBACK);
#else
- PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
+ PyModule_AddIntConstant(m, "INADDR_LOOPBACK", 0x7F000001);
#endif
-#ifdef INADDR_UNSPEC_GROUP
- PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
+#ifdef INADDR_UNSPEC_GROUP
+ PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", INADDR_UNSPEC_GROUP);
#else
- PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
+ PyModule_AddIntConstant(m, "INADDR_UNSPEC_GROUP", 0xe0000000);
#endif
-#ifdef INADDR_ALLHOSTS_GROUP
- PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
- INADDR_ALLHOSTS_GROUP);
+#ifdef INADDR_ALLHOSTS_GROUP
+ PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP",
+ INADDR_ALLHOSTS_GROUP);
#else
- PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
+ PyModule_AddIntConstant(m, "INADDR_ALLHOSTS_GROUP", 0xe0000001);
#endif
-#ifdef INADDR_MAX_LOCAL_GROUP
- PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
- INADDR_MAX_LOCAL_GROUP);
+#ifdef INADDR_MAX_LOCAL_GROUP
+ PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP",
+ INADDR_MAX_LOCAL_GROUP);
#else
- PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
+ PyModule_AddIntConstant(m, "INADDR_MAX_LOCAL_GROUP", 0xe00000ff);
#endif
-#ifdef INADDR_NONE
- PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
+#ifdef INADDR_NONE
+ PyModule_AddIntConstant(m, "INADDR_NONE", INADDR_NONE);
#else
- PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
+ PyModule_AddIntConstant(m, "INADDR_NONE", 0xffffffff);
#endif
- /* IPv4 [gs]etsockopt options */
-#ifdef IP_OPTIONS
- PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
+ /* IPv4 [gs]etsockopt options */
+#ifdef IP_OPTIONS
+ PyModule_AddIntConstant(m, "IP_OPTIONS", IP_OPTIONS);
#endif
-#ifdef IP_HDRINCL
- PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
+#ifdef IP_HDRINCL
+ PyModule_AddIntConstant(m, "IP_HDRINCL", IP_HDRINCL);
#endif
-#ifdef IP_TOS
- PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
+#ifdef IP_TOS
+ PyModule_AddIntConstant(m, "IP_TOS", IP_TOS);
#endif
-#ifdef IP_TTL
- PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
+#ifdef IP_TTL
+ PyModule_AddIntConstant(m, "IP_TTL", IP_TTL);
#endif
-#ifdef IP_RECVOPTS
- PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
+#ifdef IP_RECVOPTS
+ PyModule_AddIntConstant(m, "IP_RECVOPTS", IP_RECVOPTS);
#endif
-#ifdef IP_RECVRETOPTS
- PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
+#ifdef IP_RECVRETOPTS
+ PyModule_AddIntConstant(m, "IP_RECVRETOPTS", IP_RECVRETOPTS);
#endif
-#ifdef IP_RECVDSTADDR
- PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
+#ifdef IP_RECVDSTADDR
+ PyModule_AddIntConstant(m, "IP_RECVDSTADDR", IP_RECVDSTADDR);
#endif
-#ifdef IP_RETOPTS
- PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
+#ifdef IP_RETOPTS
+ PyModule_AddIntConstant(m, "IP_RETOPTS", IP_RETOPTS);
#endif
-#ifdef IP_MULTICAST_IF
- PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
+#ifdef IP_MULTICAST_IF
+ PyModule_AddIntConstant(m, "IP_MULTICAST_IF", IP_MULTICAST_IF);
#endif
-#ifdef IP_MULTICAST_TTL
- PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
+#ifdef IP_MULTICAST_TTL
+ PyModule_AddIntConstant(m, "IP_MULTICAST_TTL", IP_MULTICAST_TTL);
#endif
-#ifdef IP_MULTICAST_LOOP
- PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
+#ifdef IP_MULTICAST_LOOP
+ PyModule_AddIntConstant(m, "IP_MULTICAST_LOOP", IP_MULTICAST_LOOP);
#endif
-#ifdef IP_ADD_MEMBERSHIP
- PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
+#ifdef IP_ADD_MEMBERSHIP
+ PyModule_AddIntConstant(m, "IP_ADD_MEMBERSHIP", IP_ADD_MEMBERSHIP);
#endif
-#ifdef IP_DROP_MEMBERSHIP
- PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
+#ifdef IP_DROP_MEMBERSHIP
+ PyModule_AddIntConstant(m, "IP_DROP_MEMBERSHIP", IP_DROP_MEMBERSHIP);
#endif
-#ifdef IP_DEFAULT_MULTICAST_TTL
- PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
- IP_DEFAULT_MULTICAST_TTL);
+#ifdef IP_DEFAULT_MULTICAST_TTL
+ PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_TTL",
+ IP_DEFAULT_MULTICAST_TTL);
#endif
-#ifdef IP_DEFAULT_MULTICAST_LOOP
- PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
- IP_DEFAULT_MULTICAST_LOOP);
+#ifdef IP_DEFAULT_MULTICAST_LOOP
+ PyModule_AddIntConstant(m, "IP_DEFAULT_MULTICAST_LOOP",
+ IP_DEFAULT_MULTICAST_LOOP);
#endif
-#ifdef IP_MAX_MEMBERSHIPS
- PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
+#ifdef IP_MAX_MEMBERSHIPS
+ PyModule_AddIntConstant(m, "IP_MAX_MEMBERSHIPS", IP_MAX_MEMBERSHIPS);
#endif
- /* IPv6 [gs]etsockopt options, defined in RFC2553 */
-#ifdef IPV6_JOIN_GROUP
- PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
+ /* IPv6 [gs]etsockopt options, defined in RFC2553 */
+#ifdef IPV6_JOIN_GROUP
+ PyModule_AddIntConstant(m, "IPV6_JOIN_GROUP", IPV6_JOIN_GROUP);
#endif
-#ifdef IPV6_LEAVE_GROUP
- PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
+#ifdef IPV6_LEAVE_GROUP
+ PyModule_AddIntConstant(m, "IPV6_LEAVE_GROUP", IPV6_LEAVE_GROUP);
#endif
-#ifdef IPV6_MULTICAST_HOPS
- PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
+#ifdef IPV6_MULTICAST_HOPS
+ PyModule_AddIntConstant(m, "IPV6_MULTICAST_HOPS", IPV6_MULTICAST_HOPS);
#endif
-#ifdef IPV6_MULTICAST_IF
- PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
+#ifdef IPV6_MULTICAST_IF
+ PyModule_AddIntConstant(m, "IPV6_MULTICAST_IF", IPV6_MULTICAST_IF);
#endif
-#ifdef IPV6_MULTICAST_LOOP
- PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
+#ifdef IPV6_MULTICAST_LOOP
+ PyModule_AddIntConstant(m, "IPV6_MULTICAST_LOOP", IPV6_MULTICAST_LOOP);
#endif
-#ifdef IPV6_UNICAST_HOPS
- PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
+#ifdef IPV6_UNICAST_HOPS
+ PyModule_AddIntConstant(m, "IPV6_UNICAST_HOPS", IPV6_UNICAST_HOPS);
#endif
- /* Additional IPV6 socket options, defined in RFC 3493 */
+ /* Additional IPV6 socket options, defined in RFC 3493 */
#ifdef IPV6_V6ONLY
- PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
+ PyModule_AddIntConstant(m, "IPV6_V6ONLY", IPV6_V6ONLY);
#endif
- /* Advanced IPV6 socket options, from RFC 3542 */
+ /* Advanced IPV6 socket options, from RFC 3542 */
#ifdef IPV6_CHECKSUM
- PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
+ PyModule_AddIntConstant(m, "IPV6_CHECKSUM", IPV6_CHECKSUM);
#endif
#ifdef IPV6_DONTFRAG
- PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
+ PyModule_AddIntConstant(m, "IPV6_DONTFRAG", IPV6_DONTFRAG);
#endif
#ifdef IPV6_DSTOPTS
- PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
+ PyModule_AddIntConstant(m, "IPV6_DSTOPTS", IPV6_DSTOPTS);
#endif
#ifdef IPV6_HOPLIMIT
- PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
+ PyModule_AddIntConstant(m, "IPV6_HOPLIMIT", IPV6_HOPLIMIT);
#endif
#ifdef IPV6_HOPOPTS
- PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
+ PyModule_AddIntConstant(m, "IPV6_HOPOPTS", IPV6_HOPOPTS);
#endif
#ifdef IPV6_NEXTHOP
- PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
+ PyModule_AddIntConstant(m, "IPV6_NEXTHOP", IPV6_NEXTHOP);
#endif
#ifdef IPV6_PATHMTU
- PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
+ PyModule_AddIntConstant(m, "IPV6_PATHMTU", IPV6_PATHMTU);
#endif
#ifdef IPV6_PKTINFO
- PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
+ PyModule_AddIntConstant(m, "IPV6_PKTINFO", IPV6_PKTINFO);
#endif
#ifdef IPV6_RECVDSTOPTS
- PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
+ PyModule_AddIntConstant(m, "IPV6_RECVDSTOPTS", IPV6_RECVDSTOPTS);
#endif
#ifdef IPV6_RECVHOPLIMIT
- PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
+ PyModule_AddIntConstant(m, "IPV6_RECVHOPLIMIT", IPV6_RECVHOPLIMIT);
#endif
#ifdef IPV6_RECVHOPOPTS
- PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
+ PyModule_AddIntConstant(m, "IPV6_RECVHOPOPTS", IPV6_RECVHOPOPTS);
#endif
#ifdef IPV6_RECVPKTINFO
- PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
+ PyModule_AddIntConstant(m, "IPV6_RECVPKTINFO", IPV6_RECVPKTINFO);
#endif
#ifdef IPV6_RECVRTHDR
- PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
+ PyModule_AddIntConstant(m, "IPV6_RECVRTHDR", IPV6_RECVRTHDR);
#endif
#ifdef IPV6_RECVTCLASS
- PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
+ PyModule_AddIntConstant(m, "IPV6_RECVTCLASS", IPV6_RECVTCLASS);
#endif
#ifdef IPV6_RTHDR
- PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
+ PyModule_AddIntConstant(m, "IPV6_RTHDR", IPV6_RTHDR);
#endif
#ifdef IPV6_RTHDRDSTOPTS
- PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
+ PyModule_AddIntConstant(m, "IPV6_RTHDRDSTOPTS", IPV6_RTHDRDSTOPTS);
#endif
#ifdef IPV6_RTHDR_TYPE_0
- PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
+ PyModule_AddIntConstant(m, "IPV6_RTHDR_TYPE_0", IPV6_RTHDR_TYPE_0);
#endif
#ifdef IPV6_RECVPATHMTU
- PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
+ PyModule_AddIntConstant(m, "IPV6_RECVPATHMTU", IPV6_RECVPATHMTU);
#endif
#ifdef IPV6_TCLASS
- PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
+ PyModule_AddIntConstant(m, "IPV6_TCLASS", IPV6_TCLASS);
#endif
#ifdef IPV6_USE_MIN_MTU
- PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
+ PyModule_AddIntConstant(m, "IPV6_USE_MIN_MTU", IPV6_USE_MIN_MTU);
#endif
- /* TCP options */
-#ifdef TCP_NODELAY
- PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
+ /* TCP options */
+#ifdef TCP_NODELAY
+ PyModule_AddIntConstant(m, "TCP_NODELAY", TCP_NODELAY);
#endif
-#ifdef TCP_MAXSEG
- PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
+#ifdef TCP_MAXSEG
+ PyModule_AddIntConstant(m, "TCP_MAXSEG", TCP_MAXSEG);
#endif
-#ifdef TCP_CORK
- PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
+#ifdef TCP_CORK
+ PyModule_AddIntConstant(m, "TCP_CORK", TCP_CORK);
#endif
-#ifdef TCP_KEEPIDLE
- PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
+#ifdef TCP_KEEPIDLE
+ PyModule_AddIntConstant(m, "TCP_KEEPIDLE", TCP_KEEPIDLE);
#endif
-#ifdef TCP_KEEPINTVL
- PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
+#ifdef TCP_KEEPINTVL
+ PyModule_AddIntConstant(m, "TCP_KEEPINTVL", TCP_KEEPINTVL);
#endif
-#ifdef TCP_KEEPCNT
- PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
+#ifdef TCP_KEEPCNT
+ PyModule_AddIntConstant(m, "TCP_KEEPCNT", TCP_KEEPCNT);
#endif
-#ifdef TCP_SYNCNT
- PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
+#ifdef TCP_SYNCNT
+ PyModule_AddIntConstant(m, "TCP_SYNCNT", TCP_SYNCNT);
#endif
-#ifdef TCP_LINGER2
- PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
+#ifdef TCP_LINGER2
+ PyModule_AddIntConstant(m, "TCP_LINGER2", TCP_LINGER2);
#endif
-#ifdef TCP_DEFER_ACCEPT
- PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
+#ifdef TCP_DEFER_ACCEPT
+ PyModule_AddIntConstant(m, "TCP_DEFER_ACCEPT", TCP_DEFER_ACCEPT);
#endif
-#ifdef TCP_WINDOW_CLAMP
- PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
+#ifdef TCP_WINDOW_CLAMP
+ PyModule_AddIntConstant(m, "TCP_WINDOW_CLAMP", TCP_WINDOW_CLAMP);
#endif
-#ifdef TCP_INFO
- PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
+#ifdef TCP_INFO
+ PyModule_AddIntConstant(m, "TCP_INFO", TCP_INFO);
#endif
-#ifdef TCP_QUICKACK
- PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
+#ifdef TCP_QUICKACK
+ PyModule_AddIntConstant(m, "TCP_QUICKACK", TCP_QUICKACK);
#endif
- /* IPX options */
-#ifdef IPX_TYPE
- PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
+ /* IPX options */
+#ifdef IPX_TYPE
+ PyModule_AddIntConstant(m, "IPX_TYPE", IPX_TYPE);
#endif
- /* get{addr,name}info parameters */
+ /* get{addr,name}info parameters */
#ifdef EAI_ADDRFAMILY
- PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
+ PyModule_AddIntConstant(m, "EAI_ADDRFAMILY", EAI_ADDRFAMILY);
#endif
#ifdef EAI_AGAIN
- PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
+ PyModule_AddIntConstant(m, "EAI_AGAIN", EAI_AGAIN);
#endif
#ifdef EAI_BADFLAGS
- PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
+ PyModule_AddIntConstant(m, "EAI_BADFLAGS", EAI_BADFLAGS);
#endif
#ifdef EAI_FAIL
- PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
+ PyModule_AddIntConstant(m, "EAI_FAIL", EAI_FAIL);
#endif
#ifdef EAI_FAMILY
- PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
+ PyModule_AddIntConstant(m, "EAI_FAMILY", EAI_FAMILY);
#endif
#ifdef EAI_MEMORY
- PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
+ PyModule_AddIntConstant(m, "EAI_MEMORY", EAI_MEMORY);
#endif
#ifdef EAI_NODATA
- PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
+ PyModule_AddIntConstant(m, "EAI_NODATA", EAI_NODATA);
#endif
#ifdef EAI_NONAME
- PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
+ PyModule_AddIntConstant(m, "EAI_NONAME", EAI_NONAME);
#endif
#ifdef EAI_OVERFLOW
- PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
+ PyModule_AddIntConstant(m, "EAI_OVERFLOW", EAI_OVERFLOW);
#endif
#ifdef EAI_SERVICE
- PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
+ PyModule_AddIntConstant(m, "EAI_SERVICE", EAI_SERVICE);
#endif
#ifdef EAI_SOCKTYPE
- PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
+ PyModule_AddIntConstant(m, "EAI_SOCKTYPE", EAI_SOCKTYPE);
#endif
#ifdef EAI_SYSTEM
- PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
+ PyModule_AddIntConstant(m, "EAI_SYSTEM", EAI_SYSTEM);
#endif
#ifdef EAI_BADHINTS
- PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
+ PyModule_AddIntConstant(m, "EAI_BADHINTS", EAI_BADHINTS);
#endif
#ifdef EAI_PROTOCOL
- PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
+ PyModule_AddIntConstant(m, "EAI_PROTOCOL", EAI_PROTOCOL);
#endif
#ifdef EAI_MAX
- PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
+ PyModule_AddIntConstant(m, "EAI_MAX", EAI_MAX);
#endif
#ifdef AI_PASSIVE
- PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
+ PyModule_AddIntConstant(m, "AI_PASSIVE", AI_PASSIVE);
#endif
#ifdef AI_CANONNAME
- PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
+ PyModule_AddIntConstant(m, "AI_CANONNAME", AI_CANONNAME);
#endif
#ifdef AI_NUMERICHOST
- PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
+ PyModule_AddIntConstant(m, "AI_NUMERICHOST", AI_NUMERICHOST);
#endif
#ifdef AI_NUMERICSERV
- PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
+ PyModule_AddIntConstant(m, "AI_NUMERICSERV", AI_NUMERICSERV);
#endif
#ifdef AI_MASK
- PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
+ PyModule_AddIntConstant(m, "AI_MASK", AI_MASK);
#endif
#ifdef AI_ALL
- PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
+ PyModule_AddIntConstant(m, "AI_ALL", AI_ALL);
#endif
#ifdef AI_V4MAPPED_CFG
- PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
+ PyModule_AddIntConstant(m, "AI_V4MAPPED_CFG", AI_V4MAPPED_CFG);
#endif
#ifdef AI_ADDRCONFIG
- PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
+ PyModule_AddIntConstant(m, "AI_ADDRCONFIG", AI_ADDRCONFIG);
#endif
#ifdef AI_V4MAPPED
- PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
+ PyModule_AddIntConstant(m, "AI_V4MAPPED", AI_V4MAPPED);
#endif
#ifdef AI_DEFAULT
- PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
+ PyModule_AddIntConstant(m, "AI_DEFAULT", AI_DEFAULT);
#endif
#ifdef NI_MAXHOST
- PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
+ PyModule_AddIntConstant(m, "NI_MAXHOST", NI_MAXHOST);
#endif
#ifdef NI_MAXSERV
- PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
+ PyModule_AddIntConstant(m, "NI_MAXSERV", NI_MAXSERV);
#endif
#ifdef NI_NOFQDN
- PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
+ PyModule_AddIntConstant(m, "NI_NOFQDN", NI_NOFQDN);
#endif
#ifdef NI_NUMERICHOST
- PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
+ PyModule_AddIntConstant(m, "NI_NUMERICHOST", NI_NUMERICHOST);
#endif
#ifdef NI_NAMEREQD
- PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
+ PyModule_AddIntConstant(m, "NI_NAMEREQD", NI_NAMEREQD);
#endif
#ifdef NI_NUMERICSERV
- PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
+ PyModule_AddIntConstant(m, "NI_NUMERICSERV", NI_NUMERICSERV);
#endif
#ifdef NI_DGRAM
- PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
+ PyModule_AddIntConstant(m, "NI_DGRAM", NI_DGRAM);
#endif
- /* shutdown() parameters */
+ /* shutdown() parameters */
#ifdef SHUT_RD
- PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
+ PyModule_AddIntConstant(m, "SHUT_RD", SHUT_RD);
#elif defined(SD_RECEIVE)
- PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
+ PyModule_AddIntConstant(m, "SHUT_RD", SD_RECEIVE);
#else
- PyModule_AddIntConstant(m, "SHUT_RD", 0);
+ PyModule_AddIntConstant(m, "SHUT_RD", 0);
#endif
#ifdef SHUT_WR
- PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
+ PyModule_AddIntConstant(m, "SHUT_WR", SHUT_WR);
#elif defined(SD_SEND)
- PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
+ PyModule_AddIntConstant(m, "SHUT_WR", SD_SEND);
#else
- PyModule_AddIntConstant(m, "SHUT_WR", 1);
+ PyModule_AddIntConstant(m, "SHUT_WR", 1);
#endif
#ifdef SHUT_RDWR
- PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
+ PyModule_AddIntConstant(m, "SHUT_RDWR", SHUT_RDWR);
#elif defined(SD_BOTH)
- PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
+ PyModule_AddIntConstant(m, "SHUT_RDWR", SD_BOTH);
#else
- PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
+ PyModule_AddIntConstant(m, "SHUT_RDWR", 2);
#endif
#ifdef SIO_RCVALL
- {
- DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
- const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
- int i;
- for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
- PyObject *tmp;
- tmp = PyLong_FromUnsignedLong(codes[i]);
- if (tmp == NULL)
- return;
- PyModule_AddObject(m, names[i], tmp);
- }
- }
- PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
- PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
- PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
+ {
+ DWORD codes[] = {SIO_RCVALL, SIO_KEEPALIVE_VALS};
+ const char *names[] = {"SIO_RCVALL", "SIO_KEEPALIVE_VALS"};
+ int i;
+ for(i = 0; i<sizeof(codes)/sizeof(*codes); ++i) {
+ PyObject *tmp;
+ tmp = PyLong_FromUnsignedLong(codes[i]);
+ if (tmp == NULL)
+ return;
+ PyModule_AddObject(m, names[i], tmp);
+ }
+ }
+ PyModule_AddIntConstant(m, "RCVALL_OFF", RCVALL_OFF);
+ PyModule_AddIntConstant(m, "RCVALL_ON", RCVALL_ON);
+ PyModule_AddIntConstant(m, "RCVALL_SOCKETLEVELONLY", RCVALL_SOCKETLEVELONLY);
#ifdef RCVALL_IPLEVEL
- PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
+ PyModule_AddIntConstant(m, "RCVALL_IPLEVEL", RCVALL_IPLEVEL);
#endif
#ifdef RCVALL_MAX
- PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
+ PyModule_AddIntConstant(m, "RCVALL_MAX", RCVALL_MAX);
#endif
#endif /* _MSTCPIP_ */
- /* Initialize gethostbyname lock */
+ /* Initialize gethostbyname lock */
#if defined(USE_GETHOSTBYNAME_LOCK) || defined(USE_GETADDRINFO_LOCK)
- netdb_lock = PyThread_allocate_lock();
+ netdb_lock = PyThread_allocate_lock();
#endif
}
@@ -5366,34 +5366,34 @@ init_socket(void)
int
inet_pton(int af, const char *src, void *dst)
{
- if (af == AF_INET) {
+ if (af == AF_INET) {
#if (SIZEOF_INT != 4)
#error "Not sure if in_addr_t exists and int is not 32-bits."
#endif
- unsigned int packed_addr;
- packed_addr = inet_addr(src);
- if (packed_addr == INADDR_NONE)
- return 0;
- memcpy(dst, &packed_addr, 4);
- return 1;
- }
- /* Should set errno to EAFNOSUPPORT */
- return -1;
+ unsigned int packed_addr;
+ packed_addr = inet_addr(src);
+ if (packed_addr == INADDR_NONE)
+ return 0;
+ memcpy(dst, &packed_addr, 4);
+ return 1;
+ }
+ /* Should set errno to EAFNOSUPPORT */
+ return -1;
}
const char *
inet_ntop(int af, const void *src, char *dst, socklen_t size)
{
- if (af == AF_INET) {
- struct in_addr packed_addr;
- if (size < 16)
- /* Should set errno to ENOSPC. */
- return NULL;
- memcpy(&packed_addr, src, sizeof(packed_addr));
- return strncpy(dst, inet_ntoa(packed_addr), size);
- }
- /* Should set errno to EAFNOSUPPORT */
- return NULL;
+ if (af == AF_INET) {
+ struct in_addr packed_addr;
+ if (size < 16)
+ /* Should set errno to ENOSPC. */
+ return NULL;
+ memcpy(&packed_addr, src, sizeof(packed_addr));
+ return strncpy(dst, inet_ntoa(packed_addr), size);
+ }
+ /* Should set errno to EAFNOSUPPORT */
+ return NULL;
}
#endif
diff --git a/Modules/socketmodule.h b/Modules/socketmodule.h
index 48f230e..8515499 100644
--- a/Modules/socketmodule.h
+++ b/Modules/socketmodule.h
@@ -17,7 +17,7 @@
# include <ws2tcpip.h>
/* VC6 is shipped with old platform headers, and does not have MSTcpIP.h
* Separate SDKs have all the functions we want, but older ones don't have
- * any version information.
+ * any version information.
* I use SIO_GET_MULTICAST_FILTER to detect a decent SDK.
*/
# ifdef SIO_GET_MULTICAST_FILTER
@@ -76,44 +76,44 @@ extern "C" {
#endif
/* Python module and C API name */
-#define PySocket_MODULE_NAME "_socket"
-#define PySocket_CAPI_NAME "CAPI"
+#define PySocket_MODULE_NAME "_socket"
+#define PySocket_CAPI_NAME "CAPI"
#define PySocket_CAPSULE_NAME (PySocket_MODULE_NAME "." PySocket_CAPI_NAME)
/* Abstract the socket file descriptor type */
#ifdef MS_WINDOWS
typedef SOCKET SOCKET_T;
-# ifdef MS_WIN64
-# define SIZEOF_SOCKET_T 8
-# else
-# define SIZEOF_SOCKET_T 4
-# endif
+# ifdef MS_WIN64
+# define SIZEOF_SOCKET_T 8
+# else
+# define SIZEOF_SOCKET_T 4
+# endif
#else
typedef int SOCKET_T;
-# define SIZEOF_SOCKET_T SIZEOF_INT
+# define SIZEOF_SOCKET_T SIZEOF_INT
#endif
/* Socket address */
typedef union sock_addr {
- struct sockaddr_in in;
+ struct sockaddr_in in;
#ifdef AF_UNIX
- struct sockaddr_un un;
+ struct sockaddr_un un;
#endif
#ifdef AF_NETLINK
- struct sockaddr_nl nl;
+ struct sockaddr_nl nl;
#endif
#ifdef ENABLE_IPV6
- struct sockaddr_in6 in6;
- struct sockaddr_storage storage;
+ struct sockaddr_in6 in6;
+ struct sockaddr_storage storage;
#endif
#ifdef HAVE_BLUETOOTH_BLUETOOTH_H
- struct sockaddr_l2 bt_l2;
- struct sockaddr_rc bt_rc;
- struct sockaddr_sco bt_sco;
- struct sockaddr_hci bt_hci;
+ struct sockaddr_l2 bt_l2;
+ struct sockaddr_rc bt_rc;
+ struct sockaddr_sco bt_sco;
+ struct sockaddr_hci bt_hci;
#endif
#ifdef HAVE_NETPACKET_PACKET_H
- struct sockaddr_ll ll;
+ struct sockaddr_ll ll;
#endif
} sock_addr_t;
@@ -122,16 +122,16 @@ typedef union sock_addr {
arguments properly. */
typedef struct {
- PyObject_HEAD
- SOCKET_T sock_fd; /* Socket file descriptor */
- int sock_family; /* Address family, e.g., AF_INET */
- int sock_type; /* Socket type, e.g., SOCK_STREAM */
- int sock_proto; /* Protocol type, usually 0 */
- PyObject *(*errorhandler)(void); /* Error handler; checks
- errno, returns NULL and
- sets a Python exception */
- double sock_timeout; /* Operation timeout in seconds;
- 0.0 means non-blocking */
+ PyObject_HEAD
+ SOCKET_T sock_fd; /* Socket file descriptor */
+ int sock_family; /* Address family, e.g., AF_INET */
+ int sock_type; /* Socket type, e.g., SOCK_STREAM */
+ int sock_proto; /* Protocol type, usually 0 */
+ PyObject *(*errorhandler)(void); /* Error handler; checks
+ errno, returns NULL and
+ sets a Python exception */
+ double sock_timeout; /* Operation timeout in seconds;
+ 0.0 means non-blocking */
} PySocketSockObject;
/* --- C API ----------------------------------------------------*/
@@ -139,7 +139,7 @@ typedef struct {
/* Short explanation of what this C API export mechanism does
and how it works:
- The _ssl module needs access to the type object defined in
+ The _ssl module needs access to the type object defined in
the _socket module. Since cross-DLL linking introduces a lot of
problems on many platforms, the "trick" is to wrap the
C API of a module in a struct which then gets exported to
@@ -161,24 +161,24 @@ typedef struct {
Load _socket module and its C API; this sets up the global
PySocketModule:
-
- if (PySocketModule_ImportModuleAndAPI())
- return;
+
+ if (PySocketModule_ImportModuleAndAPI())
+ return;
Now use the C API as if it were defined in the using
module:
- if (!PyArg_ParseTuple(args, "O!|zz:ssl",
+ if (!PyArg_ParseTuple(args, "O!|zz:ssl",
- PySocketModule.Sock_Type,
+ PySocketModule.Sock_Type,
- (PyObject*)&Sock,
- &key_file, &cert_file))
- return NULL;
+ (PyObject*)&Sock,
+ &key_file, &cert_file))
+ return NULL;
Support could easily be extended to export more C APIs/symbols
- this way. Currently, only the type object is exported,
+ this way. Currently, only the type object is exported,
other candidates would be socket constructors and socket
access functions.
@@ -186,13 +186,13 @@ typedef struct {
/* C API for usage by other Python modules */
typedef struct {
- PyTypeObject *Sock_Type;
- PyObject *error;
+ PyTypeObject *Sock_Type;
+ PyObject *error;
} PySocketModule_APIObject;
/* XXX The net effect of the following appears to be to define a function
XXX named PySocketModule_APIObject in _ssl.c. It's unclear why it isn't
- XXX defined there directly.
+ XXX defined there directly.
>>> It's defined here because other modules might also want to use
>>> the C API.
@@ -208,8 +208,8 @@ typedef struct {
if (!PyArg_ParseTuple(args, "O!|zz:ssl",
&PySocketModule.Sock_Type, (PyObject*)&Sock,
- &key_file, &cert_file))
- return NULL;
+ &key_file, &cert_file))
+ return NULL;
...
*/
@@ -227,19 +227,19 @@ PySocketModule_APIObject PySocketModule;
static
int PySocketModule_ImportModuleAndAPI(void)
{
- void *api;
+ void *api;
DPRINTF(" Loading capsule %s\n", PySocket_CAPSULE_NAME);
api = PyCapsule_Import(PySocket_CAPSULE_NAME, 1);
- if (api == NULL)
- goto onError;
- memcpy(&PySocketModule, api, sizeof(PySocketModule));
- DPRINTF(" API object loaded and initialized.\n");
- return 0;
+ if (api == NULL)
+ goto onError;
+ memcpy(&PySocketModule, api, sizeof(PySocketModule));
+ DPRINTF(" API object loaded and initialized.\n");
+ return 0;
onError:
- DPRINTF(" not found.\n");
- return -1;
+ DPRINTF(" not found.\n");
+ return -1;
}
#endif /* !PySocket_BUILDING_SOCKET */
diff --git a/Modules/spwdmodule.c b/Modules/spwdmodule.c
index d3f309a..957de58 100644
--- a/Modules/spwdmodule.c
+++ b/Modules/spwdmodule.c
@@ -27,16 +27,16 @@ You have to be root to be able to use this module.");
#if defined(HAVE_GETSPNAM) || defined(HAVE_GETSPENT)
static PyStructSequence_Field struct_spwd_type_fields[] = {
- {"sp_nam", "login name"},
- {"sp_pwd", "encrypted password"},
- {"sp_lstchg", "date of last change"},
- {"sp_min", "min #days between changes"},
- {"sp_max", "max #days between changes"},
- {"sp_warn", "#days before pw expires to warn user about it"},
- {"sp_inact", "#days after pw expires until account is blocked"},
- {"sp_expire", "#days since 1970-01-01 until account is disabled"},
- {"sp_flag", "reserved"},
- {0}
+ {"sp_nam", "login name"},
+ {"sp_pwd", "encrypted password"},
+ {"sp_lstchg", "date of last change"},
+ {"sp_min", "min #days between changes"},
+ {"sp_max", "max #days between changes"},
+ {"sp_warn", "#days before pw expires to warn user about it"},
+ {"sp_inact", "#days after pw expires until account is blocked"},
+ {"sp_expire", "#days since 1970-01-01 until account is disabled"},
+ {"sp_flag", "reserved"},
+ {0}
};
PyDoc_STRVAR(struct_spwd__doc__,
@@ -46,10 +46,10 @@ This object may be accessed either as a 9-tuple of\n\
or via the object attributes as named in the above tuple.");
static PyStructSequence_Desc struct_spwd_type_desc = {
- "spwd.struct_spwd",
- struct_spwd__doc__,
- struct_spwd_type_fields,
- 9,
+ "spwd.struct_spwd",
+ struct_spwd__doc__,
+ struct_spwd_type_fields,
+ 9,
};
static int initialized;
@@ -60,42 +60,42 @@ static void
sets(PyObject *v, int i, char* val)
{
if (val)
- PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
+ PyStructSequence_SET_ITEM(v, i, PyString_FromString(val));
else {
- PyStructSequence_SET_ITEM(v, i, Py_None);
- Py_INCREF(Py_None);
+ PyStructSequence_SET_ITEM(v, i, Py_None);
+ Py_INCREF(Py_None);
}
}
static PyObject *mkspent(struct spwd *p)
{
- int setIndex = 0;
- PyObject *v = PyStructSequence_New(&StructSpwdType);
- if (v == NULL)
- return NULL;
+ int setIndex = 0;
+ PyObject *v = PyStructSequence_New(&StructSpwdType);
+ if (v == NULL)
+ return NULL;
#define SETI(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
#define SETS(i,val) sets(v, i, val)
- SETS(setIndex++, p->sp_namp);
- SETS(setIndex++, p->sp_pwdp);
- SETI(setIndex++, p->sp_lstchg);
- SETI(setIndex++, p->sp_min);
- SETI(setIndex++, p->sp_max);
- SETI(setIndex++, p->sp_warn);
- SETI(setIndex++, p->sp_inact);
- SETI(setIndex++, p->sp_expire);
- SETI(setIndex++, p->sp_flag);
+ SETS(setIndex++, p->sp_namp);
+ SETS(setIndex++, p->sp_pwdp);
+ SETI(setIndex++, p->sp_lstchg);
+ SETI(setIndex++, p->sp_min);
+ SETI(setIndex++, p->sp_max);
+ SETI(setIndex++, p->sp_warn);
+ SETI(setIndex++, p->sp_inact);
+ SETI(setIndex++, p->sp_expire);
+ SETI(setIndex++, p->sp_flag);
#undef SETS
#undef SETI
- if (PyErr_Occurred()) {
- Py_DECREF(v);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_DECREF(v);
+ return NULL;
+ }
- return v;
+ return v;
}
#endif /* HAVE_GETSPNAM || HAVE_GETSPENT */
@@ -111,15 +111,15 @@ See spwd.__doc__ for more on shadow password database entries.");
static PyObject* spwd_getspnam(PyObject *self, PyObject *args)
{
- char *name;
- struct spwd *p;
- if (!PyArg_ParseTuple(args, "s:getspnam", &name))
- return NULL;
- if ((p = getspnam(name)) == NULL) {
- PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
- return NULL;
- }
- return mkspent(p);
+ char *name;
+ struct spwd *p;
+ if (!PyArg_ParseTuple(args, "s:getspnam", &name))
+ return NULL;
+ if ((p = getspnam(name)) == NULL) {
+ PyErr_SetString(PyExc_KeyError, "getspnam(): name not found");
+ return NULL;
+ }
+ return mkspent(p);
}
#endif /* HAVE_GETSPNAM */
@@ -135,49 +135,49 @@ See spwd.__doc__ for more on shadow password database entries.");
static PyObject *
spwd_getspall(PyObject *self, PyObject *args)
{
- PyObject *d;
- struct spwd *p;
- if ((d = PyList_New(0)) == NULL)
- return NULL;
- setspent();
- while ((p = getspent()) != NULL) {
- PyObject *v = mkspent(p);
- if (v == NULL || PyList_Append(d, v) != 0) {
- Py_XDECREF(v);
- Py_DECREF(d);
- endspent();
- return NULL;
- }
- Py_DECREF(v);
- }
- endspent();
- return d;
+ PyObject *d;
+ struct spwd *p;
+ if ((d = PyList_New(0)) == NULL)
+ return NULL;
+ setspent();
+ while ((p = getspent()) != NULL) {
+ PyObject *v = mkspent(p);
+ if (v == NULL || PyList_Append(d, v) != 0) {
+ Py_XDECREF(v);
+ Py_DECREF(d);
+ endspent();
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ endspent();
+ return d;
}
#endif /* HAVE_GETSPENT */
static PyMethodDef spwd_methods[] = {
-#ifdef HAVE_GETSPNAM
- {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__},
+#ifdef HAVE_GETSPNAM
+ {"getspnam", spwd_getspnam, METH_VARARGS, spwd_getspnam__doc__},
#endif
#ifdef HAVE_GETSPENT
- {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__},
+ {"getspall", spwd_getspall, METH_NOARGS, spwd_getspall__doc__},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initspwd(void)
{
- PyObject *m;
- m=Py_InitModule3("spwd", spwd_methods, spwd__doc__);
- if (m == NULL)
- return;
- if (!initialized)
- PyStructSequence_InitType(&StructSpwdType,
- &struct_spwd_type_desc);
- Py_INCREF((PyObject *) &StructSpwdType);
- PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType);
- initialized = 1;
+ PyObject *m;
+ m=Py_InitModule3("spwd", spwd_methods, spwd__doc__);
+ if (m == NULL)
+ return;
+ if (!initialized)
+ PyStructSequence_InitType(&StructSpwdType,
+ &struct_spwd_type_desc);
+ Py_INCREF((PyObject *) &StructSpwdType);
+ PyModule_AddObject(m, "struct_spwd", (PyObject *) &StructSpwdType);
+ initialized = 1;
}
diff --git a/Modules/stropmodule.c b/Modules/stropmodule.c
index 7383194..4684baf 100644
--- a/Modules/stropmodule.c
+++ b/Modules/stropmodule.c
@@ -14,8 +14,8 @@ PyDoc_STRVAR(strop_module__doc__,
XXX are defined for all 8-bit characters! */
#define WARN if (PyErr_Warn(PyExc_DeprecationWarning, \
- "strop functions are obsolete; use string methods")) \
- return NULL
+ "strop functions are obsolete; use string methods")) \
+ return NULL
/* The lstrip(), rstrip() and strip() functions are implemented
in do_strip(), which uses an additional parameter to indicate what
@@ -29,56 +29,56 @@ PyDoc_STRVAR(strop_module__doc__,
static PyObject *
split_whitespace(char *s, Py_ssize_t len, Py_ssize_t maxsplit)
{
- Py_ssize_t i = 0, j;
- int err;
- Py_ssize_t countsplit = 0;
- PyObject* item;
- PyObject *list = PyList_New(0);
-
- if (list == NULL)
- return NULL;
-
- while (i < len) {
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i = i+1;
- }
- j = i;
- while (i < len && !isspace(Py_CHARMASK(s[i]))) {
- i = i+1;
- }
- if (j < i) {
- item = PyString_FromStringAndSize(s+j, i-j);
- if (item == NULL)
- goto finally;
-
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto finally;
-
- countsplit++;
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i = i+1;
- }
- if (maxsplit && (countsplit >= maxsplit) && i < len) {
- item = PyString_FromStringAndSize(
- s+i, len - i);
- if (item == NULL)
- goto finally;
-
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto finally;
-
- i = len;
- }
- }
- }
- return list;
+ Py_ssize_t i = 0, j;
+ int err;
+ Py_ssize_t countsplit = 0;
+ PyObject* item;
+ PyObject *list = PyList_New(0);
+
+ if (list == NULL)
+ return NULL;
+
+ while (i < len) {
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i = i+1;
+ }
+ j = i;
+ while (i < len && !isspace(Py_CHARMASK(s[i]))) {
+ i = i+1;
+ }
+ if (j < i) {
+ item = PyString_FromStringAndSize(s+j, i-j);
+ if (item == NULL)
+ goto finally;
+
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto finally;
+
+ countsplit++;
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i = i+1;
+ }
+ if (maxsplit && (countsplit >= maxsplit) && i < len) {
+ item = PyString_FromStringAndSize(
+ s+i, len - i);
+ if (item == NULL)
+ goto finally;
+
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto finally;
+
+ i = len;
+ }
+ }
+ }
+ return list;
finally:
- Py_DECREF(list);
- return NULL;
+ Py_DECREF(list);
+ return NULL;
}
@@ -96,60 +96,60 @@ PyDoc_STRVAR(splitfields__doc__,
static PyObject *
strop_splitfields(PyObject *self, PyObject *args)
{
- Py_ssize_t len, n, i, j, err;
- Py_ssize_t splitcount, maxsplit;
- char *s, *sub;
- PyObject *list, *item;
-
- WARN;
- sub = NULL;
- n = 0;
- splitcount = 0;
- maxsplit = 0;
- if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit))
- return NULL;
- if (sub == NULL)
- return split_whitespace(s, len, maxsplit);
- if (n == 0) {
- PyErr_SetString(PyExc_ValueError, "empty separator");
- return NULL;
- }
-
- list = PyList_New(0);
- if (list == NULL)
- return NULL;
-
- i = j = 0;
- while (i+n <= len) {
- if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
- item = PyString_FromStringAndSize(s+j, i-j);
- if (item == NULL)
- goto fail;
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto fail;
- i = j = i + n;
- splitcount++;
- if (maxsplit && (splitcount >= maxsplit))
- break;
- }
- else
- i++;
- }
- item = PyString_FromStringAndSize(s+j, len-j);
- if (item == NULL)
- goto fail;
- err = PyList_Append(list, item);
- Py_DECREF(item);
- if (err < 0)
- goto fail;
-
- return list;
+ Py_ssize_t len, n, i, j, err;
+ Py_ssize_t splitcount, maxsplit;
+ char *s, *sub;
+ PyObject *list, *item;
+
+ WARN;
+ sub = NULL;
+ n = 0;
+ splitcount = 0;
+ maxsplit = 0;
+ if (!PyArg_ParseTuple(args, "t#|z#n:split", &s, &len, &sub, &n, &maxsplit))
+ return NULL;
+ if (sub == NULL)
+ return split_whitespace(s, len, maxsplit);
+ if (n == 0) {
+ PyErr_SetString(PyExc_ValueError, "empty separator");
+ return NULL;
+ }
+
+ list = PyList_New(0);
+ if (list == NULL)
+ return NULL;
+
+ i = j = 0;
+ while (i+n <= len) {
+ if (s[i] == sub[0] && (n == 1 || memcmp(s+i, sub, n) == 0)) {
+ item = PyString_FromStringAndSize(s+j, i-j);
+ if (item == NULL)
+ goto fail;
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto fail;
+ i = j = i + n;
+ splitcount++;
+ if (maxsplit && (splitcount >= maxsplit))
+ break;
+ }
+ else
+ i++;
+ }
+ item = PyString_FromStringAndSize(s+j, len-j);
+ if (item == NULL)
+ goto fail;
+ err = PyList_Append(list, item);
+ Py_DECREF(item);
+ if (err < 0)
+ goto fail;
+
+ return list;
fail:
- Py_DECREF(list);
- return NULL;
+ Py_DECREF(list);
+ return NULL;
}
@@ -166,128 +166,128 @@ PyDoc_STRVAR(joinfields__doc__,
static PyObject *
strop_joinfields(PyObject *self, PyObject *args)
{
- PyObject *seq;
- char *sep = NULL;
- Py_ssize_t seqlen, seplen = 0;
- Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
- PyObject *res = NULL;
- char* p = NULL;
- ssizeargfunc getitemfunc;
-
- WARN;
- if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
- return NULL;
- if (sep == NULL) {
- sep = " ";
- seplen = 1;
- }
-
- seqlen = PySequence_Size(seq);
- if (seqlen < 0 && PyErr_Occurred())
- return NULL;
-
- if (seqlen == 1) {
- /* Optimization if there's only one item */
- PyObject *item = PySequence_GetItem(seq, 0);
- if (item && !PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be sequence of strings");
- Py_DECREF(item);
- return NULL;
- }
- return item;
- }
-
- if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
- return NULL;
- p = PyString_AsString(res);
-
- /* optimize for lists, since it's the most common case. all others
- * (tuples and arbitrary sequences) just use the sequence abstract
- * interface.
- */
- if (PyList_Check(seq)) {
- for (i = 0; i < seqlen; i++) {
- PyObject *item = PyList_GET_ITEM(seq, i);
- if (!PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be sequence of strings");
- Py_DECREF(res);
- return NULL;
- }
- slen = PyString_GET_SIZE(item);
- if (slen > PY_SSIZE_T_MAX - reslen ||
- seplen > PY_SSIZE_T_MAX - reslen - seplen) {
- PyErr_SetString(PyExc_OverflowError,
- "input too long");
- Py_DECREF(res);
- return NULL;
- }
- while (reslen + slen + seplen >= sz) {
- if (_PyString_Resize(&res, sz * 2) < 0)
- return NULL;
- sz *= 2;
- p = PyString_AsString(res) + reslen;
- }
- if (i > 0) {
- memcpy(p, sep, seplen);
- p += seplen;
- reslen += seplen;
- }
- memcpy(p, PyString_AS_STRING(item), slen);
- p += slen;
- reslen += slen;
- }
- _PyString_Resize(&res, reslen);
- return res;
- }
-
- if (seq->ob_type->tp_as_sequence == NULL ||
- (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
- {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be a sequence");
- return NULL;
- }
- /* This is now type safe */
- for (i = 0; i < seqlen; i++) {
- PyObject *item = getitemfunc(seq, i);
- if (!item || !PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be sequence of strings");
- Py_DECREF(res);
- Py_XDECREF(item);
- return NULL;
- }
- slen = PyString_GET_SIZE(item);
- if (slen > PY_SSIZE_T_MAX - reslen ||
- seplen > PY_SSIZE_T_MAX - reslen - seplen) {
- PyErr_SetString(PyExc_OverflowError,
- "input too long");
- Py_DECREF(res);
- Py_XDECREF(item);
- return NULL;
- }
- while (reslen + slen + seplen >= sz) {
- if (_PyString_Resize(&res, sz * 2) < 0) {
- Py_DECREF(item);
- return NULL;
- }
- sz *= 2;
- p = PyString_AsString(res) + reslen;
- }
- if (i > 0) {
- memcpy(p, sep, seplen);
- p += seplen;
- reslen += seplen;
- }
- memcpy(p, PyString_AS_STRING(item), slen);
- p += slen;
- reslen += slen;
- Py_DECREF(item);
- }
- _PyString_Resize(&res, reslen);
- return res;
+ PyObject *seq;
+ char *sep = NULL;
+ Py_ssize_t seqlen, seplen = 0;
+ Py_ssize_t i, reslen = 0, slen = 0, sz = 100;
+ PyObject *res = NULL;
+ char* p = NULL;
+ ssizeargfunc getitemfunc;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "O|t#:join", &seq, &sep, &seplen))
+ return NULL;
+ if (sep == NULL) {
+ sep = " ";
+ seplen = 1;
+ }
+
+ seqlen = PySequence_Size(seq);
+ if (seqlen < 0 && PyErr_Occurred())
+ return NULL;
+
+ if (seqlen == 1) {
+ /* Optimization if there's only one item */
+ PyObject *item = PySequence_GetItem(seq, 0);
+ if (item && !PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be sequence of strings");
+ Py_DECREF(item);
+ return NULL;
+ }
+ return item;
+ }
+
+ if (!(res = PyString_FromStringAndSize((char*)NULL, sz)))
+ return NULL;
+ p = PyString_AsString(res);
+
+ /* optimize for lists, since it's the most common case. all others
+ * (tuples and arbitrary sequences) just use the sequence abstract
+ * interface.
+ */
+ if (PyList_Check(seq)) {
+ for (i = 0; i < seqlen; i++) {
+ PyObject *item = PyList_GET_ITEM(seq, i);
+ if (!PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be sequence of strings");
+ Py_DECREF(res);
+ return NULL;
+ }
+ slen = PyString_GET_SIZE(item);
+ if (slen > PY_SSIZE_T_MAX - reslen ||
+ seplen > PY_SSIZE_T_MAX - reslen - seplen) {
+ PyErr_SetString(PyExc_OverflowError,
+ "input too long");
+ Py_DECREF(res);
+ return NULL;
+ }
+ while (reslen + slen + seplen >= sz) {
+ if (_PyString_Resize(&res, sz * 2) < 0)
+ return NULL;
+ sz *= 2;
+ p = PyString_AsString(res) + reslen;
+ }
+ if (i > 0) {
+ memcpy(p, sep, seplen);
+ p += seplen;
+ reslen += seplen;
+ }
+ memcpy(p, PyString_AS_STRING(item), slen);
+ p += slen;
+ reslen += slen;
+ }
+ _PyString_Resize(&res, reslen);
+ return res;
+ }
+
+ if (seq->ob_type->tp_as_sequence == NULL ||
+ (getitemfunc = seq->ob_type->tp_as_sequence->sq_item) == NULL)
+ {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be a sequence");
+ return NULL;
+ }
+ /* This is now type safe */
+ for (i = 0; i < seqlen; i++) {
+ PyObject *item = getitemfunc(seq, i);
+ if (!item || !PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be sequence of strings");
+ Py_DECREF(res);
+ Py_XDECREF(item);
+ return NULL;
+ }
+ slen = PyString_GET_SIZE(item);
+ if (slen > PY_SSIZE_T_MAX - reslen ||
+ seplen > PY_SSIZE_T_MAX - reslen - seplen) {
+ PyErr_SetString(PyExc_OverflowError,
+ "input too long");
+ Py_DECREF(res);
+ Py_XDECREF(item);
+ return NULL;
+ }
+ while (reslen + slen + seplen >= sz) {
+ if (_PyString_Resize(&res, sz * 2) < 0) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ sz *= 2;
+ p = PyString_AsString(res) + reslen;
+ }
+ if (i > 0) {
+ memcpy(p, sep, seplen);
+ p += seplen;
+ reslen += seplen;
+ }
+ memcpy(p, PyString_AS_STRING(item), slen);
+ p += slen;
+ reslen += slen;
+ Py_DECREF(item);
+ }
+ _PyString_Resize(&res, reslen);
+ return res;
}
@@ -303,34 +303,34 @@ PyDoc_STRVAR(find__doc__,
static PyObject *
strop_find(PyObject *self, PyObject *args)
{
- char *s, *sub;
- Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last))
- return NULL;
-
- if (last > len)
- last = len;
- if (last < 0)
- last += len;
- if (last < 0)
- last = 0;
- if (i < 0)
- i += len;
- if (i < 0)
- i = 0;
-
- if (n == 0 && i <= last)
- return PyInt_FromLong((long)i);
-
- last -= n;
- for (; i <= last; ++i)
- if (s[i] == sub[0] &&
- (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
- return PyInt_FromLong((long)i);
-
- return PyInt_FromLong(-1L);
+ char *s, *sub;
+ Py_ssize_t len, n, i = 0, last = PY_SSIZE_T_MAX;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#|nn:find", &s, &len, &sub, &n, &i, &last))
+ return NULL;
+
+ if (last > len)
+ last = len;
+ if (last < 0)
+ last += len;
+ if (last < 0)
+ last = 0;
+ if (i < 0)
+ i += len;
+ if (i < 0)
+ i = 0;
+
+ if (n == 0 && i <= last)
+ return PyInt_FromLong((long)i);
+
+ last -= n;
+ for (; i <= last; ++i)
+ if (s[i] == sub[0] &&
+ (n == 1 || memcmp(&s[i+1], &sub[1], n-1) == 0))
+ return PyInt_FromLong((long)i);
+
+ return PyInt_FromLong(-1L);
}
@@ -346,68 +346,68 @@ PyDoc_STRVAR(rfind__doc__,
static PyObject *
strop_rfind(PyObject *self, PyObject *args)
{
- char *s, *sub;
- Py_ssize_t len, n, j;
- Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last))
- return NULL;
-
- if (last > len)
- last = len;
- if (last < 0)
- last += len;
- if (last < 0)
- last = 0;
- if (i < 0)
- i += len;
- if (i < 0)
- i = 0;
-
- if (n == 0 && i <= last)
- return PyInt_FromLong((long)last);
-
- for (j = last-n; j >= i; --j)
- if (s[j] == sub[0] &&
- (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
- return PyInt_FromLong((long)j);
-
- return PyInt_FromLong(-1L);
+ char *s, *sub;
+ Py_ssize_t len, n, j;
+ Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#|nn:rfind", &s, &len, &sub, &n, &i, &last))
+ return NULL;
+
+ if (last > len)
+ last = len;
+ if (last < 0)
+ last += len;
+ if (last < 0)
+ last = 0;
+ if (i < 0)
+ i += len;
+ if (i < 0)
+ i = 0;
+
+ if (n == 0 && i <= last)
+ return PyInt_FromLong((long)last);
+
+ for (j = last-n; j >= i; --j)
+ if (s[j] == sub[0] &&
+ (n == 1 || memcmp(&s[j+1], &sub[1], n-1) == 0))
+ return PyInt_FromLong((long)j);
+
+ return PyInt_FromLong(-1L);
}
static PyObject *
do_strip(PyObject *args, int striptype)
{
- char *s;
- Py_ssize_t len, i, j;
-
-
- if (PyString_AsStringAndSize(args, &s, &len))
- return NULL;
-
- i = 0;
- if (striptype != RIGHTSTRIP) {
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i++;
- }
- }
-
- j = len;
- if (striptype != LEFTSTRIP) {
- do {
- j--;
- } while (j >= i && isspace(Py_CHARMASK(s[j])));
- j++;
- }
-
- if (i == 0 && j == len) {
- Py_INCREF(args);
- return args;
- }
- else
- return PyString_FromStringAndSize(s+i, j-i);
+ char *s;
+ Py_ssize_t len, i, j;
+
+
+ if (PyString_AsStringAndSize(args, &s, &len))
+ return NULL;
+
+ i = 0;
+ if (striptype != RIGHTSTRIP) {
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i++;
+ }
+ }
+
+ j = len;
+ if (striptype != LEFTSTRIP) {
+ do {
+ j--;
+ } while (j >= i && isspace(Py_CHARMASK(s[j])));
+ j++;
+ }
+
+ if (i == 0 && j == len) {
+ Py_INCREF(args);
+ return args;
+ }
+ else
+ return PyString_FromStringAndSize(s+i, j-i);
}
@@ -420,8 +420,8 @@ PyDoc_STRVAR(strip__doc__,
static PyObject *
strop_strip(PyObject *self, PyObject *args)
{
- WARN;
- return do_strip(args, BOTHSTRIP);
+ WARN;
+ return do_strip(args, BOTHSTRIP);
}
@@ -433,8 +433,8 @@ PyDoc_STRVAR(lstrip__doc__,
static PyObject *
strop_lstrip(PyObject *self, PyObject *args)
{
- WARN;
- return do_strip(args, LEFTSTRIP);
+ WARN;
+ return do_strip(args, LEFTSTRIP);
}
@@ -446,8 +446,8 @@ PyDoc_STRVAR(rstrip__doc__,
static PyObject *
strop_rstrip(PyObject *self, PyObject *args)
{
- WARN;
- return do_strip(args, RIGHTSTRIP);
+ WARN;
+ return do_strip(args, RIGHTSTRIP);
}
@@ -459,34 +459,34 @@ PyDoc_STRVAR(lower__doc__,
static PyObject *
strop_lower(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (isupper(c)) {
- changed = 1;
- *s_new = tolower(c);
- } else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (isupper(c)) {
+ changed = 1;
+ *s_new = tolower(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -498,34 +498,34 @@ PyDoc_STRVAR(upper__doc__,
static PyObject *
strop_upper(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- changed = 1;
- *s_new = toupper(c);
- } else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ changed = 1;
+ *s_new = toupper(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -538,43 +538,43 @@ PyDoc_STRVAR(capitalize__doc__,
static PyObject *
strop_capitalize(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- if (0 < n) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- changed = 1;
- *s_new = toupper(c);
- } else
- *s_new = c;
- s_new++;
- }
- for (i = 1; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (isupper(c)) {
- changed = 1;
- *s_new = tolower(c);
- } else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ if (0 < n) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ changed = 1;
+ *s_new = toupper(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ for (i = 1; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (isupper(c)) {
+ changed = 1;
+ *s_new = tolower(c);
+ } else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -589,75 +589,75 @@ PyDoc_STRVAR(expandtabs__doc__,
static PyObject *
strop_expandtabs(PyObject *self, PyObject *args)
{
- /* Original by Fredrik Lundh */
- char* e;
- char* p;
- char* q;
- Py_ssize_t i, j, old_j;
- PyObject* out;
- char* string;
- Py_ssize_t stringlen;
- int tabsize = 8;
-
- WARN;
- /* Get arguments */
- if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
- return NULL;
- if (tabsize < 1) {
- PyErr_SetString(PyExc_ValueError,
- "tabsize must be at least 1");
- return NULL;
- }
-
- /* First pass: determine size of output string */
- i = j = old_j = 0; /* j: current column; i: total of previous lines */
- e = string + stringlen;
- for (p = string; p < e; p++) {
- if (*p == '\t') {
- j += tabsize - (j%tabsize);
- if (old_j > j) {
- PyErr_SetString(PyExc_OverflowError,
- "new string is too long");
- return NULL;
- }
- old_j = j;
- } else {
- j++;
- if (*p == '\n') {
- i += j;
- j = 0;
- }
- }
- }
-
- if ((i + j) < 0) {
- PyErr_SetString(PyExc_OverflowError, "new string is too long");
- return NULL;
- }
-
- /* Second pass: create output string and fill it */
- out = PyString_FromStringAndSize(NULL, i+j);
- if (out == NULL)
- return NULL;
-
- i = 0;
- q = PyString_AS_STRING(out);
-
- for (p = string; p < e; p++) {
- if (*p == '\t') {
- j = tabsize - (i%tabsize);
- i += j;
- while (j-- > 0)
- *q++ = ' ';
- } else {
- *q++ = *p;
- i++;
- if (*p == '\n')
- i = 0;
- }
- }
-
- return out;
+ /* Original by Fredrik Lundh */
+ char* e;
+ char* p;
+ char* q;
+ Py_ssize_t i, j, old_j;
+ PyObject* out;
+ char* string;
+ Py_ssize_t stringlen;
+ int tabsize = 8;
+
+ WARN;
+ /* Get arguments */
+ if (!PyArg_ParseTuple(args, "s#|i:expandtabs", &string, &stringlen, &tabsize))
+ return NULL;
+ if (tabsize < 1) {
+ PyErr_SetString(PyExc_ValueError,
+ "tabsize must be at least 1");
+ return NULL;
+ }
+
+ /* First pass: determine size of output string */
+ i = j = old_j = 0; /* j: current column; i: total of previous lines */
+ e = string + stringlen;
+ for (p = string; p < e; p++) {
+ if (*p == '\t') {
+ j += tabsize - (j%tabsize);
+ if (old_j > j) {
+ PyErr_SetString(PyExc_OverflowError,
+ "new string is too long");
+ return NULL;
+ }
+ old_j = j;
+ } else {
+ j++;
+ if (*p == '\n') {
+ i += j;
+ j = 0;
+ }
+ }
+ }
+
+ if ((i + j) < 0) {
+ PyErr_SetString(PyExc_OverflowError, "new string is too long");
+ return NULL;
+ }
+
+ /* Second pass: create output string and fill it */
+ out = PyString_FromStringAndSize(NULL, i+j);
+ if (out == NULL)
+ return NULL;
+
+ i = 0;
+ q = PyString_AS_STRING(out);
+
+ for (p = string; p < e; p++) {
+ if (*p == '\t') {
+ j = tabsize - (i%tabsize);
+ i += j;
+ while (j-- > 0)
+ *q++ = ' ';
+ } else {
+ *q++ = *p;
+ i++;
+ if (*p == '\n')
+ i = 0;
+ }
+ }
+
+ return out;
}
@@ -671,38 +671,38 @@ PyDoc_STRVAR(count__doc__,
static PyObject *
strop_count(PyObject *self, PyObject *args)
{
- char *s, *sub;
- Py_ssize_t len, n;
- Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
- Py_ssize_t m, r;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last))
- return NULL;
- if (last > len)
- last = len;
- if (last < 0)
- last += len;
- if (last < 0)
- last = 0;
- if (i < 0)
- i += len;
- if (i < 0)
- i = 0;
- m = last + 1 - n;
- if (n == 0)
- return PyInt_FromLong((long) (m-i));
-
- r = 0;
- while (i < m) {
- if (!memcmp(s+i, sub, n)) {
- r++;
- i += n;
- } else {
- i++;
- }
- }
- return PyInt_FromLong((long) r);
+ char *s, *sub;
+ Py_ssize_t len, n;
+ Py_ssize_t i = 0, last = PY_SSIZE_T_MAX;
+ Py_ssize_t m, r;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#|nn:count", &s, &len, &sub, &n, &i, &last))
+ return NULL;
+ if (last > len)
+ last = len;
+ if (last < 0)
+ last += len;
+ if (last < 0)
+ last = 0;
+ if (i < 0)
+ i += len;
+ if (i < 0)
+ i = 0;
+ m = last + 1 - n;
+ if (n == 0)
+ return PyInt_FromLong((long) (m-i));
+
+ r = 0;
+ while (i < m) {
+ if (!memcmp(s+i, sub, n)) {
+ r++;
+ i += n;
+ } else {
+ i++;
+ }
+ }
+ return PyInt_FromLong((long) r);
}
@@ -715,39 +715,39 @@ PyDoc_STRVAR(swapcase__doc__,
static PyObject *
strop_swapcase(PyObject *self, PyObject *args)
{
- char *s, *s_new;
- Py_ssize_t i, n;
- PyObject *newstr;
- int changed;
-
- WARN;
- if (PyString_AsStringAndSize(args, &s, &n))
- return NULL;
- newstr = PyString_FromStringAndSize(NULL, n);
- if (newstr == NULL)
- return NULL;
- s_new = PyString_AsString(newstr);
- changed = 0;
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- changed = 1;
- *s_new = toupper(c);
- }
- else if (isupper(c)) {
- changed = 1;
- *s_new = tolower(c);
- }
- else
- *s_new = c;
- s_new++;
- }
- if (!changed) {
- Py_DECREF(newstr);
- Py_INCREF(args);
- return args;
- }
- return newstr;
+ char *s, *s_new;
+ Py_ssize_t i, n;
+ PyObject *newstr;
+ int changed;
+
+ WARN;
+ if (PyString_AsStringAndSize(args, &s, &n))
+ return NULL;
+ newstr = PyString_FromStringAndSize(NULL, n);
+ if (newstr == NULL)
+ return NULL;
+ s_new = PyString_AsString(newstr);
+ changed = 0;
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ changed = 1;
+ *s_new = toupper(c);
+ }
+ else if (isupper(c)) {
+ changed = 1;
+ *s_new = tolower(c);
+ }
+ else
+ *s_new = c;
+ s_new++;
+ }
+ if (!changed) {
+ Py_DECREF(newstr);
+ Py_INCREF(args);
+ return args;
+ }
+ return newstr;
}
@@ -764,45 +764,45 @@ PyDoc_STRVAR(atoi__doc__,
static PyObject *
strop_atoi(PyObject *self, PyObject *args)
{
- char *s, *end;
- int base = 10;
- long x;
- char buffer[256]; /* For errors */
-
- WARN;
- if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base))
- return NULL;
-
- if ((base != 0 && base < 2) || base > 36) {
- PyErr_SetString(PyExc_ValueError, "invalid base for atoi()");
- return NULL;
- }
-
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- errno = 0;
- if (base == 0 && s[0] == '0')
- x = (long) PyOS_strtoul(s, &end, base);
- else
- x = PyOS_strtol(s, &end, base);
- if (end == s || !isalnum(Py_CHARMASK(end[-1])))
- goto bad;
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
+ char *s, *end;
+ int base = 10;
+ long x;
+ char buffer[256]; /* For errors */
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "s|i:atoi", &s, &base))
+ return NULL;
+
+ if ((base != 0 && base < 2) || base > 36) {
+ PyErr_SetString(PyExc_ValueError, "invalid base for atoi()");
+ return NULL;
+ }
+
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ errno = 0;
+ if (base == 0 && s[0] == '0')
+ x = (long) PyOS_strtoul(s, &end, base);
+ else
+ x = PyOS_strtol(s, &end, base);
+ if (end == s || !isalnum(Py_CHARMASK(end[-1])))
+ goto bad;
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
bad:
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for atoi(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- else if (errno != 0) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "atoi() literal too large: %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- return PyInt_FromLong(x);
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for atoi(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ else if (errno != 0) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "atoi() literal too large: %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ return PyInt_FromLong(x);
}
@@ -820,41 +820,41 @@ PyDoc_STRVAR(atol__doc__,
static PyObject *
strop_atol(PyObject *self, PyObject *args)
{
- char *s, *end;
- int base = 10;
- PyObject *x;
- char buffer[256]; /* For errors */
-
- WARN;
- if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
- return NULL;
-
- if ((base != 0 && base < 2) || base > 36) {
- PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
- return NULL;
- }
-
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- if (s[0] == '\0') {
- PyErr_SetString(PyExc_ValueError, "empty string for atol()");
- return NULL;
- }
- x = PyLong_FromString(s, &end, base);
- if (x == NULL)
- return NULL;
- if (base == 0 && (*end == 'l' || *end == 'L'))
- end++;
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for atol(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- Py_DECREF(x);
- return NULL;
- }
- return x;
+ char *s, *end;
+ int base = 10;
+ PyObject *x;
+ char buffer[256]; /* For errors */
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "s|i:atol", &s, &base))
+ return NULL;
+
+ if ((base != 0 && base < 2) || base > 36) {
+ PyErr_SetString(PyExc_ValueError, "invalid base for atol()");
+ return NULL;
+ }
+
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ if (s[0] == '\0') {
+ PyErr_SetString(PyExc_ValueError, "empty string for atol()");
+ return NULL;
+ }
+ x = PyLong_FromString(s, &end, base);
+ if (x == NULL)
+ return NULL;
+ if (base == 0 && (*end == 'l' || *end == 'L'))
+ end++;
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for atol(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ Py_DECREF(x);
+ return NULL;
+ }
+ return x;
}
@@ -866,34 +866,34 @@ PyDoc_STRVAR(atof__doc__,
static PyObject *
strop_atof(PyObject *self, PyObject *args)
{
- char *s, *end;
- double x;
- char buffer[256]; /* For errors */
-
- WARN;
- if (!PyArg_ParseTuple(args, "s:atof", &s))
- return NULL;
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- if (s[0] == '\0') {
- PyErr_SetString(PyExc_ValueError, "empty string for atof()");
- return NULL;
- }
-
- PyFPE_START_PROTECT("strop_atof", return 0)
- x = PyOS_string_to_double(s, &end, PyExc_OverflowError);
- PyFPE_END_PROTECT(x)
- if (x == -1 && PyErr_Occurred())
- return NULL;
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for atof(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- return NULL;
- }
- return PyFloat_FromDouble(x);
+ char *s, *end;
+ double x;
+ char buffer[256]; /* For errors */
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "s:atof", &s))
+ return NULL;
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ if (s[0] == '\0') {
+ PyErr_SetString(PyExc_ValueError, "empty string for atof()");
+ return NULL;
+ }
+
+ PyFPE_START_PROTECT("strop_atof", return 0)
+ x = PyOS_string_to_double(s, &end, PyExc_OverflowError);
+ PyFPE_END_PROTECT(x)
+ if (x == -1 && PyErr_Occurred())
+ return NULL;
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for atof(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ return NULL;
+ }
+ return PyFloat_FromDouble(x);
}
@@ -907,29 +907,29 @@ PyDoc_STRVAR(maketrans__doc__,
static PyObject *
strop_maketrans(PyObject *self, PyObject *args)
{
- unsigned char *c, *from=NULL, *to=NULL;
- Py_ssize_t i, fromlen=0, tolen=0;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "t#t#:maketrans", &from, &fromlen, &to, &tolen))
- return NULL;
-
- if (fromlen != tolen) {
- PyErr_SetString(PyExc_ValueError,
- "maketrans arguments must have same length");
- return NULL;
- }
-
- result = PyString_FromStringAndSize((char *)NULL, 256);
- if (result == NULL)
- return NULL;
- c = (unsigned char *) PyString_AS_STRING((PyStringObject *)result);
- for (i = 0; i < 256; i++)
- c[i]=(unsigned char)i;
- for (i = 0; i < fromlen; i++)
- c[from[i]]=to[i];
-
- return result;
+ unsigned char *c, *from=NULL, *to=NULL;
+ Py_ssize_t i, fromlen=0, tolen=0;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "t#t#:maketrans", &from, &fromlen, &to, &tolen))
+ return NULL;
+
+ if (fromlen != tolen) {
+ PyErr_SetString(PyExc_ValueError,
+ "maketrans arguments must have same length");
+ return NULL;
+ }
+
+ result = PyString_FromStringAndSize((char *)NULL, 256);
+ if (result == NULL)
+ return NULL;
+ c = (unsigned char *) PyString_AS_STRING((PyStringObject *)result);
+ for (i = 0; i < 256; i++)
+ c[i]=(unsigned char)i;
+ for (i = 0; i < fromlen; i++)
+ c[from[i]]=to[i];
+
+ return result;
}
@@ -944,69 +944,69 @@ PyDoc_STRVAR(translate__doc__,
static PyObject *
strop_translate(PyObject *self, PyObject *args)
{
- register char *input, *table, *output;
- Py_ssize_t i;
- int c, changed = 0;
- PyObject *input_obj;
- char *table1, *output_start, *del_table=NULL;
- Py_ssize_t inlen, tablen, dellen = 0;
- PyObject *result;
- int trans_table[256];
-
- WARN;
- if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
- &table1, &tablen, &del_table, &dellen))
- return NULL;
- if (tablen != 256) {
- PyErr_SetString(PyExc_ValueError,
- "translation table must be 256 characters long");
- return NULL;
- }
-
- table = table1;
- inlen = PyString_GET_SIZE(input_obj);
- result = PyString_FromStringAndSize((char *)NULL, inlen);
- if (result == NULL)
- return NULL;
- output_start = output = PyString_AsString(result);
- input = PyString_AsString(input_obj);
-
- if (dellen == 0) {
- /* If no deletions are required, use faster code */
- for (i = inlen; --i >= 0; ) {
- c = Py_CHARMASK(*input++);
- if (Py_CHARMASK((*output++ = table[c])) != c)
- changed = 1;
- }
- if (changed)
- return result;
- Py_DECREF(result);
- Py_INCREF(input_obj);
- return input_obj;
- }
-
- for (i = 0; i < 256; i++)
- trans_table[i] = Py_CHARMASK(table[i]);
-
- for (i = 0; i < dellen; i++)
- trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
-
- for (i = inlen; --i >= 0; ) {
- c = Py_CHARMASK(*input++);
- if (trans_table[c] != -1)
- if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
- continue;
- changed = 1;
- }
- if (!changed) {
- Py_DECREF(result);
- Py_INCREF(input_obj);
- return input_obj;
- }
- /* Fix the size of the resulting string */
- if (inlen > 0)
- _PyString_Resize(&result, output - output_start);
- return result;
+ register char *input, *table, *output;
+ Py_ssize_t i;
+ int c, changed = 0;
+ PyObject *input_obj;
+ char *table1, *output_start, *del_table=NULL;
+ Py_ssize_t inlen, tablen, dellen = 0;
+ PyObject *result;
+ int trans_table[256];
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "St#|t#:translate", &input_obj,
+ &table1, &tablen, &del_table, &dellen))
+ return NULL;
+ if (tablen != 256) {
+ PyErr_SetString(PyExc_ValueError,
+ "translation table must be 256 characters long");
+ return NULL;
+ }
+
+ table = table1;
+ inlen = PyString_GET_SIZE(input_obj);
+ result = PyString_FromStringAndSize((char *)NULL, inlen);
+ if (result == NULL)
+ return NULL;
+ output_start = output = PyString_AsString(result);
+ input = PyString_AsString(input_obj);
+
+ if (dellen == 0) {
+ /* If no deletions are required, use faster code */
+ for (i = inlen; --i >= 0; ) {
+ c = Py_CHARMASK(*input++);
+ if (Py_CHARMASK((*output++ = table[c])) != c)
+ changed = 1;
+ }
+ if (changed)
+ return result;
+ Py_DECREF(result);
+ Py_INCREF(input_obj);
+ return input_obj;
+ }
+
+ for (i = 0; i < 256; i++)
+ trans_table[i] = Py_CHARMASK(table[i]);
+
+ for (i = 0; i < dellen; i++)
+ trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
+
+ for (i = inlen; --i >= 0; ) {
+ c = Py_CHARMASK(*input++);
+ if (trans_table[c] != -1)
+ if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
+ continue;
+ changed = 1;
+ }
+ if (!changed) {
+ Py_DECREF(result);
+ Py_INCREF(input_obj);
+ return input_obj;
+ }
+ /* Fix the size of the resulting string */
+ if (inlen > 0)
+ _PyString_Resize(&result, output - output_start);
+ return result;
}
@@ -1022,22 +1022,22 @@ strop_translate(PyObject *self, PyObject *args)
found, or -1 if not found. If len of PAT is greater than length of
MEM, the function returns -1.
*/
-static Py_ssize_t
+static Py_ssize_t
mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
{
- register Py_ssize_t ii;
-
- /* pattern can not occur in the last pat_len-1 chars */
- len -= pat_len;
-
- for (ii = 0; ii <= len; ii++) {
- if (mem[ii] == pat[0] &&
- (pat_len == 1 ||
- memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
- return ii;
- }
- }
- return -1;
+ register Py_ssize_t ii;
+
+ /* pattern can not occur in the last pat_len-1 chars */
+ len -= pat_len;
+
+ for (ii = 0; ii <= len; ii++) {
+ if (mem[ii] == pat[0] &&
+ (pat_len == 1 ||
+ memcmp(&mem[ii+1], &pat[1], pat_len-1) == 0)) {
+ return ii;
+ }
+ }
+ return -1;
}
/*
@@ -1045,23 +1045,23 @@ mymemfind(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
Return the number of distinct times PAT is found in MEM.
meaning mem=1111 and pat==11 returns 2.
- mem=11111 and pat==11 also return 2.
+ mem=11111 and pat==11 also return 2.
*/
-static Py_ssize_t
+static Py_ssize_t
mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
{
- register Py_ssize_t offset = 0;
- Py_ssize_t nfound = 0;
-
- while (len >= 0) {
- offset = mymemfind(mem, len, pat, pat_len);
- if (offset == -1)
- break;
- mem += offset + pat_len;
- len -= offset + pat_len;
- nfound++;
- }
- return nfound;
+ register Py_ssize_t offset = 0;
+ Py_ssize_t nfound = 0;
+
+ while (len >= 0) {
+ offset = mymemfind(mem, len, pat, pat_len);
+ if (offset == -1)
+ break;
+ mem += offset + pat_len;
+ len -= offset + pat_len;
+ nfound++;
+ }
+ return nfound;
}
/*
@@ -1084,69 +1084,69 @@ mymemcnt(const char *mem, Py_ssize_t len, const char *pat, Py_ssize_t pat_len)
NULL if an error occurred.
*/
static char *
-mymemreplace(const char *str, Py_ssize_t len, /* input string */
- const char *pat, Py_ssize_t pat_len, /* pattern string to find */
- const char *sub, Py_ssize_t sub_len, /* substitution string */
- Py_ssize_t count, /* number of replacements */
- Py_ssize_t *out_len)
+mymemreplace(const char *str, Py_ssize_t len, /* input string */
+ const char *pat, Py_ssize_t pat_len, /* pattern string to find */
+ const char *sub, Py_ssize_t sub_len, /* substitution string */
+ Py_ssize_t count, /* number of replacements */
+ Py_ssize_t *out_len)
{
- char *out_s;
- char *new_s;
- Py_ssize_t nfound, offset, new_len;
-
- if (len == 0 || pat_len > len)
- goto return_same;
-
- /* find length of output string */
- nfound = mymemcnt(str, len, pat, pat_len);
- if (count < 0)
- count = PY_SSIZE_T_MAX;
- else if (nfound > count)
- nfound = count;
- if (nfound == 0)
- goto return_same;
-
- new_len = len + nfound*(sub_len - pat_len);
- if (new_len == 0) {
- /* Have to allocate something for the caller to free(). */
- out_s = (char *)PyMem_MALLOC(1);
- if (out_s == NULL)
- return NULL;
- out_s[0] = '\0';
- }
- else {
- assert(new_len > 0);
- new_s = (char *)PyMem_MALLOC(new_len);
- if (new_s == NULL)
- return NULL;
- out_s = new_s;
-
- for (; count > 0 && len > 0; --count) {
- /* find index of next instance of pattern */
- offset = mymemfind(str, len, pat, pat_len);
- if (offset == -1)
- break;
-
- /* copy non matching part of input string */
- memcpy(new_s, str, offset);
- str += offset + pat_len;
- len -= offset + pat_len;
-
- /* copy substitute into the output string */
- new_s += offset;
- memcpy(new_s, sub, sub_len);
- new_s += sub_len;
- }
- /* copy any remaining values into output string */
- if (len > 0)
- memcpy(new_s, str, len);
- }
- *out_len = new_len;
- return out_s;
+ char *out_s;
+ char *new_s;
+ Py_ssize_t nfound, offset, new_len;
+
+ if (len == 0 || pat_len > len)
+ goto return_same;
+
+ /* find length of output string */
+ nfound = mymemcnt(str, len, pat, pat_len);
+ if (count < 0)
+ count = PY_SSIZE_T_MAX;
+ else if (nfound > count)
+ nfound = count;
+ if (nfound == 0)
+ goto return_same;
+
+ new_len = len + nfound*(sub_len - pat_len);
+ if (new_len == 0) {
+ /* Have to allocate something for the caller to free(). */
+ out_s = (char *)PyMem_MALLOC(1);
+ if (out_s == NULL)
+ return NULL;
+ out_s[0] = '\0';
+ }
+ else {
+ assert(new_len > 0);
+ new_s = (char *)PyMem_MALLOC(new_len);
+ if (new_s == NULL)
+ return NULL;
+ out_s = new_s;
+
+ for (; count > 0 && len > 0; --count) {
+ /* find index of next instance of pattern */
+ offset = mymemfind(str, len, pat, pat_len);
+ if (offset == -1)
+ break;
+
+ /* copy non matching part of input string */
+ memcpy(new_s, str, offset);
+ str += offset + pat_len;
+ len -= offset + pat_len;
+
+ /* copy substitute into the output string */
+ new_s += offset;
+ memcpy(new_s, sub, sub_len);
+ new_s += sub_len;
+ }
+ /* copy any remaining values into output string */
+ if (len > 0)
+ memcpy(new_s, str, len);
+ }
+ *out_len = new_len;
+ return out_s;
return_same:
- *out_len = -1;
- return (char *)str; /* cast away const */
+ *out_len = -1;
+ return (char *)str; /* cast away const */
}
@@ -1160,41 +1160,41 @@ PyDoc_STRVAR(replace__doc__,
static PyObject *
strop_replace(PyObject *self, PyObject *args)
{
- char *str, *pat,*sub,*new_s;
- Py_ssize_t len,pat_len,sub_len,out_len;
- Py_ssize_t count = -1;
- PyObject *newstr;
-
- WARN;
- if (!PyArg_ParseTuple(args, "t#t#t#|n:replace",
- &str, &len, &pat, &pat_len, &sub, &sub_len,
- &count))
- return NULL;
- if (pat_len <= 0) {
- PyErr_SetString(PyExc_ValueError, "empty pattern string");
- return NULL;
- }
- /* CAUTION: strop treats a replace count of 0 as infinity, unlke
- * current (2.1) string.py and string methods. Preserve this for
- * ... well, hard to say for what <wink>.
- */
- if (count == 0)
- count = -1;
- new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
- if (new_s == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- if (out_len == -1) {
- /* we're returning another reference to the input string */
- newstr = PyTuple_GetItem(args, 0);
- Py_XINCREF(newstr);
- }
- else {
- newstr = PyString_FromStringAndSize(new_s, out_len);
- PyMem_FREE(new_s);
- }
- return newstr;
+ char *str, *pat,*sub,*new_s;
+ Py_ssize_t len,pat_len,sub_len,out_len;
+ Py_ssize_t count = -1;
+ PyObject *newstr;
+
+ WARN;
+ if (!PyArg_ParseTuple(args, "t#t#t#|n:replace",
+ &str, &len, &pat, &pat_len, &sub, &sub_len,
+ &count))
+ return NULL;
+ if (pat_len <= 0) {
+ PyErr_SetString(PyExc_ValueError, "empty pattern string");
+ return NULL;
+ }
+ /* CAUTION: strop treats a replace count of 0 as infinity, unlke
+ * current (2.1) string.py and string methods. Preserve this for
+ * ... well, hard to say for what <wink>.
+ */
+ if (count == 0)
+ count = -1;
+ new_s = mymemreplace(str,len,pat,pat_len,sub,sub_len,count,&out_len);
+ if (new_s == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ if (out_len == -1) {
+ /* we're returning another reference to the input string */
+ newstr = PyTuple_GetItem(args, 0);
+ Py_XINCREF(newstr);
+ }
+ else {
+ newstr = PyString_FromStringAndSize(new_s, out_len);
+ PyMem_FREE(new_s);
+ }
+ return newstr;
}
@@ -1202,69 +1202,69 @@ strop_replace(PyObject *self, PyObject *args)
static PyMethodDef
strop_methods[] = {
- {"atof", strop_atof, METH_VARARGS, atof__doc__},
- {"atoi", strop_atoi, METH_VARARGS, atoi__doc__},
- {"atol", strop_atol, METH_VARARGS, atol__doc__},
- {"capitalize", strop_capitalize, METH_O, capitalize__doc__},
- {"count", strop_count, METH_VARARGS, count__doc__},
- {"expandtabs", strop_expandtabs, METH_VARARGS, expandtabs__doc__},
- {"find", strop_find, METH_VARARGS, find__doc__},
- {"join", strop_joinfields, METH_VARARGS, joinfields__doc__},
- {"joinfields", strop_joinfields, METH_VARARGS, joinfields__doc__},
- {"lstrip", strop_lstrip, METH_O, lstrip__doc__},
- {"lower", strop_lower, METH_O, lower__doc__},
- {"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__},
- {"replace", strop_replace, METH_VARARGS, replace__doc__},
- {"rfind", strop_rfind, METH_VARARGS, rfind__doc__},
- {"rstrip", strop_rstrip, METH_O, rstrip__doc__},
- {"split", strop_splitfields, METH_VARARGS, splitfields__doc__},
- {"splitfields", strop_splitfields, METH_VARARGS, splitfields__doc__},
- {"strip", strop_strip, METH_O, strip__doc__},
- {"swapcase", strop_swapcase, METH_O, swapcase__doc__},
- {"translate", strop_translate, METH_VARARGS, translate__doc__},
- {"upper", strop_upper, METH_O, upper__doc__},
- {NULL, NULL} /* sentinel */
+ {"atof", strop_atof, METH_VARARGS, atof__doc__},
+ {"atoi", strop_atoi, METH_VARARGS, atoi__doc__},
+ {"atol", strop_atol, METH_VARARGS, atol__doc__},
+ {"capitalize", strop_capitalize, METH_O, capitalize__doc__},
+ {"count", strop_count, METH_VARARGS, count__doc__},
+ {"expandtabs", strop_expandtabs, METH_VARARGS, expandtabs__doc__},
+ {"find", strop_find, METH_VARARGS, find__doc__},
+ {"join", strop_joinfields, METH_VARARGS, joinfields__doc__},
+ {"joinfields", strop_joinfields, METH_VARARGS, joinfields__doc__},
+ {"lstrip", strop_lstrip, METH_O, lstrip__doc__},
+ {"lower", strop_lower, METH_O, lower__doc__},
+ {"maketrans", strop_maketrans, METH_VARARGS, maketrans__doc__},
+ {"replace", strop_replace, METH_VARARGS, replace__doc__},
+ {"rfind", strop_rfind, METH_VARARGS, rfind__doc__},
+ {"rstrip", strop_rstrip, METH_O, rstrip__doc__},
+ {"split", strop_splitfields, METH_VARARGS, splitfields__doc__},
+ {"splitfields", strop_splitfields, METH_VARARGS, splitfields__doc__},
+ {"strip", strop_strip, METH_O, strip__doc__},
+ {"swapcase", strop_swapcase, METH_O, swapcase__doc__},
+ {"translate", strop_translate, METH_VARARGS, translate__doc__},
+ {"upper", strop_upper, METH_O, upper__doc__},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initstrop(void)
{
- PyObject *m, *s;
- char buf[256];
- int c, n;
- m = Py_InitModule4("strop", strop_methods, strop_module__doc__,
- (PyObject*)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- /* Create 'whitespace' object */
- n = 0;
- for (c = 0; c < 256; c++) {
- if (isspace(c))
- buf[n++] = c;
- }
- s = PyString_FromStringAndSize(buf, n);
- if (s)
- PyModule_AddObject(m, "whitespace", s);
-
- /* Create 'lowercase' object */
- n = 0;
- for (c = 0; c < 256; c++) {
- if (islower(c))
- buf[n++] = c;
- }
- s = PyString_FromStringAndSize(buf, n);
- if (s)
- PyModule_AddObject(m, "lowercase", s);
-
- /* Create 'uppercase' object */
- n = 0;
- for (c = 0; c < 256; c++) {
- if (isupper(c))
- buf[n++] = c;
- }
- s = PyString_FromStringAndSize(buf, n);
- if (s)
- PyModule_AddObject(m, "uppercase", s);
+ PyObject *m, *s;
+ char buf[256];
+ int c, n;
+ m = Py_InitModule4("strop", strop_methods, strop_module__doc__,
+ (PyObject*)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ /* Create 'whitespace' object */
+ n = 0;
+ for (c = 0; c < 256; c++) {
+ if (isspace(c))
+ buf[n++] = c;
+ }
+ s = PyString_FromStringAndSize(buf, n);
+ if (s)
+ PyModule_AddObject(m, "whitespace", s);
+
+ /* Create 'lowercase' object */
+ n = 0;
+ for (c = 0; c < 256; c++) {
+ if (islower(c))
+ buf[n++] = c;
+ }
+ s = PyString_FromStringAndSize(buf, n);
+ if (s)
+ PyModule_AddObject(m, "lowercase", s);
+
+ /* Create 'uppercase' object */
+ n = 0;
+ for (c = 0; c < 256; c++) {
+ if (isupper(c))
+ buf[n++] = c;
+ }
+ s = PyString_FromStringAndSize(buf, n);
+ if (s)
+ PyModule_AddObject(m, "uppercase", s);
}
diff --git a/Modules/sunaudiodev.c b/Modules/sunaudiodev.c
index 285dc66..0c32fe3 100644
--- a/Modules/sunaudiodev.c
+++ b/Modules/sunaudiodev.c
@@ -23,98 +23,98 @@
/* #define offsetof(str,mem) ((int)(((str *)0)->mem)) */
typedef struct {
- PyObject_HEAD
- int x_fd; /* The open file */
- int x_icount; /* # samples read */
- int x_ocount; /* # samples written */
- int x_isctl; /* True if control device */
-
+ PyObject_HEAD
+ int x_fd; /* The open file */
+ int x_icount; /* # samples read */
+ int x_ocount; /* # samples written */
+ int x_isctl; /* True if control device */
+
} sadobject;
typedef struct {
- PyObject_HEAD
- audio_info_t ai;
+ PyObject_HEAD
+ audio_info_t ai;
} sadstatusobject;
static PyTypeObject Sadtype;
static PyTypeObject Sadstatustype;
-static sadstatusobject *sads_alloc(void); /* Forward */
+static sadstatusobject *sads_alloc(void); /* Forward */
static PyObject *SunAudioError;
-#define is_sadobject(v) (Py_TYPE(v) == &Sadtype)
-#define is_sadstatusobject(v) (Py_TYPE(v) == &Sadstatustype)
+#define is_sadobject(v) (Py_TYPE(v) == &Sadtype)
+#define is_sadstatusobject(v) (Py_TYPE(v) == &Sadstatustype)
static sadobject *
newsadobject(PyObject *args)
{
- sadobject *xp;
- int fd;
- char *mode;
- int imode;
- char* basedev;
- char* ctldev;
- char* opendev;
-
- /* Check arg for r/w/rw */
- if (!PyArg_ParseTuple(args, "s", &mode))
- return NULL;
- if (strcmp(mode, "r") == 0)
- imode = 0;
- else if (strcmp(mode, "w") == 0)
- imode = 1;
- else if (strcmp(mode, "rw") == 0)
- imode = 2;
- else if (strcmp(mode, "control") == 0)
- imode = -1;
- else {
- PyErr_SetString(SunAudioError,
- "Mode should be one of 'r', 'w', 'rw' or 'control'");
- return NULL;
- }
-
- /* Open the correct device. The base device name comes from the
- * AUDIODEV environment variable first, then /dev/audio. The
- * control device tacks "ctl" onto the base device name.
- */
- basedev = getenv("AUDIODEV");
- if (!basedev)
- basedev = "/dev/audio";
- ctldev = PyMem_NEW(char, strlen(basedev) + 4);
- if (!ctldev) {
- PyErr_NoMemory();
- return NULL;
- }
- strcpy(ctldev, basedev);
- strcat(ctldev, "ctl");
-
- if (imode < 0) {
- opendev = ctldev;
- fd = open(ctldev, 2);
- }
- else {
- opendev = basedev;
- fd = open(basedev, imode);
- }
- if (fd < 0) {
- PyErr_SetFromErrnoWithFilename(SunAudioError, opendev);
- PyMem_DEL(ctldev);
- return NULL;
- }
- PyMem_DEL(ctldev);
-
- /* Create and initialize the object */
- xp = PyObject_New(sadobject, &Sadtype);
- if (xp == NULL) {
- close(fd);
- return NULL;
- }
- xp->x_fd = fd;
- xp->x_icount = xp->x_ocount = 0;
- xp->x_isctl = (imode < 0);
-
- return xp;
+ sadobject *xp;
+ int fd;
+ char *mode;
+ int imode;
+ char* basedev;
+ char* ctldev;
+ char* opendev;
+
+ /* Check arg for r/w/rw */
+ if (!PyArg_ParseTuple(args, "s", &mode))
+ return NULL;
+ if (strcmp(mode, "r") == 0)
+ imode = 0;
+ else if (strcmp(mode, "w") == 0)
+ imode = 1;
+ else if (strcmp(mode, "rw") == 0)
+ imode = 2;
+ else if (strcmp(mode, "control") == 0)
+ imode = -1;
+ else {
+ PyErr_SetString(SunAudioError,
+ "Mode should be one of 'r', 'w', 'rw' or 'control'");
+ return NULL;
+ }
+
+ /* Open the correct device. The base device name comes from the
+ * AUDIODEV environment variable first, then /dev/audio. The
+ * control device tacks "ctl" onto the base device name.
+ */
+ basedev = getenv("AUDIODEV");
+ if (!basedev)
+ basedev = "/dev/audio";
+ ctldev = PyMem_NEW(char, strlen(basedev) + 4);
+ if (!ctldev) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ strcpy(ctldev, basedev);
+ strcat(ctldev, "ctl");
+
+ if (imode < 0) {
+ opendev = ctldev;
+ fd = open(ctldev, 2);
+ }
+ else {
+ opendev = basedev;
+ fd = open(basedev, imode);
+ }
+ if (fd < 0) {
+ PyErr_SetFromErrnoWithFilename(SunAudioError, opendev);
+ PyMem_DEL(ctldev);
+ return NULL;
+ }
+ PyMem_DEL(ctldev);
+
+ /* Create and initialize the object */
+ xp = PyObject_New(sadobject, &Sadtype);
+ if (xp == NULL) {
+ close(fd);
+ return NULL;
+ }
+ xp->x_fd = fd;
+ xp->x_icount = xp->x_ocount = 0;
+ xp->x_isctl = (imode < 0);
+
+ return xp;
}
/* Sad methods */
@@ -122,327 +122,327 @@ newsadobject(PyObject *args)
static void
sad_dealloc(sadobject *xp)
{
- close(xp->x_fd);
- PyObject_Del(xp);
+ close(xp->x_fd);
+ PyObject_Del(xp);
}
static PyObject *
sad_read(sadobject *self, PyObject *args)
{
- int size, count;
- char *cp;
- PyObject *rv;
-
- if (!PyArg_ParseTuple(args, "i:read", &size))
- return NULL;
- rv = PyString_FromStringAndSize(NULL, size);
- if (rv == NULL)
- return NULL;
-
- if (!(cp = PyString_AsString(rv)))
- goto finally;
-
- count = read(self->x_fd, cp, size);
- if (count < 0) {
- PyErr_SetFromErrno(SunAudioError);
- goto finally;
- }
+ int size, count;
+ char *cp;
+ PyObject *rv;
+
+ if (!PyArg_ParseTuple(args, "i:read", &size))
+ return NULL;
+ rv = PyString_FromStringAndSize(NULL, size);
+ if (rv == NULL)
+ return NULL;
+
+ if (!(cp = PyString_AsString(rv)))
+ goto finally;
+
+ count = read(self->x_fd, cp, size);
+ if (count < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ goto finally;
+ }
#if 0
- /* TBD: why print this message if you can handle the condition?
- * assume it's debugging info which we can just as well get rid
- * of. in any case this message should *not* be using printf!
- */
- if (count != size)
- printf("sunaudio: funny read rv %d wtd %d\n", count, size);
+ /* TBD: why print this message if you can handle the condition?
+ * assume it's debugging info which we can just as well get rid
+ * of. in any case this message should *not* be using printf!
+ */
+ if (count != size)
+ printf("sunaudio: funny read rv %d wtd %d\n", count, size);
#endif
- self->x_icount += count;
- return rv;
+ self->x_icount += count;
+ return rv;
finally:
- Py_DECREF(rv);
- return NULL;
+ Py_DECREF(rv);
+ return NULL;
}
static PyObject *
sad_write(sadobject *self, PyObject *args)
{
- char *cp;
- int count, size;
-
- if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
- return NULL;
-
- count = write(self->x_fd, cp, size);
- if (count < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
+ char *cp;
+ int count, size;
+
+ if (!PyArg_ParseTuple(args, "s#:write", &cp, &size))
+ return NULL;
+
+ count = write(self->x_fd, cp, size);
+ if (count < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
#if 0
- if (count != size)
- printf("sunaudio: funny write rv %d wanted %d\n", count, size);
+ if (count != size)
+ printf("sunaudio: funny write rv %d wanted %d\n", count, size);
#endif
- self->x_ocount += count;
-
- Py_INCREF(Py_None);
- return Py_None;
+ self->x_ocount += count;
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_getinfo(sadobject *self)
{
- sadstatusobject *rv;
+ sadstatusobject *rv;
- if (!(rv = sads_alloc()))
- return NULL;
+ if (!(rv = sads_alloc()))
+ return NULL;
- if (ioctl(self->x_fd, AUDIO_GETINFO, &rv->ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- Py_DECREF(rv);
- return NULL;
- }
- return (PyObject *)rv;
+ if (ioctl(self->x_fd, AUDIO_GETINFO, &rv->ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ Py_DECREF(rv);
+ return NULL;
+ }
+ return (PyObject *)rv;
}
static PyObject *
sad_setinfo(sadobject *self, sadstatusobject *arg)
{
- if (!is_sadstatusobject(arg)) {
- PyErr_SetString(PyExc_TypeError,
- "Must be sun audio status object");
- return NULL;
- }
- if (ioctl(self->x_fd, AUDIO_SETINFO, &arg->ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (!is_sadstatusobject(arg)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Must be sun audio status object");
+ return NULL;
+ }
+ if (ioctl(self->x_fd, AUDIO_SETINFO, &arg->ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_ibufcount(sadobject *self)
{
- audio_info_t ai;
-
- if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- return PyInt_FromLong(ai.record.samples - self->x_icount);
+ audio_info_t ai;
+
+ if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ return PyInt_FromLong(ai.record.samples - self->x_icount);
}
static PyObject *
sad_obufcount(sadobject *self)
{
- audio_info_t ai;
-
- if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- /* x_ocount is in bytes, whereas play.samples is in frames */
- /* we want frames */
- return PyInt_FromLong(self->x_ocount / (ai.play.channels *
- ai.play.precision / 8) -
- ai.play.samples);
+ audio_info_t ai;
+
+ if (ioctl(self->x_fd, AUDIO_GETINFO, &ai) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ /* x_ocount is in bytes, whereas play.samples is in frames */
+ /* we want frames */
+ return PyInt_FromLong(self->x_ocount / (ai.play.channels *
+ ai.play.precision / 8) -
+ ai.play.samples);
}
static PyObject *
sad_drain(sadobject *self)
{
- if (ioctl(self->x_fd, AUDIO_DRAIN, 0) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (ioctl(self->x_fd, AUDIO_DRAIN, 0) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef SOLARIS
static PyObject *
sad_getdev(sadobject *self)
{
- struct audio_device ad;
+ struct audio_device ad;
- if (ioctl(self->x_fd, AUDIO_GETDEV, &ad) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- return Py_BuildValue("(sss)", ad.name, ad.version, ad.config);
+ if (ioctl(self->x_fd, AUDIO_GETDEV, &ad) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ return Py_BuildValue("(sss)", ad.name, ad.version, ad.config);
}
#endif
static PyObject *
sad_flush(sadobject *self)
{
- if (ioctl(self->x_fd, I_FLUSH, FLUSHW) < 0) {
- PyErr_SetFromErrno(SunAudioError);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (ioctl(self->x_fd, I_FLUSH, FLUSHW) < 0) {
+ PyErr_SetFromErrno(SunAudioError);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_close(sadobject *self)
{
-
- if (self->x_fd >= 0) {
- close(self->x_fd);
- self->x_fd = -1;
- }
- Py_INCREF(Py_None);
- return Py_None;
+
+ if (self->x_fd >= 0) {
+ close(self->x_fd);
+ self->x_fd = -1;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sad_fileno(sadobject *self)
{
- return PyInt_FromLong(self->x_fd);
+ return PyInt_FromLong(self->x_fd);
}
static PyMethodDef sad_methods[] = {
- { "read", (PyCFunction)sad_read, METH_VARARGS },
- { "write", (PyCFunction)sad_write, METH_VARARGS },
- { "ibufcount", (PyCFunction)sad_ibufcount, METH_NOARGS },
- { "obufcount", (PyCFunction)sad_obufcount, METH_NOARGS },
+ { "read", (PyCFunction)sad_read, METH_VARARGS },
+ { "write", (PyCFunction)sad_write, METH_VARARGS },
+ { "ibufcount", (PyCFunction)sad_ibufcount, METH_NOARGS },
+ { "obufcount", (PyCFunction)sad_obufcount, METH_NOARGS },
#define CTL_METHODS 4
- { "getinfo", (PyCFunction)sad_getinfo, METH_NOARGS },
- { "setinfo", (PyCFunction)sad_setinfo, METH_O},
- { "drain", (PyCFunction)sad_drain, METH_NOARGS },
- { "flush", (PyCFunction)sad_flush, METH_NOARGS },
+ { "getinfo", (PyCFunction)sad_getinfo, METH_NOARGS },
+ { "setinfo", (PyCFunction)sad_setinfo, METH_O},
+ { "drain", (PyCFunction)sad_drain, METH_NOARGS },
+ { "flush", (PyCFunction)sad_flush, METH_NOARGS },
#ifdef SOLARIS
- { "getdev", (PyCFunction)sad_getdev, METH_NOARGS },
+ { "getdev", (PyCFunction)sad_getdev, METH_NOARGS },
#endif
- { "close", (PyCFunction)sad_close, METH_NOARGS },
- { "fileno", (PyCFunction)sad_fileno, METH_NOARGS },
- {NULL, NULL} /* sentinel */
+ { "close", (PyCFunction)sad_close, METH_NOARGS },
+ { "fileno", (PyCFunction)sad_fileno, METH_NOARGS },
+ {NULL, NULL} /* sentinel */
};
static PyObject *
sad_getattr(sadobject *xp, char *name)
{
- if (xp->x_isctl)
- return Py_FindMethod(sad_methods+CTL_METHODS,
- (PyObject *)xp, name);
- else
- return Py_FindMethod(sad_methods, (PyObject *)xp, name);
+ if (xp->x_isctl)
+ return Py_FindMethod(sad_methods+CTL_METHODS,
+ (PyObject *)xp, name);
+ else
+ return Py_FindMethod(sad_methods, (PyObject *)xp, name);
}
/* ----------------------------------------------------------------- */
static sadstatusobject *
sads_alloc(void) {
- return PyObject_New(sadstatusobject, &Sadstatustype);
+ return PyObject_New(sadstatusobject, &Sadstatustype);
}
static void
sads_dealloc(sadstatusobject *xp)
{
- PyMem_DEL(xp);
+ PyMem_DEL(xp);
}
#define OFF(x) offsetof(audio_info_t,x)
static struct memberlist sads_ml[] = {
- { "i_sample_rate", T_UINT, OFF(record.sample_rate) },
- { "i_channels", T_UINT, OFF(record.channels) },
- { "i_precision", T_UINT, OFF(record.precision) },
- { "i_encoding", T_UINT, OFF(record.encoding) },
- { "i_gain", T_UINT, OFF(record.gain) },
- { "i_port", T_UINT, OFF(record.port) },
- { "i_samples", T_UINT, OFF(record.samples) },
- { "i_eof", T_UINT, OFF(record.eof) },
- { "i_pause", T_UBYTE, OFF(record.pause) },
- { "i_error", T_UBYTE, OFF(record.error) },
- { "i_waiting", T_UBYTE, OFF(record.waiting) },
- { "i_open", T_UBYTE, OFF(record.open) , RO},
- { "i_active", T_UBYTE, OFF(record.active) , RO},
+ { "i_sample_rate", T_UINT, OFF(record.sample_rate) },
+ { "i_channels", T_UINT, OFF(record.channels) },
+ { "i_precision", T_UINT, OFF(record.precision) },
+ { "i_encoding", T_UINT, OFF(record.encoding) },
+ { "i_gain", T_UINT, OFF(record.gain) },
+ { "i_port", T_UINT, OFF(record.port) },
+ { "i_samples", T_UINT, OFF(record.samples) },
+ { "i_eof", T_UINT, OFF(record.eof) },
+ { "i_pause", T_UBYTE, OFF(record.pause) },
+ { "i_error", T_UBYTE, OFF(record.error) },
+ { "i_waiting", T_UBYTE, OFF(record.waiting) },
+ { "i_open", T_UBYTE, OFF(record.open) , RO},
+ { "i_active", T_UBYTE, OFF(record.active) , RO},
#ifdef SOLARIS
- { "i_buffer_size", T_UINT, OFF(record.buffer_size) },
- { "i_balance", T_UBYTE, OFF(record.balance) },
- { "i_avail_ports", T_UINT, OFF(record.avail_ports) },
+ { "i_buffer_size", T_UINT, OFF(record.buffer_size) },
+ { "i_balance", T_UBYTE, OFF(record.balance) },
+ { "i_avail_ports", T_UINT, OFF(record.avail_ports) },
#endif
- { "o_sample_rate", T_UINT, OFF(play.sample_rate) },
- { "o_channels", T_UINT, OFF(play.channels) },
- { "o_precision", T_UINT, OFF(play.precision) },
- { "o_encoding", T_UINT, OFF(play.encoding) },
- { "o_gain", T_UINT, OFF(play.gain) },
- { "o_port", T_UINT, OFF(play.port) },
- { "o_samples", T_UINT, OFF(play.samples) },
- { "o_eof", T_UINT, OFF(play.eof) },
- { "o_pause", T_UBYTE, OFF(play.pause) },
- { "o_error", T_UBYTE, OFF(play.error) },
- { "o_waiting", T_UBYTE, OFF(play.waiting) },
- { "o_open", T_UBYTE, OFF(play.open) , RO},
- { "o_active", T_UBYTE, OFF(play.active) , RO},
+ { "o_sample_rate", T_UINT, OFF(play.sample_rate) },
+ { "o_channels", T_UINT, OFF(play.channels) },
+ { "o_precision", T_UINT, OFF(play.precision) },
+ { "o_encoding", T_UINT, OFF(play.encoding) },
+ { "o_gain", T_UINT, OFF(play.gain) },
+ { "o_port", T_UINT, OFF(play.port) },
+ { "o_samples", T_UINT, OFF(play.samples) },
+ { "o_eof", T_UINT, OFF(play.eof) },
+ { "o_pause", T_UBYTE, OFF(play.pause) },
+ { "o_error", T_UBYTE, OFF(play.error) },
+ { "o_waiting", T_UBYTE, OFF(play.waiting) },
+ { "o_open", T_UBYTE, OFF(play.open) , RO},
+ { "o_active", T_UBYTE, OFF(play.active) , RO},
#ifdef SOLARIS
- { "o_buffer_size", T_UINT, OFF(play.buffer_size) },
- { "o_balance", T_UBYTE, OFF(play.balance) },
- { "o_avail_ports", T_UINT, OFF(play.avail_ports) },
+ { "o_buffer_size", T_UINT, OFF(play.buffer_size) },
+ { "o_balance", T_UBYTE, OFF(play.balance) },
+ { "o_avail_ports", T_UINT, OFF(play.avail_ports) },
#endif
- { "monitor_gain", T_UINT, OFF(monitor_gain) },
- { NULL, 0, 0},
+ { "monitor_gain", T_UINT, OFF(monitor_gain) },
+ { NULL, 0, 0},
};
static PyObject *
sads_getattr(sadstatusobject *xp, char *name)
{
- return PyMember_Get((char *)&xp->ai, sads_ml, name);
+ return PyMember_Get((char *)&xp->ai, sads_ml, name);
}
static int
sads_setattr(sadstatusobject *xp, char *name, PyObject *v)
{
- if (v == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete sun audio status attributes");
- return -1;
- }
- return PyMember_Set((char *)&xp->ai, sads_ml, name, v);
+ if (v == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete sun audio status attributes");
+ return -1;
+ }
+ return PyMember_Set((char *)&xp->ai, sads_ml, name, v);
}
/* ------------------------------------------------------------------- */
static PyTypeObject Sadtype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "sunaudiodev.sun_audio_device", /*tp_name*/
- sizeof(sadobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)sad_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)sad_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "sunaudiodev.sun_audio_device", /*tp_name*/
+ sizeof(sadobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)sad_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)sad_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyTypeObject Sadstatustype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "sunaudiodev.sun_audio_device_status", /*tp_name*/
- sizeof(sadstatusobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)sads_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)sads_getattr, /*tp_getattr*/
- (setattrfunc)sads_setattr, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "sunaudiodev.sun_audio_device_status", /*tp_name*/
+ sizeof(sadstatusobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)sads_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)sads_getattr, /*tp_getattr*/
+ (setattrfunc)sads_setattr, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
/* ------------------------------------------------------------------- */
static PyObject *
sadopen(PyObject *self, PyObject *args)
{
- return (PyObject *)newsadobject(args);
+ return (PyObject *)newsadobject(args);
}
-
+
static PyMethodDef sunaudiodev_methods[] = {
{ "open", sadopen, METH_VARARGS },
{ 0, 0 },
@@ -451,17 +451,17 @@ static PyMethodDef sunaudiodev_methods[] = {
void
initsunaudiodev(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the sunaudiodev module has been removed in "
- "Python 3.0", 2) < 0)
- return;
-
- m = Py_InitModule("sunaudiodev", sunaudiodev_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- SunAudioError = PyErr_NewException("sunaudiodev.error", NULL, NULL);
- if (SunAudioError)
- PyDict_SetItemString(d, "error", SunAudioError);
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the sunaudiodev module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
+
+ m = Py_InitModule("sunaudiodev", sunaudiodev_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ SunAudioError = PyErr_NewException("sunaudiodev.error", NULL, NULL);
+ if (SunAudioError)
+ PyDict_SetItemString(d, "error", SunAudioError);
}
diff --git a/Modules/svmodule.c b/Modules/svmodule.c
index 3845e20..6e419ce 100644
--- a/Modules/svmodule.c
+++ b/Modules/svmodule.c
@@ -9,23 +9,23 @@
#include <svideo.h>
#include "Python.h"
#include "compile.h"
-#include "yuv.h" /* for YUV conversion functions */
+#include "yuv.h" /* for YUV conversion functions */
typedef struct {
- PyObject_HEAD
- SV_nodeP ob_svideo;
- svCaptureInfo ob_info;
+ PyObject_HEAD
+ SV_nodeP ob_svideo;
+ svCaptureInfo ob_info;
} svobject;
typedef struct {
- PyObject_HEAD
- void *ob_capture;
- int ob_mustunlock;
- svCaptureInfo ob_info;
- svobject *ob_svideo;
+ PyObject_HEAD
+ void *ob_capture;
+ int ob_mustunlock;
+ svCaptureInfo ob_info;
+ svobject *ob_svideo;
} captureobject;
-static PyObject *SvError; /* exception sv.error */
+static PyObject *SvError; /* exception sv.error */
static PyObject *newcaptureobject(svobject *, void *, int);
@@ -33,36 +33,36 @@ static PyObject *newcaptureobject(svobject *, void *, int);
static PyObject *
sv_error(void)
{
- PyErr_SetString(SvError, svStrerror(svideo_errno));
- return NULL;
+ PyErr_SetString(SvError, svStrerror(svideo_errno));
+ return NULL;
}
static PyObject *
-svc_conversion(captureobject *self, PyObject *args, void (*function)(), float factor)
+svc_conversion(captureobject *self, PyObject *args, void (*function)(), float factor)
{
- PyObject *output;
- int invert;
- char* outstr;
+ PyObject *output;
+ int invert;
+ char* outstr;
- if (!PyArg_Parse(args, "i", &invert))
- return NULL;
+ if (!PyArg_Parse(args, "i", &invert))
+ return NULL;
- if (!(output = PyString_FromStringAndSize(
- NULL,
- (int)(self->ob_info.width * self->ob_info.height * factor))))
- {
- return NULL;
- }
- if (!(outstr = PyString_AsString(output))) {
- Py_DECREF(output);
- return NULL;
- }
+ if (!(output = PyString_FromStringAndSize(
+ NULL,
+ (int)(self->ob_info.width * self->ob_info.height * factor))))
+ {
+ return NULL;
+ }
+ if (!(outstr = PyString_AsString(output))) {
+ Py_DECREF(output);
+ return NULL;
+ }
- (*function)((boolean)invert, self->ob_capture,
- outstr,
- self->ob_info.width, self->ob_info.height);
+ (*function)((boolean)invert, self->ob_capture,
+ outstr,
+ self->ob_info.width, self->ob_info.height);
- return output;
+ return output;
}
/*
@@ -72,117 +72,117 @@ svc_conversion(captureobject *self, PyObject *args, void (*function)(), float fa
static PyObject *
svc_YUVtoYUV422DC(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_YUV411_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args, yuv_sv411_to_cl422dc, 2.0);
+ if (self->ob_info.format != SV_YUV411_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, yuv_sv411_to_cl422dc, 2.0);
}
static PyObject *
svc_YUVtoYUV422DC_quarter(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_YUV411_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args,
- yuv_sv411_to_cl422dc_quartersize, 0.5);
+ if (self->ob_info.format != SV_YUV411_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args,
+ yuv_sv411_to_cl422dc_quartersize, 0.5);
}
static PyObject *
svc_YUVtoYUV422DC_sixteenth(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_YUV411_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args,
- yuv_sv411_to_cl422dc_sixteenthsize, 0.125);
+ if (self->ob_info.format != SV_YUV411_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args,
+ yuv_sv411_to_cl422dc_sixteenthsize, 0.125);
}
static PyObject *
svc_YUVtoRGB(captureobject *self, PyObject *args)
{
- switch (self->ob_info.format) {
- case SV_YUV411_FRAMES:
- case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
- break;
- default:
- PyErr_SetString(SvError, "data had bad format");
- return NULL;
- }
- return svc_conversion(self, args, svYUVtoRGB, (float) sizeof(long));
+ switch (self->ob_info.format) {
+ case SV_YUV411_FRAMES:
+ case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
+ break;
+ default:
+ PyErr_SetString(SvError, "data had bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, svYUVtoRGB, (float) sizeof(long));
}
static PyObject *
svc_RGB8toRGB32(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_RGB8_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args, svRGB8toRGB32, (float) sizeof(long));
+ if (self->ob_info.format != SV_RGB8_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, svRGB8toRGB32, (float) sizeof(long));
}
static PyObject *
svc_InterleaveFields(captureobject *self, PyObject *args)
{
- if (self->ob_info.format != SV_RGB8_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
- return svc_conversion(self, args, svInterleaveFields, 1.0);
+ if (self->ob_info.format != SV_RGB8_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+ return svc_conversion(self, args, svInterleaveFields, 1.0);
}
static PyObject *
svc_GetFields(captureobject *self, PyObject *args)
{
- PyObject *f1 = NULL;
- PyObject *f2 = NULL;
- PyObject *ret = NULL;
- int fieldsize;
- char* obcapture;
-
- if (self->ob_info.format != SV_RGB8_FRAMES) {
- PyErr_SetString(SvError, "data has bad format");
- return NULL;
- }
-
- fieldsize = self->ob_info.width * self->ob_info.height / 2;
- obcapture = (char*)self->ob_capture;
-
- if (!(f1 = PyString_FromStringAndSize(obcapture, fieldsize)))
- goto finally;
- if (!(f2 = PyString_FromStringAndSize(obcapture + fieldsize,
- fieldsize)))
- goto finally;
- ret = PyTuple_Pack(2, f1, f2);
+ PyObject *f1 = NULL;
+ PyObject *f2 = NULL;
+ PyObject *ret = NULL;
+ int fieldsize;
+ char* obcapture;
+
+ if (self->ob_info.format != SV_RGB8_FRAMES) {
+ PyErr_SetString(SvError, "data has bad format");
+ return NULL;
+ }
+
+ fieldsize = self->ob_info.width * self->ob_info.height / 2;
+ obcapture = (char*)self->ob_capture;
+
+ if (!(f1 = PyString_FromStringAndSize(obcapture, fieldsize)))
+ goto finally;
+ if (!(f2 = PyString_FromStringAndSize(obcapture + fieldsize,
+ fieldsize)))
+ goto finally;
+ ret = PyTuple_Pack(2, f1, f2);
finally:
- Py_XDECREF(f1);
- Py_XDECREF(f2);
- return ret;
+ Py_XDECREF(f1);
+ Py_XDECREF(f2);
+ return ret;
}
-
+
static PyObject *
svc_UnlockCaptureData(captureobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (!self->ob_mustunlock) {
- PyErr_SetString(SvError, "buffer should not be unlocked");
- return NULL;
- }
+ if (!self->ob_mustunlock) {
+ PyErr_SetString(SvError, "buffer should not be unlocked");
+ return NULL;
+ }
- if (svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture))
- return sv_error();
+ if (svUnlockCaptureData(self->ob_svideo->ob_svideo, self->ob_capture))
+ return sv_error();
- self->ob_mustunlock = 0;
+ self->ob_mustunlock = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#ifdef USE_GL
@@ -191,780 +191,780 @@ svc_UnlockCaptureData(captureobject *self, PyObject *args)
static PyObject *
svc_lrectwrite(captureobject *self, PyObject *args)
{
- Screencoord x1, x2, y1, y2;
+ Screencoord x1, x2, y1, y2;
- if (!PyArg_Parse(args, "(hhhh)", &x1, &x2, &y1, &y2))
- return NULL;
+ if (!PyArg_Parse(args, "(hhhh)", &x1, &x2, &y1, &y2))
+ return NULL;
- lrectwrite(x1, x2, y1, y2, (unsigned long *) self->ob_capture);
+ lrectwrite(x1, x2, y1, y2, (unsigned long *) self->ob_capture);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
static PyObject *
svc_writefile(captureobject *self, PyObject *args)
{
- PyObject *file;
- int size;
- FILE* fp;
+ PyObject *file;
+ int size;
+ FILE* fp;
- if (!PyArg_Parse(args, "O", &file))
- return NULL;
+ if (!PyArg_Parse(args, "O", &file))
+ return NULL;
- if (!PyFile_Check(file)) {
- PyErr_SetString(SvError, "not a file object");
- return NULL;
- }
+ if (!PyFile_Check(file)) {
+ PyErr_SetString(SvError, "not a file object");
+ return NULL;
+ }
- if (!(fp = PyFile_AsFile(file)))
- return NULL;
+ if (!(fp = PyFile_AsFile(file)))
+ return NULL;
- size = self->ob_info.width * self->ob_info.height;
+ size = self->ob_info.width * self->ob_info.height;
- if (fwrite(self->ob_capture, sizeof(long), size, fp) != size) {
- PyErr_SetString(SvError, "writing failed");
- return NULL;
- }
+ if (fwrite(self->ob_capture, sizeof(long), size, fp) != size) {
+ PyErr_SetString(SvError, "writing failed");
+ return NULL;
+ }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
svc_FindVisibleRegion(captureobject *self, PyObject *args)
{
- void *visible;
- int width;
+ void *visible;
+ int width;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svFindVisibleRegion(self->ob_svideo->ob_svideo,
- self->ob_capture, &visible,
- self->ob_info.width))
- return sv_error();
+ if (svFindVisibleRegion(self->ob_svideo->ob_svideo,
+ self->ob_capture, &visible,
+ self->ob_info.width))
+ return sv_error();
- if (visible == NULL) {
- PyErr_SetString(SvError, "data in wrong format");
- return NULL;
- }
+ if (visible == NULL) {
+ PyErr_SetString(SvError, "data in wrong format");
+ return NULL;
+ }
- return newcaptureobject(self->ob_svideo, visible, 0);
+ return newcaptureobject(self->ob_svideo, visible, 0);
}
static PyMethodDef capture_methods[] = {
- {"YUVtoRGB", (PyCFunction)svc_YUVtoRGB, METH_OLDARGS},
- {"RGB8toRGB32", (PyCFunction)svc_RGB8toRGB32, METH_OLDARGS},
- {"InterleaveFields", (PyCFunction)svc_InterleaveFields, METH_OLDARGS},
- {"UnlockCaptureData", (PyCFunction)svc_UnlockCaptureData, METH_OLDARGS},
- {"FindVisibleRegion", (PyCFunction)svc_FindVisibleRegion, METH_OLDARGS},
- {"GetFields", (PyCFunction)svc_GetFields, METH_OLDARGS},
- {"YUVtoYUV422DC", (PyCFunction)svc_YUVtoYUV422DC, METH_OLDARGS},
- {"YUVtoYUV422DC_quarter",(PyCFunction)svc_YUVtoYUV422DC_quarter, METH_OLDARGS},
- {"YUVtoYUV422DC_sixteenth",(PyCFunction)svc_YUVtoYUV422DC_sixteenth, METH_OLDARGS},
+ {"YUVtoRGB", (PyCFunction)svc_YUVtoRGB, METH_OLDARGS},
+ {"RGB8toRGB32", (PyCFunction)svc_RGB8toRGB32, METH_OLDARGS},
+ {"InterleaveFields", (PyCFunction)svc_InterleaveFields, METH_OLDARGS},
+ {"UnlockCaptureData", (PyCFunction)svc_UnlockCaptureData, METH_OLDARGS},
+ {"FindVisibleRegion", (PyCFunction)svc_FindVisibleRegion, METH_OLDARGS},
+ {"GetFields", (PyCFunction)svc_GetFields, METH_OLDARGS},
+ {"YUVtoYUV422DC", (PyCFunction)svc_YUVtoYUV422DC, METH_OLDARGS},
+ {"YUVtoYUV422DC_quarter",(PyCFunction)svc_YUVtoYUV422DC_quarter, METH_OLDARGS},
+ {"YUVtoYUV422DC_sixteenth",(PyCFunction)svc_YUVtoYUV422DC_sixteenth, METH_OLDARGS},
#ifdef USE_GL
- {"lrectwrite", (PyCFunction)svc_lrectwrite, METH_OLDARGS},
+ {"lrectwrite", (PyCFunction)svc_lrectwrite, METH_OLDARGS},
#endif
- {"writefile", (PyCFunction)svc_writefile, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"writefile", (PyCFunction)svc_writefile, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static void
capture_dealloc(captureobject *self)
{
- if (self->ob_capture != NULL) {
- if (self->ob_mustunlock)
- (void)svUnlockCaptureData(self->ob_svideo->ob_svideo,
- self->ob_capture);
- self->ob_capture = NULL;
- Py_DECREF(self->ob_svideo);
- self->ob_svideo = NULL;
- }
- PyObject_Del(self);
+ if (self->ob_capture != NULL) {
+ if (self->ob_mustunlock)
+ (void)svUnlockCaptureData(self->ob_svideo->ob_svideo,
+ self->ob_capture);
+ self->ob_capture = NULL;
+ Py_DECREF(self->ob_svideo);
+ self->ob_svideo = NULL;
+ }
+ PyObject_Del(self);
}
static PyObject *
capture_getattr(svobject *self, char *name)
{
- return Py_FindMethod(capture_methods, (PyObject *)self, name);
+ return Py_FindMethod(capture_methods, (PyObject *)self, name);
}
PyTypeObject Capturetype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "sv.capture", /*tp_name*/
- sizeof(captureobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)capture_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)capture_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "sv.capture", /*tp_name*/
+ sizeof(captureobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)capture_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)capture_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newcaptureobject(svobject *self, void *ptr, int mustunlock)
{
- captureobject *p;
+ captureobject *p;
- p = PyObject_New(captureobject, &Capturetype);
- if (p == NULL)
- return NULL;
- p->ob_svideo = self;
- Py_INCREF(self);
- p->ob_capture = ptr;
- p->ob_mustunlock = mustunlock;
- p->ob_info = self->ob_info;
- return (PyObject *) p;
+ p = PyObject_New(captureobject, &Capturetype);
+ if (p == NULL)
+ return NULL;
+ p->ob_svideo = self;
+ Py_INCREF(self);
+ p->ob_capture = ptr;
+ p->ob_mustunlock = mustunlock;
+ p->ob_info = self->ob_info;
+ return (PyObject *) p;
}
static PyObject *
sv_GetCaptureData(svobject *self, PyObject *args)
{
- void *ptr;
- long fieldID;
- PyObject *res, *c;
+ void *ptr;
+ long fieldID;
+ PyObject *res, *c;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svGetCaptureData(self->ob_svideo, &ptr, &fieldID))
- return sv_error();
+ if (svGetCaptureData(self->ob_svideo, &ptr, &fieldID))
+ return sv_error();
- if (ptr == NULL) {
- PyErr_SetString(SvError, "no data available");
- return NULL;
- }
+ if (ptr == NULL) {
+ PyErr_SetString(SvError, "no data available");
+ return NULL;
+ }
- c = newcaptureobject(self, ptr, 1);
- if (c == NULL)
- return NULL;
- res = Py_BuildValue("(Oi)", c, fieldID);
- Py_DECREF(c);
- return res;
+ c = newcaptureobject(self, ptr, 1);
+ if (c == NULL)
+ return NULL;
+ res = Py_BuildValue("(Oi)", c, fieldID);
+ Py_DECREF(c);
+ return res;
}
static PyObject *
sv_BindGLWindow(svobject *self, PyObject *args)
{
- long wid;
- int mode;
+ long wid;
+ int mode;
- if (!PyArg_Parse(args, "(ii)", &wid, &mode))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &wid, &mode))
+ return NULL;
- if (svBindGLWindow(self->ob_svideo, wid, mode))
- return sv_error();
+ if (svBindGLWindow(self->ob_svideo, wid, mode))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_EndContinuousCapture(svobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svEndContinuousCapture(self->ob_svideo))
- return sv_error();
+ if (svEndContinuousCapture(self->ob_svideo))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_IsVideoDisplayed(svobject *self, PyObject *args)
{
- int v;
+ int v;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- v = svIsVideoDisplayed(self->ob_svideo);
- if (v == -1)
- return sv_error();
+ v = svIsVideoDisplayed(self->ob_svideo);
+ if (v == -1)
+ return sv_error();
- return PyInt_FromLong((long) v);
+ return PyInt_FromLong((long) v);
}
static PyObject *
sv_OutputOffset(svobject *self, PyObject *args)
{
- int x_offset;
- int y_offset;
+ int x_offset;
+ int y_offset;
- if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
+ return NULL;
- if (svOutputOffset(self->ob_svideo, x_offset, y_offset))
- return sv_error();
+ if (svOutputOffset(self->ob_svideo, x_offset, y_offset))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_PutFrame(svobject *self, PyObject *args)
{
- char *buffer;
+ char *buffer;
- if (!PyArg_Parse(args, "s", &buffer))
- return NULL;
+ if (!PyArg_Parse(args, "s", &buffer))
+ return NULL;
- if (svPutFrame(self->ob_svideo, buffer))
- return sv_error();
+ if (svPutFrame(self->ob_svideo, buffer))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_QuerySize(svobject *self, PyObject *args)
{
- int w;
- int h;
- int rw;
- int rh;
+ int w;
+ int h;
+ int rw;
+ int rh;
- if (!PyArg_Parse(args, "(ii)", &w, &h))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &w, &h))
+ return NULL;
- if (svQuerySize(self->ob_svideo, w, h, &rw, &rh))
- return sv_error();
+ if (svQuerySize(self->ob_svideo, w, h, &rw, &rh))
+ return sv_error();
- return Py_BuildValue("(ii)", (long) rw, (long) rh);
+ return Py_BuildValue("(ii)", (long) rw, (long) rh);
}
static PyObject *
sv_SetSize(svobject *self, PyObject *args)
{
- int w;
- int h;
+ int w;
+ int h;
- if (!PyArg_Parse(args, "(ii)", &w, &h))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &w, &h))
+ return NULL;
- if (svSetSize(self->ob_svideo, w, h))
- return sv_error();
+ if (svSetSize(self->ob_svideo, w, h))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_SetStdDefaults(svobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svSetStdDefaults(self->ob_svideo))
- return sv_error();
+ if (svSetStdDefaults(self->ob_svideo))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_UseExclusive(svobject *self, PyObject *args)
{
- boolean onoff;
- int mode;
+ boolean onoff;
+ int mode;
- if (!PyArg_Parse(args, "(ii)", &onoff, &mode))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &onoff, &mode))
+ return NULL;
- if (svUseExclusive(self->ob_svideo, onoff, mode))
- return sv_error();
+ if (svUseExclusive(self->ob_svideo, onoff, mode))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_WindowOffset(svobject *self, PyObject *args)
{
- int x_offset;
- int y_offset;
+ int x_offset;
+ int y_offset;
- if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
- return NULL;
+ if (!PyArg_Parse(args, "(ii)", &x_offset, &y_offset))
+ return NULL;
- if (svWindowOffset(self->ob_svideo, x_offset, y_offset))
- return sv_error();
+ if (svWindowOffset(self->ob_svideo, x_offset, y_offset))
+ return sv_error();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sv_CaptureBurst(svobject *self, PyObject *args)
{
- int bytes, i;
- svCaptureInfo info;
- void *bitvector = NULL;
- PyObject *videodata = NULL;
- PyObject *bitvecobj = NULL;
- PyObject *res = NULL;
- static PyObject *evenitem, *odditem;
-
- if (!PyArg_Parse(args, "(iiiii)", &info.format,
- &info.width, &info.height,
- &info.size, &info.samplingrate))
- return NULL;
-
- switch (info.format) {
- case SV_RGB8_FRAMES:
- bitvector = malloc(SV_BITVEC_SIZE(info.size));
- break;
- case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
- break;
- default:
- PyErr_SetString(SvError, "illegal format specified");
- return NULL;
- }
-
- if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) {
- res = sv_error();
- goto finally;
- }
-
- if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
- goto finally;
-
- /* XXX -- need to do something about the bitvector */
- {
- char* str = PyString_AsString(videodata);
- if (!str)
- goto finally;
-
- if (svCaptureBurst(self->ob_svideo, &info, str, bitvector)) {
- res = sv_error();
- goto finally;
- }
- }
-
- if (bitvector) {
- if (evenitem == NULL) {
- if (!(evenitem = PyInt_FromLong(0)))
- goto finally;
- }
- if (odditem == NULL) {
- if (!(odditem = PyInt_FromLong(1)))
- goto finally;
- }
- if (!(bitvecobj = PyTuple_New(2 * info.size)))
- goto finally;
-
- for (i = 0; i < 2 * info.size; i++) {
- int sts;
-
- if (SV_GET_FIELD(bitvector, i) == SV_EVEN_FIELD) {
- Py_INCREF(evenitem);
- sts = PyTuple_SetItem(bitvecobj, i, evenitem);
- } else {
- Py_INCREF(odditem);
- sts = PyTuple_SetItem(bitvecobj, i, odditem);
- }
- if (sts < 0)
- goto finally;
- }
- } else {
- bitvecobj = Py_None;
- Py_INCREF(Py_None);
- }
-
- res = Py_BuildValue("((iiiii)OO)", info.format,
- info.width, info.height,
- info.size, info.samplingrate,
- videodata, bitvecobj);
+ int bytes, i;
+ svCaptureInfo info;
+ void *bitvector = NULL;
+ PyObject *videodata = NULL;
+ PyObject *bitvecobj = NULL;
+ PyObject *res = NULL;
+ static PyObject *evenitem, *odditem;
+
+ if (!PyArg_Parse(args, "(iiiii)", &info.format,
+ &info.width, &info.height,
+ &info.size, &info.samplingrate))
+ return NULL;
+
+ switch (info.format) {
+ case SV_RGB8_FRAMES:
+ bitvector = malloc(SV_BITVEC_SIZE(info.size));
+ break;
+ case SV_YUV411_FRAMES_AND_BLANKING_BUFFER:
+ break;
+ default:
+ PyErr_SetString(SvError, "illegal format specified");
+ return NULL;
+ }
+
+ if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
+ goto finally;
+
+ /* XXX -- need to do something about the bitvector */
+ {
+ char* str = PyString_AsString(videodata);
+ if (!str)
+ goto finally;
+
+ if (svCaptureBurst(self->ob_svideo, &info, str, bitvector)) {
+ res = sv_error();
+ goto finally;
+ }
+ }
+
+ if (bitvector) {
+ if (evenitem == NULL) {
+ if (!(evenitem = PyInt_FromLong(0)))
+ goto finally;
+ }
+ if (odditem == NULL) {
+ if (!(odditem = PyInt_FromLong(1)))
+ goto finally;
+ }
+ if (!(bitvecobj = PyTuple_New(2 * info.size)))
+ goto finally;
+
+ for (i = 0; i < 2 * info.size; i++) {
+ int sts;
+
+ if (SV_GET_FIELD(bitvector, i) == SV_EVEN_FIELD) {
+ Py_INCREF(evenitem);
+ sts = PyTuple_SetItem(bitvecobj, i, evenitem);
+ } else {
+ Py_INCREF(odditem);
+ sts = PyTuple_SetItem(bitvecobj, i, odditem);
+ }
+ if (sts < 0)
+ goto finally;
+ }
+ } else {
+ bitvecobj = Py_None;
+ Py_INCREF(Py_None);
+ }
+
+ res = Py_BuildValue("((iiiii)OO)", info.format,
+ info.width, info.height,
+ info.size, info.samplingrate,
+ videodata, bitvecobj);
finally:
- if (bitvector)
- free(bitvector);
+ if (bitvector)
+ free(bitvector);
- Py_XDECREF(videodata);
- Py_XDECREF(bitvecobj);
- return res;
+ Py_XDECREF(videodata);
+ Py_XDECREF(bitvecobj);
+ return res;
}
static PyObject *
sv_CaptureOneFrame(svobject *self, PyObject *args)
{
- svCaptureInfo info;
- int format, width, height;
- int bytes;
- PyObject *videodata = NULL;
- PyObject *res = NULL;
- char *str;
-
- if (!PyArg_Parse(args, "(iii)", &format, &width, &height))
- return NULL;
-
- info.format = format;
- info.width = width;
- info.height = height;
- info.size = 0;
- info.samplingrate = 0;
- if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes))
- return sv_error();
-
- if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
- return NULL;
-
- str = PyString_AsString(videodata);
- if (!str)
- goto finally;
-
- if (svCaptureOneFrame(self->ob_svideo, format, &width, &height, str)) {
- res = sv_error();
- goto finally;
- }
-
- res = Py_BuildValue("(iiO)", width, height, videodata);
+ svCaptureInfo info;
+ int format, width, height;
+ int bytes;
+ PyObject *videodata = NULL;
+ PyObject *res = NULL;
+ char *str;
+
+ if (!PyArg_Parse(args, "(iii)", &format, &width, &height))
+ return NULL;
+
+ info.format = format;
+ info.width = width;
+ info.height = height;
+ info.size = 0;
+ info.samplingrate = 0;
+ if (svQueryCaptureBufferSize(self->ob_svideo, &info, &bytes))
+ return sv_error();
+
+ if (!(videodata = PyString_FromStringAndSize(NULL, bytes)))
+ return NULL;
+
+ str = PyString_AsString(videodata);
+ if (!str)
+ goto finally;
+
+ if (svCaptureOneFrame(self->ob_svideo, format, &width, &height, str)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ res = Py_BuildValue("(iiO)", width, height, videodata);
finally:
- Py_XDECREF(videodata);
- return res;
+ Py_XDECREF(videodata);
+ return res;
}
static PyObject *
sv_InitContinuousCapture(svobject *self, PyObject *args)
{
- svCaptureInfo info;
+ svCaptureInfo info;
- if (!PyArg_Parse(args, "(iiiii)", &info.format,
- &info.width, &info.height,
- &info.size, &info.samplingrate))
- return NULL;
+ if (!PyArg_Parse(args, "(iiiii)", &info.format,
+ &info.width, &info.height,
+ &info.size, &info.samplingrate))
+ return NULL;
- if (svInitContinuousCapture(self->ob_svideo, &info))
- return sv_error();
+ if (svInitContinuousCapture(self->ob_svideo, &info))
+ return sv_error();
- self->ob_info = info;
+ self->ob_info = info;
- return Py_BuildValue("(iiiii)", info.format, info.width, info.height,
- info.size, info.samplingrate);
+ return Py_BuildValue("(iiiii)", info.format, info.width, info.height,
+ info.size, info.samplingrate);
}
static PyObject *
sv_LoadMap(svobject *self, PyObject *args)
{
- PyObject *rgb;
- PyObject *res = NULL;
- rgb_tuple *mapp = NULL;
- int maptype;
- int i, j; /* indices */
-
- if (!PyArg_Parse(args, "(iO)", &maptype, &rgb))
- return NULL;
-
- if (!PyList_Check(rgb) || PyList_Size(rgb) != 256) {
- PyErr_BadArgument();
- return NULL;
- }
-
- if (!(mapp = PyMem_NEW(rgb_tuple, 256)))
- return PyErr_NoMemory();
-
- for (i = 0; i < 256; i++) {
- PyObject* v = PyList_GetItem(rgb, i);
- if (!v)
- goto finally;
-
- if (!PyTuple_Check(v) || PyTuple_Size(v) != 3) {
- PyErr_BadArgument();
- goto finally;
- }
- for (j = 0; j < 3; j++) {
- PyObject* cell = PyTuple_GetItem(v, j);
- if (!cell)
- goto finally;
-
- if (!PyInt_Check(cell)) {
- PyErr_BadArgument();
- goto finally;
- }
- switch (j) {
- case 0: mapp[i].red = PyInt_AsLong(cell); break;
- case 1: mapp[i].blue = PyInt_AsLong(cell); break;
- case 2: mapp[i].green = PyInt_AsLong(cell); break;
- }
- if (PyErr_Occurred())
- goto finally;
- }
- }
-
- if (svLoadMap(self->ob_svideo, maptype, mapp)) {
- res = sv_error();
- goto finally;
- }
-
- Py_INCREF(Py_None);
- res = Py_None;
+ PyObject *rgb;
+ PyObject *res = NULL;
+ rgb_tuple *mapp = NULL;
+ int maptype;
+ int i, j; /* indices */
+
+ if (!PyArg_Parse(args, "(iO)", &maptype, &rgb))
+ return NULL;
+
+ if (!PyList_Check(rgb) || PyList_Size(rgb) != 256) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ if (!(mapp = PyMem_NEW(rgb_tuple, 256)))
+ return PyErr_NoMemory();
+
+ for (i = 0; i < 256; i++) {
+ PyObject* v = PyList_GetItem(rgb, i);
+ if (!v)
+ goto finally;
+
+ if (!PyTuple_Check(v) || PyTuple_Size(v) != 3) {
+ PyErr_BadArgument();
+ goto finally;
+ }
+ for (j = 0; j < 3; j++) {
+ PyObject* cell = PyTuple_GetItem(v, j);
+ if (!cell)
+ goto finally;
+
+ if (!PyInt_Check(cell)) {
+ PyErr_BadArgument();
+ goto finally;
+ }
+ switch (j) {
+ case 0: mapp[i].red = PyInt_AsLong(cell); break;
+ case 1: mapp[i].blue = PyInt_AsLong(cell); break;
+ case 2: mapp[i].green = PyInt_AsLong(cell); break;
+ }
+ if (PyErr_Occurred())
+ goto finally;
+ }
+ }
+
+ if (svLoadMap(self->ob_svideo, maptype, mapp)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ Py_INCREF(Py_None);
+ res = Py_None;
finally:
- PyMem_DEL(mapp);
- return res;
+ PyMem_DEL(mapp);
+ return res;
}
-
+
static PyObject *
sv_CloseVideo(svobject *self, PyObject *args)
{
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- if (svCloseVideo(self->ob_svideo))
- return sv_error();
+ if (svCloseVideo(self->ob_svideo))
+ return sv_error();
- self->ob_svideo = NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ self->ob_svideo = NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
doParams(svobject *self, PyObject *args,
int (*func)(SV_nodeP, long *, int), int modified)
{
- PyObject *list;
- PyObject *res = NULL;
- long *PVbuffer = NULL;
- long length;
- int i;
-
- if (!PyArg_Parse(args, "O", &list))
- return NULL;
-
- if (!PyList_Check(list)) {
- PyErr_BadArgument();
- return NULL;
- }
-
- if ((length = PyList_Size(list)) < 0)
- return NULL;
-
- PVbuffer = PyMem_NEW(long, length);
- if (PVbuffer == NULL)
- return PyErr_NoMemory();
-
- for (i = 0; i < length; i++) {
- PyObject *v = PyList_GetItem(list, i);
- if (!v)
- goto finally;
-
- if (!PyInt_Check(v)) {
- PyErr_BadArgument();
- goto finally;
- }
- PVbuffer[i] = PyInt_AsLong(v);
- /* can't just test the return value, because what if the
- value was -1?!
- */
- if (PVbuffer[i] == -1 && PyErr_Occurred())
- goto finally;
- }
-
- if ((*func)(self->ob_svideo, PVbuffer, length)) {
- res = sv_error();
- goto finally;
- }
-
- if (modified) {
- for (i = 0; i < length; i++) {
- PyObject* v = PyInt_FromLong(PVbuffer[i]);
- if (!v || PyList_SetItem(list, i, v) < 0)
- goto finally;
- }
- }
-
- Py_INCREF(Py_None);
- res = Py_None;
+ PyObject *list;
+ PyObject *res = NULL;
+ long *PVbuffer = NULL;
+ long length;
+ int i;
+
+ if (!PyArg_Parse(args, "O", &list))
+ return NULL;
+
+ if (!PyList_Check(list)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ if ((length = PyList_Size(list)) < 0)
+ return NULL;
+
+ PVbuffer = PyMem_NEW(long, length);
+ if (PVbuffer == NULL)
+ return PyErr_NoMemory();
+
+ for (i = 0; i < length; i++) {
+ PyObject *v = PyList_GetItem(list, i);
+ if (!v)
+ goto finally;
+
+ if (!PyInt_Check(v)) {
+ PyErr_BadArgument();
+ goto finally;
+ }
+ PVbuffer[i] = PyInt_AsLong(v);
+ /* can't just test the return value, because what if the
+ value was -1?!
+ */
+ if (PVbuffer[i] == -1 && PyErr_Occurred())
+ goto finally;
+ }
+
+ if ((*func)(self->ob_svideo, PVbuffer, length)) {
+ res = sv_error();
+ goto finally;
+ }
+
+ if (modified) {
+ for (i = 0; i < length; i++) {
+ PyObject* v = PyInt_FromLong(PVbuffer[i]);
+ if (!v || PyList_SetItem(list, i, v) < 0)
+ goto finally;
+ }
+ }
+
+ Py_INCREF(Py_None);
+ res = Py_None;
finally:
- PyMem_DEL(PVbuffer);
- return res;
+ PyMem_DEL(PVbuffer);
+ return res;
}
static PyObject *
sv_GetParam(PyObject *self, PyObject *args)
{
- return doParams(self, args, svGetParam, 1);
+ return doParams(self, args, svGetParam, 1);
}
static PyObject *
sv_GetParamRange(PyObject *self, PyObject *args)
{
- return doParams(self, args, svGetParamRange, 1);
+ return doParams(self, args, svGetParamRange, 1);
}
static PyObject *
sv_SetParam(PyObject *self, PyObject *args)
{
- return doParams(self, args, svSetParam, 0);
+ return doParams(self, args, svSetParam, 0);
}
static PyMethodDef svideo_methods[] = {
- {"BindGLWindow", (PyCFunction)sv_BindGLWindow, METH_OLDARGS},
- {"EndContinuousCapture",(PyCFunction)sv_EndContinuousCapture, METH_OLDARGS},
- {"IsVideoDisplayed", (PyCFunction)sv_IsVideoDisplayed, METH_OLDARGS},
- {"OutputOffset", (PyCFunction)sv_OutputOffset, METH_OLDARGS},
- {"PutFrame", (PyCFunction)sv_PutFrame, METH_OLDARGS},
- {"QuerySize", (PyCFunction)sv_QuerySize, METH_OLDARGS},
- {"SetSize", (PyCFunction)sv_SetSize, METH_OLDARGS},
- {"SetStdDefaults", (PyCFunction)sv_SetStdDefaults, METH_OLDARGS},
- {"UseExclusive", (PyCFunction)sv_UseExclusive, METH_OLDARGS},
- {"WindowOffset", (PyCFunction)sv_WindowOffset, METH_OLDARGS},
- {"InitContinuousCapture",(PyCFunction)sv_InitContinuousCapture, METH_OLDARGS},
- {"CaptureBurst", (PyCFunction)sv_CaptureBurst, METH_OLDARGS},
- {"CaptureOneFrame", (PyCFunction)sv_CaptureOneFrame, METH_OLDARGS},
- {"GetCaptureData", (PyCFunction)sv_GetCaptureData, METH_OLDARGS},
- {"CloseVideo", (PyCFunction)sv_CloseVideo, METH_OLDARGS},
- {"LoadMap", (PyCFunction)sv_LoadMap, METH_OLDARGS},
- {"GetParam", (PyCFunction)sv_GetParam, METH_OLDARGS},
- {"GetParamRange", (PyCFunction)sv_GetParamRange, METH_OLDARGS},
- {"SetParam", (PyCFunction)sv_SetParam, METH_OLDARGS},
- {NULL, NULL} /* sentinel */
+ {"BindGLWindow", (PyCFunction)sv_BindGLWindow, METH_OLDARGS},
+ {"EndContinuousCapture",(PyCFunction)sv_EndContinuousCapture, METH_OLDARGS},
+ {"IsVideoDisplayed", (PyCFunction)sv_IsVideoDisplayed, METH_OLDARGS},
+ {"OutputOffset", (PyCFunction)sv_OutputOffset, METH_OLDARGS},
+ {"PutFrame", (PyCFunction)sv_PutFrame, METH_OLDARGS},
+ {"QuerySize", (PyCFunction)sv_QuerySize, METH_OLDARGS},
+ {"SetSize", (PyCFunction)sv_SetSize, METH_OLDARGS},
+ {"SetStdDefaults", (PyCFunction)sv_SetStdDefaults, METH_OLDARGS},
+ {"UseExclusive", (PyCFunction)sv_UseExclusive, METH_OLDARGS},
+ {"WindowOffset", (PyCFunction)sv_WindowOffset, METH_OLDARGS},
+ {"InitContinuousCapture",(PyCFunction)sv_InitContinuousCapture, METH_OLDARGS},
+ {"CaptureBurst", (PyCFunction)sv_CaptureBurst, METH_OLDARGS},
+ {"CaptureOneFrame", (PyCFunction)sv_CaptureOneFrame, METH_OLDARGS},
+ {"GetCaptureData", (PyCFunction)sv_GetCaptureData, METH_OLDARGS},
+ {"CloseVideo", (PyCFunction)sv_CloseVideo, METH_OLDARGS},
+ {"LoadMap", (PyCFunction)sv_LoadMap, METH_OLDARGS},
+ {"GetParam", (PyCFunction)sv_GetParam, METH_OLDARGS},
+ {"GetParamRange", (PyCFunction)sv_GetParamRange, METH_OLDARGS},
+ {"SetParam", (PyCFunction)sv_SetParam, METH_OLDARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
sv_conversion(PyObject *self, PyObject *args, void (*function)(),
int inputfactor, float factor)
{
- int invert, width, height, inputlength;
- char *input, *str;
- PyObject *output;
+ int invert, width, height, inputlength;
+ char *input, *str;
+ PyObject *output;
- if (!PyArg_Parse(args, "(is#ii)", &invert,
- &input, &inputlength, &width, &height))
- return NULL;
+ if (!PyArg_Parse(args, "(is#ii)", &invert,
+ &input, &inputlength, &width, &height))
+ return NULL;
- if (width * height * inputfactor > inputlength) {
- PyErr_SetString(SvError, "input buffer not long enough");
- return NULL;
- }
+ if (width * height * inputfactor > inputlength) {
+ PyErr_SetString(SvError, "input buffer not long enough");
+ return NULL;
+ }
- if (!(output = PyString_FromStringAndSize(NULL,
- (int)(width * height * factor))))
- return NULL;
+ if (!(output = PyString_FromStringAndSize(NULL,
+ (int)(width * height * factor))))
+ return NULL;
- str = PyString_AsString(output);
- if (!str) {
- Py_DECREF(output);
- return NULL;
- }
- (*function)(invert, input, str, width, height);
+ str = PyString_AsString(output);
+ if (!str) {
+ Py_DECREF(output);
+ return NULL;
+ }
+ (*function)(invert, input, str, width, height);
- return output;
+ return output;
}
static PyObject *
sv_InterleaveFields(PyObject *self, PyObject *args)
{
- return sv_conversion(self, args, svInterleaveFields, 1, 1.0);
+ return sv_conversion(self, args, svInterleaveFields, 1, 1.0);
}
static PyObject *
sv_RGB8toRGB32(PyObject *self, PyObject *args)
{
- return sv_conversion(self, args, svRGB8toRGB32, 1, (float) sizeof(long));
+ return sv_conversion(self, args, svRGB8toRGB32, 1, (float) sizeof(long));
}
static PyObject *
sv_YUVtoRGB(PyObject *self, PyObject *args)
{
- return sv_conversion(self, args, svYUVtoRGB, 2, (float) sizeof(long));
+ return sv_conversion(self, args, svYUVtoRGB, 2, (float) sizeof(long));
}
static void
svideo_dealloc(svobject *self)
{
- if (self->ob_svideo != NULL)
- (void) svCloseVideo(self->ob_svideo);
- PyObject_Del(self);
+ if (self->ob_svideo != NULL)
+ (void) svCloseVideo(self->ob_svideo);
+ PyObject_Del(self);
}
static PyObject *
svideo_getattr(svobject *self, char *name)
{
- return Py_FindMethod(svideo_methods, (PyObject *)self, name);
+ return Py_FindMethod(svideo_methods, (PyObject *)self, name);
}
PyTypeObject Svtype = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /*ob_size*/
- "sv.sv", /*tp_name*/
- sizeof(svobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)svideo_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)svideo_getattr, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /*ob_size*/
+ "sv.sv", /*tp_name*/
+ sizeof(svobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)svideo_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)svideo_getattr, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
};
static PyObject *
newsvobject(SV_nodeP svp)
{
- svobject *p;
+ svobject *p;
- p = PyObject_New(svobject, &Svtype);
- if (p == NULL)
- return NULL;
- p->ob_svideo = svp;
- p->ob_info.format = 0;
- p->ob_info.size = 0;
- p->ob_info.width = 0;
- p->ob_info.height = 0;
- p->ob_info.samplingrate = 0;
- return (PyObject *) p;
+ p = PyObject_New(svobject, &Svtype);
+ if (p == NULL)
+ return NULL;
+ p->ob_svideo = svp;
+ p->ob_info.format = 0;
+ p->ob_info.size = 0;
+ p->ob_info.width = 0;
+ p->ob_info.height = 0;
+ p->ob_info.samplingrate = 0;
+ return (PyObject *) p;
}
static PyObject *
sv_OpenVideo(PyObject *self, PyObject *args)
{
- SV_nodeP svp;
+ SV_nodeP svp;
- if (!PyArg_Parse(args, ""))
- return NULL;
+ if (!PyArg_Parse(args, ""))
+ return NULL;
- svp = svOpenVideo();
- if (svp == NULL)
- return sv_error();
+ svp = svOpenVideo();
+ if (svp == NULL)
+ return sv_error();
- return newsvobject(svp);
+ return newsvobject(svp);
}
static PyMethodDef sv_methods[] = {
- {"InterleaveFields", (PyCFunction)sv_InterleaveFields, METH_OLDARGS},
- {"RGB8toRGB32", (PyCFunction)sv_RGB8toRGB32, METH_OLDARGS},
- {"YUVtoRGB", (PyCFunction)sv_YUVtoRGB, METH_OLDARGS},
- {"OpenVideo", (PyCFunction)sv_OpenVideo, METH_OLDARGS},
- {NULL, NULL} /* Sentinel */
+ {"InterleaveFields", (PyCFunction)sv_InterleaveFields, METH_OLDARGS},
+ {"RGB8toRGB32", (PyCFunction)sv_RGB8toRGB32, METH_OLDARGS},
+ {"YUVtoRGB", (PyCFunction)sv_YUVtoRGB, METH_OLDARGS},
+ {"OpenVideo", (PyCFunction)sv_OpenVideo, METH_OLDARGS},
+ {NULL, NULL} /* Sentinel */
};
void
initsv(void)
{
- PyObject *m, *d;
-
- if (PyErr_WarnPy3k("the sv module has been removed in "
- "Python 3.0", 2) < 0)
- return;
+ PyObject *m, *d;
+
+ if (PyErr_WarnPy3k("the sv module has been removed in "
+ "Python 3.0", 2) < 0)
+ return;
- m = Py_InitModule("sv", sv_methods);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
+ m = Py_InitModule("sv", sv_methods);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
- SvError = PyErr_NewException("sv.error", NULL, NULL);
- if (SvError == NULL || PyDict_SetItemString(d, "error", SvError) != 0)
- return;
+ SvError = PyErr_NewException("sv.error", NULL, NULL);
+ if (SvError == NULL || PyDict_SetItemString(d, "error", SvError) != 0)
+ return;
}
diff --git a/Modules/symtablemodule.c b/Modules/symtablemodule.c
index 13ae337..60f9ba9 100644
--- a/Modules/symtablemodule.c
+++ b/Modules/symtablemodule.c
@@ -8,76 +8,76 @@
static PyObject *
symtable_symtable(PyObject *self, PyObject *args)
{
- struct symtable *st;
- PyObject *t;
+ struct symtable *st;
+ PyObject *t;
- char *str;
- char *filename;
- char *startstr;
- int start;
+ char *str;
+ char *filename;
+ char *startstr;
+ int start;
- if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename,
- &startstr))
- return NULL;
- if (strcmp(startstr, "exec") == 0)
- start = Py_file_input;
- else if (strcmp(startstr, "eval") == 0)
- start = Py_eval_input;
- else if (strcmp(startstr, "single") == 0)
- start = Py_single_input;
- else {
- PyErr_SetString(PyExc_ValueError,
- "symtable() arg 3 must be 'exec' or 'eval' or 'single'");
- return NULL;
- }
- st = Py_SymtableString(str, filename, start);
- if (st == NULL)
- return NULL;
- t = st->st_symbols;
- Py_INCREF(t);
- PyMem_Free((void *)st->st_future);
- PySymtable_Free(st);
- return t;
+ if (!PyArg_ParseTuple(args, "sss:symtable", &str, &filename,
+ &startstr))
+ return NULL;
+ if (strcmp(startstr, "exec") == 0)
+ start = Py_file_input;
+ else if (strcmp(startstr, "eval") == 0)
+ start = Py_eval_input;
+ else if (strcmp(startstr, "single") == 0)
+ start = Py_single_input;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "symtable() arg 3 must be 'exec' or 'eval' or 'single'");
+ return NULL;
+ }
+ st = Py_SymtableString(str, filename, start);
+ if (st == NULL)
+ return NULL;
+ t = st->st_symbols;
+ Py_INCREF(t);
+ PyMem_Free((void *)st->st_future);
+ PySymtable_Free(st);
+ return t;
}
static PyMethodDef symtable_methods[] = {
- {"symtable", symtable_symtable, METH_VARARGS,
- PyDoc_STR("Return symbol and scope dictionaries"
- " used internally by compiler.")},
- {NULL, NULL} /* sentinel */
+ {"symtable", symtable_symtable, METH_VARARGS,
+ PyDoc_STR("Return symbol and scope dictionaries"
+ " used internally by compiler.")},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
init_symtable(void)
{
- PyObject *m;
+ PyObject *m;
- m = Py_InitModule("_symtable", symtable_methods);
- if (m == NULL)
- return;
- PyModule_AddIntConstant(m, "USE", USE);
- PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL);
- PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL);
- PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM);
- PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE);
- PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS);
- PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT);
- PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND);
+ m = Py_InitModule("_symtable", symtable_methods);
+ if (m == NULL)
+ return;
+ PyModule_AddIntConstant(m, "USE", USE);
+ PyModule_AddIntConstant(m, "DEF_GLOBAL", DEF_GLOBAL);
+ PyModule_AddIntConstant(m, "DEF_LOCAL", DEF_LOCAL);
+ PyModule_AddIntConstant(m, "DEF_PARAM", DEF_PARAM);
+ PyModule_AddIntConstant(m, "DEF_FREE", DEF_FREE);
+ PyModule_AddIntConstant(m, "DEF_FREE_CLASS", DEF_FREE_CLASS);
+ PyModule_AddIntConstant(m, "DEF_IMPORT", DEF_IMPORT);
+ PyModule_AddIntConstant(m, "DEF_BOUND", DEF_BOUND);
- PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock);
- PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock);
- PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock);
+ PyModule_AddIntConstant(m, "TYPE_FUNCTION", FunctionBlock);
+ PyModule_AddIntConstant(m, "TYPE_CLASS", ClassBlock);
+ PyModule_AddIntConstant(m, "TYPE_MODULE", ModuleBlock);
- PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR);
- PyModule_AddIntConstant(m, "OPT_EXEC", OPT_EXEC);
- PyModule_AddIntConstant(m, "OPT_BARE_EXEC", OPT_BARE_EXEC);
+ PyModule_AddIntConstant(m, "OPT_IMPORT_STAR", OPT_IMPORT_STAR);
+ PyModule_AddIntConstant(m, "OPT_EXEC", OPT_EXEC);
+ PyModule_AddIntConstant(m, "OPT_BARE_EXEC", OPT_BARE_EXEC);
- PyModule_AddIntConstant(m, "LOCAL", LOCAL);
- PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT);
- PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT);
- PyModule_AddIntConstant(m, "FREE", FREE);
- PyModule_AddIntConstant(m, "CELL", CELL);
+ PyModule_AddIntConstant(m, "LOCAL", LOCAL);
+ PyModule_AddIntConstant(m, "GLOBAL_EXPLICIT", GLOBAL_EXPLICIT);
+ PyModule_AddIntConstant(m, "GLOBAL_IMPLICIT", GLOBAL_IMPLICIT);
+ PyModule_AddIntConstant(m, "FREE", FREE);
+ PyModule_AddIntConstant(m, "CELL", CELL);
- PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFF);
- PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK);
+ PyModule_AddIntConstant(m, "SCOPE_OFF", SCOPE_OFF);
+ PyModule_AddIntConstant(m, "SCOPE_MASK", SCOPE_MASK);
}
diff --git a/Modules/syslogmodule.c b/Modules/syslogmodule.c
index 9a44d44..37eaebc 100644
--- a/Modules/syslogmodule.c
+++ b/Modules/syslogmodule.c
@@ -4,20 +4,20 @@ Cathedral City, California Republic, United States of America.
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 name of Lance Ellinghouse
-not be used in advertising or publicity pertaining to distribution
+not be used in advertising or publicity pertaining to distribution
of the software without specific, written prior permission.
LANCE ELLINGHOUSE DISCLAIMS ALL WARRANTIES WITH REGARD TO
THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
-FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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
+FITNESS, IN NO EVENT SHALL LANCE ELLINGHOUSE 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.
******************************************************************/
@@ -55,184 +55,184 @@ Revision history:
#include <syslog.h>
/* only one instance, only one syslog, so globals should be ok */
-static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */
+static PyObject *S_ident_o = NULL; /* identifier, held by openlog() */
static char S_log_open = 0;
static PyObject *
syslog_get_argv(void)
{
- /* Figure out what to use for as the program "ident" for openlog().
- * This swallows exceptions and continues rather than failing out,
- * because the syslog module can still be used because openlog(3)
- * is optional.
- */
-
- Py_ssize_t argv_len;
- PyObject *scriptobj;
- char *atslash;
- PyObject *argv = PySys_GetObject("argv");
-
- if (argv == NULL) {
- return(NULL);
- }
-
- argv_len = PyList_Size(argv);
- if (argv_len == -1) {
- PyErr_Clear();
- return(NULL);
- }
- if (argv_len == 0) {
- return(NULL);
- }
-
- scriptobj = PyList_GetItem(argv, 0);
- if (!PyString_Check(scriptobj)) {
- return(NULL);
- }
- if (PyString_GET_SIZE(scriptobj) == 0) {
- return(NULL);
- }
-
- atslash = strrchr(PyString_AsString(scriptobj), SEP);
- if (atslash) {
- return(PyString_FromString(atslash + 1));
- } else {
- Py_INCREF(scriptobj);
- return(scriptobj);
- }
-
- return(NULL);
+ /* Figure out what to use for as the program "ident" for openlog().
+ * This swallows exceptions and continues rather than failing out,
+ * because the syslog module can still be used because openlog(3)
+ * is optional.
+ */
+
+ Py_ssize_t argv_len;
+ PyObject *scriptobj;
+ char *atslash;
+ PyObject *argv = PySys_GetObject("argv");
+
+ if (argv == NULL) {
+ return(NULL);
+ }
+
+ argv_len = PyList_Size(argv);
+ if (argv_len == -1) {
+ PyErr_Clear();
+ return(NULL);
+ }
+ if (argv_len == 0) {
+ return(NULL);
+ }
+
+ scriptobj = PyList_GetItem(argv, 0);
+ if (!PyString_Check(scriptobj)) {
+ return(NULL);
+ }
+ if (PyString_GET_SIZE(scriptobj) == 0) {
+ return(NULL);
+ }
+
+ atslash = strrchr(PyString_AsString(scriptobj), SEP);
+ if (atslash) {
+ return(PyString_FromString(atslash + 1));
+ } else {
+ Py_INCREF(scriptobj);
+ return(scriptobj);
+ }
+
+ return(NULL);
}
-static PyObject *
+static PyObject *
syslog_openlog(PyObject * self, PyObject * args, PyObject *kwds)
{
- long logopt = 0;
- long facility = LOG_USER;
- PyObject *new_S_ident_o = NULL;
- static char *keywords[] = {"ident", "logoption", "facility", 0};
+ long logopt = 0;
+ long facility = LOG_USER;
+ PyObject *new_S_ident_o = NULL;
+ static char *keywords[] = {"ident", "logoption", "facility", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds,
- "|Sll:openlog", keywords, &new_S_ident_o, &logopt, &facility))
- return NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds,
+ "|Sll:openlog", keywords, &new_S_ident_o, &logopt, &facility))
+ return NULL;
- if (new_S_ident_o) { Py_INCREF(new_S_ident_o); }
+ if (new_S_ident_o) { Py_INCREF(new_S_ident_o); }
- /* get sys.argv[0] or NULL if we can't for some reason */
- if (!new_S_ident_o) {
- new_S_ident_o = syslog_get_argv();
- }
+ /* get sys.argv[0] or NULL if we can't for some reason */
+ if (!new_S_ident_o) {
+ new_S_ident_o = syslog_get_argv();
+ }
- Py_XDECREF(S_ident_o);
- S_ident_o = new_S_ident_o;
+ Py_XDECREF(S_ident_o);
+ S_ident_o = new_S_ident_o;
- /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not
- * make a copy, and syslog(3) later uses it. We can't garbagecollect it
- * If NULL, just let openlog figure it out (probably using C argv[0]).
- */
+ /* At this point, S_ident_o should be INCREF()ed. openlog(3) does not
+ * make a copy, and syslog(3) later uses it. We can't garbagecollect it
+ * If NULL, just let openlog figure it out (probably using C argv[0]).
+ */
- openlog(S_ident_o ? PyString_AsString(S_ident_o) : NULL, logopt, facility);
- S_log_open = 1;
+ openlog(S_ident_o ? PyString_AsString(S_ident_o) : NULL, logopt, facility);
+ S_log_open = 1;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_syslog(PyObject * self, PyObject * args)
{
- char *message;
- int priority = LOG_INFO;
-
- if (!PyArg_ParseTuple(args, "is;[priority,] message string",
- &priority, &message)) {
- PyErr_Clear();
- if (!PyArg_ParseTuple(args, "s;[priority,] message string",
- &message))
- return NULL;
- }
-
- /* if log is not opened, open it now */
- if (!S_log_open) {
- PyObject *openargs;
-
- /* Continue even if PyTuple_New fails, because openlog(3) is optional.
- * So, we can still do loggin in the unlikely event things are so hosed
- * that we can't do this tuple.
- */
- if ((openargs = PyTuple_New(0))) {
- PyObject *openlog_ret = syslog_openlog(self, openargs, NULL);
- Py_XDECREF(openlog_ret);
- Py_DECREF(openargs);
- }
- }
-
- Py_BEGIN_ALLOW_THREADS;
- syslog(priority, "%s", message);
- Py_END_ALLOW_THREADS;
- Py_INCREF(Py_None);
- return Py_None;
+ char *message;
+ int priority = LOG_INFO;
+
+ if (!PyArg_ParseTuple(args, "is;[priority,] message string",
+ &priority, &message)) {
+ PyErr_Clear();
+ if (!PyArg_ParseTuple(args, "s;[priority,] message string",
+ &message))
+ return NULL;
+ }
+
+ /* if log is not opened, open it now */
+ if (!S_log_open) {
+ PyObject *openargs;
+
+ /* Continue even if PyTuple_New fails, because openlog(3) is optional.
+ * So, we can still do loggin in the unlikely event things are so hosed
+ * that we can't do this tuple.
+ */
+ if ((openargs = PyTuple_New(0))) {
+ PyObject *openlog_ret = syslog_openlog(self, openargs, NULL);
+ Py_XDECREF(openlog_ret);
+ Py_DECREF(openargs);
+ }
+ }
+
+ Py_BEGIN_ALLOW_THREADS;
+ syslog(priority, "%s", message);
+ Py_END_ALLOW_THREADS;
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_closelog(PyObject *self, PyObject *unused)
{
- if (S_log_open) {
- closelog();
- Py_XDECREF(S_ident_o);
- S_ident_o = NULL;
- S_log_open = 0;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (S_log_open) {
+ closelog();
+ Py_XDECREF(S_ident_o);
+ S_ident_o = NULL;
+ S_log_open = 0;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
-static PyObject *
+static PyObject *
syslog_setlogmask(PyObject *self, PyObject *args)
{
- long maskpri, omaskpri;
+ long maskpri, omaskpri;
- if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
- return NULL;
- omaskpri = setlogmask(maskpri);
- return PyInt_FromLong(omaskpri);
+ if (!PyArg_ParseTuple(args, "l;mask for priority", &maskpri))
+ return NULL;
+ omaskpri = setlogmask(maskpri);
+ return PyInt_FromLong(omaskpri);
}
-static PyObject *
+static PyObject *
syslog_log_mask(PyObject *self, PyObject *args)
{
- long mask;
- long pri;
- if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri))
- return NULL;
- mask = LOG_MASK(pri);
- return PyInt_FromLong(mask);
+ long mask;
+ long pri;
+ if (!PyArg_ParseTuple(args, "l:LOG_MASK", &pri))
+ return NULL;
+ mask = LOG_MASK(pri);
+ return PyInt_FromLong(mask);
}
-static PyObject *
+static PyObject *
syslog_log_upto(PyObject *self, PyObject *args)
{
- long mask;
- long pri;
- if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri))
- return NULL;
- mask = LOG_UPTO(pri);
- return PyInt_FromLong(mask);
+ long mask;
+ long pri;
+ if (!PyArg_ParseTuple(args, "l:LOG_UPTO", &pri))
+ return NULL;
+ mask = LOG_UPTO(pri);
+ return PyInt_FromLong(mask);
}
/* List of functions defined in the module */
static PyMethodDef syslog_methods[] = {
- {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS},
- {"closelog", syslog_closelog, METH_NOARGS},
- {"syslog", syslog_syslog, METH_VARARGS},
- {"setlogmask", syslog_setlogmask, METH_VARARGS},
- {"LOG_MASK", syslog_log_mask, METH_VARARGS},
- {"LOG_UPTO", syslog_log_upto, METH_VARARGS},
- {NULL, NULL, 0}
+ {"openlog", (PyCFunction) syslog_openlog, METH_VARARGS | METH_KEYWORDS},
+ {"closelog", syslog_closelog, METH_NOARGS},
+ {"syslog", syslog_syslog, METH_VARARGS},
+ {"setlogmask", syslog_setlogmask, METH_VARARGS},
+ {"LOG_MASK", syslog_log_mask, METH_VARARGS},
+ {"LOG_UPTO", syslog_log_upto, METH_VARARGS},
+ {NULL, NULL, 0}
};
/* Initialization function for the module */
@@ -240,67 +240,67 @@ static PyMethodDef syslog_methods[] = {
PyMODINIT_FUNC
initsyslog(void)
{
- PyObject *m;
-
- /* Create the module and add the functions */
- m = Py_InitModule("syslog", syslog_methods);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
-
- /* Priorities */
- PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG);
- PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT);
- PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT);
- PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR);
- PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING);
- PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE);
- PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO);
- PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG);
-
- /* openlog() option flags */
- PyModule_AddIntConstant(m, "LOG_PID", LOG_PID);
- PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS);
- PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY);
+ PyObject *m;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule("syslog", syslog_methods);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+
+ /* Priorities */
+ PyModule_AddIntConstant(m, "LOG_EMERG", LOG_EMERG);
+ PyModule_AddIntConstant(m, "LOG_ALERT", LOG_ALERT);
+ PyModule_AddIntConstant(m, "LOG_CRIT", LOG_CRIT);
+ PyModule_AddIntConstant(m, "LOG_ERR", LOG_ERR);
+ PyModule_AddIntConstant(m, "LOG_WARNING", LOG_WARNING);
+ PyModule_AddIntConstant(m, "LOG_NOTICE", LOG_NOTICE);
+ PyModule_AddIntConstant(m, "LOG_INFO", LOG_INFO);
+ PyModule_AddIntConstant(m, "LOG_DEBUG", LOG_DEBUG);
+
+ /* openlog() option flags */
+ PyModule_AddIntConstant(m, "LOG_PID", LOG_PID);
+ PyModule_AddIntConstant(m, "LOG_CONS", LOG_CONS);
+ PyModule_AddIntConstant(m, "LOG_NDELAY", LOG_NDELAY);
#ifdef LOG_NOWAIT
- PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT);
+ PyModule_AddIntConstant(m, "LOG_NOWAIT", LOG_NOWAIT);
#endif
#ifdef LOG_PERROR
- PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR);
+ PyModule_AddIntConstant(m, "LOG_PERROR", LOG_PERROR);
#endif
- /* Facilities */
- PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN);
- PyModule_AddIntConstant(m, "LOG_USER", LOG_USER);
- PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL);
- PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON);
- PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH);
- PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR);
- PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0);
- PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1);
- PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2);
- PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3);
- PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4);
- PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5);
- PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6);
- PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7);
+ /* Facilities */
+ PyModule_AddIntConstant(m, "LOG_KERN", LOG_KERN);
+ PyModule_AddIntConstant(m, "LOG_USER", LOG_USER);
+ PyModule_AddIntConstant(m, "LOG_MAIL", LOG_MAIL);
+ PyModule_AddIntConstant(m, "LOG_DAEMON", LOG_DAEMON);
+ PyModule_AddIntConstant(m, "LOG_AUTH", LOG_AUTH);
+ PyModule_AddIntConstant(m, "LOG_LPR", LOG_LPR);
+ PyModule_AddIntConstant(m, "LOG_LOCAL0", LOG_LOCAL0);
+ PyModule_AddIntConstant(m, "LOG_LOCAL1", LOG_LOCAL1);
+ PyModule_AddIntConstant(m, "LOG_LOCAL2", LOG_LOCAL2);
+ PyModule_AddIntConstant(m, "LOG_LOCAL3", LOG_LOCAL3);
+ PyModule_AddIntConstant(m, "LOG_LOCAL4", LOG_LOCAL4);
+ PyModule_AddIntConstant(m, "LOG_LOCAL5", LOG_LOCAL5);
+ PyModule_AddIntConstant(m, "LOG_LOCAL6", LOG_LOCAL6);
+ PyModule_AddIntConstant(m, "LOG_LOCAL7", LOG_LOCAL7);
#ifndef LOG_SYSLOG
-#define LOG_SYSLOG LOG_DAEMON
+#define LOG_SYSLOG LOG_DAEMON
#endif
#ifndef LOG_NEWS
-#define LOG_NEWS LOG_MAIL
+#define LOG_NEWS LOG_MAIL
#endif
#ifndef LOG_UUCP
-#define LOG_UUCP LOG_MAIL
+#define LOG_UUCP LOG_MAIL
#endif
#ifndef LOG_CRON
-#define LOG_CRON LOG_DAEMON
+#define LOG_CRON LOG_DAEMON
#endif
- PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG);
- PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON);
- PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP);
- PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS);
+ PyModule_AddIntConstant(m, "LOG_SYSLOG", LOG_SYSLOG);
+ PyModule_AddIntConstant(m, "LOG_CRON", LOG_CRON);
+ PyModule_AddIntConstant(m, "LOG_UUCP", LOG_UUCP);
+ PyModule_AddIntConstant(m, "LOG_NEWS", LOG_NEWS);
}
diff --git a/Modules/termios.c b/Modules/termios.c
index e2872fb..57f30dc 100644
--- a/Modules/termios.c
+++ b/Modules/termios.c
@@ -44,14 +44,14 @@ static PyObject *TermiosError;
static int fdconv(PyObject* obj, void* p)
{
- int fd;
-
- fd = PyObject_AsFileDescriptor(obj);
- if (fd >= 0) {
- *(int*)p = fd;
- return 1;
- }
- return 0;
+ int fd;
+
+ fd = PyObject_AsFileDescriptor(obj);
+ if (fd >= 0) {
+ *(int*)p = fd;
+ return 1;
+ }
+ return 0;
}
PyDoc_STRVAR(termios_tcgetattr__doc__,
@@ -68,67 +68,67 @@ in this module.");
static PyObject *
termios_tcgetattr(PyObject *self, PyObject *args)
{
- int fd;
- struct termios mode;
- PyObject *cc;
- speed_t ispeed, ospeed;
- PyObject *v;
- int i;
- char ch;
-
- if (!PyArg_ParseTuple(args, "O&:tcgetattr",
- fdconv, (void*)&fd))
- return NULL;
-
- if (tcgetattr(fd, &mode) == -1)
- return PyErr_SetFromErrno(TermiosError);
-
- ispeed = cfgetispeed(&mode);
- ospeed = cfgetospeed(&mode);
-
- cc = PyList_New(NCCS);
- if (cc == NULL)
- return NULL;
- for (i = 0; i < NCCS; i++) {
- ch = (char)mode.c_cc[i];
- v = PyString_FromStringAndSize(&ch, 1);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, i, v);
- }
-
- /* Convert the MIN and TIME slots to integer. On some systems, the
- MIN and TIME slots are the same as the EOF and EOL slots. So we
- only do this in noncanonical input mode. */
- if ((mode.c_lflag & ICANON) == 0) {
- v = PyInt_FromLong((long)mode.c_cc[VMIN]);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, VMIN, v);
- v = PyInt_FromLong((long)mode.c_cc[VTIME]);
- if (v == NULL)
- goto err;
- PyList_SetItem(cc, VTIME, v);
- }
-
- if (!(v = PyList_New(7)))
- goto err;
-
- PyList_SetItem(v, 0, PyInt_FromLong((long)mode.c_iflag));
- PyList_SetItem(v, 1, PyInt_FromLong((long)mode.c_oflag));
- PyList_SetItem(v, 2, PyInt_FromLong((long)mode.c_cflag));
- PyList_SetItem(v, 3, PyInt_FromLong((long)mode.c_lflag));
- PyList_SetItem(v, 4, PyInt_FromLong((long)ispeed));
- PyList_SetItem(v, 5, PyInt_FromLong((long)ospeed));
- PyList_SetItem(v, 6, cc);
- if (PyErr_Occurred()){
- Py_DECREF(v);
- goto err;
- }
- return v;
+ int fd;
+ struct termios mode;
+ PyObject *cc;
+ speed_t ispeed, ospeed;
+ PyObject *v;
+ int i;
+ char ch;
+
+ if (!PyArg_ParseTuple(args, "O&:tcgetattr",
+ fdconv, (void*)&fd))
+ return NULL;
+
+ if (tcgetattr(fd, &mode) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+
+ ispeed = cfgetispeed(&mode);
+ ospeed = cfgetospeed(&mode);
+
+ cc = PyList_New(NCCS);
+ if (cc == NULL)
+ return NULL;
+ for (i = 0; i < NCCS; i++) {
+ ch = (char)mode.c_cc[i];
+ v = PyString_FromStringAndSize(&ch, 1);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, i, v);
+ }
+
+ /* Convert the MIN and TIME slots to integer. On some systems, the
+ MIN and TIME slots are the same as the EOF and EOL slots. So we
+ only do this in noncanonical input mode. */
+ if ((mode.c_lflag & ICANON) == 0) {
+ v = PyInt_FromLong((long)mode.c_cc[VMIN]);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, VMIN, v);
+ v = PyInt_FromLong((long)mode.c_cc[VTIME]);
+ if (v == NULL)
+ goto err;
+ PyList_SetItem(cc, VTIME, v);
+ }
+
+ if (!(v = PyList_New(7)))
+ goto err;
+
+ PyList_SetItem(v, 0, PyInt_FromLong((long)mode.c_iflag));
+ PyList_SetItem(v, 1, PyInt_FromLong((long)mode.c_oflag));
+ PyList_SetItem(v, 2, PyInt_FromLong((long)mode.c_cflag));
+ PyList_SetItem(v, 3, PyInt_FromLong((long)mode.c_lflag));
+ PyList_SetItem(v, 4, PyInt_FromLong((long)ispeed));
+ PyList_SetItem(v, 5, PyInt_FromLong((long)ospeed));
+ PyList_SetItem(v, 6, cc);
+ if (PyErr_Occurred()){
+ Py_DECREF(v);
+ goto err;
+ }
+ return v;
err:
- Py_DECREF(cc);
- return NULL;
+ Py_DECREF(cc);
+ return NULL;
}
PyDoc_STRVAR(termios_tcsetattr__doc__,
@@ -145,64 +145,64 @@ queued output and discarding all queued input. ");
static PyObject *
termios_tcsetattr(PyObject *self, PyObject *args)
{
- int fd, when;
- struct termios mode;
- speed_t ispeed, ospeed;
- PyObject *term, *cc, *v;
- int i;
-
- if (!PyArg_ParseTuple(args, "O&iO:tcsetattr",
- fdconv, &fd, &when, &term))
- return NULL;
- if (!PyList_Check(term) || PyList_Size(term) != 7) {
- PyErr_SetString(PyExc_TypeError,
- "tcsetattr, arg 3: must be 7 element list");
- return NULL;
- }
-
- /* Get the old mode, in case there are any hidden fields... */
- if (tcgetattr(fd, &mode) == -1)
- return PyErr_SetFromErrno(TermiosError);
- mode.c_iflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 0));
- mode.c_oflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 1));
- mode.c_cflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 2));
- mode.c_lflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 3));
- ispeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 4));
- ospeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 5));
- cc = PyList_GetItem(term, 6);
- if (PyErr_Occurred())
- return NULL;
-
- if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) {
- PyErr_Format(PyExc_TypeError,
- "tcsetattr: attributes[6] must be %d element list",
- NCCS);
- return NULL;
- }
-
- for (i = 0; i < NCCS; i++) {
- v = PyList_GetItem(cc, i);
-
- if (PyString_Check(v) && PyString_Size(v) == 1)
- mode.c_cc[i] = (cc_t) * PyString_AsString(v);
- else if (PyInt_Check(v))
- mode.c_cc[i] = (cc_t) PyInt_AsLong(v);
- else {
- PyErr_SetString(PyExc_TypeError,
+ int fd, when;
+ struct termios mode;
+ speed_t ispeed, ospeed;
+ PyObject *term, *cc, *v;
+ int i;
+
+ if (!PyArg_ParseTuple(args, "O&iO:tcsetattr",
+ fdconv, &fd, &when, &term))
+ return NULL;
+ if (!PyList_Check(term) || PyList_Size(term) != 7) {
+ PyErr_SetString(PyExc_TypeError,
+ "tcsetattr, arg 3: must be 7 element list");
+ return NULL;
+ }
+
+ /* Get the old mode, in case there are any hidden fields... */
+ if (tcgetattr(fd, &mode) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+ mode.c_iflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 0));
+ mode.c_oflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 1));
+ mode.c_cflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 2));
+ mode.c_lflag = (tcflag_t) PyInt_AsLong(PyList_GetItem(term, 3));
+ ispeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 4));
+ ospeed = (speed_t) PyInt_AsLong(PyList_GetItem(term, 5));
+ cc = PyList_GetItem(term, 6);
+ if (PyErr_Occurred())
+ return NULL;
+
+ if (!PyList_Check(cc) || PyList_Size(cc) != NCCS) {
+ PyErr_Format(PyExc_TypeError,
+ "tcsetattr: attributes[6] must be %d element list",
+ NCCS);
+ return NULL;
+ }
+
+ for (i = 0; i < NCCS; i++) {
+ v = PyList_GetItem(cc, i);
+
+ if (PyString_Check(v) && PyString_Size(v) == 1)
+ mode.c_cc[i] = (cc_t) * PyString_AsString(v);
+ else if (PyInt_Check(v))
+ mode.c_cc[i] = (cc_t) PyInt_AsLong(v);
+ else {
+ PyErr_SetString(PyExc_TypeError,
"tcsetattr: elements of attributes must be characters or integers");
- return NULL;
- }
- }
-
- if (cfsetispeed(&mode, (speed_t) ispeed) == -1)
- return PyErr_SetFromErrno(TermiosError);
- if (cfsetospeed(&mode, (speed_t) ospeed) == -1)
- return PyErr_SetFromErrno(TermiosError);
- if (tcsetattr(fd, when, &mode) == -1)
- return PyErr_SetFromErrno(TermiosError);
-
- Py_INCREF(Py_None);
- return Py_None;
+ return NULL;
+ }
+ }
+
+ if (cfsetispeed(&mode, (speed_t) ispeed) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+ if (cfsetospeed(&mode, (speed_t) ospeed) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+ if (tcsetattr(fd, when, &mode) == -1)
+ return PyErr_SetFromErrno(TermiosError);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcsendbreak__doc__,
@@ -215,16 +215,16 @@ has a system dependent meaning.");
static PyObject *
termios_tcsendbreak(PyObject *self, PyObject *args)
{
- int fd, duration;
+ int fd, duration;
- if (!PyArg_ParseTuple(args, "O&i:tcsendbreak",
- fdconv, &fd, &duration))
- return NULL;
- if (tcsendbreak(fd, duration) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&i:tcsendbreak",
+ fdconv, &fd, &duration))
+ return NULL;
+ if (tcsendbreak(fd, duration) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcdrain__doc__,
@@ -235,16 +235,16 @@ Wait until all output written to file descriptor fd has been transmitted.");
static PyObject *
termios_tcdrain(PyObject *self, PyObject *args)
{
- int fd;
+ int fd;
- if (!PyArg_ParseTuple(args, "O&:tcdrain",
- fdconv, &fd))
- return NULL;
- if (tcdrain(fd) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&:tcdrain",
+ fdconv, &fd))
+ return NULL;
+ if (tcdrain(fd) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcflush__doc__,
@@ -258,16 +258,16 @@ both queues. ");
static PyObject *
termios_tcflush(PyObject *self, PyObject *args)
{
- int fd, queue;
+ int fd, queue;
- if (!PyArg_ParseTuple(args, "O&i:tcflush",
- fdconv, &fd, &queue))
- return NULL;
- if (tcflush(fd, queue) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&i:tcflush",
+ fdconv, &fd, &queue))
+ return NULL;
+ if (tcflush(fd, queue) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(termios_tcflow__doc__,
@@ -281,33 +281,33 @@ or termios.TCION to restart input.");
static PyObject *
termios_tcflow(PyObject *self, PyObject *args)
{
- int fd, action;
+ int fd, action;
- if (!PyArg_ParseTuple(args, "O&i:tcflow",
- fdconv, &fd, &action))
- return NULL;
- if (tcflow(fd, action) == -1)
- return PyErr_SetFromErrno(TermiosError);
+ if (!PyArg_ParseTuple(args, "O&i:tcflow",
+ fdconv, &fd, &action))
+ return NULL;
+ if (tcflow(fd, action) == -1)
+ return PyErr_SetFromErrno(TermiosError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef termios_methods[] =
{
- {"tcgetattr", termios_tcgetattr,
- METH_VARARGS, termios_tcgetattr__doc__},
- {"tcsetattr", termios_tcsetattr,
- METH_VARARGS, termios_tcsetattr__doc__},
- {"tcsendbreak", termios_tcsendbreak,
- METH_VARARGS, termios_tcsendbreak__doc__},
- {"tcdrain", termios_tcdrain,
- METH_VARARGS, termios_tcdrain__doc__},
- {"tcflush", termios_tcflush,
- METH_VARARGS, termios_tcflush__doc__},
- {"tcflow", termios_tcflow,
- METH_VARARGS, termios_tcflow__doc__},
- {NULL, NULL}
+ {"tcgetattr", termios_tcgetattr,
+ METH_VARARGS, termios_tcgetattr__doc__},
+ {"tcsetattr", termios_tcsetattr,
+ METH_VARARGS, termios_tcsetattr__doc__},
+ {"tcsendbreak", termios_tcsendbreak,
+ METH_VARARGS, termios_tcsendbreak__doc__},
+ {"tcdrain", termios_tcdrain,
+ METH_VARARGS, termios_tcdrain__doc__},
+ {"tcflush", termios_tcflush,
+ METH_VARARGS, termios_tcflush__doc__},
+ {"tcflow", termios_tcflow,
+ METH_VARARGS, termios_tcflow__doc__},
+ {NULL, NULL}
};
@@ -320,610 +320,610 @@ static PyMethodDef termios_methods[] =
#endif
static struct constant {
- char *name;
- long value;
+ char *name;
+ long value;
} termios_constants[] = {
- /* cfgetospeed(), cfsetospeed() constants */
- {"B0", B0},
- {"B50", B50},
- {"B75", B75},
- {"B110", B110},
- {"B134", B134},
- {"B150", B150},
- {"B200", B200},
- {"B300", B300},
- {"B600", B600},
- {"B1200", B1200},
- {"B1800", B1800},
- {"B2400", B2400},
- {"B4800", B4800},
- {"B9600", B9600},
- {"B19200", B19200},
- {"B38400", B38400},
+ /* cfgetospeed(), cfsetospeed() constants */
+ {"B0", B0},
+ {"B50", B50},
+ {"B75", B75},
+ {"B110", B110},
+ {"B134", B134},
+ {"B150", B150},
+ {"B200", B200},
+ {"B300", B300},
+ {"B600", B600},
+ {"B1200", B1200},
+ {"B1800", B1800},
+ {"B2400", B2400},
+ {"B4800", B4800},
+ {"B9600", B9600},
+ {"B19200", B19200},
+ {"B38400", B38400},
#ifdef B57600
- {"B57600", B57600},
+ {"B57600", B57600},
#endif
#ifdef B115200
- {"B115200", B115200},
+ {"B115200", B115200},
#endif
#ifdef B230400
- {"B230400", B230400},
+ {"B230400", B230400},
#endif
#ifdef CBAUDEX
- {"CBAUDEX", CBAUDEX},
+ {"CBAUDEX", CBAUDEX},
#endif
- /* tcsetattr() constants */
- {"TCSANOW", TCSANOW},
- {"TCSADRAIN", TCSADRAIN},
- {"TCSAFLUSH", TCSAFLUSH},
+ /* tcsetattr() constants */
+ {"TCSANOW", TCSANOW},
+ {"TCSADRAIN", TCSADRAIN},
+ {"TCSAFLUSH", TCSAFLUSH},
#ifdef TCSASOFT
- {"TCSASOFT", TCSASOFT},
-#endif
-
- /* tcflush() constants */
- {"TCIFLUSH", TCIFLUSH},
- {"TCOFLUSH", TCOFLUSH},
- {"TCIOFLUSH", TCIOFLUSH},
-
- /* tcflow() constants */
- {"TCOOFF", TCOOFF},
- {"TCOON", TCOON},
- {"TCIOFF", TCIOFF},
- {"TCION", TCION},
-
- /* struct termios.c_iflag constants */
- {"IGNBRK", IGNBRK},
- {"BRKINT", BRKINT},
- {"IGNPAR", IGNPAR},
- {"PARMRK", PARMRK},
- {"INPCK", INPCK},
- {"ISTRIP", ISTRIP},
- {"INLCR", INLCR},
- {"IGNCR", IGNCR},
- {"ICRNL", ICRNL},
+ {"TCSASOFT", TCSASOFT},
+#endif
+
+ /* tcflush() constants */
+ {"TCIFLUSH", TCIFLUSH},
+ {"TCOFLUSH", TCOFLUSH},
+ {"TCIOFLUSH", TCIOFLUSH},
+
+ /* tcflow() constants */
+ {"TCOOFF", TCOOFF},
+ {"TCOON", TCOON},
+ {"TCIOFF", TCIOFF},
+ {"TCION", TCION},
+
+ /* struct termios.c_iflag constants */
+ {"IGNBRK", IGNBRK},
+ {"BRKINT", BRKINT},
+ {"IGNPAR", IGNPAR},
+ {"PARMRK", PARMRK},
+ {"INPCK", INPCK},
+ {"ISTRIP", ISTRIP},
+ {"INLCR", INLCR},
+ {"IGNCR", IGNCR},
+ {"ICRNL", ICRNL},
#ifdef IUCLC
- {"IUCLC", IUCLC},
+ {"IUCLC", IUCLC},
#endif
- {"IXON", IXON},
- {"IXANY", IXANY},
- {"IXOFF", IXOFF},
+ {"IXON", IXON},
+ {"IXANY", IXANY},
+ {"IXOFF", IXOFF},
#ifdef IMAXBEL
- {"IMAXBEL", IMAXBEL},
+ {"IMAXBEL", IMAXBEL},
#endif
- /* struct termios.c_oflag constants */
- {"OPOST", OPOST},
+ /* struct termios.c_oflag constants */
+ {"OPOST", OPOST},
#ifdef OLCUC
- {"OLCUC", OLCUC},
+ {"OLCUC", OLCUC},
#endif
#ifdef ONLCR
- {"ONLCR", ONLCR},
+ {"ONLCR", ONLCR},
#endif
#ifdef OCRNL
- {"OCRNL", OCRNL},
+ {"OCRNL", OCRNL},
#endif
#ifdef ONOCR
- {"ONOCR", ONOCR},
+ {"ONOCR", ONOCR},
#endif
#ifdef ONLRET
- {"ONLRET", ONLRET},
+ {"ONLRET", ONLRET},
#endif
#ifdef OFILL
- {"OFILL", OFILL},
+ {"OFILL", OFILL},
#endif
#ifdef OFDEL
- {"OFDEL", OFDEL},
+ {"OFDEL", OFDEL},
#endif
#ifdef NLDLY
- {"NLDLY", NLDLY},
+ {"NLDLY", NLDLY},
#endif
#ifdef CRDLY
- {"CRDLY", CRDLY},
+ {"CRDLY", CRDLY},
#endif
#ifdef TABDLY
- {"TABDLY", TABDLY},
+ {"TABDLY", TABDLY},
#endif
#ifdef BSDLY
- {"BSDLY", BSDLY},
+ {"BSDLY", BSDLY},
#endif
#ifdef VTDLY
- {"VTDLY", VTDLY},
+ {"VTDLY", VTDLY},
#endif
#ifdef FFDLY
- {"FFDLY", FFDLY},
+ {"FFDLY", FFDLY},
#endif
- /* struct termios.c_oflag-related values (delay mask) */
+ /* struct termios.c_oflag-related values (delay mask) */
#ifdef NL0
- {"NL0", NL0},
+ {"NL0", NL0},
#endif
#ifdef NL1
- {"NL1", NL1},
+ {"NL1", NL1},
#endif
#ifdef CR0
- {"CR0", CR0},
+ {"CR0", CR0},
#endif
#ifdef CR1
- {"CR1", CR1},
+ {"CR1", CR1},
#endif
#ifdef CR2
- {"CR2", CR2},
+ {"CR2", CR2},
#endif
#ifdef CR3
- {"CR3", CR3},
+ {"CR3", CR3},
#endif
#ifdef TAB0
- {"TAB0", TAB0},
+ {"TAB0", TAB0},
#endif
#ifdef TAB1
- {"TAB1", TAB1},
+ {"TAB1", TAB1},
#endif
#ifdef TAB2
- {"TAB2", TAB2},
+ {"TAB2", TAB2},
#endif
#ifdef TAB3
- {"TAB3", TAB3},
+ {"TAB3", TAB3},
#endif
#ifdef XTABS
- {"XTABS", XTABS},
+ {"XTABS", XTABS},
#endif
#ifdef BS0
- {"BS0", BS0},
+ {"BS0", BS0},
#endif
#ifdef BS1
- {"BS1", BS1},
+ {"BS1", BS1},
#endif
#ifdef VT0
- {"VT0", VT0},
+ {"VT0", VT0},
#endif
#ifdef VT1
- {"VT1", VT1},
+ {"VT1", VT1},
#endif
#ifdef FF0
- {"FF0", FF0},
+ {"FF0", FF0},
#endif
#ifdef FF1
- {"FF1", FF1},
+ {"FF1", FF1},
#endif
- /* struct termios.c_cflag constants */
- {"CSIZE", CSIZE},
- {"CSTOPB", CSTOPB},
- {"CREAD", CREAD},
- {"PARENB", PARENB},
- {"PARODD", PARODD},
- {"HUPCL", HUPCL},
- {"CLOCAL", CLOCAL},
+ /* struct termios.c_cflag constants */
+ {"CSIZE", CSIZE},
+ {"CSTOPB", CSTOPB},
+ {"CREAD", CREAD},
+ {"PARENB", PARENB},
+ {"PARODD", PARODD},
+ {"HUPCL", HUPCL},
+ {"CLOCAL", CLOCAL},
#ifdef CIBAUD
- {"CIBAUD", CIBAUD},
+ {"CIBAUD", CIBAUD},
#endif
#ifdef CRTSCTS
- {"CRTSCTS", (long)CRTSCTS},
+ {"CRTSCTS", (long)CRTSCTS},
#endif
- /* struct termios.c_cflag-related values (character size) */
- {"CS5", CS5},
- {"CS6", CS6},
- {"CS7", CS7},
- {"CS8", CS8},
+ /* struct termios.c_cflag-related values (character size) */
+ {"CS5", CS5},
+ {"CS6", CS6},
+ {"CS7", CS7},
+ {"CS8", CS8},
- /* struct termios.c_lflag constants */
- {"ISIG", ISIG},
- {"ICANON", ICANON},
+ /* struct termios.c_lflag constants */
+ {"ISIG", ISIG},
+ {"ICANON", ICANON},
#ifdef XCASE
- {"XCASE", XCASE},
+ {"XCASE", XCASE},
#endif
- {"ECHO", ECHO},
- {"ECHOE", ECHOE},
- {"ECHOK", ECHOK},
- {"ECHONL", ECHONL},
+ {"ECHO", ECHO},
+ {"ECHOE", ECHOE},
+ {"ECHOK", ECHOK},
+ {"ECHONL", ECHONL},
#ifdef ECHOCTL
- {"ECHOCTL", ECHOCTL},
+ {"ECHOCTL", ECHOCTL},
#endif
#ifdef ECHOPRT
- {"ECHOPRT", ECHOPRT},
+ {"ECHOPRT", ECHOPRT},
#endif
#ifdef ECHOKE
- {"ECHOKE", ECHOKE},
+ {"ECHOKE", ECHOKE},
#endif
#ifdef FLUSHO
- {"FLUSHO", FLUSHO},
+ {"FLUSHO", FLUSHO},
#endif
- {"NOFLSH", NOFLSH},
- {"TOSTOP", TOSTOP},
+ {"NOFLSH", NOFLSH},
+ {"TOSTOP", TOSTOP},
#ifdef PENDIN
- {"PENDIN", PENDIN},
-#endif
- {"IEXTEN", IEXTEN},
-
- /* indexes into the control chars array returned by tcgetattr() */
- {"VINTR", VINTR},
- {"VQUIT", VQUIT},
- {"VERASE", VERASE},
- {"VKILL", VKILL},
- {"VEOF", VEOF},
- {"VTIME", VTIME},
- {"VMIN", VMIN},
+ {"PENDIN", PENDIN},
+#endif
+ {"IEXTEN", IEXTEN},
+
+ /* indexes into the control chars array returned by tcgetattr() */
+ {"VINTR", VINTR},
+ {"VQUIT", VQUIT},
+ {"VERASE", VERASE},
+ {"VKILL", VKILL},
+ {"VEOF", VEOF},
+ {"VTIME", VTIME},
+ {"VMIN", VMIN},
#ifdef VSWTC
- /* The #defines above ensure that if either is defined, both are,
- * but both may be omitted by the system headers. ;-( */
- {"VSWTC", VSWTC},
- {"VSWTCH", VSWTCH},
-#endif
- {"VSTART", VSTART},
- {"VSTOP", VSTOP},
- {"VSUSP", VSUSP},
- {"VEOL", VEOL},
+ /* The #defines above ensure that if either is defined, both are,
+ * but both may be omitted by the system headers. ;-( */
+ {"VSWTC", VSWTC},
+ {"VSWTCH", VSWTCH},
+#endif
+ {"VSTART", VSTART},
+ {"VSTOP", VSTOP},
+ {"VSUSP", VSUSP},
+ {"VEOL", VEOL},
#ifdef VREPRINT
- {"VREPRINT", VREPRINT},
+ {"VREPRINT", VREPRINT},
#endif
#ifdef VDISCARD
- {"VDISCARD", VDISCARD},
+ {"VDISCARD", VDISCARD},
#endif
#ifdef VWERASE
- {"VWERASE", VWERASE},
+ {"VWERASE", VWERASE},
#endif
#ifdef VLNEXT
- {"VLNEXT", VLNEXT},
+ {"VLNEXT", VLNEXT},
#endif
#ifdef VEOL2
- {"VEOL2", VEOL2},
+ {"VEOL2", VEOL2},
#endif
#ifdef B460800
- {"B460800", B460800},
+ {"B460800", B460800},
#endif
#ifdef CBAUD
- {"CBAUD", CBAUD},
+ {"CBAUD", CBAUD},
#endif
#ifdef CDEL
- {"CDEL", CDEL},
+ {"CDEL", CDEL},
#endif
#ifdef CDSUSP
- {"CDSUSP", CDSUSP},
+ {"CDSUSP", CDSUSP},
#endif
#ifdef CEOF
- {"CEOF", CEOF},
+ {"CEOF", CEOF},
#endif
#ifdef CEOL
- {"CEOL", CEOL},
+ {"CEOL", CEOL},
#endif
#ifdef CEOL2
- {"CEOL2", CEOL2},
+ {"CEOL2", CEOL2},
#endif
#ifdef CEOT
- {"CEOT", CEOT},
+ {"CEOT", CEOT},
#endif
#ifdef CERASE
- {"CERASE", CERASE},
+ {"CERASE", CERASE},
#endif
#ifdef CESC
- {"CESC", CESC},
+ {"CESC", CESC},
#endif
#ifdef CFLUSH
- {"CFLUSH", CFLUSH},
+ {"CFLUSH", CFLUSH},
#endif
#ifdef CINTR
- {"CINTR", CINTR},
+ {"CINTR", CINTR},
#endif
#ifdef CKILL
- {"CKILL", CKILL},
+ {"CKILL", CKILL},
#endif
#ifdef CLNEXT
- {"CLNEXT", CLNEXT},
+ {"CLNEXT", CLNEXT},
#endif
#ifdef CNUL
- {"CNUL", CNUL},
+ {"CNUL", CNUL},
#endif
#ifdef COMMON
- {"COMMON", COMMON},
+ {"COMMON", COMMON},
#endif
#ifdef CQUIT
- {"CQUIT", CQUIT},
+ {"CQUIT", CQUIT},
#endif
#ifdef CRPRNT
- {"CRPRNT", CRPRNT},
+ {"CRPRNT", CRPRNT},
#endif
#ifdef CSTART
- {"CSTART", CSTART},
+ {"CSTART", CSTART},
#endif
#ifdef CSTOP
- {"CSTOP", CSTOP},
+ {"CSTOP", CSTOP},
#endif
#ifdef CSUSP
- {"CSUSP", CSUSP},
+ {"CSUSP", CSUSP},
#endif
#ifdef CSWTCH
- {"CSWTCH", CSWTCH},
+ {"CSWTCH", CSWTCH},
#endif
#ifdef CWERASE
- {"CWERASE", CWERASE},
+ {"CWERASE", CWERASE},
#endif
#ifdef EXTA
- {"EXTA", EXTA},
+ {"EXTA", EXTA},
#endif
#ifdef EXTB
- {"EXTB", EXTB},
+ {"EXTB", EXTB},
#endif
#ifdef FIOASYNC
- {"FIOASYNC", FIOASYNC},
+ {"FIOASYNC", FIOASYNC},
#endif
#ifdef FIOCLEX
- {"FIOCLEX", FIOCLEX},
+ {"FIOCLEX", FIOCLEX},
#endif
#ifdef FIONBIO
- {"FIONBIO", FIONBIO},
+ {"FIONBIO", FIONBIO},
#endif
#ifdef FIONCLEX
- {"FIONCLEX", FIONCLEX},
+ {"FIONCLEX", FIONCLEX},
#endif
#ifdef FIONREAD
- {"FIONREAD", FIONREAD},
+ {"FIONREAD", FIONREAD},
#endif
#ifdef IBSHIFT
- {"IBSHIFT", IBSHIFT},
+ {"IBSHIFT", IBSHIFT},
#endif
#ifdef INIT_C_CC
- {"INIT_C_CC", INIT_C_CC},
+ {"INIT_C_CC", INIT_C_CC},
#endif
#ifdef IOCSIZE_MASK
- {"IOCSIZE_MASK", IOCSIZE_MASK},
+ {"IOCSIZE_MASK", IOCSIZE_MASK},
#endif
#ifdef IOCSIZE_SHIFT
- {"IOCSIZE_SHIFT", IOCSIZE_SHIFT},
+ {"IOCSIZE_SHIFT", IOCSIZE_SHIFT},
#endif
#ifdef NCC
- {"NCC", NCC},
+ {"NCC", NCC},
#endif
#ifdef NCCS
- {"NCCS", NCCS},
+ {"NCCS", NCCS},
#endif
#ifdef NSWTCH
- {"NSWTCH", NSWTCH},
+ {"NSWTCH", NSWTCH},
#endif
#ifdef N_MOUSE
- {"N_MOUSE", N_MOUSE},
+ {"N_MOUSE", N_MOUSE},
#endif
#ifdef N_PPP
- {"N_PPP", N_PPP},
+ {"N_PPP", N_PPP},
#endif
#ifdef N_SLIP
- {"N_SLIP", N_SLIP},
+ {"N_SLIP", N_SLIP},
#endif
#ifdef N_STRIP
- {"N_STRIP", N_STRIP},
+ {"N_STRIP", N_STRIP},
#endif
#ifdef N_TTY
- {"N_TTY", N_TTY},
+ {"N_TTY", N_TTY},
#endif
#ifdef TCFLSH
- {"TCFLSH", TCFLSH},
+ {"TCFLSH", TCFLSH},
#endif
#ifdef TCGETA
- {"TCGETA", TCGETA},
+ {"TCGETA", TCGETA},
#endif
#ifdef TCGETS
- {"TCGETS", TCGETS},
+ {"TCGETS", TCGETS},
#endif
#ifdef TCSBRK
- {"TCSBRK", TCSBRK},
+ {"TCSBRK", TCSBRK},
#endif
#ifdef TCSBRKP
- {"TCSBRKP", TCSBRKP},
+ {"TCSBRKP", TCSBRKP},
#endif
#ifdef TCSETA
- {"TCSETA", TCSETA},
+ {"TCSETA", TCSETA},
#endif
#ifdef TCSETAF
- {"TCSETAF", TCSETAF},
+ {"TCSETAF", TCSETAF},
#endif
#ifdef TCSETAW
- {"TCSETAW", TCSETAW},
+ {"TCSETAW", TCSETAW},
#endif
#ifdef TCSETS
- {"TCSETS", TCSETS},
+ {"TCSETS", TCSETS},
#endif
#ifdef TCSETSF
- {"TCSETSF", TCSETSF},
+ {"TCSETSF", TCSETSF},
#endif
#ifdef TCSETSW
- {"TCSETSW", TCSETSW},
+ {"TCSETSW", TCSETSW},
#endif
#ifdef TCXONC
- {"TCXONC", TCXONC},
+ {"TCXONC", TCXONC},
#endif
#ifdef TIOCCONS
- {"TIOCCONS", TIOCCONS},
+ {"TIOCCONS", TIOCCONS},
#endif
#ifdef TIOCEXCL
- {"TIOCEXCL", TIOCEXCL},
+ {"TIOCEXCL", TIOCEXCL},
#endif
#ifdef TIOCGETD
- {"TIOCGETD", TIOCGETD},
+ {"TIOCGETD", TIOCGETD},
#endif
#ifdef TIOCGICOUNT
- {"TIOCGICOUNT", TIOCGICOUNT},
+ {"TIOCGICOUNT", TIOCGICOUNT},
#endif
#ifdef TIOCGLCKTRMIOS
- {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS},
+ {"TIOCGLCKTRMIOS", TIOCGLCKTRMIOS},
#endif
#ifdef TIOCGPGRP
- {"TIOCGPGRP", TIOCGPGRP},
+ {"TIOCGPGRP", TIOCGPGRP},
#endif
#ifdef TIOCGSERIAL
- {"TIOCGSERIAL", TIOCGSERIAL},
+ {"TIOCGSERIAL", TIOCGSERIAL},
#endif
#ifdef TIOCGSOFTCAR
- {"TIOCGSOFTCAR", TIOCGSOFTCAR},
+ {"TIOCGSOFTCAR", TIOCGSOFTCAR},
#endif
#ifdef TIOCGWINSZ
- {"TIOCGWINSZ", TIOCGWINSZ},
+ {"TIOCGWINSZ", TIOCGWINSZ},
#endif
#ifdef TIOCINQ
- {"TIOCINQ", TIOCINQ},
+ {"TIOCINQ", TIOCINQ},
#endif
#ifdef TIOCLINUX
- {"TIOCLINUX", TIOCLINUX},
+ {"TIOCLINUX", TIOCLINUX},
#endif
#ifdef TIOCMBIC
- {"TIOCMBIC", TIOCMBIC},
+ {"TIOCMBIC", TIOCMBIC},
#endif
#ifdef TIOCMBIS
- {"TIOCMBIS", TIOCMBIS},
+ {"TIOCMBIS", TIOCMBIS},
#endif
#ifdef TIOCMGET
- {"TIOCMGET", TIOCMGET},
+ {"TIOCMGET", TIOCMGET},
#endif
#ifdef TIOCMIWAIT
- {"TIOCMIWAIT", TIOCMIWAIT},
+ {"TIOCMIWAIT", TIOCMIWAIT},
#endif
#ifdef TIOCMSET
- {"TIOCMSET", TIOCMSET},
+ {"TIOCMSET", TIOCMSET},
#endif
#ifdef TIOCM_CAR
- {"TIOCM_CAR", TIOCM_CAR},
+ {"TIOCM_CAR", TIOCM_CAR},
#endif
#ifdef TIOCM_CD
- {"TIOCM_CD", TIOCM_CD},
+ {"TIOCM_CD", TIOCM_CD},
#endif
#ifdef TIOCM_CTS
- {"TIOCM_CTS", TIOCM_CTS},
+ {"TIOCM_CTS", TIOCM_CTS},
#endif
#ifdef TIOCM_DSR
- {"TIOCM_DSR", TIOCM_DSR},
+ {"TIOCM_DSR", TIOCM_DSR},
#endif
#ifdef TIOCM_DTR
- {"TIOCM_DTR", TIOCM_DTR},
+ {"TIOCM_DTR", TIOCM_DTR},
#endif
#ifdef TIOCM_LE
- {"TIOCM_LE", TIOCM_LE},
+ {"TIOCM_LE", TIOCM_LE},
#endif
#ifdef TIOCM_RI
- {"TIOCM_RI", TIOCM_RI},
+ {"TIOCM_RI", TIOCM_RI},
#endif
#ifdef TIOCM_RNG
- {"TIOCM_RNG", TIOCM_RNG},
+ {"TIOCM_RNG", TIOCM_RNG},
#endif
#ifdef TIOCM_RTS
- {"TIOCM_RTS", TIOCM_RTS},
+ {"TIOCM_RTS", TIOCM_RTS},
#endif
#ifdef TIOCM_SR
- {"TIOCM_SR", TIOCM_SR},
+ {"TIOCM_SR", TIOCM_SR},
#endif
#ifdef TIOCM_ST
- {"TIOCM_ST", TIOCM_ST},
+ {"TIOCM_ST", TIOCM_ST},
#endif
#ifdef TIOCNOTTY
- {"TIOCNOTTY", TIOCNOTTY},
+ {"TIOCNOTTY", TIOCNOTTY},
#endif
#ifdef TIOCNXCL
- {"TIOCNXCL", TIOCNXCL},
+ {"TIOCNXCL", TIOCNXCL},
#endif
#ifdef TIOCOUTQ
- {"TIOCOUTQ", TIOCOUTQ},
+ {"TIOCOUTQ", TIOCOUTQ},
#endif
#ifdef TIOCPKT
- {"TIOCPKT", TIOCPKT},
+ {"TIOCPKT", TIOCPKT},
#endif
#ifdef TIOCPKT_DATA
- {"TIOCPKT_DATA", TIOCPKT_DATA},
+ {"TIOCPKT_DATA", TIOCPKT_DATA},
#endif
#ifdef TIOCPKT_DOSTOP
- {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP},
+ {"TIOCPKT_DOSTOP", TIOCPKT_DOSTOP},
#endif
#ifdef TIOCPKT_FLUSHREAD
- {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD},
+ {"TIOCPKT_FLUSHREAD", TIOCPKT_FLUSHREAD},
#endif
#ifdef TIOCPKT_FLUSHWRITE
- {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE},
+ {"TIOCPKT_FLUSHWRITE", TIOCPKT_FLUSHWRITE},
#endif
#ifdef TIOCPKT_NOSTOP
- {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP},
+ {"TIOCPKT_NOSTOP", TIOCPKT_NOSTOP},
#endif
#ifdef TIOCPKT_START
- {"TIOCPKT_START", TIOCPKT_START},
+ {"TIOCPKT_START", TIOCPKT_START},
#endif
#ifdef TIOCPKT_STOP
- {"TIOCPKT_STOP", TIOCPKT_STOP},
+ {"TIOCPKT_STOP", TIOCPKT_STOP},
#endif
#ifdef TIOCSCTTY
- {"TIOCSCTTY", TIOCSCTTY},
+ {"TIOCSCTTY", TIOCSCTTY},
#endif
#ifdef TIOCSERCONFIG
- {"TIOCSERCONFIG", TIOCSERCONFIG},
+ {"TIOCSERCONFIG", TIOCSERCONFIG},
#endif
#ifdef TIOCSERGETLSR
- {"TIOCSERGETLSR", TIOCSERGETLSR},
+ {"TIOCSERGETLSR", TIOCSERGETLSR},
#endif
#ifdef TIOCSERGETMULTI
- {"TIOCSERGETMULTI", TIOCSERGETMULTI},
+ {"TIOCSERGETMULTI", TIOCSERGETMULTI},
#endif
#ifdef TIOCSERGSTRUCT
- {"TIOCSERGSTRUCT", TIOCSERGSTRUCT},
+ {"TIOCSERGSTRUCT", TIOCSERGSTRUCT},
#endif
#ifdef TIOCSERGWILD
- {"TIOCSERGWILD", TIOCSERGWILD},
+ {"TIOCSERGWILD", TIOCSERGWILD},
#endif
#ifdef TIOCSERSETMULTI
- {"TIOCSERSETMULTI", TIOCSERSETMULTI},
+ {"TIOCSERSETMULTI", TIOCSERSETMULTI},
#endif
#ifdef TIOCSERSWILD
- {"TIOCSERSWILD", TIOCSERSWILD},
+ {"TIOCSERSWILD", TIOCSERSWILD},
#endif
#ifdef TIOCSER_TEMT
- {"TIOCSER_TEMT", TIOCSER_TEMT},
+ {"TIOCSER_TEMT", TIOCSER_TEMT},
#endif
#ifdef TIOCSETD
- {"TIOCSETD", TIOCSETD},
+ {"TIOCSETD", TIOCSETD},
#endif
#ifdef TIOCSLCKTRMIOS
- {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS},
+ {"TIOCSLCKTRMIOS", TIOCSLCKTRMIOS},
#endif
#ifdef TIOCSPGRP
- {"TIOCSPGRP", TIOCSPGRP},
+ {"TIOCSPGRP", TIOCSPGRP},
#endif
#ifdef TIOCSSERIAL
- {"TIOCSSERIAL", TIOCSSERIAL},
+ {"TIOCSSERIAL", TIOCSSERIAL},
#endif
#ifdef TIOCSSOFTCAR
- {"TIOCSSOFTCAR", TIOCSSOFTCAR},
+ {"TIOCSSOFTCAR", TIOCSSOFTCAR},
#endif
#ifdef TIOCSTI
- {"TIOCSTI", TIOCSTI},
+ {"TIOCSTI", TIOCSTI},
#endif
#ifdef TIOCSWINSZ
- {"TIOCSWINSZ", TIOCSWINSZ},
+ {"TIOCSWINSZ", TIOCSWINSZ},
#endif
#ifdef TIOCTTYGSTRUCT
- {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT},
+ {"TIOCTTYGSTRUCT", TIOCTTYGSTRUCT},
#endif
- /* sentinel */
- {NULL, 0}
+ /* sentinel */
+ {NULL, 0}
};
PyMODINIT_FUNC
PyInit_termios(void)
{
- PyObject *m;
- struct constant *constant = termios_constants;
-
- m = Py_InitModule4("termios", termios_methods, termios__doc__,
- (PyObject *)NULL, PYTHON_API_VERSION);
- if (m == NULL)
- return;
-
- if (TermiosError == NULL) {
- TermiosError = PyErr_NewException("termios.error", NULL, NULL);
- }
- Py_INCREF(TermiosError);
- PyModule_AddObject(m, "error", TermiosError);
-
- while (constant->name != NULL) {
- PyModule_AddIntConstant(m, constant->name, constant->value);
- ++constant;
- }
+ PyObject *m;
+ struct constant *constant = termios_constants;
+
+ m = Py_InitModule4("termios", termios_methods, termios__doc__,
+ (PyObject *)NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ return;
+
+ if (TermiosError == NULL) {
+ TermiosError = PyErr_NewException("termios.error", NULL, NULL);
+ }
+ Py_INCREF(TermiosError);
+ PyModule_AddObject(m, "error", TermiosError);
+
+ while (constant->name != NULL) {
+ PyModule_AddIntConstant(m, constant->name, constant->value);
+ ++constant;
+ }
}
diff --git a/Modules/testcapi_long.h b/Modules/testcapi_long.h
index 60ca326..fa94fd6 100644
--- a/Modules/testcapi_long.h
+++ b/Modules/testcapi_long.h
@@ -1,182 +1,182 @@
/* Poor-man's template. Macros used:
- TESTNAME name of the test (like test_long_api_inner)
- TYPENAME the signed type (like long)
- F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject*
- F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME
- F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject*
+ TESTNAME name of the test (like test_long_api_inner)
+ TYPENAME the signed type (like long)
+ F_S_TO_PY convert signed to pylong; TYPENAME -> PyObject*
+ F_PY_TO_S convert pylong to signed; PyObject* -> TYPENAME
+ F_U_TO_PY convert unsigned to pylong; unsigned TYPENAME -> PyObject*
F_PY_TO_U convert pylong to unsigned; PyObject* -> unsigned TYPENAME
*/
static PyObject *
TESTNAME(PyObject *error(const char*))
{
- const int NBITS = sizeof(TYPENAME) * 8;
- unsigned TYPENAME base;
- PyObject *pyresult;
- int i;
-
- /* Note: This test lets PyObjects leak if an error is raised. Since
- an error should never be raised, leaks are impossible <wink>. */
-
- /* Test native -> PyLong -> native roundtrip identity.
- * Generate all powers of 2, and test them and their negations,
- * plus the numbers +-1 off from them.
- */
- base = 1;
- for (i = 0;
- i < NBITS + 1; /* on last, base overflows to 0 */
- ++i, base <<= 1)
- {
- int j;
- for (j = 0; j < 6; ++j) {
- TYPENAME in, out;
- unsigned TYPENAME uin, uout;
-
- /* For 0, 1, 2 use base; for 3, 4, 5 use -base */
- uin = j < 3 ? base
- : (unsigned TYPENAME)(-(TYPENAME)base);
-
- /* For 0 & 3, subtract 1.
- * For 1 & 4, leave alone.
- * For 2 & 5, add 1.
- */
- uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1);
-
- pyresult = F_U_TO_PY(uin);
- if (pyresult == NULL)
- return error(
- "unsigned unexpected null result");
-
- uout = F_PY_TO_U(pyresult);
- if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred())
- return error(
- "unsigned unexpected -1 result");
- if (uout != uin)
- return error(
- "unsigned output != input");
- UNBIND(pyresult);
-
- in = (TYPENAME)uin;
- pyresult = F_S_TO_PY(in);
- if (pyresult == NULL)
- return error(
- "signed unexpected null result");
-
- out = F_PY_TO_S(pyresult);
- if (out == (TYPENAME)-1 && PyErr_Occurred())
- return error(
- "signed unexpected -1 result");
- if (out != in)
- return error(
- "signed output != input");
- UNBIND(pyresult);
- }
- }
-
- /* Overflow tests. The loop above ensured that all limit cases that
- * should not overflow don't overflow, so all we need to do here is
- * provoke one-over-the-limit cases (not exhaustive, but sharp).
- */
- {
- PyObject *one, *x, *y;
- TYPENAME out;
- unsigned TYPENAME uout;
-
- one = PyLong_FromLong(1);
- if (one == NULL)
- return error(
- "unexpected NULL from PyLong_FromLong");
-
- /* Unsigned complains about -1? */
- x = PyNumber_Negative(one);
- if (x == NULL)
- return error(
- "unexpected NULL from PyNumber_Negative");
-
- uout = F_PY_TO_U(x);
- if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsUnsignedXXX(-1) didn't complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsUnsignedXXX(-1) raised "
- "something other than OverflowError");
- PyErr_Clear();
- UNBIND(x);
-
- /* Unsigned complains about 2**NBITS? */
- y = PyLong_FromLong((long)NBITS);
- if (y == NULL)
- return error(
- "unexpected NULL from PyLong_FromLong");
-
- x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */
- UNBIND(y);
- if (x == NULL)
- return error(
- "unexpected NULL from PyNumber_Lshift");
-
- uout = F_PY_TO_U(x);
- if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsUnsignedXXX(2**NBITS) didn't "
- "complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsUnsignedXXX(2**NBITS) raised "
- "something other than OverflowError");
- PyErr_Clear();
-
- /* Signed complains about 2**(NBITS-1)?
- x still has 2**NBITS. */
- y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */
- UNBIND(x);
- if (y == NULL)
- return error(
- "unexpected NULL from PyNumber_Rshift");
-
- out = F_PY_TO_S(y);
- if (out != (TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsXXX(2**(NBITS-1)) didn't "
- "complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsXXX(2**(NBITS-1)) raised "
- "something other than OverflowError");
- PyErr_Clear();
-
- /* Signed complains about -2**(NBITS-1)-1?;
- y still has 2**(NBITS-1). */
- x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */
- UNBIND(y);
- if (x == NULL)
- return error(
- "unexpected NULL from PyNumber_Negative");
-
- y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */
- UNBIND(x);
- if (y == NULL)
- return error(
- "unexpected NULL from PyNumber_Subtract");
-
- out = F_PY_TO_S(y);
- if (out != (TYPENAME)-1 || !PyErr_Occurred())
- return error(
- "PyLong_AsXXX(-2**(NBITS-1)-1) didn't "
- "complain");
- if (!PyErr_ExceptionMatches(PyExc_OverflowError))
- return error(
- "PyLong_AsXXX(-2**(NBITS-1)-1) raised "
- "something other than OverflowError");
- PyErr_Clear();
- UNBIND(y);
-
- Py_XDECREF(x);
- Py_XDECREF(y);
- Py_DECREF(one);
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ const int NBITS = sizeof(TYPENAME) * 8;
+ unsigned TYPENAME base;
+ PyObject *pyresult;
+ int i;
+
+ /* Note: This test lets PyObjects leak if an error is raised. Since
+ an error should never be raised, leaks are impossible <wink>. */
+
+ /* Test native -> PyLong -> native roundtrip identity.
+ * Generate all powers of 2, and test them and their negations,
+ * plus the numbers +-1 off from them.
+ */
+ base = 1;
+ for (i = 0;
+ i < NBITS + 1; /* on last, base overflows to 0 */
+ ++i, base <<= 1)
+ {
+ int j;
+ for (j = 0; j < 6; ++j) {
+ TYPENAME in, out;
+ unsigned TYPENAME uin, uout;
+
+ /* For 0, 1, 2 use base; for 3, 4, 5 use -base */
+ uin = j < 3 ? base
+ : (unsigned TYPENAME)(-(TYPENAME)base);
+
+ /* For 0 & 3, subtract 1.
+ * For 1 & 4, leave alone.
+ * For 2 & 5, add 1.
+ */
+ uin += (unsigned TYPENAME)(TYPENAME)(j % 3 - 1);
+
+ pyresult = F_U_TO_PY(uin);
+ if (pyresult == NULL)
+ return error(
+ "unsigned unexpected null result");
+
+ uout = F_PY_TO_U(pyresult);
+ if (uout == (unsigned TYPENAME)-1 && PyErr_Occurred())
+ return error(
+ "unsigned unexpected -1 result");
+ if (uout != uin)
+ return error(
+ "unsigned output != input");
+ UNBIND(pyresult);
+
+ in = (TYPENAME)uin;
+ pyresult = F_S_TO_PY(in);
+ if (pyresult == NULL)
+ return error(
+ "signed unexpected null result");
+
+ out = F_PY_TO_S(pyresult);
+ if (out == (TYPENAME)-1 && PyErr_Occurred())
+ return error(
+ "signed unexpected -1 result");
+ if (out != in)
+ return error(
+ "signed output != input");
+ UNBIND(pyresult);
+ }
+ }
+
+ /* Overflow tests. The loop above ensured that all limit cases that
+ * should not overflow don't overflow, so all we need to do here is
+ * provoke one-over-the-limit cases (not exhaustive, but sharp).
+ */
+ {
+ PyObject *one, *x, *y;
+ TYPENAME out;
+ unsigned TYPENAME uout;
+
+ one = PyLong_FromLong(1);
+ if (one == NULL)
+ return error(
+ "unexpected NULL from PyLong_FromLong");
+
+ /* Unsigned complains about -1? */
+ x = PyNumber_Negative(one);
+ if (x == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Negative");
+
+ uout = F_PY_TO_U(x);
+ if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsUnsignedXXX(-1) didn't complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsUnsignedXXX(-1) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+ UNBIND(x);
+
+ /* Unsigned complains about 2**NBITS? */
+ y = PyLong_FromLong((long)NBITS);
+ if (y == NULL)
+ return error(
+ "unexpected NULL from PyLong_FromLong");
+
+ x = PyNumber_Lshift(one, y); /* 1L << NBITS, == 2**NBITS */
+ UNBIND(y);
+ if (x == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Lshift");
+
+ uout = F_PY_TO_U(x);
+ if (uout != (unsigned TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsUnsignedXXX(2**NBITS) didn't "
+ "complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsUnsignedXXX(2**NBITS) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+
+ /* Signed complains about 2**(NBITS-1)?
+ x still has 2**NBITS. */
+ y = PyNumber_Rshift(x, one); /* 2**(NBITS-1) */
+ UNBIND(x);
+ if (y == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Rshift");
+
+ out = F_PY_TO_S(y);
+ if (out != (TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsXXX(2**(NBITS-1)) didn't "
+ "complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsXXX(2**(NBITS-1)) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+
+ /* Signed complains about -2**(NBITS-1)-1?;
+ y still has 2**(NBITS-1). */
+ x = PyNumber_Negative(y); /* -(2**(NBITS-1)) */
+ UNBIND(y);
+ if (x == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Negative");
+
+ y = PyNumber_Subtract(x, one); /* -(2**(NBITS-1))-1 */
+ UNBIND(x);
+ if (y == NULL)
+ return error(
+ "unexpected NULL from PyNumber_Subtract");
+
+ out = F_PY_TO_S(y);
+ if (out != (TYPENAME)-1 || !PyErr_Occurred())
+ return error(
+ "PyLong_AsXXX(-2**(NBITS-1)-1) didn't "
+ "complain");
+ if (!PyErr_ExceptionMatches(PyExc_OverflowError))
+ return error(
+ "PyLong_AsXXX(-2**(NBITS-1)-1) raised "
+ "something other than OverflowError");
+ PyErr_Clear();
+ UNBIND(y);
+
+ Py_XDECREF(x);
+ Py_XDECREF(y);
+ Py_DECREF(one);
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
diff --git a/Modules/threadmodule.c b/Modules/threadmodule.c
index 6494f49..016d5a0 100644
--- a/Modules/threadmodule.c
+++ b/Modules/threadmodule.c
@@ -19,39 +19,39 @@ static long nb_threads = 0;
/* Lock objects */
typedef struct {
- PyObject_HEAD
- PyThread_type_lock lock_lock;
- PyObject *in_weakreflist;
+ PyObject_HEAD
+ PyThread_type_lock lock_lock;
+ PyObject *in_weakreflist;
} lockobject;
static void
lock_dealloc(lockobject *self)
{
- if (self->in_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) self);
- if (self->lock_lock != NULL) {
- /* Unlock the lock so it's safe to free it */
- PyThread_acquire_lock(self->lock_lock, 0);
- PyThread_release_lock(self->lock_lock);
-
- PyThread_free_lock(self->lock_lock);
- }
- PyObject_Del(self);
+ if (self->in_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) self);
+ if (self->lock_lock != NULL) {
+ /* Unlock the lock so it's safe to free it */
+ PyThread_acquire_lock(self->lock_lock, 0);
+ PyThread_release_lock(self->lock_lock);
+
+ PyThread_free_lock(self->lock_lock);
+ }
+ PyObject_Del(self);
}
static PyObject *
lock_PyThread_acquire_lock(lockobject *self, PyObject *args)
{
- int i = 1;
+ int i = 1;
- if (!PyArg_ParseTuple(args, "|i:acquire", &i))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:acquire", &i))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- i = PyThread_acquire_lock(self->lock_lock, i);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ i = PyThread_acquire_lock(self->lock_lock, i);
+ Py_END_ALLOW_THREADS
- return PyBool_FromLong((long)i);
+ return PyBool_FromLong((long)i);
}
PyDoc_STRVAR(acquire_doc,
@@ -68,16 +68,16 @@ The blocking operation is not interruptible.");
static PyObject *
lock_PyThread_release_lock(lockobject *self)
{
- /* Sanity check: the lock must be locked */
- if (PyThread_acquire_lock(self->lock_lock, 0)) {
- PyThread_release_lock(self->lock_lock);
- PyErr_SetString(ThreadError, "release unlocked lock");
- return NULL;
- }
-
- PyThread_release_lock(self->lock_lock);
- Py_INCREF(Py_None);
- return Py_None;
+ /* Sanity check: the lock must be locked */
+ if (PyThread_acquire_lock(self->lock_lock, 0)) {
+ PyThread_release_lock(self->lock_lock);
+ PyErr_SetString(ThreadError, "release unlocked lock");
+ return NULL;
+ }
+
+ PyThread_release_lock(self->lock_lock);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(release_doc,
@@ -91,11 +91,11 @@ but it needn't be locked by the same thread that unlocks it.");
static PyObject *
lock_locked_lock(lockobject *self)
{
- if (PyThread_acquire_lock(self->lock_lock, 0)) {
- PyThread_release_lock(self->lock_lock);
- return PyBool_FromLong(0L);
- }
- return PyBool_FromLong(1L);
+ if (PyThread_acquire_lock(self->lock_lock, 0)) {
+ PyThread_release_lock(self->lock_lock);
+ return PyBool_FromLong(0L);
+ }
+ return PyBool_FromLong(1L);
}
PyDoc_STRVAR(locked_doc,
@@ -105,72 +105,72 @@ PyDoc_STRVAR(locked_doc,
Return whether the lock is in the locked state.");
static PyMethodDef lock_methods[] = {
- {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS, acquire_doc},
- {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS, acquire_doc},
- {"release_lock", (PyCFunction)lock_PyThread_release_lock,
- METH_NOARGS, release_doc},
- {"release", (PyCFunction)lock_PyThread_release_lock,
- METH_NOARGS, release_doc},
- {"locked_lock", (PyCFunction)lock_locked_lock,
- METH_NOARGS, locked_doc},
- {"locked", (PyCFunction)lock_locked_lock,
- METH_NOARGS, locked_doc},
- {"__enter__", (PyCFunction)lock_PyThread_acquire_lock,
- METH_VARARGS, acquire_doc},
- {"__exit__", (PyCFunction)lock_PyThread_release_lock,
- METH_VARARGS, release_doc},
- {NULL} /* sentinel */
+ {"acquire_lock", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS, acquire_doc},
+ {"acquire", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS, acquire_doc},
+ {"release_lock", (PyCFunction)lock_PyThread_release_lock,
+ METH_NOARGS, release_doc},
+ {"release", (PyCFunction)lock_PyThread_release_lock,
+ METH_NOARGS, release_doc},
+ {"locked_lock", (PyCFunction)lock_locked_lock,
+ METH_NOARGS, locked_doc},
+ {"locked", (PyCFunction)lock_locked_lock,
+ METH_NOARGS, locked_doc},
+ {"__enter__", (PyCFunction)lock_PyThread_acquire_lock,
+ METH_VARARGS, acquire_doc},
+ {"__exit__", (PyCFunction)lock_PyThread_release_lock,
+ METH_VARARGS, release_doc},
+ {NULL} /* sentinel */
};
static PyTypeObject Locktype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "thread.lock", /*tp_name*/
- sizeof(lockobject), /*tp_size*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)lock_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_HAVE_WEAKREFS, /* tp_flags */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(lockobject, in_weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- lock_methods, /* tp_methods */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "thread.lock", /*tp_name*/
+ sizeof(lockobject), /*tp_size*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)lock_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_HAVE_WEAKREFS, /* tp_flags */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(lockobject, in_weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ lock_methods, /* tp_methods */
};
static lockobject *
newlockobject(void)
{
- lockobject *self;
- self = PyObject_New(lockobject, &Locktype);
- if (self == NULL)
- return NULL;
- self->lock_lock = PyThread_allocate_lock();
- self->in_weakreflist = NULL;
- if (self->lock_lock == NULL) {
- Py_DECREF(self);
- PyErr_SetString(ThreadError, "can't allocate lock");
- return NULL;
- }
- return self;
+ lockobject *self;
+ self = PyObject_New(lockobject, &Locktype);
+ if (self == NULL)
+ return NULL;
+ self->lock_lock = PyThread_allocate_lock();
+ self->in_weakreflist = NULL;
+ if (self->lock_lock == NULL) {
+ Py_DECREF(self);
+ PyErr_SetString(ThreadError, "can't allocate lock");
+ return NULL;
+ }
+ return self;
}
/* Thread-local objects */
@@ -178,353 +178,353 @@ newlockobject(void)
#include "structmember.h"
typedef struct {
- PyObject_HEAD
- PyObject *key;
- PyObject *args;
- PyObject *kw;
- PyObject *dict;
+ PyObject_HEAD
+ PyObject *key;
+ PyObject *args;
+ PyObject *kw;
+ PyObject *dict;
} localobject;
static PyObject *
local_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- localobject *self;
- PyObject *tdict;
-
- if (type->tp_init == PyBaseObject_Type.tp_init
- && ((args && PyObject_IsTrue(args))
- || (kw && PyObject_IsTrue(kw)))) {
- PyErr_SetString(PyExc_TypeError,
- "Initialization arguments are not supported");
- return NULL;
- }
-
- self = (localobject *)type->tp_alloc(type, 0);
- if (self == NULL)
- return NULL;
-
- Py_XINCREF(args);
- self->args = args;
- Py_XINCREF(kw);
- self->kw = kw;
- self->dict = NULL; /* making sure */
- self->key = PyString_FromFormat("thread.local.%p", self);
- if (self->key == NULL)
- goto err;
-
- self->dict = PyDict_New();
- if (self->dict == NULL)
- goto err;
-
- tdict = PyThreadState_GetDict();
- if (tdict == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "Couldn't get thread-state dictionary");
- goto err;
- }
-
- if (PyDict_SetItem(tdict, self->key, self->dict) < 0)
- goto err;
-
- return (PyObject *)self;
+ localobject *self;
+ PyObject *tdict;
+
+ if (type->tp_init == PyBaseObject_Type.tp_init
+ && ((args && PyObject_IsTrue(args))
+ || (kw && PyObject_IsTrue(kw)))) {
+ PyErr_SetString(PyExc_TypeError,
+ "Initialization arguments are not supported");
+ return NULL;
+ }
+
+ self = (localobject *)type->tp_alloc(type, 0);
+ if (self == NULL)
+ return NULL;
+
+ Py_XINCREF(args);
+ self->args = args;
+ Py_XINCREF(kw);
+ self->kw = kw;
+ self->dict = NULL; /* making sure */
+ self->key = PyString_FromFormat("thread.local.%p", self);
+ if (self->key == NULL)
+ goto err;
+
+ self->dict = PyDict_New();
+ if (self->dict == NULL)
+ goto err;
+
+ tdict = PyThreadState_GetDict();
+ if (tdict == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "Couldn't get thread-state dictionary");
+ goto err;
+ }
+
+ if (PyDict_SetItem(tdict, self->key, self->dict) < 0)
+ goto err;
+
+ return (PyObject *)self;
err:
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
static int
local_traverse(localobject *self, visitproc visit, void *arg)
{
- Py_VISIT(self->args);
- Py_VISIT(self->kw);
- Py_VISIT(self->dict);
- return 0;
+ Py_VISIT(self->args);
+ Py_VISIT(self->kw);
+ Py_VISIT(self->dict);
+ return 0;
}
static int
local_clear(localobject *self)
{
- Py_CLEAR(self->args);
- Py_CLEAR(self->kw);
- Py_CLEAR(self->dict);
- return 0;
+ Py_CLEAR(self->args);
+ Py_CLEAR(self->kw);
+ Py_CLEAR(self->dict);
+ return 0;
}
static void
local_dealloc(localobject *self)
{
- PyThreadState *tstate;
- if (self->key
- && (tstate = PyThreadState_Get())
- && tstate->interp) {
- for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
- tstate;
- tstate = PyThreadState_Next(tstate))
- if (tstate->dict &&
- PyDict_GetItem(tstate->dict, self->key))
- PyDict_DelItem(tstate->dict, self->key);
- }
-
- Py_XDECREF(self->key);
- local_clear(self);
- Py_TYPE(self)->tp_free((PyObject*)self);
+ PyThreadState *tstate;
+ if (self->key
+ && (tstate = PyThreadState_Get())
+ && tstate->interp) {
+ for(tstate = PyInterpreterState_ThreadHead(tstate->interp);
+ tstate;
+ tstate = PyThreadState_Next(tstate))
+ if (tstate->dict &&
+ PyDict_GetItem(tstate->dict, self->key))
+ PyDict_DelItem(tstate->dict, self->key);
+ }
+
+ Py_XDECREF(self->key);
+ local_clear(self);
+ Py_TYPE(self)->tp_free((PyObject*)self);
}
static PyObject *
_ldict(localobject *self)
{
- PyObject *tdict, *ldict;
-
- tdict = PyThreadState_GetDict();
- if (tdict == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "Couldn't get thread-state dictionary");
- return NULL;
- }
-
- ldict = PyDict_GetItem(tdict, self->key);
- if (ldict == NULL) {
- ldict = PyDict_New(); /* we own ldict */
-
- if (ldict == NULL)
- return NULL;
- else {
- int i = PyDict_SetItem(tdict, self->key, ldict);
- Py_DECREF(ldict); /* now ldict is borrowed */
- if (i < 0)
- return NULL;
- }
-
- Py_CLEAR(self->dict);
- Py_INCREF(ldict);
- self->dict = ldict; /* still borrowed */
-
- if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
- Py_TYPE(self)->tp_init((PyObject*)self,
- self->args, self->kw) < 0) {
- /* we need to get rid of ldict from thread so
- we create a new one the next time we do an attr
- acces */
- PyDict_DelItem(tdict, self->key);
- return NULL;
- }
-
- }
-
- /* The call to tp_init above may have caused another thread to run.
- Install our ldict again. */
- if (self->dict != ldict) {
- Py_CLEAR(self->dict);
- Py_INCREF(ldict);
- self->dict = ldict;
- }
-
- return ldict;
+ PyObject *tdict, *ldict;
+
+ tdict = PyThreadState_GetDict();
+ if (tdict == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "Couldn't get thread-state dictionary");
+ return NULL;
+ }
+
+ ldict = PyDict_GetItem(tdict, self->key);
+ if (ldict == NULL) {
+ ldict = PyDict_New(); /* we own ldict */
+
+ if (ldict == NULL)
+ return NULL;
+ else {
+ int i = PyDict_SetItem(tdict, self->key, ldict);
+ Py_DECREF(ldict); /* now ldict is borrowed */
+ if (i < 0)
+ return NULL;
+ }
+
+ Py_CLEAR(self->dict);
+ Py_INCREF(ldict);
+ self->dict = ldict; /* still borrowed */
+
+ if (Py_TYPE(self)->tp_init != PyBaseObject_Type.tp_init &&
+ Py_TYPE(self)->tp_init((PyObject*)self,
+ self->args, self->kw) < 0) {
+ /* we need to get rid of ldict from thread so
+ we create a new one the next time we do an attr
+ acces */
+ PyDict_DelItem(tdict, self->key);
+ return NULL;
+ }
+
+ }
+
+ /* The call to tp_init above may have caused another thread to run.
+ Install our ldict again. */
+ if (self->dict != ldict) {
+ Py_CLEAR(self->dict);
+ Py_INCREF(ldict);
+ self->dict = ldict;
+ }
+
+ return ldict;
}
static int
local_setattro(localobject *self, PyObject *name, PyObject *v)
{
- PyObject *ldict;
-
- ldict = _ldict(self);
- if (ldict == NULL)
- return -1;
+ PyObject *ldict;
- return PyObject_GenericSetAttr((PyObject *)self, name, v);
+ ldict = _ldict(self);
+ if (ldict == NULL)
+ return -1;
+
+ return PyObject_GenericSetAttr((PyObject *)self, name, v);
}
static PyObject *
local_getdict(localobject *self, void *closure)
{
- if (self->dict == NULL) {
- PyErr_SetString(PyExc_AttributeError, "__dict__");
- return NULL;
- }
+ if (self->dict == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "__dict__");
+ return NULL;
+ }
- Py_INCREF(self->dict);
- return self->dict;
+ Py_INCREF(self->dict);
+ return self->dict;
}
static PyGetSetDef local_getset[] = {
- {"__dict__", (getter)local_getdict, (setter)NULL,
- "Local-data dictionary", NULL},
- {NULL} /* Sentinel */
+ {"__dict__", (getter)local_getdict, (setter)NULL,
+ "Local-data dictionary", NULL},
+ {NULL} /* Sentinel */
};
static PyObject *local_getattro(localobject *, PyObject *);
static PyTypeObject localtype = {
- PyVarObject_HEAD_INIT(NULL, 0)
- /* tp_name */ "thread._local",
- /* tp_basicsize */ sizeof(localobject),
- /* tp_itemsize */ 0,
- /* tp_dealloc */ (destructor)local_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 */ (getattrofunc)local_getattro,
- /* tp_setattro */ (setattrofunc)local_setattro,
- /* tp_as_buffer */ 0,
- /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
- /* tp_doc */ "Thread-local data",
- /* tp_traverse */ (traverseproc)local_traverse,
- /* tp_clear */ (inquiry)local_clear,
- /* tp_richcompare */ 0,
- /* tp_weaklistoffset */ 0,
- /* tp_iter */ 0,
- /* tp_iternext */ 0,
- /* tp_methods */ 0,
- /* tp_members */ 0,
- /* tp_getset */ local_getset,
- /* tp_base */ 0,
- /* tp_dict */ 0, /* internal use */
- /* tp_descr_get */ 0,
- /* tp_descr_set */ 0,
- /* tp_dictoffset */ offsetof(localobject, dict),
- /* tp_init */ 0,
- /* tp_alloc */ 0,
- /* tp_new */ local_new,
- /* tp_free */ 0, /* Low-level free-mem routine */
- /* tp_is_gc */ 0, /* For PyObject_IS_GC */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* tp_name */ "thread._local",
+ /* tp_basicsize */ sizeof(localobject),
+ /* tp_itemsize */ 0,
+ /* tp_dealloc */ (destructor)local_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 */ (getattrofunc)local_getattro,
+ /* tp_setattro */ (setattrofunc)local_setattro,
+ /* tp_as_buffer */ 0,
+ /* tp_flags */ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
+ /* tp_doc */ "Thread-local data",
+ /* tp_traverse */ (traverseproc)local_traverse,
+ /* tp_clear */ (inquiry)local_clear,
+ /* tp_richcompare */ 0,
+ /* tp_weaklistoffset */ 0,
+ /* tp_iter */ 0,
+ /* tp_iternext */ 0,
+ /* tp_methods */ 0,
+ /* tp_members */ 0,
+ /* tp_getset */ local_getset,
+ /* tp_base */ 0,
+ /* tp_dict */ 0, /* internal use */
+ /* tp_descr_get */ 0,
+ /* tp_descr_set */ 0,
+ /* tp_dictoffset */ offsetof(localobject, dict),
+ /* tp_init */ 0,
+ /* tp_alloc */ 0,
+ /* tp_new */ local_new,
+ /* tp_free */ 0, /* Low-level free-mem routine */
+ /* tp_is_gc */ 0, /* For PyObject_IS_GC */
};
static PyObject *
local_getattro(localobject *self, PyObject *name)
{
- PyObject *ldict, *value;
+ PyObject *ldict, *value;
- ldict = _ldict(self);
- if (ldict == NULL)
- return NULL;
+ ldict = _ldict(self);
+ if (ldict == NULL)
+ return NULL;
- if (Py_TYPE(self) != &localtype)
- /* use generic lookup for subtypes */
- return PyObject_GenericGetAttr((PyObject *)self, name);
+ if (Py_TYPE(self) != &localtype)
+ /* use generic lookup for subtypes */
+ return PyObject_GenericGetAttr((PyObject *)self, name);
- /* Optimization: just look in dict ourselves */
- value = PyDict_GetItem(ldict, name);
- if (value == NULL)
- /* Fall back on generic to get __class__ and __dict__ */
- return PyObject_GenericGetAttr((PyObject *)self, name);
+ /* Optimization: just look in dict ourselves */
+ value = PyDict_GetItem(ldict, name);
+ if (value == NULL)
+ /* Fall back on generic to get __class__ and __dict__ */
+ return PyObject_GenericGetAttr((PyObject *)self, name);
- Py_INCREF(value);
- return value;
+ Py_INCREF(value);
+ return value;
}
/* Module functions */
struct bootstate {
- PyInterpreterState *interp;
- PyObject *func;
- PyObject *args;
- PyObject *keyw;
- PyThreadState *tstate;
+ PyInterpreterState *interp;
+ PyObject *func;
+ PyObject *args;
+ PyObject *keyw;
+ PyThreadState *tstate;
};
static void
t_bootstrap(void *boot_raw)
{
- struct bootstate *boot = (struct bootstate *) boot_raw;
- PyThreadState *tstate;
- PyObject *res;
-
- tstate = boot->tstate;
- tstate->thread_id = PyThread_get_thread_ident();
- _PyThreadState_Init(tstate);
- PyEval_AcquireThread(tstate);
- nb_threads++;
- res = PyEval_CallObjectWithKeywords(
- boot->func, boot->args, boot->keyw);
- if (res == NULL) {
- if (PyErr_ExceptionMatches(PyExc_SystemExit))
- PyErr_Clear();
- else {
- PyObject *file;
- PySys_WriteStderr(
- "Unhandled exception in thread started by ");
- file = PySys_GetObject("stderr");
- if (file)
- PyFile_WriteObject(boot->func, file, 0);
- else
- PyObject_Print(boot->func, stderr, 0);
- PySys_WriteStderr("\n");
- PyErr_PrintEx(0);
- }
- }
- else
- Py_DECREF(res);
- Py_DECREF(boot->func);
- Py_DECREF(boot->args);
- Py_XDECREF(boot->keyw);
- PyMem_DEL(boot_raw);
- nb_threads--;
- PyThreadState_Clear(tstate);
- PyThreadState_DeleteCurrent();
- PyThread_exit_thread();
+ struct bootstate *boot = (struct bootstate *) boot_raw;
+ PyThreadState *tstate;
+ PyObject *res;
+
+ tstate = boot->tstate;
+ tstate->thread_id = PyThread_get_thread_ident();
+ _PyThreadState_Init(tstate);
+ PyEval_AcquireThread(tstate);
+ nb_threads++;
+ res = PyEval_CallObjectWithKeywords(
+ boot->func, boot->args, boot->keyw);
+ if (res == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_SystemExit))
+ PyErr_Clear();
+ else {
+ PyObject *file;
+ PySys_WriteStderr(
+ "Unhandled exception in thread started by ");
+ file = PySys_GetObject("stderr");
+ if (file)
+ PyFile_WriteObject(boot->func, file, 0);
+ else
+ PyObject_Print(boot->func, stderr, 0);
+ PySys_WriteStderr("\n");
+ PyErr_PrintEx(0);
+ }
+ }
+ else
+ Py_DECREF(res);
+ Py_DECREF(boot->func);
+ Py_DECREF(boot->args);
+ Py_XDECREF(boot->keyw);
+ PyMem_DEL(boot_raw);
+ nb_threads--;
+ PyThreadState_Clear(tstate);
+ PyThreadState_DeleteCurrent();
+ PyThread_exit_thread();
}
static PyObject *
thread_PyThread_start_new_thread(PyObject *self, PyObject *fargs)
{
- PyObject *func, *args, *keyw = NULL;
- struct bootstate *boot;
- long ident;
-
- if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
- &func, &args, &keyw))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError,
- "first arg must be callable");
- return NULL;
- }
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_TypeError,
- "2nd arg must be a tuple");
- return NULL;
- }
- if (keyw != NULL && !PyDict_Check(keyw)) {
- PyErr_SetString(PyExc_TypeError,
- "optional 3rd arg must be a dictionary");
- return NULL;
- }
- boot = PyMem_NEW(struct bootstate, 1);
- if (boot == NULL)
- return PyErr_NoMemory();
- boot->interp = PyThreadState_GET()->interp;
- boot->func = func;
- boot->args = args;
- boot->keyw = keyw;
- boot->tstate = _PyThreadState_Prealloc(boot->interp);
- if (boot->tstate == NULL) {
- PyMem_DEL(boot);
- return PyErr_NoMemory();
- }
- Py_INCREF(func);
- Py_INCREF(args);
- Py_XINCREF(keyw);
- PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
- ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
- if (ident == -1) {
- PyErr_SetString(ThreadError, "can't start new thread");
- Py_DECREF(func);
- Py_DECREF(args);
- Py_XDECREF(keyw);
- PyThreadState_Clear(boot->tstate);
- PyMem_DEL(boot);
- return NULL;
- }
- return PyInt_FromLong(ident);
+ PyObject *func, *args, *keyw = NULL;
+ struct bootstate *boot;
+ long ident;
+
+ if (!PyArg_UnpackTuple(fargs, "start_new_thread", 2, 3,
+ &func, &args, &keyw))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first arg must be callable");
+ return NULL;
+ }
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_TypeError,
+ "2nd arg must be a tuple");
+ return NULL;
+ }
+ if (keyw != NULL && !PyDict_Check(keyw)) {
+ PyErr_SetString(PyExc_TypeError,
+ "optional 3rd arg must be a dictionary");
+ return NULL;
+ }
+ boot = PyMem_NEW(struct bootstate, 1);
+ if (boot == NULL)
+ return PyErr_NoMemory();
+ boot->interp = PyThreadState_GET()->interp;
+ boot->func = func;
+ boot->args = args;
+ boot->keyw = keyw;
+ boot->tstate = _PyThreadState_Prealloc(boot->interp);
+ if (boot->tstate == NULL) {
+ PyMem_DEL(boot);
+ return PyErr_NoMemory();
+ }
+ Py_INCREF(func);
+ Py_INCREF(args);
+ Py_XINCREF(keyw);
+ PyEval_InitThreads(); /* Start the interpreter's thread-awareness */
+ ident = PyThread_start_new_thread(t_bootstrap, (void*) boot);
+ if (ident == -1) {
+ PyErr_SetString(ThreadError, "can't start new thread");
+ Py_DECREF(func);
+ Py_DECREF(args);
+ Py_XDECREF(keyw);
+ PyThreadState_Clear(boot->tstate);
+ PyMem_DEL(boot);
+ return NULL;
+ }
+ return PyInt_FromLong(ident);
}
PyDoc_STRVAR(start_new_doc,
@@ -541,8 +541,8 @@ printed unless the exception is SystemExit.\n");
static PyObject *
thread_PyThread_exit_thread(PyObject *self)
{
- PyErr_SetNone(PyExc_SystemExit);
- return NULL;
+ PyErr_SetNone(PyExc_SystemExit);
+ return NULL;
}
PyDoc_STRVAR(exit_doc,
@@ -555,9 +555,9 @@ thread to exit silently unless the exception is caught.");
static PyObject *
thread_PyThread_interrupt_main(PyObject * self)
{
- PyErr_SetInterrupt();
- Py_INCREF(Py_None);
- return Py_None;
+ PyErr_SetInterrupt();
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(interrupt_doc,
@@ -572,7 +572,7 @@ static lockobject *newlockobject(void);
static PyObject *
thread_PyThread_allocate_lock(PyObject *self)
{
- return (PyObject *) newlockobject();
+ return (PyObject *) newlockobject();
}
PyDoc_STRVAR(allocate_doc,
@@ -584,13 +584,13 @@ Create a new lock object. See LockType.__doc__ for information about locks.");
static PyObject *
thread_get_ident(PyObject *self)
{
- long ident;
- ident = PyThread_get_thread_ident();
- if (ident == -1) {
- PyErr_SetString(ThreadError, "no current thread ident");
- return NULL;
- }
- return PyInt_FromLong(ident);
+ long ident;
+ ident = PyThread_get_thread_ident();
+ if (ident == -1) {
+ PyErr_SetString(ThreadError, "no current thread ident");
+ return NULL;
+ }
+ return PyInt_FromLong(ident);
}
PyDoc_STRVAR(get_ident_doc,
@@ -607,7 +607,7 @@ A thread's identity may be reused for another thread after it exits.");
static PyObject *
thread__count(PyObject *self)
{
- return PyInt_FromLong(nb_threads);
+ return PyInt_FromLong(nb_threads);
}
PyDoc_STRVAR(_count_doc,
@@ -625,35 +625,35 @@ In most applications `threading.enumerate()` should be used instead.");
static PyObject *
thread_stack_size(PyObject *self, PyObject *args)
{
- size_t old_size;
- Py_ssize_t new_size = 0;
- int rc;
-
- if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size))
- return NULL;
-
- if (new_size < 0) {
- PyErr_SetString(PyExc_ValueError,
- "size must be 0 or a positive value");
- return NULL;
- }
-
- old_size = PyThread_get_stacksize();
-
- rc = PyThread_set_stacksize((size_t) new_size);
- if (rc == -1) {
- PyErr_Format(PyExc_ValueError,
- "size not valid: %zd bytes",
- new_size);
- return NULL;
- }
- if (rc == -2) {
- PyErr_SetString(ThreadError,
- "setting stack size not supported");
- return NULL;
- }
-
- return PyInt_FromSsize_t((Py_ssize_t) old_size);
+ size_t old_size;
+ Py_ssize_t new_size = 0;
+ int rc;
+
+ if (!PyArg_ParseTuple(args, "|n:stack_size", &new_size))
+ return NULL;
+
+ if (new_size < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "size must be 0 or a positive value");
+ return NULL;
+ }
+
+ old_size = PyThread_get_stacksize();
+
+ rc = PyThread_set_stacksize((size_t) new_size);
+ if (rc == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "size not valid: %zd bytes",
+ new_size);
+ return NULL;
+ }
+ if (rc == -2) {
+ PyErr_SetString(ThreadError,
+ "setting stack size not supported");
+ return NULL;
+ }
+
+ return PyInt_FromSsize_t((Py_ssize_t) old_size);
}
PyDoc_STRVAR(stack_size_doc,
@@ -677,30 +677,30 @@ requiring allocation in multiples of the system memory page size\n\
the suggested approach in the absence of more specific information).");
static PyMethodDef thread_methods[] = {
- {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread,
- METH_VARARGS,
- start_new_doc},
- {"start_new", (PyCFunction)thread_PyThread_start_new_thread,
- METH_VARARGS,
- start_new_doc},
- {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock,
- METH_NOARGS, allocate_doc},
- {"allocate", (PyCFunction)thread_PyThread_allocate_lock,
- METH_NOARGS, allocate_doc},
- {"exit_thread", (PyCFunction)thread_PyThread_exit_thread,
- METH_NOARGS, exit_doc},
- {"exit", (PyCFunction)thread_PyThread_exit_thread,
- METH_NOARGS, exit_doc},
- {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main,
- METH_NOARGS, interrupt_doc},
- {"get_ident", (PyCFunction)thread_get_ident,
- METH_NOARGS, get_ident_doc},
- {"_count", (PyCFunction)thread__count,
- METH_NOARGS, _count_doc},
- {"stack_size", (PyCFunction)thread_stack_size,
- METH_VARARGS,
- stack_size_doc},
- {NULL, NULL} /* sentinel */
+ {"start_new_thread", (PyCFunction)thread_PyThread_start_new_thread,
+ METH_VARARGS,
+ start_new_doc},
+ {"start_new", (PyCFunction)thread_PyThread_start_new_thread,
+ METH_VARARGS,
+ start_new_doc},
+ {"allocate_lock", (PyCFunction)thread_PyThread_allocate_lock,
+ METH_NOARGS, allocate_doc},
+ {"allocate", (PyCFunction)thread_PyThread_allocate_lock,
+ METH_NOARGS, allocate_doc},
+ {"exit_thread", (PyCFunction)thread_PyThread_exit_thread,
+ METH_NOARGS, exit_doc},
+ {"exit", (PyCFunction)thread_PyThread_exit_thread,
+ METH_NOARGS, exit_doc},
+ {"interrupt_main", (PyCFunction)thread_PyThread_interrupt_main,
+ METH_NOARGS, interrupt_doc},
+ {"get_ident", (PyCFunction)thread_get_ident,
+ METH_NOARGS, get_ident_doc},
+ {"_count", (PyCFunction)thread__count,
+ METH_NOARGS, _count_doc},
+ {"stack_size", (PyCFunction)thread_stack_size,
+ METH_VARARGS,
+ stack_size_doc},
+ {NULL, NULL} /* sentinel */
};
@@ -725,33 +725,33 @@ will block until another thread unlocks it. Deadlocks may ensue.");
PyMODINIT_FUNC
initthread(void)
{
- PyObject *m, *d;
-
- /* Initialize types: */
- if (PyType_Ready(&localtype) < 0)
- return;
-
- /* Create the module and add the functions */
- m = Py_InitModule3("thread", thread_methods, thread_doc);
- if (m == NULL)
- return;
-
- /* Add a symbolic constant */
- d = PyModule_GetDict(m);
- ThreadError = PyErr_NewException("thread.error", NULL, NULL);
- PyDict_SetItemString(d, "error", ThreadError);
- Locktype.tp_doc = lock_doc;
- if (PyType_Ready(&Locktype) < 0)
- return;
- Py_INCREF(&Locktype);
- PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
-
- Py_INCREF(&localtype);
- if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
- return;
-
- nb_threads = 0;
-
- /* Initialize the C thread library */
- PyThread_init_thread();
+ PyObject *m, *d;
+
+ /* Initialize types: */
+ if (PyType_Ready(&localtype) < 0)
+ return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule3("thread", thread_methods, thread_doc);
+ if (m == NULL)
+ return;
+
+ /* Add a symbolic constant */
+ d = PyModule_GetDict(m);
+ ThreadError = PyErr_NewException("thread.error", NULL, NULL);
+ PyDict_SetItemString(d, "error", ThreadError);
+ Locktype.tp_doc = lock_doc;
+ if (PyType_Ready(&Locktype) < 0)
+ return;
+ Py_INCREF(&Locktype);
+ PyDict_SetItemString(d, "LockType", (PyObject *)&Locktype);
+
+ Py_INCREF(&localtype);
+ if (PyModule_AddObject(m, "_local", (PyObject *)&localtype) < 0)
+ return;
+
+ nb_threads = 0;
+
+ /* Initialize the C thread library */
+ PyThread_init_thread();
}
diff --git a/Modules/timemodule.c b/Modules/timemodule.c
index 44cb9c8..78dec7c 100644
--- a/Modules/timemodule.c
+++ b/Modules/timemodule.c
@@ -46,12 +46,12 @@ extern int ftime(struct timeb *);
static HANDLE hInterruptEvent = NULL;
static BOOL WINAPI PyCtrlHandler(DWORD dwCtrlType)
{
- SetEvent(hInterruptEvent);
- /* allow other default handlers to be called.
- Default Python handler will setup the
- KeyboardInterrupt exception.
- */
- return FALSE;
+ SetEvent(hInterruptEvent);
+ /* allow other default handlers to be called.
+ Default Python handler will setup the
+ KeyboardInterrupt exception.
+ */
+ return FALSE;
}
static long main_thread;
@@ -102,38 +102,38 @@ static PyObject *moddict;
time_t
_PyTime_DoubleToTimet(double x)
{
- time_t result;
- double diff;
-
- result = (time_t)x;
- /* How much info did we lose? time_t may be an integral or
- * floating type, and we don't know which. If it's integral,
- * we don't know whether C truncates, rounds, returns the floor,
- * etc. If we lost a second or more, the C rounding is
- * unreasonable, or the input just doesn't fit in a time_t;
- * call it an error regardless. Note that the original cast to
- * time_t can cause a C error too, but nothing we can do to
- * worm around that.
- */
- diff = x - (double)result;
- if (diff <= -1.0 || diff >= 1.0) {
- PyErr_SetString(PyExc_ValueError,
- "timestamp out of range for platform time_t");
- result = (time_t)-1;
- }
- return result;
+ time_t result;
+ double diff;
+
+ result = (time_t)x;
+ /* How much info did we lose? time_t may be an integral or
+ * floating type, and we don't know which. If it's integral,
+ * we don't know whether C truncates, rounds, returns the floor,
+ * etc. If we lost a second or more, the C rounding is
+ * unreasonable, or the input just doesn't fit in a time_t;
+ * call it an error regardless. Note that the original cast to
+ * time_t can cause a C error too, but nothing we can do to
+ * worm around that.
+ */
+ diff = x - (double)result;
+ if (diff <= -1.0 || diff >= 1.0) {
+ PyErr_SetString(PyExc_ValueError,
+ "timestamp out of range for platform time_t");
+ result = (time_t)-1;
+ }
+ return result;
}
static PyObject *
time_time(PyObject *self, PyObject *unused)
{
- double secs;
- secs = floattime();
- if (secs == 0.0) {
- PyErr_SetFromErrno(PyExc_IOError);
- return NULL;
- }
- return PyFloat_FromDouble(secs);
+ double secs;
+ secs = floattime();
+ if (secs == 0.0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ return NULL;
+ }
+ return PyFloat_FromDouble(secs);
}
PyDoc_STRVAR(time_doc,
@@ -155,7 +155,7 @@ Fractions of a second may be present if the system clock provides them.");
static PyObject *
time_clock(PyObject *self, PyObject *unused)
{
- return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
+ return PyFloat_FromDouble(((double)clock()) / CLOCKS_PER_SEC);
}
#endif /* HAVE_CLOCK */
@@ -164,25 +164,25 @@ time_clock(PyObject *self, PyObject *unused)
static PyObject *
time_clock(PyObject *self, PyObject *unused)
{
- static LARGE_INTEGER ctrStart;
- static double divisor = 0.0;
- LARGE_INTEGER now;
- double diff;
-
- if (divisor == 0.0) {
- LARGE_INTEGER freq;
- QueryPerformanceCounter(&ctrStart);
- if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
- /* Unlikely to happen - this works on all intel
- machines at least! Revert to clock() */
- return PyFloat_FromDouble(((double)clock()) /
- CLOCKS_PER_SEC);
- }
- divisor = (double)freq.QuadPart;
- }
- QueryPerformanceCounter(&now);
- diff = (double)(now.QuadPart - ctrStart.QuadPart);
- return PyFloat_FromDouble(diff / divisor);
+ static LARGE_INTEGER ctrStart;
+ static double divisor = 0.0;
+ LARGE_INTEGER now;
+ double diff;
+
+ if (divisor == 0.0) {
+ LARGE_INTEGER freq;
+ QueryPerformanceCounter(&ctrStart);
+ if (!QueryPerformanceFrequency(&freq) || freq.QuadPart == 0) {
+ /* Unlikely to happen - this works on all intel
+ machines at least! Revert to clock() */
+ return PyFloat_FromDouble(((double)clock()) /
+ CLOCKS_PER_SEC);
+ }
+ divisor = (double)freq.QuadPart;
+ }
+ QueryPerformanceCounter(&now);
+ diff = (double)(now.QuadPart - ctrStart.QuadPart);
+ return PyFloat_FromDouble(diff / divisor);
}
#define HAVE_CLOCK /* So it gets included in the methods */
@@ -200,13 +200,13 @@ records.");
static PyObject *
time_sleep(PyObject *self, PyObject *args)
{
- double secs;
- if (!PyArg_ParseTuple(args, "d:sleep", &secs))
- return NULL;
- if (floatsleep(secs) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ double secs;
+ if (!PyArg_ParseTuple(args, "d:sleep", &secs))
+ return NULL;
+ if (floatsleep(secs) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(sleep_doc,
@@ -216,23 +216,23 @@ Delay execution for a given number of seconds. The argument may be\n\
a floating point number for subsecond precision.");
static PyStructSequence_Field struct_time_type_fields[] = {
- {"tm_year", NULL},
- {"tm_mon", NULL},
- {"tm_mday", NULL},
- {"tm_hour", NULL},
- {"tm_min", NULL},
- {"tm_sec", NULL},
- {"tm_wday", NULL},
- {"tm_yday", NULL},
- {"tm_isdst", NULL},
- {0}
+ {"tm_year", NULL},
+ {"tm_mon", NULL},
+ {"tm_mday", NULL},
+ {"tm_hour", NULL},
+ {"tm_min", NULL},
+ {"tm_sec", NULL},
+ {"tm_wday", NULL},
+ {"tm_yday", NULL},
+ {"tm_isdst", NULL},
+ {0}
};
static PyStructSequence_Desc struct_time_type_desc = {
- "time.struct_time",
- NULL,
- struct_time_type_fields,
- 9,
+ "time.struct_time",
+ NULL,
+ struct_time_type_fields,
+ 9,
};
static int initialized;
@@ -241,48 +241,48 @@ static PyTypeObject StructTimeType;
static PyObject *
tmtotuple(struct tm *p)
{
- PyObject *v = PyStructSequence_New(&StructTimeType);
- if (v == NULL)
- return NULL;
+ PyObject *v = PyStructSequence_New(&StructTimeType);
+ if (v == NULL)
+ return NULL;
#define SET(i,val) PyStructSequence_SET_ITEM(v, i, PyInt_FromLong((long) val))
- SET(0, p->tm_year + 1900);
- SET(1, p->tm_mon + 1); /* Want January == 1 */
- SET(2, p->tm_mday);
- SET(3, p->tm_hour);
- SET(4, p->tm_min);
- SET(5, p->tm_sec);
- SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
- SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
- SET(8, p->tm_isdst);
+ SET(0, p->tm_year + 1900);
+ SET(1, p->tm_mon + 1); /* Want January == 1 */
+ SET(2, p->tm_mday);
+ SET(3, p->tm_hour);
+ SET(4, p->tm_min);
+ SET(5, p->tm_sec);
+ SET(6, (p->tm_wday + 6) % 7); /* Want Monday == 0 */
+ SET(7, p->tm_yday + 1); /* Want January, 1 == 1 */
+ SET(8, p->tm_isdst);
#undef SET
- if (PyErr_Occurred()) {
- Py_XDECREF(v);
- return NULL;
- }
+ if (PyErr_Occurred()) {
+ Py_XDECREF(v);
+ return NULL;
+ }
- return v;
+ return v;
}
static PyObject *
time_convert(double when, struct tm * (*function)(const time_t *))
{
- struct tm *p;
- time_t whent = _PyTime_DoubleToTimet(when);
-
- if (whent == (time_t)-1 && PyErr_Occurred())
- return NULL;
- errno = 0;
- p = function(&whent);
- if (p == NULL) {
+ struct tm *p;
+ time_t whent = _PyTime_DoubleToTimet(when);
+
+ if (whent == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ errno = 0;
+ p = function(&whent);
+ if (p == NULL) {
#ifdef EINVAL
- if (errno == 0)
- errno = EINVAL;
+ if (errno == 0)
+ errno = EINVAL;
#endif
- return PyErr_SetFromErrno(PyExc_ValueError);
- }
- return tmtotuple(p);
+ return PyErr_SetFromErrno(PyExc_ValueError);
+ }
+ return tmtotuple(p);
}
/* Parse arg tuple that can contain an optional float-or-None value;
@@ -292,28 +292,28 @@ time_convert(double when, struct tm * (*function)(const time_t *))
static int
parse_time_double_args(PyObject *args, char *format, double *pwhen)
{
- PyObject *ot = NULL;
-
- if (!PyArg_ParseTuple(args, format, &ot))
- return 0;
- if (ot == NULL || ot == Py_None)
- *pwhen = floattime();
- else {
- double when = PyFloat_AsDouble(ot);
- if (PyErr_Occurred())
- return 0;
- *pwhen = when;
- }
- return 1;
+ PyObject *ot = NULL;
+
+ if (!PyArg_ParseTuple(args, format, &ot))
+ return 0;
+ if (ot == NULL || ot == Py_None)
+ *pwhen = floattime();
+ else {
+ double when = PyFloat_AsDouble(ot);
+ if (PyErr_Occurred())
+ return 0;
+ *pwhen = when;
+ }
+ return 1;
}
static PyObject *
time_gmtime(PyObject *self, PyObject *args)
{
- double when;
- if (!parse_time_double_args(args, "|O:gmtime", &when))
- return NULL;
- return time_convert(when, gmtime);
+ double when;
+ if (!parse_time_double_args(args, "|O:gmtime", &when))
+ return NULL;
+ return time_convert(when, gmtime);
}
PyDoc_STRVAR(gmtime_doc,
@@ -326,15 +326,15 @@ GMT). When 'seconds' is not passed in, convert the current time instead.");
static PyObject *
time_localtime(PyObject *self, PyObject *args)
{
- double when;
- if (!parse_time_double_args(args, "|O:localtime", &when))
- return NULL;
- return time_convert(when, localtime);
+ double when;
+ if (!parse_time_double_args(args, "|O:localtime", &when))
+ return NULL;
+ return time_convert(when, localtime);
}
PyDoc_STRVAR(localtime_doc,
"localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,\n\
- tm_sec,tm_wday,tm_yday,tm_isdst)\n\
+ tm_sec,tm_wday,tm_yday,tm_isdst)\n\
\n\
Convert seconds since the Epoch to a time tuple expressing local time.\n\
When 'seconds' is not passed in, convert the current time instead.");
@@ -342,185 +342,185 @@ When 'seconds' is not passed in, convert the current time instead.");
static int
gettmarg(PyObject *args, struct tm *p)
{
- int y;
- memset((void *) p, '\0', sizeof(struct tm));
-
- if (!PyArg_Parse(args, "(iiiiiiiii)",
- &y,
- &p->tm_mon,
- &p->tm_mday,
- &p->tm_hour,
- &p->tm_min,
- &p->tm_sec,
- &p->tm_wday,
- &p->tm_yday,
- &p->tm_isdst))
- return 0;
- if (y < 1900) {
- PyObject *accept = PyDict_GetItemString(moddict,
- "accept2dyear");
- if (accept == NULL || !PyInt_Check(accept) ||
- PyInt_AsLong(accept) == 0) {
- PyErr_SetString(PyExc_ValueError,
- "year >= 1900 required");
- return 0;
- }
- if (69 <= y && y <= 99)
- y += 1900;
- else if (0 <= y && y <= 68)
- y += 2000;
- else {
- PyErr_SetString(PyExc_ValueError,
- "year out of range");
- return 0;
- }
- }
- p->tm_year = y - 1900;
- p->tm_mon--;
- p->tm_wday = (p->tm_wday + 1) % 7;
- p->tm_yday--;
- return 1;
+ int y;
+ memset((void *) p, '\0', sizeof(struct tm));
+
+ if (!PyArg_Parse(args, "(iiiiiiiii)",
+ &y,
+ &p->tm_mon,
+ &p->tm_mday,
+ &p->tm_hour,
+ &p->tm_min,
+ &p->tm_sec,
+ &p->tm_wday,
+ &p->tm_yday,
+ &p->tm_isdst))
+ return 0;
+ if (y < 1900) {
+ PyObject *accept = PyDict_GetItemString(moddict,
+ "accept2dyear");
+ if (accept == NULL || !PyInt_Check(accept) ||
+ PyInt_AsLong(accept) == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "year >= 1900 required");
+ return 0;
+ }
+ if (69 <= y && y <= 99)
+ y += 1900;
+ else if (0 <= y && y <= 68)
+ y += 2000;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "year out of range");
+ return 0;
+ }
+ }
+ p->tm_year = y - 1900;
+ p->tm_mon--;
+ p->tm_wday = (p->tm_wday + 1) % 7;
+ p->tm_yday--;
+ return 1;
}
#ifdef HAVE_STRFTIME
static PyObject *
time_strftime(PyObject *self, PyObject *args)
{
- PyObject *tup = NULL;
- struct tm buf;
- const char *fmt;
- size_t fmtlen, buflen;
- char *outbuf = 0;
- size_t i;
-
- memset((void *) &buf, '\0', sizeof(buf));
-
- if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
- return NULL;
-
- if (tup == NULL) {
- time_t tt = time(NULL);
- buf = *localtime(&tt);
- } else if (!gettmarg(tup, &buf))
- return NULL;
-
- /* Checks added to make sure strftime() does not crash Python by
- indexing blindly into some array for a textual representation
- by some bad index (fixes bug #897625).
-
- Also support values of zero from Python code for arguments in which
- that is out of range by forcing that value to the lowest value that
- is valid (fixed bug #1520914).
-
- Valid ranges based on what is allowed in struct tm:
-
- - tm_year: [0, max(int)] (1)
- - tm_mon: [0, 11] (2)
- - tm_mday: [1, 31]
- - tm_hour: [0, 23]
- - tm_min: [0, 59]
- - tm_sec: [0, 60]
- - tm_wday: [0, 6] (1)
- - tm_yday: [0, 365] (2)
- - tm_isdst: [-max(int), max(int)]
-
- (1) gettmarg() handles bounds-checking.
- (2) Python's acceptable range is one greater than the range in C,
- thus need to check against automatic decrement by gettmarg().
- */
- if (buf.tm_mon == -1)
- buf.tm_mon = 0;
- else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
- PyErr_SetString(PyExc_ValueError, "month out of range");
- return NULL;
- }
- if (buf.tm_mday == 0)
- buf.tm_mday = 1;
- else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
- PyErr_SetString(PyExc_ValueError, "day of month out of range");
- return NULL;
- }
- if (buf.tm_hour < 0 || buf.tm_hour > 23) {
- PyErr_SetString(PyExc_ValueError, "hour out of range");
- return NULL;
- }
- if (buf.tm_min < 0 || buf.tm_min > 59) {
- PyErr_SetString(PyExc_ValueError, "minute out of range");
- return NULL;
- }
- if (buf.tm_sec < 0 || buf.tm_sec > 61) {
- PyErr_SetString(PyExc_ValueError, "seconds out of range");
- return NULL;
- }
- /* tm_wday does not need checking of its upper-bound since taking
- ``% 7`` in gettmarg() automatically restricts the range. */
- if (buf.tm_wday < 0) {
- PyErr_SetString(PyExc_ValueError, "day of week out of range");
- return NULL;
- }
- if (buf.tm_yday == -1)
- buf.tm_yday = 0;
- else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
- PyErr_SetString(PyExc_ValueError, "day of year out of range");
- return NULL;
- }
- /* Normalize tm_isdst just in case someone foolishly implements %Z
- based on the assumption that tm_isdst falls within the range of
- [-1, 1] */
- if (buf.tm_isdst < -1)
- buf.tm_isdst = -1;
- else if (buf.tm_isdst > 1)
- buf.tm_isdst = 1;
+ PyObject *tup = NULL;
+ struct tm buf;
+ const char *fmt;
+ size_t fmtlen, buflen;
+ char *outbuf = 0;
+ size_t i;
+
+ memset((void *) &buf, '\0', sizeof(buf));
+
+ if (!PyArg_ParseTuple(args, "s|O:strftime", &fmt, &tup))
+ return NULL;
+
+ if (tup == NULL) {
+ time_t tt = time(NULL);
+ buf = *localtime(&tt);
+ } else if (!gettmarg(tup, &buf))
+ return NULL;
+
+ /* Checks added to make sure strftime() does not crash Python by
+ indexing blindly into some array for a textual representation
+ by some bad index (fixes bug #897625).
+
+ Also support values of zero from Python code for arguments in which
+ that is out of range by forcing that value to the lowest value that
+ is valid (fixed bug #1520914).
+
+ Valid ranges based on what is allowed in struct tm:
+
+ - tm_year: [0, max(int)] (1)
+ - tm_mon: [0, 11] (2)
+ - tm_mday: [1, 31]
+ - tm_hour: [0, 23]
+ - tm_min: [0, 59]
+ - tm_sec: [0, 60]
+ - tm_wday: [0, 6] (1)
+ - tm_yday: [0, 365] (2)
+ - tm_isdst: [-max(int), max(int)]
+
+ (1) gettmarg() handles bounds-checking.
+ (2) Python's acceptable range is one greater than the range in C,
+ thus need to check against automatic decrement by gettmarg().
+ */
+ if (buf.tm_mon == -1)
+ buf.tm_mon = 0;
+ else if (buf.tm_mon < 0 || buf.tm_mon > 11) {
+ PyErr_SetString(PyExc_ValueError, "month out of range");
+ return NULL;
+ }
+ if (buf.tm_mday == 0)
+ buf.tm_mday = 1;
+ else if (buf.tm_mday < 0 || buf.tm_mday > 31) {
+ PyErr_SetString(PyExc_ValueError, "day of month out of range");
+ return NULL;
+ }
+ if (buf.tm_hour < 0 || buf.tm_hour > 23) {
+ PyErr_SetString(PyExc_ValueError, "hour out of range");
+ return NULL;
+ }
+ if (buf.tm_min < 0 || buf.tm_min > 59) {
+ PyErr_SetString(PyExc_ValueError, "minute out of range");
+ return NULL;
+ }
+ if (buf.tm_sec < 0 || buf.tm_sec > 61) {
+ PyErr_SetString(PyExc_ValueError, "seconds out of range");
+ return NULL;
+ }
+ /* tm_wday does not need checking of its upper-bound since taking
+ ``% 7`` in gettmarg() automatically restricts the range. */
+ if (buf.tm_wday < 0) {
+ PyErr_SetString(PyExc_ValueError, "day of week out of range");
+ return NULL;
+ }
+ if (buf.tm_yday == -1)
+ buf.tm_yday = 0;
+ else if (buf.tm_yday < 0 || buf.tm_yday > 365) {
+ PyErr_SetString(PyExc_ValueError, "day of year out of range");
+ return NULL;
+ }
+ /* Normalize tm_isdst just in case someone foolishly implements %Z
+ based on the assumption that tm_isdst falls within the range of
+ [-1, 1] */
+ if (buf.tm_isdst < -1)
+ buf.tm_isdst = -1;
+ else if (buf.tm_isdst > 1)
+ buf.tm_isdst = 1;
#ifdef MS_WINDOWS
- /* check that the format string contains only valid directives */
- for(outbuf = strchr(fmt, '%');
- outbuf != NULL;
- outbuf = strchr(outbuf+2, '%'))
- {
- if (outbuf[1]=='#')
- ++outbuf; /* not documented by python, */
- if (outbuf[1]=='\0' ||
- !strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
- {
- PyErr_SetString(PyExc_ValueError, "Invalid format string");
- return 0;
- }
- }
+ /* check that the format string contains only valid directives */
+ for(outbuf = strchr(fmt, '%');
+ outbuf != NULL;
+ outbuf = strchr(outbuf+2, '%'))
+ {
+ if (outbuf[1]=='#')
+ ++outbuf; /* not documented by python, */
+ if (outbuf[1]=='\0' ||
+ !strchr("aAbBcdfHIjmMpSUwWxXyYzZ%", outbuf[1]))
+ {
+ PyErr_SetString(PyExc_ValueError, "Invalid format string");
+ return 0;
+ }
+ }
#endif
- fmtlen = strlen(fmt);
-
- /* I hate these functions that presume you know how big the output
- * will be ahead of time...
- */
- for (i = 1024; ; i += i) {
- outbuf = (char *)malloc(i);
- if (outbuf == NULL) {
- return PyErr_NoMemory();
- }
- buflen = strftime(outbuf, i, fmt, &buf);
- if (buflen > 0 || i >= 256 * fmtlen) {
- /* If the buffer is 256 times as long as the format,
- it's probably not failing for lack of room!
- More likely, the format yields an empty result,
- e.g. an empty format, or %Z when the timezone
- is unknown. */
- PyObject *ret;
- ret = PyString_FromStringAndSize(outbuf, buflen);
- free(outbuf);
- return ret;
- }
- free(outbuf);
+ fmtlen = strlen(fmt);
+
+ /* I hate these functions that presume you know how big the output
+ * will be ahead of time...
+ */
+ for (i = 1024; ; i += i) {
+ outbuf = (char *)malloc(i);
+ if (outbuf == NULL) {
+ return PyErr_NoMemory();
+ }
+ buflen = strftime(outbuf, i, fmt, &buf);
+ if (buflen > 0 || i >= 256 * fmtlen) {
+ /* If the buffer is 256 times as long as the format,
+ it's probably not failing for lack of room!
+ More likely, the format yields an empty result,
+ e.g. an empty format, or %Z when the timezone
+ is unknown. */
+ PyObject *ret;
+ ret = PyString_FromStringAndSize(outbuf, buflen);
+ free(outbuf);
+ return ret;
+ }
+ free(outbuf);
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
- /* VisualStudio .NET 2005 does this properly */
- if (buflen == 0 && errno == EINVAL) {
- PyErr_SetString(PyExc_ValueError, "Invalid format string");
- return 0;
- }
+ /* VisualStudio .NET 2005 does this properly */
+ if (buflen == 0 && errno == EINVAL) {
+ PyErr_SetString(PyExc_ValueError, "Invalid format string");
+ return 0;
+ }
#endif
-
- }
+
+ }
}
PyDoc_STRVAR(strftime_doc,
@@ -534,15 +534,15 @@ is not present, current time as returned by localtime() is used.");
static PyObject *
time_strptime(PyObject *self, PyObject *args)
{
- PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
- PyObject *strptime_result;
-
- if (!strptime_module)
- return NULL;
- strptime_result = PyObject_CallMethod(strptime_module,
- "_strptime_time", "O", args);
- Py_DECREF(strptime_module);
- return strptime_result;
+ PyObject *strptime_module = PyImport_ImportModuleNoBlock("_strptime");
+ PyObject *strptime_result;
+
+ if (!strptime_module)
+ return NULL;
+ strptime_result = PyObject_CallMethod(strptime_module,
+ "_strptime_time", "O", args);
+ Py_DECREF(strptime_module);
+ return strptime_result;
}
PyDoc_STRVAR(strptime_doc,
@@ -555,20 +555,20 @@ See the library reference manual for formatting codes (same as strftime()).");
static PyObject *
time_asctime(PyObject *self, PyObject *args)
{
- PyObject *tup = NULL;
- struct tm buf;
- char *p;
- if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
- return NULL;
- if (tup == NULL) {
- time_t tt = time(NULL);
- buf = *localtime(&tt);
- } else if (!gettmarg(tup, &buf))
- return NULL;
- p = asctime(&buf);
- if (p[24] == '\n')
- p[24] = '\0';
- return PyString_FromString(p);
+ PyObject *tup = NULL;
+ struct tm buf;
+ char *p;
+ if (!PyArg_UnpackTuple(args, "asctime", 0, 1, &tup))
+ return NULL;
+ if (tup == NULL) {
+ time_t tt = time(NULL);
+ buf = *localtime(&tt);
+ } else if (!gettmarg(tup, &buf))
+ return NULL;
+ p = asctime(&buf);
+ if (p[24] == '\n')
+ p[24] = '\0';
+ return PyString_FromString(p);
}
PyDoc_STRVAR(asctime_doc,
@@ -581,30 +581,30 @@ is used.");
static PyObject *
time_ctime(PyObject *self, PyObject *args)
{
- PyObject *ot = NULL;
- time_t tt;
- char *p;
-
- if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
- return NULL;
- if (ot == NULL || ot == Py_None)
- tt = time(NULL);
- else {
- double dt = PyFloat_AsDouble(ot);
- if (PyErr_Occurred())
- return NULL;
- tt = _PyTime_DoubleToTimet(dt);
- if (tt == (time_t)-1 && PyErr_Occurred())
- return NULL;
- }
- p = ctime(&tt);
- if (p == NULL) {
- PyErr_SetString(PyExc_ValueError, "unconvertible time");
- return NULL;
- }
- if (p[24] == '\n')
- p[24] = '\0';
- return PyString_FromString(p);
+ PyObject *ot = NULL;
+ time_t tt;
+ char *p;
+
+ if (!PyArg_UnpackTuple(args, "ctime", 0, 1, &ot))
+ return NULL;
+ if (ot == NULL || ot == Py_None)
+ tt = time(NULL);
+ else {
+ double dt = PyFloat_AsDouble(ot);
+ if (PyErr_Occurred())
+ return NULL;
+ tt = _PyTime_DoubleToTimet(dt);
+ if (tt == (time_t)-1 && PyErr_Occurred())
+ return NULL;
+ }
+ p = ctime(&tt);
+ if (p == NULL) {
+ PyErr_SetString(PyExc_ValueError, "unconvertible time");
+ return NULL;
+ }
+ if (p[24] == '\n')
+ p[24] = '\0';
+ return PyString_FromString(p);
}
PyDoc_STRVAR(ctime_doc,
@@ -618,17 +618,17 @@ not present, current time as returned by localtime() is used.");
static PyObject *
time_mktime(PyObject *self, PyObject *tup)
{
- struct tm buf;
- time_t tt;
- if (!gettmarg(tup, &buf))
- return NULL;
- tt = mktime(&buf);
- if (tt == (time_t)(-1)) {
- PyErr_SetString(PyExc_OverflowError,
- "mktime argument out of range");
- return NULL;
- }
- return PyFloat_FromDouble((double)tt);
+ struct tm buf;
+ time_t tt;
+ if (!gettmarg(tup, &buf))
+ return NULL;
+ tt = mktime(&buf);
+ if (tt == (time_t)(-1)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "mktime argument out of range");
+ return NULL;
+ }
+ return PyFloat_FromDouble((double)tt);
}
PyDoc_STRVAR(mktime_doc,
@@ -643,21 +643,21 @@ static void inittimezone(PyObject *module);
static PyObject *
time_tzset(PyObject *self, PyObject *unused)
{
- PyObject* m;
+ PyObject* m;
- m = PyImport_ImportModuleNoBlock("time");
- if (m == NULL) {
- return NULL;
- }
+ m = PyImport_ImportModuleNoBlock("time");
+ if (m == NULL) {
+ return NULL;
+ }
- tzset();
+ tzset();
- /* Reset timezone, altzone, daylight and tzname */
- inittimezone(m);
- Py_DECREF(m);
+ /* Reset timezone, altzone, daylight and tzname */
+ inittimezone(m);
+ Py_DECREF(m);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(tzset_doc,
@@ -677,113 +677,113 @@ should not be relied on.");
static void
inittimezone(PyObject *m) {
/* This code moved from inittime wholesale to allow calling it from
- time_tzset. In the future, some parts of it can be moved back
- (for platforms that don't HAVE_WORKING_TZSET, when we know what they
- are), and the extraneous calls to tzset(3) should be removed.
- I haven't done this yet, as I don't want to change this code as
- little as possible when introducing the time.tzset and time.tzsetwall
- methods. This should simply be a method of doing the following once,
- at the top of this function and removing the call to tzset() from
- time_tzset():
-
- #ifdef HAVE_TZSET
- tzset()
- #endif
-
- And I'm lazy and hate C so nyer.
+ time_tzset. In the future, some parts of it can be moved back
+ (for platforms that don't HAVE_WORKING_TZSET, when we know what they
+ are), and the extraneous calls to tzset(3) should be removed.
+ I haven't done this yet, as I don't want to change this code as
+ little as possible when introducing the time.tzset and time.tzsetwall
+ methods. This should simply be a method of doing the following once,
+ at the top of this function and removing the call to tzset() from
+ time_tzset():
+
+ #ifdef HAVE_TZSET
+ tzset()
+ #endif
+
+ And I'm lazy and hate C so nyer.
*/
#if defined(HAVE_TZNAME) && !defined(__GLIBC__) && !defined(__CYGWIN__)
- tzset();
+ tzset();
#ifdef PYOS_OS2
- PyModule_AddIntConstant(m, "timezone", _timezone);
+ PyModule_AddIntConstant(m, "timezone", _timezone);
#else /* !PYOS_OS2 */
- PyModule_AddIntConstant(m, "timezone", timezone);
+ PyModule_AddIntConstant(m, "timezone", timezone);
#endif /* PYOS_OS2 */
#ifdef HAVE_ALTZONE
- PyModule_AddIntConstant(m, "altzone", altzone);
+ PyModule_AddIntConstant(m, "altzone", altzone);
#else
#ifdef PYOS_OS2
- PyModule_AddIntConstant(m, "altzone", _timezone-3600);
+ PyModule_AddIntConstant(m, "altzone", _timezone-3600);
#else /* !PYOS_OS2 */
- PyModule_AddIntConstant(m, "altzone", timezone-3600);
+ PyModule_AddIntConstant(m, "altzone", timezone-3600);
#endif /* PYOS_OS2 */
#endif
- PyModule_AddIntConstant(m, "daylight", daylight);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)", tzname[0], tzname[1]));
+ PyModule_AddIntConstant(m, "daylight", daylight);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)", tzname[0], tzname[1]));
#else /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
#ifdef HAVE_STRUCT_TM_TM_ZONE
- {
+ {
#define YEAR ((time_t)((365 * 24 + 6) * 3600))
- time_t t;
- struct tm *p;
- long janzone, julyzone;
- char janname[10], julyname[10];
- t = (time((time_t *)0) / YEAR) * YEAR;
- p = localtime(&t);
- janzone = -p->tm_gmtoff;
- strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
- janname[9] = '\0';
- t += YEAR/2;
- p = localtime(&t);
- julyzone = -p->tm_gmtoff;
- strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
- julyname[9] = '\0';
-
- if( janzone < julyzone ) {
- /* DST is reversed in the southern hemisphere */
- PyModule_AddIntConstant(m, "timezone", julyzone);
- PyModule_AddIntConstant(m, "altzone", janzone);
- PyModule_AddIntConstant(m, "daylight",
- janzone != julyzone);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)",
- julyname, janname));
- } else {
- PyModule_AddIntConstant(m, "timezone", janzone);
- PyModule_AddIntConstant(m, "altzone", julyzone);
- PyModule_AddIntConstant(m, "daylight",
- janzone != julyzone);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)",
- janname, julyname));
- }
- }
+ time_t t;
+ struct tm *p;
+ long janzone, julyzone;
+ char janname[10], julyname[10];
+ t = (time((time_t *)0) / YEAR) * YEAR;
+ p = localtime(&t);
+ janzone = -p->tm_gmtoff;
+ strncpy(janname, p->tm_zone ? p->tm_zone : " ", 9);
+ janname[9] = '\0';
+ t += YEAR/2;
+ p = localtime(&t);
+ julyzone = -p->tm_gmtoff;
+ strncpy(julyname, p->tm_zone ? p->tm_zone : " ", 9);
+ julyname[9] = '\0';
+
+ if( janzone < julyzone ) {
+ /* DST is reversed in the southern hemisphere */
+ PyModule_AddIntConstant(m, "timezone", julyzone);
+ PyModule_AddIntConstant(m, "altzone", janzone);
+ PyModule_AddIntConstant(m, "daylight",
+ janzone != julyzone);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)",
+ julyname, janname));
+ } else {
+ PyModule_AddIntConstant(m, "timezone", janzone);
+ PyModule_AddIntConstant(m, "altzone", julyzone);
+ PyModule_AddIntConstant(m, "daylight",
+ janzone != julyzone);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)",
+ janname, julyname));
+ }
+ }
#else
#endif /* HAVE_STRUCT_TM_TM_ZONE */
#ifdef __CYGWIN__
- tzset();
- PyModule_AddIntConstant(m, "timezone", _timezone);
- PyModule_AddIntConstant(m, "altzone", _timezone-3600);
- PyModule_AddIntConstant(m, "daylight", _daylight);
- PyModule_AddObject(m, "tzname",
- Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
+ tzset();
+ PyModule_AddIntConstant(m, "timezone", _timezone);
+ PyModule_AddIntConstant(m, "altzone", _timezone-3600);
+ PyModule_AddIntConstant(m, "daylight", _daylight);
+ PyModule_AddObject(m, "tzname",
+ Py_BuildValue("(zz)", _tzname[0], _tzname[1]));
#endif /* __CYGWIN__ */
#endif /* !HAVE_TZNAME || __GLIBC__ || __CYGWIN__*/
}
static PyMethodDef time_methods[] = {
- {"time", time_time, METH_NOARGS, time_doc},
+ {"time", time_time, METH_NOARGS, time_doc},
#ifdef HAVE_CLOCK
- {"clock", time_clock, METH_NOARGS, clock_doc},
+ {"clock", time_clock, METH_NOARGS, clock_doc},
#endif
- {"sleep", time_sleep, METH_VARARGS, sleep_doc},
- {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
- {"localtime", time_localtime, METH_VARARGS, localtime_doc},
- {"asctime", time_asctime, METH_VARARGS, asctime_doc},
- {"ctime", time_ctime, METH_VARARGS, ctime_doc},
+ {"sleep", time_sleep, METH_VARARGS, sleep_doc},
+ {"gmtime", time_gmtime, METH_VARARGS, gmtime_doc},
+ {"localtime", time_localtime, METH_VARARGS, localtime_doc},
+ {"asctime", time_asctime, METH_VARARGS, asctime_doc},
+ {"ctime", time_ctime, METH_VARARGS, ctime_doc},
#ifdef HAVE_MKTIME
- {"mktime", time_mktime, METH_O, mktime_doc},
+ {"mktime", time_mktime, METH_O, mktime_doc},
#endif
#ifdef HAVE_STRFTIME
- {"strftime", time_strftime, METH_VARARGS, strftime_doc},
+ {"strftime", time_strftime, METH_VARARGS, strftime_doc},
#endif
- {"strptime", time_strptime, METH_VARARGS, strptime_doc},
+ {"strptime", time_strptime, METH_VARARGS, strptime_doc},
#ifdef HAVE_WORKING_TZSET
- {"tzset", time_tzset, METH_NOARGS, tzset_doc},
+ {"tzset", time_tzset, METH_NOARGS, tzset_doc},
#endif
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
@@ -836,38 +836,38 @@ tzset() -- change the local timezone");
PyMODINIT_FUNC
inittime(void)
{
- PyObject *m;
- char *p;
- m = Py_InitModule3("time", time_methods, module_doc);
- if (m == NULL)
- return;
-
- /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
- p = Py_GETENV("PYTHONY2K");
- PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
- /* Squirrel away the module's dictionary for the y2k check */
- moddict = PyModule_GetDict(m);
- Py_INCREF(moddict);
-
- /* Set, or reset, module variables like time.timezone */
- inittimezone(m);
+ PyObject *m;
+ char *p;
+ m = Py_InitModule3("time", time_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ /* Accept 2-digit dates unless PYTHONY2K is set and non-empty */
+ p = Py_GETENV("PYTHONY2K");
+ PyModule_AddIntConstant(m, "accept2dyear", (long) (!p || !*p));
+ /* Squirrel away the module's dictionary for the y2k check */
+ moddict = PyModule_GetDict(m);
+ Py_INCREF(moddict);
+
+ /* Set, or reset, module variables like time.timezone */
+ inittimezone(m);
#ifdef MS_WINDOWS
- /* Helper to allow interrupts for Windows.
- If Ctrl+C event delivered while not sleeping
- it will be ignored.
- */
- main_thread = PyThread_get_thread_ident();
- hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
- SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
+ /* Helper to allow interrupts for Windows.
+ If Ctrl+C event delivered while not sleeping
+ it will be ignored.
+ */
+ main_thread = PyThread_get_thread_ident();
+ hInterruptEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
+ SetConsoleCtrlHandler( PyCtrlHandler, TRUE);
#endif /* MS_WINDOWS */
- if (!initialized) {
- PyStructSequence_InitType(&StructTimeType,
- &struct_time_type_desc);
- }
- Py_INCREF(&StructTimeType);
- PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
- initialized = 1;
+ if (!initialized) {
+ PyStructSequence_InitType(&StructTimeType,
+ &struct_time_type_desc);
+ }
+ Py_INCREF(&StructTimeType);
+ PyModule_AddObject(m, "struct_time", (PyObject*) &StructTimeType);
+ initialized = 1;
}
@@ -876,38 +876,38 @@ inittime(void)
static double
floattime(void)
{
- /* There are three ways to get the time:
- (1) gettimeofday() -- resolution in microseconds
- (2) ftime() -- resolution in milliseconds
- (3) time() -- resolution in seconds
- In all cases the return value is a float in seconds.
- Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
- fail, so we fall back on ftime() or time().
- Note: clock resolution does not imply clock accuracy! */
+ /* There are three ways to get the time:
+ (1) gettimeofday() -- resolution in microseconds
+ (2) ftime() -- resolution in milliseconds
+ (3) time() -- resolution in seconds
+ In all cases the return value is a float in seconds.
+ Since on some systems (e.g. SCO ODT 3.0) gettimeofday() may
+ fail, so we fall back on ftime() or time().
+ Note: clock resolution does not imply clock accuracy! */
#ifdef HAVE_GETTIMEOFDAY
- {
- struct timeval t;
+ {
+ struct timeval t;
#ifdef GETTIMEOFDAY_NO_TZ
- if (gettimeofday(&t) == 0)
- return (double)t.tv_sec + t.tv_usec*0.000001;
+ if (gettimeofday(&t) == 0)
+ return (double)t.tv_sec + t.tv_usec*0.000001;
#else /* !GETTIMEOFDAY_NO_TZ */
- if (gettimeofday(&t, (struct timezone *)NULL) == 0)
- return (double)t.tv_sec + t.tv_usec*0.000001;
+ if (gettimeofday(&t, (struct timezone *)NULL) == 0)
+ return (double)t.tv_sec + t.tv_usec*0.000001;
#endif /* !GETTIMEOFDAY_NO_TZ */
- }
+ }
#endif /* !HAVE_GETTIMEOFDAY */
- {
+ {
#if defined(HAVE_FTIME)
- struct timeb t;
- ftime(&t);
- return (double)t.time + (double)t.millitm * (double)0.001;
+ struct timeb t;
+ ftime(&t);
+ return (double)t.time + (double)t.millitm * (double)0.001;
#else /* !HAVE_FTIME */
- time_t secs;
- time(&secs);
- return (double)secs;
+ time_t secs;
+ time(&secs);
+ return (double)secs;
#endif /* !HAVE_FTIME */
- }
+ }
}
@@ -920,122 +920,122 @@ floatsleep(double secs)
{
/* XXX Should test for MS_WINDOWS first! */
#if defined(HAVE_SELECT) && !defined(__BEOS__) && !defined(__EMX__)
- struct timeval t;
- double frac;
- frac = fmod(secs, 1.0);
- secs = floor(secs);
- t.tv_sec = (long)secs;
- t.tv_usec = (long)(frac*1000000.0);
- Py_BEGIN_ALLOW_THREADS
- if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
+ struct timeval t;
+ double frac;
+ frac = fmod(secs, 1.0);
+ secs = floor(secs);
+ t.tv_sec = (long)secs;
+ t.tv_usec = (long)(frac*1000000.0);
+ Py_BEGIN_ALLOW_THREADS
+ if (select(0, (fd_set *)0, (fd_set *)0, (fd_set *)0, &t) != 0) {
#ifdef EINTR
- if (errno != EINTR) {
+ if (errno != EINTR) {
#else
- if (1) {
+ if (1) {
#endif
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- }
- Py_END_ALLOW_THREADS
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ }
+ Py_END_ALLOW_THREADS
#elif defined(__WATCOMC__) && !defined(__QNX__)
- /* XXX Can't interrupt this sleep */
- Py_BEGIN_ALLOW_THREADS
- delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
- Py_END_ALLOW_THREADS
+ /* XXX Can't interrupt this sleep */
+ Py_BEGIN_ALLOW_THREADS
+ delay((int)(secs * 1000 + 0.5)); /* delay() uses milliseconds */
+ Py_END_ALLOW_THREADS
#elif defined(MS_WINDOWS)
- {
- double millisecs = secs * 1000.0;
- unsigned long ul_millis;
-
- if (millisecs > (double)ULONG_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "sleep length is too large");
- return -1;
- }
- Py_BEGIN_ALLOW_THREADS
- /* Allow sleep(0) to maintain win32 semantics, and as decreed
- * by Guido, only the main thread can be interrupted.
- */
- ul_millis = (unsigned long)millisecs;
- if (ul_millis == 0 ||
- main_thread != PyThread_get_thread_ident())
- Sleep(ul_millis);
- else {
- DWORD rc;
- ResetEvent(hInterruptEvent);
- rc = WaitForSingleObject(hInterruptEvent, ul_millis);
- if (rc == WAIT_OBJECT_0) {
- /* Yield to make sure real Python signal
- * handler called.
- */
- Sleep(1);
- Py_BLOCK_THREADS
- errno = EINTR;
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- }
- Py_END_ALLOW_THREADS
- }
+ {
+ double millisecs = secs * 1000.0;
+ unsigned long ul_millis;
+
+ if (millisecs > (double)ULONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "sleep length is too large");
+ return -1;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ /* Allow sleep(0) to maintain win32 semantics, and as decreed
+ * by Guido, only the main thread can be interrupted.
+ */
+ ul_millis = (unsigned long)millisecs;
+ if (ul_millis == 0 ||
+ main_thread != PyThread_get_thread_ident())
+ Sleep(ul_millis);
+ else {
+ DWORD rc;
+ ResetEvent(hInterruptEvent);
+ rc = WaitForSingleObject(hInterruptEvent, ul_millis);
+ if (rc == WAIT_OBJECT_0) {
+ /* Yield to make sure real Python signal
+ * handler called.
+ */
+ Sleep(1);
+ Py_BLOCK_THREADS
+ errno = EINTR;
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ }
+ Py_END_ALLOW_THREADS
+ }
#elif defined(PYOS_OS2)
- /* This Sleep *IS* Interruptable by Exceptions */
- Py_BEGIN_ALLOW_THREADS
- if (DosSleep(secs * 1000) != NO_ERROR) {
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- Py_END_ALLOW_THREADS
+ /* This Sleep *IS* Interruptable by Exceptions */
+ Py_BEGIN_ALLOW_THREADS
+ if (DosSleep(secs * 1000) != NO_ERROR) {
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ Py_END_ALLOW_THREADS
#elif defined(__BEOS__)
- /* This sleep *CAN BE* interrupted. */
- {
- if( secs <= 0.0 ) {
- return;
- }
-
- Py_BEGIN_ALLOW_THREADS
- /* BeOS snooze() is in microseconds... */
- if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
- Py_BLOCK_THREADS
- PyErr_SetFromErrno( PyExc_IOError );
- return -1;
- }
- Py_END_ALLOW_THREADS
- }
+ /* This sleep *CAN BE* interrupted. */
+ {
+ if( secs <= 0.0 ) {
+ return;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ /* BeOS snooze() is in microseconds... */
+ if( snooze( (bigtime_t)( secs * 1000.0 * 1000.0 ) ) == B_INTERRUPTED ) {
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno( PyExc_IOError );
+ return -1;
+ }
+ Py_END_ALLOW_THREADS
+ }
#elif defined(RISCOS)
- if (secs <= 0.0)
- return 0;
- Py_BEGIN_ALLOW_THREADS
- /* This sleep *CAN BE* interrupted. */
- if ( riscos_sleep(secs) )
- return -1;
- Py_END_ALLOW_THREADS
+ if (secs <= 0.0)
+ return 0;
+ Py_BEGIN_ALLOW_THREADS
+ /* This sleep *CAN BE* interrupted. */
+ if ( riscos_sleep(secs) )
+ return -1;
+ Py_END_ALLOW_THREADS
#elif defined(PLAN9)
- {
- double millisecs = secs * 1000.0;
- if (millisecs > (double)LONG_MAX) {
- PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
- return -1;
- }
- /* This sleep *CAN BE* interrupted. */
- Py_BEGIN_ALLOW_THREADS
- if(sleep((long)millisecs) < 0){
- Py_BLOCK_THREADS
- PyErr_SetFromErrno(PyExc_IOError);
- return -1;
- }
- Py_END_ALLOW_THREADS
- }
+ {
+ double millisecs = secs * 1000.0;
+ if (millisecs > (double)LONG_MAX) {
+ PyErr_SetString(PyExc_OverflowError, "sleep length is too large");
+ return -1;
+ }
+ /* This sleep *CAN BE* interrupted. */
+ Py_BEGIN_ALLOW_THREADS
+ if(sleep((long)millisecs) < 0){
+ Py_BLOCK_THREADS
+ PyErr_SetFromErrno(PyExc_IOError);
+ return -1;
+ }
+ Py_END_ALLOW_THREADS
+ }
#else
- /* XXX Can't interrupt this sleep */
- Py_BEGIN_ALLOW_THREADS
- sleep((int)secs);
- Py_END_ALLOW_THREADS
+ /* XXX Can't interrupt this sleep */
+ Py_BEGIN_ALLOW_THREADS
+ sleep((int)secs);
+ Py_END_ALLOW_THREADS
#endif
- return 0;
+ return 0;
}
diff --git a/Modules/timingmodule.c b/Modules/timingmodule.c
index 0da5c6b..a4e2c7e 100644
--- a/Modules/timingmodule.c
+++ b/Modules/timingmodule.c
@@ -10,45 +10,45 @@
static PyObject *
start_timing(PyObject *self)
{
- Py_INCREF(Py_None);
- BEGINTIMING;
- return Py_None;
+ Py_INCREF(Py_None);
+ BEGINTIMING;
+ return Py_None;
}
static PyObject *
finish_timing(PyObject *self)
{
- ENDTIMING
- Py_INCREF(Py_None);
- return Py_None;
+ ENDTIMING
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
seconds(PyObject *self)
{
- return PyInt_FromLong(TIMINGS);
+ return PyInt_FromLong(TIMINGS);
}
static PyObject *
milli(PyObject *self)
{
- return PyInt_FromLong(TIMINGMS);
+ return PyInt_FromLong(TIMINGMS);
}
static PyObject *
micro(PyObject *self)
{
- return PyInt_FromLong(TIMINGUS);
+ return PyInt_FromLong(TIMINGUS);
}
static PyMethodDef timing_methods[] = {
- {"start", (PyCFunction)start_timing, METH_NOARGS},
- {"finish", (PyCFunction)finish_timing, METH_NOARGS},
- {"seconds", (PyCFunction)seconds, METH_NOARGS},
- {"milli", (PyCFunction)milli, METH_NOARGS},
- {"micro", (PyCFunction)micro, METH_NOARGS},
- {NULL, NULL}
+ {"start", (PyCFunction)start_timing, METH_NOARGS},
+ {"finish", (PyCFunction)finish_timing, METH_NOARGS},
+ {"seconds", (PyCFunction)seconds, METH_NOARGS},
+ {"milli", (PyCFunction)milli, METH_NOARGS},
+ {"micro", (PyCFunction)micro, METH_NOARGS},
+ {NULL, NULL}
};
@@ -56,7 +56,7 @@ PyMODINIT_FUNC inittiming(void)
{
if (PyErr_WarnPy3k("the timing module has been removed in "
"Python 3.0; use time.clock() instead", 2) < 0)
- return;
-
- (void)Py_InitModule("timing", timing_methods);
+ return;
+
+ (void)Py_InitModule("timing", timing_methods);
}
diff --git a/Modules/tkappinit.c b/Modules/tkappinit.c
index 353abcc..c1f97b0 100644
--- a/Modules/tkappinit.c
+++ b/Modules/tkappinit.c
@@ -26,154 +26,154 @@ static int tk_load_failed;
int
Tcl_AppInit(Tcl_Interp *interp)
{
- Tk_Window main_window;
- const char *_tkinter_skip_tk_init;
+ Tk_Window main_window;
+ const char *_tkinter_skip_tk_init;
#ifdef TKINTER_PROTECT_LOADTK
- const char *_tkinter_tk_failed;
+ const char *_tkinter_tk_failed;
#endif
#ifdef TK_AQUA
#ifndef MAX_PATH_LEN
#define MAX_PATH_LEN 1024
#endif
- char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN];
- Tcl_Obj* pathPtr;
+ char tclLibPath[MAX_PATH_LEN], tkLibPath[MAX_PATH_LEN];
+ Tcl_Obj* pathPtr;
- /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */
- Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary",
- tclLibPath, MAX_PATH_LEN, 0);
+ /* pre- Tcl_Init code copied from tkMacOSXAppInit.c */
+ Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tcllibrary",
+ tclLibPath, MAX_PATH_LEN, 0);
- if (tclLibPath[0] != '\0') {
- Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
- }
+ if (tclLibPath[0] != '\0') {
+ Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
+ }
- if (tclLibPath[0] != '\0') {
- Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
- Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
- }
+ if (tclLibPath[0] != '\0') {
+ Tcl_SetVar(interp, "tcl_library", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tclDefaultLibrary", tclLibPath, TCL_GLOBAL_ONLY);
+ Tcl_SetVar(interp, "tcl_pkgPath", tclLibPath, TCL_GLOBAL_ONLY);
+ }
#endif
- if (Tcl_Init (interp) == TCL_ERROR)
- return TCL_ERROR;
+ if (Tcl_Init (interp) == TCL_ERROR)
+ return TCL_ERROR;
#ifdef TK_AQUA
- /* pre- Tk_Init code copied from tkMacOSXAppInit.c */
- Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary",
- tkLibPath, MAX_PATH_LEN, 1);
+ /* pre- Tk_Init code copied from tkMacOSXAppInit.c */
+ Tk_MacOSXOpenBundleResources (interp, "com.tcltk.tklibrary",
+ tkLibPath, MAX_PATH_LEN, 1);
- if (tclLibPath[0] != '\0') {
- pathPtr = Tcl_NewStringObj(tclLibPath, -1);
- } else {
- Tcl_Obj *pathPtr = TclGetLibraryPath();
- }
+ if (tclLibPath[0] != '\0') {
+ pathPtr = Tcl_NewStringObj(tclLibPath, -1);
+ } else {
+ Tcl_Obj *pathPtr = TclGetLibraryPath();
+ }
- if (tkLibPath[0] != '\0') {
- Tcl_Obj *objPtr;
+ if (tkLibPath[0] != '\0') {
+ Tcl_Obj *objPtr;
- Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY);
- objPtr = Tcl_NewStringObj(tkLibPath, -1);
- Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
- }
+ Tcl_SetVar(interp, "tk_library", tkLibPath, TCL_GLOBAL_ONLY);
+ objPtr = Tcl_NewStringObj(tkLibPath, -1);
+ Tcl_ListObjAppendElement(NULL, pathPtr, objPtr);
+ }
- TclSetLibraryPath(pathPtr);
+ TclSetLibraryPath(pathPtr);
#endif
#ifdef WITH_XXX
- /* Initialize modules that don't require Tk */
+ /* Initialize modules that don't require Tk */
#endif
- _tkinter_skip_tk_init = Tcl_GetVar(interp,
- "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
- if (_tkinter_skip_tk_init != NULL &&
- strcmp(_tkinter_skip_tk_init, "1") == 0) {
- return TCL_OK;
- }
+ _tkinter_skip_tk_init = Tcl_GetVar(interp,
+ "_tkinter_skip_tk_init", TCL_GLOBAL_ONLY);
+ if (_tkinter_skip_tk_init != NULL &&
+ strcmp(_tkinter_skip_tk_init, "1") == 0) {
+ return TCL_OK;
+ }
#ifdef TKINTER_PROTECT_LOADTK
- _tkinter_tk_failed = Tcl_GetVar(interp,
- "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
+ _tkinter_tk_failed = Tcl_GetVar(interp,
+ "_tkinter_tk_failed", TCL_GLOBAL_ONLY);
- if (tk_load_failed || (
- _tkinter_tk_failed != NULL &&
- strcmp(_tkinter_tk_failed, "1") == 0)) {
- Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC);
- return TCL_ERROR;
- }
+ if (tk_load_failed || (
+ _tkinter_tk_failed != NULL &&
+ strcmp(_tkinter_tk_failed, "1") == 0)) {
+ Tcl_SetResult(interp, TKINTER_LOADTK_ERRMSG, TCL_STATIC);
+ return TCL_ERROR;
+ }
#endif
- if (Tk_Init(interp) == TCL_ERROR) {
+ if (Tk_Init(interp) == TCL_ERROR) {
#ifdef TKINTER_PROTECT_LOADTK
- tk_load_failed = 1;
- Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
+ tk_load_failed = 1;
+ Tcl_SetVar(interp, "_tkinter_tk_failed", "1", TCL_GLOBAL_ONLY);
#endif
- return TCL_ERROR;
- }
+ return TCL_ERROR;
+ }
- main_window = Tk_MainWindow(interp);
+ main_window = Tk_MainWindow(interp);
#ifdef TK_AQUA
- TkMacOSXInitAppleEvents(interp);
- TkMacOSXInitMenus(interp);
+ TkMacOSXInitAppleEvents(interp);
+ TkMacOSXInitMenus(interp);
#endif
#ifdef WITH_MOREBUTTONS
- {
- extern Tcl_CmdProc studButtonCmd;
- extern Tcl_CmdProc triButtonCmd;
+ {
+ extern Tcl_CmdProc studButtonCmd;
+ extern Tcl_CmdProc triButtonCmd;
- Tcl_CreateCommand(interp, "studbutton", studButtonCmd,
- (ClientData) main_window, NULL);
- Tcl_CreateCommand(interp, "tributton", triButtonCmd,
- (ClientData) main_window, NULL);
- }
+ Tcl_CreateCommand(interp, "studbutton", studButtonCmd,
+ (ClientData) main_window, NULL);
+ Tcl_CreateCommand(interp, "tributton", triButtonCmd,
+ (ClientData) main_window, NULL);
+ }
#endif
#ifdef WITH_PIL /* 0.2b5 and later -- not yet released as of May 14 */
- {
- extern void TkImaging_Init(Tcl_Interp *);
- TkImaging_Init(interp);
- /* XXX TkImaging_Init() doesn't have the right return type */
- /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
- }
+ {
+ extern void TkImaging_Init(Tcl_Interp *);
+ TkImaging_Init(interp);
+ /* XXX TkImaging_Init() doesn't have the right return type */
+ /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
+ }
#endif
#ifdef WITH_PIL_OLD /* 0.2b4 and earlier */
- {
- extern void TkImaging_Init(void);
- /* XXX TkImaging_Init() doesn't have the right prototype */
- /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
- }
+ {
+ extern void TkImaging_Init(void);
+ /* XXX TkImaging_Init() doesn't have the right prototype */
+ /*Tcl_StaticPackage(interp, "Imaging", TkImaging_Init, NULL);*/
+ }
#endif
#ifdef WITH_TIX
- {
- extern int Tix_Init(Tcl_Interp *interp);
- extern int Tix_SafeInit(Tcl_Interp *interp);
- Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit);
- }
+ {
+ extern int Tix_Init(Tcl_Interp *interp);
+ extern int Tix_SafeInit(Tcl_Interp *interp);
+ Tcl_StaticPackage(NULL, "Tix", Tix_Init, Tix_SafeInit);
+ }
#endif
#ifdef WITH_BLT
- {
- extern int Blt_Init(Tcl_Interp *);
- extern int Blt_SafeInit(Tcl_Interp *);
- Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit);
- }
+ {
+ extern int Blt_Init(Tcl_Interp *);
+ extern int Blt_SafeInit(Tcl_Interp *);
+ Tcl_StaticPackage(NULL, "Blt", Blt_Init, Blt_SafeInit);
+ }
#endif
#ifdef WITH_TOGL
- {
- /* XXX I've heard rumors that this doesn't work */
- extern int Togl_Init(Tcl_Interp *);
- /* XXX Is there no Togl_SafeInit? */
- Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL);
- }
+ {
+ /* XXX I've heard rumors that this doesn't work */
+ extern int Togl_Init(Tcl_Interp *);
+ /* XXX Is there no Togl_SafeInit? */
+ Tcl_StaticPackage(NULL, "Togl", Togl_Init, NULL);
+ }
#endif
#ifdef WITH_XXX
#endif
- return TCL_OK;
+ return TCL_OK;
}
diff --git a/Modules/unicodedata.c b/Modules/unicodedata.c
index ede57cb..77f3637 100644
--- a/Modules/unicodedata.c
+++ b/Modules/unicodedata.c
@@ -19,14 +19,14 @@
/* character properties */
typedef struct {
- const unsigned char category; /* index into
- _PyUnicode_CategoryNames */
- const unsigned char combining; /* combining class value 0 - 255 */
- const unsigned char bidirectional; /* index into
- _PyUnicode_BidirectionalNames */
- const unsigned char mirrored; /* true if mirrored in bidir mode */
- const unsigned char east_asian_width; /* index into
- _PyUnicode_EastAsianWidth */
+ const unsigned char category; /* index into
+ _PyUnicode_CategoryNames */
+ const unsigned char combining; /* combining class value 0 - 255 */
+ const unsigned char bidirectional; /* index into
+ _PyUnicode_BidirectionalNames */
+ const unsigned char mirrored; /* true if mirrored in bidir mode */
+ const unsigned char east_asian_width; /* index into
+ _PyUnicode_EastAsianWidth */
const unsigned char normalization_quick_check; /* see is_normalized() */
} _PyUnicode_DatabaseRecord;
@@ -67,7 +67,7 @@ typedef struct previous_version {
#define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v))
static PyMemberDef DB_members[] = {
- {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
+ {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
{NULL}
};
@@ -78,14 +78,14 @@ static PyObject*
new_previous_version(const char*name, const change_record* (*getrecord)(Py_UCS4),
Py_UCS4 (*normalization)(Py_UCS4))
{
- PreviousDBVersion *self;
- self = PyObject_New(PreviousDBVersion, &UCD_Type);
- if (self == NULL)
- return NULL;
- self->name = name;
- self->getrecord = getrecord;
+ PreviousDBVersion *self;
+ self = PyObject_New(PreviousDBVersion, &UCD_Type);
+ if (self == NULL)
+ return NULL;
+ self->name = name;
+ self->getrecord = getrecord;
self->normalization = normalization;
- return (PyObject*)self;
+ return (PyObject*)self;
}
@@ -94,12 +94,12 @@ static Py_UCS4 getuchar(PyUnicodeObject *obj)
Py_UNICODE *v = PyUnicode_AS_UNICODE(obj);
if (PyUnicode_GET_SIZE(obj) == 1)
- return *v;
+ return *v;
#ifndef Py_UNICODE_WIDE
else if ((PyUnicode_GET_SIZE(obj) == 2) &&
(0xD800 <= v[0] && v[0] <= 0xDBFF) &&
(0xDC00 <= v[1] && v[1] <= 0xDFFF))
- return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000;
+ return (((v[0] & 0x3FF)<<10) | (v[1] & 0x3FF)) + 0x10000;
#endif
PyErr_SetString(PyExc_TypeError,
"need a single Unicode character as parameter");
@@ -136,7 +136,7 @@ unicodedata_decimal(PyObject *self, PyObject *args)
/* unassigned */
have_old = 1;
rc = -1;
- }
+ }
else if (old->decimal_changed != 0xFF) {
have_old = 1;
rc = old->decimal_changed;
@@ -146,15 +146,15 @@ unicodedata_decimal(PyObject *self, PyObject *args)
if (!have_old)
rc = Py_UNICODE_TODECIMAL(c);
if (rc < 0) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "not a decimal");
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "not a decimal");
return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyInt_FromLong(rc);
}
@@ -181,14 +181,14 @@ unicodedata_digit(PyObject *self, PyObject *args)
return NULL;
rc = Py_UNICODE_TODIGIT(c);
if (rc < 0) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "not a digit");
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "not a digit");
return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyInt_FromLong(rc);
}
@@ -221,7 +221,7 @@ unicodedata_numeric(PyObject *self, PyObject *args)
/* unassigned */
have_old = 1;
rc = -1.0;
- }
+ }
else if (old->decimal_changed != 0xFF) {
have_old = 1;
rc = old->decimal_changed;
@@ -231,14 +231,14 @@ unicodedata_numeric(PyObject *self, PyObject *args)
if (!have_old)
rc = Py_UNICODE_TONUMERIC(c);
if (rc == -1.0) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "not a numeric character");
- return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "not a numeric character");
+ return NULL;
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return PyFloat_FromDouble(rc);
}
@@ -257,8 +257,8 @@ unicodedata_category(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:category",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -286,8 +286,8 @@ unicodedata_bidirectional(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:bidirectional",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -317,8 +317,8 @@ unicodedata_combining(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:combining",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -346,8 +346,8 @@ unicodedata_mirrored(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:mirrored",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -376,8 +376,8 @@ unicodedata_east_asian_width(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:east_asian_width",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -407,8 +407,8 @@ unicodedata_decomposition(PyObject *self, PyObject *args)
Py_UCS4 c;
if (!PyArg_ParseTuple(args, "O!:decomposition",
- &PyUnicode_Type, &v))
- return NULL;
+ &PyUnicode_Type, &v))
+ return NULL;
c = getuchar(v);
if (c == (Py_UCS4)-1)
return NULL;
@@ -454,7 +454,7 @@ unicodedata_decomposition(PyObject *self, PyObject *args)
decomp_data[++index]);
i += strlen(decomp + i);
}
-
+
decomp[i] = '\0';
return PyString_FromString(decomp);
@@ -474,7 +474,7 @@ get_decomp_record(PyObject *self, Py_UCS4 code, int *index, int *prefix, int *co
*index = decomp_index2[(*index<<DECOMP_SHIFT)+
(code&((1<<DECOMP_SHIFT)-1))];
}
-
+
/* high byte is number of hex bytes (usually one or two), low byte
is prefix code (from*/
*count = decomp_data[*index] >> 8;
@@ -499,11 +499,11 @@ nfd_nfkd(PyObject *self, PyObject *input, int k)
PyObject *result;
Py_UNICODE *i, *end, *o;
/* Longest decomposition in Unicode 3.2: U+FDFA */
- Py_UNICODE stack[20];
+ Py_UNICODE stack[20];
Py_ssize_t space, isize;
int index, prefix, count, stackptr;
unsigned char prev, cur;
-
+
stackptr = 0;
isize = PyUnicode_GET_SIZE(input);
/* Overallocate atmost 10 characters. */
@@ -640,12 +640,12 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
i = PyUnicode_AS_UNICODE(result);
end = i + PyUnicode_GET_SIZE(result);
o = PyUnicode_AS_UNICODE(result);
-
+
again:
while (i < end) {
for (index = 0; index < cskipped; index++) {
if (skipped[index] == i) {
- /* *i character is skipped.
+ /* *i character is skipped.
Remove from list. */
skipped[index] = skipped[cskipped-1];
cskipped--;
@@ -656,7 +656,7 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
/* Hangul Composition. We don't need to check for <LV,T>
pairs, since we always have decomposed data. */
if (LBase <= *i && *i < (LBase+LCount) &&
- i + 1 < end &&
+ i + 1 < end &&
VBase <= i[1] && i[1] <= (VBase+VCount)) {
int LIndex, VIndex;
LIndex = i[0] - LBase;
@@ -705,7 +705,7 @@ nfc_nfkc(PyObject *self, PyObject *input, int k)
(index&((1<<COMP_SHIFT)-1))];
if (code == 0)
goto not_combinable;
-
+
/* Replace the original character. */
*i = code;
/* Mark the second character unused. */
@@ -889,29 +889,29 @@ _getucname(PyObject *self, Py_UCS4 code, char* buffer, int buflen)
if (old->category_changed == 0) {
/* unassigned */
return 0;
- }
+ }
}
if (SBase <= code && code < SBase+SCount) {
- /* Hangul syllable. */
- int SIndex = code - SBase;
- int L = SIndex / NCount;
- int V = (SIndex % NCount) / TCount;
- int T = SIndex % TCount;
-
- if (buflen < 27)
- /* Worst case: HANGUL SYLLABLE <10chars>. */
- return 0;
- strcpy(buffer, "HANGUL SYLLABLE ");
- buffer += 16;
- strcpy(buffer, hangul_syllables[L][0]);
- buffer += strlen(hangul_syllables[L][0]);
- strcpy(buffer, hangul_syllables[V][1]);
- buffer += strlen(hangul_syllables[V][1]);
- strcpy(buffer, hangul_syllables[T][2]);
- buffer += strlen(hangul_syllables[T][2]);
- *buffer = '\0';
- return 1;
+ /* Hangul syllable. */
+ int SIndex = code - SBase;
+ int L = SIndex / NCount;
+ int V = (SIndex % NCount) / TCount;
+ int T = SIndex % TCount;
+
+ if (buflen < 27)
+ /* Worst case: HANGUL SYLLABLE <10chars>. */
+ return 0;
+ strcpy(buffer, "HANGUL SYLLABLE ");
+ buffer += 16;
+ strcpy(buffer, hangul_syllables[L][0]);
+ buffer += strlen(hangul_syllables[L][0]);
+ strcpy(buffer, hangul_syllables[V][1]);
+ buffer += strlen(hangul_syllables[V][1]);
+ strcpy(buffer, hangul_syllables[T][2]);
+ buffer += strlen(hangul_syllables[T][2]);
+ *buffer = '\0';
+ return 1;
}
if (is_unified_ideograph(code)) {
@@ -978,23 +978,23 @@ _cmpname(PyObject *self, int code, const char* name, int namelen)
return buffer[namelen] == '\0';
}
-static void
+static void
find_syllable(const char *str, int *len, int *pos, int count, int column)
{
int i, len1;
*len = -1;
for (i = 0; i < count; i++) {
- char *s = hangul_syllables[i][column];
- len1 = strlen(s);
- if (len1 <= *len)
- continue;
- if (strncmp(str, s, len1) == 0) {
- *len = len1;
- *pos = i;
- }
+ char *s = hangul_syllables[i][column];
+ len1 = strlen(s);
+ if (len1 <= *len)
+ continue;
+ if (strncmp(str, s, len1) == 0) {
+ *len = len1;
+ *pos = i;
+ }
}
if (*len == -1) {
- *len = 0;
+ *len = 0;
}
}
@@ -1007,18 +1007,18 @@ _getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code)
/* Check for hangul syllables. */
if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) {
- int len, L = -1, V = -1, T = -1;
- const char *pos = name + 16;
- find_syllable(pos, &len, &L, LCount, 0);
- pos += len;
- find_syllable(pos, &len, &V, VCount, 1);
- pos += len;
- find_syllable(pos, &len, &T, TCount, 2);
- pos += len;
- if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
- *code = SBase + (L*VCount+V)*TCount + T;
- return 1;
- }
+ int len, L = -1, V = -1, T = -1;
+ const char *pos = name + 16;
+ find_syllable(pos, &len, &L, LCount, 0);
+ pos += len;
+ find_syllable(pos, &len, &V, VCount, 1);
+ pos += len;
+ find_syllable(pos, &len, &T, TCount, 2);
+ pos += len;
+ if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
+ *code = SBase + (L*VCount+V)*TCount + T;
+ return 1;
+ }
/* Otherwise, it's an illegal syllable name. */
return 0;
}
@@ -1078,7 +1078,7 @@ _getcode(PyObject* self, const char* name, int namelen, Py_UCS4* code)
}
}
-static const _PyUnicode_Name_CAPI hashAPI =
+static const _PyUnicode_Name_CAPI hashAPI =
{
sizeof(_PyUnicode_Name_CAPI),
_getucname,
@@ -1110,14 +1110,14 @@ unicodedata_name(PyObject* self, PyObject* args)
return NULL;
if (!_getucname(self, c, name, sizeof(name))) {
- if (defobj == NULL) {
- PyErr_SetString(PyExc_ValueError, "no such name");
+ if (defobj == NULL) {
+ PyErr_SetString(PyExc_ValueError, "no such name");
return NULL;
- }
- else {
- Py_INCREF(defobj);
- return defobj;
- }
+ }
+ else {
+ Py_INCREF(defobj);
+ return defobj;
+ }
}
return Py_BuildValue("s", name);
@@ -1155,7 +1155,7 @@ unicodedata_lookup(PyObject* self, PyObject* args)
}
#endif
str[0] = (Py_UNICODE) code;
- return PyUnicode_FromUnicode(str, 1);
+ return PyUnicode_FromUnicode(str, 1);
}
/* XXX Add doc strings. */
@@ -1180,27 +1180,27 @@ static PyMethodDef unicodedata_functions[] = {
{"lookup", unicodedata_lookup, METH_VARARGS, unicodedata_lookup__doc__},
{"normalize", unicodedata_normalize, METH_VARARGS,
unicodedata_normalize__doc__},
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject UCD_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "unicodedata.UCD", /*tp_name*/
- sizeof(PreviousDBVersion), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)PyObject_Del, /*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*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "unicodedata.UCD", /*tp_name*/
+ sizeof(PreviousDBVersion), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)PyObject_Del, /*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*/
@@ -1266,7 +1266,7 @@ initunicodedata(void)
PyModule_AddObject(m, "ucnhash_CAPI", v);
}
-/*
+/*
Local variables:
c-basic-offset: 4
indent-tabs-mode: nil
diff --git a/Modules/xxmodule.c b/Modules/xxmodule.c
index 6b498dd..1d9b08a 100644
--- a/Modules/xxmodule.c
+++ b/Modules/xxmodule.c
@@ -19,23 +19,23 @@
static PyObject *ErrorObject;
typedef struct {
- PyObject_HEAD
- PyObject *x_attr; /* Attributes dictionary */
+ PyObject_HEAD
+ PyObject *x_attr; /* Attributes dictionary */
} XxoObject;
static PyTypeObject Xxo_Type;
-#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type)
+#define XxoObject_Check(v) (Py_TYPE(v) == &Xxo_Type)
static XxoObject *
newXxoObject(PyObject *arg)
{
- XxoObject *self;
- self = PyObject_New(XxoObject, &Xxo_Type);
- if (self == NULL)
- return NULL;
- self->x_attr = NULL;
- return self;
+ XxoObject *self;
+ self = PyObject_New(XxoObject, &Xxo_Type);
+ if (self == NULL)
+ return NULL;
+ self->x_attr = NULL;
+ return self;
}
/* Xxo methods */
@@ -43,101 +43,101 @@ newXxoObject(PyObject *arg)
static void
Xxo_dealloc(XxoObject *self)
{
- Py_XDECREF(self->x_attr);
- PyObject_Del(self);
+ Py_XDECREF(self->x_attr);
+ PyObject_Del(self);
}
static PyObject *
Xxo_demo(XxoObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":demo"))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":demo"))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef Xxo_methods[] = {
- {"demo", (PyCFunction)Xxo_demo, METH_VARARGS,
- PyDoc_STR("demo() -> None")},
- {NULL, NULL} /* sentinel */
+ {"demo", (PyCFunction)Xxo_demo, METH_VARARGS,
+ PyDoc_STR("demo() -> None")},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
Xxo_getattr(XxoObject *self, char *name)
{
- if (self->x_attr != NULL) {
- PyObject *v = PyDict_GetItemString(self->x_attr, name);
- if (v != NULL) {
- Py_INCREF(v);
- return v;
- }
- }
- return Py_FindMethod(Xxo_methods, (PyObject *)self, name);
+ if (self->x_attr != NULL) {
+ PyObject *v = PyDict_GetItemString(self->x_attr, name);
+ if (v != NULL) {
+ Py_INCREF(v);
+ return v;
+ }
+ }
+ return Py_FindMethod(Xxo_methods, (PyObject *)self, name);
}
static int
Xxo_setattr(XxoObject *self, char *name, PyObject *v)
{
- if (self->x_attr == NULL) {
- self->x_attr = PyDict_New();
- if (self->x_attr == NULL)
- return -1;
- }
- if (v == NULL) {
- int rv = PyDict_DelItemString(self->x_attr, name);
- if (rv < 0)
- PyErr_SetString(PyExc_AttributeError,
- "delete non-existing Xxo attribute");
- return rv;
- }
- else
- return PyDict_SetItemString(self->x_attr, name, v);
+ if (self->x_attr == NULL) {
+ self->x_attr = PyDict_New();
+ if (self->x_attr == NULL)
+ return -1;
+ }
+ if (v == NULL) {
+ int rv = PyDict_DelItemString(self->x_attr, name);
+ if (rv < 0)
+ PyErr_SetString(PyExc_AttributeError,
+ "delete non-existing Xxo attribute");
+ return rv;
+ }
+ else
+ return PyDict_SetItemString(self->x_attr, name, v);
}
static PyTypeObject Xxo_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "xxmodule.Xxo", /*tp_name*/
- sizeof(XxoObject), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)Xxo_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc)Xxo_getattr, /*tp_getattr*/
- (setattrfunc)Xxo_setattr, /*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, /*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*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "xxmodule.Xxo", /*tp_name*/
+ sizeof(XxoObject), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)Xxo_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc)Xxo_getattr, /*tp_getattr*/
+ (setattrfunc)Xxo_setattr, /*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, /*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*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
/* --------------------------------------------------------------------- */
@@ -151,12 +151,12 @@ Return the sum of i and j.");
static PyObject *
xx_foo(PyObject *self, PyObject *args)
{
- long i, j;
- long res;
- if (!PyArg_ParseTuple(args, "ll:foo", &i, &j))
- return NULL;
- res = i+j; /* XXX Do something here */
- return PyInt_FromLong(res);
+ long i, j;
+ long res;
+ if (!PyArg_ParseTuple(args, "ll:foo", &i, &j))
+ return NULL;
+ res = i+j; /* XXX Do something here */
+ return PyInt_FromLong(res);
}
@@ -165,14 +165,14 @@ xx_foo(PyObject *self, PyObject *args)
static PyObject *
xx_new(PyObject *self, PyObject *args)
{
- XxoObject *rv;
-
- if (!PyArg_ParseTuple(args, ":new"))
- return NULL;
- rv = newXxoObject(args);
- if (rv == NULL)
- return NULL;
- return (PyObject *)rv;
+ XxoObject *rv;
+
+ if (!PyArg_ParseTuple(args, ":new"))
+ return NULL;
+ rv = newXxoObject(args);
+ if (rv == NULL)
+ return NULL;
+ return (PyObject *)rv;
}
/* Example with subtle bug from extensions manual ("Thin Ice"). */
@@ -180,20 +180,20 @@ xx_new(PyObject *self, PyObject *args)
static PyObject *
xx_bug(PyObject *self, PyObject *args)
{
- PyObject *list, *item;
+ PyObject *list, *item;
- if (!PyArg_ParseTuple(args, "O:bug", &list))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:bug", &list))
+ return NULL;
- item = PyList_GetItem(list, 0);
- /* Py_INCREF(item); */
- PyList_SetItem(list, 1, PyInt_FromLong(0L));
- PyObject_Print(item, stdout, 0);
- printf("\n");
- /* Py_DECREF(item); */
+ item = PyList_GetItem(list, 0);
+ /* Py_INCREF(item); */
+ PyList_SetItem(list, 1, PyInt_FromLong(0L));
+ PyObject_Print(item, stdout, 0);
+ printf("\n");
+ /* Py_DECREF(item); */
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* Test bad format character */
@@ -201,61 +201,61 @@ xx_bug(PyObject *self, PyObject *args)
static PyObject *
xx_roj(PyObject *self, PyObject *args)
{
- PyObject *a;
- long b;
- if (!PyArg_ParseTuple(args, "O#:roj", &a, &b))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *a;
+ long b;
+ if (!PyArg_ParseTuple(args, "O#:roj", &a, &b))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* ---------- */
static PyTypeObject Str_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "xxmodule.Str", /*tp_name*/
- 0, /*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*/
- 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, /* see initxx */ /*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*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "xxmodule.Str", /*tp_name*/
+ 0, /*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*/
+ 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, /* see initxx */ /*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*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
/* ---------- */
@@ -263,54 +263,54 @@ static PyTypeObject Str_Type = {
static PyObject *
null_richcompare(PyObject *self, PyObject *other, int op)
{
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyTypeObject Null_Type = {
- /* The ob_type field must be initialized in the module init function
- * to be portable to Windows without using C++. */
- PyVarObject_HEAD_INIT(NULL, 0)
- "xxmodule.Null", /*tp_name*/
- 0, /*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*/
- 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*/
- null_richcompare, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- 0, /*tp_methods*/
- 0, /*tp_members*/
- 0, /*tp_getset*/
- 0, /* see initxx */ /*tp_base*/
- 0, /*tp_dict*/
- 0, /*tp_descr_get*/
- 0, /*tp_descr_set*/
- 0, /*tp_dictoffset*/
- 0, /*tp_init*/
- 0, /*tp_alloc*/
- 0, /* see initxx */ /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ /* The ob_type field must be initialized in the module init function
+ * to be portable to Windows without using C++. */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "xxmodule.Null", /*tp_name*/
+ 0, /*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*/
+ 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*/
+ null_richcompare, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ 0, /*tp_methods*/
+ 0, /*tp_members*/
+ 0, /*tp_getset*/
+ 0, /* see initxx */ /*tp_base*/
+ 0, /*tp_dict*/
+ 0, /*tp_descr_get*/
+ 0, /*tp_descr_set*/
+ 0, /*tp_dictoffset*/
+ 0, /*tp_init*/
+ 0, /*tp_alloc*/
+ 0, /* see initxx */ /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
@@ -320,15 +320,15 @@ static PyTypeObject Null_Type = {
/* List of functions defined in the module */
static PyMethodDef xx_methods[] = {
- {"roj", xx_roj, METH_VARARGS,
- PyDoc_STR("roj(a,b) -> None")},
- {"foo", xx_foo, METH_VARARGS,
- xx_foo_doc},
- {"new", xx_new, METH_VARARGS,
- PyDoc_STR("new() -> new Xx object")},
- {"bug", xx_bug, METH_VARARGS,
- PyDoc_STR("bug(o) -> None")},
- {NULL, NULL} /* sentinel */
+ {"roj", xx_roj, METH_VARARGS,
+ PyDoc_STR("roj(a,b) -> None")},
+ {"foo", xx_foo, METH_VARARGS,
+ xx_foo_doc},
+ {"new", xx_new, METH_VARARGS,
+ PyDoc_STR("new() -> new Xx object")},
+ {"bug", xx_bug, METH_VARARGS,
+ PyDoc_STR("bug(o) -> None")},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(module_doc,
@@ -339,41 +339,41 @@ PyDoc_STRVAR(module_doc,
PyMODINIT_FUNC
initxx(void)
{
- PyObject *m;
-
- /* Due to cross platform compiler issues the slots must be filled
- * here. It's required for portability to Windows without requiring
- * C++. */
- Null_Type.tp_base = &PyBaseObject_Type;
- Null_Type.tp_new = PyType_GenericNew;
- Str_Type.tp_base = &PyUnicode_Type;
-
- /* Finalize the type object including setting type of the new type
- * object; doing it here is required for portability, too. */
- if (PyType_Ready(&Xxo_Type) < 0)
- return;
-
- /* Create the module and add the functions */
- m = Py_InitModule3("xx", xx_methods, module_doc);
- if (m == NULL)
- return;
-
- /* Add some symbolic constants to the module */
- if (ErrorObject == NULL) {
- ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
- if (ErrorObject == NULL)
- return;
- }
- Py_INCREF(ErrorObject);
- PyModule_AddObject(m, "error", ErrorObject);
-
- /* Add Str */
- if (PyType_Ready(&Str_Type) < 0)
- return;
- PyModule_AddObject(m, "Str", (PyObject *)&Str_Type);
-
- /* Add Null */
- if (PyType_Ready(&Null_Type) < 0)
- return;
- PyModule_AddObject(m, "Null", (PyObject *)&Null_Type);
+ PyObject *m;
+
+ /* Due to cross platform compiler issues the slots must be filled
+ * here. It's required for portability to Windows without requiring
+ * C++. */
+ Null_Type.tp_base = &PyBaseObject_Type;
+ Null_Type.tp_new = PyType_GenericNew;
+ Str_Type.tp_base = &PyUnicode_Type;
+
+ /* Finalize the type object including setting type of the new type
+ * object; doing it here is required for portability, too. */
+ if (PyType_Ready(&Xxo_Type) < 0)
+ return;
+
+ /* Create the module and add the functions */
+ m = Py_InitModule3("xx", xx_methods, module_doc);
+ if (m == NULL)
+ return;
+
+ /* Add some symbolic constants to the module */
+ if (ErrorObject == NULL) {
+ ErrorObject = PyErr_NewException("xx.error", NULL, NULL);
+ if (ErrorObject == NULL)
+ return;
+ }
+ Py_INCREF(ErrorObject);
+ PyModule_AddObject(m, "error", ErrorObject);
+
+ /* Add Str */
+ if (PyType_Ready(&Str_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Str", (PyObject *)&Str_Type);
+
+ /* Add Null */
+ if (PyType_Ready(&Null_Type) < 0)
+ return;
+ PyModule_AddObject(m, "Null", (PyObject *)&Null_Type);
}
diff --git a/Modules/xxsubtype.c b/Modules/xxsubtype.c
index 0cf0b81..d4316e7 100644
--- a/Modules/xxsubtype.c
+++ b/Modules/xxsubtype.c
@@ -19,279 +19,279 @@ PyDoc_STRVAR(xxsubtype__doc__,
/* spamlist -- a list subtype */
typedef struct {
- PyListObject list;
- int state;
+ PyListObject list;
+ int state;
} spamlistobject;
static PyObject *
spamlist_getstate(spamlistobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":getstate"))
- return NULL;
- return PyInt_FromLong(self->state);
+ if (!PyArg_ParseTuple(args, ":getstate"))
+ return NULL;
+ return PyInt_FromLong(self->state);
}
static PyObject *
spamlist_setstate(spamlistobject *self, PyObject *args)
{
- int state;
+ int state;
- if (!PyArg_ParseTuple(args, "i:setstate", &state))
- return NULL;
- self->state = state;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:setstate", &state))
+ return NULL;
+ self->state = state;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
spamlist_specialmeth(PyObject *self, PyObject *args, PyObject *kw)
{
- PyObject *result = PyTuple_New(3);
-
- if (result != NULL) {
- if (self == NULL)
- self = Py_None;
- if (kw == NULL)
- kw = Py_None;
- Py_INCREF(self);
- PyTuple_SET_ITEM(result, 0, self);
- Py_INCREF(args);
- PyTuple_SET_ITEM(result, 1, args);
- Py_INCREF(kw);
- PyTuple_SET_ITEM(result, 2, kw);
- }
- return result;
+ PyObject *result = PyTuple_New(3);
+
+ if (result != NULL) {
+ if (self == NULL)
+ self = Py_None;
+ if (kw == NULL)
+ kw = Py_None;
+ Py_INCREF(self);
+ PyTuple_SET_ITEM(result, 0, self);
+ Py_INCREF(args);
+ PyTuple_SET_ITEM(result, 1, args);
+ Py_INCREF(kw);
+ PyTuple_SET_ITEM(result, 2, kw);
+ }
+ return result;
}
static PyMethodDef spamlist_methods[] = {
- {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS,
- PyDoc_STR("getstate() -> state")},
- {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS,
- PyDoc_STR("setstate(state)")},
- /* These entries differ only in the flags; they are used by the tests
- in test.test_descr. */
- {"classmeth", (PyCFunction)spamlist_specialmeth,
- METH_VARARGS | METH_KEYWORDS | METH_CLASS,
- PyDoc_STR("classmeth(*args, **kw)")},
- {"staticmeth", (PyCFunction)spamlist_specialmeth,
- METH_VARARGS | METH_KEYWORDS | METH_STATIC,
- PyDoc_STR("staticmeth(*args, **kw)")},
- {NULL, NULL},
+ {"getstate", (PyCFunction)spamlist_getstate, METH_VARARGS,
+ PyDoc_STR("getstate() -> state")},
+ {"setstate", (PyCFunction)spamlist_setstate, METH_VARARGS,
+ PyDoc_STR("setstate(state)")},
+ /* These entries differ only in the flags; they are used by the tests
+ in test.test_descr. */
+ {"classmeth", (PyCFunction)spamlist_specialmeth,
+ METH_VARARGS | METH_KEYWORDS | METH_CLASS,
+ PyDoc_STR("classmeth(*args, **kw)")},
+ {"staticmeth", (PyCFunction)spamlist_specialmeth,
+ METH_VARARGS | METH_KEYWORDS | METH_STATIC,
+ PyDoc_STR("staticmeth(*args, **kw)")},
+ {NULL, NULL},
};
static int
spamlist_init(spamlistobject *self, PyObject *args, PyObject *kwds)
{
- if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
- return -1;
- self->state = 0;
- return 0;
+ if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
+ return -1;
+ self->state = 0;
+ return 0;
}
static PyObject *
spamlist_state_get(spamlistobject *self)
{
- return PyInt_FromLong(self->state);
+ return PyInt_FromLong(self->state);
}
static PyGetSetDef spamlist_getsets[] = {
- {"state", (getter)spamlist_state_get, NULL,
- PyDoc_STR("an int variable for demonstration purposes")},
- {0}
+ {"state", (getter)spamlist_state_get, NULL,
+ PyDoc_STR("an int variable for demonstration purposes")},
+ {0}
};
static PyTypeObject spamlist_type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "xxsubtype.spamlist",
- sizeof(spamlistobject),
- 0,
- 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 */
- 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 */
- spamlist_methods, /* tp_methods */
- 0, /* tp_members */
- spamlist_getsets, /* tp_getset */
- DEFERRED_ADDRESS(&PyList_Type), /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)spamlist_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "xxsubtype.spamlist",
+ sizeof(spamlistobject),
+ 0,
+ 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 */
+ 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 */
+ spamlist_methods, /* tp_methods */
+ 0, /* tp_members */
+ spamlist_getsets, /* tp_getset */
+ DEFERRED_ADDRESS(&PyList_Type), /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)spamlist_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
};
/* spamdict -- a dict subtype */
typedef struct {
- PyDictObject dict;
- int state;
+ PyDictObject dict;
+ int state;
} spamdictobject;
static PyObject *
spamdict_getstate(spamdictobject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":getstate"))
- return NULL;
- return PyInt_FromLong(self->state);
+ if (!PyArg_ParseTuple(args, ":getstate"))
+ return NULL;
+ return PyInt_FromLong(self->state);
}
static PyObject *
spamdict_setstate(spamdictobject *self, PyObject *args)
{
- int state;
+ int state;
- if (!PyArg_ParseTuple(args, "i:setstate", &state))
- return NULL;
- self->state = state;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:setstate", &state))
+ return NULL;
+ self->state = state;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyMethodDef spamdict_methods[] = {
- {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS,
- PyDoc_STR("getstate() -> state")},
- {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS,
- PyDoc_STR("setstate(state)")},
- {NULL, NULL},
+ {"getstate", (PyCFunction)spamdict_getstate, METH_VARARGS,
+ PyDoc_STR("getstate() -> state")},
+ {"setstate", (PyCFunction)spamdict_setstate, METH_VARARGS,
+ PyDoc_STR("setstate(state)")},
+ {NULL, NULL},
};
static int
spamdict_init(spamdictobject *self, PyObject *args, PyObject *kwds)
{
- if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
- return -1;
- self->state = 0;
- return 0;
+ if (PyDict_Type.tp_init((PyObject *)self, args, kwds) < 0)
+ return -1;
+ self->state = 0;
+ return 0;
}
static PyMemberDef spamdict_members[] = {
- {"state", T_INT, offsetof(spamdictobject, state), READONLY,
- PyDoc_STR("an int variable for demonstration purposes")},
- {0}
+ {"state", T_INT, offsetof(spamdictobject, state), READONLY,
+ PyDoc_STR("an int variable for demonstration purposes")},
+ {0}
};
static PyTypeObject spamdict_type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "xxsubtype.spamdict",
- sizeof(spamdictobject),
- 0,
- 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 */
- 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 */
- spamdict_methods, /* tp_methods */
- spamdict_members, /* tp_members */
- 0, /* tp_getset */
- DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)spamdict_init, /* tp_init */
- 0, /* tp_alloc */
- 0, /* tp_new */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "xxsubtype.spamdict",
+ sizeof(spamdictobject),
+ 0,
+ 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 */
+ 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 */
+ spamdict_methods, /* tp_methods */
+ spamdict_members, /* tp_members */
+ 0, /* tp_getset */
+ DEFERRED_ADDRESS(&PyDict_Type), /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)spamdict_init, /* tp_init */
+ 0, /* tp_alloc */
+ 0, /* tp_new */
};
static PyObject *
spam_bench(PyObject *self, PyObject *args)
{
- PyObject *obj, *name, *res;
- int n = 1000;
- time_t t0, t1;
-
- if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n))
- return NULL;
- t0 = clock();
- while (--n >= 0) {
- res = PyObject_GetAttr(obj, name);
- if (res == NULL)
- return NULL;
- Py_DECREF(res);
- }
- t1 = clock();
- return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC);
+ PyObject *obj, *name, *res;
+ int n = 1000;
+ time_t t0, t1;
+
+ if (!PyArg_ParseTuple(args, "OS|i", &obj, &name, &n))
+ return NULL;
+ t0 = clock();
+ while (--n >= 0) {
+ res = PyObject_GetAttr(obj, name);
+ if (res == NULL)
+ return NULL;
+ Py_DECREF(res);
+ }
+ t1 = clock();
+ return PyFloat_FromDouble((double)(t1-t0) / CLOCKS_PER_SEC);
}
static PyMethodDef xxsubtype_functions[] = {
- {"bench", spam_bench, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"bench", spam_bench, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
PyMODINIT_FUNC
initxxsubtype(void)
{
- PyObject *m;
-
- /* Fill in deferred data addresses. This must be done before
- PyType_Ready() is called. Note that PyType_Ready() automatically
- initializes the ob.ob_type field to &PyType_Type if it's NULL,
- so it's not necessary to fill in ob_type first. */
- spamdict_type.tp_base = &PyDict_Type;
- if (PyType_Ready(&spamdict_type) < 0)
- return;
-
- spamlist_type.tp_base = &PyList_Type;
- if (PyType_Ready(&spamlist_type) < 0)
- return;
-
- m = Py_InitModule3("xxsubtype",
- xxsubtype_functions,
- xxsubtype__doc__);
- if (m == NULL)
- return;
-
- if (PyType_Ready(&spamlist_type) < 0)
- return;
- if (PyType_Ready(&spamdict_type) < 0)
- return;
-
- Py_INCREF(&spamlist_type);
- if (PyModule_AddObject(m, "spamlist",
- (PyObject *) &spamlist_type) < 0)
- return;
-
- Py_INCREF(&spamdict_type);
- if (PyModule_AddObject(m, "spamdict",
- (PyObject *) &spamdict_type) < 0)
- return;
+ PyObject *m;
+
+ /* Fill in deferred data addresses. This must be done before
+ PyType_Ready() is called. Note that PyType_Ready() automatically
+ initializes the ob.ob_type field to &PyType_Type if it's NULL,
+ so it's not necessary to fill in ob_type first. */
+ spamdict_type.tp_base = &PyDict_Type;
+ if (PyType_Ready(&spamdict_type) < 0)
+ return;
+
+ spamlist_type.tp_base = &PyList_Type;
+ if (PyType_Ready(&spamlist_type) < 0)
+ return;
+
+ m = Py_InitModule3("xxsubtype",
+ xxsubtype_functions,
+ xxsubtype__doc__);
+ if (m == NULL)
+ return;
+
+ if (PyType_Ready(&spamlist_type) < 0)
+ return;
+ if (PyType_Ready(&spamdict_type) < 0)
+ return;
+
+ Py_INCREF(&spamlist_type);
+ if (PyModule_AddObject(m, "spamlist",
+ (PyObject *) &spamlist_type) < 0)
+ return;
+
+ Py_INCREF(&spamdict_type);
+ if (PyModule_AddObject(m, "spamdict",
+ (PyObject *) &spamdict_type) < 0)
+ return;
}
diff --git a/Modules/yuv.h b/Modules/yuv.h
index 738c4e5..1e5fd28 100644
--- a/Modules/yuv.h
+++ b/Modules/yuv.h
@@ -19,41 +19,41 @@ extern "C" {
* +-------------------+
*/
struct yuv411 {
- struct {
- unsigned int dummy:8;
- unsigned int y0:8;
- unsigned int u0:2;
- unsigned int v0:2;
- unsigned int y1:8;
- unsigned int u1:2;
- unsigned int v1:2;
- } v[4];
+ struct {
+ unsigned int dummy:8;
+ unsigned int y0:8;
+ unsigned int u0:2;
+ unsigned int v0:2;
+ unsigned int y1:8;
+ unsigned int u1:2;
+ unsigned int v1:2;
+ } v[4];
};
-#define YUV411_Y00(y) (y).v[0].y0
-#define YUV411_Y01(y) (y).v[1].y0
-#define YUV411_Y02(y) (y).v[2].y0
-#define YUV411_Y03(y) (y).v[3].y0
-#define YUV411_Y10(y) (y).v[0].y1
-#define YUV411_Y11(y) (y).v[1].y1
-#define YUV411_Y12(y) (y).v[2].y1
-#define YUV411_Y13(y) (y).v[3].y1
-#define YUV411_U00(y) ((y).v[0].u0<<6|(y).v[1].u0<<4|(y).v[2].u0<<2|(y).v[3].u0)
-#define YUV411_U01(y) YUV411_U00(y)
-#define YUV411_U02(y) YUV411_U00(y)
-#define YUV411_U03(y) YUV411_U00(y)
-#define YUV411_U10(y) ((y).v[0].u1<<6|(y).v[1].u1<<4|(y).v[2].u1<<2|(y).v[3].u1)
-#define YUV411_U11(y) YUV411_U10(y)
-#define YUV411_U12(y) YUV411_U10(y)
-#define YUV411_U13(y) YUV411_U10(y)
-#define YUV411_V00(y) ((y).v[0].v0<<6|(y).v[1].v0<<4|(y).v[2].v0<<2|(y).v[3].v0)
-#define YUV411_V01(y) YUV411_V00(y)
-#define YUV411_V02(y) YUV411_V00(y)
-#define YUV411_V03(y) YUV411_V00(y)
-#define YUV411_V10(y) ((y).v[0].v1<<6|(y).v[1].v1<<4|(y).v[2].v1<<2|(y).v[3].v1)
-#define YUV411_V11(y) YUV411_V10(y)
-#define YUV411_V12(y) YUV411_V10(y)
-#define YUV411_V13(y) YUV411_V10(y)
+#define YUV411_Y00(y) (y).v[0].y0
+#define YUV411_Y01(y) (y).v[1].y0
+#define YUV411_Y02(y) (y).v[2].y0
+#define YUV411_Y03(y) (y).v[3].y0
+#define YUV411_Y10(y) (y).v[0].y1
+#define YUV411_Y11(y) (y).v[1].y1
+#define YUV411_Y12(y) (y).v[2].y1
+#define YUV411_Y13(y) (y).v[3].y1
+#define YUV411_U00(y) ((y).v[0].u0<<6|(y).v[1].u0<<4|(y).v[2].u0<<2|(y).v[3].u0)
+#define YUV411_U01(y) YUV411_U00(y)
+#define YUV411_U02(y) YUV411_U00(y)
+#define YUV411_U03(y) YUV411_U00(y)
+#define YUV411_U10(y) ((y).v[0].u1<<6|(y).v[1].u1<<4|(y).v[2].u1<<2|(y).v[3].u1)
+#define YUV411_U11(y) YUV411_U10(y)
+#define YUV411_U12(y) YUV411_U10(y)
+#define YUV411_U13(y) YUV411_U10(y)
+#define YUV411_V00(y) ((y).v[0].v0<<6|(y).v[1].v0<<4|(y).v[2].v0<<2|(y).v[3].v0)
+#define YUV411_V01(y) YUV411_V00(y)
+#define YUV411_V02(y) YUV411_V00(y)
+#define YUV411_V03(y) YUV411_V00(y)
+#define YUV411_V10(y) ((y).v[0].v1<<6|(y).v[1].v1<<4|(y).v[2].v1<<2|(y).v[3].v1)
+#define YUV411_V11(y) YUV411_V10(y)
+#define YUV411_V12(y) YUV411_V10(y)
+#define YUV411_V13(y) YUV411_V10(y)
/*
* Compression Library YUV 4:2:2 format.
@@ -65,17 +65,17 @@ struct yuv411 {
* +-------+
*/
struct yuv422 {
- unsigned int u:8;
- unsigned int y0:8;
- unsigned int v:8;
- unsigned int y1:8;
+ unsigned int u:8;
+ unsigned int y0:8;
+ unsigned int v:8;
+ unsigned int y1:8;
};
-#define YUV422_Y0(y) (y).y0
-#define YUV422_Y1(y) (y).y1
-#define YUV422_U0(y) (y).u
-#define YUV422_U1(y) (y).u
-#define YUV422_V0(y) (y).v
-#define YUV422_V1(y) (y).v
+#define YUV422_Y0(y) (y).y0
+#define YUV422_Y1(y) (y).y1
+#define YUV422_U0(y) (y).u
+#define YUV422_U1(y) (y).u
+#define YUV422_V0(y) (y).v
+#define YUV422_V1(y) (y).v
/*
* Compression library YUV 4:2:2 Duplicate Chroma format.
diff --git a/Modules/yuvconvert.c b/Modules/yuvconvert.c
index e5333d9..a0fa639 100644
--- a/Modules/yuvconvert.c
+++ b/Modules/yuvconvert.c
@@ -4,115 +4,115 @@
void
yuv_sv411_to_cl422dc(int invert, void *data, void *yuv, int width, int height)
{
- struct yuv411 *in = data;
- struct yuv422 *out_even = yuv;
- struct yuv422 *out_odd = out_even + width / 2;
- int i, j; /* counters */
+ struct yuv411 *in = data;
+ struct yuv422 *out_even = yuv;
+ struct yuv422 *out_odd = out_even + width / 2;
+ int i, j; /* counters */
- for (i = height / 2; i--; ) {
- for (j = width / 4; j--; ) {
- YUV422_Y0(*out_even) = YUV411_Y00(*in);
- YUV422_U0(*out_even) = YUV411_U00(*in);
- YUV422_V0(*out_even) = YUV411_V00(*in);
- YUV422_Y1(*out_even) = YUV411_Y01(*in);
- out_even++;
- YUV422_Y0(*out_even) = YUV411_Y02(*in);
- YUV422_U0(*out_even) = YUV411_U02(*in);
- YUV422_V0(*out_even) = YUV411_V02(*in);
- YUV422_Y1(*out_even) = YUV411_Y03(*in);
- out_even++;
- YUV422_Y0(*out_odd) = YUV411_Y10(*in);
- YUV422_U0(*out_odd) = YUV411_U10(*in);
- YUV422_V0(*out_odd) = YUV411_V10(*in);
- YUV422_Y1(*out_odd) = YUV411_Y11(*in);
- out_odd++;
- YUV422_Y0(*out_odd) = YUV411_Y12(*in);
- YUV422_U0(*out_odd) = YUV411_U12(*in);
- YUV422_V0(*out_odd) = YUV411_V12(*in);
- YUV422_Y1(*out_odd) = YUV411_Y13(*in);
- out_odd++;
- in++;
- }
- out_even += width / 2;
- out_odd += width / 2;
- }
+ for (i = height / 2; i--; ) {
+ for (j = width / 4; j--; ) {
+ YUV422_Y0(*out_even) = YUV411_Y00(*in);
+ YUV422_U0(*out_even) = YUV411_U00(*in);
+ YUV422_V0(*out_even) = YUV411_V00(*in);
+ YUV422_Y1(*out_even) = YUV411_Y01(*in);
+ out_even++;
+ YUV422_Y0(*out_even) = YUV411_Y02(*in);
+ YUV422_U0(*out_even) = YUV411_U02(*in);
+ YUV422_V0(*out_even) = YUV411_V02(*in);
+ YUV422_Y1(*out_even) = YUV411_Y03(*in);
+ out_even++;
+ YUV422_Y0(*out_odd) = YUV411_Y10(*in);
+ YUV422_U0(*out_odd) = YUV411_U10(*in);
+ YUV422_V0(*out_odd) = YUV411_V10(*in);
+ YUV422_Y1(*out_odd) = YUV411_Y11(*in);
+ out_odd++;
+ YUV422_Y0(*out_odd) = YUV411_Y12(*in);
+ YUV422_U0(*out_odd) = YUV411_U12(*in);
+ YUV422_V0(*out_odd) = YUV411_V12(*in);
+ YUV422_Y1(*out_odd) = YUV411_Y13(*in);
+ out_odd++;
+ in++;
+ }
+ out_even += width / 2;
+ out_odd += width / 2;
+ }
}
void
yuv_sv411_to_cl422dc_quartersize(int invert, void *data, void *yuv,
- int width, int height)
+ int width, int height)
{
- int w4 = width / 4; /* quarter of width is used often */
- struct yuv411 *in_even = data;
- struct yuv411 *in_odd = in_even + w4;
- struct yuv422 *out_even = yuv;
- struct yuv422 *out_odd = out_even + w4;
- int i, j; /* counters */
- int u, v; /* U and V values */
+ int w4 = width / 4; /* quarter of width is used often */
+ struct yuv411 *in_even = data;
+ struct yuv411 *in_odd = in_even + w4;
+ struct yuv422 *out_even = yuv;
+ struct yuv422 *out_odd = out_even + w4;
+ int i, j; /* counters */
+ int u, v; /* U and V values */
- for (i = height / 4; i--; ) {
- for (j = w4; j--; ) {
- u = YUV411_U00(*in_even);
- v = YUV411_V00(*in_even);
+ for (i = height / 4; i--; ) {
+ for (j = w4; j--; ) {
+ u = YUV411_U00(*in_even);
+ v = YUV411_V00(*in_even);
- YUV422_Y0(*out_even) = YUV411_Y00(*in_even);
- YUV422_U0(*out_even) = u;
- YUV422_V0(*out_even) = v;
- YUV422_Y1(*out_even) = YUV411_Y02(*in_even);
+ YUV422_Y0(*out_even) = YUV411_Y00(*in_even);
+ YUV422_U0(*out_even) = u;
+ YUV422_V0(*out_even) = v;
+ YUV422_Y1(*out_even) = YUV411_Y02(*in_even);
- YUV422_Y0(*out_odd) = YUV411_Y10(*in_odd);
- YUV422_U0(*out_odd) = u;
- YUV422_V0(*out_odd) = v;
- YUV422_Y1(*out_odd) = YUV411_Y12(*in_odd);
+ YUV422_Y0(*out_odd) = YUV411_Y10(*in_odd);
+ YUV422_U0(*out_odd) = u;
+ YUV422_V0(*out_odd) = v;
+ YUV422_Y1(*out_odd) = YUV411_Y12(*in_odd);
- in_even++;
- in_odd++;
- out_even++;
- out_odd++;
- }
- in_even += w4;
- in_odd += w4;
- out_even += w4;
- out_odd += w4;
- }
+ in_even++;
+ in_odd++;
+ out_even++;
+ out_odd++;
+ }
+ in_even += w4;
+ in_odd += w4;
+ out_even += w4;
+ out_odd += w4;
+ }
}
void
yuv_sv411_to_cl422dc_sixteenthsize(int invert, void *data, void *yuv,
- int width, int height)
+ int width, int height)
{
- int w4_3 = 3 * width / 4; /* three quarters of width is used often */
- int w8 = width / 8; /* and so is one eighth */
- struct yuv411 *in_even = data;
- struct yuv411 *in_odd = in_even + width / 2;
- struct yuv422 *out_even = yuv;
- struct yuv422 *out_odd = out_even + w8;
- int i, j; /* counters */
- int u, v; /* U and V values */
+ int w4_3 = 3 * width / 4; /* three quarters of width is used often */
+ int w8 = width / 8; /* and so is one eighth */
+ struct yuv411 *in_even = data;
+ struct yuv411 *in_odd = in_even + width / 2;
+ struct yuv422 *out_even = yuv;
+ struct yuv422 *out_odd = out_even + w8;
+ int i, j; /* counters */
+ int u, v; /* U and V values */
- for (i = height / 8; i--; ) {
- for (j = w8; j--; ) {
- u = YUV411_U00(in_even[0]);
- v = YUV411_V00(in_even[0]);
+ for (i = height / 8; i--; ) {
+ for (j = w8; j--; ) {
+ u = YUV411_U00(in_even[0]);
+ v = YUV411_V00(in_even[0]);
- YUV422_Y0(*out_even) = YUV411_Y00(in_even[0]);
- YUV422_U0(*out_even) = u;
- YUV422_V0(*out_even) = v;
- YUV422_Y1(*out_even) = YUV411_Y00(in_even[1]);
+ YUV422_Y0(*out_even) = YUV411_Y00(in_even[0]);
+ YUV422_U0(*out_even) = u;
+ YUV422_V0(*out_even) = v;
+ YUV422_Y1(*out_even) = YUV411_Y00(in_even[1]);
- YUV422_Y0(*out_odd) = YUV411_Y00(in_odd[0]);
- YUV422_U0(*out_odd) = u;
- YUV422_V0(*out_odd) = v;
- YUV422_Y1(*out_odd) = YUV411_Y00(in_even[1]);
+ YUV422_Y0(*out_odd) = YUV411_Y00(in_odd[0]);
+ YUV422_U0(*out_odd) = u;
+ YUV422_V0(*out_odd) = v;
+ YUV422_Y1(*out_odd) = YUV411_Y00(in_even[1]);
- in_even += 2;
- in_odd += 2;
- out_even++;
- out_odd++;
- }
- in_even += w4_3;
- in_odd += w4_3;
- out_even += w8;
- out_odd += w8;
- }
+ in_even += 2;
+ in_odd += 2;
+ out_even++;
+ out_odd++;
+ }
+ in_even += w4_3;
+ in_odd += w4_3;
+ out_even += w8;
+ out_odd += w8;
+ }
}
diff --git a/Modules/zipimport.c b/Modules/zipimport.c
index b05de24..3cce9bf 100644
--- a/Modules/zipimport.c
+++ b/Modules/zipimport.c
@@ -10,8 +10,8 @@
#define IS_PACKAGE 0x2
struct st_zip_searchorder {
- char suffix[14];
- int type;
+ char suffix[14];
+ int type;
};
/* zip_searchorder defines how we search for a module in the Zip
@@ -20,13 +20,13 @@ struct st_zip_searchorder {
are swapped by initzipimport() if we run in optimized mode. Also,
'/' is replaced by SEP there. */
static struct st_zip_searchorder zip_searchorder[] = {
- {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},
- {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE},
- {"/__init__.py", IS_PACKAGE | IS_SOURCE},
- {".pyc", IS_BYTECODE},
- {".pyo", IS_BYTECODE},
- {".py", IS_SOURCE},
- {"", 0}
+ {"/__init__.pyc", IS_PACKAGE | IS_BYTECODE},
+ {"/__init__.pyo", IS_PACKAGE | IS_BYTECODE},
+ {"/__init__.py", IS_PACKAGE | IS_SOURCE},
+ {".pyc", IS_BYTECODE},
+ {".pyo", IS_BYTECODE},
+ {".py", IS_SOURCE},
+ {"", 0}
};
/* zipimporter object definition and support */
@@ -34,10 +34,10 @@ static struct st_zip_searchorder zip_searchorder[] = {
typedef struct _zipimporter ZipImporter;
struct _zipimporter {
- PyObject_HEAD
- PyObject *archive; /* pathname of the Zip archive */
- PyObject *prefix; /* file prefix: "a/sub/directory/" */
- PyObject *files; /* dict with file info {path: toc_entry} */
+ PyObject_HEAD
+ PyObject *archive; /* pathname of the Zip archive */
+ PyObject *prefix; /* file prefix: "a/sub/directory/" */
+ PyObject *files; /* dict with file info {path: toc_entry} */
};
static PyObject *ZipImportError;
@@ -47,7 +47,7 @@ static PyObject *zip_directory_cache = NULL;
static PyObject *read_directory(char *archive);
static PyObject *get_data(char *archive, PyObject *toc_entry);
static PyObject *get_module_code(ZipImporter *self, char *fullname,
- int *p_ispackage, char **p_modpath);
+ int *p_ispackage, char **p_modpath);
#define ZipImporter_Check(op) PyObject_TypeCheck(op, &ZipImporter_Type)
@@ -60,162 +60,162 @@ static PyObject *get_module_code(ZipImporter *self, char *fullname,
static int
zipimporter_init(ZipImporter *self, PyObject *args, PyObject *kwds)
{
- char *path, *p, *prefix, buf[MAXPATHLEN+2];
- size_t len;
-
- if (!_PyArg_NoKeywords("zipimporter()", kwds))
- return -1;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter",
- &path))
- return -1;
-
- len = strlen(path);
- if (len == 0) {
- PyErr_SetString(ZipImportError, "archive path is empty");
- return -1;
- }
- if (len >= MAXPATHLEN) {
- PyErr_SetString(ZipImportError,
- "archive path too long");
- return -1;
- }
- strcpy(buf, path);
+ char *path, *p, *prefix, buf[MAXPATHLEN+2];
+ size_t len;
+
+ if (!_PyArg_NoKeywords("zipimporter()", kwds))
+ return -1;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter",
+ &path))
+ return -1;
+
+ len = strlen(path);
+ if (len == 0) {
+ PyErr_SetString(ZipImportError, "archive path is empty");
+ return -1;
+ }
+ if (len >= MAXPATHLEN) {
+ PyErr_SetString(ZipImportError,
+ "archive path too long");
+ return -1;
+ }
+ strcpy(buf, path);
#ifdef ALTSEP
- for (p = buf; *p; p++) {
- if (*p == ALTSEP)
- *p = SEP;
- }
+ for (p = buf; *p; p++) {
+ if (*p == ALTSEP)
+ *p = SEP;
+ }
#endif
- path = NULL;
- prefix = NULL;
- for (;;) {
+ path = NULL;
+ prefix = NULL;
+ for (;;) {
#ifndef RISCOS
- struct stat statbuf;
- int rv;
-
- rv = stat(buf, &statbuf);
- if (rv == 0) {
- /* it exists */
- if (S_ISREG(statbuf.st_mode))
- /* it's a file */
- path = buf;
- break;
- }
+ struct stat statbuf;
+ int rv;
+
+ rv = stat(buf, &statbuf);
+ if (rv == 0) {
+ /* it exists */
+ if (S_ISREG(statbuf.st_mode))
+ /* it's a file */
+ path = buf;
+ break;
+ }
#else
- if (object_exists(buf)) {
- /* it exists */
- if (isfile(buf))
- /* it's a file */
- path = buf;
- break;
- }
+ if (object_exists(buf)) {
+ /* it exists */
+ if (isfile(buf))
+ /* it's a file */
+ path = buf;
+ break;
+ }
#endif
- /* back up one path element */
- p = strrchr(buf, SEP);
- if (prefix != NULL)
- *prefix = SEP;
- if (p == NULL)
- break;
- *p = '\0';
- prefix = p;
- }
- if (path != NULL) {
- PyObject *files;
- files = PyDict_GetItemString(zip_directory_cache, path);
- if (files == NULL) {
- files = read_directory(buf);
- if (files == NULL)
- return -1;
- if (PyDict_SetItemString(zip_directory_cache, path,
- files) != 0)
- return -1;
- }
- else
- Py_INCREF(files);
- self->files = files;
- }
- else {
- PyErr_SetString(ZipImportError, "not a Zip file");
- return -1;
- }
-
- if (prefix == NULL)
- prefix = "";
- else {
- prefix++;
- len = strlen(prefix);
- if (prefix[len-1] != SEP) {
- /* add trailing SEP */
- prefix[len] = SEP;
- prefix[len + 1] = '\0';
- }
- }
-
- self->archive = PyString_FromString(buf);
- if (self->archive == NULL)
- return -1;
-
- self->prefix = PyString_FromString(prefix);
- if (self->prefix == NULL)
- return -1;
-
- return 0;
+ /* back up one path element */
+ p = strrchr(buf, SEP);
+ if (prefix != NULL)
+ *prefix = SEP;
+ if (p == NULL)
+ break;
+ *p = '\0';
+ prefix = p;
+ }
+ if (path != NULL) {
+ PyObject *files;
+ files = PyDict_GetItemString(zip_directory_cache, path);
+ if (files == NULL) {
+ files = read_directory(buf);
+ if (files == NULL)
+ return -1;
+ if (PyDict_SetItemString(zip_directory_cache, path,
+ files) != 0)
+ return -1;
+ }
+ else
+ Py_INCREF(files);
+ self->files = files;
+ }
+ else {
+ PyErr_SetString(ZipImportError, "not a Zip file");
+ return -1;
+ }
+
+ if (prefix == NULL)
+ prefix = "";
+ else {
+ prefix++;
+ len = strlen(prefix);
+ if (prefix[len-1] != SEP) {
+ /* add trailing SEP */
+ prefix[len] = SEP;
+ prefix[len + 1] = '\0';
+ }
+ }
+
+ self->archive = PyString_FromString(buf);
+ if (self->archive == NULL)
+ return -1;
+
+ self->prefix = PyString_FromString(prefix);
+ if (self->prefix == NULL)
+ return -1;
+
+ return 0;
}
/* GC support. */
static int
zipimporter_traverse(PyObject *obj, visitproc visit, void *arg)
{
- ZipImporter *self = (ZipImporter *)obj;
- Py_VISIT(self->files);
- return 0;
+ ZipImporter *self = (ZipImporter *)obj;
+ Py_VISIT(self->files);
+ return 0;
}
static void
zipimporter_dealloc(ZipImporter *self)
{
- PyObject_GC_UnTrack(self);
- Py_XDECREF(self->archive);
- Py_XDECREF(self->prefix);
- Py_XDECREF(self->files);
- Py_TYPE(self)->tp_free((PyObject *)self);
+ PyObject_GC_UnTrack(self);
+ Py_XDECREF(self->archive);
+ Py_XDECREF(self->prefix);
+ Py_XDECREF(self->files);
+ Py_TYPE(self)->tp_free((PyObject *)self);
}
static PyObject *
zipimporter_repr(ZipImporter *self)
{
- char buf[500];
- char *archive = "???";
- char *prefix = "";
-
- if (self->archive != NULL && PyString_Check(self->archive))
- archive = PyString_AsString(self->archive);
- if (self->prefix != NULL && PyString_Check(self->prefix))
- prefix = PyString_AsString(self->prefix);
- if (prefix != NULL && *prefix)
- PyOS_snprintf(buf, sizeof(buf),
- "<zipimporter object \"%.300s%c%.150s\">",
- archive, SEP, prefix);
- else
- PyOS_snprintf(buf, sizeof(buf),
- "<zipimporter object \"%.300s\">",
- archive);
- return PyString_FromString(buf);
+ char buf[500];
+ char *archive = "???";
+ char *prefix = "";
+
+ if (self->archive != NULL && PyString_Check(self->archive))
+ archive = PyString_AsString(self->archive);
+ if (self->prefix != NULL && PyString_Check(self->prefix))
+ prefix = PyString_AsString(self->prefix);
+ if (prefix != NULL && *prefix)
+ PyOS_snprintf(buf, sizeof(buf),
+ "<zipimporter object \"%.300s%c%.150s\">",
+ archive, SEP, prefix);
+ else
+ PyOS_snprintf(buf, sizeof(buf),
+ "<zipimporter object \"%.300s\">",
+ archive);
+ return PyString_FromString(buf);
}
/* return fullname.split(".")[-1] */
static char *
get_subname(char *fullname)
{
- char *subname = strrchr(fullname, '.');
- if (subname == NULL)
- subname = fullname;
- else
- subname++;
- return subname;
+ char *subname = strrchr(fullname, '.');
+ if (subname == NULL)
+ subname = fullname;
+ else
+ subname++;
+ return subname;
}
/* Given a (sub)modulename, write the potential file path in the
@@ -224,59 +224,59 @@ get_subname(char *fullname)
static int
make_filename(char *prefix, char *name, char *path)
{
- size_t len;
- char *p;
-
- len = strlen(prefix);
-
- /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */
- if (len + strlen(name) + 13 >= MAXPATHLEN) {
- PyErr_SetString(ZipImportError, "path too long");
- return -1;
- }
-
- strcpy(path, prefix);
- strcpy(path + len, name);
- for (p = path + len; *p; p++) {
- if (*p == '.')
- *p = SEP;
- }
- len += strlen(name);
- assert(len < INT_MAX);
- return (int)len;
+ size_t len;
+ char *p;
+
+ len = strlen(prefix);
+
+ /* self.prefix + name [+ SEP + "__init__"] + ".py[co]" */
+ if (len + strlen(name) + 13 >= MAXPATHLEN) {
+ PyErr_SetString(ZipImportError, "path too long");
+ return -1;
+ }
+
+ strcpy(path, prefix);
+ strcpy(path + len, name);
+ for (p = path + len; *p; p++) {
+ if (*p == '.')
+ *p = SEP;
+ }
+ len += strlen(name);
+ assert(len < INT_MAX);
+ return (int)len;
}
enum zi_module_info {
- MI_ERROR,
- MI_NOT_FOUND,
- MI_MODULE,
- MI_PACKAGE
+ MI_ERROR,
+ MI_NOT_FOUND,
+ MI_MODULE,
+ MI_PACKAGE
};
/* Return some information about a module. */
static enum zi_module_info
get_module_info(ZipImporter *self, char *fullname)
{
- char *subname, path[MAXPATHLEN + 1];
- int len;
- struct st_zip_searchorder *zso;
-
- subname = get_subname(fullname);
-
- len = make_filename(PyString_AsString(self->prefix), subname, path);
- if (len < 0)
- return MI_ERROR;
-
- for (zso = zip_searchorder; *zso->suffix; zso++) {
- strcpy(path + len, zso->suffix);
- if (PyDict_GetItemString(self->files, path) != NULL) {
- if (zso->type & IS_PACKAGE)
- return MI_PACKAGE;
- else
- return MI_MODULE;
- }
- }
- return MI_NOT_FOUND;
+ char *subname, path[MAXPATHLEN + 1];
+ int len;
+ struct st_zip_searchorder *zso;
+
+ subname = get_subname(fullname);
+
+ len = make_filename(PyString_AsString(self->prefix), subname, path);
+ if (len < 0)
+ return MI_ERROR;
+
+ for (zso = zip_searchorder; *zso->suffix; zso++) {
+ strcpy(path + len, zso->suffix);
+ if (PyDict_GetItemString(self->files, path) != NULL) {
+ if (zso->type & IS_PACKAGE)
+ return MI_PACKAGE;
+ else
+ return MI_MODULE;
+ }
+ }
+ return MI_NOT_FOUND;
}
/* Check whether we can satisfy the import of the module named by
@@ -284,89 +284,89 @@ get_module_info(ZipImporter *self, char *fullname)
static PyObject *
zipimporter_find_module(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- PyObject *path = NULL;
- char *fullname;
- enum zi_module_info mi;
-
- if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module",
- &fullname, &path))
- return NULL;
-
- mi = get_module_info(self, fullname);
- if (mi == MI_ERROR)
- return NULL;
- if (mi == MI_NOT_FOUND) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- Py_INCREF(self);
- return (PyObject *)self;
+ ZipImporter *self = (ZipImporter *)obj;
+ PyObject *path = NULL;
+ char *fullname;
+ enum zi_module_info mi;
+
+ if (!PyArg_ParseTuple(args, "s|O:zipimporter.find_module",
+ &fullname, &path))
+ return NULL;
+
+ mi = get_module_info(self, fullname);
+ if (mi == MI_ERROR)
+ return NULL;
+ if (mi == MI_NOT_FOUND) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ Py_INCREF(self);
+ return (PyObject *)self;
}
/* Load and return the module named by 'fullname'. */
static PyObject *
zipimporter_load_module(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- PyObject *code, *mod, *dict;
- char *fullname, *modpath;
- int ispackage;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter.load_module",
- &fullname))
- return NULL;
-
- code = get_module_code(self, fullname, &ispackage, &modpath);
- if (code == NULL)
- return NULL;
-
- mod = PyImport_AddModule(fullname);
- if (mod == NULL) {
- Py_DECREF(code);
- return NULL;
- }
- dict = PyModule_GetDict(mod);
-
- /* mod.__loader__ = self */
- if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
- goto error;
-
- if (ispackage) {
- /* add __path__ to the module *before* the code gets
- executed */
- PyObject *pkgpath, *fullpath;
- char *prefix = PyString_AsString(self->prefix);
- char *subname = get_subname(fullname);
- int err;
-
- fullpath = PyString_FromFormat("%s%c%s%s",
- PyString_AsString(self->archive),
- SEP,
- *prefix ? prefix : "",
- subname);
- if (fullpath == NULL)
- goto error;
-
- pkgpath = Py_BuildValue("[O]", fullpath);
- Py_DECREF(fullpath);
- if (pkgpath == NULL)
- goto error;
- err = PyDict_SetItemString(dict, "__path__", pkgpath);
- Py_DECREF(pkgpath);
- if (err != 0)
- goto error;
- }
- mod = PyImport_ExecCodeModuleEx(fullname, code, modpath);
- Py_DECREF(code);
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # loaded from Zip %s\n",
- fullname, modpath);
- return mod;
+ ZipImporter *self = (ZipImporter *)obj;
+ PyObject *code, *mod, *dict;
+ char *fullname, *modpath;
+ int ispackage;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter.load_module",
+ &fullname))
+ return NULL;
+
+ code = get_module_code(self, fullname, &ispackage, &modpath);
+ if (code == NULL)
+ return NULL;
+
+ mod = PyImport_AddModule(fullname);
+ if (mod == NULL) {
+ Py_DECREF(code);
+ return NULL;
+ }
+ dict = PyModule_GetDict(mod);
+
+ /* mod.__loader__ = self */
+ if (PyDict_SetItemString(dict, "__loader__", (PyObject *)self) != 0)
+ goto error;
+
+ if (ispackage) {
+ /* add __path__ to the module *before* the code gets
+ executed */
+ PyObject *pkgpath, *fullpath;
+ char *prefix = PyString_AsString(self->prefix);
+ char *subname = get_subname(fullname);
+ int err;
+
+ fullpath = PyString_FromFormat("%s%c%s%s",
+ PyString_AsString(self->archive),
+ SEP,
+ *prefix ? prefix : "",
+ subname);
+ if (fullpath == NULL)
+ goto error;
+
+ pkgpath = Py_BuildValue("[O]", fullpath);
+ Py_DECREF(fullpath);
+ if (pkgpath == NULL)
+ goto error;
+ err = PyDict_SetItemString(dict, "__path__", pkgpath);
+ Py_DECREF(pkgpath);
+ if (err != 0)
+ goto error;
+ }
+ mod = PyImport_ExecCodeModuleEx(fullname, code, modpath);
+ Py_DECREF(code);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # loaded from Zip %s\n",
+ fullname, modpath);
+ return mod;
error:
- Py_DECREF(code);
- Py_DECREF(mod);
- return NULL;
+ Py_DECREF(code);
+ Py_DECREF(mod);
+ return NULL;
}
/* Return a string matching __file__ for the named module */
@@ -380,13 +380,13 @@ zipimporter_get_filename(PyObject *obj, PyObject *args)
if (!PyArg_ParseTuple(args, "s:zipimporter.get_filename",
&fullname))
- return NULL;
+ return NULL;
/* Deciding the filename requires working out where the code
would come from if the module was actually loaded */
code = get_module_code(self, fullname, &ispackage, &modpath);
if (code == NULL)
- return NULL;
+ return NULL;
Py_DECREF(code); /* Only need the path info */
return PyString_FromString(modpath);
@@ -396,118 +396,118 @@ zipimporter_get_filename(PyObject *obj, PyObject *args)
static PyObject *
zipimporter_is_package(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- char *fullname;
- enum zi_module_info mi;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter.is_package",
- &fullname))
- return NULL;
-
- mi = get_module_info(self, fullname);
- if (mi == MI_ERROR)
- return NULL;
- if (mi == MI_NOT_FOUND) {
- PyErr_Format(ZipImportError, "can't find module '%.200s'",
- fullname);
- return NULL;
- }
- return PyBool_FromLong(mi == MI_PACKAGE);
+ ZipImporter *self = (ZipImporter *)obj;
+ char *fullname;
+ enum zi_module_info mi;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter.is_package",
+ &fullname))
+ return NULL;
+
+ mi = get_module_info(self, fullname);
+ if (mi == MI_ERROR)
+ return NULL;
+ if (mi == MI_NOT_FOUND) {
+ PyErr_Format(ZipImportError, "can't find module '%.200s'",
+ fullname);
+ return NULL;
+ }
+ return PyBool_FromLong(mi == MI_PACKAGE);
}
static PyObject *
zipimporter_get_data(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- char *path;
+ ZipImporter *self = (ZipImporter *)obj;
+ char *path;
#ifdef ALTSEP
- char *p, buf[MAXPATHLEN + 1];
+ char *p, buf[MAXPATHLEN + 1];
#endif
- PyObject *toc_entry;
- Py_ssize_t len;
+ PyObject *toc_entry;
+ Py_ssize_t len;
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:zipimporter.get_data", &path))
+ return NULL;
#ifdef ALTSEP
- if (strlen(path) >= MAXPATHLEN) {
- PyErr_SetString(ZipImportError, "path too long");
- return NULL;
- }
- strcpy(buf, path);
- for (p = buf; *p; p++) {
- if (*p == ALTSEP)
- *p = SEP;
- }
- path = buf;
+ if (strlen(path) >= MAXPATHLEN) {
+ PyErr_SetString(ZipImportError, "path too long");
+ return NULL;
+ }
+ strcpy(buf, path);
+ for (p = buf; *p; p++) {
+ if (*p == ALTSEP)
+ *p = SEP;
+ }
+ path = buf;
#endif
- len = PyString_Size(self->archive);
- if ((size_t)len < strlen(path) &&
- strncmp(path, PyString_AsString(self->archive), len) == 0 &&
- path[len] == SEP) {
- path = path + len + 1;
- }
-
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry == NULL) {
- PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
- return NULL;
- }
- return get_data(PyString_AsString(self->archive), toc_entry);
+ len = PyString_Size(self->archive);
+ if ((size_t)len < strlen(path) &&
+ strncmp(path, PyString_AsString(self->archive), len) == 0 &&
+ path[len] == SEP) {
+ path = path + len + 1;
+ }
+
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry == NULL) {
+ PyErr_SetFromErrnoWithFilename(PyExc_IOError, path);
+ return NULL;
+ }
+ return get_data(PyString_AsString(self->archive), toc_entry);
}
static PyObject *
zipimporter_get_code(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- char *fullname;
+ ZipImporter *self = (ZipImporter *)obj;
+ char *fullname;
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname))
- return NULL;
+ if (!PyArg_ParseTuple(args, "s:zipimporter.get_code", &fullname))
+ return NULL;
- return get_module_code(self, fullname, NULL, NULL);
+ return get_module_code(self, fullname, NULL, NULL);
}
static PyObject *
zipimporter_get_source(PyObject *obj, PyObject *args)
{
- ZipImporter *self = (ZipImporter *)obj;
- PyObject *toc_entry;
- char *fullname, *subname, path[MAXPATHLEN+1];
- int len;
- enum zi_module_info mi;
-
- if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname))
- return NULL;
-
- mi = get_module_info(self, fullname);
- if (mi == MI_ERROR)
- return NULL;
- if (mi == MI_NOT_FOUND) {
- PyErr_Format(ZipImportError, "can't find module '%.200s'",
- fullname);
- return NULL;
- }
- subname = get_subname(fullname);
-
- len = make_filename(PyString_AsString(self->prefix), subname, path);
- if (len < 0)
- return NULL;
-
- if (mi == MI_PACKAGE) {
- path[len] = SEP;
- strcpy(path + len + 1, "__init__.py");
- }
- else
- strcpy(path + len, ".py");
-
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry != NULL)
- return get_data(PyString_AsString(self->archive), toc_entry);
-
- /* we have the module, but no source */
- Py_INCREF(Py_None);
- return Py_None;
+ ZipImporter *self = (ZipImporter *)obj;
+ PyObject *toc_entry;
+ char *fullname, *subname, path[MAXPATHLEN+1];
+ int len;
+ enum zi_module_info mi;
+
+ if (!PyArg_ParseTuple(args, "s:zipimporter.get_source", &fullname))
+ return NULL;
+
+ mi = get_module_info(self, fullname);
+ if (mi == MI_ERROR)
+ return NULL;
+ if (mi == MI_NOT_FOUND) {
+ PyErr_Format(ZipImportError, "can't find module '%.200s'",
+ fullname);
+ return NULL;
+ }
+ subname = get_subname(fullname);
+
+ len = make_filename(PyString_AsString(self->prefix), subname, path);
+ if (len < 0)
+ return NULL;
+
+ if (mi == MI_PACKAGE) {
+ path[len] = SEP;
+ strcpy(path + len + 1, "__init__.py");
+ }
+ else
+ strcpy(path + len, ".py");
+
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry != NULL)
+ return get_data(PyString_AsString(self->archive), toc_entry);
+
+ /* we have the module, but no source */
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(doc_find_module,
@@ -558,28 +558,28 @@ PyDoc_STRVAR(doc_get_filename,
Return the filename for the specified module.");
static PyMethodDef zipimporter_methods[] = {
- {"find_module", zipimporter_find_module, METH_VARARGS,
- doc_find_module},
- {"load_module", zipimporter_load_module, METH_VARARGS,
- doc_load_module},
- {"get_data", zipimporter_get_data, METH_VARARGS,
- doc_get_data},
- {"get_code", zipimporter_get_code, METH_VARARGS,
- doc_get_code},
- {"get_source", zipimporter_get_source, METH_VARARGS,
- doc_get_source},
- {"get_filename", zipimporter_get_filename, METH_VARARGS,
- doc_get_filename},
- {"is_package", zipimporter_is_package, METH_VARARGS,
- doc_is_package},
- {NULL, NULL} /* sentinel */
+ {"find_module", zipimporter_find_module, METH_VARARGS,
+ doc_find_module},
+ {"load_module", zipimporter_load_module, METH_VARARGS,
+ doc_load_module},
+ {"get_data", zipimporter_get_data, METH_VARARGS,
+ doc_get_data},
+ {"get_code", zipimporter_get_code, METH_VARARGS,
+ doc_get_code},
+ {"get_source", zipimporter_get_source, METH_VARARGS,
+ doc_get_source},
+ {"get_filename", zipimporter_get_filename, METH_VARARGS,
+ doc_get_filename},
+ {"is_package", zipimporter_is_package, METH_VARARGS,
+ doc_is_package},
+ {NULL, NULL} /* sentinel */
};
static PyMemberDef zipimporter_members[] = {
- {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
- {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
- {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
- {NULL}
+ {"archive", T_OBJECT, offsetof(ZipImporter, archive), READONLY},
+ {"prefix", T_OBJECT, offsetof(ZipImporter, prefix), READONLY},
+ {"_files", T_OBJECT, offsetof(ZipImporter, files), READONLY},
+ {NULL}
};
PyDoc_STRVAR(zipimporter_doc,
@@ -599,46 +599,46 @@ zipfile targeted.");
#define DEFERRED_ADDRESS(ADDR) 0
static PyTypeObject ZipImporter_Type = {
- PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
- "zipimport.zipimporter",
- sizeof(ZipImporter),
- 0, /* tp_itemsize */
- (destructor)zipimporter_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)zipimporter_repr, /* 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 |
- Py_TPFLAGS_HAVE_GC, /* tp_flags */
- zipimporter_doc, /* tp_doc */
- zipimporter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- zipimporter_methods, /* tp_methods */
- zipimporter_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- (initproc)zipimporter_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(DEFERRED_ADDRESS(&PyType_Type), 0)
+ "zipimport.zipimporter",
+ sizeof(ZipImporter),
+ 0, /* tp_itemsize */
+ (destructor)zipimporter_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)zipimporter_repr, /* 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 |
+ Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ zipimporter_doc, /* tp_doc */
+ zipimporter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ zipimporter_methods, /* tp_methods */
+ zipimporter_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ (initproc)zipimporter_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -649,16 +649,16 @@ static PyTypeObject ZipImporter_Type = {
marshal.c:r_long() */
static long
get_long(unsigned char *buf) {
- long x;
- x = buf[0];
- x |= (long)buf[1] << 8;
- x |= (long)buf[2] << 16;
- x |= (long)buf[3] << 24;
+ long x;
+ x = buf[0];
+ x |= (long)buf[1] << 8;
+ x |= (long)buf[2] << 16;
+ x |= (long)buf[3] << 24;
#if SIZEOF_LONG > 4
- /* Sign extension for 64-bit machines */
- x |= -(x & 0x80000000L);
+ /* Sign extension for 64-bit machines */
+ x |= -(x & 0x80000000L);
#endif
- return x;
+ return x;
}
/*
@@ -670,13 +670,13 @@ get_long(unsigned char *buf) {
A toc_entry is a tuple:
(__file__, # value to use for __file__, available for all files
- compress, # compression kind; 0 for uncompressed
- data_size, # size of compressed data on disk
- file_size, # size of decompressed data
- file_offset, # offset of file header from start of archive
- time, # mod time of file (in dos format)
- date, # mod data of file (in dos format)
- crc, # crc checksum of the data
+ compress, # compression kind; 0 for uncompressed
+ data_size, # size of compressed data on disk
+ file_size, # size of decompressed data
+ file_offset, # offset of file header from start of archive
+ time, # mod time of file (in dos format)
+ date, # mod data of file (in dos format)
+ crc, # crc checksum of the data
)
Directories can be recognized by the trailing SEP in the name,
@@ -685,115 +685,115 @@ get_long(unsigned char *buf) {
static PyObject *
read_directory(char *archive)
{
- PyObject *files = NULL;
- FILE *fp;
- long compress, crc, data_size, file_size, file_offset, date, time;
- long header_offset, name_size, header_size, header_position;
- long i, l, count;
- size_t length;
- char path[MAXPATHLEN + 5];
- char name[MAXPATHLEN + 5];
- char *p, endof_central_dir[22];
- long arc_offset; /* offset from beginning of file to start of zip-archive */
-
- if (strlen(archive) > MAXPATHLEN) {
- PyErr_SetString(PyExc_OverflowError,
- "Zip path name is too long");
- return NULL;
- }
- strcpy(path, archive);
-
- fp = fopen(archive, "rb");
- if (fp == NULL) {
- PyErr_Format(ZipImportError, "can't open Zip file: "
- "'%.200s'", archive);
- return NULL;
- }
- fseek(fp, -22, SEEK_END);
- header_position = ftell(fp);
- if (fread(endof_central_dir, 1, 22, fp) != 22) {
- fclose(fp);
- PyErr_Format(ZipImportError, "can't read Zip file: "
- "'%.200s'", archive);
- return NULL;
- }
- if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
- /* Bad: End of Central Dir signature */
- fclose(fp);
- PyErr_Format(ZipImportError, "not a Zip file: "
- "'%.200s'", archive);
- return NULL;
- }
-
- header_size = get_long((unsigned char *)endof_central_dir + 12);
- header_offset = get_long((unsigned char *)endof_central_dir + 16);
- arc_offset = header_position - header_offset - header_size;
- header_offset += arc_offset;
-
- files = PyDict_New();
- if (files == NULL)
- goto error;
-
- length = (long)strlen(path);
- path[length] = SEP;
-
- /* Start of Central Directory */
- count = 0;
- for (;;) {
- PyObject *t;
- int err;
-
- fseek(fp, header_offset, 0); /* Start of file header */
- l = PyMarshal_ReadLongFromFile(fp);
- if (l != 0x02014B50)
- break; /* Bad: Central Dir File Header */
- fseek(fp, header_offset + 10, 0);
- compress = PyMarshal_ReadShortFromFile(fp);
- time = PyMarshal_ReadShortFromFile(fp);
- date = PyMarshal_ReadShortFromFile(fp);
- crc = PyMarshal_ReadLongFromFile(fp);
- data_size = PyMarshal_ReadLongFromFile(fp);
- file_size = PyMarshal_ReadLongFromFile(fp);
- name_size = PyMarshal_ReadShortFromFile(fp);
- header_size = 46 + name_size +
- PyMarshal_ReadShortFromFile(fp) +
- PyMarshal_ReadShortFromFile(fp);
- fseek(fp, header_offset + 42, 0);
- file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
- if (name_size > MAXPATHLEN)
- name_size = MAXPATHLEN;
-
- p = name;
- for (i = 0; i < name_size; i++) {
- *p = (char)getc(fp);
- if (*p == '/')
- *p = SEP;
- p++;
- }
- *p = 0; /* Add terminating null byte */
- header_offset += header_size;
-
- strncpy(path + length + 1, name, MAXPATHLEN - length - 1);
-
- t = Py_BuildValue("siiiiiii", path, compress, data_size,
- file_size, file_offset, time, date, crc);
- if (t == NULL)
- goto error;
- err = PyDict_SetItemString(files, name, t);
- Py_DECREF(t);
- if (err != 0)
- goto error;
- count++;
- }
- fclose(fp);
- if (Py_VerboseFlag)
- PySys_WriteStderr("# zipimport: found %ld names in %s\n",
- count, archive);
- return files;
+ PyObject *files = NULL;
+ FILE *fp;
+ long compress, crc, data_size, file_size, file_offset, date, time;
+ long header_offset, name_size, header_size, header_position;
+ long i, l, count;
+ size_t length;
+ char path[MAXPATHLEN + 5];
+ char name[MAXPATHLEN + 5];
+ char *p, endof_central_dir[22];
+ long arc_offset; /* offset from beginning of file to start of zip-archive */
+
+ if (strlen(archive) > MAXPATHLEN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Zip path name is too long");
+ return NULL;
+ }
+ strcpy(path, archive);
+
+ fp = fopen(archive, "rb");
+ if (fp == NULL) {
+ PyErr_Format(ZipImportError, "can't open Zip file: "
+ "'%.200s'", archive);
+ return NULL;
+ }
+ fseek(fp, -22, SEEK_END);
+ header_position = ftell(fp);
+ if (fread(endof_central_dir, 1, 22, fp) != 22) {
+ fclose(fp);
+ PyErr_Format(ZipImportError, "can't read Zip file: "
+ "'%.200s'", archive);
+ return NULL;
+ }
+ if (get_long((unsigned char *)endof_central_dir) != 0x06054B50) {
+ /* Bad: End of Central Dir signature */
+ fclose(fp);
+ PyErr_Format(ZipImportError, "not a Zip file: "
+ "'%.200s'", archive);
+ return NULL;
+ }
+
+ header_size = get_long((unsigned char *)endof_central_dir + 12);
+ header_offset = get_long((unsigned char *)endof_central_dir + 16);
+ arc_offset = header_position - header_offset - header_size;
+ header_offset += arc_offset;
+
+ files = PyDict_New();
+ if (files == NULL)
+ goto error;
+
+ length = (long)strlen(path);
+ path[length] = SEP;
+
+ /* Start of Central Directory */
+ count = 0;
+ for (;;) {
+ PyObject *t;
+ int err;
+
+ fseek(fp, header_offset, 0); /* Start of file header */
+ l = PyMarshal_ReadLongFromFile(fp);
+ if (l != 0x02014B50)
+ break; /* Bad: Central Dir File Header */
+ fseek(fp, header_offset + 10, 0);
+ compress = PyMarshal_ReadShortFromFile(fp);
+ time = PyMarshal_ReadShortFromFile(fp);
+ date = PyMarshal_ReadShortFromFile(fp);
+ crc = PyMarshal_ReadLongFromFile(fp);
+ data_size = PyMarshal_ReadLongFromFile(fp);
+ file_size = PyMarshal_ReadLongFromFile(fp);
+ name_size = PyMarshal_ReadShortFromFile(fp);
+ header_size = 46 + name_size +
+ PyMarshal_ReadShortFromFile(fp) +
+ PyMarshal_ReadShortFromFile(fp);
+ fseek(fp, header_offset + 42, 0);
+ file_offset = PyMarshal_ReadLongFromFile(fp) + arc_offset;
+ if (name_size > MAXPATHLEN)
+ name_size = MAXPATHLEN;
+
+ p = name;
+ for (i = 0; i < name_size; i++) {
+ *p = (char)getc(fp);
+ if (*p == '/')
+ *p = SEP;
+ p++;
+ }
+ *p = 0; /* Add terminating null byte */
+ header_offset += header_size;
+
+ strncpy(path + length + 1, name, MAXPATHLEN - length - 1);
+
+ t = Py_BuildValue("siiiiiii", path, compress, data_size,
+ file_size, file_offset, time, date, crc);
+ if (t == NULL)
+ goto error;
+ err = PyDict_SetItemString(files, name, t);
+ Py_DECREF(t);
+ if (err != 0)
+ goto error;
+ count++;
+ }
+ fclose(fp);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# zipimport: found %ld names in %s\n",
+ count, archive);
+ return files;
error:
- fclose(fp);
- Py_XDECREF(files);
- return NULL;
+ fclose(fp);
+ Py_XDECREF(files);
+ return NULL;
}
/* Return the zlib.decompress function object, or NULL if zlib couldn't
@@ -803,31 +803,31 @@ error:
static PyObject *
get_decompress_func(void)
{
- static PyObject *decompress = NULL;
-
- if (decompress == NULL) {
- PyObject *zlib;
- static int importing_zlib = 0;
-
- if (importing_zlib != 0)
- /* Someone has a zlib.py[co] in their Zip file;
- let's avoid a stack overflow. */
- return NULL;
- importing_zlib = 1;
- zlib = PyImport_ImportModuleNoBlock("zlib");
- importing_zlib = 0;
- if (zlib != NULL) {
- decompress = PyObject_GetAttrString(zlib,
- "decompress");
- Py_DECREF(zlib);
- }
- else
- PyErr_Clear();
- if (Py_VerboseFlag)
- PySys_WriteStderr("# zipimport: zlib %s\n",
- zlib != NULL ? "available": "UNAVAILABLE");
- }
- return decompress;
+ static PyObject *decompress = NULL;
+
+ if (decompress == NULL) {
+ PyObject *zlib;
+ static int importing_zlib = 0;
+
+ if (importing_zlib != 0)
+ /* Someone has a zlib.py[co] in their Zip file;
+ let's avoid a stack overflow. */
+ return NULL;
+ importing_zlib = 1;
+ zlib = PyImport_ImportModuleNoBlock("zlib");
+ importing_zlib = 0;
+ if (zlib != NULL) {
+ decompress = PyObject_GetAttrString(zlib,
+ "decompress");
+ Py_DECREF(zlib);
+ }
+ else
+ PyErr_Clear();
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# zipimport: zlib %s\n",
+ zlib != NULL ? "available": "UNAVAILABLE");
+ }
+ return decompress;
}
/* Given a path to a Zip file and a toc_entry, return the (uncompressed)
@@ -835,85 +835,85 @@ get_decompress_func(void)
static PyObject *
get_data(char *archive, PyObject *toc_entry)
{
- PyObject *raw_data, *data = NULL, *decompress;
- char *buf;
- FILE *fp;
- int err;
- Py_ssize_t bytes_read = 0;
- long l;
- char *datapath;
- long compress, data_size, file_size, file_offset;
- long time, date, crc;
-
- if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,
- &data_size, &file_size, &file_offset, &time,
- &date, &crc)) {
- return NULL;
- }
-
- fp = fopen(archive, "rb");
- if (!fp) {
- PyErr_Format(PyExc_IOError,
- "zipimport: can not open file %s", archive);
- return NULL;
- }
-
- /* Check to make sure the local file header is correct */
- fseek(fp, file_offset, 0);
- l = PyMarshal_ReadLongFromFile(fp);
- if (l != 0x04034B50) {
- /* Bad: Local File Header */
- PyErr_Format(ZipImportError,
- "bad local file header in %s",
- archive);
- fclose(fp);
- return NULL;
- }
- fseek(fp, file_offset + 26, 0);
- l = 30 + PyMarshal_ReadShortFromFile(fp) +
- PyMarshal_ReadShortFromFile(fp); /* local header size */
- file_offset += l; /* Start of file data */
-
- raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?
- data_size : data_size + 1);
- if (raw_data == NULL) {
- fclose(fp);
- return NULL;
- }
- buf = PyString_AsString(raw_data);
-
- err = fseek(fp, file_offset, 0);
- if (err == 0)
- bytes_read = fread(buf, 1, data_size, fp);
- fclose(fp);
- if (err || bytes_read != data_size) {
- PyErr_SetString(PyExc_IOError,
- "zipimport: can't read data");
- Py_DECREF(raw_data);
- return NULL;
- }
-
- if (compress != 0) {
- buf[data_size] = 'Z'; /* saw this in zipfile.py */
- data_size++;
- }
- buf[data_size] = '\0';
-
- if (compress == 0) /* data is not compressed */
- return raw_data;
-
- /* Decompress with zlib */
- decompress = get_decompress_func();
- if (decompress == NULL) {
- PyErr_SetString(ZipImportError,
- "can't decompress data; "
- "zlib not available");
- goto error;
- }
- data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
+ PyObject *raw_data, *data = NULL, *decompress;
+ char *buf;
+ FILE *fp;
+ int err;
+ Py_ssize_t bytes_read = 0;
+ long l;
+ char *datapath;
+ long compress, data_size, file_size, file_offset;
+ long time, date, crc;
+
+ if (!PyArg_ParseTuple(toc_entry, "slllllll", &datapath, &compress,
+ &data_size, &file_size, &file_offset, &time,
+ &date, &crc)) {
+ return NULL;
+ }
+
+ fp = fopen(archive, "rb");
+ if (!fp) {
+ PyErr_Format(PyExc_IOError,
+ "zipimport: can not open file %s", archive);
+ return NULL;
+ }
+
+ /* Check to make sure the local file header is correct */
+ fseek(fp, file_offset, 0);
+ l = PyMarshal_ReadLongFromFile(fp);
+ if (l != 0x04034B50) {
+ /* Bad: Local File Header */
+ PyErr_Format(ZipImportError,
+ "bad local file header in %s",
+ archive);
+ fclose(fp);
+ return NULL;
+ }
+ fseek(fp, file_offset + 26, 0);
+ l = 30 + PyMarshal_ReadShortFromFile(fp) +
+ PyMarshal_ReadShortFromFile(fp); /* local header size */
+ file_offset += l; /* Start of file data */
+
+ raw_data = PyString_FromStringAndSize((char *)NULL, compress == 0 ?
+ data_size : data_size + 1);
+ if (raw_data == NULL) {
+ fclose(fp);
+ return NULL;
+ }
+ buf = PyString_AsString(raw_data);
+
+ err = fseek(fp, file_offset, 0);
+ if (err == 0)
+ bytes_read = fread(buf, 1, data_size, fp);
+ fclose(fp);
+ if (err || bytes_read != data_size) {
+ PyErr_SetString(PyExc_IOError,
+ "zipimport: can't read data");
+ Py_DECREF(raw_data);
+ return NULL;
+ }
+
+ if (compress != 0) {
+ buf[data_size] = 'Z'; /* saw this in zipfile.py */
+ data_size++;
+ }
+ buf[data_size] = '\0';
+
+ if (compress == 0) /* data is not compressed */
+ return raw_data;
+
+ /* Decompress with zlib */
+ decompress = get_decompress_func();
+ if (decompress == NULL) {
+ PyErr_SetString(ZipImportError,
+ "can't decompress data; "
+ "zlib not available");
+ goto error;
+ }
+ data = PyObject_CallFunction(decompress, "Oi", raw_data, -15);
error:
- Py_DECREF(raw_data);
- return data;
+ Py_DECREF(raw_data);
+ return data;
}
/* Lenient date/time comparison function. The precision of the mtime
@@ -922,11 +922,11 @@ error:
static int
eq_mtime(time_t t1, time_t t2)
{
- time_t d = t1 - t2;
- if (d < 0)
- d = -d;
- /* dostime only stores even seconds, so be lenient */
- return d <= 1;
+ time_t d = t1 - t2;
+ if (d < 0)
+ d = -d;
+ /* dostime only stores even seconds, so be lenient */
+ return d <= 1;
}
/* Given the contents of a .py[co] file in a buffer, unmarshal the data
@@ -937,44 +937,44 @@ eq_mtime(time_t t1, time_t t2)
static PyObject *
unmarshal_code(char *pathname, PyObject *data, time_t mtime)
{
- PyObject *code;
- char *buf = PyString_AsString(data);
- Py_ssize_t size = PyString_Size(data);
-
- if (size <= 9) {
- PyErr_SetString(ZipImportError,
- "bad pyc data");
- return NULL;
- }
-
- if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s has bad magic\n",
- pathname);
- Py_INCREF(Py_None);
- return Py_None; /* signal caller to try alternative */
- }
-
- if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
- mtime)) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s has bad mtime\n",
- pathname);
- Py_INCREF(Py_None);
- return Py_None; /* signal caller to try alternative */
- }
-
- code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
- if (code == NULL)
- return NULL;
- if (!PyCode_Check(code)) {
- Py_DECREF(code);
- PyErr_Format(PyExc_TypeError,
- "compiled module %.200s is not a code object",
- pathname);
- return NULL;
- }
- return code;
+ PyObject *code;
+ char *buf = PyString_AsString(data);
+ Py_ssize_t size = PyString_Size(data);
+
+ if (size <= 9) {
+ PyErr_SetString(ZipImportError,
+ "bad pyc data");
+ return NULL;
+ }
+
+ if (get_long((unsigned char *)buf) != PyImport_GetMagicNumber()) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s has bad magic\n",
+ pathname);
+ Py_INCREF(Py_None);
+ return Py_None; /* signal caller to try alternative */
+ }
+
+ if (mtime != 0 && !eq_mtime(get_long((unsigned char *)buf + 4),
+ mtime)) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s has bad mtime\n",
+ pathname);
+ Py_INCREF(Py_None);
+ return Py_None; /* signal caller to try alternative */
+ }
+
+ code = PyMarshal_ReadObjectFromString(buf + 8, size - 8);
+ if (code == NULL)
+ return NULL;
+ if (!PyCode_Check(code)) {
+ Py_DECREF(code);
+ PyErr_Format(PyExc_TypeError,
+ "compiled module %.200s is not a code object",
+ pathname);
+ return NULL;
+ }
+ return code;
}
/* Replace any occurances of "\r\n?" in the input string with "\n".
@@ -984,35 +984,35 @@ unmarshal_code(char *pathname, PyObject *data, time_t mtime)
static PyObject *
normalize_line_endings(PyObject *source)
{
- char *buf, *q, *p = PyString_AsString(source);
- PyObject *fixed_source;
-
- if (!p)
- return NULL;
-
- /* one char extra for trailing \n and one for terminating \0 */
- buf = (char *)PyMem_Malloc(PyString_Size(source) + 2);
- if (buf == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "zipimport: no memory to allocate "
- "source buffer");
- return NULL;
- }
- /* replace "\r\n?" by "\n" */
- for (q = buf; *p != '\0'; p++) {
- if (*p == '\r') {
- *q++ = '\n';
- if (*(p + 1) == '\n')
- p++;
- }
- else
- *q++ = *p;
- }
- *q++ = '\n'; /* add trailing \n */
- *q = '\0';
- fixed_source = PyString_FromString(buf);
- PyMem_Free(buf);
- return fixed_source;
+ char *buf, *q, *p = PyString_AsString(source);
+ PyObject *fixed_source;
+
+ if (!p)
+ return NULL;
+
+ /* one char extra for trailing \n and one for terminating \0 */
+ buf = (char *)PyMem_Malloc(PyString_Size(source) + 2);
+ if (buf == NULL) {
+ PyErr_SetString(PyExc_MemoryError,
+ "zipimport: no memory to allocate "
+ "source buffer");
+ return NULL;
+ }
+ /* replace "\r\n?" by "\n" */
+ for (q = buf; *p != '\0'; p++) {
+ if (*p == '\r') {
+ *q++ = '\n';
+ if (*(p + 1) == '\n')
+ p++;
+ }
+ else
+ *q++ = *p;
+ }
+ *q++ = '\n'; /* add trailing \n */
+ *q = '\0';
+ fixed_source = PyString_FromString(buf);
+ PyMem_Free(buf);
+ return fixed_source;
}
/* Given a string buffer containing Python source code, compile it
@@ -1020,16 +1020,16 @@ normalize_line_endings(PyObject *source)
static PyObject *
compile_source(char *pathname, PyObject *source)
{
- PyObject *code, *fixed_source;
+ PyObject *code, *fixed_source;
- fixed_source = normalize_line_endings(source);
- if (fixed_source == NULL)
- return NULL;
+ fixed_source = normalize_line_endings(source);
+ if (fixed_source == NULL)
+ return NULL;
- code = Py_CompileString(PyString_AsString(fixed_source), pathname,
- Py_file_input);
- Py_DECREF(fixed_source);
- return code;
+ code = Py_CompileString(PyString_AsString(fixed_source), pathname,
+ Py_file_input);
+ Py_DECREF(fixed_source);
+ return code;
}
/* Convert the date/time values found in the Zip archive to a value
@@ -1037,19 +1037,19 @@ compile_source(char *pathname, PyObject *source)
static time_t
parse_dostime(int dostime, int dosdate)
{
- struct tm stm;
+ struct tm stm;
- memset((void *) &stm, '\0', sizeof(stm));
+ memset((void *) &stm, '\0', sizeof(stm));
- stm.tm_sec = (dostime & 0x1f) * 2;
- stm.tm_min = (dostime >> 5) & 0x3f;
- stm.tm_hour = (dostime >> 11) & 0x1f;
- stm.tm_mday = dosdate & 0x1f;
- stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;
- stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;
- stm.tm_isdst = -1; /* wday/yday is ignored */
+ stm.tm_sec = (dostime & 0x1f) * 2;
+ stm.tm_min = (dostime >> 5) & 0x3f;
+ stm.tm_hour = (dostime >> 11) & 0x1f;
+ stm.tm_mday = dosdate & 0x1f;
+ stm.tm_mon = ((dosdate >> 5) & 0x0f) - 1;
+ stm.tm_year = ((dosdate >> 9) & 0x7f) + 80;
+ stm.tm_isdst = -1; /* wday/yday is ignored */
- return mktime(&stm);
+ return mktime(&stm);
}
/* Given a path to a .pyc or .pyo file in the archive, return the
@@ -1058,106 +1058,106 @@ parse_dostime(int dostime, int dosdate)
static time_t
get_mtime_of_source(ZipImporter *self, char *path)
{
- PyObject *toc_entry;
- time_t mtime = 0;
- Py_ssize_t lastchar = strlen(path) - 1;
- char savechar = path[lastchar];
- path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry != NULL && PyTuple_Check(toc_entry) &&
- PyTuple_Size(toc_entry) == 8) {
- /* fetch the time stamp of the .py file for comparison
- with an embedded pyc time stamp */
- int time, date;
- time = PyInt_AsLong(PyTuple_GetItem(toc_entry, 5));
- date = PyInt_AsLong(PyTuple_GetItem(toc_entry, 6));
- mtime = parse_dostime(time, date);
- }
- path[lastchar] = savechar;
- return mtime;
+ PyObject *toc_entry;
+ time_t mtime = 0;
+ Py_ssize_t lastchar = strlen(path) - 1;
+ char savechar = path[lastchar];
+ path[lastchar] = '\0'; /* strip 'c' or 'o' from *.py[co] */
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry != NULL && PyTuple_Check(toc_entry) &&
+ PyTuple_Size(toc_entry) == 8) {
+ /* fetch the time stamp of the .py file for comparison
+ with an embedded pyc time stamp */
+ int time, date;
+ time = PyInt_AsLong(PyTuple_GetItem(toc_entry, 5));
+ date = PyInt_AsLong(PyTuple_GetItem(toc_entry, 6));
+ mtime = parse_dostime(time, date);
+ }
+ path[lastchar] = savechar;
+ return mtime;
}
/* Return the code object for the module named by 'fullname' from the
Zip archive as a new reference. */
static PyObject *
get_code_from_data(ZipImporter *self, int ispackage, int isbytecode,
- time_t mtime, PyObject *toc_entry)
+ time_t mtime, PyObject *toc_entry)
{
- PyObject *data, *code;
- char *modpath;
- char *archive = PyString_AsString(self->archive);
-
- if (archive == NULL)
- return NULL;
-
- data = get_data(archive, toc_entry);
- if (data == NULL)
- return NULL;
-
- modpath = PyString_AsString(PyTuple_GetItem(toc_entry, 0));
-
- if (isbytecode) {
- code = unmarshal_code(modpath, data, mtime);
- }
- else {
- code = compile_source(modpath, data);
- }
- Py_DECREF(data);
- return code;
+ PyObject *data, *code;
+ char *modpath;
+ char *archive = PyString_AsString(self->archive);
+
+ if (archive == NULL)
+ return NULL;
+
+ data = get_data(archive, toc_entry);
+ if (data == NULL)
+ return NULL;
+
+ modpath = PyString_AsString(PyTuple_GetItem(toc_entry, 0));
+
+ if (isbytecode) {
+ code = unmarshal_code(modpath, data, mtime);
+ }
+ else {
+ code = compile_source(modpath, data);
+ }
+ Py_DECREF(data);
+ return code;
}
/* Get the code object assoiciated with the module specified by
'fullname'. */
static PyObject *
get_module_code(ZipImporter *self, char *fullname,
- int *p_ispackage, char **p_modpath)
+ int *p_ispackage, char **p_modpath)
{
- PyObject *toc_entry;
- char *subname, path[MAXPATHLEN + 1];
- int len;
- struct st_zip_searchorder *zso;
-
- subname = get_subname(fullname);
-
- len = make_filename(PyString_AsString(self->prefix), subname, path);
- if (len < 0)
- return NULL;
-
- for (zso = zip_searchorder; *zso->suffix; zso++) {
- PyObject *code = NULL;
-
- strcpy(path + len, zso->suffix);
- if (Py_VerboseFlag > 1)
- PySys_WriteStderr("# trying %s%c%s\n",
- PyString_AsString(self->archive),
- SEP, path);
- toc_entry = PyDict_GetItemString(self->files, path);
- if (toc_entry != NULL) {
- time_t mtime = 0;
- int ispackage = zso->type & IS_PACKAGE;
- int isbytecode = zso->type & IS_BYTECODE;
-
- if (isbytecode)
- mtime = get_mtime_of_source(self, path);
- if (p_ispackage != NULL)
- *p_ispackage = ispackage;
- code = get_code_from_data(self, ispackage,
- isbytecode, mtime,
- toc_entry);
- if (code == Py_None) {
- /* bad magic number or non-matching mtime
- in byte code, try next */
- Py_DECREF(code);
- continue;
- }
- if (code != NULL && p_modpath != NULL)
- *p_modpath = PyString_AsString(
- PyTuple_GetItem(toc_entry, 0));
- return code;
- }
- }
- PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);
- return NULL;
+ PyObject *toc_entry;
+ char *subname, path[MAXPATHLEN + 1];
+ int len;
+ struct st_zip_searchorder *zso;
+
+ subname = get_subname(fullname);
+
+ len = make_filename(PyString_AsString(self->prefix), subname, path);
+ if (len < 0)
+ return NULL;
+
+ for (zso = zip_searchorder; *zso->suffix; zso++) {
+ PyObject *code = NULL;
+
+ strcpy(path + len, zso->suffix);
+ if (Py_VerboseFlag > 1)
+ PySys_WriteStderr("# trying %s%c%s\n",
+ PyString_AsString(self->archive),
+ SEP, path);
+ toc_entry = PyDict_GetItemString(self->files, path);
+ if (toc_entry != NULL) {
+ time_t mtime = 0;
+ int ispackage = zso->type & IS_PACKAGE;
+ int isbytecode = zso->type & IS_BYTECODE;
+
+ if (isbytecode)
+ mtime = get_mtime_of_source(self, path);
+ if (p_ispackage != NULL)
+ *p_ispackage = ispackage;
+ code = get_code_from_data(self, ispackage,
+ isbytecode, mtime,
+ toc_entry);
+ if (code == Py_None) {
+ /* bad magic number or non-matching mtime
+ in byte code, try next */
+ Py_DECREF(code);
+ continue;
+ }
+ if (code != NULL && p_modpath != NULL)
+ *p_modpath = PyString_AsString(
+ PyTuple_GetItem(toc_entry, 0));
+ return code;
+ }
+ }
+ PyErr_Format(ZipImportError, "can't find module '%.200s'", fullname);
+ return NULL;
}
@@ -1180,51 +1180,51 @@ to Zip archives.");
PyMODINIT_FUNC
initzipimport(void)
{
- PyObject *mod;
-
- if (PyType_Ready(&ZipImporter_Type) < 0)
- return;
-
- /* Correct directory separator */
- zip_searchorder[0].suffix[0] = SEP;
- zip_searchorder[1].suffix[0] = SEP;
- zip_searchorder[2].suffix[0] = SEP;
- if (Py_OptimizeFlag) {
- /* Reverse *.pyc and *.pyo */
- struct st_zip_searchorder tmp;
- tmp = zip_searchorder[0];
- zip_searchorder[0] = zip_searchorder[1];
- zip_searchorder[1] = tmp;
- tmp = zip_searchorder[3];
- zip_searchorder[3] = zip_searchorder[4];
- zip_searchorder[4] = tmp;
- }
-
- mod = Py_InitModule4("zipimport", NULL, zipimport_doc,
- NULL, PYTHON_API_VERSION);
- if (mod == NULL)
- return;
-
- ZipImportError = PyErr_NewException("zipimport.ZipImportError",
- PyExc_ImportError, NULL);
- if (ZipImportError == NULL)
- return;
-
- Py_INCREF(ZipImportError);
- if (PyModule_AddObject(mod, "ZipImportError",
- ZipImportError) < 0)
- return;
-
- Py_INCREF(&ZipImporter_Type);
- if (PyModule_AddObject(mod, "zipimporter",
- (PyObject *)&ZipImporter_Type) < 0)
- return;
-
- zip_directory_cache = PyDict_New();
- if (zip_directory_cache == NULL)
- return;
- Py_INCREF(zip_directory_cache);
- if (PyModule_AddObject(mod, "_zip_directory_cache",
- zip_directory_cache) < 0)
- return;
+ PyObject *mod;
+
+ if (PyType_Ready(&ZipImporter_Type) < 0)
+ return;
+
+ /* Correct directory separator */
+ zip_searchorder[0].suffix[0] = SEP;
+ zip_searchorder[1].suffix[0] = SEP;
+ zip_searchorder[2].suffix[0] = SEP;
+ if (Py_OptimizeFlag) {
+ /* Reverse *.pyc and *.pyo */
+ struct st_zip_searchorder tmp;
+ tmp = zip_searchorder[0];
+ zip_searchorder[0] = zip_searchorder[1];
+ zip_searchorder[1] = tmp;
+ tmp = zip_searchorder[3];
+ zip_searchorder[3] = zip_searchorder[4];
+ zip_searchorder[4] = tmp;
+ }
+
+ mod = Py_InitModule4("zipimport", NULL, zipimport_doc,
+ NULL, PYTHON_API_VERSION);
+ if (mod == NULL)
+ return;
+
+ ZipImportError = PyErr_NewException("zipimport.ZipImportError",
+ PyExc_ImportError, NULL);
+ if (ZipImportError == NULL)
+ return;
+
+ Py_INCREF(ZipImportError);
+ if (PyModule_AddObject(mod, "ZipImportError",
+ ZipImportError) < 0)
+ return;
+
+ Py_INCREF(&ZipImporter_Type);
+ if (PyModule_AddObject(mod, "zipimporter",
+ (PyObject *)&ZipImporter_Type) < 0)
+ return;
+
+ zip_directory_cache = PyDict_New();
+ if (zip_directory_cache == NULL)
+ return;
+ Py_INCREF(zip_directory_cache);
+ if (PyModule_AddObject(mod, "_zip_directory_cache",
+ zip_directory_cache) < 0)
+ return;
}
diff --git a/Modules/zlibmodule.c b/Modules/zlibmodule.c
index 0cb1e64..bb52fdc 100644
--- a/Modules/zlibmodule.c
+++ b/Modules/zlibmodule.c
@@ -28,12 +28,12 @@
static PyThread_type_lock zlib_lock = NULL; /* initialized on module load */
#define ENTER_ZLIB \
- Py_BEGIN_ALLOW_THREADS \
- PyThread_acquire_lock(zlib_lock, 1); \
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS \
+ PyThread_acquire_lock(zlib_lock, 1); \
+ Py_END_ALLOW_THREADS
#define LEAVE_ZLIB \
- PyThread_release_lock(zlib_lock);
+ PyThread_release_lock(zlib_lock);
#else
@@ -73,9 +73,9 @@ static void
zlib_error(z_stream zst, int err, char *msg)
{
if (zst.msg == Z_NULL)
- PyErr_Format(ZlibError, "Error %d %s", err, msg);
+ PyErr_Format(ZlibError, "Error %d %s", err, msg);
else
- PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg);
+ PyErr_Format(ZlibError, "Error %d %s: %.200s", err, msg, zst.msg);
}
PyDoc_STRVAR(compressobj__doc__,
@@ -94,17 +94,17 @@ newcompobject(PyTypeObject *type)
compobject *self;
self = PyObject_New(compobject, type);
if (self == NULL)
- return NULL;
+ return NULL;
self->is_initialised = 0;
self->unused_data = PyString_FromString("");
if (self->unused_data == NULL) {
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
self->unconsumed_tail = PyString_FromString("");
if (self->unconsumed_tail == NULL) {
- Py_DECREF(self);
- return NULL;
+ Py_DECREF(self);
+ return NULL;
}
return self;
}
@@ -124,15 +124,15 @@ PyZlib_compress(PyObject *self, PyObject *args)
/* require Python string object, optional 'level' arg */
if (!PyArg_ParseTuple(args, "s#|i:compress", &input, &length, &level))
- return NULL;
+ return NULL;
zst.avail_out = length + length/1000 + 12 + 1;
output = (Byte*)malloc(zst.avail_out);
if (output == NULL) {
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory to compress data");
- return NULL;
+ PyErr_SetString(PyExc_MemoryError,
+ "Can't allocate memory to compress data");
+ return NULL;
}
/* Past the point of no return. From here on out, we need to make sure
@@ -147,19 +147,19 @@ PyZlib_compress(PyObject *self, PyObject *args)
switch(err) {
case(Z_OK):
- break;
+ break;
case(Z_MEM_ERROR):
- PyErr_SetString(PyExc_MemoryError,
- "Out of memory while compressing data");
- goto error;
+ PyErr_SetString(PyExc_MemoryError,
+ "Out of memory while compressing data");
+ goto error;
case(Z_STREAM_ERROR):
- PyErr_SetString(ZlibError,
- "Bad compression level");
- goto error;
+ PyErr_SetString(ZlibError,
+ "Bad compression level");
+ goto error;
default:
deflateEnd(&zst);
- zlib_error(zst, err, "while compressing data");
- goto error;
+ zlib_error(zst, err, "while compressing data");
+ goto error;
}
Py_BEGIN_ALLOW_THREADS;
@@ -167,17 +167,17 @@ PyZlib_compress(PyObject *self, PyObject *args)
Py_END_ALLOW_THREADS;
if (err != Z_STREAM_END) {
- zlib_error(zst, err, "while compressing data");
- deflateEnd(&zst);
- goto error;
+ zlib_error(zst, err, "while compressing data");
+ deflateEnd(&zst);
+ goto error;
}
err=deflateEnd(&zst);
if (err == Z_OK)
- ReturnVal = PyString_FromStringAndSize((char *)output,
- zst.total_out);
+ ReturnVal = PyString_FromStringAndSize((char *)output,
+ zst.total_out);
else
- zlib_error(zst, err, "while finishing compression");
+ zlib_error(zst, err, "while finishing compression");
error:
free(output);
@@ -202,17 +202,17 @@ PyZlib_decompress(PyObject *self, PyObject *args)
z_stream zst;
if (!PyArg_ParseTuple(args, "s#|in:decompress",
- &input, &length, &wsize, &r_strlen))
- return NULL;
+ &input, &length, &wsize, &r_strlen))
+ return NULL;
if (r_strlen <= 0)
- r_strlen = 1;
+ r_strlen = 1;
zst.avail_in = length;
zst.avail_out = r_strlen;
if (!(result_str = PyString_FromStringAndSize(NULL, r_strlen)))
- return NULL;
+ return NULL;
zst.zalloc = (alloc_func)NULL;
zst.zfree = (free_func)Z_NULL;
@@ -222,60 +222,60 @@ PyZlib_decompress(PyObject *self, PyObject *args)
switch(err) {
case(Z_OK):
- break;
+ break;
case(Z_MEM_ERROR):
- PyErr_SetString(PyExc_MemoryError,
- "Out of memory while decompressing data");
- goto error;
+ PyErr_SetString(PyExc_MemoryError,
+ "Out of memory while decompressing data");
+ goto error;
default:
inflateEnd(&zst);
- zlib_error(zst, err, "while preparing to decompress data");
- goto error;
+ zlib_error(zst, err, "while preparing to decompress data");
+ goto error;
}
do {
- Py_BEGIN_ALLOW_THREADS
- err=inflate(&zst, Z_FINISH);
- Py_END_ALLOW_THREADS
-
- switch(err) {
- case(Z_STREAM_END):
- break;
- case(Z_BUF_ERROR):
- /*
- * If there is at least 1 byte of room according to zst.avail_out
- * and we get this error, assume that it means zlib cannot
- * process the inflate call() due to an error in the data.
- */
- if (zst.avail_out > 0) {
- PyErr_Format(ZlibError, "Error %i while decompressing data",
- err);
- inflateEnd(&zst);
- goto error;
- }
- /* fall through */
- case(Z_OK):
- /* need more memory */
- if (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
- inflateEnd(&zst);
- goto error;
- }
- zst.next_out = (unsigned char *)PyString_AS_STRING(result_str) \
- + r_strlen;
- zst.avail_out = r_strlen;
- r_strlen = r_strlen << 1;
- break;
- default:
- inflateEnd(&zst);
- zlib_error(zst, err, "while decompressing data");
- goto error;
- }
+ Py_BEGIN_ALLOW_THREADS
+ err=inflate(&zst, Z_FINISH);
+ Py_END_ALLOW_THREADS
+
+ switch(err) {
+ case(Z_STREAM_END):
+ break;
+ case(Z_BUF_ERROR):
+ /*
+ * If there is at least 1 byte of room according to zst.avail_out
+ * and we get this error, assume that it means zlib cannot
+ * process the inflate call() due to an error in the data.
+ */
+ if (zst.avail_out > 0) {
+ PyErr_Format(ZlibError, "Error %i while decompressing data",
+ err);
+ inflateEnd(&zst);
+ goto error;
+ }
+ /* fall through */
+ case(Z_OK):
+ /* need more memory */
+ if (_PyString_Resize(&result_str, r_strlen << 1) < 0) {
+ inflateEnd(&zst);
+ goto error;
+ }
+ zst.next_out = (unsigned char *)PyString_AS_STRING(result_str) \
+ + r_strlen;
+ zst.avail_out = r_strlen;
+ r_strlen = r_strlen << 1;
+ break;
+ default:
+ inflateEnd(&zst);
+ zlib_error(zst, err, "while decompressing data");
+ goto error;
+ }
} while (err != Z_STREAM_END);
err = inflateEnd(&zst);
if (err != Z_OK) {
- zlib_error(zst, err, "while finishing data decompression");
- goto error;
+ zlib_error(zst, err, "while finishing data decompression");
+ goto error;
}
_PyString_Resize(&result_str, zst.total_out);
@@ -294,12 +294,12 @@ PyZlib_compressobj(PyObject *selfptr, PyObject *args)
int wbits=MAX_WBITS, memLevel=DEF_MEM_LEVEL, strategy=0, err;
if (!PyArg_ParseTuple(args, "|iiiii:compressobj", &level, &method, &wbits,
- &memLevel, &strategy))
- return NULL;
+ &memLevel, &strategy))
+ return NULL;
self = newcompobject(&Comptype);
if (self==NULL)
- return(NULL);
+ return(NULL);
self->zst.zalloc = (alloc_func)NULL;
self->zst.zfree = (free_func)Z_NULL;
self->zst.next_in = NULL;
@@ -307,21 +307,21 @@ PyZlib_compressobj(PyObject *selfptr, PyObject *args)
err = deflateInit2(&self->zst, level, method, wbits, memLevel, strategy);
switch(err) {
case (Z_OK):
- self->is_initialised = 1;
- return (PyObject*)self;
+ self->is_initialised = 1;
+ return (PyObject*)self;
case (Z_MEM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory for compression object");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_MemoryError,
+ "Can't allocate memory for compression object");
+ return NULL;
case(Z_STREAM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
+ return NULL;
default:
- zlib_error(self->zst, err, "while creating compression object");
+ zlib_error(self->zst, err, "while creating compression object");
Py_DECREF(self);
- return NULL;
+ return NULL;
}
}
@@ -331,11 +331,11 @@ PyZlib_decompressobj(PyObject *selfptr, PyObject *args)
int wbits=DEF_WBITS, err;
compobject *self;
if (!PyArg_ParseTuple(args, "|i:decompressobj", &wbits))
- return NULL;
+ return NULL;
self = newcompobject(&Decomptype);
if (self == NULL)
- return(NULL);
+ return(NULL);
self->zst.zalloc = (alloc_func)NULL;
self->zst.zfree = (free_func)Z_NULL;
self->zst.next_in = NULL;
@@ -343,21 +343,21 @@ PyZlib_decompressobj(PyObject *selfptr, PyObject *args)
err = inflateInit2(&self->zst, wbits);
switch(err) {
case (Z_OK):
- self->is_initialised = 1;
- return (PyObject*)self;
+ self->is_initialised = 1;
+ return (PyObject*)self;
case(Z_STREAM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_ValueError, "Invalid initialization option");
+ return NULL;
case (Z_MEM_ERROR):
- Py_DECREF(self);
- PyErr_SetString(PyExc_MemoryError,
- "Can't allocate memory for decompression object");
- return NULL;
+ Py_DECREF(self);
+ PyErr_SetString(PyExc_MemoryError,
+ "Can't allocate memory for decompression object");
+ return NULL;
default:
- zlib_error(self->zst, err, "while creating decompression object");
+ zlib_error(self->zst, err, "while creating decompression object");
Py_DECREF(self);
- return NULL;
+ return NULL;
}
}
@@ -365,7 +365,7 @@ static void
Comp_dealloc(compobject *self)
{
if (self->is_initialised)
- deflateEnd(&self->zst);
+ deflateEnd(&self->zst);
Py_XDECREF(self->unused_data);
Py_XDECREF(self->unconsumed_tail);
PyObject_Del(self);
@@ -375,7 +375,7 @@ static void
Decomp_dealloc(compobject *self)
{
if (self->is_initialised)
- inflateEnd(&self->zst);
+ inflateEnd(&self->zst);
Py_XDECREF(self->unused_data);
Py_XDECREF(self->unconsumed_tail);
PyObject_Del(self);
@@ -399,10 +399,10 @@ PyZlib_objcompress(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "s#:compress", &input, &inplen))
- return NULL;
+ return NULL;
if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -419,16 +419,16 @@ PyZlib_objcompress(compobject *self, PyObject *args)
/* while Z_OK and the output buffer is full, there might be more output,
so extend the output buffer and try again */
while (err == Z_OK && self->zst.avail_out == 0) {
- if (_PyString_Resize(&RetVal, length << 1) < 0)
- goto error;
- self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
- + length;
- self->zst.avail_out = length;
- length = length << 1;
-
- Py_BEGIN_ALLOW_THREADS
- err = deflate(&(self->zst), Z_NO_FLUSH);
- Py_END_ALLOW_THREADS
+ if (_PyString_Resize(&RetVal, length << 1) < 0)
+ goto error;
+ self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+ + length;
+ self->zst.avail_out = length;
+ length = length << 1;
+
+ Py_BEGIN_ALLOW_THREADS
+ err = deflate(&(self->zst), Z_NO_FLUSH);
+ Py_END_ALLOW_THREADS
}
/* We will only get Z_BUF_ERROR if the output buffer was full but
there wasn't more output when we tried again, so it is not an error
@@ -436,10 +436,10 @@ PyZlib_objcompress(compobject *self, PyObject *args)
*/
if (err != Z_OK && err != Z_BUF_ERROR) {
- zlib_error(self->zst, err, "while compressing");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
+ zlib_error(self->zst, err, "while compressing");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
_PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
@@ -469,19 +469,19 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "s#|i:decompress", &input,
- &inplen, &max_length))
- return NULL;
+ &inplen, &max_length))
+ return NULL;
if (max_length < 0) {
- PyErr_SetString(PyExc_ValueError,
- "max_length must be greater than zero");
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "max_length must be greater than zero");
+ return NULL;
}
/* limit amount of data allocated to max_length */
if (max_length && length > max_length)
- length = max_length;
+ length = max_length;
if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -499,40 +499,40 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
So extend the output buffer and try again.
*/
while (err == Z_OK && self->zst.avail_out == 0) {
- /* If max_length set, don't continue decompressing if we've already
- reached the limit.
- */
- if (max_length && length >= max_length)
- break;
-
- /* otherwise, ... */
- old_length = length;
- length = length << 1;
- if (max_length && length > max_length)
- length = max_length;
-
- if (_PyString_Resize(&RetVal, length) < 0)
- goto error;
- self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
- + old_length;
- self->zst.avail_out = length - old_length;
-
- Py_BEGIN_ALLOW_THREADS
- err = inflate(&(self->zst), Z_SYNC_FLUSH);
- Py_END_ALLOW_THREADS
+ /* If max_length set, don't continue decompressing if we've already
+ reached the limit.
+ */
+ if (max_length && length >= max_length)
+ break;
+
+ /* otherwise, ... */
+ old_length = length;
+ length = length << 1;
+ if (max_length && length > max_length)
+ length = max_length;
+
+ if (_PyString_Resize(&RetVal, length) < 0)
+ goto error;
+ self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+ + old_length;
+ self->zst.avail_out = length - old_length;
+
+ Py_BEGIN_ALLOW_THREADS
+ err = inflate(&(self->zst), Z_SYNC_FLUSH);
+ Py_END_ALLOW_THREADS
}
/* Not all of the compressed data could be accommodated in the output buffer
of specified size. Return the unconsumed tail in an attribute.*/
if(max_length) {
- Py_DECREF(self->unconsumed_tail);
- self->unconsumed_tail = PyString_FromStringAndSize((char *)self->zst.next_in,
- self->zst.avail_in);
- if(!self->unconsumed_tail) {
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
- }
+ Py_DECREF(self->unconsumed_tail);
+ self->unconsumed_tail = PyString_FromStringAndSize((char *)self->zst.next_in,
+ self->zst.avail_in);
+ if(!self->unconsumed_tail) {
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
+ }
}
/* The end of the compressed data has been reached, so set the
@@ -542,22 +542,22 @@ PyZlib_objdecompress(compobject *self, PyObject *args)
preserved.
*/
if (err == Z_STREAM_END) {
- Py_XDECREF(self->unused_data); /* Free original empty string */
- self->unused_data = PyString_FromStringAndSize(
- (char *)self->zst.next_in, self->zst.avail_in);
- if (self->unused_data == NULL) {
- Py_DECREF(RetVal);
- goto error;
- }
- /* We will only get Z_BUF_ERROR if the output buffer was full
- but there wasn't more output when we tried again, so it is
- not an error condition.
- */
+ Py_XDECREF(self->unused_data); /* Free original empty string */
+ self->unused_data = PyString_FromStringAndSize(
+ (char *)self->zst.next_in, self->zst.avail_in);
+ if (self->unused_data == NULL) {
+ Py_DECREF(RetVal);
+ goto error;
+ }
+ /* We will only get Z_BUF_ERROR if the output buffer was full
+ but there wasn't more output when we tried again, so it is
+ not an error condition.
+ */
} else if (err != Z_OK && err != Z_BUF_ERROR) {
- zlib_error(self->zst, err, "while decompressing");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
+ zlib_error(self->zst, err, "while decompressing");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
_PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
@@ -585,16 +585,16 @@ PyZlib_flush(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "|i:flush", &flushmode))
- return NULL;
+ return NULL;
/* Flushing with Z_NO_FLUSH is a no-op, so there's no point in
doing any work at all; just return an empty string. */
if (flushmode == Z_NO_FLUSH) {
- return PyString_FromStringAndSize(NULL, 0);
+ return PyString_FromStringAndSize(NULL, 0);
}
if (!(RetVal = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -610,41 +610,41 @@ PyZlib_flush(compobject *self, PyObject *args)
/* while Z_OK and the output buffer is full, there might be more output,
so extend the output buffer and try again */
while (err == Z_OK && self->zst.avail_out == 0) {
- if (_PyString_Resize(&RetVal, length << 1) < 0)
- goto error;
- self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
- + length;
- self->zst.avail_out = length;
- length = length << 1;
-
- Py_BEGIN_ALLOW_THREADS
- err = deflate(&(self->zst), flushmode);
- Py_END_ALLOW_THREADS
+ if (_PyString_Resize(&RetVal, length << 1) < 0)
+ goto error;
+ self->zst.next_out = (unsigned char *)PyString_AS_STRING(RetVal) \
+ + length;
+ self->zst.avail_out = length;
+ length = length << 1;
+
+ Py_BEGIN_ALLOW_THREADS
+ err = deflate(&(self->zst), flushmode);
+ Py_END_ALLOW_THREADS
}
/* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
various data structures. Note we should only get Z_STREAM_END when
flushmode is Z_FINISH, but checking both for safety*/
if (err == Z_STREAM_END && flushmode == Z_FINISH) {
- err = deflateEnd(&(self->zst));
- if (err != Z_OK) {
- zlib_error(self->zst, err, "from deflateEnd()");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
- }
- else
- self->is_initialised = 0;
-
- /* We will only get Z_BUF_ERROR if the output buffer was full
- but there wasn't more output when we tried again, so it is
- not an error condition.
- */
+ err = deflateEnd(&(self->zst));
+ if (err != Z_OK) {
+ zlib_error(self->zst, err, "from deflateEnd()");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
+ }
+ else
+ self->is_initialised = 0;
+
+ /* We will only get Z_BUF_ERROR if the output buffer was full
+ but there wasn't more output when we tried again, so it is
+ not an error condition.
+ */
} else if (err!=Z_OK && err!=Z_BUF_ERROR) {
- zlib_error(self->zst, err, "while flushing");
- Py_DECREF(RetVal);
- RetVal = NULL;
- goto error;
+ zlib_error(self->zst, err, "while flushing");
+ Py_DECREF(RetVal);
+ RetVal = NULL;
+ goto error;
}
_PyString_Resize(&RetVal, self->zst.total_out - start_total_out);
@@ -774,13 +774,13 @@ PyZlib_unflush(compobject *self, PyObject *args)
unsigned long start_total_out;
if (!PyArg_ParseTuple(args, "|i:flush", &length))
- return NULL;
+ return NULL;
if (length <= 0) {
- PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "length must be greater than zero");
+ return NULL;
}
if (!(retval = PyString_FromStringAndSize(NULL, length)))
- return NULL;
+ return NULL;
ENTER_ZLIB
@@ -796,29 +796,29 @@ PyZlib_unflush(compobject *self, PyObject *args)
/* while Z_OK and the output buffer is full, there might be more output,
so extend the output buffer and try again */
while ((err == Z_OK || err == Z_BUF_ERROR) && self->zst.avail_out == 0) {
- if (_PyString_Resize(&retval, length << 1) < 0)
- goto error;
- self->zst.next_out = (Byte *)PyString_AS_STRING(retval) + length;
- self->zst.avail_out = length;
- length = length << 1;
-
- Py_BEGIN_ALLOW_THREADS
- err = inflate(&(self->zst), Z_FINISH);
- Py_END_ALLOW_THREADS
+ if (_PyString_Resize(&retval, length << 1) < 0)
+ goto error;
+ self->zst.next_out = (Byte *)PyString_AS_STRING(retval) + length;
+ self->zst.avail_out = length;
+ length = length << 1;
+
+ Py_BEGIN_ALLOW_THREADS
+ err = inflate(&(self->zst), Z_FINISH);
+ Py_END_ALLOW_THREADS
}
/* If flushmode is Z_FINISH, we also have to call deflateEnd() to free
various data structures. Note we should only get Z_STREAM_END when
flushmode is Z_FINISH */
if (err == Z_STREAM_END) {
- err = inflateEnd(&(self->zst));
+ err = inflateEnd(&(self->zst));
self->is_initialised = 0;
- if (err != Z_OK) {
- zlib_error(self->zst, err, "from inflateEnd()");
- Py_DECREF(retval);
- retval = NULL;
- goto error;
- }
+ if (err != Z_OK) {
+ zlib_error(self->zst, err, "from inflateEnd()");
+ Py_DECREF(retval);
+ retval = NULL;
+ goto error;
+ }
}
_PyString_Resize(&retval, self->zst.total_out - start_total_out);
@@ -872,13 +872,13 @@ Decomp_getattr(compobject *self, char *name)
ENTER_ZLIB
if (strcmp(name, "unused_data") == 0) {
- Py_INCREF(self->unused_data);
- retval = self->unused_data;
+ Py_INCREF(self->unused_data);
+ retval = self->unused_data;
} else if (strcmp(name, "unconsumed_tail") == 0) {
- Py_INCREF(self->unconsumed_tail);
- retval = self->unconsumed_tail;
+ Py_INCREF(self->unconsumed_tail);
+ retval = self->unconsumed_tail;
} else
- retval = Py_FindMethod(Decomp_methods, (PyObject *)self, name);
+ retval = Py_FindMethod(Decomp_methods, (PyObject *)self, name);
LEAVE_ZLIB
@@ -899,7 +899,7 @@ PyZlib_adler32(PyObject *self, PyObject *args)
int len, signed_val;
if (!PyArg_ParseTuple(args, "s#|I:adler32", &buf, &len, &adler32val))
- return NULL;
+ return NULL;
/* In Python 2.x we return a signed integer regardless of native platform
* long size (the 32bit unsigned long is treated as 32-bit signed and sign
* extended into a 64-bit long inside the integer object). 3.0 does the
@@ -922,7 +922,7 @@ PyZlib_crc32(PyObject *self, PyObject *args)
int len, signed_val;
if (!PyArg_ParseTuple(args, "s#|I:crc32", &buf, &len, &crc32val))
- return NULL;
+ return NULL;
/* In Python 2.x we return a signed integer regardless of native platform
* long size (the 32bit unsigned long is treated as 32-bit signed and sign
* extended into a 64-bit long inside the integer object). 3.0 does the
@@ -1003,15 +1003,15 @@ PyInit_zlib(void)
Py_TYPE(&Comptype) = &PyType_Type;
Py_TYPE(&Decomptype) = &PyType_Type;
m = Py_InitModule4("zlib", zlib_methods,
- zlib_module_documentation,
- (PyObject*)NULL,PYTHON_API_VERSION);
+ zlib_module_documentation,
+ (PyObject*)NULL,PYTHON_API_VERSION);
if (m == NULL)
- return;
+ return;
ZlibError = PyErr_NewException("zlib.error", NULL, NULL);
if (ZlibError != NULL) {
Py_INCREF(ZlibError);
- PyModule_AddObject(m, "error", ZlibError);
+ PyModule_AddObject(m, "error", ZlibError);
}
PyModule_AddIntConstant(m, "MAX_WBITS", MAX_WBITS);
PyModule_AddIntConstant(m, "DEFLATED", DEFLATED);
@@ -1030,7 +1030,7 @@ PyInit_zlib(void)
ver = PyString_FromString(ZLIB_VERSION);
if (ver != NULL)
- PyModule_AddObject(m, "ZLIB_VERSION", ver);
+ PyModule_AddObject(m, "ZLIB_VERSION", ver);
PyModule_AddStringConstant(m, "__version__", "1.0");
diff --git a/Objects/abstract.c b/Objects/abstract.c
index fddaed8..761e035 100644
--- a/Objects/abstract.c
+++ b/Objects/abstract.c
@@ -6,7 +6,7 @@
#include "longintrepr.h"
#define NEW_STYLE_NUMBER(o) PyType_HasFeature((o)->ob_type, \
- Py_TPFLAGS_CHECKTYPES)
+ Py_TPFLAGS_CHECKTYPES)
/* Shorthands to return certain errors */
@@ -14,17 +14,17 @@
static PyObject *
type_error(const char *msg, PyObject *obj)
{
- PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError, msg, obj->ob_type->tp_name);
+ return NULL;
}
static PyObject *
null_error(void)
{
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_SystemError,
- "null argument to internal routine");
- return NULL;
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_SystemError,
+ "null argument to internal routine");
+ return NULL;
}
/* Operations on any object */
@@ -32,53 +32,53 @@ null_error(void)
int
PyObject_Cmp(PyObject *o1, PyObject *o2, int *result)
{
- int r;
+ int r;
- if (o1 == NULL || o2 == NULL) {
- null_error();
- return -1;
- }
- r = PyObject_Compare(o1, o2);
- if (PyErr_Occurred())
- return -1;
- *result = r;
- return 0;
+ if (o1 == NULL || o2 == NULL) {
+ null_error();
+ return -1;
+ }
+ r = PyObject_Compare(o1, o2);
+ if (PyErr_Occurred())
+ return -1;
+ *result = r;
+ return 0;
}
PyObject *
PyObject_Type(PyObject *o)
{
- PyObject *v;
+ PyObject *v;
- if (o == NULL)
- return null_error();
- v = (PyObject *)o->ob_type;
- Py_INCREF(v);
- return v;
+ if (o == NULL)
+ return null_error();
+ v = (PyObject *)o->ob_type;
+ Py_INCREF(v);
+ return v;
}
Py_ssize_t
PyObject_Size(PyObject *o)
{
- PySequenceMethods *m;
+ PySequenceMethods *m;
- if (o == NULL) {
- null_error();
- return -1;
- }
+ if (o == NULL) {
+ null_error();
+ return -1;
+ }
- m = o->ob_type->tp_as_sequence;
- if (m && m->sq_length)
- return m->sq_length(o);
+ m = o->ob_type->tp_as_sequence;
+ if (m && m->sq_length)
+ return m->sq_length(o);
- return PyMapping_Size(o);
+ return PyMapping_Size(o);
}
#undef PyObject_Length
Py_ssize_t
PyObject_Length(PyObject *o)
{
- return PyObject_Size(o);
+ return PyObject_Size(o);
}
#define PyObject_Length PyObject_Size
@@ -92,266 +92,266 @@ PyObject_Length(PyObject *o)
Py_ssize_t
_PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
{
- static PyObject *hintstrobj = NULL;
- PyObject *ro, *hintmeth;
- Py_ssize_t rv;
-
- /* try o.__len__() */
- rv = PyObject_Size(o);
- if (rv >= 0)
- return rv;
- if (PyErr_Occurred()) {
- if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
- !PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- }
-
- if (PyInstance_Check(o))
- return defaultvalue;
- /* try o.__length_hint__() */
- hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);
- if (hintmeth == NULL) {
- if (PyErr_Occurred())
- return -1;
- else
- return defaultvalue;
- }
- ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);
- Py_DECREF(hintmeth);
- if (ro == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
- !PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- return defaultvalue;
- }
- rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
- Py_DECREF(ro);
- return rv;
+ static PyObject *hintstrobj = NULL;
+ PyObject *ro, *hintmeth;
+ Py_ssize_t rv;
+
+ /* try o.__len__() */
+ rv = PyObject_Size(o);
+ if (rv >= 0)
+ return rv;
+ if (PyErr_Occurred()) {
+ if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
+ !PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ }
+
+ if (PyInstance_Check(o))
+ return defaultvalue;
+ /* try o.__length_hint__() */
+ hintmeth = _PyObject_LookupSpecial(o, "__length_hint__", &hintstrobj);
+ if (hintmeth == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ else
+ return defaultvalue;
+ }
+ ro = PyObject_CallFunctionObjArgs(hintmeth, NULL);
+ Py_DECREF(hintmeth);
+ if (ro == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_TypeError) &&
+ !PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ return defaultvalue;
+ }
+ rv = PyLong_Check(ro) ? PyLong_AsSsize_t(ro) : defaultvalue;
+ Py_DECREF(ro);
+ return rv;
}
PyObject *
PyObject_GetItem(PyObject *o, PyObject *key)
{
- PyMappingMethods *m;
-
- if (o == NULL || key == NULL)
- return null_error();
-
- m = o->ob_type->tp_as_mapping;
- if (m && m->mp_subscript)
- return m->mp_subscript(o, key);
-
- if (o->ob_type->tp_as_sequence) {
- if (PyIndex_Check(key)) {
- Py_ssize_t key_value;
- key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (key_value == -1 && PyErr_Occurred())
- return NULL;
- return PySequence_GetItem(o, key_value);
- }
- else if (o->ob_type->tp_as_sequence->sq_item)
- return type_error("sequence index must "
- "be integer, not '%.200s'", key);
- }
+ PyMappingMethods *m;
+
+ if (o == NULL || key == NULL)
+ return null_error();
+
+ m = o->ob_type->tp_as_mapping;
+ if (m && m->mp_subscript)
+ return m->mp_subscript(o, key);
+
+ if (o->ob_type->tp_as_sequence) {
+ if (PyIndex_Check(key)) {
+ Py_ssize_t key_value;
+ key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (key_value == -1 && PyErr_Occurred())
+ return NULL;
+ return PySequence_GetItem(o, key_value);
+ }
+ else if (o->ob_type->tp_as_sequence->sq_item)
+ return type_error("sequence index must "
+ "be integer, not '%.200s'", key);
+ }
- return type_error("'%.200s' object is not subscriptable", o);
+ return type_error("'%.200s' object is not subscriptable", o);
}
int
PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
{
- PyMappingMethods *m;
-
- if (o == NULL || key == NULL || value == NULL) {
- null_error();
- return -1;
- }
- m = o->ob_type->tp_as_mapping;
- if (m && m->mp_ass_subscript)
- return m->mp_ass_subscript(o, key, value);
-
- if (o->ob_type->tp_as_sequence) {
- if (PyIndex_Check(key)) {
- Py_ssize_t key_value;
- key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (key_value == -1 && PyErr_Occurred())
- return -1;
- return PySequence_SetItem(o, key_value, value);
- }
- else if (o->ob_type->tp_as_sequence->sq_ass_item) {
- type_error("sequence index must be "
- "integer, not '%.200s'", key);
- return -1;
- }
- }
-
- type_error("'%.200s' object does not support item assignment", o);
- return -1;
+ PyMappingMethods *m;
+
+ if (o == NULL || key == NULL || value == NULL) {
+ null_error();
+ return -1;
+ }
+ m = o->ob_type->tp_as_mapping;
+ if (m && m->mp_ass_subscript)
+ return m->mp_ass_subscript(o, key, value);
+
+ if (o->ob_type->tp_as_sequence) {
+ if (PyIndex_Check(key)) {
+ Py_ssize_t key_value;
+ key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (key_value == -1 && PyErr_Occurred())
+ return -1;
+ return PySequence_SetItem(o, key_value, value);
+ }
+ else if (o->ob_type->tp_as_sequence->sq_ass_item) {
+ type_error("sequence index must be "
+ "integer, not '%.200s'", key);
+ return -1;
+ }
+ }
+
+ type_error("'%.200s' object does not support item assignment", o);
+ return -1;
}
int
PyObject_DelItem(PyObject *o, PyObject *key)
{
- PyMappingMethods *m;
-
- if (o == NULL || key == NULL) {
- null_error();
- return -1;
- }
- m = o->ob_type->tp_as_mapping;
- if (m && m->mp_ass_subscript)
- return m->mp_ass_subscript(o, key, (PyObject*)NULL);
-
- if (o->ob_type->tp_as_sequence) {
- if (PyIndex_Check(key)) {
- Py_ssize_t key_value;
- key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
- if (key_value == -1 && PyErr_Occurred())
- return -1;
- return PySequence_DelItem(o, key_value);
- }
- else if (o->ob_type->tp_as_sequence->sq_ass_item) {
- type_error("sequence index must be "
- "integer, not '%.200s'", key);
- return -1;
- }
- }
-
- type_error("'%.200s' object does not support item deletion", o);
- return -1;
+ PyMappingMethods *m;
+
+ if (o == NULL || key == NULL) {
+ null_error();
+ return -1;
+ }
+ m = o->ob_type->tp_as_mapping;
+ if (m && m->mp_ass_subscript)
+ return m->mp_ass_subscript(o, key, (PyObject*)NULL);
+
+ if (o->ob_type->tp_as_sequence) {
+ if (PyIndex_Check(key)) {
+ Py_ssize_t key_value;
+ key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
+ if (key_value == -1 && PyErr_Occurred())
+ return -1;
+ return PySequence_DelItem(o, key_value);
+ }
+ else if (o->ob_type->tp_as_sequence->sq_ass_item) {
+ type_error("sequence index must be "
+ "integer, not '%.200s'", key);
+ return -1;
+ }
+ }
+
+ type_error("'%.200s' object does not support item deletion", o);
+ return -1;
}
int
PyObject_DelItemString(PyObject *o, char *key)
{
- PyObject *okey;
- int ret;
+ PyObject *okey;
+ int ret;
- if (o == NULL || key == NULL) {
- null_error();
- return -1;
- }
- okey = PyString_FromString(key);
- if (okey == NULL)
- return -1;
- ret = PyObject_DelItem(o, okey);
- Py_DECREF(okey);
- return ret;
+ if (o == NULL || key == NULL) {
+ null_error();
+ return -1;
+ }
+ okey = PyString_FromString(key);
+ if (okey == NULL)
+ return -1;
+ ret = PyObject_DelItem(o, okey);
+ Py_DECREF(okey);
+ return ret;
}
int
PyObject_AsCharBuffer(PyObject *obj,
- const char **buffer,
- Py_ssize_t *buffer_len)
-{
- PyBufferProcs *pb;
- char *pp;
- Py_ssize_t len;
-
- if (obj == NULL || buffer == NULL || buffer_len == NULL) {
- null_error();
- return -1;
- }
- pb = obj->ob_type->tp_as_buffer;
- if (pb == NULL ||
- pb->bf_getcharbuffer == NULL ||
- pb->bf_getsegcount == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "expected a character buffer object");
- return -1;
- }
- if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
- PyErr_SetString(PyExc_TypeError,
- "expected a single-segment buffer object");
- return -1;
- }
- len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
- if (len < 0)
- return -1;
- *buffer = pp;
- *buffer_len = len;
- return 0;
+ const char **buffer,
+ Py_ssize_t *buffer_len)
+{
+ PyBufferProcs *pb;
+ char *pp;
+ Py_ssize_t len;
+
+ if (obj == NULL || buffer == NULL || buffer_len == NULL) {
+ null_error();
+ return -1;
+ }
+ pb = obj->ob_type->tp_as_buffer;
+ if (pb == NULL ||
+ pb->bf_getcharbuffer == NULL ||
+ pb->bf_getsegcount == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a character buffer object");
+ return -1;
+ }
+ if ((*pb->bf_getsegcount)(obj,NULL) != 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a single-segment buffer object");
+ return -1;
+ }
+ len = (*pb->bf_getcharbuffer)(obj, 0, &pp);
+ if (len < 0)
+ return -1;
+ *buffer = pp;
+ *buffer_len = len;
+ return 0;
}
int
PyObject_CheckReadBuffer(PyObject *obj)
{
- PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
+ PyBufferProcs *pb = obj->ob_type->tp_as_buffer;
- if (pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL ||
- (*pb->bf_getsegcount)(obj, NULL) != 1)
- return 0;
- return 1;
+ if (pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL ||
+ (*pb->bf_getsegcount)(obj, NULL) != 1)
+ return 0;
+ return 1;
}
int PyObject_AsReadBuffer(PyObject *obj,
- const void **buffer,
- Py_ssize_t *buffer_len)
-{
- PyBufferProcs *pb;
- void *pp;
- Py_ssize_t len;
-
- if (obj == NULL || buffer == NULL || buffer_len == NULL) {
- null_error();
- return -1;
- }
- pb = obj->ob_type->tp_as_buffer;
- if (pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "expected a readable buffer object");
- return -1;
- }
- if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
- PyErr_SetString(PyExc_TypeError,
- "expected a single-segment buffer object");
- return -1;
- }
- len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
- if (len < 0)
- return -1;
- *buffer = pp;
- *buffer_len = len;
- return 0;
+ const void **buffer,
+ Py_ssize_t *buffer_len)
+{
+ PyBufferProcs *pb;
+ void *pp;
+ Py_ssize_t len;
+
+ if (obj == NULL || buffer == NULL || buffer_len == NULL) {
+ null_error();
+ return -1;
+ }
+ pb = obj->ob_type->tp_as_buffer;
+ if (pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a readable buffer object");
+ return -1;
+ }
+ if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a single-segment buffer object");
+ return -1;
+ }
+ len = (*pb->bf_getreadbuffer)(obj, 0, &pp);
+ if (len < 0)
+ return -1;
+ *buffer = pp;
+ *buffer_len = len;
+ return 0;
}
int PyObject_AsWriteBuffer(PyObject *obj,
- void **buffer,
- Py_ssize_t *buffer_len)
-{
- PyBufferProcs *pb;
- void*pp;
- Py_ssize_t len;
-
- if (obj == NULL || buffer == NULL || buffer_len == NULL) {
- null_error();
- return -1;
- }
- pb = obj->ob_type->tp_as_buffer;
- if (pb == NULL ||
- pb->bf_getwritebuffer == NULL ||
- pb->bf_getsegcount == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "expected a writeable buffer object");
- return -1;
- }
- if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
- PyErr_SetString(PyExc_TypeError,
- "expected a single-segment buffer object");
- return -1;
- }
- len = (*pb->bf_getwritebuffer)(obj,0,&pp);
- if (len < 0)
- return -1;
- *buffer = pp;
- *buffer_len = len;
- return 0;
+ void **buffer,
+ Py_ssize_t *buffer_len)
+{
+ PyBufferProcs *pb;
+ void*pp;
+ Py_ssize_t len;
+
+ if (obj == NULL || buffer == NULL || buffer_len == NULL) {
+ null_error();
+ return -1;
+ }
+ pb = obj->ob_type->tp_as_buffer;
+ if (pb == NULL ||
+ pb->bf_getwritebuffer == NULL ||
+ pb->bf_getsegcount == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a writeable buffer object");
+ return -1;
+ }
+ if ((*pb->bf_getsegcount)(obj, NULL) != 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a single-segment buffer object");
+ return -1;
+ }
+ len = (*pb->bf_getwritebuffer)(obj,0,&pp);
+ if (len < 0)
+ return -1;
+ *buffer = pp;
+ *buffer_len = len;
+ return 0;
}
/* Buffer C-API for Python 3.0 */
@@ -359,119 +359,119 @@ int PyObject_AsWriteBuffer(PyObject *obj,
int
PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
{
- if (!PyObject_CheckBuffer(obj)) {
- PyErr_Format(PyExc_TypeError,
- "'%100s' does not have the buffer interface",
- Py_TYPE(obj)->tp_name);
- return -1;
- }
- return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
+ if (!PyObject_CheckBuffer(obj)) {
+ PyErr_Format(PyExc_TypeError,
+ "'%100s' does not have the buffer interface",
+ Py_TYPE(obj)->tp_name);
+ return -1;
+ }
+ return (*(obj->ob_type->tp_as_buffer->bf_getbuffer))(obj, view, flags);
}
static int
_IsFortranContiguous(Py_buffer *view)
{
- Py_ssize_t sd, dim;
- int i;
+ Py_ssize_t sd, dim;
+ int i;
- if (view->ndim == 0) return 1;
- if (view->strides == NULL) return (view->ndim == 1);
+ if (view->ndim == 0) return 1;
+ if (view->strides == NULL) return (view->ndim == 1);
- sd = view->itemsize;
- if (view->ndim == 1) return (view->shape[0] == 1 ||
- sd == view->strides[0]);
- for (i=0; i<view->ndim; i++) {
- dim = view->shape[i];
- if (dim == 0) return 1;
- if (view->strides[i] != sd) return 0;
- sd *= dim;
- }
- return 1;
+ sd = view->itemsize;
+ if (view->ndim == 1) return (view->shape[0] == 1 ||
+ sd == view->strides[0]);
+ for (i=0; i<view->ndim; i++) {
+ dim = view->shape[i];
+ if (dim == 0) return 1;
+ if (view->strides[i] != sd) return 0;
+ sd *= dim;
+ }
+ return 1;
}
static int
_IsCContiguous(Py_buffer *view)
{
- Py_ssize_t sd, dim;
- int i;
+ Py_ssize_t sd, dim;
+ int i;
- if (view->ndim == 0) return 1;
- if (view->strides == NULL) return 1;
+ if (view->ndim == 0) return 1;
+ if (view->strides == NULL) return 1;
- sd = view->itemsize;
- if (view->ndim == 1) return (view->shape[0] == 1 ||
- sd == view->strides[0]);
- for (i=view->ndim-1; i>=0; i--) {
- dim = view->shape[i];
- if (dim == 0) return 1;
- if (view->strides[i] != sd) return 0;
- sd *= dim;
- }
- return 1;
+ sd = view->itemsize;
+ if (view->ndim == 1) return (view->shape[0] == 1 ||
+ sd == view->strides[0]);
+ for (i=view->ndim-1; i>=0; i--) {
+ dim = view->shape[i];
+ if (dim == 0) return 1;
+ if (view->strides[i] != sd) return 0;
+ sd *= dim;
+ }
+ return 1;
}
int
PyBuffer_IsContiguous(Py_buffer *view, char fort)
{
- if (view->suboffsets != NULL) return 0;
+ if (view->suboffsets != NULL) return 0;
- if (fort == 'C')
- return _IsCContiguous(view);
- else if (fort == 'F')
- return _IsFortranContiguous(view);
- else if (fort == 'A')
- return (_IsCContiguous(view) || _IsFortranContiguous(view));
- return 0;
+ if (fort == 'C')
+ return _IsCContiguous(view);
+ else if (fort == 'F')
+ return _IsFortranContiguous(view);
+ else if (fort == 'A')
+ return (_IsCContiguous(view) || _IsFortranContiguous(view));
+ return 0;
}
void*
PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
{
- char* pointer;
- int i;
- pointer = (char *)view->buf;
- for (i = 0; i < view->ndim; i++) {
- pointer += view->strides[i]*indices[i];
- if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
- pointer = *((char**)pointer) + view->suboffsets[i];
- }
- }
- return (void*)pointer;
+ char* pointer;
+ int i;
+ pointer = (char *)view->buf;
+ for (i = 0; i < view->ndim; i++) {
+ pointer += view->strides[i]*indices[i];
+ if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
+ pointer = *((char**)pointer) + view->suboffsets[i];
+ }
+ }
+ return (void*)pointer;
}
void
_add_one_to_index_F(int nd, Py_ssize_t *index, Py_ssize_t *shape)
{
- int k;
+ int k;
- for (k=0; k<nd; k++) {
- if (index[k] < shape[k]-1) {
- index[k]++;
- break;
- }
- else {
- index[k] = 0;
- }
- }
+ for (k=0; k<nd; k++) {
+ if (index[k] < shape[k]-1) {
+ index[k]++;
+ break;
+ }
+ else {
+ index[k] = 0;
+ }
+ }
}
void
_add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
{
- int k;
+ int k;
- for (k=nd-1; k>=0; k--) {
- if (index[k] < shape[k]-1) {
- index[k]++;
- break;
- }
- else {
- index[k] = 0;
- }
- }
+ for (k=nd-1; k>=0; k--) {
+ if (index[k] < shape[k]-1) {
+ index[k]++;
+ break;
+ }
+ else {
+ index[k] = 0;
+ }
+ }
}
/* view is not checked for consistency in either of these. It is
@@ -482,413 +482,413 @@ _add_one_to_index_C(int nd, Py_ssize_t *index, Py_ssize_t *shape)
int
PyBuffer_ToContiguous(void *buf, Py_buffer *view, Py_ssize_t len, char fort)
{
- int k;
- void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
- Py_ssize_t *indices, elements;
- char *dest, *ptr;
-
- if (len > view->len) {
- len = view->len;
- }
-
- if (PyBuffer_IsContiguous(view, fort)) {
- /* simplest copy is all that is needed */
- memcpy(buf, view->buf, len);
- return 0;
- }
-
- /* Otherwise a more elaborate scheme is needed */
-
- /* XXX(nnorwitz): need to check for overflow! */
- indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
- if (indices == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- for (k=0; k<view->ndim;k++) {
- indices[k] = 0;
- }
-
- if (fort == 'F') {
- addone = _add_one_to_index_F;
- }
- else {
- addone = _add_one_to_index_C;
- }
- dest = buf;
- /* XXX : This is not going to be the fastest code in the world
- several optimizations are possible.
- */
- elements = len / view->itemsize;
- while (elements--) {
- addone(view->ndim, indices, view->shape);
- ptr = PyBuffer_GetPointer(view, indices);
- memcpy(dest, ptr, view->itemsize);
- dest += view->itemsize;
- }
- PyMem_Free(indices);
- return 0;
+ int k;
+ void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
+ Py_ssize_t *indices, elements;
+ char *dest, *ptr;
+
+ if (len > view->len) {
+ len = view->len;
+ }
+
+ if (PyBuffer_IsContiguous(view, fort)) {
+ /* simplest copy is all that is needed */
+ memcpy(buf, view->buf, len);
+ return 0;
+ }
+
+ /* Otherwise a more elaborate scheme is needed */
+
+ /* XXX(nnorwitz): need to check for overflow! */
+ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ for (k=0; k<view->ndim;k++) {
+ indices[k] = 0;
+ }
+
+ if (fort == 'F') {
+ addone = _add_one_to_index_F;
+ }
+ else {
+ addone = _add_one_to_index_C;
+ }
+ dest = buf;
+ /* XXX : This is not going to be the fastest code in the world
+ several optimizations are possible.
+ */
+ elements = len / view->itemsize;
+ while (elements--) {
+ addone(view->ndim, indices, view->shape);
+ ptr = PyBuffer_GetPointer(view, indices);
+ memcpy(dest, ptr, view->itemsize);
+ dest += view->itemsize;
+ }
+ PyMem_Free(indices);
+ return 0;
}
int
PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
{
- int k;
- void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
- Py_ssize_t *indices, elements;
- char *src, *ptr;
-
- if (len > view->len) {
- len = view->len;
- }
-
- if (PyBuffer_IsContiguous(view, fort)) {
- /* simplest copy is all that is needed */
- memcpy(view->buf, buf, len);
- return 0;
- }
-
- /* Otherwise a more elaborate scheme is needed */
-
- /* XXX(nnorwitz): need to check for overflow! */
- indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
- if (indices == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- for (k=0; k<view->ndim;k++) {
- indices[k] = 0;
- }
-
- if (fort == 'F') {
- addone = _add_one_to_index_F;
- }
- else {
- addone = _add_one_to_index_C;
- }
- src = buf;
- /* XXX : This is not going to be the fastest code in the world
- several optimizations are possible.
- */
- elements = len / view->itemsize;
- while (elements--) {
- addone(view->ndim, indices, view->shape);
- ptr = PyBuffer_GetPointer(view, indices);
- memcpy(ptr, src, view->itemsize);
- src += view->itemsize;
- }
-
- PyMem_Free(indices);
- return 0;
+ int k;
+ void (*addone)(int, Py_ssize_t *, Py_ssize_t *);
+ Py_ssize_t *indices, elements;
+ char *src, *ptr;
+
+ if (len > view->len) {
+ len = view->len;
+ }
+
+ if (PyBuffer_IsContiguous(view, fort)) {
+ /* simplest copy is all that is needed */
+ memcpy(view->buf, buf, len);
+ return 0;
+ }
+
+ /* Otherwise a more elaborate scheme is needed */
+
+ /* XXX(nnorwitz): need to check for overflow! */
+ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ for (k=0; k<view->ndim;k++) {
+ indices[k] = 0;
+ }
+
+ if (fort == 'F') {
+ addone = _add_one_to_index_F;
+ }
+ else {
+ addone = _add_one_to_index_C;
+ }
+ src = buf;
+ /* XXX : This is not going to be the fastest code in the world
+ several optimizations are possible.
+ */
+ elements = len / view->itemsize;
+ while (elements--) {
+ addone(view->ndim, indices, view->shape);
+ ptr = PyBuffer_GetPointer(view, indices);
+ memcpy(ptr, src, view->itemsize);
+ src += view->itemsize;
+ }
+
+ PyMem_Free(indices);
+ return 0;
}
int PyObject_CopyData(PyObject *dest, PyObject *src)
{
- Py_buffer view_dest, view_src;
- int k;
- Py_ssize_t *indices, elements;
- char *dptr, *sptr;
-
- if (!PyObject_CheckBuffer(dest) ||
- !PyObject_CheckBuffer(src)) {
- PyErr_SetString(PyExc_TypeError,
- "both destination and source must have the "\
- "buffer interface");
- return -1;
- }
-
- if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
- if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
- PyBuffer_Release(&view_dest);
- return -1;
- }
-
- if (view_dest.len < view_src.len) {
- PyErr_SetString(PyExc_BufferError,
- "destination is too small to receive data from source");
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return -1;
- }
-
- if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
- PyBuffer_IsContiguous(&view_src, 'C')) ||
- (PyBuffer_IsContiguous(&view_dest, 'F') &&
- PyBuffer_IsContiguous(&view_src, 'F'))) {
- /* simplest copy is all that is needed */
- memcpy(view_dest.buf, view_src.buf, view_src.len);
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return 0;
- }
-
- /* Otherwise a more elaborate copy scheme is needed */
-
- /* XXX(nnorwitz): need to check for overflow! */
- indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
- if (indices == NULL) {
- PyErr_NoMemory();
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return -1;
- }
- for (k=0; k<view_src.ndim;k++) {
- indices[k] = 0;
- }
- elements = 1;
- for (k=0; k<view_src.ndim; k++) {
- /* XXX(nnorwitz): can this overflow? */
- elements *= view_src.shape[k];
- }
- while (elements--) {
- _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
- dptr = PyBuffer_GetPointer(&view_dest, indices);
- sptr = PyBuffer_GetPointer(&view_src, indices);
- memcpy(dptr, sptr, view_src.itemsize);
- }
- PyMem_Free(indices);
- PyBuffer_Release(&view_dest);
- PyBuffer_Release(&view_src);
- return 0;
+ Py_buffer view_dest, view_src;
+ int k;
+ Py_ssize_t *indices, elements;
+ char *dptr, *sptr;
+
+ if (!PyObject_CheckBuffer(dest) ||
+ !PyObject_CheckBuffer(src)) {
+ PyErr_SetString(PyExc_TypeError,
+ "both destination and source must have the "\
+ "buffer interface");
+ return -1;
+ }
+
+ if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
+ if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
+ PyBuffer_Release(&view_dest);
+ return -1;
+ }
+
+ if (view_dest.len < view_src.len) {
+ PyErr_SetString(PyExc_BufferError,
+ "destination is too small to receive data from source");
+ PyBuffer_Release(&view_dest);
+ PyBuffer_Release(&view_src);
+ return -1;
+ }
+
+ if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
+ PyBuffer_IsContiguous(&view_src, 'C')) ||
+ (PyBuffer_IsContiguous(&view_dest, 'F') &&
+ PyBuffer_IsContiguous(&view_src, 'F'))) {
+ /* simplest copy is all that is needed */
+ memcpy(view_dest.buf, view_src.buf, view_src.len);
+ PyBuffer_Release(&view_dest);
+ PyBuffer_Release(&view_src);
+ return 0;
+ }
+
+ /* Otherwise a more elaborate copy scheme is needed */
+
+ /* XXX(nnorwitz): need to check for overflow! */
+ indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
+ if (indices == NULL) {
+ PyErr_NoMemory();
+ PyBuffer_Release(&view_dest);
+ PyBuffer_Release(&view_src);
+ return -1;
+ }
+ for (k=0; k<view_src.ndim;k++) {
+ indices[k] = 0;
+ }
+ elements = 1;
+ for (k=0; k<view_src.ndim; k++) {
+ /* XXX(nnorwitz): can this overflow? */
+ elements *= view_src.shape[k];
+ }
+ while (elements--) {
+ _add_one_to_index_C(view_src.ndim, indices, view_src.shape);
+ dptr = PyBuffer_GetPointer(&view_dest, indices);
+ sptr = PyBuffer_GetPointer(&view_src, indices);
+ memcpy(dptr, sptr, view_src.itemsize);
+ }
+ PyMem_Free(indices);
+ PyBuffer_Release(&view_dest);
+ PyBuffer_Release(&view_src);
+ return 0;
}
void
PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
- Py_ssize_t *strides, int itemsize,
- char fort)
-{
- int k;
- Py_ssize_t sd;
-
- sd = itemsize;
- if (fort == 'F') {
- for (k=0; k<nd; k++) {
- strides[k] = sd;
- sd *= shape[k];
- }
- }
- else {
- for (k=nd-1; k>=0; k--) {
- strides[k] = sd;
- sd *= shape[k];
- }
- }
- return;
+ Py_ssize_t *strides, int itemsize,
+ char fort)
+{
+ int k;
+ Py_ssize_t sd;
+
+ sd = itemsize;
+ if (fort == 'F') {
+ for (k=0; k<nd; k++) {
+ strides[k] = sd;
+ sd *= shape[k];
+ }
+ }
+ else {
+ for (k=nd-1; k>=0; k--) {
+ strides[k] = sd;
+ sd *= shape[k];
+ }
+ }
+ return;
}
int
PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
- int readonly, int flags)
-{
- if (view == NULL) return 0;
- if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
- (readonly == 1)) {
- PyErr_SetString(PyExc_BufferError,
- "Object is not writable.");
- return -1;
- }
-
- view->obj = obj;
- if (obj)
- Py_INCREF(obj);
- view->buf = buf;
- view->len = len;
- view->readonly = readonly;
- view->itemsize = 1;
- view->format = NULL;
- if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
- view->format = "B";
- view->ndim = 1;
- view->shape = NULL;
- if ((flags & PyBUF_ND) == PyBUF_ND)
- view->shape = &(view->len);
- view->strides = NULL;
- if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
- view->strides = &(view->itemsize);
- view->suboffsets = NULL;
- view->internal = NULL;
- return 0;
+ int readonly, int flags)
+{
+ if (view == NULL) return 0;
+ if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
+ (readonly == 1)) {
+ PyErr_SetString(PyExc_BufferError,
+ "Object is not writable.");
+ return -1;
+ }
+
+ view->obj = obj;
+ if (obj)
+ Py_INCREF(obj);
+ view->buf = buf;
+ view->len = len;
+ view->readonly = readonly;
+ view->itemsize = 1;
+ view->format = NULL;
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
+ view->format = "B";
+ view->ndim = 1;
+ view->shape = NULL;
+ if ((flags & PyBUF_ND) == PyBUF_ND)
+ view->shape = &(view->len);
+ view->strides = NULL;
+ if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
+ view->strides = &(view->itemsize);
+ view->suboffsets = NULL;
+ view->internal = NULL;
+ return 0;
}
void
PyBuffer_Release(Py_buffer *view)
{
- PyObject *obj = view->obj;
- if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
- Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
- Py_XDECREF(obj);
- view->obj = NULL;
+ PyObject *obj = view->obj;
+ if (obj && Py_TYPE(obj)->tp_as_buffer && Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer)
+ Py_TYPE(obj)->tp_as_buffer->bf_releasebuffer(obj, view);
+ Py_XDECREF(obj);
+ view->obj = NULL;
}
PyObject *
PyObject_Format(PyObject* obj, PyObject *format_spec)
{
- static PyObject * str__format__ = NULL;
- PyObject *empty = NULL;
- PyObject *result = NULL;
+ static PyObject * str__format__ = NULL;
+ PyObject *empty = NULL;
+ PyObject *result = NULL;
#ifdef Py_USING_UNICODE
- int spec_is_unicode;
- int result_is_unicode;
+ int spec_is_unicode;
+ int result_is_unicode;
#endif
- /* Initialize cached value */
- if (str__format__ == NULL) {
- /* Initialize static variable needed by _PyType_Lookup */
- str__format__ = PyString_InternFromString("__format__");
- if (str__format__ == NULL)
- goto done;
- }
-
- /* If no format_spec is provided, use an empty string */
- if (format_spec == NULL) {
- empty = PyString_FromStringAndSize(NULL, 0);
- format_spec = empty;
- }
-
- /* Check the format_spec type, and make sure it's str or unicode */
+ /* Initialize cached value */
+ if (str__format__ == NULL) {
+ /* Initialize static variable needed by _PyType_Lookup */
+ str__format__ = PyString_InternFromString("__format__");
+ if (str__format__ == NULL)
+ goto done;
+ }
+
+ /* If no format_spec is provided, use an empty string */
+ if (format_spec == NULL) {
+ empty = PyString_FromStringAndSize(NULL, 0);
+ format_spec = empty;
+ }
+
+ /* Check the format_spec type, and make sure it's str or unicode */
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(format_spec))
- spec_is_unicode = 1;
- else if (PyString_Check(format_spec))
- spec_is_unicode = 0;
- else {
+ if (PyUnicode_Check(format_spec))
+ spec_is_unicode = 1;
+ else if (PyString_Check(format_spec))
+ spec_is_unicode = 0;
+ else {
#else
- if (!PyString_Check(format_spec)) {
+ if (!PyString_Check(format_spec)) {
#endif
- PyErr_Format(PyExc_TypeError,
- "format expects arg 2 to be string "
- "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
- goto done;
- }
-
- /* Make sure the type is initialized. float gets initialized late */
- if (Py_TYPE(obj)->tp_dict == NULL)
- if (PyType_Ready(Py_TYPE(obj)) < 0)
- goto done;
-
- /* Check for a __format__ method and call it. */
- if (PyInstance_Check(obj)) {
- /* We're an instance of a classic class */
- PyObject *bound_method = PyObject_GetAttr(obj,
- str__format__);
- if (bound_method != NULL) {
- result = PyObject_CallFunctionObjArgs(bound_method,
- format_spec,
- NULL);
- Py_DECREF(bound_method);
- } else {
- PyObject *self_as_str = NULL;
- PyObject *format_method = NULL;
- Py_ssize_t format_len;
-
- PyErr_Clear();
- /* Per the PEP, convert to str (or unicode,
- depending on the type of the format
- specifier). For new-style classes, this
- logic is done by object.__format__(). */
+ PyErr_Format(PyExc_TypeError,
+ "format expects arg 2 to be string "
+ "or unicode, not %.100s", Py_TYPE(format_spec)->tp_name);
+ goto done;
+ }
+
+ /* Make sure the type is initialized. float gets initialized late */
+ if (Py_TYPE(obj)->tp_dict == NULL)
+ if (PyType_Ready(Py_TYPE(obj)) < 0)
+ goto done;
+
+ /* Check for a __format__ method and call it. */
+ if (PyInstance_Check(obj)) {
+ /* We're an instance of a classic class */
+ PyObject *bound_method = PyObject_GetAttr(obj,
+ str__format__);
+ if (bound_method != NULL) {
+ result = PyObject_CallFunctionObjArgs(bound_method,
+ format_spec,
+ NULL);
+ Py_DECREF(bound_method);
+ } else {
+ PyObject *self_as_str = NULL;
+ PyObject *format_method = NULL;
+ Py_ssize_t format_len;
+
+ PyErr_Clear();
+ /* Per the PEP, convert to str (or unicode,
+ depending on the type of the format
+ specifier). For new-style classes, this
+ logic is done by object.__format__(). */
#ifdef Py_USING_UNICODE
- if (spec_is_unicode) {
- format_len = PyUnicode_GET_SIZE(format_spec);
- self_as_str = PyObject_Unicode(obj);
- } else
+ if (spec_is_unicode) {
+ format_len = PyUnicode_GET_SIZE(format_spec);
+ self_as_str = PyObject_Unicode(obj);
+ } else
#endif
- {
- format_len = PyString_GET_SIZE(format_spec);
- self_as_str = PyObject_Str(obj);
- }
- if (self_as_str == NULL)
- goto done1;
-
- if (format_len > 0) {
- /* See the almost identical code in
- typeobject.c for new-style
- classes. */
- if (PyErr_WarnEx(
- PyExc_PendingDeprecationWarning,
- "object.__format__ with a non-empty "
- "format string is deprecated", 1)
- < 0) {
- goto done1;
- }
- /* Eventually this will become an
- error:
- PyErr_Format(PyExc_TypeError,
- "non-empty format string passed to "
- "object.__format__");
- goto done1;
- */
- }
-
- /* Then call str.__format__ on that result */
- format_method = PyObject_GetAttr(self_as_str,
- str__format__);
- if (format_method == NULL) {
- goto done1;
- }
- result = PyObject_CallFunctionObjArgs(format_method,
- format_spec,
- NULL);
+ {
+ format_len = PyString_GET_SIZE(format_spec);
+ self_as_str = PyObject_Str(obj);
+ }
+ if (self_as_str == NULL)
+ goto done1;
+
+ if (format_len > 0) {
+ /* See the almost identical code in
+ typeobject.c for new-style
+ classes. */
+ if (PyErr_WarnEx(
+ PyExc_PendingDeprecationWarning,
+ "object.__format__ with a non-empty "
+ "format string is deprecated", 1)
+ < 0) {
+ goto done1;
+ }
+ /* Eventually this will become an
+ error:
+ PyErr_Format(PyExc_TypeError,
+ "non-empty format string passed to "
+ "object.__format__");
+ goto done1;
+ */
+ }
+
+ /* Then call str.__format__ on that result */
+ format_method = PyObject_GetAttr(self_as_str,
+ str__format__);
+ if (format_method == NULL) {
+ goto done1;
+ }
+ result = PyObject_CallFunctionObjArgs(format_method,
+ format_spec,
+ NULL);
done1:
- Py_XDECREF(self_as_str);
- Py_XDECREF(format_method);
- if (result == NULL)
- goto done;
- }
- } else {
- /* Not an instance of a classic class, use the code
- from py3k */
-
- /* Find the (unbound!) __format__ method (a borrowed
- reference) */
- PyObject *method = _PyType_Lookup(Py_TYPE(obj),
- str__format__);
- if (method == NULL) {
- PyErr_Format(PyExc_TypeError,
- "Type %.100s doesn't define __format__",
- Py_TYPE(obj)->tp_name);
- goto done;
- }
- /* And call it, binding it to the value */
- result = PyObject_CallFunctionObjArgs(method, obj,
- format_spec, NULL);
- }
-
- if (result == NULL)
- goto done;
-
- /* Check the result type, and make sure it's str or unicode */
+ Py_XDECREF(self_as_str);
+ Py_XDECREF(format_method);
+ if (result == NULL)
+ goto done;
+ }
+ } else {
+ /* Not an instance of a classic class, use the code
+ from py3k */
+
+ /* Find the (unbound!) __format__ method (a borrowed
+ reference) */
+ PyObject *method = _PyType_Lookup(Py_TYPE(obj),
+ str__format__);
+ if (method == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "Type %.100s doesn't define __format__",
+ Py_TYPE(obj)->tp_name);
+ goto done;
+ }
+ /* And call it, binding it to the value */
+ result = PyObject_CallFunctionObjArgs(method, obj,
+ format_spec, NULL);
+ }
+
+ if (result == NULL)
+ goto done;
+
+ /* Check the result type, and make sure it's str or unicode */
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(result))
- result_is_unicode = 1;
- else if (PyString_Check(result))
- result_is_unicode = 0;
- else {
+ if (PyUnicode_Check(result))
+ result_is_unicode = 1;
+ else if (PyString_Check(result))
+ result_is_unicode = 0;
+ else {
#else
- if (!PyString_Check(result)) {
+ if (!PyString_Check(result)) {
#endif
- PyErr_Format(PyExc_TypeError,
- "%.100s.__format__ must return string or "
- "unicode, not %.100s", Py_TYPE(obj)->tp_name,
- Py_TYPE(result)->tp_name);
- Py_DECREF(result);
- result = NULL;
- goto done;
- }
-
- /* Convert to unicode, if needed. Required if spec is unicode
- and result is str */
+ PyErr_Format(PyExc_TypeError,
+ "%.100s.__format__ must return string or "
+ "unicode, not %.100s", Py_TYPE(obj)->tp_name,
+ Py_TYPE(result)->tp_name);
+ Py_DECREF(result);
+ result = NULL;
+ goto done;
+ }
+
+ /* Convert to unicode, if needed. Required if spec is unicode
+ and result is str */
#ifdef Py_USING_UNICODE
- if (spec_is_unicode && !result_is_unicode) {
- PyObject *tmp = PyObject_Unicode(result);
- /* This logic works whether or not tmp is NULL */
- Py_DECREF(result);
- result = tmp;
- }
+ if (spec_is_unicode && !result_is_unicode) {
+ PyObject *tmp = PyObject_Unicode(result);
+ /* This logic works whether or not tmp is NULL */
+ Py_DECREF(result);
+ result = tmp;
+ }
#endif
done:
- Py_XDECREF(empty);
- return result;
+ Py_XDECREF(empty);
+ return result;
}
/* Operations on numbers */
@@ -896,9 +896,9 @@ done:
int
PyNumber_Check(PyObject *o)
{
- return o && o->ob_type->tp_as_number &&
- (o->ob_type->tp_as_number->nb_int ||
- o->ob_type->tp_as_number->nb_float);
+ return o && o->ob_type->tp_as_number &&
+ (o->ob_type->tp_as_number->nb_int ||
+ o->ob_type->tp_as_number->nb_float);
}
/* Binary operators */
@@ -907,19 +907,19 @@ PyNumber_Check(PyObject *o)
#define NB_SLOT(x) offsetof(PyNumberMethods, x)
#define NB_BINOP(nb_methods, slot) \
- (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
+ (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
#define NB_TERNOP(nb_methods, slot) \
- (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
+ (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
/*
Calling scheme used for binary operations:
- v w Action
+ v w Action
-------------------------------------------------------------------
- new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
- new old v.op(v,w), coerce(v,w), v.op(v,w)
- old new w.op(v,w), coerce(v,w), v.op(v,w)
- old old coerce(v,w), v.op(v,w)
+ new new w.op(v,w)[*], v.op(v,w), w.op(v,w)
+ new old v.op(v,w), coerce(v,w), v.op(v,w)
+ old new w.op(v,w), coerce(v,w), v.op(v,w)
+ old old coerce(v,w), v.op(v,w)
[*] only when v->ob_type != w->ob_type && w->ob_type is a subclass of
v->ob_type
@@ -936,84 +936,84 @@ PyNumber_Check(PyObject *o)
static PyObject *
binary_op1(PyObject *v, PyObject *w, const int op_slot)
{
- PyObject *x;
- binaryfunc slotv = NULL;
- binaryfunc slotw = NULL;
-
- if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
- slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
- if (w->ob_type != v->ob_type &&
- w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
- slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
- if (slotw == slotv)
- slotw = NULL;
- }
- if (slotv) {
- if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
- x = slotw(v, w);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- slotw = NULL;
- }
- x = slotv(v, w);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- }
- if (slotw) {
- x = slotw(v, w);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- }
- if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
- int err = PyNumber_CoerceEx(&v, &w);
- if (err < 0) {
- return NULL;
- }
- if (err == 0) {
- PyNumberMethods *mv = v->ob_type->tp_as_number;
- if (mv) {
- binaryfunc slot;
- slot = NB_BINOP(mv, op_slot);
- if (slot) {
- x = slot(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- return x;
- }
- }
- /* CoerceEx incremented the reference counts */
- Py_DECREF(v);
- Py_DECREF(w);
- }
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ PyObject *x;
+ binaryfunc slotv = NULL;
+ binaryfunc slotw = NULL;
+
+ if (v->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(v))
+ slotv = NB_BINOP(v->ob_type->tp_as_number, op_slot);
+ if (w->ob_type != v->ob_type &&
+ w->ob_type->tp_as_number != NULL && NEW_STYLE_NUMBER(w)) {
+ slotw = NB_BINOP(w->ob_type->tp_as_number, op_slot);
+ if (slotw == slotv)
+ slotw = NULL;
+ }
+ if (slotv) {
+ if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
+ x = slotw(v, w);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ slotw = NULL;
+ }
+ x = slotv(v, w);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ }
+ if (slotw) {
+ x = slotw(v, w);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ }
+ if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w)) {
+ int err = PyNumber_CoerceEx(&v, &w);
+ if (err < 0) {
+ return NULL;
+ }
+ if (err == 0) {
+ PyNumberMethods *mv = v->ob_type->tp_as_number;
+ if (mv) {
+ binaryfunc slot;
+ slot = NB_BINOP(mv, op_slot);
+ if (slot) {
+ x = slot(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ return x;
+ }
+ }
+ /* CoerceEx incremented the reference counts */
+ Py_DECREF(v);
+ Py_DECREF(w);
+ }
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyObject *
binop_type_error(PyObject *v, PyObject *w, const char *op_name)
{
- PyErr_Format(PyExc_TypeError,
- "unsupported operand type(s) for %.100s: "
- "'%.100s' and '%.100s'",
- op_name,
- v->ob_type->tp_name,
- w->ob_type->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "unsupported operand type(s) for %.100s: "
+ "'%.100s' and '%.100s'",
+ op_name,
+ v->ob_type->tp_name,
+ w->ob_type->tp_name);
+ return NULL;
}
static PyObject *
binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
{
- PyObject *result = binary_op1(v, w, op_slot);
- if (result == Py_NotImplemented) {
- Py_DECREF(result);
- return binop_type_error(v, w, op_name);
- }
- return result;
+ PyObject *result = binary_op1(v, w, op_slot);
+ if (result == Py_NotImplemented) {
+ Py_DECREF(result);
+ return binop_type_error(v, w, op_name);
+ }
+ return result;
}
@@ -1022,16 +1022,16 @@ binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
*** In some cases, w.op is called before v.op; see binary_op1. ***
- v w z Action
+ v w z Action
-------------------------------------------------------------------
- new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
- new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
- old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
- old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
- new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
- new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
- old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
- old old old coerce(v,w,z), v.op(v,w,z)
+ new new new v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
+ new old new v.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
+ old new new w.op(v,w,z), z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
+ old old new z.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
+ new new old v.op(v,w,z), w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
+ new old old v.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
+ old new old w.op(v,w,z), coerce(v,w,z), v.op(v,w,z)
+ old old old coerce(v,w,z), v.op(v,w,z)
Legend:
-------
@@ -1047,141 +1047,141 @@ binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
static PyObject *
ternary_op(PyObject *v,
- PyObject *w,
- PyObject *z,
- const int op_slot,
- const char *op_name)
-{
- PyNumberMethods *mv, *mw, *mz;
- PyObject *x = NULL;
- ternaryfunc slotv = NULL;
- ternaryfunc slotw = NULL;
- ternaryfunc slotz = NULL;
-
- mv = v->ob_type->tp_as_number;
- mw = w->ob_type->tp_as_number;
- if (mv != NULL && NEW_STYLE_NUMBER(v))
- slotv = NB_TERNOP(mv, op_slot);
- if (w->ob_type != v->ob_type &&
- mw != NULL && NEW_STYLE_NUMBER(w)) {
- slotw = NB_TERNOP(mw, op_slot);
- if (slotw == slotv)
- slotw = NULL;
- }
- if (slotv) {
- if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
- x = slotw(v, w, z);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- slotw = NULL;
- }
- x = slotv(v, w, z);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- }
- if (slotw) {
- x = slotw(v, w, z);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- }
- mz = z->ob_type->tp_as_number;
- if (mz != NULL && NEW_STYLE_NUMBER(z)) {
- slotz = NB_TERNOP(mz, op_slot);
- if (slotz == slotv || slotz == slotw)
- slotz = NULL;
- if (slotz) {
- x = slotz(v, w, z);
- if (x != Py_NotImplemented)
- return x;
- Py_DECREF(x); /* can't do it */
- }
- }
-
- if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
- (z != Py_None && !NEW_STYLE_NUMBER(z))) {
- /* we have an old style operand, coerce */
- PyObject *v1, *z1, *w2, *z2;
- int c;
-
- c = PyNumber_Coerce(&v, &w);
- if (c != 0)
- goto error3;
-
- /* Special case: if the third argument is None, it is
- treated as absent argument and not coerced. */
- if (z == Py_None) {
- if (v->ob_type->tp_as_number) {
- slotz = NB_TERNOP(v->ob_type->tp_as_number,
- op_slot);
- if (slotz)
- x = slotz(v, w, z);
- else
- c = -1;
- }
- else
- c = -1;
- goto error2;
- }
- v1 = v;
- z1 = z;
- c = PyNumber_Coerce(&v1, &z1);
- if (c != 0)
- goto error2;
- w2 = w;
- z2 = z1;
- c = PyNumber_Coerce(&w2, &z2);
- if (c != 0)
- goto error1;
-
- if (v1->ob_type->tp_as_number != NULL) {
- slotv = NB_TERNOP(v1->ob_type->tp_as_number,
- op_slot);
- if (slotv)
- x = slotv(v1, w2, z2);
- else
- c = -1;
- }
- else
- c = -1;
-
- Py_DECREF(w2);
- Py_DECREF(z2);
- error1:
- Py_DECREF(v1);
- Py_DECREF(z1);
- error2:
- Py_DECREF(v);
- Py_DECREF(w);
- error3:
- if (c >= 0)
- return x;
- }
-
- if (z == Py_None)
- PyErr_Format(
- PyExc_TypeError,
- "unsupported operand type(s) for ** or pow(): "
- "'%.100s' and '%.100s'",
- v->ob_type->tp_name,
- w->ob_type->tp_name);
- else
- PyErr_Format(
- PyExc_TypeError,
- "unsupported operand type(s) for pow(): "
- "'%.100s', '%.100s', '%.100s'",
- v->ob_type->tp_name,
- w->ob_type->tp_name,
- z->ob_type->tp_name);
- return NULL;
+ PyObject *w,
+ PyObject *z,
+ const int op_slot,
+ const char *op_name)
+{
+ PyNumberMethods *mv, *mw, *mz;
+ PyObject *x = NULL;
+ ternaryfunc slotv = NULL;
+ ternaryfunc slotw = NULL;
+ ternaryfunc slotz = NULL;
+
+ mv = v->ob_type->tp_as_number;
+ mw = w->ob_type->tp_as_number;
+ if (mv != NULL && NEW_STYLE_NUMBER(v))
+ slotv = NB_TERNOP(mv, op_slot);
+ if (w->ob_type != v->ob_type &&
+ mw != NULL && NEW_STYLE_NUMBER(w)) {
+ slotw = NB_TERNOP(mw, op_slot);
+ if (slotw == slotv)
+ slotw = NULL;
+ }
+ if (slotv) {
+ if (slotw && PyType_IsSubtype(w->ob_type, v->ob_type)) {
+ x = slotw(v, w, z);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ slotw = NULL;
+ }
+ x = slotv(v, w, z);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ }
+ if (slotw) {
+ x = slotw(v, w, z);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ }
+ mz = z->ob_type->tp_as_number;
+ if (mz != NULL && NEW_STYLE_NUMBER(z)) {
+ slotz = NB_TERNOP(mz, op_slot);
+ if (slotz == slotv || slotz == slotw)
+ slotz = NULL;
+ if (slotz) {
+ x = slotz(v, w, z);
+ if (x != Py_NotImplemented)
+ return x;
+ Py_DECREF(x); /* can't do it */
+ }
+ }
+
+ if (!NEW_STYLE_NUMBER(v) || !NEW_STYLE_NUMBER(w) ||
+ (z != Py_None && !NEW_STYLE_NUMBER(z))) {
+ /* we have an old style operand, coerce */
+ PyObject *v1, *z1, *w2, *z2;
+ int c;
+
+ c = PyNumber_Coerce(&v, &w);
+ if (c != 0)
+ goto error3;
+
+ /* Special case: if the third argument is None, it is
+ treated as absent argument and not coerced. */
+ if (z == Py_None) {
+ if (v->ob_type->tp_as_number) {
+ slotz = NB_TERNOP(v->ob_type->tp_as_number,
+ op_slot);
+ if (slotz)
+ x = slotz(v, w, z);
+ else
+ c = -1;
+ }
+ else
+ c = -1;
+ goto error2;
+ }
+ v1 = v;
+ z1 = z;
+ c = PyNumber_Coerce(&v1, &z1);
+ if (c != 0)
+ goto error2;
+ w2 = w;
+ z2 = z1;
+ c = PyNumber_Coerce(&w2, &z2);
+ if (c != 0)
+ goto error1;
+
+ if (v1->ob_type->tp_as_number != NULL) {
+ slotv = NB_TERNOP(v1->ob_type->tp_as_number,
+ op_slot);
+ if (slotv)
+ x = slotv(v1, w2, z2);
+ else
+ c = -1;
+ }
+ else
+ c = -1;
+
+ Py_DECREF(w2);
+ Py_DECREF(z2);
+ error1:
+ Py_DECREF(v1);
+ Py_DECREF(z1);
+ error2:
+ Py_DECREF(v);
+ Py_DECREF(w);
+ error3:
+ if (c >= 0)
+ return x;
+ }
+
+ if (z == Py_None)
+ PyErr_Format(
+ PyExc_TypeError,
+ "unsupported operand type(s) for ** or pow(): "
+ "'%.100s' and '%.100s'",
+ v->ob_type->tp_name,
+ w->ob_type->tp_name);
+ else
+ PyErr_Format(
+ PyExc_TypeError,
+ "unsupported operand type(s) for pow(): "
+ "'%.100s', '%.100s', '%.100s'",
+ v->ob_type->tp_name,
+ w->ob_type->tp_name,
+ z->ob_type->tp_name);
+ return NULL;
}
#define BINARY_FUNC(func, op, op_name) \
PyObject * \
func(PyObject *v, PyObject *w) { \
- return binary_op(v, w, NB_SLOT(op), op_name); \
+ return binary_op(v, w, NB_SLOT(op), op_name); \
}
BINARY_FUNC(PyNumber_Or, nb_or, "|")
@@ -1196,77 +1196,77 @@ BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
PyObject *
PyNumber_Add(PyObject *v, PyObject *w)
{
- PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
- if (result == Py_NotImplemented) {
- PySequenceMethods *m = v->ob_type->tp_as_sequence;
- Py_DECREF(result);
- if (m && m->sq_concat) {
- return (*m->sq_concat)(v, w);
- }
- result = binop_type_error(v, w, "+");
- }
- return result;
+ PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
+ if (result == Py_NotImplemented) {
+ PySequenceMethods *m = v->ob_type->tp_as_sequence;
+ Py_DECREF(result);
+ if (m && m->sq_concat) {
+ return (*m->sq_concat)(v, w);
+ }
+ result = binop_type_error(v, w, "+");
+ }
+ return result;
}
static PyObject *
sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
{
- Py_ssize_t count;
- if (PyIndex_Check(n)) {
- count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
- if (count == -1 && PyErr_Occurred())
- return NULL;
- }
- else {
- return type_error("can't multiply sequence by "
- "non-int of type '%.200s'", n);
- }
- return (*repeatfunc)(seq, count);
+ Py_ssize_t count;
+ if (PyIndex_Check(n)) {
+ count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
+ if (count == -1 && PyErr_Occurred())
+ return NULL;
+ }
+ else {
+ return type_error("can't multiply sequence by "
+ "non-int of type '%.200s'", n);
+ }
+ return (*repeatfunc)(seq, count);
}
PyObject *
PyNumber_Multiply(PyObject *v, PyObject *w)
{
- PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
- if (result == Py_NotImplemented) {
- PySequenceMethods *mv = v->ob_type->tp_as_sequence;
- PySequenceMethods *mw = w->ob_type->tp_as_sequence;
- Py_DECREF(result);
- if (mv && mv->sq_repeat) {
- return sequence_repeat(mv->sq_repeat, v, w);
- }
- else if (mw && mw->sq_repeat) {
- return sequence_repeat(mw->sq_repeat, w, v);
- }
- result = binop_type_error(v, w, "*");
- }
- return result;
+ PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
+ if (result == Py_NotImplemented) {
+ PySequenceMethods *mv = v->ob_type->tp_as_sequence;
+ PySequenceMethods *mw = w->ob_type->tp_as_sequence;
+ Py_DECREF(result);
+ if (mv && mv->sq_repeat) {
+ return sequence_repeat(mv->sq_repeat, v, w);
+ }
+ else if (mw && mw->sq_repeat) {
+ return sequence_repeat(mw->sq_repeat, w, v);
+ }
+ result = binop_type_error(v, w, "*");
+ }
+ return result;
}
PyObject *
PyNumber_FloorDivide(PyObject *v, PyObject *w)
{
- /* XXX tp_flags test */
- return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
+ /* XXX tp_flags test */
+ return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
}
PyObject *
PyNumber_TrueDivide(PyObject *v, PyObject *w)
{
- /* XXX tp_flags test */
- return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
+ /* XXX tp_flags test */
+ return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
}
PyObject *
PyNumber_Remainder(PyObject *v, PyObject *w)
{
- return binary_op(v, w, NB_SLOT(nb_remainder), "%");
+ return binary_op(v, w, NB_SLOT(nb_remainder), "%");
}
PyObject *
PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
{
- return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
+ return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
}
/* Binary in-place operators */
@@ -1286,42 +1286,42 @@ PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
*/
#define HASINPLACE(t) \
- PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
+ PyType_HasFeature((t)->ob_type, Py_TPFLAGS_HAVE_INPLACEOPS)
static PyObject *
binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
{
- PyNumberMethods *mv = v->ob_type->tp_as_number;
- if (mv != NULL && HASINPLACE(v)) {
- binaryfunc slot = NB_BINOP(mv, iop_slot);
- if (slot) {
- PyObject *x = (slot)(v, w);
- if (x != Py_NotImplemented) {
- return x;
- }
- Py_DECREF(x);
- }
- }
- return binary_op1(v, w, op_slot);
+ PyNumberMethods *mv = v->ob_type->tp_as_number;
+ if (mv != NULL && HASINPLACE(v)) {
+ binaryfunc slot = NB_BINOP(mv, iop_slot);
+ if (slot) {
+ PyObject *x = (slot)(v, w);
+ if (x != Py_NotImplemented) {
+ return x;
+ }
+ Py_DECREF(x);
+ }
+ }
+ return binary_op1(v, w, op_slot);
}
static PyObject *
binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
- const char *op_name)
+ const char *op_name)
{
- PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
- if (result == Py_NotImplemented) {
- Py_DECREF(result);
- return binop_type_error(v, w, op_name);
- }
- return result;
+ PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
+ if (result == Py_NotImplemented) {
+ Py_DECREF(result);
+ return binop_type_error(v, w, op_name);
+ }
+ return result;
}
#define INPLACE_BINOP(func, iop, op, op_name) \
- PyObject * \
- func(PyObject *v, PyObject *w) { \
- return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
- }
+ PyObject * \
+ func(PyObject *v, PyObject *w) { \
+ return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
+ }
INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
@@ -1334,88 +1334,88 @@ INPLACE_BINOP(PyNumber_InPlaceDivide, nb_inplace_divide, nb_divide, "/=")
PyObject *
PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
{
- /* XXX tp_flags test */
- return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
- NB_SLOT(nb_floor_divide), "//=");
+ /* XXX tp_flags test */
+ return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
+ NB_SLOT(nb_floor_divide), "//=");
}
PyObject *
PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
{
- /* XXX tp_flags test */
- return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
- NB_SLOT(nb_true_divide), "/=");
+ /* XXX tp_flags test */
+ return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
+ NB_SLOT(nb_true_divide), "/=");
}
PyObject *
PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
{
- PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
- NB_SLOT(nb_add));
- if (result == Py_NotImplemented) {
- PySequenceMethods *m = v->ob_type->tp_as_sequence;
- Py_DECREF(result);
- if (m != NULL) {
- binaryfunc f = NULL;
- if (HASINPLACE(v))
- f = m->sq_inplace_concat;
- if (f == NULL)
- f = m->sq_concat;
- if (f != NULL)
- return (*f)(v, w);
- }
- result = binop_type_error(v, w, "+=");
- }
- return result;
+ PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
+ NB_SLOT(nb_add));
+ if (result == Py_NotImplemented) {
+ PySequenceMethods *m = v->ob_type->tp_as_sequence;
+ Py_DECREF(result);
+ if (m != NULL) {
+ binaryfunc f = NULL;
+ if (HASINPLACE(v))
+ f = m->sq_inplace_concat;
+ if (f == NULL)
+ f = m->sq_concat;
+ if (f != NULL)
+ return (*f)(v, w);
+ }
+ result = binop_type_error(v, w, "+=");
+ }
+ return result;
}
PyObject *
PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
{
- PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
- NB_SLOT(nb_multiply));
- if (result == Py_NotImplemented) {
- ssizeargfunc f = NULL;
- PySequenceMethods *mv = v->ob_type->tp_as_sequence;
- PySequenceMethods *mw = w->ob_type->tp_as_sequence;
- Py_DECREF(result);
- if (mv != NULL) {
- if (HASINPLACE(v))
- f = mv->sq_inplace_repeat;
- if (f == NULL)
- f = mv->sq_repeat;
- if (f != NULL)
- return sequence_repeat(f, v, w);
- }
- else if (mw != NULL) {
- /* Note that the right hand operand should not be
- * mutated in this case so sq_inplace_repeat is not
- * used. */
- if (mw->sq_repeat)
- return sequence_repeat(mw->sq_repeat, w, v);
- }
- result = binop_type_error(v, w, "*=");
- }
- return result;
+ PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
+ NB_SLOT(nb_multiply));
+ if (result == Py_NotImplemented) {
+ ssizeargfunc f = NULL;
+ PySequenceMethods *mv = v->ob_type->tp_as_sequence;
+ PySequenceMethods *mw = w->ob_type->tp_as_sequence;
+ Py_DECREF(result);
+ if (mv != NULL) {
+ if (HASINPLACE(v))
+ f = mv->sq_inplace_repeat;
+ if (f == NULL)
+ f = mv->sq_repeat;
+ if (f != NULL)
+ return sequence_repeat(f, v, w);
+ }
+ else if (mw != NULL) {
+ /* Note that the right hand operand should not be
+ * mutated in this case so sq_inplace_repeat is not
+ * used. */
+ if (mw->sq_repeat)
+ return sequence_repeat(mw->sq_repeat, w, v);
+ }
+ result = binop_type_error(v, w, "*=");
+ }
+ return result;
}
PyObject *
PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
{
- return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
- NB_SLOT(nb_remainder), "%=");
+ return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
+ NB_SLOT(nb_remainder), "%=");
}
PyObject *
PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
{
- if (HASINPLACE(v) && v->ob_type->tp_as_number &&
- v->ob_type->tp_as_number->nb_inplace_power != NULL) {
- return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
- }
- else {
- return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
- }
+ if (HASINPLACE(v) && v->ob_type->tp_as_number &&
+ v->ob_type->tp_as_number->nb_inplace_power != NULL) {
+ return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
+ }
+ else {
+ return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
+ }
}
@@ -1424,110 +1424,110 @@ PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
PyObject *
PyNumber_Negative(PyObject *o)
{
- PyNumberMethods *m;
+ PyNumberMethods *m;
- if (o == NULL)
- return null_error();
- m = o->ob_type->tp_as_number;
- if (m && m->nb_negative)
- return (*m->nb_negative)(o);
+ if (o == NULL)
+ return null_error();
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_negative)
+ return (*m->nb_negative)(o);
- return type_error("bad operand type for unary -: '%.200s'", o);
+ return type_error("bad operand type for unary -: '%.200s'", o);
}
PyObject *
PyNumber_Positive(PyObject *o)
{
- PyNumberMethods *m;
+ PyNumberMethods *m;
- if (o == NULL)
- return null_error();
- m = o->ob_type->tp_as_number;
- if (m && m->nb_positive)
- return (*m->nb_positive)(o);
+ if (o == NULL)
+ return null_error();
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_positive)
+ return (*m->nb_positive)(o);
- return type_error("bad operand type for unary +: '%.200s'", o);
+ return type_error("bad operand type for unary +: '%.200s'", o);
}
PyObject *
PyNumber_Invert(PyObject *o)
{
- PyNumberMethods *m;
+ PyNumberMethods *m;
- if (o == NULL)
- return null_error();
- m = o->ob_type->tp_as_number;
- if (m && m->nb_invert)
- return (*m->nb_invert)(o);
+ if (o == NULL)
+ return null_error();
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_invert)
+ return (*m->nb_invert)(o);
- return type_error("bad operand type for unary ~: '%.200s'", o);
+ return type_error("bad operand type for unary ~: '%.200s'", o);
}
PyObject *
PyNumber_Absolute(PyObject *o)
{
- PyNumberMethods *m;
+ PyNumberMethods *m;
- if (o == NULL)
- return null_error();
- m = o->ob_type->tp_as_number;
- if (m && m->nb_absolute)
- return m->nb_absolute(o);
+ if (o == NULL)
+ return null_error();
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_absolute)
+ return m->nb_absolute(o);
- return type_error("bad operand type for abs(): '%.200s'", o);
+ return type_error("bad operand type for abs(): '%.200s'", o);
}
/* Add a check for embedded NULL-bytes in the argument. */
static PyObject *
int_from_string(const char *s, Py_ssize_t len)
{
- char *end;
- PyObject *x;
-
- x = PyInt_FromString((char*)s, &end, 10);
- if (x == NULL)
- return NULL;
- if (end != s + len) {
- PyErr_SetString(PyExc_ValueError,
- "null byte in argument for int()");
- Py_DECREF(x);
- return NULL;
- }
- return x;
+ char *end;
+ PyObject *x;
+
+ x = PyInt_FromString((char*)s, &end, 10);
+ if (x == NULL)
+ return NULL;
+ if (end != s + len) {
+ PyErr_SetString(PyExc_ValueError,
+ "null byte in argument for int()");
+ Py_DECREF(x);
+ return NULL;
+ }
+ return x;
}
-/* Return a Python Int or Long from the object item
+/* Return a Python Int or Long from the object item
Raise TypeError if the result is not an int-or-long
- or if the object cannot be interpreted as an index.
+ or if the object cannot be interpreted as an index.
*/
PyObject *
PyNumber_Index(PyObject *item)
{
- PyObject *result = NULL;
- if (item == NULL)
- return null_error();
- if (PyInt_Check(item) || PyLong_Check(item)) {
- Py_INCREF(item);
- return item;
- }
- if (PyIndex_Check(item)) {
- result = item->ob_type->tp_as_number->nb_index(item);
- if (result &&
- !PyInt_Check(result) && !PyLong_Check(result)) {
- PyErr_Format(PyExc_TypeError,
- "__index__ returned non-(int,long) " \
- "(type %.200s)",
- result->ob_type->tp_name);
- Py_DECREF(result);
- return NULL;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "'%.200s' object cannot be interpreted "
- "as an index", item->ob_type->tp_name);
- }
- return result;
+ PyObject *result = NULL;
+ if (item == NULL)
+ return null_error();
+ if (PyInt_Check(item) || PyLong_Check(item)) {
+ Py_INCREF(item);
+ return item;
+ }
+ if (PyIndex_Check(item)) {
+ result = item->ob_type->tp_as_number->nb_index(item);
+ if (result &&
+ !PyInt_Check(result) && !PyLong_Check(result)) {
+ PyErr_Format(PyExc_TypeError,
+ "__index__ returned non-(int,long) " \
+ "(type %.200s)",
+ result->ob_type->tp_name);
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "'%.200s' object cannot be interpreted "
+ "as an index", item->ob_type->tp_name);
+ }
+ return result;
}
/* Return an error on Overflow only if err is not NULL*/
@@ -1535,296 +1535,296 @@ PyNumber_Index(PyObject *item)
Py_ssize_t
PyNumber_AsSsize_t(PyObject *item, PyObject *err)
{
- Py_ssize_t result;
- PyObject *runerr;
- PyObject *value = PyNumber_Index(item);
- if (value == NULL)
- return -1;
-
- /* We're done if PyInt_AsSsize_t() returns without error. */
- result = PyInt_AsSsize_t(value);
- if (result != -1 || !(runerr = PyErr_Occurred()))
- goto finish;
-
- /* Error handling code -- only manage OverflowError differently */
- if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
- goto finish;
-
- PyErr_Clear();
- /* If no error-handling desired then the default clipping
- is sufficient.
- */
- if (!err) {
- assert(PyLong_Check(value));
- /* Whether or not it is less than or equal to
- zero is determined by the sign of ob_size
- */
- if (_PyLong_Sign(value) < 0)
- result = PY_SSIZE_T_MIN;
- else
- result = PY_SSIZE_T_MAX;
- }
- else {
- /* Otherwise replace the error with caller's error object. */
- PyErr_Format(err,
- "cannot fit '%.200s' into an index-sized integer",
- item->ob_type->tp_name);
- }
-
+ Py_ssize_t result;
+ PyObject *runerr;
+ PyObject *value = PyNumber_Index(item);
+ if (value == NULL)
+ return -1;
+
+ /* We're done if PyInt_AsSsize_t() returns without error. */
+ result = PyInt_AsSsize_t(value);
+ if (result != -1 || !(runerr = PyErr_Occurred()))
+ goto finish;
+
+ /* Error handling code -- only manage OverflowError differently */
+ if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
+ goto finish;
+
+ PyErr_Clear();
+ /* If no error-handling desired then the default clipping
+ is sufficient.
+ */
+ if (!err) {
+ assert(PyLong_Check(value));
+ /* Whether or not it is less than or equal to
+ zero is determined by the sign of ob_size
+ */
+ if (_PyLong_Sign(value) < 0)
+ result = PY_SSIZE_T_MIN;
+ else
+ result = PY_SSIZE_T_MAX;
+ }
+ else {
+ /* Otherwise replace the error with caller's error object. */
+ PyErr_Format(err,
+ "cannot fit '%.200s' into an index-sized integer",
+ item->ob_type->tp_name);
+ }
+
finish:
- Py_DECREF(value);
- return result;
+ Py_DECREF(value);
+ return result;
}
PyObject *
_PyNumber_ConvertIntegralToInt(PyObject *integral, const char* error_format)
{
- const char *type_name;
- static PyObject *int_name = NULL;
- if (int_name == NULL) {
- int_name = PyString_InternFromString("__int__");
- if (int_name == NULL)
- return NULL;
- }
-
- if (integral && (!PyInt_Check(integral) &&
- !PyLong_Check(integral))) {
- /* Don't go through tp_as_number->nb_int to avoid
- hitting the classic class fallback to __trunc__. */
- PyObject *int_func = PyObject_GetAttr(integral, int_name);
- if (int_func == NULL) {
- PyErr_Clear(); /* Raise a different error. */
- goto non_integral_error;
- }
- Py_DECREF(integral);
- integral = PyEval_CallObject(int_func, NULL);
- Py_DECREF(int_func);
- if (integral && (!PyInt_Check(integral) &&
- !PyLong_Check(integral))) {
- goto non_integral_error;
- }
- }
- return integral;
+ const char *type_name;
+ static PyObject *int_name = NULL;
+ if (int_name == NULL) {
+ int_name = PyString_InternFromString("__int__");
+ if (int_name == NULL)
+ return NULL;
+ }
+
+ if (integral && (!PyInt_Check(integral) &&
+ !PyLong_Check(integral))) {
+ /* Don't go through tp_as_number->nb_int to avoid
+ hitting the classic class fallback to __trunc__. */
+ PyObject *int_func = PyObject_GetAttr(integral, int_name);
+ if (int_func == NULL) {
+ PyErr_Clear(); /* Raise a different error. */
+ goto non_integral_error;
+ }
+ Py_DECREF(integral);
+ integral = PyEval_CallObject(int_func, NULL);
+ Py_DECREF(int_func);
+ if (integral && (!PyInt_Check(integral) &&
+ !PyLong_Check(integral))) {
+ goto non_integral_error;
+ }
+ }
+ return integral;
non_integral_error:
- if (PyInstance_Check(integral)) {
- type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
- ->in_class->cl_name);
- }
- else {
- type_name = integral->ob_type->tp_name;
- }
- PyErr_Format(PyExc_TypeError, error_format, type_name);
- Py_DECREF(integral);
- return NULL;
+ if (PyInstance_Check(integral)) {
+ type_name = PyString_AS_STRING(((PyInstanceObject *)integral)
+ ->in_class->cl_name);
+ }
+ else {
+ type_name = integral->ob_type->tp_name;
+ }
+ PyErr_Format(PyExc_TypeError, error_format, type_name);
+ Py_DECREF(integral);
+ return NULL;
}
PyObject *
PyNumber_Int(PyObject *o)
{
- PyNumberMethods *m;
- static PyObject *trunc_name = NULL;
- PyObject *trunc_func;
- const char *buffer;
- Py_ssize_t buffer_len;
-
- if (trunc_name == NULL) {
- trunc_name = PyString_InternFromString("__trunc__");
- if (trunc_name == NULL)
- return NULL;
- }
-
- if (o == NULL)
- return null_error();
- if (PyInt_CheckExact(o)) {
- Py_INCREF(o);
- return o;
- }
- m = o->ob_type->tp_as_number;
- if (m && m->nb_int) { /* This should include subclasses of int */
- /* Classic classes always take this branch. */
- PyObject *res = m->nb_int(o);
- if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
- PyErr_Format(PyExc_TypeError,
- "__int__ returned non-int (type %.200s)",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
- }
- if (PyInt_Check(o)) { /* A int subclass without nb_int */
- PyIntObject *io = (PyIntObject*)o;
- return PyInt_FromLong(io->ob_ival);
- }
- trunc_func = PyObject_GetAttr(o, trunc_name);
- if (trunc_func) {
- PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
- Py_DECREF(trunc_func);
- /* __trunc__ is specified to return an Integral type, but
- int() needs to return an int. */
- return _PyNumber_ConvertIntegralToInt(
- truncated,
- "__trunc__ returned non-Integral (type %.200s)");
- }
- PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
-
- if (PyString_Check(o))
- return int_from_string(PyString_AS_STRING(o),
- PyString_GET_SIZE(o));
+ PyNumberMethods *m;
+ static PyObject *trunc_name = NULL;
+ PyObject *trunc_func;
+ const char *buffer;
+ Py_ssize_t buffer_len;
+
+ if (trunc_name == NULL) {
+ trunc_name = PyString_InternFromString("__trunc__");
+ if (trunc_name == NULL)
+ return NULL;
+ }
+
+ if (o == NULL)
+ return null_error();
+ if (PyInt_CheckExact(o)) {
+ Py_INCREF(o);
+ return o;
+ }
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_int) { /* This should include subclasses of int */
+ /* Classic classes always take this branch. */
+ PyObject *res = m->nb_int(o);
+ if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
+ PyErr_Format(PyExc_TypeError,
+ "__int__ returned non-int (type %.200s)",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
+ }
+ if (PyInt_Check(o)) { /* A int subclass without nb_int */
+ PyIntObject *io = (PyIntObject*)o;
+ return PyInt_FromLong(io->ob_ival);
+ }
+ trunc_func = PyObject_GetAttr(o, trunc_name);
+ if (trunc_func) {
+ PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
+ Py_DECREF(trunc_func);
+ /* __trunc__ is specified to return an Integral type, but
+ int() needs to return an int. */
+ return _PyNumber_ConvertIntegralToInt(
+ truncated,
+ "__trunc__ returned non-Integral (type %.200s)");
+ }
+ PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
+
+ if (PyString_Check(o))
+ return int_from_string(PyString_AS_STRING(o),
+ PyString_GET_SIZE(o));
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(o))
- return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
- PyUnicode_GET_SIZE(o),
- 10);
+ if (PyUnicode_Check(o))
+ return PyInt_FromUnicode(PyUnicode_AS_UNICODE(o),
+ PyUnicode_GET_SIZE(o),
+ 10);
#endif
- if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
- return int_from_string((char*)buffer, buffer_len);
+ if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
+ return int_from_string((char*)buffer, buffer_len);
- return type_error("int() argument must be a string or a "
- "number, not '%.200s'", o);
+ return type_error("int() argument must be a string or a "
+ "number, not '%.200s'", o);
}
/* Add a check for embedded NULL-bytes in the argument. */
static PyObject *
long_from_string(const char *s, Py_ssize_t len)
{
- char *end;
- PyObject *x;
-
- x = PyLong_FromString((char*)s, &end, 10);
- if (x == NULL)
- return NULL;
- if (end != s + len) {
- PyErr_SetString(PyExc_ValueError,
- "null byte in argument for long()");
- Py_DECREF(x);
- return NULL;
- }
- return x;
+ char *end;
+ PyObject *x;
+
+ x = PyLong_FromString((char*)s, &end, 10);
+ if (x == NULL)
+ return NULL;
+ if (end != s + len) {
+ PyErr_SetString(PyExc_ValueError,
+ "null byte in argument for long()");
+ Py_DECREF(x);
+ return NULL;
+ }
+ return x;
}
PyObject *
PyNumber_Long(PyObject *o)
{
- PyNumberMethods *m;
- static PyObject *trunc_name = NULL;
- PyObject *trunc_func;
- const char *buffer;
- Py_ssize_t buffer_len;
-
- if (trunc_name == NULL) {
- trunc_name = PyString_InternFromString("__trunc__");
- if (trunc_name == NULL)
- return NULL;
- }
-
- if (o == NULL)
- return null_error();
- m = o->ob_type->tp_as_number;
- if (m && m->nb_long) { /* This should include subclasses of long */
- /* Classic classes always take this branch. */
- PyObject *res = m->nb_long(o);
- if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
- PyErr_Format(PyExc_TypeError,
- "__long__ returned non-long (type %.200s)",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
- }
- if (PyLong_Check(o)) /* A long subclass without nb_long */
- return _PyLong_Copy((PyLongObject *)o);
- trunc_func = PyObject_GetAttr(o, trunc_name);
- if (trunc_func) {
- PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
- PyObject *int_instance;
- Py_DECREF(trunc_func);
- /* __trunc__ is specified to return an Integral type,
- but long() needs to return a long. */
- int_instance = _PyNumber_ConvertIntegralToInt(
- truncated,
- "__trunc__ returned non-Integral (type %.200s)");
- if (int_instance && PyInt_Check(int_instance)) {
- /* Make sure that long() returns a long instance. */
- long value = PyInt_AS_LONG(int_instance);
- Py_DECREF(int_instance);
- return PyLong_FromLong(value);
- }
- return int_instance;
- }
- PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
-
- if (PyString_Check(o))
- /* need to do extra error checking that PyLong_FromString()
- * doesn't do. In particular long('9.5') must raise an
- * exception, not truncate the float.
- */
- return long_from_string(PyString_AS_STRING(o),
- PyString_GET_SIZE(o));
+ PyNumberMethods *m;
+ static PyObject *trunc_name = NULL;
+ PyObject *trunc_func;
+ const char *buffer;
+ Py_ssize_t buffer_len;
+
+ if (trunc_name == NULL) {
+ trunc_name = PyString_InternFromString("__trunc__");
+ if (trunc_name == NULL)
+ return NULL;
+ }
+
+ if (o == NULL)
+ return null_error();
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_long) { /* This should include subclasses of long */
+ /* Classic classes always take this branch. */
+ PyObject *res = m->nb_long(o);
+ if (res && (!PyInt_Check(res) && !PyLong_Check(res))) {
+ PyErr_Format(PyExc_TypeError,
+ "__long__ returned non-long (type %.200s)",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
+ }
+ if (PyLong_Check(o)) /* A long subclass without nb_long */
+ return _PyLong_Copy((PyLongObject *)o);
+ trunc_func = PyObject_GetAttr(o, trunc_name);
+ if (trunc_func) {
+ PyObject *truncated = PyEval_CallObject(trunc_func, NULL);
+ PyObject *int_instance;
+ Py_DECREF(trunc_func);
+ /* __trunc__ is specified to return an Integral type,
+ but long() needs to return a long. */
+ int_instance = _PyNumber_ConvertIntegralToInt(
+ truncated,
+ "__trunc__ returned non-Integral (type %.200s)");
+ if (int_instance && PyInt_Check(int_instance)) {
+ /* Make sure that long() returns a long instance. */
+ long value = PyInt_AS_LONG(int_instance);
+ Py_DECREF(int_instance);
+ return PyLong_FromLong(value);
+ }
+ return int_instance;
+ }
+ PyErr_Clear(); /* It's not an error if o.__trunc__ doesn't exist. */
+
+ if (PyString_Check(o))
+ /* need to do extra error checking that PyLong_FromString()
+ * doesn't do. In particular long('9.5') must raise an
+ * exception, not truncate the float.
+ */
+ return long_from_string(PyString_AS_STRING(o),
+ PyString_GET_SIZE(o));
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(o))
- /* The above check is done in PyLong_FromUnicode(). */
- return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
- PyUnicode_GET_SIZE(o),
- 10);
+ if (PyUnicode_Check(o))
+ /* The above check is done in PyLong_FromUnicode(). */
+ return PyLong_FromUnicode(PyUnicode_AS_UNICODE(o),
+ PyUnicode_GET_SIZE(o),
+ 10);
#endif
- if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
- return long_from_string(buffer, buffer_len);
+ if (!PyObject_AsCharBuffer(o, &buffer, &buffer_len))
+ return long_from_string(buffer, buffer_len);
- return type_error("long() argument must be a string or a "
- "number, not '%.200s'", o);
+ return type_error("long() argument must be a string or a "
+ "number, not '%.200s'", o);
}
PyObject *
PyNumber_Float(PyObject *o)
{
- PyNumberMethods *m;
-
- if (o == NULL)
- return null_error();
- m = o->ob_type->tp_as_number;
- if (m && m->nb_float) { /* This should include subclasses of float */
- PyObject *res = m->nb_float(o);
- if (res && !PyFloat_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "__float__ returned non-float (type %.200s)",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
- }
- if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
- PyFloatObject *po = (PyFloatObject *)o;
- return PyFloat_FromDouble(po->ob_fval);
- }
- return PyFloat_FromString(o, NULL);
+ PyNumberMethods *m;
+
+ if (o == NULL)
+ return null_error();
+ m = o->ob_type->tp_as_number;
+ if (m && m->nb_float) { /* This should include subclasses of float */
+ PyObject *res = m->nb_float(o);
+ if (res && !PyFloat_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "__float__ returned non-float (type %.200s)",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
+ }
+ if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
+ PyFloatObject *po = (PyFloatObject *)o;
+ return PyFloat_FromDouble(po->ob_fval);
+ }
+ return PyFloat_FromString(o, NULL);
}
PyObject *
PyNumber_ToBase(PyObject *n, int base)
{
- PyObject *res = NULL;
- PyObject *index = PyNumber_Index(n);
+ PyObject *res = NULL;
+ PyObject *index = PyNumber_Index(n);
- if (!index)
- return NULL;
- if (PyLong_Check(index))
- res = _PyLong_Format(index, base, 0, 1);
- else if (PyInt_Check(index))
- res = _PyInt_Format((PyIntObject*)index, base, 1);
- else
- /* It should not be possible to get here, as
- PyNumber_Index already has a check for the same
- condition */
- PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
- "int or long");
- Py_DECREF(index);
- return res;
+ if (!index)
+ return NULL;
+ if (PyLong_Check(index))
+ res = _PyLong_Format(index, base, 0, 1);
+ else if (PyInt_Check(index))
+ res = _PyInt_Format((PyIntObject*)index, base, 1);
+ else
+ /* It should not be possible to get here, as
+ PyNumber_Index already has a check for the same
+ condition */
+ PyErr_SetString(PyExc_ValueError, "PyNumber_ToBase: index not "
+ "int or long");
+ Py_DECREF(index);
+ return res;
}
@@ -1833,544 +1833,544 @@ PyNumber_ToBase(PyObject *n, int base)
int
PySequence_Check(PyObject *s)
{
- if (s == NULL)
- return 0;
- if (PyInstance_Check(s))
- return PyObject_HasAttrString(s, "__getitem__");
- if (PyDict_Check(s))
- return 0;
- return s->ob_type->tp_as_sequence &&
- s->ob_type->tp_as_sequence->sq_item != NULL;
+ if (s == NULL)
+ return 0;
+ if (PyInstance_Check(s))
+ return PyObject_HasAttrString(s, "__getitem__");
+ if (PyDict_Check(s))
+ return 0;
+ return s->ob_type->tp_as_sequence &&
+ s->ob_type->tp_as_sequence->sq_item != NULL;
}
Py_ssize_t
PySequence_Size(PyObject *s)
{
- PySequenceMethods *m;
+ PySequenceMethods *m;
- if (s == NULL) {
- null_error();
- return -1;
- }
+ if (s == NULL) {
+ null_error();
+ return -1;
+ }
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_length)
- return m->sq_length(s);
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_length)
+ return m->sq_length(s);
- type_error("object of type '%.200s' has no len()", s);
- return -1;
+ type_error("object of type '%.200s' has no len()", s);
+ return -1;
}
#undef PySequence_Length
Py_ssize_t
PySequence_Length(PyObject *s)
{
- return PySequence_Size(s);
+ return PySequence_Size(s);
}
#define PySequence_Length PySequence_Size
PyObject *
PySequence_Concat(PyObject *s, PyObject *o)
{
- PySequenceMethods *m;
+ PySequenceMethods *m;
- if (s == NULL || o == NULL)
- return null_error();
+ if (s == NULL || o == NULL)
+ return null_error();
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_concat)
- return m->sq_concat(s, o);
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_concat)
+ return m->sq_concat(s, o);
- /* Instances of user classes defining an __add__() method only
- have an nb_add slot, not an sq_concat slot. So we fall back
- to nb_add if both arguments appear to be sequences. */
- if (PySequence_Check(s) && PySequence_Check(o)) {
- PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
- if (result != Py_NotImplemented)
- return result;
- Py_DECREF(result);
- }
- return type_error("'%.200s' object can't be concatenated", s);
+ /* Instances of user classes defining an __add__() method only
+ have an nb_add slot, not an sq_concat slot. So we fall back
+ to nb_add if both arguments appear to be sequences. */
+ if (PySequence_Check(s) && PySequence_Check(o)) {
+ PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
+ if (result != Py_NotImplemented)
+ return result;
+ Py_DECREF(result);
+ }
+ return type_error("'%.200s' object can't be concatenated", s);
}
PyObject *
PySequence_Repeat(PyObject *o, Py_ssize_t count)
{
- PySequenceMethods *m;
-
- if (o == NULL)
- return null_error();
-
- m = o->ob_type->tp_as_sequence;
- if (m && m->sq_repeat)
- return m->sq_repeat(o, count);
-
- /* Instances of user classes defining a __mul__() method only
- have an nb_multiply slot, not an sq_repeat slot. so we fall back
- to nb_multiply if o appears to be a sequence. */
- if (PySequence_Check(o)) {
- PyObject *n, *result;
- n = PyInt_FromSsize_t(count);
- if (n == NULL)
- return NULL;
- result = binary_op1(o, n, NB_SLOT(nb_multiply));
- Py_DECREF(n);
- if (result != Py_NotImplemented)
- return result;
- Py_DECREF(result);
- }
- return type_error("'%.200s' object can't be repeated", o);
+ PySequenceMethods *m;
+
+ if (o == NULL)
+ return null_error();
+
+ m = o->ob_type->tp_as_sequence;
+ if (m && m->sq_repeat)
+ return m->sq_repeat(o, count);
+
+ /* Instances of user classes defining a __mul__() method only
+ have an nb_multiply slot, not an sq_repeat slot. so we fall back
+ to nb_multiply if o appears to be a sequence. */
+ if (PySequence_Check(o)) {
+ PyObject *n, *result;
+ n = PyInt_FromSsize_t(count);
+ if (n == NULL)
+ return NULL;
+ result = binary_op1(o, n, NB_SLOT(nb_multiply));
+ Py_DECREF(n);
+ if (result != Py_NotImplemented)
+ return result;
+ Py_DECREF(result);
+ }
+ return type_error("'%.200s' object can't be repeated", o);
}
PyObject *
PySequence_InPlaceConcat(PyObject *s, PyObject *o)
{
- PySequenceMethods *m;
+ PySequenceMethods *m;
- if (s == NULL || o == NULL)
- return null_error();
+ if (s == NULL || o == NULL)
+ return null_error();
- m = s->ob_type->tp_as_sequence;
- if (m && HASINPLACE(s) && m->sq_inplace_concat)
- return m->sq_inplace_concat(s, o);
- if (m && m->sq_concat)
- return m->sq_concat(s, o);
+ m = s->ob_type->tp_as_sequence;
+ if (m && HASINPLACE(s) && m->sq_inplace_concat)
+ return m->sq_inplace_concat(s, o);
+ if (m && m->sq_concat)
+ return m->sq_concat(s, o);
- if (PySequence_Check(s) && PySequence_Check(o)) {
- PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
- NB_SLOT(nb_add));
- if (result != Py_NotImplemented)
- return result;
- Py_DECREF(result);
- }
- return type_error("'%.200s' object can't be concatenated", s);
+ if (PySequence_Check(s) && PySequence_Check(o)) {
+ PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
+ NB_SLOT(nb_add));
+ if (result != Py_NotImplemented)
+ return result;
+ Py_DECREF(result);
+ }
+ return type_error("'%.200s' object can't be concatenated", s);
}
PyObject *
PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
{
- PySequenceMethods *m;
-
- if (o == NULL)
- return null_error();
-
- m = o->ob_type->tp_as_sequence;
- if (m && HASINPLACE(o) && m->sq_inplace_repeat)
- return m->sq_inplace_repeat(o, count);
- if (m && m->sq_repeat)
- return m->sq_repeat(o, count);
-
- if (PySequence_Check(o)) {
- PyObject *n, *result;
- n = PyInt_FromSsize_t(count);
- if (n == NULL)
- return NULL;
- result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
- NB_SLOT(nb_multiply));
- Py_DECREF(n);
- if (result != Py_NotImplemented)
- return result;
- Py_DECREF(result);
- }
- return type_error("'%.200s' object can't be repeated", o);
+ PySequenceMethods *m;
+
+ if (o == NULL)
+ return null_error();
+
+ m = o->ob_type->tp_as_sequence;
+ if (m && HASINPLACE(o) && m->sq_inplace_repeat)
+ return m->sq_inplace_repeat(o, count);
+ if (m && m->sq_repeat)
+ return m->sq_repeat(o, count);
+
+ if (PySequence_Check(o)) {
+ PyObject *n, *result;
+ n = PyInt_FromSsize_t(count);
+ if (n == NULL)
+ return NULL;
+ result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
+ NB_SLOT(nb_multiply));
+ Py_DECREF(n);
+ if (result != Py_NotImplemented)
+ return result;
+ Py_DECREF(result);
+ }
+ return type_error("'%.200s' object can't be repeated", o);
}
PyObject *
PySequence_GetItem(PyObject *s, Py_ssize_t i)
{
- PySequenceMethods *m;
-
- if (s == NULL)
- return null_error();
-
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_item) {
- if (i < 0) {
- if (m->sq_length) {
- Py_ssize_t l = (*m->sq_length)(s);
- if (l < 0)
- return NULL;
- i += l;
- }
- }
- return m->sq_item(s, i);
- }
+ PySequenceMethods *m;
+
+ if (s == NULL)
+ return null_error();
+
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_item) {
+ if (i < 0) {
+ if (m->sq_length) {
+ Py_ssize_t l = (*m->sq_length)(s);
+ if (l < 0)
+ return NULL;
+ i += l;
+ }
+ }
+ return m->sq_item(s, i);
+ }
- return type_error("'%.200s' object does not support indexing", s);
+ return type_error("'%.200s' object does not support indexing", s);
}
PyObject *
PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
{
- PySequenceMethods *m;
- PyMappingMethods *mp;
-
- if (!s) return null_error();
-
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_slice) {
- if (i1 < 0 || i2 < 0) {
- if (m->sq_length) {
- Py_ssize_t l = (*m->sq_length)(s);
- if (l < 0)
- return NULL;
- if (i1 < 0)
- i1 += l;
- if (i2 < 0)
- i2 += l;
- }
- }
- return m->sq_slice(s, i1, i2);
- } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
- PyObject *res;
- PyObject *slice = _PySlice_FromIndices(i1, i2);
- if (!slice)
- return NULL;
- res = mp->mp_subscript(s, slice);
- Py_DECREF(slice);
- return res;
- }
-
- return type_error("'%.200s' object is unsliceable", s);
+ PySequenceMethods *m;
+ PyMappingMethods *mp;
+
+ if (!s) return null_error();
+
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_slice) {
+ if (i1 < 0 || i2 < 0) {
+ if (m->sq_length) {
+ Py_ssize_t l = (*m->sq_length)(s);
+ if (l < 0)
+ return NULL;
+ if (i1 < 0)
+ i1 += l;
+ if (i2 < 0)
+ i2 += l;
+ }
+ }
+ return m->sq_slice(s, i1, i2);
+ } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_subscript) {
+ PyObject *res;
+ PyObject *slice = _PySlice_FromIndices(i1, i2);
+ if (!slice)
+ return NULL;
+ res = mp->mp_subscript(s, slice);
+ Py_DECREF(slice);
+ return res;
+ }
+
+ return type_error("'%.200s' object is unsliceable", s);
}
int
PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
{
- PySequenceMethods *m;
+ PySequenceMethods *m;
- if (s == NULL) {
- null_error();
- return -1;
- }
+ if (s == NULL) {
+ null_error();
+ return -1;
+ }
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_ass_item) {
- if (i < 0) {
- if (m->sq_length) {
- Py_ssize_t l = (*m->sq_length)(s);
- if (l < 0)
- return -1;
- i += l;
- }
- }
- return m->sq_ass_item(s, i, o);
- }
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_ass_item) {
+ if (i < 0) {
+ if (m->sq_length) {
+ Py_ssize_t l = (*m->sq_length)(s);
+ if (l < 0)
+ return -1;
+ i += l;
+ }
+ }
+ return m->sq_ass_item(s, i, o);
+ }
- type_error("'%.200s' object does not support item assignment", s);
- return -1;
+ type_error("'%.200s' object does not support item assignment", s);
+ return -1;
}
int
PySequence_DelItem(PyObject *s, Py_ssize_t i)
{
- PySequenceMethods *m;
+ PySequenceMethods *m;
- if (s == NULL) {
- null_error();
- return -1;
- }
+ if (s == NULL) {
+ null_error();
+ return -1;
+ }
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_ass_item) {
- if (i < 0) {
- if (m->sq_length) {
- Py_ssize_t l = (*m->sq_length)(s);
- if (l < 0)
- return -1;
- i += l;
- }
- }
- return m->sq_ass_item(s, i, (PyObject *)NULL);
- }
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_ass_item) {
+ if (i < 0) {
+ if (m->sq_length) {
+ Py_ssize_t l = (*m->sq_length)(s);
+ if (l < 0)
+ return -1;
+ i += l;
+ }
+ }
+ return m->sq_ass_item(s, i, (PyObject *)NULL);
+ }
- type_error("'%.200s' object doesn't support item deletion", s);
- return -1;
+ type_error("'%.200s' object doesn't support item deletion", s);
+ return -1;
}
int
PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
{
- PySequenceMethods *m;
- PyMappingMethods *mp;
-
- if (s == NULL) {
- null_error();
- return -1;
- }
-
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_ass_slice) {
- if (i1 < 0 || i2 < 0) {
- if (m->sq_length) {
- Py_ssize_t l = (*m->sq_length)(s);
- if (l < 0)
- return -1;
- if (i1 < 0)
- i1 += l;
- if (i2 < 0)
- i2 += l;
- }
- }
- return m->sq_ass_slice(s, i1, i2, o);
- } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
- int res;
- PyObject *slice = _PySlice_FromIndices(i1, i2);
- if (!slice)
- return -1;
- res = mp->mp_ass_subscript(s, slice, o);
- Py_DECREF(slice);
- return res;
- }
-
- type_error("'%.200s' object doesn't support slice assignment", s);
- return -1;
+ PySequenceMethods *m;
+ PyMappingMethods *mp;
+
+ if (s == NULL) {
+ null_error();
+ return -1;
+ }
+
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_ass_slice) {
+ if (i1 < 0 || i2 < 0) {
+ if (m->sq_length) {
+ Py_ssize_t l = (*m->sq_length)(s);
+ if (l < 0)
+ return -1;
+ if (i1 < 0)
+ i1 += l;
+ if (i2 < 0)
+ i2 += l;
+ }
+ }
+ return m->sq_ass_slice(s, i1, i2, o);
+ } else if ((mp = s->ob_type->tp_as_mapping) && mp->mp_ass_subscript) {
+ int res;
+ PyObject *slice = _PySlice_FromIndices(i1, i2);
+ if (!slice)
+ return -1;
+ res = mp->mp_ass_subscript(s, slice, o);
+ Py_DECREF(slice);
+ return res;
+ }
+
+ type_error("'%.200s' object doesn't support slice assignment", s);
+ return -1;
}
int
PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
{
- PySequenceMethods *m;
-
- if (s == NULL) {
- null_error();
- return -1;
- }
-
- m = s->ob_type->tp_as_sequence;
- if (m && m->sq_ass_slice) {
- if (i1 < 0 || i2 < 0) {
- if (m->sq_length) {
- Py_ssize_t l = (*m->sq_length)(s);
- if (l < 0)
- return -1;
- if (i1 < 0)
- i1 += l;
- if (i2 < 0)
- i2 += l;
- }
- }
- return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
- }
- type_error("'%.200s' object doesn't support slice deletion", s);
- return -1;
+ PySequenceMethods *m;
+
+ if (s == NULL) {
+ null_error();
+ return -1;
+ }
+
+ m = s->ob_type->tp_as_sequence;
+ if (m && m->sq_ass_slice) {
+ if (i1 < 0 || i2 < 0) {
+ if (m->sq_length) {
+ Py_ssize_t l = (*m->sq_length)(s);
+ if (l < 0)
+ return -1;
+ if (i1 < 0)
+ i1 += l;
+ if (i2 < 0)
+ i2 += l;
+ }
+ }
+ return m->sq_ass_slice(s, i1, i2, (PyObject *)NULL);
+ }
+ type_error("'%.200s' object doesn't support slice deletion", s);
+ return -1;
}
PyObject *
PySequence_Tuple(PyObject *v)
{
- PyObject *it; /* iter(v) */
- Py_ssize_t n; /* guess for result tuple size */
- PyObject *result = NULL;
- Py_ssize_t j;
-
- if (v == NULL)
- return null_error();
-
- /* Special-case the common tuple and list cases, for efficiency. */
- if (PyTuple_CheckExact(v)) {
- /* Note that we can't know whether it's safe to return
- a tuple *subclass* instance as-is, hence the restriction
- to exact tuples here. In contrast, lists always make
- a copy, so there's no need for exactness below. */
- Py_INCREF(v);
- return v;
- }
- if (PyList_Check(v))
- return PyList_AsTuple(v);
-
- /* Get iterator. */
- it = PyObject_GetIter(v);
- if (it == NULL)
- return NULL;
-
- /* Guess result size and allocate space. */
- n = _PyObject_LengthHint(v, 10);
- if (n == -1)
- goto Fail;
- result = PyTuple_New(n);
- if (result == NULL)
- goto Fail;
-
- /* Fill the tuple. */
- for (j = 0; ; ++j) {
- PyObject *item = PyIter_Next(it);
- if (item == NULL) {
- if (PyErr_Occurred())
- goto Fail;
- break;
- }
- if (j >= n) {
- Py_ssize_t oldn = n;
- /* The over-allocation strategy can grow a bit faster
- than for lists because unlike lists the
- over-allocation isn't permanent -- we reclaim
- the excess before the end of this routine.
- So, grow by ten and then add 25%.
- */
- n += 10;
- n += n >> 2;
- if (n < oldn) {
- /* Check for overflow */
- PyErr_NoMemory();
- Py_DECREF(item);
- goto Fail;
- }
- if (_PyTuple_Resize(&result, n) != 0) {
- Py_DECREF(item);
- goto Fail;
- }
- }
- PyTuple_SET_ITEM(result, j, item);
- }
-
- /* Cut tuple back if guess was too large. */
- if (j < n &&
- _PyTuple_Resize(&result, j) != 0)
- goto Fail;
-
- Py_DECREF(it);
- return result;
+ PyObject *it; /* iter(v) */
+ Py_ssize_t n; /* guess for result tuple size */
+ PyObject *result = NULL;
+ Py_ssize_t j;
+
+ if (v == NULL)
+ return null_error();
+
+ /* Special-case the common tuple and list cases, for efficiency. */
+ if (PyTuple_CheckExact(v)) {
+ /* Note that we can't know whether it's safe to return
+ a tuple *subclass* instance as-is, hence the restriction
+ to exact tuples here. In contrast, lists always make
+ a copy, so there's no need for exactness below. */
+ Py_INCREF(v);
+ return v;
+ }
+ if (PyList_Check(v))
+ return PyList_AsTuple(v);
+
+ /* Get iterator. */
+ it = PyObject_GetIter(v);
+ if (it == NULL)
+ return NULL;
+
+ /* Guess result size and allocate space. */
+ n = _PyObject_LengthHint(v, 10);
+ if (n == -1)
+ goto Fail;
+ result = PyTuple_New(n);
+ if (result == NULL)
+ goto Fail;
+
+ /* Fill the tuple. */
+ for (j = 0; ; ++j) {
+ PyObject *item = PyIter_Next(it);
+ if (item == NULL) {
+ if (PyErr_Occurred())
+ goto Fail;
+ break;
+ }
+ if (j >= n) {
+ Py_ssize_t oldn = n;
+ /* The over-allocation strategy can grow a bit faster
+ than for lists because unlike lists the
+ over-allocation isn't permanent -- we reclaim
+ the excess before the end of this routine.
+ So, grow by ten and then add 25%.
+ */
+ n += 10;
+ n += n >> 2;
+ if (n < oldn) {
+ /* Check for overflow */
+ PyErr_NoMemory();
+ Py_DECREF(item);
+ goto Fail;
+ }
+ if (_PyTuple_Resize(&result, n) != 0) {
+ Py_DECREF(item);
+ goto Fail;
+ }
+ }
+ PyTuple_SET_ITEM(result, j, item);
+ }
+
+ /* Cut tuple back if guess was too large. */
+ if (j < n &&
+ _PyTuple_Resize(&result, j) != 0)
+ goto Fail;
+
+ Py_DECREF(it);
+ return result;
Fail:
- Py_XDECREF(result);
- Py_DECREF(it);
- return NULL;
+ Py_XDECREF(result);
+ Py_DECREF(it);
+ return NULL;
}
PyObject *
PySequence_List(PyObject *v)
{
- PyObject *result; /* result list */
- PyObject *rv; /* return value from PyList_Extend */
+ PyObject *result; /* result list */
+ PyObject *rv; /* return value from PyList_Extend */
- if (v == NULL)
- return null_error();
+ if (v == NULL)
+ return null_error();
- result = PyList_New(0);
- if (result == NULL)
- return NULL;
+ result = PyList_New(0);
+ if (result == NULL)
+ return NULL;
- rv = _PyList_Extend((PyListObject *)result, v);
- if (rv == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(rv);
- return result;
+ rv = _PyList_Extend((PyListObject *)result, v);
+ if (rv == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(rv);
+ return result;
}
PyObject *
PySequence_Fast(PyObject *v, const char *m)
{
- PyObject *it;
+ PyObject *it;
- if (v == NULL)
- return null_error();
+ if (v == NULL)
+ return null_error();
- if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
- Py_INCREF(v);
- return v;
- }
+ if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
+ Py_INCREF(v);
+ return v;
+ }
- it = PyObject_GetIter(v);
- if (it == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_SetString(PyExc_TypeError, m);
- return NULL;
- }
+ it = PyObject_GetIter(v);
+ if (it == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_SetString(PyExc_TypeError, m);
+ return NULL;
+ }
- v = PySequence_List(it);
- Py_DECREF(it);
+ v = PySequence_List(it);
+ Py_DECREF(it);
- return v;
+ return v;
}
/* Iterate over seq. Result depends on the operation:
PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
- set ValueError and return -1 if none found; also return -1 on error.
+ set ValueError and return -1 if none found; also return -1 on error.
Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
*/
Py_ssize_t
_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
{
- Py_ssize_t n;
- int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
- PyObject *it; /* iter(seq) */
-
- if (seq == NULL || obj == NULL) {
- null_error();
- return -1;
- }
-
- it = PyObject_GetIter(seq);
- if (it == NULL) {
- type_error("argument of type '%.200s' is not iterable", seq);
- return -1;
- }
-
- n = wrapped = 0;
- for (;;) {
- int cmp;
- PyObject *item = PyIter_Next(it);
- if (item == NULL) {
- if (PyErr_Occurred())
- goto Fail;
- break;
- }
-
- cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
- Py_DECREF(item);
- if (cmp < 0)
- goto Fail;
- if (cmp > 0) {
- switch (operation) {
- case PY_ITERSEARCH_COUNT:
- if (n == PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "count exceeds C integer size");
- goto Fail;
- }
- ++n;
- break;
-
- case PY_ITERSEARCH_INDEX:
- if (wrapped) {
- PyErr_SetString(PyExc_OverflowError,
- "index exceeds C integer size");
- goto Fail;
- }
- goto Done;
-
- case PY_ITERSEARCH_CONTAINS:
- n = 1;
- goto Done;
-
- default:
- assert(!"unknown operation");
- }
- }
-
- if (operation == PY_ITERSEARCH_INDEX) {
- if (n == PY_SSIZE_T_MAX)
- wrapped = 1;
- ++n;
- }
- }
-
- if (operation != PY_ITERSEARCH_INDEX)
- goto Done;
-
- PyErr_SetString(PyExc_ValueError,
- "sequence.index(x): x not in sequence");
- /* fall into failure code */
+ Py_ssize_t n;
+ int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
+ PyObject *it; /* iter(seq) */
+
+ if (seq == NULL || obj == NULL) {
+ null_error();
+ return -1;
+ }
+
+ it = PyObject_GetIter(seq);
+ if (it == NULL) {
+ type_error("argument of type '%.200s' is not iterable", seq);
+ return -1;
+ }
+
+ n = wrapped = 0;
+ for (;;) {
+ int cmp;
+ PyObject *item = PyIter_Next(it);
+ if (item == NULL) {
+ if (PyErr_Occurred())
+ goto Fail;
+ break;
+ }
+
+ cmp = PyObject_RichCompareBool(obj, item, Py_EQ);
+ Py_DECREF(item);
+ if (cmp < 0)
+ goto Fail;
+ if (cmp > 0) {
+ switch (operation) {
+ case PY_ITERSEARCH_COUNT:
+ if (n == PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "count exceeds C integer size");
+ goto Fail;
+ }
+ ++n;
+ break;
+
+ case PY_ITERSEARCH_INDEX:
+ if (wrapped) {
+ PyErr_SetString(PyExc_OverflowError,
+ "index exceeds C integer size");
+ goto Fail;
+ }
+ goto Done;
+
+ case PY_ITERSEARCH_CONTAINS:
+ n = 1;
+ goto Done;
+
+ default:
+ assert(!"unknown operation");
+ }
+ }
+
+ if (operation == PY_ITERSEARCH_INDEX) {
+ if (n == PY_SSIZE_T_MAX)
+ wrapped = 1;
+ ++n;
+ }
+ }
+
+ if (operation != PY_ITERSEARCH_INDEX)
+ goto Done;
+
+ PyErr_SetString(PyExc_ValueError,
+ "sequence.index(x): x not in sequence");
+ /* fall into failure code */
Fail:
- n = -1;
- /* fall through */
+ n = -1;
+ /* fall through */
Done:
- Py_DECREF(it);
- return n;
+ Py_DECREF(it);
+ return n;
}
@@ -2378,7 +2378,7 @@ Done:
Py_ssize_t
PySequence_Count(PyObject *s, PyObject *o)
{
- return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
+ return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
}
/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
@@ -2387,14 +2387,14 @@ PySequence_Count(PyObject *s, PyObject *o)
int
PySequence_Contains(PyObject *seq, PyObject *ob)
{
- Py_ssize_t result;
- if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
- PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
- if (sqm != NULL && sqm->sq_contains != NULL)
- return (*sqm->sq_contains)(seq, ob);
- }
- result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
- return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
+ Py_ssize_t result;
+ if (PyType_HasFeature(seq->ob_type, Py_TPFLAGS_HAVE_SEQUENCE_IN)) {
+ PySequenceMethods *sqm = seq->ob_type->tp_as_sequence;
+ if (sqm != NULL && sqm->sq_contains != NULL)
+ return (*sqm->sq_contains)(seq, ob);
+ }
+ result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
+ return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
}
/* Backwards compatibility */
@@ -2402,13 +2402,13 @@ PySequence_Contains(PyObject *seq, PyObject *ob)
int
PySequence_In(PyObject *w, PyObject *v)
{
- return PySequence_Contains(w, v);
+ return PySequence_Contains(w, v);
}
Py_ssize_t
PySequence_Index(PyObject *s, PyObject *o)
{
- return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
+ return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
}
/* Operations on mappings */
@@ -2416,102 +2416,102 @@ PySequence_Index(PyObject *s, PyObject *o)
int
PyMapping_Check(PyObject *o)
{
- if (o && PyInstance_Check(o))
- return PyObject_HasAttrString(o, "__getitem__");
+ if (o && PyInstance_Check(o))
+ return PyObject_HasAttrString(o, "__getitem__");
- return o && o->ob_type->tp_as_mapping &&
- o->ob_type->tp_as_mapping->mp_subscript &&
- !(o->ob_type->tp_as_sequence &&
- o->ob_type->tp_as_sequence->sq_slice);
+ return o && o->ob_type->tp_as_mapping &&
+ o->ob_type->tp_as_mapping->mp_subscript &&
+ !(o->ob_type->tp_as_sequence &&
+ o->ob_type->tp_as_sequence->sq_slice);
}
Py_ssize_t
PyMapping_Size(PyObject *o)
{
- PyMappingMethods *m;
+ PyMappingMethods *m;
- if (o == NULL) {
- null_error();
- return -1;
- }
+ if (o == NULL) {
+ null_error();
+ return -1;
+ }
- m = o->ob_type->tp_as_mapping;
- if (m && m->mp_length)
- return m->mp_length(o);
+ m = o->ob_type->tp_as_mapping;
+ if (m && m->mp_length)
+ return m->mp_length(o);
- type_error("object of type '%.200s' has no len()", o);
- return -1;
+ type_error("object of type '%.200s' has no len()", o);
+ return -1;
}
#undef PyMapping_Length
Py_ssize_t
PyMapping_Length(PyObject *o)
{
- return PyMapping_Size(o);
+ return PyMapping_Size(o);
}
#define PyMapping_Length PyMapping_Size
PyObject *
PyMapping_GetItemString(PyObject *o, char *key)
{
- PyObject *okey, *r;
+ PyObject *okey, *r;
- if (key == NULL)
- return null_error();
+ if (key == NULL)
+ return null_error();
- okey = PyString_FromString(key);
- if (okey == NULL)
- return NULL;
- r = PyObject_GetItem(o, okey);
- Py_DECREF(okey);
- return r;
+ okey = PyString_FromString(key);
+ if (okey == NULL)
+ return NULL;
+ r = PyObject_GetItem(o, okey);
+ Py_DECREF(okey);
+ return r;
}
int
PyMapping_SetItemString(PyObject *o, char *key, PyObject *value)
{
- PyObject *okey;
- int r;
+ PyObject *okey;
+ int r;
- if (key == NULL) {
- null_error();
- return -1;
- }
+ if (key == NULL) {
+ null_error();
+ return -1;
+ }
- okey = PyString_FromString(key);
- if (okey == NULL)
- return -1;
- r = PyObject_SetItem(o, okey, value);
- Py_DECREF(okey);
- return r;
+ okey = PyString_FromString(key);
+ if (okey == NULL)
+ return -1;
+ r = PyObject_SetItem(o, okey, value);
+ Py_DECREF(okey);
+ return r;
}
int
PyMapping_HasKeyString(PyObject *o, char *key)
{
- PyObject *v;
+ PyObject *v;
- v = PyMapping_GetItemString(o, key);
- if (v) {
- Py_DECREF(v);
- return 1;
- }
- PyErr_Clear();
- return 0;
+ v = PyMapping_GetItemString(o, key);
+ if (v) {
+ Py_DECREF(v);
+ return 1;
+ }
+ PyErr_Clear();
+ return 0;
}
int
PyMapping_HasKey(PyObject *o, PyObject *key)
{
- PyObject *v;
+ PyObject *v;
- v = PyObject_GetItem(o, key);
- if (v) {
- Py_DECREF(v);
- return 1;
- }
- PyErr_Clear();
- return 0;
+ v = PyObject_GetItem(o, key);
+ if (v) {
+ Py_DECREF(v);
+ return 1;
+ }
+ PyErr_Clear();
+ return 0;
}
/* Operations on callable objects */
@@ -2521,253 +2521,253 @@ PyMapping_HasKey(PyObject *o, PyObject *key)
PyObject *
PyObject_CallObject(PyObject *o, PyObject *a)
{
- return PyEval_CallObjectWithKeywords(o, a, NULL);
+ return PyEval_CallObjectWithKeywords(o, a, NULL);
}
PyObject *
PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw)
{
- ternaryfunc call;
-
- if ((call = func->ob_type->tp_call) != NULL) {
- PyObject *result;
- if (Py_EnterRecursiveCall(" while calling a Python object"))
- return NULL;
- result = (*call)(func, arg, kw);
- Py_LeaveRecursiveCall();
- if (result == NULL && !PyErr_Occurred())
- PyErr_SetString(
- PyExc_SystemError,
- "NULL result without error in PyObject_Call");
- return result;
- }
- PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
- func->ob_type->tp_name);
- return NULL;
+ ternaryfunc call;
+
+ if ((call = func->ob_type->tp_call) != NULL) {
+ PyObject *result;
+ if (Py_EnterRecursiveCall(" while calling a Python object"))
+ return NULL;
+ result = (*call)(func, arg, kw);
+ Py_LeaveRecursiveCall();
+ if (result == NULL && !PyErr_Occurred())
+ PyErr_SetString(
+ PyExc_SystemError,
+ "NULL result without error in PyObject_Call");
+ return result;
+ }
+ PyErr_Format(PyExc_TypeError, "'%.200s' object is not callable",
+ func->ob_type->tp_name);
+ return NULL;
}
static PyObject*
call_function_tail(PyObject *callable, PyObject *args)
{
- PyObject *retval;
+ PyObject *retval;
- if (args == NULL)
- return NULL;
+ if (args == NULL)
+ return NULL;
- if (!PyTuple_Check(args)) {
- PyObject *a;
+ if (!PyTuple_Check(args)) {
+ PyObject *a;
- a = PyTuple_New(1);
- if (a == NULL) {
- Py_DECREF(args);
- return NULL;
- }
- PyTuple_SET_ITEM(a, 0, args);
- args = a;
- }
- retval = PyObject_Call(callable, args, NULL);
+ a = PyTuple_New(1);
+ if (a == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(a, 0, args);
+ args = a;
+ }
+ retval = PyObject_Call(callable, args, NULL);
- Py_DECREF(args);
+ Py_DECREF(args);
- return retval;
+ return retval;
}
PyObject *
PyObject_CallFunction(PyObject *callable, char *format, ...)
{
- va_list va;
- PyObject *args;
+ va_list va;
+ PyObject *args;
- if (callable == NULL)
- return null_error();
+ if (callable == NULL)
+ return null_error();
- if (format && *format) {
- va_start(va, format);
- args = Py_VaBuildValue(format, va);
- va_end(va);
- }
- else
- args = PyTuple_New(0);
+ if (format && *format) {
+ va_start(va, format);
+ args = Py_VaBuildValue(format, va);
+ va_end(va);
+ }
+ else
+ args = PyTuple_New(0);
- return call_function_tail(callable, args);
+ return call_function_tail(callable, args);
}
PyObject *
_PyObject_CallFunction_SizeT(PyObject *callable, char *format, ...)
{
- va_list va;
- PyObject *args;
+ va_list va;
+ PyObject *args;
- if (callable == NULL)
- return null_error();
+ if (callable == NULL)
+ return null_error();
- if (format && *format) {
- va_start(va, format);
- args = _Py_VaBuildValue_SizeT(format, va);
- va_end(va);
- }
- else
- args = PyTuple_New(0);
+ if (format && *format) {
+ va_start(va, format);
+ args = _Py_VaBuildValue_SizeT(format, va);
+ va_end(va);
+ }
+ else
+ args = PyTuple_New(0);
- return call_function_tail(callable, args);
+ return call_function_tail(callable, args);
}
PyObject *
PyObject_CallMethod(PyObject *o, char *name, char *format, ...)
{
- va_list va;
- PyObject *args;
- PyObject *func = NULL;
- PyObject *retval = NULL;
+ va_list va;
+ PyObject *args;
+ PyObject *func = NULL;
+ PyObject *retval = NULL;
- if (o == NULL || name == NULL)
- return null_error();
+ if (o == NULL || name == NULL)
+ return null_error();
- func = PyObject_GetAttrString(o, name);
- if (func == NULL) {
- PyErr_SetString(PyExc_AttributeError, name);
- return 0;
- }
+ func = PyObject_GetAttrString(o, name);
+ if (func == NULL) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return 0;
+ }
- if (!PyCallable_Check(func)) {
- type_error("attribute of type '%.200s' is not callable", func);
- goto exit;
- }
+ if (!PyCallable_Check(func)) {
+ type_error("attribute of type '%.200s' is not callable", func);
+ goto exit;
+ }
- if (format && *format) {
- va_start(va, format);
- args = Py_VaBuildValue(format, va);
- va_end(va);
- }
- else
- args = PyTuple_New(0);
+ if (format && *format) {
+ va_start(va, format);
+ args = Py_VaBuildValue(format, va);
+ va_end(va);
+ }
+ else
+ args = PyTuple_New(0);
- retval = call_function_tail(func, args);
+ retval = call_function_tail(func, args);
exit:
- /* args gets consumed in call_function_tail */
- Py_XDECREF(func);
+ /* args gets consumed in call_function_tail */
+ Py_XDECREF(func);
- return retval;
+ return retval;
}
PyObject *
_PyObject_CallMethod_SizeT(PyObject *o, char *name, char *format, ...)
{
- va_list va;
- PyObject *args;
- PyObject *func = NULL;
- PyObject *retval = NULL;
+ va_list va;
+ PyObject *args;
+ PyObject *func = NULL;
+ PyObject *retval = NULL;
- if (o == NULL || name == NULL)
- return null_error();
+ if (o == NULL || name == NULL)
+ return null_error();
- func = PyObject_GetAttrString(o, name);
- if (func == NULL) {
- PyErr_SetString(PyExc_AttributeError, name);
- return 0;
- }
+ func = PyObject_GetAttrString(o, name);
+ if (func == NULL) {
+ PyErr_SetString(PyExc_AttributeError, name);
+ return 0;
+ }
- if (!PyCallable_Check(func)) {
- type_error("attribute of type '%.200s' is not callable", func);
- goto exit;
- }
+ if (!PyCallable_Check(func)) {
+ type_error("attribute of type '%.200s' is not callable", func);
+ goto exit;
+ }
- if (format && *format) {
- va_start(va, format);
- args = _Py_VaBuildValue_SizeT(format, va);
- va_end(va);
- }
- else
- args = PyTuple_New(0);
+ if (format && *format) {
+ va_start(va, format);
+ args = _Py_VaBuildValue_SizeT(format, va);
+ va_end(va);
+ }
+ else
+ args = PyTuple_New(0);
- retval = call_function_tail(func, args);
+ retval = call_function_tail(func, args);
exit:
- /* args gets consumed in call_function_tail */
- Py_XDECREF(func);
+ /* args gets consumed in call_function_tail */
+ Py_XDECREF(func);
- return retval;
+ return retval;
}
static PyObject *
objargs_mktuple(va_list va)
{
- int i, n = 0;
- va_list countva;
- PyObject *result, *tmp;
+ int i, n = 0;
+ va_list countva;
+ PyObject *result, *tmp;
#ifdef VA_LIST_IS_ARRAY
- memcpy(countva, va, sizeof(va_list));
+ memcpy(countva, va, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(countva, va);
+ __va_copy(countva, va);
#else
- countva = va;
+ countva = va;
#endif
#endif
- while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
- ++n;
- result = PyTuple_New(n);
- if (result != NULL && n > 0) {
- for (i = 0; i < n; ++i) {
- tmp = (PyObject *)va_arg(va, PyObject *);
- PyTuple_SET_ITEM(result, i, tmp);
- Py_INCREF(tmp);
- }
- }
- return result;
+ while (((PyObject *)va_arg(countva, PyObject *)) != NULL)
+ ++n;
+ result = PyTuple_New(n);
+ if (result != NULL && n > 0) {
+ for (i = 0; i < n; ++i) {
+ tmp = (PyObject *)va_arg(va, PyObject *);
+ PyTuple_SET_ITEM(result, i, tmp);
+ Py_INCREF(tmp);
+ }
+ }
+ return result;
}
PyObject *
PyObject_CallMethodObjArgs(PyObject *callable, PyObject *name, ...)
{
- PyObject *args, *tmp;
- va_list vargs;
+ PyObject *args, *tmp;
+ va_list vargs;
- if (callable == NULL || name == NULL)
- return null_error();
+ if (callable == NULL || name == NULL)
+ return null_error();
- callable = PyObject_GetAttr(callable, name);
- if (callable == NULL)
- return NULL;
+ callable = PyObject_GetAttr(callable, name);
+ if (callable == NULL)
+ return NULL;
- /* count the args */
- va_start(vargs, name);
- args = objargs_mktuple(vargs);
- va_end(vargs);
- if (args == NULL) {
- Py_DECREF(callable);
- return NULL;
- }
- tmp = PyObject_Call(callable, args, NULL);
- Py_DECREF(args);
- Py_DECREF(callable);
+ /* count the args */
+ va_start(vargs, name);
+ args = objargs_mktuple(vargs);
+ va_end(vargs);
+ if (args == NULL) {
+ Py_DECREF(callable);
+ return NULL;
+ }
+ tmp = PyObject_Call(callable, args, NULL);
+ Py_DECREF(args);
+ Py_DECREF(callable);
- return tmp;
+ return tmp;
}
PyObject *
PyObject_CallFunctionObjArgs(PyObject *callable, ...)
{
- PyObject *args, *tmp;
- va_list vargs;
+ PyObject *args, *tmp;
+ va_list vargs;
- if (callable == NULL)
- return null_error();
+ if (callable == NULL)
+ return null_error();
- /* count the args */
- va_start(vargs, callable);
- args = objargs_mktuple(vargs);
- va_end(vargs);
- if (args == NULL)
- return NULL;
- tmp = PyObject_Call(callable, args, NULL);
- Py_DECREF(args);
+ /* count the args */
+ va_start(vargs, callable);
+ args = objargs_mktuple(vargs);
+ va_end(vargs);
+ if (args == NULL)
+ return NULL;
+ tmp = PyObject_Call(callable, args, NULL);
+ Py_DECREF(args);
- return tmp;
+ return tmp;
}
@@ -2802,302 +2802,302 @@ PyObject_CallFunctionObjArgs(PyObject *callable, ...)
static PyObject *
abstract_get_bases(PyObject *cls)
{
- static PyObject *__bases__ = NULL;
- PyObject *bases;
+ static PyObject *__bases__ = NULL;
+ PyObject *bases;
- if (__bases__ == NULL) {
- __bases__ = PyString_InternFromString("__bases__");
- if (__bases__ == NULL)
- return NULL;
- }
- bases = PyObject_GetAttr(cls, __bases__);
- if (bases == NULL) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- return NULL;
- }
- if (!PyTuple_Check(bases)) {
- Py_DECREF(bases);
- return NULL;
- }
- return bases;
+ if (__bases__ == NULL) {
+ __bases__ = PyString_InternFromString("__bases__");
+ if (__bases__ == NULL)
+ return NULL;
+ }
+ bases = PyObject_GetAttr(cls, __bases__);
+ if (bases == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ return NULL;
+ }
+ if (!PyTuple_Check(bases)) {
+ Py_DECREF(bases);
+ return NULL;
+ }
+ return bases;
}
static int
abstract_issubclass(PyObject *derived, PyObject *cls)
{
- PyObject *bases = NULL;
- Py_ssize_t i, n;
- int r = 0;
-
- while (1) {
- if (derived == cls)
- return 1;
- bases = abstract_get_bases(derived);
- if (bases == NULL) {
- if (PyErr_Occurred())
- return -1;
- return 0;
- }
- n = PyTuple_GET_SIZE(bases);
- if (n == 0) {
- Py_DECREF(bases);
- return 0;
- }
- /* Avoid recursivity in the single inheritance case */
- if (n == 1) {
- derived = PyTuple_GET_ITEM(bases, 0);
- Py_DECREF(bases);
- continue;
- }
- for (i = 0; i < n; i++) {
- r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
- if (r != 0)
- break;
- }
- Py_DECREF(bases);
- return r;
- }
+ PyObject *bases = NULL;
+ Py_ssize_t i, n;
+ int r = 0;
+
+ while (1) {
+ if (derived == cls)
+ return 1;
+ bases = abstract_get_bases(derived);
+ if (bases == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ return 0;
+ }
+ n = PyTuple_GET_SIZE(bases);
+ if (n == 0) {
+ Py_DECREF(bases);
+ return 0;
+ }
+ /* Avoid recursivity in the single inheritance case */
+ if (n == 1) {
+ derived = PyTuple_GET_ITEM(bases, 0);
+ Py_DECREF(bases);
+ continue;
+ }
+ for (i = 0; i < n; i++) {
+ r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
+ if (r != 0)
+ break;
+ }
+ Py_DECREF(bases);
+ return r;
+ }
}
static int
check_class(PyObject *cls, const char *error)
{
- PyObject *bases = abstract_get_bases(cls);
- if (bases == NULL) {
- /* Do not mask errors. */
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_TypeError, error);
- return 0;
- }
- Py_DECREF(bases);
- return -1;
+ PyObject *bases = abstract_get_bases(cls);
+ if (bases == NULL) {
+ /* Do not mask errors. */
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_TypeError, error);
+ return 0;
+ }
+ Py_DECREF(bases);
+ return -1;
}
static int
recursive_isinstance(PyObject *inst, PyObject *cls)
{
- PyObject *icls;
- static PyObject *__class__ = NULL;
- int retval = 0;
-
- if (__class__ == NULL) {
- __class__ = PyString_InternFromString("__class__");
- if (__class__ == NULL)
- return -1;
- }
-
- if (PyClass_Check(cls) && PyInstance_Check(inst)) {
- PyObject *inclass =
- (PyObject*)((PyInstanceObject*)inst)->in_class;
- retval = PyClass_IsSubclass(inclass, cls);
- }
- else if (PyType_Check(cls)) {
- retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
- if (retval == 0) {
- PyObject *c = PyObject_GetAttr(inst, __class__);
- if (c == NULL) {
- PyErr_Clear();
- }
- else {
- if (c != (PyObject *)(inst->ob_type) &&
- PyType_Check(c))
- retval = PyType_IsSubtype(
- (PyTypeObject *)c,
- (PyTypeObject *)cls);
- Py_DECREF(c);
- }
- }
- }
- else {
- if (!check_class(cls,
- "isinstance() arg 2 must be a class, type,"
- " or tuple of classes and types"))
- return -1;
- icls = PyObject_GetAttr(inst, __class__);
- if (icls == NULL) {
- PyErr_Clear();
- retval = 0;
- }
- else {
- retval = abstract_issubclass(icls, cls);
- Py_DECREF(icls);
- }
- }
-
- return retval;
+ PyObject *icls;
+ static PyObject *__class__ = NULL;
+ int retval = 0;
+
+ if (__class__ == NULL) {
+ __class__ = PyString_InternFromString("__class__");
+ if (__class__ == NULL)
+ return -1;
+ }
+
+ if (PyClass_Check(cls) && PyInstance_Check(inst)) {
+ PyObject *inclass =
+ (PyObject*)((PyInstanceObject*)inst)->in_class;
+ retval = PyClass_IsSubclass(inclass, cls);
+ }
+ else if (PyType_Check(cls)) {
+ retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
+ if (retval == 0) {
+ PyObject *c = PyObject_GetAttr(inst, __class__);
+ if (c == NULL) {
+ PyErr_Clear();
+ }
+ else {
+ if (c != (PyObject *)(inst->ob_type) &&
+ PyType_Check(c))
+ retval = PyType_IsSubtype(
+ (PyTypeObject *)c,
+ (PyTypeObject *)cls);
+ Py_DECREF(c);
+ }
+ }
+ }
+ else {
+ if (!check_class(cls,
+ "isinstance() arg 2 must be a class, type,"
+ " or tuple of classes and types"))
+ return -1;
+ icls = PyObject_GetAttr(inst, __class__);
+ if (icls == NULL) {
+ PyErr_Clear();
+ retval = 0;
+ }
+ else {
+ retval = abstract_issubclass(icls, cls);
+ Py_DECREF(icls);
+ }
+ }
+
+ return retval;
}
int
PyObject_IsInstance(PyObject *inst, PyObject *cls)
{
- static PyObject *name = NULL;
-
- /* Quick test for an exact match */
- if (Py_TYPE(inst) == (PyTypeObject *)cls)
- return 1;
-
- if (PyTuple_Check(cls)) {
- Py_ssize_t i;
- Py_ssize_t n;
- int r = 0;
-
- if (Py_EnterRecursiveCall(" in __instancecheck__"))
- return -1;
- n = PyTuple_GET_SIZE(cls);
- for (i = 0; i < n; ++i) {
- PyObject *item = PyTuple_GET_ITEM(cls, i);
- r = PyObject_IsInstance(inst, item);
- if (r != 0)
- /* either found it, or got an error */
- break;
- }
- Py_LeaveRecursiveCall();
- return r;
- }
-
- if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
- PyObject *checker;
- checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
- if (checker != NULL) {
- PyObject *res;
- int ok = -1;
- if (Py_EnterRecursiveCall(" in __instancecheck__")) {
- Py_DECREF(checker);
- return ok;
- }
- res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
- Py_LeaveRecursiveCall();
- Py_DECREF(checker);
- if (res != NULL) {
- ok = PyObject_IsTrue(res);
- Py_DECREF(res);
- }
- return ok;
- }
- else if (PyErr_Occurred())
- return -1;
- }
- return recursive_isinstance(inst, cls);
+ static PyObject *name = NULL;
+
+ /* Quick test for an exact match */
+ if (Py_TYPE(inst) == (PyTypeObject *)cls)
+ return 1;
+
+ if (PyTuple_Check(cls)) {
+ Py_ssize_t i;
+ Py_ssize_t n;
+ int r = 0;
+
+ if (Py_EnterRecursiveCall(" in __instancecheck__"))
+ return -1;
+ n = PyTuple_GET_SIZE(cls);
+ for (i = 0; i < n; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(cls, i);
+ r = PyObject_IsInstance(inst, item);
+ if (r != 0)
+ /* either found it, or got an error */
+ break;
+ }
+ Py_LeaveRecursiveCall();
+ return r;
+ }
+
+ if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
+ PyObject *checker;
+ checker = _PyObject_LookupSpecial(cls, "__instancecheck__", &name);
+ if (checker != NULL) {
+ PyObject *res;
+ int ok = -1;
+ if (Py_EnterRecursiveCall(" in __instancecheck__")) {
+ Py_DECREF(checker);
+ return ok;
+ }
+ res = PyObject_CallFunctionObjArgs(checker, inst, NULL);
+ Py_LeaveRecursiveCall();
+ Py_DECREF(checker);
+ if (res != NULL) {
+ ok = PyObject_IsTrue(res);
+ Py_DECREF(res);
+ }
+ return ok;
+ }
+ else if (PyErr_Occurred())
+ return -1;
+ }
+ return recursive_isinstance(inst, cls);
}
static int
recursive_issubclass(PyObject *derived, PyObject *cls)
{
- int retval;
-
- if (PyType_Check(cls) && PyType_Check(derived)) {
- /* Fast path (non-recursive) */
- return PyType_IsSubtype(
- (PyTypeObject *)derived, (PyTypeObject *)cls);
- }
- if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
- if (!check_class(derived,
- "issubclass() arg 1 must be a class"))
- return -1;
-
- if (!check_class(cls,
- "issubclass() arg 2 must be a class"
- " or tuple of classes"))
- return -1;
- retval = abstract_issubclass(derived, cls);
- }
- else {
- /* shortcut */
- if (!(retval = (derived == cls)))
- retval = PyClass_IsSubclass(derived, cls);
- }
-
- return retval;
+ int retval;
+
+ if (PyType_Check(cls) && PyType_Check(derived)) {
+ /* Fast path (non-recursive) */
+ return PyType_IsSubtype(
+ (PyTypeObject *)derived, (PyTypeObject *)cls);
+ }
+ if (!PyClass_Check(derived) || !PyClass_Check(cls)) {
+ if (!check_class(derived,
+ "issubclass() arg 1 must be a class"))
+ return -1;
+
+ if (!check_class(cls,
+ "issubclass() arg 2 must be a class"
+ " or tuple of classes"))
+ return -1;
+ retval = abstract_issubclass(derived, cls);
+ }
+ else {
+ /* shortcut */
+ if (!(retval = (derived == cls)))
+ retval = PyClass_IsSubclass(derived, cls);
+ }
+
+ return retval;
}
int
PyObject_IsSubclass(PyObject *derived, PyObject *cls)
{
- static PyObject *name = NULL;
-
- if (PyTuple_Check(cls)) {
- Py_ssize_t i;
- Py_ssize_t n;
- int r = 0;
-
- if (Py_EnterRecursiveCall(" in __subclasscheck__"))
- return -1;
- n = PyTuple_GET_SIZE(cls);
- for (i = 0; i < n; ++i) {
- PyObject *item = PyTuple_GET_ITEM(cls, i);
- r = PyObject_IsSubclass(derived, item);
- if (r != 0)
- /* either found it, or got an error */
- break;
- }
- Py_LeaveRecursiveCall();
- return r;
- }
- if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
- PyObject *checker;
- checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
- if (checker != NULL) {
- PyObject *res;
- int ok = -1;
- if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
- Py_DECREF(checker);
- return ok;
- }
- res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
- Py_LeaveRecursiveCall();
- Py_DECREF(checker);
- if (res != NULL) {
- ok = PyObject_IsTrue(res);
- Py_DECREF(res);
- }
- return ok;
- }
- else if (PyErr_Occurred()) {
- return -1;
- }
- }
- return recursive_issubclass(derived, cls);
+ static PyObject *name = NULL;
+
+ if (PyTuple_Check(cls)) {
+ Py_ssize_t i;
+ Py_ssize_t n;
+ int r = 0;
+
+ if (Py_EnterRecursiveCall(" in __subclasscheck__"))
+ return -1;
+ n = PyTuple_GET_SIZE(cls);
+ for (i = 0; i < n; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(cls, i);
+ r = PyObject_IsSubclass(derived, item);
+ if (r != 0)
+ /* either found it, or got an error */
+ break;
+ }
+ Py_LeaveRecursiveCall();
+ return r;
+ }
+ if (!(PyClass_Check(cls) || PyInstance_Check(cls))) {
+ PyObject *checker;
+ checker = _PyObject_LookupSpecial(cls, "__subclasscheck__", &name);
+ if (checker != NULL) {
+ PyObject *res;
+ int ok = -1;
+ if (Py_EnterRecursiveCall(" in __subclasscheck__")) {
+ Py_DECREF(checker);
+ return ok;
+ }
+ res = PyObject_CallFunctionObjArgs(checker, derived, NULL);
+ Py_LeaveRecursiveCall();
+ Py_DECREF(checker);
+ if (res != NULL) {
+ ok = PyObject_IsTrue(res);
+ Py_DECREF(res);
+ }
+ return ok;
+ }
+ else if (PyErr_Occurred()) {
+ return -1;
+ }
+ }
+ return recursive_issubclass(derived, cls);
}
int
_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
{
- return recursive_isinstance(inst, cls);
+ return recursive_isinstance(inst, cls);
}
int
_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
{
- return recursive_issubclass(derived, cls);
+ return recursive_issubclass(derived, cls);
}
PyObject *
PyObject_GetIter(PyObject *o)
{
- PyTypeObject *t = o->ob_type;
- getiterfunc f = NULL;
- if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
- f = t->tp_iter;
- if (f == NULL) {
- if (PySequence_Check(o))
- return PySeqIter_New(o);
- return type_error("'%.200s' object is not iterable", o);
- }
- else {
- PyObject *res = (*f)(o);
- if (res != NULL && !PyIter_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "iter() returned non-iterator "
- "of type '%.100s'",
- res->ob_type->tp_name);
- Py_DECREF(res);
- res = NULL;
- }
- return res;
- }
+ PyTypeObject *t = o->ob_type;
+ getiterfunc f = NULL;
+ if (PyType_HasFeature(t, Py_TPFLAGS_HAVE_ITER))
+ f = t->tp_iter;
+ if (f == NULL) {
+ if (PySequence_Check(o))
+ return PySeqIter_New(o);
+ return type_error("'%.200s' object is not iterable", o);
+ }
+ else {
+ PyObject *res = (*f)(o);
+ if (res != NULL && !PyIter_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "iter() returned non-iterator "
+ "of type '%.100s'",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ res = NULL;
+ }
+ return res;
+ }
}
/* Return next item.
@@ -3110,11 +3110,11 @@ PyObject_GetIter(PyObject *o)
PyObject *
PyIter_Next(PyObject *iter)
{
- PyObject *result;
- result = (*iter->ob_type->tp_iternext)(iter);
- if (result == NULL &&
- PyErr_Occurred() &&
- PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- return result;
+ PyObject *result;
+ result = (*iter->ob_type->tp_iternext)(iter);
+ if (result == NULL &&
+ PyErr_Occurred() &&
+ PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ return result;
}
diff --git a/Objects/boolobject.c b/Objects/boolobject.c
index fd73d28..595832a 100644
--- a/Objects/boolobject.c
+++ b/Objects/boolobject.c
@@ -7,10 +7,10 @@
static int
bool_print(PyBoolObject *self, FILE *fp, int flags)
{
- Py_BEGIN_ALLOW_THREADS
- fputs(self->ob_ival == 0 ? "False" : "True", fp);
- Py_END_ALLOW_THREADS
- return 0;
+ Py_BEGIN_ALLOW_THREADS
+ fputs(self->ob_ival == 0 ? "False" : "True", fp);
+ Py_END_ALLOW_THREADS
+ return 0;
}
/* We define bool_repr to return "False" or "True" */
@@ -21,30 +21,30 @@ static PyObject *true_str = NULL;
static PyObject *
bool_repr(PyBoolObject *self)
{
- PyObject *s;
-
- if (self->ob_ival)
- s = true_str ? true_str :
- (true_str = PyString_InternFromString("True"));
- else
- s = false_str ? false_str :
- (false_str = PyString_InternFromString("False"));
- Py_XINCREF(s);
- return s;
+ PyObject *s;
+
+ if (self->ob_ival)
+ s = true_str ? true_str :
+ (true_str = PyString_InternFromString("True"));
+ else
+ s = false_str ? false_str :
+ (false_str = PyString_InternFromString("False"));
+ Py_XINCREF(s);
+ return s;
}
/* Function to return a bool from a C long */
PyObject *PyBool_FromLong(long ok)
{
- PyObject *result;
-
- if (ok)
- result = Py_True;
- else
- result = Py_False;
- Py_INCREF(result);
- return result;
+ PyObject *result;
+
+ if (ok)
+ result = Py_True;
+ else
+ result = Py_False;
+ Py_INCREF(result);
+ return result;
}
/* We define bool_new to always return either Py_True or Py_False */
@@ -52,16 +52,16 @@ PyObject *PyBool_FromLong(long ok)
static PyObject *
bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"x", 0};
- PyObject *x = Py_False;
- long ok;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x))
- return NULL;
- ok = PyObject_IsTrue(x);
- if (ok < 0)
- return NULL;
- return PyBool_FromLong(ok);
+ static char *kwlist[] = {"x", 0};
+ PyObject *x = Py_False;
+ long ok;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:bool", kwlist, &x))
+ return NULL;
+ ok = PyObject_IsTrue(x);
+ if (ok < 0)
+ return NULL;
+ return PyBool_FromLong(ok);
}
/* Arithmetic operations redefined to return bool if both args are bool. */
@@ -69,28 +69,28 @@ bool_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
bool_and(PyObject *a, PyObject *b)
{
- if (!PyBool_Check(a) || !PyBool_Check(b))
- return PyInt_Type.tp_as_number->nb_and(a, b);
- return PyBool_FromLong(
- ((PyBoolObject *)a)->ob_ival & ((PyBoolObject *)b)->ob_ival);
+ if (!PyBool_Check(a) || !PyBool_Check(b))
+ return PyInt_Type.tp_as_number->nb_and(a, b);
+ return PyBool_FromLong(
+ ((PyBoolObject *)a)->ob_ival & ((PyBoolObject *)b)->ob_ival);
}
static PyObject *
bool_or(PyObject *a, PyObject *b)
{
- if (!PyBool_Check(a) || !PyBool_Check(b))
- return PyInt_Type.tp_as_number->nb_or(a, b);
- return PyBool_FromLong(
- ((PyBoolObject *)a)->ob_ival | ((PyBoolObject *)b)->ob_ival);
+ if (!PyBool_Check(a) || !PyBool_Check(b))
+ return PyInt_Type.tp_as_number->nb_or(a, b);
+ return PyBool_FromLong(
+ ((PyBoolObject *)a)->ob_ival | ((PyBoolObject *)b)->ob_ival);
}
static PyObject *
bool_xor(PyObject *a, PyObject *b)
{
- if (!PyBool_Check(a) || !PyBool_Check(b))
- return PyInt_Type.tp_as_number->nb_xor(a, b);
- return PyBool_FromLong(
- ((PyBoolObject *)a)->ob_ival ^ ((PyBoolObject *)b)->ob_ival);
+ if (!PyBool_Check(a) || !PyBool_Check(b))
+ return PyInt_Type.tp_as_number->nb_xor(a, b);
+ return PyBool_FromLong(
+ ((PyBoolObject *)a)->ob_ival ^ ((PyBoolObject *)b)->ob_ival);
}
/* Doc string */
@@ -105,98 +105,98 @@ The class bool is a subclass of the class int, and cannot be subclassed.");
/* Arithmetic methods -- only so we can override &, |, ^. */
static PyNumberMethods bool_as_number = {
- 0, /* nb_add */
- 0, /* nb_subtract */
- 0, /* nb_multiply */
- 0, /* nb_divide */
- 0, /* nb_remainder */
- 0, /* nb_divmod */
- 0, /* nb_power */
- 0, /* nb_negative */
- 0, /* nb_positive */
- 0, /* nb_absolute */
- 0, /* nb_nonzero */
- 0, /* nb_invert */
- 0, /* nb_lshift */
- 0, /* nb_rshift */
- bool_and, /* nb_and */
- bool_xor, /* nb_xor */
- bool_or, /* nb_or */
- 0, /* nb_coerce */
- 0, /* nb_int */
- 0, /* nb_long */
- 0, /* nb_float */
- 0, /* nb_oct */
- 0, /* nb_hex */
- 0, /* nb_inplace_add */
- 0, /* nb_inplace_subtract */
- 0, /* nb_inplace_multiply */
- 0, /* nb_inplace_divide */
- 0, /* nb_inplace_remainder */
- 0, /* nb_inplace_power */
- 0, /* nb_inplace_lshift */
- 0, /* nb_inplace_rshift */
- 0, /* nb_inplace_and */
- 0, /* nb_inplace_xor */
- 0, /* nb_inplace_or */
- 0, /* nb_floor_divide */
- 0, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
+ 0, /* nb_add */
+ 0, /* nb_subtract */
+ 0, /* nb_multiply */
+ 0, /* nb_divide */
+ 0, /* nb_remainder */
+ 0, /* nb_divmod */
+ 0, /* nb_power */
+ 0, /* nb_negative */
+ 0, /* nb_positive */
+ 0, /* nb_absolute */
+ 0, /* nb_nonzero */
+ 0, /* nb_invert */
+ 0, /* nb_lshift */
+ 0, /* nb_rshift */
+ bool_and, /* nb_and */
+ bool_xor, /* nb_xor */
+ bool_or, /* nb_or */
+ 0, /* nb_coerce */
+ 0, /* nb_int */
+ 0, /* nb_long */
+ 0, /* nb_float */
+ 0, /* nb_oct */
+ 0, /* nb_hex */
+ 0, /* nb_inplace_add */
+ 0, /* nb_inplace_subtract */
+ 0, /* nb_inplace_multiply */
+ 0, /* nb_inplace_divide */
+ 0, /* nb_inplace_remainder */
+ 0, /* nb_inplace_power */
+ 0, /* nb_inplace_lshift */
+ 0, /* nb_inplace_rshift */
+ 0, /* nb_inplace_and */
+ 0, /* nb_inplace_xor */
+ 0, /* nb_inplace_or */
+ 0, /* nb_floor_divide */
+ 0, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
};
/* The type object for bool. Note that this cannot be subclassed! */
PyTypeObject PyBool_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "bool",
- sizeof(PyIntObject),
- 0,
- 0, /* tp_dealloc */
- (printfunc)bool_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)bool_repr, /* tp_repr */
- &bool_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)bool_repr, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
- bool_doc, /* 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 */
- &PyInt_Type, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- bool_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "bool",
+ sizeof(PyIntObject),
+ 0,
+ 0, /* tp_dealloc */
+ (printfunc)bool_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)bool_repr, /* tp_repr */
+ &bool_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)bool_repr, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES, /* tp_flags */
+ bool_doc, /* 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 */
+ &PyInt_Type, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ bool_new, /* tp_new */
};
/* The objects representing bool values False and True */
/* Named Zero for link-level compatibility */
PyIntObject _Py_ZeroStruct = {
- PyObject_HEAD_INIT(&PyBool_Type)
- 0
+ PyObject_HEAD_INIT(&PyBool_Type)
+ 0
};
PyIntObject _Py_TrueStruct = {
- PyObject_HEAD_INIT(&PyBool_Type)
- 1
+ PyObject_HEAD_INIT(&PyBool_Type)
+ 1
};
diff --git a/Objects/bufferobject.c b/Objects/bufferobject.c
index 5b08e1e..0f7e763 100644
--- a/Objects/bufferobject.c
+++ b/Objects/bufferobject.c
@@ -5,13 +5,13 @@
typedef struct {
- PyObject_HEAD
- PyObject *b_base;
- void *b_ptr;
- Py_ssize_t b_size;
- Py_ssize_t b_offset;
- int b_readonly;
- long b_hash;
+ PyObject_HEAD
+ PyObject *b_base;
+ void *b_ptr;
+ Py_ssize_t b_size;
+ Py_ssize_t b_offset;
+ int b_readonly;
+ long b_hash;
} PyBufferObject;
@@ -24,207 +24,207 @@ enum buffer_t {
static int
get_buf(PyBufferObject *self, void **ptr, Py_ssize_t *size,
- enum buffer_t buffer_type)
+ enum buffer_t buffer_type)
{
- if (self->b_base == NULL) {
- assert (ptr != NULL);
- *ptr = self->b_ptr;
- *size = self->b_size;
- }
- else {
- Py_ssize_t count, offset;
- readbufferproc proc = 0;
- PyBufferProcs *bp = self->b_base->ob_type->tp_as_buffer;
- if ((*bp->bf_getsegcount)(self->b_base, NULL) != 1) {
- PyErr_SetString(PyExc_TypeError,
- "single-segment buffer object expected");
- return 0;
- }
- if ((buffer_type == READ_BUFFER) ||
- ((buffer_type == ANY_BUFFER) && self->b_readonly))
- proc = bp->bf_getreadbuffer;
- else if ((buffer_type == WRITE_BUFFER) ||
- (buffer_type == ANY_BUFFER))
- proc = (readbufferproc)bp->bf_getwritebuffer;
- else if (buffer_type == CHAR_BUFFER) {
- if (!PyType_HasFeature(self->ob_type,
- Py_TPFLAGS_HAVE_GETCHARBUFFER)) {
- PyErr_SetString(PyExc_TypeError,
- "Py_TPFLAGS_HAVE_GETCHARBUFFER needed");
- return 0;
- }
- proc = (readbufferproc)bp->bf_getcharbuffer;
- }
- if (!proc) {
- char *buffer_type_name;
- switch (buffer_type) {
- case READ_BUFFER:
- buffer_type_name = "read";
- break;
- case WRITE_BUFFER:
- buffer_type_name = "write";
- break;
- case CHAR_BUFFER:
- buffer_type_name = "char";
- break;
- default:
- buffer_type_name = "no";
- break;
- }
- PyErr_Format(PyExc_TypeError,
- "%s buffer type not available",
- buffer_type_name);
- return 0;
- }
- if ((count = (*proc)(self->b_base, 0, ptr)) < 0)
- return 0;
- /* apply constraints to the start/end */
- if (self->b_offset > count)
- offset = count;
- else
- offset = self->b_offset;
- *(char **)ptr = *(char **)ptr + offset;
- if (self->b_size == Py_END_OF_BUFFER)
- *size = count;
- else
- *size = self->b_size;
- if (offset + *size > count)
- *size = count - offset;
- }
- return 1;
+ if (self->b_base == NULL) {
+ assert (ptr != NULL);
+ *ptr = self->b_ptr;
+ *size = self->b_size;
+ }
+ else {
+ Py_ssize_t count, offset;
+ readbufferproc proc = 0;
+ PyBufferProcs *bp = self->b_base->ob_type->tp_as_buffer;
+ if ((*bp->bf_getsegcount)(self->b_base, NULL) != 1) {
+ PyErr_SetString(PyExc_TypeError,
+ "single-segment buffer object expected");
+ return 0;
+ }
+ if ((buffer_type == READ_BUFFER) ||
+ ((buffer_type == ANY_BUFFER) && self->b_readonly))
+ proc = bp->bf_getreadbuffer;
+ else if ((buffer_type == WRITE_BUFFER) ||
+ (buffer_type == ANY_BUFFER))
+ proc = (readbufferproc)bp->bf_getwritebuffer;
+ else if (buffer_type == CHAR_BUFFER) {
+ if (!PyType_HasFeature(self->ob_type,
+ Py_TPFLAGS_HAVE_GETCHARBUFFER)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Py_TPFLAGS_HAVE_GETCHARBUFFER needed");
+ return 0;
+ }
+ proc = (readbufferproc)bp->bf_getcharbuffer;
+ }
+ if (!proc) {
+ char *buffer_type_name;
+ switch (buffer_type) {
+ case READ_BUFFER:
+ buffer_type_name = "read";
+ break;
+ case WRITE_BUFFER:
+ buffer_type_name = "write";
+ break;
+ case CHAR_BUFFER:
+ buffer_type_name = "char";
+ break;
+ default:
+ buffer_type_name = "no";
+ break;
+ }
+ PyErr_Format(PyExc_TypeError,
+ "%s buffer type not available",
+ buffer_type_name);
+ return 0;
+ }
+ if ((count = (*proc)(self->b_base, 0, ptr)) < 0)
+ return 0;
+ /* apply constraints to the start/end */
+ if (self->b_offset > count)
+ offset = count;
+ else
+ offset = self->b_offset;
+ *(char **)ptr = *(char **)ptr + offset;
+ if (self->b_size == Py_END_OF_BUFFER)
+ *size = count;
+ else
+ *size = self->b_size;
+ if (offset + *size > count)
+ *size = count - offset;
+ }
+ return 1;
}
static PyObject *
buffer_from_memory(PyObject *base, Py_ssize_t size, Py_ssize_t offset, void *ptr,
- int readonly)
+ int readonly)
{
- PyBufferObject * b;
-
- if (size < 0 && size != Py_END_OF_BUFFER) {
- PyErr_SetString(PyExc_ValueError,
- "size must be zero or positive");
- return NULL;
- }
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError,
- "offset must be zero or positive");
- return NULL;
- }
-
- b = PyObject_NEW(PyBufferObject, &PyBuffer_Type);
- if ( b == NULL )
- return NULL;
-
- Py_XINCREF(base);
- b->b_base = base;
- b->b_ptr = ptr;
- b->b_size = size;
- b->b_offset = offset;
- b->b_readonly = readonly;
- b->b_hash = -1;
-
- return (PyObject *) b;
+ PyBufferObject * b;
+
+ if (size < 0 && size != Py_END_OF_BUFFER) {
+ PyErr_SetString(PyExc_ValueError,
+ "size must be zero or positive");
+ return NULL;
+ }
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "offset must be zero or positive");
+ return NULL;
+ }
+
+ b = PyObject_NEW(PyBufferObject, &PyBuffer_Type);
+ if ( b == NULL )
+ return NULL;
+
+ Py_XINCREF(base);
+ b->b_base = base;
+ b->b_ptr = ptr;
+ b->b_size = size;
+ b->b_offset = offset;
+ b->b_readonly = readonly;
+ b->b_hash = -1;
+
+ return (PyObject *) b;
}
static PyObject *
buffer_from_object(PyObject *base, Py_ssize_t size, Py_ssize_t offset, int readonly)
{
- if (offset < 0) {
- PyErr_SetString(PyExc_ValueError,
- "offset must be zero or positive");
- return NULL;
- }
- if ( PyBuffer_Check(base) && (((PyBufferObject *)base)->b_base) ) {
- /* another buffer, refer to the base object */
- PyBufferObject *b = (PyBufferObject *)base;
- if (b->b_size != Py_END_OF_BUFFER) {
- Py_ssize_t base_size = b->b_size - offset;
- if (base_size < 0)
- base_size = 0;
- if (size == Py_END_OF_BUFFER || size > base_size)
- size = base_size;
- }
- offset += b->b_offset;
- base = b->b_base;
- }
- return buffer_from_memory(base, size, offset, NULL, readonly);
+ if (offset < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "offset must be zero or positive");
+ return NULL;
+ }
+ if ( PyBuffer_Check(base) && (((PyBufferObject *)base)->b_base) ) {
+ /* another buffer, refer to the base object */
+ PyBufferObject *b = (PyBufferObject *)base;
+ if (b->b_size != Py_END_OF_BUFFER) {
+ Py_ssize_t base_size = b->b_size - offset;
+ if (base_size < 0)
+ base_size = 0;
+ if (size == Py_END_OF_BUFFER || size > base_size)
+ size = base_size;
+ }
+ offset += b->b_offset;
+ base = b->b_base;
+ }
+ return buffer_from_memory(base, size, offset, NULL, readonly);
}
PyObject *
PyBuffer_FromObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
{
- PyBufferProcs *pb = base->ob_type->tp_as_buffer;
+ PyBufferProcs *pb = base->ob_type->tp_as_buffer;
- if ( pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL )
- {
- PyErr_SetString(PyExc_TypeError, "buffer object expected");
- return NULL;
- }
+ if ( pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL )
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer object expected");
+ return NULL;
+ }
- return buffer_from_object(base, size, offset, 1);
+ return buffer_from_object(base, size, offset, 1);
}
PyObject *
PyBuffer_FromReadWriteObject(PyObject *base, Py_ssize_t offset, Py_ssize_t size)
{
- PyBufferProcs *pb = base->ob_type->tp_as_buffer;
+ PyBufferProcs *pb = base->ob_type->tp_as_buffer;
- if ( pb == NULL ||
- pb->bf_getwritebuffer == NULL ||
- pb->bf_getsegcount == NULL )
- {
- PyErr_SetString(PyExc_TypeError, "buffer object expected");
- return NULL;
- }
+ if ( pb == NULL ||
+ pb->bf_getwritebuffer == NULL ||
+ pb->bf_getsegcount == NULL )
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer object expected");
+ return NULL;
+ }
- return buffer_from_object(base, size, offset, 0);
+ return buffer_from_object(base, size, offset, 0);
}
PyObject *
PyBuffer_FromMemory(void *ptr, Py_ssize_t size)
{
- return buffer_from_memory(NULL, size, 0, ptr, 1);
+ return buffer_from_memory(NULL, size, 0, ptr, 1);
}
PyObject *
PyBuffer_FromReadWriteMemory(void *ptr, Py_ssize_t size)
{
- return buffer_from_memory(NULL, size, 0, ptr, 0);
+ return buffer_from_memory(NULL, size, 0, ptr, 0);
}
PyObject *
PyBuffer_New(Py_ssize_t size)
{
- PyObject *o;
- PyBufferObject * b;
-
- if (size < 0) {
- PyErr_SetString(PyExc_ValueError,
- "size must be zero or positive");
- return NULL;
- }
- if (sizeof(*b) > PY_SSIZE_T_MAX - size) {
- /* unlikely */
- return PyErr_NoMemory();
- }
- /* Inline PyObject_New */
- o = (PyObject *)PyObject_MALLOC(sizeof(*b) + size);
- if ( o == NULL )
- return PyErr_NoMemory();
- b = (PyBufferObject *) PyObject_INIT(o, &PyBuffer_Type);
-
- b->b_base = NULL;
- b->b_ptr = (void *)(b + 1);
- b->b_size = size;
- b->b_offset = 0;
- b->b_readonly = 0;
- b->b_hash = -1;
-
- return o;
+ PyObject *o;
+ PyBufferObject * b;
+
+ if (size < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "size must be zero or positive");
+ return NULL;
+ }
+ if (sizeof(*b) > PY_SSIZE_T_MAX - size) {
+ /* unlikely */
+ return PyErr_NoMemory();
+ }
+ /* Inline PyObject_New */
+ o = (PyObject *)PyObject_MALLOC(sizeof(*b) + size);
+ if ( o == NULL )
+ return PyErr_NoMemory();
+ b = (PyBufferObject *) PyObject_INIT(o, &PyBuffer_Type);
+
+ b->b_base = NULL;
+ b->b_ptr = (void *)(b + 1);
+ b->b_size = size;
+ b->b_offset = 0;
+ b->b_readonly = 0;
+ b->b_hash = -1;
+
+ return o;
}
/* Methods */
@@ -232,19 +232,19 @@ PyBuffer_New(Py_ssize_t size)
static PyObject *
buffer_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *ob;
- Py_ssize_t offset = 0;
- Py_ssize_t size = Py_END_OF_BUFFER;
-
- if (PyErr_WarnPy3k("buffer() not supported in 3.x", 1) < 0)
- return NULL;
-
- if (!_PyArg_NoKeywords("buffer()", kw))
- return NULL;
-
- if (!PyArg_ParseTuple(args, "O|nn:buffer", &ob, &offset, &size))
- return NULL;
- return PyBuffer_FromObject(ob, offset, size);
+ PyObject *ob;
+ Py_ssize_t offset = 0;
+ Py_ssize_t size = Py_END_OF_BUFFER;
+
+ if (PyErr_WarnPy3k("buffer() not supported in 3.x", 1) < 0)
+ return NULL;
+
+ if (!_PyArg_NoKeywords("buffer()", kw))
+ return NULL;
+
+ if (!PyArg_ParseTuple(args, "O|nn:buffer", &ob, &offset, &size))
+ return NULL;
+ return PyBuffer_FromObject(ob, offset, size);
}
PyDoc_STRVAR(buffer_doc,
@@ -259,99 +259,99 @@ extend to the end of the target object (or with the specified size).");
static void
buffer_dealloc(PyBufferObject *self)
{
- Py_XDECREF(self->b_base);
- PyObject_DEL(self);
+ Py_XDECREF(self->b_base);
+ PyObject_DEL(self);
}
static int
buffer_compare(PyBufferObject *self, PyBufferObject *other)
{
- void *p1, *p2;
- Py_ssize_t len_self, len_other, min_len;
- int cmp;
-
- if (!get_buf(self, &p1, &len_self, ANY_BUFFER))
- return -1;
- if (!get_buf(other, &p2, &len_other, ANY_BUFFER))
- return -1;
- min_len = (len_self < len_other) ? len_self : len_other;
- if (min_len > 0) {
- cmp = memcmp(p1, p2, min_len);
- if (cmp != 0)
- return cmp < 0 ? -1 : 1;
- }
- return (len_self < len_other) ? -1 : (len_self > len_other) ? 1 : 0;
+ void *p1, *p2;
+ Py_ssize_t len_self, len_other, min_len;
+ int cmp;
+
+ if (!get_buf(self, &p1, &len_self, ANY_BUFFER))
+ return -1;
+ if (!get_buf(other, &p2, &len_other, ANY_BUFFER))
+ return -1;
+ min_len = (len_self < len_other) ? len_self : len_other;
+ if (min_len > 0) {
+ cmp = memcmp(p1, p2, min_len);
+ if (cmp != 0)
+ return cmp < 0 ? -1 : 1;
+ }
+ return (len_self < len_other) ? -1 : (len_self > len_other) ? 1 : 0;
}
static PyObject *
buffer_repr(PyBufferObject *self)
{
- const char *status = self->b_readonly ? "read-only" : "read-write";
-
- if ( self->b_base == NULL )
- return PyString_FromFormat("<%s buffer ptr %p, size %zd at %p>",
- status,
- self->b_ptr,
- self->b_size,
- self);
- else
- return PyString_FromFormat(
- "<%s buffer for %p, size %zd, offset %zd at %p>",
- status,
- self->b_base,
- self->b_size,
- self->b_offset,
- self);
+ const char *status = self->b_readonly ? "read-only" : "read-write";
+
+ if ( self->b_base == NULL )
+ return PyString_FromFormat("<%s buffer ptr %p, size %zd at %p>",
+ status,
+ self->b_ptr,
+ self->b_size,
+ self);
+ else
+ return PyString_FromFormat(
+ "<%s buffer for %p, size %zd, offset %zd at %p>",
+ status,
+ self->b_base,
+ self->b_size,
+ self->b_offset,
+ self);
}
static long
buffer_hash(PyBufferObject *self)
{
- void *ptr;
- Py_ssize_t size;
- register Py_ssize_t len;
- register unsigned char *p;
- register long x;
-
- if ( self->b_hash != -1 )
- return self->b_hash;
-
- /* XXX potential bugs here, a readonly buffer does not imply that the
- * underlying memory is immutable. b_readonly is a necessary but not
- * sufficient condition for a buffer to be hashable. Perhaps it would
- * be better to only allow hashing if the underlying object is known to
- * be immutable (e.g. PyString_Check() is true). Another idea would
- * be to call tp_hash on the underlying object and see if it raises
- * an error. */
- if ( !self->b_readonly )
- {
- PyErr_SetString(PyExc_TypeError,
- "writable buffers are not hashable");
- return -1;
- }
-
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return -1;
- p = (unsigned char *) ptr;
- len = size;
- x = *p << 7;
- while (--len >= 0)
- x = (1000003*x) ^ *p++;
- x ^= size;
- if (x == -1)
- x = -2;
- self->b_hash = x;
- return x;
+ void *ptr;
+ Py_ssize_t size;
+ register Py_ssize_t len;
+ register unsigned char *p;
+ register long x;
+
+ if ( self->b_hash != -1 )
+ return self->b_hash;
+
+ /* XXX potential bugs here, a readonly buffer does not imply that the
+ * underlying memory is immutable. b_readonly is a necessary but not
+ * sufficient condition for a buffer to be hashable. Perhaps it would
+ * be better to only allow hashing if the underlying object is known to
+ * be immutable (e.g. PyString_Check() is true). Another idea would
+ * be to call tp_hash on the underlying object and see if it raises
+ * an error. */
+ if ( !self->b_readonly )
+ {
+ PyErr_SetString(PyExc_TypeError,
+ "writable buffers are not hashable");
+ return -1;
+ }
+
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return -1;
+ p = (unsigned char *) ptr;
+ len = size;
+ x = *p << 7;
+ while (--len >= 0)
+ x = (1000003*x) ^ *p++;
+ x ^= size;
+ if (x == -1)
+ x = -2;
+ self->b_hash = x;
+ return x;
}
static PyObject *
buffer_str(PyBufferObject *self)
{
- void *ptr;
- Py_ssize_t size;
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return NULL;
- return PyString_FromStringAndSize((const char *)ptr, size);
+ void *ptr;
+ Py_ssize_t size;
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return NULL;
+ return PyString_FromStringAndSize((const char *)ptr, size);
}
/* Sequence methods */
@@ -359,372 +359,372 @@ buffer_str(PyBufferObject *self)
static Py_ssize_t
buffer_length(PyBufferObject *self)
{
- void *ptr;
- Py_ssize_t size;
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return -1;
- return size;
+ void *ptr;
+ Py_ssize_t size;
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return -1;
+ return size;
}
static PyObject *
buffer_concat(PyBufferObject *self, PyObject *other)
{
- PyBufferProcs *pb = other->ob_type->tp_as_buffer;
- void *ptr1, *ptr2;
- char *p;
- PyObject *ob;
- Py_ssize_t size, count;
-
- if ( pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL )
- {
- PyErr_BadArgument();
- return NULL;
- }
- if ( (*pb->bf_getsegcount)(other, NULL) != 1 )
- {
- /* ### use a different exception type/message? */
- PyErr_SetString(PyExc_TypeError,
- "single-segment buffer object expected");
- return NULL;
- }
-
- if (!get_buf(self, &ptr1, &size, ANY_BUFFER))
- return NULL;
-
- /* optimize special case */
- if ( size == 0 )
- {
- Py_INCREF(other);
- return other;
- }
-
- if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
- return NULL;
-
- assert(count <= PY_SIZE_MAX - size);
-
- ob = PyString_FromStringAndSize(NULL, size + count);
- if ( ob == NULL )
- return NULL;
- p = PyString_AS_STRING(ob);
- memcpy(p, ptr1, size);
- memcpy(p + size, ptr2, count);
-
- /* there is an extra byte in the string object, so this is safe */
- p[size + count] = '\0';
-
- return ob;
+ PyBufferProcs *pb = other->ob_type->tp_as_buffer;
+ void *ptr1, *ptr2;
+ char *p;
+ PyObject *ob;
+ Py_ssize_t size, count;
+
+ if ( pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL )
+ {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ if ( (*pb->bf_getsegcount)(other, NULL) != 1 )
+ {
+ /* ### use a different exception type/message? */
+ PyErr_SetString(PyExc_TypeError,
+ "single-segment buffer object expected");
+ return NULL;
+ }
+
+ if (!get_buf(self, &ptr1, &size, ANY_BUFFER))
+ return NULL;
+
+ /* optimize special case */
+ if ( size == 0 )
+ {
+ Py_INCREF(other);
+ return other;
+ }
+
+ if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
+ return NULL;
+
+ assert(count <= PY_SIZE_MAX - size);
+
+ ob = PyString_FromStringAndSize(NULL, size + count);
+ if ( ob == NULL )
+ return NULL;
+ p = PyString_AS_STRING(ob);
+ memcpy(p, ptr1, size);
+ memcpy(p + size, ptr2, count);
+
+ /* there is an extra byte in the string object, so this is safe */
+ p[size + count] = '\0';
+
+ return ob;
}
static PyObject *
buffer_repeat(PyBufferObject *self, Py_ssize_t count)
{
- PyObject *ob;
- register char *p;
- void *ptr;
- Py_ssize_t size;
-
- if ( count < 0 )
- count = 0;
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return NULL;
- if (count > PY_SSIZE_T_MAX / size) {
- PyErr_SetString(PyExc_MemoryError, "result too large");
- return NULL;
- }
- ob = PyString_FromStringAndSize(NULL, size * count);
- if ( ob == NULL )
- return NULL;
-
- p = PyString_AS_STRING(ob);
- while ( count-- )
- {
- memcpy(p, ptr, size);
- p += size;
- }
-
- /* there is an extra byte in the string object, so this is safe */
- *p = '\0';
-
- return ob;
+ PyObject *ob;
+ register char *p;
+ void *ptr;
+ Py_ssize_t size;
+
+ if ( count < 0 )
+ count = 0;
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return NULL;
+ if (count > PY_SSIZE_T_MAX / size) {
+ PyErr_SetString(PyExc_MemoryError, "result too large");
+ return NULL;
+ }
+ ob = PyString_FromStringAndSize(NULL, size * count);
+ if ( ob == NULL )
+ return NULL;
+
+ p = PyString_AS_STRING(ob);
+ while ( count-- )
+ {
+ memcpy(p, ptr, size);
+ p += size;
+ }
+
+ /* there is an extra byte in the string object, so this is safe */
+ *p = '\0';
+
+ return ob;
}
static PyObject *
buffer_item(PyBufferObject *self, Py_ssize_t idx)
{
- void *ptr;
- Py_ssize_t size;
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return NULL;
- if ( idx < 0 || idx >= size ) {
- PyErr_SetString(PyExc_IndexError, "buffer index out of range");
- return NULL;
- }
- return PyString_FromStringAndSize((char *)ptr + idx, 1);
+ void *ptr;
+ Py_ssize_t size;
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return NULL;
+ if ( idx < 0 || idx >= size ) {
+ PyErr_SetString(PyExc_IndexError, "buffer index out of range");
+ return NULL;
+ }
+ return PyString_FromStringAndSize((char *)ptr + idx, 1);
}
static PyObject *
buffer_slice(PyBufferObject *self, Py_ssize_t left, Py_ssize_t right)
{
- void *ptr;
- Py_ssize_t size;
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return NULL;
- if ( left < 0 )
- left = 0;
- if ( right < 0 )
- right = 0;
- if ( right > size )
- right = size;
- if ( right < left )
- right = left;
- return PyString_FromStringAndSize((char *)ptr + left,
- right - left);
+ void *ptr;
+ Py_ssize_t size;
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return NULL;
+ if ( left < 0 )
+ left = 0;
+ if ( right < 0 )
+ right = 0;
+ if ( right > size )
+ right = size;
+ if ( right < left )
+ right = left;
+ return PyString_FromStringAndSize((char *)ptr + left,
+ right - left);
}
static PyObject *
buffer_subscript(PyBufferObject *self, PyObject *item)
{
- void *p;
- Py_ssize_t size;
-
- if (!get_buf(self, &p, &size, ANY_BUFFER))
- return NULL;
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += size;
- return buffer_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength, cur, i;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item, size,
- &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0)
- return PyString_FromStringAndSize("", 0);
- else if (step == 1)
- return PyString_FromStringAndSize((char *)p + start,
- stop - start);
- else {
- PyObject *result;
- char *source_buf = (char *)p;
- char *result_buf = (char *)PyMem_Malloc(slicelength);
-
- if (result_buf == NULL)
- return PyErr_NoMemory();
-
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- result_buf[i] = source_buf[cur];
- }
-
- result = PyString_FromStringAndSize(result_buf,
- slicelength);
- PyMem_Free(result_buf);
- return result;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "sequence index must be integer");
- return NULL;
- }
+ void *p;
+ Py_ssize_t size;
+
+ if (!get_buf(self, &p, &size, ANY_BUFFER))
+ return NULL;
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += size;
+ return buffer_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength, cur, i;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, size,
+ &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0)
+ return PyString_FromStringAndSize("", 0);
+ else if (step == 1)
+ return PyString_FromStringAndSize((char *)p + start,
+ stop - start);
+ else {
+ PyObject *result;
+ char *source_buf = (char *)p;
+ char *result_buf = (char *)PyMem_Malloc(slicelength);
+
+ if (result_buf == NULL)
+ return PyErr_NoMemory();
+
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ result_buf[i] = source_buf[cur];
+ }
+
+ result = PyString_FromStringAndSize(result_buf,
+ slicelength);
+ PyMem_Free(result_buf);
+ return result;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "sequence index must be integer");
+ return NULL;
+ }
}
static int
buffer_ass_item(PyBufferObject *self, Py_ssize_t idx, PyObject *other)
{
- PyBufferProcs *pb;
- void *ptr1, *ptr2;
- Py_ssize_t size;
- Py_ssize_t count;
-
- if ( self->b_readonly ) {
- PyErr_SetString(PyExc_TypeError,
- "buffer is read-only");
- return -1;
- }
-
- if (!get_buf(self, &ptr1, &size, ANY_BUFFER))
- return -1;
-
- if (idx < 0 || idx >= size) {
- PyErr_SetString(PyExc_IndexError,
- "buffer assignment index out of range");
- return -1;
- }
-
- pb = other ? other->ob_type->tp_as_buffer : NULL;
- if ( pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL )
- {
- PyErr_BadArgument();
- return -1;
- }
- if ( (*pb->bf_getsegcount)(other, NULL) != 1 )
- {
- /* ### use a different exception type/message? */
- PyErr_SetString(PyExc_TypeError,
- "single-segment buffer object expected");
- return -1;
- }
-
- if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
- return -1;
- if ( count != 1 ) {
- PyErr_SetString(PyExc_TypeError,
- "right operand must be a single byte");
- return -1;
- }
-
- ((char *)ptr1)[idx] = *(char *)ptr2;
- return 0;
+ PyBufferProcs *pb;
+ void *ptr1, *ptr2;
+ Py_ssize_t size;
+ Py_ssize_t count;
+
+ if ( self->b_readonly ) {
+ PyErr_SetString(PyExc_TypeError,
+ "buffer is read-only");
+ return -1;
+ }
+
+ if (!get_buf(self, &ptr1, &size, ANY_BUFFER))
+ return -1;
+
+ if (idx < 0 || idx >= size) {
+ PyErr_SetString(PyExc_IndexError,
+ "buffer assignment index out of range");
+ return -1;
+ }
+
+ pb = other ? other->ob_type->tp_as_buffer : NULL;
+ if ( pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL )
+ {
+ PyErr_BadArgument();
+ return -1;
+ }
+ if ( (*pb->bf_getsegcount)(other, NULL) != 1 )
+ {
+ /* ### use a different exception type/message? */
+ PyErr_SetString(PyExc_TypeError,
+ "single-segment buffer object expected");
+ return -1;
+ }
+
+ if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
+ return -1;
+ if ( count != 1 ) {
+ PyErr_SetString(PyExc_TypeError,
+ "right operand must be a single byte");
+ return -1;
+ }
+
+ ((char *)ptr1)[idx] = *(char *)ptr2;
+ return 0;
}
static int
buffer_ass_slice(PyBufferObject *self, Py_ssize_t left, Py_ssize_t right, PyObject *other)
{
- PyBufferProcs *pb;
- void *ptr1, *ptr2;
- Py_ssize_t size;
- Py_ssize_t slice_len;
- Py_ssize_t count;
-
- if ( self->b_readonly ) {
- PyErr_SetString(PyExc_TypeError,
- "buffer is read-only");
- return -1;
- }
-
- pb = other ? other->ob_type->tp_as_buffer : NULL;
- if ( pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL )
- {
- PyErr_BadArgument();
- return -1;
- }
- if ( (*pb->bf_getsegcount)(other, NULL) != 1 )
- {
- /* ### use a different exception type/message? */
- PyErr_SetString(PyExc_TypeError,
- "single-segment buffer object expected");
- return -1;
- }
- if (!get_buf(self, &ptr1, &size, ANY_BUFFER))
- return -1;
- if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
- return -1;
-
- if ( left < 0 )
- left = 0;
- else if ( left > size )
- left = size;
- if ( right < left )
- right = left;
- else if ( right > size )
- right = size;
- slice_len = right - left;
-
- if ( count != slice_len ) {
- PyErr_SetString(
- PyExc_TypeError,
- "right operand length must match slice length");
- return -1;
- }
-
- if ( slice_len )
- memcpy((char *)ptr1 + left, ptr2, slice_len);
-
- return 0;
+ PyBufferProcs *pb;
+ void *ptr1, *ptr2;
+ Py_ssize_t size;
+ Py_ssize_t slice_len;
+ Py_ssize_t count;
+
+ if ( self->b_readonly ) {
+ PyErr_SetString(PyExc_TypeError,
+ "buffer is read-only");
+ return -1;
+ }
+
+ pb = other ? other->ob_type->tp_as_buffer : NULL;
+ if ( pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL )
+ {
+ PyErr_BadArgument();
+ return -1;
+ }
+ if ( (*pb->bf_getsegcount)(other, NULL) != 1 )
+ {
+ /* ### use a different exception type/message? */
+ PyErr_SetString(PyExc_TypeError,
+ "single-segment buffer object expected");
+ return -1;
+ }
+ if (!get_buf(self, &ptr1, &size, ANY_BUFFER))
+ return -1;
+ if ( (count = (*pb->bf_getreadbuffer)(other, 0, &ptr2)) < 0 )
+ return -1;
+
+ if ( left < 0 )
+ left = 0;
+ else if ( left > size )
+ left = size;
+ if ( right < left )
+ right = left;
+ else if ( right > size )
+ right = size;
+ slice_len = right - left;
+
+ if ( count != slice_len ) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "right operand length must match slice length");
+ return -1;
+ }
+
+ if ( slice_len )
+ memcpy((char *)ptr1 + left, ptr2, slice_len);
+
+ return 0;
}
static int
buffer_ass_subscript(PyBufferObject *self, PyObject *item, PyObject *value)
{
- PyBufferProcs *pb;
- void *ptr1, *ptr2;
- Py_ssize_t selfsize;
- Py_ssize_t othersize;
-
- if ( self->b_readonly ) {
- PyErr_SetString(PyExc_TypeError,
- "buffer is read-only");
- return -1;
- }
-
- pb = value ? value->ob_type->tp_as_buffer : NULL;
- if ( pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL )
- {
- PyErr_BadArgument();
- return -1;
- }
- if ( (*pb->bf_getsegcount)(value, NULL) != 1 )
- {
- /* ### use a different exception type/message? */
- PyErr_SetString(PyExc_TypeError,
- "single-segment buffer object expected");
- return -1;
- }
- if (!get_buf(self, &ptr1, &selfsize, ANY_BUFFER))
- return -1;
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += selfsize;
- return buffer_ass_item(self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item, selfsize,
- &start, &stop, &step, &slicelength) < 0)
- return -1;
-
- if ((othersize = (*pb->bf_getreadbuffer)(value, 0, &ptr2)) < 0)
- return -1;
-
- if (othersize != slicelength) {
- PyErr_SetString(
- PyExc_TypeError,
- "right operand length must match slice length");
- return -1;
- }
-
- if (slicelength == 0)
- return 0;
- else if (step == 1) {
- memcpy((char *)ptr1 + start, ptr2, slicelength);
- return 0;
- }
- else {
- Py_ssize_t cur, i;
-
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- ((char *)ptr1)[cur] = ((char *)ptr2)[i];
- }
-
- return 0;
- }
- } else {
- PyErr_SetString(PyExc_TypeError,
- "buffer indices must be integers");
- return -1;
- }
+ PyBufferProcs *pb;
+ void *ptr1, *ptr2;
+ Py_ssize_t selfsize;
+ Py_ssize_t othersize;
+
+ if ( self->b_readonly ) {
+ PyErr_SetString(PyExc_TypeError,
+ "buffer is read-only");
+ return -1;
+ }
+
+ pb = value ? value->ob_type->tp_as_buffer : NULL;
+ if ( pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL )
+ {
+ PyErr_BadArgument();
+ return -1;
+ }
+ if ( (*pb->bf_getsegcount)(value, NULL) != 1 )
+ {
+ /* ### use a different exception type/message? */
+ PyErr_SetString(PyExc_TypeError,
+ "single-segment buffer object expected");
+ return -1;
+ }
+ if (!get_buf(self, &ptr1, &selfsize, ANY_BUFFER))
+ return -1;
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += selfsize;
+ return buffer_ass_item(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item, selfsize,
+ &start, &stop, &step, &slicelength) < 0)
+ return -1;
+
+ if ((othersize = (*pb->bf_getreadbuffer)(value, 0, &ptr2)) < 0)
+ return -1;
+
+ if (othersize != slicelength) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "right operand length must match slice length");
+ return -1;
+ }
+
+ if (slicelength == 0)
+ return 0;
+ else if (step == 1) {
+ memcpy((char *)ptr1 + start, ptr2, slicelength);
+ return 0;
+ }
+ else {
+ Py_ssize_t cur, i;
+
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ ((char *)ptr1)[cur] = ((char *)ptr2)[i];
+ }
+
+ return 0;
+ }
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "buffer indices must be integers");
+ return -1;
+ }
}
/* Buffer methods */
@@ -732,126 +732,126 @@ buffer_ass_subscript(PyBufferObject *self, PyObject *item, PyObject *value)
static Py_ssize_t
buffer_getreadbuf(PyBufferObject *self, Py_ssize_t idx, void **pp)
{
- Py_ssize_t size;
- if ( idx != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent buffer segment");
- return -1;
- }
- if (!get_buf(self, pp, &size, READ_BUFFER))
- return -1;
- return size;
+ Py_ssize_t size;
+ if ( idx != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent buffer segment");
+ return -1;
+ }
+ if (!get_buf(self, pp, &size, READ_BUFFER))
+ return -1;
+ return size;
}
static Py_ssize_t
buffer_getwritebuf(PyBufferObject *self, Py_ssize_t idx, void **pp)
{
- Py_ssize_t size;
-
- if ( self->b_readonly )
- {
- PyErr_SetString(PyExc_TypeError, "buffer is read-only");
- return -1;
- }
-
- if ( idx != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent buffer segment");
- return -1;
- }
- if (!get_buf(self, pp, &size, WRITE_BUFFER))
- return -1;
- return size;
+ Py_ssize_t size;
+
+ if ( self->b_readonly )
+ {
+ PyErr_SetString(PyExc_TypeError, "buffer is read-only");
+ return -1;
+ }
+
+ if ( idx != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent buffer segment");
+ return -1;
+ }
+ if (!get_buf(self, pp, &size, WRITE_BUFFER))
+ return -1;
+ return size;
}
static Py_ssize_t
buffer_getsegcount(PyBufferObject *self, Py_ssize_t *lenp)
{
- void *ptr;
- Py_ssize_t size;
- if (!get_buf(self, &ptr, &size, ANY_BUFFER))
- return -1;
- if (lenp)
- *lenp = size;
- return 1;
+ void *ptr;
+ Py_ssize_t size;
+ if (!get_buf(self, &ptr, &size, ANY_BUFFER))
+ return -1;
+ if (lenp)
+ *lenp = size;
+ return 1;
}
static Py_ssize_t
buffer_getcharbuf(PyBufferObject *self, Py_ssize_t idx, const char **pp)
{
- void *ptr;
- Py_ssize_t size;
- if ( idx != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent buffer segment");
- return -1;
- }
- if (!get_buf(self, &ptr, &size, CHAR_BUFFER))
- return -1;
- *pp = (const char *)ptr;
- return size;
+ void *ptr;
+ Py_ssize_t size;
+ if ( idx != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent buffer segment");
+ return -1;
+ }
+ if (!get_buf(self, &ptr, &size, CHAR_BUFFER))
+ return -1;
+ *pp = (const char *)ptr;
+ return size;
}
static PySequenceMethods buffer_as_sequence = {
- (lenfunc)buffer_length, /*sq_length*/
- (binaryfunc)buffer_concat, /*sq_concat*/
- (ssizeargfunc)buffer_repeat, /*sq_repeat*/
- (ssizeargfunc)buffer_item, /*sq_item*/
- (ssizessizeargfunc)buffer_slice, /*sq_slice*/
- (ssizeobjargproc)buffer_ass_item, /*sq_ass_item*/
- (ssizessizeobjargproc)buffer_ass_slice, /*sq_ass_slice*/
+ (lenfunc)buffer_length, /*sq_length*/
+ (binaryfunc)buffer_concat, /*sq_concat*/
+ (ssizeargfunc)buffer_repeat, /*sq_repeat*/
+ (ssizeargfunc)buffer_item, /*sq_item*/
+ (ssizessizeargfunc)buffer_slice, /*sq_slice*/
+ (ssizeobjargproc)buffer_ass_item, /*sq_ass_item*/
+ (ssizessizeobjargproc)buffer_ass_slice, /*sq_ass_slice*/
};
static PyMappingMethods buffer_as_mapping = {
- (lenfunc)buffer_length,
- (binaryfunc)buffer_subscript,
- (objobjargproc)buffer_ass_subscript,
+ (lenfunc)buffer_length,
+ (binaryfunc)buffer_subscript,
+ (objobjargproc)buffer_ass_subscript,
};
static PyBufferProcs buffer_as_buffer = {
- (readbufferproc)buffer_getreadbuf,
- (writebufferproc)buffer_getwritebuf,
- (segcountproc)buffer_getsegcount,
- (charbufferproc)buffer_getcharbuf,
+ (readbufferproc)buffer_getreadbuf,
+ (writebufferproc)buffer_getwritebuf,
+ (segcountproc)buffer_getsegcount,
+ (charbufferproc)buffer_getcharbuf,
};
PyTypeObject PyBuffer_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "buffer",
- sizeof(PyBufferObject),
- 0,
- (destructor)buffer_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)buffer_compare, /* tp_compare */
- (reprfunc)buffer_repr, /* tp_repr */
- 0, /* tp_as_number */
- &buffer_as_sequence, /* tp_as_sequence */
- &buffer_as_mapping, /* tp_as_mapping */
- (hashfunc)buffer_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)buffer_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- &buffer_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GETCHARBUFFER, /* tp_flags */
- buffer_doc, /* 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 */
- 0, /* tp_init */
- 0, /* tp_alloc */
- buffer_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "buffer",
+ sizeof(PyBufferObject),
+ 0,
+ (destructor)buffer_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)buffer_compare, /* tp_compare */
+ (reprfunc)buffer_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &buffer_as_sequence, /* tp_as_sequence */
+ &buffer_as_mapping, /* tp_as_mapping */
+ (hashfunc)buffer_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)buffer_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ &buffer_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GETCHARBUFFER, /* tp_flags */
+ buffer_doc, /* 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 */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ buffer_new, /* tp_new */
};
diff --git a/Objects/bytes_methods.c b/Objects/bytes_methods.c
index 4d25520..a5d0c5b 100644
--- a/Objects/bytes_methods.c
+++ b/Objects/bytes_methods.c
@@ -24,7 +24,7 @@ _Py_bytes_isspace(const char *cptr, Py_ssize_t len)
e = p + len;
for (; p < e; p++) {
- if (!Py_ISSPACE(*p))
+ if (!Py_ISSPACE(*p))
Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
@@ -46,16 +46,16 @@ _Py_bytes_isalpha(const char *cptr, Py_ssize_t len)
/* Shortcut for single character strings */
if (len == 1 && Py_ISALPHA(*p))
- Py_RETURN_TRUE;
+ Py_RETURN_TRUE;
/* Special case for empty strings */
if (len == 0)
- Py_RETURN_FALSE;
+ Py_RETURN_FALSE;
e = p + len;
for (; p < e; p++) {
- if (!Py_ISALPHA(*p))
- Py_RETURN_FALSE;
+ if (!Py_ISALPHA(*p))
+ Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
}
@@ -76,16 +76,16 @@ _Py_bytes_isalnum(const char *cptr, Py_ssize_t len)
/* Shortcut for single character strings */
if (len == 1 && Py_ISALNUM(*p))
- Py_RETURN_TRUE;
+ Py_RETURN_TRUE;
/* Special case for empty strings */
if (len == 0)
- Py_RETURN_FALSE;
+ Py_RETURN_FALSE;
e = p + len;
for (; p < e; p++) {
- if (!Py_ISALNUM(*p))
- Py_RETURN_FALSE;
+ if (!Py_ISALNUM(*p))
+ Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
}
@@ -106,16 +106,16 @@ _Py_bytes_isdigit(const char *cptr, Py_ssize_t len)
/* Shortcut for single character strings */
if (len == 1 && Py_ISDIGIT(*p))
- Py_RETURN_TRUE;
+ Py_RETURN_TRUE;
/* Special case for empty strings */
if (len == 0)
- Py_RETURN_FALSE;
+ Py_RETURN_FALSE;
e = p + len;
for (; p < e; p++) {
- if (!Py_ISDIGIT(*p))
- Py_RETURN_FALSE;
+ if (!Py_ISDIGIT(*p))
+ Py_RETURN_FALSE;
}
Py_RETURN_TRUE;
}
@@ -137,19 +137,19 @@ _Py_bytes_islower(const char *cptr, Py_ssize_t len)
/* Shortcut for single character strings */
if (len == 1)
- return PyBool_FromLong(Py_ISLOWER(*p));
+ return PyBool_FromLong(Py_ISLOWER(*p));
/* Special case for empty strings */
if (len == 0)
- Py_RETURN_FALSE;
+ Py_RETURN_FALSE;
e = p + len;
cased = 0;
for (; p < e; p++) {
- if (Py_ISUPPER(*p))
- Py_RETURN_FALSE;
- else if (!cased && Py_ISLOWER(*p))
- cased = 1;
+ if (Py_ISUPPER(*p))
+ Py_RETURN_FALSE;
+ else if (!cased && Py_ISLOWER(*p))
+ cased = 1;
}
return PyBool_FromLong(cased);
}
@@ -171,19 +171,19 @@ _Py_bytes_isupper(const char *cptr, Py_ssize_t len)
/* Shortcut for single character strings */
if (len == 1)
- return PyBool_FromLong(Py_ISUPPER(*p));
+ return PyBool_FromLong(Py_ISUPPER(*p));
/* Special case for empty strings */
if (len == 0)
- Py_RETURN_FALSE;
+ Py_RETURN_FALSE;
e = p + len;
cased = 0;
for (; p < e; p++) {
- if (Py_ISLOWER(*p))
- Py_RETURN_FALSE;
- else if (!cased && Py_ISUPPER(*p))
- cased = 1;
+ if (Py_ISLOWER(*p))
+ Py_RETURN_FALSE;
+ else if (!cased && Py_ISUPPER(*p))
+ cased = 1;
}
return PyBool_FromLong(cased);
}
@@ -207,32 +207,32 @@ _Py_bytes_istitle(const char *cptr, Py_ssize_t len)
/* Shortcut for single character strings */
if (len == 1)
- return PyBool_FromLong(Py_ISUPPER(*p));
+ return PyBool_FromLong(Py_ISUPPER(*p));
/* Special case for empty strings */
if (len == 0)
- Py_RETURN_FALSE;
+ Py_RETURN_FALSE;
e = p + len;
cased = 0;
previous_is_cased = 0;
for (; p < e; p++) {
- register const unsigned char ch = *p;
-
- if (Py_ISUPPER(ch)) {
- if (previous_is_cased)
- Py_RETURN_FALSE;
- previous_is_cased = 1;
- cased = 1;
- }
- else if (Py_ISLOWER(ch)) {
- if (!previous_is_cased)
- Py_RETURN_FALSE;
- previous_is_cased = 1;
- cased = 1;
- }
- else
- previous_is_cased = 0;
+ register const unsigned char ch = *p;
+
+ if (Py_ISUPPER(ch)) {
+ if (previous_is_cased)
+ Py_RETURN_FALSE;
+ previous_is_cased = 1;
+ cased = 1;
+ }
+ else if (Py_ISLOWER(ch)) {
+ if (!previous_is_cased)
+ Py_RETURN_FALSE;
+ previous_is_cased = 1;
+ cased = 1;
+ }
+ else
+ previous_is_cased = 0;
}
return PyBool_FromLong(cased);
}
@@ -246,23 +246,23 @@ Return a copy of B with all ASCII characters converted to lowercase.");
void
_Py_bytes_lower(char *result, const char *cptr, Py_ssize_t len)
{
- Py_ssize_t i;
+ Py_ssize_t i;
/*
- newobj = PyString_FromStringAndSize(NULL, len);
- if (!newobj)
- return NULL;
+ newobj = PyString_FromStringAndSize(NULL, len);
+ if (!newobj)
+ return NULL;
- s = PyString_AS_STRING(newobj);
+ s = PyString_AS_STRING(newobj);
*/
- Py_MEMCPY(result, cptr, len);
+ Py_MEMCPY(result, cptr, len);
- for (i = 0; i < len; i++) {
- int c = Py_CHARMASK(result[i]);
- if (Py_ISUPPER(c))
- result[i] = Py_TOLOWER(c);
- }
+ for (i = 0; i < len; i++) {
+ int c = Py_CHARMASK(result[i]);
+ if (Py_ISUPPER(c))
+ result[i] = Py_TOLOWER(c);
+ }
}
@@ -274,23 +274,23 @@ Return a copy of B with all ASCII characters converted to uppercase.");
void
_Py_bytes_upper(char *result, const char *cptr, Py_ssize_t len)
{
- Py_ssize_t i;
+ Py_ssize_t i;
/*
- newobj = PyString_FromStringAndSize(NULL, len);
- if (!newobj)
- return NULL;
+ newobj = PyString_FromStringAndSize(NULL, len);
+ if (!newobj)
+ return NULL;
- s = PyString_AS_STRING(newobj);
+ s = PyString_AS_STRING(newobj);
*/
- Py_MEMCPY(result, cptr, len);
+ Py_MEMCPY(result, cptr, len);
- for (i = 0; i < len; i++) {
- int c = Py_CHARMASK(result[i]);
- if (Py_ISLOWER(c))
- result[i] = Py_TOUPPER(c);
- }
+ for (i = 0; i < len; i++) {
+ int c = Py_CHARMASK(result[i]);
+ if (Py_ISLOWER(c))
+ result[i] = Py_TOUPPER(c);
+ }
}
@@ -303,29 +303,29 @@ characters, all remaining cased characters have lowercase.");
void
_Py_bytes_title(char *result, char *s, Py_ssize_t len)
{
- Py_ssize_t i;
- int previous_is_cased = 0;
+ Py_ssize_t i;
+ int previous_is_cased = 0;
/*
- newobj = PyString_FromStringAndSize(NULL, len);
- if (newobj == NULL)
- return NULL;
- s_new = PyString_AsString(newobj);
+ newobj = PyString_FromStringAndSize(NULL, len);
+ if (newobj == NULL)
+ return NULL;
+ s_new = PyString_AsString(newobj);
*/
- for (i = 0; i < len; i++) {
- int c = Py_CHARMASK(*s++);
- if (Py_ISLOWER(c)) {
- if (!previous_is_cased)
- c = Py_TOUPPER(c);
- previous_is_cased = 1;
- } else if (Py_ISUPPER(c)) {
- if (previous_is_cased)
- c = Py_TOLOWER(c);
- previous_is_cased = 1;
- } else
- previous_is_cased = 0;
- *result++ = c;
- }
+ for (i = 0; i < len; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (Py_ISLOWER(c)) {
+ if (!previous_is_cased)
+ c = Py_TOUPPER(c);
+ previous_is_cased = 1;
+ } else if (Py_ISUPPER(c)) {
+ if (previous_is_cased)
+ c = Py_TOLOWER(c);
+ previous_is_cased = 1;
+ } else
+ previous_is_cased = 0;
+ *result++ = c;
+ }
}
@@ -337,30 +337,30 @@ Return a copy of B with only its first character capitalized (ASCII).");
void
_Py_bytes_capitalize(char *result, char *s, Py_ssize_t len)
{
- Py_ssize_t i;
+ Py_ssize_t i;
/*
- newobj = PyString_FromStringAndSize(NULL, len);
- if (newobj == NULL)
- return NULL;
- s_new = PyString_AsString(newobj);
+ newobj = PyString_FromStringAndSize(NULL, len);
+ if (newobj == NULL)
+ return NULL;
+ s_new = PyString_AsString(newobj);
*/
- if (0 < len) {
- int c = Py_CHARMASK(*s++);
- if (Py_ISLOWER(c))
- *result = Py_TOUPPER(c);
- else
- *result = c;
- result++;
- }
- for (i = 1; i < len; i++) {
- int c = Py_CHARMASK(*s++);
- if (Py_ISUPPER(c))
- *result = Py_TOLOWER(c);
- else
- *result = c;
- result++;
- }
+ if (0 < len) {
+ int c = Py_CHARMASK(*s++);
+ if (Py_ISLOWER(c))
+ *result = Py_TOUPPER(c);
+ else
+ *result = c;
+ result++;
+ }
+ for (i = 1; i < len; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (Py_ISUPPER(c))
+ *result = Py_TOLOWER(c);
+ else
+ *result = c;
+ result++;
+ }
}
@@ -373,25 +373,25 @@ to lowercase ASCII and vice versa.");
void
_Py_bytes_swapcase(char *result, char *s, Py_ssize_t len)
{
- Py_ssize_t i;
+ Py_ssize_t i;
/*
- newobj = PyString_FromStringAndSize(NULL, len);
- if (newobj == NULL)
- return NULL;
- s_new = PyString_AsString(newobj);
+ newobj = PyString_FromStringAndSize(NULL, len);
+ if (newobj == NULL)
+ return NULL;
+ s_new = PyString_AsString(newobj);
*/
- for (i = 0; i < len; i++) {
- int c = Py_CHARMASK(*s++);
- if (Py_ISLOWER(c)) {
- *result = Py_TOUPPER(c);
- }
- else if (Py_ISUPPER(c)) {
- *result = Py_TOLOWER(c);
- }
- else
- *result = c;
- result++;
- }
+ for (i = 0; i < len; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (Py_ISLOWER(c)) {
+ *result = Py_TOUPPER(c);
+ }
+ else if (Py_ISUPPER(c)) {
+ *result = Py_TOLOWER(c);
+ }
+ else
+ *result = c;
+ result++;
+ }
}
diff --git a/Objects/cellobject.c b/Objects/cellobject.c
index 4e0bcf8..d0f6cda 100644
--- a/Objects/cellobject.c
+++ b/Objects/cellobject.c
@@ -5,141 +5,141 @@
PyObject *
PyCell_New(PyObject *obj)
{
- PyCellObject *op;
+ PyCellObject *op;
- op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type);
- if (op == NULL)
- return NULL;
- op->ob_ref = obj;
- Py_XINCREF(obj);
+ op = (PyCellObject *)PyObject_GC_New(PyCellObject, &PyCell_Type);
+ if (op == NULL)
+ return NULL;
+ op->ob_ref = obj;
+ Py_XINCREF(obj);
- _PyObject_GC_TRACK(op);
- return (PyObject *)op;
+ _PyObject_GC_TRACK(op);
+ return (PyObject *)op;
}
PyObject *
PyCell_Get(PyObject *op)
{
- if (!PyCell_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- Py_XINCREF(((PyCellObject*)op)->ob_ref);
- return PyCell_GET(op);
+ if (!PyCell_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ Py_XINCREF(((PyCellObject*)op)->ob_ref);
+ return PyCell_GET(op);
}
int
PyCell_Set(PyObject *op, PyObject *obj)
{
- PyObject* oldobj;
- if (!PyCell_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- oldobj = PyCell_GET(op);
- Py_XINCREF(obj);
- PyCell_SET(op, obj);
- Py_XDECREF(oldobj);
- return 0;
+ PyObject* oldobj;
+ if (!PyCell_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ oldobj = PyCell_GET(op);
+ Py_XINCREF(obj);
+ PyCell_SET(op, obj);
+ Py_XDECREF(oldobj);
+ return 0;
}
static void
cell_dealloc(PyCellObject *op)
{
- _PyObject_GC_UNTRACK(op);
- Py_XDECREF(op->ob_ref);
- PyObject_GC_Del(op);
+ _PyObject_GC_UNTRACK(op);
+ Py_XDECREF(op->ob_ref);
+ PyObject_GC_Del(op);
}
static int
cell_compare(PyCellObject *a, PyCellObject *b)
{
- /* Py3K warning for comparisons */
- if (PyErr_WarnPy3k("cell comparisons not supported in 3.x",
- 1) < 0) {
- return -2;
- }
-
- if (a->ob_ref == NULL) {
- if (b->ob_ref == NULL)
- return 0;
- return -1;
- } else if (b->ob_ref == NULL)
- return 1;
- return PyObject_Compare(a->ob_ref, b->ob_ref);
+ /* Py3K warning for comparisons */
+ if (PyErr_WarnPy3k("cell comparisons not supported in 3.x",
+ 1) < 0) {
+ return -2;
+ }
+
+ if (a->ob_ref == NULL) {
+ if (b->ob_ref == NULL)
+ return 0;
+ return -1;
+ } else if (b->ob_ref == NULL)
+ return 1;
+ return PyObject_Compare(a->ob_ref, b->ob_ref);
}
static PyObject *
cell_repr(PyCellObject *op)
{
- if (op->ob_ref == NULL)
- return PyString_FromFormat("<cell at %p: empty>", op);
+ if (op->ob_ref == NULL)
+ return PyString_FromFormat("<cell at %p: empty>", op);
- return PyString_FromFormat("<cell at %p: %.80s object at %p>",
- op, op->ob_ref->ob_type->tp_name,
- op->ob_ref);
+ return PyString_FromFormat("<cell at %p: %.80s object at %p>",
+ op, op->ob_ref->ob_type->tp_name,
+ op->ob_ref);
}
static int
cell_traverse(PyCellObject *op, visitproc visit, void *arg)
{
- Py_VISIT(op->ob_ref);
- return 0;
+ Py_VISIT(op->ob_ref);
+ return 0;
}
static int
cell_clear(PyCellObject *op)
{
- Py_CLEAR(op->ob_ref);
- return 0;
+ Py_CLEAR(op->ob_ref);
+ return 0;
}
static PyObject *
cell_get_contents(PyCellObject *op, void *closure)
{
- if (op->ob_ref == NULL)
- {
- PyErr_SetString(PyExc_ValueError, "Cell is empty");
- return NULL;
- }
- Py_INCREF(op->ob_ref);
- return op->ob_ref;
+ if (op->ob_ref == NULL)
+ {
+ PyErr_SetString(PyExc_ValueError, "Cell is empty");
+ return NULL;
+ }
+ Py_INCREF(op->ob_ref);
+ return op->ob_ref;
}
static PyGetSetDef cell_getsetlist[] = {
- {"cell_contents", (getter)cell_get_contents, NULL},
- {NULL} /* sentinel */
+ {"cell_contents", (getter)cell_get_contents, NULL},
+ {NULL} /* sentinel */
};
PyTypeObject PyCell_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "cell",
- sizeof(PyCellObject),
- 0,
- (destructor)cell_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)cell_compare, /* tp_compare */
- (reprfunc)cell_repr, /* 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_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)cell_traverse, /* tp_traverse */
- (inquiry)cell_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- cell_getsetlist, /* tp_getset */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "cell",
+ sizeof(PyCellObject),
+ 0,
+ (destructor)cell_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)cell_compare, /* tp_compare */
+ (reprfunc)cell_repr, /* 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_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)cell_traverse, /* tp_traverse */
+ (inquiry)cell_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ cell_getsetlist, /* tp_getset */
};
diff --git a/Objects/classobject.c b/Objects/classobject.c
index 032d354..0832531 100644
--- a/Objects/classobject.c
+++ b/Objects/classobject.c
@@ -18,7 +18,7 @@ static int numfree = 0;
/* Forward */
static PyObject *class_lookup(PyClassObject *, PyObject *,
- PyClassObject **);
+ PyClassObject **);
static PyObject *instance_getattr1(PyInstanceObject *, PyObject *);
static PyObject *instance_getattr2(PyInstanceObject *, PyObject *);
@@ -29,140 +29,140 @@ PyObject *
PyClass_New(PyObject *bases, PyObject *dict, PyObject *name)
/* bases is NULL or tuple of classobjects! */
{
- PyClassObject *op, *dummy;
- static PyObject *docstr, *modstr, *namestr;
- if (docstr == NULL) {
- docstr= PyString_InternFromString("__doc__");
- if (docstr == NULL)
- return NULL;
- }
- if (modstr == NULL) {
- modstr= PyString_InternFromString("__module__");
- if (modstr == NULL)
- return NULL;
- }
- if (namestr == NULL) {
- namestr= PyString_InternFromString("__name__");
- if (namestr == NULL)
- return NULL;
- }
- if (name == NULL || !PyString_Check(name)) {
- PyErr_SetString(PyExc_TypeError,
- "PyClass_New: name must be a string");
- return NULL;
- }
- if (dict == NULL || !PyDict_Check(dict)) {
- PyErr_SetString(PyExc_TypeError,
- "PyClass_New: dict must be a dictionary");
- return NULL;
- }
- if (PyDict_GetItem(dict, docstr) == NULL) {
- if (PyDict_SetItem(dict, docstr, Py_None) < 0)
- return NULL;
- }
- if (PyDict_GetItem(dict, modstr) == NULL) {
- PyObject *globals = PyEval_GetGlobals();
- if (globals != NULL) {
- PyObject *modname = PyDict_GetItem(globals, namestr);
- if (modname != NULL) {
- if (PyDict_SetItem(dict, modstr, modname) < 0)
- return NULL;
- }
- }
- }
- if (bases == NULL) {
- bases = PyTuple_New(0);
- if (bases == NULL)
- return NULL;
- }
- else {
- Py_ssize_t i, n;
- PyObject *base;
- if (!PyTuple_Check(bases)) {
- PyErr_SetString(PyExc_TypeError,
- "PyClass_New: bases must be a tuple");
- return NULL;
- }
- n = PyTuple_Size(bases);
- for (i = 0; i < n; i++) {
- base = PyTuple_GET_ITEM(bases, i);
- if (!PyClass_Check(base)) {
- if (PyCallable_Check(
- (PyObject *) base->ob_type))
- return PyObject_CallFunctionObjArgs(
- (PyObject *) base->ob_type,
- name, bases, dict, NULL);
- PyErr_SetString(PyExc_TypeError,
- "PyClass_New: base must be a class");
- return NULL;
- }
- }
- Py_INCREF(bases);
- }
-
- if (getattrstr == NULL) {
- getattrstr = PyString_InternFromString("__getattr__");
- if (getattrstr == NULL)
- goto alloc_error;
- setattrstr = PyString_InternFromString("__setattr__");
- if (setattrstr == NULL)
- goto alloc_error;
- delattrstr = PyString_InternFromString("__delattr__");
- if (delattrstr == NULL)
- goto alloc_error;
- }
-
- op = PyObject_GC_New(PyClassObject, &PyClass_Type);
- if (op == NULL) {
+ PyClassObject *op, *dummy;
+ static PyObject *docstr, *modstr, *namestr;
+ if (docstr == NULL) {
+ docstr= PyString_InternFromString("__doc__");
+ if (docstr == NULL)
+ return NULL;
+ }
+ if (modstr == NULL) {
+ modstr= PyString_InternFromString("__module__");
+ if (modstr == NULL)
+ return NULL;
+ }
+ if (namestr == NULL) {
+ namestr= PyString_InternFromString("__name__");
+ if (namestr == NULL)
+ return NULL;
+ }
+ if (name == NULL || !PyString_Check(name)) {
+ PyErr_SetString(PyExc_TypeError,
+ "PyClass_New: name must be a string");
+ return NULL;
+ }
+ if (dict == NULL || !PyDict_Check(dict)) {
+ PyErr_SetString(PyExc_TypeError,
+ "PyClass_New: dict must be a dictionary");
+ return NULL;
+ }
+ if (PyDict_GetItem(dict, docstr) == NULL) {
+ if (PyDict_SetItem(dict, docstr, Py_None) < 0)
+ return NULL;
+ }
+ if (PyDict_GetItem(dict, modstr) == NULL) {
+ PyObject *globals = PyEval_GetGlobals();
+ if (globals != NULL) {
+ PyObject *modname = PyDict_GetItem(globals, namestr);
+ if (modname != NULL) {
+ if (PyDict_SetItem(dict, modstr, modname) < 0)
+ return NULL;
+ }
+ }
+ }
+ if (bases == NULL) {
+ bases = PyTuple_New(0);
+ if (bases == NULL)
+ return NULL;
+ }
+ else {
+ Py_ssize_t i, n;
+ PyObject *base;
+ if (!PyTuple_Check(bases)) {
+ PyErr_SetString(PyExc_TypeError,
+ "PyClass_New: bases must be a tuple");
+ return NULL;
+ }
+ n = PyTuple_Size(bases);
+ for (i = 0; i < n; i++) {
+ base = PyTuple_GET_ITEM(bases, i);
+ if (!PyClass_Check(base)) {
+ if (PyCallable_Check(
+ (PyObject *) base->ob_type))
+ return PyObject_CallFunctionObjArgs(
+ (PyObject *) base->ob_type,
+ name, bases, dict, NULL);
+ PyErr_SetString(PyExc_TypeError,
+ "PyClass_New: base must be a class");
+ return NULL;
+ }
+ }
+ Py_INCREF(bases);
+ }
+
+ if (getattrstr == NULL) {
+ getattrstr = PyString_InternFromString("__getattr__");
+ if (getattrstr == NULL)
+ goto alloc_error;
+ setattrstr = PyString_InternFromString("__setattr__");
+ if (setattrstr == NULL)
+ goto alloc_error;
+ delattrstr = PyString_InternFromString("__delattr__");
+ if (delattrstr == NULL)
+ goto alloc_error;
+ }
+
+ op = PyObject_GC_New(PyClassObject, &PyClass_Type);
+ if (op == NULL) {
alloc_error:
- Py_DECREF(bases);
- return NULL;
- }
- op->cl_bases = bases;
- Py_INCREF(dict);
- op->cl_dict = dict;
- Py_XINCREF(name);
- op->cl_name = name;
- op->cl_weakreflist = NULL;
-
- op->cl_getattr = class_lookup(op, getattrstr, &dummy);
- op->cl_setattr = class_lookup(op, setattrstr, &dummy);
- op->cl_delattr = class_lookup(op, delattrstr, &dummy);
- Py_XINCREF(op->cl_getattr);
- Py_XINCREF(op->cl_setattr);
- Py_XINCREF(op->cl_delattr);
- _PyObject_GC_TRACK(op);
- return (PyObject *) op;
+ Py_DECREF(bases);
+ return NULL;
+ }
+ op->cl_bases = bases;
+ Py_INCREF(dict);
+ op->cl_dict = dict;
+ Py_XINCREF(name);
+ op->cl_name = name;
+ op->cl_weakreflist = NULL;
+
+ op->cl_getattr = class_lookup(op, getattrstr, &dummy);
+ op->cl_setattr = class_lookup(op, setattrstr, &dummy);
+ op->cl_delattr = class_lookup(op, delattrstr, &dummy);
+ Py_XINCREF(op->cl_getattr);
+ Py_XINCREF(op->cl_setattr);
+ Py_XINCREF(op->cl_delattr);
+ _PyObject_GC_TRACK(op);
+ return (PyObject *) op;
}
PyObject *
PyMethod_Function(PyObject *im)
{
- if (!PyMethod_Check(im)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyMethodObject *)im)->im_func;
+ if (!PyMethod_Check(im)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyMethodObject *)im)->im_func;
}
PyObject *
PyMethod_Self(PyObject *im)
{
- if (!PyMethod_Check(im)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyMethodObject *)im)->im_self;
+ if (!PyMethod_Check(im)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyMethodObject *)im)->im_self;
}
PyObject *
PyMethod_Class(PyObject *im)
{
- if (!PyMethod_Check(im)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyMethodObject *)im)->im_class;
+ if (!PyMethod_Check(im)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyMethodObject *)im)->im_class;
}
PyDoc_STRVAR(class_doc,
@@ -174,13 +174,13 @@ a tuple of classes, and the third a dictionary.");
static PyObject *
class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *name, *bases, *dict;
- static char *kwlist[] = {"name", "bases", "dict", 0};
+ PyObject *name, *bases, *dict;
+ static char *kwlist[] = {"name", "bases", "dict", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
- &name, &bases, &dict))
- return NULL;
- return PyClass_New(bases, dict, name);
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "SOO", kwlist,
+ &name, &bases, &dict))
+ return NULL;
+ return PyClass_New(bases, dict, name);
}
/* Class methods */
@@ -188,315 +188,315 @@ class_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static void
class_dealloc(PyClassObject *op)
{
- _PyObject_GC_UNTRACK(op);
- if (op->cl_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) op);
- Py_DECREF(op->cl_bases);
- Py_DECREF(op->cl_dict);
- Py_XDECREF(op->cl_name);
- Py_XDECREF(op->cl_getattr);
- Py_XDECREF(op->cl_setattr);
- Py_XDECREF(op->cl_delattr);
- PyObject_GC_Del(op);
+ _PyObject_GC_UNTRACK(op);
+ if (op->cl_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) op);
+ Py_DECREF(op->cl_bases);
+ Py_DECREF(op->cl_dict);
+ Py_XDECREF(op->cl_name);
+ Py_XDECREF(op->cl_getattr);
+ Py_XDECREF(op->cl_setattr);
+ Py_XDECREF(op->cl_delattr);
+ PyObject_GC_Del(op);
}
static PyObject *
class_lookup(PyClassObject *cp, PyObject *name, PyClassObject **pclass)
{
- Py_ssize_t i, n;
- PyObject *value = PyDict_GetItem(cp->cl_dict, name);
- if (value != NULL) {
- *pclass = cp;
- return value;
- }
- n = PyTuple_Size(cp->cl_bases);
- for (i = 0; i < n; i++) {
- /* XXX What if one of the bases is not a class? */
- PyObject *v = class_lookup(
- (PyClassObject *)
- PyTuple_GetItem(cp->cl_bases, i), name, pclass);
- if (v != NULL)
- return v;
- }
- return NULL;
+ Py_ssize_t i, n;
+ PyObject *value = PyDict_GetItem(cp->cl_dict, name);
+ if (value != NULL) {
+ *pclass = cp;
+ return value;
+ }
+ n = PyTuple_Size(cp->cl_bases);
+ for (i = 0; i < n; i++) {
+ /* XXX What if one of the bases is not a class? */
+ PyObject *v = class_lookup(
+ (PyClassObject *)
+ PyTuple_GetItem(cp->cl_bases, i), name, pclass);
+ if (v != NULL)
+ return v;
+ }
+ return NULL;
}
static PyObject *
class_getattr(register PyClassObject *op, PyObject *name)
{
- register PyObject *v;
- register char *sname = PyString_AsString(name);
- PyClassObject *klass;
- descrgetfunc f;
-
- if (sname[0] == '_' && sname[1] == '_') {
- if (strcmp(sname, "__dict__") == 0) {
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "class.__dict__ not accessible in restricted mode");
- return NULL;
- }
- Py_INCREF(op->cl_dict);
- return op->cl_dict;
- }
- if (strcmp(sname, "__bases__") == 0) {
- Py_INCREF(op->cl_bases);
- return op->cl_bases;
- }
- if (strcmp(sname, "__name__") == 0) {
- if (op->cl_name == NULL)
- v = Py_None;
- else
- v = op->cl_name;
- Py_INCREF(v);
- return v;
- }
- }
- v = class_lookup(op, name, &klass);
- if (v == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "class %.50s has no attribute '%.400s'",
- PyString_AS_STRING(op->cl_name), sname);
- return NULL;
- }
- f = TP_DESCR_GET(v->ob_type);
- if (f == NULL)
- Py_INCREF(v);
- else
- v = f(v, (PyObject *)NULL, (PyObject *)op);
- return v;
+ register PyObject *v;
+ register char *sname = PyString_AsString(name);
+ PyClassObject *klass;
+ descrgetfunc f;
+
+ if (sname[0] == '_' && sname[1] == '_') {
+ if (strcmp(sname, "__dict__") == 0) {
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "class.__dict__ not accessible in restricted mode");
+ return NULL;
+ }
+ Py_INCREF(op->cl_dict);
+ return op->cl_dict;
+ }
+ if (strcmp(sname, "__bases__") == 0) {
+ Py_INCREF(op->cl_bases);
+ return op->cl_bases;
+ }
+ if (strcmp(sname, "__name__") == 0) {
+ if (op->cl_name == NULL)
+ v = Py_None;
+ else
+ v = op->cl_name;
+ Py_INCREF(v);
+ return v;
+ }
+ }
+ v = class_lookup(op, name, &klass);
+ if (v == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "class %.50s has no attribute '%.400s'",
+ PyString_AS_STRING(op->cl_name), sname);
+ return NULL;
+ }
+ f = TP_DESCR_GET(v->ob_type);
+ if (f == NULL)
+ Py_INCREF(v);
+ else
+ v = f(v, (PyObject *)NULL, (PyObject *)op);
+ return v;
}
static void
set_slot(PyObject **slot, PyObject *v)
{
- PyObject *temp = *slot;
- Py_XINCREF(v);
- *slot = v;
- Py_XDECREF(temp);
+ PyObject *temp = *slot;
+ Py_XINCREF(v);
+ *slot = v;
+ Py_XDECREF(temp);
}
static void
set_attr_slots(PyClassObject *c)
{
- PyClassObject *dummy;
+ PyClassObject *dummy;
- set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
- set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
- set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
+ set_slot(&c->cl_getattr, class_lookup(c, getattrstr, &dummy));
+ set_slot(&c->cl_setattr, class_lookup(c, setattrstr, &dummy));
+ set_slot(&c->cl_delattr, class_lookup(c, delattrstr, &dummy));
}
static char *
set_dict(PyClassObject *c, PyObject *v)
{
- if (v == NULL || !PyDict_Check(v))
- return "__dict__ must be a dictionary object";
- set_slot(&c->cl_dict, v);
- set_attr_slots(c);
- return "";
+ if (v == NULL || !PyDict_Check(v))
+ return "__dict__ must be a dictionary object";
+ set_slot(&c->cl_dict, v);
+ set_attr_slots(c);
+ return "";
}
static char *
set_bases(PyClassObject *c, PyObject *v)
{
- Py_ssize_t i, n;
+ Py_ssize_t i, n;
- if (v == NULL || !PyTuple_Check(v))
- return "__bases__ must be a tuple object";
- n = PyTuple_Size(v);
- for (i = 0; i < n; i++) {
- PyObject *x = PyTuple_GET_ITEM(v, i);
- if (!PyClass_Check(x))
- return "__bases__ items must be classes";
- if (PyClass_IsSubclass(x, (PyObject *)c))
- return "a __bases__ item causes an inheritance cycle";
- }
- set_slot(&c->cl_bases, v);
- set_attr_slots(c);
- return "";
+ if (v == NULL || !PyTuple_Check(v))
+ return "__bases__ must be a tuple object";
+ n = PyTuple_Size(v);
+ for (i = 0; i < n; i++) {
+ PyObject *x = PyTuple_GET_ITEM(v, i);
+ if (!PyClass_Check(x))
+ return "__bases__ items must be classes";
+ if (PyClass_IsSubclass(x, (PyObject *)c))
+ return "a __bases__ item causes an inheritance cycle";
+ }
+ set_slot(&c->cl_bases, v);
+ set_attr_slots(c);
+ return "";
}
static char *
set_name(PyClassObject *c, PyObject *v)
{
- if (v == NULL || !PyString_Check(v))
- return "__name__ must be a string object";
- if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
- return "__name__ must not contain null bytes";
- set_slot(&c->cl_name, v);
- return "";
+ if (v == NULL || !PyString_Check(v))
+ return "__name__ must be a string object";
+ if (strlen(PyString_AS_STRING(v)) != (size_t)PyString_GET_SIZE(v))
+ return "__name__ must not contain null bytes";
+ set_slot(&c->cl_name, v);
+ return "";
}
static int
class_setattr(PyClassObject *op, PyObject *name, PyObject *v)
{
- char *sname;
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "classes are read-only in restricted mode");
- return -1;
- }
- sname = PyString_AsString(name);
- if (sname[0] == '_' && sname[1] == '_') {
- Py_ssize_t n = PyString_Size(name);
- if (sname[n-1] == '_' && sname[n-2] == '_') {
- char *err = NULL;
- if (strcmp(sname, "__dict__") == 0)
- err = set_dict(op, v);
- else if (strcmp(sname, "__bases__") == 0)
- err = set_bases(op, v);
- else if (strcmp(sname, "__name__") == 0)
- err = set_name(op, v);
- else if (strcmp(sname, "__getattr__") == 0)
- set_slot(&op->cl_getattr, v);
- else if (strcmp(sname, "__setattr__") == 0)
- set_slot(&op->cl_setattr, v);
- else if (strcmp(sname, "__delattr__") == 0)
- set_slot(&op->cl_delattr, v);
- /* For the last three, we fall through to update the
- dictionary as well. */
- if (err != NULL) {
- if (*err == '\0')
- return 0;
- PyErr_SetString(PyExc_TypeError, err);
- return -1;
- }
- }
- }
- if (v == NULL) {
- int rv = PyDict_DelItem(op->cl_dict, name);
- if (rv < 0)
- PyErr_Format(PyExc_AttributeError,
- "class %.50s has no attribute '%.400s'",
- PyString_AS_STRING(op->cl_name), sname);
- return rv;
- }
- else
- return PyDict_SetItem(op->cl_dict, name, v);
+ char *sname;
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "classes are read-only in restricted mode");
+ return -1;
+ }
+ sname = PyString_AsString(name);
+ if (sname[0] == '_' && sname[1] == '_') {
+ Py_ssize_t n = PyString_Size(name);
+ if (sname[n-1] == '_' && sname[n-2] == '_') {
+ char *err = NULL;
+ if (strcmp(sname, "__dict__") == 0)
+ err = set_dict(op, v);
+ else if (strcmp(sname, "__bases__") == 0)
+ err = set_bases(op, v);
+ else if (strcmp(sname, "__name__") == 0)
+ err = set_name(op, v);
+ else if (strcmp(sname, "__getattr__") == 0)
+ set_slot(&op->cl_getattr, v);
+ else if (strcmp(sname, "__setattr__") == 0)
+ set_slot(&op->cl_setattr, v);
+ else if (strcmp(sname, "__delattr__") == 0)
+ set_slot(&op->cl_delattr, v);
+ /* For the last three, we fall through to update the
+ dictionary as well. */
+ if (err != NULL) {
+ if (*err == '\0')
+ return 0;
+ PyErr_SetString(PyExc_TypeError, err);
+ return -1;
+ }
+ }
+ }
+ if (v == NULL) {
+ int rv = PyDict_DelItem(op->cl_dict, name);
+ if (rv < 0)
+ PyErr_Format(PyExc_AttributeError,
+ "class %.50s has no attribute '%.400s'",
+ PyString_AS_STRING(op->cl_name), sname);
+ return rv;
+ }
+ else
+ return PyDict_SetItem(op->cl_dict, name, v);
}
static PyObject *
class_repr(PyClassObject *op)
{
- PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
- char *name;
- if (op->cl_name == NULL || !PyString_Check(op->cl_name))
- name = "?";
- else
- name = PyString_AsString(op->cl_name);
- if (mod == NULL || !PyString_Check(mod))
- return PyString_FromFormat("<class ?.%s at %p>", name, op);
- else
- return PyString_FromFormat("<class %s.%s at %p>",
- PyString_AsString(mod),
- name, op);
+ PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
+ char *name;
+ if (op->cl_name == NULL || !PyString_Check(op->cl_name))
+ name = "?";
+ else
+ name = PyString_AsString(op->cl_name);
+ if (mod == NULL || !PyString_Check(mod))
+ return PyString_FromFormat("<class ?.%s at %p>", name, op);
+ else
+ return PyString_FromFormat("<class %s.%s at %p>",
+ PyString_AsString(mod),
+ name, op);
}
static PyObject *
class_str(PyClassObject *op)
{
- PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
- PyObject *name = op->cl_name;
- PyObject *res;
- Py_ssize_t m, n;
-
- if (name == NULL || !PyString_Check(name))
- return class_repr(op);
- if (mod == NULL || !PyString_Check(mod)) {
- Py_INCREF(name);
- return name;
- }
- m = PyString_GET_SIZE(mod);
- n = PyString_GET_SIZE(name);
- res = PyString_FromStringAndSize((char *)NULL, m+1+n);
- if (res != NULL) {
- char *s = PyString_AS_STRING(res);
- memcpy(s, PyString_AS_STRING(mod), m);
- s += m;
- *s++ = '.';
- memcpy(s, PyString_AS_STRING(name), n);
- }
- return res;
+ PyObject *mod = PyDict_GetItemString(op->cl_dict, "__module__");
+ PyObject *name = op->cl_name;
+ PyObject *res;
+ Py_ssize_t m, n;
+
+ if (name == NULL || !PyString_Check(name))
+ return class_repr(op);
+ if (mod == NULL || !PyString_Check(mod)) {
+ Py_INCREF(name);
+ return name;
+ }
+ m = PyString_GET_SIZE(mod);
+ n = PyString_GET_SIZE(name);
+ res = PyString_FromStringAndSize((char *)NULL, m+1+n);
+ if (res != NULL) {
+ char *s = PyString_AS_STRING(res);
+ memcpy(s, PyString_AS_STRING(mod), m);
+ s += m;
+ *s++ = '.';
+ memcpy(s, PyString_AS_STRING(name), n);
+ }
+ return res;
}
static int
class_traverse(PyClassObject *o, visitproc visit, void *arg)
{
- Py_VISIT(o->cl_bases);
- Py_VISIT(o->cl_dict);
- Py_VISIT(o->cl_name);
- Py_VISIT(o->cl_getattr);
- Py_VISIT(o->cl_setattr);
- Py_VISIT(o->cl_delattr);
- return 0;
+ Py_VISIT(o->cl_bases);
+ Py_VISIT(o->cl_dict);
+ Py_VISIT(o->cl_name);
+ Py_VISIT(o->cl_getattr);
+ Py_VISIT(o->cl_setattr);
+ Py_VISIT(o->cl_delattr);
+ return 0;
}
PyTypeObject PyClass_Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0,
- "classobj",
- sizeof(PyClassObject),
- 0,
- (destructor)class_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)class_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- PyInstance_New, /* tp_call */
- (reprfunc)class_str, /* tp_str */
- (getattrofunc)class_getattr, /* tp_getattro */
- (setattrofunc)class_setattr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- class_doc, /* tp_doc */
- (traverseproc)class_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyClassObject, cl_weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- class_new, /* tp_new */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "classobj",
+ sizeof(PyClassObject),
+ 0,
+ (destructor)class_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)class_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ PyInstance_New, /* tp_call */
+ (reprfunc)class_str, /* tp_str */
+ (getattrofunc)class_getattr, /* tp_getattro */
+ (setattrofunc)class_setattr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ class_doc, /* tp_doc */
+ (traverseproc)class_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyClassObject, cl_weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ class_new, /* tp_new */
};
int
PyClass_IsSubclass(PyObject *klass, PyObject *base)
{
- Py_ssize_t i, n;
- PyClassObject *cp;
- if (klass == base)
- return 1;
- if (PyTuple_Check(base)) {
- n = PyTuple_GET_SIZE(base);
- for (i = 0; i < n; i++) {
- if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
- return 1;
- }
- return 0;
- }
- if (klass == NULL || !PyClass_Check(klass))
- return 0;
- cp = (PyClassObject *)klass;
- n = PyTuple_Size(cp->cl_bases);
- for (i = 0; i < n; i++) {
- if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
- return 1;
- }
- return 0;
+ Py_ssize_t i, n;
+ PyClassObject *cp;
+ if (klass == base)
+ return 1;
+ if (PyTuple_Check(base)) {
+ n = PyTuple_GET_SIZE(base);
+ for (i = 0; i < n; i++) {
+ if (PyClass_IsSubclass(klass, PyTuple_GET_ITEM(base, i)))
+ return 1;
+ }
+ return 0;
+ }
+ if (klass == NULL || !PyClass_Check(klass))
+ return 0;
+ cp = (PyClassObject *)klass;
+ n = PyTuple_Size(cp->cl_bases);
+ for (i = 0; i < n; i++) {
+ if (PyClass_IsSubclass(PyTuple_GetItem(cp->cl_bases, i), base))
+ return 1;
+ }
+ return 0;
}
@@ -505,86 +505,86 @@ PyClass_IsSubclass(PyObject *klass, PyObject *base)
PyObject *
PyInstance_NewRaw(PyObject *klass, PyObject *dict)
{
- PyInstanceObject *inst;
-
- if (!PyClass_Check(klass)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- if (dict == NULL) {
- dict = PyDict_New();
- if (dict == NULL)
- return NULL;
- }
- else {
- if (!PyDict_Check(dict)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- Py_INCREF(dict);
- }
- inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
- if (inst == NULL) {
- Py_DECREF(dict);
- return NULL;
- }
- inst->in_weakreflist = NULL;
- Py_INCREF(klass);
- inst->in_class = (PyClassObject *)klass;
- inst->in_dict = dict;
- _PyObject_GC_TRACK(inst);
- return (PyObject *)inst;
+ PyInstanceObject *inst;
+
+ if (!PyClass_Check(klass)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ if (dict == NULL) {
+ dict = PyDict_New();
+ if (dict == NULL)
+ return NULL;
+ }
+ else {
+ if (!PyDict_Check(dict)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ Py_INCREF(dict);
+ }
+ inst = PyObject_GC_New(PyInstanceObject, &PyInstance_Type);
+ if (inst == NULL) {
+ Py_DECREF(dict);
+ return NULL;
+ }
+ inst->in_weakreflist = NULL;
+ Py_INCREF(klass);
+ inst->in_class = (PyClassObject *)klass;
+ inst->in_dict = dict;
+ _PyObject_GC_TRACK(inst);
+ return (PyObject *)inst;
}
PyObject *
PyInstance_New(PyObject *klass, PyObject *arg, PyObject *kw)
{
- register PyInstanceObject *inst;
- PyObject *init;
- static PyObject *initstr;
-
- if (initstr == NULL) {
- initstr = PyString_InternFromString("__init__");
- if (initstr == NULL)
- return NULL;
- }
- inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
- if (inst == NULL)
- return NULL;
- init = instance_getattr2(inst, initstr);
- if (init == NULL) {
- if (PyErr_Occurred()) {
- Py_DECREF(inst);
- return NULL;
- }
- if ((arg != NULL && (!PyTuple_Check(arg) ||
- PyTuple_Size(arg) != 0))
- || (kw != NULL && (!PyDict_Check(kw) ||
- PyDict_Size(kw) != 0))) {
- PyErr_SetString(PyExc_TypeError,
- "this constructor takes no arguments");
- Py_DECREF(inst);
- inst = NULL;
- }
- }
- else {
- PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
- Py_DECREF(init);
- if (res == NULL) {
- Py_DECREF(inst);
- inst = NULL;
- }
- else {
- if (res != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "__init__() should return None");
- Py_DECREF(inst);
- inst = NULL;
- }
- Py_DECREF(res);
- }
- }
- return (PyObject *)inst;
+ register PyInstanceObject *inst;
+ PyObject *init;
+ static PyObject *initstr;
+
+ if (initstr == NULL) {
+ initstr = PyString_InternFromString("__init__");
+ if (initstr == NULL)
+ return NULL;
+ }
+ inst = (PyInstanceObject *) PyInstance_NewRaw(klass, NULL);
+ if (inst == NULL)
+ return NULL;
+ init = instance_getattr2(inst, initstr);
+ if (init == NULL) {
+ if (PyErr_Occurred()) {
+ Py_DECREF(inst);
+ return NULL;
+ }
+ if ((arg != NULL && (!PyTuple_Check(arg) ||
+ PyTuple_Size(arg) != 0))
+ || (kw != NULL && (!PyDict_Check(kw) ||
+ PyDict_Size(kw) != 0))) {
+ PyErr_SetString(PyExc_TypeError,
+ "this constructor takes no arguments");
+ Py_DECREF(inst);
+ inst = NULL;
+ }
+ }
+ else {
+ PyObject *res = PyEval_CallObjectWithKeywords(init, arg, kw);
+ Py_DECREF(init);
+ if (res == NULL) {
+ Py_DECREF(inst);
+ inst = NULL;
+ }
+ else {
+ if (res != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "__init__() should return None");
+ Py_DECREF(inst);
+ inst = NULL;
+ }
+ Py_DECREF(res);
+ }
+ }
+ return (PyObject *)inst;
}
/* Instance methods */
@@ -599,174 +599,174 @@ If present, dict must be a dictionary or None.");
static PyObject *
instance_new(PyTypeObject* type, PyObject* args, PyObject *kw)
{
- PyObject *klass;
- PyObject *dict = Py_None;
+ PyObject *klass;
+ PyObject *dict = Py_None;
- if (!PyArg_ParseTuple(args, "O!|O:instance",
- &PyClass_Type, &klass, &dict))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O!|O:instance",
+ &PyClass_Type, &klass, &dict))
+ return NULL;
- if (dict == Py_None)
- dict = NULL;
- else if (!PyDict_Check(dict)) {
- PyErr_SetString(PyExc_TypeError,
- "instance() second arg must be dictionary or None");
- return NULL;
- }
- return PyInstance_NewRaw(klass, dict);
+ if (dict == Py_None)
+ dict = NULL;
+ else if (!PyDict_Check(dict)) {
+ PyErr_SetString(PyExc_TypeError,
+ "instance() second arg must be dictionary or None");
+ return NULL;
+ }
+ return PyInstance_NewRaw(klass, dict);
}
static void
instance_dealloc(register PyInstanceObject *inst)
{
- PyObject *error_type, *error_value, *error_traceback;
- PyObject *del;
- static PyObject *delstr;
-
- _PyObject_GC_UNTRACK(inst);
- if (inst->in_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) inst);
-
- /* Temporarily resurrect the object. */
- assert(inst->ob_type == &PyInstance_Type);
- assert(inst->ob_refcnt == 0);
- inst->ob_refcnt = 1;
-
- /* Save the current exception, if any. */
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
- /* Execute __del__ method, if any. */
- if (delstr == NULL) {
- delstr = PyString_InternFromString("__del__");
- if (delstr == NULL)
- PyErr_WriteUnraisable((PyObject*)inst);
- }
- if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
- PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
- if (res == NULL)
- PyErr_WriteUnraisable(del);
- else
- Py_DECREF(res);
- Py_DECREF(del);
- }
- /* Restore the saved exception. */
- PyErr_Restore(error_type, error_value, error_traceback);
-
- /* Undo the temporary resurrection; can't use DECREF here, it would
- * cause a recursive call.
- */
- assert(inst->ob_refcnt > 0);
- if (--inst->ob_refcnt == 0) {
-
- /* New weakrefs could be created during the finalizer call.
- If this occurs, clear them out without calling their
- finalizers since they might rely on part of the object
- being finalized that has already been destroyed. */
- while (inst->in_weakreflist != NULL) {
- _PyWeakref_ClearRef((PyWeakReference *)
- (inst->in_weakreflist));
- }
-
- Py_DECREF(inst->in_class);
- Py_XDECREF(inst->in_dict);
- PyObject_GC_Del(inst);
- }
- else {
- Py_ssize_t refcnt = inst->ob_refcnt;
- /* __del__ resurrected it! Make it look like the original
- * Py_DECREF never happened.
- */
- _Py_NewReference((PyObject *)inst);
- inst->ob_refcnt = refcnt;
- _PyObject_GC_TRACK(inst);
- /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
- * we need to undo that. */
- _Py_DEC_REFTOTAL;
- /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
- * object chain, so no more to do there.
- * If COUNT_ALLOCS, the original decref bumped tp_frees, and
- * _Py_NewReference bumped tp_allocs: both of those need to be
- * undone.
- */
+ PyObject *error_type, *error_value, *error_traceback;
+ PyObject *del;
+ static PyObject *delstr;
+
+ _PyObject_GC_UNTRACK(inst);
+ if (inst->in_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) inst);
+
+ /* Temporarily resurrect the object. */
+ assert(inst->ob_type == &PyInstance_Type);
+ assert(inst->ob_refcnt == 0);
+ inst->ob_refcnt = 1;
+
+ /* Save the current exception, if any. */
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ /* Execute __del__ method, if any. */
+ if (delstr == NULL) {
+ delstr = PyString_InternFromString("__del__");
+ if (delstr == NULL)
+ PyErr_WriteUnraisable((PyObject*)inst);
+ }
+ if (delstr && (del = instance_getattr2(inst, delstr)) != NULL) {
+ PyObject *res = PyEval_CallObject(del, (PyObject *)NULL);
+ if (res == NULL)
+ PyErr_WriteUnraisable(del);
+ else
+ Py_DECREF(res);
+ Py_DECREF(del);
+ }
+ /* Restore the saved exception. */
+ PyErr_Restore(error_type, error_value, error_traceback);
+
+ /* Undo the temporary resurrection; can't use DECREF here, it would
+ * cause a recursive call.
+ */
+ assert(inst->ob_refcnt > 0);
+ if (--inst->ob_refcnt == 0) {
+
+ /* New weakrefs could be created during the finalizer call.
+ If this occurs, clear them out without calling their
+ finalizers since they might rely on part of the object
+ being finalized that has already been destroyed. */
+ while (inst->in_weakreflist != NULL) {
+ _PyWeakref_ClearRef((PyWeakReference *)
+ (inst->in_weakreflist));
+ }
+
+ Py_DECREF(inst->in_class);
+ Py_XDECREF(inst->in_dict);
+ PyObject_GC_Del(inst);
+ }
+ else {
+ Py_ssize_t refcnt = inst->ob_refcnt;
+ /* __del__ resurrected it! Make it look like the original
+ * Py_DECREF never happened.
+ */
+ _Py_NewReference((PyObject *)inst);
+ inst->ob_refcnt = refcnt;
+ _PyObject_GC_TRACK(inst);
+ /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
+ * we need to undo that. */
+ _Py_DEC_REFTOTAL;
+ /* If Py_TRACE_REFS, _Py_NewReference re-added self to the
+ * object chain, so no more to do there.
+ * If COUNT_ALLOCS, the original decref bumped tp_frees, and
+ * _Py_NewReference bumped tp_allocs: both of those need to be
+ * undone.
+ */
#ifdef COUNT_ALLOCS
- --inst->ob_type->tp_frees;
- --inst->ob_type->tp_allocs;
+ --inst->ob_type->tp_frees;
+ --inst->ob_type->tp_allocs;
#endif
- }
+ }
}
static PyObject *
instance_getattr1(register PyInstanceObject *inst, PyObject *name)
{
- register PyObject *v;
- register char *sname = PyString_AsString(name);
- if (sname[0] == '_' && sname[1] == '_') {
- if (strcmp(sname, "__dict__") == 0) {
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "instance.__dict__ not accessible in restricted mode");
- return NULL;
- }
- Py_INCREF(inst->in_dict);
- return inst->in_dict;
- }
- if (strcmp(sname, "__class__") == 0) {
- Py_INCREF(inst->in_class);
- return (PyObject *)inst->in_class;
- }
- }
- v = instance_getattr2(inst, name);
- if (v == NULL && !PyErr_Occurred()) {
- PyErr_Format(PyExc_AttributeError,
- "%.50s instance has no attribute '%.400s'",
- PyString_AS_STRING(inst->in_class->cl_name), sname);
- }
- return v;
+ register PyObject *v;
+ register char *sname = PyString_AsString(name);
+ if (sname[0] == '_' && sname[1] == '_') {
+ if (strcmp(sname, "__dict__") == 0) {
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "instance.__dict__ not accessible in restricted mode");
+ return NULL;
+ }
+ Py_INCREF(inst->in_dict);
+ return inst->in_dict;
+ }
+ if (strcmp(sname, "__class__") == 0) {
+ Py_INCREF(inst->in_class);
+ return (PyObject *)inst->in_class;
+ }
+ }
+ v = instance_getattr2(inst, name);
+ if (v == NULL && !PyErr_Occurred()) {
+ PyErr_Format(PyExc_AttributeError,
+ "%.50s instance has no attribute '%.400s'",
+ PyString_AS_STRING(inst->in_class->cl_name), sname);
+ }
+ return v;
}
static PyObject *
instance_getattr2(register PyInstanceObject *inst, PyObject *name)
{
- register PyObject *v;
- PyClassObject *klass;
- descrgetfunc f;
-
- v = PyDict_GetItem(inst->in_dict, name);
- if (v != NULL) {
- Py_INCREF(v);
- return v;
- }
- v = class_lookup(inst->in_class, name, &klass);
- if (v != NULL) {
- Py_INCREF(v);
- f = TP_DESCR_GET(v->ob_type);
- if (f != NULL) {
- PyObject *w = f(v, (PyObject *)inst,
- (PyObject *)(inst->in_class));
- Py_DECREF(v);
- v = w;
- }
- }
- return v;
+ register PyObject *v;
+ PyClassObject *klass;
+ descrgetfunc f;
+
+ v = PyDict_GetItem(inst->in_dict, name);
+ if (v != NULL) {
+ Py_INCREF(v);
+ return v;
+ }
+ v = class_lookup(inst->in_class, name, &klass);
+ if (v != NULL) {
+ Py_INCREF(v);
+ f = TP_DESCR_GET(v->ob_type);
+ if (f != NULL) {
+ PyObject *w = f(v, (PyObject *)inst,
+ (PyObject *)(inst->in_class));
+ Py_DECREF(v);
+ v = w;
+ }
+ }
+ return v;
}
static PyObject *
instance_getattr(register PyInstanceObject *inst, PyObject *name)
{
- register PyObject *func, *res;
- res = instance_getattr1(inst, name);
- if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
- PyObject *args;
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- args = PyTuple_Pack(2, inst, name);
- if (args == NULL)
- return NULL;
- res = PyEval_CallObject(func, args);
- Py_DECREF(args);
- }
- return res;
+ register PyObject *func, *res;
+ res = instance_getattr1(inst, name);
+ if (res == NULL && (func = inst->in_class->cl_getattr) != NULL) {
+ PyObject *args;
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ args = PyTuple_Pack(2, inst, name);
+ if (args == NULL)
+ return NULL;
+ res = PyEval_CallObject(func, args);
+ Py_DECREF(args);
+ }
+ return res;
}
/* See classobject.h comments: this only does dict lookups, and is always
@@ -775,235 +775,235 @@ instance_getattr(register PyInstanceObject *inst, PyObject *name)
PyObject *
_PyInstance_Lookup(PyObject *pinst, PyObject *name)
{
- PyObject *v;
- PyClassObject *klass;
- PyInstanceObject *inst; /* pinst cast to the right type */
+ PyObject *v;
+ PyClassObject *klass;
+ PyInstanceObject *inst; /* pinst cast to the right type */
- assert(PyInstance_Check(pinst));
- inst = (PyInstanceObject *)pinst;
+ assert(PyInstance_Check(pinst));
+ inst = (PyInstanceObject *)pinst;
- assert(PyString_Check(name));
+ assert(PyString_Check(name));
- v = PyDict_GetItem(inst->in_dict, name);
- if (v == NULL)
- v = class_lookup(inst->in_class, name, &klass);
- return v;
+ v = PyDict_GetItem(inst->in_dict, name);
+ if (v == NULL)
+ v = class_lookup(inst->in_class, name, &klass);
+ return v;
}
static int
instance_setattr1(PyInstanceObject *inst, PyObject *name, PyObject *v)
{
- if (v == NULL) {
- int rv = PyDict_DelItem(inst->in_dict, name);
- if (rv < 0)
- PyErr_Format(PyExc_AttributeError,
- "%.50s instance has no attribute '%.400s'",
- PyString_AS_STRING(inst->in_class->cl_name),
- PyString_AS_STRING(name));
- return rv;
- }
- else
- return PyDict_SetItem(inst->in_dict, name, v);
+ if (v == NULL) {
+ int rv = PyDict_DelItem(inst->in_dict, name);
+ if (rv < 0)
+ PyErr_Format(PyExc_AttributeError,
+ "%.50s instance has no attribute '%.400s'",
+ PyString_AS_STRING(inst->in_class->cl_name),
+ PyString_AS_STRING(name));
+ return rv;
+ }
+ else
+ return PyDict_SetItem(inst->in_dict, name, v);
}
static int
instance_setattr(PyInstanceObject *inst, PyObject *name, PyObject *v)
{
- PyObject *func, *args, *res, *tmp;
- char *sname = PyString_AsString(name);
- if (sname[0] == '_' && sname[1] == '_') {
- Py_ssize_t n = PyString_Size(name);
- if (sname[n-1] == '_' && sname[n-2] == '_') {
- if (strcmp(sname, "__dict__") == 0) {
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "__dict__ not accessible in restricted mode");
- return -1;
- }
- if (v == NULL || !PyDict_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "__dict__ must be set to a dictionary");
- return -1;
- }
- tmp = inst->in_dict;
- Py_INCREF(v);
- inst->in_dict = v;
- Py_DECREF(tmp);
- return 0;
- }
- if (strcmp(sname, "__class__") == 0) {
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "__class__ not accessible in restricted mode");
- return -1;
- }
- if (v == NULL || !PyClass_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "__class__ must be set to a class");
- return -1;
- }
- tmp = (PyObject *)(inst->in_class);
- Py_INCREF(v);
- inst->in_class = (PyClassObject *)v;
- Py_DECREF(tmp);
- return 0;
- }
- }
- }
- if (v == NULL)
- func = inst->in_class->cl_delattr;
- else
- func = inst->in_class->cl_setattr;
- if (func == NULL)
- return instance_setattr1(inst, name, v);
- if (v == NULL)
- args = PyTuple_Pack(2, inst, name);
- else
- args = PyTuple_Pack(3, inst, name, v);
- if (args == NULL)
- return -1;
- res = PyEval_CallObject(func, args);
- Py_DECREF(args);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *func, *args, *res, *tmp;
+ char *sname = PyString_AsString(name);
+ if (sname[0] == '_' && sname[1] == '_') {
+ Py_ssize_t n = PyString_Size(name);
+ if (sname[n-1] == '_' && sname[n-2] == '_') {
+ if (strcmp(sname, "__dict__") == 0) {
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "__dict__ not accessible in restricted mode");
+ return -1;
+ }
+ if (v == NULL || !PyDict_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__dict__ must be set to a dictionary");
+ return -1;
+ }
+ tmp = inst->in_dict;
+ Py_INCREF(v);
+ inst->in_dict = v;
+ Py_DECREF(tmp);
+ return 0;
+ }
+ if (strcmp(sname, "__class__") == 0) {
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "__class__ not accessible in restricted mode");
+ return -1;
+ }
+ if (v == NULL || !PyClass_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__class__ must be set to a class");
+ return -1;
+ }
+ tmp = (PyObject *)(inst->in_class);
+ Py_INCREF(v);
+ inst->in_class = (PyClassObject *)v;
+ Py_DECREF(tmp);
+ return 0;
+ }
+ }
+ }
+ if (v == NULL)
+ func = inst->in_class->cl_delattr;
+ else
+ func = inst->in_class->cl_setattr;
+ if (func == NULL)
+ return instance_setattr1(inst, name, v);
+ if (v == NULL)
+ args = PyTuple_Pack(2, inst, name);
+ else
+ args = PyTuple_Pack(3, inst, name, v);
+ if (args == NULL)
+ return -1;
+ res = PyEval_CallObject(func, args);
+ Py_DECREF(args);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static PyObject *
instance_repr(PyInstanceObject *inst)
{
- PyObject *func;
- PyObject *res;
- static PyObject *reprstr;
-
- if (reprstr == NULL) {
- reprstr = PyString_InternFromString("__repr__");
- if (reprstr == NULL)
- return NULL;
- }
- func = instance_getattr(inst, reprstr);
- if (func == NULL) {
- PyObject *classname, *mod;
- char *cname;
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- classname = inst->in_class->cl_name;
- mod = PyDict_GetItemString(inst->in_class->cl_dict,
- "__module__");
- if (classname != NULL && PyString_Check(classname))
- cname = PyString_AsString(classname);
- else
- cname = "?";
- if (mod == NULL || !PyString_Check(mod))
- return PyString_FromFormat("<?.%s instance at %p>",
- cname, inst);
- else
- return PyString_FromFormat("<%s.%s instance at %p>",
- PyString_AsString(mod),
- cname, inst);
- }
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- return res;
+ PyObject *func;
+ PyObject *res;
+ static PyObject *reprstr;
+
+ if (reprstr == NULL) {
+ reprstr = PyString_InternFromString("__repr__");
+ if (reprstr == NULL)
+ return NULL;
+ }
+ func = instance_getattr(inst, reprstr);
+ if (func == NULL) {
+ PyObject *classname, *mod;
+ char *cname;
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ classname = inst->in_class->cl_name;
+ mod = PyDict_GetItemString(inst->in_class->cl_dict,
+ "__module__");
+ if (classname != NULL && PyString_Check(classname))
+ cname = PyString_AsString(classname);
+ else
+ cname = "?";
+ if (mod == NULL || !PyString_Check(mod))
+ return PyString_FromFormat("<?.%s instance at %p>",
+ cname, inst);
+ else
+ return PyString_FromFormat("<%s.%s instance at %p>",
+ PyString_AsString(mod),
+ cname, inst);
+ }
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ return res;
}
static PyObject *
instance_str(PyInstanceObject *inst)
{
- PyObject *func;
- PyObject *res;
- static PyObject *strstr;
-
- if (strstr == NULL) {
- strstr = PyString_InternFromString("__str__");
- if (strstr == NULL)
- return NULL;
- }
- func = instance_getattr(inst, strstr);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- return instance_repr(inst);
- }
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- return res;
+ PyObject *func;
+ PyObject *res;
+ static PyObject *strstr;
+
+ if (strstr == NULL) {
+ strstr = PyString_InternFromString("__str__");
+ if (strstr == NULL)
+ return NULL;
+ }
+ func = instance_getattr(inst, strstr);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ return instance_repr(inst);
+ }
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ return res;
}
static long
instance_hash(PyInstanceObject *inst)
{
- PyObject *func;
- PyObject *res;
- long outcome;
- static PyObject *hashstr, *eqstr, *cmpstr;
-
- if (hashstr == NULL) {
- hashstr = PyString_InternFromString("__hash__");
- if (hashstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, hashstr);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- /* If there is no __eq__ and no __cmp__ method, we hash on the
- address. If an __eq__ or __cmp__ method exists, there must
- be a __hash__. */
- if (eqstr == NULL) {
- eqstr = PyString_InternFromString("__eq__");
- if (eqstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, eqstr);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- if (cmpstr == NULL) {
- cmpstr = PyString_InternFromString("__cmp__");
- if (cmpstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, cmpstr);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(
- PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- return _Py_HashPointer(inst);
- }
- }
- Py_XDECREF(func);
- PyErr_SetString(PyExc_TypeError, "unhashable instance");
- return -1;
- }
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- if (res == NULL)
- return -1;
- if (PyInt_Check(res) || PyLong_Check(res))
- /* This already converts a -1 result to -2. */
- outcome = res->ob_type->tp_hash(res);
- else {
- PyErr_SetString(PyExc_TypeError,
- "__hash__() should return an int");
- outcome = -1;
- }
- Py_DECREF(res);
- return outcome;
+ PyObject *func;
+ PyObject *res;
+ long outcome;
+ static PyObject *hashstr, *eqstr, *cmpstr;
+
+ if (hashstr == NULL) {
+ hashstr = PyString_InternFromString("__hash__");
+ if (hashstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, hashstr);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ /* If there is no __eq__ and no __cmp__ method, we hash on the
+ address. If an __eq__ or __cmp__ method exists, there must
+ be a __hash__. */
+ if (eqstr == NULL) {
+ eqstr = PyString_InternFromString("__eq__");
+ if (eqstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, eqstr);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ if (cmpstr == NULL) {
+ cmpstr = PyString_InternFromString("__cmp__");
+ if (cmpstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, cmpstr);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(
+ PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ return _Py_HashPointer(inst);
+ }
+ }
+ Py_XDECREF(func);
+ PyErr_SetString(PyExc_TypeError, "unhashable instance");
+ return -1;
+ }
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ if (res == NULL)
+ return -1;
+ if (PyInt_Check(res) || PyLong_Check(res))
+ /* This already converts a -1 result to -2. */
+ outcome = res->ob_type->tp_hash(res);
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "__hash__() should return an int");
+ outcome = -1;
+ }
+ Py_DECREF(res);
+ return outcome;
}
static int
instance_traverse(PyInstanceObject *o, visitproc visit, void *arg)
{
- Py_VISIT(o->in_class);
- Py_VISIT(o->in_dict);
- return 0;
+ Py_VISIT(o->in_class);
+ Py_VISIT(o->in_dict);
+ return 0;
}
static PyObject *getitemstr, *setitemstr, *delitemstr, *lenstr;
@@ -1012,413 +1012,413 @@ static PyObject *iterstr, *nextstr;
static Py_ssize_t
instance_length(PyInstanceObject *inst)
{
- PyObject *func;
- PyObject *res;
- Py_ssize_t outcome;
-
- if (lenstr == NULL) {
- lenstr = PyString_InternFromString("__len__");
- if (lenstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, lenstr);
- if (func == NULL)
- return -1;
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- if (res == NULL)
- return -1;
- if (PyInt_Check(res)) {
- outcome = PyInt_AsSsize_t(res);
- if (outcome == -1 && PyErr_Occurred()) {
- Py_DECREF(res);
- return -1;
- }
+ PyObject *func;
+ PyObject *res;
+ Py_ssize_t outcome;
+
+ if (lenstr == NULL) {
+ lenstr = PyString_InternFromString("__len__");
+ if (lenstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, lenstr);
+ if (func == NULL)
+ return -1;
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ if (res == NULL)
+ return -1;
+ if (PyInt_Check(res)) {
+ outcome = PyInt_AsSsize_t(res);
+ if (outcome == -1 && PyErr_Occurred()) {
+ Py_DECREF(res);
+ return -1;
+ }
#if SIZEOF_SIZE_T < SIZEOF_INT
- /* Overflow check -- range of PyInt is more than C int */
- if (outcome != (int)outcome) {
- PyErr_SetString(PyExc_OverflowError,
- "__len__() should return 0 <= outcome < 2**31");
- outcome = -1;
- }
- else
+ /* Overflow check -- range of PyInt is more than C int */
+ if (outcome != (int)outcome) {
+ PyErr_SetString(PyExc_OverflowError,
+ "__len__() should return 0 <= outcome < 2**31");
+ outcome = -1;
+ }
+ else
#endif
- if (outcome < 0) {
- PyErr_SetString(PyExc_ValueError,
- "__len__() should return >= 0");
- outcome = -1;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "__len__() should return an int");
- outcome = -1;
- }
- Py_DECREF(res);
- return outcome;
+ if (outcome < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "__len__() should return >= 0");
+ outcome = -1;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "__len__() should return an int");
+ outcome = -1;
+ }
+ Py_DECREF(res);
+ return outcome;
}
static PyObject *
instance_subscript(PyInstanceObject *inst, PyObject *key)
{
- PyObject *func;
- PyObject *arg;
- PyObject *res;
-
- if (getitemstr == NULL) {
- getitemstr = PyString_InternFromString("__getitem__");
- if (getitemstr == NULL)
- return NULL;
- }
- func = instance_getattr(inst, getitemstr);
- if (func == NULL)
- return NULL;
- arg = PyTuple_Pack(1, key);
- if (arg == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(func);
- Py_DECREF(arg);
- return res;
+ PyObject *func;
+ PyObject *arg;
+ PyObject *res;
+
+ if (getitemstr == NULL) {
+ getitemstr = PyString_InternFromString("__getitem__");
+ if (getitemstr == NULL)
+ return NULL;
+ }
+ func = instance_getattr(inst, getitemstr);
+ if (func == NULL)
+ return NULL;
+ arg = PyTuple_Pack(1, key);
+ if (arg == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(func);
+ Py_DECREF(arg);
+ return res;
}
static int
instance_ass_subscript(PyInstanceObject *inst, PyObject *key, PyObject *value)
{
- PyObject *func;
- PyObject *arg;
- PyObject *res;
-
- if (value == NULL) {
- if (delitemstr == NULL) {
- delitemstr = PyString_InternFromString("__delitem__");
- if (delitemstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, delitemstr);
- }
- else {
- if (setitemstr == NULL) {
- setitemstr = PyString_InternFromString("__setitem__");
- if (setitemstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, setitemstr);
- }
- if (func == NULL)
- return -1;
- if (value == NULL)
- arg = PyTuple_Pack(1, key);
- else
- arg = PyTuple_Pack(2, key, value);
- if (arg == NULL) {
- Py_DECREF(func);
- return -1;
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(func);
- Py_DECREF(arg);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *func;
+ PyObject *arg;
+ PyObject *res;
+
+ if (value == NULL) {
+ if (delitemstr == NULL) {
+ delitemstr = PyString_InternFromString("__delitem__");
+ if (delitemstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, delitemstr);
+ }
+ else {
+ if (setitemstr == NULL) {
+ setitemstr = PyString_InternFromString("__setitem__");
+ if (setitemstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, setitemstr);
+ }
+ if (func == NULL)
+ return -1;
+ if (value == NULL)
+ arg = PyTuple_Pack(1, key);
+ else
+ arg = PyTuple_Pack(2, key, value);
+ if (arg == NULL) {
+ Py_DECREF(func);
+ return -1;
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(func);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static PyMappingMethods instance_as_mapping = {
- (lenfunc)instance_length, /* mp_length */
- (binaryfunc)instance_subscript, /* mp_subscript */
- (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
+ (lenfunc)instance_length, /* mp_length */
+ (binaryfunc)instance_subscript, /* mp_subscript */
+ (objobjargproc)instance_ass_subscript, /* mp_ass_subscript */
};
static PyObject *
instance_item(PyInstanceObject *inst, Py_ssize_t i)
{
- PyObject *func, *res;
+ PyObject *func, *res;
- if (getitemstr == NULL) {
- getitemstr = PyString_InternFromString("__getitem__");
- if (getitemstr == NULL)
- return NULL;
- }
- func = instance_getattr(inst, getitemstr);
- if (func == NULL)
- return NULL;
- res = PyObject_CallFunction(func, "n", i);
- Py_DECREF(func);
- return res;
+ if (getitemstr == NULL) {
+ getitemstr = PyString_InternFromString("__getitem__");
+ if (getitemstr == NULL)
+ return NULL;
+ }
+ func = instance_getattr(inst, getitemstr);
+ if (func == NULL)
+ return NULL;
+ res = PyObject_CallFunction(func, "n", i);
+ Py_DECREF(func);
+ return res;
}
static PyObject *
instance_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j)
{
- PyObject *func, *arg, *res;
- static PyObject *getslicestr;
-
- if (getslicestr == NULL) {
- getslicestr = PyString_InternFromString("__getslice__");
- if (getslicestr == NULL)
- return NULL;
- }
- func = instance_getattr(inst, getslicestr);
-
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
-
- if (getitemstr == NULL) {
- getitemstr = PyString_InternFromString("__getitem__");
- if (getitemstr == NULL)
- return NULL;
- }
- func = instance_getattr(inst, getitemstr);
- if (func == NULL)
- return NULL;
- arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
- }
- else {
- if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
- "use __getitem__", 1) < 0) {
- Py_DECREF(func);
- return NULL;
- }
- arg = Py_BuildValue("(nn)", i, j);
- }
-
- if (arg == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(func);
- Py_DECREF(arg);
- return res;
+ PyObject *func, *arg, *res;
+ static PyObject *getslicestr;
+
+ if (getslicestr == NULL) {
+ getslicestr = PyString_InternFromString("__getslice__");
+ if (getslicestr == NULL)
+ return NULL;
+ }
+ func = instance_getattr(inst, getslicestr);
+
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+
+ if (getitemstr == NULL) {
+ getitemstr = PyString_InternFromString("__getitem__");
+ if (getitemstr == NULL)
+ return NULL;
+ }
+ func = instance_getattr(inst, getitemstr);
+ if (func == NULL)
+ return NULL;
+ arg = Py_BuildValue("(N)", _PySlice_FromIndices(i, j));
+ }
+ else {
+ if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
+ "use __getitem__", 1) < 0) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ arg = Py_BuildValue("(nn)", i, j);
+ }
+
+ if (arg == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(func);
+ Py_DECREF(arg);
+ return res;
}
static int
instance_ass_item(PyInstanceObject *inst, Py_ssize_t i, PyObject *item)
{
- PyObject *func, *arg, *res;
-
- if (item == NULL) {
- if (delitemstr == NULL) {
- delitemstr = PyString_InternFromString("__delitem__");
- if (delitemstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, delitemstr);
- }
- else {
- if (setitemstr == NULL) {
- setitemstr = PyString_InternFromString("__setitem__");
- if (setitemstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, setitemstr);
- }
- if (func == NULL)
- return -1;
- if (item == NULL)
- arg = PyInt_FromSsize_t(i);
- else
- arg = Py_BuildValue("(nO)", i, item);
- if (arg == NULL) {
- Py_DECREF(func);
- return -1;
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(func);
- Py_DECREF(arg);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *func, *arg, *res;
+
+ if (item == NULL) {
+ if (delitemstr == NULL) {
+ delitemstr = PyString_InternFromString("__delitem__");
+ if (delitemstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, delitemstr);
+ }
+ else {
+ if (setitemstr == NULL) {
+ setitemstr = PyString_InternFromString("__setitem__");
+ if (setitemstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, setitemstr);
+ }
+ if (func == NULL)
+ return -1;
+ if (item == NULL)
+ arg = PyInt_FromSsize_t(i);
+ else
+ arg = Py_BuildValue("(nO)", i, item);
+ if (arg == NULL) {
+ Py_DECREF(func);
+ return -1;
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(func);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
instance_ass_slice(PyInstanceObject *inst, Py_ssize_t i, Py_ssize_t j, PyObject *value)
{
- PyObject *func, *arg, *res;
- static PyObject *setslicestr, *delslicestr;
-
- if (value == NULL) {
- if (delslicestr == NULL) {
- delslicestr =
- PyString_InternFromString("__delslice__");
- if (delslicestr == NULL)
- return -1;
- }
- func = instance_getattr(inst, delslicestr);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- if (delitemstr == NULL) {
- delitemstr =
- PyString_InternFromString("__delitem__");
- if (delitemstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, delitemstr);
- if (func == NULL)
- return -1;
-
- arg = Py_BuildValue("(N)",
- _PySlice_FromIndices(i, j));
- }
- else {
- if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
- "removed; use __delitem__", 1) < 0) {
- Py_DECREF(func);
- return -1;
- }
- arg = Py_BuildValue("(nn)", i, j);
- }
- }
- else {
- if (setslicestr == NULL) {
- setslicestr =
- PyString_InternFromString("__setslice__");
- if (setslicestr == NULL)
- return -1;
- }
- func = instance_getattr(inst, setslicestr);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- if (setitemstr == NULL) {
- setitemstr =
- PyString_InternFromString("__setitem__");
- if (setitemstr == NULL)
- return -1;
- }
- func = instance_getattr(inst, setitemstr);
- if (func == NULL)
- return -1;
-
- arg = Py_BuildValue("(NO)",
- _PySlice_FromIndices(i, j), value);
- }
- else {
- if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
- "removed; use __setitem__", 1) < 0) {
- Py_DECREF(func);
- return -1;
- }
- arg = Py_BuildValue("(nnO)", i, j, value);
- }
- }
- if (arg == NULL) {
- Py_DECREF(func);
- return -1;
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(func);
- Py_DECREF(arg);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *func, *arg, *res;
+ static PyObject *setslicestr, *delslicestr;
+
+ if (value == NULL) {
+ if (delslicestr == NULL) {
+ delslicestr =
+ PyString_InternFromString("__delslice__");
+ if (delslicestr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, delslicestr);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ if (delitemstr == NULL) {
+ delitemstr =
+ PyString_InternFromString("__delitem__");
+ if (delitemstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, delitemstr);
+ if (func == NULL)
+ return -1;
+
+ arg = Py_BuildValue("(N)",
+ _PySlice_FromIndices(i, j));
+ }
+ else {
+ if (PyErr_WarnPy3k("in 3.x, __delslice__ has been "
+ "removed; use __delitem__", 1) < 0) {
+ Py_DECREF(func);
+ return -1;
+ }
+ arg = Py_BuildValue("(nn)", i, j);
+ }
+ }
+ else {
+ if (setslicestr == NULL) {
+ setslicestr =
+ PyString_InternFromString("__setslice__");
+ if (setslicestr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, setslicestr);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ if (setitemstr == NULL) {
+ setitemstr =
+ PyString_InternFromString("__setitem__");
+ if (setitemstr == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, setitemstr);
+ if (func == NULL)
+ return -1;
+
+ arg = Py_BuildValue("(NO)",
+ _PySlice_FromIndices(i, j), value);
+ }
+ else {
+ if (PyErr_WarnPy3k("in 3.x, __setslice__ has been "
+ "removed; use __setitem__", 1) < 0) {
+ Py_DECREF(func);
+ return -1;
+ }
+ arg = Py_BuildValue("(nnO)", i, j, value);
+ }
+ }
+ if (arg == NULL) {
+ Py_DECREF(func);
+ return -1;
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(func);
+ Py_DECREF(arg);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
instance_contains(PyInstanceObject *inst, PyObject *member)
{
- static PyObject *__contains__;
- PyObject *func;
-
- /* Try __contains__ first.
- * If that can't be done, try iterator-based searching.
- */
-
- if(__contains__ == NULL) {
- __contains__ = PyString_InternFromString("__contains__");
- if(__contains__ == NULL)
- return -1;
- }
- func = instance_getattr(inst, __contains__);
- if (func) {
- PyObject *res;
- int ret;
- PyObject *arg = PyTuple_Pack(1, member);
- if(arg == NULL) {
- Py_DECREF(func);
- return -1;
- }
- res = PyEval_CallObject(func, arg);
- Py_DECREF(func);
- Py_DECREF(arg);
- if(res == NULL)
- return -1;
- ret = PyObject_IsTrue(res);
- Py_DECREF(res);
- return ret;
- }
-
- /* Couldn't find __contains__. */
- if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
- Py_ssize_t rc;
- /* Assume the failure was simply due to that there is no
- * __contains__ attribute, and try iterating instead.
- */
- PyErr_Clear();
- rc = _PySequence_IterSearch((PyObject *)inst, member,
- PY_ITERSEARCH_CONTAINS);
- if (rc >= 0)
- return rc > 0;
- }
- return -1;
+ static PyObject *__contains__;
+ PyObject *func;
+
+ /* Try __contains__ first.
+ * If that can't be done, try iterator-based searching.
+ */
+
+ if(__contains__ == NULL) {
+ __contains__ = PyString_InternFromString("__contains__");
+ if(__contains__ == NULL)
+ return -1;
+ }
+ func = instance_getattr(inst, __contains__);
+ if (func) {
+ PyObject *res;
+ int ret;
+ PyObject *arg = PyTuple_Pack(1, member);
+ if(arg == NULL) {
+ Py_DECREF(func);
+ return -1;
+ }
+ res = PyEval_CallObject(func, arg);
+ Py_DECREF(func);
+ Py_DECREF(arg);
+ if(res == NULL)
+ return -1;
+ ret = PyObject_IsTrue(res);
+ Py_DECREF(res);
+ return ret;
+ }
+
+ /* Couldn't find __contains__. */
+ if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ Py_ssize_t rc;
+ /* Assume the failure was simply due to that there is no
+ * __contains__ attribute, and try iterating instead.
+ */
+ PyErr_Clear();
+ rc = _PySequence_IterSearch((PyObject *)inst, member,
+ PY_ITERSEARCH_CONTAINS);
+ if (rc >= 0)
+ return rc > 0;
+ }
+ return -1;
}
static PySequenceMethods
instance_as_sequence = {
- (lenfunc)instance_length, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)instance_item, /* sq_item */
- (ssizessizeargfunc)instance_slice, /* sq_slice */
- (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
- (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
- (objobjproc)instance_contains, /* sq_contains */
+ (lenfunc)instance_length, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ (ssizeargfunc)instance_item, /* sq_item */
+ (ssizessizeargfunc)instance_slice, /* sq_slice */
+ (ssizeobjargproc)instance_ass_item, /* sq_ass_item */
+ (ssizessizeobjargproc)instance_ass_slice,/* sq_ass_slice */
+ (objobjproc)instance_contains, /* sq_contains */
};
static PyObject *
generic_unary_op(PyInstanceObject *self, PyObject *methodname)
{
- PyObject *func, *res;
+ PyObject *func, *res;
- if ((func = instance_getattr(self, methodname)) == NULL)
- return NULL;
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- return res;
+ if ((func = instance_getattr(self, methodname)) == NULL)
+ return NULL;
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ return res;
}
static PyObject *
generic_binary_op(PyObject *v, PyObject *w, char *opname)
{
- PyObject *result;
- PyObject *args;
- PyObject *func = PyObject_GetAttrString(v, opname);
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- args = PyTuple_Pack(1, w);
- if (args == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- result = PyEval_CallObject(func, args);
- Py_DECREF(args);
- Py_DECREF(func);
- return result;
+ PyObject *result;
+ PyObject *args;
+ PyObject *func = PyObject_GetAttrString(v, opname);
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ args = PyTuple_Pack(1, w);
+ if (args == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ result = PyEval_CallObject(func, args);
+ Py_DECREF(args);
+ Py_DECREF(func);
+ return result;
}
@@ -1427,70 +1427,70 @@ static PyObject *coerce_obj;
/* Try one half of a binary operator involving a class instance. */
static PyObject *
half_binop(PyObject *v, PyObject *w, char *opname, binaryfunc thisfunc,
- int swapped)
-{
- PyObject *args;
- PyObject *coercefunc;
- PyObject *coerced = NULL;
- PyObject *v1;
- PyObject *result;
-
- if (!PyInstance_Check(v)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- if (coerce_obj == NULL) {
- coerce_obj = PyString_InternFromString("__coerce__");
- if (coerce_obj == NULL)
- return NULL;
- }
- coercefunc = PyObject_GetAttr(v, coerce_obj);
- if (coercefunc == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- return generic_binary_op(v, w, opname);
- }
-
- args = PyTuple_Pack(1, w);
- if (args == NULL) {
- Py_DECREF(coercefunc);
- return NULL;
- }
- coerced = PyEval_CallObject(coercefunc, args);
- Py_DECREF(args);
- Py_DECREF(coercefunc);
- if (coerced == NULL) {
- return NULL;
- }
- if (coerced == Py_None || coerced == Py_NotImplemented) {
- Py_DECREF(coerced);
- return generic_binary_op(v, w, opname);
- }
- if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
- Py_DECREF(coerced);
- PyErr_SetString(PyExc_TypeError,
- "coercion should return None or 2-tuple");
- return NULL;
- }
- v1 = PyTuple_GetItem(coerced, 0);
- w = PyTuple_GetItem(coerced, 1);
- if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
- /* prevent recursion if __coerce__ returns self as the first
- * argument */
- result = generic_binary_op(v1, w, opname);
- } else {
- if (Py_EnterRecursiveCall(" after coercion"))
- return NULL;
- if (swapped)
- result = (thisfunc)(w, v1);
- else
- result = (thisfunc)(v1, w);
- Py_LeaveRecursiveCall();
- }
- Py_DECREF(coerced);
- return result;
+ int swapped)
+{
+ PyObject *args;
+ PyObject *coercefunc;
+ PyObject *coerced = NULL;
+ PyObject *v1;
+ PyObject *result;
+
+ if (!PyInstance_Check(v)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ if (coerce_obj == NULL) {
+ coerce_obj = PyString_InternFromString("__coerce__");
+ if (coerce_obj == NULL)
+ return NULL;
+ }
+ coercefunc = PyObject_GetAttr(v, coerce_obj);
+ if (coercefunc == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ return generic_binary_op(v, w, opname);
+ }
+
+ args = PyTuple_Pack(1, w);
+ if (args == NULL) {
+ Py_DECREF(coercefunc);
+ return NULL;
+ }
+ coerced = PyEval_CallObject(coercefunc, args);
+ Py_DECREF(args);
+ Py_DECREF(coercefunc);
+ if (coerced == NULL) {
+ return NULL;
+ }
+ if (coerced == Py_None || coerced == Py_NotImplemented) {
+ Py_DECREF(coerced);
+ return generic_binary_op(v, w, opname);
+ }
+ if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
+ Py_DECREF(coerced);
+ PyErr_SetString(PyExc_TypeError,
+ "coercion should return None or 2-tuple");
+ return NULL;
+ }
+ v1 = PyTuple_GetItem(coerced, 0);
+ w = PyTuple_GetItem(coerced, 1);
+ if (v1->ob_type == v->ob_type && PyInstance_Check(v)) {
+ /* prevent recursion if __coerce__ returns self as the first
+ * argument */
+ result = generic_binary_op(v1, w, opname);
+ } else {
+ if (Py_EnterRecursiveCall(" after coercion"))
+ return NULL;
+ if (swapped)
+ result = (thisfunc)(w, v1);
+ else
+ result = (thisfunc)(v1, w);
+ Py_LeaveRecursiveCall();
+ }
+ Py_DECREF(coerced);
+ return result;
}
/* Implement a binary operator involving at least one class instance. */
@@ -1498,110 +1498,110 @@ static PyObject *
do_binop(PyObject *v, PyObject *w, char *opname, char *ropname,
binaryfunc thisfunc)
{
- PyObject *result = half_binop(v, w, opname, thisfunc, 0);
- if (result == Py_NotImplemented) {
- Py_DECREF(result);
- result = half_binop(w, v, ropname, thisfunc, 1);
- }
- return result;
+ PyObject *result = half_binop(v, w, opname, thisfunc, 0);
+ if (result == Py_NotImplemented) {
+ Py_DECREF(result);
+ result = half_binop(w, v, ropname, thisfunc, 1);
+ }
+ return result;
}
static PyObject *
do_binop_inplace(PyObject *v, PyObject *w, char *iopname, char *opname,
- char *ropname, binaryfunc thisfunc)
+ char *ropname, binaryfunc thisfunc)
{
- PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
- if (result == Py_NotImplemented) {
- Py_DECREF(result);
- result = do_binop(v, w, opname, ropname, thisfunc);
- }
- return result;
+ PyObject *result = half_binop(v, w, iopname, thisfunc, 0);
+ if (result == Py_NotImplemented) {
+ Py_DECREF(result);
+ result = do_binop(v, w, opname, ropname, thisfunc);
+ }
+ return result;
}
static int
instance_coerce(PyObject **pv, PyObject **pw)
{
- PyObject *v = *pv;
- PyObject *w = *pw;
- PyObject *coercefunc;
- PyObject *args;
- PyObject *coerced;
-
- if (coerce_obj == NULL) {
- coerce_obj = PyString_InternFromString("__coerce__");
- if (coerce_obj == NULL)
- return -1;
- }
- coercefunc = PyObject_GetAttr(v, coerce_obj);
- if (coercefunc == NULL) {
- /* No __coerce__ method */
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- return 1;
- }
- /* Has __coerce__ method: call it */
- args = PyTuple_Pack(1, w);
- if (args == NULL) {
- return -1;
- }
- coerced = PyEval_CallObject(coercefunc, args);
- Py_DECREF(args);
- Py_DECREF(coercefunc);
- if (coerced == NULL) {
- /* __coerce__ call raised an exception */
- return -1;
- }
- if (coerced == Py_None || coerced == Py_NotImplemented) {
- /* __coerce__ says "I can't do it" */
- Py_DECREF(coerced);
- return 1;
- }
- if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
- /* __coerce__ return value is malformed */
- Py_DECREF(coerced);
- PyErr_SetString(PyExc_TypeError,
- "coercion should return None or 2-tuple");
- return -1;
- }
- /* __coerce__ returned two new values */
- *pv = PyTuple_GetItem(coerced, 0);
- *pw = PyTuple_GetItem(coerced, 1);
- Py_INCREF(*pv);
- Py_INCREF(*pw);
- Py_DECREF(coerced);
- return 0;
+ PyObject *v = *pv;
+ PyObject *w = *pw;
+ PyObject *coercefunc;
+ PyObject *args;
+ PyObject *coerced;
+
+ if (coerce_obj == NULL) {
+ coerce_obj = PyString_InternFromString("__coerce__");
+ if (coerce_obj == NULL)
+ return -1;
+ }
+ coercefunc = PyObject_GetAttr(v, coerce_obj);
+ if (coercefunc == NULL) {
+ /* No __coerce__ method */
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ return 1;
+ }
+ /* Has __coerce__ method: call it */
+ args = PyTuple_Pack(1, w);
+ if (args == NULL) {
+ return -1;
+ }
+ coerced = PyEval_CallObject(coercefunc, args);
+ Py_DECREF(args);
+ Py_DECREF(coercefunc);
+ if (coerced == NULL) {
+ /* __coerce__ call raised an exception */
+ return -1;
+ }
+ if (coerced == Py_None || coerced == Py_NotImplemented) {
+ /* __coerce__ says "I can't do it" */
+ Py_DECREF(coerced);
+ return 1;
+ }
+ if (!PyTuple_Check(coerced) || PyTuple_Size(coerced) != 2) {
+ /* __coerce__ return value is malformed */
+ Py_DECREF(coerced);
+ PyErr_SetString(PyExc_TypeError,
+ "coercion should return None or 2-tuple");
+ return -1;
+ }
+ /* __coerce__ returned two new values */
+ *pv = PyTuple_GetItem(coerced, 0);
+ *pw = PyTuple_GetItem(coerced, 1);
+ Py_INCREF(*pv);
+ Py_INCREF(*pw);
+ Py_DECREF(coerced);
+ return 0;
}
#define UNARY(funcname, methodname) \
static PyObject *funcname(PyInstanceObject *self) { \
- static PyObject *o; \
- if (o == NULL) { o = PyString_InternFromString(methodname); \
- if (o == NULL) return NULL; } \
- return generic_unary_op(self, o); \
+ static PyObject *o; \
+ if (o == NULL) { o = PyString_InternFromString(methodname); \
+ if (o == NULL) return NULL; } \
+ return generic_unary_op(self, o); \
}
/* unary function with a fallback */
#define UNARY_FB(funcname, methodname, funcname_fb) \
static PyObject *funcname(PyInstanceObject *self) { \
- static PyObject *o; \
- if (o == NULL) { o = PyString_InternFromString(methodname); \
- if (o == NULL) return NULL; } \
- if (PyObject_HasAttr((PyObject*)self, o)) \
- return generic_unary_op(self, o); \
- else \
- return funcname_fb(self); \
+ static PyObject *o; \
+ if (o == NULL) { o = PyString_InternFromString(methodname); \
+ if (o == NULL) return NULL; } \
+ if (PyObject_HasAttr((PyObject*)self, o)) \
+ return generic_unary_op(self, o); \
+ else \
+ return funcname_fb(self); \
}
#define BINARY(f, m, n) \
static PyObject *f(PyObject *v, PyObject *w) { \
- return do_binop(v, w, "__" m "__", "__r" m "__", n); \
+ return do_binop(v, w, "__" m "__", "__r" m "__", n); \
}
#define BINARY_INPLACE(f, m, n) \
static PyObject *f(PyObject *v, PyObject *w) { \
- return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
- "__r" m "__", n); \
+ return do_binop_inplace(v, w, "__i" m "__", "__" m "__", \
+ "__r" m "__", n); \
}
UNARY(instance_neg, "__neg__")
@@ -1645,55 +1645,55 @@ BINARY_INPLACE(instance_itruediv, "truediv", PyNumber_InPlaceTrueDivide)
static int
half_cmp(PyObject *v, PyObject *w)
{
- static PyObject *cmp_obj;
- PyObject *args;
- PyObject *cmp_func;
- PyObject *result;
- long l;
-
- assert(PyInstance_Check(v));
-
- if (cmp_obj == NULL) {
- cmp_obj = PyString_InternFromString("__cmp__");
- if (cmp_obj == NULL)
- return -2;
- }
-
- cmp_func = PyObject_GetAttr(v, cmp_obj);
- if (cmp_func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -2;
- PyErr_Clear();
- return 2;
- }
-
- args = PyTuple_Pack(1, w);
- if (args == NULL) {
- Py_DECREF(cmp_func);
- return -2;
- }
-
- result = PyEval_CallObject(cmp_func, args);
- Py_DECREF(args);
- Py_DECREF(cmp_func);
-
- if (result == NULL)
- return -2;
-
- if (result == Py_NotImplemented) {
- Py_DECREF(result);
- return 2;
- }
-
- l = PyInt_AsLong(result);
- Py_DECREF(result);
- if (l == -1 && PyErr_Occurred()) {
- PyErr_SetString(PyExc_TypeError,
- "comparison did not return an int");
- return -2;
- }
-
- return l < 0 ? -1 : l > 0 ? 1 : 0;
+ static PyObject *cmp_obj;
+ PyObject *args;
+ PyObject *cmp_func;
+ PyObject *result;
+ long l;
+
+ assert(PyInstance_Check(v));
+
+ if (cmp_obj == NULL) {
+ cmp_obj = PyString_InternFromString("__cmp__");
+ if (cmp_obj == NULL)
+ return -2;
+ }
+
+ cmp_func = PyObject_GetAttr(v, cmp_obj);
+ if (cmp_func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -2;
+ PyErr_Clear();
+ return 2;
+ }
+
+ args = PyTuple_Pack(1, w);
+ if (args == NULL) {
+ Py_DECREF(cmp_func);
+ return -2;
+ }
+
+ result = PyEval_CallObject(cmp_func, args);
+ Py_DECREF(args);
+ Py_DECREF(cmp_func);
+
+ if (result == NULL)
+ return -2;
+
+ if (result == Py_NotImplemented) {
+ Py_DECREF(result);
+ return 2;
+ }
+
+ l = PyInt_AsLong(result);
+ Py_DECREF(result);
+ if (l == -1 && PyErr_Occurred()) {
+ PyErr_SetString(PyExc_TypeError,
+ "comparison did not return an int");
+ return -2;
+ }
+
+ return l < 0 ? -1 : l > 0 ? 1 : 0;
}
/* Try a 3-way comparison, returning an int; either v or w is an instance.
@@ -1708,124 +1708,124 @@ half_cmp(PyObject *v, PyObject *w)
static int
instance_compare(PyObject *v, PyObject *w)
{
- int c;
-
- c = PyNumber_CoerceEx(&v, &w);
- if (c < 0)
- return -2;
- if (c == 0) {
- /* If neither is now an instance, use regular comparison */
- if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
- c = PyObject_Compare(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- if (PyErr_Occurred())
- return -2;
- return c < 0 ? -1 : c > 0 ? 1 : 0;
- }
- }
- else {
- /* The coercion didn't do anything.
- Treat this the same as returning v and w unchanged. */
- Py_INCREF(v);
- Py_INCREF(w);
- }
-
- if (PyInstance_Check(v)) {
- c = half_cmp(v, w);
- if (c <= 1) {
- Py_DECREF(v);
- Py_DECREF(w);
- return c;
- }
- }
- if (PyInstance_Check(w)) {
- c = half_cmp(w, v);
- if (c <= 1) {
- Py_DECREF(v);
- Py_DECREF(w);
- if (c >= -1)
- c = -c;
- return c;
- }
- }
- Py_DECREF(v);
- Py_DECREF(w);
- return 2;
+ int c;
+
+ c = PyNumber_CoerceEx(&v, &w);
+ if (c < 0)
+ return -2;
+ if (c == 0) {
+ /* If neither is now an instance, use regular comparison */
+ if (!PyInstance_Check(v) && !PyInstance_Check(w)) {
+ c = PyObject_Compare(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ if (PyErr_Occurred())
+ return -2;
+ return c < 0 ? -1 : c > 0 ? 1 : 0;
+ }
+ }
+ else {
+ /* The coercion didn't do anything.
+ Treat this the same as returning v and w unchanged. */
+ Py_INCREF(v);
+ Py_INCREF(w);
+ }
+
+ if (PyInstance_Check(v)) {
+ c = half_cmp(v, w);
+ if (c <= 1) {
+ Py_DECREF(v);
+ Py_DECREF(w);
+ return c;
+ }
+ }
+ if (PyInstance_Check(w)) {
+ c = half_cmp(w, v);
+ if (c <= 1) {
+ Py_DECREF(v);
+ Py_DECREF(w);
+ if (c >= -1)
+ c = -c;
+ return c;
+ }
+ }
+ Py_DECREF(v);
+ Py_DECREF(w);
+ return 2;
}
static int
instance_nonzero(PyInstanceObject *self)
{
- PyObject *func, *res;
- long outcome;
- static PyObject *nonzerostr;
-
- if (nonzerostr == NULL) {
- nonzerostr = PyString_InternFromString("__nonzero__");
- if (nonzerostr == NULL)
- return -1;
- }
- if ((func = instance_getattr(self, nonzerostr)) == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- if (lenstr == NULL) {
- lenstr = PyString_InternFromString("__len__");
- if (lenstr == NULL)
- return -1;
- }
- if ((func = instance_getattr(self, lenstr)) == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_Clear();
- /* Fall back to the default behavior:
- all instances are nonzero */
- return 1;
- }
- }
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- if (res == NULL)
- return -1;
- if (!PyInt_Check(res)) {
- Py_DECREF(res);
- PyErr_SetString(PyExc_TypeError,
- "__nonzero__ should return an int");
- return -1;
- }
- outcome = PyInt_AsLong(res);
- Py_DECREF(res);
- if (outcome < 0) {
- PyErr_SetString(PyExc_ValueError,
- "__nonzero__ should return >= 0");
- return -1;
- }
- return outcome > 0;
+ PyObject *func, *res;
+ long outcome;
+ static PyObject *nonzerostr;
+
+ if (nonzerostr == NULL) {
+ nonzerostr = PyString_InternFromString("__nonzero__");
+ if (nonzerostr == NULL)
+ return -1;
+ }
+ if ((func = instance_getattr(self, nonzerostr)) == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ if (lenstr == NULL) {
+ lenstr = PyString_InternFromString("__len__");
+ if (lenstr == NULL)
+ return -1;
+ }
+ if ((func = instance_getattr(self, lenstr)) == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_Clear();
+ /* Fall back to the default behavior:
+ all instances are nonzero */
+ return 1;
+ }
+ }
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ if (res == NULL)
+ return -1;
+ if (!PyInt_Check(res)) {
+ Py_DECREF(res);
+ PyErr_SetString(PyExc_TypeError,
+ "__nonzero__ should return an int");
+ return -1;
+ }
+ outcome = PyInt_AsLong(res);
+ Py_DECREF(res);
+ if (outcome < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "__nonzero__ should return >= 0");
+ return -1;
+ }
+ return outcome > 0;
}
static PyObject *
instance_index(PyInstanceObject *self)
{
- PyObject *func, *res;
- static PyObject *indexstr = NULL;
+ PyObject *func, *res;
+ static PyObject *indexstr = NULL;
- if (indexstr == NULL) {
- indexstr = PyString_InternFromString("__index__");
- if (indexstr == NULL)
- return NULL;
- }
- if ((func = instance_getattr(self, indexstr)) == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- PyErr_SetString(PyExc_TypeError,
- "object cannot be interpreted as an index");
- return NULL;
- }
- res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- return res;
+ if (indexstr == NULL) {
+ indexstr = PyString_InternFromString("__index__");
+ if (indexstr == NULL)
+ return NULL;
+ }
+ if ((func = instance_getattr(self, indexstr)) == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ PyErr_SetString(PyExc_TypeError,
+ "object cannot be interpreted as an index");
+ return NULL;
+ }
+ res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ return res;
}
@@ -1835,22 +1835,22 @@ UNARY(_instance_trunc, "__trunc__")
static PyObject *
instance_int(PyInstanceObject *self)
{
- PyObject *truncated;
- static PyObject *int_name;
- if (int_name == NULL) {
- int_name = PyString_InternFromString("__int__");
- if (int_name == NULL)
- return NULL;
- }
- if (PyObject_HasAttr((PyObject*)self, int_name))
- return generic_unary_op(self, int_name);
+ PyObject *truncated;
+ static PyObject *int_name;
+ if (int_name == NULL) {
+ int_name = PyString_InternFromString("__int__");
+ if (int_name == NULL)
+ return NULL;
+ }
+ if (PyObject_HasAttr((PyObject*)self, int_name))
+ return generic_unary_op(self, int_name);
- truncated = _instance_trunc(self);
- /* __trunc__ is specified to return an Integral type, but
- int() needs to return an int. */
- return _PyNumber_ConvertIntegralToInt(
- truncated,
- "__trunc__ returned non-Integral (type %.200s)");
+ truncated = _instance_trunc(self);
+ /* __trunc__ is specified to return an Integral type, but
+ int() needs to return an int. */
+ return _PyNumber_ConvertIntegralToInt(
+ truncated,
+ "__trunc__ returned non-Integral (type %.200s)");
}
UNARY_FB(instance_long, "__long__", instance_int)
@@ -1861,74 +1861,74 @@ UNARY(instance_hex, "__hex__")
static PyObject *
bin_power(PyObject *v, PyObject *w)
{
- return PyNumber_Power(v, w, Py_None);
+ return PyNumber_Power(v, w, Py_None);
}
/* This version is for ternary calls only (z != None) */
static PyObject *
instance_pow(PyObject *v, PyObject *w, PyObject *z)
{
- if (z == Py_None) {
- return do_binop(v, w, "__pow__", "__rpow__", bin_power);
- }
- else {
- PyObject *func;
- PyObject *args;
- PyObject *result;
-
- /* XXX Doesn't do coercions... */
- func = PyObject_GetAttrString(v, "__pow__");
- if (func == NULL)
- return NULL;
- args = PyTuple_Pack(2, w, z);
- if (args == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- result = PyEval_CallObject(func, args);
- Py_DECREF(func);
- Py_DECREF(args);
- return result;
- }
+ if (z == Py_None) {
+ return do_binop(v, w, "__pow__", "__rpow__", bin_power);
+ }
+ else {
+ PyObject *func;
+ PyObject *args;
+ PyObject *result;
+
+ /* XXX Doesn't do coercions... */
+ func = PyObject_GetAttrString(v, "__pow__");
+ if (func == NULL)
+ return NULL;
+ args = PyTuple_Pack(2, w, z);
+ if (args == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ result = PyEval_CallObject(func, args);
+ Py_DECREF(func);
+ Py_DECREF(args);
+ return result;
+ }
}
static PyObject *
bin_inplace_power(PyObject *v, PyObject *w)
{
- return PyNumber_InPlacePower(v, w, Py_None);
+ return PyNumber_InPlacePower(v, w, Py_None);
}
static PyObject *
instance_ipow(PyObject *v, PyObject *w, PyObject *z)
{
- if (z == Py_None) {
- return do_binop_inplace(v, w, "__ipow__", "__pow__",
- "__rpow__", bin_inplace_power);
- }
- else {
- /* XXX Doesn't do coercions... */
- PyObject *func;
- PyObject *args;
- PyObject *result;
-
- func = PyObject_GetAttrString(v, "__ipow__");
- if (func == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- return instance_pow(v, w, z);
- }
- args = PyTuple_Pack(2, w, z);
- if (args == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- result = PyEval_CallObject(func, args);
- Py_DECREF(func);
- Py_DECREF(args);
- return result;
- }
+ if (z == Py_None) {
+ return do_binop_inplace(v, w, "__ipow__", "__pow__",
+ "__rpow__", bin_inplace_power);
+ }
+ else {
+ /* XXX Doesn't do coercions... */
+ PyObject *func;
+ PyObject *args;
+ PyObject *result;
+
+ func = PyObject_GetAttrString(v, "__ipow__");
+ if (func == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ return instance_pow(v, w, z);
+ }
+ args = PyTuple_Pack(2, w, z);
+ if (args == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ result = PyEval_CallObject(func, args);
+ Py_DECREF(func);
+ Py_DECREF(args);
+ return result;
+ }
}
@@ -1939,93 +1939,93 @@ static PyObject **name_op = NULL;
static int
init_name_op(void)
{
- int i;
- char *_name_op[] = {
- "__lt__",
- "__le__",
- "__eq__",
- "__ne__",
- "__gt__",
- "__ge__",
- };
-
- name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
- if (name_op == NULL)
- return -1;
- for (i = 0; i < NAME_OPS; ++i) {
- name_op[i] = PyString_InternFromString(_name_op[i]);
- if (name_op[i] == NULL)
- return -1;
- }
- return 0;
+ int i;
+ char *_name_op[] = {
+ "__lt__",
+ "__le__",
+ "__eq__",
+ "__ne__",
+ "__gt__",
+ "__ge__",
+ };
+
+ name_op = (PyObject **)malloc(sizeof(PyObject *) * NAME_OPS);
+ if (name_op == NULL)
+ return -1;
+ for (i = 0; i < NAME_OPS; ++i) {
+ name_op[i] = PyString_InternFromString(_name_op[i]);
+ if (name_op[i] == NULL)
+ return -1;
+ }
+ return 0;
}
static PyObject *
half_richcompare(PyObject *v, PyObject *w, int op)
{
- PyObject *method;
- PyObject *args;
- PyObject *res;
-
- assert(PyInstance_Check(v));
-
- if (name_op == NULL) {
- if (init_name_op() < 0)
- return NULL;
- }
- /* If the instance doesn't define an __getattr__ method, use
- instance_getattr2 directly because it will not set an
- exception on failure. */
- if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
- method = instance_getattr2((PyInstanceObject *)v,
- name_op[op]);
- else
- method = PyObject_GetAttr(v, name_op[op]);
- if (method == NULL) {
- if (PyErr_Occurred()) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- }
- res = Py_NotImplemented;
- Py_INCREF(res);
- return res;
- }
-
- args = PyTuple_Pack(1, w);
- if (args == NULL) {
- Py_DECREF(method);
- return NULL;
- }
-
- res = PyEval_CallObject(method, args);
- Py_DECREF(args);
- Py_DECREF(method);
-
- return res;
+ PyObject *method;
+ PyObject *args;
+ PyObject *res;
+
+ assert(PyInstance_Check(v));
+
+ if (name_op == NULL) {
+ if (init_name_op() < 0)
+ return NULL;
+ }
+ /* If the instance doesn't define an __getattr__ method, use
+ instance_getattr2 directly because it will not set an
+ exception on failure. */
+ if (((PyInstanceObject *)v)->in_class->cl_getattr == NULL)
+ method = instance_getattr2((PyInstanceObject *)v,
+ name_op[op]);
+ else
+ method = PyObject_GetAttr(v, name_op[op]);
+ if (method == NULL) {
+ if (PyErr_Occurred()) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ }
+ res = Py_NotImplemented;
+ Py_INCREF(res);
+ return res;
+ }
+
+ args = PyTuple_Pack(1, w);
+ if (args == NULL) {
+ Py_DECREF(method);
+ return NULL;
+ }
+
+ res = PyEval_CallObject(method, args);
+ Py_DECREF(args);
+ Py_DECREF(method);
+
+ return res;
}
static PyObject *
instance_richcompare(PyObject *v, PyObject *w, int op)
{
- PyObject *res;
+ PyObject *res;
- if (PyInstance_Check(v)) {
- res = half_richcompare(v, w, op);
- if (res != Py_NotImplemented)
- return res;
- Py_DECREF(res);
- }
+ if (PyInstance_Check(v)) {
+ res = half_richcompare(v, w, op);
+ if (res != Py_NotImplemented)
+ return res;
+ Py_DECREF(res);
+ }
- if (PyInstance_Check(w)) {
- res = half_richcompare(w, v, _Py_SwappedOp[op]);
- if (res != Py_NotImplemented)
- return res;
- Py_DECREF(res);
- }
+ if (PyInstance_Check(w)) {
+ res = half_richcompare(w, v, _Py_SwappedOp[op]);
+ if (res != Py_NotImplemented)
+ return res;
+ Py_DECREF(res);
+ }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
@@ -2033,42 +2033,42 @@ instance_richcompare(PyObject *v, PyObject *w, int op)
static PyObject *
instance_getiter(PyInstanceObject *self)
{
- PyObject *func;
-
- if (iterstr == NULL) {
- iterstr = PyString_InternFromString("__iter__");
- if (iterstr == NULL)
- return NULL;
- }
- if (getitemstr == NULL) {
- getitemstr = PyString_InternFromString("__getitem__");
- if (getitemstr == NULL)
- return NULL;
- }
-
- if ((func = instance_getattr(self, iterstr)) != NULL) {
- PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- if (res != NULL && !PyIter_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "__iter__ returned non-iterator "
- "of type '%.100s'",
- res->ob_type->tp_name);
- Py_DECREF(res);
- res = NULL;
- }
- return res;
- }
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- if ((func = instance_getattr(self, getitemstr)) == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "iteration over non-sequence");
- return NULL;
- }
- Py_DECREF(func);
- return PySeqIter_New((PyObject *)self);
+ PyObject *func;
+
+ if (iterstr == NULL) {
+ iterstr = PyString_InternFromString("__iter__");
+ if (iterstr == NULL)
+ return NULL;
+ }
+ if (getitemstr == NULL) {
+ getitemstr = PyString_InternFromString("__getitem__");
+ if (getitemstr == NULL)
+ return NULL;
+ }
+
+ if ((func = instance_getattr(self, iterstr)) != NULL) {
+ PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ if (res != NULL && !PyIter_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "__iter__ returned non-iterator "
+ "of type '%.100s'",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ res = NULL;
+ }
+ return res;
+ }
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ if ((func = instance_getattr(self, getitemstr)) == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "iteration over non-sequence");
+ return NULL;
+ }
+ Py_DECREF(func);
+ return PySeqIter_New((PyObject *)self);
}
@@ -2076,146 +2076,146 @@ instance_getiter(PyInstanceObject *self)
static PyObject *
instance_iternext(PyInstanceObject *self)
{
- PyObject *func;
-
- if (nextstr == NULL) {
- nextstr = PyString_InternFromString("next");
- if (nextstr == NULL)
- return NULL;
- }
-
- if ((func = instance_getattr(self, nextstr)) != NULL) {
- PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
- Py_DECREF(func);
- if (res != NULL) {
- return res;
- }
- if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
- PyErr_Clear();
- return NULL;
- }
- return NULL;
- }
- PyErr_SetString(PyExc_TypeError, "instance has no next() method");
- return NULL;
+ PyObject *func;
+
+ if (nextstr == NULL) {
+ nextstr = PyString_InternFromString("next");
+ if (nextstr == NULL)
+ return NULL;
+ }
+
+ if ((func = instance_getattr(self, nextstr)) != NULL) {
+ PyObject *res = PyEval_CallObject(func, (PyObject *)NULL);
+ Py_DECREF(func);
+ if (res != NULL) {
+ return res;
+ }
+ if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
+ PyErr_Clear();
+ return NULL;
+ }
+ return NULL;
+ }
+ PyErr_SetString(PyExc_TypeError, "instance has no next() method");
+ return NULL;
}
static PyObject *
instance_call(PyObject *func, PyObject *arg, PyObject *kw)
{
- PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
- if (call == NULL) {
- PyInstanceObject *inst = (PyInstanceObject*) func;
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- PyErr_Format(PyExc_AttributeError,
- "%.200s instance has no __call__ method",
- PyString_AsString(inst->in_class->cl_name));
- return NULL;
- }
- /* We must check and increment the recursion depth here. Scenario:
- class A:
- pass
- A.__call__ = A() # that's right
- a = A() # ok
- a() # infinite recursion
- This bounces between instance_call() and PyObject_Call() without
- ever hitting eval_frame() (which has the main recursion check). */
- if (Py_EnterRecursiveCall(" in __call__")) {
- res = NULL;
- }
- else {
- res = PyObject_Call(call, arg, kw);
- Py_LeaveRecursiveCall();
- }
- Py_DECREF(call);
- return res;
+ PyObject *res, *call = PyObject_GetAttrString(func, "__call__");
+ if (call == NULL) {
+ PyInstanceObject *inst = (PyInstanceObject*) func;
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ PyErr_Format(PyExc_AttributeError,
+ "%.200s instance has no __call__ method",
+ PyString_AsString(inst->in_class->cl_name));
+ return NULL;
+ }
+ /* We must check and increment the recursion depth here. Scenario:
+ class A:
+ pass
+ A.__call__ = A() # that's right
+ a = A() # ok
+ a() # infinite recursion
+ This bounces between instance_call() and PyObject_Call() without
+ ever hitting eval_frame() (which has the main recursion check). */
+ if (Py_EnterRecursiveCall(" in __call__")) {
+ res = NULL;
+ }
+ else {
+ res = PyObject_Call(call, arg, kw);
+ Py_LeaveRecursiveCall();
+ }
+ Py_DECREF(call);
+ return res;
}
static PyNumberMethods instance_as_number = {
- instance_add, /* nb_add */
- instance_sub, /* nb_subtract */
- instance_mul, /* nb_multiply */
- instance_div, /* nb_divide */
- instance_mod, /* nb_remainder */
- instance_divmod, /* nb_divmod */
- instance_pow, /* nb_power */
- (unaryfunc)instance_neg, /* nb_negative */
- (unaryfunc)instance_pos, /* nb_positive */
- (unaryfunc)instance_abs, /* nb_absolute */
- (inquiry)instance_nonzero, /* nb_nonzero */
- (unaryfunc)instance_invert, /* nb_invert */
- instance_lshift, /* nb_lshift */
- instance_rshift, /* nb_rshift */
- instance_and, /* nb_and */
- instance_xor, /* nb_xor */
- instance_or, /* nb_or */
- instance_coerce, /* nb_coerce */
- (unaryfunc)instance_int, /* nb_int */
- (unaryfunc)instance_long, /* nb_long */
- (unaryfunc)instance_float, /* nb_float */
- (unaryfunc)instance_oct, /* nb_oct */
- (unaryfunc)instance_hex, /* nb_hex */
- instance_iadd, /* nb_inplace_add */
- instance_isub, /* nb_inplace_subtract */
- instance_imul, /* nb_inplace_multiply */
- instance_idiv, /* nb_inplace_divide */
- instance_imod, /* nb_inplace_remainder */
- instance_ipow, /* nb_inplace_power */
- instance_ilshift, /* nb_inplace_lshift */
- instance_irshift, /* nb_inplace_rshift */
- instance_iand, /* nb_inplace_and */
- instance_ixor, /* nb_inplace_xor */
- instance_ior, /* nb_inplace_or */
- instance_floordiv, /* nb_floor_divide */
- instance_truediv, /* nb_true_divide */
- instance_ifloordiv, /* nb_inplace_floor_divide */
- instance_itruediv, /* nb_inplace_true_divide */
- (unaryfunc)instance_index, /* nb_index */
+ instance_add, /* nb_add */
+ instance_sub, /* nb_subtract */
+ instance_mul, /* nb_multiply */
+ instance_div, /* nb_divide */
+ instance_mod, /* nb_remainder */
+ instance_divmod, /* nb_divmod */
+ instance_pow, /* nb_power */
+ (unaryfunc)instance_neg, /* nb_negative */
+ (unaryfunc)instance_pos, /* nb_positive */
+ (unaryfunc)instance_abs, /* nb_absolute */
+ (inquiry)instance_nonzero, /* nb_nonzero */
+ (unaryfunc)instance_invert, /* nb_invert */
+ instance_lshift, /* nb_lshift */
+ instance_rshift, /* nb_rshift */
+ instance_and, /* nb_and */
+ instance_xor, /* nb_xor */
+ instance_or, /* nb_or */
+ instance_coerce, /* nb_coerce */
+ (unaryfunc)instance_int, /* nb_int */
+ (unaryfunc)instance_long, /* nb_long */
+ (unaryfunc)instance_float, /* nb_float */
+ (unaryfunc)instance_oct, /* nb_oct */
+ (unaryfunc)instance_hex, /* nb_hex */
+ instance_iadd, /* nb_inplace_add */
+ instance_isub, /* nb_inplace_subtract */
+ instance_imul, /* nb_inplace_multiply */
+ instance_idiv, /* nb_inplace_divide */
+ instance_imod, /* nb_inplace_remainder */
+ instance_ipow, /* nb_inplace_power */
+ instance_ilshift, /* nb_inplace_lshift */
+ instance_irshift, /* nb_inplace_rshift */
+ instance_iand, /* nb_inplace_and */
+ instance_ixor, /* nb_inplace_xor */
+ instance_ior, /* nb_inplace_or */
+ instance_floordiv, /* nb_floor_divide */
+ instance_truediv, /* nb_true_divide */
+ instance_ifloordiv, /* nb_inplace_floor_divide */
+ instance_itruediv, /* nb_inplace_true_divide */
+ (unaryfunc)instance_index, /* nb_index */
};
PyTypeObject PyInstance_Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0,
- "instance",
- sizeof(PyInstanceObject),
- 0,
- (destructor)instance_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- instance_compare, /* tp_compare */
- (reprfunc)instance_repr, /* tp_repr */
- &instance_as_number, /* tp_as_number */
- &instance_as_sequence, /* tp_as_sequence */
- &instance_as_mapping, /* tp_as_mapping */
- (hashfunc)instance_hash, /* tp_hash */
- instance_call, /* tp_call */
- (reprfunc)instance_str, /* tp_str */
- (getattrofunc)instance_getattr, /* tp_getattro */
- (setattrofunc)instance_setattr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
- instance_doc, /* tp_doc */
- (traverseproc)instance_traverse, /* tp_traverse */
- 0, /* tp_clear */
- instance_richcompare, /* tp_richcompare */
- offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
- (getiterfunc)instance_getiter, /* tp_iter */
- (iternextfunc)instance_iternext, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- instance_new, /* tp_new */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "instance",
+ sizeof(PyInstanceObject),
+ 0,
+ (destructor)instance_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ instance_compare, /* tp_compare */
+ (reprfunc)instance_repr, /* tp_repr */
+ &instance_as_number, /* tp_as_number */
+ &instance_as_sequence, /* tp_as_sequence */
+ &instance_as_mapping, /* tp_as_mapping */
+ (hashfunc)instance_hash, /* tp_hash */
+ instance_call, /* tp_call */
+ (reprfunc)instance_str, /* tp_str */
+ (getattrofunc)instance_getattr, /* tp_getattro */
+ (setattrofunc)instance_setattr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES,/*tp_flags*/
+ instance_doc, /* tp_doc */
+ (traverseproc)instance_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ instance_richcompare, /* tp_richcompare */
+ offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
+ (getiterfunc)instance_getiter, /* tp_iter */
+ (iternextfunc)instance_iternext, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ instance_new, /* tp_new */
};
@@ -2228,27 +2228,27 @@ PyTypeObject PyInstance_Type = {
PyObject *
PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
{
- register PyMethodObject *im;
- im = free_list;
- if (im != NULL) {
- free_list = (PyMethodObject *)(im->im_self);
- PyObject_INIT(im, &PyMethod_Type);
- numfree--;
- }
- else {
- im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
- if (im == NULL)
- return NULL;
- }
- im->im_weakreflist = NULL;
- Py_INCREF(func);
- im->im_func = func;
- Py_XINCREF(self);
- im->im_self = self;
- Py_XINCREF(klass);
- im->im_class = klass;
- _PyObject_GC_TRACK(im);
- return (PyObject *)im;
+ register PyMethodObject *im;
+ im = free_list;
+ if (im != NULL) {
+ free_list = (PyMethodObject *)(im->im_self);
+ PyObject_INIT(im, &PyMethod_Type);
+ numfree--;
+ }
+ else {
+ im = PyObject_GC_New(PyMethodObject, &PyMethod_Type);
+ if (im == NULL)
+ return NULL;
+ }
+ im->im_weakreflist = NULL;
+ Py_INCREF(func);
+ im->im_func = func;
+ Py_XINCREF(self);
+ im->im_self = self;
+ Py_XINCREF(klass);
+ im->im_class = klass;
+ _PyObject_GC_TRACK(im);
+ return (PyObject *)im;
}
/* Descriptors for PyMethod attributes */
@@ -2258,17 +2258,17 @@ PyMethod_New(PyObject *func, PyObject *self, PyObject *klass)
#define OFF(x) offsetof(PyMethodObject, x)
static PyMemberDef instancemethod_memberlist[] = {
- {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
- "the class associated with a method"},
- {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
- "the function (or other callable) implementing a method"},
- {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
- "the function (or other callable) implementing a method"},
- {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
- "the instance to which a method is bound; None for unbound methods"},
- {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
- "the instance to which a method is bound; None for unbound methods"},
- {NULL} /* Sentinel */
+ {"im_class", T_OBJECT, OFF(im_class), READONLY|RESTRICTED,
+ "the class associated with a method"},
+ {"im_func", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
+ "the function (or other callable) implementing a method"},
+ {"__func__", T_OBJECT, OFF(im_func), READONLY|RESTRICTED,
+ "the function (or other callable) implementing a method"},
+ {"im_self", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
+ "the instance to which a method is bound; None for unbound methods"},
+ {"__self__", T_OBJECT, OFF(im_self), READONLY|RESTRICTED,
+ "the instance to which a method is bound; None for unbound methods"},
+ {NULL} /* Sentinel */
};
/* Christian Tismer argued convincingly that method attributes should
@@ -2279,46 +2279,46 @@ static PyMemberDef instancemethod_memberlist[] = {
static PyObject *
instancemethod_get_doc(PyMethodObject *im, void *context)
{
- static PyObject *docstr;
- if (docstr == NULL) {
- docstr= PyString_InternFromString("__doc__");
- if (docstr == NULL)
- return NULL;
- }
- return PyObject_GetAttr(im->im_func, docstr);
+ static PyObject *docstr;
+ if (docstr == NULL) {
+ docstr= PyString_InternFromString("__doc__");
+ if (docstr == NULL)
+ return NULL;
+ }
+ return PyObject_GetAttr(im->im_func, docstr);
}
static PyGetSetDef instancemethod_getset[] = {
- {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
- {0}
+ {"__doc__", (getter)instancemethod_get_doc, NULL, NULL},
+ {0}
};
static PyObject *
instancemethod_getattro(PyObject *obj, PyObject *name)
{
- PyMethodObject *im = (PyMethodObject *)obj;
- PyTypeObject *tp = obj->ob_type;
- PyObject *descr = NULL;
+ PyMethodObject *im = (PyMethodObject *)obj;
+ PyTypeObject *tp = obj->ob_type;
+ PyObject *descr = NULL;
- if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
- if (tp->tp_dict == NULL) {
- if (PyType_Ready(tp) < 0)
- return NULL;
- }
- descr = _PyType_Lookup(tp, name);
- }
+ if (PyType_HasFeature(tp, Py_TPFLAGS_HAVE_CLASS)) {
+ if (tp->tp_dict == NULL) {
+ if (PyType_Ready(tp) < 0)
+ return NULL;
+ }
+ descr = _PyType_Lookup(tp, name);
+ }
- if (descr != NULL) {
- descrgetfunc f = TP_DESCR_GET(descr->ob_type);
- if (f != NULL)
- return f(descr, obj, (PyObject *)obj->ob_type);
- else {
- Py_INCREF(descr);
- return descr;
- }
- }
+ if (descr != NULL) {
+ descrgetfunc f = TP_DESCR_GET(descr->ob_type);
+ if (f != NULL)
+ return f(descr, obj, (PyObject *)obj->ob_type);
+ else {
+ Py_INCREF(descr);
+ return descr;
+ }
+ }
- return PyObject_GetAttr(im->im_func, name);
+ return PyObject_GetAttr(im->im_func, name);
}
PyDoc_STRVAR(instancemethod_doc,
@@ -2329,323 +2329,323 @@ Create an instance method object.");
static PyObject *
instancemethod_new(PyTypeObject* type, PyObject* args, PyObject *kw)
{
- PyObject *func;
- PyObject *self;
- PyObject *classObj = NULL;
-
- if (!_PyArg_NoKeywords("instancemethod", kw))
- return NULL;
- if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
- &func, &self, &classObj))
- return NULL;
- if (!PyCallable_Check(func)) {
- PyErr_SetString(PyExc_TypeError,
- "first argument must be callable");
- return NULL;
- }
- if (self == Py_None)
- self = NULL;
- if (self == NULL && classObj == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "unbound methods must have non-NULL im_class");
- return NULL;
- }
-
- return PyMethod_New(func, self, classObj);
+ PyObject *func;
+ PyObject *self;
+ PyObject *classObj = NULL;
+
+ if (!_PyArg_NoKeywords("instancemethod", kw))
+ return NULL;
+ if (!PyArg_UnpackTuple(args, "instancemethod", 2, 3,
+ &func, &self, &classObj))
+ return NULL;
+ if (!PyCallable_Check(func)) {
+ PyErr_SetString(PyExc_TypeError,
+ "first argument must be callable");
+ return NULL;
+ }
+ if (self == Py_None)
+ self = NULL;
+ if (self == NULL && classObj == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "unbound methods must have non-NULL im_class");
+ return NULL;
+ }
+
+ return PyMethod_New(func, self, classObj);
}
static void
instancemethod_dealloc(register PyMethodObject *im)
{
- _PyObject_GC_UNTRACK(im);
- if (im->im_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *)im);
- Py_DECREF(im->im_func);
- Py_XDECREF(im->im_self);
- Py_XDECREF(im->im_class);
- if (numfree < PyMethod_MAXFREELIST) {
- im->im_self = (PyObject *)free_list;
- free_list = im;
- numfree++;
- }
- else {
- PyObject_GC_Del(im);
- }
+ _PyObject_GC_UNTRACK(im);
+ if (im->im_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *)im);
+ Py_DECREF(im->im_func);
+ Py_XDECREF(im->im_self);
+ Py_XDECREF(im->im_class);
+ if (numfree < PyMethod_MAXFREELIST) {
+ im->im_self = (PyObject *)free_list;
+ free_list = im;
+ numfree++;
+ }
+ else {
+ PyObject_GC_Del(im);
+ }
}
static int
instancemethod_compare(PyMethodObject *a, PyMethodObject *b)
{
- int cmp;
- cmp = PyObject_Compare(a->im_func, b->im_func);
- if (cmp)
- return cmp;
+ int cmp;
+ cmp = PyObject_Compare(a->im_func, b->im_func);
+ if (cmp)
+ return cmp;
- if (a->im_self == b->im_self)
- return 0;
- if (a->im_self == NULL || b->im_self == NULL)
- return (a->im_self < b->im_self) ? -1 : 1;
- else
- return PyObject_Compare(a->im_self, b->im_self);
+ if (a->im_self == b->im_self)
+ return 0;
+ if (a->im_self == NULL || b->im_self == NULL)
+ return (a->im_self < b->im_self) ? -1 : 1;
+ else
+ return PyObject_Compare(a->im_self, b->im_self);
}
static PyObject *
instancemethod_repr(PyMethodObject *a)
{
- PyObject *self = a->im_self;
- PyObject *func = a->im_func;
- PyObject *klass = a->im_class;
- PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
- char *sfuncname = "?", *sklassname = "?";
-
- funcname = PyObject_GetAttrString(func, "__name__");
- if (funcname == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- }
- else if (!PyString_Check(funcname)) {
- Py_DECREF(funcname);
- funcname = NULL;
- }
- else
- sfuncname = PyString_AS_STRING(funcname);
- if (klass == NULL)
- klassname = NULL;
- else {
- klassname = PyObject_GetAttrString(klass, "__name__");
- if (klassname == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return NULL;
- PyErr_Clear();
- }
- else if (!PyString_Check(klassname)) {
- Py_DECREF(klassname);
- klassname = NULL;
- }
- else
- sklassname = PyString_AS_STRING(klassname);
- }
- if (self == NULL)
- result = PyString_FromFormat("<unbound method %s.%s>",
- sklassname, sfuncname);
- else {
- /* XXX Shouldn't use repr() here! */
- PyObject *selfrepr = PyObject_Repr(self);
- if (selfrepr == NULL)
- goto fail;
- if (!PyString_Check(selfrepr)) {
- Py_DECREF(selfrepr);
- goto fail;
- }
- result = PyString_FromFormat("<bound method %s.%s of %s>",
- sklassname, sfuncname,
- PyString_AS_STRING(selfrepr));
- Py_DECREF(selfrepr);
- }
+ PyObject *self = a->im_self;
+ PyObject *func = a->im_func;
+ PyObject *klass = a->im_class;
+ PyObject *funcname = NULL, *klassname = NULL, *result = NULL;
+ char *sfuncname = "?", *sklassname = "?";
+
+ funcname = PyObject_GetAttrString(func, "__name__");
+ if (funcname == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ }
+ else if (!PyString_Check(funcname)) {
+ Py_DECREF(funcname);
+ funcname = NULL;
+ }
+ else
+ sfuncname = PyString_AS_STRING(funcname);
+ if (klass == NULL)
+ klassname = NULL;
+ else {
+ klassname = PyObject_GetAttrString(klass, "__name__");
+ if (klassname == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return NULL;
+ PyErr_Clear();
+ }
+ else if (!PyString_Check(klassname)) {
+ Py_DECREF(klassname);
+ klassname = NULL;
+ }
+ else
+ sklassname = PyString_AS_STRING(klassname);
+ }
+ if (self == NULL)
+ result = PyString_FromFormat("<unbound method %s.%s>",
+ sklassname, sfuncname);
+ else {
+ /* XXX Shouldn't use repr() here! */
+ PyObject *selfrepr = PyObject_Repr(self);
+ if (selfrepr == NULL)
+ goto fail;
+ if (!PyString_Check(selfrepr)) {
+ Py_DECREF(selfrepr);
+ goto fail;
+ }
+ result = PyString_FromFormat("<bound method %s.%s of %s>",
+ sklassname, sfuncname,
+ PyString_AS_STRING(selfrepr));
+ Py_DECREF(selfrepr);
+ }
fail:
- Py_XDECREF(funcname);
- Py_XDECREF(klassname);
- return result;
+ Py_XDECREF(funcname);
+ Py_XDECREF(klassname);
+ return result;
}
static long
instancemethod_hash(PyMethodObject *a)
{
- long x, y;
- if (a->im_self == NULL)
- x = PyObject_Hash(Py_None);
- else
- x = PyObject_Hash(a->im_self);
- if (x == -1)
- return -1;
- y = PyObject_Hash(a->im_func);
- if (y == -1)
- return -1;
- x = x ^ y;
- if (x == -1)
- x = -2;
- return x;
+ long x, y;
+ if (a->im_self == NULL)
+ x = PyObject_Hash(Py_None);
+ else
+ x = PyObject_Hash(a->im_self);
+ if (x == -1)
+ return -1;
+ y = PyObject_Hash(a->im_func);
+ if (y == -1)
+ return -1;
+ x = x ^ y;
+ if (x == -1)
+ x = -2;
+ return x;
}
static int
instancemethod_traverse(PyMethodObject *im, visitproc visit, void *arg)
{
- Py_VISIT(im->im_func);
- Py_VISIT(im->im_self);
- Py_VISIT(im->im_class);
- return 0;
+ Py_VISIT(im->im_func);
+ Py_VISIT(im->im_self);
+ Py_VISIT(im->im_class);
+ return 0;
}
static void
getclassname(PyObject *klass, char *buf, int bufsize)
{
- PyObject *name;
-
- assert(bufsize > 1);
- strcpy(buf, "?"); /* Default outcome */
- if (klass == NULL)
- return;
- name = PyObject_GetAttrString(klass, "__name__");
- if (name == NULL) {
- /* This function cannot return an exception */
- PyErr_Clear();
- return;
- }
- if (PyString_Check(name)) {
- strncpy(buf, PyString_AS_STRING(name), bufsize);
- buf[bufsize-1] = '\0';
- }
- Py_DECREF(name);
+ PyObject *name;
+
+ assert(bufsize > 1);
+ strcpy(buf, "?"); /* Default outcome */
+ if (klass == NULL)
+ return;
+ name = PyObject_GetAttrString(klass, "__name__");
+ if (name == NULL) {
+ /* This function cannot return an exception */
+ PyErr_Clear();
+ return;
+ }
+ if (PyString_Check(name)) {
+ strncpy(buf, PyString_AS_STRING(name), bufsize);
+ buf[bufsize-1] = '\0';
+ }
+ Py_DECREF(name);
}
static void
getinstclassname(PyObject *inst, char *buf, int bufsize)
{
- PyObject *klass;
+ PyObject *klass;
- if (inst == NULL) {
- assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
- strcpy(buf, "nothing");
- return;
- }
+ if (inst == NULL) {
+ assert(bufsize > 0 && (size_t)bufsize > strlen("nothing"));
+ strcpy(buf, "nothing");
+ return;
+ }
- klass = PyObject_GetAttrString(inst, "__class__");
- if (klass == NULL) {
- /* This function cannot return an exception */
- PyErr_Clear();
- klass = (PyObject *)(inst->ob_type);
- Py_INCREF(klass);
- }
- getclassname(klass, buf, bufsize);
- Py_XDECREF(klass);
+ klass = PyObject_GetAttrString(inst, "__class__");
+ if (klass == NULL) {
+ /* This function cannot return an exception */
+ PyErr_Clear();
+ klass = (PyObject *)(inst->ob_type);
+ Py_INCREF(klass);
+ }
+ getclassname(klass, buf, bufsize);
+ Py_XDECREF(klass);
}
static PyObject *
instancemethod_call(PyObject *func, PyObject *arg, PyObject *kw)
{
- PyObject *self = PyMethod_GET_SELF(func);
- PyObject *klass = PyMethod_GET_CLASS(func);
- PyObject *result;
-
- func = PyMethod_GET_FUNCTION(func);
- if (self == NULL) {
- /* Unbound methods must be called with an instance of
- the class (or a derived class) as first argument */
- int ok;
- if (PyTuple_Size(arg) >= 1)
- self = PyTuple_GET_ITEM(arg, 0);
- if (self == NULL)
- ok = 0;
- else {
- ok = PyObject_IsInstance(self, klass);
- if (ok < 0)
- return NULL;
- }
- if (!ok) {
- char clsbuf[256];
- char instbuf[256];
- getclassname(klass, clsbuf, sizeof(clsbuf));
- getinstclassname(self, instbuf, sizeof(instbuf));
- PyErr_Format(PyExc_TypeError,
- "unbound method %s%s must be called with "
- "%s instance as first argument "
- "(got %s%s instead)",
- PyEval_GetFuncName(func),
- PyEval_GetFuncDesc(func),
- clsbuf,
- instbuf,
- self == NULL ? "" : " instance");
- return NULL;
- }
- Py_INCREF(arg);
- }
- else {
- Py_ssize_t argcount = PyTuple_Size(arg);
- PyObject *newarg = PyTuple_New(argcount + 1);
- int i;
- if (newarg == NULL)
- return NULL;
- Py_INCREF(self);
- PyTuple_SET_ITEM(newarg, 0, self);
- for (i = 0; i < argcount; i++) {
- PyObject *v = PyTuple_GET_ITEM(arg, i);
- Py_XINCREF(v);
- PyTuple_SET_ITEM(newarg, i+1, v);
- }
- arg = newarg;
- }
- result = PyObject_Call((PyObject *)func, arg, kw);
- Py_DECREF(arg);
- return result;
+ PyObject *self = PyMethod_GET_SELF(func);
+ PyObject *klass = PyMethod_GET_CLASS(func);
+ PyObject *result;
+
+ func = PyMethod_GET_FUNCTION(func);
+ if (self == NULL) {
+ /* Unbound methods must be called with an instance of
+ the class (or a derived class) as first argument */
+ int ok;
+ if (PyTuple_Size(arg) >= 1)
+ self = PyTuple_GET_ITEM(arg, 0);
+ if (self == NULL)
+ ok = 0;
+ else {
+ ok = PyObject_IsInstance(self, klass);
+ if (ok < 0)
+ return NULL;
+ }
+ if (!ok) {
+ char clsbuf[256];
+ char instbuf[256];
+ getclassname(klass, clsbuf, sizeof(clsbuf));
+ getinstclassname(self, instbuf, sizeof(instbuf));
+ PyErr_Format(PyExc_TypeError,
+ "unbound method %s%s must be called with "
+ "%s instance as first argument "
+ "(got %s%s instead)",
+ PyEval_GetFuncName(func),
+ PyEval_GetFuncDesc(func),
+ clsbuf,
+ instbuf,
+ self == NULL ? "" : " instance");
+ return NULL;
+ }
+ Py_INCREF(arg);
+ }
+ else {
+ Py_ssize_t argcount = PyTuple_Size(arg);
+ PyObject *newarg = PyTuple_New(argcount + 1);
+ int i;
+ if (newarg == NULL)
+ return NULL;
+ Py_INCREF(self);
+ PyTuple_SET_ITEM(newarg, 0, self);
+ for (i = 0; i < argcount; i++) {
+ PyObject *v = PyTuple_GET_ITEM(arg, i);
+ Py_XINCREF(v);
+ PyTuple_SET_ITEM(newarg, i+1, v);
+ }
+ arg = newarg;
+ }
+ result = PyObject_Call((PyObject *)func, arg, kw);
+ Py_DECREF(arg);
+ return result;
}
static PyObject *
instancemethod_descr_get(PyObject *meth, PyObject *obj, PyObject *cls)
{
- /* Don't rebind an already bound method, or an unbound method
- of a class that's not a base class of cls. */
-
- if (PyMethod_GET_SELF(meth) != NULL) {
- /* Already bound */
- Py_INCREF(meth);
- return meth;
- }
- /* No, it is an unbound method */
- if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
- /* Do subclass test. If it fails, return meth unchanged. */
- int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
- if (ok < 0)
- return NULL;
- if (!ok) {
- Py_INCREF(meth);
- return meth;
- }
- }
- /* Bind it to obj */
- return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
+ /* Don't rebind an already bound method, or an unbound method
+ of a class that's not a base class of cls. */
+
+ if (PyMethod_GET_SELF(meth) != NULL) {
+ /* Already bound */
+ Py_INCREF(meth);
+ return meth;
+ }
+ /* No, it is an unbound method */
+ if (PyMethod_GET_CLASS(meth) != NULL && cls != NULL) {
+ /* Do subclass test. If it fails, return meth unchanged. */
+ int ok = PyObject_IsSubclass(cls, PyMethod_GET_CLASS(meth));
+ if (ok < 0)
+ return NULL;
+ if (!ok) {
+ Py_INCREF(meth);
+ return meth;
+ }
+ }
+ /* Bind it to obj */
+ return PyMethod_New(PyMethod_GET_FUNCTION(meth), obj, cls);
}
PyTypeObject PyMethod_Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0,
- "instancemethod",
- sizeof(PyMethodObject),
- 0,
- (destructor)instancemethod_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)instancemethod_compare, /* tp_compare */
- (reprfunc)instancemethod_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)instancemethod_hash, /* tp_hash */
- instancemethod_call, /* tp_call */
- 0, /* tp_str */
- instancemethod_getattro, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
- instancemethod_doc, /* tp_doc */
- (traverseproc)instancemethod_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- instancemethod_memberlist, /* tp_members */
- instancemethod_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- instancemethod_descr_get, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- instancemethod_new, /* tp_new */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0,
+ "instancemethod",
+ sizeof(PyMethodObject),
+ 0,
+ (destructor)instancemethod_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)instancemethod_compare, /* tp_compare */
+ (reprfunc)instancemethod_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)instancemethod_hash, /* tp_hash */
+ instancemethod_call, /* tp_call */
+ 0, /* tp_str */
+ instancemethod_getattro, /* tp_getattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
+ instancemethod_doc, /* tp_doc */
+ (traverseproc)instancemethod_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyMethodObject, im_weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ instancemethod_memberlist, /* tp_members */
+ instancemethod_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ instancemethod_descr_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ instancemethod_new, /* tp_new */
};
/* Clear out the free list */
@@ -2653,20 +2653,20 @@ PyTypeObject PyMethod_Type = {
int
PyMethod_ClearFreeList(void)
{
- int freelist_size = numfree;
-
- while (free_list) {
- PyMethodObject *im = free_list;
- free_list = (PyMethodObject *)(im->im_self);
- PyObject_GC_Del(im);
- numfree--;
- }
- assert(numfree == 0);
- return freelist_size;
+ int freelist_size = numfree;
+
+ while (free_list) {
+ PyMethodObject *im = free_list;
+ free_list = (PyMethodObject *)(im->im_self);
+ PyObject_GC_Del(im);
+ numfree--;
+ }
+ assert(numfree == 0);
+ return freelist_size;
}
void
PyMethod_Fini(void)
{
- (void)PyMethod_ClearFreeList();
+ (void)PyMethod_ClearFreeList();
}
diff --git a/Objects/codeobject.c b/Objects/codeobject.c
index 340cef0..9879df5 100644
--- a/Objects/codeobject.c
+++ b/Objects/codeobject.c
@@ -3,176 +3,176 @@
#include "structmember.h"
#define NAME_CHARS \
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz"
/* all_name_chars(s): true iff all chars in s are valid NAME_CHARS */
static int
all_name_chars(unsigned char *s)
{
- static char ok_name_char[256];
- static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
-
- if (ok_name_char[*name_chars] == 0) {
- unsigned char *p;
- for (p = name_chars; *p; p++)
- ok_name_char[*p] = 1;
- }
- while (*s) {
- if (ok_name_char[*s++] == 0)
- return 0;
- }
- return 1;
+ static char ok_name_char[256];
+ static unsigned char *name_chars = (unsigned char *)NAME_CHARS;
+
+ if (ok_name_char[*name_chars] == 0) {
+ unsigned char *p;
+ for (p = name_chars; *p; p++)
+ ok_name_char[*p] = 1;
+ }
+ while (*s) {
+ if (ok_name_char[*s++] == 0)
+ return 0;
+ }
+ return 1;
}
static void
intern_strings(PyObject *tuple)
{
- Py_ssize_t i;
-
- for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
- PyObject *v = PyTuple_GET_ITEM(tuple, i);
- if (v == NULL || !PyString_CheckExact(v)) {
- Py_FatalError("non-string found in code slot");
- }
- PyString_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
- }
+ Py_ssize_t i;
+
+ for (i = PyTuple_GET_SIZE(tuple); --i >= 0; ) {
+ PyObject *v = PyTuple_GET_ITEM(tuple, i);
+ if (v == NULL || !PyString_CheckExact(v)) {
+ Py_FatalError("non-string found in code slot");
+ }
+ PyString_InternInPlace(&PyTuple_GET_ITEM(tuple, i));
+ }
}
PyCodeObject *
PyCode_New(int argcount, int nlocals, int stacksize, int flags,
- PyObject *code, PyObject *consts, PyObject *names,
- PyObject *varnames, PyObject *freevars, PyObject *cellvars,
- PyObject *filename, PyObject *name, int firstlineno,
- PyObject *lnotab)
+ PyObject *code, PyObject *consts, PyObject *names,
+ PyObject *varnames, PyObject *freevars, PyObject *cellvars,
+ PyObject *filename, PyObject *name, int firstlineno,
+ PyObject *lnotab)
{
- PyCodeObject *co;
- Py_ssize_t i;
- /* Check argument types */
- if (argcount < 0 || nlocals < 0 ||
- code == NULL ||
- consts == NULL || !PyTuple_Check(consts) ||
- names == NULL || !PyTuple_Check(names) ||
- varnames == NULL || !PyTuple_Check(varnames) ||
- freevars == NULL || !PyTuple_Check(freevars) ||
- cellvars == NULL || !PyTuple_Check(cellvars) ||
- name == NULL || !PyString_Check(name) ||
- filename == NULL || !PyString_Check(filename) ||
- lnotab == NULL || !PyString_Check(lnotab) ||
- !PyObject_CheckReadBuffer(code)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- intern_strings(names);
- intern_strings(varnames);
- intern_strings(freevars);
- intern_strings(cellvars);
- /* Intern selected string constants */
- for (i = PyTuple_Size(consts); --i >= 0; ) {
- PyObject *v = PyTuple_GetItem(consts, i);
- if (!PyString_Check(v))
- continue;
- if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
- continue;
- PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
- }
- co = PyObject_NEW(PyCodeObject, &PyCode_Type);
- if (co != NULL) {
- co->co_argcount = argcount;
- co->co_nlocals = nlocals;
- co->co_stacksize = stacksize;
- co->co_flags = flags;
- Py_INCREF(code);
- co->co_code = code;
- Py_INCREF(consts);
- co->co_consts = consts;
- Py_INCREF(names);
- co->co_names = names;
- Py_INCREF(varnames);
- co->co_varnames = varnames;
- Py_INCREF(freevars);
- co->co_freevars = freevars;
- Py_INCREF(cellvars);
- co->co_cellvars = cellvars;
- Py_INCREF(filename);
- co->co_filename = filename;
- Py_INCREF(name);
- co->co_name = name;
- co->co_firstlineno = firstlineno;
- Py_INCREF(lnotab);
- co->co_lnotab = lnotab;
- co->co_zombieframe = NULL;
- co->co_weakreflist = NULL;
- }
- return co;
+ PyCodeObject *co;
+ Py_ssize_t i;
+ /* Check argument types */
+ if (argcount < 0 || nlocals < 0 ||
+ code == NULL ||
+ consts == NULL || !PyTuple_Check(consts) ||
+ names == NULL || !PyTuple_Check(names) ||
+ varnames == NULL || !PyTuple_Check(varnames) ||
+ freevars == NULL || !PyTuple_Check(freevars) ||
+ cellvars == NULL || !PyTuple_Check(cellvars) ||
+ name == NULL || !PyString_Check(name) ||
+ filename == NULL || !PyString_Check(filename) ||
+ lnotab == NULL || !PyString_Check(lnotab) ||
+ !PyObject_CheckReadBuffer(code)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ intern_strings(names);
+ intern_strings(varnames);
+ intern_strings(freevars);
+ intern_strings(cellvars);
+ /* Intern selected string constants */
+ for (i = PyTuple_Size(consts); --i >= 0; ) {
+ PyObject *v = PyTuple_GetItem(consts, i);
+ if (!PyString_Check(v))
+ continue;
+ if (!all_name_chars((unsigned char *)PyString_AS_STRING(v)))
+ continue;
+ PyString_InternInPlace(&PyTuple_GET_ITEM(consts, i));
+ }
+ co = PyObject_NEW(PyCodeObject, &PyCode_Type);
+ if (co != NULL) {
+ co->co_argcount = argcount;
+ co->co_nlocals = nlocals;
+ co->co_stacksize = stacksize;
+ co->co_flags = flags;
+ Py_INCREF(code);
+ co->co_code = code;
+ Py_INCREF(consts);
+ co->co_consts = consts;
+ Py_INCREF(names);
+ co->co_names = names;
+ Py_INCREF(varnames);
+ co->co_varnames = varnames;
+ Py_INCREF(freevars);
+ co->co_freevars = freevars;
+ Py_INCREF(cellvars);
+ co->co_cellvars = cellvars;
+ Py_INCREF(filename);
+ co->co_filename = filename;
+ Py_INCREF(name);
+ co->co_name = name;
+ co->co_firstlineno = firstlineno;
+ Py_INCREF(lnotab);
+ co->co_lnotab = lnotab;
+ co->co_zombieframe = NULL;
+ co->co_weakreflist = NULL;
+ }
+ return co;
}
PyCodeObject *
PyCode_NewEmpty(const char *filename, const char *funcname, int firstlineno)
{
- static PyObject *emptystring = NULL;
- static PyObject *nulltuple = NULL;
- PyObject *filename_ob = NULL;
- PyObject *funcname_ob = NULL;
- PyCodeObject *result = NULL;
- if (emptystring == NULL) {
- emptystring = PyString_FromString("");
- if (emptystring == NULL)
- goto failed;
- }
- if (nulltuple == NULL) {
- nulltuple = PyTuple_New(0);
- if (nulltuple == NULL)
- goto failed;
- }
- funcname_ob = PyString_FromString(funcname);
- if (funcname_ob == NULL)
- goto failed;
- filename_ob = PyString_FromString(filename);
- if (filename_ob == NULL)
- goto failed;
-
- result = PyCode_New(0, /* argcount */
- 0, /* nlocals */
- 0, /* stacksize */
- 0, /* flags */
- emptystring, /* code */
- nulltuple, /* consts */
- nulltuple, /* names */
- nulltuple, /* varnames */
- nulltuple, /* freevars */
- nulltuple, /* cellvars */
- filename_ob, /* filename */
- funcname_ob, /* name */
- firstlineno, /* firstlineno */
- emptystring /* lnotab */
- );
+ static PyObject *emptystring = NULL;
+ static PyObject *nulltuple = NULL;
+ PyObject *filename_ob = NULL;
+ PyObject *funcname_ob = NULL;
+ PyCodeObject *result = NULL;
+ if (emptystring == NULL) {
+ emptystring = PyString_FromString("");
+ if (emptystring == NULL)
+ goto failed;
+ }
+ if (nulltuple == NULL) {
+ nulltuple = PyTuple_New(0);
+ if (nulltuple == NULL)
+ goto failed;
+ }
+ funcname_ob = PyString_FromString(funcname);
+ if (funcname_ob == NULL)
+ goto failed;
+ filename_ob = PyString_FromString(filename);
+ if (filename_ob == NULL)
+ goto failed;
+
+ result = PyCode_New(0, /* argcount */
+ 0, /* nlocals */
+ 0, /* stacksize */
+ 0, /* flags */
+ emptystring, /* code */
+ nulltuple, /* consts */
+ nulltuple, /* names */
+ nulltuple, /* varnames */
+ nulltuple, /* freevars */
+ nulltuple, /* cellvars */
+ filename_ob, /* filename */
+ funcname_ob, /* name */
+ firstlineno, /* firstlineno */
+ emptystring /* lnotab */
+ );
failed:
- Py_XDECREF(funcname_ob);
- Py_XDECREF(filename_ob);
- return result;
+ Py_XDECREF(funcname_ob);
+ Py_XDECREF(filename_ob);
+ return result;
}
#define OFF(x) offsetof(PyCodeObject, x)
static PyMemberDef code_memberlist[] = {
- {"co_argcount", T_INT, OFF(co_argcount), READONLY},
- {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
- {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
- {"co_flags", T_INT, OFF(co_flags), READONLY},
- {"co_code", T_OBJECT, OFF(co_code), READONLY},
- {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
- {"co_names", T_OBJECT, OFF(co_names), READONLY},
- {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
- {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
- {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
- {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
- {"co_name", T_OBJECT, OFF(co_name), READONLY},
- {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
- {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
- {NULL} /* Sentinel */
+ {"co_argcount", T_INT, OFF(co_argcount), READONLY},
+ {"co_nlocals", T_INT, OFF(co_nlocals), READONLY},
+ {"co_stacksize",T_INT, OFF(co_stacksize), READONLY},
+ {"co_flags", T_INT, OFF(co_flags), READONLY},
+ {"co_code", T_OBJECT, OFF(co_code), READONLY},
+ {"co_consts", T_OBJECT, OFF(co_consts), READONLY},
+ {"co_names", T_OBJECT, OFF(co_names), READONLY},
+ {"co_varnames", T_OBJECT, OFF(co_varnames), READONLY},
+ {"co_freevars", T_OBJECT, OFF(co_freevars), READONLY},
+ {"co_cellvars", T_OBJECT, OFF(co_cellvars), READONLY},
+ {"co_filename", T_OBJECT, OFF(co_filename), READONLY},
+ {"co_name", T_OBJECT, OFF(co_name), READONLY},
+ {"co_firstlineno", T_INT, OFF(co_firstlineno), READONLY},
+ {"co_lnotab", T_OBJECT, OFF(co_lnotab), READONLY},
+ {NULL} /* Sentinel */
};
/* Helper for code_new: return a shallow copy of a tuple that is
@@ -181,42 +181,42 @@ static PyMemberDef code_memberlist[] = {
static PyObject*
validate_and_copy_tuple(PyObject *tup)
{
- PyObject *newtuple;
- PyObject *item;
- Py_ssize_t i, len;
-
- len = PyTuple_GET_SIZE(tup);
- newtuple = PyTuple_New(len);
- if (newtuple == NULL)
- return NULL;
-
- for (i = 0; i < len; i++) {
- item = PyTuple_GET_ITEM(tup, i);
- if (PyString_CheckExact(item)) {
- Py_INCREF(item);
- }
- else if (!PyString_Check(item)) {
- PyErr_Format(
- PyExc_TypeError,
- "name tuples must contain only "
- "strings, not '%.500s'",
- item->ob_type->tp_name);
- Py_DECREF(newtuple);
- return NULL;
- }
- else {
- item = PyString_FromStringAndSize(
- PyString_AS_STRING(item),
- PyString_GET_SIZE(item));
- if (item == NULL) {
- Py_DECREF(newtuple);
- return NULL;
- }
- }
- PyTuple_SET_ITEM(newtuple, i, item);
- }
-
- return newtuple;
+ PyObject *newtuple;
+ PyObject *item;
+ Py_ssize_t i, len;
+
+ len = PyTuple_GET_SIZE(tup);
+ newtuple = PyTuple_New(len);
+ if (newtuple == NULL)
+ return NULL;
+
+ for (i = 0; i < len; i++) {
+ item = PyTuple_GET_ITEM(tup, i);
+ if (PyString_CheckExact(item)) {
+ Py_INCREF(item);
+ }
+ else if (!PyString_Check(item)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "name tuples must contain only "
+ "strings, not '%.500s'",
+ item->ob_type->tp_name);
+ Py_DECREF(newtuple);
+ return NULL;
+ }
+ else {
+ item = PyString_FromStringAndSize(
+ PyString_AS_STRING(item),
+ PyString_GET_SIZE(item));
+ if (item == NULL) {
+ Py_DECREF(newtuple);
+ return NULL;
+ }
+ }
+ PyTuple_SET_ITEM(newtuple, i, item);
+ }
+
+ return newtuple;
}
PyDoc_STRVAR(code_doc,
@@ -228,286 +228,286 @@ Create a code object. Not for the faint of heart.");
static PyObject *
code_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- int argcount;
- int nlocals;
- int stacksize;
- int flags;
- PyObject *co = NULL;
- PyObject *code;
- PyObject *consts;
- PyObject *names, *ournames = NULL;
- PyObject *varnames, *ourvarnames = NULL;
- PyObject *freevars = NULL, *ourfreevars = NULL;
- PyObject *cellvars = NULL, *ourcellvars = NULL;
- PyObject *filename;
- PyObject *name;
- int firstlineno;
- PyObject *lnotab;
-
- if (!PyArg_ParseTuple(args, "iiiiSO!O!O!SSiS|O!O!:code",
- &argcount, &nlocals, &stacksize, &flags,
- &code,
- &PyTuple_Type, &consts,
- &PyTuple_Type, &names,
- &PyTuple_Type, &varnames,
- &filename, &name,
- &firstlineno, &lnotab,
- &PyTuple_Type, &freevars,
- &PyTuple_Type, &cellvars))
- return NULL;
-
- if (argcount < 0) {
- PyErr_SetString(
- PyExc_ValueError,
- "code: argcount must not be negative");
- goto cleanup;
- }
-
- if (nlocals < 0) {
- PyErr_SetString(
- PyExc_ValueError,
- "code: nlocals must not be negative");
- goto cleanup;
- }
-
- ournames = validate_and_copy_tuple(names);
- if (ournames == NULL)
- goto cleanup;
- ourvarnames = validate_and_copy_tuple(varnames);
- if (ourvarnames == NULL)
- goto cleanup;
- if (freevars)
- ourfreevars = validate_and_copy_tuple(freevars);
- else
- ourfreevars = PyTuple_New(0);
- if (ourfreevars == NULL)
- goto cleanup;
- if (cellvars)
- ourcellvars = validate_and_copy_tuple(cellvars);
- else
- ourcellvars = PyTuple_New(0);
- if (ourcellvars == NULL)
- goto cleanup;
-
- co = (PyObject *)PyCode_New(argcount, nlocals, stacksize, flags,
- code, consts, ournames, ourvarnames,
- ourfreevars, ourcellvars, filename,
- name, firstlineno, lnotab);
+ int argcount;
+ int nlocals;
+ int stacksize;
+ int flags;
+ PyObject *co = NULL;
+ PyObject *code;
+ PyObject *consts;
+ PyObject *names, *ournames = NULL;
+ PyObject *varnames, *ourvarnames = NULL;
+ PyObject *freevars = NULL, *ourfreevars = NULL;
+ PyObject *cellvars = NULL, *ourcellvars = NULL;
+ PyObject *filename;
+ PyObject *name;
+ int firstlineno;
+ PyObject *lnotab;
+
+ if (!PyArg_ParseTuple(args, "iiiiSO!O!O!SSiS|O!O!:code",
+ &argcount, &nlocals, &stacksize, &flags,
+ &code,
+ &PyTuple_Type, &consts,
+ &PyTuple_Type, &names,
+ &PyTuple_Type, &varnames,
+ &filename, &name,
+ &firstlineno, &lnotab,
+ &PyTuple_Type, &freevars,
+ &PyTuple_Type, &cellvars))
+ return NULL;
+
+ if (argcount < 0) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "code: argcount must not be negative");
+ goto cleanup;
+ }
+
+ if (nlocals < 0) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "code: nlocals must not be negative");
+ goto cleanup;
+ }
+
+ ournames = validate_and_copy_tuple(names);
+ if (ournames == NULL)
+ goto cleanup;
+ ourvarnames = validate_and_copy_tuple(varnames);
+ if (ourvarnames == NULL)
+ goto cleanup;
+ if (freevars)
+ ourfreevars = validate_and_copy_tuple(freevars);
+ else
+ ourfreevars = PyTuple_New(0);
+ if (ourfreevars == NULL)
+ goto cleanup;
+ if (cellvars)
+ ourcellvars = validate_and_copy_tuple(cellvars);
+ else
+ ourcellvars = PyTuple_New(0);
+ if (ourcellvars == NULL)
+ goto cleanup;
+
+ co = (PyObject *)PyCode_New(argcount, nlocals, stacksize, flags,
+ code, consts, ournames, ourvarnames,
+ ourfreevars, ourcellvars, filename,
+ name, firstlineno, lnotab);
cleanup:
- Py_XDECREF(ournames);
- Py_XDECREF(ourvarnames);
- Py_XDECREF(ourfreevars);
- Py_XDECREF(ourcellvars);
- return co;
+ Py_XDECREF(ournames);
+ Py_XDECREF(ourvarnames);
+ Py_XDECREF(ourfreevars);
+ Py_XDECREF(ourcellvars);
+ return co;
}
static void
code_dealloc(PyCodeObject *co)
{
- Py_XDECREF(co->co_code);
- Py_XDECREF(co->co_consts);
- Py_XDECREF(co->co_names);
- Py_XDECREF(co->co_varnames);
- Py_XDECREF(co->co_freevars);
- Py_XDECREF(co->co_cellvars);
- Py_XDECREF(co->co_filename);
- Py_XDECREF(co->co_name);
- Py_XDECREF(co->co_lnotab);
- if (co->co_zombieframe != NULL)
- PyObject_GC_Del(co->co_zombieframe);
- if (co->co_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject*)co);
- PyObject_DEL(co);
+ Py_XDECREF(co->co_code);
+ Py_XDECREF(co->co_consts);
+ Py_XDECREF(co->co_names);
+ Py_XDECREF(co->co_varnames);
+ Py_XDECREF(co->co_freevars);
+ Py_XDECREF(co->co_cellvars);
+ Py_XDECREF(co->co_filename);
+ Py_XDECREF(co->co_name);
+ Py_XDECREF(co->co_lnotab);
+ if (co->co_zombieframe != NULL)
+ PyObject_GC_Del(co->co_zombieframe);
+ if (co->co_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject*)co);
+ PyObject_DEL(co);
}
static PyObject *
code_repr(PyCodeObject *co)
{
- char buf[500];
- int lineno = -1;
- char *filename = "???";
- char *name = "???";
-
- if (co->co_firstlineno != 0)
- lineno = co->co_firstlineno;
- if (co->co_filename && PyString_Check(co->co_filename))
- filename = PyString_AS_STRING(co->co_filename);
- if (co->co_name && PyString_Check(co->co_name))
- name = PyString_AS_STRING(co->co_name);
- PyOS_snprintf(buf, sizeof(buf),
- "<code object %.100s at %p, file \"%.300s\", line %d>",
- name, co, filename, lineno);
- return PyString_FromString(buf);
+ char buf[500];
+ int lineno = -1;
+ char *filename = "???";
+ char *name = "???";
+
+ if (co->co_firstlineno != 0)
+ lineno = co->co_firstlineno;
+ if (co->co_filename && PyString_Check(co->co_filename))
+ filename = PyString_AS_STRING(co->co_filename);
+ if (co->co_name && PyString_Check(co->co_name))
+ name = PyString_AS_STRING(co->co_name);
+ PyOS_snprintf(buf, sizeof(buf),
+ "<code object %.100s at %p, file \"%.300s\", line %d>",
+ name, co, filename, lineno);
+ return PyString_FromString(buf);
}
static int
code_compare(PyCodeObject *co, PyCodeObject *cp)
{
- int cmp;
- cmp = PyObject_Compare(co->co_name, cp->co_name);
- if (cmp) return cmp;
- cmp = co->co_argcount - cp->co_argcount;
- if (cmp) goto normalize;
- cmp = co->co_nlocals - cp->co_nlocals;
- if (cmp) goto normalize;
- cmp = co->co_flags - cp->co_flags;
- if (cmp) goto normalize;
- cmp = co->co_firstlineno - cp->co_firstlineno;
- if (cmp) goto normalize;
- cmp = PyObject_Compare(co->co_code, cp->co_code);
- if (cmp) return cmp;
- cmp = PyObject_Compare(co->co_consts, cp->co_consts);
- if (cmp) return cmp;
- cmp = PyObject_Compare(co->co_names, cp->co_names);
- if (cmp) return cmp;
- cmp = PyObject_Compare(co->co_varnames, cp->co_varnames);
- if (cmp) return cmp;
- cmp = PyObject_Compare(co->co_freevars, cp->co_freevars);
- if (cmp) return cmp;
- cmp = PyObject_Compare(co->co_cellvars, cp->co_cellvars);
- return cmp;
+ int cmp;
+ cmp = PyObject_Compare(co->co_name, cp->co_name);
+ if (cmp) return cmp;
+ cmp = co->co_argcount - cp->co_argcount;
+ if (cmp) goto normalize;
+ cmp = co->co_nlocals - cp->co_nlocals;
+ if (cmp) goto normalize;
+ cmp = co->co_flags - cp->co_flags;
+ if (cmp) goto normalize;
+ cmp = co->co_firstlineno - cp->co_firstlineno;
+ if (cmp) goto normalize;
+ cmp = PyObject_Compare(co->co_code, cp->co_code);
+ if (cmp) return cmp;
+ cmp = PyObject_Compare(co->co_consts, cp->co_consts);
+ if (cmp) return cmp;
+ cmp = PyObject_Compare(co->co_names, cp->co_names);
+ if (cmp) return cmp;
+ cmp = PyObject_Compare(co->co_varnames, cp->co_varnames);
+ if (cmp) return cmp;
+ cmp = PyObject_Compare(co->co_freevars, cp->co_freevars);
+ if (cmp) return cmp;
+ cmp = PyObject_Compare(co->co_cellvars, cp->co_cellvars);
+ return cmp;
normalize:
- if (cmp > 0)
- return 1;
- else if (cmp < 0)
- return -1;
- else
- return 0;
+ if (cmp > 0)
+ return 1;
+ else if (cmp < 0)
+ return -1;
+ else
+ return 0;
}
static PyObject *
code_richcompare(PyObject *self, PyObject *other, int op)
{
- PyCodeObject *co, *cp;
- int eq;
- PyObject *res;
-
- if ((op != Py_EQ && op != Py_NE) ||
- !PyCode_Check(self) ||
- !PyCode_Check(other)) {
-
- /* Py3K warning if types are not equal and comparison
- isn't == or != */
- if (PyErr_WarnPy3k("code inequality comparisons not supported "
- "in 3.x", 1) < 0) {
- return NULL;
- }
-
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- co = (PyCodeObject *)self;
- cp = (PyCodeObject *)other;
-
- eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
- if (eq <= 0) goto unequal;
- eq = co->co_argcount == cp->co_argcount;
- if (!eq) goto unequal;
- eq = co->co_nlocals == cp->co_nlocals;
- if (!eq) goto unequal;
- eq = co->co_flags == cp->co_flags;
- if (!eq) goto unequal;
- eq = co->co_firstlineno == cp->co_firstlineno;
- if (!eq) goto unequal;
- eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
- if (eq <= 0) goto unequal;
- eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ);
- if (eq <= 0) goto unequal;
- eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
- if (eq <= 0) goto unequal;
- eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
- if (eq <= 0) goto unequal;
- eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
- if (eq <= 0) goto unequal;
- eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
- if (eq <= 0) goto unequal;
-
- if (op == Py_EQ)
- res = Py_True;
- else
- res = Py_False;
- goto done;
+ PyCodeObject *co, *cp;
+ int eq;
+ PyObject *res;
+
+ if ((op != Py_EQ && op != Py_NE) ||
+ !PyCode_Check(self) ||
+ !PyCode_Check(other)) {
+
+ /* Py3K warning if types are not equal and comparison
+ isn't == or != */
+ if (PyErr_WarnPy3k("code inequality comparisons not supported "
+ "in 3.x", 1) < 0) {
+ return NULL;
+ }
+
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ co = (PyCodeObject *)self;
+ cp = (PyCodeObject *)other;
+
+ eq = PyObject_RichCompareBool(co->co_name, cp->co_name, Py_EQ);
+ if (eq <= 0) goto unequal;
+ eq = co->co_argcount == cp->co_argcount;
+ if (!eq) goto unequal;
+ eq = co->co_nlocals == cp->co_nlocals;
+ if (!eq) goto unequal;
+ eq = co->co_flags == cp->co_flags;
+ if (!eq) goto unequal;
+ eq = co->co_firstlineno == cp->co_firstlineno;
+ if (!eq) goto unequal;
+ eq = PyObject_RichCompareBool(co->co_code, cp->co_code, Py_EQ);
+ if (eq <= 0) goto unequal;
+ eq = PyObject_RichCompareBool(co->co_consts, cp->co_consts, Py_EQ);
+ if (eq <= 0) goto unequal;
+ eq = PyObject_RichCompareBool(co->co_names, cp->co_names, Py_EQ);
+ if (eq <= 0) goto unequal;
+ eq = PyObject_RichCompareBool(co->co_varnames, cp->co_varnames, Py_EQ);
+ if (eq <= 0) goto unequal;
+ eq = PyObject_RichCompareBool(co->co_freevars, cp->co_freevars, Py_EQ);
+ if (eq <= 0) goto unequal;
+ eq = PyObject_RichCompareBool(co->co_cellvars, cp->co_cellvars, Py_EQ);
+ if (eq <= 0) goto unequal;
+
+ if (op == Py_EQ)
+ res = Py_True;
+ else
+ res = Py_False;
+ goto done;
unequal:
- if (eq < 0)
- return NULL;
- if (op == Py_NE)
- res = Py_True;
- else
- res = Py_False;
+ if (eq < 0)
+ return NULL;
+ if (op == Py_NE)
+ res = Py_True;
+ else
+ res = Py_False;
done:
- Py_INCREF(res);
- return res;
+ Py_INCREF(res);
+ return res;
}
static long
code_hash(PyCodeObject *co)
{
- long h, h0, h1, h2, h3, h4, h5, h6;
- h0 = PyObject_Hash(co->co_name);
- if (h0 == -1) return -1;
- h1 = PyObject_Hash(co->co_code);
- if (h1 == -1) return -1;
- h2 = PyObject_Hash(co->co_consts);
- if (h2 == -1) return -1;
- h3 = PyObject_Hash(co->co_names);
- if (h3 == -1) return -1;
- h4 = PyObject_Hash(co->co_varnames);
- if (h4 == -1) return -1;
- h5 = PyObject_Hash(co->co_freevars);
- if (h5 == -1) return -1;
- h6 = PyObject_Hash(co->co_cellvars);
- if (h6 == -1) return -1;
- h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
- co->co_argcount ^ co->co_nlocals ^ co->co_flags;
- if (h == -1) h = -2;
- return h;
+ long h, h0, h1, h2, h3, h4, h5, h6;
+ h0 = PyObject_Hash(co->co_name);
+ if (h0 == -1) return -1;
+ h1 = PyObject_Hash(co->co_code);
+ if (h1 == -1) return -1;
+ h2 = PyObject_Hash(co->co_consts);
+ if (h2 == -1) return -1;
+ h3 = PyObject_Hash(co->co_names);
+ if (h3 == -1) return -1;
+ h4 = PyObject_Hash(co->co_varnames);
+ if (h4 == -1) return -1;
+ h5 = PyObject_Hash(co->co_freevars);
+ if (h5 == -1) return -1;
+ h6 = PyObject_Hash(co->co_cellvars);
+ if (h6 == -1) return -1;
+ h = h0 ^ h1 ^ h2 ^ h3 ^ h4 ^ h5 ^ h6 ^
+ co->co_argcount ^ co->co_nlocals ^ co->co_flags;
+ if (h == -1) h = -2;
+ return h;
}
/* XXX code objects need to participate in GC? */
PyTypeObject PyCode_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "code",
- sizeof(PyCodeObject),
- 0,
- (destructor)code_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)code_compare, /* tp_compare */
- (reprfunc)code_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)code_hash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- code_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- code_richcompare, /* tp_richcompare */
- offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- code_memberlist, /* 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 */
- code_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "code",
+ sizeof(PyCodeObject),
+ 0,
+ (destructor)code_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)code_compare, /* tp_compare */
+ (reprfunc)code_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)code_hash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ code_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ code_richcompare, /* tp_richcompare */
+ offsetof(PyCodeObject, co_weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ code_memberlist, /* 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 */
+ code_new, /* tp_new */
};
/* Use co_lnotab to compute the line number from a bytecode index, addrq. See
@@ -517,17 +517,17 @@ PyTypeObject PyCode_Type = {
int
PyCode_Addr2Line(PyCodeObject *co, int addrq)
{
- int size = PyString_Size(co->co_lnotab) / 2;
- unsigned char *p = (unsigned char*)PyString_AsString(co->co_lnotab);
- int line = co->co_firstlineno;
- int addr = 0;
- while (--size >= 0) {
- addr += *p++;
- if (addr > addrq)
- break;
- line += *p++;
- }
- return line;
+ int size = PyString_Size(co->co_lnotab) / 2;
+ unsigned char *p = (unsigned char*)PyString_AsString(co->co_lnotab);
+ int line = co->co_firstlineno;
+ int addr = 0;
+ while (--size >= 0) {
+ addr += *p++;
+ if (addr > addrq)
+ break;
+ line += *p++;
+ }
+ return line;
}
/* Update *bounds to describe the first and one-past-the-last instructions in
@@ -535,47 +535,47 @@ PyCode_Addr2Line(PyCodeObject *co, int addrq)
int
_PyCode_CheckLineNumber(PyCodeObject* co, int lasti, PyAddrPair *bounds)
{
- int size, addr, line;
- unsigned char* p;
-
- p = (unsigned char*)PyString_AS_STRING(co->co_lnotab);
- size = PyString_GET_SIZE(co->co_lnotab) / 2;
-
- addr = 0;
- line = co->co_firstlineno;
- assert(line > 0);
-
- /* possible optimization: if f->f_lasti == instr_ub
- (likely to be a common case) then we already know
- instr_lb -- if we stored the matching value of p
- somwhere we could skip the first while loop. */
-
- /* See lnotab_notes.txt for the description of
- co_lnotab. A point to remember: increments to p
- come in (addr, line) pairs. */
-
- bounds->ap_lower = 0;
- while (size > 0) {
- if (addr + *p > lasti)
- break;
- addr += *p++;
- if (*p)
- bounds->ap_lower = addr;
- line += *p++;
- --size;
- }
-
- if (size > 0) {
- while (--size >= 0) {
- addr += *p++;
- if (*p++)
- break;
- }
- bounds->ap_upper = addr;
- }
- else {
- bounds->ap_upper = INT_MAX;
+ int size, addr, line;
+ unsigned char* p;
+
+ p = (unsigned char*)PyString_AS_STRING(co->co_lnotab);
+ size = PyString_GET_SIZE(co->co_lnotab) / 2;
+
+ addr = 0;
+ line = co->co_firstlineno;
+ assert(line > 0);
+
+ /* possible optimization: if f->f_lasti == instr_ub
+ (likely to be a common case) then we already know
+ instr_lb -- if we stored the matching value of p
+ somwhere we could skip the first while loop. */
+
+ /* See lnotab_notes.txt for the description of
+ co_lnotab. A point to remember: increments to p
+ come in (addr, line) pairs. */
+
+ bounds->ap_lower = 0;
+ while (size > 0) {
+ if (addr + *p > lasti)
+ break;
+ addr += *p++;
+ if (*p)
+ bounds->ap_lower = addr;
+ line += *p++;
+ --size;
+ }
+
+ if (size > 0) {
+ while (--size >= 0) {
+ addr += *p++;
+ if (*p++)
+ break;
}
+ bounds->ap_upper = addr;
+ }
+ else {
+ bounds->ap_upper = INT_MAX;
+ }
- return line;
+ return line;
}
diff --git a/Objects/complexobject.c b/Objects/complexobject.c
index 42e447d..5f26a6a 100644
--- a/Objects/complexobject.c
+++ b/Objects/complexobject.c
@@ -23,8 +23,8 @@
precision for practical use.
*/
-#define PREC_REPR 17
-#define PREC_STR 12
+#define PREC_REPR 17
+#define PREC_STR 12
/* elementary operations on complex numbers */
@@ -33,414 +33,414 @@ static Py_complex c_1 = {1., 0.};
Py_complex
c_sum(Py_complex a, Py_complex b)
{
- Py_complex r;
- r.real = a.real + b.real;
- r.imag = a.imag + b.imag;
- return r;
+ Py_complex r;
+ r.real = a.real + b.real;
+ r.imag = a.imag + b.imag;
+ return r;
}
Py_complex
c_diff(Py_complex a, Py_complex b)
{
- Py_complex r;
- r.real = a.real - b.real;
- r.imag = a.imag - b.imag;
- return r;
+ Py_complex r;
+ r.real = a.real - b.real;
+ r.imag = a.imag - b.imag;
+ return r;
}
Py_complex
c_neg(Py_complex a)
{
- Py_complex r;
- r.real = -a.real;
- r.imag = -a.imag;
- return r;
+ Py_complex r;
+ r.real = -a.real;
+ r.imag = -a.imag;
+ return r;
}
Py_complex
c_prod(Py_complex a, Py_complex b)
{
- Py_complex r;
- r.real = a.real*b.real - a.imag*b.imag;
- r.imag = a.real*b.imag + a.imag*b.real;
- return r;
+ Py_complex r;
+ r.real = a.real*b.real - a.imag*b.imag;
+ r.imag = a.real*b.imag + a.imag*b.real;
+ return r;
}
Py_complex
c_quot(Py_complex a, Py_complex b)
{
- /******************************************************************
- This was the original algorithm. It's grossly prone to spurious
- overflow and underflow errors. It also merrily divides by 0 despite
- checking for that(!). The code still serves a doc purpose here, as
- the algorithm following is a simple by-cases transformation of this
- one:
-
- Py_complex r;
- double d = b.real*b.real + b.imag*b.imag;
- if (d == 0.)
- errno = EDOM;
- r.real = (a.real*b.real + a.imag*b.imag)/d;
- r.imag = (a.imag*b.real - a.real*b.imag)/d;
- return r;
- ******************************************************************/
-
- /* This algorithm is better, and is pretty obvious: first divide the
- * numerators and denominator by whichever of {b.real, b.imag} has
- * larger magnitude. The earliest reference I found was to CACM
- * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
- * University). As usual, though, we're still ignoring all IEEE
- * endcases.
- */
- Py_complex r; /* the result */
- const double abs_breal = b.real < 0 ? -b.real : b.real;
- const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
-
- if (abs_breal >= abs_bimag) {
- /* divide tops and bottom by b.real */
- if (abs_breal == 0.0) {
- errno = EDOM;
- r.real = r.imag = 0.0;
- }
- else {
- const double ratio = b.imag / b.real;
- const double denom = b.real + b.imag * ratio;
- r.real = (a.real + a.imag * ratio) / denom;
- r.imag = (a.imag - a.real * ratio) / denom;
- }
- }
- else {
- /* divide tops and bottom by b.imag */
- const double ratio = b.real / b.imag;
- const double denom = b.real * ratio + b.imag;
- assert(b.imag != 0.0);
- r.real = (a.real * ratio + a.imag) / denom;
- r.imag = (a.imag * ratio - a.real) / denom;
- }
- return r;
+ /******************************************************************
+ This was the original algorithm. It's grossly prone to spurious
+ overflow and underflow errors. It also merrily divides by 0 despite
+ checking for that(!). The code still serves a doc purpose here, as
+ the algorithm following is a simple by-cases transformation of this
+ one:
+
+ Py_complex r;
+ double d = b.real*b.real + b.imag*b.imag;
+ if (d == 0.)
+ errno = EDOM;
+ r.real = (a.real*b.real + a.imag*b.imag)/d;
+ r.imag = (a.imag*b.real - a.real*b.imag)/d;
+ return r;
+ ******************************************************************/
+
+ /* This algorithm is better, and is pretty obvious: first divide the
+ * numerators and denominator by whichever of {b.real, b.imag} has
+ * larger magnitude. The earliest reference I found was to CACM
+ * Algorithm 116 (Complex Division, Robert L. Smith, Stanford
+ * University). As usual, though, we're still ignoring all IEEE
+ * endcases.
+ */
+ Py_complex r; /* the result */
+ const double abs_breal = b.real < 0 ? -b.real : b.real;
+ const double abs_bimag = b.imag < 0 ? -b.imag : b.imag;
+
+ if (abs_breal >= abs_bimag) {
+ /* divide tops and bottom by b.real */
+ if (abs_breal == 0.0) {
+ errno = EDOM;
+ r.real = r.imag = 0.0;
+ }
+ else {
+ const double ratio = b.imag / b.real;
+ const double denom = b.real + b.imag * ratio;
+ r.real = (a.real + a.imag * ratio) / denom;
+ r.imag = (a.imag - a.real * ratio) / denom;
+ }
+ }
+ else {
+ /* divide tops and bottom by b.imag */
+ const double ratio = b.real / b.imag;
+ const double denom = b.real * ratio + b.imag;
+ assert(b.imag != 0.0);
+ r.real = (a.real * ratio + a.imag) / denom;
+ r.imag = (a.imag * ratio - a.real) / denom;
+ }
+ return r;
}
Py_complex
c_pow(Py_complex a, Py_complex b)
{
- Py_complex r;
- double vabs,len,at,phase;
- if (b.real == 0. && b.imag == 0.) {
- r.real = 1.;
- r.imag = 0.;
- }
- else if (a.real == 0. && a.imag == 0.) {
- if (b.imag != 0. || b.real < 0.)
- errno = EDOM;
- r.real = 0.;
- r.imag = 0.;
- }
- else {
- vabs = hypot(a.real,a.imag);
- len = pow(vabs,b.real);
- at = atan2(a.imag, a.real);
- phase = at*b.real;
- if (b.imag != 0.0) {
- len /= exp(at*b.imag);
- phase += b.imag*log(vabs);
- }
- r.real = len*cos(phase);
- r.imag = len*sin(phase);
- }
- return r;
+ Py_complex r;
+ double vabs,len,at,phase;
+ if (b.real == 0. && b.imag == 0.) {
+ r.real = 1.;
+ r.imag = 0.;
+ }
+ else if (a.real == 0. && a.imag == 0.) {
+ if (b.imag != 0. || b.real < 0.)
+ errno = EDOM;
+ r.real = 0.;
+ r.imag = 0.;
+ }
+ else {
+ vabs = hypot(a.real,a.imag);
+ len = pow(vabs,b.real);
+ at = atan2(a.imag, a.real);
+ phase = at*b.real;
+ if (b.imag != 0.0) {
+ len /= exp(at*b.imag);
+ phase += b.imag*log(vabs);
+ }
+ r.real = len*cos(phase);
+ r.imag = len*sin(phase);
+ }
+ return r;
}
static Py_complex
c_powu(Py_complex x, long n)
{
- Py_complex r, p;
- long mask = 1;
- r = c_1;
- p = x;
- while (mask > 0 && n >= mask) {
- if (n & mask)
- r = c_prod(r,p);
- mask <<= 1;
- p = c_prod(p,p);
- }
- return r;
+ Py_complex r, p;
+ long mask = 1;
+ r = c_1;
+ p = x;
+ while (mask > 0 && n >= mask) {
+ if (n & mask)
+ r = c_prod(r,p);
+ mask <<= 1;
+ p = c_prod(p,p);
+ }
+ return r;
}
static Py_complex
c_powi(Py_complex x, long n)
{
- Py_complex cn;
-
- if (n > 100 || n < -100) {
- cn.real = (double) n;
- cn.imag = 0.;
- return c_pow(x,cn);
- }
- else if (n > 0)
- return c_powu(x,n);
- else
- return c_quot(c_1,c_powu(x,-n));
+ Py_complex cn;
+
+ if (n > 100 || n < -100) {
+ cn.real = (double) n;
+ cn.imag = 0.;
+ return c_pow(x,cn);
+ }
+ else if (n > 0)
+ return c_powu(x,n);
+ else
+ return c_quot(c_1,c_powu(x,-n));
}
double
c_abs(Py_complex z)
{
- /* sets errno = ERANGE on overflow; otherwise errno = 0 */
- double result;
-
- if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
- /* C99 rules: if either the real or the imaginary part is an
- infinity, return infinity, even if the other part is a
- NaN. */
- if (Py_IS_INFINITY(z.real)) {
- result = fabs(z.real);
- errno = 0;
- return result;
- }
- if (Py_IS_INFINITY(z.imag)) {
- result = fabs(z.imag);
- errno = 0;
- return result;
- }
- /* either the real or imaginary part is a NaN,
- and neither is infinite. Result should be NaN. */
- return Py_NAN;
- }
- result = hypot(z.real, z.imag);
- if (!Py_IS_FINITE(result))
- errno = ERANGE;
- else
- errno = 0;
- return result;
+ /* sets errno = ERANGE on overflow; otherwise errno = 0 */
+ double result;
+
+ if (!Py_IS_FINITE(z.real) || !Py_IS_FINITE(z.imag)) {
+ /* C99 rules: if either the real or the imaginary part is an
+ infinity, return infinity, even if the other part is a
+ NaN. */
+ if (Py_IS_INFINITY(z.real)) {
+ result = fabs(z.real);
+ errno = 0;
+ return result;
+ }
+ if (Py_IS_INFINITY(z.imag)) {
+ result = fabs(z.imag);
+ errno = 0;
+ return result;
+ }
+ /* either the real or imaginary part is a NaN,
+ and neither is infinite. Result should be NaN. */
+ return Py_NAN;
+ }
+ result = hypot(z.real, z.imag);
+ if (!Py_IS_FINITE(result))
+ errno = ERANGE;
+ else
+ errno = 0;
+ return result;
}
static PyObject *
complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval)
{
- PyObject *op;
+ PyObject *op;
- op = type->tp_alloc(type, 0);
- if (op != NULL)
- ((PyComplexObject *)op)->cval = cval;
- return op;
+ op = type->tp_alloc(type, 0);
+ if (op != NULL)
+ ((PyComplexObject *)op)->cval = cval;
+ return op;
}
PyObject *
PyComplex_FromCComplex(Py_complex cval)
{
- register PyComplexObject *op;
-
- /* Inline PyObject_New */
- op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
- if (op == NULL)
- return PyErr_NoMemory();
- PyObject_INIT(op, &PyComplex_Type);
- op->cval = cval;
- return (PyObject *) op;
+ register PyComplexObject *op;
+
+ /* Inline PyObject_New */
+ op = (PyComplexObject *) PyObject_MALLOC(sizeof(PyComplexObject));
+ if (op == NULL)
+ return PyErr_NoMemory();
+ PyObject_INIT(op, &PyComplex_Type);
+ op->cval = cval;
+ return (PyObject *) op;
}
static PyObject *
complex_subtype_from_doubles(PyTypeObject *type, double real, double imag)
{
- Py_complex c;
- c.real = real;
- c.imag = imag;
- return complex_subtype_from_c_complex(type, c);
+ Py_complex c;
+ c.real = real;
+ c.imag = imag;
+ return complex_subtype_from_c_complex(type, c);
}
PyObject *
PyComplex_FromDoubles(double real, double imag)
{
- Py_complex c;
- c.real = real;
- c.imag = imag;
- return PyComplex_FromCComplex(c);
+ Py_complex c;
+ c.real = real;
+ c.imag = imag;
+ return PyComplex_FromCComplex(c);
}
double
PyComplex_RealAsDouble(PyObject *op)
{
- if (PyComplex_Check(op)) {
- return ((PyComplexObject *)op)->cval.real;
- }
- else {
- return PyFloat_AsDouble(op);
- }
+ if (PyComplex_Check(op)) {
+ return ((PyComplexObject *)op)->cval.real;
+ }
+ else {
+ return PyFloat_AsDouble(op);
+ }
}
double
PyComplex_ImagAsDouble(PyObject *op)
{
- if (PyComplex_Check(op)) {
- return ((PyComplexObject *)op)->cval.imag;
- }
- else {
- return 0.0;
- }
+ if (PyComplex_Check(op)) {
+ return ((PyComplexObject *)op)->cval.imag;
+ }
+ else {
+ return 0.0;
+ }
}
static PyObject *
try_complex_special_method(PyObject *op) {
- PyObject *f;
- static PyObject *complexstr;
-
- if (complexstr == NULL) {
- complexstr = PyString_InternFromString("__complex__");
- if (complexstr == NULL)
- return NULL;
- }
- if (PyInstance_Check(op)) {
- f = PyObject_GetAttr(op, complexstr);
- if (f == NULL) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return NULL;
- }
- }
- else {
- f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);
- if (f == NULL && PyErr_Occurred())
- return NULL;
- }
- if (f != NULL) {
- PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
- Py_DECREF(f);
- return res;
- }
- return NULL;
+ PyObject *f;
+ static PyObject *complexstr;
+
+ if (complexstr == NULL) {
+ complexstr = PyString_InternFromString("__complex__");
+ if (complexstr == NULL)
+ return NULL;
+ }
+ if (PyInstance_Check(op)) {
+ f = PyObject_GetAttr(op, complexstr);
+ if (f == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ }
+ else {
+ f = _PyObject_LookupSpecial(op, "__complex__", &complexstr);
+ if (f == NULL && PyErr_Occurred())
+ return NULL;
+ }
+ if (f != NULL) {
+ PyObject *res = PyObject_CallFunctionObjArgs(f, NULL);
+ Py_DECREF(f);
+ return res;
+ }
+ return NULL;
}
Py_complex
PyComplex_AsCComplex(PyObject *op)
{
- Py_complex cv;
- PyObject *newop = NULL;
-
- assert(op);
- /* If op is already of type PyComplex_Type, return its value */
- if (PyComplex_Check(op)) {
- return ((PyComplexObject *)op)->cval;
- }
- /* If not, use op's __complex__ method, if it exists */
-
- /* return -1 on failure */
- cv.real = -1.;
- cv.imag = 0.;
-
- newop = try_complex_special_method(op);
-
- if (newop) {
- if (!PyComplex_Check(newop)) {
- PyErr_SetString(PyExc_TypeError,
- "__complex__ should return a complex object");
- Py_DECREF(newop);
- return cv;
- }
- cv = ((PyComplexObject *)newop)->cval;
- Py_DECREF(newop);
- return cv;
- }
- else if (PyErr_Occurred()) {
- return cv;
- }
- /* If neither of the above works, interpret op as a float giving the
- real part of the result, and fill in the imaginary part as 0. */
- else {
- /* PyFloat_AsDouble will return -1 on failure */
- cv.real = PyFloat_AsDouble(op);
- return cv;
- }
+ Py_complex cv;
+ PyObject *newop = NULL;
+
+ assert(op);
+ /* If op is already of type PyComplex_Type, return its value */
+ if (PyComplex_Check(op)) {
+ return ((PyComplexObject *)op)->cval;
+ }
+ /* If not, use op's __complex__ method, if it exists */
+
+ /* return -1 on failure */
+ cv.real = -1.;
+ cv.imag = 0.;
+
+ newop = try_complex_special_method(op);
+
+ if (newop) {
+ if (!PyComplex_Check(newop)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__complex__ should return a complex object");
+ Py_DECREF(newop);
+ return cv;
+ }
+ cv = ((PyComplexObject *)newop)->cval;
+ Py_DECREF(newop);
+ return cv;
+ }
+ else if (PyErr_Occurred()) {
+ return cv;
+ }
+ /* If neither of the above works, interpret op as a float giving the
+ real part of the result, and fill in the imaginary part as 0. */
+ else {
+ /* PyFloat_AsDouble will return -1 on failure */
+ cv.real = PyFloat_AsDouble(op);
+ return cv;
+ }
}
static void
complex_dealloc(PyObject *op)
{
- op->ob_type->tp_free(op);
+ op->ob_type->tp_free(op);
}
static PyObject *
complex_format(PyComplexObject *v, int precision, char format_code)
{
- PyObject *result = NULL;
- Py_ssize_t len;
-
- /* If these are non-NULL, they'll need to be freed. */
- char *pre = NULL;
- char *im = NULL;
- char *buf = NULL;
-
- /* These do not need to be freed. re is either an alias
- for pre or a pointer to a constant. lead and tail
- are pointers to constants. */
- char *re = NULL;
- char *lead = "";
- char *tail = "";
-
- if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
- re = "";
- im = PyOS_double_to_string(v->cval.imag, format_code,
- precision, 0, NULL);
- if (!im) {
- PyErr_NoMemory();
- goto done;
- }
- } else {
- /* Format imaginary part with sign, real part without */
- pre = PyOS_double_to_string(v->cval.real, format_code,
- precision, 0, NULL);
- if (!pre) {
- PyErr_NoMemory();
- goto done;
- }
- re = pre;
-
- im = PyOS_double_to_string(v->cval.imag, format_code,
- precision, Py_DTSF_SIGN, NULL);
- if (!im) {
- PyErr_NoMemory();
- goto done;
- }
- lead = "(";
- tail = ")";
- }
- /* Alloc the final buffer. Add one for the "j" in the format string,
- and one for the trailing zero. */
- len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
- buf = PyMem_Malloc(len);
- if (!buf) {
- PyErr_NoMemory();
- goto done;
- }
- PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
- result = PyString_FromString(buf);
+ PyObject *result = NULL;
+ Py_ssize_t len;
+
+ /* If these are non-NULL, they'll need to be freed. */
+ char *pre = NULL;
+ char *im = NULL;
+ char *buf = NULL;
+
+ /* These do not need to be freed. re is either an alias
+ for pre or a pointer to a constant. lead and tail
+ are pointers to constants. */
+ char *re = NULL;
+ char *lead = "";
+ char *tail = "";
+
+ if (v->cval.real == 0. && copysign(1.0, v->cval.real)==1.0) {
+ re = "";
+ im = PyOS_double_to_string(v->cval.imag, format_code,
+ precision, 0, NULL);
+ if (!im) {
+ PyErr_NoMemory();
+ goto done;
+ }
+ } else {
+ /* Format imaginary part with sign, real part without */
+ pre = PyOS_double_to_string(v->cval.real, format_code,
+ precision, 0, NULL);
+ if (!pre) {
+ PyErr_NoMemory();
+ goto done;
+ }
+ re = pre;
+
+ im = PyOS_double_to_string(v->cval.imag, format_code,
+ precision, Py_DTSF_SIGN, NULL);
+ if (!im) {
+ PyErr_NoMemory();
+ goto done;
+ }
+ lead = "(";
+ tail = ")";
+ }
+ /* Alloc the final buffer. Add one for the "j" in the format string,
+ and one for the trailing zero. */
+ len = strlen(lead) + strlen(re) + strlen(im) + strlen(tail) + 2;
+ buf = PyMem_Malloc(len);
+ if (!buf) {
+ PyErr_NoMemory();
+ goto done;
+ }
+ PyOS_snprintf(buf, len, "%s%s%sj%s", lead, re, im, tail);
+ result = PyString_FromString(buf);
done:
- PyMem_Free(im);
- PyMem_Free(pre);
- PyMem_Free(buf);
+ PyMem_Free(im);
+ PyMem_Free(pre);
+ PyMem_Free(buf);
- return result;
+ return result;
}
static int
complex_print(PyComplexObject *v, FILE *fp, int flags)
{
- PyObject *formatv;
- char *buf;
- if (flags & Py_PRINT_RAW)
- formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');
- else
- formatv = complex_format(v, 0, 'r');
- if (formatv == NULL)
- return -1;
- buf = PyString_AS_STRING(formatv);
- Py_BEGIN_ALLOW_THREADS
- fputs(buf, fp);
- Py_END_ALLOW_THREADS
- Py_DECREF(formatv);
- return 0;
+ PyObject *formatv;
+ char *buf;
+ if (flags & Py_PRINT_RAW)
+ formatv = complex_format(v, PyFloat_STR_PRECISION, 'g');
+ else
+ formatv = complex_format(v, 0, 'r');
+ if (formatv == NULL)
+ return -1;
+ buf = PyString_AS_STRING(formatv);
+ Py_BEGIN_ALLOW_THREADS
+ fputs(buf, fp);
+ Py_END_ALLOW_THREADS
+ Py_DECREF(formatv);
+ return 0;
}
static PyObject *
@@ -458,31 +458,31 @@ complex_str(PyComplexObject *v)
static long
complex_hash(PyComplexObject *v)
{
- long hashreal, hashimag, combined;
- hashreal = _Py_HashDouble(v->cval.real);
- if (hashreal == -1)
- return -1;
- hashimag = _Py_HashDouble(v->cval.imag);
- if (hashimag == -1)
- return -1;
- /* Note: if the imaginary part is 0, hashimag is 0 now,
- * so the following returns hashreal unchanged. This is
- * important because numbers of different types that
- * compare equal must have the same hash value, so that
- * hash(x + 0*j) must equal hash(x).
- */
- combined = hashreal + 1000003 * hashimag;
- if (combined == -1)
- combined = -2;
- return combined;
+ long hashreal, hashimag, combined;
+ hashreal = _Py_HashDouble(v->cval.real);
+ if (hashreal == -1)
+ return -1;
+ hashimag = _Py_HashDouble(v->cval.imag);
+ if (hashimag == -1)
+ return -1;
+ /* Note: if the imaginary part is 0, hashimag is 0 now,
+ * so the following returns hashreal unchanged. This is
+ * important because numbers of different types that
+ * compare equal must have the same hash value, so that
+ * hash(x + 0*j) must equal hash(x).
+ */
+ combined = hashreal + 1000003 * hashimag;
+ if (combined == -1)
+ combined = -2;
+ return combined;
}
/* This macro may return! */
#define TO_COMPLEX(obj, c) \
- if (PyComplex_Check(obj)) \
- c = ((PyComplexObject *)(obj))->cval; \
- else if (to_complex(&(obj), &(c)) < 0) \
- return (obj)
+ if (PyComplex_Check(obj)) \
+ c = ((PyComplexObject *)(obj))->cval; \
+ else if (to_complex(&(obj), &(c)) < 0) \
+ return (obj)
static int
to_complex(PyObject **pobj, Py_complex *pc)
@@ -491,368 +491,368 @@ to_complex(PyObject **pobj, Py_complex *pc)
pc->real = pc->imag = 0.0;
if (PyInt_Check(obj)) {
- pc->real = PyInt_AS_LONG(obj);
- return 0;
+ pc->real = PyInt_AS_LONG(obj);
+ return 0;
}
if (PyLong_Check(obj)) {
- pc->real = PyLong_AsDouble(obj);
- if (pc->real == -1.0 && PyErr_Occurred()) {
- *pobj = NULL;
- return -1;
- }
- return 0;
+ pc->real = PyLong_AsDouble(obj);
+ if (pc->real == -1.0 && PyErr_Occurred()) {
+ *pobj = NULL;
+ return -1;
+ }
+ return 0;
}
if (PyFloat_Check(obj)) {
- pc->real = PyFloat_AsDouble(obj);
- return 0;
+ pc->real = PyFloat_AsDouble(obj);
+ return 0;
}
Py_INCREF(Py_NotImplemented);
*pobj = Py_NotImplemented;
return -1;
}
-
+
static PyObject *
complex_add(PyObject *v, PyObject *w)
{
- Py_complex result;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- PyFPE_START_PROTECT("complex_add", return 0)
- result = c_sum(a, b);
- PyFPE_END_PROTECT(result)
- return PyComplex_FromCComplex(result);
+ Py_complex result;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ PyFPE_START_PROTECT("complex_add", return 0)
+ result = c_sum(a, b);
+ PyFPE_END_PROTECT(result)
+ return PyComplex_FromCComplex(result);
}
static PyObject *
complex_sub(PyObject *v, PyObject *w)
{
- Py_complex result;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);;
- PyFPE_START_PROTECT("complex_sub", return 0)
- result = c_diff(a, b);
- PyFPE_END_PROTECT(result)
- return PyComplex_FromCComplex(result);
+ Py_complex result;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);;
+ PyFPE_START_PROTECT("complex_sub", return 0)
+ result = c_diff(a, b);
+ PyFPE_END_PROTECT(result)
+ return PyComplex_FromCComplex(result);
}
static PyObject *
complex_mul(PyObject *v, PyObject *w)
{
- Py_complex result;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- PyFPE_START_PROTECT("complex_mul", return 0)
- result = c_prod(a, b);
- PyFPE_END_PROTECT(result)
- return PyComplex_FromCComplex(result);
+ Py_complex result;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ PyFPE_START_PROTECT("complex_mul", return 0)
+ result = c_prod(a, b);
+ PyFPE_END_PROTECT(result)
+ return PyComplex_FromCComplex(result);
}
static PyObject *
complex_div(PyObject *v, PyObject *w)
{
- Py_complex quot;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- PyFPE_START_PROTECT("complex_div", return 0)
- errno = 0;
- quot = c_quot(a, b);
- PyFPE_END_PROTECT(quot)
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
- return NULL;
- }
- return PyComplex_FromCComplex(quot);
+ Py_complex quot;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ PyFPE_START_PROTECT("complex_div", return 0)
+ errno = 0;
+ quot = c_quot(a, b);
+ PyFPE_END_PROTECT(quot)
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
+ return NULL;
+ }
+ return PyComplex_FromCComplex(quot);
}
static PyObject *
complex_classic_div(PyObject *v, PyObject *w)
{
- Py_complex quot;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- if (Py_DivisionWarningFlag >= 2 &&
- PyErr_Warn(PyExc_DeprecationWarning,
- "classic complex division") < 0)
- return NULL;
-
- PyFPE_START_PROTECT("complex_classic_div", return 0)
- errno = 0;
- quot = c_quot(a, b);
- PyFPE_END_PROTECT(quot)
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
- return NULL;
- }
- return PyComplex_FromCComplex(quot);
+ Py_complex quot;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ if (Py_DivisionWarningFlag >= 2 &&
+ PyErr_Warn(PyExc_DeprecationWarning,
+ "classic complex division") < 0)
+ return NULL;
+
+ PyFPE_START_PROTECT("complex_classic_div", return 0)
+ errno = 0;
+ quot = c_quot(a, b);
+ PyFPE_END_PROTECT(quot)
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "complex division by zero");
+ return NULL;
+ }
+ return PyComplex_FromCComplex(quot);
}
static PyObject *
complex_remainder(PyObject *v, PyObject *w)
{
- Py_complex div, mod;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "complex divmod(), // and % are deprecated") < 0)
- return NULL;
-
- errno = 0;
- div = c_quot(a, b); /* The raw divisor value. */
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
- return NULL;
- }
- div.real = floor(div.real); /* Use the floor of the real part. */
- div.imag = 0.0;
- mod = c_diff(a, c_prod(b, div));
-
- return PyComplex_FromCComplex(mod);
+ Py_complex div, mod;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "complex divmod(), // and % are deprecated") < 0)
+ return NULL;
+
+ errno = 0;
+ div = c_quot(a, b); /* The raw divisor value. */
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "complex remainder");
+ return NULL;
+ }
+ div.real = floor(div.real); /* Use the floor of the real part. */
+ div.imag = 0.0;
+ mod = c_diff(a, c_prod(b, div));
+
+ return PyComplex_FromCComplex(mod);
}
static PyObject *
complex_divmod(PyObject *v, PyObject *w)
{
- Py_complex div, mod;
- PyObject *d, *m, *z;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "complex divmod(), // and % are deprecated") < 0)
- return NULL;
-
- errno = 0;
- div = c_quot(a, b); /* The raw divisor value. */
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
- return NULL;
- }
- div.real = floor(div.real); /* Use the floor of the real part. */
- div.imag = 0.0;
- mod = c_diff(a, c_prod(b, div));
- d = PyComplex_FromCComplex(div);
- m = PyComplex_FromCComplex(mod);
- z = PyTuple_Pack(2, d, m);
- Py_XDECREF(d);
- Py_XDECREF(m);
- return z;
+ Py_complex div, mod;
+ PyObject *d, *m, *z;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "complex divmod(), // and % are deprecated") < 0)
+ return NULL;
+
+ errno = 0;
+ div = c_quot(a, b); /* The raw divisor value. */
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "complex divmod()");
+ return NULL;
+ }
+ div.real = floor(div.real); /* Use the floor of the real part. */
+ div.imag = 0.0;
+ mod = c_diff(a, c_prod(b, div));
+ d = PyComplex_FromCComplex(div);
+ m = PyComplex_FromCComplex(mod);
+ z = PyTuple_Pack(2, d, m);
+ Py_XDECREF(d);
+ Py_XDECREF(m);
+ return z;
}
static PyObject *
complex_pow(PyObject *v, PyObject *w, PyObject *z)
{
- Py_complex p;
- Py_complex exponent;
- long int_exponent;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- if (z!=Py_None) {
- PyErr_SetString(PyExc_ValueError, "complex modulo");
- return NULL;
- }
- PyFPE_START_PROTECT("complex_pow", return 0)
- errno = 0;
- exponent = b;
- int_exponent = (long)exponent.real;
- if (exponent.imag == 0. && exponent.real == int_exponent)
- p = c_powi(a,int_exponent);
- else
- p = c_pow(a,exponent);
-
- PyFPE_END_PROTECT(p)
- Py_ADJUST_ERANGE2(p.real, p.imag);
- if (errno == EDOM) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "0.0 to a negative or complex power");
- return NULL;
- }
- else if (errno == ERANGE) {
- PyErr_SetString(PyExc_OverflowError,
- "complex exponentiation");
- return NULL;
- }
- return PyComplex_FromCComplex(p);
+ Py_complex p;
+ Py_complex exponent;
+ long int_exponent;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ if (z!=Py_None) {
+ PyErr_SetString(PyExc_ValueError, "complex modulo");
+ return NULL;
+ }
+ PyFPE_START_PROTECT("complex_pow", return 0)
+ errno = 0;
+ exponent = b;
+ int_exponent = (long)exponent.real;
+ if (exponent.imag == 0. && exponent.real == int_exponent)
+ p = c_powi(a,int_exponent);
+ else
+ p = c_pow(a,exponent);
+
+ PyFPE_END_PROTECT(p)
+ Py_ADJUST_ERANGE2(p.real, p.imag);
+ if (errno == EDOM) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "0.0 to a negative or complex power");
+ return NULL;
+ }
+ else if (errno == ERANGE) {
+ PyErr_SetString(PyExc_OverflowError,
+ "complex exponentiation");
+ return NULL;
+ }
+ return PyComplex_FromCComplex(p);
}
static PyObject *
complex_int_div(PyObject *v, PyObject *w)
{
- PyObject *t, *r;
- Py_complex a, b;
- TO_COMPLEX(v, a);
- TO_COMPLEX(w, b);
- if (PyErr_Warn(PyExc_DeprecationWarning,
- "complex divmod(), // and % are deprecated") < 0)
- return NULL;
-
- t = complex_divmod(v, w);
- if (t != NULL) {
- r = PyTuple_GET_ITEM(t, 0);
- Py_INCREF(r);
- Py_DECREF(t);
- return r;
- }
- return NULL;
+ PyObject *t, *r;
+ Py_complex a, b;
+ TO_COMPLEX(v, a);
+ TO_COMPLEX(w, b);
+ if (PyErr_Warn(PyExc_DeprecationWarning,
+ "complex divmod(), // and % are deprecated") < 0)
+ return NULL;
+
+ t = complex_divmod(v, w);
+ if (t != NULL) {
+ r = PyTuple_GET_ITEM(t, 0);
+ Py_INCREF(r);
+ Py_DECREF(t);
+ return r;
+ }
+ return NULL;
}
static PyObject *
complex_neg(PyComplexObject *v)
{
- Py_complex neg;
- neg.real = -v->cval.real;
- neg.imag = -v->cval.imag;
- return PyComplex_FromCComplex(neg);
+ Py_complex neg;
+ neg.real = -v->cval.real;
+ neg.imag = -v->cval.imag;
+ return PyComplex_FromCComplex(neg);
}
static PyObject *
complex_pos(PyComplexObject *v)
{
- if (PyComplex_CheckExact(v)) {
- Py_INCREF(v);
- return (PyObject *)v;
- }
- else
- return PyComplex_FromCComplex(v->cval);
+ if (PyComplex_CheckExact(v)) {
+ Py_INCREF(v);
+ return (PyObject *)v;
+ }
+ else
+ return PyComplex_FromCComplex(v->cval);
}
static PyObject *
complex_abs(PyComplexObject *v)
{
- double result;
-
- PyFPE_START_PROTECT("complex_abs", return 0)
- result = c_abs(v->cval);
- PyFPE_END_PROTECT(result)
-
- if (errno == ERANGE) {
- PyErr_SetString(PyExc_OverflowError,
- "absolute value too large");
- return NULL;
- }
- return PyFloat_FromDouble(result);
+ double result;
+
+ PyFPE_START_PROTECT("complex_abs", return 0)
+ result = c_abs(v->cval);
+ PyFPE_END_PROTECT(result)
+
+ if (errno == ERANGE) {
+ PyErr_SetString(PyExc_OverflowError,
+ "absolute value too large");
+ return NULL;
+ }
+ return PyFloat_FromDouble(result);
}
static int
complex_nonzero(PyComplexObject *v)
{
- return v->cval.real != 0.0 || v->cval.imag != 0.0;
+ return v->cval.real != 0.0 || v->cval.imag != 0.0;
}
static int
complex_coerce(PyObject **pv, PyObject **pw)
{
- Py_complex cval;
- cval.imag = 0.;
- if (PyInt_Check(*pw)) {
- cval.real = (double)PyInt_AsLong(*pw);
- *pw = PyComplex_FromCComplex(cval);
- Py_INCREF(*pv);
- return 0;
- }
- else if (PyLong_Check(*pw)) {
- cval.real = PyLong_AsDouble(*pw);
- if (cval.real == -1.0 && PyErr_Occurred())
- return -1;
- *pw = PyComplex_FromCComplex(cval);
- Py_INCREF(*pv);
- return 0;
- }
- else if (PyFloat_Check(*pw)) {
- cval.real = PyFloat_AsDouble(*pw);
- *pw = PyComplex_FromCComplex(cval);
- Py_INCREF(*pv);
- return 0;
- }
- else if (PyComplex_Check(*pw)) {
- Py_INCREF(*pv);
- Py_INCREF(*pw);
- return 0;
- }
- return 1; /* Can't do it */
+ Py_complex cval;
+ cval.imag = 0.;
+ if (PyInt_Check(*pw)) {
+ cval.real = (double)PyInt_AsLong(*pw);
+ *pw = PyComplex_FromCComplex(cval);
+ Py_INCREF(*pv);
+ return 0;
+ }
+ else if (PyLong_Check(*pw)) {
+ cval.real = PyLong_AsDouble(*pw);
+ if (cval.real == -1.0 && PyErr_Occurred())
+ return -1;
+ *pw = PyComplex_FromCComplex(cval);
+ Py_INCREF(*pv);
+ return 0;
+ }
+ else if (PyFloat_Check(*pw)) {
+ cval.real = PyFloat_AsDouble(*pw);
+ *pw = PyComplex_FromCComplex(cval);
+ Py_INCREF(*pv);
+ return 0;
+ }
+ else if (PyComplex_Check(*pw)) {
+ Py_INCREF(*pv);
+ Py_INCREF(*pw);
+ return 0;
+ }
+ return 1; /* Can't do it */
}
static PyObject *
complex_richcompare(PyObject *v, PyObject *w, int op)
{
- int c;
- Py_complex i, j;
- PyObject *res;
-
- c = PyNumber_CoerceEx(&v, &w);
- if (c < 0)
- return NULL;
- if (c > 0) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- /* Make sure both arguments are complex. */
- if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
- Py_DECREF(v);
- Py_DECREF(w);
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- i = ((PyComplexObject *)v)->cval;
- j = ((PyComplexObject *)w)->cval;
- Py_DECREF(v);
- Py_DECREF(w);
-
- if (op != Py_EQ && op != Py_NE) {
- PyErr_SetString(PyExc_TypeError,
- "no ordering relation is defined for complex numbers");
- return NULL;
- }
-
- if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
- res = Py_True;
- else
- res = Py_False;
-
- Py_INCREF(res);
- return res;
+ int c;
+ Py_complex i, j;
+ PyObject *res;
+
+ c = PyNumber_CoerceEx(&v, &w);
+ if (c < 0)
+ return NULL;
+ if (c > 0) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ /* Make sure both arguments are complex. */
+ if (!(PyComplex_Check(v) && PyComplex_Check(w))) {
+ Py_DECREF(v);
+ Py_DECREF(w);
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ i = ((PyComplexObject *)v)->cval;
+ j = ((PyComplexObject *)w)->cval;
+ Py_DECREF(v);
+ Py_DECREF(w);
+
+ if (op != Py_EQ && op != Py_NE) {
+ PyErr_SetString(PyExc_TypeError,
+ "no ordering relation is defined for complex numbers");
+ return NULL;
+ }
+
+ if ((i.real == j.real && i.imag == j.imag) == (op == Py_EQ))
+ res = Py_True;
+ else
+ res = Py_False;
+
+ Py_INCREF(res);
+ return res;
}
static PyObject *
complex_int(PyObject *v)
{
- PyErr_SetString(PyExc_TypeError,
- "can't convert complex to int");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "can't convert complex to int");
+ return NULL;
}
static PyObject *
complex_long(PyObject *v)
{
- PyErr_SetString(PyExc_TypeError,
- "can't convert complex to long");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "can't convert complex to long");
+ return NULL;
}
static PyObject *
complex_float(PyObject *v)
{
- PyErr_SetString(PyExc_TypeError,
- "can't convert complex to float");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "can't convert complex to float");
+ return NULL;
}
static PyObject *
complex_conjugate(PyObject *self)
{
- Py_complex c;
- c = ((PyComplexObject *)self)->cval;
- c.imag = -c.imag;
- return PyComplex_FromCComplex(c);
+ Py_complex c;
+ c = ((PyComplexObject *)self)->cval;
+ c.imag = -c.imag;
+ return PyComplex_FromCComplex(c);
}
PyDoc_STRVAR(complex_conjugate_doc,
@@ -863,8 +863,8 @@ PyDoc_STRVAR(complex_conjugate_doc,
static PyObject *
complex_getnewargs(PyComplexObject *v)
{
- Py_complex c = v->cval;
- return Py_BuildValue("(dd)", c.real, c.imag);
+ Py_complex c = v->cval;
+ return Py_BuildValue("(dd)", c.real, c.imag);
}
PyDoc_STRVAR(complex__format__doc,
@@ -878,25 +878,25 @@ complex__format__(PyObject* self, PyObject* args)
PyObject *format_spec;
if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
- return NULL;
+ return NULL;
if (PyBytes_Check(format_spec))
- return _PyComplex_FormatAdvanced(self,
- PyBytes_AS_STRING(format_spec),
- PyBytes_GET_SIZE(format_spec));
+ return _PyComplex_FormatAdvanced(self,
+ PyBytes_AS_STRING(format_spec),
+ PyBytes_GET_SIZE(format_spec));
if (PyUnicode_Check(format_spec)) {
- /* Convert format_spec to a str */
- PyObject *result;
- PyObject *str_spec = PyObject_Str(format_spec);
+ /* Convert format_spec to a str */
+ PyObject *result;
+ PyObject *str_spec = PyObject_Str(format_spec);
- if (str_spec == NULL)
- return NULL;
+ if (str_spec == NULL)
+ return NULL;
- result = _PyComplex_FormatAdvanced(self,
- PyBytes_AS_STRING(str_spec),
- PyBytes_GET_SIZE(str_spec));
+ result = _PyComplex_FormatAdvanced(self,
+ PyBytes_AS_STRING(str_spec),
+ PyBytes_GET_SIZE(str_spec));
- Py_DECREF(str_spec);
- return result;
+ Py_DECREF(str_spec);
+ return result;
}
PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
return NULL;
@@ -906,10 +906,10 @@ complex__format__(PyObject* self, PyObject* args)
static PyObject *
complex_is_finite(PyObject *self)
{
- Py_complex c;
- c = ((PyComplexObject *)self)->cval;
- return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
- Py_IS_FINITE(c.imag)));
+ Py_complex c;
+ c = ((PyComplexObject *)self)->cval;
+ return PyBool_FromLong((long)(Py_IS_FINITE(c.real) &&
+ Py_IS_FINITE(c.imag)));
}
PyDoc_STRVAR(complex_is_finite_doc,
@@ -919,318 +919,318 @@ PyDoc_STRVAR(complex_is_finite_doc,
#endif
static PyMethodDef complex_methods[] = {
- {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
- complex_conjugate_doc},
+ {"conjugate", (PyCFunction)complex_conjugate, METH_NOARGS,
+ complex_conjugate_doc},
#if 0
- {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
- complex_is_finite_doc},
+ {"is_finite", (PyCFunction)complex_is_finite, METH_NOARGS,
+ complex_is_finite_doc},
#endif
- {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
- {"__format__", (PyCFunction)complex__format__,
- METH_VARARGS, complex__format__doc},
- {NULL, NULL} /* sentinel */
+ {"__getnewargs__", (PyCFunction)complex_getnewargs, METH_NOARGS},
+ {"__format__", (PyCFunction)complex__format__,
+ METH_VARARGS, complex__format__doc},
+ {NULL, NULL} /* sentinel */
};
static PyMemberDef complex_members[] = {
- {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
- "the real part of a complex number"},
- {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
- "the imaginary part of a complex number"},
- {0},
+ {"real", T_DOUBLE, offsetof(PyComplexObject, cval.real), READONLY,
+ "the real part of a complex number"},
+ {"imag", T_DOUBLE, offsetof(PyComplexObject, cval.imag), READONLY,
+ "the imaginary part of a complex number"},
+ {0},
};
static PyObject *
complex_subtype_from_string(PyTypeObject *type, PyObject *v)
{
- const char *s, *start;
- char *end;
- double x=0.0, y=0.0, z;
- int got_bracket=0;
+ const char *s, *start;
+ char *end;
+ double x=0.0, y=0.0, z;
+ int got_bracket=0;
#ifdef Py_USING_UNICODE
- char *s_buffer = NULL;
+ char *s_buffer = NULL;
#endif
- Py_ssize_t len;
+ Py_ssize_t len;
- if (PyString_Check(v)) {
- s = PyString_AS_STRING(v);
- len = PyString_GET_SIZE(v);
- }
+ if (PyString_Check(v)) {
+ s = PyString_AS_STRING(v);
+ len = PyString_GET_SIZE(v);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(v)) {
- s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
- if (s_buffer == NULL)
- return PyErr_NoMemory();
- if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
- PyUnicode_GET_SIZE(v),
- s_buffer,
- NULL))
- goto error;
- s = s_buffer;
- len = strlen(s);
- }
+ else if (PyUnicode_Check(v)) {
+ s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
+ if (s_buffer == NULL)
+ return PyErr_NoMemory();
+ if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
+ PyUnicode_GET_SIZE(v),
+ s_buffer,
+ NULL))
+ goto error;
+ s = s_buffer;
+ len = strlen(s);
+ }
#endif
- else if (PyObject_AsCharBuffer(v, &s, &len)) {
- PyErr_SetString(PyExc_TypeError,
- "complex() arg is not a string");
- return NULL;
- }
-
- /* position on first nonblank */
- start = s;
- while (Py_ISSPACE(*s))
- s++;
- if (*s == '(') {
- /* Skip over possible bracket from repr(). */
- got_bracket = 1;
- s++;
- while (Py_ISSPACE(*s))
- s++;
- }
-
- /* a valid complex string usually takes one of the three forms:
-
- <float> - real part only
- <float>j - imaginary part only
- <float><signed-float>j - real and imaginary parts
-
- where <float> represents any numeric string that's accepted by the
- float constructor (including 'nan', 'inf', 'infinity', etc.), and
- <signed-float> is any string of the form <float> whose first
- character is '+' or '-'.
-
- For backwards compatibility, the extra forms
-
- <float><sign>j
- <sign>j
- j
-
- are also accepted, though support for these forms may be removed from
- a future version of Python.
- */
-
- /* first look for forms starting with <float> */
- z = PyOS_string_to_double(s, &end, NULL);
- if (z == -1.0 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_ValueError))
- PyErr_Clear();
- else
- goto error;
- }
- if (end != s) {
- /* all 4 forms starting with <float> land here */
- s = end;
- if (*s == '+' || *s == '-') {
- /* <float><signed-float>j | <float><sign>j */
- x = z;
- y = PyOS_string_to_double(s, &end, NULL);
- if (y == -1.0 && PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_ValueError))
- PyErr_Clear();
- else
- goto error;
- }
- if (end != s)
- /* <float><signed-float>j */
- s = end;
- else {
- /* <float><sign>j */
- y = *s == '+' ? 1.0 : -1.0;
- s++;
- }
- if (!(*s == 'j' || *s == 'J'))
- goto parse_error;
- s++;
- }
- else if (*s == 'j' || *s == 'J') {
- /* <float>j */
- s++;
- y = z;
- }
- else
- /* <float> */
- x = z;
- }
- else {
- /* not starting with <float>; must be <sign>j or j */
- if (*s == '+' || *s == '-') {
- /* <sign>j */
- y = *s == '+' ? 1.0 : -1.0;
- s++;
- }
- else
- /* j */
- y = 1.0;
- if (!(*s == 'j' || *s == 'J'))
- goto parse_error;
- s++;
- }
-
- /* trailing whitespace and closing bracket */
- while (Py_ISSPACE(*s))
- s++;
- if (got_bracket) {
- /* if there was an opening parenthesis, then the corresponding
- closing parenthesis should be right here */
- if (*s != ')')
- goto parse_error;
- s++;
- while (Py_ISSPACE(*s))
- s++;
- }
-
- /* we should now be at the end of the string */
- if (s-start != len)
- goto parse_error;
+ else if (PyObject_AsCharBuffer(v, &s, &len)) {
+ PyErr_SetString(PyExc_TypeError,
+ "complex() arg is not a string");
+ return NULL;
+ }
+
+ /* position on first nonblank */
+ start = s;
+ while (Py_ISSPACE(*s))
+ s++;
+ if (*s == '(') {
+ /* Skip over possible bracket from repr(). */
+ got_bracket = 1;
+ s++;
+ while (Py_ISSPACE(*s))
+ s++;
+ }
+
+ /* a valid complex string usually takes one of the three forms:
+
+ <float> - real part only
+ <float>j - imaginary part only
+ <float><signed-float>j - real and imaginary parts
+
+ where <float> represents any numeric string that's accepted by the
+ float constructor (including 'nan', 'inf', 'infinity', etc.), and
+ <signed-float> is any string of the form <float> whose first
+ character is '+' or '-'.
+
+ For backwards compatibility, the extra forms
+
+ <float><sign>j
+ <sign>j
+ j
+
+ are also accepted, though support for these forms may be removed from
+ a future version of Python.
+ */
+
+ /* first look for forms starting with <float> */
+ z = PyOS_string_to_double(s, &end, NULL);
+ if (z == -1.0 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_ValueError))
+ PyErr_Clear();
+ else
+ goto error;
+ }
+ if (end != s) {
+ /* all 4 forms starting with <float> land here */
+ s = end;
+ if (*s == '+' || *s == '-') {
+ /* <float><signed-float>j | <float><sign>j */
+ x = z;
+ y = PyOS_string_to_double(s, &end, NULL);
+ if (y == -1.0 && PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_ValueError))
+ PyErr_Clear();
+ else
+ goto error;
+ }
+ if (end != s)
+ /* <float><signed-float>j */
+ s = end;
+ else {
+ /* <float><sign>j */
+ y = *s == '+' ? 1.0 : -1.0;
+ s++;
+ }
+ if (!(*s == 'j' || *s == 'J'))
+ goto parse_error;
+ s++;
+ }
+ else if (*s == 'j' || *s == 'J') {
+ /* <float>j */
+ s++;
+ y = z;
+ }
+ else
+ /* <float> */
+ x = z;
+ }
+ else {
+ /* not starting with <float>; must be <sign>j or j */
+ if (*s == '+' || *s == '-') {
+ /* <sign>j */
+ y = *s == '+' ? 1.0 : -1.0;
+ s++;
+ }
+ else
+ /* j */
+ y = 1.0;
+ if (!(*s == 'j' || *s == 'J'))
+ goto parse_error;
+ s++;
+ }
+
+ /* trailing whitespace and closing bracket */
+ while (Py_ISSPACE(*s))
+ s++;
+ if (got_bracket) {
+ /* if there was an opening parenthesis, then the corresponding
+ closing parenthesis should be right here */
+ if (*s != ')')
+ goto parse_error;
+ s++;
+ while (Py_ISSPACE(*s))
+ s++;
+ }
+
+ /* we should now be at the end of the string */
+ if (s-start != len)
+ goto parse_error;
#ifdef Py_USING_UNICODE
- if (s_buffer)
- PyMem_FREE(s_buffer);
+ if (s_buffer)
+ PyMem_FREE(s_buffer);
#endif
- return complex_subtype_from_doubles(type, x, y);
+ return complex_subtype_from_doubles(type, x, y);
parse_error:
- PyErr_SetString(PyExc_ValueError,
- "complex() arg is a malformed string");
+ PyErr_SetString(PyExc_ValueError,
+ "complex() arg is a malformed string");
error:
#ifdef Py_USING_UNICODE
- if (s_buffer)
- PyMem_FREE(s_buffer);
+ if (s_buffer)
+ PyMem_FREE(s_buffer);
#endif
- return NULL;
+ return NULL;
}
static PyObject *
complex_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *r, *i, *tmp;
- PyNumberMethods *nbr, *nbi = NULL;
- Py_complex cr, ci;
- int own_r = 0;
- int cr_is_complex = 0;
- int ci_is_complex = 0;
- static char *kwlist[] = {"real", "imag", 0};
-
- r = Py_False;
- i = NULL;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
- &r, &i))
- return NULL;
-
- /* Special-case for a single argument when type(arg) is complex. */
- if (PyComplex_CheckExact(r) && i == NULL &&
- type == &PyComplex_Type) {
- /* Note that we can't know whether it's safe to return
- a complex *subclass* instance as-is, hence the restriction
- to exact complexes here. If either the input or the
- output is a complex subclass, it will be handled below
- as a non-orthogonal vector. */
- Py_INCREF(r);
- return r;
- }
- if (PyString_Check(r) || PyUnicode_Check(r)) {
- if (i != NULL) {
- PyErr_SetString(PyExc_TypeError,
- "complex() can't take second arg"
- " if first is a string");
- return NULL;
- }
- return complex_subtype_from_string(type, r);
- }
- if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
- PyErr_SetString(PyExc_TypeError,
- "complex() second arg can't be a string");
- return NULL;
- }
-
- tmp = try_complex_special_method(r);
- if (tmp) {
- r = tmp;
- own_r = 1;
- }
- else if (PyErr_Occurred()) {
- return NULL;
- }
-
- nbr = r->ob_type->tp_as_number;
- if (i != NULL)
- nbi = i->ob_type->tp_as_number;
- if (nbr == NULL || nbr->nb_float == NULL ||
- ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
- PyErr_SetString(PyExc_TypeError,
- "complex() argument must be a string or a number");
- if (own_r) {
- Py_DECREF(r);
- }
- return NULL;
- }
-
- /* If we get this far, then the "real" and "imag" parts should
- both be treated as numbers, and the constructor should return a
- complex number equal to (real + imag*1j).
-
- Note that we do NOT assume the input to already be in canonical
- form; the "real" and "imag" parts might themselves be complex
- numbers, which slightly complicates the code below. */
- if (PyComplex_Check(r)) {
- /* Note that if r is of a complex subtype, we're only
- retaining its real & imag parts here, and the return
- value is (properly) of the builtin complex type. */
- cr = ((PyComplexObject*)r)->cval;
- cr_is_complex = 1;
- if (own_r) {
- Py_DECREF(r);
- }
- }
- else {
- /* The "real" part really is entirely real, and contributes
- nothing in the imaginary direction.
- Just treat it as a double. */
- tmp = PyNumber_Float(r);
- if (own_r) {
- /* r was a newly created complex number, rather
- than the original "real" argument. */
- Py_DECREF(r);
- }
- if (tmp == NULL)
- return NULL;
- if (!PyFloat_Check(tmp)) {
- PyErr_SetString(PyExc_TypeError,
- "float(r) didn't return a float");
- Py_DECREF(tmp);
- return NULL;
- }
- cr.real = PyFloat_AsDouble(tmp);
- cr.imag = 0.0; /* Shut up compiler warning */
- Py_DECREF(tmp);
- }
- if (i == NULL) {
- ci.real = 0.0;
- }
- else if (PyComplex_Check(i)) {
- ci = ((PyComplexObject*)i)->cval;
- ci_is_complex = 1;
- } else {
- /* The "imag" part really is entirely imaginary, and
- contributes nothing in the real direction.
- Just treat it as a double. */
- tmp = (*nbi->nb_float)(i);
- if (tmp == NULL)
- return NULL;
- ci.real = PyFloat_AsDouble(tmp);
- Py_DECREF(tmp);
- }
- /* If the input was in canonical form, then the "real" and "imag"
- parts are real numbers, so that ci.imag and cr.imag are zero.
- We need this correction in case they were not real numbers. */
-
- if (ci_is_complex) {
- cr.real -= ci.imag;
- }
- if (cr_is_complex) {
- ci.real += cr.imag;
- }
- return complex_subtype_from_doubles(type, cr.real, ci.real);
+ PyObject *r, *i, *tmp;
+ PyNumberMethods *nbr, *nbi = NULL;
+ Py_complex cr, ci;
+ int own_r = 0;
+ int cr_is_complex = 0;
+ int ci_is_complex = 0;
+ static char *kwlist[] = {"real", "imag", 0};
+
+ r = Py_False;
+ i = NULL;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OO:complex", kwlist,
+ &r, &i))
+ return NULL;
+
+ /* Special-case for a single argument when type(arg) is complex. */
+ if (PyComplex_CheckExact(r) && i == NULL &&
+ type == &PyComplex_Type) {
+ /* Note that we can't know whether it's safe to return
+ a complex *subclass* instance as-is, hence the restriction
+ to exact complexes here. If either the input or the
+ output is a complex subclass, it will be handled below
+ as a non-orthogonal vector. */
+ Py_INCREF(r);
+ return r;
+ }
+ if (PyString_Check(r) || PyUnicode_Check(r)) {
+ if (i != NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "complex() can't take second arg"
+ " if first is a string");
+ return NULL;
+ }
+ return complex_subtype_from_string(type, r);
+ }
+ if (i != NULL && (PyString_Check(i) || PyUnicode_Check(i))) {
+ PyErr_SetString(PyExc_TypeError,
+ "complex() second arg can't be a string");
+ return NULL;
+ }
+
+ tmp = try_complex_special_method(r);
+ if (tmp) {
+ r = tmp;
+ own_r = 1;
+ }
+ else if (PyErr_Occurred()) {
+ return NULL;
+ }
+
+ nbr = r->ob_type->tp_as_number;
+ if (i != NULL)
+ nbi = i->ob_type->tp_as_number;
+ if (nbr == NULL || nbr->nb_float == NULL ||
+ ((i != NULL) && (nbi == NULL || nbi->nb_float == NULL))) {
+ PyErr_SetString(PyExc_TypeError,
+ "complex() argument must be a string or a number");
+ if (own_r) {
+ Py_DECREF(r);
+ }
+ return NULL;
+ }
+
+ /* If we get this far, then the "real" and "imag" parts should
+ both be treated as numbers, and the constructor should return a
+ complex number equal to (real + imag*1j).
+
+ Note that we do NOT assume the input to already be in canonical
+ form; the "real" and "imag" parts might themselves be complex
+ numbers, which slightly complicates the code below. */
+ if (PyComplex_Check(r)) {
+ /* Note that if r is of a complex subtype, we're only
+ retaining its real & imag parts here, and the return
+ value is (properly) of the builtin complex type. */
+ cr = ((PyComplexObject*)r)->cval;
+ cr_is_complex = 1;
+ if (own_r) {
+ Py_DECREF(r);
+ }
+ }
+ else {
+ /* The "real" part really is entirely real, and contributes
+ nothing in the imaginary direction.
+ Just treat it as a double. */
+ tmp = PyNumber_Float(r);
+ if (own_r) {
+ /* r was a newly created complex number, rather
+ than the original "real" argument. */
+ Py_DECREF(r);
+ }
+ if (tmp == NULL)
+ return NULL;
+ if (!PyFloat_Check(tmp)) {
+ PyErr_SetString(PyExc_TypeError,
+ "float(r) didn't return a float");
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ cr.real = PyFloat_AsDouble(tmp);
+ cr.imag = 0.0; /* Shut up compiler warning */
+ Py_DECREF(tmp);
+ }
+ if (i == NULL) {
+ ci.real = 0.0;
+ }
+ else if (PyComplex_Check(i)) {
+ ci = ((PyComplexObject*)i)->cval;
+ ci_is_complex = 1;
+ } else {
+ /* The "imag" part really is entirely imaginary, and
+ contributes nothing in the real direction.
+ Just treat it as a double. */
+ tmp = (*nbi->nb_float)(i);
+ if (tmp == NULL)
+ return NULL;
+ ci.real = PyFloat_AsDouble(tmp);
+ Py_DECREF(tmp);
+ }
+ /* If the input was in canonical form, then the "real" and "imag"
+ parts are real numbers, so that ci.imag and cr.imag are zero.
+ We need this correction in case they were not real numbers. */
+
+ if (ci_is_complex) {
+ cr.real -= ci.imag;
+ }
+ if (cr_is_complex) {
+ ci.real += cr.imag;
+ }
+ return complex_subtype_from_doubles(type, cr.real, ci.real);
}
PyDoc_STRVAR(complex_doc,
@@ -1240,87 +1240,87 @@ PyDoc_STRVAR(complex_doc,
"This is equivalent to (real + imag*1j) where imag defaults to 0.");
static PyNumberMethods complex_as_number = {
- (binaryfunc)complex_add, /* nb_add */
- (binaryfunc)complex_sub, /* nb_subtract */
- (binaryfunc)complex_mul, /* nb_multiply */
- (binaryfunc)complex_classic_div, /* nb_divide */
- (binaryfunc)complex_remainder, /* nb_remainder */
- (binaryfunc)complex_divmod, /* nb_divmod */
- (ternaryfunc)complex_pow, /* nb_power */
- (unaryfunc)complex_neg, /* nb_negative */
- (unaryfunc)complex_pos, /* nb_positive */
- (unaryfunc)complex_abs, /* nb_absolute */
- (inquiry)complex_nonzero, /* nb_nonzero */
- 0, /* nb_invert */
- 0, /* nb_lshift */
- 0, /* nb_rshift */
- 0, /* nb_and */
- 0, /* nb_xor */
- 0, /* nb_or */
- complex_coerce, /* nb_coerce */
- complex_int, /* nb_int */
- complex_long, /* nb_long */
- complex_float, /* nb_float */
- 0, /* nb_oct */
- 0, /* nb_hex */
- 0, /* nb_inplace_add */
- 0, /* nb_inplace_subtract */
- 0, /* nb_inplace_multiply*/
- 0, /* nb_inplace_divide */
- 0, /* nb_inplace_remainder */
- 0, /* nb_inplace_power */
- 0, /* nb_inplace_lshift */
- 0, /* nb_inplace_rshift */
- 0, /* nb_inplace_and */
- 0, /* nb_inplace_xor */
- 0, /* nb_inplace_or */
- (binaryfunc)complex_int_div, /* nb_floor_divide */
- (binaryfunc)complex_div, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
+ (binaryfunc)complex_add, /* nb_add */
+ (binaryfunc)complex_sub, /* nb_subtract */
+ (binaryfunc)complex_mul, /* nb_multiply */
+ (binaryfunc)complex_classic_div, /* nb_divide */
+ (binaryfunc)complex_remainder, /* nb_remainder */
+ (binaryfunc)complex_divmod, /* nb_divmod */
+ (ternaryfunc)complex_pow, /* nb_power */
+ (unaryfunc)complex_neg, /* nb_negative */
+ (unaryfunc)complex_pos, /* nb_positive */
+ (unaryfunc)complex_abs, /* nb_absolute */
+ (inquiry)complex_nonzero, /* nb_nonzero */
+ 0, /* nb_invert */
+ 0, /* nb_lshift */
+ 0, /* nb_rshift */
+ 0, /* nb_and */
+ 0, /* nb_xor */
+ 0, /* nb_or */
+ complex_coerce, /* nb_coerce */
+ complex_int, /* nb_int */
+ complex_long, /* nb_long */
+ complex_float, /* nb_float */
+ 0, /* nb_oct */
+ 0, /* nb_hex */
+ 0, /* nb_inplace_add */
+ 0, /* nb_inplace_subtract */
+ 0, /* nb_inplace_multiply*/
+ 0, /* nb_inplace_divide */
+ 0, /* nb_inplace_remainder */
+ 0, /* nb_inplace_power */
+ 0, /* nb_inplace_lshift */
+ 0, /* nb_inplace_rshift */
+ 0, /* nb_inplace_and */
+ 0, /* nb_inplace_xor */
+ 0, /* nb_inplace_or */
+ (binaryfunc)complex_int_div, /* nb_floor_divide */
+ (binaryfunc)complex_div, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
};
PyTypeObject PyComplex_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "complex",
- sizeof(PyComplexObject),
- 0,
- complex_dealloc, /* tp_dealloc */
- (printfunc)complex_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)complex_repr, /* tp_repr */
- &complex_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)complex_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)complex_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- complex_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- complex_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- complex_methods, /* tp_methods */
- complex_members, /* 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 */
- PyType_GenericAlloc, /* tp_alloc */
- complex_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "complex",
+ sizeof(PyComplexObject),
+ 0,
+ complex_dealloc, /* tp_dealloc */
+ (printfunc)complex_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)complex_repr, /* tp_repr */
+ &complex_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)complex_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)complex_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ complex_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ complex_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ complex_methods, /* tp_methods */
+ complex_members, /* 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 */
+ PyType_GenericAlloc, /* tp_alloc */
+ complex_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
#endif
diff --git a/Objects/descrobject.c b/Objects/descrobject.c
index 168ba74..0b83233 100644
--- a/Objects/descrobject.c
+++ b/Objects/descrobject.c
@@ -6,645 +6,645 @@
static void
descr_dealloc(PyDescrObject *descr)
{
- _PyObject_GC_UNTRACK(descr);
- Py_XDECREF(descr->d_type);
- Py_XDECREF(descr->d_name);
- PyObject_GC_Del(descr);
+ _PyObject_GC_UNTRACK(descr);
+ Py_XDECREF(descr->d_type);
+ Py_XDECREF(descr->d_name);
+ PyObject_GC_Del(descr);
}
static char *
descr_name(PyDescrObject *descr)
{
- if (descr->d_name != NULL && PyString_Check(descr->d_name))
- return PyString_AS_STRING(descr->d_name);
- else
- return "?";
+ if (descr->d_name != NULL && PyString_Check(descr->d_name))
+ return PyString_AS_STRING(descr->d_name);
+ else
+ return "?";
}
static PyObject *
descr_repr(PyDescrObject *descr, char *format)
{
- return PyString_FromFormat(format, descr_name(descr),
- descr->d_type->tp_name);
+ return PyString_FromFormat(format, descr_name(descr),
+ descr->d_type->tp_name);
}
static PyObject *
method_repr(PyMethodDescrObject *descr)
{
- return descr_repr((PyDescrObject *)descr,
- "<method '%s' of '%s' objects>");
+ return descr_repr((PyDescrObject *)descr,
+ "<method '%s' of '%s' objects>");
}
static PyObject *
member_repr(PyMemberDescrObject *descr)
{
- return descr_repr((PyDescrObject *)descr,
- "<member '%s' of '%s' objects>");
+ return descr_repr((PyDescrObject *)descr,
+ "<member '%s' of '%s' objects>");
}
static PyObject *
getset_repr(PyGetSetDescrObject *descr)
{
- return descr_repr((PyDescrObject *)descr,
- "<attribute '%s' of '%s' objects>");
+ return descr_repr((PyDescrObject *)descr,
+ "<attribute '%s' of '%s' objects>");
}
static PyObject *
wrapperdescr_repr(PyWrapperDescrObject *descr)
{
- return descr_repr((PyDescrObject *)descr,
- "<slot wrapper '%s' of '%s' objects>");
+ return descr_repr((PyDescrObject *)descr,
+ "<slot wrapper '%s' of '%s' objects>");
}
static int
descr_check(PyDescrObject *descr, PyObject *obj, PyObject **pres)
{
- if (obj == NULL) {
- Py_INCREF(descr);
- *pres = (PyObject *)descr;
- return 1;
- }
- if (!PyObject_TypeCheck(obj, descr->d_type)) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%s' for '%s' objects "
- "doesn't apply to '%s' object",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name,
- obj->ob_type->tp_name);
- *pres = NULL;
- return 1;
- }
- return 0;
+ if (obj == NULL) {
+ Py_INCREF(descr);
+ *pres = (PyObject *)descr;
+ return 1;
+ }
+ if (!PyObject_TypeCheck(obj, descr->d_type)) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%s' for '%s' objects "
+ "doesn't apply to '%s' object",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name,
+ obj->ob_type->tp_name);
+ *pres = NULL;
+ return 1;
+ }
+ return 0;
}
static PyObject *
classmethod_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type)
{
- /* Ensure a valid type. Class methods ignore obj. */
- if (type == NULL) {
- if (obj != NULL)
- type = (PyObject *)obj->ob_type;
- else {
- /* Wot - no type?! */
- PyErr_Format(PyExc_TypeError,
- "descriptor '%s' for type '%s' "
- "needs either an object or a type",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name);
- return NULL;
- }
- }
- if (!PyType_Check(type)) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%s' for type '%s' "
- "needs a type, not a '%s' as arg 2",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name,
- type->ob_type->tp_name);
- return NULL;
- }
- if (!PyType_IsSubtype((PyTypeObject *)type, descr->d_type)) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%s' for type '%s' "
- "doesn't apply to type '%s'",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name,
- ((PyTypeObject *)type)->tp_name);
- return NULL;
- }
- return PyCFunction_New(descr->d_method, type);
+ /* Ensure a valid type. Class methods ignore obj. */
+ if (type == NULL) {
+ if (obj != NULL)
+ type = (PyObject *)obj->ob_type;
+ else {
+ /* Wot - no type?! */
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%s' for type '%s' "
+ "needs either an object or a type",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name);
+ return NULL;
+ }
+ }
+ if (!PyType_Check(type)) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%s' for type '%s' "
+ "needs a type, not a '%s' as arg 2",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name,
+ type->ob_type->tp_name);
+ return NULL;
+ }
+ if (!PyType_IsSubtype((PyTypeObject *)type, descr->d_type)) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%s' for type '%s' "
+ "doesn't apply to type '%s'",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name,
+ ((PyTypeObject *)type)->tp_name);
+ return NULL;
+ }
+ return PyCFunction_New(descr->d_method, type);
}
static PyObject *
method_get(PyMethodDescrObject *descr, PyObject *obj, PyObject *type)
{
- PyObject *res;
+ PyObject *res;
- if (descr_check((PyDescrObject *)descr, obj, &res))
- return res;
- return PyCFunction_New(descr->d_method, obj);
+ if (descr_check((PyDescrObject *)descr, obj, &res))
+ return res;
+ return PyCFunction_New(descr->d_method, obj);
}
static PyObject *
member_get(PyMemberDescrObject *descr, PyObject *obj, PyObject *type)
{
- PyObject *res;
+ PyObject *res;
- if (descr_check((PyDescrObject *)descr, obj, &res))
- return res;
- return PyMember_GetOne((char *)obj, descr->d_member);
+ if (descr_check((PyDescrObject *)descr, obj, &res))
+ return res;
+ return PyMember_GetOne((char *)obj, descr->d_member);
}
static PyObject *
getset_get(PyGetSetDescrObject *descr, PyObject *obj, PyObject *type)
{
- PyObject *res;
+ PyObject *res;
- if (descr_check((PyDescrObject *)descr, obj, &res))
- return res;
- if (descr->d_getset->get != NULL)
- return descr->d_getset->get(obj, descr->d_getset->closure);
- PyErr_Format(PyExc_AttributeError,
- "attribute '%.300s' of '%.100s' objects is not readable",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name);
- return NULL;
+ if (descr_check((PyDescrObject *)descr, obj, &res))
+ return res;
+ if (descr->d_getset->get != NULL)
+ return descr->d_getset->get(obj, descr->d_getset->closure);
+ PyErr_Format(PyExc_AttributeError,
+ "attribute '%.300s' of '%.100s' objects is not readable",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name);
+ return NULL;
}
static PyObject *
wrapperdescr_get(PyWrapperDescrObject *descr, PyObject *obj, PyObject *type)
{
- PyObject *res;
+ PyObject *res;
- if (descr_check((PyDescrObject *)descr, obj, &res))
- return res;
- return PyWrapper_New((PyObject *)descr, obj);
+ if (descr_check((PyDescrObject *)descr, obj, &res))
+ return res;
+ return PyWrapper_New((PyObject *)descr, obj);
}
static int
descr_setcheck(PyDescrObject *descr, PyObject *obj, PyObject *value,
- int *pres)
-{
- assert(obj != NULL);
- if (!PyObject_TypeCheck(obj, descr->d_type)) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%.200s' for '%.100s' objects "
- "doesn't apply to '%.100s' object",
- descr_name(descr),
- descr->d_type->tp_name,
- obj->ob_type->tp_name);
- *pres = -1;
- return 1;
- }
- return 0;
+ int *pres)
+{
+ assert(obj != NULL);
+ if (!PyObject_TypeCheck(obj, descr->d_type)) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%.200s' for '%.100s' objects "
+ "doesn't apply to '%.100s' object",
+ descr_name(descr),
+ descr->d_type->tp_name,
+ obj->ob_type->tp_name);
+ *pres = -1;
+ return 1;
+ }
+ return 0;
}
static int
member_set(PyMemberDescrObject *descr, PyObject *obj, PyObject *value)
{
- int res;
+ int res;
- if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
- return res;
- return PyMember_SetOne((char *)obj, descr->d_member, value);
+ if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
+ return res;
+ return PyMember_SetOne((char *)obj, descr->d_member, value);
}
static int
getset_set(PyGetSetDescrObject *descr, PyObject *obj, PyObject *value)
{
- int res;
+ int res;
- if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
- return res;
- if (descr->d_getset->set != NULL)
- return descr->d_getset->set(obj, value,
- descr->d_getset->closure);
- PyErr_Format(PyExc_AttributeError,
- "attribute '%.300s' of '%.100s' objects is not writable",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name);
- return -1;
+ if (descr_setcheck((PyDescrObject *)descr, obj, value, &res))
+ return res;
+ if (descr->d_getset->set != NULL)
+ return descr->d_getset->set(obj, value,
+ descr->d_getset->closure);
+ PyErr_Format(PyExc_AttributeError,
+ "attribute '%.300s' of '%.100s' objects is not writable",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name);
+ return -1;
}
static PyObject *
methoddescr_call(PyMethodDescrObject *descr, PyObject *args, PyObject *kwds)
{
- Py_ssize_t argc;
- PyObject *self, *func, *result;
-
- /* Make sure that the first argument is acceptable as 'self' */
- assert(PyTuple_Check(args));
- argc = PyTuple_GET_SIZE(args);
- if (argc < 1) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%.300s' of '%.100s' "
- "object needs an argument",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name);
- return NULL;
- }
- self = PyTuple_GET_ITEM(args, 0);
- if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%.200s' "
- "requires a '%.100s' object "
- "but received a '%.100s'",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name,
- self->ob_type->tp_name);
- return NULL;
- }
-
- func = PyCFunction_New(descr->d_method, self);
- if (func == NULL)
- return NULL;
- args = PyTuple_GetSlice(args, 1, argc);
- if (args == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- result = PyEval_CallObjectWithKeywords(func, args, kwds);
- Py_DECREF(args);
- Py_DECREF(func);
- return result;
+ Py_ssize_t argc;
+ PyObject *self, *func, *result;
+
+ /* Make sure that the first argument is acceptable as 'self' */
+ assert(PyTuple_Check(args));
+ argc = PyTuple_GET_SIZE(args);
+ if (argc < 1) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%.300s' of '%.100s' "
+ "object needs an argument",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name);
+ return NULL;
+ }
+ self = PyTuple_GET_ITEM(args, 0);
+ if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%.200s' "
+ "requires a '%.100s' object "
+ "but received a '%.100s'",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name,
+ self->ob_type->tp_name);
+ return NULL;
+ }
+
+ func = PyCFunction_New(descr->d_method, self);
+ if (func == NULL)
+ return NULL;
+ args = PyTuple_GetSlice(args, 1, argc);
+ if (args == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ result = PyEval_CallObjectWithKeywords(func, args, kwds);
+ Py_DECREF(args);
+ Py_DECREF(func);
+ return result;
}
static PyObject *
classmethoddescr_call(PyMethodDescrObject *descr, PyObject *args,
- PyObject *kwds)
+ PyObject *kwds)
{
- PyObject *func, *result;
+ PyObject *func, *result;
- func = PyCFunction_New(descr->d_method, (PyObject *)descr->d_type);
- if (func == NULL)
- return NULL;
+ func = PyCFunction_New(descr->d_method, (PyObject *)descr->d_type);
+ if (func == NULL)
+ return NULL;
- result = PyEval_CallObjectWithKeywords(func, args, kwds);
- Py_DECREF(func);
- return result;
+ result = PyEval_CallObjectWithKeywords(func, args, kwds);
+ Py_DECREF(func);
+ return result;
}
static PyObject *
wrapperdescr_call(PyWrapperDescrObject *descr, PyObject *args, PyObject *kwds)
{
- Py_ssize_t argc;
- PyObject *self, *func, *result;
-
- /* Make sure that the first argument is acceptable as 'self' */
- assert(PyTuple_Check(args));
- argc = PyTuple_GET_SIZE(args);
- if (argc < 1) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%.300s' of '%.100s' "
- "object needs an argument",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name);
- return NULL;
- }
- self = PyTuple_GET_ITEM(args, 0);
- if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
- PyErr_Format(PyExc_TypeError,
- "descriptor '%.200s' "
- "requires a '%.100s' object "
- "but received a '%.100s'",
- descr_name((PyDescrObject *)descr),
- descr->d_type->tp_name,
- self->ob_type->tp_name);
- return NULL;
- }
-
- func = PyWrapper_New((PyObject *)descr, self);
- if (func == NULL)
- return NULL;
- args = PyTuple_GetSlice(args, 1, argc);
- if (args == NULL) {
- Py_DECREF(func);
- return NULL;
- }
- result = PyEval_CallObjectWithKeywords(func, args, kwds);
- Py_DECREF(args);
- Py_DECREF(func);
- return result;
+ Py_ssize_t argc;
+ PyObject *self, *func, *result;
+
+ /* Make sure that the first argument is acceptable as 'self' */
+ assert(PyTuple_Check(args));
+ argc = PyTuple_GET_SIZE(args);
+ if (argc < 1) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%.300s' of '%.100s' "
+ "object needs an argument",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name);
+ return NULL;
+ }
+ self = PyTuple_GET_ITEM(args, 0);
+ if (!PyObject_IsInstance(self, (PyObject *)(descr->d_type))) {
+ PyErr_Format(PyExc_TypeError,
+ "descriptor '%.200s' "
+ "requires a '%.100s' object "
+ "but received a '%.100s'",
+ descr_name((PyDescrObject *)descr),
+ descr->d_type->tp_name,
+ self->ob_type->tp_name);
+ return NULL;
+ }
+
+ func = PyWrapper_New((PyObject *)descr, self);
+ if (func == NULL)
+ return NULL;
+ args = PyTuple_GetSlice(args, 1, argc);
+ if (args == NULL) {
+ Py_DECREF(func);
+ return NULL;
+ }
+ result = PyEval_CallObjectWithKeywords(func, args, kwds);
+ Py_DECREF(args);
+ Py_DECREF(func);
+ return result;
}
static PyObject *
method_get_doc(PyMethodDescrObject *descr, void *closure)
{
- if (descr->d_method->ml_doc == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(descr->d_method->ml_doc);
+ if (descr->d_method->ml_doc == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(descr->d_method->ml_doc);
}
static PyMemberDef descr_members[] = {
- {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY},
- {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY},
- {0}
+ {"__objclass__", T_OBJECT, offsetof(PyDescrObject, d_type), READONLY},
+ {"__name__", T_OBJECT, offsetof(PyDescrObject, d_name), READONLY},
+ {0}
};
static PyGetSetDef method_getset[] = {
- {"__doc__", (getter)method_get_doc},
- {0}
+ {"__doc__", (getter)method_get_doc},
+ {0}
};
static PyObject *
member_get_doc(PyMemberDescrObject *descr, void *closure)
{
- if (descr->d_member->doc == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(descr->d_member->doc);
+ if (descr->d_member->doc == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(descr->d_member->doc);
}
static PyGetSetDef member_getset[] = {
- {"__doc__", (getter)member_get_doc},
- {0}
+ {"__doc__", (getter)member_get_doc},
+ {0}
};
static PyObject *
getset_get_doc(PyGetSetDescrObject *descr, void *closure)
{
- if (descr->d_getset->doc == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(descr->d_getset->doc);
+ if (descr->d_getset->doc == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(descr->d_getset->doc);
}
static PyGetSetDef getset_getset[] = {
- {"__doc__", (getter)getset_get_doc},
- {0}
+ {"__doc__", (getter)getset_get_doc},
+ {0}
};
static PyObject *
wrapperdescr_get_doc(PyWrapperDescrObject *descr, void *closure)
{
- if (descr->d_base->doc == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromString(descr->d_base->doc);
+ if (descr->d_base->doc == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromString(descr->d_base->doc);
}
static PyGetSetDef wrapperdescr_getset[] = {
- {"__doc__", (getter)wrapperdescr_get_doc},
- {0}
+ {"__doc__", (getter)wrapperdescr_get_doc},
+ {0}
};
static int
descr_traverse(PyObject *self, visitproc visit, void *arg)
{
- PyDescrObject *descr = (PyDescrObject *)self;
- Py_VISIT(descr->d_type);
- return 0;
+ PyDescrObject *descr = (PyDescrObject *)self;
+ Py_VISIT(descr->d_type);
+ return 0;
}
static PyTypeObject PyMethodDescr_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "method_descriptor",
- sizeof(PyMethodDescrObject),
- 0,
- (destructor)descr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)method_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)methoddescr_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- descr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- descr_members, /* tp_members */
- method_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)method_get, /* tp_descr_get */
- 0, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "method_descriptor",
+ sizeof(PyMethodDescrObject),
+ 0,
+ (destructor)descr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)method_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)methoddescr_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ descr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ descr_members, /* tp_members */
+ method_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)method_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
/* This is for METH_CLASS in C, not for "f = classmethod(f)" in Python! */
static PyTypeObject PyClassMethodDescr_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "classmethod_descriptor",
- sizeof(PyMethodDescrObject),
- 0,
- (destructor)descr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)method_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)classmethoddescr_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- descr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- descr_members, /* tp_members */
- method_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)classmethod_get, /* tp_descr_get */
- 0, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "classmethod_descriptor",
+ sizeof(PyMethodDescrObject),
+ 0,
+ (destructor)descr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)method_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)classmethoddescr_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ descr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ descr_members, /* tp_members */
+ method_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)classmethod_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
PyTypeObject PyMemberDescr_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "member_descriptor",
- sizeof(PyMemberDescrObject),
- 0,
- (destructor)descr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)member_repr, /* 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_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- descr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- descr_members, /* tp_members */
- member_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)member_get, /* tp_descr_get */
- (descrsetfunc)member_set, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "member_descriptor",
+ sizeof(PyMemberDescrObject),
+ 0,
+ (destructor)descr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)member_repr, /* 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_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ descr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ descr_members, /* tp_members */
+ member_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)member_get, /* tp_descr_get */
+ (descrsetfunc)member_set, /* tp_descr_set */
};
PyTypeObject PyGetSetDescr_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "getset_descriptor",
- sizeof(PyGetSetDescrObject),
- 0,
- (destructor)descr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)getset_repr, /* 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_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- descr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- descr_members, /* tp_members */
- getset_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)getset_get, /* tp_descr_get */
- (descrsetfunc)getset_set, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "getset_descriptor",
+ sizeof(PyGetSetDescrObject),
+ 0,
+ (destructor)descr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)getset_repr, /* 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_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ descr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ descr_members, /* tp_members */
+ getset_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)getset_get, /* tp_descr_get */
+ (descrsetfunc)getset_set, /* tp_descr_set */
};
PyTypeObject PyWrapperDescr_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "wrapper_descriptor",
- sizeof(PyWrapperDescrObject),
- 0,
- (destructor)descr_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)wrapperdescr_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- (ternaryfunc)wrapperdescr_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- descr_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- descr_members, /* tp_members */
- wrapperdescr_getset, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- (descrgetfunc)wrapperdescr_get, /* tp_descr_get */
- 0, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "wrapper_descriptor",
+ sizeof(PyWrapperDescrObject),
+ 0,
+ (destructor)descr_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)wrapperdescr_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ (ternaryfunc)wrapperdescr_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ descr_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ descr_members, /* tp_members */
+ wrapperdescr_getset, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ (descrgetfunc)wrapperdescr_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
static PyDescrObject *
descr_new(PyTypeObject *descrtype, PyTypeObject *type, const char *name)
{
- PyDescrObject *descr;
+ PyDescrObject *descr;
- descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0);
- if (descr != NULL) {
- Py_XINCREF(type);
- descr->d_type = type;
- descr->d_name = PyString_InternFromString(name);
- if (descr->d_name == NULL) {
- Py_DECREF(descr);
- descr = NULL;
- }
- }
- return descr;
+ descr = (PyDescrObject *)PyType_GenericAlloc(descrtype, 0);
+ if (descr != NULL) {
+ Py_XINCREF(type);
+ descr->d_type = type;
+ descr->d_name = PyString_InternFromString(name);
+ if (descr->d_name == NULL) {
+ Py_DECREF(descr);
+ descr = NULL;
+ }
+ }
+ return descr;
}
PyObject *
PyDescr_NewMethod(PyTypeObject *type, PyMethodDef *method)
{
- PyMethodDescrObject *descr;
+ PyMethodDescrObject *descr;
- descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type,
- type, method->ml_name);
- if (descr != NULL)
- descr->d_method = method;
- return (PyObject *)descr;
+ descr = (PyMethodDescrObject *)descr_new(&PyMethodDescr_Type,
+ type, method->ml_name);
+ if (descr != NULL)
+ descr->d_method = method;
+ return (PyObject *)descr;
}
PyObject *
PyDescr_NewClassMethod(PyTypeObject *type, PyMethodDef *method)
{
- PyMethodDescrObject *descr;
+ PyMethodDescrObject *descr;
- descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type,
- type, method->ml_name);
- if (descr != NULL)
- descr->d_method = method;
- return (PyObject *)descr;
+ descr = (PyMethodDescrObject *)descr_new(&PyClassMethodDescr_Type,
+ type, method->ml_name);
+ if (descr != NULL)
+ descr->d_method = method;
+ return (PyObject *)descr;
}
PyObject *
PyDescr_NewMember(PyTypeObject *type, PyMemberDef *member)
{
- PyMemberDescrObject *descr;
+ PyMemberDescrObject *descr;
- descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type,
- type, member->name);
- if (descr != NULL)
- descr->d_member = member;
- return (PyObject *)descr;
+ descr = (PyMemberDescrObject *)descr_new(&PyMemberDescr_Type,
+ type, member->name);
+ if (descr != NULL)
+ descr->d_member = member;
+ return (PyObject *)descr;
}
PyObject *
PyDescr_NewGetSet(PyTypeObject *type, PyGetSetDef *getset)
{
- PyGetSetDescrObject *descr;
+ PyGetSetDescrObject *descr;
- descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type,
- type, getset->name);
- if (descr != NULL)
- descr->d_getset = getset;
- return (PyObject *)descr;
+ descr = (PyGetSetDescrObject *)descr_new(&PyGetSetDescr_Type,
+ type, getset->name);
+ if (descr != NULL)
+ descr->d_getset = getset;
+ return (PyObject *)descr;
}
PyObject *
PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped)
{
- PyWrapperDescrObject *descr;
+ PyWrapperDescrObject *descr;
- descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type,
- type, base->name);
- if (descr != NULL) {
- descr->d_base = base;
- descr->d_wrapped = wrapped;
- }
- return (PyObject *)descr;
+ descr = (PyWrapperDescrObject *)descr_new(&PyWrapperDescr_Type,
+ type, base->name);
+ if (descr != NULL) {
+ descr->d_base = base;
+ descr->d_wrapped = wrapped;
+ }
+ return (PyObject *)descr;
}
@@ -654,221 +654,221 @@ PyDescr_NewWrapper(PyTypeObject *type, struct wrapperbase *base, void *wrapped)
bit of a pain */
typedef struct {
- PyObject_HEAD
- PyObject *dict;
+ PyObject_HEAD
+ PyObject *dict;
} proxyobject;
static Py_ssize_t
proxy_len(proxyobject *pp)
{
- return PyObject_Size(pp->dict);
+ return PyObject_Size(pp->dict);
}
static PyObject *
proxy_getitem(proxyobject *pp, PyObject *key)
{
- return PyObject_GetItem(pp->dict, key);
+ return PyObject_GetItem(pp->dict, key);
}
static PyMappingMethods proxy_as_mapping = {
- (lenfunc)proxy_len, /* mp_length */
- (binaryfunc)proxy_getitem, /* mp_subscript */
- 0, /* mp_ass_subscript */
+ (lenfunc)proxy_len, /* mp_length */
+ (binaryfunc)proxy_getitem, /* mp_subscript */
+ 0, /* mp_ass_subscript */
};
static int
proxy_contains(proxyobject *pp, PyObject *key)
{
- return PyDict_Contains(pp->dict, key);
+ return PyDict_Contains(pp->dict, key);
}
static PySequenceMethods proxy_as_sequence = {
- 0, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)proxy_contains, /* sq_contains */
- 0, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)proxy_contains, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
static PyObject *
proxy_has_key(proxyobject *pp, PyObject *key)
{
- int res = PyDict_Contains(pp->dict, key);
- if (res < 0)
- return NULL;
- return PyBool_FromLong(res);
+ int res = PyDict_Contains(pp->dict, key);
+ if (res < 0)
+ return NULL;
+ return PyBool_FromLong(res);
}
static PyObject *
proxy_get(proxyobject *pp, PyObject *args)
{
- PyObject *key, *def = Py_None;
+ PyObject *key, *def = Py_None;
- if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def))
- return NULL;
- return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def);
+ if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &def))
+ return NULL;
+ return PyObject_CallMethod(pp->dict, "get", "(OO)", key, def);
}
static PyObject *
proxy_keys(proxyobject *pp)
{
- return PyMapping_Keys(pp->dict);
+ return PyMapping_Keys(pp->dict);
}
static PyObject *
proxy_values(proxyobject *pp)
{
- return PyMapping_Values(pp->dict);
+ return PyMapping_Values(pp->dict);
}
static PyObject *
proxy_items(proxyobject *pp)
{
- return PyMapping_Items(pp->dict);
+ return PyMapping_Items(pp->dict);
}
static PyObject *
proxy_iterkeys(proxyobject *pp)
{
- return PyObject_CallMethod(pp->dict, "iterkeys", NULL);
+ return PyObject_CallMethod(pp->dict, "iterkeys", NULL);
}
static PyObject *
proxy_itervalues(proxyobject *pp)
{
- return PyObject_CallMethod(pp->dict, "itervalues", NULL);
+ return PyObject_CallMethod(pp->dict, "itervalues", NULL);
}
static PyObject *
proxy_iteritems(proxyobject *pp)
{
- return PyObject_CallMethod(pp->dict, "iteritems", NULL);
+ return PyObject_CallMethod(pp->dict, "iteritems", NULL);
}
static PyObject *
proxy_copy(proxyobject *pp)
{
- return PyObject_CallMethod(pp->dict, "copy", NULL);
+ return PyObject_CallMethod(pp->dict, "copy", NULL);
}
static PyMethodDef proxy_methods[] = {
- {"has_key", (PyCFunction)proxy_has_key, METH_O,
- PyDoc_STR("D.has_key(k) -> True if D has a key k, else False")},
- {"get", (PyCFunction)proxy_get, METH_VARARGS,
- PyDoc_STR("D.get(k[,d]) -> D[k] if D.has_key(k), else d."
- " d defaults to None.")},
- {"keys", (PyCFunction)proxy_keys, METH_NOARGS,
- PyDoc_STR("D.keys() -> list of D's keys")},
- {"values", (PyCFunction)proxy_values, METH_NOARGS,
- PyDoc_STR("D.values() -> list of D's values")},
- {"items", (PyCFunction)proxy_items, METH_NOARGS,
- PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")},
- {"iterkeys", (PyCFunction)proxy_iterkeys, METH_NOARGS,
- PyDoc_STR("D.iterkeys() -> an iterator over the keys of D")},
- {"itervalues",(PyCFunction)proxy_itervalues, METH_NOARGS,
- PyDoc_STR("D.itervalues() -> an iterator over the values of D")},
- {"iteritems", (PyCFunction)proxy_iteritems, METH_NOARGS,
- PyDoc_STR("D.iteritems() ->"
- " an iterator over the (key, value) items of D")},
- {"copy", (PyCFunction)proxy_copy, METH_NOARGS,
- PyDoc_STR("D.copy() -> a shallow copy of D")},
- {0}
+ {"has_key", (PyCFunction)proxy_has_key, METH_O,
+ PyDoc_STR("D.has_key(k) -> True if D has a key k, else False")},
+ {"get", (PyCFunction)proxy_get, METH_VARARGS,
+ PyDoc_STR("D.get(k[,d]) -> D[k] if D.has_key(k), else d."
+ " d defaults to None.")},
+ {"keys", (PyCFunction)proxy_keys, METH_NOARGS,
+ PyDoc_STR("D.keys() -> list of D's keys")},
+ {"values", (PyCFunction)proxy_values, METH_NOARGS,
+ PyDoc_STR("D.values() -> list of D's values")},
+ {"items", (PyCFunction)proxy_items, METH_NOARGS,
+ PyDoc_STR("D.items() -> list of D's (key, value) pairs, as 2-tuples")},
+ {"iterkeys", (PyCFunction)proxy_iterkeys, METH_NOARGS,
+ PyDoc_STR("D.iterkeys() -> an iterator over the keys of D")},
+ {"itervalues",(PyCFunction)proxy_itervalues, METH_NOARGS,
+ PyDoc_STR("D.itervalues() -> an iterator over the values of D")},
+ {"iteritems", (PyCFunction)proxy_iteritems, METH_NOARGS,
+ PyDoc_STR("D.iteritems() ->"
+ " an iterator over the (key, value) items of D")},
+ {"copy", (PyCFunction)proxy_copy, METH_NOARGS,
+ PyDoc_STR("D.copy() -> a shallow copy of D")},
+ {0}
};
static void
proxy_dealloc(proxyobject *pp)
{
- _PyObject_GC_UNTRACK(pp);
- Py_DECREF(pp->dict);
- PyObject_GC_Del(pp);
+ _PyObject_GC_UNTRACK(pp);
+ Py_DECREF(pp->dict);
+ PyObject_GC_Del(pp);
}
static PyObject *
proxy_getiter(proxyobject *pp)
{
- return PyObject_GetIter(pp->dict);
+ return PyObject_GetIter(pp->dict);
}
static PyObject *
proxy_str(proxyobject *pp)
{
- return PyObject_Str(pp->dict);
+ return PyObject_Str(pp->dict);
}
static int
proxy_traverse(PyObject *self, visitproc visit, void *arg)
{
- proxyobject *pp = (proxyobject *)self;
- Py_VISIT(pp->dict);
- return 0;
+ proxyobject *pp = (proxyobject *)self;
+ Py_VISIT(pp->dict);
+ return 0;
}
static int
proxy_compare(proxyobject *v, PyObject *w)
{
- return PyObject_Compare(v->dict, w);
+ return PyObject_Compare(v->dict, w);
}
static PyObject *
proxy_richcompare(proxyobject *v, PyObject *w, int op)
{
- return PyObject_RichCompare(v->dict, w, op);
+ return PyObject_RichCompare(v->dict, w, op);
}
PyTypeObject PyDictProxy_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dictproxy", /* tp_name */
- sizeof(proxyobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)proxy_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)proxy_compare, /* tp_compare */
- 0, /* tp_repr */
- 0, /* tp_as_number */
- &proxy_as_sequence, /* tp_as_sequence */
- &proxy_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)proxy_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- proxy_traverse, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)proxy_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- (getiterfunc)proxy_getiter, /* tp_iter */
- 0, /* tp_iternext */
- proxy_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dictproxy", /* tp_name */
+ sizeof(proxyobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)proxy_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)proxy_compare, /* tp_compare */
+ 0, /* tp_repr */
+ 0, /* tp_as_number */
+ &proxy_as_sequence, /* tp_as_sequence */
+ &proxy_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)proxy_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ proxy_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)proxy_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)proxy_getiter, /* tp_iter */
+ 0, /* tp_iternext */
+ proxy_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
PyObject *
PyDictProxy_New(PyObject *dict)
{
- proxyobject *pp;
+ proxyobject *pp;
- pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type);
- if (pp != NULL) {
- Py_INCREF(dict);
- pp->dict = dict;
- _PyObject_GC_TRACK(pp);
- }
- return (PyObject *)pp;
+ pp = PyObject_GC_New(proxyobject, &PyDictProxy_Type);
+ if (pp != NULL) {
+ Py_INCREF(dict);
+ pp->dict = dict;
+ _PyObject_GC_TRACK(pp);
+ }
+ return (PyObject *)pp;
}
@@ -878,185 +878,185 @@ PyDictProxy_New(PyObject *dict)
bit of a pain */
typedef struct {
- PyObject_HEAD
- PyWrapperDescrObject *descr;
- PyObject *self;
+ PyObject_HEAD
+ PyWrapperDescrObject *descr;
+ PyObject *self;
} wrapperobject;
static void
wrapper_dealloc(wrapperobject *wp)
{
- PyObject_GC_UnTrack(wp);
- Py_TRASHCAN_SAFE_BEGIN(wp)
- Py_XDECREF(wp->descr);
- Py_XDECREF(wp->self);
- PyObject_GC_Del(wp);
- Py_TRASHCAN_SAFE_END(wp)
+ PyObject_GC_UnTrack(wp);
+ Py_TRASHCAN_SAFE_BEGIN(wp)
+ Py_XDECREF(wp->descr);
+ Py_XDECREF(wp->self);
+ PyObject_GC_Del(wp);
+ Py_TRASHCAN_SAFE_END(wp)
}
static int
wrapper_compare(wrapperobject *a, wrapperobject *b)
{
- if (a->descr == b->descr)
- return PyObject_Compare(a->self, b->self);
- else
- return (a->descr < b->descr) ? -1 : 1;
+ if (a->descr == b->descr)
+ return PyObject_Compare(a->self, b->self);
+ else
+ return (a->descr < b->descr) ? -1 : 1;
}
static long
wrapper_hash(wrapperobject *wp)
{
- int x, y;
- x = _Py_HashPointer(wp->descr);
- if (x == -1)
- return -1;
- y = PyObject_Hash(wp->self);
- if (y == -1)
- return -1;
- x = x ^ y;
- if (x == -1)
- x = -2;
- return x;
+ int x, y;
+ x = _Py_HashPointer(wp->descr);
+ if (x == -1)
+ return -1;
+ y = PyObject_Hash(wp->self);
+ if (y == -1)
+ return -1;
+ x = x ^ y;
+ if (x == -1)
+ x = -2;
+ return x;
}
static PyObject *
wrapper_repr(wrapperobject *wp)
{
- return PyString_FromFormat("<method-wrapper '%s' of %s object at %p>",
- wp->descr->d_base->name,
- wp->self->ob_type->tp_name,
- wp->self);
+ return PyString_FromFormat("<method-wrapper '%s' of %s object at %p>",
+ wp->descr->d_base->name,
+ wp->self->ob_type->tp_name,
+ wp->self);
}
static PyMemberDef wrapper_members[] = {
- {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY},
- {0}
+ {"__self__", T_OBJECT, offsetof(wrapperobject, self), READONLY},
+ {0}
};
static PyObject *
wrapper_objclass(wrapperobject *wp)
{
- PyObject *c = (PyObject *)wp->descr->d_type;
+ PyObject *c = (PyObject *)wp->descr->d_type;
- Py_INCREF(c);
- return c;
+ Py_INCREF(c);
+ return c;
}
static PyObject *
wrapper_name(wrapperobject *wp)
{
- char *s = wp->descr->d_base->name;
+ char *s = wp->descr->d_base->name;
- return PyString_FromString(s);
+ return PyString_FromString(s);
}
static PyObject *
wrapper_doc(wrapperobject *wp)
{
- char *s = wp->descr->d_base->doc;
+ char *s = wp->descr->d_base->doc;
- if (s == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- else {
- return PyString_FromString(s);
- }
+ if (s == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ else {
+ return PyString_FromString(s);
+ }
}
static PyGetSetDef wrapper_getsets[] = {
- {"__objclass__", (getter)wrapper_objclass},
- {"__name__", (getter)wrapper_name},
- {"__doc__", (getter)wrapper_doc},
- {0}
+ {"__objclass__", (getter)wrapper_objclass},
+ {"__name__", (getter)wrapper_name},
+ {"__doc__", (getter)wrapper_doc},
+ {0}
};
static PyObject *
wrapper_call(wrapperobject *wp, PyObject *args, PyObject *kwds)
{
- wrapperfunc wrapper = wp->descr->d_base->wrapper;
- PyObject *self = wp->self;
+ wrapperfunc wrapper = wp->descr->d_base->wrapper;
+ PyObject *self = wp->self;
- if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) {
- wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper;
- return (*wk)(self, args, wp->descr->d_wrapped, kwds);
- }
+ if (wp->descr->d_base->flags & PyWrapperFlag_KEYWORDS) {
+ wrapperfunc_kwds wk = (wrapperfunc_kwds)wrapper;
+ return (*wk)(self, args, wp->descr->d_wrapped, kwds);
+ }
- if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) {
- PyErr_Format(PyExc_TypeError,
- "wrapper %s doesn't take keyword arguments",
- wp->descr->d_base->name);
- return NULL;
- }
- return (*wrapper)(self, args, wp->descr->d_wrapped);
+ if (kwds != NULL && (!PyDict_Check(kwds) || PyDict_Size(kwds) != 0)) {
+ PyErr_Format(PyExc_TypeError,
+ "wrapper %s doesn't take keyword arguments",
+ wp->descr->d_base->name);
+ return NULL;
+ }
+ return (*wrapper)(self, args, wp->descr->d_wrapped);
}
static int
wrapper_traverse(PyObject *self, visitproc visit, void *arg)
{
- wrapperobject *wp = (wrapperobject *)self;
- Py_VISIT(wp->descr);
- Py_VISIT(wp->self);
- return 0;
+ wrapperobject *wp = (wrapperobject *)self;
+ Py_VISIT(wp->descr);
+ Py_VISIT(wp->self);
+ return 0;
}
static PyTypeObject wrappertype = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "method-wrapper", /* tp_name */
- sizeof(wrapperobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)wrapper_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)wrapper_compare, /* tp_compare */
- (reprfunc)wrapper_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)wrapper_hash, /* tp_hash */
- (ternaryfunc)wrapper_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
- 0, /* tp_doc */
- wrapper_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- wrapper_members, /* tp_members */
- wrapper_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "method-wrapper", /* tp_name */
+ sizeof(wrapperobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)wrapper_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)wrapper_compare, /* tp_compare */
+ (reprfunc)wrapper_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)wrapper_hash, /* tp_hash */
+ (ternaryfunc)wrapper_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags */
+ 0, /* tp_doc */
+ wrapper_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ wrapper_members, /* tp_members */
+ wrapper_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
};
PyObject *
PyWrapper_New(PyObject *d, PyObject *self)
{
- wrapperobject *wp;
- PyWrapperDescrObject *descr;
+ wrapperobject *wp;
+ PyWrapperDescrObject *descr;
- assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type));
- descr = (PyWrapperDescrObject *)d;
- assert(PyObject_IsInstance(self, (PyObject *)(descr->d_type)));
+ assert(PyObject_TypeCheck(d, &PyWrapperDescr_Type));
+ descr = (PyWrapperDescrObject *)d;
+ assert(PyObject_IsInstance(self, (PyObject *)(descr->d_type)));
- wp = PyObject_GC_New(wrapperobject, &wrappertype);
- if (wp != NULL) {
- Py_INCREF(descr);
- wp->descr = descr;
- Py_INCREF(self);
- wp->self = self;
- _PyObject_GC_TRACK(wp);
- }
- return (PyObject *)wp;
+ wp = PyObject_GC_New(wrapperobject, &wrappertype);
+ if (wp != NULL) {
+ Py_INCREF(descr);
+ wp->descr = descr;
+ Py_INCREF(self);
+ wp->self = self;
+ _PyObject_GC_TRACK(wp);
+ }
+ return (PyObject *)wp;
}
@@ -1065,247 +1065,247 @@ PyWrapper_New(PyObject *d, PyObject *self)
/*
class property(object):
- def __init__(self, fget=None, fset=None, fdel=None, doc=None):
- if doc is None and fget is not None and hasattr(fget, "__doc__"):
- doc = fget.__doc__
- self.__get = fget
- self.__set = fset
- self.__del = fdel
- self.__doc__ = doc
-
- def __get__(self, inst, type=None):
- if inst is None:
- return self
- if self.__get is None:
- raise AttributeError, "unreadable attribute"
- return self.__get(inst)
-
- def __set__(self, inst, value):
- if self.__set is None:
- raise AttributeError, "can't set attribute"
- return self.__set(inst, value)
-
- def __delete__(self, inst):
- if self.__del is None:
- raise AttributeError, "can't delete attribute"
- return self.__del(inst)
+ def __init__(self, fget=None, fset=None, fdel=None, doc=None):
+ if doc is None and fget is not None and hasattr(fget, "__doc__"):
+ doc = fget.__doc__
+ self.__get = fget
+ self.__set = fset
+ self.__del = fdel
+ self.__doc__ = doc
+
+ def __get__(self, inst, type=None):
+ if inst is None:
+ return self
+ if self.__get is None:
+ raise AttributeError, "unreadable attribute"
+ return self.__get(inst)
+
+ def __set__(self, inst, value):
+ if self.__set is None:
+ raise AttributeError, "can't set attribute"
+ return self.__set(inst, value)
+
+ def __delete__(self, inst):
+ if self.__del is None:
+ raise AttributeError, "can't delete attribute"
+ return self.__del(inst)
*/
typedef struct {
- PyObject_HEAD
- PyObject *prop_get;
- PyObject *prop_set;
- PyObject *prop_del;
- PyObject *prop_doc;
- int getter_doc;
+ PyObject_HEAD
+ PyObject *prop_get;
+ PyObject *prop_set;
+ PyObject *prop_del;
+ PyObject *prop_doc;
+ int getter_doc;
} propertyobject;
static PyObject * property_copy(PyObject *, PyObject *, PyObject *,
- PyObject *, PyObject *);
+ PyObject *, PyObject *);
static PyMemberDef property_members[] = {
- {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY},
- {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY},
- {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY},
- {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY},
- {0}
+ {"fget", T_OBJECT, offsetof(propertyobject, prop_get), READONLY},
+ {"fset", T_OBJECT, offsetof(propertyobject, prop_set), READONLY},
+ {"fdel", T_OBJECT, offsetof(propertyobject, prop_del), READONLY},
+ {"__doc__", T_OBJECT, offsetof(propertyobject, prop_doc), READONLY},
+ {0}
};
PyDoc_STRVAR(getter_doc,
- "Descriptor to change the getter on a property.");
+ "Descriptor to change the getter on a property.");
static PyObject *
property_getter(PyObject *self, PyObject *getter)
{
- return property_copy(self, getter, NULL, NULL, NULL);
+ return property_copy(self, getter, NULL, NULL, NULL);
}
PyDoc_STRVAR(setter_doc,
- "Descriptor to change the setter on a property.");
+ "Descriptor to change the setter on a property.");
static PyObject *
property_setter(PyObject *self, PyObject *setter)
{
- return property_copy(self, NULL, setter, NULL, NULL);
+ return property_copy(self, NULL, setter, NULL, NULL);
}
PyDoc_STRVAR(deleter_doc,
- "Descriptor to change the deleter on a property.");
+ "Descriptor to change the deleter on a property.");
static PyObject *
property_deleter(PyObject *self, PyObject *deleter)
{
- return property_copy(self, NULL, NULL, deleter, NULL);
+ return property_copy(self, NULL, NULL, deleter, NULL);
}
static PyMethodDef property_methods[] = {
- {"getter", property_getter, METH_O, getter_doc},
- {"setter", property_setter, METH_O, setter_doc},
- {"deleter", property_deleter, METH_O, deleter_doc},
- {0}
+ {"getter", property_getter, METH_O, getter_doc},
+ {"setter", property_setter, METH_O, setter_doc},
+ {"deleter", property_deleter, METH_O, deleter_doc},
+ {0}
};
static void
property_dealloc(PyObject *self)
{
- propertyobject *gs = (propertyobject *)self;
+ propertyobject *gs = (propertyobject *)self;
- _PyObject_GC_UNTRACK(self);
- Py_XDECREF(gs->prop_get);
- Py_XDECREF(gs->prop_set);
- Py_XDECREF(gs->prop_del);
- Py_XDECREF(gs->prop_doc);
- self->ob_type->tp_free(self);
+ _PyObject_GC_UNTRACK(self);
+ Py_XDECREF(gs->prop_get);
+ Py_XDECREF(gs->prop_set);
+ Py_XDECREF(gs->prop_del);
+ Py_XDECREF(gs->prop_doc);
+ self->ob_type->tp_free(self);
}
static PyObject *
property_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
- propertyobject *gs = (propertyobject *)self;
+ propertyobject *gs = (propertyobject *)self;
- if (obj == NULL || obj == Py_None) {
- Py_INCREF(self);
- return self;
- }
- if (gs->prop_get == NULL) {
- PyErr_SetString(PyExc_AttributeError, "unreadable attribute");
- return NULL;
- }
- return PyObject_CallFunction(gs->prop_get, "(O)", obj);
+ if (obj == NULL || obj == Py_None) {
+ Py_INCREF(self);
+ return self;
+ }
+ if (gs->prop_get == NULL) {
+ PyErr_SetString(PyExc_AttributeError, "unreadable attribute");
+ return NULL;
+ }
+ return PyObject_CallFunction(gs->prop_get, "(O)", obj);
}
static int
property_descr_set(PyObject *self, PyObject *obj, PyObject *value)
{
- propertyobject *gs = (propertyobject *)self;
- PyObject *func, *res;
-
- if (value == NULL)
- func = gs->prop_del;
- else
- func = gs->prop_set;
- if (func == NULL) {
- PyErr_SetString(PyExc_AttributeError,
- value == NULL ?
- "can't delete attribute" :
- "can't set attribute");
- return -1;
- }
- if (value == NULL)
- res = PyObject_CallFunction(func, "(O)", obj);
- else
- res = PyObject_CallFunction(func, "(OO)", obj, value);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ propertyobject *gs = (propertyobject *)self;
+ PyObject *func, *res;
+
+ if (value == NULL)
+ func = gs->prop_del;
+ else
+ func = gs->prop_set;
+ if (func == NULL) {
+ PyErr_SetString(PyExc_AttributeError,
+ value == NULL ?
+ "can't delete attribute" :
+ "can't set attribute");
+ return -1;
+ }
+ if (value == NULL)
+ res = PyObject_CallFunction(func, "(O)", obj);
+ else
+ res = PyObject_CallFunction(func, "(OO)", obj, value);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static PyObject *
property_copy(PyObject *old, PyObject *get, PyObject *set, PyObject *del,
- PyObject *doc)
-{
- propertyobject *pold = (propertyobject *)old;
- PyObject *new, *type;
-
- type = PyObject_Type(old);
- if (type == NULL)
- return NULL;
-
- if (get == NULL || get == Py_None) {
- Py_XDECREF(get);
- get = pold->prop_get ? pold->prop_get : Py_None;
- }
- if (set == NULL || set == Py_None) {
- Py_XDECREF(set);
- set = pold->prop_set ? pold->prop_set : Py_None;
- }
- if (del == NULL || del == Py_None) {
- Py_XDECREF(del);
- del = pold->prop_del ? pold->prop_del : Py_None;
- }
- if (doc == NULL || doc == Py_None) {
- Py_XDECREF(doc);
- if (pold->getter_doc && get != Py_None) {
- /* make _init use __doc__ from getter */
- doc = Py_None;
- }
- else {
- doc = pold->prop_doc ? pold->prop_doc : Py_None;
- }
- }
-
- new = PyObject_CallFunction(type, "OOOO", get, set, del, doc);
- Py_DECREF(type);
- if (new == NULL)
- return NULL;
- return new;
+ PyObject *doc)
+{
+ propertyobject *pold = (propertyobject *)old;
+ PyObject *new, *type;
+
+ type = PyObject_Type(old);
+ if (type == NULL)
+ return NULL;
+
+ if (get == NULL || get == Py_None) {
+ Py_XDECREF(get);
+ get = pold->prop_get ? pold->prop_get : Py_None;
+ }
+ if (set == NULL || set == Py_None) {
+ Py_XDECREF(set);
+ set = pold->prop_set ? pold->prop_set : Py_None;
+ }
+ if (del == NULL || del == Py_None) {
+ Py_XDECREF(del);
+ del = pold->prop_del ? pold->prop_del : Py_None;
+ }
+ if (doc == NULL || doc == Py_None) {
+ Py_XDECREF(doc);
+ if (pold->getter_doc && get != Py_None) {
+ /* make _init use __doc__ from getter */
+ doc = Py_None;
+ }
+ else {
+ doc = pold->prop_doc ? pold->prop_doc : Py_None;
+ }
+ }
+
+ new = PyObject_CallFunction(type, "OOOO", get, set, del, doc);
+ Py_DECREF(type);
+ if (new == NULL)
+ return NULL;
+ return new;
}
static int
property_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL;
- static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0};
- propertyobject *prop = (propertyobject *)self;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property",
- kwlist, &get, &set, &del, &doc))
- return -1;
-
- if (get == Py_None)
- get = NULL;
- if (set == Py_None)
- set = NULL;
- if (del == Py_None)
- del = NULL;
-
- Py_XINCREF(get);
- Py_XINCREF(set);
- Py_XINCREF(del);
- Py_XINCREF(doc);
-
- prop->prop_get = get;
- prop->prop_set = set;
- prop->prop_del = del;
- prop->prop_doc = doc;
- prop->getter_doc = 0;
-
- /* if no docstring given and the getter has one, use that one */
- if ((doc == NULL || doc == Py_None) && get != NULL) {
- PyObject *get_doc = PyObject_GetAttrString(get, "__doc__");
- if (get_doc) {
- if (Py_TYPE(self) == &PyProperty_Type) {
- Py_XDECREF(prop->prop_doc);
- prop->prop_doc = get_doc;
- }
- else {
- /* If this is a property subclass, put __doc__
- in dict of the subclass instance instead,
- otherwise it gets shadowed by __doc__ in the
- class's dict. */
- int err = PyObject_SetAttrString(self, "__doc__", get_doc);
- Py_DECREF(get_doc);
- if (err < 0)
- return -1;
- }
- prop->getter_doc = 1;
- }
- else if (PyErr_ExceptionMatches(PyExc_Exception)) {
- PyErr_Clear();
- }
- else {
- return -1;
- }
- }
-
- return 0;
+ PyObject *get = NULL, *set = NULL, *del = NULL, *doc = NULL;
+ static char *kwlist[] = {"fget", "fset", "fdel", "doc", 0};
+ propertyobject *prop = (propertyobject *)self;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOOO:property",
+ kwlist, &get, &set, &del, &doc))
+ return -1;
+
+ if (get == Py_None)
+ get = NULL;
+ if (set == Py_None)
+ set = NULL;
+ if (del == Py_None)
+ del = NULL;
+
+ Py_XINCREF(get);
+ Py_XINCREF(set);
+ Py_XINCREF(del);
+ Py_XINCREF(doc);
+
+ prop->prop_get = get;
+ prop->prop_set = set;
+ prop->prop_del = del;
+ prop->prop_doc = doc;
+ prop->getter_doc = 0;
+
+ /* if no docstring given and the getter has one, use that one */
+ if ((doc == NULL || doc == Py_None) && get != NULL) {
+ PyObject *get_doc = PyObject_GetAttrString(get, "__doc__");
+ if (get_doc) {
+ if (Py_TYPE(self) == &PyProperty_Type) {
+ Py_XDECREF(prop->prop_doc);
+ prop->prop_doc = get_doc;
+ }
+ else {
+ /* If this is a property subclass, put __doc__
+ in dict of the subclass instance instead,
+ otherwise it gets shadowed by __doc__ in the
+ class's dict. */
+ int err = PyObject_SetAttrString(self, "__doc__", get_doc);
+ Py_DECREF(get_doc);
+ if (err < 0)
+ return -1;
+ }
+ prop->getter_doc = 1;
+ }
+ else if (PyErr_ExceptionMatches(PyExc_Exception)) {
+ PyErr_Clear();
+ }
+ else {
+ return -1;
+ }
+ }
+
+ return 0;
}
PyDoc_STRVAR(property_doc,
@@ -1333,54 +1333,54 @@ PyDoc_STRVAR(property_doc,
static int
property_traverse(PyObject *self, visitproc visit, void *arg)
{
- propertyobject *pp = (propertyobject *)self;
- Py_VISIT(pp->prop_get);
- Py_VISIT(pp->prop_set);
- Py_VISIT(pp->prop_del);
- Py_VISIT(pp->prop_doc);
- return 0;
+ propertyobject *pp = (propertyobject *)self;
+ Py_VISIT(pp->prop_get);
+ Py_VISIT(pp->prop_set);
+ Py_VISIT(pp->prop_del);
+ Py_VISIT(pp->prop_doc);
+ return 0;
}
PyTypeObject PyProperty_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "property", /* tp_name */
- sizeof(propertyobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- property_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- property_doc, /* tp_doc */
- property_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- property_methods, /* tp_methods */
- property_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- property_descr_get, /* tp_descr_get */
- property_descr_set, /* tp_descr_set */
- 0, /* tp_dictoffset */
- property_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "property", /* tp_name */
+ sizeof(propertyobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ property_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ property_doc, /* tp_doc */
+ property_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ property_methods, /* tp_methods */
+ property_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ property_descr_get, /* tp_descr_get */
+ property_descr_set, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ property_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index 2ab1520..def3da9 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -16,12 +16,12 @@
static void
set_key_error(PyObject *arg)
{
- PyObject *tup;
- tup = PyTuple_Pack(1, arg);
- if (!tup)
- return; /* caller will expect error to be set anyway */
- PyErr_SetObject(PyExc_KeyError, tup);
- Py_DECREF(tup);
+ PyObject *tup;
+ tup = PyTuple_Pack(1, arg);
+ if (!tup)
+ return; /* caller will expect error to be set anyway */
+ PyErr_SetObject(PyExc_KeyError, tup);
+ Py_DECREF(tup);
}
/* Define this out if you don't want conversion statistics on exit. */
@@ -141,7 +141,7 @@ static PyObject *dummy = NULL; /* Initialized by first call to newPyDictObject()
PyObject *
_PyDict_Dummy(void)
{
- return dummy;
+ return dummy;
}
#endif
@@ -156,9 +156,9 @@ static long converted = 0L;
static void
show_counts(void)
{
- fprintf(stderr, "created %ld string dicts\n", created);
- fprintf(stderr, "converted %ld to normal dicts\n", converted);
- fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
+ fprintf(stderr, "created %ld string dicts\n", created);
+ fprintf(stderr, "converted %ld to normal dicts\n", converted);
+ fprintf(stderr, "%.2f%% conversion rate\n", (100.0*converted)/created);
}
#endif
@@ -171,12 +171,12 @@ static size_t count_reuse = 0;
static void
show_alloc(void)
{
- fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n",
- count_alloc);
- fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T
- "d\n", count_reuse);
- fprintf(stderr, "%.2f%% reuse rate\n\n",
- (100.0*count_reuse/(count_alloc+count_reuse)));
+ fprintf(stderr, "Dict allocations: %" PY_FORMAT_SIZE_T "d\n",
+ count_alloc);
+ fprintf(stderr, "Dict reuse through freelist: %" PY_FORMAT_SIZE_T
+ "d\n", count_reuse);
+ fprintf(stderr, "%.2f%% reuse rate\n\n",
+ (100.0*count_reuse/(count_alloc+count_reuse)));
}
#endif
@@ -188,12 +188,12 @@ static Py_ssize_t count_tracked = 0;
static void
show_track(void)
{
- fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n",
- count_tracked + count_untracked);
- fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T
- "d\n", count_tracked);
- fprintf(stderr, "%.2f%% dict tracking rate\n\n",
- (100.0*count_tracked/(count_untracked+count_tracked)));
+ fprintf(stderr, "Dicts created: %" PY_FORMAT_SIZE_T "d\n",
+ count_tracked + count_untracked);
+ fprintf(stderr, "Dicts tracked by the GC: %" PY_FORMAT_SIZE_T
+ "d\n", count_tracked);
+ fprintf(stderr, "%.2f%% dict tracking rate\n\n",
+ (100.0*count_tracked/(count_untracked+count_tracked)));
}
#endif
@@ -207,15 +207,15 @@ show_track(void)
an excellent reason not to).
*/
-#define INIT_NONZERO_DICT_SLOTS(mp) do { \
- (mp)->ma_table = (mp)->ma_smalltable; \
- (mp)->ma_mask = PyDict_MINSIZE - 1; \
+#define INIT_NONZERO_DICT_SLOTS(mp) do { \
+ (mp)->ma_table = (mp)->ma_smalltable; \
+ (mp)->ma_mask = PyDict_MINSIZE - 1; \
} while(0)
-#define EMPTY_TO_MINSIZE(mp) do { \
- memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
- (mp)->ma_used = (mp)->ma_fill = 0; \
- INIT_NONZERO_DICT_SLOTS(mp); \
+#define EMPTY_TO_MINSIZE(mp) do { \
+ memset((mp)->ma_smalltable, 0, sizeof((mp)->ma_smalltable)); \
+ (mp)->ma_used = (mp)->ma_fill = 0; \
+ INIT_NONZERO_DICT_SLOTS(mp); \
} while(0)
/* Dictionary reuse scheme to save calls to malloc, free, and memset */
@@ -228,68 +228,68 @@ static int numfree = 0;
void
PyDict_Fini(void)
{
- PyDictObject *op;
+ PyDictObject *op;
- while (numfree) {
- op = free_list[--numfree];
- assert(PyDict_CheckExact(op));
- PyObject_GC_Del(op);
- }
+ while (numfree) {
+ op = free_list[--numfree];
+ assert(PyDict_CheckExact(op));
+ PyObject_GC_Del(op);
+ }
}
PyObject *
PyDict_New(void)
{
- register PyDictObject *mp;
- if (dummy == NULL) { /* Auto-initialize dummy */
- dummy = PyString_FromString("<dummy key>");
- if (dummy == NULL)
- return NULL;
+ register PyDictObject *mp;
+ if (dummy == NULL) { /* Auto-initialize dummy */
+ dummy = PyString_FromString("<dummy key>");
+ if (dummy == NULL)
+ return NULL;
#ifdef SHOW_CONVERSION_COUNTS
- Py_AtExit(show_counts);
+ Py_AtExit(show_counts);
#endif
#ifdef SHOW_ALLOC_COUNT
- Py_AtExit(show_alloc);
+ Py_AtExit(show_alloc);
#endif
#ifdef SHOW_TRACK_COUNT
- Py_AtExit(show_track);
+ Py_AtExit(show_track);
#endif
- }
- if (numfree) {
- mp = free_list[--numfree];
- assert (mp != NULL);
- assert (Py_TYPE(mp) == &PyDict_Type);
- _Py_NewReference((PyObject *)mp);
- if (mp->ma_fill) {
- EMPTY_TO_MINSIZE(mp);
- } else {
- /* At least set ma_table and ma_mask; these are wrong
- if an empty but presized dict is added to freelist */
- INIT_NONZERO_DICT_SLOTS(mp);
- }
- assert (mp->ma_used == 0);
- assert (mp->ma_table == mp->ma_smalltable);
- assert (mp->ma_mask == PyDict_MINSIZE - 1);
+ }
+ if (numfree) {
+ mp = free_list[--numfree];
+ assert (mp != NULL);
+ assert (Py_TYPE(mp) == &PyDict_Type);
+ _Py_NewReference((PyObject *)mp);
+ if (mp->ma_fill) {
+ EMPTY_TO_MINSIZE(mp);
+ } else {
+ /* At least set ma_table and ma_mask; these are wrong
+ if an empty but presized dict is added to freelist */
+ INIT_NONZERO_DICT_SLOTS(mp);
+ }
+ assert (mp->ma_used == 0);
+ assert (mp->ma_table == mp->ma_smalltable);
+ assert (mp->ma_mask == PyDict_MINSIZE - 1);
#ifdef SHOW_ALLOC_COUNT
- count_reuse++;
+ count_reuse++;
#endif
- } else {
- mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
- if (mp == NULL)
- return NULL;
- EMPTY_TO_MINSIZE(mp);
+ } else {
+ mp = PyObject_GC_New(PyDictObject, &PyDict_Type);
+ if (mp == NULL)
+ return NULL;
+ EMPTY_TO_MINSIZE(mp);
#ifdef SHOW_ALLOC_COUNT
- count_alloc++;
+ count_alloc++;
#endif
- }
- mp->ma_lookup = lookdict_string;
+ }
+ mp->ma_lookup = lookdict_string;
#ifdef SHOW_TRACK_COUNT
- count_untracked++;
+ count_untracked++;
#endif
#ifdef SHOW_CONVERSION_COUNTS
- ++created;
+ ++created;
#endif
- return (PyObject *)mp;
+ return (PyObject *)mp;
}
/*
@@ -319,80 +319,80 @@ PyDictEntry*.
static PyDictEntry *
lookdict(PyDictObject *mp, PyObject *key, register long hash)
{
- register size_t i;
- register size_t perturb;
- register PyDictEntry *freeslot;
- register size_t mask = (size_t)mp->ma_mask;
- PyDictEntry *ep0 = mp->ma_table;
- register PyDictEntry *ep;
- register int cmp;
- PyObject *startkey;
-
- i = (size_t)hash & mask;
- ep = &ep0[i];
- if (ep->me_key == NULL || ep->me_key == key)
- return ep;
-
- if (ep->me_key == dummy)
- freeslot = ep;
- else {
- if (ep->me_hash == hash) {
- startkey = ep->me_key;
- Py_INCREF(startkey);
- cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
- Py_DECREF(startkey);
- if (cmp < 0)
- return NULL;
- if (ep0 == mp->ma_table && ep->me_key == startkey) {
- if (cmp > 0)
- return ep;
- }
- else {
- /* The compare did major nasty stuff to the
- * dict: start over.
- * XXX A clever adversary could prevent this
- * XXX from terminating.
- */
- return lookdict(mp, key, hash);
- }
- }
- freeslot = NULL;
- }
-
- /* In the loop, me_key == dummy is by far (factor of 100s) the
- least likely outcome, so test for that last. */
- for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
- i = (i << 2) + i + perturb + 1;
- ep = &ep0[i & mask];
- if (ep->me_key == NULL)
- return freeslot == NULL ? ep : freeslot;
- if (ep->me_key == key)
- return ep;
- if (ep->me_hash == hash && ep->me_key != dummy) {
- startkey = ep->me_key;
- Py_INCREF(startkey);
- cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
- Py_DECREF(startkey);
- if (cmp < 0)
- return NULL;
- if (ep0 == mp->ma_table && ep->me_key == startkey) {
- if (cmp > 0)
- return ep;
- }
- else {
- /* The compare did major nasty stuff to the
- * dict: start over.
- * XXX A clever adversary could prevent this
- * XXX from terminating.
- */
- return lookdict(mp, key, hash);
- }
- }
- else if (ep->me_key == dummy && freeslot == NULL)
- freeslot = ep;
- }
- assert(0); /* NOT REACHED */
- return 0;
+ register size_t i;
+ register size_t perturb;
+ register PyDictEntry *freeslot;
+ register size_t mask = (size_t)mp->ma_mask;
+ PyDictEntry *ep0 = mp->ma_table;
+ register PyDictEntry *ep;
+ register int cmp;
+ PyObject *startkey;
+
+ i = (size_t)hash & mask;
+ ep = &ep0[i];
+ if (ep->me_key == NULL || ep->me_key == key)
+ return ep;
+
+ if (ep->me_key == dummy)
+ freeslot = ep;
+ else {
+ if (ep->me_hash == hash) {
+ startkey = ep->me_key;
+ Py_INCREF(startkey);
+ cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
+ Py_DECREF(startkey);
+ if (cmp < 0)
+ return NULL;
+ if (ep0 == mp->ma_table && ep->me_key == startkey) {
+ if (cmp > 0)
+ return ep;
+ }
+ else {
+ /* The compare did major nasty stuff to the
+ * dict: start over.
+ * XXX A clever adversary could prevent this
+ * XXX from terminating.
+ */
+ return lookdict(mp, key, hash);
+ }
+ }
+ freeslot = NULL;
+ }
+
+ /* In the loop, me_key == dummy is by far (factor of 100s) the
+ least likely outcome, so test for that last. */
+ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
+ i = (i << 2) + i + perturb + 1;
+ ep = &ep0[i & mask];
+ if (ep->me_key == NULL)
+ return freeslot == NULL ? ep : freeslot;
+ if (ep->me_key == key)
+ return ep;
+ if (ep->me_hash == hash && ep->me_key != dummy) {
+ startkey = ep->me_key;
+ Py_INCREF(startkey);
+ cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
+ Py_DECREF(startkey);
+ if (cmp < 0)
+ return NULL;
+ if (ep0 == mp->ma_table && ep->me_key == startkey) {
+ if (cmp > 0)
+ return ep;
+ }
+ else {
+ /* The compare did major nasty stuff to the
+ * dict: start over.
+ * XXX A clever adversary could prevent this
+ * XXX from terminating.
+ */
+ return lookdict(mp, key, hash);
+ }
+ }
+ else if (ep->me_key == dummy && freeslot == NULL)
+ freeslot = ep;
+ }
+ assert(0); /* NOT REACHED */
+ return 0;
}
/*
@@ -407,99 +407,99 @@ lookdict(PyDictObject *mp, PyObject *key, register long hash)
static PyDictEntry *
lookdict_string(PyDictObject *mp, PyObject *key, register long hash)
{
- register size_t i;
- register size_t perturb;
- register PyDictEntry *freeslot;
- register size_t mask = (size_t)mp->ma_mask;
- PyDictEntry *ep0 = mp->ma_table;
- register PyDictEntry *ep;
-
- /* Make sure this function doesn't have to handle non-string keys,
- including subclasses of str; e.g., one reason to subclass
- strings is to override __eq__, and for speed we don't cater to
- that here. */
- if (!PyString_CheckExact(key)) {
+ register size_t i;
+ register size_t perturb;
+ register PyDictEntry *freeslot;
+ register size_t mask = (size_t)mp->ma_mask;
+ PyDictEntry *ep0 = mp->ma_table;
+ register PyDictEntry *ep;
+
+ /* Make sure this function doesn't have to handle non-string keys,
+ including subclasses of str; e.g., one reason to subclass
+ strings is to override __eq__, and for speed we don't cater to
+ that here. */
+ if (!PyString_CheckExact(key)) {
#ifdef SHOW_CONVERSION_COUNTS
- ++converted;
+ ++converted;
#endif
- mp->ma_lookup = lookdict;
- return lookdict(mp, key, hash);
- }
- i = hash & mask;
- ep = &ep0[i];
- if (ep->me_key == NULL || ep->me_key == key)
- return ep;
- if (ep->me_key == dummy)
- freeslot = ep;
- else {
- if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key))
- return ep;
- freeslot = NULL;
- }
-
- /* In the loop, me_key == dummy is by far (factor of 100s) the
- least likely outcome, so test for that last. */
- for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
- i = (i << 2) + i + perturb + 1;
- ep = &ep0[i & mask];
- if (ep->me_key == NULL)
- return freeslot == NULL ? ep : freeslot;
- if (ep->me_key == key
- || (ep->me_hash == hash
- && ep->me_key != dummy
- && _PyString_Eq(ep->me_key, key)))
- return ep;
- if (ep->me_key == dummy && freeslot == NULL)
- freeslot = ep;
- }
- assert(0); /* NOT REACHED */
- return 0;
+ mp->ma_lookup = lookdict;
+ return lookdict(mp, key, hash);
+ }
+ i = hash & mask;
+ ep = &ep0[i];
+ if (ep->me_key == NULL || ep->me_key == key)
+ return ep;
+ if (ep->me_key == dummy)
+ freeslot = ep;
+ else {
+ if (ep->me_hash == hash && _PyString_Eq(ep->me_key, key))
+ return ep;
+ freeslot = NULL;
+ }
+
+ /* In the loop, me_key == dummy is by far (factor of 100s) the
+ least likely outcome, so test for that last. */
+ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
+ i = (i << 2) + i + perturb + 1;
+ ep = &ep0[i & mask];
+ if (ep->me_key == NULL)
+ return freeslot == NULL ? ep : freeslot;
+ if (ep->me_key == key
+ || (ep->me_hash == hash
+ && ep->me_key != dummy
+ && _PyString_Eq(ep->me_key, key)))
+ return ep;
+ if (ep->me_key == dummy && freeslot == NULL)
+ freeslot = ep;
+ }
+ assert(0); /* NOT REACHED */
+ return 0;
}
#ifdef SHOW_TRACK_COUNT
#define INCREASE_TRACK_COUNT \
- (count_tracked++, count_untracked--);
+ (count_tracked++, count_untracked--);
#define DECREASE_TRACK_COUNT \
- (count_tracked--, count_untracked++);
+ (count_tracked--, count_untracked++);
#else
#define INCREASE_TRACK_COUNT
#define DECREASE_TRACK_COUNT
#endif
#define MAINTAIN_TRACKING(mp, key, value) \
- do { \
- if (!_PyObject_GC_IS_TRACKED(mp)) { \
- if (_PyObject_GC_MAY_BE_TRACKED(key) || \
- _PyObject_GC_MAY_BE_TRACKED(value)) { \
- _PyObject_GC_TRACK(mp); \
- INCREASE_TRACK_COUNT \
- } \
- } \
- } while(0)
+ do { \
+ if (!_PyObject_GC_IS_TRACKED(mp)) { \
+ if (_PyObject_GC_MAY_BE_TRACKED(key) || \
+ _PyObject_GC_MAY_BE_TRACKED(value)) { \
+ _PyObject_GC_TRACK(mp); \
+ INCREASE_TRACK_COUNT \
+ } \
+ } \
+ } while(0)
void
_PyDict_MaybeUntrack(PyObject *op)
{
- PyDictObject *mp;
- PyObject *value;
- Py_ssize_t mask, i;
- PyDictEntry *ep;
-
- if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
- return;
-
- mp = (PyDictObject *) op;
- ep = mp->ma_table;
- mask = mp->ma_mask;
- for (i = 0; i <= mask; i++) {
- if ((value = ep[i].me_value) == NULL)
- continue;
- if (_PyObject_GC_MAY_BE_TRACKED(value) ||
- _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key))
- return;
- }
- DECREASE_TRACK_COUNT
- _PyObject_GC_UNTRACK(op);
+ PyDictObject *mp;
+ PyObject *value;
+ Py_ssize_t mask, i;
+ PyDictEntry *ep;
+
+ if (!PyDict_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
+ return;
+
+ mp = (PyDictObject *) op;
+ ep = mp->ma_table;
+ mask = mp->ma_mask;
+ for (i = 0; i <= mask; i++) {
+ if ((value = ep[i].me_value) == NULL)
+ continue;
+ if (_PyObject_GC_MAY_BE_TRACKED(value) ||
+ _PyObject_GC_MAY_BE_TRACKED(ep[i].me_key))
+ return;
+ }
+ DECREASE_TRACK_COUNT
+ _PyObject_GC_UNTRACK(op);
}
@@ -512,37 +512,37 @@ Returns -1 if an error occurred, or 0 on success.
static int
insertdict(register PyDictObject *mp, PyObject *key, long hash, PyObject *value)
{
- PyObject *old_value;
- register PyDictEntry *ep;
- typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);
-
- assert(mp->ma_lookup != NULL);
- ep = mp->ma_lookup(mp, key, hash);
- if (ep == NULL) {
- Py_DECREF(key);
- Py_DECREF(value);
- return -1;
- }
- MAINTAIN_TRACKING(mp, key, value);
- if (ep->me_value != NULL) {
- old_value = ep->me_value;
- ep->me_value = value;
- Py_DECREF(old_value); /* which **CAN** re-enter */
- Py_DECREF(key);
- }
- else {
- if (ep->me_key == NULL)
- mp->ma_fill++;
- else {
- assert(ep->me_key == dummy);
- Py_DECREF(dummy);
- }
- ep->me_key = key;
- ep->me_hash = (Py_ssize_t)hash;
- ep->me_value = value;
- mp->ma_used++;
- }
- return 0;
+ PyObject *old_value;
+ register PyDictEntry *ep;
+ typedef PyDictEntry *(*lookupfunc)(PyDictObject *, PyObject *, long);
+
+ assert(mp->ma_lookup != NULL);
+ ep = mp->ma_lookup(mp, key, hash);
+ if (ep == NULL) {
+ Py_DECREF(key);
+ Py_DECREF(value);
+ return -1;
+ }
+ MAINTAIN_TRACKING(mp, key, value);
+ if (ep->me_value != NULL) {
+ old_value = ep->me_value;
+ ep->me_value = value;
+ Py_DECREF(old_value); /* which **CAN** re-enter */
+ Py_DECREF(key);
+ }
+ else {
+ if (ep->me_key == NULL)
+ mp->ma_fill++;
+ else {
+ assert(ep->me_key == dummy);
+ Py_DECREF(dummy);
+ }
+ ep->me_key = key;
+ ep->me_hash = (Py_ssize_t)hash;
+ ep->me_value = value;
+ mp->ma_used++;
+ }
+ return 0;
}
/*
@@ -555,27 +555,27 @@ is responsible for incref'ing `key` and `value`.
*/
static void
insertdict_clean(register PyDictObject *mp, PyObject *key, long hash,
- PyObject *value)
-{
- register size_t i;
- register size_t perturb;
- register size_t mask = (size_t)mp->ma_mask;
- PyDictEntry *ep0 = mp->ma_table;
- register PyDictEntry *ep;
-
- MAINTAIN_TRACKING(mp, key, value);
- i = hash & mask;
- ep = &ep0[i];
- for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
- i = (i << 2) + i + perturb + 1;
- ep = &ep0[i & mask];
- }
- assert(ep->me_value == NULL);
- mp->ma_fill++;
- ep->me_key = key;
- ep->me_hash = (Py_ssize_t)hash;
- ep->me_value = value;
- mp->ma_used++;
+ PyObject *value)
+{
+ register size_t i;
+ register size_t perturb;
+ register size_t mask = (size_t)mp->ma_mask;
+ PyDictEntry *ep0 = mp->ma_table;
+ register PyDictEntry *ep;
+
+ MAINTAIN_TRACKING(mp, key, value);
+ i = hash & mask;
+ ep = &ep0[i];
+ for (perturb = hash; ep->me_key != NULL; perturb >>= PERTURB_SHIFT) {
+ i = (i << 2) + i + perturb + 1;
+ ep = &ep0[i & mask];
+ }
+ assert(ep->me_value == NULL);
+ mp->ma_fill++;
+ ep->me_key = key;
+ ep->me_hash = (Py_ssize_t)hash;
+ ep->me_value = value;
+ mp->ma_used++;
}
/*
@@ -586,84 +586,84 @@ actually be smaller than the old one.
static int
dictresize(PyDictObject *mp, Py_ssize_t minused)
{
- Py_ssize_t newsize;
- PyDictEntry *oldtable, *newtable, *ep;
- Py_ssize_t i;
- int is_oldtable_malloced;
- PyDictEntry small_copy[PyDict_MINSIZE];
-
- assert(minused >= 0);
-
- /* Find the smallest table size > minused. */
- for (newsize = PyDict_MINSIZE;
- newsize <= minused && newsize > 0;
- newsize <<= 1)
- ;
- if (newsize <= 0) {
- PyErr_NoMemory();
- return -1;
- }
-
- /* Get space for a new table. */
- oldtable = mp->ma_table;
- assert(oldtable != NULL);
- is_oldtable_malloced = oldtable != mp->ma_smalltable;
-
- if (newsize == PyDict_MINSIZE) {
- /* A large table is shrinking, or we can't get any smaller. */
- newtable = mp->ma_smalltable;
- if (newtable == oldtable) {
- if (mp->ma_fill == mp->ma_used) {
- /* No dummies, so no point doing anything. */
- return 0;
- }
- /* We're not going to resize it, but rebuild the
- table anyway to purge old dummy entries.
- Subtle: This is *necessary* if fill==size,
- as lookdict needs at least one virgin slot to
- terminate failing searches. If fill < size, it's
- merely desirable, as dummies slow searches. */
- assert(mp->ma_fill > mp->ma_used);
- memcpy(small_copy, oldtable, sizeof(small_copy));
- oldtable = small_copy;
- }
- }
- else {
- newtable = PyMem_NEW(PyDictEntry, newsize);
- if (newtable == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- }
-
- /* Make the dict empty, using the new table. */
- assert(newtable != oldtable);
- mp->ma_table = newtable;
- mp->ma_mask = newsize - 1;
- memset(newtable, 0, sizeof(PyDictEntry) * newsize);
- mp->ma_used = 0;
- i = mp->ma_fill;
- mp->ma_fill = 0;
-
- /* Copy the data over; this is refcount-neutral for active entries;
- dummy entries aren't copied over, of course */
- for (ep = oldtable; i > 0; ep++) {
- if (ep->me_value != NULL) { /* active entry */
- --i;
- insertdict_clean(mp, ep->me_key, (long)ep->me_hash,
- ep->me_value);
- }
- else if (ep->me_key != NULL) { /* dummy entry */
- --i;
- assert(ep->me_key == dummy);
- Py_DECREF(ep->me_key);
- }
- /* else key == value == NULL: nothing to do */
- }
-
- if (is_oldtable_malloced)
- PyMem_DEL(oldtable);
- return 0;
+ Py_ssize_t newsize;
+ PyDictEntry *oldtable, *newtable, *ep;
+ Py_ssize_t i;
+ int is_oldtable_malloced;
+ PyDictEntry small_copy[PyDict_MINSIZE];
+
+ assert(minused >= 0);
+
+ /* Find the smallest table size > minused. */
+ for (newsize = PyDict_MINSIZE;
+ newsize <= minused && newsize > 0;
+ newsize <<= 1)
+ ;
+ if (newsize <= 0) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ /* Get space for a new table. */
+ oldtable = mp->ma_table;
+ assert(oldtable != NULL);
+ is_oldtable_malloced = oldtable != mp->ma_smalltable;
+
+ if (newsize == PyDict_MINSIZE) {
+ /* A large table is shrinking, or we can't get any smaller. */
+ newtable = mp->ma_smalltable;
+ if (newtable == oldtable) {
+ if (mp->ma_fill == mp->ma_used) {
+ /* No dummies, so no point doing anything. */
+ return 0;
+ }
+ /* We're not going to resize it, but rebuild the
+ table anyway to purge old dummy entries.
+ Subtle: This is *necessary* if fill==size,
+ as lookdict needs at least one virgin slot to
+ terminate failing searches. If fill < size, it's
+ merely desirable, as dummies slow searches. */
+ assert(mp->ma_fill > mp->ma_used);
+ memcpy(small_copy, oldtable, sizeof(small_copy));
+ oldtable = small_copy;
+ }
+ }
+ else {
+ newtable = PyMem_NEW(PyDictEntry, newsize);
+ if (newtable == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ }
+
+ /* Make the dict empty, using the new table. */
+ assert(newtable != oldtable);
+ mp->ma_table = newtable;
+ mp->ma_mask = newsize - 1;
+ memset(newtable, 0, sizeof(PyDictEntry) * newsize);
+ mp->ma_used = 0;
+ i = mp->ma_fill;
+ mp->ma_fill = 0;
+
+ /* Copy the data over; this is refcount-neutral for active entries;
+ dummy entries aren't copied over, of course */
+ for (ep = oldtable; i > 0; ep++) {
+ if (ep->me_value != NULL) { /* active entry */
+ --i;
+ insertdict_clean(mp, ep->me_key, (long)ep->me_hash,
+ ep->me_value);
+ }
+ else if (ep->me_key != NULL) { /* dummy entry */
+ --i;
+ assert(ep->me_key == dummy);
+ Py_DECREF(ep->me_key);
+ }
+ /* else key == value == NULL: nothing to do */
+ }
+
+ if (is_oldtable_malloced)
+ PyMem_DEL(oldtable);
+ return 0;
}
/* Create a new dictionary pre-sized to hold an estimated number of elements.
@@ -674,13 +674,13 @@ dictresize(PyDictObject *mp, Py_ssize_t minused)
PyObject *
_PyDict_NewPresized(Py_ssize_t minused)
{
- PyObject *op = PyDict_New();
+ PyObject *op = PyDict_New();
- if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {
- Py_DECREF(op);
- return NULL;
- }
- return op;
+ if (minused>5 && op != NULL && dictresize((PyDictObject *)op, minused) == -1) {
+ Py_DECREF(op);
+ return NULL;
+ }
+ return op;
}
/* Note that, for historical reasons, PyDict_GetItem() suppresses all errors
@@ -696,46 +696,46 @@ _PyDict_NewPresized(Py_ssize_t minused)
PyObject *
PyDict_GetItem(PyObject *op, PyObject *key)
{
- long hash;
- PyDictObject *mp = (PyDictObject *)op;
- PyDictEntry *ep;
- PyThreadState *tstate;
- if (!PyDict_Check(op))
- return NULL;
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1)
- {
- hash = PyObject_Hash(key);
- if (hash == -1) {
- PyErr_Clear();
- return NULL;
- }
- }
-
- /* We can arrive here with a NULL tstate during initialization: try
- running "python -Wi" for an example related to string interning.
- Let's just hope that no exception occurs then... This must be
- _PyThreadState_Current and not PyThreadState_GET() because in debug
- mode, the latter complains if tstate is NULL. */
- tstate = _PyThreadState_Current;
- if (tstate != NULL && tstate->curexc_type != NULL) {
- /* preserve the existing exception */
- PyObject *err_type, *err_value, *err_tb;
- PyErr_Fetch(&err_type, &err_value, &err_tb);
- ep = (mp->ma_lookup)(mp, key, hash);
- /* ignore errors */
- PyErr_Restore(err_type, err_value, err_tb);
- if (ep == NULL)
- return NULL;
- }
- else {
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL) {
- PyErr_Clear();
- return NULL;
- }
- }
- return ep->me_value;
+ long hash;
+ PyDictObject *mp = (PyDictObject *)op;
+ PyDictEntry *ep;
+ PyThreadState *tstate;
+ if (!PyDict_Check(op))
+ return NULL;
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1)
+ {
+ hash = PyObject_Hash(key);
+ if (hash == -1) {
+ PyErr_Clear();
+ return NULL;
+ }
+ }
+
+ /* We can arrive here with a NULL tstate during initialization: try
+ running "python -Wi" for an example related to string interning.
+ Let's just hope that no exception occurs then... This must be
+ _PyThreadState_Current and not PyThreadState_GET() because in debug
+ mode, the latter complains if tstate is NULL. */
+ tstate = _PyThreadState_Current;
+ if (tstate != NULL && tstate->curexc_type != NULL) {
+ /* preserve the existing exception */
+ PyObject *err_type, *err_value, *err_tb;
+ PyErr_Fetch(&err_type, &err_value, &err_tb);
+ ep = (mp->ma_lookup)(mp, key, hash);
+ /* ignore errors */
+ PyErr_Restore(err_type, err_value, err_tb);
+ if (ep == NULL)
+ return NULL;
+ }
+ else {
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL) {
+ PyErr_Clear();
+ return NULL;
+ }
+ }
+ return ep->me_value;
}
/* CAUTION: PyDict_SetItem() must guarantee that it won't resize the
@@ -747,157 +747,157 @@ PyDict_GetItem(PyObject *op, PyObject *key)
int
PyDict_SetItem(register PyObject *op, PyObject *key, PyObject *value)
{
- register PyDictObject *mp;
- register long hash;
- register Py_ssize_t n_used;
-
- if (!PyDict_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- assert(key);
- assert(value);
- mp = (PyDictObject *)op;
- if (PyString_CheckExact(key)) {
- hash = ((PyStringObject *)key)->ob_shash;
- if (hash == -1)
- hash = PyObject_Hash(key);
- }
- else {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return -1;
- }
- assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
- n_used = mp->ma_used;
- Py_INCREF(value);
- Py_INCREF(key);
- if (insertdict(mp, key, hash, value) != 0)
- return -1;
- /* If we added a key, we can safely resize. Otherwise just return!
- * If fill >= 2/3 size, adjust size. Normally, this doubles or
- * quaduples the size, but it's also possible for the dict to shrink
- * (if ma_fill is much larger than ma_used, meaning a lot of dict
- * keys have been * deleted).
- *
- * Quadrupling the size improves average dictionary sparseness
- * (reducing collisions) at the cost of some memory and iteration
- * speed (which loops over every possible entry). It also halves
- * the number of expensive resize operations in a growing dictionary.
- *
- * Very large dictionaries (over 50K items) use doubling instead.
- * This may help applications with severe memory constraints.
- */
- if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
- return 0;
- return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);
+ register PyDictObject *mp;
+ register long hash;
+ register Py_ssize_t n_used;
+
+ if (!PyDict_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ assert(key);
+ assert(value);
+ mp = (PyDictObject *)op;
+ if (PyString_CheckExact(key)) {
+ hash = ((PyStringObject *)key)->ob_shash;
+ if (hash == -1)
+ hash = PyObject_Hash(key);
+ }
+ else {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ assert(mp->ma_fill <= mp->ma_mask); /* at least one empty slot */
+ n_used = mp->ma_used;
+ Py_INCREF(value);
+ Py_INCREF(key);
+ if (insertdict(mp, key, hash, value) != 0)
+ return -1;
+ /* If we added a key, we can safely resize. Otherwise just return!
+ * If fill >= 2/3 size, adjust size. Normally, this doubles or
+ * quaduples the size, but it's also possible for the dict to shrink
+ * (if ma_fill is much larger than ma_used, meaning a lot of dict
+ * keys have been * deleted).
+ *
+ * Quadrupling the size improves average dictionary sparseness
+ * (reducing collisions) at the cost of some memory and iteration
+ * speed (which loops over every possible entry). It also halves
+ * the number of expensive resize operations in a growing dictionary.
+ *
+ * Very large dictionaries (over 50K items) use doubling instead.
+ * This may help applications with severe memory constraints.
+ */
+ if (!(mp->ma_used > n_used && mp->ma_fill*3 >= (mp->ma_mask+1)*2))
+ return 0;
+ return dictresize(mp, (mp->ma_used > 50000 ? 2 : 4) * mp->ma_used);
}
int
PyDict_DelItem(PyObject *op, PyObject *key)
{
- register PyDictObject *mp;
- register long hash;
- register PyDictEntry *ep;
- PyObject *old_value, *old_key;
-
- if (!PyDict_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- assert(key);
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return -1;
- }
- mp = (PyDictObject *)op;
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL)
- return -1;
- if (ep->me_value == NULL) {
- set_key_error(key);
- return -1;
- }
- old_key = ep->me_key;
- Py_INCREF(dummy);
- ep->me_key = dummy;
- old_value = ep->me_value;
- ep->me_value = NULL;
- mp->ma_used--;
- Py_DECREF(old_value);
- Py_DECREF(old_key);
- return 0;
+ register PyDictObject *mp;
+ register long hash;
+ register PyDictEntry *ep;
+ PyObject *old_value, *old_key;
+
+ if (!PyDict_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ assert(key);
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ mp = (PyDictObject *)op;
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL)
+ return -1;
+ if (ep->me_value == NULL) {
+ set_key_error(key);
+ return -1;
+ }
+ old_key = ep->me_key;
+ Py_INCREF(dummy);
+ ep->me_key = dummy;
+ old_value = ep->me_value;
+ ep->me_value = NULL;
+ mp->ma_used--;
+ Py_DECREF(old_value);
+ Py_DECREF(old_key);
+ return 0;
}
void
PyDict_Clear(PyObject *op)
{
- PyDictObject *mp;
- PyDictEntry *ep, *table;
- int table_is_malloced;
- Py_ssize_t fill;
- PyDictEntry small_copy[PyDict_MINSIZE];
+ PyDictObject *mp;
+ PyDictEntry *ep, *table;
+ int table_is_malloced;
+ Py_ssize_t fill;
+ PyDictEntry small_copy[PyDict_MINSIZE];
#ifdef Py_DEBUG
- Py_ssize_t i, n;
+ Py_ssize_t i, n;
#endif
- if (!PyDict_Check(op))
- return;
- mp = (PyDictObject *)op;
+ if (!PyDict_Check(op))
+ return;
+ mp = (PyDictObject *)op;
#ifdef Py_DEBUG
- n = mp->ma_mask + 1;
- i = 0;
+ n = mp->ma_mask + 1;
+ i = 0;
#endif
- table = mp->ma_table;
- assert(table != NULL);
- table_is_malloced = table != mp->ma_smalltable;
-
- /* This is delicate. During the process of clearing the dict,
- * decrefs can cause the dict to mutate. To avoid fatal confusion
- * (voice of experience), we have to make the dict empty before
- * clearing the slots, and never refer to anything via mp->xxx while
- * clearing.
- */
- fill = mp->ma_fill;
- if (table_is_malloced)
- EMPTY_TO_MINSIZE(mp);
-
- else if (fill > 0) {
- /* It's a small table with something that needs to be cleared.
- * Afraid the only safe way is to copy the dict entries into
- * another small table first.
- */
- memcpy(small_copy, table, sizeof(small_copy));
- table = small_copy;
- EMPTY_TO_MINSIZE(mp);
- }
- /* else it's a small table that's already empty */
-
- /* Now we can finally clear things. If C had refcounts, we could
- * assert that the refcount on table is 1 now, i.e. that this function
- * has unique access to it, so decref side-effects can't alter it.
- */
- for (ep = table; fill > 0; ++ep) {
+ table = mp->ma_table;
+ assert(table != NULL);
+ table_is_malloced = table != mp->ma_smalltable;
+
+ /* This is delicate. During the process of clearing the dict,
+ * decrefs can cause the dict to mutate. To avoid fatal confusion
+ * (voice of experience), we have to make the dict empty before
+ * clearing the slots, and never refer to anything via mp->xxx while
+ * clearing.
+ */
+ fill = mp->ma_fill;
+ if (table_is_malloced)
+ EMPTY_TO_MINSIZE(mp);
+
+ else if (fill > 0) {
+ /* It's a small table with something that needs to be cleared.
+ * Afraid the only safe way is to copy the dict entries into
+ * another small table first.
+ */
+ memcpy(small_copy, table, sizeof(small_copy));
+ table = small_copy;
+ EMPTY_TO_MINSIZE(mp);
+ }
+ /* else it's a small table that's already empty */
+
+ /* Now we can finally clear things. If C had refcounts, we could
+ * assert that the refcount on table is 1 now, i.e. that this function
+ * has unique access to it, so decref side-effects can't alter it.
+ */
+ for (ep = table; fill > 0; ++ep) {
#ifdef Py_DEBUG
- assert(i < n);
- ++i;
+ assert(i < n);
+ ++i;
#endif
- if (ep->me_key) {
- --fill;
- Py_DECREF(ep->me_key);
- Py_XDECREF(ep->me_value);
- }
+ if (ep->me_key) {
+ --fill;
+ Py_DECREF(ep->me_key);
+ Py_XDECREF(ep->me_value);
+ }
#ifdef Py_DEBUG
- else
- assert(ep->me_value == NULL);
+ else
+ assert(ep->me_value == NULL);
#endif
- }
+ }
- if (table_is_malloced)
- PyMem_DEL(table);
+ if (table_is_malloced)
+ PyMem_DEL(table);
}
/*
@@ -918,55 +918,55 @@ PyDict_Clear(PyObject *op)
int
PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue)
{
- register Py_ssize_t i;
- register Py_ssize_t mask;
- register PyDictEntry *ep;
-
- if (!PyDict_Check(op))
- return 0;
- i = *ppos;
- if (i < 0)
- return 0;
- ep = ((PyDictObject *)op)->ma_table;
- mask = ((PyDictObject *)op)->ma_mask;
- while (i <= mask && ep[i].me_value == NULL)
- i++;
- *ppos = i+1;
- if (i > mask)
- return 0;
- if (pkey)
- *pkey = ep[i].me_key;
- if (pvalue)
- *pvalue = ep[i].me_value;
- return 1;
+ register Py_ssize_t i;
+ register Py_ssize_t mask;
+ register PyDictEntry *ep;
+
+ if (!PyDict_Check(op))
+ return 0;
+ i = *ppos;
+ if (i < 0)
+ return 0;
+ ep = ((PyDictObject *)op)->ma_table;
+ mask = ((PyDictObject *)op)->ma_mask;
+ while (i <= mask && ep[i].me_value == NULL)
+ i++;
+ *ppos = i+1;
+ if (i > mask)
+ return 0;
+ if (pkey)
+ *pkey = ep[i].me_key;
+ if (pvalue)
+ *pvalue = ep[i].me_value;
+ return 1;
}
/* Internal version of PyDict_Next that returns a hash value in addition to the key and value.*/
int
_PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue, long *phash)
{
- register Py_ssize_t i;
- register Py_ssize_t mask;
- register PyDictEntry *ep;
-
- if (!PyDict_Check(op))
- return 0;
- i = *ppos;
- if (i < 0)
- return 0;
- ep = ((PyDictObject *)op)->ma_table;
- mask = ((PyDictObject *)op)->ma_mask;
- while (i <= mask && ep[i].me_value == NULL)
- i++;
- *ppos = i+1;
- if (i > mask)
- return 0;
- *phash = (long)(ep[i].me_hash);
- if (pkey)
- *pkey = ep[i].me_key;
- if (pvalue)
- *pvalue = ep[i].me_value;
- return 1;
+ register Py_ssize_t i;
+ register Py_ssize_t mask;
+ register PyDictEntry *ep;
+
+ if (!PyDict_Check(op))
+ return 0;
+ i = *ppos;
+ if (i < 0)
+ return 0;
+ ep = ((PyDictObject *)op)->ma_table;
+ mask = ((PyDictObject *)op)->ma_mask;
+ while (i <= mask && ep[i].me_value == NULL)
+ i++;
+ *ppos = i+1;
+ if (i > mask)
+ return 0;
+ *phash = (long)(ep[i].me_hash);
+ if (pkey)
+ *pkey = ep[i].me_key;
+ if (pvalue)
+ *pvalue = ep[i].me_value;
+ return 1;
}
/* Methods */
@@ -974,456 +974,456 @@ _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue,
static void
dict_dealloc(register PyDictObject *mp)
{
- register PyDictEntry *ep;
- Py_ssize_t fill = mp->ma_fill;
- PyObject_GC_UnTrack(mp);
- Py_TRASHCAN_SAFE_BEGIN(mp)
- for (ep = mp->ma_table; fill > 0; ep++) {
- if (ep->me_key) {
- --fill;
- Py_DECREF(ep->me_key);
- Py_XDECREF(ep->me_value);
- }
- }
- if (mp->ma_table != mp->ma_smalltable)
- PyMem_DEL(mp->ma_table);
- if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
- free_list[numfree++] = mp;
- else
- Py_TYPE(mp)->tp_free((PyObject *)mp);
- Py_TRASHCAN_SAFE_END(mp)
+ register PyDictEntry *ep;
+ Py_ssize_t fill = mp->ma_fill;
+ PyObject_GC_UnTrack(mp);
+ Py_TRASHCAN_SAFE_BEGIN(mp)
+ for (ep = mp->ma_table; fill > 0; ep++) {
+ if (ep->me_key) {
+ --fill;
+ Py_DECREF(ep->me_key);
+ Py_XDECREF(ep->me_value);
+ }
+ }
+ if (mp->ma_table != mp->ma_smalltable)
+ PyMem_DEL(mp->ma_table);
+ if (numfree < PyDict_MAXFREELIST && Py_TYPE(mp) == &PyDict_Type)
+ free_list[numfree++] = mp;
+ else
+ Py_TYPE(mp)->tp_free((PyObject *)mp);
+ Py_TRASHCAN_SAFE_END(mp)
}
static int
dict_print(register PyDictObject *mp, register FILE *fp, register int flags)
{
- register Py_ssize_t i;
- register Py_ssize_t any;
- int status;
-
- status = Py_ReprEnter((PyObject*)mp);
- if (status != 0) {
- if (status < 0)
- return status;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "{...}");
- Py_END_ALLOW_THREADS
- return 0;
- }
-
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "{");
- Py_END_ALLOW_THREADS
- any = 0;
- for (i = 0; i <= mp->ma_mask; i++) {
- PyDictEntry *ep = mp->ma_table + i;
- PyObject *pvalue = ep->me_value;
- if (pvalue != NULL) {
- /* Prevent PyObject_Repr from deleting value during
- key format */
- Py_INCREF(pvalue);
- if (any++ > 0) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ", ");
- Py_END_ALLOW_THREADS
- }
- if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
- Py_DECREF(pvalue);
- Py_ReprLeave((PyObject*)mp);
- return -1;
- }
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ": ");
- Py_END_ALLOW_THREADS
- if (PyObject_Print(pvalue, fp, 0) != 0) {
- Py_DECREF(pvalue);
- Py_ReprLeave((PyObject*)mp);
- return -1;
- }
- Py_DECREF(pvalue);
- }
- }
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "}");
- Py_END_ALLOW_THREADS
- Py_ReprLeave((PyObject*)mp);
- return 0;
+ register Py_ssize_t i;
+ register Py_ssize_t any;
+ int status;
+
+ status = Py_ReprEnter((PyObject*)mp);
+ if (status != 0) {
+ if (status < 0)
+ return status;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "{...}");
+ Py_END_ALLOW_THREADS
+ return 0;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "{");
+ Py_END_ALLOW_THREADS
+ any = 0;
+ for (i = 0; i <= mp->ma_mask; i++) {
+ PyDictEntry *ep = mp->ma_table + i;
+ PyObject *pvalue = ep->me_value;
+ if (pvalue != NULL) {
+ /* Prevent PyObject_Repr from deleting value during
+ key format */
+ Py_INCREF(pvalue);
+ if (any++ > 0) {
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ", ");
+ Py_END_ALLOW_THREADS
+ }
+ if (PyObject_Print((PyObject *)ep->me_key, fp, 0)!=0) {
+ Py_DECREF(pvalue);
+ Py_ReprLeave((PyObject*)mp);
+ return -1;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ": ");
+ Py_END_ALLOW_THREADS
+ if (PyObject_Print(pvalue, fp, 0) != 0) {
+ Py_DECREF(pvalue);
+ Py_ReprLeave((PyObject*)mp);
+ return -1;
+ }
+ Py_DECREF(pvalue);
+ }
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "}");
+ Py_END_ALLOW_THREADS
+ Py_ReprLeave((PyObject*)mp);
+ return 0;
}
static PyObject *
dict_repr(PyDictObject *mp)
{
- Py_ssize_t i;
- PyObject *s, *temp, *colon = NULL;
- PyObject *pieces = NULL, *result = NULL;
- PyObject *key, *value;
-
- i = Py_ReprEnter((PyObject *)mp);
- if (i != 0) {
- return i > 0 ? PyString_FromString("{...}") : NULL;
- }
-
- if (mp->ma_used == 0) {
- result = PyString_FromString("{}");
- goto Done;
- }
-
- pieces = PyList_New(0);
- if (pieces == NULL)
- goto Done;
-
- colon = PyString_FromString(": ");
- if (colon == NULL)
- goto Done;
-
- /* Do repr() on each key+value pair, and insert ": " between them.
- Note that repr may mutate the dict. */
- i = 0;
- while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
- int status;
- /* Prevent repr from deleting value during key format. */
- Py_INCREF(value);
- s = PyObject_Repr(key);
- PyString_Concat(&s, colon);
- PyString_ConcatAndDel(&s, PyObject_Repr(value));
- Py_DECREF(value);
- if (s == NULL)
- goto Done;
- status = PyList_Append(pieces, s);
- Py_DECREF(s); /* append created a new ref */
- if (status < 0)
- goto Done;
- }
-
- /* Add "{}" decorations to the first and last items. */
- assert(PyList_GET_SIZE(pieces) > 0);
- s = PyString_FromString("{");
- if (s == NULL)
- goto Done;
- temp = PyList_GET_ITEM(pieces, 0);
- PyString_ConcatAndDel(&s, temp);
- PyList_SET_ITEM(pieces, 0, s);
- if (s == NULL)
- goto Done;
-
- s = PyString_FromString("}");
- if (s == NULL)
- goto Done;
- temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
- PyString_ConcatAndDel(&temp, s);
- PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
- if (temp == NULL)
- goto Done;
-
- /* Paste them all together with ", " between. */
- s = PyString_FromString(", ");
- if (s == NULL)
- goto Done;
- result = _PyString_Join(s, pieces);
- Py_DECREF(s);
+ Py_ssize_t i;
+ PyObject *s, *temp, *colon = NULL;
+ PyObject *pieces = NULL, *result = NULL;
+ PyObject *key, *value;
+
+ i = Py_ReprEnter((PyObject *)mp);
+ if (i != 0) {
+ return i > 0 ? PyString_FromString("{...}") : NULL;
+ }
+
+ if (mp->ma_used == 0) {
+ result = PyString_FromString("{}");
+ goto Done;
+ }
+
+ pieces = PyList_New(0);
+ if (pieces == NULL)
+ goto Done;
+
+ colon = PyString_FromString(": ");
+ if (colon == NULL)
+ goto Done;
+
+ /* Do repr() on each key+value pair, and insert ": " between them.
+ Note that repr may mutate the dict. */
+ i = 0;
+ while (PyDict_Next((PyObject *)mp, &i, &key, &value)) {
+ int status;
+ /* Prevent repr from deleting value during key format. */
+ Py_INCREF(value);
+ s = PyObject_Repr(key);
+ PyString_Concat(&s, colon);
+ PyString_ConcatAndDel(&s, PyObject_Repr(value));
+ Py_DECREF(value);
+ if (s == NULL)
+ goto Done;
+ status = PyList_Append(pieces, s);
+ Py_DECREF(s); /* append created a new ref */
+ if (status < 0)
+ goto Done;
+ }
+
+ /* Add "{}" decorations to the first and last items. */
+ assert(PyList_GET_SIZE(pieces) > 0);
+ s = PyString_FromString("{");
+ if (s == NULL)
+ goto Done;
+ temp = PyList_GET_ITEM(pieces, 0);
+ PyString_ConcatAndDel(&s, temp);
+ PyList_SET_ITEM(pieces, 0, s);
+ if (s == NULL)
+ goto Done;
+
+ s = PyString_FromString("}");
+ if (s == NULL)
+ goto Done;
+ temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
+ PyString_ConcatAndDel(&temp, s);
+ PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
+ if (temp == NULL)
+ goto Done;
+
+ /* Paste them all together with ", " between. */
+ s = PyString_FromString(", ");
+ if (s == NULL)
+ goto Done;
+ result = _PyString_Join(s, pieces);
+ Py_DECREF(s);
Done:
- Py_XDECREF(pieces);
- Py_XDECREF(colon);
- Py_ReprLeave((PyObject *)mp);
- return result;
+ Py_XDECREF(pieces);
+ Py_XDECREF(colon);
+ Py_ReprLeave((PyObject *)mp);
+ return result;
}
static Py_ssize_t
dict_length(PyDictObject *mp)
{
- return mp->ma_used;
+ return mp->ma_used;
}
static PyObject *
dict_subscript(PyDictObject *mp, register PyObject *key)
{
- PyObject *v;
- long hash;
- PyDictEntry *ep;
- assert(mp->ma_table != NULL);
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return NULL;
- }
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL)
- return NULL;
- v = ep->me_value;
- if (v == NULL) {
- if (!PyDict_CheckExact(mp)) {
- /* Look up __missing__ method if we're a subclass. */
- PyObject *missing, *res;
- static PyObject *missing_str = NULL;
- missing = _PyObject_LookupSpecial((PyObject *)mp,
- "__missing__",
- &missing_str);
- if (missing != NULL) {
- res = PyObject_CallFunctionObjArgs(missing,
- key, NULL);
- Py_DECREF(missing);
- return res;
- }
- else if (PyErr_Occurred())
- return NULL;
- }
- set_key_error(key);
- return NULL;
- }
- else
- Py_INCREF(v);
- return v;
+ PyObject *v;
+ long hash;
+ PyDictEntry *ep;
+ assert(mp->ma_table != NULL);
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return NULL;
+ }
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL)
+ return NULL;
+ v = ep->me_value;
+ if (v == NULL) {
+ if (!PyDict_CheckExact(mp)) {
+ /* Look up __missing__ method if we're a subclass. */
+ PyObject *missing, *res;
+ static PyObject *missing_str = NULL;
+ missing = _PyObject_LookupSpecial((PyObject *)mp,
+ "__missing__",
+ &missing_str);
+ if (missing != NULL) {
+ res = PyObject_CallFunctionObjArgs(missing,
+ key, NULL);
+ Py_DECREF(missing);
+ return res;
+ }
+ else if (PyErr_Occurred())
+ return NULL;
+ }
+ set_key_error(key);
+ return NULL;
+ }
+ else
+ Py_INCREF(v);
+ return v;
}
static int
dict_ass_sub(PyDictObject *mp, PyObject *v, PyObject *w)
{
- if (w == NULL)
- return PyDict_DelItem((PyObject *)mp, v);
- else
- return PyDict_SetItem((PyObject *)mp, v, w);
+ if (w == NULL)
+ return PyDict_DelItem((PyObject *)mp, v);
+ else
+ return PyDict_SetItem((PyObject *)mp, v, w);
}
static PyMappingMethods dict_as_mapping = {
- (lenfunc)dict_length, /*mp_length*/
- (binaryfunc)dict_subscript, /*mp_subscript*/
- (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
+ (lenfunc)dict_length, /*mp_length*/
+ (binaryfunc)dict_subscript, /*mp_subscript*/
+ (objobjargproc)dict_ass_sub, /*mp_ass_subscript*/
};
static PyObject *
dict_keys(register PyDictObject *mp)
{
- register PyObject *v;
- register Py_ssize_t i, j;
- PyDictEntry *ep;
- Py_ssize_t mask, n;
+ register PyObject *v;
+ register Py_ssize_t i, j;
+ PyDictEntry *ep;
+ Py_ssize_t mask, n;
again:
- n = mp->ma_used;
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- if (n != mp->ma_used) {
- /* Durnit. The allocations caused the dict to resize.
- * Just start over, this shouldn't normally happen.
- */
- Py_DECREF(v);
- goto again;
- }
- ep = mp->ma_table;
- mask = mp->ma_mask;
- for (i = 0, j = 0; i <= mask; i++) {
- if (ep[i].me_value != NULL) {
- PyObject *key = ep[i].me_key;
- Py_INCREF(key);
- PyList_SET_ITEM(v, j, key);
- j++;
- }
- }
- assert(j == n);
- return v;
+ n = mp->ma_used;
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ if (n != mp->ma_used) {
+ /* Durnit. The allocations caused the dict to resize.
+ * Just start over, this shouldn't normally happen.
+ */
+ Py_DECREF(v);
+ goto again;
+ }
+ ep = mp->ma_table;
+ mask = mp->ma_mask;
+ for (i = 0, j = 0; i <= mask; i++) {
+ if (ep[i].me_value != NULL) {
+ PyObject *key = ep[i].me_key;
+ Py_INCREF(key);
+ PyList_SET_ITEM(v, j, key);
+ j++;
+ }
+ }
+ assert(j == n);
+ return v;
}
static PyObject *
dict_values(register PyDictObject *mp)
{
- register PyObject *v;
- register Py_ssize_t i, j;
- PyDictEntry *ep;
- Py_ssize_t mask, n;
+ register PyObject *v;
+ register Py_ssize_t i, j;
+ PyDictEntry *ep;
+ Py_ssize_t mask, n;
again:
- n = mp->ma_used;
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- if (n != mp->ma_used) {
- /* Durnit. The allocations caused the dict to resize.
- * Just start over, this shouldn't normally happen.
- */
- Py_DECREF(v);
- goto again;
- }
- ep = mp->ma_table;
- mask = mp->ma_mask;
- for (i = 0, j = 0; i <= mask; i++) {
- if (ep[i].me_value != NULL) {
- PyObject *value = ep[i].me_value;
- Py_INCREF(value);
- PyList_SET_ITEM(v, j, value);
- j++;
- }
- }
- assert(j == n);
- return v;
+ n = mp->ma_used;
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ if (n != mp->ma_used) {
+ /* Durnit. The allocations caused the dict to resize.
+ * Just start over, this shouldn't normally happen.
+ */
+ Py_DECREF(v);
+ goto again;
+ }
+ ep = mp->ma_table;
+ mask = mp->ma_mask;
+ for (i = 0, j = 0; i <= mask; i++) {
+ if (ep[i].me_value != NULL) {
+ PyObject *value = ep[i].me_value;
+ Py_INCREF(value);
+ PyList_SET_ITEM(v, j, value);
+ j++;
+ }
+ }
+ assert(j == n);
+ return v;
}
static PyObject *
dict_items(register PyDictObject *mp)
{
- register PyObject *v;
- register Py_ssize_t i, j, n;
- Py_ssize_t mask;
- PyObject *item, *key, *value;
- PyDictEntry *ep;
+ register PyObject *v;
+ register Py_ssize_t i, j, n;
+ Py_ssize_t mask;
+ PyObject *item, *key, *value;
+ PyDictEntry *ep;
- /* Preallocate the list of tuples, to avoid allocations during
- * the loop over the items, which could trigger GC, which
- * could resize the dict. :-(
- */
+ /* Preallocate the list of tuples, to avoid allocations during
+ * the loop over the items, which could trigger GC, which
+ * could resize the dict. :-(
+ */
again:
- n = mp->ma_used;
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- for (i = 0; i < n; i++) {
- item = PyTuple_New(2);
- if (item == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SET_ITEM(v, i, item);
- }
- if (n != mp->ma_used) {
- /* Durnit. The allocations caused the dict to resize.
- * Just start over, this shouldn't normally happen.
- */
- Py_DECREF(v);
- goto again;
- }
- /* Nothing we do below makes any function calls. */
- ep = mp->ma_table;
- mask = mp->ma_mask;
- for (i = 0, j = 0; i <= mask; i++) {
- if ((value=ep[i].me_value) != NULL) {
- key = ep[i].me_key;
- item = PyList_GET_ITEM(v, j);
- Py_INCREF(key);
- PyTuple_SET_ITEM(item, 0, key);
- Py_INCREF(value);
- PyTuple_SET_ITEM(item, 1, value);
- j++;
- }
- }
- assert(j == n);
- return v;
+ n = mp->ma_used;
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ for (i = 0; i < n; i++) {
+ item = PyTuple_New(2);
+ if (item == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SET_ITEM(v, i, item);
+ }
+ if (n != mp->ma_used) {
+ /* Durnit. The allocations caused the dict to resize.
+ * Just start over, this shouldn't normally happen.
+ */
+ Py_DECREF(v);
+ goto again;
+ }
+ /* Nothing we do below makes any function calls. */
+ ep = mp->ma_table;
+ mask = mp->ma_mask;
+ for (i = 0, j = 0; i <= mask; i++) {
+ if ((value=ep[i].me_value) != NULL) {
+ key = ep[i].me_key;
+ item = PyList_GET_ITEM(v, j);
+ Py_INCREF(key);
+ PyTuple_SET_ITEM(item, 0, key);
+ Py_INCREF(value);
+ PyTuple_SET_ITEM(item, 1, value);
+ j++;
+ }
+ }
+ assert(j == n);
+ return v;
}
static PyObject *
dict_fromkeys(PyObject *cls, PyObject *args)
{
- PyObject *seq;
- PyObject *value = Py_None;
- PyObject *it; /* iter(seq) */
- PyObject *key;
- PyObject *d;
- int status;
-
- if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
- return NULL;
-
- d = PyObject_CallObject(cls, NULL);
- if (d == NULL)
- return NULL;
-
- if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) {
- PyDictObject *mp = (PyDictObject *)d;
- PyObject *oldvalue;
- Py_ssize_t pos = 0;
- PyObject *key;
- long hash;
-
- if (dictresize(mp, Py_SIZE(seq)))
- return NULL;
-
- while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
- Py_INCREF(key);
- Py_INCREF(value);
- if (insertdict(mp, key, hash, value))
- return NULL;
- }
- return d;
- }
-
- if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {
- PyDictObject *mp = (PyDictObject *)d;
- Py_ssize_t pos = 0;
- PyObject *key;
- long hash;
-
- if (dictresize(mp, PySet_GET_SIZE(seq)))
- return NULL;
-
- while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
- Py_INCREF(key);
- Py_INCREF(value);
- if (insertdict(mp, key, hash, value))
- return NULL;
- }
- return d;
- }
-
- it = PyObject_GetIter(seq);
- if (it == NULL){
- Py_DECREF(d);
- return NULL;
- }
-
- if (PyDict_CheckExact(d)) {
- while ((key = PyIter_Next(it)) != NULL) {
- status = PyDict_SetItem(d, key, value);
- Py_DECREF(key);
- if (status < 0)
- goto Fail;
- }
- } else {
- while ((key = PyIter_Next(it)) != NULL) {
- status = PyObject_SetItem(d, key, value);
- Py_DECREF(key);
- if (status < 0)
- goto Fail;
- }
- }
-
- if (PyErr_Occurred())
- goto Fail;
- Py_DECREF(it);
- return d;
+ PyObject *seq;
+ PyObject *value = Py_None;
+ PyObject *it; /* iter(seq) */
+ PyObject *key;
+ PyObject *d;
+ int status;
+
+ if (!PyArg_UnpackTuple(args, "fromkeys", 1, 2, &seq, &value))
+ return NULL;
+
+ d = PyObject_CallObject(cls, NULL);
+ if (d == NULL)
+ return NULL;
+
+ if (PyDict_CheckExact(d) && PyDict_CheckExact(seq)) {
+ PyDictObject *mp = (PyDictObject *)d;
+ PyObject *oldvalue;
+ Py_ssize_t pos = 0;
+ PyObject *key;
+ long hash;
+
+ if (dictresize(mp, Py_SIZE(seq)))
+ return NULL;
+
+ while (_PyDict_Next(seq, &pos, &key, &oldvalue, &hash)) {
+ Py_INCREF(key);
+ Py_INCREF(value);
+ if (insertdict(mp, key, hash, value))
+ return NULL;
+ }
+ return d;
+ }
+
+ if (PyDict_CheckExact(d) && PyAnySet_CheckExact(seq)) {
+ PyDictObject *mp = (PyDictObject *)d;
+ Py_ssize_t pos = 0;
+ PyObject *key;
+ long hash;
+
+ if (dictresize(mp, PySet_GET_SIZE(seq)))
+ return NULL;
+
+ while (_PySet_NextEntry(seq, &pos, &key, &hash)) {
+ Py_INCREF(key);
+ Py_INCREF(value);
+ if (insertdict(mp, key, hash, value))
+ return NULL;
+ }
+ return d;
+ }
+
+ it = PyObject_GetIter(seq);
+ if (it == NULL){
+ Py_DECREF(d);
+ return NULL;
+ }
+
+ if (PyDict_CheckExact(d)) {
+ while ((key = PyIter_Next(it)) != NULL) {
+ status = PyDict_SetItem(d, key, value);
+ Py_DECREF(key);
+ if (status < 0)
+ goto Fail;
+ }
+ } else {
+ while ((key = PyIter_Next(it)) != NULL) {
+ status = PyObject_SetItem(d, key, value);
+ Py_DECREF(key);
+ if (status < 0)
+ goto Fail;
+ }
+ }
+
+ if (PyErr_Occurred())
+ goto Fail;
+ Py_DECREF(it);
+ return d;
Fail:
- Py_DECREF(it);
- Py_DECREF(d);
- return NULL;
+ Py_DECREF(it);
+ Py_DECREF(d);
+ return NULL;
}
static int
dict_update_common(PyObject *self, PyObject *args, PyObject *kwds, char *methname)
{
- PyObject *arg = NULL;
- int result = 0;
+ PyObject *arg = NULL;
+ int result = 0;
- if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
- result = -1;
+ if (!PyArg_UnpackTuple(args, methname, 0, 1, &arg))
+ result = -1;
- else if (arg != NULL) {
- if (PyObject_HasAttrString(arg, "keys"))
- result = PyDict_Merge(self, arg, 1);
- else
- result = PyDict_MergeFromSeq2(self, arg, 1);
- }
- if (result == 0 && kwds != NULL)
- result = PyDict_Merge(self, kwds, 1);
- return result;
+ else if (arg != NULL) {
+ if (PyObject_HasAttrString(arg, "keys"))
+ result = PyDict_Merge(self, arg, 1);
+ else
+ result = PyDict_MergeFromSeq2(self, arg, 1);
+ }
+ if (result == 0 && kwds != NULL)
+ result = PyDict_Merge(self, kwds, 1);
+ return result;
}
static PyObject *
dict_update(PyObject *self, PyObject *args, PyObject *kwds)
{
- if (dict_update_common(self, args, kwds, "update") != -1)
- Py_RETURN_NONE;
- return NULL;
+ if (dict_update_common(self, args, kwds, "update") != -1)
+ Py_RETURN_NONE;
+ return NULL;
}
/* Update unconditionally replaces existing items.
@@ -1439,238 +1439,238 @@ dict_update(PyObject *self, PyObject *args, PyObject *kwds)
int
PyDict_MergeFromSeq2(PyObject *d, PyObject *seq2, int override)
{
- PyObject *it; /* iter(seq2) */
- Py_ssize_t i; /* index into seq2 of current element */
- PyObject *item; /* seq2[i] */
- PyObject *fast; /* item as a 2-tuple or 2-list */
-
- assert(d != NULL);
- assert(PyDict_Check(d));
- assert(seq2 != NULL);
-
- it = PyObject_GetIter(seq2);
- if (it == NULL)
- return -1;
-
- for (i = 0; ; ++i) {
- PyObject *key, *value;
- Py_ssize_t n;
-
- fast = NULL;
- item = PyIter_Next(it);
- if (item == NULL) {
- if (PyErr_Occurred())
- goto Fail;
- break;
- }
-
- /* Convert item to sequence, and verify length 2. */
- fast = PySequence_Fast(item, "");
- if (fast == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_Format(PyExc_TypeError,
- "cannot convert dictionary update "
- "sequence element #%zd to a sequence",
- i);
- goto Fail;
- }
- n = PySequence_Fast_GET_SIZE(fast);
- if (n != 2) {
- PyErr_Format(PyExc_ValueError,
- "dictionary update sequence element #%zd "
- "has length %zd; 2 is required",
- i, n);
- goto Fail;
- }
-
- /* Update/merge with this (key, value) pair. */
- key = PySequence_Fast_GET_ITEM(fast, 0);
- value = PySequence_Fast_GET_ITEM(fast, 1);
- if (override || PyDict_GetItem(d, key) == NULL) {
- int status = PyDict_SetItem(d, key, value);
- if (status < 0)
- goto Fail;
- }
- Py_DECREF(fast);
- Py_DECREF(item);
- }
-
- i = 0;
- goto Return;
+ PyObject *it; /* iter(seq2) */
+ Py_ssize_t i; /* index into seq2 of current element */
+ PyObject *item; /* seq2[i] */
+ PyObject *fast; /* item as a 2-tuple or 2-list */
+
+ assert(d != NULL);
+ assert(PyDict_Check(d));
+ assert(seq2 != NULL);
+
+ it = PyObject_GetIter(seq2);
+ if (it == NULL)
+ return -1;
+
+ for (i = 0; ; ++i) {
+ PyObject *key, *value;
+ Py_ssize_t n;
+
+ fast = NULL;
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ if (PyErr_Occurred())
+ goto Fail;
+ break;
+ }
+
+ /* Convert item to sequence, and verify length 2. */
+ fast = PySequence_Fast(item, "");
+ if (fast == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_Format(PyExc_TypeError,
+ "cannot convert dictionary update "
+ "sequence element #%zd to a sequence",
+ i);
+ goto Fail;
+ }
+ n = PySequence_Fast_GET_SIZE(fast);
+ if (n != 2) {
+ PyErr_Format(PyExc_ValueError,
+ "dictionary update sequence element #%zd "
+ "has length %zd; 2 is required",
+ i, n);
+ goto Fail;
+ }
+
+ /* Update/merge with this (key, value) pair. */
+ key = PySequence_Fast_GET_ITEM(fast, 0);
+ value = PySequence_Fast_GET_ITEM(fast, 1);
+ if (override || PyDict_GetItem(d, key) == NULL) {
+ int status = PyDict_SetItem(d, key, value);
+ if (status < 0)
+ goto Fail;
+ }
+ Py_DECREF(fast);
+ Py_DECREF(item);
+ }
+
+ i = 0;
+ goto Return;
Fail:
- Py_XDECREF(item);
- Py_XDECREF(fast);
- i = -1;
+ Py_XDECREF(item);
+ Py_XDECREF(fast);
+ i = -1;
Return:
- Py_DECREF(it);
- return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
+ Py_DECREF(it);
+ return Py_SAFE_DOWNCAST(i, Py_ssize_t, int);
}
int
PyDict_Update(PyObject *a, PyObject *b)
{
- return PyDict_Merge(a, b, 1);
+ return PyDict_Merge(a, b, 1);
}
int
PyDict_Merge(PyObject *a, PyObject *b, int override)
{
- register PyDictObject *mp, *other;
- register Py_ssize_t i;
- PyDictEntry *entry;
-
- /* We accept for the argument either a concrete dictionary object,
- * or an abstract "mapping" object. For the former, we can do
- * things quite efficiently. For the latter, we only require that
- * PyMapping_Keys() and PyObject_GetItem() be supported.
- */
- if (a == NULL || !PyDict_Check(a) || b == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
- mp = (PyDictObject*)a;
- if (PyDict_Check(b)) {
- other = (PyDictObject*)b;
- if (other == mp || other->ma_used == 0)
- /* a.update(a) or a.update({}); nothing to do */
- return 0;
- if (mp->ma_used == 0)
- /* Since the target dict is empty, PyDict_GetItem()
- * always returns NULL. Setting override to 1
- * skips the unnecessary test.
- */
- override = 1;
- /* Do one big resize at the start, rather than
- * incrementally resizing as we insert new items. Expect
- * that there will be no (or few) overlapping keys.
- */
- if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
- if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
- return -1;
- }
- for (i = 0; i <= other->ma_mask; i++) {
- entry = &other->ma_table[i];
- if (entry->me_value != NULL &&
- (override ||
- PyDict_GetItem(a, entry->me_key) == NULL)) {
- Py_INCREF(entry->me_key);
- Py_INCREF(entry->me_value);
- if (insertdict(mp, entry->me_key,
- (long)entry->me_hash,
- entry->me_value) != 0)
- return -1;
- }
- }
- }
- else {
- /* Do it the generic, slower way */
- PyObject *keys = PyMapping_Keys(b);
- PyObject *iter;
- PyObject *key, *value;
- int status;
-
- if (keys == NULL)
- /* Docstring says this is equivalent to E.keys() so
- * if E doesn't have a .keys() method we want
- * AttributeError to percolate up. Might as well
- * do the same for any other error.
- */
- return -1;
-
- iter = PyObject_GetIter(keys);
- Py_DECREF(keys);
- if (iter == NULL)
- return -1;
-
- for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
- if (!override && PyDict_GetItem(a, key) != NULL) {
- Py_DECREF(key);
- continue;
- }
- value = PyObject_GetItem(b, key);
- if (value == NULL) {
- Py_DECREF(iter);
- Py_DECREF(key);
- return -1;
- }
- status = PyDict_SetItem(a, key, value);
- Py_DECREF(key);
- Py_DECREF(value);
- if (status < 0) {
- Py_DECREF(iter);
- return -1;
- }
- }
- Py_DECREF(iter);
- if (PyErr_Occurred())
- /* Iterator completed, via error */
- return -1;
- }
- return 0;
+ register PyDictObject *mp, *other;
+ register Py_ssize_t i;
+ PyDictEntry *entry;
+
+ /* We accept for the argument either a concrete dictionary object,
+ * or an abstract "mapping" object. For the former, we can do
+ * things quite efficiently. For the latter, we only require that
+ * PyMapping_Keys() and PyObject_GetItem() be supported.
+ */
+ if (a == NULL || !PyDict_Check(a) || b == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ mp = (PyDictObject*)a;
+ if (PyDict_Check(b)) {
+ other = (PyDictObject*)b;
+ if (other == mp || other->ma_used == 0)
+ /* a.update(a) or a.update({}); nothing to do */
+ return 0;
+ if (mp->ma_used == 0)
+ /* Since the target dict is empty, PyDict_GetItem()
+ * always returns NULL. Setting override to 1
+ * skips the unnecessary test.
+ */
+ override = 1;
+ /* Do one big resize at the start, rather than
+ * incrementally resizing as we insert new items. Expect
+ * that there will be no (or few) overlapping keys.
+ */
+ if ((mp->ma_fill + other->ma_used)*3 >= (mp->ma_mask+1)*2) {
+ if (dictresize(mp, (mp->ma_used + other->ma_used)*2) != 0)
+ return -1;
+ }
+ for (i = 0; i <= other->ma_mask; i++) {
+ entry = &other->ma_table[i];
+ if (entry->me_value != NULL &&
+ (override ||
+ PyDict_GetItem(a, entry->me_key) == NULL)) {
+ Py_INCREF(entry->me_key);
+ Py_INCREF(entry->me_value);
+ if (insertdict(mp, entry->me_key,
+ (long)entry->me_hash,
+ entry->me_value) != 0)
+ return -1;
+ }
+ }
+ }
+ else {
+ /* Do it the generic, slower way */
+ PyObject *keys = PyMapping_Keys(b);
+ PyObject *iter;
+ PyObject *key, *value;
+ int status;
+
+ if (keys == NULL)
+ /* Docstring says this is equivalent to E.keys() so
+ * if E doesn't have a .keys() method we want
+ * AttributeError to percolate up. Might as well
+ * do the same for any other error.
+ */
+ return -1;
+
+ iter = PyObject_GetIter(keys);
+ Py_DECREF(keys);
+ if (iter == NULL)
+ return -1;
+
+ for (key = PyIter_Next(iter); key; key = PyIter_Next(iter)) {
+ if (!override && PyDict_GetItem(a, key) != NULL) {
+ Py_DECREF(key);
+ continue;
+ }
+ value = PyObject_GetItem(b, key);
+ if (value == NULL) {
+ Py_DECREF(iter);
+ Py_DECREF(key);
+ return -1;
+ }
+ status = PyDict_SetItem(a, key, value);
+ Py_DECREF(key);
+ Py_DECREF(value);
+ if (status < 0) {
+ Py_DECREF(iter);
+ return -1;
+ }
+ }
+ Py_DECREF(iter);
+ if (PyErr_Occurred())
+ /* Iterator completed, via error */
+ return -1;
+ }
+ return 0;
}
static PyObject *
dict_copy(register PyDictObject *mp)
{
- return PyDict_Copy((PyObject*)mp);
+ return PyDict_Copy((PyObject*)mp);
}
PyObject *
PyDict_Copy(PyObject *o)
{
- PyObject *copy;
+ PyObject *copy;
- if (o == NULL || !PyDict_Check(o)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- copy = PyDict_New();
- if (copy == NULL)
- return NULL;
- if (PyDict_Merge(copy, o, 1) == 0)
- return copy;
- Py_DECREF(copy);
- return NULL;
+ if (o == NULL || !PyDict_Check(o)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ copy = PyDict_New();
+ if (copy == NULL)
+ return NULL;
+ if (PyDict_Merge(copy, o, 1) == 0)
+ return copy;
+ Py_DECREF(copy);
+ return NULL;
}
Py_ssize_t
PyDict_Size(PyObject *mp)
{
- if (mp == NULL || !PyDict_Check(mp)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return ((PyDictObject *)mp)->ma_used;
+ if (mp == NULL || !PyDict_Check(mp)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return ((PyDictObject *)mp)->ma_used;
}
PyObject *
PyDict_Keys(PyObject *mp)
{
- if (mp == NULL || !PyDict_Check(mp)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return dict_keys((PyDictObject *)mp);
+ if (mp == NULL || !PyDict_Check(mp)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return dict_keys((PyDictObject *)mp);
}
PyObject *
PyDict_Values(PyObject *mp)
{
- if (mp == NULL || !PyDict_Check(mp)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return dict_values((PyDictObject *)mp);
+ if (mp == NULL || !PyDict_Check(mp)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return dict_values((PyDictObject *)mp);
}
PyObject *
PyDict_Items(PyObject *mp)
{
- if (mp == NULL || !PyDict_Check(mp)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return dict_items((PyDictObject *)mp);
+ if (mp == NULL || !PyDict_Check(mp)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return dict_items((PyDictObject *)mp);
}
/* Subroutine which returns the smallest key in a for which b's value
@@ -1684,123 +1684,123 @@ PyDict_Items(PyObject *mp)
static PyObject *
characterize(PyDictObject *a, PyDictObject *b, PyObject **pval)
{
- PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
- PyObject *aval = NULL; /* a[akey] */
- Py_ssize_t i;
- int cmp;
-
- for (i = 0; i <= a->ma_mask; i++) {
- PyObject *thiskey, *thisaval, *thisbval;
- if (a->ma_table[i].me_value == NULL)
- continue;
- thiskey = a->ma_table[i].me_key;
- Py_INCREF(thiskey); /* keep alive across compares */
- if (akey != NULL) {
- cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
- if (cmp < 0) {
- Py_DECREF(thiskey);
- goto Fail;
- }
- if (cmp > 0 ||
- i > a->ma_mask ||
- a->ma_table[i].me_value == NULL)
- {
- /* Not the *smallest* a key; or maybe it is
- * but the compare shrunk the dict so we can't
- * find its associated value anymore; or
- * maybe it is but the compare deleted the
- * a[thiskey] entry.
- */
- Py_DECREF(thiskey);
- continue;
- }
- }
-
- /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
- thisaval = a->ma_table[i].me_value;
- assert(thisaval);
- Py_INCREF(thisaval); /* keep alive */
- thisbval = PyDict_GetItem((PyObject *)b, thiskey);
- if (thisbval == NULL)
- cmp = 0;
- else {
- /* both dicts have thiskey: same values? */
- cmp = PyObject_RichCompareBool(
- thisaval, thisbval, Py_EQ);
- if (cmp < 0) {
- Py_DECREF(thiskey);
- Py_DECREF(thisaval);
- goto Fail;
- }
- }
- if (cmp == 0) {
- /* New winner. */
- Py_XDECREF(akey);
- Py_XDECREF(aval);
- akey = thiskey;
- aval = thisaval;
- }
- else {
- Py_DECREF(thiskey);
- Py_DECREF(thisaval);
- }
- }
- *pval = aval;
- return akey;
+ PyObject *akey = NULL; /* smallest key in a s.t. a[akey] != b[akey] */
+ PyObject *aval = NULL; /* a[akey] */
+ Py_ssize_t i;
+ int cmp;
+
+ for (i = 0; i <= a->ma_mask; i++) {
+ PyObject *thiskey, *thisaval, *thisbval;
+ if (a->ma_table[i].me_value == NULL)
+ continue;
+ thiskey = a->ma_table[i].me_key;
+ Py_INCREF(thiskey); /* keep alive across compares */
+ if (akey != NULL) {
+ cmp = PyObject_RichCompareBool(akey, thiskey, Py_LT);
+ if (cmp < 0) {
+ Py_DECREF(thiskey);
+ goto Fail;
+ }
+ if (cmp > 0 ||
+ i > a->ma_mask ||
+ a->ma_table[i].me_value == NULL)
+ {
+ /* Not the *smallest* a key; or maybe it is
+ * but the compare shrunk the dict so we can't
+ * find its associated value anymore; or
+ * maybe it is but the compare deleted the
+ * a[thiskey] entry.
+ */
+ Py_DECREF(thiskey);
+ continue;
+ }
+ }
+
+ /* Compare a[thiskey] to b[thiskey]; cmp <- true iff equal. */
+ thisaval = a->ma_table[i].me_value;
+ assert(thisaval);
+ Py_INCREF(thisaval); /* keep alive */
+ thisbval = PyDict_GetItem((PyObject *)b, thiskey);
+ if (thisbval == NULL)
+ cmp = 0;
+ else {
+ /* both dicts have thiskey: same values? */
+ cmp = PyObject_RichCompareBool(
+ thisaval, thisbval, Py_EQ);
+ if (cmp < 0) {
+ Py_DECREF(thiskey);
+ Py_DECREF(thisaval);
+ goto Fail;
+ }
+ }
+ if (cmp == 0) {
+ /* New winner. */
+ Py_XDECREF(akey);
+ Py_XDECREF(aval);
+ akey = thiskey;
+ aval = thisaval;
+ }
+ else {
+ Py_DECREF(thiskey);
+ Py_DECREF(thisaval);
+ }
+ }
+ *pval = aval;
+ return akey;
Fail:
- Py_XDECREF(akey);
- Py_XDECREF(aval);
- *pval = NULL;
- return NULL;
+ Py_XDECREF(akey);
+ Py_XDECREF(aval);
+ *pval = NULL;
+ return NULL;
}
static int
dict_compare(PyDictObject *a, PyDictObject *b)
{
- PyObject *adiff, *bdiff, *aval, *bval;
- int res;
-
- /* Compare lengths first */
- if (a->ma_used < b->ma_used)
- return -1; /* a is shorter */
- else if (a->ma_used > b->ma_used)
- return 1; /* b is shorter */
-
- /* Same length -- check all keys */
- bdiff = bval = NULL;
- adiff = characterize(a, b, &aval);
- if (adiff == NULL) {
- assert(!aval);
- /* Either an error, or a is a subset with the same length so
- * must be equal.
- */
- res = PyErr_Occurred() ? -1 : 0;
- goto Finished;
- }
- bdiff = characterize(b, a, &bval);
- if (bdiff == NULL && PyErr_Occurred()) {
- assert(!bval);
- res = -1;
- goto Finished;
- }
- res = 0;
- if (bdiff) {
- /* bdiff == NULL "should be" impossible now, but perhaps
- * the last comparison done by the characterize() on a had
- * the side effect of making the dicts equal!
- */
- res = PyObject_Compare(adiff, bdiff);
- }
- if (res == 0 && bval != NULL)
- res = PyObject_Compare(aval, bval);
+ PyObject *adiff, *bdiff, *aval, *bval;
+ int res;
+
+ /* Compare lengths first */
+ if (a->ma_used < b->ma_used)
+ return -1; /* a is shorter */
+ else if (a->ma_used > b->ma_used)
+ return 1; /* b is shorter */
+
+ /* Same length -- check all keys */
+ bdiff = bval = NULL;
+ adiff = characterize(a, b, &aval);
+ if (adiff == NULL) {
+ assert(!aval);
+ /* Either an error, or a is a subset with the same length so
+ * must be equal.
+ */
+ res = PyErr_Occurred() ? -1 : 0;
+ goto Finished;
+ }
+ bdiff = characterize(b, a, &bval);
+ if (bdiff == NULL && PyErr_Occurred()) {
+ assert(!bval);
+ res = -1;
+ goto Finished;
+ }
+ res = 0;
+ if (bdiff) {
+ /* bdiff == NULL "should be" impossible now, but perhaps
+ * the last comparison done by the characterize() on a had
+ * the side effect of making the dicts equal!
+ */
+ res = PyObject_Compare(adiff, bdiff);
+ }
+ if (res == 0 && bval != NULL)
+ res = PyObject_Compare(aval, bval);
Finished:
- Py_XDECREF(adiff);
- Py_XDECREF(bdiff);
- Py_XDECREF(aval);
- Py_XDECREF(bval);
- return res;
+ Py_XDECREF(adiff);
+ Py_XDECREF(bdiff);
+ Py_XDECREF(aval);
+ Py_XDECREF(bval);
+ return res;
}
/* Return 1 if dicts equal, 0 if not, -1 if error.
@@ -1810,284 +1810,284 @@ Finished:
static int
dict_equal(PyDictObject *a, PyDictObject *b)
{
- Py_ssize_t i;
-
- if (a->ma_used != b->ma_used)
- /* can't be equal if # of entries differ */
- return 0;
-
- /* Same # of entries -- check all of 'em. Exit early on any diff. */
- for (i = 0; i <= a->ma_mask; i++) {
- PyObject *aval = a->ma_table[i].me_value;
- if (aval != NULL) {
- int cmp;
- PyObject *bval;
- PyObject *key = a->ma_table[i].me_key;
- /* temporarily bump aval's refcount to ensure it stays
- alive until we're done with it */
- Py_INCREF(aval);
- /* ditto for key */
- Py_INCREF(key);
- bval = PyDict_GetItem((PyObject *)b, key);
- Py_DECREF(key);
- if (bval == NULL) {
- Py_DECREF(aval);
- return 0;
- }
- cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
- Py_DECREF(aval);
- if (cmp <= 0) /* error or not equal */
- return cmp;
- }
- }
- return 1;
+ Py_ssize_t i;
+
+ if (a->ma_used != b->ma_used)
+ /* can't be equal if # of entries differ */
+ return 0;
+
+ /* Same # of entries -- check all of 'em. Exit early on any diff. */
+ for (i = 0; i <= a->ma_mask; i++) {
+ PyObject *aval = a->ma_table[i].me_value;
+ if (aval != NULL) {
+ int cmp;
+ PyObject *bval;
+ PyObject *key = a->ma_table[i].me_key;
+ /* temporarily bump aval's refcount to ensure it stays
+ alive until we're done with it */
+ Py_INCREF(aval);
+ /* ditto for key */
+ Py_INCREF(key);
+ bval = PyDict_GetItem((PyObject *)b, key);
+ Py_DECREF(key);
+ if (bval == NULL) {
+ Py_DECREF(aval);
+ return 0;
+ }
+ cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);
+ Py_DECREF(aval);
+ if (cmp <= 0) /* error or not equal */
+ return cmp;
+ }
+ }
+ return 1;
}
static PyObject *
dict_richcompare(PyObject *v, PyObject *w, int op)
{
- int cmp;
- PyObject *res;
-
- if (!PyDict_Check(v) || !PyDict_Check(w)) {
- res = Py_NotImplemented;
- }
- else if (op == Py_EQ || op == Py_NE) {
- cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
- if (cmp < 0)
- return NULL;
- res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
- }
- else {
- /* Py3K warning if comparison isn't == or != */
- if (PyErr_WarnPy3k("dict inequality comparisons not supported "
- "in 3.x", 1) < 0) {
- return NULL;
- }
- res = Py_NotImplemented;
- }
- Py_INCREF(res);
- return res;
+ int cmp;
+ PyObject *res;
+
+ if (!PyDict_Check(v) || !PyDict_Check(w)) {
+ res = Py_NotImplemented;
+ }
+ else if (op == Py_EQ || op == Py_NE) {
+ cmp = dict_equal((PyDictObject *)v, (PyDictObject *)w);
+ if (cmp < 0)
+ return NULL;
+ res = (cmp == (op == Py_EQ)) ? Py_True : Py_False;
+ }
+ else {
+ /* Py3K warning if comparison isn't == or != */
+ if (PyErr_WarnPy3k("dict inequality comparisons not supported "
+ "in 3.x", 1) < 0) {
+ return NULL;
+ }
+ res = Py_NotImplemented;
+ }
+ Py_INCREF(res);
+ return res;
}
static PyObject *
dict_contains(register PyDictObject *mp, PyObject *key)
{
- long hash;
- PyDictEntry *ep;
+ long hash;
+ PyDictEntry *ep;
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return NULL;
- }
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL)
- return NULL;
- return PyBool_FromLong(ep->me_value != NULL);
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return NULL;
+ }
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL)
+ return NULL;
+ return PyBool_FromLong(ep->me_value != NULL);
}
static PyObject *
dict_has_key(register PyDictObject *mp, PyObject *key)
{
- if (PyErr_WarnPy3k("dict.has_key() not supported in 3.x; "
- "use the in operator", 1) < 0)
- return NULL;
- return dict_contains(mp, key);
+ if (PyErr_WarnPy3k("dict.has_key() not supported in 3.x; "
+ "use the in operator", 1) < 0)
+ return NULL;
+ return dict_contains(mp, key);
}
static PyObject *
dict_get(register PyDictObject *mp, PyObject *args)
{
- PyObject *key;
- PyObject *failobj = Py_None;
- PyObject *val = NULL;
- long hash;
- PyDictEntry *ep;
+ PyObject *key;
+ PyObject *failobj = Py_None;
+ PyObject *val = NULL;
+ long hash;
+ PyDictEntry *ep;
- if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "get", 1, 2, &key, &failobj))
+ return NULL;
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return NULL;
- }
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL)
- return NULL;
- val = ep->me_value;
- if (val == NULL)
- val = failobj;
- Py_INCREF(val);
- return val;
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return NULL;
+ }
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL)
+ return NULL;
+ val = ep->me_value;
+ if (val == NULL)
+ val = failobj;
+ Py_INCREF(val);
+ return val;
}
static PyObject *
dict_setdefault(register PyDictObject *mp, PyObject *args)
{
- PyObject *key;
- PyObject *failobj = Py_None;
- PyObject *val = NULL;
- long hash;
- PyDictEntry *ep;
-
- if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
- return NULL;
-
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return NULL;
- }
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL)
- return NULL;
- val = ep->me_value;
- if (val == NULL) {
- val = failobj;
- if (PyDict_SetItem((PyObject*)mp, key, failobj))
- val = NULL;
- }
- Py_XINCREF(val);
- return val;
+ PyObject *key;
+ PyObject *failobj = Py_None;
+ PyObject *val = NULL;
+ long hash;
+ PyDictEntry *ep;
+
+ if (!PyArg_UnpackTuple(args, "setdefault", 1, 2, &key, &failobj))
+ return NULL;
+
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return NULL;
+ }
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL)
+ return NULL;
+ val = ep->me_value;
+ if (val == NULL) {
+ val = failobj;
+ if (PyDict_SetItem((PyObject*)mp, key, failobj))
+ val = NULL;
+ }
+ Py_XINCREF(val);
+ return val;
}
static PyObject *
dict_clear(register PyDictObject *mp)
{
- PyDict_Clear((PyObject *)mp);
- Py_RETURN_NONE;
+ PyDict_Clear((PyObject *)mp);
+ Py_RETURN_NONE;
}
static PyObject *
dict_pop(PyDictObject *mp, PyObject *args)
{
- long hash;
- PyDictEntry *ep;
- PyObject *old_value, *old_key;
- PyObject *key, *deflt = NULL;
-
- if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
- return NULL;
- if (mp->ma_used == 0) {
- if (deflt) {
- Py_INCREF(deflt);
- return deflt;
- }
- PyErr_SetString(PyExc_KeyError,
- "pop(): dictionary is empty");
- return NULL;
- }
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return NULL;
- }
- ep = (mp->ma_lookup)(mp, key, hash);
- if (ep == NULL)
- return NULL;
- if (ep->me_value == NULL) {
- if (deflt) {
- Py_INCREF(deflt);
- return deflt;
- }
- set_key_error(key);
- return NULL;
- }
- old_key = ep->me_key;
- Py_INCREF(dummy);
- ep->me_key = dummy;
- old_value = ep->me_value;
- ep->me_value = NULL;
- mp->ma_used--;
- Py_DECREF(old_key);
- return old_value;
+ long hash;
+ PyDictEntry *ep;
+ PyObject *old_value, *old_key;
+ PyObject *key, *deflt = NULL;
+
+ if(!PyArg_UnpackTuple(args, "pop", 1, 2, &key, &deflt))
+ return NULL;
+ if (mp->ma_used == 0) {
+ if (deflt) {
+ Py_INCREF(deflt);
+ return deflt;
+ }
+ PyErr_SetString(PyExc_KeyError,
+ "pop(): dictionary is empty");
+ return NULL;
+ }
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return NULL;
+ }
+ ep = (mp->ma_lookup)(mp, key, hash);
+ if (ep == NULL)
+ return NULL;
+ if (ep->me_value == NULL) {
+ if (deflt) {
+ Py_INCREF(deflt);
+ return deflt;
+ }
+ set_key_error(key);
+ return NULL;
+ }
+ old_key = ep->me_key;
+ Py_INCREF(dummy);
+ ep->me_key = dummy;
+ old_value = ep->me_value;
+ ep->me_value = NULL;
+ mp->ma_used--;
+ Py_DECREF(old_key);
+ return old_value;
}
static PyObject *
dict_popitem(PyDictObject *mp)
{
- Py_ssize_t i = 0;
- PyDictEntry *ep;
- PyObject *res;
-
- /* Allocate the result tuple before checking the size. Believe it
- * or not, this allocation could trigger a garbage collection which
- * could empty the dict, so if we checked the size first and that
- * happened, the result would be an infinite loop (searching for an
- * entry that no longer exists). Note that the usual popitem()
- * idiom is "while d: k, v = d.popitem()". so needing to throw the
- * tuple away if the dict *is* empty isn't a significant
- * inefficiency -- possible, but unlikely in practice.
- */
- res = PyTuple_New(2);
- if (res == NULL)
- return NULL;
- if (mp->ma_used == 0) {
- Py_DECREF(res);
- PyErr_SetString(PyExc_KeyError,
- "popitem(): dictionary is empty");
- return NULL;
- }
- /* Set ep to "the first" dict entry with a value. We abuse the hash
- * field of slot 0 to hold a search finger:
- * If slot 0 has a value, use slot 0.
- * Else slot 0 is being used to hold a search finger,
- * and we use its hash value as the first index to look.
- */
- ep = &mp->ma_table[0];
- if (ep->me_value == NULL) {
- i = ep->me_hash;
- /* The hash field may be a real hash value, or it may be a
- * legit search finger, or it may be a once-legit search
- * finger that's out of bounds now because it wrapped around
- * or the table shrunk -- simply make sure it's in bounds now.
- */
- if (i > mp->ma_mask || i < 1)
- i = 1; /* skip slot 0 */
- while ((ep = &mp->ma_table[i])->me_value == NULL) {
- i++;
- if (i > mp->ma_mask)
- i = 1;
- }
- }
- PyTuple_SET_ITEM(res, 0, ep->me_key);
- PyTuple_SET_ITEM(res, 1, ep->me_value);
- Py_INCREF(dummy);
- ep->me_key = dummy;
- ep->me_value = NULL;
- mp->ma_used--;
- assert(mp->ma_table[0].me_value == NULL);
- mp->ma_table[0].me_hash = i + 1; /* next place to start */
- return res;
+ Py_ssize_t i = 0;
+ PyDictEntry *ep;
+ PyObject *res;
+
+ /* Allocate the result tuple before checking the size. Believe it
+ * or not, this allocation could trigger a garbage collection which
+ * could empty the dict, so if we checked the size first and that
+ * happened, the result would be an infinite loop (searching for an
+ * entry that no longer exists). Note that the usual popitem()
+ * idiom is "while d: k, v = d.popitem()". so needing to throw the
+ * tuple away if the dict *is* empty isn't a significant
+ * inefficiency -- possible, but unlikely in practice.
+ */
+ res = PyTuple_New(2);
+ if (res == NULL)
+ return NULL;
+ if (mp->ma_used == 0) {
+ Py_DECREF(res);
+ PyErr_SetString(PyExc_KeyError,
+ "popitem(): dictionary is empty");
+ return NULL;
+ }
+ /* Set ep to "the first" dict entry with a value. We abuse the hash
+ * field of slot 0 to hold a search finger:
+ * If slot 0 has a value, use slot 0.
+ * Else slot 0 is being used to hold a search finger,
+ * and we use its hash value as the first index to look.
+ */
+ ep = &mp->ma_table[0];
+ if (ep->me_value == NULL) {
+ i = ep->me_hash;
+ /* The hash field may be a real hash value, or it may be a
+ * legit search finger, or it may be a once-legit search
+ * finger that's out of bounds now because it wrapped around
+ * or the table shrunk -- simply make sure it's in bounds now.
+ */
+ if (i > mp->ma_mask || i < 1)
+ i = 1; /* skip slot 0 */
+ while ((ep = &mp->ma_table[i])->me_value == NULL) {
+ i++;
+ if (i > mp->ma_mask)
+ i = 1;
+ }
+ }
+ PyTuple_SET_ITEM(res, 0, ep->me_key);
+ PyTuple_SET_ITEM(res, 1, ep->me_value);
+ Py_INCREF(dummy);
+ ep->me_key = dummy;
+ ep->me_value = NULL;
+ mp->ma_used--;
+ assert(mp->ma_table[0].me_value == NULL);
+ mp->ma_table[0].me_hash = i + 1; /* next place to start */
+ return res;
}
static int
dict_traverse(PyObject *op, visitproc visit, void *arg)
{
- Py_ssize_t i = 0;
- PyObject *pk;
- PyObject *pv;
+ Py_ssize_t i = 0;
+ PyObject *pk;
+ PyObject *pv;
- while (PyDict_Next(op, &i, &pk, &pv)) {
- Py_VISIT(pk);
- Py_VISIT(pv);
- }
- return 0;
+ while (PyDict_Next(op, &i, &pk, &pv)) {
+ Py_VISIT(pk);
+ Py_VISIT(pv);
+ }
+ return 0;
}
static int
dict_tp_clear(PyObject *op)
{
- PyDict_Clear(op);
- return 0;
+ PyDict_Clear(op);
+ return 0;
}
@@ -2099,30 +2099,30 @@ static PyObject *dictiter_new(PyDictObject *, PyTypeObject *);
static PyObject *
dict_iterkeys(PyDictObject *dict)
{
- return dictiter_new(dict, &PyDictIterKey_Type);
+ return dictiter_new(dict, &PyDictIterKey_Type);
}
static PyObject *
dict_itervalues(PyDictObject *dict)
{
- return dictiter_new(dict, &PyDictIterValue_Type);
+ return dictiter_new(dict, &PyDictIterValue_Type);
}
static PyObject *
dict_iteritems(PyDictObject *dict)
{
- return dictiter_new(dict, &PyDictIterItem_Type);
+ return dictiter_new(dict, &PyDictIterItem_Type);
}
static PyObject *
dict_sizeof(PyDictObject *mp)
{
- Py_ssize_t res;
+ Py_ssize_t res;
- res = sizeof(PyDictObject);
- if (mp->ma_table != mp->ma_smalltable)
- res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry);
- return PyInt_FromSsize_t(res);
+ res = sizeof(PyDictObject);
+ if (mp->ma_table != mp->ma_smalltable)
+ res = res + (mp->ma_mask + 1) * sizeof(PyDictEntry);
+ return PyInt_FromSsize_t(res);
}
PyDoc_STRVAR(has_key__doc__,
@@ -2190,140 +2190,140 @@ static PyObject *dictitems_new(PyObject *);
static PyObject *dictvalues_new(PyObject *);
PyDoc_STRVAR(viewkeys__doc__,
- "D.viewkeys() -> a set-like object providing a view on D's keys");
+ "D.viewkeys() -> a set-like object providing a view on D's keys");
PyDoc_STRVAR(viewitems__doc__,
- "D.viewitems() -> a set-like object providing a view on D's items");
+ "D.viewitems() -> a set-like object providing a view on D's items");
PyDoc_STRVAR(viewvalues__doc__,
- "D.viewvalues() -> an object providing a view on D's values");
+ "D.viewvalues() -> an object providing a view on D's values");
static PyMethodDef mapp_methods[] = {
- {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
- contains__doc__},
- {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
- getitem__doc__},
- {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
- sizeof__doc__},
- {"has_key", (PyCFunction)dict_has_key, METH_O,
- has_key__doc__},
- {"get", (PyCFunction)dict_get, METH_VARARGS,
- get__doc__},
- {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
- setdefault_doc__},
- {"pop", (PyCFunction)dict_pop, METH_VARARGS,
- pop__doc__},
- {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
- popitem__doc__},
- {"keys", (PyCFunction)dict_keys, METH_NOARGS,
- keys__doc__},
- {"items", (PyCFunction)dict_items, METH_NOARGS,
- items__doc__},
- {"values", (PyCFunction)dict_values, METH_NOARGS,
- values__doc__},
- {"viewkeys", (PyCFunction)dictkeys_new, METH_NOARGS,
- viewkeys__doc__},
- {"viewitems", (PyCFunction)dictitems_new, METH_NOARGS,
- viewitems__doc__},
- {"viewvalues", (PyCFunction)dictvalues_new, METH_NOARGS,
- viewvalues__doc__},
- {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
- update__doc__},
- {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
- fromkeys__doc__},
- {"clear", (PyCFunction)dict_clear, METH_NOARGS,
- clear__doc__},
- {"copy", (PyCFunction)dict_copy, METH_NOARGS,
- copy__doc__},
- {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
- iterkeys__doc__},
- {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
- itervalues__doc__},
- {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
- iteritems__doc__},
- {NULL, NULL} /* sentinel */
+ {"__contains__",(PyCFunction)dict_contains, METH_O | METH_COEXIST,
+ contains__doc__},
+ {"__getitem__", (PyCFunction)dict_subscript, METH_O | METH_COEXIST,
+ getitem__doc__},
+ {"__sizeof__", (PyCFunction)dict_sizeof, METH_NOARGS,
+ sizeof__doc__},
+ {"has_key", (PyCFunction)dict_has_key, METH_O,
+ has_key__doc__},
+ {"get", (PyCFunction)dict_get, METH_VARARGS,
+ get__doc__},
+ {"setdefault", (PyCFunction)dict_setdefault, METH_VARARGS,
+ setdefault_doc__},
+ {"pop", (PyCFunction)dict_pop, METH_VARARGS,
+ pop__doc__},
+ {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
+ popitem__doc__},
+ {"keys", (PyCFunction)dict_keys, METH_NOARGS,
+ keys__doc__},
+ {"items", (PyCFunction)dict_items, METH_NOARGS,
+ items__doc__},
+ {"values", (PyCFunction)dict_values, METH_NOARGS,
+ values__doc__},
+ {"viewkeys", (PyCFunction)dictkeys_new, METH_NOARGS,
+ viewkeys__doc__},
+ {"viewitems", (PyCFunction)dictitems_new, METH_NOARGS,
+ viewitems__doc__},
+ {"viewvalues", (PyCFunction)dictvalues_new, METH_NOARGS,
+ viewvalues__doc__},
+ {"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
+ update__doc__},
+ {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
+ fromkeys__doc__},
+ {"clear", (PyCFunction)dict_clear, METH_NOARGS,
+ clear__doc__},
+ {"copy", (PyCFunction)dict_copy, METH_NOARGS,
+ copy__doc__},
+ {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
+ iterkeys__doc__},
+ {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
+ itervalues__doc__},
+ {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
+ iteritems__doc__},
+ {NULL, NULL} /* sentinel */
};
/* Return 1 if `key` is in dict `op`, 0 if not, and -1 on error. */
int
PyDict_Contains(PyObject *op, PyObject *key)
{
- long hash;
- PyDictObject *mp = (PyDictObject *)op;
- PyDictEntry *ep;
+ long hash;
+ PyDictObject *mp = (PyDictObject *)op;
+ PyDictEntry *ep;
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return -1;
- }
- ep = (mp->ma_lookup)(mp, key, hash);
- return ep == NULL ? -1 : (ep->me_value != NULL);
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ ep = (mp->ma_lookup)(mp, key, hash);
+ return ep == NULL ? -1 : (ep->me_value != NULL);
}
/* Internal version of PyDict_Contains used when the hash value is already known */
int
_PyDict_Contains(PyObject *op, PyObject *key, long hash)
{
- PyDictObject *mp = (PyDictObject *)op;
- PyDictEntry *ep;
+ PyDictObject *mp = (PyDictObject *)op;
+ PyDictEntry *ep;
- ep = (mp->ma_lookup)(mp, key, hash);
- return ep == NULL ? -1 : (ep->me_value != NULL);
+ ep = (mp->ma_lookup)(mp, key, hash);
+ return ep == NULL ? -1 : (ep->me_value != NULL);
}
/* Hack to implement "key in dict" */
static PySequenceMethods dict_as_sequence = {
- 0, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- PyDict_Contains, /* sq_contains */
- 0, /* sq_inplace_concat */
- 0, /* sq_inplace_repeat */
+ 0, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ PyDict_Contains, /* sq_contains */
+ 0, /* sq_inplace_concat */
+ 0, /* sq_inplace_repeat */
};
static PyObject *
dict_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *self;
-
- assert(type != NULL && type->tp_alloc != NULL);
- self = type->tp_alloc(type, 0);
- if (self != NULL) {
- PyDictObject *d = (PyDictObject *)self;
- /* It's guaranteed that tp->alloc zeroed out the struct. */
- assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
- INIT_NONZERO_DICT_SLOTS(d);
- d->ma_lookup = lookdict_string;
- /* The object has been implicitely tracked by tp_alloc */
- if (type == &PyDict_Type)
- _PyObject_GC_UNTRACK(d);
+ PyObject *self;
+
+ assert(type != NULL && type->tp_alloc != NULL);
+ self = type->tp_alloc(type, 0);
+ if (self != NULL) {
+ PyDictObject *d = (PyDictObject *)self;
+ /* It's guaranteed that tp->alloc zeroed out the struct. */
+ assert(d->ma_table == NULL && d->ma_fill == 0 && d->ma_used == 0);
+ INIT_NONZERO_DICT_SLOTS(d);
+ d->ma_lookup = lookdict_string;
+ /* The object has been implicitely tracked by tp_alloc */
+ if (type == &PyDict_Type)
+ _PyObject_GC_UNTRACK(d);
#ifdef SHOW_CONVERSION_COUNTS
- ++created;
+ ++created;
#endif
#ifdef SHOW_TRACK_COUNT
- if (_PyObject_GC_IS_TRACKED(d))
- count_tracked++;
- else
- count_untracked++;
+ if (_PyObject_GC_IS_TRACKED(d))
+ count_tracked++;
+ else
+ count_untracked++;
#endif
- }
- return self;
+ }
+ return self;
}
static int
dict_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- return dict_update_common(self, args, kwds, "dict");
+ return dict_update_common(self, args, kwds, "dict");
}
static PyObject *
dict_iter(PyDictObject *dict)
{
- return dictiter_new(dict, &PyDictIterKey_Type);
+ return dictiter_new(dict, &PyDictIterKey_Type);
}
PyDoc_STRVAR(dictionary_doc,
@@ -2338,46 +2338,46 @@ PyDoc_STRVAR(dictionary_doc,
" in the keyword argument list. For example: dict(one=1, two=2)");
PyTypeObject PyDict_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dict",
- sizeof(PyDictObject),
- 0,
- (destructor)dict_dealloc, /* tp_dealloc */
- (printfunc)dict_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)dict_compare, /* tp_compare */
- (reprfunc)dict_repr, /* tp_repr */
- 0, /* tp_as_number */
- &dict_as_sequence, /* tp_as_sequence */
- &dict_as_mapping, /* tp_as_mapping */
- (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
- dictionary_doc, /* tp_doc */
- dict_traverse, /* tp_traverse */
- dict_tp_clear, /* tp_clear */
- dict_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- (getiterfunc)dict_iter, /* tp_iter */
- 0, /* tp_iternext */
- mapp_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 */
- dict_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- dict_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dict",
+ sizeof(PyDictObject),
+ 0,
+ (destructor)dict_dealloc, /* tp_dealloc */
+ (printfunc)dict_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)dict_compare, /* tp_compare */
+ (reprfunc)dict_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &dict_as_sequence, /* tp_as_sequence */
+ &dict_as_mapping, /* tp_as_mapping */
+ (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_DICT_SUBCLASS, /* tp_flags */
+ dictionary_doc, /* tp_doc */
+ dict_traverse, /* tp_traverse */
+ dict_tp_clear, /* tp_clear */
+ dict_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)dict_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ mapp_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 */
+ dict_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ dict_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* For backward compatibility with old dictionary interface */
@@ -2385,338 +2385,338 @@ PyTypeObject PyDict_Type = {
PyObject *
PyDict_GetItemString(PyObject *v, const char *key)
{
- PyObject *kv, *rv;
- kv = PyString_FromString(key);
- if (kv == NULL)
- return NULL;
- rv = PyDict_GetItem(v, kv);
- Py_DECREF(kv);
- return rv;
+ PyObject *kv, *rv;
+ kv = PyString_FromString(key);
+ if (kv == NULL)
+ return NULL;
+ rv = PyDict_GetItem(v, kv);
+ Py_DECREF(kv);
+ return rv;
}
int
PyDict_SetItemString(PyObject *v, const char *key, PyObject *item)
{
- PyObject *kv;
- int err;
- kv = PyString_FromString(key);
- if (kv == NULL)
- return -1;
- PyString_InternInPlace(&kv); /* XXX Should we really? */
- err = PyDict_SetItem(v, kv, item);
- Py_DECREF(kv);
- return err;
+ PyObject *kv;
+ int err;
+ kv = PyString_FromString(key);
+ if (kv == NULL)
+ return -1;
+ PyString_InternInPlace(&kv); /* XXX Should we really? */
+ err = PyDict_SetItem(v, kv, item);
+ Py_DECREF(kv);
+ return err;
}
int
PyDict_DelItemString(PyObject *v, const char *key)
{
- PyObject *kv;
- int err;
- kv = PyString_FromString(key);
- if (kv == NULL)
- return -1;
- err = PyDict_DelItem(v, kv);
- Py_DECREF(kv);
- return err;
+ PyObject *kv;
+ int err;
+ kv = PyString_FromString(key);
+ if (kv == NULL)
+ return -1;
+ err = PyDict_DelItem(v, kv);
+ Py_DECREF(kv);
+ return err;
}
/* Dictionary iterator types */
typedef struct {
- PyObject_HEAD
- PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
- Py_ssize_t di_used;
- Py_ssize_t di_pos;
- PyObject* di_result; /* reusable result tuple for iteritems */
- Py_ssize_t len;
+ PyObject_HEAD
+ PyDictObject *di_dict; /* Set to NULL when iterator is exhausted */
+ Py_ssize_t di_used;
+ Py_ssize_t di_pos;
+ PyObject* di_result; /* reusable result tuple for iteritems */
+ Py_ssize_t len;
} dictiterobject;
static PyObject *
dictiter_new(PyDictObject *dict, PyTypeObject *itertype)
{
- dictiterobject *di;
- di = PyObject_GC_New(dictiterobject, itertype);
- if (di == NULL)
- return NULL;
- Py_INCREF(dict);
- di->di_dict = dict;
- di->di_used = dict->ma_used;
- di->di_pos = 0;
- di->len = dict->ma_used;
- if (itertype == &PyDictIterItem_Type) {
- di->di_result = PyTuple_Pack(2, Py_None, Py_None);
- if (di->di_result == NULL) {
- Py_DECREF(di);
- return NULL;
- }
- }
- else
- di->di_result = NULL;
- _PyObject_GC_TRACK(di);
- return (PyObject *)di;
+ dictiterobject *di;
+ di = PyObject_GC_New(dictiterobject, itertype);
+ if (di == NULL)
+ return NULL;
+ Py_INCREF(dict);
+ di->di_dict = dict;
+ di->di_used = dict->ma_used;
+ di->di_pos = 0;
+ di->len = dict->ma_used;
+ if (itertype == &PyDictIterItem_Type) {
+ di->di_result = PyTuple_Pack(2, Py_None, Py_None);
+ if (di->di_result == NULL) {
+ Py_DECREF(di);
+ return NULL;
+ }
+ }
+ else
+ di->di_result = NULL;
+ _PyObject_GC_TRACK(di);
+ return (PyObject *)di;
}
static void
dictiter_dealloc(dictiterobject *di)
{
- Py_XDECREF(di->di_dict);
- Py_XDECREF(di->di_result);
- PyObject_GC_Del(di);
+ Py_XDECREF(di->di_dict);
+ Py_XDECREF(di->di_result);
+ PyObject_GC_Del(di);
}
static int
dictiter_traverse(dictiterobject *di, visitproc visit, void *arg)
{
- Py_VISIT(di->di_dict);
- Py_VISIT(di->di_result);
- return 0;
+ Py_VISIT(di->di_dict);
+ Py_VISIT(di->di_result);
+ return 0;
}
static PyObject *
dictiter_len(dictiterobject *di)
{
- Py_ssize_t len = 0;
- if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
- len = di->len;
- return PyInt_FromSize_t(len);
+ Py_ssize_t len = 0;
+ if (di->di_dict != NULL && di->di_used == di->di_dict->ma_used)
+ len = di->len;
+ return PyInt_FromSize_t(len);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef dictiter_methods[] = {
- {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)dictiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *dictiter_iternextkey(dictiterobject *di)
{
- PyObject *key;
- register Py_ssize_t i, mask;
- register PyDictEntry *ep;
- PyDictObject *d = di->di_dict;
-
- if (d == NULL)
- return NULL;
- assert (PyDict_Check(d));
-
- if (di->di_used != d->ma_used) {
- PyErr_SetString(PyExc_RuntimeError,
- "dictionary changed size during iteration");
- di->di_used = -1; /* Make this state sticky */
- return NULL;
- }
-
- i = di->di_pos;
- if (i < 0)
- goto fail;
- ep = d->ma_table;
- mask = d->ma_mask;
- while (i <= mask && ep[i].me_value == NULL)
- i++;
- di->di_pos = i+1;
- if (i > mask)
- goto fail;
- di->len--;
- key = ep[i].me_key;
- Py_INCREF(key);
- return key;
+ PyObject *key;
+ register Py_ssize_t i, mask;
+ register PyDictEntry *ep;
+ PyDictObject *d = di->di_dict;
+
+ if (d == NULL)
+ return NULL;
+ assert (PyDict_Check(d));
+
+ if (di->di_used != d->ma_used) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "dictionary changed size during iteration");
+ di->di_used = -1; /* Make this state sticky */
+ return NULL;
+ }
+
+ i = di->di_pos;
+ if (i < 0)
+ goto fail;
+ ep = d->ma_table;
+ mask = d->ma_mask;
+ while (i <= mask && ep[i].me_value == NULL)
+ i++;
+ di->di_pos = i+1;
+ if (i > mask)
+ goto fail;
+ di->len--;
+ key = ep[i].me_key;
+ Py_INCREF(key);
+ return key;
fail:
- Py_DECREF(d);
- di->di_dict = NULL;
- return NULL;
+ Py_DECREF(d);
+ di->di_dict = NULL;
+ return NULL;
}
PyTypeObject PyDictIterKey_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dictionary-keyiterator", /* tp_name */
- sizeof(dictiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dictiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dictiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dictiter_iternextkey, /* tp_iternext */
- dictiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dictionary-keyiterator", /* tp_name */
+ sizeof(dictiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dictiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dictiter_iternextkey, /* tp_iternext */
+ dictiter_methods, /* tp_methods */
+ 0,
};
static PyObject *dictiter_iternextvalue(dictiterobject *di)
{
- PyObject *value;
- register Py_ssize_t i, mask;
- register PyDictEntry *ep;
- PyDictObject *d = di->di_dict;
-
- if (d == NULL)
- return NULL;
- assert (PyDict_Check(d));
-
- if (di->di_used != d->ma_used) {
- PyErr_SetString(PyExc_RuntimeError,
- "dictionary changed size during iteration");
- di->di_used = -1; /* Make this state sticky */
- return NULL;
- }
-
- i = di->di_pos;
- mask = d->ma_mask;
- if (i < 0 || i > mask)
- goto fail;
- ep = d->ma_table;
- while ((value=ep[i].me_value) == NULL) {
- i++;
- if (i > mask)
- goto fail;
- }
- di->di_pos = i+1;
- di->len--;
- Py_INCREF(value);
- return value;
+ PyObject *value;
+ register Py_ssize_t i, mask;
+ register PyDictEntry *ep;
+ PyDictObject *d = di->di_dict;
+
+ if (d == NULL)
+ return NULL;
+ assert (PyDict_Check(d));
+
+ if (di->di_used != d->ma_used) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "dictionary changed size during iteration");
+ di->di_used = -1; /* Make this state sticky */
+ return NULL;
+ }
+
+ i = di->di_pos;
+ mask = d->ma_mask;
+ if (i < 0 || i > mask)
+ goto fail;
+ ep = d->ma_table;
+ while ((value=ep[i].me_value) == NULL) {
+ i++;
+ if (i > mask)
+ goto fail;
+ }
+ di->di_pos = i+1;
+ di->len--;
+ Py_INCREF(value);
+ return value;
fail:
- Py_DECREF(d);
- di->di_dict = NULL;
- return NULL;
+ Py_DECREF(d);
+ di->di_dict = NULL;
+ return NULL;
}
PyTypeObject PyDictIterValue_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dictionary-valueiterator", /* tp_name */
- sizeof(dictiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dictiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dictiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
- dictiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dictionary-valueiterator", /* tp_name */
+ sizeof(dictiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dictiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dictiter_iternextvalue, /* tp_iternext */
+ dictiter_methods, /* tp_methods */
+ 0,
};
static PyObject *dictiter_iternextitem(dictiterobject *di)
{
- PyObject *key, *value, *result = di->di_result;
- register Py_ssize_t i, mask;
- register PyDictEntry *ep;
- PyDictObject *d = di->di_dict;
-
- if (d == NULL)
- return NULL;
- assert (PyDict_Check(d));
-
- if (di->di_used != d->ma_used) {
- PyErr_SetString(PyExc_RuntimeError,
- "dictionary changed size during iteration");
- di->di_used = -1; /* Make this state sticky */
- return NULL;
- }
-
- i = di->di_pos;
- if (i < 0)
- goto fail;
- ep = d->ma_table;
- mask = d->ma_mask;
- while (i <= mask && ep[i].me_value == NULL)
- i++;
- di->di_pos = i+1;
- if (i > mask)
- goto fail;
-
- if (result->ob_refcnt == 1) {
- Py_INCREF(result);
- Py_DECREF(PyTuple_GET_ITEM(result, 0));
- Py_DECREF(PyTuple_GET_ITEM(result, 1));
- } else {
- result = PyTuple_New(2);
- if (result == NULL)
- return NULL;
- }
- di->len--;
- key = ep[i].me_key;
- value = ep[i].me_value;
- Py_INCREF(key);
- Py_INCREF(value);
- PyTuple_SET_ITEM(result, 0, key);
- PyTuple_SET_ITEM(result, 1, value);
- return result;
+ PyObject *key, *value, *result = di->di_result;
+ register Py_ssize_t i, mask;
+ register PyDictEntry *ep;
+ PyDictObject *d = di->di_dict;
+
+ if (d == NULL)
+ return NULL;
+ assert (PyDict_Check(d));
+
+ if (di->di_used != d->ma_used) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "dictionary changed size during iteration");
+ di->di_used = -1; /* Make this state sticky */
+ return NULL;
+ }
+
+ i = di->di_pos;
+ if (i < 0)
+ goto fail;
+ ep = d->ma_table;
+ mask = d->ma_mask;
+ while (i <= mask && ep[i].me_value == NULL)
+ i++;
+ di->di_pos = i+1;
+ if (i > mask)
+ goto fail;
+
+ if (result->ob_refcnt == 1) {
+ Py_INCREF(result);
+ Py_DECREF(PyTuple_GET_ITEM(result, 0));
+ Py_DECREF(PyTuple_GET_ITEM(result, 1));
+ } else {
+ result = PyTuple_New(2);
+ if (result == NULL)
+ return NULL;
+ }
+ di->len--;
+ key = ep[i].me_key;
+ value = ep[i].me_value;
+ Py_INCREF(key);
+ Py_INCREF(value);
+ PyTuple_SET_ITEM(result, 0, key);
+ PyTuple_SET_ITEM(result, 1, value);
+ return result;
fail:
- Py_DECREF(d);
- di->di_dict = NULL;
- return NULL;
+ Py_DECREF(d);
+ di->di_dict = NULL;
+ return NULL;
}
PyTypeObject PyDictIterItem_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dictionary-itemiterator", /* tp_name */
- sizeof(dictiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dictiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dictiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)dictiter_iternextitem, /* tp_iternext */
- dictiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dictionary-itemiterator", /* tp_name */
+ sizeof(dictiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dictiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)dictiter_iternextitem, /* tp_iternext */
+ dictiter_methods, /* tp_methods */
+ 0,
};
/***********************************************/
@@ -2726,56 +2726,56 @@ PyTypeObject PyDictIterItem_Type = {
/* The instance lay-out is the same for all three; but the type differs. */
typedef struct {
- PyObject_HEAD
- PyDictObject *dv_dict;
+ PyObject_HEAD
+ PyDictObject *dv_dict;
} dictviewobject;
static void
dictview_dealloc(dictviewobject *dv)
{
- Py_XDECREF(dv->dv_dict);
- PyObject_GC_Del(dv);
+ Py_XDECREF(dv->dv_dict);
+ PyObject_GC_Del(dv);
}
static int
dictview_traverse(dictviewobject *dv, visitproc visit, void *arg)
{
- Py_VISIT(dv->dv_dict);
- return 0;
+ Py_VISIT(dv->dv_dict);
+ return 0;
}
static Py_ssize_t
dictview_len(dictviewobject *dv)
{
- Py_ssize_t len = 0;
- if (dv->dv_dict != NULL)
- len = dv->dv_dict->ma_used;
- return len;
+ Py_ssize_t len = 0;
+ if (dv->dv_dict != NULL)
+ len = dv->dv_dict->ma_used;
+ return len;
}
static PyObject *
dictview_new(PyObject *dict, PyTypeObject *type)
{
- dictviewobject *dv;
- if (dict == NULL) {
- PyErr_BadInternalCall();
- return NULL;
- }
- if (!PyDict_Check(dict)) {
- /* XXX Get rid of this restriction later */
- PyErr_Format(PyExc_TypeError,
- "%s() requires a dict argument, not '%s'",
- type->tp_name, dict->ob_type->tp_name);
- return NULL;
- }
- dv = PyObject_GC_New(dictviewobject, type);
- if (dv == NULL)
- return NULL;
- Py_INCREF(dict);
- dv->dv_dict = (PyDictObject *)dict;
- _PyObject_GC_TRACK(dv);
- return (PyObject *)dv;
+ dictviewobject *dv;
+ if (dict == NULL) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ if (!PyDict_Check(dict)) {
+ /* XXX Get rid of this restriction later */
+ PyErr_Format(PyExc_TypeError,
+ "%s() requires a dict argument, not '%s'",
+ type->tp_name, dict->ob_type->tp_name);
+ return NULL;
+ }
+ dv = PyObject_GC_New(dictviewobject, type);
+ if (dv == NULL)
+ return NULL;
+ Py_INCREF(dict);
+ dv->dv_dict = (PyDictObject *)dict;
+ _PyObject_GC_TRACK(dv);
+ return (PyObject *)dv;
}
/* TODO(guido): The views objects are not complete:
@@ -2791,106 +2791,106 @@ dictview_new(PyObject *dict, PyTypeObject *type)
static int
all_contained_in(PyObject *self, PyObject *other)
{
- PyObject *iter = PyObject_GetIter(self);
- int ok = 1;
-
- if (iter == NULL)
- return -1;
- for (;;) {
- PyObject *next = PyIter_Next(iter);
- if (next == NULL) {
- if (PyErr_Occurred())
- ok = -1;
- break;
- }
- ok = PySequence_Contains(other, next);
- Py_DECREF(next);
- if (ok <= 0)
- break;
- }
- Py_DECREF(iter);
- return ok;
+ PyObject *iter = PyObject_GetIter(self);
+ int ok = 1;
+
+ if (iter == NULL)
+ return -1;
+ for (;;) {
+ PyObject *next = PyIter_Next(iter);
+ if (next == NULL) {
+ if (PyErr_Occurred())
+ ok = -1;
+ break;
+ }
+ ok = PySequence_Contains(other, next);
+ Py_DECREF(next);
+ if (ok <= 0)
+ break;
+ }
+ Py_DECREF(iter);
+ return ok;
}
static PyObject *
dictview_richcompare(PyObject *self, PyObject *other, int op)
{
- Py_ssize_t len_self, len_other;
- int ok;
- PyObject *result;
-
- assert(self != NULL);
- assert(PyDictViewSet_Check(self));
- assert(other != NULL);
-
- if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- len_self = PyObject_Size(self);
- if (len_self < 0)
- return NULL;
- len_other = PyObject_Size(other);
- if (len_other < 0)
- return NULL;
-
- ok = 0;
- switch(op) {
-
- case Py_NE:
- case Py_EQ:
- if (len_self == len_other)
- ok = all_contained_in(self, other);
- if (op == Py_NE && ok >= 0)
- ok = !ok;
- break;
-
- case Py_LT:
- if (len_self < len_other)
- ok = all_contained_in(self, other);
- break;
-
- case Py_LE:
- if (len_self <= len_other)
- ok = all_contained_in(self, other);
- break;
-
- case Py_GT:
- if (len_self > len_other)
- ok = all_contained_in(other, self);
- break;
-
- case Py_GE:
- if (len_self >= len_other)
- ok = all_contained_in(other, self);
- break;
-
- }
- if (ok < 0)
- return NULL;
- result = ok ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
+ Py_ssize_t len_self, len_other;
+ int ok;
+ PyObject *result;
+
+ assert(self != NULL);
+ assert(PyDictViewSet_Check(self));
+ assert(other != NULL);
+
+ if (!PyAnySet_Check(other) && !PyDictViewSet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ len_self = PyObject_Size(self);
+ if (len_self < 0)
+ return NULL;
+ len_other = PyObject_Size(other);
+ if (len_other < 0)
+ return NULL;
+
+ ok = 0;
+ switch(op) {
+
+ case Py_NE:
+ case Py_EQ:
+ if (len_self == len_other)
+ ok = all_contained_in(self, other);
+ if (op == Py_NE && ok >= 0)
+ ok = !ok;
+ break;
+
+ case Py_LT:
+ if (len_self < len_other)
+ ok = all_contained_in(self, other);
+ break;
+
+ case Py_LE:
+ if (len_self <= len_other)
+ ok = all_contained_in(self, other);
+ break;
+
+ case Py_GT:
+ if (len_self > len_other)
+ ok = all_contained_in(other, self);
+ break;
+
+ case Py_GE:
+ if (len_self >= len_other)
+ ok = all_contained_in(other, self);
+ break;
+
+ }
+ if (ok < 0)
+ return NULL;
+ result = ok ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
}
static PyObject *
dictview_repr(dictviewobject *dv)
{
- PyObject *seq;
- PyObject *seq_str;
- PyObject *result;
-
- seq = PySequence_List((PyObject *)dv);
- if (seq == NULL)
- return NULL;
+ PyObject *seq;
+ PyObject *seq_str;
+ PyObject *result;
+
+ seq = PySequence_List((PyObject *)dv);
+ if (seq == NULL)
+ return NULL;
- seq_str = PyObject_Repr(seq);
- result = PyString_FromFormat("%s(%s)", Py_TYPE(dv)->tp_name,
- PyString_AS_STRING(seq_str));
- Py_DECREF(seq_str);
- Py_DECREF(seq);
- return result;
+ seq_str = PyObject_Repr(seq);
+ result = PyString_FromFormat("%s(%s)", Py_TYPE(dv)->tp_name,
+ PyString_AS_STRING(seq_str));
+ Py_DECREF(seq_str);
+ Py_DECREF(seq);
+ return result;
}
/*** dict_keys ***/
@@ -2898,166 +2898,166 @@ dictview_repr(dictviewobject *dv)
static PyObject *
dictkeys_iter(dictviewobject *dv)
{
- if (dv->dv_dict == NULL) {
- Py_RETURN_NONE;
- }
- return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
+ if (dv->dv_dict == NULL) {
+ Py_RETURN_NONE;
+ }
+ return dictiter_new(dv->dv_dict, &PyDictIterKey_Type);
}
static int
dictkeys_contains(dictviewobject *dv, PyObject *obj)
{
- if (dv->dv_dict == NULL)
- return 0;
- return PyDict_Contains((PyObject *)dv->dv_dict, obj);
+ if (dv->dv_dict == NULL)
+ return 0;
+ return PyDict_Contains((PyObject *)dv->dv_dict, obj);
}
static PySequenceMethods dictkeys_as_sequence = {
- (lenfunc)dictview_len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)dictkeys_contains, /* sq_contains */
+ (lenfunc)dictview_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)dictkeys_contains, /* sq_contains */
};
static PyObject*
dictviews_sub(PyObject* self, PyObject *other)
{
- PyObject *result = PySet_New(self);
- PyObject *tmp;
- if (result == NULL)
- return NULL;
+ PyObject *result = PySet_New(self);
+ PyObject *tmp;
+ if (result == NULL)
+ return NULL;
- tmp = PyObject_CallMethod(result, "difference_update", "O", other);
- if (tmp == NULL) {
- Py_DECREF(result);
- return NULL;
- }
+ tmp = PyObject_CallMethod(result, "difference_update", "O", other);
+ if (tmp == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
- Py_DECREF(tmp);
- return result;
+ Py_DECREF(tmp);
+ return result;
}
static PyObject*
dictviews_and(PyObject* self, PyObject *other)
{
- PyObject *result = PySet_New(self);
- PyObject *tmp;
- if (result == NULL)
- return NULL;
+ PyObject *result = PySet_New(self);
+ PyObject *tmp;
+ if (result == NULL)
+ return NULL;
- tmp = PyObject_CallMethod(result, "intersection_update", "O", other);
- if (tmp == NULL) {
- Py_DECREF(result);
- return NULL;
- }
+ tmp = PyObject_CallMethod(result, "intersection_update", "O", other);
+ if (tmp == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
- Py_DECREF(tmp);
- return result;
+ Py_DECREF(tmp);
+ return result;
}
static PyObject*
dictviews_or(PyObject* self, PyObject *other)
{
- PyObject *result = PySet_New(self);
- PyObject *tmp;
- if (result == NULL)
- return NULL;
+ PyObject *result = PySet_New(self);
+ PyObject *tmp;
+ if (result == NULL)
+ return NULL;
- tmp = PyObject_CallMethod(result, "update", "O", other);
- if (tmp == NULL) {
- Py_DECREF(result);
- return NULL;
- }
+ tmp = PyObject_CallMethod(result, "update", "O", other);
+ if (tmp == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
- Py_DECREF(tmp);
- return result;
+ Py_DECREF(tmp);
+ return result;
}
static PyObject*
dictviews_xor(PyObject* self, PyObject *other)
{
- PyObject *result = PySet_New(self);
- PyObject *tmp;
- if (result == NULL)
- return NULL;
+ PyObject *result = PySet_New(self);
+ PyObject *tmp;
+ if (result == NULL)
+ return NULL;
- tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O",
- other);
- if (tmp == NULL) {
- Py_DECREF(result);
- return NULL;
- }
+ tmp = PyObject_CallMethod(result, "symmetric_difference_update", "O",
+ other);
+ if (tmp == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
- Py_DECREF(tmp);
- return result;
+ Py_DECREF(tmp);
+ return result;
}
static PyNumberMethods dictviews_as_number = {
- 0, /*nb_add*/
- (binaryfunc)dictviews_sub, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- (binaryfunc)dictviews_and, /*nb_and*/
- (binaryfunc)dictviews_xor, /*nb_xor*/
- (binaryfunc)dictviews_or, /*nb_or*/
+ 0, /*nb_add*/
+ (binaryfunc)dictviews_sub, /*nb_subtract*/
+ 0, /*nb_multiply*/
+ 0, /*nb_divide*/
+ 0, /*nb_remainder*/
+ 0, /*nb_divmod*/
+ 0, /*nb_power*/
+ 0, /*nb_negative*/
+ 0, /*nb_positive*/
+ 0, /*nb_absolute*/
+ 0, /*nb_nonzero*/
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ (binaryfunc)dictviews_and, /*nb_and*/
+ (binaryfunc)dictviews_xor, /*nb_xor*/
+ (binaryfunc)dictviews_or, /*nb_or*/
};
static PyMethodDef dictkeys_methods[] = {
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyDictKeys_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dict_keys", /* tp_name */
- sizeof(dictviewobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dictview_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)dictview_repr, /* tp_repr */
- &dictviews_as_number, /* tp_as_number */
- &dictkeys_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_CHECKTYPES, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dictview_traverse, /* tp_traverse */
- 0, /* tp_clear */
- dictview_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- (getiterfunc)dictkeys_iter, /* tp_iter */
- 0, /* tp_iternext */
- dictkeys_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dict_keys", /* tp_name */
+ sizeof(dictviewobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictview_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)dictview_repr, /* tp_repr */
+ &dictviews_as_number, /* tp_as_number */
+ &dictkeys_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_CHECKTYPES, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dictview_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ dictview_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)dictkeys_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ dictkeys_methods, /* tp_methods */
+ 0,
};
static PyObject *
dictkeys_new(PyObject *dict)
{
- return dictview_new(dict, &PyDictKeys_Type);
+ return dictview_new(dict, &PyDictKeys_Type);
}
/*** dict_items ***/
@@ -3065,84 +3065,84 @@ dictkeys_new(PyObject *dict)
static PyObject *
dictitems_iter(dictviewobject *dv)
{
- if (dv->dv_dict == NULL) {
- Py_RETURN_NONE;
- }
- return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
+ if (dv->dv_dict == NULL) {
+ Py_RETURN_NONE;
+ }
+ return dictiter_new(dv->dv_dict, &PyDictIterItem_Type);
}
static int
dictitems_contains(dictviewobject *dv, PyObject *obj)
{
- PyObject *key, *value, *found;
- if (dv->dv_dict == NULL)
- return 0;
- if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
- return 0;
- key = PyTuple_GET_ITEM(obj, 0);
- value = PyTuple_GET_ITEM(obj, 1);
- found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
- if (found == NULL) {
- if (PyErr_Occurred())
- return -1;
- return 0;
- }
- return PyObject_RichCompareBool(value, found, Py_EQ);
+ PyObject *key, *value, *found;
+ if (dv->dv_dict == NULL)
+ return 0;
+ if (!PyTuple_Check(obj) || PyTuple_GET_SIZE(obj) != 2)
+ return 0;
+ key = PyTuple_GET_ITEM(obj, 0);
+ value = PyTuple_GET_ITEM(obj, 1);
+ found = PyDict_GetItem((PyObject *)dv->dv_dict, key);
+ if (found == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ return 0;
+ }
+ return PyObject_RichCompareBool(value, found, Py_EQ);
}
static PySequenceMethods dictitems_as_sequence = {
- (lenfunc)dictview_len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)dictitems_contains, /* sq_contains */
+ (lenfunc)dictview_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)dictitems_contains, /* sq_contains */
};
static PyMethodDef dictitems_methods[] = {
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyDictItems_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dict_items", /* tp_name */
- sizeof(dictviewobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dictview_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)dictview_repr, /* tp_repr */
- &dictviews_as_number, /* tp_as_number */
- &dictitems_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_CHECKTYPES, /* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dictview_traverse, /* tp_traverse */
- 0, /* tp_clear */
- dictview_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- (getiterfunc)dictitems_iter, /* tp_iter */
- 0, /* tp_iternext */
- dictitems_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dict_items", /* tp_name */
+ sizeof(dictviewobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictview_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)dictview_repr, /* tp_repr */
+ &dictviews_as_number, /* tp_as_number */
+ &dictitems_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_CHECKTYPES, /* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dictview_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ dictview_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)dictitems_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ dictitems_methods, /* tp_methods */
+ 0,
};
static PyObject *
dictitems_new(PyObject *dict)
{
- return dictview_new(dict, &PyDictItems_Type);
+ return dictview_new(dict, &PyDictItems_Type);
}
/*** dict_values ***/
@@ -3150,62 +3150,62 @@ dictitems_new(PyObject *dict)
static PyObject *
dictvalues_iter(dictviewobject *dv)
{
- if (dv->dv_dict == NULL) {
- Py_RETURN_NONE;
- }
- return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
+ if (dv->dv_dict == NULL) {
+ Py_RETURN_NONE;
+ }
+ return dictiter_new(dv->dv_dict, &PyDictIterValue_Type);
}
static PySequenceMethods dictvalues_as_sequence = {
- (lenfunc)dictview_len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)0, /* sq_contains */
+ (lenfunc)dictview_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)0, /* sq_contains */
};
static PyMethodDef dictvalues_methods[] = {
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyDictValues_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "dict_values", /* tp_name */
- sizeof(dictviewobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)dictview_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_reserved */
- (reprfunc)dictview_repr, /* tp_repr */
- 0, /* tp_as_number */
- &dictvalues_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)dictview_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- (getiterfunc)dictvalues_iter, /* tp_iter */
- 0, /* tp_iternext */
- dictvalues_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "dict_values", /* tp_name */
+ sizeof(dictviewobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)dictview_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_reserved */
+ (reprfunc)dictview_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &dictvalues_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)dictview_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ (getiterfunc)dictvalues_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ dictvalues_methods, /* tp_methods */
+ 0,
};
static PyObject *
dictvalues_new(PyObject *dict)
{
- return dictview_new(dict, &PyDictValues_Type);
+ return dictview_new(dict, &PyDictValues_Type);
}
diff --git a/Objects/enumobject.c b/Objects/enumobject.c
index 2c1c3f8..a83fc7c 100644
--- a/Objects/enumobject.c
+++ b/Objects/enumobject.c
@@ -3,159 +3,159 @@
#include "Python.h"
typedef struct {
- PyObject_HEAD
- Py_ssize_t en_index; /* current index of enumeration */
- PyObject* en_sit; /* secondary iterator of enumeration */
- PyObject* en_result; /* result tuple */
- PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */
+ PyObject_HEAD
+ Py_ssize_t en_index; /* current index of enumeration */
+ PyObject* en_sit; /* secondary iterator of enumeration */
+ PyObject* en_result; /* result tuple */
+ PyObject* en_longindex; /* index for sequences >= PY_SSIZE_T_MAX */
} enumobject;
static PyObject *
enum_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- enumobject *en;
- PyObject *seq = NULL;
- PyObject *start = NULL;
- static char *kwlist[] = {"sequence", "start", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist,
- &seq, &start))
- return NULL;
-
- en = (enumobject *)type->tp_alloc(type, 0);
- if (en == NULL)
- return NULL;
- if (start != NULL) {
- start = PyNumber_Index(start);
- if (start == NULL) {
- Py_DECREF(en);
- return NULL;
- }
- assert(PyInt_Check(start) || PyLong_Check(start));
- en->en_index = PyInt_AsSsize_t(start);
- if (en->en_index == -1 && PyErr_Occurred()) {
- PyErr_Clear();
- en->en_index = PY_SSIZE_T_MAX;
- en->en_longindex = start;
- } else {
- en->en_longindex = NULL;
- Py_DECREF(start);
- }
- } else {
- en->en_index = 0;
- en->en_longindex = NULL;
- }
- en->en_sit = PyObject_GetIter(seq);
- if (en->en_sit == NULL) {
- Py_DECREF(en);
- return NULL;
- }
- en->en_result = PyTuple_Pack(2, Py_None, Py_None);
- if (en->en_result == NULL) {
- Py_DECREF(en);
- return NULL;
- }
- return (PyObject *)en;
+ enumobject *en;
+ PyObject *seq = NULL;
+ PyObject *start = NULL;
+ static char *kwlist[] = {"sequence", "start", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:enumerate", kwlist,
+ &seq, &start))
+ return NULL;
+
+ en = (enumobject *)type->tp_alloc(type, 0);
+ if (en == NULL)
+ return NULL;
+ if (start != NULL) {
+ start = PyNumber_Index(start);
+ if (start == NULL) {
+ Py_DECREF(en);
+ return NULL;
+ }
+ assert(PyInt_Check(start) || PyLong_Check(start));
+ en->en_index = PyInt_AsSsize_t(start);
+ if (en->en_index == -1 && PyErr_Occurred()) {
+ PyErr_Clear();
+ en->en_index = PY_SSIZE_T_MAX;
+ en->en_longindex = start;
+ } else {
+ en->en_longindex = NULL;
+ Py_DECREF(start);
+ }
+ } else {
+ en->en_index = 0;
+ en->en_longindex = NULL;
+ }
+ en->en_sit = PyObject_GetIter(seq);
+ if (en->en_sit == NULL) {
+ Py_DECREF(en);
+ return NULL;
+ }
+ en->en_result = PyTuple_Pack(2, Py_None, Py_None);
+ if (en->en_result == NULL) {
+ Py_DECREF(en);
+ return NULL;
+ }
+ return (PyObject *)en;
}
static void
enum_dealloc(enumobject *en)
{
- PyObject_GC_UnTrack(en);
- Py_XDECREF(en->en_sit);
- Py_XDECREF(en->en_result);
- Py_XDECREF(en->en_longindex);
- Py_TYPE(en)->tp_free(en);
+ PyObject_GC_UnTrack(en);
+ Py_XDECREF(en->en_sit);
+ Py_XDECREF(en->en_result);
+ Py_XDECREF(en->en_longindex);
+ Py_TYPE(en)->tp_free(en);
}
static int
enum_traverse(enumobject *en, visitproc visit, void *arg)
{
- Py_VISIT(en->en_sit);
- Py_VISIT(en->en_result);
- Py_VISIT(en->en_longindex);
- return 0;
+ Py_VISIT(en->en_sit);
+ Py_VISIT(en->en_result);
+ Py_VISIT(en->en_longindex);
+ return 0;
}
static PyObject *
enum_next_long(enumobject *en, PyObject* next_item)
{
- static PyObject *one = NULL;
- PyObject *result = en->en_result;
- PyObject *next_index;
- PyObject *stepped_up;
-
- if (en->en_longindex == NULL) {
- en->en_longindex = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
- if (en->en_longindex == NULL)
- return NULL;
- }
- if (one == NULL) {
- one = PyInt_FromLong(1);
- if (one == NULL)
- return NULL;
- }
- next_index = en->en_longindex;
- assert(next_index != NULL);
- stepped_up = PyNumber_Add(next_index, one);
- if (stepped_up == NULL)
- return NULL;
- en->en_longindex = stepped_up;
-
- if (result->ob_refcnt == 1) {
- Py_INCREF(result);
- Py_DECREF(PyTuple_GET_ITEM(result, 0));
- Py_DECREF(PyTuple_GET_ITEM(result, 1));
- } else {
- result = PyTuple_New(2);
- if (result == NULL) {
- Py_DECREF(next_index);
- Py_DECREF(next_item);
- return NULL;
- }
- }
- PyTuple_SET_ITEM(result, 0, next_index);
- PyTuple_SET_ITEM(result, 1, next_item);
- return result;
+ static PyObject *one = NULL;
+ PyObject *result = en->en_result;
+ PyObject *next_index;
+ PyObject *stepped_up;
+
+ if (en->en_longindex == NULL) {
+ en->en_longindex = PyInt_FromSsize_t(PY_SSIZE_T_MAX);
+ if (en->en_longindex == NULL)
+ return NULL;
+ }
+ if (one == NULL) {
+ one = PyInt_FromLong(1);
+ if (one == NULL)
+ return NULL;
+ }
+ next_index = en->en_longindex;
+ assert(next_index != NULL);
+ stepped_up = PyNumber_Add(next_index, one);
+ if (stepped_up == NULL)
+ return NULL;
+ en->en_longindex = stepped_up;
+
+ if (result->ob_refcnt == 1) {
+ Py_INCREF(result);
+ Py_DECREF(PyTuple_GET_ITEM(result, 0));
+ Py_DECREF(PyTuple_GET_ITEM(result, 1));
+ } else {
+ result = PyTuple_New(2);
+ if (result == NULL) {
+ Py_DECREF(next_index);
+ Py_DECREF(next_item);
+ return NULL;
+ }
+ }
+ PyTuple_SET_ITEM(result, 0, next_index);
+ PyTuple_SET_ITEM(result, 1, next_item);
+ return result;
}
static PyObject *
enum_next(enumobject *en)
{
- PyObject *next_index;
- PyObject *next_item;
- PyObject *result = en->en_result;
- PyObject *it = en->en_sit;
-
- next_item = (*Py_TYPE(it)->tp_iternext)(it);
- if (next_item == NULL)
- return NULL;
-
- if (en->en_index == PY_SSIZE_T_MAX)
- return enum_next_long(en, next_item);
-
- next_index = PyInt_FromSsize_t(en->en_index);
- if (next_index == NULL) {
- Py_DECREF(next_item);
- return NULL;
- }
- en->en_index++;
-
- if (result->ob_refcnt == 1) {
- Py_INCREF(result);
- Py_DECREF(PyTuple_GET_ITEM(result, 0));
- Py_DECREF(PyTuple_GET_ITEM(result, 1));
- } else {
- result = PyTuple_New(2);
- if (result == NULL) {
- Py_DECREF(next_index);
- Py_DECREF(next_item);
- return NULL;
- }
- }
- PyTuple_SET_ITEM(result, 0, next_index);
- PyTuple_SET_ITEM(result, 1, next_item);
- return result;
+ PyObject *next_index;
+ PyObject *next_item;
+ PyObject *result = en->en_result;
+ PyObject *it = en->en_sit;
+
+ next_item = (*Py_TYPE(it)->tp_iternext)(it);
+ if (next_item == NULL)
+ return NULL;
+
+ if (en->en_index == PY_SSIZE_T_MAX)
+ return enum_next_long(en, next_item);
+
+ next_index = PyInt_FromSsize_t(en->en_index);
+ if (next_index == NULL) {
+ Py_DECREF(next_item);
+ return NULL;
+ }
+ en->en_index++;
+
+ if (result->ob_refcnt == 1) {
+ Py_INCREF(result);
+ Py_DECREF(PyTuple_GET_ITEM(result, 0));
+ Py_DECREF(PyTuple_GET_ITEM(result, 1));
+ } else {
+ result = PyTuple_New(2);
+ if (result == NULL) {
+ Py_DECREF(next_index);
+ Py_DECREF(next_item);
+ return NULL;
+ }
+ }
+ PyTuple_SET_ITEM(result, 0, next_index);
+ PyTuple_SET_ITEM(result, 1, next_item);
+ return result;
}
PyDoc_STRVAR(enum_doc,
@@ -167,146 +167,146 @@ PyDoc_STRVAR(enum_doc,
"for obtaining an indexed list: (0, seq[0]), (1, seq[1]), (2, seq[2]), ...");
PyTypeObject PyEnum_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "enumerate", /* tp_name */
- sizeof(enumobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)enum_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- enum_doc, /* tp_doc */
- (traverseproc)enum_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)enum_next, /* tp_iternext */
- 0, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- enum_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "enumerate", /* tp_name */
+ sizeof(enumobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)enum_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ enum_doc, /* tp_doc */
+ (traverseproc)enum_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)enum_next, /* tp_iternext */
+ 0, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ enum_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* Reversed Object ***************************************************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t index;
- PyObject* seq;
+ PyObject_HEAD
+ Py_ssize_t index;
+ PyObject* seq;
} reversedobject;
static PyObject *
reversed_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- Py_ssize_t n;
- PyObject *seq, *reversed_meth;
- static PyObject *reversed_cache = NULL;
- reversedobject *ro;
-
- if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds))
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) )
- return NULL;
-
- if (PyInstance_Check(seq)) {
- reversed_meth = PyObject_GetAttrString(seq, "__reversed__");
- if (reversed_meth == NULL) {
- if (PyErr_ExceptionMatches(PyExc_AttributeError))
- PyErr_Clear();
- else
- return NULL;
- }
- }
- else {
- reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__",
- &reversed_cache);
- if (reversed_meth == NULL && PyErr_Occurred())
- return NULL;
- }
- if (reversed_meth != NULL) {
- PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL);
- Py_DECREF(reversed_meth);
- return res;
- }
-
- if (!PySequence_Check(seq)) {
- PyErr_SetString(PyExc_TypeError,
- "argument to reversed() must be a sequence");
- return NULL;
- }
-
- n = PySequence_Size(seq);
- if (n == -1)
- return NULL;
-
- ro = (reversedobject *)type->tp_alloc(type, 0);
- if (ro == NULL)
- return NULL;
-
- ro->index = n-1;
- Py_INCREF(seq);
- ro->seq = seq;
- return (PyObject *)ro;
+ Py_ssize_t n;
+ PyObject *seq, *reversed_meth;
+ static PyObject *reversed_cache = NULL;
+ reversedobject *ro;
+
+ if (type == &PyReversed_Type && !_PyArg_NoKeywords("reversed()", kwds))
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "reversed", 1, 1, &seq) )
+ return NULL;
+
+ if (PyInstance_Check(seq)) {
+ reversed_meth = PyObject_GetAttrString(seq, "__reversed__");
+ if (reversed_meth == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_AttributeError))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ }
+ else {
+ reversed_meth = _PyObject_LookupSpecial(seq, "__reversed__",
+ &reversed_cache);
+ if (reversed_meth == NULL && PyErr_Occurred())
+ return NULL;
+ }
+ if (reversed_meth != NULL) {
+ PyObject *res = PyObject_CallFunctionObjArgs(reversed_meth, NULL);
+ Py_DECREF(reversed_meth);
+ return res;
+ }
+
+ if (!PySequence_Check(seq)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument to reversed() must be a sequence");
+ return NULL;
+ }
+
+ n = PySequence_Size(seq);
+ if (n == -1)
+ return NULL;
+
+ ro = (reversedobject *)type->tp_alloc(type, 0);
+ if (ro == NULL)
+ return NULL;
+
+ ro->index = n-1;
+ Py_INCREF(seq);
+ ro->seq = seq;
+ return (PyObject *)ro;
}
static void
reversed_dealloc(reversedobject *ro)
{
- PyObject_GC_UnTrack(ro);
- Py_XDECREF(ro->seq);
- Py_TYPE(ro)->tp_free(ro);
+ PyObject_GC_UnTrack(ro);
+ Py_XDECREF(ro->seq);
+ Py_TYPE(ro)->tp_free(ro);
}
static int
reversed_traverse(reversedobject *ro, visitproc visit, void *arg)
{
- Py_VISIT(ro->seq);
- return 0;
+ Py_VISIT(ro->seq);
+ return 0;
}
static PyObject *
reversed_next(reversedobject *ro)
{
- PyObject *item;
- Py_ssize_t index = ro->index;
-
- if (index >= 0) {
- item = PySequence_GetItem(ro->seq, index);
- if (item != NULL) {
- ro->index--;
- return item;
- }
- if (PyErr_ExceptionMatches(PyExc_IndexError) ||
- PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- }
- ro->index = -1;
- Py_CLEAR(ro->seq);
- return NULL;
+ PyObject *item;
+ Py_ssize_t index = ro->index;
+
+ if (index >= 0) {
+ item = PySequence_GetItem(ro->seq, index);
+ if (item != NULL) {
+ ro->index--;
+ return item;
+ }
+ if (PyErr_ExceptionMatches(PyExc_IndexError) ||
+ PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ }
+ ro->index = -1;
+ Py_CLEAR(ro->seq);
+ return NULL;
}
PyDoc_STRVAR(reversed_doc,
@@ -317,64 +317,64 @@ PyDoc_STRVAR(reversed_doc,
static PyObject *
reversed_len(reversedobject *ro)
{
- Py_ssize_t position, seqsize;
-
- if (ro->seq == NULL)
- return PyInt_FromLong(0);
- seqsize = PySequence_Size(ro->seq);
- if (seqsize == -1)
- return NULL;
- position = ro->index + 1;
- return PyInt_FromSsize_t((seqsize < position) ? 0 : position);
+ Py_ssize_t position, seqsize;
+
+ if (ro->seq == NULL)
+ return PyInt_FromLong(0);
+ seqsize = PySequence_Size(ro->seq);
+ if (seqsize == -1)
+ return NULL;
+ position = ro->index + 1;
+ return PyInt_FromSsize_t((seqsize < position) ? 0 : position);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef reversediter_methods[] = {
- {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)reversed_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyReversed_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "reversed", /* tp_name */
- sizeof(reversedobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)reversed_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 | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- reversed_doc, /* tp_doc */
- (traverseproc)reversed_traverse,/* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)reversed_next, /* tp_iternext */
- reversediter_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 */
- PyType_GenericAlloc, /* tp_alloc */
- reversed_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "reversed", /* tp_name */
+ sizeof(reversedobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)reversed_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 | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ reversed_doc, /* tp_doc */
+ (traverseproc)reversed_traverse,/* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)reversed_next, /* tp_iternext */
+ reversediter_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 */
+ PyType_GenericAlloc, /* tp_alloc */
+ reversed_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
diff --git a/Objects/exceptions.c b/Objects/exceptions.c
index a961143..2e98283 100644
--- a/Objects/exceptions.c
+++ b/Objects/exceptions.c
@@ -217,7 +217,7 @@ BaseException_setstate(PyObject *self, PyObject *state)
static PyMethodDef BaseException_methods[] = {
{"__reduce__", (PyCFunction)BaseException_reduce, METH_NOARGS },
{"__setstate__", (PyCFunction)BaseException_setstate, METH_O },
-#ifdef Py_USING_UNICODE
+#ifdef Py_USING_UNICODE
{"__unicode__", (PyCFunction)BaseException_unicode, METH_NOARGS },
#endif
{NULL, NULL, 0, NULL},
@@ -236,7 +236,7 @@ BaseException_getitem(PyBaseExceptionObject *self, Py_ssize_t index)
static PyObject *
BaseException_getslice(PyBaseExceptionObject *self,
- Py_ssize_t start, Py_ssize_t stop)
+ Py_ssize_t start, Py_ssize_t stop)
{
if (PyErr_WarnPy3k("__getslice__ not supported for exception "
"classes in 3.x; use args attribute", 1) < 0)
@@ -316,7 +316,7 @@ static PyObject *
BaseException_get_message(PyBaseExceptionObject *self)
{
PyObject *msg;
-
+
/* if "message" is in self->dict, accessing a user-set message attribute */
if (self->dict &&
(msg = PyDict_GetItemString(self->dict, "message"))) {
@@ -352,7 +352,7 @@ BaseException_set_message(PyBaseExceptionObject *self, PyObject *val)
self->message = NULL;
return 0;
}
-
+
/* else set it in __dict__, but may need to create the dict first */
if (self->dict == NULL) {
self->dict = PyDict_New();
@@ -366,7 +366,7 @@ static PyGetSetDef BaseException_getset[] = {
{"__dict__", (getter)BaseException_get_dict, (setter)BaseException_set_dict},
{"args", (getter)BaseException_get_args, (setter)BaseException_set_args},
{"message", (getter)BaseException_get_message,
- (setter)BaseException_set_message},
+ (setter)BaseException_set_message},
{NULL},
};
@@ -393,7 +393,7 @@ static PyTypeObject _PyExc_BaseException = {
PyObject_GenericSetAttr, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
+ Py_TPFLAGS_BASE_EXC_SUBCLASS, /*tp_flags*/
PyDoc_STR("Common base class for all exceptions"), /* tp_doc */
(traverseproc)BaseException_traverse, /* tp_traverse */
(inquiry)BaseException_clear, /* tp_clear */
@@ -2186,25 +2186,25 @@ _PyExc_Init(void)
PyExc_RecursionErrorInst = BaseException_new(&_PyExc_RuntimeError, NULL, NULL);
if (!PyExc_RecursionErrorInst)
- Py_FatalError("Cannot pre-allocate RuntimeError instance for "
- "recursion errors");
+ Py_FatalError("Cannot pre-allocate RuntimeError instance for "
+ "recursion errors");
else {
- PyBaseExceptionObject *err_inst =
- (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
- PyObject *args_tuple;
- PyObject *exc_message;
- exc_message = PyString_FromString("maximum recursion depth exceeded");
- if (!exc_message)
- Py_FatalError("cannot allocate argument for RuntimeError "
- "pre-allocation");
- args_tuple = PyTuple_Pack(1, exc_message);
- if (!args_tuple)
- Py_FatalError("cannot allocate tuple for RuntimeError "
- "pre-allocation");
- Py_DECREF(exc_message);
- if (BaseException_init(err_inst, args_tuple, NULL))
- Py_FatalError("init of pre-allocated RuntimeError failed");
- Py_DECREF(args_tuple);
+ PyBaseExceptionObject *err_inst =
+ (PyBaseExceptionObject *)PyExc_RecursionErrorInst;
+ PyObject *args_tuple;
+ PyObject *exc_message;
+ exc_message = PyString_FromString("maximum recursion depth exceeded");
+ if (!exc_message)
+ Py_FatalError("cannot allocate argument for RuntimeError "
+ "pre-allocation");
+ args_tuple = PyTuple_Pack(1, exc_message);
+ if (!args_tuple)
+ Py_FatalError("cannot allocate tuple for RuntimeError "
+ "pre-allocation");
+ Py_DECREF(exc_message);
+ if (BaseException_init(err_inst, args_tuple, NULL))
+ Py_FatalError("init of pre-allocated RuntimeError failed");
+ Py_DECREF(args_tuple);
}
Py_DECREF(bltinmod);
diff --git a/Objects/fileobject.c b/Objects/fileobject.c
index f479501..6b95a0c 100644
--- a/Objects/fileobject.c
+++ b/Objects/fileobject.c
@@ -37,10 +37,10 @@
#endif
/* Bits in f_newlinetypes */
-#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
-#define NEWLINE_CR 1 /* \r newline seen */
-#define NEWLINE_LF 2 /* \n newline seen */
-#define NEWLINE_CRLF 4 /* \r\n newline seen */
+#define NEWLINE_UNKNOWN 0 /* No newline seen, yet */
+#define NEWLINE_CR 1 /* \r newline seen */
+#define NEWLINE_LF 2 /* \n newline seen */
+#define NEWLINE_CRLF 4 /* \r\n newline seen */
/*
* These macros release the GIL while preventing the f_close() function being
@@ -52,19 +52,19 @@
#define FILE_BEGIN_ALLOW_THREADS(fobj) \
{ \
- fobj->unlocked_count++; \
- Py_BEGIN_ALLOW_THREADS
+ fobj->unlocked_count++; \
+ Py_BEGIN_ALLOW_THREADS
#define FILE_END_ALLOW_THREADS(fobj) \
- Py_END_ALLOW_THREADS \
- fobj->unlocked_count--; \
- assert(fobj->unlocked_count >= 0); \
+ Py_END_ALLOW_THREADS \
+ fobj->unlocked_count--; \
+ assert(fobj->unlocked_count >= 0); \
}
#define FILE_ABORT_ALLOW_THREADS(fobj) \
- Py_BLOCK_THREADS \
- fobj->unlocked_count--; \
- assert(fobj->unlocked_count >= 0);
+ Py_BLOCK_THREADS \
+ fobj->unlocked_count--; \
+ assert(fobj->unlocked_count >= 0);
#ifdef __cplusplus
extern "C" {
@@ -73,30 +73,30 @@ extern "C" {
FILE *
PyFile_AsFile(PyObject *f)
{
- if (f == NULL || !PyFile_Check(f))
- return NULL;
- else
- return ((PyFileObject *)f)->f_fp;
+ if (f == NULL || !PyFile_Check(f))
+ return NULL;
+ else
+ return ((PyFileObject *)f)->f_fp;
}
void PyFile_IncUseCount(PyFileObject *fobj)
{
- fobj->unlocked_count++;
+ fobj->unlocked_count++;
}
void PyFile_DecUseCount(PyFileObject *fobj)
{
- fobj->unlocked_count--;
- assert(fobj->unlocked_count >= 0);
+ fobj->unlocked_count--;
+ assert(fobj->unlocked_count >= 0);
}
PyObject *
PyFile_Name(PyObject *f)
{
- if (f == NULL || !PyFile_Check(f))
- return NULL;
- else
- return ((PyFileObject *)f)->f_name;
+ if (f == NULL || !PyFile_Check(f))
+ return NULL;
+ else
+ return ((PyFileObject *)f)->f_name;
}
/* This is a safe wrapper around PyObject_Print to print to the FILE
@@ -105,11 +105,11 @@ PyFile_Name(PyObject *f)
static int
file_PyObject_Print(PyObject *op, PyFileObject *f, int flags)
{
- int result;
- PyFile_IncUseCount(f);
- result = PyObject_Print(op, f->f_fp, flags);
- PyFile_DecUseCount(f);
- return result;
+ int result;
+ PyFile_IncUseCount(f);
+ result = PyObject_Print(op, f->f_fp, flags);
+ PyFile_DecUseCount(f);
+ return result;
}
/* On Unix, fopen will succeed for directories.
@@ -120,66 +120,66 @@ static PyFileObject*
dircheck(PyFileObject* f)
{
#if defined(HAVE_FSTAT) && defined(S_IFDIR) && defined(EISDIR)
- struct stat buf;
- if (f->f_fp == NULL)
- return f;
- if (fstat(fileno(f->f_fp), &buf) == 0 &&
- S_ISDIR(buf.st_mode)) {
- char *msg = strerror(EISDIR);
- PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
- EISDIR, msg, f->f_name);
- PyErr_SetObject(PyExc_IOError, exc);
- Py_XDECREF(exc);
- return NULL;
- }
+ struct stat buf;
+ if (f->f_fp == NULL)
+ return f;
+ if (fstat(fileno(f->f_fp), &buf) == 0 &&
+ S_ISDIR(buf.st_mode)) {
+ char *msg = strerror(EISDIR);
+ PyObject *exc = PyObject_CallFunction(PyExc_IOError, "(isO)",
+ EISDIR, msg, f->f_name);
+ PyErr_SetObject(PyExc_IOError, exc);
+ Py_XDECREF(exc);
+ return NULL;
+ }
#endif
- return f;
+ return f;
}
static PyObject *
fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
- int (*close)(FILE *))
+ int (*close)(FILE *))
{
- assert(name != NULL);
- assert(f != NULL);
- assert(PyFile_Check(f));
- assert(f->f_fp == NULL);
-
- Py_DECREF(f->f_name);
- Py_DECREF(f->f_mode);
- Py_DECREF(f->f_encoding);
- Py_DECREF(f->f_errors);
-
- Py_INCREF(name);
- f->f_name = name;
-
- f->f_mode = PyString_FromString(mode);
-
- f->f_close = close;
- f->f_softspace = 0;
- f->f_binary = strchr(mode,'b') != NULL;
- f->f_buf = NULL;
- f->f_univ_newline = (strchr(mode, 'U') != NULL);
- f->f_newlinetypes = NEWLINE_UNKNOWN;
- f->f_skipnextlf = 0;
- Py_INCREF(Py_None);
- f->f_encoding = Py_None;
- Py_INCREF(Py_None);
- f->f_errors = Py_None;
- f->readable = f->writable = 0;
- if (strchr(mode, 'r') != NULL || f->f_univ_newline)
- f->readable = 1;
- if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
- f->writable = 1;
- if (strchr(mode, '+') != NULL)
- f->readable = f->writable = 1;
-
- if (f->f_mode == NULL)
- return NULL;
- f->f_fp = fp;
- f = dircheck(f);
- return (PyObject *) f;
+ assert(name != NULL);
+ assert(f != NULL);
+ assert(PyFile_Check(f));
+ assert(f->f_fp == NULL);
+
+ Py_DECREF(f->f_name);
+ Py_DECREF(f->f_mode);
+ Py_DECREF(f->f_encoding);
+ Py_DECREF(f->f_errors);
+
+ Py_INCREF(name);
+ f->f_name = name;
+
+ f->f_mode = PyString_FromString(mode);
+
+ f->f_close = close;
+ f->f_softspace = 0;
+ f->f_binary = strchr(mode,'b') != NULL;
+ f->f_buf = NULL;
+ f->f_univ_newline = (strchr(mode, 'U') != NULL);
+ f->f_newlinetypes = NEWLINE_UNKNOWN;
+ f->f_skipnextlf = 0;
+ Py_INCREF(Py_None);
+ f->f_encoding = Py_None;
+ Py_INCREF(Py_None);
+ f->f_errors = Py_None;
+ f->readable = f->writable = 0;
+ if (strchr(mode, 'r') != NULL || f->f_univ_newline)
+ f->readable = 1;
+ if (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL)
+ f->writable = 1;
+ if (strchr(mode, '+') != NULL)
+ f->readable = f->writable = 1;
+
+ if (f->f_mode == NULL)
+ return NULL;
+ f->f_fp = fp;
+ f = dircheck(f);
+ return (PyObject *) f;
}
#if defined _MSC_VER && _MSC_VER >= 1400 && defined(__STDC_SECURE_LIB__)
@@ -192,74 +192,74 @@ fill_file_fields(PyFileObject *f, FILE *fp, PyObject *name, char *mode,
*/
static int _PyVerify_Mode_WINNT(const char *mode)
{
- /* See if mode string is valid on Windows to avoid hard assertions */
- /* remove leading spacese */
- int singles = 0;
- int pairs = 0;
- int encoding = 0;
- const char *s, *c;
-
- while(*mode == ' ') /* strip initial spaces */
- ++mode;
- if (!strchr("rwa", *mode)) /* must start with one of these */
- return 0;
- while (*++mode) {
- if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
- continue;
- s = "+TD"; /* each of this can appear only once */
- c = strchr(s, *mode);
- if (c) {
- ptrdiff_t idx = s-c;
- if (singles & (1<<idx))
- return 0;
- singles |= (1<<idx);
- continue;
- }
- s = "btcnSR"; /* only one of each letter in the pairs allowed */
- c = strchr(s, *mode);
- if (c) {
- ptrdiff_t idx = (s-c)/2;
- if (pairs & (1<<idx))
- return 0;
- pairs |= (1<<idx);
- continue;
- }
- if (*mode == ',') {
- encoding = 1;
- break;
- }
- return 0; /* found an invalid char */
- }
-
- if (encoding) {
- char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
- while (*mode == ' ')
- ++mode;
- /* find 'ccs =' */
- if (strncmp(mode, "ccs", 3))
- return 0;
- mode += 3;
- while (*mode == ' ')
- ++mode;
- if (*mode != '=')
- return 0;
- while (*mode == ' ')
- ++mode;
- for(encoding = 0; encoding<_countof(e); ++encoding) {
- size_t l = strlen(e[encoding]);
- if (!strncmp(mode, e[encoding], l)) {
- mode += l; /* found a valid encoding */
- break;
- }
- }
- if (encoding == _countof(e))
- return 0;
- }
- /* skip trailing spaces */
- while (*mode == ' ')
- ++mode;
-
- return *mode == '\0'; /* must be at the end of the string */
+ /* See if mode string is valid on Windows to avoid hard assertions */
+ /* remove leading spacese */
+ int singles = 0;
+ int pairs = 0;
+ int encoding = 0;
+ const char *s, *c;
+
+ while(*mode == ' ') /* strip initial spaces */
+ ++mode;
+ if (!strchr("rwa", *mode)) /* must start with one of these */
+ return 0;
+ while (*++mode) {
+ if (*mode == ' ' || *mode == 'N') /* ignore spaces and N */
+ continue;
+ s = "+TD"; /* each of this can appear only once */
+ c = strchr(s, *mode);
+ if (c) {
+ ptrdiff_t idx = s-c;
+ if (singles & (1<<idx))
+ return 0;
+ singles |= (1<<idx);
+ continue;
+ }
+ s = "btcnSR"; /* only one of each letter in the pairs allowed */
+ c = strchr(s, *mode);
+ if (c) {
+ ptrdiff_t idx = (s-c)/2;
+ if (pairs & (1<<idx))
+ return 0;
+ pairs |= (1<<idx);
+ continue;
+ }
+ if (*mode == ',') {
+ encoding = 1;
+ break;
+ }
+ return 0; /* found an invalid char */
+ }
+
+ if (encoding) {
+ char *e[] = {"UTF-8", "UTF-16LE", "UNICODE"};
+ while (*mode == ' ')
+ ++mode;
+ /* find 'ccs =' */
+ if (strncmp(mode, "ccs", 3))
+ return 0;
+ mode += 3;
+ while (*mode == ' ')
+ ++mode;
+ if (*mode != '=')
+ return 0;
+ while (*mode == ' ')
+ ++mode;
+ for(encoding = 0; encoding<_countof(e); ++encoding) {
+ size_t l = strlen(e[encoding]);
+ if (!strncmp(mode, e[encoding], l)) {
+ mode += l; /* found a valid encoding */
+ break;
+ }
+ }
+ if (encoding == _countof(e))
+ return 0;
+ }
+ /* skip trailing spaces */
+ while (*mode == ' ')
+ ++mode;
+
+ return *mode == '\0'; /* must be at the end of the string */
}
#endif
@@ -272,264 +272,264 @@ static int _PyVerify_Mode_WINNT(const char *mode)
int
_PyFile_SanitizeMode(char *mode)
{
- char *upos;
- size_t len = strlen(mode);
-
- if (!len) {
- PyErr_SetString(PyExc_ValueError, "empty mode string");
- return -1;
- }
-
- upos = strchr(mode, 'U');
- if (upos) {
- memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
-
- if (mode[0] == 'w' || mode[0] == 'a') {
- PyErr_Format(PyExc_ValueError, "universal newline "
- "mode can only be used with modes "
- "starting with 'r'");
- return -1;
- }
-
- if (mode[0] != 'r') {
- memmove(mode+1, mode, strlen(mode)+1);
- mode[0] = 'r';
- }
-
- if (!strchr(mode, 'b')) {
- memmove(mode+2, mode+1, strlen(mode));
- mode[1] = 'b';
- }
- } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
- PyErr_Format(PyExc_ValueError, "mode string must begin with "
- "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
- return -1;
- }
+ char *upos;
+ size_t len = strlen(mode);
+
+ if (!len) {
+ PyErr_SetString(PyExc_ValueError, "empty mode string");
+ return -1;
+ }
+
+ upos = strchr(mode, 'U');
+ if (upos) {
+ memmove(upos, upos+1, len-(upos-mode)); /* incl null char */
+
+ if (mode[0] == 'w' || mode[0] == 'a') {
+ PyErr_Format(PyExc_ValueError, "universal newline "
+ "mode can only be used with modes "
+ "starting with 'r'");
+ return -1;
+ }
+
+ if (mode[0] != 'r') {
+ memmove(mode+1, mode, strlen(mode)+1);
+ mode[0] = 'r';
+ }
+
+ if (!strchr(mode, 'b')) {
+ memmove(mode+2, mode+1, strlen(mode));
+ mode[1] = 'b';
+ }
+ } else if (mode[0] != 'r' && mode[0] != 'w' && mode[0] != 'a') {
+ PyErr_Format(PyExc_ValueError, "mode string must begin with "
+ "one of 'r', 'w', 'a' or 'U', not '%.200s'", mode);
+ return -1;
+ }
#ifdef Py_VERIFY_WINNT
- /* additional checks on NT with visual studio 2005 and higher */
- if (!_PyVerify_Mode_WINNT(mode)) {
- PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
- return -1;
- }
+ /* additional checks on NT with visual studio 2005 and higher */
+ if (!_PyVerify_Mode_WINNT(mode)) {
+ PyErr_Format(PyExc_ValueError, "Invalid mode ('%.50s')", mode);
+ return -1;
+ }
#endif
- return 0;
+ return 0;
}
static PyObject *
open_the_file(PyFileObject *f, char *name, char *mode)
{
- char *newmode;
- assert(f != NULL);
- assert(PyFile_Check(f));
+ char *newmode;
+ assert(f != NULL);
+ assert(PyFile_Check(f));
#ifdef MS_WINDOWS
- /* windows ignores the passed name in order to support Unicode */
- assert(f->f_name != NULL);
+ /* windows ignores the passed name in order to support Unicode */
+ assert(f->f_name != NULL);
#else
- assert(name != NULL);
+ assert(name != NULL);
#endif
- assert(mode != NULL);
- assert(f->f_fp == NULL);
-
- /* probably need to replace 'U' by 'rb' */
- newmode = PyMem_MALLOC(strlen(mode) + 3);
- if (!newmode) {
- PyErr_NoMemory();
- return NULL;
- }
- strcpy(newmode, mode);
-
- if (_PyFile_SanitizeMode(newmode)) {
- f = NULL;
- goto cleanup;
- }
-
- /* rexec.py can't stop a user from getting the file() constructor --
- all they have to do is get *any* file object f, and then do
- type(f). Here we prevent them from doing damage with it. */
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_IOError,
- "file() constructor not accessible in restricted mode");
- f = NULL;
- goto cleanup;
- }
- errno = 0;
+ assert(mode != NULL);
+ assert(f->f_fp == NULL);
+
+ /* probably need to replace 'U' by 'rb' */
+ newmode = PyMem_MALLOC(strlen(mode) + 3);
+ if (!newmode) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ strcpy(newmode, mode);
+
+ if (_PyFile_SanitizeMode(newmode)) {
+ f = NULL;
+ goto cleanup;
+ }
+
+ /* rexec.py can't stop a user from getting the file() constructor --
+ all they have to do is get *any* file object f, and then do
+ type(f). Here we prevent them from doing damage with it. */
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_IOError,
+ "file() constructor not accessible in restricted mode");
+ f = NULL;
+ goto cleanup;
+ }
+ errno = 0;
#ifdef MS_WINDOWS
- if (PyUnicode_Check(f->f_name)) {
- PyObject *wmode;
- wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
- if (f->f_name && wmode) {
- FILE_BEGIN_ALLOW_THREADS(f)
- /* PyUnicode_AS_UNICODE OK without thread
- lock as it is a simple dereference. */
- f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
- PyUnicode_AS_UNICODE(wmode));
- FILE_END_ALLOW_THREADS(f)
- }
- Py_XDECREF(wmode);
- }
+ if (PyUnicode_Check(f->f_name)) {
+ PyObject *wmode;
+ wmode = PyUnicode_DecodeASCII(newmode, strlen(newmode), NULL);
+ if (f->f_name && wmode) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ /* PyUnicode_AS_UNICODE OK without thread
+ lock as it is a simple dereference. */
+ f->f_fp = _wfopen(PyUnicode_AS_UNICODE(f->f_name),
+ PyUnicode_AS_UNICODE(wmode));
+ FILE_END_ALLOW_THREADS(f)
+ }
+ Py_XDECREF(wmode);
+ }
#endif
- if (NULL == f->f_fp && NULL != name) {
- FILE_BEGIN_ALLOW_THREADS(f)
- f->f_fp = fopen(name, newmode);
- FILE_END_ALLOW_THREADS(f)
- }
+ if (NULL == f->f_fp && NULL != name) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ f->f_fp = fopen(name, newmode);
+ FILE_END_ALLOW_THREADS(f)
+ }
- if (f->f_fp == NULL) {
+ if (f->f_fp == NULL) {
#if defined _MSC_VER && (_MSC_VER < 1400 || !defined(__STDC_SECURE_LIB__))
- /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
- * across all Windows flavors. When it sets EINVAL varies
- * across Windows flavors, the exact conditions aren't
- * documented, and the answer lies in the OS's implementation
- * of Win32's CreateFile function (whose source is secret).
- * Seems the best we can do is map EINVAL to ENOENT.
- * Starting with Visual Studio .NET 2005, EINVAL is correctly
- * set by our CRT error handler (set in exceptions.c.)
- */
- if (errno == 0) /* bad mode string */
- errno = EINVAL;
- else if (errno == EINVAL) /* unknown, but not a mode string */
- errno = ENOENT;
+ /* MSVC 6 (Microsoft) leaves errno at 0 for bad mode strings,
+ * across all Windows flavors. When it sets EINVAL varies
+ * across Windows flavors, the exact conditions aren't
+ * documented, and the answer lies in the OS's implementation
+ * of Win32's CreateFile function (whose source is secret).
+ * Seems the best we can do is map EINVAL to ENOENT.
+ * Starting with Visual Studio .NET 2005, EINVAL is correctly
+ * set by our CRT error handler (set in exceptions.c.)
+ */
+ if (errno == 0) /* bad mode string */
+ errno = EINVAL;
+ else if (errno == EINVAL) /* unknown, but not a mode string */
+ errno = ENOENT;
#endif
- /* EINVAL is returned when an invalid filename or
- * an invalid mode is supplied. */
- if (errno == EINVAL) {
- PyObject *v;
- char message[100];
- PyOS_snprintf(message, 100,
- "invalid mode ('%.50s') or filename", mode);
- v = Py_BuildValue("(isO)", errno, message, f->f_name);
- if (v != NULL) {
- PyErr_SetObject(PyExc_IOError, v);
- Py_DECREF(v);
- }
- }
- else
- PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
- f = NULL;
- }
- if (f != NULL)
- f = dircheck(f);
+ /* EINVAL is returned when an invalid filename or
+ * an invalid mode is supplied. */
+ if (errno == EINVAL) {
+ PyObject *v;
+ char message[100];
+ PyOS_snprintf(message, 100,
+ "invalid mode ('%.50s') or filename", mode);
+ v = Py_BuildValue("(isO)", errno, message, f->f_name);
+ if (v != NULL) {
+ PyErr_SetObject(PyExc_IOError, v);
+ Py_DECREF(v);
+ }
+ }
+ else
+ PyErr_SetFromErrnoWithFilenameObject(PyExc_IOError, f->f_name);
+ f = NULL;
+ }
+ if (f != NULL)
+ f = dircheck(f);
cleanup:
- PyMem_FREE(newmode);
+ PyMem_FREE(newmode);
- return (PyObject *)f;
+ return (PyObject *)f;
}
static PyObject *
close_the_file(PyFileObject *f)
{
- int sts = 0;
- int (*local_close)(FILE *);
- FILE *local_fp = f->f_fp;
- if (local_fp != NULL) {
- local_close = f->f_close;
- if (local_close != NULL && f->unlocked_count > 0) {
- if (f->ob_refcnt > 0) {
- PyErr_SetString(PyExc_IOError,
- "close() called during concurrent "
- "operation on the same file object.");
- } else {
- /* This should not happen unless someone is
- * carelessly playing with the PyFileObject
- * struct fields and/or its associated FILE
- * pointer. */
- PyErr_SetString(PyExc_SystemError,
- "PyFileObject locking error in "
- "destructor (refcnt <= 0 at close).");
- }
- return NULL;
- }
- /* NULL out the FILE pointer before releasing the GIL, because
- * it will not be valid anymore after the close() function is
- * called. */
- f->f_fp = NULL;
- if (local_close != NULL) {
- Py_BEGIN_ALLOW_THREADS
- errno = 0;
- sts = (*local_close)(local_fp);
- Py_END_ALLOW_THREADS
- if (sts == EOF)
- return PyErr_SetFromErrno(PyExc_IOError);
- if (sts != 0)
- return PyInt_FromLong((long)sts);
- }
- }
- Py_RETURN_NONE;
+ int sts = 0;
+ int (*local_close)(FILE *);
+ FILE *local_fp = f->f_fp;
+ if (local_fp != NULL) {
+ local_close = f->f_close;
+ if (local_close != NULL && f->unlocked_count > 0) {
+ if (f->ob_refcnt > 0) {
+ PyErr_SetString(PyExc_IOError,
+ "close() called during concurrent "
+ "operation on the same file object.");
+ } else {
+ /* This should not happen unless someone is
+ * carelessly playing with the PyFileObject
+ * struct fields and/or its associated FILE
+ * pointer. */
+ PyErr_SetString(PyExc_SystemError,
+ "PyFileObject locking error in "
+ "destructor (refcnt <= 0 at close).");
+ }
+ return NULL;
+ }
+ /* NULL out the FILE pointer before releasing the GIL, because
+ * it will not be valid anymore after the close() function is
+ * called. */
+ f->f_fp = NULL;
+ if (local_close != NULL) {
+ Py_BEGIN_ALLOW_THREADS
+ errno = 0;
+ sts = (*local_close)(local_fp);
+ Py_END_ALLOW_THREADS
+ if (sts == EOF)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ if (sts != 0)
+ return PyInt_FromLong((long)sts);
+ }
+ }
+ Py_RETURN_NONE;
}
PyObject *
PyFile_FromFile(FILE *fp, char *name, char *mode, int (*close)(FILE *))
{
- PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
- NULL, NULL);
- if (f != NULL) {
- PyObject *o_name = PyString_FromString(name);
- if (o_name == NULL)
- return NULL;
- if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
- Py_DECREF(f);
- f = NULL;
- }
- Py_DECREF(o_name);
- }
- return (PyObject *) f;
+ PyFileObject *f = (PyFileObject *)PyFile_Type.tp_new(&PyFile_Type,
+ NULL, NULL);
+ if (f != NULL) {
+ PyObject *o_name = PyString_FromString(name);
+ if (o_name == NULL)
+ return NULL;
+ if (fill_file_fields(f, fp, o_name, mode, close) == NULL) {
+ Py_DECREF(f);
+ f = NULL;
+ }
+ Py_DECREF(o_name);
+ }
+ return (PyObject *) f;
}
PyObject *
PyFile_FromString(char *name, char *mode)
{
- extern int fclose(FILE *);
- PyFileObject *f;
-
- f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
- if (f != NULL) {
- if (open_the_file(f, name, mode) == NULL) {
- Py_DECREF(f);
- f = NULL;
- }
- }
- return (PyObject *)f;
+ extern int fclose(FILE *);
+ PyFileObject *f;
+
+ f = (PyFileObject *)PyFile_FromFile((FILE *)NULL, name, mode, fclose);
+ if (f != NULL) {
+ if (open_the_file(f, name, mode) == NULL) {
+ Py_DECREF(f);
+ f = NULL;
+ }
+ }
+ return (PyObject *)f;
}
void
PyFile_SetBufSize(PyObject *f, int bufsize)
{
- PyFileObject *file = (PyFileObject *)f;
- if (bufsize >= 0) {
- int type;
- switch (bufsize) {
- case 0:
- type = _IONBF;
- break;
+ PyFileObject *file = (PyFileObject *)f;
+ if (bufsize >= 0) {
+ int type;
+ switch (bufsize) {
+ case 0:
+ type = _IONBF;
+ break;
#ifdef HAVE_SETVBUF
- case 1:
- type = _IOLBF;
- bufsize = BUFSIZ;
- break;
+ case 1:
+ type = _IOLBF;
+ bufsize = BUFSIZ;
+ break;
#endif
- default:
- type = _IOFBF;
+ default:
+ type = _IOFBF;
#ifndef HAVE_SETVBUF
- bufsize = BUFSIZ;
+ bufsize = BUFSIZ;
#endif
- break;
- }
- fflush(file->f_fp);
- if (type == _IONBF) {
- PyMem_Free(file->f_setbuf);
- file->f_setbuf = NULL;
- } else {
- file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
- bufsize);
- }
+ break;
+ }
+ fflush(file->f_fp);
+ if (type == _IONBF) {
+ PyMem_Free(file->f_setbuf);
+ file->f_setbuf = NULL;
+ } else {
+ file->f_setbuf = (char *)PyMem_Realloc(file->f_setbuf,
+ bufsize);
+ }
#ifdef HAVE_SETVBUF
- setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
+ setvbuf(file->f_fp, file->f_setbuf, type, bufsize);
#else /* !HAVE_SETVBUF */
- setbuf(file->f_fp, file->f_setbuf);
+ setbuf(file->f_fp, file->f_setbuf);
#endif /* !HAVE_SETVBUF */
- }
+ }
}
/* Set the encoding used to output Unicode strings.
@@ -538,48 +538,48 @@ PyFile_SetBufSize(PyObject *f, int bufsize)
int
PyFile_SetEncoding(PyObject *f, const char *enc)
{
- return PyFile_SetEncodingAndErrors(f, enc, NULL);
+ return PyFile_SetEncodingAndErrors(f, enc, NULL);
}
int
PyFile_SetEncodingAndErrors(PyObject *f, const char *enc, char* errors)
{
- PyFileObject *file = (PyFileObject*)f;
- PyObject *str, *oerrors;
-
- assert(PyFile_Check(f));
- str = PyString_FromString(enc);
- if (!str)
- return 0;
- if (errors) {
- oerrors = PyString_FromString(errors);
- if (!oerrors) {
- Py_DECREF(str);
- return 0;
- }
- } else {
- oerrors = Py_None;
- Py_INCREF(Py_None);
- }
- Py_DECREF(file->f_encoding);
- file->f_encoding = str;
- Py_DECREF(file->f_errors);
- file->f_errors = oerrors;
- return 1;
+ PyFileObject *file = (PyFileObject*)f;
+ PyObject *str, *oerrors;
+
+ assert(PyFile_Check(f));
+ str = PyString_FromString(enc);
+ if (!str)
+ return 0;
+ if (errors) {
+ oerrors = PyString_FromString(errors);
+ if (!oerrors) {
+ Py_DECREF(str);
+ return 0;
+ }
+ } else {
+ oerrors = Py_None;
+ Py_INCREF(Py_None);
+ }
+ Py_DECREF(file->f_encoding);
+ file->f_encoding = str;
+ Py_DECREF(file->f_errors);
+ file->f_errors = oerrors;
+ return 1;
}
static PyObject *
err_closed(void)
{
- PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
- return NULL;
+ PyErr_SetString(PyExc_ValueError, "I/O operation on closed file");
+ return NULL;
}
static PyObject *
err_mode(char *action)
{
- PyErr_Format(PyExc_IOError, "File not open for %s", action);
- return NULL;
+ PyErr_Format(PyExc_IOError, "File not open for %s", action);
+ return NULL;
}
/* Refuse regular file I/O if there's data in the iteration-buffer.
@@ -588,9 +588,9 @@ err_mode(char *action)
static PyObject *
err_iterbuffered(void)
{
- PyErr_SetString(PyExc_ValueError,
- "Mixing iteration and read methods would lose data");
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "Mixing iteration and read methods would lose data");
+ return NULL;
}
static void drop_readahead(PyFileObject *);
@@ -600,58 +600,58 @@ static void drop_readahead(PyFileObject *);
static void
file_dealloc(PyFileObject *f)
{
- PyObject *ret;
- if (f->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) f);
- ret = close_the_file(f);
- if (!ret) {
- PySys_WriteStderr("close failed in file object destructor:\n");
- PyErr_Print();
- }
- else {
- Py_DECREF(ret);
- }
- PyMem_Free(f->f_setbuf);
- Py_XDECREF(f->f_name);
- Py_XDECREF(f->f_mode);
- Py_XDECREF(f->f_encoding);
- Py_XDECREF(f->f_errors);
- drop_readahead(f);
- Py_TYPE(f)->tp_free((PyObject *)f);
+ PyObject *ret;
+ if (f->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) f);
+ ret = close_the_file(f);
+ if (!ret) {
+ PySys_WriteStderr("close failed in file object destructor:\n");
+ PyErr_Print();
+ }
+ else {
+ Py_DECREF(ret);
+ }
+ PyMem_Free(f->f_setbuf);
+ Py_XDECREF(f->f_name);
+ Py_XDECREF(f->f_mode);
+ Py_XDECREF(f->f_encoding);
+ Py_XDECREF(f->f_errors);
+ drop_readahead(f);
+ Py_TYPE(f)->tp_free((PyObject *)f);
}
static PyObject *
file_repr(PyFileObject *f)
{
- if (PyUnicode_Check(f->f_name)) {
+ if (PyUnicode_Check(f->f_name)) {
#ifdef Py_USING_UNICODE
- PyObject *ret = NULL;
- PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
- const char *name_str = name ? PyString_AsString(name) : "?";
- ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
- f->f_fp == NULL ? "closed" : "open",
- name_str,
- PyString_AsString(f->f_mode),
- f);
- Py_XDECREF(name);
- return ret;
+ PyObject *ret = NULL;
+ PyObject *name = PyUnicode_AsUnicodeEscapeString(f->f_name);
+ const char *name_str = name ? PyString_AsString(name) : "?";
+ ret = PyString_FromFormat("<%s file u'%s', mode '%s' at %p>",
+ f->f_fp == NULL ? "closed" : "open",
+ name_str,
+ PyString_AsString(f->f_mode),
+ f);
+ Py_XDECREF(name);
+ return ret;
#endif
- } else {
- return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
- f->f_fp == NULL ? "closed" : "open",
- PyString_AsString(f->f_name),
- PyString_AsString(f->f_mode),
- f);
- }
+ } else {
+ return PyString_FromFormat("<%s file '%s', mode '%s' at %p>",
+ f->f_fp == NULL ? "closed" : "open",
+ PyString_AsString(f->f_name),
+ PyString_AsString(f->f_mode),
+ f);
+ }
}
static PyObject *
file_close(PyFileObject *f)
{
- PyObject *sts = close_the_file(f);
- PyMem_Free(f->f_setbuf);
- f->f_setbuf = NULL;
- return sts;
+ PyObject *sts = close_the_file(f);
+ PyMem_Free(f->f_setbuf);
+ f->f_setbuf = NULL;
+ return sts;
}
@@ -673,36 +673,36 @@ static int
_portable_fseek(FILE *fp, Py_off_t offset, int whence)
{
#if !defined(HAVE_LARGEFILE_SUPPORT)
- return fseek(fp, offset, whence);
+ return fseek(fp, offset, whence);
#elif defined(HAVE_FSEEKO) && SIZEOF_OFF_T >= 8
- return fseeko(fp, offset, whence);
+ return fseeko(fp, offset, whence);
#elif defined(HAVE_FSEEK64)
- return fseek64(fp, offset, whence);
+ return fseek64(fp, offset, whence);
#elif defined(__BEOS__)
- return _fseek(fp, offset, whence);
+ return _fseek(fp, offset, whence);
#elif SIZEOF_FPOS_T >= 8
- /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
- and fgetpos() to implement fseek()*/
- fpos_t pos;
- switch (whence) {
- case SEEK_END:
+ /* lacking a 64-bit capable fseek(), use a 64-bit capable fsetpos()
+ and fgetpos() to implement fseek()*/
+ fpos_t pos;
+ switch (whence) {
+ case SEEK_END:
#ifdef MS_WINDOWS
- fflush(fp);
- if (_lseeki64(fileno(fp), 0, 2) == -1)
- return -1;
+ fflush(fp);
+ if (_lseeki64(fileno(fp), 0, 2) == -1)
+ return -1;
#else
- if (fseek(fp, 0, SEEK_END) != 0)
- return -1;
+ if (fseek(fp, 0, SEEK_END) != 0)
+ return -1;
#endif
- /* fall through */
- case SEEK_CUR:
- if (fgetpos(fp, &pos) != 0)
- return -1;
- offset += pos;
- break;
- /* case SEEK_SET: break; */
- }
- return fsetpos(fp, &offset);
+ /* fall through */
+ case SEEK_CUR:
+ if (fgetpos(fp, &pos) != 0)
+ return -1;
+ offset += pos;
+ break;
+ /* case SEEK_SET: break; */
+ }
+ return fsetpos(fp, &offset);
#else
#error "Large file support, but no way to fseek."
#endif
@@ -716,16 +716,16 @@ static Py_off_t
_portable_ftell(FILE* fp)
{
#if !defined(HAVE_LARGEFILE_SUPPORT)
- return ftell(fp);
+ return ftell(fp);
#elif defined(HAVE_FTELLO) && SIZEOF_OFF_T >= 8
- return ftello(fp);
+ return ftello(fp);
#elif defined(HAVE_FTELL64)
- return ftell64(fp);
+ return ftell64(fp);
#elif SIZEOF_FPOS_T >= 8
- fpos_t pos;
- if (fgetpos(fp, &pos) != 0)
- return -1;
- return pos;
+ fpos_t pos;
+ if (fgetpos(fp, &pos) != 0)
+ return -1;
+ return pos;
#else
#error "Large file support, but no way to ftell."
#endif
@@ -735,53 +735,53 @@ _portable_ftell(FILE* fp)
static PyObject *
file_seek(PyFileObject *f, PyObject *args)
{
- int whence;
- int ret;
- Py_off_t offset;
- PyObject *offobj, *off_index;
-
- if (f->f_fp == NULL)
- return err_closed();
- drop_readahead(f);
- whence = 0;
- if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
- return NULL;
- off_index = PyNumber_Index(offobj);
- if (!off_index) {
- if (!PyFloat_Check(offobj))
- return NULL;
- /* Deprecated in 2.6 */
- PyErr_Clear();
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "integer argument expected, got float",
- 1) < 0)
- return NULL;
- off_index = offobj;
- Py_INCREF(offobj);
- }
+ int whence;
+ int ret;
+ Py_off_t offset;
+ PyObject *offobj, *off_index;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ drop_readahead(f);
+ whence = 0;
+ if (!PyArg_ParseTuple(args, "O|i:seek", &offobj, &whence))
+ return NULL;
+ off_index = PyNumber_Index(offobj);
+ if (!off_index) {
+ if (!PyFloat_Check(offobj))
+ return NULL;
+ /* Deprecated in 2.6 */
+ PyErr_Clear();
+ if (PyErr_WarnEx(PyExc_DeprecationWarning,
+ "integer argument expected, got float",
+ 1) < 0)
+ return NULL;
+ off_index = offobj;
+ Py_INCREF(offobj);
+ }
#if !defined(HAVE_LARGEFILE_SUPPORT)
- offset = PyInt_AsLong(off_index);
+ offset = PyInt_AsLong(off_index);
#else
- offset = PyLong_Check(off_index) ?
- PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
+ offset = PyLong_Check(off_index) ?
+ PyLong_AsLongLong(off_index) : PyInt_AsLong(off_index);
#endif
- Py_DECREF(off_index);
- if (PyErr_Occurred())
- return NULL;
-
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- ret = _portable_fseek(f->f_fp, offset, whence);
- FILE_END_ALLOW_THREADS(f)
-
- if (ret != 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- return NULL;
- }
- f->f_skipnextlf = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_DECREF(off_index);
+ if (PyErr_Occurred())
+ return NULL;
+
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ ret = _portable_fseek(f->f_fp, offset, whence);
+ FILE_END_ALLOW_THREADS(f)
+
+ if (ret != 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ return NULL;
+ }
+ f->f_skipnextlf = 0;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -789,186 +789,186 @@ file_seek(PyFileObject *f, PyObject *args)
static PyObject *
file_truncate(PyFileObject *f, PyObject *args)
{
- Py_off_t newsize;
- PyObject *newsizeobj = NULL;
- Py_off_t initialpos;
- int ret;
-
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->writable)
- return err_mode("writing");
- if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
- return NULL;
-
- /* Get current file position. If the file happens to be open for
- * update and the last operation was an input operation, C doesn't
- * define what the later fflush() will do, but we promise truncate()
- * won't change the current position (and fflush() *does* change it
- * then at least on Windows). The easiest thing is to capture
- * current pos now and seek back to it at the end.
- */
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- initialpos = _portable_ftell(f->f_fp);
- FILE_END_ALLOW_THREADS(f)
- if (initialpos == -1)
- goto onioerror;
-
- /* Set newsize to current postion if newsizeobj NULL, else to the
- * specified value.
- */
- if (newsizeobj != NULL) {
+ Py_off_t newsize;
+ PyObject *newsizeobj = NULL;
+ Py_off_t initialpos;
+ int ret;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->writable)
+ return err_mode("writing");
+ if (!PyArg_UnpackTuple(args, "truncate", 0, 1, &newsizeobj))
+ return NULL;
+
+ /* Get current file position. If the file happens to be open for
+ * update and the last operation was an input operation, C doesn't
+ * define what the later fflush() will do, but we promise truncate()
+ * won't change the current position (and fflush() *does* change it
+ * then at least on Windows). The easiest thing is to capture
+ * current pos now and seek back to it at the end.
+ */
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ initialpos = _portable_ftell(f->f_fp);
+ FILE_END_ALLOW_THREADS(f)
+ if (initialpos == -1)
+ goto onioerror;
+
+ /* Set newsize to current postion if newsizeobj NULL, else to the
+ * specified value.
+ */
+ if (newsizeobj != NULL) {
#if !defined(HAVE_LARGEFILE_SUPPORT)
- newsize = PyInt_AsLong(newsizeobj);
+ newsize = PyInt_AsLong(newsizeobj);
#else
- newsize = PyLong_Check(newsizeobj) ?
- PyLong_AsLongLong(newsizeobj) :
- PyInt_AsLong(newsizeobj);
+ newsize = PyLong_Check(newsizeobj) ?
+ PyLong_AsLongLong(newsizeobj) :
+ PyInt_AsLong(newsizeobj);
#endif
- if (PyErr_Occurred())
- return NULL;
- }
- else /* default to current position */
- newsize = initialpos;
-
- /* Flush the stream. We're mixing stream-level I/O with lower-level
- * I/O, and a flush may be necessary to synch both platform views
- * of the current file state.
- */
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- ret = fflush(f->f_fp);
- FILE_END_ALLOW_THREADS(f)
- if (ret != 0)
- goto onioerror;
+ if (PyErr_Occurred())
+ return NULL;
+ }
+ else /* default to current position */
+ newsize = initialpos;
+
+ /* Flush the stream. We're mixing stream-level I/O with lower-level
+ * I/O, and a flush may be necessary to synch both platform views
+ * of the current file state.
+ */
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ ret = fflush(f->f_fp);
+ FILE_END_ALLOW_THREADS(f)
+ if (ret != 0)
+ goto onioerror;
#ifdef MS_WINDOWS
- /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
- so don't even try using it. */
- {
- HANDLE hFile;
-
- /* Have to move current pos to desired endpoint on Windows. */
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
- FILE_END_ALLOW_THREADS(f)
- if (ret)
- goto onioerror;
-
- /* Truncate. Note that this may grow the file! */
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
- ret = hFile == (HANDLE)-1;
- if (ret == 0) {
- ret = SetEndOfFile(hFile) == 0;
- if (ret)
- errno = EACCES;
- }
- FILE_END_ALLOW_THREADS(f)
- if (ret)
- goto onioerror;
- }
+ /* MS _chsize doesn't work if newsize doesn't fit in 32 bits,
+ so don't even try using it. */
+ {
+ HANDLE hFile;
+
+ /* Have to move current pos to desired endpoint on Windows. */
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ ret = _portable_fseek(f->f_fp, newsize, SEEK_SET) != 0;
+ FILE_END_ALLOW_THREADS(f)
+ if (ret)
+ goto onioerror;
+
+ /* Truncate. Note that this may grow the file! */
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ hFile = (HANDLE)_get_osfhandle(fileno(f->f_fp));
+ ret = hFile == (HANDLE)-1;
+ if (ret == 0) {
+ ret = SetEndOfFile(hFile) == 0;
+ if (ret)
+ errno = EACCES;
+ }
+ FILE_END_ALLOW_THREADS(f)
+ if (ret)
+ goto onioerror;
+ }
#else
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- ret = ftruncate(fileno(f->f_fp), newsize);
- FILE_END_ALLOW_THREADS(f)
- if (ret != 0)
- goto onioerror;
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ ret = ftruncate(fileno(f->f_fp), newsize);
+ FILE_END_ALLOW_THREADS(f)
+ if (ret != 0)
+ goto onioerror;
#endif /* !MS_WINDOWS */
- /* Restore original file position. */
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
- FILE_END_ALLOW_THREADS(f)
- if (ret)
- goto onioerror;
+ /* Restore original file position. */
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ ret = _portable_fseek(f->f_fp, initialpos, SEEK_SET) != 0;
+ FILE_END_ALLOW_THREADS(f)
+ if (ret)
+ goto onioerror;
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
onioerror:
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- return NULL;
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ return NULL;
}
#endif /* HAVE_FTRUNCATE */
static PyObject *
file_tell(PyFileObject *f)
{
- Py_off_t pos;
-
- if (f->f_fp == NULL)
- return err_closed();
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- pos = _portable_ftell(f->f_fp);
- FILE_END_ALLOW_THREADS(f)
-
- if (pos == -1) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- return NULL;
- }
- if (f->f_skipnextlf) {
- int c;
- c = GETC(f->f_fp);
- if (c == '\n') {
- f->f_newlinetypes |= NEWLINE_CRLF;
- pos++;
- f->f_skipnextlf = 0;
- } else if (c != EOF) ungetc(c, f->f_fp);
- }
+ Py_off_t pos;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ pos = _portable_ftell(f->f_fp);
+ FILE_END_ALLOW_THREADS(f)
+
+ if (pos == -1) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ return NULL;
+ }
+ if (f->f_skipnextlf) {
+ int c;
+ c = GETC(f->f_fp);
+ if (c == '\n') {
+ f->f_newlinetypes |= NEWLINE_CRLF;
+ pos++;
+ f->f_skipnextlf = 0;
+ } else if (c != EOF) ungetc(c, f->f_fp);
+ }
#if !defined(HAVE_LARGEFILE_SUPPORT)
- return PyInt_FromLong(pos);
+ return PyInt_FromLong(pos);
#else
- return PyLong_FromLongLong(pos);
+ return PyLong_FromLongLong(pos);
#endif
}
static PyObject *
file_fileno(PyFileObject *f)
{
- if (f->f_fp == NULL)
- return err_closed();
- return PyInt_FromLong((long) fileno(f->f_fp));
+ if (f->f_fp == NULL)
+ return err_closed();
+ return PyInt_FromLong((long) fileno(f->f_fp));
}
static PyObject *
file_flush(PyFileObject *f)
{
- int res;
-
- if (f->f_fp == NULL)
- return err_closed();
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- res = fflush(f->f_fp);
- FILE_END_ALLOW_THREADS(f)
- if (res != 0) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ int res;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ res = fflush(f->f_fp);
+ FILE_END_ALLOW_THREADS(f)
+ if (res != 0) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
file_isatty(PyFileObject *f)
{
- long res;
- if (f->f_fp == NULL)
- return err_closed();
- FILE_BEGIN_ALLOW_THREADS(f)
- res = isatty((int)fileno(f->f_fp));
- FILE_END_ALLOW_THREADS(f)
- return PyBool_FromLong(res);
+ long res;
+ if (f->f_fp == NULL)
+ return err_closed();
+ FILE_BEGIN_ALLOW_THREADS(f)
+ res = isatty((int)fileno(f->f_fp));
+ FILE_END_ALLOW_THREADS(f)
+ return PyBool_FromLong(res);
}
@@ -988,39 +988,39 @@ static size_t
new_buffersize(PyFileObject *f, size_t currentsize)
{
#ifdef HAVE_FSTAT
- off_t pos, end;
- struct stat st;
- if (fstat(fileno(f->f_fp), &st) == 0) {
- end = st.st_size;
- /* The following is not a bug: we really need to call lseek()
- *and* ftell(). The reason is that some stdio libraries
- mistakenly flush their buffer when ftell() is called and
- the lseek() call it makes fails, thereby throwing away
- data that cannot be recovered in any way. To avoid this,
- we first test lseek(), and only call ftell() if lseek()
- works. We can't use the lseek() value either, because we
- need to take the amount of buffered data into account.
- (Yet another reason why stdio stinks. :-) */
- pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
- if (pos >= 0) {
- pos = ftell(f->f_fp);
- }
- if (pos < 0)
- clearerr(f->f_fp);
- if (end > pos && pos >= 0)
- return currentsize + end - pos + 1;
- /* Add 1 so if the file were to grow we'd notice. */
- }
+ off_t pos, end;
+ struct stat st;
+ if (fstat(fileno(f->f_fp), &st) == 0) {
+ end = st.st_size;
+ /* The following is not a bug: we really need to call lseek()
+ *and* ftell(). The reason is that some stdio libraries
+ mistakenly flush their buffer when ftell() is called and
+ the lseek() call it makes fails, thereby throwing away
+ data that cannot be recovered in any way. To avoid this,
+ we first test lseek(), and only call ftell() if lseek()
+ works. We can't use the lseek() value either, because we
+ need to take the amount of buffered data into account.
+ (Yet another reason why stdio stinks. :-) */
+ pos = lseek(fileno(f->f_fp), 0L, SEEK_CUR);
+ if (pos >= 0) {
+ pos = ftell(f->f_fp);
+ }
+ if (pos < 0)
+ clearerr(f->f_fp);
+ if (end > pos && pos >= 0)
+ return currentsize + end - pos + 1;
+ /* Add 1 so if the file were to grow we'd notice. */
+ }
#endif
- if (currentsize > SMALLCHUNK) {
- /* Keep doubling until we reach BIGCHUNK;
- then keep adding BIGCHUNK. */
- if (currentsize <= BIGCHUNK)
- return currentsize + currentsize;
- else
- return currentsize + BIGCHUNK;
- }
- return currentsize + SMALLCHUNK;
+ if (currentsize > SMALLCHUNK) {
+ /* Keep doubling until we reach BIGCHUNK;
+ then keep adding BIGCHUNK. */
+ if (currentsize <= BIGCHUNK)
+ return currentsize + currentsize;
+ else
+ return currentsize + BIGCHUNK;
+ }
+ return currentsize + SMALLCHUNK;
}
#if defined(EWOULDBLOCK) && defined(EAGAIN) && EWOULDBLOCK != EAGAIN
@@ -1040,114 +1040,114 @@ new_buffersize(PyFileObject *f, size_t currentsize)
static PyObject *
file_read(PyFileObject *f, PyObject *args)
{
- long bytesrequested = -1;
- size_t bytesread, buffersize, chunksize;
- PyObject *v;
-
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->readable)
- return err_mode("reading");
- /* refuse to mix with f.next() */
- if (f->f_buf != NULL &&
- (f->f_bufend - f->f_bufptr) > 0 &&
- f->f_buf[0] != '\0')
- return err_iterbuffered();
- if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
- return NULL;
- if (bytesrequested < 0)
- buffersize = new_buffersize(f, (size_t)0);
- else
- buffersize = bytesrequested;
- if (buffersize > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "requested number of bytes is more than a Python string can hold");
- return NULL;
- }
- v = PyString_FromStringAndSize((char *)NULL, buffersize);
- if (v == NULL)
- return NULL;
- bytesread = 0;
- for (;;) {
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
- buffersize - bytesread, f->f_fp, (PyObject *)f);
- FILE_END_ALLOW_THREADS(f)
- if (chunksize == 0) {
- if (!ferror(f->f_fp))
- break;
- clearerr(f->f_fp);
- /* When in non-blocking mode, data shouldn't
- * be discarded if a blocking signal was
- * received. That will also happen if
- * chunksize != 0, but bytesread < buffersize. */
- if (bytesread > 0 && BLOCKED_ERRNO(errno))
- break;
- PyErr_SetFromErrno(PyExc_IOError);
- Py_DECREF(v);
- return NULL;
- }
- bytesread += chunksize;
- if (bytesread < buffersize) {
- clearerr(f->f_fp);
- break;
- }
- if (bytesrequested < 0) {
- buffersize = new_buffersize(f, buffersize);
- if (_PyString_Resize(&v, buffersize) < 0)
- return NULL;
- } else {
- /* Got what was requested. */
- break;
- }
- }
- if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
- return NULL;
- return v;
+ long bytesrequested = -1;
+ size_t bytesread, buffersize, chunksize;
+ PyObject *v;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->readable)
+ return err_mode("reading");
+ /* refuse to mix with f.next() */
+ if (f->f_buf != NULL &&
+ (f->f_bufend - f->f_bufptr) > 0 &&
+ f->f_buf[0] != '\0')
+ return err_iterbuffered();
+ if (!PyArg_ParseTuple(args, "|l:read", &bytesrequested))
+ return NULL;
+ if (bytesrequested < 0)
+ buffersize = new_buffersize(f, (size_t)0);
+ else
+ buffersize = bytesrequested;
+ if (buffersize > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "requested number of bytes is more than a Python string can hold");
+ return NULL;
+ }
+ v = PyString_FromStringAndSize((char *)NULL, buffersize);
+ if (v == NULL)
+ return NULL;
+ bytesread = 0;
+ for (;;) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ chunksize = Py_UniversalNewlineFread(BUF(v) + bytesread,
+ buffersize - bytesread, f->f_fp, (PyObject *)f);
+ FILE_END_ALLOW_THREADS(f)
+ if (chunksize == 0) {
+ if (!ferror(f->f_fp))
+ break;
+ clearerr(f->f_fp);
+ /* When in non-blocking mode, data shouldn't
+ * be discarded if a blocking signal was
+ * received. That will also happen if
+ * chunksize != 0, but bytesread < buffersize. */
+ if (bytesread > 0 && BLOCKED_ERRNO(errno))
+ break;
+ PyErr_SetFromErrno(PyExc_IOError);
+ Py_DECREF(v);
+ return NULL;
+ }
+ bytesread += chunksize;
+ if (bytesread < buffersize) {
+ clearerr(f->f_fp);
+ break;
+ }
+ if (bytesrequested < 0) {
+ buffersize = new_buffersize(f, buffersize);
+ if (_PyString_Resize(&v, buffersize) < 0)
+ return NULL;
+ } else {
+ /* Got what was requested. */
+ break;
+ }
+ }
+ if (bytesread != buffersize && _PyString_Resize(&v, bytesread))
+ return NULL;
+ return v;
}
static PyObject *
file_readinto(PyFileObject *f, PyObject *args)
{
- char *ptr;
- Py_ssize_t ntodo;
- Py_ssize_t ndone, nnow;
- Py_buffer pbuf;
-
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->readable)
- return err_mode("reading");
- /* refuse to mix with f.next() */
- if (f->f_buf != NULL &&
- (f->f_bufend - f->f_bufptr) > 0 &&
- f->f_buf[0] != '\0')
- return err_iterbuffered();
- if (!PyArg_ParseTuple(args, "w*", &pbuf))
- return NULL;
- ptr = pbuf.buf;
- ntodo = pbuf.len;
- ndone = 0;
- while (ntodo > 0) {
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
- (PyObject *)f);
- FILE_END_ALLOW_THREADS(f)
- if (nnow == 0) {
- if (!ferror(f->f_fp))
- break;
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- PyBuffer_Release(&pbuf);
- return NULL;
- }
- ndone += nnow;
- ntodo -= nnow;
- }
- PyBuffer_Release(&pbuf);
- return PyInt_FromSsize_t(ndone);
+ char *ptr;
+ Py_ssize_t ntodo;
+ Py_ssize_t ndone, nnow;
+ Py_buffer pbuf;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->readable)
+ return err_mode("reading");
+ /* refuse to mix with f.next() */
+ if (f->f_buf != NULL &&
+ (f->f_bufend - f->f_bufptr) > 0 &&
+ f->f_buf[0] != '\0')
+ return err_iterbuffered();
+ if (!PyArg_ParseTuple(args, "w*", &pbuf))
+ return NULL;
+ ptr = pbuf.buf;
+ ntodo = pbuf.len;
+ ndone = 0;
+ while (ntodo > 0) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ nnow = Py_UniversalNewlineFread(ptr+ndone, ntodo, f->f_fp,
+ (PyObject *)f);
+ FILE_END_ALLOW_THREADS(f)
+ if (nnow == 0) {
+ if (!ferror(f->f_fp))
+ break;
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ PyBuffer_Release(&pbuf);
+ return NULL;
+ }
+ ndone += nnow;
+ ntodo -= nnow;
+ }
+ PyBuffer_Release(&pbuf);
+ return PyInt_FromSsize_t(ndone);
}
/**************************************************************************
@@ -1169,9 +1169,9 @@ MS realloc is also slow.
Reports from other platforms on this method vs getc_unlocked (which MS doesn't
have):
- Linux a wash
- Solaris a wash
- Tru64 Unix getline_via_fgets significantly faster
+ Linux a wash
+ Solaris a wash
+ Tru64 Unix getline_via_fgets significantly faster
CAUTION: The C std isn't clear about this: in those cases where fgets
writes something into the buffer, can it write into any position beyond the
@@ -1218,151 +1218,151 @@ getline_via_fgets(PyFileObject *f, FILE *fp)
*/
#define INITBUFSIZE 100
#define MAXBUFSIZE 300
- char* p; /* temp */
- char buf[MAXBUFSIZE];
- PyObject* v; /* the string object result */
- char* pvfree; /* address of next free slot */
- char* pvend; /* address one beyond last free slot */
- size_t nfree; /* # of free buffer slots; pvend-pvfree */
- size_t total_v_size; /* total # of slots in buffer */
- size_t increment; /* amount to increment the buffer */
- size_t prev_v_size;
-
- /* Optimize for normal case: avoid _PyString_Resize if at all
- * possible via first reading into stack buffer "buf".
- */
- total_v_size = INITBUFSIZE; /* start small and pray */
- pvfree = buf;
- for (;;) {
- FILE_BEGIN_ALLOW_THREADS(f)
- pvend = buf + total_v_size;
- nfree = pvend - pvfree;
- memset(pvfree, '\n', nfree);
- assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
- p = fgets(pvfree, (int)nfree, fp);
- FILE_END_ALLOW_THREADS(f)
-
- if (p == NULL) {
- clearerr(fp);
- if (PyErr_CheckSignals())
- return NULL;
- v = PyString_FromStringAndSize(buf, pvfree - buf);
- return v;
- }
- /* fgets read *something* */
- p = memchr(pvfree, '\n', nfree);
- if (p != NULL) {
- /* Did the \n come from fgets or from us?
- * Since fgets stops at the first \n, and then writes
- * \0, if it's from fgets a \0 must be next. But if
- * that's so, it could not have come from us, since
- * the \n's we filled the buffer with have only more
- * \n's to the right.
- */
- if (p+1 < pvend && *(p+1) == '\0') {
- /* It's from fgets: we win! In particular,
- * we haven't done any mallocs yet, and can
- * build the final result on the first try.
- */
- ++p; /* include \n from fgets */
- }
- else {
- /* Must be from us: fgets didn't fill the
- * buffer and didn't find a newline, so it
- * must be the last and newline-free line of
- * the file.
- */
- assert(p > pvfree && *(p-1) == '\0');
- --p; /* don't include \0 from fgets */
- }
- v = PyString_FromStringAndSize(buf, p - buf);
- return v;
- }
- /* yuck: fgets overwrote all the newlines, i.e. the entire
- * buffer. So this line isn't over yet, or maybe it is but
- * we're exactly at EOF. If we haven't already, try using the
- * rest of the stack buffer.
- */
- assert(*(pvend-1) == '\0');
- if (pvfree == buf) {
- pvfree = pvend - 1; /* overwrite trailing null */
- total_v_size = MAXBUFSIZE;
- }
- else
- break;
- }
-
- /* The stack buffer isn't big enough; malloc a string object and read
- * into its buffer.
- */
- total_v_size = MAXBUFSIZE << 1;
- v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
- if (v == NULL)
- return v;
- /* copy over everything except the last null byte */
- memcpy(BUF(v), buf, MAXBUFSIZE-1);
- pvfree = BUF(v) + MAXBUFSIZE - 1;
-
- /* Keep reading stuff into v; if it ever ends successfully, break
- * after setting p one beyond the end of the line. The code here is
- * very much like the code above, except reads into v's buffer; see
- * the code above for detailed comments about the logic.
- */
- for (;;) {
- FILE_BEGIN_ALLOW_THREADS(f)
- pvend = BUF(v) + total_v_size;
- nfree = pvend - pvfree;
- memset(pvfree, '\n', nfree);
- assert(nfree < INT_MAX);
- p = fgets(pvfree, (int)nfree, fp);
- FILE_END_ALLOW_THREADS(f)
-
- if (p == NULL) {
- clearerr(fp);
- if (PyErr_CheckSignals()) {
- Py_DECREF(v);
- return NULL;
- }
- p = pvfree;
- break;
- }
- p = memchr(pvfree, '\n', nfree);
- if (p != NULL) {
- if (p+1 < pvend && *(p+1) == '\0') {
- /* \n came from fgets */
- ++p;
- break;
- }
- /* \n came from us; last line of file, no newline */
- assert(p > pvfree && *(p-1) == '\0');
- --p;
- break;
- }
- /* expand buffer and try again */
- assert(*(pvend-1) == '\0');
- increment = total_v_size >> 2; /* mild exponential growth */
- prev_v_size = total_v_size;
- total_v_size += increment;
- /* check for overflow */
- if (total_v_size <= prev_v_size ||
- total_v_size > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- Py_DECREF(v);
- return NULL;
- }
- if (_PyString_Resize(&v, (int)total_v_size) < 0)
- return NULL;
- /* overwrite the trailing null byte */
- pvfree = BUF(v) + (prev_v_size - 1);
- }
- if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
- return NULL;
- return v;
+ char* p; /* temp */
+ char buf[MAXBUFSIZE];
+ PyObject* v; /* the string object result */
+ char* pvfree; /* address of next free slot */
+ char* pvend; /* address one beyond last free slot */
+ size_t nfree; /* # of free buffer slots; pvend-pvfree */
+ size_t total_v_size; /* total # of slots in buffer */
+ size_t increment; /* amount to increment the buffer */
+ size_t prev_v_size;
+
+ /* Optimize for normal case: avoid _PyString_Resize if at all
+ * possible via first reading into stack buffer "buf".
+ */
+ total_v_size = INITBUFSIZE; /* start small and pray */
+ pvfree = buf;
+ for (;;) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ pvend = buf + total_v_size;
+ nfree = pvend - pvfree;
+ memset(pvfree, '\n', nfree);
+ assert(nfree < INT_MAX); /* Should be atmost MAXBUFSIZE */
+ p = fgets(pvfree, (int)nfree, fp);
+ FILE_END_ALLOW_THREADS(f)
+
+ if (p == NULL) {
+ clearerr(fp);
+ if (PyErr_CheckSignals())
+ return NULL;
+ v = PyString_FromStringAndSize(buf, pvfree - buf);
+ return v;
+ }
+ /* fgets read *something* */
+ p = memchr(pvfree, '\n', nfree);
+ if (p != NULL) {
+ /* Did the \n come from fgets or from us?
+ * Since fgets stops at the first \n, and then writes
+ * \0, if it's from fgets a \0 must be next. But if
+ * that's so, it could not have come from us, since
+ * the \n's we filled the buffer with have only more
+ * \n's to the right.
+ */
+ if (p+1 < pvend && *(p+1) == '\0') {
+ /* It's from fgets: we win! In particular,
+ * we haven't done any mallocs yet, and can
+ * build the final result on the first try.
+ */
+ ++p; /* include \n from fgets */
+ }
+ else {
+ /* Must be from us: fgets didn't fill the
+ * buffer and didn't find a newline, so it
+ * must be the last and newline-free line of
+ * the file.
+ */
+ assert(p > pvfree && *(p-1) == '\0');
+ --p; /* don't include \0 from fgets */
+ }
+ v = PyString_FromStringAndSize(buf, p - buf);
+ return v;
+ }
+ /* yuck: fgets overwrote all the newlines, i.e. the entire
+ * buffer. So this line isn't over yet, or maybe it is but
+ * we're exactly at EOF. If we haven't already, try using the
+ * rest of the stack buffer.
+ */
+ assert(*(pvend-1) == '\0');
+ if (pvfree == buf) {
+ pvfree = pvend - 1; /* overwrite trailing null */
+ total_v_size = MAXBUFSIZE;
+ }
+ else
+ break;
+ }
+
+ /* The stack buffer isn't big enough; malloc a string object and read
+ * into its buffer.
+ */
+ total_v_size = MAXBUFSIZE << 1;
+ v = PyString_FromStringAndSize((char*)NULL, (int)total_v_size);
+ if (v == NULL)
+ return v;
+ /* copy over everything except the last null byte */
+ memcpy(BUF(v), buf, MAXBUFSIZE-1);
+ pvfree = BUF(v) + MAXBUFSIZE - 1;
+
+ /* Keep reading stuff into v; if it ever ends successfully, break
+ * after setting p one beyond the end of the line. The code here is
+ * very much like the code above, except reads into v's buffer; see
+ * the code above for detailed comments about the logic.
+ */
+ for (;;) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ pvend = BUF(v) + total_v_size;
+ nfree = pvend - pvfree;
+ memset(pvfree, '\n', nfree);
+ assert(nfree < INT_MAX);
+ p = fgets(pvfree, (int)nfree, fp);
+ FILE_END_ALLOW_THREADS(f)
+
+ if (p == NULL) {
+ clearerr(fp);
+ if (PyErr_CheckSignals()) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ p = pvfree;
+ break;
+ }
+ p = memchr(pvfree, '\n', nfree);
+ if (p != NULL) {
+ if (p+1 < pvend && *(p+1) == '\0') {
+ /* \n came from fgets */
+ ++p;
+ break;
+ }
+ /* \n came from us; last line of file, no newline */
+ assert(p > pvfree && *(p-1) == '\0');
+ --p;
+ break;
+ }
+ /* expand buffer and try again */
+ assert(*(pvend-1) == '\0');
+ increment = total_v_size >> 2; /* mild exponential growth */
+ prev_v_size = total_v_size;
+ total_v_size += increment;
+ /* check for overflow */
+ if (total_v_size <= prev_v_size ||
+ total_v_size > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (_PyString_Resize(&v, (int)total_v_size) < 0)
+ return NULL;
+ /* overwrite the trailing null byte */
+ pvfree = BUF(v) + (prev_v_size - 1);
+ }
+ if (BUF(v) + total_v_size != p && _PyString_Resize(&v, p - BUF(v)))
+ return NULL;
+ return v;
#undef INITBUFSIZE
#undef MAXBUFSIZE
}
-#endif /* ifdef USE_FGETS_IN_GETLINE */
+#endif /* ifdef USE_FGETS_IN_GETLINE */
/* Internal routine to get a line.
Size argument interpretation:
@@ -1373,105 +1373,105 @@ getline_via_fgets(PyFileObject *f, FILE *fp)
static PyObject *
get_line(PyFileObject *f, int n)
{
- FILE *fp = f->f_fp;
- int c;
- char *buf, *end;
- size_t total_v_size; /* total # of slots in buffer */
- size_t used_v_size; /* # used slots in buffer */
- size_t increment; /* amount to increment the buffer */
- PyObject *v;
- int newlinetypes = f->f_newlinetypes;
- int skipnextlf = f->f_skipnextlf;
- int univ_newline = f->f_univ_newline;
+ FILE *fp = f->f_fp;
+ int c;
+ char *buf, *end;
+ size_t total_v_size; /* total # of slots in buffer */
+ size_t used_v_size; /* # used slots in buffer */
+ size_t increment; /* amount to increment the buffer */
+ PyObject *v;
+ int newlinetypes = f->f_newlinetypes;
+ int skipnextlf = f->f_skipnextlf;
+ int univ_newline = f->f_univ_newline;
#if defined(USE_FGETS_IN_GETLINE)
- if (n <= 0 && !univ_newline )
- return getline_via_fgets(f, fp);
+ if (n <= 0 && !univ_newline )
+ return getline_via_fgets(f, fp);
#endif
- total_v_size = n > 0 ? n : 100;
- v = PyString_FromStringAndSize((char *)NULL, total_v_size);
- if (v == NULL)
- return NULL;
- buf = BUF(v);
- end = buf + total_v_size;
-
- for (;;) {
- FILE_BEGIN_ALLOW_THREADS(f)
- FLOCKFILE(fp);
- if (univ_newline) {
- c = 'x'; /* Shut up gcc warning */
- while ( buf != end && (c = GETC(fp)) != EOF ) {
- if (skipnextlf ) {
- skipnextlf = 0;
- if (c == '\n') {
- /* Seeing a \n here with
- * skipnextlf true means we
- * saw a \r before.
- */
- newlinetypes |= NEWLINE_CRLF;
- c = GETC(fp);
- if (c == EOF) break;
- } else {
- newlinetypes |= NEWLINE_CR;
- }
- }
- if (c == '\r') {
- skipnextlf = 1;
- c = '\n';
- } else if ( c == '\n')
- newlinetypes |= NEWLINE_LF;
- *buf++ = c;
- if (c == '\n') break;
- }
- if ( c == EOF && skipnextlf )
- newlinetypes |= NEWLINE_CR;
- } else /* If not universal newlines use the normal loop */
- while ((c = GETC(fp)) != EOF &&
- (*buf++ = c) != '\n' &&
- buf != end)
- ;
- FUNLOCKFILE(fp);
- FILE_END_ALLOW_THREADS(f)
- f->f_newlinetypes = newlinetypes;
- f->f_skipnextlf = skipnextlf;
- if (c == '\n')
- break;
- if (c == EOF) {
- if (ferror(fp)) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(fp);
- Py_DECREF(v);
- return NULL;
- }
- clearerr(fp);
- if (PyErr_CheckSignals()) {
- Py_DECREF(v);
- return NULL;
- }
- break;
- }
- /* Must be because buf == end */
- if (n > 0)
- break;
- used_v_size = total_v_size;
- increment = total_v_size >> 2; /* mild exponential growth */
- total_v_size += increment;
- if (total_v_size > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- Py_DECREF(v);
- return NULL;
- }
- if (_PyString_Resize(&v, total_v_size) < 0)
- return NULL;
- buf = BUF(v) + used_v_size;
- end = BUF(v) + total_v_size;
- }
-
- used_v_size = buf - BUF(v);
- if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
- return NULL;
- return v;
+ total_v_size = n > 0 ? n : 100;
+ v = PyString_FromStringAndSize((char *)NULL, total_v_size);
+ if (v == NULL)
+ return NULL;
+ buf = BUF(v);
+ end = buf + total_v_size;
+
+ for (;;) {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ FLOCKFILE(fp);
+ if (univ_newline) {
+ c = 'x'; /* Shut up gcc warning */
+ while ( buf != end && (c = GETC(fp)) != EOF ) {
+ if (skipnextlf ) {
+ skipnextlf = 0;
+ if (c == '\n') {
+ /* Seeing a \n here with
+ * skipnextlf true means we
+ * saw a \r before.
+ */
+ newlinetypes |= NEWLINE_CRLF;
+ c = GETC(fp);
+ if (c == EOF) break;
+ } else {
+ newlinetypes |= NEWLINE_CR;
+ }
+ }
+ if (c == '\r') {
+ skipnextlf = 1;
+ c = '\n';
+ } else if ( c == '\n')
+ newlinetypes |= NEWLINE_LF;
+ *buf++ = c;
+ if (c == '\n') break;
+ }
+ if ( c == EOF && skipnextlf )
+ newlinetypes |= NEWLINE_CR;
+ } else /* If not universal newlines use the normal loop */
+ while ((c = GETC(fp)) != EOF &&
+ (*buf++ = c) != '\n' &&
+ buf != end)
+ ;
+ FUNLOCKFILE(fp);
+ FILE_END_ALLOW_THREADS(f)
+ f->f_newlinetypes = newlinetypes;
+ f->f_skipnextlf = skipnextlf;
+ if (c == '\n')
+ break;
+ if (c == EOF) {
+ if (ferror(fp)) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(fp);
+ Py_DECREF(v);
+ return NULL;
+ }
+ clearerr(fp);
+ if (PyErr_CheckSignals()) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ break;
+ }
+ /* Must be because buf == end */
+ if (n > 0)
+ break;
+ used_v_size = total_v_size;
+ increment = total_v_size >> 2; /* mild exponential growth */
+ total_v_size += increment;
+ if (total_v_size > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (_PyString_Resize(&v, total_v_size) < 0)
+ return NULL;
+ buf = BUF(v) + used_v_size;
+ end = BUF(v) + total_v_size;
+ }
+
+ used_v_size = buf - BUF(v);
+ if (used_v_size != total_v_size && _PyString_Resize(&v, used_v_size))
+ return NULL;
+ return v;
}
/* External C interface */
@@ -1479,98 +1479,98 @@ get_line(PyFileObject *f, int n)
PyObject *
PyFile_GetLine(PyObject *f, int n)
{
- PyObject *result;
-
- if (f == NULL) {
- PyErr_BadInternalCall();
- return NULL;
- }
-
- if (PyFile_Check(f)) {
- PyFileObject *fo = (PyFileObject *)f;
- if (fo->f_fp == NULL)
- return err_closed();
- if (!fo->readable)
- return err_mode("reading");
- /* refuse to mix with f.next() */
- if (fo->f_buf != NULL &&
- (fo->f_bufend - fo->f_bufptr) > 0 &&
- fo->f_buf[0] != '\0')
- return err_iterbuffered();
- result = get_line(fo, n);
- }
- else {
- PyObject *reader;
- PyObject *args;
-
- reader = PyObject_GetAttrString(f, "readline");
- if (reader == NULL)
- return NULL;
- if (n <= 0)
- args = PyTuple_New(0);
- else
- args = Py_BuildValue("(i)", n);
- if (args == NULL) {
- Py_DECREF(reader);
- return NULL;
- }
- result = PyEval_CallObject(reader, args);
- Py_DECREF(reader);
- Py_DECREF(args);
- if (result != NULL && !PyString_Check(result) &&
- !PyUnicode_Check(result)) {
- Py_DECREF(result);
- result = NULL;
- PyErr_SetString(PyExc_TypeError,
- "object.readline() returned non-string");
- }
- }
-
- if (n < 0 && result != NULL && PyString_Check(result)) {
- char *s = PyString_AS_STRING(result);
- Py_ssize_t len = PyString_GET_SIZE(result);
- if (len == 0) {
- Py_DECREF(result);
- result = NULL;
- PyErr_SetString(PyExc_EOFError,
- "EOF when reading a line");
- }
- else if (s[len-1] == '\n') {
- if (result->ob_refcnt == 1) {
- if (_PyString_Resize(&result, len-1))
- return NULL;
- }
- else {
- PyObject *v;
- v = PyString_FromStringAndSize(s, len-1);
- Py_DECREF(result);
- result = v;
- }
- }
- }
+ PyObject *result;
+
+ if (f == NULL) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ if (PyFile_Check(f)) {
+ PyFileObject *fo = (PyFileObject *)f;
+ if (fo->f_fp == NULL)
+ return err_closed();
+ if (!fo->readable)
+ return err_mode("reading");
+ /* refuse to mix with f.next() */
+ if (fo->f_buf != NULL &&
+ (fo->f_bufend - fo->f_bufptr) > 0 &&
+ fo->f_buf[0] != '\0')
+ return err_iterbuffered();
+ result = get_line(fo, n);
+ }
+ else {
+ PyObject *reader;
+ PyObject *args;
+
+ reader = PyObject_GetAttrString(f, "readline");
+ if (reader == NULL)
+ return NULL;
+ if (n <= 0)
+ args = PyTuple_New(0);
+ else
+ args = Py_BuildValue("(i)", n);
+ if (args == NULL) {
+ Py_DECREF(reader);
+ return NULL;
+ }
+ result = PyEval_CallObject(reader, args);
+ Py_DECREF(reader);
+ Py_DECREF(args);
+ if (result != NULL && !PyString_Check(result) &&
+ !PyUnicode_Check(result)) {
+ Py_DECREF(result);
+ result = NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "object.readline() returned non-string");
+ }
+ }
+
+ if (n < 0 && result != NULL && PyString_Check(result)) {
+ char *s = PyString_AS_STRING(result);
+ Py_ssize_t len = PyString_GET_SIZE(result);
+ if (len == 0) {
+ Py_DECREF(result);
+ result = NULL;
+ PyErr_SetString(PyExc_EOFError,
+ "EOF when reading a line");
+ }
+ else if (s[len-1] == '\n') {
+ if (result->ob_refcnt == 1) {
+ if (_PyString_Resize(&result, len-1))
+ return NULL;
+ }
+ else {
+ PyObject *v;
+ v = PyString_FromStringAndSize(s, len-1);
+ Py_DECREF(result);
+ result = v;
+ }
+ }
+ }
#ifdef Py_USING_UNICODE
- if (n < 0 && result != NULL && PyUnicode_Check(result)) {
- Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
- Py_ssize_t len = PyUnicode_GET_SIZE(result);
- if (len == 0) {
- Py_DECREF(result);
- result = NULL;
- PyErr_SetString(PyExc_EOFError,
- "EOF when reading a line");
- }
- else if (s[len-1] == '\n') {
- if (result->ob_refcnt == 1)
- PyUnicode_Resize(&result, len-1);
- else {
- PyObject *v;
- v = PyUnicode_FromUnicode(s, len-1);
- Py_DECREF(result);
- result = v;
- }
- }
- }
+ if (n < 0 && result != NULL && PyUnicode_Check(result)) {
+ Py_UNICODE *s = PyUnicode_AS_UNICODE(result);
+ Py_ssize_t len = PyUnicode_GET_SIZE(result);
+ if (len == 0) {
+ Py_DECREF(result);
+ result = NULL;
+ PyErr_SetString(PyExc_EOFError,
+ "EOF when reading a line");
+ }
+ else if (s[len-1] == '\n') {
+ if (result->ob_refcnt == 1)
+ PyUnicode_Resize(&result, len-1);
+ else {
+ PyObject *v;
+ v = PyUnicode_FromUnicode(s, len-1);
+ Py_DECREF(result);
+ result = v;
+ }
+ }
+ }
#endif
- return result;
+ return result;
}
/* Python method */
@@ -1578,341 +1578,341 @@ PyFile_GetLine(PyObject *f, int n)
static PyObject *
file_readline(PyFileObject *f, PyObject *args)
{
- int n = -1;
-
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->readable)
- return err_mode("reading");
- /* refuse to mix with f.next() */
- if (f->f_buf != NULL &&
- (f->f_bufend - f->f_bufptr) > 0 &&
- f->f_buf[0] != '\0')
- return err_iterbuffered();
- if (!PyArg_ParseTuple(args, "|i:readline", &n))
- return NULL;
- if (n == 0)
- return PyString_FromString("");
- if (n < 0)
- n = 0;
- return get_line(f, n);
+ int n = -1;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->readable)
+ return err_mode("reading");
+ /* refuse to mix with f.next() */
+ if (f->f_buf != NULL &&
+ (f->f_bufend - f->f_bufptr) > 0 &&
+ f->f_buf[0] != '\0')
+ return err_iterbuffered();
+ if (!PyArg_ParseTuple(args, "|i:readline", &n))
+ return NULL;
+ if (n == 0)
+ return PyString_FromString("");
+ if (n < 0)
+ n = 0;
+ return get_line(f, n);
}
static PyObject *
file_readlines(PyFileObject *f, PyObject *args)
{
- long sizehint = 0;
- PyObject *list = NULL;
- PyObject *line;
- char small_buffer[SMALLCHUNK];
- char *buffer = small_buffer;
- size_t buffersize = SMALLCHUNK;
- PyObject *big_buffer = NULL;
- size_t nfilled = 0;
- size_t nread;
- size_t totalread = 0;
- char *p, *q, *end;
- int err;
- int shortread = 0;
-
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->readable)
- return err_mode("reading");
- /* refuse to mix with f.next() */
- if (f->f_buf != NULL &&
- (f->f_bufend - f->f_bufptr) > 0 &&
- f->f_buf[0] != '\0')
- return err_iterbuffered();
- if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
- return NULL;
- if ((list = PyList_New(0)) == NULL)
- return NULL;
- for (;;) {
- if (shortread)
- nread = 0;
- else {
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- nread = Py_UniversalNewlineFread(buffer+nfilled,
- buffersize-nfilled, f->f_fp, (PyObject *)f);
- FILE_END_ALLOW_THREADS(f)
- shortread = (nread < buffersize-nfilled);
- }
- if (nread == 0) {
- sizehint = 0;
- if (!ferror(f->f_fp))
- break;
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- goto error;
- }
- totalread += nread;
- p = (char *)memchr(buffer+nfilled, '\n', nread);
- if (p == NULL) {
- /* Need a larger buffer to fit this line */
- nfilled += nread;
- buffersize *= 2;
- if (buffersize > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "line is longer than a Python string can hold");
- goto error;
- }
- if (big_buffer == NULL) {
- /* Create the big buffer */
- big_buffer = PyString_FromStringAndSize(
- NULL, buffersize);
- if (big_buffer == NULL)
- goto error;
- buffer = PyString_AS_STRING(big_buffer);
- memcpy(buffer, small_buffer, nfilled);
- }
- else {
- /* Grow the big buffer */
- if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
- goto error;
- buffer = PyString_AS_STRING(big_buffer);
- }
- continue;
- }
- end = buffer+nfilled+nread;
- q = buffer;
- do {
- /* Process complete lines */
- p++;
- line = PyString_FromStringAndSize(q, p-q);
- if (line == NULL)
- goto error;
- err = PyList_Append(list, line);
- Py_DECREF(line);
- if (err != 0)
- goto error;
- q = p;
- p = (char *)memchr(q, '\n', end-q);
- } while (p != NULL);
- /* Move the remaining incomplete line to the start */
- nfilled = end-q;
- memmove(buffer, q, nfilled);
- if (sizehint > 0)
- if (totalread >= (size_t)sizehint)
- break;
- }
- if (nfilled != 0) {
- /* Partial last line */
- line = PyString_FromStringAndSize(buffer, nfilled);
- if (line == NULL)
- goto error;
- if (sizehint > 0) {
- /* Need to complete the last line */
- PyObject *rest = get_line(f, 0);
- if (rest == NULL) {
- Py_DECREF(line);
- goto error;
- }
- PyString_Concat(&line, rest);
- Py_DECREF(rest);
- if (line == NULL)
- goto error;
- }
- err = PyList_Append(list, line);
- Py_DECREF(line);
- if (err != 0)
- goto error;
- }
+ long sizehint = 0;
+ PyObject *list = NULL;
+ PyObject *line;
+ char small_buffer[SMALLCHUNK];
+ char *buffer = small_buffer;
+ size_t buffersize = SMALLCHUNK;
+ PyObject *big_buffer = NULL;
+ size_t nfilled = 0;
+ size_t nread;
+ size_t totalread = 0;
+ char *p, *q, *end;
+ int err;
+ int shortread = 0;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->readable)
+ return err_mode("reading");
+ /* refuse to mix with f.next() */
+ if (f->f_buf != NULL &&
+ (f->f_bufend - f->f_bufptr) > 0 &&
+ f->f_buf[0] != '\0')
+ return err_iterbuffered();
+ if (!PyArg_ParseTuple(args, "|l:readlines", &sizehint))
+ return NULL;
+ if ((list = PyList_New(0)) == NULL)
+ return NULL;
+ for (;;) {
+ if (shortread)
+ nread = 0;
+ else {
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ nread = Py_UniversalNewlineFread(buffer+nfilled,
+ buffersize-nfilled, f->f_fp, (PyObject *)f);
+ FILE_END_ALLOW_THREADS(f)
+ shortread = (nread < buffersize-nfilled);
+ }
+ if (nread == 0) {
+ sizehint = 0;
+ if (!ferror(f->f_fp))
+ break;
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ goto error;
+ }
+ totalread += nread;
+ p = (char *)memchr(buffer+nfilled, '\n', nread);
+ if (p == NULL) {
+ /* Need a larger buffer to fit this line */
+ nfilled += nread;
+ buffersize *= 2;
+ if (buffersize > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "line is longer than a Python string can hold");
+ goto error;
+ }
+ if (big_buffer == NULL) {
+ /* Create the big buffer */
+ big_buffer = PyString_FromStringAndSize(
+ NULL, buffersize);
+ if (big_buffer == NULL)
+ goto error;
+ buffer = PyString_AS_STRING(big_buffer);
+ memcpy(buffer, small_buffer, nfilled);
+ }
+ else {
+ /* Grow the big buffer */
+ if ( _PyString_Resize(&big_buffer, buffersize) < 0 )
+ goto error;
+ buffer = PyString_AS_STRING(big_buffer);
+ }
+ continue;
+ }
+ end = buffer+nfilled+nread;
+ q = buffer;
+ do {
+ /* Process complete lines */
+ p++;
+ line = PyString_FromStringAndSize(q, p-q);
+ if (line == NULL)
+ goto error;
+ err = PyList_Append(list, line);
+ Py_DECREF(line);
+ if (err != 0)
+ goto error;
+ q = p;
+ p = (char *)memchr(q, '\n', end-q);
+ } while (p != NULL);
+ /* Move the remaining incomplete line to the start */
+ nfilled = end-q;
+ memmove(buffer, q, nfilled);
+ if (sizehint > 0)
+ if (totalread >= (size_t)sizehint)
+ break;
+ }
+ if (nfilled != 0) {
+ /* Partial last line */
+ line = PyString_FromStringAndSize(buffer, nfilled);
+ if (line == NULL)
+ goto error;
+ if (sizehint > 0) {
+ /* Need to complete the last line */
+ PyObject *rest = get_line(f, 0);
+ if (rest == NULL) {
+ Py_DECREF(line);
+ goto error;
+ }
+ PyString_Concat(&line, rest);
+ Py_DECREF(rest);
+ if (line == NULL)
+ goto error;
+ }
+ err = PyList_Append(list, line);
+ Py_DECREF(line);
+ if (err != 0)
+ goto error;
+ }
cleanup:
- Py_XDECREF(big_buffer);
- return list;
+ Py_XDECREF(big_buffer);
+ return list;
error:
- Py_CLEAR(list);
- goto cleanup;
+ Py_CLEAR(list);
+ goto cleanup;
}
static PyObject *
file_write(PyFileObject *f, PyObject *args)
{
- Py_buffer pbuf;
- char *s;
- Py_ssize_t n, n2;
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->writable)
- return err_mode("writing");
- if (f->f_binary) {
- if (!PyArg_ParseTuple(args, "s*", &pbuf))
- return NULL;
- s = pbuf.buf;
- n = pbuf.len;
- } else
- if (!PyArg_ParseTuple(args, "t#", &s, &n))
- return NULL;
- f->f_softspace = 0;
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- n2 = fwrite(s, 1, n, f->f_fp);
- FILE_END_ALLOW_THREADS(f)
- if (f->f_binary)
- PyBuffer_Release(&pbuf);
- if (n2 != n) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ Py_buffer pbuf;
+ char *s;
+ Py_ssize_t n, n2;
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->writable)
+ return err_mode("writing");
+ if (f->f_binary) {
+ if (!PyArg_ParseTuple(args, "s*", &pbuf))
+ return NULL;
+ s = pbuf.buf;
+ n = pbuf.len;
+ } else
+ if (!PyArg_ParseTuple(args, "t#", &s, &n))
+ return NULL;
+ f->f_softspace = 0;
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ n2 = fwrite(s, 1, n, f->f_fp);
+ FILE_END_ALLOW_THREADS(f)
+ if (f->f_binary)
+ PyBuffer_Release(&pbuf);
+ if (n2 != n) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
file_writelines(PyFileObject *f, PyObject *seq)
{
#define CHUNKSIZE 1000
- PyObject *list, *line;
- PyObject *it; /* iter(seq) */
- PyObject *result;
- int index, islist;
- Py_ssize_t i, j, nwritten, len;
-
- assert(seq != NULL);
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->writable)
- return err_mode("writing");
-
- result = NULL;
- list = NULL;
- islist = PyList_Check(seq);
- if (islist)
- it = NULL;
- else {
- it = PyObject_GetIter(seq);
- if (it == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "writelines() requires an iterable argument");
- return NULL;
- }
- /* From here on, fail by going to error, to reclaim "it". */
- list = PyList_New(CHUNKSIZE);
- if (list == NULL)
- goto error;
- }
-
- /* Strategy: slurp CHUNKSIZE lines into a private list,
- checking that they are all strings, then write that list
- without holding the interpreter lock, then come back for more. */
- for (index = 0; ; index += CHUNKSIZE) {
- if (islist) {
- Py_XDECREF(list);
- list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
- if (list == NULL)
- goto error;
- j = PyList_GET_SIZE(list);
- }
- else {
- for (j = 0; j < CHUNKSIZE; j++) {
- line = PyIter_Next(it);
- if (line == NULL) {
- if (PyErr_Occurred())
- goto error;
- break;
- }
- PyList_SetItem(list, j, line);
- }
- }
- if (j == 0)
- break;
-
- /* Check that all entries are indeed strings. If not,
- apply the same rules as for file.write() and
- convert the results to strings. This is slow, but
- seems to be the only way since all conversion APIs
- could potentially execute Python code. */
- for (i = 0; i < j; i++) {
- PyObject *v = PyList_GET_ITEM(list, i);
- if (!PyString_Check(v)) {
- const char *buffer;
- if (((f->f_binary &&
- PyObject_AsReadBuffer(v,
- (const void**)&buffer,
- &len)) ||
- PyObject_AsCharBuffer(v,
- &buffer,
- &len))) {
- PyErr_SetString(PyExc_TypeError,
- "writelines() argument must be a sequence of strings");
- goto error;
- }
- line = PyString_FromStringAndSize(buffer,
- len);
- if (line == NULL)
- goto error;
- Py_DECREF(v);
- PyList_SET_ITEM(list, i, line);
- }
- }
-
- /* Since we are releasing the global lock, the
- following code may *not* execute Python code. */
- f->f_softspace = 0;
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- for (i = 0; i < j; i++) {
- line = PyList_GET_ITEM(list, i);
- len = PyString_GET_SIZE(line);
- nwritten = fwrite(PyString_AS_STRING(line),
- 1, len, f->f_fp);
- if (nwritten != len) {
- FILE_ABORT_ALLOW_THREADS(f)
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- goto error;
- }
- }
- FILE_END_ALLOW_THREADS(f)
-
- if (j < CHUNKSIZE)
- break;
- }
-
- Py_INCREF(Py_None);
- result = Py_None;
+ PyObject *list, *line;
+ PyObject *it; /* iter(seq) */
+ PyObject *result;
+ int index, islist;
+ Py_ssize_t i, j, nwritten, len;
+
+ assert(seq != NULL);
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->writable)
+ return err_mode("writing");
+
+ result = NULL;
+ list = NULL;
+ islist = PyList_Check(seq);
+ if (islist)
+ it = NULL;
+ else {
+ it = PyObject_GetIter(seq);
+ if (it == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "writelines() requires an iterable argument");
+ return NULL;
+ }
+ /* From here on, fail by going to error, to reclaim "it". */
+ list = PyList_New(CHUNKSIZE);
+ if (list == NULL)
+ goto error;
+ }
+
+ /* Strategy: slurp CHUNKSIZE lines into a private list,
+ checking that they are all strings, then write that list
+ without holding the interpreter lock, then come back for more. */
+ for (index = 0; ; index += CHUNKSIZE) {
+ if (islist) {
+ Py_XDECREF(list);
+ list = PyList_GetSlice(seq, index, index+CHUNKSIZE);
+ if (list == NULL)
+ goto error;
+ j = PyList_GET_SIZE(list);
+ }
+ else {
+ for (j = 0; j < CHUNKSIZE; j++) {
+ line = PyIter_Next(it);
+ if (line == NULL) {
+ if (PyErr_Occurred())
+ goto error;
+ break;
+ }
+ PyList_SetItem(list, j, line);
+ }
+ }
+ if (j == 0)
+ break;
+
+ /* Check that all entries are indeed strings. If not,
+ apply the same rules as for file.write() and
+ convert the results to strings. This is slow, but
+ seems to be the only way since all conversion APIs
+ could potentially execute Python code. */
+ for (i = 0; i < j; i++) {
+ PyObject *v = PyList_GET_ITEM(list, i);
+ if (!PyString_Check(v)) {
+ const char *buffer;
+ if (((f->f_binary &&
+ PyObject_AsReadBuffer(v,
+ (const void**)&buffer,
+ &len)) ||
+ PyObject_AsCharBuffer(v,
+ &buffer,
+ &len))) {
+ PyErr_SetString(PyExc_TypeError,
+ "writelines() argument must be a sequence of strings");
+ goto error;
+ }
+ line = PyString_FromStringAndSize(buffer,
+ len);
+ if (line == NULL)
+ goto error;
+ Py_DECREF(v);
+ PyList_SET_ITEM(list, i, line);
+ }
+ }
+
+ /* Since we are releasing the global lock, the
+ following code may *not* execute Python code. */
+ f->f_softspace = 0;
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ for (i = 0; i < j; i++) {
+ line = PyList_GET_ITEM(list, i);
+ len = PyString_GET_SIZE(line);
+ nwritten = fwrite(PyString_AS_STRING(line),
+ 1, len, f->f_fp);
+ if (nwritten != len) {
+ FILE_ABORT_ALLOW_THREADS(f)
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ goto error;
+ }
+ }
+ FILE_END_ALLOW_THREADS(f)
+
+ if (j < CHUNKSIZE)
+ break;
+ }
+
+ Py_INCREF(Py_None);
+ result = Py_None;
error:
- Py_XDECREF(list);
- Py_XDECREF(it);
- return result;
+ Py_XDECREF(list);
+ Py_XDECREF(it);
+ return result;
#undef CHUNKSIZE
}
static PyObject *
file_self(PyFileObject *f)
{
- if (f->f_fp == NULL)
- return err_closed();
- Py_INCREF(f);
- return (PyObject *)f;
+ if (f->f_fp == NULL)
+ return err_closed();
+ Py_INCREF(f);
+ return (PyObject *)f;
}
static PyObject *
file_xreadlines(PyFileObject *f)
{
- if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
- "try 'for line in f' instead", 1) < 0)
- return NULL;
- return file_self(f);
+ if (PyErr_WarnPy3k("f.xreadlines() not supported in 3.x, "
+ "try 'for line in f' instead", 1) < 0)
+ return NULL;
+ return file_self(f);
}
static PyObject *
file_exit(PyObject *f, PyObject *args)
{
- PyObject *ret = PyObject_CallMethod(f, "close", NULL);
- if (!ret)
- /* If error occurred, pass through */
- return NULL;
- Py_DECREF(ret);
- /* We cannot return the result of close since a true
- * value will be interpreted as "yes, swallow the
- * exception if one was raised inside the with block". */
- Py_RETURN_NONE;
+ PyObject *ret = PyObject_CallMethod(f, "close", NULL);
+ if (!ret)
+ /* If error occurred, pass through */
+ return NULL;
+ Py_DECREF(ret);
+ /* We cannot return the result of close since a true
+ * value will be interpreted as "yes, swallow the
+ * exception if one was raised inside the with block". */
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(readline_doc,
@@ -2000,126 +2000,126 @@ PyDoc_STRVAR(isatty_doc,
"isatty() -> true or false. True if the file is connected to a tty device.");
PyDoc_STRVAR(enter_doc,
- "__enter__() -> self.");
+ "__enter__() -> self.");
PyDoc_STRVAR(exit_doc,
- "__exit__(*excinfo) -> None. Closes the file.");
+ "__exit__(*excinfo) -> None. Closes the file.");
static PyMethodDef file_methods[] = {
- {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
- {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
- {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
- {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
- {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
+ {"readline", (PyCFunction)file_readline, METH_VARARGS, readline_doc},
+ {"read", (PyCFunction)file_read, METH_VARARGS, read_doc},
+ {"write", (PyCFunction)file_write, METH_VARARGS, write_doc},
+ {"fileno", (PyCFunction)file_fileno, METH_NOARGS, fileno_doc},
+ {"seek", (PyCFunction)file_seek, METH_VARARGS, seek_doc},
#ifdef HAVE_FTRUNCATE
- {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
+ {"truncate", (PyCFunction)file_truncate, METH_VARARGS, truncate_doc},
#endif
- {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
- {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
- {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
- {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
- {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
- {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
- {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
- {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
- {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
- {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
- {NULL, NULL} /* sentinel */
+ {"tell", (PyCFunction)file_tell, METH_NOARGS, tell_doc},
+ {"readinto", (PyCFunction)file_readinto, METH_VARARGS, readinto_doc},
+ {"readlines", (PyCFunction)file_readlines, METH_VARARGS, readlines_doc},
+ {"xreadlines",(PyCFunction)file_xreadlines, METH_NOARGS, xreadlines_doc},
+ {"writelines",(PyCFunction)file_writelines, METH_O, writelines_doc},
+ {"flush", (PyCFunction)file_flush, METH_NOARGS, flush_doc},
+ {"close", (PyCFunction)file_close, METH_NOARGS, close_doc},
+ {"isatty", (PyCFunction)file_isatty, METH_NOARGS, isatty_doc},
+ {"__enter__", (PyCFunction)file_self, METH_NOARGS, enter_doc},
+ {"__exit__", (PyCFunction)file_exit, METH_VARARGS, exit_doc},
+ {NULL, NULL} /* sentinel */
};
#define OFF(x) offsetof(PyFileObject, x)
static PyMemberDef file_memberlist[] = {
- {"mode", T_OBJECT, OFF(f_mode), RO,
- "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
- {"name", T_OBJECT, OFF(f_name), RO,
- "file name"},
- {"encoding", T_OBJECT, OFF(f_encoding), RO,
- "file encoding"},
- {"errors", T_OBJECT, OFF(f_errors), RO,
- "Unicode error handler"},
- /* getattr(f, "closed") is implemented without this table */
- {NULL} /* Sentinel */
+ {"mode", T_OBJECT, OFF(f_mode), RO,
+ "file mode ('r', 'U', 'w', 'a', possibly with 'b' or '+' added)"},
+ {"name", T_OBJECT, OFF(f_name), RO,
+ "file name"},
+ {"encoding", T_OBJECT, OFF(f_encoding), RO,
+ "file encoding"},
+ {"errors", T_OBJECT, OFF(f_errors), RO,
+ "Unicode error handler"},
+ /* getattr(f, "closed") is implemented without this table */
+ {NULL} /* Sentinel */
};
static PyObject *
get_closed(PyFileObject *f, void *closure)
{
- return PyBool_FromLong((long)(f->f_fp == 0));
+ return PyBool_FromLong((long)(f->f_fp == 0));
}
static PyObject *
get_newlines(PyFileObject *f, void *closure)
{
- switch (f->f_newlinetypes) {
- case NEWLINE_UNKNOWN:
- Py_INCREF(Py_None);
- return Py_None;
- case NEWLINE_CR:
- return PyString_FromString("\r");
- case NEWLINE_LF:
- return PyString_FromString("\n");
- case NEWLINE_CR|NEWLINE_LF:
- return Py_BuildValue("(ss)", "\r", "\n");
- case NEWLINE_CRLF:
- return PyString_FromString("\r\n");
- case NEWLINE_CR|NEWLINE_CRLF:
- return Py_BuildValue("(ss)", "\r", "\r\n");
- case NEWLINE_LF|NEWLINE_CRLF:
- return Py_BuildValue("(ss)", "\n", "\r\n");
- case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
- return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
- default:
- PyErr_Format(PyExc_SystemError,
- "Unknown newlines value 0x%x\n",
- f->f_newlinetypes);
- return NULL;
- }
+ switch (f->f_newlinetypes) {
+ case NEWLINE_UNKNOWN:
+ Py_INCREF(Py_None);
+ return Py_None;
+ case NEWLINE_CR:
+ return PyString_FromString("\r");
+ case NEWLINE_LF:
+ return PyString_FromString("\n");
+ case NEWLINE_CR|NEWLINE_LF:
+ return Py_BuildValue("(ss)", "\r", "\n");
+ case NEWLINE_CRLF:
+ return PyString_FromString("\r\n");
+ case NEWLINE_CR|NEWLINE_CRLF:
+ return Py_BuildValue("(ss)", "\r", "\r\n");
+ case NEWLINE_LF|NEWLINE_CRLF:
+ return Py_BuildValue("(ss)", "\n", "\r\n");
+ case NEWLINE_CR|NEWLINE_LF|NEWLINE_CRLF:
+ return Py_BuildValue("(sss)", "\r", "\n", "\r\n");
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "Unknown newlines value 0x%x\n",
+ f->f_newlinetypes);
+ return NULL;
+ }
}
static PyObject *
get_softspace(PyFileObject *f, void *closure)
{
- if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
- return NULL;
- return PyInt_FromLong(f->f_softspace);
+ if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
+ return NULL;
+ return PyInt_FromLong(f->f_softspace);
}
static int
set_softspace(PyFileObject *f, PyObject *value)
{
- int new;
- if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
- return -1;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete softspace attribute");
- return -1;
- }
-
- new = PyInt_AsLong(value);
- if (new == -1 && PyErr_Occurred())
- return -1;
- f->f_softspace = new;
- return 0;
+ int new;
+ if (PyErr_WarnPy3k("file.softspace not supported in 3.x", 1) < 0)
+ return -1;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete softspace attribute");
+ return -1;
+ }
+
+ new = PyInt_AsLong(value);
+ if (new == -1 && PyErr_Occurred())
+ return -1;
+ f->f_softspace = new;
+ return 0;
}
static PyGetSetDef file_getsetlist[] = {
- {"closed", (getter)get_closed, NULL, "True if the file is closed"},
- {"newlines", (getter)get_newlines, NULL,
- "end-of-line convention used in this file"},
- {"softspace", (getter)get_softspace, (setter)set_softspace,
- "flag indicating that a space needs to be printed; used by print"},
- {0},
+ {"closed", (getter)get_closed, NULL, "True if the file is closed"},
+ {"newlines", (getter)get_newlines, NULL,
+ "end-of-line convention used in this file"},
+ {"softspace", (getter)get_softspace, (setter)set_softspace,
+ "flag indicating that a space needs to be printed; used by print"},
+ {0},
};
static void
drop_readahead(PyFileObject *f)
{
- if (f->f_buf != NULL) {
- PyMem_Free(f->f_buf);
- f->f_buf = NULL;
- }
+ if (f->f_buf != NULL) {
+ PyMem_Free(f->f_buf);
+ f->f_buf = NULL;
+ }
}
/* Make sure that file has a readahead buffer with at least one byte
@@ -2128,34 +2128,34 @@ drop_readahead(PyFileObject *f)
static int
readahead(PyFileObject *f, int bufsize)
{
- Py_ssize_t chunksize;
-
- if (f->f_buf != NULL) {
- if( (f->f_bufend - f->f_bufptr) >= 1)
- return 0;
- else
- drop_readahead(f);
- }
- if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- FILE_BEGIN_ALLOW_THREADS(f)
- errno = 0;
- chunksize = Py_UniversalNewlineFread(
- f->f_buf, bufsize, f->f_fp, (PyObject *)f);
- FILE_END_ALLOW_THREADS(f)
- if (chunksize == 0) {
- if (ferror(f->f_fp)) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(f->f_fp);
- drop_readahead(f);
- return -1;
- }
- }
- f->f_bufptr = f->f_buf;
- f->f_bufend = f->f_buf + chunksize;
- return 0;
+ Py_ssize_t chunksize;
+
+ if (f->f_buf != NULL) {
+ if( (f->f_bufend - f->f_bufptr) >= 1)
+ return 0;
+ else
+ drop_readahead(f);
+ }
+ if ((f->f_buf = (char *)PyMem_Malloc(bufsize)) == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ FILE_BEGIN_ALLOW_THREADS(f)
+ errno = 0;
+ chunksize = Py_UniversalNewlineFread(
+ f->f_buf, bufsize, f->f_fp, (PyObject *)f);
+ FILE_END_ALLOW_THREADS(f)
+ if (chunksize == 0) {
+ if (ferror(f->f_fp)) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(f->f_fp);
+ drop_readahead(f);
+ return -1;
+ }
+ }
+ f->f_bufptr = f->f_buf;
+ f->f_bufend = f->f_buf + chunksize;
+ return 0;
}
/* Used by file_iternext. The returned string will start with 'skip'
@@ -2166,46 +2166,46 @@ readahead(PyFileObject *f, int bufsize)
static PyStringObject *
readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
{
- PyStringObject* s;
- char *bufptr;
- char *buf;
- Py_ssize_t len;
-
- if (f->f_buf == NULL)
- if (readahead(f, bufsize) < 0)
- return NULL;
-
- len = f->f_bufend - f->f_bufptr;
- if (len == 0)
- return (PyStringObject *)
- PyString_FromStringAndSize(NULL, skip);
- bufptr = (char *)memchr(f->f_bufptr, '\n', len);
- if (bufptr != NULL) {
- bufptr++; /* Count the '\n' */
- len = bufptr - f->f_bufptr;
- s = (PyStringObject *)
- PyString_FromStringAndSize(NULL, skip+len);
- if (s == NULL)
- return NULL;
- memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
- f->f_bufptr = bufptr;
- if (bufptr == f->f_bufend)
- drop_readahead(f);
- } else {
- bufptr = f->f_bufptr;
- buf = f->f_buf;
- f->f_buf = NULL; /* Force new readahead buffer */
- assert(skip+len < INT_MAX);
- s = readahead_get_line_skip(
- f, (int)(skip+len), bufsize + (bufsize>>2) );
- if (s == NULL) {
- PyMem_Free(buf);
- return NULL;
- }
- memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
- PyMem_Free(buf);
- }
- return s;
+ PyStringObject* s;
+ char *bufptr;
+ char *buf;
+ Py_ssize_t len;
+
+ if (f->f_buf == NULL)
+ if (readahead(f, bufsize) < 0)
+ return NULL;
+
+ len = f->f_bufend - f->f_bufptr;
+ if (len == 0)
+ return (PyStringObject *)
+ PyString_FromStringAndSize(NULL, skip);
+ bufptr = (char *)memchr(f->f_bufptr, '\n', len);
+ if (bufptr != NULL) {
+ bufptr++; /* Count the '\n' */
+ len = bufptr - f->f_bufptr;
+ s = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, skip+len);
+ if (s == NULL)
+ return NULL;
+ memcpy(PyString_AS_STRING(s)+skip, f->f_bufptr, len);
+ f->f_bufptr = bufptr;
+ if (bufptr == f->f_bufend)
+ drop_readahead(f);
+ } else {
+ bufptr = f->f_bufptr;
+ buf = f->f_buf;
+ f->f_buf = NULL; /* Force new readahead buffer */
+ assert(skip+len < INT_MAX);
+ s = readahead_get_line_skip(
+ f, (int)(skip+len), bufsize + (bufsize>>2) );
+ if (s == NULL) {
+ PyMem_Free(buf);
+ return NULL;
+ }
+ memcpy(PyString_AS_STRING(s)+skip, bufptr, len);
+ PyMem_Free(buf);
+ }
+ return s;
}
/* A larger buffer size may actually decrease performance. */
@@ -2214,122 +2214,122 @@ readahead_get_line_skip(PyFileObject *f, int skip, int bufsize)
static PyObject *
file_iternext(PyFileObject *f)
{
- PyStringObject* l;
-
- if (f->f_fp == NULL)
- return err_closed();
- if (!f->readable)
- return err_mode("reading");
-
- l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
- if (l == NULL || PyString_GET_SIZE(l) == 0) {
- Py_XDECREF(l);
- return NULL;
- }
- return (PyObject *)l;
+ PyStringObject* l;
+
+ if (f->f_fp == NULL)
+ return err_closed();
+ if (!f->readable)
+ return err_mode("reading");
+
+ l = readahead_get_line_skip(f, 0, READAHEAD_BUFSIZE);
+ if (l == NULL || PyString_GET_SIZE(l) == 0) {
+ Py_XDECREF(l);
+ return NULL;
+ }
+ return (PyObject *)l;
}
static PyObject *
file_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *self;
- static PyObject *not_yet_string;
-
- assert(type != NULL && type->tp_alloc != NULL);
-
- if (not_yet_string == NULL) {
- not_yet_string = PyString_InternFromString("<uninitialized file>");
- if (not_yet_string == NULL)
- return NULL;
- }
-
- self = type->tp_alloc(type, 0);
- if (self != NULL) {
- /* Always fill in the name and mode, so that nobody else
- needs to special-case NULLs there. */
- Py_INCREF(not_yet_string);
- ((PyFileObject *)self)->f_name = not_yet_string;
- Py_INCREF(not_yet_string);
- ((PyFileObject *)self)->f_mode = not_yet_string;
- Py_INCREF(Py_None);
- ((PyFileObject *)self)->f_encoding = Py_None;
- Py_INCREF(Py_None);
- ((PyFileObject *)self)->f_errors = Py_None;
- ((PyFileObject *)self)->weakreflist = NULL;
- ((PyFileObject *)self)->unlocked_count = 0;
- }
- return self;
+ PyObject *self;
+ static PyObject *not_yet_string;
+
+ assert(type != NULL && type->tp_alloc != NULL);
+
+ if (not_yet_string == NULL) {
+ not_yet_string = PyString_InternFromString("<uninitialized file>");
+ if (not_yet_string == NULL)
+ return NULL;
+ }
+
+ self = type->tp_alloc(type, 0);
+ if (self != NULL) {
+ /* Always fill in the name and mode, so that nobody else
+ needs to special-case NULLs there. */
+ Py_INCREF(not_yet_string);
+ ((PyFileObject *)self)->f_name = not_yet_string;
+ Py_INCREF(not_yet_string);
+ ((PyFileObject *)self)->f_mode = not_yet_string;
+ Py_INCREF(Py_None);
+ ((PyFileObject *)self)->f_encoding = Py_None;
+ Py_INCREF(Py_None);
+ ((PyFileObject *)self)->f_errors = Py_None;
+ ((PyFileObject *)self)->weakreflist = NULL;
+ ((PyFileObject *)self)->unlocked_count = 0;
+ }
+ return self;
}
static int
file_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyFileObject *foself = (PyFileObject *)self;
- int ret = 0;
- static char *kwlist[] = {"name", "mode", "buffering", 0};
- char *name = NULL;
- char *mode = "r";
- int bufsize = -1;
- int wideargument = 0;
+ PyFileObject *foself = (PyFileObject *)self;
+ int ret = 0;
+ static char *kwlist[] = {"name", "mode", "buffering", 0};
+ char *name = NULL;
+ char *mode = "r";
+ int bufsize = -1;
+ int wideargument = 0;
#ifdef MS_WINDOWS
- PyObject *po;
+ PyObject *po;
#endif
- assert(PyFile_Check(self));
- if (foself->f_fp != NULL) {
- /* Have to close the existing file first. */
- PyObject *closeresult = file_close(foself);
- if (closeresult == NULL)
- return -1;
- Py_DECREF(closeresult);
- }
+ assert(PyFile_Check(self));
+ if (foself->f_fp != NULL) {
+ /* Have to close the existing file first. */
+ PyObject *closeresult = file_close(foself);
+ if (closeresult == NULL)
+ return -1;
+ Py_DECREF(closeresult);
+ }
#ifdef MS_WINDOWS
- if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
- kwlist, &po, &mode, &bufsize)) {
- wideargument = 1;
- if (fill_file_fields(foself, NULL, po, mode,
- fclose) == NULL)
- goto Error;
- } else {
- /* Drop the argument parsing error as narrow
- strings are also valid. */
- PyErr_Clear();
- }
+ if (PyArg_ParseTupleAndKeywords(args, kwds, "U|si:file",
+ kwlist, &po, &mode, &bufsize)) {
+ wideargument = 1;
+ if (fill_file_fields(foself, NULL, po, mode,
+ fclose) == NULL)
+ goto Error;
+ } else {
+ /* Drop the argument parsing error as narrow
+ strings are also valid. */
+ PyErr_Clear();
+ }
#endif
- if (!wideargument) {
- PyObject *o_name;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
- Py_FileSystemDefaultEncoding,
- &name,
- &mode, &bufsize))
- return -1;
-
- /* We parse again to get the name as a PyObject */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
- kwlist, &o_name, &mode,
- &bufsize))
- goto Error;
-
- if (fill_file_fields(foself, NULL, o_name, mode,
- fclose) == NULL)
- goto Error;
- }
- if (open_the_file(foself, name, mode) == NULL)
- goto Error;
- foself->f_setbuf = NULL;
- PyFile_SetBufSize(self, bufsize);
- goto Done;
+ if (!wideargument) {
+ PyObject *o_name;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "et|si:file", kwlist,
+ Py_FileSystemDefaultEncoding,
+ &name,
+ &mode, &bufsize))
+ return -1;
+
+ /* We parse again to get the name as a PyObject */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|si:file",
+ kwlist, &o_name, &mode,
+ &bufsize))
+ goto Error;
+
+ if (fill_file_fields(foself, NULL, o_name, mode,
+ fclose) == NULL)
+ goto Error;
+ }
+ if (open_the_file(foself, name, mode) == NULL)
+ goto Error;
+ foself->f_setbuf = NULL;
+ PyFile_SetBufSize(self, bufsize);
+ goto Done;
Error:
- ret = -1;
- /* fall through */
+ ret = -1;
+ /* fall through */
Done:
- PyMem_Free(name); /* free the encoded string */
- return ret;
+ PyMem_Free(name); /* free the encoded string */
+ return ret;
}
PyDoc_VAR(file_doc) =
@@ -2356,46 +2356,46 @@ PyDoc_STR(
);
PyTypeObject PyFile_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "file",
- sizeof(PyFileObject),
- 0,
- (destructor)file_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)file_repr, /* 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 */
- /* softspace is writable: we must supply tp_setattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
- file_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
- (getiterfunc)file_self, /* tp_iter */
- (iternextfunc)file_iternext, /* tp_iternext */
- file_methods, /* tp_methods */
- file_memberlist, /* tp_members */
- file_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- file_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- file_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "file",
+ sizeof(PyFileObject),
+ 0,
+ (destructor)file_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)file_repr, /* 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 */
+ /* softspace is writable: we must supply tp_setattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_WEAKREFS, /* tp_flags */
+ file_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyFileObject, weakreflist), /* tp_weaklistoffset */
+ (getiterfunc)file_self, /* tp_iter */
+ (iternextfunc)file_iternext, /* tp_iternext */
+ file_methods, /* tp_methods */
+ file_memberlist, /* tp_members */
+ file_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ file_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ file_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
/* Interface for the 'soft space' between print items. */
@@ -2403,35 +2403,35 @@ PyTypeObject PyFile_Type = {
int
PyFile_SoftSpace(PyObject *f, int newflag)
{
- long oldflag = 0;
- if (f == NULL) {
- /* Do nothing */
- }
- else if (PyFile_Check(f)) {
- oldflag = ((PyFileObject *)f)->f_softspace;
- ((PyFileObject *)f)->f_softspace = newflag;
- }
- else {
- PyObject *v;
- v = PyObject_GetAttrString(f, "softspace");
- if (v == NULL)
- PyErr_Clear();
- else {
- if (PyInt_Check(v))
- oldflag = PyInt_AsLong(v);
- assert(oldflag < INT_MAX);
- Py_DECREF(v);
- }
- v = PyInt_FromLong((long)newflag);
- if (v == NULL)
- PyErr_Clear();
- else {
- if (PyObject_SetAttrString(f, "softspace", v) != 0)
- PyErr_Clear();
- Py_DECREF(v);
- }
- }
- return (int)oldflag;
+ long oldflag = 0;
+ if (f == NULL) {
+ /* Do nothing */
+ }
+ else if (PyFile_Check(f)) {
+ oldflag = ((PyFileObject *)f)->f_softspace;
+ ((PyFileObject *)f)->f_softspace = newflag;
+ }
+ else {
+ PyObject *v;
+ v = PyObject_GetAttrString(f, "softspace");
+ if (v == NULL)
+ PyErr_Clear();
+ else {
+ if (PyInt_Check(v))
+ oldflag = PyInt_AsLong(v);
+ assert(oldflag < INT_MAX);
+ Py_DECREF(v);
+ }
+ v = PyInt_FromLong((long)newflag);
+ if (v == NULL)
+ PyErr_Clear();
+ else {
+ if (PyObject_SetAttrString(f, "softspace", v) != 0)
+ PyErr_Clear();
+ Py_DECREF(v);
+ }
+ }
+ return (int)oldflag;
}
/* Interfaces to write objects/strings to file-like objects */
@@ -2439,107 +2439,107 @@ PyFile_SoftSpace(PyObject *f, int newflag)
int
PyFile_WriteObject(PyObject *v, PyObject *f, int flags)
{
- PyObject *writer, *value, *args, *result;
- if (f == NULL) {
- PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
- return -1;
- }
- else if (PyFile_Check(f)) {
- PyFileObject *fobj = (PyFileObject *) f;
+ PyObject *writer, *value, *args, *result;
+ if (f == NULL) {
+ PyErr_SetString(PyExc_TypeError, "writeobject with NULL file");
+ return -1;
+ }
+ else if (PyFile_Check(f)) {
+ PyFileObject *fobj = (PyFileObject *) f;
#ifdef Py_USING_UNICODE
- PyObject *enc = fobj->f_encoding;
- int result;
+ PyObject *enc = fobj->f_encoding;
+ int result;
#endif
- if (fobj->f_fp == NULL) {
- err_closed();
- return -1;
- }
+ if (fobj->f_fp == NULL) {
+ err_closed();
+ return -1;
+ }
#ifdef Py_USING_UNICODE
- if ((flags & Py_PRINT_RAW) &&
- PyUnicode_Check(v) && enc != Py_None) {
- char *cenc = PyString_AS_STRING(enc);
- char *errors = fobj->f_errors == Py_None ?
- "strict" : PyString_AS_STRING(fobj->f_errors);
- value = PyUnicode_AsEncodedString(v, cenc, errors);
- if (value == NULL)
- return -1;
- } else {
- value = v;
- Py_INCREF(value);
- }
- result = file_PyObject_Print(value, fobj, flags);
- Py_DECREF(value);
- return result;
+ if ((flags & Py_PRINT_RAW) &&
+ PyUnicode_Check(v) && enc != Py_None) {
+ char *cenc = PyString_AS_STRING(enc);
+ char *errors = fobj->f_errors == Py_None ?
+ "strict" : PyString_AS_STRING(fobj->f_errors);
+ value = PyUnicode_AsEncodedString(v, cenc, errors);
+ if (value == NULL)
+ return -1;
+ } else {
+ value = v;
+ Py_INCREF(value);
+ }
+ result = file_PyObject_Print(value, fobj, flags);
+ Py_DECREF(value);
+ return result;
#else
- return file_PyObject_Print(v, fobj, flags);
+ return file_PyObject_Print(v, fobj, flags);
#endif
- }
- writer = PyObject_GetAttrString(f, "write");
- if (writer == NULL)
- return -1;
- if (flags & Py_PRINT_RAW) {
- if (PyUnicode_Check(v)) {
- value = v;
- Py_INCREF(value);
- } else
- value = PyObject_Str(v);
- }
- else
- value = PyObject_Repr(v);
- if (value == NULL) {
- Py_DECREF(writer);
- return -1;
- }
- args = PyTuple_Pack(1, value);
- if (args == NULL) {
- Py_DECREF(value);
- Py_DECREF(writer);
- return -1;
- }
- result = PyEval_CallObject(writer, args);
- Py_DECREF(args);
- Py_DECREF(value);
- Py_DECREF(writer);
- if (result == NULL)
- return -1;
- Py_DECREF(result);
- return 0;
+ }
+ writer = PyObject_GetAttrString(f, "write");
+ if (writer == NULL)
+ return -1;
+ if (flags & Py_PRINT_RAW) {
+ if (PyUnicode_Check(v)) {
+ value = v;
+ Py_INCREF(value);
+ } else
+ value = PyObject_Str(v);
+ }
+ else
+ value = PyObject_Repr(v);
+ if (value == NULL) {
+ Py_DECREF(writer);
+ return -1;
+ }
+ args = PyTuple_Pack(1, value);
+ if (args == NULL) {
+ Py_DECREF(value);
+ Py_DECREF(writer);
+ return -1;
+ }
+ result = PyEval_CallObject(writer, args);
+ Py_DECREF(args);
+ Py_DECREF(value);
+ Py_DECREF(writer);
+ if (result == NULL)
+ return -1;
+ Py_DECREF(result);
+ return 0;
}
int
PyFile_WriteString(const char *s, PyObject *f)
{
- if (f == NULL) {
- /* Should be caused by a pre-existing error */
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_SystemError,
- "null file for PyFile_WriteString");
- return -1;
- }
- else if (PyFile_Check(f)) {
- PyFileObject *fobj = (PyFileObject *) f;
- FILE *fp = PyFile_AsFile(f);
- if (fp == NULL) {
- err_closed();
- return -1;
- }
- FILE_BEGIN_ALLOW_THREADS(fobj)
- fputs(s, fp);
- FILE_END_ALLOW_THREADS(fobj)
- return 0;
- }
- else if (!PyErr_Occurred()) {
- PyObject *v = PyString_FromString(s);
- int err;
- if (v == NULL)
- return -1;
- err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
- Py_DECREF(v);
- return err;
- }
- else
- return -1;
+ if (f == NULL) {
+ /* Should be caused by a pre-existing error */
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_SystemError,
+ "null file for PyFile_WriteString");
+ return -1;
+ }
+ else if (PyFile_Check(f)) {
+ PyFileObject *fobj = (PyFileObject *) f;
+ FILE *fp = PyFile_AsFile(f);
+ if (fp == NULL) {
+ err_closed();
+ return -1;
+ }
+ FILE_BEGIN_ALLOW_THREADS(fobj)
+ fputs(s, fp);
+ FILE_END_ALLOW_THREADS(fobj)
+ return 0;
+ }
+ else if (!PyErr_Occurred()) {
+ PyObject *v = PyString_FromString(s);
+ int err;
+ if (v == NULL)
+ return -1;
+ err = PyFile_WriteObject(v, f, Py_PRINT_RAW);
+ Py_DECREF(v);
+ return err;
+ }
+ else
+ return -1;
}
/* Try to get a file-descriptor from a Python object. If the object
@@ -2551,50 +2551,50 @@ PyFile_WriteString(const char *s, PyObject *f)
int PyObject_AsFileDescriptor(PyObject *o)
{
- int fd;
- PyObject *meth;
-
- if (PyInt_Check(o)) {
- fd = PyInt_AsLong(o);
- }
- else if (PyLong_Check(o)) {
- fd = PyLong_AsLong(o);
- }
- else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
- {
- PyObject *fno = PyEval_CallObject(meth, NULL);
- Py_DECREF(meth);
- if (fno == NULL)
- return -1;
-
- if (PyInt_Check(fno)) {
- fd = PyInt_AsLong(fno);
- Py_DECREF(fno);
- }
- else if (PyLong_Check(fno)) {
- fd = PyLong_AsLong(fno);
- Py_DECREF(fno);
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "fileno() returned a non-integer");
- Py_DECREF(fno);
- return -1;
- }
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "argument must be an int, or have a fileno() method.");
- return -1;
- }
-
- if (fd < 0) {
- PyErr_Format(PyExc_ValueError,
- "file descriptor cannot be a negative integer (%i)",
- fd);
- return -1;
- }
- return fd;
+ int fd;
+ PyObject *meth;
+
+ if (PyInt_Check(o)) {
+ fd = PyInt_AsLong(o);
+ }
+ else if (PyLong_Check(o)) {
+ fd = PyLong_AsLong(o);
+ }
+ else if ((meth = PyObject_GetAttrString(o, "fileno")) != NULL)
+ {
+ PyObject *fno = PyEval_CallObject(meth, NULL);
+ Py_DECREF(meth);
+ if (fno == NULL)
+ return -1;
+
+ if (PyInt_Check(fno)) {
+ fd = PyInt_AsLong(fno);
+ Py_DECREF(fno);
+ }
+ else if (PyLong_Check(fno)) {
+ fd = PyLong_AsLong(fno);
+ Py_DECREF(fno);
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "fileno() returned a non-integer");
+ Py_DECREF(fno);
+ return -1;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "argument must be an int, or have a fileno() method.");
+ return -1;
+ }
+
+ if (fd < 0) {
+ PyErr_Format(PyExc_ValueError,
+ "file descriptor cannot be a negative integer (%i)",
+ fd);
+ return -1;
+ }
+ return fd;
}
/* From here on we need access to the real fgets and fread */
@@ -2618,79 +2618,79 @@ int PyObject_AsFileDescriptor(PyObject *o)
char *
Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
{
- char *p = buf;
- int c;
- int newlinetypes = 0;
- int skipnextlf = 0;
- int univ_newline = 1;
-
- if (fobj) {
- if (!PyFile_Check(fobj)) {
- errno = ENXIO; /* What can you do... */
- return NULL;
- }
- univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
- if ( !univ_newline )
- return fgets(buf, n, stream);
- newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
- skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
- }
- FLOCKFILE(stream);
- c = 'x'; /* Shut up gcc warning */
- while (--n > 0 && (c = GETC(stream)) != EOF ) {
- if (skipnextlf ) {
- skipnextlf = 0;
- if (c == '\n') {
- /* Seeing a \n here with skipnextlf true
- ** means we saw a \r before.
- */
- newlinetypes |= NEWLINE_CRLF;
- c = GETC(stream);
- if (c == EOF) break;
- } else {
- /*
- ** Note that c == EOF also brings us here,
- ** so we're okay if the last char in the file
- ** is a CR.
- */
- newlinetypes |= NEWLINE_CR;
- }
- }
- if (c == '\r') {
- /* A \r is translated into a \n, and we skip
- ** an adjacent \n, if any. We don't set the
- ** newlinetypes flag until we've seen the next char.
- */
- skipnextlf = 1;
- c = '\n';
- } else if ( c == '\n') {
- newlinetypes |= NEWLINE_LF;
- }
- *p++ = c;
- if (c == '\n') break;
- }
- if ( c == EOF && skipnextlf )
- newlinetypes |= NEWLINE_CR;
- FUNLOCKFILE(stream);
- *p = '\0';
- if (fobj) {
- ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
- ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
- } else if ( skipnextlf ) {
- /* If we have no file object we cannot save the
- ** skipnextlf flag. We have to readahead, which
- ** will cause a pause if we're reading from an
- ** interactive stream, but that is very unlikely
- ** unless we're doing something silly like
- ** execfile("/dev/tty").
- */
- c = GETC(stream);
- if ( c != '\n' )
- ungetc(c, stream);
- }
- if (p == buf)
- return NULL;
- return buf;
+ char *p = buf;
+ int c;
+ int newlinetypes = 0;
+ int skipnextlf = 0;
+ int univ_newline = 1;
+
+ if (fobj) {
+ if (!PyFile_Check(fobj)) {
+ errno = ENXIO; /* What can you do... */
+ return NULL;
+ }
+ univ_newline = ((PyFileObject *)fobj)->f_univ_newline;
+ if ( !univ_newline )
+ return fgets(buf, n, stream);
+ newlinetypes = ((PyFileObject *)fobj)->f_newlinetypes;
+ skipnextlf = ((PyFileObject *)fobj)->f_skipnextlf;
+ }
+ FLOCKFILE(stream);
+ c = 'x'; /* Shut up gcc warning */
+ while (--n > 0 && (c = GETC(stream)) != EOF ) {
+ if (skipnextlf ) {
+ skipnextlf = 0;
+ if (c == '\n') {
+ /* Seeing a \n here with skipnextlf true
+ ** means we saw a \r before.
+ */
+ newlinetypes |= NEWLINE_CRLF;
+ c = GETC(stream);
+ if (c == EOF) break;
+ } else {
+ /*
+ ** Note that c == EOF also brings us here,
+ ** so we're okay if the last char in the file
+ ** is a CR.
+ */
+ newlinetypes |= NEWLINE_CR;
+ }
+ }
+ if (c == '\r') {
+ /* A \r is translated into a \n, and we skip
+ ** an adjacent \n, if any. We don't set the
+ ** newlinetypes flag until we've seen the next char.
+ */
+ skipnextlf = 1;
+ c = '\n';
+ } else if ( c == '\n') {
+ newlinetypes |= NEWLINE_LF;
+ }
+ *p++ = c;
+ if (c == '\n') break;
+ }
+ if ( c == EOF && skipnextlf )
+ newlinetypes |= NEWLINE_CR;
+ FUNLOCKFILE(stream);
+ *p = '\0';
+ if (fobj) {
+ ((PyFileObject *)fobj)->f_newlinetypes = newlinetypes;
+ ((PyFileObject *)fobj)->f_skipnextlf = skipnextlf;
+ } else if ( skipnextlf ) {
+ /* If we have no file object we cannot save the
+ ** skipnextlf flag. We have to readahead, which
+ ** will cause a pause if we're reading from an
+ ** interactive stream, but that is very unlikely
+ ** unless we're doing something silly like
+ ** execfile("/dev/tty").
+ */
+ c = GETC(stream);
+ if ( c != '\n' )
+ ungetc(c, stream);
+ }
+ if (p == buf)
+ return NULL;
+ return buf;
}
/*
@@ -2705,74 +2705,74 @@ Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
*/
size_t
Py_UniversalNewlineFread(char *buf, size_t n,
- FILE *stream, PyObject *fobj)
+ FILE *stream, PyObject *fobj)
{
- char *dst = buf;
- PyFileObject *f = (PyFileObject *)fobj;
- int newlinetypes, skipnextlf;
-
- assert(buf != NULL);
- assert(stream != NULL);
-
- if (!fobj || !PyFile_Check(fobj)) {
- errno = ENXIO; /* What can you do... */
- return 0;
- }
- if (!f->f_univ_newline)
- return fread(buf, 1, n, stream);
- newlinetypes = f->f_newlinetypes;
- skipnextlf = f->f_skipnextlf;
- /* Invariant: n is the number of bytes remaining to be filled
- * in the buffer.
- */
- while (n) {
- size_t nread;
- int shortread;
- char *src = dst;
-
- nread = fread(dst, 1, n, stream);
- assert(nread <= n);
- if (nread == 0)
- break;
-
- n -= nread; /* assuming 1 byte out for each in; will adjust */
- shortread = n != 0; /* true iff EOF or error */
- while (nread--) {
- char c = *src++;
- if (c == '\r') {
- /* Save as LF and set flag to skip next LF. */
- *dst++ = '\n';
- skipnextlf = 1;
- }
- else if (skipnextlf && c == '\n') {
- /* Skip LF, and remember we saw CR LF. */
- skipnextlf = 0;
- newlinetypes |= NEWLINE_CRLF;
- ++n;
- }
- else {
- /* Normal char to be stored in buffer. Also
- * update the newlinetypes flag if either this
- * is an LF or the previous char was a CR.
- */
- if (c == '\n')
- newlinetypes |= NEWLINE_LF;
- else if (skipnextlf)
- newlinetypes |= NEWLINE_CR;
- *dst++ = c;
- skipnextlf = 0;
- }
- }
- if (shortread) {
- /* If this is EOF, update type flags. */
- if (skipnextlf && feof(stream))
- newlinetypes |= NEWLINE_CR;
- break;
- }
- }
- f->f_newlinetypes = newlinetypes;
- f->f_skipnextlf = skipnextlf;
- return dst - buf;
+ char *dst = buf;
+ PyFileObject *f = (PyFileObject *)fobj;
+ int newlinetypes, skipnextlf;
+
+ assert(buf != NULL);
+ assert(stream != NULL);
+
+ if (!fobj || !PyFile_Check(fobj)) {
+ errno = ENXIO; /* What can you do... */
+ return 0;
+ }
+ if (!f->f_univ_newline)
+ return fread(buf, 1, n, stream);
+ newlinetypes = f->f_newlinetypes;
+ skipnextlf = f->f_skipnextlf;
+ /* Invariant: n is the number of bytes remaining to be filled
+ * in the buffer.
+ */
+ while (n) {
+ size_t nread;
+ int shortread;
+ char *src = dst;
+
+ nread = fread(dst, 1, n, stream);
+ assert(nread <= n);
+ if (nread == 0)
+ break;
+
+ n -= nread; /* assuming 1 byte out for each in; will adjust */
+ shortread = n != 0; /* true iff EOF or error */
+ while (nread--) {
+ char c = *src++;
+ if (c == '\r') {
+ /* Save as LF and set flag to skip next LF. */
+ *dst++ = '\n';
+ skipnextlf = 1;
+ }
+ else if (skipnextlf && c == '\n') {
+ /* Skip LF, and remember we saw CR LF. */
+ skipnextlf = 0;
+ newlinetypes |= NEWLINE_CRLF;
+ ++n;
+ }
+ else {
+ /* Normal char to be stored in buffer. Also
+ * update the newlinetypes flag if either this
+ * is an LF or the previous char was a CR.
+ */
+ if (c == '\n')
+ newlinetypes |= NEWLINE_LF;
+ else if (skipnextlf)
+ newlinetypes |= NEWLINE_CR;
+ *dst++ = c;
+ skipnextlf = 0;
+ }
+ }
+ if (shortread) {
+ /* If this is EOF, update type flags. */
+ if (skipnextlf && feof(stream))
+ newlinetypes |= NEWLINE_CR;
+ break;
+ }
+ }
+ f->f_newlinetypes = newlinetypes;
+ f->f_skipnextlf = skipnextlf;
+ return dst - buf;
}
#ifdef __cplusplus
diff --git a/Objects/floatobject.c b/Objects/floatobject.c
index d6a5a35..682bafb 100644
--- a/Objects/floatobject.c
+++ b/Objects/floatobject.c
@@ -21,13 +21,13 @@ extern int finite(double);
#endif
/* Special free list -- see comments for same code in intobject.c. */
-#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
-#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
-#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
+#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
+#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
+#define N_FLOATOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyFloatObject))
struct _floatblock {
- struct _floatblock *next;
- PyFloatObject objects[N_FLOATOBJECTS];
+ struct _floatblock *next;
+ PyFloatObject objects[N_FLOATOBJECTS];
};
typedef struct _floatblock PyFloatBlock;
@@ -38,31 +38,31 @@ static PyFloatObject *free_list = NULL;
static PyFloatObject *
fill_free_list(void)
{
- PyFloatObject *p, *q;
- /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
- p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
- if (p == NULL)
- return (PyFloatObject *) PyErr_NoMemory();
- ((PyFloatBlock *)p)->next = block_list;
- block_list = (PyFloatBlock *)p;
- p = &((PyFloatBlock *)p)->objects[0];
- q = p + N_FLOATOBJECTS;
- while (--q > p)
- Py_TYPE(q) = (struct _typeobject *)(q-1);
- Py_TYPE(q) = NULL;
- return p + N_FLOATOBJECTS - 1;
+ PyFloatObject *p, *q;
+ /* XXX Float blocks escape the object heap. Use PyObject_MALLOC ??? */
+ p = (PyFloatObject *) PyMem_MALLOC(sizeof(PyFloatBlock));
+ if (p == NULL)
+ return (PyFloatObject *) PyErr_NoMemory();
+ ((PyFloatBlock *)p)->next = block_list;
+ block_list = (PyFloatBlock *)p;
+ p = &((PyFloatBlock *)p)->objects[0];
+ q = p + N_FLOATOBJECTS;
+ while (--q > p)
+ Py_TYPE(q) = (struct _typeobject *)(q-1);
+ Py_TYPE(q) = NULL;
+ return p + N_FLOATOBJECTS - 1;
}
double
PyFloat_GetMax(void)
{
- return DBL_MAX;
+ return DBL_MAX;
}
double
PyFloat_GetMin(void)
{
- return DBL_MIN;
+ return DBL_MIN;
}
static PyTypeObject FloatInfoType = {0, 0, 0, 0, 0, 0};
@@ -75,83 +75,83 @@ information about the precision and internal representation. Please study\n\
your system's :file:`float.h` for more information.");
static PyStructSequence_Field floatinfo_fields[] = {
- {"max", "DBL_MAX -- maximum representable finite float"},
- {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
- "is representable"},
- {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
- "is representable"},
- {"min", "DBL_MIN -- Minimum positive normalizer float"},
- {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
- "is a normalized float"},
- {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
- "a normalized"},
- {"dig", "DBL_DIG -- digits"},
- {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
- {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
- "representable float"},
- {"radix", "FLT_RADIX -- radix of exponent"},
- {"rounds", "FLT_ROUNDS -- addition rounds"},
- {0}
+ {"max", "DBL_MAX -- maximum representable finite float"},
+ {"max_exp", "DBL_MAX_EXP -- maximum int e such that radix**(e-1) "
+ "is representable"},
+ {"max_10_exp", "DBL_MAX_10_EXP -- maximum int e such that 10**e "
+ "is representable"},
+ {"min", "DBL_MIN -- Minimum positive normalizer float"},
+ {"min_exp", "DBL_MIN_EXP -- minimum int e such that radix**(e-1) "
+ "is a normalized float"},
+ {"min_10_exp", "DBL_MIN_10_EXP -- minimum int e such that 10**e is "
+ "a normalized"},
+ {"dig", "DBL_DIG -- digits"},
+ {"mant_dig", "DBL_MANT_DIG -- mantissa digits"},
+ {"epsilon", "DBL_EPSILON -- Difference between 1 and the next "
+ "representable float"},
+ {"radix", "FLT_RADIX -- radix of exponent"},
+ {"rounds", "FLT_ROUNDS -- addition rounds"},
+ {0}
};
static PyStructSequence_Desc floatinfo_desc = {
- "sys.float_info", /* name */
- floatinfo__doc__, /* doc */
- floatinfo_fields, /* fields */
- 11
+ "sys.float_info", /* name */
+ floatinfo__doc__, /* doc */
+ floatinfo_fields, /* fields */
+ 11
};
PyObject *
PyFloat_GetInfo(void)
{
- PyObject* floatinfo;
- int pos = 0;
+ PyObject* floatinfo;
+ int pos = 0;
- floatinfo = PyStructSequence_New(&FloatInfoType);
- if (floatinfo == NULL) {
- return NULL;
- }
+ floatinfo = PyStructSequence_New(&FloatInfoType);
+ if (floatinfo == NULL) {
+ return NULL;
+ }
#define SetIntFlag(flag) \
- PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
+ PyStructSequence_SET_ITEM(floatinfo, pos++, PyInt_FromLong(flag))
#define SetDblFlag(flag) \
- PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
-
- SetDblFlag(DBL_MAX);
- SetIntFlag(DBL_MAX_EXP);
- SetIntFlag(DBL_MAX_10_EXP);
- SetDblFlag(DBL_MIN);
- SetIntFlag(DBL_MIN_EXP);
- SetIntFlag(DBL_MIN_10_EXP);
- SetIntFlag(DBL_DIG);
- SetIntFlag(DBL_MANT_DIG);
- SetDblFlag(DBL_EPSILON);
- SetIntFlag(FLT_RADIX);
- SetIntFlag(FLT_ROUNDS);
+ PyStructSequence_SET_ITEM(floatinfo, pos++, PyFloat_FromDouble(flag))
+
+ SetDblFlag(DBL_MAX);
+ SetIntFlag(DBL_MAX_EXP);
+ SetIntFlag(DBL_MAX_10_EXP);
+ SetDblFlag(DBL_MIN);
+ SetIntFlag(DBL_MIN_EXP);
+ SetIntFlag(DBL_MIN_10_EXP);
+ SetIntFlag(DBL_DIG);
+ SetIntFlag(DBL_MANT_DIG);
+ SetDblFlag(DBL_EPSILON);
+ SetIntFlag(FLT_RADIX);
+ SetIntFlag(FLT_ROUNDS);
#undef SetIntFlag
#undef SetDblFlag
-
- if (PyErr_Occurred()) {
- Py_CLEAR(floatinfo);
- return NULL;
- }
- return floatinfo;
+
+ if (PyErr_Occurred()) {
+ Py_CLEAR(floatinfo);
+ return NULL;
+ }
+ return floatinfo;
}
PyObject *
PyFloat_FromDouble(double fval)
{
- register PyFloatObject *op;
- if (free_list == NULL) {
- if ((free_list = fill_free_list()) == NULL)
- return NULL;
- }
- /* Inline PyObject_New */
- op = free_list;
- free_list = (PyFloatObject *)Py_TYPE(op);
- PyObject_INIT(op, &PyFloat_Type);
- op->ob_fval = fval;
- return (PyObject *) op;
+ register PyFloatObject *op;
+ if (free_list == NULL) {
+ if ((free_list = fill_free_list()) == NULL)
+ return NULL;
+ }
+ /* Inline PyObject_New */
+ op = free_list;
+ free_list = (PyFloatObject *)Py_TYPE(op);
+ PyObject_INIT(op, &PyFloat_Type);
+ op->ob_fval = fval;
+ return (PyObject *) op;
}
/**************************************************************************
@@ -173,113 +173,113 @@ still supported but now *officially* useless: if pend is not NULL,
PyObject *
PyFloat_FromString(PyObject *v, char **pend)
{
- const char *s, *last, *end;
- double x;
- char buffer[256]; /* for errors */
+ const char *s, *last, *end;
+ double x;
+ char buffer[256]; /* for errors */
#ifdef Py_USING_UNICODE
- char *s_buffer = NULL;
+ char *s_buffer = NULL;
#endif
- Py_ssize_t len;
- PyObject *result = NULL;
-
- if (pend)
- *pend = NULL;
- if (PyString_Check(v)) {
- s = PyString_AS_STRING(v);
- len = PyString_GET_SIZE(v);
- }
+ Py_ssize_t len;
+ PyObject *result = NULL;
+
+ if (pend)
+ *pend = NULL;
+ if (PyString_Check(v)) {
+ s = PyString_AS_STRING(v);
+ len = PyString_GET_SIZE(v);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(v)) {
- s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
- if (s_buffer == NULL)
- return PyErr_NoMemory();
- if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
- PyUnicode_GET_SIZE(v),
- s_buffer,
- NULL))
- goto error;
- s = s_buffer;
- len = strlen(s);
- }
+ else if (PyUnicode_Check(v)) {
+ s_buffer = (char *)PyMem_MALLOC(PyUnicode_GET_SIZE(v)+1);
+ if (s_buffer == NULL)
+ return PyErr_NoMemory();
+ if (PyUnicode_EncodeDecimal(PyUnicode_AS_UNICODE(v),
+ PyUnicode_GET_SIZE(v),
+ s_buffer,
+ NULL))
+ goto error;
+ s = s_buffer;
+ len = strlen(s);
+ }
#endif
- else if (PyObject_AsCharBuffer(v, &s, &len)) {
- PyErr_SetString(PyExc_TypeError,
- "float() argument must be a string or a number");
- return NULL;
- }
- last = s + len;
-
- while (Py_ISSPACE(*s))
- s++;
- /* We don't care about overflow or underflow. If the platform
- * supports them, infinities and signed zeroes (on underflow) are
- * fine. */
- x = PyOS_string_to_double(s, (char **)&end, NULL);
- if (x == -1.0 && PyErr_Occurred())
- goto error;
- while (Py_ISSPACE(*end))
- end++;
- if (end == last)
- result = PyFloat_FromDouble(x);
- else {
- PyOS_snprintf(buffer, sizeof(buffer),
- "invalid literal for float(): %.200s", s);
- PyErr_SetString(PyExc_ValueError, buffer);
- result = NULL;
- }
+ else if (PyObject_AsCharBuffer(v, &s, &len)) {
+ PyErr_SetString(PyExc_TypeError,
+ "float() argument must be a string or a number");
+ return NULL;
+ }
+ last = s + len;
+
+ while (Py_ISSPACE(*s))
+ s++;
+ /* We don't care about overflow or underflow. If the platform
+ * supports them, infinities and signed zeroes (on underflow) are
+ * fine. */
+ x = PyOS_string_to_double(s, (char **)&end, NULL);
+ if (x == -1.0 && PyErr_Occurred())
+ goto error;
+ while (Py_ISSPACE(*end))
+ end++;
+ if (end == last)
+ result = PyFloat_FromDouble(x);
+ else {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "invalid literal for float(): %.200s", s);
+ PyErr_SetString(PyExc_ValueError, buffer);
+ result = NULL;
+ }
error:
#ifdef Py_USING_UNICODE
- if (s_buffer)
- PyMem_FREE(s_buffer);
+ if (s_buffer)
+ PyMem_FREE(s_buffer);
#endif
- return result;
+ return result;
}
static void
float_dealloc(PyFloatObject *op)
{
- if (PyFloat_CheckExact(op)) {
- Py_TYPE(op) = (struct _typeobject *)free_list;
- free_list = op;
- }
- else
- Py_TYPE(op)->tp_free((PyObject *)op);
+ if (PyFloat_CheckExact(op)) {
+ Py_TYPE(op) = (struct _typeobject *)free_list;
+ free_list = op;
+ }
+ else
+ Py_TYPE(op)->tp_free((PyObject *)op);
}
double
PyFloat_AsDouble(PyObject *op)
{
- PyNumberMethods *nb;
- PyFloatObject *fo;
- double val;
-
- if (op && PyFloat_Check(op))
- return PyFloat_AS_DOUBLE((PyFloatObject*) op);
-
- if (op == NULL) {
- PyErr_BadArgument();
- return -1;
- }
-
- if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
- PyErr_SetString(PyExc_TypeError, "a float is required");
- return -1;
- }
-
- fo = (PyFloatObject*) (*nb->nb_float) (op);
- if (fo == NULL)
- return -1;
- if (!PyFloat_Check(fo)) {
- PyErr_SetString(PyExc_TypeError,
- "nb_float should return float object");
- return -1;
- }
-
- val = PyFloat_AS_DOUBLE(fo);
- Py_DECREF(fo);
-
- return val;
+ PyNumberMethods *nb;
+ PyFloatObject *fo;
+ double val;
+
+ if (op && PyFloat_Check(op))
+ return PyFloat_AS_DOUBLE((PyFloatObject*) op);
+
+ if (op == NULL) {
+ PyErr_BadArgument();
+ return -1;
+ }
+
+ if ((nb = Py_TYPE(op)->tp_as_number) == NULL || nb->nb_float == NULL) {
+ PyErr_SetString(PyExc_TypeError, "a float is required");
+ return -1;
+ }
+
+ fo = (PyFloatObject*) (*nb->nb_float) (op);
+ if (fo == NULL)
+ return -1;
+ if (!PyFloat_Check(fo)) {
+ PyErr_SetString(PyExc_TypeError,
+ "nb_float should return float object");
+ return -1;
+ }
+
+ val = PyFloat_AS_DOUBLE(fo);
+ Py_DECREF(fo);
+
+ return val;
}
/* Methods */
@@ -291,33 +291,33 @@ PyFloat_AsDouble(PyObject *op)
obj is not of float, int or long type, Py_NotImplemented is incref'ed,
stored in obj, and returned from the function invoking this macro.
*/
-#define CONVERT_TO_DOUBLE(obj, dbl) \
- if (PyFloat_Check(obj)) \
- dbl = PyFloat_AS_DOUBLE(obj); \
- else if (convert_to_double(&(obj), &(dbl)) < 0) \
- return obj;
+#define CONVERT_TO_DOUBLE(obj, dbl) \
+ if (PyFloat_Check(obj)) \
+ dbl = PyFloat_AS_DOUBLE(obj); \
+ else if (convert_to_double(&(obj), &(dbl)) < 0) \
+ return obj;
static int
convert_to_double(PyObject **v, double *dbl)
{
- register PyObject *obj = *v;
-
- if (PyInt_Check(obj)) {
- *dbl = (double)PyInt_AS_LONG(obj);
- }
- else if (PyLong_Check(obj)) {
- *dbl = PyLong_AsDouble(obj);
- if (*dbl == -1.0 && PyErr_Occurred()) {
- *v = NULL;
- return -1;
- }
- }
- else {
- Py_INCREF(Py_NotImplemented);
- *v = Py_NotImplemented;
- return -1;
- }
- return 0;
+ register PyObject *obj = *v;
+
+ if (PyInt_Check(obj)) {
+ *dbl = (double)PyInt_AS_LONG(obj);
+ }
+ else if (PyLong_Check(obj)) {
+ *dbl = PyLong_AsDouble(obj);
+ if (*dbl == -1.0 && PyErr_Occurred()) {
+ *v = NULL;
+ return -1;
+ }
+ }
+ else {
+ Py_INCREF(Py_NotImplemented);
+ *v = Py_NotImplemented;
+ return -1;
+ }
+ return 0;
}
/* XXX PyFloat_AsString and PyFloat_AsReprString are deprecated:
@@ -326,66 +326,66 @@ convert_to_double(PyObject **v, double *dbl)
void
PyFloat_AsString(char *buf, PyFloatObject *v)
{
- char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
- PyFloat_STR_PRECISION,
- Py_DTSF_ADD_DOT_0, NULL);
- strcpy(buf, tmp);
- PyMem_Free(tmp);
+ char *tmp = PyOS_double_to_string(v->ob_fval, 'g',
+ PyFloat_STR_PRECISION,
+ Py_DTSF_ADD_DOT_0, NULL);
+ strcpy(buf, tmp);
+ PyMem_Free(tmp);
}
void
PyFloat_AsReprString(char *buf, PyFloatObject *v)
{
- char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
- Py_DTSF_ADD_DOT_0, NULL);
- strcpy(buf, tmp);
- PyMem_Free(tmp);
+ char * tmp = PyOS_double_to_string(v->ob_fval, 'r', 0,
+ Py_DTSF_ADD_DOT_0, NULL);
+ strcpy(buf, tmp);
+ PyMem_Free(tmp);
}
/* ARGSUSED */
static int
float_print(PyFloatObject *v, FILE *fp, int flags)
{
- char *buf;
- if (flags & Py_PRINT_RAW)
- buf = PyOS_double_to_string(v->ob_fval,
- 'g', PyFloat_STR_PRECISION,
- Py_DTSF_ADD_DOT_0, NULL);
- else
- buf = PyOS_double_to_string(v->ob_fval,
- 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
- Py_BEGIN_ALLOW_THREADS
- fputs(buf, fp);
- Py_END_ALLOW_THREADS
- PyMem_Free(buf);
- return 0;
+ char *buf;
+ if (flags & Py_PRINT_RAW)
+ buf = PyOS_double_to_string(v->ob_fval,
+ 'g', PyFloat_STR_PRECISION,
+ Py_DTSF_ADD_DOT_0, NULL);
+ else
+ buf = PyOS_double_to_string(v->ob_fval,
+ 'r', 0, Py_DTSF_ADD_DOT_0, NULL);
+ Py_BEGIN_ALLOW_THREADS
+ fputs(buf, fp);
+ Py_END_ALLOW_THREADS
+ PyMem_Free(buf);
+ return 0;
}
static PyObject *
float_str_or_repr(PyFloatObject *v, int precision, char format_code)
{
- PyObject *result;
- char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
- format_code, precision,
- Py_DTSF_ADD_DOT_0,
- NULL);
- if (!buf)
- return PyErr_NoMemory();
- result = PyString_FromString(buf);
- PyMem_Free(buf);
- return result;
+ PyObject *result;
+ char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
+ format_code, precision,
+ Py_DTSF_ADD_DOT_0,
+ NULL);
+ if (!buf)
+ return PyErr_NoMemory();
+ result = PyString_FromString(buf);
+ PyMem_Free(buf);
+ return result;
}
static PyObject *
float_repr(PyFloatObject *v)
{
- return float_str_or_repr(v, 0, 'r');
+ return float_str_or_repr(v, 0, 'r');
}
static PyObject *
float_str(PyFloatObject *v)
{
- return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
+ return float_str_or_repr(v, PyFloat_STR_PRECISION, 'g');
}
/* Comparison is pretty much a nightmare. When comparing float to float,
@@ -406,389 +406,389 @@ float_str(PyFloatObject *v)
static PyObject*
float_richcompare(PyObject *v, PyObject *w, int op)
{
- double i, j;
- int r = 0;
-
- assert(PyFloat_Check(v));
- i = PyFloat_AS_DOUBLE(v);
-
- /* Switch on the type of w. Set i and j to doubles to be compared,
- * and op to the richcomp to use.
- */
- if (PyFloat_Check(w))
- j = PyFloat_AS_DOUBLE(w);
-
- else if (!Py_IS_FINITE(i)) {
- if (PyInt_Check(w) || PyLong_Check(w))
- /* If i is an infinity, its magnitude exceeds any
- * finite integer, so it doesn't matter which int we
- * compare i with. If i is a NaN, similarly.
- */
- j = 0.0;
- else
- goto Unimplemented;
- }
-
- else if (PyInt_Check(w)) {
- long jj = PyInt_AS_LONG(w);
- /* In the worst realistic case I can imagine, C double is a
- * Cray single with 48 bits of precision, and long has 64
- * bits.
- */
+ double i, j;
+ int r = 0;
+
+ assert(PyFloat_Check(v));
+ i = PyFloat_AS_DOUBLE(v);
+
+ /* Switch on the type of w. Set i and j to doubles to be compared,
+ * and op to the richcomp to use.
+ */
+ if (PyFloat_Check(w))
+ j = PyFloat_AS_DOUBLE(w);
+
+ else if (!Py_IS_FINITE(i)) {
+ if (PyInt_Check(w) || PyLong_Check(w))
+ /* If i is an infinity, its magnitude exceeds any
+ * finite integer, so it doesn't matter which int we
+ * compare i with. If i is a NaN, similarly.
+ */
+ j = 0.0;
+ else
+ goto Unimplemented;
+ }
+
+ else if (PyInt_Check(w)) {
+ long jj = PyInt_AS_LONG(w);
+ /* In the worst realistic case I can imagine, C double is a
+ * Cray single with 48 bits of precision, and long has 64
+ * bits.
+ */
#if SIZEOF_LONG > 6
- unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
- if (abs >> 48) {
- /* Needs more than 48 bits. Make it take the
- * PyLong path.
- */
- PyObject *result;
- PyObject *ww = PyLong_FromLong(jj);
-
- if (ww == NULL)
- return NULL;
- result = float_richcompare(v, ww, op);
- Py_DECREF(ww);
- return result;
- }
+ unsigned long abs = (unsigned long)(jj < 0 ? -jj : jj);
+ if (abs >> 48) {
+ /* Needs more than 48 bits. Make it take the
+ * PyLong path.
+ */
+ PyObject *result;
+ PyObject *ww = PyLong_FromLong(jj);
+
+ if (ww == NULL)
+ return NULL;
+ result = float_richcompare(v, ww, op);
+ Py_DECREF(ww);
+ return result;
+ }
#endif
- j = (double)jj;
- assert((long)j == jj);
- }
-
- else if (PyLong_Check(w)) {
- int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
- int wsign = _PyLong_Sign(w);
- size_t nbits;
- int exponent;
-
- if (vsign != wsign) {
- /* Magnitudes are irrelevant -- the signs alone
- * determine the outcome.
- */
- i = (double)vsign;
- j = (double)wsign;
- goto Compare;
- }
- /* The signs are the same. */
- /* Convert w to a double if it fits. In particular, 0 fits. */
- nbits = _PyLong_NumBits(w);
- if (nbits == (size_t)-1 && PyErr_Occurred()) {
- /* This long is so large that size_t isn't big enough
- * to hold the # of bits. Replace with little doubles
- * that give the same outcome -- w is so large that
- * its magnitude must exceed the magnitude of any
- * finite float.
- */
- PyErr_Clear();
- i = (double)vsign;
- assert(wsign != 0);
- j = wsign * 2.0;
- goto Compare;
- }
- if (nbits <= 48) {
- j = PyLong_AsDouble(w);
- /* It's impossible that <= 48 bits overflowed. */
- assert(j != -1.0 || ! PyErr_Occurred());
- goto Compare;
- }
- assert(wsign != 0); /* else nbits was 0 */
- assert(vsign != 0); /* if vsign were 0, then since wsign is
- * not 0, we would have taken the
- * vsign != wsign branch at the start */
- /* We want to work with non-negative numbers. */
- if (vsign < 0) {
- /* "Multiply both sides" by -1; this also swaps the
- * comparator.
- */
- i = -i;
- op = _Py_SwappedOp[op];
- }
- assert(i > 0.0);
- (void) frexp(i, &exponent);
- /* exponent is the # of bits in v before the radix point;
- * we know that nbits (the # of bits in w) > 48 at this point
- */
- if (exponent < 0 || (size_t)exponent < nbits) {
- i = 1.0;
- j = 2.0;
- goto Compare;
- }
- if ((size_t)exponent > nbits) {
- i = 2.0;
- j = 1.0;
- goto Compare;
- }
- /* v and w have the same number of bits before the radix
- * point. Construct two longs that have the same comparison
- * outcome.
- */
- {
- double fracpart;
- double intpart;
- PyObject *result = NULL;
- PyObject *one = NULL;
- PyObject *vv = NULL;
- PyObject *ww = w;
-
- if (wsign < 0) {
- ww = PyNumber_Negative(w);
- if (ww == NULL)
- goto Error;
- }
- else
- Py_INCREF(ww);
-
- fracpart = modf(i, &intpart);
- vv = PyLong_FromDouble(intpart);
- if (vv == NULL)
- goto Error;
-
- if (fracpart != 0.0) {
- /* Shift left, and or a 1 bit into vv
- * to represent the lost fraction.
- */
- PyObject *temp;
-
- one = PyInt_FromLong(1);
- if (one == NULL)
- goto Error;
-
- temp = PyNumber_Lshift(ww, one);
- if (temp == NULL)
- goto Error;
- Py_DECREF(ww);
- ww = temp;
-
- temp = PyNumber_Lshift(vv, one);
- if (temp == NULL)
- goto Error;
- Py_DECREF(vv);
- vv = temp;
-
- temp = PyNumber_Or(vv, one);
- if (temp == NULL)
- goto Error;
- Py_DECREF(vv);
- vv = temp;
- }
-
- r = PyObject_RichCompareBool(vv, ww, op);
- if (r < 0)
- goto Error;
- result = PyBool_FromLong(r);
- Error:
- Py_XDECREF(vv);
- Py_XDECREF(ww);
- Py_XDECREF(one);
- return result;
- }
- } /* else if (PyLong_Check(w)) */
-
- else /* w isn't float, int, or long */
- goto Unimplemented;
+ j = (double)jj;
+ assert((long)j == jj);
+ }
+
+ else if (PyLong_Check(w)) {
+ int vsign = i == 0.0 ? 0 : i < 0.0 ? -1 : 1;
+ int wsign = _PyLong_Sign(w);
+ size_t nbits;
+ int exponent;
+
+ if (vsign != wsign) {
+ /* Magnitudes are irrelevant -- the signs alone
+ * determine the outcome.
+ */
+ i = (double)vsign;
+ j = (double)wsign;
+ goto Compare;
+ }
+ /* The signs are the same. */
+ /* Convert w to a double if it fits. In particular, 0 fits. */
+ nbits = _PyLong_NumBits(w);
+ if (nbits == (size_t)-1 && PyErr_Occurred()) {
+ /* This long is so large that size_t isn't big enough
+ * to hold the # of bits. Replace with little doubles
+ * that give the same outcome -- w is so large that
+ * its magnitude must exceed the magnitude of any
+ * finite float.
+ */
+ PyErr_Clear();
+ i = (double)vsign;
+ assert(wsign != 0);
+ j = wsign * 2.0;
+ goto Compare;
+ }
+ if (nbits <= 48) {
+ j = PyLong_AsDouble(w);
+ /* It's impossible that <= 48 bits overflowed. */
+ assert(j != -1.0 || ! PyErr_Occurred());
+ goto Compare;
+ }
+ assert(wsign != 0); /* else nbits was 0 */
+ assert(vsign != 0); /* if vsign were 0, then since wsign is
+ * not 0, we would have taken the
+ * vsign != wsign branch at the start */
+ /* We want to work with non-negative numbers. */
+ if (vsign < 0) {
+ /* "Multiply both sides" by -1; this also swaps the
+ * comparator.
+ */
+ i = -i;
+ op = _Py_SwappedOp[op];
+ }
+ assert(i > 0.0);
+ (void) frexp(i, &exponent);
+ /* exponent is the # of bits in v before the radix point;
+ * we know that nbits (the # of bits in w) > 48 at this point
+ */
+ if (exponent < 0 || (size_t)exponent < nbits) {
+ i = 1.0;
+ j = 2.0;
+ goto Compare;
+ }
+ if ((size_t)exponent > nbits) {
+ i = 2.0;
+ j = 1.0;
+ goto Compare;
+ }
+ /* v and w have the same number of bits before the radix
+ * point. Construct two longs that have the same comparison
+ * outcome.
+ */
+ {
+ double fracpart;
+ double intpart;
+ PyObject *result = NULL;
+ PyObject *one = NULL;
+ PyObject *vv = NULL;
+ PyObject *ww = w;
+
+ if (wsign < 0) {
+ ww = PyNumber_Negative(w);
+ if (ww == NULL)
+ goto Error;
+ }
+ else
+ Py_INCREF(ww);
+
+ fracpart = modf(i, &intpart);
+ vv = PyLong_FromDouble(intpart);
+ if (vv == NULL)
+ goto Error;
+
+ if (fracpart != 0.0) {
+ /* Shift left, and or a 1 bit into vv
+ * to represent the lost fraction.
+ */
+ PyObject *temp;
+
+ one = PyInt_FromLong(1);
+ if (one == NULL)
+ goto Error;
+
+ temp = PyNumber_Lshift(ww, one);
+ if (temp == NULL)
+ goto Error;
+ Py_DECREF(ww);
+ ww = temp;
+
+ temp = PyNumber_Lshift(vv, one);
+ if (temp == NULL)
+ goto Error;
+ Py_DECREF(vv);
+ vv = temp;
+
+ temp = PyNumber_Or(vv, one);
+ if (temp == NULL)
+ goto Error;
+ Py_DECREF(vv);
+ vv = temp;
+ }
+
+ r = PyObject_RichCompareBool(vv, ww, op);
+ if (r < 0)
+ goto Error;
+ result = PyBool_FromLong(r);
+ Error:
+ Py_XDECREF(vv);
+ Py_XDECREF(ww);
+ Py_XDECREF(one);
+ return result;
+ }
+ } /* else if (PyLong_Check(w)) */
+
+ else /* w isn't float, int, or long */
+ goto Unimplemented;
Compare:
- PyFPE_START_PROTECT("richcompare", return NULL)
- switch (op) {
- case Py_EQ:
- r = i == j;
- break;
- case Py_NE:
- r = i != j;
- break;
- case Py_LE:
- r = i <= j;
- break;
- case Py_GE:
- r = i >= j;
- break;
- case Py_LT:
- r = i < j;
- break;
- case Py_GT:
- r = i > j;
- break;
- }
- PyFPE_END_PROTECT(r)
- return PyBool_FromLong(r);
+ PyFPE_START_PROTECT("richcompare", return NULL)
+ switch (op) {
+ case Py_EQ:
+ r = i == j;
+ break;
+ case Py_NE:
+ r = i != j;
+ break;
+ case Py_LE:
+ r = i <= j;
+ break;
+ case Py_GE:
+ r = i >= j;
+ break;
+ case Py_LT:
+ r = i < j;
+ break;
+ case Py_GT:
+ r = i > j;
+ break;
+ }
+ PyFPE_END_PROTECT(r)
+ return PyBool_FromLong(r);
Unimplemented:
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static long
float_hash(PyFloatObject *v)
{
- return _Py_HashDouble(v->ob_fval);
+ return _Py_HashDouble(v->ob_fval);
}
static PyObject *
float_add(PyObject *v, PyObject *w)
{
- double a,b;
- CONVERT_TO_DOUBLE(v, a);
- CONVERT_TO_DOUBLE(w, b);
- PyFPE_START_PROTECT("add", return 0)
- a = a + b;
- PyFPE_END_PROTECT(a)
- return PyFloat_FromDouble(a);
+ double a,b;
+ CONVERT_TO_DOUBLE(v, a);
+ CONVERT_TO_DOUBLE(w, b);
+ PyFPE_START_PROTECT("add", return 0)
+ a = a + b;
+ PyFPE_END_PROTECT(a)
+ return PyFloat_FromDouble(a);
}
static PyObject *
float_sub(PyObject *v, PyObject *w)
{
- double a,b;
- CONVERT_TO_DOUBLE(v, a);
- CONVERT_TO_DOUBLE(w, b);
- PyFPE_START_PROTECT("subtract", return 0)
- a = a - b;
- PyFPE_END_PROTECT(a)
- return PyFloat_FromDouble(a);
+ double a,b;
+ CONVERT_TO_DOUBLE(v, a);
+ CONVERT_TO_DOUBLE(w, b);
+ PyFPE_START_PROTECT("subtract", return 0)
+ a = a - b;
+ PyFPE_END_PROTECT(a)
+ return PyFloat_FromDouble(a);
}
static PyObject *
float_mul(PyObject *v, PyObject *w)
{
- double a,b;
- CONVERT_TO_DOUBLE(v, a);
- CONVERT_TO_DOUBLE(w, b);
- PyFPE_START_PROTECT("multiply", return 0)
- a = a * b;
- PyFPE_END_PROTECT(a)
- return PyFloat_FromDouble(a);
+ double a,b;
+ CONVERT_TO_DOUBLE(v, a);
+ CONVERT_TO_DOUBLE(w, b);
+ PyFPE_START_PROTECT("multiply", return 0)
+ a = a * b;
+ PyFPE_END_PROTECT(a)
+ return PyFloat_FromDouble(a);
}
static PyObject *
float_div(PyObject *v, PyObject *w)
{
- double a,b;
- CONVERT_TO_DOUBLE(v, a);
- CONVERT_TO_DOUBLE(w, b);
+ double a,b;
+ CONVERT_TO_DOUBLE(v, a);
+ CONVERT_TO_DOUBLE(w, b);
#ifdef Py_NAN
- if (b == 0.0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "float division by zero");
- return NULL;
- }
+ if (b == 0.0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "float division by zero");
+ return NULL;
+ }
#endif
- PyFPE_START_PROTECT("divide", return 0)
- a = a / b;
- PyFPE_END_PROTECT(a)
- return PyFloat_FromDouble(a);
+ PyFPE_START_PROTECT("divide", return 0)
+ a = a / b;
+ PyFPE_END_PROTECT(a)
+ return PyFloat_FromDouble(a);
}
static PyObject *
float_classic_div(PyObject *v, PyObject *w)
{
- double a,b;
- CONVERT_TO_DOUBLE(v, a);
- CONVERT_TO_DOUBLE(w, b);
- if (Py_DivisionWarningFlag >= 2 &&
- PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
- return NULL;
+ double a,b;
+ CONVERT_TO_DOUBLE(v, a);
+ CONVERT_TO_DOUBLE(w, b);
+ if (Py_DivisionWarningFlag >= 2 &&
+ PyErr_Warn(PyExc_DeprecationWarning, "classic float division") < 0)
+ return NULL;
#ifdef Py_NAN
- if (b == 0.0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "float division by zero");
- return NULL;
- }
+ if (b == 0.0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "float division by zero");
+ return NULL;
+ }
#endif
- PyFPE_START_PROTECT("divide", return 0)
- a = a / b;
- PyFPE_END_PROTECT(a)
- return PyFloat_FromDouble(a);
+ PyFPE_START_PROTECT("divide", return 0)
+ a = a / b;
+ PyFPE_END_PROTECT(a)
+ return PyFloat_FromDouble(a);
}
static PyObject *
float_rem(PyObject *v, PyObject *w)
{
- double vx, wx;
- double mod;
- CONVERT_TO_DOUBLE(v, vx);
- CONVERT_TO_DOUBLE(w, wx);
+ double vx, wx;
+ double mod;
+ CONVERT_TO_DOUBLE(v, vx);
+ CONVERT_TO_DOUBLE(w, wx);
#ifdef Py_NAN
- if (wx == 0.0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "float modulo");
- return NULL;
- }
+ if (wx == 0.0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "float modulo");
+ return NULL;
+ }
#endif
- PyFPE_START_PROTECT("modulo", return 0)
- mod = fmod(vx, wx);
- /* note: checking mod*wx < 0 is incorrect -- underflows to
- 0 if wx < sqrt(smallest nonzero double) */
- if (mod && ((wx < 0) != (mod < 0))) {
- mod += wx;
- }
- PyFPE_END_PROTECT(mod)
- return PyFloat_FromDouble(mod);
+ PyFPE_START_PROTECT("modulo", return 0)
+ mod = fmod(vx, wx);
+ /* note: checking mod*wx < 0 is incorrect -- underflows to
+ 0 if wx < sqrt(smallest nonzero double) */
+ if (mod && ((wx < 0) != (mod < 0))) {
+ mod += wx;
+ }
+ PyFPE_END_PROTECT(mod)
+ return PyFloat_FromDouble(mod);
}
static PyObject *
float_divmod(PyObject *v, PyObject *w)
{
- double vx, wx;
- double div, mod, floordiv;
- CONVERT_TO_DOUBLE(v, vx);
- CONVERT_TO_DOUBLE(w, wx);
- if (wx == 0.0) {
- PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
- return NULL;
- }
- PyFPE_START_PROTECT("divmod", return 0)
- mod = fmod(vx, wx);
- /* fmod is typically exact, so vx-mod is *mathematically* an
- exact multiple of wx. But this is fp arithmetic, and fp
- vx - mod is an approximation; the result is that div may
- not be an exact integral value after the division, although
- it will always be very close to one.
- */
- div = (vx - mod) / wx;
- if (mod) {
- /* ensure the remainder has the same sign as the denominator */
- if ((wx < 0) != (mod < 0)) {
- mod += wx;
- div -= 1.0;
- }
- }
- else {
- /* the remainder is zero, and in the presence of signed zeroes
- fmod returns different results across platforms; ensure
- it has the same sign as the denominator; we'd like to do
- "mod = wx * 0.0", but that may get optimized away */
- mod *= mod; /* hide "mod = +0" from optimizer */
- if (wx < 0.0)
- mod = -mod;
- }
- /* snap quotient to nearest integral value */
- if (div) {
- floordiv = floor(div);
- if (div - floordiv > 0.5)
- floordiv += 1.0;
- }
- else {
- /* div is zero - get the same sign as the true quotient */
- div *= div; /* hide "div = +0" from optimizers */
- floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
- }
- PyFPE_END_PROTECT(floordiv)
- return Py_BuildValue("(dd)", floordiv, mod);
+ double vx, wx;
+ double div, mod, floordiv;
+ CONVERT_TO_DOUBLE(v, vx);
+ CONVERT_TO_DOUBLE(w, wx);
+ if (wx == 0.0) {
+ PyErr_SetString(PyExc_ZeroDivisionError, "float divmod()");
+ return NULL;
+ }
+ PyFPE_START_PROTECT("divmod", return 0)
+ mod = fmod(vx, wx);
+ /* fmod is typically exact, so vx-mod is *mathematically* an
+ exact multiple of wx. But this is fp arithmetic, and fp
+ vx - mod is an approximation; the result is that div may
+ not be an exact integral value after the division, although
+ it will always be very close to one.
+ */
+ div = (vx - mod) / wx;
+ if (mod) {
+ /* ensure the remainder has the same sign as the denominator */
+ if ((wx < 0) != (mod < 0)) {
+ mod += wx;
+ div -= 1.0;
+ }
+ }
+ else {
+ /* the remainder is zero, and in the presence of signed zeroes
+ fmod returns different results across platforms; ensure
+ it has the same sign as the denominator; we'd like to do
+ "mod = wx * 0.0", but that may get optimized away */
+ mod *= mod; /* hide "mod = +0" from optimizer */
+ if (wx < 0.0)
+ mod = -mod;
+ }
+ /* snap quotient to nearest integral value */
+ if (div) {
+ floordiv = floor(div);
+ if (div - floordiv > 0.5)
+ floordiv += 1.0;
+ }
+ else {
+ /* div is zero - get the same sign as the true quotient */
+ div *= div; /* hide "div = +0" from optimizers */
+ floordiv = div * vx / wx; /* zero w/ sign of vx/wx */
+ }
+ PyFPE_END_PROTECT(floordiv)
+ return Py_BuildValue("(dd)", floordiv, mod);
}
static PyObject *
float_floor_div(PyObject *v, PyObject *w)
{
- PyObject *t, *r;
-
- t = float_divmod(v, w);
- if (t == NULL || t == Py_NotImplemented)
- return t;
- assert(PyTuple_CheckExact(t));
- r = PyTuple_GET_ITEM(t, 0);
- Py_INCREF(r);
- Py_DECREF(t);
- return r;
+ PyObject *t, *r;
+
+ t = float_divmod(v, w);
+ if (t == NULL || t == Py_NotImplemented)
+ return t;
+ assert(PyTuple_CheckExact(t));
+ r = PyTuple_GET_ITEM(t, 0);
+ Py_INCREF(r);
+ Py_DECREF(t);
+ return r;
}
/* determine whether x is an odd integer or not; assumes that
@@ -798,122 +798,122 @@ float_floor_div(PyObject *v, PyObject *w)
static PyObject *
float_pow(PyObject *v, PyObject *w, PyObject *z)
{
- double iv, iw, ix;
- int negate_result = 0;
-
- if ((PyObject *)z != Py_None) {
- PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
- "allowed unless all arguments are integers");
- return NULL;
- }
-
- CONVERT_TO_DOUBLE(v, iv);
- CONVERT_TO_DOUBLE(w, iw);
-
- /* Sort out special cases here instead of relying on pow() */
- if (iw == 0) { /* v**0 is 1, even 0**0 */
- return PyFloat_FromDouble(1.0);
- }
- if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
- return PyFloat_FromDouble(iv);
- }
- if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
- return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
- }
- if (Py_IS_INFINITY(iw)) {
- /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
- * abs(v) > 1 (including case where v infinite)
- *
- * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
- * abs(v) > 1 (including case where v infinite)
- */
- iv = fabs(iv);
- if (iv == 1.0)
- return PyFloat_FromDouble(1.0);
- else if ((iw > 0.0) == (iv > 1.0))
- return PyFloat_FromDouble(fabs(iw)); /* return inf */
- else
- return PyFloat_FromDouble(0.0);
- }
- if (Py_IS_INFINITY(iv)) {
- /* (+-inf)**w is: inf for w positive, 0 for w negative; in
- * both cases, we need to add the appropriate sign if w is
- * an odd integer.
- */
- int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
- if (iw > 0.0)
- return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
- else
- return PyFloat_FromDouble(iw_is_odd ?
- copysign(0.0, iv) : 0.0);
- }
- if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
- (already dealt with above), and an error
- if w is negative. */
- int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
- if (iw < 0.0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "0.0 cannot be raised to a "
- "negative power");
- return NULL;
- }
- /* use correct sign if iw is odd */
- return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
- }
-
- if (iv < 0.0) {
- /* Whether this is an error is a mess, and bumps into libm
- * bugs so we have to figure it out ourselves.
- */
- if (iw != floor(iw)) {
- PyErr_SetString(PyExc_ValueError, "negative number "
- "cannot be raised to a fractional power");
- return NULL;
- }
- /* iw is an exact integer, albeit perhaps a very large
- * one. Replace iv by its absolute value and remember
- * to negate the pow result if iw is odd.
- */
- iv = -iv;
- negate_result = DOUBLE_IS_ODD_INTEGER(iw);
- }
-
- if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
- /* (-1) ** large_integer also ends up here. Here's an
- * extract from the comments for the previous
- * implementation explaining why this special case is
- * necessary:
- *
- * -1 raised to an exact integer should never be exceptional.
- * Alas, some libms (chiefly glibc as of early 2003) return
- * NaN and set EDOM on pow(-1, large_int) if the int doesn't
- * happen to be representable in a *C* integer. That's a
- * bug.
- */
- return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
- }
-
- /* Now iv and iw are finite, iw is nonzero, and iv is
- * positive and not equal to 1.0. We finally allow
- * the platform pow to step in and do the rest.
- */
- errno = 0;
- PyFPE_START_PROTECT("pow", return NULL)
- ix = pow(iv, iw);
- PyFPE_END_PROTECT(ix)
- Py_ADJUST_ERANGE1(ix);
- if (negate_result)
- ix = -ix;
-
- if (errno != 0) {
- /* We don't expect any errno value other than ERANGE, but
- * the range of libm bugs appears unbounded.
- */
- PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
- PyExc_ValueError);
- return NULL;
- }
- return PyFloat_FromDouble(ix);
+ double iv, iw, ix;
+ int negate_result = 0;
+
+ if ((PyObject *)z != Py_None) {
+ PyErr_SetString(PyExc_TypeError, "pow() 3rd argument not "
+ "allowed unless all arguments are integers");
+ return NULL;
+ }
+
+ CONVERT_TO_DOUBLE(v, iv);
+ CONVERT_TO_DOUBLE(w, iw);
+
+ /* Sort out special cases here instead of relying on pow() */
+ if (iw == 0) { /* v**0 is 1, even 0**0 */
+ return PyFloat_FromDouble(1.0);
+ }
+ if (Py_IS_NAN(iv)) { /* nan**w = nan, unless w == 0 */
+ return PyFloat_FromDouble(iv);
+ }
+ if (Py_IS_NAN(iw)) { /* v**nan = nan, unless v == 1; 1**nan = 1 */
+ return PyFloat_FromDouble(iv == 1.0 ? 1.0 : iw);
+ }
+ if (Py_IS_INFINITY(iw)) {
+ /* v**inf is: 0.0 if abs(v) < 1; 1.0 if abs(v) == 1; inf if
+ * abs(v) > 1 (including case where v infinite)
+ *
+ * v**-inf is: inf if abs(v) < 1; 1.0 if abs(v) == 1; 0.0 if
+ * abs(v) > 1 (including case where v infinite)
+ */
+ iv = fabs(iv);
+ if (iv == 1.0)
+ return PyFloat_FromDouble(1.0);
+ else if ((iw > 0.0) == (iv > 1.0))
+ return PyFloat_FromDouble(fabs(iw)); /* return inf */
+ else
+ return PyFloat_FromDouble(0.0);
+ }
+ if (Py_IS_INFINITY(iv)) {
+ /* (+-inf)**w is: inf for w positive, 0 for w negative; in
+ * both cases, we need to add the appropriate sign if w is
+ * an odd integer.
+ */
+ int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
+ if (iw > 0.0)
+ return PyFloat_FromDouble(iw_is_odd ? iv : fabs(iv));
+ else
+ return PyFloat_FromDouble(iw_is_odd ?
+ copysign(0.0, iv) : 0.0);
+ }
+ if (iv == 0.0) { /* 0**w is: 0 for w positive, 1 for w zero
+ (already dealt with above), and an error
+ if w is negative. */
+ int iw_is_odd = DOUBLE_IS_ODD_INTEGER(iw);
+ if (iw < 0.0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "0.0 cannot be raised to a "
+ "negative power");
+ return NULL;
+ }
+ /* use correct sign if iw is odd */
+ return PyFloat_FromDouble(iw_is_odd ? iv : 0.0);
+ }
+
+ if (iv < 0.0) {
+ /* Whether this is an error is a mess, and bumps into libm
+ * bugs so we have to figure it out ourselves.
+ */
+ if (iw != floor(iw)) {
+ PyErr_SetString(PyExc_ValueError, "negative number "
+ "cannot be raised to a fractional power");
+ return NULL;
+ }
+ /* iw is an exact integer, albeit perhaps a very large
+ * one. Replace iv by its absolute value and remember
+ * to negate the pow result if iw is odd.
+ */
+ iv = -iv;
+ negate_result = DOUBLE_IS_ODD_INTEGER(iw);
+ }
+
+ if (iv == 1.0) { /* 1**w is 1, even 1**inf and 1**nan */
+ /* (-1) ** large_integer also ends up here. Here's an
+ * extract from the comments for the previous
+ * implementation explaining why this special case is
+ * necessary:
+ *
+ * -1 raised to an exact integer should never be exceptional.
+ * Alas, some libms (chiefly glibc as of early 2003) return
+ * NaN and set EDOM on pow(-1, large_int) if the int doesn't
+ * happen to be representable in a *C* integer. That's a
+ * bug.
+ */
+ return PyFloat_FromDouble(negate_result ? -1.0 : 1.0);
+ }
+
+ /* Now iv and iw are finite, iw is nonzero, and iv is
+ * positive and not equal to 1.0. We finally allow
+ * the platform pow to step in and do the rest.
+ */
+ errno = 0;
+ PyFPE_START_PROTECT("pow", return NULL)
+ ix = pow(iv, iw);
+ PyFPE_END_PROTECT(ix)
+ Py_ADJUST_ERANGE1(ix);
+ if (negate_result)
+ ix = -ix;
+
+ if (errno != 0) {
+ /* We don't expect any errno value other than ERANGE, but
+ * the range of libm bugs appears unbounded.
+ */
+ PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
+ PyExc_ValueError);
+ return NULL;
+ }
+ return PyFloat_FromDouble(ix);
}
#undef DOUBLE_IS_ODD_INTEGER
@@ -921,129 +921,129 @@ float_pow(PyObject *v, PyObject *w, PyObject *z)
static PyObject *
float_neg(PyFloatObject *v)
{
- return PyFloat_FromDouble(-v->ob_fval);
+ return PyFloat_FromDouble(-v->ob_fval);
}
static PyObject *
float_abs(PyFloatObject *v)
{
- return PyFloat_FromDouble(fabs(v->ob_fval));
+ return PyFloat_FromDouble(fabs(v->ob_fval));
}
static int
float_nonzero(PyFloatObject *v)
{
- return v->ob_fval != 0.0;
+ return v->ob_fval != 0.0;
}
static int
float_coerce(PyObject **pv, PyObject **pw)
{
- if (PyInt_Check(*pw)) {
- long x = PyInt_AsLong(*pw);
- *pw = PyFloat_FromDouble((double)x);
- Py_INCREF(*pv);
- return 0;
- }
- else if (PyLong_Check(*pw)) {
- double x = PyLong_AsDouble(*pw);
- if (x == -1.0 && PyErr_Occurred())
- return -1;
- *pw = PyFloat_FromDouble(x);
- Py_INCREF(*pv);
- return 0;
- }
- else if (PyFloat_Check(*pw)) {
- Py_INCREF(*pv);
- Py_INCREF(*pw);
- return 0;
- }
- return 1; /* Can't do it */
+ if (PyInt_Check(*pw)) {
+ long x = PyInt_AsLong(*pw);
+ *pw = PyFloat_FromDouble((double)x);
+ Py_INCREF(*pv);
+ return 0;
+ }
+ else if (PyLong_Check(*pw)) {
+ double x = PyLong_AsDouble(*pw);
+ if (x == -1.0 && PyErr_Occurred())
+ return -1;
+ *pw = PyFloat_FromDouble(x);
+ Py_INCREF(*pv);
+ return 0;
+ }
+ else if (PyFloat_Check(*pw)) {
+ Py_INCREF(*pv);
+ Py_INCREF(*pw);
+ return 0;
+ }
+ return 1; /* Can't do it */
}
static PyObject *
float_is_integer(PyObject *v)
{
- double x = PyFloat_AsDouble(v);
- PyObject *o;
-
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- if (!Py_IS_FINITE(x))
- Py_RETURN_FALSE;
- errno = 0;
- PyFPE_START_PROTECT("is_integer", return NULL)
- o = (floor(x) == x) ? Py_True : Py_False;
- PyFPE_END_PROTECT(x)
- if (errno != 0) {
- PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
- PyExc_ValueError);
- return NULL;
- }
- Py_INCREF(o);
- return o;
+ double x = PyFloat_AsDouble(v);
+ PyObject *o;
+
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ if (!Py_IS_FINITE(x))
+ Py_RETURN_FALSE;
+ errno = 0;
+ PyFPE_START_PROTECT("is_integer", return NULL)
+ o = (floor(x) == x) ? Py_True : Py_False;
+ PyFPE_END_PROTECT(x)
+ if (errno != 0) {
+ PyErr_SetFromErrno(errno == ERANGE ? PyExc_OverflowError :
+ PyExc_ValueError);
+ return NULL;
+ }
+ Py_INCREF(o);
+ return o;
}
#if 0
static PyObject *
float_is_inf(PyObject *v)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_INFINITY(x));
+ double x = PyFloat_AsDouble(v);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_INFINITY(x));
}
static PyObject *
float_is_nan(PyObject *v)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_NAN(x));
+ double x = PyFloat_AsDouble(v);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_NAN(x));
}
static PyObject *
float_is_finite(PyObject *v)
{
- double x = PyFloat_AsDouble(v);
- if (x == -1.0 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)Py_IS_FINITE(x));
+ double x = PyFloat_AsDouble(v);
+ if (x == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)Py_IS_FINITE(x));
}
#endif
static PyObject *
float_trunc(PyObject *v)
{
- double x = PyFloat_AsDouble(v);
- double wholepart; /* integral portion of x, rounded toward 0 */
-
- (void)modf(x, &wholepart);
- /* Try to get out cheap if this fits in a Python int. The attempt
- * to cast to long must be protected, as C doesn't define what
- * happens if the double is too big to fit in a long. Some rare
- * systems raise an exception then (RISCOS was mentioned as one,
- * and someone using a non-default option on Sun also bumped into
- * that). Note that checking for >= and <= LONG_{MIN,MAX} would
- * still be vulnerable: if a long has more bits of precision than
- * a double, casting MIN/MAX to double may yield an approximation,
- * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
- * yield true from the C expression wholepart<=LONG_MAX, despite
- * that wholepart is actually greater than LONG_MAX.
- */
- if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
- const long aslong = (long)wholepart;
- return PyInt_FromLong(aslong);
- }
- return PyLong_FromDouble(wholepart);
+ double x = PyFloat_AsDouble(v);
+ double wholepart; /* integral portion of x, rounded toward 0 */
+
+ (void)modf(x, &wholepart);
+ /* Try to get out cheap if this fits in a Python int. The attempt
+ * to cast to long must be protected, as C doesn't define what
+ * happens if the double is too big to fit in a long. Some rare
+ * systems raise an exception then (RISCOS was mentioned as one,
+ * and someone using a non-default option on Sun also bumped into
+ * that). Note that checking for >= and <= LONG_{MIN,MAX} would
+ * still be vulnerable: if a long has more bits of precision than
+ * a double, casting MIN/MAX to double may yield an approximation,
+ * and if that's rounded up, then, e.g., wholepart=LONG_MAX+1 would
+ * yield true from the C expression wholepart<=LONG_MAX, despite
+ * that wholepart is actually greater than LONG_MAX.
+ */
+ if (LONG_MIN < wholepart && wholepart < LONG_MAX) {
+ const long aslong = (long)wholepart;
+ return PyInt_FromLong(aslong);
+ }
+ return PyLong_FromDouble(wholepart);
}
static PyObject *
float_long(PyObject *v)
{
- double x = PyFloat_AsDouble(v);
- return PyLong_FromDouble(x);
+ double x = PyFloat_AsDouble(v);
+ return PyLong_FromDouble(x);
}
/* _Py_double_round: rounds a finite nonzero double to the closest multiple of
@@ -1068,124 +1068,124 @@ float_long(PyObject *v)
PyObject *
_Py_double_round(double x, int ndigits) {
- double rounded, m;
- Py_ssize_t buflen, mybuflen=100;
- char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
- int decpt, sign, val, halfway_case;
- PyObject *result = NULL;
-
- /* The basic idea is very simple: convert and round the double to a
- decimal string using _Py_dg_dtoa, then convert that decimal string
- back to a double with _Py_dg_strtod. There's one minor difficulty:
- Python 2.x expects round to do round-half-away-from-zero, while
- _Py_dg_dtoa does round-half-to-even. So we need some way to detect
- and correct the halfway cases.
-
- Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
- some odd integer k. Or in other words, a rational number x is
- exactly halfway between two multiples of 10**-ndigits if its
- 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
- -ndigits. For ndigits >= 0 the latter condition is automatically
- satisfied for a binary float x, since any such float has
- nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
- integral multiple of 5**-ndigits; we can check this using fmod.
- For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
- to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
- 23 takes at least 54 bits of precision to represent exactly.
-
- Correction: a simple strategy for dealing with halfway cases is to
- (for the halfway cases only) call _Py_dg_dtoa with an argument of
- ndigits+1 instead of ndigits (thus doing an exact conversion to
- decimal), round the resulting string manually, and then convert
- back using _Py_dg_strtod.
- */
-
- /* nans, infinities and zeros should have already been dealt
- with by the caller (in this case, builtin_round) */
- assert(Py_IS_FINITE(x) && x != 0.0);
-
- /* find 2-valuation val of x */
- m = frexp(x, &val);
- while (m != floor(m)) {
- m *= 2.0;
- val--;
- }
-
- /* determine whether this is a halfway case */
- if (val == -ndigits-1) {
- if (ndigits >= 0)
- halfway_case = 1;
- else if (ndigits >= -FIVE_POW_LIMIT) {
- double five_pow = 1.0;
- int i;
- for (i=0; i < -ndigits; i++)
- five_pow *= 5.0;
- halfway_case = fmod(x, five_pow) == 0.0;
- }
- else
- halfway_case = 0;
- }
- else
- halfway_case = 0;
-
- /* round to a decimal string; use an extra place for halfway case */
- buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
- if (buf == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- buflen = buf_end - buf;
-
- /* in halfway case, do the round-half-away-from-zero manually */
- if (halfway_case) {
- int i, carry;
- /* sanity check: _Py_dg_dtoa should not have stripped
- any zeros from the result: there should be exactly
- ndigits+1 places following the decimal point, and
- the last digit in the buffer should be a '5'.*/
- assert(buflen - decpt == ndigits+1);
- assert(buf[buflen-1] == '5');
-
- /* increment and shift right at the same time. */
- decpt += 1;
- carry = 1;
- for (i=buflen-1; i-- > 0;) {
- carry += buf[i] - '0';
- buf[i+1] = carry % 10 + '0';
- carry /= 10;
- }
- buf[0] = carry + '0';
- }
-
- /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
- buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
- if (buflen + 8 > mybuflen) {
- mybuflen = buflen+8;
- mybuf = (char *)PyMem_Malloc(mybuflen);
- if (mybuf == NULL) {
- PyErr_NoMemory();
- goto exit;
- }
- }
- /* copy buf to mybuf, adding exponent, sign and leading 0 */
- PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
- buf, decpt - (int)buflen);
-
- /* and convert the resulting string back to a double */
- errno = 0;
- rounded = _Py_dg_strtod(mybuf, NULL);
- if (errno == ERANGE && fabs(rounded) >= 1.)
- PyErr_SetString(PyExc_OverflowError,
- "rounded value too large to represent");
- else
- result = PyFloat_FromDouble(rounded);
-
- /* done computing value; now clean up */
- if (mybuf != shortbuf)
- PyMem_Free(mybuf);
+ double rounded, m;
+ Py_ssize_t buflen, mybuflen=100;
+ char *buf, *buf_end, shortbuf[100], *mybuf=shortbuf;
+ int decpt, sign, val, halfway_case;
+ PyObject *result = NULL;
+
+ /* The basic idea is very simple: convert and round the double to a
+ decimal string using _Py_dg_dtoa, then convert that decimal string
+ back to a double with _Py_dg_strtod. There's one minor difficulty:
+ Python 2.x expects round to do round-half-away-from-zero, while
+ _Py_dg_dtoa does round-half-to-even. So we need some way to detect
+ and correct the halfway cases.
+
+ Detection: a halfway value has the form k * 0.5 * 10**-ndigits for
+ some odd integer k. Or in other words, a rational number x is
+ exactly halfway between two multiples of 10**-ndigits if its
+ 2-valuation is exactly -ndigits-1 and its 5-valuation is at least
+ -ndigits. For ndigits >= 0 the latter condition is automatically
+ satisfied for a binary float x, since any such float has
+ nonnegative 5-valuation. For 0 > ndigits >= -22, x needs to be an
+ integral multiple of 5**-ndigits; we can check this using fmod.
+ For -22 > ndigits, there are no halfway cases: 5**23 takes 54 bits
+ to represent exactly, so any odd multiple of 0.5 * 10**n for n >=
+ 23 takes at least 54 bits of precision to represent exactly.
+
+ Correction: a simple strategy for dealing with halfway cases is to
+ (for the halfway cases only) call _Py_dg_dtoa with an argument of
+ ndigits+1 instead of ndigits (thus doing an exact conversion to
+ decimal), round the resulting string manually, and then convert
+ back using _Py_dg_strtod.
+ */
+
+ /* nans, infinities and zeros should have already been dealt
+ with by the caller (in this case, builtin_round) */
+ assert(Py_IS_FINITE(x) && x != 0.0);
+
+ /* find 2-valuation val of x */
+ m = frexp(x, &val);
+ while (m != floor(m)) {
+ m *= 2.0;
+ val--;
+ }
+
+ /* determine whether this is a halfway case */
+ if (val == -ndigits-1) {
+ if (ndigits >= 0)
+ halfway_case = 1;
+ else if (ndigits >= -FIVE_POW_LIMIT) {
+ double five_pow = 1.0;
+ int i;
+ for (i=0; i < -ndigits; i++)
+ five_pow *= 5.0;
+ halfway_case = fmod(x, five_pow) == 0.0;
+ }
+ else
+ halfway_case = 0;
+ }
+ else
+ halfway_case = 0;
+
+ /* round to a decimal string; use an extra place for halfway case */
+ buf = _Py_dg_dtoa(x, 3, ndigits+halfway_case, &decpt, &sign, &buf_end);
+ if (buf == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ buflen = buf_end - buf;
+
+ /* in halfway case, do the round-half-away-from-zero manually */
+ if (halfway_case) {
+ int i, carry;
+ /* sanity check: _Py_dg_dtoa should not have stripped
+ any zeros from the result: there should be exactly
+ ndigits+1 places following the decimal point, and
+ the last digit in the buffer should be a '5'.*/
+ assert(buflen - decpt == ndigits+1);
+ assert(buf[buflen-1] == '5');
+
+ /* increment and shift right at the same time. */
+ decpt += 1;
+ carry = 1;
+ for (i=buflen-1; i-- > 0;) {
+ carry += buf[i] - '0';
+ buf[i+1] = carry % 10 + '0';
+ carry /= 10;
+ }
+ buf[0] = carry + '0';
+ }
+
+ /* Get new buffer if shortbuf is too small. Space needed <= buf_end -
+ buf + 8: (1 extra for '0', 1 for sign, 5 for exp, 1 for '\0'). */
+ if (buflen + 8 > mybuflen) {
+ mybuflen = buflen+8;
+ mybuf = (char *)PyMem_Malloc(mybuflen);
+ if (mybuf == NULL) {
+ PyErr_NoMemory();
+ goto exit;
+ }
+ }
+ /* copy buf to mybuf, adding exponent, sign and leading 0 */
+ PyOS_snprintf(mybuf, mybuflen, "%s0%se%d", (sign ? "-" : ""),
+ buf, decpt - (int)buflen);
+
+ /* and convert the resulting string back to a double */
+ errno = 0;
+ rounded = _Py_dg_strtod(mybuf, NULL);
+ if (errno == ERANGE && fabs(rounded) >= 1.)
+ PyErr_SetString(PyExc_OverflowError,
+ "rounded value too large to represent");
+ else
+ result = PyFloat_FromDouble(rounded);
+
+ /* done computing value; now clean up */
+ if (mybuf != shortbuf)
+ PyMem_Free(mybuf);
exit:
- _Py_dg_freedtoa(buf);
- return result;
+ _Py_dg_freedtoa(buf);
+ return result;
}
#undef FIVE_POW_LIMIT
@@ -1197,47 +1197,47 @@ _Py_double_round(double x, int ndigits) {
PyObject *
_Py_double_round(double x, int ndigits) {
- double pow1, pow2, y, z;
- if (ndigits >= 0) {
- if (ndigits > 22) {
- /* pow1 and pow2 are each safe from overflow, but
- pow1*pow2 ~= pow(10.0, ndigits) might overflow */
- pow1 = pow(10.0, (double)(ndigits-22));
- pow2 = 1e22;
- }
- else {
- pow1 = pow(10.0, (double)ndigits);
- pow2 = 1.0;
- }
- y = (x*pow1)*pow2;
- /* if y overflows, then rounded value is exactly x */
- if (!Py_IS_FINITE(y))
- return PyFloat_FromDouble(x);
- }
- else {
- pow1 = pow(10.0, (double)-ndigits);
- pow2 = 1.0; /* unused; silences a gcc compiler warning */
- y = x / pow1;
- }
-
- z = round(y);
- if (fabs(y-z) == 0.5)
- /* halfway between two integers; use round-away-from-zero */
- z = y + copysign(0.5, y);
-
- if (ndigits >= 0)
- z = (z / pow2) / pow1;
- else
- z *= pow1;
-
- /* if computation resulted in overflow, raise OverflowError */
- if (!Py_IS_FINITE(z)) {
- PyErr_SetString(PyExc_OverflowError,
- "overflow occurred during round");
- return NULL;
- }
-
- return PyFloat_FromDouble(z);
+ double pow1, pow2, y, z;
+ if (ndigits >= 0) {
+ if (ndigits > 22) {
+ /* pow1 and pow2 are each safe from overflow, but
+ pow1*pow2 ~= pow(10.0, ndigits) might overflow */
+ pow1 = pow(10.0, (double)(ndigits-22));
+ pow2 = 1e22;
+ }
+ else {
+ pow1 = pow(10.0, (double)ndigits);
+ pow2 = 1.0;
+ }
+ y = (x*pow1)*pow2;
+ /* if y overflows, then rounded value is exactly x */
+ if (!Py_IS_FINITE(y))
+ return PyFloat_FromDouble(x);
+ }
+ else {
+ pow1 = pow(10.0, (double)-ndigits);
+ pow2 = 1.0; /* unused; silences a gcc compiler warning */
+ y = x / pow1;
+ }
+
+ z = round(y);
+ if (fabs(y-z) == 0.5)
+ /* halfway between two integers; use round-away-from-zero */
+ z = y + copysign(0.5, y);
+
+ if (ndigits >= 0)
+ z = (z / pow2) / pow1;
+ else
+ z *= pow1;
+
+ /* if computation resulted in overflow, raise OverflowError */
+ if (!Py_IS_FINITE(z)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "overflow occurred during round");
+ return NULL;
+ }
+
+ return PyFloat_FromDouble(z);
}
#endif /* PY_NO_SHORT_FLOAT_REPR */
@@ -1245,11 +1245,11 @@ _Py_double_round(double x, int ndigits) {
static PyObject *
float_float(PyObject *v)
{
- if (PyFloat_CheckExact(v))
- Py_INCREF(v);
- else
- v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
- return v;
+ if (PyFloat_CheckExact(v))
+ Py_INCREF(v);
+ else
+ v = PyFloat_FromDouble(((PyFloatObject *)v)->ob_fval);
+ return v;
}
/* turn ASCII hex characters into integer values and vice versa */
@@ -1257,73 +1257,73 @@ float_float(PyObject *v)
static char
char_from_hex(int x)
{
- assert(0 <= x && x < 16);
- return "0123456789abcdef"[x];
+ assert(0 <= x && x < 16);
+ return "0123456789abcdef"[x];
}
static int
hex_from_char(char c) {
- int x;
- switch(c) {
- case '0':
- x = 0;
- break;
- case '1':
- x = 1;
- break;
- case '2':
- x = 2;
- break;
- case '3':
- x = 3;
- break;
- case '4':
- x = 4;
- break;
- case '5':
- x = 5;
- break;
- case '6':
- x = 6;
- break;
- case '7':
- x = 7;
- break;
- case '8':
- x = 8;
- break;
- case '9':
- x = 9;
- break;
- case 'a':
- case 'A':
- x = 10;
- break;
- case 'b':
- case 'B':
- x = 11;
- break;
- case 'c':
- case 'C':
- x = 12;
- break;
- case 'd':
- case 'D':
- x = 13;
- break;
- case 'e':
- case 'E':
- x = 14;
- break;
- case 'f':
- case 'F':
- x = 15;
- break;
- default:
- x = -1;
- break;
- }
- return x;
+ int x;
+ switch(c) {
+ case '0':
+ x = 0;
+ break;
+ case '1':
+ x = 1;
+ break;
+ case '2':
+ x = 2;
+ break;
+ case '3':
+ x = 3;
+ break;
+ case '4':
+ x = 4;
+ break;
+ case '5':
+ x = 5;
+ break;
+ case '6':
+ x = 6;
+ break;
+ case '7':
+ x = 7;
+ break;
+ case '8':
+ x = 8;
+ break;
+ case '9':
+ x = 9;
+ break;
+ case 'a':
+ case 'A':
+ x = 10;
+ break;
+ case 'b':
+ case 'B':
+ x = 11;
+ break;
+ case 'c':
+ case 'C':
+ x = 12;
+ break;
+ case 'd':
+ case 'D':
+ x = 13;
+ break;
+ case 'e':
+ case 'E':
+ x = 14;
+ break;
+ case 'f':
+ case 'F':
+ x = 15;
+ break;
+ default:
+ x = -1;
+ break;
+ }
+ return x;
}
/* convert a float to a hexadecimal string */
@@ -1335,54 +1335,54 @@ hex_from_char(char c) {
static PyObject *
float_hex(PyObject *v)
{
- double x, m;
- int e, shift, i, si, esign;
- /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
- trailing NUL byte. */
- char s[(TOHEX_NBITS-1)/4+3];
-
- CONVERT_TO_DOUBLE(v, x);
-
- if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
- return float_str((PyFloatObject *)v);
-
- if (x == 0.0) {
- if(copysign(1.0, x) == -1.0)
- return PyString_FromString("-0x0.0p+0");
- else
- return PyString_FromString("0x0.0p+0");
- }
-
- m = frexp(fabs(x), &e);
- shift = 1 - MAX(DBL_MIN_EXP - e, 0);
- m = ldexp(m, shift);
- e -= shift;
-
- si = 0;
- s[si] = char_from_hex((int)m);
- si++;
- m -= (int)m;
- s[si] = '.';
- si++;
- for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
- m *= 16.0;
- s[si] = char_from_hex((int)m);
- si++;
- m -= (int)m;
- }
- s[si] = '\0';
-
- if (e < 0) {
- esign = (int)'-';
- e = -e;
- }
- else
- esign = (int)'+';
-
- if (x < 0.0)
- return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
- else
- return PyString_FromFormat("0x%sp%c%d", s, esign, e);
+ double x, m;
+ int e, shift, i, si, esign;
+ /* Space for 1+(TOHEX_NBITS-1)/4 digits, a decimal point, and the
+ trailing NUL byte. */
+ char s[(TOHEX_NBITS-1)/4+3];
+
+ CONVERT_TO_DOUBLE(v, x);
+
+ if (Py_IS_NAN(x) || Py_IS_INFINITY(x))
+ return float_str((PyFloatObject *)v);
+
+ if (x == 0.0) {
+ if(copysign(1.0, x) == -1.0)
+ return PyString_FromString("-0x0.0p+0");
+ else
+ return PyString_FromString("0x0.0p+0");
+ }
+
+ m = frexp(fabs(x), &e);
+ shift = 1 - MAX(DBL_MIN_EXP - e, 0);
+ m = ldexp(m, shift);
+ e -= shift;
+
+ si = 0;
+ s[si] = char_from_hex((int)m);
+ si++;
+ m -= (int)m;
+ s[si] = '.';
+ si++;
+ for (i=0; i < (TOHEX_NBITS-1)/4; i++) {
+ m *= 16.0;
+ s[si] = char_from_hex((int)m);
+ si++;
+ m -= (int)m;
+ }
+ s[si] = '\0';
+
+ if (e < 0) {
+ esign = (int)'-';
+ e = -e;
+ }
+ else
+ esign = (int)'+';
+
+ if (x < 0.0)
+ return PyString_FromFormat("-0x%sp%c%d", s, esign, e);
+ else
+ return PyString_FromFormat("0x%sp%c%d", s, esign, e);
}
PyDoc_STRVAR(float_hex_doc,
@@ -1401,11 +1401,11 @@ Return a hexadecimal representation of a floating-point number.\n\
static int
case_insensitive_match(const char *s, const char *t)
{
- while(*t && Py_TOLOWER(*s) == *t) {
- s++;
- t++;
- }
- return *t ? 0 : 1;
+ while(*t && Py_TOLOWER(*s) == *t) {
+ s++;
+ t++;
+ }
+ return *t ? 0 : 1;
}
/* Convert a hexadecimal string to a float. */
@@ -1413,250 +1413,250 @@ case_insensitive_match(const char *s, const char *t)
static PyObject *
float_fromhex(PyObject *cls, PyObject *arg)
{
- PyObject *result_as_float, *result;
- double x;
- long exp, top_exp, lsb, key_digit;
- char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
- int half_eps, digit, round_up, sign=1;
- Py_ssize_t length, ndigits, fdigits, i;
-
- /*
- * For the sake of simplicity and correctness, we impose an artificial
- * limit on ndigits, the total number of hex digits in the coefficient
- * The limit is chosen to ensure that, writing exp for the exponent,
- *
- * (1) if exp > LONG_MAX/2 then the value of the hex string is
- * guaranteed to overflow (provided it's nonzero)
- *
- * (2) if exp < LONG_MIN/2 then the value of the hex string is
- * guaranteed to underflow to 0.
- *
- * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
- * overflow in the calculation of exp and top_exp below.
- *
- * More specifically, ndigits is assumed to satisfy the following
- * inequalities:
- *
- * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
- * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
- *
- * If either of these inequalities is not satisfied, a ValueError is
- * raised. Otherwise, write x for the value of the hex string, and
- * assume x is nonzero. Then
- *
- * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
- *
- * Now if exp > LONG_MAX/2 then:
- *
- * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
- * = DBL_MAX_EXP
- *
- * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
- * double, so overflows. If exp < LONG_MIN/2, then
- *
- * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
- * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
- * = DBL_MIN_EXP - DBL_MANT_DIG - 1
- *
- * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
- * when converted to a C double.
- *
- * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
- * exp+4*ndigits and exp-4*ndigits are within the range of a long.
- */
-
- if (PyString_AsStringAndSize(arg, &s, &length))
- return NULL;
- s_end = s + length;
-
- /********************
- * Parse the string *
- ********************/
-
- /* leading whitespace and optional sign */
- while (Py_ISSPACE(*s))
- s++;
- if (*s == '-') {
- s++;
- sign = -1;
- }
- else if (*s == '+')
- s++;
-
- /* infinities and nans */
- if (*s == 'i' || *s == 'I') {
- if (!case_insensitive_match(s+1, "nf"))
- goto parse_error;
- s += 3;
- x = Py_HUGE_VAL;
- if (case_insensitive_match(s, "inity"))
- s += 5;
- goto finished;
- }
- if (*s == 'n' || *s == 'N') {
- if (!case_insensitive_match(s+1, "an"))
- goto parse_error;
- s += 3;
- x = Py_NAN;
- goto finished;
- }
-
- /* [0x] */
- s_store = s;
- if (*s == '0') {
- s++;
- if (*s == 'x' || *s == 'X')
- s++;
- else
- s = s_store;
- }
-
- /* coefficient: <integer> [. <fraction>] */
- coeff_start = s;
- while (hex_from_char(*s) >= 0)
- s++;
- s_store = s;
- if (*s == '.') {
- s++;
- while (hex_from_char(*s) >= 0)
- s++;
- coeff_end = s-1;
- }
- else
- coeff_end = s;
-
- /* ndigits = total # of hex digits; fdigits = # after point */
- ndigits = coeff_end - coeff_start;
- fdigits = coeff_end - s_store;
- if (ndigits == 0)
- goto parse_error;
- if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
- LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
- goto insane_length_error;
-
- /* [p <exponent>] */
- if (*s == 'p' || *s == 'P') {
- s++;
- exp_start = s;
- if (*s == '-' || *s == '+')
- s++;
- if (!('0' <= *s && *s <= '9'))
- goto parse_error;
- s++;
- while ('0' <= *s && *s <= '9')
- s++;
- exp = strtol(exp_start, NULL, 10);
- }
- else
- exp = 0;
+ PyObject *result_as_float, *result;
+ double x;
+ long exp, top_exp, lsb, key_digit;
+ char *s, *coeff_start, *s_store, *coeff_end, *exp_start, *s_end;
+ int half_eps, digit, round_up, sign=1;
+ Py_ssize_t length, ndigits, fdigits, i;
+
+ /*
+ * For the sake of simplicity and correctness, we impose an artificial
+ * limit on ndigits, the total number of hex digits in the coefficient
+ * The limit is chosen to ensure that, writing exp for the exponent,
+ *
+ * (1) if exp > LONG_MAX/2 then the value of the hex string is
+ * guaranteed to overflow (provided it's nonzero)
+ *
+ * (2) if exp < LONG_MIN/2 then the value of the hex string is
+ * guaranteed to underflow to 0.
+ *
+ * (3) if LONG_MIN/2 <= exp <= LONG_MAX/2 then there's no danger of
+ * overflow in the calculation of exp and top_exp below.
+ *
+ * More specifically, ndigits is assumed to satisfy the following
+ * inequalities:
+ *
+ * 4*ndigits <= DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2
+ * 4*ndigits <= LONG_MAX/2 + 1 - DBL_MAX_EXP
+ *
+ * If either of these inequalities is not satisfied, a ValueError is
+ * raised. Otherwise, write x for the value of the hex string, and
+ * assume x is nonzero. Then
+ *
+ * 2**(exp-4*ndigits) <= |x| < 2**(exp+4*ndigits).
+ *
+ * Now if exp > LONG_MAX/2 then:
+ *
+ * exp - 4*ndigits >= LONG_MAX/2 + 1 - (LONG_MAX/2 + 1 - DBL_MAX_EXP)
+ * = DBL_MAX_EXP
+ *
+ * so |x| >= 2**DBL_MAX_EXP, which is too large to be stored in C
+ * double, so overflows. If exp < LONG_MIN/2, then
+ *
+ * exp + 4*ndigits <= LONG_MIN/2 - 1 + (
+ * DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2)
+ * = DBL_MIN_EXP - DBL_MANT_DIG - 1
+ *
+ * and so |x| < 2**(DBL_MIN_EXP-DBL_MANT_DIG-1), hence underflows to 0
+ * when converted to a C double.
+ *
+ * It's easy to show that if LONG_MIN/2 <= exp <= LONG_MAX/2 then both
+ * exp+4*ndigits and exp-4*ndigits are within the range of a long.
+ */
+
+ if (PyString_AsStringAndSize(arg, &s, &length))
+ return NULL;
+ s_end = s + length;
+
+ /********************
+ * Parse the string *
+ ********************/
+
+ /* leading whitespace and optional sign */
+ while (Py_ISSPACE(*s))
+ s++;
+ if (*s == '-') {
+ s++;
+ sign = -1;
+ }
+ else if (*s == '+')
+ s++;
+
+ /* infinities and nans */
+ if (*s == 'i' || *s == 'I') {
+ if (!case_insensitive_match(s+1, "nf"))
+ goto parse_error;
+ s += 3;
+ x = Py_HUGE_VAL;
+ if (case_insensitive_match(s, "inity"))
+ s += 5;
+ goto finished;
+ }
+ if (*s == 'n' || *s == 'N') {
+ if (!case_insensitive_match(s+1, "an"))
+ goto parse_error;
+ s += 3;
+ x = Py_NAN;
+ goto finished;
+ }
+
+ /* [0x] */
+ s_store = s;
+ if (*s == '0') {
+ s++;
+ if (*s == 'x' || *s == 'X')
+ s++;
+ else
+ s = s_store;
+ }
+
+ /* coefficient: <integer> [. <fraction>] */
+ coeff_start = s;
+ while (hex_from_char(*s) >= 0)
+ s++;
+ s_store = s;
+ if (*s == '.') {
+ s++;
+ while (hex_from_char(*s) >= 0)
+ s++;
+ coeff_end = s-1;
+ }
+ else
+ coeff_end = s;
+
+ /* ndigits = total # of hex digits; fdigits = # after point */
+ ndigits = coeff_end - coeff_start;
+ fdigits = coeff_end - s_store;
+ if (ndigits == 0)
+ goto parse_error;
+ if (ndigits > MIN(DBL_MIN_EXP - DBL_MANT_DIG - LONG_MIN/2,
+ LONG_MAX/2 + 1 - DBL_MAX_EXP)/4)
+ goto insane_length_error;
+
+ /* [p <exponent>] */
+ if (*s == 'p' || *s == 'P') {
+ s++;
+ exp_start = s;
+ if (*s == '-' || *s == '+')
+ s++;
+ if (!('0' <= *s && *s <= '9'))
+ goto parse_error;
+ s++;
+ while ('0' <= *s && *s <= '9')
+ s++;
+ exp = strtol(exp_start, NULL, 10);
+ }
+ else
+ exp = 0;
/* for 0 <= j < ndigits, HEX_DIGIT(j) gives the jth most significant digit */
-#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
- coeff_end-(j) : \
- coeff_end-1-(j)))
-
- /*******************************************
- * Compute rounded value of the hex string *
- *******************************************/
-
- /* Discard leading zeros, and catch extreme overflow and underflow */
- while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
- ndigits--;
- if (ndigits == 0 || exp < LONG_MIN/2) {
- x = 0.0;
- goto finished;
- }
- if (exp > LONG_MAX/2)
- goto overflow_error;
-
- /* Adjust exponent for fractional part. */
- exp = exp - 4*((long)fdigits);
-
- /* top_exp = 1 more than exponent of most sig. bit of coefficient */
- top_exp = exp + 4*((long)ndigits - 1);
- for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
- top_exp++;
-
- /* catch almost all nonextreme cases of overflow and underflow here */
- if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
- x = 0.0;
- goto finished;
- }
- if (top_exp > DBL_MAX_EXP)
- goto overflow_error;
-
- /* lsb = exponent of least significant bit of the *rounded* value.
- This is top_exp - DBL_MANT_DIG unless result is subnormal. */
- lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
-
- x = 0.0;
- if (exp >= lsb) {
- /* no rounding required */
- for (i = ndigits-1; i >= 0; i--)
- x = 16.0*x + HEX_DIGIT(i);
- x = ldexp(x, (int)(exp));
- goto finished;
- }
- /* rounding required. key_digit is the index of the hex digit
- containing the first bit to be rounded away. */
- half_eps = 1 << (int)((lsb - exp - 1) % 4);
- key_digit = (lsb - exp - 1) / 4;
- for (i = ndigits-1; i > key_digit; i--)
- x = 16.0*x + HEX_DIGIT(i);
- digit = HEX_DIGIT(key_digit);
- x = 16.0*x + (double)(digit & (16-2*half_eps));
-
- /* round-half-even: round up if bit lsb-1 is 1 and at least one of
- bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
- if ((digit & half_eps) != 0) {
- round_up = 0;
- if ((digit & (3*half_eps-1)) != 0 ||
- (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
- round_up = 1;
- else
- for (i = key_digit-1; i >= 0; i--)
- if (HEX_DIGIT(i) != 0) {
- round_up = 1;
- break;
- }
- if (round_up == 1) {
- x += 2*half_eps;
- if (top_exp == DBL_MAX_EXP &&
- x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
- /* overflow corner case: pre-rounded value <
- 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
- goto overflow_error;
- }
- }
- x = ldexp(x, (int)(exp+4*key_digit));
+#define HEX_DIGIT(j) hex_from_char(*((j) < fdigits ? \
+ coeff_end-(j) : \
+ coeff_end-1-(j)))
+
+ /*******************************************
+ * Compute rounded value of the hex string *
+ *******************************************/
+
+ /* Discard leading zeros, and catch extreme overflow and underflow */
+ while (ndigits > 0 && HEX_DIGIT(ndigits-1) == 0)
+ ndigits--;
+ if (ndigits == 0 || exp < LONG_MIN/2) {
+ x = 0.0;
+ goto finished;
+ }
+ if (exp > LONG_MAX/2)
+ goto overflow_error;
+
+ /* Adjust exponent for fractional part. */
+ exp = exp - 4*((long)fdigits);
+
+ /* top_exp = 1 more than exponent of most sig. bit of coefficient */
+ top_exp = exp + 4*((long)ndigits - 1);
+ for (digit = HEX_DIGIT(ndigits-1); digit != 0; digit /= 2)
+ top_exp++;
+
+ /* catch almost all nonextreme cases of overflow and underflow here */
+ if (top_exp < DBL_MIN_EXP - DBL_MANT_DIG) {
+ x = 0.0;
+ goto finished;
+ }
+ if (top_exp > DBL_MAX_EXP)
+ goto overflow_error;
+
+ /* lsb = exponent of least significant bit of the *rounded* value.
+ This is top_exp - DBL_MANT_DIG unless result is subnormal. */
+ lsb = MAX(top_exp, (long)DBL_MIN_EXP) - DBL_MANT_DIG;
+
+ x = 0.0;
+ if (exp >= lsb) {
+ /* no rounding required */
+ for (i = ndigits-1; i >= 0; i--)
+ x = 16.0*x + HEX_DIGIT(i);
+ x = ldexp(x, (int)(exp));
+ goto finished;
+ }
+ /* rounding required. key_digit is the index of the hex digit
+ containing the first bit to be rounded away. */
+ half_eps = 1 << (int)((lsb - exp - 1) % 4);
+ key_digit = (lsb - exp - 1) / 4;
+ for (i = ndigits-1; i > key_digit; i--)
+ x = 16.0*x + HEX_DIGIT(i);
+ digit = HEX_DIGIT(key_digit);
+ x = 16.0*x + (double)(digit & (16-2*half_eps));
+
+ /* round-half-even: round up if bit lsb-1 is 1 and at least one of
+ bits lsb, lsb-2, lsb-3, lsb-4, ... is 1. */
+ if ((digit & half_eps) != 0) {
+ round_up = 0;
+ if ((digit & (3*half_eps-1)) != 0 ||
+ (half_eps == 8 && (HEX_DIGIT(key_digit+1) & 1) != 0))
+ round_up = 1;
+ else
+ for (i = key_digit-1; i >= 0; i--)
+ if (HEX_DIGIT(i) != 0) {
+ round_up = 1;
+ break;
+ }
+ if (round_up == 1) {
+ x += 2*half_eps;
+ if (top_exp == DBL_MAX_EXP &&
+ x == ldexp((double)(2*half_eps), DBL_MANT_DIG))
+ /* overflow corner case: pre-rounded value <
+ 2**DBL_MAX_EXP; rounded=2**DBL_MAX_EXP. */
+ goto overflow_error;
+ }
+ }
+ x = ldexp(x, (int)(exp+4*key_digit));
finished:
- /* optional trailing whitespace leading to the end of the string */
- while (Py_ISSPACE(*s))
- s++;
- if (s != s_end)
- goto parse_error;
- result_as_float = Py_BuildValue("(d)", sign * x);
- if (result_as_float == NULL)
- return NULL;
- result = PyObject_CallObject(cls, result_as_float);
- Py_DECREF(result_as_float);
- return result;
+ /* optional trailing whitespace leading to the end of the string */
+ while (Py_ISSPACE(*s))
+ s++;
+ if (s != s_end)
+ goto parse_error;
+ result_as_float = Py_BuildValue("(d)", sign * x);
+ if (result_as_float == NULL)
+ return NULL;
+ result = PyObject_CallObject(cls, result_as_float);
+ Py_DECREF(result_as_float);
+ return result;
overflow_error:
- PyErr_SetString(PyExc_OverflowError,
- "hexadecimal value too large to represent as a float");
- return NULL;
+ PyErr_SetString(PyExc_OverflowError,
+ "hexadecimal value too large to represent as a float");
+ return NULL;
parse_error:
- PyErr_SetString(PyExc_ValueError,
- "invalid hexadecimal floating-point string");
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "invalid hexadecimal floating-point string");
+ return NULL;
insane_length_error:
- PyErr_SetString(PyExc_ValueError,
- "hexadecimal string too long to convert");
- return NULL;
+ PyErr_SetString(PyExc_ValueError,
+ "hexadecimal string too long to convert");
+ return NULL;
}
PyDoc_STRVAR(float_fromhex_doc,
@@ -1672,85 +1672,85 @@ Create a floating-point number from a hexadecimal string.\n\
static PyObject *
float_as_integer_ratio(PyObject *v, PyObject *unused)
{
- double self;
- double float_part;
- int exponent;
- int i;
-
- PyObject *prev;
- PyObject *py_exponent = NULL;
- PyObject *numerator = NULL;
- PyObject *denominator = NULL;
- PyObject *result_pair = NULL;
- PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
+ double self;
+ double float_part;
+ int exponent;
+ int i;
+
+ PyObject *prev;
+ PyObject *py_exponent = NULL;
+ PyObject *numerator = NULL;
+ PyObject *denominator = NULL;
+ PyObject *result_pair = NULL;
+ PyNumberMethods *long_methods = PyLong_Type.tp_as_number;
#define INPLACE_UPDATE(obj, call) \
- prev = obj; \
- obj = call; \
- Py_DECREF(prev); \
+ prev = obj; \
+ obj = call; \
+ Py_DECREF(prev); \
- CONVERT_TO_DOUBLE(v, self);
+ CONVERT_TO_DOUBLE(v, self);
- if (Py_IS_INFINITY(self)) {
- PyErr_SetString(PyExc_OverflowError,
- "Cannot pass infinity to float.as_integer_ratio.");
- return NULL;
- }
+ if (Py_IS_INFINITY(self)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "Cannot pass infinity to float.as_integer_ratio.");
+ return NULL;
+ }
#ifdef Py_NAN
- if (Py_IS_NAN(self)) {
- PyErr_SetString(PyExc_ValueError,
- "Cannot pass NaN to float.as_integer_ratio.");
- return NULL;
- }
+ if (Py_IS_NAN(self)) {
+ PyErr_SetString(PyExc_ValueError,
+ "Cannot pass NaN to float.as_integer_ratio.");
+ return NULL;
+ }
#endif
- PyFPE_START_PROTECT("as_integer_ratio", goto error);
- float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
- PyFPE_END_PROTECT(float_part);
-
- for (i=0; i<300 && float_part != floor(float_part) ; i++) {
- float_part *= 2.0;
- exponent--;
- }
- /* self == float_part * 2**exponent exactly and float_part is integral.
- If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
- to be truncated by PyLong_FromDouble(). */
-
- numerator = PyLong_FromDouble(float_part);
- if (numerator == NULL) goto error;
-
- /* fold in 2**exponent */
- denominator = PyLong_FromLong(1);
- py_exponent = PyLong_FromLong(labs((long)exponent));
- if (py_exponent == NULL) goto error;
- INPLACE_UPDATE(py_exponent,
- long_methods->nb_lshift(denominator, py_exponent));
- if (py_exponent == NULL) goto error;
- if (exponent > 0) {
- INPLACE_UPDATE(numerator,
- long_methods->nb_multiply(numerator, py_exponent));
- if (numerator == NULL) goto error;
- }
- else {
- Py_DECREF(denominator);
- denominator = py_exponent;
- py_exponent = NULL;
- }
-
- /* Returns ints instead of longs where possible */
- INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
- if (numerator == NULL) goto error;
- INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
- if (denominator == NULL) goto error;
-
- result_pair = PyTuple_Pack(2, numerator, denominator);
+ PyFPE_START_PROTECT("as_integer_ratio", goto error);
+ float_part = frexp(self, &exponent); /* self == float_part * 2**exponent exactly */
+ PyFPE_END_PROTECT(float_part);
+
+ for (i=0; i<300 && float_part != floor(float_part) ; i++) {
+ float_part *= 2.0;
+ exponent--;
+ }
+ /* self == float_part * 2**exponent exactly and float_part is integral.
+ If FLT_RADIX != 2, the 300 steps may leave a tiny fractional part
+ to be truncated by PyLong_FromDouble(). */
+
+ numerator = PyLong_FromDouble(float_part);
+ if (numerator == NULL) goto error;
+
+ /* fold in 2**exponent */
+ denominator = PyLong_FromLong(1);
+ py_exponent = PyLong_FromLong(labs((long)exponent));
+ if (py_exponent == NULL) goto error;
+ INPLACE_UPDATE(py_exponent,
+ long_methods->nb_lshift(denominator, py_exponent));
+ if (py_exponent == NULL) goto error;
+ if (exponent > 0) {
+ INPLACE_UPDATE(numerator,
+ long_methods->nb_multiply(numerator, py_exponent));
+ if (numerator == NULL) goto error;
+ }
+ else {
+ Py_DECREF(denominator);
+ denominator = py_exponent;
+ py_exponent = NULL;
+ }
+
+ /* Returns ints instead of longs where possible */
+ INPLACE_UPDATE(numerator, PyNumber_Int(numerator));
+ if (numerator == NULL) goto error;
+ INPLACE_UPDATE(denominator, PyNumber_Int(denominator));
+ if (denominator == NULL) goto error;
+
+ result_pair = PyTuple_Pack(2, numerator, denominator);
#undef INPLACE_UPDATE
error:
- Py_XDECREF(py_exponent);
- Py_XDECREF(denominator);
- Py_XDECREF(numerator);
- return result_pair;
+ Py_XDECREF(py_exponent);
+ Py_XDECREF(denominator);
+ Py_XDECREF(numerator);
+ return result_pair;
}
PyDoc_STRVAR(float_as_integer_ratio_doc,
@@ -1774,18 +1774,18 @@ float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *x = Py_False; /* Integer zero */
- static char *kwlist[] = {"x", 0};
-
- if (type != &PyFloat_Type)
- return float_subtype_new(type, args, kwds); /* Wimp out */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
- return NULL;
- /* If it's a string, but not a string subclass, use
- PyFloat_FromString. */
- if (PyString_CheckExact(x))
- return PyFloat_FromString(x, NULL);
- return PyNumber_Float(x);
+ PyObject *x = Py_False; /* Integer zero */
+ static char *kwlist[] = {"x", 0};
+
+ if (type != &PyFloat_Type)
+ return float_subtype_new(type, args, kwds); /* Wimp out */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:float", kwlist, &x))
+ return NULL;
+ /* If it's a string, but not a string subclass, use
+ PyFloat_FromString. */
+ if (PyString_CheckExact(x))
+ return PyFloat_FromString(x, NULL);
+ return PyNumber_Float(x);
}
/* Wimpy, slow approach to tp_new calls for subtypes of float:
@@ -1796,33 +1796,33 @@ float_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
float_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *tmp, *newobj;
-
- assert(PyType_IsSubtype(type, &PyFloat_Type));
- tmp = float_new(&PyFloat_Type, args, kwds);
- if (tmp == NULL)
- return NULL;
- assert(PyFloat_CheckExact(tmp));
- newobj = type->tp_alloc(type, 0);
- if (newobj == NULL) {
- Py_DECREF(tmp);
- return NULL;
- }
- ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
- Py_DECREF(tmp);
- return newobj;
+ PyObject *tmp, *newobj;
+
+ assert(PyType_IsSubtype(type, &PyFloat_Type));
+ tmp = float_new(&PyFloat_Type, args, kwds);
+ if (tmp == NULL)
+ return NULL;
+ assert(PyFloat_CheckExact(tmp));
+ newobj = type->tp_alloc(type, 0);
+ if (newobj == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ ((PyFloatObject *)newobj)->ob_fval = ((PyFloatObject *)tmp)->ob_fval;
+ Py_DECREF(tmp);
+ return newobj;
}
static PyObject *
float_getnewargs(PyFloatObject *v)
{
- return Py_BuildValue("(d)", v->ob_fval);
+ return Py_BuildValue("(d)", v->ob_fval);
}
/* this is for the benefit of the pack/unpack routines below */
typedef enum {
- unknown_format, ieee_big_endian_format, ieee_little_endian_format
+ unknown_format, ieee_big_endian_format, ieee_little_endian_format
} float_format_type;
static float_format_type double_format, float_format;
@@ -1831,40 +1831,40 @@ static float_format_type detected_double_format, detected_float_format;
static PyObject *
float_getformat(PyTypeObject *v, PyObject* arg)
{
- char* s;
- float_format_type r;
-
- if (!PyString_Check(arg)) {
- PyErr_Format(PyExc_TypeError,
- "__getformat__() argument must be string, not %.500s",
- Py_TYPE(arg)->tp_name);
- return NULL;
- }
- s = PyString_AS_STRING(arg);
- if (strcmp(s, "double") == 0) {
- r = double_format;
- }
- else if (strcmp(s, "float") == 0) {
- r = float_format;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "__getformat__() argument 1 must be "
- "'double' or 'float'");
- return NULL;
- }
-
- switch (r) {
- case unknown_format:
- return PyString_FromString("unknown");
- case ieee_little_endian_format:
- return PyString_FromString("IEEE, little-endian");
- case ieee_big_endian_format:
- return PyString_FromString("IEEE, big-endian");
- default:
- Py_FatalError("insane float_format or double_format");
- return NULL;
- }
+ char* s;
+ float_format_type r;
+
+ if (!PyString_Check(arg)) {
+ PyErr_Format(PyExc_TypeError,
+ "__getformat__() argument must be string, not %.500s",
+ Py_TYPE(arg)->tp_name);
+ return NULL;
+ }
+ s = PyString_AS_STRING(arg);
+ if (strcmp(s, "double") == 0) {
+ r = double_format;
+ }
+ else if (strcmp(s, "float") == 0) {
+ r = float_format;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "__getformat__() argument 1 must be "
+ "'double' or 'float'");
+ return NULL;
+ }
+
+ switch (r) {
+ case unknown_format:
+ return PyString_FromString("unknown");
+ case ieee_little_endian_format:
+ return PyString_FromString("IEEE, little-endian");
+ case ieee_big_endian_format:
+ return PyString_FromString("IEEE, big-endian");
+ default:
+ Py_FatalError("insane float_format or double_format");
+ return NULL;
+ }
}
PyDoc_STRVAR(float_getformat_doc,
@@ -1880,57 +1880,57 @@ PyDoc_STRVAR(float_getformat_doc,
static PyObject *
float_setformat(PyTypeObject *v, PyObject* args)
{
- char* typestr;
- char* format;
- float_format_type f;
- float_format_type detected;
- float_format_type *p;
-
- if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
- return NULL;
-
- if (strcmp(typestr, "double") == 0) {
- p = &double_format;
- detected = detected_double_format;
- }
- else if (strcmp(typestr, "float") == 0) {
- p = &float_format;
- detected = detected_float_format;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "__setformat__() argument 1 must "
- "be 'double' or 'float'");
- return NULL;
- }
-
- if (strcmp(format, "unknown") == 0) {
- f = unknown_format;
- }
- else if (strcmp(format, "IEEE, little-endian") == 0) {
- f = ieee_little_endian_format;
- }
- else if (strcmp(format, "IEEE, big-endian") == 0) {
- f = ieee_big_endian_format;
- }
- else {
- PyErr_SetString(PyExc_ValueError,
- "__setformat__() argument 2 must be "
- "'unknown', 'IEEE, little-endian' or "
- "'IEEE, big-endian'");
- return NULL;
-
- }
-
- if (f != unknown_format && f != detected) {
- PyErr_Format(PyExc_ValueError,
- "can only set %s format to 'unknown' or the "
- "detected platform value", typestr);
- return NULL;
- }
-
- *p = f;
- Py_RETURN_NONE;
+ char* typestr;
+ char* format;
+ float_format_type f;
+ float_format_type detected;
+ float_format_type *p;
+
+ if (!PyArg_ParseTuple(args, "ss:__setformat__", &typestr, &format))
+ return NULL;
+
+ if (strcmp(typestr, "double") == 0) {
+ p = &double_format;
+ detected = detected_double_format;
+ }
+ else if (strcmp(typestr, "float") == 0) {
+ p = &float_format;
+ detected = detected_float_format;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "__setformat__() argument 1 must "
+ "be 'double' or 'float'");
+ return NULL;
+ }
+
+ if (strcmp(format, "unknown") == 0) {
+ f = unknown_format;
+ }
+ else if (strcmp(format, "IEEE, little-endian") == 0) {
+ f = ieee_little_endian_format;
+ }
+ else if (strcmp(format, "IEEE, big-endian") == 0) {
+ f = ieee_big_endian_format;
+ }
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "__setformat__() argument 2 must be "
+ "'unknown', 'IEEE, little-endian' or "
+ "'IEEE, big-endian'");
+ return NULL;
+
+ }
+
+ if (f != unknown_format && f != detected) {
+ PyErr_Format(PyExc_ValueError,
+ "can only set %s format to 'unknown' or the "
+ "detected platform value", typestr);
+ return NULL;
+ }
+
+ *p = f;
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(float_setformat_doc,
@@ -1949,37 +1949,37 @@ PyDoc_STRVAR(float_setformat_doc,
static PyObject *
float_getzero(PyObject *v, void *closure)
{
- return PyFloat_FromDouble(0.0);
+ return PyFloat_FromDouble(0.0);
}
static PyObject *
float__format__(PyObject *self, PyObject *args)
{
- PyObject *format_spec;
-
- if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
- return NULL;
- if (PyBytes_Check(format_spec))
- return _PyFloat_FormatAdvanced(self,
- PyBytes_AS_STRING(format_spec),
- PyBytes_GET_SIZE(format_spec));
- if (PyUnicode_Check(format_spec)) {
- /* Convert format_spec to a str */
- PyObject *result;
- PyObject *str_spec = PyObject_Str(format_spec);
-
- if (str_spec == NULL)
- return NULL;
-
- result = _PyFloat_FormatAdvanced(self,
- PyBytes_AS_STRING(str_spec),
- PyBytes_GET_SIZE(str_spec));
-
- Py_DECREF(str_spec);
- return result;
- }
- PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
- return NULL;
+ PyObject *format_spec;
+
+ if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
+ return NULL;
+ if (PyBytes_Check(format_spec))
+ return _PyFloat_FormatAdvanced(self,
+ PyBytes_AS_STRING(format_spec),
+ PyBytes_GET_SIZE(format_spec));
+ if (PyUnicode_Check(format_spec)) {
+ /* Convert format_spec to a str */
+ PyObject *result;
+ PyObject *str_spec = PyObject_Str(format_spec);
+
+ if (str_spec == NULL)
+ return NULL;
+
+ result = _PyFloat_FormatAdvanced(self,
+ PyBytes_AS_STRING(str_spec),
+ PyBytes_GET_SIZE(str_spec));
+
+ Py_DECREF(str_spec);
+ return result;
+ }
+ PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
+ return NULL;
}
PyDoc_STRVAR(float__format__doc,
@@ -1989,42 +1989,42 @@ PyDoc_STRVAR(float__format__doc,
static PyMethodDef float_methods[] = {
- {"conjugate", (PyCFunction)float_float, METH_NOARGS,
- "Returns self, the complex conjugate of any float."},
- {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
- "Returns the Integral closest to x between 0 and x."},
- {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
- float_as_integer_ratio_doc},
- {"fromhex", (PyCFunction)float_fromhex,
- METH_O|METH_CLASS, float_fromhex_doc},
- {"hex", (PyCFunction)float_hex,
- METH_NOARGS, float_hex_doc},
- {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
- "Returns True if the float is an integer."},
+ {"conjugate", (PyCFunction)float_float, METH_NOARGS,
+ "Returns self, the complex conjugate of any float."},
+ {"__trunc__", (PyCFunction)float_trunc, METH_NOARGS,
+ "Returns the Integral closest to x between 0 and x."},
+ {"as_integer_ratio", (PyCFunction)float_as_integer_ratio, METH_NOARGS,
+ float_as_integer_ratio_doc},
+ {"fromhex", (PyCFunction)float_fromhex,
+ METH_O|METH_CLASS, float_fromhex_doc},
+ {"hex", (PyCFunction)float_hex,
+ METH_NOARGS, float_hex_doc},
+ {"is_integer", (PyCFunction)float_is_integer, METH_NOARGS,
+ "Returns True if the float is an integer."},
#if 0
- {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
- "Returns True if the float is positive or negative infinite."},
- {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
- "Returns True if the float is finite, neither infinite nor NaN."},
- {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
- "Returns True if the float is not a number (NaN)."},
+ {"is_inf", (PyCFunction)float_is_inf, METH_NOARGS,
+ "Returns True if the float is positive or negative infinite."},
+ {"is_finite", (PyCFunction)float_is_finite, METH_NOARGS,
+ "Returns True if the float is finite, neither infinite nor NaN."},
+ {"is_nan", (PyCFunction)float_is_nan, METH_NOARGS,
+ "Returns True if the float is not a number (NaN)."},
#endif
- {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
- {"__getformat__", (PyCFunction)float_getformat,
- METH_O|METH_CLASS, float_getformat_doc},
- {"__setformat__", (PyCFunction)float_setformat,
- METH_VARARGS|METH_CLASS, float_setformat_doc},
- {"__format__", (PyCFunction)float__format__,
- METH_VARARGS, float__format__doc},
- {NULL, NULL} /* sentinel */
+ {"__getnewargs__", (PyCFunction)float_getnewargs, METH_NOARGS},
+ {"__getformat__", (PyCFunction)float_getformat,
+ METH_O|METH_CLASS, float_getformat_doc},
+ {"__setformat__", (PyCFunction)float_setformat,
+ METH_VARARGS|METH_CLASS, float_setformat_doc},
+ {"__format__", (PyCFunction)float__format__,
+ METH_VARARGS, float__format__doc},
+ {NULL, NULL} /* sentinel */
};
static PyGetSetDef float_getset[] = {
- {"real",
+ {"real",
(getter)float_float, (setter)NULL,
"the real part of a complex number",
NULL},
- {"imag",
+ {"imag",
(getter)float_getzero, (setter)NULL,
"the imaginary part of a complex number",
NULL},
@@ -2038,235 +2038,235 @@ Convert a string or number to a floating point number, if possible.");
static PyNumberMethods float_as_number = {
- float_add, /*nb_add*/
- float_sub, /*nb_subtract*/
- float_mul, /*nb_multiply*/
- float_classic_div, /*nb_divide*/
- float_rem, /*nb_remainder*/
- float_divmod, /*nb_divmod*/
- float_pow, /*nb_power*/
- (unaryfunc)float_neg, /*nb_negative*/
- (unaryfunc)float_float, /*nb_positive*/
- (unaryfunc)float_abs, /*nb_absolute*/
- (inquiry)float_nonzero, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- 0, /*nb_and*/
- 0, /*nb_xor*/
- 0, /*nb_or*/
- float_coerce, /*nb_coerce*/
- float_trunc, /*nb_int*/
- float_long, /*nb_long*/
- float_float, /*nb_float*/
- 0, /* nb_oct */
- 0, /* nb_hex */
- 0, /* nb_inplace_add */
- 0, /* nb_inplace_subtract */
- 0, /* nb_inplace_multiply */
- 0, /* nb_inplace_divide */
- 0, /* nb_inplace_remainder */
- 0, /* nb_inplace_power */
- 0, /* nb_inplace_lshift */
- 0, /* nb_inplace_rshift */
- 0, /* nb_inplace_and */
- 0, /* nb_inplace_xor */
- 0, /* nb_inplace_or */
- float_floor_div, /* nb_floor_divide */
- float_div, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
+ float_add, /*nb_add*/
+ float_sub, /*nb_subtract*/
+ float_mul, /*nb_multiply*/
+ float_classic_div, /*nb_divide*/
+ float_rem, /*nb_remainder*/
+ float_divmod, /*nb_divmod*/
+ float_pow, /*nb_power*/
+ (unaryfunc)float_neg, /*nb_negative*/
+ (unaryfunc)float_float, /*nb_positive*/
+ (unaryfunc)float_abs, /*nb_absolute*/
+ (inquiry)float_nonzero, /*nb_nonzero*/
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ 0, /*nb_and*/
+ 0, /*nb_xor*/
+ 0, /*nb_or*/
+ float_coerce, /*nb_coerce*/
+ float_trunc, /*nb_int*/
+ float_long, /*nb_long*/
+ float_float, /*nb_float*/
+ 0, /* nb_oct */
+ 0, /* nb_hex */
+ 0, /* nb_inplace_add */
+ 0, /* nb_inplace_subtract */
+ 0, /* nb_inplace_multiply */
+ 0, /* nb_inplace_divide */
+ 0, /* nb_inplace_remainder */
+ 0, /* nb_inplace_power */
+ 0, /* nb_inplace_lshift */
+ 0, /* nb_inplace_rshift */
+ 0, /* nb_inplace_and */
+ 0, /* nb_inplace_xor */
+ 0, /* nb_inplace_or */
+ float_floor_div, /* nb_floor_divide */
+ float_div, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
};
PyTypeObject PyFloat_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "float",
- sizeof(PyFloatObject),
- 0,
- (destructor)float_dealloc, /* tp_dealloc */
- (printfunc)float_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)float_repr, /* tp_repr */
- &float_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)float_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)float_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- float_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- float_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- float_methods, /* tp_methods */
- 0, /* tp_members */
- float_getset, /* 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 */
- float_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "float",
+ sizeof(PyFloatObject),
+ 0,
+ (destructor)float_dealloc, /* tp_dealloc */
+ (printfunc)float_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)float_repr, /* tp_repr */
+ &float_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)float_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)float_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ float_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ float_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ float_methods, /* tp_methods */
+ 0, /* tp_members */
+ float_getset, /* 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 */
+ float_new, /* tp_new */
};
void
_PyFloat_Init(void)
{
- /* We attempt to determine if this machine is using IEEE
- floating point formats by peering at the bits of some
- carefully chosen values. If it looks like we are on an
- IEEE platform, the float packing/unpacking routines can
- just copy bits, if not they resort to arithmetic & shifts
- and masks. The shifts & masks approach works on all finite
- values, but what happens to infinities, NaNs and signed
- zeroes on packing is an accident, and attempting to unpack
- a NaN or an infinity will raise an exception.
-
- Note that if we're on some whacked-out platform which uses
- IEEE formats but isn't strictly little-endian or big-
- endian, we will fall back to the portable shifts & masks
- method. */
+ /* We attempt to determine if this machine is using IEEE
+ floating point formats by peering at the bits of some
+ carefully chosen values. If it looks like we are on an
+ IEEE platform, the float packing/unpacking routines can
+ just copy bits, if not they resort to arithmetic & shifts
+ and masks. The shifts & masks approach works on all finite
+ values, but what happens to infinities, NaNs and signed
+ zeroes on packing is an accident, and attempting to unpack
+ a NaN or an infinity will raise an exception.
+
+ Note that if we're on some whacked-out platform which uses
+ IEEE formats but isn't strictly little-endian or big-
+ endian, we will fall back to the portable shifts & masks
+ method. */
#if SIZEOF_DOUBLE == 8
- {
- double x = 9006104071832581.0;
- if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
- detected_double_format = ieee_big_endian_format;
- else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
- detected_double_format = ieee_little_endian_format;
- else
- detected_double_format = unknown_format;
- }
+ {
+ double x = 9006104071832581.0;
+ if (memcmp(&x, "\x43\x3f\xff\x01\x02\x03\x04\x05", 8) == 0)
+ detected_double_format = ieee_big_endian_format;
+ else if (memcmp(&x, "\x05\x04\x03\x02\x01\xff\x3f\x43", 8) == 0)
+ detected_double_format = ieee_little_endian_format;
+ else
+ detected_double_format = unknown_format;
+ }
#else
- detected_double_format = unknown_format;
+ detected_double_format = unknown_format;
#endif
#if SIZEOF_FLOAT == 4
- {
- float y = 16711938.0;
- if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
- detected_float_format = ieee_big_endian_format;
- else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
- detected_float_format = ieee_little_endian_format;
- else
- detected_float_format = unknown_format;
- }
+ {
+ float y = 16711938.0;
+ if (memcmp(&y, "\x4b\x7f\x01\x02", 4) == 0)
+ detected_float_format = ieee_big_endian_format;
+ else if (memcmp(&y, "\x02\x01\x7f\x4b", 4) == 0)
+ detected_float_format = ieee_little_endian_format;
+ else
+ detected_float_format = unknown_format;
+ }
#else
- detected_float_format = unknown_format;
+ detected_float_format = unknown_format;
#endif
- double_format = detected_double_format;
- float_format = detected_float_format;
+ double_format = detected_double_format;
+ float_format = detected_float_format;
- /* Init float info */
- if (FloatInfoType.tp_name == 0)
- PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
+ /* Init float info */
+ if (FloatInfoType.tp_name == 0)
+ PyStructSequence_InitType(&FloatInfoType, &floatinfo_desc);
}
int
PyFloat_ClearFreeList(void)
{
- PyFloatObject *p;
- PyFloatBlock *list, *next;
- int i;
- int u; /* remaining unfreed ints per block */
- int freelist_size = 0;
-
- list = block_list;
- block_list = NULL;
- free_list = NULL;
- while (list != NULL) {
- u = 0;
- for (i = 0, p = &list->objects[0];
- i < N_FLOATOBJECTS;
- i++, p++) {
- if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
- u++;
- }
- next = list->next;
- if (u) {
- list->next = block_list;
- block_list = list;
- for (i = 0, p = &list->objects[0];
- i < N_FLOATOBJECTS;
- i++, p++) {
- if (!PyFloat_CheckExact(p) ||
- Py_REFCNT(p) == 0) {
- Py_TYPE(p) = (struct _typeobject *)
- free_list;
- free_list = p;
- }
- }
- }
- else {
- PyMem_FREE(list);
- }
- freelist_size += u;
- list = next;
- }
- return freelist_size;
+ PyFloatObject *p;
+ PyFloatBlock *list, *next;
+ int i;
+ int u; /* remaining unfreed ints per block */
+ int freelist_size = 0;
+
+ list = block_list;
+ block_list = NULL;
+ free_list = NULL;
+ while (list != NULL) {
+ u = 0;
+ for (i = 0, p = &list->objects[0];
+ i < N_FLOATOBJECTS;
+ i++, p++) {
+ if (PyFloat_CheckExact(p) && Py_REFCNT(p) != 0)
+ u++;
+ }
+ next = list->next;
+ if (u) {
+ list->next = block_list;
+ block_list = list;
+ for (i = 0, p = &list->objects[0];
+ i < N_FLOATOBJECTS;
+ i++, p++) {
+ if (!PyFloat_CheckExact(p) ||
+ Py_REFCNT(p) == 0) {
+ Py_TYPE(p) = (struct _typeobject *)
+ free_list;
+ free_list = p;
+ }
+ }
+ }
+ else {
+ PyMem_FREE(list);
+ }
+ freelist_size += u;
+ list = next;
+ }
+ return freelist_size;
}
void
PyFloat_Fini(void)
{
- PyFloatObject *p;
- PyFloatBlock *list;
- int i;
- int u; /* total unfreed floats per block */
-
- u = PyFloat_ClearFreeList();
-
- if (!Py_VerboseFlag)
- return;
- fprintf(stderr, "# cleanup floats");
- if (!u) {
- fprintf(stderr, "\n");
- }
- else {
- fprintf(stderr,
- ": %d unfreed float%s\n",
- u, u == 1 ? "" : "s");
- }
- if (Py_VerboseFlag > 1) {
- list = block_list;
- while (list != NULL) {
- for (i = 0, p = &list->objects[0];
- i < N_FLOATOBJECTS;
- i++, p++) {
- if (PyFloat_CheckExact(p) &&
- Py_REFCNT(p) != 0) {
- char *buf = PyOS_double_to_string(
- PyFloat_AS_DOUBLE(p), 'r',
- 0, 0, NULL);
- if (buf) {
- /* XXX(twouters) cast
- refcount to long
- until %zd is
- universally
- available
- */
- fprintf(stderr,
- "# <float at %p, refcnt=%ld, val=%s>\n",
- p, (long)Py_REFCNT(p), buf);
- PyMem_Free(buf);
- }
- }
- }
- list = list->next;
- }
- }
+ PyFloatObject *p;
+ PyFloatBlock *list;
+ int i;
+ int u; /* total unfreed floats per block */
+
+ u = PyFloat_ClearFreeList();
+
+ if (!Py_VerboseFlag)
+ return;
+ fprintf(stderr, "# cleanup floats");
+ if (!u) {
+ fprintf(stderr, "\n");
+ }
+ else {
+ fprintf(stderr,
+ ": %d unfreed float%s\n",
+ u, u == 1 ? "" : "s");
+ }
+ if (Py_VerboseFlag > 1) {
+ list = block_list;
+ while (list != NULL) {
+ for (i = 0, p = &list->objects[0];
+ i < N_FLOATOBJECTS;
+ i++, p++) {
+ if (PyFloat_CheckExact(p) &&
+ Py_REFCNT(p) != 0) {
+ char *buf = PyOS_double_to_string(
+ PyFloat_AS_DOUBLE(p), 'r',
+ 0, 0, NULL);
+ if (buf) {
+ /* XXX(twouters) cast
+ refcount to long
+ until %zd is
+ universally
+ available
+ */
+ fprintf(stderr,
+ "# <float at %p, refcnt=%ld, val=%s>\n",
+ p, (long)Py_REFCNT(p), buf);
+ PyMem_Free(buf);
+ }
+ }
+ }
+ list = list->next;
+ }
+ }
}
/*----------------------------------------------------------------------------
@@ -2275,406 +2275,406 @@ PyFloat_Fini(void)
int
_PyFloat_Pack4(double x, unsigned char *p, int le)
{
- if (float_format == unknown_format) {
- unsigned char sign;
- int e;
- double f;
- unsigned int fbits;
- int incr = 1;
-
- if (le) {
- p += 3;
- incr = -1;
- }
-
- if (x < 0) {
- sign = 1;
- x = -x;
- }
- else
- sign = 0;
-
- f = frexp(x, &e);
-
- /* Normalize f to be in the range [1.0, 2.0) */
- if (0.5 <= f && f < 1.0) {
- f *= 2.0;
- e--;
- }
- else if (f == 0.0)
- e = 0;
- else {
- PyErr_SetString(PyExc_SystemError,
- "frexp() result out of range");
- return -1;
- }
-
- if (e >= 128)
- goto Overflow;
- else if (e < -126) {
- /* Gradual underflow */
- f = ldexp(f, 126 + e);
- e = 0;
- }
- else if (!(e == 0 && f == 0.0)) {
- e += 127;
- f -= 1.0; /* Get rid of leading 1 */
- }
-
- f *= 8388608.0; /* 2**23 */
- fbits = (unsigned int)(f + 0.5); /* Round */
- assert(fbits <= 8388608);
- if (fbits >> 23) {
- /* The carry propagated out of a string of 23 1 bits. */
- fbits = 0;
- ++e;
- if (e >= 255)
- goto Overflow;
- }
-
- /* First byte */
- *p = (sign << 7) | (e >> 1);
- p += incr;
-
- /* Second byte */
- *p = (char) (((e & 1) << 7) | (fbits >> 16));
- p += incr;
-
- /* Third byte */
- *p = (fbits >> 8) & 0xFF;
- p += incr;
-
- /* Fourth byte */
- *p = fbits & 0xFF;
-
- /* Done */
- return 0;
-
- }
- else {
- float y = (float)x;
- const char *s = (char*)&y;
- int i, incr = 1;
-
- if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
- goto Overflow;
-
- if ((float_format == ieee_little_endian_format && !le)
- || (float_format == ieee_big_endian_format && le)) {
- p += 3;
- incr = -1;
- }
-
- for (i = 0; i < 4; i++) {
- *p = *s++;
- p += incr;
- }
- return 0;
- }
+ if (float_format == unknown_format) {
+ unsigned char sign;
+ int e;
+ double f;
+ unsigned int fbits;
+ int incr = 1;
+
+ if (le) {
+ p += 3;
+ incr = -1;
+ }
+
+ if (x < 0) {
+ sign = 1;
+ x = -x;
+ }
+ else
+ sign = 0;
+
+ f = frexp(x, &e);
+
+ /* Normalize f to be in the range [1.0, 2.0) */
+ if (0.5 <= f && f < 1.0) {
+ f *= 2.0;
+ e--;
+ }
+ else if (f == 0.0)
+ e = 0;
+ else {
+ PyErr_SetString(PyExc_SystemError,
+ "frexp() result out of range");
+ return -1;
+ }
+
+ if (e >= 128)
+ goto Overflow;
+ else if (e < -126) {
+ /* Gradual underflow */
+ f = ldexp(f, 126 + e);
+ e = 0;
+ }
+ else if (!(e == 0 && f == 0.0)) {
+ e += 127;
+ f -= 1.0; /* Get rid of leading 1 */
+ }
+
+ f *= 8388608.0; /* 2**23 */
+ fbits = (unsigned int)(f + 0.5); /* Round */
+ assert(fbits <= 8388608);
+ if (fbits >> 23) {
+ /* The carry propagated out of a string of 23 1 bits. */
+ fbits = 0;
+ ++e;
+ if (e >= 255)
+ goto Overflow;
+ }
+
+ /* First byte */
+ *p = (sign << 7) | (e >> 1);
+ p += incr;
+
+ /* Second byte */
+ *p = (char) (((e & 1) << 7) | (fbits >> 16));
+ p += incr;
+
+ /* Third byte */
+ *p = (fbits >> 8) & 0xFF;
+ p += incr;
+
+ /* Fourth byte */
+ *p = fbits & 0xFF;
+
+ /* Done */
+ return 0;
+
+ }
+ else {
+ float y = (float)x;
+ const char *s = (char*)&y;
+ int i, incr = 1;
+
+ if (Py_IS_INFINITY(y) && !Py_IS_INFINITY(x))
+ goto Overflow;
+
+ if ((float_format == ieee_little_endian_format && !le)
+ || (float_format == ieee_big_endian_format && le)) {
+ p += 3;
+ incr = -1;
+ }
+
+ for (i = 0; i < 4; i++) {
+ *p = *s++;
+ p += incr;
+ }
+ return 0;
+ }
Overflow:
- PyErr_SetString(PyExc_OverflowError,
- "float too large to pack with f format");
- return -1;
+ PyErr_SetString(PyExc_OverflowError,
+ "float too large to pack with f format");
+ return -1;
}
int
_PyFloat_Pack8(double x, unsigned char *p, int le)
{
- if (double_format == unknown_format) {
- unsigned char sign;
- int e;
- double f;
- unsigned int fhi, flo;
- int incr = 1;
-
- if (le) {
- p += 7;
- incr = -1;
- }
-
- if (x < 0) {
- sign = 1;
- x = -x;
- }
- else
- sign = 0;
-
- f = frexp(x, &e);
-
- /* Normalize f to be in the range [1.0, 2.0) */
- if (0.5 <= f && f < 1.0) {
- f *= 2.0;
- e--;
- }
- else if (f == 0.0)
- e = 0;
- else {
- PyErr_SetString(PyExc_SystemError,
- "frexp() result out of range");
- return -1;
- }
-
- if (e >= 1024)
- goto Overflow;
- else if (e < -1022) {
- /* Gradual underflow */
- f = ldexp(f, 1022 + e);
- e = 0;
- }
- else if (!(e == 0 && f == 0.0)) {
- e += 1023;
- f -= 1.0; /* Get rid of leading 1 */
- }
-
- /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
- f *= 268435456.0; /* 2**28 */
- fhi = (unsigned int)f; /* Truncate */
- assert(fhi < 268435456);
-
- f -= (double)fhi;
- f *= 16777216.0; /* 2**24 */
- flo = (unsigned int)(f + 0.5); /* Round */
- assert(flo <= 16777216);
- if (flo >> 24) {
- /* The carry propagated out of a string of 24 1 bits. */
- flo = 0;
- ++fhi;
- if (fhi >> 28) {
- /* And it also progagated out of the next 28 bits. */
- fhi = 0;
- ++e;
- if (e >= 2047)
- goto Overflow;
- }
- }
-
- /* First byte */
- *p = (sign << 7) | (e >> 4);
- p += incr;
-
- /* Second byte */
- *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
- p += incr;
-
- /* Third byte */
- *p = (fhi >> 16) & 0xFF;
- p += incr;
-
- /* Fourth byte */
- *p = (fhi >> 8) & 0xFF;
- p += incr;
-
- /* Fifth byte */
- *p = fhi & 0xFF;
- p += incr;
-
- /* Sixth byte */
- *p = (flo >> 16) & 0xFF;
- p += incr;
-
- /* Seventh byte */
- *p = (flo >> 8) & 0xFF;
- p += incr;
-
- /* Eighth byte */
- *p = flo & 0xFF;
- /* p += incr; Unneeded (for now) */
-
- /* Done */
- return 0;
-
- Overflow:
- PyErr_SetString(PyExc_OverflowError,
- "float too large to pack with d format");
- return -1;
- }
- else {
- const char *s = (char*)&x;
- int i, incr = 1;
-
- if ((double_format == ieee_little_endian_format && !le)
- || (double_format == ieee_big_endian_format && le)) {
- p += 7;
- incr = -1;
- }
-
- for (i = 0; i < 8; i++) {
- *p = *s++;
- p += incr;
- }
- return 0;
- }
+ if (double_format == unknown_format) {
+ unsigned char sign;
+ int e;
+ double f;
+ unsigned int fhi, flo;
+ int incr = 1;
+
+ if (le) {
+ p += 7;
+ incr = -1;
+ }
+
+ if (x < 0) {
+ sign = 1;
+ x = -x;
+ }
+ else
+ sign = 0;
+
+ f = frexp(x, &e);
+
+ /* Normalize f to be in the range [1.0, 2.0) */
+ if (0.5 <= f && f < 1.0) {
+ f *= 2.0;
+ e--;
+ }
+ else if (f == 0.0)
+ e = 0;
+ else {
+ PyErr_SetString(PyExc_SystemError,
+ "frexp() result out of range");
+ return -1;
+ }
+
+ if (e >= 1024)
+ goto Overflow;
+ else if (e < -1022) {
+ /* Gradual underflow */
+ f = ldexp(f, 1022 + e);
+ e = 0;
+ }
+ else if (!(e == 0 && f == 0.0)) {
+ e += 1023;
+ f -= 1.0; /* Get rid of leading 1 */
+ }
+
+ /* fhi receives the high 28 bits; flo the low 24 bits (== 52 bits) */
+ f *= 268435456.0; /* 2**28 */
+ fhi = (unsigned int)f; /* Truncate */
+ assert(fhi < 268435456);
+
+ f -= (double)fhi;
+ f *= 16777216.0; /* 2**24 */
+ flo = (unsigned int)(f + 0.5); /* Round */
+ assert(flo <= 16777216);
+ if (flo >> 24) {
+ /* The carry propagated out of a string of 24 1 bits. */
+ flo = 0;
+ ++fhi;
+ if (fhi >> 28) {
+ /* And it also progagated out of the next 28 bits. */
+ fhi = 0;
+ ++e;
+ if (e >= 2047)
+ goto Overflow;
+ }
+ }
+
+ /* First byte */
+ *p = (sign << 7) | (e >> 4);
+ p += incr;
+
+ /* Second byte */
+ *p = (unsigned char) (((e & 0xF) << 4) | (fhi >> 24));
+ p += incr;
+
+ /* Third byte */
+ *p = (fhi >> 16) & 0xFF;
+ p += incr;
+
+ /* Fourth byte */
+ *p = (fhi >> 8) & 0xFF;
+ p += incr;
+
+ /* Fifth byte */
+ *p = fhi & 0xFF;
+ p += incr;
+
+ /* Sixth byte */
+ *p = (flo >> 16) & 0xFF;
+ p += incr;
+
+ /* Seventh byte */
+ *p = (flo >> 8) & 0xFF;
+ p += incr;
+
+ /* Eighth byte */
+ *p = flo & 0xFF;
+ /* p += incr; Unneeded (for now) */
+
+ /* Done */
+ return 0;
+
+ Overflow:
+ PyErr_SetString(PyExc_OverflowError,
+ "float too large to pack with d format");
+ return -1;
+ }
+ else {
+ const char *s = (char*)&x;
+ int i, incr = 1;
+
+ if ((double_format == ieee_little_endian_format && !le)
+ || (double_format == ieee_big_endian_format && le)) {
+ p += 7;
+ incr = -1;
+ }
+
+ for (i = 0; i < 8; i++) {
+ *p = *s++;
+ p += incr;
+ }
+ return 0;
+ }
}
double
_PyFloat_Unpack4(const unsigned char *p, int le)
{
- if (float_format == unknown_format) {
- unsigned char sign;
- int e;
- unsigned int f;
- double x;
- int incr = 1;
-
- if (le) {
- p += 3;
- incr = -1;
- }
-
- /* First byte */
- sign = (*p >> 7) & 1;
- e = (*p & 0x7F) << 1;
- p += incr;
-
- /* Second byte */
- e |= (*p >> 7) & 1;
- f = (*p & 0x7F) << 16;
- p += incr;
-
- if (e == 255) {
- PyErr_SetString(
- PyExc_ValueError,
- "can't unpack IEEE 754 special value "
- "on non-IEEE platform");
- return -1;
- }
-
- /* Third byte */
- f |= *p << 8;
- p += incr;
-
- /* Fourth byte */
- f |= *p;
-
- x = (double)f / 8388608.0;
-
- /* XXX This sadly ignores Inf/NaN issues */
- if (e == 0)
- e = -126;
- else {
- x += 1.0;
- e -= 127;
- }
- x = ldexp(x, e);
-
- if (sign)
- x = -x;
-
- return x;
- }
- else {
- float x;
-
- if ((float_format == ieee_little_endian_format && !le)
- || (float_format == ieee_big_endian_format && le)) {
- char buf[4];
- char *d = &buf[3];
- int i;
-
- for (i = 0; i < 4; i++) {
- *d-- = *p++;
- }
- memcpy(&x, buf, 4);
- }
- else {
- memcpy(&x, p, 4);
- }
-
- return x;
- }
+ if (float_format == unknown_format) {
+ unsigned char sign;
+ int e;
+ unsigned int f;
+ double x;
+ int incr = 1;
+
+ if (le) {
+ p += 3;
+ incr = -1;
+ }
+
+ /* First byte */
+ sign = (*p >> 7) & 1;
+ e = (*p & 0x7F) << 1;
+ p += incr;
+
+ /* Second byte */
+ e |= (*p >> 7) & 1;
+ f = (*p & 0x7F) << 16;
+ p += incr;
+
+ if (e == 255) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "can't unpack IEEE 754 special value "
+ "on non-IEEE platform");
+ return -1;
+ }
+
+ /* Third byte */
+ f |= *p << 8;
+ p += incr;
+
+ /* Fourth byte */
+ f |= *p;
+
+ x = (double)f / 8388608.0;
+
+ /* XXX This sadly ignores Inf/NaN issues */
+ if (e == 0)
+ e = -126;
+ else {
+ x += 1.0;
+ e -= 127;
+ }
+ x = ldexp(x, e);
+
+ if (sign)
+ x = -x;
+
+ return x;
+ }
+ else {
+ float x;
+
+ if ((float_format == ieee_little_endian_format && !le)
+ || (float_format == ieee_big_endian_format && le)) {
+ char buf[4];
+ char *d = &buf[3];
+ int i;
+
+ for (i = 0; i < 4; i++) {
+ *d-- = *p++;
+ }
+ memcpy(&x, buf, 4);
+ }
+ else {
+ memcpy(&x, p, 4);
+ }
+
+ return x;
+ }
}
double
_PyFloat_Unpack8(const unsigned char *p, int le)
{
- if (double_format == unknown_format) {
- unsigned char sign;
- int e;
- unsigned int fhi, flo;
- double x;
- int incr = 1;
-
- if (le) {
- p += 7;
- incr = -1;
- }
-
- /* First byte */
- sign = (*p >> 7) & 1;
- e = (*p & 0x7F) << 4;
-
- p += incr;
-
- /* Second byte */
- e |= (*p >> 4) & 0xF;
- fhi = (*p & 0xF) << 24;
- p += incr;
-
- if (e == 2047) {
- PyErr_SetString(
- PyExc_ValueError,
- "can't unpack IEEE 754 special value "
- "on non-IEEE platform");
- return -1.0;
- }
-
- /* Third byte */
- fhi |= *p << 16;
- p += incr;
-
- /* Fourth byte */
- fhi |= *p << 8;
- p += incr;
-
- /* Fifth byte */
- fhi |= *p;
- p += incr;
-
- /* Sixth byte */
- flo = *p << 16;
- p += incr;
-
- /* Seventh byte */
- flo |= *p << 8;
- p += incr;
-
- /* Eighth byte */
- flo |= *p;
-
- x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
- x /= 268435456.0; /* 2**28 */
-
- if (e == 0)
- e = -1022;
- else {
- x += 1.0;
- e -= 1023;
- }
- x = ldexp(x, e);
-
- if (sign)
- x = -x;
-
- return x;
- }
- else {
- double x;
-
- if ((double_format == ieee_little_endian_format && !le)
- || (double_format == ieee_big_endian_format && le)) {
- char buf[8];
- char *d = &buf[7];
- int i;
-
- for (i = 0; i < 8; i++) {
- *d-- = *p++;
- }
- memcpy(&x, buf, 8);
- }
- else {
- memcpy(&x, p, 8);
- }
-
- return x;
- }
+ if (double_format == unknown_format) {
+ unsigned char sign;
+ int e;
+ unsigned int fhi, flo;
+ double x;
+ int incr = 1;
+
+ if (le) {
+ p += 7;
+ incr = -1;
+ }
+
+ /* First byte */
+ sign = (*p >> 7) & 1;
+ e = (*p & 0x7F) << 4;
+
+ p += incr;
+
+ /* Second byte */
+ e |= (*p >> 4) & 0xF;
+ fhi = (*p & 0xF) << 24;
+ p += incr;
+
+ if (e == 2047) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "can't unpack IEEE 754 special value "
+ "on non-IEEE platform");
+ return -1.0;
+ }
+
+ /* Third byte */
+ fhi |= *p << 16;
+ p += incr;
+
+ /* Fourth byte */
+ fhi |= *p << 8;
+ p += incr;
+
+ /* Fifth byte */
+ fhi |= *p;
+ p += incr;
+
+ /* Sixth byte */
+ flo = *p << 16;
+ p += incr;
+
+ /* Seventh byte */
+ flo |= *p << 8;
+ p += incr;
+
+ /* Eighth byte */
+ flo |= *p;
+
+ x = (double)fhi + (double)flo / 16777216.0; /* 2**24 */
+ x /= 268435456.0; /* 2**28 */
+
+ if (e == 0)
+ e = -1022;
+ else {
+ x += 1.0;
+ e -= 1023;
+ }
+ x = ldexp(x, e);
+
+ if (sign)
+ x = -x;
+
+ return x;
+ }
+ else {
+ double x;
+
+ if ((double_format == ieee_little_endian_format && !le)
+ || (double_format == ieee_big_endian_format && le)) {
+ char buf[8];
+ char *d = &buf[7];
+ int i;
+
+ for (i = 0; i < 8; i++) {
+ *d-- = *p++;
+ }
+ memcpy(&x, buf, 8);
+ }
+ else {
+ memcpy(&x, p, 8);
+ }
+
+ return x;
+ }
}
diff --git a/Objects/frameobject.c b/Objects/frameobject.c
index 21396ff..a3476cf 100644
--- a/Objects/frameobject.c
+++ b/Objects/frameobject.c
@@ -15,35 +15,35 @@
#define OFF(x) offsetof(PyFrameObject, x)
static PyMemberDef frame_memberlist[] = {
- {"f_back", T_OBJECT, OFF(f_back), RO},
- {"f_code", T_OBJECT, OFF(f_code), RO},
- {"f_builtins", T_OBJECT, OFF(f_builtins),RO},
- {"f_globals", T_OBJECT, OFF(f_globals), RO},
- {"f_lasti", T_INT, OFF(f_lasti), RO},
- {NULL} /* Sentinel */
+ {"f_back", T_OBJECT, OFF(f_back), RO},
+ {"f_code", T_OBJECT, OFF(f_code), RO},
+ {"f_builtins", T_OBJECT, OFF(f_builtins),RO},
+ {"f_globals", T_OBJECT, OFF(f_globals), RO},
+ {"f_lasti", T_INT, OFF(f_lasti), RO},
+ {NULL} /* Sentinel */
};
#define WARN_GET_SET(NAME) \
static PyObject * frame_get_ ## NAME(PyFrameObject *f) { \
- if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
- return NULL; \
- if (f->NAME) { \
- Py_INCREF(f->NAME); \
- return f->NAME; \
- } \
- Py_RETURN_NONE; \
+ if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
+ return NULL; \
+ if (f->NAME) { \
+ Py_INCREF(f->NAME); \
+ return f->NAME; \
+ } \
+ Py_RETURN_NONE; \
} \
static int frame_set_ ## NAME(PyFrameObject *f, PyObject *new) { \
- if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
- return -1; \
- if (f->NAME) { \
- Py_CLEAR(f->NAME); \
- } \
- if (new == Py_None) \
- new = NULL; \
- Py_XINCREF(new); \
- f->NAME = new; \
- return 0; \
+ if (PyErr_WarnPy3k(#NAME " has been removed in 3.x", 2) < 0) \
+ return -1; \
+ if (f->NAME) { \
+ Py_CLEAR(f->NAME); \
+ } \
+ if (new == Py_None) \
+ new = NULL; \
+ Py_XINCREF(new); \
+ f->NAME = new; \
+ return 0; \
}
@@ -55,28 +55,28 @@ WARN_GET_SET(f_exc_value)
static PyObject *
frame_getlocals(PyFrameObject *f, void *closure)
{
- PyFrame_FastToLocals(f);
- Py_INCREF(f->f_locals);
- return f->f_locals;
+ PyFrame_FastToLocals(f);
+ Py_INCREF(f->f_locals);
+ return f->f_locals;
}
int
PyFrame_GetLineNumber(PyFrameObject *f)
{
- if (f->f_trace)
- return f->f_lineno;
- else
- return PyCode_Addr2Line(f->f_code, f->f_lasti);
+ if (f->f_trace)
+ return f->f_lineno;
+ else
+ return PyCode_Addr2Line(f->f_code, f->f_lasti);
}
static PyObject *
frame_getlineno(PyFrameObject *f, void *closure)
{
- return PyInt_FromLong(PyFrame_GetLineNumber(f));
+ return PyInt_FromLong(PyFrame_GetLineNumber(f));
}
/* Setter for f_lineno - you can set f_lineno from within a trace function in
- * order to jump to a given line of code, subject to some restrictions. Most
+ * order to jump to a given line of code, subject to some restrictions. Most
* lines are OK to jump to because they don't make any assumptions about the
* state of the stack (obvious because you could remove the line and the code
* would still work without any stack errors), but there are some constructs
@@ -93,307 +93,307 @@ frame_getlineno(PyFrameObject *f, void *closure)
static int
frame_setlineno(PyFrameObject *f, PyObject* p_new_lineno)
{
- int new_lineno = 0; /* The new value of f_lineno */
- int new_lasti = 0; /* The new value of f_lasti */
- int new_iblock = 0; /* The new value of f_iblock */
- unsigned char *code = NULL; /* The bytecode for the frame... */
- Py_ssize_t code_len = 0; /* ...and its length */
- unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
- Py_ssize_t lnotab_len = 0; /* (ditto) */
- int offset = 0; /* (ditto) */
- int line = 0; /* (ditto) */
- int addr = 0; /* (ditto) */
- int min_addr = 0; /* Scanning the SETUPs and POPs */
- int max_addr = 0; /* (ditto) */
- int delta_iblock = 0; /* (ditto) */
- int min_delta_iblock = 0; /* (ditto) */
- int min_iblock = 0; /* (ditto) */
- int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
- int new_lasti_setup_addr = 0; /* (ditto) */
- int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
- int in_finally[CO_MAXBLOCKS]; /* (ditto) */
- int blockstack_top = 0; /* (ditto) */
- unsigned char setup_op = 0; /* (ditto) */
-
- /* f_lineno must be an integer. */
- if (!PyInt_Check(p_new_lineno)) {
- PyErr_SetString(PyExc_ValueError,
- "lineno must be an integer");
- return -1;
- }
-
- /* You can only do this from within a trace function, not via
- * _getframe or similar hackery. */
- if (!f->f_trace)
- {
- PyErr_Format(PyExc_ValueError,
- "f_lineno can only be set by a"
- " line trace function");
- return -1;
- }
-
- /* Fail if the line comes before the start of the code block. */
- new_lineno = (int) PyInt_AsLong(p_new_lineno);
- if (new_lineno < f->f_code->co_firstlineno) {
- PyErr_Format(PyExc_ValueError,
- "line %d comes before the current code block",
- new_lineno);
- return -1;
- }
- else if (new_lineno == f->f_code->co_firstlineno) {
- new_lasti = 0;
- new_lineno = f->f_code->co_firstlineno;
- }
- else {
- /* Find the bytecode offset for the start of the given
- * line, or the first code-owning line after it. */
- char *tmp;
- PyString_AsStringAndSize(f->f_code->co_lnotab,
- &tmp, &lnotab_len);
- lnotab = (unsigned char *) tmp;
- addr = 0;
- line = f->f_code->co_firstlineno;
- new_lasti = -1;
- for (offset = 0; offset < lnotab_len; offset += 2) {
- addr += lnotab[offset];
- line += lnotab[offset+1];
- if (line >= new_lineno) {
- new_lasti = addr;
- new_lineno = line;
- break;
- }
- }
- }
-
- /* If we didn't reach the requested line, return an error. */
- if (new_lasti == -1) {
- PyErr_Format(PyExc_ValueError,
- "line %d comes after the current code block",
- new_lineno);
- return -1;
- }
-
- /* We're now ready to look at the bytecode. */
- PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
- min_addr = MIN(new_lasti, f->f_lasti);
- max_addr = MAX(new_lasti, f->f_lasti);
-
- /* You can't jump onto a line with an 'except' statement on it -
- * they expect to have an exception on the top of the stack, which
- * won't be true if you jump to them. They always start with code
- * that either pops the exception using POP_TOP (plain 'except:'
- * lines do this) or duplicates the exception on the stack using
- * DUP_TOP (if there's an exception type specified). See compile.c,
- * 'com_try_except' for the full details. There aren't any other
- * cases (AFAIK) where a line's code can start with DUP_TOP or
- * POP_TOP, but if any ever appear, they'll be subject to the same
- * restriction (but with a different error message). */
- if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
- PyErr_SetString(PyExc_ValueError,
- "can't jump to 'except' line as there's no exception");
- return -1;
- }
-
- /* You can't jump into or out of a 'finally' block because the 'try'
- * block leaves something on the stack for the END_FINALLY to clean
- * up. So we walk the bytecode, maintaining a simulated blockstack.
- * When we reach the old or new address and it's in a 'finally' block
- * we note the address of the corresponding SETUP_FINALLY. The jump
- * is only legal if neither address is in a 'finally' block or
- * they're both in the same one. 'blockstack' is a stack of the
- * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
- * whether we're in a 'finally' block at each blockstack level. */
- f_lasti_setup_addr = -1;
- new_lasti_setup_addr = -1;
- memset(blockstack, '\0', sizeof(blockstack));
- memset(in_finally, '\0', sizeof(in_finally));
- blockstack_top = 0;
- for (addr = 0; addr < code_len; addr++) {
- unsigned char op = code[addr];
- switch (op) {
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- blockstack[blockstack_top++] = addr;
- in_finally[blockstack_top-1] = 0;
- break;
-
- case POP_BLOCK:
- assert(blockstack_top > 0);
- setup_op = code[blockstack[blockstack_top-1]];
- if (setup_op == SETUP_FINALLY) {
- in_finally[blockstack_top-1] = 1;
- }
- else {
- blockstack_top--;
- }
- break;
-
- case END_FINALLY:
- /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
- * in the bytecode but don't correspond to an actual
- * 'finally' block. (If blockstack_top is 0, we must
- * be seeing such an END_FINALLY.) */
- if (blockstack_top > 0) {
- setup_op = code[blockstack[blockstack_top-1]];
- if (setup_op == SETUP_FINALLY) {
- blockstack_top--;
- }
- }
- break;
- }
-
- /* For the addresses we're interested in, see whether they're
- * within a 'finally' block and if so, remember the address
- * of the SETUP_FINALLY. */
- if (addr == new_lasti || addr == f->f_lasti) {
- int i = 0;
- int setup_addr = -1;
- for (i = blockstack_top-1; i >= 0; i--) {
- if (in_finally[i]) {
- setup_addr = blockstack[i];
- break;
- }
- }
-
- if (setup_addr != -1) {
- if (addr == new_lasti) {
- new_lasti_setup_addr = setup_addr;
- }
-
- if (addr == f->f_lasti) {
- f_lasti_setup_addr = setup_addr;
- }
- }
- }
-
- if (op >= HAVE_ARGUMENT) {
- addr += 2;
- }
- }
-
- /* Verify that the blockstack tracking code didn't get lost. */
- assert(blockstack_top == 0);
-
- /* After all that, are we jumping into / out of a 'finally' block? */
- if (new_lasti_setup_addr != f_lasti_setup_addr) {
- PyErr_SetString(PyExc_ValueError,
- "can't jump into or out of a 'finally' block");
- return -1;
- }
-
-
- /* Police block-jumping (you can't jump into the middle of a block)
- * and ensure that the blockstack finishes up in a sensible state (by
- * popping any blocks we're jumping out of). We look at all the
- * blockstack operations between the current position and the new
- * one, and keep track of how many blocks we drop out of on the way.
- * By also keeping track of the lowest blockstack position we see, we
- * can tell whether the jump goes into any blocks without coming out
- * again - in that case we raise an exception below. */
- delta_iblock = 0;
- for (addr = min_addr; addr < max_addr; addr++) {
- unsigned char op = code[addr];
- switch (op) {
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- delta_iblock++;
- break;
-
- case POP_BLOCK:
- delta_iblock--;
- break;
- }
-
- min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
-
- if (op >= HAVE_ARGUMENT) {
- addr += 2;
- }
- }
-
- /* Derive the absolute iblock values from the deltas. */
- min_iblock = f->f_iblock + min_delta_iblock;
- if (new_lasti > f->f_lasti) {
- /* Forwards jump. */
- new_iblock = f->f_iblock + delta_iblock;
- }
- else {
- /* Backwards jump. */
- new_iblock = f->f_iblock - delta_iblock;
- }
-
- /* Are we jumping into a block? */
- if (new_iblock > min_iblock) {
- PyErr_SetString(PyExc_ValueError,
- "can't jump into the middle of a block");
- return -1;
- }
-
- /* Pop any blocks that we're jumping out of. */
- while (f->f_iblock > new_iblock) {
- PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
- while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
- PyObject *v = (*--f->f_stacktop);
- Py_DECREF(v);
- }
- }
-
- /* Finally set the new f_lineno and f_lasti and return OK. */
- f->f_lineno = new_lineno;
- f->f_lasti = new_lasti;
- return 0;
+ int new_lineno = 0; /* The new value of f_lineno */
+ int new_lasti = 0; /* The new value of f_lasti */
+ int new_iblock = 0; /* The new value of f_iblock */
+ unsigned char *code = NULL; /* The bytecode for the frame... */
+ Py_ssize_t code_len = 0; /* ...and its length */
+ unsigned char *lnotab = NULL; /* Iterating over co_lnotab */
+ Py_ssize_t lnotab_len = 0; /* (ditto) */
+ int offset = 0; /* (ditto) */
+ int line = 0; /* (ditto) */
+ int addr = 0; /* (ditto) */
+ int min_addr = 0; /* Scanning the SETUPs and POPs */
+ int max_addr = 0; /* (ditto) */
+ int delta_iblock = 0; /* (ditto) */
+ int min_delta_iblock = 0; /* (ditto) */
+ int min_iblock = 0; /* (ditto) */
+ int f_lasti_setup_addr = 0; /* Policing no-jump-into-finally */
+ int new_lasti_setup_addr = 0; /* (ditto) */
+ int blockstack[CO_MAXBLOCKS]; /* Walking the 'finally' blocks */
+ int in_finally[CO_MAXBLOCKS]; /* (ditto) */
+ int blockstack_top = 0; /* (ditto) */
+ unsigned char setup_op = 0; /* (ditto) */
+
+ /* f_lineno must be an integer. */
+ if (!PyInt_Check(p_new_lineno)) {
+ PyErr_SetString(PyExc_ValueError,
+ "lineno must be an integer");
+ return -1;
+ }
+
+ /* You can only do this from within a trace function, not via
+ * _getframe or similar hackery. */
+ if (!f->f_trace)
+ {
+ PyErr_Format(PyExc_ValueError,
+ "f_lineno can only be set by a"
+ " line trace function");
+ return -1;
+ }
+
+ /* Fail if the line comes before the start of the code block. */
+ new_lineno = (int) PyInt_AsLong(p_new_lineno);
+ if (new_lineno < f->f_code->co_firstlineno) {
+ PyErr_Format(PyExc_ValueError,
+ "line %d comes before the current code block",
+ new_lineno);
+ return -1;
+ }
+ else if (new_lineno == f->f_code->co_firstlineno) {
+ new_lasti = 0;
+ new_lineno = f->f_code->co_firstlineno;
+ }
+ else {
+ /* Find the bytecode offset for the start of the given
+ * line, or the first code-owning line after it. */
+ char *tmp;
+ PyString_AsStringAndSize(f->f_code->co_lnotab,
+ &tmp, &lnotab_len);
+ lnotab = (unsigned char *) tmp;
+ addr = 0;
+ line = f->f_code->co_firstlineno;
+ new_lasti = -1;
+ for (offset = 0; offset < lnotab_len; offset += 2) {
+ addr += lnotab[offset];
+ line += lnotab[offset+1];
+ if (line >= new_lineno) {
+ new_lasti = addr;
+ new_lineno = line;
+ break;
+ }
+ }
+ }
+
+ /* If we didn't reach the requested line, return an error. */
+ if (new_lasti == -1) {
+ PyErr_Format(PyExc_ValueError,
+ "line %d comes after the current code block",
+ new_lineno);
+ return -1;
+ }
+
+ /* We're now ready to look at the bytecode. */
+ PyString_AsStringAndSize(f->f_code->co_code, (char **)&code, &code_len);
+ min_addr = MIN(new_lasti, f->f_lasti);
+ max_addr = MAX(new_lasti, f->f_lasti);
+
+ /* You can't jump onto a line with an 'except' statement on it -
+ * they expect to have an exception on the top of the stack, which
+ * won't be true if you jump to them. They always start with code
+ * that either pops the exception using POP_TOP (plain 'except:'
+ * lines do this) or duplicates the exception on the stack using
+ * DUP_TOP (if there's an exception type specified). See compile.c,
+ * 'com_try_except' for the full details. There aren't any other
+ * cases (AFAIK) where a line's code can start with DUP_TOP or
+ * POP_TOP, but if any ever appear, they'll be subject to the same
+ * restriction (but with a different error message). */
+ if (code[new_lasti] == DUP_TOP || code[new_lasti] == POP_TOP) {
+ PyErr_SetString(PyExc_ValueError,
+ "can't jump to 'except' line as there's no exception");
+ return -1;
+ }
+
+ /* You can't jump into or out of a 'finally' block because the 'try'
+ * block leaves something on the stack for the END_FINALLY to clean
+ * up. So we walk the bytecode, maintaining a simulated blockstack.
+ * When we reach the old or new address and it's in a 'finally' block
+ * we note the address of the corresponding SETUP_FINALLY. The jump
+ * is only legal if neither address is in a 'finally' block or
+ * they're both in the same one. 'blockstack' is a stack of the
+ * bytecode addresses of the SETUP_X opcodes, and 'in_finally' tracks
+ * whether we're in a 'finally' block at each blockstack level. */
+ f_lasti_setup_addr = -1;
+ new_lasti_setup_addr = -1;
+ memset(blockstack, '\0', sizeof(blockstack));
+ memset(in_finally, '\0', sizeof(in_finally));
+ blockstack_top = 0;
+ for (addr = 0; addr < code_len; addr++) {
+ unsigned char op = code[addr];
+ switch (op) {
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ blockstack[blockstack_top++] = addr;
+ in_finally[blockstack_top-1] = 0;
+ break;
+
+ case POP_BLOCK:
+ assert(blockstack_top > 0);
+ setup_op = code[blockstack[blockstack_top-1]];
+ if (setup_op == SETUP_FINALLY) {
+ in_finally[blockstack_top-1] = 1;
+ }
+ else {
+ blockstack_top--;
+ }
+ break;
+
+ case END_FINALLY:
+ /* Ignore END_FINALLYs for SETUP_EXCEPTs - they exist
+ * in the bytecode but don't correspond to an actual
+ * 'finally' block. (If blockstack_top is 0, we must
+ * be seeing such an END_FINALLY.) */
+ if (blockstack_top > 0) {
+ setup_op = code[blockstack[blockstack_top-1]];
+ if (setup_op == SETUP_FINALLY) {
+ blockstack_top--;
+ }
+ }
+ break;
+ }
+
+ /* For the addresses we're interested in, see whether they're
+ * within a 'finally' block and if so, remember the address
+ * of the SETUP_FINALLY. */
+ if (addr == new_lasti || addr == f->f_lasti) {
+ int i = 0;
+ int setup_addr = -1;
+ for (i = blockstack_top-1; i >= 0; i--) {
+ if (in_finally[i]) {
+ setup_addr = blockstack[i];
+ break;
+ }
+ }
+
+ if (setup_addr != -1) {
+ if (addr == new_lasti) {
+ new_lasti_setup_addr = setup_addr;
+ }
+
+ if (addr == f->f_lasti) {
+ f_lasti_setup_addr = setup_addr;
+ }
+ }
+ }
+
+ if (op >= HAVE_ARGUMENT) {
+ addr += 2;
+ }
+ }
+
+ /* Verify that the blockstack tracking code didn't get lost. */
+ assert(blockstack_top == 0);
+
+ /* After all that, are we jumping into / out of a 'finally' block? */
+ if (new_lasti_setup_addr != f_lasti_setup_addr) {
+ PyErr_SetString(PyExc_ValueError,
+ "can't jump into or out of a 'finally' block");
+ return -1;
+ }
+
+
+ /* Police block-jumping (you can't jump into the middle of a block)
+ * and ensure that the blockstack finishes up in a sensible state (by
+ * popping any blocks we're jumping out of). We look at all the
+ * blockstack operations between the current position and the new
+ * one, and keep track of how many blocks we drop out of on the way.
+ * By also keeping track of the lowest blockstack position we see, we
+ * can tell whether the jump goes into any blocks without coming out
+ * again - in that case we raise an exception below. */
+ delta_iblock = 0;
+ for (addr = min_addr; addr < max_addr; addr++) {
+ unsigned char op = code[addr];
+ switch (op) {
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ delta_iblock++;
+ break;
+
+ case POP_BLOCK:
+ delta_iblock--;
+ break;
+ }
+
+ min_delta_iblock = MIN(min_delta_iblock, delta_iblock);
+
+ if (op >= HAVE_ARGUMENT) {
+ addr += 2;
+ }
+ }
+
+ /* Derive the absolute iblock values from the deltas. */
+ min_iblock = f->f_iblock + min_delta_iblock;
+ if (new_lasti > f->f_lasti) {
+ /* Forwards jump. */
+ new_iblock = f->f_iblock + delta_iblock;
+ }
+ else {
+ /* Backwards jump. */
+ new_iblock = f->f_iblock - delta_iblock;
+ }
+
+ /* Are we jumping into a block? */
+ if (new_iblock > min_iblock) {
+ PyErr_SetString(PyExc_ValueError,
+ "can't jump into the middle of a block");
+ return -1;
+ }
+
+ /* Pop any blocks that we're jumping out of. */
+ while (f->f_iblock > new_iblock) {
+ PyTryBlock *b = &f->f_blockstack[--f->f_iblock];
+ while ((f->f_stacktop - f->f_valuestack) > b->b_level) {
+ PyObject *v = (*--f->f_stacktop);
+ Py_DECREF(v);
+ }
+ }
+
+ /* Finally set the new f_lineno and f_lasti and return OK. */
+ f->f_lineno = new_lineno;
+ f->f_lasti = new_lasti;
+ return 0;
}
static PyObject *
frame_gettrace(PyFrameObject *f, void *closure)
{
- PyObject* trace = f->f_trace;
+ PyObject* trace = f->f_trace;
- if (trace == NULL)
- trace = Py_None;
+ if (trace == NULL)
+ trace = Py_None;
- Py_INCREF(trace);
+ Py_INCREF(trace);
- return trace;
+ return trace;
}
static int
frame_settrace(PyFrameObject *f, PyObject* v, void *closure)
{
- PyObject* old_value;
+ PyObject* old_value;
- /* We rely on f_lineno being accurate when f_trace is set. */
- f->f_lineno = PyFrame_GetLineNumber(f);
+ /* We rely on f_lineno being accurate when f_trace is set. */
+ f->f_lineno = PyFrame_GetLineNumber(f);
- old_value = f->f_trace;
- Py_XINCREF(v);
- f->f_trace = v;
- Py_XDECREF(old_value);
+ old_value = f->f_trace;
+ Py_XINCREF(v);
+ f->f_trace = v;
+ Py_XDECREF(old_value);
- return 0;
+ return 0;
}
static PyObject *
frame_getrestricted(PyFrameObject *f, void *closure)
{
- return PyBool_FromLong(PyFrame_IsRestricted(f));
+ return PyBool_FromLong(PyFrame_IsRestricted(f));
}
static PyGetSetDef frame_getsetlist[] = {
- {"f_locals", (getter)frame_getlocals, NULL, NULL},
- {"f_lineno", (getter)frame_getlineno,
- (setter)frame_setlineno, NULL},
- {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
- {"f_restricted",(getter)frame_getrestricted,NULL, NULL},
- {"f_exc_traceback", (getter)frame_get_f_exc_traceback,
- (setter)frame_set_f_exc_traceback, NULL},
- {"f_exc_type", (getter)frame_get_f_exc_type,
- (setter)frame_set_f_exc_type, NULL},
- {"f_exc_value", (getter)frame_get_f_exc_value,
- (setter)frame_set_f_exc_value, NULL},
- {0}
+ {"f_locals", (getter)frame_getlocals, NULL, NULL},
+ {"f_lineno", (getter)frame_getlineno,
+ (setter)frame_setlineno, NULL},
+ {"f_trace", (getter)frame_gettrace, (setter)frame_settrace, NULL},
+ {"f_restricted",(getter)frame_getrestricted,NULL, NULL},
+ {"f_exc_traceback", (getter)frame_get_f_exc_traceback,
+ (setter)frame_set_f_exc_traceback, NULL},
+ {"f_exc_type", (getter)frame_get_f_exc_type,
+ (setter)frame_set_f_exc_type, NULL},
+ {"f_exc_value", (getter)frame_get_f_exc_value,
+ (setter)frame_set_f_exc_value, NULL},
+ {0}
};
/* Stack frames are allocated and deallocated at a considerable rate.
@@ -410,7 +410,7 @@ static PyGetSetDef frame_getsetlist[] = {
the following fields are still valid:
* ob_type, ob_size, f_code, f_valuestack;
-
+
* f_locals, f_trace,
f_exc_type, f_exc_value, f_exc_traceback are NULL;
@@ -421,10 +421,10 @@ static PyGetSetDef frame_getsetlist[] = {
integers are allocated in a special way -- see intobject.c). When
a stack frame is on the free list, only the following members have
a meaning:
- ob_type == &Frametype
- f_back next item on free list, or NULL
- f_stacksize size of value stack
- ob_size size of localsplus
+ ob_type == &Frametype
+ f_back next item on free list, or NULL
+ f_stacksize size of value stack
+ ob_size size of localsplus
Note that the value and block stacks are preserved -- this can save
another malloc() call or two (and two free() calls as well!).
Also note that, unlike for integers, each frame object is a
@@ -440,307 +440,307 @@ static PyGetSetDef frame_getsetlist[] = {
*/
static PyFrameObject *free_list = NULL;
-static int numfree = 0; /* number of frames currently in free_list */
+static int numfree = 0; /* number of frames currently in free_list */
/* max value for numfree */
-#define PyFrame_MAXFREELIST 200
+#define PyFrame_MAXFREELIST 200
static void
frame_dealloc(PyFrameObject *f)
{
- PyObject **p, **valuestack;
- PyCodeObject *co;
-
- PyObject_GC_UnTrack(f);
- Py_TRASHCAN_SAFE_BEGIN(f)
- /* Kill all local variables */
- valuestack = f->f_valuestack;
- for (p = f->f_localsplus; p < valuestack; p++)
- Py_CLEAR(*p);
-
- /* Free stack */
- if (f->f_stacktop != NULL) {
- for (p = valuestack; p < f->f_stacktop; p++)
- Py_XDECREF(*p);
- }
-
- Py_XDECREF(f->f_back);
- Py_DECREF(f->f_builtins);
- Py_DECREF(f->f_globals);
- Py_CLEAR(f->f_locals);
- Py_CLEAR(f->f_trace);
- Py_CLEAR(f->f_exc_type);
- Py_CLEAR(f->f_exc_value);
- Py_CLEAR(f->f_exc_traceback);
-
- co = f->f_code;
- if (co->co_zombieframe == NULL)
- co->co_zombieframe = f;
- else if (numfree < PyFrame_MAXFREELIST) {
- ++numfree;
- f->f_back = free_list;
- free_list = f;
- }
- else
- PyObject_GC_Del(f);
-
- Py_DECREF(co);
- Py_TRASHCAN_SAFE_END(f)
+ PyObject **p, **valuestack;
+ PyCodeObject *co;
+
+ PyObject_GC_UnTrack(f);
+ Py_TRASHCAN_SAFE_BEGIN(f)
+ /* Kill all local variables */
+ valuestack = f->f_valuestack;
+ for (p = f->f_localsplus; p < valuestack; p++)
+ Py_CLEAR(*p);
+
+ /* Free stack */
+ if (f->f_stacktop != NULL) {
+ for (p = valuestack; p < f->f_stacktop; p++)
+ Py_XDECREF(*p);
+ }
+
+ Py_XDECREF(f->f_back);
+ Py_DECREF(f->f_builtins);
+ Py_DECREF(f->f_globals);
+ Py_CLEAR(f->f_locals);
+ Py_CLEAR(f->f_trace);
+ Py_CLEAR(f->f_exc_type);
+ Py_CLEAR(f->f_exc_value);
+ Py_CLEAR(f->f_exc_traceback);
+
+ co = f->f_code;
+ if (co->co_zombieframe == NULL)
+ co->co_zombieframe = f;
+ else if (numfree < PyFrame_MAXFREELIST) {
+ ++numfree;
+ f->f_back = free_list;
+ free_list = f;
+ }
+ else
+ PyObject_GC_Del(f);
+
+ Py_DECREF(co);
+ Py_TRASHCAN_SAFE_END(f)
}
static int
frame_traverse(PyFrameObject *f, visitproc visit, void *arg)
{
- PyObject **fastlocals, **p;
- int i, slots;
-
- Py_VISIT(f->f_back);
- Py_VISIT(f->f_code);
- Py_VISIT(f->f_builtins);
- Py_VISIT(f->f_globals);
- Py_VISIT(f->f_locals);
- Py_VISIT(f->f_trace);
- Py_VISIT(f->f_exc_type);
- Py_VISIT(f->f_exc_value);
- Py_VISIT(f->f_exc_traceback);
-
- /* locals */
- slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
- fastlocals = f->f_localsplus;
- for (i = slots; --i >= 0; ++fastlocals)
- Py_VISIT(*fastlocals);
-
- /* stack */
- if (f->f_stacktop != NULL) {
- for (p = f->f_valuestack; p < f->f_stacktop; p++)
- Py_VISIT(*p);
- }
- return 0;
+ PyObject **fastlocals, **p;
+ int i, slots;
+
+ Py_VISIT(f->f_back);
+ Py_VISIT(f->f_code);
+ Py_VISIT(f->f_builtins);
+ Py_VISIT(f->f_globals);
+ Py_VISIT(f->f_locals);
+ Py_VISIT(f->f_trace);
+ Py_VISIT(f->f_exc_type);
+ Py_VISIT(f->f_exc_value);
+ Py_VISIT(f->f_exc_traceback);
+
+ /* locals */
+ slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
+ fastlocals = f->f_localsplus;
+ for (i = slots; --i >= 0; ++fastlocals)
+ Py_VISIT(*fastlocals);
+
+ /* stack */
+ if (f->f_stacktop != NULL) {
+ for (p = f->f_valuestack; p < f->f_stacktop; p++)
+ Py_VISIT(*p);
+ }
+ return 0;
}
static void
frame_clear(PyFrameObject *f)
{
- PyObject **fastlocals, **p, **oldtop;
- int i, slots;
-
- /* Before anything else, make sure that this frame is clearly marked
- * as being defunct! Else, e.g., a generator reachable from this
- * frame may also point to this frame, believe itself to still be
- * active, and try cleaning up this frame again.
- */
- oldtop = f->f_stacktop;
- f->f_stacktop = NULL;
-
- Py_CLEAR(f->f_exc_type);
- Py_CLEAR(f->f_exc_value);
- Py_CLEAR(f->f_exc_traceback);
- Py_CLEAR(f->f_trace);
-
- /* locals */
- slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
- fastlocals = f->f_localsplus;
- for (i = slots; --i >= 0; ++fastlocals)
- Py_CLEAR(*fastlocals);
-
- /* stack */
- if (oldtop != NULL) {
- for (p = f->f_valuestack; p < oldtop; p++)
- Py_CLEAR(*p);
- }
+ PyObject **fastlocals, **p, **oldtop;
+ int i, slots;
+
+ /* Before anything else, make sure that this frame is clearly marked
+ * as being defunct! Else, e.g., a generator reachable from this
+ * frame may also point to this frame, believe itself to still be
+ * active, and try cleaning up this frame again.
+ */
+ oldtop = f->f_stacktop;
+ f->f_stacktop = NULL;
+
+ Py_CLEAR(f->f_exc_type);
+ Py_CLEAR(f->f_exc_value);
+ Py_CLEAR(f->f_exc_traceback);
+ Py_CLEAR(f->f_trace);
+
+ /* locals */
+ slots = f->f_code->co_nlocals + PyTuple_GET_SIZE(f->f_code->co_cellvars) + PyTuple_GET_SIZE(f->f_code->co_freevars);
+ fastlocals = f->f_localsplus;
+ for (i = slots; --i >= 0; ++fastlocals)
+ Py_CLEAR(*fastlocals);
+
+ /* stack */
+ if (oldtop != NULL) {
+ for (p = f->f_valuestack; p < oldtop; p++)
+ Py_CLEAR(*p);
+ }
}
static PyObject *
frame_sizeof(PyFrameObject *f)
{
- Py_ssize_t res, extras, ncells, nfrees;
+ Py_ssize_t res, extras, ncells, nfrees;
- ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
- nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
- extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
- ncells + nfrees;
- /* subtract one as it is already included in PyFrameObject */
- res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
+ ncells = PyTuple_GET_SIZE(f->f_code->co_cellvars);
+ nfrees = PyTuple_GET_SIZE(f->f_code->co_freevars);
+ extras = f->f_code->co_stacksize + f->f_code->co_nlocals +
+ ncells + nfrees;
+ /* subtract one as it is already included in PyFrameObject */
+ res = sizeof(PyFrameObject) + (extras-1) * sizeof(PyObject *);
- return PyInt_FromSsize_t(res);
+ return PyInt_FromSsize_t(res);
}
PyDoc_STRVAR(sizeof__doc__,
"F.__sizeof__() -> size of F in memory, in bytes");
static PyMethodDef frame_methods[] = {
- {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
- sizeof__doc__},
- {NULL, NULL} /* sentinel */
+ {"__sizeof__", (PyCFunction)frame_sizeof, METH_NOARGS,
+ sizeof__doc__},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyFrame_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "frame",
- sizeof(PyFrameObject),
- sizeof(PyObject *),
- (destructor)frame_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 */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)frame_traverse, /* tp_traverse */
- (inquiry)frame_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- frame_methods, /* tp_methods */
- frame_memberlist, /* tp_members */
- frame_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "frame",
+ sizeof(PyFrameObject),
+ sizeof(PyObject *),
+ (destructor)frame_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 */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)frame_traverse, /* tp_traverse */
+ (inquiry)frame_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ frame_methods, /* tp_methods */
+ frame_memberlist, /* tp_members */
+ frame_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
};
static PyObject *builtin_object;
int _PyFrame_Init()
{
- builtin_object = PyString_InternFromString("__builtins__");
- if (builtin_object == NULL)
- return 0;
- return 1;
+ builtin_object = PyString_InternFromString("__builtins__");
+ if (builtin_object == NULL)
+ return 0;
+ return 1;
}
PyFrameObject *
PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
- PyObject *locals)
+ PyObject *locals)
{
- PyFrameObject *back = tstate->frame;
- PyFrameObject *f;
- PyObject *builtins;
- Py_ssize_t i;
+ PyFrameObject *back = tstate->frame;
+ PyFrameObject *f;
+ PyObject *builtins;
+ Py_ssize_t i;
#ifdef Py_DEBUG
- if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
- (locals != NULL && !PyMapping_Check(locals))) {
- PyErr_BadInternalCall();
- return NULL;
- }
+ if (code == NULL || globals == NULL || !PyDict_Check(globals) ||
+ (locals != NULL && !PyMapping_Check(locals))) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
#endif
- if (back == NULL || back->f_globals != globals) {
- builtins = PyDict_GetItem(globals, builtin_object);
- if (builtins) {
- if (PyModule_Check(builtins)) {
- builtins = PyModule_GetDict(builtins);
- assert(!builtins || PyDict_Check(builtins));
- }
- else if (!PyDict_Check(builtins))
- builtins = NULL;
- }
- if (builtins == NULL) {
- /* No builtins! Make up a minimal one
- Give them 'None', at least. */
- builtins = PyDict_New();
- if (builtins == NULL ||
- PyDict_SetItemString(
- builtins, "None", Py_None) < 0)
- return NULL;
- }
- else
- Py_INCREF(builtins);
-
- }
- else {
- /* If we share the globals, we share the builtins.
- Save a lookup and a call. */
- builtins = back->f_builtins;
- assert(builtins != NULL && PyDict_Check(builtins));
- Py_INCREF(builtins);
- }
- if (code->co_zombieframe != NULL) {
- f = code->co_zombieframe;
- code->co_zombieframe = NULL;
- _Py_NewReference((PyObject *)f);
- assert(f->f_code == code);
- }
- else {
- Py_ssize_t extras, ncells, nfrees;
- ncells = PyTuple_GET_SIZE(code->co_cellvars);
- nfrees = PyTuple_GET_SIZE(code->co_freevars);
- extras = code->co_stacksize + code->co_nlocals + ncells +
- nfrees;
- if (free_list == NULL) {
- f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
- extras);
- if (f == NULL) {
- Py_DECREF(builtins);
- return NULL;
- }
- }
- else {
- assert(numfree > 0);
- --numfree;
- f = free_list;
- free_list = free_list->f_back;
- if (Py_SIZE(f) < extras) {
- f = PyObject_GC_Resize(PyFrameObject, f, extras);
- if (f == NULL) {
- Py_DECREF(builtins);
- return NULL;
- }
- }
- _Py_NewReference((PyObject *)f);
- }
-
- f->f_code = code;
- extras = code->co_nlocals + ncells + nfrees;
- f->f_valuestack = f->f_localsplus + extras;
- for (i=0; i<extras; i++)
- f->f_localsplus[i] = NULL;
- f->f_locals = NULL;
- f->f_trace = NULL;
- f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
- }
- f->f_stacktop = f->f_valuestack;
- f->f_builtins = builtins;
- Py_XINCREF(back);
- f->f_back = back;
- Py_INCREF(code);
- Py_INCREF(globals);
- f->f_globals = globals;
- /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
- if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
- (CO_NEWLOCALS | CO_OPTIMIZED))
- ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
- else if (code->co_flags & CO_NEWLOCALS) {
- locals = PyDict_New();
- if (locals == NULL) {
- Py_DECREF(f);
- return NULL;
- }
- f->f_locals = locals;
- }
- else {
- if (locals == NULL)
- locals = globals;
- Py_INCREF(locals);
- f->f_locals = locals;
- }
- f->f_tstate = tstate;
-
- f->f_lasti = -1;
- f->f_lineno = code->co_firstlineno;
- f->f_iblock = 0;
-
- _PyObject_GC_TRACK(f);
- return f;
+ if (back == NULL || back->f_globals != globals) {
+ builtins = PyDict_GetItem(globals, builtin_object);
+ if (builtins) {
+ if (PyModule_Check(builtins)) {
+ builtins = PyModule_GetDict(builtins);
+ assert(!builtins || PyDict_Check(builtins));
+ }
+ else if (!PyDict_Check(builtins))
+ builtins = NULL;
+ }
+ if (builtins == NULL) {
+ /* No builtins! Make up a minimal one
+ Give them 'None', at least. */
+ builtins = PyDict_New();
+ if (builtins == NULL ||
+ PyDict_SetItemString(
+ builtins, "None", Py_None) < 0)
+ return NULL;
+ }
+ else
+ Py_INCREF(builtins);
+
+ }
+ else {
+ /* If we share the globals, we share the builtins.
+ Save a lookup and a call. */
+ builtins = back->f_builtins;
+ assert(builtins != NULL && PyDict_Check(builtins));
+ Py_INCREF(builtins);
+ }
+ if (code->co_zombieframe != NULL) {
+ f = code->co_zombieframe;
+ code->co_zombieframe = NULL;
+ _Py_NewReference((PyObject *)f);
+ assert(f->f_code == code);
+ }
+ else {
+ Py_ssize_t extras, ncells, nfrees;
+ ncells = PyTuple_GET_SIZE(code->co_cellvars);
+ nfrees = PyTuple_GET_SIZE(code->co_freevars);
+ extras = code->co_stacksize + code->co_nlocals + ncells +
+ nfrees;
+ if (free_list == NULL) {
+ f = PyObject_GC_NewVar(PyFrameObject, &PyFrame_Type,
+ extras);
+ if (f == NULL) {
+ Py_DECREF(builtins);
+ return NULL;
+ }
+ }
+ else {
+ assert(numfree > 0);
+ --numfree;
+ f = free_list;
+ free_list = free_list->f_back;
+ if (Py_SIZE(f) < extras) {
+ f = PyObject_GC_Resize(PyFrameObject, f, extras);
+ if (f == NULL) {
+ Py_DECREF(builtins);
+ return NULL;
+ }
+ }
+ _Py_NewReference((PyObject *)f);
+ }
+
+ f->f_code = code;
+ extras = code->co_nlocals + ncells + nfrees;
+ f->f_valuestack = f->f_localsplus + extras;
+ for (i=0; i<extras; i++)
+ f->f_localsplus[i] = NULL;
+ f->f_locals = NULL;
+ f->f_trace = NULL;
+ f->f_exc_type = f->f_exc_value = f->f_exc_traceback = NULL;
+ }
+ f->f_stacktop = f->f_valuestack;
+ f->f_builtins = builtins;
+ Py_XINCREF(back);
+ f->f_back = back;
+ Py_INCREF(code);
+ Py_INCREF(globals);
+ f->f_globals = globals;
+ /* Most functions have CO_NEWLOCALS and CO_OPTIMIZED set. */
+ if ((code->co_flags & (CO_NEWLOCALS | CO_OPTIMIZED)) ==
+ (CO_NEWLOCALS | CO_OPTIMIZED))
+ ; /* f_locals = NULL; will be set by PyFrame_FastToLocals() */
+ else if (code->co_flags & CO_NEWLOCALS) {
+ locals = PyDict_New();
+ if (locals == NULL) {
+ Py_DECREF(f);
+ return NULL;
+ }
+ f->f_locals = locals;
+ }
+ else {
+ if (locals == NULL)
+ locals = globals;
+ Py_INCREF(locals);
+ f->f_locals = locals;
+ }
+ f->f_tstate = tstate;
+
+ f->f_lasti = -1;
+ f->f_lineno = code->co_firstlineno;
+ f->f_iblock = 0;
+
+ _PyObject_GC_TRACK(f);
+ return f;
}
/* Block management */
@@ -748,28 +748,28 @@ PyFrame_New(PyThreadState *tstate, PyCodeObject *code, PyObject *globals,
void
PyFrame_BlockSetup(PyFrameObject *f, int type, int handler, int level)
{
- PyTryBlock *b;
- if (f->f_iblock >= CO_MAXBLOCKS)
- Py_FatalError("XXX block stack overflow");
- b = &f->f_blockstack[f->f_iblock++];
- b->b_type = type;
- b->b_level = level;
- b->b_handler = handler;
+ PyTryBlock *b;
+ if (f->f_iblock >= CO_MAXBLOCKS)
+ Py_FatalError("XXX block stack overflow");
+ b = &f->f_blockstack[f->f_iblock++];
+ b->b_type = type;
+ b->b_level = level;
+ b->b_handler = handler;
}
PyTryBlock *
PyFrame_BlockPop(PyFrameObject *f)
{
- PyTryBlock *b;
- if (f->f_iblock <= 0)
- Py_FatalError("XXX block stack underflow");
- b = &f->f_blockstack[--f->f_iblock];
- return b;
+ PyTryBlock *b;
+ if (f->f_iblock <= 0)
+ Py_FatalError("XXX block stack underflow");
+ b = &f->f_blockstack[--f->f_iblock];
+ return b;
}
/* Convert between "fast" version of locals and dictionary version.
-
- map and values are input arguments. map is a tuple of strings.
+
+ map and values are input arguments. map is a tuple of strings.
values is an array of PyObject*. At index i, map[i] is the name of
the variable with value values[i]. The function copies the first
nmap variable from map/values into dict. If values[i] is NULL,
@@ -785,29 +785,29 @@ PyFrame_BlockPop(PyFrameObject *f)
static void
map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
- int deref)
+ int deref)
{
- Py_ssize_t j;
- assert(PyTuple_Check(map));
- assert(PyDict_Check(dict));
- assert(PyTuple_Size(map) >= nmap);
- for (j = nmap; --j >= 0; ) {
- PyObject *key = PyTuple_GET_ITEM(map, j);
- PyObject *value = values[j];
- assert(PyString_Check(key));
- if (deref) {
- assert(PyCell_Check(value));
- value = PyCell_GET(value);
- }
- if (value == NULL) {
- if (PyObject_DelItem(dict, key) != 0)
- PyErr_Clear();
- }
- else {
- if (PyObject_SetItem(dict, key, value) != 0)
- PyErr_Clear();
- }
- }
+ Py_ssize_t j;
+ assert(PyTuple_Check(map));
+ assert(PyDict_Check(dict));
+ assert(PyTuple_Size(map) >= nmap);
+ for (j = nmap; --j >= 0; ) {
+ PyObject *key = PyTuple_GET_ITEM(map, j);
+ PyObject *value = values[j];
+ assert(PyString_Check(key));
+ if (deref) {
+ assert(PyCell_Check(value));
+ value = PyCell_GET(value);
+ }
+ if (value == NULL) {
+ if (PyObject_DelItem(dict, key) != 0)
+ PyErr_Clear();
+ }
+ else {
+ if (PyObject_SetItem(dict, key, value) != 0)
+ PyErr_Clear();
+ }
+ }
}
/* Copy values from the "locals" dict into the fast locals.
@@ -815,7 +815,7 @@ map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
dict is an input argument containing string keys representing
variables names and arbitrary PyObject* as values.
- map and values are input arguments. map is a tuple of strings.
+ map and values are input arguments. map is a tuple of strings.
values is an array of PyObject*. At index i, map[i] is the name of
the variable with value values[i]. The function copies the first
nmap variable from map/values into dict. If values[i] is NULL,
@@ -833,150 +833,150 @@ map_to_dict(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
static void
dict_to_map(PyObject *map, Py_ssize_t nmap, PyObject *dict, PyObject **values,
- int deref, int clear)
+ int deref, int clear)
{
- Py_ssize_t j;
- assert(PyTuple_Check(map));
- assert(PyDict_Check(dict));
- assert(PyTuple_Size(map) >= nmap);
- for (j = nmap; --j >= 0; ) {
- PyObject *key = PyTuple_GET_ITEM(map, j);
- PyObject *value = PyObject_GetItem(dict, key);
- assert(PyString_Check(key));
- /* We only care about NULLs if clear is true. */
- if (value == NULL) {
- PyErr_Clear();
- if (!clear)
- continue;
- }
- if (deref) {
- assert(PyCell_Check(values[j]));
- if (PyCell_GET(values[j]) != value) {
- if (PyCell_Set(values[j], value) < 0)
- PyErr_Clear();
- }
- } else if (values[j] != value) {
- Py_XINCREF(value);
- Py_XDECREF(values[j]);
- values[j] = value;
- }
- Py_XDECREF(value);
- }
+ Py_ssize_t j;
+ assert(PyTuple_Check(map));
+ assert(PyDict_Check(dict));
+ assert(PyTuple_Size(map) >= nmap);
+ for (j = nmap; --j >= 0; ) {
+ PyObject *key = PyTuple_GET_ITEM(map, j);
+ PyObject *value = PyObject_GetItem(dict, key);
+ assert(PyString_Check(key));
+ /* We only care about NULLs if clear is true. */
+ if (value == NULL) {
+ PyErr_Clear();
+ if (!clear)
+ continue;
+ }
+ if (deref) {
+ assert(PyCell_Check(values[j]));
+ if (PyCell_GET(values[j]) != value) {
+ if (PyCell_Set(values[j], value) < 0)
+ PyErr_Clear();
+ }
+ } else if (values[j] != value) {
+ Py_XINCREF(value);
+ Py_XDECREF(values[j]);
+ values[j] = value;
+ }
+ Py_XDECREF(value);
+ }
}
void
PyFrame_FastToLocals(PyFrameObject *f)
{
- /* Merge fast locals into f->f_locals */
- PyObject *locals, *map;
- PyObject **fast;
- PyObject *error_type, *error_value, *error_traceback;
- PyCodeObject *co;
- Py_ssize_t j;
- int ncells, nfreevars;
- if (f == NULL)
- return;
- locals = f->f_locals;
- if (locals == NULL) {
- locals = f->f_locals = PyDict_New();
- if (locals == NULL) {
- PyErr_Clear(); /* Can't report it :-( */
- return;
- }
- }
- co = f->f_code;
- map = co->co_varnames;
- if (!PyTuple_Check(map))
- return;
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
- fast = f->f_localsplus;
- j = PyTuple_GET_SIZE(map);
- if (j > co->co_nlocals)
- j = co->co_nlocals;
- if (co->co_nlocals)
- map_to_dict(map, j, locals, fast, 0);
- ncells = PyTuple_GET_SIZE(co->co_cellvars);
- nfreevars = PyTuple_GET_SIZE(co->co_freevars);
- if (ncells || nfreevars) {
- map_to_dict(co->co_cellvars, ncells,
- locals, fast + co->co_nlocals, 1);
- /* If the namespace is unoptimized, then one of the
- following cases applies:
- 1. It does not contain free variables, because it
- uses import * or is a top-level namespace.
- 2. It is a class namespace.
- We don't want to accidentally copy free variables
- into the locals dict used by the class.
- */
- if (co->co_flags & CO_OPTIMIZED) {
- map_to_dict(co->co_freevars, nfreevars,
- locals, fast + co->co_nlocals + ncells, 1);
- }
- }
- PyErr_Restore(error_type, error_value, error_traceback);
+ /* Merge fast locals into f->f_locals */
+ PyObject *locals, *map;
+ PyObject **fast;
+ PyObject *error_type, *error_value, *error_traceback;
+ PyCodeObject *co;
+ Py_ssize_t j;
+ int ncells, nfreevars;
+ if (f == NULL)
+ return;
+ locals = f->f_locals;
+ if (locals == NULL) {
+ locals = f->f_locals = PyDict_New();
+ if (locals == NULL) {
+ PyErr_Clear(); /* Can't report it :-( */
+ return;
+ }
+ }
+ co = f->f_code;
+ map = co->co_varnames;
+ if (!PyTuple_Check(map))
+ return;
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ fast = f->f_localsplus;
+ j = PyTuple_GET_SIZE(map);
+ if (j > co->co_nlocals)
+ j = co->co_nlocals;
+ if (co->co_nlocals)
+ map_to_dict(map, j, locals, fast, 0);
+ ncells = PyTuple_GET_SIZE(co->co_cellvars);
+ nfreevars = PyTuple_GET_SIZE(co->co_freevars);
+ if (ncells || nfreevars) {
+ map_to_dict(co->co_cellvars, ncells,
+ locals, fast + co->co_nlocals, 1);
+ /* If the namespace is unoptimized, then one of the
+ following cases applies:
+ 1. It does not contain free variables, because it
+ uses import * or is a top-level namespace.
+ 2. It is a class namespace.
+ We don't want to accidentally copy free variables
+ into the locals dict used by the class.
+ */
+ if (co->co_flags & CO_OPTIMIZED) {
+ map_to_dict(co->co_freevars, nfreevars,
+ locals, fast + co->co_nlocals + ncells, 1);
+ }
+ }
+ PyErr_Restore(error_type, error_value, error_traceback);
}
void
PyFrame_LocalsToFast(PyFrameObject *f, int clear)
{
- /* Merge f->f_locals into fast locals */
- PyObject *locals, *map;
- PyObject **fast;
- PyObject *error_type, *error_value, *error_traceback;
- PyCodeObject *co;
- Py_ssize_t j;
- int ncells, nfreevars;
- if (f == NULL)
- return;
- locals = f->f_locals;
- co = f->f_code;
- map = co->co_varnames;
- if (locals == NULL)
- return;
- if (!PyTuple_Check(map))
- return;
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
- fast = f->f_localsplus;
- j = PyTuple_GET_SIZE(map);
- if (j > co->co_nlocals)
- j = co->co_nlocals;
- if (co->co_nlocals)
- dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
- ncells = PyTuple_GET_SIZE(co->co_cellvars);
- nfreevars = PyTuple_GET_SIZE(co->co_freevars);
- if (ncells || nfreevars) {
- dict_to_map(co->co_cellvars, ncells,
- locals, fast + co->co_nlocals, 1, clear);
- /* Same test as in PyFrame_FastToLocals() above. */
- if (co->co_flags & CO_OPTIMIZED) {
- dict_to_map(co->co_freevars, nfreevars,
- locals, fast + co->co_nlocals + ncells, 1,
- clear);
- }
- }
- PyErr_Restore(error_type, error_value, error_traceback);
+ /* Merge f->f_locals into fast locals */
+ PyObject *locals, *map;
+ PyObject **fast;
+ PyObject *error_type, *error_value, *error_traceback;
+ PyCodeObject *co;
+ Py_ssize_t j;
+ int ncells, nfreevars;
+ if (f == NULL)
+ return;
+ locals = f->f_locals;
+ co = f->f_code;
+ map = co->co_varnames;
+ if (locals == NULL)
+ return;
+ if (!PyTuple_Check(map))
+ return;
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ fast = f->f_localsplus;
+ j = PyTuple_GET_SIZE(map);
+ if (j > co->co_nlocals)
+ j = co->co_nlocals;
+ if (co->co_nlocals)
+ dict_to_map(co->co_varnames, j, locals, fast, 0, clear);
+ ncells = PyTuple_GET_SIZE(co->co_cellvars);
+ nfreevars = PyTuple_GET_SIZE(co->co_freevars);
+ if (ncells || nfreevars) {
+ dict_to_map(co->co_cellvars, ncells,
+ locals, fast + co->co_nlocals, 1, clear);
+ /* Same test as in PyFrame_FastToLocals() above. */
+ if (co->co_flags & CO_OPTIMIZED) {
+ dict_to_map(co->co_freevars, nfreevars,
+ locals, fast + co->co_nlocals + ncells, 1,
+ clear);
+ }
+ }
+ PyErr_Restore(error_type, error_value, error_traceback);
}
/* Clear out the free list */
int
PyFrame_ClearFreeList(void)
{
- int freelist_size = numfree;
-
- while (free_list != NULL) {
- PyFrameObject *f = free_list;
- free_list = free_list->f_back;
- PyObject_GC_Del(f);
- --numfree;
- }
- assert(numfree == 0);
- return freelist_size;
+ int freelist_size = numfree;
+
+ while (free_list != NULL) {
+ PyFrameObject *f = free_list;
+ free_list = free_list->f_back;
+ PyObject_GC_Del(f);
+ --numfree;
+ }
+ assert(numfree == 0);
+ return freelist_size;
}
void
PyFrame_Fini(void)
{
- (void)PyFrame_ClearFreeList();
- Py_XDECREF(builtin_object);
- builtin_object = NULL;
+ (void)PyFrame_ClearFreeList();
+ Py_XDECREF(builtin_object);
+ builtin_object = NULL;
}
diff --git a/Objects/funcobject.c b/Objects/funcobject.c
index 075f820..ad0f427 100644
--- a/Objects/funcobject.c
+++ b/Objects/funcobject.c
@@ -9,149 +9,149 @@
PyObject *
PyFunction_New(PyObject *code, PyObject *globals)
{
- PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
- &PyFunction_Type);
- static PyObject *__name__ = 0;
- if (op != NULL) {
- PyObject *doc;
- PyObject *consts;
- PyObject *module;
- op->func_weakreflist = NULL;
- Py_INCREF(code);
- op->func_code = code;
- Py_INCREF(globals);
- op->func_globals = globals;
- op->func_name = ((PyCodeObject *)code)->co_name;
- Py_INCREF(op->func_name);
- op->func_defaults = NULL; /* No default arguments */
- op->func_closure = NULL;
- consts = ((PyCodeObject *)code)->co_consts;
- if (PyTuple_Size(consts) >= 1) {
- doc = PyTuple_GetItem(consts, 0);
- if (!PyString_Check(doc) && !PyUnicode_Check(doc))
- doc = Py_None;
- }
- else
- doc = Py_None;
- Py_INCREF(doc);
- op->func_doc = doc;
- op->func_dict = NULL;
- op->func_module = NULL;
-
- /* __module__: If module name is in globals, use it.
- Otherwise, use None.
- */
- if (!__name__) {
- __name__ = PyString_InternFromString("__name__");
- if (!__name__) {
- Py_DECREF(op);
- return NULL;
- }
- }
- module = PyDict_GetItem(globals, __name__);
- if (module) {
- Py_INCREF(module);
- op->func_module = module;
- }
- }
- else
- return NULL;
- _PyObject_GC_TRACK(op);
- return (PyObject *)op;
+ PyFunctionObject *op = PyObject_GC_New(PyFunctionObject,
+ &PyFunction_Type);
+ static PyObject *__name__ = 0;
+ if (op != NULL) {
+ PyObject *doc;
+ PyObject *consts;
+ PyObject *module;
+ op->func_weakreflist = NULL;
+ Py_INCREF(code);
+ op->func_code = code;
+ Py_INCREF(globals);
+ op->func_globals = globals;
+ op->func_name = ((PyCodeObject *)code)->co_name;
+ Py_INCREF(op->func_name);
+ op->func_defaults = NULL; /* No default arguments */
+ op->func_closure = NULL;
+ consts = ((PyCodeObject *)code)->co_consts;
+ if (PyTuple_Size(consts) >= 1) {
+ doc = PyTuple_GetItem(consts, 0);
+ if (!PyString_Check(doc) && !PyUnicode_Check(doc))
+ doc = Py_None;
+ }
+ else
+ doc = Py_None;
+ Py_INCREF(doc);
+ op->func_doc = doc;
+ op->func_dict = NULL;
+ op->func_module = NULL;
+
+ /* __module__: If module name is in globals, use it.
+ Otherwise, use None.
+ */
+ if (!__name__) {
+ __name__ = PyString_InternFromString("__name__");
+ if (!__name__) {
+ Py_DECREF(op);
+ return NULL;
+ }
+ }
+ module = PyDict_GetItem(globals, __name__);
+ if (module) {
+ Py_INCREF(module);
+ op->func_module = module;
+ }
+ }
+ else
+ return NULL;
+ _PyObject_GC_TRACK(op);
+ return (PyObject *)op;
}
PyObject *
PyFunction_GetCode(PyObject *op)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyFunctionObject *) op) -> func_code;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyFunctionObject *) op) -> func_code;
}
PyObject *
PyFunction_GetGlobals(PyObject *op)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyFunctionObject *) op) -> func_globals;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyFunctionObject *) op) -> func_globals;
}
PyObject *
PyFunction_GetModule(PyObject *op)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyFunctionObject *) op) -> func_module;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyFunctionObject *) op) -> func_module;
}
PyObject *
PyFunction_GetDefaults(PyObject *op)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyFunctionObject *) op) -> func_defaults;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyFunctionObject *) op) -> func_defaults;
}
int
PyFunction_SetDefaults(PyObject *op, PyObject *defaults)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (defaults == Py_None)
- defaults = NULL;
- else if (defaults && PyTuple_Check(defaults)) {
- Py_INCREF(defaults);
- }
- else {
- PyErr_SetString(PyExc_SystemError, "non-tuple default args");
- return -1;
- }
- Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
- ((PyFunctionObject *) op) -> func_defaults = defaults;
- return 0;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (defaults == Py_None)
+ defaults = NULL;
+ else if (defaults && PyTuple_Check(defaults)) {
+ Py_INCREF(defaults);
+ }
+ else {
+ PyErr_SetString(PyExc_SystemError, "non-tuple default args");
+ return -1;
+ }
+ Py_XDECREF(((PyFunctionObject *) op) -> func_defaults);
+ ((PyFunctionObject *) op) -> func_defaults = defaults;
+ return 0;
}
PyObject *
PyFunction_GetClosure(PyObject *op)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyFunctionObject *) op) -> func_closure;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyFunctionObject *) op) -> func_closure;
}
int
PyFunction_SetClosure(PyObject *op, PyObject *closure)
{
- if (!PyFunction_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (closure == Py_None)
- closure = NULL;
- else if (PyTuple_Check(closure)) {
- Py_INCREF(closure);
- }
- else {
- PyErr_Format(PyExc_SystemError,
- "expected tuple for closure, got '%.100s'",
- closure->ob_type->tp_name);
- return -1;
- }
- Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
- ((PyFunctionObject *) op) -> func_closure = closure;
- return 0;
+ if (!PyFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (closure == Py_None)
+ closure = NULL;
+ else if (PyTuple_Check(closure)) {
+ Py_INCREF(closure);
+ }
+ else {
+ PyErr_Format(PyExc_SystemError,
+ "expected tuple for closure, got '%.100s'",
+ closure->ob_type->tp_name);
+ return -1;
+ }
+ Py_XDECREF(((PyFunctionObject *) op) -> func_closure);
+ ((PyFunctionObject *) op) -> func_closure = closure;
+ return 0;
}
/* Methods */
@@ -159,188 +159,188 @@ PyFunction_SetClosure(PyObject *op, PyObject *closure)
#define OFF(x) offsetof(PyFunctionObject, x)
static PyMemberDef func_memberlist[] = {
- {"func_closure", T_OBJECT, OFF(func_closure),
- RESTRICTED|READONLY},
- {"__closure__", T_OBJECT, OFF(func_closure),
- RESTRICTED|READONLY},
- {"func_doc", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
- {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
- {"func_globals", T_OBJECT, OFF(func_globals),
- RESTRICTED|READONLY},
- {"__globals__", T_OBJECT, OFF(func_globals),
- RESTRICTED|READONLY},
- {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED},
- {NULL} /* Sentinel */
+ {"func_closure", T_OBJECT, OFF(func_closure),
+ RESTRICTED|READONLY},
+ {"__closure__", T_OBJECT, OFF(func_closure),
+ RESTRICTED|READONLY},
+ {"func_doc", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
+ {"__doc__", T_OBJECT, OFF(func_doc), PY_WRITE_RESTRICTED},
+ {"func_globals", T_OBJECT, OFF(func_globals),
+ RESTRICTED|READONLY},
+ {"__globals__", T_OBJECT, OFF(func_globals),
+ RESTRICTED|READONLY},
+ {"__module__", T_OBJECT, OFF(func_module), PY_WRITE_RESTRICTED},
+ {NULL} /* Sentinel */
};
static int
restricted(void)
{
- if (!PyEval_GetRestricted())
- return 0;
- PyErr_SetString(PyExc_RuntimeError,
- "function attributes not accessible in restricted mode");
- return 1;
+ if (!PyEval_GetRestricted())
+ return 0;
+ PyErr_SetString(PyExc_RuntimeError,
+ "function attributes not accessible in restricted mode");
+ return 1;
}
static PyObject *
func_get_dict(PyFunctionObject *op)
{
- if (restricted())
- return NULL;
- if (op->func_dict == NULL) {
- op->func_dict = PyDict_New();
- if (op->func_dict == NULL)
- return NULL;
- }
- Py_INCREF(op->func_dict);
- return op->func_dict;
+ if (restricted())
+ return NULL;
+ if (op->func_dict == NULL) {
+ op->func_dict = PyDict_New();
+ if (op->func_dict == NULL)
+ return NULL;
+ }
+ Py_INCREF(op->func_dict);
+ return op->func_dict;
}
static int
func_set_dict(PyFunctionObject *op, PyObject *value)
{
- PyObject *tmp;
-
- if (restricted())
- return -1;
- /* It is illegal to del f.func_dict */
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "function's dictionary may not be deleted");
- return -1;
- }
- /* Can only set func_dict to a dictionary */
- if (!PyDict_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "setting function's dictionary to a non-dict");
- return -1;
- }
- tmp = op->func_dict;
- Py_INCREF(value);
- op->func_dict = value;
- Py_XDECREF(tmp);
- return 0;
+ PyObject *tmp;
+
+ if (restricted())
+ return -1;
+ /* It is illegal to del f.func_dict */
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "function's dictionary may not be deleted");
+ return -1;
+ }
+ /* Can only set func_dict to a dictionary */
+ if (!PyDict_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "setting function's dictionary to a non-dict");
+ return -1;
+ }
+ tmp = op->func_dict;
+ Py_INCREF(value);
+ op->func_dict = value;
+ Py_XDECREF(tmp);
+ return 0;
}
static PyObject *
func_get_code(PyFunctionObject *op)
{
- if (restricted())
- return NULL;
- Py_INCREF(op->func_code);
- return op->func_code;
+ if (restricted())
+ return NULL;
+ Py_INCREF(op->func_code);
+ return op->func_code;
}
static int
func_set_code(PyFunctionObject *op, PyObject *value)
{
- PyObject *tmp;
- Py_ssize_t nfree, nclosure;
-
- if (restricted())
- return -1;
- /* Not legal to del f.func_code or to set it to anything
- * other than a code object. */
- if (value == NULL || !PyCode_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "__code__ must be set to a code object");
- return -1;
- }
- nfree = PyCode_GetNumFree((PyCodeObject *)value);
- nclosure = (op->func_closure == NULL ? 0 :
- PyTuple_GET_SIZE(op->func_closure));
- if (nclosure != nfree) {
- PyErr_Format(PyExc_ValueError,
- "%s() requires a code object with %zd free vars,"
- " not %zd",
- PyString_AsString(op->func_name),
- nclosure, nfree);
- return -1;
- }
- tmp = op->func_code;
- Py_INCREF(value);
- op->func_code = value;
- Py_DECREF(tmp);
- return 0;
+ PyObject *tmp;
+ Py_ssize_t nfree, nclosure;
+
+ if (restricted())
+ return -1;
+ /* Not legal to del f.func_code or to set it to anything
+ * other than a code object. */
+ if (value == NULL || !PyCode_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__code__ must be set to a code object");
+ return -1;
+ }
+ nfree = PyCode_GetNumFree((PyCodeObject *)value);
+ nclosure = (op->func_closure == NULL ? 0 :
+ PyTuple_GET_SIZE(op->func_closure));
+ if (nclosure != nfree) {
+ PyErr_Format(PyExc_ValueError,
+ "%s() requires a code object with %zd free vars,"
+ " not %zd",
+ PyString_AsString(op->func_name),
+ nclosure, nfree);
+ return -1;
+ }
+ tmp = op->func_code;
+ Py_INCREF(value);
+ op->func_code = value;
+ Py_DECREF(tmp);
+ return 0;
}
static PyObject *
func_get_name(PyFunctionObject *op)
{
- Py_INCREF(op->func_name);
- return op->func_name;
+ Py_INCREF(op->func_name);
+ return op->func_name;
}
static int
func_set_name(PyFunctionObject *op, PyObject *value)
{
- PyObject *tmp;
+ PyObject *tmp;
- if (restricted())
- return -1;
- /* Not legal to del f.func_name or to set it to anything
- * other than a string object. */
- if (value == NULL || !PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "__name__ must be set to a string object");
- return -1;
- }
- tmp = op->func_name;
- Py_INCREF(value);
- op->func_name = value;
- Py_DECREF(tmp);
- return 0;
+ if (restricted())
+ return -1;
+ /* Not legal to del f.func_name or to set it to anything
+ * other than a string object. */
+ if (value == NULL || !PyString_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__name__ must be set to a string object");
+ return -1;
+ }
+ tmp = op->func_name;
+ Py_INCREF(value);
+ op->func_name = value;
+ Py_DECREF(tmp);
+ return 0;
}
static PyObject *
func_get_defaults(PyFunctionObject *op)
{
- if (restricted())
- return NULL;
- if (op->func_defaults == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- Py_INCREF(op->func_defaults);
- return op->func_defaults;
+ if (restricted())
+ return NULL;
+ if (op->func_defaults == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ Py_INCREF(op->func_defaults);
+ return op->func_defaults;
}
static int
func_set_defaults(PyFunctionObject *op, PyObject *value)
{
- PyObject *tmp;
-
- if (restricted())
- return -1;
- /* Legal to del f.func_defaults.
- * Can only set func_defaults to NULL or a tuple. */
- if (value == Py_None)
- value = NULL;
- if (value != NULL && !PyTuple_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "__defaults__ must be set to a tuple object");
- return -1;
- }
- tmp = op->func_defaults;
- Py_XINCREF(value);
- op->func_defaults = value;
- Py_XDECREF(tmp);
- return 0;
+ PyObject *tmp;
+
+ if (restricted())
+ return -1;
+ /* Legal to del f.func_defaults.
+ * Can only set func_defaults to NULL or a tuple. */
+ if (value == Py_None)
+ value = NULL;
+ if (value != NULL && !PyTuple_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "__defaults__ must be set to a tuple object");
+ return -1;
+ }
+ tmp = op->func_defaults;
+ Py_XINCREF(value);
+ op->func_defaults = value;
+ Py_XDECREF(tmp);
+ return 0;
}
static PyGetSetDef func_getsetlist[] = {
- {"func_code", (getter)func_get_code, (setter)func_set_code},
- {"__code__", (getter)func_get_code, (setter)func_set_code},
- {"func_defaults", (getter)func_get_defaults,
- (setter)func_set_defaults},
- {"__defaults__", (getter)func_get_defaults,
- (setter)func_set_defaults},
- {"func_dict", (getter)func_get_dict, (setter)func_set_dict},
- {"__dict__", (getter)func_get_dict, (setter)func_set_dict},
- {"func_name", (getter)func_get_name, (setter)func_set_name},
- {"__name__", (getter)func_get_name, (setter)func_set_name},
- {NULL} /* Sentinel */
+ {"func_code", (getter)func_get_code, (setter)func_set_code},
+ {"__code__", (getter)func_get_code, (setter)func_set_code},
+ {"func_defaults", (getter)func_get_defaults,
+ (setter)func_set_defaults},
+ {"__defaults__", (getter)func_get_defaults,
+ (setter)func_set_defaults},
+ {"func_dict", (getter)func_get_dict, (setter)func_set_dict},
+ {"__dict__", (getter)func_get_dict, (setter)func_set_dict},
+ {"func_name", (getter)func_get_name, (setter)func_set_name},
+ {"__name__", (getter)func_get_name, (setter)func_set_name},
+ {NULL} /* Sentinel */
};
PyDoc_STRVAR(func_doc,
@@ -353,236 +353,236 @@ The optional closure tuple supplies the bindings for free variables.");
/* func_new() maintains the following invariants for closures. The
closure must correspond to the free variables of the code object.
-
- if len(code.co_freevars) == 0:
- closure = NULL
+
+ if len(code.co_freevars) == 0:
+ closure = NULL
else:
- len(closure) == len(code.co_freevars)
+ len(closure) == len(code.co_freevars)
for every elt in closure, type(elt) == cell
*/
static PyObject *
func_new(PyTypeObject* type, PyObject* args, PyObject* kw)
{
- PyCodeObject *code;
- PyObject *globals;
- PyObject *name = Py_None;
- PyObject *defaults = Py_None;
- PyObject *closure = Py_None;
- PyFunctionObject *newfunc;
- Py_ssize_t nfree, nclosure;
- static char *kwlist[] = {"code", "globals", "name",
- "argdefs", "closure", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
- kwlist,
- &PyCode_Type, &code,
- &PyDict_Type, &globals,
- &name, &defaults, &closure))
- return NULL;
- if (name != Py_None && !PyString_Check(name)) {
- PyErr_SetString(PyExc_TypeError,
- "arg 3 (name) must be None or string");
- return NULL;
- }
- if (defaults != Py_None && !PyTuple_Check(defaults)) {
- PyErr_SetString(PyExc_TypeError,
- "arg 4 (defaults) must be None or tuple");
- return NULL;
- }
- nfree = PyTuple_GET_SIZE(code->co_freevars);
- if (!PyTuple_Check(closure)) {
- if (nfree && closure == Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "arg 5 (closure) must be tuple");
- return NULL;
- }
- else if (closure != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "arg 5 (closure) must be None or tuple");
- return NULL;
- }
- }
-
- /* check that the closure is well-formed */
- nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
- if (nfree != nclosure)
- return PyErr_Format(PyExc_ValueError,
- "%s requires closure of length %zd, not %zd",
- PyString_AS_STRING(code->co_name),
- nfree, nclosure);
- if (nclosure) {
- Py_ssize_t i;
- for (i = 0; i < nclosure; i++) {
- PyObject *o = PyTuple_GET_ITEM(closure, i);
- if (!PyCell_Check(o)) {
- return PyErr_Format(PyExc_TypeError,
- "arg 5 (closure) expected cell, found %s",
- o->ob_type->tp_name);
- }
- }
- }
-
- newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
- globals);
- if (newfunc == NULL)
- return NULL;
-
- if (name != Py_None) {
- Py_INCREF(name);
- Py_DECREF(newfunc->func_name);
- newfunc->func_name = name;
- }
- if (defaults != Py_None) {
- Py_INCREF(defaults);
- newfunc->func_defaults = defaults;
- }
- if (closure != Py_None) {
- Py_INCREF(closure);
- newfunc->func_closure = closure;
- }
-
- return (PyObject *)newfunc;
+ PyCodeObject *code;
+ PyObject *globals;
+ PyObject *name = Py_None;
+ PyObject *defaults = Py_None;
+ PyObject *closure = Py_None;
+ PyFunctionObject *newfunc;
+ Py_ssize_t nfree, nclosure;
+ static char *kwlist[] = {"code", "globals", "name",
+ "argdefs", "closure", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "O!O!|OOO:function",
+ kwlist,
+ &PyCode_Type, &code,
+ &PyDict_Type, &globals,
+ &name, &defaults, &closure))
+ return NULL;
+ if (name != Py_None && !PyString_Check(name)) {
+ PyErr_SetString(PyExc_TypeError,
+ "arg 3 (name) must be None or string");
+ return NULL;
+ }
+ if (defaults != Py_None && !PyTuple_Check(defaults)) {
+ PyErr_SetString(PyExc_TypeError,
+ "arg 4 (defaults) must be None or tuple");
+ return NULL;
+ }
+ nfree = PyTuple_GET_SIZE(code->co_freevars);
+ if (!PyTuple_Check(closure)) {
+ if (nfree && closure == Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "arg 5 (closure) must be tuple");
+ return NULL;
+ }
+ else if (closure != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "arg 5 (closure) must be None or tuple");
+ return NULL;
+ }
+ }
+
+ /* check that the closure is well-formed */
+ nclosure = closure == Py_None ? 0 : PyTuple_GET_SIZE(closure);
+ if (nfree != nclosure)
+ return PyErr_Format(PyExc_ValueError,
+ "%s requires closure of length %zd, not %zd",
+ PyString_AS_STRING(code->co_name),
+ nfree, nclosure);
+ if (nclosure) {
+ Py_ssize_t i;
+ for (i = 0; i < nclosure; i++) {
+ PyObject *o = PyTuple_GET_ITEM(closure, i);
+ if (!PyCell_Check(o)) {
+ return PyErr_Format(PyExc_TypeError,
+ "arg 5 (closure) expected cell, found %s",
+ o->ob_type->tp_name);
+ }
+ }
+ }
+
+ newfunc = (PyFunctionObject *)PyFunction_New((PyObject *)code,
+ globals);
+ if (newfunc == NULL)
+ return NULL;
+
+ if (name != Py_None) {
+ Py_INCREF(name);
+ Py_DECREF(newfunc->func_name);
+ newfunc->func_name = name;
+ }
+ if (defaults != Py_None) {
+ Py_INCREF(defaults);
+ newfunc->func_defaults = defaults;
+ }
+ if (closure != Py_None) {
+ Py_INCREF(closure);
+ newfunc->func_closure = closure;
+ }
+
+ return (PyObject *)newfunc;
}
static void
func_dealloc(PyFunctionObject *op)
{
- _PyObject_GC_UNTRACK(op);
- if (op->func_weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) op);
- Py_DECREF(op->func_code);
- Py_DECREF(op->func_globals);
- Py_XDECREF(op->func_module);
- Py_DECREF(op->func_name);
- Py_XDECREF(op->func_defaults);
- Py_XDECREF(op->func_doc);
- Py_XDECREF(op->func_dict);
- Py_XDECREF(op->func_closure);
- PyObject_GC_Del(op);
+ _PyObject_GC_UNTRACK(op);
+ if (op->func_weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) op);
+ Py_DECREF(op->func_code);
+ Py_DECREF(op->func_globals);
+ Py_XDECREF(op->func_module);
+ Py_DECREF(op->func_name);
+ Py_XDECREF(op->func_defaults);
+ Py_XDECREF(op->func_doc);
+ Py_XDECREF(op->func_dict);
+ Py_XDECREF(op->func_closure);
+ PyObject_GC_Del(op);
}
static PyObject*
func_repr(PyFunctionObject *op)
{
- return PyString_FromFormat("<function %s at %p>",
- PyString_AsString(op->func_name),
- op);
+ return PyString_FromFormat("<function %s at %p>",
+ PyString_AsString(op->func_name),
+ op);
}
static int
func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
{
- Py_VISIT(f->func_code);
- Py_VISIT(f->func_globals);
- Py_VISIT(f->func_module);
- Py_VISIT(f->func_defaults);
- Py_VISIT(f->func_doc);
- Py_VISIT(f->func_name);
- Py_VISIT(f->func_dict);
- Py_VISIT(f->func_closure);
- return 0;
+ Py_VISIT(f->func_code);
+ Py_VISIT(f->func_globals);
+ Py_VISIT(f->func_module);
+ Py_VISIT(f->func_defaults);
+ Py_VISIT(f->func_doc);
+ Py_VISIT(f->func_name);
+ Py_VISIT(f->func_dict);
+ Py_VISIT(f->func_closure);
+ return 0;
}
static PyObject *
function_call(PyObject *func, PyObject *arg, PyObject *kw)
{
- PyObject *result;
- PyObject *argdefs;
- PyObject *kwtuple = NULL;
- PyObject **d, **k;
- Py_ssize_t nk, nd;
-
- argdefs = PyFunction_GET_DEFAULTS(func);
- if (argdefs != NULL && PyTuple_Check(argdefs)) {
- d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
- nd = PyTuple_GET_SIZE(argdefs);
- }
- else {
- d = NULL;
- nd = 0;
- }
-
- if (kw != NULL && PyDict_Check(kw)) {
- Py_ssize_t pos, i;
- nk = PyDict_Size(kw);
- kwtuple = PyTuple_New(2*nk);
- if (kwtuple == NULL)
- return NULL;
- k = &PyTuple_GET_ITEM(kwtuple, 0);
- pos = i = 0;
- while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) {
- Py_INCREF(k[i]);
- Py_INCREF(k[i+1]);
- i += 2;
- }
- nk = i/2;
- }
- else {
- k = NULL;
- nk = 0;
- }
-
- result = PyEval_EvalCodeEx(
- (PyCodeObject *)PyFunction_GET_CODE(func),
- PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
- &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg),
- k, nk, d, nd,
- PyFunction_GET_CLOSURE(func));
-
- Py_XDECREF(kwtuple);
-
- return result;
+ PyObject *result;
+ PyObject *argdefs;
+ PyObject *kwtuple = NULL;
+ PyObject **d, **k;
+ Py_ssize_t nk, nd;
+
+ argdefs = PyFunction_GET_DEFAULTS(func);
+ if (argdefs != NULL && PyTuple_Check(argdefs)) {
+ d = &PyTuple_GET_ITEM((PyTupleObject *)argdefs, 0);
+ nd = PyTuple_GET_SIZE(argdefs);
+ }
+ else {
+ d = NULL;
+ nd = 0;
+ }
+
+ if (kw != NULL && PyDict_Check(kw)) {
+ Py_ssize_t pos, i;
+ nk = PyDict_Size(kw);
+ kwtuple = PyTuple_New(2*nk);
+ if (kwtuple == NULL)
+ return NULL;
+ k = &PyTuple_GET_ITEM(kwtuple, 0);
+ pos = i = 0;
+ while (PyDict_Next(kw, &pos, &k[i], &k[i+1])) {
+ Py_INCREF(k[i]);
+ Py_INCREF(k[i+1]);
+ i += 2;
+ }
+ nk = i/2;
+ }
+ else {
+ k = NULL;
+ nk = 0;
+ }
+
+ result = PyEval_EvalCodeEx(
+ (PyCodeObject *)PyFunction_GET_CODE(func),
+ PyFunction_GET_GLOBALS(func), (PyObject *)NULL,
+ &PyTuple_GET_ITEM(arg, 0), PyTuple_GET_SIZE(arg),
+ k, nk, d, nd,
+ PyFunction_GET_CLOSURE(func));
+
+ Py_XDECREF(kwtuple);
+
+ return result;
}
/* Bind a function to an object */
static PyObject *
func_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{
- if (obj == Py_None)
- obj = NULL;
- return PyMethod_New(func, obj, type);
+ if (obj == Py_None)
+ obj = NULL;
+ return PyMethod_New(func, obj, type);
}
PyTypeObject PyFunction_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "function",
- sizeof(PyFunctionObject),
- 0,
- (destructor)func_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)func_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- function_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,/* tp_flags */
- func_doc, /* tp_doc */
- (traverseproc)func_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- func_memberlist, /* tp_members */
- func_getsetlist, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- func_descr_get, /* tp_descr_get */
- 0, /* tp_descr_set */
- offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- func_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "function",
+ sizeof(PyFunctionObject),
+ 0,
+ (destructor)func_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)func_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ function_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,/* tp_flags */
+ func_doc, /* tp_doc */
+ (traverseproc)func_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyFunctionObject, func_weakreflist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ func_memberlist, /* tp_members */
+ func_getsetlist, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ func_descr_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ offsetof(PyFunctionObject, func_dict), /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ func_new, /* tp_new */
};
@@ -593,9 +593,9 @@ PyTypeObject PyFunction_Type = {
To declare a class method, use this idiom:
class C:
- def f(cls, arg1, arg2, ...): ...
- f = classmethod(f)
-
+ def f(cls, arg1, arg2, ...): ...
+ f = classmethod(f)
+
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()); the instance is ignored except for its class.
If a class method is called for a derived class, the derived class
@@ -606,67 +606,67 @@ PyTypeObject PyFunction_Type = {
*/
typedef struct {
- PyObject_HEAD
- PyObject *cm_callable;
+ PyObject_HEAD
+ PyObject *cm_callable;
} classmethod;
static void
cm_dealloc(classmethod *cm)
{
- _PyObject_GC_UNTRACK((PyObject *)cm);
- Py_XDECREF(cm->cm_callable);
- Py_TYPE(cm)->tp_free((PyObject *)cm);
+ _PyObject_GC_UNTRACK((PyObject *)cm);
+ Py_XDECREF(cm->cm_callable);
+ Py_TYPE(cm)->tp_free((PyObject *)cm);
}
static int
cm_traverse(classmethod *cm, visitproc visit, void *arg)
{
- Py_VISIT(cm->cm_callable);
- return 0;
+ Py_VISIT(cm->cm_callable);
+ return 0;
}
static int
cm_clear(classmethod *cm)
{
- Py_CLEAR(cm->cm_callable);
- return 0;
+ Py_CLEAR(cm->cm_callable);
+ return 0;
}
static PyObject *
cm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
- classmethod *cm = (classmethod *)self;
+ classmethod *cm = (classmethod *)self;
- if (cm->cm_callable == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "uninitialized classmethod object");
- return NULL;
- }
- if (type == NULL)
- type = (PyObject *)(Py_TYPE(obj));
- return PyMethod_New(cm->cm_callable,
- type, (PyObject *)(Py_TYPE(type)));
+ if (cm->cm_callable == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "uninitialized classmethod object");
+ return NULL;
+ }
+ if (type == NULL)
+ type = (PyObject *)(Py_TYPE(obj));
+ return PyMethod_New(cm->cm_callable,
+ type, (PyObject *)(Py_TYPE(type)));
}
static int
cm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- classmethod *cm = (classmethod *)self;
- PyObject *callable;
+ classmethod *cm = (classmethod *)self;
+ PyObject *callable;
- if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
- return -1;
- if (!_PyArg_NoKeywords("classmethod", kwds))
- return -1;
- Py_INCREF(callable);
- cm->cm_callable = callable;
- return 0;
+ if (!PyArg_UnpackTuple(args, "classmethod", 1, 1, &callable))
+ return -1;
+ if (!_PyArg_NoKeywords("classmethod", kwds))
+ return -1;
+ Py_INCREF(callable);
+ cm->cm_callable = callable;
+ return 0;
}
static PyMemberDef cm_memberlist[] = {
- {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
- {NULL} /* Sentinel */
+ {"__func__", T_OBJECT, offsetof(classmethod, cm_callable), READONLY},
+ {NULL} /* Sentinel */
};
PyDoc_STRVAR(classmethod_doc,
@@ -691,57 +691,57 @@ Class methods are different than C++ or Java static methods.\n\
If you want those, see the staticmethod builtin.");
PyTypeObject PyClassMethod_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "classmethod",
- sizeof(classmethod),
- 0,
- (destructor)cm_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 | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- classmethod_doc, /* tp_doc */
- (traverseproc)cm_traverse, /* tp_traverse */
- (inquiry)cm_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- cm_memberlist, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- cm_descr_get, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- cm_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "classmethod",
+ sizeof(classmethod),
+ 0,
+ (destructor)cm_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 | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ classmethod_doc, /* tp_doc */
+ (traverseproc)cm_traverse, /* tp_traverse */
+ (inquiry)cm_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ cm_memberlist, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ cm_descr_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ cm_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
PyObject *
PyClassMethod_New(PyObject *callable)
{
- classmethod *cm = (classmethod *)
- PyType_GenericAlloc(&PyClassMethod_Type, 0);
- if (cm != NULL) {
- Py_INCREF(callable);
- cm->cm_callable = callable;
- }
- return (PyObject *)cm;
+ classmethod *cm = (classmethod *)
+ PyType_GenericAlloc(&PyClassMethod_Type, 0);
+ if (cm != NULL) {
+ Py_INCREF(callable);
+ cm->cm_callable = callable;
+ }
+ return (PyObject *)cm;
}
@@ -751,8 +751,8 @@ PyClassMethod_New(PyObject *callable)
To declare a static method, use this idiom:
class C:
- def f(arg1, arg2, ...): ...
- f = staticmethod(f)
+ def f(arg1, arg2, ...): ...
+ f = staticmethod(f)
It can be called either on the class (e.g. C.f()) or on an instance
(e.g. C().f()); the instance is ignored except for its class.
@@ -762,66 +762,66 @@ PyClassMethod_New(PyObject *callable)
*/
typedef struct {
- PyObject_HEAD
- PyObject *sm_callable;
+ PyObject_HEAD
+ PyObject *sm_callable;
} staticmethod;
static void
sm_dealloc(staticmethod *sm)
{
- _PyObject_GC_UNTRACK((PyObject *)sm);
- Py_XDECREF(sm->sm_callable);
- Py_TYPE(sm)->tp_free((PyObject *)sm);
+ _PyObject_GC_UNTRACK((PyObject *)sm);
+ Py_XDECREF(sm->sm_callable);
+ Py_TYPE(sm)->tp_free((PyObject *)sm);
}
static int
sm_traverse(staticmethod *sm, visitproc visit, void *arg)
{
- Py_VISIT(sm->sm_callable);
- return 0;
+ Py_VISIT(sm->sm_callable);
+ return 0;
}
static int
sm_clear(staticmethod *sm)
{
- Py_XDECREF(sm->sm_callable);
- sm->sm_callable = NULL;
+ Py_XDECREF(sm->sm_callable);
+ sm->sm_callable = NULL;
- return 0;
+ return 0;
}
static PyObject *
sm_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
- staticmethod *sm = (staticmethod *)self;
+ staticmethod *sm = (staticmethod *)self;
- if (sm->sm_callable == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "uninitialized staticmethod object");
- return NULL;
- }
- Py_INCREF(sm->sm_callable);
- return sm->sm_callable;
+ if (sm->sm_callable == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "uninitialized staticmethod object");
+ return NULL;
+ }
+ Py_INCREF(sm->sm_callable);
+ return sm->sm_callable;
}
static int
sm_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- staticmethod *sm = (staticmethod *)self;
- PyObject *callable;
+ staticmethod *sm = (staticmethod *)self;
+ PyObject *callable;
- if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
- return -1;
- if (!_PyArg_NoKeywords("staticmethod", kwds))
- return -1;
- Py_INCREF(callable);
- sm->sm_callable = callable;
- return 0;
+ if (!PyArg_UnpackTuple(args, "staticmethod", 1, 1, &callable))
+ return -1;
+ if (!_PyArg_NoKeywords("staticmethod", kwds))
+ return -1;
+ Py_INCREF(callable);
+ sm->sm_callable = callable;
+ return 0;
}
static PyMemberDef sm_memberlist[] = {
- {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
- {NULL} /* Sentinel */
+ {"__func__", T_OBJECT, offsetof(staticmethod, sm_callable), READONLY},
+ {NULL} /* Sentinel */
};
PyDoc_STRVAR(staticmethod_doc,
@@ -833,8 +833,8 @@ A static method does not receive an implicit first argument.\n\
To declare a static method, use this idiom:\n\
\n\
class C:\n\
- def f(arg1, arg2, ...): ...\n\
- f = staticmethod(f)\n\
+ def f(arg1, arg2, ...): ...\n\
+ f = staticmethod(f)\n\
\n\
It can be called either on the class (e.g. C.f()) or on an instance\n\
(e.g. C().f()). The instance is ignored except for its class.\n\
@@ -843,55 +843,55 @@ Static methods in Python are similar to those found in Java or C++.\n\
For a more advanced concept, see the classmethod builtin.");
PyTypeObject PyStaticMethod_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "staticmethod",
- sizeof(staticmethod),
- 0,
- (destructor)sm_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 | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
- staticmethod_doc, /* tp_doc */
- (traverseproc)sm_traverse, /* tp_traverse */
- (inquiry)sm_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- sm_memberlist, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- sm_descr_get, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- sm_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "staticmethod",
+ sizeof(staticmethod),
+ 0,
+ (destructor)sm_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 | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
+ staticmethod_doc, /* tp_doc */
+ (traverseproc)sm_traverse, /* tp_traverse */
+ (inquiry)sm_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ sm_memberlist, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ sm_descr_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ sm_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
PyObject *
PyStaticMethod_New(PyObject *callable)
{
- staticmethod *sm = (staticmethod *)
- PyType_GenericAlloc(&PyStaticMethod_Type, 0);
- if (sm != NULL) {
- Py_INCREF(callable);
- sm->sm_callable = callable;
- }
- return (PyObject *)sm;
+ staticmethod *sm = (staticmethod *)
+ PyType_GenericAlloc(&PyStaticMethod_Type, 0);
+ if (sm != NULL) {
+ Py_INCREF(callable);
+ sm->sm_callable = callable;
+ }
+ return (PyObject *)sm;
}
diff --git a/Objects/genobject.c b/Objects/genobject.c
index c3fa64b..af812c0 100644
--- a/Objects/genobject.c
+++ b/Objects/genobject.c
@@ -10,103 +10,103 @@
static int
gen_traverse(PyGenObject *gen, visitproc visit, void *arg)
{
- Py_VISIT((PyObject *)gen->gi_frame);
- Py_VISIT(gen->gi_code);
- return 0;
+ Py_VISIT((PyObject *)gen->gi_frame);
+ Py_VISIT(gen->gi_code);
+ return 0;
}
static void
gen_dealloc(PyGenObject *gen)
{
- PyObject *self = (PyObject *) gen;
+ PyObject *self = (PyObject *) gen;
- _PyObject_GC_UNTRACK(gen);
+ _PyObject_GC_UNTRACK(gen);
- if (gen->gi_weakreflist != NULL)
- PyObject_ClearWeakRefs(self);
+ if (gen->gi_weakreflist != NULL)
+ PyObject_ClearWeakRefs(self);
- _PyObject_GC_TRACK(self);
+ _PyObject_GC_TRACK(self);
- if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
- /* Generator is paused, so we need to close */
- Py_TYPE(gen)->tp_del(self);
- if (self->ob_refcnt > 0)
- return; /* resurrected. :( */
- }
+ if (gen->gi_frame != NULL && gen->gi_frame->f_stacktop != NULL) {
+ /* Generator is paused, so we need to close */
+ Py_TYPE(gen)->tp_del(self);
+ if (self->ob_refcnt > 0)
+ return; /* resurrected. :( */
+ }
- _PyObject_GC_UNTRACK(self);
- Py_CLEAR(gen->gi_frame);
- Py_CLEAR(gen->gi_code);
- PyObject_GC_Del(gen);
+ _PyObject_GC_UNTRACK(self);
+ Py_CLEAR(gen->gi_frame);
+ Py_CLEAR(gen->gi_code);
+ PyObject_GC_Del(gen);
}
static PyObject *
gen_send_ex(PyGenObject *gen, PyObject *arg, int exc)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyFrameObject *f = gen->gi_frame;
- PyObject *result;
-
- if (gen->gi_running) {
- PyErr_SetString(PyExc_ValueError,
- "generator already executing");
- return NULL;
- }
- if (f==NULL || f->f_stacktop == NULL) {
- /* Only set exception if called from send() */
- if (arg && !exc)
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
-
- if (f->f_lasti == -1) {
- if (arg && arg != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "can't send non-None value to a "
- "just-started generator");
- return NULL;
- }
- } else {
- /* Push arg onto the frame's value stack */
- result = arg ? arg : Py_None;
- Py_INCREF(result);
- *(f->f_stacktop++) = result;
- }
-
- /* Generators always return to their most recent caller, not
- * necessarily their creator. */
- Py_XINCREF(tstate->frame);
- assert(f->f_back == NULL);
- f->f_back = tstate->frame;
-
- gen->gi_running = 1;
- result = PyEval_EvalFrameEx(f, exc);
- gen->gi_running = 0;
-
- /* Don't keep the reference to f_back any longer than necessary. It
- * may keep a chain of frames alive or it could create a reference
- * cycle. */
- assert(f->f_back == tstate->frame);
- Py_CLEAR(f->f_back);
-
- /* If the generator just returned (as opposed to yielding), signal
- * that the generator is exhausted. */
- if (result == Py_None && f->f_stacktop == NULL) {
- Py_DECREF(result);
- result = NULL;
- /* Set exception if not called by gen_iternext() */
- if (arg)
- PyErr_SetNone(PyExc_StopIteration);
- }
-
- if (!result || f->f_stacktop == NULL) {
- /* generator can't be rerun, so release the frame */
- Py_DECREF(f);
- gen->gi_frame = NULL;
- }
-
- return result;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyFrameObject *f = gen->gi_frame;
+ PyObject *result;
+
+ if (gen->gi_running) {
+ PyErr_SetString(PyExc_ValueError,
+ "generator already executing");
+ return NULL;
+ }
+ if (f==NULL || f->f_stacktop == NULL) {
+ /* Only set exception if called from send() */
+ if (arg && !exc)
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
+
+ if (f->f_lasti == -1) {
+ if (arg && arg != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't send non-None value to a "
+ "just-started generator");
+ return NULL;
+ }
+ } else {
+ /* Push arg onto the frame's value stack */
+ result = arg ? arg : Py_None;
+ Py_INCREF(result);
+ *(f->f_stacktop++) = result;
+ }
+
+ /* Generators always return to their most recent caller, not
+ * necessarily their creator. */
+ Py_XINCREF(tstate->frame);
+ assert(f->f_back == NULL);
+ f->f_back = tstate->frame;
+
+ gen->gi_running = 1;
+ result = PyEval_EvalFrameEx(f, exc);
+ gen->gi_running = 0;
+
+ /* Don't keep the reference to f_back any longer than necessary. It
+ * may keep a chain of frames alive or it could create a reference
+ * cycle. */
+ assert(f->f_back == tstate->frame);
+ Py_CLEAR(f->f_back);
+
+ /* If the generator just returned (as opposed to yielding), signal
+ * that the generator is exhausted. */
+ if (result == Py_None && f->f_stacktop == NULL) {
+ Py_DECREF(result);
+ result = NULL;
+ /* Set exception if not called by gen_iternext() */
+ if (arg)
+ PyErr_SetNone(PyExc_StopIteration);
+ }
+
+ if (!result || f->f_stacktop == NULL) {
+ /* generator can't be rerun, so release the frame */
+ Py_DECREF(f);
+ gen->gi_frame = NULL;
+ }
+
+ return result;
}
PyDoc_STRVAR(send_doc,
@@ -116,7 +116,7 @@ return next yielded value or raise StopIteration.");
static PyObject *
gen_send(PyGenObject *gen, PyObject *arg)
{
- return gen_send_ex(gen, arg, 0);
+ return gen_send_ex(gen, arg, 0);
}
PyDoc_STRVAR(close_doc,
@@ -125,83 +125,83 @@ PyDoc_STRVAR(close_doc,
static PyObject *
gen_close(PyGenObject *gen, PyObject *args)
{
- PyObject *retval;
- PyErr_SetNone(PyExc_GeneratorExit);
- retval = gen_send_ex(gen, Py_None, 1);
- if (retval) {
- Py_DECREF(retval);
- PyErr_SetString(PyExc_RuntimeError,
- "generator ignored GeneratorExit");
- return NULL;
- }
- if (PyErr_ExceptionMatches(PyExc_StopIteration)
- || PyErr_ExceptionMatches(PyExc_GeneratorExit))
- {
- PyErr_Clear(); /* ignore these errors */
- Py_INCREF(Py_None);
- return Py_None;
- }
- return NULL;
+ PyObject *retval;
+ PyErr_SetNone(PyExc_GeneratorExit);
+ retval = gen_send_ex(gen, Py_None, 1);
+ if (retval) {
+ Py_DECREF(retval);
+ PyErr_SetString(PyExc_RuntimeError,
+ "generator ignored GeneratorExit");
+ return NULL;
+ }
+ if (PyErr_ExceptionMatches(PyExc_StopIteration)
+ || PyErr_ExceptionMatches(PyExc_GeneratorExit))
+ {
+ PyErr_Clear(); /* ignore these errors */
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return NULL;
}
static void
gen_del(PyObject *self)
{
- PyObject *res;
- PyObject *error_type, *error_value, *error_traceback;
- PyGenObject *gen = (PyGenObject *)self;
-
- if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
- /* Generator isn't paused, so no need to close */
- return;
-
- /* Temporarily resurrect the object. */
- assert(self->ob_refcnt == 0);
- self->ob_refcnt = 1;
-
- /* Save the current exception, if any. */
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
-
- res = gen_close(gen, NULL);
-
- if (res == NULL)
- PyErr_WriteUnraisable(self);
- else
- Py_DECREF(res);
-
- /* Restore the saved exception. */
- PyErr_Restore(error_type, error_value, error_traceback);
-
- /* Undo the temporary resurrection; can't use DECREF here, it would
- * cause a recursive call.
- */
- assert(self->ob_refcnt > 0);
- if (--self->ob_refcnt == 0)
- return; /* this is the normal path out */
-
- /* close() resurrected it! Make it look like the original Py_DECREF
- * never happened.
- */
- {
- Py_ssize_t refcnt = self->ob_refcnt;
- _Py_NewReference(self);
- self->ob_refcnt = refcnt;
- }
- assert(PyType_IS_GC(self->ob_type) &&
- _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
-
- /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
- * we need to undo that. */
- _Py_DEC_REFTOTAL;
- /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
- * chain, so no more to do there.
- * If COUNT_ALLOCS, the original decref bumped tp_frees, and
- * _Py_NewReference bumped tp_allocs: both of those need to be
- * undone.
- */
+ PyObject *res;
+ PyObject *error_type, *error_value, *error_traceback;
+ PyGenObject *gen = (PyGenObject *)self;
+
+ if (gen->gi_frame == NULL || gen->gi_frame->f_stacktop == NULL)
+ /* Generator isn't paused, so no need to close */
+ return;
+
+ /* Temporarily resurrect the object. */
+ assert(self->ob_refcnt == 0);
+ self->ob_refcnt = 1;
+
+ /* Save the current exception, if any. */
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+
+ res = gen_close(gen, NULL);
+
+ if (res == NULL)
+ PyErr_WriteUnraisable(self);
+ else
+ Py_DECREF(res);
+
+ /* Restore the saved exception. */
+ PyErr_Restore(error_type, error_value, error_traceback);
+
+ /* Undo the temporary resurrection; can't use DECREF here, it would
+ * cause a recursive call.
+ */
+ assert(self->ob_refcnt > 0);
+ if (--self->ob_refcnt == 0)
+ return; /* this is the normal path out */
+
+ /* close() resurrected it! Make it look like the original Py_DECREF
+ * never happened.
+ */
+ {
+ Py_ssize_t refcnt = self->ob_refcnt;
+ _Py_NewReference(self);
+ self->ob_refcnt = refcnt;
+ }
+ assert(PyType_IS_GC(self->ob_type) &&
+ _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
+
+ /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
+ * we need to undo that. */
+ _Py_DEC_REFTOTAL;
+ /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
+ * chain, so no more to do there.
+ * If COUNT_ALLOCS, the original decref bumped tp_frees, and
+ * _Py_NewReference bumped tp_allocs: both of those need to be
+ * undone.
+ */
#ifdef COUNT_ALLOCS
- --self->ob_type->tp_frees;
- --self->ob_type->tp_allocs;
+ --self->ob_type->tp_frees;
+ --self->ob_type->tp_allocs;
#endif
}
@@ -214,91 +214,91 @@ return next yielded value or raise StopIteration.");
static PyObject *
gen_throw(PyGenObject *gen, PyObject *args)
{
- PyObject *typ;
- PyObject *tb = NULL;
- PyObject *val = NULL;
-
- if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
- return NULL;
-
- /* First, check the traceback argument, replacing None with
- NULL. */
- if (tb == Py_None)
- tb = NULL;
- else if (tb != NULL && !PyTraceBack_Check(tb)) {
- PyErr_SetString(PyExc_TypeError,
- "throw() third argument must be a traceback object");
- return NULL;
- }
-
- Py_INCREF(typ);
- Py_XINCREF(val);
- Py_XINCREF(tb);
-
- if (PyExceptionClass_Check(typ)) {
- PyErr_NormalizeException(&typ, &val, &tb);
- }
-
- else if (PyExceptionInstance_Check(typ)) {
- /* Raising an instance. The value should be a dummy. */
- if (val && val != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "instance exception may not have a separate value");
- goto failed_throw;
- }
- else {
- /* Normalize to raise <class>, <instance> */
- Py_XDECREF(val);
- val = typ;
- typ = PyExceptionInstance_Class(typ);
- Py_INCREF(typ);
- }
- }
- else {
- /* Not something you can raise. throw() fails. */
- PyErr_Format(PyExc_TypeError,
- "exceptions must be classes, or instances, not %s",
- typ->ob_type->tp_name);
- goto failed_throw;
- }
-
- PyErr_Restore(typ, val, tb);
- return gen_send_ex(gen, Py_None, 1);
+ PyObject *typ;
+ PyObject *tb = NULL;
+ PyObject *val = NULL;
+
+ if (!PyArg_UnpackTuple(args, "throw", 1, 3, &typ, &val, &tb))
+ return NULL;
+
+ /* First, check the traceback argument, replacing None with
+ NULL. */
+ if (tb == Py_None)
+ tb = NULL;
+ else if (tb != NULL && !PyTraceBack_Check(tb)) {
+ PyErr_SetString(PyExc_TypeError,
+ "throw() third argument must be a traceback object");
+ return NULL;
+ }
+
+ Py_INCREF(typ);
+ Py_XINCREF(val);
+ Py_XINCREF(tb);
+
+ if (PyExceptionClass_Check(typ)) {
+ PyErr_NormalizeException(&typ, &val, &tb);
+ }
+
+ else if (PyExceptionInstance_Check(typ)) {
+ /* Raising an instance. The value should be a dummy. */
+ if (val && val != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "instance exception may not have a separate value");
+ goto failed_throw;
+ }
+ else {
+ /* Normalize to raise <class>, <instance> */
+ Py_XDECREF(val);
+ val = typ;
+ typ = PyExceptionInstance_Class(typ);
+ Py_INCREF(typ);
+ }
+ }
+ else {
+ /* Not something you can raise. throw() fails. */
+ PyErr_Format(PyExc_TypeError,
+ "exceptions must be classes, or instances, not %s",
+ typ->ob_type->tp_name);
+ goto failed_throw;
+ }
+
+ PyErr_Restore(typ, val, tb);
+ return gen_send_ex(gen, Py_None, 1);
failed_throw:
- /* Didn't use our arguments, so restore their original refcounts */
- Py_DECREF(typ);
- Py_XDECREF(val);
- Py_XDECREF(tb);
- return NULL;
+ /* Didn't use our arguments, so restore their original refcounts */
+ Py_DECREF(typ);
+ Py_XDECREF(val);
+ Py_XDECREF(tb);
+ return NULL;
}
static PyObject *
gen_iternext(PyGenObject *gen)
{
- return gen_send_ex(gen, NULL, 0);
+ return gen_send_ex(gen, NULL, 0);
}
static PyObject *
gen_repr(PyGenObject *gen)
{
- char *code_name;
- code_name = PyString_AsString(((PyCodeObject *)gen->gi_code)->co_name);
- if (code_name == NULL)
- return NULL;
- return PyString_FromFormat("<generator object %.200s at %p>",
- code_name, gen);
+ char *code_name;
+ code_name = PyString_AsString(((PyCodeObject *)gen->gi_code)->co_name);
+ if (code_name == NULL)
+ return NULL;
+ return PyString_FromFormat("<generator object %.200s at %p>",
+ code_name, gen);
}
static PyObject *
gen_get_name(PyGenObject *gen)
{
- PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
- Py_INCREF(name);
- return name;
+ PyObject *name = ((PyCodeObject *)gen->gi_code)->co_name;
+ Py_INCREF(name);
+ return name;
}
@@ -306,109 +306,109 @@ PyDoc_STRVAR(gen__name__doc__,
"Return the name of the generator's associated code object.");
static PyGetSetDef gen_getsetlist[] = {
- {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
- {NULL}
+ {"__name__", (getter)gen_get_name, NULL, gen__name__doc__},
+ {NULL}
};
static PyMemberDef gen_memberlist[] = {
- {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), RO},
- {"gi_running", T_INT, offsetof(PyGenObject, gi_running), RO},
- {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), RO},
- {NULL} /* Sentinel */
+ {"gi_frame", T_OBJECT, offsetof(PyGenObject, gi_frame), RO},
+ {"gi_running", T_INT, offsetof(PyGenObject, gi_running), RO},
+ {"gi_code", T_OBJECT, offsetof(PyGenObject, gi_code), RO},
+ {NULL} /* Sentinel */
};
static PyMethodDef gen_methods[] = {
- {"send",(PyCFunction)gen_send, METH_O, send_doc},
- {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
- {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
- {NULL, NULL} /* Sentinel */
+ {"send",(PyCFunction)gen_send, METH_O, send_doc},
+ {"throw",(PyCFunction)gen_throw, METH_VARARGS, throw_doc},
+ {"close",(PyCFunction)gen_close, METH_NOARGS, close_doc},
+ {NULL, NULL} /* Sentinel */
};
PyTypeObject PyGen_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "generator", /* tp_name */
- sizeof(PyGenObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)gen_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)gen_repr, /* 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_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)gen_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)gen_iternext, /* tp_iternext */
- gen_methods, /* tp_methods */
- gen_memberlist, /* tp_members */
- gen_getsetlist, /* 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 */
- 0, /* tp_free */
- 0, /* tp_is_gc */
- 0, /* tp_bases */
- 0, /* tp_mro */
- 0, /* tp_cache */
- 0, /* tp_subclasses */
- 0, /* tp_weaklist */
- gen_del, /* tp_del */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "generator", /* tp_name */
+ sizeof(PyGenObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)gen_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)gen_repr, /* 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_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)gen_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ offsetof(PyGenObject, gi_weakreflist), /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)gen_iternext, /* tp_iternext */
+ gen_methods, /* tp_methods */
+ gen_memberlist, /* tp_members */
+ gen_getsetlist, /* 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 */
+ 0, /* tp_free */
+ 0, /* tp_is_gc */
+ 0, /* tp_bases */
+ 0, /* tp_mro */
+ 0, /* tp_cache */
+ 0, /* tp_subclasses */
+ 0, /* tp_weaklist */
+ gen_del, /* tp_del */
};
PyObject *
PyGen_New(PyFrameObject *f)
{
- PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
- if (gen == NULL) {
- Py_DECREF(f);
- return NULL;
- }
- gen->gi_frame = f;
- Py_INCREF(f->f_code);
- gen->gi_code = (PyObject *)(f->f_code);
- gen->gi_running = 0;
- gen->gi_weakreflist = NULL;
- _PyObject_GC_TRACK(gen);
- return (PyObject *)gen;
+ PyGenObject *gen = PyObject_GC_New(PyGenObject, &PyGen_Type);
+ if (gen == NULL) {
+ Py_DECREF(f);
+ return NULL;
+ }
+ gen->gi_frame = f;
+ Py_INCREF(f->f_code);
+ gen->gi_code = (PyObject *)(f->f_code);
+ gen->gi_running = 0;
+ gen->gi_weakreflist = NULL;
+ _PyObject_GC_TRACK(gen);
+ return (PyObject *)gen;
}
int
PyGen_NeedsFinalizing(PyGenObject *gen)
{
- int i;
- PyFrameObject *f = gen->gi_frame;
+ int i;
+ PyFrameObject *f = gen->gi_frame;
- if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0)
- return 0; /* no frame or empty blockstack == no finalization */
+ if (f == NULL || f->f_stacktop == NULL || f->f_iblock <= 0)
+ return 0; /* no frame or empty blockstack == no finalization */
- /* Any block type besides a loop requires cleanup. */
- i = f->f_iblock;
- while (--i >= 0) {
- if (f->f_blockstack[i].b_type != SETUP_LOOP)
- return 1;
- }
+ /* Any block type besides a loop requires cleanup. */
+ i = f->f_iblock;
+ while (--i >= 0) {
+ if (f->f_blockstack[i].b_type != SETUP_LOOP)
+ return 1;
+ }
- /* No blocks except loops, it's safe to skip finalization. */
- return 0;
+ /* No blocks except loops, it's safe to skip finalization. */
+ return 0;
}
diff --git a/Objects/intobject.c b/Objects/intobject.c
index b302d2f..7d70bfb 100644
--- a/Objects/intobject.c
+++ b/Objects/intobject.c
@@ -10,7 +10,7 @@ static PyObject *int_int(PyIntObject *v);
long
PyInt_GetMax(void)
{
- return LONG_MAX; /* To initialize sys.maxint */
+ return LONG_MAX; /* To initialize sys.maxint */
}
/* Integers are quite normal objects, to make object handling uniform.
@@ -30,13 +30,13 @@ PyInt_GetMax(void)
via abuse of their ob_type members.
*/
-#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
-#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
-#define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
+#define BLOCK_SIZE 1000 /* 1K less typical malloc overhead */
+#define BHEAD_SIZE 8 /* Enough for a 64-bit pointer */
+#define N_INTOBJECTS ((BLOCK_SIZE - BHEAD_SIZE) / sizeof(PyIntObject))
struct _intblock {
- struct _intblock *next;
- PyIntObject objects[N_INTOBJECTS];
+ struct _intblock *next;
+ PyIntObject objects[N_INTOBJECTS];
};
typedef struct _intblock PyIntBlock;
@@ -47,28 +47,28 @@ static PyIntObject *free_list = NULL;
static PyIntObject *
fill_free_list(void)
{
- PyIntObject *p, *q;
- /* Python's object allocator isn't appropriate for large blocks. */
- p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
- if (p == NULL)
- return (PyIntObject *) PyErr_NoMemory();
- ((PyIntBlock *)p)->next = block_list;
- block_list = (PyIntBlock *)p;
- /* Link the int objects together, from rear to front, then return
- the address of the last int object in the block. */
- p = &((PyIntBlock *)p)->objects[0];
- q = p + N_INTOBJECTS;
- while (--q > p)
- Py_TYPE(q) = (struct _typeobject *)(q-1);
- Py_TYPE(q) = NULL;
- return p + N_INTOBJECTS - 1;
+ PyIntObject *p, *q;
+ /* Python's object allocator isn't appropriate for large blocks. */
+ p = (PyIntObject *) PyMem_MALLOC(sizeof(PyIntBlock));
+ if (p == NULL)
+ return (PyIntObject *) PyErr_NoMemory();
+ ((PyIntBlock *)p)->next = block_list;
+ block_list = (PyIntBlock *)p;
+ /* Link the int objects together, from rear to front, then return
+ the address of the last int object in the block. */
+ p = &((PyIntBlock *)p)->objects[0];
+ q = p + N_INTOBJECTS;
+ while (--q > p)
+ Py_TYPE(q) = (struct _typeobject *)(q-1);
+ Py_TYPE(q) = NULL;
+ return p + N_INTOBJECTS - 1;
}
#ifndef NSMALLPOSINTS
-#define NSMALLPOSINTS 257
+#define NSMALLPOSINTS 257
#endif
#ifndef NSMALLNEGINTS
-#define NSMALLNEGINTS 5
+#define NSMALLNEGINTS 5
#endif
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
/* References to small integers are saved in this array so that they
@@ -86,326 +86,326 @@ Py_ssize_t quick_neg_int_allocs;
PyObject *
PyInt_FromLong(long ival)
{
- register PyIntObject *v;
+ register PyIntObject *v;
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
- if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
- v = small_ints[ival + NSMALLNEGINTS];
- Py_INCREF(v);
+ if (-NSMALLNEGINTS <= ival && ival < NSMALLPOSINTS) {
+ v = small_ints[ival + NSMALLNEGINTS];
+ Py_INCREF(v);
#ifdef COUNT_ALLOCS
- if (ival >= 0)
- quick_int_allocs++;
- else
- quick_neg_int_allocs++;
+ if (ival >= 0)
+ quick_int_allocs++;
+ else
+ quick_neg_int_allocs++;
#endif
- return (PyObject *) v;
- }
+ return (PyObject *) v;
+ }
#endif
- if (free_list == NULL) {
- if ((free_list = fill_free_list()) == NULL)
- return NULL;
- }
- /* Inline PyObject_New */
- v = free_list;
- free_list = (PyIntObject *)Py_TYPE(v);
- PyObject_INIT(v, &PyInt_Type);
- v->ob_ival = ival;
- return (PyObject *) v;
+ if (free_list == NULL) {
+ if ((free_list = fill_free_list()) == NULL)
+ return NULL;
+ }
+ /* Inline PyObject_New */
+ v = free_list;
+ free_list = (PyIntObject *)Py_TYPE(v);
+ PyObject_INIT(v, &PyInt_Type);
+ v->ob_ival = ival;
+ return (PyObject *) v;
}
PyObject *
PyInt_FromSize_t(size_t ival)
{
- if (ival <= LONG_MAX)
- return PyInt_FromLong((long)ival);
- return _PyLong_FromSize_t(ival);
+ if (ival <= LONG_MAX)
+ return PyInt_FromLong((long)ival);
+ return _PyLong_FromSize_t(ival);
}
PyObject *
PyInt_FromSsize_t(Py_ssize_t ival)
{
- if (ival >= LONG_MIN && ival <= LONG_MAX)
- return PyInt_FromLong((long)ival);
- return _PyLong_FromSsize_t(ival);
+ if (ival >= LONG_MIN && ival <= LONG_MAX)
+ return PyInt_FromLong((long)ival);
+ return _PyLong_FromSsize_t(ival);
}
static void
int_dealloc(PyIntObject *v)
{
- if (PyInt_CheckExact(v)) {
- Py_TYPE(v) = (struct _typeobject *)free_list;
- free_list = v;
- }
- else
- Py_TYPE(v)->tp_free((PyObject *)v);
+ if (PyInt_CheckExact(v)) {
+ Py_TYPE(v) = (struct _typeobject *)free_list;
+ free_list = v;
+ }
+ else
+ Py_TYPE(v)->tp_free((PyObject *)v);
}
static void
int_free(PyIntObject *v)
{
- Py_TYPE(v) = (struct _typeobject *)free_list;
- free_list = v;
+ Py_TYPE(v) = (struct _typeobject *)free_list;
+ free_list = v;
}
long
PyInt_AsLong(register PyObject *op)
{
- PyNumberMethods *nb;
- PyIntObject *io;
- long val;
-
- if (op && PyInt_Check(op))
- return PyInt_AS_LONG((PyIntObject*) op);
-
- if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
- nb->nb_int == NULL) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return -1;
- }
-
- io = (PyIntObject*) (*nb->nb_int) (op);
- if (io == NULL)
- return -1;
- if (!PyInt_Check(io)) {
- if (PyLong_Check(io)) {
- /* got a long? => retry int conversion */
- val = PyLong_AsLong((PyObject *)io);
- Py_DECREF(io);
- if ((val == -1) && PyErr_Occurred())
- return -1;
- return val;
- }
- else
- {
- Py_DECREF(io);
- PyErr_SetString(PyExc_TypeError,
- "__int__ method should return an integer");
- return -1;
- }
- }
-
- val = PyInt_AS_LONG(io);
- Py_DECREF(io);
-
- return val;
+ PyNumberMethods *nb;
+ PyIntObject *io;
+ long val;
+
+ if (op && PyInt_Check(op))
+ return PyInt_AS_LONG((PyIntObject*) op);
+
+ if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return -1;
+ }
+
+ io = (PyIntObject*) (*nb->nb_int) (op);
+ if (io == NULL)
+ return -1;
+ if (!PyInt_Check(io)) {
+ if (PyLong_Check(io)) {
+ /* got a long? => retry int conversion */
+ val = PyLong_AsLong((PyObject *)io);
+ Py_DECREF(io);
+ if ((val == -1) && PyErr_Occurred())
+ return -1;
+ return val;
+ }
+ else
+ {
+ Py_DECREF(io);
+ PyErr_SetString(PyExc_TypeError,
+ "__int__ method should return an integer");
+ return -1;
+ }
+ }
+
+ val = PyInt_AS_LONG(io);
+ Py_DECREF(io);
+
+ return val;
}
Py_ssize_t
PyInt_AsSsize_t(register PyObject *op)
{
#if SIZEOF_SIZE_T != SIZEOF_LONG
- PyNumberMethods *nb;
- PyIntObject *io;
- Py_ssize_t val;
+ PyNumberMethods *nb;
+ PyIntObject *io;
+ Py_ssize_t val;
#endif
- if (op == NULL) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return -1;
- }
+ if (op == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return -1;
+ }
- if (PyInt_Check(op))
- return PyInt_AS_LONG((PyIntObject*) op);
- if (PyLong_Check(op))
- return _PyLong_AsSsize_t(op);
+ if (PyInt_Check(op))
+ return PyInt_AS_LONG((PyIntObject*) op);
+ if (PyLong_Check(op))
+ return _PyLong_AsSsize_t(op);
#if SIZEOF_SIZE_T == SIZEOF_LONG
- return PyInt_AsLong(op);
+ return PyInt_AsLong(op);
#else
- if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
- (nb->nb_int == NULL && nb->nb_long == 0)) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return -1;
- }
-
- if (nb->nb_long != 0)
- io = (PyIntObject*) (*nb->nb_long) (op);
- else
- io = (PyIntObject*) (*nb->nb_int) (op);
- if (io == NULL)
- return -1;
- if (!PyInt_Check(io)) {
- if (PyLong_Check(io)) {
- /* got a long? => retry int conversion */
- val = _PyLong_AsSsize_t((PyObject *)io);
- Py_DECREF(io);
- if ((val == -1) && PyErr_Occurred())
- return -1;
- return val;
- }
- else
- {
- Py_DECREF(io);
- PyErr_SetString(PyExc_TypeError,
- "__int__ method should return an integer");
- return -1;
- }
- }
-
- val = PyInt_AS_LONG(io);
- Py_DECREF(io);
-
- return val;
+ if ((nb = Py_TYPE(op)->tp_as_number) == NULL ||
+ (nb->nb_int == NULL && nb->nb_long == 0)) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return -1;
+ }
+
+ if (nb->nb_long != 0)
+ io = (PyIntObject*) (*nb->nb_long) (op);
+ else
+ io = (PyIntObject*) (*nb->nb_int) (op);
+ if (io == NULL)
+ return -1;
+ if (!PyInt_Check(io)) {
+ if (PyLong_Check(io)) {
+ /* got a long? => retry int conversion */
+ val = _PyLong_AsSsize_t((PyObject *)io);
+ Py_DECREF(io);
+ if ((val == -1) && PyErr_Occurred())
+ return -1;
+ return val;
+ }
+ else
+ {
+ Py_DECREF(io);
+ PyErr_SetString(PyExc_TypeError,
+ "__int__ method should return an integer");
+ return -1;
+ }
+ }
+
+ val = PyInt_AS_LONG(io);
+ Py_DECREF(io);
+
+ return val;
#endif
}
unsigned long
PyInt_AsUnsignedLongMask(register PyObject *op)
{
- PyNumberMethods *nb;
- PyIntObject *io;
- unsigned long val;
-
- if (op && PyInt_Check(op))
- return PyInt_AS_LONG((PyIntObject*) op);
- if (op && PyLong_Check(op))
- return PyLong_AsUnsignedLongMask(op);
-
- if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
- nb->nb_int == NULL) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return (unsigned long)-1;
- }
-
- io = (PyIntObject*) (*nb->nb_int) (op);
- if (io == NULL)
- return (unsigned long)-1;
- if (!PyInt_Check(io)) {
- if (PyLong_Check(io)) {
- val = PyLong_AsUnsignedLongMask((PyObject *)io);
- Py_DECREF(io);
- if (PyErr_Occurred())
- return (unsigned long)-1;
- return val;
- }
- else
- {
- Py_DECREF(io);
- PyErr_SetString(PyExc_TypeError,
- "__int__ method should return an integer");
- return (unsigned long)-1;
- }
- }
-
- val = PyInt_AS_LONG(io);
- Py_DECREF(io);
-
- return val;
+ PyNumberMethods *nb;
+ PyIntObject *io;
+ unsigned long val;
+
+ if (op && PyInt_Check(op))
+ return PyInt_AS_LONG((PyIntObject*) op);
+ if (op && PyLong_Check(op))
+ return PyLong_AsUnsignedLongMask(op);
+
+ if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return (unsigned long)-1;
+ }
+
+ io = (PyIntObject*) (*nb->nb_int) (op);
+ if (io == NULL)
+ return (unsigned long)-1;
+ if (!PyInt_Check(io)) {
+ if (PyLong_Check(io)) {
+ val = PyLong_AsUnsignedLongMask((PyObject *)io);
+ Py_DECREF(io);
+ if (PyErr_Occurred())
+ return (unsigned long)-1;
+ return val;
+ }
+ else
+ {
+ Py_DECREF(io);
+ PyErr_SetString(PyExc_TypeError,
+ "__int__ method should return an integer");
+ return (unsigned long)-1;
+ }
+ }
+
+ val = PyInt_AS_LONG(io);
+ Py_DECREF(io);
+
+ return val;
}
#ifdef HAVE_LONG_LONG
unsigned PY_LONG_LONG
PyInt_AsUnsignedLongLongMask(register PyObject *op)
{
- PyNumberMethods *nb;
- PyIntObject *io;
- unsigned PY_LONG_LONG val;
-
- if (op && PyInt_Check(op))
- return PyInt_AS_LONG((PyIntObject*) op);
- if (op && PyLong_Check(op))
- return PyLong_AsUnsignedLongLongMask(op);
-
- if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
- nb->nb_int == NULL) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return (unsigned PY_LONG_LONG)-1;
- }
-
- io = (PyIntObject*) (*nb->nb_int) (op);
- if (io == NULL)
- return (unsigned PY_LONG_LONG)-1;
- if (!PyInt_Check(io)) {
- if (PyLong_Check(io)) {
- val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
- Py_DECREF(io);
- if (PyErr_Occurred())
- return (unsigned PY_LONG_LONG)-1;
- return val;
- }
- else
- {
- Py_DECREF(io);
- PyErr_SetString(PyExc_TypeError,
- "__int__ method should return an integer");
- return (unsigned PY_LONG_LONG)-1;
- }
- }
-
- val = PyInt_AS_LONG(io);
- Py_DECREF(io);
-
- return val;
+ PyNumberMethods *nb;
+ PyIntObject *io;
+ unsigned PY_LONG_LONG val;
+
+ if (op && PyInt_Check(op))
+ return PyInt_AS_LONG((PyIntObject*) op);
+ if (op && PyLong_Check(op))
+ return PyLong_AsUnsignedLongLongMask(op);
+
+ if (op == NULL || (nb = Py_TYPE(op)->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return (unsigned PY_LONG_LONG)-1;
+ }
+
+ io = (PyIntObject*) (*nb->nb_int) (op);
+ if (io == NULL)
+ return (unsigned PY_LONG_LONG)-1;
+ if (!PyInt_Check(io)) {
+ if (PyLong_Check(io)) {
+ val = PyLong_AsUnsignedLongLongMask((PyObject *)io);
+ Py_DECREF(io);
+ if (PyErr_Occurred())
+ return (unsigned PY_LONG_LONG)-1;
+ return val;
+ }
+ else
+ {
+ Py_DECREF(io);
+ PyErr_SetString(PyExc_TypeError,
+ "__int__ method should return an integer");
+ return (unsigned PY_LONG_LONG)-1;
+ }
+ }
+
+ val = PyInt_AS_LONG(io);
+ Py_DECREF(io);
+
+ return val;
}
#endif
PyObject *
PyInt_FromString(char *s, char **pend, int base)
{
- char *end;
- long x;
- Py_ssize_t slen;
- PyObject *sobj, *srepr;
-
- if ((base != 0 && base < 2) || base > 36) {
- PyErr_SetString(PyExc_ValueError,
- "int() base must be >= 2 and <= 36");
- return NULL;
- }
-
- while (*s && isspace(Py_CHARMASK(*s)))
- s++;
- errno = 0;
- if (base == 0 && s[0] == '0') {
- x = (long) PyOS_strtoul(s, &end, base);
- if (x < 0)
- return PyLong_FromString(s, pend, base);
- }
- else
- x = PyOS_strtol(s, &end, base);
- if (end == s || !isalnum(Py_CHARMASK(end[-1])))
- goto bad;
- while (*end && isspace(Py_CHARMASK(*end)))
- end++;
- if (*end != '\0') {
+ char *end;
+ long x;
+ Py_ssize_t slen;
+ PyObject *sobj, *srepr;
+
+ if ((base != 0 && base < 2) || base > 36) {
+ PyErr_SetString(PyExc_ValueError,
+ "int() base must be >= 2 and <= 36");
+ return NULL;
+ }
+
+ while (*s && isspace(Py_CHARMASK(*s)))
+ s++;
+ errno = 0;
+ if (base == 0 && s[0] == '0') {
+ x = (long) PyOS_strtoul(s, &end, base);
+ if (x < 0)
+ return PyLong_FromString(s, pend, base);
+ }
+ else
+ x = PyOS_strtol(s, &end, base);
+ if (end == s || !isalnum(Py_CHARMASK(end[-1])))
+ goto bad;
+ while (*end && isspace(Py_CHARMASK(*end)))
+ end++;
+ if (*end != '\0') {
bad:
- slen = strlen(s) < 200 ? strlen(s) : 200;
- sobj = PyString_FromStringAndSize(s, slen);
- if (sobj == NULL)
- return NULL;
- srepr = PyObject_Repr(sobj);
- Py_DECREF(sobj);
- if (srepr == NULL)
- return NULL;
- PyErr_Format(PyExc_ValueError,
- "invalid literal for int() with base %d: %s",
- base, PyString_AS_STRING(srepr));
- Py_DECREF(srepr);
- return NULL;
- }
- else if (errno != 0)
- return PyLong_FromString(s, pend, base);
- if (pend)
- *pend = end;
- return PyInt_FromLong(x);
+ slen = strlen(s) < 200 ? strlen(s) : 200;
+ sobj = PyString_FromStringAndSize(s, slen);
+ if (sobj == NULL)
+ return NULL;
+ srepr = PyObject_Repr(sobj);
+ Py_DECREF(sobj);
+ if (srepr == NULL)
+ return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "invalid literal for int() with base %d: %s",
+ base, PyString_AS_STRING(srepr));
+ Py_DECREF(srepr);
+ return NULL;
+ }
+ else if (errno != 0)
+ return PyLong_FromString(s, pend, base);
+ if (pend)
+ *pend = end;
+ return PyInt_FromLong(x);
}
#ifdef Py_USING_UNICODE
PyObject *
PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
{
- PyObject *result;
- char *buffer = (char *)PyMem_MALLOC(length+1);
-
- if (buffer == NULL)
- return PyErr_NoMemory();
-
- if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
- PyMem_FREE(buffer);
- return NULL;
- }
- result = PyInt_FromString(buffer, NULL, base);
- PyMem_FREE(buffer);
- return result;
+ PyObject *result;
+ char *buffer = (char *)PyMem_MALLOC(length+1);
+
+ if (buffer == NULL)
+ return PyErr_NoMemory();
+
+ if (PyUnicode_EncodeDecimal(s, length, buffer, NULL)) {
+ PyMem_FREE(buffer);
+ return NULL;
+ }
+ result = PyInt_FromString(buffer, NULL, base);
+ PyMem_FREE(buffer);
+ return result;
}
#endif
@@ -415,71 +415,71 @@ PyInt_FromUnicode(Py_UNICODE *s, Py_ssize_t length, int base)
don't have any knowledge about conversion of other types to
integers. */
-#define CONVERT_TO_LONG(obj, lng) \
- if (PyInt_Check(obj)) { \
- lng = PyInt_AS_LONG(obj); \
- } \
- else { \
- Py_INCREF(Py_NotImplemented); \
- return Py_NotImplemented; \
- }
+#define CONVERT_TO_LONG(obj, lng) \
+ if (PyInt_Check(obj)) { \
+ lng = PyInt_AS_LONG(obj); \
+ } \
+ else { \
+ Py_INCREF(Py_NotImplemented); \
+ return Py_NotImplemented; \
+ }
/* ARGSUSED */
static int
int_print(PyIntObject *v, FILE *fp, int flags)
/* flags -- not used but required by interface */
{
- long int_val = v->ob_ival;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "%ld", int_val);
- Py_END_ALLOW_THREADS
- return 0;
+ long int_val = v->ob_ival;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "%ld", int_val);
+ Py_END_ALLOW_THREADS
+ return 0;
}
static int
int_compare(PyIntObject *v, PyIntObject *w)
{
- register long i = v->ob_ival;
- register long j = w->ob_ival;
- return (i < j) ? -1 : (i > j) ? 1 : 0;
+ register long i = v->ob_ival;
+ register long j = w->ob_ival;
+ return (i < j) ? -1 : (i > j) ? 1 : 0;
}
static long
int_hash(PyIntObject *v)
{
- /* XXX If this is changed, you also need to change the way
- Python's long, float and complex types are hashed. */
- long x = v -> ob_ival;
- if (x == -1)
- x = -2;
- return x;
+ /* XXX If this is changed, you also need to change the way
+ Python's long, float and complex types are hashed. */
+ long x = v -> ob_ival;
+ if (x == -1)
+ x = -2;
+ return x;
}
static PyObject *
int_add(PyIntObject *v, PyIntObject *w)
{
- register long a, b, x;
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- /* casts in the line below avoid undefined behaviour on overflow */
- x = (long)((unsigned long)a + b);
- if ((x^a) >= 0 || (x^b) >= 0)
- return PyInt_FromLong(x);
- return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
+ register long a, b, x;
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ /* casts in the line below avoid undefined behaviour on overflow */
+ x = (long)((unsigned long)a + b);
+ if ((x^a) >= 0 || (x^b) >= 0)
+ return PyInt_FromLong(x);
+ return PyLong_Type.tp_as_number->nb_add((PyObject *)v, (PyObject *)w);
}
static PyObject *
int_sub(PyIntObject *v, PyIntObject *w)
{
- register long a, b, x;
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- /* casts in the line below avoid undefined behaviour on overflow */
- x = (long)((unsigned long)a - b);
- if ((x^a) >= 0 || (x^~b) >= 0)
- return PyInt_FromLong(x);
- return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
- (PyObject *)w);
+ register long a, b, x;
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ /* casts in the line below avoid undefined behaviour on overflow */
+ x = (long)((unsigned long)a - b);
+ if ((x^a) >= 0 || (x^~b) >= 0)
+ return PyInt_FromLong(x);
+ return PyLong_Type.tp_as_number->nb_subtract((PyObject *)v,
+ (PyObject *)w);
}
/*
@@ -511,40 +511,40 @@ product that must have overflowed.
static PyObject *
int_mul(PyObject *v, PyObject *w)
{
- long a, b;
- long longprod; /* a*b in native long arithmetic */
- double doubled_longprod; /* (double)longprod */
- double doubleprod; /* (double)a * (double)b */
-
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- /* casts in the next line avoid undefined behaviour on overflow */
- longprod = (long)((unsigned long)a * b);
- doubleprod = (double)a * (double)b;
- doubled_longprod = (double)longprod;
-
- /* Fast path for normal case: small multiplicands, and no info
- is lost in either method. */
- if (doubled_longprod == doubleprod)
- return PyInt_FromLong(longprod);
-
- /* Somebody somewhere lost info. Close enough, or way off? Note
- that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
- The difference either is or isn't significant compared to the
- true value (of which doubleprod is a good approximation).
- */
- {
- const double diff = doubled_longprod - doubleprod;
- const double absdiff = diff >= 0.0 ? diff : -diff;
- const double absprod = doubleprod >= 0.0 ? doubleprod :
- -doubleprod;
- /* absdiff/absprod <= 1/32 iff
- 32 * absdiff <= absprod -- 5 good bits is "close enough" */
- if (32.0 * absdiff <= absprod)
- return PyInt_FromLong(longprod);
- else
- return PyLong_Type.tp_as_number->nb_multiply(v, w);
- }
+ long a, b;
+ long longprod; /* a*b in native long arithmetic */
+ double doubled_longprod; /* (double)longprod */
+ double doubleprod; /* (double)a * (double)b */
+
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ /* casts in the next line avoid undefined behaviour on overflow */
+ longprod = (long)((unsigned long)a * b);
+ doubleprod = (double)a * (double)b;
+ doubled_longprod = (double)longprod;
+
+ /* Fast path for normal case: small multiplicands, and no info
+ is lost in either method. */
+ if (doubled_longprod == doubleprod)
+ return PyInt_FromLong(longprod);
+
+ /* Somebody somewhere lost info. Close enough, or way off? Note
+ that a != 0 and b != 0 (else doubled_longprod == doubleprod == 0).
+ The difference either is or isn't significant compared to the
+ true value (of which doubleprod is a good approximation).
+ */
+ {
+ const double diff = doubled_longprod - doubleprod;
+ const double absdiff = diff >= 0.0 ? diff : -diff;
+ const double absprod = doubleprod >= 0.0 ? doubleprod :
+ -doubleprod;
+ /* absdiff/absprod <= 1/32 iff
+ 32 * absdiff <= absprod -- 5 good bits is "close enough" */
+ if (32.0 * absdiff <= absprod)
+ return PyInt_FromLong(longprod);
+ else
+ return PyLong_Type.tp_as_number->nb_multiply(v, w);
+ }
}
/* Integer overflow checking for unary negation: on a 2's-complement
@@ -555,420 +555,420 @@ int_mul(PyObject *v, PyObject *w)
* warn about applying unary minus to an unsigned operand. Hence the
* weird "0-".
*/
-#define UNARY_NEG_WOULD_OVERFLOW(x) \
- ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
+#define UNARY_NEG_WOULD_OVERFLOW(x) \
+ ((x) < 0 && (unsigned long)(x) == 0-(unsigned long)(x))
/* Return type of i_divmod */
enum divmod_result {
- DIVMOD_OK, /* Correct result */
- DIVMOD_OVERFLOW, /* Overflow, try again using longs */
- DIVMOD_ERROR /* Exception raised */
+ DIVMOD_OK, /* Correct result */
+ DIVMOD_OVERFLOW, /* Overflow, try again using longs */
+ DIVMOD_ERROR /* Exception raised */
};
static enum divmod_result
i_divmod(register long x, register long y,
long *p_xdivy, long *p_xmody)
{
- long xdivy, xmody;
-
- if (y == 0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "integer division or modulo by zero");
- return DIVMOD_ERROR;
- }
- /* (-sys.maxint-1)/-1 is the only overflow case. */
- if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
- return DIVMOD_OVERFLOW;
- xdivy = x / y;
- /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
- * for x and y with differing signs. (This is unusual
- * behaviour, and C99 prohibits it, but it's allowed by C89;
- * for an example of overflow, take x = LONG_MIN, y = 5 or x =
- * LONG_MAX, y = -5.) However, x - xdivy*y is always
- * representable as a long, since it lies strictly between
- * -abs(y) and abs(y). We add casts to avoid intermediate
- * overflow.
- */
- xmody = (long)(x - (unsigned long)xdivy * y);
- /* If the signs of x and y differ, and the remainder is non-0,
- * C89 doesn't define whether xdivy is now the floor or the
- * ceiling of the infinitely precise quotient. We want the floor,
- * and we have it iff the remainder's sign matches y's.
- */
- if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
- xmody += y;
- --xdivy;
- assert(xmody && ((y ^ xmody) >= 0));
- }
- *p_xdivy = xdivy;
- *p_xmody = xmody;
- return DIVMOD_OK;
+ long xdivy, xmody;
+
+ if (y == 0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "integer division or modulo by zero");
+ return DIVMOD_ERROR;
+ }
+ /* (-sys.maxint-1)/-1 is the only overflow case. */
+ if (y == -1 && UNARY_NEG_WOULD_OVERFLOW(x))
+ return DIVMOD_OVERFLOW;
+ xdivy = x / y;
+ /* xdiv*y can overflow on platforms where x/y gives floor(x/y)
+ * for x and y with differing signs. (This is unusual
+ * behaviour, and C99 prohibits it, but it's allowed by C89;
+ * for an example of overflow, take x = LONG_MIN, y = 5 or x =
+ * LONG_MAX, y = -5.) However, x - xdivy*y is always
+ * representable as a long, since it lies strictly between
+ * -abs(y) and abs(y). We add casts to avoid intermediate
+ * overflow.
+ */
+ xmody = (long)(x - (unsigned long)xdivy * y);
+ /* If the signs of x and y differ, and the remainder is non-0,
+ * C89 doesn't define whether xdivy is now the floor or the
+ * ceiling of the infinitely precise quotient. We want the floor,
+ * and we have it iff the remainder's sign matches y's.
+ */
+ if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
+ xmody += y;
+ --xdivy;
+ assert(xmody && ((y ^ xmody) >= 0));
+ }
+ *p_xdivy = xdivy;
+ *p_xmody = xmody;
+ return DIVMOD_OK;
}
static PyObject *
int_div(PyIntObject *x, PyIntObject *y)
{
- long xi, yi;
- long d, m;
- CONVERT_TO_LONG(x, xi);
- CONVERT_TO_LONG(y, yi);
- switch (i_divmod(xi, yi, &d, &m)) {
- case DIVMOD_OK:
- return PyInt_FromLong(d);
- case DIVMOD_OVERFLOW:
- return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
- (PyObject *)y);
- default:
- return NULL;
- }
+ long xi, yi;
+ long d, m;
+ CONVERT_TO_LONG(x, xi);
+ CONVERT_TO_LONG(y, yi);
+ switch (i_divmod(xi, yi, &d, &m)) {
+ case DIVMOD_OK:
+ return PyInt_FromLong(d);
+ case DIVMOD_OVERFLOW:
+ return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
+ (PyObject *)y);
+ default:
+ return NULL;
+ }
}
static PyObject *
int_classic_div(PyIntObject *x, PyIntObject *y)
{
- long xi, yi;
- long d, m;
- CONVERT_TO_LONG(x, xi);
- CONVERT_TO_LONG(y, yi);
- if (Py_DivisionWarningFlag &&
- PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
- return NULL;
- switch (i_divmod(xi, yi, &d, &m)) {
- case DIVMOD_OK:
- return PyInt_FromLong(d);
- case DIVMOD_OVERFLOW:
- return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
- (PyObject *)y);
- default:
- return NULL;
- }
+ long xi, yi;
+ long d, m;
+ CONVERT_TO_LONG(x, xi);
+ CONVERT_TO_LONG(y, yi);
+ if (Py_DivisionWarningFlag &&
+ PyErr_Warn(PyExc_DeprecationWarning, "classic int division") < 0)
+ return NULL;
+ switch (i_divmod(xi, yi, &d, &m)) {
+ case DIVMOD_OK:
+ return PyInt_FromLong(d);
+ case DIVMOD_OVERFLOW:
+ return PyLong_Type.tp_as_number->nb_divide((PyObject *)x,
+ (PyObject *)y);
+ default:
+ return NULL;
+ }
}
static PyObject *
int_true_divide(PyIntObject *x, PyIntObject *y)
{
- long xi, yi;
- /* If they aren't both ints, give someone else a chance. In
- particular, this lets int/long get handled by longs, which
- underflows to 0 gracefully if the long is too big to convert
- to float. */
- CONVERT_TO_LONG(x, xi);
- CONVERT_TO_LONG(y, yi);
- if (yi == 0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "division by zero");
- return NULL;
- }
- if (xi == 0)
- return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0);
+ long xi, yi;
+ /* If they aren't both ints, give someone else a chance. In
+ particular, this lets int/long get handled by longs, which
+ underflows to 0 gracefully if the long is too big to convert
+ to float. */
+ CONVERT_TO_LONG(x, xi);
+ CONVERT_TO_LONG(y, yi);
+ if (yi == 0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "division by zero");
+ return NULL;
+ }
+ if (xi == 0)
+ return PyFloat_FromDouble(yi < 0 ? -0.0 : 0.0);
#define WIDTH_OF_ULONG (CHAR_BIT*SIZEOF_LONG)
#if DBL_MANT_DIG < WIDTH_OF_ULONG
- if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG ||
- (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG)
- /* Large x or y. Use long integer arithmetic. */
- return PyLong_Type.tp_as_number->nb_true_divide(
- (PyObject *)x, (PyObject *)y);
- else
+ if ((xi >= 0 ? 0UL + xi : 0UL - xi) >> DBL_MANT_DIG ||
+ (yi >= 0 ? 0UL + yi : 0UL - yi) >> DBL_MANT_DIG)
+ /* Large x or y. Use long integer arithmetic. */
+ return PyLong_Type.tp_as_number->nb_true_divide(
+ (PyObject *)x, (PyObject *)y);
+ else
#endif
- /* Both ints can be exactly represented as doubles. Do a
- floating-point division. */
- return PyFloat_FromDouble((double)xi / (double)yi);
+ /* Both ints can be exactly represented as doubles. Do a
+ floating-point division. */
+ return PyFloat_FromDouble((double)xi / (double)yi);
}
static PyObject *
int_mod(PyIntObject *x, PyIntObject *y)
{
- long xi, yi;
- long d, m;
- CONVERT_TO_LONG(x, xi);
- CONVERT_TO_LONG(y, yi);
- switch (i_divmod(xi, yi, &d, &m)) {
- case DIVMOD_OK:
- return PyInt_FromLong(m);
- case DIVMOD_OVERFLOW:
- return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
- (PyObject *)y);
- default:
- return NULL;
- }
+ long xi, yi;
+ long d, m;
+ CONVERT_TO_LONG(x, xi);
+ CONVERT_TO_LONG(y, yi);
+ switch (i_divmod(xi, yi, &d, &m)) {
+ case DIVMOD_OK:
+ return PyInt_FromLong(m);
+ case DIVMOD_OVERFLOW:
+ return PyLong_Type.tp_as_number->nb_remainder((PyObject *)x,
+ (PyObject *)y);
+ default:
+ return NULL;
+ }
}
static PyObject *
int_divmod(PyIntObject *x, PyIntObject *y)
{
- long xi, yi;
- long d, m;
- CONVERT_TO_LONG(x, xi);
- CONVERT_TO_LONG(y, yi);
- switch (i_divmod(xi, yi, &d, &m)) {
- case DIVMOD_OK:
- return Py_BuildValue("(ll)", d, m);
- case DIVMOD_OVERFLOW:
- return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
- (PyObject *)y);
- default:
- return NULL;
- }
+ long xi, yi;
+ long d, m;
+ CONVERT_TO_LONG(x, xi);
+ CONVERT_TO_LONG(y, yi);
+ switch (i_divmod(xi, yi, &d, &m)) {
+ case DIVMOD_OK:
+ return Py_BuildValue("(ll)", d, m);
+ case DIVMOD_OVERFLOW:
+ return PyLong_Type.tp_as_number->nb_divmod((PyObject *)x,
+ (PyObject *)y);
+ default:
+ return NULL;
+ }
}
static PyObject *
int_pow(PyIntObject *v, PyIntObject *w, PyIntObject *z)
{
- register long iv, iw, iz=0, ix, temp, prev;
- CONVERT_TO_LONG(v, iv);
- CONVERT_TO_LONG(w, iw);
- if (iw < 0) {
- if ((PyObject *)z != Py_None) {
- PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
- "cannot be negative when 3rd argument specified");
- return NULL;
- }
- /* Return a float. This works because we know that
- this calls float_pow() which converts its
- arguments to double. */
- return PyFloat_Type.tp_as_number->nb_power(
- (PyObject *)v, (PyObject *)w, (PyObject *)z);
- }
- if ((PyObject *)z != Py_None) {
- CONVERT_TO_LONG(z, iz);
- if (iz == 0) {
- PyErr_SetString(PyExc_ValueError,
- "pow() 3rd argument cannot be 0");
- return NULL;
- }
- }
- /*
- * XXX: The original exponentiation code stopped looping
- * when temp hit zero; this code will continue onwards
- * unnecessarily, but at least it won't cause any errors.
- * Hopefully the speed improvement from the fast exponentiation
- * will compensate for the slight inefficiency.
- * XXX: Better handling of overflows is desperately needed.
- */
- temp = iv;
- ix = 1;
- while (iw > 0) {
- prev = ix; /* Save value for overflow check */
- if (iw & 1) {
- ix = ix*temp;
- if (temp == 0)
- break; /* Avoid ix / 0 */
- if (ix / temp != prev) {
- return PyLong_Type.tp_as_number->nb_power(
- (PyObject *)v,
- (PyObject *)w,
- (PyObject *)z);
- }
- }
- iw >>= 1; /* Shift exponent down by 1 bit */
- if (iw==0) break;
- prev = temp;
- temp *= temp; /* Square the value of temp */
- if (prev != 0 && temp / prev != prev) {
- return PyLong_Type.tp_as_number->nb_power(
- (PyObject *)v, (PyObject *)w, (PyObject *)z);
- }
- if (iz) {
- /* If we did a multiplication, perform a modulo */
- ix = ix % iz;
- temp = temp % iz;
- }
- }
- if (iz) {
- long div, mod;
- switch (i_divmod(ix, iz, &div, &mod)) {
- case DIVMOD_OK:
- ix = mod;
- break;
- case DIVMOD_OVERFLOW:
- return PyLong_Type.tp_as_number->nb_power(
- (PyObject *)v, (PyObject *)w, (PyObject *)z);
- default:
- return NULL;
- }
- }
- return PyInt_FromLong(ix);
+ register long iv, iw, iz=0, ix, temp, prev;
+ CONVERT_TO_LONG(v, iv);
+ CONVERT_TO_LONG(w, iw);
+ if (iw < 0) {
+ if ((PyObject *)z != Py_None) {
+ PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
+ "cannot be negative when 3rd argument specified");
+ return NULL;
+ }
+ /* Return a float. This works because we know that
+ this calls float_pow() which converts its
+ arguments to double. */
+ return PyFloat_Type.tp_as_number->nb_power(
+ (PyObject *)v, (PyObject *)w, (PyObject *)z);
+ }
+ if ((PyObject *)z != Py_None) {
+ CONVERT_TO_LONG(z, iz);
+ if (iz == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "pow() 3rd argument cannot be 0");
+ return NULL;
+ }
+ }
+ /*
+ * XXX: The original exponentiation code stopped looping
+ * when temp hit zero; this code will continue onwards
+ * unnecessarily, but at least it won't cause any errors.
+ * Hopefully the speed improvement from the fast exponentiation
+ * will compensate for the slight inefficiency.
+ * XXX: Better handling of overflows is desperately needed.
+ */
+ temp = iv;
+ ix = 1;
+ while (iw > 0) {
+ prev = ix; /* Save value for overflow check */
+ if (iw & 1) {
+ ix = ix*temp;
+ if (temp == 0)
+ break; /* Avoid ix / 0 */
+ if (ix / temp != prev) {
+ return PyLong_Type.tp_as_number->nb_power(
+ (PyObject *)v,
+ (PyObject *)w,
+ (PyObject *)z);
+ }
+ }
+ iw >>= 1; /* Shift exponent down by 1 bit */
+ if (iw==0) break;
+ prev = temp;
+ temp *= temp; /* Square the value of temp */
+ if (prev != 0 && temp / prev != prev) {
+ return PyLong_Type.tp_as_number->nb_power(
+ (PyObject *)v, (PyObject *)w, (PyObject *)z);
+ }
+ if (iz) {
+ /* If we did a multiplication, perform a modulo */
+ ix = ix % iz;
+ temp = temp % iz;
+ }
+ }
+ if (iz) {
+ long div, mod;
+ switch (i_divmod(ix, iz, &div, &mod)) {
+ case DIVMOD_OK:
+ ix = mod;
+ break;
+ case DIVMOD_OVERFLOW:
+ return PyLong_Type.tp_as_number->nb_power(
+ (PyObject *)v, (PyObject *)w, (PyObject *)z);
+ default:
+ return NULL;
+ }
+ }
+ return PyInt_FromLong(ix);
}
static PyObject *
int_neg(PyIntObject *v)
{
- register long a;
- a = v->ob_ival;
- /* check for overflow */
- if (UNARY_NEG_WOULD_OVERFLOW(a)) {
- PyObject *o = PyLong_FromLong(a);
- if (o != NULL) {
- PyObject *result = PyNumber_Negative(o);
- Py_DECREF(o);
- return result;
- }
- return NULL;
- }
- return PyInt_FromLong(-a);
+ register long a;
+ a = v->ob_ival;
+ /* check for overflow */
+ if (UNARY_NEG_WOULD_OVERFLOW(a)) {
+ PyObject *o = PyLong_FromLong(a);
+ if (o != NULL) {
+ PyObject *result = PyNumber_Negative(o);
+ Py_DECREF(o);
+ return result;
+ }
+ return NULL;
+ }
+ return PyInt_FromLong(-a);
}
static PyObject *
int_abs(PyIntObject *v)
{
- if (v->ob_ival >= 0)
- return int_int(v);
- else
- return int_neg(v);
+ if (v->ob_ival >= 0)
+ return int_int(v);
+ else
+ return int_neg(v);
}
static int
int_nonzero(PyIntObject *v)
{
- return v->ob_ival != 0;
+ return v->ob_ival != 0;
}
static PyObject *
int_invert(PyIntObject *v)
{
- return PyInt_FromLong(~v->ob_ival);
+ return PyInt_FromLong(~v->ob_ival);
}
static PyObject *
int_lshift(PyIntObject *v, PyIntObject *w)
{
- long a, b, c;
- PyObject *vv, *ww, *result;
-
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- if (b < 0) {
- PyErr_SetString(PyExc_ValueError, "negative shift count");
- return NULL;
- }
- if (a == 0 || b == 0)
- return int_int(v);
- if (b >= LONG_BIT) {
- vv = PyLong_FromLong(PyInt_AS_LONG(v));
- if (vv == NULL)
- return NULL;
- ww = PyLong_FromLong(PyInt_AS_LONG(w));
- if (ww == NULL) {
- Py_DECREF(vv);
- return NULL;
- }
- result = PyNumber_Lshift(vv, ww);
- Py_DECREF(vv);
- Py_DECREF(ww);
- return result;
- }
- c = a << b;
- if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
- vv = PyLong_FromLong(PyInt_AS_LONG(v));
- if (vv == NULL)
- return NULL;
- ww = PyLong_FromLong(PyInt_AS_LONG(w));
- if (ww == NULL) {
- Py_DECREF(vv);
- return NULL;
- }
- result = PyNumber_Lshift(vv, ww);
- Py_DECREF(vv);
- Py_DECREF(ww);
- return result;
- }
- return PyInt_FromLong(c);
+ long a, b, c;
+ PyObject *vv, *ww, *result;
+
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ if (b < 0) {
+ PyErr_SetString(PyExc_ValueError, "negative shift count");
+ return NULL;
+ }
+ if (a == 0 || b == 0)
+ return int_int(v);
+ if (b >= LONG_BIT) {
+ vv = PyLong_FromLong(PyInt_AS_LONG(v));
+ if (vv == NULL)
+ return NULL;
+ ww = PyLong_FromLong(PyInt_AS_LONG(w));
+ if (ww == NULL) {
+ Py_DECREF(vv);
+ return NULL;
+ }
+ result = PyNumber_Lshift(vv, ww);
+ Py_DECREF(vv);
+ Py_DECREF(ww);
+ return result;
+ }
+ c = a << b;
+ if (a != Py_ARITHMETIC_RIGHT_SHIFT(long, c, b)) {
+ vv = PyLong_FromLong(PyInt_AS_LONG(v));
+ if (vv == NULL)
+ return NULL;
+ ww = PyLong_FromLong(PyInt_AS_LONG(w));
+ if (ww == NULL) {
+ Py_DECREF(vv);
+ return NULL;
+ }
+ result = PyNumber_Lshift(vv, ww);
+ Py_DECREF(vv);
+ Py_DECREF(ww);
+ return result;
+ }
+ return PyInt_FromLong(c);
}
static PyObject *
int_rshift(PyIntObject *v, PyIntObject *w)
{
- register long a, b;
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- if (b < 0) {
- PyErr_SetString(PyExc_ValueError, "negative shift count");
- return NULL;
- }
- if (a == 0 || b == 0)
- return int_int(v);
- if (b >= LONG_BIT) {
- if (a < 0)
- a = -1;
- else
- a = 0;
- }
- else {
- a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
- }
- return PyInt_FromLong(a);
+ register long a, b;
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ if (b < 0) {
+ PyErr_SetString(PyExc_ValueError, "negative shift count");
+ return NULL;
+ }
+ if (a == 0 || b == 0)
+ return int_int(v);
+ if (b >= LONG_BIT) {
+ if (a < 0)
+ a = -1;
+ else
+ a = 0;
+ }
+ else {
+ a = Py_ARITHMETIC_RIGHT_SHIFT(long, a, b);
+ }
+ return PyInt_FromLong(a);
}
static PyObject *
int_and(PyIntObject *v, PyIntObject *w)
{
- register long a, b;
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- return PyInt_FromLong(a & b);
+ register long a, b;
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ return PyInt_FromLong(a & b);
}
static PyObject *
int_xor(PyIntObject *v, PyIntObject *w)
{
- register long a, b;
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- return PyInt_FromLong(a ^ b);
+ register long a, b;
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ return PyInt_FromLong(a ^ b);
}
static PyObject *
int_or(PyIntObject *v, PyIntObject *w)
{
- register long a, b;
- CONVERT_TO_LONG(v, a);
- CONVERT_TO_LONG(w, b);
- return PyInt_FromLong(a | b);
+ register long a, b;
+ CONVERT_TO_LONG(v, a);
+ CONVERT_TO_LONG(w, b);
+ return PyInt_FromLong(a | b);
}
static int
int_coerce(PyObject **pv, PyObject **pw)
{
- if (PyInt_Check(*pw)) {
- Py_INCREF(*pv);
- Py_INCREF(*pw);
- return 0;
- }
- return 1; /* Can't do it */
+ if (PyInt_Check(*pw)) {
+ Py_INCREF(*pv);
+ Py_INCREF(*pw);
+ return 0;
+ }
+ return 1; /* Can't do it */
}
static PyObject *
int_int(PyIntObject *v)
{
- if (PyInt_CheckExact(v))
- Py_INCREF(v);
- else
- v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
- return (PyObject *)v;
+ if (PyInt_CheckExact(v))
+ Py_INCREF(v);
+ else
+ v = (PyIntObject *)PyInt_FromLong(v->ob_ival);
+ return (PyObject *)v;
}
static PyObject *
int_long(PyIntObject *v)
{
- return PyLong_FromLong((v -> ob_ival));
+ return PyLong_FromLong((v -> ob_ival));
}
static const unsigned char BitLengthTable[32] = {
- 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
- 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
+ 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
};
static int
bits_in_ulong(unsigned long d)
{
- int d_bits = 0;
- while (d >= 32) {
- d_bits += 6;
- d >>= 6;
- }
- d_bits += (int)BitLengthTable[d];
- return d_bits;
+ int d_bits = 0;
+ while (d >= 32) {
+ d_bits += 6;
+ d >>= 6;
+ }
+ d_bits += (int)BitLengthTable[d];
+ return d_bits;
}
#if 8*SIZEOF_LONG-1 <= DBL_MANT_DIG
@@ -977,7 +977,7 @@ bits_in_ulong(unsigned long d)
static PyObject *
int_float(PyIntObject *v)
{
- return PyFloat_FromDouble((double)(v -> ob_ival));
+ return PyFloat_FromDouble((double)(v -> ob_ival));
}
#else
@@ -988,40 +988,40 @@ int_float(PyIntObject *v)
static PyObject *
int_float(PyIntObject *v)
{
- unsigned long abs_ival, lsb;
- int round_up;
-
- if (v->ob_ival < 0)
- abs_ival = 0U-(unsigned long)v->ob_ival;
- else
- abs_ival = (unsigned long)v->ob_ival;
- if (abs_ival < (1L << DBL_MANT_DIG))
- /* small integer; no need to round */
- return PyFloat_FromDouble((double)v->ob_ival);
-
- /* Round abs_ival to MANT_DIG significant bits, using the
- round-half-to-even rule. abs_ival & lsb picks out the 'rounding'
- bit: the first bit after the most significant MANT_DIG bits of
- abs_ival. We round up if this bit is set, provided that either:
-
- (1) abs_ival isn't exactly halfway between two floats, in which
- case at least one of the bits following the rounding bit must be
- set; i.e., abs_ival & lsb-1 != 0, or:
-
- (2) the resulting rounded value has least significant bit 0; or
- in other words the bit above the rounding bit is set (this is the
- 'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0
-
- The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */
-
- lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1);
- round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1));
- abs_ival &= -2*lsb;
- if (round_up)
- abs_ival += 2*lsb;
- return PyFloat_FromDouble(v->ob_ival < 0 ?
- -(double)abs_ival :
- (double)abs_ival);
+ unsigned long abs_ival, lsb;
+ int round_up;
+
+ if (v->ob_ival < 0)
+ abs_ival = 0U-(unsigned long)v->ob_ival;
+ else
+ abs_ival = (unsigned long)v->ob_ival;
+ if (abs_ival < (1L << DBL_MANT_DIG))
+ /* small integer; no need to round */
+ return PyFloat_FromDouble((double)v->ob_ival);
+
+ /* Round abs_ival to MANT_DIG significant bits, using the
+ round-half-to-even rule. abs_ival & lsb picks out the 'rounding'
+ bit: the first bit after the most significant MANT_DIG bits of
+ abs_ival. We round up if this bit is set, provided that either:
+
+ (1) abs_ival isn't exactly halfway between two floats, in which
+ case at least one of the bits following the rounding bit must be
+ set; i.e., abs_ival & lsb-1 != 0, or:
+
+ (2) the resulting rounded value has least significant bit 0; or
+ in other words the bit above the rounding bit is set (this is the
+ 'to-even' bit of round-half-to-even); i.e., abs_ival & 2*lsb != 0
+
+ The condition "(1) or (2)" equates to abs_ival & 3*lsb-1 != 0. */
+
+ lsb = 1L << (bits_in_ulong(abs_ival)-DBL_MANT_DIG-1);
+ round_up = (abs_ival & lsb) && (abs_ival & (3*lsb-1));
+ abs_ival &= -2*lsb;
+ if (round_up)
+ abs_ival += 2*lsb;
+ return PyFloat_FromDouble(v->ob_ival < 0 ?
+ -(double)abs_ival :
+ (double)abs_ival);
}
#endif
@@ -1029,13 +1029,13 @@ int_float(PyIntObject *v)
static PyObject *
int_oct(PyIntObject *v)
{
- return _PyInt_Format(v, 8, 0);
+ return _PyInt_Format(v, 8, 0);
}
static PyObject *
int_hex(PyIntObject *v)
{
- return _PyInt_Format(v, 16, 0);
+ return _PyInt_Format(v, 16, 0);
}
static PyObject *
@@ -1044,47 +1044,47 @@ int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *x = NULL;
- int base = -909;
- static char *kwlist[] = {"x", "base", 0};
-
- if (type != &PyInt_Type)
- return int_subtype_new(type, args, kwds); /* Wimp out */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
- &x, &base))
- return NULL;
- if (x == NULL)
- return PyInt_FromLong(0L);
- if (base == -909)
- return PyNumber_Int(x);
- if (PyString_Check(x)) {
- /* Since PyInt_FromString doesn't have a length parameter,
- * check here for possible NULs in the string. */
- char *string = PyString_AS_STRING(x);
- if (strlen(string) != PyString_Size(x)) {
- /* create a repr() of the input string,
- * just like PyInt_FromString does */
- PyObject *srepr;
- srepr = PyObject_Repr(x);
- if (srepr == NULL)
- return NULL;
- PyErr_Format(PyExc_ValueError,
- "invalid literal for int() with base %d: %s",
- base, PyString_AS_STRING(srepr));
- Py_DECREF(srepr);
- return NULL;
- }
- return PyInt_FromString(string, NULL, base);
- }
+ PyObject *x = NULL;
+ int base = -909;
+ static char *kwlist[] = {"x", "base", 0};
+
+ if (type != &PyInt_Type)
+ return int_subtype_new(type, args, kwds); /* Wimp out */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:int", kwlist,
+ &x, &base))
+ return NULL;
+ if (x == NULL)
+ return PyInt_FromLong(0L);
+ if (base == -909)
+ return PyNumber_Int(x);
+ if (PyString_Check(x)) {
+ /* Since PyInt_FromString doesn't have a length parameter,
+ * check here for possible NULs in the string. */
+ char *string = PyString_AS_STRING(x);
+ if (strlen(string) != PyString_Size(x)) {
+ /* create a repr() of the input string,
+ * just like PyInt_FromString does */
+ PyObject *srepr;
+ srepr = PyObject_Repr(x);
+ if (srepr == NULL)
+ return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "invalid literal for int() with base %d: %s",
+ base, PyString_AS_STRING(srepr));
+ Py_DECREF(srepr);
+ return NULL;
+ }
+ return PyInt_FromString(string, NULL, base);
+ }
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(x))
- return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
- PyUnicode_GET_SIZE(x),
- base);
+ if (PyUnicode_Check(x))
+ return PyInt_FromUnicode(PyUnicode_AS_UNICODE(x),
+ PyUnicode_GET_SIZE(x),
+ base);
#endif
- PyErr_SetString(PyExc_TypeError,
- "int() can't convert non-string with explicit base");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "int() can't convert non-string with explicit base");
+ return NULL;
}
/* Wimpy, slow approach to tp_new calls for subtypes of int:
@@ -1095,47 +1095,47 @@ int_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
int_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *tmp, *newobj;
- long ival;
-
- assert(PyType_IsSubtype(type, &PyInt_Type));
- tmp = int_new(&PyInt_Type, args, kwds);
- if (tmp == NULL)
- return NULL;
- if (!PyInt_Check(tmp)) {
- ival = PyLong_AsLong(tmp);
- if (ival == -1 && PyErr_Occurred()) {
- Py_DECREF(tmp);
- return NULL;
- }
- } else {
- ival = ((PyIntObject *)tmp)->ob_ival;
- }
-
- newobj = type->tp_alloc(type, 0);
- if (newobj == NULL) {
- Py_DECREF(tmp);
- return NULL;
- }
- ((PyIntObject *)newobj)->ob_ival = ival;
- Py_DECREF(tmp);
- return newobj;
+ PyObject *tmp, *newobj;
+ long ival;
+
+ assert(PyType_IsSubtype(type, &PyInt_Type));
+ tmp = int_new(&PyInt_Type, args, kwds);
+ if (tmp == NULL)
+ return NULL;
+ if (!PyInt_Check(tmp)) {
+ ival = PyLong_AsLong(tmp);
+ if (ival == -1 && PyErr_Occurred()) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ } else {
+ ival = ((PyIntObject *)tmp)->ob_ival;
+ }
+
+ newobj = type->tp_alloc(type, 0);
+ if (newobj == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ ((PyIntObject *)newobj)->ob_ival = ival;
+ Py_DECREF(tmp);
+ return newobj;
}
static PyObject *
int_getnewargs(PyIntObject *v)
{
- return Py_BuildValue("(l)", v->ob_ival);
+ return Py_BuildValue("(l)", v->ob_ival);
}
static PyObject *
int_get0(PyIntObject *v, void *context) {
- return PyInt_FromLong(0L);
+ return PyInt_FromLong(0L);
}
static PyObject *
int_get1(PyIntObject *v, void *context) {
- return PyInt_FromLong(1L);
+ return PyInt_FromLong(1L);
}
/* Convert an integer to a decimal string. On many platforms, this
@@ -1144,18 +1144,18 @@ int_get1(PyIntObject *v, void *context) {
opportunities offered by division by a compile-time constant. */
static PyObject *
int_to_decimal_string(PyIntObject *v) {
- char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
- long n = v->ob_ival;
- unsigned long absn;
- p = bufend = buf + sizeof(buf);
- absn = n < 0 ? 0UL - n : n;
- do {
- *--p = '0' + (char)(absn % 10);
- absn /= 10;
- } while (absn);
- if (n < 0)
- *--p = '-';
- return PyString_FromStringAndSize(p, bufend - p);
+ char buf[sizeof(long)*CHAR_BIT/3+6], *p, *bufend;
+ long n = v->ob_ival;
+ unsigned long absn;
+ p = bufend = buf + sizeof(buf);
+ absn = n < 0 ? 0UL - n : n;
+ do {
+ *--p = '0' + (char)(absn % 10);
+ absn /= 10;
+ } while (absn);
+ if (n < 0)
+ *--p = '-';
+ return PyString_FromStringAndSize(p, bufend - p);
}
/* Convert an integer to the given base. Returns a string.
@@ -1165,113 +1165,113 @@ int_to_decimal_string(PyIntObject *v) {
PyAPI_FUNC(PyObject*)
_PyInt_Format(PyIntObject *v, int base, int newstyle)
{
- /* There are no doubt many, many ways to optimize this, using code
- similar to _PyLong_Format */
- long n = v->ob_ival;
- int negative = n < 0;
- int is_zero = n == 0;
-
- /* For the reasoning behind this size, see
- http://c-faq.com/misc/hexio.html. Then, add a few bytes for
- the possible sign and prefix "0[box]" */
- char buf[sizeof(n)*CHAR_BIT+6];
-
- /* Start by pointing to the end of the buffer. We fill in from
- the back forward. */
- char* p = &buf[sizeof(buf)];
-
- assert(base >= 2 && base <= 36);
-
- /* Special case base 10, for speed */
- if (base == 10)
- return int_to_decimal_string(v);
-
- do {
- /* I'd use i_divmod, except it doesn't produce the results
- I want when n is negative. So just duplicate the salient
- part here. */
- long div = n / base;
- long mod = n - div * base;
-
- /* convert abs(mod) to the right character in [0-9, a-z] */
- char cdigit = (char)(mod < 0 ? -mod : mod);
- cdigit += (cdigit < 10) ? '0' : 'a'-10;
- *--p = cdigit;
-
- n = div;
- } while(n);
-
- if (base == 2) {
- *--p = 'b';
- *--p = '0';
- }
- else if (base == 8) {
- if (newstyle) {
- *--p = 'o';
- *--p = '0';
- }
- else
- if (!is_zero)
- *--p = '0';
- }
- else if (base == 16) {
- *--p = 'x';
- *--p = '0';
- }
- else {
- *--p = '#';
- *--p = '0' + base%10;
- if (base > 10)
- *--p = '0' + base/10;
- }
- if (negative)
- *--p = '-';
-
- return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
+ /* There are no doubt many, many ways to optimize this, using code
+ similar to _PyLong_Format */
+ long n = v->ob_ival;
+ int negative = n < 0;
+ int is_zero = n == 0;
+
+ /* For the reasoning behind this size, see
+ http://c-faq.com/misc/hexio.html. Then, add a few bytes for
+ the possible sign and prefix "0[box]" */
+ char buf[sizeof(n)*CHAR_BIT+6];
+
+ /* Start by pointing to the end of the buffer. We fill in from
+ the back forward. */
+ char* p = &buf[sizeof(buf)];
+
+ assert(base >= 2 && base <= 36);
+
+ /* Special case base 10, for speed */
+ if (base == 10)
+ return int_to_decimal_string(v);
+
+ do {
+ /* I'd use i_divmod, except it doesn't produce the results
+ I want when n is negative. So just duplicate the salient
+ part here. */
+ long div = n / base;
+ long mod = n - div * base;
+
+ /* convert abs(mod) to the right character in [0-9, a-z] */
+ char cdigit = (char)(mod < 0 ? -mod : mod);
+ cdigit += (cdigit < 10) ? '0' : 'a'-10;
+ *--p = cdigit;
+
+ n = div;
+ } while(n);
+
+ if (base == 2) {
+ *--p = 'b';
+ *--p = '0';
+ }
+ else if (base == 8) {
+ if (newstyle) {
+ *--p = 'o';
+ *--p = '0';
+ }
+ else
+ if (!is_zero)
+ *--p = '0';
+ }
+ else if (base == 16) {
+ *--p = 'x';
+ *--p = '0';
+ }
+ else {
+ *--p = '#';
+ *--p = '0' + base%10;
+ if (base > 10)
+ *--p = '0' + base/10;
+ }
+ if (negative)
+ *--p = '-';
+
+ return PyString_FromStringAndSize(p, &buf[sizeof(buf)] - p);
}
static PyObject *
int__format__(PyObject *self, PyObject *args)
{
- PyObject *format_spec;
-
- if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
- return NULL;
- if (PyBytes_Check(format_spec))
- return _PyInt_FormatAdvanced(self,
- PyBytes_AS_STRING(format_spec),
- PyBytes_GET_SIZE(format_spec));
- if (PyUnicode_Check(format_spec)) {
- /* Convert format_spec to a str */
- PyObject *result;
- PyObject *str_spec = PyObject_Str(format_spec);
-
- if (str_spec == NULL)
- return NULL;
-
- result = _PyInt_FormatAdvanced(self,
- PyBytes_AS_STRING(str_spec),
- PyBytes_GET_SIZE(str_spec));
-
- Py_DECREF(str_spec);
- return result;
- }
- PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
- return NULL;
+ PyObject *format_spec;
+
+ if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
+ return NULL;
+ if (PyBytes_Check(format_spec))
+ return _PyInt_FormatAdvanced(self,
+ PyBytes_AS_STRING(format_spec),
+ PyBytes_GET_SIZE(format_spec));
+ if (PyUnicode_Check(format_spec)) {
+ /* Convert format_spec to a str */
+ PyObject *result;
+ PyObject *str_spec = PyObject_Str(format_spec);
+
+ if (str_spec == NULL)
+ return NULL;
+
+ result = _PyInt_FormatAdvanced(self,
+ PyBytes_AS_STRING(str_spec),
+ PyBytes_GET_SIZE(str_spec));
+
+ Py_DECREF(str_spec);
+ return result;
+ }
+ PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
+ return NULL;
}
static PyObject *
int_bit_length(PyIntObject *v)
{
- unsigned long n;
+ unsigned long n;
- if (v->ob_ival < 0)
- /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
- n = 0U-(unsigned long)v->ob_ival;
- else
- n = (unsigned long)v->ob_ival;
+ if (v->ob_ival < 0)
+ /* avoid undefined behaviour when v->ob_ival == -LONG_MAX-1 */
+ n = 0U-(unsigned long)v->ob_ival;
+ else
+ n = (unsigned long)v->ob_ival;
- return PyInt_FromLong(bits_in_ulong(n));
+ return PyInt_FromLong(bits_in_ulong(n));
}
PyDoc_STRVAR(int_bit_length_doc,
@@ -1287,44 +1287,44 @@ Number of bits necessary to represent self in binary.\n\
static PyObject *
int_is_finite(PyObject *v)
{
- Py_RETURN_TRUE;
+ Py_RETURN_TRUE;
}
#endif
static PyMethodDef int_methods[] = {
- {"conjugate", (PyCFunction)int_int, METH_NOARGS,
- "Returns self, the complex conjugate of any int."},
- {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
- int_bit_length_doc},
+ {"conjugate", (PyCFunction)int_int, METH_NOARGS,
+ "Returns self, the complex conjugate of any int."},
+ {"bit_length", (PyCFunction)int_bit_length, METH_NOARGS,
+ int_bit_length_doc},
#if 0
- {"is_finite", (PyCFunction)int_is_finite, METH_NOARGS,
- "Returns always True."},
+ {"is_finite", (PyCFunction)int_is_finite, METH_NOARGS,
+ "Returns always True."},
#endif
- {"__trunc__", (PyCFunction)int_int, METH_NOARGS,
- "Truncating an Integral returns itself."},
- {"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS},
- {"__format__", (PyCFunction)int__format__, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"__trunc__", (PyCFunction)int_int, METH_NOARGS,
+ "Truncating an Integral returns itself."},
+ {"__getnewargs__", (PyCFunction)int_getnewargs, METH_NOARGS},
+ {"__format__", (PyCFunction)int__format__, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static PyGetSetDef int_getset[] = {
- {"real",
- (getter)int_int, (setter)NULL,
- "the real part of a complex number",
- NULL},
- {"imag",
- (getter)int_get0, (setter)NULL,
- "the imaginary part of a complex number",
- NULL},
- {"numerator",
- (getter)int_int, (setter)NULL,
- "the numerator of a rational number in lowest terms",
- NULL},
- {"denominator",
- (getter)int_get1, (setter)NULL,
- "the denominator of a rational number in lowest terms",
- NULL},
- {NULL} /* Sentinel */
+ {"real",
+ (getter)int_int, (setter)NULL,
+ "the real part of a complex number",
+ NULL},
+ {"imag",
+ (getter)int_get0, (setter)NULL,
+ "the imaginary part of a complex number",
+ NULL},
+ {"numerator",
+ (getter)int_int, (setter)NULL,
+ "the numerator of a rational number in lowest terms",
+ NULL},
+ {"denominator",
+ (getter)int_get1, (setter)NULL,
+ "the denominator of a rational number in lowest terms",
+ NULL},
+ {NULL} /* Sentinel */
};
PyDoc_STRVAR(int_doc,
@@ -1339,212 +1339,212 @@ string content. If the argument is outside the integer range a\n\
long object will be returned instead.");
static PyNumberMethods int_as_number = {
- (binaryfunc)int_add, /*nb_add*/
- (binaryfunc)int_sub, /*nb_subtract*/
- (binaryfunc)int_mul, /*nb_multiply*/
- (binaryfunc)int_classic_div, /*nb_divide*/
- (binaryfunc)int_mod, /*nb_remainder*/
- (binaryfunc)int_divmod, /*nb_divmod*/
- (ternaryfunc)int_pow, /*nb_power*/
- (unaryfunc)int_neg, /*nb_negative*/
- (unaryfunc)int_int, /*nb_positive*/
- (unaryfunc)int_abs, /*nb_absolute*/
- (inquiry)int_nonzero, /*nb_nonzero*/
- (unaryfunc)int_invert, /*nb_invert*/
- (binaryfunc)int_lshift, /*nb_lshift*/
- (binaryfunc)int_rshift, /*nb_rshift*/
- (binaryfunc)int_and, /*nb_and*/
- (binaryfunc)int_xor, /*nb_xor*/
- (binaryfunc)int_or, /*nb_or*/
- int_coerce, /*nb_coerce*/
- (unaryfunc)int_int, /*nb_int*/
- (unaryfunc)int_long, /*nb_long*/
- (unaryfunc)int_float, /*nb_float*/
- (unaryfunc)int_oct, /*nb_oct*/
- (unaryfunc)int_hex, /*nb_hex*/
- 0, /*nb_inplace_add*/
- 0, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- 0, /*nb_inplace_and*/
- 0, /*nb_inplace_xor*/
- 0, /*nb_inplace_or*/
- (binaryfunc)int_div, /* nb_floor_divide */
- (binaryfunc)int_true_divide, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
- (unaryfunc)int_int, /* nb_index */
+ (binaryfunc)int_add, /*nb_add*/
+ (binaryfunc)int_sub, /*nb_subtract*/
+ (binaryfunc)int_mul, /*nb_multiply*/
+ (binaryfunc)int_classic_div, /*nb_divide*/
+ (binaryfunc)int_mod, /*nb_remainder*/
+ (binaryfunc)int_divmod, /*nb_divmod*/
+ (ternaryfunc)int_pow, /*nb_power*/
+ (unaryfunc)int_neg, /*nb_negative*/
+ (unaryfunc)int_int, /*nb_positive*/
+ (unaryfunc)int_abs, /*nb_absolute*/
+ (inquiry)int_nonzero, /*nb_nonzero*/
+ (unaryfunc)int_invert, /*nb_invert*/
+ (binaryfunc)int_lshift, /*nb_lshift*/
+ (binaryfunc)int_rshift, /*nb_rshift*/
+ (binaryfunc)int_and, /*nb_and*/
+ (binaryfunc)int_xor, /*nb_xor*/
+ (binaryfunc)int_or, /*nb_or*/
+ int_coerce, /*nb_coerce*/
+ (unaryfunc)int_int, /*nb_int*/
+ (unaryfunc)int_long, /*nb_long*/
+ (unaryfunc)int_float, /*nb_float*/
+ (unaryfunc)int_oct, /*nb_oct*/
+ (unaryfunc)int_hex, /*nb_hex*/
+ 0, /*nb_inplace_add*/
+ 0, /*nb_inplace_subtract*/
+ 0, /*nb_inplace_multiply*/
+ 0, /*nb_inplace_divide*/
+ 0, /*nb_inplace_remainder*/
+ 0, /*nb_inplace_power*/
+ 0, /*nb_inplace_lshift*/
+ 0, /*nb_inplace_rshift*/
+ 0, /*nb_inplace_and*/
+ 0, /*nb_inplace_xor*/
+ 0, /*nb_inplace_or*/
+ (binaryfunc)int_div, /* nb_floor_divide */
+ (binaryfunc)int_true_divide, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
+ (unaryfunc)int_int, /* nb_index */
};
PyTypeObject PyInt_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "int",
- sizeof(PyIntObject),
- 0,
- (destructor)int_dealloc, /* tp_dealloc */
- (printfunc)int_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)int_compare, /* tp_compare */
- (reprfunc)int_to_decimal_string, /* tp_repr */
- &int_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)int_hash, /* tp_hash */
- 0, /* tp_call */
- (reprfunc)int_to_decimal_string, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */
- int_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- int_methods, /* tp_methods */
- 0, /* tp_members */
- int_getset, /* 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 */
- int_new, /* tp_new */
- (freefunc)int_free, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "int",
+ sizeof(PyIntObject),
+ 0,
+ (destructor)int_dealloc, /* tp_dealloc */
+ (printfunc)int_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)int_compare, /* tp_compare */
+ (reprfunc)int_to_decimal_string, /* tp_repr */
+ &int_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)int_hash, /* tp_hash */
+ 0, /* tp_call */
+ (reprfunc)int_to_decimal_string, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_INT_SUBCLASS, /* tp_flags */
+ int_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ int_methods, /* tp_methods */
+ 0, /* tp_members */
+ int_getset, /* 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 */
+ int_new, /* tp_new */
+ (freefunc)int_free, /* tp_free */
};
int
_PyInt_Init(void)
{
- PyIntObject *v;
- int ival;
+ PyIntObject *v;
+ int ival;
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
- for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
- if (!free_list && (free_list = fill_free_list()) == NULL)
- return 0;
- /* PyObject_New is inlined */
- v = free_list;
- free_list = (PyIntObject *)Py_TYPE(v);
- PyObject_INIT(v, &PyInt_Type);
- v->ob_ival = ival;
- small_ints[ival + NSMALLNEGINTS] = v;
- }
+ for (ival = -NSMALLNEGINTS; ival < NSMALLPOSINTS; ival++) {
+ if (!free_list && (free_list = fill_free_list()) == NULL)
+ return 0;
+ /* PyObject_New is inlined */
+ v = free_list;
+ free_list = (PyIntObject *)Py_TYPE(v);
+ PyObject_INIT(v, &PyInt_Type);
+ v->ob_ival = ival;
+ small_ints[ival + NSMALLNEGINTS] = v;
+ }
#endif
- return 1;
+ return 1;
}
int
PyInt_ClearFreeList(void)
{
- PyIntObject *p;
- PyIntBlock *list, *next;
- int i;
- int u; /* remaining unfreed ints per block */
- int freelist_size = 0;
-
- list = block_list;
- block_list = NULL;
- free_list = NULL;
- while (list != NULL) {
- u = 0;
- for (i = 0, p = &list->objects[0];
- i < N_INTOBJECTS;
- i++, p++) {
- if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
- u++;
- }
- next = list->next;
- if (u) {
- list->next = block_list;
- block_list = list;
- for (i = 0, p = &list->objects[0];
- i < N_INTOBJECTS;
- i++, p++) {
- if (!PyInt_CheckExact(p) ||
- p->ob_refcnt == 0) {
- Py_TYPE(p) = (struct _typeobject *)
- free_list;
- free_list = p;
- }
+ PyIntObject *p;
+ PyIntBlock *list, *next;
+ int i;
+ int u; /* remaining unfreed ints per block */
+ int freelist_size = 0;
+
+ list = block_list;
+ block_list = NULL;
+ free_list = NULL;
+ while (list != NULL) {
+ u = 0;
+ for (i = 0, p = &list->objects[0];
+ i < N_INTOBJECTS;
+ i++, p++) {
+ if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
+ u++;
+ }
+ next = list->next;
+ if (u) {
+ list->next = block_list;
+ block_list = list;
+ for (i = 0, p = &list->objects[0];
+ i < N_INTOBJECTS;
+ i++, p++) {
+ if (!PyInt_CheckExact(p) ||
+ p->ob_refcnt == 0) {
+ Py_TYPE(p) = (struct _typeobject *)
+ free_list;
+ free_list = p;
+ }
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
- else if (-NSMALLNEGINTS <= p->ob_ival &&
- p->ob_ival < NSMALLPOSINTS &&
- small_ints[p->ob_ival +
- NSMALLNEGINTS] == NULL) {
- Py_INCREF(p);
- small_ints[p->ob_ival +
- NSMALLNEGINTS] = p;
- }
+ else if (-NSMALLNEGINTS <= p->ob_ival &&
+ p->ob_ival < NSMALLPOSINTS &&
+ small_ints[p->ob_ival +
+ NSMALLNEGINTS] == NULL) {
+ Py_INCREF(p);
+ small_ints[p->ob_ival +
+ NSMALLNEGINTS] = p;
+ }
#endif
- }
- }
- else {
- PyMem_FREE(list);
- }
- freelist_size += u;
- list = next;
- }
-
- return freelist_size;
+ }
+ }
+ else {
+ PyMem_FREE(list);
+ }
+ freelist_size += u;
+ list = next;
+ }
+
+ return freelist_size;
}
void
PyInt_Fini(void)
{
- PyIntObject *p;
- PyIntBlock *list;
- int i;
- int u; /* total unfreed ints per block */
+ PyIntObject *p;
+ PyIntBlock *list;
+ int i;
+ int u; /* total unfreed ints per block */
#if NSMALLNEGINTS + NSMALLPOSINTS > 0
- PyIntObject **q;
-
- i = NSMALLNEGINTS + NSMALLPOSINTS;
- q = small_ints;
- while (--i >= 0) {
- Py_XDECREF(*q);
- *q++ = NULL;
- }
+ PyIntObject **q;
+
+ i = NSMALLNEGINTS + NSMALLPOSINTS;
+ q = small_ints;
+ while (--i >= 0) {
+ Py_XDECREF(*q);
+ *q++ = NULL;
+ }
#endif
- u = PyInt_ClearFreeList();
- if (!Py_VerboseFlag)
- return;
- fprintf(stderr, "# cleanup ints");
- if (!u) {
- fprintf(stderr, "\n");
- }
- else {
- fprintf(stderr,
- ": %d unfreed int%s\n",
- u, u == 1 ? "" : "s");
- }
- if (Py_VerboseFlag > 1) {
- list = block_list;
- while (list != NULL) {
- for (i = 0, p = &list->objects[0];
- i < N_INTOBJECTS;
- i++, p++) {
- if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
- /* XXX(twouters) cast refcount to
- long until %zd is universally
- available
- */
- fprintf(stderr,
- "# <int at %p, refcnt=%ld, val=%ld>\n",
- p, (long)p->ob_refcnt,
- p->ob_ival);
- }
- list = list->next;
- }
- }
+ u = PyInt_ClearFreeList();
+ if (!Py_VerboseFlag)
+ return;
+ fprintf(stderr, "# cleanup ints");
+ if (!u) {
+ fprintf(stderr, "\n");
+ }
+ else {
+ fprintf(stderr,
+ ": %d unfreed int%s\n",
+ u, u == 1 ? "" : "s");
+ }
+ if (Py_VerboseFlag > 1) {
+ list = block_list;
+ while (list != NULL) {
+ for (i = 0, p = &list->objects[0];
+ i < N_INTOBJECTS;
+ i++, p++) {
+ if (PyInt_CheckExact(p) && p->ob_refcnt != 0)
+ /* XXX(twouters) cast refcount to
+ long until %zd is universally
+ available
+ */
+ fprintf(stderr,
+ "# <int at %p, refcnt=%ld, val=%ld>\n",
+ p, (long)p->ob_refcnt,
+ p->ob_ival);
+ }
+ list = list->next;
+ }
+ }
}
diff --git a/Objects/iterobject.c b/Objects/iterobject.c
index 9cebac9..5a9a2dd 100644
--- a/Objects/iterobject.c
+++ b/Objects/iterobject.c
@@ -3,228 +3,228 @@
#include "Python.h"
typedef struct {
- PyObject_HEAD
- long it_index;
- PyObject *it_seq; /* Set to NULL when iterator is exhausted */
+ PyObject_HEAD
+ long it_index;
+ PyObject *it_seq; /* Set to NULL when iterator is exhausted */
} seqiterobject;
PyObject *
PySeqIter_New(PyObject *seq)
{
- seqiterobject *it;
-
- if (!PySequence_Check(seq)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- it = PyObject_GC_New(seqiterobject, &PySeqIter_Type);
- if (it == NULL)
- return NULL;
- it->it_index = 0;
- Py_INCREF(seq);
- it->it_seq = seq;
- _PyObject_GC_TRACK(it);
- return (PyObject *)it;
+ seqiterobject *it;
+
+ if (!PySequence_Check(seq)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ it = PyObject_GC_New(seqiterobject, &PySeqIter_Type);
+ if (it == NULL)
+ return NULL;
+ it->it_index = 0;
+ Py_INCREF(seq);
+ it->it_seq = seq;
+ _PyObject_GC_TRACK(it);
+ return (PyObject *)it;
}
static void
iter_dealloc(seqiterobject *it)
{
- _PyObject_GC_UNTRACK(it);
- Py_XDECREF(it->it_seq);
- PyObject_GC_Del(it);
+ _PyObject_GC_UNTRACK(it);
+ Py_XDECREF(it->it_seq);
+ PyObject_GC_Del(it);
}
static int
iter_traverse(seqiterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->it_seq);
- return 0;
+ Py_VISIT(it->it_seq);
+ return 0;
}
static PyObject *
iter_iternext(PyObject *iterator)
{
- seqiterobject *it;
- PyObject *seq;
- PyObject *result;
-
- assert(PySeqIter_Check(iterator));
- it = (seqiterobject *)iterator;
- seq = it->it_seq;
- if (seq == NULL)
- return NULL;
-
- result = PySequence_GetItem(seq, it->it_index);
- if (result != NULL) {
- it->it_index++;
- return result;
- }
- if (PyErr_ExceptionMatches(PyExc_IndexError) ||
- PyErr_ExceptionMatches(PyExc_StopIteration))
- {
- PyErr_Clear();
- Py_DECREF(seq);
- it->it_seq = NULL;
- }
- return NULL;
+ seqiterobject *it;
+ PyObject *seq;
+ PyObject *result;
+
+ assert(PySeqIter_Check(iterator));
+ it = (seqiterobject *)iterator;
+ seq = it->it_seq;
+ if (seq == NULL)
+ return NULL;
+
+ result = PySequence_GetItem(seq, it->it_index);
+ if (result != NULL) {
+ it->it_index++;
+ return result;
+ }
+ if (PyErr_ExceptionMatches(PyExc_IndexError) ||
+ PyErr_ExceptionMatches(PyExc_StopIteration))
+ {
+ PyErr_Clear();
+ Py_DECREF(seq);
+ it->it_seq = NULL;
+ }
+ return NULL;
}
static PyObject *
iter_len(seqiterobject *it)
{
- Py_ssize_t seqsize, len;
-
- if (it->it_seq) {
- seqsize = PySequence_Size(it->it_seq);
- if (seqsize == -1)
- return NULL;
- len = seqsize - it->it_index;
- if (len >= 0)
- return PyInt_FromSsize_t(len);
- }
- return PyInt_FromLong(0);
+ Py_ssize_t seqsize, len;
+
+ if (it->it_seq) {
+ seqsize = PySequence_Size(it->it_seq);
+ if (seqsize == -1)
+ return NULL;
+ len = seqsize - it->it_index;
+ if (len >= 0)
+ return PyInt_FromSsize_t(len);
+ }
+ return PyInt_FromLong(0);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef seqiter_methods[] = {
- {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)iter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PySeqIter_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "iterator", /* tp_name */
- sizeof(seqiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)iter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)iter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- iter_iternext, /* tp_iternext */
- seqiter_methods, /* tp_methods */
- 0, /* tp_members */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "iterator", /* tp_name */
+ sizeof(seqiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)iter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)iter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ iter_iternext, /* tp_iternext */
+ seqiter_methods, /* tp_methods */
+ 0, /* tp_members */
};
/* -------------------------------------- */
typedef struct {
- PyObject_HEAD
- PyObject *it_callable; /* Set to NULL when iterator is exhausted */
- PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */
+ PyObject_HEAD
+ PyObject *it_callable; /* Set to NULL when iterator is exhausted */
+ PyObject *it_sentinel; /* Set to NULL when iterator is exhausted */
} calliterobject;
PyObject *
PyCallIter_New(PyObject *callable, PyObject *sentinel)
{
- calliterobject *it;
- it = PyObject_GC_New(calliterobject, &PyCallIter_Type);
- if (it == NULL)
- return NULL;
- Py_INCREF(callable);
- it->it_callable = callable;
- Py_INCREF(sentinel);
- it->it_sentinel = sentinel;
- _PyObject_GC_TRACK(it);
- return (PyObject *)it;
+ calliterobject *it;
+ it = PyObject_GC_New(calliterobject, &PyCallIter_Type);
+ if (it == NULL)
+ return NULL;
+ Py_INCREF(callable);
+ it->it_callable = callable;
+ Py_INCREF(sentinel);
+ it->it_sentinel = sentinel;
+ _PyObject_GC_TRACK(it);
+ return (PyObject *)it;
}
static void
calliter_dealloc(calliterobject *it)
{
- _PyObject_GC_UNTRACK(it);
- Py_XDECREF(it->it_callable);
- Py_XDECREF(it->it_sentinel);
- PyObject_GC_Del(it);
+ _PyObject_GC_UNTRACK(it);
+ Py_XDECREF(it->it_callable);
+ Py_XDECREF(it->it_sentinel);
+ PyObject_GC_Del(it);
}
static int
calliter_traverse(calliterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->it_callable);
- Py_VISIT(it->it_sentinel);
- return 0;
+ Py_VISIT(it->it_callable);
+ Py_VISIT(it->it_sentinel);
+ return 0;
}
static PyObject *
calliter_iternext(calliterobject *it)
{
- if (it->it_callable != NULL) {
- PyObject *args = PyTuple_New(0);
- PyObject *result;
- if (args == NULL)
- return NULL;
- result = PyObject_Call(it->it_callable, args, NULL);
- Py_DECREF(args);
- if (result != NULL) {
- int ok;
- ok = PyObject_RichCompareBool(result,
- it->it_sentinel,
- Py_EQ);
- if (ok == 0)
- return result; /* Common case, fast path */
- Py_DECREF(result);
- if (ok > 0) {
- Py_CLEAR(it->it_callable);
- Py_CLEAR(it->it_sentinel);
- }
- }
- else if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
- PyErr_Clear();
- Py_CLEAR(it->it_callable);
- Py_CLEAR(it->it_sentinel);
- }
- }
- return NULL;
+ if (it->it_callable != NULL) {
+ PyObject *args = PyTuple_New(0);
+ PyObject *result;
+ if (args == NULL)
+ return NULL;
+ result = PyObject_Call(it->it_callable, args, NULL);
+ Py_DECREF(args);
+ if (result != NULL) {
+ int ok;
+ ok = PyObject_RichCompareBool(result,
+ it->it_sentinel,
+ Py_EQ);
+ if (ok == 0)
+ return result; /* Common case, fast path */
+ Py_DECREF(result);
+ if (ok > 0) {
+ Py_CLEAR(it->it_callable);
+ Py_CLEAR(it->it_sentinel);
+ }
+ }
+ else if (PyErr_ExceptionMatches(PyExc_StopIteration)) {
+ PyErr_Clear();
+ Py_CLEAR(it->it_callable);
+ Py_CLEAR(it->it_sentinel);
+ }
+ }
+ return NULL;
}
PyTypeObject PyCallIter_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "callable-iterator", /* tp_name */
- sizeof(calliterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)calliter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)calliter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)calliter_iternext, /* tp_iternext */
- 0, /* tp_methods */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "callable-iterator", /* tp_name */
+ sizeof(calliterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)calliter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)calliter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)calliter_iternext, /* tp_iternext */
+ 0, /* tp_methods */
};
diff --git a/Objects/listobject.c b/Objects/listobject.c
index 8610085..9704d8d 100644
--- a/Objects/listobject.c
+++ b/Objects/listobject.c
@@ -5,7 +5,7 @@
#ifdef STDC_HEADERS
#include <stddef.h>
#else
-#include <sys/types.h> /* For size_t */
+#include <sys/types.h> /* For size_t */
#endif
/* Ensure ob_item has room for at least newsize elements, and set
@@ -24,52 +24,52 @@
static int
list_resize(PyListObject *self, Py_ssize_t newsize)
{
- PyObject **items;
- size_t new_allocated;
- Py_ssize_t allocated = self->allocated;
-
- /* Bypass realloc() when a previous overallocation is large enough
- to accommodate the newsize. If the newsize falls lower than half
- the allocated size, then proceed with the realloc() to shrink the list.
- */
- if (allocated >= newsize && newsize >= (allocated >> 1)) {
- assert(self->ob_item != NULL || newsize == 0);
- Py_SIZE(self) = newsize;
- return 0;
- }
-
- /* This over-allocates proportional to the list size, making room
- * for additional growth. The over-allocation is mild, but is
- * enough to give linear-time amortized behavior over a long
- * sequence of appends() in the presence of a poorly-performing
- * system realloc().
- * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
- */
- new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
-
- /* check for integer overflow */
- if (new_allocated > PY_SIZE_MAX - newsize) {
- PyErr_NoMemory();
- return -1;
- } else {
- new_allocated += newsize;
- }
-
- if (newsize == 0)
- new_allocated = 0;
- items = self->ob_item;
- if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
- PyMem_RESIZE(items, PyObject *, new_allocated);
- else
- items = NULL;
- if (items == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- self->ob_item = items;
- Py_SIZE(self) = newsize;
- self->allocated = new_allocated;
- return 0;
+ PyObject **items;
+ size_t new_allocated;
+ Py_ssize_t allocated = self->allocated;
+
+ /* Bypass realloc() when a previous overallocation is large enough
+ to accommodate the newsize. If the newsize falls lower than half
+ the allocated size, then proceed with the realloc() to shrink the list.
+ */
+ if (allocated >= newsize && newsize >= (allocated >> 1)) {
+ assert(self->ob_item != NULL || newsize == 0);
+ Py_SIZE(self) = newsize;
+ return 0;
+ }
+
+ /* This over-allocates proportional to the list size, making room
+ * for additional growth. The over-allocation is mild, but is
+ * enough to give linear-time amortized behavior over a long
+ * sequence of appends() in the presence of a poorly-performing
+ * system realloc().
+ * The growth pattern is: 0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
+ */
+ new_allocated = (newsize >> 3) + (newsize < 9 ? 3 : 6);
+
+ /* check for integer overflow */
+ if (new_allocated > PY_SIZE_MAX - newsize) {
+ PyErr_NoMemory();
+ return -1;
+ } else {
+ new_allocated += newsize;
+ }
+
+ if (newsize == 0)
+ new_allocated = 0;
+ items = self->ob_item;
+ if (new_allocated <= ((~(size_t)0) / sizeof(PyObject *)))
+ PyMem_RESIZE(items, PyObject *, new_allocated);
+ else
+ items = NULL;
+ if (items == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ self->ob_item = items;
+ Py_SIZE(self) = newsize;
+ self->allocated = new_allocated;
+ return 0;
}
/* Debug statistic to compare allocations with reuse through the free list */
@@ -81,12 +81,12 @@ static size_t count_reuse = 0;
static void
show_alloc(void)
{
- fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
- count_alloc);
- fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
- "d\n", count_reuse);
- fprintf(stderr, "%.2f%% reuse rate\n\n",
- (100.0*count_reuse/(count_alloc+count_reuse)));
+ fprintf(stderr, "List allocations: %" PY_FORMAT_SIZE_T "d\n",
+ count_alloc);
+ fprintf(stderr, "List reuse through freelist: %" PY_FORMAT_SIZE_T
+ "d\n", count_reuse);
+ fprintf(stderr, "%.2f%% reuse rate\n\n",
+ (100.0*count_reuse/(count_alloc+count_reuse)));
}
#endif
@@ -100,77 +100,77 @@ static int numfree = 0;
void
PyList_Fini(void)
{
- PyListObject *op;
+ PyListObject *op;
- while (numfree) {
- op = free_list[--numfree];
- assert(PyList_CheckExact(op));
- PyObject_GC_Del(op);
- }
+ while (numfree) {
+ op = free_list[--numfree];
+ assert(PyList_CheckExact(op));
+ PyObject_GC_Del(op);
+ }
}
PyObject *
PyList_New(Py_ssize_t size)
{
- PyListObject *op;
- size_t nbytes;
+ PyListObject *op;
+ size_t nbytes;
#ifdef SHOW_ALLOC_COUNT
- static int initialized = 0;
- if (!initialized) {
- Py_AtExit(show_alloc);
- initialized = 1;
- }
+ static int initialized = 0;
+ if (!initialized) {
+ Py_AtExit(show_alloc);
+ initialized = 1;
+ }
#endif
- if (size < 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
- /* Check for overflow without an actual overflow,
- * which can cause compiler to optimise out */
- if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
- return PyErr_NoMemory();
- nbytes = size * sizeof(PyObject *);
- if (numfree) {
- numfree--;
- op = free_list[numfree];
- _Py_NewReference((PyObject *)op);
+ if (size < 0) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ /* Check for overflow without an actual overflow,
+ * which can cause compiler to optimise out */
+ if ((size_t)size > PY_SIZE_MAX / sizeof(PyObject *))
+ return PyErr_NoMemory();
+ nbytes = size * sizeof(PyObject *);
+ if (numfree) {
+ numfree--;
+ op = free_list[numfree];
+ _Py_NewReference((PyObject *)op);
#ifdef SHOW_ALLOC_COUNT
- count_reuse++;
+ count_reuse++;
#endif
- } else {
- op = PyObject_GC_New(PyListObject, &PyList_Type);
- if (op == NULL)
- return NULL;
+ } else {
+ op = PyObject_GC_New(PyListObject, &PyList_Type);
+ if (op == NULL)
+ return NULL;
#ifdef SHOW_ALLOC_COUNT
- count_alloc++;
+ count_alloc++;
#endif
- }
- if (size <= 0)
- op->ob_item = NULL;
- else {
- op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
- if (op->ob_item == NULL) {
- Py_DECREF(op);
- return PyErr_NoMemory();
- }
- memset(op->ob_item, 0, nbytes);
- }
- Py_SIZE(op) = size;
- op->allocated = size;
- _PyObject_GC_TRACK(op);
- return (PyObject *) op;
+ }
+ if (size <= 0)
+ op->ob_item = NULL;
+ else {
+ op->ob_item = (PyObject **) PyMem_MALLOC(nbytes);
+ if (op->ob_item == NULL) {
+ Py_DECREF(op);
+ return PyErr_NoMemory();
+ }
+ memset(op->ob_item, 0, nbytes);
+ }
+ Py_SIZE(op) = size;
+ op->allocated = size;
+ _PyObject_GC_TRACK(op);
+ return (PyObject *) op;
}
Py_ssize_t
PyList_Size(PyObject *op)
{
- if (!PyList_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- else
- return Py_SIZE(op);
+ if (!PyList_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ else
+ return Py_SIZE(op);
}
static PyObject *indexerr = NULL;
@@ -178,117 +178,117 @@ static PyObject *indexerr = NULL;
PyObject *
PyList_GetItem(PyObject *op, Py_ssize_t i)
{
- if (!PyList_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- if (i < 0 || i >= Py_SIZE(op)) {
- if (indexerr == NULL) {
- indexerr = PyString_FromString(
- "list index out of range");
- if (indexerr == NULL)
- return NULL;
- }
- PyErr_SetObject(PyExc_IndexError, indexerr);
- return NULL;
- }
- return ((PyListObject *)op) -> ob_item[i];
+ if (!PyList_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ if (i < 0 || i >= Py_SIZE(op)) {
+ if (indexerr == NULL) {
+ indexerr = PyString_FromString(
+ "list index out of range");
+ if (indexerr == NULL)
+ return NULL;
+ }
+ PyErr_SetObject(PyExc_IndexError, indexerr);
+ return NULL;
+ }
+ return ((PyListObject *)op) -> ob_item[i];
}
int
PyList_SetItem(register PyObject *op, register Py_ssize_t i,
register PyObject *newitem)
{
- register PyObject *olditem;
- register PyObject **p;
- if (!PyList_Check(op)) {
- Py_XDECREF(newitem);
- PyErr_BadInternalCall();
- return -1;
- }
- if (i < 0 || i >= Py_SIZE(op)) {
- Py_XDECREF(newitem);
- PyErr_SetString(PyExc_IndexError,
- "list assignment index out of range");
- return -1;
- }
- p = ((PyListObject *)op) -> ob_item + i;
- olditem = *p;
- *p = newitem;
- Py_XDECREF(olditem);
- return 0;
+ register PyObject *olditem;
+ register PyObject **p;
+ if (!PyList_Check(op)) {
+ Py_XDECREF(newitem);
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (i < 0 || i >= Py_SIZE(op)) {
+ Py_XDECREF(newitem);
+ PyErr_SetString(PyExc_IndexError,
+ "list assignment index out of range");
+ return -1;
+ }
+ p = ((PyListObject *)op) -> ob_item + i;
+ olditem = *p;
+ *p = newitem;
+ Py_XDECREF(olditem);
+ return 0;
}
static int
ins1(PyListObject *self, Py_ssize_t where, PyObject *v)
{
- Py_ssize_t i, n = Py_SIZE(self);
- PyObject **items;
- if (v == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (n == PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "cannot add more objects to list");
- return -1;
- }
-
- if (list_resize(self, n+1) == -1)
- return -1;
-
- if (where < 0) {
- where += n;
- if (where < 0)
- where = 0;
- }
- if (where > n)
- where = n;
- items = self->ob_item;
- for (i = n; --i >= where; )
- items[i+1] = items[i];
- Py_INCREF(v);
- items[where] = v;
- return 0;
+ Py_ssize_t i, n = Py_SIZE(self);
+ PyObject **items;
+ if (v == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (n == PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot add more objects to list");
+ return -1;
+ }
+
+ if (list_resize(self, n+1) == -1)
+ return -1;
+
+ if (where < 0) {
+ where += n;
+ if (where < 0)
+ where = 0;
+ }
+ if (where > n)
+ where = n;
+ items = self->ob_item;
+ for (i = n; --i >= where; )
+ items[i+1] = items[i];
+ Py_INCREF(v);
+ items[where] = v;
+ return 0;
}
int
PyList_Insert(PyObject *op, Py_ssize_t where, PyObject *newitem)
{
- if (!PyList_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return ins1((PyListObject *)op, where, newitem);
+ if (!PyList_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return ins1((PyListObject *)op, where, newitem);
}
static int
app1(PyListObject *self, PyObject *v)
{
- Py_ssize_t n = PyList_GET_SIZE(self);
+ Py_ssize_t n = PyList_GET_SIZE(self);
- assert (v != NULL);
- if (n == PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "cannot add more objects to list");
- return -1;
- }
+ assert (v != NULL);
+ if (n == PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot add more objects to list");
+ return -1;
+ }
- if (list_resize(self, n+1) == -1)
- return -1;
+ if (list_resize(self, n+1) == -1)
+ return -1;
- Py_INCREF(v);
- PyList_SET_ITEM(self, n, v);
- return 0;
+ Py_INCREF(v);
+ PyList_SET_ITEM(self, n, v);
+ return 0;
}
int
PyList_Append(PyObject *op, PyObject *newitem)
{
- if (PyList_Check(op) && (newitem != NULL))
- return app1((PyListObject *)op, newitem);
- PyErr_BadInternalCall();
- return -1;
+ if (PyList_Check(op) && (newitem != NULL))
+ return app1((PyListObject *)op, newitem);
+ PyErr_BadInternalCall();
+ return -1;
}
/* Methods */
@@ -296,312 +296,312 @@ PyList_Append(PyObject *op, PyObject *newitem)
static void
list_dealloc(PyListObject *op)
{
- Py_ssize_t i;
- PyObject_GC_UnTrack(op);
- Py_TRASHCAN_SAFE_BEGIN(op)
- if (op->ob_item != NULL) {
- /* Do it backwards, for Christian Tismer.
- There's a simple test case where somehow this reduces
- thrashing when a *very* large list is created and
- immediately deleted. */
- i = Py_SIZE(op);
- while (--i >= 0) {
- Py_XDECREF(op->ob_item[i]);
- }
- PyMem_FREE(op->ob_item);
- }
- if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
- free_list[numfree++] = op;
- else
- Py_TYPE(op)->tp_free((PyObject *)op);
- Py_TRASHCAN_SAFE_END(op)
+ Py_ssize_t i;
+ PyObject_GC_UnTrack(op);
+ Py_TRASHCAN_SAFE_BEGIN(op)
+ if (op->ob_item != NULL) {
+ /* Do it backwards, for Christian Tismer.
+ There's a simple test case where somehow this reduces
+ thrashing when a *very* large list is created and
+ immediately deleted. */
+ i = Py_SIZE(op);
+ while (--i >= 0) {
+ Py_XDECREF(op->ob_item[i]);
+ }
+ PyMem_FREE(op->ob_item);
+ }
+ if (numfree < PyList_MAXFREELIST && PyList_CheckExact(op))
+ free_list[numfree++] = op;
+ else
+ Py_TYPE(op)->tp_free((PyObject *)op);
+ Py_TRASHCAN_SAFE_END(op)
}
static int
list_print(PyListObject *op, FILE *fp, int flags)
{
- int rc;
- Py_ssize_t i;
- PyObject *item;
-
- rc = Py_ReprEnter((PyObject*)op);
- if (rc != 0) {
- if (rc < 0)
- return rc;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "[...]");
- Py_END_ALLOW_THREADS
- return 0;
- }
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "[");
- Py_END_ALLOW_THREADS
- for (i = 0; i < Py_SIZE(op); i++) {
- item = op->ob_item[i];
- Py_INCREF(item);
- if (i > 0) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ", ");
- Py_END_ALLOW_THREADS
- }
- if (PyObject_Print(item, fp, 0) != 0) {
- Py_DECREF(item);
- Py_ReprLeave((PyObject *)op);
- return -1;
- }
- Py_DECREF(item);
- }
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "]");
- Py_END_ALLOW_THREADS
- Py_ReprLeave((PyObject *)op);
- return 0;
+ int rc;
+ Py_ssize_t i;
+ PyObject *item;
+
+ rc = Py_ReprEnter((PyObject*)op);
+ if (rc != 0) {
+ if (rc < 0)
+ return rc;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "[...]");
+ Py_END_ALLOW_THREADS
+ return 0;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "[");
+ Py_END_ALLOW_THREADS
+ for (i = 0; i < Py_SIZE(op); i++) {
+ item = op->ob_item[i];
+ Py_INCREF(item);
+ if (i > 0) {
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ", ");
+ Py_END_ALLOW_THREADS
+ }
+ if (PyObject_Print(item, fp, 0) != 0) {
+ Py_DECREF(item);
+ Py_ReprLeave((PyObject *)op);
+ return -1;
+ }
+ Py_DECREF(item);
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "]");
+ Py_END_ALLOW_THREADS
+ Py_ReprLeave((PyObject *)op);
+ return 0;
}
static PyObject *
list_repr(PyListObject *v)
{
- Py_ssize_t i;
- PyObject *s, *temp;
- PyObject *pieces = NULL, *result = NULL;
-
- i = Py_ReprEnter((PyObject*)v);
- if (i != 0) {
- return i > 0 ? PyString_FromString("[...]") : NULL;
- }
-
- if (Py_SIZE(v) == 0) {
- result = PyString_FromString("[]");
- goto Done;
- }
-
- pieces = PyList_New(0);
- if (pieces == NULL)
- goto Done;
-
- /* Do repr() on each element. Note that this may mutate the list,
- so must refetch the list size on each iteration. */
- for (i = 0; i < Py_SIZE(v); ++i) {
- int status;
- if (Py_EnterRecursiveCall(" while getting the repr of a list"))
- goto Done;
- s = PyObject_Repr(v->ob_item[i]);
- Py_LeaveRecursiveCall();
- if (s == NULL)
- goto Done;
- status = PyList_Append(pieces, s);
- Py_DECREF(s); /* append created a new ref */
- if (status < 0)
- goto Done;
- }
-
- /* Add "[]" decorations to the first and last items. */
- assert(PyList_GET_SIZE(pieces) > 0);
- s = PyString_FromString("[");
- if (s == NULL)
- goto Done;
- temp = PyList_GET_ITEM(pieces, 0);
- PyString_ConcatAndDel(&s, temp);
- PyList_SET_ITEM(pieces, 0, s);
- if (s == NULL)
- goto Done;
-
- s = PyString_FromString("]");
- if (s == NULL)
- goto Done;
- temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
- PyString_ConcatAndDel(&temp, s);
- PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
- if (temp == NULL)
- goto Done;
-
- /* Paste them all together with ", " between. */
- s = PyString_FromString(", ");
- if (s == NULL)
- goto Done;
- result = _PyString_Join(s, pieces);
- Py_DECREF(s);
+ Py_ssize_t i;
+ PyObject *s, *temp;
+ PyObject *pieces = NULL, *result = NULL;
+
+ i = Py_ReprEnter((PyObject*)v);
+ if (i != 0) {
+ return i > 0 ? PyString_FromString("[...]") : NULL;
+ }
+
+ if (Py_SIZE(v) == 0) {
+ result = PyString_FromString("[]");
+ goto Done;
+ }
+
+ pieces = PyList_New(0);
+ if (pieces == NULL)
+ goto Done;
+
+ /* Do repr() on each element. Note that this may mutate the list,
+ so must refetch the list size on each iteration. */
+ for (i = 0; i < Py_SIZE(v); ++i) {
+ int status;
+ if (Py_EnterRecursiveCall(" while getting the repr of a list"))
+ goto Done;
+ s = PyObject_Repr(v->ob_item[i]);
+ Py_LeaveRecursiveCall();
+ if (s == NULL)
+ goto Done;
+ status = PyList_Append(pieces, s);
+ Py_DECREF(s); /* append created a new ref */
+ if (status < 0)
+ goto Done;
+ }
+
+ /* Add "[]" decorations to the first and last items. */
+ assert(PyList_GET_SIZE(pieces) > 0);
+ s = PyString_FromString("[");
+ if (s == NULL)
+ goto Done;
+ temp = PyList_GET_ITEM(pieces, 0);
+ PyString_ConcatAndDel(&s, temp);
+ PyList_SET_ITEM(pieces, 0, s);
+ if (s == NULL)
+ goto Done;
+
+ s = PyString_FromString("]");
+ if (s == NULL)
+ goto Done;
+ temp = PyList_GET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1);
+ PyString_ConcatAndDel(&temp, s);
+ PyList_SET_ITEM(pieces, PyList_GET_SIZE(pieces) - 1, temp);
+ if (temp == NULL)
+ goto Done;
+
+ /* Paste them all together with ", " between. */
+ s = PyString_FromString(", ");
+ if (s == NULL)
+ goto Done;
+ result = _PyString_Join(s, pieces);
+ Py_DECREF(s);
Done:
- Py_XDECREF(pieces);
- Py_ReprLeave((PyObject *)v);
- return result;
+ Py_XDECREF(pieces);
+ Py_ReprLeave((PyObject *)v);
+ return result;
}
static Py_ssize_t
list_length(PyListObject *a)
{
- return Py_SIZE(a);
+ return Py_SIZE(a);
}
static int
list_contains(PyListObject *a, PyObject *el)
{
- Py_ssize_t i;
- int cmp;
+ Py_ssize_t i;
+ int cmp;
- for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
- cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
- Py_EQ);
- return cmp;
+ for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
+ cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
+ Py_EQ);
+ return cmp;
}
static PyObject *
list_item(PyListObject *a, Py_ssize_t i)
{
- if (i < 0 || i >= Py_SIZE(a)) {
- if (indexerr == NULL) {
- indexerr = PyString_FromString(
- "list index out of range");
- if (indexerr == NULL)
- return NULL;
- }
- PyErr_SetObject(PyExc_IndexError, indexerr);
- return NULL;
- }
- Py_INCREF(a->ob_item[i]);
- return a->ob_item[i];
+ if (i < 0 || i >= Py_SIZE(a)) {
+ if (indexerr == NULL) {
+ indexerr = PyString_FromString(
+ "list index out of range");
+ if (indexerr == NULL)
+ return NULL;
+ }
+ PyErr_SetObject(PyExc_IndexError, indexerr);
+ return NULL;
+ }
+ Py_INCREF(a->ob_item[i]);
+ return a->ob_item[i];
}
static PyObject *
list_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- PyListObject *np;
- PyObject **src, **dest;
- Py_ssize_t i, len;
- if (ilow < 0)
- ilow = 0;
- else if (ilow > Py_SIZE(a))
- ilow = Py_SIZE(a);
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
- len = ihigh - ilow;
- np = (PyListObject *) PyList_New(len);
- if (np == NULL)
- return NULL;
-
- src = a->ob_item + ilow;
- dest = np->ob_item;
- for (i = 0; i < len; i++) {
- PyObject *v = src[i];
- Py_INCREF(v);
- dest[i] = v;
- }
- return (PyObject *)np;
+ PyListObject *np;
+ PyObject **src, **dest;
+ Py_ssize_t i, len;
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > Py_SIZE(a))
+ ilow = Py_SIZE(a);
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+ len = ihigh - ilow;
+ np = (PyListObject *) PyList_New(len);
+ if (np == NULL)
+ return NULL;
+
+ src = a->ob_item + ilow;
+ dest = np->ob_item;
+ for (i = 0; i < len; i++) {
+ PyObject *v = src[i];
+ Py_INCREF(v);
+ dest[i] = v;
+ }
+ return (PyObject *)np;
}
PyObject *
PyList_GetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh)
{
- if (!PyList_Check(a)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return list_slice((PyListObject *)a, ilow, ihigh);
+ if (!PyList_Check(a)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return list_slice((PyListObject *)a, ilow, ihigh);
}
static PyObject *
list_concat(PyListObject *a, PyObject *bb)
{
- Py_ssize_t size;
- Py_ssize_t i;
- PyObject **src, **dest;
- PyListObject *np;
- if (!PyList_Check(bb)) {
- PyErr_Format(PyExc_TypeError,
- "can only concatenate list (not \"%.200s\") to list",
- bb->ob_type->tp_name);
- return NULL;
- }
+ Py_ssize_t size;
+ Py_ssize_t i;
+ PyObject **src, **dest;
+ PyListObject *np;
+ if (!PyList_Check(bb)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only concatenate list (not \"%.200s\") to list",
+ bb->ob_type->tp_name);
+ return NULL;
+ }
#define b ((PyListObject *)bb)
- size = Py_SIZE(a) + Py_SIZE(b);
- if (size < 0)
- return PyErr_NoMemory();
- np = (PyListObject *) PyList_New(size);
- if (np == NULL) {
- return NULL;
- }
- src = a->ob_item;
- dest = np->ob_item;
- for (i = 0; i < Py_SIZE(a); i++) {
- PyObject *v = src[i];
- Py_INCREF(v);
- dest[i] = v;
- }
- src = b->ob_item;
- dest = np->ob_item + Py_SIZE(a);
- for (i = 0; i < Py_SIZE(b); i++) {
- PyObject *v = src[i];
- Py_INCREF(v);
- dest[i] = v;
- }
- return (PyObject *)np;
+ size = Py_SIZE(a) + Py_SIZE(b);
+ if (size < 0)
+ return PyErr_NoMemory();
+ np = (PyListObject *) PyList_New(size);
+ if (np == NULL) {
+ return NULL;
+ }
+ src = a->ob_item;
+ dest = np->ob_item;
+ for (i = 0; i < Py_SIZE(a); i++) {
+ PyObject *v = src[i];
+ Py_INCREF(v);
+ dest[i] = v;
+ }
+ src = b->ob_item;
+ dest = np->ob_item + Py_SIZE(a);
+ for (i = 0; i < Py_SIZE(b); i++) {
+ PyObject *v = src[i];
+ Py_INCREF(v);
+ dest[i] = v;
+ }
+ return (PyObject *)np;
#undef b
}
static PyObject *
list_repeat(PyListObject *a, Py_ssize_t n)
{
- Py_ssize_t i, j;
- Py_ssize_t size;
- PyListObject *np;
- PyObject **p, **items;
- PyObject *elem;
- if (n < 0)
- n = 0;
- size = Py_SIZE(a) * n;
- if (n && size/n != Py_SIZE(a))
- return PyErr_NoMemory();
- if (size == 0)
- return PyList_New(0);
- np = (PyListObject *) PyList_New(size);
- if (np == NULL)
- return NULL;
-
- items = np->ob_item;
- if (Py_SIZE(a) == 1) {
- elem = a->ob_item[0];
- for (i = 0; i < n; i++) {
- items[i] = elem;
- Py_INCREF(elem);
- }
- return (PyObject *) np;
- }
- p = np->ob_item;
- items = a->ob_item;
- for (i = 0; i < n; i++) {
- for (j = 0; j < Py_SIZE(a); j++) {
- *p = items[j];
- Py_INCREF(*p);
- p++;
- }
- }
- return (PyObject *) np;
+ Py_ssize_t i, j;
+ Py_ssize_t size;
+ PyListObject *np;
+ PyObject **p, **items;
+ PyObject *elem;
+ if (n < 0)
+ n = 0;
+ size = Py_SIZE(a) * n;
+ if (n && size/n != Py_SIZE(a))
+ return PyErr_NoMemory();
+ if (size == 0)
+ return PyList_New(0);
+ np = (PyListObject *) PyList_New(size);
+ if (np == NULL)
+ return NULL;
+
+ items = np->ob_item;
+ if (Py_SIZE(a) == 1) {
+ elem = a->ob_item[0];
+ for (i = 0; i < n; i++) {
+ items[i] = elem;
+ Py_INCREF(elem);
+ }
+ return (PyObject *) np;
+ }
+ p = np->ob_item;
+ items = a->ob_item;
+ for (i = 0; i < n; i++) {
+ for (j = 0; j < Py_SIZE(a); j++) {
+ *p = items[j];
+ Py_INCREF(*p);
+ p++;
+ }
+ }
+ return (PyObject *) np;
}
static int
list_clear(PyListObject *a)
{
- Py_ssize_t i;
- PyObject **item = a->ob_item;
- if (item != NULL) {
- /* Because XDECREF can recursively invoke operations on
- this list, we make it empty first. */
- i = Py_SIZE(a);
- Py_SIZE(a) = 0;
- a->ob_item = NULL;
- a->allocated = 0;
- while (--i >= 0) {
- Py_XDECREF(item[i]);
- }
- PyMem_FREE(item);
- }
- /* Never fails; the return value can be ignored.
- Note that there is no guarantee that the list is actually empty
- at this point, because XDECREF may have populated it again! */
- return 0;
+ Py_ssize_t i;
+ PyObject **item = a->ob_item;
+ if (item != NULL) {
+ /* Because XDECREF can recursively invoke operations on
+ this list, we make it empty first. */
+ i = Py_SIZE(a);
+ Py_SIZE(a) = 0;
+ a->ob_item = NULL;
+ a->allocated = 0;
+ while (--i >= 0) {
+ Py_XDECREF(item[i]);
+ }
+ PyMem_FREE(item);
+ }
+ /* Never fails; the return value can be ignored.
+ Note that there is no guarantee that the list is actually empty
+ at this point, because XDECREF may have populated it again! */
+ return 0;
}
/* a[ilow:ihigh] = v if v != NULL.
@@ -613,368 +613,368 @@ list_clear(PyListObject *a)
static int
list_ass_slice(PyListObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
- /* Because [X]DECREF can recursively invoke list operations on
- this list, we must postpone all [X]DECREF activity until
- after the list is back in its canonical shape. Therefore
- we must allocate an additional array, 'recycle', into which
- we temporarily copy the items that are deleted from the
- list. :-( */
- PyObject *recycle_on_stack[8];
- PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
- PyObject **item;
- PyObject **vitem = NULL;
- PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
- Py_ssize_t n; /* # of elements in replacement list */
- Py_ssize_t norig; /* # of elements in list getting replaced */
- Py_ssize_t d; /* Change in size */
- Py_ssize_t k;
- size_t s;
- int result = -1; /* guilty until proved innocent */
+ /* Because [X]DECREF can recursively invoke list operations on
+ this list, we must postpone all [X]DECREF activity until
+ after the list is back in its canonical shape. Therefore
+ we must allocate an additional array, 'recycle', into which
+ we temporarily copy the items that are deleted from the
+ list. :-( */
+ PyObject *recycle_on_stack[8];
+ PyObject **recycle = recycle_on_stack; /* will allocate more if needed */
+ PyObject **item;
+ PyObject **vitem = NULL;
+ PyObject *v_as_SF = NULL; /* PySequence_Fast(v) */
+ Py_ssize_t n; /* # of elements in replacement list */
+ Py_ssize_t norig; /* # of elements in list getting replaced */
+ Py_ssize_t d; /* Change in size */
+ Py_ssize_t k;
+ size_t s;
+ int result = -1; /* guilty until proved innocent */
#define b ((PyListObject *)v)
- if (v == NULL)
- n = 0;
- else {
- if (a == b) {
- /* Special case "a[i:j] = a" -- copy b first */
- v = list_slice(b, 0, Py_SIZE(b));
- if (v == NULL)
- return result;
- result = list_ass_slice(a, ilow, ihigh, v);
- Py_DECREF(v);
- return result;
- }
- v_as_SF = PySequence_Fast(v, "can only assign an iterable");
- if(v_as_SF == NULL)
- goto Error;
- n = PySequence_Fast_GET_SIZE(v_as_SF);
- vitem = PySequence_Fast_ITEMS(v_as_SF);
- }
- if (ilow < 0)
- ilow = 0;
- else if (ilow > Py_SIZE(a))
- ilow = Py_SIZE(a);
-
- if (ihigh < ilow)
- ihigh = ilow;
- else if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
-
- norig = ihigh - ilow;
- assert(norig >= 0);
- d = n - norig;
- if (Py_SIZE(a) + d == 0) {
- Py_XDECREF(v_as_SF);
- return list_clear(a);
- }
- item = a->ob_item;
- /* recycle the items that we are about to remove */
- s = norig * sizeof(PyObject *);
- if (s > sizeof(recycle_on_stack)) {
- recycle = (PyObject **)PyMem_MALLOC(s);
- if (recycle == NULL) {
- PyErr_NoMemory();
- goto Error;
- }
- }
- memcpy(recycle, &item[ilow], s);
-
- if (d < 0) { /* Delete -d items */
- memmove(&item[ihigh+d], &item[ihigh],
- (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
- list_resize(a, Py_SIZE(a) + d);
- item = a->ob_item;
- }
- else if (d > 0) { /* Insert d items */
- k = Py_SIZE(a);
- if (list_resize(a, k+d) < 0)
- goto Error;
- item = a->ob_item;
- memmove(&item[ihigh+d], &item[ihigh],
- (k - ihigh)*sizeof(PyObject *));
- }
- for (k = 0; k < n; k++, ilow++) {
- PyObject *w = vitem[k];
- Py_XINCREF(w);
- item[ilow] = w;
- }
- for (k = norig - 1; k >= 0; --k)
- Py_XDECREF(recycle[k]);
- result = 0;
+ if (v == NULL)
+ n = 0;
+ else {
+ if (a == b) {
+ /* Special case "a[i:j] = a" -- copy b first */
+ v = list_slice(b, 0, Py_SIZE(b));
+ if (v == NULL)
+ return result;
+ result = list_ass_slice(a, ilow, ihigh, v);
+ Py_DECREF(v);
+ return result;
+ }
+ v_as_SF = PySequence_Fast(v, "can only assign an iterable");
+ if(v_as_SF == NULL)
+ goto Error;
+ n = PySequence_Fast_GET_SIZE(v_as_SF);
+ vitem = PySequence_Fast_ITEMS(v_as_SF);
+ }
+ if (ilow < 0)
+ ilow = 0;
+ else if (ilow > Py_SIZE(a))
+ ilow = Py_SIZE(a);
+
+ if (ihigh < ilow)
+ ihigh = ilow;
+ else if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+
+ norig = ihigh - ilow;
+ assert(norig >= 0);
+ d = n - norig;
+ if (Py_SIZE(a) + d == 0) {
+ Py_XDECREF(v_as_SF);
+ return list_clear(a);
+ }
+ item = a->ob_item;
+ /* recycle the items that we are about to remove */
+ s = norig * sizeof(PyObject *);
+ if (s > sizeof(recycle_on_stack)) {
+ recycle = (PyObject **)PyMem_MALLOC(s);
+ if (recycle == NULL) {
+ PyErr_NoMemory();
+ goto Error;
+ }
+ }
+ memcpy(recycle, &item[ilow], s);
+
+ if (d < 0) { /* Delete -d items */
+ memmove(&item[ihigh+d], &item[ihigh],
+ (Py_SIZE(a) - ihigh)*sizeof(PyObject *));
+ list_resize(a, Py_SIZE(a) + d);
+ item = a->ob_item;
+ }
+ else if (d > 0) { /* Insert d items */
+ k = Py_SIZE(a);
+ if (list_resize(a, k+d) < 0)
+ goto Error;
+ item = a->ob_item;
+ memmove(&item[ihigh+d], &item[ihigh],
+ (k - ihigh)*sizeof(PyObject *));
+ }
+ for (k = 0; k < n; k++, ilow++) {
+ PyObject *w = vitem[k];
+ Py_XINCREF(w);
+ item[ilow] = w;
+ }
+ for (k = norig - 1; k >= 0; --k)
+ Py_XDECREF(recycle[k]);
+ result = 0;
Error:
- if (recycle != recycle_on_stack)
- PyMem_FREE(recycle);
- Py_XDECREF(v_as_SF);
- return result;
+ if (recycle != recycle_on_stack)
+ PyMem_FREE(recycle);
+ Py_XDECREF(v_as_SF);
+ return result;
#undef b
}
int
PyList_SetSlice(PyObject *a, Py_ssize_t ilow, Py_ssize_t ihigh, PyObject *v)
{
- if (!PyList_Check(a)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
+ if (!PyList_Check(a)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return list_ass_slice((PyListObject *)a, ilow, ihigh, v);
}
static PyObject *
list_inplace_repeat(PyListObject *self, Py_ssize_t n)
{
- PyObject **items;
- Py_ssize_t size, i, j, p;
+ PyObject **items;
+ Py_ssize_t size, i, j, p;
- size = PyList_GET_SIZE(self);
- if (size == 0 || n == 1) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
+ size = PyList_GET_SIZE(self);
+ if (size == 0 || n == 1) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
- if (n < 1) {
- (void)list_clear(self);
- Py_INCREF(self);
- return (PyObject *)self;
- }
+ if (n < 1) {
+ (void)list_clear(self);
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
- if (size > PY_SSIZE_T_MAX / n) {
- return PyErr_NoMemory();
- }
+ if (size > PY_SSIZE_T_MAX / n) {
+ return PyErr_NoMemory();
+ }
- if (list_resize(self, size*n) == -1)
- return NULL;
+ if (list_resize(self, size*n) == -1)
+ return NULL;
- p = size;
- items = self->ob_item;
- for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
- for (j = 0; j < size; j++) {
- PyObject *o = items[j];
- Py_INCREF(o);
- items[p++] = o;
- }
- }
- Py_INCREF(self);
- return (PyObject *)self;
+ p = size;
+ items = self->ob_item;
+ for (i = 1; i < n; i++) { /* Start counting at 1, not 0 */
+ for (j = 0; j < size; j++) {
+ PyObject *o = items[j];
+ Py_INCREF(o);
+ items[p++] = o;
+ }
+ }
+ Py_INCREF(self);
+ return (PyObject *)self;
}
static int
list_ass_item(PyListObject *a, Py_ssize_t i, PyObject *v)
{
- PyObject *old_value;
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError,
- "list assignment index out of range");
- return -1;
- }
- if (v == NULL)
- return list_ass_slice(a, i, i+1, v);
- Py_INCREF(v);
- old_value = a->ob_item[i];
- a->ob_item[i] = v;
- Py_DECREF(old_value);
- return 0;
+ PyObject *old_value;
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError,
+ "list assignment index out of range");
+ return -1;
+ }
+ if (v == NULL)
+ return list_ass_slice(a, i, i+1, v);
+ Py_INCREF(v);
+ old_value = a->ob_item[i];
+ a->ob_item[i] = v;
+ Py_DECREF(old_value);
+ return 0;
}
static PyObject *
listinsert(PyListObject *self, PyObject *args)
{
- Py_ssize_t i;
- PyObject *v;
- if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
- return NULL;
- if (ins1(self, i, v) == 0)
- Py_RETURN_NONE;
- return NULL;
+ Py_ssize_t i;
+ PyObject *v;
+ if (!PyArg_ParseTuple(args, "nO:insert", &i, &v))
+ return NULL;
+ if (ins1(self, i, v) == 0)
+ Py_RETURN_NONE;
+ return NULL;
}
static PyObject *
listappend(PyListObject *self, PyObject *v)
{
- if (app1(self, v) == 0)
- Py_RETURN_NONE;
- return NULL;
+ if (app1(self, v) == 0)
+ Py_RETURN_NONE;
+ return NULL;
}
static PyObject *
listextend(PyListObject *self, PyObject *b)
{
- PyObject *it; /* iter(v) */
- Py_ssize_t m; /* size of self */
- Py_ssize_t n; /* guess for size of b */
- Py_ssize_t mn; /* m + n */
- Py_ssize_t i;
- PyObject *(*iternext)(PyObject *);
-
- /* Special cases:
- 1) lists and tuples which can use PySequence_Fast ops
- 2) extending self to self requires making a copy first
- */
- if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
- PyObject **src, **dest;
- b = PySequence_Fast(b, "argument must be iterable");
- if (!b)
- return NULL;
- n = PySequence_Fast_GET_SIZE(b);
- if (n == 0) {
- /* short circuit when b is empty */
- Py_DECREF(b);
- Py_RETURN_NONE;
- }
- m = Py_SIZE(self);
- if (list_resize(self, m + n) == -1) {
- Py_DECREF(b);
- return NULL;
- }
- /* note that we may still have self == b here for the
- * situation a.extend(a), but the following code works
- * in that case too. Just make sure to resize self
- * before calling PySequence_Fast_ITEMS.
- */
- /* populate the end of self with b's items */
- src = PySequence_Fast_ITEMS(b);
- dest = self->ob_item + m;
- for (i = 0; i < n; i++) {
- PyObject *o = src[i];
- Py_INCREF(o);
- dest[i] = o;
- }
- Py_DECREF(b);
- Py_RETURN_NONE;
- }
-
- it = PyObject_GetIter(b);
- if (it == NULL)
- return NULL;
- iternext = *it->ob_type->tp_iternext;
-
- /* Guess a result list size. */
- n = _PyObject_LengthHint(b, 8);
- if (n == -1) {
- Py_DECREF(it);
- return NULL;
- }
- m = Py_SIZE(self);
- mn = m + n;
- if (mn >= m) {
- /* Make room. */
- if (list_resize(self, mn) == -1)
- goto error;
- /* Make the list sane again. */
- Py_SIZE(self) = m;
- }
- /* Else m + n overflowed; on the chance that n lied, and there really
- * is enough room, ignore it. If n was telling the truth, we'll
- * eventually run out of memory during the loop.
- */
-
- /* Run iterator to exhaustion. */
- for (;;) {
- PyObject *item = iternext(it);
- if (item == NULL) {
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- goto error;
- }
- break;
- }
- if (Py_SIZE(self) < self->allocated) {
- /* steals ref */
- PyList_SET_ITEM(self, Py_SIZE(self), item);
- ++Py_SIZE(self);
- }
- else {
- int status = app1(self, item);
- Py_DECREF(item); /* append creates a new ref */
- if (status < 0)
- goto error;
- }
- }
-
- /* Cut back result list if initial guess was too large. */
- if (Py_SIZE(self) < self->allocated)
- list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
-
- Py_DECREF(it);
- Py_RETURN_NONE;
+ PyObject *it; /* iter(v) */
+ Py_ssize_t m; /* size of self */
+ Py_ssize_t n; /* guess for size of b */
+ Py_ssize_t mn; /* m + n */
+ Py_ssize_t i;
+ PyObject *(*iternext)(PyObject *);
+
+ /* Special cases:
+ 1) lists and tuples which can use PySequence_Fast ops
+ 2) extending self to self requires making a copy first
+ */
+ if (PyList_CheckExact(b) || PyTuple_CheckExact(b) || (PyObject *)self == b) {
+ PyObject **src, **dest;
+ b = PySequence_Fast(b, "argument must be iterable");
+ if (!b)
+ return NULL;
+ n = PySequence_Fast_GET_SIZE(b);
+ if (n == 0) {
+ /* short circuit when b is empty */
+ Py_DECREF(b);
+ Py_RETURN_NONE;
+ }
+ m = Py_SIZE(self);
+ if (list_resize(self, m + n) == -1) {
+ Py_DECREF(b);
+ return NULL;
+ }
+ /* note that we may still have self == b here for the
+ * situation a.extend(a), but the following code works
+ * in that case too. Just make sure to resize self
+ * before calling PySequence_Fast_ITEMS.
+ */
+ /* populate the end of self with b's items */
+ src = PySequence_Fast_ITEMS(b);
+ dest = self->ob_item + m;
+ for (i = 0; i < n; i++) {
+ PyObject *o = src[i];
+ Py_INCREF(o);
+ dest[i] = o;
+ }
+ Py_DECREF(b);
+ Py_RETURN_NONE;
+ }
+
+ it = PyObject_GetIter(b);
+ if (it == NULL)
+ return NULL;
+ iternext = *it->ob_type->tp_iternext;
+
+ /* Guess a result list size. */
+ n = _PyObject_LengthHint(b, 8);
+ if (n == -1) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ m = Py_SIZE(self);
+ mn = m + n;
+ if (mn >= m) {
+ /* Make room. */
+ if (list_resize(self, mn) == -1)
+ goto error;
+ /* Make the list sane again. */
+ Py_SIZE(self) = m;
+ }
+ /* Else m + n overflowed; on the chance that n lied, and there really
+ * is enough room, ignore it. If n was telling the truth, we'll
+ * eventually run out of memory during the loop.
+ */
+
+ /* Run iterator to exhaustion. */
+ for (;;) {
+ PyObject *item = iternext(it);
+ if (item == NULL) {
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ goto error;
+ }
+ break;
+ }
+ if (Py_SIZE(self) < self->allocated) {
+ /* steals ref */
+ PyList_SET_ITEM(self, Py_SIZE(self), item);
+ ++Py_SIZE(self);
+ }
+ else {
+ int status = app1(self, item);
+ Py_DECREF(item); /* append creates a new ref */
+ if (status < 0)
+ goto error;
+ }
+ }
+
+ /* Cut back result list if initial guess was too large. */
+ if (Py_SIZE(self) < self->allocated)
+ list_resize(self, Py_SIZE(self)); /* shrinking can't fail */
+
+ Py_DECREF(it);
+ Py_RETURN_NONE;
error:
- Py_DECREF(it);
- return NULL;
+ Py_DECREF(it);
+ return NULL;
}
PyObject *
_PyList_Extend(PyListObject *self, PyObject *b)
{
- return listextend(self, b);
+ return listextend(self, b);
}
static PyObject *
list_inplace_concat(PyListObject *self, PyObject *other)
{
- PyObject *result;
+ PyObject *result;
- result = listextend(self, other);
- if (result == NULL)
- return result;
- Py_DECREF(result);
- Py_INCREF(self);
- return (PyObject *)self;
+ result = listextend(self, other);
+ if (result == NULL)
+ return result;
+ Py_DECREF(result);
+ Py_INCREF(self);
+ return (PyObject *)self;
}
static PyObject *
listpop(PyListObject *self, PyObject *args)
{
- Py_ssize_t i = -1;
- PyObject *v;
- int status;
-
- if (!PyArg_ParseTuple(args, "|n:pop", &i))
- return NULL;
-
- if (Py_SIZE(self) == 0) {
- /* Special-case most common failure cause */
- PyErr_SetString(PyExc_IndexError, "pop from empty list");
- return NULL;
- }
- if (i < 0)
- i += Py_SIZE(self);
- if (i < 0 || i >= Py_SIZE(self)) {
- PyErr_SetString(PyExc_IndexError, "pop index out of range");
- return NULL;
- }
- v = self->ob_item[i];
- if (i == Py_SIZE(self) - 1) {
- status = list_resize(self, Py_SIZE(self) - 1);
- assert(status >= 0);
- return v; /* and v now owns the reference the list had */
- }
- Py_INCREF(v);
- status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
- assert(status >= 0);
- /* Use status, so that in a release build compilers don't
- * complain about the unused name.
- */
- (void) status;
-
- return v;
+ Py_ssize_t i = -1;
+ PyObject *v;
+ int status;
+
+ if (!PyArg_ParseTuple(args, "|n:pop", &i))
+ return NULL;
+
+ if (Py_SIZE(self) == 0) {
+ /* Special-case most common failure cause */
+ PyErr_SetString(PyExc_IndexError, "pop from empty list");
+ return NULL;
+ }
+ if (i < 0)
+ i += Py_SIZE(self);
+ if (i < 0 || i >= Py_SIZE(self)) {
+ PyErr_SetString(PyExc_IndexError, "pop index out of range");
+ return NULL;
+ }
+ v = self->ob_item[i];
+ if (i == Py_SIZE(self) - 1) {
+ status = list_resize(self, Py_SIZE(self) - 1);
+ assert(status >= 0);
+ return v; /* and v now owns the reference the list had */
+ }
+ Py_INCREF(v);
+ status = list_ass_slice(self, i, i+1, (PyObject *)NULL);
+ assert(status >= 0);
+ /* Use status, so that in a release build compilers don't
+ * complain about the unused name.
+ */
+ (void) status;
+
+ return v;
}
/* Reverse a slice of a list in place, from lo up to (exclusive) hi. */
static void
reverse_slice(PyObject **lo, PyObject **hi)
{
- assert(lo && hi);
+ assert(lo && hi);
- --hi;
- while (lo < hi) {
- PyObject *t = *lo;
- *lo = *hi;
- *hi = t;
- ++lo;
- --hi;
- }
+ --hi;
+ while (lo < hi) {
+ PyObject *t = *lo;
+ *lo = *hi;
+ *hi = t;
+ ++lo;
+ --hi;
+ }
}
/* Lots of code for an adaptive, stable, natural mergesort. There are many
@@ -990,35 +990,35 @@ reverse_slice(PyObject **lo, PyObject **hi)
static int
islt(PyObject *x, PyObject *y, PyObject *compare)
{
- PyObject *res;
- PyObject *args;
- Py_ssize_t i;
-
- assert(compare != NULL);
- /* Call the user's comparison function and translate the 3-way
- * result into true or false (or error).
- */
- args = PyTuple_New(2);
- if (args == NULL)
- return -1;
- Py_INCREF(x);
- Py_INCREF(y);
- PyTuple_SET_ITEM(args, 0, x);
- PyTuple_SET_ITEM(args, 1, y);
- res = PyObject_Call(compare, args, NULL);
- Py_DECREF(args);
- if (res == NULL)
- return -1;
- if (!PyInt_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "comparison function must return int, not %.200s",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return -1;
- }
- i = PyInt_AsLong(res);
- Py_DECREF(res);
- return i < 0;
+ PyObject *res;
+ PyObject *args;
+ Py_ssize_t i;
+
+ assert(compare != NULL);
+ /* Call the user's comparison function and translate the 3-way
+ * result into true or false (or error).
+ */
+ args = PyTuple_New(2);
+ if (args == NULL)
+ return -1;
+ Py_INCREF(x);
+ Py_INCREF(y);
+ PyTuple_SET_ITEM(args, 0, x);
+ PyTuple_SET_ITEM(args, 1, y);
+ res = PyObject_Call(compare, args, NULL);
+ Py_DECREF(args);
+ if (res == NULL)
+ return -1;
+ if (!PyInt_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "comparison function must return int, not %.200s",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return -1;
+ }
+ i = PyInt_AsLong(res);
+ Py_DECREF(res);
+ return i < 0;
}
/* If COMPARE is NULL, calls PyObject_RichCompareBool with Py_LT, else calls
@@ -1026,16 +1026,16 @@ islt(PyObject *x, PyObject *y, PyObject *compare)
* sorting does many comparisons.
* Returns -1 on error, 1 if x < y, 0 if x >= y.
*/
-#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
- PyObject_RichCompareBool(X, Y, Py_LT) : \
- islt(X, Y, COMPARE))
+#define ISLT(X, Y, COMPARE) ((COMPARE) == NULL ? \
+ PyObject_RichCompareBool(X, Y, Py_LT) : \
+ islt(X, Y, COMPARE))
/* Compare X to Y via "<". Goto "fail" if the comparison raises an
error. Else "k" is set to true iff X<Y, and an "if (k)" block is
started. It makes more sense in context <wink>. X and Y are PyObject*s.
*/
#define IFLT(X, Y) if ((k = ISLT(X, Y, compare)) < 0) goto fail; \
- if (k)
+ if (k)
/* binarysort is the best method for sorting small arrays: it does
few compares, but can do data movement quadratic in the number of
@@ -1052,48 +1052,48 @@ static int
binarysort(PyObject **lo, PyObject **hi, PyObject **start, PyObject *compare)
/* compare -- comparison function object, or NULL for default */
{
- register Py_ssize_t k;
- register PyObject **l, **p, **r;
- register PyObject *pivot;
-
- assert(lo <= start && start <= hi);
- /* assert [lo, start) is sorted */
- if (lo == start)
- ++start;
- for (; start < hi; ++start) {
- /* set l to where *start belongs */
- l = lo;
- r = start;
- pivot = *r;
- /* Invariants:
- * pivot >= all in [lo, l).
- * pivot < all in [r, start).
- * The second is vacuously true at the start.
- */
- assert(l < r);
- do {
- p = l + ((r - l) >> 1);
- IFLT(pivot, *p)
- r = p;
- else
- l = p+1;
- } while (l < r);
- assert(l == r);
- /* The invariants still hold, so pivot >= all in [lo, l) and
- pivot < all in [l, start), so pivot belongs at l. Note
- that if there are elements equal to pivot, l points to the
- first slot after them -- that's why this sort is stable.
- Slide over to make room.
- Caution: using memmove is much slower under MSVC 5;
- we're not usually moving many slots. */
- for (p = start; p > l; --p)
- *p = *(p-1);
- *l = pivot;
- }
- return 0;
+ register Py_ssize_t k;
+ register PyObject **l, **p, **r;
+ register PyObject *pivot;
+
+ assert(lo <= start && start <= hi);
+ /* assert [lo, start) is sorted */
+ if (lo == start)
+ ++start;
+ for (; start < hi; ++start) {
+ /* set l to where *start belongs */
+ l = lo;
+ r = start;
+ pivot = *r;
+ /* Invariants:
+ * pivot >= all in [lo, l).
+ * pivot < all in [r, start).
+ * The second is vacuously true at the start.
+ */
+ assert(l < r);
+ do {
+ p = l + ((r - l) >> 1);
+ IFLT(pivot, *p)
+ r = p;
+ else
+ l = p+1;
+ } while (l < r);
+ assert(l == r);
+ /* The invariants still hold, so pivot >= all in [lo, l) and
+ pivot < all in [l, start), so pivot belongs at l. Note
+ that if there are elements equal to pivot, l points to the
+ first slot after them -- that's why this sort is stable.
+ Slide over to make room.
+ Caution: using memmove is much slower under MSVC 5;
+ we're not usually moving many slots. */
+ for (p = start; p > l; --p)
+ *p = *(p-1);
+ *l = pivot;
+ }
+ return 0;
fail:
- return -1;
+ return -1;
}
/*
@@ -1117,35 +1117,35 @@ Returns -1 in case of error.
static Py_ssize_t
count_run(PyObject **lo, PyObject **hi, PyObject *compare, int *descending)
{
- Py_ssize_t k;
- Py_ssize_t n;
-
- assert(lo < hi);
- *descending = 0;
- ++lo;
- if (lo == hi)
- return 1;
-
- n = 2;
- IFLT(*lo, *(lo-1)) {
- *descending = 1;
- for (lo = lo+1; lo < hi; ++lo, ++n) {
- IFLT(*lo, *(lo-1))
- ;
- else
- break;
- }
- }
- else {
- for (lo = lo+1; lo < hi; ++lo, ++n) {
- IFLT(*lo, *(lo-1))
- break;
- }
- }
-
- return n;
+ Py_ssize_t k;
+ Py_ssize_t n;
+
+ assert(lo < hi);
+ *descending = 0;
+ ++lo;
+ if (lo == hi)
+ return 1;
+
+ n = 2;
+ IFLT(*lo, *(lo-1)) {
+ *descending = 1;
+ for (lo = lo+1; lo < hi; ++lo, ++n) {
+ IFLT(*lo, *(lo-1))
+ ;
+ else
+ break;
+ }
+ }
+ else {
+ for (lo = lo+1; lo < hi; ++lo, ++n) {
+ IFLT(*lo, *(lo-1))
+ break;
+ }
+ }
+
+ return n;
fail:
- return -1;
+ return -1;
}
/*
@@ -1172,78 +1172,78 @@ Returns -1 on error. See listsort.txt for info on the method.
static Py_ssize_t
gallop_left(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
{
- Py_ssize_t ofs;
- Py_ssize_t lastofs;
- Py_ssize_t k;
-
- assert(key && a && n > 0 && hint >= 0 && hint < n);
-
- a += hint;
- lastofs = 0;
- ofs = 1;
- IFLT(*a, key) {
- /* a[hint] < key -- gallop right, until
- * a[hint + lastofs] < key <= a[hint + ofs]
- */
- const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
- while (ofs < maxofs) {
- IFLT(a[ofs], key) {
- lastofs = ofs;
- ofs = (ofs << 1) + 1;
- if (ofs <= 0) /* int overflow */
- ofs = maxofs;
- }
- else /* key <= a[hint + ofs] */
- break;
- }
- if (ofs > maxofs)
- ofs = maxofs;
- /* Translate back to offsets relative to &a[0]. */
- lastofs += hint;
- ofs += hint;
- }
- else {
- /* key <= a[hint] -- gallop left, until
- * a[hint - ofs] < key <= a[hint - lastofs]
- */
- const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
- while (ofs < maxofs) {
- IFLT(*(a-ofs), key)
- break;
- /* key <= a[hint - ofs] */
- lastofs = ofs;
- ofs = (ofs << 1) + 1;
- if (ofs <= 0) /* int overflow */
- ofs = maxofs;
- }
- if (ofs > maxofs)
- ofs = maxofs;
- /* Translate back to positive offsets relative to &a[0]. */
- k = lastofs;
- lastofs = hint - ofs;
- ofs = hint - k;
- }
- a -= hint;
-
- assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
- /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
- * right of lastofs but no farther right than ofs. Do a binary
- * search, with invariant a[lastofs-1] < key <= a[ofs].
- */
- ++lastofs;
- while (lastofs < ofs) {
- Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
-
- IFLT(a[m], key)
- lastofs = m+1; /* a[m] < key */
- else
- ofs = m; /* key <= a[m] */
- }
- assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
- return ofs;
+ Py_ssize_t ofs;
+ Py_ssize_t lastofs;
+ Py_ssize_t k;
+
+ assert(key && a && n > 0 && hint >= 0 && hint < n);
+
+ a += hint;
+ lastofs = 0;
+ ofs = 1;
+ IFLT(*a, key) {
+ /* a[hint] < key -- gallop right, until
+ * a[hint + lastofs] < key <= a[hint + ofs]
+ */
+ const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
+ while (ofs < maxofs) {
+ IFLT(a[ofs], key) {
+ lastofs = ofs;
+ ofs = (ofs << 1) + 1;
+ if (ofs <= 0) /* int overflow */
+ ofs = maxofs;
+ }
+ else /* key <= a[hint + ofs] */
+ break;
+ }
+ if (ofs > maxofs)
+ ofs = maxofs;
+ /* Translate back to offsets relative to &a[0]. */
+ lastofs += hint;
+ ofs += hint;
+ }
+ else {
+ /* key <= a[hint] -- gallop left, until
+ * a[hint - ofs] < key <= a[hint - lastofs]
+ */
+ const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
+ while (ofs < maxofs) {
+ IFLT(*(a-ofs), key)
+ break;
+ /* key <= a[hint - ofs] */
+ lastofs = ofs;
+ ofs = (ofs << 1) + 1;
+ if (ofs <= 0) /* int overflow */
+ ofs = maxofs;
+ }
+ if (ofs > maxofs)
+ ofs = maxofs;
+ /* Translate back to positive offsets relative to &a[0]. */
+ k = lastofs;
+ lastofs = hint - ofs;
+ ofs = hint - k;
+ }
+ a -= hint;
+
+ assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
+ /* Now a[lastofs] < key <= a[ofs], so key belongs somewhere to the
+ * right of lastofs but no farther right than ofs. Do a binary
+ * search, with invariant a[lastofs-1] < key <= a[ofs].
+ */
+ ++lastofs;
+ while (lastofs < ofs) {
+ Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
+
+ IFLT(a[m], key)
+ lastofs = m+1; /* a[m] < key */
+ else
+ ofs = m; /* key <= a[m] */
+ }
+ assert(lastofs == ofs); /* so a[ofs-1] < key <= a[ofs] */
+ return ofs;
fail:
- return -1;
+ return -1;
}
/*
@@ -1263,78 +1263,78 @@ written as one routine with yet another "left or right?" flag.
static Py_ssize_t
gallop_right(PyObject *key, PyObject **a, Py_ssize_t n, Py_ssize_t hint, PyObject *compare)
{
- Py_ssize_t ofs;
- Py_ssize_t lastofs;
- Py_ssize_t k;
-
- assert(key && a && n > 0 && hint >= 0 && hint < n);
-
- a += hint;
- lastofs = 0;
- ofs = 1;
- IFLT(key, *a) {
- /* key < a[hint] -- gallop left, until
- * a[hint - ofs] <= key < a[hint - lastofs]
- */
- const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
- while (ofs < maxofs) {
- IFLT(key, *(a-ofs)) {
- lastofs = ofs;
- ofs = (ofs << 1) + 1;
- if (ofs <= 0) /* int overflow */
- ofs = maxofs;
- }
- else /* a[hint - ofs] <= key */
- break;
- }
- if (ofs > maxofs)
- ofs = maxofs;
- /* Translate back to positive offsets relative to &a[0]. */
- k = lastofs;
- lastofs = hint - ofs;
- ofs = hint - k;
- }
- else {
- /* a[hint] <= key -- gallop right, until
- * a[hint + lastofs] <= key < a[hint + ofs]
- */
- const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
- while (ofs < maxofs) {
- IFLT(key, a[ofs])
- break;
- /* a[hint + ofs] <= key */
- lastofs = ofs;
- ofs = (ofs << 1) + 1;
- if (ofs <= 0) /* int overflow */
- ofs = maxofs;
- }
- if (ofs > maxofs)
- ofs = maxofs;
- /* Translate back to offsets relative to &a[0]. */
- lastofs += hint;
- ofs += hint;
- }
- a -= hint;
-
- assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
- /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
- * right of lastofs but no farther right than ofs. Do a binary
- * search, with invariant a[lastofs-1] <= key < a[ofs].
- */
- ++lastofs;
- while (lastofs < ofs) {
- Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
-
- IFLT(key, a[m])
- ofs = m; /* key < a[m] */
- else
- lastofs = m+1; /* a[m] <= key */
- }
- assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
- return ofs;
+ Py_ssize_t ofs;
+ Py_ssize_t lastofs;
+ Py_ssize_t k;
+
+ assert(key && a && n > 0 && hint >= 0 && hint < n);
+
+ a += hint;
+ lastofs = 0;
+ ofs = 1;
+ IFLT(key, *a) {
+ /* key < a[hint] -- gallop left, until
+ * a[hint - ofs] <= key < a[hint - lastofs]
+ */
+ const Py_ssize_t maxofs = hint + 1; /* &a[0] is lowest */
+ while (ofs < maxofs) {
+ IFLT(key, *(a-ofs)) {
+ lastofs = ofs;
+ ofs = (ofs << 1) + 1;
+ if (ofs <= 0) /* int overflow */
+ ofs = maxofs;
+ }
+ else /* a[hint - ofs] <= key */
+ break;
+ }
+ if (ofs > maxofs)
+ ofs = maxofs;
+ /* Translate back to positive offsets relative to &a[0]. */
+ k = lastofs;
+ lastofs = hint - ofs;
+ ofs = hint - k;
+ }
+ else {
+ /* a[hint] <= key -- gallop right, until
+ * a[hint + lastofs] <= key < a[hint + ofs]
+ */
+ const Py_ssize_t maxofs = n - hint; /* &a[n-1] is highest */
+ while (ofs < maxofs) {
+ IFLT(key, a[ofs])
+ break;
+ /* a[hint + ofs] <= key */
+ lastofs = ofs;
+ ofs = (ofs << 1) + 1;
+ if (ofs <= 0) /* int overflow */
+ ofs = maxofs;
+ }
+ if (ofs > maxofs)
+ ofs = maxofs;
+ /* Translate back to offsets relative to &a[0]. */
+ lastofs += hint;
+ ofs += hint;
+ }
+ a -= hint;
+
+ assert(-1 <= lastofs && lastofs < ofs && ofs <= n);
+ /* Now a[lastofs] <= key < a[ofs], so key belongs somewhere to the
+ * right of lastofs but no farther right than ofs. Do a binary
+ * search, with invariant a[lastofs-1] <= key < a[ofs].
+ */
+ ++lastofs;
+ while (lastofs < ofs) {
+ Py_ssize_t m = lastofs + ((ofs - lastofs) >> 1);
+
+ IFLT(key, a[m])
+ ofs = m; /* key < a[m] */
+ else
+ lastofs = m+1; /* a[m] <= key */
+ }
+ assert(lastofs == ofs); /* so a[ofs-1] <= key < a[ofs] */
+ return ofs;
fail:
- return -1;
+ return -1;
}
/* The maximum number of entries in a MergeState's pending-runs stack.
@@ -1357,52 +1357,52 @@ fail:
* a convenient way to pass state around among the helper functions.
*/
struct s_slice {
- PyObject **base;
- Py_ssize_t len;
+ PyObject **base;
+ Py_ssize_t len;
};
typedef struct s_MergeState {
- /* The user-supplied comparison function. or NULL if none given. */
- PyObject *compare;
-
- /* This controls when we get *into* galloping mode. It's initialized
- * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
- * random data, and lower for highly structured data.
- */
- Py_ssize_t min_gallop;
-
- /* 'a' is temp storage to help with merges. It contains room for
- * alloced entries.
- */
- PyObject **a; /* may point to temparray below */
- Py_ssize_t alloced;
-
- /* A stack of n pending runs yet to be merged. Run #i starts at
- * address base[i] and extends for len[i] elements. It's always
- * true (so long as the indices are in bounds) that
- *
- * pending[i].base + pending[i].len == pending[i+1].base
- *
- * so we could cut the storage for this, but it's a minor amount,
- * and keeping all the info explicit simplifies the code.
- */
- int n;
- struct s_slice pending[MAX_MERGE_PENDING];
-
- /* 'a' points to this when possible, rather than muck with malloc. */
- PyObject *temparray[MERGESTATE_TEMP_SIZE];
+ /* The user-supplied comparison function. or NULL if none given. */
+ PyObject *compare;
+
+ /* This controls when we get *into* galloping mode. It's initialized
+ * to MIN_GALLOP. merge_lo and merge_hi tend to nudge it higher for
+ * random data, and lower for highly structured data.
+ */
+ Py_ssize_t min_gallop;
+
+ /* 'a' is temp storage to help with merges. It contains room for
+ * alloced entries.
+ */
+ PyObject **a; /* may point to temparray below */
+ Py_ssize_t alloced;
+
+ /* A stack of n pending runs yet to be merged. Run #i starts at
+ * address base[i] and extends for len[i] elements. It's always
+ * true (so long as the indices are in bounds) that
+ *
+ * pending[i].base + pending[i].len == pending[i+1].base
+ *
+ * so we could cut the storage for this, but it's a minor amount,
+ * and keeping all the info explicit simplifies the code.
+ */
+ int n;
+ struct s_slice pending[MAX_MERGE_PENDING];
+
+ /* 'a' points to this when possible, rather than muck with malloc. */
+ PyObject *temparray[MERGESTATE_TEMP_SIZE];
} MergeState;
/* Conceptually a MergeState's constructor. */
static void
merge_init(MergeState *ms, PyObject *compare)
{
- assert(ms != NULL);
- ms->compare = compare;
- ms->a = ms->temparray;
- ms->alloced = MERGESTATE_TEMP_SIZE;
- ms->n = 0;
- ms->min_gallop = MIN_GALLOP;
+ assert(ms != NULL);
+ ms->compare = compare;
+ ms->a = ms->temparray;
+ ms->alloced = MERGESTATE_TEMP_SIZE;
+ ms->n = 0;
+ ms->min_gallop = MIN_GALLOP;
}
/* Free all the temp memory owned by the MergeState. This must be called
@@ -1412,11 +1412,11 @@ merge_init(MergeState *ms, PyObject *compare)
static void
merge_freemem(MergeState *ms)
{
- assert(ms != NULL);
- if (ms->a != ms->temparray)
- PyMem_Free(ms->a);
- ms->a = ms->temparray;
- ms->alloced = MERGESTATE_TEMP_SIZE;
+ assert(ms != NULL);
+ if (ms->a != ms->temparray)
+ PyMem_Free(ms->a);
+ ms->a = ms->temparray;
+ ms->alloced = MERGESTATE_TEMP_SIZE;
}
/* Ensure enough temp memory for 'need' array slots is available.
@@ -1425,28 +1425,28 @@ merge_freemem(MergeState *ms)
static int
merge_getmem(MergeState *ms, Py_ssize_t need)
{
- assert(ms != NULL);
- if (need <= ms->alloced)
- return 0;
- /* Don't realloc! That can cost cycles to copy the old data, but
- * we don't care what's in the block.
- */
- merge_freemem(ms);
- if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
- PyErr_NoMemory();
- return -1;
- }
- ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
- if (ms->a) {
- ms->alloced = need;
- return 0;
- }
- PyErr_NoMemory();
- merge_freemem(ms); /* reset to sane state */
- return -1;
-}
-#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
- merge_getmem(MS, NEED))
+ assert(ms != NULL);
+ if (need <= ms->alloced)
+ return 0;
+ /* Don't realloc! That can cost cycles to copy the old data, but
+ * we don't care what's in the block.
+ */
+ merge_freemem(ms);
+ if ((size_t)need > PY_SSIZE_T_MAX / sizeof(PyObject*)) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ ms->a = (PyObject **)PyMem_Malloc(need * sizeof(PyObject*));
+ if (ms->a) {
+ ms->alloced = need;
+ return 0;
+ }
+ PyErr_NoMemory();
+ merge_freemem(ms); /* reset to sane state */
+ return -1;
+}
+#define MERGE_GETMEM(MS, NEED) ((NEED) <= (MS)->alloced ? 0 : \
+ merge_getmem(MS, NEED))
/* Merge the na elements starting at pa with the nb elements starting at pb
* in a stable way, in-place. na and nb must be > 0, and pa + na == pb.
@@ -1458,127 +1458,127 @@ static Py_ssize_t
merge_lo(MergeState *ms, PyObject **pa, Py_ssize_t na,
PyObject **pb, Py_ssize_t nb)
{
- Py_ssize_t k;
- PyObject *compare;
- PyObject **dest;
- int result = -1; /* guilty until proved innocent */
- Py_ssize_t min_gallop;
-
- assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
- if (MERGE_GETMEM(ms, na) < 0)
- return -1;
- memcpy(ms->a, pa, na * sizeof(PyObject*));
- dest = pa;
- pa = ms->a;
-
- *dest++ = *pb++;
- --nb;
- if (nb == 0)
- goto Succeed;
- if (na == 1)
- goto CopyB;
-
- min_gallop = ms->min_gallop;
- compare = ms->compare;
- for (;;) {
- Py_ssize_t acount = 0; /* # of times A won in a row */
- Py_ssize_t bcount = 0; /* # of times B won in a row */
-
- /* Do the straightforward thing until (if ever) one run
- * appears to win consistently.
- */
- for (;;) {
- assert(na > 1 && nb > 0);
- k = ISLT(*pb, *pa, compare);
- if (k) {
- if (k < 0)
- goto Fail;
- *dest++ = *pb++;
- ++bcount;
- acount = 0;
- --nb;
- if (nb == 0)
- goto Succeed;
- if (bcount >= min_gallop)
- break;
- }
- else {
- *dest++ = *pa++;
- ++acount;
- bcount = 0;
- --na;
- if (na == 1)
- goto CopyB;
- if (acount >= min_gallop)
- break;
- }
- }
-
- /* One run is winning so consistently that galloping may
- * be a huge win. So try that, and continue galloping until
- * (if ever) neither run appears to be winning consistently
- * anymore.
- */
- ++min_gallop;
- do {
- assert(na > 1 && nb > 0);
- min_gallop -= min_gallop > 1;
- ms->min_gallop = min_gallop;
- k = gallop_right(*pb, pa, na, 0, compare);
- acount = k;
- if (k) {
- if (k < 0)
- goto Fail;
- memcpy(dest, pa, k * sizeof(PyObject *));
- dest += k;
- pa += k;
- na -= k;
- if (na == 1)
- goto CopyB;
- /* na==0 is impossible now if the comparison
- * function is consistent, but we can't assume
- * that it is.
- */
- if (na == 0)
- goto Succeed;
- }
- *dest++ = *pb++;
- --nb;
- if (nb == 0)
- goto Succeed;
-
- k = gallop_left(*pa, pb, nb, 0, compare);
- bcount = k;
- if (k) {
- if (k < 0)
- goto Fail;
- memmove(dest, pb, k * sizeof(PyObject *));
- dest += k;
- pb += k;
- nb -= k;
- if (nb == 0)
- goto Succeed;
- }
- *dest++ = *pa++;
- --na;
- if (na == 1)
- goto CopyB;
- } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
- ++min_gallop; /* penalize it for leaving galloping mode */
- ms->min_gallop = min_gallop;
- }
+ Py_ssize_t k;
+ PyObject *compare;
+ PyObject **dest;
+ int result = -1; /* guilty until proved innocent */
+ Py_ssize_t min_gallop;
+
+ assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
+ if (MERGE_GETMEM(ms, na) < 0)
+ return -1;
+ memcpy(ms->a, pa, na * sizeof(PyObject*));
+ dest = pa;
+ pa = ms->a;
+
+ *dest++ = *pb++;
+ --nb;
+ if (nb == 0)
+ goto Succeed;
+ if (na == 1)
+ goto CopyB;
+
+ min_gallop = ms->min_gallop;
+ compare = ms->compare;
+ for (;;) {
+ Py_ssize_t acount = 0; /* # of times A won in a row */
+ Py_ssize_t bcount = 0; /* # of times B won in a row */
+
+ /* Do the straightforward thing until (if ever) one run
+ * appears to win consistently.
+ */
+ for (;;) {
+ assert(na > 1 && nb > 0);
+ k = ISLT(*pb, *pa, compare);
+ if (k) {
+ if (k < 0)
+ goto Fail;
+ *dest++ = *pb++;
+ ++bcount;
+ acount = 0;
+ --nb;
+ if (nb == 0)
+ goto Succeed;
+ if (bcount >= min_gallop)
+ break;
+ }
+ else {
+ *dest++ = *pa++;
+ ++acount;
+ bcount = 0;
+ --na;
+ if (na == 1)
+ goto CopyB;
+ if (acount >= min_gallop)
+ break;
+ }
+ }
+
+ /* One run is winning so consistently that galloping may
+ * be a huge win. So try that, and continue galloping until
+ * (if ever) neither run appears to be winning consistently
+ * anymore.
+ */
+ ++min_gallop;
+ do {
+ assert(na > 1 && nb > 0);
+ min_gallop -= min_gallop > 1;
+ ms->min_gallop = min_gallop;
+ k = gallop_right(*pb, pa, na, 0, compare);
+ acount = k;
+ if (k) {
+ if (k < 0)
+ goto Fail;
+ memcpy(dest, pa, k * sizeof(PyObject *));
+ dest += k;
+ pa += k;
+ na -= k;
+ if (na == 1)
+ goto CopyB;
+ /* na==0 is impossible now if the comparison
+ * function is consistent, but we can't assume
+ * that it is.
+ */
+ if (na == 0)
+ goto Succeed;
+ }
+ *dest++ = *pb++;
+ --nb;
+ if (nb == 0)
+ goto Succeed;
+
+ k = gallop_left(*pa, pb, nb, 0, compare);
+ bcount = k;
+ if (k) {
+ if (k < 0)
+ goto Fail;
+ memmove(dest, pb, k * sizeof(PyObject *));
+ dest += k;
+ pb += k;
+ nb -= k;
+ if (nb == 0)
+ goto Succeed;
+ }
+ *dest++ = *pa++;
+ --na;
+ if (na == 1)
+ goto CopyB;
+ } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
+ ++min_gallop; /* penalize it for leaving galloping mode */
+ ms->min_gallop = min_gallop;
+ }
Succeed:
- result = 0;
+ result = 0;
Fail:
- if (na)
- memcpy(dest, pa, na * sizeof(PyObject*));
- return result;
+ if (na)
+ memcpy(dest, pa, na * sizeof(PyObject*));
+ return result;
CopyB:
- assert(na == 1 && nb > 0);
- /* The last element of pa belongs at the end of the merge. */
- memmove(dest, pb, nb * sizeof(PyObject *));
- dest[nb] = *pa;
- return 0;
+ assert(na == 1 && nb > 0);
+ /* The last element of pa belongs at the end of the merge. */
+ memmove(dest, pb, nb * sizeof(PyObject *));
+ dest[nb] = *pa;
+ return 0;
}
/* Merge the na elements starting at pa with the nb elements starting at pb
@@ -1590,136 +1590,136 @@ CopyB:
static Py_ssize_t
merge_hi(MergeState *ms, PyObject **pa, Py_ssize_t na, PyObject **pb, Py_ssize_t nb)
{
- Py_ssize_t k;
- PyObject *compare;
- PyObject **dest;
- int result = -1; /* guilty until proved innocent */
- PyObject **basea;
- PyObject **baseb;
- Py_ssize_t min_gallop;
-
- assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
- if (MERGE_GETMEM(ms, nb) < 0)
- return -1;
- dest = pb + nb - 1;
- memcpy(ms->a, pb, nb * sizeof(PyObject*));
- basea = pa;
- baseb = ms->a;
- pb = ms->a + nb - 1;
- pa += na - 1;
-
- *dest-- = *pa--;
- --na;
- if (na == 0)
- goto Succeed;
- if (nb == 1)
- goto CopyA;
-
- min_gallop = ms->min_gallop;
- compare = ms->compare;
- for (;;) {
- Py_ssize_t acount = 0; /* # of times A won in a row */
- Py_ssize_t bcount = 0; /* # of times B won in a row */
-
- /* Do the straightforward thing until (if ever) one run
- * appears to win consistently.
- */
- for (;;) {
- assert(na > 0 && nb > 1);
- k = ISLT(*pb, *pa, compare);
- if (k) {
- if (k < 0)
- goto Fail;
- *dest-- = *pa--;
- ++acount;
- bcount = 0;
- --na;
- if (na == 0)
- goto Succeed;
- if (acount >= min_gallop)
- break;
- }
- else {
- *dest-- = *pb--;
- ++bcount;
- acount = 0;
- --nb;
- if (nb == 1)
- goto CopyA;
- if (bcount >= min_gallop)
- break;
- }
- }
-
- /* One run is winning so consistently that galloping may
- * be a huge win. So try that, and continue galloping until
- * (if ever) neither run appears to be winning consistently
- * anymore.
- */
- ++min_gallop;
- do {
- assert(na > 0 && nb > 1);
- min_gallop -= min_gallop > 1;
- ms->min_gallop = min_gallop;
- k = gallop_right(*pb, basea, na, na-1, compare);
- if (k < 0)
- goto Fail;
- k = na - k;
- acount = k;
- if (k) {
- dest -= k;
- pa -= k;
- memmove(dest+1, pa+1, k * sizeof(PyObject *));
- na -= k;
- if (na == 0)
- goto Succeed;
- }
- *dest-- = *pb--;
- --nb;
- if (nb == 1)
- goto CopyA;
-
- k = gallop_left(*pa, baseb, nb, nb-1, compare);
- if (k < 0)
- goto Fail;
- k = nb - k;
- bcount = k;
- if (k) {
- dest -= k;
- pb -= k;
- memcpy(dest+1, pb+1, k * sizeof(PyObject *));
- nb -= k;
- if (nb == 1)
- goto CopyA;
- /* nb==0 is impossible now if the comparison
- * function is consistent, but we can't assume
- * that it is.
- */
- if (nb == 0)
- goto Succeed;
- }
- *dest-- = *pa--;
- --na;
- if (na == 0)
- goto Succeed;
- } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
- ++min_gallop; /* penalize it for leaving galloping mode */
- ms->min_gallop = min_gallop;
- }
+ Py_ssize_t k;
+ PyObject *compare;
+ PyObject **dest;
+ int result = -1; /* guilty until proved innocent */
+ PyObject **basea;
+ PyObject **baseb;
+ Py_ssize_t min_gallop;
+
+ assert(ms && pa && pb && na > 0 && nb > 0 && pa + na == pb);
+ if (MERGE_GETMEM(ms, nb) < 0)
+ return -1;
+ dest = pb + nb - 1;
+ memcpy(ms->a, pb, nb * sizeof(PyObject*));
+ basea = pa;
+ baseb = ms->a;
+ pb = ms->a + nb - 1;
+ pa += na - 1;
+
+ *dest-- = *pa--;
+ --na;
+ if (na == 0)
+ goto Succeed;
+ if (nb == 1)
+ goto CopyA;
+
+ min_gallop = ms->min_gallop;
+ compare = ms->compare;
+ for (;;) {
+ Py_ssize_t acount = 0; /* # of times A won in a row */
+ Py_ssize_t bcount = 0; /* # of times B won in a row */
+
+ /* Do the straightforward thing until (if ever) one run
+ * appears to win consistently.
+ */
+ for (;;) {
+ assert(na > 0 && nb > 1);
+ k = ISLT(*pb, *pa, compare);
+ if (k) {
+ if (k < 0)
+ goto Fail;
+ *dest-- = *pa--;
+ ++acount;
+ bcount = 0;
+ --na;
+ if (na == 0)
+ goto Succeed;
+ if (acount >= min_gallop)
+ break;
+ }
+ else {
+ *dest-- = *pb--;
+ ++bcount;
+ acount = 0;
+ --nb;
+ if (nb == 1)
+ goto CopyA;
+ if (bcount >= min_gallop)
+ break;
+ }
+ }
+
+ /* One run is winning so consistently that galloping may
+ * be a huge win. So try that, and continue galloping until
+ * (if ever) neither run appears to be winning consistently
+ * anymore.
+ */
+ ++min_gallop;
+ do {
+ assert(na > 0 && nb > 1);
+ min_gallop -= min_gallop > 1;
+ ms->min_gallop = min_gallop;
+ k = gallop_right(*pb, basea, na, na-1, compare);
+ if (k < 0)
+ goto Fail;
+ k = na - k;
+ acount = k;
+ if (k) {
+ dest -= k;
+ pa -= k;
+ memmove(dest+1, pa+1, k * sizeof(PyObject *));
+ na -= k;
+ if (na == 0)
+ goto Succeed;
+ }
+ *dest-- = *pb--;
+ --nb;
+ if (nb == 1)
+ goto CopyA;
+
+ k = gallop_left(*pa, baseb, nb, nb-1, compare);
+ if (k < 0)
+ goto Fail;
+ k = nb - k;
+ bcount = k;
+ if (k) {
+ dest -= k;
+ pb -= k;
+ memcpy(dest+1, pb+1, k * sizeof(PyObject *));
+ nb -= k;
+ if (nb == 1)
+ goto CopyA;
+ /* nb==0 is impossible now if the comparison
+ * function is consistent, but we can't assume
+ * that it is.
+ */
+ if (nb == 0)
+ goto Succeed;
+ }
+ *dest-- = *pa--;
+ --na;
+ if (na == 0)
+ goto Succeed;
+ } while (acount >= MIN_GALLOP || bcount >= MIN_GALLOP);
+ ++min_gallop; /* penalize it for leaving galloping mode */
+ ms->min_gallop = min_gallop;
+ }
Succeed:
- result = 0;
+ result = 0;
Fail:
- if (nb)
- memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
- return result;
+ if (nb)
+ memcpy(dest-(nb-1), baseb, nb * sizeof(PyObject*));
+ return result;
CopyA:
- assert(nb == 1 && na > 0);
- /* The first element of pb belongs at the front of the merge. */
- dest -= na;
- pa -= na;
- memmove(dest+1, pa+1, na * sizeof(PyObject *));
- *dest = *pb;
- return 0;
+ assert(nb == 1 && na > 0);
+ /* The first element of pb belongs at the front of the merge. */
+ dest -= na;
+ pa -= na;
+ memmove(dest+1, pa+1, na * sizeof(PyObject *));
+ *dest = *pb;
+ return 0;
}
/* Merge the two runs at stack indices i and i+1.
@@ -1728,58 +1728,58 @@ CopyA:
static Py_ssize_t
merge_at(MergeState *ms, Py_ssize_t i)
{
- PyObject **pa, **pb;
- Py_ssize_t na, nb;
- Py_ssize_t k;
- PyObject *compare;
-
- assert(ms != NULL);
- assert(ms->n >= 2);
- assert(i >= 0);
- assert(i == ms->n - 2 || i == ms->n - 3);
-
- pa = ms->pending[i].base;
- na = ms->pending[i].len;
- pb = ms->pending[i+1].base;
- nb = ms->pending[i+1].len;
- assert(na > 0 && nb > 0);
- assert(pa + na == pb);
-
- /* Record the length of the combined runs; if i is the 3rd-last
- * run now, also slide over the last run (which isn't involved
- * in this merge). The current run i+1 goes away in any case.
- */
- ms->pending[i].len = na + nb;
- if (i == ms->n - 3)
- ms->pending[i+1] = ms->pending[i+2];
- --ms->n;
-
- /* Where does b start in a? Elements in a before that can be
- * ignored (already in place).
- */
- compare = ms->compare;
- k = gallop_right(*pb, pa, na, 0, compare);
- if (k < 0)
- return -1;
- pa += k;
- na -= k;
- if (na == 0)
- return 0;
-
- /* Where does a end in b? Elements in b after that can be
- * ignored (already in place).
- */
- nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
- if (nb <= 0)
- return nb;
-
- /* Merge what remains of the runs, using a temp array with
- * min(na, nb) elements.
- */
- if (na <= nb)
- return merge_lo(ms, pa, na, pb, nb);
- else
- return merge_hi(ms, pa, na, pb, nb);
+ PyObject **pa, **pb;
+ Py_ssize_t na, nb;
+ Py_ssize_t k;
+ PyObject *compare;
+
+ assert(ms != NULL);
+ assert(ms->n >= 2);
+ assert(i >= 0);
+ assert(i == ms->n - 2 || i == ms->n - 3);
+
+ pa = ms->pending[i].base;
+ na = ms->pending[i].len;
+ pb = ms->pending[i+1].base;
+ nb = ms->pending[i+1].len;
+ assert(na > 0 && nb > 0);
+ assert(pa + na == pb);
+
+ /* Record the length of the combined runs; if i is the 3rd-last
+ * run now, also slide over the last run (which isn't involved
+ * in this merge). The current run i+1 goes away in any case.
+ */
+ ms->pending[i].len = na + nb;
+ if (i == ms->n - 3)
+ ms->pending[i+1] = ms->pending[i+2];
+ --ms->n;
+
+ /* Where does b start in a? Elements in a before that can be
+ * ignored (already in place).
+ */
+ compare = ms->compare;
+ k = gallop_right(*pb, pa, na, 0, compare);
+ if (k < 0)
+ return -1;
+ pa += k;
+ na -= k;
+ if (na == 0)
+ return 0;
+
+ /* Where does a end in b? Elements in b after that can be
+ * ignored (already in place).
+ */
+ nb = gallop_left(pa[na-1], pb, nb, nb-1, compare);
+ if (nb <= 0)
+ return nb;
+
+ /* Merge what remains of the runs, using a temp array with
+ * min(na, nb) elements.
+ */
+ if (na <= nb)
+ return merge_lo(ms, pa, na, pb, nb);
+ else
+ return merge_hi(ms, pa, na, pb, nb);
}
/* Examine the stack of runs waiting to be merged, merging adjacent runs
@@ -1795,25 +1795,25 @@ merge_at(MergeState *ms, Py_ssize_t i)
static int
merge_collapse(MergeState *ms)
{
- struct s_slice *p = ms->pending;
-
- assert(ms);
- while (ms->n > 1) {
- Py_ssize_t n = ms->n - 2;
- if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
- if (p[n-1].len < p[n+1].len)
- --n;
- if (merge_at(ms, n) < 0)
- return -1;
- }
- else if (p[n].len <= p[n+1].len) {
- if (merge_at(ms, n) < 0)
- return -1;
- }
- else
- break;
- }
- return 0;
+ struct s_slice *p = ms->pending;
+
+ assert(ms);
+ while (ms->n > 1) {
+ Py_ssize_t n = ms->n - 2;
+ if (n > 0 && p[n-1].len <= p[n].len + p[n+1].len) {
+ if (p[n-1].len < p[n+1].len)
+ --n;
+ if (merge_at(ms, n) < 0)
+ return -1;
+ }
+ else if (p[n].len <= p[n+1].len) {
+ if (merge_at(ms, n) < 0)
+ return -1;
+ }
+ else
+ break;
+ }
+ return 0;
}
/* Regardless of invariants, merge all runs on the stack until only one
@@ -1824,17 +1824,17 @@ merge_collapse(MergeState *ms)
static int
merge_force_collapse(MergeState *ms)
{
- struct s_slice *p = ms->pending;
+ struct s_slice *p = ms->pending;
- assert(ms);
- while (ms->n > 1) {
- Py_ssize_t n = ms->n - 2;
- if (n > 0 && p[n-1].len < p[n+1].len)
- --n;
- if (merge_at(ms, n) < 0)
- return -1;
- }
- return 0;
+ assert(ms);
+ while (ms->n > 1) {
+ Py_ssize_t n = ms->n - 2;
+ if (n > 0 && p[n-1].len < p[n+1].len)
+ --n;
+ if (merge_at(ms, n) < 0)
+ return -1;
+ }
+ return 0;
}
/* Compute a good value for the minimum run length; natural runs shorter
@@ -1850,14 +1850,14 @@ merge_force_collapse(MergeState *ms)
static Py_ssize_t
merge_compute_minrun(Py_ssize_t n)
{
- Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
+ Py_ssize_t r = 0; /* becomes 1 if any 1 bits are shifted off */
- assert(n >= 0);
- while (n >= 64) {
- r |= n & 1;
- n >>= 1;
- }
- return n + r;
+ assert(n >= 0);
+ while (n >= 64) {
+ r |= n & 1;
+ n >>= 1;
+ }
+ return n + r;
}
/* Special wrapper to support stable sorting using the decorate-sort-undecorate
@@ -1868,9 +1868,9 @@ merge_compute_minrun(Py_ssize_t n)
the key instead of a full record. */
typedef struct {
- PyObject_HEAD
- PyObject *key;
- PyObject *value;
+ PyObject_HEAD
+ PyObject *key;
+ PyObject *value;
} sortwrapperobject;
PyDoc_STRVAR(sortwrapper_doc, "Object wrapper with a custom sort key.");
@@ -1880,52 +1880,52 @@ static void
sortwrapper_dealloc(sortwrapperobject *);
static PyTypeObject sortwrapper_type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "sortwrapper", /* tp_name */
- sizeof(sortwrapperobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)sortwrapper_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 |
- Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
- sortwrapper_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "sortwrapper", /* tp_name */
+ sizeof(sortwrapperobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)sortwrapper_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 |
+ Py_TPFLAGS_HAVE_RICHCOMPARE, /* tp_flags */
+ sortwrapper_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)sortwrapper_richcompare, /* tp_richcompare */
};
static PyObject *
sortwrapper_richcompare(sortwrapperobject *a, sortwrapperobject *b, int op)
{
- if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
- PyErr_SetString(PyExc_TypeError,
- "expected a sortwrapperobject");
- return NULL;
- }
- return PyObject_RichCompare(a->key, b->key, op);
+ if (!PyObject_TypeCheck(b, &sortwrapper_type)) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a sortwrapperobject");
+ return NULL;
+ }
+ return PyObject_RichCompare(a->key, b->key, op);
}
static void
sortwrapper_dealloc(sortwrapperobject *so)
{
- Py_XDECREF(so->key);
- Py_XDECREF(so->value);
- PyObject_Del(so);
+ Py_XDECREF(so->key);
+ Py_XDECREF(so->value);
+ PyObject_Del(so);
}
/* Returns a new reference to a sortwrapper.
@@ -1934,30 +1934,30 @@ sortwrapper_dealloc(sortwrapperobject *so)
static PyObject *
build_sortwrapper(PyObject *key, PyObject *value)
{
- sortwrapperobject *so;
+ sortwrapperobject *so;
- so = PyObject_New(sortwrapperobject, &sortwrapper_type);
- if (so == NULL)
- return NULL;
- so->key = key;
- so->value = value;
- return (PyObject *)so;
+ so = PyObject_New(sortwrapperobject, &sortwrapper_type);
+ if (so == NULL)
+ return NULL;
+ so->key = key;
+ so->value = value;
+ return (PyObject *)so;
}
/* Returns a new reference to the value underlying the wrapper. */
static PyObject *
sortwrapper_getvalue(PyObject *so)
{
- PyObject *value;
+ PyObject *value;
- if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
- PyErr_SetString(PyExc_TypeError,
- "expected a sortwrapperobject");
- return NULL;
- }
- value = ((sortwrapperobject *)so)->value;
- Py_INCREF(value);
- return value;
+ if (!PyObject_TypeCheck(so, &sortwrapper_type)) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a sortwrapperobject");
+ return NULL;
+ }
+ value = ((sortwrapperobject *)so)->value;
+ Py_INCREF(value);
+ return value;
}
/* Wrapper for user specified cmp functions in combination with a
@@ -1965,73 +1965,73 @@ sortwrapper_getvalue(PyObject *so)
with the actual key instead of the sortwrapper */
typedef struct {
- PyObject_HEAD
- PyObject *func;
+ PyObject_HEAD
+ PyObject *func;
} cmpwrapperobject;
static void
cmpwrapper_dealloc(cmpwrapperobject *co)
{
- Py_XDECREF(co->func);
- PyObject_Del(co);
+ Py_XDECREF(co->func);
+ PyObject_Del(co);
}
static PyObject *
cmpwrapper_call(cmpwrapperobject *co, PyObject *args, PyObject *kwds)
{
- PyObject *x, *y, *xx, *yy;
+ PyObject *x, *y, *xx, *yy;
- if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
- return NULL;
- if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
- !PyObject_TypeCheck(y, &sortwrapper_type)) {
- PyErr_SetString(PyExc_TypeError,
- "expected a sortwrapperobject");
- return NULL;
- }
- xx = ((sortwrapperobject *)x)->key;
- yy = ((sortwrapperobject *)y)->key;
- return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
+ if (!PyArg_UnpackTuple(args, "", 2, 2, &x, &y))
+ return NULL;
+ if (!PyObject_TypeCheck(x, &sortwrapper_type) ||
+ !PyObject_TypeCheck(y, &sortwrapper_type)) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected a sortwrapperobject");
+ return NULL;
+ }
+ xx = ((sortwrapperobject *)x)->key;
+ yy = ((sortwrapperobject *)y)->key;
+ return PyObject_CallFunctionObjArgs(co->func, xx, yy, NULL);
}
PyDoc_STRVAR(cmpwrapper_doc, "cmp() wrapper for sort with custom keys.");
static PyTypeObject cmpwrapper_type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "cmpwrapper", /* tp_name */
- sizeof(cmpwrapperobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)cmpwrapper_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)cmpwrapper_call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- cmpwrapper_doc, /* tp_doc */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "cmpwrapper", /* tp_name */
+ sizeof(cmpwrapperobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)cmpwrapper_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)cmpwrapper_call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ cmpwrapper_doc, /* tp_doc */
};
static PyObject *
build_cmpwrapper(PyObject *cmpfunc)
{
- cmpwrapperobject *co;
+ cmpwrapperobject *co;
- co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
- if (co == NULL)
- return NULL;
- Py_INCREF(cmpfunc);
- co->func = cmpfunc;
- return (PyObject *)co;
+ co = PyObject_New(cmpwrapperobject, &cmpwrapper_type);
+ if (co == NULL)
+ return NULL;
+ Py_INCREF(cmpfunc);
+ co->func = cmpfunc;
+ return (PyObject *)co;
}
/* An adaptive, stable, natural mergesort. See listsort.txt.
@@ -2042,171 +2042,171 @@ build_cmpwrapper(PyObject *cmpfunc)
static PyObject *
listsort(PyListObject *self, PyObject *args, PyObject *kwds)
{
- MergeState ms;
- PyObject **lo, **hi;
- Py_ssize_t nremaining;
- Py_ssize_t minrun;
- Py_ssize_t saved_ob_size, saved_allocated;
- PyObject **saved_ob_item;
- PyObject **final_ob_item;
- PyObject *compare = NULL;
- PyObject *result = NULL; /* guilty until proved innocent */
- int reverse = 0;
- PyObject *keyfunc = NULL;
- Py_ssize_t i;
- PyObject *key, *value, *kvpair;
- static char *kwlist[] = {"cmp", "key", "reverse", 0};
-
- assert(self != NULL);
- assert (PyList_Check(self));
- if (args != NULL) {
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
- kwlist, &compare, &keyfunc, &reverse))
- return NULL;
- }
- if (compare == Py_None)
- compare = NULL;
- if (compare != NULL &&
- PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
- return NULL;
- if (keyfunc == Py_None)
- keyfunc = NULL;
- if (compare != NULL && keyfunc != NULL) {
- compare = build_cmpwrapper(compare);
- if (compare == NULL)
- return NULL;
- } else
- Py_XINCREF(compare);
-
- /* The list is temporarily made empty, so that mutations performed
- * by comparison functions can't affect the slice of memory we're
- * sorting (allowing mutations during sorting is a core-dump
- * factory, since ob_item may change).
- */
- saved_ob_size = Py_SIZE(self);
- saved_ob_item = self->ob_item;
- saved_allocated = self->allocated;
- Py_SIZE(self) = 0;
- self->ob_item = NULL;
- self->allocated = -1; /* any operation will reset it to >= 0 */
-
- if (keyfunc != NULL) {
- for (i=0 ; i < saved_ob_size ; i++) {
- value = saved_ob_item[i];
- key = PyObject_CallFunctionObjArgs(keyfunc, value,
- NULL);
- if (key == NULL) {
- for (i=i-1 ; i>=0 ; i--) {
- kvpair = saved_ob_item[i];
- value = sortwrapper_getvalue(kvpair);
- saved_ob_item[i] = value;
- Py_DECREF(kvpair);
- }
- goto dsu_fail;
- }
- kvpair = build_sortwrapper(key, value);
- if (kvpair == NULL)
- goto dsu_fail;
- saved_ob_item[i] = kvpair;
- }
- }
-
- /* Reverse sort stability achieved by initially reversing the list,
- applying a stable forward sort, then reversing the final result. */
- if (reverse && saved_ob_size > 1)
- reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
-
- merge_init(&ms, compare);
-
- nremaining = saved_ob_size;
- if (nremaining < 2)
- goto succeed;
-
- /* March over the array once, left to right, finding natural runs,
- * and extending short natural runs to minrun elements.
- */
- lo = saved_ob_item;
- hi = lo + nremaining;
- minrun = merge_compute_minrun(nremaining);
- do {
- int descending;
- Py_ssize_t n;
-
- /* Identify next run. */
- n = count_run(lo, hi, compare, &descending);
- if (n < 0)
- goto fail;
- if (descending)
- reverse_slice(lo, lo + n);
- /* If short, extend to min(minrun, nremaining). */
- if (n < minrun) {
- const Py_ssize_t force = nremaining <= minrun ?
- nremaining : minrun;
- if (binarysort(lo, lo + force, lo + n, compare) < 0)
- goto fail;
- n = force;
- }
- /* Push run onto pending-runs stack, and maybe merge. */
- assert(ms.n < MAX_MERGE_PENDING);
- ms.pending[ms.n].base = lo;
- ms.pending[ms.n].len = n;
- ++ms.n;
- if (merge_collapse(&ms) < 0)
- goto fail;
- /* Advance to find next run. */
- lo += n;
- nremaining -= n;
- } while (nremaining);
- assert(lo == hi);
-
- if (merge_force_collapse(&ms) < 0)
- goto fail;
- assert(ms.n == 1);
- assert(ms.pending[0].base == saved_ob_item);
- assert(ms.pending[0].len == saved_ob_size);
+ MergeState ms;
+ PyObject **lo, **hi;
+ Py_ssize_t nremaining;
+ Py_ssize_t minrun;
+ Py_ssize_t saved_ob_size, saved_allocated;
+ PyObject **saved_ob_item;
+ PyObject **final_ob_item;
+ PyObject *compare = NULL;
+ PyObject *result = NULL; /* guilty until proved innocent */
+ int reverse = 0;
+ PyObject *keyfunc = NULL;
+ Py_ssize_t i;
+ PyObject *key, *value, *kvpair;
+ static char *kwlist[] = {"cmp", "key", "reverse", 0};
+
+ assert(self != NULL);
+ assert (PyList_Check(self));
+ if (args != NULL) {
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi:sort",
+ kwlist, &compare, &keyfunc, &reverse))
+ return NULL;
+ }
+ if (compare == Py_None)
+ compare = NULL;
+ if (compare != NULL &&
+ PyErr_WarnPy3k("the cmp argument is not supported in 3.x", 1) < 0)
+ return NULL;
+ if (keyfunc == Py_None)
+ keyfunc = NULL;
+ if (compare != NULL && keyfunc != NULL) {
+ compare = build_cmpwrapper(compare);
+ if (compare == NULL)
+ return NULL;
+ } else
+ Py_XINCREF(compare);
+
+ /* The list is temporarily made empty, so that mutations performed
+ * by comparison functions can't affect the slice of memory we're
+ * sorting (allowing mutations during sorting is a core-dump
+ * factory, since ob_item may change).
+ */
+ saved_ob_size = Py_SIZE(self);
+ saved_ob_item = self->ob_item;
+ saved_allocated = self->allocated;
+ Py_SIZE(self) = 0;
+ self->ob_item = NULL;
+ self->allocated = -1; /* any operation will reset it to >= 0 */
+
+ if (keyfunc != NULL) {
+ for (i=0 ; i < saved_ob_size ; i++) {
+ value = saved_ob_item[i];
+ key = PyObject_CallFunctionObjArgs(keyfunc, value,
+ NULL);
+ if (key == NULL) {
+ for (i=i-1 ; i>=0 ; i--) {
+ kvpair = saved_ob_item[i];
+ value = sortwrapper_getvalue(kvpair);
+ saved_ob_item[i] = value;
+ Py_DECREF(kvpair);
+ }
+ goto dsu_fail;
+ }
+ kvpair = build_sortwrapper(key, value);
+ if (kvpair == NULL)
+ goto dsu_fail;
+ saved_ob_item[i] = kvpair;
+ }
+ }
+
+ /* Reverse sort stability achieved by initially reversing the list,
+ applying a stable forward sort, then reversing the final result. */
+ if (reverse && saved_ob_size > 1)
+ reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
+
+ merge_init(&ms, compare);
+
+ nremaining = saved_ob_size;
+ if (nremaining < 2)
+ goto succeed;
+
+ /* March over the array once, left to right, finding natural runs,
+ * and extending short natural runs to minrun elements.
+ */
+ lo = saved_ob_item;
+ hi = lo + nremaining;
+ minrun = merge_compute_minrun(nremaining);
+ do {
+ int descending;
+ Py_ssize_t n;
+
+ /* Identify next run. */
+ n = count_run(lo, hi, compare, &descending);
+ if (n < 0)
+ goto fail;
+ if (descending)
+ reverse_slice(lo, lo + n);
+ /* If short, extend to min(minrun, nremaining). */
+ if (n < minrun) {
+ const Py_ssize_t force = nremaining <= minrun ?
+ nremaining : minrun;
+ if (binarysort(lo, lo + force, lo + n, compare) < 0)
+ goto fail;
+ n = force;
+ }
+ /* Push run onto pending-runs stack, and maybe merge. */
+ assert(ms.n < MAX_MERGE_PENDING);
+ ms.pending[ms.n].base = lo;
+ ms.pending[ms.n].len = n;
+ ++ms.n;
+ if (merge_collapse(&ms) < 0)
+ goto fail;
+ /* Advance to find next run. */
+ lo += n;
+ nremaining -= n;
+ } while (nremaining);
+ assert(lo == hi);
+
+ if (merge_force_collapse(&ms) < 0)
+ goto fail;
+ assert(ms.n == 1);
+ assert(ms.pending[0].base == saved_ob_item);
+ assert(ms.pending[0].len == saved_ob_size);
succeed:
- result = Py_None;
+ result = Py_None;
fail:
- if (keyfunc != NULL) {
- for (i=0 ; i < saved_ob_size ; i++) {
- kvpair = saved_ob_item[i];
- value = sortwrapper_getvalue(kvpair);
- saved_ob_item[i] = value;
- Py_DECREF(kvpair);
- }
- }
-
- if (self->allocated != -1 && result != NULL) {
- /* The user mucked with the list during the sort,
- * and we don't already have another error to report.
- */
- PyErr_SetString(PyExc_ValueError, "list modified during sort");
- result = NULL;
- }
-
- if (reverse && saved_ob_size > 1)
- reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
-
- merge_freemem(&ms);
+ if (keyfunc != NULL) {
+ for (i=0 ; i < saved_ob_size ; i++) {
+ kvpair = saved_ob_item[i];
+ value = sortwrapper_getvalue(kvpair);
+ saved_ob_item[i] = value;
+ Py_DECREF(kvpair);
+ }
+ }
+
+ if (self->allocated != -1 && result != NULL) {
+ /* The user mucked with the list during the sort,
+ * and we don't already have another error to report.
+ */
+ PyErr_SetString(PyExc_ValueError, "list modified during sort");
+ result = NULL;
+ }
+
+ if (reverse && saved_ob_size > 1)
+ reverse_slice(saved_ob_item, saved_ob_item + saved_ob_size);
+
+ merge_freemem(&ms);
dsu_fail:
- final_ob_item = self->ob_item;
- i = Py_SIZE(self);
- Py_SIZE(self) = saved_ob_size;
- self->ob_item = saved_ob_item;
- self->allocated = saved_allocated;
- if (final_ob_item != NULL) {
- /* we cannot use list_clear() for this because it does not
- guarantee that the list is really empty when it returns */
- while (--i >= 0) {
- Py_XDECREF(final_ob_item[i]);
- }
- PyMem_FREE(final_ob_item);
- }
- Py_XDECREF(compare);
- Py_XINCREF(result);
- return result;
+ final_ob_item = self->ob_item;
+ i = Py_SIZE(self);
+ Py_SIZE(self) = saved_ob_size;
+ self->ob_item = saved_ob_item;
+ self->allocated = saved_allocated;
+ if (final_ob_item != NULL) {
+ /* we cannot use list_clear() for this because it does not
+ guarantee that the list is really empty when it returns */
+ while (--i >= 0) {
+ Py_XDECREF(final_ob_item[i]);
+ }
+ PyMem_FREE(final_ob_item);
+ }
+ Py_XDECREF(compare);
+ Py_XINCREF(result);
+ return result;
}
#undef IFLT
#undef ISLT
@@ -2214,262 +2214,262 @@ dsu_fail:
int
PyList_Sort(PyObject *v)
{
- if (v == NULL || !PyList_Check(v)) {
- PyErr_BadInternalCall();
- return -1;
- }
- v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
- if (v == NULL)
- return -1;
- Py_DECREF(v);
- return 0;
+ if (v == NULL || !PyList_Check(v)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ v = listsort((PyListObject *)v, (PyObject *)NULL, (PyObject *)NULL);
+ if (v == NULL)
+ return -1;
+ Py_DECREF(v);
+ return 0;
}
static PyObject *
listreverse(PyListObject *self)
{
- if (Py_SIZE(self) > 1)
- reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
- Py_RETURN_NONE;
+ if (Py_SIZE(self) > 1)
+ reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
+ Py_RETURN_NONE;
}
int
PyList_Reverse(PyObject *v)
{
- PyListObject *self = (PyListObject *)v;
+ PyListObject *self = (PyListObject *)v;
- if (v == NULL || !PyList_Check(v)) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (Py_SIZE(self) > 1)
- reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
- return 0;
+ if (v == NULL || !PyList_Check(v)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (Py_SIZE(self) > 1)
+ reverse_slice(self->ob_item, self->ob_item + Py_SIZE(self));
+ return 0;
}
PyObject *
PyList_AsTuple(PyObject *v)
{
- PyObject *w;
- PyObject **p, **q;
- Py_ssize_t n;
- if (v == NULL || !PyList_Check(v)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- n = Py_SIZE(v);
- w = PyTuple_New(n);
- if (w == NULL)
- return NULL;
- p = ((PyTupleObject *)w)->ob_item;
- q = ((PyListObject *)v)->ob_item;
- while (--n >= 0) {
- Py_INCREF(*q);
- *p = *q;
- p++;
- q++;
- }
- return w;
+ PyObject *w;
+ PyObject **p, **q;
+ Py_ssize_t n;
+ if (v == NULL || !PyList_Check(v)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ n = Py_SIZE(v);
+ w = PyTuple_New(n);
+ if (w == NULL)
+ return NULL;
+ p = ((PyTupleObject *)w)->ob_item;
+ q = ((PyListObject *)v)->ob_item;
+ while (--n >= 0) {
+ Py_INCREF(*q);
+ *p = *q;
+ p++;
+ q++;
+ }
+ return w;
}
static PyObject *
listindex(PyListObject *self, PyObject *args)
{
- Py_ssize_t i, start=0, stop=Py_SIZE(self);
- PyObject *v, *format_tuple, *err_string;
- static PyObject *err_format = NULL;
-
- if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
- _PyEval_SliceIndex, &start,
- _PyEval_SliceIndex, &stop))
- return NULL;
- if (start < 0) {
- start += Py_SIZE(self);
- if (start < 0)
- start = 0;
- }
- if (stop < 0) {
- stop += Py_SIZE(self);
- if (stop < 0)
- stop = 0;
- }
- for (i = start; i < stop && i < Py_SIZE(self); i++) {
- int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
- if (cmp > 0)
- return PyInt_FromSsize_t(i);
- else if (cmp < 0)
- return NULL;
- }
- if (err_format == NULL) {
- err_format = PyString_FromString("%r is not in list");
- if (err_format == NULL)
- return NULL;
- }
- format_tuple = PyTuple_Pack(1, v);
- if (format_tuple == NULL)
- return NULL;
- err_string = PyString_Format(err_format, format_tuple);
- Py_DECREF(format_tuple);
- if (err_string == NULL)
- return NULL;
- PyErr_SetObject(PyExc_ValueError, err_string);
- Py_DECREF(err_string);
- return NULL;
+ Py_ssize_t i, start=0, stop=Py_SIZE(self);
+ PyObject *v, *format_tuple, *err_string;
+ static PyObject *err_format = NULL;
+
+ if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
+ _PyEval_SliceIndex, &start,
+ _PyEval_SliceIndex, &stop))
+ return NULL;
+ if (start < 0) {
+ start += Py_SIZE(self);
+ if (start < 0)
+ start = 0;
+ }
+ if (stop < 0) {
+ stop += Py_SIZE(self);
+ if (stop < 0)
+ stop = 0;
+ }
+ for (i = start; i < stop && i < Py_SIZE(self); i++) {
+ int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
+ if (cmp > 0)
+ return PyInt_FromSsize_t(i);
+ else if (cmp < 0)
+ return NULL;
+ }
+ if (err_format == NULL) {
+ err_format = PyString_FromString("%r is not in list");
+ if (err_format == NULL)
+ return NULL;
+ }
+ format_tuple = PyTuple_Pack(1, v);
+ if (format_tuple == NULL)
+ return NULL;
+ err_string = PyString_Format(err_format, format_tuple);
+ Py_DECREF(format_tuple);
+ if (err_string == NULL)
+ return NULL;
+ PyErr_SetObject(PyExc_ValueError, err_string);
+ Py_DECREF(err_string);
+ return NULL;
}
static PyObject *
listcount(PyListObject *self, PyObject *v)
{
- Py_ssize_t count = 0;
- Py_ssize_t i;
+ Py_ssize_t count = 0;
+ Py_ssize_t i;
- for (i = 0; i < Py_SIZE(self); i++) {
- int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
- if (cmp > 0)
- count++;
- else if (cmp < 0)
- return NULL;
- }
- return PyInt_FromSsize_t(count);
+ for (i = 0; i < Py_SIZE(self); i++) {
+ int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
+ if (cmp > 0)
+ count++;
+ else if (cmp < 0)
+ return NULL;
+ }
+ return PyInt_FromSsize_t(count);
}
static PyObject *
listremove(PyListObject *self, PyObject *v)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i = 0; i < Py_SIZE(self); i++) {
- int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
- if (cmp > 0) {
- if (list_ass_slice(self, i, i+1,
- (PyObject *)NULL) == 0)
- Py_RETURN_NONE;
- return NULL;
- }
- else if (cmp < 0)
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
- return NULL;
+ for (i = 0; i < Py_SIZE(self); i++) {
+ int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
+ if (cmp > 0) {
+ if (list_ass_slice(self, i, i+1,
+ (PyObject *)NULL) == 0)
+ Py_RETURN_NONE;
+ return NULL;
+ }
+ else if (cmp < 0)
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "list.remove(x): x not in list");
+ return NULL;
}
static int
list_traverse(PyListObject *o, visitproc visit, void *arg)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i = Py_SIZE(o); --i >= 0; )
- Py_VISIT(o->ob_item[i]);
- return 0;
+ for (i = Py_SIZE(o); --i >= 0; )
+ Py_VISIT(o->ob_item[i]);
+ return 0;
}
static PyObject *
list_richcompare(PyObject *v, PyObject *w, int op)
{
- PyListObject *vl, *wl;
- Py_ssize_t i;
-
- if (!PyList_Check(v) || !PyList_Check(w)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- vl = (PyListObject *)v;
- wl = (PyListObject *)w;
-
- if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
- /* Shortcut: if the lengths differ, the lists differ */
- PyObject *res;
- if (op == Py_EQ)
- res = Py_False;
- else
- res = Py_True;
- Py_INCREF(res);
- return res;
- }
-
- /* Search for the first index where items are different */
- for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
- int k = PyObject_RichCompareBool(vl->ob_item[i],
- wl->ob_item[i], Py_EQ);
- if (k < 0)
- return NULL;
- if (!k)
- break;
- }
-
- if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
- /* No more items to compare -- compare sizes */
- Py_ssize_t vs = Py_SIZE(vl);
- Py_ssize_t ws = Py_SIZE(wl);
- int cmp;
- PyObject *res;
- switch (op) {
- case Py_LT: cmp = vs < ws; break;
- case Py_LE: cmp = vs <= ws; break;
- case Py_EQ: cmp = vs == ws; break;
- case Py_NE: cmp = vs != ws; break;
- case Py_GT: cmp = vs > ws; break;
- case Py_GE: cmp = vs >= ws; break;
- default: return NULL; /* cannot happen */
- }
- if (cmp)
- res = Py_True;
- else
- res = Py_False;
- Py_INCREF(res);
- return res;
- }
-
- /* We have an item that differs -- shortcuts for EQ/NE */
- if (op == Py_EQ) {
- Py_INCREF(Py_False);
- return Py_False;
- }
- if (op == Py_NE) {
- Py_INCREF(Py_True);
- return Py_True;
- }
-
- /* Compare the final item again using the proper operator */
- return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
+ PyListObject *vl, *wl;
+ Py_ssize_t i;
+
+ if (!PyList_Check(v) || !PyList_Check(w)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ vl = (PyListObject *)v;
+ wl = (PyListObject *)w;
+
+ if (Py_SIZE(vl) != Py_SIZE(wl) && (op == Py_EQ || op == Py_NE)) {
+ /* Shortcut: if the lengths differ, the lists differ */
+ PyObject *res;
+ if (op == Py_EQ)
+ res = Py_False;
+ else
+ res = Py_True;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* Search for the first index where items are different */
+ for (i = 0; i < Py_SIZE(vl) && i < Py_SIZE(wl); i++) {
+ int k = PyObject_RichCompareBool(vl->ob_item[i],
+ wl->ob_item[i], Py_EQ);
+ if (k < 0)
+ return NULL;
+ if (!k)
+ break;
+ }
+
+ if (i >= Py_SIZE(vl) || i >= Py_SIZE(wl)) {
+ /* No more items to compare -- compare sizes */
+ Py_ssize_t vs = Py_SIZE(vl);
+ Py_ssize_t ws = Py_SIZE(wl);
+ int cmp;
+ PyObject *res;
+ switch (op) {
+ case Py_LT: cmp = vs < ws; break;
+ case Py_LE: cmp = vs <= ws; break;
+ case Py_EQ: cmp = vs == ws; break;
+ case Py_NE: cmp = vs != ws; break;
+ case Py_GT: cmp = vs > ws; break;
+ case Py_GE: cmp = vs >= ws; break;
+ default: return NULL; /* cannot happen */
+ }
+ if (cmp)
+ res = Py_True;
+ else
+ res = Py_False;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* We have an item that differs -- shortcuts for EQ/NE */
+ if (op == Py_EQ) {
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ if (op == Py_NE) {
+ Py_INCREF(Py_True);
+ return Py_True;
+ }
+
+ /* Compare the final item again using the proper operator */
+ return PyObject_RichCompare(vl->ob_item[i], wl->ob_item[i], op);
}
static int
list_init(PyListObject *self, PyObject *args, PyObject *kw)
{
- PyObject *arg = NULL;
- static char *kwlist[] = {"sequence", 0};
+ PyObject *arg = NULL;
+ static char *kwlist[] = {"sequence", 0};
- if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
- return -1;
+ if (!PyArg_ParseTupleAndKeywords(args, kw, "|O:list", kwlist, &arg))
+ return -1;
- /* Verify list invariants established by PyType_GenericAlloc() */
- assert(0 <= Py_SIZE(self));
- assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
- assert(self->ob_item != NULL ||
- self->allocated == 0 || self->allocated == -1);
+ /* Verify list invariants established by PyType_GenericAlloc() */
+ assert(0 <= Py_SIZE(self));
+ assert(Py_SIZE(self) <= self->allocated || self->allocated == -1);
+ assert(self->ob_item != NULL ||
+ self->allocated == 0 || self->allocated == -1);
- /* Empty previous contents */
- if (self->ob_item != NULL) {
- (void)list_clear(self);
- }
- if (arg != NULL) {
- PyObject *rv = listextend(self, arg);
- if (rv == NULL)
- return -1;
- Py_DECREF(rv);
- }
- return 0;
+ /* Empty previous contents */
+ if (self->ob_item != NULL) {
+ (void)list_clear(self);
+ }
+ if (arg != NULL) {
+ PyObject *rv = listextend(self, arg);
+ if (rv == NULL)
+ return -1;
+ Py_DECREF(rv);
+ }
+ return 0;
}
static PyObject *
list_sizeof(PyListObject *self)
{
- Py_ssize_t res;
+ Py_ssize_t res;
- res = sizeof(PyListObject) + self->allocated * sizeof(void*);
- return PyInt_FromSsize_t(res);
+ res = sizeof(PyListObject) + self->allocated * sizeof(void*);
+ return PyInt_FromSsize_t(res);
}
static PyObject *list_iter(PyObject *seq);
@@ -2507,32 +2507,32 @@ cmp(x, y) -> -1, 0, 1");
static PyObject *list_subscript(PyListObject*, PyObject*);
static PyMethodDef list_methods[] = {
- {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
- {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
- {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
- {"append", (PyCFunction)listappend, METH_O, append_doc},
- {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
- {"extend", (PyCFunction)listextend, METH_O, extend_doc},
- {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
- {"remove", (PyCFunction)listremove, METH_O, remove_doc},
- {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
- {"count", (PyCFunction)listcount, METH_O, count_doc},
- {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
- {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
- {NULL, NULL} /* sentinel */
+ {"__getitem__", (PyCFunction)list_subscript, METH_O|METH_COEXIST, getitem_doc},
+ {"__reversed__",(PyCFunction)list_reversed, METH_NOARGS, reversed_doc},
+ {"__sizeof__", (PyCFunction)list_sizeof, METH_NOARGS, sizeof_doc},
+ {"append", (PyCFunction)listappend, METH_O, append_doc},
+ {"insert", (PyCFunction)listinsert, METH_VARARGS, insert_doc},
+ {"extend", (PyCFunction)listextend, METH_O, extend_doc},
+ {"pop", (PyCFunction)listpop, METH_VARARGS, pop_doc},
+ {"remove", (PyCFunction)listremove, METH_O, remove_doc},
+ {"index", (PyCFunction)listindex, METH_VARARGS, index_doc},
+ {"count", (PyCFunction)listcount, METH_O, count_doc},
+ {"reverse", (PyCFunction)listreverse, METH_NOARGS, reverse_doc},
+ {"sort", (PyCFunction)listsort, METH_VARARGS | METH_KEYWORDS, sort_doc},
+ {NULL, NULL} /* sentinel */
};
static PySequenceMethods list_as_sequence = {
- (lenfunc)list_length, /* sq_length */
- (binaryfunc)list_concat, /* sq_concat */
- (ssizeargfunc)list_repeat, /* sq_repeat */
- (ssizeargfunc)list_item, /* sq_item */
- (ssizessizeargfunc)list_slice, /* sq_slice */
- (ssizeobjargproc)list_ass_item, /* sq_ass_item */
- (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
- (objobjproc)list_contains, /* sq_contains */
- (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
- (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
+ (lenfunc)list_length, /* sq_length */
+ (binaryfunc)list_concat, /* sq_concat */
+ (ssizeargfunc)list_repeat, /* sq_repeat */
+ (ssizeargfunc)list_item, /* sq_item */
+ (ssizessizeargfunc)list_slice, /* sq_slice */
+ (ssizeobjargproc)list_ass_item, /* sq_ass_item */
+ (ssizessizeobjargproc)list_ass_slice, /* sq_ass_slice */
+ (objobjproc)list_contains, /* sq_contains */
+ (binaryfunc)list_inplace_concat, /* sq_inplace_concat */
+ (ssizeargfunc)list_inplace_repeat, /* sq_inplace_repeat */
};
PyDoc_STRVAR(list_doc,
@@ -2543,275 +2543,275 @@ PyDoc_STRVAR(list_doc,
static PyObject *
list_subscript(PyListObject* self, PyObject* item)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i;
- i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += PyList_GET_SIZE(self);
- return list_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength, cur, i;
- PyObject* result;
- PyObject* it;
- PyObject **src, **dest;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
- &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyList_New(0);
- }
- else if (step == 1) {
- return list_slice(self, start, stop);
- }
- else {
- result = PyList_New(slicelength);
- if (!result) return NULL;
-
- src = self->ob_item;
- dest = ((PyListObject *)result)->ob_item;
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- it = src[cur];
- Py_INCREF(it);
- dest[i] = it;
- }
-
- return result;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "list indices must be integers, not %.200s",
- item->ob_type->tp_name);
- return NULL;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i;
+ i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += PyList_GET_SIZE(self);
+ return list_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength, cur, i;
+ PyObject* result;
+ PyObject* it;
+ PyObject **src, **dest;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+ &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyList_New(0);
+ }
+ else if (step == 1) {
+ return list_slice(self, start, stop);
+ }
+ else {
+ result = PyList_New(slicelength);
+ if (!result) return NULL;
+
+ src = self->ob_item;
+ dest = ((PyListObject *)result)->ob_item;
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ it = src[cur];
+ Py_INCREF(it);
+ dest[i] = it;
+ }
+
+ return result;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "list indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return NULL;
+ }
}
static int
list_ass_subscript(PyListObject* self, PyObject* item, PyObject* value)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0)
- i += PyList_GET_SIZE(self);
- return list_ass_item(self, i, value);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
- &start, &stop, &step, &slicelength) < 0) {
- return -1;
- }
-
- if (step == 1)
- return list_ass_slice(self, start, stop, value);
-
- /* Make sure s[5:2] = [..] inserts at the right place:
- before 5, not before 2. */
- if ((step < 0 && start < stop) ||
- (step > 0 && start > stop))
- stop = start;
-
- if (value == NULL) {
- /* delete slice */
- PyObject **garbage;
- size_t cur;
- Py_ssize_t i;
-
- if (slicelength <= 0)
- return 0;
-
- if (step < 0) {
- stop = start + 1;
- start = stop + step*(slicelength - 1) - 1;
- step = -step;
- }
-
- assert((size_t)slicelength <=
- PY_SIZE_MAX / sizeof(PyObject*));
-
- garbage = (PyObject**)
- PyMem_MALLOC(slicelength*sizeof(PyObject*));
- if (!garbage) {
- PyErr_NoMemory();
- return -1;
- }
-
- /* drawing pictures might help understand these for
- loops. Basically, we memmove the parts of the
- list that are *not* part of the slice: step-1
- items for each item that is part of the slice,
- and then tail end of the list that was not
- covered by the slice */
- for (cur = start, i = 0;
- cur < (size_t)stop;
- cur += step, i++) {
- Py_ssize_t lim = step - 1;
-
- garbage[i] = PyList_GET_ITEM(self, cur);
-
- if (cur + step >= (size_t)Py_SIZE(self)) {
- lim = Py_SIZE(self) - cur - 1;
- }
-
- memmove(self->ob_item + cur - i,
- self->ob_item + cur + 1,
- lim * sizeof(PyObject *));
- }
- cur = start + slicelength*step;
- if (cur < (size_t)Py_SIZE(self)) {
- memmove(self->ob_item + cur - slicelength,
- self->ob_item + cur,
- (Py_SIZE(self) - cur) *
- sizeof(PyObject *));
- }
-
- Py_SIZE(self) -= slicelength;
- list_resize(self, Py_SIZE(self));
-
- for (i = 0; i < slicelength; i++) {
- Py_DECREF(garbage[i]);
- }
- PyMem_FREE(garbage);
-
- return 0;
- }
- else {
- /* assign slice */
- PyObject *ins, *seq;
- PyObject **garbage, **seqitems, **selfitems;
- Py_ssize_t cur, i;
-
- /* protect against a[::-1] = a */
- if (self == (PyListObject*)value) {
- seq = list_slice((PyListObject*)value, 0,
- PyList_GET_SIZE(value));
- }
- else {
- seq = PySequence_Fast(value,
- "must assign iterable "
- "to extended slice");
- }
- if (!seq)
- return -1;
-
- if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
- PyErr_Format(PyExc_ValueError,
- "attempt to assign sequence of "
- "size %zd to extended slice of "
- "size %zd",
- PySequence_Fast_GET_SIZE(seq),
- slicelength);
- Py_DECREF(seq);
- return -1;
- }
-
- if (!slicelength) {
- Py_DECREF(seq);
- return 0;
- }
-
- garbage = (PyObject**)
- PyMem_MALLOC(slicelength*sizeof(PyObject*));
- if (!garbage) {
- Py_DECREF(seq);
- PyErr_NoMemory();
- return -1;
- }
-
- selfitems = self->ob_item;
- seqitems = PySequence_Fast_ITEMS(seq);
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- garbage[i] = selfitems[cur];
- ins = seqitems[i];
- Py_INCREF(ins);
- selfitems[cur] = ins;
- }
-
- for (i = 0; i < slicelength; i++) {
- Py_DECREF(garbage[i]);
- }
-
- PyMem_FREE(garbage);
- Py_DECREF(seq);
-
- return 0;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "list indices must be integers, not %.200s",
- item->ob_type->tp_name);
- return -1;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0)
+ i += PyList_GET_SIZE(self);
+ return list_ass_item(self, i, value);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item, Py_SIZE(self),
+ &start, &stop, &step, &slicelength) < 0) {
+ return -1;
+ }
+
+ if (step == 1)
+ return list_ass_slice(self, start, stop, value);
+
+ /* Make sure s[5:2] = [..] inserts at the right place:
+ before 5, not before 2. */
+ if ((step < 0 && start < stop) ||
+ (step > 0 && start > stop))
+ stop = start;
+
+ if (value == NULL) {
+ /* delete slice */
+ PyObject **garbage;
+ size_t cur;
+ Py_ssize_t i;
+
+ if (slicelength <= 0)
+ return 0;
+
+ if (step < 0) {
+ stop = start + 1;
+ start = stop + step*(slicelength - 1) - 1;
+ step = -step;
+ }
+
+ assert((size_t)slicelength <=
+ PY_SIZE_MAX / sizeof(PyObject*));
+
+ garbage = (PyObject**)
+ PyMem_MALLOC(slicelength*sizeof(PyObject*));
+ if (!garbage) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ /* drawing pictures might help understand these for
+ loops. Basically, we memmove the parts of the
+ list that are *not* part of the slice: step-1
+ items for each item that is part of the slice,
+ and then tail end of the list that was not
+ covered by the slice */
+ for (cur = start, i = 0;
+ cur < (size_t)stop;
+ cur += step, i++) {
+ Py_ssize_t lim = step - 1;
+
+ garbage[i] = PyList_GET_ITEM(self, cur);
+
+ if (cur + step >= (size_t)Py_SIZE(self)) {
+ lim = Py_SIZE(self) - cur - 1;
+ }
+
+ memmove(self->ob_item + cur - i,
+ self->ob_item + cur + 1,
+ lim * sizeof(PyObject *));
+ }
+ cur = start + slicelength*step;
+ if (cur < (size_t)Py_SIZE(self)) {
+ memmove(self->ob_item + cur - slicelength,
+ self->ob_item + cur,
+ (Py_SIZE(self) - cur) *
+ sizeof(PyObject *));
+ }
+
+ Py_SIZE(self) -= slicelength;
+ list_resize(self, Py_SIZE(self));
+
+ for (i = 0; i < slicelength; i++) {
+ Py_DECREF(garbage[i]);
+ }
+ PyMem_FREE(garbage);
+
+ return 0;
+ }
+ else {
+ /* assign slice */
+ PyObject *ins, *seq;
+ PyObject **garbage, **seqitems, **selfitems;
+ Py_ssize_t cur, i;
+
+ /* protect against a[::-1] = a */
+ if (self == (PyListObject*)value) {
+ seq = list_slice((PyListObject*)value, 0,
+ PyList_GET_SIZE(value));
+ }
+ else {
+ seq = PySequence_Fast(value,
+ "must assign iterable "
+ "to extended slice");
+ }
+ if (!seq)
+ return -1;
+
+ if (PySequence_Fast_GET_SIZE(seq) != slicelength) {
+ PyErr_Format(PyExc_ValueError,
+ "attempt to assign sequence of "
+ "size %zd to extended slice of "
+ "size %zd",
+ PySequence_Fast_GET_SIZE(seq),
+ slicelength);
+ Py_DECREF(seq);
+ return -1;
+ }
+
+ if (!slicelength) {
+ Py_DECREF(seq);
+ return 0;
+ }
+
+ garbage = (PyObject**)
+ PyMem_MALLOC(slicelength*sizeof(PyObject*));
+ if (!garbage) {
+ Py_DECREF(seq);
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ selfitems = self->ob_item;
+ seqitems = PySequence_Fast_ITEMS(seq);
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ garbage[i] = selfitems[cur];
+ ins = seqitems[i];
+ Py_INCREF(ins);
+ selfitems[cur] = ins;
+ }
+
+ for (i = 0; i < slicelength; i++) {
+ Py_DECREF(garbage[i]);
+ }
+
+ PyMem_FREE(garbage);
+ Py_DECREF(seq);
+
+ return 0;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "list indices must be integers, not %.200s",
+ item->ob_type->tp_name);
+ return -1;
+ }
}
static PyMappingMethods list_as_mapping = {
- (lenfunc)list_length,
- (binaryfunc)list_subscript,
- (objobjargproc)list_ass_subscript
+ (lenfunc)list_length,
+ (binaryfunc)list_subscript,
+ (objobjargproc)list_ass_subscript
};
PyTypeObject PyList_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "list",
- sizeof(PyListObject),
- 0,
- (destructor)list_dealloc, /* tp_dealloc */
- (printfunc)list_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)list_repr, /* tp_repr */
- 0, /* tp_as_number */
- &list_as_sequence, /* tp_as_sequence */
- &list_as_mapping, /* tp_as_mapping */
- (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
- list_doc, /* tp_doc */
- (traverseproc)list_traverse, /* tp_traverse */
- (inquiry)list_clear, /* tp_clear */
- list_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- list_iter, /* tp_iter */
- 0, /* tp_iternext */
- list_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 */
- (initproc)list_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "list",
+ sizeof(PyListObject),
+ 0,
+ (destructor)list_dealloc, /* tp_dealloc */
+ (printfunc)list_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)list_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &list_as_sequence, /* tp_as_sequence */
+ &list_as_mapping, /* tp_as_mapping */
+ (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LIST_SUBCLASS, /* tp_flags */
+ list_doc, /* tp_doc */
+ (traverseproc)list_traverse, /* tp_traverse */
+ (inquiry)list_clear, /* tp_clear */
+ list_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ list_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ list_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 */
+ (initproc)list_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/*********************** List Iterator **************************/
typedef struct {
- PyObject_HEAD
- long it_index;
- PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
+ PyObject_HEAD
+ long it_index;
+ PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
} listiterobject;
static PyObject *list_iter(PyObject *);
@@ -2823,119 +2823,119 @@ static PyObject *listiter_len(listiterobject *);
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef listiter_methods[] = {
- {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)listiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyListIter_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "listiterator", /* tp_name */
- sizeof(listiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)listiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)listiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)listiter_next, /* tp_iternext */
- listiter_methods, /* tp_methods */
- 0, /* tp_members */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "listiterator", /* tp_name */
+ sizeof(listiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)listiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)listiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)listiter_next, /* tp_iternext */
+ listiter_methods, /* tp_methods */
+ 0, /* tp_members */
};
static PyObject *
list_iter(PyObject *seq)
{
- listiterobject *it;
+ listiterobject *it;
- if (!PyList_Check(seq)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- it = PyObject_GC_New(listiterobject, &PyListIter_Type);
- if (it == NULL)
- return NULL;
- it->it_index = 0;
- Py_INCREF(seq);
- it->it_seq = (PyListObject *)seq;
- _PyObject_GC_TRACK(it);
- return (PyObject *)it;
+ if (!PyList_Check(seq)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ it = PyObject_GC_New(listiterobject, &PyListIter_Type);
+ if (it == NULL)
+ return NULL;
+ it->it_index = 0;
+ Py_INCREF(seq);
+ it->it_seq = (PyListObject *)seq;
+ _PyObject_GC_TRACK(it);
+ return (PyObject *)it;
}
static void
listiter_dealloc(listiterobject *it)
{
- _PyObject_GC_UNTRACK(it);
- Py_XDECREF(it->it_seq);
- PyObject_GC_Del(it);
+ _PyObject_GC_UNTRACK(it);
+ Py_XDECREF(it->it_seq);
+ PyObject_GC_Del(it);
}
static int
listiter_traverse(listiterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->it_seq);
- return 0;
+ Py_VISIT(it->it_seq);
+ return 0;
}
static PyObject *
listiter_next(listiterobject *it)
{
- PyListObject *seq;
- PyObject *item;
+ PyListObject *seq;
+ PyObject *item;
- assert(it != NULL);
- seq = it->it_seq;
- if (seq == NULL)
- return NULL;
- assert(PyList_Check(seq));
+ assert(it != NULL);
+ seq = it->it_seq;
+ if (seq == NULL)
+ return NULL;
+ assert(PyList_Check(seq));
- if (it->it_index < PyList_GET_SIZE(seq)) {
- item = PyList_GET_ITEM(seq, it->it_index);
- ++it->it_index;
- Py_INCREF(item);
- return item;
- }
+ if (it->it_index < PyList_GET_SIZE(seq)) {
+ item = PyList_GET_ITEM(seq, it->it_index);
+ ++it->it_index;
+ Py_INCREF(item);
+ return item;
+ }
- Py_DECREF(seq);
- it->it_seq = NULL;
- return NULL;
+ Py_DECREF(seq);
+ it->it_seq = NULL;
+ return NULL;
}
static PyObject *
listiter_len(listiterobject *it)
{
- Py_ssize_t len;
- if (it->it_seq) {
- len = PyList_GET_SIZE(it->it_seq) - it->it_index;
- if (len >= 0)
- return PyInt_FromSsize_t(len);
- }
- return PyInt_FromLong(0);
+ Py_ssize_t len;
+ if (it->it_seq) {
+ len = PyList_GET_SIZE(it->it_seq) - it->it_index;
+ if (len >= 0)
+ return PyInt_FromSsize_t(len);
+ }
+ return PyInt_FromLong(0);
}
/*********************** List Reverse Iterator **************************/
typedef struct {
- PyObject_HEAD
- Py_ssize_t it_index;
- PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
+ PyObject_HEAD
+ Py_ssize_t it_index;
+ PyListObject *it_seq; /* Set to NULL when iterator is exhausted */
} listreviterobject;
static PyObject *list_reversed(PyListObject *, PyObject *);
@@ -2945,100 +2945,100 @@ static PyObject *listreviter_next(listreviterobject *);
static PyObject *listreviter_len(listreviterobject *);
static PyMethodDef listreviter_methods[] = {
- {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)listreviter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyListRevIter_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "listreverseiterator", /* tp_name */
- sizeof(listreviterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)listreviter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)listreviter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)listreviter_next, /* tp_iternext */
- listreviter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "listreverseiterator", /* tp_name */
+ sizeof(listreviterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)listreviter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)listreviter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)listreviter_next, /* tp_iternext */
+ listreviter_methods, /* tp_methods */
+ 0,
};
static PyObject *
list_reversed(PyListObject *seq, PyObject *unused)
{
- listreviterobject *it;
+ listreviterobject *it;
- it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
- if (it == NULL)
- return NULL;
- assert(PyList_Check(seq));
- it->it_index = PyList_GET_SIZE(seq) - 1;
- Py_INCREF(seq);
- it->it_seq = seq;
- PyObject_GC_Track(it);
- return (PyObject *)it;
+ it = PyObject_GC_New(listreviterobject, &PyListRevIter_Type);
+ if (it == NULL)
+ return NULL;
+ assert(PyList_Check(seq));
+ it->it_index = PyList_GET_SIZE(seq) - 1;
+ Py_INCREF(seq);
+ it->it_seq = seq;
+ PyObject_GC_Track(it);
+ return (PyObject *)it;
}
static void
listreviter_dealloc(listreviterobject *it)
{
- PyObject_GC_UnTrack(it);
- Py_XDECREF(it->it_seq);
- PyObject_GC_Del(it);
+ PyObject_GC_UnTrack(it);
+ Py_XDECREF(it->it_seq);
+ PyObject_GC_Del(it);
}
static int
listreviter_traverse(listreviterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->it_seq);
- return 0;
+ Py_VISIT(it->it_seq);
+ return 0;
}
static PyObject *
listreviter_next(listreviterobject *it)
{
- PyObject *item;
- Py_ssize_t index = it->it_index;
- PyListObject *seq = it->it_seq;
+ PyObject *item;
+ Py_ssize_t index = it->it_index;
+ PyListObject *seq = it->it_seq;
- if (index>=0 && index < PyList_GET_SIZE(seq)) {
- item = PyList_GET_ITEM(seq, index);
- it->it_index--;
- Py_INCREF(item);
- return item;
- }
- it->it_index = -1;
- if (seq != NULL) {
- it->it_seq = NULL;
- Py_DECREF(seq);
- }
- return NULL;
+ if (index>=0 && index < PyList_GET_SIZE(seq)) {
+ item = PyList_GET_ITEM(seq, index);
+ it->it_index--;
+ Py_INCREF(item);
+ return item;
+ }
+ it->it_index = -1;
+ if (seq != NULL) {
+ it->it_seq = NULL;
+ Py_DECREF(seq);
+ }
+ return NULL;
}
static PyObject *
listreviter_len(listreviterobject *it)
{
- Py_ssize_t len = it->it_index + 1;
- if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
- len = 0;
- return PyLong_FromSsize_t(len);
+ Py_ssize_t len = it->it_index + 1;
+ if (it->it_seq == NULL || PyList_GET_SIZE(it->it_seq) < len)
+ len = 0;
+ return PyLong_FromSsize_t(len);
}
diff --git a/Objects/longobject.c b/Objects/longobject.c
index a41782a..698a6db 100644
--- a/Objects/longobject.c
+++ b/Objects/longobject.c
@@ -34,10 +34,10 @@
#define MIN(x, y) ((x) > (y) ? (y) : (x))
#define SIGCHECK(PyTryBlock) \
- if (--_Py_Ticker < 0) { \
- _Py_Ticker = _Py_CheckInterval; \
- if (PyErr_CheckSignals()) PyTryBlock \
- }
+ if (--_Py_Ticker < 0) { \
+ _Py_Ticker = _Py_CheckInterval; \
+ if (PyErr_CheckSignals()) PyTryBlock \
+ }
/* Normalize (remove leading zeros from) a long int object.
Doesn't attempt to free the storage--in most cases, due to the nature
@@ -46,53 +46,53 @@
static PyLongObject *
long_normalize(register PyLongObject *v)
{
- Py_ssize_t j = ABS(Py_SIZE(v));
- Py_ssize_t i = j;
-
- while (i > 0 && v->ob_digit[i-1] == 0)
- --i;
- if (i != j)
- Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
- return v;
+ Py_ssize_t j = ABS(Py_SIZE(v));
+ Py_ssize_t i = j;
+
+ while (i > 0 && v->ob_digit[i-1] == 0)
+ --i;
+ if (i != j)
+ Py_SIZE(v) = (Py_SIZE(v) < 0) ? -(i) : i;
+ return v;
}
/* Allocate a new long int object with size digits.
Return NULL and set exception if we run out of memory. */
#define MAX_LONG_DIGITS \
- ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
+ ((PY_SSIZE_T_MAX - offsetof(PyLongObject, ob_digit))/sizeof(digit))
PyLongObject *
_PyLong_New(Py_ssize_t size)
{
- if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
- PyErr_SetString(PyExc_OverflowError,
- "too many digits in integer");
- return NULL;
- }
- /* coverity[ampersand_in_size] */
- /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
- overflow */
- return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
+ if (size > (Py_ssize_t)MAX_LONG_DIGITS) {
+ PyErr_SetString(PyExc_OverflowError,
+ "too many digits in integer");
+ return NULL;
+ }
+ /* coverity[ampersand_in_size] */
+ /* XXX(nnorwitz): PyObject_NEW_VAR / _PyObject_VAR_SIZE need to detect
+ overflow */
+ return PyObject_NEW_VAR(PyLongObject, &PyLong_Type, size);
}
PyObject *
_PyLong_Copy(PyLongObject *src)
{
- PyLongObject *result;
- Py_ssize_t i;
-
- assert(src != NULL);
- i = src->ob_size;
- if (i < 0)
- i = -(i);
- result = _PyLong_New(i);
- if (result != NULL) {
- result->ob_size = src->ob_size;
- while (--i >= 0)
- result->ob_digit[i] = src->ob_digit[i];
- }
- return (PyObject *)result;
+ PyLongObject *result;
+ Py_ssize_t i;
+
+ assert(src != NULL);
+ i = src->ob_size;
+ if (i < 0)
+ i = -(i);
+ result = _PyLong_New(i);
+ if (result != NULL) {
+ result->ob_size = src->ob_size;
+ while (--i >= 0)
+ result->ob_digit[i] = src->ob_digit[i];
+ }
+ return (PyObject *)result;
}
/* Create a new long int object from a C long int */
@@ -100,43 +100,43 @@ _PyLong_Copy(PyLongObject *src)
PyObject *
PyLong_FromLong(long ival)
{
- PyLongObject *v;
- unsigned long abs_ival;
- unsigned long t; /* unsigned so >> doesn't propagate sign bit */
- int ndigits = 0;
- int negative = 0;
-
- if (ival < 0) {
- /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
- ANSI C says that the result of -ival is undefined when ival
- == LONG_MIN. Hence the following workaround. */
- abs_ival = (unsigned long)(-1-ival) + 1;
- negative = 1;
- }
- else {
- abs_ival = (unsigned long)ival;
- }
-
- /* Count the number of Python digits.
- We used to pick 5 ("big enough for anything"), but that's a
- waste of time and space given that 5*15 = 75 bits are rarely
- needed. */
- t = abs_ival;
- while (t) {
- ++ndigits;
- t >>= PyLong_SHIFT;
- }
- v = _PyLong_New(ndigits);
- if (v != NULL) {
- digit *p = v->ob_digit;
- v->ob_size = negative ? -ndigits : ndigits;
- t = abs_ival;
- while (t) {
- *p++ = (digit)(t & PyLong_MASK);
- t >>= PyLong_SHIFT;
- }
- }
- return (PyObject *)v;
+ PyLongObject *v;
+ unsigned long abs_ival;
+ unsigned long t; /* unsigned so >> doesn't propagate sign bit */
+ int ndigits = 0;
+ int negative = 0;
+
+ if (ival < 0) {
+ /* if LONG_MIN == -LONG_MAX-1 (true on most platforms) then
+ ANSI C says that the result of -ival is undefined when ival
+ == LONG_MIN. Hence the following workaround. */
+ abs_ival = (unsigned long)(-1-ival) + 1;
+ negative = 1;
+ }
+ else {
+ abs_ival = (unsigned long)ival;
+ }
+
+ /* Count the number of Python digits.
+ We used to pick 5 ("big enough for anything"), but that's a
+ waste of time and space given that 5*15 = 75 bits are rarely
+ needed. */
+ t = abs_ival;
+ while (t) {
+ ++ndigits;
+ t >>= PyLong_SHIFT;
+ }
+ v = _PyLong_New(ndigits);
+ if (v != NULL) {
+ digit *p = v->ob_digit;
+ v->ob_size = negative ? -ndigits : ndigits;
+ t = abs_ival;
+ while (t) {
+ *p++ = (digit)(t & PyLong_MASK);
+ t >>= PyLong_SHIFT;
+ }
+ }
+ return (PyObject *)v;
}
/* Create a new long int object from a C unsigned long int */
@@ -144,26 +144,26 @@ PyLong_FromLong(long ival)
PyObject *
PyLong_FromUnsignedLong(unsigned long ival)
{
- PyLongObject *v;
- unsigned long t;
- int ndigits = 0;
-
- /* Count the number of Python digits. */
- t = (unsigned long)ival;
- while (t) {
- ++ndigits;
- t >>= PyLong_SHIFT;
- }
- v = _PyLong_New(ndigits);
- if (v != NULL) {
- digit *p = v->ob_digit;
- Py_SIZE(v) = ndigits;
- while (ival) {
- *p++ = (digit)(ival & PyLong_MASK);
- ival >>= PyLong_SHIFT;
- }
- }
- return (PyObject *)v;
+ PyLongObject *v;
+ unsigned long t;
+ int ndigits = 0;
+
+ /* Count the number of Python digits. */
+ t = (unsigned long)ival;
+ while (t) {
+ ++ndigits;
+ t >>= PyLong_SHIFT;
+ }
+ v = _PyLong_New(ndigits);
+ if (v != NULL) {
+ digit *p = v->ob_digit;
+ Py_SIZE(v) = ndigits;
+ while (ival) {
+ *p++ = (digit)(ival & PyLong_MASK);
+ ival >>= PyLong_SHIFT;
+ }
+ }
+ return (PyObject *)v;
}
/* Create a new long int object from a C double */
@@ -171,41 +171,41 @@ PyLong_FromUnsignedLong(unsigned long ival)
PyObject *
PyLong_FromDouble(double dval)
{
- PyLongObject *v;
- double frac;
- int i, ndig, expo, neg;
- neg = 0;
- if (Py_IS_INFINITY(dval)) {
- PyErr_SetString(PyExc_OverflowError,
- "cannot convert float infinity to integer");
- return NULL;
- }
- if (Py_IS_NAN(dval)) {
- PyErr_SetString(PyExc_ValueError,
- "cannot convert float NaN to integer");
- return NULL;
- }
- if (dval < 0.0) {
- neg = 1;
- dval = -dval;
- }
- frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
- if (expo <= 0)
- return PyLong_FromLong(0L);
- ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
- v = _PyLong_New(ndig);
- if (v == NULL)
- return NULL;
- frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
- for (i = ndig; --i >= 0; ) {
- digit bits = (digit)frac;
- v->ob_digit[i] = bits;
- frac = frac - (double)bits;
- frac = ldexp(frac, PyLong_SHIFT);
- }
- if (neg)
- Py_SIZE(v) = -(Py_SIZE(v));
- return (PyObject *)v;
+ PyLongObject *v;
+ double frac;
+ int i, ndig, expo, neg;
+ neg = 0;
+ if (Py_IS_INFINITY(dval)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "cannot convert float infinity to integer");
+ return NULL;
+ }
+ if (Py_IS_NAN(dval)) {
+ PyErr_SetString(PyExc_ValueError,
+ "cannot convert float NaN to integer");
+ return NULL;
+ }
+ if (dval < 0.0) {
+ neg = 1;
+ dval = -dval;
+ }
+ frac = frexp(dval, &expo); /* dval = frac*2**expo; 0.0 <= frac < 1.0 */
+ if (expo <= 0)
+ return PyLong_FromLong(0L);
+ ndig = (expo-1) / PyLong_SHIFT + 1; /* Number of 'digits' in result */
+ v = _PyLong_New(ndig);
+ if (v == NULL)
+ return NULL;
+ frac = ldexp(frac, (expo-1) % PyLong_SHIFT + 1);
+ for (i = ndig; --i >= 0; ) {
+ digit bits = (digit)frac;
+ v->ob_digit[i] = bits;
+ frac = frac - (double)bits;
+ frac = ldexp(frac, PyLong_SHIFT);
+ }
+ if (neg)
+ Py_SIZE(v) = -(Py_SIZE(v));
+ return (PyObject *)v;
}
/* Checking for overflow in PyLong_AsLong is a PITA since C doesn't define
@@ -217,8 +217,8 @@ PyLong_FromDouble(double dval)
* However, some other compilers warn about applying unary minus to an
* unsigned operand. Hence the weird "0-".
*/
-#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
-#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
+#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
+#define PY_ABS_SSIZE_T_MIN (0-(size_t)PY_SSIZE_T_MIN)
/* Get a C long int from a Python long or Python int object.
On overflow, returns -1 and sets *overflow to 1 or -1 depending
@@ -231,95 +231,95 @@ PyLong_FromDouble(double dval)
long
PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
{
- /* This version by Tim Peters */
- register PyLongObject *v;
- unsigned long x, prev;
- long res;
- Py_ssize_t i;
- int sign;
- int do_decref = 0; /* if nb_int was called */
-
- *overflow = 0;
- if (vv == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
-
- if(PyInt_Check(vv))
- return PyInt_AsLong(vv);
-
- if (!PyLong_Check(vv)) {
- PyNumberMethods *nb;
- nb = vv->ob_type->tp_as_number;
- if (nb == NULL || nb->nb_int == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "an integer is required");
- return -1;
- }
- vv = (*nb->nb_int) (vv);
- if (vv == NULL)
- return -1;
- do_decref = 1;
- if(PyInt_Check(vv)) {
- res = PyInt_AsLong(vv);
- goto exit;
- }
- if (!PyLong_Check(vv)) {
- Py_DECREF(vv);
- PyErr_SetString(PyExc_TypeError,
- "nb_int should return int object");
- return -1;
- }
- }
-
- res = -1;
- v = (PyLongObject *)vv;
- i = Py_SIZE(v);
-
- switch (i) {
- case -1:
- res = -(sdigit)v->ob_digit[0];
- break;
- case 0:
- res = 0;
- break;
- case 1:
- res = v->ob_digit[0];
- break;
- default:
- sign = 1;
- x = 0;
- if (i < 0) {
- sign = -1;
- i = -(i);
- }
- while (--i >= 0) {
- prev = x;
- x = (x << PyLong_SHIFT) + v->ob_digit[i];
- if ((x >> PyLong_SHIFT) != prev) {
- *overflow = sign;
- goto exit;
- }
- }
- /* Haven't lost any bits, but casting to long requires extra
- * care (see comment above).
- */
- if (x <= (unsigned long)LONG_MAX) {
- res = (long)x * sign;
- }
- else if (sign < 0 && x == PY_ABS_LONG_MIN) {
- res = LONG_MIN;
- }
- else {
- *overflow = sign;
- /* res is already set to -1 */
- }
- }
+ /* This version by Tim Peters */
+ register PyLongObject *v;
+ unsigned long x, prev;
+ long res;
+ Py_ssize_t i;
+ int sign;
+ int do_decref = 0; /* if nb_int was called */
+
+ *overflow = 0;
+ if (vv == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+
+ if(PyInt_Check(vv))
+ return PyInt_AsLong(vv);
+
+ if (!PyLong_Check(vv)) {
+ PyNumberMethods *nb;
+ nb = vv->ob_type->tp_as_number;
+ if (nb == NULL || nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "an integer is required");
+ return -1;
+ }
+ vv = (*nb->nb_int) (vv);
+ if (vv == NULL)
+ return -1;
+ do_decref = 1;
+ if(PyInt_Check(vv)) {
+ res = PyInt_AsLong(vv);
+ goto exit;
+ }
+ if (!PyLong_Check(vv)) {
+ Py_DECREF(vv);
+ PyErr_SetString(PyExc_TypeError,
+ "nb_int should return int object");
+ return -1;
+ }
+ }
+
+ res = -1;
+ v = (PyLongObject *)vv;
+ i = Py_SIZE(v);
+
+ switch (i) {
+ case -1:
+ res = -(sdigit)v->ob_digit[0];
+ break;
+ case 0:
+ res = 0;
+ break;
+ case 1:
+ res = v->ob_digit[0];
+ break;
+ default:
+ sign = 1;
+ x = 0;
+ if (i < 0) {
+ sign = -1;
+ i = -(i);
+ }
+ while (--i >= 0) {
+ prev = x;
+ x = (x << PyLong_SHIFT) + v->ob_digit[i];
+ if ((x >> PyLong_SHIFT) != prev) {
+ *overflow = sign;
+ goto exit;
+ }
+ }
+ /* Haven't lost any bits, but casting to long requires extra
+ * care (see comment above).
+ */
+ if (x <= (unsigned long)LONG_MAX) {
+ res = (long)x * sign;
+ }
+ else if (sign < 0 && x == PY_ABS_LONG_MIN) {
+ res = LONG_MIN;
+ }
+ else {
+ *overflow = sign;
+ /* res is already set to -1 */
+ }
+ }
exit:
- if (do_decref) {
- Py_DECREF(vv);
- }
- return res;
+ if (do_decref) {
+ Py_DECREF(vv);
+ }
+ return res;
}
/* Get a C long int from a long int object.
@@ -328,15 +328,15 @@ PyLong_AsLongAndOverflow(PyObject *vv, int *overflow)
long
PyLong_AsLong(PyObject *obj)
{
- int overflow;
- long result = PyLong_AsLongAndOverflow(obj, &overflow);
- if (overflow) {
- /* XXX: could be cute and give a different
- message for overflow == -1 */
- PyErr_SetString(PyExc_OverflowError,
- "Python int too large to convert to C long");
- }
- return result;
+ int overflow;
+ long result = PyLong_AsLongAndOverflow(obj, &overflow);
+ if (overflow) {
+ /* XXX: could be cute and give a different
+ message for overflow == -1 */
+ PyErr_SetString(PyExc_OverflowError,
+ "Python int too large to convert to C long");
+ }
+ return result;
}
/* Get a Py_ssize_t from a long int object.
@@ -344,44 +344,44 @@ PyLong_AsLong(PyObject *obj)
Py_ssize_t
PyLong_AsSsize_t(PyObject *vv) {
- register PyLongObject *v;
- size_t x, prev;
- Py_ssize_t i;
- int sign;
-
- if (vv == NULL || !PyLong_Check(vv)) {
- PyErr_BadInternalCall();
- return -1;
- }
- v = (PyLongObject *)vv;
- i = v->ob_size;
- sign = 1;
- x = 0;
- if (i < 0) {
- sign = -1;
- i = -(i);
- }
- while (--i >= 0) {
- prev = x;
- x = (x << PyLong_SHIFT) | v->ob_digit[i];
- if ((x >> PyLong_SHIFT) != prev)
- goto overflow;
- }
- /* Haven't lost any bits, but casting to a signed type requires
- * extra care (see comment above).
- */
- if (x <= (size_t)PY_SSIZE_T_MAX) {
- return (Py_ssize_t)x * sign;
- }
- else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
- return PY_SSIZE_T_MIN;
- }
- /* else overflow */
+ register PyLongObject *v;
+ size_t x, prev;
+ Py_ssize_t i;
+ int sign;
+
+ if (vv == NULL || !PyLong_Check(vv)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ v = (PyLongObject *)vv;
+ i = v->ob_size;
+ sign = 1;
+ x = 0;
+ if (i < 0) {
+ sign = -1;
+ i = -(i);
+ }
+ while (--i >= 0) {
+ prev = x;
+ x = (x << PyLong_SHIFT) | v->ob_digit[i];
+ if ((x >> PyLong_SHIFT) != prev)
+ goto overflow;
+ }
+ /* Haven't lost any bits, but casting to a signed type requires
+ * extra care (see comment above).
+ */
+ if (x <= (size_t)PY_SSIZE_T_MAX) {
+ return (Py_ssize_t)x * sign;
+ }
+ else if (sign < 0 && x == PY_ABS_SSIZE_T_MIN) {
+ return PY_SSIZE_T_MIN;
+ }
+ /* else overflow */
overflow:
- PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert to int");
- return -1;
+ PyErr_SetString(PyExc_OverflowError,
+ "long int too large to convert to int");
+ return -1;
}
/* Get a C unsigned long int from a long int object.
@@ -390,41 +390,41 @@ PyLong_AsSsize_t(PyObject *vv) {
unsigned long
PyLong_AsUnsignedLong(PyObject *vv)
{
- register PyLongObject *v;
- unsigned long x, prev;
- Py_ssize_t i;
-
- if (vv == NULL || !PyLong_Check(vv)) {
- if (vv != NULL && PyInt_Check(vv)) {
- long val = PyInt_AsLong(vv);
- if (val < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative value to unsigned long");
- return (unsigned long) -1;
- }
- return val;
- }
- PyErr_BadInternalCall();
- return (unsigned long) -1;
- }
- v = (PyLongObject *)vv;
- i = Py_SIZE(v);
- x = 0;
- if (i < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative value to unsigned long");
- return (unsigned long) -1;
- }
- while (--i >= 0) {
- prev = x;
- x = (x << PyLong_SHIFT) | v->ob_digit[i];
- if ((x >> PyLong_SHIFT) != prev) {
- PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert");
- return (unsigned long) -1;
- }
- }
- return x;
+ register PyLongObject *v;
+ unsigned long x, prev;
+ Py_ssize_t i;
+
+ if (vv == NULL || !PyLong_Check(vv)) {
+ if (vv != NULL && PyInt_Check(vv)) {
+ long val = PyInt_AsLong(vv);
+ if (val < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative value to unsigned long");
+ return (unsigned long) -1;
+ }
+ return val;
+ }
+ PyErr_BadInternalCall();
+ return (unsigned long) -1;
+ }
+ v = (PyLongObject *)vv;
+ i = Py_SIZE(v);
+ x = 0;
+ if (i < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative value to unsigned long");
+ return (unsigned long) -1;
+ }
+ while (--i >= 0) {
+ prev = x;
+ x = (x << PyLong_SHIFT) | v->ob_digit[i];
+ if ((x >> PyLong_SHIFT) != prev) {
+ PyErr_SetString(PyExc_OverflowError,
+ "long int too large to convert");
+ return (unsigned long) -1;
+ }
+ }
+ return x;
}
/* Get a C unsigned long int from a long int object, ignoring the high bits.
@@ -433,317 +433,317 @@ PyLong_AsUnsignedLong(PyObject *vv)
unsigned long
PyLong_AsUnsignedLongMask(PyObject *vv)
{
- register PyLongObject *v;
- unsigned long x;
- Py_ssize_t i;
- int sign;
-
- if (vv == NULL || !PyLong_Check(vv)) {
- if (vv != NULL && PyInt_Check(vv))
- return PyInt_AsUnsignedLongMask(vv);
- PyErr_BadInternalCall();
- return (unsigned long) -1;
- }
- v = (PyLongObject *)vv;
- i = v->ob_size;
- sign = 1;
- x = 0;
- if (i < 0) {
- sign = -1;
- i = -i;
- }
- while (--i >= 0) {
- x = (x << PyLong_SHIFT) | v->ob_digit[i];
- }
- return x * sign;
+ register PyLongObject *v;
+ unsigned long x;
+ Py_ssize_t i;
+ int sign;
+
+ if (vv == NULL || !PyLong_Check(vv)) {
+ if (vv != NULL && PyInt_Check(vv))
+ return PyInt_AsUnsignedLongMask(vv);
+ PyErr_BadInternalCall();
+ return (unsigned long) -1;
+ }
+ v = (PyLongObject *)vv;
+ i = v->ob_size;
+ sign = 1;
+ x = 0;
+ if (i < 0) {
+ sign = -1;
+ i = -i;
+ }
+ while (--i >= 0) {
+ x = (x << PyLong_SHIFT) | v->ob_digit[i];
+ }
+ return x * sign;
}
int
_PyLong_Sign(PyObject *vv)
{
- PyLongObject *v = (PyLongObject *)vv;
+ PyLongObject *v = (PyLongObject *)vv;
- assert(v != NULL);
- assert(PyLong_Check(v));
+ assert(v != NULL);
+ assert(PyLong_Check(v));
- return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
+ return Py_SIZE(v) == 0 ? 0 : (Py_SIZE(v) < 0 ? -1 : 1);
}
size_t
_PyLong_NumBits(PyObject *vv)
{
- PyLongObject *v = (PyLongObject *)vv;
- size_t result = 0;
- Py_ssize_t ndigits;
-
- assert(v != NULL);
- assert(PyLong_Check(v));
- ndigits = ABS(Py_SIZE(v));
- assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
- if (ndigits > 0) {
- digit msd = v->ob_digit[ndigits - 1];
-
- result = (ndigits - 1) * PyLong_SHIFT;
- if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
- goto Overflow;
- do {
- ++result;
- if (result == 0)
- goto Overflow;
- msd >>= 1;
- } while (msd);
- }
- return result;
+ PyLongObject *v = (PyLongObject *)vv;
+ size_t result = 0;
+ Py_ssize_t ndigits;
+
+ assert(v != NULL);
+ assert(PyLong_Check(v));
+ ndigits = ABS(Py_SIZE(v));
+ assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
+ if (ndigits > 0) {
+ digit msd = v->ob_digit[ndigits - 1];
+
+ result = (ndigits - 1) * PyLong_SHIFT;
+ if (result / PyLong_SHIFT != (size_t)(ndigits - 1))
+ goto Overflow;
+ do {
+ ++result;
+ if (result == 0)
+ goto Overflow;
+ msd >>= 1;
+ } while (msd);
+ }
+ return result;
Overflow:
- PyErr_SetString(PyExc_OverflowError, "long has too many bits "
- "to express in a platform size_t");
- return (size_t)-1;
+ PyErr_SetString(PyExc_OverflowError, "long has too many bits "
+ "to express in a platform size_t");
+ return (size_t)-1;
}
PyObject *
_PyLong_FromByteArray(const unsigned char* bytes, size_t n,
- int little_endian, int is_signed)
+ int little_endian, int is_signed)
{
- const unsigned char* pstartbyte;/* LSB of bytes */
- int incr; /* direction to move pstartbyte */
- const unsigned char* pendbyte; /* MSB of bytes */
- size_t numsignificantbytes; /* number of bytes that matter */
- Py_ssize_t ndigits; /* number of Python long digits */
- PyLongObject* v; /* result */
- Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
-
- if (n == 0)
- return PyLong_FromLong(0L);
-
- if (little_endian) {
- pstartbyte = bytes;
- pendbyte = bytes + n - 1;
- incr = 1;
- }
- else {
- pstartbyte = bytes + n - 1;
- pendbyte = bytes;
- incr = -1;
- }
-
- if (is_signed)
- is_signed = *pendbyte >= 0x80;
-
- /* Compute numsignificantbytes. This consists of finding the most
- significant byte. Leading 0 bytes are insignficant if the number
- is positive, and leading 0xff bytes if negative. */
- {
- size_t i;
- const unsigned char* p = pendbyte;
- const int pincr = -incr; /* search MSB to LSB */
- const unsigned char insignficant = is_signed ? 0xff : 0x00;
-
- for (i = 0; i < n; ++i, p += pincr) {
- if (*p != insignficant)
- break;
- }
- numsignificantbytes = n - i;
- /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
- actually has 2 significant bytes. OTOH, 0xff0001 ==
- -0x00ffff, so we wouldn't *need* to bump it there; but we
- do for 0xffff = -0x0001. To be safe without bothering to
- check every case, bump it regardless. */
- if (is_signed && numsignificantbytes < n)
- ++numsignificantbytes;
- }
-
- /* How many Python long digits do we need? We have
- 8*numsignificantbytes bits, and each Python long digit has
- PyLong_SHIFT bits, so it's the ceiling of the quotient. */
- /* catch overflow before it happens */
- if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
- PyErr_SetString(PyExc_OverflowError,
- "byte array too long to convert to int");
- return NULL;
- }
- ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
- v = _PyLong_New(ndigits);
- if (v == NULL)
- return NULL;
-
- /* Copy the bits over. The tricky parts are computing 2's-comp on
- the fly for signed numbers, and dealing with the mismatch between
- 8-bit bytes and (probably) 15-bit Python digits.*/
- {
- size_t i;
- twodigits carry = 1; /* for 2's-comp calculation */
- twodigits accum = 0; /* sliding register */
- unsigned int accumbits = 0; /* number of bits in accum */
- const unsigned char* p = pstartbyte;
-
- for (i = 0; i < numsignificantbytes; ++i, p += incr) {
- twodigits thisbyte = *p;
- /* Compute correction for 2's comp, if needed. */
- if (is_signed) {
- thisbyte = (0xff ^ thisbyte) + carry;
- carry = thisbyte >> 8;
- thisbyte &= 0xff;
- }
- /* Because we're going LSB to MSB, thisbyte is
- more significant than what's already in accum,
- so needs to be prepended to accum. */
- accum |= (twodigits)thisbyte << accumbits;
- accumbits += 8;
- if (accumbits >= PyLong_SHIFT) {
- /* There's enough to fill a Python digit. */
- assert(idigit < ndigits);
- v->ob_digit[idigit] = (digit)(accum &
- PyLong_MASK);
- ++idigit;
- accum >>= PyLong_SHIFT;
- accumbits -= PyLong_SHIFT;
- assert(accumbits < PyLong_SHIFT);
- }
- }
- assert(accumbits < PyLong_SHIFT);
- if (accumbits) {
- assert(idigit < ndigits);
- v->ob_digit[idigit] = (digit)accum;
- ++idigit;
- }
- }
-
- Py_SIZE(v) = is_signed ? -idigit : idigit;
- return (PyObject *)long_normalize(v);
+ const unsigned char* pstartbyte;/* LSB of bytes */
+ int incr; /* direction to move pstartbyte */
+ const unsigned char* pendbyte; /* MSB of bytes */
+ size_t numsignificantbytes; /* number of bytes that matter */
+ Py_ssize_t ndigits; /* number of Python long digits */
+ PyLongObject* v; /* result */
+ Py_ssize_t idigit = 0; /* next free index in v->ob_digit */
+
+ if (n == 0)
+ return PyLong_FromLong(0L);
+
+ if (little_endian) {
+ pstartbyte = bytes;
+ pendbyte = bytes + n - 1;
+ incr = 1;
+ }
+ else {
+ pstartbyte = bytes + n - 1;
+ pendbyte = bytes;
+ incr = -1;
+ }
+
+ if (is_signed)
+ is_signed = *pendbyte >= 0x80;
+
+ /* Compute numsignificantbytes. This consists of finding the most
+ significant byte. Leading 0 bytes are insignficant if the number
+ is positive, and leading 0xff bytes if negative. */
+ {
+ size_t i;
+ const unsigned char* p = pendbyte;
+ const int pincr = -incr; /* search MSB to LSB */
+ const unsigned char insignficant = is_signed ? 0xff : 0x00;
+
+ for (i = 0; i < n; ++i, p += pincr) {
+ if (*p != insignficant)
+ break;
+ }
+ numsignificantbytes = n - i;
+ /* 2's-comp is a bit tricky here, e.g. 0xff00 == -0x0100, so
+ actually has 2 significant bytes. OTOH, 0xff0001 ==
+ -0x00ffff, so we wouldn't *need* to bump it there; but we
+ do for 0xffff = -0x0001. To be safe without bothering to
+ check every case, bump it regardless. */
+ if (is_signed && numsignificantbytes < n)
+ ++numsignificantbytes;
+ }
+
+ /* How many Python long digits do we need? We have
+ 8*numsignificantbytes bits, and each Python long digit has
+ PyLong_SHIFT bits, so it's the ceiling of the quotient. */
+ /* catch overflow before it happens */
+ if (numsignificantbytes > (PY_SSIZE_T_MAX - PyLong_SHIFT) / 8) {
+ PyErr_SetString(PyExc_OverflowError,
+ "byte array too long to convert to int");
+ return NULL;
+ }
+ ndigits = (numsignificantbytes * 8 + PyLong_SHIFT - 1) / PyLong_SHIFT;
+ v = _PyLong_New(ndigits);
+ if (v == NULL)
+ return NULL;
+
+ /* Copy the bits over. The tricky parts are computing 2's-comp on
+ the fly for signed numbers, and dealing with the mismatch between
+ 8-bit bytes and (probably) 15-bit Python digits.*/
+ {
+ size_t i;
+ twodigits carry = 1; /* for 2's-comp calculation */
+ twodigits accum = 0; /* sliding register */
+ unsigned int accumbits = 0; /* number of bits in accum */
+ const unsigned char* p = pstartbyte;
+
+ for (i = 0; i < numsignificantbytes; ++i, p += incr) {
+ twodigits thisbyte = *p;
+ /* Compute correction for 2's comp, if needed. */
+ if (is_signed) {
+ thisbyte = (0xff ^ thisbyte) + carry;
+ carry = thisbyte >> 8;
+ thisbyte &= 0xff;
+ }
+ /* Because we're going LSB to MSB, thisbyte is
+ more significant than what's already in accum,
+ so needs to be prepended to accum. */
+ accum |= (twodigits)thisbyte << accumbits;
+ accumbits += 8;
+ if (accumbits >= PyLong_SHIFT) {
+ /* There's enough to fill a Python digit. */
+ assert(idigit < ndigits);
+ v->ob_digit[idigit] = (digit)(accum &
+ PyLong_MASK);
+ ++idigit;
+ accum >>= PyLong_SHIFT;
+ accumbits -= PyLong_SHIFT;
+ assert(accumbits < PyLong_SHIFT);
+ }
+ }
+ assert(accumbits < PyLong_SHIFT);
+ if (accumbits) {
+ assert(idigit < ndigits);
+ v->ob_digit[idigit] = (digit)accum;
+ ++idigit;
+ }
+ }
+
+ Py_SIZE(v) = is_signed ? -idigit : idigit;
+ return (PyObject *)long_normalize(v);
}
int
_PyLong_AsByteArray(PyLongObject* v,
- unsigned char* bytes, size_t n,
- int little_endian, int is_signed)
+ unsigned char* bytes, size_t n,
+ int little_endian, int is_signed)
{
- Py_ssize_t i; /* index into v->ob_digit */
- Py_ssize_t ndigits; /* |v->ob_size| */
- twodigits accum; /* sliding register */
- unsigned int accumbits; /* # bits in accum */
- int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
- digit carry; /* for computing 2's-comp */
- size_t j; /* # bytes filled */
- unsigned char* p; /* pointer to next byte in bytes */
- int pincr; /* direction to move p */
-
- assert(v != NULL && PyLong_Check(v));
-
- if (Py_SIZE(v) < 0) {
- ndigits = -(Py_SIZE(v));
- if (!is_signed) {
- PyErr_SetString(PyExc_OverflowError,
- "can't convert negative long to unsigned");
- return -1;
- }
- do_twos_comp = 1;
- }
- else {
- ndigits = Py_SIZE(v);
- do_twos_comp = 0;
- }
-
- if (little_endian) {
- p = bytes;
- pincr = 1;
- }
- else {
- p = bytes + n - 1;
- pincr = -1;
- }
-
- /* Copy over all the Python digits.
- It's crucial that every Python digit except for the MSD contribute
- exactly PyLong_SHIFT bits to the total, so first assert that the long is
- normalized. */
- assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
- j = 0;
- accum = 0;
- accumbits = 0;
- carry = do_twos_comp ? 1 : 0;
- for (i = 0; i < ndigits; ++i) {
- digit thisdigit = v->ob_digit[i];
- if (do_twos_comp) {
- thisdigit = (thisdigit ^ PyLong_MASK) + carry;
- carry = thisdigit >> PyLong_SHIFT;
- thisdigit &= PyLong_MASK;
- }
- /* Because we're going LSB to MSB, thisdigit is more
- significant than what's already in accum, so needs to be
- prepended to accum. */
- accum |= (twodigits)thisdigit << accumbits;
-
- /* The most-significant digit may be (probably is) at least
- partly empty. */
- if (i == ndigits - 1) {
- /* Count # of sign bits -- they needn't be stored,
- * although for signed conversion we need later to
- * make sure at least one sign bit gets stored. */
- digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
- thisdigit;
- while (s != 0) {
- s >>= 1;
- accumbits++;
- }
- }
- else
- accumbits += PyLong_SHIFT;
-
- /* Store as many bytes as possible. */
- while (accumbits >= 8) {
- if (j >= n)
- goto Overflow;
- ++j;
- *p = (unsigned char)(accum & 0xff);
- p += pincr;
- accumbits -= 8;
- accum >>= 8;
- }
- }
-
- /* Store the straggler (if any). */
- assert(accumbits < 8);
- assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
- if (accumbits > 0) {
- if (j >= n)
- goto Overflow;
- ++j;
- if (do_twos_comp) {
- /* Fill leading bits of the byte with sign bits
- (appropriately pretending that the long had an
- infinite supply of sign bits). */
- accum |= (~(twodigits)0) << accumbits;
- }
- *p = (unsigned char)(accum & 0xff);
- p += pincr;
- }
- else if (j == n && n > 0 && is_signed) {
- /* The main loop filled the byte array exactly, so the code
- just above didn't get to ensure there's a sign bit, and the
- loop below wouldn't add one either. Make sure a sign bit
- exists. */
- unsigned char msb = *(p - pincr);
- int sign_bit_set = msb >= 0x80;
- assert(accumbits == 0);
- if (sign_bit_set == do_twos_comp)
- return 0;
- else
- goto Overflow;
- }
-
- /* Fill remaining bytes with copies of the sign bit. */
- {
- unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
- for ( ; j < n; ++j, p += pincr)
- *p = signbyte;
- }
-
- return 0;
+ Py_ssize_t i; /* index into v->ob_digit */
+ Py_ssize_t ndigits; /* |v->ob_size| */
+ twodigits accum; /* sliding register */
+ unsigned int accumbits; /* # bits in accum */
+ int do_twos_comp; /* store 2's-comp? is_signed and v < 0 */
+ digit carry; /* for computing 2's-comp */
+ size_t j; /* # bytes filled */
+ unsigned char* p; /* pointer to next byte in bytes */
+ int pincr; /* direction to move p */
+
+ assert(v != NULL && PyLong_Check(v));
+
+ if (Py_SIZE(v) < 0) {
+ ndigits = -(Py_SIZE(v));
+ if (!is_signed) {
+ PyErr_SetString(PyExc_OverflowError,
+ "can't convert negative long to unsigned");
+ return -1;
+ }
+ do_twos_comp = 1;
+ }
+ else {
+ ndigits = Py_SIZE(v);
+ do_twos_comp = 0;
+ }
+
+ if (little_endian) {
+ p = bytes;
+ pincr = 1;
+ }
+ else {
+ p = bytes + n - 1;
+ pincr = -1;
+ }
+
+ /* Copy over all the Python digits.
+ It's crucial that every Python digit except for the MSD contribute
+ exactly PyLong_SHIFT bits to the total, so first assert that the long is
+ normalized. */
+ assert(ndigits == 0 || v->ob_digit[ndigits - 1] != 0);
+ j = 0;
+ accum = 0;
+ accumbits = 0;
+ carry = do_twos_comp ? 1 : 0;
+ for (i = 0; i < ndigits; ++i) {
+ digit thisdigit = v->ob_digit[i];
+ if (do_twos_comp) {
+ thisdigit = (thisdigit ^ PyLong_MASK) + carry;
+ carry = thisdigit >> PyLong_SHIFT;
+ thisdigit &= PyLong_MASK;
+ }
+ /* Because we're going LSB to MSB, thisdigit is more
+ significant than what's already in accum, so needs to be
+ prepended to accum. */
+ accum |= (twodigits)thisdigit << accumbits;
+
+ /* The most-significant digit may be (probably is) at least
+ partly empty. */
+ if (i == ndigits - 1) {
+ /* Count # of sign bits -- they needn't be stored,
+ * although for signed conversion we need later to
+ * make sure at least one sign bit gets stored. */
+ digit s = do_twos_comp ? thisdigit ^ PyLong_MASK :
+ thisdigit;
+ while (s != 0) {
+ s >>= 1;
+ accumbits++;
+ }
+ }
+ else
+ accumbits += PyLong_SHIFT;
+
+ /* Store as many bytes as possible. */
+ while (accumbits >= 8) {
+ if (j >= n)
+ goto Overflow;
+ ++j;
+ *p = (unsigned char)(accum & 0xff);
+ p += pincr;
+ accumbits -= 8;
+ accum >>= 8;
+ }
+ }
+
+ /* Store the straggler (if any). */
+ assert(accumbits < 8);
+ assert(carry == 0); /* else do_twos_comp and *every* digit was 0 */
+ if (accumbits > 0) {
+ if (j >= n)
+ goto Overflow;
+ ++j;
+ if (do_twos_comp) {
+ /* Fill leading bits of the byte with sign bits
+ (appropriately pretending that the long had an
+ infinite supply of sign bits). */
+ accum |= (~(twodigits)0) << accumbits;
+ }
+ *p = (unsigned char)(accum & 0xff);
+ p += pincr;
+ }
+ else if (j == n && n > 0 && is_signed) {
+ /* The main loop filled the byte array exactly, so the code
+ just above didn't get to ensure there's a sign bit, and the
+ loop below wouldn't add one either. Make sure a sign bit
+ exists. */
+ unsigned char msb = *(p - pincr);
+ int sign_bit_set = msb >= 0x80;
+ assert(accumbits == 0);
+ if (sign_bit_set == do_twos_comp)
+ return 0;
+ else
+ goto Overflow;
+ }
+
+ /* Fill remaining bytes with copies of the sign bit. */
+ {
+ unsigned char signbyte = do_twos_comp ? 0xffU : 0U;
+ for ( ; j < n; ++j, p += pincr)
+ *p = signbyte;
+ }
+
+ return 0;
Overflow:
- PyErr_SetString(PyExc_OverflowError, "long too big to convert");
- return -1;
+ PyErr_SetString(PyExc_OverflowError, "long too big to convert");
+ return -1;
}
@@ -753,9 +753,9 @@ PyObject *
PyLong_FromVoidPtr(void *p)
{
#if SIZEOF_VOID_P <= SIZEOF_LONG
- if ((long)p < 0)
- return PyLong_FromUnsignedLong((unsigned long)p);
- return PyInt_FromLong((long)p);
+ if ((long)p < 0)
+ return PyLong_FromUnsignedLong((unsigned long)p);
+ return PyInt_FromLong((long)p);
#else
#ifndef HAVE_LONG_LONG
@@ -764,10 +764,10 @@ PyLong_FromVoidPtr(void *p)
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
# error "PyLong_FromVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
#endif
- /* optimize null pointers */
- if (p == NULL)
- return PyInt_FromLong(0);
- return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
+ /* optimize null pointers */
+ if (p == NULL)
+ return PyInt_FromLong(0);
+ return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG)p);
#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
}
@@ -777,19 +777,19 @@ PyLong_FromVoidPtr(void *p)
void *
PyLong_AsVoidPtr(PyObject *vv)
{
- /* This function will allow int or long objects. If vv is neither,
- then the PyLong_AsLong*() functions will raise the exception:
- PyExc_SystemError, "bad argument to internal function"
- */
+ /* This function will allow int or long objects. If vv is neither,
+ then the PyLong_AsLong*() functions will raise the exception:
+ PyExc_SystemError, "bad argument to internal function"
+ */
#if SIZEOF_VOID_P <= SIZEOF_LONG
- long x;
-
- if (PyInt_Check(vv))
- x = PyInt_AS_LONG(vv);
- else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
- x = PyLong_AsLong(vv);
- else
- x = PyLong_AsUnsignedLong(vv);
+ long x;
+
+ if (PyInt_Check(vv))
+ x = PyInt_AS_LONG(vv);
+ else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
+ x = PyLong_AsLong(vv);
+ else
+ x = PyLong_AsUnsignedLong(vv);
#else
#ifndef HAVE_LONG_LONG
@@ -798,20 +798,20 @@ PyLong_AsVoidPtr(PyObject *vv)
#if SIZEOF_LONG_LONG < SIZEOF_VOID_P
# error "PyLong_AsVoidPtr: sizeof(PY_LONG_LONG) < sizeof(void*)"
#endif
- PY_LONG_LONG x;
+ PY_LONG_LONG x;
- if (PyInt_Check(vv))
- x = PyInt_AS_LONG(vv);
- else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
- x = PyLong_AsLongLong(vv);
- else
- x = PyLong_AsUnsignedLongLong(vv);
+ if (PyInt_Check(vv))
+ x = PyInt_AS_LONG(vv);
+ else if (PyLong_Check(vv) && _PyLong_Sign(vv) < 0)
+ x = PyLong_AsLongLong(vv);
+ else
+ x = PyLong_AsUnsignedLongLong(vv);
#endif /* SIZEOF_VOID_P <= SIZEOF_LONG */
- if (x == -1 && PyErr_Occurred())
- return NULL;
- return (void *)x;
+ if (x == -1 && PyErr_Occurred())
+ return NULL;
+ return (void *)x;
}
#ifdef HAVE_LONG_LONG
@@ -821,49 +821,49 @@ PyLong_AsVoidPtr(PyObject *vv)
*/
#define IS_LITTLE_ENDIAN (int)*(unsigned char*)&one
-#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
+#define PY_ABS_LLONG_MIN (0-(unsigned PY_LONG_LONG)PY_LLONG_MIN)
/* Create a new long int object from a C PY_LONG_LONG int. */
PyObject *
PyLong_FromLongLong(PY_LONG_LONG ival)
{
- PyLongObject *v;
- unsigned PY_LONG_LONG abs_ival;
- unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
- int ndigits = 0;
- int negative = 0;
-
- if (ival < 0) {
- /* avoid signed overflow on negation; see comments
- in PyLong_FromLong above. */
- abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
- negative = 1;
- }
- else {
- abs_ival = (unsigned PY_LONG_LONG)ival;
- }
-
- /* Count the number of Python digits.
- We used to pick 5 ("big enough for anything"), but that's a
- waste of time and space given that 5*15 = 75 bits are rarely
- needed. */
- t = abs_ival;
- while (t) {
- ++ndigits;
- t >>= PyLong_SHIFT;
- }
- v = _PyLong_New(ndigits);
- if (v != NULL) {
- digit *p = v->ob_digit;
- Py_SIZE(v) = negative ? -ndigits : ndigits;
- t = abs_ival;
- while (t) {
- *p++ = (digit)(t & PyLong_MASK);
- t >>= PyLong_SHIFT;
- }
- }
- return (PyObject *)v;
+ PyLongObject *v;
+ unsigned PY_LONG_LONG abs_ival;
+ unsigned PY_LONG_LONG t; /* unsigned so >> doesn't propagate sign bit */
+ int ndigits = 0;
+ int negative = 0;
+
+ if (ival < 0) {
+ /* avoid signed overflow on negation; see comments
+ in PyLong_FromLong above. */
+ abs_ival = (unsigned PY_LONG_LONG)(-1-ival) + 1;
+ negative = 1;
+ }
+ else {
+ abs_ival = (unsigned PY_LONG_LONG)ival;
+ }
+
+ /* Count the number of Python digits.
+ We used to pick 5 ("big enough for anything"), but that's a
+ waste of time and space given that 5*15 = 75 bits are rarely
+ needed. */
+ t = abs_ival;
+ while (t) {
+ ++ndigits;
+ t >>= PyLong_SHIFT;
+ }
+ v = _PyLong_New(ndigits);
+ if (v != NULL) {
+ digit *p = v->ob_digit;
+ Py_SIZE(v) = negative ? -ndigits : ndigits;
+ t = abs_ival;
+ while (t) {
+ *p++ = (digit)(t & PyLong_MASK);
+ t >>= PyLong_SHIFT;
+ }
+ }
+ return (PyObject *)v;
}
/* Create a new long int object from a C unsigned PY_LONG_LONG int. */
@@ -871,26 +871,26 @@ PyLong_FromLongLong(PY_LONG_LONG ival)
PyObject *
PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
{
- PyLongObject *v;
- unsigned PY_LONG_LONG t;
- int ndigits = 0;
-
- /* Count the number of Python digits. */
- t = (unsigned PY_LONG_LONG)ival;
- while (t) {
- ++ndigits;
- t >>= PyLong_SHIFT;
- }
- v = _PyLong_New(ndigits);
- if (v != NULL) {
- digit *p = v->ob_digit;
- Py_SIZE(v) = ndigits;
- while (ival) {
- *p++ = (digit)(ival & PyLong_MASK);
- ival >>= PyLong_SHIFT;
- }
- }
- return (PyObject *)v;
+ PyLongObject *v;
+ unsigned PY_LONG_LONG t;
+ int ndigits = 0;
+
+ /* Count the number of Python digits. */
+ t = (unsigned PY_LONG_LONG)ival;
+ while (t) {
+ ++ndigits;
+ t >>= PyLong_SHIFT;
+ }
+ v = _PyLong_New(ndigits);
+ if (v != NULL) {
+ digit *p = v->ob_digit;
+ Py_SIZE(v) = ndigits;
+ while (ival) {
+ *p++ = (digit)(ival & PyLong_MASK);
+ ival >>= PyLong_SHIFT;
+ }
+ }
+ return (PyObject *)v;
}
/* Create a new long int object from a C Py_ssize_t. */
@@ -898,11 +898,11 @@ PyLong_FromUnsignedLongLong(unsigned PY_LONG_LONG ival)
PyObject *
PyLong_FromSsize_t(Py_ssize_t ival)
{
- Py_ssize_t bytes = ival;
- int one = 1;
- return _PyLong_FromByteArray(
- (unsigned char *)&bytes,
- SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
+ Py_ssize_t bytes = ival;
+ int one = 1;
+ return _PyLong_FromByteArray(
+ (unsigned char *)&bytes,
+ SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 1);
}
/* Create a new long int object from a C size_t. */
@@ -910,11 +910,11 @@ PyLong_FromSsize_t(Py_ssize_t ival)
PyObject *
PyLong_FromSize_t(size_t ival)
{
- size_t bytes = ival;
- int one = 1;
- return _PyLong_FromByteArray(
- (unsigned char *)&bytes,
- SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
+ size_t bytes = ival;
+ int one = 1;
+ return _PyLong_FromByteArray(
+ (unsigned char *)&bytes,
+ SIZEOF_SIZE_T, IS_LITTLE_ENDIAN, 0);
}
/* Get a C PY_LONG_LONG int from a long int object.
@@ -923,51 +923,51 @@ PyLong_FromSize_t(size_t ival)
PY_LONG_LONG
PyLong_AsLongLong(PyObject *vv)
{
- PY_LONG_LONG bytes;
- int one = 1;
- int res;
-
- if (vv == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (!PyLong_Check(vv)) {
- PyNumberMethods *nb;
- PyObject *io;
- if (PyInt_Check(vv))
- return (PY_LONG_LONG)PyInt_AsLong(vv);
- if ((nb = vv->ob_type->tp_as_number) == NULL ||
- nb->nb_int == NULL) {
- PyErr_SetString(PyExc_TypeError, "an integer is required");
- return -1;
- }
- io = (*nb->nb_int) (vv);
- if (io == NULL)
- return -1;
- if (PyInt_Check(io)) {
- bytes = PyInt_AsLong(io);
- Py_DECREF(io);
- return bytes;
- }
- if (PyLong_Check(io)) {
- bytes = PyLong_AsLongLong(io);
- Py_DECREF(io);
- return bytes;
- }
- Py_DECREF(io);
- PyErr_SetString(PyExc_TypeError, "integer conversion failed");
- return -1;
- }
-
- res = _PyLong_AsByteArray(
- (PyLongObject *)vv, (unsigned char *)&bytes,
- SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
-
- /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
- if (res < 0)
- return (PY_LONG_LONG)-1;
- else
- return bytes;
+ PY_LONG_LONG bytes;
+ int one = 1;
+ int res;
+
+ if (vv == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (!PyLong_Check(vv)) {
+ PyNumberMethods *nb;
+ PyObject *io;
+ if (PyInt_Check(vv))
+ return (PY_LONG_LONG)PyInt_AsLong(vv);
+ if ((nb = vv->ob_type->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError, "an integer is required");
+ return -1;
+ }
+ io = (*nb->nb_int) (vv);
+ if (io == NULL)
+ return -1;
+ if (PyInt_Check(io)) {
+ bytes = PyInt_AsLong(io);
+ Py_DECREF(io);
+ return bytes;
+ }
+ if (PyLong_Check(io)) {
+ bytes = PyLong_AsLongLong(io);
+ Py_DECREF(io);
+ return bytes;
+ }
+ Py_DECREF(io);
+ PyErr_SetString(PyExc_TypeError, "integer conversion failed");
+ return -1;
+ }
+
+ res = _PyLong_AsByteArray(
+ (PyLongObject *)vv, (unsigned char *)&bytes,
+ SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 1);
+
+ /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
+ if (res < 0)
+ return (PY_LONG_LONG)-1;
+ else
+ return bytes;
}
/* Get a C unsigned PY_LONG_LONG int from a long int object.
@@ -976,24 +976,24 @@ PyLong_AsLongLong(PyObject *vv)
unsigned PY_LONG_LONG
PyLong_AsUnsignedLongLong(PyObject *vv)
{
- unsigned PY_LONG_LONG bytes;
- int one = 1;
- int res;
-
- if (vv == NULL || !PyLong_Check(vv)) {
- PyErr_BadInternalCall();
- return (unsigned PY_LONG_LONG)-1;
- }
-
- res = _PyLong_AsByteArray(
- (PyLongObject *)vv, (unsigned char *)&bytes,
- SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
-
- /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
- if (res < 0)
- return (unsigned PY_LONG_LONG)res;
- else
- return bytes;
+ unsigned PY_LONG_LONG bytes;
+ int one = 1;
+ int res;
+
+ if (vv == NULL || !PyLong_Check(vv)) {
+ PyErr_BadInternalCall();
+ return (unsigned PY_LONG_LONG)-1;
+ }
+
+ res = _PyLong_AsByteArray(
+ (PyLongObject *)vv, (unsigned char *)&bytes,
+ SIZEOF_LONG_LONG, IS_LITTLE_ENDIAN, 0);
+
+ /* Plan 9 can't handle PY_LONG_LONG in ? : expressions */
+ if (res < 0)
+ return (unsigned PY_LONG_LONG)res;
+ else
+ return bytes;
}
/* Get a C unsigned long int from a long int object, ignoring the high bits.
@@ -1002,27 +1002,27 @@ PyLong_AsUnsignedLongLong(PyObject *vv)
unsigned PY_LONG_LONG
PyLong_AsUnsignedLongLongMask(PyObject *vv)
{
- register PyLongObject *v;
- unsigned PY_LONG_LONG x;
- Py_ssize_t i;
- int sign;
-
- if (vv == NULL || !PyLong_Check(vv)) {
- PyErr_BadInternalCall();
- return (unsigned long) -1;
- }
- v = (PyLongObject *)vv;
- i = v->ob_size;
- sign = 1;
- x = 0;
- if (i < 0) {
- sign = -1;
- i = -i;
- }
- while (--i >= 0) {
- x = (x << PyLong_SHIFT) | v->ob_digit[i];
- }
- return x * sign;
+ register PyLongObject *v;
+ unsigned PY_LONG_LONG x;
+ Py_ssize_t i;
+ int sign;
+
+ if (vv == NULL || !PyLong_Check(vv)) {
+ PyErr_BadInternalCall();
+ return (unsigned long) -1;
+ }
+ v = (PyLongObject *)vv;
+ i = v->ob_size;
+ sign = 1;
+ x = 0;
+ if (i < 0) {
+ sign = -1;
+ i = -i;
+ }
+ while (--i >= 0) {
+ x = (x << PyLong_SHIFT) | v->ob_digit[i];
+ }
+ return x * sign;
}
/* Get a C long long int from a Python long or Python int object.
@@ -1036,95 +1036,95 @@ PyLong_AsUnsignedLongLongMask(PyObject *vv)
PY_LONG_LONG
PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
{
- /* This version by Tim Peters */
- register PyLongObject *v;
- unsigned PY_LONG_LONG x, prev;
- PY_LONG_LONG res;
- Py_ssize_t i;
- int sign;
- int do_decref = 0; /* if nb_int was called */
-
- *overflow = 0;
- if (vv == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
-
- if (PyInt_Check(vv))
- return PyInt_AsLong(vv);
-
- if (!PyLong_Check(vv)) {
- PyNumberMethods *nb;
- nb = vv->ob_type->tp_as_number;
- if (nb == NULL || nb->nb_int == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "an integer is required");
- return -1;
- }
- vv = (*nb->nb_int) (vv);
- if (vv == NULL)
- return -1;
- do_decref = 1;
- if(PyInt_Check(vv)) {
- res = PyInt_AsLong(vv);
- goto exit;
- }
- if (!PyLong_Check(vv)) {
- Py_DECREF(vv);
- PyErr_SetString(PyExc_TypeError,
- "nb_int should return int object");
- return -1;
- }
- }
-
- res = -1;
- v = (PyLongObject *)vv;
- i = Py_SIZE(v);
-
- switch (i) {
- case -1:
- res = -(sdigit)v->ob_digit[0];
- break;
- case 0:
- res = 0;
- break;
- case 1:
- res = v->ob_digit[0];
- break;
- default:
- sign = 1;
- x = 0;
- if (i < 0) {
- sign = -1;
- i = -(i);
- }
- while (--i >= 0) {
- prev = x;
- x = (x << PyLong_SHIFT) + v->ob_digit[i];
- if ((x >> PyLong_SHIFT) != prev) {
- *overflow = sign;
- goto exit;
- }
- }
- /* Haven't lost any bits, but casting to long requires extra
- * care (see comment above).
- */
- if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
- res = (PY_LONG_LONG)x * sign;
- }
- else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
- res = PY_LLONG_MIN;
- }
- else {
- *overflow = sign;
- /* res is already set to -1 */
- }
- }
+ /* This version by Tim Peters */
+ register PyLongObject *v;
+ unsigned PY_LONG_LONG x, prev;
+ PY_LONG_LONG res;
+ Py_ssize_t i;
+ int sign;
+ int do_decref = 0; /* if nb_int was called */
+
+ *overflow = 0;
+ if (vv == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+
+ if (PyInt_Check(vv))
+ return PyInt_AsLong(vv);
+
+ if (!PyLong_Check(vv)) {
+ PyNumberMethods *nb;
+ nb = vv->ob_type->tp_as_number;
+ if (nb == NULL || nb->nb_int == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "an integer is required");
+ return -1;
+ }
+ vv = (*nb->nb_int) (vv);
+ if (vv == NULL)
+ return -1;
+ do_decref = 1;
+ if(PyInt_Check(vv)) {
+ res = PyInt_AsLong(vv);
+ goto exit;
+ }
+ if (!PyLong_Check(vv)) {
+ Py_DECREF(vv);
+ PyErr_SetString(PyExc_TypeError,
+ "nb_int should return int object");
+ return -1;
+ }
+ }
+
+ res = -1;
+ v = (PyLongObject *)vv;
+ i = Py_SIZE(v);
+
+ switch (i) {
+ case -1:
+ res = -(sdigit)v->ob_digit[0];
+ break;
+ case 0:
+ res = 0;
+ break;
+ case 1:
+ res = v->ob_digit[0];
+ break;
+ default:
+ sign = 1;
+ x = 0;
+ if (i < 0) {
+ sign = -1;
+ i = -(i);
+ }
+ while (--i >= 0) {
+ prev = x;
+ x = (x << PyLong_SHIFT) + v->ob_digit[i];
+ if ((x >> PyLong_SHIFT) != prev) {
+ *overflow = sign;
+ goto exit;
+ }
+ }
+ /* Haven't lost any bits, but casting to long requires extra
+ * care (see comment above).
+ */
+ if (x <= (unsigned PY_LONG_LONG)PY_LLONG_MAX) {
+ res = (PY_LONG_LONG)x * sign;
+ }
+ else if (sign < 0 && x == PY_ABS_LLONG_MIN) {
+ res = PY_LLONG_MIN;
+ }
+ else {
+ *overflow = sign;
+ /* res is already set to -1 */
+ }
+ }
exit:
- if (do_decref) {
- Py_DECREF(vv);
- }
- return res;
+ if (do_decref) {
+ Py_DECREF(vv);
+ }
+ return res;
}
#undef IS_LITTLE_ENDIAN
@@ -1134,54 +1134,54 @@ PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow)
static int
convert_binop(PyObject *v, PyObject *w, PyLongObject **a, PyLongObject **b) {
- if (PyLong_Check(v)) {
- *a = (PyLongObject *) v;
- Py_INCREF(v);
- }
- else if (PyInt_Check(v)) {
- *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
- }
- else {
- return 0;
- }
- if (PyLong_Check(w)) {
- *b = (PyLongObject *) w;
- Py_INCREF(w);
- }
- else if (PyInt_Check(w)) {
- *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
- }
- else {
- Py_DECREF(*a);
- return 0;
- }
- return 1;
+ if (PyLong_Check(v)) {
+ *a = (PyLongObject *) v;
+ Py_INCREF(v);
+ }
+ else if (PyInt_Check(v)) {
+ *a = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(v));
+ }
+ else {
+ return 0;
+ }
+ if (PyLong_Check(w)) {
+ *b = (PyLongObject *) w;
+ Py_INCREF(w);
+ }
+ else if (PyInt_Check(w)) {
+ *b = (PyLongObject *) PyLong_FromLong(PyInt_AS_LONG(w));
+ }
+ else {
+ Py_DECREF(*a);
+ return 0;
+ }
+ return 1;
}
#define CONVERT_BINOP(v, w, a, b) \
- if (!convert_binop(v, w, a, b)) { \
- Py_INCREF(Py_NotImplemented); \
- return Py_NotImplemented; \
- }
+ if (!convert_binop(v, w, a, b)) { \
+ Py_INCREF(Py_NotImplemented); \
+ return Py_NotImplemented; \
+ }
/* bits_in_digit(d) returns the unique integer k such that 2**(k-1) <= d <
2**k if d is nonzero, else 0. */
static const unsigned char BitLengthTable[32] = {
- 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
- 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
+ 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4,
+ 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5
};
static int
bits_in_digit(digit d)
{
- int d_bits = 0;
- while (d >= 32) {
- d_bits += 6;
- d >>= 6;
- }
- d_bits += (int)BitLengthTable[d];
- return d_bits;
+ int d_bits = 0;
+ while (d >= 32) {
+ d_bits += 6;
+ d >>= 6;
+ }
+ d_bits += (int)BitLengthTable[d];
+ return d_bits;
}
/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
@@ -1191,23 +1191,23 @@ bits_in_digit(digit d)
static digit
v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
{
- Py_ssize_t i;
- digit carry = 0;
-
- assert(m >= n);
- for (i = 0; i < n; ++i) {
- carry += x[i] + y[i];
- x[i] = carry & PyLong_MASK;
- carry >>= PyLong_SHIFT;
- assert((carry & 1) == carry);
- }
- for (; carry && i < m; ++i) {
- carry += x[i];
- x[i] = carry & PyLong_MASK;
- carry >>= PyLong_SHIFT;
- assert((carry & 1) == carry);
- }
- return carry;
+ Py_ssize_t i;
+ digit carry = 0;
+
+ assert(m >= n);
+ for (i = 0; i < n; ++i) {
+ carry += x[i] + y[i];
+ x[i] = carry & PyLong_MASK;
+ carry >>= PyLong_SHIFT;
+ assert((carry & 1) == carry);
+ }
+ for (; carry && i < m; ++i) {
+ carry += x[i];
+ x[i] = carry & PyLong_MASK;
+ carry >>= PyLong_SHIFT;
+ assert((carry & 1) == carry);
+ }
+ return carry;
}
/* x[0:m] and y[0:n] are digit vectors, LSD first, m >= n required. x[0:n]
@@ -1217,23 +1217,23 @@ v_iadd(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
static digit
v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
{
- Py_ssize_t i;
- digit borrow = 0;
-
- assert(m >= n);
- for (i = 0; i < n; ++i) {
- borrow = x[i] - y[i] - borrow;
- x[i] = borrow & PyLong_MASK;
- borrow >>= PyLong_SHIFT;
- borrow &= 1; /* keep only 1 sign bit */
- }
- for (; borrow && i < m; ++i) {
- borrow = x[i] - borrow;
- x[i] = borrow & PyLong_MASK;
- borrow >>= PyLong_SHIFT;
- borrow &= 1;
- }
- return borrow;
+ Py_ssize_t i;
+ digit borrow = 0;
+
+ assert(m >= n);
+ for (i = 0; i < n; ++i) {
+ borrow = x[i] - y[i] - borrow;
+ x[i] = borrow & PyLong_MASK;
+ borrow >>= PyLong_SHIFT;
+ borrow &= 1; /* keep only 1 sign bit */
+ }
+ for (; borrow && i < m; ++i) {
+ borrow = x[i] - borrow;
+ x[i] = borrow & PyLong_MASK;
+ borrow >>= PyLong_SHIFT;
+ borrow &= 1;
+ }
+ return borrow;
}
/* Shift digit vector a[0:m] d bits left, with 0 <= d < PyLong_SHIFT. Put
@@ -1242,16 +1242,16 @@ v_isub(digit *x, Py_ssize_t m, digit *y, Py_ssize_t n)
static digit
v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
{
- Py_ssize_t i;
- digit carry = 0;
-
- assert(0 <= d && d < PyLong_SHIFT);
- for (i=0; i < m; i++) {
- twodigits acc = (twodigits)a[i] << d | carry;
- z[i] = (digit)acc & PyLong_MASK;
- carry = (digit)(acc >> PyLong_SHIFT);
- }
- return carry;
+ Py_ssize_t i;
+ digit carry = 0;
+
+ assert(0 <= d && d < PyLong_SHIFT);
+ for (i=0; i < m; i++) {
+ twodigits acc = (twodigits)a[i] << d | carry;
+ z[i] = (digit)acc & PyLong_MASK;
+ carry = (digit)(acc >> PyLong_SHIFT);
+ }
+ return carry;
}
/* Shift digit vector a[0:m] d bits right, with 0 <= d < PyLong_SHIFT. Put
@@ -1260,17 +1260,17 @@ v_lshift(digit *z, digit *a, Py_ssize_t m, int d)
static digit
v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
{
- Py_ssize_t i;
- digit carry = 0;
- digit mask = ((digit)1 << d) - 1U;
-
- assert(0 <= d && d < PyLong_SHIFT);
- for (i=m; i-- > 0;) {
- twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
- carry = (digit)acc & mask;
- z[i] = (digit)(acc >> d);
- }
- return carry;
+ Py_ssize_t i;
+ digit carry = 0;
+ digit mask = ((digit)1 << d) - 1U;
+
+ assert(0 <= d && d < PyLong_SHIFT);
+ for (i=m; i-- > 0;) {
+ twodigits acc = (twodigits)carry << PyLong_SHIFT | a[i];
+ carry = (digit)acc & mask;
+ z[i] = (digit)(acc >> d);
+ }
+ return carry;
}
/* Divide long pin, w/ size digits, by non-zero digit n, storing quotient
@@ -1282,18 +1282,18 @@ v_rshift(digit *z, digit *a, Py_ssize_t m, int d)
static digit
inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
{
- twodigits rem = 0;
-
- assert(n > 0 && n <= PyLong_MASK);
- pin += size;
- pout += size;
- while (--size >= 0) {
- digit hi;
- rem = (rem << PyLong_SHIFT) | *--pin;
- *--pout = hi = (digit)(rem / n);
- rem -= (twodigits)hi * n;
- }
- return (digit)rem;
+ twodigits rem = 0;
+
+ assert(n > 0 && n <= PyLong_MASK);
+ pin += size;
+ pout += size;
+ while (--size >= 0) {
+ digit hi;
+ rem = (rem << PyLong_SHIFT) | *--pin;
+ *--pout = hi = (digit)(rem / n);
+ rem -= (twodigits)hi * n;
+ }
+ return (digit)rem;
}
/* Divide a long integer by a digit, returning both the quotient
@@ -1303,15 +1303,15 @@ inplace_divrem1(digit *pout, digit *pin, Py_ssize_t size, digit n)
static PyLongObject *
divrem1(PyLongObject *a, digit n, digit *prem)
{
- const Py_ssize_t size = ABS(Py_SIZE(a));
- PyLongObject *z;
-
- assert(n > 0 && n <= PyLong_MASK);
- z = _PyLong_New(size);
- if (z == NULL)
- return NULL;
- *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
- return long_normalize(z);
+ const Py_ssize_t size = ABS(Py_SIZE(a));
+ PyLongObject *z;
+
+ assert(n > 0 && n <= PyLong_MASK);
+ z = _PyLong_New(size);
+ if (z == NULL)
+ return NULL;
+ *prem = inplace_divrem1(z->ob_digit, a->ob_digit, size, n);
+ return long_normalize(z);
}
/* Convert a long integer to a base 10 string. Returns a new non-shared
@@ -1321,114 +1321,114 @@ divrem1(PyLongObject *a, digit n, digit *prem)
static PyObject *
long_to_decimal_string(PyObject *aa, int addL)
{
- PyLongObject *scratch, *a;
- PyObject *str;
- Py_ssize_t size, strlen, size_a, i, j;
- digit *pout, *pin, rem, tenpow;
- char *p;
- int negative;
-
- a = (PyLongObject *)aa;
- if (a == NULL || !PyLong_Check(a)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- size_a = ABS(Py_SIZE(a));
- negative = Py_SIZE(a) < 0;
-
- /* quick and dirty upper bound for the number of digits
- required to express a in base _PyLong_DECIMAL_BASE:
-
- #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
-
- But log2(a) < size_a * PyLong_SHIFT, and
- log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
- > 3 * _PyLong_DECIMAL_SHIFT
- */
- if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
- PyErr_SetString(PyExc_OverflowError,
- "long is too large to format");
- return NULL;
- }
- /* the expression size_a * PyLong_SHIFT is now safe from overflow */
- size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
- scratch = _PyLong_New(size);
- if (scratch == NULL)
- return NULL;
-
- /* convert array of base _PyLong_BASE digits in pin to an array of
- base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
- Volume 2 (3rd edn), section 4.4, Method 1b). */
- pin = a->ob_digit;
- pout = scratch->ob_digit;
- size = 0;
- for (i = size_a; --i >= 0; ) {
- digit hi = pin[i];
- for (j = 0; j < size; j++) {
- twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
- hi = (digit)(z / _PyLong_DECIMAL_BASE);
- pout[j] = (digit)(z - (twodigits)hi *
- _PyLong_DECIMAL_BASE);
- }
- while (hi) {
- pout[size++] = hi % _PyLong_DECIMAL_BASE;
- hi /= _PyLong_DECIMAL_BASE;
- }
- /* check for keyboard interrupt */
- SIGCHECK({
- Py_DECREF(scratch);
- return NULL;
- })
- }
- /* pout should have at least one digit, so that the case when a = 0
- works correctly */
- if (size == 0)
- pout[size++] = 0;
-
- /* calculate exact length of output string, and allocate */
- strlen = (addL != 0) + negative +
- 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
- tenpow = 10;
- rem = pout[size-1];
- while (rem >= tenpow) {
- tenpow *= 10;
- strlen++;
- }
- str = PyString_FromStringAndSize(NULL, strlen);
- if (str == NULL) {
- Py_DECREF(scratch);
- return NULL;
- }
-
- /* fill the string right-to-left */
- p = PyString_AS_STRING(str) + strlen;
- *p = '\0';
- if (addL)
- *--p = 'L';
- /* pout[0] through pout[size-2] contribute exactly
- _PyLong_DECIMAL_SHIFT digits each */
- for (i=0; i < size - 1; i++) {
- rem = pout[i];
- for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
- *--p = '0' + rem % 10;
- rem /= 10;
- }
- }
- /* pout[size-1]: always produce at least one decimal digit */
- rem = pout[i];
- do {
- *--p = '0' + rem % 10;
- rem /= 10;
- } while (rem != 0);
-
- /* and sign */
- if (negative)
- *--p = '-';
-
- /* check we've counted correctly */
- assert(p == PyString_AS_STRING(str));
- Py_DECREF(scratch);
- return (PyObject *)str;
+ PyLongObject *scratch, *a;
+ PyObject *str;
+ Py_ssize_t size, strlen, size_a, i, j;
+ digit *pout, *pin, rem, tenpow;
+ char *p;
+ int negative;
+
+ a = (PyLongObject *)aa;
+ if (a == NULL || !PyLong_Check(a)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ size_a = ABS(Py_SIZE(a));
+ negative = Py_SIZE(a) < 0;
+
+ /* quick and dirty upper bound for the number of digits
+ required to express a in base _PyLong_DECIMAL_BASE:
+
+ #digits = 1 + floor(log2(a) / log2(_PyLong_DECIMAL_BASE))
+
+ But log2(a) < size_a * PyLong_SHIFT, and
+ log2(_PyLong_DECIMAL_BASE) = log2(10) * _PyLong_DECIMAL_SHIFT
+ > 3 * _PyLong_DECIMAL_SHIFT
+ */
+ if (size_a > PY_SSIZE_T_MAX / PyLong_SHIFT) {
+ PyErr_SetString(PyExc_OverflowError,
+ "long is too large to format");
+ return NULL;
+ }
+ /* the expression size_a * PyLong_SHIFT is now safe from overflow */
+ size = 1 + size_a * PyLong_SHIFT / (3 * _PyLong_DECIMAL_SHIFT);
+ scratch = _PyLong_New(size);
+ if (scratch == NULL)
+ return NULL;
+
+ /* convert array of base _PyLong_BASE digits in pin to an array of
+ base _PyLong_DECIMAL_BASE digits in pout, following Knuth (TAOCP,
+ Volume 2 (3rd edn), section 4.4, Method 1b). */
+ pin = a->ob_digit;
+ pout = scratch->ob_digit;
+ size = 0;
+ for (i = size_a; --i >= 0; ) {
+ digit hi = pin[i];
+ for (j = 0; j < size; j++) {
+ twodigits z = (twodigits)pout[j] << PyLong_SHIFT | hi;
+ hi = (digit)(z / _PyLong_DECIMAL_BASE);
+ pout[j] = (digit)(z - (twodigits)hi *
+ _PyLong_DECIMAL_BASE);
+ }
+ while (hi) {
+ pout[size++] = hi % _PyLong_DECIMAL_BASE;
+ hi /= _PyLong_DECIMAL_BASE;
+ }
+ /* check for keyboard interrupt */
+ SIGCHECK({
+ Py_DECREF(scratch);
+ return NULL;
+ })
+ }
+ /* pout should have at least one digit, so that the case when a = 0
+ works correctly */
+ if (size == 0)
+ pout[size++] = 0;
+
+ /* calculate exact length of output string, and allocate */
+ strlen = (addL != 0) + negative +
+ 1 + (size - 1) * _PyLong_DECIMAL_SHIFT;
+ tenpow = 10;
+ rem = pout[size-1];
+ while (rem >= tenpow) {
+ tenpow *= 10;
+ strlen++;
+ }
+ str = PyString_FromStringAndSize(NULL, strlen);
+ if (str == NULL) {
+ Py_DECREF(scratch);
+ return NULL;
+ }
+
+ /* fill the string right-to-left */
+ p = PyString_AS_STRING(str) + strlen;
+ *p = '\0';
+ if (addL)
+ *--p = 'L';
+ /* pout[0] through pout[size-2] contribute exactly
+ _PyLong_DECIMAL_SHIFT digits each */
+ for (i=0; i < size - 1; i++) {
+ rem = pout[i];
+ for (j = 0; j < _PyLong_DECIMAL_SHIFT; j++) {
+ *--p = '0' + rem % 10;
+ rem /= 10;
+ }
+ }
+ /* pout[size-1]: always produce at least one decimal digit */
+ rem = pout[i];
+ do {
+ *--p = '0' + rem % 10;
+ rem /= 10;
+ } while (rem != 0);
+
+ /* and sign */
+ if (negative)
+ *--p = '-';
+
+ /* check we've counted correctly */
+ assert(p == PyString_AS_STRING(str));
+ Py_DECREF(scratch);
+ return (PyObject *)str;
}
/* Convert the long to a string object with given base,
@@ -1439,170 +1439,170 @@ long_to_decimal_string(PyObject *aa, int addL)
PyAPI_FUNC(PyObject *)
_PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
{
- register PyLongObject *a = (PyLongObject *)aa;
- PyStringObject *str;
- Py_ssize_t i, sz;
- Py_ssize_t size_a;
- char *p;
- int bits;
- char sign = '\0';
-
- if (base == 10)
- return long_to_decimal_string((PyObject *)a, addL);
-
- if (a == NULL || !PyLong_Check(a)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- assert(base >= 2 && base <= 36);
- size_a = ABS(Py_SIZE(a));
-
- /* Compute a rough upper bound for the length of the string */
- i = base;
- bits = 0;
- while (i > 1) {
- ++bits;
- i >>= 1;
- }
- i = 5 + (addL ? 1 : 0);
- /* ensure we don't get signed overflow in sz calculation */
- if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
- PyErr_SetString(PyExc_OverflowError,
- "long is too large to format");
- return NULL;
- }
- sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
- assert(sz >= 0);
- str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
- if (str == NULL)
- return NULL;
- p = PyString_AS_STRING(str) + sz;
- *p = '\0';
- if (addL)
- *--p = 'L';
- if (a->ob_size < 0)
- sign = '-';
-
- if (a->ob_size == 0) {
- *--p = '0';
- }
- else if ((base & (base - 1)) == 0) {
- /* JRH: special case for power-of-2 bases */
- twodigits accum = 0;
- int accumbits = 0; /* # of bits in accum */
- int basebits = 1; /* # of bits in base-1 */
- i = base;
- while ((i >>= 1) > 1)
- ++basebits;
-
- for (i = 0; i < size_a; ++i) {
- accum |= (twodigits)a->ob_digit[i] << accumbits;
- accumbits += PyLong_SHIFT;
- assert(accumbits >= basebits);
- do {
- char cdigit = (char)(accum & (base - 1));
- cdigit += (cdigit < 10) ? '0' : 'a'-10;
- assert(p > PyString_AS_STRING(str));
- *--p = cdigit;
- accumbits -= basebits;
- accum >>= basebits;
- } while (i < size_a-1 ? accumbits >= basebits :
- accum > 0);
- }
- }
- else {
- /* Not 0, and base not a power of 2. Divide repeatedly by
- base, but for speed use the highest power of base that
- fits in a digit. */
- Py_ssize_t size = size_a;
- digit *pin = a->ob_digit;
- PyLongObject *scratch;
- /* powbasw <- largest power of base that fits in a digit. */
- digit powbase = base; /* powbase == base ** power */
- int power = 1;
- for (;;) {
- twodigits newpow = powbase * (twodigits)base;
- if (newpow >> PyLong_SHIFT)
- /* doesn't fit in a digit */
- break;
- powbase = (digit)newpow;
- ++power;
- }
-
- /* Get a scratch area for repeated division. */
- scratch = _PyLong_New(size);
- if (scratch == NULL) {
- Py_DECREF(str);
- return NULL;
- }
-
- /* Repeatedly divide by powbase. */
- do {
- int ntostore = power;
- digit rem = inplace_divrem1(scratch->ob_digit,
- pin, size, powbase);
- pin = scratch->ob_digit; /* no need to use a again */
- if (pin[size - 1] == 0)
- --size;
- SIGCHECK({
- Py_DECREF(scratch);
- Py_DECREF(str);
- return NULL;
- })
-
- /* Break rem into digits. */
- assert(ntostore > 0);
- do {
- digit nextrem = (digit)(rem / base);
- char c = (char)(rem - nextrem * base);
- assert(p > PyString_AS_STRING(str));
- c += (c < 10) ? '0' : 'a'-10;
- *--p = c;
- rem = nextrem;
- --ntostore;
- /* Termination is a bit delicate: must not
- store leading zeroes, so must get out if
- remaining quotient and rem are both 0. */
- } while (ntostore && (size || rem));
- } while (size != 0);
- Py_DECREF(scratch);
- }
-
- if (base == 2) {
- *--p = 'b';
- *--p = '0';
- }
- else if (base == 8) {
- if (newstyle) {
- *--p = 'o';
- *--p = '0';
- }
- else
- if (size_a != 0)
- *--p = '0';
- }
- else if (base == 16) {
- *--p = 'x';
- *--p = '0';
- }
- else if (base != 10) {
- *--p = '#';
- *--p = '0' + base%10;
- if (base > 10)
- *--p = '0' + base/10;
- }
- if (sign)
- *--p = sign;
- if (p != PyString_AS_STRING(str)) {
- char *q = PyString_AS_STRING(str);
- assert(p > q);
- do {
- } while ((*q++ = *p++) != '\0');
- q--;
- _PyString_Resize((PyObject **)&str,
- (Py_ssize_t) (q - PyString_AS_STRING(str)));
- }
- return (PyObject *)str;
+ register PyLongObject *a = (PyLongObject *)aa;
+ PyStringObject *str;
+ Py_ssize_t i, sz;
+ Py_ssize_t size_a;
+ char *p;
+ int bits;
+ char sign = '\0';
+
+ if (base == 10)
+ return long_to_decimal_string((PyObject *)a, addL);
+
+ if (a == NULL || !PyLong_Check(a)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ assert(base >= 2 && base <= 36);
+ size_a = ABS(Py_SIZE(a));
+
+ /* Compute a rough upper bound for the length of the string */
+ i = base;
+ bits = 0;
+ while (i > 1) {
+ ++bits;
+ i >>= 1;
+ }
+ i = 5 + (addL ? 1 : 0);
+ /* ensure we don't get signed overflow in sz calculation */
+ if (size_a > (PY_SSIZE_T_MAX - i) / PyLong_SHIFT) {
+ PyErr_SetString(PyExc_OverflowError,
+ "long is too large to format");
+ return NULL;
+ }
+ sz = i + 1 + (size_a * PyLong_SHIFT - 1) / bits;
+ assert(sz >= 0);
+ str = (PyStringObject *) PyString_FromStringAndSize((char *)0, sz);
+ if (str == NULL)
+ return NULL;
+ p = PyString_AS_STRING(str) + sz;
+ *p = '\0';
+ if (addL)
+ *--p = 'L';
+ if (a->ob_size < 0)
+ sign = '-';
+
+ if (a->ob_size == 0) {
+ *--p = '0';
+ }
+ else if ((base & (base - 1)) == 0) {
+ /* JRH: special case for power-of-2 bases */
+ twodigits accum = 0;
+ int accumbits = 0; /* # of bits in accum */
+ int basebits = 1; /* # of bits in base-1 */
+ i = base;
+ while ((i >>= 1) > 1)
+ ++basebits;
+
+ for (i = 0; i < size_a; ++i) {
+ accum |= (twodigits)a->ob_digit[i] << accumbits;
+ accumbits += PyLong_SHIFT;
+ assert(accumbits >= basebits);
+ do {
+ char cdigit = (char)(accum & (base - 1));
+ cdigit += (cdigit < 10) ? '0' : 'a'-10;
+ assert(p > PyString_AS_STRING(str));
+ *--p = cdigit;
+ accumbits -= basebits;
+ accum >>= basebits;
+ } while (i < size_a-1 ? accumbits >= basebits :
+ accum > 0);
+ }
+ }
+ else {
+ /* Not 0, and base not a power of 2. Divide repeatedly by
+ base, but for speed use the highest power of base that
+ fits in a digit. */
+ Py_ssize_t size = size_a;
+ digit *pin = a->ob_digit;
+ PyLongObject *scratch;
+ /* powbasw <- largest power of base that fits in a digit. */
+ digit powbase = base; /* powbase == base ** power */
+ int power = 1;
+ for (;;) {
+ twodigits newpow = powbase * (twodigits)base;
+ if (newpow >> PyLong_SHIFT)
+ /* doesn't fit in a digit */
+ break;
+ powbase = (digit)newpow;
+ ++power;
+ }
+
+ /* Get a scratch area for repeated division. */
+ scratch = _PyLong_New(size);
+ if (scratch == NULL) {
+ Py_DECREF(str);
+ return NULL;
+ }
+
+ /* Repeatedly divide by powbase. */
+ do {
+ int ntostore = power;
+ digit rem = inplace_divrem1(scratch->ob_digit,
+ pin, size, powbase);
+ pin = scratch->ob_digit; /* no need to use a again */
+ if (pin[size - 1] == 0)
+ --size;
+ SIGCHECK({
+ Py_DECREF(scratch);
+ Py_DECREF(str);
+ return NULL;
+ })
+
+ /* Break rem into digits. */
+ assert(ntostore > 0);
+ do {
+ digit nextrem = (digit)(rem / base);
+ char c = (char)(rem - nextrem * base);
+ assert(p > PyString_AS_STRING(str));
+ c += (c < 10) ? '0' : 'a'-10;
+ *--p = c;
+ rem = nextrem;
+ --ntostore;
+ /* Termination is a bit delicate: must not
+ store leading zeroes, so must get out if
+ remaining quotient and rem are both 0. */
+ } while (ntostore && (size || rem));
+ } while (size != 0);
+ Py_DECREF(scratch);
+ }
+
+ if (base == 2) {
+ *--p = 'b';
+ *--p = '0';
+ }
+ else if (base == 8) {
+ if (newstyle) {
+ *--p = 'o';
+ *--p = '0';
+ }
+ else
+ if (size_a != 0)
+ *--p = '0';
+ }
+ else if (base == 16) {
+ *--p = 'x';
+ *--p = '0';
+ }
+ else if (base != 10) {
+ *--p = '#';
+ *--p = '0' + base%10;
+ if (base > 10)
+ *--p = '0' + base/10;
+ }
+ if (sign)
+ *--p = sign;
+ if (p != PyString_AS_STRING(str)) {
+ char *q = PyString_AS_STRING(str);
+ assert(p > q);
+ do {
+ } while ((*q++ = *p++) != '\0');
+ q--;
+ _PyString_Resize((PyObject **)&str,
+ (Py_ssize_t) (q - PyString_AS_STRING(str)));
+ }
+ return (PyObject *)str;
}
/* Table of digit values for 8-bit string -> integer conversion.
@@ -1613,22 +1613,22 @@ _PyLong_Format(PyObject *aa, int base, int addL, int newstyle)
* base B digit iff _PyLong_DigitValue[Py_CHARMASK(c)] < B.
*/
int _PyLong_DigitValue[256] = {
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
- 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
- 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
- 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
- 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
- 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 37, 37, 37, 37, 37, 37,
+ 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
+ 37, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
+ 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
+ 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37,
};
/* *str points to the first digit in a string of base `base` digits. base
@@ -1640,115 +1640,115 @@ int _PyLong_DigitValue[256] = {
static PyLongObject *
long_from_binary_base(char **str, int base)
{
- char *p = *str;
- char *start = p;
- int bits_per_char;
- Py_ssize_t n;
- PyLongObject *z;
- twodigits accum;
- int bits_in_accum;
- digit *pdigit;
-
- assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
- n = base;
- for (bits_per_char = -1; n; ++bits_per_char)
- n >>= 1;
- /* n <- total # of bits needed, while setting p to end-of-string */
- while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
- ++p;
- *str = p;
- /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
- n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
- if (n / bits_per_char < p - start) {
- PyErr_SetString(PyExc_ValueError,
- "long string too large to convert");
- return NULL;
- }
- n = n / PyLong_SHIFT;
- z = _PyLong_New(n);
- if (z == NULL)
- return NULL;
- /* Read string from right, and fill in long from left; i.e.,
- * from least to most significant in both.
- */
- accum = 0;
- bits_in_accum = 0;
- pdigit = z->ob_digit;
- while (--p >= start) {
- int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
- assert(k >= 0 && k < base);
- accum |= (twodigits)k << bits_in_accum;
- bits_in_accum += bits_per_char;
- if (bits_in_accum >= PyLong_SHIFT) {
- *pdigit++ = (digit)(accum & PyLong_MASK);
- assert(pdigit - z->ob_digit <= n);
- accum >>= PyLong_SHIFT;
- bits_in_accum -= PyLong_SHIFT;
- assert(bits_in_accum < PyLong_SHIFT);
- }
- }
- if (bits_in_accum) {
- assert(bits_in_accum <= PyLong_SHIFT);
- *pdigit++ = (digit)accum;
- assert(pdigit - z->ob_digit <= n);
- }
- while (pdigit - z->ob_digit < n)
- *pdigit++ = 0;
- return long_normalize(z);
+ char *p = *str;
+ char *start = p;
+ int bits_per_char;
+ Py_ssize_t n;
+ PyLongObject *z;
+ twodigits accum;
+ int bits_in_accum;
+ digit *pdigit;
+
+ assert(base >= 2 && base <= 32 && (base & (base - 1)) == 0);
+ n = base;
+ for (bits_per_char = -1; n; ++bits_per_char)
+ n >>= 1;
+ /* n <- total # of bits needed, while setting p to end-of-string */
+ while (_PyLong_DigitValue[Py_CHARMASK(*p)] < base)
+ ++p;
+ *str = p;
+ /* n <- # of Python digits needed, = ceiling(n/PyLong_SHIFT). */
+ n = (p - start) * bits_per_char + PyLong_SHIFT - 1;
+ if (n / bits_per_char < p - start) {
+ PyErr_SetString(PyExc_ValueError,
+ "long string too large to convert");
+ return NULL;
+ }
+ n = n / PyLong_SHIFT;
+ z = _PyLong_New(n);
+ if (z == NULL)
+ return NULL;
+ /* Read string from right, and fill in long from left; i.e.,
+ * from least to most significant in both.
+ */
+ accum = 0;
+ bits_in_accum = 0;
+ pdigit = z->ob_digit;
+ while (--p >= start) {
+ int k = _PyLong_DigitValue[Py_CHARMASK(*p)];
+ assert(k >= 0 && k < base);
+ accum |= (twodigits)k << bits_in_accum;
+ bits_in_accum += bits_per_char;
+ if (bits_in_accum >= PyLong_SHIFT) {
+ *pdigit++ = (digit)(accum & PyLong_MASK);
+ assert(pdigit - z->ob_digit <= n);
+ accum >>= PyLong_SHIFT;
+ bits_in_accum -= PyLong_SHIFT;
+ assert(bits_in_accum < PyLong_SHIFT);
+ }
+ }
+ if (bits_in_accum) {
+ assert(bits_in_accum <= PyLong_SHIFT);
+ *pdigit++ = (digit)accum;
+ assert(pdigit - z->ob_digit <= n);
+ }
+ while (pdigit - z->ob_digit < n)
+ *pdigit++ = 0;
+ return long_normalize(z);
}
PyObject *
PyLong_FromString(char *str, char **pend, int base)
{
- int sign = 1;
- char *start, *orig_str = str;
- PyLongObject *z;
- PyObject *strobj, *strrepr;
- Py_ssize_t slen;
-
- if ((base != 0 && base < 2) || base > 36) {
- PyErr_SetString(PyExc_ValueError,
- "long() arg 2 must be >= 2 and <= 36");
- return NULL;
- }
- while (*str != '\0' && isspace(Py_CHARMASK(*str)))
- str++;
- if (*str == '+')
- ++str;
- else if (*str == '-') {
- ++str;
- sign = -1;
- }
- while (*str != '\0' && isspace(Py_CHARMASK(*str)))
- str++;
- if (base == 0) {
- /* No base given. Deduce the base from the contents
- of the string */
- if (str[0] != '0')
- base = 10;
- else if (str[1] == 'x' || str[1] == 'X')
- base = 16;
- else if (str[1] == 'o' || str[1] == 'O')
- base = 8;
- else if (str[1] == 'b' || str[1] == 'B')
- base = 2;
- else
- /* "old" (C-style) octal literal, still valid in
- 2.x, although illegal in 3.x */
- base = 8;
- }
- /* Whether or not we were deducing the base, skip leading chars
- as needed */
- if (str[0] == '0' &&
- ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
- (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
- (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
- str += 2;
-
- start = str;
- if ((base & (base - 1)) == 0)
- z = long_from_binary_base(&str, base);
- else {
+ int sign = 1;
+ char *start, *orig_str = str;
+ PyLongObject *z;
+ PyObject *strobj, *strrepr;
+ Py_ssize_t slen;
+
+ if ((base != 0 && base < 2) || base > 36) {
+ PyErr_SetString(PyExc_ValueError,
+ "long() arg 2 must be >= 2 and <= 36");
+ return NULL;
+ }
+ while (*str != '\0' && isspace(Py_CHARMASK(*str)))
+ str++;
+ if (*str == '+')
+ ++str;
+ else if (*str == '-') {
+ ++str;
+ sign = -1;
+ }
+ while (*str != '\0' && isspace(Py_CHARMASK(*str)))
+ str++;
+ if (base == 0) {
+ /* No base given. Deduce the base from the contents
+ of the string */
+ if (str[0] != '0')
+ base = 10;
+ else if (str[1] == 'x' || str[1] == 'X')
+ base = 16;
+ else if (str[1] == 'o' || str[1] == 'O')
+ base = 8;
+ else if (str[1] == 'b' || str[1] == 'B')
+ base = 2;
+ else
+ /* "old" (C-style) octal literal, still valid in
+ 2.x, although illegal in 3.x */
+ base = 8;
+ }
+ /* Whether or not we were deducing the base, skip leading chars
+ as needed */
+ if (str[0] == '0' &&
+ ((base == 16 && (str[1] == 'x' || str[1] == 'X')) ||
+ (base == 8 && (str[1] == 'o' || str[1] == 'O')) ||
+ (base == 2 && (str[1] == 'b' || str[1] == 'B'))))
+ str += 2;
+
+ start = str;
+ if ((base & (base - 1)) == 0)
+ z = long_from_binary_base(&str, base);
+ else {
/***
Binary bases can be converted in time linear in the number of digits, because
Python's representation base is binary. Other bases (including decimal!) use
@@ -1834,225 +1834,225 @@ that triggers it(!). Instead the code was tested by artificially allocating
just 1 digit at the start, so that the copying code was exercised for every
digit beyond the first.
***/
- register twodigits c; /* current input character */
- Py_ssize_t size_z;
- int i;
- int convwidth;
- twodigits convmultmax, convmult;
- digit *pz, *pzstop;
- char* scan;
-
- static double log_base_PyLong_BASE[37] = {0.0e0,};
- static int convwidth_base[37] = {0,};
- static twodigits convmultmax_base[37] = {0,};
-
- if (log_base_PyLong_BASE[base] == 0.0) {
- twodigits convmax = base;
- int i = 1;
-
- log_base_PyLong_BASE[base] = log((double)base) /
- log((double)PyLong_BASE);
- for (;;) {
- twodigits next = convmax * base;
- if (next > PyLong_BASE)
- break;
- convmax = next;
- ++i;
- }
- convmultmax_base[base] = convmax;
- assert(i > 0);
- convwidth_base[base] = i;
- }
-
- /* Find length of the string of numeric characters. */
- scan = str;
- while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
- ++scan;
-
- /* Create a long object that can contain the largest possible
- * integer with this base and length. Note that there's no
- * need to initialize z->ob_digit -- no slot is read up before
- * being stored into.
- */
- size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
- /* Uncomment next line to test exceedingly rare copy code */
- /* size_z = 1; */
- assert(size_z > 0);
- z = _PyLong_New(size_z);
- if (z == NULL)
- return NULL;
- Py_SIZE(z) = 0;
-
- /* `convwidth` consecutive input digits are treated as a single
- * digit in base `convmultmax`.
- */
- convwidth = convwidth_base[base];
- convmultmax = convmultmax_base[base];
-
- /* Work ;-) */
- while (str < scan) {
- /* grab up to convwidth digits from the input string */
- c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
- for (i = 1; i < convwidth && str != scan; ++i, ++str) {
- c = (twodigits)(c * base +
- _PyLong_DigitValue[Py_CHARMASK(*str)]);
- assert(c < PyLong_BASE);
- }
-
- convmult = convmultmax;
- /* Calculate the shift only if we couldn't get
- * convwidth digits.
- */
- if (i != convwidth) {
- convmult = base;
- for ( ; i > 1; --i)
- convmult *= base;
- }
-
- /* Multiply z by convmult, and add c. */
- pz = z->ob_digit;
- pzstop = pz + Py_SIZE(z);
- for (; pz < pzstop; ++pz) {
- c += (twodigits)*pz * convmult;
- *pz = (digit)(c & PyLong_MASK);
- c >>= PyLong_SHIFT;
- }
- /* carry off the current end? */
- if (c) {
- assert(c < PyLong_BASE);
- if (Py_SIZE(z) < size_z) {
- *pz = (digit)c;
- ++Py_SIZE(z);
- }
- else {
- PyLongObject *tmp;
- /* Extremely rare. Get more space. */
- assert(Py_SIZE(z) == size_z);
- tmp = _PyLong_New(size_z + 1);
- if (tmp == NULL) {
- Py_DECREF(z);
- return NULL;
- }
- memcpy(tmp->ob_digit,
- z->ob_digit,
- sizeof(digit) * size_z);
- Py_DECREF(z);
- z = tmp;
- z->ob_digit[size_z] = (digit)c;
- ++size_z;
- }
- }
- }
- }
- if (z == NULL)
- return NULL;
- if (str == start)
- goto onError;
- if (sign < 0)
- Py_SIZE(z) = -(Py_SIZE(z));
- if (*str == 'L' || *str == 'l')
- str++;
- while (*str && isspace(Py_CHARMASK(*str)))
- str++;
- if (*str != '\0')
- goto onError;
- if (pend)
- *pend = str;
- return (PyObject *) z;
+ register twodigits c; /* current input character */
+ Py_ssize_t size_z;
+ int i;
+ int convwidth;
+ twodigits convmultmax, convmult;
+ digit *pz, *pzstop;
+ char* scan;
+
+ static double log_base_PyLong_BASE[37] = {0.0e0,};
+ static int convwidth_base[37] = {0,};
+ static twodigits convmultmax_base[37] = {0,};
+
+ if (log_base_PyLong_BASE[base] == 0.0) {
+ twodigits convmax = base;
+ int i = 1;
+
+ log_base_PyLong_BASE[base] = log((double)base) /
+ log((double)PyLong_BASE);
+ for (;;) {
+ twodigits next = convmax * base;
+ if (next > PyLong_BASE)
+ break;
+ convmax = next;
+ ++i;
+ }
+ convmultmax_base[base] = convmax;
+ assert(i > 0);
+ convwidth_base[base] = i;
+ }
+
+ /* Find length of the string of numeric characters. */
+ scan = str;
+ while (_PyLong_DigitValue[Py_CHARMASK(*scan)] < base)
+ ++scan;
+
+ /* Create a long object that can contain the largest possible
+ * integer with this base and length. Note that there's no
+ * need to initialize z->ob_digit -- no slot is read up before
+ * being stored into.
+ */
+ size_z = (Py_ssize_t)((scan - str) * log_base_PyLong_BASE[base]) + 1;
+ /* Uncomment next line to test exceedingly rare copy code */
+ /* size_z = 1; */
+ assert(size_z > 0);
+ z = _PyLong_New(size_z);
+ if (z == NULL)
+ return NULL;
+ Py_SIZE(z) = 0;
+
+ /* `convwidth` consecutive input digits are treated as a single
+ * digit in base `convmultmax`.
+ */
+ convwidth = convwidth_base[base];
+ convmultmax = convmultmax_base[base];
+
+ /* Work ;-) */
+ while (str < scan) {
+ /* grab up to convwidth digits from the input string */
+ c = (digit)_PyLong_DigitValue[Py_CHARMASK(*str++)];
+ for (i = 1; i < convwidth && str != scan; ++i, ++str) {
+ c = (twodigits)(c * base +
+ _PyLong_DigitValue[Py_CHARMASK(*str)]);
+ assert(c < PyLong_BASE);
+ }
+
+ convmult = convmultmax;
+ /* Calculate the shift only if we couldn't get
+ * convwidth digits.
+ */
+ if (i != convwidth) {
+ convmult = base;
+ for ( ; i > 1; --i)
+ convmult *= base;
+ }
+
+ /* Multiply z by convmult, and add c. */
+ pz = z->ob_digit;
+ pzstop = pz + Py_SIZE(z);
+ for (; pz < pzstop; ++pz) {
+ c += (twodigits)*pz * convmult;
+ *pz = (digit)(c & PyLong_MASK);
+ c >>= PyLong_SHIFT;
+ }
+ /* carry off the current end? */
+ if (c) {
+ assert(c < PyLong_BASE);
+ if (Py_SIZE(z) < size_z) {
+ *pz = (digit)c;
+ ++Py_SIZE(z);
+ }
+ else {
+ PyLongObject *tmp;
+ /* Extremely rare. Get more space. */
+ assert(Py_SIZE(z) == size_z);
+ tmp = _PyLong_New(size_z + 1);
+ if (tmp == NULL) {
+ Py_DECREF(z);
+ return NULL;
+ }
+ memcpy(tmp->ob_digit,
+ z->ob_digit,
+ sizeof(digit) * size_z);
+ Py_DECREF(z);
+ z = tmp;
+ z->ob_digit[size_z] = (digit)c;
+ ++size_z;
+ }
+ }
+ }
+ }
+ if (z == NULL)
+ return NULL;
+ if (str == start)
+ goto onError;
+ if (sign < 0)
+ Py_SIZE(z) = -(Py_SIZE(z));
+ if (*str == 'L' || *str == 'l')
+ str++;
+ while (*str && isspace(Py_CHARMASK(*str)))
+ str++;
+ if (*str != '\0')
+ goto onError;
+ if (pend)
+ *pend = str;
+ return (PyObject *) z;
onError:
- Py_XDECREF(z);
- slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
- strobj = PyString_FromStringAndSize(orig_str, slen);
- if (strobj == NULL)
- return NULL;
- strrepr = PyObject_Repr(strobj);
- Py_DECREF(strobj);
- if (strrepr == NULL)
- return NULL;
- PyErr_Format(PyExc_ValueError,
- "invalid literal for long() with base %d: %s",
- base, PyString_AS_STRING(strrepr));
- Py_DECREF(strrepr);
- return NULL;
+ Py_XDECREF(z);
+ slen = strlen(orig_str) < 200 ? strlen(orig_str) : 200;
+ strobj = PyString_FromStringAndSize(orig_str, slen);
+ if (strobj == NULL)
+ return NULL;
+ strrepr = PyObject_Repr(strobj);
+ Py_DECREF(strobj);
+ if (strrepr == NULL)
+ return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "invalid literal for long() with base %d: %s",
+ base, PyString_AS_STRING(strrepr));
+ Py_DECREF(strrepr);
+ return NULL;
}
#ifdef Py_USING_UNICODE
PyObject *
PyLong_FromUnicode(Py_UNICODE *u, Py_ssize_t length, int base)
{
- PyObject *result;
- char *buffer = (char *)PyMem_MALLOC(length+1);
-
- if (buffer == NULL)
- return NULL;
-
- if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
- PyMem_FREE(buffer);
- return NULL;
- }
- result = PyLong_FromString(buffer, NULL, base);
- PyMem_FREE(buffer);
- return result;
+ PyObject *result;
+ char *buffer = (char *)PyMem_MALLOC(length+1);
+
+ if (buffer == NULL)
+ return NULL;
+
+ if (PyUnicode_EncodeDecimal(u, length, buffer, NULL)) {
+ PyMem_FREE(buffer);
+ return NULL;
+ }
+ result = PyLong_FromString(buffer, NULL, base);
+ PyMem_FREE(buffer);
+ return result;
}
#endif
/* forward */
static PyLongObject *x_divrem
- (PyLongObject *, PyLongObject *, PyLongObject **);
+ (PyLongObject *, PyLongObject *, PyLongObject **);
static PyObject *long_long(PyObject *v);
/* Long division with remainder, top-level routine */
static int
long_divrem(PyLongObject *a, PyLongObject *b,
- PyLongObject **pdiv, PyLongObject **prem)
+ PyLongObject **pdiv, PyLongObject **prem)
{
- Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
- PyLongObject *z;
-
- if (size_b == 0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "long division or modulo by zero");
- return -1;
- }
- if (size_a < size_b ||
- (size_a == size_b &&
- a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
- /* |a| < |b|. */
- *pdiv = _PyLong_New(0);
- if (*pdiv == NULL)
- return -1;
- Py_INCREF(a);
- *prem = (PyLongObject *) a;
- return 0;
- }
- if (size_b == 1) {
- digit rem = 0;
- z = divrem1(a, b->ob_digit[0], &rem);
- if (z == NULL)
- return -1;
- *prem = (PyLongObject *) PyLong_FromLong((long)rem);
- if (*prem == NULL) {
- Py_DECREF(z);
- return -1;
- }
- }
- else {
- z = x_divrem(a, b, prem);
- if (z == NULL)
- return -1;
- }
- /* Set the signs.
- The quotient z has the sign of a*b;
- the remainder r has the sign of a,
- so a = b*z + r. */
- if ((a->ob_size < 0) != (b->ob_size < 0))
- z->ob_size = -(z->ob_size);
- if (a->ob_size < 0 && (*prem)->ob_size != 0)
- (*prem)->ob_size = -((*prem)->ob_size);
- *pdiv = z;
- return 0;
+ Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
+ PyLongObject *z;
+
+ if (size_b == 0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "long division or modulo by zero");
+ return -1;
+ }
+ if (size_a < size_b ||
+ (size_a == size_b &&
+ a->ob_digit[size_a-1] < b->ob_digit[size_b-1])) {
+ /* |a| < |b|. */
+ *pdiv = _PyLong_New(0);
+ if (*pdiv == NULL)
+ return -1;
+ Py_INCREF(a);
+ *prem = (PyLongObject *) a;
+ return 0;
+ }
+ if (size_b == 1) {
+ digit rem = 0;
+ z = divrem1(a, b->ob_digit[0], &rem);
+ if (z == NULL)
+ return -1;
+ *prem = (PyLongObject *) PyLong_FromLong((long)rem);
+ if (*prem == NULL) {
+ Py_DECREF(z);
+ return -1;
+ }
+ }
+ else {
+ z = x_divrem(a, b, prem);
+ if (z == NULL)
+ return -1;
+ }
+ /* Set the signs.
+ The quotient z has the sign of a*b;
+ the remainder r has the sign of a,
+ so a = b*z + r. */
+ if ((a->ob_size < 0) != (b->ob_size < 0))
+ z->ob_size = -(z->ob_size);
+ if (a->ob_size < 0 && (*prem)->ob_size != 0)
+ (*prem)->ob_size = -((*prem)->ob_size);
+ *pdiv = z;
+ return 0;
}
/* Unsigned long division with remainder -- the algorithm. The arguments v1
@@ -2061,125 +2061,125 @@ long_divrem(PyLongObject *a, PyLongObject *b,
static PyLongObject *
x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
{
- PyLongObject *v, *w, *a;
- Py_ssize_t i, k, size_v, size_w;
- int d;
- digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
- twodigits vv;
- sdigit zhi;
- stwodigits z;
-
- /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
- edn.), section 4.3.1, Algorithm D], except that we don't explicitly
- handle the special case when the initial estimate q for a quotient
- digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
- that won't overflow a digit. */
-
- /* allocate space; w will also be used to hold the final remainder */
- size_v = ABS(Py_SIZE(v1));
- size_w = ABS(Py_SIZE(w1));
- assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
- v = _PyLong_New(size_v+1);
- if (v == NULL) {
- *prem = NULL;
- return NULL;
- }
- w = _PyLong_New(size_w);
- if (w == NULL) {
- Py_DECREF(v);
- *prem = NULL;
- return NULL;
- }
-
- /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
- shift v1 left by the same amount. Results go into w and v. */
- d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
- carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
- assert(carry == 0);
- carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
- if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
- v->ob_digit[size_v] = carry;
- size_v++;
- }
-
- /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
- at most (and usually exactly) k = size_v - size_w digits. */
- k = size_v - size_w;
- assert(k >= 0);
- a = _PyLong_New(k);
- if (a == NULL) {
- Py_DECREF(w);
- Py_DECREF(v);
- *prem = NULL;
- return NULL;
- }
- v0 = v->ob_digit;
- w0 = w->ob_digit;
- wm1 = w0[size_w-1];
- wm2 = w0[size_w-2];
- for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
- /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
- single-digit quotient q, remainder in vk[0:size_w]. */
-
- SIGCHECK({
- Py_DECREF(a);
- Py_DECREF(w);
- Py_DECREF(v);
- *prem = NULL;
- return NULL;
- })
-
- /* estimate quotient digit q; may overestimate by 1 (rare) */
- vtop = vk[size_w];
- assert(vtop <= wm1);
- vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
- q = (digit)(vv / wm1);
- r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
- while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
- | vk[size_w-2])) {
- --q;
- r += wm1;
- if (r >= PyLong_BASE)
- break;
- }
- assert(q <= PyLong_BASE);
-
- /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
- zhi = 0;
- for (i = 0; i < size_w; ++i) {
- /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
- -PyLong_BASE * q <= z < PyLong_BASE */
- z = (sdigit)vk[i] + zhi -
- (stwodigits)q * (stwodigits)w0[i];
- vk[i] = (digit)z & PyLong_MASK;
- zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
- z, PyLong_SHIFT);
- }
-
- /* add w back if q was too large (this branch taken rarely) */
- assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
- if ((sdigit)vtop + zhi < 0) {
- carry = 0;
- for (i = 0; i < size_w; ++i) {
- carry += vk[i] + w0[i];
- vk[i] = carry & PyLong_MASK;
- carry >>= PyLong_SHIFT;
- }
- --q;
- }
-
- /* store quotient digit */
- assert(q < PyLong_BASE);
- *--ak = q;
- }
-
- /* unshift remainder; we reuse w to store the result */
- carry = v_rshift(w0, v0, size_w, d);
- assert(carry==0);
- Py_DECREF(v);
-
- *prem = long_normalize(w);
- return long_normalize(a);
+ PyLongObject *v, *w, *a;
+ Py_ssize_t i, k, size_v, size_w;
+ int d;
+ digit wm1, wm2, carry, q, r, vtop, *v0, *vk, *w0, *ak;
+ twodigits vv;
+ sdigit zhi;
+ stwodigits z;
+
+ /* We follow Knuth [The Art of Computer Programming, Vol. 2 (3rd
+ edn.), section 4.3.1, Algorithm D], except that we don't explicitly
+ handle the special case when the initial estimate q for a quotient
+ digit is >= PyLong_BASE: the max value for q is PyLong_BASE+1, and
+ that won't overflow a digit. */
+
+ /* allocate space; w will also be used to hold the final remainder */
+ size_v = ABS(Py_SIZE(v1));
+ size_w = ABS(Py_SIZE(w1));
+ assert(size_v >= size_w && size_w >= 2); /* Assert checks by div() */
+ v = _PyLong_New(size_v+1);
+ if (v == NULL) {
+ *prem = NULL;
+ return NULL;
+ }
+ w = _PyLong_New(size_w);
+ if (w == NULL) {
+ Py_DECREF(v);
+ *prem = NULL;
+ return NULL;
+ }
+
+ /* normalize: shift w1 left so that its top digit is >= PyLong_BASE/2.
+ shift v1 left by the same amount. Results go into w and v. */
+ d = PyLong_SHIFT - bits_in_digit(w1->ob_digit[size_w-1]);
+ carry = v_lshift(w->ob_digit, w1->ob_digit, size_w, d);
+ assert(carry == 0);
+ carry = v_lshift(v->ob_digit, v1->ob_digit, size_v, d);
+ if (carry != 0 || v->ob_digit[size_v-1] >= w->ob_digit[size_w-1]) {
+ v->ob_digit[size_v] = carry;
+ size_v++;
+ }
+
+ /* Now v->ob_digit[size_v-1] < w->ob_digit[size_w-1], so quotient has
+ at most (and usually exactly) k = size_v - size_w digits. */
+ k = size_v - size_w;
+ assert(k >= 0);
+ a = _PyLong_New(k);
+ if (a == NULL) {
+ Py_DECREF(w);
+ Py_DECREF(v);
+ *prem = NULL;
+ return NULL;
+ }
+ v0 = v->ob_digit;
+ w0 = w->ob_digit;
+ wm1 = w0[size_w-1];
+ wm2 = w0[size_w-2];
+ for (vk = v0+k, ak = a->ob_digit + k; vk-- > v0;) {
+ /* inner loop: divide vk[0:size_w+1] by w0[0:size_w], giving
+ single-digit quotient q, remainder in vk[0:size_w]. */
+
+ SIGCHECK({
+ Py_DECREF(a);
+ Py_DECREF(w);
+ Py_DECREF(v);
+ *prem = NULL;
+ return NULL;
+ })
+
+ /* estimate quotient digit q; may overestimate by 1 (rare) */
+ vtop = vk[size_w];
+ assert(vtop <= wm1);
+ vv = ((twodigits)vtop << PyLong_SHIFT) | vk[size_w-1];
+ q = (digit)(vv / wm1);
+ r = (digit)(vv - (twodigits)wm1 * q); /* r = vv % wm1 */
+ while ((twodigits)wm2 * q > (((twodigits)r << PyLong_SHIFT)
+ | vk[size_w-2])) {
+ --q;
+ r += wm1;
+ if (r >= PyLong_BASE)
+ break;
+ }
+ assert(q <= PyLong_BASE);
+
+ /* subtract q*w0[0:size_w] from vk[0:size_w+1] */
+ zhi = 0;
+ for (i = 0; i < size_w; ++i) {
+ /* invariants: -PyLong_BASE <= -q <= zhi <= 0;
+ -PyLong_BASE * q <= z < PyLong_BASE */
+ z = (sdigit)vk[i] + zhi -
+ (stwodigits)q * (stwodigits)w0[i];
+ vk[i] = (digit)z & PyLong_MASK;
+ zhi = (sdigit)Py_ARITHMETIC_RIGHT_SHIFT(stwodigits,
+ z, PyLong_SHIFT);
+ }
+
+ /* add w back if q was too large (this branch taken rarely) */
+ assert((sdigit)vtop + zhi == -1 || (sdigit)vtop + zhi == 0);
+ if ((sdigit)vtop + zhi < 0) {
+ carry = 0;
+ for (i = 0; i < size_w; ++i) {
+ carry += vk[i] + w0[i];
+ vk[i] = carry & PyLong_MASK;
+ carry >>= PyLong_SHIFT;
+ }
+ --q;
+ }
+
+ /* store quotient digit */
+ assert(q < PyLong_BASE);
+ *--ak = q;
+ }
+
+ /* unshift remainder; we reuse w to store the result */
+ carry = v_rshift(w0, v0, size_w, d);
+ assert(carry==0);
+ Py_DECREF(v);
+
+ *prem = long_normalize(w);
+ return long_normalize(a);
}
/* For a nonzero PyLong a, express a in the form x * 2**e, with 0.5 <=
@@ -2199,111 +2199,111 @@ x_divrem(PyLongObject *v1, PyLongObject *w1, PyLongObject **prem)
double
_PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
{
- Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
- /* See below for why x_digits is always large enough. */
- digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
- double dx;
- /* Correction term for round-half-to-even rounding. For a digit x,
- "x + half_even_correction[x & 7]" gives x rounded to the nearest
- multiple of 4, rounding ties to a multiple of 8. */
- static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
-
- a_size = ABS(Py_SIZE(a));
- if (a_size == 0) {
- /* Special case for 0: significand 0.0, exponent 0. */
- *e = 0;
- return 0.0;
- }
- a_bits = bits_in_digit(a->ob_digit[a_size-1]);
- /* The following is an overflow-free version of the check
- "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
- if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
- (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
- a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
- goto overflow;
- a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
-
- /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
- (shifting left if a_bits <= DBL_MANT_DIG + 2).
-
- Number of digits needed for result: write // for floor division.
- Then if shifting left, we end up using
-
- 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
-
- digits. If shifting right, we use
-
- a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
-
- digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
- the inequalities
-
- m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
- m // PyLong_SHIFT - n // PyLong_SHIFT <=
- 1 + (m - n - 1) // PyLong_SHIFT,
-
- valid for any integers m and n, we find that x_size satisfies
-
- x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
-
- in both cases.
- */
- if (a_bits <= DBL_MANT_DIG + 2) {
- shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
- shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
- x_size = 0;
- while (x_size < shift_digits)
- x_digits[x_size++] = 0;
- rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
- (int)shift_bits);
- x_size += a_size;
- x_digits[x_size++] = rem;
- }
- else {
- shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
- shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
- rem = v_rshift(x_digits, a->ob_digit + shift_digits,
- a_size - shift_digits, (int)shift_bits);
- x_size = a_size - shift_digits;
- /* For correct rounding below, we need the least significant
- bit of x to be 'sticky' for this shift: if any of the bits
- shifted out was nonzero, we set the least significant bit
- of x. */
- if (rem)
- x_digits[0] |= 1;
- else
- while (shift_digits > 0)
- if (a->ob_digit[--shift_digits]) {
- x_digits[0] |= 1;
- break;
- }
- }
- assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
-
- /* Round, and convert to double. */
- x_digits[0] += half_even_correction[x_digits[0] & 7];
- dx = x_digits[--x_size];
- while (x_size > 0)
- dx = dx * PyLong_BASE + x_digits[--x_size];
-
- /* Rescale; make correction if result is 1.0. */
- dx /= 4.0 * EXP2_DBL_MANT_DIG;
- if (dx == 1.0) {
- if (a_bits == PY_SSIZE_T_MAX)
- goto overflow;
- dx = 0.5;
- a_bits += 1;
- }
-
- *e = a_bits;
- return Py_SIZE(a) < 0 ? -dx : dx;
+ Py_ssize_t a_size, a_bits, shift_digits, shift_bits, x_size;
+ /* See below for why x_digits is always large enough. */
+ digit rem, x_digits[2 + (DBL_MANT_DIG + 1) / PyLong_SHIFT];
+ double dx;
+ /* Correction term for round-half-to-even rounding. For a digit x,
+ "x + half_even_correction[x & 7]" gives x rounded to the nearest
+ multiple of 4, rounding ties to a multiple of 8. */
+ static const int half_even_correction[8] = {0, -1, -2, 1, 0, -1, 2, 1};
+
+ a_size = ABS(Py_SIZE(a));
+ if (a_size == 0) {
+ /* Special case for 0: significand 0.0, exponent 0. */
+ *e = 0;
+ return 0.0;
+ }
+ a_bits = bits_in_digit(a->ob_digit[a_size-1]);
+ /* The following is an overflow-free version of the check
+ "if ((a_size - 1) * PyLong_SHIFT + a_bits > PY_SSIZE_T_MAX) ..." */
+ if (a_size >= (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 &&
+ (a_size > (PY_SSIZE_T_MAX - 1) / PyLong_SHIFT + 1 ||
+ a_bits > (PY_SSIZE_T_MAX - 1) % PyLong_SHIFT + 1))
+ goto overflow;
+ a_bits = (a_size - 1) * PyLong_SHIFT + a_bits;
+
+ /* Shift the first DBL_MANT_DIG + 2 bits of a into x_digits[0:x_size]
+ (shifting left if a_bits <= DBL_MANT_DIG + 2).
+
+ Number of digits needed for result: write // for floor division.
+ Then if shifting left, we end up using
+
+ 1 + a_size + (DBL_MANT_DIG + 2 - a_bits) // PyLong_SHIFT
+
+ digits. If shifting right, we use
+
+ a_size - (a_bits - DBL_MANT_DIG - 2) // PyLong_SHIFT
+
+ digits. Using a_size = 1 + (a_bits - 1) // PyLong_SHIFT along with
+ the inequalities
+
+ m // PyLong_SHIFT + n // PyLong_SHIFT <= (m + n) // PyLong_SHIFT
+ m // PyLong_SHIFT - n // PyLong_SHIFT <=
+ 1 + (m - n - 1) // PyLong_SHIFT,
+
+ valid for any integers m and n, we find that x_size satisfies
+
+ x_size <= 2 + (DBL_MANT_DIG + 1) // PyLong_SHIFT
+
+ in both cases.
+ */
+ if (a_bits <= DBL_MANT_DIG + 2) {
+ shift_digits = (DBL_MANT_DIG + 2 - a_bits) / PyLong_SHIFT;
+ shift_bits = (DBL_MANT_DIG + 2 - a_bits) % PyLong_SHIFT;
+ x_size = 0;
+ while (x_size < shift_digits)
+ x_digits[x_size++] = 0;
+ rem = v_lshift(x_digits + x_size, a->ob_digit, a_size,
+ (int)shift_bits);
+ x_size += a_size;
+ x_digits[x_size++] = rem;
+ }
+ else {
+ shift_digits = (a_bits - DBL_MANT_DIG - 2) / PyLong_SHIFT;
+ shift_bits = (a_bits - DBL_MANT_DIG - 2) % PyLong_SHIFT;
+ rem = v_rshift(x_digits, a->ob_digit + shift_digits,
+ a_size - shift_digits, (int)shift_bits);
+ x_size = a_size - shift_digits;
+ /* For correct rounding below, we need the least significant
+ bit of x to be 'sticky' for this shift: if any of the bits
+ shifted out was nonzero, we set the least significant bit
+ of x. */
+ if (rem)
+ x_digits[0] |= 1;
+ else
+ while (shift_digits > 0)
+ if (a->ob_digit[--shift_digits]) {
+ x_digits[0] |= 1;
+ break;
+ }
+ }
+ assert(1 <= x_size && x_size <= (Py_ssize_t)(sizeof(x_digits)/sizeof(digit)));
+
+ /* Round, and convert to double. */
+ x_digits[0] += half_even_correction[x_digits[0] & 7];
+ dx = x_digits[--x_size];
+ while (x_size > 0)
+ dx = dx * PyLong_BASE + x_digits[--x_size];
+
+ /* Rescale; make correction if result is 1.0. */
+ dx /= 4.0 * EXP2_DBL_MANT_DIG;
+ if (dx == 1.0) {
+ if (a_bits == PY_SSIZE_T_MAX)
+ goto overflow;
+ dx = 0.5;
+ a_bits += 1;
+ }
+
+ *e = a_bits;
+ return Py_SIZE(a) < 0 ? -dx : dx;
overflow:
- /* exponent > PY_SSIZE_T_MAX */
- PyErr_SetString(PyExc_OverflowError,
- "huge integer: number of bits overflows a Py_ssize_t");
- *e = 0;
- return -1.0;
+ /* exponent > PY_SSIZE_T_MAX */
+ PyErr_SetString(PyExc_OverflowError,
+ "huge integer: number of bits overflows a Py_ssize_t");
+ *e = 0;
+ return -1.0;
}
/* Get a C double from a long int object. Rounds to the nearest double,
@@ -2312,20 +2312,20 @@ _PyLong_Frexp(PyLongObject *a, Py_ssize_t *e)
double
PyLong_AsDouble(PyObject *v)
{
- Py_ssize_t exponent;
- double x;
-
- if (v == NULL || !PyLong_Check(v)) {
- PyErr_BadInternalCall();
- return -1.0;
- }
- x = _PyLong_Frexp((PyLongObject *)v, &exponent);
- if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
- PyErr_SetString(PyExc_OverflowError,
- "long int too large to convert to float");
- return -1.0;
- }
- return ldexp(x, (int)exponent);
+ Py_ssize_t exponent;
+ double x;
+
+ if (v == NULL || !PyLong_Check(v)) {
+ PyErr_BadInternalCall();
+ return -1.0;
+ }
+ x = _PyLong_Frexp((PyLongObject *)v, &exponent);
+ if ((x == -1.0 && PyErr_Occurred()) || exponent > DBL_MAX_EXP) {
+ PyErr_SetString(PyExc_OverflowError,
+ "long int too large to convert to float");
+ return -1.0;
+ }
+ return ldexp(x, (int)exponent);
}
/* Methods */
@@ -2333,78 +2333,78 @@ PyLong_AsDouble(PyObject *v)
static void
long_dealloc(PyObject *v)
{
- Py_TYPE(v)->tp_free(v);
+ Py_TYPE(v)->tp_free(v);
}
static PyObject *
long_repr(PyObject *v)
{
- return _PyLong_Format(v, 10, 1, 0);
+ return _PyLong_Format(v, 10, 1, 0);
}
static PyObject *
long_str(PyObject *v)
{
- return _PyLong_Format(v, 10, 0, 0);
+ return _PyLong_Format(v, 10, 0, 0);
}
static int
long_compare(PyLongObject *a, PyLongObject *b)
{
- Py_ssize_t sign;
-
- if (Py_SIZE(a) != Py_SIZE(b)) {
- sign = Py_SIZE(a) - Py_SIZE(b);
- }
- else {
- Py_ssize_t i = ABS(Py_SIZE(a));
- while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
- ;
- if (i < 0)
- sign = 0;
- else {
- sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
- if (Py_SIZE(a) < 0)
- sign = -sign;
- }
- }
- return sign < 0 ? -1 : sign > 0 ? 1 : 0;
+ Py_ssize_t sign;
+
+ if (Py_SIZE(a) != Py_SIZE(b)) {
+ sign = Py_SIZE(a) - Py_SIZE(b);
+ }
+ else {
+ Py_ssize_t i = ABS(Py_SIZE(a));
+ while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
+ ;
+ if (i < 0)
+ sign = 0;
+ else {
+ sign = (sdigit)a->ob_digit[i] - (sdigit)b->ob_digit[i];
+ if (Py_SIZE(a) < 0)
+ sign = -sign;
+ }
+ }
+ return sign < 0 ? -1 : sign > 0 ? 1 : 0;
}
static long
long_hash(PyLongObject *v)
{
- unsigned long x;
- Py_ssize_t i;
- int sign;
-
- /* This is designed so that Python ints and longs with the
- same value hash to the same value, otherwise comparisons
- of mapping keys will turn out weird */
- i = v->ob_size;
- sign = 1;
- x = 0;
- if (i < 0) {
- sign = -1;
- i = -(i);
- }
- /* The following loop produces a C unsigned long x such that x is
- congruent to the absolute value of v modulo ULONG_MAX. The
- resulting x is nonzero if and only if v is. */
- while (--i >= 0) {
- /* Force a native long #-bits (32 or 64) circular shift */
- x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
- x += v->ob_digit[i];
- /* If the addition above overflowed we compensate by
- incrementing. This preserves the value modulo
- ULONG_MAX. */
- if (x < v->ob_digit[i])
- x++;
- }
- x = x * sign;
- if (x == (unsigned long)-1)
- x = (unsigned long)-2;
- return (long)x;
+ unsigned long x;
+ Py_ssize_t i;
+ int sign;
+
+ /* This is designed so that Python ints and longs with the
+ same value hash to the same value, otherwise comparisons
+ of mapping keys will turn out weird */
+ i = v->ob_size;
+ sign = 1;
+ x = 0;
+ if (i < 0) {
+ sign = -1;
+ i = -(i);
+ }
+ /* The following loop produces a C unsigned long x such that x is
+ congruent to the absolute value of v modulo ULONG_MAX. The
+ resulting x is nonzero if and only if v is. */
+ while (--i >= 0) {
+ /* Force a native long #-bits (32 or 64) circular shift */
+ x = (x >> (8*SIZEOF_LONG-PyLong_SHIFT)) | (x << PyLong_SHIFT);
+ x += v->ob_digit[i];
+ /* If the addition above overflowed we compensate by
+ incrementing. This preserves the value modulo
+ ULONG_MAX. */
+ if (x < v->ob_digit[i])
+ x++;
+ }
+ x = x * sign;
+ if (x == (unsigned long)-1)
+ x = (unsigned long)-2;
+ return (long)x;
}
@@ -2413,33 +2413,33 @@ long_hash(PyLongObject *v)
static PyLongObject *
x_add(PyLongObject *a, PyLongObject *b)
{
- Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
- PyLongObject *z;
- Py_ssize_t i;
- digit carry = 0;
-
- /* Ensure a is the larger of the two: */
- if (size_a < size_b) {
- { PyLongObject *temp = a; a = b; b = temp; }
- { Py_ssize_t size_temp = size_a;
- size_a = size_b;
- size_b = size_temp; }
- }
- z = _PyLong_New(size_a+1);
- if (z == NULL)
- return NULL;
- for (i = 0; i < size_b; ++i) {
- carry += a->ob_digit[i] + b->ob_digit[i];
- z->ob_digit[i] = carry & PyLong_MASK;
- carry >>= PyLong_SHIFT;
- }
- for (; i < size_a; ++i) {
- carry += a->ob_digit[i];
- z->ob_digit[i] = carry & PyLong_MASK;
- carry >>= PyLong_SHIFT;
- }
- z->ob_digit[i] = carry;
- return long_normalize(z);
+ Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
+ PyLongObject *z;
+ Py_ssize_t i;
+ digit carry = 0;
+
+ /* Ensure a is the larger of the two: */
+ if (size_a < size_b) {
+ { PyLongObject *temp = a; a = b; b = temp; }
+ { Py_ssize_t size_temp = size_a;
+ size_a = size_b;
+ size_b = size_temp; }
+ }
+ z = _PyLong_New(size_a+1);
+ if (z == NULL)
+ return NULL;
+ for (i = 0; i < size_b; ++i) {
+ carry += a->ob_digit[i] + b->ob_digit[i];
+ z->ob_digit[i] = carry & PyLong_MASK;
+ carry >>= PyLong_SHIFT;
+ }
+ for (; i < size_a; ++i) {
+ carry += a->ob_digit[i];
+ z->ob_digit[i] = carry & PyLong_MASK;
+ carry >>= PyLong_SHIFT;
+ }
+ z->ob_digit[i] = carry;
+ return long_normalize(z);
}
/* Subtract the absolute values of two integers. */
@@ -2447,107 +2447,107 @@ x_add(PyLongObject *a, PyLongObject *b)
static PyLongObject *
x_sub(PyLongObject *a, PyLongObject *b)
{
- Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
- PyLongObject *z;
- Py_ssize_t i;
- int sign = 1;
- digit borrow = 0;
-
- /* Ensure a is the larger of the two: */
- if (size_a < size_b) {
- sign = -1;
- { PyLongObject *temp = a; a = b; b = temp; }
- { Py_ssize_t size_temp = size_a;
- size_a = size_b;
- size_b = size_temp; }
- }
- else if (size_a == size_b) {
- /* Find highest digit where a and b differ: */
- i = size_a;
- while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
- ;
- if (i < 0)
- return _PyLong_New(0);
- if (a->ob_digit[i] < b->ob_digit[i]) {
- sign = -1;
- { PyLongObject *temp = a; a = b; b = temp; }
- }
- size_a = size_b = i+1;
- }
- z = _PyLong_New(size_a);
- if (z == NULL)
- return NULL;
- for (i = 0; i < size_b; ++i) {
- /* The following assumes unsigned arithmetic
- works module 2**N for some N>PyLong_SHIFT. */
- borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
- z->ob_digit[i] = borrow & PyLong_MASK;
- borrow >>= PyLong_SHIFT;
- borrow &= 1; /* Keep only one sign bit */
- }
- for (; i < size_a; ++i) {
- borrow = a->ob_digit[i] - borrow;
- z->ob_digit[i] = borrow & PyLong_MASK;
- borrow >>= PyLong_SHIFT;
- borrow &= 1; /* Keep only one sign bit */
- }
- assert(borrow == 0);
- if (sign < 0)
- z->ob_size = -(z->ob_size);
- return long_normalize(z);
+ Py_ssize_t size_a = ABS(Py_SIZE(a)), size_b = ABS(Py_SIZE(b));
+ PyLongObject *z;
+ Py_ssize_t i;
+ int sign = 1;
+ digit borrow = 0;
+
+ /* Ensure a is the larger of the two: */
+ if (size_a < size_b) {
+ sign = -1;
+ { PyLongObject *temp = a; a = b; b = temp; }
+ { Py_ssize_t size_temp = size_a;
+ size_a = size_b;
+ size_b = size_temp; }
+ }
+ else if (size_a == size_b) {
+ /* Find highest digit where a and b differ: */
+ i = size_a;
+ while (--i >= 0 && a->ob_digit[i] == b->ob_digit[i])
+ ;
+ if (i < 0)
+ return _PyLong_New(0);
+ if (a->ob_digit[i] < b->ob_digit[i]) {
+ sign = -1;
+ { PyLongObject *temp = a; a = b; b = temp; }
+ }
+ size_a = size_b = i+1;
+ }
+ z = _PyLong_New(size_a);
+ if (z == NULL)
+ return NULL;
+ for (i = 0; i < size_b; ++i) {
+ /* The following assumes unsigned arithmetic
+ works module 2**N for some N>PyLong_SHIFT. */
+ borrow = a->ob_digit[i] - b->ob_digit[i] - borrow;
+ z->ob_digit[i] = borrow & PyLong_MASK;
+ borrow >>= PyLong_SHIFT;
+ borrow &= 1; /* Keep only one sign bit */
+ }
+ for (; i < size_a; ++i) {
+ borrow = a->ob_digit[i] - borrow;
+ z->ob_digit[i] = borrow & PyLong_MASK;
+ borrow >>= PyLong_SHIFT;
+ borrow &= 1; /* Keep only one sign bit */
+ }
+ assert(borrow == 0);
+ if (sign < 0)
+ z->ob_size = -(z->ob_size);
+ return long_normalize(z);
}
static PyObject *
long_add(PyLongObject *v, PyLongObject *w)
{
- PyLongObject *a, *b, *z;
-
- CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
-
- if (a->ob_size < 0) {
- if (b->ob_size < 0) {
- z = x_add(a, b);
- if (z != NULL && z->ob_size != 0)
- z->ob_size = -(z->ob_size);
- }
- else
- z = x_sub(b, a);
- }
- else {
- if (b->ob_size < 0)
- z = x_sub(a, b);
- else
- z = x_add(a, b);
- }
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)z;
+ PyLongObject *a, *b, *z;
+
+ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
+
+ if (a->ob_size < 0) {
+ if (b->ob_size < 0) {
+ z = x_add(a, b);
+ if (z != NULL && z->ob_size != 0)
+ z->ob_size = -(z->ob_size);
+ }
+ else
+ z = x_sub(b, a);
+ }
+ else {
+ if (b->ob_size < 0)
+ z = x_sub(a, b);
+ else
+ z = x_add(a, b);
+ }
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)z;
}
static PyObject *
long_sub(PyLongObject *v, PyLongObject *w)
{
- PyLongObject *a, *b, *z;
-
- CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
-
- if (a->ob_size < 0) {
- if (b->ob_size < 0)
- z = x_sub(a, b);
- else
- z = x_add(a, b);
- if (z != NULL && z->ob_size != 0)
- z->ob_size = -(z->ob_size);
- }
- else {
- if (b->ob_size < 0)
- z = x_add(a, b);
- else
- z = x_sub(a, b);
- }
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)z;
+ PyLongObject *a, *b, *z;
+
+ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
+
+ if (a->ob_size < 0) {
+ if (b->ob_size < 0)
+ z = x_sub(a, b);
+ else
+ z = x_add(a, b);
+ if (z != NULL && z->ob_size != 0)
+ z->ob_size = -(z->ob_size);
+ }
+ else {
+ if (b->ob_size < 0)
+ z = x_add(a, b);
+ else
+ z = x_sub(a, b);
+ }
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)z;
}
/* Grade school multiplication, ignoring the signs.
@@ -2556,85 +2556,85 @@ long_sub(PyLongObject *v, PyLongObject *w)
static PyLongObject *
x_mul(PyLongObject *a, PyLongObject *b)
{
- PyLongObject *z;
- Py_ssize_t size_a = ABS(Py_SIZE(a));
- Py_ssize_t size_b = ABS(Py_SIZE(b));
- Py_ssize_t i;
-
- z = _PyLong_New(size_a + size_b);
- if (z == NULL)
- return NULL;
-
- memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
- if (a == b) {
- /* Efficient squaring per HAC, Algorithm 14.16:
- * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
- * Gives slightly less than a 2x speedup when a == b,
- * via exploiting that each entry in the multiplication
- * pyramid appears twice (except for the size_a squares).
- */
- for (i = 0; i < size_a; ++i) {
- twodigits carry;
- twodigits f = a->ob_digit[i];
- digit *pz = z->ob_digit + (i << 1);
- digit *pa = a->ob_digit + i + 1;
- digit *paend = a->ob_digit + size_a;
-
- SIGCHECK({
- Py_DECREF(z);
- return NULL;
- })
-
- carry = *pz + f * f;
- *pz++ = (digit)(carry & PyLong_MASK);
- carry >>= PyLong_SHIFT;
- assert(carry <= PyLong_MASK);
-
- /* Now f is added in twice in each column of the
- * pyramid it appears. Same as adding f<<1 once.
- */
- f <<= 1;
- while (pa < paend) {
- carry += *pz + *pa++ * f;
- *pz++ = (digit)(carry & PyLong_MASK);
- carry >>= PyLong_SHIFT;
- assert(carry <= (PyLong_MASK << 1));
- }
- if (carry) {
- carry += *pz;
- *pz++ = (digit)(carry & PyLong_MASK);
- carry >>= PyLong_SHIFT;
- }
- if (carry)
- *pz += (digit)(carry & PyLong_MASK);
- assert((carry >> PyLong_SHIFT) == 0);
- }
- }
- else { /* a is not the same as b -- gradeschool long mult */
- for (i = 0; i < size_a; ++i) {
- twodigits carry = 0;
- twodigits f = a->ob_digit[i];
- digit *pz = z->ob_digit + i;
- digit *pb = b->ob_digit;
- digit *pbend = b->ob_digit + size_b;
-
- SIGCHECK({
- Py_DECREF(z);
- return NULL;
- })
-
- while (pb < pbend) {
- carry += *pz + *pb++ * f;
- *pz++ = (digit)(carry & PyLong_MASK);
- carry >>= PyLong_SHIFT;
- assert(carry <= PyLong_MASK);
- }
- if (carry)
- *pz += (digit)(carry & PyLong_MASK);
- assert((carry >> PyLong_SHIFT) == 0);
- }
- }
- return long_normalize(z);
+ PyLongObject *z;
+ Py_ssize_t size_a = ABS(Py_SIZE(a));
+ Py_ssize_t size_b = ABS(Py_SIZE(b));
+ Py_ssize_t i;
+
+ z = _PyLong_New(size_a + size_b);
+ if (z == NULL)
+ return NULL;
+
+ memset(z->ob_digit, 0, Py_SIZE(z) * sizeof(digit));
+ if (a == b) {
+ /* Efficient squaring per HAC, Algorithm 14.16:
+ * http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf
+ * Gives slightly less than a 2x speedup when a == b,
+ * via exploiting that each entry in the multiplication
+ * pyramid appears twice (except for the size_a squares).
+ */
+ for (i = 0; i < size_a; ++i) {
+ twodigits carry;
+ twodigits f = a->ob_digit[i];
+ digit *pz = z->ob_digit + (i << 1);
+ digit *pa = a->ob_digit + i + 1;
+ digit *paend = a->ob_digit + size_a;
+
+ SIGCHECK({
+ Py_DECREF(z);
+ return NULL;
+ })
+
+ carry = *pz + f * f;
+ *pz++ = (digit)(carry & PyLong_MASK);
+ carry >>= PyLong_SHIFT;
+ assert(carry <= PyLong_MASK);
+
+ /* Now f is added in twice in each column of the
+ * pyramid it appears. Same as adding f<<1 once.
+ */
+ f <<= 1;
+ while (pa < paend) {
+ carry += *pz + *pa++ * f;
+ *pz++ = (digit)(carry & PyLong_MASK);
+ carry >>= PyLong_SHIFT;
+ assert(carry <= (PyLong_MASK << 1));
+ }
+ if (carry) {
+ carry += *pz;
+ *pz++ = (digit)(carry & PyLong_MASK);
+ carry >>= PyLong_SHIFT;
+ }
+ if (carry)
+ *pz += (digit)(carry & PyLong_MASK);
+ assert((carry >> PyLong_SHIFT) == 0);
+ }
+ }
+ else { /* a is not the same as b -- gradeschool long mult */
+ for (i = 0; i < size_a; ++i) {
+ twodigits carry = 0;
+ twodigits f = a->ob_digit[i];
+ digit *pz = z->ob_digit + i;
+ digit *pb = b->ob_digit;
+ digit *pbend = b->ob_digit + size_b;
+
+ SIGCHECK({
+ Py_DECREF(z);
+ return NULL;
+ })
+
+ while (pb < pbend) {
+ carry += *pz + *pb++ * f;
+ *pz++ = (digit)(carry & PyLong_MASK);
+ carry >>= PyLong_SHIFT;
+ assert(carry <= PyLong_MASK);
+ }
+ if (carry)
+ *pz += (digit)(carry & PyLong_MASK);
+ assert((carry >> PyLong_SHIFT) == 0);
+ }
+ }
+ return long_normalize(z);
}
/* A helper for Karatsuba multiplication (k_mul).
@@ -2647,26 +2647,26 @@ x_mul(PyLongObject *a, PyLongObject *b)
static int
kmul_split(PyLongObject *n, Py_ssize_t size, PyLongObject **high, PyLongObject **low)
{
- PyLongObject *hi, *lo;
- Py_ssize_t size_lo, size_hi;
- const Py_ssize_t size_n = ABS(Py_SIZE(n));
-
- size_lo = MIN(size_n, size);
- size_hi = size_n - size_lo;
-
- if ((hi = _PyLong_New(size_hi)) == NULL)
- return -1;
- if ((lo = _PyLong_New(size_lo)) == NULL) {
- Py_DECREF(hi);
- return -1;
- }
-
- memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
- memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
-
- *high = long_normalize(hi);
- *low = long_normalize(lo);
- return 0;
+ PyLongObject *hi, *lo;
+ Py_ssize_t size_lo, size_hi;
+ const Py_ssize_t size_n = ABS(Py_SIZE(n));
+
+ size_lo = MIN(size_n, size);
+ size_hi = size_n - size_lo;
+
+ if ((hi = _PyLong_New(size_hi)) == NULL)
+ return -1;
+ if ((lo = _PyLong_New(size_lo)) == NULL) {
+ Py_DECREF(hi);
+ return -1;
+ }
+
+ memcpy(lo->ob_digit, n->ob_digit, size_lo * sizeof(digit));
+ memcpy(hi->ob_digit, n->ob_digit + size_lo, size_hi * sizeof(digit));
+
+ *high = long_normalize(hi);
+ *low = long_normalize(lo);
+ return 0;
}
static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
@@ -2678,169 +2678,169 @@ static PyLongObject *k_lopsided_mul(PyLongObject *a, PyLongObject *b);
static PyLongObject *
k_mul(PyLongObject *a, PyLongObject *b)
{
- Py_ssize_t asize = ABS(Py_SIZE(a));
- Py_ssize_t bsize = ABS(Py_SIZE(b));
- PyLongObject *ah = NULL;
- PyLongObject *al = NULL;
- PyLongObject *bh = NULL;
- PyLongObject *bl = NULL;
- PyLongObject *ret = NULL;
- PyLongObject *t1, *t2, *t3;
- Py_ssize_t shift; /* the number of digits we split off */
- Py_ssize_t i;
-
- /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
- * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
- * Then the original product is
- * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
- * By picking X to be a power of 2, "*X" is just shifting, and it's
- * been reduced to 3 multiplies on numbers half the size.
- */
-
- /* We want to split based on the larger number; fiddle so that b
- * is largest.
- */
- if (asize > bsize) {
- t1 = a;
- a = b;
- b = t1;
-
- i = asize;
- asize = bsize;
- bsize = i;
- }
-
- /* Use gradeschool math when either number is too small. */
- i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
- if (asize <= i) {
- if (asize == 0)
- return _PyLong_New(0);
- else
- return x_mul(a, b);
- }
-
- /* If a is small compared to b, splitting on b gives a degenerate
- * case with ah==0, and Karatsuba may be (even much) less efficient
- * than "grade school" then. However, we can still win, by viewing
- * b as a string of "big digits", each of width a->ob_size. That
- * leads to a sequence of balanced calls to k_mul.
- */
- if (2 * asize <= bsize)
- return k_lopsided_mul(a, b);
-
- /* Split a & b into hi & lo pieces. */
- shift = bsize >> 1;
- if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
- assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
-
- if (a == b) {
- bh = ah;
- bl = al;
- Py_INCREF(bh);
- Py_INCREF(bl);
- }
- else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
-
- /* The plan:
- * 1. Allocate result space (asize + bsize digits: that's always
- * enough).
- * 2. Compute ah*bh, and copy into result at 2*shift.
- * 3. Compute al*bl, and copy into result at 0. Note that this
- * can't overlap with #2.
- * 4. Subtract al*bl from the result, starting at shift. This may
- * underflow (borrow out of the high digit), but we don't care:
- * we're effectively doing unsigned arithmetic mod
- * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
- * borrows and carries out of the high digit can be ignored.
- * 5. Subtract ah*bh from the result, starting at shift.
- * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
- * at shift.
- */
-
- /* 1. Allocate result space. */
- ret = _PyLong_New(asize + bsize);
- if (ret == NULL) goto fail;
+ Py_ssize_t asize = ABS(Py_SIZE(a));
+ Py_ssize_t bsize = ABS(Py_SIZE(b));
+ PyLongObject *ah = NULL;
+ PyLongObject *al = NULL;
+ PyLongObject *bh = NULL;
+ PyLongObject *bl = NULL;
+ PyLongObject *ret = NULL;
+ PyLongObject *t1, *t2, *t3;
+ Py_ssize_t shift; /* the number of digits we split off */
+ Py_ssize_t i;
+
+ /* (ah*X+al)(bh*X+bl) = ah*bh*X*X + (ah*bl + al*bh)*X + al*bl
+ * Let k = (ah+al)*(bh+bl) = ah*bl + al*bh + ah*bh + al*bl
+ * Then the original product is
+ * ah*bh*X*X + (k - ah*bh - al*bl)*X + al*bl
+ * By picking X to be a power of 2, "*X" is just shifting, and it's
+ * been reduced to 3 multiplies on numbers half the size.
+ */
+
+ /* We want to split based on the larger number; fiddle so that b
+ * is largest.
+ */
+ if (asize > bsize) {
+ t1 = a;
+ a = b;
+ b = t1;
+
+ i = asize;
+ asize = bsize;
+ bsize = i;
+ }
+
+ /* Use gradeschool math when either number is too small. */
+ i = a == b ? KARATSUBA_SQUARE_CUTOFF : KARATSUBA_CUTOFF;
+ if (asize <= i) {
+ if (asize == 0)
+ return _PyLong_New(0);
+ else
+ return x_mul(a, b);
+ }
+
+ /* If a is small compared to b, splitting on b gives a degenerate
+ * case with ah==0, and Karatsuba may be (even much) less efficient
+ * than "grade school" then. However, we can still win, by viewing
+ * b as a string of "big digits", each of width a->ob_size. That
+ * leads to a sequence of balanced calls to k_mul.
+ */
+ if (2 * asize <= bsize)
+ return k_lopsided_mul(a, b);
+
+ /* Split a & b into hi & lo pieces. */
+ shift = bsize >> 1;
+ if (kmul_split(a, shift, &ah, &al) < 0) goto fail;
+ assert(Py_SIZE(ah) > 0); /* the split isn't degenerate */
+
+ if (a == b) {
+ bh = ah;
+ bl = al;
+ Py_INCREF(bh);
+ Py_INCREF(bl);
+ }
+ else if (kmul_split(b, shift, &bh, &bl) < 0) goto fail;
+
+ /* The plan:
+ * 1. Allocate result space (asize + bsize digits: that's always
+ * enough).
+ * 2. Compute ah*bh, and copy into result at 2*shift.
+ * 3. Compute al*bl, and copy into result at 0. Note that this
+ * can't overlap with #2.
+ * 4. Subtract al*bl from the result, starting at shift. This may
+ * underflow (borrow out of the high digit), but we don't care:
+ * we're effectively doing unsigned arithmetic mod
+ * PyLong_BASE**(sizea + sizeb), and so long as the *final* result fits,
+ * borrows and carries out of the high digit can be ignored.
+ * 5. Subtract ah*bh from the result, starting at shift.
+ * 6. Compute (ah+al)*(bh+bl), and add it into the result starting
+ * at shift.
+ */
+
+ /* 1. Allocate result space. */
+ ret = _PyLong_New(asize + bsize);
+ if (ret == NULL) goto fail;
#ifdef Py_DEBUG
- /* Fill with trash, to catch reference to uninitialized digits. */
- memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
+ /* Fill with trash, to catch reference to uninitialized digits. */
+ memset(ret->ob_digit, 0xDF, Py_SIZE(ret) * sizeof(digit));
#endif
- /* 2. t1 <- ah*bh, and copy into high digits of result. */
- if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
- assert(Py_SIZE(t1) >= 0);
- assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
- memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
- Py_SIZE(t1) * sizeof(digit));
-
- /* Zero-out the digits higher than the ah*bh copy. */
- i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
- if (i)
- memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
- i * sizeof(digit));
-
- /* 3. t2 <- al*bl, and copy into the low digits. */
- if ((t2 = k_mul(al, bl)) == NULL) {
- Py_DECREF(t1);
- goto fail;
- }
- assert(Py_SIZE(t2) >= 0);
- assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
- memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
-
- /* Zero out remaining digits. */
- i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
- if (i)
- memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
-
- /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
- * because it's fresher in cache.
- */
- i = Py_SIZE(ret) - shift; /* # digits after shift */
- (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
- Py_DECREF(t2);
-
- (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
- Py_DECREF(t1);
-
- /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
- if ((t1 = x_add(ah, al)) == NULL) goto fail;
- Py_DECREF(ah);
- Py_DECREF(al);
- ah = al = NULL;
-
- if (a == b) {
- t2 = t1;
- Py_INCREF(t2);
- }
- else if ((t2 = x_add(bh, bl)) == NULL) {
- Py_DECREF(t1);
- goto fail;
- }
- Py_DECREF(bh);
- Py_DECREF(bl);
- bh = bl = NULL;
-
- t3 = k_mul(t1, t2);
- Py_DECREF(t1);
- Py_DECREF(t2);
- if (t3 == NULL) goto fail;
- assert(Py_SIZE(t3) >= 0);
-
- /* Add t3. It's not obvious why we can't run out of room here.
- * See the (*) comment after this function.
- */
- (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
- Py_DECREF(t3);
-
- return long_normalize(ret);
+ /* 2. t1 <- ah*bh, and copy into high digits of result. */
+ if ((t1 = k_mul(ah, bh)) == NULL) goto fail;
+ assert(Py_SIZE(t1) >= 0);
+ assert(2*shift + Py_SIZE(t1) <= Py_SIZE(ret));
+ memcpy(ret->ob_digit + 2*shift, t1->ob_digit,
+ Py_SIZE(t1) * sizeof(digit));
+
+ /* Zero-out the digits higher than the ah*bh copy. */
+ i = Py_SIZE(ret) - 2*shift - Py_SIZE(t1);
+ if (i)
+ memset(ret->ob_digit + 2*shift + Py_SIZE(t1), 0,
+ i * sizeof(digit));
+
+ /* 3. t2 <- al*bl, and copy into the low digits. */
+ if ((t2 = k_mul(al, bl)) == NULL) {
+ Py_DECREF(t1);
+ goto fail;
+ }
+ assert(Py_SIZE(t2) >= 0);
+ assert(Py_SIZE(t2) <= 2*shift); /* no overlap with high digits */
+ memcpy(ret->ob_digit, t2->ob_digit, Py_SIZE(t2) * sizeof(digit));
+
+ /* Zero out remaining digits. */
+ i = 2*shift - Py_SIZE(t2); /* number of uninitialized digits */
+ if (i)
+ memset(ret->ob_digit + Py_SIZE(t2), 0, i * sizeof(digit));
+
+ /* 4 & 5. Subtract ah*bh (t1) and al*bl (t2). We do al*bl first
+ * because it's fresher in cache.
+ */
+ i = Py_SIZE(ret) - shift; /* # digits after shift */
+ (void)v_isub(ret->ob_digit + shift, i, t2->ob_digit, Py_SIZE(t2));
+ Py_DECREF(t2);
+
+ (void)v_isub(ret->ob_digit + shift, i, t1->ob_digit, Py_SIZE(t1));
+ Py_DECREF(t1);
+
+ /* 6. t3 <- (ah+al)(bh+bl), and add into result. */
+ if ((t1 = x_add(ah, al)) == NULL) goto fail;
+ Py_DECREF(ah);
+ Py_DECREF(al);
+ ah = al = NULL;
+
+ if (a == b) {
+ t2 = t1;
+ Py_INCREF(t2);
+ }
+ else if ((t2 = x_add(bh, bl)) == NULL) {
+ Py_DECREF(t1);
+ goto fail;
+ }
+ Py_DECREF(bh);
+ Py_DECREF(bl);
+ bh = bl = NULL;
+
+ t3 = k_mul(t1, t2);
+ Py_DECREF(t1);
+ Py_DECREF(t2);
+ if (t3 == NULL) goto fail;
+ assert(Py_SIZE(t3) >= 0);
+
+ /* Add t3. It's not obvious why we can't run out of room here.
+ * See the (*) comment after this function.
+ */
+ (void)v_iadd(ret->ob_digit + shift, i, t3->ob_digit, Py_SIZE(t3));
+ Py_DECREF(t3);
+
+ return long_normalize(ret);
fail:
- Py_XDECREF(ret);
- Py_XDECREF(ah);
- Py_XDECREF(al);
- Py_XDECREF(bh);
- Py_XDECREF(bl);
- return NULL;
+ Py_XDECREF(ret);
+ Py_XDECREF(ah);
+ Py_XDECREF(al);
+ Py_XDECREF(bh);
+ Py_XDECREF(bl);
+ return NULL;
}
/* (*) Why adding t3 can't "run out of room" above.
@@ -2899,74 +2899,74 @@ ah*bh and al*bl too.
static PyLongObject *
k_lopsided_mul(PyLongObject *a, PyLongObject *b)
{
- const Py_ssize_t asize = ABS(Py_SIZE(a));
- Py_ssize_t bsize = ABS(Py_SIZE(b));
- Py_ssize_t nbdone; /* # of b digits already multiplied */
- PyLongObject *ret;
- PyLongObject *bslice = NULL;
-
- assert(asize > KARATSUBA_CUTOFF);
- assert(2 * asize <= bsize);
-
- /* Allocate result space, and zero it out. */
- ret = _PyLong_New(asize + bsize);
- if (ret == NULL)
- return NULL;
- memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
-
- /* Successive slices of b are copied into bslice. */
- bslice = _PyLong_New(asize);
- if (bslice == NULL)
- goto fail;
-
- nbdone = 0;
- while (bsize > 0) {
- PyLongObject *product;
- const Py_ssize_t nbtouse = MIN(bsize, asize);
-
- /* Multiply the next slice of b by a. */
- memcpy(bslice->ob_digit, b->ob_digit + nbdone,
- nbtouse * sizeof(digit));
- Py_SIZE(bslice) = nbtouse;
- product = k_mul(a, bslice);
- if (product == NULL)
- goto fail;
-
- /* Add into result. */
- (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
- product->ob_digit, Py_SIZE(product));
- Py_DECREF(product);
-
- bsize -= nbtouse;
- nbdone += nbtouse;
- }
-
- Py_DECREF(bslice);
- return long_normalize(ret);
+ const Py_ssize_t asize = ABS(Py_SIZE(a));
+ Py_ssize_t bsize = ABS(Py_SIZE(b));
+ Py_ssize_t nbdone; /* # of b digits already multiplied */
+ PyLongObject *ret;
+ PyLongObject *bslice = NULL;
+
+ assert(asize > KARATSUBA_CUTOFF);
+ assert(2 * asize <= bsize);
+
+ /* Allocate result space, and zero it out. */
+ ret = _PyLong_New(asize + bsize);
+ if (ret == NULL)
+ return NULL;
+ memset(ret->ob_digit, 0, Py_SIZE(ret) * sizeof(digit));
+
+ /* Successive slices of b are copied into bslice. */
+ bslice = _PyLong_New(asize);
+ if (bslice == NULL)
+ goto fail;
+
+ nbdone = 0;
+ while (bsize > 0) {
+ PyLongObject *product;
+ const Py_ssize_t nbtouse = MIN(bsize, asize);
+
+ /* Multiply the next slice of b by a. */
+ memcpy(bslice->ob_digit, b->ob_digit + nbdone,
+ nbtouse * sizeof(digit));
+ Py_SIZE(bslice) = nbtouse;
+ product = k_mul(a, bslice);
+ if (product == NULL)
+ goto fail;
+
+ /* Add into result. */
+ (void)v_iadd(ret->ob_digit + nbdone, Py_SIZE(ret) - nbdone,
+ product->ob_digit, Py_SIZE(product));
+ Py_DECREF(product);
+
+ bsize -= nbtouse;
+ nbdone += nbtouse;
+ }
+
+ Py_DECREF(bslice);
+ return long_normalize(ret);
fail:
- Py_DECREF(ret);
- Py_XDECREF(bslice);
- return NULL;
+ Py_DECREF(ret);
+ Py_XDECREF(bslice);
+ return NULL;
}
static PyObject *
long_mul(PyLongObject *v, PyLongObject *w)
{
- PyLongObject *a, *b, *z;
-
- if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- z = k_mul(a, b);
- /* Negate if exactly one of the inputs is negative. */
- if (((a->ob_size ^ b->ob_size) < 0) && z)
- z->ob_size = -(z->ob_size);
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)z;
+ PyLongObject *a, *b, *z;
+
+ if (!convert_binop((PyObject *)v, (PyObject *)w, &a, &b)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ z = k_mul(a, b);
+ /* Negate if exactly one of the inputs is negative. */
+ if (((a->ob_size ^ b->ob_size) < 0) && z)
+ z->ob_size = -(z->ob_size);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)z;
}
/* The / and % operators are now defined in terms of divmod().
@@ -2975,11 +2975,11 @@ long_mul(PyLongObject *v, PyLongObject *w)
|a| by |b|, with the sign of a. This is also expressed
as a - b*trunc(a/b), if trunc truncates towards zero.
Some examples:
- a b a rem b a mod b
- 13 10 3 3
- -13 10 -3 7
- 13 -10 3 -7
- -13 -10 -3 -3
+ a b a rem b a mod b
+ 13 10 3 3
+ -13 10 -3 7
+ 13 -10 3 -7
+ -13 -10 -3 -3
So, to get from rem to mod, we have to add b if a and b
have different signs. We then subtract one from the 'div'
part of the outcome to keep the invariant intact. */
@@ -2992,75 +2992,75 @@ long_mul(PyLongObject *v, PyLongObject *w)
*/
static int
l_divmod(PyLongObject *v, PyLongObject *w,
- PyLongObject **pdiv, PyLongObject **pmod)
+ PyLongObject **pdiv, PyLongObject **pmod)
{
- PyLongObject *div, *mod;
-
- if (long_divrem(v, w, &div, &mod) < 0)
- return -1;
- if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
- (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
- PyLongObject *temp;
- PyLongObject *one;
- temp = (PyLongObject *) long_add(mod, w);
- Py_DECREF(mod);
- mod = temp;
- if (mod == NULL) {
- Py_DECREF(div);
- return -1;
- }
- one = (PyLongObject *) PyLong_FromLong(1L);
- if (one == NULL ||
- (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
- Py_DECREF(mod);
- Py_DECREF(div);
- Py_XDECREF(one);
- return -1;
- }
- Py_DECREF(one);
- Py_DECREF(div);
- div = temp;
- }
- if (pdiv != NULL)
- *pdiv = div;
- else
- Py_DECREF(div);
-
- if (pmod != NULL)
- *pmod = mod;
- else
- Py_DECREF(mod);
-
- return 0;
+ PyLongObject *div, *mod;
+
+ if (long_divrem(v, w, &div, &mod) < 0)
+ return -1;
+ if ((Py_SIZE(mod) < 0 && Py_SIZE(w) > 0) ||
+ (Py_SIZE(mod) > 0 && Py_SIZE(w) < 0)) {
+ PyLongObject *temp;
+ PyLongObject *one;
+ temp = (PyLongObject *) long_add(mod, w);
+ Py_DECREF(mod);
+ mod = temp;
+ if (mod == NULL) {
+ Py_DECREF(div);
+ return -1;
+ }
+ one = (PyLongObject *) PyLong_FromLong(1L);
+ if (one == NULL ||
+ (temp = (PyLongObject *) long_sub(div, one)) == NULL) {
+ Py_DECREF(mod);
+ Py_DECREF(div);
+ Py_XDECREF(one);
+ return -1;
+ }
+ Py_DECREF(one);
+ Py_DECREF(div);
+ div = temp;
+ }
+ if (pdiv != NULL)
+ *pdiv = div;
+ else
+ Py_DECREF(div);
+
+ if (pmod != NULL)
+ *pmod = mod;
+ else
+ Py_DECREF(mod);
+
+ return 0;
}
static PyObject *
long_div(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b, *div;
-
- CONVERT_BINOP(v, w, &a, &b);
- if (l_divmod(a, b, &div, NULL) < 0)
- div = NULL;
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)div;
+ PyLongObject *a, *b, *div;
+
+ CONVERT_BINOP(v, w, &a, &b);
+ if (l_divmod(a, b, &div, NULL) < 0)
+ div = NULL;
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)div;
}
static PyObject *
long_classic_div(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b, *div;
-
- CONVERT_BINOP(v, w, &a, &b);
- if (Py_DivisionWarningFlag &&
- PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
- div = NULL;
- else if (l_divmod(a, b, &div, NULL) < 0)
- div = NULL;
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)div;
+ PyLongObject *a, *b, *div;
+
+ CONVERT_BINOP(v, w, &a, &b);
+ if (Py_DivisionWarningFlag &&
+ PyErr_Warn(PyExc_DeprecationWarning, "classic long division") < 0)
+ div = NULL;
+ else if (l_divmod(a, b, &div, NULL) < 0)
+ div = NULL;
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)div;
}
/* PyLong/PyLong -> float, with correctly rounded result. */
@@ -3071,653 +3071,653 @@ long_classic_div(PyObject *v, PyObject *w)
static PyObject *
long_true_divide(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b, *x;
- Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
- digit mask, low;
- int inexact, negate, a_is_small, b_is_small;
- double dx, result;
-
- CONVERT_BINOP(v, w, &a, &b);
-
- /*
- Method in a nutshell:
-
- 0. reduce to case a, b > 0; filter out obvious underflow/overflow
- 1. choose a suitable integer 'shift'
- 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
- 3. adjust x for correct rounding
- 4. convert x to a double dx with the same value
- 5. return ldexp(dx, shift).
-
- In more detail:
-
- 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
- returns either 0.0 or -0.0, depending on the sign of b. For a and
- b both nonzero, ignore signs of a and b, and add the sign back in
- at the end. Now write a_bits and b_bits for the bit lengths of a
- and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
- for b). Then
-
- 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
-
- So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
- so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
- DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
- the way, we can assume that
-
- DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
-
- 1. The integer 'shift' is chosen so that x has the right number of
- bits for a double, plus two or three extra bits that will be used
- in the rounding decisions. Writing a_bits and b_bits for the
- number of significant bits in a and b respectively, a
- straightforward formula for shift is:
-
- shift = a_bits - b_bits - DBL_MANT_DIG - 2
-
- This is fine in the usual case, but if a/b is smaller than the
- smallest normal float then it can lead to double rounding on an
- IEEE 754 platform, giving incorrectly rounded results. So we
- adjust the formula slightly. The actual formula used is:
-
- shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
-
- 2. The quantity x is computed by first shifting a (left -shift bits
- if shift <= 0, right shift bits if shift > 0) and then dividing by
- b. For both the shift and the division, we keep track of whether
- the result is inexact, in a flag 'inexact'; this information is
- needed at the rounding stage.
-
- With the choice of shift above, together with our assumption that
- a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
- that x >= 1.
-
- 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
- this with an exactly representable float of the form
-
- round(x/2**extra_bits) * 2**(extra_bits+shift).
-
- For float representability, we need x/2**extra_bits <
- 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
- DBL_MANT_DIG. This translates to the condition:
-
- extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
-
- To round, we just modify the bottom digit of x in-place; this can
- end up giving a digit with value > PyLONG_MASK, but that's not a
- problem since digits can hold values up to 2*PyLONG_MASK+1.
-
- With the original choices for shift above, extra_bits will always
- be 2 or 3. Then rounding under the round-half-to-even rule, we
- round up iff the most significant of the extra bits is 1, and
- either: (a) the computation of x in step 2 had an inexact result,
- or (b) at least one other of the extra bits is 1, or (c) the least
- significant bit of x (above those to be rounded) is 1.
-
- 4. Conversion to a double is straightforward; all floating-point
- operations involved in the conversion are exact, so there's no
- danger of rounding errors.
-
- 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
- The result will always be exactly representable as a double, except
- in the case that it overflows. To avoid dependence on the exact
- behaviour of ldexp on overflow, we check for overflow before
- applying ldexp. The result of ldexp is adjusted for sign before
- returning.
- */
-
- /* Reduce to case where a and b are both positive. */
- a_size = ABS(Py_SIZE(a));
- b_size = ABS(Py_SIZE(b));
- negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
- if (b_size == 0) {
- PyErr_SetString(PyExc_ZeroDivisionError,
- "division by zero");
- goto error;
- }
- if (a_size == 0)
- goto underflow_or_zero;
-
- /* Fast path for a and b small (exactly representable in a double).
- Relies on floating-point division being correctly rounded; results
- may be subject to double rounding on x86 machines that operate with
- the x87 FPU set to 64-bit precision. */
- a_is_small = a_size <= MANT_DIG_DIGITS ||
- (a_size == MANT_DIG_DIGITS+1 &&
- a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
- b_is_small = b_size <= MANT_DIG_DIGITS ||
- (b_size == MANT_DIG_DIGITS+1 &&
- b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
- if (a_is_small && b_is_small) {
- double da, db;
- da = a->ob_digit[--a_size];
- while (a_size > 0)
- da = da * PyLong_BASE + a->ob_digit[--a_size];
- db = b->ob_digit[--b_size];
- while (b_size > 0)
- db = db * PyLong_BASE + b->ob_digit[--b_size];
- result = da / db;
- goto success;
- }
-
- /* Catch obvious cases of underflow and overflow */
- diff = a_size - b_size;
- if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
- /* Extreme overflow */
- goto overflow;
- else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
- /* Extreme underflow */
- goto underflow_or_zero;
- /* Next line is now safe from overflowing a Py_ssize_t */
- diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
- bits_in_digit(b->ob_digit[b_size - 1]);
- /* Now diff = a_bits - b_bits. */
- if (diff > DBL_MAX_EXP)
- goto overflow;
- else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
- goto underflow_or_zero;
-
- /* Choose value for shift; see comments for step 1 above. */
- shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
-
- inexact = 0;
-
- /* x = abs(a * 2**-shift) */
- if (shift <= 0) {
- Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
- digit rem;
- /* x = a << -shift */
- if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
- /* In practice, it's probably impossible to end up
- here. Both a and b would have to be enormous,
- using close to SIZE_T_MAX bytes of memory each. */
- PyErr_SetString(PyExc_OverflowError,
- "intermediate overflow during division");
- goto error;
- }
- x = _PyLong_New(a_size + shift_digits + 1);
- if (x == NULL)
- goto error;
- for (i = 0; i < shift_digits; i++)
- x->ob_digit[i] = 0;
- rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
- a_size, -shift % PyLong_SHIFT);
- x->ob_digit[a_size + shift_digits] = rem;
- }
- else {
- Py_ssize_t shift_digits = shift / PyLong_SHIFT;
- digit rem;
- /* x = a >> shift */
- assert(a_size >= shift_digits);
- x = _PyLong_New(a_size - shift_digits);
- if (x == NULL)
- goto error;
- rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
- a_size - shift_digits, shift % PyLong_SHIFT);
- /* set inexact if any of the bits shifted out is nonzero */
- if (rem)
- inexact = 1;
- while (!inexact && shift_digits > 0)
- if (a->ob_digit[--shift_digits])
- inexact = 1;
- }
- long_normalize(x);
- x_size = Py_SIZE(x);
-
- /* x //= b. If the remainder is nonzero, set inexact. We own the only
- reference to x, so it's safe to modify it in-place. */
- if (b_size == 1) {
- digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
- b->ob_digit[0]);
- long_normalize(x);
- if (rem)
- inexact = 1;
- }
- else {
- PyLongObject *div, *rem;
- div = x_divrem(x, b, &rem);
- Py_DECREF(x);
- x = div;
- if (x == NULL)
- goto error;
- if (Py_SIZE(rem))
- inexact = 1;
- Py_DECREF(rem);
- }
- x_size = ABS(Py_SIZE(x));
- assert(x_size > 0); /* result of division is never zero */
- x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
-
- /* The number of extra bits that have to be rounded away. */
- extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
- assert(extra_bits == 2 || extra_bits == 3);
-
- /* Round by directly modifying the low digit of x. */
- mask = (digit)1 << (extra_bits - 1);
- low = x->ob_digit[0] | inexact;
- if (low & mask && low & (3*mask-1))
- low += mask;
- x->ob_digit[0] = low & ~(mask-1U);
-
- /* Convert x to a double dx; the conversion is exact. */
- dx = x->ob_digit[--x_size];
- while (x_size > 0)
- dx = dx * PyLong_BASE + x->ob_digit[--x_size];
- Py_DECREF(x);
-
- /* Check whether ldexp result will overflow a double. */
- if (shift + x_bits >= DBL_MAX_EXP &&
- (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
- goto overflow;
- result = ldexp(dx, (int)shift);
+ PyLongObject *a, *b, *x;
+ Py_ssize_t a_size, b_size, shift, extra_bits, diff, x_size, x_bits;
+ digit mask, low;
+ int inexact, negate, a_is_small, b_is_small;
+ double dx, result;
+
+ CONVERT_BINOP(v, w, &a, &b);
+
+ /*
+ Method in a nutshell:
+
+ 0. reduce to case a, b > 0; filter out obvious underflow/overflow
+ 1. choose a suitable integer 'shift'
+ 2. use integer arithmetic to compute x = floor(2**-shift*a/b)
+ 3. adjust x for correct rounding
+ 4. convert x to a double dx with the same value
+ 5. return ldexp(dx, shift).
+
+ In more detail:
+
+ 0. For any a, a/0 raises ZeroDivisionError; for nonzero b, 0/b
+ returns either 0.0 or -0.0, depending on the sign of b. For a and
+ b both nonzero, ignore signs of a and b, and add the sign back in
+ at the end. Now write a_bits and b_bits for the bit lengths of a
+ and b respectively (that is, a_bits = 1 + floor(log_2(a)); likewise
+ for b). Then
+
+ 2**(a_bits - b_bits - 1) < a/b < 2**(a_bits - b_bits + 1).
+
+ So if a_bits - b_bits > DBL_MAX_EXP then a/b > 2**DBL_MAX_EXP and
+ so overflows. Similarly, if a_bits - b_bits < DBL_MIN_EXP -
+ DBL_MANT_DIG - 1 then a/b underflows to 0. With these cases out of
+ the way, we can assume that
+
+ DBL_MIN_EXP - DBL_MANT_DIG - 1 <= a_bits - b_bits <= DBL_MAX_EXP.
+
+ 1. The integer 'shift' is chosen so that x has the right number of
+ bits for a double, plus two or three extra bits that will be used
+ in the rounding decisions. Writing a_bits and b_bits for the
+ number of significant bits in a and b respectively, a
+ straightforward formula for shift is:
+
+ shift = a_bits - b_bits - DBL_MANT_DIG - 2
+
+ This is fine in the usual case, but if a/b is smaller than the
+ smallest normal float then it can lead to double rounding on an
+ IEEE 754 platform, giving incorrectly rounded results. So we
+ adjust the formula slightly. The actual formula used is:
+
+ shift = MAX(a_bits - b_bits, DBL_MIN_EXP) - DBL_MANT_DIG - 2
+
+ 2. The quantity x is computed by first shifting a (left -shift bits
+ if shift <= 0, right shift bits if shift > 0) and then dividing by
+ b. For both the shift and the division, we keep track of whether
+ the result is inexact, in a flag 'inexact'; this information is
+ needed at the rounding stage.
+
+ With the choice of shift above, together with our assumption that
+ a_bits - b_bits >= DBL_MIN_EXP - DBL_MANT_DIG - 1, it follows
+ that x >= 1.
+
+ 3. Now x * 2**shift <= a/b < (x+1) * 2**shift. We want to replace
+ this with an exactly representable float of the form
+
+ round(x/2**extra_bits) * 2**(extra_bits+shift).
+
+ For float representability, we need x/2**extra_bits <
+ 2**DBL_MANT_DIG and extra_bits + shift >= DBL_MIN_EXP -
+ DBL_MANT_DIG. This translates to the condition:
+
+ extra_bits >= MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG
+
+ To round, we just modify the bottom digit of x in-place; this can
+ end up giving a digit with value > PyLONG_MASK, but that's not a
+ problem since digits can hold values up to 2*PyLONG_MASK+1.
+
+ With the original choices for shift above, extra_bits will always
+ be 2 or 3. Then rounding under the round-half-to-even rule, we
+ round up iff the most significant of the extra bits is 1, and
+ either: (a) the computation of x in step 2 had an inexact result,
+ or (b) at least one other of the extra bits is 1, or (c) the least
+ significant bit of x (above those to be rounded) is 1.
+
+ 4. Conversion to a double is straightforward; all floating-point
+ operations involved in the conversion are exact, so there's no
+ danger of rounding errors.
+
+ 5. Use ldexp(x, shift) to compute x*2**shift, the final result.
+ The result will always be exactly representable as a double, except
+ in the case that it overflows. To avoid dependence on the exact
+ behaviour of ldexp on overflow, we check for overflow before
+ applying ldexp. The result of ldexp is adjusted for sign before
+ returning.
+ */
+
+ /* Reduce to case where a and b are both positive. */
+ a_size = ABS(Py_SIZE(a));
+ b_size = ABS(Py_SIZE(b));
+ negate = (Py_SIZE(a) < 0) ^ (Py_SIZE(b) < 0);
+ if (b_size == 0) {
+ PyErr_SetString(PyExc_ZeroDivisionError,
+ "division by zero");
+ goto error;
+ }
+ if (a_size == 0)
+ goto underflow_or_zero;
+
+ /* Fast path for a and b small (exactly representable in a double).
+ Relies on floating-point division being correctly rounded; results
+ may be subject to double rounding on x86 machines that operate with
+ the x87 FPU set to 64-bit precision. */
+ a_is_small = a_size <= MANT_DIG_DIGITS ||
+ (a_size == MANT_DIG_DIGITS+1 &&
+ a->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
+ b_is_small = b_size <= MANT_DIG_DIGITS ||
+ (b_size == MANT_DIG_DIGITS+1 &&
+ b->ob_digit[MANT_DIG_DIGITS] >> MANT_DIG_BITS == 0);
+ if (a_is_small && b_is_small) {
+ double da, db;
+ da = a->ob_digit[--a_size];
+ while (a_size > 0)
+ da = da * PyLong_BASE + a->ob_digit[--a_size];
+ db = b->ob_digit[--b_size];
+ while (b_size > 0)
+ db = db * PyLong_BASE + b->ob_digit[--b_size];
+ result = da / db;
+ goto success;
+ }
+
+ /* Catch obvious cases of underflow and overflow */
+ diff = a_size - b_size;
+ if (diff > PY_SSIZE_T_MAX/PyLong_SHIFT - 1)
+ /* Extreme overflow */
+ goto overflow;
+ else if (diff < 1 - PY_SSIZE_T_MAX/PyLong_SHIFT)
+ /* Extreme underflow */
+ goto underflow_or_zero;
+ /* Next line is now safe from overflowing a Py_ssize_t */
+ diff = diff * PyLong_SHIFT + bits_in_digit(a->ob_digit[a_size - 1]) -
+ bits_in_digit(b->ob_digit[b_size - 1]);
+ /* Now diff = a_bits - b_bits. */
+ if (diff > DBL_MAX_EXP)
+ goto overflow;
+ else if (diff < DBL_MIN_EXP - DBL_MANT_DIG - 1)
+ goto underflow_or_zero;
+
+ /* Choose value for shift; see comments for step 1 above. */
+ shift = MAX(diff, DBL_MIN_EXP) - DBL_MANT_DIG - 2;
+
+ inexact = 0;
+
+ /* x = abs(a * 2**-shift) */
+ if (shift <= 0) {
+ Py_ssize_t i, shift_digits = -shift / PyLong_SHIFT;
+ digit rem;
+ /* x = a << -shift */
+ if (a_size >= PY_SSIZE_T_MAX - 1 - shift_digits) {
+ /* In practice, it's probably impossible to end up
+ here. Both a and b would have to be enormous,
+ using close to SIZE_T_MAX bytes of memory each. */
+ PyErr_SetString(PyExc_OverflowError,
+ "intermediate overflow during division");
+ goto error;
+ }
+ x = _PyLong_New(a_size + shift_digits + 1);
+ if (x == NULL)
+ goto error;
+ for (i = 0; i < shift_digits; i++)
+ x->ob_digit[i] = 0;
+ rem = v_lshift(x->ob_digit + shift_digits, a->ob_digit,
+ a_size, -shift % PyLong_SHIFT);
+ x->ob_digit[a_size + shift_digits] = rem;
+ }
+ else {
+ Py_ssize_t shift_digits = shift / PyLong_SHIFT;
+ digit rem;
+ /* x = a >> shift */
+ assert(a_size >= shift_digits);
+ x = _PyLong_New(a_size - shift_digits);
+ if (x == NULL)
+ goto error;
+ rem = v_rshift(x->ob_digit, a->ob_digit + shift_digits,
+ a_size - shift_digits, shift % PyLong_SHIFT);
+ /* set inexact if any of the bits shifted out is nonzero */
+ if (rem)
+ inexact = 1;
+ while (!inexact && shift_digits > 0)
+ if (a->ob_digit[--shift_digits])
+ inexact = 1;
+ }
+ long_normalize(x);
+ x_size = Py_SIZE(x);
+
+ /* x //= b. If the remainder is nonzero, set inexact. We own the only
+ reference to x, so it's safe to modify it in-place. */
+ if (b_size == 1) {
+ digit rem = inplace_divrem1(x->ob_digit, x->ob_digit, x_size,
+ b->ob_digit[0]);
+ long_normalize(x);
+ if (rem)
+ inexact = 1;
+ }
+ else {
+ PyLongObject *div, *rem;
+ div = x_divrem(x, b, &rem);
+ Py_DECREF(x);
+ x = div;
+ if (x == NULL)
+ goto error;
+ if (Py_SIZE(rem))
+ inexact = 1;
+ Py_DECREF(rem);
+ }
+ x_size = ABS(Py_SIZE(x));
+ assert(x_size > 0); /* result of division is never zero */
+ x_bits = (x_size-1)*PyLong_SHIFT+bits_in_digit(x->ob_digit[x_size-1]);
+
+ /* The number of extra bits that have to be rounded away. */
+ extra_bits = MAX(x_bits, DBL_MIN_EXP - shift) - DBL_MANT_DIG;
+ assert(extra_bits == 2 || extra_bits == 3);
+
+ /* Round by directly modifying the low digit of x. */
+ mask = (digit)1 << (extra_bits - 1);
+ low = x->ob_digit[0] | inexact;
+ if (low & mask && low & (3*mask-1))
+ low += mask;
+ x->ob_digit[0] = low & ~(mask-1U);
+
+ /* Convert x to a double dx; the conversion is exact. */
+ dx = x->ob_digit[--x_size];
+ while (x_size > 0)
+ dx = dx * PyLong_BASE + x->ob_digit[--x_size];
+ Py_DECREF(x);
+
+ /* Check whether ldexp result will overflow a double. */
+ if (shift + x_bits >= DBL_MAX_EXP &&
+ (shift + x_bits > DBL_MAX_EXP || dx == ldexp(1.0, (int)x_bits)))
+ goto overflow;
+ result = ldexp(dx, (int)shift);
success:
- Py_DECREF(a);
- Py_DECREF(b);
- return PyFloat_FromDouble(negate ? -result : result);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return PyFloat_FromDouble(negate ? -result : result);
underflow_or_zero:
- Py_DECREF(a);
- Py_DECREF(b);
- return PyFloat_FromDouble(negate ? -0.0 : 0.0);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return PyFloat_FromDouble(negate ? -0.0 : 0.0);
overflow:
- PyErr_SetString(PyExc_OverflowError,
- "integer division result too large for a float");
+ PyErr_SetString(PyExc_OverflowError,
+ "integer division result too large for a float");
error:
- Py_DECREF(a);
- Py_DECREF(b);
- return NULL;
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
}
static PyObject *
long_mod(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b, *mod;
+ PyLongObject *a, *b, *mod;
- CONVERT_BINOP(v, w, &a, &b);
+ CONVERT_BINOP(v, w, &a, &b);
- if (l_divmod(a, b, NULL, &mod) < 0)
- mod = NULL;
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)mod;
+ if (l_divmod(a, b, NULL, &mod) < 0)
+ mod = NULL;
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)mod;
}
static PyObject *
long_divmod(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b, *div, *mod;
- PyObject *z;
-
- CONVERT_BINOP(v, w, &a, &b);
-
- if (l_divmod(a, b, &div, &mod) < 0) {
- Py_DECREF(a);
- Py_DECREF(b);
- return NULL;
- }
- z = PyTuple_New(2);
- if (z != NULL) {
- PyTuple_SetItem(z, 0, (PyObject *) div);
- PyTuple_SetItem(z, 1, (PyObject *) mod);
- }
- else {
- Py_DECREF(div);
- Py_DECREF(mod);
- }
- Py_DECREF(a);
- Py_DECREF(b);
- return z;
+ PyLongObject *a, *b, *div, *mod;
+ PyObject *z;
+
+ CONVERT_BINOP(v, w, &a, &b);
+
+ if (l_divmod(a, b, &div, &mod) < 0) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+ z = PyTuple_New(2);
+ if (z != NULL) {
+ PyTuple_SetItem(z, 0, (PyObject *) div);
+ PyTuple_SetItem(z, 1, (PyObject *) mod);
+ }
+ else {
+ Py_DECREF(div);
+ Py_DECREF(mod);
+ }
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return z;
}
/* pow(v, w, x) */
static PyObject *
long_pow(PyObject *v, PyObject *w, PyObject *x)
{
- PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
- int negativeOutput = 0; /* if x<0 return negative output */
-
- PyLongObject *z = NULL; /* accumulated result */
- Py_ssize_t i, j, k; /* counters */
- PyLongObject *temp = NULL;
-
- /* 5-ary values. If the exponent is large enough, table is
- * precomputed so that table[i] == a**i % c for i in range(32).
- */
- PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
-
- /* a, b, c = v, w, x */
- CONVERT_BINOP(v, w, &a, &b);
- if (PyLong_Check(x)) {
- c = (PyLongObject *)x;
- Py_INCREF(x);
- }
- else if (PyInt_Check(x)) {
- c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
- if (c == NULL)
- goto Error;
- }
- else if (x == Py_None)
- c = NULL;
- else {
- Py_DECREF(a);
- Py_DECREF(b);
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- if (Py_SIZE(b) < 0) { /* if exponent is negative */
- if (c) {
- PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
- "cannot be negative when 3rd argument specified");
- goto Error;
- }
- else {
- /* else return a float. This works because we know
- that this calls float_pow() which converts its
- arguments to double. */
- Py_DECREF(a);
- Py_DECREF(b);
- return PyFloat_Type.tp_as_number->nb_power(v, w, x);
- }
- }
-
- if (c) {
- /* if modulus == 0:
- raise ValueError() */
- if (Py_SIZE(c) == 0) {
- PyErr_SetString(PyExc_ValueError,
- "pow() 3rd argument cannot be 0");
- goto Error;
- }
-
- /* if modulus < 0:
- negativeOutput = True
- modulus = -modulus */
- if (Py_SIZE(c) < 0) {
- negativeOutput = 1;
- temp = (PyLongObject *)_PyLong_Copy(c);
- if (temp == NULL)
- goto Error;
- Py_DECREF(c);
- c = temp;
- temp = NULL;
- c->ob_size = - c->ob_size;
- }
-
- /* if modulus == 1:
- return 0 */
- if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
- z = (PyLongObject *)PyLong_FromLong(0L);
- goto Done;
- }
-
- /* if base < 0:
- base = base % modulus
- Having the base positive just makes things easier. */
- if (Py_SIZE(a) < 0) {
- if (l_divmod(a, c, NULL, &temp) < 0)
- goto Error;
- Py_DECREF(a);
- a = temp;
- temp = NULL;
- }
- }
-
- /* At this point a, b, and c are guaranteed non-negative UNLESS
- c is NULL, in which case a may be negative. */
-
- z = (PyLongObject *)PyLong_FromLong(1L);
- if (z == NULL)
- goto Error;
-
- /* Perform a modular reduction, X = X % c, but leave X alone if c
- * is NULL.
- */
-#define REDUCE(X) \
- if (c != NULL) { \
- if (l_divmod(X, c, NULL, &temp) < 0) \
- goto Error; \
- Py_XDECREF(X); \
- X = temp; \
- temp = NULL; \
- }
-
- /* Multiply two values, then reduce the result:
- result = X*Y % c. If c is NULL, skip the mod. */
-#define MULT(X, Y, result) \
-{ \
- temp = (PyLongObject *)long_mul(X, Y); \
- if (temp == NULL) \
- goto Error; \
- Py_XDECREF(result); \
- result = temp; \
- temp = NULL; \
- REDUCE(result) \
+ PyLongObject *a, *b, *c; /* a,b,c = v,w,x */
+ int negativeOutput = 0; /* if x<0 return negative output */
+
+ PyLongObject *z = NULL; /* accumulated result */
+ Py_ssize_t i, j, k; /* counters */
+ PyLongObject *temp = NULL;
+
+ /* 5-ary values. If the exponent is large enough, table is
+ * precomputed so that table[i] == a**i % c for i in range(32).
+ */
+ PyLongObject *table[32] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
+ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
+
+ /* a, b, c = v, w, x */
+ CONVERT_BINOP(v, w, &a, &b);
+ if (PyLong_Check(x)) {
+ c = (PyLongObject *)x;
+ Py_INCREF(x);
+ }
+ else if (PyInt_Check(x)) {
+ c = (PyLongObject *)PyLong_FromLong(PyInt_AS_LONG(x));
+ if (c == NULL)
+ goto Error;
+ }
+ else if (x == Py_None)
+ c = NULL;
+ else {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ if (Py_SIZE(b) < 0) { /* if exponent is negative */
+ if (c) {
+ PyErr_SetString(PyExc_TypeError, "pow() 2nd argument "
+ "cannot be negative when 3rd argument specified");
+ goto Error;
+ }
+ else {
+ /* else return a float. This works because we know
+ that this calls float_pow() which converts its
+ arguments to double. */
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return PyFloat_Type.tp_as_number->nb_power(v, w, x);
+ }
+ }
+
+ if (c) {
+ /* if modulus == 0:
+ raise ValueError() */
+ if (Py_SIZE(c) == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "pow() 3rd argument cannot be 0");
+ goto Error;
+ }
+
+ /* if modulus < 0:
+ negativeOutput = True
+ modulus = -modulus */
+ if (Py_SIZE(c) < 0) {
+ negativeOutput = 1;
+ temp = (PyLongObject *)_PyLong_Copy(c);
+ if (temp == NULL)
+ goto Error;
+ Py_DECREF(c);
+ c = temp;
+ temp = NULL;
+ c->ob_size = - c->ob_size;
+ }
+
+ /* if modulus == 1:
+ return 0 */
+ if ((Py_SIZE(c) == 1) && (c->ob_digit[0] == 1)) {
+ z = (PyLongObject *)PyLong_FromLong(0L);
+ goto Done;
+ }
+
+ /* if base < 0:
+ base = base % modulus
+ Having the base positive just makes things easier. */
+ if (Py_SIZE(a) < 0) {
+ if (l_divmod(a, c, NULL, &temp) < 0)
+ goto Error;
+ Py_DECREF(a);
+ a = temp;
+ temp = NULL;
+ }
+ }
+
+ /* At this point a, b, and c are guaranteed non-negative UNLESS
+ c is NULL, in which case a may be negative. */
+
+ z = (PyLongObject *)PyLong_FromLong(1L);
+ if (z == NULL)
+ goto Error;
+
+ /* Perform a modular reduction, X = X % c, but leave X alone if c
+ * is NULL.
+ */
+#define REDUCE(X) \
+ if (c != NULL) { \
+ if (l_divmod(X, c, NULL, &temp) < 0) \
+ goto Error; \
+ Py_XDECREF(X); \
+ X = temp; \
+ temp = NULL; \
+ }
+
+ /* Multiply two values, then reduce the result:
+ result = X*Y % c. If c is NULL, skip the mod. */
+#define MULT(X, Y, result) \
+{ \
+ temp = (PyLongObject *)long_mul(X, Y); \
+ if (temp == NULL) \
+ goto Error; \
+ Py_XDECREF(result); \
+ result = temp; \
+ temp = NULL; \
+ REDUCE(result) \
}
- if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
- /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
- /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
- for (i = Py_SIZE(b) - 1; i >= 0; --i) {
- digit bi = b->ob_digit[i];
-
- for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
- MULT(z, z, z)
- if (bi & j)
- MULT(z, a, z)
- }
- }
- }
- else {
- /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
- Py_INCREF(z); /* still holds 1L */
- table[0] = z;
- for (i = 1; i < 32; ++i)
- MULT(table[i-1], a, table[i])
-
- for (i = Py_SIZE(b) - 1; i >= 0; --i) {
- const digit bi = b->ob_digit[i];
-
- for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
- const int index = (bi >> j) & 0x1f;
- for (k = 0; k < 5; ++k)
- MULT(z, z, z)
- if (index)
- MULT(z, table[index], z)
- }
- }
- }
-
- if (negativeOutput && (Py_SIZE(z) != 0)) {
- temp = (PyLongObject *)long_sub(z, c);
- if (temp == NULL)
- goto Error;
- Py_DECREF(z);
- z = temp;
- temp = NULL;
- }
- goto Done;
+ if (Py_SIZE(b) <= FIVEARY_CUTOFF) {
+ /* Left-to-right binary exponentiation (HAC Algorithm 14.79) */
+ /* http://www.cacr.math.uwaterloo.ca/hac/about/chap14.pdf */
+ for (i = Py_SIZE(b) - 1; i >= 0; --i) {
+ digit bi = b->ob_digit[i];
+
+ for (j = (digit)1 << (PyLong_SHIFT-1); j != 0; j >>= 1) {
+ MULT(z, z, z)
+ if (bi & j)
+ MULT(z, a, z)
+ }
+ }
+ }
+ else {
+ /* Left-to-right 5-ary exponentiation (HAC Algorithm 14.82) */
+ Py_INCREF(z); /* still holds 1L */
+ table[0] = z;
+ for (i = 1; i < 32; ++i)
+ MULT(table[i-1], a, table[i])
+
+ for (i = Py_SIZE(b) - 1; i >= 0; --i) {
+ const digit bi = b->ob_digit[i];
+
+ for (j = PyLong_SHIFT - 5; j >= 0; j -= 5) {
+ const int index = (bi >> j) & 0x1f;
+ for (k = 0; k < 5; ++k)
+ MULT(z, z, z)
+ if (index)
+ MULT(z, table[index], z)
+ }
+ }
+ }
+
+ if (negativeOutput && (Py_SIZE(z) != 0)) {
+ temp = (PyLongObject *)long_sub(z, c);
+ if (temp == NULL)
+ goto Error;
+ Py_DECREF(z);
+ z = temp;
+ temp = NULL;
+ }
+ goto Done;
Error:
- if (z != NULL) {
- Py_DECREF(z);
- z = NULL;
- }
- /* fall through */
+ if (z != NULL) {
+ Py_DECREF(z);
+ z = NULL;
+ }
+ /* fall through */
Done:
- if (Py_SIZE(b) > FIVEARY_CUTOFF) {
- for (i = 0; i < 32; ++i)
- Py_XDECREF(table[i]);
- }
- Py_DECREF(a);
- Py_DECREF(b);
- Py_XDECREF(c);
- Py_XDECREF(temp);
- return (PyObject *)z;
+ if (Py_SIZE(b) > FIVEARY_CUTOFF) {
+ for (i = 0; i < 32; ++i)
+ Py_XDECREF(table[i]);
+ }
+ Py_DECREF(a);
+ Py_DECREF(b);
+ Py_XDECREF(c);
+ Py_XDECREF(temp);
+ return (PyObject *)z;
}
static PyObject *
long_invert(PyLongObject *v)
{
- /* Implement ~x as -(x+1) */
- PyLongObject *x;
- PyLongObject *w;
- w = (PyLongObject *)PyLong_FromLong(1L);
- if (w == NULL)
- return NULL;
- x = (PyLongObject *) long_add(v, w);
- Py_DECREF(w);
- if (x == NULL)
- return NULL;
- Py_SIZE(x) = -(Py_SIZE(x));
- return (PyObject *)x;
+ /* Implement ~x as -(x+1) */
+ PyLongObject *x;
+ PyLongObject *w;
+ w = (PyLongObject *)PyLong_FromLong(1L);
+ if (w == NULL)
+ return NULL;
+ x = (PyLongObject *) long_add(v, w);
+ Py_DECREF(w);
+ if (x == NULL)
+ return NULL;
+ Py_SIZE(x) = -(Py_SIZE(x));
+ return (PyObject *)x;
}
static PyObject *
long_neg(PyLongObject *v)
{
- PyLongObject *z;
- if (v->ob_size == 0 && PyLong_CheckExact(v)) {
- /* -0 == 0 */
- Py_INCREF(v);
- return (PyObject *) v;
- }
- z = (PyLongObject *)_PyLong_Copy(v);
- if (z != NULL)
- z->ob_size = -(v->ob_size);
- return (PyObject *)z;
+ PyLongObject *z;
+ if (v->ob_size == 0 && PyLong_CheckExact(v)) {
+ /* -0 == 0 */
+ Py_INCREF(v);
+ return (PyObject *) v;
+ }
+ z = (PyLongObject *)_PyLong_Copy(v);
+ if (z != NULL)
+ z->ob_size = -(v->ob_size);
+ return (PyObject *)z;
}
static PyObject *
long_abs(PyLongObject *v)
{
- if (v->ob_size < 0)
- return long_neg(v);
- else
- return long_long((PyObject *)v);
+ if (v->ob_size < 0)
+ return long_neg(v);
+ else
+ return long_long((PyObject *)v);
}
static int
long_nonzero(PyLongObject *v)
{
- return Py_SIZE(v) != 0;
+ return Py_SIZE(v) != 0;
}
static PyObject *
long_rshift(PyLongObject *v, PyLongObject *w)
{
- PyLongObject *a, *b;
- PyLongObject *z = NULL;
- Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
- digit lomask, himask;
-
- CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
-
- if (Py_SIZE(a) < 0) {
- /* Right shifting negative numbers is harder */
- PyLongObject *a1, *a2;
- a1 = (PyLongObject *) long_invert(a);
- if (a1 == NULL)
- goto rshift_error;
- a2 = (PyLongObject *) long_rshift(a1, b);
- Py_DECREF(a1);
- if (a2 == NULL)
- goto rshift_error;
- z = (PyLongObject *) long_invert(a2);
- Py_DECREF(a2);
- }
- else {
- shiftby = PyLong_AsSsize_t((PyObject *)b);
- if (shiftby == -1L && PyErr_Occurred())
- goto rshift_error;
- if (shiftby < 0) {
- PyErr_SetString(PyExc_ValueError,
- "negative shift count");
- goto rshift_error;
- }
- wordshift = shiftby / PyLong_SHIFT;
- newsize = ABS(Py_SIZE(a)) - wordshift;
- if (newsize <= 0) {
- z = _PyLong_New(0);
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)z;
- }
- loshift = shiftby % PyLong_SHIFT;
- hishift = PyLong_SHIFT - loshift;
- lomask = ((digit)1 << hishift) - 1;
- himask = PyLong_MASK ^ lomask;
- z = _PyLong_New(newsize);
- if (z == NULL)
- goto rshift_error;
- if (Py_SIZE(a) < 0)
- Py_SIZE(z) = -(Py_SIZE(z));
- for (i = 0, j = wordshift; i < newsize; i++, j++) {
- z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
- if (i+1 < newsize)
- z->ob_digit[i] |=
- (a->ob_digit[j+1] << hishift) & himask;
- }
- z = long_normalize(z);
- }
+ PyLongObject *a, *b;
+ PyLongObject *z = NULL;
+ Py_ssize_t shiftby, newsize, wordshift, loshift, hishift, i, j;
+ digit lomask, himask;
+
+ CONVERT_BINOP((PyObject *)v, (PyObject *)w, &a, &b);
+
+ if (Py_SIZE(a) < 0) {
+ /* Right shifting negative numbers is harder */
+ PyLongObject *a1, *a2;
+ a1 = (PyLongObject *) long_invert(a);
+ if (a1 == NULL)
+ goto rshift_error;
+ a2 = (PyLongObject *) long_rshift(a1, b);
+ Py_DECREF(a1);
+ if (a2 == NULL)
+ goto rshift_error;
+ z = (PyLongObject *) long_invert(a2);
+ Py_DECREF(a2);
+ }
+ else {
+ shiftby = PyLong_AsSsize_t((PyObject *)b);
+ if (shiftby == -1L && PyErr_Occurred())
+ goto rshift_error;
+ if (shiftby < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "negative shift count");
+ goto rshift_error;
+ }
+ wordshift = shiftby / PyLong_SHIFT;
+ newsize = ABS(Py_SIZE(a)) - wordshift;
+ if (newsize <= 0) {
+ z = _PyLong_New(0);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)z;
+ }
+ loshift = shiftby % PyLong_SHIFT;
+ hishift = PyLong_SHIFT - loshift;
+ lomask = ((digit)1 << hishift) - 1;
+ himask = PyLong_MASK ^ lomask;
+ z = _PyLong_New(newsize);
+ if (z == NULL)
+ goto rshift_error;
+ if (Py_SIZE(a) < 0)
+ Py_SIZE(z) = -(Py_SIZE(z));
+ for (i = 0, j = wordshift; i < newsize; i++, j++) {
+ z->ob_digit[i] = (a->ob_digit[j] >> loshift) & lomask;
+ if (i+1 < newsize)
+ z->ob_digit[i] |=
+ (a->ob_digit[j+1] << hishift) & himask;
+ }
+ z = long_normalize(z);
+ }
rshift_error:
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *) z;
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *) z;
}
static PyObject *
long_lshift(PyObject *v, PyObject *w)
{
- /* This version due to Tim Peters */
- PyLongObject *a, *b;
- PyLongObject *z = NULL;
- Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
- twodigits accum;
-
- CONVERT_BINOP(v, w, &a, &b);
-
- shiftby = PyLong_AsSsize_t((PyObject *)b);
- if (shiftby == -1L && PyErr_Occurred())
- goto lshift_error;
- if (shiftby < 0) {
- PyErr_SetString(PyExc_ValueError, "negative shift count");
- goto lshift_error;
- }
- /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
- wordshift = shiftby / PyLong_SHIFT;
- remshift = shiftby - wordshift * PyLong_SHIFT;
-
- oldsize = ABS(a->ob_size);
- newsize = oldsize + wordshift;
- if (remshift)
- ++newsize;
- z = _PyLong_New(newsize);
- if (z == NULL)
- goto lshift_error;
- if (a->ob_size < 0)
- z->ob_size = -(z->ob_size);
- for (i = 0; i < wordshift; i++)
- z->ob_digit[i] = 0;
- accum = 0;
- for (i = wordshift, j = 0; j < oldsize; i++, j++) {
- accum |= (twodigits)a->ob_digit[j] << remshift;
- z->ob_digit[i] = (digit)(accum & PyLong_MASK);
- accum >>= PyLong_SHIFT;
- }
- if (remshift)
- z->ob_digit[newsize-1] = (digit)accum;
- else
- assert(!accum);
- z = long_normalize(z);
+ /* This version due to Tim Peters */
+ PyLongObject *a, *b;
+ PyLongObject *z = NULL;
+ Py_ssize_t shiftby, oldsize, newsize, wordshift, remshift, i, j;
+ twodigits accum;
+
+ CONVERT_BINOP(v, w, &a, &b);
+
+ shiftby = PyLong_AsSsize_t((PyObject *)b);
+ if (shiftby == -1L && PyErr_Occurred())
+ goto lshift_error;
+ if (shiftby < 0) {
+ PyErr_SetString(PyExc_ValueError, "negative shift count");
+ goto lshift_error;
+ }
+ /* wordshift, remshift = divmod(shiftby, PyLong_SHIFT) */
+ wordshift = shiftby / PyLong_SHIFT;
+ remshift = shiftby - wordshift * PyLong_SHIFT;
+
+ oldsize = ABS(a->ob_size);
+ newsize = oldsize + wordshift;
+ if (remshift)
+ ++newsize;
+ z = _PyLong_New(newsize);
+ if (z == NULL)
+ goto lshift_error;
+ if (a->ob_size < 0)
+ z->ob_size = -(z->ob_size);
+ for (i = 0; i < wordshift; i++)
+ z->ob_digit[i] = 0;
+ accum = 0;
+ for (i = wordshift, j = 0; j < oldsize; i++, j++) {
+ accum |= (twodigits)a->ob_digit[j] << remshift;
+ z->ob_digit[i] = (digit)(accum & PyLong_MASK);
+ accum >>= PyLong_SHIFT;
+ }
+ if (remshift)
+ z->ob_digit[newsize-1] = (digit)accum;
+ else
+ assert(!accum);
+ z = long_normalize(z);
lshift_error:
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *) z;
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *) z;
}
/* Compute two's complement of digit vector a[0:m], writing result to
@@ -3727,246 +3727,246 @@ lshift_error:
static void
v_complement(digit *z, digit *a, Py_ssize_t m)
{
- Py_ssize_t i;
- digit carry = 1;
- for (i = 0; i < m; ++i) {
- carry += a[i] ^ PyLong_MASK;
- z[i] = carry & PyLong_MASK;
- carry >>= PyLong_SHIFT;
- }
- assert(carry == 0);
+ Py_ssize_t i;
+ digit carry = 1;
+ for (i = 0; i < m; ++i) {
+ carry += a[i] ^ PyLong_MASK;
+ z[i] = carry & PyLong_MASK;
+ carry >>= PyLong_SHIFT;
+ }
+ assert(carry == 0);
}
/* Bitwise and/xor/or operations */
static PyObject *
long_bitwise(PyLongObject *a,
- int op, /* '&', '|', '^' */
- PyLongObject *b)
+ int op, /* '&', '|', '^' */
+ PyLongObject *b)
{
- int nega, negb, negz;
- Py_ssize_t size_a, size_b, size_z, i;
- PyLongObject *z;
-
- /* Bitwise operations for negative numbers operate as though
- on a two's complement representation. So convert arguments
- from sign-magnitude to two's complement, and convert the
- result back to sign-magnitude at the end. */
-
- /* If a is negative, replace it by its two's complement. */
- size_a = ABS(Py_SIZE(a));
- nega = Py_SIZE(a) < 0;
- if (nega) {
- z = _PyLong_New(size_a);
- if (z == NULL)
- return NULL;
- v_complement(z->ob_digit, a->ob_digit, size_a);
- a = z;
- }
- else
- /* Keep reference count consistent. */
- Py_INCREF(a);
-
- /* Same for b. */
- size_b = ABS(Py_SIZE(b));
- negb = Py_SIZE(b) < 0;
- if (negb) {
- z = _PyLong_New(size_b);
- if (z == NULL) {
- Py_DECREF(a);
- return NULL;
- }
- v_complement(z->ob_digit, b->ob_digit, size_b);
- b = z;
- }
- else
- Py_INCREF(b);
-
- /* Swap a and b if necessary to ensure size_a >= size_b. */
- if (size_a < size_b) {
- z = a; a = b; b = z;
- size_z = size_a; size_a = size_b; size_b = size_z;
- negz = nega; nega = negb; negb = negz;
- }
-
- /* JRH: The original logic here was to allocate the result value (z)
- as the longer of the two operands. However, there are some cases
- where the result is guaranteed to be shorter than that: AND of two
- positives, OR of two negatives: use the shorter number. AND with
- mixed signs: use the positive number. OR with mixed signs: use the
- negative number.
- */
- switch (op) {
- case '^':
- negz = nega ^ negb;
- size_z = size_a;
- break;
- case '&':
- negz = nega & negb;
- size_z = negb ? size_a : size_b;
- break;
- case '|':
- negz = nega | negb;
- size_z = negb ? size_b : size_a;
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- /* We allow an extra digit if z is negative, to make sure that
- the final two's complement of z doesn't overflow. */
- z = _PyLong_New(size_z + negz);
- if (z == NULL) {
- Py_DECREF(a);
- Py_DECREF(b);
- return NULL;
- }
-
- /* Compute digits for overlap of a and b. */
- switch(op) {
- case '&':
- for (i = 0; i < size_b; ++i)
- z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
- break;
- case '|':
- for (i = 0; i < size_b; ++i)
- z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
- break;
- case '^':
- for (i = 0; i < size_b; ++i)
- z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
- break;
- default:
- PyErr_BadArgument();
- return NULL;
- }
-
- /* Copy any remaining digits of a, inverting if necessary. */
- if (op == '^' && negb)
- for (; i < size_z; ++i)
- z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
- else if (i < size_z)
- memcpy(&z->ob_digit[i], &a->ob_digit[i],
- (size_z-i)*sizeof(digit));
-
- /* Complement result if negative. */
- if (negz) {
- Py_SIZE(z) = -(Py_SIZE(z));
- z->ob_digit[size_z] = PyLong_MASK;
- v_complement(z->ob_digit, z->ob_digit, size_z+1);
- }
-
- Py_DECREF(a);
- Py_DECREF(b);
- return (PyObject *)long_normalize(z);
+ int nega, negb, negz;
+ Py_ssize_t size_a, size_b, size_z, i;
+ PyLongObject *z;
+
+ /* Bitwise operations for negative numbers operate as though
+ on a two's complement representation. So convert arguments
+ from sign-magnitude to two's complement, and convert the
+ result back to sign-magnitude at the end. */
+
+ /* If a is negative, replace it by its two's complement. */
+ size_a = ABS(Py_SIZE(a));
+ nega = Py_SIZE(a) < 0;
+ if (nega) {
+ z = _PyLong_New(size_a);
+ if (z == NULL)
+ return NULL;
+ v_complement(z->ob_digit, a->ob_digit, size_a);
+ a = z;
+ }
+ else
+ /* Keep reference count consistent. */
+ Py_INCREF(a);
+
+ /* Same for b. */
+ size_b = ABS(Py_SIZE(b));
+ negb = Py_SIZE(b) < 0;
+ if (negb) {
+ z = _PyLong_New(size_b);
+ if (z == NULL) {
+ Py_DECREF(a);
+ return NULL;
+ }
+ v_complement(z->ob_digit, b->ob_digit, size_b);
+ b = z;
+ }
+ else
+ Py_INCREF(b);
+
+ /* Swap a and b if necessary to ensure size_a >= size_b. */
+ if (size_a < size_b) {
+ z = a; a = b; b = z;
+ size_z = size_a; size_a = size_b; size_b = size_z;
+ negz = nega; nega = negb; negb = negz;
+ }
+
+ /* JRH: The original logic here was to allocate the result value (z)
+ as the longer of the two operands. However, there are some cases
+ where the result is guaranteed to be shorter than that: AND of two
+ positives, OR of two negatives: use the shorter number. AND with
+ mixed signs: use the positive number. OR with mixed signs: use the
+ negative number.
+ */
+ switch (op) {
+ case '^':
+ negz = nega ^ negb;
+ size_z = size_a;
+ break;
+ case '&':
+ negz = nega & negb;
+ size_z = negb ? size_a : size_b;
+ break;
+ case '|':
+ negz = nega | negb;
+ size_z = negb ? size_b : size_a;
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ /* We allow an extra digit if z is negative, to make sure that
+ the final two's complement of z doesn't overflow. */
+ z = _PyLong_New(size_z + negz);
+ if (z == NULL) {
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return NULL;
+ }
+
+ /* Compute digits for overlap of a and b. */
+ switch(op) {
+ case '&':
+ for (i = 0; i < size_b; ++i)
+ z->ob_digit[i] = a->ob_digit[i] & b->ob_digit[i];
+ break;
+ case '|':
+ for (i = 0; i < size_b; ++i)
+ z->ob_digit[i] = a->ob_digit[i] | b->ob_digit[i];
+ break;
+ case '^':
+ for (i = 0; i < size_b; ++i)
+ z->ob_digit[i] = a->ob_digit[i] ^ b->ob_digit[i];
+ break;
+ default:
+ PyErr_BadArgument();
+ return NULL;
+ }
+
+ /* Copy any remaining digits of a, inverting if necessary. */
+ if (op == '^' && negb)
+ for (; i < size_z; ++i)
+ z->ob_digit[i] = a->ob_digit[i] ^ PyLong_MASK;
+ else if (i < size_z)
+ memcpy(&z->ob_digit[i], &a->ob_digit[i],
+ (size_z-i)*sizeof(digit));
+
+ /* Complement result if negative. */
+ if (negz) {
+ Py_SIZE(z) = -(Py_SIZE(z));
+ z->ob_digit[size_z] = PyLong_MASK;
+ v_complement(z->ob_digit, z->ob_digit, size_z+1);
+ }
+
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return (PyObject *)long_normalize(z);
}
static PyObject *
long_and(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b;
- PyObject *c;
- CONVERT_BINOP(v, w, &a, &b);
- c = long_bitwise(a, '&', b);
- Py_DECREF(a);
- Py_DECREF(b);
- return c;
+ PyLongObject *a, *b;
+ PyObject *c;
+ CONVERT_BINOP(v, w, &a, &b);
+ c = long_bitwise(a, '&', b);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return c;
}
static PyObject *
long_xor(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b;
- PyObject *c;
- CONVERT_BINOP(v, w, &a, &b);
- c = long_bitwise(a, '^', b);
- Py_DECREF(a);
- Py_DECREF(b);
- return c;
+ PyLongObject *a, *b;
+ PyObject *c;
+ CONVERT_BINOP(v, w, &a, &b);
+ c = long_bitwise(a, '^', b);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return c;
}
static PyObject *
long_or(PyObject *v, PyObject *w)
{
- PyLongObject *a, *b;
- PyObject *c;
- CONVERT_BINOP(v, w, &a, &b);
- c = long_bitwise(a, '|', b);
- Py_DECREF(a);
- Py_DECREF(b);
- return c;
+ PyLongObject *a, *b;
+ PyObject *c;
+ CONVERT_BINOP(v, w, &a, &b);
+ c = long_bitwise(a, '|', b);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ return c;
}
static int
long_coerce(PyObject **pv, PyObject **pw)
{
- if (PyInt_Check(*pw)) {
- *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
- if (*pw == NULL)
- return -1;
- Py_INCREF(*pv);
- return 0;
- }
- else if (PyLong_Check(*pw)) {
- Py_INCREF(*pv);
- Py_INCREF(*pw);
- return 0;
- }
- return 1; /* Can't do it */
+ if (PyInt_Check(*pw)) {
+ *pw = PyLong_FromLong(PyInt_AS_LONG(*pw));
+ if (*pw == NULL)
+ return -1;
+ Py_INCREF(*pv);
+ return 0;
+ }
+ else if (PyLong_Check(*pw)) {
+ Py_INCREF(*pv);
+ Py_INCREF(*pw);
+ return 0;
+ }
+ return 1; /* Can't do it */
}
static PyObject *
long_long(PyObject *v)
{
- if (PyLong_CheckExact(v))
- Py_INCREF(v);
- else
- v = _PyLong_Copy((PyLongObject *)v);
- return v;
+ if (PyLong_CheckExact(v))
+ Py_INCREF(v);
+ else
+ v = _PyLong_Copy((PyLongObject *)v);
+ return v;
}
static PyObject *
long_int(PyObject *v)
{
- long x;
- x = PyLong_AsLong(v);
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
- PyErr_Clear();
- if (PyLong_CheckExact(v)) {
- Py_INCREF(v);
- return v;
- }
- else
- return _PyLong_Copy((PyLongObject *)v);
- }
- else
- return NULL;
- }
- return PyInt_FromLong(x);
+ long x;
+ x = PyLong_AsLong(v);
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
+ PyErr_Clear();
+ if (PyLong_CheckExact(v)) {
+ Py_INCREF(v);
+ return v;
+ }
+ else
+ return _PyLong_Copy((PyLongObject *)v);
+ }
+ else
+ return NULL;
+ }
+ return PyInt_FromLong(x);
}
static PyObject *
long_float(PyObject *v)
{
- double result;
- result = PyLong_AsDouble(v);
- if (result == -1.0 && PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(result);
+ double result;
+ result = PyLong_AsDouble(v);
+ if (result == -1.0 && PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(result);
}
static PyObject *
long_oct(PyObject *v)
{
- return _PyLong_Format(v, 8, 1, 0);
+ return _PyLong_Format(v, 8, 1, 0);
}
static PyObject *
long_hex(PyObject *v)
{
- return _PyLong_Format(v, 16, 1, 0);
+ return _PyLong_Format(v, 16, 1, 0);
}
static PyObject *
@@ -3975,49 +3975,49 @@ long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *x = NULL;
- int base = -909; /* unlikely! */
- static char *kwlist[] = {"x", "base", 0};
-
- if (type != &PyLong_Type)
- return long_subtype_new(type, args, kwds); /* Wimp out */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
- &x, &base))
- return NULL;
- if (x == NULL)
- return PyLong_FromLong(0L);
- if (base == -909)
- return PyNumber_Long(x);
- else if (PyString_Check(x)) {
- /* Since PyLong_FromString doesn't have a length parameter,
- * check here for possible NULs in the string. */
- char *string = PyString_AS_STRING(x);
- if (strlen(string) != (size_t)PyString_Size(x)) {
- /* create a repr() of the input string,
- * just like PyLong_FromString does. */
- PyObject *srepr;
- srepr = PyObject_Repr(x);
- if (srepr == NULL)
- return NULL;
- PyErr_Format(PyExc_ValueError,
- "invalid literal for long() with base %d: %s",
- base, PyString_AS_STRING(srepr));
- Py_DECREF(srepr);
- return NULL;
- }
- return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
- }
+ PyObject *x = NULL;
+ int base = -909; /* unlikely! */
+ static char *kwlist[] = {"x", "base", 0};
+
+ if (type != &PyLong_Type)
+ return long_subtype_new(type, args, kwds); /* Wimp out */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|Oi:long", kwlist,
+ &x, &base))
+ return NULL;
+ if (x == NULL)
+ return PyLong_FromLong(0L);
+ if (base == -909)
+ return PyNumber_Long(x);
+ else if (PyString_Check(x)) {
+ /* Since PyLong_FromString doesn't have a length parameter,
+ * check here for possible NULs in the string. */
+ char *string = PyString_AS_STRING(x);
+ if (strlen(string) != (size_t)PyString_Size(x)) {
+ /* create a repr() of the input string,
+ * just like PyLong_FromString does. */
+ PyObject *srepr;
+ srepr = PyObject_Repr(x);
+ if (srepr == NULL)
+ return NULL;
+ PyErr_Format(PyExc_ValueError,
+ "invalid literal for long() with base %d: %s",
+ base, PyString_AS_STRING(srepr));
+ Py_DECREF(srepr);
+ return NULL;
+ }
+ return PyLong_FromString(PyString_AS_STRING(x), NULL, base);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(x))
- return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
- PyUnicode_GET_SIZE(x),
- base);
+ else if (PyUnicode_Check(x))
+ return PyLong_FromUnicode(PyUnicode_AS_UNICODE(x),
+ PyUnicode_GET_SIZE(x),
+ base);
#endif
- else {
- PyErr_SetString(PyExc_TypeError,
- "long() can't convert non-string with explicit base");
- return NULL;
- }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "long() can't convert non-string with explicit base");
+ return NULL;
+ }
}
/* Wimpy, slow approach to tp_new calls for subtypes of long:
@@ -4028,138 +4028,138 @@ long_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
static PyObject *
long_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyLongObject *tmp, *newobj;
- Py_ssize_t i, n;
-
- assert(PyType_IsSubtype(type, &PyLong_Type));
- tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
- if (tmp == NULL)
- return NULL;
- assert(PyLong_CheckExact(tmp));
- n = Py_SIZE(tmp);
- if (n < 0)
- n = -n;
- newobj = (PyLongObject *)type->tp_alloc(type, n);
- if (newobj == NULL) {
- Py_DECREF(tmp);
- return NULL;
- }
- assert(PyLong_Check(newobj));
- Py_SIZE(newobj) = Py_SIZE(tmp);
- for (i = 0; i < n; i++)
- newobj->ob_digit[i] = tmp->ob_digit[i];
- Py_DECREF(tmp);
- return (PyObject *)newobj;
+ PyLongObject *tmp, *newobj;
+ Py_ssize_t i, n;
+
+ assert(PyType_IsSubtype(type, &PyLong_Type));
+ tmp = (PyLongObject *)long_new(&PyLong_Type, args, kwds);
+ if (tmp == NULL)
+ return NULL;
+ assert(PyLong_CheckExact(tmp));
+ n = Py_SIZE(tmp);
+ if (n < 0)
+ n = -n;
+ newobj = (PyLongObject *)type->tp_alloc(type, n);
+ if (newobj == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ assert(PyLong_Check(newobj));
+ Py_SIZE(newobj) = Py_SIZE(tmp);
+ for (i = 0; i < n; i++)
+ newobj->ob_digit[i] = tmp->ob_digit[i];
+ Py_DECREF(tmp);
+ return (PyObject *)newobj;
}
static PyObject *
long_getnewargs(PyLongObject *v)
{
- return Py_BuildValue("(N)", _PyLong_Copy(v));
+ return Py_BuildValue("(N)", _PyLong_Copy(v));
}
static PyObject *
long_get0(PyLongObject *v, void *context) {
- return PyLong_FromLong(0L);
+ return PyLong_FromLong(0L);
}
static PyObject *
long_get1(PyLongObject *v, void *context) {
- return PyLong_FromLong(1L);
+ return PyLong_FromLong(1L);
}
static PyObject *
long__format__(PyObject *self, PyObject *args)
{
- PyObject *format_spec;
-
- if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
- return NULL;
- if (PyBytes_Check(format_spec))
- return _PyLong_FormatAdvanced(self,
- PyBytes_AS_STRING(format_spec),
- PyBytes_GET_SIZE(format_spec));
- if (PyUnicode_Check(format_spec)) {
- /* Convert format_spec to a str */
- PyObject *result;
- PyObject *str_spec = PyObject_Str(format_spec);
-
- if (str_spec == NULL)
- return NULL;
-
- result = _PyLong_FormatAdvanced(self,
- PyBytes_AS_STRING(str_spec),
- PyBytes_GET_SIZE(str_spec));
-
- Py_DECREF(str_spec);
- return result;
- }
- PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
- return NULL;
+ PyObject *format_spec;
+
+ if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
+ return NULL;
+ if (PyBytes_Check(format_spec))
+ return _PyLong_FormatAdvanced(self,
+ PyBytes_AS_STRING(format_spec),
+ PyBytes_GET_SIZE(format_spec));
+ if (PyUnicode_Check(format_spec)) {
+ /* Convert format_spec to a str */
+ PyObject *result;
+ PyObject *str_spec = PyObject_Str(format_spec);
+
+ if (str_spec == NULL)
+ return NULL;
+
+ result = _PyLong_FormatAdvanced(self,
+ PyBytes_AS_STRING(str_spec),
+ PyBytes_GET_SIZE(str_spec));
+
+ Py_DECREF(str_spec);
+ return result;
+ }
+ PyErr_SetString(PyExc_TypeError, "__format__ requires str or unicode");
+ return NULL;
}
static PyObject *
long_sizeof(PyLongObject *v)
{
- Py_ssize_t res;
+ Py_ssize_t res;
- res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
- return PyInt_FromSsize_t(res);
+ res = v->ob_type->tp_basicsize + ABS(Py_SIZE(v))*sizeof(digit);
+ return PyInt_FromSsize_t(res);
}
static PyObject *
long_bit_length(PyLongObject *v)
{
- PyLongObject *result, *x, *y;
- Py_ssize_t ndigits, msd_bits = 0;
- digit msd;
-
- assert(v != NULL);
- assert(PyLong_Check(v));
-
- ndigits = ABS(Py_SIZE(v));
- if (ndigits == 0)
- return PyInt_FromLong(0);
-
- msd = v->ob_digit[ndigits-1];
- while (msd >= 32) {
- msd_bits += 6;
- msd >>= 6;
- }
- msd_bits += (long)(BitLengthTable[msd]);
-
- if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
- return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
-
- /* expression above may overflow; use Python integers instead */
- result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
- if (result == NULL)
- return NULL;
- x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
- if (x == NULL)
- goto error;
- y = (PyLongObject *)long_mul(result, x);
- Py_DECREF(x);
- if (y == NULL)
- goto error;
- Py_DECREF(result);
- result = y;
-
- x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
- if (x == NULL)
- goto error;
- y = (PyLongObject *)long_add(result, x);
- Py_DECREF(x);
- if (y == NULL)
- goto error;
- Py_DECREF(result);
- result = y;
-
- return (PyObject *)result;
+ PyLongObject *result, *x, *y;
+ Py_ssize_t ndigits, msd_bits = 0;
+ digit msd;
+
+ assert(v != NULL);
+ assert(PyLong_Check(v));
+
+ ndigits = ABS(Py_SIZE(v));
+ if (ndigits == 0)
+ return PyInt_FromLong(0);
+
+ msd = v->ob_digit[ndigits-1];
+ while (msd >= 32) {
+ msd_bits += 6;
+ msd >>= 6;
+ }
+ msd_bits += (long)(BitLengthTable[msd]);
+
+ if (ndigits <= PY_SSIZE_T_MAX/PyLong_SHIFT)
+ return PyInt_FromSsize_t((ndigits-1)*PyLong_SHIFT + msd_bits);
+
+ /* expression above may overflow; use Python integers instead */
+ result = (PyLongObject *)PyLong_FromSsize_t(ndigits - 1);
+ if (result == NULL)
+ return NULL;
+ x = (PyLongObject *)PyLong_FromLong(PyLong_SHIFT);
+ if (x == NULL)
+ goto error;
+ y = (PyLongObject *)long_mul(result, x);
+ Py_DECREF(x);
+ if (y == NULL)
+ goto error;
+ Py_DECREF(result);
+ result = y;
+
+ x = (PyLongObject *)PyLong_FromLong((long)msd_bits);
+ if (x == NULL)
+ goto error;
+ y = (PyLongObject *)long_add(result, x);
+ Py_DECREF(x);
+ if (y == NULL)
+ goto error;
+ Py_DECREF(result);
+ result = y;
+
+ return (PyObject *)result;
error:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
PyDoc_STRVAR(long_bit_length_doc,
@@ -4175,26 +4175,26 @@ Number of bits necessary to represent self in binary.\n\
static PyObject *
long_is_finite(PyObject *v)
{
- Py_RETURN_TRUE;
+ Py_RETURN_TRUE;
}
#endif
static PyMethodDef long_methods[] = {
- {"conjugate", (PyCFunction)long_long, METH_NOARGS,
- "Returns self, the complex conjugate of any long."},
- {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
- long_bit_length_doc},
+ {"conjugate", (PyCFunction)long_long, METH_NOARGS,
+ "Returns self, the complex conjugate of any long."},
+ {"bit_length", (PyCFunction)long_bit_length, METH_NOARGS,
+ long_bit_length_doc},
#if 0
- {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
- "Returns always True."},
+ {"is_finite", (PyCFunction)long_is_finite, METH_NOARGS,
+ "Returns always True."},
#endif
- {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
- "Truncating an Integral returns itself."},
- {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
- {"__format__", (PyCFunction)long__format__, METH_VARARGS},
- {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
- "Returns size in memory, in bytes"},
- {NULL, NULL} /* sentinel */
+ {"__trunc__", (PyCFunction)long_long, METH_NOARGS,
+ "Truncating an Integral returns itself."},
+ {"__getnewargs__", (PyCFunction)long_getnewargs, METH_NOARGS},
+ {"__format__", (PyCFunction)long__format__, METH_VARARGS},
+ {"__sizeof__", (PyCFunction)long_sizeof, METH_NOARGS,
+ "Returns size in memory, in bytes"},
+ {NULL, NULL} /* sentinel */
};
static PyGetSetDef long_getset[] = {
@@ -4227,89 +4227,89 @@ string, use the optional base. It is an error to supply a base when\n\
converting a non-string.");
static PyNumberMethods long_as_number = {
- (binaryfunc) long_add, /*nb_add*/
- (binaryfunc) long_sub, /*nb_subtract*/
- (binaryfunc) long_mul, /*nb_multiply*/
- long_classic_div, /*nb_divide*/
- long_mod, /*nb_remainder*/
- long_divmod, /*nb_divmod*/
- long_pow, /*nb_power*/
- (unaryfunc) long_neg, /*nb_negative*/
- (unaryfunc) long_long, /*tp_positive*/
- (unaryfunc) long_abs, /*tp_absolute*/
- (inquiry) long_nonzero, /*tp_nonzero*/
- (unaryfunc) long_invert, /*nb_invert*/
- long_lshift, /*nb_lshift*/
- (binaryfunc) long_rshift, /*nb_rshift*/
- long_and, /*nb_and*/
- long_xor, /*nb_xor*/
- long_or, /*nb_or*/
- long_coerce, /*nb_coerce*/
- long_int, /*nb_int*/
- long_long, /*nb_long*/
- long_float, /*nb_float*/
- long_oct, /*nb_oct*/
- long_hex, /*nb_hex*/
- 0, /* nb_inplace_add */
- 0, /* nb_inplace_subtract */
- 0, /* nb_inplace_multiply */
- 0, /* nb_inplace_divide */
- 0, /* nb_inplace_remainder */
- 0, /* nb_inplace_power */
- 0, /* nb_inplace_lshift */
- 0, /* nb_inplace_rshift */
- 0, /* nb_inplace_and */
- 0, /* nb_inplace_xor */
- 0, /* nb_inplace_or */
- long_div, /* nb_floor_divide */
- long_true_divide, /* nb_true_divide */
- 0, /* nb_inplace_floor_divide */
- 0, /* nb_inplace_true_divide */
- long_long, /* nb_index */
+ (binaryfunc) long_add, /*nb_add*/
+ (binaryfunc) long_sub, /*nb_subtract*/
+ (binaryfunc) long_mul, /*nb_multiply*/
+ long_classic_div, /*nb_divide*/
+ long_mod, /*nb_remainder*/
+ long_divmod, /*nb_divmod*/
+ long_pow, /*nb_power*/
+ (unaryfunc) long_neg, /*nb_negative*/
+ (unaryfunc) long_long, /*tp_positive*/
+ (unaryfunc) long_abs, /*tp_absolute*/
+ (inquiry) long_nonzero, /*tp_nonzero*/
+ (unaryfunc) long_invert, /*nb_invert*/
+ long_lshift, /*nb_lshift*/
+ (binaryfunc) long_rshift, /*nb_rshift*/
+ long_and, /*nb_and*/
+ long_xor, /*nb_xor*/
+ long_or, /*nb_or*/
+ long_coerce, /*nb_coerce*/
+ long_int, /*nb_int*/
+ long_long, /*nb_long*/
+ long_float, /*nb_float*/
+ long_oct, /*nb_oct*/
+ long_hex, /*nb_hex*/
+ 0, /* nb_inplace_add */
+ 0, /* nb_inplace_subtract */
+ 0, /* nb_inplace_multiply */
+ 0, /* nb_inplace_divide */
+ 0, /* nb_inplace_remainder */
+ 0, /* nb_inplace_power */
+ 0, /* nb_inplace_lshift */
+ 0, /* nb_inplace_rshift */
+ 0, /* nb_inplace_and */
+ 0, /* nb_inplace_xor */
+ 0, /* nb_inplace_or */
+ long_div, /* nb_floor_divide */
+ long_true_divide, /* nb_true_divide */
+ 0, /* nb_inplace_floor_divide */
+ 0, /* nb_inplace_true_divide */
+ long_long, /* nb_index */
};
PyTypeObject PyLong_Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /* ob_size */
- "long", /* tp_name */
- offsetof(PyLongObject, ob_digit), /* tp_basicsize */
- sizeof(digit), /* tp_itemsize */
- long_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)long_compare, /* tp_compare */
- long_repr, /* tp_repr */
- &long_as_number, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)long_hash, /* tp_hash */
- 0, /* tp_call */
- long_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
- long_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- long_methods, /* tp_methods */
- 0, /* tp_members */
- long_getset, /* 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 */
- long_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /* ob_size */
+ "long", /* tp_name */
+ offsetof(PyLongObject, ob_digit), /* tp_basicsize */
+ sizeof(digit), /* tp_itemsize */
+ long_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)long_compare, /* tp_compare */
+ long_repr, /* tp_repr */
+ &long_as_number, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)long_hash, /* tp_hash */
+ 0, /* tp_call */
+ long_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_LONG_SUBCLASS, /* tp_flags */
+ long_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ long_methods, /* tp_methods */
+ 0, /* tp_members */
+ long_getset, /* 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 */
+ long_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
static PyTypeObject Long_InfoType;
@@ -4321,43 +4321,43 @@ A struct sequence that holds information about Python's\n\
internal representation of integers. The attributes are read only.");
static PyStructSequence_Field long_info_fields[] = {
- {"bits_per_digit", "size of a digit in bits"},
- {"sizeof_digit", "size in bytes of the C type used to "
- "represent a digit"},
- {NULL, NULL}
+ {"bits_per_digit", "size of a digit in bits"},
+ {"sizeof_digit", "size in bytes of the C type used to "
+ "represent a digit"},
+ {NULL, NULL}
};
static PyStructSequence_Desc long_info_desc = {
- "sys.long_info", /* name */
- long_info__doc__, /* doc */
- long_info_fields, /* fields */
- 2 /* number of fields */
+ "sys.long_info", /* name */
+ long_info__doc__, /* doc */
+ long_info_fields, /* fields */
+ 2 /* number of fields */
};
PyObject *
PyLong_GetInfo(void)
{
- PyObject* long_info;
- int field = 0;
- long_info = PyStructSequence_New(&Long_InfoType);
- if (long_info == NULL)
- return NULL;
- PyStructSequence_SET_ITEM(long_info, field++,
- PyInt_FromLong(PyLong_SHIFT));
- PyStructSequence_SET_ITEM(long_info, field++,
- PyInt_FromLong(sizeof(digit)));
- if (PyErr_Occurred()) {
- Py_CLEAR(long_info);
- return NULL;
- }
- return long_info;
+ PyObject* long_info;
+ int field = 0;
+ long_info = PyStructSequence_New(&Long_InfoType);
+ if (long_info == NULL)
+ return NULL;
+ PyStructSequence_SET_ITEM(long_info, field++,
+ PyInt_FromLong(PyLong_SHIFT));
+ PyStructSequence_SET_ITEM(long_info, field++,
+ PyInt_FromLong(sizeof(digit)));
+ if (PyErr_Occurred()) {
+ Py_CLEAR(long_info);
+ return NULL;
+ }
+ return long_info;
}
int
_PyLong_Init(void)
{
- /* initialize long_info */
- if (Long_InfoType.tp_name == 0)
- PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
- return 1;
+ /* initialize long_info */
+ if (Long_InfoType.tp_name == 0)
+ PyStructSequence_InitType(&Long_InfoType, &long_info_desc);
+ return 1;
}
diff --git a/Objects/methodobject.c b/Objects/methodobject.c
index 69d7791..0b60ca3 100644
--- a/Objects/methodobject.c
+++ b/Objects/methodobject.c
@@ -16,113 +16,113 @@ static int numfree = 0;
PyObject *
PyCFunction_NewEx(PyMethodDef *ml, PyObject *self, PyObject *module)
{
- PyCFunctionObject *op;
- op = free_list;
- if (op != NULL) {
- free_list = (PyCFunctionObject *)(op->m_self);
- PyObject_INIT(op, &PyCFunction_Type);
- numfree--;
- }
- else {
- op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type);
- if (op == NULL)
- return NULL;
- }
- op->m_ml = ml;
- Py_XINCREF(self);
- op->m_self = self;
- Py_XINCREF(module);
- op->m_module = module;
- _PyObject_GC_TRACK(op);
- return (PyObject *)op;
+ PyCFunctionObject *op;
+ op = free_list;
+ if (op != NULL) {
+ free_list = (PyCFunctionObject *)(op->m_self);
+ PyObject_INIT(op, &PyCFunction_Type);
+ numfree--;
+ }
+ else {
+ op = PyObject_GC_New(PyCFunctionObject, &PyCFunction_Type);
+ if (op == NULL)
+ return NULL;
+ }
+ op->m_ml = ml;
+ Py_XINCREF(self);
+ op->m_self = self;
+ Py_XINCREF(module);
+ op->m_module = module;
+ _PyObject_GC_TRACK(op);
+ return (PyObject *)op;
}
PyCFunction
PyCFunction_GetFunction(PyObject *op)
{
- if (!PyCFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyCFunctionObject *)op) -> m_ml -> ml_meth;
+ if (!PyCFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyCFunctionObject *)op) -> m_ml -> ml_meth;
}
PyObject *
PyCFunction_GetSelf(PyObject *op)
{
- if (!PyCFunction_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return ((PyCFunctionObject *)op) -> m_self;
+ if (!PyCFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return ((PyCFunctionObject *)op) -> m_self;
}
int
PyCFunction_GetFlags(PyObject *op)
{
- if (!PyCFunction_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return ((PyCFunctionObject *)op) -> m_ml -> ml_flags;
+ if (!PyCFunction_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return ((PyCFunctionObject *)op) -> m_ml -> ml_flags;
}
PyObject *
PyCFunction_Call(PyObject *func, PyObject *arg, PyObject *kw)
{
- PyCFunctionObject* f = (PyCFunctionObject*)func;
- PyCFunction meth = PyCFunction_GET_FUNCTION(func);
- PyObject *self = PyCFunction_GET_SELF(func);
- Py_ssize_t size;
-
- switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
- case METH_VARARGS:
- if (kw == NULL || PyDict_Size(kw) == 0)
- return (*meth)(self, arg);
- break;
- case METH_VARARGS | METH_KEYWORDS:
- case METH_OLDARGS | METH_KEYWORDS:
- return (*(PyCFunctionWithKeywords)meth)(self, arg, kw);
- case METH_NOARGS:
- if (kw == NULL || PyDict_Size(kw) == 0) {
- size = PyTuple_GET_SIZE(arg);
- if (size == 0)
- return (*meth)(self, NULL);
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes no arguments (%zd given)",
- f->m_ml->ml_name, size);
- return NULL;
- }
- break;
- case METH_O:
- if (kw == NULL || PyDict_Size(kw) == 0) {
- size = PyTuple_GET_SIZE(arg);
- if (size == 1)
- return (*meth)(self, PyTuple_GET_ITEM(arg, 0));
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes exactly one argument (%zd given)",
- f->m_ml->ml_name, size);
- return NULL;
- }
- break;
- case METH_OLDARGS:
- /* the really old style */
- if (kw == NULL || PyDict_Size(kw) == 0) {
- size = PyTuple_GET_SIZE(arg);
- if (size == 1)
- arg = PyTuple_GET_ITEM(arg, 0);
- else if (size == 0)
- arg = NULL;
- return (*meth)(self, arg);
- }
- break;
- default:
- PyErr_BadInternalCall();
- return NULL;
- }
- PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
- f->m_ml->ml_name);
- return NULL;
+ PyCFunctionObject* f = (PyCFunctionObject*)func;
+ PyCFunction meth = PyCFunction_GET_FUNCTION(func);
+ PyObject *self = PyCFunction_GET_SELF(func);
+ Py_ssize_t size;
+
+ switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
+ case METH_VARARGS:
+ if (kw == NULL || PyDict_Size(kw) == 0)
+ return (*meth)(self, arg);
+ break;
+ case METH_VARARGS | METH_KEYWORDS:
+ case METH_OLDARGS | METH_KEYWORDS:
+ return (*(PyCFunctionWithKeywords)meth)(self, arg, kw);
+ case METH_NOARGS:
+ if (kw == NULL || PyDict_Size(kw) == 0) {
+ size = PyTuple_GET_SIZE(arg);
+ if (size == 0)
+ return (*meth)(self, NULL);
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes no arguments (%zd given)",
+ f->m_ml->ml_name, size);
+ return NULL;
+ }
+ break;
+ case METH_O:
+ if (kw == NULL || PyDict_Size(kw) == 0) {
+ size = PyTuple_GET_SIZE(arg);
+ if (size == 1)
+ return (*meth)(self, PyTuple_GET_ITEM(arg, 0));
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes exactly one argument (%zd given)",
+ f->m_ml->ml_name, size);
+ return NULL;
+ }
+ break;
+ case METH_OLDARGS:
+ /* the really old style */
+ if (kw == NULL || PyDict_Size(kw) == 0) {
+ size = PyTuple_GET_SIZE(arg);
+ if (size == 1)
+ arg = PyTuple_GET_ITEM(arg, 0);
+ else if (size == 0)
+ arg = NULL;
+ return (*meth)(self, arg);
+ }
+ break;
+ default:
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
+ f->m_ml->ml_name);
+ return NULL;
}
/* Methods (the standard built-in methods, that is) */
@@ -130,187 +130,187 @@ PyCFunction_Call(PyObject *func, PyObject *arg, PyObject *kw)
static void
meth_dealloc(PyCFunctionObject *m)
{
- _PyObject_GC_UNTRACK(m);
- Py_XDECREF(m->m_self);
- Py_XDECREF(m->m_module);
- if (numfree < PyCFunction_MAXFREELIST) {
- m->m_self = (PyObject *)free_list;
- free_list = m;
- numfree++;
- }
- else {
- PyObject_GC_Del(m);
- }
+ _PyObject_GC_UNTRACK(m);
+ Py_XDECREF(m->m_self);
+ Py_XDECREF(m->m_module);
+ if (numfree < PyCFunction_MAXFREELIST) {
+ m->m_self = (PyObject *)free_list;
+ free_list = m;
+ numfree++;
+ }
+ else {
+ PyObject_GC_Del(m);
+ }
}
static PyObject *
meth_get__doc__(PyCFunctionObject *m, void *closure)
{
- const char *doc = m->m_ml->ml_doc;
+ const char *doc = m->m_ml->ml_doc;
- if (doc != NULL)
- return PyString_FromString(doc);
- Py_INCREF(Py_None);
- return Py_None;
+ if (doc != NULL)
+ return PyString_FromString(doc);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
meth_get__name__(PyCFunctionObject *m, void *closure)
{
- return PyString_FromString(m->m_ml->ml_name);
+ return PyString_FromString(m->m_ml->ml_name);
}
static int
meth_traverse(PyCFunctionObject *m, visitproc visit, void *arg)
{
- Py_VISIT(m->m_self);
- Py_VISIT(m->m_module);
- return 0;
+ Py_VISIT(m->m_self);
+ Py_VISIT(m->m_module);
+ return 0;
}
static PyObject *
meth_get__self__(PyCFunctionObject *m, void *closure)
{
- PyObject *self;
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "method.__self__ not accessible in restricted mode");
- return NULL;
- }
- self = m->m_self;
- if (self == NULL)
- self = Py_None;
- Py_INCREF(self);
- return self;
+ PyObject *self;
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "method.__self__ not accessible in restricted mode");
+ return NULL;
+ }
+ self = m->m_self;
+ if (self == NULL)
+ self = Py_None;
+ Py_INCREF(self);
+ return self;
}
static PyGetSetDef meth_getsets [] = {
- {"__doc__", (getter)meth_get__doc__, NULL, NULL},
- {"__name__", (getter)meth_get__name__, NULL, NULL},
- {"__self__", (getter)meth_get__self__, NULL, NULL},
- {0}
+ {"__doc__", (getter)meth_get__doc__, NULL, NULL},
+ {"__name__", (getter)meth_get__name__, NULL, NULL},
+ {"__self__", (getter)meth_get__self__, NULL, NULL},
+ {0}
};
#define OFF(x) offsetof(PyCFunctionObject, x)
static PyMemberDef meth_members[] = {
- {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED},
- {NULL}
+ {"__module__", T_OBJECT, OFF(m_module), PY_WRITE_RESTRICTED},
+ {NULL}
};
static PyObject *
meth_repr(PyCFunctionObject *m)
{
- if (m->m_self == NULL)
- return PyString_FromFormat("<built-in function %s>",
- m->m_ml->ml_name);
- return PyString_FromFormat("<built-in method %s of %s object at %p>",
- m->m_ml->ml_name,
- m->m_self->ob_type->tp_name,
- m->m_self);
+ if (m->m_self == NULL)
+ return PyString_FromFormat("<built-in function %s>",
+ m->m_ml->ml_name);
+ return PyString_FromFormat("<built-in method %s of %s object at %p>",
+ m->m_ml->ml_name,
+ m->m_self->ob_type->tp_name,
+ m->m_self);
}
static int
meth_compare(PyCFunctionObject *a, PyCFunctionObject *b)
{
- if (a->m_self != b->m_self)
- return (a->m_self < b->m_self) ? -1 : 1;
- if (a->m_ml->ml_meth == b->m_ml->ml_meth)
- return 0;
- if (strcmp(a->m_ml->ml_name, b->m_ml->ml_name) < 0)
- return -1;
- else
- return 1;
+ if (a->m_self != b->m_self)
+ return (a->m_self < b->m_self) ? -1 : 1;
+ if (a->m_ml->ml_meth == b->m_ml->ml_meth)
+ return 0;
+ if (strcmp(a->m_ml->ml_name, b->m_ml->ml_name) < 0)
+ return -1;
+ else
+ return 1;
}
static PyObject *
meth_richcompare(PyObject *self, PyObject *other, int op)
{
- PyCFunctionObject *a, *b;
- PyObject *res;
- int eq;
-
- if (op != Py_EQ && op != Py_NE) {
- /* Py3K warning if comparison isn't == or !=. */
- if (PyErr_WarnPy3k("builtin_function_or_method order "
- "comparisons not supported in 3.x", 1) < 0) {
- return NULL;
- }
-
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- else if (!PyCFunction_Check(self) || !PyCFunction_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- a = (PyCFunctionObject *)self;
- b = (PyCFunctionObject *)other;
- eq = a->m_self == b->m_self;
- if (eq)
- eq = a->m_ml->ml_meth == b->m_ml->ml_meth;
- if (op == Py_EQ)
- res = eq ? Py_True : Py_False;
- else
- res = eq ? Py_False : Py_True;
- Py_INCREF(res);
- return res;
+ PyCFunctionObject *a, *b;
+ PyObject *res;
+ int eq;
+
+ if (op != Py_EQ && op != Py_NE) {
+ /* Py3K warning if comparison isn't == or !=. */
+ if (PyErr_WarnPy3k("builtin_function_or_method order "
+ "comparisons not supported in 3.x", 1) < 0) {
+ return NULL;
+ }
+
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ else if (!PyCFunction_Check(self) || !PyCFunction_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ a = (PyCFunctionObject *)self;
+ b = (PyCFunctionObject *)other;
+ eq = a->m_self == b->m_self;
+ if (eq)
+ eq = a->m_ml->ml_meth == b->m_ml->ml_meth;
+ if (op == Py_EQ)
+ res = eq ? Py_True : Py_False;
+ else
+ res = eq ? Py_False : Py_True;
+ Py_INCREF(res);
+ return res;
}
static long
meth_hash(PyCFunctionObject *a)
{
- long x,y;
- if (a->m_self == NULL)
- x = 0;
- else {
- x = PyObject_Hash(a->m_self);
- if (x == -1)
- return -1;
- }
- y = _Py_HashPointer((void*)(a->m_ml->ml_meth));
- if (y == -1)
- return -1;
- x ^= y;
- if (x == -1)
- x = -2;
- return x;
+ long x,y;
+ if (a->m_self == NULL)
+ x = 0;
+ else {
+ x = PyObject_Hash(a->m_self);
+ if (x == -1)
+ return -1;
+ }
+ y = _Py_HashPointer((void*)(a->m_ml->ml_meth));
+ if (y == -1)
+ return -1;
+ x ^= y;
+ if (x == -1)
+ x = -2;
+ return x;
}
PyTypeObject PyCFunction_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "builtin_function_or_method",
- sizeof(PyCFunctionObject),
- 0,
- (destructor)meth_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)meth_compare, /* tp_compare */
- (reprfunc)meth_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)meth_hash, /* tp_hash */
- PyCFunction_Call, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)meth_traverse, /* tp_traverse */
- 0, /* tp_clear */
- meth_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- meth_members, /* tp_members */
- meth_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "builtin_function_or_method",
+ sizeof(PyCFunctionObject),
+ 0,
+ (destructor)meth_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)meth_compare, /* tp_compare */
+ (reprfunc)meth_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)meth_hash, /* tp_hash */
+ PyCFunction_Call, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)meth_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ meth_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ meth_members, /* tp_members */
+ meth_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
};
/* List all methods in a chain -- helper for findmethodinchain */
@@ -318,32 +318,32 @@ PyTypeObject PyCFunction_Type = {
static PyObject *
listmethodchain(PyMethodChain *chain)
{
- PyMethodChain *c;
- PyMethodDef *ml;
- int i, n;
- PyObject *v;
-
- n = 0;
- for (c = chain; c != NULL; c = c->link) {
- for (ml = c->methods; ml->ml_name != NULL; ml++)
- n++;
- }
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- i = 0;
- for (c = chain; c != NULL; c = c->link) {
- for (ml = c->methods; ml->ml_name != NULL; ml++) {
- PyList_SetItem(v, i, PyString_FromString(ml->ml_name));
- i++;
- }
- }
- if (PyErr_Occurred()) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_Sort(v);
- return v;
+ PyMethodChain *c;
+ PyMethodDef *ml;
+ int i, n;
+ PyObject *v;
+
+ n = 0;
+ for (c = chain; c != NULL; c = c->link) {
+ for (ml = c->methods; ml->ml_name != NULL; ml++)
+ n++;
+ }
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ i = 0;
+ for (c = chain; c != NULL; c = c->link) {
+ for (ml = c->methods; ml->ml_name != NULL; ml++) {
+ PyList_SetItem(v, i, PyString_FromString(ml->ml_name));
+ i++;
+ }
+ }
+ if (PyErr_Occurred()) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_Sort(v);
+ return v;
}
/* Find a method in a method chain */
@@ -351,31 +351,31 @@ listmethodchain(PyMethodChain *chain)
PyObject *
Py_FindMethodInChain(PyMethodChain *chain, PyObject *self, const char *name)
{
- if (name[0] == '_' && name[1] == '_') {
- if (strcmp(name, "__methods__") == 0) {
- if (PyErr_WarnPy3k("__methods__ not supported in 3.x",
- 1) < 0)
- return NULL;
- return listmethodchain(chain);
- }
- if (strcmp(name, "__doc__") == 0) {
- const char *doc = self->ob_type->tp_doc;
- if (doc != NULL)
- return PyString_FromString(doc);
- }
- }
- while (chain != NULL) {
- PyMethodDef *ml = chain->methods;
- for (; ml->ml_name != NULL; ml++) {
- if (name[0] == ml->ml_name[0] &&
- strcmp(name+1, ml->ml_name+1) == 0)
- /* XXX */
- return PyCFunction_New(ml, self);
- }
- chain = chain->link;
- }
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
+ if (name[0] == '_' && name[1] == '_') {
+ if (strcmp(name, "__methods__") == 0) {
+ if (PyErr_WarnPy3k("__methods__ not supported in 3.x",
+ 1) < 0)
+ return NULL;
+ return listmethodchain(chain);
+ }
+ if (strcmp(name, "__doc__") == 0) {
+ const char *doc = self->ob_type->tp_doc;
+ if (doc != NULL)
+ return PyString_FromString(doc);
+ }
+ }
+ while (chain != NULL) {
+ PyMethodDef *ml = chain->methods;
+ for (; ml->ml_name != NULL; ml++) {
+ if (name[0] == ml->ml_name[0] &&
+ strcmp(name+1, ml->ml_name+1) == 0)
+ /* XXX */
+ return PyCFunction_New(ml, self);
+ }
+ chain = chain->link;
+ }
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
}
/* Find a method in a single method list */
@@ -383,10 +383,10 @@ Py_FindMethodInChain(PyMethodChain *chain, PyObject *self, const char *name)
PyObject *
Py_FindMethod(PyMethodDef *methods, PyObject *self, const char *name)
{
- PyMethodChain chain;
- chain.methods = methods;
- chain.link = NULL;
- return Py_FindMethodInChain(&chain, self, name);
+ PyMethodChain chain;
+ chain.methods = methods;
+ chain.link = NULL;
+ return Py_FindMethodInChain(&chain, self, name);
}
/* Clear out the free list */
@@ -394,22 +394,22 @@ Py_FindMethod(PyMethodDef *methods, PyObject *self, const char *name)
int
PyCFunction_ClearFreeList(void)
{
- int freelist_size = numfree;
-
- while (free_list) {
- PyCFunctionObject *v = free_list;
- free_list = (PyCFunctionObject *)(v->m_self);
- PyObject_GC_Del(v);
- numfree--;
- }
- assert(numfree == 0);
- return freelist_size;
+ int freelist_size = numfree;
+
+ while (free_list) {
+ PyCFunctionObject *v = free_list;
+ free_list = (PyCFunctionObject *)(v->m_self);
+ PyObject_GC_Del(v);
+ numfree--;
+ }
+ assert(numfree == 0);
+ return freelist_size;
}
void
PyCFunction_Fini(void)
{
- (void)PyCFunction_ClearFreeList();
+ (void)PyCFunction_ClearFreeList();
}
/* PyCFunction_New() is now just a macro that calls PyCFunction_NewEx(),
@@ -423,5 +423,5 @@ PyAPI_FUNC(PyObject *) PyCFunction_New(PyMethodDef *, PyObject *);
PyObject *
PyCFunction_New(PyMethodDef *ml, PyObject *self)
{
- return PyCFunction_NewEx(ml, self, NULL);
+ return PyCFunction_NewEx(ml, self, NULL);
}
diff --git a/Objects/moduleobject.c b/Objects/moduleobject.c
index c9f00e9..ced16eb 100644
--- a/Objects/moduleobject.c
+++ b/Objects/moduleobject.c
@@ -5,144 +5,144 @@
#include "structmember.h"
typedef struct {
- PyObject_HEAD
- PyObject *md_dict;
+ PyObject_HEAD
+ PyObject *md_dict;
} PyModuleObject;
static PyMemberDef module_members[] = {
- {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
- {0}
+ {"__dict__", T_OBJECT, offsetof(PyModuleObject, md_dict), READONLY},
+ {0}
};
PyObject *
PyModule_New(const char *name)
{
- PyModuleObject *m;
- PyObject *nameobj;
- m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
- if (m == NULL)
- return NULL;
- nameobj = PyString_FromString(name);
- m->md_dict = PyDict_New();
- if (m->md_dict == NULL || nameobj == NULL)
- goto fail;
- if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0)
- goto fail;
- if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0)
- goto fail;
- if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0)
- goto fail;
- Py_DECREF(nameobj);
- PyObject_GC_Track(m);
- return (PyObject *)m;
+ PyModuleObject *m;
+ PyObject *nameobj;
+ m = PyObject_GC_New(PyModuleObject, &PyModule_Type);
+ if (m == NULL)
+ return NULL;
+ nameobj = PyString_FromString(name);
+ m->md_dict = PyDict_New();
+ if (m->md_dict == NULL || nameobj == NULL)
+ goto fail;
+ if (PyDict_SetItemString(m->md_dict, "__name__", nameobj) != 0)
+ goto fail;
+ if (PyDict_SetItemString(m->md_dict, "__doc__", Py_None) != 0)
+ goto fail;
+ if (PyDict_SetItemString(m->md_dict, "__package__", Py_None) != 0)
+ goto fail;
+ Py_DECREF(nameobj);
+ PyObject_GC_Track(m);
+ return (PyObject *)m;
fail:
- Py_XDECREF(nameobj);
- Py_DECREF(m);
- return NULL;
+ Py_XDECREF(nameobj);
+ Py_DECREF(m);
+ return NULL;
}
PyObject *
PyModule_GetDict(PyObject *m)
{
- PyObject *d;
- if (!PyModule_Check(m)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- d = ((PyModuleObject *)m) -> md_dict;
- if (d == NULL)
- ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
- return d;
+ PyObject *d;
+ if (!PyModule_Check(m)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ d = ((PyModuleObject *)m) -> md_dict;
+ if (d == NULL)
+ ((PyModuleObject *)m) -> md_dict = d = PyDict_New();
+ return d;
}
char *
PyModule_GetName(PyObject *m)
{
- PyObject *d;
- PyObject *nameobj;
- if (!PyModule_Check(m)) {
- PyErr_BadArgument();
- return NULL;
- }
- d = ((PyModuleObject *)m)->md_dict;
- if (d == NULL ||
- (nameobj = PyDict_GetItemString(d, "__name__")) == NULL ||
- !PyString_Check(nameobj))
- {
- PyErr_SetString(PyExc_SystemError, "nameless module");
- return NULL;
- }
- return PyString_AsString(nameobj);
+ PyObject *d;
+ PyObject *nameobj;
+ if (!PyModule_Check(m)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ d = ((PyModuleObject *)m)->md_dict;
+ if (d == NULL ||
+ (nameobj = PyDict_GetItemString(d, "__name__")) == NULL ||
+ !PyString_Check(nameobj))
+ {
+ PyErr_SetString(PyExc_SystemError, "nameless module");
+ return NULL;
+ }
+ return PyString_AsString(nameobj);
}
char *
PyModule_GetFilename(PyObject *m)
{
- PyObject *d;
- PyObject *fileobj;
- if (!PyModule_Check(m)) {
- PyErr_BadArgument();
- return NULL;
- }
- d = ((PyModuleObject *)m)->md_dict;
- if (d == NULL ||
- (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
- !PyString_Check(fileobj))
- {
- PyErr_SetString(PyExc_SystemError, "module filename missing");
- return NULL;
- }
- return PyString_AsString(fileobj);
+ PyObject *d;
+ PyObject *fileobj;
+ if (!PyModule_Check(m)) {
+ PyErr_BadArgument();
+ return NULL;
+ }
+ d = ((PyModuleObject *)m)->md_dict;
+ if (d == NULL ||
+ (fileobj = PyDict_GetItemString(d, "__file__")) == NULL ||
+ !PyString_Check(fileobj))
+ {
+ PyErr_SetString(PyExc_SystemError, "module filename missing");
+ return NULL;
+ }
+ return PyString_AsString(fileobj);
}
void
_PyModule_Clear(PyObject *m)
{
- /* To make the execution order of destructors for global
- objects a bit more predictable, we first zap all objects
- whose name starts with a single underscore, before we clear
- the entire dictionary. We zap them by replacing them with
- None, rather than deleting them from the dictionary, to
- avoid rehashing the dictionary (to some extent). */
+ /* To make the execution order of destructors for global
+ objects a bit more predictable, we first zap all objects
+ whose name starts with a single underscore, before we clear
+ the entire dictionary. We zap them by replacing them with
+ None, rather than deleting them from the dictionary, to
+ avoid rehashing the dictionary (to some extent). */
- Py_ssize_t pos;
- PyObject *key, *value;
- PyObject *d;
+ Py_ssize_t pos;
+ PyObject *key, *value;
+ PyObject *d;
- d = ((PyModuleObject *)m)->md_dict;
- if (d == NULL)
- return;
+ d = ((PyModuleObject *)m)->md_dict;
+ if (d == NULL)
+ return;
- /* First, clear only names starting with a single underscore */
- pos = 0;
- while (PyDict_Next(d, &pos, &key, &value)) {
- if (value != Py_None && PyString_Check(key)) {
- char *s = PyString_AsString(key);
- if (s[0] == '_' && s[1] != '_') {
- if (Py_VerboseFlag > 1)
- PySys_WriteStderr("# clear[1] %s\n", s);
- PyDict_SetItem(d, key, Py_None);
- }
- }
- }
+ /* First, clear only names starting with a single underscore */
+ pos = 0;
+ while (PyDict_Next(d, &pos, &key, &value)) {
+ if (value != Py_None && PyString_Check(key)) {
+ char *s = PyString_AsString(key);
+ if (s[0] == '_' && s[1] != '_') {
+ if (Py_VerboseFlag > 1)
+ PySys_WriteStderr("# clear[1] %s\n", s);
+ PyDict_SetItem(d, key, Py_None);
+ }
+ }
+ }
- /* Next, clear all names except for __builtins__ */
- pos = 0;
- while (PyDict_Next(d, &pos, &key, &value)) {
- if (value != Py_None && PyString_Check(key)) {
- char *s = PyString_AsString(key);
- if (s[0] != '_' || strcmp(s, "__builtins__") != 0) {
- if (Py_VerboseFlag > 1)
- PySys_WriteStderr("# clear[2] %s\n", s);
- PyDict_SetItem(d, key, Py_None);
- }
- }
- }
+ /* Next, clear all names except for __builtins__ */
+ pos = 0;
+ while (PyDict_Next(d, &pos, &key, &value)) {
+ if (value != Py_None && PyString_Check(key)) {
+ char *s = PyString_AsString(key);
+ if (s[0] != '_' || strcmp(s, "__builtins__") != 0) {
+ if (Py_VerboseFlag > 1)
+ PySys_WriteStderr("# clear[2] %s\n", s);
+ PyDict_SetItem(d, key, Py_None);
+ }
+ }
+ }
- /* Note: we leave __builtins__ in place, so that destructors
- of non-global objects defined in this module can still use
- builtins, in particularly 'None'. */
+ /* Note: we leave __builtins__ in place, so that destructors
+ of non-global objects defined in this module can still use
+ builtins, in particularly 'None'. */
}
@@ -151,56 +151,56 @@ _PyModule_Clear(PyObject *m)
static int
module_init(PyModuleObject *m, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"name", "doc", NULL};
- PyObject *dict, *name = Py_None, *doc = Py_None;
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "S|O:module.__init__",
- kwlist, &name, &doc))
- return -1;
- dict = m->md_dict;
- if (dict == NULL) {
- dict = PyDict_New();
- if (dict == NULL)
- return -1;
- m->md_dict = dict;
- }
- if (PyDict_SetItemString(dict, "__name__", name) < 0)
- return -1;
- if (PyDict_SetItemString(dict, "__doc__", doc) < 0)
- return -1;
- return 0;
+ static char *kwlist[] = {"name", "doc", NULL};
+ PyObject *dict, *name = Py_None, *doc = Py_None;
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "S|O:module.__init__",
+ kwlist, &name, &doc))
+ return -1;
+ dict = m->md_dict;
+ if (dict == NULL) {
+ dict = PyDict_New();
+ if (dict == NULL)
+ return -1;
+ m->md_dict = dict;
+ }
+ if (PyDict_SetItemString(dict, "__name__", name) < 0)
+ return -1;
+ if (PyDict_SetItemString(dict, "__doc__", doc) < 0)
+ return -1;
+ return 0;
}
static void
module_dealloc(PyModuleObject *m)
{
- PyObject_GC_UnTrack(m);
- if (m->md_dict != NULL) {
- /* If we are the only ones holding a reference, we can clear
- the dictionary. */
- if (Py_REFCNT(m->md_dict) == 1)
- _PyModule_Clear((PyObject *)m);
- Py_DECREF(m->md_dict);
- }
- Py_TYPE(m)->tp_free((PyObject *)m);
+ PyObject_GC_UnTrack(m);
+ if (m->md_dict != NULL) {
+ /* If we are the only ones holding a reference, we can clear
+ the dictionary. */
+ if (Py_REFCNT(m->md_dict) == 1)
+ _PyModule_Clear((PyObject *)m);
+ Py_DECREF(m->md_dict);
+ }
+ Py_TYPE(m)->tp_free((PyObject *)m);
}
static PyObject *
module_repr(PyModuleObject *m)
{
- char *name;
- char *filename;
+ char *name;
+ char *filename;
- name = PyModule_GetName((PyObject *)m);
- if (name == NULL) {
- PyErr_Clear();
- name = "?";
- }
- filename = PyModule_GetFilename((PyObject *)m);
- if (filename == NULL) {
- PyErr_Clear();
- return PyString_FromFormat("<module '%s' (built-in)>", name);
- }
- return PyString_FromFormat("<module '%s' from '%s'>", name, filename);
+ name = PyModule_GetName((PyObject *)m);
+ if (name == NULL) {
+ PyErr_Clear();
+ name = "?";
+ }
+ filename = PyModule_GetFilename((PyObject *)m);
+ if (filename == NULL) {
+ PyErr_Clear();
+ return PyString_FromFormat("<module '%s' (built-in)>", name);
+ }
+ return PyString_FromFormat("<module '%s' from '%s'>", name, filename);
}
/* We only need a traverse function, no clear function: If the module
@@ -209,8 +209,8 @@ module_repr(PyModuleObject *m)
static int
module_traverse(PyModuleObject *m, visitproc visit, void *arg)
{
- Py_VISIT(m->md_dict);
- return 0;
+ Py_VISIT(m->md_dict);
+ return 0;
}
PyDoc_STRVAR(module_doc,
@@ -220,44 +220,44 @@ Create a module object.\n\
The name must be a string; the optional doc argument can have any type.");
PyTypeObject PyModule_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "module", /* tp_name */
- sizeof(PyModuleObject), /* tp_size */
- 0, /* tp_itemsize */
- (destructor)module_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)module_repr, /* 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 */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- module_doc, /* tp_doc */
- (traverseproc)module_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- module_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
- (initproc)module_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "module", /* tp_name */
+ sizeof(PyModuleObject), /* tp_size */
+ 0, /* tp_itemsize */
+ (destructor)module_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)module_repr, /* 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 */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ module_doc, /* tp_doc */
+ (traverseproc)module_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ module_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ offsetof(PyModuleObject, md_dict), /* tp_dictoffset */
+ (initproc)module_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
diff --git a/Objects/object.c b/Objects/object.c
index cf8a550..e4252c5 100644
--- a/Objects/object.c
+++ b/Objects/object.c
@@ -14,18 +14,18 @@ Py_ssize_t _Py_RefTotal;
Py_ssize_t
_Py_GetRefTotal(void)
{
- PyObject *o;
- Py_ssize_t total = _Py_RefTotal;
- /* ignore the references to the dummy object of the dicts and sets
- because they are not reliable and not useful (now that the
- hash table code is well-tested) */
- o = _PyDict_Dummy();
- if (o != NULL)
- total -= o->ob_refcnt;
- o = _PySet_Dummy();
- if (o != NULL)
- total -= o->ob_refcnt;
- return total;
+ PyObject *o;
+ Py_ssize_t total = _Py_RefTotal;
+ /* ignore the references to the dummy object of the dicts and sets
+ because they are not reliable and not useful (now that the
+ hash table code is well-tested) */
+ o = _PyDict_Dummy();
+ if (o != NULL)
+ total -= o->ob_refcnt;
+ o = _PySet_Dummy();
+ if (o != NULL)
+ total -= o->ob_refcnt;
+ return total;
}
#endif /* Py_REF_DEBUG */
@@ -58,21 +58,21 @@ void
_Py_AddToAllObjects(PyObject *op, int force)
{
#ifdef Py_DEBUG
- if (!force) {
- /* If it's initialized memory, op must be in or out of
- * the list unambiguously.
- */
- assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
- }
+ if (!force) {
+ /* If it's initialized memory, op must be in or out of
+ * the list unambiguously.
+ */
+ assert((op->_ob_prev == NULL) == (op->_ob_next == NULL));
+ }
#endif
- if (force || op->_ob_prev == NULL) {
- op->_ob_next = refchain._ob_next;
- op->_ob_prev = &refchain;
- refchain._ob_next->_ob_prev = op;
- refchain._ob_next = op;
- }
+ if (force || op->_ob_prev == NULL) {
+ op->_ob_next = refchain._ob_next;
+ op->_ob_prev = &refchain;
+ refchain._ob_next->_ob_prev = op;
+ refchain._ob_next = op;
+ }
}
-#endif /* Py_TRACE_REFS */
+#endif /* Py_TRACE_REFS */
#ifdef COUNT_ALLOCS
static PyTypeObject *type_list;
@@ -89,99 +89,99 @@ extern Py_ssize_t null_strings, one_strings;
void
dump_counts(FILE* f)
{
- PyTypeObject *tp;
-
- for (tp = type_list; tp; tp = tp->tp_next)
- fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
- "freed: %" PY_FORMAT_SIZE_T "d, "
- "max in use: %" PY_FORMAT_SIZE_T "d\n",
- tp->tp_name, tp->tp_allocs, tp->tp_frees,
- tp->tp_maxalloc);
- fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
- "empty: %" PY_FORMAT_SIZE_T "d\n",
- fast_tuple_allocs, tuple_zero_allocs);
- fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
- "neg: %" PY_FORMAT_SIZE_T "d\n",
- quick_int_allocs, quick_neg_int_allocs);
- fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
- "1-strings: %" PY_FORMAT_SIZE_T "d\n",
- null_strings, one_strings);
+ PyTypeObject *tp;
+
+ for (tp = type_list; tp; tp = tp->tp_next)
+ fprintf(f, "%s alloc'd: %" PY_FORMAT_SIZE_T "d, "
+ "freed: %" PY_FORMAT_SIZE_T "d, "
+ "max in use: %" PY_FORMAT_SIZE_T "d\n",
+ tp->tp_name, tp->tp_allocs, tp->tp_frees,
+ tp->tp_maxalloc);
+ fprintf(f, "fast tuple allocs: %" PY_FORMAT_SIZE_T "d, "
+ "empty: %" PY_FORMAT_SIZE_T "d\n",
+ fast_tuple_allocs, tuple_zero_allocs);
+ fprintf(f, "fast int allocs: pos: %" PY_FORMAT_SIZE_T "d, "
+ "neg: %" PY_FORMAT_SIZE_T "d\n",
+ quick_int_allocs, quick_neg_int_allocs);
+ fprintf(f, "null strings: %" PY_FORMAT_SIZE_T "d, "
+ "1-strings: %" PY_FORMAT_SIZE_T "d\n",
+ null_strings, one_strings);
}
PyObject *
get_counts(void)
{
- PyTypeObject *tp;
- PyObject *result;
- PyObject *v;
-
- result = PyList_New(0);
- if (result == NULL)
- return NULL;
- for (tp = type_list; tp; tp = tp->tp_next) {
- v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
- tp->tp_frees, tp->tp_maxalloc);
- if (v == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- if (PyList_Append(result, v) < 0) {
- Py_DECREF(v);
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(v);
- }
- return result;
+ PyTypeObject *tp;
+ PyObject *result;
+ PyObject *v;
+
+ result = PyList_New(0);
+ if (result == NULL)
+ return NULL;
+ for (tp = type_list; tp; tp = tp->tp_next) {
+ v = Py_BuildValue("(snnn)", tp->tp_name, tp->tp_allocs,
+ tp->tp_frees, tp->tp_maxalloc);
+ if (v == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ if (PyList_Append(result, v) < 0) {
+ Py_DECREF(v);
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ return result;
}
void
inc_count(PyTypeObject *tp)
{
- if (tp->tp_next == NULL && tp->tp_prev == NULL) {
- /* first time; insert in linked list */
- if (tp->tp_next != NULL) /* sanity check */
- Py_FatalError("XXX inc_count sanity check");
- if (type_list)
- type_list->tp_prev = tp;
- tp->tp_next = type_list;
- /* Note that as of Python 2.2, heap-allocated type objects
- * can go away, but this code requires that they stay alive
- * until program exit. That's why we're careful with
- * refcounts here. type_list gets a new reference to tp,
- * while ownership of the reference type_list used to hold
- * (if any) was transferred to tp->tp_next in the line above.
- * tp is thus effectively immortal after this.
- */
- Py_INCREF(tp);
- type_list = tp;
+ if (tp->tp_next == NULL && tp->tp_prev == NULL) {
+ /* first time; insert in linked list */
+ if (tp->tp_next != NULL) /* sanity check */
+ Py_FatalError("XXX inc_count sanity check");
+ if (type_list)
+ type_list->tp_prev = tp;
+ tp->tp_next = type_list;
+ /* Note that as of Python 2.2, heap-allocated type objects
+ * can go away, but this code requires that they stay alive
+ * until program exit. That's why we're careful with
+ * refcounts here. type_list gets a new reference to tp,
+ * while ownership of the reference type_list used to hold
+ * (if any) was transferred to tp->tp_next in the line above.
+ * tp is thus effectively immortal after this.
+ */
+ Py_INCREF(tp);
+ type_list = tp;
#ifdef Py_TRACE_REFS
- /* Also insert in the doubly-linked list of all objects,
- * if not already there.
- */
- _Py_AddToAllObjects((PyObject *)tp, 0);
+ /* Also insert in the doubly-linked list of all objects,
+ * if not already there.
+ */
+ _Py_AddToAllObjects((PyObject *)tp, 0);
#endif
- }
- tp->tp_allocs++;
- if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
- tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
+ }
+ tp->tp_allocs++;
+ if (tp->tp_allocs - tp->tp_frees > tp->tp_maxalloc)
+ tp->tp_maxalloc = tp->tp_allocs - tp->tp_frees;
}
void dec_count(PyTypeObject *tp)
{
- tp->tp_frees++;
- if (unlist_types_without_objects &&
- tp->tp_allocs == tp->tp_frees) {
- /* unlink the type from type_list */
- if (tp->tp_prev)
- tp->tp_prev->tp_next = tp->tp_next;
- else
- type_list = tp->tp_next;
- if (tp->tp_next)
- tp->tp_next->tp_prev = tp->tp_prev;
- tp->tp_next = tp->tp_prev = NULL;
- Py_DECREF(tp);
- }
+ tp->tp_frees++;
+ if (unlist_types_without_objects &&
+ tp->tp_allocs == tp->tp_frees) {
+ /* unlink the type from type_list */
+ if (tp->tp_prev)
+ tp->tp_prev->tp_next = tp->tp_next;
+ else
+ type_list = tp->tp_next;
+ if (tp->tp_next)
+ tp->tp_next->tp_prev = tp->tp_prev;
+ tp->tp_next = tp->tp_prev = NULL;
+ Py_DECREF(tp);
+ }
}
#endif
@@ -191,13 +191,13 @@ void dec_count(PyTypeObject *tp)
void
_Py_NegativeRefcount(const char *fname, int lineno, PyObject *op)
{
- char buf[300];
+ char buf[300];
- PyOS_snprintf(buf, sizeof(buf),
- "%s:%i object at %p has negative ref count "
- "%" PY_FORMAT_SIZE_T "d",
- fname, lineno, op, op->ob_refcnt);
- Py_FatalError(buf);
+ PyOS_snprintf(buf, sizeof(buf),
+ "%s:%i object at %p has negative ref count "
+ "%" PY_FORMAT_SIZE_T "d",
+ fname, lineno, op, op->ob_refcnt);
+ Py_FatalError(buf);
}
#endif /* Py_REF_DEBUG */
@@ -217,45 +217,45 @@ Py_DecRef(PyObject *o)
PyObject *
PyObject_Init(PyObject *op, PyTypeObject *tp)
{
- if (op == NULL)
- return PyErr_NoMemory();
- /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
- Py_TYPE(op) = tp;
- _Py_NewReference(op);
- return op;
+ if (op == NULL)
+ return PyErr_NoMemory();
+ /* Any changes should be reflected in PyObject_INIT (objimpl.h) */
+ Py_TYPE(op) = tp;
+ _Py_NewReference(op);
+ return op;
}
PyVarObject *
PyObject_InitVar(PyVarObject *op, PyTypeObject *tp, Py_ssize_t size)
{
- if (op == NULL)
- return (PyVarObject *) PyErr_NoMemory();
- /* Any changes should be reflected in PyObject_INIT_VAR */
- op->ob_size = size;
- Py_TYPE(op) = tp;
- _Py_NewReference((PyObject *)op);
- return op;
+ if (op == NULL)
+ return (PyVarObject *) PyErr_NoMemory();
+ /* Any changes should be reflected in PyObject_INIT_VAR */
+ op->ob_size = size;
+ Py_TYPE(op) = tp;
+ _Py_NewReference((PyObject *)op);
+ return op;
}
PyObject *
_PyObject_New(PyTypeObject *tp)
{
- PyObject *op;
- op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
- if (op == NULL)
- return PyErr_NoMemory();
- return PyObject_INIT(op, tp);
+ PyObject *op;
+ op = (PyObject *) PyObject_MALLOC(_PyObject_SIZE(tp));
+ if (op == NULL)
+ return PyErr_NoMemory();
+ return PyObject_INIT(op, tp);
}
PyVarObject *
_PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
{
- PyVarObject *op;
- const size_t size = _PyObject_VAR_SIZE(tp, nitems);
- op = (PyVarObject *) PyObject_MALLOC(size);
- if (op == NULL)
- return (PyVarObject *)PyErr_NoMemory();
- return PyObject_INIT_VAR(op, tp, nitems);
+ PyVarObject *op;
+ const size_t size = _PyObject_VAR_SIZE(tp, nitems);
+ op = (PyVarObject *) PyObject_MALLOC(size);
+ if (op == NULL)
+ return (PyVarObject *)PyErr_NoMemory();
+ return PyObject_INIT_VAR(op, tp, nitems);
}
/* for binary compatibility with 2.2 */
@@ -263,284 +263,284 @@ _PyObject_NewVar(PyTypeObject *tp, Py_ssize_t nitems)
void
_PyObject_Del(PyObject *op)
{
- PyObject_FREE(op);
+ PyObject_FREE(op);
}
/* Implementation of PyObject_Print with recursion checking */
static int
internal_print(PyObject *op, FILE *fp, int flags, int nesting)
{
- int ret = 0;
- if (nesting > 10) {
- PyErr_SetString(PyExc_RuntimeError, "print recursion");
- return -1;
- }
- if (PyErr_CheckSignals())
- return -1;
+ int ret = 0;
+ if (nesting > 10) {
+ PyErr_SetString(PyExc_RuntimeError, "print recursion");
+ return -1;
+ }
+ if (PyErr_CheckSignals())
+ return -1;
#ifdef USE_STACKCHECK
- if (PyOS_CheckStack()) {
- PyErr_SetString(PyExc_MemoryError, "stack overflow");
- return -1;
- }
+ if (PyOS_CheckStack()) {
+ PyErr_SetString(PyExc_MemoryError, "stack overflow");
+ return -1;
+ }
#endif
- clearerr(fp); /* Clear any previous error condition */
- if (op == NULL) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "<nil>");
- Py_END_ALLOW_THREADS
- }
- else {
- if (op->ob_refcnt <= 0)
- /* XXX(twouters) cast refcount to long until %zd is
- universally available */
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "<refcnt %ld at %p>",
- (long)op->ob_refcnt, op);
- Py_END_ALLOW_THREADS
- else if (Py_TYPE(op)->tp_print == NULL) {
- PyObject *s;
- if (flags & Py_PRINT_RAW)
- s = PyObject_Str(op);
- else
- s = PyObject_Repr(op);
- if (s == NULL)
- ret = -1;
- else {
- ret = internal_print(s, fp, Py_PRINT_RAW,
- nesting+1);
- }
- Py_XDECREF(s);
- }
- else
- ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
- }
- if (ret == 0) {
- if (ferror(fp)) {
- PyErr_SetFromErrno(PyExc_IOError);
- clearerr(fp);
- ret = -1;
- }
- }
- return ret;
+ clearerr(fp); /* Clear any previous error condition */
+ if (op == NULL) {
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "<nil>");
+ Py_END_ALLOW_THREADS
+ }
+ else {
+ if (op->ob_refcnt <= 0)
+ /* XXX(twouters) cast refcount to long until %zd is
+ universally available */
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "<refcnt %ld at %p>",
+ (long)op->ob_refcnt, op);
+ Py_END_ALLOW_THREADS
+ else if (Py_TYPE(op)->tp_print == NULL) {
+ PyObject *s;
+ if (flags & Py_PRINT_RAW)
+ s = PyObject_Str(op);
+ else
+ s = PyObject_Repr(op);
+ if (s == NULL)
+ ret = -1;
+ else {
+ ret = internal_print(s, fp, Py_PRINT_RAW,
+ nesting+1);
+ }
+ Py_XDECREF(s);
+ }
+ else
+ ret = (*Py_TYPE(op)->tp_print)(op, fp, flags);
+ }
+ if (ret == 0) {
+ if (ferror(fp)) {
+ PyErr_SetFromErrno(PyExc_IOError);
+ clearerr(fp);
+ ret = -1;
+ }
+ }
+ return ret;
}
int
PyObject_Print(PyObject *op, FILE *fp, int flags)
{
- return internal_print(op, fp, flags, 0);
+ return internal_print(op, fp, flags, 0);
}
/* For debugging convenience. See Misc/gdbinit for some useful gdb hooks */
void _PyObject_Dump(PyObject* op)
{
- if (op == NULL)
- fprintf(stderr, "NULL\n");
- else {
+ if (op == NULL)
+ fprintf(stderr, "NULL\n");
+ else {
#ifdef WITH_THREAD
- PyGILState_STATE gil;
+ PyGILState_STATE gil;
#endif
- fprintf(stderr, "object : ");
+ fprintf(stderr, "object : ");
#ifdef WITH_THREAD
- gil = PyGILState_Ensure();
+ gil = PyGILState_Ensure();
#endif
- (void)PyObject_Print(op, stderr, 0);
+ (void)PyObject_Print(op, stderr, 0);
#ifdef WITH_THREAD
- PyGILState_Release(gil);
+ PyGILState_Release(gil);
#endif
- /* XXX(twouters) cast refcount to long until %zd is
- universally available */
- fprintf(stderr, "\n"
- "type : %s\n"
- "refcount: %ld\n"
- "address : %p\n",
- Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
- (long)op->ob_refcnt,
- op);
- }
+ /* XXX(twouters) cast refcount to long until %zd is
+ universally available */
+ fprintf(stderr, "\n"
+ "type : %s\n"
+ "refcount: %ld\n"
+ "address : %p\n",
+ Py_TYPE(op)==NULL ? "NULL" : Py_TYPE(op)->tp_name,
+ (long)op->ob_refcnt,
+ op);
+ }
}
PyObject *
PyObject_Repr(PyObject *v)
{
- if (PyErr_CheckSignals())
- return NULL;
+ if (PyErr_CheckSignals())
+ return NULL;
#ifdef USE_STACKCHECK
- if (PyOS_CheckStack()) {
- PyErr_SetString(PyExc_MemoryError, "stack overflow");
- return NULL;
- }
+ if (PyOS_CheckStack()) {
+ PyErr_SetString(PyExc_MemoryError, "stack overflow");
+ return NULL;
+ }
#endif
- if (v == NULL)
- return PyString_FromString("<NULL>");
- else if (Py_TYPE(v)->tp_repr == NULL)
- return PyString_FromFormat("<%s object at %p>",
- Py_TYPE(v)->tp_name, v);
- else {
- PyObject *res;
- res = (*Py_TYPE(v)->tp_repr)(v);
- if (res == NULL)
- return NULL;
+ if (v == NULL)
+ return PyString_FromString("<NULL>");
+ else if (Py_TYPE(v)->tp_repr == NULL)
+ return PyString_FromFormat("<%s object at %p>",
+ Py_TYPE(v)->tp_name, v);
+ else {
+ PyObject *res;
+ res = (*Py_TYPE(v)->tp_repr)(v);
+ if (res == NULL)
+ return NULL;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(res)) {
- PyObject* str;
- str = PyUnicode_AsEncodedString(res, NULL, NULL);
- Py_DECREF(res);
- if (str)
- res = str;
- else
- return NULL;
- }
+ if (PyUnicode_Check(res)) {
+ PyObject* str;
+ str = PyUnicode_AsEncodedString(res, NULL, NULL);
+ Py_DECREF(res);
+ if (str)
+ res = str;
+ else
+ return NULL;
+ }
#endif
- if (!PyString_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "__repr__ returned non-string (type %.200s)",
- Py_TYPE(res)->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
- }
+ if (!PyString_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "__repr__ returned non-string (type %.200s)",
+ Py_TYPE(res)->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
+ }
}
PyObject *
_PyObject_Str(PyObject *v)
{
- PyObject *res;
- int type_ok;
- if (v == NULL)
- return PyString_FromString("<NULL>");
- if (PyString_CheckExact(v)) {
- Py_INCREF(v);
- return v;
- }
+ PyObject *res;
+ int type_ok;
+ if (v == NULL)
+ return PyString_FromString("<NULL>");
+ if (PyString_CheckExact(v)) {
+ Py_INCREF(v);
+ return v;
+ }
#ifdef Py_USING_UNICODE
- if (PyUnicode_CheckExact(v)) {
- Py_INCREF(v);
- return v;
- }
+ if (PyUnicode_CheckExact(v)) {
+ Py_INCREF(v);
+ return v;
+ }
#endif
- if (Py_TYPE(v)->tp_str == NULL)
- return PyObject_Repr(v);
-
- /* It is possible for a type to have a tp_str representation that loops
- infinitely. */
- if (Py_EnterRecursiveCall(" while getting the str of an object"))
- return NULL;
- res = (*Py_TYPE(v)->tp_str)(v);
- Py_LeaveRecursiveCall();
- if (res == NULL)
- return NULL;
- type_ok = PyString_Check(res);
+ if (Py_TYPE(v)->tp_str == NULL)
+ return PyObject_Repr(v);
+
+ /* It is possible for a type to have a tp_str representation that loops
+ infinitely. */
+ if (Py_EnterRecursiveCall(" while getting the str of an object"))
+ return NULL;
+ res = (*Py_TYPE(v)->tp_str)(v);
+ Py_LeaveRecursiveCall();
+ if (res == NULL)
+ return NULL;
+ type_ok = PyString_Check(res);
#ifdef Py_USING_UNICODE
- type_ok = type_ok || PyUnicode_Check(res);
+ type_ok = type_ok || PyUnicode_Check(res);
#endif
- if (!type_ok) {
- PyErr_Format(PyExc_TypeError,
- "__str__ returned non-string (type %.200s)",
- Py_TYPE(res)->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
+ if (!type_ok) {
+ PyErr_Format(PyExc_TypeError,
+ "__str__ returned non-string (type %.200s)",
+ Py_TYPE(res)->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
}
PyObject *
PyObject_Str(PyObject *v)
{
- PyObject *res = _PyObject_Str(v);
- if (res == NULL)
- return NULL;
+ PyObject *res = _PyObject_Str(v);
+ if (res == NULL)
+ return NULL;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(res)) {
- PyObject* str;
- str = PyUnicode_AsEncodedString(res, NULL, NULL);
- Py_DECREF(res);
- if (str)
- res = str;
- else
- return NULL;
- }
+ if (PyUnicode_Check(res)) {
+ PyObject* str;
+ str = PyUnicode_AsEncodedString(res, NULL, NULL);
+ Py_DECREF(res);
+ if (str)
+ res = str;
+ else
+ return NULL;
+ }
#endif
- assert(PyString_Check(res));
- return res;
+ assert(PyString_Check(res));
+ return res;
}
#ifdef Py_USING_UNICODE
PyObject *
PyObject_Unicode(PyObject *v)
{
- PyObject *res;
- PyObject *func;
- PyObject *str;
- int unicode_method_found = 0;
- static PyObject *unicodestr;
-
- if (v == NULL) {
- res = PyString_FromString("<NULL>");
- if (res == NULL)
- return NULL;
- str = PyUnicode_FromEncodedObject(res, NULL, "strict");
- Py_DECREF(res);
- return str;
- } else if (PyUnicode_CheckExact(v)) {
- Py_INCREF(v);
- return v;
- }
-
- if (PyInstance_Check(v)) {
- /* We're an instance of a classic class */
- /* Try __unicode__ from the instance -- alas we have no type */
- func = PyObject_GetAttr(v, unicodestr);
- if (func != NULL) {
- unicode_method_found = 1;
- res = PyObject_CallFunctionObjArgs(func, NULL);
- Py_DECREF(func);
- }
- else {
- PyErr_Clear();
- }
- }
- else {
- /* Not a classic class instance, try __unicode__. */
- func = _PyObject_LookupSpecial(v, "__unicode__", &unicodestr);
- if (func != NULL) {
- unicode_method_found = 1;
- res = PyObject_CallFunctionObjArgs(func, NULL);
- Py_DECREF(func);
- }
- else if (PyErr_Occurred())
- return NULL;
- }
-
- /* Didn't find __unicode__ */
- if (!unicode_method_found) {
- if (PyUnicode_Check(v)) {
- /* For a Unicode subtype that's didn't overwrite __unicode__,
- return a true Unicode object with the same data. */
- return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
- PyUnicode_GET_SIZE(v));
- }
- if (PyString_CheckExact(v)) {
- Py_INCREF(v);
- res = v;
- }
- else {
- if (Py_TYPE(v)->tp_str != NULL)
- res = (*Py_TYPE(v)->tp_str)(v);
- else
- res = PyObject_Repr(v);
- }
- }
-
- if (res == NULL)
- return NULL;
- if (!PyUnicode_Check(res)) {
- str = PyUnicode_FromEncodedObject(res, NULL, "strict");
- Py_DECREF(res);
- res = str;
- }
- return res;
+ PyObject *res;
+ PyObject *func;
+ PyObject *str;
+ int unicode_method_found = 0;
+ static PyObject *unicodestr;
+
+ if (v == NULL) {
+ res = PyString_FromString("<NULL>");
+ if (res == NULL)
+ return NULL;
+ str = PyUnicode_FromEncodedObject(res, NULL, "strict");
+ Py_DECREF(res);
+ return str;
+ } else if (PyUnicode_CheckExact(v)) {
+ Py_INCREF(v);
+ return v;
+ }
+
+ if (PyInstance_Check(v)) {
+ /* We're an instance of a classic class */
+ /* Try __unicode__ from the instance -- alas we have no type */
+ func = PyObject_GetAttr(v, unicodestr);
+ if (func != NULL) {
+ unicode_method_found = 1;
+ res = PyObject_CallFunctionObjArgs(func, NULL);
+ Py_DECREF(func);
+ }
+ else {
+ PyErr_Clear();
+ }
+ }
+ else {
+ /* Not a classic class instance, try __unicode__. */
+ func = _PyObject_LookupSpecial(v, "__unicode__", &unicodestr);
+ if (func != NULL) {
+ unicode_method_found = 1;
+ res = PyObject_CallFunctionObjArgs(func, NULL);
+ Py_DECREF(func);
+ }
+ else if (PyErr_Occurred())
+ return NULL;
+ }
+
+ /* Didn't find __unicode__ */
+ if (!unicode_method_found) {
+ if (PyUnicode_Check(v)) {
+ /* For a Unicode subtype that's didn't overwrite __unicode__,
+ return a true Unicode object with the same data. */
+ return PyUnicode_FromUnicode(PyUnicode_AS_UNICODE(v),
+ PyUnicode_GET_SIZE(v));
+ }
+ if (PyString_CheckExact(v)) {
+ Py_INCREF(v);
+ res = v;
+ }
+ else {
+ if (Py_TYPE(v)->tp_str != NULL)
+ res = (*Py_TYPE(v)->tp_str)(v);
+ else
+ res = PyObject_Repr(v);
+ }
+ }
+
+ if (res == NULL)
+ return NULL;
+ if (!PyUnicode_Check(res)) {
+ str = PyUnicode_FromEncodedObject(res, NULL, "strict");
+ Py_DECREF(res);
+ res = str;
+ }
+ return res;
}
#endif
@@ -555,39 +555,39 @@ PyObject_Unicode(PyObject *v)
static int
adjust_tp_compare(int c)
{
- if (PyErr_Occurred()) {
- if (c != -1 && c != -2) {
- PyObject *t, *v, *tb;
- PyErr_Fetch(&t, &v, &tb);
- if (PyErr_Warn(PyExc_RuntimeWarning,
- "tp_compare didn't return -1 or -2 "
- "for exception") < 0) {
- Py_XDECREF(t);
- Py_XDECREF(v);
- Py_XDECREF(tb);
- }
- else
- PyErr_Restore(t, v, tb);
- }
- return -2;
- }
- else if (c < -1 || c > 1) {
- if (PyErr_Warn(PyExc_RuntimeWarning,
- "tp_compare didn't return -1, 0 or 1") < 0)
- return -2;
- else
- return c < -1 ? -1 : 1;
- }
- else {
- assert(c >= -1 && c <= 1);
- return c;
- }
+ if (PyErr_Occurred()) {
+ if (c != -1 && c != -2) {
+ PyObject *t, *v, *tb;
+ PyErr_Fetch(&t, &v, &tb);
+ if (PyErr_Warn(PyExc_RuntimeWarning,
+ "tp_compare didn't return -1 or -2 "
+ "for exception") < 0) {
+ Py_XDECREF(t);
+ Py_XDECREF(v);
+ Py_XDECREF(tb);
+ }
+ else
+ PyErr_Restore(t, v, tb);
+ }
+ return -2;
+ }
+ else if (c < -1 || c > 1) {
+ if (PyErr_Warn(PyExc_RuntimeWarning,
+ "tp_compare didn't return -1, 0 or 1") < 0)
+ return -2;
+ else
+ return c < -1 ? -1 : 1;
+ }
+ else {
+ assert(c >= -1 && c <= 1);
+ return c;
+ }
}
/* Macro to get the tp_richcompare field of a type if defined */
#define RICHCOMPARE(t) (PyType_HasFeature((t), Py_TPFLAGS_HAVE_RICHCOMPARE) \
- ? (t)->tp_richcompare : NULL)
+ ? (t)->tp_richcompare : NULL)
/* Map rich comparison operators to their swapped version, e.g. LT --> GT */
int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
@@ -602,29 +602,29 @@ int _Py_SwappedOp[] = {Py_GT, Py_GE, Py_EQ, Py_NE, Py_LT, Py_LE};
static PyObject *
try_rich_compare(PyObject *v, PyObject *w, int op)
{
- richcmpfunc f;
- PyObject *res;
-
- if (v->ob_type != w->ob_type &&
- PyType_IsSubtype(w->ob_type, v->ob_type) &&
- (f = RICHCOMPARE(w->ob_type)) != NULL) {
- res = (*f)(w, v, _Py_SwappedOp[op]);
- if (res != Py_NotImplemented)
- return res;
- Py_DECREF(res);
- }
- if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
- res = (*f)(v, w, op);
- if (res != Py_NotImplemented)
- return res;
- Py_DECREF(res);
- }
- if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
- return (*f)(w, v, _Py_SwappedOp[op]);
- }
- res = Py_NotImplemented;
- Py_INCREF(res);
- return res;
+ richcmpfunc f;
+ PyObject *res;
+
+ if (v->ob_type != w->ob_type &&
+ PyType_IsSubtype(w->ob_type, v->ob_type) &&
+ (f = RICHCOMPARE(w->ob_type)) != NULL) {
+ res = (*f)(w, v, _Py_SwappedOp[op]);
+ if (res != Py_NotImplemented)
+ return res;
+ Py_DECREF(res);
+ }
+ if ((f = RICHCOMPARE(v->ob_type)) != NULL) {
+ res = (*f)(v, w, op);
+ if (res != Py_NotImplemented)
+ return res;
+ Py_DECREF(res);
+ }
+ if ((f = RICHCOMPARE(w->ob_type)) != NULL) {
+ return (*f)(w, v, _Py_SwappedOp[op]);
+ }
+ res = Py_NotImplemented;
+ Py_INCREF(res);
+ return res;
}
/* Try a genuine rich comparison, returning an int. Return:
@@ -637,21 +637,21 @@ try_rich_compare(PyObject *v, PyObject *w, int op)
static int
try_rich_compare_bool(PyObject *v, PyObject *w, int op)
{
- PyObject *res;
- int ok;
+ PyObject *res;
+ int ok;
- if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
- return 2; /* Shortcut, avoid INCREF+DECREF */
- res = try_rich_compare(v, w, op);
- if (res == NULL)
- return -1;
- if (res == Py_NotImplemented) {
- Py_DECREF(res);
- return 2;
- }
- ok = PyObject_IsTrue(res);
- Py_DECREF(res);
- return ok;
+ if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
+ return 2; /* Shortcut, avoid INCREF+DECREF */
+ res = try_rich_compare(v, w, op);
+ if (res == NULL)
+ return -1;
+ if (res == Py_NotImplemented) {
+ Py_DECREF(res);
+ return 2;
+ }
+ ok = PyObject_IsTrue(res);
+ Py_DECREF(res);
+ return ok;
}
/* Try rich comparisons to determine a 3-way comparison. Return:
@@ -664,27 +664,27 @@ try_rich_compare_bool(PyObject *v, PyObject *w, int op)
static int
try_rich_to_3way_compare(PyObject *v, PyObject *w)
{
- static struct { int op; int outcome; } tries[3] = {
- /* Try this operator, and if it is true, use this outcome: */
- {Py_EQ, 0},
- {Py_LT, -1},
- {Py_GT, 1},
- };
- int i;
+ static struct { int op; int outcome; } tries[3] = {
+ /* Try this operator, and if it is true, use this outcome: */
+ {Py_EQ, 0},
+ {Py_LT, -1},
+ {Py_GT, 1},
+ };
+ int i;
- if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
- return 2; /* Shortcut */
+ if (RICHCOMPARE(v->ob_type) == NULL && RICHCOMPARE(w->ob_type) == NULL)
+ return 2; /* Shortcut */
- for (i = 0; i < 3; i++) {
- switch (try_rich_compare_bool(v, w, tries[i].op)) {
- case -1:
- return -2;
- case 1:
- return tries[i].outcome;
- }
- }
+ for (i = 0; i < 3; i++) {
+ switch (try_rich_compare_bool(v, w, tries[i].op)) {
+ case -1:
+ return -2;
+ case 1:
+ return tries[i].outcome;
+ }
+ }
- return 2;
+ return 2;
}
/* Try a 3-way comparison, returning an int. Return:
@@ -697,55 +697,55 @@ try_rich_to_3way_compare(PyObject *v, PyObject *w)
static int
try_3way_compare(PyObject *v, PyObject *w)
{
- int c;
- cmpfunc f;
-
- /* Comparisons involving instances are given to instance_compare,
- which has the same return conventions as this function. */
-
- f = v->ob_type->tp_compare;
- if (PyInstance_Check(v))
- return (*f)(v, w);
- if (PyInstance_Check(w))
- return (*w->ob_type->tp_compare)(v, w);
-
- /* If both have the same (non-NULL) tp_compare, use it. */
- if (f != NULL && f == w->ob_type->tp_compare) {
- c = (*f)(v, w);
- return adjust_tp_compare(c);
- }
-
- /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
- if (f == _PyObject_SlotCompare ||
- w->ob_type->tp_compare == _PyObject_SlotCompare)
- return _PyObject_SlotCompare(v, w);
-
- /* If we're here, v and w,
- a) are not instances;
- b) have different types or a type without tp_compare; and
- c) don't have a user-defined tp_compare.
- tp_compare implementations in C assume that both arguments
- have their type, so we give up if the coercion fails or if
- it yields types which are still incompatible (which can
- happen with a user-defined nb_coerce).
- */
- c = PyNumber_CoerceEx(&v, &w);
- if (c < 0)
- return -2;
- if (c > 0)
- return 2;
- f = v->ob_type->tp_compare;
- if (f != NULL && f == w->ob_type->tp_compare) {
- c = (*f)(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- return adjust_tp_compare(c);
- }
-
- /* No comparison defined */
- Py_DECREF(v);
- Py_DECREF(w);
- return 2;
+ int c;
+ cmpfunc f;
+
+ /* Comparisons involving instances are given to instance_compare,
+ which has the same return conventions as this function. */
+
+ f = v->ob_type->tp_compare;
+ if (PyInstance_Check(v))
+ return (*f)(v, w);
+ if (PyInstance_Check(w))
+ return (*w->ob_type->tp_compare)(v, w);
+
+ /* If both have the same (non-NULL) tp_compare, use it. */
+ if (f != NULL && f == w->ob_type->tp_compare) {
+ c = (*f)(v, w);
+ return adjust_tp_compare(c);
+ }
+
+ /* If either tp_compare is _PyObject_SlotCompare, that's safe. */
+ if (f == _PyObject_SlotCompare ||
+ w->ob_type->tp_compare == _PyObject_SlotCompare)
+ return _PyObject_SlotCompare(v, w);
+
+ /* If we're here, v and w,
+ a) are not instances;
+ b) have different types or a type without tp_compare; and
+ c) don't have a user-defined tp_compare.
+ tp_compare implementations in C assume that both arguments
+ have their type, so we give up if the coercion fails or if
+ it yields types which are still incompatible (which can
+ happen with a user-defined nb_coerce).
+ */
+ c = PyNumber_CoerceEx(&v, &w);
+ if (c < 0)
+ return -2;
+ if (c > 0)
+ return 2;
+ f = v->ob_type->tp_compare;
+ if (f != NULL && f == w->ob_type->tp_compare) {
+ c = (*f)(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ return adjust_tp_compare(c);
+ }
+
+ /* No comparison defined */
+ Py_DECREF(v);
+ Py_DECREF(w);
+ return 2;
}
/* Final fallback 3-way comparison, returning an int. Return:
@@ -757,43 +757,43 @@ try_3way_compare(PyObject *v, PyObject *w)
static int
default_3way_compare(PyObject *v, PyObject *w)
{
- int c;
- const char *vname, *wname;
-
- if (v->ob_type == w->ob_type) {
- /* When comparing these pointers, they must be cast to
- * integer types (i.e. Py_uintptr_t, our spelling of C9X's
- * uintptr_t). ANSI specifies that pointer compares other
- * than == and != to non-related structures are undefined.
- */
- Py_uintptr_t vv = (Py_uintptr_t)v;
- Py_uintptr_t ww = (Py_uintptr_t)w;
- return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
- }
-
- /* None is smaller than anything */
- if (v == Py_None)
- return -1;
- if (w == Py_None)
- return 1;
-
- /* different type: compare type names; numbers are smaller */
- if (PyNumber_Check(v))
- vname = "";
- else
- vname = v->ob_type->tp_name;
- if (PyNumber_Check(w))
- wname = "";
- else
- wname = w->ob_type->tp_name;
- c = strcmp(vname, wname);
- if (c < 0)
- return -1;
- if (c > 0)
- return 1;
- /* Same type name, or (more likely) incomparable numeric types */
- return ((Py_uintptr_t)(v->ob_type) < (
- Py_uintptr_t)(w->ob_type)) ? -1 : 1;
+ int c;
+ const char *vname, *wname;
+
+ if (v->ob_type == w->ob_type) {
+ /* When comparing these pointers, they must be cast to
+ * integer types (i.e. Py_uintptr_t, our spelling of C9X's
+ * uintptr_t). ANSI specifies that pointer compares other
+ * than == and != to non-related structures are undefined.
+ */
+ Py_uintptr_t vv = (Py_uintptr_t)v;
+ Py_uintptr_t ww = (Py_uintptr_t)w;
+ return (vv < ww) ? -1 : (vv > ww) ? 1 : 0;
+ }
+
+ /* None is smaller than anything */
+ if (v == Py_None)
+ return -1;
+ if (w == Py_None)
+ return 1;
+
+ /* different type: compare type names; numbers are smaller */
+ if (PyNumber_Check(v))
+ vname = "";
+ else
+ vname = v->ob_type->tp_name;
+ if (PyNumber_Check(w))
+ wname = "";
+ else
+ wname = w->ob_type->tp_name;
+ c = strcmp(vname, wname);
+ if (c < 0)
+ return -1;
+ if (c > 0)
+ return 1;
+ /* Same type name, or (more likely) incomparable numeric types */
+ return ((Py_uintptr_t)(v->ob_type) < (
+ Py_uintptr_t)(w->ob_type)) ? -1 : 1;
}
/* Do a 3-way comparison, by hook or by crook. Return:
@@ -807,35 +807,35 @@ default_3way_compare(PyObject *v, PyObject *w)
static int
do_cmp(PyObject *v, PyObject *w)
{
- int c;
- cmpfunc f;
-
- if (v->ob_type == w->ob_type
- && (f = v->ob_type->tp_compare) != NULL) {
- c = (*f)(v, w);
- if (PyInstance_Check(v)) {
- /* Instance tp_compare has a different signature.
- But if it returns undefined we fall through. */
- if (c != 2)
- return c;
- /* Else fall through to try_rich_to_3way_compare() */
- }
- else
- return adjust_tp_compare(c);
- }
- /* We only get here if one of the following is true:
- a) v and w have different types
- b) v and w have the same type, which doesn't have tp_compare
- c) v and w are instances, and either __cmp__ is not defined or
- __cmp__ returns NotImplemented
- */
- c = try_rich_to_3way_compare(v, w);
- if (c < 2)
- return c;
- c = try_3way_compare(v, w);
- if (c < 2)
- return c;
- return default_3way_compare(v, w);
+ int c;
+ cmpfunc f;
+
+ if (v->ob_type == w->ob_type
+ && (f = v->ob_type->tp_compare) != NULL) {
+ c = (*f)(v, w);
+ if (PyInstance_Check(v)) {
+ /* Instance tp_compare has a different signature.
+ But if it returns undefined we fall through. */
+ if (c != 2)
+ return c;
+ /* Else fall through to try_rich_to_3way_compare() */
+ }
+ else
+ return adjust_tp_compare(c);
+ }
+ /* We only get here if one of the following is true:
+ a) v and w have different types
+ b) v and w have the same type, which doesn't have tp_compare
+ c) v and w are instances, and either __cmp__ is not defined or
+ __cmp__ returns NotImplemented
+ */
+ c = try_rich_to_3way_compare(v, w);
+ if (c < 2)
+ return c;
+ c = try_3way_compare(v, w);
+ if (c < 2)
+ return c;
+ return default_3way_compare(v, w);
}
/* Compare v to w. Return
@@ -848,37 +848,37 @@ do_cmp(PyObject *v, PyObject *w)
int
PyObject_Compare(PyObject *v, PyObject *w)
{
- int result;
+ int result;
- if (v == NULL || w == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (v == w)
- return 0;
- if (Py_EnterRecursiveCall(" in cmp"))
- return -1;
- result = do_cmp(v, w);
- Py_LeaveRecursiveCall();
- return result < 0 ? -1 : result;
+ if (v == NULL || w == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (v == w)
+ return 0;
+ if (Py_EnterRecursiveCall(" in cmp"))
+ return -1;
+ result = do_cmp(v, w);
+ Py_LeaveRecursiveCall();
+ return result < 0 ? -1 : result;
}
/* Return (new reference to) Py_True or Py_False. */
static PyObject *
convert_3way_to_object(int op, int c)
{
- PyObject *result;
- switch (op) {
- case Py_LT: c = c < 0; break;
- case Py_LE: c = c <= 0; break;
- case Py_EQ: c = c == 0; break;
- case Py_NE: c = c != 0; break;
- case Py_GT: c = c > 0; break;
- case Py_GE: c = c >= 0; break;
- }
- result = c ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
+ PyObject *result;
+ switch (op) {
+ case Py_LT: c = c < 0; break;
+ case Py_LE: c = c <= 0; break;
+ case Py_EQ: c = c == 0; break;
+ case Py_NE: c = c != 0; break;
+ case Py_GT: c = c > 0; break;
+ case Py_GE: c = c >= 0; break;
+ }
+ result = c ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
}
/* We want a rich comparison but don't have one. Try a 3-way cmp instead.
@@ -890,25 +890,25 @@ convert_3way_to_object(int op, int c)
static PyObject *
try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
{
- int c;
+ int c;
- c = try_3way_compare(v, w);
- if (c >= 2) {
+ c = try_3way_compare(v, w);
+ if (c >= 2) {
- /* Py3K warning if types are not equal and comparison isn't == or != */
- if (Py_Py3kWarningFlag &&
- v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
- PyErr_WarnEx(PyExc_DeprecationWarning,
- "comparing unequal types not supported "
- "in 3.x", 1) < 0) {
- return NULL;
- }
+ /* Py3K warning if types are not equal and comparison isn't == or != */
+ if (Py_Py3kWarningFlag &&
+ v->ob_type != w->ob_type && op != Py_EQ && op != Py_NE &&
+ PyErr_WarnEx(PyExc_DeprecationWarning,
+ "comparing unequal types not supported "
+ "in 3.x", 1) < 0) {
+ return NULL;
+ }
- c = default_3way_compare(v, w);
- }
- if (c <= -2)
- return NULL;
- return convert_3way_to_object(op, c);
+ c = default_3way_compare(v, w);
+ }
+ if (c <= -2)
+ return NULL;
+ return convert_3way_to_object(op, c);
}
/* Do rich comparison on v and w. Return
@@ -920,14 +920,14 @@ try_3way_to_rich_compare(PyObject *v, PyObject *w, int op)
static PyObject *
do_richcmp(PyObject *v, PyObject *w, int op)
{
- PyObject *res;
+ PyObject *res;
- res = try_rich_compare(v, w, op);
- if (res != Py_NotImplemented)
- return res;
- Py_DECREF(res);
+ res = try_rich_compare(v, w, op);
+ if (res != Py_NotImplemented)
+ return res;
+ Py_DECREF(res);
- return try_3way_to_rich_compare(v, w, op);
+ return try_3way_to_rich_compare(v, w, op);
}
/* Return:
@@ -938,77 +938,77 @@ do_richcmp(PyObject *v, PyObject *w, int op)
PyObject *
PyObject_RichCompare(PyObject *v, PyObject *w, int op)
{
- PyObject *res;
-
- assert(Py_LT <= op && op <= Py_GE);
- if (Py_EnterRecursiveCall(" in cmp"))
- return NULL;
-
- /* If the types are equal, and not old-style instances, try to
- get out cheap (don't bother with coercions etc.). */
- if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
- cmpfunc fcmp;
- richcmpfunc frich = RICHCOMPARE(v->ob_type);
- /* If the type has richcmp, try it first. try_rich_compare
- tries it two-sided, which is not needed since we've a
- single type only. */
- if (frich != NULL) {
- res = (*frich)(v, w, op);
- if (res != Py_NotImplemented)
- goto Done;
- Py_DECREF(res);
- }
- /* No richcmp, or this particular richmp not implemented.
- Try 3-way cmp. */
- fcmp = v->ob_type->tp_compare;
- if (fcmp != NULL) {
- int c = (*fcmp)(v, w);
- c = adjust_tp_compare(c);
- if (c == -2) {
- res = NULL;
- goto Done;
- }
- res = convert_3way_to_object(op, c);
- goto Done;
- }
- }
-
- /* Fast path not taken, or couldn't deliver a useful result. */
- res = do_richcmp(v, w, op);
+ PyObject *res;
+
+ assert(Py_LT <= op && op <= Py_GE);
+ if (Py_EnterRecursiveCall(" in cmp"))
+ return NULL;
+
+ /* If the types are equal, and not old-style instances, try to
+ get out cheap (don't bother with coercions etc.). */
+ if (v->ob_type == w->ob_type && !PyInstance_Check(v)) {
+ cmpfunc fcmp;
+ richcmpfunc frich = RICHCOMPARE(v->ob_type);
+ /* If the type has richcmp, try it first. try_rich_compare
+ tries it two-sided, which is not needed since we've a
+ single type only. */
+ if (frich != NULL) {
+ res = (*frich)(v, w, op);
+ if (res != Py_NotImplemented)
+ goto Done;
+ Py_DECREF(res);
+ }
+ /* No richcmp, or this particular richmp not implemented.
+ Try 3-way cmp. */
+ fcmp = v->ob_type->tp_compare;
+ if (fcmp != NULL) {
+ int c = (*fcmp)(v, w);
+ c = adjust_tp_compare(c);
+ if (c == -2) {
+ res = NULL;
+ goto Done;
+ }
+ res = convert_3way_to_object(op, c);
+ goto Done;
+ }
+ }
+
+ /* Fast path not taken, or couldn't deliver a useful result. */
+ res = do_richcmp(v, w, op);
Done:
- Py_LeaveRecursiveCall();
- return res;
+ Py_LeaveRecursiveCall();
+ return res;
}
/* Return -1 if error; 1 if v op w; 0 if not (v op w). */
int
PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
{
- PyObject *res;
- int ok;
-
- /* Quick result when objects are the same.
- Guarantees that identity implies equality. */
- if (v == w) {
- if (op == Py_EQ)
- return 1;
- else if (op == Py_NE)
- return 0;
- }
-
- res = PyObject_RichCompare(v, w, op);
- if (res == NULL)
- return -1;
- if (PyBool_Check(res))
- ok = (res == Py_True);
- else
- ok = PyObject_IsTrue(res);
- Py_DECREF(res);
- return ok;
+ PyObject *res;
+ int ok;
+
+ /* Quick result when objects are the same.
+ Guarantees that identity implies equality. */
+ if (v == w) {
+ if (op == Py_EQ)
+ return 1;
+ else if (op == Py_NE)
+ return 0;
+ }
+
+ res = PyObject_RichCompare(v, w, op);
+ if (res == NULL)
+ return -1;
+ if (PyBool_Check(res))
+ ok = (res == Py_True);
+ else
+ ok = PyObject_IsTrue(res);
+ Py_DECREF(res);
+ return ok;
}
/* Set of hash utility functions to help maintaining the invariant that
- if a==b then hash(a)==hash(b)
+ if a==b then hash(a)==hash(b)
All the utility functions (_Py_Hash*()) return "-1" to signify an error.
*/
@@ -1016,252 +1016,252 @@ PyObject_RichCompareBool(PyObject *v, PyObject *w, int op)
long
_Py_HashDouble(double v)
{
- double intpart, fractpart;
- int expo;
- long hipart;
- long x; /* the final hash value */
- /* This is designed so that Python numbers of different types
- * that compare equal hash to the same value; otherwise comparisons
- * of mapping keys will turn out weird.
- */
-
- if (!Py_IS_FINITE(v)) {
- if (Py_IS_INFINITY(v))
- return v < 0 ? -271828 : 314159;
- else
- return 0;
- }
- fractpart = modf(v, &intpart);
- if (fractpart == 0.0) {
- /* This must return the same hash as an equal int or long. */
- if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
- /* Convert to long and use its hash. */
- PyObject *plong; /* converted to Python long */
- plong = PyLong_FromDouble(v);
- if (plong == NULL)
- return -1;
- x = PyObject_Hash(plong);
- Py_DECREF(plong);
- return x;
- }
- /* Fits in a C long == a Python int, so is its own hash. */
- x = (long)intpart;
- if (x == -1)
- x = -2;
- return x;
- }
- /* The fractional part is non-zero, so we don't have to worry about
- * making this match the hash of some other type.
- * Use frexp to get at the bits in the double.
- * Since the VAX D double format has 56 mantissa bits, which is the
- * most of any double format in use, each of these parts may have as
- * many as (but no more than) 56 significant bits.
- * So, assuming sizeof(long) >= 4, each part can be broken into two
- * longs; frexp and multiplication are used to do that.
- * Also, since the Cray double format has 15 exponent bits, which is
- * the most of any double format in use, shifting the exponent field
- * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
- */
- v = frexp(v, &expo);
- v *= 2147483648.0; /* 2**31 */
- hipart = (long)v; /* take the top 32 bits */
- v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
- x = hipart + (long)v + (expo << 15);
- if (x == -1)
- x = -2;
- return x;
+ double intpart, fractpart;
+ int expo;
+ long hipart;
+ long x; /* the final hash value */
+ /* This is designed so that Python numbers of different types
+ * that compare equal hash to the same value; otherwise comparisons
+ * of mapping keys will turn out weird.
+ */
+
+ if (!Py_IS_FINITE(v)) {
+ if (Py_IS_INFINITY(v))
+ return v < 0 ? -271828 : 314159;
+ else
+ return 0;
+ }
+ fractpart = modf(v, &intpart);
+ if (fractpart == 0.0) {
+ /* This must return the same hash as an equal int or long. */
+ if (intpart > LONG_MAX/2 || -intpart > LONG_MAX/2) {
+ /* Convert to long and use its hash. */
+ PyObject *plong; /* converted to Python long */
+ plong = PyLong_FromDouble(v);
+ if (plong == NULL)
+ return -1;
+ x = PyObject_Hash(plong);
+ Py_DECREF(plong);
+ return x;
+ }
+ /* Fits in a C long == a Python int, so is its own hash. */
+ x = (long)intpart;
+ if (x == -1)
+ x = -2;
+ return x;
+ }
+ /* The fractional part is non-zero, so we don't have to worry about
+ * making this match the hash of some other type.
+ * Use frexp to get at the bits in the double.
+ * Since the VAX D double format has 56 mantissa bits, which is the
+ * most of any double format in use, each of these parts may have as
+ * many as (but no more than) 56 significant bits.
+ * So, assuming sizeof(long) >= 4, each part can be broken into two
+ * longs; frexp and multiplication are used to do that.
+ * Also, since the Cray double format has 15 exponent bits, which is
+ * the most of any double format in use, shifting the exponent field
+ * left by 15 won't overflow a long (again assuming sizeof(long) >= 4).
+ */
+ v = frexp(v, &expo);
+ v *= 2147483648.0; /* 2**31 */
+ hipart = (long)v; /* take the top 32 bits */
+ v = (v - (double)hipart) * 2147483648.0; /* get the next 32 bits */
+ x = hipart + (long)v + (expo << 15);
+ if (x == -1)
+ x = -2;
+ return x;
}
long
_Py_HashPointer(void *p)
{
- long x;
- size_t y = (size_t)p;
- /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
- excessive hash collisions for dicts and sets */
- y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
- x = (long)y;
- if (x == -1)
- x = -2;
- return x;
+ long x;
+ size_t y = (size_t)p;
+ /* bottom 3 or 4 bits are likely to be 0; rotate y by 4 to avoid
+ excessive hash collisions for dicts and sets */
+ y = (y >> 4) | (y << (8 * SIZEOF_VOID_P - 4));
+ x = (long)y;
+ if (x == -1)
+ x = -2;
+ return x;
}
long
PyObject_HashNotImplemented(PyObject *self)
{
- PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
- self->ob_type->tp_name);
- return -1;
+ PyErr_Format(PyExc_TypeError, "unhashable type: '%.200s'",
+ self->ob_type->tp_name);
+ return -1;
}
long
PyObject_Hash(PyObject *v)
{
- PyTypeObject *tp = v->ob_type;
- if (tp->tp_hash != NULL)
- return (*tp->tp_hash)(v);
- /* To keep to the general practice that inheriting
- * solely from object in C code should work without
- * an explicit call to PyType_Ready, we implicitly call
- * PyType_Ready here and then check the tp_hash slot again
- */
- if (tp->tp_dict == NULL) {
- if (PyType_Ready(tp) < 0)
- return -1;
- if (tp->tp_hash != NULL)
- return (*tp->tp_hash)(v);
- }
- if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
- return _Py_HashPointer(v); /* Use address as hash value */
- }
- /* If there's a cmp but no hash defined, the object can't be hashed */
- return PyObject_HashNotImplemented(v);
+ PyTypeObject *tp = v->ob_type;
+ if (tp->tp_hash != NULL)
+ return (*tp->tp_hash)(v);
+ /* To keep to the general practice that inheriting
+ * solely from object in C code should work without
+ * an explicit call to PyType_Ready, we implicitly call
+ * PyType_Ready here and then check the tp_hash slot again
+ */
+ if (tp->tp_dict == NULL) {
+ if (PyType_Ready(tp) < 0)
+ return -1;
+ if (tp->tp_hash != NULL)
+ return (*tp->tp_hash)(v);
+ }
+ if (tp->tp_compare == NULL && RICHCOMPARE(tp) == NULL) {
+ return _Py_HashPointer(v); /* Use address as hash value */
+ }
+ /* If there's a cmp but no hash defined, the object can't be hashed */
+ return PyObject_HashNotImplemented(v);
}
PyObject *
PyObject_GetAttrString(PyObject *v, const char *name)
{
- PyObject *w, *res;
+ PyObject *w, *res;
- if (Py_TYPE(v)->tp_getattr != NULL)
- return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
- w = PyString_InternFromString(name);
- if (w == NULL)
- return NULL;
- res = PyObject_GetAttr(v, w);
- Py_XDECREF(w);
- return res;
+ if (Py_TYPE(v)->tp_getattr != NULL)
+ return (*Py_TYPE(v)->tp_getattr)(v, (char*)name);
+ w = PyString_InternFromString(name);
+ if (w == NULL)
+ return NULL;
+ res = PyObject_GetAttr(v, w);
+ Py_XDECREF(w);
+ return res;
}
int
PyObject_HasAttrString(PyObject *v, const char *name)
{
- PyObject *res = PyObject_GetAttrString(v, name);
- if (res != NULL) {
- Py_DECREF(res);
- return 1;
- }
- PyErr_Clear();
- return 0;
+ PyObject *res = PyObject_GetAttrString(v, name);
+ if (res != NULL) {
+ Py_DECREF(res);
+ return 1;
+ }
+ PyErr_Clear();
+ return 0;
}
int
PyObject_SetAttrString(PyObject *v, const char *name, PyObject *w)
{
- PyObject *s;
- int res;
+ PyObject *s;
+ int res;
- if (Py_TYPE(v)->tp_setattr != NULL)
- return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
- s = PyString_InternFromString(name);
- if (s == NULL)
- return -1;
- res = PyObject_SetAttr(v, s, w);
- Py_XDECREF(s);
- return res;
+ if (Py_TYPE(v)->tp_setattr != NULL)
+ return (*Py_TYPE(v)->tp_setattr)(v, (char*)name, w);
+ s = PyString_InternFromString(name);
+ if (s == NULL)
+ return -1;
+ res = PyObject_SetAttr(v, s, w);
+ Py_XDECREF(s);
+ return res;
}
PyObject *
PyObject_GetAttr(PyObject *v, PyObject *name)
{
- PyTypeObject *tp = Py_TYPE(v);
+ PyTypeObject *tp = Py_TYPE(v);
- if (!PyString_Check(name)) {
+ if (!PyString_Check(name)) {
#ifdef Py_USING_UNICODE
- /* The Unicode to string conversion is done here because the
- existing tp_getattro slots expect a string object as name
- and we wouldn't want to break those. */
- if (PyUnicode_Check(name)) {
- name = _PyUnicode_AsDefaultEncodedString(name, NULL);
- if (name == NULL)
- return NULL;
- }
- else
+ /* The Unicode to string conversion is done here because the
+ existing tp_getattro slots expect a string object as name
+ and we wouldn't want to break those. */
+ if (PyUnicode_Check(name)) {
+ name = _PyUnicode_AsDefaultEncodedString(name, NULL);
+ if (name == NULL)
+ return NULL;
+ }
+ else
#endif
- {
- PyErr_Format(PyExc_TypeError,
- "attribute name must be string, not '%.200s'",
- Py_TYPE(name)->tp_name);
- return NULL;
- }
- }
- if (tp->tp_getattro != NULL)
- return (*tp->tp_getattro)(v, name);
- if (tp->tp_getattr != NULL)
- return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
- PyErr_Format(PyExc_AttributeError,
- "'%.50s' object has no attribute '%.400s'",
- tp->tp_name, PyString_AS_STRING(name));
- return NULL;
+ {
+ PyErr_Format(PyExc_TypeError,
+ "attribute name must be string, not '%.200s'",
+ Py_TYPE(name)->tp_name);
+ return NULL;
+ }
+ }
+ if (tp->tp_getattro != NULL)
+ return (*tp->tp_getattro)(v, name);
+ if (tp->tp_getattr != NULL)
+ return (*tp->tp_getattr)(v, PyString_AS_STRING(name));
+ PyErr_Format(PyExc_AttributeError,
+ "'%.50s' object has no attribute '%.400s'",
+ tp->tp_name, PyString_AS_STRING(name));
+ return NULL;
}
int
PyObject_HasAttr(PyObject *v, PyObject *name)
{
- PyObject *res = PyObject_GetAttr(v, name);
- if (res != NULL) {
- Py_DECREF(res);
- return 1;
- }
- PyErr_Clear();
- return 0;
+ PyObject *res = PyObject_GetAttr(v, name);
+ if (res != NULL) {
+ Py_DECREF(res);
+ return 1;
+ }
+ PyErr_Clear();
+ return 0;
}
int
PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
{
- PyTypeObject *tp = Py_TYPE(v);
- int err;
+ PyTypeObject *tp = Py_TYPE(v);
+ int err;
- if (!PyString_Check(name)){
+ if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
- /* The Unicode to string conversion is done here because the
- existing tp_setattro slots expect a string object as name
- and we wouldn't want to break those. */
- if (PyUnicode_Check(name)) {
- name = PyUnicode_AsEncodedString(name, NULL, NULL);
- if (name == NULL)
- return -1;
- }
- else
+ /* The Unicode to string conversion is done here because the
+ existing tp_setattro slots expect a string object as name
+ and we wouldn't want to break those. */
+ if (PyUnicode_Check(name)) {
+ name = PyUnicode_AsEncodedString(name, NULL, NULL);
+ if (name == NULL)
+ return -1;
+ }
+ else
#endif
- {
- PyErr_Format(PyExc_TypeError,
- "attribute name must be string, not '%.200s'",
- Py_TYPE(name)->tp_name);
- return -1;
- }
- }
- else
- Py_INCREF(name);
-
- PyString_InternInPlace(&name);
- if (tp->tp_setattro != NULL) {
- err = (*tp->tp_setattro)(v, name, value);
- Py_DECREF(name);
- return err;
- }
- if (tp->tp_setattr != NULL) {
- err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
- Py_DECREF(name);
- return err;
- }
- Py_DECREF(name);
- if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
- PyErr_Format(PyExc_TypeError,
- "'%.100s' object has no attributes "
- "(%s .%.100s)",
- tp->tp_name,
- value==NULL ? "del" : "assign to",
- PyString_AS_STRING(name));
- else
- PyErr_Format(PyExc_TypeError,
- "'%.100s' object has only read-only attributes "
- "(%s .%.100s)",
- tp->tp_name,
- value==NULL ? "del" : "assign to",
- PyString_AS_STRING(name));
- return -1;
+ {
+ PyErr_Format(PyExc_TypeError,
+ "attribute name must be string, not '%.200s'",
+ Py_TYPE(name)->tp_name);
+ return -1;
+ }
+ }
+ else
+ Py_INCREF(name);
+
+ PyString_InternInPlace(&name);
+ if (tp->tp_setattro != NULL) {
+ err = (*tp->tp_setattro)(v, name, value);
+ Py_DECREF(name);
+ return err;
+ }
+ if (tp->tp_setattr != NULL) {
+ err = (*tp->tp_setattr)(v, PyString_AS_STRING(name), value);
+ Py_DECREF(name);
+ return err;
+ }
+ Py_DECREF(name);
+ if (tp->tp_getattr == NULL && tp->tp_getattro == NULL)
+ PyErr_Format(PyExc_TypeError,
+ "'%.100s' object has no attributes "
+ "(%s .%.100s)",
+ tp->tp_name,
+ value==NULL ? "del" : "assign to",
+ PyString_AS_STRING(name));
+ else
+ PyErr_Format(PyExc_TypeError,
+ "'%.100s' object has only read-only attributes "
+ "(%s .%.100s)",
+ tp->tp_name,
+ value==NULL ? "del" : "assign to",
+ PyString_AS_STRING(name));
+ return -1;
}
/* Helper to get a pointer to an object's __dict__ slot, if any */
@@ -1269,35 +1269,35 @@ PyObject_SetAttr(PyObject *v, PyObject *name, PyObject *value)
PyObject **
_PyObject_GetDictPtr(PyObject *obj)
{
- Py_ssize_t dictoffset;
- PyTypeObject *tp = Py_TYPE(obj);
+ Py_ssize_t dictoffset;
+ PyTypeObject *tp = Py_TYPE(obj);
- if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
- return NULL;
- dictoffset = tp->tp_dictoffset;
- if (dictoffset == 0)
- return NULL;
- if (dictoffset < 0) {
- Py_ssize_t tsize;
- size_t size;
+ if (!(tp->tp_flags & Py_TPFLAGS_HAVE_CLASS))
+ return NULL;
+ dictoffset = tp->tp_dictoffset;
+ if (dictoffset == 0)
+ return NULL;
+ if (dictoffset < 0) {
+ Py_ssize_t tsize;
+ size_t size;
- tsize = ((PyVarObject *)obj)->ob_size;
- if (tsize < 0)
- tsize = -tsize;
- size = _PyObject_VAR_SIZE(tp, tsize);
+ tsize = ((PyVarObject *)obj)->ob_size;
+ if (tsize < 0)
+ tsize = -tsize;
+ size = _PyObject_VAR_SIZE(tp, tsize);
- dictoffset += (long)size;
- assert(dictoffset > 0);
- assert(dictoffset % SIZEOF_VOID_P == 0);
- }
- return (PyObject **) ((char *)obj + dictoffset);
+ dictoffset += (long)size;
+ assert(dictoffset > 0);
+ assert(dictoffset % SIZEOF_VOID_P == 0);
+ }
+ return (PyObject **) ((char *)obj + dictoffset);
}
PyObject *
PyObject_SelfIter(PyObject *obj)
{
- Py_INCREF(obj);
- return obj;
+ Py_INCREF(obj);
+ return obj;
}
/* Helper used when the __next__ method is removed from a type:
@@ -1308,10 +1308,10 @@ PyObject_SelfIter(PyObject *obj)
PyObject *
_PyObject_NextNotImplemented(PyObject *self)
{
- PyErr_Format(PyExc_TypeError,
- "'%.200s' object is not iterable",
- Py_TYPE(self)->tp_name);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "'%.200s' object is not iterable",
+ Py_TYPE(self)->tp_name);
+ return NULL;
}
/* Generic GetAttr functions - put these in your tp_[gs]etattro slot */
@@ -1319,221 +1319,221 @@ _PyObject_NextNotImplemented(PyObject *self)
PyObject *
PyObject_GenericGetAttr(PyObject *obj, PyObject *name)
{
- PyTypeObject *tp = Py_TYPE(obj);
- PyObject *descr = NULL;
- PyObject *res = NULL;
- descrgetfunc f;
- Py_ssize_t dictoffset;
- PyObject **dictptr;
+ PyTypeObject *tp = Py_TYPE(obj);
+ PyObject *descr = NULL;
+ PyObject *res = NULL;
+ descrgetfunc f;
+ Py_ssize_t dictoffset;
+ PyObject **dictptr;
- if (!PyString_Check(name)){
+ if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
- /* The Unicode to string conversion is done here because the
- existing tp_setattro slots expect a string object as name
- and we wouldn't want to break those. */
- if (PyUnicode_Check(name)) {
- name = PyUnicode_AsEncodedString(name, NULL, NULL);
- if (name == NULL)
- return NULL;
- }
- else
+ /* The Unicode to string conversion is done here because the
+ existing tp_setattro slots expect a string object as name
+ and we wouldn't want to break those. */
+ if (PyUnicode_Check(name)) {
+ name = PyUnicode_AsEncodedString(name, NULL, NULL);
+ if (name == NULL)
+ return NULL;
+ }
+ else
#endif
- {
- PyErr_Format(PyExc_TypeError,
- "attribute name must be string, not '%.200s'",
- Py_TYPE(name)->tp_name);
- return NULL;
- }
- }
- else
- Py_INCREF(name);
-
- if (tp->tp_dict == NULL) {
- if (PyType_Ready(tp) < 0)
- goto done;
- }
+ {
+ PyErr_Format(PyExc_TypeError,
+ "attribute name must be string, not '%.200s'",
+ Py_TYPE(name)->tp_name);
+ return NULL;
+ }
+ }
+ else
+ Py_INCREF(name);
+
+ if (tp->tp_dict == NULL) {
+ if (PyType_Ready(tp) < 0)
+ goto done;
+ }
#if 0 /* XXX this is not quite _PyType_Lookup anymore */
- /* Inline _PyType_Lookup */
- {
- Py_ssize_t i, n;
- PyObject *mro, *base, *dict;
-
- /* Look in tp_dict of types in MRO */
- mro = tp->tp_mro;
- assert(mro != NULL);
- assert(PyTuple_Check(mro));
- n = PyTuple_GET_SIZE(mro);
- for (i = 0; i < n; i++) {
- base = PyTuple_GET_ITEM(mro, i);
- if (PyClass_Check(base))
- dict = ((PyClassObject *)base)->cl_dict;
- else {
- assert(PyType_Check(base));
- dict = ((PyTypeObject *)base)->tp_dict;
- }
- assert(dict && PyDict_Check(dict));
- descr = PyDict_GetItem(dict, name);
- if (descr != NULL)
- break;
- }
- }
+ /* Inline _PyType_Lookup */
+ {
+ Py_ssize_t i, n;
+ PyObject *mro, *base, *dict;
+
+ /* Look in tp_dict of types in MRO */
+ mro = tp->tp_mro;
+ assert(mro != NULL);
+ assert(PyTuple_Check(mro));
+ n = PyTuple_GET_SIZE(mro);
+ for (i = 0; i < n; i++) {
+ base = PyTuple_GET_ITEM(mro, i);
+ if (PyClass_Check(base))
+ dict = ((PyClassObject *)base)->cl_dict;
+ else {
+ assert(PyType_Check(base));
+ dict = ((PyTypeObject *)base)->tp_dict;
+ }
+ assert(dict && PyDict_Check(dict));
+ descr = PyDict_GetItem(dict, name);
+ if (descr != NULL)
+ break;
+ }
+ }
#else
- descr = _PyType_Lookup(tp, name);
+ descr = _PyType_Lookup(tp, name);
#endif
- Py_XINCREF(descr);
-
- f = NULL;
- if (descr != NULL &&
- PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
- f = descr->ob_type->tp_descr_get;
- if (f != NULL && PyDescr_IsData(descr)) {
- res = f(descr, obj, (PyObject *)obj->ob_type);
- Py_DECREF(descr);
- goto done;
- }
- }
-
- /* Inline _PyObject_GetDictPtr */
- dictoffset = tp->tp_dictoffset;
- if (dictoffset != 0) {
- PyObject *dict;
- if (dictoffset < 0) {
- Py_ssize_t tsize;
- size_t size;
-
- tsize = ((PyVarObject *)obj)->ob_size;
- if (tsize < 0)
- tsize = -tsize;
- size = _PyObject_VAR_SIZE(tp, tsize);
-
- dictoffset += (long)size;
- assert(dictoffset > 0);
- assert(dictoffset % SIZEOF_VOID_P == 0);
- }
- dictptr = (PyObject **) ((char *)obj + dictoffset);
- dict = *dictptr;
- if (dict != NULL) {
- Py_INCREF(dict);
- res = PyDict_GetItem(dict, name);
- if (res != NULL) {
- Py_INCREF(res);
- Py_XDECREF(descr);
- Py_DECREF(dict);
- goto done;
- }
- Py_DECREF(dict);
- }
- }
-
- if (f != NULL) {
- res = f(descr, obj, (PyObject *)Py_TYPE(obj));
- Py_DECREF(descr);
- goto done;
- }
-
- if (descr != NULL) {
- res = descr;
- /* descr was already increfed above */
- goto done;
- }
-
- PyErr_Format(PyExc_AttributeError,
- "'%.50s' object has no attribute '%.400s'",
- tp->tp_name, PyString_AS_STRING(name));
+ Py_XINCREF(descr);
+
+ f = NULL;
+ if (descr != NULL &&
+ PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
+ f = descr->ob_type->tp_descr_get;
+ if (f != NULL && PyDescr_IsData(descr)) {
+ res = f(descr, obj, (PyObject *)obj->ob_type);
+ Py_DECREF(descr);
+ goto done;
+ }
+ }
+
+ /* Inline _PyObject_GetDictPtr */
+ dictoffset = tp->tp_dictoffset;
+ if (dictoffset != 0) {
+ PyObject *dict;
+ if (dictoffset < 0) {
+ Py_ssize_t tsize;
+ size_t size;
+
+ tsize = ((PyVarObject *)obj)->ob_size;
+ if (tsize < 0)
+ tsize = -tsize;
+ size = _PyObject_VAR_SIZE(tp, tsize);
+
+ dictoffset += (long)size;
+ assert(dictoffset > 0);
+ assert(dictoffset % SIZEOF_VOID_P == 0);
+ }
+ dictptr = (PyObject **) ((char *)obj + dictoffset);
+ dict = *dictptr;
+ if (dict != NULL) {
+ Py_INCREF(dict);
+ res = PyDict_GetItem(dict, name);
+ if (res != NULL) {
+ Py_INCREF(res);
+ Py_XDECREF(descr);
+ Py_DECREF(dict);
+ goto done;
+ }
+ Py_DECREF(dict);
+ }
+ }
+
+ if (f != NULL) {
+ res = f(descr, obj, (PyObject *)Py_TYPE(obj));
+ Py_DECREF(descr);
+ goto done;
+ }
+
+ if (descr != NULL) {
+ res = descr;
+ /* descr was already increfed above */
+ goto done;
+ }
+
+ PyErr_Format(PyExc_AttributeError,
+ "'%.50s' object has no attribute '%.400s'",
+ tp->tp_name, PyString_AS_STRING(name));
done:
- Py_DECREF(name);
- return res;
+ Py_DECREF(name);
+ return res;
}
int
PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
{
- PyTypeObject *tp = Py_TYPE(obj);
- PyObject *descr;
- descrsetfunc f;
- PyObject **dictptr;
- int res = -1;
+ PyTypeObject *tp = Py_TYPE(obj);
+ PyObject *descr;
+ descrsetfunc f;
+ PyObject **dictptr;
+ int res = -1;
- if (!PyString_Check(name)){
+ if (!PyString_Check(name)){
#ifdef Py_USING_UNICODE
- /* The Unicode to string conversion is done here because the
- existing tp_setattro slots expect a string object as name
- and we wouldn't want to break those. */
- if (PyUnicode_Check(name)) {
- name = PyUnicode_AsEncodedString(name, NULL, NULL);
- if (name == NULL)
- return -1;
- }
- else
+ /* The Unicode to string conversion is done here because the
+ existing tp_setattro slots expect a string object as name
+ and we wouldn't want to break those. */
+ if (PyUnicode_Check(name)) {
+ name = PyUnicode_AsEncodedString(name, NULL, NULL);
+ if (name == NULL)
+ return -1;
+ }
+ else
#endif
- {
- PyErr_Format(PyExc_TypeError,
- "attribute name must be string, not '%.200s'",
- Py_TYPE(name)->tp_name);
- return -1;
- }
- }
- else
- Py_INCREF(name);
-
- if (tp->tp_dict == NULL) {
- if (PyType_Ready(tp) < 0)
- goto done;
- }
-
- descr = _PyType_Lookup(tp, name);
- f = NULL;
- if (descr != NULL &&
- PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
- f = descr->ob_type->tp_descr_set;
- if (f != NULL && PyDescr_IsData(descr)) {
- res = f(descr, obj, value);
- goto done;
- }
- }
-
- dictptr = _PyObject_GetDictPtr(obj);
- if (dictptr != NULL) {
- PyObject *dict = *dictptr;
- if (dict == NULL && value != NULL) {
- dict = PyDict_New();
- if (dict == NULL)
- goto done;
- *dictptr = dict;
- }
- if (dict != NULL) {
- Py_INCREF(dict);
- if (value == NULL)
- res = PyDict_DelItem(dict, name);
- else
- res = PyDict_SetItem(dict, name, value);
- if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
- PyErr_SetObject(PyExc_AttributeError, name);
- Py_DECREF(dict);
- goto done;
- }
- }
-
- if (f != NULL) {
- res = f(descr, obj, value);
- goto done;
- }
-
- if (descr == NULL) {
- PyErr_Format(PyExc_AttributeError,
- "'%.100s' object has no attribute '%.200s'",
- tp->tp_name, PyString_AS_STRING(name));
- goto done;
- }
-
- PyErr_Format(PyExc_AttributeError,
- "'%.50s' object attribute '%.400s' is read-only",
- tp->tp_name, PyString_AS_STRING(name));
+ {
+ PyErr_Format(PyExc_TypeError,
+ "attribute name must be string, not '%.200s'",
+ Py_TYPE(name)->tp_name);
+ return -1;
+ }
+ }
+ else
+ Py_INCREF(name);
+
+ if (tp->tp_dict == NULL) {
+ if (PyType_Ready(tp) < 0)
+ goto done;
+ }
+
+ descr = _PyType_Lookup(tp, name);
+ f = NULL;
+ if (descr != NULL &&
+ PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
+ f = descr->ob_type->tp_descr_set;
+ if (f != NULL && PyDescr_IsData(descr)) {
+ res = f(descr, obj, value);
+ goto done;
+ }
+ }
+
+ dictptr = _PyObject_GetDictPtr(obj);
+ if (dictptr != NULL) {
+ PyObject *dict = *dictptr;
+ if (dict == NULL && value != NULL) {
+ dict = PyDict_New();
+ if (dict == NULL)
+ goto done;
+ *dictptr = dict;
+ }
+ if (dict != NULL) {
+ Py_INCREF(dict);
+ if (value == NULL)
+ res = PyDict_DelItem(dict, name);
+ else
+ res = PyDict_SetItem(dict, name, value);
+ if (res < 0 && PyErr_ExceptionMatches(PyExc_KeyError))
+ PyErr_SetObject(PyExc_AttributeError, name);
+ Py_DECREF(dict);
+ goto done;
+ }
+ }
+
+ if (f != NULL) {
+ res = f(descr, obj, value);
+ goto done;
+ }
+
+ if (descr == NULL) {
+ PyErr_Format(PyExc_AttributeError,
+ "'%.100s' object has no attribute '%.200s'",
+ tp->tp_name, PyString_AS_STRING(name));
+ goto done;
+ }
+
+ PyErr_Format(PyExc_AttributeError,
+ "'%.50s' object attribute '%.400s' is read-only",
+ tp->tp_name, PyString_AS_STRING(name));
done:
- Py_DECREF(name);
- return res;
+ Py_DECREF(name);
+ return res;
}
/* Test a value used as condition, e.g., in a for or if statement.
@@ -1542,26 +1542,26 @@ PyObject_GenericSetAttr(PyObject *obj, PyObject *name, PyObject *value)
int
PyObject_IsTrue(PyObject *v)
{
- Py_ssize_t res;
- if (v == Py_True)
- return 1;
- if (v == Py_False)
- return 0;
- if (v == Py_None)
- return 0;
- else if (v->ob_type->tp_as_number != NULL &&
- v->ob_type->tp_as_number->nb_nonzero != NULL)
- res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
- else if (v->ob_type->tp_as_mapping != NULL &&
- v->ob_type->tp_as_mapping->mp_length != NULL)
- res = (*v->ob_type->tp_as_mapping->mp_length)(v);
- else if (v->ob_type->tp_as_sequence != NULL &&
- v->ob_type->tp_as_sequence->sq_length != NULL)
- res = (*v->ob_type->tp_as_sequence->sq_length)(v);
- else
- return 1;
- /* if it is negative, it should be either -1 or -2 */
- return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
+ Py_ssize_t res;
+ if (v == Py_True)
+ return 1;
+ if (v == Py_False)
+ return 0;
+ if (v == Py_None)
+ return 0;
+ else if (v->ob_type->tp_as_number != NULL &&
+ v->ob_type->tp_as_number->nb_nonzero != NULL)
+ res = (*v->ob_type->tp_as_number->nb_nonzero)(v);
+ else if (v->ob_type->tp_as_mapping != NULL &&
+ v->ob_type->tp_as_mapping->mp_length != NULL)
+ res = (*v->ob_type->tp_as_mapping->mp_length)(v);
+ else if (v->ob_type->tp_as_sequence != NULL &&
+ v->ob_type->tp_as_sequence->sq_length != NULL)
+ res = (*v->ob_type->tp_as_sequence->sq_length)(v);
+ else
+ return 1;
+ /* if it is negative, it should be either -1 or -2 */
+ return (res > 0) ? 1 : Py_SAFE_DOWNCAST(res, Py_ssize_t, int);
}
/* equivalent of 'not v'
@@ -1570,11 +1570,11 @@ PyObject_IsTrue(PyObject *v)
int
PyObject_Not(PyObject *v)
{
- int res;
- res = PyObject_IsTrue(v);
- if (res < 0)
- return res;
- return res == 0;
+ int res;
+ res = PyObject_IsTrue(v);
+ if (res < 0)
+ return res;
+ return res == 0;
}
/* Coerce two numeric types to the "larger" one.
@@ -1587,29 +1587,29 @@ PyObject_Not(PyObject *v)
int
PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
{
- register PyObject *v = *pv;
- register PyObject *w = *pw;
- int res;
-
- /* Shortcut only for old-style types */
- if (v->ob_type == w->ob_type &&
- !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
- {
- Py_INCREF(v);
- Py_INCREF(w);
- return 0;
- }
- if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
- res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
- if (res <= 0)
- return res;
- }
- if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
- res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
- if (res <= 0)
- return res;
- }
- return 1;
+ register PyObject *v = *pv;
+ register PyObject *w = *pw;
+ int res;
+
+ /* Shortcut only for old-style types */
+ if (v->ob_type == w->ob_type &&
+ !PyType_HasFeature(v->ob_type, Py_TPFLAGS_CHECKTYPES))
+ {
+ Py_INCREF(v);
+ Py_INCREF(w);
+ return 0;
+ }
+ if (v->ob_type->tp_as_number && v->ob_type->tp_as_number->nb_coerce) {
+ res = (*v->ob_type->tp_as_number->nb_coerce)(pv, pw);
+ if (res <= 0)
+ return res;
+ }
+ if (w->ob_type->tp_as_number && w->ob_type->tp_as_number->nb_coerce) {
+ res = (*w->ob_type->tp_as_number->nb_coerce)(pw, pv);
+ if (res <= 0)
+ return res;
+ }
+ return 1;
}
/* Coerce two numeric types to the "larger" one.
@@ -1620,11 +1620,11 @@ PyNumber_CoerceEx(PyObject **pv, PyObject **pw)
int
PyNumber_Coerce(PyObject **pv, PyObject **pw)
{
- int err = PyNumber_CoerceEx(pv, pw);
- if (err <= 0)
- return err;
- PyErr_SetString(PyExc_TypeError, "number coercion failed");
- return -1;
+ int err = PyNumber_CoerceEx(pv, pw);
+ if (err <= 0)
+ return err;
+ PyErr_SetString(PyExc_TypeError, "number coercion failed");
+ return -1;
}
@@ -1633,22 +1633,22 @@ PyNumber_Coerce(PyObject **pv, PyObject **pw)
int
PyCallable_Check(PyObject *x)
{
- if (x == NULL)
- return 0;
- if (PyInstance_Check(x)) {
- PyObject *call = PyObject_GetAttrString(x, "__call__");
- if (call == NULL) {
- PyErr_Clear();
- return 0;
- }
- /* Could test recursively but don't, for fear of endless
- recursion if some joker sets self.__call__ = self */
- Py_DECREF(call);
- return 1;
- }
- else {
- return x->ob_type->tp_call != NULL;
- }
+ if (x == NULL)
+ return 0;
+ if (PyInstance_Check(x)) {
+ PyObject *call = PyObject_GetAttrString(x, "__call__");
+ if (call == NULL) {
+ PyErr_Clear();
+ return 0;
+ }
+ /* Could test recursively but don't, for fear of endless
+ recursion if some joker sets self.__call__ = self */
+ Py_DECREF(call);
+ return 1;
+ }
+ else {
+ return x->ob_type->tp_call != NULL;
+ }
}
/* ------------------------- PyObject_Dir() helpers ------------------------- */
@@ -1664,52 +1664,52 @@ PyCallable_Check(PyObject *x)
static int
merge_class_dict(PyObject* dict, PyObject* aclass)
{
- PyObject *classdict;
- PyObject *bases;
-
- assert(PyDict_Check(dict));
- assert(aclass);
-
- /* Merge in the type's dict (if any). */
- classdict = PyObject_GetAttrString(aclass, "__dict__");
- if (classdict == NULL)
- PyErr_Clear();
- else {
- int status = PyDict_Update(dict, classdict);
- Py_DECREF(classdict);
- if (status < 0)
- return -1;
- }
-
- /* Recursively merge in the base types' (if any) dicts. */
- bases = PyObject_GetAttrString(aclass, "__bases__");
- if (bases == NULL)
- PyErr_Clear();
- else {
- /* We have no guarantee that bases is a real tuple */
- Py_ssize_t i, n;
- n = PySequence_Size(bases); /* This better be right */
- if (n < 0)
- PyErr_Clear();
- else {
- for (i = 0; i < n; i++) {
- int status;
- PyObject *base = PySequence_GetItem(bases, i);
- if (base == NULL) {
- Py_DECREF(bases);
- return -1;
- }
- status = merge_class_dict(dict, base);
- Py_DECREF(base);
- if (status < 0) {
- Py_DECREF(bases);
- return -1;
- }
- }
- }
- Py_DECREF(bases);
- }
- return 0;
+ PyObject *classdict;
+ PyObject *bases;
+
+ assert(PyDict_Check(dict));
+ assert(aclass);
+
+ /* Merge in the type's dict (if any). */
+ classdict = PyObject_GetAttrString(aclass, "__dict__");
+ if (classdict == NULL)
+ PyErr_Clear();
+ else {
+ int status = PyDict_Update(dict, classdict);
+ Py_DECREF(classdict);
+ if (status < 0)
+ return -1;
+ }
+
+ /* Recursively merge in the base types' (if any) dicts. */
+ bases = PyObject_GetAttrString(aclass, "__bases__");
+ if (bases == NULL)
+ PyErr_Clear();
+ else {
+ /* We have no guarantee that bases is a real tuple */
+ Py_ssize_t i, n;
+ n = PySequence_Size(bases); /* This better be right */
+ if (n < 0)
+ PyErr_Clear();
+ else {
+ for (i = 0; i < n; i++) {
+ int status;
+ PyObject *base = PySequence_GetItem(bases, i);
+ if (base == NULL) {
+ Py_DECREF(bases);
+ return -1;
+ }
+ status = merge_class_dict(dict, base);
+ Py_DECREF(base);
+ if (status < 0) {
+ Py_DECREF(bases);
+ return -1;
+ }
+ }
+ }
+ Py_DECREF(bases);
+ }
+ return 0;
}
/* Helper for PyObject_Dir.
@@ -1722,107 +1722,107 @@ merge_class_dict(PyObject* dict, PyObject* aclass)
static int
merge_list_attr(PyObject* dict, PyObject* obj, const char *attrname)
{
- PyObject *list;
- int result = 0;
-
- assert(PyDict_Check(dict));
- assert(obj);
- assert(attrname);
-
- list = PyObject_GetAttrString(obj, attrname);
- if (list == NULL)
- PyErr_Clear();
-
- else if (PyList_Check(list)) {
- int i;
- for (i = 0; i < PyList_GET_SIZE(list); ++i) {
- PyObject *item = PyList_GET_ITEM(list, i);
- if (PyString_Check(item)) {
- result = PyDict_SetItem(dict, item, Py_None);
- if (result < 0)
- break;
- }
- }
- if (Py_Py3kWarningFlag &&
- (strcmp(attrname, "__members__") == 0 ||
- strcmp(attrname, "__methods__") == 0)) {
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "__members__ and __methods__ not "
- "supported in 3.x", 1) < 0) {
- Py_XDECREF(list);
- return -1;
- }
- }
- }
-
- Py_XDECREF(list);
- return result;
+ PyObject *list;
+ int result = 0;
+
+ assert(PyDict_Check(dict));
+ assert(obj);
+ assert(attrname);
+
+ list = PyObject_GetAttrString(obj, attrname);
+ if (list == NULL)
+ PyErr_Clear();
+
+ else if (PyList_Check(list)) {
+ int i;
+ for (i = 0; i < PyList_GET_SIZE(list); ++i) {
+ PyObject *item = PyList_GET_ITEM(list, i);
+ if (PyString_Check(item)) {
+ result = PyDict_SetItem(dict, item, Py_None);
+ if (result < 0)
+ break;
+ }
+ }
+ if (Py_Py3kWarningFlag &&
+ (strcmp(attrname, "__members__") == 0 ||
+ strcmp(attrname, "__methods__") == 0)) {
+ if (PyErr_WarnEx(PyExc_DeprecationWarning,
+ "__members__ and __methods__ not "
+ "supported in 3.x", 1) < 0) {
+ Py_XDECREF(list);
+ return -1;
+ }
+ }
+ }
+
+ Py_XDECREF(list);
+ return result;
}
/* Helper for PyObject_Dir without arguments: returns the local scope. */
static PyObject *
_dir_locals(void)
{
- PyObject *names;
- PyObject *locals = PyEval_GetLocals();
+ PyObject *names;
+ PyObject *locals = PyEval_GetLocals();
- if (locals == NULL) {
- PyErr_SetString(PyExc_SystemError, "frame does not exist");
- return NULL;
- }
+ if (locals == NULL) {
+ PyErr_SetString(PyExc_SystemError, "frame does not exist");
+ return NULL;
+ }
- names = PyMapping_Keys(locals);
- if (!names)
- return NULL;
- if (!PyList_Check(names)) {
- PyErr_Format(PyExc_TypeError,
- "dir(): expected keys() of locals to be a list, "
- "not '%.200s'", Py_TYPE(names)->tp_name);
- Py_DECREF(names);
- return NULL;
- }
- /* the locals don't need to be DECREF'd */
- return names;
+ names = PyMapping_Keys(locals);
+ if (!names)
+ return NULL;
+ if (!PyList_Check(names)) {
+ PyErr_Format(PyExc_TypeError,
+ "dir(): expected keys() of locals to be a list, "
+ "not '%.200s'", Py_TYPE(names)->tp_name);
+ Py_DECREF(names);
+ return NULL;
+ }
+ /* the locals don't need to be DECREF'd */
+ return names;
}
/* Helper for PyObject_Dir of type objects: returns __dict__ and __bases__.
- We deliberately don't suck up its __class__, as methods belonging to the
- metaclass would probably be more confusing than helpful.
+ We deliberately don't suck up its __class__, as methods belonging to the
+ metaclass would probably be more confusing than helpful.
*/
-static PyObject *
+static PyObject *
_specialized_dir_type(PyObject *obj)
{
- PyObject *result = NULL;
- PyObject *dict = PyDict_New();
+ PyObject *result = NULL;
+ PyObject *dict = PyDict_New();
- if (dict != NULL && merge_class_dict(dict, obj) == 0)
- result = PyDict_Keys(dict);
+ if (dict != NULL && merge_class_dict(dict, obj) == 0)
+ result = PyDict_Keys(dict);
- Py_XDECREF(dict);
- return result;
+ Py_XDECREF(dict);
+ return result;
}
/* Helper for PyObject_Dir of module objects: returns the module's __dict__. */
static PyObject *
_specialized_dir_module(PyObject *obj)
{
- PyObject *result = NULL;
- PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
+ PyObject *result = NULL;
+ PyObject *dict = PyObject_GetAttrString(obj, "__dict__");
- if (dict != NULL) {
- if (PyDict_Check(dict))
- result = PyDict_Keys(dict);
- else {
- char *name = PyModule_GetName(obj);
- if (name)
- PyErr_Format(PyExc_TypeError,
- "%.200s.__dict__ is not a dictionary",
- name);
- }
- }
+ if (dict != NULL) {
+ if (PyDict_Check(dict))
+ result = PyDict_Keys(dict);
+ else {
+ char *name = PyModule_GetName(obj);
+ if (name)
+ PyErr_Format(PyExc_TypeError,
+ "%.200s.__dict__ is not a dictionary",
+ name);
+ }
+ }
- Py_XDECREF(dict);
- return result;
+ Py_XDECREF(dict);
+ return result;
}
/* Helper for PyObject_Dir of generic objects: returns __dict__, __class__,
@@ -1831,54 +1831,54 @@ _specialized_dir_module(PyObject *obj)
static PyObject *
_generic_dir(PyObject *obj)
{
- PyObject *result = NULL;
- PyObject *dict = NULL;
- PyObject *itsclass = NULL;
-
- /* Get __dict__ (which may or may not be a real dict...) */
- dict = PyObject_GetAttrString(obj, "__dict__");
- if (dict == NULL) {
- PyErr_Clear();
- dict = PyDict_New();
- }
- else if (!PyDict_Check(dict)) {
- Py_DECREF(dict);
- dict = PyDict_New();
- }
- else {
- /* Copy __dict__ to avoid mutating it. */
- PyObject *temp = PyDict_Copy(dict);
- Py_DECREF(dict);
- dict = temp;
- }
-
- if (dict == NULL)
- goto error;
-
- /* Merge in __members__ and __methods__ (if any).
- * This is removed in Python 3000. */
- if (merge_list_attr(dict, obj, "__members__") < 0)
- goto error;
- if (merge_list_attr(dict, obj, "__methods__") < 0)
- goto error;
-
- /* Merge in attrs reachable from its class. */
- itsclass = PyObject_GetAttrString(obj, "__class__");
- if (itsclass == NULL)
- /* XXX(tomer): Perhaps fall back to obj->ob_type if no
- __class__ exists? */
- PyErr_Clear();
- else {
- if (merge_class_dict(dict, itsclass) != 0)
- goto error;
- }
-
- result = PyDict_Keys(dict);
- /* fall through */
+ PyObject *result = NULL;
+ PyObject *dict = NULL;
+ PyObject *itsclass = NULL;
+
+ /* Get __dict__ (which may or may not be a real dict...) */
+ dict = PyObject_GetAttrString(obj, "__dict__");
+ if (dict == NULL) {
+ PyErr_Clear();
+ dict = PyDict_New();
+ }
+ else if (!PyDict_Check(dict)) {
+ Py_DECREF(dict);
+ dict = PyDict_New();
+ }
+ else {
+ /* Copy __dict__ to avoid mutating it. */
+ PyObject *temp = PyDict_Copy(dict);
+ Py_DECREF(dict);
+ dict = temp;
+ }
+
+ if (dict == NULL)
+ goto error;
+
+ /* Merge in __members__ and __methods__ (if any).
+ * This is removed in Python 3000. */
+ if (merge_list_attr(dict, obj, "__members__") < 0)
+ goto error;
+ if (merge_list_attr(dict, obj, "__methods__") < 0)
+ goto error;
+
+ /* Merge in attrs reachable from its class. */
+ itsclass = PyObject_GetAttrString(obj, "__class__");
+ if (itsclass == NULL)
+ /* XXX(tomer): Perhaps fall back to obj->ob_type if no
+ __class__ exists? */
+ PyErr_Clear();
+ else {
+ if (merge_class_dict(dict, itsclass) != 0)
+ goto error;
+ }
+
+ result = PyDict_Keys(dict);
+ /* fall through */
error:
- Py_XDECREF(itsclass);
- Py_XDECREF(dict);
- return result;
+ Py_XDECREF(itsclass);
+ Py_XDECREF(dict);
+ return result;
}
/* Helper for PyObject_Dir: object introspection.
@@ -1887,40 +1887,40 @@ error:
static PyObject *
_dir_object(PyObject *obj)
{
- PyObject *result = NULL;
- PyObject *dirfunc = PyObject_GetAttrString((PyObject *)obj->ob_type,
- "__dir__");
-
- assert(obj);
- if (dirfunc == NULL) {
- /* use default implementation */
- PyErr_Clear();
- if (PyModule_Check(obj))
- result = _specialized_dir_module(obj);
- else if (PyType_Check(obj) || PyClass_Check(obj))
- result = _specialized_dir_type(obj);
- else
- result = _generic_dir(obj);
- }
- else {
- /* use __dir__ */
- result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
- Py_DECREF(dirfunc);
- if (result == NULL)
- return NULL;
-
- /* result must be a list */
- /* XXX(gbrandl): could also check if all items are strings */
- if (!PyList_Check(result)) {
- PyErr_Format(PyExc_TypeError,
- "__dir__() must return a list, not %.200s",
- Py_TYPE(result)->tp_name);
- Py_DECREF(result);
- result = NULL;
- }
- }
-
- return result;
+ PyObject *result = NULL;
+ PyObject *dirfunc = PyObject_GetAttrString((PyObject *)obj->ob_type,
+ "__dir__");
+
+ assert(obj);
+ if (dirfunc == NULL) {
+ /* use default implementation */
+ PyErr_Clear();
+ if (PyModule_Check(obj))
+ result = _specialized_dir_module(obj);
+ else if (PyType_Check(obj) || PyClass_Check(obj))
+ result = _specialized_dir_type(obj);
+ else
+ result = _generic_dir(obj);
+ }
+ else {
+ /* use __dir__ */
+ result = PyObject_CallFunctionObjArgs(dirfunc, obj, NULL);
+ Py_DECREF(dirfunc);
+ if (result == NULL)
+ return NULL;
+
+ /* result must be a list */
+ /* XXX(gbrandl): could also check if all items are strings */
+ if (!PyList_Check(result)) {
+ PyErr_Format(PyExc_TypeError,
+ "__dir__() must return a list, not %.200s",
+ Py_TYPE(result)->tp_name);
+ Py_DECREF(result);
+ result = NULL;
+ }
+ }
+
+ return result;
}
/* Implementation of dir() -- if obj is NULL, returns the names in the current
@@ -1930,24 +1930,24 @@ _dir_object(PyObject *obj)
PyObject *
PyObject_Dir(PyObject *obj)
{
- PyObject * result;
+ PyObject * result;
+
+ if (obj == NULL)
+ /* no object -- introspect the locals */
+ result = _dir_locals();
+ else
+ /* object -- introspect the object */
+ result = _dir_object(obj);
- if (obj == NULL)
- /* no object -- introspect the locals */
- result = _dir_locals();
- else
- /* object -- introspect the object */
- result = _dir_object(obj);
+ assert(result == NULL || PyList_Check(result));
- assert(result == NULL || PyList_Check(result));
+ if (result != NULL && PyList_Sort(result) != 0) {
+ /* sorting the list failed */
+ Py_DECREF(result);
+ result = NULL;
+ }
- if (result != NULL && PyList_Sort(result) != 0) {
- /* sorting the list failed */
- Py_DECREF(result);
- result = NULL;
- }
-
- return result;
+ return result;
}
/*
@@ -1961,35 +1961,35 @@ so there is exactly one (which is indestructible, by the way).
static PyObject *
none_repr(PyObject *op)
{
- return PyString_FromString("None");
+ return PyString_FromString("None");
}
/* ARGUSED */
static void
none_dealloc(PyObject* ignore)
{
- /* This should never get called, but we also don't want to SEGV if
- * we accidentally decref None out of existence.
- */
- Py_FatalError("deallocating None");
+ /* This should never get called, but we also don't want to SEGV if
+ * we accidentally decref None out of existence.
+ */
+ Py_FatalError("deallocating None");
}
static PyTypeObject PyNone_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "NoneType",
- 0,
- 0,
- none_dealloc, /*tp_dealloc*/ /*never called*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- none_repr, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- (hashfunc)_Py_HashPointer, /*tp_hash */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "NoneType",
+ 0,
+ 0,
+ none_dealloc, /*tp_dealloc*/ /*never called*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ none_repr, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ (hashfunc)_Py_HashPointer, /*tp_hash */
};
PyObject _Py_NoneStruct = {
@@ -2003,167 +2003,167 @@ PyObject _Py_NoneStruct = {
static PyObject *
NotImplemented_repr(PyObject *op)
{
- return PyString_FromString("NotImplemented");
+ return PyString_FromString("NotImplemented");
}
static PyTypeObject PyNotImplemented_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "NotImplementedType",
- 0,
- 0,
- none_dealloc, /*tp_dealloc*/ /*never called*/
- 0, /*tp_print*/
- 0, /*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- NotImplemented_repr, /*tp_repr*/
- 0, /*tp_as_number*/
- 0, /*tp_as_sequence*/
- 0, /*tp_as_mapping*/
- 0, /*tp_hash */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "NotImplementedType",
+ 0,
+ 0,
+ none_dealloc, /*tp_dealloc*/ /*never called*/
+ 0, /*tp_print*/
+ 0, /*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ NotImplemented_repr, /*tp_repr*/
+ 0, /*tp_as_number*/
+ 0, /*tp_as_sequence*/
+ 0, /*tp_as_mapping*/
+ 0, /*tp_hash */
};
PyObject _Py_NotImplementedStruct = {
- _PyObject_EXTRA_INIT
- 1, &PyNotImplemented_Type
+ _PyObject_EXTRA_INIT
+ 1, &PyNotImplemented_Type
};
void
_Py_ReadyTypes(void)
{
- if (PyType_Ready(&PyType_Type) < 0)
- Py_FatalError("Can't initialize type type");
+ if (PyType_Ready(&PyType_Type) < 0)
+ Py_FatalError("Can't initialize type type");
- if (PyType_Ready(&_PyWeakref_RefType) < 0)
- Py_FatalError("Can't initialize weakref type");
+ if (PyType_Ready(&_PyWeakref_RefType) < 0)
+ Py_FatalError("Can't initialize weakref type");
- if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
- Py_FatalError("Can't initialize callable weakref proxy type");
+ if (PyType_Ready(&_PyWeakref_CallableProxyType) < 0)
+ Py_FatalError("Can't initialize callable weakref proxy type");
- if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
- Py_FatalError("Can't initialize weakref proxy type");
+ if (PyType_Ready(&_PyWeakref_ProxyType) < 0)
+ Py_FatalError("Can't initialize weakref proxy type");
- if (PyType_Ready(&PyBool_Type) < 0)
- Py_FatalError("Can't initialize bool type");
+ if (PyType_Ready(&PyBool_Type) < 0)
+ Py_FatalError("Can't initialize bool type");
- if (PyType_Ready(&PyString_Type) < 0)
- Py_FatalError("Can't initialize str type");
+ if (PyType_Ready(&PyString_Type) < 0)
+ Py_FatalError("Can't initialize str type");
- if (PyType_Ready(&PyByteArray_Type) < 0)
- Py_FatalError("Can't initialize bytearray type");
+ if (PyType_Ready(&PyByteArray_Type) < 0)
+ Py_FatalError("Can't initialize bytearray type");
- if (PyType_Ready(&PyList_Type) < 0)
- Py_FatalError("Can't initialize list type");
+ if (PyType_Ready(&PyList_Type) < 0)
+ Py_FatalError("Can't initialize list type");
- if (PyType_Ready(&PyNone_Type) < 0)
- Py_FatalError("Can't initialize None type");
+ if (PyType_Ready(&PyNone_Type) < 0)
+ Py_FatalError("Can't initialize None type");
- if (PyType_Ready(&PyNotImplemented_Type) < 0)
- Py_FatalError("Can't initialize NotImplemented type");
+ if (PyType_Ready(&PyNotImplemented_Type) < 0)
+ Py_FatalError("Can't initialize NotImplemented type");
- if (PyType_Ready(&PyTraceBack_Type) < 0)
- Py_FatalError("Can't initialize traceback type");
+ if (PyType_Ready(&PyTraceBack_Type) < 0)
+ Py_FatalError("Can't initialize traceback type");
- if (PyType_Ready(&PySuper_Type) < 0)
- Py_FatalError("Can't initialize super type");
+ if (PyType_Ready(&PySuper_Type) < 0)
+ Py_FatalError("Can't initialize super type");
- if (PyType_Ready(&PyBaseObject_Type) < 0)
- Py_FatalError("Can't initialize object type");
+ if (PyType_Ready(&PyBaseObject_Type) < 0)
+ Py_FatalError("Can't initialize object type");
- if (PyType_Ready(&PyRange_Type) < 0)
- Py_FatalError("Can't initialize xrange type");
+ if (PyType_Ready(&PyRange_Type) < 0)
+ Py_FatalError("Can't initialize xrange type");
- if (PyType_Ready(&PyDict_Type) < 0)
- Py_FatalError("Can't initialize dict type");
+ if (PyType_Ready(&PyDict_Type) < 0)
+ Py_FatalError("Can't initialize dict type");
- if (PyType_Ready(&PySet_Type) < 0)
- Py_FatalError("Can't initialize set type");
+ if (PyType_Ready(&PySet_Type) < 0)
+ Py_FatalError("Can't initialize set type");
- if (PyType_Ready(&PyUnicode_Type) < 0)
- Py_FatalError("Can't initialize unicode type");
+ if (PyType_Ready(&PyUnicode_Type) < 0)
+ Py_FatalError("Can't initialize unicode type");
- if (PyType_Ready(&PySlice_Type) < 0)
- Py_FatalError("Can't initialize slice type");
+ if (PyType_Ready(&PySlice_Type) < 0)
+ Py_FatalError("Can't initialize slice type");
- if (PyType_Ready(&PyStaticMethod_Type) < 0)
- Py_FatalError("Can't initialize static method type");
+ if (PyType_Ready(&PyStaticMethod_Type) < 0)
+ Py_FatalError("Can't initialize static method type");
#ifndef WITHOUT_COMPLEX
- if (PyType_Ready(&PyComplex_Type) < 0)
- Py_FatalError("Can't initialize complex type");
+ if (PyType_Ready(&PyComplex_Type) < 0)
+ Py_FatalError("Can't initialize complex type");
#endif
- if (PyType_Ready(&PyFloat_Type) < 0)
- Py_FatalError("Can't initialize float type");
+ if (PyType_Ready(&PyFloat_Type) < 0)
+ Py_FatalError("Can't initialize float type");
- if (PyType_Ready(&PyBuffer_Type) < 0)
- Py_FatalError("Can't initialize buffer type");
+ if (PyType_Ready(&PyBuffer_Type) < 0)
+ Py_FatalError("Can't initialize buffer type");
- if (PyType_Ready(&PyLong_Type) < 0)
- Py_FatalError("Can't initialize long type");
+ if (PyType_Ready(&PyLong_Type) < 0)
+ Py_FatalError("Can't initialize long type");
- if (PyType_Ready(&PyInt_Type) < 0)
- Py_FatalError("Can't initialize int type");
+ if (PyType_Ready(&PyInt_Type) < 0)
+ Py_FatalError("Can't initialize int type");
- if (PyType_Ready(&PyFrozenSet_Type) < 0)
- Py_FatalError("Can't initialize frozenset type");
+ if (PyType_Ready(&PyFrozenSet_Type) < 0)
+ Py_FatalError("Can't initialize frozenset type");
- if (PyType_Ready(&PyProperty_Type) < 0)
- Py_FatalError("Can't initialize property type");
+ if (PyType_Ready(&PyProperty_Type) < 0)
+ Py_FatalError("Can't initialize property type");
- if (PyType_Ready(&PyMemoryView_Type) < 0)
- Py_FatalError("Can't initialize memoryview type");
+ if (PyType_Ready(&PyMemoryView_Type) < 0)
+ Py_FatalError("Can't initialize memoryview type");
- if (PyType_Ready(&PyTuple_Type) < 0)
- Py_FatalError("Can't initialize tuple type");
+ if (PyType_Ready(&PyTuple_Type) < 0)
+ Py_FatalError("Can't initialize tuple type");
- if (PyType_Ready(&PyEnum_Type) < 0)
- Py_FatalError("Can't initialize enumerate type");
+ if (PyType_Ready(&PyEnum_Type) < 0)
+ Py_FatalError("Can't initialize enumerate type");
- if (PyType_Ready(&PyReversed_Type) < 0)
- Py_FatalError("Can't initialize reversed type");
+ if (PyType_Ready(&PyReversed_Type) < 0)
+ Py_FatalError("Can't initialize reversed type");
- if (PyType_Ready(&PyCode_Type) < 0)
- Py_FatalError("Can't initialize code type");
+ if (PyType_Ready(&PyCode_Type) < 0)
+ Py_FatalError("Can't initialize code type");
- if (PyType_Ready(&PyFrame_Type) < 0)
- Py_FatalError("Can't initialize frame type");
+ if (PyType_Ready(&PyFrame_Type) < 0)
+ Py_FatalError("Can't initialize frame type");
- if (PyType_Ready(&PyCFunction_Type) < 0)
- Py_FatalError("Can't initialize builtin function type");
+ if (PyType_Ready(&PyCFunction_Type) < 0)
+ Py_FatalError("Can't initialize builtin function type");
- if (PyType_Ready(&PyMethod_Type) < 0)
- Py_FatalError("Can't initialize method type");
+ if (PyType_Ready(&PyMethod_Type) < 0)
+ Py_FatalError("Can't initialize method type");
- if (PyType_Ready(&PyFunction_Type) < 0)
- Py_FatalError("Can't initialize function type");
+ if (PyType_Ready(&PyFunction_Type) < 0)
+ Py_FatalError("Can't initialize function type");
- if (PyType_Ready(&PyClass_Type) < 0)
- Py_FatalError("Can't initialize class type");
+ if (PyType_Ready(&PyClass_Type) < 0)
+ Py_FatalError("Can't initialize class type");
- if (PyType_Ready(&PyDictProxy_Type) < 0)
- Py_FatalError("Can't initialize dict proxy type");
+ if (PyType_Ready(&PyDictProxy_Type) < 0)
+ Py_FatalError("Can't initialize dict proxy type");
- if (PyType_Ready(&PyGen_Type) < 0)
- Py_FatalError("Can't initialize generator type");
+ if (PyType_Ready(&PyGen_Type) < 0)
+ Py_FatalError("Can't initialize generator type");
- if (PyType_Ready(&PyGetSetDescr_Type) < 0)
- Py_FatalError("Can't initialize get-set descriptor type");
+ if (PyType_Ready(&PyGetSetDescr_Type) < 0)
+ Py_FatalError("Can't initialize get-set descriptor type");
- if (PyType_Ready(&PyWrapperDescr_Type) < 0)
- Py_FatalError("Can't initialize wrapper type");
+ if (PyType_Ready(&PyWrapperDescr_Type) < 0)
+ Py_FatalError("Can't initialize wrapper type");
- if (PyType_Ready(&PyInstance_Type) < 0)
- Py_FatalError("Can't initialize instance type");
+ if (PyType_Ready(&PyInstance_Type) < 0)
+ Py_FatalError("Can't initialize instance type");
- if (PyType_Ready(&PyEllipsis_Type) < 0)
- Py_FatalError("Can't initialize ellipsis type");
+ if (PyType_Ready(&PyEllipsis_Type) < 0)
+ Py_FatalError("Can't initialize ellipsis type");
- if (PyType_Ready(&PyMemberDescr_Type) < 0)
- Py_FatalError("Can't initialize member descriptor type");
+ if (PyType_Ready(&PyMemberDescr_Type) < 0)
+ Py_FatalError("Can't initialize member descriptor type");
- if (PyType_Ready(&PyFile_Type) < 0)
- Py_FatalError("Can't initialize file type");
+ if (PyType_Ready(&PyFile_Type) < 0)
+ Py_FatalError("Can't initialize file type");
}
@@ -2172,43 +2172,43 @@ _Py_ReadyTypes(void)
void
_Py_NewReference(PyObject *op)
{
- _Py_INC_REFTOTAL;
- op->ob_refcnt = 1;
- _Py_AddToAllObjects(op, 1);
- _Py_INC_TPALLOCS(op);
+ _Py_INC_REFTOTAL;
+ op->ob_refcnt = 1;
+ _Py_AddToAllObjects(op, 1);
+ _Py_INC_TPALLOCS(op);
}
void
_Py_ForgetReference(register PyObject *op)
{
#ifdef SLOW_UNREF_CHECK
- register PyObject *p;
+ register PyObject *p;
#endif
- if (op->ob_refcnt < 0)
- Py_FatalError("UNREF negative refcnt");
- if (op == &refchain ||
- op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
- Py_FatalError("UNREF invalid object");
+ if (op->ob_refcnt < 0)
+ Py_FatalError("UNREF negative refcnt");
+ if (op == &refchain ||
+ op->_ob_prev->_ob_next != op || op->_ob_next->_ob_prev != op)
+ Py_FatalError("UNREF invalid object");
#ifdef SLOW_UNREF_CHECK
- for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
- if (p == op)
- break;
- }
- if (p == &refchain) /* Not found */
- Py_FatalError("UNREF unknown object");
+ for (p = refchain._ob_next; p != &refchain; p = p->_ob_next) {
+ if (p == op)
+ break;
+ }
+ if (p == &refchain) /* Not found */
+ Py_FatalError("UNREF unknown object");
#endif
- op->_ob_next->_ob_prev = op->_ob_prev;
- op->_ob_prev->_ob_next = op->_ob_next;
- op->_ob_next = op->_ob_prev = NULL;
- _Py_INC_TPFREES(op);
+ op->_ob_next->_ob_prev = op->_ob_prev;
+ op->_ob_prev->_ob_next = op->_ob_next;
+ op->_ob_next = op->_ob_prev = NULL;
+ _Py_INC_TPFREES(op);
}
void
_Py_Dealloc(PyObject *op)
{
- destructor dealloc = Py_TYPE(op)->tp_dealloc;
- _Py_ForgetReference(op);
- (*dealloc)(op);
+ destructor dealloc = Py_TYPE(op)->tp_dealloc;
+ _Py_ForgetReference(op);
+ (*dealloc)(op);
}
/* Print all live objects. Because PyObject_Print is called, the
@@ -2217,14 +2217,14 @@ _Py_Dealloc(PyObject *op)
void
_Py_PrintReferences(FILE *fp)
{
- PyObject *op;
- fprintf(fp, "Remaining objects:\n");
- for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
- fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
- if (PyObject_Print(op, fp, 0) != 0)
- PyErr_Clear();
- putc('\n', fp);
- }
+ PyObject *op;
+ fprintf(fp, "Remaining objects:\n");
+ for (op = refchain._ob_next; op != &refchain; op = op->_ob_next) {
+ fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] ", op, op->ob_refcnt);
+ if (PyObject_Print(op, fp, 0) != 0)
+ PyErr_Clear();
+ putc('\n', fp);
+ }
}
/* Print the addresses of all live objects. Unlike _Py_PrintReferences, this
@@ -2233,40 +2233,40 @@ _Py_PrintReferences(FILE *fp)
void
_Py_PrintReferenceAddresses(FILE *fp)
{
- PyObject *op;
- fprintf(fp, "Remaining object addresses:\n");
- for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
- fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
- op->ob_refcnt, Py_TYPE(op)->tp_name);
+ PyObject *op;
+ fprintf(fp, "Remaining object addresses:\n");
+ for (op = refchain._ob_next; op != &refchain; op = op->_ob_next)
+ fprintf(fp, "%p [%" PY_FORMAT_SIZE_T "d] %s\n", op,
+ op->ob_refcnt, Py_TYPE(op)->tp_name);
}
PyObject *
_Py_GetObjects(PyObject *self, PyObject *args)
{
- int i, n;
- PyObject *t = NULL;
- PyObject *res, *op;
-
- if (!PyArg_ParseTuple(args, "i|O", &n, &t))
- return NULL;
- op = refchain._ob_next;
- res = PyList_New(0);
- if (res == NULL)
- return NULL;
- for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
- while (op == self || op == args || op == res || op == t ||
- (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
- op = op->_ob_next;
- if (op == &refchain)
- return res;
- }
- if (PyList_Append(res, op) < 0) {
- Py_DECREF(res);
- return NULL;
- }
- op = op->_ob_next;
- }
- return res;
+ int i, n;
+ PyObject *t = NULL;
+ PyObject *res, *op;
+
+ if (!PyArg_ParseTuple(args, "i|O", &n, &t))
+ return NULL;
+ op = refchain._ob_next;
+ res = PyList_New(0);
+ if (res == NULL)
+ return NULL;
+ for (i = 0; (n == 0 || i < n) && op != &refchain; i++) {
+ while (op == self || op == args || op == res || op == t ||
+ (t != NULL && Py_TYPE(op) != (PyTypeObject *) t)) {
+ op = op->_ob_next;
+ if (op == &refchain)
+ return res;
+ }
+ if (PyList_Append(res, op) < 0) {
+ Py_DECREF(res);
+ return NULL;
+ }
+ op = op->_ob_next;
+ }
+ return res;
}
#endif
@@ -2289,19 +2289,19 @@ Py_ssize_t (*_Py_abstract_hack)(PyObject *) = PyObject_Size;
void *
PyMem_Malloc(size_t nbytes)
{
- return PyMem_MALLOC(nbytes);
+ return PyMem_MALLOC(nbytes);
}
void *
PyMem_Realloc(void *p, size_t nbytes)
{
- return PyMem_REALLOC(p, nbytes);
+ return PyMem_REALLOC(p, nbytes);
}
void
PyMem_Free(void *p)
{
- PyMem_FREE(p);
+ PyMem_FREE(p);
}
@@ -2322,52 +2322,52 @@ PyMem_Free(void *p)
int
Py_ReprEnter(PyObject *obj)
{
- PyObject *dict;
- PyObject *list;
- Py_ssize_t i;
-
- dict = PyThreadState_GetDict();
- if (dict == NULL)
- return 0;
- list = PyDict_GetItemString(dict, KEY);
- if (list == NULL) {
- list = PyList_New(0);
- if (list == NULL)
- return -1;
- if (PyDict_SetItemString(dict, KEY, list) < 0)
- return -1;
- Py_DECREF(list);
- }
- i = PyList_GET_SIZE(list);
- while (--i >= 0) {
- if (PyList_GET_ITEM(list, i) == obj)
- return 1;
- }
- PyList_Append(list, obj);
- return 0;
+ PyObject *dict;
+ PyObject *list;
+ Py_ssize_t i;
+
+ dict = PyThreadState_GetDict();
+ if (dict == NULL)
+ return 0;
+ list = PyDict_GetItemString(dict, KEY);
+ if (list == NULL) {
+ list = PyList_New(0);
+ if (list == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, KEY, list) < 0)
+ return -1;
+ Py_DECREF(list);
+ }
+ i = PyList_GET_SIZE(list);
+ while (--i >= 0) {
+ if (PyList_GET_ITEM(list, i) == obj)
+ return 1;
+ }
+ PyList_Append(list, obj);
+ return 0;
}
void
Py_ReprLeave(PyObject *obj)
{
- PyObject *dict;
- PyObject *list;
- Py_ssize_t i;
-
- dict = PyThreadState_GetDict();
- if (dict == NULL)
- return;
- list = PyDict_GetItemString(dict, KEY);
- if (list == NULL || !PyList_Check(list))
- return;
- i = PyList_GET_SIZE(list);
- /* Count backwards because we always expect obj to be list[-1] */
- while (--i >= 0) {
- if (PyList_GET_ITEM(list, i) == obj) {
- PyList_SetSlice(list, i, i + 1, NULL);
- break;
- }
- }
+ PyObject *dict;
+ PyObject *list;
+ Py_ssize_t i;
+
+ dict = PyThreadState_GetDict();
+ if (dict == NULL)
+ return;
+ list = PyDict_GetItemString(dict, KEY);
+ if (list == NULL || !PyList_Check(list))
+ return;
+ i = PyList_GET_SIZE(list);
+ /* Count backwards because we always expect obj to be list[-1] */
+ while (--i >= 0) {
+ if (PyList_GET_ITEM(list, i) == obj) {
+ PyList_SetSlice(list, i, i + 1, NULL);
+ break;
+ }
+ }
}
/* Trashcan support. */
@@ -2387,11 +2387,11 @@ PyObject *_PyTrash_delete_later = NULL;
void
_PyTrash_deposit_object(PyObject *op)
{
- assert(PyObject_IS_GC(op));
- assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
- assert(op->ob_refcnt == 0);
- _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
- _PyTrash_delete_later = op;
+ assert(PyObject_IS_GC(op));
+ assert(_Py_AS_GC(op)->gc.gc_refs == _PyGC_REFS_UNTRACKED);
+ assert(op->ob_refcnt == 0);
+ _Py_AS_GC(op)->gc.gc_prev = (PyGC_Head *)_PyTrash_delete_later;
+ _PyTrash_delete_later = op;
}
/* Dealloccate all the objects in the _PyTrash_delete_later list. Called when
@@ -2400,24 +2400,24 @@ _PyTrash_deposit_object(PyObject *op)
void
_PyTrash_destroy_chain(void)
{
- while (_PyTrash_delete_later) {
- PyObject *op = _PyTrash_delete_later;
- destructor dealloc = Py_TYPE(op)->tp_dealloc;
-
- _PyTrash_delete_later =
- (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
-
- /* Call the deallocator directly. This used to try to
- * fool Py_DECREF into calling it indirectly, but
- * Py_DECREF was already called on this object, and in
- * assorted non-release builds calling Py_DECREF again ends
- * up distorting allocation statistics.
- */
- assert(op->ob_refcnt == 0);
- ++_PyTrash_delete_nesting;
- (*dealloc)(op);
- --_PyTrash_delete_nesting;
- }
+ while (_PyTrash_delete_later) {
+ PyObject *op = _PyTrash_delete_later;
+ destructor dealloc = Py_TYPE(op)->tp_dealloc;
+
+ _PyTrash_delete_later =
+ (PyObject*) _Py_AS_GC(op)->gc.gc_prev;
+
+ /* Call the deallocator directly. This used to try to
+ * fool Py_DECREF into calling it indirectly, but
+ * Py_DECREF was already called on this object, and in
+ * assorted non-release builds calling Py_DECREF again ends
+ * up distorting allocation statistics.
+ */
+ assert(op->ob_refcnt == 0);
+ ++_PyTrash_delete_nesting;
+ (*dealloc)(op);
+ --_PyTrash_delete_nesting;
+ }
}
#ifdef __cplusplus
diff --git a/Objects/obmalloc.c b/Objects/obmalloc.c
index c8c36d5..506b1c1 100644
--- a/Objects/obmalloc.c
+++ b/Objects/obmalloc.c
@@ -27,7 +27,7 @@ static int running_on_valgrind = -1;
the cyclic garbage collector operates selectively on container objects.
- Object-specific allocators
+ Object-specific allocators
_____ ______ ______ ________
[ int ] [ dict ] [ list ] ... [ string ] Python core |
+3 | <----- Object-specific memory -----> | <-- Non-object memory --> |
@@ -67,7 +67,7 @@ static int running_on_valgrind = -1;
* in Proc. 1995 Int'l. Workshop on Memory Management, September 1995.
*/
-/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
+/* #undef WITH_MEMORY_LIMITS */ /* disable mem limit checks */
/*==========================================================================*/
@@ -95,22 +95,22 @@ static int running_on_valgrind = -1;
*
* For small requests we have the following table:
*
- * Request in bytes Size of allocated block Size class idx
+ * Request in bytes Size of allocated block Size class idx
* ----------------------------------------------------------------
* 1-8 8 0
- * 9-16 16 1
- * 17-24 24 2
- * 25-32 32 3
- * 33-40 40 4
- * 41-48 48 5
- * 49-56 56 6
- * 57-64 64 7
- * 65-72 72 8
- * ... ... ...
- * 241-248 248 30
- * 249-256 256 31
+ * 9-16 16 1
+ * 17-24 24 2
+ * 25-32 32 3
+ * 33-40 40 4
+ * 41-48 48 5
+ * 49-56 56 6
+ * 57-64 64 7
+ * 65-72 72 8
+ * ... ... ...
+ * 241-248 248 30
+ * 249-256 256 31
*
- * 0, 257 and up: routed to the underlying allocator.
+ * 0, 257 and up: routed to the underlying allocator.
*/
/*==========================================================================*/
@@ -127,9 +127,9 @@ static int running_on_valgrind = -1;
*
* You shouldn't change this unless you know what you are doing.
*/
-#define ALIGNMENT 8 /* must be 2^N */
-#define ALIGNMENT_SHIFT 3
-#define ALIGNMENT_MASK (ALIGNMENT - 1)
+#define ALIGNMENT 8 /* must be 2^N */
+#define ALIGNMENT_SHIFT 3
+#define ALIGNMENT_MASK (ALIGNMENT - 1)
/* Return the number of bytes in size class I, as a uint. */
#define INDEX2SIZE(I) (((uint)(I) + 1) << ALIGNMENT_SHIFT)
@@ -140,14 +140,14 @@ static int running_on_valgrind = -1;
* this value according to your application behaviour and memory needs.
*
* The following invariants must hold:
- * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256
- * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
+ * 1) ALIGNMENT <= SMALL_REQUEST_THRESHOLD <= 256
+ * 2) SMALL_REQUEST_THRESHOLD is evenly divisible by ALIGNMENT
*
* Although not required, for better performance and space efficiency,
* it is recommended that SMALL_REQUEST_THRESHOLD is set to a power of 2.
*/
-#define SMALL_REQUEST_THRESHOLD 256
-#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
+#define SMALL_REQUEST_THRESHOLD 256
+#define NB_SMALL_SIZE_CLASSES (SMALL_REQUEST_THRESHOLD / ALIGNMENT)
/*
* The system's VMM page size can be obtained on most unices with a
@@ -159,15 +159,15 @@ static int running_on_valgrind = -1;
* violation fault. 4K is apparently OK for all the platforms that python
* currently targets.
*/
-#define SYSTEM_PAGE_SIZE (4 * 1024)
-#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
+#define SYSTEM_PAGE_SIZE (4 * 1024)
+#define SYSTEM_PAGE_SIZE_MASK (SYSTEM_PAGE_SIZE - 1)
/*
* Maximum amount of memory managed by the allocator for small requests.
*/
#ifdef WITH_MEMORY_LIMITS
#ifndef SMALL_MEMORY_LIMIT
-#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
+#define SMALL_MEMORY_LIMIT (64 * 1024 * 1024) /* 64 MB -- more? */
#endif
#endif
@@ -184,18 +184,18 @@ static int running_on_valgrind = -1;
* some address space wastage, but this is the most portable way to request
* memory from the system across various platforms.
*/
-#define ARENA_SIZE (256 << 10) /* 256KB */
+#define ARENA_SIZE (256 << 10) /* 256KB */
#ifdef WITH_MEMORY_LIMITS
-#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
+#define MAX_ARENAS (SMALL_MEMORY_LIMIT / ARENA_SIZE)
#endif
/*
* Size of the pools used for small blocks. Should be a power of 2,
* between 1K and SYSTEM_PAGE_SIZE, that is: 1k, 2k, 4k.
*/
-#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
-#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
+#define POOL_SIZE SYSTEM_PAGE_SIZE /* must be 2^N */
+#define POOL_SIZE_MASK SYSTEM_PAGE_SIZE_MASK
/*
* -- End of tunable settings section --
@@ -221,92 +221,92 @@ static int running_on_valgrind = -1;
/*
* Python's threads are serialized, so object malloc locking is disabled.
*/
-#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
-#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
-#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
-#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
-#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
+#define SIMPLELOCK_DECL(lock) /* simple lock declaration */
+#define SIMPLELOCK_INIT(lock) /* allocate (if needed) and initialize */
+#define SIMPLELOCK_FINI(lock) /* free/destroy an existing lock */
+#define SIMPLELOCK_LOCK(lock) /* acquire released lock */
+#define SIMPLELOCK_UNLOCK(lock) /* release acquired lock */
/*
* Basic types
* I don't care if these are defined in <sys/types.h> or elsewhere. Axiom.
*/
#undef uchar
-#define uchar unsigned char /* assuming == 8 bits */
+#define uchar unsigned char /* assuming == 8 bits */
#undef uint
-#define uint unsigned int /* assuming >= 16 bits */
+#define uint unsigned int /* assuming >= 16 bits */
#undef ulong
-#define ulong unsigned long /* assuming >= 32 bits */
+#define ulong unsigned long /* assuming >= 32 bits */
#undef uptr
-#define uptr Py_uintptr_t
+#define uptr Py_uintptr_t
/* When you say memory, my mind reasons in terms of (pointers to) blocks */
typedef uchar block;
/* Pool for small blocks. */
struct pool_header {
- union { block *_padding;
- uint count; } ref; /* number of allocated blocks */
- block *freeblock; /* pool's free list head */
- struct pool_header *nextpool; /* next pool of this size class */
- struct pool_header *prevpool; /* previous pool "" */
- uint arenaindex; /* index into arenas of base adr */
- uint szidx; /* block size class index */
- uint nextoffset; /* bytes to virgin block */
- uint maxnextoffset; /* largest valid nextoffset */
+ union { block *_padding;
+ uint count; } ref; /* number of allocated blocks */
+ block *freeblock; /* pool's free list head */
+ struct pool_header *nextpool; /* next pool of this size class */
+ struct pool_header *prevpool; /* previous pool "" */
+ uint arenaindex; /* index into arenas of base adr */
+ uint szidx; /* block size class index */
+ uint nextoffset; /* bytes to virgin block */
+ uint maxnextoffset; /* largest valid nextoffset */
};
typedef struct pool_header *poolp;
/* Record keeping for arenas. */
struct arena_object {
- /* The address of the arena, as returned by malloc. Note that 0
- * will never be returned by a successful malloc, and is used
- * here to mark an arena_object that doesn't correspond to an
- * allocated arena.
- */
- uptr address;
-
- /* Pool-aligned pointer to the next pool to be carved off. */
- block* pool_address;
-
- /* The number of available pools in the arena: free pools + never-
- * allocated pools.
- */
- uint nfreepools;
-
- /* The total number of pools in the arena, whether or not available. */
- uint ntotalpools;
-
- /* Singly-linked list of available pools. */
- struct pool_header* freepools;
-
- /* Whenever this arena_object is not associated with an allocated
- * arena, the nextarena member is used to link all unassociated
- * arena_objects in the singly-linked `unused_arena_objects` list.
- * The prevarena member is unused in this case.
- *
- * When this arena_object is associated with an allocated arena
- * with at least one available pool, both members are used in the
- * doubly-linked `usable_arenas` list, which is maintained in
- * increasing order of `nfreepools` values.
- *
- * Else this arena_object is associated with an allocated arena
- * all of whose pools are in use. `nextarena` and `prevarena`
- * are both meaningless in this case.
- */
- struct arena_object* nextarena;
- struct arena_object* prevarena;
+ /* The address of the arena, as returned by malloc. Note that 0
+ * will never be returned by a successful malloc, and is used
+ * here to mark an arena_object that doesn't correspond to an
+ * allocated arena.
+ */
+ uptr address;
+
+ /* Pool-aligned pointer to the next pool to be carved off. */
+ block* pool_address;
+
+ /* The number of available pools in the arena: free pools + never-
+ * allocated pools.
+ */
+ uint nfreepools;
+
+ /* The total number of pools in the arena, whether or not available. */
+ uint ntotalpools;
+
+ /* Singly-linked list of available pools. */
+ struct pool_header* freepools;
+
+ /* Whenever this arena_object is not associated with an allocated
+ * arena, the nextarena member is used to link all unassociated
+ * arena_objects in the singly-linked `unused_arena_objects` list.
+ * The prevarena member is unused in this case.
+ *
+ * When this arena_object is associated with an allocated arena
+ * with at least one available pool, both members are used in the
+ * doubly-linked `usable_arenas` list, which is maintained in
+ * increasing order of `nfreepools` values.
+ *
+ * Else this arena_object is associated with an allocated arena
+ * all of whose pools are in use. `nextarena` and `prevarena`
+ * are both meaningless in this case.
+ */
+ struct arena_object* nextarena;
+ struct arena_object* prevarena;
};
#undef ROUNDUP
-#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
-#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
+#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
+#define POOL_OVERHEAD ROUNDUP(sizeof(struct pool_header))
-#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
+#define DUMMY_SIZE_IDX 0xffff /* size class of newly cached pools */
/* Round pointer P down to the closest pool-aligned address <= P, as a poolp */
#define POOL_ADDR(P) ((poolp)((uptr)(P) & ~(uptr)POOL_SIZE_MASK))
@@ -320,10 +320,10 @@ struct arena_object {
* This malloc lock
*/
SIMPLELOCK_DECL(_malloc_lock)
-#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
-#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
-#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
-#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
+#define LOCK() SIMPLELOCK_LOCK(_malloc_lock)
+#define UNLOCK() SIMPLELOCK_UNLOCK(_malloc_lock)
+#define LOCK_INIT() SIMPLELOCK_INIT(_malloc_lock)
+#define LOCK_FINI() SIMPLELOCK_FINI(_malloc_lock)
/*
* Pool table -- headed, circular, doubly-linked lists of partially used pools.
@@ -403,9 +403,9 @@ nextpool and prevpool members. The "- 2*sizeof(block *)" gibberish is
compensating for that a pool_header's nextpool and prevpool members
immediately follow a pool_header's first two members:
- union { block *_padding;
- uint count; } ref;
- block *freeblock;
+ union { block *_padding;
+ uint count; } ref;
+ block *freeblock;
each of which consume sizeof(block *) bytes. So what usedpools[i+i] really
contains is a fudged-up pointer p such that *if* C believes it's a poolp
@@ -421,25 +421,25 @@ on that C doesn't insert any padding anywhere in a pool_header at or before
the prevpool member.
**************************************************************************** */
-#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
-#define PT(x) PTA(x), PTA(x)
+#define PTA(x) ((poolp )((uchar *)&(usedpools[2*(x)]) - 2*sizeof(block *)))
+#define PT(x) PTA(x), PTA(x)
static poolp usedpools[2 * ((NB_SMALL_SIZE_CLASSES + 7) / 8) * 8] = {
- PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
+ PT(0), PT(1), PT(2), PT(3), PT(4), PT(5), PT(6), PT(7)
#if NB_SMALL_SIZE_CLASSES > 8
- , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
+ , PT(8), PT(9), PT(10), PT(11), PT(12), PT(13), PT(14), PT(15)
#if NB_SMALL_SIZE_CLASSES > 16
- , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
+ , PT(16), PT(17), PT(18), PT(19), PT(20), PT(21), PT(22), PT(23)
#if NB_SMALL_SIZE_CLASSES > 24
- , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
+ , PT(24), PT(25), PT(26), PT(27), PT(28), PT(29), PT(30), PT(31)
#if NB_SMALL_SIZE_CLASSES > 32
- , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
+ , PT(32), PT(33), PT(34), PT(35), PT(36), PT(37), PT(38), PT(39)
#if NB_SMALL_SIZE_CLASSES > 40
- , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
+ , PT(40), PT(41), PT(42), PT(43), PT(44), PT(45), PT(46), PT(47)
#if NB_SMALL_SIZE_CLASSES > 48
- , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
+ , PT(48), PT(49), PT(50), PT(51), PT(52), PT(53), PT(54), PT(55)
#if NB_SMALL_SIZE_CLASSES > 56
- , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
+ , PT(56), PT(57), PT(58), PT(59), PT(60), PT(61), PT(62), PT(63)
#endif /* NB_SMALL_SIZE_CLASSES > 56 */
#endif /* NB_SMALL_SIZE_CLASSES > 48 */
#endif /* NB_SMALL_SIZE_CLASSES > 40 */
@@ -523,90 +523,90 @@ static size_t narenas_highwater = 0;
static struct arena_object*
new_arena(void)
{
- struct arena_object* arenaobj;
- uint excess; /* number of bytes above pool alignment */
+ struct arena_object* arenaobj;
+ uint excess; /* number of bytes above pool alignment */
#ifdef PYMALLOC_DEBUG
- if (Py_GETENV("PYTHONMALLOCSTATS"))
- _PyObject_DebugMallocStats();
+ if (Py_GETENV("PYTHONMALLOCSTATS"))
+ _PyObject_DebugMallocStats();
#endif
- if (unused_arena_objects == NULL) {
- uint i;
- uint numarenas;
- size_t nbytes;
-
- /* Double the number of arena objects on each allocation.
- * Note that it's possible for `numarenas` to overflow.
- */
- numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
- if (numarenas <= maxarenas)
- return NULL; /* overflow */
+ if (unused_arena_objects == NULL) {
+ uint i;
+ uint numarenas;
+ size_t nbytes;
+
+ /* Double the number of arena objects on each allocation.
+ * Note that it's possible for `numarenas` to overflow.
+ */
+ numarenas = maxarenas ? maxarenas << 1 : INITIAL_ARENA_OBJECTS;
+ if (numarenas <= maxarenas)
+ return NULL; /* overflow */
#if SIZEOF_SIZE_T <= SIZEOF_INT
- if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
- return NULL; /* overflow */
+ if (numarenas > PY_SIZE_MAX / sizeof(*arenas))
+ return NULL; /* overflow */
#endif
- nbytes = numarenas * sizeof(*arenas);
- arenaobj = (struct arena_object *)realloc(arenas, nbytes);
- if (arenaobj == NULL)
- return NULL;
- arenas = arenaobj;
-
- /* We might need to fix pointers that were copied. However,
- * new_arena only gets called when all the pages in the
- * previous arenas are full. Thus, there are *no* pointers
- * into the old array. Thus, we don't have to worry about
- * invalid pointers. Just to be sure, some asserts:
- */
- assert(usable_arenas == NULL);
- assert(unused_arena_objects == NULL);
-
- /* Put the new arenas on the unused_arena_objects list. */
- for (i = maxarenas; i < numarenas; ++i) {
- arenas[i].address = 0; /* mark as unassociated */
- arenas[i].nextarena = i < numarenas - 1 ?
- &arenas[i+1] : NULL;
- }
-
- /* Update globals. */
- unused_arena_objects = &arenas[maxarenas];
- maxarenas = numarenas;
- }
-
- /* Take the next available arena object off the head of the list. */
- assert(unused_arena_objects != NULL);
- arenaobj = unused_arena_objects;
- unused_arena_objects = arenaobj->nextarena;
- assert(arenaobj->address == 0);
- arenaobj->address = (uptr)malloc(ARENA_SIZE);
- if (arenaobj->address == 0) {
- /* The allocation failed: return NULL after putting the
- * arenaobj back.
- */
- arenaobj->nextarena = unused_arena_objects;
- unused_arena_objects = arenaobj;
- return NULL;
- }
-
- ++narenas_currently_allocated;
+ nbytes = numarenas * sizeof(*arenas);
+ arenaobj = (struct arena_object *)realloc(arenas, nbytes);
+ if (arenaobj == NULL)
+ return NULL;
+ arenas = arenaobj;
+
+ /* We might need to fix pointers that were copied. However,
+ * new_arena only gets called when all the pages in the
+ * previous arenas are full. Thus, there are *no* pointers
+ * into the old array. Thus, we don't have to worry about
+ * invalid pointers. Just to be sure, some asserts:
+ */
+ assert(usable_arenas == NULL);
+ assert(unused_arena_objects == NULL);
+
+ /* Put the new arenas on the unused_arena_objects list. */
+ for (i = maxarenas; i < numarenas; ++i) {
+ arenas[i].address = 0; /* mark as unassociated */
+ arenas[i].nextarena = i < numarenas - 1 ?
+ &arenas[i+1] : NULL;
+ }
+
+ /* Update globals. */
+ unused_arena_objects = &arenas[maxarenas];
+ maxarenas = numarenas;
+ }
+
+ /* Take the next available arena object off the head of the list. */
+ assert(unused_arena_objects != NULL);
+ arenaobj = unused_arena_objects;
+ unused_arena_objects = arenaobj->nextarena;
+ assert(arenaobj->address == 0);
+ arenaobj->address = (uptr)malloc(ARENA_SIZE);
+ if (arenaobj->address == 0) {
+ /* The allocation failed: return NULL after putting the
+ * arenaobj back.
+ */
+ arenaobj->nextarena = unused_arena_objects;
+ unused_arena_objects = arenaobj;
+ return NULL;
+ }
+
+ ++narenas_currently_allocated;
#ifdef PYMALLOC_DEBUG
- ++ntimes_arena_allocated;
- if (narenas_currently_allocated > narenas_highwater)
- narenas_highwater = narenas_currently_allocated;
+ ++ntimes_arena_allocated;
+ if (narenas_currently_allocated > narenas_highwater)
+ narenas_highwater = narenas_currently_allocated;
#endif
- arenaobj->freepools = NULL;
- /* pool_address <- first pool-aligned address in the arena
- nfreepools <- number of whole pools that fit after alignment */
- arenaobj->pool_address = (block*)arenaobj->address;
- arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
- assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
- excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
- if (excess != 0) {
- --arenaobj->nfreepools;
- arenaobj->pool_address += POOL_SIZE - excess;
- }
- arenaobj->ntotalpools = arenaobj->nfreepools;
-
- return arenaobj;
+ arenaobj->freepools = NULL;
+ /* pool_address <- first pool-aligned address in the arena
+ nfreepools <- number of whole pools that fit after alignment */
+ arenaobj->pool_address = (block*)arenaobj->address;
+ arenaobj->nfreepools = ARENA_SIZE / POOL_SIZE;
+ assert(POOL_SIZE * arenaobj->nfreepools == ARENA_SIZE);
+ excess = (uint)(arenaobj->address & POOL_SIZE_MASK);
+ if (excess != 0) {
+ --arenaobj->nfreepools;
+ arenaobj->pool_address += POOL_SIZE - excess;
+ }
+ arenaobj->ntotalpools = arenaobj->nfreepools;
+
+ return arenaobj;
}
/*
@@ -622,11 +622,11 @@ called on every alloc/realloc/free, micro-efficiency is important here).
Tricky: Let B be the arena base address associated with the pool, B =
arenas[(POOL)->arenaindex].address. Then P belongs to the arena if and only if
- B <= P < B + ARENA_SIZE
+ B <= P < B + ARENA_SIZE
Subtracting B throughout, this is true iff
- 0 <= P-B < ARENA_SIZE
+ 0 <= P-B < ARENA_SIZE
By using unsigned arithmetic, the "0 <=" half of the test can be skipped.
@@ -660,7 +660,7 @@ Finally, if P is not controlled by obmalloc and AO corresponds to an unused
arena_object (one not currently associated with an allocated arena),
AO.address is 0, and the second test in the macro reduces to:
- P < ARENA_SIZE
+ P < ARENA_SIZE
If P >= ARENA_SIZE (extremely likely), the macro again correctly concludes
that P is not controlled by obmalloc. However, if P < ARENA_SIZE, this part
@@ -683,10 +683,10 @@ obmalloc in a small constant time, independent of the number of arenas
obmalloc controls. Since this test is needed at every entry point, it's
extremely desirable that it be this fast.
*/
-#define Py_ADDRESS_IN_RANGE(P, POOL) \
- ((POOL)->arenaindex < maxarenas && \
- (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \
- arenas[(POOL)->arenaindex].address != 0)
+#define Py_ADDRESS_IN_RANGE(P, POOL) \
+ ((POOL)->arenaindex < maxarenas && \
+ (uptr)(P) - arenas[(POOL)->arenaindex].address < (uptr)ARENA_SIZE && \
+ arenas[(POOL)->arenaindex].address != 0)
/* This is only useful when running memory debuggers such as
@@ -709,7 +709,7 @@ extremely desirable that it be this fast.
#undef Py_ADDRESS_IN_RANGE
#if defined(__GNUC__) && ((__GNUC__ == 3) && (__GNUC_MINOR__ >= 1) || \
- (__GNUC__ >= 4))
+ (__GNUC__ >= 4))
#define Py_NO_INLINE __attribute__((__noinline__))
#else
#define Py_NO_INLINE
@@ -738,201 +738,201 @@ int Py_ADDRESS_IN_RANGE(void *P, poolp pool) Py_NO_INLINE;
void *
PyObject_Malloc(size_t nbytes)
{
- block *bp;
- poolp pool;
- poolp next;
- uint size;
+ block *bp;
+ poolp pool;
+ poolp next;
+ uint size;
#ifdef WITH_VALGRIND
- if (UNLIKELY(running_on_valgrind == -1))
- running_on_valgrind = RUNNING_ON_VALGRIND;
- if (UNLIKELY(running_on_valgrind))
- goto redirect;
+ if (UNLIKELY(running_on_valgrind == -1))
+ running_on_valgrind = RUNNING_ON_VALGRIND;
+ if (UNLIKELY(running_on_valgrind))
+ goto redirect;
#endif
- /*
- * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
- * Most python internals blindly use a signed Py_ssize_t to track
- * things without checking for overflows or negatives.
- * As size_t is unsigned, checking for nbytes < 0 is not required.
- */
- if (nbytes > PY_SSIZE_T_MAX)
- return NULL;
-
- /*
- * This implicitly redirects malloc(0).
- */
- if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
- LOCK();
- /*
- * Most frequent paths first
- */
- size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
- pool = usedpools[size + size];
- if (pool != pool->nextpool) {
- /*
- * There is a used pool for this size class.
- * Pick up the head block of its free list.
- */
- ++pool->ref.count;
- bp = pool->freeblock;
- assert(bp != NULL);
- if ((pool->freeblock = *(block **)bp) != NULL) {
- UNLOCK();
- return (void *)bp;
- }
- /*
- * Reached the end of the free list, try to extend it.
- */
- if (pool->nextoffset <= pool->maxnextoffset) {
- /* There is room for another block. */
- pool->freeblock = (block*)pool +
- pool->nextoffset;
- pool->nextoffset += INDEX2SIZE(size);
- *(block **)(pool->freeblock) = NULL;
- UNLOCK();
- return (void *)bp;
- }
- /* Pool is full, unlink from used pools. */
- next = pool->nextpool;
- pool = pool->prevpool;
- next->prevpool = pool;
- pool->nextpool = next;
- UNLOCK();
- return (void *)bp;
- }
-
- /* There isn't a pool of the right size class immediately
- * available: use a free pool.
- */
- if (usable_arenas == NULL) {
- /* No arena has a free pool: allocate a new arena. */
+ /*
+ * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
+ * Most python internals blindly use a signed Py_ssize_t to track
+ * things without checking for overflows or negatives.
+ * As size_t is unsigned, checking for nbytes < 0 is not required.
+ */
+ if (nbytes > PY_SSIZE_T_MAX)
+ return NULL;
+
+ /*
+ * This implicitly redirects malloc(0).
+ */
+ if ((nbytes - 1) < SMALL_REQUEST_THRESHOLD) {
+ LOCK();
+ /*
+ * Most frequent paths first
+ */
+ size = (uint)(nbytes - 1) >> ALIGNMENT_SHIFT;
+ pool = usedpools[size + size];
+ if (pool != pool->nextpool) {
+ /*
+ * There is a used pool for this size class.
+ * Pick up the head block of its free list.
+ */
+ ++pool->ref.count;
+ bp = pool->freeblock;
+ assert(bp != NULL);
+ if ((pool->freeblock = *(block **)bp) != NULL) {
+ UNLOCK();
+ return (void *)bp;
+ }
+ /*
+ * Reached the end of the free list, try to extend it.
+ */
+ if (pool->nextoffset <= pool->maxnextoffset) {
+ /* There is room for another block. */
+ pool->freeblock = (block*)pool +
+ pool->nextoffset;
+ pool->nextoffset += INDEX2SIZE(size);
+ *(block **)(pool->freeblock) = NULL;
+ UNLOCK();
+ return (void *)bp;
+ }
+ /* Pool is full, unlink from used pools. */
+ next = pool->nextpool;
+ pool = pool->prevpool;
+ next->prevpool = pool;
+ pool->nextpool = next;
+ UNLOCK();
+ return (void *)bp;
+ }
+
+ /* There isn't a pool of the right size class immediately
+ * available: use a free pool.
+ */
+ if (usable_arenas == NULL) {
+ /* No arena has a free pool: allocate a new arena. */
#ifdef WITH_MEMORY_LIMITS
- if (narenas_currently_allocated >= MAX_ARENAS) {
- UNLOCK();
- goto redirect;
- }
+ if (narenas_currently_allocated >= MAX_ARENAS) {
+ UNLOCK();
+ goto redirect;
+ }
#endif
- usable_arenas = new_arena();
- if (usable_arenas == NULL) {
- UNLOCK();
- goto redirect;
- }
- usable_arenas->nextarena =
- usable_arenas->prevarena = NULL;
- }
- assert(usable_arenas->address != 0);
-
- /* Try to get a cached free pool. */
- pool = usable_arenas->freepools;
- if (pool != NULL) {
- /* Unlink from cached pools. */
- usable_arenas->freepools = pool->nextpool;
-
- /* This arena already had the smallest nfreepools
- * value, so decreasing nfreepools doesn't change
- * that, and we don't need to rearrange the
- * usable_arenas list. However, if the arena has
- * become wholly allocated, we need to remove its
- * arena_object from usable_arenas.
- */
- --usable_arenas->nfreepools;
- if (usable_arenas->nfreepools == 0) {
- /* Wholly allocated: remove. */
- assert(usable_arenas->freepools == NULL);
- assert(usable_arenas->nextarena == NULL ||
- usable_arenas->nextarena->prevarena ==
- usable_arenas);
-
- usable_arenas = usable_arenas->nextarena;
- if (usable_arenas != NULL) {
- usable_arenas->prevarena = NULL;
- assert(usable_arenas->address != 0);
- }
- }
- else {
- /* nfreepools > 0: it must be that freepools
- * isn't NULL, or that we haven't yet carved
- * off all the arena's pools for the first
- * time.
- */
- assert(usable_arenas->freepools != NULL ||
- usable_arenas->pool_address <=
- (block*)usable_arenas->address +
- ARENA_SIZE - POOL_SIZE);
- }
- init_pool:
- /* Frontlink to used pools. */
- next = usedpools[size + size]; /* == prev */
- pool->nextpool = next;
- pool->prevpool = next;
- next->nextpool = pool;
- next->prevpool = pool;
- pool->ref.count = 1;
- if (pool->szidx == size) {
- /* Luckily, this pool last contained blocks
- * of the same size class, so its header
- * and free list are already initialized.
- */
- bp = pool->freeblock;
- pool->freeblock = *(block **)bp;
- UNLOCK();
- return (void *)bp;
- }
- /*
- * Initialize the pool header, set up the free list to
- * contain just the second block, and return the first
- * block.
- */
- pool->szidx = size;
- size = INDEX2SIZE(size);
- bp = (block *)pool + POOL_OVERHEAD;
- pool->nextoffset = POOL_OVERHEAD + (size << 1);
- pool->maxnextoffset = POOL_SIZE - size;
- pool->freeblock = bp + size;
- *(block **)(pool->freeblock) = NULL;
- UNLOCK();
- return (void *)bp;
- }
-
- /* Carve off a new pool. */
- assert(usable_arenas->nfreepools > 0);
- assert(usable_arenas->freepools == NULL);
- pool = (poolp)usable_arenas->pool_address;
- assert((block*)pool <= (block*)usable_arenas->address +
- ARENA_SIZE - POOL_SIZE);
- pool->arenaindex = usable_arenas - arenas;
- assert(&arenas[pool->arenaindex] == usable_arenas);
- pool->szidx = DUMMY_SIZE_IDX;
- usable_arenas->pool_address += POOL_SIZE;
- --usable_arenas->nfreepools;
-
- if (usable_arenas->nfreepools == 0) {
- assert(usable_arenas->nextarena == NULL ||
- usable_arenas->nextarena->prevarena ==
- usable_arenas);
- /* Unlink the arena: it is completely allocated. */
- usable_arenas = usable_arenas->nextarena;
- if (usable_arenas != NULL) {
- usable_arenas->prevarena = NULL;
- assert(usable_arenas->address != 0);
- }
- }
-
- goto init_pool;
- }
-
- /* The small block allocator ends here. */
+ usable_arenas = new_arena();
+ if (usable_arenas == NULL) {
+ UNLOCK();
+ goto redirect;
+ }
+ usable_arenas->nextarena =
+ usable_arenas->prevarena = NULL;
+ }
+ assert(usable_arenas->address != 0);
+
+ /* Try to get a cached free pool. */
+ pool = usable_arenas->freepools;
+ if (pool != NULL) {
+ /* Unlink from cached pools. */
+ usable_arenas->freepools = pool->nextpool;
+
+ /* This arena already had the smallest nfreepools
+ * value, so decreasing nfreepools doesn't change
+ * that, and we don't need to rearrange the
+ * usable_arenas list. However, if the arena has
+ * become wholly allocated, we need to remove its
+ * arena_object from usable_arenas.
+ */
+ --usable_arenas->nfreepools;
+ if (usable_arenas->nfreepools == 0) {
+ /* Wholly allocated: remove. */
+ assert(usable_arenas->freepools == NULL);
+ assert(usable_arenas->nextarena == NULL ||
+ usable_arenas->nextarena->prevarena ==
+ usable_arenas);
+
+ usable_arenas = usable_arenas->nextarena;
+ if (usable_arenas != NULL) {
+ usable_arenas->prevarena = NULL;
+ assert(usable_arenas->address != 0);
+ }
+ }
+ else {
+ /* nfreepools > 0: it must be that freepools
+ * isn't NULL, or that we haven't yet carved
+ * off all the arena's pools for the first
+ * time.
+ */
+ assert(usable_arenas->freepools != NULL ||
+ usable_arenas->pool_address <=
+ (block*)usable_arenas->address +
+ ARENA_SIZE - POOL_SIZE);
+ }
+ init_pool:
+ /* Frontlink to used pools. */
+ next = usedpools[size + size]; /* == prev */
+ pool->nextpool = next;
+ pool->prevpool = next;
+ next->nextpool = pool;
+ next->prevpool = pool;
+ pool->ref.count = 1;
+ if (pool->szidx == size) {
+ /* Luckily, this pool last contained blocks
+ * of the same size class, so its header
+ * and free list are already initialized.
+ */
+ bp = pool->freeblock;
+ pool->freeblock = *(block **)bp;
+ UNLOCK();
+ return (void *)bp;
+ }
+ /*
+ * Initialize the pool header, set up the free list to
+ * contain just the second block, and return the first
+ * block.
+ */
+ pool->szidx = size;
+ size = INDEX2SIZE(size);
+ bp = (block *)pool + POOL_OVERHEAD;
+ pool->nextoffset = POOL_OVERHEAD + (size << 1);
+ pool->maxnextoffset = POOL_SIZE - size;
+ pool->freeblock = bp + size;
+ *(block **)(pool->freeblock) = NULL;
+ UNLOCK();
+ return (void *)bp;
+ }
+
+ /* Carve off a new pool. */
+ assert(usable_arenas->nfreepools > 0);
+ assert(usable_arenas->freepools == NULL);
+ pool = (poolp)usable_arenas->pool_address;
+ assert((block*)pool <= (block*)usable_arenas->address +
+ ARENA_SIZE - POOL_SIZE);
+ pool->arenaindex = usable_arenas - arenas;
+ assert(&arenas[pool->arenaindex] == usable_arenas);
+ pool->szidx = DUMMY_SIZE_IDX;
+ usable_arenas->pool_address += POOL_SIZE;
+ --usable_arenas->nfreepools;
+
+ if (usable_arenas->nfreepools == 0) {
+ assert(usable_arenas->nextarena == NULL ||
+ usable_arenas->nextarena->prevarena ==
+ usable_arenas);
+ /* Unlink the arena: it is completely allocated. */
+ usable_arenas = usable_arenas->nextarena;
+ if (usable_arenas != NULL) {
+ usable_arenas->prevarena = NULL;
+ assert(usable_arenas->address != 0);
+ }
+ }
+
+ goto init_pool;
+ }
+
+ /* The small block allocator ends here. */
redirect:
- /* Redirect the original request to the underlying (libc) allocator.
- * We jump here on bigger requests, on error in the code above (as a
- * last chance to serve the request) or when the max memory limit
- * has been reached.
- */
- if (nbytes == 0)
- nbytes = 1;
- return (void *)malloc(nbytes);
+ /* Redirect the original request to the underlying (libc) allocator.
+ * We jump here on bigger requests, on error in the code above (as a
+ * last chance to serve the request) or when the max memory limit
+ * has been reached.
+ */
+ if (nbytes == 0)
+ nbytes = 1;
+ return (void *)malloc(nbytes);
}
/* free */
@@ -941,218 +941,218 @@ redirect:
void
PyObject_Free(void *p)
{
- poolp pool;
- block *lastfree;
- poolp next, prev;
- uint size;
+ poolp pool;
+ block *lastfree;
+ poolp next, prev;
+ uint size;
- if (p == NULL) /* free(NULL) has no effect */
- return;
+ if (p == NULL) /* free(NULL) has no effect */
+ return;
#ifdef WITH_VALGRIND
- if (UNLIKELY(running_on_valgrind > 0))
- goto redirect;
+ if (UNLIKELY(running_on_valgrind > 0))
+ goto redirect;
#endif
- pool = POOL_ADDR(p);
- if (Py_ADDRESS_IN_RANGE(p, pool)) {
- /* We allocated this address. */
- LOCK();
- /* Link p to the start of the pool's freeblock list. Since
- * the pool had at least the p block outstanding, the pool
- * wasn't empty (so it's already in a usedpools[] list, or
- * was full and is in no list -- it's not in the freeblocks
- * list in any case).
- */
- assert(pool->ref.count > 0); /* else it was empty */
- *(block **)p = lastfree = pool->freeblock;
- pool->freeblock = (block *)p;
- if (lastfree) {
- struct arena_object* ao;
- uint nf; /* ao->nfreepools */
-
- /* freeblock wasn't NULL, so the pool wasn't full,
- * and the pool is in a usedpools[] list.
- */
- if (--pool->ref.count != 0) {
- /* pool isn't empty: leave it in usedpools */
- UNLOCK();
- return;
- }
- /* Pool is now empty: unlink from usedpools, and
- * link to the front of freepools. This ensures that
- * previously freed pools will be allocated later
- * (being not referenced, they are perhaps paged out).
- */
- next = pool->nextpool;
- prev = pool->prevpool;
- next->prevpool = prev;
- prev->nextpool = next;
-
- /* Link the pool to freepools. This is a singly-linked
- * list, and pool->prevpool isn't used there.
- */
- ao = &arenas[pool->arenaindex];
- pool->nextpool = ao->freepools;
- ao->freepools = pool;
- nf = ++ao->nfreepools;
-
- /* All the rest is arena management. We just freed
- * a pool, and there are 4 cases for arena mgmt:
- * 1. If all the pools are free, return the arena to
- * the system free().
- * 2. If this is the only free pool in the arena,
- * add the arena back to the `usable_arenas` list.
- * 3. If the "next" arena has a smaller count of free
- * pools, we have to "slide this arena right" to
- * restore that usable_arenas is sorted in order of
- * nfreepools.
- * 4. Else there's nothing more to do.
- */
- if (nf == ao->ntotalpools) {
- /* Case 1. First unlink ao from usable_arenas.
- */
- assert(ao->prevarena == NULL ||
- ao->prevarena->address != 0);
- assert(ao ->nextarena == NULL ||
- ao->nextarena->address != 0);
-
- /* Fix the pointer in the prevarena, or the
- * usable_arenas pointer.
- */
- if (ao->prevarena == NULL) {
- usable_arenas = ao->nextarena;
- assert(usable_arenas == NULL ||
- usable_arenas->address != 0);
- }
- else {
- assert(ao->prevarena->nextarena == ao);
- ao->prevarena->nextarena =
- ao->nextarena;
- }
- /* Fix the pointer in the nextarena. */
- if (ao->nextarena != NULL) {
- assert(ao->nextarena->prevarena == ao);
- ao->nextarena->prevarena =
- ao->prevarena;
- }
- /* Record that this arena_object slot is
- * available to be reused.
- */
- ao->nextarena = unused_arena_objects;
- unused_arena_objects = ao;
-
- /* Free the entire arena. */
- free((void *)ao->address);
- ao->address = 0; /* mark unassociated */
- --narenas_currently_allocated;
-
- UNLOCK();
- return;
- }
- if (nf == 1) {
- /* Case 2. Put ao at the head of
- * usable_arenas. Note that because
- * ao->nfreepools was 0 before, ao isn't
- * currently on the usable_arenas list.
- */
- ao->nextarena = usable_arenas;
- ao->prevarena = NULL;
- if (usable_arenas)
- usable_arenas->prevarena = ao;
- usable_arenas = ao;
- assert(usable_arenas->address != 0);
-
- UNLOCK();
- return;
- }
- /* If this arena is now out of order, we need to keep
- * the list sorted. The list is kept sorted so that
- * the "most full" arenas are used first, which allows
- * the nearly empty arenas to be completely freed. In
- * a few un-scientific tests, it seems like this
- * approach allowed a lot more memory to be freed.
- */
- if (ao->nextarena == NULL ||
- nf <= ao->nextarena->nfreepools) {
- /* Case 4. Nothing to do. */
- UNLOCK();
- return;
- }
- /* Case 3: We have to move the arena towards the end
- * of the list, because it has more free pools than
- * the arena to its right.
- * First unlink ao from usable_arenas.
- */
- if (ao->prevarena != NULL) {
- /* ao isn't at the head of the list */
- assert(ao->prevarena->nextarena == ao);
- ao->prevarena->nextarena = ao->nextarena;
- }
- else {
- /* ao is at the head of the list */
- assert(usable_arenas == ao);
- usable_arenas = ao->nextarena;
- }
- ao->nextarena->prevarena = ao->prevarena;
-
- /* Locate the new insertion point by iterating over
- * the list, using our nextarena pointer.
- */
- while (ao->nextarena != NULL &&
- nf > ao->nextarena->nfreepools) {
- ao->prevarena = ao->nextarena;
- ao->nextarena = ao->nextarena->nextarena;
- }
-
- /* Insert ao at this point. */
- assert(ao->nextarena == NULL ||
- ao->prevarena == ao->nextarena->prevarena);
- assert(ao->prevarena->nextarena == ao->nextarena);
-
- ao->prevarena->nextarena = ao;
- if (ao->nextarena != NULL)
- ao->nextarena->prevarena = ao;
-
- /* Verify that the swaps worked. */
- assert(ao->nextarena == NULL ||
- nf <= ao->nextarena->nfreepools);
- assert(ao->prevarena == NULL ||
- nf > ao->prevarena->nfreepools);
- assert(ao->nextarena == NULL ||
- ao->nextarena->prevarena == ao);
- assert((usable_arenas == ao &&
- ao->prevarena == NULL) ||
- ao->prevarena->nextarena == ao);
-
- UNLOCK();
- return;
- }
- /* Pool was full, so doesn't currently live in any list:
- * link it to the front of the appropriate usedpools[] list.
- * This mimics LRU pool usage for new allocations and
- * targets optimal filling when several pools contain
- * blocks of the same size class.
- */
- --pool->ref.count;
- assert(pool->ref.count > 0); /* else the pool is empty */
- size = pool->szidx;
- next = usedpools[size + size];
- prev = next->prevpool;
- /* insert pool before next: prev <-> pool <-> next */
- pool->nextpool = next;
- pool->prevpool = prev;
- next->prevpool = pool;
- prev->nextpool = pool;
- UNLOCK();
- return;
- }
+ pool = POOL_ADDR(p);
+ if (Py_ADDRESS_IN_RANGE(p, pool)) {
+ /* We allocated this address. */
+ LOCK();
+ /* Link p to the start of the pool's freeblock list. Since
+ * the pool had at least the p block outstanding, the pool
+ * wasn't empty (so it's already in a usedpools[] list, or
+ * was full and is in no list -- it's not in the freeblocks
+ * list in any case).
+ */
+ assert(pool->ref.count > 0); /* else it was empty */
+ *(block **)p = lastfree = pool->freeblock;
+ pool->freeblock = (block *)p;
+ if (lastfree) {
+ struct arena_object* ao;
+ uint nf; /* ao->nfreepools */
+
+ /* freeblock wasn't NULL, so the pool wasn't full,
+ * and the pool is in a usedpools[] list.
+ */
+ if (--pool->ref.count != 0) {
+ /* pool isn't empty: leave it in usedpools */
+ UNLOCK();
+ return;
+ }
+ /* Pool is now empty: unlink from usedpools, and
+ * link to the front of freepools. This ensures that
+ * previously freed pools will be allocated later
+ * (being not referenced, they are perhaps paged out).
+ */
+ next = pool->nextpool;
+ prev = pool->prevpool;
+ next->prevpool = prev;
+ prev->nextpool = next;
+
+ /* Link the pool to freepools. This is a singly-linked
+ * list, and pool->prevpool isn't used there.
+ */
+ ao = &arenas[pool->arenaindex];
+ pool->nextpool = ao->freepools;
+ ao->freepools = pool;
+ nf = ++ao->nfreepools;
+
+ /* All the rest is arena management. We just freed
+ * a pool, and there are 4 cases for arena mgmt:
+ * 1. If all the pools are free, return the arena to
+ * the system free().
+ * 2. If this is the only free pool in the arena,
+ * add the arena back to the `usable_arenas` list.
+ * 3. If the "next" arena has a smaller count of free
+ * pools, we have to "slide this arena right" to
+ * restore that usable_arenas is sorted in order of
+ * nfreepools.
+ * 4. Else there's nothing more to do.
+ */
+ if (nf == ao->ntotalpools) {
+ /* Case 1. First unlink ao from usable_arenas.
+ */
+ assert(ao->prevarena == NULL ||
+ ao->prevarena->address != 0);
+ assert(ao ->nextarena == NULL ||
+ ao->nextarena->address != 0);
+
+ /* Fix the pointer in the prevarena, or the
+ * usable_arenas pointer.
+ */
+ if (ao->prevarena == NULL) {
+ usable_arenas = ao->nextarena;
+ assert(usable_arenas == NULL ||
+ usable_arenas->address != 0);
+ }
+ else {
+ assert(ao->prevarena->nextarena == ao);
+ ao->prevarena->nextarena =
+ ao->nextarena;
+ }
+ /* Fix the pointer in the nextarena. */
+ if (ao->nextarena != NULL) {
+ assert(ao->nextarena->prevarena == ao);
+ ao->nextarena->prevarena =
+ ao->prevarena;
+ }
+ /* Record that this arena_object slot is
+ * available to be reused.
+ */
+ ao->nextarena = unused_arena_objects;
+ unused_arena_objects = ao;
+
+ /* Free the entire arena. */
+ free((void *)ao->address);
+ ao->address = 0; /* mark unassociated */
+ --narenas_currently_allocated;
+
+ UNLOCK();
+ return;
+ }
+ if (nf == 1) {
+ /* Case 2. Put ao at the head of
+ * usable_arenas. Note that because
+ * ao->nfreepools was 0 before, ao isn't
+ * currently on the usable_arenas list.
+ */
+ ao->nextarena = usable_arenas;
+ ao->prevarena = NULL;
+ if (usable_arenas)
+ usable_arenas->prevarena = ao;
+ usable_arenas = ao;
+ assert(usable_arenas->address != 0);
+
+ UNLOCK();
+ return;
+ }
+ /* If this arena is now out of order, we need to keep
+ * the list sorted. The list is kept sorted so that
+ * the "most full" arenas are used first, which allows
+ * the nearly empty arenas to be completely freed. In
+ * a few un-scientific tests, it seems like this
+ * approach allowed a lot more memory to be freed.
+ */
+ if (ao->nextarena == NULL ||
+ nf <= ao->nextarena->nfreepools) {
+ /* Case 4. Nothing to do. */
+ UNLOCK();
+ return;
+ }
+ /* Case 3: We have to move the arena towards the end
+ * of the list, because it has more free pools than
+ * the arena to its right.
+ * First unlink ao from usable_arenas.
+ */
+ if (ao->prevarena != NULL) {
+ /* ao isn't at the head of the list */
+ assert(ao->prevarena->nextarena == ao);
+ ao->prevarena->nextarena = ao->nextarena;
+ }
+ else {
+ /* ao is at the head of the list */
+ assert(usable_arenas == ao);
+ usable_arenas = ao->nextarena;
+ }
+ ao->nextarena->prevarena = ao->prevarena;
+
+ /* Locate the new insertion point by iterating over
+ * the list, using our nextarena pointer.
+ */
+ while (ao->nextarena != NULL &&
+ nf > ao->nextarena->nfreepools) {
+ ao->prevarena = ao->nextarena;
+ ao->nextarena = ao->nextarena->nextarena;
+ }
+
+ /* Insert ao at this point. */
+ assert(ao->nextarena == NULL ||
+ ao->prevarena == ao->nextarena->prevarena);
+ assert(ao->prevarena->nextarena == ao->nextarena);
+
+ ao->prevarena->nextarena = ao;
+ if (ao->nextarena != NULL)
+ ao->nextarena->prevarena = ao;
+
+ /* Verify that the swaps worked. */
+ assert(ao->nextarena == NULL ||
+ nf <= ao->nextarena->nfreepools);
+ assert(ao->prevarena == NULL ||
+ nf > ao->prevarena->nfreepools);
+ assert(ao->nextarena == NULL ||
+ ao->nextarena->prevarena == ao);
+ assert((usable_arenas == ao &&
+ ao->prevarena == NULL) ||
+ ao->prevarena->nextarena == ao);
+
+ UNLOCK();
+ return;
+ }
+ /* Pool was full, so doesn't currently live in any list:
+ * link it to the front of the appropriate usedpools[] list.
+ * This mimics LRU pool usage for new allocations and
+ * targets optimal filling when several pools contain
+ * blocks of the same size class.
+ */
+ --pool->ref.count;
+ assert(pool->ref.count > 0); /* else the pool is empty */
+ size = pool->szidx;
+ next = usedpools[size + size];
+ prev = next->prevpool;
+ /* insert pool before next: prev <-> pool <-> next */
+ pool->nextpool = next;
+ pool->prevpool = prev;
+ next->prevpool = pool;
+ prev->nextpool = pool;
+ UNLOCK();
+ return;
+ }
#ifdef WITH_VALGRIND
redirect:
#endif
- /* We didn't allocate this address. */
- free(p);
+ /* We didn't allocate this address. */
+ free(p);
}
/* realloc. If p is NULL, this acts like malloc(nbytes). Else if nbytes==0,
@@ -1164,81 +1164,81 @@ redirect:
void *
PyObject_Realloc(void *p, size_t nbytes)
{
- void *bp;
- poolp pool;
- size_t size;
-
- if (p == NULL)
- return PyObject_Malloc(nbytes);
-
- /*
- * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
- * Most python internals blindly use a signed Py_ssize_t to track
- * things without checking for overflows or negatives.
- * As size_t is unsigned, checking for nbytes < 0 is not required.
- */
- if (nbytes > PY_SSIZE_T_MAX)
- return NULL;
+ void *bp;
+ poolp pool;
+ size_t size;
+
+ if (p == NULL)
+ return PyObject_Malloc(nbytes);
+
+ /*
+ * Limit ourselves to PY_SSIZE_T_MAX bytes to prevent security holes.
+ * Most python internals blindly use a signed Py_ssize_t to track
+ * things without checking for overflows or negatives.
+ * As size_t is unsigned, checking for nbytes < 0 is not required.
+ */
+ if (nbytes > PY_SSIZE_T_MAX)
+ return NULL;
#ifdef WITH_VALGRIND
- /* Treat running_on_valgrind == -1 the same as 0 */
- if (UNLIKELY(running_on_valgrind > 0))
- goto redirect;
+ /* Treat running_on_valgrind == -1 the same as 0 */
+ if (UNLIKELY(running_on_valgrind > 0))
+ goto redirect;
#endif
- pool = POOL_ADDR(p);
- if (Py_ADDRESS_IN_RANGE(p, pool)) {
- /* We're in charge of this block */
- size = INDEX2SIZE(pool->szidx);
- if (nbytes <= size) {
- /* The block is staying the same or shrinking. If
- * it's shrinking, there's a tradeoff: it costs
- * cycles to copy the block to a smaller size class,
- * but it wastes memory not to copy it. The
- * compromise here is to copy on shrink only if at
- * least 25% of size can be shaved off.
- */
- if (4 * nbytes > 3 * size) {
- /* It's the same,
- * or shrinking and new/old > 3/4.
- */
- return p;
- }
- size = nbytes;
- }
- bp = PyObject_Malloc(nbytes);
- if (bp != NULL) {
- memcpy(bp, p, size);
- PyObject_Free(p);
- }
- return bp;
- }
+ pool = POOL_ADDR(p);
+ if (Py_ADDRESS_IN_RANGE(p, pool)) {
+ /* We're in charge of this block */
+ size = INDEX2SIZE(pool->szidx);
+ if (nbytes <= size) {
+ /* The block is staying the same or shrinking. If
+ * it's shrinking, there's a tradeoff: it costs
+ * cycles to copy the block to a smaller size class,
+ * but it wastes memory not to copy it. The
+ * compromise here is to copy on shrink only if at
+ * least 25% of size can be shaved off.
+ */
+ if (4 * nbytes > 3 * size) {
+ /* It's the same,
+ * or shrinking and new/old > 3/4.
+ */
+ return p;
+ }
+ size = nbytes;
+ }
+ bp = PyObject_Malloc(nbytes);
+ if (bp != NULL) {
+ memcpy(bp, p, size);
+ PyObject_Free(p);
+ }
+ return bp;
+ }
#ifdef WITH_VALGRIND
redirect:
#endif
- /* We're not managing this block. If nbytes <=
- * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
- * block. However, if we do, we need to copy the valid data from
- * the C-managed block to one of our blocks, and there's no portable
- * way to know how much of the memory space starting at p is valid.
- * As bug 1185883 pointed out the hard way, it's possible that the
- * C-managed block is "at the end" of allocated VM space, so that
- * a memory fault can occur if we try to copy nbytes bytes starting
- * at p. Instead we punt: let C continue to manage this block.
- */
- if (nbytes)
- return realloc(p, nbytes);
- /* C doesn't define the result of realloc(p, 0) (it may or may not
- * return NULL then), but Python's docs promise that nbytes==0 never
- * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
- * to begin with. Even then, we can't be sure that realloc() won't
- * return NULL.
- */
- bp = realloc(p, 1);
- return bp ? bp : p;
+ /* We're not managing this block. If nbytes <=
+ * SMALL_REQUEST_THRESHOLD, it's tempting to try to take over this
+ * block. However, if we do, we need to copy the valid data from
+ * the C-managed block to one of our blocks, and there's no portable
+ * way to know how much of the memory space starting at p is valid.
+ * As bug 1185883 pointed out the hard way, it's possible that the
+ * C-managed block is "at the end" of allocated VM space, so that
+ * a memory fault can occur if we try to copy nbytes bytes starting
+ * at p. Instead we punt: let C continue to manage this block.
+ */
+ if (nbytes)
+ return realloc(p, nbytes);
+ /* C doesn't define the result of realloc(p, 0) (it may or may not
+ * return NULL then), but Python's docs promise that nbytes==0 never
+ * returns NULL. We don't pass 0 to realloc(), to avoid that endcase
+ * to begin with. Even then, we can't be sure that realloc() won't
+ * return NULL.
+ */
+ bp = realloc(p, 1);
+ return bp ? bp : p;
}
-#else /* ! WITH_PYMALLOC */
+#else /* ! WITH_PYMALLOC */
/*==========================================================================*/
/* pymalloc not enabled: Redirect the entry points to malloc. These will
@@ -1247,19 +1247,19 @@ PyObject_Realloc(void *p, size_t nbytes)
void *
PyObject_Malloc(size_t n)
{
- return PyMem_MALLOC(n);
+ return PyMem_MALLOC(n);
}
void *
PyObject_Realloc(void *p, size_t n)
{
- return PyMem_REALLOC(p, n);
+ return PyMem_REALLOC(p, n);
}
void
PyObject_Free(void *p)
{
- PyMem_FREE(p);
+ PyMem_FREE(p);
}
#endif /* WITH_PYMALLOC */
@@ -1284,7 +1284,7 @@ PyObject_Free(void *p)
#define _PYMALLOC_MEM_ID 'm' /* the PyMem_Malloc() API */
#define _PYMALLOC_OBJ_ID 'o' /* The PyObject_Malloc() API */
-static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
+static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
/* serialno is always incremented via calling this routine. The point is
* to supply a single place to set a breakpoint.
@@ -1292,7 +1292,7 @@ static size_t serialno = 0; /* incremented on each debug {m,re}alloc */
static void
bumpserialno(void)
{
- ++serialno;
+ ++serialno;
}
#define SST SIZEOF_SIZE_T
@@ -1301,13 +1301,13 @@ bumpserialno(void)
static size_t
read_size_t(const void *p)
{
- const uchar *q = (const uchar *)p;
- size_t result = *q++;
- int i;
+ const uchar *q = (const uchar *)p;
+ size_t result = *q++;
+ int i;
- for (i = SST; --i > 0; ++q)
- result = (result << 8) | *q;
- return result;
+ for (i = SST; --i > 0; ++q)
+ result = (result << 8) | *q;
+ return result;
}
/* Write n as a big-endian size_t, MSB at address p, LSB at
@@ -1316,13 +1316,13 @@ read_size_t(const void *p)
static void
write_size_t(void *p, size_t n)
{
- uchar *q = (uchar *)p + SST - 1;
- int i;
+ uchar *q = (uchar *)p + SST - 1;
+ int i;
- for (i = SST; --i >= 0; --q) {
- *q = (uchar)(n & 0xff);
- n >>= 8;
- }
+ for (i = SST; --i >= 0; --q) {
+ *q = (uchar)(n & 0xff);
+ n >>= 8;
+ }
}
#ifdef Py_DEBUG
@@ -1333,22 +1333,22 @@ write_size_t(void *p, size_t n)
static int
pool_is_in_list(const poolp target, poolp list)
{
- poolp origlist = list;
- assert(target != NULL);
- if (list == NULL)
- return 0;
- do {
- if (target == list)
- return 1;
- list = list->nextpool;
- } while (list != NULL && list != origlist);
- return 0;
+ poolp origlist = list;
+ assert(target != NULL);
+ if (list == NULL)
+ return 0;
+ do {
+ if (target == list)
+ return 1;
+ list = list->nextpool;
+ } while (list != NULL && list != origlist);
+ return 0;
}
#else
#define pool_is_in_list(X, Y) 1
-#endif /* Py_DEBUG */
+#endif /* Py_DEBUG */
/* Let S = sizeof(size_t). The debug malloc asks for 4*S extra bytes and
fills them with useful stuff, here calling the underlying malloc's result p:
@@ -1378,39 +1378,39 @@ p[2*S+n+S: 2*S+n+2*S]
void *
_PyMem_DebugMalloc(size_t nbytes)
{
- return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
+ return _PyObject_DebugMallocApi(_PYMALLOC_MEM_ID, nbytes);
}
void *
_PyMem_DebugRealloc(void *p, size_t nbytes)
{
- return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
+ return _PyObject_DebugReallocApi(_PYMALLOC_MEM_ID, p, nbytes);
}
void
_PyMem_DebugFree(void *p)
{
- _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
+ _PyObject_DebugFreeApi(_PYMALLOC_MEM_ID, p);
}
/* debug replacements for the PyObject_* memory API */
void *
_PyObject_DebugMalloc(size_t nbytes)
{
- return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
+ return _PyObject_DebugMallocApi(_PYMALLOC_OBJ_ID, nbytes);
}
void *
_PyObject_DebugRealloc(void *p, size_t nbytes)
{
- return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
+ return _PyObject_DebugReallocApi(_PYMALLOC_OBJ_ID, p, nbytes);
}
void
_PyObject_DebugFree(void *p)
{
- _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
+ _PyObject_DebugFreeApi(_PYMALLOC_OBJ_ID, p);
}
void
_PyObject_DebugCheckAddress(const void *p)
{
- _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
+ _PyObject_DebugCheckAddressApi(_PYMALLOC_OBJ_ID, p);
}
@@ -1418,34 +1418,34 @@ _PyObject_DebugCheckAddress(const void *p)
void *
_PyObject_DebugMallocApi(char id, size_t nbytes)
{
- uchar *p; /* base address of malloc'ed block */
- uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
- size_t total; /* nbytes + 4*SST */
-
- bumpserialno();
- total = nbytes + 4*SST;
- if (total < nbytes)
- /* overflow: can't represent total as a size_t */
- return NULL;
-
- p = (uchar *)PyObject_Malloc(total);
- if (p == NULL)
- return NULL;
-
- /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
- write_size_t(p, nbytes);
- p[SST] = (uchar)id;
- memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
-
- if (nbytes > 0)
- memset(p + 2*SST, CLEANBYTE, nbytes);
-
- /* at tail, write pad (SST bytes) and serialno (SST bytes) */
- tail = p + 2*SST + nbytes;
- memset(tail, FORBIDDENBYTE, SST);
- write_size_t(tail + SST, serialno);
-
- return p + 2*SST;
+ uchar *p; /* base address of malloc'ed block */
+ uchar *tail; /* p + 2*SST + nbytes == pointer to tail pad bytes */
+ size_t total; /* nbytes + 4*SST */
+
+ bumpserialno();
+ total = nbytes + 4*SST;
+ if (total < nbytes)
+ /* overflow: can't represent total as a size_t */
+ return NULL;
+
+ p = (uchar *)PyObject_Malloc(total);
+ if (p == NULL)
+ return NULL;
+
+ /* at p, write size (SST bytes), id (1 byte), pad (SST-1 bytes) */
+ write_size_t(p, nbytes);
+ p[SST] = (uchar)id;
+ memset(p + SST + 1 , FORBIDDENBYTE, SST-1);
+
+ if (nbytes > 0)
+ memset(p + 2*SST, CLEANBYTE, nbytes);
+
+ /* at tail, write pad (SST bytes) and serialno (SST bytes) */
+ tail = p + 2*SST + nbytes;
+ memset(tail, FORBIDDENBYTE, SST);
+ write_size_t(tail + SST, serialno);
+
+ return p + 2*SST;
}
/* The debug free first checks the 2*SST bytes on each end for sanity (in
@@ -1456,68 +1456,68 @@ _PyObject_DebugMallocApi(char id, size_t nbytes)
void
_PyObject_DebugFreeApi(char api, void *p)
{
- uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
- size_t nbytes;
-
- if (p == NULL)
- return;
- _PyObject_DebugCheckAddressApi(api, p);
- nbytes = read_size_t(q);
- nbytes += 4*SST;
- if (nbytes > 0)
- memset(q, DEADBYTE, nbytes);
- PyObject_Free(q);
+ uchar *q = (uchar *)p - 2*SST; /* address returned from malloc */
+ size_t nbytes;
+
+ if (p == NULL)
+ return;
+ _PyObject_DebugCheckAddressApi(api, p);
+ nbytes = read_size_t(q);
+ nbytes += 4*SST;
+ if (nbytes > 0)
+ memset(q, DEADBYTE, nbytes);
+ PyObject_Free(q);
}
void *
_PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
{
- uchar *q = (uchar *)p;
- uchar *tail;
- size_t total; /* nbytes + 4*SST */
- size_t original_nbytes;
- int i;
-
- if (p == NULL)
- return _PyObject_DebugMallocApi(api, nbytes);
-
- _PyObject_DebugCheckAddressApi(api, p);
- bumpserialno();
- original_nbytes = read_size_t(q - 2*SST);
- total = nbytes + 4*SST;
- if (total < nbytes)
- /* overflow: can't represent total as a size_t */
- return NULL;
-
- if (nbytes < original_nbytes) {
- /* shrinking: mark old extra memory dead */
- memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
- }
-
- /* Resize and add decorations. We may get a new pointer here, in which
- * case we didn't get the chance to mark the old memory with DEADBYTE,
- * but we live with that.
- */
- q = (uchar *)PyObject_Realloc(q - 2*SST, total);
- if (q == NULL)
- return NULL;
-
- write_size_t(q, nbytes);
- assert(q[SST] == (uchar)api);
- for (i = 1; i < SST; ++i)
- assert(q[SST + i] == FORBIDDENBYTE);
- q += 2*SST;
- tail = q + nbytes;
- memset(tail, FORBIDDENBYTE, SST);
- write_size_t(tail + SST, serialno);
-
- if (nbytes > original_nbytes) {
- /* growing: mark new extra memory clean */
- memset(q + original_nbytes, CLEANBYTE,
- nbytes - original_nbytes);
- }
-
- return q;
+ uchar *q = (uchar *)p;
+ uchar *tail;
+ size_t total; /* nbytes + 4*SST */
+ size_t original_nbytes;
+ int i;
+
+ if (p == NULL)
+ return _PyObject_DebugMallocApi(api, nbytes);
+
+ _PyObject_DebugCheckAddressApi(api, p);
+ bumpserialno();
+ original_nbytes = read_size_t(q - 2*SST);
+ total = nbytes + 4*SST;
+ if (total < nbytes)
+ /* overflow: can't represent total as a size_t */
+ return NULL;
+
+ if (nbytes < original_nbytes) {
+ /* shrinking: mark old extra memory dead */
+ memset(q + nbytes, DEADBYTE, original_nbytes - nbytes + 2*SST);
+ }
+
+ /* Resize and add decorations. We may get a new pointer here, in which
+ * case we didn't get the chance to mark the old memory with DEADBYTE,
+ * but we live with that.
+ */
+ q = (uchar *)PyObject_Realloc(q - 2*SST, total);
+ if (q == NULL)
+ return NULL;
+
+ write_size_t(q, nbytes);
+ assert(q[SST] == (uchar)api);
+ for (i = 1; i < SST; ++i)
+ assert(q[SST + i] == FORBIDDENBYTE);
+ q += 2*SST;
+ tail = q + nbytes;
+ memset(tail, FORBIDDENBYTE, SST);
+ write_size_t(tail + SST, serialno);
+
+ if (nbytes > original_nbytes) {
+ /* growing: mark new extra memory clean */
+ memset(q + original_nbytes, CLEANBYTE,
+ nbytes - original_nbytes);
+ }
+
+ return q;
}
/* Check the forbidden bytes on both ends of the memory allocated for p.
@@ -1528,192 +1528,192 @@ _PyObject_DebugReallocApi(char api, void *p, size_t nbytes)
void
_PyObject_DebugCheckAddressApi(char api, const void *p)
{
- const uchar *q = (const uchar *)p;
- char msgbuf[64];
- char *msg;
- size_t nbytes;
- const uchar *tail;
- int i;
- char id;
-
- if (p == NULL) {
- msg = "didn't expect a NULL pointer";
- goto error;
- }
-
- /* Check the API id */
- id = (char)q[-SST];
- if (id != api) {
- msg = msgbuf;
- snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
- msgbuf[sizeof(msgbuf)-1] = 0;
- goto error;
- }
-
- /* Check the stuff at the start of p first: if there's underwrite
- * corruption, the number-of-bytes field may be nuts, and checking
- * the tail could lead to a segfault then.
- */
- for (i = SST-1; i >= 1; --i) {
- if (*(q-i) != FORBIDDENBYTE) {
- msg = "bad leading pad byte";
- goto error;
- }
- }
-
- nbytes = read_size_t(q - 2*SST);
- tail = q + nbytes;
- for (i = 0; i < SST; ++i) {
- if (tail[i] != FORBIDDENBYTE) {
- msg = "bad trailing pad byte";
- goto error;
- }
- }
-
- return;
+ const uchar *q = (const uchar *)p;
+ char msgbuf[64];
+ char *msg;
+ size_t nbytes;
+ const uchar *tail;
+ int i;
+ char id;
+
+ if (p == NULL) {
+ msg = "didn't expect a NULL pointer";
+ goto error;
+ }
+
+ /* Check the API id */
+ id = (char)q[-SST];
+ if (id != api) {
+ msg = msgbuf;
+ snprintf(msg, sizeof(msgbuf), "bad ID: Allocated using API '%c', verified using API '%c'", id, api);
+ msgbuf[sizeof(msgbuf)-1] = 0;
+ goto error;
+ }
+
+ /* Check the stuff at the start of p first: if there's underwrite
+ * corruption, the number-of-bytes field may be nuts, and checking
+ * the tail could lead to a segfault then.
+ */
+ for (i = SST-1; i >= 1; --i) {
+ if (*(q-i) != FORBIDDENBYTE) {
+ msg = "bad leading pad byte";
+ goto error;
+ }
+ }
+
+ nbytes = read_size_t(q - 2*SST);
+ tail = q + nbytes;
+ for (i = 0; i < SST; ++i) {
+ if (tail[i] != FORBIDDENBYTE) {
+ msg = "bad trailing pad byte";
+ goto error;
+ }
+ }
+
+ return;
error:
- _PyObject_DebugDumpAddress(p);
- Py_FatalError(msg);
+ _PyObject_DebugDumpAddress(p);
+ Py_FatalError(msg);
}
/* Display info to stderr about the memory block at p. */
void
_PyObject_DebugDumpAddress(const void *p)
{
- const uchar *q = (const uchar *)p;
- const uchar *tail;
- size_t nbytes, serial;
- int i;
- int ok;
- char id;
-
- fprintf(stderr, "Debug memory block at address p=%p:", p);
- if (p == NULL) {
- fprintf(stderr, "\n");
- return;
- }
- id = (char)q[-SST];
- fprintf(stderr, " API '%c'\n", id);
-
- nbytes = read_size_t(q - 2*SST);
- fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
- "requested\n", nbytes);
-
- /* In case this is nuts, check the leading pad bytes first. */
- fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
- ok = 1;
- for (i = 1; i <= SST-1; ++i) {
- if (*(q-i) != FORBIDDENBYTE) {
- ok = 0;
- break;
- }
- }
- if (ok)
- fputs("FORBIDDENBYTE, as expected.\n", stderr);
- else {
- fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
- FORBIDDENBYTE);
- for (i = SST-1; i >= 1; --i) {
- const uchar byte = *(q-i);
- fprintf(stderr, " at p-%d: 0x%02x", i, byte);
- if (byte != FORBIDDENBYTE)
- fputs(" *** OUCH", stderr);
- fputc('\n', stderr);
- }
-
- fputs(" Because memory is corrupted at the start, the "
- "count of bytes requested\n"
- " may be bogus, and checking the trailing pad "
- "bytes may segfault.\n", stderr);
- }
-
- tail = q + nbytes;
- fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
- ok = 1;
- for (i = 0; i < SST; ++i) {
- if (tail[i] != FORBIDDENBYTE) {
- ok = 0;
- break;
- }
- }
- if (ok)
- fputs("FORBIDDENBYTE, as expected.\n", stderr);
- else {
- fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
- FORBIDDENBYTE);
- for (i = 0; i < SST; ++i) {
- const uchar byte = tail[i];
- fprintf(stderr, " at tail+%d: 0x%02x",
- i, byte);
- if (byte != FORBIDDENBYTE)
- fputs(" *** OUCH", stderr);
- fputc('\n', stderr);
- }
- }
-
- serial = read_size_t(tail + SST);
- fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
- "u to debug malloc/realloc.\n", serial);
-
- if (nbytes > 0) {
- i = 0;
- fputs(" Data at p:", stderr);
- /* print up to 8 bytes at the start */
- while (q < tail && i < 8) {
- fprintf(stderr, " %02x", *q);
- ++i;
- ++q;
- }
- /* and up to 8 at the end */
- if (q < tail) {
- if (tail - q > 8) {
- fputs(" ...", stderr);
- q = tail - 8;
- }
- while (q < tail) {
- fprintf(stderr, " %02x", *q);
- ++q;
- }
- }
- fputc('\n', stderr);
- }
+ const uchar *q = (const uchar *)p;
+ const uchar *tail;
+ size_t nbytes, serial;
+ int i;
+ int ok;
+ char id;
+
+ fprintf(stderr, "Debug memory block at address p=%p:", p);
+ if (p == NULL) {
+ fprintf(stderr, "\n");
+ return;
+ }
+ id = (char)q[-SST];
+ fprintf(stderr, " API '%c'\n", id);
+
+ nbytes = read_size_t(q - 2*SST);
+ fprintf(stderr, " %" PY_FORMAT_SIZE_T "u bytes originally "
+ "requested\n", nbytes);
+
+ /* In case this is nuts, check the leading pad bytes first. */
+ fprintf(stderr, " The %d pad bytes at p-%d are ", SST-1, SST-1);
+ ok = 1;
+ for (i = 1; i <= SST-1; ++i) {
+ if (*(q-i) != FORBIDDENBYTE) {
+ ok = 0;
+ break;
+ }
+ }
+ if (ok)
+ fputs("FORBIDDENBYTE, as expected.\n", stderr);
+ else {
+ fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
+ FORBIDDENBYTE);
+ for (i = SST-1; i >= 1; --i) {
+ const uchar byte = *(q-i);
+ fprintf(stderr, " at p-%d: 0x%02x", i, byte);
+ if (byte != FORBIDDENBYTE)
+ fputs(" *** OUCH", stderr);
+ fputc('\n', stderr);
+ }
+
+ fputs(" Because memory is corrupted at the start, the "
+ "count of bytes requested\n"
+ " may be bogus, and checking the trailing pad "
+ "bytes may segfault.\n", stderr);
+ }
+
+ tail = q + nbytes;
+ fprintf(stderr, " The %d pad bytes at tail=%p are ", SST, tail);
+ ok = 1;
+ for (i = 0; i < SST; ++i) {
+ if (tail[i] != FORBIDDENBYTE) {
+ ok = 0;
+ break;
+ }
+ }
+ if (ok)
+ fputs("FORBIDDENBYTE, as expected.\n", stderr);
+ else {
+ fprintf(stderr, "not all FORBIDDENBYTE (0x%02x):\n",
+ FORBIDDENBYTE);
+ for (i = 0; i < SST; ++i) {
+ const uchar byte = tail[i];
+ fprintf(stderr, " at tail+%d: 0x%02x",
+ i, byte);
+ if (byte != FORBIDDENBYTE)
+ fputs(" *** OUCH", stderr);
+ fputc('\n', stderr);
+ }
+ }
+
+ serial = read_size_t(tail + SST);
+ fprintf(stderr, " The block was made by call #%" PY_FORMAT_SIZE_T
+ "u to debug malloc/realloc.\n", serial);
+
+ if (nbytes > 0) {
+ i = 0;
+ fputs(" Data at p:", stderr);
+ /* print up to 8 bytes at the start */
+ while (q < tail && i < 8) {
+ fprintf(stderr, " %02x", *q);
+ ++i;
+ ++q;
+ }
+ /* and up to 8 at the end */
+ if (q < tail) {
+ if (tail - q > 8) {
+ fputs(" ...", stderr);
+ q = tail - 8;
+ }
+ while (q < tail) {
+ fprintf(stderr, " %02x", *q);
+ ++q;
+ }
+ }
+ fputc('\n', stderr);
+ }
}
static size_t
printone(const char* msg, size_t value)
{
- int i, k;
- char buf[100];
- size_t origvalue = value;
-
- fputs(msg, stderr);
- for (i = (int)strlen(msg); i < 35; ++i)
- fputc(' ', stderr);
- fputc('=', stderr);
-
- /* Write the value with commas. */
- i = 22;
- buf[i--] = '\0';
- buf[i--] = '\n';
- k = 3;
- do {
- size_t nextvalue = value / 10;
- uint digit = (uint)(value - nextvalue * 10);
- value = nextvalue;
- buf[i--] = (char)(digit + '0');
- --k;
- if (k == 0 && value && i >= 0) {
- k = 3;
- buf[i--] = ',';
- }
- } while (value && i >= 0);
-
- while (i >= 0)
- buf[i--] = ' ';
- fputs(buf, stderr);
-
- return origvalue;
+ int i, k;
+ char buf[100];
+ size_t origvalue = value;
+
+ fputs(msg, stderr);
+ for (i = (int)strlen(msg); i < 35; ++i)
+ fputc(' ', stderr);
+ fputc('=', stderr);
+
+ /* Write the value with commas. */
+ i = 22;
+ buf[i--] = '\0';
+ buf[i--] = '\n';
+ k = 3;
+ do {
+ size_t nextvalue = value / 10;
+ uint digit = (uint)(value - nextvalue * 10);
+ value = nextvalue;
+ buf[i--] = (char)(digit + '0');
+ --k;
+ if (k == 0 && value && i >= 0) {
+ k = 3;
+ buf[i--] = ',';
+ }
+ } while (value && i >= 0);
+
+ while (i >= 0)
+ buf[i--] = ' ';
+ fputs(buf, stderr);
+
+ return origvalue;
}
/* Print summary info to stderr about the state of pymalloc's structures.
@@ -1723,140 +1723,140 @@ printone(const char* msg, size_t value)
void
_PyObject_DebugMallocStats(void)
{
- uint i;
- const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
- /* # of pools, allocated blocks, and free blocks per class index */
- size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
- size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
- size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
- /* total # of allocated bytes in used and full pools */
- size_t allocated_bytes = 0;
- /* total # of available bytes in used pools */
- size_t available_bytes = 0;
- /* # of free pools + pools not yet carved out of current arena */
- uint numfreepools = 0;
- /* # of bytes for arena alignment padding */
- size_t arena_alignment = 0;
- /* # of bytes in used and full pools used for pool_headers */
- size_t pool_header_bytes = 0;
- /* # of bytes in used and full pools wasted due to quantization,
- * i.e. the necessarily leftover space at the ends of used and
- * full pools.
- */
- size_t quantization = 0;
- /* # of arenas actually allocated. */
- size_t narenas = 0;
- /* running total -- should equal narenas * ARENA_SIZE */
- size_t total;
- char buf[128];
-
- fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
- SMALL_REQUEST_THRESHOLD, numclasses);
-
- for (i = 0; i < numclasses; ++i)
- numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
-
- /* Because full pools aren't linked to from anything, it's easiest
- * to march over all the arenas. If we're lucky, most of the memory
- * will be living in full pools -- would be a shame to miss them.
- */
- for (i = 0; i < maxarenas; ++i) {
- uint j;
- uptr base = arenas[i].address;
-
- /* Skip arenas which are not allocated. */
- if (arenas[i].address == (uptr)NULL)
- continue;
- narenas += 1;
-
- numfreepools += arenas[i].nfreepools;
-
- /* round up to pool alignment */
- if (base & (uptr)POOL_SIZE_MASK) {
- arena_alignment += POOL_SIZE;
- base &= ~(uptr)POOL_SIZE_MASK;
- base += POOL_SIZE;
- }
-
- /* visit every pool in the arena */
- assert(base <= (uptr) arenas[i].pool_address);
- for (j = 0;
- base < (uptr) arenas[i].pool_address;
- ++j, base += POOL_SIZE) {
- poolp p = (poolp)base;
- const uint sz = p->szidx;
- uint freeblocks;
-
- if (p->ref.count == 0) {
- /* currently unused */
- assert(pool_is_in_list(p, arenas[i].freepools));
- continue;
- }
- ++numpools[sz];
- numblocks[sz] += p->ref.count;
- freeblocks = NUMBLOCKS(sz) - p->ref.count;
- numfreeblocks[sz] += freeblocks;
+ uint i;
+ const uint numclasses = SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT;
+ /* # of pools, allocated blocks, and free blocks per class index */
+ size_t numpools[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
+ size_t numblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
+ size_t numfreeblocks[SMALL_REQUEST_THRESHOLD >> ALIGNMENT_SHIFT];
+ /* total # of allocated bytes in used and full pools */
+ size_t allocated_bytes = 0;
+ /* total # of available bytes in used pools */
+ size_t available_bytes = 0;
+ /* # of free pools + pools not yet carved out of current arena */
+ uint numfreepools = 0;
+ /* # of bytes for arena alignment padding */
+ size_t arena_alignment = 0;
+ /* # of bytes in used and full pools used for pool_headers */
+ size_t pool_header_bytes = 0;
+ /* # of bytes in used and full pools wasted due to quantization,
+ * i.e. the necessarily leftover space at the ends of used and
+ * full pools.
+ */
+ size_t quantization = 0;
+ /* # of arenas actually allocated. */
+ size_t narenas = 0;
+ /* running total -- should equal narenas * ARENA_SIZE */
+ size_t total;
+ char buf[128];
+
+ fprintf(stderr, "Small block threshold = %d, in %u size classes.\n",
+ SMALL_REQUEST_THRESHOLD, numclasses);
+
+ for (i = 0; i < numclasses; ++i)
+ numpools[i] = numblocks[i] = numfreeblocks[i] = 0;
+
+ /* Because full pools aren't linked to from anything, it's easiest
+ * to march over all the arenas. If we're lucky, most of the memory
+ * will be living in full pools -- would be a shame to miss them.
+ */
+ for (i = 0; i < maxarenas; ++i) {
+ uint j;
+ uptr base = arenas[i].address;
+
+ /* Skip arenas which are not allocated. */
+ if (arenas[i].address == (uptr)NULL)
+ continue;
+ narenas += 1;
+
+ numfreepools += arenas[i].nfreepools;
+
+ /* round up to pool alignment */
+ if (base & (uptr)POOL_SIZE_MASK) {
+ arena_alignment += POOL_SIZE;
+ base &= ~(uptr)POOL_SIZE_MASK;
+ base += POOL_SIZE;
+ }
+
+ /* visit every pool in the arena */
+ assert(base <= (uptr) arenas[i].pool_address);
+ for (j = 0;
+ base < (uptr) arenas[i].pool_address;
+ ++j, base += POOL_SIZE) {
+ poolp p = (poolp)base;
+ const uint sz = p->szidx;
+ uint freeblocks;
+
+ if (p->ref.count == 0) {
+ /* currently unused */
+ assert(pool_is_in_list(p, arenas[i].freepools));
+ continue;
+ }
+ ++numpools[sz];
+ numblocks[sz] += p->ref.count;
+ freeblocks = NUMBLOCKS(sz) - p->ref.count;
+ numfreeblocks[sz] += freeblocks;
#ifdef Py_DEBUG
- if (freeblocks > 0)
- assert(pool_is_in_list(p, usedpools[sz + sz]));
+ if (freeblocks > 0)
+ assert(pool_is_in_list(p, usedpools[sz + sz]));
#endif
- }
- }
- assert(narenas == narenas_currently_allocated);
-
- fputc('\n', stderr);
- fputs("class size num pools blocks in use avail blocks\n"
- "----- ---- --------- ------------- ------------\n",
- stderr);
-
- for (i = 0; i < numclasses; ++i) {
- size_t p = numpools[i];
- size_t b = numblocks[i];
- size_t f = numfreeblocks[i];
- uint size = INDEX2SIZE(i);
- if (p == 0) {
- assert(b == 0 && f == 0);
- continue;
- }
- fprintf(stderr, "%5u %6u "
- "%11" PY_FORMAT_SIZE_T "u "
- "%15" PY_FORMAT_SIZE_T "u "
- "%13" PY_FORMAT_SIZE_T "u\n",
- i, size, p, b, f);
- allocated_bytes += b * size;
- available_bytes += f * size;
- pool_header_bytes += p * POOL_OVERHEAD;
- quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
- }
- fputc('\n', stderr);
- (void)printone("# times object malloc called", serialno);
-
- (void)printone("# arenas allocated total", ntimes_arena_allocated);
- (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
- (void)printone("# arenas highwater mark", narenas_highwater);
- (void)printone("# arenas allocated current", narenas);
-
- PyOS_snprintf(buf, sizeof(buf),
- "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
- narenas, ARENA_SIZE);
- (void)printone(buf, narenas * ARENA_SIZE);
-
- fputc('\n', stderr);
-
- total = printone("# bytes in allocated blocks", allocated_bytes);
- total += printone("# bytes in available blocks", available_bytes);
-
- PyOS_snprintf(buf, sizeof(buf),
- "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
- total += printone(buf, (size_t)numfreepools * POOL_SIZE);
-
- total += printone("# bytes lost to pool headers", pool_header_bytes);
- total += printone("# bytes lost to quantization", quantization);
- total += printone("# bytes lost to arena alignment", arena_alignment);
- (void)printone("Total", total);
+ }
+ }
+ assert(narenas == narenas_currently_allocated);
+
+ fputc('\n', stderr);
+ fputs("class size num pools blocks in use avail blocks\n"
+ "----- ---- --------- ------------- ------------\n",
+ stderr);
+
+ for (i = 0; i < numclasses; ++i) {
+ size_t p = numpools[i];
+ size_t b = numblocks[i];
+ size_t f = numfreeblocks[i];
+ uint size = INDEX2SIZE(i);
+ if (p == 0) {
+ assert(b == 0 && f == 0);
+ continue;
+ }
+ fprintf(stderr, "%5u %6u "
+ "%11" PY_FORMAT_SIZE_T "u "
+ "%15" PY_FORMAT_SIZE_T "u "
+ "%13" PY_FORMAT_SIZE_T "u\n",
+ i, size, p, b, f);
+ allocated_bytes += b * size;
+ available_bytes += f * size;
+ pool_header_bytes += p * POOL_OVERHEAD;
+ quantization += p * ((POOL_SIZE - POOL_OVERHEAD) % size);
+ }
+ fputc('\n', stderr);
+ (void)printone("# times object malloc called", serialno);
+
+ (void)printone("# arenas allocated total", ntimes_arena_allocated);
+ (void)printone("# arenas reclaimed", ntimes_arena_allocated - narenas);
+ (void)printone("# arenas highwater mark", narenas_highwater);
+ (void)printone("# arenas allocated current", narenas);
+
+ PyOS_snprintf(buf, sizeof(buf),
+ "%" PY_FORMAT_SIZE_T "u arenas * %d bytes/arena",
+ narenas, ARENA_SIZE);
+ (void)printone(buf, narenas * ARENA_SIZE);
+
+ fputc('\n', stderr);
+
+ total = printone("# bytes in allocated blocks", allocated_bytes);
+ total += printone("# bytes in available blocks", available_bytes);
+
+ PyOS_snprintf(buf, sizeof(buf),
+ "%u unused pools * %d bytes", numfreepools, POOL_SIZE);
+ total += printone(buf, (size_t)numfreepools * POOL_SIZE);
+
+ total += printone("# bytes lost to pool headers", pool_header_bytes);
+ total += printone("# bytes lost to quantization", quantization);
+ total += printone("# bytes lost to arena alignment", arena_alignment);
+ (void)printone("Total", total);
}
-#endif /* PYMALLOC_DEBUG */
+#endif /* PYMALLOC_DEBUG */
#ifdef Py_USING_MEMORY_DEBUGGER
/* Make this function last so gcc won't inline it since the definition is
@@ -1865,8 +1865,8 @@ _PyObject_DebugMallocStats(void)
int
Py_ADDRESS_IN_RANGE(void *P, poolp pool)
{
- return pool->arenaindex < maxarenas &&
- (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE &&
- arenas[pool->arenaindex].address != 0;
+ return pool->arenaindex < maxarenas &&
+ (uptr)P - arenas[pool->arenaindex].address < (uptr)ARENA_SIZE &&
+ arenas[pool->arenaindex].address != 0;
}
#endif
diff --git a/Objects/rangeobject.c b/Objects/rangeobject.c
index f45b771..4e64dba 100644
--- a/Objects/rangeobject.c
+++ b/Objects/rangeobject.c
@@ -3,10 +3,10 @@
#include "Python.h"
typedef struct {
- PyObject_HEAD
- long start;
- long step;
- long len;
+ PyObject_HEAD
+ long start;
+ long step;
+ long len;
} rangeobject;
/* Return number of items in range (lo, hi, step). step != 0
@@ -30,53 +30,53 @@ get_len_of_range(long lo, long hi, long step)
---------------------------------------------------------------*/
assert(step != 0);
if (step > 0 && lo < hi)
- return 1UL + (hi - 1UL - lo) / step;
+ return 1UL + (hi - 1UL - lo) / step;
else if (step < 0 && lo > hi)
- return 1UL + (lo - 1UL - hi) / (0UL - step);
+ return 1UL + (lo - 1UL - hi) / (0UL - step);
else
- return 0UL;
+ return 0UL;
}
static PyObject *
range_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- rangeobject *obj;
- long ilow = 0, ihigh = 0, istep = 1;
- unsigned long n;
-
- if (!_PyArg_NoKeywords("xrange()", kw))
- return NULL;
-
- if (PyTuple_Size(args) <= 1) {
- if (!PyArg_ParseTuple(args,
- "l;xrange() requires 1-3 int arguments",
- &ihigh))
- return NULL;
- }
- else {
- if (!PyArg_ParseTuple(args,
- "ll|l;xrange() requires 1-3 int arguments",
- &ilow, &ihigh, &istep))
- return NULL;
- }
- if (istep == 0) {
- PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
- return NULL;
- }
- n = get_len_of_range(ilow, ihigh, istep);
- if (n > (unsigned long)LONG_MAX || (long)n > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "xrange() result has too many items");
- return NULL;
- }
-
- obj = PyObject_New(rangeobject, &PyRange_Type);
- if (obj == NULL)
- return NULL;
- obj->start = ilow;
- obj->len = (long)n;
- obj->step = istep;
- return (PyObject *) obj;
+ rangeobject *obj;
+ long ilow = 0, ihigh = 0, istep = 1;
+ unsigned long n;
+
+ if (!_PyArg_NoKeywords("xrange()", kw))
+ return NULL;
+
+ if (PyTuple_Size(args) <= 1) {
+ if (!PyArg_ParseTuple(args,
+ "l;xrange() requires 1-3 int arguments",
+ &ihigh))
+ return NULL;
+ }
+ else {
+ if (!PyArg_ParseTuple(args,
+ "ll|l;xrange() requires 1-3 int arguments",
+ &ilow, &ihigh, &istep))
+ return NULL;
+ }
+ if (istep == 0) {
+ PyErr_SetString(PyExc_ValueError, "xrange() arg 3 must not be zero");
+ return NULL;
+ }
+ n = get_len_of_range(ilow, ihigh, istep);
+ if (n > (unsigned long)LONG_MAX || (long)n > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "xrange() result has too many items");
+ return NULL;
+ }
+
+ obj = PyObject_New(rangeobject, &PyRange_Type);
+ if (obj == NULL)
+ return NULL;
+ obj->start = ilow;
+ obj->len = (long)n;
+ obj->step = istep;
+ return (PyObject *) obj;
}
PyDoc_STRVAR(range_doc,
@@ -89,60 +89,60 @@ slightly faster than range() and more memory efficient.");
static PyObject *
range_item(rangeobject *r, Py_ssize_t i)
{
- if (i < 0 || i >= r->len) {
- PyErr_SetString(PyExc_IndexError,
- "xrange object index out of range");
- return NULL;
- }
- /* do calculation entirely using unsigned longs, to avoid
- undefined behaviour due to signed overflow. */
- return PyInt_FromLong((long)(r->start + (unsigned long)i * r->step));
+ if (i < 0 || i >= r->len) {
+ PyErr_SetString(PyExc_IndexError,
+ "xrange object index out of range");
+ return NULL;
+ }
+ /* do calculation entirely using unsigned longs, to avoid
+ undefined behaviour due to signed overflow. */
+ return PyInt_FromLong((long)(r->start + (unsigned long)i * r->step));
}
static Py_ssize_t
range_length(rangeobject *r)
{
- return (Py_ssize_t)(r->len);
+ return (Py_ssize_t)(r->len);
}
static PyObject *
range_repr(rangeobject *r)
{
- PyObject *rtn;
-
- if (r->start == 0 && r->step == 1)
- rtn = PyString_FromFormat("xrange(%ld)",
- r->start + r->len * r->step);
-
- else if (r->step == 1)
- rtn = PyString_FromFormat("xrange(%ld, %ld)",
- r->start,
- r->start + r->len * r->step);
-
- else
- rtn = PyString_FromFormat("xrange(%ld, %ld, %ld)",
- r->start,
- r->start + r->len * r->step,
- r->step);
- return rtn;
+ PyObject *rtn;
+
+ if (r->start == 0 && r->step == 1)
+ rtn = PyString_FromFormat("xrange(%ld)",
+ r->start + r->len * r->step);
+
+ else if (r->step == 1)
+ rtn = PyString_FromFormat("xrange(%ld, %ld)",
+ r->start,
+ r->start + r->len * r->step);
+
+ else
+ rtn = PyString_FromFormat("xrange(%ld, %ld, %ld)",
+ r->start,
+ r->start + r->len * r->step,
+ r->step);
+ return rtn;
}
/* Pickling support */
static PyObject *
range_reduce(rangeobject *r, PyObject *args)
{
- return Py_BuildValue("(O(iii))", Py_TYPE(r),
- r->start,
- r->start + r->len * r->step,
- r->step);
+ return Py_BuildValue("(O(iii))", Py_TYPE(r),
+ r->start,
+ r->start + r->len * r->step,
+ r->step);
}
static PySequenceMethods range_as_sequence = {
- (lenfunc)range_length, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- (ssizeargfunc)range_item, /* sq_item */
- 0, /* sq_slice */
+ (lenfunc)range_length, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ (ssizeargfunc)range_item, /* sq_item */
+ 0, /* sq_slice */
};
static PyObject * range_iter(PyObject *seq);
@@ -152,171 +152,171 @@ PyDoc_STRVAR(reverse_doc,
"Returns a reverse iterator.");
static PyMethodDef range_methods[] = {
- {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc},
- {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"__reversed__", (PyCFunction)range_reverse, METH_NOARGS, reverse_doc},
+ {"__reduce__", (PyCFunction)range_reduce, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyRange_Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /* Number of items for varobject */
- "xrange", /* Name of this type */
- sizeof(rangeobject), /* Basic object size */
- 0, /* Item size for varobject */
- (destructor)PyObject_Del, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)range_repr, /* tp_repr */
- 0, /* tp_as_number */
- &range_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 */
- range_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- range_iter, /* tp_iter */
- 0, /* tp_iternext */
- range_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 */
- range_new, /* tp_new */
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /* Number of items for varobject */
+ "xrange", /* Name of this type */
+ sizeof(rangeobject), /* Basic object size */
+ 0, /* Item size for varobject */
+ (destructor)PyObject_Del, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)range_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &range_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 */
+ range_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ range_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ range_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 */
+ range_new, /* tp_new */
};
/*********************** Xrange Iterator **************************/
typedef struct {
- PyObject_HEAD
- long index;
- long start;
- long step;
- long len;
+ PyObject_HEAD
+ long index;
+ long start;
+ long step;
+ long len;
} rangeiterobject;
static PyObject *
rangeiter_next(rangeiterobject *r)
{
- if (r->index < r->len)
- return PyInt_FromLong(r->start + (r->index++) * r->step);
- return NULL;
+ if (r->index < r->len)
+ return PyInt_FromLong(r->start + (r->index++) * r->step);
+ return NULL;
}
static PyObject *
rangeiter_len(rangeiterobject *r)
{
- return PyInt_FromLong(r->len - r->index);
+ return PyInt_FromLong(r->len - r->index);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef rangeiter_methods[] = {
- {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)rangeiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject Pyrangeiter_Type = {
- PyObject_HEAD_INIT(&PyType_Type)
- 0, /* ob_size */
- "rangeiterator", /* tp_name */
- sizeof(rangeiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)PyObject_Del, /* 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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)rangeiter_next, /* tp_iternext */
- rangeiter_methods, /* tp_methods */
- 0,
+ PyObject_HEAD_INIT(&PyType_Type)
+ 0, /* ob_size */
+ "rangeiterator", /* tp_name */
+ sizeof(rangeiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)PyObject_Del, /* 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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)rangeiter_next, /* tp_iternext */
+ rangeiter_methods, /* tp_methods */
+ 0,
};
static PyObject *
range_iter(PyObject *seq)
{
- rangeiterobject *it;
-
- if (!PyRange_Check(seq)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
- if (it == NULL)
- return NULL;
- it->index = 0;
- it->start = ((rangeobject *)seq)->start;
- it->step = ((rangeobject *)seq)->step;
- it->len = ((rangeobject *)seq)->len;
- return (PyObject *)it;
+ rangeiterobject *it;
+
+ if (!PyRange_Check(seq)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
+ if (it == NULL)
+ return NULL;
+ it->index = 0;
+ it->start = ((rangeobject *)seq)->start;
+ it->step = ((rangeobject *)seq)->step;
+ it->len = ((rangeobject *)seq)->len;
+ return (PyObject *)it;
}
static PyObject *
range_reverse(PyObject *seq)
{
- rangeiterobject *it;
- long start, step, len;
-
- if (!PyRange_Check(seq)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
- if (it == NULL)
- return NULL;
-
- start = ((rangeobject *)seq)->start;
- step = ((rangeobject *)seq)->step;
- len = ((rangeobject *)seq)->len;
-
- it->index = 0;
- it->len = len;
- /* the casts below guard against signed overflow by turning it
- into unsigned overflow instead. The correctness of this
- code still depends on conversion from unsigned long to long
- wrapping modulo ULONG_MAX+1, which isn't guaranteed (see
- C99 6.3.1.3p3) but seems to hold in practice for all
- platforms we're likely to meet.
-
- If step == LONG_MIN then we still end up with LONG_MIN
- after negation; but this works out, since we've still got
- the correct value modulo ULONG_MAX+1, and the range_item
- calculation is also done modulo ULONG_MAX+1.
- */
- it->start = (long)(start + (unsigned long)(len-1) * step);
- it->step = (long)(0UL-step);
-
- return (PyObject *)it;
+ rangeiterobject *it;
+ long start, step, len;
+
+ if (!PyRange_Check(seq)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ it = PyObject_New(rangeiterobject, &Pyrangeiter_Type);
+ if (it == NULL)
+ return NULL;
+
+ start = ((rangeobject *)seq)->start;
+ step = ((rangeobject *)seq)->step;
+ len = ((rangeobject *)seq)->len;
+
+ it->index = 0;
+ it->len = len;
+ /* the casts below guard against signed overflow by turning it
+ into unsigned overflow instead. The correctness of this
+ code still depends on conversion from unsigned long to long
+ wrapping modulo ULONG_MAX+1, which isn't guaranteed (see
+ C99 6.3.1.3p3) but seems to hold in practice for all
+ platforms we're likely to meet.
+
+ If step == LONG_MIN then we still end up with LONG_MIN
+ after negation; but this works out, since we've still got
+ the correct value modulo ULONG_MAX+1, and the range_item
+ calculation is also done modulo ULONG_MAX+1.
+ */
+ it->start = (long)(start + (unsigned long)(len-1) * step);
+ it->step = (long)(0UL-step);
+
+ return (PyObject *)it;
}
diff --git a/Objects/setobject.c b/Objects/setobject.c
index f97b0c0..f98a930 100644
--- a/Objects/setobject.c
+++ b/Objects/setobject.c
@@ -1,5 +1,5 @@
-/* set object implementation
+/* set object implementation
Written and maintained by Raymond D. Hettinger <python@rcn.com>
Derived from Lib/sets.py and Objects/dictobject.c.
@@ -16,12 +16,12 @@
static void
set_key_error(PyObject *arg)
{
- PyObject *tup;
- tup = PyTuple_Pack(1, arg);
- if (!tup)
- return; /* caller will expect error to be set anyway */
- PyErr_SetObject(PyExc_KeyError, tup);
- Py_DECREF(tup);
+ PyObject *tup;
+ tup = PyTuple_Pack(1, arg);
+ if (!tup)
+ return; /* caller will expect error to be set anyway */
+ PyErr_SetObject(PyExc_KeyError, tup);
+ Py_DECREF(tup);
}
/* This must be >= 1. */
@@ -34,20 +34,20 @@ static PyObject *dummy = NULL; /* Initialized by first call to make_new_set() */
PyObject *
_PySet_Dummy(void)
{
- return dummy;
+ return dummy;
}
#endif
-#define INIT_NONZERO_SET_SLOTS(so) do { \
- (so)->table = (so)->smalltable; \
- (so)->mask = PySet_MINSIZE - 1; \
- (so)->hash = -1; \
+#define INIT_NONZERO_SET_SLOTS(so) do { \
+ (so)->table = (so)->smalltable; \
+ (so)->mask = PySet_MINSIZE - 1; \
+ (so)->hash = -1; \
} while(0)
-#define EMPTY_TO_MINSIZE(so) do { \
- memset((so)->smalltable, 0, sizeof((so)->smalltable)); \
- (so)->used = (so)->fill = 0; \
- INIT_NONZERO_SET_SLOTS(so); \
+#define EMPTY_TO_MINSIZE(so) do { \
+ memset((so)->smalltable, 0, sizeof((so)->smalltable)); \
+ (so)->used = (so)->fill = 0; \
+ INIT_NONZERO_SET_SLOTS(so); \
} while(0)
/* Reuse scheme to save calls to malloc, free, and memset */
@@ -75,78 +75,78 @@ NULL if the rich comparison returns an error.
static setentry *
set_lookkey(PySetObject *so, PyObject *key, register long hash)
{
- register Py_ssize_t i;
- register size_t perturb;
- register setentry *freeslot;
- register size_t mask = so->mask;
- setentry *table = so->table;
- register setentry *entry;
- register int cmp;
- PyObject *startkey;
-
- i = hash & mask;
- entry = &table[i];
- if (entry->key == NULL || entry->key == key)
- return entry;
-
- if (entry->key == dummy)
- freeslot = entry;
- else {
- if (entry->hash == hash) {
- startkey = entry->key;
- Py_INCREF(startkey);
- cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
- Py_DECREF(startkey);
- if (cmp < 0)
- return NULL;
- if (table == so->table && entry->key == startkey) {
- if (cmp > 0)
- return entry;
- }
- else {
- /* The compare did major nasty stuff to the
- * set: start over.
- */
- return set_lookkey(so, key, hash);
- }
- }
- freeslot = NULL;
- }
-
- /* In the loop, key == dummy is by far (factor of 100s) the
- least likely outcome, so test for that last. */
- for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
- i = (i << 2) + i + perturb + 1;
- entry = &table[i & mask];
- if (entry->key == NULL) {
- if (freeslot != NULL)
- entry = freeslot;
- break;
- }
- if (entry->key == key)
- break;
- if (entry->hash == hash && entry->key != dummy) {
- startkey = entry->key;
- Py_INCREF(startkey);
- cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
- Py_DECREF(startkey);
- if (cmp < 0)
- return NULL;
- if (table == so->table && entry->key == startkey) {
- if (cmp > 0)
- break;
- }
- else {
- /* The compare did major nasty stuff to the
- * set: start over.
- */
- return set_lookkey(so, key, hash);
- }
- }
- else if (entry->key == dummy && freeslot == NULL)
- freeslot = entry;
- }
- return entry;
+ register Py_ssize_t i;
+ register size_t perturb;
+ register setentry *freeslot;
+ register size_t mask = so->mask;
+ setentry *table = so->table;
+ register setentry *entry;
+ register int cmp;
+ PyObject *startkey;
+
+ i = hash & mask;
+ entry = &table[i];
+ if (entry->key == NULL || entry->key == key)
+ return entry;
+
+ if (entry->key == dummy)
+ freeslot = entry;
+ else {
+ if (entry->hash == hash) {
+ startkey = entry->key;
+ Py_INCREF(startkey);
+ cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
+ Py_DECREF(startkey);
+ if (cmp < 0)
+ return NULL;
+ if (table == so->table && entry->key == startkey) {
+ if (cmp > 0)
+ return entry;
+ }
+ else {
+ /* The compare did major nasty stuff to the
+ * set: start over.
+ */
+ return set_lookkey(so, key, hash);
+ }
+ }
+ freeslot = NULL;
+ }
+
+ /* In the loop, key == dummy is by far (factor of 100s) the
+ least likely outcome, so test for that last. */
+ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
+ i = (i << 2) + i + perturb + 1;
+ entry = &table[i & mask];
+ if (entry->key == NULL) {
+ if (freeslot != NULL)
+ entry = freeslot;
+ break;
+ }
+ if (entry->key == key)
+ break;
+ if (entry->hash == hash && entry->key != dummy) {
+ startkey = entry->key;
+ Py_INCREF(startkey);
+ cmp = PyObject_RichCompareBool(startkey, key, Py_EQ);
+ Py_DECREF(startkey);
+ if (cmp < 0)
+ return NULL;
+ if (table == so->table && entry->key == startkey) {
+ if (cmp > 0)
+ break;
+ }
+ else {
+ /* The compare did major nasty stuff to the
+ * set: start over.
+ */
+ return set_lookkey(so, key, hash);
+ }
+ }
+ else if (entry->key == dummy && freeslot == NULL)
+ freeslot = entry;
+ }
+ return entry;
}
/*
@@ -157,50 +157,50 @@ set_lookkey(PySetObject *so, PyObject *key, register long hash)
static setentry *
set_lookkey_string(PySetObject *so, PyObject *key, register long hash)
{
- register Py_ssize_t i;
- register size_t perturb;
- register setentry *freeslot;
- register size_t mask = so->mask;
- setentry *table = so->table;
- register setentry *entry;
-
- /* Make sure this function doesn't have to handle non-string keys,
- including subclasses of str; e.g., one reason to subclass
- strings is to override __eq__, and for speed we don't cater to
- that here. */
- if (!PyString_CheckExact(key)) {
- so->lookup = set_lookkey;
- return set_lookkey(so, key, hash);
- }
- i = hash & mask;
- entry = &table[i];
- if (entry->key == NULL || entry->key == key)
- return entry;
- if (entry->key == dummy)
- freeslot = entry;
- else {
- if (entry->hash == hash && _PyString_Eq(entry->key, key))
- return entry;
- freeslot = NULL;
- }
-
- /* In the loop, key == dummy is by far (factor of 100s) the
- least likely outcome, so test for that last. */
- for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
- i = (i << 2) + i + perturb + 1;
- entry = &table[i & mask];
- if (entry->key == NULL)
- return freeslot == NULL ? entry : freeslot;
- if (entry->key == key
- || (entry->hash == hash
- && entry->key != dummy
- && _PyString_Eq(entry->key, key)))
- return entry;
- if (entry->key == dummy && freeslot == NULL)
- freeslot = entry;
- }
- assert(0); /* NOT REACHED */
- return 0;
+ register Py_ssize_t i;
+ register size_t perturb;
+ register setentry *freeslot;
+ register size_t mask = so->mask;
+ setentry *table = so->table;
+ register setentry *entry;
+
+ /* Make sure this function doesn't have to handle non-string keys,
+ including subclasses of str; e.g., one reason to subclass
+ strings is to override __eq__, and for speed we don't cater to
+ that here. */
+ if (!PyString_CheckExact(key)) {
+ so->lookup = set_lookkey;
+ return set_lookkey(so, key, hash);
+ }
+ i = hash & mask;
+ entry = &table[i];
+ if (entry->key == NULL || entry->key == key)
+ return entry;
+ if (entry->key == dummy)
+ freeslot = entry;
+ else {
+ if (entry->hash == hash && _PyString_Eq(entry->key, key))
+ return entry;
+ freeslot = NULL;
+ }
+
+ /* In the loop, key == dummy is by far (factor of 100s) the
+ least likely outcome, so test for that last. */
+ for (perturb = hash; ; perturb >>= PERTURB_SHIFT) {
+ i = (i << 2) + i + perturb + 1;
+ entry = &table[i & mask];
+ if (entry->key == NULL)
+ return freeslot == NULL ? entry : freeslot;
+ if (entry->key == key
+ || (entry->hash == hash
+ && entry->key != dummy
+ && _PyString_Eq(entry->key, key)))
+ return entry;
+ if (entry->key == dummy && freeslot == NULL)
+ freeslot = entry;
+ }
+ assert(0); /* NOT REACHED */
+ return 0;
}
/*
@@ -211,30 +211,30 @@ Eats a reference to key.
static int
set_insert_key(register PySetObject *so, PyObject *key, long hash)
{
- register setentry *entry;
- typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long);
-
- assert(so->lookup != NULL);
- entry = so->lookup(so, key, hash);
- if (entry == NULL)
- return -1;
- if (entry->key == NULL) {
- /* UNUSED */
- so->fill++;
- entry->key = key;
- entry->hash = hash;
- so->used++;
- } else if (entry->key == dummy) {
- /* DUMMY */
- entry->key = key;
- entry->hash = hash;
- so->used++;
- Py_DECREF(dummy);
- } else {
- /* ACTIVE */
- Py_DECREF(key);
- }
- return 0;
+ register setentry *entry;
+ typedef setentry *(*lookupfunc)(PySetObject *, PyObject *, long);
+
+ assert(so->lookup != NULL);
+ entry = so->lookup(so, key, hash);
+ if (entry == NULL)
+ return -1;
+ if (entry->key == NULL) {
+ /* UNUSED */
+ so->fill++;
+ entry->key = key;
+ entry->hash = hash;
+ so->used++;
+ } else if (entry->key == dummy) {
+ /* DUMMY */
+ entry->key = key;
+ entry->hash = hash;
+ so->used++;
+ Py_DECREF(dummy);
+ } else {
+ /* ACTIVE */
+ Py_DECREF(key);
+ }
+ return 0;
}
/*
@@ -248,22 +248,22 @@ is responsible for incref'ing `key`.
static void
set_insert_clean(register PySetObject *so, PyObject *key, long hash)
{
- register size_t i;
- register size_t perturb;
- register size_t mask = (size_t)so->mask;
- setentry *table = so->table;
- register setentry *entry;
+ register size_t i;
+ register size_t perturb;
+ register size_t mask = (size_t)so->mask;
+ setentry *table = so->table;
+ register setentry *entry;
- i = hash & mask;
- entry = &table[i];
- for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) {
- i = (i << 2) + i + perturb + 1;
- entry = &table[i & mask];
- }
- so->fill++;
- entry->key = key;
- entry->hash = hash;
- so->used++;
+ i = hash & mask;
+ entry = &table[i];
+ for (perturb = hash; entry->key != NULL; perturb >>= PERTURB_SHIFT) {
+ i = (i << 2) + i + perturb + 1;
+ entry = &table[i & mask];
+ }
+ so->fill++;
+ entry->key = key;
+ entry->hash = hash;
+ so->used++;
}
/*
@@ -274,86 +274,86 @@ actually be smaller than the old one.
static int
set_table_resize(PySetObject *so, Py_ssize_t minused)
{
- Py_ssize_t newsize;
- setentry *oldtable, *newtable, *entry;
- Py_ssize_t i;
- int is_oldtable_malloced;
- setentry small_copy[PySet_MINSIZE];
-
- assert(minused >= 0);
-
- /* Find the smallest table size > minused. */
- for (newsize = PySet_MINSIZE;
- newsize <= minused && newsize > 0;
- newsize <<= 1)
- ;
- if (newsize <= 0) {
- PyErr_NoMemory();
- return -1;
- }
-
- /* Get space for a new table. */
- oldtable = so->table;
- assert(oldtable != NULL);
- is_oldtable_malloced = oldtable != so->smalltable;
-
- if (newsize == PySet_MINSIZE) {
- /* A large table is shrinking, or we can't get any smaller. */
- newtable = so->smalltable;
- if (newtable == oldtable) {
- if (so->fill == so->used) {
- /* No dummies, so no point doing anything. */
- return 0;
- }
- /* We're not going to resize it, but rebuild the
- table anyway to purge old dummy entries.
- Subtle: This is *necessary* if fill==size,
- as set_lookkey needs at least one virgin slot to
- terminate failing searches. If fill < size, it's
- merely desirable, as dummies slow searches. */
- assert(so->fill > so->used);
- memcpy(small_copy, oldtable, sizeof(small_copy));
- oldtable = small_copy;
- }
- }
- else {
- newtable = PyMem_NEW(setentry, newsize);
- if (newtable == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- }
-
- /* Make the set empty, using the new table. */
- assert(newtable != oldtable);
- so->table = newtable;
- so->mask = newsize - 1;
- memset(newtable, 0, sizeof(setentry) * newsize);
- so->used = 0;
- i = so->fill;
- so->fill = 0;
-
- /* Copy the data over; this is refcount-neutral for active entries;
- dummy entries aren't copied over, of course */
- for (entry = oldtable; i > 0; entry++) {
- if (entry->key == NULL) {
- /* UNUSED */
- ;
- } else if (entry->key == dummy) {
- /* DUMMY */
- --i;
- assert(entry->key == dummy);
- Py_DECREF(entry->key);
- } else {
- /* ACTIVE */
- --i;
- set_insert_clean(so, entry->key, entry->hash);
- }
- }
-
- if (is_oldtable_malloced)
- PyMem_DEL(oldtable);
- return 0;
+ Py_ssize_t newsize;
+ setentry *oldtable, *newtable, *entry;
+ Py_ssize_t i;
+ int is_oldtable_malloced;
+ setentry small_copy[PySet_MINSIZE];
+
+ assert(minused >= 0);
+
+ /* Find the smallest table size > minused. */
+ for (newsize = PySet_MINSIZE;
+ newsize <= minused && newsize > 0;
+ newsize <<= 1)
+ ;
+ if (newsize <= 0) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ /* Get space for a new table. */
+ oldtable = so->table;
+ assert(oldtable != NULL);
+ is_oldtable_malloced = oldtable != so->smalltable;
+
+ if (newsize == PySet_MINSIZE) {
+ /* A large table is shrinking, or we can't get any smaller. */
+ newtable = so->smalltable;
+ if (newtable == oldtable) {
+ if (so->fill == so->used) {
+ /* No dummies, so no point doing anything. */
+ return 0;
+ }
+ /* We're not going to resize it, but rebuild the
+ table anyway to purge old dummy entries.
+ Subtle: This is *necessary* if fill==size,
+ as set_lookkey needs at least one virgin slot to
+ terminate failing searches. If fill < size, it's
+ merely desirable, as dummies slow searches. */
+ assert(so->fill > so->used);
+ memcpy(small_copy, oldtable, sizeof(small_copy));
+ oldtable = small_copy;
+ }
+ }
+ else {
+ newtable = PyMem_NEW(setentry, newsize);
+ if (newtable == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ }
+
+ /* Make the set empty, using the new table. */
+ assert(newtable != oldtable);
+ so->table = newtable;
+ so->mask = newsize - 1;
+ memset(newtable, 0, sizeof(setentry) * newsize);
+ so->used = 0;
+ i = so->fill;
+ so->fill = 0;
+
+ /* Copy the data over; this is refcount-neutral for active entries;
+ dummy entries aren't copied over, of course */
+ for (entry = oldtable; i > 0; entry++) {
+ if (entry->key == NULL) {
+ /* UNUSED */
+ ;
+ } else if (entry->key == dummy) {
+ /* DUMMY */
+ --i;
+ assert(entry->key == dummy);
+ Py_DECREF(entry->key);
+ } else {
+ /* ACTIVE */
+ --i;
+ set_insert_clean(so, entry->key, entry->hash);
+ }
+ }
+
+ if (is_oldtable_malloced)
+ PyMem_DEL(oldtable);
+ return 0;
}
/* CAUTION: set_add_key/entry() must guarantee it won't resize the table */
@@ -361,42 +361,42 @@ set_table_resize(PySetObject *so, Py_ssize_t minused)
static int
set_add_entry(register PySetObject *so, setentry *entry)
{
- register Py_ssize_t n_used;
+ register Py_ssize_t n_used;
- assert(so->fill <= so->mask); /* at least one empty slot */
- n_used = so->used;
- Py_INCREF(entry->key);
- if (set_insert_key(so, entry->key, entry->hash) == -1) {
- Py_DECREF(entry->key);
- return -1;
- }
- if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
- return 0;
- return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
+ assert(so->fill <= so->mask); /* at least one empty slot */
+ n_used = so->used;
+ Py_INCREF(entry->key);
+ if (set_insert_key(so, entry->key, entry->hash) == -1) {
+ Py_DECREF(entry->key);
+ return -1;
+ }
+ if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
+ return 0;
+ return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
}
static int
set_add_key(register PySetObject *so, PyObject *key)
{
- register long hash;
- register Py_ssize_t n_used;
-
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return -1;
- }
- assert(so->fill <= so->mask); /* at least one empty slot */
- n_used = so->used;
- Py_INCREF(key);
- if (set_insert_key(so, key, hash) == -1) {
- Py_DECREF(key);
- return -1;
- }
- if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
- return 0;
- return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
+ register long hash;
+ register Py_ssize_t n_used;
+
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ assert(so->fill <= so->mask); /* at least one empty slot */
+ n_used = so->used;
+ Py_INCREF(key);
+ if (set_insert_key(so, key, hash) == -1) {
+ Py_DECREF(key);
+ return -1;
+ }
+ if (!(so->used > n_used && so->fill*3 >= (so->mask+1)*2))
+ return 0;
+ return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
}
#define DISCARD_NOTFOUND 0
@@ -404,111 +404,111 @@ set_add_key(register PySetObject *so, PyObject *key)
static int
set_discard_entry(PySetObject *so, setentry *oldentry)
-{ register setentry *entry;
- PyObject *old_key;
-
- entry = (so->lookup)(so, oldentry->key, oldentry->hash);
- if (entry == NULL)
- return -1;
- if (entry->key == NULL || entry->key == dummy)
- return DISCARD_NOTFOUND;
- old_key = entry->key;
- Py_INCREF(dummy);
- entry->key = dummy;
- so->used--;
- Py_DECREF(old_key);
- return DISCARD_FOUND;
+{ register setentry *entry;
+ PyObject *old_key;
+
+ entry = (so->lookup)(so, oldentry->key, oldentry->hash);
+ if (entry == NULL)
+ return -1;
+ if (entry->key == NULL || entry->key == dummy)
+ return DISCARD_NOTFOUND;
+ old_key = entry->key;
+ Py_INCREF(dummy);
+ entry->key = dummy;
+ so->used--;
+ Py_DECREF(old_key);
+ return DISCARD_FOUND;
}
static int
set_discard_key(PySetObject *so, PyObject *key)
{
- register long hash;
- register setentry *entry;
- PyObject *old_key;
-
- assert (PyAnySet_Check(so));
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return -1;
- }
- entry = (so->lookup)(so, key, hash);
- if (entry == NULL)
- return -1;
- if (entry->key == NULL || entry->key == dummy)
- return DISCARD_NOTFOUND;
- old_key = entry->key;
- Py_INCREF(dummy);
- entry->key = dummy;
- so->used--;
- Py_DECREF(old_key);
- return DISCARD_FOUND;
+ register long hash;
+ register setentry *entry;
+ PyObject *old_key;
+
+ assert (PyAnySet_Check(so));
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ entry = (so->lookup)(so, key, hash);
+ if (entry == NULL)
+ return -1;
+ if (entry->key == NULL || entry->key == dummy)
+ return DISCARD_NOTFOUND;
+ old_key = entry->key;
+ Py_INCREF(dummy);
+ entry->key = dummy;
+ so->used--;
+ Py_DECREF(old_key);
+ return DISCARD_FOUND;
}
static int
set_clear_internal(PySetObject *so)
{
- setentry *entry, *table;
- int table_is_malloced;
- Py_ssize_t fill;
- setentry small_copy[PySet_MINSIZE];
+ setentry *entry, *table;
+ int table_is_malloced;
+ Py_ssize_t fill;
+ setentry small_copy[PySet_MINSIZE];
#ifdef Py_DEBUG
- Py_ssize_t i, n;
- assert (PyAnySet_Check(so));
+ Py_ssize_t i, n;
+ assert (PyAnySet_Check(so));
- n = so->mask + 1;
- i = 0;
+ n = so->mask + 1;
+ i = 0;
#endif
- table = so->table;
- assert(table != NULL);
- table_is_malloced = table != so->smalltable;
-
- /* This is delicate. During the process of clearing the set,
- * decrefs can cause the set to mutate. To avoid fatal confusion
- * (voice of experience), we have to make the set empty before
- * clearing the slots, and never refer to anything via so->ref while
- * clearing.
- */
- fill = so->fill;
- if (table_is_malloced)
- EMPTY_TO_MINSIZE(so);
-
- else if (fill > 0) {
- /* It's a small table with something that needs to be cleared.
- * Afraid the only safe way is to copy the set entries into
- * another small table first.
- */
- memcpy(small_copy, table, sizeof(small_copy));
- table = small_copy;
- EMPTY_TO_MINSIZE(so);
- }
- /* else it's a small table that's already empty */
-
- /* Now we can finally clear things. If C had refcounts, we could
- * assert that the refcount on table is 1 now, i.e. that this function
- * has unique access to it, so decref side-effects can't alter it.
- */
- for (entry = table; fill > 0; ++entry) {
+ table = so->table;
+ assert(table != NULL);
+ table_is_malloced = table != so->smalltable;
+
+ /* This is delicate. During the process of clearing the set,
+ * decrefs can cause the set to mutate. To avoid fatal confusion
+ * (voice of experience), we have to make the set empty before
+ * clearing the slots, and never refer to anything via so->ref while
+ * clearing.
+ */
+ fill = so->fill;
+ if (table_is_malloced)
+ EMPTY_TO_MINSIZE(so);
+
+ else if (fill > 0) {
+ /* It's a small table with something that needs to be cleared.
+ * Afraid the only safe way is to copy the set entries into
+ * another small table first.
+ */
+ memcpy(small_copy, table, sizeof(small_copy));
+ table = small_copy;
+ EMPTY_TO_MINSIZE(so);
+ }
+ /* else it's a small table that's already empty */
+
+ /* Now we can finally clear things. If C had refcounts, we could
+ * assert that the refcount on table is 1 now, i.e. that this function
+ * has unique access to it, so decref side-effects can't alter it.
+ */
+ for (entry = table; fill > 0; ++entry) {
#ifdef Py_DEBUG
- assert(i < n);
- ++i;
+ assert(i < n);
+ ++i;
#endif
- if (entry->key) {
- --fill;
- Py_DECREF(entry->key);
- }
+ if (entry->key) {
+ --fill;
+ Py_DECREF(entry->key);
+ }
#ifdef Py_DEBUG
- else
- assert(entry->key == NULL);
+ else
+ assert(entry->key == NULL);
#endif
- }
+ }
- if (table_is_malloced)
- PyMem_DEL(table);
- return 0;
+ if (table_is_malloced)
+ PyMem_DEL(table);
+ return 0;
}
/*
@@ -522,236 +522,236 @@ set_clear_internal(PySetObject *so)
* }
*
* CAUTION: In general, it isn't safe to use set_next in a loop that
- * mutates the table.
+ * mutates the table.
*/
static int
set_next(PySetObject *so, Py_ssize_t *pos_ptr, setentry **entry_ptr)
{
- Py_ssize_t i;
- Py_ssize_t mask;
- register setentry *table;
-
- assert (PyAnySet_Check(so));
- i = *pos_ptr;
- assert(i >= 0);
- table = so->table;
- mask = so->mask;
- while (i <= mask && (table[i].key == NULL || table[i].key == dummy))
- i++;
- *pos_ptr = i+1;
- if (i > mask)
- return 0;
- assert(table[i].key != NULL);
- *entry_ptr = &table[i];
- return 1;
+ Py_ssize_t i;
+ Py_ssize_t mask;
+ register setentry *table;
+
+ assert (PyAnySet_Check(so));
+ i = *pos_ptr;
+ assert(i >= 0);
+ table = so->table;
+ mask = so->mask;
+ while (i <= mask && (table[i].key == NULL || table[i].key == dummy))
+ i++;
+ *pos_ptr = i+1;
+ if (i > mask)
+ return 0;
+ assert(table[i].key != NULL);
+ *entry_ptr = &table[i];
+ return 1;
}
static void
set_dealloc(PySetObject *so)
{
- register setentry *entry;
- Py_ssize_t fill = so->fill;
- PyObject_GC_UnTrack(so);
- Py_TRASHCAN_SAFE_BEGIN(so)
- if (so->weakreflist != NULL)
- PyObject_ClearWeakRefs((PyObject *) so);
-
- for (entry = so->table; fill > 0; entry++) {
- if (entry->key) {
- --fill;
- Py_DECREF(entry->key);
- }
- }
- if (so->table != so->smalltable)
- PyMem_DEL(so->table);
- if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so))
- free_list[numfree++] = so;
- else
- Py_TYPE(so)->tp_free(so);
- Py_TRASHCAN_SAFE_END(so)
+ register setentry *entry;
+ Py_ssize_t fill = so->fill;
+ PyObject_GC_UnTrack(so);
+ Py_TRASHCAN_SAFE_BEGIN(so)
+ if (so->weakreflist != NULL)
+ PyObject_ClearWeakRefs((PyObject *) so);
+
+ for (entry = so->table; fill > 0; entry++) {
+ if (entry->key) {
+ --fill;
+ Py_DECREF(entry->key);
+ }
+ }
+ if (so->table != so->smalltable)
+ PyMem_DEL(so->table);
+ if (numfree < PySet_MAXFREELIST && PyAnySet_CheckExact(so))
+ free_list[numfree++] = so;
+ else
+ Py_TYPE(so)->tp_free(so);
+ Py_TRASHCAN_SAFE_END(so)
}
static int
set_tp_print(PySetObject *so, FILE *fp, int flags)
{
- setentry *entry;
- Py_ssize_t pos=0;
- char *emit = ""; /* No separator emitted on first pass */
- char *separator = ", ";
- int status = Py_ReprEnter((PyObject*)so);
-
- if (status != 0) {
- if (status < 0)
- return status;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "%s(...)", so->ob_type->tp_name);
- Py_END_ALLOW_THREADS
- return 0;
- }
-
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "%s([", so->ob_type->tp_name);
- Py_END_ALLOW_THREADS
- while (set_next(so, &pos, &entry)) {
- Py_BEGIN_ALLOW_THREADS
- fputs(emit, fp);
- Py_END_ALLOW_THREADS
- emit = separator;
- if (PyObject_Print(entry->key, fp, 0) != 0) {
- Py_ReprLeave((PyObject*)so);
- return -1;
- }
- }
- Py_BEGIN_ALLOW_THREADS
- fputs("])", fp);
- Py_END_ALLOW_THREADS
- Py_ReprLeave((PyObject*)so);
- return 0;
+ setentry *entry;
+ Py_ssize_t pos=0;
+ char *emit = ""; /* No separator emitted on first pass */
+ char *separator = ", ";
+ int status = Py_ReprEnter((PyObject*)so);
+
+ if (status != 0) {
+ if (status < 0)
+ return status;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "%s(...)", so->ob_type->tp_name);
+ Py_END_ALLOW_THREADS
+ return 0;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "%s([", so->ob_type->tp_name);
+ Py_END_ALLOW_THREADS
+ while (set_next(so, &pos, &entry)) {
+ Py_BEGIN_ALLOW_THREADS
+ fputs(emit, fp);
+ Py_END_ALLOW_THREADS
+ emit = separator;
+ if (PyObject_Print(entry->key, fp, 0) != 0) {
+ Py_ReprLeave((PyObject*)so);
+ return -1;
+ }
+ }
+ Py_BEGIN_ALLOW_THREADS
+ fputs("])", fp);
+ Py_END_ALLOW_THREADS
+ Py_ReprLeave((PyObject*)so);
+ return 0;
}
static PyObject *
set_repr(PySetObject *so)
{
- PyObject *keys, *result=NULL, *listrepr;
- int status = Py_ReprEnter((PyObject*)so);
-
- if (status != 0) {
- if (status < 0)
- return NULL;
- return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
- }
-
- keys = PySequence_List((PyObject *)so);
- if (keys == NULL)
- goto done;
- listrepr = PyObject_Repr(keys);
- Py_DECREF(keys);
- if (listrepr == NULL)
- goto done;
-
- result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
- PyString_AS_STRING(listrepr));
- Py_DECREF(listrepr);
+ PyObject *keys, *result=NULL, *listrepr;
+ int status = Py_ReprEnter((PyObject*)so);
+
+ if (status != 0) {
+ if (status < 0)
+ return NULL;
+ return PyString_FromFormat("%s(...)", so->ob_type->tp_name);
+ }
+
+ keys = PySequence_List((PyObject *)so);
+ if (keys == NULL)
+ goto done;
+ listrepr = PyObject_Repr(keys);
+ Py_DECREF(keys);
+ if (listrepr == NULL)
+ goto done;
+
+ result = PyString_FromFormat("%s(%s)", so->ob_type->tp_name,
+ PyString_AS_STRING(listrepr));
+ Py_DECREF(listrepr);
done:
- Py_ReprLeave((PyObject*)so);
- return result;
+ Py_ReprLeave((PyObject*)so);
+ return result;
}
static Py_ssize_t
set_len(PyObject *so)
{
- return ((PySetObject *)so)->used;
+ return ((PySetObject *)so)->used;
}
static int
set_merge(PySetObject *so, PyObject *otherset)
{
- PySetObject *other;
- register Py_ssize_t i;
- register setentry *entry;
-
- assert (PyAnySet_Check(so));
- assert (PyAnySet_Check(otherset));
-
- other = (PySetObject*)otherset;
- if (other == so || other->used == 0)
- /* a.update(a) or a.update({}); nothing to do */
- return 0;
- /* Do one big resize at the start, rather than
- * incrementally resizing as we insert new keys. Expect
- * that there will be no (or few) overlapping keys.
- */
- if ((so->fill + other->used)*3 >= (so->mask+1)*2) {
- if (set_table_resize(so, (so->used + other->used)*2) != 0)
- return -1;
- }
- for (i = 0; i <= other->mask; i++) {
- entry = &other->table[i];
- if (entry->key != NULL &&
- entry->key != dummy) {
- Py_INCREF(entry->key);
- if (set_insert_key(so, entry->key, entry->hash) == -1) {
- Py_DECREF(entry->key);
- return -1;
- }
- }
- }
- return 0;
+ PySetObject *other;
+ register Py_ssize_t i;
+ register setentry *entry;
+
+ assert (PyAnySet_Check(so));
+ assert (PyAnySet_Check(otherset));
+
+ other = (PySetObject*)otherset;
+ if (other == so || other->used == 0)
+ /* a.update(a) or a.update({}); nothing to do */
+ return 0;
+ /* Do one big resize at the start, rather than
+ * incrementally resizing as we insert new keys. Expect
+ * that there will be no (or few) overlapping keys.
+ */
+ if ((so->fill + other->used)*3 >= (so->mask+1)*2) {
+ if (set_table_resize(so, (so->used + other->used)*2) != 0)
+ return -1;
+ }
+ for (i = 0; i <= other->mask; i++) {
+ entry = &other->table[i];
+ if (entry->key != NULL &&
+ entry->key != dummy) {
+ Py_INCREF(entry->key);
+ if (set_insert_key(so, entry->key, entry->hash) == -1) {
+ Py_DECREF(entry->key);
+ return -1;
+ }
+ }
+ }
+ return 0;
}
static int
set_contains_key(PySetObject *so, PyObject *key)
{
- long hash;
- setentry *entry;
+ long hash;
+ setentry *entry;
- if (!PyString_CheckExact(key) ||
- (hash = ((PyStringObject *) key)->ob_shash) == -1) {
- hash = PyObject_Hash(key);
- if (hash == -1)
- return -1;
- }
- entry = (so->lookup)(so, key, hash);
- if (entry == NULL)
- return -1;
- key = entry->key;
- return key != NULL && key != dummy;
+ if (!PyString_CheckExact(key) ||
+ (hash = ((PyStringObject *) key)->ob_shash) == -1) {
+ hash = PyObject_Hash(key);
+ if (hash == -1)
+ return -1;
+ }
+ entry = (so->lookup)(so, key, hash);
+ if (entry == NULL)
+ return -1;
+ key = entry->key;
+ return key != NULL && key != dummy;
}
static int
set_contains_entry(PySetObject *so, setentry *entry)
{
- PyObject *key;
- setentry *lu_entry;
+ PyObject *key;
+ setentry *lu_entry;
- lu_entry = (so->lookup)(so, entry->key, entry->hash);
- if (lu_entry == NULL)
- return -1;
- key = lu_entry->key;
- return key != NULL && key != dummy;
+ lu_entry = (so->lookup)(so, entry->key, entry->hash);
+ if (lu_entry == NULL)
+ return -1;
+ key = lu_entry->key;
+ return key != NULL && key != dummy;
}
static PyObject *
set_pop(PySetObject *so)
{
- register Py_ssize_t i = 0;
- register setentry *entry;
- PyObject *key;
-
- assert (PyAnySet_Check(so));
- if (so->used == 0) {
- PyErr_SetString(PyExc_KeyError, "pop from an empty set");
- return NULL;
- }
-
- /* Set entry to "the first" unused or dummy set entry. We abuse
- * the hash field of slot 0 to hold a search finger:
- * If slot 0 has a value, use slot 0.
- * Else slot 0 is being used to hold a search finger,
- * and we use its hash value as the first index to look.
- */
- entry = &so->table[0];
- if (entry->key == NULL || entry->key == dummy) {
- i = entry->hash;
- /* The hash field may be a real hash value, or it may be a
- * legit search finger, or it may be a once-legit search
- * finger that's out of bounds now because it wrapped around
- * or the table shrunk -- simply make sure it's in bounds now.
- */
- if (i > so->mask || i < 1)
- i = 1; /* skip slot 0 */
- while ((entry = &so->table[i])->key == NULL || entry->key==dummy) {
- i++;
- if (i > so->mask)
- i = 1;
- }
- }
- key = entry->key;
- Py_INCREF(dummy);
- entry->key = dummy;
- so->used--;
- so->table[0].hash = i + 1; /* next place to start */
- return key;
+ register Py_ssize_t i = 0;
+ register setentry *entry;
+ PyObject *key;
+
+ assert (PyAnySet_Check(so));
+ if (so->used == 0) {
+ PyErr_SetString(PyExc_KeyError, "pop from an empty set");
+ return NULL;
+ }
+
+ /* Set entry to "the first" unused or dummy set entry. We abuse
+ * the hash field of slot 0 to hold a search finger:
+ * If slot 0 has a value, use slot 0.
+ * Else slot 0 is being used to hold a search finger,
+ * and we use its hash value as the first index to look.
+ */
+ entry = &so->table[0];
+ if (entry->key == NULL || entry->key == dummy) {
+ i = entry->hash;
+ /* The hash field may be a real hash value, or it may be a
+ * legit search finger, or it may be a once-legit search
+ * finger that's out of bounds now because it wrapped around
+ * or the table shrunk -- simply make sure it's in bounds now.
+ */
+ if (i > so->mask || i < 1)
+ i = 1; /* skip slot 0 */
+ while ((entry = &so->table[i])->key == NULL || entry->key==dummy) {
+ i++;
+ if (i > so->mask)
+ i = 1;
+ }
+ }
+ key = entry->key;
+ Py_INCREF(dummy);
+ entry->key = dummy;
+ so->used--;
+ so->table[0].hash = i + 1; /* next place to start */
+ return key;
}
PyDoc_STRVAR(pop_doc, "Remove and return an arbitrary set element.\n\
@@ -760,277 +760,277 @@ Raises KeyError if the set is empty.");
static int
set_traverse(PySetObject *so, visitproc visit, void *arg)
{
- Py_ssize_t pos = 0;
- setentry *entry;
+ Py_ssize_t pos = 0;
+ setentry *entry;
- while (set_next(so, &pos, &entry))
- Py_VISIT(entry->key);
- return 0;
+ while (set_next(so, &pos, &entry))
+ Py_VISIT(entry->key);
+ return 0;
}
static long
frozenset_hash(PyObject *self)
{
- PySetObject *so = (PySetObject *)self;
- long h, hash = 1927868237L;
- setentry *entry;
- Py_ssize_t pos = 0;
-
- if (so->hash != -1)
- return so->hash;
-
- hash *= PySet_GET_SIZE(self) + 1;
- while (set_next(so, &pos, &entry)) {
- /* Work to increase the bit dispersion for closely spaced hash
- values. The is important because some use cases have many
- combinations of a small number of elements with nearby
- hashes so that many distinct combinations collapse to only
- a handful of distinct hash values. */
- h = entry->hash;
- hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u;
- }
- hash = hash * 69069L + 907133923L;
- if (hash == -1)
- hash = 590923713L;
- so->hash = hash;
- return hash;
+ PySetObject *so = (PySetObject *)self;
+ long h, hash = 1927868237L;
+ setentry *entry;
+ Py_ssize_t pos = 0;
+
+ if (so->hash != -1)
+ return so->hash;
+
+ hash *= PySet_GET_SIZE(self) + 1;
+ while (set_next(so, &pos, &entry)) {
+ /* Work to increase the bit dispersion for closely spaced hash
+ values. The is important because some use cases have many
+ combinations of a small number of elements with nearby
+ hashes so that many distinct combinations collapse to only
+ a handful of distinct hash values. */
+ h = entry->hash;
+ hash ^= (h ^ (h << 16) ^ 89869747L) * 3644798167u;
+ }
+ hash = hash * 69069L + 907133923L;
+ if (hash == -1)
+ hash = 590923713L;
+ so->hash = hash;
+ return hash;
}
/***** Set iterator type ***********************************************/
typedef struct {
- PyObject_HEAD
- PySetObject *si_set; /* Set to NULL when iterator is exhausted */
- Py_ssize_t si_used;
- Py_ssize_t si_pos;
- Py_ssize_t len;
+ PyObject_HEAD
+ PySetObject *si_set; /* Set to NULL when iterator is exhausted */
+ Py_ssize_t si_used;
+ Py_ssize_t si_pos;
+ Py_ssize_t len;
} setiterobject;
static void
setiter_dealloc(setiterobject *si)
{
- Py_XDECREF(si->si_set);
- PyObject_GC_Del(si);
+ Py_XDECREF(si->si_set);
+ PyObject_GC_Del(si);
}
static int
setiter_traverse(setiterobject *si, visitproc visit, void *arg)
{
- Py_VISIT(si->si_set);
- return 0;
+ Py_VISIT(si->si_set);
+ return 0;
}
static PyObject *
setiter_len(setiterobject *si)
{
- Py_ssize_t len = 0;
- if (si->si_set != NULL && si->si_used == si->si_set->used)
- len = si->len;
- return PyInt_FromLong(len);
+ Py_ssize_t len = 0;
+ if (si->si_set != NULL && si->si_used == si->si_set->used)
+ len = si->len;
+ return PyInt_FromLong(len);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef setiter_methods[] = {
- {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)setiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *setiter_iternext(setiterobject *si)
{
- PyObject *key;
- register Py_ssize_t i, mask;
- register setentry *entry;
- PySetObject *so = si->si_set;
-
- if (so == NULL)
- return NULL;
- assert (PyAnySet_Check(so));
-
- if (si->si_used != so->used) {
- PyErr_SetString(PyExc_RuntimeError,
- "Set changed size during iteration");
- si->si_used = -1; /* Make this state sticky */
- return NULL;
- }
-
- i = si->si_pos;
- assert(i>=0);
- entry = so->table;
- mask = so->mask;
- while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
- i++;
- si->si_pos = i+1;
- if (i > mask)
- goto fail;
- si->len--;
- key = entry[i].key;
- Py_INCREF(key);
- return key;
+ PyObject *key;
+ register Py_ssize_t i, mask;
+ register setentry *entry;
+ PySetObject *so = si->si_set;
+
+ if (so == NULL)
+ return NULL;
+ assert (PyAnySet_Check(so));
+
+ if (si->si_used != so->used) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Set changed size during iteration");
+ si->si_used = -1; /* Make this state sticky */
+ return NULL;
+ }
+
+ i = si->si_pos;
+ assert(i>=0);
+ entry = so->table;
+ mask = so->mask;
+ while (i <= mask && (entry[i].key == NULL || entry[i].key == dummy))
+ i++;
+ si->si_pos = i+1;
+ if (i > mask)
+ goto fail;
+ si->len--;
+ key = entry[i].key;
+ Py_INCREF(key);
+ return key;
fail:
- Py_DECREF(so);
- si->si_set = NULL;
- return NULL;
+ Py_DECREF(so);
+ si->si_set = NULL;
+ return NULL;
}
static PyTypeObject PySetIter_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "setiterator", /* tp_name */
- sizeof(setiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)setiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)setiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)setiter_iternext, /* tp_iternext */
- setiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "setiterator", /* tp_name */
+ sizeof(setiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)setiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)setiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)setiter_iternext, /* tp_iternext */
+ setiter_methods, /* tp_methods */
+ 0,
};
static PyObject *
set_iter(PySetObject *so)
{
- setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
- if (si == NULL)
- return NULL;
- Py_INCREF(so);
- si->si_set = so;
- si->si_used = so->used;
- si->si_pos = 0;
- si->len = so->used;
- _PyObject_GC_TRACK(si);
- return (PyObject *)si;
+ setiterobject *si = PyObject_GC_New(setiterobject, &PySetIter_Type);
+ if (si == NULL)
+ return NULL;
+ Py_INCREF(so);
+ si->si_set = so;
+ si->si_used = so->used;
+ si->si_pos = 0;
+ si->len = so->used;
+ _PyObject_GC_TRACK(si);
+ return (PyObject *)si;
}
static int
set_update_internal(PySetObject *so, PyObject *other)
{
- PyObject *key, *it;
-
- if (PyAnySet_Check(other))
- return set_merge(so, other);
-
- if (PyDict_CheckExact(other)) {
- PyObject *value;
- Py_ssize_t pos = 0;
- long hash;
- Py_ssize_t dictsize = PyDict_Size(other);
-
- /* Do one big resize at the start, rather than
- * incrementally resizing as we insert new keys. Expect
- * that there will be no (or few) overlapping keys.
- */
- if (dictsize == -1)
- return -1;
- if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
- if (set_table_resize(so, (so->used + dictsize)*2) != 0)
- return -1;
- }
- while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
- setentry an_entry;
-
- an_entry.hash = hash;
- an_entry.key = key;
- if (set_add_entry(so, &an_entry) == -1)
- return -1;
- }
- return 0;
- }
-
- it = PyObject_GetIter(other);
- if (it == NULL)
- return -1;
-
- while ((key = PyIter_Next(it)) != NULL) {
- if (set_add_key(so, key) == -1) {
- Py_DECREF(it);
- Py_DECREF(key);
- return -1;
- }
- Py_DECREF(key);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return -1;
- return 0;
+ PyObject *key, *it;
+
+ if (PyAnySet_Check(other))
+ return set_merge(so, other);
+
+ if (PyDict_CheckExact(other)) {
+ PyObject *value;
+ Py_ssize_t pos = 0;
+ long hash;
+ Py_ssize_t dictsize = PyDict_Size(other);
+
+ /* Do one big resize at the start, rather than
+ * incrementally resizing as we insert new keys. Expect
+ * that there will be no (or few) overlapping keys.
+ */
+ if (dictsize == -1)
+ return -1;
+ if ((so->fill + dictsize)*3 >= (so->mask+1)*2) {
+ if (set_table_resize(so, (so->used + dictsize)*2) != 0)
+ return -1;
+ }
+ while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
+ setentry an_entry;
+
+ an_entry.hash = hash;
+ an_entry.key = key;
+ if (set_add_entry(so, &an_entry) == -1)
+ return -1;
+ }
+ return 0;
+ }
+
+ it = PyObject_GetIter(other);
+ if (it == NULL)
+ return -1;
+
+ while ((key = PyIter_Next(it)) != NULL) {
+ if (set_add_key(so, key) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(key);
+ return -1;
+ }
+ Py_DECREF(key);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return -1;
+ return 0;
}
static PyObject *
set_update(PySetObject *so, PyObject *args)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
- PyObject *other = PyTuple_GET_ITEM(args, i);
- if (set_update_internal(so, other) == -1)
- return NULL;
- }
- Py_RETURN_NONE;
+ for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
+ PyObject *other = PyTuple_GET_ITEM(args, i);
+ if (set_update_internal(so, other) == -1)
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(update_doc,
+PyDoc_STRVAR(update_doc,
"Update a set with the union of itself and others.");
static PyObject *
make_new_set(PyTypeObject *type, PyObject *iterable)
{
- register PySetObject *so = NULL;
-
- if (dummy == NULL) { /* Auto-initialize dummy */
- dummy = PyString_FromString("<dummy key>");
- if (dummy == NULL)
- return NULL;
- }
-
- /* create PySetObject structure */
- if (numfree &&
- (type == &PySet_Type || type == &PyFrozenSet_Type)) {
- so = free_list[--numfree];
- assert (so != NULL && PyAnySet_CheckExact(so));
- Py_TYPE(so) = type;
- _Py_NewReference((PyObject *)so);
- EMPTY_TO_MINSIZE(so);
- PyObject_GC_Track(so);
- } else {
- so = (PySetObject *)type->tp_alloc(type, 0);
- if (so == NULL)
- return NULL;
- /* tp_alloc has already zeroed the structure */
- assert(so->table == NULL && so->fill == 0 && so->used == 0);
- INIT_NONZERO_SET_SLOTS(so);
- }
-
- so->lookup = set_lookkey_string;
- so->weakreflist = NULL;
-
- if (iterable != NULL) {
- if (set_update_internal(so, iterable) == -1) {
- Py_DECREF(so);
- return NULL;
- }
- }
-
- return (PyObject *)so;
+ register PySetObject *so = NULL;
+
+ if (dummy == NULL) { /* Auto-initialize dummy */
+ dummy = PyString_FromString("<dummy key>");
+ if (dummy == NULL)
+ return NULL;
+ }
+
+ /* create PySetObject structure */
+ if (numfree &&
+ (type == &PySet_Type || type == &PyFrozenSet_Type)) {
+ so = free_list[--numfree];
+ assert (so != NULL && PyAnySet_CheckExact(so));
+ Py_TYPE(so) = type;
+ _Py_NewReference((PyObject *)so);
+ EMPTY_TO_MINSIZE(so);
+ PyObject_GC_Track(so);
+ } else {
+ so = (PySetObject *)type->tp_alloc(type, 0);
+ if (so == NULL)
+ return NULL;
+ /* tp_alloc has already zeroed the structure */
+ assert(so->table == NULL && so->fill == 0 && so->used == 0);
+ INIT_NONZERO_SET_SLOTS(so);
+ }
+
+ so->lookup = set_lookkey_string;
+ so->weakreflist = NULL;
+
+ if (iterable != NULL) {
+ if (set_update_internal(so, iterable) == -1) {
+ Py_DECREF(so);
+ return NULL;
+ }
+ }
+
+ return (PyObject *)so;
}
/* The empty frozenset is a singleton */
@@ -1039,56 +1039,56 @@ static PyObject *emptyfrozenset = NULL;
static PyObject *
frozenset_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *iterable = NULL, *result;
+ PyObject *iterable = NULL, *result;
- if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
- return NULL;
+ if (type == &PyFrozenSet_Type && !_PyArg_NoKeywords("frozenset()", kwds))
+ return NULL;
- if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
- return NULL;
+ if (!PyArg_UnpackTuple(args, type->tp_name, 0, 1, &iterable))
+ return NULL;
- if (type != &PyFrozenSet_Type)
- return make_new_set(type, iterable);
+ if (type != &PyFrozenSet_Type)
+ return make_new_set(type, iterable);
- if (iterable != NULL) {
- /* frozenset(f) is idempotent */
- if (PyFrozenSet_CheckExact(iterable)) {
- Py_INCREF(iterable);
- return iterable;
- }
- result = make_new_set(type, iterable);
- if (result == NULL || PySet_GET_SIZE(result))
- return result;
- Py_DECREF(result);
- }
- /* The empty frozenset is a singleton */
- if (emptyfrozenset == NULL)
- emptyfrozenset = make_new_set(type, NULL);
- Py_XINCREF(emptyfrozenset);
- return emptyfrozenset;
+ if (iterable != NULL) {
+ /* frozenset(f) is idempotent */
+ if (PyFrozenSet_CheckExact(iterable)) {
+ Py_INCREF(iterable);
+ return iterable;
+ }
+ result = make_new_set(type, iterable);
+ if (result == NULL || PySet_GET_SIZE(result))
+ return result;
+ Py_DECREF(result);
+ }
+ /* The empty frozenset is a singleton */
+ if (emptyfrozenset == NULL)
+ emptyfrozenset = make_new_set(type, NULL);
+ Py_XINCREF(emptyfrozenset);
+ return emptyfrozenset;
}
void
PySet_Fini(void)
{
- PySetObject *so;
+ PySetObject *so;
- while (numfree) {
- numfree--;
- so = free_list[numfree];
- PyObject_GC_Del(so);
- }
- Py_CLEAR(dummy);
- Py_CLEAR(emptyfrozenset);
+ while (numfree) {
+ numfree--;
+ so = free_list[numfree];
+ PyObject_GC_Del(so);
+ }
+ Py_CLEAR(dummy);
+ Py_CLEAR(emptyfrozenset);
}
static PyObject *
set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
- return NULL;
-
- return make_new_set(type, NULL);
+ if (type == &PySet_Type && !_PyArg_NoKeywords("set()", kwds))
+ return NULL;
+
+ return make_new_set(type, NULL);
}
/* set_swap_bodies() switches the contents of any two sets by moving their
@@ -1098,64 +1098,64 @@ set_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
t=set(a); a.clear(); a.update(b); b.clear(); b.update(t); del t
The function always succeeds and it leaves both objects in a stable state.
- Useful for creating temporary frozensets from sets for membership testing
+ Useful for creating temporary frozensets from sets for membership testing
in __contains__(), discard(), and remove(). Also useful for operations
- that update in-place (by allowing an intermediate result to be swapped
+ that update in-place (by allowing an intermediate result to be swapped
into one of the original inputs).
*/
static void
set_swap_bodies(PySetObject *a, PySetObject *b)
{
- Py_ssize_t t;
- setentry *u;
- setentry *(*f)(PySetObject *so, PyObject *key, long hash);
- setentry tab[PySet_MINSIZE];
- long h;
-
- t = a->fill; a->fill = b->fill; b->fill = t;
- t = a->used; a->used = b->used; b->used = t;
- t = a->mask; a->mask = b->mask; b->mask = t;
-
- u = a->table;
- if (a->table == a->smalltable)
- u = b->smalltable;
- a->table = b->table;
- if (b->table == b->smalltable)
- a->table = a->smalltable;
- b->table = u;
-
- f = a->lookup; a->lookup = b->lookup; b->lookup = f;
-
- if (a->table == a->smalltable || b->table == b->smalltable) {
- memcpy(tab, a->smalltable, sizeof(tab));
- memcpy(a->smalltable, b->smalltable, sizeof(tab));
- memcpy(b->smalltable, tab, sizeof(tab));
- }
-
- if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) &&
- PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
- h = a->hash; a->hash = b->hash; b->hash = h;
- } else {
- a->hash = -1;
- b->hash = -1;
- }
+ Py_ssize_t t;
+ setentry *u;
+ setentry *(*f)(PySetObject *so, PyObject *key, long hash);
+ setentry tab[PySet_MINSIZE];
+ long h;
+
+ t = a->fill; a->fill = b->fill; b->fill = t;
+ t = a->used; a->used = b->used; b->used = t;
+ t = a->mask; a->mask = b->mask; b->mask = t;
+
+ u = a->table;
+ if (a->table == a->smalltable)
+ u = b->smalltable;
+ a->table = b->table;
+ if (b->table == b->smalltable)
+ a->table = a->smalltable;
+ b->table = u;
+
+ f = a->lookup; a->lookup = b->lookup; b->lookup = f;
+
+ if (a->table == a->smalltable || b->table == b->smalltable) {
+ memcpy(tab, a->smalltable, sizeof(tab));
+ memcpy(a->smalltable, b->smalltable, sizeof(tab));
+ memcpy(b->smalltable, tab, sizeof(tab));
+ }
+
+ if (PyType_IsSubtype(Py_TYPE(a), &PyFrozenSet_Type) &&
+ PyType_IsSubtype(Py_TYPE(b), &PyFrozenSet_Type)) {
+ h = a->hash; a->hash = b->hash; b->hash = h;
+ } else {
+ a->hash = -1;
+ b->hash = -1;
+ }
}
static PyObject *
set_copy(PySetObject *so)
{
- return make_new_set(Py_TYPE(so), (PyObject *)so);
+ return make_new_set(Py_TYPE(so), (PyObject *)so);
}
static PyObject *
frozenset_copy(PySetObject *so)
{
- if (PyFrozenSet_CheckExact(so)) {
- Py_INCREF(so);
- return (PyObject *)so;
- }
- return set_copy(so);
+ if (PyFrozenSet_CheckExact(so)) {
+ Py_INCREF(so);
+ return (PyObject *)so;
+ }
+ return set_copy(so);
}
PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set.");
@@ -1163,8 +1163,8 @@ PyDoc_STRVAR(copy_doc, "Return a shallow copy of a set.");
static PyObject *
set_clear(PySetObject *so)
{
- set_clear_internal(so);
- Py_RETURN_NONE;
+ set_clear_internal(so);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(clear_doc, "Remove all elements from this set.");
@@ -1172,24 +1172,24 @@ PyDoc_STRVAR(clear_doc, "Remove all elements from this set.");
static PyObject *
set_union(PySetObject *so, PyObject *args)
{
- PySetObject *result;
- PyObject *other;
- Py_ssize_t i;
+ PySetObject *result;
+ PyObject *other;
+ Py_ssize_t i;
- result = (PySetObject *)set_copy(so);
- if (result == NULL)
- return NULL;
+ result = (PySetObject *)set_copy(so);
+ if (result == NULL)
+ return NULL;
- for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
- other = PyTuple_GET_ITEM(args, i);
- if ((PyObject *)so == other)
- continue;
- if (set_update_internal(result, other) == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return (PyObject *)result;
+ for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
+ other = PyTuple_GET_ITEM(args, i);
+ if ((PyObject *)so == other)
+ continue;
+ if (set_update_internal(result, other) == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return (PyObject *)result;
}
PyDoc_STRVAR(union_doc,
@@ -1200,142 +1200,142 @@ PyDoc_STRVAR(union_doc,
static PyObject *
set_or(PySetObject *so, PyObject *other)
{
- PySetObject *result;
+ PySetObject *result;
- if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
+ if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
- result = (PySetObject *)set_copy(so);
- if (result == NULL)
- return NULL;
- if ((PyObject *)so == other)
- return (PyObject *)result;
- if (set_update_internal(result, other) == -1) {
- Py_DECREF(result);
- return NULL;
- }
- return (PyObject *)result;
+ result = (PySetObject *)set_copy(so);
+ if (result == NULL)
+ return NULL;
+ if ((PyObject *)so == other)
+ return (PyObject *)result;
+ if (set_update_internal(result, other) == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return (PyObject *)result;
}
static PyObject *
set_ior(PySetObject *so, PyObject *other)
{
- if (!PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (set_update_internal(so, other) == -1)
- return NULL;
- Py_INCREF(so);
- return (PyObject *)so;
+ if (!PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (set_update_internal(so, other) == -1)
+ return NULL;
+ Py_INCREF(so);
+ return (PyObject *)so;
}
static PyObject *
set_intersection(PySetObject *so, PyObject *other)
{
- PySetObject *result;
- PyObject *key, *it, *tmp;
-
- if ((PyObject *)so == other)
- return set_copy(so);
-
- result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
- if (result == NULL)
- return NULL;
-
- if (PyAnySet_Check(other)) {
- Py_ssize_t pos = 0;
- setentry *entry;
-
- if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
- tmp = (PyObject *)so;
- so = (PySetObject *)other;
- other = tmp;
- }
-
- while (set_next((PySetObject *)other, &pos, &entry)) {
- int rv = set_contains_entry(so, entry);
- if (rv == -1) {
- Py_DECREF(result);
- return NULL;
- }
- if (rv) {
- if (set_add_entry(result, entry) == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- }
- return (PyObject *)result;
- }
-
- it = PyObject_GetIter(other);
- if (it == NULL) {
- Py_DECREF(result);
- return NULL;
- }
-
- while ((key = PyIter_Next(it)) != NULL) {
- int rv;
- setentry entry;
- long hash = PyObject_Hash(key);
-
- if (hash == -1) {
- Py_DECREF(it);
- Py_DECREF(result);
- Py_DECREF(key);
- return NULL;
- }
- entry.hash = hash;
- entry.key = key;
- rv = set_contains_entry(so, &entry);
- if (rv == -1) {
- Py_DECREF(it);
- Py_DECREF(result);
- Py_DECREF(key);
- return NULL;
- }
- if (rv) {
- if (set_add_entry(result, &entry) == -1) {
- Py_DECREF(it);
- Py_DECREF(result);
- Py_DECREF(key);
- return NULL;
- }
- }
- Py_DECREF(key);
- }
- Py_DECREF(it);
- if (PyErr_Occurred()) {
- Py_DECREF(result);
- return NULL;
- }
- return (PyObject *)result;
+ PySetObject *result;
+ PyObject *key, *it, *tmp;
+
+ if ((PyObject *)so == other)
+ return set_copy(so);
+
+ result = (PySetObject *)make_new_set(Py_TYPE(so), NULL);
+ if (result == NULL)
+ return NULL;
+
+ if (PyAnySet_Check(other)) {
+ Py_ssize_t pos = 0;
+ setentry *entry;
+
+ if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
+ tmp = (PyObject *)so;
+ so = (PySetObject *)other;
+ other = tmp;
+ }
+
+ while (set_next((PySetObject *)other, &pos, &entry)) {
+ int rv = set_contains_entry(so, entry);
+ if (rv == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ if (rv) {
+ if (set_add_entry(result, entry) == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ }
+ return (PyObject *)result;
+ }
+
+ it = PyObject_GetIter(other);
+ if (it == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ while ((key = PyIter_Next(it)) != NULL) {
+ int rv;
+ setentry entry;
+ long hash = PyObject_Hash(key);
+
+ if (hash == -1) {
+ Py_DECREF(it);
+ Py_DECREF(result);
+ Py_DECREF(key);
+ return NULL;
+ }
+ entry.hash = hash;
+ entry.key = key;
+ rv = set_contains_entry(so, &entry);
+ if (rv == -1) {
+ Py_DECREF(it);
+ Py_DECREF(result);
+ Py_DECREF(key);
+ return NULL;
+ }
+ if (rv) {
+ if (set_add_entry(result, &entry) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(result);
+ Py_DECREF(key);
+ return NULL;
+ }
+ }
+ Py_DECREF(key);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred()) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ return (PyObject *)result;
}
static PyObject *
set_intersection_multi(PySetObject *so, PyObject *args)
{
- Py_ssize_t i;
- PyObject *result = (PyObject *)so;
+ Py_ssize_t i;
+ PyObject *result = (PyObject *)so;
- if (PyTuple_GET_SIZE(args) == 0)
- return set_copy(so);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return set_copy(so);
- Py_INCREF(so);
- for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
- PyObject *other = PyTuple_GET_ITEM(args, i);
- PyObject *newresult = set_intersection((PySetObject *)result, other);
- if (newresult == NULL) {
- Py_DECREF(result);
- return NULL;
- }
- Py_DECREF(result);
- result = newresult;
- }
- return result;
+ Py_INCREF(so);
+ for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
+ PyObject *other = PyTuple_GET_ITEM(args, i);
+ PyObject *newresult = set_intersection((PySetObject *)result, other);
+ if (newresult == NULL) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ Py_DECREF(result);
+ result = newresult;
+ }
+ return result;
}
PyDoc_STRVAR(intersection_doc,
@@ -1346,27 +1346,27 @@ PyDoc_STRVAR(intersection_doc,
static PyObject *
set_intersection_update(PySetObject *so, PyObject *other)
{
- PyObject *tmp;
+ PyObject *tmp;
- tmp = set_intersection(so, other);
- if (tmp == NULL)
- return NULL;
- set_swap_bodies(so, (PySetObject *)tmp);
- Py_DECREF(tmp);
- Py_RETURN_NONE;
+ tmp = set_intersection(so, other);
+ if (tmp == NULL)
+ return NULL;
+ set_swap_bodies(so, (PySetObject *)tmp);
+ Py_DECREF(tmp);
+ Py_RETURN_NONE;
}
static PyObject *
set_intersection_update_multi(PySetObject *so, PyObject *args)
{
- PyObject *tmp;
+ PyObject *tmp;
- tmp = set_intersection_multi(so, args);
- if (tmp == NULL)
- return NULL;
- set_swap_bodies(so, (PySetObject *)tmp);
- Py_DECREF(tmp);
- Py_RETURN_NONE;
+ tmp = set_intersection_multi(so, args);
+ if (tmp == NULL)
+ return NULL;
+ set_swap_bodies(so, (PySetObject *)tmp);
+ Py_DECREF(tmp);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(intersection_update_doc,
@@ -1375,92 +1375,92 @@ PyDoc_STRVAR(intersection_update_doc,
static PyObject *
set_and(PySetObject *so, PyObject *other)
{
- if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return set_intersection(so, other);
+ if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return set_intersection(so, other);
}
static PyObject *
set_iand(PySetObject *so, PyObject *other)
{
- PyObject *result;
+ PyObject *result;
- if (!PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- result = set_intersection_update(so, other);
- if (result == NULL)
- return NULL;
- Py_DECREF(result);
- Py_INCREF(so);
- return (PyObject *)so;
+ if (!PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ result = set_intersection_update(so, other);
+ if (result == NULL)
+ return NULL;
+ Py_DECREF(result);
+ Py_INCREF(so);
+ return (PyObject *)so;
}
static PyObject *
set_isdisjoint(PySetObject *so, PyObject *other)
{
- PyObject *key, *it, *tmp;
-
- if ((PyObject *)so == other) {
- if (PySet_GET_SIZE(so) == 0)
- Py_RETURN_TRUE;
- else
- Py_RETURN_FALSE;
- }
-
- if (PyAnySet_CheckExact(other)) {
- Py_ssize_t pos = 0;
- setentry *entry;
-
- if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
- tmp = (PyObject *)so;
- so = (PySetObject *)other;
- other = tmp;
- }
- while (set_next((PySetObject *)other, &pos, &entry)) {
- int rv = set_contains_entry(so, entry);
- if (rv == -1)
- return NULL;
- if (rv)
- Py_RETURN_FALSE;
- }
- Py_RETURN_TRUE;
- }
-
- it = PyObject_GetIter(other);
- if (it == NULL)
- return NULL;
-
- while ((key = PyIter_Next(it)) != NULL) {
- int rv;
- setentry entry;
- long hash = PyObject_Hash(key);
-
- if (hash == -1) {
- Py_DECREF(key);
- Py_DECREF(it);
- return NULL;
- }
- entry.hash = hash;
- entry.key = key;
- rv = set_contains_entry(so, &entry);
- Py_DECREF(key);
- if (rv == -1) {
- Py_DECREF(it);
- return NULL;
- }
- if (rv) {
- Py_DECREF(it);
- Py_RETURN_FALSE;
- }
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return NULL;
- Py_RETURN_TRUE;
+ PyObject *key, *it, *tmp;
+
+ if ((PyObject *)so == other) {
+ if (PySet_GET_SIZE(so) == 0)
+ Py_RETURN_TRUE;
+ else
+ Py_RETURN_FALSE;
+ }
+
+ if (PyAnySet_CheckExact(other)) {
+ Py_ssize_t pos = 0;
+ setentry *entry;
+
+ if (PySet_GET_SIZE(other) > PySet_GET_SIZE(so)) {
+ tmp = (PyObject *)so;
+ so = (PySetObject *)other;
+ other = tmp;
+ }
+ while (set_next((PySetObject *)other, &pos, &entry)) {
+ int rv = set_contains_entry(so, entry);
+ if (rv == -1)
+ return NULL;
+ if (rv)
+ Py_RETURN_FALSE;
+ }
+ Py_RETURN_TRUE;
+ }
+
+ it = PyObject_GetIter(other);
+ if (it == NULL)
+ return NULL;
+
+ while ((key = PyIter_Next(it)) != NULL) {
+ int rv;
+ setentry entry;
+ long hash = PyObject_Hash(key);
+
+ if (hash == -1) {
+ Py_DECREF(key);
+ Py_DECREF(it);
+ return NULL;
+ }
+ entry.hash = hash;
+ entry.key = key;
+ rv = set_contains_entry(so, &entry);
+ Py_DECREF(key);
+ if (rv == -1) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ if (rv) {
+ Py_DECREF(it);
+ Py_RETURN_FALSE;
+ }
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return NULL;
+ Py_RETURN_TRUE;
}
PyDoc_STRVAR(isdisjoint_doc,
@@ -1469,51 +1469,51 @@ PyDoc_STRVAR(isdisjoint_doc,
static int
set_difference_update_internal(PySetObject *so, PyObject *other)
{
- if ((PyObject *)so == other)
- return set_clear_internal(so);
-
- if (PyAnySet_Check(other)) {
- setentry *entry;
- Py_ssize_t pos = 0;
-
- while (set_next((PySetObject *)other, &pos, &entry))
- if (set_discard_entry(so, entry) == -1)
- return -1;
- } else {
- PyObject *key, *it;
- it = PyObject_GetIter(other);
- if (it == NULL)
- return -1;
-
- while ((key = PyIter_Next(it)) != NULL) {
- if (set_discard_key(so, key) == -1) {
- Py_DECREF(it);
- Py_DECREF(key);
- return -1;
- }
- Py_DECREF(key);
- }
- Py_DECREF(it);
- if (PyErr_Occurred())
- return -1;
- }
- /* If more than 1/5 are dummies, then resize them away. */
- if ((so->fill - so->used) * 5 < so->mask)
- return 0;
- return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
+ if ((PyObject *)so == other)
+ return set_clear_internal(so);
+
+ if (PyAnySet_Check(other)) {
+ setentry *entry;
+ Py_ssize_t pos = 0;
+
+ while (set_next((PySetObject *)other, &pos, &entry))
+ if (set_discard_entry(so, entry) == -1)
+ return -1;
+ } else {
+ PyObject *key, *it;
+ it = PyObject_GetIter(other);
+ if (it == NULL)
+ return -1;
+
+ while ((key = PyIter_Next(it)) != NULL) {
+ if (set_discard_key(so, key) == -1) {
+ Py_DECREF(it);
+ Py_DECREF(key);
+ return -1;
+ }
+ Py_DECREF(key);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred())
+ return -1;
+ }
+ /* If more than 1/5 are dummies, then resize them away. */
+ if ((so->fill - so->used) * 5 < so->mask)
+ return 0;
+ return set_table_resize(so, so->used>50000 ? so->used*2 : so->used*4);
}
static PyObject *
set_difference_update(PySetObject *so, PyObject *args)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
- PyObject *other = PyTuple_GET_ITEM(args, i);
- if (set_difference_update_internal(so, other) == -1)
- return NULL;
- }
- Py_RETURN_NONE;
+ for (i=0 ; i<PyTuple_GET_SIZE(args) ; i++) {
+ PyObject *other = PyTuple_GET_ITEM(args, i);
+ if (set_difference_update_internal(so, other) == -1)
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(difference_update_doc,
@@ -1522,77 +1522,77 @@ PyDoc_STRVAR(difference_update_doc,
static PyObject *
set_difference(PySetObject *so, PyObject *other)
{
- PyObject *result;
- setentry *entry;
- Py_ssize_t pos = 0;
-
- if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) {
- result = set_copy(so);
- if (result == NULL)
- return NULL;
- if (set_difference_update_internal((PySetObject *)result, other) != -1)
- return result;
- Py_DECREF(result);
- return NULL;
- }
-
- result = make_new_set(Py_TYPE(so), NULL);
- if (result == NULL)
- return NULL;
-
- if (PyDict_CheckExact(other)) {
- while (set_next(so, &pos, &entry)) {
- setentry entrycopy;
- entrycopy.hash = entry->hash;
- entrycopy.key = entry->key;
- if (!_PyDict_Contains(other, entry->key, entry->hash)) {
- if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- }
- return result;
- }
-
- while (set_next(so, &pos, &entry)) {
- int rv = set_contains_entry((PySetObject *)other, entry);
- if (rv == -1) {
- Py_DECREF(result);
- return NULL;
- }
- if (!rv) {
- if (set_add_entry((PySetObject *)result, entry) == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- }
- return result;
+ PyObject *result;
+ setentry *entry;
+ Py_ssize_t pos = 0;
+
+ if (!PyAnySet_Check(other) && !PyDict_CheckExact(other)) {
+ result = set_copy(so);
+ if (result == NULL)
+ return NULL;
+ if (set_difference_update_internal((PySetObject *)result, other) != -1)
+ return result;
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ result = make_new_set(Py_TYPE(so), NULL);
+ if (result == NULL)
+ return NULL;
+
+ if (PyDict_CheckExact(other)) {
+ while (set_next(so, &pos, &entry)) {
+ setentry entrycopy;
+ entrycopy.hash = entry->hash;
+ entrycopy.key = entry->key;
+ if (!_PyDict_Contains(other, entry->key, entry->hash)) {
+ if (set_add_entry((PySetObject *)result, &entrycopy) == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ }
+ return result;
+ }
+
+ while (set_next(so, &pos, &entry)) {
+ int rv = set_contains_entry((PySetObject *)other, entry);
+ if (rv == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ if (!rv) {
+ if (set_add_entry((PySetObject *)result, entry) == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ }
+ return result;
}
static PyObject *
set_difference_multi(PySetObject *so, PyObject *args)
{
- Py_ssize_t i;
- PyObject *result, *other;
+ Py_ssize_t i;
+ PyObject *result, *other;
- if (PyTuple_GET_SIZE(args) == 0)
- return set_copy(so);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return set_copy(so);
- other = PyTuple_GET_ITEM(args, 0);
- result = set_difference(so, other);
- if (result == NULL)
- return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ result = set_difference(so, other);
+ if (result == NULL)
+ return NULL;
- for (i=1 ; i<PyTuple_GET_SIZE(args) ; i++) {
- other = PyTuple_GET_ITEM(args, i);
- if (set_difference_update_internal((PySetObject *)result, other) == -1) {
- Py_DECREF(result);
- return NULL;
- }
- }
- return result;
+ for (i=1 ; i<PyTuple_GET_SIZE(args) ; i++) {
+ other = PyTuple_GET_ITEM(args, i);
+ if (set_difference_update_internal((PySetObject *)result, other) == -1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ }
+ return result;
}
PyDoc_STRVAR(difference_doc,
@@ -1602,81 +1602,81 @@ PyDoc_STRVAR(difference_doc,
static PyObject *
set_sub(PySetObject *so, PyObject *other)
{
- if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return set_difference(so, other);
+ if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return set_difference(so, other);
}
static PyObject *
set_isub(PySetObject *so, PyObject *other)
{
- if (!PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- if (set_difference_update_internal(so, other) == -1)
- return NULL;
- Py_INCREF(so);
- return (PyObject *)so;
+ if (!PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ if (set_difference_update_internal(so, other) == -1)
+ return NULL;
+ Py_INCREF(so);
+ return (PyObject *)so;
}
static PyObject *
set_symmetric_difference_update(PySetObject *so, PyObject *other)
{
- PySetObject *otherset;
- PyObject *key;
- Py_ssize_t pos = 0;
- setentry *entry;
-
- if ((PyObject *)so == other)
- return set_clear(so);
-
- if (PyDict_CheckExact(other)) {
- PyObject *value;
- int rv;
- long hash;
- while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
- setentry an_entry;
-
- an_entry.hash = hash;
- an_entry.key = key;
- rv = set_discard_entry(so, &an_entry);
- if (rv == -1)
- return NULL;
- if (rv == DISCARD_NOTFOUND) {
- if (set_add_entry(so, &an_entry) == -1)
- return NULL;
- }
- }
- Py_RETURN_NONE;
- }
-
- if (PyAnySet_Check(other)) {
- Py_INCREF(other);
- otherset = (PySetObject *)other;
- } else {
- otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
- if (otherset == NULL)
- return NULL;
- }
-
- while (set_next(otherset, &pos, &entry)) {
- int rv = set_discard_entry(so, entry);
- if (rv == -1) {
- Py_DECREF(otherset);
- return NULL;
- }
- if (rv == DISCARD_NOTFOUND) {
- if (set_add_entry(so, entry) == -1) {
- Py_DECREF(otherset);
- return NULL;
- }
- }
- }
- Py_DECREF(otherset);
- Py_RETURN_NONE;
+ PySetObject *otherset;
+ PyObject *key;
+ Py_ssize_t pos = 0;
+ setentry *entry;
+
+ if ((PyObject *)so == other)
+ return set_clear(so);
+
+ if (PyDict_CheckExact(other)) {
+ PyObject *value;
+ int rv;
+ long hash;
+ while (_PyDict_Next(other, &pos, &key, &value, &hash)) {
+ setentry an_entry;
+
+ an_entry.hash = hash;
+ an_entry.key = key;
+ rv = set_discard_entry(so, &an_entry);
+ if (rv == -1)
+ return NULL;
+ if (rv == DISCARD_NOTFOUND) {
+ if (set_add_entry(so, &an_entry) == -1)
+ return NULL;
+ }
+ }
+ Py_RETURN_NONE;
+ }
+
+ if (PyAnySet_Check(other)) {
+ Py_INCREF(other);
+ otherset = (PySetObject *)other;
+ } else {
+ otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
+ if (otherset == NULL)
+ return NULL;
+ }
+
+ while (set_next(otherset, &pos, &entry)) {
+ int rv = set_discard_entry(so, entry);
+ if (rv == -1) {
+ Py_DECREF(otherset);
+ return NULL;
+ }
+ if (rv == DISCARD_NOTFOUND) {
+ if (set_add_entry(so, entry) == -1) {
+ Py_DECREF(otherset);
+ return NULL;
+ }
+ }
+ }
+ Py_DECREF(otherset);
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(symmetric_difference_update_doc,
@@ -1685,17 +1685,17 @@ PyDoc_STRVAR(symmetric_difference_update_doc,
static PyObject *
set_symmetric_difference(PySetObject *so, PyObject *other)
{
- PyObject *rv;
- PySetObject *otherset;
+ PyObject *rv;
+ PySetObject *otherset;
- otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
- if (otherset == NULL)
- return NULL;
- rv = set_symmetric_difference_update(otherset, (PyObject *)so);
- if (rv == NULL)
- return NULL;
- Py_DECREF(rv);
- return (PyObject *)otherset;
+ otherset = (PySetObject *)make_new_set(Py_TYPE(so), other);
+ if (otherset == NULL)
+ return NULL;
+ rv = set_symmetric_difference_update(otherset, (PyObject *)so);
+ if (rv == NULL)
+ return NULL;
+ Py_DECREF(rv);
+ return (PyObject *)otherset;
}
PyDoc_STRVAR(symmetric_difference_doc,
@@ -1706,56 +1706,56 @@ PyDoc_STRVAR(symmetric_difference_doc,
static PyObject *
set_xor(PySetObject *so, PyObject *other)
{
- if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return set_symmetric_difference(so, other);
+ if (!PyAnySet_Check(so) || !PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return set_symmetric_difference(so, other);
}
static PyObject *
set_ixor(PySetObject *so, PyObject *other)
{
- PyObject *result;
+ PyObject *result;
- if (!PyAnySet_Check(other)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- result = set_symmetric_difference_update(so, other);
- if (result == NULL)
- return NULL;
- Py_DECREF(result);
- Py_INCREF(so);
- return (PyObject *)so;
+ if (!PyAnySet_Check(other)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ result = set_symmetric_difference_update(so, other);
+ if (result == NULL)
+ return NULL;
+ Py_DECREF(result);
+ Py_INCREF(so);
+ return (PyObject *)so;
}
static PyObject *
set_issubset(PySetObject *so, PyObject *other)
{
- setentry *entry;
- Py_ssize_t pos = 0;
-
- if (!PyAnySet_Check(other)) {
- PyObject *tmp, *result;
- tmp = make_new_set(&PySet_Type, other);
- if (tmp == NULL)
- return NULL;
- result = set_issubset(so, tmp);
- Py_DECREF(tmp);
- return result;
- }
- if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
- Py_RETURN_FALSE;
-
- while (set_next(so, &pos, &entry)) {
- int rv = set_contains_entry((PySetObject *)other, entry);
- if (rv == -1)
- return NULL;
- if (!rv)
- Py_RETURN_FALSE;
- }
- Py_RETURN_TRUE;
+ setentry *entry;
+ Py_ssize_t pos = 0;
+
+ if (!PyAnySet_Check(other)) {
+ PyObject *tmp, *result;
+ tmp = make_new_set(&PySet_Type, other);
+ if (tmp == NULL)
+ return NULL;
+ result = set_issubset(so, tmp);
+ Py_DECREF(tmp);
+ return result;
+ }
+ if (PySet_GET_SIZE(so) > PySet_GET_SIZE(other))
+ Py_RETURN_FALSE;
+
+ while (set_next(so, &pos, &entry)) {
+ int rv = set_contains_entry((PySetObject *)other, entry);
+ if (rv == -1)
+ return NULL;
+ if (!rv)
+ Py_RETURN_FALSE;
+ }
+ Py_RETURN_TRUE;
}
PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set.");
@@ -1763,17 +1763,17 @@ PyDoc_STRVAR(issubset_doc, "Report whether another set contains this set.");
static PyObject *
set_issuperset(PySetObject *so, PyObject *other)
{
- PyObject *tmp, *result;
+ PyObject *tmp, *result;
- if (!PyAnySet_Check(other)) {
- tmp = make_new_set(&PySet_Type, other);
- if (tmp == NULL)
- return NULL;
- result = set_issuperset(so, tmp);
- Py_DECREF(tmp);
- return result;
- }
- return set_issubset((PySetObject *)other, (PyObject *)so);
+ if (!PyAnySet_Check(other)) {
+ tmp = make_new_set(&PySet_Type, other);
+ if (tmp == NULL)
+ return NULL;
+ result = set_issuperset(so, tmp);
+ Py_DECREF(tmp);
+ return result;
+ }
+ return set_issubset((PySetObject *)other, (PyObject *)so);
}
PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set.");
@@ -1781,65 +1781,65 @@ PyDoc_STRVAR(issuperset_doc, "Report whether this set contains another set.");
static PyObject *
set_richcompare(PySetObject *v, PyObject *w, int op)
{
- PyObject *r1, *r2;
-
- if(!PyAnySet_Check(w)) {
- if (op == Py_EQ)
- Py_RETURN_FALSE;
- if (op == Py_NE)
- Py_RETURN_TRUE;
- PyErr_SetString(PyExc_TypeError, "can only compare to a set");
- return NULL;
- }
- switch (op) {
- case Py_EQ:
- if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
- Py_RETURN_FALSE;
- if (v->hash != -1 &&
- ((PySetObject *)w)->hash != -1 &&
- v->hash != ((PySetObject *)w)->hash)
- Py_RETURN_FALSE;
- return set_issubset(v, w);
- case Py_NE:
- r1 = set_richcompare(v, w, Py_EQ);
- if (r1 == NULL)
- return NULL;
- r2 = PyBool_FromLong(PyObject_Not(r1));
- Py_DECREF(r1);
- return r2;
- case Py_LE:
- return set_issubset(v, w);
- case Py_GE:
- return set_issuperset(v, w);
- case Py_LT:
- if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
- Py_RETURN_FALSE;
- return set_issubset(v, w);
- case Py_GT:
- if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
- Py_RETURN_FALSE;
- return set_issuperset(v, w);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ PyObject *r1, *r2;
+
+ if(!PyAnySet_Check(w)) {
+ if (op == Py_EQ)
+ Py_RETURN_FALSE;
+ if (op == Py_NE)
+ Py_RETURN_TRUE;
+ PyErr_SetString(PyExc_TypeError, "can only compare to a set");
+ return NULL;
+ }
+ switch (op) {
+ case Py_EQ:
+ if (PySet_GET_SIZE(v) != PySet_GET_SIZE(w))
+ Py_RETURN_FALSE;
+ if (v->hash != -1 &&
+ ((PySetObject *)w)->hash != -1 &&
+ v->hash != ((PySetObject *)w)->hash)
+ Py_RETURN_FALSE;
+ return set_issubset(v, w);
+ case Py_NE:
+ r1 = set_richcompare(v, w, Py_EQ);
+ if (r1 == NULL)
+ return NULL;
+ r2 = PyBool_FromLong(PyObject_Not(r1));
+ Py_DECREF(r1);
+ return r2;
+ case Py_LE:
+ return set_issubset(v, w);
+ case Py_GE:
+ return set_issuperset(v, w);
+ case Py_LT:
+ if (PySet_GET_SIZE(v) >= PySet_GET_SIZE(w))
+ Py_RETURN_FALSE;
+ return set_issubset(v, w);
+ case Py_GT:
+ if (PySet_GET_SIZE(v) <= PySet_GET_SIZE(w))
+ Py_RETURN_FALSE;
+ return set_issuperset(v, w);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static int
set_nocmp(PyObject *self, PyObject *other)
{
- PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "cannot compare sets using cmp()");
+ return -1;
}
static PyObject *
set_add(PySetObject *so, PyObject *key)
{
- if (set_add_key(so, key) == -1)
- return NULL;
- Py_RETURN_NONE;
+ if (set_add_key(so, key) == -1)
+ return NULL;
+ Py_RETURN_NONE;
}
-PyDoc_STRVAR(add_doc,
+PyDoc_STRVAR(add_doc,
"Add an element to a set.\n\
\n\
This has no effect if the element is already present.");
@@ -1847,34 +1847,34 @@ This has no effect if the element is already present.");
static int
set_contains(PySetObject *so, PyObject *key)
{
- PyObject *tmpkey;
- int rv;
-
- rv = set_contains_key(so, key);
- if (rv == -1) {
- if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
- return -1;
- PyErr_Clear();
- tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
- if (tmpkey == NULL)
- return -1;
- set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
- rv = set_contains(so, tmpkey);
- set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
- Py_DECREF(tmpkey);
- }
- return rv;
+ PyObject *tmpkey;
+ int rv;
+
+ rv = set_contains_key(so, key);
+ if (rv == -1) {
+ if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
+ return -1;
+ PyErr_Clear();
+ tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
+ if (tmpkey == NULL)
+ return -1;
+ set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
+ rv = set_contains(so, tmpkey);
+ set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
+ Py_DECREF(tmpkey);
+ }
+ return rv;
}
static PyObject *
set_direct_contains(PySetObject *so, PyObject *key)
{
- long result;
+ long result;
- result = set_contains(so, key);
- if (result == -1)
- return NULL;
- return PyBool_FromLong(result);
+ result = set_contains(so, key);
+ if (result == -1)
+ return NULL;
+ return PyBool_FromLong(result);
}
PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x.");
@@ -1882,30 +1882,30 @@ PyDoc_STRVAR(contains_doc, "x.__contains__(y) <==> y in x.");
static PyObject *
set_remove(PySetObject *so, PyObject *key)
{
- PyObject *tmpkey;
- int rv;
-
- rv = set_discard_key(so, key);
- if (rv == -1) {
- if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
- return NULL;
- PyErr_Clear();
- tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
- if (tmpkey == NULL)
- return NULL;
- set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
- rv = set_discard_key(so, tmpkey);
- set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
- Py_DECREF(tmpkey);
- if (rv == -1)
- return NULL;
- }
-
- if (rv == DISCARD_NOTFOUND) {
- set_key_error(key);
- return NULL;
- }
- Py_RETURN_NONE;
+ PyObject *tmpkey;
+ int rv;
+
+ rv = set_discard_key(so, key);
+ if (rv == -1) {
+ if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
+ return NULL;
+ PyErr_Clear();
+ tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
+ if (tmpkey == NULL)
+ return NULL;
+ set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
+ rv = set_discard_key(so, tmpkey);
+ set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
+ Py_DECREF(tmpkey);
+ if (rv == -1)
+ return NULL;
+ }
+
+ if (rv == DISCARD_NOTFOUND) {
+ set_key_error(key);
+ return NULL;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(remove_doc,
@@ -1916,54 +1916,54 @@ If the element is not a member, raise a KeyError.");
static PyObject *
set_discard(PySetObject *so, PyObject *key)
{
- PyObject *tmpkey, *result;
- int rv;
-
- rv = set_discard_key(so, key);
- if (rv == -1) {
- if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
- return NULL;
- PyErr_Clear();
- tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
- if (tmpkey == NULL)
- return NULL;
- set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
- result = set_discard(so, tmpkey);
- set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
- Py_DECREF(tmpkey);
- return result;
- }
- Py_RETURN_NONE;
+ PyObject *tmpkey, *result;
+ int rv;
+
+ rv = set_discard_key(so, key);
+ if (rv == -1) {
+ if (!PySet_Check(key) || !PyErr_ExceptionMatches(PyExc_TypeError))
+ return NULL;
+ PyErr_Clear();
+ tmpkey = make_new_set(&PyFrozenSet_Type, NULL);
+ if (tmpkey == NULL)
+ return NULL;
+ set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
+ result = set_discard(so, tmpkey);
+ set_swap_bodies((PySetObject *)tmpkey, (PySetObject *)key);
+ Py_DECREF(tmpkey);
+ return result;
+ }
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(discard_doc,
"Remove an element from a set if it is a member.\n\
\n\
-If the element is not a member, do nothing.");
+If the element is not a member, do nothing.");
static PyObject *
set_reduce(PySetObject *so)
{
- PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL;
-
- keys = PySequence_List((PyObject *)so);
- if (keys == NULL)
- goto done;
- args = PyTuple_Pack(1, keys);
- if (args == NULL)
- goto done;
- dict = PyObject_GetAttrString((PyObject *)so, "__dict__");
- if (dict == NULL) {
- PyErr_Clear();
- dict = Py_None;
- Py_INCREF(dict);
- }
- result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
+ PyObject *keys=NULL, *args=NULL, *result=NULL, *dict=NULL;
+
+ keys = PySequence_List((PyObject *)so);
+ if (keys == NULL)
+ goto done;
+ args = PyTuple_Pack(1, keys);
+ if (args == NULL)
+ goto done;
+ dict = PyObject_GetAttrString((PyObject *)so, "__dict__");
+ if (dict == NULL) {
+ PyErr_Clear();
+ dict = Py_None;
+ Py_INCREF(dict);
+ }
+ result = PyTuple_Pack(3, Py_TYPE(so), args, dict);
done:
- Py_XDECREF(args);
- Py_XDECREF(keys);
- Py_XDECREF(dict);
- return result;
+ Py_XDECREF(args);
+ Py_XDECREF(keys);
+ Py_XDECREF(dict);
+ return result;
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
@@ -1971,42 +1971,42 @@ PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyObject *
set_sizeof(PySetObject *so)
{
- Py_ssize_t res;
+ Py_ssize_t res;
- res = sizeof(PySetObject);
- if (so->table != so->smalltable)
- res = res + (so->mask + 1) * sizeof(setentry);
- return PyInt_FromSsize_t(res);
+ res = sizeof(PySetObject);
+ if (so->table != so->smalltable)
+ res = res + (so->mask + 1) * sizeof(setentry);
+ return PyInt_FromSsize_t(res);
}
PyDoc_STRVAR(sizeof_doc, "S.__sizeof__() -> size of S in memory, in bytes");
static int
set_init(PySetObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *iterable = NULL;
+ PyObject *iterable = NULL;
- if (!PyAnySet_Check(self))
- return -1;
- if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds))
- return -1;
- if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
- return -1;
- set_clear_internal(self);
- self->hash = -1;
- if (iterable == NULL)
- return 0;
- return set_update_internal(self, iterable);
+ if (!PyAnySet_Check(self))
+ return -1;
+ if (PySet_Check(self) && !_PyArg_NoKeywords("set()", kwds))
+ return -1;
+ if (!PyArg_UnpackTuple(args, Py_TYPE(self)->tp_name, 0, 1, &iterable))
+ return -1;
+ set_clear_internal(self);
+ self->hash = -1;
+ if (iterable == NULL)
+ return 0;
+ return set_update_internal(self, iterable);
}
static PySequenceMethods set_as_sequence = {
- set_len, /* sq_length */
- 0, /* sq_concat */
- 0, /* sq_repeat */
- 0, /* sq_item */
- 0, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)set_contains, /* sq_contains */
+ set_len, /* sq_length */
+ 0, /* sq_concat */
+ 0, /* sq_repeat */
+ 0, /* sq_item */
+ 0, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)set_contains, /* sq_contains */
};
/* set object ********************************************************/
@@ -2019,88 +2019,88 @@ All is well if assertions don't fail.");
#endif
static PyMethodDef set_methods[] = {
- {"add", (PyCFunction)set_add, METH_O,
- add_doc},
- {"clear", (PyCFunction)set_clear, METH_NOARGS,
- clear_doc},
- {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
- contains_doc},
- {"copy", (PyCFunction)set_copy, METH_NOARGS,
- copy_doc},
- {"discard", (PyCFunction)set_discard, METH_O,
- discard_doc},
- {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
- difference_doc},
- {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS,
- difference_update_doc},
- {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
- intersection_doc},
- {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS,
- intersection_update_doc},
- {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
- isdisjoint_doc},
- {"issubset", (PyCFunction)set_issubset, METH_O,
- issubset_doc},
- {"issuperset", (PyCFunction)set_issuperset, METH_O,
- issuperset_doc},
- {"pop", (PyCFunction)set_pop, METH_NOARGS,
- pop_doc},
- {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
- reduce_doc},
- {"remove", (PyCFunction)set_remove, METH_O,
- remove_doc},
- {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
- sizeof_doc},
- {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
- symmetric_difference_doc},
- {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O,
- symmetric_difference_update_doc},
+ {"add", (PyCFunction)set_add, METH_O,
+ add_doc},
+ {"clear", (PyCFunction)set_clear, METH_NOARGS,
+ clear_doc},
+ {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
+ contains_doc},
+ {"copy", (PyCFunction)set_copy, METH_NOARGS,
+ copy_doc},
+ {"discard", (PyCFunction)set_discard, METH_O,
+ discard_doc},
+ {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
+ difference_doc},
+ {"difference_update", (PyCFunction)set_difference_update, METH_VARARGS,
+ difference_update_doc},
+ {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
+ intersection_doc},
+ {"intersection_update",(PyCFunction)set_intersection_update_multi, METH_VARARGS,
+ intersection_update_doc},
+ {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
+ isdisjoint_doc},
+ {"issubset", (PyCFunction)set_issubset, METH_O,
+ issubset_doc},
+ {"issuperset", (PyCFunction)set_issuperset, METH_O,
+ issuperset_doc},
+ {"pop", (PyCFunction)set_pop, METH_NOARGS,
+ pop_doc},
+ {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
+ reduce_doc},
+ {"remove", (PyCFunction)set_remove, METH_O,
+ remove_doc},
+ {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
+ sizeof_doc},
+ {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
+ symmetric_difference_doc},
+ {"symmetric_difference_update",(PyCFunction)set_symmetric_difference_update, METH_O,
+ symmetric_difference_update_doc},
#ifdef Py_DEBUG
- {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS,
- test_c_api_doc},
+ {"test_c_api", (PyCFunction)test_c_api, METH_NOARGS,
+ test_c_api_doc},
#endif
- {"union", (PyCFunction)set_union, METH_VARARGS,
- union_doc},
- {"update", (PyCFunction)set_update, METH_VARARGS,
- update_doc},
- {NULL, NULL} /* sentinel */
+ {"union", (PyCFunction)set_union, METH_VARARGS,
+ union_doc},
+ {"update", (PyCFunction)set_update, METH_VARARGS,
+ update_doc},
+ {NULL, NULL} /* sentinel */
};
static PyNumberMethods set_as_number = {
- 0, /*nb_add*/
- (binaryfunc)set_sub, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- (binaryfunc)set_and, /*nb_and*/
- (binaryfunc)set_xor, /*nb_xor*/
- (binaryfunc)set_or, /*nb_or*/
- 0, /*nb_coerce*/
- 0, /*nb_int*/
- 0, /*nb_long*/
- 0, /*nb_float*/
- 0, /*nb_oct*/
- 0, /*nb_hex*/
- 0, /*nb_inplace_add*/
- (binaryfunc)set_isub, /*nb_inplace_subtract*/
- 0, /*nb_inplace_multiply*/
- 0, /*nb_inplace_divide*/
- 0, /*nb_inplace_remainder*/
- 0, /*nb_inplace_power*/
- 0, /*nb_inplace_lshift*/
- 0, /*nb_inplace_rshift*/
- (binaryfunc)set_iand, /*nb_inplace_and*/
- (binaryfunc)set_ixor, /*nb_inplace_xor*/
- (binaryfunc)set_ior, /*nb_inplace_or*/
+ 0, /*nb_add*/
+ (binaryfunc)set_sub, /*nb_subtract*/
+ 0, /*nb_multiply*/
+ 0, /*nb_divide*/
+ 0, /*nb_remainder*/
+ 0, /*nb_divmod*/
+ 0, /*nb_power*/
+ 0, /*nb_negative*/
+ 0, /*nb_positive*/
+ 0, /*nb_absolute*/
+ 0, /*nb_nonzero*/
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ (binaryfunc)set_and, /*nb_and*/
+ (binaryfunc)set_xor, /*nb_xor*/
+ (binaryfunc)set_or, /*nb_or*/
+ 0, /*nb_coerce*/
+ 0, /*nb_int*/
+ 0, /*nb_long*/
+ 0, /*nb_float*/
+ 0, /*nb_oct*/
+ 0, /*nb_hex*/
+ 0, /*nb_inplace_add*/
+ (binaryfunc)set_isub, /*nb_inplace_subtract*/
+ 0, /*nb_inplace_multiply*/
+ 0, /*nb_inplace_divide*/
+ 0, /*nb_inplace_remainder*/
+ 0, /*nb_inplace_power*/
+ 0, /*nb_inplace_lshift*/
+ 0, /*nb_inplace_rshift*/
+ (binaryfunc)set_iand, /*nb_inplace_and*/
+ (binaryfunc)set_ixor, /*nb_inplace_xor*/
+ (binaryfunc)set_ior, /*nb_inplace_or*/
};
PyDoc_STRVAR(set_doc,
@@ -2110,96 +2110,96 @@ set(iterable) -> new set object\n\
Build an unordered collection of unique elements.");
PyTypeObject PySet_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "set", /* tp_name */
- sizeof(PySetObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)set_dealloc, /* tp_dealloc */
- (printfunc)set_tp_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- set_nocmp, /* tp_compare */
- (reprfunc)set_repr, /* tp_repr */
- &set_as_number, /* tp_as_number */
- &set_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- set_doc, /* tp_doc */
- (traverseproc)set_traverse, /* tp_traverse */
- (inquiry)set_clear_internal, /* tp_clear */
- (richcmpfunc)set_richcompare, /* tp_richcompare */
- offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
- (getiterfunc)set_iter, /* tp_iter */
- 0, /* tp_iternext */
- set_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 */
- (initproc)set_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- set_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "set", /* tp_name */
+ sizeof(PySetObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)set_dealloc, /* tp_dealloc */
+ (printfunc)set_tp_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ set_nocmp, /* tp_compare */
+ (reprfunc)set_repr, /* tp_repr */
+ &set_as_number, /* tp_as_number */
+ &set_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)PyObject_HashNotImplemented, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ set_doc, /* tp_doc */
+ (traverseproc)set_traverse, /* tp_traverse */
+ (inquiry)set_clear_internal, /* tp_clear */
+ (richcmpfunc)set_richcompare, /* tp_richcompare */
+ offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
+ (getiterfunc)set_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ set_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 */
+ (initproc)set_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ set_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* frozenset object ********************************************************/
static PyMethodDef frozenset_methods[] = {
- {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
- contains_doc},
- {"copy", (PyCFunction)frozenset_copy, METH_NOARGS,
- copy_doc},
- {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
- difference_doc},
- {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
- intersection_doc},
- {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
- isdisjoint_doc},
- {"issubset", (PyCFunction)set_issubset, METH_O,
- issubset_doc},
- {"issuperset", (PyCFunction)set_issuperset, METH_O,
- issuperset_doc},
- {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
- reduce_doc},
- {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
- sizeof_doc},
- {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
- symmetric_difference_doc},
- {"union", (PyCFunction)set_union, METH_VARARGS,
- union_doc},
- {NULL, NULL} /* sentinel */
+ {"__contains__",(PyCFunction)set_direct_contains, METH_O | METH_COEXIST,
+ contains_doc},
+ {"copy", (PyCFunction)frozenset_copy, METH_NOARGS,
+ copy_doc},
+ {"difference", (PyCFunction)set_difference_multi, METH_VARARGS,
+ difference_doc},
+ {"intersection",(PyCFunction)set_intersection_multi, METH_VARARGS,
+ intersection_doc},
+ {"isdisjoint", (PyCFunction)set_isdisjoint, METH_O,
+ isdisjoint_doc},
+ {"issubset", (PyCFunction)set_issubset, METH_O,
+ issubset_doc},
+ {"issuperset", (PyCFunction)set_issuperset, METH_O,
+ issuperset_doc},
+ {"__reduce__", (PyCFunction)set_reduce, METH_NOARGS,
+ reduce_doc},
+ {"__sizeof__", (PyCFunction)set_sizeof, METH_NOARGS,
+ sizeof_doc},
+ {"symmetric_difference",(PyCFunction)set_symmetric_difference, METH_O,
+ symmetric_difference_doc},
+ {"union", (PyCFunction)set_union, METH_VARARGS,
+ union_doc},
+ {NULL, NULL} /* sentinel */
};
static PyNumberMethods frozenset_as_number = {
- 0, /*nb_add*/
- (binaryfunc)set_sub, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- 0, /*nb_remainder*/
- 0, /*nb_divmod*/
- 0, /*nb_power*/
- 0, /*nb_negative*/
- 0, /*nb_positive*/
- 0, /*nb_absolute*/
- 0, /*nb_nonzero*/
- 0, /*nb_invert*/
- 0, /*nb_lshift*/
- 0, /*nb_rshift*/
- (binaryfunc)set_and, /*nb_and*/
- (binaryfunc)set_xor, /*nb_xor*/
- (binaryfunc)set_or, /*nb_or*/
+ 0, /*nb_add*/
+ (binaryfunc)set_sub, /*nb_subtract*/
+ 0, /*nb_multiply*/
+ 0, /*nb_divide*/
+ 0, /*nb_remainder*/
+ 0, /*nb_divmod*/
+ 0, /*nb_power*/
+ 0, /*nb_negative*/
+ 0, /*nb_positive*/
+ 0, /*nb_absolute*/
+ 0, /*nb_nonzero*/
+ 0, /*nb_invert*/
+ 0, /*nb_lshift*/
+ 0, /*nb_rshift*/
+ (binaryfunc)set_and, /*nb_and*/
+ (binaryfunc)set_xor, /*nb_xor*/
+ (binaryfunc)set_or, /*nb_or*/
};
PyDoc_STRVAR(frozenset_doc,
@@ -2209,47 +2209,47 @@ frozenset(iterable) -> frozenset object\n\
Build an immutable unordered collection of unique elements.");
PyTypeObject PyFrozenSet_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "frozenset", /* tp_name */
- sizeof(PySetObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)set_dealloc, /* tp_dealloc */
- (printfunc)set_tp_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- set_nocmp, /* tp_compare */
- (reprfunc)set_repr, /* tp_repr */
- &frozenset_as_number, /* tp_as_number */
- &set_as_sequence, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- frozenset_hash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- frozenset_doc, /* tp_doc */
- (traverseproc)set_traverse, /* tp_traverse */
- (inquiry)set_clear_internal, /* tp_clear */
- (richcmpfunc)set_richcompare, /* tp_richcompare */
- offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
- (getiterfunc)set_iter, /* tp_iter */
- 0, /* tp_iternext */
- frozenset_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 */
- PyType_GenericAlloc, /* tp_alloc */
- frozenset_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "frozenset", /* tp_name */
+ sizeof(PySetObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)set_dealloc, /* tp_dealloc */
+ (printfunc)set_tp_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ set_nocmp, /* tp_compare */
+ (reprfunc)set_repr, /* tp_repr */
+ &frozenset_as_number, /* tp_as_number */
+ &set_as_sequence, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ frozenset_hash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ frozenset_doc, /* tp_doc */
+ (traverseproc)set_traverse, /* tp_traverse */
+ (inquiry)set_clear_internal, /* tp_clear */
+ (richcmpfunc)set_richcompare, /* tp_richcompare */
+ offsetof(PySetObject, weakreflist), /* tp_weaklistoffset */
+ (getiterfunc)set_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ frozenset_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 */
+ PyType_GenericAlloc, /* tp_alloc */
+ frozenset_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
@@ -2258,252 +2258,252 @@ PyTypeObject PyFrozenSet_Type = {
PyObject *
PySet_New(PyObject *iterable)
{
- return make_new_set(&PySet_Type, iterable);
+ return make_new_set(&PySet_Type, iterable);
}
PyObject *
PyFrozenSet_New(PyObject *iterable)
{
- return make_new_set(&PyFrozenSet_Type, iterable);
+ return make_new_set(&PyFrozenSet_Type, iterable);
}
Py_ssize_t
PySet_Size(PyObject *anyset)
{
- if (!PyAnySet_Check(anyset)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return PySet_GET_SIZE(anyset);
+ if (!PyAnySet_Check(anyset)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return PySet_GET_SIZE(anyset);
}
int
PySet_Clear(PyObject *set)
{
- if (!PySet_Check(set)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return set_clear_internal((PySetObject *)set);
+ if (!PySet_Check(set)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return set_clear_internal((PySetObject *)set);
}
int
PySet_Contains(PyObject *anyset, PyObject *key)
{
- if (!PyAnySet_Check(anyset)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return set_contains_key((PySetObject *)anyset, key);
+ if (!PyAnySet_Check(anyset)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return set_contains_key((PySetObject *)anyset, key);
}
int
PySet_Discard(PyObject *set, PyObject *key)
{
- if (!PySet_Check(set)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return set_discard_key((PySetObject *)set, key);
+ if (!PySet_Check(set)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return set_discard_key((PySetObject *)set, key);
}
int
PySet_Add(PyObject *anyset, PyObject *key)
{
- if (!PySet_Check(anyset) &&
- (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return set_add_key((PySetObject *)anyset, key);
+ if (!PySet_Check(anyset) &&
+ (!PyFrozenSet_Check(anyset) || Py_REFCNT(anyset) != 1)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return set_add_key((PySetObject *)anyset, key);
}
int
_PySet_Next(PyObject *set, Py_ssize_t *pos, PyObject **key)
{
- setentry *entry_ptr;
+ setentry *entry_ptr;
- if (!PyAnySet_Check(set)) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
- return 0;
- *key = entry_ptr->key;
- return 1;
+ if (!PyAnySet_Check(set)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (set_next((PySetObject *)set, pos, &entry_ptr) == 0)
+ return 0;
+ *key = entry_ptr->key;
+ return 1;
}
int
_PySet_NextEntry(PyObject *set, Py_ssize_t *pos, PyObject **key, long *hash)
{
- setentry *entry;
+ setentry *entry;
- if (!PyAnySet_Check(set)) {
- PyErr_BadInternalCall();
- return -1;
- }
- if (set_next((PySetObject *)set, pos, &entry) == 0)
- return 0;
- *key = entry->key;
- *hash = entry->hash;
- return 1;
+ if (!PyAnySet_Check(set)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (set_next((PySetObject *)set, pos, &entry) == 0)
+ return 0;
+ *key = entry->key;
+ *hash = entry->hash;
+ return 1;
}
PyObject *
PySet_Pop(PyObject *set)
{
- if (!PySet_Check(set)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return set_pop((PySetObject *)set);
+ if (!PySet_Check(set)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return set_pop((PySetObject *)set);
}
int
_PySet_Update(PyObject *set, PyObject *iterable)
{
- if (!PySet_Check(set)) {
- PyErr_BadInternalCall();
- return -1;
- }
- return set_update_internal((PySetObject *)set, iterable);
+ if (!PySet_Check(set)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ return set_update_internal((PySetObject *)set, iterable);
}
#ifdef Py_DEBUG
-/* Test code to be called with any three element set.
+/* Test code to be called with any three element set.
Returns True and original set is restored. */
-#define assertRaises(call_return_value, exception) \
- do { \
- assert(call_return_value); \
- assert(PyErr_ExceptionMatches(exception)); \
- PyErr_Clear(); \
- } while(0)
+#define assertRaises(call_return_value, exception) \
+ do { \
+ assert(call_return_value); \
+ assert(PyErr_ExceptionMatches(exception)); \
+ PyErr_Clear(); \
+ } while(0)
static PyObject *
test_c_api(PySetObject *so)
{
- Py_ssize_t count;
- char *s;
- Py_ssize_t i;
- PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
- PyObject *ob = (PyObject *)so;
- PyObject *str;
-
- /* Verify preconditions */
- assert(PyAnySet_Check(ob));
- assert(PyAnySet_CheckExact(ob));
- assert(!PyFrozenSet_CheckExact(ob));
-
- /* so.clear(); so |= set("abc"); */
- str = PyString_FromString("abc");
- if (str == NULL)
- return NULL;
- set_clear_internal(so);
- if (set_update_internal(so, str) == -1) {
- Py_DECREF(str);
- return NULL;
- }
- Py_DECREF(str);
-
- /* Exercise type/size checks */
- assert(PySet_Size(ob) == 3);
- assert(PySet_GET_SIZE(ob) == 3);
-
- /* Raise TypeError for non-iterable constructor arguments */
- assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError);
- assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError);
-
- /* Raise TypeError for unhashable key */
- dup = PySet_New(ob);
- assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError);
- assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError);
- assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError);
-
- /* Exercise successful pop, contains, add, and discard */
- elem = PySet_Pop(ob);
- assert(PySet_Contains(ob, elem) == 0);
- assert(PySet_GET_SIZE(ob) == 2);
- assert(PySet_Add(ob, elem) == 0);
- assert(PySet_Contains(ob, elem) == 1);
- assert(PySet_GET_SIZE(ob) == 3);
- assert(PySet_Discard(ob, elem) == 1);
- assert(PySet_GET_SIZE(ob) == 2);
- assert(PySet_Discard(ob, elem) == 0);
- assert(PySet_GET_SIZE(ob) == 2);
-
- /* Exercise clear */
- dup2 = PySet_New(dup);
- assert(PySet_Clear(dup2) == 0);
- assert(PySet_Size(dup2) == 0);
- Py_DECREF(dup2);
-
- /* Raise SystemError on clear or update of frozen set */
- f = PyFrozenSet_New(dup);
- assertRaises(PySet_Clear(f) == -1, PyExc_SystemError);
- assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError);
- assert(PySet_Add(f, elem) == 0);
- Py_INCREF(f);
- assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError);
- Py_DECREF(f);
- Py_DECREF(f);
-
- /* Exercise direct iteration */
- i = 0, count = 0;
- while (_PySet_Next((PyObject *)dup, &i, &x)) {
- s = PyString_AsString(x);
- assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
- count++;
- }
- assert(count == 3);
-
- /* Exercise updates */
- dup2 = PySet_New(NULL);
- assert(_PySet_Update(dup2, dup) == 0);
- assert(PySet_Size(dup2) == 3);
- assert(_PySet_Update(dup2, dup) == 0);
- assert(PySet_Size(dup2) == 3);
- Py_DECREF(dup2);
-
- /* Raise SystemError when self argument is not a set or frozenset. */
- t = PyTuple_New(0);
- assertRaises(PySet_Size(t) == -1, PyExc_SystemError);
- assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError);
- Py_DECREF(t);
-
- /* Raise SystemError when self argument is not a set. */
- f = PyFrozenSet_New(dup);
- assert(PySet_Size(f) == 3);
- assert(PyFrozenSet_CheckExact(f));
- assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError);
- assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError);
- Py_DECREF(f);
-
- /* Raise KeyError when popping from an empty set */
- assert(PyNumber_InPlaceSubtract(ob, ob) == ob);
- Py_DECREF(ob);
- assert(PySet_GET_SIZE(ob) == 0);
- assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError);
-
- /* Restore the set from the copy using the PyNumber API */
- assert(PyNumber_InPlaceOr(ob, dup) == ob);
- Py_DECREF(ob);
-
- /* Verify constructors accept NULL arguments */
- f = PySet_New(NULL);
- assert(f != NULL);
- assert(PySet_GET_SIZE(f) == 0);
- Py_DECREF(f);
- f = PyFrozenSet_New(NULL);
- assert(f != NULL);
- assert(PyFrozenSet_CheckExact(f));
- assert(PySet_GET_SIZE(f) == 0);
- Py_DECREF(f);
-
- Py_DECREF(elem);
- Py_DECREF(dup);
- Py_RETURN_TRUE;
+ Py_ssize_t count;
+ char *s;
+ Py_ssize_t i;
+ PyObject *elem=NULL, *dup=NULL, *t, *f, *dup2, *x;
+ PyObject *ob = (PyObject *)so;
+ PyObject *str;
+
+ /* Verify preconditions */
+ assert(PyAnySet_Check(ob));
+ assert(PyAnySet_CheckExact(ob));
+ assert(!PyFrozenSet_CheckExact(ob));
+
+ /* so.clear(); so |= set("abc"); */
+ str = PyString_FromString("abc");
+ if (str == NULL)
+ return NULL;
+ set_clear_internal(so);
+ if (set_update_internal(so, str) == -1) {
+ Py_DECREF(str);
+ return NULL;
+ }
+ Py_DECREF(str);
+
+ /* Exercise type/size checks */
+ assert(PySet_Size(ob) == 3);
+ assert(PySet_GET_SIZE(ob) == 3);
+
+ /* Raise TypeError for non-iterable constructor arguments */
+ assertRaises(PySet_New(Py_None) == NULL, PyExc_TypeError);
+ assertRaises(PyFrozenSet_New(Py_None) == NULL, PyExc_TypeError);
+
+ /* Raise TypeError for unhashable key */
+ dup = PySet_New(ob);
+ assertRaises(PySet_Discard(ob, dup) == -1, PyExc_TypeError);
+ assertRaises(PySet_Contains(ob, dup) == -1, PyExc_TypeError);
+ assertRaises(PySet_Add(ob, dup) == -1, PyExc_TypeError);
+
+ /* Exercise successful pop, contains, add, and discard */
+ elem = PySet_Pop(ob);
+ assert(PySet_Contains(ob, elem) == 0);
+ assert(PySet_GET_SIZE(ob) == 2);
+ assert(PySet_Add(ob, elem) == 0);
+ assert(PySet_Contains(ob, elem) == 1);
+ assert(PySet_GET_SIZE(ob) == 3);
+ assert(PySet_Discard(ob, elem) == 1);
+ assert(PySet_GET_SIZE(ob) == 2);
+ assert(PySet_Discard(ob, elem) == 0);
+ assert(PySet_GET_SIZE(ob) == 2);
+
+ /* Exercise clear */
+ dup2 = PySet_New(dup);
+ assert(PySet_Clear(dup2) == 0);
+ assert(PySet_Size(dup2) == 0);
+ Py_DECREF(dup2);
+
+ /* Raise SystemError on clear or update of frozen set */
+ f = PyFrozenSet_New(dup);
+ assertRaises(PySet_Clear(f) == -1, PyExc_SystemError);
+ assertRaises(_PySet_Update(f, dup) == -1, PyExc_SystemError);
+ assert(PySet_Add(f, elem) == 0);
+ Py_INCREF(f);
+ assertRaises(PySet_Add(f, elem) == -1, PyExc_SystemError);
+ Py_DECREF(f);
+ Py_DECREF(f);
+
+ /* Exercise direct iteration */
+ i = 0, count = 0;
+ while (_PySet_Next((PyObject *)dup, &i, &x)) {
+ s = PyString_AsString(x);
+ assert(s && (s[0] == 'a' || s[0] == 'b' || s[0] == 'c'));
+ count++;
+ }
+ assert(count == 3);
+
+ /* Exercise updates */
+ dup2 = PySet_New(NULL);
+ assert(_PySet_Update(dup2, dup) == 0);
+ assert(PySet_Size(dup2) == 3);
+ assert(_PySet_Update(dup2, dup) == 0);
+ assert(PySet_Size(dup2) == 3);
+ Py_DECREF(dup2);
+
+ /* Raise SystemError when self argument is not a set or frozenset. */
+ t = PyTuple_New(0);
+ assertRaises(PySet_Size(t) == -1, PyExc_SystemError);
+ assertRaises(PySet_Contains(t, elem) == -1, PyExc_SystemError);
+ Py_DECREF(t);
+
+ /* Raise SystemError when self argument is not a set. */
+ f = PyFrozenSet_New(dup);
+ assert(PySet_Size(f) == 3);
+ assert(PyFrozenSet_CheckExact(f));
+ assertRaises(PySet_Discard(f, elem) == -1, PyExc_SystemError);
+ assertRaises(PySet_Pop(f) == NULL, PyExc_SystemError);
+ Py_DECREF(f);
+
+ /* Raise KeyError when popping from an empty set */
+ assert(PyNumber_InPlaceSubtract(ob, ob) == ob);
+ Py_DECREF(ob);
+ assert(PySet_GET_SIZE(ob) == 0);
+ assertRaises(PySet_Pop(ob) == NULL, PyExc_KeyError);
+
+ /* Restore the set from the copy using the PyNumber API */
+ assert(PyNumber_InPlaceOr(ob, dup) == ob);
+ Py_DECREF(ob);
+
+ /* Verify constructors accept NULL arguments */
+ f = PySet_New(NULL);
+ assert(f != NULL);
+ assert(PySet_GET_SIZE(f) == 0);
+ Py_DECREF(f);
+ f = PyFrozenSet_New(NULL);
+ assert(f != NULL);
+ assert(PyFrozenSet_CheckExact(f));
+ assert(PySet_GET_SIZE(f) == 0);
+ Py_DECREF(f);
+
+ Py_DECREF(elem);
+ Py_DECREF(dup);
+ Py_RETURN_TRUE;
}
#undef assertRaises
diff --git a/Objects/sliceobject.c b/Objects/sliceobject.c
index 2eb3941..d1fe052 100644
--- a/Objects/sliceobject.c
+++ b/Objects/sliceobject.c
@@ -7,7 +7,7 @@ Guido, feel free to do whatever you want in the way of copyrights
for this file.
*/
-/*
+/*
Py_Ellipsis encodes the '...' rubber index token. It is similar to
the Py_NoneStruct in that there is no way to create other objects of
this type and there is exactly one in existence.
@@ -19,35 +19,35 @@ this type and there is exactly one in existence.
static PyObject *
ellipsis_repr(PyObject *op)
{
- return PyString_FromString("Ellipsis");
+ return PyString_FromString("Ellipsis");
}
PyTypeObject PyEllipsis_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "ellipsis", /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- 0, /*never called*/ /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- ellipsis_repr, /* 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 */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "ellipsis", /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ 0, /*never called*/ /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ ellipsis_repr, /* 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 */
};
PyObject _Py_EllipsisObject = {
- _PyObject_EXTRA_INIT
- 1, &PyEllipsis_Type
+ _PyObject_EXTRA_INIT
+ 1, &PyEllipsis_Type
};
@@ -60,154 +60,154 @@ PyObject _Py_EllipsisObject = {
PyObject *
PySlice_New(PyObject *start, PyObject *stop, PyObject *step)
{
- PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type);
+ PySliceObject *obj = PyObject_New(PySliceObject, &PySlice_Type);
- if (obj == NULL)
- return NULL;
+ if (obj == NULL)
+ return NULL;
- if (step == NULL) step = Py_None;
- Py_INCREF(step);
- if (start == NULL) start = Py_None;
- Py_INCREF(start);
- if (stop == NULL) stop = Py_None;
- Py_INCREF(stop);
+ if (step == NULL) step = Py_None;
+ Py_INCREF(step);
+ if (start == NULL) start = Py_None;
+ Py_INCREF(start);
+ if (stop == NULL) stop = Py_None;
+ Py_INCREF(stop);
- obj->step = step;
- obj->start = start;
- obj->stop = stop;
+ obj->step = step;
+ obj->start = start;
+ obj->stop = stop;
- return (PyObject *) obj;
+ return (PyObject *) obj;
}
PyObject *
_PySlice_FromIndices(Py_ssize_t istart, Py_ssize_t istop)
{
- PyObject *start, *end, *slice;
- start = PyInt_FromSsize_t(istart);
- if (!start)
- return NULL;
- end = PyInt_FromSsize_t(istop);
- if (!end) {
- Py_DECREF(start);
- return NULL;
- }
-
- slice = PySlice_New(start, end, NULL);
- Py_DECREF(start);
- Py_DECREF(end);
- return slice;
+ PyObject *start, *end, *slice;
+ start = PyInt_FromSsize_t(istart);
+ if (!start)
+ return NULL;
+ end = PyInt_FromSsize_t(istop);
+ if (!end) {
+ Py_DECREF(start);
+ return NULL;
+ }
+
+ slice = PySlice_New(start, end, NULL);
+ Py_DECREF(start);
+ Py_DECREF(end);
+ return slice;
}
int
PySlice_GetIndices(PySliceObject *r, Py_ssize_t length,
Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step)
{
- /* XXX support long ints */
- if (r->step == Py_None) {
- *step = 1;
- } else {
- if (!PyInt_Check(r->step) && !PyLong_Check(r->step)) return -1;
- *step = PyInt_AsSsize_t(r->step);
- }
- if (r->start == Py_None) {
- *start = *step < 0 ? length-1 : 0;
- } else {
- if (!PyInt_Check(r->start) && !PyLong_Check(r->step)) return -1;
- *start = PyInt_AsSsize_t(r->start);
- if (*start < 0) *start += length;
- }
- if (r->stop == Py_None) {
- *stop = *step < 0 ? -1 : length;
- } else {
- if (!PyInt_Check(r->stop) && !PyLong_Check(r->step)) return -1;
- *stop = PyInt_AsSsize_t(r->stop);
- if (*stop < 0) *stop += length;
- }
- if (*stop > length) return -1;
- if (*start >= length) return -1;
- if (*step == 0) return -1;
- return 0;
+ /* XXX support long ints */
+ if (r->step == Py_None) {
+ *step = 1;
+ } else {
+ if (!PyInt_Check(r->step) && !PyLong_Check(r->step)) return -1;
+ *step = PyInt_AsSsize_t(r->step);
+ }
+ if (r->start == Py_None) {
+ *start = *step < 0 ? length-1 : 0;
+ } else {
+ if (!PyInt_Check(r->start) && !PyLong_Check(r->step)) return -1;
+ *start = PyInt_AsSsize_t(r->start);
+ if (*start < 0) *start += length;
+ }
+ if (r->stop == Py_None) {
+ *stop = *step < 0 ? -1 : length;
+ } else {
+ if (!PyInt_Check(r->stop) && !PyLong_Check(r->step)) return -1;
+ *stop = PyInt_AsSsize_t(r->stop);
+ if (*stop < 0) *stop += length;
+ }
+ if (*stop > length) return -1;
+ if (*start >= length) return -1;
+ if (*step == 0) return -1;
+ return 0;
}
int
PySlice_GetIndicesEx(PySliceObject *r, Py_ssize_t length,
- Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)
+ Py_ssize_t *start, Py_ssize_t *stop, Py_ssize_t *step, Py_ssize_t *slicelength)
{
- /* this is harder to get right than you might think */
-
- Py_ssize_t defstart, defstop;
-
- if (r->step == Py_None) {
- *step = 1;
- }
- else {
- if (!_PyEval_SliceIndex(r->step, step)) return -1;
- if (*step == 0) {
- PyErr_SetString(PyExc_ValueError,
- "slice step cannot be zero");
- return -1;
- }
- }
-
- defstart = *step < 0 ? length-1 : 0;
- defstop = *step < 0 ? -1 : length;
-
- if (r->start == Py_None) {
- *start = defstart;
- }
- else {
- if (!_PyEval_SliceIndex(r->start, start)) return -1;
- if (*start < 0) *start += length;
- if (*start < 0) *start = (*step < 0) ? -1 : 0;
- if (*start >= length)
- *start = (*step < 0) ? length - 1 : length;
- }
-
- if (r->stop == Py_None) {
- *stop = defstop;
- }
- else {
- if (!_PyEval_SliceIndex(r->stop, stop)) return -1;
- if (*stop < 0) *stop += length;
- if (*stop < 0) *stop = (*step < 0) ? -1 : 0;
- if (*stop >= length)
- *stop = (*step < 0) ? length - 1 : length;
- }
-
- if ((*step < 0 && *stop >= *start)
- || (*step > 0 && *start >= *stop)) {
- *slicelength = 0;
- }
- else if (*step < 0) {
- *slicelength = (*stop-*start+1)/(*step)+1;
- }
- else {
- *slicelength = (*stop-*start-1)/(*step)+1;
- }
-
- return 0;
+ /* this is harder to get right than you might think */
+
+ Py_ssize_t defstart, defstop;
+
+ if (r->step == Py_None) {
+ *step = 1;
+ }
+ else {
+ if (!_PyEval_SliceIndex(r->step, step)) return -1;
+ if (*step == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "slice step cannot be zero");
+ return -1;
+ }
+ }
+
+ defstart = *step < 0 ? length-1 : 0;
+ defstop = *step < 0 ? -1 : length;
+
+ if (r->start == Py_None) {
+ *start = defstart;
+ }
+ else {
+ if (!_PyEval_SliceIndex(r->start, start)) return -1;
+ if (*start < 0) *start += length;
+ if (*start < 0) *start = (*step < 0) ? -1 : 0;
+ if (*start >= length)
+ *start = (*step < 0) ? length - 1 : length;
+ }
+
+ if (r->stop == Py_None) {
+ *stop = defstop;
+ }
+ else {
+ if (!_PyEval_SliceIndex(r->stop, stop)) return -1;
+ if (*stop < 0) *stop += length;
+ if (*stop < 0) *stop = (*step < 0) ? -1 : 0;
+ if (*stop >= length)
+ *stop = (*step < 0) ? length - 1 : length;
+ }
+
+ if ((*step < 0 && *stop >= *start)
+ || (*step > 0 && *start >= *stop)) {
+ *slicelength = 0;
+ }
+ else if (*step < 0) {
+ *slicelength = (*stop-*start+1)/(*step)+1;
+ }
+ else {
+ *slicelength = (*stop-*start-1)/(*step)+1;
+ }
+
+ return 0;
}
static PyObject *
slice_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
- PyObject *start, *stop, *step;
+ PyObject *start, *stop, *step;
- start = stop = step = NULL;
+ start = stop = step = NULL;
- if (!_PyArg_NoKeywords("slice()", kw))
- return NULL;
+ if (!_PyArg_NoKeywords("slice()", kw))
+ return NULL;
- if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "slice", 1, 3, &start, &stop, &step))
+ return NULL;
- /* This swapping of stop and start is to maintain similarity with
- range(). */
- if (stop == NULL) {
- stop = start;
- start = NULL;
- }
- return PySlice_New(start, stop, step);
+ /* This swapping of stop and start is to maintain similarity with
+ range(). */
+ if (stop == NULL) {
+ stop = start;
+ start = NULL;
+ }
+ return PySlice_New(start, stop, step);
}
PyDoc_STRVAR(slice_doc,
@@ -218,53 +218,53 @@ Create a slice object. This is used for extended slicing (e.g. a[0:10:2]).");
static void
slice_dealloc(PySliceObject *r)
{
- Py_DECREF(r->step);
- Py_DECREF(r->start);
- Py_DECREF(r->stop);
- PyObject_Del(r);
+ Py_DECREF(r->step);
+ Py_DECREF(r->start);
+ Py_DECREF(r->stop);
+ PyObject_Del(r);
}
static PyObject *
slice_repr(PySliceObject *r)
{
- PyObject *s, *comma;
-
- s = PyString_FromString("slice(");
- comma = PyString_FromString(", ");
- PyString_ConcatAndDel(&s, PyObject_Repr(r->start));
- PyString_Concat(&s, comma);
- PyString_ConcatAndDel(&s, PyObject_Repr(r->stop));
- PyString_Concat(&s, comma);
- PyString_ConcatAndDel(&s, PyObject_Repr(r->step));
- PyString_ConcatAndDel(&s, PyString_FromString(")"));
- Py_DECREF(comma);
- return s;
+ PyObject *s, *comma;
+
+ s = PyString_FromString("slice(");
+ comma = PyString_FromString(", ");
+ PyString_ConcatAndDel(&s, PyObject_Repr(r->start));
+ PyString_Concat(&s, comma);
+ PyString_ConcatAndDel(&s, PyObject_Repr(r->stop));
+ PyString_Concat(&s, comma);
+ PyString_ConcatAndDel(&s, PyObject_Repr(r->step));
+ PyString_ConcatAndDel(&s, PyString_FromString(")"));
+ Py_DECREF(comma);
+ return s;
}
static PyMemberDef slice_members[] = {
- {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY},
- {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY},
- {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY},
- {0}
+ {"start", T_OBJECT, offsetof(PySliceObject, start), READONLY},
+ {"stop", T_OBJECT, offsetof(PySliceObject, stop), READONLY},
+ {"step", T_OBJECT, offsetof(PySliceObject, step), READONLY},
+ {0}
};
static PyObject*
slice_indices(PySliceObject* self, PyObject* len)
{
- Py_ssize_t ilen, start, stop, step, slicelength;
+ Py_ssize_t ilen, start, stop, step, slicelength;
- ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError);
+ ilen = PyNumber_AsSsize_t(len, PyExc_OverflowError);
- if (ilen == -1 && PyErr_Occurred()) {
- return NULL;
- }
+ if (ilen == -1 && PyErr_Occurred()) {
+ return NULL;
+ }
- if (PySlice_GetIndicesEx(self, ilen, &start, &stop,
- &step, &slicelength) < 0) {
- return NULL;
- }
+ if (PySlice_GetIndicesEx(self, ilen, &start, &stop,
+ &step, &slicelength) < 0) {
+ return NULL;
+ }
- return Py_BuildValue("(nnn)", start, stop, step);
+ return Py_BuildValue("(nnn)", start, stop, step);
}
PyDoc_STRVAR(slice_indices_doc,
@@ -278,84 +278,84 @@ handling of normal slices.");
static PyObject *
slice_reduce(PySliceObject* self)
{
- return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step);
+ return Py_BuildValue("O(OOO)", Py_TYPE(self), self->start, self->stop, self->step);
}
PyDoc_STRVAR(reduce_doc, "Return state information for pickling.");
static PyMethodDef slice_methods[] = {
- {"indices", (PyCFunction)slice_indices,
- METH_O, slice_indices_doc},
- {"__reduce__", (PyCFunction)slice_reduce,
- METH_NOARGS, reduce_doc},
- {NULL, NULL}
+ {"indices", (PyCFunction)slice_indices,
+ METH_O, slice_indices_doc},
+ {"__reduce__", (PyCFunction)slice_reduce,
+ METH_NOARGS, reduce_doc},
+ {NULL, NULL}
};
static int
slice_compare(PySliceObject *v, PySliceObject *w)
{
- int result = 0;
-
- if (v == w)
- return 0;
-
- if (PyObject_Cmp(v->start, w->start, &result) < 0)
- return -2;
- if (result != 0)
- return result;
- if (PyObject_Cmp(v->stop, w->stop, &result) < 0)
- return -2;
- if (result != 0)
- return result;
- if (PyObject_Cmp(v->step, w->step, &result) < 0)
- return -2;
- return result;
+ int result = 0;
+
+ if (v == w)
+ return 0;
+
+ if (PyObject_Cmp(v->start, w->start, &result) < 0)
+ return -2;
+ if (result != 0)
+ return result;
+ if (PyObject_Cmp(v->stop, w->stop, &result) < 0)
+ return -2;
+ if (result != 0)
+ return result;
+ if (PyObject_Cmp(v->step, w->step, &result) < 0)
+ return -2;
+ return result;
}
static long
slice_hash(PySliceObject *v)
{
- PyErr_SetString(PyExc_TypeError, "unhashable type");
- return -1L;
+ PyErr_SetString(PyExc_TypeError, "unhashable type");
+ return -1L;
}
PyTypeObject PySlice_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "slice", /* Name of this type */
- sizeof(PySliceObject), /* Basic object size */
- 0, /* Item size for varobject */
- (destructor)slice_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- (cmpfunc)slice_compare, /* tp_compare */
- (reprfunc)slice_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)slice_hash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- slice_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- slice_methods, /* tp_methods */
- slice_members, /* 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 */
- slice_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "slice", /* Name of this type */
+ sizeof(PySliceObject), /* Basic object size */
+ 0, /* Item size for varobject */
+ (destructor)slice_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ (cmpfunc)slice_compare, /* tp_compare */
+ (reprfunc)slice_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)slice_hash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ slice_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ slice_methods, /* tp_methods */
+ slice_members, /* 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 */
+ slice_new, /* tp_new */
};
diff --git a/Objects/stringlib/string_format.h b/Objects/stringlib/string_format.h
index ee6533e..0aafb14 100644
--- a/Objects/stringlib/string_format.h
+++ b/Objects/stringlib/string_format.h
@@ -563,15 +563,15 @@ render_field(PyObject *fieldobj, SubString *format_spec, OutputString *output)
PyObject *format_spec_object = NULL;
PyObject *(*formatter)(PyObject *, STRINGLIB_CHAR *, Py_ssize_t) = NULL;
STRINGLIB_CHAR* format_spec_start = format_spec->ptr ?
- format_spec->ptr : NULL;
+ format_spec->ptr : NULL;
Py_ssize_t format_spec_len = format_spec->ptr ?
- format_spec->end - format_spec->ptr : 0;
+ format_spec->end - format_spec->ptr : 0;
/* If we know the type exactly, skip the lookup of __format__ and just
call the formatter directly. */
#if STRINGLIB_IS_UNICODE
if (PyUnicode_CheckExact(fieldobj))
- formatter = _PyUnicode_FormatAdvanced;
+ formatter = _PyUnicode_FormatAdvanced;
/* Unfortunately, there's a problem with checking for int, long,
and float here. If we're being included as unicode, their
formatters expect string format_spec args. For now, just skip
@@ -579,29 +579,29 @@ render_field(PyObject *fieldobj, SubString *format_spec, OutputString *output)
hassle. */
#else
if (PyString_CheckExact(fieldobj))
- formatter = _PyBytes_FormatAdvanced;
+ formatter = _PyBytes_FormatAdvanced;
else if (PyInt_CheckExact(fieldobj))
- formatter =_PyInt_FormatAdvanced;
+ formatter =_PyInt_FormatAdvanced;
else if (PyLong_CheckExact(fieldobj))
- formatter =_PyLong_FormatAdvanced;
+ formatter =_PyLong_FormatAdvanced;
else if (PyFloat_CheckExact(fieldobj))
- formatter = _PyFloat_FormatAdvanced;
+ formatter = _PyFloat_FormatAdvanced;
#endif
if (formatter) {
- /* we know exactly which formatter will be called when __format__ is
- looked up, so call it directly, instead. */
- result = formatter(fieldobj, format_spec_start, format_spec_len);
+ /* we know exactly which formatter will be called when __format__ is
+ looked up, so call it directly, instead. */
+ result = formatter(fieldobj, format_spec_start, format_spec_len);
}
else {
- /* We need to create an object out of the pointers we have, because
- __format__ takes a string/unicode object for format_spec. */
- format_spec_object = STRINGLIB_NEW(format_spec_start,
- format_spec_len);
- if (format_spec_object == NULL)
- goto done;
-
- result = PyObject_Format(fieldobj, format_spec_object);
+ /* We need to create an object out of the pointers we have, because
+ __format__ takes a string/unicode object for format_spec. */
+ format_spec_object = STRINGLIB_NEW(format_spec_start,
+ format_spec_len);
+ if (format_spec_object == NULL)
+ goto done;
+
+ result = PyObject_Format(fieldobj, format_spec_object);
}
if (result == NULL)
goto done;
@@ -614,11 +614,11 @@ render_field(PyObject *fieldobj, SubString *format_spec, OutputString *output)
/* Convert result to our type. We could be str, and result could
be unicode */
{
- PyObject *tmp = STRINGLIB_TOSTR(result);
- if (tmp == NULL)
- goto done;
- Py_DECREF(result);
- result = tmp;
+ PyObject *tmp = STRINGLIB_TOSTR(result);
+ if (tmp == NULL)
+ goto done;
+ Py_DECREF(result);
+ result = tmp;
}
#endif
@@ -849,17 +849,17 @@ do_conversion(PyObject *obj, STRINGLIB_CHAR conversion)
case 's':
return STRINGLIB_TOSTR(obj);
default:
- if (conversion > 32 && conversion < 127) {
- /* It's the ASCII subrange; casting to char is safe
- (assuming the execution character set is an ASCII
- superset). */
- PyErr_Format(PyExc_ValueError,
+ if (conversion > 32 && conversion < 127) {
+ /* It's the ASCII subrange; casting to char is safe
+ (assuming the execution character set is an ASCII
+ superset). */
+ PyErr_Format(PyExc_ValueError,
"Unknown conversion specifier %c",
(char)conversion);
- } else
- PyErr_Format(PyExc_ValueError,
- "Unknown conversion specifier \\x%x",
- (unsigned int)conversion);
+ } else
+ PyErr_Format(PyExc_ValueError,
+ "Unknown conversion specifier \\x%x",
+ (unsigned int)conversion);
return NULL;
}
}
@@ -1124,7 +1124,7 @@ formatteriter_next(formatteriterobject *it)
Py_INCREF(conversion_str);
}
else
- conversion_str = STRINGLIB_NEW(&conversion, 1);
+ conversion_str = STRINGLIB_NEW(&conversion, 1);
if (conversion_str == NULL)
goto done;
@@ -1140,39 +1140,39 @@ formatteriter_next(formatteriterobject *it)
}
static PyMethodDef formatteriter_methods[] = {
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject PyFormatterIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "formatteriterator", /* tp_name */
- sizeof(formatteriterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
+ "formatteriterator", /* tp_name */
+ sizeof(formatteriterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
/* methods */
- (destructor)formatteriter_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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)formatteriter_next, /* tp_iternext */
- formatteriter_methods, /* tp_methods */
+ (destructor)formatteriter_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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)formatteriter_next, /* tp_iternext */
+ formatteriter_methods, /* tp_methods */
0,
};
@@ -1273,39 +1273,39 @@ fieldnameiter_next(fieldnameiterobject *it)
}
static PyMethodDef fieldnameiter_methods[] = {
- {NULL, NULL} /* sentinel */
+ {NULL, NULL} /* sentinel */
};
static PyTypeObject PyFieldNameIter_Type = {
PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "fieldnameiterator", /* tp_name */
- sizeof(fieldnameiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
+ "fieldnameiterator", /* tp_name */
+ sizeof(fieldnameiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
/* methods */
- (destructor)fieldnameiter_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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)fieldnameiter_next, /* tp_iternext */
- fieldnameiter_methods, /* tp_methods */
+ (destructor)fieldnameiter_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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)fieldnameiter_next, /* tp_iternext */
+ fieldnameiter_methods, /* tp_methods */
0};
/* unicode_formatter_field_name_split is used to implement
diff --git a/Objects/stringobject.c b/Objects/stringobject.c
index abb1d3a..0fbc01c 100644
--- a/Objects/stringobject.c
+++ b/Objects/stringobject.c
@@ -60,402 +60,402 @@ static PyObject *interned;
PyObject *
PyString_FromStringAndSize(const char *str, Py_ssize_t size)
{
- register PyStringObject *op;
- if (size < 0) {
- PyErr_SetString(PyExc_SystemError,
- "Negative size passed to PyString_FromStringAndSize");
- return NULL;
- }
- if (size == 0 && (op = nullstring) != NULL) {
+ register PyStringObject *op;
+ if (size < 0) {
+ PyErr_SetString(PyExc_SystemError,
+ "Negative size passed to PyString_FromStringAndSize");
+ return NULL;
+ }
+ if (size == 0 && (op = nullstring) != NULL) {
#ifdef COUNT_ALLOCS
- null_strings++;
+ null_strings++;
#endif
- Py_INCREF(op);
- return (PyObject *)op;
- }
- if (size == 1 && str != NULL &&
- (op = characters[*str & UCHAR_MAX]) != NULL)
- {
+ Py_INCREF(op);
+ return (PyObject *)op;
+ }
+ if (size == 1 && str != NULL &&
+ (op = characters[*str & UCHAR_MAX]) != NULL)
+ {
#ifdef COUNT_ALLOCS
- one_strings++;
+ one_strings++;
#endif
- Py_INCREF(op);
- return (PyObject *)op;
- }
-
- if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
- PyErr_SetString(PyExc_OverflowError, "string is too large");
- return NULL;
- }
-
- /* Inline PyObject_NewVar */
- op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
- if (op == NULL)
- return PyErr_NoMemory();
- PyObject_INIT_VAR(op, &PyString_Type, size);
- op->ob_shash = -1;
- op->ob_sstate = SSTATE_NOT_INTERNED;
- if (str != NULL)
- Py_MEMCPY(op->ob_sval, str, size);
- op->ob_sval[size] = '\0';
- /* share short strings */
- if (size == 0) {
- PyObject *t = (PyObject *)op;
- PyString_InternInPlace(&t);
- op = (PyStringObject *)t;
- nullstring = op;
- Py_INCREF(op);
- } else if (size == 1 && str != NULL) {
- PyObject *t = (PyObject *)op;
- PyString_InternInPlace(&t);
- op = (PyStringObject *)t;
- characters[*str & UCHAR_MAX] = op;
- Py_INCREF(op);
- }
- return (PyObject *) op;
+ Py_INCREF(op);
+ return (PyObject *)op;
+ }
+
+ if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
+ PyErr_SetString(PyExc_OverflowError, "string is too large");
+ return NULL;
+ }
+
+ /* Inline PyObject_NewVar */
+ op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
+ if (op == NULL)
+ return PyErr_NoMemory();
+ PyObject_INIT_VAR(op, &PyString_Type, size);
+ op->ob_shash = -1;
+ op->ob_sstate = SSTATE_NOT_INTERNED;
+ if (str != NULL)
+ Py_MEMCPY(op->ob_sval, str, size);
+ op->ob_sval[size] = '\0';
+ /* share short strings */
+ if (size == 0) {
+ PyObject *t = (PyObject *)op;
+ PyString_InternInPlace(&t);
+ op = (PyStringObject *)t;
+ nullstring = op;
+ Py_INCREF(op);
+ } else if (size == 1 && str != NULL) {
+ PyObject *t = (PyObject *)op;
+ PyString_InternInPlace(&t);
+ op = (PyStringObject *)t;
+ characters[*str & UCHAR_MAX] = op;
+ Py_INCREF(op);
+ }
+ return (PyObject *) op;
}
PyObject *
PyString_FromString(const char *str)
{
- register size_t size;
- register PyStringObject *op;
-
- assert(str != NULL);
- size = strlen(str);
- if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
- PyErr_SetString(PyExc_OverflowError,
- "string is too long for a Python string");
- return NULL;
- }
- if (size == 0 && (op = nullstring) != NULL) {
+ register size_t size;
+ register PyStringObject *op;
+
+ assert(str != NULL);
+ size = strlen(str);
+ if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
+ PyErr_SetString(PyExc_OverflowError,
+ "string is too long for a Python string");
+ return NULL;
+ }
+ if (size == 0 && (op = nullstring) != NULL) {
#ifdef COUNT_ALLOCS
- null_strings++;
+ null_strings++;
#endif
- Py_INCREF(op);
- return (PyObject *)op;
- }
- if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
+ Py_INCREF(op);
+ return (PyObject *)op;
+ }
+ if (size == 1 && (op = characters[*str & UCHAR_MAX]) != NULL) {
#ifdef COUNT_ALLOCS
- one_strings++;
+ one_strings++;
#endif
- Py_INCREF(op);
- return (PyObject *)op;
- }
-
- /* Inline PyObject_NewVar */
- op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
- if (op == NULL)
- return PyErr_NoMemory();
- PyObject_INIT_VAR(op, &PyString_Type, size);
- op->ob_shash = -1;
- op->ob_sstate = SSTATE_NOT_INTERNED;
- Py_MEMCPY(op->ob_sval, str, size+1);
- /* share short strings */
- if (size == 0) {
- PyObject *t = (PyObject *)op;
- PyString_InternInPlace(&t);
- op = (PyStringObject *)t;
- nullstring = op;
- Py_INCREF(op);
- } else if (size == 1) {
- PyObject *t = (PyObject *)op;
- PyString_InternInPlace(&t);
- op = (PyStringObject *)t;
- characters[*str & UCHAR_MAX] = op;
- Py_INCREF(op);
- }
- return (PyObject *) op;
+ Py_INCREF(op);
+ return (PyObject *)op;
+ }
+
+ /* Inline PyObject_NewVar */
+ op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
+ if (op == NULL)
+ return PyErr_NoMemory();
+ PyObject_INIT_VAR(op, &PyString_Type, size);
+ op->ob_shash = -1;
+ op->ob_sstate = SSTATE_NOT_INTERNED;
+ Py_MEMCPY(op->ob_sval, str, size+1);
+ /* share short strings */
+ if (size == 0) {
+ PyObject *t = (PyObject *)op;
+ PyString_InternInPlace(&t);
+ op = (PyStringObject *)t;
+ nullstring = op;
+ Py_INCREF(op);
+ } else if (size == 1) {
+ PyObject *t = (PyObject *)op;
+ PyString_InternInPlace(&t);
+ op = (PyStringObject *)t;
+ characters[*str & UCHAR_MAX] = op;
+ Py_INCREF(op);
+ }
+ return (PyObject *) op;
}
PyObject *
PyString_FromFormatV(const char *format, va_list vargs)
{
- va_list count;
- Py_ssize_t n = 0;
- const char* f;
- char *s;
- PyObject* string;
+ va_list count;
+ Py_ssize_t n = 0;
+ const char* f;
+ char *s;
+ PyObject* string;
#ifdef VA_LIST_IS_ARRAY
- Py_MEMCPY(count, vargs, sizeof(va_list));
+ Py_MEMCPY(count, vargs, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(count, vargs);
+ __va_copy(count, vargs);
#else
- count = vargs;
+ count = vargs;
#endif
#endif
- /* step 1: figure out how large a buffer we need */
- for (f = format; *f; f++) {
- if (*f == '%') {
+ /* step 1: figure out how large a buffer we need */
+ for (f = format; *f; f++) {
+ if (*f == '%') {
#ifdef HAVE_LONG_LONG
- int longlongflag = 0;
+ int longlongflag = 0;
#endif
- const char* p = f;
- while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
- ;
-
- /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
- * they don't affect the amount of space we reserve.
- */
- if (*f == 'l') {
- if (f[1] == 'd' || f[1] == 'u') {
- ++f;
- }
+ const char* p = f;
+ while (*++f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
+ ;
+
+ /* skip the 'l' or 'z' in {%ld, %zd, %lu, %zu} since
+ * they don't affect the amount of space we reserve.
+ */
+ if (*f == 'l') {
+ if (f[1] == 'd' || f[1] == 'u') {
+ ++f;
+ }
#ifdef HAVE_LONG_LONG
- else if (f[1] == 'l' &&
- (f[2] == 'd' || f[2] == 'u')) {
- longlongflag = 1;
- f += 2;
- }
+ else if (f[1] == 'l' &&
+ (f[2] == 'd' || f[2] == 'u')) {
+ longlongflag = 1;
+ f += 2;
+ }
#endif
- }
- else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
- ++f;
- }
-
- switch (*f) {
- case 'c':
- (void)va_arg(count, int);
- /* fall through... */
- case '%':
- n++;
- break;
- case 'd': case 'u': case 'i': case 'x':
- (void) va_arg(count, int);
+ }
+ else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
+ ++f;
+ }
+
+ switch (*f) {
+ case 'c':
+ (void)va_arg(count, int);
+ /* fall through... */
+ case '%':
+ n++;
+ break;
+ case 'd': case 'u': case 'i': case 'x':
+ (void) va_arg(count, int);
#ifdef HAVE_LONG_LONG
- /* Need at most
- ceil(log10(256)*SIZEOF_LONG_LONG) digits,
- plus 1 for the sign. 53/22 is an upper
- bound for log10(256). */
- if (longlongflag)
- n += 2 + (SIZEOF_LONG_LONG*53-1) / 22;
- else
+ /* Need at most
+ ceil(log10(256)*SIZEOF_LONG_LONG) digits,
+ plus 1 for the sign. 53/22 is an upper
+ bound for log10(256). */
+ if (longlongflag)
+ n += 2 + (SIZEOF_LONG_LONG*53-1) / 22;
+ else
#endif
- /* 20 bytes is enough to hold a 64-bit
- integer. Decimal takes the most
- space. This isn't enough for
- octal. */
- n += 20;
-
- break;
- case 's':
- s = va_arg(count, char*);
- n += strlen(s);
- break;
- case 'p':
- (void) va_arg(count, int);
- /* maximum 64-bit pointer representation:
- * 0xffffffffffffffff
- * so 19 characters is enough.
- * XXX I count 18 -- what's the extra for?
- */
- n += 19;
- break;
- default:
- /* if we stumble upon an unknown
- formatting code, copy the rest of
- the format string to the output
- string. (we cannot just skip the
- code, since there's no way to know
- what's in the argument list) */
- n += strlen(p);
- goto expand;
- }
- } else
- n++;
- }
+ /* 20 bytes is enough to hold a 64-bit
+ integer. Decimal takes the most
+ space. This isn't enough for
+ octal. */
+ n += 20;
+
+ break;
+ case 's':
+ s = va_arg(count, char*);
+ n += strlen(s);
+ break;
+ case 'p':
+ (void) va_arg(count, int);
+ /* maximum 64-bit pointer representation:
+ * 0xffffffffffffffff
+ * so 19 characters is enough.
+ * XXX I count 18 -- what's the extra for?
+ */
+ n += 19;
+ break;
+ default:
+ /* if we stumble upon an unknown
+ formatting code, copy the rest of
+ the format string to the output
+ string. (we cannot just skip the
+ code, since there's no way to know
+ what's in the argument list) */
+ n += strlen(p);
+ goto expand;
+ }
+ } else
+ n++;
+ }
expand:
- /* step 2: fill the buffer */
- /* Since we've analyzed how much space we need for the worst case,
- use sprintf directly instead of the slower PyOS_snprintf. */
- string = PyString_FromStringAndSize(NULL, n);
- if (!string)
- return NULL;
-
- s = PyString_AsString(string);
-
- for (f = format; *f; f++) {
- if (*f == '%') {
- const char* p = f++;
- Py_ssize_t i;
- int longflag = 0;
+ /* step 2: fill the buffer */
+ /* Since we've analyzed how much space we need for the worst case,
+ use sprintf directly instead of the slower PyOS_snprintf. */
+ string = PyString_FromStringAndSize(NULL, n);
+ if (!string)
+ return NULL;
+
+ s = PyString_AsString(string);
+
+ for (f = format; *f; f++) {
+ if (*f == '%') {
+ const char* p = f++;
+ Py_ssize_t i;
+ int longflag = 0;
#ifdef HAVE_LONG_LONG
- int longlongflag = 0;
+ int longlongflag = 0;
#endif
- int size_tflag = 0;
- /* parse the width.precision part (we're only
- interested in the precision value, if any) */
- n = 0;
- while (isdigit(Py_CHARMASK(*f)))
- n = (n*10) + *f++ - '0';
- if (*f == '.') {
- f++;
- n = 0;
- while (isdigit(Py_CHARMASK(*f)))
- n = (n*10) + *f++ - '0';
- }
- while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
- f++;
- /* Handle %ld, %lu, %lld and %llu. */
- if (*f == 'l') {
- if (f[1] == 'd' || f[1] == 'u') {
- longflag = 1;
- ++f;
- }
+ int size_tflag = 0;
+ /* parse the width.precision part (we're only
+ interested in the precision value, if any) */
+ n = 0;
+ while (isdigit(Py_CHARMASK(*f)))
+ n = (n*10) + *f++ - '0';
+ if (*f == '.') {
+ f++;
+ n = 0;
+ while (isdigit(Py_CHARMASK(*f)))
+ n = (n*10) + *f++ - '0';
+ }
+ while (*f && *f != '%' && !isalpha(Py_CHARMASK(*f)))
+ f++;
+ /* Handle %ld, %lu, %lld and %llu. */
+ if (*f == 'l') {
+ if (f[1] == 'd' || f[1] == 'u') {
+ longflag = 1;
+ ++f;
+ }
#ifdef HAVE_LONG_LONG
- else if (f[1] == 'l' &&
- (f[2] == 'd' || f[2] == 'u')) {
- longlongflag = 1;
- f += 2;
- }
+ else if (f[1] == 'l' &&
+ (f[2] == 'd' || f[2] == 'u')) {
+ longlongflag = 1;
+ f += 2;
+ }
#endif
- }
- /* handle the size_t flag. */
- else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
- size_tflag = 1;
- ++f;
- }
-
- switch (*f) {
- case 'c':
- *s++ = va_arg(vargs, int);
- break;
- case 'd':
- if (longflag)
- sprintf(s, "%ld", va_arg(vargs, long));
+ }
+ /* handle the size_t flag. */
+ else if (*f == 'z' && (f[1] == 'd' || f[1] == 'u')) {
+ size_tflag = 1;
+ ++f;
+ }
+
+ switch (*f) {
+ case 'c':
+ *s++ = va_arg(vargs, int);
+ break;
+ case 'd':
+ if (longflag)
+ sprintf(s, "%ld", va_arg(vargs, long));
#ifdef HAVE_LONG_LONG
- else if (longlongflag)
- sprintf(s, "%" PY_FORMAT_LONG_LONG "d",
- va_arg(vargs, PY_LONG_LONG));
+ else if (longlongflag)
+ sprintf(s, "%" PY_FORMAT_LONG_LONG "d",
+ va_arg(vargs, PY_LONG_LONG));
#endif
- else if (size_tflag)
- sprintf(s, "%" PY_FORMAT_SIZE_T "d",
- va_arg(vargs, Py_ssize_t));
- else
- sprintf(s, "%d", va_arg(vargs, int));
- s += strlen(s);
- break;
- case 'u':
- if (longflag)
- sprintf(s, "%lu",
- va_arg(vargs, unsigned long));
+ else if (size_tflag)
+ sprintf(s, "%" PY_FORMAT_SIZE_T "d",
+ va_arg(vargs, Py_ssize_t));
+ else
+ sprintf(s, "%d", va_arg(vargs, int));
+ s += strlen(s);
+ break;
+ case 'u':
+ if (longflag)
+ sprintf(s, "%lu",
+ va_arg(vargs, unsigned long));
#ifdef HAVE_LONG_LONG
- else if (longlongflag)
- sprintf(s, "%" PY_FORMAT_LONG_LONG "u",
- va_arg(vargs, PY_LONG_LONG));
+ else if (longlongflag)
+ sprintf(s, "%" PY_FORMAT_LONG_LONG "u",
+ va_arg(vargs, PY_LONG_LONG));
#endif
- else if (size_tflag)
- sprintf(s, "%" PY_FORMAT_SIZE_T "u",
- va_arg(vargs, size_t));
- else
- sprintf(s, "%u",
- va_arg(vargs, unsigned int));
- s += strlen(s);
- break;
- case 'i':
- sprintf(s, "%i", va_arg(vargs, int));
- s += strlen(s);
- break;
- case 'x':
- sprintf(s, "%x", va_arg(vargs, int));
- s += strlen(s);
- break;
- case 's':
- p = va_arg(vargs, char*);
- i = strlen(p);
- if (n > 0 && i > n)
- i = n;
- Py_MEMCPY(s, p, i);
- s += i;
- break;
- case 'p':
- sprintf(s, "%p", va_arg(vargs, void*));
- /* %p is ill-defined: ensure leading 0x. */
- if (s[1] == 'X')
- s[1] = 'x';
- else if (s[1] != 'x') {
- memmove(s+2, s, strlen(s)+1);
- s[0] = '0';
- s[1] = 'x';
- }
- s += strlen(s);
- break;
- case '%':
- *s++ = '%';
- break;
- default:
- strcpy(s, p);
- s += strlen(s);
- goto end;
- }
- } else
- *s++ = *f;
- }
+ else if (size_tflag)
+ sprintf(s, "%" PY_FORMAT_SIZE_T "u",
+ va_arg(vargs, size_t));
+ else
+ sprintf(s, "%u",
+ va_arg(vargs, unsigned int));
+ s += strlen(s);
+ break;
+ case 'i':
+ sprintf(s, "%i", va_arg(vargs, int));
+ s += strlen(s);
+ break;
+ case 'x':
+ sprintf(s, "%x", va_arg(vargs, int));
+ s += strlen(s);
+ break;
+ case 's':
+ p = va_arg(vargs, char*);
+ i = strlen(p);
+ if (n > 0 && i > n)
+ i = n;
+ Py_MEMCPY(s, p, i);
+ s += i;
+ break;
+ case 'p':
+ sprintf(s, "%p", va_arg(vargs, void*));
+ /* %p is ill-defined: ensure leading 0x. */
+ if (s[1] == 'X')
+ s[1] = 'x';
+ else if (s[1] != 'x') {
+ memmove(s+2, s, strlen(s)+1);
+ s[0] = '0';
+ s[1] = 'x';
+ }
+ s += strlen(s);
+ break;
+ case '%':
+ *s++ = '%';
+ break;
+ default:
+ strcpy(s, p);
+ s += strlen(s);
+ goto end;
+ }
+ } else
+ *s++ = *f;
+ }
end:
- if (_PyString_Resize(&string, s - PyString_AS_STRING(string)))
- return NULL;
- return string;
+ if (_PyString_Resize(&string, s - PyString_AS_STRING(string)))
+ return NULL;
+ return string;
}
PyObject *
PyString_FromFormat(const char *format, ...)
{
- PyObject* ret;
- va_list vargs;
+ PyObject* ret;
+ va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
- va_start(vargs, format);
+ va_start(vargs, format);
#else
- va_start(vargs);
+ va_start(vargs);
#endif
- ret = PyString_FromFormatV(format, vargs);
- va_end(vargs);
- return ret;
+ ret = PyString_FromFormatV(format, vargs);
+ va_end(vargs);
+ return ret;
}
PyObject *PyString_Decode(const char *s,
- Py_ssize_t size,
- const char *encoding,
- const char *errors)
+ Py_ssize_t size,
+ const char *encoding,
+ const char *errors)
{
PyObject *v, *str;
str = PyString_FromStringAndSize(s, size);
if (str == NULL)
- return NULL;
+ return NULL;
v = PyString_AsDecodedString(str, encoding, errors);
Py_DECREF(str);
return v;
}
PyObject *PyString_AsDecodedObject(PyObject *str,
- const char *encoding,
- const char *errors)
+ const char *encoding,
+ const char *errors)
{
PyObject *v;
if (!PyString_Check(str)) {
- PyErr_BadArgument();
- goto onError;
+ PyErr_BadArgument();
+ goto onError;
}
if (encoding == NULL) {
#ifdef Py_USING_UNICODE
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
#else
- PyErr_SetString(PyExc_ValueError, "no encoding specified");
- goto onError;
+ PyErr_SetString(PyExc_ValueError, "no encoding specified");
+ goto onError;
#endif
}
/* Decode via the codec registry */
v = PyCodec_Decode(str, encoding, errors);
if (v == NULL)
- goto onError;
+ goto onError;
return v;
@@ -464,31 +464,31 @@ PyObject *PyString_AsDecodedObject(PyObject *str,
}
PyObject *PyString_AsDecodedString(PyObject *str,
- const char *encoding,
- const char *errors)
+ const char *encoding,
+ const char *errors)
{
PyObject *v;
v = PyString_AsDecodedObject(str, encoding, errors);
if (v == NULL)
- goto onError;
+ goto onError;
#ifdef Py_USING_UNICODE
/* Convert Unicode to a string using the default encoding */
if (PyUnicode_Check(v)) {
- PyObject *temp = v;
- v = PyUnicode_AsEncodedString(v, NULL, NULL);
- Py_DECREF(temp);
- if (v == NULL)
- goto onError;
+ PyObject *temp = v;
+ v = PyUnicode_AsEncodedString(v, NULL, NULL);
+ Py_DECREF(temp);
+ if (v == NULL)
+ goto onError;
}
#endif
if (!PyString_Check(v)) {
- PyErr_Format(PyExc_TypeError,
- "decoder did not return a string object (type=%.400s)",
- Py_TYPE(v)->tp_name);
- Py_DECREF(v);
- goto onError;
+ PyErr_Format(PyExc_TypeError,
+ "decoder did not return a string object (type=%.400s)",
+ Py_TYPE(v)->tp_name);
+ Py_DECREF(v);
+ goto onError;
}
return v;
@@ -498,44 +498,44 @@ PyObject *PyString_AsDecodedString(PyObject *str,
}
PyObject *PyString_Encode(const char *s,
- Py_ssize_t size,
- const char *encoding,
- const char *errors)
+ Py_ssize_t size,
+ const char *encoding,
+ const char *errors)
{
PyObject *v, *str;
str = PyString_FromStringAndSize(s, size);
if (str == NULL)
- return NULL;
+ return NULL;
v = PyString_AsEncodedString(str, encoding, errors);
Py_DECREF(str);
return v;
}
PyObject *PyString_AsEncodedObject(PyObject *str,
- const char *encoding,
- const char *errors)
+ const char *encoding,
+ const char *errors)
{
PyObject *v;
if (!PyString_Check(str)) {
- PyErr_BadArgument();
- goto onError;
+ PyErr_BadArgument();
+ goto onError;
}
if (encoding == NULL) {
#ifdef Py_USING_UNICODE
- encoding = PyUnicode_GetDefaultEncoding();
+ encoding = PyUnicode_GetDefaultEncoding();
#else
- PyErr_SetString(PyExc_ValueError, "no encoding specified");
- goto onError;
+ PyErr_SetString(PyExc_ValueError, "no encoding specified");
+ goto onError;
#endif
}
/* Encode via the codec registry */
v = PyCodec_Encode(str, encoding, errors);
if (v == NULL)
- goto onError;
+ goto onError;
return v;
@@ -544,31 +544,31 @@ PyObject *PyString_AsEncodedObject(PyObject *str,
}
PyObject *PyString_AsEncodedString(PyObject *str,
- const char *encoding,
- const char *errors)
+ const char *encoding,
+ const char *errors)
{
PyObject *v;
v = PyString_AsEncodedObject(str, encoding, errors);
if (v == NULL)
- goto onError;
+ goto onError;
#ifdef Py_USING_UNICODE
/* Convert Unicode to a string using the default encoding */
if (PyUnicode_Check(v)) {
- PyObject *temp = v;
- v = PyUnicode_AsEncodedString(v, NULL, NULL);
- Py_DECREF(temp);
- if (v == NULL)
- goto onError;
+ PyObject *temp = v;
+ v = PyUnicode_AsEncodedString(v, NULL, NULL);
+ Py_DECREF(temp);
+ if (v == NULL)
+ goto onError;
}
#endif
if (!PyString_Check(v)) {
- PyErr_Format(PyExc_TypeError,
- "encoder did not return a string object (type=%.400s)",
- Py_TYPE(v)->tp_name);
- Py_DECREF(v);
- goto onError;
+ PyErr_Format(PyExc_TypeError,
+ "encoder did not return a string object (type=%.400s)",
+ Py_TYPE(v)->tp_name);
+ Py_DECREF(v);
+ goto onError;
}
return v;
@@ -580,25 +580,25 @@ PyObject *PyString_AsEncodedString(PyObject *str,
static void
string_dealloc(PyObject *op)
{
- switch (PyString_CHECK_INTERNED(op)) {
- case SSTATE_NOT_INTERNED:
- break;
-
- case SSTATE_INTERNED_MORTAL:
- /* revive dead object temporarily for DelItem */
- Py_REFCNT(op) = 3;
- if (PyDict_DelItem(interned, op) != 0)
- Py_FatalError(
- "deletion of interned string failed");
- break;
-
- case SSTATE_INTERNED_IMMORTAL:
- Py_FatalError("Immortal interned string died.");
-
- default:
- Py_FatalError("Inconsistent interned string state.");
- }
- Py_TYPE(op)->tp_free(op);
+ switch (PyString_CHECK_INTERNED(op)) {
+ case SSTATE_NOT_INTERNED:
+ break;
+
+ case SSTATE_INTERNED_MORTAL:
+ /* revive dead object temporarily for DelItem */
+ Py_REFCNT(op) = 3;
+ if (PyDict_DelItem(interned, op) != 0)
+ Py_FatalError(
+ "deletion of interned string failed");
+ break;
+
+ case SSTATE_INTERNED_IMMORTAL:
+ Py_FatalError("Immortal interned string died.");
+
+ default:
+ Py_FatalError("Inconsistent interned string state.");
+ }
+ Py_TYPE(op)->tp_free(op);
}
/* Unescape a backslash-escaped string. If unicode is non-zero,
@@ -607,153 +607,153 @@ string_dealloc(PyObject *op)
specified encoding. */
PyObject *PyString_DecodeEscape(const char *s,
- Py_ssize_t len,
- const char *errors,
- Py_ssize_t unicode,
- const char *recode_encoding)
+ Py_ssize_t len,
+ const char *errors,
+ Py_ssize_t unicode,
+ const char *recode_encoding)
{
- int c;
- char *p, *buf;
- const char *end;
- PyObject *v;
- Py_ssize_t newlen = recode_encoding ? 4*len:len;
- v = PyString_FromStringAndSize((char *)NULL, newlen);
- if (v == NULL)
- return NULL;
- p = buf = PyString_AsString(v);
- end = s + len;
- while (s < end) {
- if (*s != '\\') {
- non_esc:
+ int c;
+ char *p, *buf;
+ const char *end;
+ PyObject *v;
+ Py_ssize_t newlen = recode_encoding ? 4*len:len;
+ v = PyString_FromStringAndSize((char *)NULL, newlen);
+ if (v == NULL)
+ return NULL;
+ p = buf = PyString_AsString(v);
+ end = s + len;
+ while (s < end) {
+ if (*s != '\\') {
+ non_esc:
#ifdef Py_USING_UNICODE
- if (recode_encoding && (*s & 0x80)) {
- PyObject *u, *w;
- char *r;
- const char* t;
- Py_ssize_t rn;
- t = s;
- /* Decode non-ASCII bytes as UTF-8. */
- while (t < end && (*t & 0x80)) t++;
- u = PyUnicode_DecodeUTF8(s, t - s, errors);
- if(!u) goto failed;
-
- /* Recode them in target encoding. */
- w = PyUnicode_AsEncodedString(
- u, recode_encoding, errors);
- Py_DECREF(u);
- if (!w) goto failed;
-
- /* Append bytes to output buffer. */
- assert(PyString_Check(w));
- r = PyString_AS_STRING(w);
- rn = PyString_GET_SIZE(w);
- Py_MEMCPY(p, r, rn);
- p += rn;
- Py_DECREF(w);
- s = t;
- } else {
- *p++ = *s++;
- }
+ if (recode_encoding && (*s & 0x80)) {
+ PyObject *u, *w;
+ char *r;
+ const char* t;
+ Py_ssize_t rn;
+ t = s;
+ /* Decode non-ASCII bytes as UTF-8. */
+ while (t < end && (*t & 0x80)) t++;
+ u = PyUnicode_DecodeUTF8(s, t - s, errors);
+ if(!u) goto failed;
+
+ /* Recode them in target encoding. */
+ w = PyUnicode_AsEncodedString(
+ u, recode_encoding, errors);
+ Py_DECREF(u);
+ if (!w) goto failed;
+
+ /* Append bytes to output buffer. */
+ assert(PyString_Check(w));
+ r = PyString_AS_STRING(w);
+ rn = PyString_GET_SIZE(w);
+ Py_MEMCPY(p, r, rn);
+ p += rn;
+ Py_DECREF(w);
+ s = t;
+ } else {
+ *p++ = *s++;
+ }
#else
- *p++ = *s++;
+ *p++ = *s++;
#endif
- continue;
- }
- s++;
- if (s==end) {
- PyErr_SetString(PyExc_ValueError,
- "Trailing \\ in string");
- goto failed;
- }
- switch (*s++) {
- /* XXX This assumes ASCII! */
- case '\n': break;
- case '\\': *p++ = '\\'; break;
- case '\'': *p++ = '\''; break;
- case '\"': *p++ = '\"'; break;
- case 'b': *p++ = '\b'; break;
- case 'f': *p++ = '\014'; break; /* FF */
- case 't': *p++ = '\t'; break;
- case 'n': *p++ = '\n'; break;
- case 'r': *p++ = '\r'; break;
- case 'v': *p++ = '\013'; break; /* VT */
- case 'a': *p++ = '\007'; break; /* BEL, not classic C */
- case '0': case '1': case '2': case '3':
- case '4': case '5': case '6': case '7':
- c = s[-1] - '0';
- if (s < end && '0' <= *s && *s <= '7') {
- c = (c<<3) + *s++ - '0';
- if (s < end && '0' <= *s && *s <= '7')
- c = (c<<3) + *s++ - '0';
- }
- *p++ = c;
- break;
- case 'x':
- if (s+1 < end &&
- isxdigit(Py_CHARMASK(s[0])) &&
- isxdigit(Py_CHARMASK(s[1])))
- {
- unsigned int x = 0;
- c = Py_CHARMASK(*s);
- s++;
- if (isdigit(c))
- x = c - '0';
- else if (islower(c))
- x = 10 + c - 'a';
- else
- x = 10 + c - 'A';
- x = x << 4;
- c = Py_CHARMASK(*s);
- s++;
- if (isdigit(c))
- x += c - '0';
- else if (islower(c))
- x += 10 + c - 'a';
- else
- x += 10 + c - 'A';
- *p++ = x;
- break;
- }
- if (!errors || strcmp(errors, "strict") == 0) {
- PyErr_SetString(PyExc_ValueError,
- "invalid \\x escape");
- goto failed;
- }
- if (strcmp(errors, "replace") == 0) {
- *p++ = '?';
- } else if (strcmp(errors, "ignore") == 0)
- /* do nothing */;
- else {
- PyErr_Format(PyExc_ValueError,
- "decoding error; "
- "unknown error handling code: %.400s",
- errors);
- goto failed;
- }
+ continue;
+ }
+ s++;
+ if (s==end) {
+ PyErr_SetString(PyExc_ValueError,
+ "Trailing \\ in string");
+ goto failed;
+ }
+ switch (*s++) {
+ /* XXX This assumes ASCII! */
+ case '\n': break;
+ case '\\': *p++ = '\\'; break;
+ case '\'': *p++ = '\''; break;
+ case '\"': *p++ = '\"'; break;
+ case 'b': *p++ = '\b'; break;
+ case 'f': *p++ = '\014'; break; /* FF */
+ case 't': *p++ = '\t'; break;
+ case 'n': *p++ = '\n'; break;
+ case 'r': *p++ = '\r'; break;
+ case 'v': *p++ = '\013'; break; /* VT */
+ case 'a': *p++ = '\007'; break; /* BEL, not classic C */
+ case '0': case '1': case '2': case '3':
+ case '4': case '5': case '6': case '7':
+ c = s[-1] - '0';
+ if (s < end && '0' <= *s && *s <= '7') {
+ c = (c<<3) + *s++ - '0';
+ if (s < end && '0' <= *s && *s <= '7')
+ c = (c<<3) + *s++ - '0';
+ }
+ *p++ = c;
+ break;
+ case 'x':
+ if (s+1 < end &&
+ isxdigit(Py_CHARMASK(s[0])) &&
+ isxdigit(Py_CHARMASK(s[1])))
+ {
+ unsigned int x = 0;
+ c = Py_CHARMASK(*s);
+ s++;
+ if (isdigit(c))
+ x = c - '0';
+ else if (islower(c))
+ x = 10 + c - 'a';
+ else
+ x = 10 + c - 'A';
+ x = x << 4;
+ c = Py_CHARMASK(*s);
+ s++;
+ if (isdigit(c))
+ x += c - '0';
+ else if (islower(c))
+ x += 10 + c - 'a';
+ else
+ x += 10 + c - 'A';
+ *p++ = x;
+ break;
+ }
+ if (!errors || strcmp(errors, "strict") == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "invalid \\x escape");
+ goto failed;
+ }
+ if (strcmp(errors, "replace") == 0) {
+ *p++ = '?';
+ } else if (strcmp(errors, "ignore") == 0)
+ /* do nothing */;
+ else {
+ PyErr_Format(PyExc_ValueError,
+ "decoding error; "
+ "unknown error handling code: %.400s",
+ errors);
+ goto failed;
+ }
#ifndef Py_USING_UNICODE
- case 'u':
- case 'U':
- case 'N':
- if (unicode) {
- PyErr_SetString(PyExc_ValueError,
- "Unicode escapes not legal "
- "when Unicode disabled");
- goto failed;
- }
+ case 'u':
+ case 'U':
+ case 'N':
+ if (unicode) {
+ PyErr_SetString(PyExc_ValueError,
+ "Unicode escapes not legal "
+ "when Unicode disabled");
+ goto failed;
+ }
#endif
- default:
- *p++ = '\\';
- s--;
- goto non_esc; /* an arbitry number of unescaped
- UTF-8 bytes may follow. */
- }
- }
- if (p-buf < newlen && _PyString_Resize(&v, p - buf))
- goto failed;
- return v;
+ default:
+ *p++ = '\\';
+ s--;
+ goto non_esc; /* an arbitry number of unescaped
+ UTF-8 bytes may follow. */
+ }
+ }
+ if (p-buf < newlen && _PyString_Resize(&v, p - buf))
+ goto failed;
+ return v;
failed:
- Py_DECREF(v);
- return NULL;
+ Py_DECREF(v);
+ return NULL;
}
/* -------------------------------------------------------------------- */
@@ -762,75 +762,75 @@ PyObject *PyString_DecodeEscape(const char *s,
static Py_ssize_t
string_getsize(register PyObject *op)
{
- char *s;
- Py_ssize_t len;
- if (PyString_AsStringAndSize(op, &s, &len))
- return -1;
- return len;
+ char *s;
+ Py_ssize_t len;
+ if (PyString_AsStringAndSize(op, &s, &len))
+ return -1;
+ return len;
}
static /*const*/ char *
string_getbuffer(register PyObject *op)
{
- char *s;
- Py_ssize_t len;
- if (PyString_AsStringAndSize(op, &s, &len))
- return NULL;
- return s;
+ char *s;
+ Py_ssize_t len;
+ if (PyString_AsStringAndSize(op, &s, &len))
+ return NULL;
+ return s;
}
Py_ssize_t
PyString_Size(register PyObject *op)
{
- if (!PyString_Check(op))
- return string_getsize(op);
- return Py_SIZE(op);
+ if (!PyString_Check(op))
+ return string_getsize(op);
+ return Py_SIZE(op);
}
/*const*/ char *
PyString_AsString(register PyObject *op)
{
- if (!PyString_Check(op))
- return string_getbuffer(op);
- return ((PyStringObject *)op) -> ob_sval;
+ if (!PyString_Check(op))
+ return string_getbuffer(op);
+ return ((PyStringObject *)op) -> ob_sval;
}
int
PyString_AsStringAndSize(register PyObject *obj,
- register char **s,
- register Py_ssize_t *len)
+ register char **s,
+ register Py_ssize_t *len)
{
- if (s == NULL) {
- PyErr_BadInternalCall();
- return -1;
- }
+ if (s == NULL) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
- if (!PyString_Check(obj)) {
+ if (!PyString_Check(obj)) {
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(obj)) {
- obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
- if (obj == NULL)
- return -1;
- }
- else
+ if (PyUnicode_Check(obj)) {
+ obj = _PyUnicode_AsDefaultEncodedString(obj, NULL);
+ if (obj == NULL)
+ return -1;
+ }
+ else
#endif
- {
- PyErr_Format(PyExc_TypeError,
- "expected string or Unicode object, "
- "%.200s found", Py_TYPE(obj)->tp_name);
- return -1;
- }
- }
-
- *s = PyString_AS_STRING(obj);
- if (len != NULL)
- *len = PyString_GET_SIZE(obj);
- else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
- PyErr_SetString(PyExc_TypeError,
- "expected string without null bytes");
- return -1;
- }
- return 0;
+ {
+ PyErr_Format(PyExc_TypeError,
+ "expected string or Unicode object, "
+ "%.200s found", Py_TYPE(obj)->tp_name);
+ return -1;
+ }
+ }
+
+ *s = PyString_AS_STRING(obj);
+ if (len != NULL)
+ *len = PyString_GET_SIZE(obj);
+ else if (strlen(*s) != (size_t)PyString_GET_SIZE(obj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "expected string without null bytes");
+ return -1;
+ }
+ return 0;
}
/* -------------------------------------------------------------------- */
@@ -852,568 +852,568 @@ PyString_AsStringAndSize(register PyObject *obj,
static int
string_print(PyStringObject *op, FILE *fp, int flags)
{
- Py_ssize_t i, str_len;
- char c;
- int quote;
-
- /* XXX Ought to check for interrupts when writing long strings */
- if (! PyString_CheckExact(op)) {
- int ret;
- /* A str subclass may have its own __str__ method. */
- op = (PyStringObject *) PyObject_Str((PyObject *)op);
- if (op == NULL)
- return -1;
- ret = string_print(op, fp, flags);
- Py_DECREF(op);
- return ret;
- }
- if (flags & Py_PRINT_RAW) {
- char *data = op->ob_sval;
- Py_ssize_t size = Py_SIZE(op);
- Py_BEGIN_ALLOW_THREADS
- while (size > INT_MAX) {
- /* Very long strings cannot be written atomically.
- * But don't write exactly INT_MAX bytes at a time
- * to avoid memory aligment issues.
- */
- const int chunk_size = INT_MAX & ~0x3FFF;
- fwrite(data, 1, chunk_size, fp);
- data += chunk_size;
- size -= chunk_size;
- }
+ Py_ssize_t i, str_len;
+ char c;
+ int quote;
+
+ /* XXX Ought to check for interrupts when writing long strings */
+ if (! PyString_CheckExact(op)) {
+ int ret;
+ /* A str subclass may have its own __str__ method. */
+ op = (PyStringObject *) PyObject_Str((PyObject *)op);
+ if (op == NULL)
+ return -1;
+ ret = string_print(op, fp, flags);
+ Py_DECREF(op);
+ return ret;
+ }
+ if (flags & Py_PRINT_RAW) {
+ char *data = op->ob_sval;
+ Py_ssize_t size = Py_SIZE(op);
+ Py_BEGIN_ALLOW_THREADS
+ while (size > INT_MAX) {
+ /* Very long strings cannot be written atomically.
+ * But don't write exactly INT_MAX bytes at a time
+ * to avoid memory aligment issues.
+ */
+ const int chunk_size = INT_MAX & ~0x3FFF;
+ fwrite(data, 1, chunk_size, fp);
+ data += chunk_size;
+ size -= chunk_size;
+ }
#ifdef __VMS
- if (size) fwrite(data, (int)size, 1, fp);
+ if (size) fwrite(data, (int)size, 1, fp);
#else
- fwrite(data, 1, (int)size, fp);
+ fwrite(data, 1, (int)size, fp);
#endif
- Py_END_ALLOW_THREADS
- return 0;
- }
-
- /* figure out which quote to use; single is preferred */
- quote = '\'';
- if (memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
- !memchr(op->ob_sval, '"', Py_SIZE(op)))
- quote = '"';
-
- str_len = Py_SIZE(op);
- Py_BEGIN_ALLOW_THREADS
- fputc(quote, fp);
- for (i = 0; i < str_len; i++) {
- /* Since strings are immutable and the caller should have a
- reference, accessing the interal buffer should not be an issue
- with the GIL released. */
- c = op->ob_sval[i];
- if (c == quote || c == '\\')
- fprintf(fp, "\\%c", c);
- else if (c == '\t')
- fprintf(fp, "\\t");
- else if (c == '\n')
- fprintf(fp, "\\n");
- else if (c == '\r')
- fprintf(fp, "\\r");
- else if (c < ' ' || c >= 0x7f)
- fprintf(fp, "\\x%02x", c & 0xff);
- else
- fputc(c, fp);
- }
- fputc(quote, fp);
- Py_END_ALLOW_THREADS
- return 0;
+ Py_END_ALLOW_THREADS
+ return 0;
+ }
+
+ /* figure out which quote to use; single is preferred */
+ quote = '\'';
+ if (memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
+ !memchr(op->ob_sval, '"', Py_SIZE(op)))
+ quote = '"';
+
+ str_len = Py_SIZE(op);
+ Py_BEGIN_ALLOW_THREADS
+ fputc(quote, fp);
+ for (i = 0; i < str_len; i++) {
+ /* Since strings are immutable and the caller should have a
+ reference, accessing the interal buffer should not be an issue
+ with the GIL released. */
+ c = op->ob_sval[i];
+ if (c == quote || c == '\\')
+ fprintf(fp, "\\%c", c);
+ else if (c == '\t')
+ fprintf(fp, "\\t");
+ else if (c == '\n')
+ fprintf(fp, "\\n");
+ else if (c == '\r')
+ fprintf(fp, "\\r");
+ else if (c < ' ' || c >= 0x7f)
+ fprintf(fp, "\\x%02x", c & 0xff);
+ else
+ fputc(c, fp);
+ }
+ fputc(quote, fp);
+ Py_END_ALLOW_THREADS
+ return 0;
}
PyObject *
PyString_Repr(PyObject *obj, int smartquotes)
{
- register PyStringObject* op = (PyStringObject*) obj;
- size_t newsize = 2 + 4 * Py_SIZE(op);
- PyObject *v;
- if (newsize > PY_SSIZE_T_MAX || newsize / 4 != Py_SIZE(op)) {
- PyErr_SetString(PyExc_OverflowError,
- "string is too large to make repr");
- return NULL;
- }
- v = PyString_FromStringAndSize((char *)NULL, newsize);
- if (v == NULL) {
- return NULL;
- }
- else {
- register Py_ssize_t i;
- register char c;
- register char *p;
- int quote;
-
- /* figure out which quote to use; single is preferred */
- quote = '\'';
- if (smartquotes &&
- memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
- !memchr(op->ob_sval, '"', Py_SIZE(op)))
- quote = '"';
-
- p = PyString_AS_STRING(v);
- *p++ = quote;
- for (i = 0; i < Py_SIZE(op); i++) {
- /* There's at least enough room for a hex escape
- and a closing quote. */
- assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
- c = op->ob_sval[i];
- if (c == quote || c == '\\')
- *p++ = '\\', *p++ = c;
- else if (c == '\t')
- *p++ = '\\', *p++ = 't';
- else if (c == '\n')
- *p++ = '\\', *p++ = 'n';
- else if (c == '\r')
- *p++ = '\\', *p++ = 'r';
- else if (c < ' ' || c >= 0x7f) {
- /* For performance, we don't want to call
- PyOS_snprintf here (extra layers of
- function call). */
- sprintf(p, "\\x%02x", c & 0xff);
- p += 4;
- }
- else
- *p++ = c;
- }
- assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
- *p++ = quote;
- *p = '\0';
- if (_PyString_Resize(&v, (p - PyString_AS_STRING(v))))
- return NULL;
- return v;
- }
+ register PyStringObject* op = (PyStringObject*) obj;
+ size_t newsize = 2 + 4 * Py_SIZE(op);
+ PyObject *v;
+ if (newsize > PY_SSIZE_T_MAX || newsize / 4 != Py_SIZE(op)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "string is too large to make repr");
+ return NULL;
+ }
+ v = PyString_FromStringAndSize((char *)NULL, newsize);
+ if (v == NULL) {
+ return NULL;
+ }
+ else {
+ register Py_ssize_t i;
+ register char c;
+ register char *p;
+ int quote;
+
+ /* figure out which quote to use; single is preferred */
+ quote = '\'';
+ if (smartquotes &&
+ memchr(op->ob_sval, '\'', Py_SIZE(op)) &&
+ !memchr(op->ob_sval, '"', Py_SIZE(op)))
+ quote = '"';
+
+ p = PyString_AS_STRING(v);
+ *p++ = quote;
+ for (i = 0; i < Py_SIZE(op); i++) {
+ /* There's at least enough room for a hex escape
+ and a closing quote. */
+ assert(newsize - (p - PyString_AS_STRING(v)) >= 5);
+ c = op->ob_sval[i];
+ if (c == quote || c == '\\')
+ *p++ = '\\', *p++ = c;
+ else if (c == '\t')
+ *p++ = '\\', *p++ = 't';
+ else if (c == '\n')
+ *p++ = '\\', *p++ = 'n';
+ else if (c == '\r')
+ *p++ = '\\', *p++ = 'r';
+ else if (c < ' ' || c >= 0x7f) {
+ /* For performance, we don't want to call
+ PyOS_snprintf here (extra layers of
+ function call). */
+ sprintf(p, "\\x%02x", c & 0xff);
+ p += 4;
+ }
+ else
+ *p++ = c;
+ }
+ assert(newsize - (p - PyString_AS_STRING(v)) >= 1);
+ *p++ = quote;
+ *p = '\0';
+ if (_PyString_Resize(&v, (p - PyString_AS_STRING(v))))
+ return NULL;
+ return v;
+ }
}
static PyObject *
string_repr(PyObject *op)
{
- return PyString_Repr(op, 1);
+ return PyString_Repr(op, 1);
}
static PyObject *
string_str(PyObject *s)
{
- assert(PyString_Check(s));
- if (PyString_CheckExact(s)) {
- Py_INCREF(s);
- return s;
- }
- else {
- /* Subtype -- return genuine string with the same value. */
- PyStringObject *t = (PyStringObject *) s;
- return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
- }
+ assert(PyString_Check(s));
+ if (PyString_CheckExact(s)) {
+ Py_INCREF(s);
+ return s;
+ }
+ else {
+ /* Subtype -- return genuine string with the same value. */
+ PyStringObject *t = (PyStringObject *) s;
+ return PyString_FromStringAndSize(t->ob_sval, Py_SIZE(t));
+ }
}
static Py_ssize_t
string_length(PyStringObject *a)
{
- return Py_SIZE(a);
+ return Py_SIZE(a);
}
static PyObject *
string_concat(register PyStringObject *a, register PyObject *bb)
{
- register Py_ssize_t size;
- register PyStringObject *op;
- if (!PyString_Check(bb)) {
+ register Py_ssize_t size;
+ register PyStringObject *op;
+ if (!PyString_Check(bb)) {
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(bb))
- return PyUnicode_Concat((PyObject *)a, bb);
+ if (PyUnicode_Check(bb))
+ return PyUnicode_Concat((PyObject *)a, bb);
#endif
- if (PyByteArray_Check(bb))
- return PyByteArray_Concat((PyObject *)a, bb);
- PyErr_Format(PyExc_TypeError,
- "cannot concatenate 'str' and '%.200s' objects",
- Py_TYPE(bb)->tp_name);
- return NULL;
- }
+ if (PyByteArray_Check(bb))
+ return PyByteArray_Concat((PyObject *)a, bb);
+ PyErr_Format(PyExc_TypeError,
+ "cannot concatenate 'str' and '%.200s' objects",
+ Py_TYPE(bb)->tp_name);
+ return NULL;
+ }
#define b ((PyStringObject *)bb)
- /* Optimize cases with empty left or right operand */
- if ((Py_SIZE(a) == 0 || Py_SIZE(b) == 0) &&
- PyString_CheckExact(a) && PyString_CheckExact(b)) {
- if (Py_SIZE(a) == 0) {
- Py_INCREF(bb);
- return bb;
- }
- Py_INCREF(a);
- return (PyObject *)a;
- }
- size = Py_SIZE(a) + Py_SIZE(b);
- /* Check that string sizes are not negative, to prevent an
- overflow in cases where we are passed incorrectly-created
- strings with negative lengths (due to a bug in other code).
- */
- if (Py_SIZE(a) < 0 || Py_SIZE(b) < 0 ||
- Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
- PyErr_SetString(PyExc_OverflowError,
- "strings are too large to concat");
- return NULL;
- }
-
- /* Inline PyObject_NewVar */
- if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
- PyErr_SetString(PyExc_OverflowError,
- "strings are too large to concat");
- return NULL;
- }
- op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
- if (op == NULL)
- return PyErr_NoMemory();
- PyObject_INIT_VAR(op, &PyString_Type, size);
- op->ob_shash = -1;
- op->ob_sstate = SSTATE_NOT_INTERNED;
- Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
- Py_MEMCPY(op->ob_sval + Py_SIZE(a), b->ob_sval, Py_SIZE(b));
- op->ob_sval[size] = '\0';
- return (PyObject *) op;
+ /* Optimize cases with empty left or right operand */
+ if ((Py_SIZE(a) == 0 || Py_SIZE(b) == 0) &&
+ PyString_CheckExact(a) && PyString_CheckExact(b)) {
+ if (Py_SIZE(a) == 0) {
+ Py_INCREF(bb);
+ return bb;
+ }
+ Py_INCREF(a);
+ return (PyObject *)a;
+ }
+ size = Py_SIZE(a) + Py_SIZE(b);
+ /* Check that string sizes are not negative, to prevent an
+ overflow in cases where we are passed incorrectly-created
+ strings with negative lengths (due to a bug in other code).
+ */
+ if (Py_SIZE(a) < 0 || Py_SIZE(b) < 0 ||
+ Py_SIZE(a) > PY_SSIZE_T_MAX - Py_SIZE(b)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "strings are too large to concat");
+ return NULL;
+ }
+
+ /* Inline PyObject_NewVar */
+ if (size > PY_SSIZE_T_MAX - PyStringObject_SIZE) {
+ PyErr_SetString(PyExc_OverflowError,
+ "strings are too large to concat");
+ return NULL;
+ }
+ op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + size);
+ if (op == NULL)
+ return PyErr_NoMemory();
+ PyObject_INIT_VAR(op, &PyString_Type, size);
+ op->ob_shash = -1;
+ op->ob_sstate = SSTATE_NOT_INTERNED;
+ Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
+ Py_MEMCPY(op->ob_sval + Py_SIZE(a), b->ob_sval, Py_SIZE(b));
+ op->ob_sval[size] = '\0';
+ return (PyObject *) op;
#undef b
}
static PyObject *
string_repeat(register PyStringObject *a, register Py_ssize_t n)
{
- register Py_ssize_t i;
- register Py_ssize_t j;
- register Py_ssize_t size;
- register PyStringObject *op;
- size_t nbytes;
- if (n < 0)
- n = 0;
- /* watch out for overflows: the size can overflow int,
- * and the # of bytes needed can overflow size_t
- */
- size = Py_SIZE(a) * n;
- if (n && size / n != Py_SIZE(a)) {
- PyErr_SetString(PyExc_OverflowError,
- "repeated string is too long");
- return NULL;
- }
- if (size == Py_SIZE(a) && PyString_CheckExact(a)) {
- Py_INCREF(a);
- return (PyObject *)a;
- }
- nbytes = (size_t)size;
- if (nbytes + PyStringObject_SIZE <= nbytes) {
- PyErr_SetString(PyExc_OverflowError,
- "repeated string is too long");
- return NULL;
- }
- op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + nbytes);
- if (op == NULL)
- return PyErr_NoMemory();
- PyObject_INIT_VAR(op, &PyString_Type, size);
- op->ob_shash = -1;
- op->ob_sstate = SSTATE_NOT_INTERNED;
- op->ob_sval[size] = '\0';
- if (Py_SIZE(a) == 1 && n > 0) {
- memset(op->ob_sval, a->ob_sval[0] , n);
- return (PyObject *) op;
- }
- i = 0;
- if (i < size) {
- Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
- i = Py_SIZE(a);
- }
- while (i < size) {
- j = (i <= size-i) ? i : size-i;
- Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
- i += j;
- }
- return (PyObject *) op;
+ register Py_ssize_t i;
+ register Py_ssize_t j;
+ register Py_ssize_t size;
+ register PyStringObject *op;
+ size_t nbytes;
+ if (n < 0)
+ n = 0;
+ /* watch out for overflows: the size can overflow int,
+ * and the # of bytes needed can overflow size_t
+ */
+ size = Py_SIZE(a) * n;
+ if (n && size / n != Py_SIZE(a)) {
+ PyErr_SetString(PyExc_OverflowError,
+ "repeated string is too long");
+ return NULL;
+ }
+ if (size == Py_SIZE(a) && PyString_CheckExact(a)) {
+ Py_INCREF(a);
+ return (PyObject *)a;
+ }
+ nbytes = (size_t)size;
+ if (nbytes + PyStringObject_SIZE <= nbytes) {
+ PyErr_SetString(PyExc_OverflowError,
+ "repeated string is too long");
+ return NULL;
+ }
+ op = (PyStringObject *)PyObject_MALLOC(PyStringObject_SIZE + nbytes);
+ if (op == NULL)
+ return PyErr_NoMemory();
+ PyObject_INIT_VAR(op, &PyString_Type, size);
+ op->ob_shash = -1;
+ op->ob_sstate = SSTATE_NOT_INTERNED;
+ op->ob_sval[size] = '\0';
+ if (Py_SIZE(a) == 1 && n > 0) {
+ memset(op->ob_sval, a->ob_sval[0] , n);
+ return (PyObject *) op;
+ }
+ i = 0;
+ if (i < size) {
+ Py_MEMCPY(op->ob_sval, a->ob_sval, Py_SIZE(a));
+ i = Py_SIZE(a);
+ }
+ while (i < size) {
+ j = (i <= size-i) ? i : size-i;
+ Py_MEMCPY(op->ob_sval+i, op->ob_sval, j);
+ i += j;
+ }
+ return (PyObject *) op;
}
/* String slice a[i:j] consists of characters a[i] ... a[j-1] */
static PyObject *
string_slice(register PyStringObject *a, register Py_ssize_t i,
- register Py_ssize_t j)
+ register Py_ssize_t j)
/* j -- may be negative! */
{
- if (i < 0)
- i = 0;
- if (j < 0)
- j = 0; /* Avoid signed/unsigned bug in next line */
- if (j > Py_SIZE(a))
- j = Py_SIZE(a);
- if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
- /* It's the same as a */
- Py_INCREF(a);
- return (PyObject *)a;
- }
- if (j < i)
- j = i;
- return PyString_FromStringAndSize(a->ob_sval + i, j-i);
+ if (i < 0)
+ i = 0;
+ if (j < 0)
+ j = 0; /* Avoid signed/unsigned bug in next line */
+ if (j > Py_SIZE(a))
+ j = Py_SIZE(a);
+ if (i == 0 && j == Py_SIZE(a) && PyString_CheckExact(a)) {
+ /* It's the same as a */
+ Py_INCREF(a);
+ return (PyObject *)a;
+ }
+ if (j < i)
+ j = i;
+ return PyString_FromStringAndSize(a->ob_sval + i, j-i);
}
static int
string_contains(PyObject *str_obj, PyObject *sub_obj)
{
- if (!PyString_CheckExact(sub_obj)) {
+ if (!PyString_CheckExact(sub_obj)) {
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(sub_obj))
- return PyUnicode_Contains(str_obj, sub_obj);
+ if (PyUnicode_Check(sub_obj))
+ return PyUnicode_Contains(str_obj, sub_obj);
#endif
- if (!PyString_Check(sub_obj)) {
- PyErr_Format(PyExc_TypeError,
- "'in <string>' requires string as left operand, "
- "not %.200s", Py_TYPE(sub_obj)->tp_name);
- return -1;
- }
- }
-
- return stringlib_contains_obj(str_obj, sub_obj);
+ if (!PyString_Check(sub_obj)) {
+ PyErr_Format(PyExc_TypeError,
+ "'in <string>' requires string as left operand, "
+ "not %.200s", Py_TYPE(sub_obj)->tp_name);
+ return -1;
+ }
+ }
+
+ return stringlib_contains_obj(str_obj, sub_obj);
}
static PyObject *
string_item(PyStringObject *a, register Py_ssize_t i)
{
- char pchar;
- PyObject *v;
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError, "string index out of range");
- return NULL;
- }
- pchar = a->ob_sval[i];
- v = (PyObject *)characters[pchar & UCHAR_MAX];
- if (v == NULL)
- v = PyString_FromStringAndSize(&pchar, 1);
- else {
+ char pchar;
+ PyObject *v;
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError, "string index out of range");
+ return NULL;
+ }
+ pchar = a->ob_sval[i];
+ v = (PyObject *)characters[pchar & UCHAR_MAX];
+ if (v == NULL)
+ v = PyString_FromStringAndSize(&pchar, 1);
+ else {
#ifdef COUNT_ALLOCS
- one_strings++;
+ one_strings++;
#endif
- Py_INCREF(v);
- }
- return v;
+ Py_INCREF(v);
+ }
+ return v;
}
static PyObject*
string_richcompare(PyStringObject *a, PyStringObject *b, int op)
{
- int c;
- Py_ssize_t len_a, len_b;
- Py_ssize_t min_len;
- PyObject *result;
-
- /* Make sure both arguments are strings. */
- if (!(PyString_Check(a) && PyString_Check(b))) {
- result = Py_NotImplemented;
- goto out;
- }
- if (a == b) {
- switch (op) {
- case Py_EQ:case Py_LE:case Py_GE:
- result = Py_True;
- goto out;
- case Py_NE:case Py_LT:case Py_GT:
- result = Py_False;
- goto out;
- }
- }
- if (op == Py_EQ) {
- /* Supporting Py_NE here as well does not save
- much time, since Py_NE is rarely used. */
- if (Py_SIZE(a) == Py_SIZE(b)
- && (a->ob_sval[0] == b->ob_sval[0]
- && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
- result = Py_True;
- } else {
- result = Py_False;
- }
- goto out;
- }
- len_a = Py_SIZE(a); len_b = Py_SIZE(b);
- min_len = (len_a < len_b) ? len_a : len_b;
- if (min_len > 0) {
- c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
- if (c==0)
- c = memcmp(a->ob_sval, b->ob_sval, min_len);
- } else
- c = 0;
- if (c == 0)
- c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
- switch (op) {
- case Py_LT: c = c < 0; break;
- case Py_LE: c = c <= 0; break;
- case Py_EQ: assert(0); break; /* unreachable */
- case Py_NE: c = c != 0; break;
- case Py_GT: c = c > 0; break;
- case Py_GE: c = c >= 0; break;
- default:
- result = Py_NotImplemented;
- goto out;
- }
- result = c ? Py_True : Py_False;
+ int c;
+ Py_ssize_t len_a, len_b;
+ Py_ssize_t min_len;
+ PyObject *result;
+
+ /* Make sure both arguments are strings. */
+ if (!(PyString_Check(a) && PyString_Check(b))) {
+ result = Py_NotImplemented;
+ goto out;
+ }
+ if (a == b) {
+ switch (op) {
+ case Py_EQ:case Py_LE:case Py_GE:
+ result = Py_True;
+ goto out;
+ case Py_NE:case Py_LT:case Py_GT:
+ result = Py_False;
+ goto out;
+ }
+ }
+ if (op == Py_EQ) {
+ /* Supporting Py_NE here as well does not save
+ much time, since Py_NE is rarely used. */
+ if (Py_SIZE(a) == Py_SIZE(b)
+ && (a->ob_sval[0] == b->ob_sval[0]
+ && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0)) {
+ result = Py_True;
+ } else {
+ result = Py_False;
+ }
+ goto out;
+ }
+ len_a = Py_SIZE(a); len_b = Py_SIZE(b);
+ min_len = (len_a < len_b) ? len_a : len_b;
+ if (min_len > 0) {
+ c = Py_CHARMASK(*a->ob_sval) - Py_CHARMASK(*b->ob_sval);
+ if (c==0)
+ c = memcmp(a->ob_sval, b->ob_sval, min_len);
+ } else
+ c = 0;
+ if (c == 0)
+ c = (len_a < len_b) ? -1 : (len_a > len_b) ? 1 : 0;
+ switch (op) {
+ case Py_LT: c = c < 0; break;
+ case Py_LE: c = c <= 0; break;
+ case Py_EQ: assert(0); break; /* unreachable */
+ case Py_NE: c = c != 0; break;
+ case Py_GT: c = c > 0; break;
+ case Py_GE: c = c >= 0; break;
+ default:
+ result = Py_NotImplemented;
+ goto out;
+ }
+ result = c ? Py_True : Py_False;
out:
- Py_INCREF(result);
- return result;
+ Py_INCREF(result);
+ return result;
}
int
_PyString_Eq(PyObject *o1, PyObject *o2)
{
- PyStringObject *a = (PyStringObject*) o1;
- PyStringObject *b = (PyStringObject*) o2;
- return Py_SIZE(a) == Py_SIZE(b)
- && *a->ob_sval == *b->ob_sval
- && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0;
+ PyStringObject *a = (PyStringObject*) o1;
+ PyStringObject *b = (PyStringObject*) o2;
+ return Py_SIZE(a) == Py_SIZE(b)
+ && *a->ob_sval == *b->ob_sval
+ && memcmp(a->ob_sval, b->ob_sval, Py_SIZE(a)) == 0;
}
static long
string_hash(PyStringObject *a)
{
- register Py_ssize_t len;
- register unsigned char *p;
- register long x;
-
- if (a->ob_shash != -1)
- return a->ob_shash;
- len = Py_SIZE(a);
- p = (unsigned char *) a->ob_sval;
- x = *p << 7;
- while (--len >= 0)
- x = (1000003*x) ^ *p++;
- x ^= Py_SIZE(a);
- if (x == -1)
- x = -2;
- a->ob_shash = x;
- return x;
+ register Py_ssize_t len;
+ register unsigned char *p;
+ register long x;
+
+ if (a->ob_shash != -1)
+ return a->ob_shash;
+ len = Py_SIZE(a);
+ p = (unsigned char *) a->ob_sval;
+ x = *p << 7;
+ while (--len >= 0)
+ x = (1000003*x) ^ *p++;
+ x ^= Py_SIZE(a);
+ if (x == -1)
+ x = -2;
+ a->ob_shash = x;
+ return x;
}
static PyObject*
string_subscript(PyStringObject* self, PyObject* item)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += PyString_GET_SIZE(self);
- return string_item(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength, cur, i;
- char* source_buf;
- char* result_buf;
- PyObject* result;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item,
- PyString_GET_SIZE(self),
- &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyString_FromStringAndSize("", 0);
- }
- else if (start == 0 && step == 1 &&
- slicelength == PyString_GET_SIZE(self) &&
- PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- else if (step == 1) {
- return PyString_FromStringAndSize(
- PyString_AS_STRING(self) + start,
- slicelength);
- }
- else {
- source_buf = PyString_AsString((PyObject*)self);
- result_buf = (char *)PyMem_Malloc(slicelength);
- if (result_buf == NULL)
- return PyErr_NoMemory();
-
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- result_buf[i] = source_buf[cur];
- }
-
- result = PyString_FromStringAndSize(result_buf,
- slicelength);
- PyMem_Free(result_buf);
- return result;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "string indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += PyString_GET_SIZE(self);
+ return string_item(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength, cur, i;
+ char* source_buf;
+ char* result_buf;
+ PyObject* result;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item,
+ PyString_GET_SIZE(self),
+ &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyString_FromStringAndSize("", 0);
+ }
+ else if (start == 0 && step == 1 &&
+ slicelength == PyString_GET_SIZE(self) &&
+ PyString_CheckExact(self)) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ else if (step == 1) {
+ return PyString_FromStringAndSize(
+ PyString_AS_STRING(self) + start,
+ slicelength);
+ }
+ else {
+ source_buf = PyString_AsString((PyObject*)self);
+ result_buf = (char *)PyMem_Malloc(slicelength);
+ if (result_buf == NULL)
+ return PyErr_NoMemory();
+
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ result_buf[i] = source_buf[cur];
+ }
+
+ result = PyString_FromStringAndSize(result_buf,
+ slicelength);
+ PyMem_Free(result_buf);
+ return result;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "string indices must be integers, not %.200s",
+ Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static Py_ssize_t
string_buffer_getreadbuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
{
- if ( index != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent string segment");
- return -1;
- }
- *ptr = (void *)self->ob_sval;
- return Py_SIZE(self);
+ if ( index != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent string segment");
+ return -1;
+ }
+ *ptr = (void *)self->ob_sval;
+ return Py_SIZE(self);
}
static Py_ssize_t
string_buffer_getwritebuf(PyStringObject *self, Py_ssize_t index, const void **ptr)
{
- PyErr_SetString(PyExc_TypeError,
- "Cannot use string as modifiable buffer");
- return -1;
+ PyErr_SetString(PyExc_TypeError,
+ "Cannot use string as modifiable buffer");
+ return -1;
}
static Py_ssize_t
string_buffer_getsegcount(PyStringObject *self, Py_ssize_t *lenp)
{
- if ( lenp )
- *lenp = Py_SIZE(self);
- return 1;
+ if ( lenp )
+ *lenp = Py_SIZE(self);
+ return 1;
}
static Py_ssize_t
string_buffer_getcharbuf(PyStringObject *self, Py_ssize_t index, const char **ptr)
{
- if ( index != 0 ) {
- PyErr_SetString(PyExc_SystemError,
- "accessing non-existent string segment");
- return -1;
- }
- *ptr = self->ob_sval;
- return Py_SIZE(self);
+ if ( index != 0 ) {
+ PyErr_SetString(PyExc_SystemError,
+ "accessing non-existent string segment");
+ return -1;
+ }
+ *ptr = self->ob_sval;
+ return Py_SIZE(self);
}
static int
string_buffer_getbuffer(PyStringObject *self, Py_buffer *view, int flags)
{
- return PyBuffer_FillInfo(view, (PyObject*)self,
- (void *)self->ob_sval, Py_SIZE(self),
- 1, flags);
+ return PyBuffer_FillInfo(view, (PyObject*)self,
+ (void *)self->ob_sval, Py_SIZE(self),
+ 1, flags);
}
static PySequenceMethods string_as_sequence = {
- (lenfunc)string_length, /*sq_length*/
- (binaryfunc)string_concat, /*sq_concat*/
- (ssizeargfunc)string_repeat, /*sq_repeat*/
- (ssizeargfunc)string_item, /*sq_item*/
- (ssizessizeargfunc)string_slice, /*sq_slice*/
- 0, /*sq_ass_item*/
- 0, /*sq_ass_slice*/
- (objobjproc)string_contains /*sq_contains*/
+ (lenfunc)string_length, /*sq_length*/
+ (binaryfunc)string_concat, /*sq_concat*/
+ (ssizeargfunc)string_repeat, /*sq_repeat*/
+ (ssizeargfunc)string_item, /*sq_item*/
+ (ssizessizeargfunc)string_slice, /*sq_slice*/
+ 0, /*sq_ass_item*/
+ 0, /*sq_ass_slice*/
+ (objobjproc)string_contains /*sq_contains*/
};
static PyMappingMethods string_as_mapping = {
- (lenfunc)string_length,
- (binaryfunc)string_subscript,
- 0,
+ (lenfunc)string_length,
+ (binaryfunc)string_subscript,
+ 0,
};
static PyBufferProcs string_as_buffer = {
- (readbufferproc)string_buffer_getreadbuf,
- (writebufferproc)string_buffer_getwritebuf,
- (segcountproc)string_buffer_getsegcount,
- (charbufferproc)string_buffer_getcharbuf,
- (getbufferproc)string_buffer_getbuffer,
- 0, /* XXX */
+ (readbufferproc)string_buffer_getreadbuf,
+ (writebufferproc)string_buffer_getwritebuf,
+ (segcountproc)string_buffer_getsegcount,
+ (charbufferproc)string_buffer_getcharbuf,
+ (getbufferproc)string_buffer_getbuffer,
+ 0, /* XXX */
};
@@ -1439,29 +1439,29 @@ from the result.");
static PyObject *
string_split(PyStringObject *self, PyObject *args)
{
- Py_ssize_t len = PyString_GET_SIZE(self), n;
- Py_ssize_t maxsplit = -1;
- const char *s = PyString_AS_STRING(self), *sub;
- PyObject *subobj = Py_None;
-
- if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
- return NULL;
- if (maxsplit < 0)
- maxsplit = PY_SSIZE_T_MAX;
- if (subobj == Py_None)
- return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
- if (PyString_Check(subobj)) {
- sub = PyString_AS_STRING(subobj);
- n = PyString_GET_SIZE(subobj);
- }
+ Py_ssize_t len = PyString_GET_SIZE(self), n;
+ Py_ssize_t maxsplit = -1;
+ const char *s = PyString_AS_STRING(self), *sub;
+ PyObject *subobj = Py_None;
+
+ if (!PyArg_ParseTuple(args, "|On:split", &subobj, &maxsplit))
+ return NULL;
+ if (maxsplit < 0)
+ maxsplit = PY_SSIZE_T_MAX;
+ if (subobj == Py_None)
+ return stringlib_split_whitespace((PyObject*) self, s, len, maxsplit);
+ if (PyString_Check(subobj)) {
+ sub = PyString_AS_STRING(subobj);
+ n = PyString_GET_SIZE(subobj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(subobj))
- return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
+ else if (PyUnicode_Check(subobj))
+ return PyUnicode_Split((PyObject *)self, subobj, maxsplit);
#endif
- else if (PyObject_AsCharBuffer(subobj, &sub, &n))
- return NULL;
+ else if (PyObject_AsCharBuffer(subobj, &sub, &n))
+ return NULL;
- return stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
+ return stringlib_split((PyObject*) self, s, len, sub, n, maxsplit);
}
PyDoc_STRVAR(partition__doc__,
@@ -1474,25 +1474,25 @@ found, return S and two empty strings.");
static PyObject *
string_partition(PyStringObject *self, PyObject *sep_obj)
{
- const char *sep;
- Py_ssize_t sep_len;
+ const char *sep;
+ Py_ssize_t sep_len;
- if (PyString_Check(sep_obj)) {
- sep = PyString_AS_STRING(sep_obj);
- sep_len = PyString_GET_SIZE(sep_obj);
- }
+ if (PyString_Check(sep_obj)) {
+ sep = PyString_AS_STRING(sep_obj);
+ sep_len = PyString_GET_SIZE(sep_obj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(sep_obj))
- return PyUnicode_Partition((PyObject *) self, sep_obj);
+ else if (PyUnicode_Check(sep_obj))
+ return PyUnicode_Partition((PyObject *) self, sep_obj);
#endif
- else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
- return NULL;
-
- return stringlib_partition(
- (PyObject*) self,
- PyString_AS_STRING(self), PyString_GET_SIZE(self),
- sep_obj, sep, sep_len
- );
+ else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
+ return NULL;
+
+ return stringlib_partition(
+ (PyObject*) self,
+ PyString_AS_STRING(self), PyString_GET_SIZE(self),
+ sep_obj, sep, sep_len
+ );
}
PyDoc_STRVAR(rpartition__doc__,
@@ -1505,25 +1505,25 @@ separator is not found, return two empty strings and S.");
static PyObject *
string_rpartition(PyStringObject *self, PyObject *sep_obj)
{
- const char *sep;
- Py_ssize_t sep_len;
+ const char *sep;
+ Py_ssize_t sep_len;
- if (PyString_Check(sep_obj)) {
- sep = PyString_AS_STRING(sep_obj);
- sep_len = PyString_GET_SIZE(sep_obj);
- }
+ if (PyString_Check(sep_obj)) {
+ sep = PyString_AS_STRING(sep_obj);
+ sep_len = PyString_GET_SIZE(sep_obj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(sep_obj))
- return PyUnicode_RPartition((PyObject *) self, sep_obj);
+ else if (PyUnicode_Check(sep_obj))
+ return PyUnicode_RPartition((PyObject *) self, sep_obj);
#endif
- else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
- return NULL;
-
- return stringlib_rpartition(
- (PyObject*) self,
- PyString_AS_STRING(self), PyString_GET_SIZE(self),
- sep_obj, sep, sep_len
- );
+ else if (PyObject_AsCharBuffer(sep_obj, &sep, &sep_len))
+ return NULL;
+
+ return stringlib_rpartition(
+ (PyObject*) self,
+ PyString_AS_STRING(self), PyString_GET_SIZE(self),
+ sep_obj, sep, sep_len
+ );
}
PyDoc_STRVAR(rsplit__doc__,
@@ -1538,29 +1538,29 @@ is a separator.");
static PyObject *
string_rsplit(PyStringObject *self, PyObject *args)
{
- Py_ssize_t len = PyString_GET_SIZE(self), n;
- Py_ssize_t maxsplit = -1;
- const char *s = PyString_AS_STRING(self), *sub;
- PyObject *subobj = Py_None;
-
- if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
- return NULL;
- if (maxsplit < 0)
- maxsplit = PY_SSIZE_T_MAX;
- if (subobj == Py_None)
- return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
- if (PyString_Check(subobj)) {
- sub = PyString_AS_STRING(subobj);
- n = PyString_GET_SIZE(subobj);
- }
+ Py_ssize_t len = PyString_GET_SIZE(self), n;
+ Py_ssize_t maxsplit = -1;
+ const char *s = PyString_AS_STRING(self), *sub;
+ PyObject *subobj = Py_None;
+
+ if (!PyArg_ParseTuple(args, "|On:rsplit", &subobj, &maxsplit))
+ return NULL;
+ if (maxsplit < 0)
+ maxsplit = PY_SSIZE_T_MAX;
+ if (subobj == Py_None)
+ return stringlib_rsplit_whitespace((PyObject*) self, s, len, maxsplit);
+ if (PyString_Check(subobj)) {
+ sub = PyString_AS_STRING(subobj);
+ n = PyString_GET_SIZE(subobj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(subobj))
- return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
+ else if (PyUnicode_Check(subobj))
+ return PyUnicode_RSplit((PyObject *)self, subobj, maxsplit);
#endif
- else if (PyObject_AsCharBuffer(subobj, &sub, &n))
- return NULL;
+ else if (PyObject_AsCharBuffer(subobj, &sub, &n))
+ return NULL;
- return stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
+ return stringlib_rsplit((PyObject*) self, s, len, sub, n, maxsplit);
}
@@ -1573,167 +1573,167 @@ iterable. The separator between elements is S.");
static PyObject *
string_join(PyStringObject *self, PyObject *orig)
{
- char *sep = PyString_AS_STRING(self);
- const Py_ssize_t seplen = PyString_GET_SIZE(self);
- PyObject *res = NULL;
- char *p;
- Py_ssize_t seqlen = 0;
- size_t sz = 0;
- Py_ssize_t i;
- PyObject *seq, *item;
-
- seq = PySequence_Fast(orig, "");
- if (seq == NULL) {
- return NULL;
- }
-
- seqlen = PySequence_Size(seq);
- if (seqlen == 0) {
- Py_DECREF(seq);
- return PyString_FromString("");
- }
- if (seqlen == 1) {
- item = PySequence_Fast_GET_ITEM(seq, 0);
- if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
- Py_INCREF(item);
- Py_DECREF(seq);
- return item;
- }
- }
-
- /* There are at least two things to join, or else we have a subclass
- * of the builtin types in the sequence.
- * Do a pre-pass to figure out the total amount of space we'll
- * need (sz), see whether any argument is absurd, and defer to
- * the Unicode join if appropriate.
- */
- for (i = 0; i < seqlen; i++) {
- const size_t old_sz = sz;
- item = PySequence_Fast_GET_ITEM(seq, i);
- if (!PyString_Check(item)){
+ char *sep = PyString_AS_STRING(self);
+ const Py_ssize_t seplen = PyString_GET_SIZE(self);
+ PyObject *res = NULL;
+ char *p;
+ Py_ssize_t seqlen = 0;
+ size_t sz = 0;
+ Py_ssize_t i;
+ PyObject *seq, *item;
+
+ seq = PySequence_Fast(orig, "");
+ if (seq == NULL) {
+ return NULL;
+ }
+
+ seqlen = PySequence_Size(seq);
+ if (seqlen == 0) {
+ Py_DECREF(seq);
+ return PyString_FromString("");
+ }
+ if (seqlen == 1) {
+ item = PySequence_Fast_GET_ITEM(seq, 0);
+ if (PyString_CheckExact(item) || PyUnicode_CheckExact(item)) {
+ Py_INCREF(item);
+ Py_DECREF(seq);
+ return item;
+ }
+ }
+
+ /* There are at least two things to join, or else we have a subclass
+ * of the builtin types in the sequence.
+ * Do a pre-pass to figure out the total amount of space we'll
+ * need (sz), see whether any argument is absurd, and defer to
+ * the Unicode join if appropriate.
+ */
+ for (i = 0; i < seqlen; i++) {
+ const size_t old_sz = sz;
+ item = PySequence_Fast_GET_ITEM(seq, i);
+ if (!PyString_Check(item)){
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(item)) {
- /* Defer to Unicode join.
- * CAUTION: There's no gurantee that the
- * original sequence can be iterated over
- * again, so we must pass seq here.
- */
- PyObject *result;
- result = PyUnicode_Join((PyObject *)self, seq);
- Py_DECREF(seq);
- return result;
- }
+ if (PyUnicode_Check(item)) {
+ /* Defer to Unicode join.
+ * CAUTION: There's no gurantee that the
+ * original sequence can be iterated over
+ * again, so we must pass seq here.
+ */
+ PyObject *result;
+ result = PyUnicode_Join((PyObject *)self, seq);
+ Py_DECREF(seq);
+ return result;
+ }
#endif
- PyErr_Format(PyExc_TypeError,
- "sequence item %zd: expected string,"
- " %.80s found",
- i, Py_TYPE(item)->tp_name);
- Py_DECREF(seq);
- return NULL;
- }
- sz += PyString_GET_SIZE(item);
- if (i != 0)
- sz += seplen;
- if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "join() result is too long for a Python string");
- Py_DECREF(seq);
- return NULL;
- }
- }
-
- /* Allocate result space. */
- res = PyString_FromStringAndSize((char*)NULL, sz);
- if (res == NULL) {
- Py_DECREF(seq);
- return NULL;
- }
-
- /* Catenate everything. */
- p = PyString_AS_STRING(res);
- for (i = 0; i < seqlen; ++i) {
- size_t n;
- item = PySequence_Fast_GET_ITEM(seq, i);
- n = PyString_GET_SIZE(item);
- Py_MEMCPY(p, PyString_AS_STRING(item), n);
- p += n;
- if (i < seqlen - 1) {
- Py_MEMCPY(p, sep, seplen);
- p += seplen;
- }
- }
-
- Py_DECREF(seq);
- return res;
+ PyErr_Format(PyExc_TypeError,
+ "sequence item %zd: expected string,"
+ " %.80s found",
+ i, Py_TYPE(item)->tp_name);
+ Py_DECREF(seq);
+ return NULL;
+ }
+ sz += PyString_GET_SIZE(item);
+ if (i != 0)
+ sz += seplen;
+ if (sz < old_sz || sz > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "join() result is too long for a Python string");
+ Py_DECREF(seq);
+ return NULL;
+ }
+ }
+
+ /* Allocate result space. */
+ res = PyString_FromStringAndSize((char*)NULL, sz);
+ if (res == NULL) {
+ Py_DECREF(seq);
+ return NULL;
+ }
+
+ /* Catenate everything. */
+ p = PyString_AS_STRING(res);
+ for (i = 0; i < seqlen; ++i) {
+ size_t n;
+ item = PySequence_Fast_GET_ITEM(seq, i);
+ n = PyString_GET_SIZE(item);
+ Py_MEMCPY(p, PyString_AS_STRING(item), n);
+ p += n;
+ if (i < seqlen - 1) {
+ Py_MEMCPY(p, sep, seplen);
+ p += seplen;
+ }
+ }
+
+ Py_DECREF(seq);
+ return res;
}
PyObject *
_PyString_Join(PyObject *sep, PyObject *x)
{
- assert(sep != NULL && PyString_Check(sep));
- assert(x != NULL);
- return string_join((PyStringObject *)sep, x);
+ assert(sep != NULL && PyString_Check(sep));
+ assert(x != NULL);
+ return string_join((PyStringObject *)sep, x);
}
/* helper macro to fixup start/end slice values */
#define ADJUST_INDICES(start, end, len) \
- if (end > len) \
- end = len; \
- else if (end < 0) { \
- end += len; \
- if (end < 0) \
- end = 0; \
- } \
- if (start < 0) { \
- start += len; \
- if (start < 0) \
- start = 0; \
- }
+ if (end > len) \
+ end = len; \
+ else if (end < 0) { \
+ end += len; \
+ if (end < 0) \
+ end = 0; \
+ } \
+ if (start < 0) { \
+ start += len; \
+ if (start < 0) \
+ start = 0; \
+ }
Py_LOCAL_INLINE(Py_ssize_t)
string_find_internal(PyStringObject *self, PyObject *args, int dir)
{
- PyObject *subobj;
- const char *sub;
- Py_ssize_t sub_len;
- Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
- PyObject *obj_start=Py_None, *obj_end=Py_None;
-
- if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj,
- &obj_start, &obj_end))
- return -2;
- /* To support None in "start" and "end" arguments, meaning
- the same as if they were not passed.
- */
- if (obj_start != Py_None)
- if (!_PyEval_SliceIndex(obj_start, &start))
- return -2;
- if (obj_end != Py_None)
- if (!_PyEval_SliceIndex(obj_end, &end))
- return -2;
-
- if (PyString_Check(subobj)) {
- sub = PyString_AS_STRING(subobj);
- sub_len = PyString_GET_SIZE(subobj);
- }
+ PyObject *subobj;
+ const char *sub;
+ Py_ssize_t sub_len;
+ Py_ssize_t start=0, end=PY_SSIZE_T_MAX;
+ PyObject *obj_start=Py_None, *obj_end=Py_None;
+
+ if (!PyArg_ParseTuple(args, "O|OO:find/rfind/index/rindex", &subobj,
+ &obj_start, &obj_end))
+ return -2;
+ /* To support None in "start" and "end" arguments, meaning
+ the same as if they were not passed.
+ */
+ if (obj_start != Py_None)
+ if (!_PyEval_SliceIndex(obj_start, &start))
+ return -2;
+ if (obj_end != Py_None)
+ if (!_PyEval_SliceIndex(obj_end, &end))
+ return -2;
+
+ if (PyString_Check(subobj)) {
+ sub = PyString_AS_STRING(subobj);
+ sub_len = PyString_GET_SIZE(subobj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(subobj))
- return PyUnicode_Find(
- (PyObject *)self, subobj, start, end, dir);
+ else if (PyUnicode_Check(subobj))
+ return PyUnicode_Find(
+ (PyObject *)self, subobj, start, end, dir);
#endif
- else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
- /* XXX - the "expected a character buffer object" is pretty
- confusing for a non-expert. remap to something else ? */
- return -2;
-
- if (dir > 0)
- return stringlib_find_slice(
- PyString_AS_STRING(self), PyString_GET_SIZE(self),
- sub, sub_len, start, end);
- else
- return stringlib_rfind_slice(
- PyString_AS_STRING(self), PyString_GET_SIZE(self),
- sub, sub_len, start, end);
+ else if (PyObject_AsCharBuffer(subobj, &sub, &sub_len))
+ /* XXX - the "expected a character buffer object" is pretty
+ confusing for a non-expert. remap to something else ? */
+ return -2;
+
+ if (dir > 0)
+ return stringlib_find_slice(
+ PyString_AS_STRING(self), PyString_GET_SIZE(self),
+ sub, sub_len, start, end);
+ else
+ return stringlib_rfind_slice(
+ PyString_AS_STRING(self), PyString_GET_SIZE(self),
+ sub, sub_len, start, end);
}
@@ -1749,10 +1749,10 @@ Return -1 on failure.");
static PyObject *
string_find(PyStringObject *self, PyObject *args)
{
- Py_ssize_t result = string_find_internal(self, args, +1);
- if (result == -2)
- return NULL;
- return PyInt_FromSsize_t(result);
+ Py_ssize_t result = string_find_internal(self, args, +1);
+ if (result == -2)
+ return NULL;
+ return PyInt_FromSsize_t(result);
}
@@ -1764,15 +1764,15 @@ Like S.find() but raise ValueError when the substring is not found.");
static PyObject *
string_index(PyStringObject *self, PyObject *args)
{
- Py_ssize_t result = string_find_internal(self, args, +1);
- if (result == -2)
- return NULL;
- if (result == -1) {
- PyErr_SetString(PyExc_ValueError,
- "substring not found");
- return NULL;
- }
- return PyInt_FromSsize_t(result);
+ Py_ssize_t result = string_find_internal(self, args, +1);
+ if (result == -2)
+ return NULL;
+ if (result == -1) {
+ PyErr_SetString(PyExc_ValueError,
+ "substring not found");
+ return NULL;
+ }
+ return PyInt_FromSsize_t(result);
}
@@ -1788,10 +1788,10 @@ Return -1 on failure.");
static PyObject *
string_rfind(PyStringObject *self, PyObject *args)
{
- Py_ssize_t result = string_find_internal(self, args, -1);
- if (result == -2)
- return NULL;
- return PyInt_FromSsize_t(result);
+ Py_ssize_t result = string_find_internal(self, args, -1);
+ if (result == -2)
+ return NULL;
+ return PyInt_FromSsize_t(result);
}
@@ -1803,115 +1803,115 @@ Like S.rfind() but raise ValueError when the substring is not found.");
static PyObject *
string_rindex(PyStringObject *self, PyObject *args)
{
- Py_ssize_t result = string_find_internal(self, args, -1);
- if (result == -2)
- return NULL;
- if (result == -1) {
- PyErr_SetString(PyExc_ValueError,
- "substring not found");
- return NULL;
- }
- return PyInt_FromSsize_t(result);
+ Py_ssize_t result = string_find_internal(self, args, -1);
+ if (result == -2)
+ return NULL;
+ if (result == -1) {
+ PyErr_SetString(PyExc_ValueError,
+ "substring not found");
+ return NULL;
+ }
+ return PyInt_FromSsize_t(result);
}
Py_LOCAL_INLINE(PyObject *)
do_xstrip(PyStringObject *self, int striptype, PyObject *sepobj)
{
- char *s = PyString_AS_STRING(self);
- Py_ssize_t len = PyString_GET_SIZE(self);
- char *sep = PyString_AS_STRING(sepobj);
- Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
- Py_ssize_t i, j;
-
- i = 0;
- if (striptype != RIGHTSTRIP) {
- while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
- i++;
- }
- }
-
- j = len;
- if (striptype != LEFTSTRIP) {
- do {
- j--;
- } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
- j++;
- }
-
- if (i == 0 && j == len && PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject*)self;
- }
- else
- return PyString_FromStringAndSize(s+i, j-i);
+ char *s = PyString_AS_STRING(self);
+ Py_ssize_t len = PyString_GET_SIZE(self);
+ char *sep = PyString_AS_STRING(sepobj);
+ Py_ssize_t seplen = PyString_GET_SIZE(sepobj);
+ Py_ssize_t i, j;
+
+ i = 0;
+ if (striptype != RIGHTSTRIP) {
+ while (i < len && memchr(sep, Py_CHARMASK(s[i]), seplen)) {
+ i++;
+ }
+ }
+
+ j = len;
+ if (striptype != LEFTSTRIP) {
+ do {
+ j--;
+ } while (j >= i && memchr(sep, Py_CHARMASK(s[j]), seplen));
+ j++;
+ }
+
+ if (i == 0 && j == len && PyString_CheckExact(self)) {
+ Py_INCREF(self);
+ return (PyObject*)self;
+ }
+ else
+ return PyString_FromStringAndSize(s+i, j-i);
}
Py_LOCAL_INLINE(PyObject *)
do_strip(PyStringObject *self, int striptype)
{
- char *s = PyString_AS_STRING(self);
- Py_ssize_t len = PyString_GET_SIZE(self), i, j;
-
- i = 0;
- if (striptype != RIGHTSTRIP) {
- while (i < len && isspace(Py_CHARMASK(s[i]))) {
- i++;
- }
- }
-
- j = len;
- if (striptype != LEFTSTRIP) {
- do {
- j--;
- } while (j >= i && isspace(Py_CHARMASK(s[j])));
- j++;
- }
-
- if (i == 0 && j == len && PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject*)self;
- }
- else
- return PyString_FromStringAndSize(s+i, j-i);
+ char *s = PyString_AS_STRING(self);
+ Py_ssize_t len = PyString_GET_SIZE(self), i, j;
+
+ i = 0;
+ if (striptype != RIGHTSTRIP) {
+ while (i < len && isspace(Py_CHARMASK(s[i]))) {
+ i++;
+ }
+ }
+
+ j = len;
+ if (striptype != LEFTSTRIP) {
+ do {
+ j--;
+ } while (j >= i && isspace(Py_CHARMASK(s[j])));
+ j++;
+ }
+
+ if (i == 0 && j == len && PyString_CheckExact(self)) {
+ Py_INCREF(self);
+ return (PyObject*)self;
+ }
+ else
+ return PyString_FromStringAndSize(s+i, j-i);
}
Py_LOCAL_INLINE(PyObject *)
do_argstrip(PyStringObject *self, int striptype, PyObject *args)
{
- PyObject *sep = NULL;
+ PyObject *sep = NULL;
- if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
- return NULL;
+ if (!PyArg_ParseTuple(args, (char *)stripformat[striptype], &sep))
+ return NULL;
- if (sep != NULL && sep != Py_None) {
- if (PyString_Check(sep))
- return do_xstrip(self, striptype, sep);
+ if (sep != NULL && sep != Py_None) {
+ if (PyString_Check(sep))
+ return do_xstrip(self, striptype, sep);
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(sep)) {
- PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
- PyObject *res;
- if (uniself==NULL)
- return NULL;
- res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
- striptype, sep);
- Py_DECREF(uniself);
- return res;
- }
+ else if (PyUnicode_Check(sep)) {
+ PyObject *uniself = PyUnicode_FromObject((PyObject *)self);
+ PyObject *res;
+ if (uniself==NULL)
+ return NULL;
+ res = _PyUnicode_XStrip((PyUnicodeObject *)uniself,
+ striptype, sep);
+ Py_DECREF(uniself);
+ return res;
+ }
#endif
- PyErr_Format(PyExc_TypeError,
+ PyErr_Format(PyExc_TypeError,
#ifdef Py_USING_UNICODE
- "%s arg must be None, str or unicode",
+ "%s arg must be None, str or unicode",
#else
- "%s arg must be None or str",
+ "%s arg must be None or str",
#endif
- STRIPNAME(striptype));
- return NULL;
- }
+ STRIPNAME(striptype));
+ return NULL;
+ }
- return do_strip(self, striptype);
+ return do_strip(self, striptype);
}
@@ -1926,10 +1926,10 @@ If chars is unicode, S will be converted to unicode before stripping");
static PyObject *
string_strip(PyStringObject *self, PyObject *args)
{
- if (PyTuple_GET_SIZE(args) == 0)
- return do_strip(self, BOTHSTRIP); /* Common case */
- else
- return do_argstrip(self, BOTHSTRIP, args);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return do_strip(self, BOTHSTRIP); /* Common case */
+ else
+ return do_argstrip(self, BOTHSTRIP, args);
}
@@ -1943,10 +1943,10 @@ If chars is unicode, S will be converted to unicode before stripping");
static PyObject *
string_lstrip(PyStringObject *self, PyObject *args)
{
- if (PyTuple_GET_SIZE(args) == 0)
- return do_strip(self, LEFTSTRIP); /* Common case */
- else
- return do_argstrip(self, LEFTSTRIP, args);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return do_strip(self, LEFTSTRIP); /* Common case */
+ else
+ return do_argstrip(self, LEFTSTRIP, args);
}
@@ -1960,10 +1960,10 @@ If chars is unicode, S will be converted to unicode before stripping");
static PyObject *
string_rstrip(PyStringObject *self, PyObject *args)
{
- if (PyTuple_GET_SIZE(args) == 0)
- return do_strip(self, RIGHTSTRIP); /* Common case */
- else
- return do_argstrip(self, RIGHTSTRIP, args);
+ if (PyTuple_GET_SIZE(args) == 0)
+ return do_strip(self, RIGHTSTRIP); /* Common case */
+ else
+ return do_argstrip(self, RIGHTSTRIP, args);
}
@@ -1980,25 +1980,25 @@ Return a copy of the string S converted to lowercase.");
static PyObject *
string_lower(PyStringObject *self)
{
- char *s;
- Py_ssize_t i, n = PyString_GET_SIZE(self);
- PyObject *newobj;
+ char *s;
+ Py_ssize_t i, n = PyString_GET_SIZE(self);
+ PyObject *newobj;
- newobj = PyString_FromStringAndSize(NULL, n);
- if (!newobj)
- return NULL;
+ newobj = PyString_FromStringAndSize(NULL, n);
+ if (!newobj)
+ return NULL;
- s = PyString_AS_STRING(newobj);
+ s = PyString_AS_STRING(newobj);
- Py_MEMCPY(s, PyString_AS_STRING(self), n);
+ Py_MEMCPY(s, PyString_AS_STRING(self), n);
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(s[i]);
- if (isupper(c))
- s[i] = _tolower(c);
- }
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(s[i]);
+ if (isupper(c))
+ s[i] = _tolower(c);
+ }
- return newobj;
+ return newobj;
}
PyDoc_STRVAR(upper__doc__,
@@ -2013,25 +2013,25 @@ Return a copy of the string S converted to uppercase.");
static PyObject *
string_upper(PyStringObject *self)
{
- char *s;
- Py_ssize_t i, n = PyString_GET_SIZE(self);
- PyObject *newobj;
+ char *s;
+ Py_ssize_t i, n = PyString_GET_SIZE(self);
+ PyObject *newobj;
- newobj = PyString_FromStringAndSize(NULL, n);
- if (!newobj)
- return NULL;
+ newobj = PyString_FromStringAndSize(NULL, n);
+ if (!newobj)
+ return NULL;
- s = PyString_AS_STRING(newobj);
+ s = PyString_AS_STRING(newobj);
- Py_MEMCPY(s, PyString_AS_STRING(self), n);
+ Py_MEMCPY(s, PyString_AS_STRING(self), n);
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(s[i]);
- if (islower(c))
- s[i] = _toupper(c);
- }
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(s[i]);
+ if (islower(c))
+ s[i] = _toupper(c);
+ }
- return newobj;
+ return newobj;
}
PyDoc_STRVAR(title__doc__,
@@ -2043,30 +2043,30 @@ characters, all remaining cased characters have lowercase.");
static PyObject*
string_title(PyStringObject *self)
{
- char *s = PyString_AS_STRING(self), *s_new;
- Py_ssize_t i, n = PyString_GET_SIZE(self);
- int previous_is_cased = 0;
- PyObject *newobj;
-
- newobj = PyString_FromStringAndSize(NULL, n);
- if (newobj == NULL)
- return NULL;
- s_new = PyString_AsString(newobj);
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- if (!previous_is_cased)
- c = toupper(c);
- previous_is_cased = 1;
- } else if (isupper(c)) {
- if (previous_is_cased)
- c = tolower(c);
- previous_is_cased = 1;
- } else
- previous_is_cased = 0;
- *s_new++ = c;
- }
- return newobj;
+ char *s = PyString_AS_STRING(self), *s_new;
+ Py_ssize_t i, n = PyString_GET_SIZE(self);
+ int previous_is_cased = 0;
+ PyObject *newobj;
+
+ newobj = PyString_FromStringAndSize(NULL, n);
+ if (newobj == NULL)
+ return NULL;
+ s_new = PyString_AsString(newobj);
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ if (!previous_is_cased)
+ c = toupper(c);
+ previous_is_cased = 1;
+ } else if (isupper(c)) {
+ if (previous_is_cased)
+ c = tolower(c);
+ previous_is_cased = 1;
+ } else
+ previous_is_cased = 0;
+ *s_new++ = c;
+ }
+ return newobj;
}
PyDoc_STRVAR(capitalize__doc__,
@@ -2078,31 +2078,31 @@ capitalized.");
static PyObject *
string_capitalize(PyStringObject *self)
{
- char *s = PyString_AS_STRING(self), *s_new;
- Py_ssize_t i, n = PyString_GET_SIZE(self);
- PyObject *newobj;
-
- newobj = PyString_FromStringAndSize(NULL, n);
- if (newobj == NULL)
- return NULL;
- s_new = PyString_AsString(newobj);
- if (0 < n) {
- int c = Py_CHARMASK(*s++);
- if (islower(c))
- *s_new = toupper(c);
- else
- *s_new = c;
- s_new++;
- }
- for (i = 1; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (isupper(c))
- *s_new = tolower(c);
- else
- *s_new = c;
- s_new++;
- }
- return newobj;
+ char *s = PyString_AS_STRING(self), *s_new;
+ Py_ssize_t i, n = PyString_GET_SIZE(self);
+ PyObject *newobj;
+
+ newobj = PyString_FromStringAndSize(NULL, n);
+ if (newobj == NULL)
+ return NULL;
+ s_new = PyString_AsString(newobj);
+ if (0 < n) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c))
+ *s_new = toupper(c);
+ else
+ *s_new = c;
+ s_new++;
+ }
+ for (i = 1; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (isupper(c))
+ *s_new = tolower(c);
+ else
+ *s_new = c;
+ s_new++;
+ }
+ return newobj;
}
@@ -2116,37 +2116,37 @@ as in slice notation.");
static PyObject *
string_count(PyStringObject *self, PyObject *args)
{
- PyObject *sub_obj;
- const char *str = PyString_AS_STRING(self), *sub;
- Py_ssize_t sub_len;
- Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
-
- if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
- _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
- return NULL;
-
- if (PyString_Check(sub_obj)) {
- sub = PyString_AS_STRING(sub_obj);
- sub_len = PyString_GET_SIZE(sub_obj);
- }
+ PyObject *sub_obj;
+ const char *str = PyString_AS_STRING(self), *sub;
+ Py_ssize_t sub_len;
+ Py_ssize_t start = 0, end = PY_SSIZE_T_MAX;
+
+ if (!PyArg_ParseTuple(args, "O|O&O&:count", &sub_obj,
+ _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+ return NULL;
+
+ if (PyString_Check(sub_obj)) {
+ sub = PyString_AS_STRING(sub_obj);
+ sub_len = PyString_GET_SIZE(sub_obj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(sub_obj)) {
- Py_ssize_t count;
- count = PyUnicode_Count((PyObject *)self, sub_obj, start, end);
- if (count == -1)
- return NULL;
- else
- return PyInt_FromSsize_t(count);
- }
+ else if (PyUnicode_Check(sub_obj)) {
+ Py_ssize_t count;
+ count = PyUnicode_Count((PyObject *)self, sub_obj, start, end);
+ if (count == -1)
+ return NULL;
+ else
+ return PyInt_FromSsize_t(count);
+ }
#endif
- else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
- return NULL;
+ else if (PyObject_AsCharBuffer(sub_obj, &sub, &sub_len))
+ return NULL;
- ADJUST_INDICES(start, end, PyString_GET_SIZE(self));
+ ADJUST_INDICES(start, end, PyString_GET_SIZE(self));
- return PyInt_FromSsize_t(
- stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
- );
+ return PyInt_FromSsize_t(
+ stringlib_count(str + start, end - start, sub, sub_len, PY_SSIZE_T_MAX)
+ );
}
PyDoc_STRVAR(swapcase__doc__,
@@ -2158,27 +2158,27 @@ converted to lowercase and vice versa.");
static PyObject *
string_swapcase(PyStringObject *self)
{
- char *s = PyString_AS_STRING(self), *s_new;
- Py_ssize_t i, n = PyString_GET_SIZE(self);
- PyObject *newobj;
-
- newobj = PyString_FromStringAndSize(NULL, n);
- if (newobj == NULL)
- return NULL;
- s_new = PyString_AsString(newobj);
- for (i = 0; i < n; i++) {
- int c = Py_CHARMASK(*s++);
- if (islower(c)) {
- *s_new = toupper(c);
- }
- else if (isupper(c)) {
- *s_new = tolower(c);
- }
- else
- *s_new = c;
- s_new++;
- }
- return newobj;
+ char *s = PyString_AS_STRING(self), *s_new;
+ Py_ssize_t i, n = PyString_GET_SIZE(self);
+ PyObject *newobj;
+
+ newobj = PyString_FromStringAndSize(NULL, n);
+ if (newobj == NULL)
+ return NULL;
+ s_new = PyString_AsString(newobj);
+ for (i = 0; i < n; i++) {
+ int c = Py_CHARMASK(*s++);
+ if (islower(c)) {
+ *s_new = toupper(c);
+ }
+ else if (isupper(c)) {
+ *s_new = tolower(c);
+ }
+ else
+ *s_new = c;
+ s_new++;
+ }
+ return newobj;
}
@@ -2193,124 +2193,124 @@ translation table, which must be a string of length 256.");
static PyObject *
string_translate(PyStringObject *self, PyObject *args)
{
- register char *input, *output;
- const char *table;
- register Py_ssize_t i, c, changed = 0;
- PyObject *input_obj = (PyObject*)self;
- const char *output_start, *del_table=NULL;
- Py_ssize_t inlen, tablen, dellen = 0;
- PyObject *result;
- int trans_table[256];
- PyObject *tableobj, *delobj = NULL;
-
- if (!PyArg_UnpackTuple(args, "translate", 1, 2,
- &tableobj, &delobj))
- return NULL;
-
- if (PyString_Check(tableobj)) {
- table = PyString_AS_STRING(tableobj);
- tablen = PyString_GET_SIZE(tableobj);
- }
- else if (tableobj == Py_None) {
- table = NULL;
- tablen = 256;
- }
+ register char *input, *output;
+ const char *table;
+ register Py_ssize_t i, c, changed = 0;
+ PyObject *input_obj = (PyObject*)self;
+ const char *output_start, *del_table=NULL;
+ Py_ssize_t inlen, tablen, dellen = 0;
+ PyObject *result;
+ int trans_table[256];
+ PyObject *tableobj, *delobj = NULL;
+
+ if (!PyArg_UnpackTuple(args, "translate", 1, 2,
+ &tableobj, &delobj))
+ return NULL;
+
+ if (PyString_Check(tableobj)) {
+ table = PyString_AS_STRING(tableobj);
+ tablen = PyString_GET_SIZE(tableobj);
+ }
+ else if (tableobj == Py_None) {
+ table = NULL;
+ tablen = 256;
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(tableobj)) {
- /* Unicode .translate() does not support the deletechars
- parameter; instead a mapping to None will cause characters
- to be deleted. */
- if (delobj != NULL) {
- PyErr_SetString(PyExc_TypeError,
- "deletions are implemented differently for unicode");
- return NULL;
- }
- return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
- }
+ else if (PyUnicode_Check(tableobj)) {
+ /* Unicode .translate() does not support the deletechars
+ parameter; instead a mapping to None will cause characters
+ to be deleted. */
+ if (delobj != NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "deletions are implemented differently for unicode");
+ return NULL;
+ }
+ return PyUnicode_Translate((PyObject *)self, tableobj, NULL);
+ }
#endif
- else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
- return NULL;
-
- if (tablen != 256) {
- PyErr_SetString(PyExc_ValueError,
- "translation table must be 256 characters long");
- return NULL;
- }
-
- if (delobj != NULL) {
- if (PyString_Check(delobj)) {
- del_table = PyString_AS_STRING(delobj);
- dellen = PyString_GET_SIZE(delobj);
- }
+ else if (PyObject_AsCharBuffer(tableobj, &table, &tablen))
+ return NULL;
+
+ if (tablen != 256) {
+ PyErr_SetString(PyExc_ValueError,
+ "translation table must be 256 characters long");
+ return NULL;
+ }
+
+ if (delobj != NULL) {
+ if (PyString_Check(delobj)) {
+ del_table = PyString_AS_STRING(delobj);
+ dellen = PyString_GET_SIZE(delobj);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(delobj)) {
- PyErr_SetString(PyExc_TypeError,
- "deletions are implemented differently for unicode");
- return NULL;
- }
+ else if (PyUnicode_Check(delobj)) {
+ PyErr_SetString(PyExc_TypeError,
+ "deletions are implemented differently for unicode");
+ return NULL;
+ }
#endif
- else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
- return NULL;
- }
- else {
- del_table = NULL;
- dellen = 0;
- }
-
- inlen = PyString_GET_SIZE(input_obj);
- result = PyString_FromStringAndSize((char *)NULL, inlen);
- if (result == NULL)
- return NULL;
- output_start = output = PyString_AsString(result);
- input = PyString_AS_STRING(input_obj);
-
- if (dellen == 0 && table != NULL) {
- /* If no deletions are required, use faster code */
- for (i = inlen; --i >= 0; ) {
- c = Py_CHARMASK(*input++);
- if (Py_CHARMASK((*output++ = table[c])) != c)
- changed = 1;
- }
- if (changed || !PyString_CheckExact(input_obj))
- return result;
- Py_DECREF(result);
- Py_INCREF(input_obj);
- return input_obj;
- }
-
- if (table == NULL) {
- for (i = 0; i < 256; i++)
- trans_table[i] = Py_CHARMASK(i);
- } else {
- for (i = 0; i < 256; i++)
- trans_table[i] = Py_CHARMASK(table[i]);
- }
-
- for (i = 0; i < dellen; i++)
- trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
-
- for (i = inlen; --i >= 0; ) {
- c = Py_CHARMASK(*input++);
- if (trans_table[c] != -1)
- if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
- continue;
- changed = 1;
- }
- if (!changed && PyString_CheckExact(input_obj)) {
- Py_DECREF(result);
- Py_INCREF(input_obj);
- return input_obj;
- }
- /* Fix the size of the resulting string */
- if (inlen > 0 && _PyString_Resize(&result, output - output_start))
- return NULL;
- return result;
+ else if (PyObject_AsCharBuffer(delobj, &del_table, &dellen))
+ return NULL;
+ }
+ else {
+ del_table = NULL;
+ dellen = 0;
+ }
+
+ inlen = PyString_GET_SIZE(input_obj);
+ result = PyString_FromStringAndSize((char *)NULL, inlen);
+ if (result == NULL)
+ return NULL;
+ output_start = output = PyString_AsString(result);
+ input = PyString_AS_STRING(input_obj);
+
+ if (dellen == 0 && table != NULL) {
+ /* If no deletions are required, use faster code */
+ for (i = inlen; --i >= 0; ) {
+ c = Py_CHARMASK(*input++);
+ if (Py_CHARMASK((*output++ = table[c])) != c)
+ changed = 1;
+ }
+ if (changed || !PyString_CheckExact(input_obj))
+ return result;
+ Py_DECREF(result);
+ Py_INCREF(input_obj);
+ return input_obj;
+ }
+
+ if (table == NULL) {
+ for (i = 0; i < 256; i++)
+ trans_table[i] = Py_CHARMASK(i);
+ } else {
+ for (i = 0; i < 256; i++)
+ trans_table[i] = Py_CHARMASK(table[i]);
+ }
+
+ for (i = 0; i < dellen; i++)
+ trans_table[(int) Py_CHARMASK(del_table[i])] = -1;
+
+ for (i = inlen; --i >= 0; ) {
+ c = Py_CHARMASK(*input++);
+ if (trans_table[c] != -1)
+ if (Py_CHARMASK(*output++ = (char)trans_table[c]) == c)
+ continue;
+ changed = 1;
+ }
+ if (!changed && PyString_CheckExact(input_obj)) {
+ Py_DECREF(result);
+ Py_INCREF(input_obj);
+ return input_obj;
+ }
+ /* Fix the size of the resulting string */
+ if (inlen > 0 && _PyString_Resize(&result, output - output_start))
+ return NULL;
+ return result;
}
/* find and count characters and substrings */
-#define findchar(target, target_len, c) \
+#define findchar(target, target_len, c) \
((char *)memchr((const void *)(target), c, target_len))
/* String ops must return a string. */
@@ -2318,29 +2318,29 @@ string_translate(PyStringObject *self, PyObject *args)
Py_LOCAL(PyStringObject *)
return_self(PyStringObject *self)
{
- if (PyString_CheckExact(self)) {
- Py_INCREF(self);
- return self;
- }
- return (PyStringObject *)PyString_FromStringAndSize(
- PyString_AS_STRING(self),
- PyString_GET_SIZE(self));
+ if (PyString_CheckExact(self)) {
+ Py_INCREF(self);
+ return self;
+ }
+ return (PyStringObject *)PyString_FromStringAndSize(
+ PyString_AS_STRING(self),
+ PyString_GET_SIZE(self));
}
Py_LOCAL_INLINE(Py_ssize_t)
countchar(const char *target, int target_len, char c, Py_ssize_t maxcount)
{
- Py_ssize_t count=0;
- const char *start=target;
- const char *end=target+target_len;
-
- while ( (start=findchar(start, end-start, c)) != NULL ) {
- count++;
- if (count >= maxcount)
- break;
- start += 1;
- }
- return count;
+ Py_ssize_t count=0;
+ const char *start=target;
+ const char *end=target+target_len;
+
+ while ( (start=findchar(start, end-start, c)) != NULL ) {
+ count++;
+ if (count >= maxcount)
+ break;
+ start += 1;
+ }
+ return count;
}
@@ -2349,460 +2349,460 @@ countchar(const char *target, int target_len, char c, Py_ssize_t maxcount)
/* len(self)>=1, from="", len(to)>=1, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_interleave(PyStringObject *self,
- const char *to_s, Py_ssize_t to_len,
- Py_ssize_t maxcount)
+ const char *to_s, Py_ssize_t to_len,
+ Py_ssize_t maxcount)
{
- char *self_s, *result_s;
- Py_ssize_t self_len, result_len;
- Py_ssize_t count, i, product;
- PyStringObject *result;
-
- self_len = PyString_GET_SIZE(self);
-
- /* 1 at the end plus 1 after every character */
- count = self_len+1;
- if (maxcount < count)
- count = maxcount;
-
- /* Check for overflow */
- /* result_len = count * to_len + self_len; */
- product = count * to_len;
- if (product / to_len != count) {
- PyErr_SetString(PyExc_OverflowError,
- "replace string is too long");
- return NULL;
- }
- result_len = product + self_len;
- if (result_len < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "replace string is too long");
- return NULL;
- }
-
- if (! (result = (PyStringObject *)
- PyString_FromStringAndSize(NULL, result_len)) )
- return NULL;
-
- self_s = PyString_AS_STRING(self);
- result_s = PyString_AS_STRING(result);
-
- /* TODO: special case single character, which doesn't need memcpy */
-
- /* Lay the first one down (guaranteed this will occur) */
- Py_MEMCPY(result_s, to_s, to_len);
- result_s += to_len;
- count -= 1;
-
- for (i=0; i<count; i++) {
- *result_s++ = *self_s++;
- Py_MEMCPY(result_s, to_s, to_len);
- result_s += to_len;
- }
-
- /* Copy the rest of the original string */
- Py_MEMCPY(result_s, self_s, self_len-i);
-
- return result;
+ char *self_s, *result_s;
+ Py_ssize_t self_len, result_len;
+ Py_ssize_t count, i, product;
+ PyStringObject *result;
+
+ self_len = PyString_GET_SIZE(self);
+
+ /* 1 at the end plus 1 after every character */
+ count = self_len+1;
+ if (maxcount < count)
+ count = maxcount;
+
+ /* Check for overflow */
+ /* result_len = count * to_len + self_len; */
+ product = count * to_len;
+ if (product / to_len != count) {
+ PyErr_SetString(PyExc_OverflowError,
+ "replace string is too long");
+ return NULL;
+ }
+ result_len = product + self_len;
+ if (result_len < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "replace string is too long");
+ return NULL;
+ }
+
+ if (! (result = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, result_len)) )
+ return NULL;
+
+ self_s = PyString_AS_STRING(self);
+ result_s = PyString_AS_STRING(result);
+
+ /* TODO: special case single character, which doesn't need memcpy */
+
+ /* Lay the first one down (guaranteed this will occur) */
+ Py_MEMCPY(result_s, to_s, to_len);
+ result_s += to_len;
+ count -= 1;
+
+ for (i=0; i<count; i++) {
+ *result_s++ = *self_s++;
+ Py_MEMCPY(result_s, to_s, to_len);
+ result_s += to_len;
+ }
+
+ /* Copy the rest of the original string */
+ Py_MEMCPY(result_s, self_s, self_len-i);
+
+ return result;
}
/* Special case for deleting a single character */
/* len(self)>=1, len(from)==1, to="", maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_delete_single_character(PyStringObject *self,
- char from_c, Py_ssize_t maxcount)
+ char from_c, Py_ssize_t maxcount)
{
- char *self_s, *result_s;
- char *start, *next, *end;
- Py_ssize_t self_len, result_len;
- Py_ssize_t count;
- PyStringObject *result;
-
- self_len = PyString_GET_SIZE(self);
- self_s = PyString_AS_STRING(self);
-
- count = countchar(self_s, self_len, from_c, maxcount);
- if (count == 0) {
- return return_self(self);
- }
-
- result_len = self_len - count; /* from_len == 1 */
- assert(result_len>=0);
-
- if ( (result = (PyStringObject *)
- PyString_FromStringAndSize(NULL, result_len)) == NULL)
- return NULL;
- result_s = PyString_AS_STRING(result);
-
- start = self_s;
- end = self_s + self_len;
- while (count-- > 0) {
- next = findchar(start, end-start, from_c);
- if (next == NULL)
- break;
- Py_MEMCPY(result_s, start, next-start);
- result_s += (next-start);
- start = next+1;
- }
- Py_MEMCPY(result_s, start, end-start);
-
- return result;
+ char *self_s, *result_s;
+ char *start, *next, *end;
+ Py_ssize_t self_len, result_len;
+ Py_ssize_t count;
+ PyStringObject *result;
+
+ self_len = PyString_GET_SIZE(self);
+ self_s = PyString_AS_STRING(self);
+
+ count = countchar(self_s, self_len, from_c, maxcount);
+ if (count == 0) {
+ return return_self(self);
+ }
+
+ result_len = self_len - count; /* from_len == 1 */
+ assert(result_len>=0);
+
+ if ( (result = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, result_len)) == NULL)
+ return NULL;
+ result_s = PyString_AS_STRING(result);
+
+ start = self_s;
+ end = self_s + self_len;
+ while (count-- > 0) {
+ next = findchar(start, end-start, from_c);
+ if (next == NULL)
+ break;
+ Py_MEMCPY(result_s, start, next-start);
+ result_s += (next-start);
+ start = next+1;
+ }
+ Py_MEMCPY(result_s, start, end-start);
+
+ return result;
}
/* len(self)>=1, len(from)>=2, to="", maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_delete_substring(PyStringObject *self,
- const char *from_s, Py_ssize_t from_len,
- Py_ssize_t maxcount) {
- char *self_s, *result_s;
- char *start, *next, *end;
- Py_ssize_t self_len, result_len;
- Py_ssize_t count, offset;
- PyStringObject *result;
-
- self_len = PyString_GET_SIZE(self);
- self_s = PyString_AS_STRING(self);
-
- count = stringlib_count(self_s, self_len,
- from_s, from_len,
- maxcount);
-
- if (count == 0) {
- /* no matches */
- return return_self(self);
- }
-
- result_len = self_len - (count * from_len);
- assert (result_len>=0);
-
- if ( (result = (PyStringObject *)
- PyString_FromStringAndSize(NULL, result_len)) == NULL )
- return NULL;
-
- result_s = PyString_AS_STRING(result);
-
- start = self_s;
- end = self_s + self_len;
- while (count-- > 0) {
- offset = stringlib_find(start, end-start,
- from_s, from_len,
- 0);
- if (offset == -1)
- break;
- next = start + offset;
-
- Py_MEMCPY(result_s, start, next-start);
-
- result_s += (next-start);
- start = next+from_len;
- }
- Py_MEMCPY(result_s, start, end-start);
- return result;
+ const char *from_s, Py_ssize_t from_len,
+ Py_ssize_t maxcount) {
+ char *self_s, *result_s;
+ char *start, *next, *end;
+ Py_ssize_t self_len, result_len;
+ Py_ssize_t count, offset;
+ PyStringObject *result;
+
+ self_len = PyString_GET_SIZE(self);
+ self_s = PyString_AS_STRING(self);
+
+ count = stringlib_count(self_s, self_len,
+ from_s, from_len,
+ maxcount);
+
+ if (count == 0) {
+ /* no matches */
+ return return_self(self);
+ }
+
+ result_len = self_len - (count * from_len);
+ assert (result_len>=0);
+
+ if ( (result = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, result_len)) == NULL )
+ return NULL;
+
+ result_s = PyString_AS_STRING(result);
+
+ start = self_s;
+ end = self_s + self_len;
+ while (count-- > 0) {
+ offset = stringlib_find(start, end-start,
+ from_s, from_len,
+ 0);
+ if (offset == -1)
+ break;
+ next = start + offset;
+
+ Py_MEMCPY(result_s, start, next-start);
+
+ result_s += (next-start);
+ start = next+from_len;
+ }
+ Py_MEMCPY(result_s, start, end-start);
+ return result;
}
/* len(self)>=1, len(from)==len(to)==1, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_single_character_in_place(PyStringObject *self,
- char from_c, char to_c,
- Py_ssize_t maxcount)
+ char from_c, char to_c,
+ Py_ssize_t maxcount)
{
- char *self_s, *result_s, *start, *end, *next;
- Py_ssize_t self_len;
- PyStringObject *result;
-
- /* The result string will be the same size */
- self_s = PyString_AS_STRING(self);
- self_len = PyString_GET_SIZE(self);
-
- next = findchar(self_s, self_len, from_c);
-
- if (next == NULL) {
- /* No matches; return the original string */
- return return_self(self);
- }
-
- /* Need to make a new string */
- result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
- if (result == NULL)
- return NULL;
- result_s = PyString_AS_STRING(result);
- Py_MEMCPY(result_s, self_s, self_len);
-
- /* change everything in-place, starting with this one */
- start = result_s + (next-self_s);
- *start = to_c;
- start++;
- end = result_s + self_len;
-
- while (--maxcount > 0) {
- next = findchar(start, end-start, from_c);
- if (next == NULL)
- break;
- *next = to_c;
- start = next+1;
- }
-
- return result;
+ char *self_s, *result_s, *start, *end, *next;
+ Py_ssize_t self_len;
+ PyStringObject *result;
+
+ /* The result string will be the same size */
+ self_s = PyString_AS_STRING(self);
+ self_len = PyString_GET_SIZE(self);
+
+ next = findchar(self_s, self_len, from_c);
+
+ if (next == NULL) {
+ /* No matches; return the original string */
+ return return_self(self);
+ }
+
+ /* Need to make a new string */
+ result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
+ if (result == NULL)
+ return NULL;
+ result_s = PyString_AS_STRING(result);
+ Py_MEMCPY(result_s, self_s, self_len);
+
+ /* change everything in-place, starting with this one */
+ start = result_s + (next-self_s);
+ *start = to_c;
+ start++;
+ end = result_s + self_len;
+
+ while (--maxcount > 0) {
+ next = findchar(start, end-start, from_c);
+ if (next == NULL)
+ break;
+ *next = to_c;
+ start = next+1;
+ }
+
+ return result;
}
/* len(self)>=1, len(from)==len(to)>=2, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_substring_in_place(PyStringObject *self,
- const char *from_s, Py_ssize_t from_len,
- const char *to_s, Py_ssize_t to_len,
- Py_ssize_t maxcount)
+ const char *from_s, Py_ssize_t from_len,
+ const char *to_s, Py_ssize_t to_len,
+ Py_ssize_t maxcount)
{
- char *result_s, *start, *end;
- char *self_s;
- Py_ssize_t self_len, offset;
- PyStringObject *result;
-
- /* The result string will be the same size */
-
- self_s = PyString_AS_STRING(self);
- self_len = PyString_GET_SIZE(self);
-
- offset = stringlib_find(self_s, self_len,
- from_s, from_len,
- 0);
- if (offset == -1) {
- /* No matches; return the original string */
- return return_self(self);
- }
-
- /* Need to make a new string */
- result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
- if (result == NULL)
- return NULL;
- result_s = PyString_AS_STRING(result);
- Py_MEMCPY(result_s, self_s, self_len);
-
- /* change everything in-place, starting with this one */
- start = result_s + offset;
- Py_MEMCPY(start, to_s, from_len);
- start += from_len;
- end = result_s + self_len;
-
- while ( --maxcount > 0) {
- offset = stringlib_find(start, end-start,
- from_s, from_len,
- 0);
- if (offset==-1)
- break;
- Py_MEMCPY(start+offset, to_s, from_len);
- start += offset+from_len;
- }
-
- return result;
+ char *result_s, *start, *end;
+ char *self_s;
+ Py_ssize_t self_len, offset;
+ PyStringObject *result;
+
+ /* The result string will be the same size */
+
+ self_s = PyString_AS_STRING(self);
+ self_len = PyString_GET_SIZE(self);
+
+ offset = stringlib_find(self_s, self_len,
+ from_s, from_len,
+ 0);
+ if (offset == -1) {
+ /* No matches; return the original string */
+ return return_self(self);
+ }
+
+ /* Need to make a new string */
+ result = (PyStringObject *) PyString_FromStringAndSize(NULL, self_len);
+ if (result == NULL)
+ return NULL;
+ result_s = PyString_AS_STRING(result);
+ Py_MEMCPY(result_s, self_s, self_len);
+
+ /* change everything in-place, starting with this one */
+ start = result_s + offset;
+ Py_MEMCPY(start, to_s, from_len);
+ start += from_len;
+ end = result_s + self_len;
+
+ while ( --maxcount > 0) {
+ offset = stringlib_find(start, end-start,
+ from_s, from_len,
+ 0);
+ if (offset==-1)
+ break;
+ Py_MEMCPY(start+offset, to_s, from_len);
+ start += offset+from_len;
+ }
+
+ return result;
}
/* len(self)>=1, len(from)==1, len(to)>=2, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_single_character(PyStringObject *self,
- char from_c,
- const char *to_s, Py_ssize_t to_len,
- Py_ssize_t maxcount)
+ char from_c,
+ const char *to_s, Py_ssize_t to_len,
+ Py_ssize_t maxcount)
{
- char *self_s, *result_s;
- char *start, *next, *end;
- Py_ssize_t self_len, result_len;
- Py_ssize_t count, product;
- PyStringObject *result;
-
- self_s = PyString_AS_STRING(self);
- self_len = PyString_GET_SIZE(self);
-
- count = countchar(self_s, self_len, from_c, maxcount);
- if (count == 0) {
- /* no matches, return unchanged */
- return return_self(self);
- }
-
- /* use the difference between current and new, hence the "-1" */
- /* result_len = self_len + count * (to_len-1) */
- product = count * (to_len-1);
- if (product / (to_len-1) != count) {
- PyErr_SetString(PyExc_OverflowError, "replace string is too long");
- return NULL;
- }
- result_len = self_len + product;
- if (result_len < 0) {
- PyErr_SetString(PyExc_OverflowError, "replace string is too long");
- return NULL;
- }
-
- if ( (result = (PyStringObject *)
- PyString_FromStringAndSize(NULL, result_len)) == NULL)
- return NULL;
- result_s = PyString_AS_STRING(result);
-
- start = self_s;
- end = self_s + self_len;
- while (count-- > 0) {
- next = findchar(start, end-start, from_c);
- if (next == NULL)
- break;
-
- if (next == start) {
- /* replace with the 'to' */
- Py_MEMCPY(result_s, to_s, to_len);
- result_s += to_len;
- start += 1;
- } else {
- /* copy the unchanged old then the 'to' */
- Py_MEMCPY(result_s, start, next-start);
- result_s += (next-start);
- Py_MEMCPY(result_s, to_s, to_len);
- result_s += to_len;
- start = next+1;
- }
- }
- /* Copy the remainder of the remaining string */
- Py_MEMCPY(result_s, start, end-start);
-
- return result;
+ char *self_s, *result_s;
+ char *start, *next, *end;
+ Py_ssize_t self_len, result_len;
+ Py_ssize_t count, product;
+ PyStringObject *result;
+
+ self_s = PyString_AS_STRING(self);
+ self_len = PyString_GET_SIZE(self);
+
+ count = countchar(self_s, self_len, from_c, maxcount);
+ if (count == 0) {
+ /* no matches, return unchanged */
+ return return_self(self);
+ }
+
+ /* use the difference between current and new, hence the "-1" */
+ /* result_len = self_len + count * (to_len-1) */
+ product = count * (to_len-1);
+ if (product / (to_len-1) != count) {
+ PyErr_SetString(PyExc_OverflowError, "replace string is too long");
+ return NULL;
+ }
+ result_len = self_len + product;
+ if (result_len < 0) {
+ PyErr_SetString(PyExc_OverflowError, "replace string is too long");
+ return NULL;
+ }
+
+ if ( (result = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, result_len)) == NULL)
+ return NULL;
+ result_s = PyString_AS_STRING(result);
+
+ start = self_s;
+ end = self_s + self_len;
+ while (count-- > 0) {
+ next = findchar(start, end-start, from_c);
+ if (next == NULL)
+ break;
+
+ if (next == start) {
+ /* replace with the 'to' */
+ Py_MEMCPY(result_s, to_s, to_len);
+ result_s += to_len;
+ start += 1;
+ } else {
+ /* copy the unchanged old then the 'to' */
+ Py_MEMCPY(result_s, start, next-start);
+ result_s += (next-start);
+ Py_MEMCPY(result_s, to_s, to_len);
+ result_s += to_len;
+ start = next+1;
+ }
+ }
+ /* Copy the remainder of the remaining string */
+ Py_MEMCPY(result_s, start, end-start);
+
+ return result;
}
/* len(self)>=1, len(from)>=2, len(to)>=2, maxcount>=1 */
Py_LOCAL(PyStringObject *)
replace_substring(PyStringObject *self,
- const char *from_s, Py_ssize_t from_len,
- const char *to_s, Py_ssize_t to_len,
- Py_ssize_t maxcount) {
- char *self_s, *result_s;
- char *start, *next, *end;
- Py_ssize_t self_len, result_len;
- Py_ssize_t count, offset, product;
- PyStringObject *result;
-
- self_s = PyString_AS_STRING(self);
- self_len = PyString_GET_SIZE(self);
-
- count = stringlib_count(self_s, self_len,
- from_s, from_len,
- maxcount);
-
- if (count == 0) {
- /* no matches, return unchanged */
- return return_self(self);
- }
-
- /* Check for overflow */
- /* result_len = self_len + count * (to_len-from_len) */
- product = count * (to_len-from_len);
- if (product / (to_len-from_len) != count) {
- PyErr_SetString(PyExc_OverflowError, "replace string is too long");
- return NULL;
- }
- result_len = self_len + product;
- if (result_len < 0) {
- PyErr_SetString(PyExc_OverflowError, "replace string is too long");
- return NULL;
- }
-
- if ( (result = (PyStringObject *)
- PyString_FromStringAndSize(NULL, result_len)) == NULL)
- return NULL;
- result_s = PyString_AS_STRING(result);
-
- start = self_s;
- end = self_s + self_len;
- while (count-- > 0) {
- offset = stringlib_find(start, end-start,
- from_s, from_len,
- 0);
- if (offset == -1)
- break;
- next = start+offset;
- if (next == start) {
- /* replace with the 'to' */
- Py_MEMCPY(result_s, to_s, to_len);
- result_s += to_len;
- start += from_len;
- } else {
- /* copy the unchanged old then the 'to' */
- Py_MEMCPY(result_s, start, next-start);
- result_s += (next-start);
- Py_MEMCPY(result_s, to_s, to_len);
- result_s += to_len;
- start = next+from_len;
- }
- }
- /* Copy the remainder of the remaining string */
- Py_MEMCPY(result_s, start, end-start);
-
- return result;
+ const char *from_s, Py_ssize_t from_len,
+ const char *to_s, Py_ssize_t to_len,
+ Py_ssize_t maxcount) {
+ char *self_s, *result_s;
+ char *start, *next, *end;
+ Py_ssize_t self_len, result_len;
+ Py_ssize_t count, offset, product;
+ PyStringObject *result;
+
+ self_s = PyString_AS_STRING(self);
+ self_len = PyString_GET_SIZE(self);
+
+ count = stringlib_count(self_s, self_len,
+ from_s, from_len,
+ maxcount);
+
+ if (count == 0) {
+ /* no matches, return unchanged */
+ return return_self(self);
+ }
+
+ /* Check for overflow */
+ /* result_len = self_len + count * (to_len-from_len) */
+ product = count * (to_len-from_len);
+ if (product / (to_len-from_len) != count) {
+ PyErr_SetString(PyExc_OverflowError, "replace string is too long");
+ return NULL;
+ }
+ result_len = self_len + product;
+ if (result_len < 0) {
+ PyErr_SetString(PyExc_OverflowError, "replace string is too long");
+ return NULL;
+ }
+
+ if ( (result = (PyStringObject *)
+ PyString_FromStringAndSize(NULL, result_len)) == NULL)
+ return NULL;
+ result_s = PyString_AS_STRING(result);
+
+ start = self_s;
+ end = self_s + self_len;
+ while (count-- > 0) {
+ offset = stringlib_find(start, end-start,
+ from_s, from_len,
+ 0);
+ if (offset == -1)
+ break;
+ next = start+offset;
+ if (next == start) {
+ /* replace with the 'to' */
+ Py_MEMCPY(result_s, to_s, to_len);
+ result_s += to_len;
+ start += from_len;
+ } else {
+ /* copy the unchanged old then the 'to' */
+ Py_MEMCPY(result_s, start, next-start);
+ result_s += (next-start);
+ Py_MEMCPY(result_s, to_s, to_len);
+ result_s += to_len;
+ start = next+from_len;
+ }
+ }
+ /* Copy the remainder of the remaining string */
+ Py_MEMCPY(result_s, start, end-start);
+
+ return result;
}
Py_LOCAL(PyStringObject *)
replace(PyStringObject *self,
- const char *from_s, Py_ssize_t from_len,
- const char *to_s, Py_ssize_t to_len,
- Py_ssize_t maxcount)
+ const char *from_s, Py_ssize_t from_len,
+ const char *to_s, Py_ssize_t to_len,
+ Py_ssize_t maxcount)
{
- if (maxcount < 0) {
- maxcount = PY_SSIZE_T_MAX;
- } else if (maxcount == 0 || PyString_GET_SIZE(self) == 0) {
- /* nothing to do; return the original string */
- return return_self(self);
- }
-
- if (maxcount == 0 ||
- (from_len == 0 && to_len == 0)) {
- /* nothing to do; return the original string */
- return return_self(self);
- }
-
- /* Handle zero-length special cases */
-
- if (from_len == 0) {
- /* insert the 'to' string everywhere. */
- /* >>> "Python".replace("", ".") */
- /* '.P.y.t.h.o.n.' */
- return replace_interleave(self, to_s, to_len, maxcount);
- }
-
- /* Except for "".replace("", "A") == "A" there is no way beyond this */
- /* point for an empty self string to generate a non-empty string */
- /* Special case so the remaining code always gets a non-empty string */
- if (PyString_GET_SIZE(self) == 0) {
- return return_self(self);
- }
-
- if (to_len == 0) {
- /* delete all occurances of 'from' string */
- if (from_len == 1) {
- return replace_delete_single_character(
- self, from_s[0], maxcount);
- } else {
- return replace_delete_substring(self, from_s, from_len, maxcount);
- }
- }
-
- /* Handle special case where both strings have the same length */
-
- if (from_len == to_len) {
- if (from_len == 1) {
- return replace_single_character_in_place(
- self,
- from_s[0],
- to_s[0],
- maxcount);
- } else {
- return replace_substring_in_place(
- self, from_s, from_len, to_s, to_len, maxcount);
- }
- }
-
- /* Otherwise use the more generic algorithms */
- if (from_len == 1) {
- return replace_single_character(self, from_s[0],
- to_s, to_len, maxcount);
- } else {
- /* len('from')>=2, len('to')>=1 */
- return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
- }
+ if (maxcount < 0) {
+ maxcount = PY_SSIZE_T_MAX;
+ } else if (maxcount == 0 || PyString_GET_SIZE(self) == 0) {
+ /* nothing to do; return the original string */
+ return return_self(self);
+ }
+
+ if (maxcount == 0 ||
+ (from_len == 0 && to_len == 0)) {
+ /* nothing to do; return the original string */
+ return return_self(self);
+ }
+
+ /* Handle zero-length special cases */
+
+ if (from_len == 0) {
+ /* insert the 'to' string everywhere. */
+ /* >>> "Python".replace("", ".") */
+ /* '.P.y.t.h.o.n.' */
+ return replace_interleave(self, to_s, to_len, maxcount);
+ }
+
+ /* Except for "".replace("", "A") == "A" there is no way beyond this */
+ /* point for an empty self string to generate a non-empty string */
+ /* Special case so the remaining code always gets a non-empty string */
+ if (PyString_GET_SIZE(self) == 0) {
+ return return_self(self);
+ }
+
+ if (to_len == 0) {
+ /* delete all occurances of 'from' string */
+ if (from_len == 1) {
+ return replace_delete_single_character(
+ self, from_s[0], maxcount);
+ } else {
+ return replace_delete_substring(self, from_s, from_len, maxcount);
+ }
+ }
+
+ /* Handle special case where both strings have the same length */
+
+ if (from_len == to_len) {
+ if (from_len == 1) {
+ return replace_single_character_in_place(
+ self,
+ from_s[0],
+ to_s[0],
+ maxcount);
+ } else {
+ return replace_substring_in_place(
+ self, from_s, from_len, to_s, to_len, maxcount);
+ }
+ }
+
+ /* Otherwise use the more generic algorithms */
+ if (from_len == 1) {
+ return replace_single_character(self, from_s[0],
+ to_s, to_len, maxcount);
+ } else {
+ /* len('from')>=2, len('to')>=1 */
+ return replace_substring(self, from_s, from_len, to_s, to_len, maxcount);
+ }
}
PyDoc_STRVAR(replace__doc__,
@@ -2815,41 +2815,41 @@ given, only the first count occurrences are replaced.");
static PyObject *
string_replace(PyStringObject *self, PyObject *args)
{
- Py_ssize_t count = -1;
- PyObject *from, *to;
- const char *from_s, *to_s;
- Py_ssize_t from_len, to_len;
-
- if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
- return NULL;
-
- if (PyString_Check(from)) {
- from_s = PyString_AS_STRING(from);
- from_len = PyString_GET_SIZE(from);
- }
+ Py_ssize_t count = -1;
+ PyObject *from, *to;
+ const char *from_s, *to_s;
+ Py_ssize_t from_len, to_len;
+
+ if (!PyArg_ParseTuple(args, "OO|n:replace", &from, &to, &count))
+ return NULL;
+
+ if (PyString_Check(from)) {
+ from_s = PyString_AS_STRING(from);
+ from_len = PyString_GET_SIZE(from);
+ }
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(from))
- return PyUnicode_Replace((PyObject *)self,
- from, to, count);
+ if (PyUnicode_Check(from))
+ return PyUnicode_Replace((PyObject *)self,
+ from, to, count);
#endif
- else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
- return NULL;
+ else if (PyObject_AsCharBuffer(from, &from_s, &from_len))
+ return NULL;
- if (PyString_Check(to)) {
- to_s = PyString_AS_STRING(to);
- to_len = PyString_GET_SIZE(to);
- }
+ if (PyString_Check(to)) {
+ to_s = PyString_AS_STRING(to);
+ to_len = PyString_GET_SIZE(to);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(to))
- return PyUnicode_Replace((PyObject *)self,
- from, to, count);
+ else if (PyUnicode_Check(to))
+ return PyUnicode_Replace((PyObject *)self,
+ from, to, count);
#endif
- else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
- return NULL;
+ else if (PyObject_AsCharBuffer(to, &to_s, &to_len))
+ return NULL;
- return (PyObject *)replace((PyStringObject *) self,
- from_s, from_len,
- to_s, to_len, count);
+ return (PyObject *)replace((PyStringObject *) self,
+ from_s, from_len,
+ to_s, to_len, count);
}
/** End DALKE **/
@@ -2860,43 +2860,43 @@ string_replace(PyStringObject *self, PyObject *args)
*/
Py_LOCAL(int)
_string_tailmatch(PyStringObject *self, PyObject *substr, Py_ssize_t start,
- Py_ssize_t end, int direction)
+ Py_ssize_t end, int direction)
{
- Py_ssize_t len = PyString_GET_SIZE(self);
- Py_ssize_t slen;
- const char* sub;
- const char* str;
-
- if (PyString_Check(substr)) {
- sub = PyString_AS_STRING(substr);
- slen = PyString_GET_SIZE(substr);
- }
+ Py_ssize_t len = PyString_GET_SIZE(self);
+ Py_ssize_t slen;
+ const char* sub;
+ const char* str;
+
+ if (PyString_Check(substr)) {
+ sub = PyString_AS_STRING(substr);
+ slen = PyString_GET_SIZE(substr);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(substr))
- return PyUnicode_Tailmatch((PyObject *)self,
- substr, start, end, direction);
+ else if (PyUnicode_Check(substr))
+ return PyUnicode_Tailmatch((PyObject *)self,
+ substr, start, end, direction);
#endif
- else if (PyObject_AsCharBuffer(substr, &sub, &slen))
- return -1;
- str = PyString_AS_STRING(self);
-
- ADJUST_INDICES(start, end, len);
-
- if (direction < 0) {
- /* startswith */
- if (start+slen > len)
- return 0;
- } else {
- /* endswith */
- if (end-start < slen || start > len)
- return 0;
-
- if (end-slen > start)
- start = end - slen;
- }
- if (end-start >= slen)
- return ! memcmp(str+start, sub, slen);
- return 0;
+ else if (PyObject_AsCharBuffer(substr, &sub, &slen))
+ return -1;
+ str = PyString_AS_STRING(self);
+
+ ADJUST_INDICES(start, end, len);
+
+ if (direction < 0) {
+ /* startswith */
+ if (start+slen > len)
+ return 0;
+ } else {
+ /* endswith */
+ if (end-start < slen || start > len)
+ return 0;
+
+ if (end-slen > start)
+ start = end - slen;
+ }
+ if (end-start >= slen)
+ return ! memcmp(str+start, sub, slen);
+ return 0;
}
@@ -2911,33 +2911,33 @@ prefix can also be a tuple of strings to try.");
static PyObject *
string_startswith(PyStringObject *self, PyObject *args)
{
- Py_ssize_t start = 0;
- Py_ssize_t end = PY_SSIZE_T_MAX;
- PyObject *subobj;
- int result;
-
- if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
- _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
- return NULL;
- if (PyTuple_Check(subobj)) {
- Py_ssize_t i;
- for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
- result = _string_tailmatch(self,
- PyTuple_GET_ITEM(subobj, i),
- start, end, -1);
- if (result == -1)
- return NULL;
- else if (result) {
- Py_RETURN_TRUE;
- }
- }
- Py_RETURN_FALSE;
- }
- result = _string_tailmatch(self, subobj, start, end, -1);
- if (result == -1)
- return NULL;
- else
- return PyBool_FromLong(result);
+ Py_ssize_t start = 0;
+ Py_ssize_t end = PY_SSIZE_T_MAX;
+ PyObject *subobj;
+ int result;
+
+ if (!PyArg_ParseTuple(args, "O|O&O&:startswith", &subobj,
+ _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+ return NULL;
+ if (PyTuple_Check(subobj)) {
+ Py_ssize_t i;
+ for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
+ result = _string_tailmatch(self,
+ PyTuple_GET_ITEM(subobj, i),
+ start, end, -1);
+ if (result == -1)
+ return NULL;
+ else if (result) {
+ Py_RETURN_TRUE;
+ }
+ }
+ Py_RETURN_FALSE;
+ }
+ result = _string_tailmatch(self, subobj, start, end, -1);
+ if (result == -1)
+ return NULL;
+ else
+ return PyBool_FromLong(result);
}
@@ -2952,33 +2952,33 @@ suffix can also be a tuple of strings to try.");
static PyObject *
string_endswith(PyStringObject *self, PyObject *args)
{
- Py_ssize_t start = 0;
- Py_ssize_t end = PY_SSIZE_T_MAX;
- PyObject *subobj;
- int result;
-
- if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
- _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
- return NULL;
- if (PyTuple_Check(subobj)) {
- Py_ssize_t i;
- for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
- result = _string_tailmatch(self,
- PyTuple_GET_ITEM(subobj, i),
- start, end, +1);
- if (result == -1)
- return NULL;
- else if (result) {
- Py_RETURN_TRUE;
- }
- }
- Py_RETURN_FALSE;
- }
- result = _string_tailmatch(self, subobj, start, end, +1);
- if (result == -1)
- return NULL;
- else
- return PyBool_FromLong(result);
+ Py_ssize_t start = 0;
+ Py_ssize_t end = PY_SSIZE_T_MAX;
+ PyObject *subobj;
+ int result;
+
+ if (!PyArg_ParseTuple(args, "O|O&O&:endswith", &subobj,
+ _PyEval_SliceIndex, &start, _PyEval_SliceIndex, &end))
+ return NULL;
+ if (PyTuple_Check(subobj)) {
+ Py_ssize_t i;
+ for (i = 0; i < PyTuple_GET_SIZE(subobj); i++) {
+ result = _string_tailmatch(self,
+ PyTuple_GET_ITEM(subobj, i),
+ start, end, +1);
+ if (result == -1)
+ return NULL;
+ else if (result) {
+ Py_RETURN_TRUE;
+ }
+ }
+ Py_RETURN_FALSE;
+ }
+ result = _string_tailmatch(self, subobj, start, end, +1);
+ if (result == -1)
+ return NULL;
+ else
+ return PyBool_FromLong(result);
}
@@ -3001,18 +3001,18 @@ string_encode(PyStringObject *self, PyObject *args, PyObject *kwargs)
PyObject *v;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:encode",
- kwlist, &encoding, &errors))
- return NULL;
+ kwlist, &encoding, &errors))
+ return NULL;
v = PyString_AsEncodedObject((PyObject *)self, encoding, errors);
if (v == NULL)
- goto onError;
+ goto onError;
if (!PyString_Check(v) && !PyUnicode_Check(v)) {
- PyErr_Format(PyExc_TypeError,
- "encoder did not return a string/unicode object "
- "(type=%.400s)",
- Py_TYPE(v)->tp_name);
- Py_DECREF(v);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "encoder did not return a string/unicode object "
+ "(type=%.400s)",
+ Py_TYPE(v)->tp_name);
+ Py_DECREF(v);
+ return NULL;
}
return v;
@@ -3040,18 +3040,18 @@ string_decode(PyStringObject *self, PyObject *args, PyObject *kwargs)
PyObject *v;
if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss:decode",
- kwlist, &encoding, &errors))
- return NULL;
+ kwlist, &encoding, &errors))
+ return NULL;
v = PyString_AsDecodedObject((PyObject *)self, encoding, errors);
if (v == NULL)
- goto onError;
+ goto onError;
if (!PyString_Check(v) && !PyUnicode_Check(v)) {
- PyErr_Format(PyExc_TypeError,
- "decoder did not return a string/unicode object "
- "(type=%.400s)",
- Py_TYPE(v)->tp_name);
- Py_DECREF(v);
- return NULL;
+ PyErr_Format(PyExc_TypeError,
+ "decoder did not return a string/unicode object "
+ "(type=%.400s)",
+ Py_TYPE(v)->tp_name);
+ Py_DECREF(v);
+ return NULL;
}
return v;
@@ -3076,65 +3076,65 @@ string_expandtabs(PyStringObject *self, PyObject *args)
int tabsize = 8;
if (!PyArg_ParseTuple(args, "|i:expandtabs", &tabsize))
- return NULL;
+ return NULL;
/* First pass: determine size of output string */
i = 0; /* chars up to and including most recent \n or \r */
j = 0; /* chars since most recent \n or \r (use in tab calculations) */
e = PyString_AS_STRING(self) + PyString_GET_SIZE(self); /* end of input */
for (p = PyString_AS_STRING(self); p < e; p++)
- if (*p == '\t') {
- if (tabsize > 0) {
- incr = tabsize - (j % tabsize);
- if (j > PY_SSIZE_T_MAX - incr)
- goto overflow1;
- j += incr;
- }
- }
- else {
- if (j > PY_SSIZE_T_MAX - 1)
- goto overflow1;
- j++;
- if (*p == '\n' || *p == '\r') {
- if (i > PY_SSIZE_T_MAX - j)
- goto overflow1;
- i += j;
- j = 0;
- }
+ if (*p == '\t') {
+ if (tabsize > 0) {
+ incr = tabsize - (j % tabsize);
+ if (j > PY_SSIZE_T_MAX - incr)
+ goto overflow1;
+ j += incr;
}
+ }
+ else {
+ if (j > PY_SSIZE_T_MAX - 1)
+ goto overflow1;
+ j++;
+ if (*p == '\n' || *p == '\r') {
+ if (i > PY_SSIZE_T_MAX - j)
+ goto overflow1;
+ i += j;
+ j = 0;
+ }
+ }
if (i > PY_SSIZE_T_MAX - j)
- goto overflow1;
+ goto overflow1;
/* Second pass: create output string and fill it */
u = PyString_FromStringAndSize(NULL, i + j);
if (!u)
- return NULL;
+ return NULL;
j = 0; /* same as in first pass */
q = PyString_AS_STRING(u); /* next output char */
qe = PyString_AS_STRING(u) + PyString_GET_SIZE(u); /* end of output */
for (p = PyString_AS_STRING(self); p < e; p++)
- if (*p == '\t') {
- if (tabsize > 0) {
- i = tabsize - (j % tabsize);
- j += i;
- while (i--) {
- if (q >= qe)
- goto overflow2;
- *q++ = ' ';
- }
- }
- }
- else {
- if (q >= qe)
- goto overflow2;
- *q++ = *p;
- j++;
- if (*p == '\n' || *p == '\r')
- j = 0;
+ if (*p == '\t') {
+ if (tabsize > 0) {
+ i = tabsize - (j % tabsize);
+ j += i;
+ while (i--) {
+ if (q >= qe)
+ goto overflow2;
+ *q++ = ' ';
}
+ }
+ }
+ else {
+ if (q >= qe)
+ goto overflow2;
+ *q++ = *p;
+ j++;
+ if (*p == '\n' || *p == '\r')
+ j = 0;
+ }
return u;
@@ -3151,26 +3151,26 @@ pad(PyStringObject *self, Py_ssize_t left, Py_ssize_t right, char fill)
PyObject *u;
if (left < 0)
- left = 0;
+ left = 0;
if (right < 0)
- right = 0;
+ right = 0;
if (left == 0 && right == 0 && PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject *)self;
+ Py_INCREF(self);
+ return (PyObject *)self;
}
u = PyString_FromStringAndSize(NULL,
- left + PyString_GET_SIZE(self) + right);
+ left + PyString_GET_SIZE(self) + right);
if (u) {
- if (left)
- memset(PyString_AS_STRING(u), fill, left);
- Py_MEMCPY(PyString_AS_STRING(u) + left,
- PyString_AS_STRING(self),
- PyString_GET_SIZE(self));
- if (right)
- memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
- fill, right);
+ if (left)
+ memset(PyString_AS_STRING(u), fill, left);
+ Py_MEMCPY(PyString_AS_STRING(u) + left,
+ PyString_AS_STRING(self),
+ PyString_GET_SIZE(self));
+ if (right)
+ memset(PyString_AS_STRING(u) + left + PyString_GET_SIZE(self),
+ fill, right);
}
return u;
@@ -3189,11 +3189,11 @@ string_ljust(PyStringObject *self, PyObject *args)
char fillchar = ' ';
if (!PyArg_ParseTuple(args, "n|c:ljust", &width, &fillchar))
- return NULL;
+ return NULL;
if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject*) self;
+ Py_INCREF(self);
+ return (PyObject*) self;
}
return pad(self, 0, width - PyString_GET_SIZE(self), fillchar);
@@ -3213,11 +3213,11 @@ string_rjust(PyStringObject *self, PyObject *args)
char fillchar = ' ';
if (!PyArg_ParseTuple(args, "n|c:rjust", &width, &fillchar))
- return NULL;
+ return NULL;
if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject*) self;
+ Py_INCREF(self);
+ return (PyObject*) self;
}
return pad(self, width - PyString_GET_SIZE(self), 0, fillchar);
@@ -3238,11 +3238,11 @@ string_center(PyStringObject *self, PyObject *args)
char fillchar = ' ';
if (!PyArg_ParseTuple(args, "n|c:center", &width, &fillchar))
- return NULL;
+ return NULL;
if (PyString_GET_SIZE(self) >= width && PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject*) self;
+ Py_INCREF(self);
+ return (PyObject*) self;
}
marg = width - PyString_GET_SIZE(self);
@@ -3266,18 +3266,18 @@ string_zfill(PyStringObject *self, PyObject *args)
Py_ssize_t width;
if (!PyArg_ParseTuple(args, "n:zfill", &width))
- return NULL;
+ return NULL;
if (PyString_GET_SIZE(self) >= width) {
- if (PyString_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject*) self;
- }
- else
- return PyString_FromStringAndSize(
- PyString_AS_STRING(self),
- PyString_GET_SIZE(self)
- );
+ if (PyString_CheckExact(self)) {
+ Py_INCREF(self);
+ return (PyObject*) self;
+ }
+ else
+ return PyString_FromStringAndSize(
+ PyString_AS_STRING(self),
+ PyString_GET_SIZE(self)
+ );
}
fill = width - PyString_GET_SIZE(self);
@@ -3285,13 +3285,13 @@ string_zfill(PyStringObject *self, PyObject *args)
s = pad(self, fill, 0, '0');
if (s == NULL)
- return NULL;
+ return NULL;
p = PyString_AS_STRING(s);
if (p[fill] == '+' || p[fill] == '-') {
- /* move sign to beginning of string */
- p[0] = p[fill];
- p[fill] = '0';
+ /* move sign to beginning of string */
+ p[0] = p[fill];
+ p[fill] = '0';
}
return (PyObject*) s;
@@ -3307,22 +3307,22 @@ static PyObject*
string_isspace(PyStringObject *self)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1 &&
- isspace(*p))
- return PyBool_FromLong(1);
+ isspace(*p))
+ return PyBool_FromLong(1);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
for (; p < e; p++) {
- if (!isspace(*p))
- return PyBool_FromLong(0);
+ if (!isspace(*p))
+ return PyBool_FromLong(0);
}
return PyBool_FromLong(1);
}
@@ -3338,22 +3338,22 @@ static PyObject*
string_isalpha(PyStringObject *self)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1 &&
- isalpha(*p))
- return PyBool_FromLong(1);
+ isalpha(*p))
+ return PyBool_FromLong(1);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
for (; p < e; p++) {
- if (!isalpha(*p))
- return PyBool_FromLong(0);
+ if (!isalpha(*p))
+ return PyBool_FromLong(0);
}
return PyBool_FromLong(1);
}
@@ -3369,22 +3369,22 @@ static PyObject*
string_isalnum(PyStringObject *self)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1 &&
- isalnum(*p))
- return PyBool_FromLong(1);
+ isalnum(*p))
+ return PyBool_FromLong(1);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
for (; p < e; p++) {
- if (!isalnum(*p))
- return PyBool_FromLong(0);
+ if (!isalnum(*p))
+ return PyBool_FromLong(0);
}
return PyBool_FromLong(1);
}
@@ -3400,22 +3400,22 @@ static PyObject*
string_isdigit(PyStringObject *self)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1 &&
- isdigit(*p))
- return PyBool_FromLong(1);
+ isdigit(*p))
+ return PyBool_FromLong(1);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
for (; p < e; p++) {
- if (!isdigit(*p))
- return PyBool_FromLong(0);
+ if (!isdigit(*p))
+ return PyBool_FromLong(0);
}
return PyBool_FromLong(1);
}
@@ -3431,25 +3431,25 @@ static PyObject*
string_islower(PyStringObject *self)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
int cased;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1)
- return PyBool_FromLong(islower(*p) != 0);
+ return PyBool_FromLong(islower(*p) != 0);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
cased = 0;
for (; p < e; p++) {
- if (isupper(*p))
- return PyBool_FromLong(0);
- else if (!cased && islower(*p))
- cased = 1;
+ if (isupper(*p))
+ return PyBool_FromLong(0);
+ else if (!cased && islower(*p))
+ cased = 1;
}
return PyBool_FromLong(cased);
}
@@ -3465,25 +3465,25 @@ static PyObject*
string_isupper(PyStringObject *self)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
int cased;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1)
- return PyBool_FromLong(isupper(*p) != 0);
+ return PyBool_FromLong(isupper(*p) != 0);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
cased = 0;
for (; p < e; p++) {
- if (islower(*p))
- return PyBool_FromLong(0);
- else if (!cased && isupper(*p))
- cased = 1;
+ if (islower(*p))
+ return PyBool_FromLong(0);
+ else if (!cased && isupper(*p))
+ cased = 1;
}
return PyBool_FromLong(cased);
}
@@ -3501,38 +3501,38 @@ static PyObject*
string_istitle(PyStringObject *self, PyObject *uncased)
{
register const unsigned char *p
- = (unsigned char *) PyString_AS_STRING(self);
+ = (unsigned char *) PyString_AS_STRING(self);
register const unsigned char *e;
int cased, previous_is_cased;
/* Shortcut for single character strings */
if (PyString_GET_SIZE(self) == 1)
- return PyBool_FromLong(isupper(*p) != 0);
+ return PyBool_FromLong(isupper(*p) != 0);
/* Special case for empty strings */
if (PyString_GET_SIZE(self) == 0)
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
e = p + PyString_GET_SIZE(self);
cased = 0;
previous_is_cased = 0;
for (; p < e; p++) {
- register const unsigned char ch = *p;
-
- if (isupper(ch)) {
- if (previous_is_cased)
- return PyBool_FromLong(0);
- previous_is_cased = 1;
- cased = 1;
- }
- else if (islower(ch)) {
- if (!previous_is_cased)
- return PyBool_FromLong(0);
- previous_is_cased = 1;
- cased = 1;
- }
- else
- previous_is_cased = 0;
+ register const unsigned char ch = *p;
+
+ if (isupper(ch)) {
+ if (previous_is_cased)
+ return PyBool_FromLong(0);
+ previous_is_cased = 1;
+ cased = 1;
+ }
+ else if (islower(ch)) {
+ if (!previous_is_cased)
+ return PyBool_FromLong(0);
+ previous_is_cased = 1;
+ cased = 1;
+ }
+ else
+ previous_is_cased = 0;
}
return PyBool_FromLong(cased);
}
@@ -3551,12 +3551,12 @@ string_splitlines(PyStringObject *self, PyObject *args)
int keepends = 0;
if (!PyArg_ParseTuple(args, "|i:splitlines", &keepends))
- return NULL;
+ return NULL;
return stringlib_splitlines(
- (PyObject*) self, PyString_AS_STRING(self), PyString_GET_SIZE(self),
- keepends
- );
+ (PyObject*) self, PyString_AS_STRING(self), PyString_GET_SIZE(self),
+ keepends
+ );
}
PyDoc_STRVAR(sizeof__doc__,
@@ -3565,15 +3565,15 @@ PyDoc_STRVAR(sizeof__doc__,
static PyObject *
string_sizeof(PyStringObject *v)
{
- Py_ssize_t res;
- res = PyStringObject_SIZE + PyString_GET_SIZE(v) * Py_TYPE(v)->tp_itemsize;
- return PyInt_FromSsize_t(res);
+ Py_ssize_t res;
+ res = PyStringObject_SIZE + PyString_GET_SIZE(v) * Py_TYPE(v)->tp_itemsize;
+ return PyInt_FromSsize_t(res);
}
static PyObject *
string_getnewargs(PyStringObject *v)
{
- return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v));
+ return Py_BuildValue("(s#)", v->ob_sval, Py_SIZE(v));
}
@@ -3594,20 +3594,20 @@ string__format__(PyObject* self, PyObject* args)
/* If 2.x, convert format_spec to the same type as value */
/* This is to allow things like u''.format('') */
if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
- goto done;
+ goto done;
if (!(PyString_Check(format_spec) || PyUnicode_Check(format_spec))) {
- PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
- "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
- goto done;
+ PyErr_Format(PyExc_TypeError, "__format__ arg must be str "
+ "or unicode, not %s", Py_TYPE(format_spec)->tp_name);
+ goto done;
}
tmp = PyObject_Str(format_spec);
if (tmp == NULL)
- goto done;
+ goto done;
format_spec = tmp;
result = _PyBytes_FormatAdvanced(self,
- PyString_AS_STRING(format_spec),
- PyString_GET_SIZE(format_spec));
+ PyString_AS_STRING(format_spec),
+ PyString_GET_SIZE(format_spec));
done:
Py_XDECREF(tmp);
return result;
@@ -3621,61 +3621,61 @@ PyDoc_STRVAR(p_format__doc__,
static PyMethodDef
string_methods[] = {
- /* Counterparts of the obsolete stropmodule functions; except
- string.maketrans(). */
- {"join", (PyCFunction)string_join, METH_O, join__doc__},
- {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
- {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
- {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
- {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
- {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
- {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
- {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
- {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
- {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
- {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
- {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
- {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
- capitalize__doc__},
- {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
- {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
- endswith__doc__},
- {"partition", (PyCFunction)string_partition, METH_O, partition__doc__},
- {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
- {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
- {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
- {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
- {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
- {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
- {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
- {"rpartition", (PyCFunction)string_rpartition, METH_O,
- rpartition__doc__},
- {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
- startswith__doc__},
- {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
- {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
- swapcase__doc__},
- {"translate", (PyCFunction)string_translate, METH_VARARGS,
- translate__doc__},
- {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
- {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
- {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
- {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
- {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
- {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
- {"__format__", (PyCFunction) string__format__, METH_VARARGS, p_format__doc__},
- {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
- {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
- {"encode", (PyCFunction)string_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
- {"decode", (PyCFunction)string_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__},
- {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
- expandtabs__doc__},
- {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
- splitlines__doc__},
- {"__sizeof__", (PyCFunction)string_sizeof, METH_NOARGS,
- sizeof__doc__},
- {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS},
- {NULL, NULL} /* sentinel */
+ /* Counterparts of the obsolete stropmodule functions; except
+ string.maketrans(). */
+ {"join", (PyCFunction)string_join, METH_O, join__doc__},
+ {"split", (PyCFunction)string_split, METH_VARARGS, split__doc__},
+ {"rsplit", (PyCFunction)string_rsplit, METH_VARARGS, rsplit__doc__},
+ {"lower", (PyCFunction)string_lower, METH_NOARGS, lower__doc__},
+ {"upper", (PyCFunction)string_upper, METH_NOARGS, upper__doc__},
+ {"islower", (PyCFunction)string_islower, METH_NOARGS, islower__doc__},
+ {"isupper", (PyCFunction)string_isupper, METH_NOARGS, isupper__doc__},
+ {"isspace", (PyCFunction)string_isspace, METH_NOARGS, isspace__doc__},
+ {"isdigit", (PyCFunction)string_isdigit, METH_NOARGS, isdigit__doc__},
+ {"istitle", (PyCFunction)string_istitle, METH_NOARGS, istitle__doc__},
+ {"isalpha", (PyCFunction)string_isalpha, METH_NOARGS, isalpha__doc__},
+ {"isalnum", (PyCFunction)string_isalnum, METH_NOARGS, isalnum__doc__},
+ {"capitalize", (PyCFunction)string_capitalize, METH_NOARGS,
+ capitalize__doc__},
+ {"count", (PyCFunction)string_count, METH_VARARGS, count__doc__},
+ {"endswith", (PyCFunction)string_endswith, METH_VARARGS,
+ endswith__doc__},
+ {"partition", (PyCFunction)string_partition, METH_O, partition__doc__},
+ {"find", (PyCFunction)string_find, METH_VARARGS, find__doc__},
+ {"index", (PyCFunction)string_index, METH_VARARGS, index__doc__},
+ {"lstrip", (PyCFunction)string_lstrip, METH_VARARGS, lstrip__doc__},
+ {"replace", (PyCFunction)string_replace, METH_VARARGS, replace__doc__},
+ {"rfind", (PyCFunction)string_rfind, METH_VARARGS, rfind__doc__},
+ {"rindex", (PyCFunction)string_rindex, METH_VARARGS, rindex__doc__},
+ {"rstrip", (PyCFunction)string_rstrip, METH_VARARGS, rstrip__doc__},
+ {"rpartition", (PyCFunction)string_rpartition, METH_O,
+ rpartition__doc__},
+ {"startswith", (PyCFunction)string_startswith, METH_VARARGS,
+ startswith__doc__},
+ {"strip", (PyCFunction)string_strip, METH_VARARGS, strip__doc__},
+ {"swapcase", (PyCFunction)string_swapcase, METH_NOARGS,
+ swapcase__doc__},
+ {"translate", (PyCFunction)string_translate, METH_VARARGS,
+ translate__doc__},
+ {"title", (PyCFunction)string_title, METH_NOARGS, title__doc__},
+ {"ljust", (PyCFunction)string_ljust, METH_VARARGS, ljust__doc__},
+ {"rjust", (PyCFunction)string_rjust, METH_VARARGS, rjust__doc__},
+ {"center", (PyCFunction)string_center, METH_VARARGS, center__doc__},
+ {"zfill", (PyCFunction)string_zfill, METH_VARARGS, zfill__doc__},
+ {"format", (PyCFunction) do_string_format, METH_VARARGS | METH_KEYWORDS, format__doc__},
+ {"__format__", (PyCFunction) string__format__, METH_VARARGS, p_format__doc__},
+ {"_formatter_field_name_split", (PyCFunction) formatter_field_name_split, METH_NOARGS},
+ {"_formatter_parser", (PyCFunction) formatter_parser, METH_NOARGS},
+ {"encode", (PyCFunction)string_encode, METH_VARARGS | METH_KEYWORDS, encode__doc__},
+ {"decode", (PyCFunction)string_decode, METH_VARARGS | METH_KEYWORDS, decode__doc__},
+ {"expandtabs", (PyCFunction)string_expandtabs, METH_VARARGS,
+ expandtabs__doc__},
+ {"splitlines", (PyCFunction)string_splitlines, METH_VARARGS,
+ splitlines__doc__},
+ {"__sizeof__", (PyCFunction)string_sizeof, METH_NOARGS,
+ sizeof__doc__},
+ {"__getnewargs__", (PyCFunction)string_getnewargs, METH_NOARGS},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
@@ -3684,111 +3684,111 @@ str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
string_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *x = NULL;
- static char *kwlist[] = {"object", 0};
-
- if (type != &PyString_Type)
- return str_subtype_new(type, args, kwds);
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
- return NULL;
- if (x == NULL)
- return PyString_FromString("");
- return PyObject_Str(x);
+ PyObject *x = NULL;
+ static char *kwlist[] = {"object", 0};
+
+ if (type != &PyString_Type)
+ return str_subtype_new(type, args, kwds);
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:str", kwlist, &x))
+ return NULL;
+ if (x == NULL)
+ return PyString_FromString("");
+ return PyObject_Str(x);
}
static PyObject *
str_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *tmp, *pnew;
- Py_ssize_t n;
-
- assert(PyType_IsSubtype(type, &PyString_Type));
- tmp = string_new(&PyString_Type, args, kwds);
- if (tmp == NULL)
- return NULL;
- assert(PyString_CheckExact(tmp));
- n = PyString_GET_SIZE(tmp);
- pnew = type->tp_alloc(type, n);
- if (pnew != NULL) {
- Py_MEMCPY(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
- ((PyStringObject *)pnew)->ob_shash =
- ((PyStringObject *)tmp)->ob_shash;
- ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
- }
- Py_DECREF(tmp);
- return pnew;
+ PyObject *tmp, *pnew;
+ Py_ssize_t n;
+
+ assert(PyType_IsSubtype(type, &PyString_Type));
+ tmp = string_new(&PyString_Type, args, kwds);
+ if (tmp == NULL)
+ return NULL;
+ assert(PyString_CheckExact(tmp));
+ n = PyString_GET_SIZE(tmp);
+ pnew = type->tp_alloc(type, n);
+ if (pnew != NULL) {
+ Py_MEMCPY(PyString_AS_STRING(pnew), PyString_AS_STRING(tmp), n+1);
+ ((PyStringObject *)pnew)->ob_shash =
+ ((PyStringObject *)tmp)->ob_shash;
+ ((PyStringObject *)pnew)->ob_sstate = SSTATE_NOT_INTERNED;
+ }
+ Py_DECREF(tmp);
+ return pnew;
}
static PyObject *
basestring_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyErr_SetString(PyExc_TypeError,
- "The basestring type cannot be instantiated");
- return NULL;
+ PyErr_SetString(PyExc_TypeError,
+ "The basestring type cannot be instantiated");
+ return NULL;
}
static PyObject *
string_mod(PyObject *v, PyObject *w)
{
- if (!PyString_Check(v)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return PyString_Format(v, w);
+ if (!PyString_Check(v)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return PyString_Format(v, w);
}
PyDoc_STRVAR(basestring_doc,
"Type basestring cannot be instantiated; it is the base for str and unicode.");
static PyNumberMethods string_as_number = {
- 0, /*nb_add*/
- 0, /*nb_subtract*/
- 0, /*nb_multiply*/
- 0, /*nb_divide*/
- string_mod, /*nb_remainder*/
+ 0, /*nb_add*/
+ 0, /*nb_subtract*/
+ 0, /*nb_multiply*/
+ 0, /*nb_divide*/
+ string_mod, /*nb_remainder*/
};
PyTypeObject PyBaseString_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "basestring",
- 0,
- 0,
- 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 */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- basestring_doc, /* 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 */
- &PyBaseObject_Type, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- basestring_new, /* tp_new */
- 0, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "basestring",
+ 0,
+ 0,
+ 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 */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ basestring_doc, /* 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 */
+ &PyBaseObject_Type, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ basestring_new, /* tp_new */
+ 0, /* tp_free */
};
PyDoc_STRVAR(string_doc,
@@ -3798,70 +3798,70 @@ Return a nice string representation of the object.\n\
If the argument is a string, the return value is the same object.");
PyTypeObject PyString_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "str",
- PyStringObject_SIZE,
- sizeof(char),
- string_dealloc, /* tp_dealloc */
- (printfunc)string_print, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- string_repr, /* tp_repr */
- &string_as_number, /* tp_as_number */
- &string_as_sequence, /* tp_as_sequence */
- &string_as_mapping, /* tp_as_mapping */
- (hashfunc)string_hash, /* tp_hash */
- 0, /* tp_call */
- string_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- &string_as_buffer, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS |
- Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */
- string_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- (richcmpfunc)string_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- string_methods, /* tp_methods */
- 0, /* tp_members */
- 0, /* tp_getset */
- &PyBaseString_Type, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- 0, /* tp_init */
- 0, /* tp_alloc */
- string_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "str",
+ PyStringObject_SIZE,
+ sizeof(char),
+ string_dealloc, /* tp_dealloc */
+ (printfunc)string_print, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ string_repr, /* tp_repr */
+ &string_as_number, /* tp_as_number */
+ &string_as_sequence, /* tp_as_sequence */
+ &string_as_mapping, /* tp_as_mapping */
+ (hashfunc)string_hash, /* tp_hash */
+ 0, /* tp_call */
+ string_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ &string_as_buffer, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_STRING_SUBCLASS |
+ Py_TPFLAGS_HAVE_NEWBUFFER, /* tp_flags */
+ string_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ (richcmpfunc)string_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ string_methods, /* tp_methods */
+ 0, /* tp_members */
+ 0, /* tp_getset */
+ &PyBaseString_Type, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ 0, /* tp_init */
+ 0, /* tp_alloc */
+ string_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
void
PyString_Concat(register PyObject **pv, register PyObject *w)
{
- register PyObject *v;
- if (*pv == NULL)
- return;
- if (w == NULL || !PyString_Check(*pv)) {
- Py_DECREF(*pv);
- *pv = NULL;
- return;
- }
- v = string_concat((PyStringObject *) *pv, w);
- Py_DECREF(*pv);
- *pv = v;
+ register PyObject *v;
+ if (*pv == NULL)
+ return;
+ if (w == NULL || !PyString_Check(*pv)) {
+ Py_DECREF(*pv);
+ *pv = NULL;
+ return;
+ }
+ v = string_concat((PyStringObject *) *pv, w);
+ Py_DECREF(*pv);
+ *pv = v;
}
void
PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
{
- PyString_Concat(pv, w);
- Py_XDECREF(w);
+ PyString_Concat(pv, w);
+ Py_XDECREF(w);
}
@@ -3882,32 +3882,32 @@ PyString_ConcatAndDel(register PyObject **pv, register PyObject *w)
int
_PyString_Resize(PyObject **pv, Py_ssize_t newsize)
{
- register PyObject *v;
- register PyStringObject *sv;
- v = *pv;
- if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
- PyString_CHECK_INTERNED(v)) {
- *pv = 0;
- Py_DECREF(v);
- PyErr_BadInternalCall();
- return -1;
- }
- /* XXX UNREF/NEWREF interface should be more symmetrical */
- _Py_DEC_REFTOTAL;
- _Py_ForgetReference(v);
- *pv = (PyObject *)
- PyObject_REALLOC((char *)v, PyStringObject_SIZE + newsize);
- if (*pv == NULL) {
- PyObject_Del(v);
- PyErr_NoMemory();
- return -1;
- }
- _Py_NewReference(*pv);
- sv = (PyStringObject *) *pv;
- Py_SIZE(sv) = newsize;
- sv->ob_sval[newsize] = '\0';
- sv->ob_shash = -1; /* invalidate cached hash value */
- return 0;
+ register PyObject *v;
+ register PyStringObject *sv;
+ v = *pv;
+ if (!PyString_Check(v) || Py_REFCNT(v) != 1 || newsize < 0 ||
+ PyString_CHECK_INTERNED(v)) {
+ *pv = 0;
+ Py_DECREF(v);
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ /* XXX UNREF/NEWREF interface should be more symmetrical */
+ _Py_DEC_REFTOTAL;
+ _Py_ForgetReference(v);
+ *pv = (PyObject *)
+ PyObject_REALLOC((char *)v, PyStringObject_SIZE + newsize);
+ if (*pv == NULL) {
+ PyObject_Del(v);
+ PyErr_NoMemory();
+ return -1;
+ }
+ _Py_NewReference(*pv);
+ sv = (PyStringObject *) *pv;
+ Py_SIZE(sv) = newsize;
+ sv->ob_sval[newsize] = '\0';
+ sv->ob_shash = -1; /* invalidate cached hash value */
+ return 0;
}
/* Helpers for formatstring */
@@ -3915,59 +3915,59 @@ _PyString_Resize(PyObject **pv, Py_ssize_t newsize)
Py_LOCAL_INLINE(PyObject *)
getnextarg(PyObject *args, Py_ssize_t arglen, Py_ssize_t *p_argidx)
{
- Py_ssize_t argidx = *p_argidx;
- if (argidx < arglen) {
- (*p_argidx)++;
- if (arglen < 0)
- return args;
- else
- return PyTuple_GetItem(args, argidx);
- }
- PyErr_SetString(PyExc_TypeError,
- "not enough arguments for format string");
- return NULL;
+ Py_ssize_t argidx = *p_argidx;
+ if (argidx < arglen) {
+ (*p_argidx)++;
+ if (arglen < 0)
+ return args;
+ else
+ return PyTuple_GetItem(args, argidx);
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "not enough arguments for format string");
+ return NULL;
}
/* Format codes
- * F_LJUST '-'
- * F_SIGN '+'
- * F_BLANK ' '
- * F_ALT '#'
- * F_ZERO '0'
+ * F_LJUST '-'
+ * F_SIGN '+'
+ * F_BLANK ' '
+ * F_ALT '#'
+ * F_ZERO '0'
*/
#define F_LJUST (1<<0)
-#define F_SIGN (1<<1)
+#define F_SIGN (1<<1)
#define F_BLANK (1<<2)
-#define F_ALT (1<<3)
-#define F_ZERO (1<<4)
+#define F_ALT (1<<3)
+#define F_ZERO (1<<4)
/* Returns a new reference to a PyString object, or NULL on failure. */
static PyObject *
formatfloat(PyObject *v, int flags, int prec, int type)
{
- char *p;
- PyObject *result;
- double x;
-
- x = PyFloat_AsDouble(v);
- if (x == -1.0 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError, "float argument required, "
- "not %.200s", Py_TYPE(v)->tp_name);
- return NULL;
- }
-
- if (prec < 0)
- prec = 6;
-
- p = PyOS_double_to_string(x, type, prec,
- (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
-
- if (p == NULL)
- return NULL;
- result = PyString_FromStringAndSize(p, strlen(p));
- PyMem_Free(p);
- return result;
+ char *p;
+ PyObject *result;
+ double x;
+
+ x = PyFloat_AsDouble(v);
+ if (x == -1.0 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError, "float argument required, "
+ "not %.200s", Py_TYPE(v)->tp_name);
+ return NULL;
+ }
+
+ if (prec < 0)
+ prec = 6;
+
+ p = PyOS_double_to_string(x, type, prec,
+ (flags & F_ALT) ? Py_DTSF_ALT : 0, NULL);
+
+ if (p == NULL)
+ return NULL;
+ result = PyString_FromStringAndSize(p, strlen(p));
+ PyMem_Free(p);
+ return result;
}
/* _PyString_FormatLong emulates the format codes d, u, o, x and X, and
@@ -3983,226 +3983,226 @@ formatfloat(PyObject *v, int flags, int prec, int type)
* set in flags. The case of hex digits will be correct,
* There will be at least prec digits, zero-filled on the left if
* necessary to get that many.
- * val object to be converted
- * flags bitmask of format flags; only F_ALT is looked at
- * prec minimum number of digits; 0-fill on left if needed
- * type a character in [duoxX]; u acts the same as d
+ * val object to be converted
+ * flags bitmask of format flags; only F_ALT is looked at
+ * prec minimum number of digits; 0-fill on left if needed
+ * type a character in [duoxX]; u acts the same as d
*
* CAUTION: o, x and X conversions on regular ints can never
* produce a '-' sign, but can for Python's unbounded ints.
*/
PyObject*
_PyString_FormatLong(PyObject *val, int flags, int prec, int type,
- char **pbuf, int *plen)
+ char **pbuf, int *plen)
{
- PyObject *result = NULL;
- char *buf;
- Py_ssize_t i;
- int sign; /* 1 if '-', else 0 */
- int len; /* number of characters */
- Py_ssize_t llen;
- int numdigits; /* len == numnondigits + numdigits */
- int numnondigits = 0;
-
- switch (type) {
- case 'd':
- case 'u':
- result = Py_TYPE(val)->tp_str(val);
- break;
- case 'o':
- result = Py_TYPE(val)->tp_as_number->nb_oct(val);
- break;
- case 'x':
- case 'X':
- numnondigits = 2;
- result = Py_TYPE(val)->tp_as_number->nb_hex(val);
- break;
- default:
- assert(!"'type' not in [duoxX]");
- }
- if (!result)
- return NULL;
-
- buf = PyString_AsString(result);
- if (!buf) {
- Py_DECREF(result);
- return NULL;
- }
-
- /* To modify the string in-place, there can only be one reference. */
- if (Py_REFCNT(result) != 1) {
- PyErr_BadInternalCall();
- return NULL;
- }
- llen = PyString_Size(result);
- if (llen > INT_MAX) {
- PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
- return NULL;
- }
- len = (int)llen;
- if (buf[len-1] == 'L') {
- --len;
- buf[len] = '\0';
- }
- sign = buf[0] == '-';
- numnondigits += sign;
- numdigits = len - numnondigits;
- assert(numdigits > 0);
-
- /* Get rid of base marker unless F_ALT */
- if ((flags & F_ALT) == 0) {
- /* Need to skip 0x, 0X or 0. */
- int skipped = 0;
- switch (type) {
- case 'o':
- assert(buf[sign] == '0');
- /* If 0 is only digit, leave it alone. */
- if (numdigits > 1) {
- skipped = 1;
- --numdigits;
- }
- break;
- case 'x':
- case 'X':
- assert(buf[sign] == '0');
- assert(buf[sign + 1] == 'x');
- skipped = 2;
- numnondigits -= 2;
- break;
- }
- if (skipped) {
- buf += skipped;
- len -= skipped;
- if (sign)
- buf[0] = '-';
- }
- assert(len == numnondigits + numdigits);
- assert(numdigits > 0);
- }
-
- /* Fill with leading zeroes to meet minimum width. */
- if (prec > numdigits) {
- PyObject *r1 = PyString_FromStringAndSize(NULL,
- numnondigits + prec);
- char *b1;
- if (!r1) {
- Py_DECREF(result);
- return NULL;
- }
- b1 = PyString_AS_STRING(r1);
- for (i = 0; i < numnondigits; ++i)
- *b1++ = *buf++;
- for (i = 0; i < prec - numdigits; i++)
- *b1++ = '0';
- for (i = 0; i < numdigits; i++)
- *b1++ = *buf++;
- *b1 = '\0';
- Py_DECREF(result);
- result = r1;
- buf = PyString_AS_STRING(result);
- len = numnondigits + prec;
- }
-
- /* Fix up case for hex conversions. */
- if (type == 'X') {
- /* Need to convert all lower case letters to upper case.
- and need to convert 0x to 0X (and -0x to -0X). */
- for (i = 0; i < len; i++)
- if (buf[i] >= 'a' && buf[i] <= 'x')
- buf[i] -= 'a'-'A';
- }
- *pbuf = buf;
- *plen = len;
- return result;
+ PyObject *result = NULL;
+ char *buf;
+ Py_ssize_t i;
+ int sign; /* 1 if '-', else 0 */
+ int len; /* number of characters */
+ Py_ssize_t llen;
+ int numdigits; /* len == numnondigits + numdigits */
+ int numnondigits = 0;
+
+ switch (type) {
+ case 'd':
+ case 'u':
+ result = Py_TYPE(val)->tp_str(val);
+ break;
+ case 'o':
+ result = Py_TYPE(val)->tp_as_number->nb_oct(val);
+ break;
+ case 'x':
+ case 'X':
+ numnondigits = 2;
+ result = Py_TYPE(val)->tp_as_number->nb_hex(val);
+ break;
+ default:
+ assert(!"'type' not in [duoxX]");
+ }
+ if (!result)
+ return NULL;
+
+ buf = PyString_AsString(result);
+ if (!buf) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ /* To modify the string in-place, there can only be one reference. */
+ if (Py_REFCNT(result) != 1) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ llen = PyString_Size(result);
+ if (llen > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "string too large in _PyString_FormatLong");
+ return NULL;
+ }
+ len = (int)llen;
+ if (buf[len-1] == 'L') {
+ --len;
+ buf[len] = '\0';
+ }
+ sign = buf[0] == '-';
+ numnondigits += sign;
+ numdigits = len - numnondigits;
+ assert(numdigits > 0);
+
+ /* Get rid of base marker unless F_ALT */
+ if ((flags & F_ALT) == 0) {
+ /* Need to skip 0x, 0X or 0. */
+ int skipped = 0;
+ switch (type) {
+ case 'o':
+ assert(buf[sign] == '0');
+ /* If 0 is only digit, leave it alone. */
+ if (numdigits > 1) {
+ skipped = 1;
+ --numdigits;
+ }
+ break;
+ case 'x':
+ case 'X':
+ assert(buf[sign] == '0');
+ assert(buf[sign + 1] == 'x');
+ skipped = 2;
+ numnondigits -= 2;
+ break;
+ }
+ if (skipped) {
+ buf += skipped;
+ len -= skipped;
+ if (sign)
+ buf[0] = '-';
+ }
+ assert(len == numnondigits + numdigits);
+ assert(numdigits > 0);
+ }
+
+ /* Fill with leading zeroes to meet minimum width. */
+ if (prec > numdigits) {
+ PyObject *r1 = PyString_FromStringAndSize(NULL,
+ numnondigits + prec);
+ char *b1;
+ if (!r1) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ b1 = PyString_AS_STRING(r1);
+ for (i = 0; i < numnondigits; ++i)
+ *b1++ = *buf++;
+ for (i = 0; i < prec - numdigits; i++)
+ *b1++ = '0';
+ for (i = 0; i < numdigits; i++)
+ *b1++ = *buf++;
+ *b1 = '\0';
+ Py_DECREF(result);
+ result = r1;
+ buf = PyString_AS_STRING(result);
+ len = numnondigits + prec;
+ }
+
+ /* Fix up case for hex conversions. */
+ if (type == 'X') {
+ /* Need to convert all lower case letters to upper case.
+ and need to convert 0x to 0X (and -0x to -0X). */
+ for (i = 0; i < len; i++)
+ if (buf[i] >= 'a' && buf[i] <= 'x')
+ buf[i] -= 'a'-'A';
+ }
+ *pbuf = buf;
+ *plen = len;
+ return result;
}
Py_LOCAL_INLINE(int)
formatint(char *buf, size_t buflen, int flags,
int prec, int type, PyObject *v)
{
- /* fmt = '%#.' + `prec` + 'l' + `type`
- worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
- + 1 + 1 = 24 */
- char fmt[64]; /* plenty big enough! */
- char *sign;
- long x;
-
- x = PyInt_AsLong(v);
- if (x == -1 && PyErr_Occurred()) {
- PyErr_Format(PyExc_TypeError, "int argument required, not %.200s",
- Py_TYPE(v)->tp_name);
- return -1;
- }
- if (x < 0 && type == 'u') {
- type = 'd';
- }
- if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
- sign = "-";
- else
- sign = "";
- if (prec < 0)
- prec = 1;
-
- if ((flags & F_ALT) &&
- (type == 'x' || type == 'X')) {
- /* When converting under %#x or %#X, there are a number
- * of issues that cause pain:
- * - when 0 is being converted, the C standard leaves off
- * the '0x' or '0X', which is inconsistent with other
- * %#x/%#X conversions and inconsistent with Python's
- * hex() function
- * - there are platforms that violate the standard and
- * convert 0 with the '0x' or '0X'
- * (Metrowerks, Compaq Tru64)
- * - there are platforms that give '0x' when converting
- * under %#X, but convert 0 in accordance with the
- * standard (OS/2 EMX)
- *
- * We can achieve the desired consistency by inserting our
- * own '0x' or '0X' prefix, and substituting %x/%X in place
- * of %#x/%#X.
- *
- * Note that this is the same approach as used in
- * formatint() in unicodeobject.c
- */
- PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
- sign, type, prec, type);
- }
- else {
- PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
- sign, (flags&F_ALT) ? "#" : "",
- prec, type);
- }
-
- /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
- * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
- */
- if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
- PyErr_SetString(PyExc_OverflowError,
- "formatted integer is too long (precision too large?)");
- return -1;
- }
- if (sign[0])
- PyOS_snprintf(buf, buflen, fmt, -x);
- else
- PyOS_snprintf(buf, buflen, fmt, x);
- return (int)strlen(buf);
+ /* fmt = '%#.' + `prec` + 'l' + `type`
+ worst case length = 3 + 19 (worst len of INT_MAX on 64-bit machine)
+ + 1 + 1 = 24 */
+ char fmt[64]; /* plenty big enough! */
+ char *sign;
+ long x;
+
+ x = PyInt_AsLong(v);
+ if (x == -1 && PyErr_Occurred()) {
+ PyErr_Format(PyExc_TypeError, "int argument required, not %.200s",
+ Py_TYPE(v)->tp_name);
+ return -1;
+ }
+ if (x < 0 && type == 'u') {
+ type = 'd';
+ }
+ if (x < 0 && (type == 'x' || type == 'X' || type == 'o'))
+ sign = "-";
+ else
+ sign = "";
+ if (prec < 0)
+ prec = 1;
+
+ if ((flags & F_ALT) &&
+ (type == 'x' || type == 'X')) {
+ /* When converting under %#x or %#X, there are a number
+ * of issues that cause pain:
+ * - when 0 is being converted, the C standard leaves off
+ * the '0x' or '0X', which is inconsistent with other
+ * %#x/%#X conversions and inconsistent with Python's
+ * hex() function
+ * - there are platforms that violate the standard and
+ * convert 0 with the '0x' or '0X'
+ * (Metrowerks, Compaq Tru64)
+ * - there are platforms that give '0x' when converting
+ * under %#X, but convert 0 in accordance with the
+ * standard (OS/2 EMX)
+ *
+ * We can achieve the desired consistency by inserting our
+ * own '0x' or '0X' prefix, and substituting %x/%X in place
+ * of %#x/%#X.
+ *
+ * Note that this is the same approach as used in
+ * formatint() in unicodeobject.c
+ */
+ PyOS_snprintf(fmt, sizeof(fmt), "%s0%c%%.%dl%c",
+ sign, type, prec, type);
+ }
+ else {
+ PyOS_snprintf(fmt, sizeof(fmt), "%s%%%s.%dl%c",
+ sign, (flags&F_ALT) ? "#" : "",
+ prec, type);
+ }
+
+ /* buf = '+'/'-'/'' + '0'/'0x'/'' + '[0-9]'*max(prec, len(x in octal))
+ * worst case buf = '-0x' + [0-9]*prec, where prec >= 11
+ */
+ if (buflen <= 14 || buflen <= (size_t)3 + (size_t)prec) {
+ PyErr_SetString(PyExc_OverflowError,
+ "formatted integer is too long (precision too large?)");
+ return -1;
+ }
+ if (sign[0])
+ PyOS_snprintf(buf, buflen, fmt, -x);
+ else
+ PyOS_snprintf(buf, buflen, fmt, x);
+ return (int)strlen(buf);
}
Py_LOCAL_INLINE(int)
formatchar(char *buf, size_t buflen, PyObject *v)
{
- /* presume that the buffer is at least 2 characters long */
- if (PyString_Check(v)) {
- if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
- return -1;
- }
- else {
- if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
- return -1;
- }
- buf[1] = '\0';
- return 1;
+ /* presume that the buffer is at least 2 characters long */
+ if (PyString_Check(v)) {
+ if (!PyArg_Parse(v, "c;%c requires int or char", &buf[0]))
+ return -1;
+ }
+ else {
+ if (!PyArg_Parse(v, "b;%c requires int or char", &buf[0]))
+ return -1;
+ }
+ buf[1] = '\0';
+ return 1;
}
/* fmt%(v1,v2,...) is roughly equivalent to sprintf(fmt, v1, v2, ...)
@@ -4218,615 +4218,615 @@ formatchar(char *buf, size_t buflen, PyObject *v)
PyObject *
PyString_Format(PyObject *format, PyObject *args)
{
- char *fmt, *res;
- Py_ssize_t arglen, argidx;
- Py_ssize_t reslen, rescnt, fmtcnt;
- int args_owned = 0;
- PyObject *result, *orig_args;
+ char *fmt, *res;
+ Py_ssize_t arglen, argidx;
+ Py_ssize_t reslen, rescnt, fmtcnt;
+ int args_owned = 0;
+ PyObject *result, *orig_args;
#ifdef Py_USING_UNICODE
- PyObject *v, *w;
+ PyObject *v, *w;
#endif
- PyObject *dict = NULL;
- if (format == NULL || !PyString_Check(format) || args == NULL) {
- PyErr_BadInternalCall();
- return NULL;
- }
- orig_args = args;
- fmt = PyString_AS_STRING(format);
- fmtcnt = PyString_GET_SIZE(format);
- reslen = rescnt = fmtcnt + 100;
- result = PyString_FromStringAndSize((char *)NULL, reslen);
- if (result == NULL)
- return NULL;
- res = PyString_AsString(result);
- if (PyTuple_Check(args)) {
- arglen = PyTuple_GET_SIZE(args);
- argidx = 0;
- }
- else {
- arglen = -1;
- argidx = -2;
- }
- if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
- !PyObject_TypeCheck(args, &PyBaseString_Type))
- dict = args;
- while (--fmtcnt >= 0) {
- if (*fmt != '%') {
- if (--rescnt < 0) {
- rescnt = fmtcnt + 100;
- reslen += rescnt;
- if (_PyString_Resize(&result, reslen))
- return NULL;
- res = PyString_AS_STRING(result)
- + reslen - rescnt;
- --rescnt;
- }
- *res++ = *fmt++;
- }
- else {
- /* Got a format specifier */
- int flags = 0;
- Py_ssize_t width = -1;
- int prec = -1;
- int c = '\0';
- int fill;
- int isnumok;
- PyObject *v = NULL;
- PyObject *temp = NULL;
- char *pbuf;
- int sign;
- Py_ssize_t len;
- char formatbuf[FORMATBUFLEN];
- /* For format{int,char}() */
+ PyObject *dict = NULL;
+ if (format == NULL || !PyString_Check(format) || args == NULL) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ orig_args = args;
+ fmt = PyString_AS_STRING(format);
+ fmtcnt = PyString_GET_SIZE(format);
+ reslen = rescnt = fmtcnt + 100;
+ result = PyString_FromStringAndSize((char *)NULL, reslen);
+ if (result == NULL)
+ return NULL;
+ res = PyString_AsString(result);
+ if (PyTuple_Check(args)) {
+ arglen = PyTuple_GET_SIZE(args);
+ argidx = 0;
+ }
+ else {
+ arglen = -1;
+ argidx = -2;
+ }
+ if (Py_TYPE(args)->tp_as_mapping && !PyTuple_Check(args) &&
+ !PyObject_TypeCheck(args, &PyBaseString_Type))
+ dict = args;
+ while (--fmtcnt >= 0) {
+ if (*fmt != '%') {
+ if (--rescnt < 0) {
+ rescnt = fmtcnt + 100;
+ reslen += rescnt;
+ if (_PyString_Resize(&result, reslen))
+ return NULL;
+ res = PyString_AS_STRING(result)
+ + reslen - rescnt;
+ --rescnt;
+ }
+ *res++ = *fmt++;
+ }
+ else {
+ /* Got a format specifier */
+ int flags = 0;
+ Py_ssize_t width = -1;
+ int prec = -1;
+ int c = '\0';
+ int fill;
+ int isnumok;
+ PyObject *v = NULL;
+ PyObject *temp = NULL;
+ char *pbuf;
+ int sign;
+ Py_ssize_t len;
+ char formatbuf[FORMATBUFLEN];
+ /* For format{int,char}() */
#ifdef Py_USING_UNICODE
- char *fmt_start = fmt;
- Py_ssize_t argidx_start = argidx;
+ char *fmt_start = fmt;
+ Py_ssize_t argidx_start = argidx;
#endif
- fmt++;
- if (*fmt == '(') {
- char *keystart;
- Py_ssize_t keylen;
- PyObject *key;
- int pcount = 1;
-
- if (dict == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "format requires a mapping");
- goto error;
- }
- ++fmt;
- --fmtcnt;
- keystart = fmt;
- /* Skip over balanced parentheses */
- while (pcount > 0 && --fmtcnt >= 0) {
- if (*fmt == ')')
- --pcount;
- else if (*fmt == '(')
- ++pcount;
- fmt++;
- }
- keylen = fmt - keystart - 1;
- if (fmtcnt < 0 || pcount > 0) {
- PyErr_SetString(PyExc_ValueError,
- "incomplete format key");
- goto error;
- }
- key = PyString_FromStringAndSize(keystart,
- keylen);
- if (key == NULL)
- goto error;
- if (args_owned) {
- Py_DECREF(args);
- args_owned = 0;
- }
- args = PyObject_GetItem(dict, key);
- Py_DECREF(key);
- if (args == NULL) {
- goto error;
- }
- args_owned = 1;
- arglen = -1;
- argidx = -2;
- }
- while (--fmtcnt >= 0) {
- switch (c = *fmt++) {
- case '-': flags |= F_LJUST; continue;
- case '+': flags |= F_SIGN; continue;
- case ' ': flags |= F_BLANK; continue;
- case '#': flags |= F_ALT; continue;
- case '0': flags |= F_ZERO; continue;
- }
- break;
- }
- if (c == '*') {
- v = getnextarg(args, arglen, &argidx);
- if (v == NULL)
- goto error;
- if (!PyInt_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "* wants int");
- goto error;
- }
- width = PyInt_AsLong(v);
- if (width < 0) {
- flags |= F_LJUST;
- width = -width;
- }
- if (--fmtcnt >= 0)
- c = *fmt++;
- }
- else if (c >= 0 && isdigit(c)) {
- width = c - '0';
- while (--fmtcnt >= 0) {
- c = Py_CHARMASK(*fmt++);
- if (!isdigit(c))
- break;
- if ((width*10) / 10 != width) {
- PyErr_SetString(
- PyExc_ValueError,
- "width too big");
- goto error;
- }
- width = width*10 + (c - '0');
- }
- }
- if (c == '.') {
- prec = 0;
- if (--fmtcnt >= 0)
- c = *fmt++;
- if (c == '*') {
- v = getnextarg(args, arglen, &argidx);
- if (v == NULL)
- goto error;
- if (!PyInt_Check(v)) {
- PyErr_SetString(
- PyExc_TypeError,
- "* wants int");
- goto error;
- }
- prec = PyInt_AsLong(v);
- if (prec < 0)
- prec = 0;
- if (--fmtcnt >= 0)
- c = *fmt++;
- }
- else if (c >= 0 && isdigit(c)) {
- prec = c - '0';
- while (--fmtcnt >= 0) {
- c = Py_CHARMASK(*fmt++);
- if (!isdigit(c))
- break;
- if ((prec*10) / 10 != prec) {
- PyErr_SetString(
- PyExc_ValueError,
- "prec too big");
- goto error;
- }
- prec = prec*10 + (c - '0');
- }
- }
- } /* prec */
- if (fmtcnt >= 0) {
- if (c == 'h' || c == 'l' || c == 'L') {
- if (--fmtcnt >= 0)
- c = *fmt++;
- }
- }
- if (fmtcnt < 0) {
- PyErr_SetString(PyExc_ValueError,
- "incomplete format");
- goto error;
- }
- if (c != '%') {
- v = getnextarg(args, arglen, &argidx);
- if (v == NULL)
- goto error;
- }
- sign = 0;
- fill = ' ';
- switch (c) {
- case '%':
- pbuf = "%";
- len = 1;
- break;
- case 's':
-#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(v)) {
- fmt = fmt_start;
- argidx = argidx_start;
- goto unicode;
- }
-#endif
- temp = _PyObject_Str(v);
+ fmt++;
+ if (*fmt == '(') {
+ char *keystart;
+ Py_ssize_t keylen;
+ PyObject *key;
+ int pcount = 1;
+
+ if (dict == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "format requires a mapping");
+ goto error;
+ }
+ ++fmt;
+ --fmtcnt;
+ keystart = fmt;
+ /* Skip over balanced parentheses */
+ while (pcount > 0 && --fmtcnt >= 0) {
+ if (*fmt == ')')
+ --pcount;
+ else if (*fmt == '(')
+ ++pcount;
+ fmt++;
+ }
+ keylen = fmt - keystart - 1;
+ if (fmtcnt < 0 || pcount > 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "incomplete format key");
+ goto error;
+ }
+ key = PyString_FromStringAndSize(keystart,
+ keylen);
+ if (key == NULL)
+ goto error;
+ if (args_owned) {
+ Py_DECREF(args);
+ args_owned = 0;
+ }
+ args = PyObject_GetItem(dict, key);
+ Py_DECREF(key);
+ if (args == NULL) {
+ goto error;
+ }
+ args_owned = 1;
+ arglen = -1;
+ argidx = -2;
+ }
+ while (--fmtcnt >= 0) {
+ switch (c = *fmt++) {
+ case '-': flags |= F_LJUST; continue;
+ case '+': flags |= F_SIGN; continue;
+ case ' ': flags |= F_BLANK; continue;
+ case '#': flags |= F_ALT; continue;
+ case '0': flags |= F_ZERO; continue;
+ }
+ break;
+ }
+ if (c == '*') {
+ v = getnextarg(args, arglen, &argidx);
+ if (v == NULL)
+ goto error;
+ if (!PyInt_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "* wants int");
+ goto error;
+ }
+ width = PyInt_AsLong(v);
+ if (width < 0) {
+ flags |= F_LJUST;
+ width = -width;
+ }
+ if (--fmtcnt >= 0)
+ c = *fmt++;
+ }
+ else if (c >= 0 && isdigit(c)) {
+ width = c - '0';
+ while (--fmtcnt >= 0) {
+ c = Py_CHARMASK(*fmt++);
+ if (!isdigit(c))
+ break;
+ if ((width*10) / 10 != width) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "width too big");
+ goto error;
+ }
+ width = width*10 + (c - '0');
+ }
+ }
+ if (c == '.') {
+ prec = 0;
+ if (--fmtcnt >= 0)
+ c = *fmt++;
+ if (c == '*') {
+ v = getnextarg(args, arglen, &argidx);
+ if (v == NULL)
+ goto error;
+ if (!PyInt_Check(v)) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "* wants int");
+ goto error;
+ }
+ prec = PyInt_AsLong(v);
+ if (prec < 0)
+ prec = 0;
+ if (--fmtcnt >= 0)
+ c = *fmt++;
+ }
+ else if (c >= 0 && isdigit(c)) {
+ prec = c - '0';
+ while (--fmtcnt >= 0) {
+ c = Py_CHARMASK(*fmt++);
+ if (!isdigit(c))
+ break;
+ if ((prec*10) / 10 != prec) {
+ PyErr_SetString(
+ PyExc_ValueError,
+ "prec too big");
+ goto error;
+ }
+ prec = prec*10 + (c - '0');
+ }
+ }
+ } /* prec */
+ if (fmtcnt >= 0) {
+ if (c == 'h' || c == 'l' || c == 'L') {
+ if (--fmtcnt >= 0)
+ c = *fmt++;
+ }
+ }
+ if (fmtcnt < 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "incomplete format");
+ goto error;
+ }
+ if (c != '%') {
+ v = getnextarg(args, arglen, &argidx);
+ if (v == NULL)
+ goto error;
+ }
+ sign = 0;
+ fill = ' ';
+ switch (c) {
+ case '%':
+ pbuf = "%";
+ len = 1;
+ break;
+ case 's':
#ifdef Py_USING_UNICODE
- if (temp != NULL && PyUnicode_Check(temp)) {
- Py_DECREF(temp);
- fmt = fmt_start;
- argidx = argidx_start;
- goto unicode;
- }
+ if (PyUnicode_Check(v)) {
+ fmt = fmt_start;
+ argidx = argidx_start;
+ goto unicode;
+ }
#endif
- /* Fall through */
- case 'r':
- if (c == 'r')
- temp = PyObject_Repr(v);
- if (temp == NULL)
- goto error;
- if (!PyString_Check(temp)) {
- PyErr_SetString(PyExc_TypeError,
- "%s argument has non-string str()");
- Py_DECREF(temp);
- goto error;
- }
- pbuf = PyString_AS_STRING(temp);
- len = PyString_GET_SIZE(temp);
- if (prec >= 0 && len > prec)
- len = prec;
- break;
- case 'i':
- case 'd':
- case 'u':
- case 'o':
- case 'x':
- case 'X':
- if (c == 'i')
- c = 'd';
- isnumok = 0;
- if (PyNumber_Check(v)) {
- PyObject *iobj=NULL;
-
- if (PyInt_Check(v) || (PyLong_Check(v))) {
- iobj = v;
- Py_INCREF(iobj);
- }
- else {
- iobj = PyNumber_Int(v);
- if (iobj==NULL) iobj = PyNumber_Long(v);
- }
- if (iobj!=NULL) {
- if (PyInt_Check(iobj)) {
- isnumok = 1;
- pbuf = formatbuf;
- len = formatint(pbuf,
- sizeof(formatbuf),
- flags, prec, c, iobj);
- Py_DECREF(iobj);
- if (len < 0)
- goto error;
- sign = 1;
- }
- else if (PyLong_Check(iobj)) {
- int ilen;
-
- isnumok = 1;
- temp = _PyString_FormatLong(iobj, flags,
- prec, c, &pbuf, &ilen);
- Py_DECREF(iobj);
- len = ilen;
- if (!temp)
- goto error;
- sign = 1;
- }
- else {
- Py_DECREF(iobj);
- }
- }
- }
- if (!isnumok) {
- PyErr_Format(PyExc_TypeError,
- "%%%c format: a number is required, "
- "not %.200s", c, Py_TYPE(v)->tp_name);
- goto error;
- }
- if (flags & F_ZERO)
- fill = '0';
- break;
- case 'e':
- case 'E':
- case 'f':
- case 'F':
- case 'g':
- case 'G':
- temp = formatfloat(v, flags, prec, c);
- if (temp == NULL)
- goto error;
- pbuf = PyString_AS_STRING(temp);
- len = PyString_GET_SIZE(temp);
- sign = 1;
- if (flags & F_ZERO)
- fill = '0';
- break;
- case 'c':
+ temp = _PyObject_Str(v);
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(v)) {
- fmt = fmt_start;
- argidx = argidx_start;
- goto unicode;
- }
+ if (temp != NULL && PyUnicode_Check(temp)) {
+ Py_DECREF(temp);
+ fmt = fmt_start;
+ argidx = argidx_start;
+ goto unicode;
+ }
#endif
- pbuf = formatbuf;
- len = formatchar(pbuf, sizeof(formatbuf), v);
- if (len < 0)
- goto error;
- break;
- default:
- PyErr_Format(PyExc_ValueError,
- "unsupported format character '%c' (0x%x) "
- "at index %zd",
- c, c,
- (Py_ssize_t)(fmt - 1 -
- PyString_AsString(format)));
- goto error;
- }
- if (sign) {
- if (*pbuf == '-' || *pbuf == '+') {
- sign = *pbuf++;
- len--;
- }
- else if (flags & F_SIGN)
- sign = '+';
- else if (flags & F_BLANK)
- sign = ' ';
- else
- sign = 0;
- }
- if (width < len)
- width = len;
- if (rescnt - (sign != 0) < width) {
- reslen -= rescnt;
- rescnt = width + fmtcnt + 100;
- reslen += rescnt;
- if (reslen < 0) {
- Py_DECREF(result);
- Py_XDECREF(temp);
- return PyErr_NoMemory();
- }
- if (_PyString_Resize(&result, reslen)) {
- Py_XDECREF(temp);
- return NULL;
- }
- res = PyString_AS_STRING(result)
- + reslen - rescnt;
- }
- if (sign) {
- if (fill != ' ')
- *res++ = sign;
- rescnt--;
- if (width > len)
- width--;
- }
- if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
- assert(pbuf[0] == '0');
- assert(pbuf[1] == c);
- if (fill != ' ') {
- *res++ = *pbuf++;
- *res++ = *pbuf++;
- }
- rescnt -= 2;
- width -= 2;
- if (width < 0)
- width = 0;
- len -= 2;
- }
- if (width > len && !(flags & F_LJUST)) {
- do {
- --rescnt;
- *res++ = fill;
- } while (--width > len);
- }
- if (fill == ' ') {
- if (sign)
- *res++ = sign;
- if ((flags & F_ALT) &&
- (c == 'x' || c == 'X')) {
- assert(pbuf[0] == '0');
- assert(pbuf[1] == c);
- *res++ = *pbuf++;
- *res++ = *pbuf++;
- }
- }
- Py_MEMCPY(res, pbuf, len);
- res += len;
- rescnt -= len;
- while (--width >= len) {
- --rescnt;
- *res++ = ' ';
- }
- if (dict && (argidx < arglen) && c != '%') {
- PyErr_SetString(PyExc_TypeError,
- "not all arguments converted during string formatting");
- Py_XDECREF(temp);
+ /* Fall through */
+ case 'r':
+ if (c == 'r')
+ temp = PyObject_Repr(v);
+ if (temp == NULL)
+ goto error;
+ if (!PyString_Check(temp)) {
+ PyErr_SetString(PyExc_TypeError,
+ "%s argument has non-string str()");
+ Py_DECREF(temp);
+ goto error;
+ }
+ pbuf = PyString_AS_STRING(temp);
+ len = PyString_GET_SIZE(temp);
+ if (prec >= 0 && len > prec)
+ len = prec;
+ break;
+ case 'i':
+ case 'd':
+ case 'u':
+ case 'o':
+ case 'x':
+ case 'X':
+ if (c == 'i')
+ c = 'd';
+ isnumok = 0;
+ if (PyNumber_Check(v)) {
+ PyObject *iobj=NULL;
+
+ if (PyInt_Check(v) || (PyLong_Check(v))) {
+ iobj = v;
+ Py_INCREF(iobj);
+ }
+ else {
+ iobj = PyNumber_Int(v);
+ if (iobj==NULL) iobj = PyNumber_Long(v);
+ }
+ if (iobj!=NULL) {
+ if (PyInt_Check(iobj)) {
+ isnumok = 1;
+ pbuf = formatbuf;
+ len = formatint(pbuf,
+ sizeof(formatbuf),
+ flags, prec, c, iobj);
+ Py_DECREF(iobj);
+ if (len < 0)
+ goto error;
+ sign = 1;
+ }
+ else if (PyLong_Check(iobj)) {
+ int ilen;
+
+ isnumok = 1;
+ temp = _PyString_FormatLong(iobj, flags,
+ prec, c, &pbuf, &ilen);
+ Py_DECREF(iobj);
+ len = ilen;
+ if (!temp)
goto error;
+ sign = 1;
+ }
+ else {
+ Py_DECREF(iobj);
}
- Py_XDECREF(temp);
- } /* '%' */
- } /* until end */
- if (argidx < arglen && !dict) {
- PyErr_SetString(PyExc_TypeError,
- "not all arguments converted during string formatting");
- goto error;
- }
- if (args_owned) {
- Py_DECREF(args);
- }
- if (_PyString_Resize(&result, reslen - rescnt))
- return NULL;
- return result;
+ }
+ }
+ if (!isnumok) {
+ PyErr_Format(PyExc_TypeError,
+ "%%%c format: a number is required, "
+ "not %.200s", c, Py_TYPE(v)->tp_name);
+ goto error;
+ }
+ if (flags & F_ZERO)
+ fill = '0';
+ break;
+ case 'e':
+ case 'E':
+ case 'f':
+ case 'F':
+ case 'g':
+ case 'G':
+ temp = formatfloat(v, flags, prec, c);
+ if (temp == NULL)
+ goto error;
+ pbuf = PyString_AS_STRING(temp);
+ len = PyString_GET_SIZE(temp);
+ sign = 1;
+ if (flags & F_ZERO)
+ fill = '0';
+ break;
+ case 'c':
+#ifdef Py_USING_UNICODE
+ if (PyUnicode_Check(v)) {
+ fmt = fmt_start;
+ argidx = argidx_start;
+ goto unicode;
+ }
+#endif
+ pbuf = formatbuf;
+ len = formatchar(pbuf, sizeof(formatbuf), v);
+ if (len < 0)
+ goto error;
+ break;
+ default:
+ PyErr_Format(PyExc_ValueError,
+ "unsupported format character '%c' (0x%x) "
+ "at index %zd",
+ c, c,
+ (Py_ssize_t)(fmt - 1 -
+ PyString_AsString(format)));
+ goto error;
+ }
+ if (sign) {
+ if (*pbuf == '-' || *pbuf == '+') {
+ sign = *pbuf++;
+ len--;
+ }
+ else if (flags & F_SIGN)
+ sign = '+';
+ else if (flags & F_BLANK)
+ sign = ' ';
+ else
+ sign = 0;
+ }
+ if (width < len)
+ width = len;
+ if (rescnt - (sign != 0) < width) {
+ reslen -= rescnt;
+ rescnt = width + fmtcnt + 100;
+ reslen += rescnt;
+ if (reslen < 0) {
+ Py_DECREF(result);
+ Py_XDECREF(temp);
+ return PyErr_NoMemory();
+ }
+ if (_PyString_Resize(&result, reslen)) {
+ Py_XDECREF(temp);
+ return NULL;
+ }
+ res = PyString_AS_STRING(result)
+ + reslen - rescnt;
+ }
+ if (sign) {
+ if (fill != ' ')
+ *res++ = sign;
+ rescnt--;
+ if (width > len)
+ width--;
+ }
+ if ((flags & F_ALT) && (c == 'x' || c == 'X')) {
+ assert(pbuf[0] == '0');
+ assert(pbuf[1] == c);
+ if (fill != ' ') {
+ *res++ = *pbuf++;
+ *res++ = *pbuf++;
+ }
+ rescnt -= 2;
+ width -= 2;
+ if (width < 0)
+ width = 0;
+ len -= 2;
+ }
+ if (width > len && !(flags & F_LJUST)) {
+ do {
+ --rescnt;
+ *res++ = fill;
+ } while (--width > len);
+ }
+ if (fill == ' ') {
+ if (sign)
+ *res++ = sign;
+ if ((flags & F_ALT) &&
+ (c == 'x' || c == 'X')) {
+ assert(pbuf[0] == '0');
+ assert(pbuf[1] == c);
+ *res++ = *pbuf++;
+ *res++ = *pbuf++;
+ }
+ }
+ Py_MEMCPY(res, pbuf, len);
+ res += len;
+ rescnt -= len;
+ while (--width >= len) {
+ --rescnt;
+ *res++ = ' ';
+ }
+ if (dict && (argidx < arglen) && c != '%') {
+ PyErr_SetString(PyExc_TypeError,
+ "not all arguments converted during string formatting");
+ Py_XDECREF(temp);
+ goto error;
+ }
+ Py_XDECREF(temp);
+ } /* '%' */
+ } /* until end */
+ if (argidx < arglen && !dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "not all arguments converted during string formatting");
+ goto error;
+ }
+ if (args_owned) {
+ Py_DECREF(args);
+ }
+ if (_PyString_Resize(&result, reslen - rescnt))
+ return NULL;
+ return result;
#ifdef Py_USING_UNICODE
unicode:
- if (args_owned) {
- Py_DECREF(args);
- args_owned = 0;
- }
- /* Fiddle args right (remove the first argidx arguments) */
- if (PyTuple_Check(orig_args) && argidx > 0) {
- PyObject *v;
- Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
- v = PyTuple_New(n);
- if (v == NULL)
- goto error;
- while (--n >= 0) {
- PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
- Py_INCREF(w);
- PyTuple_SET_ITEM(v, n, w);
- }
- args = v;
- } else {
- Py_INCREF(orig_args);
- args = orig_args;
- }
- args_owned = 1;
- /* Take what we have of the result and let the Unicode formatting
- function format the rest of the input. */
- rescnt = res - PyString_AS_STRING(result);
- if (_PyString_Resize(&result, rescnt))
- goto error;
- fmtcnt = PyString_GET_SIZE(format) - \
- (fmt - PyString_AS_STRING(format));
- format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
- if (format == NULL)
- goto error;
- v = PyUnicode_Format(format, args);
- Py_DECREF(format);
- if (v == NULL)
- goto error;
- /* Paste what we have (result) to what the Unicode formatting
- function returned (v) and return the result (or error) */
- w = PyUnicode_Concat(result, v);
- Py_DECREF(result);
- Py_DECREF(v);
- Py_DECREF(args);
- return w;
+ if (args_owned) {
+ Py_DECREF(args);
+ args_owned = 0;
+ }
+ /* Fiddle args right (remove the first argidx arguments) */
+ if (PyTuple_Check(orig_args) && argidx > 0) {
+ PyObject *v;
+ Py_ssize_t n = PyTuple_GET_SIZE(orig_args) - argidx;
+ v = PyTuple_New(n);
+ if (v == NULL)
+ goto error;
+ while (--n >= 0) {
+ PyObject *w = PyTuple_GET_ITEM(orig_args, n + argidx);
+ Py_INCREF(w);
+ PyTuple_SET_ITEM(v, n, w);
+ }
+ args = v;
+ } else {
+ Py_INCREF(orig_args);
+ args = orig_args;
+ }
+ args_owned = 1;
+ /* Take what we have of the result and let the Unicode formatting
+ function format the rest of the input. */
+ rescnt = res - PyString_AS_STRING(result);
+ if (_PyString_Resize(&result, rescnt))
+ goto error;
+ fmtcnt = PyString_GET_SIZE(format) - \
+ (fmt - PyString_AS_STRING(format));
+ format = PyUnicode_Decode(fmt, fmtcnt, NULL, NULL);
+ if (format == NULL)
+ goto error;
+ v = PyUnicode_Format(format, args);
+ Py_DECREF(format);
+ if (v == NULL)
+ goto error;
+ /* Paste what we have (result) to what the Unicode formatting
+ function returned (v) and return the result (or error) */
+ w = PyUnicode_Concat(result, v);
+ Py_DECREF(result);
+ Py_DECREF(v);
+ Py_DECREF(args);
+ return w;
#endif /* Py_USING_UNICODE */
error:
- Py_DECREF(result);
- if (args_owned) {
- Py_DECREF(args);
- }
- return NULL;
+ Py_DECREF(result);
+ if (args_owned) {
+ Py_DECREF(args);
+ }
+ return NULL;
}
void
PyString_InternInPlace(PyObject **p)
{
- register PyStringObject *s = (PyStringObject *)(*p);
- PyObject *t;
- if (s == NULL || !PyString_Check(s))
- Py_FatalError("PyString_InternInPlace: strings only please!");
- /* If it's a string subclass, we don't really know what putting
- it in the interned dict might do. */
- if (!PyString_CheckExact(s))
- return;
- if (PyString_CHECK_INTERNED(s))
- return;
- if (interned == NULL) {
- interned = PyDict_New();
- if (interned == NULL) {
- PyErr_Clear(); /* Don't leave an exception */
- return;
- }
- }
- t = PyDict_GetItem(interned, (PyObject *)s);
- if (t) {
- Py_INCREF(t);
- Py_DECREF(*p);
- *p = t;
- return;
- }
-
- if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
- PyErr_Clear();
- return;
- }
- /* The two references in interned are not counted by refcnt.
- The string deallocator will take care of this */
- Py_REFCNT(s) -= 2;
- PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
+ register PyStringObject *s = (PyStringObject *)(*p);
+ PyObject *t;
+ if (s == NULL || !PyString_Check(s))
+ Py_FatalError("PyString_InternInPlace: strings only please!");
+ /* If it's a string subclass, we don't really know what putting
+ it in the interned dict might do. */
+ if (!PyString_CheckExact(s))
+ return;
+ if (PyString_CHECK_INTERNED(s))
+ return;
+ if (interned == NULL) {
+ interned = PyDict_New();
+ if (interned == NULL) {
+ PyErr_Clear(); /* Don't leave an exception */
+ return;
+ }
+ }
+ t = PyDict_GetItem(interned, (PyObject *)s);
+ if (t) {
+ Py_INCREF(t);
+ Py_DECREF(*p);
+ *p = t;
+ return;
+ }
+
+ if (PyDict_SetItem(interned, (PyObject *)s, (PyObject *)s) < 0) {
+ PyErr_Clear();
+ return;
+ }
+ /* The two references in interned are not counted by refcnt.
+ The string deallocator will take care of this */
+ Py_REFCNT(s) -= 2;
+ PyString_CHECK_INTERNED(s) = SSTATE_INTERNED_MORTAL;
}
void
PyString_InternImmortal(PyObject **p)
{
- PyString_InternInPlace(p);
- if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
- PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
- Py_INCREF(*p);
- }
+ PyString_InternInPlace(p);
+ if (PyString_CHECK_INTERNED(*p) != SSTATE_INTERNED_IMMORTAL) {
+ PyString_CHECK_INTERNED(*p) = SSTATE_INTERNED_IMMORTAL;
+ Py_INCREF(*p);
+ }
}
PyObject *
PyString_InternFromString(const char *cp)
{
- PyObject *s = PyString_FromString(cp);
- if (s == NULL)
- return NULL;
- PyString_InternInPlace(&s);
- return s;
+ PyObject *s = PyString_FromString(cp);
+ if (s == NULL)
+ return NULL;
+ PyString_InternInPlace(&s);
+ return s;
}
void
PyString_Fini(void)
{
- int i;
- for (i = 0; i < UCHAR_MAX + 1; i++) {
- Py_XDECREF(characters[i]);
- characters[i] = NULL;
- }
- Py_XDECREF(nullstring);
- nullstring = NULL;
+ int i;
+ for (i = 0; i < UCHAR_MAX + 1; i++) {
+ Py_XDECREF(characters[i]);
+ characters[i] = NULL;
+ }
+ Py_XDECREF(nullstring);
+ nullstring = NULL;
}
void _Py_ReleaseInternedStrings(void)
{
- PyObject *keys;
- PyStringObject *s;
- Py_ssize_t i, n;
- Py_ssize_t immortal_size = 0, mortal_size = 0;
-
- if (interned == NULL || !PyDict_Check(interned))
- return;
- keys = PyDict_Keys(interned);
- if (keys == NULL || !PyList_Check(keys)) {
- PyErr_Clear();
- return;
- }
-
- /* Since _Py_ReleaseInternedStrings() is intended to help a leak
- detector, interned strings are not forcibly deallocated; rather, we
- give them their stolen references back, and then clear and DECREF
- the interned dict. */
-
- n = PyList_GET_SIZE(keys);
- fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
- n);
- for (i = 0; i < n; i++) {
- s = (PyStringObject *) PyList_GET_ITEM(keys, i);
- switch (s->ob_sstate) {
- case SSTATE_NOT_INTERNED:
- /* XXX Shouldn't happen */
- break;
- case SSTATE_INTERNED_IMMORTAL:
- Py_REFCNT(s) += 1;
- immortal_size += Py_SIZE(s);
- break;
- case SSTATE_INTERNED_MORTAL:
- Py_REFCNT(s) += 2;
- mortal_size += Py_SIZE(s);
- break;
- default:
- Py_FatalError("Inconsistent interned string state.");
- }
- s->ob_sstate = SSTATE_NOT_INTERNED;
- }
- fprintf(stderr, "total size of all interned strings: "
- "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
- "mortal/immortal\n", mortal_size, immortal_size);
- Py_DECREF(keys);
- PyDict_Clear(interned);
- Py_DECREF(interned);
- interned = NULL;
+ PyObject *keys;
+ PyStringObject *s;
+ Py_ssize_t i, n;
+ Py_ssize_t immortal_size = 0, mortal_size = 0;
+
+ if (interned == NULL || !PyDict_Check(interned))
+ return;
+ keys = PyDict_Keys(interned);
+ if (keys == NULL || !PyList_Check(keys)) {
+ PyErr_Clear();
+ return;
+ }
+
+ /* Since _Py_ReleaseInternedStrings() is intended to help a leak
+ detector, interned strings are not forcibly deallocated; rather, we
+ give them their stolen references back, and then clear and DECREF
+ the interned dict. */
+
+ n = PyList_GET_SIZE(keys);
+ fprintf(stderr, "releasing %" PY_FORMAT_SIZE_T "d interned strings\n",
+ n);
+ for (i = 0; i < n; i++) {
+ s = (PyStringObject *) PyList_GET_ITEM(keys, i);
+ switch (s->ob_sstate) {
+ case SSTATE_NOT_INTERNED:
+ /* XXX Shouldn't happen */
+ break;
+ case SSTATE_INTERNED_IMMORTAL:
+ Py_REFCNT(s) += 1;
+ immortal_size += Py_SIZE(s);
+ break;
+ case SSTATE_INTERNED_MORTAL:
+ Py_REFCNT(s) += 2;
+ mortal_size += Py_SIZE(s);
+ break;
+ default:
+ Py_FatalError("Inconsistent interned string state.");
+ }
+ s->ob_sstate = SSTATE_NOT_INTERNED;
+ }
+ fprintf(stderr, "total size of all interned strings: "
+ "%" PY_FORMAT_SIZE_T "d/%" PY_FORMAT_SIZE_T "d "
+ "mortal/immortal\n", mortal_size, immortal_size);
+ Py_DECREF(keys);
+ PyDict_Clear(interned);
+ Py_DECREF(interned);
+ interned = NULL;
}
diff --git a/Objects/structseq.c b/Objects/structseq.c
index ad246a1..58e15cb 100644
--- a/Objects/structseq.c
+++ b/Objects/structseq.c
@@ -9,7 +9,7 @@ static char visible_length_key[] = "n_sequence_fields";
static char real_length_key[] = "n_fields";
static char unnamed_fields_key[] = "n_unnamed_fields";
-/* Fields with this name have only a field index, not a field name.
+/* Fields with this name have only a field index, not a field name.
They are only allowed for indices < n_visible_fields. */
char *PyStructSequence_UnnamedField = "unnamed field";
@@ -29,511 +29,511 @@ char *PyStructSequence_UnnamedField = "unnamed field";
PyObject *
PyStructSequence_New(PyTypeObject *type)
{
- PyStructSequence *obj;
+ PyStructSequence *obj;
- obj = PyObject_New(PyStructSequence, type);
- if (obj == NULL)
- return NULL;
- Py_SIZE(obj) = VISIBLE_SIZE_TP(type);
+ obj = PyObject_New(PyStructSequence, type);
+ if (obj == NULL)
+ return NULL;
+ Py_SIZE(obj) = VISIBLE_SIZE_TP(type);
- return (PyObject*) obj;
+ return (PyObject*) obj;
}
static void
structseq_dealloc(PyStructSequence *obj)
{
- Py_ssize_t i, size;
+ Py_ssize_t i, size;
- size = REAL_SIZE(obj);
- for (i = 0; i < size; ++i) {
- Py_XDECREF(obj->ob_item[i]);
- }
- PyObject_Del(obj);
+ size = REAL_SIZE(obj);
+ for (i = 0; i < size; ++i) {
+ Py_XDECREF(obj->ob_item[i]);
+ }
+ PyObject_Del(obj);
}
static Py_ssize_t
structseq_length(PyStructSequence *obj)
{
- return VISIBLE_SIZE(obj);
+ return VISIBLE_SIZE(obj);
}
static PyObject*
structseq_item(PyStructSequence *obj, Py_ssize_t i)
{
- if (i < 0 || i >= VISIBLE_SIZE(obj)) {
- PyErr_SetString(PyExc_IndexError, "tuple index out of range");
- return NULL;
- }
- Py_INCREF(obj->ob_item[i]);
- return obj->ob_item[i];
+ if (i < 0 || i >= VISIBLE_SIZE(obj)) {
+ PyErr_SetString(PyExc_IndexError, "tuple index out of range");
+ return NULL;
+ }
+ Py_INCREF(obj->ob_item[i]);
+ return obj->ob_item[i];
}
static PyObject*
structseq_slice(PyStructSequence *obj, Py_ssize_t low, Py_ssize_t high)
{
- PyTupleObject *np;
- Py_ssize_t i;
-
- if (low < 0)
- low = 0;
- if (high > VISIBLE_SIZE(obj))
- high = VISIBLE_SIZE(obj);
- if (high < low)
- high = low;
- np = (PyTupleObject *)PyTuple_New(high-low);
- if (np == NULL)
- return NULL;
- for(i = low; i < high; ++i) {
- PyObject *v = obj->ob_item[i];
- Py_INCREF(v);
- PyTuple_SET_ITEM(np, i-low, v);
- }
- return (PyObject *) np;
+ PyTupleObject *np;
+ Py_ssize_t i;
+
+ if (low < 0)
+ low = 0;
+ if (high > VISIBLE_SIZE(obj))
+ high = VISIBLE_SIZE(obj);
+ if (high < low)
+ high = low;
+ np = (PyTupleObject *)PyTuple_New(high-low);
+ if (np == NULL)
+ return NULL;
+ for(i = low; i < high; ++i) {
+ PyObject *v = obj->ob_item[i];
+ Py_INCREF(v);
+ PyTuple_SET_ITEM(np, i-low, v);
+ }
+ return (PyObject *) np;
}
static PyObject *
structseq_subscript(PyStructSequence *self, PyObject *item)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
-
- if (i < 0)
- i += VISIBLE_SIZE(self);
-
- if (i < 0 || i >= VISIBLE_SIZE(self)) {
- PyErr_SetString(PyExc_IndexError,
- "tuple index out of range");
- return NULL;
- }
- Py_INCREF(self->ob_item[i]);
- return self->ob_item[i];
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelen, cur, i;
- PyObject *result;
-
- if (PySlice_GetIndicesEx((PySliceObject *)item,
- VISIBLE_SIZE(self), &start, &stop,
- &step, &slicelen) < 0) {
- return NULL;
- }
- if (slicelen <= 0)
- return PyTuple_New(0);
- result = PyTuple_New(slicelen);
- if (result == NULL)
- return NULL;
- for (cur = start, i = 0; i < slicelen;
- cur += step, i++) {
- PyObject *v = self->ob_item[cur];
- Py_INCREF(v);
- PyTuple_SET_ITEM(result, i, v);
- }
- return result;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "structseq index must be integer");
- return NULL;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+
+ if (i < 0)
+ i += VISIBLE_SIZE(self);
+
+ if (i < 0 || i >= VISIBLE_SIZE(self)) {
+ PyErr_SetString(PyExc_IndexError,
+ "tuple index out of range");
+ return NULL;
+ }
+ Py_INCREF(self->ob_item[i]);
+ return self->ob_item[i];
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelen, cur, i;
+ PyObject *result;
+
+ if (PySlice_GetIndicesEx((PySliceObject *)item,
+ VISIBLE_SIZE(self), &start, &stop,
+ &step, &slicelen) < 0) {
+ return NULL;
+ }
+ if (slicelen <= 0)
+ return PyTuple_New(0);
+ result = PyTuple_New(slicelen);
+ if (result == NULL)
+ return NULL;
+ for (cur = start, i = 0; i < slicelen;
+ cur += step, i++) {
+ PyObject *v = self->ob_item[cur];
+ Py_INCREF(v);
+ PyTuple_SET_ITEM(result, i, v);
+ }
+ return result;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "structseq index must be integer");
+ return NULL;
+ }
}
static PyObject *
structseq_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *arg = NULL;
- PyObject *dict = NULL;
- PyObject *ob;
- PyStructSequence *res = NULL;
- Py_ssize_t len, min_len, max_len, i, n_unnamed_fields;
- static char *kwlist[] = {"sequence", "dict", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq",
- kwlist, &arg, &dict))
- return NULL;
-
- arg = PySequence_Fast(arg, "constructor requires a sequence");
-
- if (!arg) {
- return NULL;
- }
-
- if (dict && !PyDict_Check(dict)) {
- PyErr_Format(PyExc_TypeError,
- "%.500s() takes a dict as second arg, if any",
- type->tp_name);
- Py_DECREF(arg);
- return NULL;
- }
-
- len = PySequence_Fast_GET_SIZE(arg);
- min_len = VISIBLE_SIZE_TP(type);
- max_len = REAL_SIZE_TP(type);
- n_unnamed_fields = UNNAMED_FIELDS_TP(type);
-
- if (min_len != max_len) {
- if (len < min_len) {
- PyErr_Format(PyExc_TypeError,
- "%.500s() takes an at least %zd-sequence (%zd-sequence given)",
- type->tp_name, min_len, len);
- Py_DECREF(arg);
- return NULL;
- }
-
- if (len > max_len) {
- PyErr_Format(PyExc_TypeError,
- "%.500s() takes an at most %zd-sequence (%zd-sequence given)",
- type->tp_name, max_len, len);
- Py_DECREF(arg);
- return NULL;
- }
- }
- else {
- if (len != min_len) {
- PyErr_Format(PyExc_TypeError,
- "%.500s() takes a %zd-sequence (%zd-sequence given)",
- type->tp_name, min_len, len);
- Py_DECREF(arg);
- return NULL;
- }
- }
-
- res = (PyStructSequence*) PyStructSequence_New(type);
- if (res == NULL) {
- return NULL;
- }
- for (i = 0; i < len; ++i) {
- PyObject *v = PySequence_Fast_GET_ITEM(arg, i);
- Py_INCREF(v);
- res->ob_item[i] = v;
- }
- for (; i < max_len; ++i) {
- if (dict && (ob = PyDict_GetItemString(
- dict, type->tp_members[i-n_unnamed_fields].name))) {
- }
- else {
- ob = Py_None;
- }
- Py_INCREF(ob);
- res->ob_item[i] = ob;
- }
-
- Py_DECREF(arg);
- return (PyObject*) res;
+ PyObject *arg = NULL;
+ PyObject *dict = NULL;
+ PyObject *ob;
+ PyStructSequence *res = NULL;
+ Py_ssize_t len, min_len, max_len, i, n_unnamed_fields;
+ static char *kwlist[] = {"sequence", "dict", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:structseq",
+ kwlist, &arg, &dict))
+ return NULL;
+
+ arg = PySequence_Fast(arg, "constructor requires a sequence");
+
+ if (!arg) {
+ return NULL;
+ }
+
+ if (dict && !PyDict_Check(dict)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.500s() takes a dict as second arg, if any",
+ type->tp_name);
+ Py_DECREF(arg);
+ return NULL;
+ }
+
+ len = PySequence_Fast_GET_SIZE(arg);
+ min_len = VISIBLE_SIZE_TP(type);
+ max_len = REAL_SIZE_TP(type);
+ n_unnamed_fields = UNNAMED_FIELDS_TP(type);
+
+ if (min_len != max_len) {
+ if (len < min_len) {
+ PyErr_Format(PyExc_TypeError,
+ "%.500s() takes an at least %zd-sequence (%zd-sequence given)",
+ type->tp_name, min_len, len);
+ Py_DECREF(arg);
+ return NULL;
+ }
+
+ if (len > max_len) {
+ PyErr_Format(PyExc_TypeError,
+ "%.500s() takes an at most %zd-sequence (%zd-sequence given)",
+ type->tp_name, max_len, len);
+ Py_DECREF(arg);
+ return NULL;
+ }
+ }
+ else {
+ if (len != min_len) {
+ PyErr_Format(PyExc_TypeError,
+ "%.500s() takes a %zd-sequence (%zd-sequence given)",
+ type->tp_name, min_len, len);
+ Py_DECREF(arg);
+ return NULL;
+ }
+ }
+
+ res = (PyStructSequence*) PyStructSequence_New(type);
+ if (res == NULL) {
+ return NULL;
+ }
+ for (i = 0; i < len; ++i) {
+ PyObject *v = PySequence_Fast_GET_ITEM(arg, i);
+ Py_INCREF(v);
+ res->ob_item[i] = v;
+ }
+ for (; i < max_len; ++i) {
+ if (dict && (ob = PyDict_GetItemString(
+ dict, type->tp_members[i-n_unnamed_fields].name))) {
+ }
+ else {
+ ob = Py_None;
+ }
+ Py_INCREF(ob);
+ res->ob_item[i] = ob;
+ }
+
+ Py_DECREF(arg);
+ return (PyObject*) res;
}
static PyObject *
make_tuple(PyStructSequence *obj)
{
- return structseq_slice(obj, 0, VISIBLE_SIZE(obj));
+ return structseq_slice(obj, 0, VISIBLE_SIZE(obj));
}
static PyObject *
structseq_repr(PyStructSequence *obj)
{
- /* buffer and type size were chosen well considered. */
+ /* buffer and type size were chosen well considered. */
#define REPR_BUFFER_SIZE 512
#define TYPE_MAXSIZE 100
- PyObject *tup;
- PyTypeObject *typ = Py_TYPE(obj);
- int i, removelast = 0;
- Py_ssize_t len;
- char buf[REPR_BUFFER_SIZE];
- char *endofbuf, *pbuf = buf;
-
- /* pointer to end of writeable buffer; safes space for "...)\0" */
- endofbuf= &buf[REPR_BUFFER_SIZE-5];
-
- if ((tup = make_tuple(obj)) == NULL) {
- return NULL;
- }
-
- /* "typename(", limited to TYPE_MAXSIZE */
- len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE :
- strlen(typ->tp_name);
- strncpy(pbuf, typ->tp_name, len);
- pbuf += len;
- *pbuf++ = '(';
-
- for (i=0; i < VISIBLE_SIZE(obj); i++) {
- PyObject *val, *repr;
- char *cname, *crepr;
-
- cname = typ->tp_members[i].name;
-
- val = PyTuple_GetItem(tup, i);
- if (cname == NULL || val == NULL) {
- return NULL;
- }
- repr = PyObject_Repr(val);
- if (repr == NULL) {
- Py_DECREF(tup);
- return NULL;
- }
- crepr = PyString_AsString(repr);
- if (crepr == NULL) {
- Py_DECREF(tup);
- Py_DECREF(repr);
- return NULL;
- }
-
- /* + 3: keep space for "=" and ", " */
- len = strlen(cname) + strlen(crepr) + 3;
- if ((pbuf+len) <= endofbuf) {
- strcpy(pbuf, cname);
- pbuf += strlen(cname);
- *pbuf++ = '=';
- strcpy(pbuf, crepr);
- pbuf += strlen(crepr);
- *pbuf++ = ',';
- *pbuf++ = ' ';
- removelast = 1;
- Py_DECREF(repr);
- }
- else {
- strcpy(pbuf, "...");
- pbuf += 3;
- removelast = 0;
- Py_DECREF(repr);
- break;
- }
- }
- Py_DECREF(tup);
- if (removelast) {
- /* overwrite last ", " */
- pbuf-=2;
- }
- *pbuf++ = ')';
- *pbuf = '\0';
-
- return PyString_FromString(buf);
+ PyObject *tup;
+ PyTypeObject *typ = Py_TYPE(obj);
+ int i, removelast = 0;
+ Py_ssize_t len;
+ char buf[REPR_BUFFER_SIZE];
+ char *endofbuf, *pbuf = buf;
+
+ /* pointer to end of writeable buffer; safes space for "...)\0" */
+ endofbuf= &buf[REPR_BUFFER_SIZE-5];
+
+ if ((tup = make_tuple(obj)) == NULL) {
+ return NULL;
+ }
+
+ /* "typename(", limited to TYPE_MAXSIZE */
+ len = strlen(typ->tp_name) > TYPE_MAXSIZE ? TYPE_MAXSIZE :
+ strlen(typ->tp_name);
+ strncpy(pbuf, typ->tp_name, len);
+ pbuf += len;
+ *pbuf++ = '(';
+
+ for (i=0; i < VISIBLE_SIZE(obj); i++) {
+ PyObject *val, *repr;
+ char *cname, *crepr;
+
+ cname = typ->tp_members[i].name;
+
+ val = PyTuple_GetItem(tup, i);
+ if (cname == NULL || val == NULL) {
+ return NULL;
+ }
+ repr = PyObject_Repr(val);
+ if (repr == NULL) {
+ Py_DECREF(tup);
+ return NULL;
+ }
+ crepr = PyString_AsString(repr);
+ if (crepr == NULL) {
+ Py_DECREF(tup);
+ Py_DECREF(repr);
+ return NULL;
+ }
+
+ /* + 3: keep space for "=" and ", " */
+ len = strlen(cname) + strlen(crepr) + 3;
+ if ((pbuf+len) <= endofbuf) {
+ strcpy(pbuf, cname);
+ pbuf += strlen(cname);
+ *pbuf++ = '=';
+ strcpy(pbuf, crepr);
+ pbuf += strlen(crepr);
+ *pbuf++ = ',';
+ *pbuf++ = ' ';
+ removelast = 1;
+ Py_DECREF(repr);
+ }
+ else {
+ strcpy(pbuf, "...");
+ pbuf += 3;
+ removelast = 0;
+ Py_DECREF(repr);
+ break;
+ }
+ }
+ Py_DECREF(tup);
+ if (removelast) {
+ /* overwrite last ", " */
+ pbuf-=2;
+ }
+ *pbuf++ = ')';
+ *pbuf = '\0';
+
+ return PyString_FromString(buf);
}
static PyObject *
structseq_concat(PyStructSequence *obj, PyObject *b)
{
- PyObject *tup, *result;
- tup = make_tuple(obj);
- result = PySequence_Concat(tup, b);
- Py_DECREF(tup);
- return result;
+ PyObject *tup, *result;
+ tup = make_tuple(obj);
+ result = PySequence_Concat(tup, b);
+ Py_DECREF(tup);
+ return result;
}
static PyObject *
structseq_repeat(PyStructSequence *obj, Py_ssize_t n)
{
- PyObject *tup, *result;
- tup = make_tuple(obj);
- result = PySequence_Repeat(tup, n);
- Py_DECREF(tup);
- return result;
+ PyObject *tup, *result;
+ tup = make_tuple(obj);
+ result = PySequence_Repeat(tup, n);
+ Py_DECREF(tup);
+ return result;
}
static int
structseq_contains(PyStructSequence *obj, PyObject *o)
{
- PyObject *tup;
- int result;
- tup = make_tuple(obj);
- if (!tup)
- return -1;
- result = PySequence_Contains(tup, o);
- Py_DECREF(tup);
- return result;
+ PyObject *tup;
+ int result;
+ tup = make_tuple(obj);
+ if (!tup)
+ return -1;
+ result = PySequence_Contains(tup, o);
+ Py_DECREF(tup);
+ return result;
}
static long
structseq_hash(PyObject *obj)
{
- PyObject *tup;
- long result;
- tup = make_tuple((PyStructSequence*) obj);
- if (!tup)
- return -1;
- result = PyObject_Hash(tup);
- Py_DECREF(tup);
- return result;
+ PyObject *tup;
+ long result;
+ tup = make_tuple((PyStructSequence*) obj);
+ if (!tup)
+ return -1;
+ result = PyObject_Hash(tup);
+ Py_DECREF(tup);
+ return result;
}
static PyObject *
structseq_richcompare(PyObject *obj, PyObject *o2, int op)
{
- PyObject *tup, *result;
- tup = make_tuple((PyStructSequence*) obj);
- result = PyObject_RichCompare(tup, o2, op);
- Py_DECREF(tup);
- return result;
+ PyObject *tup, *result;
+ tup = make_tuple((PyStructSequence*) obj);
+ result = PyObject_RichCompare(tup, o2, op);
+ Py_DECREF(tup);
+ return result;
}
static PyObject *
structseq_reduce(PyStructSequence* self)
{
- PyObject* tup;
- PyObject* dict;
- PyObject* result;
- Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields;
- int i;
-
- n_fields = REAL_SIZE(self);
- n_visible_fields = VISIBLE_SIZE(self);
- n_unnamed_fields = UNNAMED_FIELDS(self);
- tup = PyTuple_New(n_visible_fields);
- if (!tup) {
- return NULL;
- }
-
- dict = PyDict_New();
- if (!dict) {
- Py_DECREF(tup);
- return NULL;
- }
-
- for (i = 0; i < n_visible_fields; i++) {
- Py_INCREF(self->ob_item[i]);
- PyTuple_SET_ITEM(tup, i, self->ob_item[i]);
- }
-
- for (; i < n_fields; i++) {
- char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name;
- PyDict_SetItemString(dict, n,
- self->ob_item[i]);
- }
-
- result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict);
-
- Py_DECREF(tup);
- Py_DECREF(dict);
-
- return result;
+ PyObject* tup;
+ PyObject* dict;
+ PyObject* result;
+ Py_ssize_t n_fields, n_visible_fields, n_unnamed_fields;
+ int i;
+
+ n_fields = REAL_SIZE(self);
+ n_visible_fields = VISIBLE_SIZE(self);
+ n_unnamed_fields = UNNAMED_FIELDS(self);
+ tup = PyTuple_New(n_visible_fields);
+ if (!tup) {
+ return NULL;
+ }
+
+ dict = PyDict_New();
+ if (!dict) {
+ Py_DECREF(tup);
+ return NULL;
+ }
+
+ for (i = 0; i < n_visible_fields; i++) {
+ Py_INCREF(self->ob_item[i]);
+ PyTuple_SET_ITEM(tup, i, self->ob_item[i]);
+ }
+
+ for (; i < n_fields; i++) {
+ char *n = Py_TYPE(self)->tp_members[i-n_unnamed_fields].name;
+ PyDict_SetItemString(dict, n,
+ self->ob_item[i]);
+ }
+
+ result = Py_BuildValue("(O(OO))", Py_TYPE(self), tup, dict);
+
+ Py_DECREF(tup);
+ Py_DECREF(dict);
+
+ return result;
}
static PySequenceMethods structseq_as_sequence = {
- (lenfunc)structseq_length,
- (binaryfunc)structseq_concat, /* sq_concat */
- (ssizeargfunc)structseq_repeat, /* sq_repeat */
- (ssizeargfunc)structseq_item, /* sq_item */
- (ssizessizeargfunc)structseq_slice, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)structseq_contains, /* sq_contains */
+ (lenfunc)structseq_length,
+ (binaryfunc)structseq_concat, /* sq_concat */
+ (ssizeargfunc)structseq_repeat, /* sq_repeat */
+ (ssizeargfunc)structseq_item, /* sq_item */
+ (ssizessizeargfunc)structseq_slice, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)structseq_contains, /* sq_contains */
};
static PyMappingMethods structseq_as_mapping = {
- (lenfunc)structseq_length,
- (binaryfunc)structseq_subscript,
+ (lenfunc)structseq_length,
+ (binaryfunc)structseq_subscript,
};
static PyMethodDef structseq_methods[] = {
- {"__reduce__", (PyCFunction)structseq_reduce,
- METH_NOARGS, NULL},
- {NULL, NULL}
+ {"__reduce__", (PyCFunction)structseq_reduce,
+ METH_NOARGS, NULL},
+ {NULL, NULL}
};
static PyTypeObject _struct_sequence_template = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- NULL, /* tp_name */
- 0, /* tp_basicsize */
- 0, /* tp_itemsize */
- (destructor)structseq_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)structseq_repr, /* tp_repr */
- 0, /* tp_as_number */
- &structseq_as_sequence, /* tp_as_sequence */
- &structseq_as_mapping, /* tp_as_mapping */
- structseq_hash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- NULL, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- structseq_richcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- structseq_methods, /* tp_methods */
- NULL, /* 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 */
- structseq_new, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ NULL, /* tp_name */
+ 0, /* tp_basicsize */
+ 0, /* tp_itemsize */
+ (destructor)structseq_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)structseq_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ &structseq_as_sequence, /* tp_as_sequence */
+ &structseq_as_mapping, /* tp_as_mapping */
+ structseq_hash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ NULL, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ structseq_richcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ structseq_methods, /* tp_methods */
+ NULL, /* 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 */
+ structseq_new, /* tp_new */
};
void
PyStructSequence_InitType(PyTypeObject *type, PyStructSequence_Desc *desc)
{
- PyObject *dict;
- PyMemberDef* members;
- int n_members, n_unnamed_members, i, k;
+ PyObject *dict;
+ PyMemberDef* members;
+ int n_members, n_unnamed_members, i, k;
#ifdef Py_TRACE_REFS
- /* if the type object was chained, unchain it first
- before overwriting its storage */
- if (type->_ob_next) {
- _Py_ForgetReference((PyObject*)type);
- }
+ /* if the type object was chained, unchain it first
+ before overwriting its storage */
+ if (type->_ob_next) {
+ _Py_ForgetReference((PyObject*)type);
+ }
#endif
- n_unnamed_members = 0;
- for (i = 0; desc->fields[i].name != NULL; ++i)
- if (desc->fields[i].name == PyStructSequence_UnnamedField)
- n_unnamed_members++;
- n_members = i;
-
- memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject));
- type->tp_name = desc->name;
- type->tp_doc = desc->doc;
- type->tp_basicsize = sizeof(PyStructSequence)+
- sizeof(PyObject*)*(n_members-1);
- type->tp_itemsize = 0;
-
- members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1);
- if (members == NULL)
- return;
-
- for (i = k = 0; i < n_members; ++i) {
- if (desc->fields[i].name == PyStructSequence_UnnamedField)
- continue;
- members[k].name = desc->fields[i].name;
- members[k].type = T_OBJECT;
- members[k].offset = offsetof(PyStructSequence, ob_item)
- + i * sizeof(PyObject*);
- members[k].flags = READONLY;
- members[k].doc = desc->fields[i].doc;
- k++;
- }
- members[k].name = NULL;
-
- type->tp_members = members;
-
- if (PyType_Ready(type) < 0)
- return;
- Py_INCREF(type);
-
- dict = type->tp_dict;
-#define SET_DICT_FROM_INT(key, value) \
- do { \
- PyObject *v = PyInt_FromLong((long) value); \
- if (v != NULL) { \
- PyDict_SetItemString(dict, key, v); \
- Py_DECREF(v); \
- } \
- } while (0)
-
- SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence);
- SET_DICT_FROM_INT(real_length_key, n_members);
- SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members);
+ n_unnamed_members = 0;
+ for (i = 0; desc->fields[i].name != NULL; ++i)
+ if (desc->fields[i].name == PyStructSequence_UnnamedField)
+ n_unnamed_members++;
+ n_members = i;
+
+ memcpy(type, &_struct_sequence_template, sizeof(PyTypeObject));
+ type->tp_name = desc->name;
+ type->tp_doc = desc->doc;
+ type->tp_basicsize = sizeof(PyStructSequence)+
+ sizeof(PyObject*)*(n_members-1);
+ type->tp_itemsize = 0;
+
+ members = PyMem_NEW(PyMemberDef, n_members-n_unnamed_members+1);
+ if (members == NULL)
+ return;
+
+ for (i = k = 0; i < n_members; ++i) {
+ if (desc->fields[i].name == PyStructSequence_UnnamedField)
+ continue;
+ members[k].name = desc->fields[i].name;
+ members[k].type = T_OBJECT;
+ members[k].offset = offsetof(PyStructSequence, ob_item)
+ + i * sizeof(PyObject*);
+ members[k].flags = READONLY;
+ members[k].doc = desc->fields[i].doc;
+ k++;
+ }
+ members[k].name = NULL;
+
+ type->tp_members = members;
+
+ if (PyType_Ready(type) < 0)
+ return;
+ Py_INCREF(type);
+
+ dict = type->tp_dict;
+#define SET_DICT_FROM_INT(key, value) \
+ do { \
+ PyObject *v = PyInt_FromLong((long) value); \
+ if (v != NULL) { \
+ PyDict_SetItemString(dict, key, v); \
+ Py_DECREF(v); \
+ } \
+ } while (0)
+
+ SET_DICT_FROM_INT(visible_length_key, desc->n_in_sequence);
+ SET_DICT_FROM_INT(real_length_key, n_members);
+ SET_DICT_FROM_INT(unnamed_fields_key, n_unnamed_members);
}
diff --git a/Objects/tupleobject.c b/Objects/tupleobject.c
index 143a62c..3249ccc 100644
--- a/Objects/tupleobject.c
+++ b/Objects/tupleobject.c
@@ -5,7 +5,7 @@
/* Speed optimization to avoid frequent malloc/free of small tuples */
#ifndef PyTuple_MAXSAVESIZE
-#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */
+#define PyTuple_MAXSAVESIZE 20 /* Largest tuple to save on free list */
#endif
#ifndef PyTuple_MAXFREELIST
#define PyTuple_MAXFREELIST 2000 /* Maximum number of tuples of each size to save */
@@ -35,12 +35,12 @@ static Py_ssize_t count_tracked = 0;
static void
show_track(void)
{
- fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n",
- count_tracked + count_untracked);
- fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T
- "d\n", count_tracked);
- fprintf(stderr, "%.2f%% tuple tracking rate\n\n",
- (100.0*count_tracked/(count_untracked+count_tracked)));
+ fprintf(stderr, "Tuples created: %" PY_FORMAT_SIZE_T "d\n",
+ count_tracked + count_untracked);
+ fprintf(stderr, "Tuples tracked by the GC: %" PY_FORMAT_SIZE_T
+ "d\n", count_tracked);
+ fprintf(stderr, "%.2f%% tuple tracking rate\n\n",
+ (100.0*count_tracked/(count_untracked+count_tracked)));
}
#endif
@@ -48,160 +48,160 @@ show_track(void)
PyObject *
PyTuple_New(register Py_ssize_t size)
{
- register PyTupleObject *op;
- Py_ssize_t i;
- if (size < 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
+ register PyTupleObject *op;
+ Py_ssize_t i;
+ if (size < 0) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
#if PyTuple_MAXSAVESIZE > 0
- if (size == 0 && free_list[0]) {
- op = free_list[0];
- Py_INCREF(op);
+ if (size == 0 && free_list[0]) {
+ op = free_list[0];
+ Py_INCREF(op);
#ifdef COUNT_ALLOCS
- tuple_zero_allocs++;
+ tuple_zero_allocs++;
#endif
- return (PyObject *) op;
- }
- if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) {
- free_list[size] = (PyTupleObject *) op->ob_item[0];
- numfree[size]--;
+ return (PyObject *) op;
+ }
+ if (size < PyTuple_MAXSAVESIZE && (op = free_list[size]) != NULL) {
+ free_list[size] = (PyTupleObject *) op->ob_item[0];
+ numfree[size]--;
#ifdef COUNT_ALLOCS
- fast_tuple_allocs++;
+ fast_tuple_allocs++;
#endif
- /* Inline PyObject_InitVar */
+ /* Inline PyObject_InitVar */
#ifdef Py_TRACE_REFS
- Py_SIZE(op) = size;
- Py_TYPE(op) = &PyTuple_Type;
+ Py_SIZE(op) = size;
+ Py_TYPE(op) = &PyTuple_Type;
#endif
- _Py_NewReference((PyObject *)op);
- }
- else
+ _Py_NewReference((PyObject *)op);
+ }
+ else
#endif
- {
- Py_ssize_t nbytes = size * sizeof(PyObject *);
- /* Check for overflow */
- if (nbytes / sizeof(PyObject *) != (size_t)size ||
- (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *)))
- {
- return PyErr_NoMemory();
- }
-
- op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size);
- if (op == NULL)
- return NULL;
- }
- for (i=0; i < size; i++)
- op->ob_item[i] = NULL;
+ {
+ Py_ssize_t nbytes = size * sizeof(PyObject *);
+ /* Check for overflow */
+ if (nbytes / sizeof(PyObject *) != (size_t)size ||
+ (nbytes > PY_SSIZE_T_MAX - sizeof(PyTupleObject) - sizeof(PyObject *)))
+ {
+ return PyErr_NoMemory();
+ }
+
+ op = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size);
+ if (op == NULL)
+ return NULL;
+ }
+ for (i=0; i < size; i++)
+ op->ob_item[i] = NULL;
#if PyTuple_MAXSAVESIZE > 0
- if (size == 0) {
- free_list[0] = op;
- ++numfree[0];
- Py_INCREF(op); /* extra INCREF so that this is never freed */
- }
+ if (size == 0) {
+ free_list[0] = op;
+ ++numfree[0];
+ Py_INCREF(op); /* extra INCREF so that this is never freed */
+ }
#endif
#ifdef SHOW_TRACK_COUNT
- count_tracked++;
+ count_tracked++;
#endif
- _PyObject_GC_TRACK(op);
- return (PyObject *) op;
+ _PyObject_GC_TRACK(op);
+ return (PyObject *) op;
}
Py_ssize_t
PyTuple_Size(register PyObject *op)
{
- if (!PyTuple_Check(op)) {
- PyErr_BadInternalCall();
- return -1;
- }
- else
- return Py_SIZE(op);
+ if (!PyTuple_Check(op)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ else
+ return Py_SIZE(op);
}
PyObject *
PyTuple_GetItem(register PyObject *op, register Py_ssize_t i)
{
- if (!PyTuple_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- if (i < 0 || i >= Py_SIZE(op)) {
- PyErr_SetString(PyExc_IndexError, "tuple index out of range");
- return NULL;
- }
- return ((PyTupleObject *)op) -> ob_item[i];
+ if (!PyTuple_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ if (i < 0 || i >= Py_SIZE(op)) {
+ PyErr_SetString(PyExc_IndexError, "tuple index out of range");
+ return NULL;
+ }
+ return ((PyTupleObject *)op) -> ob_item[i];
}
int
PyTuple_SetItem(register PyObject *op, register Py_ssize_t i, PyObject *newitem)
{
- register PyObject *olditem;
- register PyObject **p;
- if (!PyTuple_Check(op) || op->ob_refcnt != 1) {
- Py_XDECREF(newitem);
- PyErr_BadInternalCall();
- return -1;
- }
- if (i < 0 || i >= Py_SIZE(op)) {
- Py_XDECREF(newitem);
- PyErr_SetString(PyExc_IndexError,
- "tuple assignment index out of range");
- return -1;
- }
- p = ((PyTupleObject *)op) -> ob_item + i;
- olditem = *p;
- *p = newitem;
- Py_XDECREF(olditem);
- return 0;
+ register PyObject *olditem;
+ register PyObject **p;
+ if (!PyTuple_Check(op) || op->ob_refcnt != 1) {
+ Py_XDECREF(newitem);
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ if (i < 0 || i >= Py_SIZE(op)) {
+ Py_XDECREF(newitem);
+ PyErr_SetString(PyExc_IndexError,
+ "tuple assignment index out of range");
+ return -1;
+ }
+ p = ((PyTupleObject *)op) -> ob_item + i;
+ olditem = *p;
+ *p = newitem;
+ Py_XDECREF(olditem);
+ return 0;
}
void
_PyTuple_MaybeUntrack(PyObject *op)
{
- PyTupleObject *t;
- Py_ssize_t i, n;
-
- if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
- return;
- t = (PyTupleObject *) op;
- n = Py_SIZE(t);
- for (i = 0; i < n; i++) {
- PyObject *elt = PyTuple_GET_ITEM(t, i);
- /* Tuple with NULL elements aren't
- fully constructed, don't untrack
- them yet. */
- if (!elt ||
- _PyObject_GC_MAY_BE_TRACKED(elt))
- return;
- }
+ PyTupleObject *t;
+ Py_ssize_t i, n;
+
+ if (!PyTuple_CheckExact(op) || !_PyObject_GC_IS_TRACKED(op))
+ return;
+ t = (PyTupleObject *) op;
+ n = Py_SIZE(t);
+ for (i = 0; i < n; i++) {
+ PyObject *elt = PyTuple_GET_ITEM(t, i);
+ /* Tuple with NULL elements aren't
+ fully constructed, don't untrack
+ them yet. */
+ if (!elt ||
+ _PyObject_GC_MAY_BE_TRACKED(elt))
+ return;
+ }
#ifdef SHOW_TRACK_COUNT
- count_tracked--;
- count_untracked++;
+ count_tracked--;
+ count_untracked++;
#endif
- _PyObject_GC_UNTRACK(op);
+ _PyObject_GC_UNTRACK(op);
}
PyObject *
PyTuple_Pack(Py_ssize_t n, ...)
{
- Py_ssize_t i;
- PyObject *o;
- PyObject *result;
- PyObject **items;
- va_list vargs;
-
- va_start(vargs, n);
- result = PyTuple_New(n);
- if (result == NULL)
- return NULL;
- items = ((PyTupleObject *)result)->ob_item;
- for (i = 0; i < n; i++) {
- o = va_arg(vargs, PyObject *);
- Py_INCREF(o);
- items[i] = o;
- }
- va_end(vargs);
- return result;
+ Py_ssize_t i;
+ PyObject *o;
+ PyObject *result;
+ PyObject **items;
+ va_list vargs;
+
+ va_start(vargs, n);
+ result = PyTuple_New(n);
+ if (result == NULL)
+ return NULL;
+ items = ((PyTupleObject *)result)->ob_item;
+ for (i = 0; i < n; i++) {
+ o = va_arg(vargs, PyObject *);
+ Py_INCREF(o);
+ items[i] = o;
+ }
+ va_end(vargs);
+ return result;
}
@@ -210,430 +210,430 @@ PyTuple_Pack(Py_ssize_t n, ...)
static void
tupledealloc(register PyTupleObject *op)
{
- register Py_ssize_t i;
- register Py_ssize_t len = Py_SIZE(op);
- PyObject_GC_UnTrack(op);
- Py_TRASHCAN_SAFE_BEGIN(op)
- if (len > 0) {
- i = len;
- while (--i >= 0)
- Py_XDECREF(op->ob_item[i]);
+ register Py_ssize_t i;
+ register Py_ssize_t len = Py_SIZE(op);
+ PyObject_GC_UnTrack(op);
+ Py_TRASHCAN_SAFE_BEGIN(op)
+ if (len > 0) {
+ i = len;
+ while (--i >= 0)
+ Py_XDECREF(op->ob_item[i]);
#if PyTuple_MAXSAVESIZE > 0
- if (len < PyTuple_MAXSAVESIZE &&
- numfree[len] < PyTuple_MAXFREELIST &&
- Py_TYPE(op) == &PyTuple_Type)
- {
- op->ob_item[0] = (PyObject *) free_list[len];
- numfree[len]++;
- free_list[len] = op;
- goto done; /* return */
- }
+ if (len < PyTuple_MAXSAVESIZE &&
+ numfree[len] < PyTuple_MAXFREELIST &&
+ Py_TYPE(op) == &PyTuple_Type)
+ {
+ op->ob_item[0] = (PyObject *) free_list[len];
+ numfree[len]++;
+ free_list[len] = op;
+ goto done; /* return */
+ }
#endif
- }
- Py_TYPE(op)->tp_free((PyObject *)op);
+ }
+ Py_TYPE(op)->tp_free((PyObject *)op);
done:
- Py_TRASHCAN_SAFE_END(op)
+ Py_TRASHCAN_SAFE_END(op)
}
static int
tupleprint(PyTupleObject *op, FILE *fp, int flags)
{
- Py_ssize_t i;
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, "(");
- Py_END_ALLOW_THREADS
- for (i = 0; i < Py_SIZE(op); i++) {
- if (i > 0) {
- Py_BEGIN_ALLOW_THREADS
- fprintf(fp, ", ");
- Py_END_ALLOW_THREADS
- }
- if (PyObject_Print(op->ob_item[i], fp, 0) != 0)
- return -1;
- }
- i = Py_SIZE(op);
- Py_BEGIN_ALLOW_THREADS
- if (i == 1)
- fprintf(fp, ",");
- fprintf(fp, ")");
- Py_END_ALLOW_THREADS
- return 0;
+ Py_ssize_t i;
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, "(");
+ Py_END_ALLOW_THREADS
+ for (i = 0; i < Py_SIZE(op); i++) {
+ if (i > 0) {
+ Py_BEGIN_ALLOW_THREADS
+ fprintf(fp, ", ");
+ Py_END_ALLOW_THREADS
+ }
+ if (PyObject_Print(op->ob_item[i], fp, 0) != 0)
+ return -1;
+ }
+ i = Py_SIZE(op);
+ Py_BEGIN_ALLOW_THREADS
+ if (i == 1)
+ fprintf(fp, ",");
+ fprintf(fp, ")");
+ Py_END_ALLOW_THREADS
+ return 0;
}
static PyObject *
tuplerepr(PyTupleObject *v)
{
- Py_ssize_t i, n;
- PyObject *s, *temp;
- PyObject *pieces, *result = NULL;
-
- n = Py_SIZE(v);
- if (n == 0)
- return PyString_FromString("()");
-
- /* While not mutable, it is still possible to end up with a cycle in a
- tuple through an object that stores itself within a tuple (and thus
- infinitely asks for the repr of itself). This should only be
- possible within a type. */
- i = Py_ReprEnter((PyObject *)v);
- if (i != 0) {
- return i > 0 ? PyString_FromString("(...)") : NULL;
- }
-
- pieces = PyTuple_New(n);
- if (pieces == NULL)
- return NULL;
-
- /* Do repr() on each element. */
- for (i = 0; i < n; ++i) {
- if (Py_EnterRecursiveCall(" while getting the repr of a tuple"))
- goto Done;
- s = PyObject_Repr(v->ob_item[i]);
- Py_LeaveRecursiveCall();
- if (s == NULL)
- goto Done;
- PyTuple_SET_ITEM(pieces, i, s);
- }
-
- /* Add "()" decorations to the first and last items. */
- assert(n > 0);
- s = PyString_FromString("(");
- if (s == NULL)
- goto Done;
- temp = PyTuple_GET_ITEM(pieces, 0);
- PyString_ConcatAndDel(&s, temp);
- PyTuple_SET_ITEM(pieces, 0, s);
- if (s == NULL)
- goto Done;
-
- s = PyString_FromString(n == 1 ? ",)" : ")");
- if (s == NULL)
- goto Done;
- temp = PyTuple_GET_ITEM(pieces, n-1);
- PyString_ConcatAndDel(&temp, s);
- PyTuple_SET_ITEM(pieces, n-1, temp);
- if (temp == NULL)
- goto Done;
-
- /* Paste them all together with ", " between. */
- s = PyString_FromString(", ");
- if (s == NULL)
- goto Done;
- result = _PyString_Join(s, pieces);
- Py_DECREF(s);
+ Py_ssize_t i, n;
+ PyObject *s, *temp;
+ PyObject *pieces, *result = NULL;
+
+ n = Py_SIZE(v);
+ if (n == 0)
+ return PyString_FromString("()");
+
+ /* While not mutable, it is still possible to end up with a cycle in a
+ tuple through an object that stores itself within a tuple (and thus
+ infinitely asks for the repr of itself). This should only be
+ possible within a type. */
+ i = Py_ReprEnter((PyObject *)v);
+ if (i != 0) {
+ return i > 0 ? PyString_FromString("(...)") : NULL;
+ }
+
+ pieces = PyTuple_New(n);
+ if (pieces == NULL)
+ return NULL;
+
+ /* Do repr() on each element. */
+ for (i = 0; i < n; ++i) {
+ if (Py_EnterRecursiveCall(" while getting the repr of a tuple"))
+ goto Done;
+ s = PyObject_Repr(v->ob_item[i]);
+ Py_LeaveRecursiveCall();
+ if (s == NULL)
+ goto Done;
+ PyTuple_SET_ITEM(pieces, i, s);
+ }
+
+ /* Add "()" decorations to the first and last items. */
+ assert(n > 0);
+ s = PyString_FromString("(");
+ if (s == NULL)
+ goto Done;
+ temp = PyTuple_GET_ITEM(pieces, 0);
+ PyString_ConcatAndDel(&s, temp);
+ PyTuple_SET_ITEM(pieces, 0, s);
+ if (s == NULL)
+ goto Done;
+
+ s = PyString_FromString(n == 1 ? ",)" : ")");
+ if (s == NULL)
+ goto Done;
+ temp = PyTuple_GET_ITEM(pieces, n-1);
+ PyString_ConcatAndDel(&temp, s);
+ PyTuple_SET_ITEM(pieces, n-1, temp);
+ if (temp == NULL)
+ goto Done;
+
+ /* Paste them all together with ", " between. */
+ s = PyString_FromString(", ");
+ if (s == NULL)
+ goto Done;
+ result = _PyString_Join(s, pieces);
+ Py_DECREF(s);
Done:
- Py_DECREF(pieces);
- Py_ReprLeave((PyObject *)v);
- return result;
+ Py_DECREF(pieces);
+ Py_ReprLeave((PyObject *)v);
+ return result;
}
-/* The addend 82520, was selected from the range(0, 1000000) for
- generating the greatest number of prime multipliers for tuples
+/* The addend 82520, was selected from the range(0, 1000000) for
+ generating the greatest number of prime multipliers for tuples
upto length eight:
- 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533,
+ 1082527, 1165049, 1082531, 1165057, 1247581, 1330103, 1082533,
1330111, 1412633, 1165069, 1247599, 1495177, 1577699
*/
static long
tuplehash(PyTupleObject *v)
{
- register long x, y;
- register Py_ssize_t len = Py_SIZE(v);
- register PyObject **p;
- long mult = 1000003L;
- x = 0x345678L;
- p = v->ob_item;
- while (--len >= 0) {
- y = PyObject_Hash(*p++);
- if (y == -1)
- return -1;
- x = (x ^ y) * mult;
- /* the cast might truncate len; that doesn't change hash stability */
- mult += (long)(82520L + len + len);
- }
- x += 97531L;
- if (x == -1)
- x = -2;
- return x;
+ register long x, y;
+ register Py_ssize_t len = Py_SIZE(v);
+ register PyObject **p;
+ long mult = 1000003L;
+ x = 0x345678L;
+ p = v->ob_item;
+ while (--len >= 0) {
+ y = PyObject_Hash(*p++);
+ if (y == -1)
+ return -1;
+ x = (x ^ y) * mult;
+ /* the cast might truncate len; that doesn't change hash stability */
+ mult += (long)(82520L + len + len);
+ }
+ x += 97531L;
+ if (x == -1)
+ x = -2;
+ return x;
}
static Py_ssize_t
tuplelength(PyTupleObject *a)
{
- return Py_SIZE(a);
+ return Py_SIZE(a);
}
static int
tuplecontains(PyTupleObject *a, PyObject *el)
{
- Py_ssize_t i;
- int cmp;
+ Py_ssize_t i;
+ int cmp;
- for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
- cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i),
- Py_EQ);
- return cmp;
+ for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
+ cmp = PyObject_RichCompareBool(el, PyTuple_GET_ITEM(a, i),
+ Py_EQ);
+ return cmp;
}
static PyObject *
tupleitem(register PyTupleObject *a, register Py_ssize_t i)
{
- if (i < 0 || i >= Py_SIZE(a)) {
- PyErr_SetString(PyExc_IndexError, "tuple index out of range");
- return NULL;
- }
- Py_INCREF(a->ob_item[i]);
- return a->ob_item[i];
+ if (i < 0 || i >= Py_SIZE(a)) {
+ PyErr_SetString(PyExc_IndexError, "tuple index out of range");
+ return NULL;
+ }
+ Py_INCREF(a->ob_item[i]);
+ return a->ob_item[i];
}
static PyObject *
-tupleslice(register PyTupleObject *a, register Py_ssize_t ilow,
- register Py_ssize_t ihigh)
+tupleslice(register PyTupleObject *a, register Py_ssize_t ilow,
+ register Py_ssize_t ihigh)
{
- register PyTupleObject *np;
- PyObject **src, **dest;
- register Py_ssize_t i;
- Py_ssize_t len;
- if (ilow < 0)
- ilow = 0;
- if (ihigh > Py_SIZE(a))
- ihigh = Py_SIZE(a);
- if (ihigh < ilow)
- ihigh = ilow;
- if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) {
- Py_INCREF(a);
- return (PyObject *)a;
- }
- len = ihigh - ilow;
- np = (PyTupleObject *)PyTuple_New(len);
- if (np == NULL)
- return NULL;
- src = a->ob_item + ilow;
- dest = np->ob_item;
- for (i = 0; i < len; i++) {
- PyObject *v = src[i];
- Py_INCREF(v);
- dest[i] = v;
- }
- return (PyObject *)np;
+ register PyTupleObject *np;
+ PyObject **src, **dest;
+ register Py_ssize_t i;
+ Py_ssize_t len;
+ if (ilow < 0)
+ ilow = 0;
+ if (ihigh > Py_SIZE(a))
+ ihigh = Py_SIZE(a);
+ if (ihigh < ilow)
+ ihigh = ilow;
+ if (ilow == 0 && ihigh == Py_SIZE(a) && PyTuple_CheckExact(a)) {
+ Py_INCREF(a);
+ return (PyObject *)a;
+ }
+ len = ihigh - ilow;
+ np = (PyTupleObject *)PyTuple_New(len);
+ if (np == NULL)
+ return NULL;
+ src = a->ob_item + ilow;
+ dest = np->ob_item;
+ for (i = 0; i < len; i++) {
+ PyObject *v = src[i];
+ Py_INCREF(v);
+ dest[i] = v;
+ }
+ return (PyObject *)np;
}
PyObject *
PyTuple_GetSlice(PyObject *op, Py_ssize_t i, Py_ssize_t j)
{
- if (op == NULL || !PyTuple_Check(op)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- return tupleslice((PyTupleObject *)op, i, j);
+ if (op == NULL || !PyTuple_Check(op)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ return tupleslice((PyTupleObject *)op, i, j);
}
static PyObject *
tupleconcat(register PyTupleObject *a, register PyObject *bb)
{
- register Py_ssize_t size;
- register Py_ssize_t i;
- PyObject **src, **dest;
- PyTupleObject *np;
- if (!PyTuple_Check(bb)) {
- PyErr_Format(PyExc_TypeError,
- "can only concatenate tuple (not \"%.200s\") to tuple",
- Py_TYPE(bb)->tp_name);
- return NULL;
- }
+ register Py_ssize_t size;
+ register Py_ssize_t i;
+ PyObject **src, **dest;
+ PyTupleObject *np;
+ if (!PyTuple_Check(bb)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only concatenate tuple (not \"%.200s\") to tuple",
+ Py_TYPE(bb)->tp_name);
+ return NULL;
+ }
#define b ((PyTupleObject *)bb)
- size = Py_SIZE(a) + Py_SIZE(b);
- if (size < 0)
- return PyErr_NoMemory();
- np = (PyTupleObject *) PyTuple_New(size);
- if (np == NULL) {
- return NULL;
- }
- src = a->ob_item;
- dest = np->ob_item;
- for (i = 0; i < Py_SIZE(a); i++) {
- PyObject *v = src[i];
- Py_INCREF(v);
- dest[i] = v;
- }
- src = b->ob_item;
- dest = np->ob_item + Py_SIZE(a);
- for (i = 0; i < Py_SIZE(b); i++) {
- PyObject *v = src[i];
- Py_INCREF(v);
- dest[i] = v;
- }
- return (PyObject *)np;
+ size = Py_SIZE(a) + Py_SIZE(b);
+ if (size < 0)
+ return PyErr_NoMemory();
+ np = (PyTupleObject *) PyTuple_New(size);
+ if (np == NULL) {
+ return NULL;
+ }
+ src = a->ob_item;
+ dest = np->ob_item;
+ for (i = 0; i < Py_SIZE(a); i++) {
+ PyObject *v = src[i];
+ Py_INCREF(v);
+ dest[i] = v;
+ }
+ src = b->ob_item;
+ dest = np->ob_item + Py_SIZE(a);
+ for (i = 0; i < Py_SIZE(b); i++) {
+ PyObject *v = src[i];
+ Py_INCREF(v);
+ dest[i] = v;
+ }
+ return (PyObject *)np;
#undef b
}
static PyObject *
tuplerepeat(PyTupleObject *a, Py_ssize_t n)
{
- Py_ssize_t i, j;
- Py_ssize_t size;
- PyTupleObject *np;
- PyObject **p, **items;
- if (n < 0)
- n = 0;
- if (Py_SIZE(a) == 0 || n == 1) {
- if (PyTuple_CheckExact(a)) {
- /* Since tuples are immutable, we can return a shared
- copy in this case */
- Py_INCREF(a);
- return (PyObject *)a;
- }
- if (Py_SIZE(a) == 0)
- return PyTuple_New(0);
- }
- size = Py_SIZE(a) * n;
- if (size/Py_SIZE(a) != n)
- return PyErr_NoMemory();
- np = (PyTupleObject *) PyTuple_New(size);
- if (np == NULL)
- return NULL;
- p = np->ob_item;
- items = a->ob_item;
- for (i = 0; i < n; i++) {
- for (j = 0; j < Py_SIZE(a); j++) {
- *p = items[j];
- Py_INCREF(*p);
- p++;
- }
- }
- return (PyObject *) np;
+ Py_ssize_t i, j;
+ Py_ssize_t size;
+ PyTupleObject *np;
+ PyObject **p, **items;
+ if (n < 0)
+ n = 0;
+ if (Py_SIZE(a) == 0 || n == 1) {
+ if (PyTuple_CheckExact(a)) {
+ /* Since tuples are immutable, we can return a shared
+ copy in this case */
+ Py_INCREF(a);
+ return (PyObject *)a;
+ }
+ if (Py_SIZE(a) == 0)
+ return PyTuple_New(0);
+ }
+ size = Py_SIZE(a) * n;
+ if (size/Py_SIZE(a) != n)
+ return PyErr_NoMemory();
+ np = (PyTupleObject *) PyTuple_New(size);
+ if (np == NULL)
+ return NULL;
+ p = np->ob_item;
+ items = a->ob_item;
+ for (i = 0; i < n; i++) {
+ for (j = 0; j < Py_SIZE(a); j++) {
+ *p = items[j];
+ Py_INCREF(*p);
+ p++;
+ }
+ }
+ return (PyObject *) np;
}
static PyObject *
tupleindex(PyTupleObject *self, PyObject *args)
{
- Py_ssize_t i, start=0, stop=Py_SIZE(self);
- PyObject *v;
-
- if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
- _PyEval_SliceIndex, &start,
- _PyEval_SliceIndex, &stop))
- return NULL;
- if (start < 0) {
- start += Py_SIZE(self);
- if (start < 0)
- start = 0;
- }
- if (stop < 0) {
- stop += Py_SIZE(self);
- if (stop < 0)
- stop = 0;
- }
- for (i = start; i < stop && i < Py_SIZE(self); i++) {
- int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
- if (cmp > 0)
- return PyInt_FromSsize_t(i);
- else if (cmp < 0)
- return NULL;
- }
- PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple");
- return NULL;
+ Py_ssize_t i, start=0, stop=Py_SIZE(self);
+ PyObject *v;
+
+ if (!PyArg_ParseTuple(args, "O|O&O&:index", &v,
+ _PyEval_SliceIndex, &start,
+ _PyEval_SliceIndex, &stop))
+ return NULL;
+ if (start < 0) {
+ start += Py_SIZE(self);
+ if (start < 0)
+ start = 0;
+ }
+ if (stop < 0) {
+ stop += Py_SIZE(self);
+ if (stop < 0)
+ stop = 0;
+ }
+ for (i = start; i < stop && i < Py_SIZE(self); i++) {
+ int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
+ if (cmp > 0)
+ return PyInt_FromSsize_t(i);
+ else if (cmp < 0)
+ return NULL;
+ }
+ PyErr_SetString(PyExc_ValueError, "tuple.index(x): x not in tuple");
+ return NULL;
}
static PyObject *
tuplecount(PyTupleObject *self, PyObject *v)
{
- Py_ssize_t count = 0;
- Py_ssize_t i;
-
- for (i = 0; i < Py_SIZE(self); i++) {
- int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
- if (cmp > 0)
- count++;
- else if (cmp < 0)
- return NULL;
- }
- return PyInt_FromSsize_t(count);
+ Py_ssize_t count = 0;
+ Py_ssize_t i;
+
+ for (i = 0; i < Py_SIZE(self); i++) {
+ int cmp = PyObject_RichCompareBool(self->ob_item[i], v, Py_EQ);
+ if (cmp > 0)
+ count++;
+ else if (cmp < 0)
+ return NULL;
+ }
+ return PyInt_FromSsize_t(count);
}
static int
tupletraverse(PyTupleObject *o, visitproc visit, void *arg)
{
- Py_ssize_t i;
+ Py_ssize_t i;
- for (i = Py_SIZE(o); --i >= 0; )
- Py_VISIT(o->ob_item[i]);
- return 0;
+ for (i = Py_SIZE(o); --i >= 0; )
+ Py_VISIT(o->ob_item[i]);
+ return 0;
}
static PyObject *
tuplerichcompare(PyObject *v, PyObject *w, int op)
{
- PyTupleObject *vt, *wt;
- Py_ssize_t i;
- Py_ssize_t vlen, wlen;
-
- if (!PyTuple_Check(v) || !PyTuple_Check(w)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
-
- vt = (PyTupleObject *)v;
- wt = (PyTupleObject *)w;
-
- vlen = Py_SIZE(vt);
- wlen = Py_SIZE(wt);
-
- /* Note: the corresponding code for lists has an "early out" test
- * here when op is EQ or NE and the lengths differ. That pays there,
- * but Tim was unable to find any real code where EQ/NE tuple
- * compares don't have the same length, so testing for it here would
- * have cost without benefit.
- */
-
- /* Search for the first index where items are different.
- * Note that because tuples are immutable, it's safe to reuse
- * vlen and wlen across the comparison calls.
- */
- for (i = 0; i < vlen && i < wlen; i++) {
- int k = PyObject_RichCompareBool(vt->ob_item[i],
- wt->ob_item[i], Py_EQ);
- if (k < 0)
- return NULL;
- if (!k)
- break;
- }
-
- if (i >= vlen || i >= wlen) {
- /* No more items to compare -- compare sizes */
- int cmp;
- PyObject *res;
- switch (op) {
- case Py_LT: cmp = vlen < wlen; break;
- case Py_LE: cmp = vlen <= wlen; break;
- case Py_EQ: cmp = vlen == wlen; break;
- case Py_NE: cmp = vlen != wlen; break;
- case Py_GT: cmp = vlen > wlen; break;
- case Py_GE: cmp = vlen >= wlen; break;
- default: return NULL; /* cannot happen */
- }
- if (cmp)
- res = Py_True;
- else
- res = Py_False;
- Py_INCREF(res);
- return res;
- }
-
- /* We have an item that differs -- shortcuts for EQ/NE */
- if (op == Py_EQ) {
- Py_INCREF(Py_False);
- return Py_False;
- }
- if (op == Py_NE) {
- Py_INCREF(Py_True);
- return Py_True;
- }
-
- /* Compare the final item again using the proper operator */
- return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op);
+ PyTupleObject *vt, *wt;
+ Py_ssize_t i;
+ Py_ssize_t vlen, wlen;
+
+ if (!PyTuple_Check(v) || !PyTuple_Check(w)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+
+ vt = (PyTupleObject *)v;
+ wt = (PyTupleObject *)w;
+
+ vlen = Py_SIZE(vt);
+ wlen = Py_SIZE(wt);
+
+ /* Note: the corresponding code for lists has an "early out" test
+ * here when op is EQ or NE and the lengths differ. That pays there,
+ * but Tim was unable to find any real code where EQ/NE tuple
+ * compares don't have the same length, so testing for it here would
+ * have cost without benefit.
+ */
+
+ /* Search for the first index where items are different.
+ * Note that because tuples are immutable, it's safe to reuse
+ * vlen and wlen across the comparison calls.
+ */
+ for (i = 0; i < vlen && i < wlen; i++) {
+ int k = PyObject_RichCompareBool(vt->ob_item[i],
+ wt->ob_item[i], Py_EQ);
+ if (k < 0)
+ return NULL;
+ if (!k)
+ break;
+ }
+
+ if (i >= vlen || i >= wlen) {
+ /* No more items to compare -- compare sizes */
+ int cmp;
+ PyObject *res;
+ switch (op) {
+ case Py_LT: cmp = vlen < wlen; break;
+ case Py_LE: cmp = vlen <= wlen; break;
+ case Py_EQ: cmp = vlen == wlen; break;
+ case Py_NE: cmp = vlen != wlen; break;
+ case Py_GT: cmp = vlen > wlen; break;
+ case Py_GE: cmp = vlen >= wlen; break;
+ default: return NULL; /* cannot happen */
+ }
+ if (cmp)
+ res = Py_True;
+ else
+ res = Py_False;
+ Py_INCREF(res);
+ return res;
+ }
+
+ /* We have an item that differs -- shortcuts for EQ/NE */
+ if (op == Py_EQ) {
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ if (op == Py_NE) {
+ Py_INCREF(Py_True);
+ return Py_True;
+ }
+
+ /* Compare the final item again using the proper operator */
+ return PyObject_RichCompare(vt->ob_item[i], wt->ob_item[i], op);
}
static PyObject *
@@ -642,41 +642,41 @@ tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static PyObject *
tuple_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *arg = NULL;
- static char *kwlist[] = {"sequence", 0};
-
- if (type != &PyTuple_Type)
- return tuple_subtype_new(type, args, kwds);
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg))
- return NULL;
-
- if (arg == NULL)
- return PyTuple_New(0);
- else
- return PySequence_Tuple(arg);
+ PyObject *arg = NULL;
+ static char *kwlist[] = {"sequence", 0};
+
+ if (type != &PyTuple_Type)
+ return tuple_subtype_new(type, args, kwds);
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:tuple", kwlist, &arg))
+ return NULL;
+
+ if (arg == NULL)
+ return PyTuple_New(0);
+ else
+ return PySequence_Tuple(arg);
}
static PyObject *
tuple_subtype_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *tmp, *newobj, *item;
- Py_ssize_t i, n;
-
- assert(PyType_IsSubtype(type, &PyTuple_Type));
- tmp = tuple_new(&PyTuple_Type, args, kwds);
- if (tmp == NULL)
- return NULL;
- assert(PyTuple_Check(tmp));
- newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp));
- if (newobj == NULL)
- return NULL;
- for (i = 0; i < n; i++) {
- item = PyTuple_GET_ITEM(tmp, i);
- Py_INCREF(item);
- PyTuple_SET_ITEM(newobj, i, item);
- }
- Py_DECREF(tmp);
- return newobj;
+ PyObject *tmp, *newobj, *item;
+ Py_ssize_t i, n;
+
+ assert(PyType_IsSubtype(type, &PyTuple_Type));
+ tmp = tuple_new(&PyTuple_Type, args, kwds);
+ if (tmp == NULL)
+ return NULL;
+ assert(PyTuple_Check(tmp));
+ newobj = type->tp_alloc(type, n = PyTuple_GET_SIZE(tmp));
+ if (newobj == NULL)
+ return NULL;
+ for (i = 0; i < n; i++) {
+ item = PyTuple_GET_ITEM(tmp, i);
+ Py_INCREF(item);
+ PyTuple_SET_ITEM(newobj, i, item);
+ }
+ Py_DECREF(tmp);
+ return newobj;
}
PyDoc_STRVAR(tuple_doc,
@@ -686,86 +686,86 @@ tuple(iterable) -> tuple initialized from iterable's items\n\
If the argument is a tuple, the return value is the same object.");
static PySequenceMethods tuple_as_sequence = {
- (lenfunc)tuplelength, /* sq_length */
- (binaryfunc)tupleconcat, /* sq_concat */
- (ssizeargfunc)tuplerepeat, /* sq_repeat */
- (ssizeargfunc)tupleitem, /* sq_item */
- (ssizessizeargfunc)tupleslice, /* sq_slice */
- 0, /* sq_ass_item */
- 0, /* sq_ass_slice */
- (objobjproc)tuplecontains, /* sq_contains */
+ (lenfunc)tuplelength, /* sq_length */
+ (binaryfunc)tupleconcat, /* sq_concat */
+ (ssizeargfunc)tuplerepeat, /* sq_repeat */
+ (ssizeargfunc)tupleitem, /* sq_item */
+ (ssizessizeargfunc)tupleslice, /* sq_slice */
+ 0, /* sq_ass_item */
+ 0, /* sq_ass_slice */
+ (objobjproc)tuplecontains, /* sq_contains */
};
static PyObject*
tuplesubscript(PyTupleObject* self, PyObject* item)
{
- if (PyIndex_Check(item)) {
- Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- if (i < 0)
- i += PyTuple_GET_SIZE(self);
- return tupleitem(self, i);
- }
- else if (PySlice_Check(item)) {
- Py_ssize_t start, stop, step, slicelength, cur, i;
- PyObject* result;
- PyObject* it;
- PyObject **src, **dest;
-
- if (PySlice_GetIndicesEx((PySliceObject*)item,
- PyTuple_GET_SIZE(self),
- &start, &stop, &step, &slicelength) < 0) {
- return NULL;
- }
-
- if (slicelength <= 0) {
- return PyTuple_New(0);
- }
- else if (start == 0 && step == 1 &&
- slicelength == PyTuple_GET_SIZE(self) &&
- PyTuple_CheckExact(self)) {
- Py_INCREF(self);
- return (PyObject *)self;
- }
- else {
- result = PyTuple_New(slicelength);
- if (!result) return NULL;
-
- src = self->ob_item;
- dest = ((PyTupleObject *)result)->ob_item;
- for (cur = start, i = 0; i < slicelength;
- cur += step, i++) {
- it = src[cur];
- Py_INCREF(it);
- dest[i] = it;
- }
-
- return result;
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "tuple indices must be integers, not %.200s",
- Py_TYPE(item)->tp_name);
- return NULL;
- }
+ if (PyIndex_Check(item)) {
+ Py_ssize_t i = PyNumber_AsSsize_t(item, PyExc_IndexError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ if (i < 0)
+ i += PyTuple_GET_SIZE(self);
+ return tupleitem(self, i);
+ }
+ else if (PySlice_Check(item)) {
+ Py_ssize_t start, stop, step, slicelength, cur, i;
+ PyObject* result;
+ PyObject* it;
+ PyObject **src, **dest;
+
+ if (PySlice_GetIndicesEx((PySliceObject*)item,
+ PyTuple_GET_SIZE(self),
+ &start, &stop, &step, &slicelength) < 0) {
+ return NULL;
+ }
+
+ if (slicelength <= 0) {
+ return PyTuple_New(0);
+ }
+ else if (start == 0 && step == 1 &&
+ slicelength == PyTuple_GET_SIZE(self) &&
+ PyTuple_CheckExact(self)) {
+ Py_INCREF(self);
+ return (PyObject *)self;
+ }
+ else {
+ result = PyTuple_New(slicelength);
+ if (!result) return NULL;
+
+ src = self->ob_item;
+ dest = ((PyTupleObject *)result)->ob_item;
+ for (cur = start, i = 0; i < slicelength;
+ cur += step, i++) {
+ it = src[cur];
+ Py_INCREF(it);
+ dest[i] = it;
+ }
+
+ return result;
+ }
+ }
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "tuple indices must be integers, not %.200s",
+ Py_TYPE(item)->tp_name);
+ return NULL;
+ }
}
static PyObject *
tuple_getnewargs(PyTupleObject *v)
{
- return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v)));
-
+ return Py_BuildValue("(N)", tupleslice(v, 0, Py_SIZE(v)));
+
}
static PyObject *
tuple_sizeof(PyTupleObject *self)
{
- Py_ssize_t res;
+ Py_ssize_t res;
- res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *);
- return PyInt_FromSsize_t(res);
+ res = PyTuple_Type.tp_basicsize + Py_SIZE(self) * sizeof(PyObject *);
+ return PyInt_FromSsize_t(res);
}
PyDoc_STRVAR(index_doc,
@@ -778,62 +778,62 @@ PyDoc_STRVAR(sizeof_doc,
"T.__sizeof__() -- size of T in memory, in bytes");
static PyMethodDef tuple_methods[] = {
- {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS},
- {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc},
- {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc},
- {"count", (PyCFunction)tuplecount, METH_O, count_doc},
- {NULL, NULL} /* sentinel */
+ {"__getnewargs__", (PyCFunction)tuple_getnewargs, METH_NOARGS},
+ {"__sizeof__", (PyCFunction)tuple_sizeof, METH_NOARGS, sizeof_doc},
+ {"index", (PyCFunction)tupleindex, METH_VARARGS, index_doc},
+ {"count", (PyCFunction)tuplecount, METH_O, count_doc},
+ {NULL, NULL} /* sentinel */
};
static PyMappingMethods tuple_as_mapping = {
- (lenfunc)tuplelength,
- (binaryfunc)tuplesubscript,
- 0
+ (lenfunc)tuplelength,
+ (binaryfunc)tuplesubscript,
+ 0
};
static PyObject *tuple_iter(PyObject *seq);
PyTypeObject PyTuple_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "tuple",
- sizeof(PyTupleObject) - sizeof(PyObject *),
- sizeof(PyObject *),
- (destructor)tupledealloc, /* tp_dealloc */
- (printfunc)tupleprint, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)tuplerepr, /* tp_repr */
- 0, /* tp_as_number */
- &tuple_as_sequence, /* tp_as_sequence */
- &tuple_as_mapping, /* tp_as_mapping */
- (hashfunc)tuplehash, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */
- tuple_doc, /* tp_doc */
- (traverseproc)tupletraverse, /* tp_traverse */
- 0, /* tp_clear */
- tuplerichcompare, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- tuple_iter, /* tp_iter */
- 0, /* tp_iternext */
- tuple_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 */
- tuple_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "tuple",
+ sizeof(PyTupleObject) - sizeof(PyObject *),
+ sizeof(PyObject *),
+ (destructor)tupledealloc, /* tp_dealloc */
+ (printfunc)tupleprint, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)tuplerepr, /* tp_repr */
+ 0, /* tp_as_number */
+ &tuple_as_sequence, /* tp_as_sequence */
+ &tuple_as_mapping, /* tp_as_mapping */
+ (hashfunc)tuplehash, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TUPLE_SUBCLASS, /* tp_flags */
+ tuple_doc, /* tp_doc */
+ (traverseproc)tupletraverse, /* tp_traverse */
+ 0, /* tp_clear */
+ tuplerichcompare, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ tuple_iter, /* tp_iter */
+ 0, /* tp_iternext */
+ tuple_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 */
+ tuple_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
/* The following function breaks the notion that tuples are immutable:
@@ -846,207 +846,207 @@ PyTypeObject PyTuple_Type = {
int
_PyTuple_Resize(PyObject **pv, Py_ssize_t newsize)
{
- register PyTupleObject *v;
- register PyTupleObject *sv;
- Py_ssize_t i;
- Py_ssize_t oldsize;
-
- v = (PyTupleObject *) *pv;
- if (v == NULL || Py_TYPE(v) != &PyTuple_Type ||
- (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) {
- *pv = 0;
- Py_XDECREF(v);
- PyErr_BadInternalCall();
- return -1;
- }
- oldsize = Py_SIZE(v);
- if (oldsize == newsize)
- return 0;
-
- if (oldsize == 0) {
- /* Empty tuples are often shared, so we should never
- resize them in-place even if we do own the only
- (current) reference */
- Py_DECREF(v);
- *pv = PyTuple_New(newsize);
- return *pv == NULL ? -1 : 0;
- }
-
- /* XXX UNREF/NEWREF interface should be more symmetrical */
- _Py_DEC_REFTOTAL;
- if (_PyObject_GC_IS_TRACKED(v))
- _PyObject_GC_UNTRACK(v);
- _Py_ForgetReference((PyObject *) v);
- /* DECREF items deleted by shrinkage */
- for (i = newsize; i < oldsize; i++) {
- Py_XDECREF(v->ob_item[i]);
- v->ob_item[i] = NULL;
- }
- sv = PyObject_GC_Resize(PyTupleObject, v, newsize);
- if (sv == NULL) {
- *pv = NULL;
- PyObject_GC_Del(v);
- return -1;
- }
- _Py_NewReference((PyObject *) sv);
- /* Zero out items added by growing */
- if (newsize > oldsize)
- memset(&sv->ob_item[oldsize], 0,
- sizeof(*sv->ob_item) * (newsize - oldsize));
- *pv = (PyObject *) sv;
- _PyObject_GC_TRACK(sv);
- return 0;
+ register PyTupleObject *v;
+ register PyTupleObject *sv;
+ Py_ssize_t i;
+ Py_ssize_t oldsize;
+
+ v = (PyTupleObject *) *pv;
+ if (v == NULL || Py_TYPE(v) != &PyTuple_Type ||
+ (Py_SIZE(v) != 0 && Py_REFCNT(v) != 1)) {
+ *pv = 0;
+ Py_XDECREF(v);
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ oldsize = Py_SIZE(v);
+ if (oldsize == newsize)
+ return 0;
+
+ if (oldsize == 0) {
+ /* Empty tuples are often shared, so we should never
+ resize them in-place even if we do own the only
+ (current) reference */
+ Py_DECREF(v);
+ *pv = PyTuple_New(newsize);
+ return *pv == NULL ? -1 : 0;
+ }
+
+ /* XXX UNREF/NEWREF interface should be more symmetrical */
+ _Py_DEC_REFTOTAL;
+ if (_PyObject_GC_IS_TRACKED(v))
+ _PyObject_GC_UNTRACK(v);
+ _Py_ForgetReference((PyObject *) v);
+ /* DECREF items deleted by shrinkage */
+ for (i = newsize; i < oldsize; i++) {
+ Py_XDECREF(v->ob_item[i]);
+ v->ob_item[i] = NULL;
+ }
+ sv = PyObject_GC_Resize(PyTupleObject, v, newsize);
+ if (sv == NULL) {
+ *pv = NULL;
+ PyObject_GC_Del(v);
+ return -1;
+ }
+ _Py_NewReference((PyObject *) sv);
+ /* Zero out items added by growing */
+ if (newsize > oldsize)
+ memset(&sv->ob_item[oldsize], 0,
+ sizeof(*sv->ob_item) * (newsize - oldsize));
+ *pv = (PyObject *) sv;
+ _PyObject_GC_TRACK(sv);
+ return 0;
}
int
PyTuple_ClearFreeList(void)
{
- int freelist_size = 0;
+ int freelist_size = 0;
#if PyTuple_MAXSAVESIZE > 0
- int i;
- for (i = 1; i < PyTuple_MAXSAVESIZE; i++) {
- PyTupleObject *p, *q;
- p = free_list[i];
- freelist_size += numfree[i];
- free_list[i] = NULL;
- numfree[i] = 0;
- while (p) {
- q = p;
- p = (PyTupleObject *)(p->ob_item[0]);
- PyObject_GC_Del(q);
- }
- }
+ int i;
+ for (i = 1; i < PyTuple_MAXSAVESIZE; i++) {
+ PyTupleObject *p, *q;
+ p = free_list[i];
+ freelist_size += numfree[i];
+ free_list[i] = NULL;
+ numfree[i] = 0;
+ while (p) {
+ q = p;
+ p = (PyTupleObject *)(p->ob_item[0]);
+ PyObject_GC_Del(q);
+ }
+ }
#endif
- return freelist_size;
+ return freelist_size;
}
-
+
void
PyTuple_Fini(void)
{
#if PyTuple_MAXSAVESIZE > 0
- /* empty tuples are used all over the place and applications may
- * rely on the fact that an empty tuple is a singleton. */
- Py_XDECREF(free_list[0]);
- free_list[0] = NULL;
+ /* empty tuples are used all over the place and applications may
+ * rely on the fact that an empty tuple is a singleton. */
+ Py_XDECREF(free_list[0]);
+ free_list[0] = NULL;
- (void)PyTuple_ClearFreeList();
+ (void)PyTuple_ClearFreeList();
#endif
#ifdef SHOW_TRACK_COUNT
- show_track();
+ show_track();
#endif
}
/*********************** Tuple Iterator **************************/
typedef struct {
- PyObject_HEAD
- long it_index;
- PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */
+ PyObject_HEAD
+ long it_index;
+ PyTupleObject *it_seq; /* Set to NULL when iterator is exhausted */
} tupleiterobject;
static void
tupleiter_dealloc(tupleiterobject *it)
{
- _PyObject_GC_UNTRACK(it);
- Py_XDECREF(it->it_seq);
- PyObject_GC_Del(it);
+ _PyObject_GC_UNTRACK(it);
+ Py_XDECREF(it->it_seq);
+ PyObject_GC_Del(it);
}
static int
tupleiter_traverse(tupleiterobject *it, visitproc visit, void *arg)
{
- Py_VISIT(it->it_seq);
- return 0;
+ Py_VISIT(it->it_seq);
+ return 0;
}
static PyObject *
tupleiter_next(tupleiterobject *it)
{
- PyTupleObject *seq;
- PyObject *item;
-
- assert(it != NULL);
- seq = it->it_seq;
- if (seq == NULL)
- return NULL;
- assert(PyTuple_Check(seq));
-
- if (it->it_index < PyTuple_GET_SIZE(seq)) {
- item = PyTuple_GET_ITEM(seq, it->it_index);
- ++it->it_index;
- Py_INCREF(item);
- return item;
- }
-
- Py_DECREF(seq);
- it->it_seq = NULL;
- return NULL;
+ PyTupleObject *seq;
+ PyObject *item;
+
+ assert(it != NULL);
+ seq = it->it_seq;
+ if (seq == NULL)
+ return NULL;
+ assert(PyTuple_Check(seq));
+
+ if (it->it_index < PyTuple_GET_SIZE(seq)) {
+ item = PyTuple_GET_ITEM(seq, it->it_index);
+ ++it->it_index;
+ Py_INCREF(item);
+ return item;
+ }
+
+ Py_DECREF(seq);
+ it->it_seq = NULL;
+ return NULL;
}
static PyObject *
tupleiter_len(tupleiterobject *it)
{
- Py_ssize_t len = 0;
- if (it->it_seq)
- len = PyTuple_GET_SIZE(it->it_seq) - it->it_index;
- return PyInt_FromSsize_t(len);
+ Py_ssize_t len = 0;
+ if (it->it_seq)
+ len = PyTuple_GET_SIZE(it->it_seq) - it->it_index;
+ return PyInt_FromSsize_t(len);
}
PyDoc_STRVAR(length_hint_doc, "Private method returning an estimate of len(list(it)).");
static PyMethodDef tupleiter_methods[] = {
- {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc},
- {NULL, NULL} /* sentinel */
+ {"__length_hint__", (PyCFunction)tupleiter_len, METH_NOARGS, length_hint_doc},
+ {NULL, NULL} /* sentinel */
};
PyTypeObject PyTupleIter_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "tupleiterator", /* tp_name */
- sizeof(tupleiterobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- (destructor)tupleiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)tupleiter_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- PyObject_SelfIter, /* tp_iter */
- (iternextfunc)tupleiter_next, /* tp_iternext */
- tupleiter_methods, /* tp_methods */
- 0,
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "tupleiterator", /* tp_name */
+ sizeof(tupleiterobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ (destructor)tupleiter_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 | Py_TPFLAGS_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)tupleiter_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ PyObject_SelfIter, /* tp_iter */
+ (iternextfunc)tupleiter_next, /* tp_iternext */
+ tupleiter_methods, /* tp_methods */
+ 0,
};
static PyObject *
tuple_iter(PyObject *seq)
{
- tupleiterobject *it;
-
- if (!PyTuple_Check(seq)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type);
- if (it == NULL)
- return NULL;
- it->it_index = 0;
- Py_INCREF(seq);
- it->it_seq = (PyTupleObject *)seq;
- _PyObject_GC_TRACK(it);
- return (PyObject *)it;
+ tupleiterobject *it;
+
+ if (!PyTuple_Check(seq)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ it = PyObject_GC_New(tupleiterobject, &PyTupleIter_Type);
+ if (it == NULL)
+ return NULL;
+ it->it_index = 0;
+ Py_INCREF(seq);
+ it->it_seq = (PyTupleObject *)seq;
+ _PyObject_GC_TRACK(it);
+ return (PyObject *)it;
}
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index e347328..c4b9dbf 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -12,22 +12,22 @@
they normally would. This is why the maximum size is limited to
MCACHE_MAX_ATTR_SIZE, since it might be a problem if very large
strings are used as attribute names. */
-#define MCACHE_MAX_ATTR_SIZE 100
-#define MCACHE_SIZE_EXP 10
-#define MCACHE_HASH(version, name_hash) \
- (((unsigned int)(version) * (unsigned int)(name_hash)) \
- >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
+#define MCACHE_MAX_ATTR_SIZE 100
+#define MCACHE_SIZE_EXP 10
+#define MCACHE_HASH(version, name_hash) \
+ (((unsigned int)(version) * (unsigned int)(name_hash)) \
+ >> (8*sizeof(unsigned int) - MCACHE_SIZE_EXP))
#define MCACHE_HASH_METHOD(type, name) \
- MCACHE_HASH((type)->tp_version_tag, \
- ((PyStringObject *)(name))->ob_shash)
+ MCACHE_HASH((type)->tp_version_tag, \
+ ((PyStringObject *)(name))->ob_shash)
#define MCACHE_CACHEABLE_NAME(name) \
- PyString_CheckExact(name) && \
- PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
+ PyString_CheckExact(name) && \
+ PyString_GET_SIZE(name) <= MCACHE_MAX_ATTR_SIZE
struct method_cache_entry {
- unsigned int version;
- PyObject *name; /* reference to exactly a str or None */
- PyObject *value; /* borrowed */
+ unsigned int version;
+ PyObject *name; /* reference to exactly a str or None */
+ PyObject *value; /* borrowed */
};
static struct method_cache_entry method_cache[1 << MCACHE_SIZE_EXP];
@@ -36,313 +36,313 @@ static unsigned int next_version_tag = 0;
unsigned int
PyType_ClearCache(void)
{
- Py_ssize_t i;
- unsigned int cur_version_tag = next_version_tag - 1;
+ Py_ssize_t i;
+ unsigned int cur_version_tag = next_version_tag - 1;
- for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
- method_cache[i].version = 0;
- Py_CLEAR(method_cache[i].name);
- method_cache[i].value = NULL;
- }
- next_version_tag = 0;
- /* mark all version tags as invalid */
- PyType_Modified(&PyBaseObject_Type);
- return cur_version_tag;
+ for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
+ method_cache[i].version = 0;
+ Py_CLEAR(method_cache[i].name);
+ method_cache[i].value = NULL;
+ }
+ next_version_tag = 0;
+ /* mark all version tags as invalid */
+ PyType_Modified(&PyBaseObject_Type);
+ return cur_version_tag;
}
void
PyType_Modified(PyTypeObject *type)
{
- /* Invalidate any cached data for the specified type and all
- subclasses. This function is called after the base
- classes, mro, or attributes of the type are altered.
-
- Invariants:
-
- - Py_TPFLAGS_VALID_VERSION_TAG is never set if
- Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
- objects coming from non-recompiled extension modules)
-
- - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
- it must first be set on all super types.
-
- This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
- type (so it must first clear it on all subclasses). The
- tp_version_tag value is meaningless unless this flag is set.
- We don't assign new version tags eagerly, but only as
- needed.
- */
- PyObject *raw, *ref;
- Py_ssize_t i, n;
-
- if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
- return;
-
- raw = type->tp_subclasses;
- if (raw != NULL) {
- n = PyList_GET_SIZE(raw);
- for (i = 0; i < n; i++) {
- ref = PyList_GET_ITEM(raw, i);
- ref = PyWeakref_GET_OBJECT(ref);
- if (ref != Py_None) {
- PyType_Modified((PyTypeObject *)ref);
- }
- }
- }
- type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
+ /* Invalidate any cached data for the specified type and all
+ subclasses. This function is called after the base
+ classes, mro, or attributes of the type are altered.
+
+ Invariants:
+
+ - Py_TPFLAGS_VALID_VERSION_TAG is never set if
+ Py_TPFLAGS_HAVE_VERSION_TAG is not set (e.g. on type
+ objects coming from non-recompiled extension modules)
+
+ - before Py_TPFLAGS_VALID_VERSION_TAG can be set on a type,
+ it must first be set on all super types.
+
+ This function clears the Py_TPFLAGS_VALID_VERSION_TAG of a
+ type (so it must first clear it on all subclasses). The
+ tp_version_tag value is meaningless unless this flag is set.
+ We don't assign new version tags eagerly, but only as
+ needed.
+ */
+ PyObject *raw, *ref;
+ Py_ssize_t i, n;
+
+ if (!PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
+ return;
+
+ raw = type->tp_subclasses;
+ if (raw != NULL) {
+ n = PyList_GET_SIZE(raw);
+ for (i = 0; i < n; i++) {
+ ref = PyList_GET_ITEM(raw, i);
+ ref = PyWeakref_GET_OBJECT(ref);
+ if (ref != Py_None) {
+ PyType_Modified((PyTypeObject *)ref);
+ }
+ }
+ }
+ type->tp_flags &= ~Py_TPFLAGS_VALID_VERSION_TAG;
}
static void
type_mro_modified(PyTypeObject *type, PyObject *bases) {
- /*
- Check that all base classes or elements of the mro of type are
- able to be cached. This function is called after the base
- classes or mro of the type are altered.
-
- Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
- inherits from an old-style class, either directly or if it
- appears in the MRO of a new-style class. No support either for
- custom MROs that include types that are not officially super
- types.
-
- Called from mro_internal, which will subsequently be called on
- each subclass when their mro is recursively updated.
- */
- Py_ssize_t i, n;
- int clear = 0;
-
- if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
- return;
-
- n = PyTuple_GET_SIZE(bases);
- for (i = 0; i < n; i++) {
- PyObject *b = PyTuple_GET_ITEM(bases, i);
- PyTypeObject *cls;
-
- if (!PyType_Check(b) ) {
- clear = 1;
- break;
- }
-
- cls = (PyTypeObject *)b;
-
- if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
- !PyType_IsSubtype(type, cls)) {
- clear = 1;
- break;
- }
- }
-
- if (clear)
- type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
- Py_TPFLAGS_VALID_VERSION_TAG);
+ /*
+ Check that all base classes or elements of the mro of type are
+ able to be cached. This function is called after the base
+ classes or mro of the type are altered.
+
+ Unset HAVE_VERSION_TAG and VALID_VERSION_TAG if the type
+ inherits from an old-style class, either directly or if it
+ appears in the MRO of a new-style class. No support either for
+ custom MROs that include types that are not officially super
+ types.
+
+ Called from mro_internal, which will subsequently be called on
+ each subclass when their mro is recursively updated.
+ */
+ Py_ssize_t i, n;
+ int clear = 0;
+
+ if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
+ return;
+
+ n = PyTuple_GET_SIZE(bases);
+ for (i = 0; i < n; i++) {
+ PyObject *b = PyTuple_GET_ITEM(bases, i);
+ PyTypeObject *cls;
+
+ if (!PyType_Check(b) ) {
+ clear = 1;
+ break;
+ }
+
+ cls = (PyTypeObject *)b;
+
+ if (!PyType_HasFeature(cls, Py_TPFLAGS_HAVE_VERSION_TAG) ||
+ !PyType_IsSubtype(type, cls)) {
+ clear = 1;
+ break;
+ }
+ }
+
+ if (clear)
+ type->tp_flags &= ~(Py_TPFLAGS_HAVE_VERSION_TAG|
+ Py_TPFLAGS_VALID_VERSION_TAG);
}
static int
assign_version_tag(PyTypeObject *type)
{
- /* Ensure that the tp_version_tag is valid and set
- Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
- must first be done on all super classes. Return 0 if this
- cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
- */
- Py_ssize_t i, n;
- PyObject *bases;
-
- if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
- return 1;
- if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
- return 0;
- if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
- return 0;
-
- type->tp_version_tag = next_version_tag++;
- /* for stress-testing: next_version_tag &= 0xFF; */
-
- if (type->tp_version_tag == 0) {
- /* wrap-around or just starting Python - clear the whole
- cache by filling names with references to Py_None.
- Values are also set to NULL for added protection, as they
- are borrowed reference */
- for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
- method_cache[i].value = NULL;
- Py_XDECREF(method_cache[i].name);
- method_cache[i].name = Py_None;
- Py_INCREF(Py_None);
- }
- /* mark all version tags as invalid */
- PyType_Modified(&PyBaseObject_Type);
- return 1;
- }
- bases = type->tp_bases;
- n = PyTuple_GET_SIZE(bases);
- for (i = 0; i < n; i++) {
- PyObject *b = PyTuple_GET_ITEM(bases, i);
- assert(PyType_Check(b));
- if (!assign_version_tag((PyTypeObject *)b))
- return 0;
- }
- type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
- return 1;
+ /* Ensure that the tp_version_tag is valid and set
+ Py_TPFLAGS_VALID_VERSION_TAG. To respect the invariant, this
+ must first be done on all super classes. Return 0 if this
+ cannot be done, 1 if Py_TPFLAGS_VALID_VERSION_TAG.
+ */
+ Py_ssize_t i, n;
+ PyObject *bases;
+
+ if (PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG))
+ return 1;
+ if (!PyType_HasFeature(type, Py_TPFLAGS_HAVE_VERSION_TAG))
+ return 0;
+ if (!PyType_HasFeature(type, Py_TPFLAGS_READY))
+ return 0;
+
+ type->tp_version_tag = next_version_tag++;
+ /* for stress-testing: next_version_tag &= 0xFF; */
+
+ if (type->tp_version_tag == 0) {
+ /* wrap-around or just starting Python - clear the whole
+ cache by filling names with references to Py_None.
+ Values are also set to NULL for added protection, as they
+ are borrowed reference */
+ for (i = 0; i < (1 << MCACHE_SIZE_EXP); i++) {
+ method_cache[i].value = NULL;
+ Py_XDECREF(method_cache[i].name);
+ method_cache[i].name = Py_None;
+ Py_INCREF(Py_None);
+ }
+ /* mark all version tags as invalid */
+ PyType_Modified(&PyBaseObject_Type);
+ return 1;
+ }
+ bases = type->tp_bases;
+ n = PyTuple_GET_SIZE(bases);
+ for (i = 0; i < n; i++) {
+ PyObject *b = PyTuple_GET_ITEM(bases, i);
+ assert(PyType_Check(b));
+ if (!assign_version_tag((PyTypeObject *)b))
+ return 0;
+ }
+ type->tp_flags |= Py_TPFLAGS_VALID_VERSION_TAG;
+ return 1;
}
static PyMemberDef type_members[] = {
- {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
- {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
- {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
- {"__weakrefoffset__", T_LONG,
- offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
- {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
- {"__dictoffset__", T_LONG,
- offsetof(PyTypeObject, tp_dictoffset), READONLY},
- {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
- {0}
+ {"__basicsize__", T_INT, offsetof(PyTypeObject,tp_basicsize),READONLY},
+ {"__itemsize__", T_INT, offsetof(PyTypeObject, tp_itemsize), READONLY},
+ {"__flags__", T_LONG, offsetof(PyTypeObject, tp_flags), READONLY},
+ {"__weakrefoffset__", T_LONG,
+ offsetof(PyTypeObject, tp_weaklistoffset), READONLY},
+ {"__base__", T_OBJECT, offsetof(PyTypeObject, tp_base), READONLY},
+ {"__dictoffset__", T_LONG,
+ offsetof(PyTypeObject, tp_dictoffset), READONLY},
+ {"__mro__", T_OBJECT, offsetof(PyTypeObject, tp_mro), READONLY},
+ {0}
};
static PyObject *
type_name(PyTypeObject *type, void *context)
{
- const char *s;
+ const char *s;
- if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
- PyHeapTypeObject* et = (PyHeapTypeObject*)type;
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
+ PyHeapTypeObject* et = (PyHeapTypeObject*)type;
- Py_INCREF(et->ht_name);
- return et->ht_name;
- }
- else {
- s = strrchr(type->tp_name, '.');
- if (s == NULL)
- s = type->tp_name;
- else
- s++;
- return PyString_FromString(s);
- }
+ Py_INCREF(et->ht_name);
+ return et->ht_name;
+ }
+ else {
+ s = strrchr(type->tp_name, '.');
+ if (s == NULL)
+ s = type->tp_name;
+ else
+ s++;
+ return PyString_FromString(s);
+ }
}
static int
type_set_name(PyTypeObject *type, PyObject *value, void *context)
{
- PyHeapTypeObject* et;
+ PyHeapTypeObject* et;
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
- PyErr_Format(PyExc_TypeError,
- "can't set %s.__name__", type->tp_name);
- return -1;
- }
- if (!value) {
- PyErr_Format(PyExc_TypeError,
- "can't delete %s.__name__", type->tp_name);
- return -1;
- }
- if (!PyString_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "can only assign string to %s.__name__, not '%s'",
- type->tp_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- if (strlen(PyString_AS_STRING(value))
- != (size_t)PyString_GET_SIZE(value)) {
- PyErr_Format(PyExc_ValueError,
- "__name__ must not contain null bytes");
- return -1;
- }
+ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
+ PyErr_Format(PyExc_TypeError,
+ "can't set %s.__name__", type->tp_name);
+ return -1;
+ }
+ if (!value) {
+ PyErr_Format(PyExc_TypeError,
+ "can't delete %s.__name__", type->tp_name);
+ return -1;
+ }
+ if (!PyString_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign string to %s.__name__, not '%s'",
+ type->tp_name, Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ if (strlen(PyString_AS_STRING(value))
+ != (size_t)PyString_GET_SIZE(value)) {
+ PyErr_Format(PyExc_ValueError,
+ "__name__ must not contain null bytes");
+ return -1;
+ }
- et = (PyHeapTypeObject*)type;
+ et = (PyHeapTypeObject*)type;
- Py_INCREF(value);
+ Py_INCREF(value);
- Py_DECREF(et->ht_name);
- et->ht_name = value;
+ Py_DECREF(et->ht_name);
+ et->ht_name = value;
- type->tp_name = PyString_AS_STRING(value);
+ type->tp_name = PyString_AS_STRING(value);
- return 0;
+ return 0;
}
static PyObject *
type_module(PyTypeObject *type, void *context)
{
- PyObject *mod;
- char *s;
-
- if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
- mod = PyDict_GetItemString(type->tp_dict, "__module__");
- if (!mod) {
- PyErr_Format(PyExc_AttributeError, "__module__");
- return 0;
- }
- Py_XINCREF(mod);
- return mod;
- }
- else {
- s = strrchr(type->tp_name, '.');
- if (s != NULL)
- return PyString_FromStringAndSize(
- type->tp_name, (Py_ssize_t)(s - type->tp_name));
- return PyString_FromString("__builtin__");
- }
+ PyObject *mod;
+ char *s;
+
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE) {
+ mod = PyDict_GetItemString(type->tp_dict, "__module__");
+ if (!mod) {
+ PyErr_Format(PyExc_AttributeError, "__module__");
+ return 0;
+ }
+ Py_XINCREF(mod);
+ return mod;
+ }
+ else {
+ s = strrchr(type->tp_name, '.');
+ if (s != NULL)
+ return PyString_FromStringAndSize(
+ type->tp_name, (Py_ssize_t)(s - type->tp_name));
+ return PyString_FromString("__builtin__");
+ }
}
static int
type_set_module(PyTypeObject *type, PyObject *value, void *context)
{
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
- PyErr_Format(PyExc_TypeError,
- "can't set %s.__module__", type->tp_name);
- return -1;
- }
- if (!value) {
- PyErr_Format(PyExc_TypeError,
- "can't delete %s.__module__", type->tp_name);
- return -1;
- }
+ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
+ PyErr_Format(PyExc_TypeError,
+ "can't set %s.__module__", type->tp_name);
+ return -1;
+ }
+ if (!value) {
+ PyErr_Format(PyExc_TypeError,
+ "can't delete %s.__module__", type->tp_name);
+ return -1;
+ }
- PyType_Modified(type);
+ PyType_Modified(type);
- return PyDict_SetItemString(type->tp_dict, "__module__", value);
+ return PyDict_SetItemString(type->tp_dict, "__module__", value);
}
static PyObject *
type_abstractmethods(PyTypeObject *type, void *context)
{
- PyObject *mod = PyDict_GetItemString(type->tp_dict,
- "__abstractmethods__");
- if (!mod) {
- PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
- return NULL;
- }
- Py_XINCREF(mod);
- return mod;
+ PyObject *mod = PyDict_GetItemString(type->tp_dict,
+ "__abstractmethods__");
+ if (!mod) {
+ PyErr_Format(PyExc_AttributeError, "__abstractmethods__");
+ return NULL;
+ }
+ Py_XINCREF(mod);
+ return mod;
}
static int
type_set_abstractmethods(PyTypeObject *type, PyObject *value, void *context)
{
- /* __abstractmethods__ should only be set once on a type, in
- abc.ABCMeta.__new__, so this function doesn't do anything
- special to update subclasses.
- */
- int res = PyDict_SetItemString(type->tp_dict,
- "__abstractmethods__", value);
- if (res == 0) {
- PyType_Modified(type);
- if (value && PyObject_IsTrue(value)) {
- type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
- }
- else {
- type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
- }
- }
- return res;
+ /* __abstractmethods__ should only be set once on a type, in
+ abc.ABCMeta.__new__, so this function doesn't do anything
+ special to update subclasses.
+ */
+ int res = PyDict_SetItemString(type->tp_dict,
+ "__abstractmethods__", value);
+ if (res == 0) {
+ PyType_Modified(type);
+ if (value && PyObject_IsTrue(value)) {
+ type->tp_flags |= Py_TPFLAGS_IS_ABSTRACT;
+ }
+ else {
+ type->tp_flags &= ~Py_TPFLAGS_IS_ABSTRACT;
+ }
+ }
+ return res;
}
static PyObject *
type_get_bases(PyTypeObject *type, void *context)
{
- Py_INCREF(type->tp_bases);
- return type->tp_bases;
+ Py_INCREF(type->tp_bases);
+ return type->tp_bases;
}
static PyTypeObject *best_base(PyObject *);
@@ -354,416 +354,416 @@ static void update_all_slots(PyTypeObject *);
typedef int (*update_callback)(PyTypeObject *, void *);
static int update_subclasses(PyTypeObject *type, PyObject *name,
- update_callback callback, void *data);
+ update_callback callback, void *data);
static int recurse_down_subclasses(PyTypeObject *type, PyObject *name,
- update_callback callback, void *data);
+ update_callback callback, void *data);
static int
mro_subclasses(PyTypeObject *type, PyObject* temp)
{
- PyTypeObject *subclass;
- PyObject *ref, *subclasses, *old_mro;
- Py_ssize_t i, n;
-
- subclasses = type->tp_subclasses;
- if (subclasses == NULL)
- return 0;
- assert(PyList_Check(subclasses));
- n = PyList_GET_SIZE(subclasses);
- for (i = 0; i < n; i++) {
- ref = PyList_GET_ITEM(subclasses, i);
- assert(PyWeakref_CheckRef(ref));
- subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
- assert(subclass != NULL);
- if ((PyObject *)subclass == Py_None)
- continue;
- assert(PyType_Check(subclass));
- old_mro = subclass->tp_mro;
- if (mro_internal(subclass) < 0) {
- subclass->tp_mro = old_mro;
- return -1;
- }
- else {
- PyObject* tuple;
- tuple = PyTuple_Pack(2, subclass, old_mro);
- Py_DECREF(old_mro);
- if (!tuple)
- return -1;
- if (PyList_Append(temp, tuple) < 0)
- return -1;
- Py_DECREF(tuple);
- }
- if (mro_subclasses(subclass, temp) < 0)
- return -1;
- }
- return 0;
+ PyTypeObject *subclass;
+ PyObject *ref, *subclasses, *old_mro;
+ Py_ssize_t i, n;
+
+ subclasses = type->tp_subclasses;
+ if (subclasses == NULL)
+ return 0;
+ assert(PyList_Check(subclasses));
+ n = PyList_GET_SIZE(subclasses);
+ for (i = 0; i < n; i++) {
+ ref = PyList_GET_ITEM(subclasses, i);
+ assert(PyWeakref_CheckRef(ref));
+ subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
+ assert(subclass != NULL);
+ if ((PyObject *)subclass == Py_None)
+ continue;
+ assert(PyType_Check(subclass));
+ old_mro = subclass->tp_mro;
+ if (mro_internal(subclass) < 0) {
+ subclass->tp_mro = old_mro;
+ return -1;
+ }
+ else {
+ PyObject* tuple;
+ tuple = PyTuple_Pack(2, subclass, old_mro);
+ Py_DECREF(old_mro);
+ if (!tuple)
+ return -1;
+ if (PyList_Append(temp, tuple) < 0)
+ return -1;
+ Py_DECREF(tuple);
+ }
+ if (mro_subclasses(subclass, temp) < 0)
+ return -1;
+ }
+ return 0;
}
static int
type_set_bases(PyTypeObject *type, PyObject *value, void *context)
{
- Py_ssize_t i;
- int r = 0;
- PyObject *ob, *temp;
- PyTypeObject *new_base, *old_base;
- PyObject *old_bases, *old_mro;
-
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
- PyErr_Format(PyExc_TypeError,
- "can't set %s.__bases__", type->tp_name);
- return -1;
- }
- if (!value) {
- PyErr_Format(PyExc_TypeError,
- "can't delete %s.__bases__", type->tp_name);
- return -1;
- }
- if (!PyTuple_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "can only assign tuple to %s.__bases__, not %s",
- type->tp_name, Py_TYPE(value)->tp_name);
- return -1;
- }
- if (PyTuple_GET_SIZE(value) == 0) {
- PyErr_Format(PyExc_TypeError,
- "can only assign non-empty tuple to %s.__bases__, not ()",
- type->tp_name);
- return -1;
- }
- for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
- ob = PyTuple_GET_ITEM(value, i);
- if (!PyClass_Check(ob) && !PyType_Check(ob)) {
- PyErr_Format(
- PyExc_TypeError,
- "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
- type->tp_name, Py_TYPE(ob)->tp_name);
- return -1;
- }
- if (PyType_Check(ob)) {
- if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
- PyErr_SetString(PyExc_TypeError,
- "a __bases__ item causes an inheritance cycle");
- return -1;
- }
- }
- }
-
- new_base = best_base(value);
-
- if (!new_base) {
- return -1;
- }
-
- if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
- return -1;
-
- Py_INCREF(new_base);
- Py_INCREF(value);
-
- old_bases = type->tp_bases;
- old_base = type->tp_base;
- old_mro = type->tp_mro;
-
- type->tp_bases = value;
- type->tp_base = new_base;
-
- if (mro_internal(type) < 0) {
- goto bail;
- }
-
- temp = PyList_New(0);
- if (!temp)
- goto bail;
-
- r = mro_subclasses(type, temp);
-
- if (r < 0) {
- for (i = 0; i < PyList_Size(temp); i++) {
- PyTypeObject* cls;
- PyObject* mro;
- PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
- "", 2, 2, &cls, &mro);
- Py_INCREF(mro);
- ob = cls->tp_mro;
- cls->tp_mro = mro;
- Py_DECREF(ob);
- }
- Py_DECREF(temp);
- goto bail;
- }
-
- Py_DECREF(temp);
-
- /* any base that was in __bases__ but now isn't, we
- need to remove |type| from its tp_subclasses.
- conversely, any class now in __bases__ that wasn't
- needs to have |type| added to its subclasses. */
-
- /* for now, sod that: just remove from all old_bases,
- add to all new_bases */
-
- for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
- ob = PyTuple_GET_ITEM(old_bases, i);
- if (PyType_Check(ob)) {
- remove_subclass(
- (PyTypeObject*)ob, type);
- }
- }
-
- for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
- ob = PyTuple_GET_ITEM(value, i);
- if (PyType_Check(ob)) {
- if (add_subclass((PyTypeObject*)ob, type) < 0)
- r = -1;
- }
- }
-
- update_all_slots(type);
-
- Py_DECREF(old_bases);
- Py_DECREF(old_base);
- Py_DECREF(old_mro);
-
- return r;
+ Py_ssize_t i;
+ int r = 0;
+ PyObject *ob, *temp;
+ PyTypeObject *new_base, *old_base;
+ PyObject *old_bases, *old_mro;
+
+ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
+ PyErr_Format(PyExc_TypeError,
+ "can't set %s.__bases__", type->tp_name);
+ return -1;
+ }
+ if (!value) {
+ PyErr_Format(PyExc_TypeError,
+ "can't delete %s.__bases__", type->tp_name);
+ return -1;
+ }
+ if (!PyTuple_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign tuple to %s.__bases__, not %s",
+ type->tp_name, Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ if (PyTuple_GET_SIZE(value) == 0) {
+ PyErr_Format(PyExc_TypeError,
+ "can only assign non-empty tuple to %s.__bases__, not ()",
+ type->tp_name);
+ return -1;
+ }
+ for (i = 0; i < PyTuple_GET_SIZE(value); i++) {
+ ob = PyTuple_GET_ITEM(value, i);
+ if (!PyClass_Check(ob) && !PyType_Check(ob)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s.__bases__ must be tuple of old- or new-style classes, not '%s'",
+ type->tp_name, Py_TYPE(ob)->tp_name);
+ return -1;
+ }
+ if (PyType_Check(ob)) {
+ if (PyType_IsSubtype((PyTypeObject*)ob, type)) {
+ PyErr_SetString(PyExc_TypeError,
+ "a __bases__ item causes an inheritance cycle");
+ return -1;
+ }
+ }
+ }
+
+ new_base = best_base(value);
+
+ if (!new_base) {
+ return -1;
+ }
+
+ if (!compatible_for_assignment(type->tp_base, new_base, "__bases__"))
+ return -1;
+
+ Py_INCREF(new_base);
+ Py_INCREF(value);
+
+ old_bases = type->tp_bases;
+ old_base = type->tp_base;
+ old_mro = type->tp_mro;
+
+ type->tp_bases = value;
+ type->tp_base = new_base;
+
+ if (mro_internal(type) < 0) {
+ goto bail;
+ }
+
+ temp = PyList_New(0);
+ if (!temp)
+ goto bail;
+
+ r = mro_subclasses(type, temp);
+
+ if (r < 0) {
+ for (i = 0; i < PyList_Size(temp); i++) {
+ PyTypeObject* cls;
+ PyObject* mro;
+ PyArg_UnpackTuple(PyList_GET_ITEM(temp, i),
+ "", 2, 2, &cls, &mro);
+ Py_INCREF(mro);
+ ob = cls->tp_mro;
+ cls->tp_mro = mro;
+ Py_DECREF(ob);
+ }
+ Py_DECREF(temp);
+ goto bail;
+ }
+
+ Py_DECREF(temp);
+
+ /* any base that was in __bases__ but now isn't, we
+ need to remove |type| from its tp_subclasses.
+ conversely, any class now in __bases__ that wasn't
+ needs to have |type| added to its subclasses. */
+
+ /* for now, sod that: just remove from all old_bases,
+ add to all new_bases */
+
+ for (i = PyTuple_GET_SIZE(old_bases) - 1; i >= 0; i--) {
+ ob = PyTuple_GET_ITEM(old_bases, i);
+ if (PyType_Check(ob)) {
+ remove_subclass(
+ (PyTypeObject*)ob, type);
+ }
+ }
+
+ for (i = PyTuple_GET_SIZE(value) - 1; i >= 0; i--) {
+ ob = PyTuple_GET_ITEM(value, i);
+ if (PyType_Check(ob)) {
+ if (add_subclass((PyTypeObject*)ob, type) < 0)
+ r = -1;
+ }
+ }
+
+ update_all_slots(type);
+
+ Py_DECREF(old_bases);
+ Py_DECREF(old_base);
+ Py_DECREF(old_mro);
+
+ return r;
bail:
- Py_DECREF(type->tp_bases);
- Py_DECREF(type->tp_base);
- if (type->tp_mro != old_mro) {
- Py_DECREF(type->tp_mro);
- }
+ Py_DECREF(type->tp_bases);
+ Py_DECREF(type->tp_base);
+ if (type->tp_mro != old_mro) {
+ Py_DECREF(type->tp_mro);
+ }
- type->tp_bases = old_bases;
- type->tp_base = old_base;
- type->tp_mro = old_mro;
+ type->tp_bases = old_bases;
+ type->tp_base = old_base;
+ type->tp_mro = old_mro;
- return -1;
+ return -1;
}
static PyObject *
type_dict(PyTypeObject *type, void *context)
{
- if (type->tp_dict == NULL) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyDictProxy_New(type->tp_dict);
+ if (type->tp_dict == NULL) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyDictProxy_New(type->tp_dict);
}
static PyObject *
type_get_doc(PyTypeObject *type, void *context)
{
- PyObject *result;
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
- return PyString_FromString(type->tp_doc);
- result = PyDict_GetItemString(type->tp_dict, "__doc__");
- if (result == NULL) {
- result = Py_None;
- Py_INCREF(result);
- }
- else if (Py_TYPE(result)->tp_descr_get) {
- result = Py_TYPE(result)->tp_descr_get(result, NULL,
- (PyObject *)type);
- }
- else {
- Py_INCREF(result);
- }
- return result;
+ PyObject *result;
+ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE) && type->tp_doc != NULL)
+ return PyString_FromString(type->tp_doc);
+ result = PyDict_GetItemString(type->tp_dict, "__doc__");
+ if (result == NULL) {
+ result = Py_None;
+ Py_INCREF(result);
+ }
+ else if (Py_TYPE(result)->tp_descr_get) {
+ result = Py_TYPE(result)->tp_descr_get(result, NULL,
+ (PyObject *)type);
+ }
+ else {
+ Py_INCREF(result);
+ }
+ return result;
}
static PyObject *
type___instancecheck__(PyObject *type, PyObject *inst)
{
- switch (_PyObject_RealIsInstance(inst, type)) {
- case -1:
- return NULL;
- case 0:
- Py_RETURN_FALSE;
- default:
- Py_RETURN_TRUE;
- }
+ switch (_PyObject_RealIsInstance(inst, type)) {
+ case -1:
+ return NULL;
+ case 0:
+ Py_RETURN_FALSE;
+ default:
+ Py_RETURN_TRUE;
+ }
}
static PyObject *
type___subclasscheck__(PyObject *type, PyObject *inst)
{
- switch (_PyObject_RealIsSubclass(inst, type)) {
- case -1:
- return NULL;
- case 0:
- Py_RETURN_FALSE;
- default:
- Py_RETURN_TRUE;
- }
+ switch (_PyObject_RealIsSubclass(inst, type)) {
+ case -1:
+ return NULL;
+ case 0:
+ Py_RETURN_FALSE;
+ default:
+ Py_RETURN_TRUE;
+ }
}
static PyGetSetDef type_getsets[] = {
- {"__name__", (getter)type_name, (setter)type_set_name, NULL},
- {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
- {"__module__", (getter)type_module, (setter)type_set_module, NULL},
- {"__abstractmethods__", (getter)type_abstractmethods,
- (setter)type_set_abstractmethods, NULL},
- {"__dict__", (getter)type_dict, NULL, NULL},
- {"__doc__", (getter)type_get_doc, NULL, NULL},
- {0}
+ {"__name__", (getter)type_name, (setter)type_set_name, NULL},
+ {"__bases__", (getter)type_get_bases, (setter)type_set_bases, NULL},
+ {"__module__", (getter)type_module, (setter)type_set_module, NULL},
+ {"__abstractmethods__", (getter)type_abstractmethods,
+ (setter)type_set_abstractmethods, NULL},
+ {"__dict__", (getter)type_dict, NULL, NULL},
+ {"__doc__", (getter)type_get_doc, NULL, NULL},
+ {0}
};
static PyObject*
type_richcompare(PyObject *v, PyObject *w, int op)
{
- PyObject *result;
- Py_uintptr_t vv, ww;
- int c;
-
- /* Make sure both arguments are types. */
- if (!PyType_Check(v) || !PyType_Check(w) ||
- /* If there is a __cmp__ method defined, let it be called instead
- of our dumb function designed merely to warn. See bug
- #7491. */
- Py_TYPE(v)->tp_compare || Py_TYPE(w)->tp_compare) {
- result = Py_NotImplemented;
- goto out;
- }
-
- /* Py3K warning if comparison isn't == or != */
- if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
- PyErr_WarnEx(PyExc_DeprecationWarning,
- "type inequality comparisons not supported "
- "in 3.x", 1) < 0) {
- return NULL;
- }
-
- /* Compare addresses */
- vv = (Py_uintptr_t)v;
- ww = (Py_uintptr_t)w;
- switch (op) {
- case Py_LT: c = vv < ww; break;
- case Py_LE: c = vv <= ww; break;
- case Py_EQ: c = vv == ww; break;
- case Py_NE: c = vv != ww; break;
- case Py_GT: c = vv > ww; break;
- case Py_GE: c = vv >= ww; break;
- default:
- result = Py_NotImplemented;
- goto out;
- }
- result = c ? Py_True : Py_False;
+ PyObject *result;
+ Py_uintptr_t vv, ww;
+ int c;
+
+ /* Make sure both arguments are types. */
+ if (!PyType_Check(v) || !PyType_Check(w) ||
+ /* If there is a __cmp__ method defined, let it be called instead
+ of our dumb function designed merely to warn. See bug
+ #7491. */
+ Py_TYPE(v)->tp_compare || Py_TYPE(w)->tp_compare) {
+ result = Py_NotImplemented;
+ goto out;
+ }
+
+ /* Py3K warning if comparison isn't == or != */
+ if (Py_Py3kWarningFlag && op != Py_EQ && op != Py_NE &&
+ PyErr_WarnEx(PyExc_DeprecationWarning,
+ "type inequality comparisons not supported "
+ "in 3.x", 1) < 0) {
+ return NULL;
+ }
+
+ /* Compare addresses */
+ vv = (Py_uintptr_t)v;
+ ww = (Py_uintptr_t)w;
+ switch (op) {
+ case Py_LT: c = vv < ww; break;
+ case Py_LE: c = vv <= ww; break;
+ case Py_EQ: c = vv == ww; break;
+ case Py_NE: c = vv != ww; break;
+ case Py_GT: c = vv > ww; break;
+ case Py_GE: c = vv >= ww; break;
+ default:
+ result = Py_NotImplemented;
+ goto out;
+ }
+ result = c ? Py_True : Py_False;
/* incref and return */
out:
- Py_INCREF(result);
- return result;
+ Py_INCREF(result);
+ return result;
}
static PyObject *
type_repr(PyTypeObject *type)
{
- PyObject *mod, *name, *rtn;
- char *kind;
-
- mod = type_module(type, NULL);
- if (mod == NULL)
- PyErr_Clear();
- else if (!PyString_Check(mod)) {
- Py_DECREF(mod);
- mod = NULL;
- }
- name = type_name(type, NULL);
- if (name == NULL)
- return NULL;
-
- if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- kind = "class";
- else
- kind = "type";
-
- if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
- rtn = PyString_FromFormat("<%s '%s.%s'>",
- kind,
- PyString_AS_STRING(mod),
- PyString_AS_STRING(name));
- }
- else
- rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
-
- Py_XDECREF(mod);
- Py_DECREF(name);
- return rtn;
+ PyObject *mod, *name, *rtn;
+ char *kind;
+
+ mod = type_module(type, NULL);
+ if (mod == NULL)
+ PyErr_Clear();
+ else if (!PyString_Check(mod)) {
+ Py_DECREF(mod);
+ mod = NULL;
+ }
+ name = type_name(type, NULL);
+ if (name == NULL)
+ return NULL;
+
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
+ kind = "class";
+ else
+ kind = "type";
+
+ if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__")) {
+ rtn = PyString_FromFormat("<%s '%s.%s'>",
+ kind,
+ PyString_AS_STRING(mod),
+ PyString_AS_STRING(name));
+ }
+ else
+ rtn = PyString_FromFormat("<%s '%s'>", kind, type->tp_name);
+
+ Py_XDECREF(mod);
+ Py_DECREF(name);
+ return rtn;
}
static PyObject *
type_call(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- PyObject *obj;
-
- if (type->tp_new == NULL) {
- PyErr_Format(PyExc_TypeError,
- "cannot create '%.100s' instances",
- type->tp_name);
- return NULL;
- }
-
- obj = type->tp_new(type, args, kwds);
- if (obj != NULL) {
- /* Ugly exception: when the call was type(something),
- don't call tp_init on the result. */
- if (type == &PyType_Type &&
- PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
- (kwds == NULL ||
- (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
- return obj;
- /* If the returned object is not an instance of type,
- it won't be initialized. */
- if (!PyType_IsSubtype(obj->ob_type, type))
- return obj;
- type = obj->ob_type;
- if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
- type->tp_init != NULL &&
- type->tp_init(obj, args, kwds) < 0) {
- Py_DECREF(obj);
- obj = NULL;
- }
- }
- return obj;
+ PyObject *obj;
+
+ if (type->tp_new == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "cannot create '%.100s' instances",
+ type->tp_name);
+ return NULL;
+ }
+
+ obj = type->tp_new(type, args, kwds);
+ if (obj != NULL) {
+ /* Ugly exception: when the call was type(something),
+ don't call tp_init on the result. */
+ if (type == &PyType_Type &&
+ PyTuple_Check(args) && PyTuple_GET_SIZE(args) == 1 &&
+ (kwds == NULL ||
+ (PyDict_Check(kwds) && PyDict_Size(kwds) == 0)))
+ return obj;
+ /* If the returned object is not an instance of type,
+ it won't be initialized. */
+ if (!PyType_IsSubtype(obj->ob_type, type))
+ return obj;
+ type = obj->ob_type;
+ if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_CLASS) &&
+ type->tp_init != NULL &&
+ type->tp_init(obj, args, kwds) < 0) {
+ Py_DECREF(obj);
+ obj = NULL;
+ }
+ }
+ return obj;
}
PyObject *
PyType_GenericAlloc(PyTypeObject *type, Py_ssize_t nitems)
{
- PyObject *obj;
- const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
- /* note that we need to add one, for the sentinel */
+ PyObject *obj;
+ const size_t size = _PyObject_VAR_SIZE(type, nitems+1);
+ /* note that we need to add one, for the sentinel */
- if (PyType_IS_GC(type))
- obj = _PyObject_GC_Malloc(size);
- else
- obj = (PyObject *)PyObject_MALLOC(size);
+ if (PyType_IS_GC(type))
+ obj = _PyObject_GC_Malloc(size);
+ else
+ obj = (PyObject *)PyObject_MALLOC(size);
- if (obj == NULL)
- return PyErr_NoMemory();
+ if (obj == NULL)
+ return PyErr_NoMemory();
- memset(obj, '\0', size);
+ memset(obj, '\0', size);
- if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- Py_INCREF(type);
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
+ Py_INCREF(type);
- if (type->tp_itemsize == 0)
- PyObject_INIT(obj, type);
- else
- (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
+ if (type->tp_itemsize == 0)
+ PyObject_INIT(obj, type);
+ else
+ (void) PyObject_INIT_VAR((PyVarObject *)obj, type, nitems);
- if (PyType_IS_GC(type))
- _PyObject_GC_TRACK(obj);
- return obj;
+ if (PyType_IS_GC(type))
+ _PyObject_GC_TRACK(obj);
+ return obj;
}
PyObject *
PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- return type->tp_alloc(type, 0);
+ return type->tp_alloc(type, 0);
}
/* Helpers for subtyping */
@@ -771,341 +771,341 @@ PyType_GenericNew(PyTypeObject *type, PyObject *args, PyObject *kwds)
static int
traverse_slots(PyTypeObject *type, PyObject *self, visitproc visit, void *arg)
{
- Py_ssize_t i, n;
- PyMemberDef *mp;
-
- n = Py_SIZE(type);
- mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
- for (i = 0; i < n; i++, mp++) {
- if (mp->type == T_OBJECT_EX) {
- char *addr = (char *)self + mp->offset;
- PyObject *obj = *(PyObject **)addr;
- if (obj != NULL) {
- int err = visit(obj, arg);
- if (err)
- return err;
- }
- }
- }
- return 0;
+ Py_ssize_t i, n;
+ PyMemberDef *mp;
+
+ n = Py_SIZE(type);
+ mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
+ for (i = 0; i < n; i++, mp++) {
+ if (mp->type == T_OBJECT_EX) {
+ char *addr = (char *)self + mp->offset;
+ PyObject *obj = *(PyObject **)addr;
+ if (obj != NULL) {
+ int err = visit(obj, arg);
+ if (err)
+ return err;
+ }
+ }
+ }
+ return 0;
}
static int
subtype_traverse(PyObject *self, visitproc visit, void *arg)
{
- PyTypeObject *type, *base;
- traverseproc basetraverse;
-
- /* Find the nearest base with a different tp_traverse,
- and traverse slots while we're at it */
- type = Py_TYPE(self);
- base = type;
- while ((basetraverse = base->tp_traverse) == subtype_traverse) {
- if (Py_SIZE(base)) {
- int err = traverse_slots(base, self, visit, arg);
- if (err)
- return err;
- }
- base = base->tp_base;
- assert(base);
- }
-
- if (type->tp_dictoffset != base->tp_dictoffset) {
- PyObject **dictptr = _PyObject_GetDictPtr(self);
- if (dictptr && *dictptr)
- Py_VISIT(*dictptr);
- }
-
- if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- /* For a heaptype, the instances count as references
- to the type. Traverse the type so the collector
- can find cycles involving this link. */
- Py_VISIT(type);
-
- if (basetraverse)
- return basetraverse(self, visit, arg);
- return 0;
+ PyTypeObject *type, *base;
+ traverseproc basetraverse;
+
+ /* Find the nearest base with a different tp_traverse,
+ and traverse slots while we're at it */
+ type = Py_TYPE(self);
+ base = type;
+ while ((basetraverse = base->tp_traverse) == subtype_traverse) {
+ if (Py_SIZE(base)) {
+ int err = traverse_slots(base, self, visit, arg);
+ if (err)
+ return err;
+ }
+ base = base->tp_base;
+ assert(base);
+ }
+
+ if (type->tp_dictoffset != base->tp_dictoffset) {
+ PyObject **dictptr = _PyObject_GetDictPtr(self);
+ if (dictptr && *dictptr)
+ Py_VISIT(*dictptr);
+ }
+
+ if (type->tp_flags & Py_TPFLAGS_HEAPTYPE)
+ /* For a heaptype, the instances count as references
+ to the type. Traverse the type so the collector
+ can find cycles involving this link. */
+ Py_VISIT(type);
+
+ if (basetraverse)
+ return basetraverse(self, visit, arg);
+ return 0;
}
static void
clear_slots(PyTypeObject *type, PyObject *self)
{
- Py_ssize_t i, n;
- PyMemberDef *mp;
-
- n = Py_SIZE(type);
- mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
- for (i = 0; i < n; i++, mp++) {
- if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
- char *addr = (char *)self + mp->offset;
- PyObject *obj = *(PyObject **)addr;
- if (obj != NULL) {
- *(PyObject **)addr = NULL;
- Py_DECREF(obj);
- }
- }
- }
+ Py_ssize_t i, n;
+ PyMemberDef *mp;
+
+ n = Py_SIZE(type);
+ mp = PyHeapType_GET_MEMBERS((PyHeapTypeObject *)type);
+ for (i = 0; i < n; i++, mp++) {
+ if (mp->type == T_OBJECT_EX && !(mp->flags & READONLY)) {
+ char *addr = (char *)self + mp->offset;
+ PyObject *obj = *(PyObject **)addr;
+ if (obj != NULL) {
+ *(PyObject **)addr = NULL;
+ Py_DECREF(obj);
+ }
+ }
+ }
}
static int
subtype_clear(PyObject *self)
{
- PyTypeObject *type, *base;
- inquiry baseclear;
+ PyTypeObject *type, *base;
+ inquiry baseclear;
- /* Find the nearest base with a different tp_clear
- and clear slots while we're at it */
- type = Py_TYPE(self);
- base = type;
- while ((baseclear = base->tp_clear) == subtype_clear) {
- if (Py_SIZE(base))
- clear_slots(base, self);
- base = base->tp_base;
- assert(base);
- }
+ /* Find the nearest base with a different tp_clear
+ and clear slots while we're at it */
+ type = Py_TYPE(self);
+ base = type;
+ while ((baseclear = base->tp_clear) == subtype_clear) {
+ if (Py_SIZE(base))
+ clear_slots(base, self);
+ base = base->tp_base;
+ assert(base);
+ }
- /* There's no need to clear the instance dict (if any);
- the collector will call its tp_clear handler. */
+ /* There's no need to clear the instance dict (if any);
+ the collector will call its tp_clear handler. */
- if (baseclear)
- return baseclear(self);
- return 0;
+ if (baseclear)
+ return baseclear(self);
+ return 0;
}
static void
subtype_dealloc(PyObject *self)
{
- PyTypeObject *type, *base;
- destructor basedealloc;
-
- /* Extract the type; we expect it to be a heap type */
- type = Py_TYPE(self);
- assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
-
- /* Test whether the type has GC exactly once */
-
- if (!PyType_IS_GC(type)) {
- /* It's really rare to find a dynamic type that doesn't have
- GC; it can only happen when deriving from 'object' and not
- adding any slots or instance variables. This allows
- certain simplifications: there's no need to call
- clear_slots(), or DECREF the dict, or clear weakrefs. */
-
- /* Maybe call finalizer; exit early if resurrected */
- if (type->tp_del) {
- type->tp_del(self);
- if (self->ob_refcnt > 0)
- return;
- }
-
- /* Find the nearest base with a different tp_dealloc */
- base = type;
- while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
- assert(Py_SIZE(base) == 0);
- base = base->tp_base;
- assert(base);
- }
-
- /* Extract the type again; tp_del may have changed it */
- type = Py_TYPE(self);
-
- /* Call the base tp_dealloc() */
- assert(basedealloc);
- basedealloc(self);
-
- /* Can't reference self beyond this point */
- Py_DECREF(type);
-
- /* Done */
- return;
- }
-
- /* We get here only if the type has GC */
-
- /* UnTrack and re-Track around the trashcan macro, alas */
- /* See explanation at end of function for full disclosure */
- PyObject_GC_UnTrack(self);
- ++_PyTrash_delete_nesting;
- Py_TRASHCAN_SAFE_BEGIN(self);
- --_PyTrash_delete_nesting;
- /* DO NOT restore GC tracking at this point. weakref callbacks
- * (if any, and whether directly here or indirectly in something we
- * call) may trigger GC, and if self is tracked at that point, it
- * will look like trash to GC and GC will try to delete self again.
- */
-
- /* Find the nearest base with a different tp_dealloc */
- base = type;
- while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
- base = base->tp_base;
- assert(base);
- }
-
- /* If we added a weaklist, we clear it. Do this *before* calling
- the finalizer (__del__), clearing slots, or clearing the instance
- dict. */
-
- if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
- PyObject_ClearWeakRefs(self);
-
- /* Maybe call finalizer; exit early if resurrected */
- if (type->tp_del) {
- _PyObject_GC_TRACK(self);
- type->tp_del(self);
- if (self->ob_refcnt > 0)
- goto endlabel; /* resurrected */
- else
- _PyObject_GC_UNTRACK(self);
- /* New weakrefs could be created during the finalizer call.
- If this occurs, clear them out without calling their
- finalizers since they might rely on part of the object
- being finalized that has already been destroyed. */
- if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
- /* Modeled after GET_WEAKREFS_LISTPTR() */
- PyWeakReference **list = (PyWeakReference **) \
- PyObject_GET_WEAKREFS_LISTPTR(self);
- while (*list)
- _PyWeakref_ClearRef(*list);
- }
- }
-
- /* Clear slots up to the nearest base with a different tp_dealloc */
- base = type;
- while (base->tp_dealloc == subtype_dealloc) {
- if (Py_SIZE(base))
- clear_slots(base, self);
- base = base->tp_base;
- assert(base);
- }
-
- /* If we added a dict, DECREF it */
- if (type->tp_dictoffset && !base->tp_dictoffset) {
- PyObject **dictptr = _PyObject_GetDictPtr(self);
- if (dictptr != NULL) {
- PyObject *dict = *dictptr;
- if (dict != NULL) {
- Py_DECREF(dict);
- *dictptr = NULL;
- }
- }
- }
-
- /* Extract the type again; tp_del may have changed it */
- type = Py_TYPE(self);
-
- /* Call the base tp_dealloc(); first retrack self if
- * basedealloc knows about gc.
- */
- if (PyType_IS_GC(base))
- _PyObject_GC_TRACK(self);
- assert(basedealloc);
- basedealloc(self);
-
- /* Can't reference self beyond this point */
- Py_DECREF(type);
+ PyTypeObject *type, *base;
+ destructor basedealloc;
+
+ /* Extract the type; we expect it to be a heap type */
+ type = Py_TYPE(self);
+ assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
+
+ /* Test whether the type has GC exactly once */
+
+ if (!PyType_IS_GC(type)) {
+ /* It's really rare to find a dynamic type that doesn't have
+ GC; it can only happen when deriving from 'object' and not
+ adding any slots or instance variables. This allows
+ certain simplifications: there's no need to call
+ clear_slots(), or DECREF the dict, or clear weakrefs. */
+
+ /* Maybe call finalizer; exit early if resurrected */
+ if (type->tp_del) {
+ type->tp_del(self);
+ if (self->ob_refcnt > 0)
+ return;
+ }
+
+ /* Find the nearest base with a different tp_dealloc */
+ base = type;
+ while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
+ assert(Py_SIZE(base) == 0);
+ base = base->tp_base;
+ assert(base);
+ }
+
+ /* Extract the type again; tp_del may have changed it */
+ type = Py_TYPE(self);
+
+ /* Call the base tp_dealloc() */
+ assert(basedealloc);
+ basedealloc(self);
+
+ /* Can't reference self beyond this point */
+ Py_DECREF(type);
+
+ /* Done */
+ return;
+ }
+
+ /* We get here only if the type has GC */
+
+ /* UnTrack and re-Track around the trashcan macro, alas */
+ /* See explanation at end of function for full disclosure */
+ PyObject_GC_UnTrack(self);
+ ++_PyTrash_delete_nesting;
+ Py_TRASHCAN_SAFE_BEGIN(self);
+ --_PyTrash_delete_nesting;
+ /* DO NOT restore GC tracking at this point. weakref callbacks
+ * (if any, and whether directly here or indirectly in something we
+ * call) may trigger GC, and if self is tracked at that point, it
+ * will look like trash to GC and GC will try to delete self again.
+ */
+
+ /* Find the nearest base with a different tp_dealloc */
+ base = type;
+ while ((basedealloc = base->tp_dealloc) == subtype_dealloc) {
+ base = base->tp_base;
+ assert(base);
+ }
+
+ /* If we added a weaklist, we clear it. Do this *before* calling
+ the finalizer (__del__), clearing slots, or clearing the instance
+ dict. */
+
+ if (type->tp_weaklistoffset && !base->tp_weaklistoffset)
+ PyObject_ClearWeakRefs(self);
+
+ /* Maybe call finalizer; exit early if resurrected */
+ if (type->tp_del) {
+ _PyObject_GC_TRACK(self);
+ type->tp_del(self);
+ if (self->ob_refcnt > 0)
+ goto endlabel; /* resurrected */
+ else
+ _PyObject_GC_UNTRACK(self);
+ /* New weakrefs could be created during the finalizer call.
+ If this occurs, clear them out without calling their
+ finalizers since they might rely on part of the object
+ being finalized that has already been destroyed. */
+ if (type->tp_weaklistoffset && !base->tp_weaklistoffset) {
+ /* Modeled after GET_WEAKREFS_LISTPTR() */
+ PyWeakReference **list = (PyWeakReference **) \
+ PyObject_GET_WEAKREFS_LISTPTR(self);
+ while (*list)
+ _PyWeakref_ClearRef(*list);
+ }
+ }
+
+ /* Clear slots up to the nearest base with a different tp_dealloc */
+ base = type;
+ while (base->tp_dealloc == subtype_dealloc) {
+ if (Py_SIZE(base))
+ clear_slots(base, self);
+ base = base->tp_base;
+ assert(base);
+ }
+
+ /* If we added a dict, DECREF it */
+ if (type->tp_dictoffset && !base->tp_dictoffset) {
+ PyObject **dictptr = _PyObject_GetDictPtr(self);
+ if (dictptr != NULL) {
+ PyObject *dict = *dictptr;
+ if (dict != NULL) {
+ Py_DECREF(dict);
+ *dictptr = NULL;
+ }
+ }
+ }
+
+ /* Extract the type again; tp_del may have changed it */
+ type = Py_TYPE(self);
+
+ /* Call the base tp_dealloc(); first retrack self if
+ * basedealloc knows about gc.
+ */
+ if (PyType_IS_GC(base))
+ _PyObject_GC_TRACK(self);
+ assert(basedealloc);
+ basedealloc(self);
+
+ /* Can't reference self beyond this point */
+ Py_DECREF(type);
endlabel:
- ++_PyTrash_delete_nesting;
- Py_TRASHCAN_SAFE_END(self);
- --_PyTrash_delete_nesting;
+ ++_PyTrash_delete_nesting;
+ Py_TRASHCAN_SAFE_END(self);
+ --_PyTrash_delete_nesting;
- /* Explanation of the weirdness around the trashcan macros:
+ /* Explanation of the weirdness around the trashcan macros:
- Q. What do the trashcan macros do?
+ Q. What do the trashcan macros do?
- A. Read the comment titled "Trashcan mechanism" in object.h.
- For one, this explains why there must be a call to GC-untrack
- before the trashcan begin macro. Without understanding the
- trashcan code, the answers to the following questions don't make
- sense.
+ A. Read the comment titled "Trashcan mechanism" in object.h.
+ For one, this explains why there must be a call to GC-untrack
+ before the trashcan begin macro. Without understanding the
+ trashcan code, the answers to the following questions don't make
+ sense.
- Q. Why do we GC-untrack before the trashcan and then immediately
- GC-track again afterward?
+ Q. Why do we GC-untrack before the trashcan and then immediately
+ GC-track again afterward?
- A. In the case that the base class is GC-aware, the base class
- probably GC-untracks the object. If it does that using the
- UNTRACK macro, this will crash when the object is already
- untracked. Because we don't know what the base class does, the
- only safe thing is to make sure the object is tracked when we
- call the base class dealloc. But... The trashcan begin macro
- requires that the object is *untracked* before it is called. So
- the dance becomes:
+ A. In the case that the base class is GC-aware, the base class
+ probably GC-untracks the object. If it does that using the
+ UNTRACK macro, this will crash when the object is already
+ untracked. Because we don't know what the base class does, the
+ only safe thing is to make sure the object is tracked when we
+ call the base class dealloc. But... The trashcan begin macro
+ requires that the object is *untracked* before it is called. So
+ the dance becomes:
- GC untrack
- trashcan begin
- GC track
+ GC untrack
+ trashcan begin
+ GC track
- Q. Why did the last question say "immediately GC-track again"?
- It's nowhere near immediately.
+ Q. Why did the last question say "immediately GC-track again"?
+ It's nowhere near immediately.
- A. Because the code *used* to re-track immediately. Bad Idea.
- self has a refcount of 0, and if gc ever gets its hands on it
- (which can happen if any weakref callback gets invoked), it
- looks like trash to gc too, and gc also tries to delete self
- then. But we're already deleting self. Double dealloction is
- a subtle disaster.
+ A. Because the code *used* to re-track immediately. Bad Idea.
+ self has a refcount of 0, and if gc ever gets its hands on it
+ (which can happen if any weakref callback gets invoked), it
+ looks like trash to gc too, and gc also tries to delete self
+ then. But we're already deleting self. Double dealloction is
+ a subtle disaster.
- Q. Why the bizarre (net-zero) manipulation of
- _PyTrash_delete_nesting around the trashcan macros?
+ Q. Why the bizarre (net-zero) manipulation of
+ _PyTrash_delete_nesting around the trashcan macros?
- A. Some base classes (e.g. list) also use the trashcan mechanism.
- The following scenario used to be possible:
+ A. Some base classes (e.g. list) also use the trashcan mechanism.
+ The following scenario used to be possible:
- - suppose the trashcan level is one below the trashcan limit
+ - suppose the trashcan level is one below the trashcan limit
- - subtype_dealloc() is called
+ - subtype_dealloc() is called
- - the trashcan limit is not yet reached, so the trashcan level
- is incremented and the code between trashcan begin and end is
- executed
+ - the trashcan limit is not yet reached, so the trashcan level
+ is incremented and the code between trashcan begin and end is
+ executed
- - this destroys much of the object's contents, including its
- slots and __dict__
+ - this destroys much of the object's contents, including its
+ slots and __dict__
- - basedealloc() is called; this is really list_dealloc(), or
- some other type which also uses the trashcan macros
+ - basedealloc() is called; this is really list_dealloc(), or
+ some other type which also uses the trashcan macros
- - the trashcan limit is now reached, so the object is put on the
- trashcan's to-be-deleted-later list
+ - the trashcan limit is now reached, so the object is put on the
+ trashcan's to-be-deleted-later list
- - basedealloc() returns
+ - basedealloc() returns
- - subtype_dealloc() decrefs the object's type
+ - subtype_dealloc() decrefs the object's type
- - subtype_dealloc() returns
+ - subtype_dealloc() returns
- - later, the trashcan code starts deleting the objects from its
- to-be-deleted-later list
+ - later, the trashcan code starts deleting the objects from its
+ to-be-deleted-later list
- - subtype_dealloc() is called *AGAIN* for the same object
+ - subtype_dealloc() is called *AGAIN* for the same object
- - at the very least (if the destroyed slots and __dict__ don't
- cause problems) the object's type gets decref'ed a second
- time, which is *BAD*!!!
+ - at the very least (if the destroyed slots and __dict__ don't
+ cause problems) the object's type gets decref'ed a second
+ time, which is *BAD*!!!
- The remedy is to make sure that if the code between trashcan
- begin and end in subtype_dealloc() is called, the code between
- trashcan begin and end in basedealloc() will also be called.
- This is done by decrementing the level after passing into the
- trashcan block, and incrementing it just before leaving the
- block.
+ The remedy is to make sure that if the code between trashcan
+ begin and end in subtype_dealloc() is called, the code between
+ trashcan begin and end in basedealloc() will also be called.
+ This is done by decrementing the level after passing into the
+ trashcan block, and incrementing it just before leaving the
+ block.
- But now it's possible that a chain of objects consisting solely
- of objects whose deallocator is subtype_dealloc() will defeat
- the trashcan mechanism completely: the decremented level means
- that the effective level never reaches the limit. Therefore, we
- *increment* the level *before* entering the trashcan block, and
- matchingly decrement it after leaving. This means the trashcan
- code will trigger a little early, but that's no big deal.
+ But now it's possible that a chain of objects consisting solely
+ of objects whose deallocator is subtype_dealloc() will defeat
+ the trashcan mechanism completely: the decremented level means
+ that the effective level never reaches the limit. Therefore, we
+ *increment* the level *before* entering the trashcan block, and
+ matchingly decrement it after leaving. This means the trashcan
+ code will trigger a little early, but that's no big deal.
- Q. Are there any live examples of code in need of all this
- complexity?
+ Q. Are there any live examples of code in need of all this
+ complexity?
- A. Yes. See SF bug 668433 for code that crashed (when Python was
- compiled in debug mode) before the trashcan level manipulations
- were added. For more discussion, see SF patches 581742, 575073
- and bug 574207.
- */
+ A. Yes. See SF bug 668433 for code that crashed (when Python was
+ compiled in debug mode) before the trashcan level manipulations
+ were added. For more discussion, see SF patches 581742, 575073
+ and bug 574207.
+ */
}
static PyTypeObject *solid_base(PyTypeObject *type);
@@ -1115,39 +1115,39 @@ static PyTypeObject *solid_base(PyTypeObject *type);
int
PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
{
- PyObject *mro;
-
- if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
- return b == a || b == &PyBaseObject_Type;
-
- mro = a->tp_mro;
- if (mro != NULL) {
- /* Deal with multiple inheritance without recursion
- by walking the MRO tuple */
- Py_ssize_t i, n;
- assert(PyTuple_Check(mro));
- n = PyTuple_GET_SIZE(mro);
- for (i = 0; i < n; i++) {
- if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
- return 1;
- }
- return 0;
- }
- else {
- /* a is not completely initilized yet; follow tp_base */
- do {
- if (a == b)
- return 1;
- a = a->tp_base;
- } while (a != NULL);
- return b == &PyBaseObject_Type;
- }
+ PyObject *mro;
+
+ if (!(a->tp_flags & Py_TPFLAGS_HAVE_CLASS))
+ return b == a || b == &PyBaseObject_Type;
+
+ mro = a->tp_mro;
+ if (mro != NULL) {
+ /* Deal with multiple inheritance without recursion
+ by walking the MRO tuple */
+ Py_ssize_t i, n;
+ assert(PyTuple_Check(mro));
+ n = PyTuple_GET_SIZE(mro);
+ for (i = 0; i < n; i++) {
+ if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b)
+ return 1;
+ }
+ return 0;
+ }
+ else {
+ /* a is not completely initilized yet; follow tp_base */
+ do {
+ if (a == b)
+ return 1;
+ a = a->tp_base;
+ } while (a != NULL);
+ return b == &PyBaseObject_Type;
+ }
}
/* Internal routines to do a method lookup in the type
without looking in the instance dictionary
(so we can't use PyObject_GetAttr) but still binding
- it to the instance. The arguments are the object,
+ it to the instance. The arguments are the object,
the method name as a C string, and the address of a
static variable used to cache the interned Python string.
@@ -1164,76 +1164,76 @@ PyType_IsSubtype(PyTypeObject *a, PyTypeObject *b)
static PyObject *
lookup_maybe(PyObject *self, char *attrstr, PyObject **attrobj)
{
- PyObject *res;
+ PyObject *res;
- if (*attrobj == NULL) {
- *attrobj = PyString_InternFromString(attrstr);
- if (*attrobj == NULL)
- return NULL;
- }
- res = _PyType_Lookup(Py_TYPE(self), *attrobj);
- if (res != NULL) {
- descrgetfunc f;
- if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
- Py_INCREF(res);
- else
- res = f(res, self, (PyObject *)(Py_TYPE(self)));
- }
- return res;
+ if (*attrobj == NULL) {
+ *attrobj = PyString_InternFromString(attrstr);
+ if (*attrobj == NULL)
+ return NULL;
+ }
+ res = _PyType_Lookup(Py_TYPE(self), *attrobj);
+ if (res != NULL) {
+ descrgetfunc f;
+ if ((f = Py_TYPE(res)->tp_descr_get) == NULL)
+ Py_INCREF(res);
+ else
+ res = f(res, self, (PyObject *)(Py_TYPE(self)));
+ }
+ return res;
}
static PyObject *
lookup_method(PyObject *self, char *attrstr, PyObject **attrobj)
{
- PyObject *res = lookup_maybe(self, attrstr, attrobj);
- if (res == NULL && !PyErr_Occurred())
- PyErr_SetObject(PyExc_AttributeError, *attrobj);
- return res;
+ PyObject *res = lookup_maybe(self, attrstr, attrobj);
+ if (res == NULL && !PyErr_Occurred())
+ PyErr_SetObject(PyExc_AttributeError, *attrobj);
+ return res;
}
PyObject *
_PyObject_LookupSpecial(PyObject *self, char *attrstr, PyObject **attrobj)
{
- assert(!PyInstance_Check(self));
- return lookup_maybe(self, attrstr, attrobj);
+ assert(!PyInstance_Check(self));
+ return lookup_maybe(self, attrstr, attrobj);
}
/* A variation of PyObject_CallMethod that uses lookup_method()
- instead of PyObject_GetAttrString(). This uses the same convention
+ instead of PyObject_GetAttrString(). This uses the same convention
as lookup_method to cache the interned name string object. */
static PyObject *
call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
{
- va_list va;
- PyObject *args, *func = 0, *retval;
- va_start(va, format);
+ va_list va;
+ PyObject *args, *func = 0, *retval;
+ va_start(va, format);
- func = lookup_maybe(o, name, nameobj);
- if (func == NULL) {
- va_end(va);
- if (!PyErr_Occurred())
- PyErr_SetObject(PyExc_AttributeError, *nameobj);
- return NULL;
- }
+ func = lookup_maybe(o, name, nameobj);
+ if (func == NULL) {
+ va_end(va);
+ if (!PyErr_Occurred())
+ PyErr_SetObject(PyExc_AttributeError, *nameobj);
+ return NULL;
+ }
- if (format && *format)
- args = Py_VaBuildValue(format, va);
- else
- args = PyTuple_New(0);
+ if (format && *format)
+ args = Py_VaBuildValue(format, va);
+ else
+ args = PyTuple_New(0);
- va_end(va);
+ va_end(va);
- if (args == NULL)
- return NULL;
+ if (args == NULL)
+ return NULL;
- assert(PyTuple_Check(args));
- retval = PyObject_Call(func, args, NULL);
+ assert(PyTuple_Check(args));
+ retval = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- Py_DECREF(func);
+ Py_DECREF(args);
+ Py_DECREF(func);
- return retval;
+ return retval;
}
/* Clone of call_method() that returns NotImplemented when the lookup fails. */
@@ -1241,78 +1241,78 @@ call_method(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
static PyObject *
call_maybe(PyObject *o, char *name, PyObject **nameobj, char *format, ...)
{
- va_list va;
- PyObject *args, *func = 0, *retval;
- va_start(va, format);
+ va_list va;
+ PyObject *args, *func = 0, *retval;
+ va_start(va, format);
- func = lookup_maybe(o, name, nameobj);
- if (func == NULL) {
- va_end(va);
- if (!PyErr_Occurred()) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return NULL;
- }
+ func = lookup_maybe(o, name, nameobj);
+ if (func == NULL) {
+ va_end(va);
+ if (!PyErr_Occurred()) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return NULL;
+ }
- if (format && *format)
- args = Py_VaBuildValue(format, va);
- else
- args = PyTuple_New(0);
+ if (format && *format)
+ args = Py_VaBuildValue(format, va);
+ else
+ args = PyTuple_New(0);
- va_end(va);
+ va_end(va);
- if (args == NULL)
- return NULL;
+ if (args == NULL)
+ return NULL;
- assert(PyTuple_Check(args));
- retval = PyObject_Call(func, args, NULL);
+ assert(PyTuple_Check(args));
+ retval = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- Py_DECREF(func);
+ Py_DECREF(args);
+ Py_DECREF(func);
- return retval;
+ return retval;
}
static int
fill_classic_mro(PyObject *mro, PyObject *cls)
{
- PyObject *bases, *base;
- Py_ssize_t i, n;
-
- assert(PyList_Check(mro));
- assert(PyClass_Check(cls));
- i = PySequence_Contains(mro, cls);
- if (i < 0)
- return -1;
- if (!i) {
- if (PyList_Append(mro, cls) < 0)
- return -1;
- }
- bases = ((PyClassObject *)cls)->cl_bases;
- assert(bases && PyTuple_Check(bases));
- n = PyTuple_GET_SIZE(bases);
- for (i = 0; i < n; i++) {
- base = PyTuple_GET_ITEM(bases, i);
- if (fill_classic_mro(mro, base) < 0)
- return -1;
- }
- return 0;
+ PyObject *bases, *base;
+ Py_ssize_t i, n;
+
+ assert(PyList_Check(mro));
+ assert(PyClass_Check(cls));
+ i = PySequence_Contains(mro, cls);
+ if (i < 0)
+ return -1;
+ if (!i) {
+ if (PyList_Append(mro, cls) < 0)
+ return -1;
+ }
+ bases = ((PyClassObject *)cls)->cl_bases;
+ assert(bases && PyTuple_Check(bases));
+ n = PyTuple_GET_SIZE(bases);
+ for (i = 0; i < n; i++) {
+ base = PyTuple_GET_ITEM(bases, i);
+ if (fill_classic_mro(mro, base) < 0)
+ return -1;
+ }
+ return 0;
}
static PyObject *
classic_mro(PyObject *cls)
{
- PyObject *mro;
+ PyObject *mro;
- assert(PyClass_Check(cls));
- mro = PyList_New(0);
- if (mro != NULL) {
- if (fill_classic_mro(mro, cls) == 0)
- return mro;
- Py_DECREF(mro);
- }
- return NULL;
+ assert(PyClass_Check(cls));
+ mro = PyList_New(0);
+ if (mro != NULL) {
+ if (fill_classic_mro(mro, cls) == 0)
+ return mro;
+ Py_DECREF(mro);
+ }
+ return NULL;
}
/*
@@ -1345,63 +1345,63 @@ classic_mro(PyObject *cls)
static int
tail_contains(PyObject *list, int whence, PyObject *o) {
- Py_ssize_t j, size;
- size = PyList_GET_SIZE(list);
+ Py_ssize_t j, size;
+ size = PyList_GET_SIZE(list);
- for (j = whence+1; j < size; j++) {
- if (PyList_GET_ITEM(list, j) == o)
- return 1;
- }
- return 0;
+ for (j = whence+1; j < size; j++) {
+ if (PyList_GET_ITEM(list, j) == o)
+ return 1;
+ }
+ return 0;
}
static PyObject *
class_name(PyObject *cls)
{
- PyObject *name = PyObject_GetAttrString(cls, "__name__");
- if (name == NULL) {
- PyErr_Clear();
- Py_XDECREF(name);
- name = PyObject_Repr(cls);
- }
- if (name == NULL)
- return NULL;
- if (!PyString_Check(name)) {
- Py_DECREF(name);
- return NULL;
- }
- return name;
+ PyObject *name = PyObject_GetAttrString(cls, "__name__");
+ if (name == NULL) {
+ PyErr_Clear();
+ Py_XDECREF(name);
+ name = PyObject_Repr(cls);
+ }
+ if (name == NULL)
+ return NULL;
+ if (!PyString_Check(name)) {
+ Py_DECREF(name);
+ return NULL;
+ }
+ return name;
}
static int
check_duplicates(PyObject *list)
{
- Py_ssize_t i, j, n;
- /* Let's use a quadratic time algorithm,
- assuming that the bases lists is short.
- */
- n = PyList_GET_SIZE(list);
- for (i = 0; i < n; i++) {
- PyObject *o = PyList_GET_ITEM(list, i);
- for (j = i + 1; j < n; j++) {
- if (PyList_GET_ITEM(list, j) == o) {
- o = class_name(o);
- PyErr_Format(PyExc_TypeError,
- "duplicate base class %s",
- o ? PyString_AS_STRING(o) : "?");
- Py_XDECREF(o);
- return -1;
- }
- }
- }
- return 0;
+ Py_ssize_t i, j, n;
+ /* Let's use a quadratic time algorithm,
+ assuming that the bases lists is short.
+ */
+ n = PyList_GET_SIZE(list);
+ for (i = 0; i < n; i++) {
+ PyObject *o = PyList_GET_ITEM(list, i);
+ for (j = i + 1; j < n; j++) {
+ if (PyList_GET_ITEM(list, j) == o) {
+ o = class_name(o);
+ PyErr_Format(PyExc_TypeError,
+ "duplicate base class %s",
+ o ? PyString_AS_STRING(o) : "?");
+ Py_XDECREF(o);
+ return -1;
+ }
+ }
+ }
+ return 0;
}
/* Raise a TypeError for an MRO order disagreement.
It's hard to produce a good error message. In the absence of better
insight into error reporting, report the classes that were candidates
- to be put next into the MRO. There is some conflict between the
+ to be put next into the MRO. There is some conflict between the
order in which they should be put in the MRO, but it's hard to
diagnose what constraint can't be satisfied.
*/
@@ -1409,258 +1409,258 @@ check_duplicates(PyObject *list)
static void
set_mro_error(PyObject *to_merge, int *remain)
{
- Py_ssize_t i, n, off, to_merge_size;
- char buf[1000];
- PyObject *k, *v;
- PyObject *set = PyDict_New();
- if (!set) return;
-
- to_merge_size = PyList_GET_SIZE(to_merge);
- for (i = 0; i < to_merge_size; i++) {
- PyObject *L = PyList_GET_ITEM(to_merge, i);
- if (remain[i] < PyList_GET_SIZE(L)) {
- PyObject *c = PyList_GET_ITEM(L, remain[i]);
- if (PyDict_SetItem(set, c, Py_None) < 0) {
- Py_DECREF(set);
- return;
- }
- }
- }
- n = PyDict_Size(set);
-
- off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
+ Py_ssize_t i, n, off, to_merge_size;
+ char buf[1000];
+ PyObject *k, *v;
+ PyObject *set = PyDict_New();
+ if (!set) return;
+
+ to_merge_size = PyList_GET_SIZE(to_merge);
+ for (i = 0; i < to_merge_size; i++) {
+ PyObject *L = PyList_GET_ITEM(to_merge, i);
+ if (remain[i] < PyList_GET_SIZE(L)) {
+ PyObject *c = PyList_GET_ITEM(L, remain[i]);
+ if (PyDict_SetItem(set, c, Py_None) < 0) {
+ Py_DECREF(set);
+ return;
+ }
+ }
+ }
+ n = PyDict_Size(set);
+
+ off = PyOS_snprintf(buf, sizeof(buf), "Cannot create a \
consistent method resolution\norder (MRO) for bases");
- i = 0;
- while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
- PyObject *name = class_name(k);
- off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
- name ? PyString_AS_STRING(name) : "?");
- Py_XDECREF(name);
- if (--n && (size_t)(off+1) < sizeof(buf)) {
- buf[off++] = ',';
- buf[off] = '\0';
- }
- }
- PyErr_SetString(PyExc_TypeError, buf);
- Py_DECREF(set);
+ i = 0;
+ while (PyDict_Next(set, &i, &k, &v) && (size_t)off < sizeof(buf)) {
+ PyObject *name = class_name(k);
+ off += PyOS_snprintf(buf + off, sizeof(buf) - off, " %s",
+ name ? PyString_AS_STRING(name) : "?");
+ Py_XDECREF(name);
+ if (--n && (size_t)(off+1) < sizeof(buf)) {
+ buf[off++] = ',';
+ buf[off] = '\0';
+ }
+ }
+ PyErr_SetString(PyExc_TypeError, buf);
+ Py_DECREF(set);
}
static int
pmerge(PyObject *acc, PyObject* to_merge) {
- Py_ssize_t i, j, to_merge_size, empty_cnt;
- int *remain;
- int ok;
-
- to_merge_size = PyList_GET_SIZE(to_merge);
-
- /* remain stores an index into each sublist of to_merge.
- remain[i] is the index of the next base in to_merge[i]
- that is not included in acc.
- */
- remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
- if (remain == NULL)
- return -1;
- for (i = 0; i < to_merge_size; i++)
- remain[i] = 0;
+ Py_ssize_t i, j, to_merge_size, empty_cnt;
+ int *remain;
+ int ok;
+
+ to_merge_size = PyList_GET_SIZE(to_merge);
+
+ /* remain stores an index into each sublist of to_merge.
+ remain[i] is the index of the next base in to_merge[i]
+ that is not included in acc.
+ */
+ remain = (int *)PyMem_MALLOC(SIZEOF_INT*to_merge_size);
+ if (remain == NULL)
+ return -1;
+ for (i = 0; i < to_merge_size; i++)
+ remain[i] = 0;
again:
- empty_cnt = 0;
- for (i = 0; i < to_merge_size; i++) {
- PyObject *candidate;
-
- PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
-
- if (remain[i] >= PyList_GET_SIZE(cur_list)) {
- empty_cnt++;
- continue;
- }
-
- /* Choose next candidate for MRO.
-
- The input sequences alone can determine the choice.
- If not, choose the class which appears in the MRO
- of the earliest direct superclass of the new class.
- */
-
- candidate = PyList_GET_ITEM(cur_list, remain[i]);
- for (j = 0; j < to_merge_size; j++) {
- PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
- if (tail_contains(j_lst, remain[j], candidate)) {
- goto skip; /* continue outer loop */
- }
- }
- ok = PyList_Append(acc, candidate);
- if (ok < 0) {
- PyMem_Free(remain);
- return -1;
- }
- for (j = 0; j < to_merge_size; j++) {
- PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
- if (remain[j] < PyList_GET_SIZE(j_lst) &&
- PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
- remain[j]++;
- }
- }
- goto again;
- skip: ;
- }
-
- if (empty_cnt == to_merge_size) {
- PyMem_FREE(remain);
- return 0;
- }
- set_mro_error(to_merge, remain);
- PyMem_FREE(remain);
- return -1;
+ empty_cnt = 0;
+ for (i = 0; i < to_merge_size; i++) {
+ PyObject *candidate;
+
+ PyObject *cur_list = PyList_GET_ITEM(to_merge, i);
+
+ if (remain[i] >= PyList_GET_SIZE(cur_list)) {
+ empty_cnt++;
+ continue;
+ }
+
+ /* Choose next candidate for MRO.
+
+ The input sequences alone can determine the choice.
+ If not, choose the class which appears in the MRO
+ of the earliest direct superclass of the new class.
+ */
+
+ candidate = PyList_GET_ITEM(cur_list, remain[i]);
+ for (j = 0; j < to_merge_size; j++) {
+ PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
+ if (tail_contains(j_lst, remain[j], candidate)) {
+ goto skip; /* continue outer loop */
+ }
+ }
+ ok = PyList_Append(acc, candidate);
+ if (ok < 0) {
+ PyMem_Free(remain);
+ return -1;
+ }
+ for (j = 0; j < to_merge_size; j++) {
+ PyObject *j_lst = PyList_GET_ITEM(to_merge, j);
+ if (remain[j] < PyList_GET_SIZE(j_lst) &&
+ PyList_GET_ITEM(j_lst, remain[j]) == candidate) {
+ remain[j]++;
+ }
+ }
+ goto again;
+ skip: ;
+ }
+
+ if (empty_cnt == to_merge_size) {
+ PyMem_FREE(remain);
+ return 0;
+ }
+ set_mro_error(to_merge, remain);
+ PyMem_FREE(remain);
+ return -1;
}
static PyObject *
mro_implementation(PyTypeObject *type)
{
- Py_ssize_t i, n;
- int ok;
- PyObject *bases, *result;
- PyObject *to_merge, *bases_aslist;
-
- if (type->tp_dict == NULL) {
- if (PyType_Ready(type) < 0)
- return NULL;
- }
-
- /* Find a superclass linearization that honors the constraints
- of the explicit lists of bases and the constraints implied by
- each base class.
-
- to_merge is a list of lists, where each list is a superclass
- linearization implied by a base class. The last element of
- to_merge is the declared list of bases.
- */
-
- bases = type->tp_bases;
- n = PyTuple_GET_SIZE(bases);
-
- to_merge = PyList_New(n+1);
- if (to_merge == NULL)
- return NULL;
-
- for (i = 0; i < n; i++) {
- PyObject *base = PyTuple_GET_ITEM(bases, i);
- PyObject *parentMRO;
- if (PyType_Check(base))
- parentMRO = PySequence_List(
- ((PyTypeObject*)base)->tp_mro);
- else
- parentMRO = classic_mro(base);
- if (parentMRO == NULL) {
- Py_DECREF(to_merge);
- return NULL;
- }
-
- PyList_SET_ITEM(to_merge, i, parentMRO);
- }
-
- bases_aslist = PySequence_List(bases);
- if (bases_aslist == NULL) {
- Py_DECREF(to_merge);
- return NULL;
- }
- /* This is just a basic sanity check. */
- if (check_duplicates(bases_aslist) < 0) {
- Py_DECREF(to_merge);
- Py_DECREF(bases_aslist);
- return NULL;
- }
- PyList_SET_ITEM(to_merge, n, bases_aslist);
-
- result = Py_BuildValue("[O]", (PyObject *)type);
- if (result == NULL) {
- Py_DECREF(to_merge);
- return NULL;
- }
-
- ok = pmerge(result, to_merge);
- Py_DECREF(to_merge);
- if (ok < 0) {
- Py_DECREF(result);
- return NULL;
- }
-
- return result;
+ Py_ssize_t i, n;
+ int ok;
+ PyObject *bases, *result;
+ PyObject *to_merge, *bases_aslist;
+
+ if (type->tp_dict == NULL) {
+ if (PyType_Ready(type) < 0)
+ return NULL;
+ }
+
+ /* Find a superclass linearization that honors the constraints
+ of the explicit lists of bases and the constraints implied by
+ each base class.
+
+ to_merge is a list of lists, where each list is a superclass
+ linearization implied by a base class. The last element of
+ to_merge is the declared list of bases.
+ */
+
+ bases = type->tp_bases;
+ n = PyTuple_GET_SIZE(bases);
+
+ to_merge = PyList_New(n+1);
+ if (to_merge == NULL)
+ return NULL;
+
+ for (i = 0; i < n; i++) {
+ PyObject *base = PyTuple_GET_ITEM(bases, i);
+ PyObject *parentMRO;
+ if (PyType_Check(base))
+ parentMRO = PySequence_List(
+ ((PyTypeObject*)base)->tp_mro);
+ else
+ parentMRO = classic_mro(base);
+ if (parentMRO == NULL) {
+ Py_DECREF(to_merge);
+ return NULL;
+ }
+
+ PyList_SET_ITEM(to_merge, i, parentMRO);
+ }
+
+ bases_aslist = PySequence_List(bases);
+ if (bases_aslist == NULL) {
+ Py_DECREF(to_merge);
+ return NULL;
+ }
+ /* This is just a basic sanity check. */
+ if (check_duplicates(bases_aslist) < 0) {
+ Py_DECREF(to_merge);
+ Py_DECREF(bases_aslist);
+ return NULL;
+ }
+ PyList_SET_ITEM(to_merge, n, bases_aslist);
+
+ result = Py_BuildValue("[O]", (PyObject *)type);
+ if (result == NULL) {
+ Py_DECREF(to_merge);
+ return NULL;
+ }
+
+ ok = pmerge(result, to_merge);
+ Py_DECREF(to_merge);
+ if (ok < 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+
+ return result;
}
static PyObject *
mro_external(PyObject *self)
{
- PyTypeObject *type = (PyTypeObject *)self;
+ PyTypeObject *type = (PyTypeObject *)self;
- return mro_implementation(type);
+ return mro_implementation(type);
}
static int
mro_internal(PyTypeObject *type)
{
- PyObject *mro, *result, *tuple;
- int checkit = 0;
-
- if (Py_TYPE(type) == &PyType_Type) {
- result = mro_implementation(type);
- }
- else {
- static PyObject *mro_str;
- checkit = 1;
- mro = lookup_method((PyObject *)type, "mro", &mro_str);
- if (mro == NULL)
- return -1;
- result = PyObject_CallObject(mro, NULL);
- Py_DECREF(mro);
- }
- if (result == NULL)
- return -1;
- tuple = PySequence_Tuple(result);
- Py_DECREF(result);
- if (tuple == NULL)
- return -1;
- if (checkit) {
- Py_ssize_t i, len;
- PyObject *cls;
- PyTypeObject *solid;
-
- solid = solid_base(type);
-
- len = PyTuple_GET_SIZE(tuple);
-
- for (i = 0; i < len; i++) {
- PyTypeObject *t;
- cls = PyTuple_GET_ITEM(tuple, i);
- if (PyClass_Check(cls))
- continue;
- else if (!PyType_Check(cls)) {
- PyErr_Format(PyExc_TypeError,
- "mro() returned a non-class ('%.500s')",
- Py_TYPE(cls)->tp_name);
- Py_DECREF(tuple);
- return -1;
- }
- t = (PyTypeObject*)cls;
- if (!PyType_IsSubtype(solid, solid_base(t))) {
- PyErr_Format(PyExc_TypeError,
- "mro() returned base with unsuitable layout ('%.500s')",
- t->tp_name);
- Py_DECREF(tuple);
- return -1;
- }
- }
- }
- type->tp_mro = tuple;
-
- type_mro_modified(type, type->tp_mro);
- /* corner case: the old-style super class might have been hidden
- from the custom MRO */
- type_mro_modified(type, type->tp_bases);
-
- PyType_Modified(type);
-
- return 0;
+ PyObject *mro, *result, *tuple;
+ int checkit = 0;
+
+ if (Py_TYPE(type) == &PyType_Type) {
+ result = mro_implementation(type);
+ }
+ else {
+ static PyObject *mro_str;
+ checkit = 1;
+ mro = lookup_method((PyObject *)type, "mro", &mro_str);
+ if (mro == NULL)
+ return -1;
+ result = PyObject_CallObject(mro, NULL);
+ Py_DECREF(mro);
+ }
+ if (result == NULL)
+ return -1;
+ tuple = PySequence_Tuple(result);
+ Py_DECREF(result);
+ if (tuple == NULL)
+ return -1;
+ if (checkit) {
+ Py_ssize_t i, len;
+ PyObject *cls;
+ PyTypeObject *solid;
+
+ solid = solid_base(type);
+
+ len = PyTuple_GET_SIZE(tuple);
+
+ for (i = 0; i < len; i++) {
+ PyTypeObject *t;
+ cls = PyTuple_GET_ITEM(tuple, i);
+ if (PyClass_Check(cls))
+ continue;
+ else if (!PyType_Check(cls)) {
+ PyErr_Format(PyExc_TypeError,
+ "mro() returned a non-class ('%.500s')",
+ Py_TYPE(cls)->tp_name);
+ Py_DECREF(tuple);
+ return -1;
+ }
+ t = (PyTypeObject*)cls;
+ if (!PyType_IsSubtype(solid, solid_base(t))) {
+ PyErr_Format(PyExc_TypeError,
+ "mro() returned base with unsuitable layout ('%.500s')",
+ t->tp_name);
+ Py_DECREF(tuple);
+ return -1;
+ }
+ }
+ }
+ type->tp_mro = tuple;
+
+ type_mro_modified(type, type->tp_mro);
+ /* corner case: the old-style super class might have been hidden
+ from the custom MRO */
+ type_mro_modified(type, type->tp_bases);
+
+ PyType_Modified(type);
+
+ return 0;
}
@@ -1670,92 +1670,92 @@ mro_internal(PyTypeObject *type)
static PyTypeObject *
best_base(PyObject *bases)
{
- Py_ssize_t i, n;
- PyTypeObject *base, *winner, *candidate, *base_i;
- PyObject *base_proto;
-
- assert(PyTuple_Check(bases));
- n = PyTuple_GET_SIZE(bases);
- assert(n > 0);
- base = NULL;
- winner = NULL;
- for (i = 0; i < n; i++) {
- base_proto = PyTuple_GET_ITEM(bases, i);
- if (PyClass_Check(base_proto))
- continue;
- if (!PyType_Check(base_proto)) {
- PyErr_SetString(
- PyExc_TypeError,
- "bases must be types");
- return NULL;
- }
- base_i = (PyTypeObject *)base_proto;
- if (base_i->tp_dict == NULL) {
- if (PyType_Ready(base_i) < 0)
- return NULL;
- }
- candidate = solid_base(base_i);
- if (winner == NULL) {
- winner = candidate;
- base = base_i;
- }
- else if (PyType_IsSubtype(winner, candidate))
- ;
- else if (PyType_IsSubtype(candidate, winner)) {
- winner = candidate;
- base = base_i;
- }
- else {
- PyErr_SetString(
- PyExc_TypeError,
- "multiple bases have "
- "instance lay-out conflict");
- return NULL;
- }
- }
- if (base == NULL)
- PyErr_SetString(PyExc_TypeError,
- "a new-style class can't have only classic bases");
- return base;
+ Py_ssize_t i, n;
+ PyTypeObject *base, *winner, *candidate, *base_i;
+ PyObject *base_proto;
+
+ assert(PyTuple_Check(bases));
+ n = PyTuple_GET_SIZE(bases);
+ assert(n > 0);
+ base = NULL;
+ winner = NULL;
+ for (i = 0; i < n; i++) {
+ base_proto = PyTuple_GET_ITEM(bases, i);
+ if (PyClass_Check(base_proto))
+ continue;
+ if (!PyType_Check(base_proto)) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "bases must be types");
+ return NULL;
+ }
+ base_i = (PyTypeObject *)base_proto;
+ if (base_i->tp_dict == NULL) {
+ if (PyType_Ready(base_i) < 0)
+ return NULL;
+ }
+ candidate = solid_base(base_i);
+ if (winner == NULL) {
+ winner = candidate;
+ base = base_i;
+ }
+ else if (PyType_IsSubtype(winner, candidate))
+ ;
+ else if (PyType_IsSubtype(candidate, winner)) {
+ winner = candidate;
+ base = base_i;
+ }
+ else {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "multiple bases have "
+ "instance lay-out conflict");
+ return NULL;
+ }
+ }
+ if (base == NULL)
+ PyErr_SetString(PyExc_TypeError,
+ "a new-style class can't have only classic bases");
+ return base;
}
static int
extra_ivars(PyTypeObject *type, PyTypeObject *base)
{
- size_t t_size = type->tp_basicsize;
- size_t b_size = base->tp_basicsize;
+ size_t t_size = type->tp_basicsize;
+ size_t b_size = base->tp_basicsize;
- assert(t_size >= b_size); /* Else type smaller than base! */
- if (type->tp_itemsize || base->tp_itemsize) {
- /* If itemsize is involved, stricter rules */
- return t_size != b_size ||
- type->tp_itemsize != base->tp_itemsize;
- }
- if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
- type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
- type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- t_size -= sizeof(PyObject *);
- if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
- type->tp_dictoffset + sizeof(PyObject *) == t_size &&
- type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- t_size -= sizeof(PyObject *);
+ assert(t_size >= b_size); /* Else type smaller than base! */
+ if (type->tp_itemsize || base->tp_itemsize) {
+ /* If itemsize is involved, stricter rules */
+ return t_size != b_size ||
+ type->tp_itemsize != base->tp_itemsize;
+ }
+ if (type->tp_weaklistoffset && base->tp_weaklistoffset == 0 &&
+ type->tp_weaklistoffset + sizeof(PyObject *) == t_size &&
+ type->tp_flags & Py_TPFLAGS_HEAPTYPE)
+ t_size -= sizeof(PyObject *);
+ if (type->tp_dictoffset && base->tp_dictoffset == 0 &&
+ type->tp_dictoffset + sizeof(PyObject *) == t_size &&
+ type->tp_flags & Py_TPFLAGS_HEAPTYPE)
+ t_size -= sizeof(PyObject *);
- return t_size != b_size;
+ return t_size != b_size;
}
static PyTypeObject *
solid_base(PyTypeObject *type)
{
- PyTypeObject *base;
+ PyTypeObject *base;
- if (type->tp_base)
- base = solid_base(type->tp_base);
- else
- base = &PyBaseObject_Type;
- if (extra_ivars(type, base))
- return type;
- else
- return base;
+ if (type->tp_base)
+ base = solid_base(type->tp_base);
+ else
+ base = &PyBaseObject_Type;
+ if (extra_ivars(type, base))
+ return type;
+ else
+ return base;
}
static void object_dealloc(PyObject *);
@@ -1771,191 +1771,191 @@ static void fixup_slot_dispatchers(PyTypeObject *);
static PyTypeObject *
get_builtin_base_with_dict(PyTypeObject *type)
{
- while (type->tp_base != NULL) {
- if (type->tp_dictoffset != 0 &&
- !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
- return type;
- type = type->tp_base;
- }
- return NULL;
+ while (type->tp_base != NULL) {
+ if (type->tp_dictoffset != 0 &&
+ !(type->tp_flags & Py_TPFLAGS_HEAPTYPE))
+ return type;
+ type = type->tp_base;
+ }
+ return NULL;
}
static PyObject *
get_dict_descriptor(PyTypeObject *type)
{
- static PyObject *dict_str;
- PyObject *descr;
+ static PyObject *dict_str;
+ PyObject *descr;
- if (dict_str == NULL) {
- dict_str = PyString_InternFromString("__dict__");
- if (dict_str == NULL)
- return NULL;
- }
- descr = _PyType_Lookup(type, dict_str);
- if (descr == NULL || !PyDescr_IsData(descr))
- return NULL;
+ if (dict_str == NULL) {
+ dict_str = PyString_InternFromString("__dict__");
+ if (dict_str == NULL)
+ return NULL;
+ }
+ descr = _PyType_Lookup(type, dict_str);
+ if (descr == NULL || !PyDescr_IsData(descr))
+ return NULL;
- return descr;
+ return descr;
}
static void
raise_dict_descr_error(PyObject *obj)
{
- PyErr_Format(PyExc_TypeError,
- "this __dict__ descriptor does not support "
- "'%.200s' objects", obj->ob_type->tp_name);
+ PyErr_Format(PyExc_TypeError,
+ "this __dict__ descriptor does not support "
+ "'%.200s' objects", obj->ob_type->tp_name);
}
static PyObject *
subtype_dict(PyObject *obj, void *context)
{
- PyObject **dictptr;
- PyObject *dict;
- PyTypeObject *base;
-
- base = get_builtin_base_with_dict(obj->ob_type);
- if (base != NULL) {
- descrgetfunc func;
- PyObject *descr = get_dict_descriptor(base);
- if (descr == NULL) {
- raise_dict_descr_error(obj);
- return NULL;
- }
- func = descr->ob_type->tp_descr_get;
- if (func == NULL) {
- raise_dict_descr_error(obj);
- return NULL;
- }
- return func(descr, obj, (PyObject *)(obj->ob_type));
- }
-
- dictptr = _PyObject_GetDictPtr(obj);
- if (dictptr == NULL) {
- PyErr_SetString(PyExc_AttributeError,
- "This object has no __dict__");
- return NULL;
- }
- dict = *dictptr;
- if (dict == NULL)
- *dictptr = dict = PyDict_New();
- Py_XINCREF(dict);
- return dict;
+ PyObject **dictptr;
+ PyObject *dict;
+ PyTypeObject *base;
+
+ base = get_builtin_base_with_dict(obj->ob_type);
+ if (base != NULL) {
+ descrgetfunc func;
+ PyObject *descr = get_dict_descriptor(base);
+ if (descr == NULL) {
+ raise_dict_descr_error(obj);
+ return NULL;
+ }
+ func = descr->ob_type->tp_descr_get;
+ if (func == NULL) {
+ raise_dict_descr_error(obj);
+ return NULL;
+ }
+ return func(descr, obj, (PyObject *)(obj->ob_type));
+ }
+
+ dictptr = _PyObject_GetDictPtr(obj);
+ if (dictptr == NULL) {
+ PyErr_SetString(PyExc_AttributeError,
+ "This object has no __dict__");
+ return NULL;
+ }
+ dict = *dictptr;
+ if (dict == NULL)
+ *dictptr = dict = PyDict_New();
+ Py_XINCREF(dict);
+ return dict;
}
static int
subtype_setdict(PyObject *obj, PyObject *value, void *context)
{
- PyObject **dictptr;
- PyObject *dict;
- PyTypeObject *base;
-
- base = get_builtin_base_with_dict(obj->ob_type);
- if (base != NULL) {
- descrsetfunc func;
- PyObject *descr = get_dict_descriptor(base);
- if (descr == NULL) {
- raise_dict_descr_error(obj);
- return -1;
- }
- func = descr->ob_type->tp_descr_set;
- if (func == NULL) {
- raise_dict_descr_error(obj);
- return -1;
- }
- return func(descr, obj, value);
- }
-
- dictptr = _PyObject_GetDictPtr(obj);
- if (dictptr == NULL) {
- PyErr_SetString(PyExc_AttributeError,
- "This object has no __dict__");
- return -1;
- }
- if (value != NULL && !PyDict_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "__dict__ must be set to a dictionary, "
- "not a '%.200s'", Py_TYPE(value)->tp_name);
- return -1;
- }
- dict = *dictptr;
- Py_XINCREF(value);
- *dictptr = value;
- Py_XDECREF(dict);
- return 0;
+ PyObject **dictptr;
+ PyObject *dict;
+ PyTypeObject *base;
+
+ base = get_builtin_base_with_dict(obj->ob_type);
+ if (base != NULL) {
+ descrsetfunc func;
+ PyObject *descr = get_dict_descriptor(base);
+ if (descr == NULL) {
+ raise_dict_descr_error(obj);
+ return -1;
+ }
+ func = descr->ob_type->tp_descr_set;
+ if (func == NULL) {
+ raise_dict_descr_error(obj);
+ return -1;
+ }
+ return func(descr, obj, value);
+ }
+
+ dictptr = _PyObject_GetDictPtr(obj);
+ if (dictptr == NULL) {
+ PyErr_SetString(PyExc_AttributeError,
+ "This object has no __dict__");
+ return -1;
+ }
+ if (value != NULL && !PyDict_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "__dict__ must be set to a dictionary, "
+ "not a '%.200s'", Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ dict = *dictptr;
+ Py_XINCREF(value);
+ *dictptr = value;
+ Py_XDECREF(dict);
+ return 0;
}
static PyObject *
subtype_getweakref(PyObject *obj, void *context)
{
- PyObject **weaklistptr;
- PyObject *result;
-
- if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
- PyErr_SetString(PyExc_AttributeError,
- "This object has no __weakref__");
- return NULL;
- }
- assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
- assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
- (size_t)(Py_TYPE(obj)->tp_basicsize));
- weaklistptr = (PyObject **)
- ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
- if (*weaklistptr == NULL)
- result = Py_None;
- else
- result = *weaklistptr;
- Py_INCREF(result);
- return result;
+ PyObject **weaklistptr;
+ PyObject *result;
+
+ if (Py_TYPE(obj)->tp_weaklistoffset == 0) {
+ PyErr_SetString(PyExc_AttributeError,
+ "This object has no __weakref__");
+ return NULL;
+ }
+ assert(Py_TYPE(obj)->tp_weaklistoffset > 0);
+ assert(Py_TYPE(obj)->tp_weaklistoffset + sizeof(PyObject *) <=
+ (size_t)(Py_TYPE(obj)->tp_basicsize));
+ weaklistptr = (PyObject **)
+ ((char *)obj + Py_TYPE(obj)->tp_weaklistoffset);
+ if (*weaklistptr == NULL)
+ result = Py_None;
+ else
+ result = *weaklistptr;
+ Py_INCREF(result);
+ return result;
}
/* Three variants on the subtype_getsets list. */
static PyGetSetDef subtype_getsets_full[] = {
- {"__dict__", subtype_dict, subtype_setdict,
- PyDoc_STR("dictionary for instance variables (if defined)")},
- {"__weakref__", subtype_getweakref, NULL,
- PyDoc_STR("list of weak references to the object (if defined)")},
- {0}
+ {"__dict__", subtype_dict, subtype_setdict,
+ PyDoc_STR("dictionary for instance variables (if defined)")},
+ {"__weakref__", subtype_getweakref, NULL,
+ PyDoc_STR("list of weak references to the object (if defined)")},
+ {0}
};
static PyGetSetDef subtype_getsets_dict_only[] = {
- {"__dict__", subtype_dict, subtype_setdict,
- PyDoc_STR("dictionary for instance variables (if defined)")},
- {0}
+ {"__dict__", subtype_dict, subtype_setdict,
+ PyDoc_STR("dictionary for instance variables (if defined)")},
+ {0}
};
static PyGetSetDef subtype_getsets_weakref_only[] = {
- {"__weakref__", subtype_getweakref, NULL,
- PyDoc_STR("list of weak references to the object (if defined)")},
- {0}
+ {"__weakref__", subtype_getweakref, NULL,
+ PyDoc_STR("list of weak references to the object (if defined)")},
+ {0}
};
static int
valid_identifier(PyObject *s)
{
- unsigned char *p;
- Py_ssize_t i, n;
-
- if (!PyString_Check(s)) {
- PyErr_Format(PyExc_TypeError,
- "__slots__ items must be strings, not '%.200s'",
- Py_TYPE(s)->tp_name);
- return 0;
- }
- p = (unsigned char *) PyString_AS_STRING(s);
- n = PyString_GET_SIZE(s);
- /* We must reject an empty name. As a hack, we bump the
- length to 1 so that the loop will balk on the trailing \0. */
- if (n == 0)
- n = 1;
- for (i = 0; i < n; i++, p++) {
- if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
- PyErr_SetString(PyExc_TypeError,
- "__slots__ must be identifiers");
- return 0;
- }
- }
- return 1;
+ unsigned char *p;
+ Py_ssize_t i, n;
+
+ if (!PyString_Check(s)) {
+ PyErr_Format(PyExc_TypeError,
+ "__slots__ items must be strings, not '%.200s'",
+ Py_TYPE(s)->tp_name);
+ return 0;
+ }
+ p = (unsigned char *) PyString_AS_STRING(s);
+ n = PyString_GET_SIZE(s);
+ /* We must reject an empty name. As a hack, we bump the
+ length to 1 so that the loop will balk on the trailing \0. */
+ if (n == 0)
+ n = 1;
+ for (i = 0; i < n; i++, p++) {
+ if (!(i == 0 ? isalpha(*p) : isalnum(*p)) && *p != '_') {
+ PyErr_SetString(PyExc_TypeError,
+ "__slots__ must be identifiers");
+ return 0;
+ }
+ }
+ return 1;
}
#ifdef Py_USING_UNICODE
@@ -1964,33 +1964,33 @@ valid_identifier(PyObject *s)
static PyObject *
_unicode_to_string(PyObject *slots, Py_ssize_t nslots)
{
- PyObject *tmp = NULL;
- PyObject *slot_name, *new_name;
- Py_ssize_t i;
-
- for (i = 0; i < nslots; i++) {
- if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
- if (tmp == NULL) {
- tmp = PySequence_List(slots);
- if (tmp == NULL)
- return NULL;
- }
- new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
- NULL);
- if (new_name == NULL) {
- Py_DECREF(tmp);
- return NULL;
- }
- Py_INCREF(new_name);
- PyList_SET_ITEM(tmp, i, new_name);
- Py_DECREF(slot_name);
- }
- }
- if (tmp != NULL) {
- slots = PyList_AsTuple(tmp);
- Py_DECREF(tmp);
- }
- return slots;
+ PyObject *tmp = NULL;
+ PyObject *slot_name, *new_name;
+ Py_ssize_t i;
+
+ for (i = 0; i < nslots; i++) {
+ if (PyUnicode_Check(slot_name = PyTuple_GET_ITEM(slots, i))) {
+ if (tmp == NULL) {
+ tmp = PySequence_List(slots);
+ if (tmp == NULL)
+ return NULL;
+ }
+ new_name = _PyUnicode_AsDefaultEncodedString(slot_name,
+ NULL);
+ if (new_name == NULL) {
+ Py_DECREF(tmp);
+ return NULL;
+ }
+ Py_INCREF(new_name);
+ PyList_SET_ITEM(tmp, i, new_name);
+ Py_DECREF(slot_name);
+ }
+ }
+ if (tmp != NULL) {
+ slots = PyList_AsTuple(tmp);
+ Py_DECREF(tmp);
+ }
+ return slots;
}
#endif
@@ -2001,450 +2001,450 @@ object_init(PyObject *self, PyObject *args, PyObject *kwds);
static int
type_init(PyObject *cls, PyObject *args, PyObject *kwds)
{
- int res;
+ int res;
- assert(args != NULL && PyTuple_Check(args));
- assert(kwds == NULL || PyDict_Check(kwds));
+ assert(args != NULL && PyTuple_Check(args));
+ assert(kwds == NULL || PyDict_Check(kwds));
- if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
- PyErr_SetString(PyExc_TypeError,
- "type.__init__() takes no keyword arguments");
- return -1;
- }
+ if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds) != 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "type.__init__() takes no keyword arguments");
+ return -1;
+ }
- if (args != NULL && PyTuple_Check(args) &&
- (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
- PyErr_SetString(PyExc_TypeError,
- "type.__init__() takes 1 or 3 arguments");
- return -1;
- }
+ if (args != NULL && PyTuple_Check(args) &&
+ (PyTuple_GET_SIZE(args) != 1 && PyTuple_GET_SIZE(args) != 3)) {
+ PyErr_SetString(PyExc_TypeError,
+ "type.__init__() takes 1 or 3 arguments");
+ return -1;
+ }
- /* Call object.__init__(self) now. */
- /* XXX Could call super(type, cls).__init__() but what's the point? */
- args = PyTuple_GetSlice(args, 0, 0);
- res = object_init(cls, args, NULL);
- Py_DECREF(args);
- return res;
+ /* Call object.__init__(self) now. */
+ /* XXX Could call super(type, cls).__init__() but what's the point? */
+ args = PyTuple_GetSlice(args, 0, 0);
+ res = object_init(cls, args, NULL);
+ Py_DECREF(args);
+ return res;
}
static PyObject *
type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
{
- PyObject *name, *bases, *dict;
- static char *kwlist[] = {"name", "bases", "dict", 0};
- PyObject *slots, *tmp, *newslots;
- PyTypeObject *type, *base, *tmptype, *winner;
- PyHeapTypeObject *et;
- PyMemberDef *mp;
- Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
- int j, may_add_dict, may_add_weak;
-
- assert(args != NULL && PyTuple_Check(args));
- assert(kwds == NULL || PyDict_Check(kwds));
-
- /* Special case: type(x) should return x->ob_type */
- {
- const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
- const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
-
- if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
- PyObject *x = PyTuple_GET_ITEM(args, 0);
- Py_INCREF(Py_TYPE(x));
- return (PyObject *) Py_TYPE(x);
- }
-
- /* SF bug 475327 -- if that didn't trigger, we need 3
- arguments. but PyArg_ParseTupleAndKeywords below may give
- a msg saying type() needs exactly 3. */
- if (nargs + nkwds != 3) {
- PyErr_SetString(PyExc_TypeError,
- "type() takes 1 or 3 arguments");
- return NULL;
- }
- }
-
- /* Check arguments: (name, bases, dict) */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
- &name,
- &PyTuple_Type, &bases,
- &PyDict_Type, &dict))
- return NULL;
-
- /* Determine the proper metatype to deal with this,
- and check for metatype conflicts while we're at it.
- Note that if some other metatype wins to contract,
- it's possible that its instances are not types. */
- nbases = PyTuple_GET_SIZE(bases);
- winner = metatype;
- for (i = 0; i < nbases; i++) {
- tmp = PyTuple_GET_ITEM(bases, i);
- tmptype = tmp->ob_type;
- if (tmptype == &PyClass_Type)
- continue; /* Special case classic classes */
- if (PyType_IsSubtype(winner, tmptype))
- continue;
- if (PyType_IsSubtype(tmptype, winner)) {
- winner = tmptype;
- continue;
- }
- PyErr_SetString(PyExc_TypeError,
- "metaclass conflict: "
- "the metaclass of a derived class "
- "must be a (non-strict) subclass "
- "of the metaclasses of all its bases");
- return NULL;
- }
- if (winner != metatype) {
- if (winner->tp_new != type_new) /* Pass it to the winner */
- return winner->tp_new(winner, args, kwds);
- metatype = winner;
- }
-
- /* Adjust for empty tuple bases */
- if (nbases == 0) {
- bases = PyTuple_Pack(1, &PyBaseObject_Type);
- if (bases == NULL)
- return NULL;
- nbases = 1;
- }
- else
- Py_INCREF(bases);
-
- /* XXX From here until type is allocated, "return NULL" leaks bases! */
-
- /* Calculate best base, and check that all bases are type objects */
- base = best_base(bases);
- if (base == NULL) {
- Py_DECREF(bases);
- return NULL;
- }
- if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
- PyErr_Format(PyExc_TypeError,
- "type '%.100s' is not an acceptable base type",
- base->tp_name);
- Py_DECREF(bases);
- return NULL;
- }
-
- /* Check for a __slots__ sequence variable in dict, and count it */
- slots = PyDict_GetItemString(dict, "__slots__");
- nslots = 0;
- add_dict = 0;
- add_weak = 0;
- may_add_dict = base->tp_dictoffset == 0;
- may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
- if (slots == NULL) {
- if (may_add_dict) {
- add_dict++;
- }
- if (may_add_weak) {
- add_weak++;
- }
- }
- else {
- /* Have slots */
-
- /* Make it into a tuple */
- if (PyString_Check(slots) || PyUnicode_Check(slots))
- slots = PyTuple_Pack(1, slots);
- else
- slots = PySequence_Tuple(slots);
- if (slots == NULL) {
- Py_DECREF(bases);
- return NULL;
- }
- assert(PyTuple_Check(slots));
-
- /* Are slots allowed? */
- nslots = PyTuple_GET_SIZE(slots);
- if (nslots > 0 && base->tp_itemsize != 0) {
- PyErr_Format(PyExc_TypeError,
- "nonempty __slots__ "
- "not supported for subtype of '%s'",
- base->tp_name);
- bad_slots:
- Py_DECREF(bases);
- Py_DECREF(slots);
- return NULL;
- }
+ PyObject *name, *bases, *dict;
+ static char *kwlist[] = {"name", "bases", "dict", 0};
+ PyObject *slots, *tmp, *newslots;
+ PyTypeObject *type, *base, *tmptype, *winner;
+ PyHeapTypeObject *et;
+ PyMemberDef *mp;
+ Py_ssize_t i, nbases, nslots, slotoffset, add_dict, add_weak;
+ int j, may_add_dict, may_add_weak;
+
+ assert(args != NULL && PyTuple_Check(args));
+ assert(kwds == NULL || PyDict_Check(kwds));
+
+ /* Special case: type(x) should return x->ob_type */
+ {
+ const Py_ssize_t nargs = PyTuple_GET_SIZE(args);
+ const Py_ssize_t nkwds = kwds == NULL ? 0 : PyDict_Size(kwds);
+
+ if (PyType_CheckExact(metatype) && nargs == 1 && nkwds == 0) {
+ PyObject *x = PyTuple_GET_ITEM(args, 0);
+ Py_INCREF(Py_TYPE(x));
+ return (PyObject *) Py_TYPE(x);
+ }
+
+ /* SF bug 475327 -- if that didn't trigger, we need 3
+ arguments. but PyArg_ParseTupleAndKeywords below may give
+ a msg saying type() needs exactly 3. */
+ if (nargs + nkwds != 3) {
+ PyErr_SetString(PyExc_TypeError,
+ "type() takes 1 or 3 arguments");
+ return NULL;
+ }
+ }
+
+ /* Check arguments: (name, bases, dict) */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "SO!O!:type", kwlist,
+ &name,
+ &PyTuple_Type, &bases,
+ &PyDict_Type, &dict))
+ return NULL;
+
+ /* Determine the proper metatype to deal with this,
+ and check for metatype conflicts while we're at it.
+ Note that if some other metatype wins to contract,
+ it's possible that its instances are not types. */
+ nbases = PyTuple_GET_SIZE(bases);
+ winner = metatype;
+ for (i = 0; i < nbases; i++) {
+ tmp = PyTuple_GET_ITEM(bases, i);
+ tmptype = tmp->ob_type;
+ if (tmptype == &PyClass_Type)
+ continue; /* Special case classic classes */
+ if (PyType_IsSubtype(winner, tmptype))
+ continue;
+ if (PyType_IsSubtype(tmptype, winner)) {
+ winner = tmptype;
+ continue;
+ }
+ PyErr_SetString(PyExc_TypeError,
+ "metaclass conflict: "
+ "the metaclass of a derived class "
+ "must be a (non-strict) subclass "
+ "of the metaclasses of all its bases");
+ return NULL;
+ }
+ if (winner != metatype) {
+ if (winner->tp_new != type_new) /* Pass it to the winner */
+ return winner->tp_new(winner, args, kwds);
+ metatype = winner;
+ }
+
+ /* Adjust for empty tuple bases */
+ if (nbases == 0) {
+ bases = PyTuple_Pack(1, &PyBaseObject_Type);
+ if (bases == NULL)
+ return NULL;
+ nbases = 1;
+ }
+ else
+ Py_INCREF(bases);
+
+ /* XXX From here until type is allocated, "return NULL" leaks bases! */
+
+ /* Calculate best base, and check that all bases are type objects */
+ base = best_base(bases);
+ if (base == NULL) {
+ Py_DECREF(bases);
+ return NULL;
+ }
+ if (!PyType_HasFeature(base, Py_TPFLAGS_BASETYPE)) {
+ PyErr_Format(PyExc_TypeError,
+ "type '%.100s' is not an acceptable base type",
+ base->tp_name);
+ Py_DECREF(bases);
+ return NULL;
+ }
+
+ /* Check for a __slots__ sequence variable in dict, and count it */
+ slots = PyDict_GetItemString(dict, "__slots__");
+ nslots = 0;
+ add_dict = 0;
+ add_weak = 0;
+ may_add_dict = base->tp_dictoffset == 0;
+ may_add_weak = base->tp_weaklistoffset == 0 && base->tp_itemsize == 0;
+ if (slots == NULL) {
+ if (may_add_dict) {
+ add_dict++;
+ }
+ if (may_add_weak) {
+ add_weak++;
+ }
+ }
+ else {
+ /* Have slots */
+
+ /* Make it into a tuple */
+ if (PyString_Check(slots) || PyUnicode_Check(slots))
+ slots = PyTuple_Pack(1, slots);
+ else
+ slots = PySequence_Tuple(slots);
+ if (slots == NULL) {
+ Py_DECREF(bases);
+ return NULL;
+ }
+ assert(PyTuple_Check(slots));
+
+ /* Are slots allowed? */
+ nslots = PyTuple_GET_SIZE(slots);
+ if (nslots > 0 && base->tp_itemsize != 0) {
+ PyErr_Format(PyExc_TypeError,
+ "nonempty __slots__ "
+ "not supported for subtype of '%s'",
+ base->tp_name);
+ bad_slots:
+ Py_DECREF(bases);
+ Py_DECREF(slots);
+ return NULL;
+ }
#ifdef Py_USING_UNICODE
- tmp = _unicode_to_string(slots, nslots);
- if (tmp == NULL)
- goto bad_slots;
- if (tmp != slots) {
- Py_DECREF(slots);
- slots = tmp;
- }
+ tmp = _unicode_to_string(slots, nslots);
+ if (tmp == NULL)
+ goto bad_slots;
+ if (tmp != slots) {
+ Py_DECREF(slots);
+ slots = tmp;
+ }
#endif
- /* Check for valid slot names and two special cases */
- for (i = 0; i < nslots; i++) {
- PyObject *tmp = PyTuple_GET_ITEM(slots, i);
- char *s;
- if (!valid_identifier(tmp))
- goto bad_slots;
- assert(PyString_Check(tmp));
- s = PyString_AS_STRING(tmp);
- if (strcmp(s, "__dict__") == 0) {
- if (!may_add_dict || add_dict) {
- PyErr_SetString(PyExc_TypeError,
- "__dict__ slot disallowed: "
- "we already got one");
- goto bad_slots;
- }
- add_dict++;
- }
- if (strcmp(s, "__weakref__") == 0) {
- if (!may_add_weak || add_weak) {
- PyErr_SetString(PyExc_TypeError,
- "__weakref__ slot disallowed: "
- "either we already got one, "
- "or __itemsize__ != 0");
- goto bad_slots;
- }
- add_weak++;
- }
- }
-
- /* Copy slots into a list, mangle names and sort them.
- Sorted names are needed for __class__ assignment.
- Convert them back to tuple at the end.
- */
- newslots = PyList_New(nslots - add_dict - add_weak);
- if (newslots == NULL)
- goto bad_slots;
- for (i = j = 0; i < nslots; i++) {
- char *s;
- tmp = PyTuple_GET_ITEM(slots, i);
- s = PyString_AS_STRING(tmp);
- if ((add_dict && strcmp(s, "__dict__") == 0) ||
- (add_weak && strcmp(s, "__weakref__") == 0))
- continue;
- tmp =_Py_Mangle(name, tmp);
- if (!tmp)
- goto bad_slots;
- PyList_SET_ITEM(newslots, j, tmp);
- j++;
- }
- assert(j == nslots - add_dict - add_weak);
- nslots = j;
- Py_DECREF(slots);
- if (PyList_Sort(newslots) == -1) {
- Py_DECREF(bases);
- Py_DECREF(newslots);
- return NULL;
- }
- slots = PyList_AsTuple(newslots);
- Py_DECREF(newslots);
- if (slots == NULL) {
- Py_DECREF(bases);
- return NULL;
- }
-
- /* Secondary bases may provide weakrefs or dict */
- if (nbases > 1 &&
- ((may_add_dict && !add_dict) ||
- (may_add_weak && !add_weak))) {
- for (i = 0; i < nbases; i++) {
- tmp = PyTuple_GET_ITEM(bases, i);
- if (tmp == (PyObject *)base)
- continue; /* Skip primary base */
- if (PyClass_Check(tmp)) {
- /* Classic base class provides both */
- if (may_add_dict && !add_dict)
- add_dict++;
- if (may_add_weak && !add_weak)
- add_weak++;
- break;
- }
- assert(PyType_Check(tmp));
- tmptype = (PyTypeObject *)tmp;
- if (may_add_dict && !add_dict &&
- tmptype->tp_dictoffset != 0)
- add_dict++;
- if (may_add_weak && !add_weak &&
- tmptype->tp_weaklistoffset != 0)
- add_weak++;
- if (may_add_dict && !add_dict)
- continue;
- if (may_add_weak && !add_weak)
- continue;
- /* Nothing more to check */
- break;
- }
- }
- }
-
- /* XXX From here until type is safely allocated,
- "return NULL" may leak slots! */
-
- /* Allocate the type object */
- type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
- if (type == NULL) {
- Py_XDECREF(slots);
- Py_DECREF(bases);
- return NULL;
- }
-
- /* Keep name and slots alive in the extended type object */
- et = (PyHeapTypeObject *)type;
- Py_INCREF(name);
- et->ht_name = name;
- et->ht_slots = slots;
-
- /* Initialize tp_flags */
- type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
- Py_TPFLAGS_BASETYPE;
- if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
- type->tp_flags |= Py_TPFLAGS_HAVE_GC;
- if (base->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER)
- type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
-
- /* It's a new-style number unless it specifically inherits any
- old-style numeric behavior */
- if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
- (base->tp_as_number == NULL))
- type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
-
- /* Initialize essential fields */
- type->tp_as_number = &et->as_number;
- type->tp_as_sequence = &et->as_sequence;
- type->tp_as_mapping = &et->as_mapping;
- type->tp_as_buffer = &et->as_buffer;
- type->tp_name = PyString_AS_STRING(name);
-
- /* Set tp_base and tp_bases */
- type->tp_bases = bases;
- Py_INCREF(base);
- type->tp_base = base;
-
- /* Initialize tp_dict from passed-in dict */
- type->tp_dict = dict = PyDict_Copy(dict);
- if (dict == NULL) {
- Py_DECREF(type);
- return NULL;
- }
-
- /* Set __module__ in the dict */
- if (PyDict_GetItemString(dict, "__module__") == NULL) {
- tmp = PyEval_GetGlobals();
- if (tmp != NULL) {
- tmp = PyDict_GetItemString(tmp, "__name__");
- if (tmp != NULL) {
- if (PyDict_SetItemString(dict, "__module__",
- tmp) < 0)
- return NULL;
- }
- }
- }
-
- /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
- and is a string. The __doc__ accessor will first look for tp_doc;
- if that fails, it will still look into __dict__.
- */
- {
- PyObject *doc = PyDict_GetItemString(dict, "__doc__");
- if (doc != NULL && PyString_Check(doc)) {
- const size_t n = (size_t)PyString_GET_SIZE(doc);
- char *tp_doc = (char *)PyObject_MALLOC(n+1);
- if (tp_doc == NULL) {
- Py_DECREF(type);
- return NULL;
- }
- memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
- type->tp_doc = tp_doc;
- }
- }
-
- /* Special-case __new__: if it's a plain function,
- make it a static function */
- tmp = PyDict_GetItemString(dict, "__new__");
- if (tmp != NULL && PyFunction_Check(tmp)) {
- tmp = PyStaticMethod_New(tmp);
- if (tmp == NULL) {
- Py_DECREF(type);
- return NULL;
- }
- PyDict_SetItemString(dict, "__new__", tmp);
- Py_DECREF(tmp);
- }
-
- /* Add descriptors for custom slots from __slots__, or for __dict__ */
- mp = PyHeapType_GET_MEMBERS(et);
- slotoffset = base->tp_basicsize;
- if (slots != NULL) {
- for (i = 0; i < nslots; i++, mp++) {
- mp->name = PyString_AS_STRING(
- PyTuple_GET_ITEM(slots, i));
- mp->type = T_OBJECT_EX;
- mp->offset = slotoffset;
-
- /* __dict__ and __weakref__ are already filtered out */
- assert(strcmp(mp->name, "__dict__") != 0);
- assert(strcmp(mp->name, "__weakref__") != 0);
-
- slotoffset += sizeof(PyObject *);
- }
- }
- if (add_dict) {
- if (base->tp_itemsize)
- type->tp_dictoffset = -(long)sizeof(PyObject *);
- else
- type->tp_dictoffset = slotoffset;
- slotoffset += sizeof(PyObject *);
- }
- if (add_weak) {
- assert(!base->tp_itemsize);
- type->tp_weaklistoffset = slotoffset;
- slotoffset += sizeof(PyObject *);
- }
- type->tp_basicsize = slotoffset;
- type->tp_itemsize = base->tp_itemsize;
- type->tp_members = PyHeapType_GET_MEMBERS(et);
-
- if (type->tp_weaklistoffset && type->tp_dictoffset)
- type->tp_getset = subtype_getsets_full;
- else if (type->tp_weaklistoffset && !type->tp_dictoffset)
- type->tp_getset = subtype_getsets_weakref_only;
- else if (!type->tp_weaklistoffset && type->tp_dictoffset)
- type->tp_getset = subtype_getsets_dict_only;
- else
- type->tp_getset = NULL;
-
- /* Special case some slots */
- if (type->tp_dictoffset != 0 || nslots > 0) {
- if (base->tp_getattr == NULL && base->tp_getattro == NULL)
- type->tp_getattro = PyObject_GenericGetAttr;
- if (base->tp_setattr == NULL && base->tp_setattro == NULL)
- type->tp_setattro = PyObject_GenericSetAttr;
- }
- type->tp_dealloc = subtype_dealloc;
-
- /* Enable GC unless there are really no instance variables possible */
- if (!(type->tp_basicsize == sizeof(PyObject) &&
- type->tp_itemsize == 0))
- type->tp_flags |= Py_TPFLAGS_HAVE_GC;
-
- /* Always override allocation strategy to use regular heap */
- type->tp_alloc = PyType_GenericAlloc;
- if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
- type->tp_free = PyObject_GC_Del;
- type->tp_traverse = subtype_traverse;
- type->tp_clear = subtype_clear;
- }
- else
- type->tp_free = PyObject_Del;
-
- /* Initialize the rest */
- if (PyType_Ready(type) < 0) {
- Py_DECREF(type);
- return NULL;
- }
-
- /* Put the proper slots in place */
- fixup_slot_dispatchers(type);
-
- return (PyObject *)type;
+ /* Check for valid slot names and two special cases */
+ for (i = 0; i < nslots; i++) {
+ PyObject *tmp = PyTuple_GET_ITEM(slots, i);
+ char *s;
+ if (!valid_identifier(tmp))
+ goto bad_slots;
+ assert(PyString_Check(tmp));
+ s = PyString_AS_STRING(tmp);
+ if (strcmp(s, "__dict__") == 0) {
+ if (!may_add_dict || add_dict) {
+ PyErr_SetString(PyExc_TypeError,
+ "__dict__ slot disallowed: "
+ "we already got one");
+ goto bad_slots;
+ }
+ add_dict++;
+ }
+ if (strcmp(s, "__weakref__") == 0) {
+ if (!may_add_weak || add_weak) {
+ PyErr_SetString(PyExc_TypeError,
+ "__weakref__ slot disallowed: "
+ "either we already got one, "
+ "or __itemsize__ != 0");
+ goto bad_slots;
+ }
+ add_weak++;
+ }
+ }
+
+ /* Copy slots into a list, mangle names and sort them.
+ Sorted names are needed for __class__ assignment.
+ Convert them back to tuple at the end.
+ */
+ newslots = PyList_New(nslots - add_dict - add_weak);
+ if (newslots == NULL)
+ goto bad_slots;
+ for (i = j = 0; i < nslots; i++) {
+ char *s;
+ tmp = PyTuple_GET_ITEM(slots, i);
+ s = PyString_AS_STRING(tmp);
+ if ((add_dict && strcmp(s, "__dict__") == 0) ||
+ (add_weak && strcmp(s, "__weakref__") == 0))
+ continue;
+ tmp =_Py_Mangle(name, tmp);
+ if (!tmp)
+ goto bad_slots;
+ PyList_SET_ITEM(newslots, j, tmp);
+ j++;
+ }
+ assert(j == nslots - add_dict - add_weak);
+ nslots = j;
+ Py_DECREF(slots);
+ if (PyList_Sort(newslots) == -1) {
+ Py_DECREF(bases);
+ Py_DECREF(newslots);
+ return NULL;
+ }
+ slots = PyList_AsTuple(newslots);
+ Py_DECREF(newslots);
+ if (slots == NULL) {
+ Py_DECREF(bases);
+ return NULL;
+ }
+
+ /* Secondary bases may provide weakrefs or dict */
+ if (nbases > 1 &&
+ ((may_add_dict && !add_dict) ||
+ (may_add_weak && !add_weak))) {
+ for (i = 0; i < nbases; i++) {
+ tmp = PyTuple_GET_ITEM(bases, i);
+ if (tmp == (PyObject *)base)
+ continue; /* Skip primary base */
+ if (PyClass_Check(tmp)) {
+ /* Classic base class provides both */
+ if (may_add_dict && !add_dict)
+ add_dict++;
+ if (may_add_weak && !add_weak)
+ add_weak++;
+ break;
+ }
+ assert(PyType_Check(tmp));
+ tmptype = (PyTypeObject *)tmp;
+ if (may_add_dict && !add_dict &&
+ tmptype->tp_dictoffset != 0)
+ add_dict++;
+ if (may_add_weak && !add_weak &&
+ tmptype->tp_weaklistoffset != 0)
+ add_weak++;
+ if (may_add_dict && !add_dict)
+ continue;
+ if (may_add_weak && !add_weak)
+ continue;
+ /* Nothing more to check */
+ break;
+ }
+ }
+ }
+
+ /* XXX From here until type is safely allocated,
+ "return NULL" may leak slots! */
+
+ /* Allocate the type object */
+ type = (PyTypeObject *)metatype->tp_alloc(metatype, nslots);
+ if (type == NULL) {
+ Py_XDECREF(slots);
+ Py_DECREF(bases);
+ return NULL;
+ }
+
+ /* Keep name and slots alive in the extended type object */
+ et = (PyHeapTypeObject *)type;
+ Py_INCREF(name);
+ et->ht_name = name;
+ et->ht_slots = slots;
+
+ /* Initialize tp_flags */
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE |
+ Py_TPFLAGS_BASETYPE;
+ if (base->tp_flags & Py_TPFLAGS_HAVE_GC)
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
+ if (base->tp_flags & Py_TPFLAGS_HAVE_NEWBUFFER)
+ type->tp_flags |= Py_TPFLAGS_HAVE_NEWBUFFER;
+
+ /* It's a new-style number unless it specifically inherits any
+ old-style numeric behavior */
+ if ((base->tp_flags & Py_TPFLAGS_CHECKTYPES) ||
+ (base->tp_as_number == NULL))
+ type->tp_flags |= Py_TPFLAGS_CHECKTYPES;
+
+ /* Initialize essential fields */
+ type->tp_as_number = &et->as_number;
+ type->tp_as_sequence = &et->as_sequence;
+ type->tp_as_mapping = &et->as_mapping;
+ type->tp_as_buffer = &et->as_buffer;
+ type->tp_name = PyString_AS_STRING(name);
+
+ /* Set tp_base and tp_bases */
+ type->tp_bases = bases;
+ Py_INCREF(base);
+ type->tp_base = base;
+
+ /* Initialize tp_dict from passed-in dict */
+ type->tp_dict = dict = PyDict_Copy(dict);
+ if (dict == NULL) {
+ Py_DECREF(type);
+ return NULL;
+ }
+
+ /* Set __module__ in the dict */
+ if (PyDict_GetItemString(dict, "__module__") == NULL) {
+ tmp = PyEval_GetGlobals();
+ if (tmp != NULL) {
+ tmp = PyDict_GetItemString(tmp, "__name__");
+ if (tmp != NULL) {
+ if (PyDict_SetItemString(dict, "__module__",
+ tmp) < 0)
+ return NULL;
+ }
+ }
+ }
+
+ /* Set tp_doc to a copy of dict['__doc__'], if the latter is there
+ and is a string. The __doc__ accessor will first look for tp_doc;
+ if that fails, it will still look into __dict__.
+ */
+ {
+ PyObject *doc = PyDict_GetItemString(dict, "__doc__");
+ if (doc != NULL && PyString_Check(doc)) {
+ const size_t n = (size_t)PyString_GET_SIZE(doc);
+ char *tp_doc = (char *)PyObject_MALLOC(n+1);
+ if (tp_doc == NULL) {
+ Py_DECREF(type);
+ return NULL;
+ }
+ memcpy(tp_doc, PyString_AS_STRING(doc), n+1);
+ type->tp_doc = tp_doc;
+ }
+ }
+
+ /* Special-case __new__: if it's a plain function,
+ make it a static function */
+ tmp = PyDict_GetItemString(dict, "__new__");
+ if (tmp != NULL && PyFunction_Check(tmp)) {
+ tmp = PyStaticMethod_New(tmp);
+ if (tmp == NULL) {
+ Py_DECREF(type);
+ return NULL;
+ }
+ PyDict_SetItemString(dict, "__new__", tmp);
+ Py_DECREF(tmp);
+ }
+
+ /* Add descriptors for custom slots from __slots__, or for __dict__ */
+ mp = PyHeapType_GET_MEMBERS(et);
+ slotoffset = base->tp_basicsize;
+ if (slots != NULL) {
+ for (i = 0; i < nslots; i++, mp++) {
+ mp->name = PyString_AS_STRING(
+ PyTuple_GET_ITEM(slots, i));
+ mp->type = T_OBJECT_EX;
+ mp->offset = slotoffset;
+
+ /* __dict__ and __weakref__ are already filtered out */
+ assert(strcmp(mp->name, "__dict__") != 0);
+ assert(strcmp(mp->name, "__weakref__") != 0);
+
+ slotoffset += sizeof(PyObject *);
+ }
+ }
+ if (add_dict) {
+ if (base->tp_itemsize)
+ type->tp_dictoffset = -(long)sizeof(PyObject *);
+ else
+ type->tp_dictoffset = slotoffset;
+ slotoffset += sizeof(PyObject *);
+ }
+ if (add_weak) {
+ assert(!base->tp_itemsize);
+ type->tp_weaklistoffset = slotoffset;
+ slotoffset += sizeof(PyObject *);
+ }
+ type->tp_basicsize = slotoffset;
+ type->tp_itemsize = base->tp_itemsize;
+ type->tp_members = PyHeapType_GET_MEMBERS(et);
+
+ if (type->tp_weaklistoffset && type->tp_dictoffset)
+ type->tp_getset = subtype_getsets_full;
+ else if (type->tp_weaklistoffset && !type->tp_dictoffset)
+ type->tp_getset = subtype_getsets_weakref_only;
+ else if (!type->tp_weaklistoffset && type->tp_dictoffset)
+ type->tp_getset = subtype_getsets_dict_only;
+ else
+ type->tp_getset = NULL;
+
+ /* Special case some slots */
+ if (type->tp_dictoffset != 0 || nslots > 0) {
+ if (base->tp_getattr == NULL && base->tp_getattro == NULL)
+ type->tp_getattro = PyObject_GenericGetAttr;
+ if (base->tp_setattr == NULL && base->tp_setattro == NULL)
+ type->tp_setattro = PyObject_GenericSetAttr;
+ }
+ type->tp_dealloc = subtype_dealloc;
+
+ /* Enable GC unless there are really no instance variables possible */
+ if (!(type->tp_basicsize == sizeof(PyObject) &&
+ type->tp_itemsize == 0))
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
+
+ /* Always override allocation strategy to use regular heap */
+ type->tp_alloc = PyType_GenericAlloc;
+ if (type->tp_flags & Py_TPFLAGS_HAVE_GC) {
+ type->tp_free = PyObject_GC_Del;
+ type->tp_traverse = subtype_traverse;
+ type->tp_clear = subtype_clear;
+ }
+ else
+ type->tp_free = PyObject_Del;
+
+ /* Initialize the rest */
+ if (PyType_Ready(type) < 0) {
+ Py_DECREF(type);
+ return NULL;
+ }
+
+ /* Put the proper slots in place */
+ fixup_slot_dispatchers(type);
+
+ return (PyObject *)type;
}
/* Internal API to look for a name through the MRO.
@@ -2452,54 +2452,54 @@ type_new(PyTypeObject *metatype, PyObject *args, PyObject *kwds)
PyObject *
_PyType_Lookup(PyTypeObject *type, PyObject *name)
{
- Py_ssize_t i, n;
- PyObject *mro, *res, *base, *dict;
- unsigned int h;
-
- if (MCACHE_CACHEABLE_NAME(name) &&
- PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
- /* fast path */
- h = MCACHE_HASH_METHOD(type, name);
- if (method_cache[h].version == type->tp_version_tag &&
- method_cache[h].name == name)
- return method_cache[h].value;
- }
-
- /* Look in tp_dict of types in MRO */
- mro = type->tp_mro;
-
- /* If mro is NULL, the type is either not yet initialized
- by PyType_Ready(), or already cleared by type_clear().
- Either way the safest thing to do is to return NULL. */
- if (mro == NULL)
- return NULL;
-
- res = NULL;
- assert(PyTuple_Check(mro));
- n = PyTuple_GET_SIZE(mro);
- for (i = 0; i < n; i++) {
- base = PyTuple_GET_ITEM(mro, i);
- if (PyClass_Check(base))
- dict = ((PyClassObject *)base)->cl_dict;
- else {
- assert(PyType_Check(base));
- dict = ((PyTypeObject *)base)->tp_dict;
- }
- assert(dict && PyDict_Check(dict));
- res = PyDict_GetItem(dict, name);
- if (res != NULL)
- break;
- }
-
- if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
- h = MCACHE_HASH_METHOD(type, name);
- method_cache[h].version = type->tp_version_tag;
- method_cache[h].value = res; /* borrowed */
- Py_INCREF(name);
- Py_DECREF(method_cache[h].name);
- method_cache[h].name = name;
- }
- return res;
+ Py_ssize_t i, n;
+ PyObject *mro, *res, *base, *dict;
+ unsigned int h;
+
+ if (MCACHE_CACHEABLE_NAME(name) &&
+ PyType_HasFeature(type, Py_TPFLAGS_VALID_VERSION_TAG)) {
+ /* fast path */
+ h = MCACHE_HASH_METHOD(type, name);
+ if (method_cache[h].version == type->tp_version_tag &&
+ method_cache[h].name == name)
+ return method_cache[h].value;
+ }
+
+ /* Look in tp_dict of types in MRO */
+ mro = type->tp_mro;
+
+ /* If mro is NULL, the type is either not yet initialized
+ by PyType_Ready(), or already cleared by type_clear().
+ Either way the safest thing to do is to return NULL. */
+ if (mro == NULL)
+ return NULL;
+
+ res = NULL;
+ assert(PyTuple_Check(mro));
+ n = PyTuple_GET_SIZE(mro);
+ for (i = 0; i < n; i++) {
+ base = PyTuple_GET_ITEM(mro, i);
+ if (PyClass_Check(base))
+ dict = ((PyClassObject *)base)->cl_dict;
+ else {
+ assert(PyType_Check(base));
+ dict = ((PyTypeObject *)base)->tp_dict;
+ }
+ assert(dict && PyDict_Check(dict));
+ res = PyDict_GetItem(dict, name);
+ if (res != NULL)
+ break;
+ }
+
+ if (MCACHE_CACHEABLE_NAME(name) && assign_version_tag(type)) {
+ h = MCACHE_HASH_METHOD(type, name);
+ method_cache[h].version = type->tp_version_tag;
+ method_cache[h].value = res; /* borrowed */
+ Py_INCREF(name);
+ Py_DECREF(method_cache[h].name);
+ method_cache[h].name = name;
+ }
+ return res;
}
/* This is similar to PyObject_GenericGetAttr(),
@@ -2507,156 +2507,156 @@ _PyType_Lookup(PyTypeObject *type, PyObject *name)
static PyObject *
type_getattro(PyTypeObject *type, PyObject *name)
{
- PyTypeObject *metatype = Py_TYPE(type);
- PyObject *meta_attribute, *attribute;
- descrgetfunc meta_get;
-
- /* Initialize this type (we'll assume the metatype is initialized) */
- if (type->tp_dict == NULL) {
- if (PyType_Ready(type) < 0)
- return NULL;
- }
-
- /* No readable descriptor found yet */
- meta_get = NULL;
-
- /* Look for the attribute in the metatype */
- meta_attribute = _PyType_Lookup(metatype, name);
-
- if (meta_attribute != NULL) {
- meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
-
- if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
- /* Data descriptors implement tp_descr_set to intercept
- * writes. Assume the attribute is not overridden in
- * type's tp_dict (and bases): call the descriptor now.
- */
- return meta_get(meta_attribute, (PyObject *)type,
- (PyObject *)metatype);
- }
- Py_INCREF(meta_attribute);
- }
-
- /* No data descriptor found on metatype. Look in tp_dict of this
- * type and its bases */
- attribute = _PyType_Lookup(type, name);
- if (attribute != NULL) {
- /* Implement descriptor functionality, if any */
- descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
-
- Py_XDECREF(meta_attribute);
-
- if (local_get != NULL) {
- /* NULL 2nd argument indicates the descriptor was
- * found on the target object itself (or a base) */
- return local_get(attribute, (PyObject *)NULL,
- (PyObject *)type);
- }
-
- Py_INCREF(attribute);
- return attribute;
- }
-
- /* No attribute found in local __dict__ (or bases): use the
- * descriptor from the metatype, if any */
- if (meta_get != NULL) {
- PyObject *res;
- res = meta_get(meta_attribute, (PyObject *)type,
- (PyObject *)metatype);
- Py_DECREF(meta_attribute);
- return res;
- }
-
- /* If an ordinary attribute was found on the metatype, return it now */
- if (meta_attribute != NULL) {
- return meta_attribute;
- }
-
- /* Give up */
- PyErr_Format(PyExc_AttributeError,
- "type object '%.50s' has no attribute '%.400s'",
- type->tp_name, PyString_AS_STRING(name));
- return NULL;
+ PyTypeObject *metatype = Py_TYPE(type);
+ PyObject *meta_attribute, *attribute;
+ descrgetfunc meta_get;
+
+ /* Initialize this type (we'll assume the metatype is initialized) */
+ if (type->tp_dict == NULL) {
+ if (PyType_Ready(type) < 0)
+ return NULL;
+ }
+
+ /* No readable descriptor found yet */
+ meta_get = NULL;
+
+ /* Look for the attribute in the metatype */
+ meta_attribute = _PyType_Lookup(metatype, name);
+
+ if (meta_attribute != NULL) {
+ meta_get = Py_TYPE(meta_attribute)->tp_descr_get;
+
+ if (meta_get != NULL && PyDescr_IsData(meta_attribute)) {
+ /* Data descriptors implement tp_descr_set to intercept
+ * writes. Assume the attribute is not overridden in
+ * type's tp_dict (and bases): call the descriptor now.
+ */
+ return meta_get(meta_attribute, (PyObject *)type,
+ (PyObject *)metatype);
+ }
+ Py_INCREF(meta_attribute);
+ }
+
+ /* No data descriptor found on metatype. Look in tp_dict of this
+ * type and its bases */
+ attribute = _PyType_Lookup(type, name);
+ if (attribute != NULL) {
+ /* Implement descriptor functionality, if any */
+ descrgetfunc local_get = Py_TYPE(attribute)->tp_descr_get;
+
+ Py_XDECREF(meta_attribute);
+
+ if (local_get != NULL) {
+ /* NULL 2nd argument indicates the descriptor was
+ * found on the target object itself (or a base) */
+ return local_get(attribute, (PyObject *)NULL,
+ (PyObject *)type);
+ }
+
+ Py_INCREF(attribute);
+ return attribute;
+ }
+
+ /* No attribute found in local __dict__ (or bases): use the
+ * descriptor from the metatype, if any */
+ if (meta_get != NULL) {
+ PyObject *res;
+ res = meta_get(meta_attribute, (PyObject *)type,
+ (PyObject *)metatype);
+ Py_DECREF(meta_attribute);
+ return res;
+ }
+
+ /* If an ordinary attribute was found on the metatype, return it now */
+ if (meta_attribute != NULL) {
+ return meta_attribute;
+ }
+
+ /* Give up */
+ PyErr_Format(PyExc_AttributeError,
+ "type object '%.50s' has no attribute '%.400s'",
+ type->tp_name, PyString_AS_STRING(name));
+ return NULL;
}
static int
type_setattro(PyTypeObject *type, PyObject *name, PyObject *value)
{
- if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
- PyErr_Format(
- PyExc_TypeError,
- "can't set attributes of built-in/extension type '%s'",
- type->tp_name);
- return -1;
- }
- if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
- return -1;
- return update_slot(type, name);
+ if (!(type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "can't set attributes of built-in/extension type '%s'",
+ type->tp_name);
+ return -1;
+ }
+ if (PyObject_GenericSetAttr((PyObject *)type, name, value) < 0)
+ return -1;
+ return update_slot(type, name);
}
static void
type_dealloc(PyTypeObject *type)
{
- PyHeapTypeObject *et;
-
- /* Assert this is a heap-allocated type object */
- assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
- _PyObject_GC_UNTRACK(type);
- PyObject_ClearWeakRefs((PyObject *)type);
- et = (PyHeapTypeObject *)type;
- Py_XDECREF(type->tp_base);
- Py_XDECREF(type->tp_dict);
- Py_XDECREF(type->tp_bases);
- Py_XDECREF(type->tp_mro);
- Py_XDECREF(type->tp_cache);
- Py_XDECREF(type->tp_subclasses);
- /* A type's tp_doc is heap allocated, unlike the tp_doc slots
- * of most other objects. It's okay to cast it to char *.
- */
- PyObject_Free((char *)type->tp_doc);
- Py_XDECREF(et->ht_name);
- Py_XDECREF(et->ht_slots);
- Py_TYPE(type)->tp_free((PyObject *)type);
+ PyHeapTypeObject *et;
+
+ /* Assert this is a heap-allocated type object */
+ assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
+ _PyObject_GC_UNTRACK(type);
+ PyObject_ClearWeakRefs((PyObject *)type);
+ et = (PyHeapTypeObject *)type;
+ Py_XDECREF(type->tp_base);
+ Py_XDECREF(type->tp_dict);
+ Py_XDECREF(type->tp_bases);
+ Py_XDECREF(type->tp_mro);
+ Py_XDECREF(type->tp_cache);
+ Py_XDECREF(type->tp_subclasses);
+ /* A type's tp_doc is heap allocated, unlike the tp_doc slots
+ * of most other objects. It's okay to cast it to char *.
+ */
+ PyObject_Free((char *)type->tp_doc);
+ Py_XDECREF(et->ht_name);
+ Py_XDECREF(et->ht_slots);
+ Py_TYPE(type)->tp_free((PyObject *)type);
}
static PyObject *
type_subclasses(PyTypeObject *type, PyObject *args_ignored)
{
- PyObject *list, *raw, *ref;
- Py_ssize_t i, n;
-
- list = PyList_New(0);
- if (list == NULL)
- return NULL;
- raw = type->tp_subclasses;
- if (raw == NULL)
- return list;
- assert(PyList_Check(raw));
- n = PyList_GET_SIZE(raw);
- for (i = 0; i < n; i++) {
- ref = PyList_GET_ITEM(raw, i);
- assert(PyWeakref_CheckRef(ref));
- ref = PyWeakref_GET_OBJECT(ref);
- if (ref != Py_None) {
- if (PyList_Append(list, ref) < 0) {
- Py_DECREF(list);
- return NULL;
- }
- }
- }
- return list;
+ PyObject *list, *raw, *ref;
+ Py_ssize_t i, n;
+
+ list = PyList_New(0);
+ if (list == NULL)
+ return NULL;
+ raw = type->tp_subclasses;
+ if (raw == NULL)
+ return list;
+ assert(PyList_Check(raw));
+ n = PyList_GET_SIZE(raw);
+ for (i = 0; i < n; i++) {
+ ref = PyList_GET_ITEM(raw, i);
+ assert(PyWeakref_CheckRef(ref));
+ ref = PyWeakref_GET_OBJECT(ref);
+ if (ref != Py_None) {
+ if (PyList_Append(list, ref) < 0) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ }
+ }
+ return list;
}
static PyMethodDef type_methods[] = {
- {"mro", (PyCFunction)mro_external, METH_NOARGS,
- PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
- {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
- PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
- {"__instancecheck__", type___instancecheck__, METH_O,
- PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
- {"__subclasscheck__", type___subclasscheck__, METH_O,
- PyDoc_STR("__subclasschck__ -> check if an class is a subclass")},
- {0}
+ {"mro", (PyCFunction)mro_external, METH_NOARGS,
+ PyDoc_STR("mro() -> list\nreturn a type's method resolution order")},
+ {"__subclasses__", (PyCFunction)type_subclasses, METH_NOARGS,
+ PyDoc_STR("__subclasses__() -> list of immediate subclasses")},
+ {"__instancecheck__", type___instancecheck__, METH_O,
+ PyDoc_STR("__instancecheck__() -> check if an object is an instance")},
+ {"__subclasscheck__", type___subclasscheck__, METH_O,
+ PyDoc_STR("__subclasschck__ -> check if an class is a subclass")},
+ {0}
};
PyDoc_STRVAR(type_doc,
@@ -2666,109 +2666,109 @@ PyDoc_STRVAR(type_doc,
static int
type_traverse(PyTypeObject *type, visitproc visit, void *arg)
{
- /* Because of type_is_gc(), the collector only calls this
- for heaptypes. */
- assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
+ /* Because of type_is_gc(), the collector only calls this
+ for heaptypes. */
+ assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
- Py_VISIT(type->tp_dict);
- Py_VISIT(type->tp_cache);
- Py_VISIT(type->tp_mro);
- Py_VISIT(type->tp_bases);
- Py_VISIT(type->tp_base);
+ Py_VISIT(type->tp_dict);
+ Py_VISIT(type->tp_cache);
+ Py_VISIT(type->tp_mro);
+ Py_VISIT(type->tp_bases);
+ Py_VISIT(type->tp_base);
- /* There's no need to visit type->tp_subclasses or
- ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
- in cycles; tp_subclasses is a list of weak references,
- and slots is a tuple of strings. */
+ /* There's no need to visit type->tp_subclasses or
+ ((PyHeapTypeObject *)type)->ht_slots, because they can't be involved
+ in cycles; tp_subclasses is a list of weak references,
+ and slots is a tuple of strings. */
- return 0;
+ return 0;
}
static int
type_clear(PyTypeObject *type)
{
- /* Because of type_is_gc(), the collector only calls this
- for heaptypes. */
- assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
+ /* Because of type_is_gc(), the collector only calls this
+ for heaptypes. */
+ assert(type->tp_flags & Py_TPFLAGS_HEAPTYPE);
- /* The only field we need to clear is tp_mro, which is part of a
- hard cycle (its first element is the class itself) that won't
- be broken otherwise (it's a tuple and tuples don't have a
- tp_clear handler). None of the other fields need to be
- cleared, and here's why:
+ /* The only field we need to clear is tp_mro, which is part of a
+ hard cycle (its first element is the class itself) that won't
+ be broken otherwise (it's a tuple and tuples don't have a
+ tp_clear handler). None of the other fields need to be
+ cleared, and here's why:
- tp_dict:
- It is a dict, so the collector will call its tp_clear.
+ tp_dict:
+ It is a dict, so the collector will call its tp_clear.
- tp_cache:
- Not used; if it were, it would be a dict.
+ tp_cache:
+ Not used; if it were, it would be a dict.
- tp_bases, tp_base:
- If these are involved in a cycle, there must be at least
- one other, mutable object in the cycle, e.g. a base
- class's dict; the cycle will be broken that way.
+ tp_bases, tp_base:
+ If these are involved in a cycle, there must be at least
+ one other, mutable object in the cycle, e.g. a base
+ class's dict; the cycle will be broken that way.
- tp_subclasses:
- A list of weak references can't be part of a cycle; and
- lists have their own tp_clear.
+ tp_subclasses:
+ A list of weak references can't be part of a cycle; and
+ lists have their own tp_clear.
- slots (in PyHeapTypeObject):
- A tuple of strings can't be part of a cycle.
- */
+ slots (in PyHeapTypeObject):
+ A tuple of strings can't be part of a cycle.
+ */
- Py_CLEAR(type->tp_mro);
+ Py_CLEAR(type->tp_mro);
- return 0;
+ return 0;
}
static int
type_is_gc(PyTypeObject *type)
{
- return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
+ return type->tp_flags & Py_TPFLAGS_HEAPTYPE;
}
PyTypeObject PyType_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "type", /* tp_name */
- sizeof(PyHeapTypeObject), /* tp_basicsize */
- sizeof(PyMemberDef), /* tp_itemsize */
- (destructor)type_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)type_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)_Py_HashPointer, /* tp_hash */
- (ternaryfunc)type_call, /* tp_call */
- 0, /* tp_str */
- (getattrofunc)type_getattro, /* tp_getattro */
- (setattrofunc)type_setattro, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
- type_doc, /* tp_doc */
- (traverseproc)type_traverse, /* tp_traverse */
- (inquiry)type_clear, /* tp_clear */
- type_richcompare, /* tp_richcompare */
- offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- type_methods, /* tp_methods */
- type_members, /* tp_members */
- type_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
- type_init, /* tp_init */
- 0, /* tp_alloc */
- type_new, /* tp_new */
- PyObject_GC_Del, /* tp_free */
- (inquiry)type_is_gc, /* tp_is_gc */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "type", /* tp_name */
+ sizeof(PyHeapTypeObject), /* tp_basicsize */
+ sizeof(PyMemberDef), /* tp_itemsize */
+ (destructor)type_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)type_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)_Py_HashPointer, /* tp_hash */
+ (ternaryfunc)type_call, /* tp_call */
+ 0, /* tp_str */
+ (getattrofunc)type_getattro, /* tp_getattro */
+ (setattrofunc)type_setattro, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE | Py_TPFLAGS_TYPE_SUBCLASS, /* tp_flags */
+ type_doc, /* tp_doc */
+ (traverseproc)type_traverse, /* tp_traverse */
+ (inquiry)type_clear, /* tp_clear */
+ type_richcompare, /* tp_richcompare */
+ offsetof(PyTypeObject, tp_weaklist), /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ type_methods, /* tp_methods */
+ type_members, /* tp_members */
+ type_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ offsetof(PyTypeObject, tp_dict), /* tp_dictoffset */
+ type_init, /* tp_init */
+ 0, /* tp_alloc */
+ type_new, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
+ (inquiry)type_is_gc, /* tp_is_gc */
};
@@ -2821,282 +2821,282 @@ object_new(PyTypeObject *type, PyObject *args, PyObject *kwds);
static int
excess_args(PyObject *args, PyObject *kwds)
{
- return PyTuple_GET_SIZE(args) ||
- (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
+ return PyTuple_GET_SIZE(args) ||
+ (kwds && PyDict_Check(kwds) && PyDict_Size(kwds));
}
static int
object_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- int err = 0;
- if (excess_args(args, kwds)) {
- PyTypeObject *type = Py_TYPE(self);
- if (type->tp_init != object_init &&
- type->tp_new != object_new)
- {
- err = PyErr_WarnEx(PyExc_DeprecationWarning,
- "object.__init__() takes no parameters",
- 1);
- }
- else if (type->tp_init != object_init ||
- type->tp_new == object_new)
- {
- PyErr_SetString(PyExc_TypeError,
- "object.__init__() takes no parameters");
- err = -1;
- }
- }
- return err;
+ int err = 0;
+ if (excess_args(args, kwds)) {
+ PyTypeObject *type = Py_TYPE(self);
+ if (type->tp_init != object_init &&
+ type->tp_new != object_new)
+ {
+ err = PyErr_WarnEx(PyExc_DeprecationWarning,
+ "object.__init__() takes no parameters",
+ 1);
+ }
+ else if (type->tp_init != object_init ||
+ type->tp_new == object_new)
+ {
+ PyErr_SetString(PyExc_TypeError,
+ "object.__init__() takes no parameters");
+ err = -1;
+ }
+ }
+ return err;
}
static PyObject *
object_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- int err = 0;
- if (excess_args(args, kwds)) {
- if (type->tp_new != object_new &&
- type->tp_init != object_init)
- {
- err = PyErr_WarnEx(PyExc_DeprecationWarning,
- "object.__new__() takes no parameters",
- 1);
- }
- else if (type->tp_new != object_new ||
- type->tp_init == object_init)
- {
- PyErr_SetString(PyExc_TypeError,
- "object.__new__() takes no parameters");
- err = -1;
- }
- }
- if (err < 0)
- return NULL;
-
- if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
- static PyObject *comma = NULL;
- PyObject *abstract_methods = NULL;
- PyObject *builtins;
- PyObject *sorted;
- PyObject *sorted_methods = NULL;
- PyObject *joined = NULL;
- const char *joined_str;
-
- /* Compute ", ".join(sorted(type.__abstractmethods__))
- into joined. */
- abstract_methods = type_abstractmethods(type, NULL);
- if (abstract_methods == NULL)
- goto error;
- builtins = PyEval_GetBuiltins();
- if (builtins == NULL)
- goto error;
- sorted = PyDict_GetItemString(builtins, "sorted");
- if (sorted == NULL)
- goto error;
- sorted_methods = PyObject_CallFunctionObjArgs(sorted,
- abstract_methods,
- NULL);
- if (sorted_methods == NULL)
- goto error;
- if (comma == NULL) {
- comma = PyString_InternFromString(", ");
- if (comma == NULL)
- goto error;
- }
- joined = PyObject_CallMethod(comma, "join",
- "O", sorted_methods);
- if (joined == NULL)
- goto error;
- joined_str = PyString_AsString(joined);
- if (joined_str == NULL)
- goto error;
-
- PyErr_Format(PyExc_TypeError,
- "Can't instantiate abstract class %s "
- "with abstract methods %s",
- type->tp_name,
- joined_str);
- error:
- Py_XDECREF(joined);
- Py_XDECREF(sorted_methods);
- Py_XDECREF(abstract_methods);
- return NULL;
- }
- return type->tp_alloc(type, 0);
+ int err = 0;
+ if (excess_args(args, kwds)) {
+ if (type->tp_new != object_new &&
+ type->tp_init != object_init)
+ {
+ err = PyErr_WarnEx(PyExc_DeprecationWarning,
+ "object.__new__() takes no parameters",
+ 1);
+ }
+ else if (type->tp_new != object_new ||
+ type->tp_init == object_init)
+ {
+ PyErr_SetString(PyExc_TypeError,
+ "object.__new__() takes no parameters");
+ err = -1;
+ }
+ }
+ if (err < 0)
+ return NULL;
+
+ if (type->tp_flags & Py_TPFLAGS_IS_ABSTRACT) {
+ static PyObject *comma = NULL;
+ PyObject *abstract_methods = NULL;
+ PyObject *builtins;
+ PyObject *sorted;
+ PyObject *sorted_methods = NULL;
+ PyObject *joined = NULL;
+ const char *joined_str;
+
+ /* Compute ", ".join(sorted(type.__abstractmethods__))
+ into joined. */
+ abstract_methods = type_abstractmethods(type, NULL);
+ if (abstract_methods == NULL)
+ goto error;
+ builtins = PyEval_GetBuiltins();
+ if (builtins == NULL)
+ goto error;
+ sorted = PyDict_GetItemString(builtins, "sorted");
+ if (sorted == NULL)
+ goto error;
+ sorted_methods = PyObject_CallFunctionObjArgs(sorted,
+ abstract_methods,
+ NULL);
+ if (sorted_methods == NULL)
+ goto error;
+ if (comma == NULL) {
+ comma = PyString_InternFromString(", ");
+ if (comma == NULL)
+ goto error;
+ }
+ joined = PyObject_CallMethod(comma, "join",
+ "O", sorted_methods);
+ if (joined == NULL)
+ goto error;
+ joined_str = PyString_AsString(joined);
+ if (joined_str == NULL)
+ goto error;
+
+ PyErr_Format(PyExc_TypeError,
+ "Can't instantiate abstract class %s "
+ "with abstract methods %s",
+ type->tp_name,
+ joined_str);
+ error:
+ Py_XDECREF(joined);
+ Py_XDECREF(sorted_methods);
+ Py_XDECREF(abstract_methods);
+ return NULL;
+ }
+ return type->tp_alloc(type, 0);
}
static void
object_dealloc(PyObject *self)
{
- Py_TYPE(self)->tp_free(self);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject *
object_repr(PyObject *self)
{
- PyTypeObject *type;
- PyObject *mod, *name, *rtn;
-
- type = Py_TYPE(self);
- mod = type_module(type, NULL);
- if (mod == NULL)
- PyErr_Clear();
- else if (!PyString_Check(mod)) {
- Py_DECREF(mod);
- mod = NULL;
- }
- name = type_name(type, NULL);
- if (name == NULL)
- return NULL;
- if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
- rtn = PyString_FromFormat("<%s.%s object at %p>",
- PyString_AS_STRING(mod),
- PyString_AS_STRING(name),
- self);
- else
- rtn = PyString_FromFormat("<%s object at %p>",
- type->tp_name, self);
- Py_XDECREF(mod);
- Py_DECREF(name);
- return rtn;
+ PyTypeObject *type;
+ PyObject *mod, *name, *rtn;
+
+ type = Py_TYPE(self);
+ mod = type_module(type, NULL);
+ if (mod == NULL)
+ PyErr_Clear();
+ else if (!PyString_Check(mod)) {
+ Py_DECREF(mod);
+ mod = NULL;
+ }
+ name = type_name(type, NULL);
+ if (name == NULL)
+ return NULL;
+ if (mod != NULL && strcmp(PyString_AS_STRING(mod), "__builtin__"))
+ rtn = PyString_FromFormat("<%s.%s object at %p>",
+ PyString_AS_STRING(mod),
+ PyString_AS_STRING(name),
+ self);
+ else
+ rtn = PyString_FromFormat("<%s object at %p>",
+ type->tp_name, self);
+ Py_XDECREF(mod);
+ Py_DECREF(name);
+ return rtn;
}
static PyObject *
object_str(PyObject *self)
{
- unaryfunc f;
+ unaryfunc f;
- f = Py_TYPE(self)->tp_repr;
- if (f == NULL)
- f = object_repr;
- return f(self);
+ f = Py_TYPE(self)->tp_repr;
+ if (f == NULL)
+ f = object_repr;
+ return f(self);
}
static PyObject *
object_get_class(PyObject *self, void *closure)
{
- Py_INCREF(Py_TYPE(self));
- return (PyObject *)(Py_TYPE(self));
+ Py_INCREF(Py_TYPE(self));
+ return (PyObject *)(Py_TYPE(self));
}
static int
equiv_structs(PyTypeObject *a, PyTypeObject *b)
{
- return a == b ||
- (a != NULL &&
- b != NULL &&
- a->tp_basicsize == b->tp_basicsize &&
- a->tp_itemsize == b->tp_itemsize &&
- a->tp_dictoffset == b->tp_dictoffset &&
- a->tp_weaklistoffset == b->tp_weaklistoffset &&
- ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
- (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
+ return a == b ||
+ (a != NULL &&
+ b != NULL &&
+ a->tp_basicsize == b->tp_basicsize &&
+ a->tp_itemsize == b->tp_itemsize &&
+ a->tp_dictoffset == b->tp_dictoffset &&
+ a->tp_weaklistoffset == b->tp_weaklistoffset &&
+ ((a->tp_flags & Py_TPFLAGS_HAVE_GC) ==
+ (b->tp_flags & Py_TPFLAGS_HAVE_GC)));
}
static int
same_slots_added(PyTypeObject *a, PyTypeObject *b)
{
- PyTypeObject *base = a->tp_base;
- Py_ssize_t size;
- PyObject *slots_a, *slots_b;
-
- if (base != b->tp_base)
- return 0;
- if (equiv_structs(a, base) && equiv_structs(b, base))
- return 1;
- size = base->tp_basicsize;
- if (a->tp_dictoffset == size && b->tp_dictoffset == size)
- size += sizeof(PyObject *);
- if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
- size += sizeof(PyObject *);
-
- /* Check slots compliance */
- slots_a = ((PyHeapTypeObject *)a)->ht_slots;
- slots_b = ((PyHeapTypeObject *)b)->ht_slots;
- if (slots_a && slots_b) {
- if (PyObject_Compare(slots_a, slots_b) != 0)
- return 0;
- size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
- }
- return size == a->tp_basicsize && size == b->tp_basicsize;
+ PyTypeObject *base = a->tp_base;
+ Py_ssize_t size;
+ PyObject *slots_a, *slots_b;
+
+ if (base != b->tp_base)
+ return 0;
+ if (equiv_structs(a, base) && equiv_structs(b, base))
+ return 1;
+ size = base->tp_basicsize;
+ if (a->tp_dictoffset == size && b->tp_dictoffset == size)
+ size += sizeof(PyObject *);
+ if (a->tp_weaklistoffset == size && b->tp_weaklistoffset == size)
+ size += sizeof(PyObject *);
+
+ /* Check slots compliance */
+ slots_a = ((PyHeapTypeObject *)a)->ht_slots;
+ slots_b = ((PyHeapTypeObject *)b)->ht_slots;
+ if (slots_a && slots_b) {
+ if (PyObject_Compare(slots_a, slots_b) != 0)
+ return 0;
+ size += sizeof(PyObject *) * PyTuple_GET_SIZE(slots_a);
+ }
+ return size == a->tp_basicsize && size == b->tp_basicsize;
}
static int
compatible_for_assignment(PyTypeObject* oldto, PyTypeObject* newto, char* attr)
{
- PyTypeObject *newbase, *oldbase;
-
- if (newto->tp_dealloc != oldto->tp_dealloc ||
- newto->tp_free != oldto->tp_free)
- {
- PyErr_Format(PyExc_TypeError,
- "%s assignment: "
- "'%s' deallocator differs from '%s'",
- attr,
- newto->tp_name,
- oldto->tp_name);
- return 0;
- }
- newbase = newto;
- oldbase = oldto;
- while (equiv_structs(newbase, newbase->tp_base))
- newbase = newbase->tp_base;
- while (equiv_structs(oldbase, oldbase->tp_base))
- oldbase = oldbase->tp_base;
- if (newbase != oldbase &&
- (newbase->tp_base != oldbase->tp_base ||
- !same_slots_added(newbase, oldbase))) {
- PyErr_Format(PyExc_TypeError,
- "%s assignment: "
- "'%s' object layout differs from '%s'",
- attr,
- newto->tp_name,
- oldto->tp_name);
- return 0;
- }
-
- return 1;
+ PyTypeObject *newbase, *oldbase;
+
+ if (newto->tp_dealloc != oldto->tp_dealloc ||
+ newto->tp_free != oldto->tp_free)
+ {
+ PyErr_Format(PyExc_TypeError,
+ "%s assignment: "
+ "'%s' deallocator differs from '%s'",
+ attr,
+ newto->tp_name,
+ oldto->tp_name);
+ return 0;
+ }
+ newbase = newto;
+ oldbase = oldto;
+ while (equiv_structs(newbase, newbase->tp_base))
+ newbase = newbase->tp_base;
+ while (equiv_structs(oldbase, oldbase->tp_base))
+ oldbase = oldbase->tp_base;
+ if (newbase != oldbase &&
+ (newbase->tp_base != oldbase->tp_base ||
+ !same_slots_added(newbase, oldbase))) {
+ PyErr_Format(PyExc_TypeError,
+ "%s assignment: "
+ "'%s' object layout differs from '%s'",
+ attr,
+ newto->tp_name,
+ oldto->tp_name);
+ return 0;
+ }
+
+ return 1;
}
static int
object_set_class(PyObject *self, PyObject *value, void *closure)
{
- PyTypeObject *oldto = Py_TYPE(self);
- PyTypeObject *newto;
-
- if (value == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete __class__ attribute");
- return -1;
- }
- if (!PyType_Check(value)) {
- PyErr_Format(PyExc_TypeError,
- "__class__ must be set to new-style class, not '%s' object",
- Py_TYPE(value)->tp_name);
- return -1;
- }
- newto = (PyTypeObject *)value;
- if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
- !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
- {
- PyErr_Format(PyExc_TypeError,
- "__class__ assignment: only for heap types");
- return -1;
- }
- if (compatible_for_assignment(newto, oldto, "__class__")) {
- Py_INCREF(newto);
- Py_TYPE(self) = newto;
- Py_DECREF(oldto);
- return 0;
- }
- else {
- return -1;
- }
+ PyTypeObject *oldto = Py_TYPE(self);
+ PyTypeObject *newto;
+
+ if (value == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete __class__ attribute");
+ return -1;
+ }
+ if (!PyType_Check(value)) {
+ PyErr_Format(PyExc_TypeError,
+ "__class__ must be set to new-style class, not '%s' object",
+ Py_TYPE(value)->tp_name);
+ return -1;
+ }
+ newto = (PyTypeObject *)value;
+ if (!(newto->tp_flags & Py_TPFLAGS_HEAPTYPE) ||
+ !(oldto->tp_flags & Py_TPFLAGS_HEAPTYPE))
+ {
+ PyErr_Format(PyExc_TypeError,
+ "__class__ assignment: only for heap types");
+ return -1;
+ }
+ if (compatible_for_assignment(newto, oldto, "__class__")) {
+ Py_INCREF(newto);
+ Py_TYPE(self) = newto;
+ Py_DECREF(oldto);
+ return 0;
+ }
+ else {
+ return -1;
+ }
}
static PyGetSetDef object_getsets[] = {
- {"__class__", object_get_class, object_set_class,
- PyDoc_STR("the object's class")},
- {0}
+ {"__class__", object_get_class, object_set_class,
+ PyDoc_STR("the object's class")},
+ {0}
};
@@ -3110,190 +3110,190 @@ static PyGetSetDef object_getsets[] = {
static PyObject *
import_copyreg(void)
{
- static PyObject *copyreg_str;
+ static PyObject *copyreg_str;
- if (!copyreg_str) {
- copyreg_str = PyString_InternFromString("copy_reg");
- if (copyreg_str == NULL)
- return NULL;
- }
+ if (!copyreg_str) {
+ copyreg_str = PyString_InternFromString("copy_reg");
+ if (copyreg_str == NULL)
+ return NULL;
+ }
- return PyImport_Import(copyreg_str);
+ return PyImport_Import(copyreg_str);
}
static PyObject *
slotnames(PyObject *cls)
{
- PyObject *clsdict;
- PyObject *copyreg;
- PyObject *slotnames;
-
- if (!PyType_Check(cls)) {
- Py_INCREF(Py_None);
- return Py_None;
- }
-
- clsdict = ((PyTypeObject *)cls)->tp_dict;
- slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
- if (slotnames != NULL && PyList_Check(slotnames)) {
- Py_INCREF(slotnames);
- return slotnames;
- }
-
- copyreg = import_copyreg();
- if (copyreg == NULL)
- return NULL;
-
- slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
- Py_DECREF(copyreg);
- if (slotnames != NULL &&
- slotnames != Py_None &&
- !PyList_Check(slotnames))
- {
- PyErr_SetString(PyExc_TypeError,
- "copy_reg._slotnames didn't return a list or None");
- Py_DECREF(slotnames);
- slotnames = NULL;
- }
-
- return slotnames;
+ PyObject *clsdict;
+ PyObject *copyreg;
+ PyObject *slotnames;
+
+ if (!PyType_Check(cls)) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+
+ clsdict = ((PyTypeObject *)cls)->tp_dict;
+ slotnames = PyDict_GetItemString(clsdict, "__slotnames__");
+ if (slotnames != NULL && PyList_Check(slotnames)) {
+ Py_INCREF(slotnames);
+ return slotnames;
+ }
+
+ copyreg = import_copyreg();
+ if (copyreg == NULL)
+ return NULL;
+
+ slotnames = PyObject_CallMethod(copyreg, "_slotnames", "O", cls);
+ Py_DECREF(copyreg);
+ if (slotnames != NULL &&
+ slotnames != Py_None &&
+ !PyList_Check(slotnames))
+ {
+ PyErr_SetString(PyExc_TypeError,
+ "copy_reg._slotnames didn't return a list or None");
+ Py_DECREF(slotnames);
+ slotnames = NULL;
+ }
+
+ return slotnames;
}
static PyObject *
reduce_2(PyObject *obj)
{
- PyObject *cls, *getnewargs;
- PyObject *args = NULL, *args2 = NULL;
- PyObject *getstate = NULL, *state = NULL, *names = NULL;
- PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
- PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
- Py_ssize_t i, n;
-
- cls = PyObject_GetAttrString(obj, "__class__");
- if (cls == NULL)
- return NULL;
-
- getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
- if (getnewargs != NULL) {
- args = PyObject_CallObject(getnewargs, NULL);
- Py_DECREF(getnewargs);
- if (args != NULL && !PyTuple_Check(args)) {
- PyErr_Format(PyExc_TypeError,
- "__getnewargs__ should return a tuple, "
- "not '%.200s'", Py_TYPE(args)->tp_name);
- goto end;
- }
- }
- else {
- PyErr_Clear();
- args = PyTuple_New(0);
- }
- if (args == NULL)
- goto end;
-
- getstate = PyObject_GetAttrString(obj, "__getstate__");
- if (getstate != NULL) {
- state = PyObject_CallObject(getstate, NULL);
- Py_DECREF(getstate);
- if (state == NULL)
- goto end;
- }
- else {
- PyErr_Clear();
- state = PyObject_GetAttrString(obj, "__dict__");
- if (state == NULL) {
- PyErr_Clear();
- state = Py_None;
- Py_INCREF(state);
- }
- names = slotnames(cls);
- if (names == NULL)
- goto end;
- if (names != Py_None) {
- assert(PyList_Check(names));
- slots = PyDict_New();
- if (slots == NULL)
- goto end;
- n = 0;
- /* Can't pre-compute the list size; the list
- is stored on the class so accessible to other
- threads, which may be run by DECREF */
- for (i = 0; i < PyList_GET_SIZE(names); i++) {
- PyObject *name, *value;
- name = PyList_GET_ITEM(names, i);
- value = PyObject_GetAttr(obj, name);
- if (value == NULL)
- PyErr_Clear();
- else {
- int err = PyDict_SetItem(slots, name,
- value);
- Py_DECREF(value);
- if (err)
- goto end;
- n++;
- }
- }
- if (n) {
- state = Py_BuildValue("(NO)", state, slots);
- if (state == NULL)
- goto end;
- }
- }
- }
-
- if (!PyList_Check(obj)) {
- listitems = Py_None;
- Py_INCREF(listitems);
- }
- else {
- listitems = PyObject_GetIter(obj);
- if (listitems == NULL)
- goto end;
- }
-
- if (!PyDict_Check(obj)) {
- dictitems = Py_None;
- Py_INCREF(dictitems);
- }
- else {
- dictitems = PyObject_CallMethod(obj, "iteritems", "");
- if (dictitems == NULL)
- goto end;
- }
-
- copyreg = import_copyreg();
- if (copyreg == NULL)
- goto end;
- newobj = PyObject_GetAttrString(copyreg, "__newobj__");
- if (newobj == NULL)
- goto end;
-
- n = PyTuple_GET_SIZE(args);
- args2 = PyTuple_New(n+1);
- if (args2 == NULL)
- goto end;
- PyTuple_SET_ITEM(args2, 0, cls);
- cls = NULL;
- for (i = 0; i < n; i++) {
- PyObject *v = PyTuple_GET_ITEM(args, i);
- Py_INCREF(v);
- PyTuple_SET_ITEM(args2, i+1, v);
- }
-
- res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
+ PyObject *cls, *getnewargs;
+ PyObject *args = NULL, *args2 = NULL;
+ PyObject *getstate = NULL, *state = NULL, *names = NULL;
+ PyObject *slots = NULL, *listitems = NULL, *dictitems = NULL;
+ PyObject *copyreg = NULL, *newobj = NULL, *res = NULL;
+ Py_ssize_t i, n;
+
+ cls = PyObject_GetAttrString(obj, "__class__");
+ if (cls == NULL)
+ return NULL;
+
+ getnewargs = PyObject_GetAttrString(obj, "__getnewargs__");
+ if (getnewargs != NULL) {
+ args = PyObject_CallObject(getnewargs, NULL);
+ Py_DECREF(getnewargs);
+ if (args != NULL && !PyTuple_Check(args)) {
+ PyErr_Format(PyExc_TypeError,
+ "__getnewargs__ should return a tuple, "
+ "not '%.200s'", Py_TYPE(args)->tp_name);
+ goto end;
+ }
+ }
+ else {
+ PyErr_Clear();
+ args = PyTuple_New(0);
+ }
+ if (args == NULL)
+ goto end;
+
+ getstate = PyObject_GetAttrString(obj, "__getstate__");
+ if (getstate != NULL) {
+ state = PyObject_CallObject(getstate, NULL);
+ Py_DECREF(getstate);
+ if (state == NULL)
+ goto end;
+ }
+ else {
+ PyErr_Clear();
+ state = PyObject_GetAttrString(obj, "__dict__");
+ if (state == NULL) {
+ PyErr_Clear();
+ state = Py_None;
+ Py_INCREF(state);
+ }
+ names = slotnames(cls);
+ if (names == NULL)
+ goto end;
+ if (names != Py_None) {
+ assert(PyList_Check(names));
+ slots = PyDict_New();
+ if (slots == NULL)
+ goto end;
+ n = 0;
+ /* Can't pre-compute the list size; the list
+ is stored on the class so accessible to other
+ threads, which may be run by DECREF */
+ for (i = 0; i < PyList_GET_SIZE(names); i++) {
+ PyObject *name, *value;
+ name = PyList_GET_ITEM(names, i);
+ value = PyObject_GetAttr(obj, name);
+ if (value == NULL)
+ PyErr_Clear();
+ else {
+ int err = PyDict_SetItem(slots, name,
+ value);
+ Py_DECREF(value);
+ if (err)
+ goto end;
+ n++;
+ }
+ }
+ if (n) {
+ state = Py_BuildValue("(NO)", state, slots);
+ if (state == NULL)
+ goto end;
+ }
+ }
+ }
+
+ if (!PyList_Check(obj)) {
+ listitems = Py_None;
+ Py_INCREF(listitems);
+ }
+ else {
+ listitems = PyObject_GetIter(obj);
+ if (listitems == NULL)
+ goto end;
+ }
+
+ if (!PyDict_Check(obj)) {
+ dictitems = Py_None;
+ Py_INCREF(dictitems);
+ }
+ else {
+ dictitems = PyObject_CallMethod(obj, "iteritems", "");
+ if (dictitems == NULL)
+ goto end;
+ }
+
+ copyreg = import_copyreg();
+ if (copyreg == NULL)
+ goto end;
+ newobj = PyObject_GetAttrString(copyreg, "__newobj__");
+ if (newobj == NULL)
+ goto end;
+
+ n = PyTuple_GET_SIZE(args);
+ args2 = PyTuple_New(n+1);
+ if (args2 == NULL)
+ goto end;
+ PyTuple_SET_ITEM(args2, 0, cls);
+ cls = NULL;
+ for (i = 0; i < n; i++) {
+ PyObject *v = PyTuple_GET_ITEM(args, i);
+ Py_INCREF(v);
+ PyTuple_SET_ITEM(args2, i+1, v);
+ }
+
+ res = PyTuple_Pack(5, newobj, args2, state, listitems, dictitems);
end:
- Py_XDECREF(cls);
- Py_XDECREF(args);
- Py_XDECREF(args2);
- Py_XDECREF(slots);
- Py_XDECREF(state);
- Py_XDECREF(names);
- Py_XDECREF(listitems);
- Py_XDECREF(dictitems);
- Py_XDECREF(copyreg);
- Py_XDECREF(newobj);
- return res;
+ Py_XDECREF(cls);
+ Py_XDECREF(args);
+ Py_XDECREF(args2);
+ Py_XDECREF(slots);
+ Py_XDECREF(state);
+ Py_XDECREF(names);
+ Py_XDECREF(listitems);
+ Py_XDECREF(dictitems);
+ Py_XDECREF(copyreg);
+ Py_XDECREF(newobj);
+ return res;
}
/*
@@ -3314,79 +3314,79 @@ reduce_2(PyObject *obj)
static PyObject *
_common_reduce(PyObject *self, int proto)
{
- PyObject *copyreg, *res;
+ PyObject *copyreg, *res;
- if (proto >= 2)
- return reduce_2(self);
+ if (proto >= 2)
+ return reduce_2(self);
- copyreg = import_copyreg();
- if (!copyreg)
- return NULL;
+ copyreg = import_copyreg();
+ if (!copyreg)
+ return NULL;
- res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
- Py_DECREF(copyreg);
+ res = PyEval_CallMethod(copyreg, "_reduce_ex", "(Oi)", self, proto);
+ Py_DECREF(copyreg);
- return res;
+ return res;
}
static PyObject *
object_reduce(PyObject *self, PyObject *args)
{
- int proto = 0;
+ int proto = 0;
- if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
- return NULL;
+ if (!PyArg_ParseTuple(args, "|i:__reduce__", &proto))
+ return NULL;
- return _common_reduce(self, proto);
+ return _common_reduce(self, proto);
}
static PyObject *
object_reduce_ex(PyObject *self, PyObject *args)
{
- PyObject *reduce, *res;
- int proto = 0;
-
- if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
- return NULL;
-
- reduce = PyObject_GetAttrString(self, "__reduce__");
- if (reduce == NULL)
- PyErr_Clear();
- else {
- PyObject *cls, *clsreduce, *objreduce;
- int override;
- cls = PyObject_GetAttrString(self, "__class__");
- if (cls == NULL) {
- Py_DECREF(reduce);
- return NULL;
- }
- clsreduce = PyObject_GetAttrString(cls, "__reduce__");
- Py_DECREF(cls);
- if (clsreduce == NULL) {
- Py_DECREF(reduce);
- return NULL;
- }
- objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
- "__reduce__");
- override = (clsreduce != objreduce);
- Py_DECREF(clsreduce);
- if (override) {
- res = PyObject_CallObject(reduce, NULL);
- Py_DECREF(reduce);
- return res;
- }
- else
- Py_DECREF(reduce);
- }
-
- return _common_reduce(self, proto);
+ PyObject *reduce, *res;
+ int proto = 0;
+
+ if (!PyArg_ParseTuple(args, "|i:__reduce_ex__", &proto))
+ return NULL;
+
+ reduce = PyObject_GetAttrString(self, "__reduce__");
+ if (reduce == NULL)
+ PyErr_Clear();
+ else {
+ PyObject *cls, *clsreduce, *objreduce;
+ int override;
+ cls = PyObject_GetAttrString(self, "__class__");
+ if (cls == NULL) {
+ Py_DECREF(reduce);
+ return NULL;
+ }
+ clsreduce = PyObject_GetAttrString(cls, "__reduce__");
+ Py_DECREF(cls);
+ if (clsreduce == NULL) {
+ Py_DECREF(reduce);
+ return NULL;
+ }
+ objreduce = PyDict_GetItemString(PyBaseObject_Type.tp_dict,
+ "__reduce__");
+ override = (clsreduce != objreduce);
+ Py_DECREF(clsreduce);
+ if (override) {
+ res = PyObject_CallObject(reduce, NULL);
+ Py_DECREF(reduce);
+ return res;
+ }
+ else
+ Py_DECREF(reduce);
+ }
+
+ return _common_reduce(self, proto);
}
static PyObject *
object_subclasshook(PyObject *cls, PyObject *args)
{
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
PyDoc_STRVAR(object_subclasshook_doc,
@@ -3402,141 +3402,141 @@ PyDoc_STRVAR(object_subclasshook_doc,
class object:
def __format__(self, format_spec):
- if isinstance(format_spec, str):
- return format(str(self), format_spec)
- elif isinstance(format_spec, unicode):
- return format(unicode(self), format_spec)
+ if isinstance(format_spec, str):
+ return format(str(self), format_spec)
+ elif isinstance(format_spec, unicode):
+ return format(unicode(self), format_spec)
*/
static PyObject *
object_format(PyObject *self, PyObject *args)
{
- PyObject *format_spec;
- PyObject *self_as_str = NULL;
- PyObject *result = NULL;
- PyObject *format_meth = NULL;
- Py_ssize_t format_len;
+ PyObject *format_spec;
+ PyObject *self_as_str = NULL;
+ PyObject *result = NULL;
+ PyObject *format_meth = NULL;
+ Py_ssize_t format_len;
- if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O:__format__", &format_spec))
+ return NULL;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(format_spec)) {
- format_len = PyUnicode_GET_SIZE(format_spec);
- self_as_str = PyObject_Unicode(self);
- } else if (PyString_Check(format_spec)) {
+ if (PyUnicode_Check(format_spec)) {
+ format_len = PyUnicode_GET_SIZE(format_spec);
+ self_as_str = PyObject_Unicode(self);
+ } else if (PyString_Check(format_spec)) {
#else
- if (PyString_Check(format_spec)) {
+ if (PyString_Check(format_spec)) {
#endif
- format_len = PyString_GET_SIZE(format_spec);
- self_as_str = PyObject_Str(self);
- } else {
- PyErr_SetString(PyExc_TypeError,
- "argument to __format__ must be unicode or str");
- return NULL;
- }
-
- if (self_as_str != NULL) {
- /* Issue 7994: If we're converting to a string, we
- should reject format specifications */
- if (format_len > 0) {
- if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
- "object.__format__ with a non-empty format "
- "string is deprecated", 1) < 0) {
- goto done;
- }
- /* Eventually this will become an error:
- PyErr_Format(PyExc_TypeError,
- "non-empty format string passed to object.__format__");
- goto done;
- */
- }
+ format_len = PyString_GET_SIZE(format_spec);
+ self_as_str = PyObject_Str(self);
+ } else {
+ PyErr_SetString(PyExc_TypeError,
+ "argument to __format__ must be unicode or str");
+ return NULL;
+ }
+
+ if (self_as_str != NULL) {
+ /* Issue 7994: If we're converting to a string, we
+ should reject format specifications */
+ if (format_len > 0) {
+ if (PyErr_WarnEx(PyExc_PendingDeprecationWarning,
+ "object.__format__ with a non-empty format "
+ "string is deprecated", 1) < 0) {
+ goto done;
+ }
+ /* Eventually this will become an error:
+ PyErr_Format(PyExc_TypeError,
+ "non-empty format string passed to object.__format__");
+ goto done;
+ */
+ }
- /* find the format function */
- format_meth = PyObject_GetAttrString(self_as_str,
- "__format__");
- if (format_meth != NULL) {
- /* and call it */
- result = PyObject_CallFunctionObjArgs(format_meth,
- format_spec,
- NULL);
- }
+ /* find the format function */
+ format_meth = PyObject_GetAttrString(self_as_str,
+ "__format__");
+ if (format_meth != NULL) {
+ /* and call it */
+ result = PyObject_CallFunctionObjArgs(format_meth,
+ format_spec,
+ NULL);
}
+ }
done:
- Py_XDECREF(self_as_str);
- Py_XDECREF(format_meth);
+ Py_XDECREF(self_as_str);
+ Py_XDECREF(format_meth);
- return result;
+ return result;
}
static PyObject *
object_sizeof(PyObject *self, PyObject *args)
{
- Py_ssize_t res, isize;
+ Py_ssize_t res, isize;
- res = 0;
- isize = self->ob_type->tp_itemsize;
- if (isize > 0)
- res = self->ob_type->ob_size * isize;
- res += self->ob_type->tp_basicsize;
+ res = 0;
+ isize = self->ob_type->tp_itemsize;
+ if (isize > 0)
+ res = self->ob_type->ob_size * isize;
+ res += self->ob_type->tp_basicsize;
- return PyInt_FromSsize_t(res);
+ return PyInt_FromSsize_t(res);
}
static PyMethodDef object_methods[] = {
- {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
- PyDoc_STR("helper for pickle")},
- {"__reduce__", object_reduce, METH_VARARGS,
- PyDoc_STR("helper for pickle")},
- {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
- object_subclasshook_doc},
- {"__format__", object_format, METH_VARARGS,
- PyDoc_STR("default object formatter")},
- {"__sizeof__", object_sizeof, METH_NOARGS,
- PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
- {0}
+ {"__reduce_ex__", object_reduce_ex, METH_VARARGS,
+ PyDoc_STR("helper for pickle")},
+ {"__reduce__", object_reduce, METH_VARARGS,
+ PyDoc_STR("helper for pickle")},
+ {"__subclasshook__", object_subclasshook, METH_CLASS | METH_VARARGS,
+ object_subclasshook_doc},
+ {"__format__", object_format, METH_VARARGS,
+ PyDoc_STR("default object formatter")},
+ {"__sizeof__", object_sizeof, METH_NOARGS,
+ PyDoc_STR("__sizeof__() -> size of object in memory, in bytes")},
+ {0}
};
PyTypeObject PyBaseObject_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "object", /* tp_name */
- sizeof(PyObject), /* tp_basicsize */
- 0, /* tp_itemsize */
- object_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- object_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- (hashfunc)_Py_HashPointer, /* tp_hash */
- 0, /* tp_call */
- object_str, /* tp_str */
- PyObject_GenericGetAttr, /* tp_getattro */
- PyObject_GenericSetAttr, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
- PyDoc_STR("The most base type"), /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- object_methods, /* tp_methods */
- 0, /* tp_members */
- object_getsets, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- 0, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- object_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- object_new, /* tp_new */
- PyObject_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "object", /* tp_name */
+ sizeof(PyObject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ object_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ object_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ (hashfunc)_Py_HashPointer, /* tp_hash */
+ 0, /* tp_call */
+ object_str, /* tp_str */
+ PyObject_GenericGetAttr, /* tp_getattro */
+ PyObject_GenericSetAttr, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
+ PyDoc_STR("The most base type"), /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ object_methods, /* tp_methods */
+ 0, /* tp_members */
+ object_getsets, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ 0, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ object_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ object_new, /* tp_new */
+ PyObject_Del, /* tp_free */
};
@@ -3545,77 +3545,77 @@ PyTypeObject PyBaseObject_Type = {
static int
add_methods(PyTypeObject *type, PyMethodDef *meth)
{
- PyObject *dict = type->tp_dict;
-
- for (; meth->ml_name != NULL; meth++) {
- PyObject *descr;
- if (PyDict_GetItemString(dict, meth->ml_name) &&
- !(meth->ml_flags & METH_COEXIST))
- continue;
- if (meth->ml_flags & METH_CLASS) {
- if (meth->ml_flags & METH_STATIC) {
- PyErr_SetString(PyExc_ValueError,
- "method cannot be both class and static");
- return -1;
- }
- descr = PyDescr_NewClassMethod(type, meth);
- }
- else if (meth->ml_flags & METH_STATIC) {
- PyObject *cfunc = PyCFunction_New(meth, NULL);
- if (cfunc == NULL)
- return -1;
- descr = PyStaticMethod_New(cfunc);
- Py_DECREF(cfunc);
- }
- else {
- descr = PyDescr_NewMethod(type, meth);
- }
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+
+ for (; meth->ml_name != NULL; meth++) {
+ PyObject *descr;
+ if (PyDict_GetItemString(dict, meth->ml_name) &&
+ !(meth->ml_flags & METH_COEXIST))
+ continue;
+ if (meth->ml_flags & METH_CLASS) {
+ if (meth->ml_flags & METH_STATIC) {
+ PyErr_SetString(PyExc_ValueError,
+ "method cannot be both class and static");
+ return -1;
+ }
+ descr = PyDescr_NewClassMethod(type, meth);
+ }
+ else if (meth->ml_flags & METH_STATIC) {
+ PyObject *cfunc = PyCFunction_New(meth, NULL);
+ if (cfunc == NULL)
+ return -1;
+ descr = PyStaticMethod_New(cfunc);
+ Py_DECREF(cfunc);
+ }
+ else {
+ descr = PyDescr_NewMethod(type, meth);
+ }
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, meth->ml_name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
static int
add_members(PyTypeObject *type, PyMemberDef *memb)
{
- PyObject *dict = type->tp_dict;
+ PyObject *dict = type->tp_dict;
- for (; memb->name != NULL; memb++) {
- PyObject *descr;
- if (PyDict_GetItemString(dict, memb->name))
- continue;
- descr = PyDescr_NewMember(type, memb);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, memb->name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ for (; memb->name != NULL; memb++) {
+ PyObject *descr;
+ if (PyDict_GetItemString(dict, memb->name))
+ continue;
+ descr = PyDescr_NewMember(type, memb);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, memb->name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
static int
add_getset(PyTypeObject *type, PyGetSetDef *gsp)
{
- PyObject *dict = type->tp_dict;
+ PyObject *dict = type->tp_dict;
- for (; gsp->name != NULL; gsp++) {
- PyObject *descr;
- if (PyDict_GetItemString(dict, gsp->name))
- continue;
- descr = PyDescr_NewGetSet(type, gsp);
+ for (; gsp->name != NULL; gsp++) {
+ PyObject *descr;
+ if (PyDict_GetItemString(dict, gsp->name))
+ continue;
+ descr = PyDescr_NewGetSet(type, gsp);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- return 0;
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItemString(dict, gsp->name, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ return 0;
}
#define BUFFER_FLAGS (Py_TPFLAGS_HAVE_GETCHARBUFFER | Py_TPFLAGS_HAVE_NEWBUFFER)
@@ -3623,114 +3623,114 @@ add_getset(PyTypeObject *type, PyGetSetDef *gsp)
static void
inherit_special(PyTypeObject *type, PyTypeObject *base)
{
- Py_ssize_t oldsize, newsize;
-
- /* Special flag magic */
- if (!type->tp_as_buffer && base->tp_as_buffer) {
- type->tp_flags &= ~BUFFER_FLAGS;
- type->tp_flags |=
- base->tp_flags & BUFFER_FLAGS;
- }
- if (!type->tp_as_sequence && base->tp_as_sequence) {
- type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
- type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
- }
- if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
- (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
- if ((!type->tp_as_number && base->tp_as_number) ||
- (!type->tp_as_sequence && base->tp_as_sequence)) {
- type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
- if (!type->tp_as_number && !type->tp_as_sequence) {
- type->tp_flags |= base->tp_flags &
- Py_TPFLAGS_HAVE_INPLACEOPS;
- }
- }
- /* Wow */
- }
- if (!type->tp_as_number && base->tp_as_number) {
- type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
- type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
- }
-
- /* Copying basicsize is connected to the GC flags */
- oldsize = base->tp_basicsize;
- newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
- if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
- (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
- (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
- (!type->tp_traverse && !type->tp_clear)) {
- type->tp_flags |= Py_TPFLAGS_HAVE_GC;
- if (type->tp_traverse == NULL)
- type->tp_traverse = base->tp_traverse;
- if (type->tp_clear == NULL)
- type->tp_clear = base->tp_clear;
- }
- if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
- /* The condition below could use some explanation.
- It appears that tp_new is not inherited for static types
- whose base class is 'object'; this seems to be a precaution
- so that old extension types don't suddenly become
- callable (object.__new__ wouldn't insure the invariants
- that the extension type's own factory function ensures).
- Heap types, of course, are under our control, so they do
- inherit tp_new; static extension types that specify some
- other built-in type as the default are considered
- new-style-aware so they also inherit object.__new__. */
- if (base != &PyBaseObject_Type ||
- (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
- if (type->tp_new == NULL)
- type->tp_new = base->tp_new;
- }
- }
- type->tp_basicsize = newsize;
-
- /* Copy other non-function slots */
+ Py_ssize_t oldsize, newsize;
+
+ /* Special flag magic */
+ if (!type->tp_as_buffer && base->tp_as_buffer) {
+ type->tp_flags &= ~BUFFER_FLAGS;
+ type->tp_flags |=
+ base->tp_flags & BUFFER_FLAGS;
+ }
+ if (!type->tp_as_sequence && base->tp_as_sequence) {
+ type->tp_flags &= ~Py_TPFLAGS_HAVE_SEQUENCE_IN;
+ type->tp_flags |= base->tp_flags & Py_TPFLAGS_HAVE_SEQUENCE_IN;
+ }
+ if ((type->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS) !=
+ (base->tp_flags & Py_TPFLAGS_HAVE_INPLACEOPS)) {
+ if ((!type->tp_as_number && base->tp_as_number) ||
+ (!type->tp_as_sequence && base->tp_as_sequence)) {
+ type->tp_flags &= ~Py_TPFLAGS_HAVE_INPLACEOPS;
+ if (!type->tp_as_number && !type->tp_as_sequence) {
+ type->tp_flags |= base->tp_flags &
+ Py_TPFLAGS_HAVE_INPLACEOPS;
+ }
+ }
+ /* Wow */
+ }
+ if (!type->tp_as_number && base->tp_as_number) {
+ type->tp_flags &= ~Py_TPFLAGS_CHECKTYPES;
+ type->tp_flags |= base->tp_flags & Py_TPFLAGS_CHECKTYPES;
+ }
+
+ /* Copying basicsize is connected to the GC flags */
+ oldsize = base->tp_basicsize;
+ newsize = type->tp_basicsize ? type->tp_basicsize : oldsize;
+ if (!(type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
+ (base->tp_flags & Py_TPFLAGS_HAVE_GC) &&
+ (type->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE/*GC slots exist*/) &&
+ (!type->tp_traverse && !type->tp_clear)) {
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
+ if (type->tp_traverse == NULL)
+ type->tp_traverse = base->tp_traverse;
+ if (type->tp_clear == NULL)
+ type->tp_clear = base->tp_clear;
+ }
+ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
+ /* The condition below could use some explanation.
+ It appears that tp_new is not inherited for static types
+ whose base class is 'object'; this seems to be a precaution
+ so that old extension types don't suddenly become
+ callable (object.__new__ wouldn't insure the invariants
+ that the extension type's own factory function ensures).
+ Heap types, of course, are under our control, so they do
+ inherit tp_new; static extension types that specify some
+ other built-in type as the default are considered
+ new-style-aware so they also inherit object.__new__. */
+ if (base != &PyBaseObject_Type ||
+ (type->tp_flags & Py_TPFLAGS_HEAPTYPE)) {
+ if (type->tp_new == NULL)
+ type->tp_new = base->tp_new;
+ }
+ }
+ type->tp_basicsize = newsize;
+
+ /* Copy other non-function slots */
#undef COPYVAL
#define COPYVAL(SLOT) \
- if (type->SLOT == 0) type->SLOT = base->SLOT
-
- COPYVAL(tp_itemsize);
- if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
- COPYVAL(tp_weaklistoffset);
- }
- if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
- COPYVAL(tp_dictoffset);
- }
-
- /* Setup fast subclass flags */
- if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
- type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
- else if (PyType_IsSubtype(base, &PyType_Type))
- type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
- else if (PyType_IsSubtype(base, &PyInt_Type))
- type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
- else if (PyType_IsSubtype(base, &PyLong_Type))
- type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
- else if (PyType_IsSubtype(base, &PyString_Type))
- type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
+ if (type->SLOT == 0) type->SLOT = base->SLOT
+
+ COPYVAL(tp_itemsize);
+ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_WEAKREFS) {
+ COPYVAL(tp_weaklistoffset);
+ }
+ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
+ COPYVAL(tp_dictoffset);
+ }
+
+ /* Setup fast subclass flags */
+ if (PyType_IsSubtype(base, (PyTypeObject*)PyExc_BaseException))
+ type->tp_flags |= Py_TPFLAGS_BASE_EXC_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyType_Type))
+ type->tp_flags |= Py_TPFLAGS_TYPE_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyInt_Type))
+ type->tp_flags |= Py_TPFLAGS_INT_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyLong_Type))
+ type->tp_flags |= Py_TPFLAGS_LONG_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyString_Type))
+ type->tp_flags |= Py_TPFLAGS_STRING_SUBCLASS;
#ifdef Py_USING_UNICODE
- else if (PyType_IsSubtype(base, &PyUnicode_Type))
- type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyUnicode_Type))
+ type->tp_flags |= Py_TPFLAGS_UNICODE_SUBCLASS;
#endif
- else if (PyType_IsSubtype(base, &PyTuple_Type))
- type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
- else if (PyType_IsSubtype(base, &PyList_Type))
- type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
- else if (PyType_IsSubtype(base, &PyDict_Type))
- type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyTuple_Type))
+ type->tp_flags |= Py_TPFLAGS_TUPLE_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyList_Type))
+ type->tp_flags |= Py_TPFLAGS_LIST_SUBCLASS;
+ else if (PyType_IsSubtype(base, &PyDict_Type))
+ type->tp_flags |= Py_TPFLAGS_DICT_SUBCLASS;
}
static int
overrides_name(PyTypeObject *type, char *name)
{
- PyObject *dict = type->tp_dict;
+ PyObject *dict = type->tp_dict;
- assert(dict != NULL);
- if (PyDict_GetItemString(dict, name) != NULL) {
- return 1;
- }
- return 0;
+ assert(dict != NULL);
+ if (PyDict_GetItemString(dict, name) != NULL) {
+ return 1;
+ }
+ return 0;
}
#define OVERRIDES_HASH(x) overrides_name(x, "__hash__")
@@ -3740,7 +3740,7 @@ overrides_name(PyTypeObject *type, char *name)
static void
inherit_slots(PyTypeObject *type, PyTypeObject *base)
{
- PyTypeObject *basebase;
+ PyTypeObject *basebase;
#undef SLOTDEFINED
#undef COPYSLOT
@@ -3750,185 +3750,185 @@ inherit_slots(PyTypeObject *type, PyTypeObject *base)
#undef COPYBUF
#define SLOTDEFINED(SLOT) \
- (base->SLOT != 0 && \
- (basebase == NULL || base->SLOT != basebase->SLOT))
+ (base->SLOT != 0 && \
+ (basebase == NULL || base->SLOT != basebase->SLOT))
#define COPYSLOT(SLOT) \
- if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
+ if (!type->SLOT && SLOTDEFINED(SLOT)) type->SLOT = base->SLOT
#define COPYNUM(SLOT) COPYSLOT(tp_as_number->SLOT)
#define COPYSEQ(SLOT) COPYSLOT(tp_as_sequence->SLOT)
#define COPYMAP(SLOT) COPYSLOT(tp_as_mapping->SLOT)
#define COPYBUF(SLOT) COPYSLOT(tp_as_buffer->SLOT)
- /* This won't inherit indirect slots (from tp_as_number etc.)
- if type doesn't provide the space. */
-
- if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
- basebase = base->tp_base;
- if (basebase->tp_as_number == NULL)
- basebase = NULL;
- COPYNUM(nb_add);
- COPYNUM(nb_subtract);
- COPYNUM(nb_multiply);
- COPYNUM(nb_divide);
- COPYNUM(nb_remainder);
- COPYNUM(nb_divmod);
- COPYNUM(nb_power);
- COPYNUM(nb_negative);
- COPYNUM(nb_positive);
- COPYNUM(nb_absolute);
- COPYNUM(nb_nonzero);
- COPYNUM(nb_invert);
- COPYNUM(nb_lshift);
- COPYNUM(nb_rshift);
- COPYNUM(nb_and);
- COPYNUM(nb_xor);
- COPYNUM(nb_or);
- COPYNUM(nb_coerce);
- COPYNUM(nb_int);
- COPYNUM(nb_long);
- COPYNUM(nb_float);
- COPYNUM(nb_oct);
- COPYNUM(nb_hex);
- COPYNUM(nb_inplace_add);
- COPYNUM(nb_inplace_subtract);
- COPYNUM(nb_inplace_multiply);
- COPYNUM(nb_inplace_divide);
- COPYNUM(nb_inplace_remainder);
- COPYNUM(nb_inplace_power);
- COPYNUM(nb_inplace_lshift);
- COPYNUM(nb_inplace_rshift);
- COPYNUM(nb_inplace_and);
- COPYNUM(nb_inplace_xor);
- COPYNUM(nb_inplace_or);
- if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
- COPYNUM(nb_true_divide);
- COPYNUM(nb_floor_divide);
- COPYNUM(nb_inplace_true_divide);
- COPYNUM(nb_inplace_floor_divide);
- }
- if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
- COPYNUM(nb_index);
- }
- }
-
- if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
- basebase = base->tp_base;
- if (basebase->tp_as_sequence == NULL)
- basebase = NULL;
- COPYSEQ(sq_length);
- COPYSEQ(sq_concat);
- COPYSEQ(sq_repeat);
- COPYSEQ(sq_item);
- COPYSEQ(sq_slice);
- COPYSEQ(sq_ass_item);
- COPYSEQ(sq_ass_slice);
- COPYSEQ(sq_contains);
- COPYSEQ(sq_inplace_concat);
- COPYSEQ(sq_inplace_repeat);
- }
-
- if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
- basebase = base->tp_base;
- if (basebase->tp_as_mapping == NULL)
- basebase = NULL;
- COPYMAP(mp_length);
- COPYMAP(mp_subscript);
- COPYMAP(mp_ass_subscript);
- }
-
- if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
- basebase = base->tp_base;
- if (basebase->tp_as_buffer == NULL)
- basebase = NULL;
- COPYBUF(bf_getreadbuffer);
- COPYBUF(bf_getwritebuffer);
- COPYBUF(bf_getsegcount);
- COPYBUF(bf_getcharbuffer);
- COPYBUF(bf_getbuffer);
- COPYBUF(bf_releasebuffer);
- }
-
- basebase = base->tp_base;
-
- COPYSLOT(tp_dealloc);
- COPYSLOT(tp_print);
- if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
- type->tp_getattr = base->tp_getattr;
- type->tp_getattro = base->tp_getattro;
- }
- if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
- type->tp_setattr = base->tp_setattr;
- type->tp_setattro = base->tp_setattro;
- }
- /* tp_compare see tp_richcompare */
- COPYSLOT(tp_repr);
- /* tp_hash see tp_richcompare */
- COPYSLOT(tp_call);
- COPYSLOT(tp_str);
- if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
- if (type->tp_compare == NULL &&
- type->tp_richcompare == NULL &&
- type->tp_hash == NULL)
- {
- type->tp_compare = base->tp_compare;
- type->tp_richcompare = base->tp_richcompare;
- type->tp_hash = base->tp_hash;
- /* Check for changes to inherited methods in Py3k*/
- if (Py_Py3kWarningFlag) {
- if (base->tp_hash &&
- (base->tp_hash != PyObject_HashNotImplemented) &&
- !OVERRIDES_HASH(type)) {
- if (OVERRIDES_CMP(type)) {
- PyErr_WarnPy3k("Overriding "
- "__cmp__ blocks inheritance "
- "of __hash__ in 3.x",
- 1);
- }
- if (OVERRIDES_EQ(type)) {
- PyErr_WarnPy3k("Overriding "
- "__eq__ blocks inheritance "
- "of __hash__ in 3.x",
- 1);
- }
- }
- }
- }
- }
- else {
- COPYSLOT(tp_compare);
- }
- if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
- COPYSLOT(tp_iter);
- COPYSLOT(tp_iternext);
- }
- if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
- COPYSLOT(tp_descr_get);
- COPYSLOT(tp_descr_set);
- COPYSLOT(tp_dictoffset);
- COPYSLOT(tp_init);
- COPYSLOT(tp_alloc);
- COPYSLOT(tp_is_gc);
- if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
- (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
- /* They agree about gc. */
- COPYSLOT(tp_free);
- }
- else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
- type->tp_free == NULL &&
- base->tp_free == _PyObject_Del) {
- /* A bit of magic to plug in the correct default
- * tp_free function when a derived class adds gc,
- * didn't define tp_free, and the base uses the
- * default non-gc tp_free.
- */
- type->tp_free = PyObject_GC_Del;
- }
- /* else they didn't agree about gc, and there isn't something
- * obvious to be done -- the type is on its own.
- */
- }
+ /* This won't inherit indirect slots (from tp_as_number etc.)
+ if type doesn't provide the space. */
+
+ if (type->tp_as_number != NULL && base->tp_as_number != NULL) {
+ basebase = base->tp_base;
+ if (basebase->tp_as_number == NULL)
+ basebase = NULL;
+ COPYNUM(nb_add);
+ COPYNUM(nb_subtract);
+ COPYNUM(nb_multiply);
+ COPYNUM(nb_divide);
+ COPYNUM(nb_remainder);
+ COPYNUM(nb_divmod);
+ COPYNUM(nb_power);
+ COPYNUM(nb_negative);
+ COPYNUM(nb_positive);
+ COPYNUM(nb_absolute);
+ COPYNUM(nb_nonzero);
+ COPYNUM(nb_invert);
+ COPYNUM(nb_lshift);
+ COPYNUM(nb_rshift);
+ COPYNUM(nb_and);
+ COPYNUM(nb_xor);
+ COPYNUM(nb_or);
+ COPYNUM(nb_coerce);
+ COPYNUM(nb_int);
+ COPYNUM(nb_long);
+ COPYNUM(nb_float);
+ COPYNUM(nb_oct);
+ COPYNUM(nb_hex);
+ COPYNUM(nb_inplace_add);
+ COPYNUM(nb_inplace_subtract);
+ COPYNUM(nb_inplace_multiply);
+ COPYNUM(nb_inplace_divide);
+ COPYNUM(nb_inplace_remainder);
+ COPYNUM(nb_inplace_power);
+ COPYNUM(nb_inplace_lshift);
+ COPYNUM(nb_inplace_rshift);
+ COPYNUM(nb_inplace_and);
+ COPYNUM(nb_inplace_xor);
+ COPYNUM(nb_inplace_or);
+ if (base->tp_flags & Py_TPFLAGS_CHECKTYPES) {
+ COPYNUM(nb_true_divide);
+ COPYNUM(nb_floor_divide);
+ COPYNUM(nb_inplace_true_divide);
+ COPYNUM(nb_inplace_floor_divide);
+ }
+ if (base->tp_flags & Py_TPFLAGS_HAVE_INDEX) {
+ COPYNUM(nb_index);
+ }
+ }
+
+ if (type->tp_as_sequence != NULL && base->tp_as_sequence != NULL) {
+ basebase = base->tp_base;
+ if (basebase->tp_as_sequence == NULL)
+ basebase = NULL;
+ COPYSEQ(sq_length);
+ COPYSEQ(sq_concat);
+ COPYSEQ(sq_repeat);
+ COPYSEQ(sq_item);
+ COPYSEQ(sq_slice);
+ COPYSEQ(sq_ass_item);
+ COPYSEQ(sq_ass_slice);
+ COPYSEQ(sq_contains);
+ COPYSEQ(sq_inplace_concat);
+ COPYSEQ(sq_inplace_repeat);
+ }
+
+ if (type->tp_as_mapping != NULL && base->tp_as_mapping != NULL) {
+ basebase = base->tp_base;
+ if (basebase->tp_as_mapping == NULL)
+ basebase = NULL;
+ COPYMAP(mp_length);
+ COPYMAP(mp_subscript);
+ COPYMAP(mp_ass_subscript);
+ }
+
+ if (type->tp_as_buffer != NULL && base->tp_as_buffer != NULL) {
+ basebase = base->tp_base;
+ if (basebase->tp_as_buffer == NULL)
+ basebase = NULL;
+ COPYBUF(bf_getreadbuffer);
+ COPYBUF(bf_getwritebuffer);
+ COPYBUF(bf_getsegcount);
+ COPYBUF(bf_getcharbuffer);
+ COPYBUF(bf_getbuffer);
+ COPYBUF(bf_releasebuffer);
+ }
+
+ basebase = base->tp_base;
+
+ COPYSLOT(tp_dealloc);
+ COPYSLOT(tp_print);
+ if (type->tp_getattr == NULL && type->tp_getattro == NULL) {
+ type->tp_getattr = base->tp_getattr;
+ type->tp_getattro = base->tp_getattro;
+ }
+ if (type->tp_setattr == NULL && type->tp_setattro == NULL) {
+ type->tp_setattr = base->tp_setattr;
+ type->tp_setattro = base->tp_setattro;
+ }
+ /* tp_compare see tp_richcompare */
+ COPYSLOT(tp_repr);
+ /* tp_hash see tp_richcompare */
+ COPYSLOT(tp_call);
+ COPYSLOT(tp_str);
+ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_RICHCOMPARE) {
+ if (type->tp_compare == NULL &&
+ type->tp_richcompare == NULL &&
+ type->tp_hash == NULL)
+ {
+ type->tp_compare = base->tp_compare;
+ type->tp_richcompare = base->tp_richcompare;
+ type->tp_hash = base->tp_hash;
+ /* Check for changes to inherited methods in Py3k*/
+ if (Py_Py3kWarningFlag) {
+ if (base->tp_hash &&
+ (base->tp_hash != PyObject_HashNotImplemented) &&
+ !OVERRIDES_HASH(type)) {
+ if (OVERRIDES_CMP(type)) {
+ PyErr_WarnPy3k("Overriding "
+ "__cmp__ blocks inheritance "
+ "of __hash__ in 3.x",
+ 1);
+ }
+ if (OVERRIDES_EQ(type)) {
+ PyErr_WarnPy3k("Overriding "
+ "__eq__ blocks inheritance "
+ "of __hash__ in 3.x",
+ 1);
+ }
+ }
+ }
+ }
+ }
+ else {
+ COPYSLOT(tp_compare);
+ }
+ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_ITER) {
+ COPYSLOT(tp_iter);
+ COPYSLOT(tp_iternext);
+ }
+ if (type->tp_flags & base->tp_flags & Py_TPFLAGS_HAVE_CLASS) {
+ COPYSLOT(tp_descr_get);
+ COPYSLOT(tp_descr_set);
+ COPYSLOT(tp_dictoffset);
+ COPYSLOT(tp_init);
+ COPYSLOT(tp_alloc);
+ COPYSLOT(tp_is_gc);
+ if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) ==
+ (base->tp_flags & Py_TPFLAGS_HAVE_GC)) {
+ /* They agree about gc. */
+ COPYSLOT(tp_free);
+ }
+ else if ((type->tp_flags & Py_TPFLAGS_HAVE_GC) &&
+ type->tp_free == NULL &&
+ base->tp_free == _PyObject_Del) {
+ /* A bit of magic to plug in the correct default
+ * tp_free function when a derived class adds gc,
+ * didn't define tp_free, and the base uses the
+ * default non-gc tp_free.
+ */
+ type->tp_free = PyObject_GC_Del;
+ }
+ /* else they didn't agree about gc, and there isn't something
+ * obvious to be done -- the type is on its own.
+ */
+ }
}
static int add_operators(PyTypeObject *);
@@ -3936,244 +3936,244 @@ static int add_operators(PyTypeObject *);
int
PyType_Ready(PyTypeObject *type)
{
- PyObject *dict, *bases;
- PyTypeObject *base;
- Py_ssize_t i, n;
+ PyObject *dict, *bases;
+ PyTypeObject *base;
+ Py_ssize_t i, n;
- if (type->tp_flags & Py_TPFLAGS_READY) {
- assert(type->tp_dict != NULL);
- return 0;
- }
- assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
+ if (type->tp_flags & Py_TPFLAGS_READY) {
+ assert(type->tp_dict != NULL);
+ return 0;
+ }
+ assert((type->tp_flags & Py_TPFLAGS_READYING) == 0);
- type->tp_flags |= Py_TPFLAGS_READYING;
+ type->tp_flags |= Py_TPFLAGS_READYING;
#ifdef Py_TRACE_REFS
- /* PyType_Ready is the closest thing we have to a choke point
- * for type objects, so is the best place I can think of to try
- * to get type objects into the doubly-linked list of all objects.
- * Still, not all type objects go thru PyType_Ready.
- */
- _Py_AddToAllObjects((PyObject *)type, 0);
+ /* PyType_Ready is the closest thing we have to a choke point
+ * for type objects, so is the best place I can think of to try
+ * to get type objects into the doubly-linked list of all objects.
+ * Still, not all type objects go thru PyType_Ready.
+ */
+ _Py_AddToAllObjects((PyObject *)type, 0);
#endif
- /* Initialize tp_base (defaults to BaseObject unless that's us) */
- base = type->tp_base;
- if (base == NULL && type != &PyBaseObject_Type) {
- base = type->tp_base = &PyBaseObject_Type;
- Py_INCREF(base);
- }
-
- /* Now the only way base can still be NULL is if type is
- * &PyBaseObject_Type.
- */
-
- /* Initialize the base class */
- if (base && base->tp_dict == NULL) {
- if (PyType_Ready(base) < 0)
- goto error;
- }
-
- /* Initialize ob_type if NULL. This means extensions that want to be
- compilable separately on Windows can call PyType_Ready() instead of
- initializing the ob_type field of their type objects. */
- /* The test for base != NULL is really unnecessary, since base is only
- NULL when type is &PyBaseObject_Type, and we know its ob_type is
- not NULL (it's initialized to &PyType_Type). But coverity doesn't
- know that. */
- if (Py_TYPE(type) == NULL && base != NULL)
- Py_TYPE(type) = Py_TYPE(base);
-
- /* Initialize tp_bases */
- bases = type->tp_bases;
- if (bases == NULL) {
- if (base == NULL)
- bases = PyTuple_New(0);
- else
- bases = PyTuple_Pack(1, base);
- if (bases == NULL)
- goto error;
- type->tp_bases = bases;
- }
-
- /* Initialize tp_dict */
- dict = type->tp_dict;
- if (dict == NULL) {
- dict = PyDict_New();
- if (dict == NULL)
- goto error;
- type->tp_dict = dict;
- }
-
- /* Add type-specific descriptors to tp_dict */
- if (add_operators(type) < 0)
- goto error;
- if (type->tp_methods != NULL) {
- if (add_methods(type, type->tp_methods) < 0)
- goto error;
- }
- if (type->tp_members != NULL) {
- if (add_members(type, type->tp_members) < 0)
- goto error;
- }
- if (type->tp_getset != NULL) {
- if (add_getset(type, type->tp_getset) < 0)
- goto error;
- }
-
- /* Calculate method resolution order */
- if (mro_internal(type) < 0) {
- goto error;
- }
-
- /* Inherit special flags from dominant base */
- if (type->tp_base != NULL)
- inherit_special(type, type->tp_base);
-
- /* Initialize tp_dict properly */
- bases = type->tp_mro;
- assert(bases != NULL);
- assert(PyTuple_Check(bases));
- n = PyTuple_GET_SIZE(bases);
- for (i = 1; i < n; i++) {
- PyObject *b = PyTuple_GET_ITEM(bases, i);
- if (PyType_Check(b))
- inherit_slots(type, (PyTypeObject *)b);
- }
-
- /* Sanity check for tp_free. */
- if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
- (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
- /* This base class needs to call tp_free, but doesn't have
- * one, or its tp_free is for non-gc'ed objects.
- */
- PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
- "gc and is a base type but has inappropriate "
- "tp_free slot",
- type->tp_name);
- goto error;
- }
-
- /* if the type dictionary doesn't contain a __doc__, set it from
- the tp_doc slot.
- */
- if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
- if (type->tp_doc != NULL) {
- PyObject *doc = PyString_FromString(type->tp_doc);
- if (doc == NULL)
- goto error;
- PyDict_SetItemString(type->tp_dict, "__doc__", doc);
- Py_DECREF(doc);
- } else {
- PyDict_SetItemString(type->tp_dict,
- "__doc__", Py_None);
- }
- }
-
- /* Some more special stuff */
- base = type->tp_base;
- if (base != NULL) {
- if (type->tp_as_number == NULL)
- type->tp_as_number = base->tp_as_number;
- if (type->tp_as_sequence == NULL)
- type->tp_as_sequence = base->tp_as_sequence;
- if (type->tp_as_mapping == NULL)
- type->tp_as_mapping = base->tp_as_mapping;
- if (type->tp_as_buffer == NULL)
- type->tp_as_buffer = base->tp_as_buffer;
- }
-
- /* Link into each base class's list of subclasses */
- bases = type->tp_bases;
- n = PyTuple_GET_SIZE(bases);
- for (i = 0; i < n; i++) {
- PyObject *b = PyTuple_GET_ITEM(bases, i);
- if (PyType_Check(b) &&
- add_subclass((PyTypeObject *)b, type) < 0)
- goto error;
- }
-
- /* All done -- set the ready flag */
- assert(type->tp_dict != NULL);
- type->tp_flags =
- (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
- return 0;
+ /* Initialize tp_base (defaults to BaseObject unless that's us) */
+ base = type->tp_base;
+ if (base == NULL && type != &PyBaseObject_Type) {
+ base = type->tp_base = &PyBaseObject_Type;
+ Py_INCREF(base);
+ }
+
+ /* Now the only way base can still be NULL is if type is
+ * &PyBaseObject_Type.
+ */
+
+ /* Initialize the base class */
+ if (base && base->tp_dict == NULL) {
+ if (PyType_Ready(base) < 0)
+ goto error;
+ }
+
+ /* Initialize ob_type if NULL. This means extensions that want to be
+ compilable separately on Windows can call PyType_Ready() instead of
+ initializing the ob_type field of their type objects. */
+ /* The test for base != NULL is really unnecessary, since base is only
+ NULL when type is &PyBaseObject_Type, and we know its ob_type is
+ not NULL (it's initialized to &PyType_Type). But coverity doesn't
+ know that. */
+ if (Py_TYPE(type) == NULL && base != NULL)
+ Py_TYPE(type) = Py_TYPE(base);
+
+ /* Initialize tp_bases */
+ bases = type->tp_bases;
+ if (bases == NULL) {
+ if (base == NULL)
+ bases = PyTuple_New(0);
+ else
+ bases = PyTuple_Pack(1, base);
+ if (bases == NULL)
+ goto error;
+ type->tp_bases = bases;
+ }
+
+ /* Initialize tp_dict */
+ dict = type->tp_dict;
+ if (dict == NULL) {
+ dict = PyDict_New();
+ if (dict == NULL)
+ goto error;
+ type->tp_dict = dict;
+ }
+
+ /* Add type-specific descriptors to tp_dict */
+ if (add_operators(type) < 0)
+ goto error;
+ if (type->tp_methods != NULL) {
+ if (add_methods(type, type->tp_methods) < 0)
+ goto error;
+ }
+ if (type->tp_members != NULL) {
+ if (add_members(type, type->tp_members) < 0)
+ goto error;
+ }
+ if (type->tp_getset != NULL) {
+ if (add_getset(type, type->tp_getset) < 0)
+ goto error;
+ }
+
+ /* Calculate method resolution order */
+ if (mro_internal(type) < 0) {
+ goto error;
+ }
+
+ /* Inherit special flags from dominant base */
+ if (type->tp_base != NULL)
+ inherit_special(type, type->tp_base);
+
+ /* Initialize tp_dict properly */
+ bases = type->tp_mro;
+ assert(bases != NULL);
+ assert(PyTuple_Check(bases));
+ n = PyTuple_GET_SIZE(bases);
+ for (i = 1; i < n; i++) {
+ PyObject *b = PyTuple_GET_ITEM(bases, i);
+ if (PyType_Check(b))
+ inherit_slots(type, (PyTypeObject *)b);
+ }
+
+ /* Sanity check for tp_free. */
+ if (PyType_IS_GC(type) && (type->tp_flags & Py_TPFLAGS_BASETYPE) &&
+ (type->tp_free == NULL || type->tp_free == PyObject_Del)) {
+ /* This base class needs to call tp_free, but doesn't have
+ * one, or its tp_free is for non-gc'ed objects.
+ */
+ PyErr_Format(PyExc_TypeError, "type '%.100s' participates in "
+ "gc and is a base type but has inappropriate "
+ "tp_free slot",
+ type->tp_name);
+ goto error;
+ }
+
+ /* if the type dictionary doesn't contain a __doc__, set it from
+ the tp_doc slot.
+ */
+ if (PyDict_GetItemString(type->tp_dict, "__doc__") == NULL) {
+ if (type->tp_doc != NULL) {
+ PyObject *doc = PyString_FromString(type->tp_doc);
+ if (doc == NULL)
+ goto error;
+ PyDict_SetItemString(type->tp_dict, "__doc__", doc);
+ Py_DECREF(doc);
+ } else {
+ PyDict_SetItemString(type->tp_dict,
+ "__doc__", Py_None);
+ }
+ }
+
+ /* Some more special stuff */
+ base = type->tp_base;
+ if (base != NULL) {
+ if (type->tp_as_number == NULL)
+ type->tp_as_number = base->tp_as_number;
+ if (type->tp_as_sequence == NULL)
+ type->tp_as_sequence = base->tp_as_sequence;
+ if (type->tp_as_mapping == NULL)
+ type->tp_as_mapping = base->tp_as_mapping;
+ if (type->tp_as_buffer == NULL)
+ type->tp_as_buffer = base->tp_as_buffer;
+ }
+
+ /* Link into each base class's list of subclasses */
+ bases = type->tp_bases;
+ n = PyTuple_GET_SIZE(bases);
+ for (i = 0; i < n; i++) {
+ PyObject *b = PyTuple_GET_ITEM(bases, i);
+ if (PyType_Check(b) &&
+ add_subclass((PyTypeObject *)b, type) < 0)
+ goto error;
+ }
+
+ /* All done -- set the ready flag */
+ assert(type->tp_dict != NULL);
+ type->tp_flags =
+ (type->tp_flags & ~Py_TPFLAGS_READYING) | Py_TPFLAGS_READY;
+ return 0;
error:
- type->tp_flags &= ~Py_TPFLAGS_READYING;
- return -1;
+ type->tp_flags &= ~Py_TPFLAGS_READYING;
+ return -1;
}
static int
add_subclass(PyTypeObject *base, PyTypeObject *type)
{
- Py_ssize_t i;
- int result;
- PyObject *list, *ref, *newobj;
-
- list = base->tp_subclasses;
- if (list == NULL) {
- base->tp_subclasses = list = PyList_New(0);
- if (list == NULL)
- return -1;
- }
- assert(PyList_Check(list));
- newobj = PyWeakref_NewRef((PyObject *)type, NULL);
- i = PyList_GET_SIZE(list);
- while (--i >= 0) {
- ref = PyList_GET_ITEM(list, i);
- assert(PyWeakref_CheckRef(ref));
- if (PyWeakref_GET_OBJECT(ref) == Py_None)
- return PyList_SetItem(list, i, newobj);
- }
- result = PyList_Append(list, newobj);
- Py_DECREF(newobj);
- return result;
+ Py_ssize_t i;
+ int result;
+ PyObject *list, *ref, *newobj;
+
+ list = base->tp_subclasses;
+ if (list == NULL) {
+ base->tp_subclasses = list = PyList_New(0);
+ if (list == NULL)
+ return -1;
+ }
+ assert(PyList_Check(list));
+ newobj = PyWeakref_NewRef((PyObject *)type, NULL);
+ i = PyList_GET_SIZE(list);
+ while (--i >= 0) {
+ ref = PyList_GET_ITEM(list, i);
+ assert(PyWeakref_CheckRef(ref));
+ if (PyWeakref_GET_OBJECT(ref) == Py_None)
+ return PyList_SetItem(list, i, newobj);
+ }
+ result = PyList_Append(list, newobj);
+ Py_DECREF(newobj);
+ return result;
}
static void
remove_subclass(PyTypeObject *base, PyTypeObject *type)
{
- Py_ssize_t i;
- PyObject *list, *ref;
-
- list = base->tp_subclasses;
- if (list == NULL) {
- return;
- }
- assert(PyList_Check(list));
- i = PyList_GET_SIZE(list);
- while (--i >= 0) {
- ref = PyList_GET_ITEM(list, i);
- assert(PyWeakref_CheckRef(ref));
- if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
- /* this can't fail, right? */
- PySequence_DelItem(list, i);
- return;
- }
- }
+ Py_ssize_t i;
+ PyObject *list, *ref;
+
+ list = base->tp_subclasses;
+ if (list == NULL) {
+ return;
+ }
+ assert(PyList_Check(list));
+ i = PyList_GET_SIZE(list);
+ while (--i >= 0) {
+ ref = PyList_GET_ITEM(list, i);
+ assert(PyWeakref_CheckRef(ref));
+ if (PyWeakref_GET_OBJECT(ref) == (PyObject*)type) {
+ /* this can't fail, right? */
+ PySequence_DelItem(list, i);
+ return;
+ }
+ }
}
static int
check_num_args(PyObject *ob, int n)
{
- if (!PyTuple_CheckExact(ob)) {
- PyErr_SetString(PyExc_SystemError,
- "PyArg_UnpackTuple() argument list is not a tuple");
- return 0;
- }
- if (n == PyTuple_GET_SIZE(ob))
- return 1;
- PyErr_Format(
- PyExc_TypeError,
- "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
- return 0;
+ if (!PyTuple_CheckExact(ob)) {
+ PyErr_SetString(PyExc_SystemError,
+ "PyArg_UnpackTuple() argument list is not a tuple");
+ return 0;
+ }
+ if (n == PyTuple_GET_SIZE(ob))
+ return 1;
+ PyErr_Format(
+ PyExc_TypeError,
+ "expected %d arguments, got %zd", n, PyTuple_GET_SIZE(ob));
+ return 0;
}
/* Generic wrappers for overloadable 'operators' such as __getitem__ */
/* There's a wrapper *function* for each distinct function typedef used
- for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
+ for type object slots (e.g. binaryfunc, ternaryfunc, etc.). There's a
wrapper *table* for each distinct operation (e.g. __len__, __add__).
Most tables have only one entry; the tables for binary operators have two
entries, one regular and one with reversed arguments. */
@@ -4181,357 +4181,357 @@ check_num_args(PyObject *ob, int n)
static PyObject *
wrap_lenfunc(PyObject *self, PyObject *args, void *wrapped)
{
- lenfunc func = (lenfunc)wrapped;
- Py_ssize_t res;
+ lenfunc func = (lenfunc)wrapped;
+ Py_ssize_t res;
- if (!check_num_args(args, 0))
- return NULL;
- res = (*func)(self);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- return PyInt_FromLong((long)res);
+ if (!check_num_args(args, 0))
+ return NULL;
+ res = (*func)(self);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ return PyInt_FromLong((long)res);
}
static PyObject *
wrap_inquirypred(PyObject *self, PyObject *args, void *wrapped)
{
- inquiry func = (inquiry)wrapped;
- int res;
+ inquiry func = (inquiry)wrapped;
+ int res;
- if (!check_num_args(args, 0))
- return NULL;
- res = (*func)(self);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- return PyBool_FromLong((long)res);
+ if (!check_num_args(args, 0))
+ return NULL;
+ res = (*func)(self);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ return PyBool_FromLong((long)res);
}
static PyObject *
wrap_binaryfunc(PyObject *self, PyObject *args, void *wrapped)
{
- binaryfunc func = (binaryfunc)wrapped;
- PyObject *other;
+ binaryfunc func = (binaryfunc)wrapped;
+ PyObject *other;
- if (!check_num_args(args, 1))
- return NULL;
- other = PyTuple_GET_ITEM(args, 0);
- return (*func)(self, other);
+ if (!check_num_args(args, 1))
+ return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ return (*func)(self, other);
}
static PyObject *
wrap_binaryfunc_l(PyObject *self, PyObject *args, void *wrapped)
{
- binaryfunc func = (binaryfunc)wrapped;
- PyObject *other;
+ binaryfunc func = (binaryfunc)wrapped;
+ PyObject *other;
- if (!check_num_args(args, 1))
- return NULL;
- other = PyTuple_GET_ITEM(args, 0);
- if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
- !PyType_IsSubtype(other->ob_type, self->ob_type)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return (*func)(self, other);
+ if (!check_num_args(args, 1))
+ return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
+ !PyType_IsSubtype(other->ob_type, self->ob_type)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return (*func)(self, other);
}
static PyObject *
wrap_binaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
{
- binaryfunc func = (binaryfunc)wrapped;
- PyObject *other;
+ binaryfunc func = (binaryfunc)wrapped;
+ PyObject *other;
- if (!check_num_args(args, 1))
- return NULL;
- other = PyTuple_GET_ITEM(args, 0);
- if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
- !PyType_IsSubtype(other->ob_type, self->ob_type)) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- return (*func)(other, self);
+ if (!check_num_args(args, 1))
+ return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ if (!(self->ob_type->tp_flags & Py_TPFLAGS_CHECKTYPES) &&
+ !PyType_IsSubtype(other->ob_type, self->ob_type)) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ return (*func)(other, self);
}
static PyObject *
wrap_coercefunc(PyObject *self, PyObject *args, void *wrapped)
{
- coercion func = (coercion)wrapped;
- PyObject *other, *res;
- int ok;
-
- if (!check_num_args(args, 1))
- return NULL;
- other = PyTuple_GET_ITEM(args, 0);
- ok = func(&self, &other);
- if (ok < 0)
- return NULL;
- if (ok > 0) {
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- res = PyTuple_New(2);
- if (res == NULL) {
- Py_DECREF(self);
- Py_DECREF(other);
- return NULL;
- }
- PyTuple_SET_ITEM(res, 0, self);
- PyTuple_SET_ITEM(res, 1, other);
- return res;
+ coercion func = (coercion)wrapped;
+ PyObject *other, *res;
+ int ok;
+
+ if (!check_num_args(args, 1))
+ return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ ok = func(&self, &other);
+ if (ok < 0)
+ return NULL;
+ if (ok > 0) {
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ res = PyTuple_New(2);
+ if (res == NULL) {
+ Py_DECREF(self);
+ Py_DECREF(other);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(res, 0, self);
+ PyTuple_SET_ITEM(res, 1, other);
+ return res;
}
static PyObject *
wrap_ternaryfunc(PyObject *self, PyObject *args, void *wrapped)
{
- ternaryfunc func = (ternaryfunc)wrapped;
- PyObject *other;
- PyObject *third = Py_None;
+ ternaryfunc func = (ternaryfunc)wrapped;
+ PyObject *other;
+ PyObject *third = Py_None;
- /* Note: This wrapper only works for __pow__() */
+ /* Note: This wrapper only works for __pow__() */
- if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
- return NULL;
- return (*func)(self, other, third);
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
+ return NULL;
+ return (*func)(self, other, third);
}
static PyObject *
wrap_ternaryfunc_r(PyObject *self, PyObject *args, void *wrapped)
{
- ternaryfunc func = (ternaryfunc)wrapped;
- PyObject *other;
- PyObject *third = Py_None;
+ ternaryfunc func = (ternaryfunc)wrapped;
+ PyObject *other;
+ PyObject *third = Py_None;
- /* Note: This wrapper only works for __pow__() */
+ /* Note: This wrapper only works for __pow__() */
- if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
- return NULL;
- return (*func)(other, self, third);
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &other, &third))
+ return NULL;
+ return (*func)(other, self, third);
}
static PyObject *
wrap_unaryfunc(PyObject *self, PyObject *args, void *wrapped)
{
- unaryfunc func = (unaryfunc)wrapped;
+ unaryfunc func = (unaryfunc)wrapped;
- if (!check_num_args(args, 0))
- return NULL;
- return (*func)(self);
+ if (!check_num_args(args, 0))
+ return NULL;
+ return (*func)(self);
}
static PyObject *
wrap_indexargfunc(PyObject *self, PyObject *args, void *wrapped)
{
- ssizeargfunc func = (ssizeargfunc)wrapped;
- PyObject* o;
- Py_ssize_t i;
+ ssizeargfunc func = (ssizeargfunc)wrapped;
+ PyObject* o;
+ Py_ssize_t i;
- if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
- return NULL;
- i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- return (*func)(self, i);
+ if (!PyArg_UnpackTuple(args, "", 1, 1, &o))
+ return NULL;
+ i = PyNumber_AsSsize_t(o, PyExc_OverflowError);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ return (*func)(self, i);
}
static Py_ssize_t
getindex(PyObject *self, PyObject *arg)
{
- Py_ssize_t i;
-
- i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
- if (i == -1 && PyErr_Occurred())
- return -1;
- if (i < 0) {
- PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
- if (sq && sq->sq_length) {
- Py_ssize_t n = (*sq->sq_length)(self);
- if (n < 0)
- return -1;
- i += n;
- }
- }
- return i;
+ Py_ssize_t i;
+
+ i = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
+ if (i == -1 && PyErr_Occurred())
+ return -1;
+ if (i < 0) {
+ PySequenceMethods *sq = Py_TYPE(self)->tp_as_sequence;
+ if (sq && sq->sq_length) {
+ Py_ssize_t n = (*sq->sq_length)(self);
+ if (n < 0)
+ return -1;
+ i += n;
+ }
+ }
+ return i;
}
static PyObject *
wrap_sq_item(PyObject *self, PyObject *args, void *wrapped)
{
- ssizeargfunc func = (ssizeargfunc)wrapped;
- PyObject *arg;
- Py_ssize_t i;
+ ssizeargfunc func = (ssizeargfunc)wrapped;
+ PyObject *arg;
+ Py_ssize_t i;
- if (PyTuple_GET_SIZE(args) == 1) {
- arg = PyTuple_GET_ITEM(args, 0);
- i = getindex(self, arg);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- return (*func)(self, i);
- }
- check_num_args(args, 1);
- assert(PyErr_Occurred());
- return NULL;
+ if (PyTuple_GET_SIZE(args) == 1) {
+ arg = PyTuple_GET_ITEM(args, 0);
+ i = getindex(self, arg);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ return (*func)(self, i);
+ }
+ check_num_args(args, 1);
+ assert(PyErr_Occurred());
+ return NULL;
}
static PyObject *
wrap_ssizessizeargfunc(PyObject *self, PyObject *args, void *wrapped)
{
- ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
- Py_ssize_t i, j;
+ ssizessizeargfunc func = (ssizessizeargfunc)wrapped;
+ Py_ssize_t i, j;
- if (!PyArg_ParseTuple(args, "nn", &i, &j))
- return NULL;
- return (*func)(self, i, j);
+ if (!PyArg_ParseTuple(args, "nn", &i, &j))
+ return NULL;
+ return (*func)(self, i, j);
}
static PyObject *
wrap_sq_setitem(PyObject *self, PyObject *args, void *wrapped)
{
- ssizeobjargproc func = (ssizeobjargproc)wrapped;
- Py_ssize_t i;
- int res;
- PyObject *arg, *value;
+ ssizeobjargproc func = (ssizeobjargproc)wrapped;
+ Py_ssize_t i;
+ int res;
+ PyObject *arg, *value;
- if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
- return NULL;
- i = getindex(self, arg);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- res = (*func)(self, i, value);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_UnpackTuple(args, "", 2, 2, &arg, &value))
+ return NULL;
+ i = getindex(self, arg);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ res = (*func)(self, i, value);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_sq_delitem(PyObject *self, PyObject *args, void *wrapped)
{
- ssizeobjargproc func = (ssizeobjargproc)wrapped;
- Py_ssize_t i;
- int res;
- PyObject *arg;
+ ssizeobjargproc func = (ssizeobjargproc)wrapped;
+ Py_ssize_t i;
+ int res;
+ PyObject *arg;
- if (!check_num_args(args, 1))
- return NULL;
- arg = PyTuple_GET_ITEM(args, 0);
- i = getindex(self, arg);
- if (i == -1 && PyErr_Occurred())
- return NULL;
- res = (*func)(self, i, NULL);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!check_num_args(args, 1))
+ return NULL;
+ arg = PyTuple_GET_ITEM(args, 0);
+ i = getindex(self, arg);
+ if (i == -1 && PyErr_Occurred())
+ return NULL;
+ res = (*func)(self, i, NULL);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_ssizessizeobjargproc(PyObject *self, PyObject *args, void *wrapped)
{
- ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
- Py_ssize_t i, j;
- int res;
- PyObject *value;
+ ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
+ Py_ssize_t i, j;
+ int res;
+ PyObject *value;
- if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
- return NULL;
- res = (*func)(self, i, j, value);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "nnO", &i, &j, &value))
+ return NULL;
+ res = (*func)(self, i, j, value);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_delslice(PyObject *self, PyObject *args, void *wrapped)
{
- ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
- Py_ssize_t i, j;
- int res;
+ ssizessizeobjargproc func = (ssizessizeobjargproc)wrapped;
+ Py_ssize_t i, j;
+ int res;
- if (!PyArg_ParseTuple(args, "nn", &i, &j))
- return NULL;
- res = (*func)(self, i, j, NULL);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "nn", &i, &j))
+ return NULL;
+ res = (*func)(self, i, j, NULL);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
/* XXX objobjproc is a misnomer; should be objargpred */
static PyObject *
wrap_objobjproc(PyObject *self, PyObject *args, void *wrapped)
{
- objobjproc func = (objobjproc)wrapped;
- int res;
- PyObject *value;
+ objobjproc func = (objobjproc)wrapped;
+ int res;
+ PyObject *value;
- if (!check_num_args(args, 1))
- return NULL;
- value = PyTuple_GET_ITEM(args, 0);
- res = (*func)(self, value);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- else
- return PyBool_FromLong(res);
+ if (!check_num_args(args, 1))
+ return NULL;
+ value = PyTuple_GET_ITEM(args, 0);
+ res = (*func)(self, value);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ else
+ return PyBool_FromLong(res);
}
static PyObject *
wrap_objobjargproc(PyObject *self, PyObject *args, void *wrapped)
{
- objobjargproc func = (objobjargproc)wrapped;
- int res;
- PyObject *key, *value;
+ objobjargproc func = (objobjargproc)wrapped;
+ int res;
+ PyObject *key, *value;
- if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
- return NULL;
- res = (*func)(self, key, value);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_UnpackTuple(args, "", 2, 2, &key, &value))
+ return NULL;
+ res = (*func)(self, key, value);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_delitem(PyObject *self, PyObject *args, void *wrapped)
{
- objobjargproc func = (objobjargproc)wrapped;
- int res;
- PyObject *key;
+ objobjargproc func = (objobjargproc)wrapped;
+ int res;
+ PyObject *key;
- if (!check_num_args(args, 1))
- return NULL;
- key = PyTuple_GET_ITEM(args, 0);
- res = (*func)(self, key, NULL);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!check_num_args(args, 1))
+ return NULL;
+ key = PyTuple_GET_ITEM(args, 0);
+ res = (*func)(self, key, NULL);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
{
- cmpfunc func = (cmpfunc)wrapped;
- int res;
- PyObject *other;
-
- if (!check_num_args(args, 1))
- return NULL;
- other = PyTuple_GET_ITEM(args, 0);
- if (Py_TYPE(other)->tp_compare != func &&
- !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
- PyErr_Format(
- PyExc_TypeError,
- "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
- Py_TYPE(self)->tp_name,
- Py_TYPE(self)->tp_name,
- Py_TYPE(other)->tp_name);
- return NULL;
- }
- res = (*func)(self, other);
- if (PyErr_Occurred())
- return NULL;
- return PyInt_FromLong((long)res);
+ cmpfunc func = (cmpfunc)wrapped;
+ int res;
+ PyObject *other;
+
+ if (!check_num_args(args, 1))
+ return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ if (Py_TYPE(other)->tp_compare != func &&
+ !PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self))) {
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s.__cmp__(x,y) requires y to be a '%s', not a '%s'",
+ Py_TYPE(self)->tp_name,
+ Py_TYPE(self)->tp_name,
+ Py_TYPE(other)->tp_name);
+ return NULL;
+ }
+ res = (*func)(self, other);
+ if (PyErr_Occurred())
+ return NULL;
+ return PyInt_FromLong((long)res);
}
/* Helper to check for object.__setattr__ or __delattr__ applied to a type.
@@ -4539,90 +4539,90 @@ wrap_cmpfunc(PyObject *self, PyObject *args, void *wrapped)
static int
hackcheck(PyObject *self, setattrofunc func, char *what)
{
- PyTypeObject *type = Py_TYPE(self);
- while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
- type = type->tp_base;
- /* If type is NULL now, this is a really weird type.
- In the spirit of backwards compatibility (?), just shut up. */
- if (type && type->tp_setattro != func) {
- PyErr_Format(PyExc_TypeError,
- "can't apply this %s to %s object",
- what,
- type->tp_name);
- return 0;
- }
- return 1;
+ PyTypeObject *type = Py_TYPE(self);
+ while (type && type->tp_flags & Py_TPFLAGS_HEAPTYPE)
+ type = type->tp_base;
+ /* If type is NULL now, this is a really weird type.
+ In the spirit of backwards compatibility (?), just shut up. */
+ if (type && type->tp_setattro != func) {
+ PyErr_Format(PyExc_TypeError,
+ "can't apply this %s to %s object",
+ what,
+ type->tp_name);
+ return 0;
+ }
+ return 1;
}
static PyObject *
wrap_setattr(PyObject *self, PyObject *args, void *wrapped)
{
- setattrofunc func = (setattrofunc)wrapped;
- int res;
- PyObject *name, *value;
+ setattrofunc func = (setattrofunc)wrapped;
+ int res;
+ PyObject *name, *value;
- if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
- return NULL;
- if (!hackcheck(self, func, "__setattr__"))
- return NULL;
- res = (*func)(self, name, value);
- if (res < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_UnpackTuple(args, "", 2, 2, &name, &value))
+ return NULL;
+ if (!hackcheck(self, func, "__setattr__"))
+ return NULL;
+ res = (*func)(self, name, value);
+ if (res < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_delattr(PyObject *self, PyObject *args, void *wrapped)
{
- setattrofunc func = (setattrofunc)wrapped;
- int res;
- PyObject *name;
+ setattrofunc func = (setattrofunc)wrapped;
+ int res;
+ PyObject *name;
- if (!check_num_args(args, 1))
- return NULL;
- name = PyTuple_GET_ITEM(args, 0);
- if (!hackcheck(self, func, "__delattr__"))
- return NULL;
- res = (*func)(self, name, NULL);
- if (res < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!check_num_args(args, 1))
+ return NULL;
+ name = PyTuple_GET_ITEM(args, 0);
+ if (!hackcheck(self, func, "__delattr__"))
+ return NULL;
+ res = (*func)(self, name, NULL);
+ if (res < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_hashfunc(PyObject *self, PyObject *args, void *wrapped)
{
- hashfunc func = (hashfunc)wrapped;
- long res;
+ hashfunc func = (hashfunc)wrapped;
+ long res;
- if (!check_num_args(args, 0))
- return NULL;
- res = (*func)(self);
- if (res == -1 && PyErr_Occurred())
- return NULL;
- return PyInt_FromLong(res);
+ if (!check_num_args(args, 0))
+ return NULL;
+ res = (*func)(self);
+ if (res == -1 && PyErr_Occurred())
+ return NULL;
+ return PyInt_FromLong(res);
}
static PyObject *
wrap_call(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
{
- ternaryfunc func = (ternaryfunc)wrapped;
+ ternaryfunc func = (ternaryfunc)wrapped;
- return (*func)(self, args, kwds);
+ return (*func)(self, args, kwds);
}
static PyObject *
wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
{
- richcmpfunc func = (richcmpfunc)wrapped;
- PyObject *other;
+ richcmpfunc func = (richcmpfunc)wrapped;
+ PyObject *other;
- if (!check_num_args(args, 1))
- return NULL;
- other = PyTuple_GET_ITEM(args, 0);
- return (*func)(self, other, op);
+ if (!check_num_args(args, 1))
+ return NULL;
+ other = PyTuple_GET_ITEM(args, 0);
+ return (*func)(self, other, op);
}
#undef RICHCMP_WRAPPER
@@ -4630,7 +4630,7 @@ wrap_richcmpfunc(PyObject *self, PyObject *args, void *wrapped, int op)
static PyObject * \
richcmp_##NAME(PyObject *self, PyObject *args, void *wrapped) \
{ \
- return wrap_richcmpfunc(self, args, wrapped, OP); \
+ return wrap_richcmpfunc(self, args, wrapped, OP); \
}
RICHCMP_WRAPPER(lt, Py_LT)
@@ -4643,164 +4643,164 @@ RICHCMP_WRAPPER(ge, Py_GE)
static PyObject *
wrap_next(PyObject *self, PyObject *args, void *wrapped)
{
- unaryfunc func = (unaryfunc)wrapped;
- PyObject *res;
+ unaryfunc func = (unaryfunc)wrapped;
+ PyObject *res;
- if (!check_num_args(args, 0))
- return NULL;
- res = (*func)(self);
- if (res == NULL && !PyErr_Occurred())
- PyErr_SetNone(PyExc_StopIteration);
- return res;
+ if (!check_num_args(args, 0))
+ return NULL;
+ res = (*func)(self);
+ if (res == NULL && !PyErr_Occurred())
+ PyErr_SetNone(PyExc_StopIteration);
+ return res;
}
static PyObject *
wrap_descr_get(PyObject *self, PyObject *args, void *wrapped)
{
- descrgetfunc func = (descrgetfunc)wrapped;
- PyObject *obj;
- PyObject *type = NULL;
+ descrgetfunc func = (descrgetfunc)wrapped;
+ PyObject *obj;
+ PyObject *type = NULL;
- if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
- return NULL;
- if (obj == Py_None)
- obj = NULL;
- if (type == Py_None)
- type = NULL;
- if (type == NULL &&obj == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "__get__(None, None) is invalid");
- return NULL;
- }
- return (*func)(self, obj, type);
+ if (!PyArg_UnpackTuple(args, "", 1, 2, &obj, &type))
+ return NULL;
+ if (obj == Py_None)
+ obj = NULL;
+ if (type == Py_None)
+ type = NULL;
+ if (type == NULL &&obj == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "__get__(None, None) is invalid");
+ return NULL;
+ }
+ return (*func)(self, obj, type);
}
static PyObject *
wrap_descr_set(PyObject *self, PyObject *args, void *wrapped)
{
- descrsetfunc func = (descrsetfunc)wrapped;
- PyObject *obj, *value;
- int ret;
+ descrsetfunc func = (descrsetfunc)wrapped;
+ PyObject *obj, *value;
+ int ret;
- if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
- return NULL;
- ret = (*func)(self, obj, value);
- if (ret < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_UnpackTuple(args, "", 2, 2, &obj, &value))
+ return NULL;
+ ret = (*func)(self, obj, value);
+ if (ret < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_descr_delete(PyObject *self, PyObject *args, void *wrapped)
{
- descrsetfunc func = (descrsetfunc)wrapped;
- PyObject *obj;
- int ret;
+ descrsetfunc func = (descrsetfunc)wrapped;
+ PyObject *obj;
+ int ret;
- if (!check_num_args(args, 1))
- return NULL;
- obj = PyTuple_GET_ITEM(args, 0);
- ret = (*func)(self, obj, NULL);
- if (ret < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!check_num_args(args, 1))
+ return NULL;
+ obj = PyTuple_GET_ITEM(args, 0);
+ ret = (*func)(self, obj, NULL);
+ if (ret < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
wrap_init(PyObject *self, PyObject *args, void *wrapped, PyObject *kwds)
{
- initproc func = (initproc)wrapped;
+ initproc func = (initproc)wrapped;
- if (func(self, args, kwds) < 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (func(self, args, kwds) < 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
tp_new_wrapper(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyTypeObject *type, *subtype, *staticbase;
- PyObject *arg0, *res;
-
- if (self == NULL || !PyType_Check(self))
- Py_FatalError("__new__() called with non-type 'self'");
- type = (PyTypeObject *)self;
- if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
- PyErr_Format(PyExc_TypeError,
- "%s.__new__(): not enough arguments",
- type->tp_name);
- return NULL;
- }
- arg0 = PyTuple_GET_ITEM(args, 0);
- if (!PyType_Check(arg0)) {
- PyErr_Format(PyExc_TypeError,
- "%s.__new__(X): X is not a type object (%s)",
- type->tp_name,
- Py_TYPE(arg0)->tp_name);
- return NULL;
- }
- subtype = (PyTypeObject *)arg0;
- if (!PyType_IsSubtype(subtype, type)) {
- PyErr_Format(PyExc_TypeError,
- "%s.__new__(%s): %s is not a subtype of %s",
- type->tp_name,
- subtype->tp_name,
- subtype->tp_name,
- type->tp_name);
- return NULL;
- }
-
- /* Check that the use doesn't do something silly and unsafe like
- object.__new__(dict). To do this, we check that the
- most derived base that's not a heap type is this type. */
- staticbase = subtype;
- while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
- staticbase = staticbase->tp_base;
- /* If staticbase is NULL now, it is a really weird type.
- In the spirit of backwards compatibility (?), just shut up. */
- if (staticbase && staticbase->tp_new != type->tp_new) {
- PyErr_Format(PyExc_TypeError,
- "%s.__new__(%s) is not safe, use %s.__new__()",
- type->tp_name,
- subtype->tp_name,
- staticbase == NULL ? "?" : staticbase->tp_name);
- return NULL;
- }
-
- args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
- if (args == NULL)
- return NULL;
- res = type->tp_new(subtype, args, kwds);
- Py_DECREF(args);
- return res;
+ PyTypeObject *type, *subtype, *staticbase;
+ PyObject *arg0, *res;
+
+ if (self == NULL || !PyType_Check(self))
+ Py_FatalError("__new__() called with non-type 'self'");
+ type = (PyTypeObject *)self;
+ if (!PyTuple_Check(args) || PyTuple_GET_SIZE(args) < 1) {
+ PyErr_Format(PyExc_TypeError,
+ "%s.__new__(): not enough arguments",
+ type->tp_name);
+ return NULL;
+ }
+ arg0 = PyTuple_GET_ITEM(args, 0);
+ if (!PyType_Check(arg0)) {
+ PyErr_Format(PyExc_TypeError,
+ "%s.__new__(X): X is not a type object (%s)",
+ type->tp_name,
+ Py_TYPE(arg0)->tp_name);
+ return NULL;
+ }
+ subtype = (PyTypeObject *)arg0;
+ if (!PyType_IsSubtype(subtype, type)) {
+ PyErr_Format(PyExc_TypeError,
+ "%s.__new__(%s): %s is not a subtype of %s",
+ type->tp_name,
+ subtype->tp_name,
+ subtype->tp_name,
+ type->tp_name);
+ return NULL;
+ }
+
+ /* Check that the use doesn't do something silly and unsafe like
+ object.__new__(dict). To do this, we check that the
+ most derived base that's not a heap type is this type. */
+ staticbase = subtype;
+ while (staticbase && (staticbase->tp_flags & Py_TPFLAGS_HEAPTYPE))
+ staticbase = staticbase->tp_base;
+ /* If staticbase is NULL now, it is a really weird type.
+ In the spirit of backwards compatibility (?), just shut up. */
+ if (staticbase && staticbase->tp_new != type->tp_new) {
+ PyErr_Format(PyExc_TypeError,
+ "%s.__new__(%s) is not safe, use %s.__new__()",
+ type->tp_name,
+ subtype->tp_name,
+ staticbase == NULL ? "?" : staticbase->tp_name);
+ return NULL;
+ }
+
+ args = PyTuple_GetSlice(args, 1, PyTuple_GET_SIZE(args));
+ if (args == NULL)
+ return NULL;
+ res = type->tp_new(subtype, args, kwds);
+ Py_DECREF(args);
+ return res;
}
static struct PyMethodDef tp_new_methoddef[] = {
- {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
- PyDoc_STR("T.__new__(S, ...) -> "
- "a new object with type S, a subtype of T")},
- {0}
+ {"__new__", (PyCFunction)tp_new_wrapper, METH_VARARGS|METH_KEYWORDS,
+ PyDoc_STR("T.__new__(S, ...) -> "
+ "a new object with type S, a subtype of T")},
+ {0}
};
static int
add_tp_new_wrapper(PyTypeObject *type)
{
- PyObject *func;
+ PyObject *func;
- if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
- return 0;
- func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
- if (func == NULL)
- return -1;
- if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
- Py_DECREF(func);
- return -1;
- }
- Py_DECREF(func);
- return 0;
+ if (PyDict_GetItemString(type->tp_dict, "__new__") != NULL)
+ return 0;
+ func = PyCFunction_New(tp_new_methoddef, (PyObject *)type);
+ if (func == NULL)
+ return -1;
+ if (PyDict_SetItemString(type->tp_dict, "__new__", func)) {
+ Py_DECREF(func);
+ return -1;
+ }
+ Py_DECREF(func);
+ return 0;
}
/* Slot wrappers that call the corresponding __foo__ slot. See comments
@@ -4810,16 +4810,16 @@ add_tp_new_wrapper(PyTypeObject *type)
static PyObject * \
FUNCNAME(PyObject *self) \
{ \
- static PyObject *cache_str; \
- return call_method(self, OPSTR, &cache_str, "()"); \
+ static PyObject *cache_str; \
+ return call_method(self, OPSTR, &cache_str, "()"); \
}
#define SLOT1(FUNCNAME, OPSTR, ARG1TYPE, ARGCODES) \
static PyObject * \
FUNCNAME(PyObject *self, ARG1TYPE arg1) \
{ \
- static PyObject *cache_str; \
- return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
+ static PyObject *cache_str; \
+ return call_method(self, OPSTR, &cache_str, "(" ARGCODES ")", arg1); \
}
/* Boolean helper for SLOT1BINFULL().
@@ -4827,33 +4827,33 @@ FUNCNAME(PyObject *self, ARG1TYPE arg1) \
static int
method_is_overloaded(PyObject *left, PyObject *right, char *name)
{
- PyObject *a, *b;
- int ok;
+ PyObject *a, *b;
+ int ok;
- b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
- if (b == NULL) {
- PyErr_Clear();
- /* If right doesn't have it, it's not overloaded */
- return 0;
- }
+ b = PyObject_GetAttrString((PyObject *)(Py_TYPE(right)), name);
+ if (b == NULL) {
+ PyErr_Clear();
+ /* If right doesn't have it, it's not overloaded */
+ return 0;
+ }
- a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
- if (a == NULL) {
- PyErr_Clear();
- Py_DECREF(b);
- /* If right has it but left doesn't, it's overloaded */
- return 1;
- }
+ a = PyObject_GetAttrString((PyObject *)(Py_TYPE(left)), name);
+ if (a == NULL) {
+ PyErr_Clear();
+ Py_DECREF(b);
+ /* If right has it but left doesn't, it's overloaded */
+ return 1;
+ }
- ok = PyObject_RichCompareBool(a, b, Py_NE);
- Py_DECREF(a);
- Py_DECREF(b);
- if (ok < 0) {
- PyErr_Clear();
- return 0;
- }
+ ok = PyObject_RichCompareBool(a, b, Py_NE);
+ Py_DECREF(a);
+ Py_DECREF(b);
+ if (ok < 0) {
+ PyErr_Clear();
+ return 0;
+ }
- return ok;
+ return ok;
}
@@ -4861,68 +4861,68 @@ method_is_overloaded(PyObject *left, PyObject *right, char *name)
static PyObject * \
FUNCNAME(PyObject *self, PyObject *other) \
{ \
- static PyObject *cache_str, *rcache_str; \
- int do_other = Py_TYPE(self) != Py_TYPE(other) && \
- Py_TYPE(other)->tp_as_number != NULL && \
- Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
- if (Py_TYPE(self)->tp_as_number != NULL && \
- Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
- PyObject *r; \
- if (do_other && \
- PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
- method_is_overloaded(self, other, ROPSTR)) { \
- r = call_maybe( \
- other, ROPSTR, &rcache_str, "(O)", self); \
- if (r != Py_NotImplemented) \
- return r; \
- Py_DECREF(r); \
- do_other = 0; \
- } \
- r = call_maybe( \
- self, OPSTR, &cache_str, "(O)", other); \
- if (r != Py_NotImplemented || \
- Py_TYPE(other) == Py_TYPE(self)) \
- return r; \
- Py_DECREF(r); \
- } \
- if (do_other) { \
- return call_maybe( \
- other, ROPSTR, &rcache_str, "(O)", self); \
- } \
- Py_INCREF(Py_NotImplemented); \
- return Py_NotImplemented; \
+ static PyObject *cache_str, *rcache_str; \
+ int do_other = Py_TYPE(self) != Py_TYPE(other) && \
+ Py_TYPE(other)->tp_as_number != NULL && \
+ Py_TYPE(other)->tp_as_number->SLOTNAME == TESTFUNC; \
+ if (Py_TYPE(self)->tp_as_number != NULL && \
+ Py_TYPE(self)->tp_as_number->SLOTNAME == TESTFUNC) { \
+ PyObject *r; \
+ if (do_other && \
+ PyType_IsSubtype(Py_TYPE(other), Py_TYPE(self)) && \
+ method_is_overloaded(self, other, ROPSTR)) { \
+ r = call_maybe( \
+ other, ROPSTR, &rcache_str, "(O)", self); \
+ if (r != Py_NotImplemented) \
+ return r; \
+ Py_DECREF(r); \
+ do_other = 0; \
+ } \
+ r = call_maybe( \
+ self, OPSTR, &cache_str, "(O)", other); \
+ if (r != Py_NotImplemented || \
+ Py_TYPE(other) == Py_TYPE(self)) \
+ return r; \
+ Py_DECREF(r); \
+ } \
+ if (do_other) { \
+ return call_maybe( \
+ other, ROPSTR, &rcache_str, "(O)", self); \
+ } \
+ Py_INCREF(Py_NotImplemented); \
+ return Py_NotImplemented; \
}
#define SLOT1BIN(FUNCNAME, SLOTNAME, OPSTR, ROPSTR) \
- SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
+ SLOT1BINFULL(FUNCNAME, FUNCNAME, SLOTNAME, OPSTR, ROPSTR)
#define SLOT2(FUNCNAME, OPSTR, ARG1TYPE, ARG2TYPE, ARGCODES) \
static PyObject * \
FUNCNAME(PyObject *self, ARG1TYPE arg1, ARG2TYPE arg2) \
{ \
- static PyObject *cache_str; \
- return call_method(self, OPSTR, &cache_str, \
- "(" ARGCODES ")", arg1, arg2); \
+ static PyObject *cache_str; \
+ return call_method(self, OPSTR, &cache_str, \
+ "(" ARGCODES ")", arg1, arg2); \
}
static Py_ssize_t
slot_sq_length(PyObject *self)
{
- static PyObject *len_str;
- PyObject *res = call_method(self, "__len__", &len_str, "()");
- Py_ssize_t len;
+ static PyObject *len_str;
+ PyObject *res = call_method(self, "__len__", &len_str, "()");
+ Py_ssize_t len;
- if (res == NULL)
- return -1;
- len = PyInt_AsSsize_t(res);
- Py_DECREF(res);
- if (len < 0) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_ValueError,
- "__len__() should return >= 0");
- return -1;
- }
- return len;
+ if (res == NULL)
+ return -1;
+ len = PyInt_AsSsize_t(res);
+ Py_DECREF(res);
+ if (len < 0) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_ValueError,
+ "__len__() should return >= 0");
+ return -1;
+ }
+ return len;
}
/* Super-optimized version of slot_sq_item.
@@ -4930,131 +4930,131 @@ slot_sq_length(PyObject *self)
static PyObject *
slot_sq_item(PyObject *self, Py_ssize_t i)
{
- static PyObject *getitem_str;
- PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
- descrgetfunc f;
-
- if (getitem_str == NULL) {
- getitem_str = PyString_InternFromString("__getitem__");
- if (getitem_str == NULL)
- return NULL;
- }
- func = _PyType_Lookup(Py_TYPE(self), getitem_str);
- if (func != NULL) {
- if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
- Py_INCREF(func);
- else {
- func = f(func, self, (PyObject *)(Py_TYPE(self)));
- if (func == NULL) {
- return NULL;
- }
- }
- ival = PyInt_FromSsize_t(i);
- if (ival != NULL) {
- args = PyTuple_New(1);
- if (args != NULL) {
- PyTuple_SET_ITEM(args, 0, ival);
- retval = PyObject_Call(func, args, NULL);
- Py_XDECREF(args);
- Py_XDECREF(func);
- return retval;
- }
- }
- }
- else {
- PyErr_SetObject(PyExc_AttributeError, getitem_str);
- }
- Py_XDECREF(args);
- Py_XDECREF(ival);
- Py_XDECREF(func);
- return NULL;
+ static PyObject *getitem_str;
+ PyObject *func, *args = NULL, *ival = NULL, *retval = NULL;
+ descrgetfunc f;
+
+ if (getitem_str == NULL) {
+ getitem_str = PyString_InternFromString("__getitem__");
+ if (getitem_str == NULL)
+ return NULL;
+ }
+ func = _PyType_Lookup(Py_TYPE(self), getitem_str);
+ if (func != NULL) {
+ if ((f = Py_TYPE(func)->tp_descr_get) == NULL)
+ Py_INCREF(func);
+ else {
+ func = f(func, self, (PyObject *)(Py_TYPE(self)));
+ if (func == NULL) {
+ return NULL;
+ }
+ }
+ ival = PyInt_FromSsize_t(i);
+ if (ival != NULL) {
+ args = PyTuple_New(1);
+ if (args != NULL) {
+ PyTuple_SET_ITEM(args, 0, ival);
+ retval = PyObject_Call(func, args, NULL);
+ Py_XDECREF(args);
+ Py_XDECREF(func);
+ return retval;
+ }
+ }
+ }
+ else {
+ PyErr_SetObject(PyExc_AttributeError, getitem_str);
+ }
+ Py_XDECREF(args);
+ Py_XDECREF(ival);
+ Py_XDECREF(func);
+ return NULL;
}
static PyObject*
slot_sq_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j)
{
- static PyObject *getslice_str;
-
- if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
- "use __getitem__", 1) < 0)
- return NULL;
- return call_method(self, "__getslice__", &getslice_str,
- "nn", i, j);
+ static PyObject *getslice_str;
+
+ if (PyErr_WarnPy3k("in 3.x, __getslice__ has been removed; "
+ "use __getitem__", 1) < 0)
+ return NULL;
+ return call_method(self, "__getslice__", &getslice_str,
+ "nn", i, j);
}
static int
slot_sq_ass_item(PyObject *self, Py_ssize_t index, PyObject *value)
{
- PyObject *res;
- static PyObject *delitem_str, *setitem_str;
+ PyObject *res;
+ static PyObject *delitem_str, *setitem_str;
- if (value == NULL)
- res = call_method(self, "__delitem__", &delitem_str,
- "(n)", index);
- else
- res = call_method(self, "__setitem__", &setitem_str,
- "(nO)", index, value);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ if (value == NULL)
+ res = call_method(self, "__delitem__", &delitem_str,
+ "(n)", index);
+ else
+ res = call_method(self, "__setitem__", &setitem_str,
+ "(nO)", index, value);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
slot_sq_ass_slice(PyObject *self, Py_ssize_t i, Py_ssize_t j, PyObject *value)
{
- PyObject *res;
- static PyObject *delslice_str, *setslice_str;
-
- if (value == NULL) {
- if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
- "use __delitem__", 1) < 0)
- return -1;
- res = call_method(self, "__delslice__", &delslice_str,
- "(nn)", i, j);
- }
- else {
- if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
- "use __setitem__", 1) < 0)
- return -1;
- res = call_method(self, "__setslice__", &setslice_str,
- "(nnO)", i, j, value);
- }
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ PyObject *res;
+ static PyObject *delslice_str, *setslice_str;
+
+ if (value == NULL) {
+ if (PyErr_WarnPy3k("in 3.x, __delslice__ has been removed; "
+ "use __delitem__", 1) < 0)
+ return -1;
+ res = call_method(self, "__delslice__", &delslice_str,
+ "(nn)", i, j);
+ }
+ else {
+ if (PyErr_WarnPy3k("in 3.x, __setslice__ has been removed; "
+ "use __setitem__", 1) < 0)
+ return -1;
+ res = call_method(self, "__setslice__", &setslice_str,
+ "(nnO)", i, j, value);
+ }
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
slot_sq_contains(PyObject *self, PyObject *value)
{
- PyObject *func, *res, *args;
- int result = -1;
-
- static PyObject *contains_str;
-
- func = lookup_maybe(self, "__contains__", &contains_str);
- if (func != NULL) {
- args = PyTuple_Pack(1, value);
- if (args == NULL)
- res = NULL;
- else {
- res = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- }
- Py_DECREF(func);
- if (res != NULL) {
- result = PyObject_IsTrue(res);
- Py_DECREF(res);
- }
- }
- else if (! PyErr_Occurred()) {
- /* Possible results: -1 and 1 */
- result = (int)_PySequence_IterSearch(self, value,
- PY_ITERSEARCH_CONTAINS);
- }
- return result;
+ PyObject *func, *res, *args;
+ int result = -1;
+
+ static PyObject *contains_str;
+
+ func = lookup_maybe(self, "__contains__", &contains_str);
+ if (func != NULL) {
+ args = PyTuple_Pack(1, value);
+ if (args == NULL)
+ res = NULL;
+ else {
+ res = PyObject_Call(func, args, NULL);
+ Py_DECREF(args);
+ }
+ Py_DECREF(func);
+ if (res != NULL) {
+ result = PyObject_IsTrue(res);
+ Py_DECREF(res);
+ }
+ }
+ else if (! PyErr_Occurred()) {
+ /* Possible results: -1 and 1 */
+ result = (int)_PySequence_IterSearch(self, value,
+ PY_ITERSEARCH_CONTAINS);
+ }
+ return result;
}
#define slot_mp_length slot_sq_length
@@ -5064,19 +5064,19 @@ SLOT1(slot_mp_subscript, "__getitem__", PyObject *, "O")
static int
slot_mp_ass_subscript(PyObject *self, PyObject *key, PyObject *value)
{
- PyObject *res;
- static PyObject *delitem_str, *setitem_str;
+ PyObject *res;
+ static PyObject *delitem_str, *setitem_str;
- if (value == NULL)
- res = call_method(self, "__delitem__", &delitem_str,
- "(O)", key);
- else
- res = call_method(self, "__setitem__", &setitem_str,
- "(OO)", key, value);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ if (value == NULL)
+ res = call_method(self, "__delitem__", &delitem_str,
+ "(O)", key);
+ else
+ res = call_method(self, "__setitem__", &setitem_str,
+ "(OO)", key, value);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
SLOT1BIN(slot_nb_add, nb_add, "__add__", "__radd__")
@@ -5089,25 +5089,25 @@ SLOT1BIN(slot_nb_divmod, nb_divmod, "__divmod__", "__rdivmod__")
static PyObject *slot_nb_power(PyObject *, PyObject *, PyObject *);
SLOT1BINFULL(slot_nb_power_binary, slot_nb_power,
- nb_power, "__pow__", "__rpow__")
+ nb_power, "__pow__", "__rpow__")
static PyObject *
slot_nb_power(PyObject *self, PyObject *other, PyObject *modulus)
{
- static PyObject *pow_str;
+ static PyObject *pow_str;
- if (modulus == Py_None)
- return slot_nb_power_binary(self, other);
- /* Three-arg power doesn't use __rpow__. But ternary_op
- can call this when the second argument's type uses
- slot_nb_power, so check before calling self.__pow__. */
- if (Py_TYPE(self)->tp_as_number != NULL &&
- Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
- return call_method(self, "__pow__", &pow_str,
- "(OO)", other, modulus);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ if (modulus == Py_None)
+ return slot_nb_power_binary(self, other);
+ /* Three-arg power doesn't use __rpow__. But ternary_op
+ can call this when the second argument's type uses
+ slot_nb_power, so check before calling self.__pow__. */
+ if (Py_TYPE(self)->tp_as_number != NULL &&
+ Py_TYPE(self)->tp_as_number->nb_power == slot_nb_power) {
+ return call_method(self, "__pow__", &pow_str,
+ "(OO)", other, modulus);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
SLOT0(slot_nb_negative, "__neg__")
@@ -5117,49 +5117,49 @@ SLOT0(slot_nb_absolute, "__abs__")
static int
slot_nb_nonzero(PyObject *self)
{
- PyObject *func, *args;
- static PyObject *nonzero_str, *len_str;
- int result = -1;
- int using_len = 0;
-
- func = lookup_maybe(self, "__nonzero__", &nonzero_str);
- if (func == NULL) {
- if (PyErr_Occurred())
- return -1;
- func = lookup_maybe(self, "__len__", &len_str);
- if (func == NULL)
- return PyErr_Occurred() ? -1 : 1;
- using_len = 1;
- }
- args = PyTuple_New(0);
- if (args != NULL) {
- PyObject *temp = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- if (temp != NULL) {
- if (PyInt_CheckExact(temp) || PyBool_Check(temp))
- result = PyObject_IsTrue(temp);
- else {
- PyErr_Format(PyExc_TypeError,
- "%s should return "
- "bool or int, returned %s",
- (using_len ? "__len__"
- : "__nonzero__"),
- temp->ob_type->tp_name);
- result = -1;
- }
- Py_DECREF(temp);
- }
- }
- Py_DECREF(func);
- return result;
+ PyObject *func, *args;
+ static PyObject *nonzero_str, *len_str;
+ int result = -1;
+ int using_len = 0;
+
+ func = lookup_maybe(self, "__nonzero__", &nonzero_str);
+ if (func == NULL) {
+ if (PyErr_Occurred())
+ return -1;
+ func = lookup_maybe(self, "__len__", &len_str);
+ if (func == NULL)
+ return PyErr_Occurred() ? -1 : 1;
+ using_len = 1;
+ }
+ args = PyTuple_New(0);
+ if (args != NULL) {
+ PyObject *temp = PyObject_Call(func, args, NULL);
+ Py_DECREF(args);
+ if (temp != NULL) {
+ if (PyInt_CheckExact(temp) || PyBool_Check(temp))
+ result = PyObject_IsTrue(temp);
+ else {
+ PyErr_Format(PyExc_TypeError,
+ "%s should return "
+ "bool or int, returned %s",
+ (using_len ? "__len__"
+ : "__nonzero__"),
+ temp->ob_type->tp_name);
+ result = -1;
+ }
+ Py_DECREF(temp);
+ }
+ }
+ Py_DECREF(func);
+ return result;
}
static PyObject *
slot_nb_index(PyObject *self)
{
- static PyObject *index_str;
- return call_method(self, "__index__", &index_str, "()");
+ static PyObject *index_str;
+ return call_method(self, "__index__", &index_str, "()");
}
@@ -5173,59 +5173,59 @@ SLOT1BIN(slot_nb_or, nb_or, "__or__", "__ror__")
static int
slot_nb_coerce(PyObject **a, PyObject **b)
{
- static PyObject *coerce_str;
- PyObject *self = *a, *other = *b;
-
- if (self->ob_type->tp_as_number != NULL &&
- self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
- PyObject *r;
- r = call_maybe(
- self, "__coerce__", &coerce_str, "(O)", other);
- if (r == NULL)
- return -1;
- if (r == Py_NotImplemented) {
- Py_DECREF(r);
- }
- else {
- if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
- PyErr_SetString(PyExc_TypeError,
- "__coerce__ didn't return a 2-tuple");
- Py_DECREF(r);
- return -1;
- }
- *a = PyTuple_GET_ITEM(r, 0);
- Py_INCREF(*a);
- *b = PyTuple_GET_ITEM(r, 1);
- Py_INCREF(*b);
- Py_DECREF(r);
- return 0;
- }
- }
- if (other->ob_type->tp_as_number != NULL &&
- other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
- PyObject *r;
- r = call_maybe(
- other, "__coerce__", &coerce_str, "(O)", self);
- if (r == NULL)
- return -1;
- if (r == Py_NotImplemented) {
- Py_DECREF(r);
- return 1;
- }
- if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
- PyErr_SetString(PyExc_TypeError,
- "__coerce__ didn't return a 2-tuple");
- Py_DECREF(r);
- return -1;
- }
- *a = PyTuple_GET_ITEM(r, 1);
- Py_INCREF(*a);
- *b = PyTuple_GET_ITEM(r, 0);
- Py_INCREF(*b);
- Py_DECREF(r);
- return 0;
- }
- return 1;
+ static PyObject *coerce_str;
+ PyObject *self = *a, *other = *b;
+
+ if (self->ob_type->tp_as_number != NULL &&
+ self->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
+ PyObject *r;
+ r = call_maybe(
+ self, "__coerce__", &coerce_str, "(O)", other);
+ if (r == NULL)
+ return -1;
+ if (r == Py_NotImplemented) {
+ Py_DECREF(r);
+ }
+ else {
+ if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "__coerce__ didn't return a 2-tuple");
+ Py_DECREF(r);
+ return -1;
+ }
+ *a = PyTuple_GET_ITEM(r, 0);
+ Py_INCREF(*a);
+ *b = PyTuple_GET_ITEM(r, 1);
+ Py_INCREF(*b);
+ Py_DECREF(r);
+ return 0;
+ }
+ }
+ if (other->ob_type->tp_as_number != NULL &&
+ other->ob_type->tp_as_number->nb_coerce == slot_nb_coerce) {
+ PyObject *r;
+ r = call_maybe(
+ other, "__coerce__", &coerce_str, "(O)", self);
+ if (r == NULL)
+ return -1;
+ if (r == Py_NotImplemented) {
+ Py_DECREF(r);
+ return 1;
+ }
+ if (!PyTuple_Check(r) || PyTuple_GET_SIZE(r) != 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "__coerce__ didn't return a 2-tuple");
+ Py_DECREF(r);
+ return -1;
+ }
+ *a = PyTuple_GET_ITEM(r, 1);
+ Py_INCREF(*a);
+ *b = PyTuple_GET_ITEM(r, 0);
+ Py_INCREF(*b);
+ Py_DECREF(r);
+ return 0;
+ }
+ return 1;
}
SLOT0(slot_nb_int, "__int__")
@@ -5239,11 +5239,11 @@ SLOT1(slot_nb_inplace_multiply, "__imul__", PyObject *, "O")
SLOT1(slot_nb_inplace_divide, "__idiv__", PyObject *, "O")
SLOT1(slot_nb_inplace_remainder, "__imod__", PyObject *, "O")
/* Can't use SLOT1 here, because nb_inplace_power is ternary */
-static PyObject *
-slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
-{
- static PyObject *cache_str;
- return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
+static PyObject *
+slot_nb_inplace_power(PyObject *self, PyObject * arg1, PyObject *arg2)
+{
+ static PyObject *cache_str;
+ return call_method(self, "__ipow__", &cache_str, "(" "O" ")", arg1);
}
SLOT1(slot_nb_inplace_lshift, "__ilshift__", PyObject *, "O")
SLOT1(slot_nb_inplace_rshift, "__irshift__", PyObject *, "O")
@@ -5251,7 +5251,7 @@ SLOT1(slot_nb_inplace_and, "__iand__", PyObject *, "O")
SLOT1(slot_nb_inplace_xor, "__ixor__", PyObject *, "O")
SLOT1(slot_nb_inplace_or, "__ior__", PyObject *, "O")
SLOT1BIN(slot_nb_floor_divide, nb_floor_divide,
- "__floordiv__", "__rfloordiv__")
+ "__floordiv__", "__rfloordiv__")
SLOT1BIN(slot_nb_true_divide, nb_true_divide, "__truediv__", "__rtruediv__")
SLOT1(slot_nb_inplace_floor_divide, "__ifloordiv__", PyObject *, "O")
SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
@@ -5259,148 +5259,148 @@ SLOT1(slot_nb_inplace_true_divide, "__itruediv__", PyObject *, "O")
static int
half_compare(PyObject *self, PyObject *other)
{
- PyObject *func, *args, *res;
- static PyObject *cmp_str;
- Py_ssize_t c;
-
- func = lookup_method(self, "__cmp__", &cmp_str);
- if (func == NULL) {
- PyErr_Clear();
- }
- else {
- args = PyTuple_Pack(1, other);
- if (args == NULL)
- res = NULL;
- else {
- res = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- }
- Py_DECREF(func);
- if (res != Py_NotImplemented) {
- if (res == NULL)
- return -2;
- c = PyInt_AsLong(res);
- Py_DECREF(res);
- if (c == -1 && PyErr_Occurred())
- return -2;
- return (c < 0) ? -1 : (c > 0) ? 1 : 0;
- }
- Py_DECREF(res);
- }
- return 2;
+ PyObject *func, *args, *res;
+ static PyObject *cmp_str;
+ Py_ssize_t c;
+
+ func = lookup_method(self, "__cmp__", &cmp_str);
+ if (func == NULL) {
+ PyErr_Clear();
+ }
+ else {
+ args = PyTuple_Pack(1, other);
+ if (args == NULL)
+ res = NULL;
+ else {
+ res = PyObject_Call(func, args, NULL);
+ Py_DECREF(args);
+ }
+ Py_DECREF(func);
+ if (res != Py_NotImplemented) {
+ if (res == NULL)
+ return -2;
+ c = PyInt_AsLong(res);
+ Py_DECREF(res);
+ if (c == -1 && PyErr_Occurred())
+ return -2;
+ return (c < 0) ? -1 : (c > 0) ? 1 : 0;
+ }
+ Py_DECREF(res);
+ }
+ return 2;
}
/* This slot is published for the benefit of try_3way_compare in object.c */
int
_PyObject_SlotCompare(PyObject *self, PyObject *other)
{
- int c;
+ int c;
- if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
- c = half_compare(self, other);
- if (c <= 1)
- return c;
- }
- if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
- c = half_compare(other, self);
- if (c < -1)
- return -2;
- if (c <= 1)
- return -c;
- }
- return (void *)self < (void *)other ? -1 :
- (void *)self > (void *)other ? 1 : 0;
+ if (Py_TYPE(self)->tp_compare == _PyObject_SlotCompare) {
+ c = half_compare(self, other);
+ if (c <= 1)
+ return c;
+ }
+ if (Py_TYPE(other)->tp_compare == _PyObject_SlotCompare) {
+ c = half_compare(other, self);
+ if (c < -1)
+ return -2;
+ if (c <= 1)
+ return -c;
+ }
+ return (void *)self < (void *)other ? -1 :
+ (void *)self > (void *)other ? 1 : 0;
}
static PyObject *
slot_tp_repr(PyObject *self)
{
- PyObject *func, *res;
- static PyObject *repr_str;
+ PyObject *func, *res;
+ static PyObject *repr_str;
- func = lookup_method(self, "__repr__", &repr_str);
- if (func != NULL) {
- res = PyEval_CallObject(func, NULL);
- Py_DECREF(func);
- return res;
- }
- PyErr_Clear();
- return PyString_FromFormat("<%s object at %p>",
- Py_TYPE(self)->tp_name, self);
+ func = lookup_method(self, "__repr__", &repr_str);
+ if (func != NULL) {
+ res = PyEval_CallObject(func, NULL);
+ Py_DECREF(func);
+ return res;
+ }
+ PyErr_Clear();
+ return PyString_FromFormat("<%s object at %p>",
+ Py_TYPE(self)->tp_name, self);
}
static PyObject *
slot_tp_str(PyObject *self)
{
- PyObject *func, *res;
- static PyObject *str_str;
+ PyObject *func, *res;
+ static PyObject *str_str;
- func = lookup_method(self, "__str__", &str_str);
- if (func != NULL) {
- res = PyEval_CallObject(func, NULL);
- Py_DECREF(func);
- return res;
- }
- else {
- PyErr_Clear();
- return slot_tp_repr(self);
- }
+ func = lookup_method(self, "__str__", &str_str);
+ if (func != NULL) {
+ res = PyEval_CallObject(func, NULL);
+ Py_DECREF(func);
+ return res;
+ }
+ else {
+ PyErr_Clear();
+ return slot_tp_repr(self);
+ }
}
static long
slot_tp_hash(PyObject *self)
{
- PyObject *func;
- static PyObject *hash_str, *eq_str, *cmp_str;
- long h;
-
- func = lookup_method(self, "__hash__", &hash_str);
-
- if (func != NULL && func != Py_None) {
- PyObject *res = PyEval_CallObject(func, NULL);
- Py_DECREF(func);
- if (res == NULL)
- return -1;
- if (PyLong_Check(res))
- h = PyLong_Type.tp_hash(res);
- else
- h = PyInt_AsLong(res);
- Py_DECREF(res);
- }
- else {
- Py_XDECREF(func); /* may be None */
- PyErr_Clear();
- func = lookup_method(self, "__eq__", &eq_str);
- if (func == NULL) {
- PyErr_Clear();
- func = lookup_method(self, "__cmp__", &cmp_str);
- }
- if (func != NULL) {
- Py_DECREF(func);
- return PyObject_HashNotImplemented(self);
- }
- PyErr_Clear();
- h = _Py_HashPointer((void *)self);
- }
- if (h == -1 && !PyErr_Occurred())
- h = -2;
- return h;
+ PyObject *func;
+ static PyObject *hash_str, *eq_str, *cmp_str;
+ long h;
+
+ func = lookup_method(self, "__hash__", &hash_str);
+
+ if (func != NULL && func != Py_None) {
+ PyObject *res = PyEval_CallObject(func, NULL);
+ Py_DECREF(func);
+ if (res == NULL)
+ return -1;
+ if (PyLong_Check(res))
+ h = PyLong_Type.tp_hash(res);
+ else
+ h = PyInt_AsLong(res);
+ Py_DECREF(res);
+ }
+ else {
+ Py_XDECREF(func); /* may be None */
+ PyErr_Clear();
+ func = lookup_method(self, "__eq__", &eq_str);
+ if (func == NULL) {
+ PyErr_Clear();
+ func = lookup_method(self, "__cmp__", &cmp_str);
+ }
+ if (func != NULL) {
+ Py_DECREF(func);
+ return PyObject_HashNotImplemented(self);
+ }
+ PyErr_Clear();
+ h = _Py_HashPointer((void *)self);
+ }
+ if (h == -1 && !PyErr_Occurred())
+ h = -2;
+ return h;
}
static PyObject *
slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
{
- static PyObject *call_str;
- PyObject *meth = lookup_method(self, "__call__", &call_str);
- PyObject *res;
+ static PyObject *call_str;
+ PyObject *meth = lookup_method(self, "__call__", &call_str);
+ PyObject *res;
- if (meth == NULL)
- return NULL;
+ if (meth == NULL)
+ return NULL;
- res = PyObject_Call(meth, args, kwds);
+ res = PyObject_Call(meth, args, kwds);
- Py_DECREF(meth);
- return res;
+ Py_DECREF(meth);
+ return res;
}
/* There are two slot dispatch functions for tp_getattro.
@@ -5417,100 +5417,100 @@ slot_tp_call(PyObject *self, PyObject *args, PyObject *kwds)
static PyObject *
slot_tp_getattro(PyObject *self, PyObject *name)
{
- static PyObject *getattribute_str = NULL;
- return call_method(self, "__getattribute__", &getattribute_str,
- "(O)", name);
+ static PyObject *getattribute_str = NULL;
+ return call_method(self, "__getattribute__", &getattribute_str,
+ "(O)", name);
}
static PyObject *
call_attribute(PyObject *self, PyObject *attr, PyObject *name)
{
- PyObject *res, *descr = NULL;
- descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
+ PyObject *res, *descr = NULL;
+ descrgetfunc f = Py_TYPE(attr)->tp_descr_get;
- if (f != NULL) {
- descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
- if (descr == NULL)
- return NULL;
- else
- attr = descr;
- }
- res = PyObject_CallFunctionObjArgs(attr, name, NULL);
- Py_XDECREF(descr);
- return res;
+ if (f != NULL) {
+ descr = f(attr, self, (PyObject *)(Py_TYPE(self)));
+ if (descr == NULL)
+ return NULL;
+ else
+ attr = descr;
+ }
+ res = PyObject_CallFunctionObjArgs(attr, name, NULL);
+ Py_XDECREF(descr);
+ return res;
}
static PyObject *
slot_tp_getattr_hook(PyObject *self, PyObject *name)
{
- PyTypeObject *tp = Py_TYPE(self);
- PyObject *getattr, *getattribute, *res;
- static PyObject *getattribute_str = NULL;
- static PyObject *getattr_str = NULL;
-
- if (getattr_str == NULL) {
- getattr_str = PyString_InternFromString("__getattr__");
- if (getattr_str == NULL)
- return NULL;
- }
- if (getattribute_str == NULL) {
- getattribute_str =
- PyString_InternFromString("__getattribute__");
- if (getattribute_str == NULL)
- return NULL;
- }
- /* speed hack: we could use lookup_maybe, but that would resolve the
- method fully for each attribute lookup for classes with
- __getattr__, even when the attribute is present. So we use
- _PyType_Lookup and create the method only when needed, with
- call_attribute. */
- getattr = _PyType_Lookup(tp, getattr_str);
- if (getattr == NULL) {
- /* No __getattr__ hook: use a simpler dispatcher */
- tp->tp_getattro = slot_tp_getattro;
- return slot_tp_getattro(self, name);
- }
- Py_INCREF(getattr);
- /* speed hack: we could use lookup_maybe, but that would resolve the
- method fully for each attribute lookup for classes with
- __getattr__, even when self has the default __getattribute__
- method. So we use _PyType_Lookup and create the method only when
- needed, with call_attribute. */
- getattribute = _PyType_Lookup(tp, getattribute_str);
- if (getattribute == NULL ||
- (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
- ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
- (void *)PyObject_GenericGetAttr))
- res = PyObject_GenericGetAttr(self, name);
- else {
- Py_INCREF(getattribute);
- res = call_attribute(self, getattribute, name);
- Py_DECREF(getattribute);
- }
- if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
- PyErr_Clear();
- res = call_attribute(self, getattr, name);
- }
- Py_DECREF(getattr);
- return res;
+ PyTypeObject *tp = Py_TYPE(self);
+ PyObject *getattr, *getattribute, *res;
+ static PyObject *getattribute_str = NULL;
+ static PyObject *getattr_str = NULL;
+
+ if (getattr_str == NULL) {
+ getattr_str = PyString_InternFromString("__getattr__");
+ if (getattr_str == NULL)
+ return NULL;
+ }
+ if (getattribute_str == NULL) {
+ getattribute_str =
+ PyString_InternFromString("__getattribute__");
+ if (getattribute_str == NULL)
+ return NULL;
+ }
+ /* speed hack: we could use lookup_maybe, but that would resolve the
+ method fully for each attribute lookup for classes with
+ __getattr__, even when the attribute is present. So we use
+ _PyType_Lookup and create the method only when needed, with
+ call_attribute. */
+ getattr = _PyType_Lookup(tp, getattr_str);
+ if (getattr == NULL) {
+ /* No __getattr__ hook: use a simpler dispatcher */
+ tp->tp_getattro = slot_tp_getattro;
+ return slot_tp_getattro(self, name);
+ }
+ Py_INCREF(getattr);
+ /* speed hack: we could use lookup_maybe, but that would resolve the
+ method fully for each attribute lookup for classes with
+ __getattr__, even when self has the default __getattribute__
+ method. So we use _PyType_Lookup and create the method only when
+ needed, with call_attribute. */
+ getattribute = _PyType_Lookup(tp, getattribute_str);
+ if (getattribute == NULL ||
+ (Py_TYPE(getattribute) == &PyWrapperDescr_Type &&
+ ((PyWrapperDescrObject *)getattribute)->d_wrapped ==
+ (void *)PyObject_GenericGetAttr))
+ res = PyObject_GenericGetAttr(self, name);
+ else {
+ Py_INCREF(getattribute);
+ res = call_attribute(self, getattribute, name);
+ Py_DECREF(getattribute);
+ }
+ if (res == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ PyErr_Clear();
+ res = call_attribute(self, getattr, name);
+ }
+ Py_DECREF(getattr);
+ return res;
}
static int
slot_tp_setattro(PyObject *self, PyObject *name, PyObject *value)
{
- PyObject *res;
- static PyObject *delattr_str, *setattr_str;
+ PyObject *res;
+ static PyObject *delattr_str, *setattr_str;
- if (value == NULL)
- res = call_method(self, "__delattr__", &delattr_str,
- "(O)", name);
- else
- res = call_method(self, "__setattr__", &setattr_str,
- "(OO)", name, value);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ if (value == NULL)
+ res = call_method(self, "__delattr__", &delattr_str,
+ "(O)", name);
+ else
+ res = call_method(self, "__setattr__", &setattr_str,
+ "(OO)", name, value);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static char *name_op[] = {
@@ -5525,244 +5525,244 @@ static char *name_op[] = {
static PyObject *
half_richcompare(PyObject *self, PyObject *other, int op)
{
- PyObject *func, *args, *res;
- static PyObject *op_str[6];
-
- func = lookup_method(self, name_op[op], &op_str[op]);
- if (func == NULL) {
- PyErr_Clear();
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
- }
- args = PyTuple_Pack(1, other);
- if (args == NULL)
- res = NULL;
- else {
- res = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- }
- Py_DECREF(func);
- return res;
+ PyObject *func, *args, *res;
+ static PyObject *op_str[6];
+
+ func = lookup_method(self, name_op[op], &op_str[op]);
+ if (func == NULL) {
+ PyErr_Clear();
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
+ }
+ args = PyTuple_Pack(1, other);
+ if (args == NULL)
+ res = NULL;
+ else {
+ res = PyObject_Call(func, args, NULL);
+ Py_DECREF(args);
+ }
+ Py_DECREF(func);
+ return res;
}
static PyObject *
slot_tp_richcompare(PyObject *self, PyObject *other, int op)
{
- PyObject *res;
-
- if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
- res = half_richcompare(self, other, op);
- if (res != Py_NotImplemented)
- return res;
- Py_DECREF(res);
- }
- if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
- res = half_richcompare(other, self, _Py_SwappedOp[op]);
- if (res != Py_NotImplemented) {
- return res;
- }
- Py_DECREF(res);
- }
- Py_INCREF(Py_NotImplemented);
- return Py_NotImplemented;
+ PyObject *res;
+
+ if (Py_TYPE(self)->tp_richcompare == slot_tp_richcompare) {
+ res = half_richcompare(self, other, op);
+ if (res != Py_NotImplemented)
+ return res;
+ Py_DECREF(res);
+ }
+ if (Py_TYPE(other)->tp_richcompare == slot_tp_richcompare) {
+ res = half_richcompare(other, self, _Py_SwappedOp[op]);
+ if (res != Py_NotImplemented) {
+ return res;
+ }
+ Py_DECREF(res);
+ }
+ Py_INCREF(Py_NotImplemented);
+ return Py_NotImplemented;
}
static PyObject *
slot_tp_iter(PyObject *self)
{
- PyObject *func, *res;
- static PyObject *iter_str, *getitem_str;
-
- func = lookup_method(self, "__iter__", &iter_str);
- if (func != NULL) {
- PyObject *args;
- args = res = PyTuple_New(0);
- if (args != NULL) {
- res = PyObject_Call(func, args, NULL);
- Py_DECREF(args);
- }
- Py_DECREF(func);
- return res;
- }
- PyErr_Clear();
- func = lookup_method(self, "__getitem__", &getitem_str);
- if (func == NULL) {
- PyErr_Format(PyExc_TypeError,
- "'%.200s' object is not iterable",
- Py_TYPE(self)->tp_name);
- return NULL;
- }
- Py_DECREF(func);
- return PySeqIter_New(self);
+ PyObject *func, *res;
+ static PyObject *iter_str, *getitem_str;
+
+ func = lookup_method(self, "__iter__", &iter_str);
+ if (func != NULL) {
+ PyObject *args;
+ args = res = PyTuple_New(0);
+ if (args != NULL) {
+ res = PyObject_Call(func, args, NULL);
+ Py_DECREF(args);
+ }
+ Py_DECREF(func);
+ return res;
+ }
+ PyErr_Clear();
+ func = lookup_method(self, "__getitem__", &getitem_str);
+ if (func == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "'%.200s' object is not iterable",
+ Py_TYPE(self)->tp_name);
+ return NULL;
+ }
+ Py_DECREF(func);
+ return PySeqIter_New(self);
}
static PyObject *
slot_tp_iternext(PyObject *self)
{
- static PyObject *next_str;
- return call_method(self, "next", &next_str, "()");
+ static PyObject *next_str;
+ return call_method(self, "next", &next_str, "()");
}
static PyObject *
slot_tp_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
- PyTypeObject *tp = Py_TYPE(self);
- PyObject *get;
- static PyObject *get_str = NULL;
-
- if (get_str == NULL) {
- get_str = PyString_InternFromString("__get__");
- if (get_str == NULL)
- return NULL;
- }
- get = _PyType_Lookup(tp, get_str);
- if (get == NULL) {
- /* Avoid further slowdowns */
- if (tp->tp_descr_get == slot_tp_descr_get)
- tp->tp_descr_get = NULL;
- Py_INCREF(self);
- return self;
- }
- if (obj == NULL)
- obj = Py_None;
- if (type == NULL)
- type = Py_None;
- return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
+ PyTypeObject *tp = Py_TYPE(self);
+ PyObject *get;
+ static PyObject *get_str = NULL;
+
+ if (get_str == NULL) {
+ get_str = PyString_InternFromString("__get__");
+ if (get_str == NULL)
+ return NULL;
+ }
+ get = _PyType_Lookup(tp, get_str);
+ if (get == NULL) {
+ /* Avoid further slowdowns */
+ if (tp->tp_descr_get == slot_tp_descr_get)
+ tp->tp_descr_get = NULL;
+ Py_INCREF(self);
+ return self;
+ }
+ if (obj == NULL)
+ obj = Py_None;
+ if (type == NULL)
+ type = Py_None;
+ return PyObject_CallFunctionObjArgs(get, self, obj, type, NULL);
}
static int
slot_tp_descr_set(PyObject *self, PyObject *target, PyObject *value)
{
- PyObject *res;
- static PyObject *del_str, *set_str;
+ PyObject *res;
+ static PyObject *del_str, *set_str;
- if (value == NULL)
- res = call_method(self, "__delete__", &del_str,
- "(O)", target);
- else
- res = call_method(self, "__set__", &set_str,
- "(OO)", target, value);
- if (res == NULL)
- return -1;
- Py_DECREF(res);
- return 0;
+ if (value == NULL)
+ res = call_method(self, "__delete__", &del_str,
+ "(O)", target);
+ else
+ res = call_method(self, "__set__", &set_str,
+ "(OO)", target, value);
+ if (res == NULL)
+ return -1;
+ Py_DECREF(res);
+ return 0;
}
static int
slot_tp_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- static PyObject *init_str;
- PyObject *meth = lookup_method(self, "__init__", &init_str);
- PyObject *res;
-
- if (meth == NULL)
- return -1;
- res = PyObject_Call(meth, args, kwds);
- Py_DECREF(meth);
- if (res == NULL)
- return -1;
- if (res != Py_None) {
- PyErr_Format(PyExc_TypeError,
- "__init__() should return None, not '%.200s'",
- Py_TYPE(res)->tp_name);
- Py_DECREF(res);
- return -1;
- }
- Py_DECREF(res);
- return 0;
+ static PyObject *init_str;
+ PyObject *meth = lookup_method(self, "__init__", &init_str);
+ PyObject *res;
+
+ if (meth == NULL)
+ return -1;
+ res = PyObject_Call(meth, args, kwds);
+ Py_DECREF(meth);
+ if (res == NULL)
+ return -1;
+ if (res != Py_None) {
+ PyErr_Format(PyExc_TypeError,
+ "__init__() should return None, not '%.200s'",
+ Py_TYPE(res)->tp_name);
+ Py_DECREF(res);
+ return -1;
+ }
+ Py_DECREF(res);
+ return 0;
}
static PyObject *
slot_tp_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
- static PyObject *new_str;
- PyObject *func;
- PyObject *newargs, *x;
- Py_ssize_t i, n;
-
- if (new_str == NULL) {
- new_str = PyString_InternFromString("__new__");
- if (new_str == NULL)
- return NULL;
- }
- func = PyObject_GetAttr((PyObject *)type, new_str);
- if (func == NULL)
- return NULL;
- assert(PyTuple_Check(args));
- n = PyTuple_GET_SIZE(args);
- newargs = PyTuple_New(n+1);
- if (newargs == NULL)
- return NULL;
- Py_INCREF(type);
- PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
- for (i = 0; i < n; i++) {
- x = PyTuple_GET_ITEM(args, i);
- Py_INCREF(x);
- PyTuple_SET_ITEM(newargs, i+1, x);
- }
- x = PyObject_Call(func, newargs, kwds);
- Py_DECREF(newargs);
- Py_DECREF(func);
- return x;
+ static PyObject *new_str;
+ PyObject *func;
+ PyObject *newargs, *x;
+ Py_ssize_t i, n;
+
+ if (new_str == NULL) {
+ new_str = PyString_InternFromString("__new__");
+ if (new_str == NULL)
+ return NULL;
+ }
+ func = PyObject_GetAttr((PyObject *)type, new_str);
+ if (func == NULL)
+ return NULL;
+ assert(PyTuple_Check(args));
+ n = PyTuple_GET_SIZE(args);
+ newargs = PyTuple_New(n+1);
+ if (newargs == NULL)
+ return NULL;
+ Py_INCREF(type);
+ PyTuple_SET_ITEM(newargs, 0, (PyObject *)type);
+ for (i = 0; i < n; i++) {
+ x = PyTuple_GET_ITEM(args, i);
+ Py_INCREF(x);
+ PyTuple_SET_ITEM(newargs, i+1, x);
+ }
+ x = PyObject_Call(func, newargs, kwds);
+ Py_DECREF(newargs);
+ Py_DECREF(func);
+ return x;
}
static void
slot_tp_del(PyObject *self)
{
- static PyObject *del_str = NULL;
- PyObject *del, *res;
- PyObject *error_type, *error_value, *error_traceback;
-
- /* Temporarily resurrect the object. */
- assert(self->ob_refcnt == 0);
- self->ob_refcnt = 1;
-
- /* Save the current exception, if any. */
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
-
- /* Execute __del__ method, if any. */
- del = lookup_maybe(self, "__del__", &del_str);
- if (del != NULL) {
- res = PyEval_CallObject(del, NULL);
- if (res == NULL)
- PyErr_WriteUnraisable(del);
- else
- Py_DECREF(res);
- Py_DECREF(del);
- }
-
- /* Restore the saved exception. */
- PyErr_Restore(error_type, error_value, error_traceback);
-
- /* Undo the temporary resurrection; can't use DECREF here, it would
- * cause a recursive call.
- */
- assert(self->ob_refcnt > 0);
- if (--self->ob_refcnt == 0)
- return; /* this is the normal path out */
-
- /* __del__ resurrected it! Make it look like the original Py_DECREF
- * never happened.
- */
- {
- Py_ssize_t refcnt = self->ob_refcnt;
- _Py_NewReference(self);
- self->ob_refcnt = refcnt;
- }
- assert(!PyType_IS_GC(Py_TYPE(self)) ||
- _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
- /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
- * we need to undo that. */
- _Py_DEC_REFTOTAL;
- /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
- * chain, so no more to do there.
- * If COUNT_ALLOCS, the original decref bumped tp_frees, and
- * _Py_NewReference bumped tp_allocs: both of those need to be
- * undone.
- */
+ static PyObject *del_str = NULL;
+ PyObject *del, *res;
+ PyObject *error_type, *error_value, *error_traceback;
+
+ /* Temporarily resurrect the object. */
+ assert(self->ob_refcnt == 0);
+ self->ob_refcnt = 1;
+
+ /* Save the current exception, if any. */
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+
+ /* Execute __del__ method, if any. */
+ del = lookup_maybe(self, "__del__", &del_str);
+ if (del != NULL) {
+ res = PyEval_CallObject(del, NULL);
+ if (res == NULL)
+ PyErr_WriteUnraisable(del);
+ else
+ Py_DECREF(res);
+ Py_DECREF(del);
+ }
+
+ /* Restore the saved exception. */
+ PyErr_Restore(error_type, error_value, error_traceback);
+
+ /* Undo the temporary resurrection; can't use DECREF here, it would
+ * cause a recursive call.
+ */
+ assert(self->ob_refcnt > 0);
+ if (--self->ob_refcnt == 0)
+ return; /* this is the normal path out */
+
+ /* __del__ resurrected it! Make it look like the original Py_DECREF
+ * never happened.
+ */
+ {
+ Py_ssize_t refcnt = self->ob_refcnt;
+ _Py_NewReference(self);
+ self->ob_refcnt = refcnt;
+ }
+ assert(!PyType_IS_GC(Py_TYPE(self)) ||
+ _Py_AS_GC(self)->gc.gc_refs != _PyGC_REFS_UNTRACKED);
+ /* If Py_REF_DEBUG, _Py_NewReference bumped _Py_RefTotal, so
+ * we need to undo that. */
+ _Py_DEC_REFTOTAL;
+ /* If Py_TRACE_REFS, _Py_NewReference re-added self to the object
+ * chain, so no more to do there.
+ * If COUNT_ALLOCS, the original decref bumped tp_frees, and
+ * _Py_NewReference bumped tp_allocs: both of those need to be
+ * undone.
+ */
#ifdef COUNT_ALLOCS
- --Py_TYPE(self)->tp_frees;
- --Py_TYPE(self)->tp_allocs;
+ --Py_TYPE(self)->tp_frees;
+ --Py_TYPE(self)->tp_allocs;
#endif
}
@@ -5791,267 +5791,267 @@ typedef struct wrapperbase slotdef;
#undef RBINSLOT
#define TPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
- PyDoc_STR(DOC)}
+ {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
+ PyDoc_STR(DOC)}
#define FLSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC, FLAGS) \
- {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
- PyDoc_STR(DOC), FLAGS}
+ {NAME, offsetof(PyTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
+ PyDoc_STR(DOC), FLAGS}
#define ETSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
- PyDoc_STR(DOC)}
+ {NAME, offsetof(PyHeapTypeObject, SLOT), (void *)(FUNCTION), WRAPPER, \
+ PyDoc_STR(DOC)}
#define SQSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
+ ETSLOT(NAME, as_sequence.SLOT, FUNCTION, WRAPPER, DOC)
#define MPSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
+ ETSLOT(NAME, as_mapping.SLOT, FUNCTION, WRAPPER, DOC)
#define NBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, DOC)
#define UNSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
- "x." NAME "() <==> " DOC)
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
+ "x." NAME "() <==> " DOC)
#define IBSLOT(NAME, SLOT, FUNCTION, WRAPPER, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
- "x." NAME "(y) <==> x" DOC "y")
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, WRAPPER, \
+ "x." NAME "(y) <==> x" DOC "y")
#define BINSLOT(NAME, SLOT, FUNCTION, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
- "x." NAME "(y) <==> x" DOC "y")
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
+ "x." NAME "(y) <==> x" DOC "y")
#define RBINSLOT(NAME, SLOT, FUNCTION, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
- "x." NAME "(y) <==> y" DOC "x")
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
+ "x." NAME "(y) <==> y" DOC "x")
#define BINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
- "x." NAME "(y) <==> " DOC)
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_l, \
+ "x." NAME "(y) <==> " DOC)
#define RBINSLOTNOTINFIX(NAME, SLOT, FUNCTION, DOC) \
- ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
- "x." NAME "(y) <==> " DOC)
+ ETSLOT(NAME, as_number.SLOT, FUNCTION, wrap_binaryfunc_r, \
+ "x." NAME "(y) <==> " DOC)
static slotdef slotdefs[] = {
- SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
- "x.__len__() <==> len(x)"),
- /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
- The logic in abstract.c always falls back to nb_add/nb_multiply in
- this case. Defining both the nb_* and the sq_* slots to call the
- user-defined methods has unexpected side-effects, as shown by
- test_descr.notimplemented() */
- SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
- "x.__add__(y) <==> x+y"),
- SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
- "x.__mul__(n) <==> x*n"),
- SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
- "x.__rmul__(n) <==> n*x"),
- SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
- "x.__getitem__(y) <==> x[y]"),
- SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
- "x.__getslice__(i, j) <==> x[i:j]\n\
- \n\
- Use of negative indices is not supported."),
- SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
- "x.__setitem__(i, y) <==> x[i]=y"),
- SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
- "x.__delitem__(y) <==> del x[y]"),
- SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
- wrap_ssizessizeobjargproc,
- "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
- \n\
- Use of negative indices is not supported."),
- SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
- "x.__delslice__(i, j) <==> del x[i:j]\n\
- \n\
- Use of negative indices is not supported."),
- SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
- "x.__contains__(y) <==> y in x"),
- SQSLOT("__iadd__", sq_inplace_concat, NULL,
- wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
- SQSLOT("__imul__", sq_inplace_repeat, NULL,
- wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
-
- MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
- "x.__len__() <==> len(x)"),
- MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
- wrap_binaryfunc,
- "x.__getitem__(y) <==> x[y]"),
- MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
- wrap_objobjargproc,
- "x.__setitem__(i, y) <==> x[i]=y"),
- MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
- wrap_delitem,
- "x.__delitem__(y) <==> del x[y]"),
-
- BINSLOT("__add__", nb_add, slot_nb_add,
- "+"),
- RBINSLOT("__radd__", nb_add, slot_nb_add,
- "+"),
- BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
- "-"),
- RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
- "-"),
- BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
- "*"),
- RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
- "*"),
- BINSLOT("__div__", nb_divide, slot_nb_divide,
- "/"),
- RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
- "/"),
- BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
- "%"),
- RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
- "%"),
- BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
- "divmod(x, y)"),
- RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
- "divmod(y, x)"),
- NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
- "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
- NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
- "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
- UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
- UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
- UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
- "abs(x)"),
- UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
- "x != 0"),
- UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
- BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
- RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
- BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
- RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
- BINSLOT("__and__", nb_and, slot_nb_and, "&"),
- RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
- BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
- RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
- BINSLOT("__or__", nb_or, slot_nb_or, "|"),
- RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
- NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
- "x.__coerce__(y) <==> coerce(x, y)"),
- UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
- "int(x)"),
- UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
- "long(x)"),
- UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
- "float(x)"),
- UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
- "oct(x)"),
- UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
- "hex(x)"),
- NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
- "x[y:z] <==> x[y.__index__():z.__index__()]"),
- IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
- wrap_binaryfunc, "+"),
- IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
- wrap_binaryfunc, "-"),
- IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
- wrap_binaryfunc, "*"),
- IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
- wrap_binaryfunc, "/"),
- IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
- wrap_binaryfunc, "%"),
- IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
- wrap_binaryfunc, "**"),
- IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
- wrap_binaryfunc, "<<"),
- IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
- wrap_binaryfunc, ">>"),
- IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
- wrap_binaryfunc, "&"),
- IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
- wrap_binaryfunc, "^"),
- IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
- wrap_binaryfunc, "|"),
- BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
- RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
- BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
- RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
- IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
- slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
- IBSLOT("__itruediv__", nb_inplace_true_divide,
- slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
-
- TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
- "x.__str__() <==> str(x)"),
- TPSLOT("__str__", tp_print, NULL, NULL, ""),
- TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
- "x.__repr__() <==> repr(x)"),
- TPSLOT("__repr__", tp_print, NULL, NULL, ""),
- TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
- "x.__cmp__(y) <==> cmp(x,y)"),
- TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
- "x.__hash__() <==> hash(x)"),
- FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
- "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
- TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
- wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
- TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
- TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
- TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
- TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
- "x.__setattr__('name', value) <==> x.name = value"),
- TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
- TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
- "x.__delattr__('name') <==> del x.name"),
- TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
- TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
- "x.__lt__(y) <==> x<y"),
- TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
- "x.__le__(y) <==> x<=y"),
- TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
- "x.__eq__(y) <==> x==y"),
- TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
- "x.__ne__(y) <==> x!=y"),
- TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
- "x.__gt__(y) <==> x>y"),
- TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
- "x.__ge__(y) <==> x>=y"),
- TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
- "x.__iter__() <==> iter(x)"),
- TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
- "x.next() -> the next value, or raise StopIteration"),
- TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
- "descr.__get__(obj[, type]) -> value"),
- TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
- "descr.__set__(obj, value)"),
- TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
- wrap_descr_delete, "descr.__delete__(obj)"),
- FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
- "x.__init__(...) initializes x; "
- "see x.__class__.__doc__ for signature",
- PyWrapperFlag_KEYWORDS),
- TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
- TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
- {NULL}
+ SQSLOT("__len__", sq_length, slot_sq_length, wrap_lenfunc,
+ "x.__len__() <==> len(x)"),
+ /* Heap types defining __add__/__mul__ have sq_concat/sq_repeat == NULL.
+ The logic in abstract.c always falls back to nb_add/nb_multiply in
+ this case. Defining both the nb_* and the sq_* slots to call the
+ user-defined methods has unexpected side-effects, as shown by
+ test_descr.notimplemented() */
+ SQSLOT("__add__", sq_concat, NULL, wrap_binaryfunc,
+ "x.__add__(y) <==> x+y"),
+ SQSLOT("__mul__", sq_repeat, NULL, wrap_indexargfunc,
+ "x.__mul__(n) <==> x*n"),
+ SQSLOT("__rmul__", sq_repeat, NULL, wrap_indexargfunc,
+ "x.__rmul__(n) <==> n*x"),
+ SQSLOT("__getitem__", sq_item, slot_sq_item, wrap_sq_item,
+ "x.__getitem__(y) <==> x[y]"),
+ SQSLOT("__getslice__", sq_slice, slot_sq_slice, wrap_ssizessizeargfunc,
+ "x.__getslice__(i, j) <==> x[i:j]\n\
+ \n\
+ Use of negative indices is not supported."),
+ SQSLOT("__setitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_setitem,
+ "x.__setitem__(i, y) <==> x[i]=y"),
+ SQSLOT("__delitem__", sq_ass_item, slot_sq_ass_item, wrap_sq_delitem,
+ "x.__delitem__(y) <==> del x[y]"),
+ SQSLOT("__setslice__", sq_ass_slice, slot_sq_ass_slice,
+ wrap_ssizessizeobjargproc,
+ "x.__setslice__(i, j, y) <==> x[i:j]=y\n\
+ \n\
+ Use of negative indices is not supported."),
+ SQSLOT("__delslice__", sq_ass_slice, slot_sq_ass_slice, wrap_delslice,
+ "x.__delslice__(i, j) <==> del x[i:j]\n\
+ \n\
+ Use of negative indices is not supported."),
+ SQSLOT("__contains__", sq_contains, slot_sq_contains, wrap_objobjproc,
+ "x.__contains__(y) <==> y in x"),
+ SQSLOT("__iadd__", sq_inplace_concat, NULL,
+ wrap_binaryfunc, "x.__iadd__(y) <==> x+=y"),
+ SQSLOT("__imul__", sq_inplace_repeat, NULL,
+ wrap_indexargfunc, "x.__imul__(y) <==> x*=y"),
+
+ MPSLOT("__len__", mp_length, slot_mp_length, wrap_lenfunc,
+ "x.__len__() <==> len(x)"),
+ MPSLOT("__getitem__", mp_subscript, slot_mp_subscript,
+ wrap_binaryfunc,
+ "x.__getitem__(y) <==> x[y]"),
+ MPSLOT("__setitem__", mp_ass_subscript, slot_mp_ass_subscript,
+ wrap_objobjargproc,
+ "x.__setitem__(i, y) <==> x[i]=y"),
+ MPSLOT("__delitem__", mp_ass_subscript, slot_mp_ass_subscript,
+ wrap_delitem,
+ "x.__delitem__(y) <==> del x[y]"),
+
+ BINSLOT("__add__", nb_add, slot_nb_add,
+ "+"),
+ RBINSLOT("__radd__", nb_add, slot_nb_add,
+ "+"),
+ BINSLOT("__sub__", nb_subtract, slot_nb_subtract,
+ "-"),
+ RBINSLOT("__rsub__", nb_subtract, slot_nb_subtract,
+ "-"),
+ BINSLOT("__mul__", nb_multiply, slot_nb_multiply,
+ "*"),
+ RBINSLOT("__rmul__", nb_multiply, slot_nb_multiply,
+ "*"),
+ BINSLOT("__div__", nb_divide, slot_nb_divide,
+ "/"),
+ RBINSLOT("__rdiv__", nb_divide, slot_nb_divide,
+ "/"),
+ BINSLOT("__mod__", nb_remainder, slot_nb_remainder,
+ "%"),
+ RBINSLOT("__rmod__", nb_remainder, slot_nb_remainder,
+ "%"),
+ BINSLOTNOTINFIX("__divmod__", nb_divmod, slot_nb_divmod,
+ "divmod(x, y)"),
+ RBINSLOTNOTINFIX("__rdivmod__", nb_divmod, slot_nb_divmod,
+ "divmod(y, x)"),
+ NBSLOT("__pow__", nb_power, slot_nb_power, wrap_ternaryfunc,
+ "x.__pow__(y[, z]) <==> pow(x, y[, z])"),
+ NBSLOT("__rpow__", nb_power, slot_nb_power, wrap_ternaryfunc_r,
+ "y.__rpow__(x[, z]) <==> pow(x, y[, z])"),
+ UNSLOT("__neg__", nb_negative, slot_nb_negative, wrap_unaryfunc, "-x"),
+ UNSLOT("__pos__", nb_positive, slot_nb_positive, wrap_unaryfunc, "+x"),
+ UNSLOT("__abs__", nb_absolute, slot_nb_absolute, wrap_unaryfunc,
+ "abs(x)"),
+ UNSLOT("__nonzero__", nb_nonzero, slot_nb_nonzero, wrap_inquirypred,
+ "x != 0"),
+ UNSLOT("__invert__", nb_invert, slot_nb_invert, wrap_unaryfunc, "~x"),
+ BINSLOT("__lshift__", nb_lshift, slot_nb_lshift, "<<"),
+ RBINSLOT("__rlshift__", nb_lshift, slot_nb_lshift, "<<"),
+ BINSLOT("__rshift__", nb_rshift, slot_nb_rshift, ">>"),
+ RBINSLOT("__rrshift__", nb_rshift, slot_nb_rshift, ">>"),
+ BINSLOT("__and__", nb_and, slot_nb_and, "&"),
+ RBINSLOT("__rand__", nb_and, slot_nb_and, "&"),
+ BINSLOT("__xor__", nb_xor, slot_nb_xor, "^"),
+ RBINSLOT("__rxor__", nb_xor, slot_nb_xor, "^"),
+ BINSLOT("__or__", nb_or, slot_nb_or, "|"),
+ RBINSLOT("__ror__", nb_or, slot_nb_or, "|"),
+ NBSLOT("__coerce__", nb_coerce, slot_nb_coerce, wrap_coercefunc,
+ "x.__coerce__(y) <==> coerce(x, y)"),
+ UNSLOT("__int__", nb_int, slot_nb_int, wrap_unaryfunc,
+ "int(x)"),
+ UNSLOT("__long__", nb_long, slot_nb_long, wrap_unaryfunc,
+ "long(x)"),
+ UNSLOT("__float__", nb_float, slot_nb_float, wrap_unaryfunc,
+ "float(x)"),
+ UNSLOT("__oct__", nb_oct, slot_nb_oct, wrap_unaryfunc,
+ "oct(x)"),
+ UNSLOT("__hex__", nb_hex, slot_nb_hex, wrap_unaryfunc,
+ "hex(x)"),
+ NBSLOT("__index__", nb_index, slot_nb_index, wrap_unaryfunc,
+ "x[y:z] <==> x[y.__index__():z.__index__()]"),
+ IBSLOT("__iadd__", nb_inplace_add, slot_nb_inplace_add,
+ wrap_binaryfunc, "+"),
+ IBSLOT("__isub__", nb_inplace_subtract, slot_nb_inplace_subtract,
+ wrap_binaryfunc, "-"),
+ IBSLOT("__imul__", nb_inplace_multiply, slot_nb_inplace_multiply,
+ wrap_binaryfunc, "*"),
+ IBSLOT("__idiv__", nb_inplace_divide, slot_nb_inplace_divide,
+ wrap_binaryfunc, "/"),
+ IBSLOT("__imod__", nb_inplace_remainder, slot_nb_inplace_remainder,
+ wrap_binaryfunc, "%"),
+ IBSLOT("__ipow__", nb_inplace_power, slot_nb_inplace_power,
+ wrap_binaryfunc, "**"),
+ IBSLOT("__ilshift__", nb_inplace_lshift, slot_nb_inplace_lshift,
+ wrap_binaryfunc, "<<"),
+ IBSLOT("__irshift__", nb_inplace_rshift, slot_nb_inplace_rshift,
+ wrap_binaryfunc, ">>"),
+ IBSLOT("__iand__", nb_inplace_and, slot_nb_inplace_and,
+ wrap_binaryfunc, "&"),
+ IBSLOT("__ixor__", nb_inplace_xor, slot_nb_inplace_xor,
+ wrap_binaryfunc, "^"),
+ IBSLOT("__ior__", nb_inplace_or, slot_nb_inplace_or,
+ wrap_binaryfunc, "|"),
+ BINSLOT("__floordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
+ RBINSLOT("__rfloordiv__", nb_floor_divide, slot_nb_floor_divide, "//"),
+ BINSLOT("__truediv__", nb_true_divide, slot_nb_true_divide, "/"),
+ RBINSLOT("__rtruediv__", nb_true_divide, slot_nb_true_divide, "/"),
+ IBSLOT("__ifloordiv__", nb_inplace_floor_divide,
+ slot_nb_inplace_floor_divide, wrap_binaryfunc, "//"),
+ IBSLOT("__itruediv__", nb_inplace_true_divide,
+ slot_nb_inplace_true_divide, wrap_binaryfunc, "/"),
+
+ TPSLOT("__str__", tp_str, slot_tp_str, wrap_unaryfunc,
+ "x.__str__() <==> str(x)"),
+ TPSLOT("__str__", tp_print, NULL, NULL, ""),
+ TPSLOT("__repr__", tp_repr, slot_tp_repr, wrap_unaryfunc,
+ "x.__repr__() <==> repr(x)"),
+ TPSLOT("__repr__", tp_print, NULL, NULL, ""),
+ TPSLOT("__cmp__", tp_compare, _PyObject_SlotCompare, wrap_cmpfunc,
+ "x.__cmp__(y) <==> cmp(x,y)"),
+ TPSLOT("__hash__", tp_hash, slot_tp_hash, wrap_hashfunc,
+ "x.__hash__() <==> hash(x)"),
+ FLSLOT("__call__", tp_call, slot_tp_call, (wrapperfunc)wrap_call,
+ "x.__call__(...) <==> x(...)", PyWrapperFlag_KEYWORDS),
+ TPSLOT("__getattribute__", tp_getattro, slot_tp_getattr_hook,
+ wrap_binaryfunc, "x.__getattribute__('name') <==> x.name"),
+ TPSLOT("__getattribute__", tp_getattr, NULL, NULL, ""),
+ TPSLOT("__getattr__", tp_getattro, slot_tp_getattr_hook, NULL, ""),
+ TPSLOT("__getattr__", tp_getattr, NULL, NULL, ""),
+ TPSLOT("__setattr__", tp_setattro, slot_tp_setattro, wrap_setattr,
+ "x.__setattr__('name', value) <==> x.name = value"),
+ TPSLOT("__setattr__", tp_setattr, NULL, NULL, ""),
+ TPSLOT("__delattr__", tp_setattro, slot_tp_setattro, wrap_delattr,
+ "x.__delattr__('name') <==> del x.name"),
+ TPSLOT("__delattr__", tp_setattr, NULL, NULL, ""),
+ TPSLOT("__lt__", tp_richcompare, slot_tp_richcompare, richcmp_lt,
+ "x.__lt__(y) <==> x<y"),
+ TPSLOT("__le__", tp_richcompare, slot_tp_richcompare, richcmp_le,
+ "x.__le__(y) <==> x<=y"),
+ TPSLOT("__eq__", tp_richcompare, slot_tp_richcompare, richcmp_eq,
+ "x.__eq__(y) <==> x==y"),
+ TPSLOT("__ne__", tp_richcompare, slot_tp_richcompare, richcmp_ne,
+ "x.__ne__(y) <==> x!=y"),
+ TPSLOT("__gt__", tp_richcompare, slot_tp_richcompare, richcmp_gt,
+ "x.__gt__(y) <==> x>y"),
+ TPSLOT("__ge__", tp_richcompare, slot_tp_richcompare, richcmp_ge,
+ "x.__ge__(y) <==> x>=y"),
+ TPSLOT("__iter__", tp_iter, slot_tp_iter, wrap_unaryfunc,
+ "x.__iter__() <==> iter(x)"),
+ TPSLOT("next", tp_iternext, slot_tp_iternext, wrap_next,
+ "x.next() -> the next value, or raise StopIteration"),
+ TPSLOT("__get__", tp_descr_get, slot_tp_descr_get, wrap_descr_get,
+ "descr.__get__(obj[, type]) -> value"),
+ TPSLOT("__set__", tp_descr_set, slot_tp_descr_set, wrap_descr_set,
+ "descr.__set__(obj, value)"),
+ TPSLOT("__delete__", tp_descr_set, slot_tp_descr_set,
+ wrap_descr_delete, "descr.__delete__(obj)"),
+ FLSLOT("__init__", tp_init, slot_tp_init, (wrapperfunc)wrap_init,
+ "x.__init__(...) initializes x; "
+ "see x.__class__.__doc__ for signature",
+ PyWrapperFlag_KEYWORDS),
+ TPSLOT("__new__", tp_new, slot_tp_new, NULL, ""),
+ TPSLOT("__del__", tp_del, slot_tp_del, NULL, ""),
+ {NULL}
};
/* Given a type pointer and an offset gotten from a slotdef entry, return a
- pointer to the actual slot. This is not quite the same as simply adding
+ pointer to the actual slot. This is not quite the same as simply adding
the offset to the type pointer, since it takes care to indirect through the
proper indirection pointer (as_buffer, etc.); it returns NULL if the
indirection pointer is NULL. */
static void **
slotptr(PyTypeObject *type, int ioffset)
{
- char *ptr;
- long offset = ioffset;
-
- /* Note: this depends on the order of the members of PyHeapTypeObject! */
- assert(offset >= 0);
- assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
- if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
- ptr = (char *)type->tp_as_sequence;
- offset -= offsetof(PyHeapTypeObject, as_sequence);
- }
- else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
- ptr = (char *)type->tp_as_mapping;
- offset -= offsetof(PyHeapTypeObject, as_mapping);
- }
- else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
- ptr = (char *)type->tp_as_number;
- offset -= offsetof(PyHeapTypeObject, as_number);
- }
- else {
- ptr = (char *)type;
- }
- if (ptr != NULL)
- ptr += offset;
- return (void **)ptr;
+ char *ptr;
+ long offset = ioffset;
+
+ /* Note: this depends on the order of the members of PyHeapTypeObject! */
+ assert(offset >= 0);
+ assert((size_t)offset < offsetof(PyHeapTypeObject, as_buffer));
+ if ((size_t)offset >= offsetof(PyHeapTypeObject, as_sequence)) {
+ ptr = (char *)type->tp_as_sequence;
+ offset -= offsetof(PyHeapTypeObject, as_sequence);
+ }
+ else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_mapping)) {
+ ptr = (char *)type->tp_as_mapping;
+ offset -= offsetof(PyHeapTypeObject, as_mapping);
+ }
+ else if ((size_t)offset >= offsetof(PyHeapTypeObject, as_number)) {
+ ptr = (char *)type->tp_as_number;
+ offset -= offsetof(PyHeapTypeObject, as_number);
+ }
+ else {
+ ptr = (char *)type;
+ }
+ if (ptr != NULL)
+ ptr += offset;
+ return (void **)ptr;
}
/* Length of array of slotdef pointers used to store slots with the
@@ -6065,37 +6065,37 @@ slotptr(PyTypeObject *type, int ioffset)
static void **
resolve_slotdups(PyTypeObject *type, PyObject *name)
{
- /* XXX Maybe this could be optimized more -- but is it worth it? */
-
- /* pname and ptrs act as a little cache */
- static PyObject *pname;
- static slotdef *ptrs[MAX_EQUIV];
- slotdef *p, **pp;
- void **res, **ptr;
-
- if (pname != name) {
- /* Collect all slotdefs that match name into ptrs. */
- pname = name;
- pp = ptrs;
- for (p = slotdefs; p->name_strobj; p++) {
- if (p->name_strobj == name)
- *pp++ = p;
- }
- *pp = NULL;
- }
-
- /* Look in all matching slots of the type; if exactly one of these has
- a filled-in slot, return its value. Otherwise return NULL. */
- res = NULL;
- for (pp = ptrs; *pp; pp++) {
- ptr = slotptr(type, (*pp)->offset);
- if (ptr == NULL || *ptr == NULL)
- continue;
- if (res != NULL)
- return NULL;
- res = ptr;
- }
- return res;
+ /* XXX Maybe this could be optimized more -- but is it worth it? */
+
+ /* pname and ptrs act as a little cache */
+ static PyObject *pname;
+ static slotdef *ptrs[MAX_EQUIV];
+ slotdef *p, **pp;
+ void **res, **ptr;
+
+ if (pname != name) {
+ /* Collect all slotdefs that match name into ptrs. */
+ pname = name;
+ pp = ptrs;
+ for (p = slotdefs; p->name_strobj; p++) {
+ if (p->name_strobj == name)
+ *pp++ = p;
+ }
+ *pp = NULL;
+ }
+
+ /* Look in all matching slots of the type; if exactly one of these has
+ a filled-in slot, return its value. Otherwise return NULL. */
+ res = NULL;
+ for (pp = ptrs; *pp; pp++) {
+ ptr = slotptr(type, (*pp)->offset);
+ if (ptr == NULL || *ptr == NULL)
+ continue;
+ if (res != NULL)
+ return NULL;
+ res = ptr;
+ }
+ return res;
}
/* Common code for update_slots_callback() and fixup_slot_dispatchers(). This
@@ -6107,81 +6107,81 @@ resolve_slotdups(PyTypeObject *type, PyObject *name)
static slotdef *
update_one_slot(PyTypeObject *type, slotdef *p)
{
- PyObject *descr;
- PyWrapperDescrObject *d;
- void *generic = NULL, *specific = NULL;
- int use_generic = 0;
- int offset = p->offset;
- void **ptr = slotptr(type, offset);
-
- if (ptr == NULL) {
- do {
- ++p;
- } while (p->offset == offset);
- return p;
- }
- do {
- descr = _PyType_Lookup(type, p->name_strobj);
- if (descr == NULL) {
- if (ptr == (void**)&type->tp_iternext) {
- specific = _PyObject_NextNotImplemented;
- }
- continue;
- }
- if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
- void **tptr = resolve_slotdups(type, p->name_strobj);
- if (tptr == NULL || tptr == ptr)
- generic = p->function;
- d = (PyWrapperDescrObject *)descr;
- if (d->d_base->wrapper == p->wrapper &&
- PyType_IsSubtype(type, d->d_type))
- {
- if (specific == NULL ||
- specific == d->d_wrapped)
- specific = d->d_wrapped;
- else
- use_generic = 1;
- }
- }
- else if (Py_TYPE(descr) == &PyCFunction_Type &&
- PyCFunction_GET_FUNCTION(descr) ==
- (PyCFunction)tp_new_wrapper &&
- ptr == (void**)&type->tp_new)
- {
- /* The __new__ wrapper is not a wrapper descriptor,
- so must be special-cased differently.
- If we don't do this, creating an instance will
- always use slot_tp_new which will look up
- __new__ in the MRO which will call tp_new_wrapper
- which will look through the base classes looking
- for a static base and call its tp_new (usually
- PyType_GenericNew), after performing various
- sanity checks and constructing a new argument
- list. Cut all that nonsense short -- this speeds
- up instance creation tremendously. */
- specific = (void *)type->tp_new;
- /* XXX I'm not 100% sure that there isn't a hole
- in this reasoning that requires additional
- sanity checks. I'll buy the first person to
- point out a bug in this reasoning a beer. */
- }
- else if (descr == Py_None &&
- ptr == (void**)&type->tp_hash) {
- /* We specifically allow __hash__ to be set to None
- to prevent inheritance of the default
- implementation from object.__hash__ */
- specific = PyObject_HashNotImplemented;
- }
- else {
- use_generic = 1;
- generic = p->function;
- }
- } while ((++p)->offset == offset);
- if (specific && !use_generic)
- *ptr = specific;
- else
- *ptr = generic;
- return p;
+ PyObject *descr;
+ PyWrapperDescrObject *d;
+ void *generic = NULL, *specific = NULL;
+ int use_generic = 0;
+ int offset = p->offset;
+ void **ptr = slotptr(type, offset);
+
+ if (ptr == NULL) {
+ do {
+ ++p;
+ } while (p->offset == offset);
+ return p;
+ }
+ do {
+ descr = _PyType_Lookup(type, p->name_strobj);
+ if (descr == NULL) {
+ if (ptr == (void**)&type->tp_iternext) {
+ specific = _PyObject_NextNotImplemented;
+ }
+ continue;
+ }
+ if (Py_TYPE(descr) == &PyWrapperDescr_Type) {
+ void **tptr = resolve_slotdups(type, p->name_strobj);
+ if (tptr == NULL || tptr == ptr)
+ generic = p->function;
+ d = (PyWrapperDescrObject *)descr;
+ if (d->d_base->wrapper == p->wrapper &&
+ PyType_IsSubtype(type, d->d_type))
+ {
+ if (specific == NULL ||
+ specific == d->d_wrapped)
+ specific = d->d_wrapped;
+ else
+ use_generic = 1;
+ }
+ }
+ else if (Py_TYPE(descr) == &PyCFunction_Type &&
+ PyCFunction_GET_FUNCTION(descr) ==
+ (PyCFunction)tp_new_wrapper &&
+ ptr == (void**)&type->tp_new)
+ {
+ /* The __new__ wrapper is not a wrapper descriptor,
+ so must be special-cased differently.
+ If we don't do this, creating an instance will
+ always use slot_tp_new which will look up
+ __new__ in the MRO which will call tp_new_wrapper
+ which will look through the base classes looking
+ for a static base and call its tp_new (usually
+ PyType_GenericNew), after performing various
+ sanity checks and constructing a new argument
+ list. Cut all that nonsense short -- this speeds
+ up instance creation tremendously. */
+ specific = (void *)type->tp_new;
+ /* XXX I'm not 100% sure that there isn't a hole
+ in this reasoning that requires additional
+ sanity checks. I'll buy the first person to
+ point out a bug in this reasoning a beer. */
+ }
+ else if (descr == Py_None &&
+ ptr == (void**)&type->tp_hash) {
+ /* We specifically allow __hash__ to be set to None
+ to prevent inheritance of the default
+ implementation from object.__hash__ */
+ specific = PyObject_HashNotImplemented;
+ }
+ else {
+ use_generic = 1;
+ generic = p->function;
+ }
+ } while ((++p)->offset == offset);
+ if (specific && !use_generic)
+ *ptr = specific;
+ else
+ *ptr = generic;
+ return p;
}
/* In the type, update the slots whose slotdefs are gathered in the pp array.
@@ -6189,11 +6189,11 @@ update_one_slot(PyTypeObject *type, slotdef *p)
static int
update_slots_callback(PyTypeObject *type, void *data)
{
- slotdef **pp = (slotdef **)data;
+ slotdef **pp = (slotdef **)data;
- for (; *pp; pp++)
- update_one_slot(type, *pp);
- return 0;
+ for (; *pp; pp++)
+ update_one_slot(type, *pp);
+ return 0;
}
/* Comparison function for qsort() to compare slotdefs by their offset, and
@@ -6201,14 +6201,14 @@ update_slots_callback(PyTypeObject *type, void *data)
static int
slotdef_cmp(const void *aa, const void *bb)
{
- const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
- int c = a->offset - b->offset;
- if (c != 0)
- return c;
- else
- /* Cannot use a-b, as this gives off_t,
- which may lose precision when converted to int. */
- return (a > b) ? 1 : (a < b) ? -1 : 0;
+ const slotdef *a = (const slotdef *)aa, *b = (const slotdef *)bb;
+ int c = a->offset - b->offset;
+ if (c != 0)
+ return c;
+ else
+ /* Cannot use a-b, as this gives off_t,
+ which may lose precision when converted to int. */
+ return (a > b) ? 1 : (a < b) ? -1 : 0;
}
/* Initialize the slotdefs table by adding interned string objects for the
@@ -6216,56 +6216,56 @@ slotdef_cmp(const void *aa, const void *bb)
static void
init_slotdefs(void)
{
- slotdef *p;
- static int initialized = 0;
+ slotdef *p;
+ static int initialized = 0;
- if (initialized)
- return;
- for (p = slotdefs; p->name; p++) {
- p->name_strobj = PyString_InternFromString(p->name);
- if (!p->name_strobj)
- Py_FatalError("Out of memory interning slotdef names");
- }
- qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
- slotdef_cmp);
- initialized = 1;
+ if (initialized)
+ return;
+ for (p = slotdefs; p->name; p++) {
+ p->name_strobj = PyString_InternFromString(p->name);
+ if (!p->name_strobj)
+ Py_FatalError("Out of memory interning slotdef names");
+ }
+ qsort((void *)slotdefs, (size_t)(p-slotdefs), sizeof(slotdef),
+ slotdef_cmp);
+ initialized = 1;
}
/* Update the slots after assignment to a class (type) attribute. */
static int
update_slot(PyTypeObject *type, PyObject *name)
{
- slotdef *ptrs[MAX_EQUIV];
- slotdef *p;
- slotdef **pp;
- int offset;
-
- /* Clear the VALID_VERSION flag of 'type' and all its
- subclasses. This could possibly be unified with the
- update_subclasses() recursion below, but carefully:
- they each have their own conditions on which to stop
- recursing into subclasses. */
- PyType_Modified(type);
-
- init_slotdefs();
- pp = ptrs;
- for (p = slotdefs; p->name; p++) {
- /* XXX assume name is interned! */
- if (p->name_strobj == name)
- *pp++ = p;
- }
- *pp = NULL;
- for (pp = ptrs; *pp; pp++) {
- p = *pp;
- offset = p->offset;
- while (p > slotdefs && (p-1)->offset == offset)
- --p;
- *pp = p;
- }
- if (ptrs[0] == NULL)
- return 0; /* Not an attribute that affects any slots */
- return update_subclasses(type, name,
- update_slots_callback, (void *)ptrs);
+ slotdef *ptrs[MAX_EQUIV];
+ slotdef *p;
+ slotdef **pp;
+ int offset;
+
+ /* Clear the VALID_VERSION flag of 'type' and all its
+ subclasses. This could possibly be unified with the
+ update_subclasses() recursion below, but carefully:
+ they each have their own conditions on which to stop
+ recursing into subclasses. */
+ PyType_Modified(type);
+
+ init_slotdefs();
+ pp = ptrs;
+ for (p = slotdefs; p->name; p++) {
+ /* XXX assume name is interned! */
+ if (p->name_strobj == name)
+ *pp++ = p;
+ }
+ *pp = NULL;
+ for (pp = ptrs; *pp; pp++) {
+ p = *pp;
+ offset = p->offset;
+ while (p > slotdefs && (p-1)->offset == offset)
+ --p;
+ *pp = p;
+ }
+ if (ptrs[0] == NULL)
+ return 0; /* Not an attribute that affects any slots */
+ return update_subclasses(type, name,
+ update_slots_callback, (void *)ptrs);
}
/* Store the proper functions in the slot dispatches at class (type)
@@ -6274,23 +6274,23 @@ update_slot(PyTypeObject *type, PyObject *name)
static void
fixup_slot_dispatchers(PyTypeObject *type)
{
- slotdef *p;
+ slotdef *p;
- init_slotdefs();
- for (p = slotdefs; p->name; )
- p = update_one_slot(type, p);
+ init_slotdefs();
+ for (p = slotdefs; p->name; )
+ p = update_one_slot(type, p);
}
static void
update_all_slots(PyTypeObject* type)
{
- slotdef *p;
+ slotdef *p;
- init_slotdefs();
- for (p = slotdefs; p->name; p++) {
- /* update_slot returns int but can't actually fail */
- update_slot(type, p->name_strobj);
- }
+ init_slotdefs();
+ for (p = slotdefs; p->name; p++) {
+ /* update_slot returns int but can't actually fail */
+ update_slot(type, p->name_strobj);
+ }
}
/* recurse_down_subclasses() and update_subclasses() are mutually
@@ -6299,56 +6299,56 @@ update_all_slots(PyTypeObject* type)
static int
update_subclasses(PyTypeObject *type, PyObject *name,
- update_callback callback, void *data)
+ update_callback callback, void *data)
{
- if (callback(type, data) < 0)
- return -1;
- return recurse_down_subclasses(type, name, callback, data);
+ if (callback(type, data) < 0)
+ return -1;
+ return recurse_down_subclasses(type, name, callback, data);
}
static int
recurse_down_subclasses(PyTypeObject *type, PyObject *name,
- update_callback callback, void *data)
-{
- PyTypeObject *subclass;
- PyObject *ref, *subclasses, *dict;
- Py_ssize_t i, n;
-
- subclasses = type->tp_subclasses;
- if (subclasses == NULL)
- return 0;
- assert(PyList_Check(subclasses));
- n = PyList_GET_SIZE(subclasses);
- for (i = 0; i < n; i++) {
- ref = PyList_GET_ITEM(subclasses, i);
- assert(PyWeakref_CheckRef(ref));
- subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
- assert(subclass != NULL);
- if ((PyObject *)subclass == Py_None)
- continue;
- assert(PyType_Check(subclass));
- /* Avoid recursing down into unaffected classes */
- dict = subclass->tp_dict;
- if (dict != NULL && PyDict_Check(dict) &&
- PyDict_GetItem(dict, name) != NULL)
- continue;
- if (update_subclasses(subclass, name, callback, data) < 0)
- return -1;
- }
- return 0;
+ update_callback callback, void *data)
+{
+ PyTypeObject *subclass;
+ PyObject *ref, *subclasses, *dict;
+ Py_ssize_t i, n;
+
+ subclasses = type->tp_subclasses;
+ if (subclasses == NULL)
+ return 0;
+ assert(PyList_Check(subclasses));
+ n = PyList_GET_SIZE(subclasses);
+ for (i = 0; i < n; i++) {
+ ref = PyList_GET_ITEM(subclasses, i);
+ assert(PyWeakref_CheckRef(ref));
+ subclass = (PyTypeObject *)PyWeakref_GET_OBJECT(ref);
+ assert(subclass != NULL);
+ if ((PyObject *)subclass == Py_None)
+ continue;
+ assert(PyType_Check(subclass));
+ /* Avoid recursing down into unaffected classes */
+ dict = subclass->tp_dict;
+ if (dict != NULL && PyDict_Check(dict) &&
+ PyDict_GetItem(dict, name) != NULL)
+ continue;
+ if (update_subclasses(subclass, name, callback, data) < 0)
+ return -1;
+ }
+ return 0;
}
/* This function is called by PyType_Ready() to populate the type's
dictionary with method descriptors for function slots. For each
function slot (like tp_repr) that's defined in the type, one or more
corresponding descriptors are added in the type's tp_dict dictionary
- under the appropriate name (like __repr__). Some function slots
+ under the appropriate name (like __repr__). Some function slots
cause more than one descriptor to be added (for example, the nb_add
slot adds both __add__ and __radd__ descriptors) and some function
slots compete for the same descriptor (for example both sq_item and
mp_subscript generate a __getitem__ descriptor).
- In the latter case, the first slotdef entry encoutered wins. Since
+ In the latter case, the first slotdef entry encoutered wins. Since
slotdef entries are sorted by the offset of the slot in the
PyHeapTypeObject, this gives us some control over disambiguating
between competing slots: the members of PyHeapTypeObject are listed
@@ -6371,282 +6371,282 @@ recurse_down_subclasses(PyTypeObject *type, PyObject *name,
static int
add_operators(PyTypeObject *type)
{
- PyObject *dict = type->tp_dict;
- slotdef *p;
- PyObject *descr;
- void **ptr;
-
- init_slotdefs();
- for (p = slotdefs; p->name; p++) {
- if (p->wrapper == NULL)
- continue;
- ptr = slotptr(type, p->offset);
- if (!ptr || !*ptr)
- continue;
- if (PyDict_GetItem(dict, p->name_strobj))
- continue;
- if (*ptr == PyObject_HashNotImplemented) {
- /* Classes may prevent the inheritance of the tp_hash
- slot by storing PyObject_HashNotImplemented in it. Make it
- visible as a None value for the __hash__ attribute. */
- if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
- return -1;
- }
- else {
- descr = PyDescr_NewWrapper(type, p, *ptr);
- if (descr == NULL)
- return -1;
- if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
- return -1;
- Py_DECREF(descr);
- }
- }
- if (type->tp_new != NULL) {
- if (add_tp_new_wrapper(type) < 0)
- return -1;
- }
- return 0;
+ PyObject *dict = type->tp_dict;
+ slotdef *p;
+ PyObject *descr;
+ void **ptr;
+
+ init_slotdefs();
+ for (p = slotdefs; p->name; p++) {
+ if (p->wrapper == NULL)
+ continue;
+ ptr = slotptr(type, p->offset);
+ if (!ptr || !*ptr)
+ continue;
+ if (PyDict_GetItem(dict, p->name_strobj))
+ continue;
+ if (*ptr == PyObject_HashNotImplemented) {
+ /* Classes may prevent the inheritance of the tp_hash
+ slot by storing PyObject_HashNotImplemented in it. Make it
+ visible as a None value for the __hash__ attribute. */
+ if (PyDict_SetItem(dict, p->name_strobj, Py_None) < 0)
+ return -1;
+ }
+ else {
+ descr = PyDescr_NewWrapper(type, p, *ptr);
+ if (descr == NULL)
+ return -1;
+ if (PyDict_SetItem(dict, p->name_strobj, descr) < 0)
+ return -1;
+ Py_DECREF(descr);
+ }
+ }
+ if (type->tp_new != NULL) {
+ if (add_tp_new_wrapper(type) < 0)
+ return -1;
+ }
+ return 0;
}
/* Cooperative 'super' */
typedef struct {
- PyObject_HEAD
- PyTypeObject *type;
- PyObject *obj;
- PyTypeObject *obj_type;
+ PyObject_HEAD
+ PyTypeObject *type;
+ PyObject *obj;
+ PyTypeObject *obj_type;
} superobject;
static PyMemberDef super_members[] = {
- {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
- "the class invoking super()"},
- {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
- "the instance invoking super(); may be None"},
- {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
- "the type of the instance invoking super(); may be None"},
- {0}
+ {"__thisclass__", T_OBJECT, offsetof(superobject, type), READONLY,
+ "the class invoking super()"},
+ {"__self__", T_OBJECT, offsetof(superobject, obj), READONLY,
+ "the instance invoking super(); may be None"},
+ {"__self_class__", T_OBJECT, offsetof(superobject, obj_type), READONLY,
+ "the type of the instance invoking super(); may be None"},
+ {0}
};
static void
super_dealloc(PyObject *self)
{
- superobject *su = (superobject *)self;
+ superobject *su = (superobject *)self;
- _PyObject_GC_UNTRACK(self);
- Py_XDECREF(su->obj);
- Py_XDECREF(su->type);
- Py_XDECREF(su->obj_type);
- Py_TYPE(self)->tp_free(self);
+ _PyObject_GC_UNTRACK(self);
+ Py_XDECREF(su->obj);
+ Py_XDECREF(su->type);
+ Py_XDECREF(su->obj_type);
+ Py_TYPE(self)->tp_free(self);
}
static PyObject *
super_repr(PyObject *self)
{
- superobject *su = (superobject *)self;
+ superobject *su = (superobject *)self;
- if (su->obj_type)
- return PyString_FromFormat(
- "<super: <class '%s'>, <%s object>>",
- su->type ? su->type->tp_name : "NULL",
- su->obj_type->tp_name);
- else
- return PyString_FromFormat(
- "<super: <class '%s'>, NULL>",
- su->type ? su->type->tp_name : "NULL");
+ if (su->obj_type)
+ return PyString_FromFormat(
+ "<super: <class '%s'>, <%s object>>",
+ su->type ? su->type->tp_name : "NULL",
+ su->obj_type->tp_name);
+ else
+ return PyString_FromFormat(
+ "<super: <class '%s'>, NULL>",
+ su->type ? su->type->tp_name : "NULL");
}
static PyObject *
super_getattro(PyObject *self, PyObject *name)
{
- superobject *su = (superobject *)self;
- int skip = su->obj_type == NULL;
-
- if (!skip) {
- /* We want __class__ to return the class of the super object
- (i.e. super, or a subclass), not the class of su->obj. */
- skip = (PyString_Check(name) &&
- PyString_GET_SIZE(name) == 9 &&
- strcmp(PyString_AS_STRING(name), "__class__") == 0);
- }
-
- if (!skip) {
- PyObject *mro, *res, *tmp, *dict;
- PyTypeObject *starttype;
- descrgetfunc f;
- Py_ssize_t i, n;
-
- starttype = su->obj_type;
- mro = starttype->tp_mro;
-
- if (mro == NULL)
- n = 0;
- else {
- assert(PyTuple_Check(mro));
- n = PyTuple_GET_SIZE(mro);
- }
- for (i = 0; i < n; i++) {
- if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
- break;
- }
- i++;
- res = NULL;
- for (; i < n; i++) {
- tmp = PyTuple_GET_ITEM(mro, i);
- if (PyType_Check(tmp))
- dict = ((PyTypeObject *)tmp)->tp_dict;
- else if (PyClass_Check(tmp))
- dict = ((PyClassObject *)tmp)->cl_dict;
- else
- continue;
- res = PyDict_GetItem(dict, name);
- if (res != NULL) {
- Py_INCREF(res);
- f = Py_TYPE(res)->tp_descr_get;
- if (f != NULL) {
- tmp = f(res,
- /* Only pass 'obj' param if
- this is instance-mode super
- (See SF ID #743627)
- */
- (su->obj == (PyObject *)
- su->obj_type
- ? (PyObject *)NULL
- : su->obj),
- (PyObject *)starttype);
- Py_DECREF(res);
- res = tmp;
- }
- return res;
- }
- }
- }
- return PyObject_GenericGetAttr(self, name);
+ superobject *su = (superobject *)self;
+ int skip = su->obj_type == NULL;
+
+ if (!skip) {
+ /* We want __class__ to return the class of the super object
+ (i.e. super, or a subclass), not the class of su->obj. */
+ skip = (PyString_Check(name) &&
+ PyString_GET_SIZE(name) == 9 &&
+ strcmp(PyString_AS_STRING(name), "__class__") == 0);
+ }
+
+ if (!skip) {
+ PyObject *mro, *res, *tmp, *dict;
+ PyTypeObject *starttype;
+ descrgetfunc f;
+ Py_ssize_t i, n;
+
+ starttype = su->obj_type;
+ mro = starttype->tp_mro;
+
+ if (mro == NULL)
+ n = 0;
+ else {
+ assert(PyTuple_Check(mro));
+ n = PyTuple_GET_SIZE(mro);
+ }
+ for (i = 0; i < n; i++) {
+ if ((PyObject *)(su->type) == PyTuple_GET_ITEM(mro, i))
+ break;
+ }
+ i++;
+ res = NULL;
+ for (; i < n; i++) {
+ tmp = PyTuple_GET_ITEM(mro, i);
+ if (PyType_Check(tmp))
+ dict = ((PyTypeObject *)tmp)->tp_dict;
+ else if (PyClass_Check(tmp))
+ dict = ((PyClassObject *)tmp)->cl_dict;
+ else
+ continue;
+ res = PyDict_GetItem(dict, name);
+ if (res != NULL) {
+ Py_INCREF(res);
+ f = Py_TYPE(res)->tp_descr_get;
+ if (f != NULL) {
+ tmp = f(res,
+ /* Only pass 'obj' param if
+ this is instance-mode super
+ (See SF ID #743627)
+ */
+ (su->obj == (PyObject *)
+ su->obj_type
+ ? (PyObject *)NULL
+ : su->obj),
+ (PyObject *)starttype);
+ Py_DECREF(res);
+ res = tmp;
+ }
+ return res;
+ }
+ }
+ }
+ return PyObject_GenericGetAttr(self, name);
}
static PyTypeObject *
supercheck(PyTypeObject *type, PyObject *obj)
{
- /* Check that a super() call makes sense. Return a type object.
-
- obj can be a new-style class, or an instance of one:
-
- - If it is a class, it must be a subclass of 'type'. This case is
- used for class methods; the return value is obj.
-
- - If it is an instance, it must be an instance of 'type'. This is
- the normal case; the return value is obj.__class__.
-
- But... when obj is an instance, we want to allow for the case where
- Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
- This will allow using super() with a proxy for obj.
- */
-
- /* Check for first bullet above (special case) */
- if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
- Py_INCREF(obj);
- return (PyTypeObject *)obj;
- }
-
- /* Normal case */
- if (PyType_IsSubtype(Py_TYPE(obj), type)) {
- Py_INCREF(Py_TYPE(obj));
- return Py_TYPE(obj);
- }
- else {
- /* Try the slow way */
- static PyObject *class_str = NULL;
- PyObject *class_attr;
-
- if (class_str == NULL) {
- class_str = PyString_FromString("__class__");
- if (class_str == NULL)
- return NULL;
- }
-
- class_attr = PyObject_GetAttr(obj, class_str);
-
- if (class_attr != NULL &&
- PyType_Check(class_attr) &&
- (PyTypeObject *)class_attr != Py_TYPE(obj))
- {
- int ok = PyType_IsSubtype(
- (PyTypeObject *)class_attr, type);
- if (ok)
- return (PyTypeObject *)class_attr;
- }
-
- if (class_attr == NULL)
- PyErr_Clear();
- else
- Py_DECREF(class_attr);
- }
-
- PyErr_SetString(PyExc_TypeError,
- "super(type, obj): "
- "obj must be an instance or subtype of type");
- return NULL;
+ /* Check that a super() call makes sense. Return a type object.
+
+ obj can be a new-style class, or an instance of one:
+
+ - If it is a class, it must be a subclass of 'type'. This case is
+ used for class methods; the return value is obj.
+
+ - If it is an instance, it must be an instance of 'type'. This is
+ the normal case; the return value is obj.__class__.
+
+ But... when obj is an instance, we want to allow for the case where
+ Py_TYPE(obj) is not a subclass of type, but obj.__class__ is!
+ This will allow using super() with a proxy for obj.
+ */
+
+ /* Check for first bullet above (special case) */
+ if (PyType_Check(obj) && PyType_IsSubtype((PyTypeObject *)obj, type)) {
+ Py_INCREF(obj);
+ return (PyTypeObject *)obj;
+ }
+
+ /* Normal case */
+ if (PyType_IsSubtype(Py_TYPE(obj), type)) {
+ Py_INCREF(Py_TYPE(obj));
+ return Py_TYPE(obj);
+ }
+ else {
+ /* Try the slow way */
+ static PyObject *class_str = NULL;
+ PyObject *class_attr;
+
+ if (class_str == NULL) {
+ class_str = PyString_FromString("__class__");
+ if (class_str == NULL)
+ return NULL;
+ }
+
+ class_attr = PyObject_GetAttr(obj, class_str);
+
+ if (class_attr != NULL &&
+ PyType_Check(class_attr) &&
+ (PyTypeObject *)class_attr != Py_TYPE(obj))
+ {
+ int ok = PyType_IsSubtype(
+ (PyTypeObject *)class_attr, type);
+ if (ok)
+ return (PyTypeObject *)class_attr;
+ }
+
+ if (class_attr == NULL)
+ PyErr_Clear();
+ else
+ Py_DECREF(class_attr);
+ }
+
+ PyErr_SetString(PyExc_TypeError,
+ "super(type, obj): "
+ "obj must be an instance or subtype of type");
+ return NULL;
}
static PyObject *
super_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
- superobject *su = (superobject *)self;
- superobject *newobj;
-
- if (obj == NULL || obj == Py_None || su->obj != NULL) {
- /* Not binding to an object, or already bound */
- Py_INCREF(self);
- return self;
- }
- if (Py_TYPE(su) != &PySuper_Type)
- /* If su is an instance of a (strict) subclass of super,
- call its type */
- return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
- su->type, obj, NULL);
- else {
- /* Inline the common case */
- PyTypeObject *obj_type = supercheck(su->type, obj);
- if (obj_type == NULL)
- return NULL;
- newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
- NULL, NULL);
- if (newobj == NULL)
- return NULL;
- Py_INCREF(su->type);
- Py_INCREF(obj);
- newobj->type = su->type;
- newobj->obj = obj;
- newobj->obj_type = obj_type;
- return (PyObject *)newobj;
- }
+ superobject *su = (superobject *)self;
+ superobject *newobj;
+
+ if (obj == NULL || obj == Py_None || su->obj != NULL) {
+ /* Not binding to an object, or already bound */
+ Py_INCREF(self);
+ return self;
+ }
+ if (Py_TYPE(su) != &PySuper_Type)
+ /* If su is an instance of a (strict) subclass of super,
+ call its type */
+ return PyObject_CallFunctionObjArgs((PyObject *)Py_TYPE(su),
+ su->type, obj, NULL);
+ else {
+ /* Inline the common case */
+ PyTypeObject *obj_type = supercheck(su->type, obj);
+ if (obj_type == NULL)
+ return NULL;
+ newobj = (superobject *)PySuper_Type.tp_new(&PySuper_Type,
+ NULL, NULL);
+ if (newobj == NULL)
+ return NULL;
+ Py_INCREF(su->type);
+ Py_INCREF(obj);
+ newobj->type = su->type;
+ newobj->obj = obj;
+ newobj->obj_type = obj_type;
+ return (PyObject *)newobj;
+ }
}
static int
super_init(PyObject *self, PyObject *args, PyObject *kwds)
{
- superobject *su = (superobject *)self;
- PyTypeObject *type;
- PyObject *obj = NULL;
- PyTypeObject *obj_type = NULL;
-
- if (!_PyArg_NoKeywords("super", kwds))
- return -1;
- if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
- return -1;
- if (obj == Py_None)
- obj = NULL;
- if (obj != NULL) {
- obj_type = supercheck(type, obj);
- if (obj_type == NULL)
- return -1;
- Py_INCREF(obj);
- }
- Py_INCREF(type);
- su->type = type;
- su->obj = obj;
- su->obj_type = obj_type;
- return 0;
+ superobject *su = (superobject *)self;
+ PyTypeObject *type;
+ PyObject *obj = NULL;
+ PyTypeObject *obj_type = NULL;
+
+ if (!_PyArg_NoKeywords("super", kwds))
+ return -1;
+ if (!PyArg_ParseTuple(args, "O!|O:super", &PyType_Type, &type, &obj))
+ return -1;
+ if (obj == Py_None)
+ obj = NULL;
+ if (obj != NULL) {
+ obj_type = supercheck(type, obj);
+ if (obj_type == NULL)
+ return -1;
+ Py_INCREF(obj);
+ }
+ Py_INCREF(type);
+ su->type = type;
+ su->obj = obj;
+ su->obj_type = obj_type;
+ return 0;
}
PyDoc_STRVAR(super_doc,
@@ -6656,60 +6656,60 @@ PyDoc_STRVAR(super_doc,
"Typical use to call a cooperative superclass method:\n"
"class C(B):\n"
" def meth(self, arg):\n"
-" super(C, self).meth(arg)");
+" super(C, self).meth(arg)");
static int
super_traverse(PyObject *self, visitproc visit, void *arg)
{
- superobject *su = (superobject *)self;
+ superobject *su = (superobject *)self;
- Py_VISIT(su->obj);
- Py_VISIT(su->type);
- Py_VISIT(su->obj_type);
+ Py_VISIT(su->obj);
+ Py_VISIT(su->type);
+ Py_VISIT(su->obj_type);
- return 0;
+ return 0;
}
PyTypeObject PySuper_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "super", /* tp_name */
- sizeof(superobject), /* tp_basicsize */
- 0, /* tp_itemsize */
- /* methods */
- super_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- super_repr, /* tp_repr */
- 0, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
- 0, /* tp_str */
- super_getattro, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
- Py_TPFLAGS_BASETYPE, /* tp_flags */
- super_doc, /* tp_doc */
- super_traverse, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- super_members, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
- super_descr_get, /* tp_descr_get */
- 0, /* tp_descr_set */
- 0, /* tp_dictoffset */
- super_init, /* tp_init */
- PyType_GenericAlloc, /* tp_alloc */
- PyType_GenericNew, /* tp_new */
- PyObject_GC_Del, /* tp_free */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "super", /* tp_name */
+ sizeof(superobject), /* tp_basicsize */
+ 0, /* tp_itemsize */
+ /* methods */
+ super_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ super_repr, /* tp_repr */
+ 0, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
+ 0, /* tp_str */
+ super_getattro, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
+ Py_TPFLAGS_BASETYPE, /* tp_flags */
+ super_doc, /* tp_doc */
+ super_traverse, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ super_members, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
+ super_descr_get, /* tp_descr_get */
+ 0, /* tp_descr_set */
+ 0, /* tp_dictoffset */
+ super_init, /* tp_init */
+ PyType_GenericAlloc, /* tp_alloc */
+ PyType_GenericNew, /* tp_new */
+ PyObject_GC_Del, /* tp_free */
};
diff --git a/Objects/weakrefobject.c b/Objects/weakrefobject.c
index 1a998b6..0e46d92 100644
--- a/Objects/weakrefobject.c
+++ b/Objects/weakrefobject.c
@@ -57,9 +57,9 @@ clear_weakref(PyWeakReference *self)
PyWeakref_GET_OBJECT(self));
if (*list == self)
- /* If 'self' is the end of the list (and thus self->wr_next == NULL)
- then the weakref list itself (and thus the value of *list) will
- end up being set to NULL. */
+ /* If 'self' is the end of the list (and thus self->wr_next == NULL)
+ then the weakref list itself (and thus the value of *list) will
+ end up being set to NULL. */
*list = self->wr_next;
self->wr_object = Py_None;
if (self->wr_prev != NULL)
@@ -161,21 +161,21 @@ weakref_repr(PyWeakReference *self)
PyOS_snprintf(buffer, sizeof(buffer), "<weakref at %p; dead>", self);
}
else {
- char *name = NULL;
- PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self),
- "__name__");
- if (nameobj == NULL)
- PyErr_Clear();
- else if (PyString_Check(nameobj))
- name = PyString_AS_STRING(nameobj);
+ char *name = NULL;
+ PyObject *nameobj = PyObject_GetAttrString(PyWeakref_GET_OBJECT(self),
+ "__name__");
+ if (nameobj == NULL)
+ PyErr_Clear();
+ else if (PyString_Check(nameobj))
+ name = PyString_AS_STRING(nameobj);
PyOS_snprintf(buffer, sizeof(buffer),
- name ? "<weakref at %p; to '%.50s' at %p (%s)>"
- : "<weakref at %p; to '%.50s' at %p>",
- self,
- Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name,
- PyWeakref_GET_OBJECT(self),
- name);
- Py_XDECREF(nameobj);
+ name ? "<weakref at %p; to '%.50s' at %p (%s)>"
+ : "<weakref at %p; to '%.50s' at %p>",
+ self,
+ Py_TYPE(PyWeakref_GET_OBJECT(self))->tp_name,
+ PyWeakref_GET_OBJECT(self),
+ name);
+ Py_XDECREF(nameobj);
}
return PyString_FromString(buffer);
}
@@ -337,10 +337,10 @@ _PyWeakref_RefType = {
sizeof(PyWeakReference),
0,
weakref_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
+ 0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
- 0, /*tp_compare*/
+ 0, /*tp_compare*/
(reprfunc)weakref_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
@@ -356,7 +356,7 @@ _PyWeakref_RefType = {
0, /*tp_doc*/
(traverseproc)gc_traverse, /*tp_traverse*/
(inquiry)gc_clear, /*tp_clear*/
- (richcmpfunc)weakref_richcompare, /*tp_richcompare*/
+ (richcmpfunc)weakref_richcompare, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
@@ -436,9 +436,9 @@ proxy_checkref(PyWeakReference *proxy)
#define WRAP_METHOD(method, special) \
static PyObject * \
method(PyObject *proxy) { \
- UNWRAP(proxy); \
- return PyObject_CallMethod(proxy, special, ""); \
- }
+ UNWRAP(proxy); \
+ return PyObject_CallMethod(proxy, special, ""); \
+ }
/* direct slots */
@@ -452,9 +452,9 @@ proxy_repr(PyWeakReference *proxy)
{
char buf[160];
PyOS_snprintf(buf, sizeof(buf),
- "<weakproxy at %p to %.100s at %p>", proxy,
- Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name,
- PyWeakref_GET_OBJECT(proxy));
+ "<weakproxy at %p to %.100s at %p>", proxy,
+ Py_TYPE(PyWeakref_GET_OBJECT(proxy))->tp_name,
+ PyWeakref_GET_OBJECT(proxy));
return PyString_FromString(buf);
}
@@ -604,8 +604,8 @@ WRAP_METHOD(proxy_unicode, "__unicode__");
static PyMethodDef proxy_methods[] = {
- {"__unicode__", (PyCFunction)proxy_unicode, METH_NOARGS},
- {NULL, NULL}
+ {"__unicode__", (PyCFunction)proxy_unicode, METH_NOARGS},
+ {NULL, NULL}
};
@@ -677,20 +677,20 @@ _PyWeakref_ProxyType = {
0,
/* methods */
(destructor)proxy_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- proxy_compare, /* tp_compare */
- (reprfunc)proxy_repr, /* tp_repr */
- &proxy_as_number, /* tp_as_number */
- &proxy_as_sequence, /* tp_as_sequence */
- &proxy_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- 0, /* tp_call */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ proxy_compare, /* tp_compare */
+ (reprfunc)proxy_repr, /* tp_repr */
+ &proxy_as_number, /* tp_as_number */
+ &proxy_as_sequence, /* tp_as_sequence */
+ &proxy_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ 0, /* tp_call */
proxy_str, /* tp_str */
proxy_getattr, /* tp_getattro */
(setattrofunc)proxy_setattr, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES, /* tp_flags */
0, /* tp_doc */
@@ -700,7 +700,7 @@ _PyWeakref_ProxyType = {
0, /* tp_weaklistoffset */
(getiterfunc)proxy_iter, /* tp_iter */
(iternextfunc)proxy_iternext, /* tp_iternext */
- proxy_methods, /* tp_methods */
+ proxy_methods, /* tp_methods */
};
@@ -712,20 +712,20 @@ _PyWeakref_CallableProxyType = {
0,
/* methods */
(destructor)proxy_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- proxy_compare, /* tp_compare */
- (unaryfunc)proxy_repr, /* tp_repr */
- &proxy_as_number, /* tp_as_number */
- &proxy_as_sequence, /* tp_as_sequence */
- &proxy_as_mapping, /* tp_as_mapping */
- 0, /* tp_hash */
- proxy_call, /* tp_call */
- proxy_str, /* tp_str */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ proxy_compare, /* tp_compare */
+ (unaryfunc)proxy_repr, /* tp_repr */
+ &proxy_as_number, /* tp_as_number */
+ &proxy_as_sequence, /* tp_as_sequence */
+ &proxy_as_mapping, /* tp_as_mapping */
+ 0, /* tp_hash */
+ proxy_call, /* tp_call */
+ proxy_str, /* tp_str */
proxy_getattr, /* tp_getattro */
(setattrofunc)proxy_setattr, /* tp_setattro */
- 0, /* tp_as_buffer */
+ 0, /* tp_as_buffer */
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC
| Py_TPFLAGS_CHECKTYPES, /* tp_flags */
0, /* tp_doc */
@@ -748,7 +748,7 @@ PyWeakref_NewRef(PyObject *ob, PyObject *callback)
if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) {
PyErr_Format(PyExc_TypeError,
- "cannot create weak reference to '%s' object",
+ "cannot create weak reference to '%s' object",
Py_TYPE(ob)->tp_name);
return NULL;
}
@@ -807,7 +807,7 @@ PyWeakref_NewProxy(PyObject *ob, PyObject *callback)
if (!PyType_SUPPORTS_WEAKREFS(Py_TYPE(ob))) {
PyErr_Format(PyExc_TypeError,
- "cannot create weak reference to '%s' object",
+ "cannot create weak reference to '%s' object",
Py_TYPE(ob)->tp_name);
return NULL;
}
@@ -932,7 +932,7 @@ PyObject_ClearWeakRefs(PyObject *object)
else {
PyObject *tuple;
Py_ssize_t i = 0;
-
+
tuple = PyTuple_New(count * 2);
if (tuple == NULL) {
if (restore_error)
diff --git a/PC/VS7.1/make_buildinfo.c b/PC/VS7.1/make_buildinfo.c
index 27580bb..2aa2b66 100644
--- a/PC/VS7.1/make_buildinfo.c
+++ b/PC/VS7.1/make_buildinfo.c
@@ -21,72 +21,72 @@
int make_buildinfo2()
{
- struct _stat st;
- HKEY hTortoise;
- char command[500];
- DWORD type, size;
- if (_stat(".svn", &st) < 0)
- return 0;
- /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
- if (_stat("no_subwcrev", &st) == 0)
- return 0;
- if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
- RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
- /* Tortoise not installed */
- return 0;
- command[0] = '"'; /* quote the path to the executable */
- size = sizeof(command) - 1;
- if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
- type != REG_SZ)
- /* Registry corrupted */
- return 0;
- strcat(command, "bin\\subwcrev.exe");
- if (_stat(command+1, &st) < 0)
- /* subwcrev.exe not part of the release */
- return 0;
- strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c");
- puts(command); fflush(stdout);
- if (system(command) < 0)
- return 0;
- return 1;
+ struct _stat st;
+ HKEY hTortoise;
+ char command[500];
+ DWORD type, size;
+ if (_stat(".svn", &st) < 0)
+ return 0;
+ /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
+ if (_stat("no_subwcrev", &st) == 0)
+ return 0;
+ if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
+ RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
+ /* Tortoise not installed */
+ return 0;
+ command[0] = '"'; /* quote the path to the executable */
+ size = sizeof(command) - 1;
+ if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
+ type != REG_SZ)
+ /* Registry corrupted */
+ return 0;
+ strcat(command, "bin\\subwcrev.exe");
+ if (_stat(command+1, &st) < 0)
+ /* subwcrev.exe not part of the release */
+ return 0;
+ strcat(command, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c");
+ puts(command); fflush(stdout);
+ if (system(command) < 0)
+ return 0;
+ return 1;
}
int main(int argc, char*argv[])
{
- char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
- int do_unlink, result;
- if (argc != 2) {
- fprintf(stderr, "make_buildinfo $(ConfigurationName)\n");
- return EXIT_FAILURE;
- }
- if (strcmp(argv[1], "Release") == 0) {
- strcat(command, "-MD ");
- }
- else if (strcmp(argv[1], "Debug") == 0) {
- strcat(command, "-D_DEBUG -MDd ");
- }
- else if (strcmp(argv[1], "ReleaseItanium") == 0) {
- strcat(command, "-MD /USECL:MS_ITANIUM ");
- }
- else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
- strcat(command, "-MD ");
- strcat(command, "-MD /USECL:MS_OPTERON ");
- }
- else {
- fprintf(stderr, "unsupported configuration %s\n", argv[1]);
- return EXIT_FAILURE;
- }
+ char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
+ int do_unlink, result;
+ if (argc != 2) {
+ fprintf(stderr, "make_buildinfo $(ConfigurationName)\n");
+ return EXIT_FAILURE;
+ }
+ if (strcmp(argv[1], "Release") == 0) {
+ strcat(command, "-MD ");
+ }
+ else if (strcmp(argv[1], "Debug") == 0) {
+ strcat(command, "-D_DEBUG -MDd ");
+ }
+ else if (strcmp(argv[1], "ReleaseItanium") == 0) {
+ strcat(command, "-MD /USECL:MS_ITANIUM ");
+ }
+ else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
+ strcat(command, "-MD ");
+ strcat(command, "-MD /USECL:MS_OPTERON ");
+ }
+ else {
+ fprintf(stderr, "unsupported configuration %s\n", argv[1]);
+ return EXIT_FAILURE;
+ }
- if ((do_unlink = make_buildinfo2()))
- strcat(command, "getbuildinfo2.c -DSUBWCREV ");
- else
- strcat(command, "..\\..\\Modules\\getbuildinfo.c");
- strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC");
- puts(command); fflush(stdout);
- result = system(command);
- if (do_unlink)
- unlink("getbuildinfo2.c");
- if (result < 0)
- return EXIT_FAILURE;
- return 0;
+ if ((do_unlink = make_buildinfo2()))
+ strcat(command, "getbuildinfo2.c -DSUBWCREV ");
+ else
+ strcat(command, "..\\..\\Modules\\getbuildinfo.c");
+ strcat(command, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC");
+ puts(command); fflush(stdout);
+ result = system(command);
+ if (do_unlink)
+ unlink("getbuildinfo2.c");
+ if (result < 0)
+ return EXIT_FAILURE;
+ return 0;
}
diff --git a/PC/VS8.0/make_buildinfo.c b/PC/VS8.0/make_buildinfo.c
index 133cfee..8cc3da2 100644
--- a/PC/VS8.0/make_buildinfo.c
+++ b/PC/VS8.0/make_buildinfo.c
@@ -23,72 +23,72 @@
int make_buildinfo2()
{
- struct _stat st;
- HKEY hTortoise;
- char command[CMD_SIZE+1];
- DWORD type, size;
- if (_stat(".svn", &st) < 0)
- return 0;
- /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
- if (_stat("no_subwcrev", &st) == 0)
- return 0;
- if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
- RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
- /* Tortoise not installed */
- return 0;
- command[0] = '"'; /* quote the path to the executable */
- size = sizeof(command) - 1;
- if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
- type != REG_SZ)
- /* Registry corrupted */
- return 0;
- strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe");
- if (_stat(command+1, &st) < 0)
- /* subwcrev.exe not part of the release */
- return 0;
- strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c");
- puts(command); fflush(stdout);
- if (system(command) < 0)
- return 0;
- return 1;
+ struct _stat st;
+ HKEY hTortoise;
+ char command[CMD_SIZE+1];
+ DWORD type, size;
+ if (_stat(".svn", &st) < 0)
+ return 0;
+ /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
+ if (_stat("no_subwcrev", &st) == 0)
+ return 0;
+ if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
+ RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
+ /* Tortoise not installed */
+ return 0;
+ command[0] = '"'; /* quote the path to the executable */
+ size = sizeof(command) - 1;
+ if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
+ type != REG_SZ)
+ /* Registry corrupted */
+ return 0;
+ strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe");
+ if (_stat(command+1, &st) < 0)
+ /* subwcrev.exe not part of the release */
+ return 0;
+ strcat_s(command, CMD_SIZE, "\" ..\\.. ..\\..\\Modules\\getbuildinfo.c getbuildinfo2.c");
+ puts(command); fflush(stdout);
+ if (system(command) < 0)
+ return 0;
+ return 1;
}
int main(int argc, char*argv[])
{
- char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
- int do_unlink, result;
- if (argc != 2) {
- fprintf(stderr, "make_buildinfo $(ConfigurationName)\n");
- return EXIT_FAILURE;
- }
- if (strcmp(argv[1], "Release") == 0) {
- strcat_s(command, CMD_SIZE, "-MD ");
- }
- else if (strcmp(argv[1], "Debug") == 0) {
- strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd ");
- }
- else if (strcmp(argv[1], "ReleaseItanium") == 0) {
- strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM ");
- }
- else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
- strcat_s(command, CMD_SIZE, "-MD ");
- strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON ");
- }
- else {
- fprintf(stderr, "unsupported configuration %s\n", argv[1]);
- return EXIT_FAILURE;
- }
+ char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
+ int do_unlink, result;
+ if (argc != 2) {
+ fprintf(stderr, "make_buildinfo $(ConfigurationName)\n");
+ return EXIT_FAILURE;
+ }
+ if (strcmp(argv[1], "Release") == 0) {
+ strcat_s(command, CMD_SIZE, "-MD ");
+ }
+ else if (strcmp(argv[1], "Debug") == 0) {
+ strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd ");
+ }
+ else if (strcmp(argv[1], "ReleaseItanium") == 0) {
+ strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM ");
+ }
+ else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
+ strcat_s(command, CMD_SIZE, "-MD ");
+ strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON ");
+ }
+ else {
+ fprintf(stderr, "unsupported configuration %s\n", argv[1]);
+ return EXIT_FAILURE;
+ }
- if ((do_unlink = make_buildinfo2()))
- strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV ");
- else
- strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c");
- strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC");
- puts(command); fflush(stdout);
- result = system(command);
- if (do_unlink)
- _unlink("getbuildinfo2.c");
- if (result < 0)
- return EXIT_FAILURE;
- return 0;
-} \ No newline at end of file
+ if ((do_unlink = make_buildinfo2()))
+ strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV ");
+ else
+ strcat_s(command, CMD_SIZE, "..\\..\\Modules\\getbuildinfo.c");
+ strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\..\\Include -I..\\..\\PC");
+ puts(command); fflush(stdout);
+ result = system(command);
+ if (do_unlink)
+ _unlink("getbuildinfo2.c");
+ if (result < 0)
+ return EXIT_FAILURE;
+ return 0;
+}
diff --git a/PC/_msi.c b/PC/_msi.c
index 58b2530..591fc4a 100644
--- a/PC/_msi.c
+++ b/PC/_msi.c
@@ -20,19 +20,19 @@ uuidcreate(PyObject* obj, PyObject*args)
UUID result;
char *cresult;
PyObject *oresult;
-
+
/* May return ok, local only, and no address.
For local only, the documentation says we still get a uuid.
For RPC_S_UUID_NO_ADDRESS, it's not clear whether we can
use the result. */
if (UuidCreate(&result) == RPC_S_UUID_NO_ADDRESS) {
- PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result");
- return NULL;
+ PyErr_SetString(PyExc_NotImplementedError, "processing 'no address' result");
+ return NULL;
}
if (UuidToString(&result, &cresult) == RPC_S_OUT_OF_MEMORY) {
- PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen");
- return NULL;
+ PyErr_SetString(PyExc_MemoryError, "out of memory in uuidgen");
+ return NULL;
}
oresult = PyString_FromString(cresult);
@@ -57,7 +57,7 @@ static FNFCIOPEN(cb_open)
{
int result = _open(pszFile, oflag, pmode);
if (result == -1)
- *err = errno;
+ *err = errno;
return result;
}
@@ -65,7 +65,7 @@ static FNFCIREAD(cb_read)
{
UINT result = (UINT)_read(hf, memory, cb);
if (result != cb)
- *err = errno;
+ *err = errno;
return result;
}
@@ -73,7 +73,7 @@ static FNFCIWRITE(cb_write)
{
UINT result = (UINT)_write(hf, memory, cb);
if (result != cb)
- *err = errno;
+ *err = errno;
return result;
}
@@ -81,7 +81,7 @@ static FNFCICLOSE(cb_close)
{
int result = _close(hf);
if (result != 0)
- *err = errno;
+ *err = errno;
return result;
}
@@ -89,7 +89,7 @@ static FNFCISEEK(cb_seek)
{
long result = (long)_lseek(hf, dist, seektype);
if (result == -1)
- *err = errno;
+ *err = errno;
return result;
}
@@ -97,7 +97,7 @@ static FNFCIDELETE(cb_delete)
{
int result = remove(pszFile);
if (result != 0)
- *err = errno;
+ *err = errno;
return result;
}
@@ -110,9 +110,9 @@ static FNFCIGETTEMPFILE(cb_gettempfile)
{
char *name = _tempnam("", "tmp");
if ((name != NULL) && ((int)strlen(name) < cbTempName)) {
- strcpy(pszTempName, name);
- free(name);
- return TRUE;
+ strcpy(pszTempName, name);
+ free(name);
+ return TRUE;
}
if (name) free(name);
@@ -122,10 +122,10 @@ static FNFCIGETTEMPFILE(cb_gettempfile)
static FNFCISTATUS(cb_status)
{
if (pv) {
- PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2);
- if (result == NULL)
- return -1;
- Py_DECREF(result);
+ PyObject *result = PyObject_CallMethod(pv, "status", "iii", typeStatus, cb1, cb2);
+ if (result == NULL)
+ return -1;
+ Py_DECREF(result);
}
return 0;
}
@@ -133,18 +133,18 @@ static FNFCISTATUS(cb_status)
static FNFCIGETNEXTCABINET(cb_getnextcabinet)
{
if (pv) {
- PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab);
- if (result == NULL)
- return -1;
- if (!PyString_Check(result)) {
- PyErr_Format(PyExc_TypeError,
- "Incorrect return type %s from getnextcabinet",
- result->ob_type->tp_name);
- Py_DECREF(result);
- return FALSE;
- }
- strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab));
- return TRUE;
+ PyObject *result = PyObject_CallMethod(pv, "getnextcabinet", "i", pccab->iCab);
+ if (result == NULL)
+ return -1;
+ if (!PyString_Check(result)) {
+ PyErr_Format(PyExc_TypeError,
+ "Incorrect return type %s from getnextcabinet",
+ result->ob_type->tp_name);
+ Py_DECREF(result);
+ return FALSE;
+ }
+ strncpy(pccab->szCab, PyString_AsString(result), sizeof(pccab->szCab));
+ return TRUE;
}
return FALSE;
}
@@ -157,21 +157,21 @@ static FNFCIGETOPENINFO(cb_getopeninfo)
/* Need Win32 handle to get time stamps */
handle = CreateFile(pszName, GENERIC_READ, FILE_SHARE_READ, NULL,
- OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
+ OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (handle == INVALID_HANDLE_VALUE)
- return -1;
+ return -1;
if (GetFileInformationByHandle(handle, &bhfi) == FALSE)
{
- CloseHandle(handle);
- return -1;
+ CloseHandle(handle);
+ return -1;
}
FileTimeToLocalFileTime(&bhfi.ftLastWriteTime, &filetime);
FileTimeToDosDateTime(&filetime, pdate, ptime);
- *pattribs = (int)(bhfi.dwFileAttributes &
- (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH));
+ *pattribs = (int)(bhfi.dwFileAttributes &
+ (_A_RDONLY | _A_SYSTEM | _A_HIDDEN | _A_ARCH));
CloseHandle(handle);
@@ -189,11 +189,11 @@ static PyObject* fcicreate(PyObject* obj, PyObject* args)
if (!PyArg_ParseTuple(args, "sO:FCICreate", &cabname, &files))
- return NULL;
+ return NULL;
if (!PyList_Check(files)) {
- PyErr_SetString(PyExc_TypeError, "FCICreate expects a list");
- return NULL;
+ PyErr_SetString(PyExc_TypeError, "FCICreate expects a list");
+ return NULL;
}
ccab.cb = INT_MAX; /* no need to split CAB into multiple media */
@@ -209,49 +209,49 @@ static PyObject* fcicreate(PyObject* obj, PyObject* args)
ccab.szDisk[0] = '\0';
for (i = 0, p = cabname; *p; p = CharNext(p))
- if (*p == '\\' || *p == '/')
- i = p - cabname + 1;
+ if (*p == '\\' || *p == '/')
+ i = p - cabname + 1;
if (i >= sizeof(ccab.szCabPath) ||
- strlen(cabname+i) >= sizeof(ccab.szCab)) {
- PyErr_SetString(PyExc_ValueError, "path name too long");
- return 0;
+ strlen(cabname+i) >= sizeof(ccab.szCab)) {
+ PyErr_SetString(PyExc_ValueError, "path name too long");
+ return 0;
}
if (i > 0) {
- memcpy(ccab.szCabPath, cabname, i);
- ccab.szCabPath[i] = '\0';
- strcpy(ccab.szCab, cabname+i);
+ memcpy(ccab.szCabPath, cabname, i);
+ ccab.szCabPath[i] = '\0';
+ strcpy(ccab.szCab, cabname+i);
} else {
- strcpy(ccab.szCabPath, ".\\");
- strcpy(ccab.szCab, cabname);
+ strcpy(ccab.szCabPath, ".\\");
+ strcpy(ccab.szCab, cabname);
}
hfci = FCICreate(&erf, cb_fileplaced, cb_alloc, cb_free,
- cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete,
- cb_gettempfile, &ccab, NULL);
+ cb_open, cb_read, cb_write, cb_close, cb_seek, cb_delete,
+ cb_gettempfile, &ccab, NULL);
if (hfci == NULL) {
- PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper);
- return NULL;
+ PyErr_Format(PyExc_ValueError, "FCI error %d", erf.erfOper);
+ return NULL;
}
for (i=0; i < PyList_GET_SIZE(files); i++) {
- PyObject *item = PyList_GET_ITEM(files, i);
- char *filename, *cabname;
- if (!PyArg_ParseTuple(item, "ss", &filename, &cabname))
- goto err;
- if (!FCIAddFile(hfci, filename, cabname, FALSE,
- cb_getnextcabinet, cb_status, cb_getopeninfo,
- tcompTYPE_MSZIP))
- goto err;
+ PyObject *item = PyList_GET_ITEM(files, i);
+ char *filename, *cabname;
+ if (!PyArg_ParseTuple(item, "ss", &filename, &cabname))
+ goto err;
+ if (!FCIAddFile(hfci, filename, cabname, FALSE,
+ cb_getnextcabinet, cb_status, cb_getopeninfo,
+ tcompTYPE_MSZIP))
+ goto err;
}
if (!FCIFlushCabinet(hfci, FALSE, cb_getnextcabinet, cb_status))
- goto err;
+ goto err;
if (!FCIDestroy(hfci))
- goto err;
+ goto err;
Py_INCREF(Py_None);
return Py_None;
@@ -266,7 +266,7 @@ typedef struct msiobj{
MSIHANDLE h;
}msiobj;
-static void
+static void
msiobj_dealloc(msiobj* msidb)
{
MsiCloseHandle(msidb->h);
@@ -292,41 +292,41 @@ msierror(int status)
MSIHANDLE err = MsiGetLastErrorRecord();
if (err == 0) {
- switch(status) {
- case ERROR_ACCESS_DENIED:
- PyErr_SetString(MSIError, "access denied");
- return NULL;
- case ERROR_FUNCTION_FAILED:
- PyErr_SetString(MSIError, "function failed");
- return NULL;
- case ERROR_INVALID_DATA:
- PyErr_SetString(MSIError, "invalid data");
- return NULL;
- case ERROR_INVALID_HANDLE:
- PyErr_SetString(MSIError, "invalid handle");
- return NULL;
- case ERROR_INVALID_STATE:
- PyErr_SetString(MSIError, "invalid state");
- return NULL;
- case ERROR_INVALID_PARAMETER:
- PyErr_SetString(MSIError, "invalid parameter");
- return NULL;
- default:
- PyErr_Format(MSIError, "unknown error %x", status);
- return NULL;
- }
+ switch(status) {
+ case ERROR_ACCESS_DENIED:
+ PyErr_SetString(MSIError, "access denied");
+ return NULL;
+ case ERROR_FUNCTION_FAILED:
+ PyErr_SetString(MSIError, "function failed");
+ return NULL;
+ case ERROR_INVALID_DATA:
+ PyErr_SetString(MSIError, "invalid data");
+ return NULL;
+ case ERROR_INVALID_HANDLE:
+ PyErr_SetString(MSIError, "invalid handle");
+ return NULL;
+ case ERROR_INVALID_STATE:
+ PyErr_SetString(MSIError, "invalid state");
+ return NULL;
+ case ERROR_INVALID_PARAMETER:
+ PyErr_SetString(MSIError, "invalid parameter");
+ return NULL;
+ default:
+ PyErr_Format(MSIError, "unknown error %x", status);
+ return NULL;
+ }
}
code = MsiRecordGetInteger(err, 1); /* XXX code */
if (MsiFormatRecord(0, err, res, &size) == ERROR_MORE_DATA) {
- res = malloc(size+1);
- MsiFormatRecord(0, err, res, &size);
- res[size]='\0';
+ res = malloc(size+1);
+ MsiFormatRecord(0, err, res, &size);
+ res[size]='\0';
}
MsiCloseHandle(err);
PyErr_SetString(MSIError, res);
if (res != buf)
- free(res);
+ free(res);
return NULL;
}
@@ -343,13 +343,13 @@ record_getinteger(msiobj* record, PyObject* args)
{
unsigned int field;
int status;
-
+
if (!PyArg_ParseTuple(args, "I:GetInteger", &field))
- return NULL;
+ return NULL;
status = MsiRecordGetInteger(record->h, field);
if (status == MSI_NULL_INTEGER){
- PyErr_SetString(MSIError, "could not convert record field to integer");
- return NULL;
+ PyErr_SetString(MSIError, "could not convert record field to integer");
+ return NULL;
}
return PyInt_FromLong((long) status);
}
@@ -363,21 +363,21 @@ record_getstring(msiobj* record, PyObject* args)
char *res = buf;
DWORD size = sizeof(buf);
PyObject* string;
-
+
if (!PyArg_ParseTuple(args, "I:GetString", &field))
- return NULL;
+ return NULL;
status = MsiRecordGetString(record->h, field, res, &size);
if (status == ERROR_MORE_DATA) {
- res = (char*) malloc(size + 1);
- if (res == NULL)
- return PyErr_NoMemory();
- status = MsiRecordGetString(record->h, field, res, &size);
+ res = (char*) malloc(size + 1);
+ if (res == NULL)
+ return PyErr_NoMemory();
+ status = MsiRecordGetString(record->h, field, res, &size);
}
if (status != ERROR_SUCCESS)
- return msierror((int) status);
+ return msierror((int) status);
string = PyString_FromString(res);
if (buf != res)
- free(res);
+ free(res);
return string;
}
@@ -386,7 +386,7 @@ record_cleardata(msiobj* record, PyObject *args)
{
int status = MsiRecordClearData(record->h);
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -400,10 +400,10 @@ record_setstring(msiobj* record, PyObject *args)
char *data;
if (!PyArg_ParseTuple(args, "is:SetString", &field, &data))
- return NULL;
+ return NULL;
if ((status = MsiRecordSetString(record->h, field, data)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -417,10 +417,10 @@ record_setstream(msiobj* record, PyObject *args)
char *data;
if (!PyArg_ParseTuple(args, "is:SetStream", &field, &data))
- return NULL;
+ return NULL;
if ((status = MsiRecordSetStream(record->h, field, data)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -434,10 +434,10 @@ record_setinteger(msiobj* record, PyObject *args)
int data;
if (!PyArg_ParseTuple(args, "ii:SetInteger", &field, &data))
- return NULL;
+ return NULL;
if ((status = MsiRecordSetInteger(record->h, field, data)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -446,65 +446,65 @@ record_setinteger(msiobj* record, PyObject *args)
static PyMethodDef record_methods[] = {
- { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS,
- PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")},
+ { "GetFieldCount", (PyCFunction)record_getfieldcount, METH_NOARGS,
+ PyDoc_STR("GetFieldCount() -> int\nWraps MsiRecordGetFieldCount")},
{ "GetInteger", (PyCFunction)record_getinteger, METH_VARARGS,
PyDoc_STR("GetInteger(field) -> int\nWraps MsiRecordGetInteger")},
{ "GetString", (PyCFunction)record_getstring, METH_VARARGS,
PyDoc_STR("GetString(field) -> string\nWraps MsiRecordGetString")},
- { "SetString", (PyCFunction)record_setstring, METH_VARARGS,
- PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")},
- { "SetStream", (PyCFunction)record_setstream, METH_VARARGS,
- PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")},
- { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS,
- PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")},
- { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS,
- PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")},
+ { "SetString", (PyCFunction)record_setstring, METH_VARARGS,
+ PyDoc_STR("SetString(field,str) -> None\nWraps MsiRecordSetString")},
+ { "SetStream", (PyCFunction)record_setstream, METH_VARARGS,
+ PyDoc_STR("SetStream(field,filename) -> None\nWraps MsiRecordSetInteger")},
+ { "SetInteger", (PyCFunction)record_setinteger, METH_VARARGS,
+ PyDoc_STR("SetInteger(field,int) -> None\nWraps MsiRecordSetInteger")},
+ { "ClearData", (PyCFunction)record_cleardata, METH_NOARGS,
+ PyDoc_STR("ClearData() -> int\nWraps MsiRecordGClearData")},
{ NULL, NULL }
};
static PyTypeObject record_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_msi.Record", /*tp_name*/
- sizeof(msiobj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)msiobj_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- record_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*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_msi.Record", /*tp_name*/
+ sizeof(msiobj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)msiobj_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ record_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*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
static PyObject*
@@ -513,8 +513,8 @@ record_new(MSIHANDLE h)
msiobj *result = PyObject_NEW(struct msiobj, &record_Type);
if (!result) {
- MsiCloseHandle(h);
- return NULL;
+ MsiCloseHandle(h);
+ return NULL;
}
result->h = h;
@@ -537,27 +537,27 @@ summary_getproperty(msiobj* si, PyObject *args)
DWORD ssize = sizeof(sval);
if (!PyArg_ParseTuple(args, "i:GetProperty", &field))
- return NULL;
+ return NULL;
- status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival,
- &fval, sval, &ssize);
+ status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival,
+ &fval, sval, &ssize);
if (status == ERROR_MORE_DATA) {
- sval = malloc(ssize);
- status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival,
- &fval, sval, &ssize);
+ sval = malloc(ssize);
+ status = MsiSummaryInfoGetProperty(si->h, field, &type, &ival,
+ &fval, sval, &ssize);
}
switch(type) {
- case VT_I2: case VT_I4:
- return PyInt_FromLong(ival);
- case VT_FILETIME:
- PyErr_SetString(PyExc_NotImplementedError, "FILETIME result");
- return NULL;
- case VT_LPSTR:
- result = PyString_FromStringAndSize(sval, ssize);
- if (sval != sbuf)
- free(sval);
- return result;
+ case VT_I2: case VT_I4:
+ return PyInt_FromLong(ival);
+ case VT_FILETIME:
+ PyErr_SetString(PyExc_NotImplementedError, "FILETIME result");
+ return NULL;
+ case VT_LPSTR:
+ result = PyString_FromStringAndSize(sval, ssize);
+ if (sval != sbuf)
+ free(sval);
+ return result;
}
PyErr_Format(PyExc_NotImplementedError, "result of type %d", type);
return NULL;
@@ -571,7 +571,7 @@ summary_getpropertycount(msiobj* si, PyObject *args)
status = MsiSummaryInfoGetPropertyCount(si->h, &result);
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
return PyInt_FromLong(result);
}
@@ -584,21 +584,21 @@ summary_setproperty(msiobj* si, PyObject *args)
PyObject* data;
if (!PyArg_ParseTuple(args, "iO:SetProperty", &field, &data))
- return NULL;
+ return NULL;
if (PyString_Check(data)) {
- status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR,
- 0, NULL, PyString_AsString(data));
+ status = MsiSummaryInfoSetProperty(si->h, field, VT_LPSTR,
+ 0, NULL, PyString_AsString(data));
} else if (PyInt_Check(data)) {
- status = MsiSummaryInfoSetProperty(si->h, field, VT_I4,
- PyInt_AsLong(data), NULL, NULL);
+ status = MsiSummaryInfoSetProperty(si->h, field, VT_I4,
+ PyInt_AsLong(data), NULL, NULL);
} else {
- PyErr_SetString(PyExc_TypeError, "unsupported type");
- return NULL;
+ PyErr_SetString(PyExc_TypeError, "unsupported type");
+ return NULL;
}
-
+
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -612,65 +612,65 @@ summary_persist(msiobj* si, PyObject *args)
status = MsiSummaryInfoPersist(si->h);
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef summary_methods[] = {
- { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS,
- PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")},
- { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS,
- PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")},
- { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS,
- PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")},
- { "Persist", (PyCFunction)summary_persist, METH_NOARGS,
- PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")},
+ { "GetProperty", (PyCFunction)summary_getproperty, METH_VARARGS,
+ PyDoc_STR("GetProperty(propid) -> value\nWraps MsiSummaryInfoGetProperty")},
+ { "GetPropertyCount", (PyCFunction)summary_getpropertycount, METH_NOARGS,
+ PyDoc_STR("GetProperty() -> int\nWraps MsiSummaryInfoGetPropertyCount")},
+ { "SetProperty", (PyCFunction)summary_setproperty, METH_VARARGS,
+ PyDoc_STR("SetProperty(value) -> None\nWraps MsiSummaryInfoProperty")},
+ { "Persist", (PyCFunction)summary_persist, METH_NOARGS,
+ PyDoc_STR("Persist() -> None\nWraps MsiSummaryInfoPersist")},
{ NULL, NULL }
};
static PyTypeObject summary_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_msi.SummaryInformation", /*tp_name*/
- sizeof(msiobj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)msiobj_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- summary_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*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_msi.SummaryInformation", /*tp_name*/
+ sizeof(msiobj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)msiobj_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ summary_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*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
/*************************** View objects **************/
@@ -683,19 +683,19 @@ view_execute(msiobj *view, PyObject*args)
PyObject *oparams = Py_None;
if (!PyArg_ParseTuple(args, "O:Execute", &oparams))
- return NULL;
+ return NULL;
if (oparams != Py_None) {
- if (oparams->ob_type != &record_Type) {
- PyErr_SetString(PyExc_TypeError, "Execute argument must be a record");
- return NULL;
- }
- params = ((msiobj*)oparams)->h;
+ if (oparams->ob_type != &record_Type) {
+ PyErr_SetString(PyExc_TypeError, "Execute argument must be a record");
+ return NULL;
+ }
+ params = ((msiobj*)oparams)->h;
}
status = MsiViewExecute(view->h, params);
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -708,7 +708,7 @@ view_fetch(msiobj *view, PyObject*args)
MSIHANDLE result;
if ((status = MsiViewFetch(view->h, &result)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
return record_new(result);
}
@@ -721,10 +721,10 @@ view_getcolumninfo(msiobj *view, PyObject *args)
MSIHANDLE result;
if (!PyArg_ParseTuple(args, "i:GetColumnInfo", &kind))
- return NULL;
+ return NULL;
if ((status = MsiViewGetColumnInfo(view->h, kind, &result)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
return record_new(result);
}
@@ -737,15 +737,15 @@ view_modify(msiobj *view, PyObject *args)
int status;
if (!PyArg_ParseTuple(args, "iO:Modify", &kind, &data))
- return NULL;
+ return NULL;
if (data->ob_type != &record_Type) {
- PyErr_SetString(PyExc_TypeError, "Modify expects a record object");
- return NULL;
+ PyErr_SetString(PyExc_TypeError, "Modify expects a record object");
+ return NULL;
}
if ((status = MsiViewModify(view->h, kind, ((msiobj*)data)->h)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -757,68 +757,68 @@ view_close(msiobj *view, PyObject*args)
int status;
if ((status = MsiViewClose(view->h)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
}
static PyMethodDef view_methods[] = {
- { "Execute", (PyCFunction)view_execute, METH_VARARGS,
- PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")},
+ { "Execute", (PyCFunction)view_execute, METH_VARARGS,
+ PyDoc_STR("Execute(params=None) -> None\nWraps MsiViewExecute")},
{ "GetColumnInfo", (PyCFunction)view_getcolumninfo, METH_VARARGS,
- PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")},
+ PyDoc_STR("GetColumnInfo() -> result\nWraps MsiGetColumnInfo")},
{ "Fetch", (PyCFunction)view_fetch, METH_NOARGS,
- PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")},
+ PyDoc_STR("Fetch() -> result\nWraps MsiViewFetch")},
{ "Modify", (PyCFunction)view_modify, METH_VARARGS,
- PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")},
+ PyDoc_STR("Modify(mode,record) -> None\nWraps MsiViewModify")},
{ "Close", (PyCFunction)view_close, METH_NOARGS,
- PyDoc_STR("Close() -> result\nWraps MsiViewClose")},
+ PyDoc_STR("Close() -> result\nWraps MsiViewClose")},
{ NULL, NULL }
};
static PyTypeObject msiview_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_msi.View", /*tp_name*/
- sizeof(msiobj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)msiobj_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- view_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*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_msi.View", /*tp_name*/
+ sizeof(msiobj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)msiobj_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ view_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*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
/*************************** Database objects **************/
@@ -832,15 +832,15 @@ msidb_openview(msiobj *msidb, PyObject *args)
msiobj *result;
if (!PyArg_ParseTuple(args, "s:OpenView", &sql))
- return NULL;
+ return NULL;
if ((status = MsiDatabaseOpenView(msidb->h, sql, &hView)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
result = PyObject_NEW(struct msiobj, &msiview_Type);
if (!result) {
- MsiCloseHandle(hView);
- return NULL;
+ MsiCloseHandle(hView);
+ return NULL;
}
result->h = hView;
@@ -853,7 +853,7 @@ msidb_commit(msiobj *msidb, PyObject *args)
int status;
if ((status = MsiDatabaseCommit(msidb->h)) != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
Py_INCREF(Py_None);
return Py_None;
@@ -868,16 +868,16 @@ msidb_getsummaryinformation(msiobj *db, PyObject *args)
msiobj *oresult;
if (!PyArg_ParseTuple(args, "i:GetSummaryInformation", &count))
- return NULL;
+ return NULL;
status = MsiGetSummaryInformation(db->h, NULL, count, &result);
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
oresult = PyObject_NEW(struct msiobj, &summary_Type);
if (!result) {
- MsiCloseHandle(result);
- return NULL;
+ MsiCloseHandle(result);
+ return NULL;
}
oresult->h = result;
@@ -885,57 +885,57 @@ msidb_getsummaryinformation(msiobj *db, PyObject *args)
}
static PyMethodDef db_methods[] = {
- { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS,
- PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")},
+ { "OpenView", (PyCFunction)msidb_openview, METH_VARARGS,
+ PyDoc_STR("OpenView(sql) -> viewobj\nWraps MsiDatabaseOpenView")},
{ "Commit", (PyCFunction)msidb_commit, METH_NOARGS,
- PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")},
- { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS,
- PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")},
+ PyDoc_STR("Commit() -> None\nWraps MsiDatabaseCommit")},
+ { "GetSummaryInformation", (PyCFunction)msidb_getsummaryinformation, METH_VARARGS,
+ PyDoc_STR("GetSummaryInformation(updateCount) -> viewobj\nWraps MsiGetSummaryInformation")},
{ NULL, NULL }
};
static PyTypeObject msidb_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "_msi.Database", /*tp_name*/
- sizeof(msiobj), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- /* methods */
- (destructor)msiobj_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*/
- PyObject_GenericSetAttr,/*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- 0, /*tp_doc*/
- 0, /*tp_traverse*/
- 0, /*tp_clear*/
- 0, /*tp_richcompare*/
- 0, /*tp_weaklistoffset*/
- 0, /*tp_iter*/
- 0, /*tp_iternext*/
- db_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*/
- 0, /*tp_new*/
- 0, /*tp_free*/
- 0, /*tp_is_gc*/
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "_msi.Database", /*tp_name*/
+ sizeof(msiobj), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ /* methods */
+ (destructor)msiobj_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*/
+ PyObject_GenericSetAttr,/*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ 0, /*tp_doc*/
+ 0, /*tp_traverse*/
+ 0, /*tp_clear*/
+ 0, /*tp_richcompare*/
+ 0, /*tp_weaklistoffset*/
+ 0, /*tp_iter*/
+ 0, /*tp_iternext*/
+ db_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*/
+ 0, /*tp_new*/
+ 0, /*tp_free*/
+ 0, /*tp_is_gc*/
};
static PyObject* msiopendb(PyObject *obj, PyObject *args)
@@ -945,18 +945,18 @@ static PyObject* msiopendb(PyObject *obj, PyObject *args)
int persist;
MSIHANDLE h;
msiobj *result;
-
+
if (!PyArg_ParseTuple(args, "si:MSIOpenDatabase", &path, &persist))
- return NULL;
+ return NULL;
- status = MsiOpenDatabase(path, (LPCSTR)persist, &h);
+ status = MsiOpenDatabase(path, (LPCSTR)persist, &h);
if (status != ERROR_SUCCESS)
- return msierror(status);
+ return msierror(status);
result = PyObject_NEW(struct msiobj, &msidb_Type);
if (!result) {
- MsiCloseHandle(h);
- return NULL;
+ MsiCloseHandle(h);
+ return NULL;
}
result->h = h;
return (PyObject*)result;
@@ -969,26 +969,26 @@ createrecord(PyObject *o, PyObject *args)
MSIHANDLE h;
if (!PyArg_ParseTuple(args, "i:CreateRecord", &count))
- return NULL;
-
+ return NULL;
+
h = MsiCreateRecord(count);
if (h == 0)
- return msierror(0);
+ return msierror(0);
return record_new(h);
}
static PyMethodDef msi_methods[] = {
- {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS,
- PyDoc_STR("UuidCreate() -> string")},
- {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS,
- PyDoc_STR("fcicreate(cabname,files) -> None")},
- {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS,
- PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")},
- {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS,
- PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")},
- {NULL, NULL} /* sentinel */
+ {"UuidCreate", (PyCFunction)uuidcreate, METH_NOARGS,
+ PyDoc_STR("UuidCreate() -> string")},
+ {"FCICreate", (PyCFunction)fcicreate, METH_VARARGS,
+ PyDoc_STR("fcicreate(cabname,files) -> None")},
+ {"OpenDatabase", (PyCFunction)msiopendb, METH_VARARGS,
+ PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiOpenDatabase")},
+ {"CreateRecord", (PyCFunction)createrecord, METH_VARARGS,
+ PyDoc_STR("OpenDatabase(name, flags) -> dbobj\nWraps MsiCreateRecord")},
+ {NULL, NULL} /* sentinel */
};
static char msi_doc[] = "Documentation";
@@ -1000,7 +1000,7 @@ init_msi(void)
m = Py_InitModule3("_msi", msi_methods, msi_doc);
if (m == NULL)
- return;
+ return;
PyModule_AddIntConstant(m, "MSIDBOPEN_CREATEDIRECT", (int)MSIDBOPEN_CREATEDIRECT);
PyModule_AddIntConstant(m, "MSIDBOPEN_CREATE", (int)MSIDBOPEN_CREATE);
@@ -1046,6 +1046,6 @@ init_msi(void)
MSIError = PyErr_NewException ("_msi.MSIError", NULL, NULL);
if (!MSIError)
- return;
+ return;
PyModule_AddObject(m, "MSIError", MSIError);
}
diff --git a/PC/_subprocess.c b/PC/_subprocess.c
index bbe75ff..6780382 100644
--- a/PC/_subprocess.c
+++ b/PC/_subprocess.c
@@ -49,8 +49,8 @@
the wrapper is used to provide Detach and Close methods */
typedef struct {
- PyObject_HEAD
- HANDLE handle;
+ PyObject_HEAD
+ HANDLE handle;
} sp_handle_object;
staticforward PyTypeObject sp_handle_type;
@@ -58,97 +58,97 @@ staticforward PyTypeObject sp_handle_type;
static PyObject*
sp_handle_new(HANDLE handle)
{
- sp_handle_object* self;
+ sp_handle_object* self;
- self = PyObject_NEW(sp_handle_object, &sp_handle_type);
- if (self == NULL)
- return NULL;
+ self = PyObject_NEW(sp_handle_object, &sp_handle_type);
+ if (self == NULL)
+ return NULL;
- self->handle = handle;
+ self->handle = handle;
- return (PyObject*) self;
+ return (PyObject*) self;
}
#if defined(MS_WIN32) && !defined(MS_WIN64)
-#define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle)
-#define PY_HANDLE_PARAM "l"
+#define HANDLE_TO_PYNUM(handle) PyInt_FromLong((long) handle)
+#define PY_HANDLE_PARAM "l"
#else
-#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle)
-#define PY_HANDLE_PARAM "L"
+#define HANDLE_TO_PYNUM(handle) PyLong_FromLongLong((long long) handle)
+#define PY_HANDLE_PARAM "L"
#endif
static PyObject*
sp_handle_detach(sp_handle_object* self, PyObject* args)
{
- HANDLE handle;
+ HANDLE handle;
- if (! PyArg_ParseTuple(args, ":Detach"))
- return NULL;
+ if (! PyArg_ParseTuple(args, ":Detach"))
+ return NULL;
- handle = self->handle;
+ handle = self->handle;
- self->handle = INVALID_HANDLE_VALUE;
+ self->handle = INVALID_HANDLE_VALUE;
- /* note: return the current handle, as an integer */
- return HANDLE_TO_PYNUM(handle);
+ /* note: return the current handle, as an integer */
+ return HANDLE_TO_PYNUM(handle);
}
static PyObject*
sp_handle_close(sp_handle_object* self, PyObject* args)
{
- if (! PyArg_ParseTuple(args, ":Close"))
- return NULL;
-
- if (self->handle != INVALID_HANDLE_VALUE) {
- CloseHandle(self->handle);
- self->handle = INVALID_HANDLE_VALUE;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ if (! PyArg_ParseTuple(args, ":Close"))
+ return NULL;
+
+ if (self->handle != INVALID_HANDLE_VALUE) {
+ CloseHandle(self->handle);
+ self->handle = INVALID_HANDLE_VALUE;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
sp_handle_dealloc(sp_handle_object* self)
{
- if (self->handle != INVALID_HANDLE_VALUE)
- CloseHandle(self->handle);
- PyObject_FREE(self);
+ if (self->handle != INVALID_HANDLE_VALUE)
+ CloseHandle(self->handle);
+ PyObject_FREE(self);
}
static PyMethodDef sp_handle_methods[] = {
- {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS},
- {"Close", (PyCFunction) sp_handle_close, METH_VARARGS},
- {NULL, NULL}
+ {"Detach", (PyCFunction) sp_handle_detach, METH_VARARGS},
+ {"Close", (PyCFunction) sp_handle_close, METH_VARARGS},
+ {NULL, NULL}
};
static PyObject*
sp_handle_getattr(sp_handle_object* self, char* name)
{
- return Py_FindMethod(sp_handle_methods, (PyObject*) self, name);
+ return Py_FindMethod(sp_handle_methods, (PyObject*) self, name);
}
static PyObject*
sp_handle_as_int(sp_handle_object* self)
{
- return HANDLE_TO_PYNUM(self->handle);
+ return HANDLE_TO_PYNUM(self->handle);
}
static PyNumberMethods sp_handle_as_number;
statichere PyTypeObject sp_handle_type = {
- PyObject_HEAD_INIT(NULL)
- 0, /*ob_size*/
- "_subprocess_handle", sizeof(sp_handle_object), 0,
- (destructor) sp_handle_dealloc, /*tp_dealloc*/
- 0, /*tp_print*/
- (getattrfunc) sp_handle_getattr,/*tp_getattr*/
- 0, /*tp_setattr*/
- 0, /*tp_compare*/
- 0, /*tp_repr*/
- &sp_handle_as_number, /*tp_as_number */
- 0, /*tp_as_sequence */
- 0, /*tp_as_mapping */
- 0 /*tp_hash*/
+ PyObject_HEAD_INIT(NULL)
+ 0, /*ob_size*/
+ "_subprocess_handle", sizeof(sp_handle_object), 0,
+ (destructor) sp_handle_dealloc, /*tp_dealloc*/
+ 0, /*tp_print*/
+ (getattrfunc) sp_handle_getattr,/*tp_getattr*/
+ 0, /*tp_setattr*/
+ 0, /*tp_compare*/
+ 0, /*tp_repr*/
+ &sp_handle_as_number, /*tp_as_number */
+ 0, /*tp_as_sequence */
+ 0, /*tp_as_mapping */
+ 0 /*tp_hash*/
};
/* -------------------------------------------------------------------- */
@@ -164,26 +164,26 @@ The integer associated with the handle object is returned.");
static PyObject *
sp_GetStdHandle(PyObject* self, PyObject* args)
{
- HANDLE handle;
- int std_handle;
+ HANDLE handle;
+ int std_handle;
- if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle))
- return NULL;
+ if (! PyArg_ParseTuple(args, "i:GetStdHandle", &std_handle))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- handle = GetStdHandle((DWORD) std_handle);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ handle = GetStdHandle((DWORD) std_handle);
+ Py_END_ALLOW_THREADS
- if (handle == INVALID_HANDLE_VALUE)
- return PyErr_SetFromWindowsErr(GetLastError());
+ if (handle == INVALID_HANDLE_VALUE)
+ return PyErr_SetFromWindowsErr(GetLastError());
- if (! handle) {
- Py_INCREF(Py_None);
- return Py_None;
- }
+ if (! handle) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
- /* note: returns integer, not handle object */
- return HANDLE_TO_PYNUM(handle);
+ /* note: returns integer, not handle object */
+ return HANDLE_TO_PYNUM(handle);
}
PyDoc_STRVAR(GetCurrentProcess_doc,
@@ -194,10 +194,10 @@ Return a handle object for the current process.");
static PyObject *
sp_GetCurrentProcess(PyObject* self, PyObject* args)
{
- if (! PyArg_ParseTuple(args, ":GetCurrentProcess"))
- return NULL;
+ if (! PyArg_ParseTuple(args, ":GetCurrentProcess"))
+ return NULL;
- return sp_handle_new(GetCurrentProcess());
+ return sp_handle_new(GetCurrentProcess());
}
PyDoc_STRVAR(DuplicateHandle_doc,
@@ -214,43 +214,43 @@ through both handles.");
static PyObject *
sp_DuplicateHandle(PyObject* self, PyObject* args)
{
- HANDLE target_handle;
- BOOL result;
-
- HANDLE source_process_handle;
- HANDLE source_handle;
- HANDLE target_process_handle;
- int desired_access;
- int inherit_handle;
- int options = 0;
-
- if (! PyArg_ParseTuple(args,
- PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM
- "ii|i:DuplicateHandle",
- &source_process_handle,
- &source_handle,
- &target_process_handle,
- &desired_access,
- &inherit_handle,
- &options))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- result = DuplicateHandle(
- source_process_handle,
- source_handle,
- target_process_handle,
- &target_handle,
- desired_access,
- inherit_handle,
- options
- );
- Py_END_ALLOW_THREADS
-
- if (! result)
- return PyErr_SetFromWindowsErr(GetLastError());
-
- return sp_handle_new(target_handle);
+ HANDLE target_handle;
+ BOOL result;
+
+ HANDLE source_process_handle;
+ HANDLE source_handle;
+ HANDLE target_process_handle;
+ int desired_access;
+ int inherit_handle;
+ int options = 0;
+
+ if (! PyArg_ParseTuple(args,
+ PY_HANDLE_PARAM PY_HANDLE_PARAM PY_HANDLE_PARAM
+ "ii|i:DuplicateHandle",
+ &source_process_handle,
+ &source_handle,
+ &target_process_handle,
+ &desired_access,
+ &inherit_handle,
+ &options))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ result = DuplicateHandle(
+ source_process_handle,
+ source_handle,
+ target_process_handle,
+ &target_handle,
+ desired_access,
+ inherit_handle,
+ options
+ );
+ Py_END_ALLOW_THREADS
+
+ if (! result)
+ return PyErr_SetFromWindowsErr(GetLastError());
+
+ return sp_handle_new(target_handle);
}
PyDoc_STRVAR(CreatePipe_doc,
@@ -264,25 +264,25 @@ pipe_attrs is ignored internally and can be None.");
static PyObject *
sp_CreatePipe(PyObject* self, PyObject* args)
{
- HANDLE read_pipe;
- HANDLE write_pipe;
- BOOL result;
+ HANDLE read_pipe;
+ HANDLE write_pipe;
+ BOOL result;
- PyObject* pipe_attributes; /* ignored */
- int size;
+ PyObject* pipe_attributes; /* ignored */
+ int size;
- if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size))
- return NULL;
+ if (! PyArg_ParseTuple(args, "Oi:CreatePipe", &pipe_attributes, &size))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ result = CreatePipe(&read_pipe, &write_pipe, NULL, size);
+ Py_END_ALLOW_THREADS
- if (! result)
- return PyErr_SetFromWindowsErr(GetLastError());
+ if (! result)
+ return PyErr_SetFromWindowsErr(GetLastError());
- return Py_BuildValue(
- "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe));
+ return Py_BuildValue(
+ "NN", sp_handle_new(read_pipe), sp_handle_new(write_pipe));
}
/* helpers for createprocess */
@@ -290,110 +290,110 @@ sp_CreatePipe(PyObject* self, PyObject* args)
static int
getint(PyObject* obj, char* name)
{
- PyObject* value;
- int ret;
-
- value = PyObject_GetAttrString(obj, name);
- if (! value) {
- PyErr_Clear(); /* FIXME: propagate error? */
- return 0;
- }
- ret = (int) PyInt_AsLong(value);
- Py_DECREF(value);
- return ret;
+ PyObject* value;
+ int ret;
+
+ value = PyObject_GetAttrString(obj, name);
+ if (! value) {
+ PyErr_Clear(); /* FIXME: propagate error? */
+ return 0;
+ }
+ ret = (int) PyInt_AsLong(value);
+ Py_DECREF(value);
+ return ret;
}
static HANDLE
gethandle(PyObject* obj, char* name)
{
- sp_handle_object* value;
- HANDLE ret;
-
- value = (sp_handle_object*) PyObject_GetAttrString(obj, name);
- if (! value) {
- PyErr_Clear(); /* FIXME: propagate error? */
- return NULL;
- }
- if (value->ob_type != &sp_handle_type)
- ret = NULL;
- else
- ret = value->handle;
- Py_DECREF(value);
- return ret;
+ sp_handle_object* value;
+ HANDLE ret;
+
+ value = (sp_handle_object*) PyObject_GetAttrString(obj, name);
+ if (! value) {
+ PyErr_Clear(); /* FIXME: propagate error? */
+ return NULL;
+ }
+ if (value->ob_type != &sp_handle_type)
+ ret = NULL;
+ else
+ ret = value->handle;
+ Py_DECREF(value);
+ return ret;
}
static PyObject*
getenvironment(PyObject* environment)
{
- int i, envsize;
- PyObject* out = NULL;
- PyObject* keys;
- PyObject* values;
- char* p;
-
- /* convert environment dictionary to windows enviroment string */
- if (! PyMapping_Check(environment)) {
- PyErr_SetString(
- PyExc_TypeError, "environment must be dictionary or None");
- return NULL;
- }
-
- envsize = PyMapping_Length(environment);
-
- keys = PyMapping_Keys(environment);
- values = PyMapping_Values(environment);
- if (!keys || !values)
- goto error;
-
- out = PyString_FromStringAndSize(NULL, 2048);
- if (! out)
- goto error;
-
- p = PyString_AS_STRING(out);
-
- for (i = 0; i < envsize; i++) {
- int ksize, vsize, totalsize;
- PyObject* key = PyList_GET_ITEM(keys, i);
- PyObject* value = PyList_GET_ITEM(values, i);
-
- if (! PyString_Check(key) || ! PyString_Check(value)) {
- PyErr_SetString(PyExc_TypeError,
- "environment can only contain strings");
- goto error;
- }
- ksize = PyString_GET_SIZE(key);
- vsize = PyString_GET_SIZE(value);
- totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 +
- vsize + 1 + 1;
- if (totalsize > PyString_GET_SIZE(out)) {
- int offset = p - PyString_AS_STRING(out);
- _PyString_Resize(&out, totalsize + 1024);
- p = PyString_AS_STRING(out) + offset;
- }
- memcpy(p, PyString_AS_STRING(key), ksize);
- p += ksize;
- *p++ = '=';
- memcpy(p, PyString_AS_STRING(value), vsize);
- p += vsize;
- *p++ = '\0';
- }
-
- /* add trailing null byte */
- *p++ = '\0';
- _PyString_Resize(&out, p - PyString_AS_STRING(out));
-
- /* PyObject_Print(out, stdout, 0); */
-
- Py_XDECREF(keys);
- Py_XDECREF(values);
-
- return out;
+ int i, envsize;
+ PyObject* out = NULL;
+ PyObject* keys;
+ PyObject* values;
+ char* p;
+
+ /* convert environment dictionary to windows enviroment string */
+ if (! PyMapping_Check(environment)) {
+ PyErr_SetString(
+ PyExc_TypeError, "environment must be dictionary or None");
+ return NULL;
+ }
+
+ envsize = PyMapping_Length(environment);
+
+ keys = PyMapping_Keys(environment);
+ values = PyMapping_Values(environment);
+ if (!keys || !values)
+ goto error;
+
+ out = PyString_FromStringAndSize(NULL, 2048);
+ if (! out)
+ goto error;
+
+ p = PyString_AS_STRING(out);
+
+ for (i = 0; i < envsize; i++) {
+ int ksize, vsize, totalsize;
+ PyObject* key = PyList_GET_ITEM(keys, i);
+ PyObject* value = PyList_GET_ITEM(values, i);
+
+ if (! PyString_Check(key) || ! PyString_Check(value)) {
+ PyErr_SetString(PyExc_TypeError,
+ "environment can only contain strings");
+ goto error;
+ }
+ ksize = PyString_GET_SIZE(key);
+ vsize = PyString_GET_SIZE(value);
+ totalsize = (p - PyString_AS_STRING(out)) + ksize + 1 +
+ vsize + 1 + 1;
+ if (totalsize > PyString_GET_SIZE(out)) {
+ int offset = p - PyString_AS_STRING(out);
+ _PyString_Resize(&out, totalsize + 1024);
+ p = PyString_AS_STRING(out) + offset;
+ }
+ memcpy(p, PyString_AS_STRING(key), ksize);
+ p += ksize;
+ *p++ = '=';
+ memcpy(p, PyString_AS_STRING(value), vsize);
+ p += vsize;
+ *p++ = '\0';
+ }
+
+ /* add trailing null byte */
+ *p++ = '\0';
+ _PyString_Resize(&out, p - PyString_AS_STRING(out));
+
+ /* PyObject_Print(out, stdout, 0); */
+
+ Py_XDECREF(keys);
+ Py_XDECREF(values);
+
+ return out;
error:
- Py_XDECREF(out);
- Py_XDECREF(keys);
- Py_XDECREF(values);
- return NULL;
+ Py_XDECREF(out);
+ Py_XDECREF(keys);
+ Py_XDECREF(values);
+ return NULL;
}
PyDoc_STRVAR(CreateProcess_doc,
@@ -411,77 +411,77 @@ proc_attrs and thread_attrs are ignored internally and can be None.");
static PyObject *
sp_CreateProcess(PyObject* self, PyObject* args)
{
- BOOL result;
- PROCESS_INFORMATION pi;
- STARTUPINFO si;
- PyObject* environment;
-
- char* application_name;
- char* command_line;
- PyObject* process_attributes; /* ignored */
- PyObject* thread_attributes; /* ignored */
- int inherit_handles;
- int creation_flags;
- PyObject* env_mapping;
- char* current_directory;
- PyObject* startup_info;
-
- if (! PyArg_ParseTuple(args, "zzOOiiOzO:CreateProcess",
- &application_name,
- &command_line,
- &process_attributes,
- &thread_attributes,
- &inherit_handles,
- &creation_flags,
- &env_mapping,
- &current_directory,
- &startup_info))
- return NULL;
-
- ZeroMemory(&si, sizeof(si));
- si.cb = sizeof(si);
-
- /* note: we only support a small subset of all SI attributes */
- si.dwFlags = getint(startup_info, "dwFlags");
- si.wShowWindow = getint(startup_info, "wShowWindow");
- si.hStdInput = gethandle(startup_info, "hStdInput");
- si.hStdOutput = gethandle(startup_info, "hStdOutput");
- si.hStdError = gethandle(startup_info, "hStdError");
-
- if (PyErr_Occurred())
- return NULL;
-
- if (env_mapping == Py_None)
- environment = NULL;
- else {
- environment = getenvironment(env_mapping);
- if (! environment)
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- result = CreateProcess(application_name,
- command_line,
- NULL,
- NULL,
- inherit_handles,
- creation_flags,
- environment ? PyString_AS_STRING(environment) : NULL,
- current_directory,
- &si,
- &pi);
- Py_END_ALLOW_THREADS
-
- Py_XDECREF(environment);
-
- if (! result)
- return PyErr_SetFromWindowsErr(GetLastError());
-
- return Py_BuildValue("NNii",
- sp_handle_new(pi.hProcess),
- sp_handle_new(pi.hThread),
- pi.dwProcessId,
- pi.dwThreadId);
+ BOOL result;
+ PROCESS_INFORMATION pi;
+ STARTUPINFO si;
+ PyObject* environment;
+
+ char* application_name;
+ char* command_line;
+ PyObject* process_attributes; /* ignored */
+ PyObject* thread_attributes; /* ignored */
+ int inherit_handles;
+ int creation_flags;
+ PyObject* env_mapping;
+ char* current_directory;
+ PyObject* startup_info;
+
+ if (! PyArg_ParseTuple(args, "zzOOiiOzO:CreateProcess",
+ &application_name,
+ &command_line,
+ &process_attributes,
+ &thread_attributes,
+ &inherit_handles,
+ &creation_flags,
+ &env_mapping,
+ &current_directory,
+ &startup_info))
+ return NULL;
+
+ ZeroMemory(&si, sizeof(si));
+ si.cb = sizeof(si);
+
+ /* note: we only support a small subset of all SI attributes */
+ si.dwFlags = getint(startup_info, "dwFlags");
+ si.wShowWindow = getint(startup_info, "wShowWindow");
+ si.hStdInput = gethandle(startup_info, "hStdInput");
+ si.hStdOutput = gethandle(startup_info, "hStdOutput");
+ si.hStdError = gethandle(startup_info, "hStdError");
+
+ if (PyErr_Occurred())
+ return NULL;
+
+ if (env_mapping == Py_None)
+ environment = NULL;
+ else {
+ environment = getenvironment(env_mapping);
+ if (! environment)
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ result = CreateProcess(application_name,
+ command_line,
+ NULL,
+ NULL,
+ inherit_handles,
+ creation_flags,
+ environment ? PyString_AS_STRING(environment) : NULL,
+ current_directory,
+ &si,
+ &pi);
+ Py_END_ALLOW_THREADS
+
+ Py_XDECREF(environment);
+
+ if (! result)
+ return PyErr_SetFromWindowsErr(GetLastError());
+
+ return Py_BuildValue("NNii",
+ sp_handle_new(pi.hProcess),
+ sp_handle_new(pi.hThread),
+ pi.dwProcessId,
+ pi.dwThreadId);
}
PyDoc_STRVAR(TerminateProcess_doc,
@@ -492,21 +492,21 @@ Terminate the specified process and all of its threads.");
static PyObject *
sp_TerminateProcess(PyObject* self, PyObject* args)
{
- BOOL result;
+ BOOL result;
- HANDLE process;
- int exit_code;
- if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess",
- &process, &exit_code))
- return NULL;
+ HANDLE process;
+ int exit_code;
+ if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:TerminateProcess",
+ &process, &exit_code))
+ return NULL;
- result = TerminateProcess(process, exit_code);
+ result = TerminateProcess(process, exit_code);
- if (! result)
- return PyErr_SetFromWindowsErr(GetLastError());
+ if (! result)
+ return PyErr_SetFromWindowsErr(GetLastError());
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(GetExitCodeProcess_doc,
@@ -517,19 +517,19 @@ Return the termination status of the specified process.");
static PyObject *
sp_GetExitCodeProcess(PyObject* self, PyObject* args)
{
- DWORD exit_code;
- BOOL result;
+ DWORD exit_code;
+ BOOL result;
- HANDLE process;
- if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process))
- return NULL;
+ HANDLE process;
+ if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetExitCodeProcess", &process))
+ return NULL;
- result = GetExitCodeProcess(process, &exit_code);
+ result = GetExitCodeProcess(process, &exit_code);
- if (! result)
- return PyErr_SetFromWindowsErr(GetLastError());
+ if (! result)
+ return PyErr_SetFromWindowsErr(GetLastError());
- return PyInt_FromLong(exit_code);
+ return PyInt_FromLong(exit_code);
}
PyDoc_STRVAR(WaitForSingleObject_doc,
@@ -542,23 +542,23 @@ in milliseconds.");
static PyObject *
sp_WaitForSingleObject(PyObject* self, PyObject* args)
{
- DWORD result;
+ DWORD result;
- HANDLE handle;
- int milliseconds;
- if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject",
- &handle,
- &milliseconds))
- return NULL;
+ HANDLE handle;
+ int milliseconds;
+ if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM "i:WaitForSingleObject",
+ &handle,
+ &milliseconds))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- result = WaitForSingleObject(handle, (DWORD) milliseconds);
- Py_END_ALLOW_THREADS
+ Py_BEGIN_ALLOW_THREADS
+ result = WaitForSingleObject(handle, (DWORD) milliseconds);
+ Py_END_ALLOW_THREADS
- if (result == WAIT_FAILED)
- return PyErr_SetFromWindowsErr(GetLastError());
+ if (result == WAIT_FAILED)
+ return PyErr_SetFromWindowsErr(GetLastError());
- return PyInt_FromLong((int) result);
+ return PyInt_FromLong((int) result);
}
PyDoc_STRVAR(GetVersion_doc,
@@ -569,10 +569,10 @@ Return the version number of the current operating system.");
static PyObject *
sp_GetVersion(PyObject* self, PyObject* args)
{
- if (! PyArg_ParseTuple(args, ":GetVersion"))
- return NULL;
+ if (! PyArg_ParseTuple(args, ":GetVersion"))
+ return NULL;
- return PyInt_FromLong((int) GetVersion());
+ return PyInt_FromLong((int) GetVersion());
}
PyDoc_STRVAR(GetModuleFileName_doc,
@@ -590,41 +590,41 @@ of the current process.");
static PyObject *
sp_GetModuleFileName(PyObject* self, PyObject* args)
{
- BOOL result;
- HMODULE module;
- TCHAR filename[MAX_PATH];
+ BOOL result;
+ HMODULE module;
+ TCHAR filename[MAX_PATH];
- if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName",
- &module))
- return NULL;
+ if (! PyArg_ParseTuple(args, PY_HANDLE_PARAM ":GetModuleFileName",
+ &module))
+ return NULL;
- result = GetModuleFileName(module, filename, MAX_PATH);
- filename[MAX_PATH-1] = '\0';
+ result = GetModuleFileName(module, filename, MAX_PATH);
+ filename[MAX_PATH-1] = '\0';
- if (! result)
- return PyErr_SetFromWindowsErr(GetLastError());
+ if (! result)
+ return PyErr_SetFromWindowsErr(GetLastError());
- return PyString_FromString(filename);
+ return PyString_FromString(filename);
}
static PyMethodDef sp_functions[] = {
- {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc},
- {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS,
- GetCurrentProcess_doc},
- {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS,
- DuplicateHandle_doc},
- {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc},
- {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc},
- {"TerminateProcess", sp_TerminateProcess, METH_VARARGS,
- TerminateProcess_doc},
- {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS,
- GetExitCodeProcess_doc},
- {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS,
- WaitForSingleObject_doc},
- {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc},
- {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS,
- GetModuleFileName_doc},
- {NULL, NULL}
+ {"GetStdHandle", sp_GetStdHandle, METH_VARARGS, GetStdHandle_doc},
+ {"GetCurrentProcess", sp_GetCurrentProcess, METH_VARARGS,
+ GetCurrentProcess_doc},
+ {"DuplicateHandle", sp_DuplicateHandle, METH_VARARGS,
+ DuplicateHandle_doc},
+ {"CreatePipe", sp_CreatePipe, METH_VARARGS, CreatePipe_doc},
+ {"CreateProcess", sp_CreateProcess, METH_VARARGS, CreateProcess_doc},
+ {"TerminateProcess", sp_TerminateProcess, METH_VARARGS,
+ TerminateProcess_doc},
+ {"GetExitCodeProcess", sp_GetExitCodeProcess, METH_VARARGS,
+ GetExitCodeProcess_doc},
+ {"WaitForSingleObject", sp_WaitForSingleObject, METH_VARARGS,
+ WaitForSingleObject_doc},
+ {"GetVersion", sp_GetVersion, METH_VARARGS, GetVersion_doc},
+ {"GetModuleFileName", sp_GetModuleFileName, METH_VARARGS,
+ GetModuleFileName_doc},
+ {NULL, NULL}
};
/* -------------------------------------------------------------------- */
@@ -632,11 +632,11 @@ static PyMethodDef sp_functions[] = {
static void
defint(PyObject* d, const char* name, int value)
{
- PyObject* v = PyInt_FromLong((long) value);
- if (v) {
- PyDict_SetItemString(d, (char*) name, v);
- Py_DECREF(v);
- }
+ PyObject* v = PyInt_FromLong((long) value);
+ if (v) {
+ PyDict_SetItemString(d, (char*) name, v);
+ Py_DECREF(v);
+ }
}
#if PY_VERSION_HEX >= 0x02030000
@@ -646,28 +646,28 @@ DL_EXPORT(void)
#endif
init_subprocess()
{
- PyObject *d;
- PyObject *m;
-
- /* patch up object descriptors */
- sp_handle_type.ob_type = &PyType_Type;
- sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int;
-
- m = Py_InitModule("_subprocess", sp_functions);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
-
- /* constants */
- defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE);
- defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE);
- defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE);
- defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS);
- defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES);
- defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW);
- defint(d, "SW_HIDE", SW_HIDE);
- defint(d, "INFINITE", INFINITE);
- defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0);
- defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE);
- defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP);
+ PyObject *d;
+ PyObject *m;
+
+ /* patch up object descriptors */
+ sp_handle_type.ob_type = &PyType_Type;
+ sp_handle_as_number.nb_int = (unaryfunc) sp_handle_as_int;
+
+ m = Py_InitModule("_subprocess", sp_functions);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+
+ /* constants */
+ defint(d, "STD_INPUT_HANDLE", STD_INPUT_HANDLE);
+ defint(d, "STD_OUTPUT_HANDLE", STD_OUTPUT_HANDLE);
+ defint(d, "STD_ERROR_HANDLE", STD_ERROR_HANDLE);
+ defint(d, "DUPLICATE_SAME_ACCESS", DUPLICATE_SAME_ACCESS);
+ defint(d, "STARTF_USESTDHANDLES", STARTF_USESTDHANDLES);
+ defint(d, "STARTF_USESHOWWINDOW", STARTF_USESHOWWINDOW);
+ defint(d, "SW_HIDE", SW_HIDE);
+ defint(d, "INFINITE", INFINITE);
+ defint(d, "WAIT_OBJECT_0", WAIT_OBJECT_0);
+ defint(d, "CREATE_NEW_CONSOLE", CREATE_NEW_CONSOLE);
+ defint(d, "CREATE_NEW_PROCESS_GROUP", CREATE_NEW_PROCESS_GROUP);
}
diff --git a/PC/_winreg.c b/PC/_winreg.c
index 57fe22b..6872603 100644
--- a/PC/_winreg.c
+++ b/PC/_winreg.c
@@ -4,7 +4,7 @@
Windows Registry access module for Python.
* Simple registry access written by Mark Hammond in win32api
- module circa 1995.
+ module circa 1995.
* Bill Tutt expanded the support significantly not long after.
* Numerous other people have submitted patches since then.
* Ripped from win32api module 03-Feb-2000 by Mark Hammond, and
@@ -29,7 +29,7 @@ static char errNotAHandle[] = "Object is not a handle";
want to lose this info...
*/
#define PyErr_SetFromWindowsErrWithFunction(rc, fnname) \
- PyErr_SetFromWindowsErr(rc)
+ PyErr_SetFromWindowsErr(rc)
/* Forward declares */
@@ -384,8 +384,8 @@ PyDoc_STRVAR(PyHKEY_Detach_doc,
************************************************************************/
typedef struct {
- PyObject_VAR_HEAD
- HKEY hkey;
+ PyObject_VAR_HEAD
+ HKEY hkey;
} PyHKEYObject;
#define PyHKEY_Check(op) ((op)->ob_type == &PyHKEY_Type)
@@ -395,46 +395,46 @@ static char *failMsg = "bad operand type";
static PyObject *
PyHKEY_unaryFailureFunc(PyObject *ob)
{
- PyErr_SetString(PyExc_TypeError, failMsg);
- return NULL;
+ PyErr_SetString(PyExc_TypeError, failMsg);
+ return NULL;
}
static PyObject *
PyHKEY_binaryFailureFunc(PyObject *ob1, PyObject *ob2)
{
- PyErr_SetString(PyExc_TypeError, failMsg);
- return NULL;
+ PyErr_SetString(PyExc_TypeError, failMsg);
+ return NULL;
}
static PyObject *
PyHKEY_ternaryFailureFunc(PyObject *ob1, PyObject *ob2, PyObject *ob3)
{
- PyErr_SetString(PyExc_TypeError, failMsg);
- return NULL;
+ PyErr_SetString(PyExc_TypeError, failMsg);
+ return NULL;
}
static void
PyHKEY_deallocFunc(PyObject *ob)
{
- /* Can not call PyHKEY_Close, as the ob->tp_type
- has already been cleared, thus causing the type
- check to fail!
- */
- PyHKEYObject *obkey = (PyHKEYObject *)ob;
- if (obkey->hkey)
- RegCloseKey((HKEY)obkey->hkey);
- PyObject_DEL(ob);
+ /* Can not call PyHKEY_Close, as the ob->tp_type
+ has already been cleared, thus causing the type
+ check to fail!
+ */
+ PyHKEYObject *obkey = (PyHKEYObject *)ob;
+ if (obkey->hkey)
+ RegCloseKey((HKEY)obkey->hkey);
+ PyObject_DEL(ob);
}
static int
PyHKEY_nonzeroFunc(PyObject *ob)
{
- return ((PyHKEYObject *)ob)->hkey != 0;
+ return ((PyHKEYObject *)ob)->hkey != 0;
}
static PyObject *
PyHKEY_intFunc(PyObject *ob)
{
- PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
- return PyLong_FromVoidPtr(pyhkey->hkey);
+ PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
+ return PyLong_FromVoidPtr(pyhkey->hkey);
}
static int
@@ -442,7 +442,7 @@ PyHKEY_printFunc(PyObject *ob, FILE *fp, int flags)
{
PyHKEYObject *pyhkey = (PyHKEYObject *)ob;
fprintf(fp, "<PyHKEY at %p (%p)>",
- ob, pyhkey->hkey);
+ ob, pyhkey->hkey);
return 0;
}
@@ -456,47 +456,47 @@ PyHKEY_strFunc(PyObject *ob)
static int
PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
{
- PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
- PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
- return pyhkey1 == pyhkey2 ? 0 :
- (pyhkey1 < pyhkey2 ? -1 : 1);
+ PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
+ PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
+ return pyhkey1 == pyhkey2 ? 0 :
+ (pyhkey1 < pyhkey2 ? -1 : 1);
}
static long
PyHKEY_hashFunc(PyObject *ob)
{
- /* Just use the address.
- XXX - should we use the handle value?
- */
- return _Py_HashPointer(ob);
+ /* Just use the address.
+ XXX - should we use the handle value?
+ */
+ return _Py_HashPointer(ob);
}
static PyNumberMethods PyHKEY_NumberMethods =
{
- PyHKEY_binaryFailureFunc, /* nb_add */
- PyHKEY_binaryFailureFunc, /* nb_subtract */
- PyHKEY_binaryFailureFunc, /* nb_multiply */
- PyHKEY_binaryFailureFunc, /* nb_divide */
- PyHKEY_binaryFailureFunc, /* nb_remainder */
- PyHKEY_binaryFailureFunc, /* nb_divmod */
- PyHKEY_ternaryFailureFunc, /* nb_power */
- PyHKEY_unaryFailureFunc, /* nb_negative */
- PyHKEY_unaryFailureFunc, /* nb_positive */
- PyHKEY_unaryFailureFunc, /* nb_absolute */
- PyHKEY_nonzeroFunc, /* nb_nonzero */
- PyHKEY_unaryFailureFunc, /* nb_invert */
- PyHKEY_binaryFailureFunc, /* nb_lshift */
- PyHKEY_binaryFailureFunc, /* nb_rshift */
- PyHKEY_binaryFailureFunc, /* nb_and */
- PyHKEY_binaryFailureFunc, /* nb_xor */
- PyHKEY_binaryFailureFunc, /* nb_or */
- 0, /* nb_coerce (allowed to be zero) */
- PyHKEY_intFunc, /* nb_int */
- PyHKEY_unaryFailureFunc, /* nb_long */
- PyHKEY_unaryFailureFunc, /* nb_float */
- PyHKEY_unaryFailureFunc, /* nb_oct */
- PyHKEY_unaryFailureFunc, /* nb_hex */
+ PyHKEY_binaryFailureFunc, /* nb_add */
+ PyHKEY_binaryFailureFunc, /* nb_subtract */
+ PyHKEY_binaryFailureFunc, /* nb_multiply */
+ PyHKEY_binaryFailureFunc, /* nb_divide */
+ PyHKEY_binaryFailureFunc, /* nb_remainder */
+ PyHKEY_binaryFailureFunc, /* nb_divmod */
+ PyHKEY_ternaryFailureFunc, /* nb_power */
+ PyHKEY_unaryFailureFunc, /* nb_negative */
+ PyHKEY_unaryFailureFunc, /* nb_positive */
+ PyHKEY_unaryFailureFunc, /* nb_absolute */
+ PyHKEY_nonzeroFunc, /* nb_nonzero */
+ PyHKEY_unaryFailureFunc, /* nb_invert */
+ PyHKEY_binaryFailureFunc, /* nb_lshift */
+ PyHKEY_binaryFailureFunc, /* nb_rshift */
+ PyHKEY_binaryFailureFunc, /* nb_and */
+ PyHKEY_binaryFailureFunc, /* nb_xor */
+ PyHKEY_binaryFailureFunc, /* nb_or */
+ 0, /* nb_coerce (allowed to be zero) */
+ PyHKEY_intFunc, /* nb_int */
+ PyHKEY_unaryFailureFunc, /* nb_long */
+ PyHKEY_unaryFailureFunc, /* nb_float */
+ PyHKEY_unaryFailureFunc, /* nb_oct */
+ PyHKEY_unaryFailureFunc, /* nb_hex */
};
static PyObject *PyHKEY_CloseMethod(PyObject *self, PyObject *args);
@@ -505,50 +505,50 @@ static PyObject *PyHKEY_Enter(PyObject *self);
static PyObject *PyHKEY_Exit(PyObject *self, PyObject *args);
static struct PyMethodDef PyHKEY_methods[] = {
- {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc},
- {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc},
- {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL},
- {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL},
- {NULL}
+ {"Close", PyHKEY_CloseMethod, METH_VARARGS, PyHKEY_Close_doc},
+ {"Detach", PyHKEY_DetachMethod, METH_VARARGS, PyHKEY_Detach_doc},
+ {"__enter__", (PyCFunction)PyHKEY_Enter, METH_NOARGS, NULL},
+ {"__exit__", PyHKEY_Exit, METH_VARARGS, NULL},
+ {NULL}
};
static PyMemberDef PyHKEY_memberlist[] = {
- {"handle", T_PYSSIZET, offsetof(PyHKEYObject, hkey), READONLY},
- {NULL} /* Sentinel */
+ {"handle", T_PYSSIZET, offsetof(PyHKEYObject, hkey), READONLY},
+ {NULL} /* Sentinel */
};
/* The type itself */
PyTypeObject PyHKEY_Type =
{
- PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */
- "PyHKEY",
- sizeof(PyHKEYObject),
- 0,
- PyHKEY_deallocFunc, /* tp_dealloc */
- PyHKEY_printFunc, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- PyHKEY_compareFunc, /* tp_compare */
- 0, /* tp_repr */
- &PyHKEY_NumberMethods, /* tp_as_number */
- 0, /* tp_as_sequence */
- 0, /* tp_as_mapping */
- PyHKEY_hashFunc, /* tp_hash */
- 0, /* tp_call */
- PyHKEY_strFunc, /* tp_str */
- 0, /* tp_getattro */
- 0, /* tp_setattro */
- 0, /* tp_as_buffer */
- Py_TPFLAGS_DEFAULT, /* tp_flags */
- PyHKEY_doc, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- PyHKEY_methods, /* tp_methods */
- PyHKEY_memberlist, /* tp_members */
+ PyVarObject_HEAD_INIT(0, 0) /* fill in type at module init */
+ "PyHKEY",
+ sizeof(PyHKEYObject),
+ 0,
+ PyHKEY_deallocFunc, /* tp_dealloc */
+ PyHKEY_printFunc, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ PyHKEY_compareFunc, /* tp_compare */
+ 0, /* tp_repr */
+ &PyHKEY_NumberMethods, /* tp_as_number */
+ 0, /* tp_as_sequence */
+ 0, /* tp_as_mapping */
+ PyHKEY_hashFunc, /* tp_hash */
+ 0, /* tp_call */
+ PyHKEY_strFunc, /* tp_str */
+ 0, /* tp_getattro */
+ 0, /* tp_setattro */
+ 0, /* tp_as_buffer */
+ Py_TPFLAGS_DEFAULT, /* tp_flags */
+ PyHKEY_doc, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ PyHKEY_methods, /* tp_methods */
+ PyHKEY_memberlist, /* tp_members */
};
/************************************************************************
@@ -559,39 +559,39 @@ PyTypeObject PyHKEY_Type =
static PyObject *
PyHKEY_CloseMethod(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":Close"))
- return NULL;
- if (!PyHKEY_Close(self))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, ":Close"))
+ return NULL;
+ if (!PyHKEY_Close(self))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyHKEY_DetachMethod(PyObject *self, PyObject *args)
{
- void* ret;
- PyHKEYObject *pThis = (PyHKEYObject *)self;
- if (!PyArg_ParseTuple(args, ":Detach"))
- return NULL;
- ret = (void*)pThis->hkey;
- pThis->hkey = 0;
- return PyLong_FromVoidPtr(ret);
+ void* ret;
+ PyHKEYObject *pThis = (PyHKEYObject *)self;
+ if (!PyArg_ParseTuple(args, ":Detach"))
+ return NULL;
+ ret = (void*)pThis->hkey;
+ pThis->hkey = 0;
+ return PyLong_FromVoidPtr(ret);
}
static PyObject *
PyHKEY_Enter(PyObject *self)
{
- Py_XINCREF(self);
- return self;
+ Py_XINCREF(self);
+ return self;
}
static PyObject *
PyHKEY_Exit(PyObject *self, PyObject *args)
{
- if (!PyHKEY_Close(self))
- return NULL;
- Py_RETURN_NONE;
+ if (!PyHKEY_Close(self))
+ return NULL;
+ Py_RETURN_NONE;
}
@@ -601,74 +601,74 @@ PyHKEY_Exit(PyObject *self, PyObject *args)
PyObject *
PyHKEY_New(HKEY hInit)
{
- PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
- if (key)
- key->hkey = hInit;
- return (PyObject *)key;
+ PyHKEYObject *key = PyObject_NEW(PyHKEYObject, &PyHKEY_Type);
+ if (key)
+ key->hkey = hInit;
+ return (PyObject *)key;
}
BOOL
PyHKEY_Close(PyObject *ob_handle)
{
- LONG rc;
- PyHKEYObject *key;
-
- if (!PyHKEY_Check(ob_handle)) {
- PyErr_SetString(PyExc_TypeError, "bad operand type");
- return FALSE;
- }
- key = (PyHKEYObject *)ob_handle;
- rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS;
- key->hkey = 0;
- if (rc != ERROR_SUCCESS)
- PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
- return rc == ERROR_SUCCESS;
+ LONG rc;
+ PyHKEYObject *key;
+
+ if (!PyHKEY_Check(ob_handle)) {
+ PyErr_SetString(PyExc_TypeError, "bad operand type");
+ return FALSE;
+ }
+ key = (PyHKEYObject *)ob_handle;
+ rc = key->hkey ? RegCloseKey((HKEY)key->hkey) : ERROR_SUCCESS;
+ key->hkey = 0;
+ if (rc != ERROR_SUCCESS)
+ PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
+ return rc == ERROR_SUCCESS;
}
BOOL
PyHKEY_AsHKEY(PyObject *ob, HKEY *pHANDLE, BOOL bNoneOK)
{
- if (ob == Py_None) {
- if (!bNoneOK) {
- PyErr_SetString(
- PyExc_TypeError,
- "None is not a valid HKEY in this context");
- return FALSE;
- }
- *pHANDLE = (HKEY)0;
- }
- else if (PyHKEY_Check(ob)) {
- PyHKEYObject *pH = (PyHKEYObject *)ob;
- *pHANDLE = pH->hkey;
- }
- else if (PyInt_Check(ob) || PyLong_Check(ob)) {
- /* We also support integers */
- PyErr_Clear();
- *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
- if (PyErr_Occurred())
- return FALSE;
- }
- else {
- PyErr_SetString(
- PyExc_TypeError,
- "The object is not a PyHKEY object");
- return FALSE;
- }
- return TRUE;
+ if (ob == Py_None) {
+ if (!bNoneOK) {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "None is not a valid HKEY in this context");
+ return FALSE;
+ }
+ *pHANDLE = (HKEY)0;
+ }
+ else if (PyHKEY_Check(ob)) {
+ PyHKEYObject *pH = (PyHKEYObject *)ob;
+ *pHANDLE = pH->hkey;
+ }
+ else if (PyInt_Check(ob) || PyLong_Check(ob)) {
+ /* We also support integers */
+ PyErr_Clear();
+ *pHANDLE = (HKEY)PyLong_AsVoidPtr(ob);
+ if (PyErr_Occurred())
+ return FALSE;
+ }
+ else {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "The object is not a PyHKEY object");
+ return FALSE;
+ }
+ return TRUE;
}
PyObject *
PyHKEY_FromHKEY(HKEY h)
{
- PyHKEYObject *op;
-
- /* Inline PyObject_New */
- op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
- if (op == NULL)
- return PyErr_NoMemory();
- PyObject_INIT(op, &PyHKEY_Type);
- op->hkey = h;
- return (PyObject *)op;
+ PyHKEYObject *op;
+
+ /* Inline PyObject_New */
+ op = (PyHKEYObject *) PyObject_MALLOC(sizeof(PyHKEYObject));
+ if (op == NULL)
+ return PyErr_NoMemory();
+ PyObject_INIT(op, &PyHKEY_Type);
+ op->hkey = h;
+ return (PyObject *)op;
}
@@ -678,32 +678,32 @@ PyHKEY_FromHKEY(HKEY h)
BOOL
PyWinObject_CloseHKEY(PyObject *obHandle)
{
- BOOL ok;
- if (PyHKEY_Check(obHandle)) {
- ok = PyHKEY_Close(obHandle);
- }
+ BOOL ok;
+ if (PyHKEY_Check(obHandle)) {
+ ok = PyHKEY_Close(obHandle);
+ }
#if SIZEOF_LONG >= SIZEOF_HKEY
- else if (PyInt_Check(obHandle)) {
- long rc = RegCloseKey((HKEY)PyInt_AsLong(obHandle));
- ok = (rc == ERROR_SUCCESS);
- if (!ok)
- PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
- }
+ else if (PyInt_Check(obHandle)) {
+ long rc = RegCloseKey((HKEY)PyInt_AsLong(obHandle));
+ ok = (rc == ERROR_SUCCESS);
+ if (!ok)
+ PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
+ }
#else
- else if (PyLong_Check(obHandle)) {
- long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
- ok = (rc == ERROR_SUCCESS);
- if (!ok)
- PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
- }
+ else if (PyLong_Check(obHandle)) {
+ long rc = RegCloseKey((HKEY)PyLong_AsVoidPtr(obHandle));
+ ok = (rc == ERROR_SUCCESS);
+ if (!ok)
+ PyErr_SetFromWindowsErrWithFunction(rc, "RegCloseKey");
+ }
#endif
- else {
- PyErr_SetString(
- PyExc_TypeError,
- "A handle must be a HKEY object or an integer");
- return FALSE;
- }
- return ok;
+ else {
+ PyErr_SetString(
+ PyExc_TypeError,
+ "A handle must be a HKEY object or an integer");
+ return FALSE;
+ }
+ return ok;
}
@@ -720,29 +720,29 @@ PyWinObject_CloseHKEY(PyObject *obHandle)
static void
fixupMultiSZ(char **str, char *data, int len)
{
- char *P;
- int i;
- char *Q;
-
- Q = data + len;
- for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
- str[i] = P;
- for(; *P != '\0'; P++)
- ;
- }
+ char *P;
+ int i;
+ char *Q;
+
+ Q = data + len;
+ for (P = data, i = 0; P < Q && *P != '\0'; P++, i++) {
+ str[i] = P;
+ for(; *P != '\0'; P++)
+ ;
+ }
}
static int
countStrings(char *data, int len)
{
- int strings;
- char *P;
- char *Q = data + len;
-
- for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
- for (; P < Q && *P != '\0'; P++)
- ;
- return strings;
+ int strings;
+ char *P;
+ char *Q = data + len;
+
+ for (P = data, strings = 0; P < Q && *P != '\0'; P++, strings++)
+ for (; P < Q && *P != '\0'; P++)
+ ;
+ return strings;
}
/* Convert PyObject into Registry data.
@@ -750,244 +750,244 @@ countStrings(char *data, int len)
static BOOL
Py2Reg(PyObject *value, DWORD typ, BYTE **retDataBuf, DWORD *retDataSize)
{
- Py_ssize_t i,j;
- switch (typ) {
- case REG_DWORD:
- if (value != Py_None && !PyInt_Check(value))
- return FALSE;
- *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
- if (*retDataBuf==NULL){
- PyErr_NoMemory();
- return FALSE;
- }
- *retDataSize = sizeof(DWORD);
- if (value == Py_None) {
- DWORD zero = 0;
- memcpy(*retDataBuf, &zero, sizeof(DWORD));
- }
- else
- memcpy(*retDataBuf,
- &PyInt_AS_LONG((PyIntObject *)value),
- sizeof(DWORD));
- break;
- case REG_SZ:
- case REG_EXPAND_SZ:
- {
- int need_decref = 0;
- if (value == Py_None)
- *retDataSize = 1;
- else {
- if (PyUnicode_Check(value)) {
- value = PyUnicode_AsEncodedString(
- value,
- "mbcs",
- NULL);
- if (value==NULL)
- return FALSE;
- need_decref = 1;
- }
- if (!PyString_Check(value))
- return FALSE;
- *retDataSize = 1 + strlen(
- PyString_AS_STRING(
- (PyStringObject *)value));
- }
- *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
- if (*retDataBuf==NULL){
- PyErr_NoMemory();
- return FALSE;
- }
- if (value == Py_None)
- strcpy((char *)*retDataBuf, "");
- else
- strcpy((char *)*retDataBuf,
- PyString_AS_STRING(
- (PyStringObject *)value));
- if (need_decref)
- Py_DECREF(value);
- break;
- }
- case REG_MULTI_SZ:
- {
- DWORD size = 0;
- char *P;
- PyObject **obs = NULL;
-
- if (value == Py_None)
- i = 0;
- else {
- if (!PyList_Check(value))
- return FALSE;
- i = PyList_Size(value);
- }
- obs = malloc(sizeof(PyObject *) * i);
- memset(obs, 0, sizeof(PyObject *) * i);
- for (j = 0; j < i; j++)
- {
- PyObject *t;
- t = PyList_GET_ITEM(
- (PyListObject *)value,j);
- if (PyString_Check(t)) {
- obs[j] = t;
- Py_INCREF(t);
- } else if (PyUnicode_Check(t)) {
- obs[j] = PyUnicode_AsEncodedString(
- t,
- "mbcs",
- NULL);
- if (obs[j]==NULL)
- goto reg_multi_fail;
- } else
- goto reg_multi_fail;
- size += 1 + strlen(
- PyString_AS_STRING(
- (PyStringObject *)obs[j]));
- }
-
- *retDataSize = size + 1;
- *retDataBuf = (BYTE *)PyMem_NEW(char,
- *retDataSize);
- if (*retDataBuf==NULL){
- PyErr_NoMemory();
- goto reg_multi_fail;
- }
- P = (char *)*retDataBuf;
-
- for (j = 0; j < i; j++)
- {
- PyObject *t;
- t = obs[j];
- strcpy(P,
- PyString_AS_STRING(
- (PyStringObject *)t));
- P += 1 + strlen(
- PyString_AS_STRING(
- (PyStringObject *)t));
- Py_DECREF(obs[j]);
- }
- /* And doubly-terminate the list... */
- *P = '\0';
- free(obs);
- break;
- reg_multi_fail:
- if (obs) {
- for (j = 0; j < i; j++)
- Py_XDECREF(obs[j]);
-
- free(obs);
- }
- return FALSE;
- }
- case REG_BINARY:
- /* ALSO handle ALL unknown data types here. Even if we can't
- support it natively, we should handle the bits. */
- default:
- if (value == Py_None)
- *retDataSize = 0;
- else {
- void *src_buf;
- PyBufferProcs *pb = value->ob_type->tp_as_buffer;
- if (pb==NULL) {
- PyErr_Format(PyExc_TypeError,
- "Objects of type '%s' can not "
- "be used as binary registry values",
- value->ob_type->tp_name);
- return FALSE;
- }
- *retDataSize = (*pb->bf_getreadbuffer)(value, 0, &src_buf);
- *retDataBuf = (BYTE *)PyMem_NEW(char,
- *retDataSize);
- if (*retDataBuf==NULL){
- PyErr_NoMemory();
- return FALSE;
- }
- memcpy(*retDataBuf, src_buf, *retDataSize);
- }
- break;
- }
- return TRUE;
+ Py_ssize_t i,j;
+ switch (typ) {
+ case REG_DWORD:
+ if (value != Py_None && !PyInt_Check(value))
+ return FALSE;
+ *retDataBuf = (BYTE *)PyMem_NEW(DWORD, 1);
+ if (*retDataBuf==NULL){
+ PyErr_NoMemory();
+ return FALSE;
+ }
+ *retDataSize = sizeof(DWORD);
+ if (value == Py_None) {
+ DWORD zero = 0;
+ memcpy(*retDataBuf, &zero, sizeof(DWORD));
+ }
+ else
+ memcpy(*retDataBuf,
+ &PyInt_AS_LONG((PyIntObject *)value),
+ sizeof(DWORD));
+ break;
+ case REG_SZ:
+ case REG_EXPAND_SZ:
+ {
+ int need_decref = 0;
+ if (value == Py_None)
+ *retDataSize = 1;
+ else {
+ if (PyUnicode_Check(value)) {
+ value = PyUnicode_AsEncodedString(
+ value,
+ "mbcs",
+ NULL);
+ if (value==NULL)
+ return FALSE;
+ need_decref = 1;
+ }
+ if (!PyString_Check(value))
+ return FALSE;
+ *retDataSize = 1 + strlen(
+ PyString_AS_STRING(
+ (PyStringObject *)value));
+ }
+ *retDataBuf = (BYTE *)PyMem_NEW(DWORD, *retDataSize);
+ if (*retDataBuf==NULL){
+ PyErr_NoMemory();
+ return FALSE;
+ }
+ if (value == Py_None)
+ strcpy((char *)*retDataBuf, "");
+ else
+ strcpy((char *)*retDataBuf,
+ PyString_AS_STRING(
+ (PyStringObject *)value));
+ if (need_decref)
+ Py_DECREF(value);
+ break;
+ }
+ case REG_MULTI_SZ:
+ {
+ DWORD size = 0;
+ char *P;
+ PyObject **obs = NULL;
+
+ if (value == Py_None)
+ i = 0;
+ else {
+ if (!PyList_Check(value))
+ return FALSE;
+ i = PyList_Size(value);
+ }
+ obs = malloc(sizeof(PyObject *) * i);
+ memset(obs, 0, sizeof(PyObject *) * i);
+ for (j = 0; j < i; j++)
+ {
+ PyObject *t;
+ t = PyList_GET_ITEM(
+ (PyListObject *)value,j);
+ if (PyString_Check(t)) {
+ obs[j] = t;
+ Py_INCREF(t);
+ } else if (PyUnicode_Check(t)) {
+ obs[j] = PyUnicode_AsEncodedString(
+ t,
+ "mbcs",
+ NULL);
+ if (obs[j]==NULL)
+ goto reg_multi_fail;
+ } else
+ goto reg_multi_fail;
+ size += 1 + strlen(
+ PyString_AS_STRING(
+ (PyStringObject *)obs[j]));
+ }
+
+ *retDataSize = size + 1;
+ *retDataBuf = (BYTE *)PyMem_NEW(char,
+ *retDataSize);
+ if (*retDataBuf==NULL){
+ PyErr_NoMemory();
+ goto reg_multi_fail;
+ }
+ P = (char *)*retDataBuf;
+
+ for (j = 0; j < i; j++)
+ {
+ PyObject *t;
+ t = obs[j];
+ strcpy(P,
+ PyString_AS_STRING(
+ (PyStringObject *)t));
+ P += 1 + strlen(
+ PyString_AS_STRING(
+ (PyStringObject *)t));
+ Py_DECREF(obs[j]);
+ }
+ /* And doubly-terminate the list... */
+ *P = '\0';
+ free(obs);
+ break;
+ reg_multi_fail:
+ if (obs) {
+ for (j = 0; j < i; j++)
+ Py_XDECREF(obs[j]);
+
+ free(obs);
+ }
+ return FALSE;
+ }
+ case REG_BINARY:
+ /* ALSO handle ALL unknown data types here. Even if we can't
+ support it natively, we should handle the bits. */
+ default:
+ if (value == Py_None)
+ *retDataSize = 0;
+ else {
+ void *src_buf;
+ PyBufferProcs *pb = value->ob_type->tp_as_buffer;
+ if (pb==NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "Objects of type '%s' can not "
+ "be used as binary registry values",
+ value->ob_type->tp_name);
+ return FALSE;
+ }
+ *retDataSize = (*pb->bf_getreadbuffer)(value, 0, &src_buf);
+ *retDataBuf = (BYTE *)PyMem_NEW(char,
+ *retDataSize);
+ if (*retDataBuf==NULL){
+ PyErr_NoMemory();
+ return FALSE;
+ }
+ memcpy(*retDataBuf, src_buf, *retDataSize);
+ }
+ break;
+ }
+ return TRUE;
}
/* Convert Registry data into PyObject*/
static PyObject *
Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ)
{
- PyObject *obData;
-
- switch (typ) {
- case REG_DWORD:
- if (retDataSize == 0)
- obData = Py_BuildValue("i", 0);
- else
- obData = Py_BuildValue("i",
- *(int *)retDataBuf);
- break;
- case REG_SZ:
- case REG_EXPAND_SZ:
- /* retDataBuf may or may not have a trailing NULL in
- the buffer. */
- if (retDataSize && retDataBuf[retDataSize-1] == '\0')
- --retDataSize;
- if (retDataSize ==0)
- retDataBuf = "";
- obData = PyUnicode_DecodeMBCS(retDataBuf,
- retDataSize,
- NULL);
- break;
- case REG_MULTI_SZ:
- if (retDataSize == 0)
- obData = PyList_New(0);
- else
- {
- int index = 0;
- int s = countStrings(retDataBuf, retDataSize);
- char **str = (char **)malloc(sizeof(char *)*s);
- if (str == NULL)
- return PyErr_NoMemory();
-
- fixupMultiSZ(str, retDataBuf, retDataSize);
- obData = PyList_New(s);
- if (obData == NULL)
- return NULL;
- for (index = 0; index < s; index++)
- {
- size_t len = _mbstrlen(str[index]);
- if (len > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "registry string is too long for a Python string");
- Py_DECREF(obData);
- return NULL;
- }
- PyList_SetItem(obData,
- index,
- PyUnicode_DecodeMBCS(
- (const char *)str[index],
- (int)len,
- NULL)
- );
- }
- free(str);
-
- break;
- }
- case REG_BINARY:
- /* ALSO handle ALL unknown data types here. Even if we can't
- support it natively, we should handle the bits. */
- default:
- if (retDataSize == 0) {
- Py_INCREF(Py_None);
- obData = Py_None;
- }
- else
- obData = Py_BuildValue("s#",
- (char *)retDataBuf,
- retDataSize);
- break;
- }
- if (obData == NULL)
- return NULL;
- else
- return obData;
+ PyObject *obData;
+
+ switch (typ) {
+ case REG_DWORD:
+ if (retDataSize == 0)
+ obData = Py_BuildValue("i", 0);
+ else
+ obData = Py_BuildValue("i",
+ *(int *)retDataBuf);
+ break;
+ case REG_SZ:
+ case REG_EXPAND_SZ:
+ /* retDataBuf may or may not have a trailing NULL in
+ the buffer. */
+ if (retDataSize && retDataBuf[retDataSize-1] == '\0')
+ --retDataSize;
+ if (retDataSize ==0)
+ retDataBuf = "";
+ obData = PyUnicode_DecodeMBCS(retDataBuf,
+ retDataSize,
+ NULL);
+ break;
+ case REG_MULTI_SZ:
+ if (retDataSize == 0)
+ obData = PyList_New(0);
+ else
+ {
+ int index = 0;
+ int s = countStrings(retDataBuf, retDataSize);
+ char **str = (char **)malloc(sizeof(char *)*s);
+ if (str == NULL)
+ return PyErr_NoMemory();
+
+ fixupMultiSZ(str, retDataBuf, retDataSize);
+ obData = PyList_New(s);
+ if (obData == NULL)
+ return NULL;
+ for (index = 0; index < s; index++)
+ {
+ size_t len = _mbstrlen(str[index]);
+ if (len > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "registry string is too long for a Python string");
+ Py_DECREF(obData);
+ return NULL;
+ }
+ PyList_SetItem(obData,
+ index,
+ PyUnicode_DecodeMBCS(
+ (const char *)str[index],
+ (int)len,
+ NULL)
+ );
+ }
+ free(str);
+
+ break;
+ }
+ case REG_BINARY:
+ /* ALSO handle ALL unknown data types here. Even if we can't
+ support it natively, we should handle the bits. */
+ default:
+ if (retDataSize == 0) {
+ Py_INCREF(Py_None);
+ obData = Py_None;
+ }
+ else
+ obData = Py_BuildValue("s#",
+ (char *)retDataBuf,
+ retDataSize);
+ break;
+ }
+ if (obData == NULL)
+ return NULL;
+ else
+ return obData;
}
/* The Python methods */
@@ -995,344 +995,344 @@ Reg2Py(char *retDataBuf, DWORD retDataSize, DWORD typ)
static PyObject *
PyCloseKey(PyObject *self, PyObject *args)
{
- PyObject *obKey;
- if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey))
- return NULL;
- if (!PyHKEY_Close(obKey))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *obKey;
+ if (!PyArg_ParseTuple(args, "O:CloseKey", &obKey))
+ return NULL;
+ if (!PyHKEY_Close(obKey))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyConnectRegistry(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *szCompName = NULL;
- HKEY retKey;
- long rc;
- if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- rc = RegConnectRegistry(szCompName, hKey, &retKey);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "ConnectRegistry");
- return PyHKEY_FromHKEY(retKey);
+ HKEY hKey;
+ PyObject *obKey;
+ char *szCompName = NULL;
+ HKEY retKey;
+ long rc;
+ if (!PyArg_ParseTuple(args, "zO:ConnectRegistry", &szCompName, &obKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegConnectRegistry(szCompName, hKey, &retKey);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "ConnectRegistry");
+ return PyHKEY_FromHKEY(retKey);
}
static PyObject *
PyCreateKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- HKEY retKey;
- long rc;
- if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- rc = RegCreateKey(hKey, subKey, &retKey);
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
- return PyHKEY_FromHKEY(retKey);
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ HKEY retKey;
+ long rc;
+ if (!PyArg_ParseTuple(args, "Oz:CreateKey", &obKey, &subKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ rc = RegCreateKey(hKey, subKey, &retKey);
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKey");
+ return PyHKEY_FromHKEY(retKey);
}
static PyObject *
PyCreateKeyEx(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- HKEY retKey;
- int res = 0;
- REGSAM sam = KEY_WRITE;
- long rc;
- if (!PyArg_ParseTuple(args, "Oz|ii:CreateKeyEx", &obKey, &subKey,
- &res, &sam))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- rc = RegCreateKeyEx(hKey, subKey, res, NULL, (DWORD)NULL,
- sam, NULL, &retKey, NULL);
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx");
- return PyHKEY_FromHKEY(retKey);
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ HKEY retKey;
+ int res = 0;
+ REGSAM sam = KEY_WRITE;
+ long rc;
+ if (!PyArg_ParseTuple(args, "Oz|ii:CreateKeyEx", &obKey, &subKey,
+ &res, &sam))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ rc = RegCreateKeyEx(hKey, subKey, res, NULL, (DWORD)NULL,
+ sam, NULL, &retKey, NULL);
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "CreateKeyEx");
+ return PyHKEY_FromHKEY(retKey);
}
static PyObject *
PyDeleteKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- long rc;
- if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- rc = RegDeleteKey(hKey, subKey );
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ long rc;
+ if (!PyArg_ParseTuple(args, "Os:DeleteKey", &obKey, &subKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ rc = RegDeleteKey(hKey, subKey );
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKey");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyDeleteKeyEx(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- HMODULE hMod;
- typedef LONG (WINAPI *RDKEFunc)(HKEY, const char*, REGSAM, int);
- RDKEFunc pfn = NULL;
- char *subKey;
- long rc;
- int res = 0;
- REGSAM sam = KEY_WOW64_64KEY;
-
- if (!PyArg_ParseTuple(args, "Os|ii:DeleteKeyEx",
- &obKey, &subKey, &sam, &res))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- /* Only available on 64bit platforms, so we must load it
- dynamically. */
- hMod = GetModuleHandle("advapi32.dll");
- if (hMod)
- pfn = (RDKEFunc)GetProcAddress(hMod,
- "RegDeleteKeyExA");
- if (!pfn) {
- PyErr_SetString(PyExc_NotImplementedError,
- "not implemented on this platform");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- rc = (*pfn)(hKey, subKey, sam, res);
- Py_END_ALLOW_THREADS
-
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ HMODULE hMod;
+ typedef LONG (WINAPI *RDKEFunc)(HKEY, const char*, REGSAM, int);
+ RDKEFunc pfn = NULL;
+ char *subKey;
+ long rc;
+ int res = 0;
+ REGSAM sam = KEY_WOW64_64KEY;
+
+ if (!PyArg_ParseTuple(args, "Os|ii:DeleteKeyEx",
+ &obKey, &subKey, &sam, &res))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ /* Only available on 64bit platforms, so we must load it
+ dynamically. */
+ hMod = GetModuleHandle("advapi32.dll");
+ if (hMod)
+ pfn = (RDKEFunc)GetProcAddress(hMod,
+ "RegDeleteKeyExA");
+ if (!pfn) {
+ PyErr_SetString(PyExc_NotImplementedError,
+ "not implemented on this platform");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ rc = (*pfn)(hKey, subKey, sam, res);
+ Py_END_ALLOW_THREADS
+
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegDeleteKeyEx");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyDeleteValue(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- long rc;
- if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- rc = RegDeleteValue(hKey, subKey);
- Py_END_ALLOW_THREADS
- if (rc !=ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegDeleteValue");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ long rc;
+ if (!PyArg_ParseTuple(args, "Oz:DeleteValue", &obKey, &subKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegDeleteValue(hKey, subKey);
+ Py_END_ALLOW_THREADS
+ if (rc !=ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegDeleteValue");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyEnumKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- int index;
- long rc;
- PyObject *retStr;
- char tmpbuf[256]; /* max key name length is 255 */
- DWORD len = sizeof(tmpbuf); /* includes NULL terminator */
-
- if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- rc = RegEnumKeyEx(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx");
-
- retStr = PyString_FromStringAndSize(tmpbuf, len);
- return retStr; /* can be NULL */
+ HKEY hKey;
+ PyObject *obKey;
+ int index;
+ long rc;
+ PyObject *retStr;
+ char tmpbuf[256]; /* max key name length is 255 */
+ DWORD len = sizeof(tmpbuf); /* includes NULL terminator */
+
+ if (!PyArg_ParseTuple(args, "Oi:EnumKey", &obKey, &index))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegEnumKeyEx(hKey, index, tmpbuf, &len, NULL, NULL, NULL, NULL);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegEnumKeyEx");
+
+ retStr = PyString_FromStringAndSize(tmpbuf, len);
+ return retStr; /* can be NULL */
}
static PyObject *
PyEnumValue(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- int index;
- long rc;
- char *retValueBuf;
- char *retDataBuf;
- DWORD retValueSize;
- DWORD retDataSize;
- DWORD typ;
- PyObject *obData;
- PyObject *retVal;
-
- if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
- NULL,
- &retValueSize, &retDataSize, NULL, NULL))
- != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegQueryInfoKey");
- ++retValueSize; /* include null terminators */
- ++retDataSize;
- retValueBuf = (char *)PyMem_Malloc(retValueSize);
- if (retValueBuf == NULL)
- return PyErr_NoMemory();
- retDataBuf = (char *)PyMem_Malloc(retDataSize);
- if (retDataBuf == NULL) {
- PyMem_Free(retValueBuf);
- return PyErr_NoMemory();
- }
-
- Py_BEGIN_ALLOW_THREADS
- rc = RegEnumValue(hKey,
- index,
- retValueBuf,
- &retValueSize,
- NULL,
- &typ,
- (BYTE *)retDataBuf,
- &retDataSize);
- Py_END_ALLOW_THREADS
-
- if (rc != ERROR_SUCCESS) {
- retVal = PyErr_SetFromWindowsErrWithFunction(rc,
- "PyRegEnumValue");
- goto fail;
- }
- obData = Reg2Py(retDataBuf, retDataSize, typ);
- if (obData == NULL) {
- retVal = NULL;
- goto fail;
- }
- retVal = Py_BuildValue("sOi", retValueBuf, obData, typ);
- Py_DECREF(obData);
+ HKEY hKey;
+ PyObject *obKey;
+ int index;
+ long rc;
+ char *retValueBuf;
+ char *retDataBuf;
+ DWORD retValueSize;
+ DWORD retDataSize;
+ DWORD typ;
+ PyObject *obData;
+ PyObject *retVal;
+
+ if (!PyArg_ParseTuple(args, "Oi:EnumValue", &obKey, &index))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ if ((rc = RegQueryInfoKey(hKey, NULL, NULL, NULL, NULL, NULL, NULL,
+ NULL,
+ &retValueSize, &retDataSize, NULL, NULL))
+ != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegQueryInfoKey");
+ ++retValueSize; /* include null terminators */
+ ++retDataSize;
+ retValueBuf = (char *)PyMem_Malloc(retValueSize);
+ if (retValueBuf == NULL)
+ return PyErr_NoMemory();
+ retDataBuf = (char *)PyMem_Malloc(retDataSize);
+ if (retDataBuf == NULL) {
+ PyMem_Free(retValueBuf);
+ return PyErr_NoMemory();
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegEnumValue(hKey,
+ index,
+ retValueBuf,
+ &retValueSize,
+ NULL,
+ &typ,
+ (BYTE *)retDataBuf,
+ &retDataSize);
+ Py_END_ALLOW_THREADS
+
+ if (rc != ERROR_SUCCESS) {
+ retVal = PyErr_SetFromWindowsErrWithFunction(rc,
+ "PyRegEnumValue");
+ goto fail;
+ }
+ obData = Reg2Py(retDataBuf, retDataSize, typ);
+ if (obData == NULL) {
+ retVal = NULL;
+ goto fail;
+ }
+ retVal = Py_BuildValue("sOi", retValueBuf, obData, typ);
+ Py_DECREF(obData);
fail:
- PyMem_Free(retValueBuf);
- PyMem_Free(retDataBuf);
- return retVal;
+ PyMem_Free(retValueBuf);
+ PyMem_Free(retDataBuf);
+ return retVal;
}
static PyObject *
PyExpandEnvironmentStrings(PyObject *self, PyObject *args)
{
- Py_UNICODE *retValue = NULL;
- Py_UNICODE *src;
- DWORD retValueSize;
- DWORD rc;
- PyObject *o;
-
- if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src))
- return NULL;
-
- retValueSize = ExpandEnvironmentStringsW(src, retValue, 0);
- if (retValueSize == 0) {
- return PyErr_SetFromWindowsErrWithFunction(retValueSize,
- "ExpandEnvironmentStrings");
- }
- retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE));
- if (retValue == NULL) {
- return PyErr_NoMemory();
- }
-
- rc = ExpandEnvironmentStringsW(src, retValue, retValueSize);
- if (rc == 0) {
- PyMem_Free(retValue);
- return PyErr_SetFromWindowsErrWithFunction(retValueSize,
- "ExpandEnvironmentStrings");
- }
- o = PyUnicode_FromUnicode(retValue, wcslen(retValue));
- PyMem_Free(retValue);
- return o;
+ Py_UNICODE *retValue = NULL;
+ Py_UNICODE *src;
+ DWORD retValueSize;
+ DWORD rc;
+ PyObject *o;
+
+ if (!PyArg_ParseTuple(args, "u:ExpandEnvironmentStrings", &src))
+ return NULL;
+
+ retValueSize = ExpandEnvironmentStringsW(src, retValue, 0);
+ if (retValueSize == 0) {
+ return PyErr_SetFromWindowsErrWithFunction(retValueSize,
+ "ExpandEnvironmentStrings");
+ }
+ retValue = (Py_UNICODE *)PyMem_Malloc(retValueSize * sizeof(Py_UNICODE));
+ if (retValue == NULL) {
+ return PyErr_NoMemory();
+ }
+
+ rc = ExpandEnvironmentStringsW(src, retValue, retValueSize);
+ if (rc == 0) {
+ PyMem_Free(retValue);
+ return PyErr_SetFromWindowsErrWithFunction(retValueSize,
+ "ExpandEnvironmentStrings");
+ }
+ o = PyUnicode_FromUnicode(retValue, wcslen(retValue));
+ PyMem_Free(retValue);
+ return o;
}
static PyObject *
PyFlushKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- long rc;
- if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- rc = RegFlushKey(hKey);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ long rc;
+ if (!PyArg_ParseTuple(args, "O:FlushKey", &obKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegFlushKey(hKey);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegFlushKey");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyLoadKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- char *fileName;
-
- long rc;
- if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- Py_BEGIN_ALLOW_THREADS
- rc = RegLoadKey(hKey, subKey, fileName );
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ char *fileName;
+
+ long rc;
+ if (!PyArg_ParseTuple(args, "Oss:LoadKey", &obKey, &subKey, &fileName))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegLoadKey(hKey, subKey, fileName );
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegLoadKey");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyOpenKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
-
- char *subKey;
- int res = 0;
- HKEY retKey;
- long rc;
- REGSAM sam = KEY_READ;
- if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey,
- &res, &sam))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
- return PyHKEY_FromHKEY(retKey);
+ HKEY hKey;
+ PyObject *obKey;
+
+ char *subKey;
+ int res = 0;
+ HKEY retKey;
+ long rc;
+ REGSAM sam = KEY_READ;
+ if (!PyArg_ParseTuple(args, "Oz|ii:OpenKey", &obKey, &subKey,
+ &res, &sam))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegOpenKeyEx(hKey, subKey, res, sam, &retKey);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegOpenKeyEx");
+ return PyHKEY_FromHKEY(retKey);
}
@@ -1348,18 +1348,18 @@ PyQueryInfoKey(PyObject *self, PyObject *args)
PyObject *l;
PyObject *ret;
if (!PyArg_ParseTuple(args, "O:QueryInfoKey", &obKey))
- return NULL;
+ return NULL;
if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
+ return NULL;
if ((rc = RegQueryInfoKey(hKey, NULL, NULL, 0, &nSubKeys, NULL, NULL,
- &nValues, NULL, NULL, NULL, &ft))
+ &nValues, NULL, NULL, NULL, &ft))
!= ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegQueryInfoKey");
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
l = PyLong_FromLongLong(li.QuadPart);
if (l == NULL)
- return NULL;
+ return NULL;
ret = Py_BuildValue("iiO", nSubKeys, nValues, l);
Py_DECREF(l);
return ret;
@@ -1368,338 +1368,338 @@ PyQueryInfoKey(PyObject *self, PyObject *args)
static PyObject *
PyQueryValue(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- long rc;
- PyObject *retStr;
- char *retBuf;
- long bufSize = 0;
-
- if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey))
- return NULL;
-
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize))
- != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegQueryValue");
- retStr = PyString_FromStringAndSize(NULL, bufSize);
- if (retStr == NULL)
- return NULL;
- retBuf = PyString_AS_STRING(retStr);
- if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize))
- != ERROR_SUCCESS) {
- Py_DECREF(retStr);
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegQueryValue");
- }
- _PyString_Resize(&retStr, strlen(retBuf));
- return retStr;
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ long rc;
+ PyObject *retStr;
+ char *retBuf;
+ long bufSize = 0;
+
+ if (!PyArg_ParseTuple(args, "Oz:QueryValue", &obKey, &subKey))
+ return NULL;
+
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ if ((rc = RegQueryValue(hKey, subKey, NULL, &bufSize))
+ != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegQueryValue");
+ retStr = PyString_FromStringAndSize(NULL, bufSize);
+ if (retStr == NULL)
+ return NULL;
+ retBuf = PyString_AS_STRING(retStr);
+ if ((rc = RegQueryValue(hKey, subKey, retBuf, &bufSize))
+ != ERROR_SUCCESS) {
+ Py_DECREF(retStr);
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegQueryValue");
+ }
+ _PyString_Resize(&retStr, strlen(retBuf));
+ return retStr;
}
static PyObject *
PyQueryValueEx(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *valueName;
-
- long rc;
- char *retBuf;
- DWORD bufSize = 0;
- DWORD typ;
- PyObject *obData;
- PyObject *result;
-
- if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName))
- return NULL;
-
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- if ((rc = RegQueryValueEx(hKey, valueName,
- NULL, NULL, NULL,
- &bufSize))
- != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegQueryValueEx");
- retBuf = (char *)PyMem_Malloc(bufSize);
- if (retBuf == NULL)
- return PyErr_NoMemory();
- if ((rc = RegQueryValueEx(hKey, valueName, NULL,
- &typ, (BYTE *)retBuf, &bufSize))
- != ERROR_SUCCESS) {
- PyMem_Free(retBuf);
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegQueryValueEx");
- }
- obData = Reg2Py(retBuf, bufSize, typ);
- PyMem_Free((void *)retBuf);
- if (obData == NULL)
- return NULL;
- result = Py_BuildValue("Oi", obData, typ);
- Py_DECREF(obData);
- return result;
+ HKEY hKey;
+ PyObject *obKey;
+ char *valueName;
+
+ long rc;
+ char *retBuf;
+ DWORD bufSize = 0;
+ DWORD typ;
+ PyObject *obData;
+ PyObject *result;
+
+ if (!PyArg_ParseTuple(args, "Oz:QueryValueEx", &obKey, &valueName))
+ return NULL;
+
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ if ((rc = RegQueryValueEx(hKey, valueName,
+ NULL, NULL, NULL,
+ &bufSize))
+ != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegQueryValueEx");
+ retBuf = (char *)PyMem_Malloc(bufSize);
+ if (retBuf == NULL)
+ return PyErr_NoMemory();
+ if ((rc = RegQueryValueEx(hKey, valueName, NULL,
+ &typ, (BYTE *)retBuf, &bufSize))
+ != ERROR_SUCCESS) {
+ PyMem_Free(retBuf);
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegQueryValueEx");
+ }
+ obData = Reg2Py(retBuf, bufSize, typ);
+ PyMem_Free((void *)retBuf);
+ if (obData == NULL)
+ return NULL;
+ result = Py_BuildValue("Oi", obData, typ);
+ Py_DECREF(obData);
+ return result;
}
static PyObject *
PySaveKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *fileName;
- LPSECURITY_ATTRIBUTES pSA = NULL;
-
- long rc;
- if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
+ HKEY hKey;
+ PyObject *obKey;
+ char *fileName;
+ LPSECURITY_ATTRIBUTES pSA = NULL;
+
+ long rc;
+ if (!PyArg_ParseTuple(args, "Os:SaveKey", &obKey, &fileName))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
/* One day we may get security into the core?
- if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
- return NULL;
+ if (!PyWinObject_AsSECURITY_ATTRIBUTES(obSA, &pSA, TRUE))
+ return NULL;
*/
- Py_BEGIN_ALLOW_THREADS
- rc = RegSaveKey(hKey, fileName, pSA );
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
- Py_INCREF(Py_None);
- return Py_None;
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegSaveKey(hKey, fileName, pSA );
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegSaveKey");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PySetValue(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *subKey;
- char *str;
- DWORD typ;
- DWORD len;
- long rc;
- PyObject *obStrVal;
- PyObject *obSubKey;
- if (!PyArg_ParseTuple(args, "OOiO:SetValue",
- &obKey,
- &obSubKey,
- &typ,
- &obStrVal))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- if (typ != REG_SZ) {
- PyErr_SetString(PyExc_TypeError,
- "Type must be _winreg.REG_SZ");
- return NULL;
- }
- /* XXX - need Unicode support */
- str = PyString_AsString(obStrVal);
- if (str == NULL)
- return NULL;
- len = PyString_Size(obStrVal);
- if (obSubKey == Py_None)
- subKey = NULL;
- else {
- subKey = PyString_AsString(obSubKey);
- if (subKey == NULL)
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ char *subKey;
+ char *str;
+ DWORD typ;
+ DWORD len;
+ long rc;
+ PyObject *obStrVal;
+ PyObject *obSubKey;
+ if (!PyArg_ParseTuple(args, "OOiO:SetValue",
+ &obKey,
+ &obSubKey,
+ &typ,
+ &obStrVal))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ if (typ != REG_SZ) {
+ PyErr_SetString(PyExc_TypeError,
+ "Type must be _winreg.REG_SZ");
+ return NULL;
+ }
+ /* XXX - need Unicode support */
+ str = PyString_AsString(obStrVal);
+ if (str == NULL)
+ return NULL;
+ len = PyString_Size(obStrVal);
+ if (obSubKey == Py_None)
+ subKey = NULL;
+ else {
+ subKey = PyString_AsString(obSubKey);
+ if (subKey == NULL)
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegSetValue(hKey, subKey, REG_SZ, str, len+1);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc, "RegSetValue");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PySetValueEx(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- char *valueName;
- PyObject *obRes;
- PyObject *value;
- BYTE *data;
- DWORD len;
- DWORD typ;
-
- LONG rc;
-
- if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx",
- &obKey,
- &valueName,
- &obRes,
- &typ,
- &value))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
- if (!Py2Reg(value, typ, &data, &len))
- {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_ValueError,
- "Could not convert the data to the specified type.");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- rc = RegSetValueEx(hKey, valueName, 0, typ, data, len);
- Py_END_ALLOW_THREADS
- PyMem_DEL(data);
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegSetValueEx");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ char *valueName;
+ PyObject *obRes;
+ PyObject *value;
+ BYTE *data;
+ DWORD len;
+ DWORD typ;
+
+ LONG rc;
+
+ if (!PyArg_ParseTuple(args, "OzOiO:SetValueEx",
+ &obKey,
+ &valueName,
+ &obRes,
+ &typ,
+ &value))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+ if (!Py2Reg(value, typ, &data, &len))
+ {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_ValueError,
+ "Could not convert the data to the specified type.");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ rc = RegSetValueEx(hKey, valueName, 0, typ, data, len);
+ Py_END_ALLOW_THREADS
+ PyMem_DEL(data);
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegSetValueEx");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyDisableReflectionKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- HMODULE hMod;
- typedef LONG (WINAPI *RDRKFunc)(HKEY);
- RDRKFunc pfn = NULL;
- LONG rc;
-
- if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- /* Only available on 64bit platforms, so we must load it
- dynamically. */
- hMod = GetModuleHandle("advapi32.dll");
- if (hMod)
- pfn = (RDRKFunc)GetProcAddress(hMod,
- "RegDisableReflectionKey");
- if (!pfn) {
- PyErr_SetString(PyExc_NotImplementedError,
- "not implemented on this platform");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- rc = (*pfn)(hKey);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegDisableReflectionKey");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ HMODULE hMod;
+ typedef LONG (WINAPI *RDRKFunc)(HKEY);
+ RDRKFunc pfn = NULL;
+ LONG rc;
+
+ if (!PyArg_ParseTuple(args, "O:DisableReflectionKey", &obKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ /* Only available on 64bit platforms, so we must load it
+ dynamically. */
+ hMod = GetModuleHandle("advapi32.dll");
+ if (hMod)
+ pfn = (RDRKFunc)GetProcAddress(hMod,
+ "RegDisableReflectionKey");
+ if (!pfn) {
+ PyErr_SetString(PyExc_NotImplementedError,
+ "not implemented on this platform");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ rc = (*pfn)(hKey);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegDisableReflectionKey");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyEnableReflectionKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- HMODULE hMod;
- typedef LONG (WINAPI *RERKFunc)(HKEY);
- RERKFunc pfn = NULL;
- LONG rc;
-
- if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- /* Only available on 64bit platforms, so we must load it
- dynamically. */
- hMod = GetModuleHandle("advapi32.dll");
- if (hMod)
- pfn = (RERKFunc)GetProcAddress(hMod,
- "RegEnableReflectionKey");
- if (!pfn) {
- PyErr_SetString(PyExc_NotImplementedError,
- "not implemented on this platform");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- rc = (*pfn)(hKey);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegEnableReflectionKey");
- Py_INCREF(Py_None);
- return Py_None;
+ HKEY hKey;
+ PyObject *obKey;
+ HMODULE hMod;
+ typedef LONG (WINAPI *RERKFunc)(HKEY);
+ RERKFunc pfn = NULL;
+ LONG rc;
+
+ if (!PyArg_ParseTuple(args, "O:EnableReflectionKey", &obKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ /* Only available on 64bit platforms, so we must load it
+ dynamically. */
+ hMod = GetModuleHandle("advapi32.dll");
+ if (hMod)
+ pfn = (RERKFunc)GetProcAddress(hMod,
+ "RegEnableReflectionKey");
+ if (!pfn) {
+ PyErr_SetString(PyExc_NotImplementedError,
+ "not implemented on this platform");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ rc = (*pfn)(hKey);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegEnableReflectionKey");
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
PyQueryReflectionKey(PyObject *self, PyObject *args)
{
- HKEY hKey;
- PyObject *obKey;
- HMODULE hMod;
- typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *);
- RQRKFunc pfn = NULL;
- BOOL result;
- LONG rc;
-
- if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey))
- return NULL;
- if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
- return NULL;
-
- /* Only available on 64bit platforms, so we must load it
- dynamically. */
- hMod = GetModuleHandle("advapi32.dll");
- if (hMod)
- pfn = (RQRKFunc)GetProcAddress(hMod,
- "RegQueryReflectionKey");
- if (!pfn) {
- PyErr_SetString(PyExc_NotImplementedError,
- "not implemented on this platform");
- return NULL;
- }
- Py_BEGIN_ALLOW_THREADS
- rc = (*pfn)(hKey, &result);
- Py_END_ALLOW_THREADS
- if (rc != ERROR_SUCCESS)
- return PyErr_SetFromWindowsErrWithFunction(rc,
- "RegQueryReflectionKey");
- return PyBool_FromLong(result);
+ HKEY hKey;
+ PyObject *obKey;
+ HMODULE hMod;
+ typedef LONG (WINAPI *RQRKFunc)(HKEY, BOOL *);
+ RQRKFunc pfn = NULL;
+ BOOL result;
+ LONG rc;
+
+ if (!PyArg_ParseTuple(args, "O:QueryReflectionKey", &obKey))
+ return NULL;
+ if (!PyHKEY_AsHKEY(obKey, &hKey, FALSE))
+ return NULL;
+
+ /* Only available on 64bit platforms, so we must load it
+ dynamically. */
+ hMod = GetModuleHandle("advapi32.dll");
+ if (hMod)
+ pfn = (RQRKFunc)GetProcAddress(hMod,
+ "RegQueryReflectionKey");
+ if (!pfn) {
+ PyErr_SetString(PyExc_NotImplementedError,
+ "not implemented on this platform");
+ return NULL;
+ }
+ Py_BEGIN_ALLOW_THREADS
+ rc = (*pfn)(hKey, &result);
+ Py_END_ALLOW_THREADS
+ if (rc != ERROR_SUCCESS)
+ return PyErr_SetFromWindowsErrWithFunction(rc,
+ "RegQueryReflectionKey");
+ return PyBool_FromLong(result);
}
static struct PyMethodDef winreg_methods[] = {
- {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc},
- {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc},
- {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc},
- {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc},
- {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc},
- {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc},
- {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc},
- {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc},
- {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc},
- {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc},
- {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc},
- {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS,
- ExpandEnvironmentStrings_doc },
- {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc},
- {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc},
- {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc},
- {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc},
- {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc},
- {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc},
- {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc},
- {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc},
- {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc},
- {"SetValue", PySetValue, METH_VARARGS, SetValue_doc},
- {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc},
- NULL,
+ {"CloseKey", PyCloseKey, METH_VARARGS, CloseKey_doc},
+ {"ConnectRegistry", PyConnectRegistry, METH_VARARGS, ConnectRegistry_doc},
+ {"CreateKey", PyCreateKey, METH_VARARGS, CreateKey_doc},
+ {"CreateKeyEx", PyCreateKeyEx, METH_VARARGS, CreateKeyEx_doc},
+ {"DeleteKey", PyDeleteKey, METH_VARARGS, DeleteKey_doc},
+ {"DeleteKeyEx", PyDeleteKeyEx, METH_VARARGS, DeleteKeyEx_doc},
+ {"DeleteValue", PyDeleteValue, METH_VARARGS, DeleteValue_doc},
+ {"DisableReflectionKey", PyDisableReflectionKey, METH_VARARGS, DisableReflectionKey_doc},
+ {"EnableReflectionKey", PyEnableReflectionKey, METH_VARARGS, EnableReflectionKey_doc},
+ {"EnumKey", PyEnumKey, METH_VARARGS, EnumKey_doc},
+ {"EnumValue", PyEnumValue, METH_VARARGS, EnumValue_doc},
+ {"ExpandEnvironmentStrings", PyExpandEnvironmentStrings, METH_VARARGS,
+ ExpandEnvironmentStrings_doc },
+ {"FlushKey", PyFlushKey, METH_VARARGS, FlushKey_doc},
+ {"LoadKey", PyLoadKey, METH_VARARGS, LoadKey_doc},
+ {"OpenKey", PyOpenKey, METH_VARARGS, OpenKey_doc},
+ {"OpenKeyEx", PyOpenKey, METH_VARARGS, OpenKeyEx_doc},
+ {"QueryValue", PyQueryValue, METH_VARARGS, QueryValue_doc},
+ {"QueryValueEx", PyQueryValueEx, METH_VARARGS, QueryValueEx_doc},
+ {"QueryInfoKey", PyQueryInfoKey, METH_VARARGS, QueryInfoKey_doc},
+ {"QueryReflectionKey",PyQueryReflectionKey,METH_VARARGS, QueryReflectionKey_doc},
+ {"SaveKey", PySaveKey, METH_VARARGS, SaveKey_doc},
+ {"SetValue", PySetValue, METH_VARARGS, SetValue_doc},
+ {"SetValueEx", PySetValueEx, METH_VARARGS, SetValueEx_doc},
+ NULL,
};
static void
insint(PyObject * d, char * name, long value)
{
- PyObject *v = PyInt_FromLong(value);
- if (!v || PyDict_SetItemString(d, name, v))
- PyErr_Clear();
- Py_XDECREF(v);
+ PyObject *v = PyInt_FromLong(value);
+ if (!v || PyDict_SetItemString(d, name, v))
+ PyErr_Clear();
+ Py_XDECREF(v);
}
#define ADD_INT(val) insint(d, #val, val)
@@ -1707,89 +1707,89 @@ insint(PyObject * d, char * name, long value)
static void
inskey(PyObject * d, char * name, HKEY key)
{
- PyObject *v = PyLong_FromVoidPtr(key);
- if (!v || PyDict_SetItemString(d, name, v))
- PyErr_Clear();
- Py_XDECREF(v);
+ PyObject *v = PyLong_FromVoidPtr(key);
+ if (!v || PyDict_SetItemString(d, name, v))
+ PyErr_Clear();
+ Py_XDECREF(v);
}
#define ADD_KEY(val) inskey(d, #val, val)
PyMODINIT_FUNC init_winreg(void)
{
- PyObject *m, *d;
- m = Py_InitModule3("_winreg", winreg_methods, module_doc);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
- if (PyType_Ready(&PyHKEY_Type) < 0)
- return;
- PyHKEY_Type.tp_doc = PyHKEY_doc;
- Py_INCREF(&PyHKEY_Type);
- if (PyDict_SetItemString(d, "HKEYType",
- (PyObject *)&PyHKEY_Type) != 0)
- return;
- Py_INCREF(PyExc_WindowsError);
- if (PyDict_SetItemString(d, "error",
- PyExc_WindowsError) != 0)
- return;
-
- /* Add the relevant constants */
- ADD_KEY(HKEY_CLASSES_ROOT);
- ADD_KEY(HKEY_CURRENT_USER);
- ADD_KEY(HKEY_LOCAL_MACHINE);
- ADD_KEY(HKEY_USERS);
- ADD_KEY(HKEY_PERFORMANCE_DATA);
+ PyObject *m, *d;
+ m = Py_InitModule3("_winreg", winreg_methods, module_doc);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+ if (PyType_Ready(&PyHKEY_Type) < 0)
+ return;
+ PyHKEY_Type.tp_doc = PyHKEY_doc;
+ Py_INCREF(&PyHKEY_Type);
+ if (PyDict_SetItemString(d, "HKEYType",
+ (PyObject *)&PyHKEY_Type) != 0)
+ return;
+ Py_INCREF(PyExc_WindowsError);
+ if (PyDict_SetItemString(d, "error",
+ PyExc_WindowsError) != 0)
+ return;
+
+ /* Add the relevant constants */
+ ADD_KEY(HKEY_CLASSES_ROOT);
+ ADD_KEY(HKEY_CURRENT_USER);
+ ADD_KEY(HKEY_LOCAL_MACHINE);
+ ADD_KEY(HKEY_USERS);
+ ADD_KEY(HKEY_PERFORMANCE_DATA);
#ifdef HKEY_CURRENT_CONFIG
- ADD_KEY(HKEY_CURRENT_CONFIG);
+ ADD_KEY(HKEY_CURRENT_CONFIG);
#endif
#ifdef HKEY_DYN_DATA
- ADD_KEY(HKEY_DYN_DATA);
+ ADD_KEY(HKEY_DYN_DATA);
#endif
- ADD_INT(KEY_QUERY_VALUE);
- ADD_INT(KEY_SET_VALUE);
- ADD_INT(KEY_CREATE_SUB_KEY);
- ADD_INT(KEY_ENUMERATE_SUB_KEYS);
- ADD_INT(KEY_NOTIFY);
- ADD_INT(KEY_CREATE_LINK);
- ADD_INT(KEY_READ);
- ADD_INT(KEY_WRITE);
- ADD_INT(KEY_EXECUTE);
- ADD_INT(KEY_ALL_ACCESS);
+ ADD_INT(KEY_QUERY_VALUE);
+ ADD_INT(KEY_SET_VALUE);
+ ADD_INT(KEY_CREATE_SUB_KEY);
+ ADD_INT(KEY_ENUMERATE_SUB_KEYS);
+ ADD_INT(KEY_NOTIFY);
+ ADD_INT(KEY_CREATE_LINK);
+ ADD_INT(KEY_READ);
+ ADD_INT(KEY_WRITE);
+ ADD_INT(KEY_EXECUTE);
+ ADD_INT(KEY_ALL_ACCESS);
#ifdef KEY_WOW64_64KEY
- ADD_INT(KEY_WOW64_64KEY);
+ ADD_INT(KEY_WOW64_64KEY);
#endif
#ifdef KEY_WOW64_32KEY
- ADD_INT(KEY_WOW64_32KEY);
+ ADD_INT(KEY_WOW64_32KEY);
#endif
- ADD_INT(REG_OPTION_RESERVED);
- ADD_INT(REG_OPTION_NON_VOLATILE);
- ADD_INT(REG_OPTION_VOLATILE);
- ADD_INT(REG_OPTION_CREATE_LINK);
- ADD_INT(REG_OPTION_BACKUP_RESTORE);
- ADD_INT(REG_OPTION_OPEN_LINK);
- ADD_INT(REG_LEGAL_OPTION);
- ADD_INT(REG_CREATED_NEW_KEY);
- ADD_INT(REG_OPENED_EXISTING_KEY);
- ADD_INT(REG_WHOLE_HIVE_VOLATILE);
- ADD_INT(REG_REFRESH_HIVE);
- ADD_INT(REG_NO_LAZY_FLUSH);
- ADD_INT(REG_NOTIFY_CHANGE_NAME);
- ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
- ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
- ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
- ADD_INT(REG_LEGAL_CHANGE_FILTER);
- ADD_INT(REG_NONE);
- ADD_INT(REG_SZ);
- ADD_INT(REG_EXPAND_SZ);
- ADD_INT(REG_BINARY);
- ADD_INT(REG_DWORD);
- ADD_INT(REG_DWORD_LITTLE_ENDIAN);
- ADD_INT(REG_DWORD_BIG_ENDIAN);
- ADD_INT(REG_LINK);
- ADD_INT(REG_MULTI_SZ);
- ADD_INT(REG_RESOURCE_LIST);
- ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
- ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
+ ADD_INT(REG_OPTION_RESERVED);
+ ADD_INT(REG_OPTION_NON_VOLATILE);
+ ADD_INT(REG_OPTION_VOLATILE);
+ ADD_INT(REG_OPTION_CREATE_LINK);
+ ADD_INT(REG_OPTION_BACKUP_RESTORE);
+ ADD_INT(REG_OPTION_OPEN_LINK);
+ ADD_INT(REG_LEGAL_OPTION);
+ ADD_INT(REG_CREATED_NEW_KEY);
+ ADD_INT(REG_OPENED_EXISTING_KEY);
+ ADD_INT(REG_WHOLE_HIVE_VOLATILE);
+ ADD_INT(REG_REFRESH_HIVE);
+ ADD_INT(REG_NO_LAZY_FLUSH);
+ ADD_INT(REG_NOTIFY_CHANGE_NAME);
+ ADD_INT(REG_NOTIFY_CHANGE_ATTRIBUTES);
+ ADD_INT(REG_NOTIFY_CHANGE_LAST_SET);
+ ADD_INT(REG_NOTIFY_CHANGE_SECURITY);
+ ADD_INT(REG_LEGAL_CHANGE_FILTER);
+ ADD_INT(REG_NONE);
+ ADD_INT(REG_SZ);
+ ADD_INT(REG_EXPAND_SZ);
+ ADD_INT(REG_BINARY);
+ ADD_INT(REG_DWORD);
+ ADD_INT(REG_DWORD_LITTLE_ENDIAN);
+ ADD_INT(REG_DWORD_BIG_ENDIAN);
+ ADD_INT(REG_LINK);
+ ADD_INT(REG_MULTI_SZ);
+ ADD_INT(REG_RESOURCE_LIST);
+ ADD_INT(REG_FULL_RESOURCE_DESCRIPTOR);
+ ADD_INT(REG_RESOURCE_REQUIREMENTS_LIST);
}
diff --git a/PC/bdist_wininst/archive.h b/PC/bdist_wininst/archive.h
index 35d2fd6..31a7805 100644
--- a/PC/bdist_wininst/archive.h
+++ b/PC/bdist_wininst/archive.h
@@ -14,55 +14,55 @@
*/
struct eof_cdir {
- long tag; /* must be 0x06054b50 */
- short disknum;
- short firstdisk;
- short nTotalCDirThis;
- short nTotalCDir;
- long nBytesCDir;
- long ofsCDir;
- short commentlen;
+ long tag; /* must be 0x06054b50 */
+ short disknum;
+ short firstdisk;
+ short nTotalCDirThis;
+ short nTotalCDir;
+ long nBytesCDir;
+ long ofsCDir;
+ short commentlen;
};
struct cdir {
- long tag; /* must be 0x02014b50 */
- short version_made;
- short version_extract;
- short gp_bitflag;
- short comp_method;
- short last_mod_file_time;
- short last_mod_file_date;
- long crc32;
- long comp_size;
- long uncomp_size;
- short fname_length;
- short extra_length;
- short comment_length;
- short disknum_start;
- short int_file_attr;
- long ext_file_attr;
- long ofs_local_header;
+ long tag; /* must be 0x02014b50 */
+ short version_made;
+ short version_extract;
+ short gp_bitflag;
+ short comp_method;
+ short last_mod_file_time;
+ short last_mod_file_date;
+ long crc32;
+ long comp_size;
+ long uncomp_size;
+ short fname_length;
+ short extra_length;
+ short comment_length;
+ short disknum_start;
+ short int_file_attr;
+ long ext_file_attr;
+ long ofs_local_header;
};
struct fhdr {
- long tag; /* must be 0x04034b50 */
- short version_needed;
- short flags;
- short method;
- short last_mod_file_time;
- short last_mod_file_date;
- long crc32;
- long comp_size;
- long uncomp_size;
- short fname_length;
- short extra_length;
+ long tag; /* must be 0x04034b50 */
+ short version_needed;
+ short flags;
+ short method;
+ short last_mod_file_time;
+ short last_mod_file_date;
+ long crc32;
+ long comp_size;
+ long uncomp_size;
+ short fname_length;
+ short extra_length;
};
struct meta_data_hdr {
- int tag;
- int uncomp_size;
- int bitmap_size;
+ int tag;
+ int uncomp_size;
+ int bitmap_size;
};
#pragma pack()
@@ -70,29 +70,29 @@ struct meta_data_hdr {
/* installation scheme */
typedef struct tagSCHEME {
- char *name;
- char *prefix;
+ char *name;
+ char *prefix;
} SCHEME;
typedef int (*NOTIFYPROC)(int code, LPSTR text, ...);
extern BOOL
extract_file(char *dst, char *src, int method, int comp_size,
- int uncomp_size, NOTIFYPROC notify);
+ int uncomp_size, NOTIFYPROC notify);
extern BOOL
unzip_archive(SCHEME *scheme, char *dirname, char *data,
- DWORD size, NOTIFYPROC notify);
+ DWORD size, NOTIFYPROC notify);
extern char *
map_new_file(DWORD flags, char *filename, char
- *pathname_part, int size,
- WORD wFatDate, WORD wFatTime,
- NOTIFYPROC callback);
+ *pathname_part, int size,
+ WORD wFatDate, WORD wFatTime,
+ NOTIFYPROC callback);
extern BOOL
ensure_directory (char *pathname, char *new_part,
- NOTIFYPROC callback);
+ NOTIFYPROC callback);
/* codes for NOITIFYPROC */
#define DIR_CREATED 1
diff --git a/PC/bdist_wininst/extract.c b/PC/bdist_wininst/extract.c
index b495e1c..fc2d2b9 100644
--- a/PC/bdist_wininst/extract.c
+++ b/PC/bdist_wininst/extract.c
@@ -19,181 +19,181 @@
/* Convert unix-path to dos-path */
static void normpath(char *path)
{
- while (path && *path) {
- if (*path == '/')
- *path = '\\';
- ++path;
- }
+ while (path && *path) {
+ if (*path == '/')
+ *path = '\\';
+ ++path;
+ }
}
BOOL ensure_directory(char *pathname, char *new_part, NOTIFYPROC notify)
{
- while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) {
- DWORD attr;
- *new_part = '\0';
- attr = GetFileAttributes(pathname);
- if (attr == -1) {
- /* nothing found */
- if (!CreateDirectory(pathname, NULL) && notify)
- notify(SYSTEM_ERROR,
- "CreateDirectory (%s)", pathname);
- else
- notify(DIR_CREATED, pathname);
- }
- if (attr & FILE_ATTRIBUTE_DIRECTORY) {
- ;
- } else {
- SetLastError(183);
- if (notify)
- notify(SYSTEM_ERROR,
- "CreateDirectory (%s)", pathname);
- }
- *new_part = '\\';
- ++new_part;
- }
- return TRUE;
+ while (new_part && *new_part && (new_part = strchr(new_part, '\\'))) {
+ DWORD attr;
+ *new_part = '\0';
+ attr = GetFileAttributes(pathname);
+ if (attr == -1) {
+ /* nothing found */
+ if (!CreateDirectory(pathname, NULL) && notify)
+ notify(SYSTEM_ERROR,
+ "CreateDirectory (%s)", pathname);
+ else
+ notify(DIR_CREATED, pathname);
+ }
+ if (attr & FILE_ATTRIBUTE_DIRECTORY) {
+ ;
+ } else {
+ SetLastError(183);
+ if (notify)
+ notify(SYSTEM_ERROR,
+ "CreateDirectory (%s)", pathname);
+ }
+ *new_part = '\\';
+ ++new_part;
+ }
+ return TRUE;
}
/* XXX Should better explicitely specify
* uncomp_size and file_times instead of pfhdr!
*/
char *map_new_file(DWORD flags, char *filename,
- char *pathname_part, int size,
- WORD wFatDate, WORD wFatTime,
- NOTIFYPROC notify)
+ char *pathname_part, int size,
+ WORD wFatDate, WORD wFatTime,
+ NOTIFYPROC notify)
{
- HANDLE hFile, hFileMapping;
- char *dst;
- FILETIME ft;
+ HANDLE hFile, hFileMapping;
+ char *dst;
+ FILETIME ft;
try_again:
- if (!flags)
- flags = CREATE_NEW;
- hFile = CreateFile(filename,
- GENERIC_WRITE | GENERIC_READ,
- 0, NULL,
- flags,
- FILE_ATTRIBUTE_NORMAL, NULL);
- if (hFile == INVALID_HANDLE_VALUE) {
- DWORD x = GetLastError();
- switch (x) {
- case ERROR_FILE_EXISTS:
- if (notify && notify(CAN_OVERWRITE, filename))
- hFile = CreateFile(filename,
- GENERIC_WRITE|GENERIC_READ,
- 0, NULL,
- CREATE_ALWAYS,
- FILE_ATTRIBUTE_NORMAL,
- NULL);
- else {
- if (notify)
- notify(FILE_OVERWRITTEN, filename);
- return NULL;
- }
- break;
- case ERROR_PATH_NOT_FOUND:
- if (ensure_directory(filename, pathname_part, notify))
- goto try_again;
- else
- return FALSE;
- break;
- default:
- SetLastError(x);
- break;
- }
- }
- if (hFile == INVALID_HANDLE_VALUE) {
- if (notify)
- notify (SYSTEM_ERROR, "CreateFile (%s)", filename);
- return NULL;
- }
-
- if (notify)
- notify(FILE_CREATED, filename);
-
- DosDateTimeToFileTime(wFatDate, wFatTime, &ft);
- SetFileTime(hFile, &ft, &ft, &ft);
-
-
- if (size == 0) {
- /* We cannot map a zero-length file (Also it makes
- no sense */
- CloseHandle(hFile);
- return NULL;
- }
-
- hFileMapping = CreateFileMapping(hFile,
- NULL, PAGE_READWRITE, 0, size, NULL);
-
- CloseHandle(hFile);
-
- if (hFileMapping == INVALID_HANDLE_VALUE) {
- if (notify)
- notify(SYSTEM_ERROR,
- "CreateFileMapping (%s)", filename);
- return NULL;
- }
-
- dst = MapViewOfFile(hFileMapping,
- FILE_MAP_WRITE, 0, 0, 0);
-
- CloseHandle(hFileMapping);
-
- if (!dst) {
- if (notify)
- notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename);
- return NULL;
- }
- return dst;
+ if (!flags)
+ flags = CREATE_NEW;
+ hFile = CreateFile(filename,
+ GENERIC_WRITE | GENERIC_READ,
+ 0, NULL,
+ flags,
+ FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == INVALID_HANDLE_VALUE) {
+ DWORD x = GetLastError();
+ switch (x) {
+ case ERROR_FILE_EXISTS:
+ if (notify && notify(CAN_OVERWRITE, filename))
+ hFile = CreateFile(filename,
+ GENERIC_WRITE|GENERIC_READ,
+ 0, NULL,
+ CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL,
+ NULL);
+ else {
+ if (notify)
+ notify(FILE_OVERWRITTEN, filename);
+ return NULL;
+ }
+ break;
+ case ERROR_PATH_NOT_FOUND:
+ if (ensure_directory(filename, pathname_part, notify))
+ goto try_again;
+ else
+ return FALSE;
+ break;
+ default:
+ SetLastError(x);
+ break;
+ }
+ }
+ if (hFile == INVALID_HANDLE_VALUE) {
+ if (notify)
+ notify (SYSTEM_ERROR, "CreateFile (%s)", filename);
+ return NULL;
+ }
+
+ if (notify)
+ notify(FILE_CREATED, filename);
+
+ DosDateTimeToFileTime(wFatDate, wFatTime, &ft);
+ SetFileTime(hFile, &ft, &ft, &ft);
+
+
+ if (size == 0) {
+ /* We cannot map a zero-length file (Also it makes
+ no sense */
+ CloseHandle(hFile);
+ return NULL;
+ }
+
+ hFileMapping = CreateFileMapping(hFile,
+ NULL, PAGE_READWRITE, 0, size, NULL);
+
+ CloseHandle(hFile);
+
+ if (hFileMapping == INVALID_HANDLE_VALUE) {
+ if (notify)
+ notify(SYSTEM_ERROR,
+ "CreateFileMapping (%s)", filename);
+ return NULL;
+ }
+
+ dst = MapViewOfFile(hFileMapping,
+ FILE_MAP_WRITE, 0, 0, 0);
+
+ CloseHandle(hFileMapping);
+
+ if (!dst) {
+ if (notify)
+ notify(SYSTEM_ERROR, "MapViewOfFile (%s)", filename);
+ return NULL;
+ }
+ return dst;
}
BOOL
extract_file(char *dst, char *src, int method, int comp_size,
- int uncomp_size, NOTIFYPROC notify)
+ int uncomp_size, NOTIFYPROC notify)
{
- z_stream zstream;
- int result;
+ z_stream zstream;
+ int result;
- if (method == Z_DEFLATED) {
- int x;
- memset(&zstream, 0, sizeof(zstream));
- zstream.next_in = src;
- zstream.avail_in = comp_size+1;
- zstream.next_out = dst;
- zstream.avail_out = uncomp_size;
+ if (method == Z_DEFLATED) {
+ int x;
+ memset(&zstream, 0, sizeof(zstream));
+ zstream.next_in = src;
+ zstream.avail_in = comp_size+1;
+ zstream.next_out = dst;
+ zstream.avail_out = uncomp_size;
/* Apparently an undocumented feature of zlib: Set windowsize
to negative values to supress the gzip header and be compatible with
zip! */
- result = TRUE;
- if (Z_OK != (x = inflateInit2(&zstream, -15))) {
- if (notify)
- notify(ZLIB_ERROR,
- "inflateInit2 returns %d", x);
- result = FALSE;
- goto cleanup;
- }
- if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) {
- if (notify)
- notify(ZLIB_ERROR,
- "inflate returns %d", x);
- result = FALSE;
- }
- cleanup:
- if (Z_OK != (x = inflateEnd(&zstream))) {
- if (notify)
- notify (ZLIB_ERROR,
- "inflateEnd returns %d", x);
- result = FALSE;
- }
- } else if (method == 0) {
- memcpy(dst, src, uncomp_size);
- result = TRUE;
- } else
- result = FALSE;
- UnmapViewOfFile(dst);
- return result;
+ result = TRUE;
+ if (Z_OK != (x = inflateInit2(&zstream, -15))) {
+ if (notify)
+ notify(ZLIB_ERROR,
+ "inflateInit2 returns %d", x);
+ result = FALSE;
+ goto cleanup;
+ }
+ if (Z_STREAM_END != (x = inflate(&zstream, Z_FINISH))) {
+ if (notify)
+ notify(ZLIB_ERROR,
+ "inflate returns %d", x);
+ result = FALSE;
+ }
+ cleanup:
+ if (Z_OK != (x = inflateEnd(&zstream))) {
+ if (notify)
+ notify (ZLIB_ERROR,
+ "inflateEnd returns %d", x);
+ result = FALSE;
+ }
+ } else if (method == 0) {
+ memcpy(dst, src, uncomp_size);
+ result = TRUE;
+ } else
+ result = FALSE;
+ UnmapViewOfFile(dst);
+ return result;
}
/* Open a zip-compatible archive and extract all files
@@ -201,121 +201,121 @@ extract_file(char *dst, char *src, int method, int comp_size,
*/
BOOL
unzip_archive(SCHEME *scheme, char *dirname, char *data, DWORD size,
- NOTIFYPROC notify)
+ NOTIFYPROC notify)
{
- int n;
- char pathname[MAX_PATH];
- char *new_part;
-
- /* read the end of central directory record */
- struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof
- (struct eof_cdir)];
-
- int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir -
- pe->ofsCDir;
-
- /* set position to start of central directory */
- int pos = arc_start + pe->ofsCDir;
-
- /* make sure this is a zip file */
- if (pe->tag != 0x06054b50)
- return FALSE;
-
- /* Loop through the central directory, reading all entries */
- for (n = 0; n < pe->nTotalCDir; ++n) {
- int i;
- char *fname;
- char *pcomp;
- char *dst;
- struct cdir *pcdir;
- struct fhdr *pfhdr;
-
- pcdir = (struct cdir *)&data[pos];
- pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header +
- arc_start];
-
- if (pcdir->tag != 0x02014b50)
- return FALSE;
- if (pfhdr->tag != 0x04034b50)
- return FALSE;
- pos += sizeof(struct cdir);
- fname = (char *)&data[pos]; /* This is not null terminated! */
- pos += pcdir->fname_length + pcdir->extra_length +
- pcdir->comment_length;
-
- pcomp = &data[pcdir->ofs_local_header
- + sizeof(struct fhdr)
- + arc_start
- + pfhdr->fname_length
- + pfhdr->extra_length];
-
- /* dirname is the Python home directory (prefix) */
- strcpy(pathname, dirname);
- if (pathname[strlen(pathname)-1] != '\\')
- strcat(pathname, "\\");
- new_part = &pathname[lstrlen(pathname)];
- /* we must now match the first part of the pathname
- * in the archive to a component in the installation
- * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA)
- * and replace this part by the one in the scheme to use
- */
- for (i = 0; scheme[i].name; ++i) {
- if (0 == strnicmp(scheme[i].name, fname,
- strlen(scheme[i].name))) {
- char *rest;
- int len;
-
- /* length of the replaced part */
- int namelen = strlen(scheme[i].name);
-
- strcat(pathname, scheme[i].prefix);
-
- rest = fname + namelen;
- len = pfhdr->fname_length - namelen;
-
- if ((pathname[strlen(pathname)-1] != '\\')
- && (pathname[strlen(pathname)-1] != '/'))
- strcat(pathname, "\\");
- /* Now that pathname ends with a separator,
- * we must make sure rest does not start with
- * an additional one.
- */
- if ((rest[0] == '\\') || (rest[0] == '/')) {
- ++rest;
- --len;
- }
-
- strncat(pathname, rest, len);
- goto Done;
- }
- }
- /* no prefix to replace found, go unchanged */
- strncat(pathname, fname, pfhdr->fname_length);
- Done:
- normpath(pathname);
- if (pathname[strlen(pathname)-1] != '\\') {
- /*
- * The local file header (pfhdr) does not always
- * contain the compressed and uncompressed sizes of
- * the data depending on bit 3 of the flags field. So
- * it seems better to use the data from the central
- * directory (pcdir).
- */
- dst = map_new_file(0, pathname, new_part,
- pcdir->uncomp_size,
- pcdir->last_mod_file_date,
- pcdir->last_mod_file_time, notify);
- if (dst) {
- if (!extract_file(dst, pcomp, pfhdr->method,
- pcdir->comp_size,
- pcdir->uncomp_size,
- notify))
- return FALSE;
- } /* else ??? */
- }
- if (notify)
- notify(NUM_FILES, new_part, (int)pe->nTotalCDir,
- (int)n+1);
- }
- return TRUE;
+ int n;
+ char pathname[MAX_PATH];
+ char *new_part;
+
+ /* read the end of central directory record */
+ struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof
+ (struct eof_cdir)];
+
+ int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir -
+ pe->ofsCDir;
+
+ /* set position to start of central directory */
+ int pos = arc_start + pe->ofsCDir;
+
+ /* make sure this is a zip file */
+ if (pe->tag != 0x06054b50)
+ return FALSE;
+
+ /* Loop through the central directory, reading all entries */
+ for (n = 0; n < pe->nTotalCDir; ++n) {
+ int i;
+ char *fname;
+ char *pcomp;
+ char *dst;
+ struct cdir *pcdir;
+ struct fhdr *pfhdr;
+
+ pcdir = (struct cdir *)&data[pos];
+ pfhdr = (struct fhdr *)&data[pcdir->ofs_local_header +
+ arc_start];
+
+ if (pcdir->tag != 0x02014b50)
+ return FALSE;
+ if (pfhdr->tag != 0x04034b50)
+ return FALSE;
+ pos += sizeof(struct cdir);
+ fname = (char *)&data[pos]; /* This is not null terminated! */
+ pos += pcdir->fname_length + pcdir->extra_length +
+ pcdir->comment_length;
+
+ pcomp = &data[pcdir->ofs_local_header
+ + sizeof(struct fhdr)
+ + arc_start
+ + pfhdr->fname_length
+ + pfhdr->extra_length];
+
+ /* dirname is the Python home directory (prefix) */
+ strcpy(pathname, dirname);
+ if (pathname[strlen(pathname)-1] != '\\')
+ strcat(pathname, "\\");
+ new_part = &pathname[lstrlen(pathname)];
+ /* we must now match the first part of the pathname
+ * in the archive to a component in the installation
+ * scheme (PURELIB, PLATLIB, HEADERS, SCRIPTS, or DATA)
+ * and replace this part by the one in the scheme to use
+ */
+ for (i = 0; scheme[i].name; ++i) {
+ if (0 == strnicmp(scheme[i].name, fname,
+ strlen(scheme[i].name))) {
+ char *rest;
+ int len;
+
+ /* length of the replaced part */
+ int namelen = strlen(scheme[i].name);
+
+ strcat(pathname, scheme[i].prefix);
+
+ rest = fname + namelen;
+ len = pfhdr->fname_length - namelen;
+
+ if ((pathname[strlen(pathname)-1] != '\\')
+ && (pathname[strlen(pathname)-1] != '/'))
+ strcat(pathname, "\\");
+ /* Now that pathname ends with a separator,
+ * we must make sure rest does not start with
+ * an additional one.
+ */
+ if ((rest[0] == '\\') || (rest[0] == '/')) {
+ ++rest;
+ --len;
+ }
+
+ strncat(pathname, rest, len);
+ goto Done;
+ }
+ }
+ /* no prefix to replace found, go unchanged */
+ strncat(pathname, fname, pfhdr->fname_length);
+ Done:
+ normpath(pathname);
+ if (pathname[strlen(pathname)-1] != '\\') {
+ /*
+ * The local file header (pfhdr) does not always
+ * contain the compressed and uncompressed sizes of
+ * the data depending on bit 3 of the flags field. So
+ * it seems better to use the data from the central
+ * directory (pcdir).
+ */
+ dst = map_new_file(0, pathname, new_part,
+ pcdir->uncomp_size,
+ pcdir->last_mod_file_date,
+ pcdir->last_mod_file_time, notify);
+ if (dst) {
+ if (!extract_file(dst, pcomp, pfhdr->method,
+ pcdir->comp_size,
+ pcdir->uncomp_size,
+ notify))
+ return FALSE;
+ } /* else ??? */
+ }
+ if (notify)
+ notify(NUM_FILES, new_part, (int)pe->nTotalCDir,
+ (int)n+1);
+ }
+ return TRUE;
}
diff --git a/PC/bdist_wininst/install.c b/PC/bdist_wininst/install.c
index ae8d0db..d5472ef 100644
--- a/PC/bdist_wininst/install.c
+++ b/PC/bdist_wininst/install.c
@@ -20,21 +20,21 @@
*
* At runtime, the exefile has appended:
* - compressed setup-data in ini-format, containing the following sections:
- * [metadata]
- * author=Greg Ward
- * author_email=gward@python.net
- * description=Python Distribution Utilities
- * licence=Python
- * name=Distutils
- * url=http://www.python.org/sigs/distutils-sig/
- * version=0.9pre
+ * [metadata]
+ * author=Greg Ward
+ * author_email=gward@python.net
+ * description=Python Distribution Utilities
+ * licence=Python
+ * name=Distutils
+ * url=http://www.python.org/sigs/distutils-sig/
+ * version=0.9pre
*
- * [Setup]
- * info= text to be displayed in the edit-box
- * title= to be displayed by this program
- * target_version = if present, python version required
- * pyc_compile = if 0, do not compile py to pyc
- * pyo_compile = if 0, do not compile py to pyo
+ * [Setup]
+ * info= text to be displayed in the edit-box
+ * title= to be displayed by this program
+ * target_version = if present, python version required
+ * pyc_compile = if 0, do not compile py to pyc
+ * pyo_compile = if 0, do not compile py to pyo
*
* - a struct meta_data_hdr, describing the above
* - a zip-file, containing the modules to be installed.
@@ -118,28 +118,28 @@ char modulename[MAX_PATH];
HWND hwndMain;
HWND hDialog;
-char *ini_file; /* Full pathname of ini-file */
+char *ini_file; /* Full pathname of ini-file */
/* From ini-file */
-char info[4096]; /* [Setup] info= */
-char title[80]; /* [Setup] title=, contains package name
- including version: "Distutils-1.0.1" */
-char target_version[10]; /* [Setup] target_version=, required python
- version or empty string */
-char build_info[80]; /* [Setup] build_info=, distutils version
- and build date */
-
-char meta_name[80]; /* package name without version like
- 'Distutils' */
+char info[4096]; /* [Setup] info= */
+char title[80]; /* [Setup] title=, contains package name
+ including version: "Distutils-1.0.1" */
+char target_version[10]; /* [Setup] target_version=, required python
+ version or empty string */
+char build_info[80]; /* [Setup] build_info=, distutils version
+ and build date */
+
+char meta_name[80]; /* package name without version like
+ 'Distutils' */
char install_script[MAX_PATH];
char *pre_install_script; /* run before we install a single file */
char user_access_control[10]; // one of 'auto', 'force', otherwise none.
-int py_major, py_minor; /* Python version selected for installation */
+int py_major, py_minor; /* Python version selected for installation */
-char *arc_data; /* memory mapped archive */
-DWORD arc_size; /* number of bytes in archive */
-int exe_size; /* number of bytes for exe-file portion */
+char *arc_data; /* memory mapped archive */
+DWORD arc_size; /* number of bytes in archive */
+int exe_size; /* number of bytes for exe-file portion */
char python_dir[MAX_PATH];
char pythondll[MAX_PATH];
BOOL pyc_compile, pyo_compile;
@@ -147,7 +147,7 @@ BOOL pyc_compile, pyo_compile;
the permissions of the current user. */
HKEY hkey_root = (HKEY)-1;
-BOOL success; /* Installation successfull? */
+BOOL success; /* Installation successfull? */
char *failure_reason = NULL;
HANDLE hBitmap;
@@ -165,128 +165,128 @@ static BOOL notify(int code, char *fmt, ...);
/* Note: If scheme.prefix is nonempty, it must end with a '\'! */
/* Note: purelib must be the FIRST entry! */
SCHEME old_scheme[] = {
- { "PURELIB", "" },
- { "PLATLIB", "" },
- { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */
- { "SCRIPTS", "Scripts\\" },
- { "DATA", "" },
- { NULL, NULL },
+ { "PURELIB", "" },
+ { "PLATLIB", "" },
+ { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */
+ { "SCRIPTS", "Scripts\\" },
+ { "DATA", "" },
+ { NULL, NULL },
};
SCHEME new_scheme[] = {
- { "PURELIB", "Lib\\site-packages\\" },
- { "PLATLIB", "Lib\\site-packages\\" },
- { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */
- { "SCRIPTS", "Scripts\\" },
- { "DATA", "" },
- { NULL, NULL },
+ { "PURELIB", "Lib\\site-packages\\" },
+ { "PLATLIB", "Lib\\site-packages\\" },
+ { "HEADERS", "" }, /* 'Include/dist_name' part already in archive */
+ { "SCRIPTS", "Scripts\\" },
+ { "DATA", "" },
+ { NULL, NULL },
};
static void unescape(char *dst, char *src, unsigned size)
{
- char *eon;
- char ch;
-
- while (src && *src && (size > 2)) {
- if (*src == '\\') {
- switch (*++src) {
- case 'n':
- ++src;
- *dst++ = '\r';
- *dst++ = '\n';
- size -= 2;
- break;
- case 'r':
- ++src;
- *dst++ = '\r';
- --size;
- break;
- case '0': case '1': case '2': case '3':
- ch = (char)strtol(src, &eon, 8);
- if (ch == '\n') {
- *dst++ = '\r';
- --size;
- }
- *dst++ = ch;
- --size;
- src = eon;
- }
- } else {
- *dst++ = *src++;
- --size;
- }
- }
- *dst = '\0';
+ char *eon;
+ char ch;
+
+ while (src && *src && (size > 2)) {
+ if (*src == '\\') {
+ switch (*++src) {
+ case 'n':
+ ++src;
+ *dst++ = '\r';
+ *dst++ = '\n';
+ size -= 2;
+ break;
+ case 'r':
+ ++src;
+ *dst++ = '\r';
+ --size;
+ break;
+ case '0': case '1': case '2': case '3':
+ ch = (char)strtol(src, &eon, 8);
+ if (ch == '\n') {
+ *dst++ = '\r';
+ --size;
+ }
+ *dst++ = ch;
+ --size;
+ src = eon;
+ }
+ } else {
+ *dst++ = *src++;
+ --size;
+ }
+ }
+ *dst = '\0';
}
static struct tagFile {
- char *path;
- struct tagFile *next;
+ char *path;
+ struct tagFile *next;
} *file_list = NULL;
static void set_failure_reason(char *reason)
{
if (failure_reason)
- free(failure_reason);
+ free(failure_reason);
failure_reason = strdup(reason);
success = FALSE;
}
static char *get_failure_reason()
{
if (!failure_reason)
- return "Installation failed.";
+ return "Installation failed.";
return failure_reason;
}
static void add_to_filelist(char *path)
{
- struct tagFile *p;
- p = (struct tagFile *)malloc(sizeof(struct tagFile));
- p->path = strdup(path);
- p->next = file_list;
- file_list = p;
+ struct tagFile *p;
+ p = (struct tagFile *)malloc(sizeof(struct tagFile));
+ p->path = strdup(path);
+ p->next = file_list;
+ file_list = p;
}
static int do_compile_files(int (__cdecl * PyRun_SimpleString)(char *),
- int optimize)
+ int optimize)
{
- struct tagFile *p;
- int total, n;
- char Buffer[MAX_PATH + 64];
- int errors = 0;
-
- total = 0;
- p = file_list;
- while (p) {
- ++total;
- p = p->next;
- }
- SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0,
- MAKELPARAM(0, total));
- SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0);
-
- n = 0;
- p = file_list;
- while (p) {
- ++n;
- wsprintf(Buffer,
- "import py_compile; py_compile.compile (r'%s')",
- p->path);
- if (PyRun_SimpleString(Buffer)) {
- ++errors;
- }
- /* We send the notification even if the files could not
- * be created so that the uninstaller will remove them
- * in case they are created later.
- */
- wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c');
- notify(FILE_CREATED, Buffer);
-
- SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0);
- SetDlgItemText(hDialog, IDC_INFO, p->path);
- p = p->next;
- }
- return errors;
+ struct tagFile *p;
+ int total, n;
+ char Buffer[MAX_PATH + 64];
+ int errors = 0;
+
+ total = 0;
+ p = file_list;
+ while (p) {
+ ++total;
+ p = p->next;
+ }
+ SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETRANGE, 0,
+ MAKELPARAM(0, total));
+ SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, 0, 0);
+
+ n = 0;
+ p = file_list;
+ while (p) {
+ ++n;
+ wsprintf(Buffer,
+ "import py_compile; py_compile.compile (r'%s')",
+ p->path);
+ if (PyRun_SimpleString(Buffer)) {
+ ++errors;
+ }
+ /* We send the notification even if the files could not
+ * be created so that the uninstaller will remove them
+ * in case they are created later.
+ */
+ wsprintf(Buffer, "%s%c", p->path, optimize ? 'o' : 'c');
+ notify(FILE_CREATED, Buffer);
+
+ SendDlgItemMessage(hDialog, IDC_PROGRESS, PBM_SETPOS, n, 0);
+ SetDlgItemText(hDialog, IDC_INFO, p->path);
+ p = p->next;
+ }
+ return errors;
}
#define DECLPROC(dll, result, name, args)\
@@ -306,47 +306,47 @@ typedef void PyObject;
*/
static int compile_filelist(HINSTANCE hPython, BOOL optimize_flag)
{
- DECLPROC(hPython, void, Py_Initialize, (void));
- DECLPROC(hPython, void, Py_SetProgramName, (char *));
- DECLPROC(hPython, void, Py_Finalize, (void));
- DECLPROC(hPython, int, PyRun_SimpleString, (char *));
- DECLPROC(hPython, PyObject *, PySys_GetObject, (char *));
- DECLVAR(hPython, int, Py_OptimizeFlag);
+ DECLPROC(hPython, void, Py_Initialize, (void));
+ DECLPROC(hPython, void, Py_SetProgramName, (char *));
+ DECLPROC(hPython, void, Py_Finalize, (void));
+ DECLPROC(hPython, int, PyRun_SimpleString, (char *));
+ DECLPROC(hPython, PyObject *, PySys_GetObject, (char *));
+ DECLVAR(hPython, int, Py_OptimizeFlag);
- int errors = 0;
- struct tagFile *p = file_list;
+ int errors = 0;
+ struct tagFile *p = file_list;
- if (!p)
- return 0;
+ if (!p)
+ return 0;
- if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize)
- return -1;
+ if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize)
+ return -1;
- if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag)
- return -1;
+ if (!PyRun_SimpleString || !PySys_GetObject || !Py_OptimizeFlag)
+ return -1;
- *Py_OptimizeFlag = optimize_flag ? 1 : 0;
- Py_SetProgramName(modulename);
- Py_Initialize();
+ *Py_OptimizeFlag = optimize_flag ? 1 : 0;
+ Py_SetProgramName(modulename);
+ Py_Initialize();
- errors += do_compile_files(PyRun_SimpleString, optimize_flag);
- Py_Finalize();
+ errors += do_compile_files(PyRun_SimpleString, optimize_flag);
+ Py_Finalize();
- return errors;
+ return errors;
}
typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
struct PyMethodDef {
- char *ml_name;
- PyCFunction ml_meth;
- int ml_flags;
- char *ml_doc;
+ char *ml_name;
+ PyCFunction ml_meth;
+ int ml_flags;
+ char *ml_doc;
};
typedef struct PyMethodDef PyMethodDef;
// XXX - all of these are potentially fragile! We load and unload
-// the Python DLL multiple times - so storing functions pointers
+// the Python DLL multiple times - so storing functions pointers
// is dangerous (although things *look* OK at present)
// Better might be to roll prepare_script_environment() into
// LoadPythonDll(), and create a new UnloadPythonDLL() which also
@@ -363,249 +363,249 @@ PyObject *(*g_PyErr_Format)(PyObject *, char *, ...);
#define DEF_CSIDL(name) { name, #name }
struct {
- int nFolder;
- char *name;
+ int nFolder;
+ char *name;
} csidl_names[] = {
- /* Startup menu for all users.
- NT only */
- DEF_CSIDL(CSIDL_COMMON_STARTMENU),
- /* Startup menu. */
- DEF_CSIDL(CSIDL_STARTMENU),
+ /* Startup menu for all users.
+ NT only */
+ DEF_CSIDL(CSIDL_COMMON_STARTMENU),
+ /* Startup menu. */
+ DEF_CSIDL(CSIDL_STARTMENU),
/* DEF_CSIDL(CSIDL_COMMON_APPDATA), */
/* DEF_CSIDL(CSIDL_LOCAL_APPDATA), */
- /* Repository for application-specific data.
- Needs Internet Explorer 4.0 */
- DEF_CSIDL(CSIDL_APPDATA),
-
- /* The desktop for all users.
- NT only */
- DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY),
- /* The desktop. */
- DEF_CSIDL(CSIDL_DESKTOPDIRECTORY),
-
- /* Startup folder for all users.
- NT only */
- DEF_CSIDL(CSIDL_COMMON_STARTUP),
- /* Startup folder. */
- DEF_CSIDL(CSIDL_STARTUP),
-
- /* Programs item in the start menu for all users.
- NT only */
- DEF_CSIDL(CSIDL_COMMON_PROGRAMS),
- /* Program item in the user's start menu. */
- DEF_CSIDL(CSIDL_PROGRAMS),
+ /* Repository for application-specific data.
+ Needs Internet Explorer 4.0 */
+ DEF_CSIDL(CSIDL_APPDATA),
+
+ /* The desktop for all users.
+ NT only */
+ DEF_CSIDL(CSIDL_COMMON_DESKTOPDIRECTORY),
+ /* The desktop. */
+ DEF_CSIDL(CSIDL_DESKTOPDIRECTORY),
+
+ /* Startup folder for all users.
+ NT only */
+ DEF_CSIDL(CSIDL_COMMON_STARTUP),
+ /* Startup folder. */
+ DEF_CSIDL(CSIDL_STARTUP),
+
+ /* Programs item in the start menu for all users.
+ NT only */
+ DEF_CSIDL(CSIDL_COMMON_PROGRAMS),
+ /* Program item in the user's start menu. */
+ DEF_CSIDL(CSIDL_PROGRAMS),
/* DEF_CSIDL(CSIDL_PROGRAM_FILES_COMMON), */
/* DEF_CSIDL(CSIDL_PROGRAM_FILES), */
- /* Virtual folder containing fonts. */
- DEF_CSIDL(CSIDL_FONTS),
+ /* Virtual folder containing fonts. */
+ DEF_CSIDL(CSIDL_FONTS),
};
#define DIM(a) (sizeof(a) / sizeof((a)[0]))
static PyObject *FileCreated(PyObject *self, PyObject *args)
{
- char *path;
- if (!g_PyArg_ParseTuple(args, "s", &path))
- return NULL;
- notify(FILE_CREATED, path);
- return g_Py_BuildValue("");
+ char *path;
+ if (!g_PyArg_ParseTuple(args, "s", &path))
+ return NULL;
+ notify(FILE_CREATED, path);
+ return g_Py_BuildValue("");
}
static PyObject *DirectoryCreated(PyObject *self, PyObject *args)
{
- char *path;
- if (!g_PyArg_ParseTuple(args, "s", &path))
- return NULL;
- notify(DIR_CREATED, path);
- return g_Py_BuildValue("");
+ char *path;
+ if (!g_PyArg_ParseTuple(args, "s", &path))
+ return NULL;
+ notify(DIR_CREATED, path);
+ return g_Py_BuildValue("");
}
static PyObject *GetSpecialFolderPath(PyObject *self, PyObject *args)
{
- char *name;
- char lpszPath[MAX_PATH];
- int i;
- static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd,
- LPTSTR lpszPath,
- int nFolder,
- BOOL fCreate);
-
- if (!My_SHGetSpecialFolderPath) {
- HINSTANCE hLib = LoadLibrary("shell32.dll");
- if (!hLib) {
- g_PyErr_Format(g_PyExc_OSError,
- "function not available");
- return NULL;
- }
- My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR,
- int, BOOL))
- GetProcAddress(hLib,
- "SHGetSpecialFolderPathA");
- }
-
- if (!g_PyArg_ParseTuple(args, "s", &name))
- return NULL;
-
- if (!My_SHGetSpecialFolderPath) {
- g_PyErr_Format(g_PyExc_OSError, "function not available");
- return NULL;
- }
-
- for (i = 0; i < DIM(csidl_names); ++i) {
- if (0 == strcmpi(csidl_names[i].name, name)) {
- int nFolder;
- nFolder = csidl_names[i].nFolder;
- if (My_SHGetSpecialFolderPath(NULL, lpszPath,
- nFolder, 0))
- return g_Py_BuildValue("s", lpszPath);
- else {
- g_PyErr_Format(g_PyExc_OSError,
- "no such folder (%s)", name);
- return NULL;
- }
-
- }
- };
- g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name);
- return NULL;
+ char *name;
+ char lpszPath[MAX_PATH];
+ int i;
+ static HRESULT (WINAPI *My_SHGetSpecialFolderPath)(HWND hwnd,
+ LPTSTR lpszPath,
+ int nFolder,
+ BOOL fCreate);
+
+ if (!My_SHGetSpecialFolderPath) {
+ HINSTANCE hLib = LoadLibrary("shell32.dll");
+ if (!hLib) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "function not available");
+ return NULL;
+ }
+ My_SHGetSpecialFolderPath = (BOOL (WINAPI *)(HWND, LPTSTR,
+ int, BOOL))
+ GetProcAddress(hLib,
+ "SHGetSpecialFolderPathA");
+ }
+
+ if (!g_PyArg_ParseTuple(args, "s", &name))
+ return NULL;
+
+ if (!My_SHGetSpecialFolderPath) {
+ g_PyErr_Format(g_PyExc_OSError, "function not available");
+ return NULL;
+ }
+
+ for (i = 0; i < DIM(csidl_names); ++i) {
+ if (0 == strcmpi(csidl_names[i].name, name)) {
+ int nFolder;
+ nFolder = csidl_names[i].nFolder;
+ if (My_SHGetSpecialFolderPath(NULL, lpszPath,
+ nFolder, 0))
+ return g_Py_BuildValue("s", lpszPath);
+ else {
+ g_PyErr_Format(g_PyExc_OSError,
+ "no such folder (%s)", name);
+ return NULL;
+ }
+
+ }
+ };
+ g_PyErr_Format(g_PyExc_ValueError, "unknown CSIDL (%s)", name);
+ return NULL;
}
static PyObject *CreateShortcut(PyObject *self, PyObject *args)
{
- char *path; /* path and filename */
- char *description;
- char *filename;
-
- char *arguments = NULL;
- char *iconpath = NULL;
- int iconindex = 0;
- char *workdir = NULL;
-
- WCHAR wszFilename[MAX_PATH];
-
- IShellLink *ps1 = NULL;
- IPersistFile *pPf = NULL;
-
- HRESULT hr;
-
- hr = CoInitialize(NULL);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "CoInitialize failed, error 0x%x", hr);
- goto error;
- }
-
- if (!g_PyArg_ParseTuple(args, "sss|sssi",
- &path, &description, &filename,
- &arguments, &workdir, &iconpath, &iconindex))
- return NULL;
-
- hr = CoCreateInstance(&CLSID_ShellLink,
- NULL,
- CLSCTX_INPROC_SERVER,
- &IID_IShellLink,
- &ps1);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "CoCreateInstance failed, error 0x%x", hr);
- goto error;
- }
-
- hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile,
- (void **)&pPf);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "QueryInterface(IPersistFile) error 0x%x", hr);
- goto error;
- }
-
-
- hr = ps1->lpVtbl->SetPath(ps1, path);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "SetPath() failed, error 0x%x", hr);
- goto error;
- }
-
- hr = ps1->lpVtbl->SetDescription(ps1, description);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "SetDescription() failed, error 0x%x", hr);
- goto error;
- }
-
- if (arguments) {
- hr = ps1->lpVtbl->SetArguments(ps1, arguments);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "SetArguments() error 0x%x", hr);
- goto error;
- }
- }
-
- if (iconpath) {
- hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "SetIconLocation() error 0x%x", hr);
- goto error;
- }
- }
-
- if (workdir) {
- hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "SetWorkingDirectory() error 0x%x", hr);
- goto error;
- }
- }
-
- MultiByteToWideChar(CP_ACP, 0,
- filename, -1,
- wszFilename, MAX_PATH);
-
- hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE);
- if (FAILED(hr)) {
- g_PyErr_Format(g_PyExc_OSError,
- "Failed to create shortcut '%s' - error 0x%x", filename, hr);
- goto error;
- }
-
- pPf->lpVtbl->Release(pPf);
- ps1->lpVtbl->Release(ps1);
- CoUninitialize();
- return g_Py_BuildValue("");
-
+ char *path; /* path and filename */
+ char *description;
+ char *filename;
+
+ char *arguments = NULL;
+ char *iconpath = NULL;
+ int iconindex = 0;
+ char *workdir = NULL;
+
+ WCHAR wszFilename[MAX_PATH];
+
+ IShellLink *ps1 = NULL;
+ IPersistFile *pPf = NULL;
+
+ HRESULT hr;
+
+ hr = CoInitialize(NULL);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "CoInitialize failed, error 0x%x", hr);
+ goto error;
+ }
+
+ if (!g_PyArg_ParseTuple(args, "sss|sssi",
+ &path, &description, &filename,
+ &arguments, &workdir, &iconpath, &iconindex))
+ return NULL;
+
+ hr = CoCreateInstance(&CLSID_ShellLink,
+ NULL,
+ CLSCTX_INPROC_SERVER,
+ &IID_IShellLink,
+ &ps1);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "CoCreateInstance failed, error 0x%x", hr);
+ goto error;
+ }
+
+ hr = ps1->lpVtbl->QueryInterface(ps1, &IID_IPersistFile,
+ (void **)&pPf);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "QueryInterface(IPersistFile) error 0x%x", hr);
+ goto error;
+ }
+
+
+ hr = ps1->lpVtbl->SetPath(ps1, path);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "SetPath() failed, error 0x%x", hr);
+ goto error;
+ }
+
+ hr = ps1->lpVtbl->SetDescription(ps1, description);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "SetDescription() failed, error 0x%x", hr);
+ goto error;
+ }
+
+ if (arguments) {
+ hr = ps1->lpVtbl->SetArguments(ps1, arguments);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "SetArguments() error 0x%x", hr);
+ goto error;
+ }
+ }
+
+ if (iconpath) {
+ hr = ps1->lpVtbl->SetIconLocation(ps1, iconpath, iconindex);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "SetIconLocation() error 0x%x", hr);
+ goto error;
+ }
+ }
+
+ if (workdir) {
+ hr = ps1->lpVtbl->SetWorkingDirectory(ps1, workdir);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "SetWorkingDirectory() error 0x%x", hr);
+ goto error;
+ }
+ }
+
+ MultiByteToWideChar(CP_ACP, 0,
+ filename, -1,
+ wszFilename, MAX_PATH);
+
+ hr = pPf->lpVtbl->Save(pPf, wszFilename, TRUE);
+ if (FAILED(hr)) {
+ g_PyErr_Format(g_PyExc_OSError,
+ "Failed to create shortcut '%s' - error 0x%x", filename, hr);
+ goto error;
+ }
+
+ pPf->lpVtbl->Release(pPf);
+ ps1->lpVtbl->Release(ps1);
+ CoUninitialize();
+ return g_Py_BuildValue("");
+
error:
- if (pPf)
- pPf->lpVtbl->Release(pPf);
+ if (pPf)
+ pPf->lpVtbl->Release(pPf);
- if (ps1)
- ps1->lpVtbl->Release(ps1);
+ if (ps1)
+ ps1->lpVtbl->Release(ps1);
- CoUninitialize();
+ CoUninitialize();
- return NULL;
+ return NULL;
}
static PyObject *PyMessageBox(PyObject *self, PyObject *args)
{
- int rc;
- char *text, *caption;
- int flags;
- if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags))
- return NULL;
- rc = MessageBox(GetFocus(), text, caption, flags);
- return g_Py_BuildValue("i", rc);
+ int rc;
+ char *text, *caption;
+ int flags;
+ if (!g_PyArg_ParseTuple(args, "ssi", &text, &caption, &flags))
+ return NULL;
+ rc = MessageBox(GetFocus(), text, caption, flags);
+ return g_Py_BuildValue("i", rc);
}
static PyObject *GetRootHKey(PyObject *self)
{
- return g_PyLong_FromVoidPtr(hkey_root);
+ return g_PyLong_FromVoidPtr(hkey_root);
}
#define METH_VARARGS 0x0001
@@ -613,74 +613,74 @@ static PyObject *GetRootHKey(PyObject *self)
typedef PyObject *(*PyCFunction)(PyObject *, PyObject *);
PyMethodDef meth[] = {
- {"create_shortcut", CreateShortcut, METH_VARARGS, NULL},
- {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL},
- {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL},
- {"file_created", FileCreated, METH_VARARGS, NULL},
- {"directory_created", DirectoryCreated, METH_VARARGS, NULL},
- {"message_box", PyMessageBox, METH_VARARGS, NULL},
+ {"create_shortcut", CreateShortcut, METH_VARARGS, NULL},
+ {"get_special_folder_path", GetSpecialFolderPath, METH_VARARGS, NULL},
+ {"get_root_hkey", (PyCFunction)GetRootHKey, METH_NOARGS, NULL},
+ {"file_created", FileCreated, METH_VARARGS, NULL},
+ {"directory_created", DirectoryCreated, METH_VARARGS, NULL},
+ {"message_box", PyMessageBox, METH_VARARGS, NULL},
};
static HINSTANCE LoadPythonDll(char *fname)
{
- char fullpath[_MAX_PATH];
- LONG size = sizeof(fullpath);
- char subkey_name[80];
- char buffer[260 + 12];
- HINSTANCE h;
-
- /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */
- wsprintf(buffer, "PYTHONHOME=%s", python_dir);
- _putenv(buffer);
- h = LoadLibrary(fname);
- if (h)
- return h;
- wsprintf(subkey_name,
- "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath",
- py_major, py_minor);
- if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name,
- fullpath, &size) &&
- ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name,
- fullpath, &size))
- return NULL;
- strcat(fullpath, "\\");
- strcat(fullpath, fname);
- return LoadLibrary(fullpath);
+ char fullpath[_MAX_PATH];
+ LONG size = sizeof(fullpath);
+ char subkey_name[80];
+ char buffer[260 + 12];
+ HINSTANCE h;
+
+ /* make sure PYTHONHOME is set, to that sys.path is initialized correctly */
+ wsprintf(buffer, "PYTHONHOME=%s", python_dir);
+ _putenv(buffer);
+ h = LoadLibrary(fname);
+ if (h)
+ return h;
+ wsprintf(subkey_name,
+ "SOFTWARE\\Python\\PythonCore\\%d.%d\\InstallPath",
+ py_major, py_minor);
+ if (ERROR_SUCCESS != RegQueryValue(HKEY_CURRENT_USER, subkey_name,
+ fullpath, &size) &&
+ ERROR_SUCCESS != RegQueryValue(HKEY_LOCAL_MACHINE, subkey_name,
+ fullpath, &size))
+ return NULL;
+ strcat(fullpath, "\\");
+ strcat(fullpath, fname);
+ return LoadLibrary(fullpath);
}
static int prepare_script_environment(HINSTANCE hPython)
{
- PyObject *mod;
- DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *));
- DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *));
- DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *));
- DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *));
- DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
- DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
- DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
- DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *));
- if (!PyImport_ImportModule || !PyObject_GetAttrString ||
- !PyObject_SetAttrString || !PyCFunction_New)
- return 1;
- if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
- return 1;
-
- mod = PyImport_ImportModule("__builtin__");
- if (mod) {
- int i;
- g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError");
- g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError");
- for (i = 0; i < DIM(meth); ++i) {
- PyObject_SetAttrString(mod, meth[i].ml_name,
- PyCFunction_New(&meth[i], NULL));
- }
- }
- g_Py_BuildValue = Py_BuildValue;
- g_PyArg_ParseTuple = PyArg_ParseTuple;
- g_PyErr_Format = PyErr_Format;
- g_PyLong_FromVoidPtr = PyLong_FromVoidPtr;
-
- return 0;
+ PyObject *mod;
+ DECLPROC(hPython, PyObject *, PyImport_ImportModule, (char *));
+ DECLPROC(hPython, int, PyObject_SetAttrString, (PyObject *, char *, PyObject *));
+ DECLPROC(hPython, PyObject *, PyObject_GetAttrString, (PyObject *, char *));
+ DECLPROC(hPython, PyObject *, PyCFunction_New, (PyMethodDef *, PyObject *));
+ DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
+ DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
+ DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
+ DECLPROC(hPython, PyObject *, PyLong_FromVoidPtr, (void *));
+ if (!PyImport_ImportModule || !PyObject_GetAttrString ||
+ !PyObject_SetAttrString || !PyCFunction_New)
+ return 1;
+ if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
+ return 1;
+
+ mod = PyImport_ImportModule("__builtin__");
+ if (mod) {
+ int i;
+ g_PyExc_ValueError = PyObject_GetAttrString(mod, "ValueError");
+ g_PyExc_OSError = PyObject_GetAttrString(mod, "OSError");
+ for (i = 0; i < DIM(meth); ++i) {
+ PyObject_SetAttrString(mod, meth[i].ml_name,
+ PyCFunction_New(&meth[i], NULL));
+ }
+ }
+ g_Py_BuildValue = Py_BuildValue;
+ g_PyArg_ParseTuple = PyArg_ParseTuple;
+ g_PyErr_Format = PyErr_Format;
+ g_PyLong_FromVoidPtr = PyLong_FromVoidPtr;
+
+ return 0;
}
/*
@@ -696,473 +696,473 @@ static int prepare_script_environment(HINSTANCE hPython)
static int
do_run_installscript(HINSTANCE hPython, char *pathname, int argc, char **argv)
{
- int fh, result;
- DECLPROC(hPython, void, Py_Initialize, (void));
- DECLPROC(hPython, int, PySys_SetArgv, (int, char **));
- DECLPROC(hPython, int, PyRun_SimpleString, (char *));
- DECLPROC(hPython, void, Py_Finalize, (void));
- DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
- DECLPROC(hPython, PyObject *, PyCFunction_New,
- (PyMethodDef *, PyObject *));
- DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
- DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
-
- if (!Py_Initialize || !PySys_SetArgv
- || !PyRun_SimpleString || !Py_Finalize)
- return 1;
-
- if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
- return 1;
-
- if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format)
- return 1;
-
- if (pathname == NULL || pathname[0] == '\0')
- return 2;
-
- fh = open(pathname, _O_RDONLY);
- if (-1 == fh) {
- fprintf(stderr, "Could not open postinstall-script %s\n",
- pathname);
- return 3;
- }
-
- SetDlgItemText(hDialog, IDC_INFO, "Running Script...");
-
- Py_Initialize();
-
- prepare_script_environment(hPython);
- PySys_SetArgv(argc, argv);
- result = 3;
- {
- struct _stat statbuf;
- if(0 == _fstat(fh, &statbuf)) {
- char *script = alloca(statbuf.st_size + 5);
- int n = read(fh, script, statbuf.st_size);
- if (n > 0) {
- script[n] = '\n';
- script[n+1] = 0;
- result = PyRun_SimpleString(script);
- }
- }
- }
- Py_Finalize();
-
- close(fh);
- return result;
+ int fh, result;
+ DECLPROC(hPython, void, Py_Initialize, (void));
+ DECLPROC(hPython, int, PySys_SetArgv, (int, char **));
+ DECLPROC(hPython, int, PyRun_SimpleString, (char *));
+ DECLPROC(hPython, void, Py_Finalize, (void));
+ DECLPROC(hPython, PyObject *, Py_BuildValue, (char *, ...));
+ DECLPROC(hPython, PyObject *, PyCFunction_New,
+ (PyMethodDef *, PyObject *));
+ DECLPROC(hPython, int, PyArg_ParseTuple, (PyObject *, char *, ...));
+ DECLPROC(hPython, PyObject *, PyErr_Format, (PyObject *, char *));
+
+ if (!Py_Initialize || !PySys_SetArgv
+ || !PyRun_SimpleString || !Py_Finalize)
+ return 1;
+
+ if (!Py_BuildValue || !PyArg_ParseTuple || !PyErr_Format)
+ return 1;
+
+ if (!PyCFunction_New || !PyArg_ParseTuple || !PyErr_Format)
+ return 1;
+
+ if (pathname == NULL || pathname[0] == '\0')
+ return 2;
+
+ fh = open(pathname, _O_RDONLY);
+ if (-1 == fh) {
+ fprintf(stderr, "Could not open postinstall-script %s\n",
+ pathname);
+ return 3;
+ }
+
+ SetDlgItemText(hDialog, IDC_INFO, "Running Script...");
+
+ Py_Initialize();
+
+ prepare_script_environment(hPython);
+ PySys_SetArgv(argc, argv);
+ result = 3;
+ {
+ struct _stat statbuf;
+ if(0 == _fstat(fh, &statbuf)) {
+ char *script = alloca(statbuf.st_size + 5);
+ int n = read(fh, script, statbuf.st_size);
+ if (n > 0) {
+ script[n] = '\n';
+ script[n+1] = 0;
+ result = PyRun_SimpleString(script);
+ }
+ }
+ }
+ Py_Finalize();
+
+ close(fh);
+ return result;
}
static int
run_installscript(char *pathname, int argc, char **argv, char **pOutput)
{
- HINSTANCE hPython;
- int result = 1;
- int out_buf_size;
- HANDLE redirected, old_stderr, old_stdout;
- char *tempname;
-
- *pOutput = NULL;
-
- tempname = tempnam(NULL, NULL);
- // We use a static CRT while the Python version we load uses
- // the CRT from one of various possibile DLLs. As a result we
- // need to redirect the standard handles using the API rather
- // than the CRT.
- redirected = CreateFile(
- tempname,
- GENERIC_WRITE | GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- CREATE_ALWAYS,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
- NULL);
- old_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
- old_stderr = GetStdHandle(STD_ERROR_HANDLE);
- SetStdHandle(STD_OUTPUT_HANDLE, redirected);
- SetStdHandle(STD_ERROR_HANDLE, redirected);
-
- hPython = LoadPythonDll(pythondll);
- if (hPython) {
- result = do_run_installscript(hPython, pathname, argc, argv);
- FreeLibrary(hPython);
- } else {
- fprintf(stderr, "*** Could not load Python ***");
- }
- SetStdHandle(STD_OUTPUT_HANDLE, old_stdout);
- SetStdHandle(STD_ERROR_HANDLE, old_stderr);
- out_buf_size = min(GetFileSize(redirected, NULL), 4096);
- *pOutput = malloc(out_buf_size+1);
- if (*pOutput) {
- DWORD nread = 0;
- SetFilePointer(redirected, 0, 0, FILE_BEGIN);
- ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL);
- (*pOutput)[nread] = '\0';
- }
- CloseHandle(redirected);
- DeleteFile(tempname);
- return result;
+ HINSTANCE hPython;
+ int result = 1;
+ int out_buf_size;
+ HANDLE redirected, old_stderr, old_stdout;
+ char *tempname;
+
+ *pOutput = NULL;
+
+ tempname = tempnam(NULL, NULL);
+ // We use a static CRT while the Python version we load uses
+ // the CRT from one of various possibile DLLs. As a result we
+ // need to redirect the standard handles using the API rather
+ // than the CRT.
+ redirected = CreateFile(
+ tempname,
+ GENERIC_WRITE | GENERIC_READ,
+ FILE_SHARE_READ,
+ NULL,
+ CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
+ NULL);
+ old_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
+ old_stderr = GetStdHandle(STD_ERROR_HANDLE);
+ SetStdHandle(STD_OUTPUT_HANDLE, redirected);
+ SetStdHandle(STD_ERROR_HANDLE, redirected);
+
+ hPython = LoadPythonDll(pythondll);
+ if (hPython) {
+ result = do_run_installscript(hPython, pathname, argc, argv);
+ FreeLibrary(hPython);
+ } else {
+ fprintf(stderr, "*** Could not load Python ***");
+ }
+ SetStdHandle(STD_OUTPUT_HANDLE, old_stdout);
+ SetStdHandle(STD_ERROR_HANDLE, old_stderr);
+ out_buf_size = min(GetFileSize(redirected, NULL), 4096);
+ *pOutput = malloc(out_buf_size+1);
+ if (*pOutput) {
+ DWORD nread = 0;
+ SetFilePointer(redirected, 0, 0, FILE_BEGIN);
+ ReadFile(redirected, *pOutput, out_buf_size, &nread, NULL);
+ (*pOutput)[nread] = '\0';
+ }
+ CloseHandle(redirected);
+ DeleteFile(tempname);
+ return result;
}
static int do_run_simple_script(HINSTANCE hPython, char *script)
{
- int rc;
- DECLPROC(hPython, void, Py_Initialize, (void));
- DECLPROC(hPython, void, Py_SetProgramName, (char *));
- DECLPROC(hPython, void, Py_Finalize, (void));
- DECLPROC(hPython, int, PyRun_SimpleString, (char *));
- DECLPROC(hPython, void, PyErr_Print, (void));
-
- if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize ||
- !PyRun_SimpleString || !PyErr_Print)
- return -1;
-
- Py_SetProgramName(modulename);
- Py_Initialize();
- prepare_script_environment(hPython);
- rc = PyRun_SimpleString(script);
- if (rc)
- PyErr_Print();
- Py_Finalize();
- return rc;
+ int rc;
+ DECLPROC(hPython, void, Py_Initialize, (void));
+ DECLPROC(hPython, void, Py_SetProgramName, (char *));
+ DECLPROC(hPython, void, Py_Finalize, (void));
+ DECLPROC(hPython, int, PyRun_SimpleString, (char *));
+ DECLPROC(hPython, void, PyErr_Print, (void));
+
+ if (!Py_Initialize || !Py_SetProgramName || !Py_Finalize ||
+ !PyRun_SimpleString || !PyErr_Print)
+ return -1;
+
+ Py_SetProgramName(modulename);
+ Py_Initialize();
+ prepare_script_environment(hPython);
+ rc = PyRun_SimpleString(script);
+ if (rc)
+ PyErr_Print();
+ Py_Finalize();
+ return rc;
}
static int run_simple_script(char *script)
{
- int rc;
- HINSTANCE hPython;
- char *tempname = tempnam(NULL, NULL);
- // Redirect output using win32 API - see comments above...
- HANDLE redirected = CreateFile(
- tempname,
- GENERIC_WRITE | GENERIC_READ,
- FILE_SHARE_READ,
- NULL,
- CREATE_ALWAYS,
- FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
- NULL);
- HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
- HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE);
- SetStdHandle(STD_OUTPUT_HANDLE, redirected);
- SetStdHandle(STD_ERROR_HANDLE, redirected);
-
- hPython = LoadPythonDll(pythondll);
- if (!hPython) {
- char reason[128];
- wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError());
- set_failure_reason(reason);
- return -1;
- }
- rc = do_run_simple_script(hPython, script);
- FreeLibrary(hPython);
- SetStdHandle(STD_OUTPUT_HANDLE, old_stdout);
- SetStdHandle(STD_ERROR_HANDLE, old_stderr);
- /* We only care about the output when we fail. If the script works
- OK, then we discard it
- */
- if (rc) {
- int err_buf_size;
- char *err_buf;
- const char *prefix = "Running the pre-installation script failed\r\n";
- int prefix_len = strlen(prefix);
- err_buf_size = GetFileSize(redirected, NULL);
- if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway...
- err_buf_size = 4096;
- err_buf = malloc(prefix_len + err_buf_size + 1);
- if (err_buf) {
- DWORD n = 0;
- strcpy(err_buf, prefix);
- SetFilePointer(redirected, 0, 0, FILE_BEGIN);
- ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL);
- err_buf[prefix_len+n] = '\0';
- set_failure_reason(err_buf);
- free(err_buf);
- } else {
- set_failure_reason("Out of memory!");
- }
- }
- CloseHandle(redirected);
- DeleteFile(tempname);
- return rc;
+ int rc;
+ HINSTANCE hPython;
+ char *tempname = tempnam(NULL, NULL);
+ // Redirect output using win32 API - see comments above...
+ HANDLE redirected = CreateFile(
+ tempname,
+ GENERIC_WRITE | GENERIC_READ,
+ FILE_SHARE_READ,
+ NULL,
+ CREATE_ALWAYS,
+ FILE_ATTRIBUTE_NORMAL | FILE_FLAG_WRITE_THROUGH,
+ NULL);
+ HANDLE old_stdout = GetStdHandle(STD_OUTPUT_HANDLE);
+ HANDLE old_stderr = GetStdHandle(STD_ERROR_HANDLE);
+ SetStdHandle(STD_OUTPUT_HANDLE, redirected);
+ SetStdHandle(STD_ERROR_HANDLE, redirected);
+
+ hPython = LoadPythonDll(pythondll);
+ if (!hPython) {
+ char reason[128];
+ wsprintf(reason, "Can't load Python for pre-install script (%d)", GetLastError());
+ set_failure_reason(reason);
+ return -1;
+ }
+ rc = do_run_simple_script(hPython, script);
+ FreeLibrary(hPython);
+ SetStdHandle(STD_OUTPUT_HANDLE, old_stdout);
+ SetStdHandle(STD_ERROR_HANDLE, old_stderr);
+ /* We only care about the output when we fail. If the script works
+ OK, then we discard it
+ */
+ if (rc) {
+ int err_buf_size;
+ char *err_buf;
+ const char *prefix = "Running the pre-installation script failed\r\n";
+ int prefix_len = strlen(prefix);
+ err_buf_size = GetFileSize(redirected, NULL);
+ if (err_buf_size==INVALID_FILE_SIZE) // an error - let's try anyway...
+ err_buf_size = 4096;
+ err_buf = malloc(prefix_len + err_buf_size + 1);
+ if (err_buf) {
+ DWORD n = 0;
+ strcpy(err_buf, prefix);
+ SetFilePointer(redirected, 0, 0, FILE_BEGIN);
+ ReadFile(redirected, err_buf+prefix_len, err_buf_size, &n, NULL);
+ err_buf[prefix_len+n] = '\0';
+ set_failure_reason(err_buf);
+ free(err_buf);
+ } else {
+ set_failure_reason("Out of memory!");
+ }
+ }
+ CloseHandle(redirected);
+ DeleteFile(tempname);
+ return rc;
}
static BOOL SystemError(int error, char *msg)
{
- char Buffer[1024];
- int n;
-
- if (error) {
- LPVOID lpMsgBuf;
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- error,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
- (LPSTR)&lpMsgBuf,
- 0,
- NULL
- );
- strncpy(Buffer, lpMsgBuf, sizeof(Buffer));
- LocalFree(lpMsgBuf);
- } else
- Buffer[0] = '\0';
- n = lstrlen(Buffer);
- _snprintf(Buffer+n, sizeof(Buffer)-n, msg);
- MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP);
- return FALSE;
+ char Buffer[1024];
+ int n;
+
+ if (error) {
+ LPVOID lpMsgBuf;
+ FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM,
+ NULL,
+ error,
+ MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+ (LPSTR)&lpMsgBuf,
+ 0,
+ NULL
+ );
+ strncpy(Buffer, lpMsgBuf, sizeof(Buffer));
+ LocalFree(lpMsgBuf);
+ } else
+ Buffer[0] = '\0';
+ n = lstrlen(Buffer);
+ _snprintf(Buffer+n, sizeof(Buffer)-n, msg);
+ MessageBox(hwndMain, Buffer, "Runtime Error", MB_OK | MB_ICONSTOP);
+ return FALSE;
}
static BOOL notify (int code, char *fmt, ...)
{
- char Buffer[1024];
- va_list marker;
- BOOL result = TRUE;
- int a, b;
- char *cp;
+ char Buffer[1024];
+ va_list marker;
+ BOOL result = TRUE;
+ int a, b;
+ char *cp;
- va_start(marker, fmt);
- _vsnprintf(Buffer, sizeof(Buffer), fmt, marker);
+ va_start(marker, fmt);
+ _vsnprintf(Buffer, sizeof(Buffer), fmt, marker);
- switch (code) {
+ switch (code) {
/* Questions */
- case CAN_OVERWRITE:
- break;
+ case CAN_OVERWRITE:
+ break;
/* Information notification */
- case DIR_CREATED:
- if (logfile)
- fprintf(logfile, "100 Made Dir: %s\n", fmt);
- break;
-
- case FILE_CREATED:
- if (logfile)
- fprintf(logfile, "200 File Copy: %s\n", fmt);
- goto add_to_filelist_label;
- break;
-
- case FILE_OVERWRITTEN:
- if (logfile)
- fprintf(logfile, "200 File Overwrite: %s\n", fmt);
- add_to_filelist_label:
- if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py")))
- add_to_filelist(fmt);
- break;
+ case DIR_CREATED:
+ if (logfile)
+ fprintf(logfile, "100 Made Dir: %s\n", fmt);
+ break;
+
+ case FILE_CREATED:
+ if (logfile)
+ fprintf(logfile, "200 File Copy: %s\n", fmt);
+ goto add_to_filelist_label;
+ break;
+
+ case FILE_OVERWRITTEN:
+ if (logfile)
+ fprintf(logfile, "200 File Overwrite: %s\n", fmt);
+ add_to_filelist_label:
+ if ((cp = strrchr(fmt, '.')) && (0 == strcmp (cp, ".py")))
+ add_to_filelist(fmt);
+ break;
/* Error Messages */
- case ZLIB_ERROR:
- MessageBox(GetFocus(), Buffer, "Error",
- MB_OK | MB_ICONWARNING);
- break;
-
- case SYSTEM_ERROR:
- SystemError(GetLastError(), Buffer);
- break;
-
- case NUM_FILES:
- a = va_arg(marker, int);
- b = va_arg(marker, int);
- SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a));
- SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt);
- }
- va_end(marker);
-
- return result;
+ case ZLIB_ERROR:
+ MessageBox(GetFocus(), Buffer, "Error",
+ MB_OK | MB_ICONWARNING);
+ break;
+
+ case SYSTEM_ERROR:
+ SystemError(GetLastError(), Buffer);
+ break;
+
+ case NUM_FILES:
+ a = va_arg(marker, int);
+ b = va_arg(marker, int);
+ SendMessage(hDialog, WM_NUMFILES, 0, MAKELPARAM(0, a));
+ SendMessage(hDialog, WM_NEXTFILE, b,(LPARAM)fmt);
+ }
+ va_end(marker);
+
+ return result;
}
static char *MapExistingFile(char *pathname, DWORD *psize)
{
- HANDLE hFile, hFileMapping;
- DWORD nSizeLow, nSizeHigh;
- char *data;
-
- hFile = CreateFile(pathname,
- GENERIC_READ, FILE_SHARE_READ, NULL,
- OPEN_EXISTING,
- FILE_ATTRIBUTE_NORMAL, NULL);
- if (hFile == INVALID_HANDLE_VALUE)
- return NULL;
- nSizeLow = GetFileSize(hFile, &nSizeHigh);
- hFileMapping = CreateFileMapping(hFile,
- NULL, PAGE_READONLY, 0, 0, NULL);
- CloseHandle(hFile);
-
- if (hFileMapping == INVALID_HANDLE_VALUE)
- return NULL;
-
- data = MapViewOfFile(hFileMapping,
- FILE_MAP_READ, 0, 0, 0);
-
- CloseHandle(hFileMapping);
- *psize = nSizeLow;
- return data;
+ HANDLE hFile, hFileMapping;
+ DWORD nSizeLow, nSizeHigh;
+ char *data;
+
+ hFile = CreateFile(pathname,
+ GENERIC_READ, FILE_SHARE_READ, NULL,
+ OPEN_EXISTING,
+ FILE_ATTRIBUTE_NORMAL, NULL);
+ if (hFile == INVALID_HANDLE_VALUE)
+ return NULL;
+ nSizeLow = GetFileSize(hFile, &nSizeHigh);
+ hFileMapping = CreateFileMapping(hFile,
+ NULL, PAGE_READONLY, 0, 0, NULL);
+ CloseHandle(hFile);
+
+ if (hFileMapping == INVALID_HANDLE_VALUE)
+ return NULL;
+
+ data = MapViewOfFile(hFileMapping,
+ FILE_MAP_READ, 0, 0, 0);
+
+ CloseHandle(hFileMapping);
+ *psize = nSizeLow;
+ return data;
}
static void create_bitmap(HWND hwnd)
{
- BITMAPFILEHEADER *bfh;
- BITMAPINFO *bi;
- HDC hdc;
+ BITMAPFILEHEADER *bfh;
+ BITMAPINFO *bi;
+ HDC hdc;
- if (!bitmap_bytes)
- return;
+ if (!bitmap_bytes)
+ return;
- if (hBitmap)
- return;
+ if (hBitmap)
+ return;
- hdc = GetDC(hwnd);
+ hdc = GetDC(hwnd);
- bfh = (BITMAPFILEHEADER *)bitmap_bytes;
- bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER));
+ bfh = (BITMAPFILEHEADER *)bitmap_bytes;
+ bi = (BITMAPINFO *)(bitmap_bytes + sizeof(BITMAPFILEHEADER));
- hBitmap = CreateDIBitmap(hdc,
- &bi->bmiHeader,
- CBM_INIT,
- bitmap_bytes + bfh->bfOffBits,
- bi,
- DIB_RGB_COLORS);
- ReleaseDC(hwnd, hdc);
+ hBitmap = CreateDIBitmap(hdc,
+ &bi->bmiHeader,
+ CBM_INIT,
+ bitmap_bytes + bfh->bfOffBits,
+ bi,
+ DIB_RGB_COLORS);
+ ReleaseDC(hwnd, hdc);
}
/* Extract everything we need to begin the installation. Currently this
is the INI filename with install data, and the raw pre-install script
*/
static BOOL ExtractInstallData(char *data, DWORD size, int *pexe_size,
- char **out_ini_file, char **out_preinstall_script)
+ char **out_ini_file, char **out_preinstall_script)
{
- /* read the end of central directory record */
- struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof
- (struct eof_cdir)];
-
- int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir -
- pe->ofsCDir;
-
- int ofs = arc_start - sizeof (struct meta_data_hdr);
-
- /* read meta_data info */
- struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs];
- char *src, *dst;
- char *ini_file;
- char tempdir[MAX_PATH];
-
- /* ensure that if we fail, we don't have garbage out pointers */
- *out_ini_file = *out_preinstall_script = NULL;
-
- if (pe->tag != 0x06054b50) {
- return FALSE;
- }
-
- if (pmd->tag != 0x1234567B) {
- return SystemError(0,
- "Invalid cfgdata magic number (see bdist_wininst.py)");
- }
- if (ofs < 0) {
- return FALSE;
- }
-
- if (pmd->bitmap_size) {
- /* Store pointer to bitmap bytes */
- bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size;
- }
-
- *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size;
-
- src = ((char *)pmd) - pmd->uncomp_size;
- ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */
- if (!ini_file)
- return FALSE;
- if (!GetTempPath(sizeof(tempdir), tempdir)
- || !GetTempFileName(tempdir, "~du", 0, ini_file)) {
- SystemError(GetLastError(),
- "Could not create temporary file");
- return FALSE;
- }
-
- dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size,
- 0, 0, NULL/*notify*/);
- if (!dst)
- return FALSE;
- /* Up to the first \0 is the INI file data. */
- strncpy(dst, src, pmd->uncomp_size);
- src += strlen(dst) + 1;
- /* Up to next \0 is the pre-install script */
- *out_preinstall_script = strdup(src);
- *out_ini_file = ini_file;
- UnmapViewOfFile(dst);
- return TRUE;
+ /* read the end of central directory record */
+ struct eof_cdir *pe = (struct eof_cdir *)&data[size - sizeof
+ (struct eof_cdir)];
+
+ int arc_start = size - sizeof (struct eof_cdir) - pe->nBytesCDir -
+ pe->ofsCDir;
+
+ int ofs = arc_start - sizeof (struct meta_data_hdr);
+
+ /* read meta_data info */
+ struct meta_data_hdr *pmd = (struct meta_data_hdr *)&data[ofs];
+ char *src, *dst;
+ char *ini_file;
+ char tempdir[MAX_PATH];
+
+ /* ensure that if we fail, we don't have garbage out pointers */
+ *out_ini_file = *out_preinstall_script = NULL;
+
+ if (pe->tag != 0x06054b50) {
+ return FALSE;
+ }
+
+ if (pmd->tag != 0x1234567B) {
+ return SystemError(0,
+ "Invalid cfgdata magic number (see bdist_wininst.py)");
+ }
+ if (ofs < 0) {
+ return FALSE;
+ }
+
+ if (pmd->bitmap_size) {
+ /* Store pointer to bitmap bytes */
+ bitmap_bytes = (char *)pmd - pmd->uncomp_size - pmd->bitmap_size;
+ }
+
+ *pexe_size = ofs - pmd->uncomp_size - pmd->bitmap_size;
+
+ src = ((char *)pmd) - pmd->uncomp_size;
+ ini_file = malloc(MAX_PATH); /* will be returned, so do not free it */
+ if (!ini_file)
+ return FALSE;
+ if (!GetTempPath(sizeof(tempdir), tempdir)
+ || !GetTempFileName(tempdir, "~du", 0, ini_file)) {
+ SystemError(GetLastError(),
+ "Could not create temporary file");
+ return FALSE;
+ }
+
+ dst = map_new_file(CREATE_ALWAYS, ini_file, NULL, pmd->uncomp_size,
+ 0, 0, NULL/*notify*/);
+ if (!dst)
+ return FALSE;
+ /* Up to the first \0 is the INI file data. */
+ strncpy(dst, src, pmd->uncomp_size);
+ src += strlen(dst) + 1;
+ /* Up to next \0 is the pre-install script */
+ *out_preinstall_script = strdup(src);
+ *out_ini_file = ini_file;
+ UnmapViewOfFile(dst);
+ return TRUE;
}
static void PumpMessages(void)
{
- MSG msg;
- while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
- TranslateMessage(&msg);
- DispatchMessage(&msg);
- }
+ MSG msg;
+ while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
+ TranslateMessage(&msg);
+ DispatchMessage(&msg);
+ }
}
LRESULT CALLBACK
WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- HDC hdc;
- HFONT hFont;
- int h;
- PAINTSTRUCT ps;
- switch (msg) {
- case WM_PAINT:
- hdc = BeginPaint(hwnd, &ps);
- h = GetSystemMetrics(SM_CYSCREEN) / 10;
- hFont = CreateFont(h, 0, 0, 0, 700, TRUE,
- 0, 0, 0, 0, 0, 0, 0, "Times Roman");
- hFont = SelectObject(hdc, hFont);
- SetBkMode(hdc, TRANSPARENT);
- TextOut(hdc, 15, 15, title, strlen(title));
- SetTextColor(hdc, RGB(255, 255, 255));
- TextOut(hdc, 10, 10, title, strlen(title));
- DeleteObject(SelectObject(hdc, hFont));
- EndPaint(hwnd, &ps);
- return 0;
- }
- return DefWindowProc(hwnd, msg, wParam, lParam);
+ HDC hdc;
+ HFONT hFont;
+ int h;
+ PAINTSTRUCT ps;
+ switch (msg) {
+ case WM_PAINT:
+ hdc = BeginPaint(hwnd, &ps);
+ h = GetSystemMetrics(SM_CYSCREEN) / 10;
+ hFont = CreateFont(h, 0, 0, 0, 700, TRUE,
+ 0, 0, 0, 0, 0, 0, 0, "Times Roman");
+ hFont = SelectObject(hdc, hFont);
+ SetBkMode(hdc, TRANSPARENT);
+ TextOut(hdc, 15, 15, title, strlen(title));
+ SetTextColor(hdc, RGB(255, 255, 255));
+ TextOut(hdc, 10, 10, title, strlen(title));
+ DeleteObject(SelectObject(hdc, hFont));
+ EndPaint(hwnd, &ps);
+ return 0;
+ }
+ return DefWindowProc(hwnd, msg, wParam, lParam);
}
static HWND CreateBackground(char *title)
{
- WNDCLASS wc;
- HWND hwnd;
- char buffer[4096];
-
- wc.style = CS_VREDRAW | CS_HREDRAW;
- wc.lpfnWndProc = WindowProc;
- wc.cbWndExtra = 0;
- wc.cbClsExtra = 0;
- wc.hInstance = GetModuleHandle(NULL);
- wc.hIcon = NULL;
- wc.hCursor = LoadCursor(NULL, IDC_ARROW);
- wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128));
- wc.lpszMenuName = NULL;
- wc.lpszClassName = "SetupWindowClass";
-
- if (!RegisterClass(&wc))
- MessageBox(hwndMain,
- "Could not register window class",
- "Setup.exe", MB_OK);
-
- wsprintf(buffer, "Setup %s", title);
- hwnd = CreateWindow("SetupWindowClass",
- buffer,
- 0,
- 0, 0,
- GetSystemMetrics(SM_CXFULLSCREEN),
- GetSystemMetrics(SM_CYFULLSCREEN),
- NULL,
- NULL,
- GetModuleHandle(NULL),
- NULL);
- ShowWindow(hwnd, SW_SHOWMAXIMIZED);
- UpdateWindow(hwnd);
- return hwnd;
+ WNDCLASS wc;
+ HWND hwnd;
+ char buffer[4096];
+
+ wc.style = CS_VREDRAW | CS_HREDRAW;
+ wc.lpfnWndProc = WindowProc;
+ wc.cbWndExtra = 0;
+ wc.cbClsExtra = 0;
+ wc.hInstance = GetModuleHandle(NULL);
+ wc.hIcon = NULL;
+ wc.hCursor = LoadCursor(NULL, IDC_ARROW);
+ wc.hbrBackground = CreateSolidBrush(RGB(0, 0, 128));
+ wc.lpszMenuName = NULL;
+ wc.lpszClassName = "SetupWindowClass";
+
+ if (!RegisterClass(&wc))
+ MessageBox(hwndMain,
+ "Could not register window class",
+ "Setup.exe", MB_OK);
+
+ wsprintf(buffer, "Setup %s", title);
+ hwnd = CreateWindow("SetupWindowClass",
+ buffer,
+ 0,
+ 0, 0,
+ GetSystemMetrics(SM_CXFULLSCREEN),
+ GetSystemMetrics(SM_CYFULLSCREEN),
+ NULL,
+ NULL,
+ GetModuleHandle(NULL),
+ NULL);
+ ShowWindow(hwnd, SW_SHOWMAXIMIZED);
+ UpdateWindow(hwnd);
+ return hwnd;
}
/*
@@ -1170,16 +1170,16 @@ static HWND CreateBackground(char *title)
*/
static void CenterWindow(HWND hwnd)
{
- RECT rc;
- int w, h;
-
- GetWindowRect(hwnd, &rc);
- w = GetSystemMetrics(SM_CXSCREEN);
- h = GetSystemMetrics(SM_CYSCREEN);
- MoveWindow(hwnd,
- (w - (rc.right-rc.left))/2,
- (h - (rc.bottom-rc.top))/2,
- rc.right-rc.left, rc.bottom-rc.top, FALSE);
+ RECT rc;
+ int w, h;
+
+ GetWindowRect(hwnd, &rc);
+ w = GetSystemMetrics(SM_CXSCREEN);
+ h = GetSystemMetrics(SM_CYSCREEN);
+ MoveWindow(hwnd,
+ (w - (rc.right-rc.left))/2,
+ (h - (rc.bottom-rc.top))/2,
+ rc.right-rc.left, rc.bottom-rc.top, FALSE);
}
#include <prsht.h>
@@ -1187,45 +1187,45 @@ static void CenterWindow(HWND hwnd)
BOOL CALLBACK
IntroDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- LPNMHDR lpnm;
- char Buffer[4096];
-
- switch (msg) {
- case WM_INITDIALOG:
- create_bitmap(hwnd);
- if(hBitmap)
- SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
- IMAGE_BITMAP, (LPARAM)hBitmap);
- CenterWindow(GetParent(hwnd));
- wsprintf(Buffer,
- "This Wizard will install %s on your computer. "
- "Click Next to continue "
- "or Cancel to exit the Setup Wizard.",
- meta_name);
- SetDlgItemText(hwnd, IDC_TITLE, Buffer);
- SetDlgItemText(hwnd, IDC_INTRO_TEXT, info);
- SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info);
- return FALSE;
-
- case WM_NOTIFY:
- lpnm = (LPNMHDR) lParam;
-
- switch (lpnm->code) {
- case PSN_SETACTIVE:
- PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT);
- break;
-
- case PSN_WIZNEXT:
- break;
-
- case PSN_RESET:
- break;
-
- default:
- break;
- }
- }
- return FALSE;
+ LPNMHDR lpnm;
+ char Buffer[4096];
+
+ switch (msg) {
+ case WM_INITDIALOG:
+ create_bitmap(hwnd);
+ if(hBitmap)
+ SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
+ IMAGE_BITMAP, (LPARAM)hBitmap);
+ CenterWindow(GetParent(hwnd));
+ wsprintf(Buffer,
+ "This Wizard will install %s on your computer. "
+ "Click Next to continue "
+ "or Cancel to exit the Setup Wizard.",
+ meta_name);
+ SetDlgItemText(hwnd, IDC_TITLE, Buffer);
+ SetDlgItemText(hwnd, IDC_INTRO_TEXT, info);
+ SetDlgItemText(hwnd, IDC_BUILD_INFO, build_info);
+ return FALSE;
+
+ case WM_NOTIFY:
+ lpnm = (LPNMHDR) lParam;
+
+ switch (lpnm->code) {
+ case PSN_SETACTIVE:
+ PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_NEXT);
+ break;
+
+ case PSN_WIZNEXT:
+ break;
+
+ case PSN_RESET:
+ break;
+
+ default:
+ break;
+ }
+ }
+ return FALSE;
}
#ifdef USE_OTHER_PYTHON_VERSIONS
@@ -1237,133 +1237,133 @@ int bound_image_major;
int bound_image_minor;
static BOOL __stdcall StatusRoutine(IMAGEHLP_STATUS_REASON reason,
- PSTR ImageName,
- PSTR DllName,
- ULONG Va,
- ULONG Parameter)
+ PSTR ImageName,
+ PSTR DllName,
+ ULONG Va,
+ ULONG Parameter)
{
- char fname[_MAX_PATH];
- int int_version;
-
- switch(reason) {
- case BindOutOfMemory:
- case BindRvaToVaFailed:
- case BindNoRoomInImage:
- case BindImportProcedureFailed:
- break;
-
- case BindImportProcedure:
- case BindForwarder:
- case BindForwarderNOT:
- case BindImageModified:
- case BindExpandFileHeaders:
- case BindImageComplete:
- case BindSymbolsNotUpdated:
- case BindMismatchedSymbols:
- case BindImportModuleFailed:
- break;
-
- case BindImportModule:
- if (1 == sscanf(DllName, "python%d", &int_version)) {
- SearchPath(NULL, DllName, NULL, sizeof(fname),
- fname, NULL);
- strcpy(bound_image_dll, fname);
- bound_image_major = int_version / 10;
- bound_image_minor = int_version % 10;
- OutputDebugString("BOUND ");
- OutputDebugString(fname);
- OutputDebugString("\n");
- }
- break;
- }
- return TRUE;
+ char fname[_MAX_PATH];
+ int int_version;
+
+ switch(reason) {
+ case BindOutOfMemory:
+ case BindRvaToVaFailed:
+ case BindNoRoomInImage:
+ case BindImportProcedureFailed:
+ break;
+
+ case BindImportProcedure:
+ case BindForwarder:
+ case BindForwarderNOT:
+ case BindImageModified:
+ case BindExpandFileHeaders:
+ case BindImageComplete:
+ case BindSymbolsNotUpdated:
+ case BindMismatchedSymbols:
+ case BindImportModuleFailed:
+ break;
+
+ case BindImportModule:
+ if (1 == sscanf(DllName, "python%d", &int_version)) {
+ SearchPath(NULL, DllName, NULL, sizeof(fname),
+ fname, NULL);
+ strcpy(bound_image_dll, fname);
+ bound_image_major = int_version / 10;
+ bound_image_minor = int_version % 10;
+ OutputDebugString("BOUND ");
+ OutputDebugString(fname);
+ OutputDebugString("\n");
+ }
+ break;
+ }
+ return TRUE;
}
/*
*/
static LPSTR get_sys_prefix(LPSTR exe, LPSTR dll)
{
- void (__cdecl * Py_Initialize)(void);
- void (__cdecl * Py_SetProgramName)(char *);
- void (__cdecl * Py_Finalize)(void);
- void* (__cdecl * PySys_GetObject)(char *);
- void (__cdecl * PySys_SetArgv)(int, char **);
- char* (__cdecl * Py_GetPrefix)(void);
- char* (__cdecl * Py_GetPath)(void);
- HINSTANCE hPython;
- LPSTR prefix = NULL;
- int (__cdecl * PyRun_SimpleString)(char *);
-
- {
- char Buffer[256];
- wsprintf(Buffer, "PYTHONHOME=%s", exe);
- *strrchr(Buffer, '\\') = '\0';
-// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK);
- _putenv(Buffer);
- _putenv("PYTHONPATH=");
- }
-
- hPython = LoadLibrary(dll);
- if (!hPython)
- return NULL;
- Py_Initialize = (void (*)(void))GetProcAddress
- (hPython,"Py_Initialize");
-
- PySys_SetArgv = (void (*)(int, char **))GetProcAddress
- (hPython,"PySys_SetArgv");
-
- PyRun_SimpleString = (int (*)(char *))GetProcAddress
- (hPython,"PyRun_SimpleString");
-
- Py_SetProgramName = (void (*)(char *))GetProcAddress
- (hPython,"Py_SetProgramName");
-
- PySys_GetObject = (void* (*)(char *))GetProcAddress
- (hPython,"PySys_GetObject");
-
- Py_GetPrefix = (char * (*)(void))GetProcAddress
- (hPython,"Py_GetPrefix");
-
- Py_GetPath = (char * (*)(void))GetProcAddress
- (hPython,"Py_GetPath");
-
- Py_Finalize = (void (*)(void))GetProcAddress(hPython,
- "Py_Finalize");
- Py_SetProgramName(exe);
- Py_Initialize();
- PySys_SetArgv(1, &exe);
-
- MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK);
- MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK);
-
- Py_Finalize();
- FreeLibrary(hPython);
-
- return prefix;
+ void (__cdecl * Py_Initialize)(void);
+ void (__cdecl * Py_SetProgramName)(char *);
+ void (__cdecl * Py_Finalize)(void);
+ void* (__cdecl * PySys_GetObject)(char *);
+ void (__cdecl * PySys_SetArgv)(int, char **);
+ char* (__cdecl * Py_GetPrefix)(void);
+ char* (__cdecl * Py_GetPath)(void);
+ HINSTANCE hPython;
+ LPSTR prefix = NULL;
+ int (__cdecl * PyRun_SimpleString)(char *);
+
+ {
+ char Buffer[256];
+ wsprintf(Buffer, "PYTHONHOME=%s", exe);
+ *strrchr(Buffer, '\\') = '\0';
+// MessageBox(GetFocus(), Buffer, "PYTHONHOME", MB_OK);
+ _putenv(Buffer);
+ _putenv("PYTHONPATH=");
+ }
+
+ hPython = LoadLibrary(dll);
+ if (!hPython)
+ return NULL;
+ Py_Initialize = (void (*)(void))GetProcAddress
+ (hPython,"Py_Initialize");
+
+ PySys_SetArgv = (void (*)(int, char **))GetProcAddress
+ (hPython,"PySys_SetArgv");
+
+ PyRun_SimpleString = (int (*)(char *))GetProcAddress
+ (hPython,"PyRun_SimpleString");
+
+ Py_SetProgramName = (void (*)(char *))GetProcAddress
+ (hPython,"Py_SetProgramName");
+
+ PySys_GetObject = (void* (*)(char *))GetProcAddress
+ (hPython,"PySys_GetObject");
+
+ Py_GetPrefix = (char * (*)(void))GetProcAddress
+ (hPython,"Py_GetPrefix");
+
+ Py_GetPath = (char * (*)(void))GetProcAddress
+ (hPython,"Py_GetPath");
+
+ Py_Finalize = (void (*)(void))GetProcAddress(hPython,
+ "Py_Finalize");
+ Py_SetProgramName(exe);
+ Py_Initialize();
+ PySys_SetArgv(1, &exe);
+
+ MessageBox(GetFocus(), Py_GetPrefix(), "PREFIX", MB_OK);
+ MessageBox(GetFocus(), Py_GetPath(), "PATH", MB_OK);
+
+ Py_Finalize();
+ FreeLibrary(hPython);
+
+ return prefix;
}
static BOOL
CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor)
{
- bound_image_dll[0] = '\0';
- if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES,
- pathname,
- NULL,
- NULL,
- StatusRoutine))
- return SystemError(0, "Could not bind image");
- if (bound_image_dll[0] == '\0')
- return SystemError(0, "Does not seem to be a python executable");
- *pmajor = bound_image_major;
- *pminor = bound_image_minor;
- if (version && *version) {
- char core_version[12];
- wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor);
- if (strcmp(version, core_version))
- return SystemError(0, "Wrong Python version");
- }
- get_sys_prefix(pathname, bound_image_dll);
- return TRUE;
+ bound_image_dll[0] = '\0';
+ if (!BindImageEx(BIND_NO_BOUND_IMPORTS | BIND_NO_UPDATE | BIND_ALL_IMAGES,
+ pathname,
+ NULL,
+ NULL,
+ StatusRoutine))
+ return SystemError(0, "Could not bind image");
+ if (bound_image_dll[0] == '\0')
+ return SystemError(0, "Does not seem to be a python executable");
+ *pmajor = bound_image_major;
+ *pminor = bound_image_minor;
+ if (version && *version) {
+ char core_version[12];
+ wsprintf(core_version, "%d.%d", bound_image_major, bound_image_minor);
+ if (strcmp(version, core_version))
+ return SystemError(0, "Wrong Python version");
+ }
+ get_sys_prefix(pathname, bound_image_dll);
+ return TRUE;
}
/*
@@ -1372,48 +1372,48 @@ CheckPythonExe(LPSTR pathname, LPSTR version, int *pmajor, int *pminor)
*/
static BOOL GetOtherPythonVersion(HWND hwnd, LPSTR version)
{
- char vers_name[_MAX_PATH + 80];
- DWORD itemindex;
- OPENFILENAME of;
- char pathname[_MAX_PATH];
- DWORD result;
-
- strcpy(pathname, "python.exe");
-
- memset(&of, 0, sizeof(of));
- of.lStructSize = sizeof(OPENFILENAME);
- of.hwndOwner = GetParent(hwnd);
- of.hInstance = NULL;
- of.lpstrFilter = "python.exe\0python.exe\0";
- of.lpstrCustomFilter = NULL;
- of.nMaxCustFilter = 0;
- of.nFilterIndex = 1;
- of.lpstrFile = pathname;
- of.nMaxFile = sizeof(pathname);
- of.lpstrFileTitle = NULL;
- of.nMaxFileTitle = 0;
- of.lpstrInitialDir = NULL;
- of.lpstrTitle = "Python executable";
- of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
- of.lpstrDefExt = "exe";
-
- result = GetOpenFileName(&of);
- if (result) {
- int major, minor;
- if (!CheckPythonExe(pathname, version, &major, &minor)) {
- return FALSE;
- }
- *strrchr(pathname, '\\') = '\0';
- wsprintf(vers_name, "Python Version %d.%d in %s",
- major, minor, pathname);
- itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1,
- (LPARAM)(LPSTR)vers_name);
- SendMessage(hwnd, LB_SETCURSEL, itemindex, 0);
- SendMessage(hwnd, LB_SETITEMDATA, itemindex,
- (LPARAM)(LPSTR)strdup(pathname));
- return TRUE;
- }
- return FALSE;
+ char vers_name[_MAX_PATH + 80];
+ DWORD itemindex;
+ OPENFILENAME of;
+ char pathname[_MAX_PATH];
+ DWORD result;
+
+ strcpy(pathname, "python.exe");
+
+ memset(&of, 0, sizeof(of));
+ of.lStructSize = sizeof(OPENFILENAME);
+ of.hwndOwner = GetParent(hwnd);
+ of.hInstance = NULL;
+ of.lpstrFilter = "python.exe\0python.exe\0";
+ of.lpstrCustomFilter = NULL;
+ of.nMaxCustFilter = 0;
+ of.nFilterIndex = 1;
+ of.lpstrFile = pathname;
+ of.nMaxFile = sizeof(pathname);
+ of.lpstrFileTitle = NULL;
+ of.nMaxFileTitle = 0;
+ of.lpstrInitialDir = NULL;
+ of.lpstrTitle = "Python executable";
+ of.Flags = OFN_FILEMUSTEXIST | OFN_PATHMUSTEXIST;
+ of.lpstrDefExt = "exe";
+
+ result = GetOpenFileName(&of);
+ if (result) {
+ int major, minor;
+ if (!CheckPythonExe(pathname, version, &major, &minor)) {
+ return FALSE;
+ }
+ *strrchr(pathname, '\\') = '\0';
+ wsprintf(vers_name, "Python Version %d.%d in %s",
+ major, minor, pathname);
+ itemindex = SendMessage(hwnd, LB_INSERTSTRING, -1,
+ (LPARAM)(LPSTR)vers_name);
+ SendMessage(hwnd, LB_SETCURSEL, itemindex, 0);
+ SendMessage(hwnd, LB_SETITEMDATA, itemindex,
+ (LPARAM)(LPSTR)strdup(pathname));
+ return TRUE;
+ }
+ return FALSE;
}
#endif /* USE_OTHER_PYTHON_VERSIONS */
@@ -1430,71 +1430,71 @@ typedef struct _InstalledVersionInfo {
*/
static BOOL GetPythonVersions(HWND hwnd, HKEY hkRoot, LPSTR version)
{
- DWORD index = 0;
- char core_version[80];
- HKEY hKey;
- BOOL result = TRUE;
- DWORD bufsize;
-
- if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot,
- "Software\\Python\\PythonCore",
- 0, KEY_READ, &hKey))
- return FALSE;
- bufsize = sizeof(core_version);
- while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index,
- core_version, &bufsize, NULL,
- NULL, NULL, NULL)) {
- char subkey_name[80], vers_name[80];
- int itemindex;
- DWORD value_size;
- HKEY hk;
-
- bufsize = sizeof(core_version);
- ++index;
- if (version && *version && strcmp(version, core_version))
- continue;
-
- wsprintf(vers_name, "Python Version %s (found in registry)",
- core_version);
- wsprintf(subkey_name,
- "Software\\Python\\PythonCore\\%s\\InstallPath",
- core_version);
- if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) {
- InstalledVersionInfo *ivi =
- (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo));
- value_size = sizeof(ivi->prefix);
- if (ivi &&
- ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL,
- ivi->prefix, &value_size)) {
- itemindex = SendMessage(hwnd, LB_ADDSTRING, 0,
- (LPARAM)(LPSTR)vers_name);
- ivi->hkey = hkRoot;
- SendMessage(hwnd, LB_SETITEMDATA, itemindex,
- (LPARAM)(LPSTR)ivi);
- }
- RegCloseKey(hk);
- }
- }
- RegCloseKey(hKey);
- return result;
+ DWORD index = 0;
+ char core_version[80];
+ HKEY hKey;
+ BOOL result = TRUE;
+ DWORD bufsize;
+
+ if (ERROR_SUCCESS != RegOpenKeyEx(hkRoot,
+ "Software\\Python\\PythonCore",
+ 0, KEY_READ, &hKey))
+ return FALSE;
+ bufsize = sizeof(core_version);
+ while (ERROR_SUCCESS == RegEnumKeyEx(hKey, index,
+ core_version, &bufsize, NULL,
+ NULL, NULL, NULL)) {
+ char subkey_name[80], vers_name[80];
+ int itemindex;
+ DWORD value_size;
+ HKEY hk;
+
+ bufsize = sizeof(core_version);
+ ++index;
+ if (version && *version && strcmp(version, core_version))
+ continue;
+
+ wsprintf(vers_name, "Python Version %s (found in registry)",
+ core_version);
+ wsprintf(subkey_name,
+ "Software\\Python\\PythonCore\\%s\\InstallPath",
+ core_version);
+ if (ERROR_SUCCESS == RegOpenKeyEx(hkRoot, subkey_name, 0, KEY_READ, &hk)) {
+ InstalledVersionInfo *ivi =
+ (InstalledVersionInfo *)malloc(sizeof(InstalledVersionInfo));
+ value_size = sizeof(ivi->prefix);
+ if (ivi &&
+ ERROR_SUCCESS == RegQueryValueEx(hk, NULL, NULL, NULL,
+ ivi->prefix, &value_size)) {
+ itemindex = SendMessage(hwnd, LB_ADDSTRING, 0,
+ (LPARAM)(LPSTR)vers_name);
+ ivi->hkey = hkRoot;
+ SendMessage(hwnd, LB_SETITEMDATA, itemindex,
+ (LPARAM)(LPSTR)ivi);
+ }
+ RegCloseKey(hk);
+ }
+ }
+ RegCloseKey(hKey);
+ return result;
}
/* Determine if the current user can write to HKEY_LOCAL_MACHINE */
BOOL HasLocalMachinePrivs()
{
- HKEY hKey;
- DWORD result;
- static char KeyName[] =
- "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
-
- result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- KeyName,
- 0,
- KEY_CREATE_SUB_KEY,
- &hKey);
- if (result==0)
- RegCloseKey(hKey);
- return result==0;
+ HKEY hKey;
+ DWORD result;
+ static char KeyName[] =
+ "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
+
+ result = RegOpenKeyEx(HKEY_LOCAL_MACHINE,
+ KeyName,
+ 0,
+ KEY_CREATE_SUB_KEY,
+ &hKey);
+ if (result==0)
+ RegCloseKey(hKey);
+ return result==0;
}
// Check the root registry key to use - either HKLM or HKCU.
@@ -1507,86 +1507,86 @@ BOOL HasLocalMachinePrivs()
// We assume hkey_root is already set to where Python itself is installed.
void CheckRootKey(HWND hwnd)
{
- if (hkey_root==HKEY_CURRENT_USER) {
- ; // as above, always install ourself in HKCU too.
- } else if (hkey_root==HKEY_LOCAL_MACHINE) {
- // Python in HKLM, but we may or may not have permissions there.
- // Open the uninstall key with 'create' permissions - if this fails,
- // we don't have permission.
- if (!HasLocalMachinePrivs())
- hkey_root = HKEY_CURRENT_USER;
- } else {
- MessageBox(hwnd, "Don't know Python's installation type",
- "Strange", MB_OK | MB_ICONSTOP);
- /* Default to wherever they can, but preferring HKLM */
- hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
- }
+ if (hkey_root==HKEY_CURRENT_USER) {
+ ; // as above, always install ourself in HKCU too.
+ } else if (hkey_root==HKEY_LOCAL_MACHINE) {
+ // Python in HKLM, but we may or may not have permissions there.
+ // Open the uninstall key with 'create' permissions - if this fails,
+ // we don't have permission.
+ if (!HasLocalMachinePrivs())
+ hkey_root = HKEY_CURRENT_USER;
+ } else {
+ MessageBox(hwnd, "Don't know Python's installation type",
+ "Strange", MB_OK | MB_ICONSTOP);
+ /* Default to wherever they can, but preferring HKLM */
+ hkey_root = HasLocalMachinePrivs() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER;
+ }
}
/* Return the installation scheme depending on Python version number */
SCHEME *GetScheme(int major, int minor)
{
- if (major > 2)
- return new_scheme;
- else if((major == 2) && (minor >= 2))
- return new_scheme;
- return old_scheme;
+ if (major > 2)
+ return new_scheme;
+ else if((major == 2) && (minor >= 2))
+ return new_scheme;
+ return old_scheme;
}
BOOL CALLBACK
SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- LPNMHDR lpnm;
-
- switch (msg) {
- case WM_INITDIALOG:
- if (hBitmap)
- SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
- IMAGE_BITMAP, (LPARAM)hBitmap);
- GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
- HKEY_LOCAL_MACHINE, target_version);
- GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
- HKEY_CURRENT_USER, target_version);
- { /* select the last entry which is the highest python
- version found */
- int count;
- count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
- LB_GETCOUNT, 0, 0);
- if (count && count != LB_ERR)
- SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL,
- count-1, 0);
-
- /* If a specific Python version is required,
- * display a prominent notice showing this fact.
- */
- if (target_version && target_version[0]) {
- char buffer[4096];
- wsprintf(buffer,
- "Python %s is required for this package. "
- "Select installation to use:",
- target_version);
- SetDlgItemText(hwnd, IDC_TITLE, buffer);
- }
-
- if (count == 0) {
- char Buffer[4096];
- char *msg;
- if (target_version && target_version[0]) {
- wsprintf(Buffer,
- "Python version %s required, which was not found"
- " in the registry.", target_version);
- msg = Buffer;
- } else
- msg = "No Python installation found in the registry.";
- MessageBox(hwnd, msg, "Cannot install",
- MB_OK | MB_ICONSTOP);
- }
- }
- goto UpdateInstallDir;
- break;
-
- case WM_COMMAND:
- switch (LOWORD(wParam)) {
+ LPNMHDR lpnm;
+
+ switch (msg) {
+ case WM_INITDIALOG:
+ if (hBitmap)
+ SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
+ IMAGE_BITMAP, (LPARAM)hBitmap);
+ GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
+ HKEY_LOCAL_MACHINE, target_version);
+ GetPythonVersions(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
+ HKEY_CURRENT_USER, target_version);
+ { /* select the last entry which is the highest python
+ version found */
+ int count;
+ count = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
+ LB_GETCOUNT, 0, 0);
+ if (count && count != LB_ERR)
+ SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST, LB_SETCURSEL,
+ count-1, 0);
+
+ /* If a specific Python version is required,
+ * display a prominent notice showing this fact.
+ */
+ if (target_version && target_version[0]) {
+ char buffer[4096];
+ wsprintf(buffer,
+ "Python %s is required for this package. "
+ "Select installation to use:",
+ target_version);
+ SetDlgItemText(hwnd, IDC_TITLE, buffer);
+ }
+
+ if (count == 0) {
+ char Buffer[4096];
+ char *msg;
+ if (target_version && target_version[0]) {
+ wsprintf(Buffer,
+ "Python version %s required, which was not found"
+ " in the registry.", target_version);
+ msg = Buffer;
+ } else
+ msg = "No Python installation found in the registry.";
+ MessageBox(hwnd, msg, "Cannot install",
+ MB_OK | MB_ICONSTOP);
+ }
+ }
+ goto UpdateInstallDir;
+ break;
+
+ case WM_COMMAND:
+ switch (LOWORD(wParam)) {
/*
case IDC_OTHERPYTHON:
if (GetOtherPythonVersion(GetDlgItem(hwnd, IDC_VERSIONS_LIST),
@@ -1594,307 +1594,307 @@ SelectPythonDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
goto UpdateInstallDir;
break;
*/
- case IDC_VERSIONS_LIST:
- switch (HIWORD(wParam)) {
- int id;
- case LBN_SELCHANGE:
- UpdateInstallDir:
- PropSheet_SetWizButtons(GetParent(hwnd),
- PSWIZB_BACK | PSWIZB_NEXT);
- id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
- LB_GETCURSEL, 0, 0);
- if (id == LB_ERR) {
- PropSheet_SetWizButtons(GetParent(hwnd),
- PSWIZB_BACK);
- SetDlgItemText(hwnd, IDC_PATH, "");
- SetDlgItemText(hwnd, IDC_INSTALL_PATH, "");
- strcpy(python_dir, "");
- strcpy(pythondll, "");
- } else {
- char *pbuf;
- int result;
- InstalledVersionInfo *ivi;
- PropSheet_SetWizButtons(GetParent(hwnd),
- PSWIZB_BACK | PSWIZB_NEXT);
- /* Get the python directory */
- ivi = (InstalledVersionInfo *)
- SendDlgItemMessage(hwnd,
- IDC_VERSIONS_LIST,
- LB_GETITEMDATA,
- id,
- 0);
- hkey_root = ivi->hkey;
- strcpy(python_dir, ivi->prefix);
- SetDlgItemText(hwnd, IDC_PATH, python_dir);
- /* retrieve the python version and pythondll to use */
- result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
- LB_GETTEXTLEN, (WPARAM)id, 0);
- pbuf = (char *)malloc(result + 1);
- if (pbuf) {
- /* guess the name of the python-dll */
- SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
- LB_GETTEXT, (WPARAM)id,
- (LPARAM)pbuf);
- result = sscanf(pbuf, "Python Version %d.%d",
- &py_major, &py_minor);
- if (result == 2) {
+ case IDC_VERSIONS_LIST:
+ switch (HIWORD(wParam)) {
+ int id;
+ case LBN_SELCHANGE:
+ UpdateInstallDir:
+ PropSheet_SetWizButtons(GetParent(hwnd),
+ PSWIZB_BACK | PSWIZB_NEXT);
+ id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
+ LB_GETCURSEL, 0, 0);
+ if (id == LB_ERR) {
+ PropSheet_SetWizButtons(GetParent(hwnd),
+ PSWIZB_BACK);
+ SetDlgItemText(hwnd, IDC_PATH, "");
+ SetDlgItemText(hwnd, IDC_INSTALL_PATH, "");
+ strcpy(python_dir, "");
+ strcpy(pythondll, "");
+ } else {
+ char *pbuf;
+ int result;
+ InstalledVersionInfo *ivi;
+ PropSheet_SetWizButtons(GetParent(hwnd),
+ PSWIZB_BACK | PSWIZB_NEXT);
+ /* Get the python directory */
+ ivi = (InstalledVersionInfo *)
+ SendDlgItemMessage(hwnd,
+ IDC_VERSIONS_LIST,
+ LB_GETITEMDATA,
+ id,
+ 0);
+ hkey_root = ivi->hkey;
+ strcpy(python_dir, ivi->prefix);
+ SetDlgItemText(hwnd, IDC_PATH, python_dir);
+ /* retrieve the python version and pythondll to use */
+ result = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
+ LB_GETTEXTLEN, (WPARAM)id, 0);
+ pbuf = (char *)malloc(result + 1);
+ if (pbuf) {
+ /* guess the name of the python-dll */
+ SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
+ LB_GETTEXT, (WPARAM)id,
+ (LPARAM)pbuf);
+ result = sscanf(pbuf, "Python Version %d.%d",
+ &py_major, &py_minor);
+ if (result == 2) {
#ifdef _DEBUG
- wsprintf(pythondll, "python%d%d_d.dll",
- py_major, py_minor);
+ wsprintf(pythondll, "python%d%d_d.dll",
+ py_major, py_minor);
#else
- wsprintf(pythondll, "python%d%d.dll",
- py_major, py_minor);
+ wsprintf(pythondll, "python%d%d.dll",
+ py_major, py_minor);
#endif
- }
- free(pbuf);
- } else
- strcpy(pythondll, "");
- /* retrieve the scheme for this version */
- {
- char install_path[_MAX_PATH];
- SCHEME *scheme = GetScheme(py_major, py_minor);
- strcpy(install_path, python_dir);
- if (install_path[strlen(install_path)-1] != '\\')
- strcat(install_path, "\\");
- strcat(install_path, scheme[0].prefix);
- SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
- }
- }
- }
- break;
- }
- return 0;
-
- case WM_NOTIFY:
- lpnm = (LPNMHDR) lParam;
-
- switch (lpnm->code) {
- int id;
- case PSN_SETACTIVE:
- id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
- LB_GETCURSEL, 0, 0);
- if (id == LB_ERR)
- PropSheet_SetWizButtons(GetParent(hwnd),
- PSWIZB_BACK);
- else
- PropSheet_SetWizButtons(GetParent(hwnd),
- PSWIZB_BACK | PSWIZB_NEXT);
- break;
-
- case PSN_WIZNEXT:
- break;
-
- case PSN_WIZFINISH:
- break;
-
- case PSN_RESET:
- break;
-
- default:
- break;
- }
- }
- return 0;
+ }
+ free(pbuf);
+ } else
+ strcpy(pythondll, "");
+ /* retrieve the scheme for this version */
+ {
+ char install_path[_MAX_PATH];
+ SCHEME *scheme = GetScheme(py_major, py_minor);
+ strcpy(install_path, python_dir);
+ if (install_path[strlen(install_path)-1] != '\\')
+ strcat(install_path, "\\");
+ strcat(install_path, scheme[0].prefix);
+ SetDlgItemText(hwnd, IDC_INSTALL_PATH, install_path);
+ }
+ }
+ }
+ break;
+ }
+ return 0;
+
+ case WM_NOTIFY:
+ lpnm = (LPNMHDR) lParam;
+
+ switch (lpnm->code) {
+ int id;
+ case PSN_SETACTIVE:
+ id = SendDlgItemMessage(hwnd, IDC_VERSIONS_LIST,
+ LB_GETCURSEL, 0, 0);
+ if (id == LB_ERR)
+ PropSheet_SetWizButtons(GetParent(hwnd),
+ PSWIZB_BACK);
+ else
+ PropSheet_SetWizButtons(GetParent(hwnd),
+ PSWIZB_BACK | PSWIZB_NEXT);
+ break;
+
+ case PSN_WIZNEXT:
+ break;
+
+ case PSN_WIZFINISH:
+ break;
+
+ case PSN_RESET:
+ break;
+
+ default:
+ break;
+ }
+ }
+ return 0;
}
static BOOL OpenLogfile(char *dir)
{
- char buffer[_MAX_PATH+1];
- time_t ltime;
- struct tm *now;
- long result;
- HKEY hKey, hSubkey;
- char subkey_name[256];
- static char KeyName[] =
- "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
- const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ?
- "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER");
- DWORD disposition;
-
- /* Use Create, as the Uninstall subkey may not exist under HKCU.
- Use CreateKeyEx, so we can specify a SAM specifying write access
- */
- result = RegCreateKeyEx(hkey_root,
- KeyName,
- 0, /* reserved */
- NULL, /* class */
- 0, /* options */
- KEY_CREATE_SUB_KEY, /* sam */
- NULL, /* security */
- &hKey, /* result key */
- NULL); /* disposition */
- if (result != ERROR_SUCCESS) {
- if (result == ERROR_ACCESS_DENIED) {
- /* This should no longer be able to happen - we have already
- checked if they have permissions in HKLM, and all users
- should have write access to HKCU.
- */
- MessageBox(GetFocus(),
- "You do not seem to have sufficient access rights\n"
- "on this machine to install this software",
- NULL,
- MB_OK | MB_ICONSTOP);
- return FALSE;
- } else {
- MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK);
- }
- }
-
- sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name);
- logfile = fopen(buffer, "a");
- time(&ltime);
- now = localtime(&ltime);
- strftime(buffer, sizeof(buffer),
- "*** Installation started %Y/%m/%d %H:%M ***\n",
- localtime(&ltime));
- fprintf(logfile, buffer);
- fprintf(logfile, "Source: %s\n", modulename);
-
- /* Root key must be first entry processed by uninstaller. */
- fprintf(logfile, "999 Root Key: %s\n", root_name);
-
- sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor);
-
- result = RegCreateKeyEx(hKey, subkey_name,
- 0, NULL, 0,
- KEY_WRITE,
- NULL,
- &hSubkey,
- &disposition);
-
- if (result != ERROR_SUCCESS)
- MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK);
-
- RegCloseKey(hKey);
-
- if (disposition == REG_CREATED_NEW_KEY)
- fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name);
-
- sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title);
-
- result = RegSetValueEx(hSubkey, "DisplayName",
- 0,
- REG_SZ,
- buffer,
- strlen(buffer)+1);
-
- if (result != ERROR_SUCCESS)
- MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
-
- fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
- KeyName, subkey_name, "DisplayName", buffer);
-
- {
- FILE *fp;
- sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name);
- fp = fopen(buffer, "wb");
- fwrite(arc_data, exe_size, 1, fp);
- fclose(fp);
-
- sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"",
- dir, meta_name, dir, meta_name);
-
- result = RegSetValueEx(hSubkey, "UninstallString",
- 0,
- REG_SZ,
- buffer,
- strlen(buffer)+1);
-
- if (result != ERROR_SUCCESS)
- MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
-
- fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
- KeyName, subkey_name, "UninstallString", buffer);
- }
- return TRUE;
+ char buffer[_MAX_PATH+1];
+ time_t ltime;
+ struct tm *now;
+ long result;
+ HKEY hKey, hSubkey;
+ char subkey_name[256];
+ static char KeyName[] =
+ "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall";
+ const char *root_name = (hkey_root==HKEY_LOCAL_MACHINE ?
+ "HKEY_LOCAL_MACHINE" : "HKEY_CURRENT_USER");
+ DWORD disposition;
+
+ /* Use Create, as the Uninstall subkey may not exist under HKCU.
+ Use CreateKeyEx, so we can specify a SAM specifying write access
+ */
+ result = RegCreateKeyEx(hkey_root,
+ KeyName,
+ 0, /* reserved */
+ NULL, /* class */
+ 0, /* options */
+ KEY_CREATE_SUB_KEY, /* sam */
+ NULL, /* security */
+ &hKey, /* result key */
+ NULL); /* disposition */
+ if (result != ERROR_SUCCESS) {
+ if (result == ERROR_ACCESS_DENIED) {
+ /* This should no longer be able to happen - we have already
+ checked if they have permissions in HKLM, and all users
+ should have write access to HKCU.
+ */
+ MessageBox(GetFocus(),
+ "You do not seem to have sufficient access rights\n"
+ "on this machine to install this software",
+ NULL,
+ MB_OK | MB_ICONSTOP);
+ return FALSE;
+ } else {
+ MessageBox(GetFocus(), KeyName, "Could not open key", MB_OK);
+ }
+ }
+
+ sprintf(buffer, "%s\\%s-wininst.log", dir, meta_name);
+ logfile = fopen(buffer, "a");
+ time(&ltime);
+ now = localtime(&ltime);
+ strftime(buffer, sizeof(buffer),
+ "*** Installation started %Y/%m/%d %H:%M ***\n",
+ localtime(&ltime));
+ fprintf(logfile, buffer);
+ fprintf(logfile, "Source: %s\n", modulename);
+
+ /* Root key must be first entry processed by uninstaller. */
+ fprintf(logfile, "999 Root Key: %s\n", root_name);
+
+ sprintf(subkey_name, "%s-py%d.%d", meta_name, py_major, py_minor);
+
+ result = RegCreateKeyEx(hKey, subkey_name,
+ 0, NULL, 0,
+ KEY_WRITE,
+ NULL,
+ &hSubkey,
+ &disposition);
+
+ if (result != ERROR_SUCCESS)
+ MessageBox(GetFocus(), subkey_name, "Could not create key", MB_OK);
+
+ RegCloseKey(hKey);
+
+ if (disposition == REG_CREATED_NEW_KEY)
+ fprintf(logfile, "020 Reg DB Key: [%s]%s\n", KeyName, subkey_name);
+
+ sprintf(buffer, "Python %d.%d %s", py_major, py_minor, title);
+
+ result = RegSetValueEx(hSubkey, "DisplayName",
+ 0,
+ REG_SZ,
+ buffer,
+ strlen(buffer)+1);
+
+ if (result != ERROR_SUCCESS)
+ MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
+
+ fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
+ KeyName, subkey_name, "DisplayName", buffer);
+
+ {
+ FILE *fp;
+ sprintf(buffer, "%s\\Remove%s.exe", dir, meta_name);
+ fp = fopen(buffer, "wb");
+ fwrite(arc_data, exe_size, 1, fp);
+ fclose(fp);
+
+ sprintf(buffer, "\"%s\\Remove%s.exe\" -u \"%s\\%s-wininst.log\"",
+ dir, meta_name, dir, meta_name);
+
+ result = RegSetValueEx(hSubkey, "UninstallString",
+ 0,
+ REG_SZ,
+ buffer,
+ strlen(buffer)+1);
+
+ if (result != ERROR_SUCCESS)
+ MessageBox(GetFocus(), buffer, "Could not set key value", MB_OK);
+
+ fprintf(logfile, "040 Reg DB Value: [%s\\%s]%s=%s\n",
+ KeyName, subkey_name, "UninstallString", buffer);
+ }
+ return TRUE;
}
static void CloseLogfile(void)
{
- char buffer[_MAX_PATH+1];
- time_t ltime;
- struct tm *now;
-
- time(&ltime);
- now = localtime(&ltime);
- strftime(buffer, sizeof(buffer),
- "*** Installation finished %Y/%m/%d %H:%M ***\n",
- localtime(&ltime));
- fprintf(logfile, buffer);
- if (logfile)
- fclose(logfile);
+ char buffer[_MAX_PATH+1];
+ time_t ltime;
+ struct tm *now;
+
+ time(&ltime);
+ now = localtime(&ltime);
+ strftime(buffer, sizeof(buffer),
+ "*** Installation finished %Y/%m/%d %H:%M ***\n",
+ localtime(&ltime));
+ fprintf(logfile, buffer);
+ if (logfile)
+ fclose(logfile);
}
BOOL CALLBACK
InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- LPNMHDR lpnm;
- char Buffer[4096];
- SCHEME *scheme;
-
- switch (msg) {
- case WM_INITDIALOG:
- if (hBitmap)
- SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
- IMAGE_BITMAP, (LPARAM)hBitmap);
- wsprintf(Buffer,
- "Click Next to begin the installation of %s. "
- "If you want to review or change any of your "
- " installation settings, click Back. "
- "Click Cancel to exit the wizard.",
- meta_name);
- SetDlgItemText(hwnd, IDC_TITLE, Buffer);
- SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
- break;
-
- case WM_NUMFILES:
- SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam);
- PumpMessages();
- return TRUE;
-
- case WM_NEXTFILE:
- SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam,
- 0);
- SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam);
- PumpMessages();
- return TRUE;
-
- case WM_NOTIFY:
- lpnm = (LPNMHDR) lParam;
-
- switch (lpnm->code) {
- case PSN_SETACTIVE:
- PropSheet_SetWizButtons(GetParent(hwnd),
- PSWIZB_BACK | PSWIZB_NEXT);
- break;
-
- case PSN_WIZFINISH:
- break;
-
- case PSN_WIZNEXT:
- /* Handle a Next button click here */
- hDialog = hwnd;
- success = TRUE;
-
- /* Disable the buttons while we work. Sending CANCELTOCLOSE has
- the effect of disabling the cancel button, which is a) as we
- do everything synchronously we can't cancel, and b) the next
- step is 'finished', when it is too late to cancel anyway.
- The next step being 'Finished' means we also don't need to
- restore the button state back */
- PropSheet_SetWizButtons(GetParent(hwnd), 0);
- SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0);
- /* Make sure the installation directory name ends in a */
- /* backslash */
- if (python_dir[strlen(python_dir)-1] != '\\')
- strcat(python_dir, "\\");
- /* Strip the trailing backslash again */
- python_dir[strlen(python_dir)-1] = '\0';
-
- CheckRootKey(hwnd);
-
- if (!OpenLogfile(python_dir))
- break;
+ LPNMHDR lpnm;
+ char Buffer[4096];
+ SCHEME *scheme;
+
+ switch (msg) {
+ case WM_INITDIALOG:
+ if (hBitmap)
+ SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
+ IMAGE_BITMAP, (LPARAM)hBitmap);
+ wsprintf(Buffer,
+ "Click Next to begin the installation of %s. "
+ "If you want to review or change any of your "
+ " installation settings, click Back. "
+ "Click Cancel to exit the wizard.",
+ meta_name);
+ SetDlgItemText(hwnd, IDC_TITLE, Buffer);
+ SetDlgItemText(hwnd, IDC_INFO, "Ready to install");
+ break;
+
+ case WM_NUMFILES:
+ SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETRANGE, 0, lParam);
+ PumpMessages();
+ return TRUE;
+
+ case WM_NEXTFILE:
+ SendDlgItemMessage(hwnd, IDC_PROGRESS, PBM_SETPOS, wParam,
+ 0);
+ SetDlgItemText(hwnd, IDC_INFO, (LPSTR)lParam);
+ PumpMessages();
+ return TRUE;
+
+ case WM_NOTIFY:
+ lpnm = (LPNMHDR) lParam;
+
+ switch (lpnm->code) {
+ case PSN_SETACTIVE:
+ PropSheet_SetWizButtons(GetParent(hwnd),
+ PSWIZB_BACK | PSWIZB_NEXT);
+ break;
+
+ case PSN_WIZFINISH:
+ break;
+
+ case PSN_WIZNEXT:
+ /* Handle a Next button click here */
+ hDialog = hwnd;
+ success = TRUE;
+
+ /* Disable the buttons while we work. Sending CANCELTOCLOSE has
+ the effect of disabling the cancel button, which is a) as we
+ do everything synchronously we can't cancel, and b) the next
+ step is 'finished', when it is too late to cancel anyway.
+ The next step being 'Finished' means we also don't need to
+ restore the button state back */
+ PropSheet_SetWizButtons(GetParent(hwnd), 0);
+ SendMessage(GetParent(hwnd), PSM_CANCELTOCLOSE, 0, 0);
+ /* Make sure the installation directory name ends in a */
+ /* backslash */
+ if (python_dir[strlen(python_dir)-1] != '\\')
+ strcat(python_dir, "\\");
+ /* Strip the trailing backslash again */
+ python_dir[strlen(python_dir)-1] = '\0';
+
+ CheckRootKey(hwnd);
+
+ if (!OpenLogfile(python_dir))
+ break;
/*
* The scheme we have to use depends on the Python version...
@@ -1915,202 +1915,202 @@ InstallFilesDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
'data' : '$base',
}
*/
- scheme = GetScheme(py_major, py_minor);
- /* Run the pre-install script. */
- if (pre_install_script && *pre_install_script) {
- SetDlgItemText (hwnd, IDC_TITLE,
- "Running pre-installation script");
- run_simple_script(pre_install_script);
- }
- if (!success) {
- break;
- }
- /* Extract all files from the archive */
- SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
- if (!unzip_archive (scheme,
- python_dir, arc_data,
- arc_size, notify))
- set_failure_reason("Failed to unzip installation files");
- /* Compile the py-files */
- if (success && pyc_compile) {
- int errors;
- HINSTANCE hPython;
- SetDlgItemText(hwnd, IDC_TITLE,
- "Compiling files to .pyc...");
-
- SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
- hPython = LoadPythonDll(pythondll);
- if (hPython) {
- errors = compile_filelist(hPython, FALSE);
- FreeLibrary(hPython);
- }
- /* Compilation errors are intentionally ignored:
- * Python2.0 contains a bug which will result
- * in sys.path containing garbage under certain
- * circumstances, and an error message will only
- * confuse the user.
- */
- }
- if (success && pyo_compile) {
- int errors;
- HINSTANCE hPython;
- SetDlgItemText(hwnd, IDC_TITLE,
- "Compiling files to .pyo...");
-
- SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
- hPython = LoadPythonDll(pythondll);
- if (hPython) {
- errors = compile_filelist(hPython, TRUE);
- FreeLibrary(hPython);
- }
- /* Errors ignored: see above */
- }
-
-
- break;
-
- case PSN_RESET:
- break;
-
- default:
- break;
- }
- }
- return 0;
+ scheme = GetScheme(py_major, py_minor);
+ /* Run the pre-install script. */
+ if (pre_install_script && *pre_install_script) {
+ SetDlgItemText (hwnd, IDC_TITLE,
+ "Running pre-installation script");
+ run_simple_script(pre_install_script);
+ }
+ if (!success) {
+ break;
+ }
+ /* Extract all files from the archive */
+ SetDlgItemText(hwnd, IDC_TITLE, "Installing files...");
+ if (!unzip_archive (scheme,
+ python_dir, arc_data,
+ arc_size, notify))
+ set_failure_reason("Failed to unzip installation files");
+ /* Compile the py-files */
+ if (success && pyc_compile) {
+ int errors;
+ HINSTANCE hPython;
+ SetDlgItemText(hwnd, IDC_TITLE,
+ "Compiling files to .pyc...");
+
+ SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
+ hPython = LoadPythonDll(pythondll);
+ if (hPython) {
+ errors = compile_filelist(hPython, FALSE);
+ FreeLibrary(hPython);
+ }
+ /* Compilation errors are intentionally ignored:
+ * Python2.0 contains a bug which will result
+ * in sys.path containing garbage under certain
+ * circumstances, and an error message will only
+ * confuse the user.
+ */
+ }
+ if (success && pyo_compile) {
+ int errors;
+ HINSTANCE hPython;
+ SetDlgItemText(hwnd, IDC_TITLE,
+ "Compiling files to .pyo...");
+
+ SetDlgItemText(hDialog, IDC_INFO, "Loading python...");
+ hPython = LoadPythonDll(pythondll);
+ if (hPython) {
+ errors = compile_filelist(hPython, TRUE);
+ FreeLibrary(hPython);
+ }
+ /* Errors ignored: see above */
+ }
+
+
+ break;
+
+ case PSN_RESET:
+ break;
+
+ default:
+ break;
+ }
+ }
+ return 0;
}
BOOL CALLBACK
FinishedDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
- LPNMHDR lpnm;
-
- switch (msg) {
- case WM_INITDIALOG:
- if (hBitmap)
- SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
- IMAGE_BITMAP, (LPARAM)hBitmap);
- if (!success)
- SetDlgItemText(hwnd, IDC_INFO, get_failure_reason());
-
- /* async delay: will show the dialog box completely before
- the install_script is started */
- PostMessage(hwnd, WM_USER, 0, 0L);
- return TRUE;
-
- case WM_USER:
-
- if (success && install_script && install_script[0]) {
- char fname[MAX_PATH];
- char *buffer;
- HCURSOR hCursor;
- int result;
-
- char *argv[3] = {NULL, "-install", NULL};
-
- SetDlgItemText(hwnd, IDC_TITLE,
- "Please wait while running postinstall script...");
- strcpy(fname, python_dir);
- strcat(fname, "\\Scripts\\");
- strcat(fname, install_script);
-
- if (logfile)
- fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname);
-
- hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
-
- argv[0] = fname;
-
- result = run_installscript(fname, 2, argv, &buffer);
- if (0 != result) {
- fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
- }
- if (buffer)
- SetDlgItemText(hwnd, IDC_INFO, buffer);
- SetDlgItemText(hwnd, IDC_TITLE,
- "Postinstall script finished.\n"
- "Click the Finish button to exit the Setup wizard.");
-
- free(buffer);
- SetCursor(hCursor);
- CloseLogfile();
- }
-
- return TRUE;
-
- case WM_NOTIFY:
- lpnm = (LPNMHDR) lParam;
-
- switch (lpnm->code) {
- case PSN_SETACTIVE: /* Enable the Finish button */
- PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH);
- break;
-
- case PSN_WIZNEXT:
- break;
-
- case PSN_WIZFINISH:
- break;
-
- case PSN_RESET:
- break;
-
- default:
- break;
- }
- }
- return 0;
+ LPNMHDR lpnm;
+
+ switch (msg) {
+ case WM_INITDIALOG:
+ if (hBitmap)
+ SendDlgItemMessage(hwnd, IDC_BITMAP, STM_SETIMAGE,
+ IMAGE_BITMAP, (LPARAM)hBitmap);
+ if (!success)
+ SetDlgItemText(hwnd, IDC_INFO, get_failure_reason());
+
+ /* async delay: will show the dialog box completely before
+ the install_script is started */
+ PostMessage(hwnd, WM_USER, 0, 0L);
+ return TRUE;
+
+ case WM_USER:
+
+ if (success && install_script && install_script[0]) {
+ char fname[MAX_PATH];
+ char *buffer;
+ HCURSOR hCursor;
+ int result;
+
+ char *argv[3] = {NULL, "-install", NULL};
+
+ SetDlgItemText(hwnd, IDC_TITLE,
+ "Please wait while running postinstall script...");
+ strcpy(fname, python_dir);
+ strcat(fname, "\\Scripts\\");
+ strcat(fname, install_script);
+
+ if (logfile)
+ fprintf(logfile, "300 Run Script: [%s]%s\n", pythondll, fname);
+
+ hCursor = SetCursor(LoadCursor(NULL, IDC_WAIT));
+
+ argv[0] = fname;
+
+ result = run_installscript(fname, 2, argv, &buffer);
+ if (0 != result) {
+ fprintf(stderr, "*** run_installscript: internal error 0x%X ***\n", result);
+ }
+ if (buffer)
+ SetDlgItemText(hwnd, IDC_INFO, buffer);
+ SetDlgItemText(hwnd, IDC_TITLE,
+ "Postinstall script finished.\n"
+ "Click the Finish button to exit the Setup wizard.");
+
+ free(buffer);
+ SetCursor(hCursor);
+ CloseLogfile();
+ }
+
+ return TRUE;
+
+ case WM_NOTIFY:
+ lpnm = (LPNMHDR) lParam;
+
+ switch (lpnm->code) {
+ case PSN_SETACTIVE: /* Enable the Finish button */
+ PropSheet_SetWizButtons(GetParent(hwnd), PSWIZB_FINISH);
+ break;
+
+ case PSN_WIZNEXT:
+ break;
+
+ case PSN_WIZFINISH:
+ break;
+
+ case PSN_RESET:
+ break;
+
+ default:
+ break;
+ }
+ }
+ return 0;
}
void RunWizard(HWND hwnd)
{
- PROPSHEETPAGE psp = {0};
- HPROPSHEETPAGE ahpsp[4] = {0};
- PROPSHEETHEADER psh = {0};
-
- /* Display module information */
- psp.dwSize = sizeof(psp);
- psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
- psp.hInstance = GetModuleHandle (NULL);
- psp.lParam = 0;
- psp.pfnDlgProc = IntroDlgProc;
- psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO);
-
- ahpsp[0] = CreatePropertySheetPage(&psp);
-
- /* Select python version to use */
- psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
- psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON);
- psp.pfnDlgProc = SelectPythonDlgProc;
-
- ahpsp[1] = CreatePropertySheetPage(&psp);
-
- /* Install the files */
- psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
- psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES);
- psp.pfnDlgProc = InstallFilesDlgProc;
-
- ahpsp[2] = CreatePropertySheetPage(&psp);
-
- /* Show success or failure */
- psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
- psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED);
- psp.pfnDlgProc = FinishedDlgProc;
-
- ahpsp[3] = CreatePropertySheetPage(&psp);
-
- /* Create the property sheet */
- psh.dwSize = sizeof(psh);
- psh.hInstance = GetModuleHandle(NULL);
- psh.hwndParent = hwnd;
- psh.phpage = ahpsp;
- psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/;
- psh.pszbmWatermark = NULL;
- psh.pszbmHeader = NULL;
- psh.nStartPage = 0;
- psh.nPages = 4;
-
- PropertySheet(&psh);
+ PROPSHEETPAGE psp = {0};
+ HPROPSHEETPAGE ahpsp[4] = {0};
+ PROPSHEETHEADER psh = {0};
+
+ /* Display module information */
+ psp.dwSize = sizeof(psp);
+ psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
+ psp.hInstance = GetModuleHandle (NULL);
+ psp.lParam = 0;
+ psp.pfnDlgProc = IntroDlgProc;
+ psp.pszTemplate = MAKEINTRESOURCE(IDD_INTRO);
+
+ ahpsp[0] = CreatePropertySheetPage(&psp);
+
+ /* Select python version to use */
+ psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
+ psp.pszTemplate = MAKEINTRESOURCE(IDD_SELECTPYTHON);
+ psp.pfnDlgProc = SelectPythonDlgProc;
+
+ ahpsp[1] = CreatePropertySheetPage(&psp);
+
+ /* Install the files */
+ psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
+ psp.pszTemplate = MAKEINTRESOURCE(IDD_INSTALLFILES);
+ psp.pfnDlgProc = InstallFilesDlgProc;
+
+ ahpsp[2] = CreatePropertySheetPage(&psp);
+
+ /* Show success or failure */
+ psp.dwFlags = PSP_DEFAULT|PSP_HIDEHEADER;
+ psp.pszTemplate = MAKEINTRESOURCE(IDD_FINISHED);
+ psp.pfnDlgProc = FinishedDlgProc;
+
+ ahpsp[3] = CreatePropertySheetPage(&psp);
+
+ /* Create the property sheet */
+ psh.dwSize = sizeof(psh);
+ psh.hInstance = GetModuleHandle(NULL);
+ psh.hwndParent = hwnd;
+ psh.phpage = ahpsp;
+ psh.dwFlags = PSH_WIZARD/*97*//*|PSH_WATERMARK|PSH_HEADER*/;
+ psh.pszbmWatermark = NULL;
+ psh.pszbmHeader = NULL;
+ psh.nStartPage = 0;
+ psh.nPages = 4;
+
+ PropertySheet(&psh);
}
// subtly different from HasLocalMachinePrivs(), in that after executing
@@ -2118,16 +2118,16 @@ void RunWizard(HWND hwnd)
// such implication for HasLocalMachinePrivs
BOOL MyIsUserAnAdmin()
{
- typedef BOOL (WINAPI *PFNIsUserAnAdmin)();
- static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL;
- HMODULE shell32;
- // This function isn't guaranteed to be available (and it can't hurt
- // to leave the library loaded)
- if (0 == (shell32=LoadLibrary("shell32.dll")))
- return FALSE;
- if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin")))
- return FALSE;
- return (*pfnIsUserAnAdmin)();
+ typedef BOOL (WINAPI *PFNIsUserAnAdmin)();
+ static PFNIsUserAnAdmin pfnIsUserAnAdmin = NULL;
+ HMODULE shell32;
+ // This function isn't guaranteed to be available (and it can't hurt
+ // to leave the library loaded)
+ if (0 == (shell32=LoadLibrary("shell32.dll")))
+ return FALSE;
+ if (0 == (pfnIsUserAnAdmin=(PFNIsUserAnAdmin)GetProcAddress(shell32, "IsUserAnAdmin")))
+ return FALSE;
+ return (*pfnIsUserAnAdmin)();
}
// Some magic for Vista's UAC. If there is a target_version, and
@@ -2139,38 +2139,38 @@ BOOL MyIsUserAnAdmin()
// Returns TRUE if we should spawn an elevated child
BOOL NeedAutoUAC()
{
- HKEY hk;
- char key_name[80];
- // no Python version info == we can't know yet.
- if (target_version[0] == '\0')
- return FALSE;
- // see how python is current installed
- wsprintf(key_name,
- "Software\\Python\\PythonCore\\%s\\InstallPath",
- target_version);
- if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE,
- key_name, 0, KEY_READ, &hk))
- return FALSE;
- RegCloseKey(hk);
- // Python is installed in HKLM - we must elevate.
- return TRUE;
+ HKEY hk;
+ char key_name[80];
+ // no Python version info == we can't know yet.
+ if (target_version[0] == '\0')
+ return FALSE;
+ // see how python is current installed
+ wsprintf(key_name,
+ "Software\\Python\\PythonCore\\%s\\InstallPath",
+ target_version);
+ if (ERROR_SUCCESS != RegOpenKeyEx(HKEY_LOCAL_MACHINE,
+ key_name, 0, KEY_READ, &hk))
+ return FALSE;
+ RegCloseKey(hk);
+ // Python is installed in HKLM - we must elevate.
+ return TRUE;
}
// Returns TRUE if the platform supports UAC.
BOOL PlatformSupportsUAC()
{
- // Note that win2k does seem to support ShellExecute with 'runas',
- // but does *not* support IsUserAnAdmin - so we just pretend things
- // only work on XP and later.
- BOOL bIsWindowsXPorLater;
- OSVERSIONINFO winverinfo;
- winverinfo.dwOSVersionInfoSize = sizeof(winverinfo);
- if (!GetVersionEx(&winverinfo))
- return FALSE; // something bad has gone wrong
- bIsWindowsXPorLater =
+ // Note that win2k does seem to support ShellExecute with 'runas',
+ // but does *not* support IsUserAnAdmin - so we just pretend things
+ // only work on XP and later.
+ BOOL bIsWindowsXPorLater;
+ OSVERSIONINFO winverinfo;
+ winverinfo.dwOSVersionInfoSize = sizeof(winverinfo);
+ if (!GetVersionEx(&winverinfo))
+ return FALSE; // something bad has gone wrong
+ bIsWindowsXPorLater =
( (winverinfo.dwMajorVersion > 5) ||
( (winverinfo.dwMajorVersion == 5) && (winverinfo.dwMinorVersion >= 1) ));
- return bIsWindowsXPorLater;
+ return bIsWindowsXPorLater;
}
// Spawn ourself as an elevated application. On failure, a message is
@@ -2178,97 +2178,97 @@ BOOL PlatformSupportsUAC()
// on error.
void SpawnUAC()
{
- // interesting failure scenario that has been seen: initial executable
- // runs from a network drive - but once elevated, that network share
- // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED.
- int ret = (int)ShellExecute(0, "runas", modulename, "", NULL,
- SW_SHOWNORMAL);
- if (ret <= 32) {
- char msg[128];
- wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret);
- MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR);
- }
+ // interesting failure scenario that has been seen: initial executable
+ // runs from a network drive - but once elevated, that network share
+ // isn't seen, and ShellExecute fails with SE_ERR_ACCESSDENIED.
+ int ret = (int)ShellExecute(0, "runas", modulename, "", NULL,
+ SW_SHOWNORMAL);
+ if (ret <= 32) {
+ char msg[128];
+ wsprintf(msg, "Failed to start elevated process (ShellExecute returned %d)", ret);
+ MessageBox(0, msg, "Setup", MB_OK | MB_ICONERROR);
+ }
}
int DoInstall(void)
{
- char ini_buffer[4096];
-
- /* Read installation information */
- GetPrivateProfileString("Setup", "title", "", ini_buffer,
- sizeof(ini_buffer), ini_file);
- unescape(title, ini_buffer, sizeof(title));
-
- GetPrivateProfileString("Setup", "info", "", ini_buffer,
- sizeof(ini_buffer), ini_file);
- unescape(info, ini_buffer, sizeof(info));
-
- GetPrivateProfileString("Setup", "build_info", "", build_info,
- sizeof(build_info), ini_file);
-
- pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1,
- ini_file);
- pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1,
- ini_file);
-
- GetPrivateProfileString("Setup", "target_version", "",
- target_version, sizeof(target_version),
- ini_file);
-
- GetPrivateProfileString("metadata", "name", "",
- meta_name, sizeof(meta_name),
- ini_file);
-
- GetPrivateProfileString("Setup", "install_script", "",
- install_script, sizeof(install_script),
- ini_file);
-
- GetPrivateProfileString("Setup", "user_access_control", "",
- user_access_control, sizeof(user_access_control), ini_file);
-
- // See if we need to do the Vista UAC magic.
- if (strcmp(user_access_control, "force")==0) {
- if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) {
- SpawnUAC();
- return 0;
- }
- // already admin - keep going
- } else if (strcmp(user_access_control, "auto")==0) {
- // Check if it looks like we need UAC control, based
- // on how Python itself was installed.
- if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) {
- SpawnUAC();
- return 0;
- }
- } else {
- // display a warning about unknown values - only the developer
- // of the extension will see it (until they fix it!)
- if (user_access_control[0] && strcmp(user_access_control, "none") != 0) {
- MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK);
- // nothing to do.
- }
- }
-
- hwndMain = CreateBackground(title);
-
- RunWizard(hwndMain);
-
- /* Clean up */
- UnmapViewOfFile(arc_data);
- if (ini_file)
- DeleteFile(ini_file);
-
- if (hBitmap)
- DeleteObject(hBitmap);
-
- return 0;
+ char ini_buffer[4096];
+
+ /* Read installation information */
+ GetPrivateProfileString("Setup", "title", "", ini_buffer,
+ sizeof(ini_buffer), ini_file);
+ unescape(title, ini_buffer, sizeof(title));
+
+ GetPrivateProfileString("Setup", "info", "", ini_buffer,
+ sizeof(ini_buffer), ini_file);
+ unescape(info, ini_buffer, sizeof(info));
+
+ GetPrivateProfileString("Setup", "build_info", "", build_info,
+ sizeof(build_info), ini_file);
+
+ pyc_compile = GetPrivateProfileInt("Setup", "target_compile", 1,
+ ini_file);
+ pyo_compile = GetPrivateProfileInt("Setup", "target_optimize", 1,
+ ini_file);
+
+ GetPrivateProfileString("Setup", "target_version", "",
+ target_version, sizeof(target_version),
+ ini_file);
+
+ GetPrivateProfileString("metadata", "name", "",
+ meta_name, sizeof(meta_name),
+ ini_file);
+
+ GetPrivateProfileString("Setup", "install_script", "",
+ install_script, sizeof(install_script),
+ ini_file);
+
+ GetPrivateProfileString("Setup", "user_access_control", "",
+ user_access_control, sizeof(user_access_control), ini_file);
+
+ // See if we need to do the Vista UAC magic.
+ if (strcmp(user_access_control, "force")==0) {
+ if (PlatformSupportsUAC() && !MyIsUserAnAdmin()) {
+ SpawnUAC();
+ return 0;
+ }
+ // already admin - keep going
+ } else if (strcmp(user_access_control, "auto")==0) {
+ // Check if it looks like we need UAC control, based
+ // on how Python itself was installed.
+ if (PlatformSupportsUAC() && !MyIsUserAnAdmin() && NeedAutoUAC()) {
+ SpawnUAC();
+ return 0;
+ }
+ } else {
+ // display a warning about unknown values - only the developer
+ // of the extension will see it (until they fix it!)
+ if (user_access_control[0] && strcmp(user_access_control, "none") != 0) {
+ MessageBox(GetFocus(), "Bad user_access_control value", "oops", MB_OK);
+ // nothing to do.
+ }
+ }
+
+ hwndMain = CreateBackground(title);
+
+ RunWizard(hwndMain);
+
+ /* Clean up */
+ UnmapViewOfFile(arc_data);
+ if (ini_file)
+ DeleteFile(ini_file);
+
+ if (hBitmap)
+ DeleteObject(hBitmap);
+
+ return 0;
}
/*********************** uninstall section ******************************/
static int compare(const void *p1, const void *p2)
{
- return strcmp(*(char **)p2, *(char **)p1);
+ return strcmp(*(char **)p2, *(char **)p1);
}
/*
@@ -2282,379 +2282,379 @@ static int compare(const void *p1, const void *p2)
*/
void remove_exe(void)
{
- char exename[_MAX_PATH];
- char batname[_MAX_PATH];
- FILE *fp;
- STARTUPINFO si;
- PROCESS_INFORMATION pi;
-
- GetModuleFileName(NULL, exename, sizeof(exename));
- sprintf(batname, "%s.bat", exename);
- fp = fopen(batname, "w");
- fprintf(fp, ":Repeat\n");
- fprintf(fp, "del \"%s\"\n", exename);
- fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
- fprintf(fp, "del \"%s\"\n", batname);
- fclose(fp);
-
- ZeroMemory(&si, sizeof(si));
- si.cb = sizeof(si);
- si.dwFlags = STARTF_USESHOWWINDOW;
- si.wShowWindow = SW_HIDE;
- if (CreateProcess(NULL,
- batname,
- NULL,
- NULL,
- FALSE,
- CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
- NULL,
- "\\",
- &si,
- &pi)) {
- SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
- SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
- SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
- CloseHandle(pi.hProcess);
- ResumeThread(pi.hThread);
- CloseHandle(pi.hThread);
- }
+ char exename[_MAX_PATH];
+ char batname[_MAX_PATH];
+ FILE *fp;
+ STARTUPINFO si;
+ PROCESS_INFORMATION pi;
+
+ GetModuleFileName(NULL, exename, sizeof(exename));
+ sprintf(batname, "%s.bat", exename);
+ fp = fopen(batname, "w");
+ fprintf(fp, ":Repeat\n");
+ fprintf(fp, "del \"%s\"\n", exename);
+ fprintf(fp, "if exist \"%s\" goto Repeat\n", exename);
+ fprintf(fp, "del \"%s\"\n", batname);
+ fclose(fp);
+
+ ZeroMemory(&si, sizeof(si));
+ si.cb = sizeof(si);
+ si.dwFlags = STARTF_USESHOWWINDOW;
+ si.wShowWindow = SW_HIDE;
+ if (CreateProcess(NULL,
+ batname,
+ NULL,
+ NULL,
+ FALSE,
+ CREATE_SUSPENDED | IDLE_PRIORITY_CLASS,
+ NULL,
+ "\\",
+ &si,
+ &pi)) {
+ SetThreadPriority(pi.hThread, THREAD_PRIORITY_IDLE);
+ SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
+ SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS);
+ CloseHandle(pi.hProcess);
+ ResumeThread(pi.hThread);
+ CloseHandle(pi.hThread);
+ }
}
void DeleteRegistryKey(char *string)
{
- char *keyname;
- char *subkeyname;
- char *delim;
- HKEY hKey;
- long result;
- char *line;
-
- line = strdup(string); /* so we can change it */
-
- keyname = strchr(line, '[');
- if (!keyname)
- return;
- ++keyname;
-
- subkeyname = strchr(keyname, ']');
- if (!subkeyname)
- return;
- *subkeyname++='\0';
- delim = strchr(subkeyname, '\n');
- if (delim)
- *delim = '\0';
-
- result = RegOpenKeyEx(hkey_root,
- keyname,
- 0,
- KEY_WRITE,
- &hKey);
-
- if (result != ERROR_SUCCESS)
- MessageBox(GetFocus(), string, "Could not open key", MB_OK);
- else {
- result = RegDeleteKey(hKey, subkeyname);
- if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND)
- MessageBox(GetFocus(), string, "Could not delete key", MB_OK);
- RegCloseKey(hKey);
- }
- free(line);
+ char *keyname;
+ char *subkeyname;
+ char *delim;
+ HKEY hKey;
+ long result;
+ char *line;
+
+ line = strdup(string); /* so we can change it */
+
+ keyname = strchr(line, '[');
+ if (!keyname)
+ return;
+ ++keyname;
+
+ subkeyname = strchr(keyname, ']');
+ if (!subkeyname)
+ return;
+ *subkeyname++='\0';
+ delim = strchr(subkeyname, '\n');
+ if (delim)
+ *delim = '\0';
+
+ result = RegOpenKeyEx(hkey_root,
+ keyname,
+ 0,
+ KEY_WRITE,
+ &hKey);
+
+ if (result != ERROR_SUCCESS)
+ MessageBox(GetFocus(), string, "Could not open key", MB_OK);
+ else {
+ result = RegDeleteKey(hKey, subkeyname);
+ if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND)
+ MessageBox(GetFocus(), string, "Could not delete key", MB_OK);
+ RegCloseKey(hKey);
+ }
+ free(line);
}
void DeleteRegistryValue(char *string)
{
- char *keyname;
- char *valuename;
- char *value;
- HKEY hKey;
- long result;
- char *line;
+ char *keyname;
+ char *valuename;
+ char *value;
+ HKEY hKey;
+ long result;
+ char *line;
- line = strdup(string); /* so we can change it */
+ line = strdup(string); /* so we can change it */
/* Format is 'Reg DB Value: [key]name=value' */
- keyname = strchr(line, '[');
- if (!keyname)
- return;
- ++keyname;
- valuename = strchr(keyname, ']');
- if (!valuename)
- return;
- *valuename++ = '\0';
- value = strchr(valuename, '=');
- if (!value)
- return;
-
- *value++ = '\0';
-
- result = RegOpenKeyEx(hkey_root,
- keyname,
- 0,
- KEY_WRITE,
- &hKey);
- if (result != ERROR_SUCCESS)
- MessageBox(GetFocus(), string, "Could not open key", MB_OK);
- else {
- result = RegDeleteValue(hKey, valuename);
- if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND)
- MessageBox(GetFocus(), string, "Could not delete value", MB_OK);
- RegCloseKey(hKey);
- }
- free(line);
+ keyname = strchr(line, '[');
+ if (!keyname)
+ return;
+ ++keyname;
+ valuename = strchr(keyname, ']');
+ if (!valuename)
+ return;
+ *valuename++ = '\0';
+ value = strchr(valuename, '=');
+ if (!value)
+ return;
+
+ *value++ = '\0';
+
+ result = RegOpenKeyEx(hkey_root,
+ keyname,
+ 0,
+ KEY_WRITE,
+ &hKey);
+ if (result != ERROR_SUCCESS)
+ MessageBox(GetFocus(), string, "Could not open key", MB_OK);
+ else {
+ result = RegDeleteValue(hKey, valuename);
+ if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND)
+ MessageBox(GetFocus(), string, "Could not delete value", MB_OK);
+ RegCloseKey(hKey);
+ }
+ free(line);
}
BOOL MyDeleteFile(char *line)
{
- char *pathname = strchr(line, ':');
- if (!pathname)
- return FALSE;
- ++pathname;
- while (isspace(*pathname))
- ++pathname;
- return DeleteFile(pathname);
+ char *pathname = strchr(line, ':');
+ if (!pathname)
+ return FALSE;
+ ++pathname;
+ while (isspace(*pathname))
+ ++pathname;
+ return DeleteFile(pathname);
}
BOOL MyRemoveDirectory(char *line)
{
- char *pathname = strchr(line, ':');
- if (!pathname)
- return FALSE;
- ++pathname;
- while (isspace(*pathname))
- ++pathname;
- return RemoveDirectory(pathname);
+ char *pathname = strchr(line, ':');
+ if (!pathname)
+ return FALSE;
+ ++pathname;
+ while (isspace(*pathname))
+ ++pathname;
+ return RemoveDirectory(pathname);
}
BOOL Run_RemoveScript(char *line)
{
- char *dllname;
- char *scriptname;
- static char lastscript[MAX_PATH];
+ char *dllname;
+ char *scriptname;
+ static char lastscript[MAX_PATH];
/* Format is 'Run Scripts: [pythondll]scriptname' */
/* XXX Currently, pythondll carries no path!!! */
- dllname = strchr(line, '[');
- if (!dllname)
- return FALSE;
- ++dllname;
- scriptname = strchr(dllname, ']');
- if (!scriptname)
- return FALSE;
- *scriptname++ = '\0';
- /* this function may be called more than one time with the same
- script, only run it one time */
- if (strcmp(lastscript, scriptname)) {
- char *argv[3] = {NULL, "-remove", NULL};
- char *buffer = NULL;
-
- argv[0] = scriptname;
-
- if (0 != run_installscript(scriptname, 2, argv, &buffer))
- fprintf(stderr, "*** Could not run installation script ***");
-
- if (buffer && buffer[0])
- MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK);
- free(buffer);
-
- strcpy(lastscript, scriptname);
- }
- return TRUE;
+ dllname = strchr(line, '[');
+ if (!dllname)
+ return FALSE;
+ ++dllname;
+ scriptname = strchr(dllname, ']');
+ if (!scriptname)
+ return FALSE;
+ *scriptname++ = '\0';
+ /* this function may be called more than one time with the same
+ script, only run it one time */
+ if (strcmp(lastscript, scriptname)) {
+ char *argv[3] = {NULL, "-remove", NULL};
+ char *buffer = NULL;
+
+ argv[0] = scriptname;
+
+ if (0 != run_installscript(scriptname, 2, argv, &buffer))
+ fprintf(stderr, "*** Could not run installation script ***");
+
+ if (buffer && buffer[0])
+ MessageBox(GetFocus(), buffer, "uninstall-script", MB_OK);
+ free(buffer);
+
+ strcpy(lastscript, scriptname);
+ }
+ return TRUE;
}
int DoUninstall(int argc, char **argv)
{
- FILE *logfile;
- char buffer[4096];
- int nLines = 0;
- int i;
- char *cp;
- int nFiles = 0;
- int nDirs = 0;
- int nErrors = 0;
- char **lines;
- int lines_buffer_size = 10;
-
- if (argc != 3) {
- MessageBox(NULL,
- "Wrong number of args",
- NULL,
- MB_OK);
- return 1; /* Error */
- }
- if (strcmp(argv[1], "-u")) {
- MessageBox(NULL,
- "2. arg is not -u",
- NULL,
- MB_OK);
- return 1; /* Error */
- }
-
- logfile = fopen(argv[2], "r");
- if (!logfile) {
- MessageBox(NULL,
- "could not open logfile",
- NULL,
- MB_OK);
- return 1; /* Error */
- }
-
- lines = (char **)malloc(sizeof(char *) * lines_buffer_size);
- if (!lines)
- return SystemError(0, "Out of memory");
-
- /* Read the whole logfile, realloacting the buffer */
- while (fgets(buffer, sizeof(buffer), logfile)) {
- int len = strlen(buffer);
- /* remove trailing white space */
- while (isspace(buffer[len-1]))
- len -= 1;
- buffer[len] = '\0';
- lines[nLines++] = strdup(buffer);
- if (nLines >= lines_buffer_size) {
- lines_buffer_size += 10;
- lines = (char **)realloc(lines,
- sizeof(char *) * lines_buffer_size);
- if (!lines)
- return SystemError(0, "Out of memory");
- }
- }
- fclose(logfile);
-
- /* Sort all the lines, so that highest 3-digit codes are first */
- qsort(&lines[0], nLines, sizeof(char *),
- compare);
-
- if (IDYES != MessageBox(NULL,
- "Are you sure you want to remove\n"
- "this package from your computer?",
- "Please confirm",
- MB_YESNO | MB_ICONQUESTION))
- return 0;
-
- hkey_root = HKEY_LOCAL_MACHINE;
- cp = "";
- for (i = 0; i < nLines; ++i) {
- /* Ignore duplicate lines */
- if (strcmp(cp, lines[i])) {
- int ign;
- cp = lines[i];
- /* Parse the lines */
- if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) {
- if (strcmp(buffer, "HKEY_CURRENT_USER")==0)
- hkey_root = HKEY_CURRENT_USER;
- else {
- // HKLM - check they have permissions.
- if (!HasLocalMachinePrivs()) {
- MessageBox(GetFocus(),
- "You do not seem to have sufficient access rights\n"
- "on this machine to uninstall this software",
- NULL,
- MB_OK | MB_ICONSTOP);
- return 1; /* Error */
- }
- }
- } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) {
- if (MyRemoveDirectory(cp))
- ++nDirs;
- else {
- int code = GetLastError();
- if (code != 2 && code != 3) { /* file or path not found */
- ++nErrors;
- }
- }
- } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) {
- if (MyDeleteFile(cp))
- ++nFiles;
- else {
- int code = GetLastError();
- if (code != 2 && code != 3) { /* file or path not found */
- ++nErrors;
- }
- }
- } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) {
- if (MyDeleteFile(cp))
- ++nFiles;
- else {
- int code = GetLastError();
- if (code != 2 && code != 3) { /* file or path not found */
- ++nErrors;
- }
- }
- } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) {
- DeleteRegistryKey(cp);
- } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) {
- DeleteRegistryValue(cp);
- } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) {
- Run_RemoveScript(cp);
- }
- }
- }
-
- if (DeleteFile(argv[2])) {
- ++nFiles;
- } else {
- ++nErrors;
- SystemError(GetLastError(), argv[2]);
- }
- if (nErrors)
- wsprintf(buffer,
- "%d files and %d directories removed\n"
- "%d files or directories could not be removed",
- nFiles, nDirs, nErrors);
- else
- wsprintf(buffer, "%d files and %d directories removed",
- nFiles, nDirs);
- MessageBox(NULL, buffer, "Uninstall Finished!",
- MB_OK | MB_ICONINFORMATION);
- remove_exe();
- return 0;
+ FILE *logfile;
+ char buffer[4096];
+ int nLines = 0;
+ int i;
+ char *cp;
+ int nFiles = 0;
+ int nDirs = 0;
+ int nErrors = 0;
+ char **lines;
+ int lines_buffer_size = 10;
+
+ if (argc != 3) {
+ MessageBox(NULL,
+ "Wrong number of args",
+ NULL,
+ MB_OK);
+ return 1; /* Error */
+ }
+ if (strcmp(argv[1], "-u")) {
+ MessageBox(NULL,
+ "2. arg is not -u",
+ NULL,
+ MB_OK);
+ return 1; /* Error */
+ }
+
+ logfile = fopen(argv[2], "r");
+ if (!logfile) {
+ MessageBox(NULL,
+ "could not open logfile",
+ NULL,
+ MB_OK);
+ return 1; /* Error */
+ }
+
+ lines = (char **)malloc(sizeof(char *) * lines_buffer_size);
+ if (!lines)
+ return SystemError(0, "Out of memory");
+
+ /* Read the whole logfile, realloacting the buffer */
+ while (fgets(buffer, sizeof(buffer), logfile)) {
+ int len = strlen(buffer);
+ /* remove trailing white space */
+ while (isspace(buffer[len-1]))
+ len -= 1;
+ buffer[len] = '\0';
+ lines[nLines++] = strdup(buffer);
+ if (nLines >= lines_buffer_size) {
+ lines_buffer_size += 10;
+ lines = (char **)realloc(lines,
+ sizeof(char *) * lines_buffer_size);
+ if (!lines)
+ return SystemError(0, "Out of memory");
+ }
+ }
+ fclose(logfile);
+
+ /* Sort all the lines, so that highest 3-digit codes are first */
+ qsort(&lines[0], nLines, sizeof(char *),
+ compare);
+
+ if (IDYES != MessageBox(NULL,
+ "Are you sure you want to remove\n"
+ "this package from your computer?",
+ "Please confirm",
+ MB_YESNO | MB_ICONQUESTION))
+ return 0;
+
+ hkey_root = HKEY_LOCAL_MACHINE;
+ cp = "";
+ for (i = 0; i < nLines; ++i) {
+ /* Ignore duplicate lines */
+ if (strcmp(cp, lines[i])) {
+ int ign;
+ cp = lines[i];
+ /* Parse the lines */
+ if (2 == sscanf(cp, "%d Root Key: %s", &ign, &buffer)) {
+ if (strcmp(buffer, "HKEY_CURRENT_USER")==0)
+ hkey_root = HKEY_CURRENT_USER;
+ else {
+ // HKLM - check they have permissions.
+ if (!HasLocalMachinePrivs()) {
+ MessageBox(GetFocus(),
+ "You do not seem to have sufficient access rights\n"
+ "on this machine to uninstall this software",
+ NULL,
+ MB_OK | MB_ICONSTOP);
+ return 1; /* Error */
+ }
+ }
+ } else if (2 == sscanf(cp, "%d Made Dir: %s", &ign, &buffer)) {
+ if (MyRemoveDirectory(cp))
+ ++nDirs;
+ else {
+ int code = GetLastError();
+ if (code != 2 && code != 3) { /* file or path not found */
+ ++nErrors;
+ }
+ }
+ } else if (2 == sscanf(cp, "%d File Copy: %s", &ign, &buffer)) {
+ if (MyDeleteFile(cp))
+ ++nFiles;
+ else {
+ int code = GetLastError();
+ if (code != 2 && code != 3) { /* file or path not found */
+ ++nErrors;
+ }
+ }
+ } else if (2 == sscanf(cp, "%d File Overwrite: %s", &ign, &buffer)) {
+ if (MyDeleteFile(cp))
+ ++nFiles;
+ else {
+ int code = GetLastError();
+ if (code != 2 && code != 3) { /* file or path not found */
+ ++nErrors;
+ }
+ }
+ } else if (2 == sscanf(cp, "%d Reg DB Key: %s", &ign, &buffer)) {
+ DeleteRegistryKey(cp);
+ } else if (2 == sscanf(cp, "%d Reg DB Value: %s", &ign, &buffer)) {
+ DeleteRegistryValue(cp);
+ } else if (2 == sscanf(cp, "%d Run Script: %s", &ign, &buffer)) {
+ Run_RemoveScript(cp);
+ }
+ }
+ }
+
+ if (DeleteFile(argv[2])) {
+ ++nFiles;
+ } else {
+ ++nErrors;
+ SystemError(GetLastError(), argv[2]);
+ }
+ if (nErrors)
+ wsprintf(buffer,
+ "%d files and %d directories removed\n"
+ "%d files or directories could not be removed",
+ nFiles, nDirs, nErrors);
+ else
+ wsprintf(buffer, "%d files and %d directories removed",
+ nFiles, nDirs);
+ MessageBox(NULL, buffer, "Uninstall Finished!",
+ MB_OK | MB_ICONINFORMATION);
+ remove_exe();
+ return 0;
}
int WINAPI WinMain(HINSTANCE hInst, HINSTANCE hPrevInst,
- LPSTR lpszCmdLine, INT nCmdShow)
+ LPSTR lpszCmdLine, INT nCmdShow)
{
- extern int __argc;
- extern char **__argv;
- char *basename;
-
- GetModuleFileName(NULL, modulename, sizeof(modulename));
-
- /* Map the executable file to memory */
- arc_data = MapExistingFile(modulename, &arc_size);
- if (!arc_data) {
- SystemError(GetLastError(), "Could not open archive");
- return 1;
- }
-
- /* OK. So this program can act as installer (self-extracting
- * zip-file, or as uninstaller when started with '-u logfile'
- * command line flags.
- *
- * The installer is usually started without command line flags,
- * and the uninstaller is usually started with the '-u logfile'
- * flag. What to do if some innocent user double-clicks the
- * exe-file?
- * The following implements a defensive strategy...
- */
-
- /* Try to extract the configuration data into a temporary file */
- if (ExtractInstallData(arc_data, arc_size, &exe_size,
- &ini_file, &pre_install_script))
- return DoInstall();
-
- if (!ini_file && __argc > 1) {
- return DoUninstall(__argc, __argv);
- }
-
-
- basename = strrchr(modulename, '\\');
- if (basename)
- ++basename;
-
- /* Last guess about the purpose of this program */
- if (basename && (0 == strncmp(basename, "Remove", 6)))
- SystemError(0, "This program is normally started by windows");
- else
- SystemError(0, "Setup program invalid or damaged");
- return 1;
+ extern int __argc;
+ extern char **__argv;
+ char *basename;
+
+ GetModuleFileName(NULL, modulename, sizeof(modulename));
+
+ /* Map the executable file to memory */
+ arc_data = MapExistingFile(modulename, &arc_size);
+ if (!arc_data) {
+ SystemError(GetLastError(), "Could not open archive");
+ return 1;
+ }
+
+ /* OK. So this program can act as installer (self-extracting
+ * zip-file, or as uninstaller when started with '-u logfile'
+ * command line flags.
+ *
+ * The installer is usually started without command line flags,
+ * and the uninstaller is usually started with the '-u logfile'
+ * flag. What to do if some innocent user double-clicks the
+ * exe-file?
+ * The following implements a defensive strategy...
+ */
+
+ /* Try to extract the configuration data into a temporary file */
+ if (ExtractInstallData(arc_data, arc_size, &exe_size,
+ &ini_file, &pre_install_script))
+ return DoInstall();
+
+ if (!ini_file && __argc > 1) {
+ return DoUninstall(__argc, __argv);
+ }
+
+
+ basename = strrchr(modulename, '\\');
+ if (basename)
+ ++basename;
+
+ /* Last guess about the purpose of this program */
+ if (basename && (0 == strncmp(basename, "Remove", 6)))
+ SystemError(0, "This program is normally started by windows");
+ else
+ SystemError(0, "Setup program invalid or damaged");
+ return 1;
}
diff --git a/PC/config.c b/PC/config.c
index 41f0573..35c6608 100644
--- a/PC/config.c
+++ b/PC/config.c
@@ -77,94 +77,94 @@ extern void initimp(void);
struct _inittab _PyImport_Inittab[] = {
- {"array", initarray},
- {"_ast", init_ast},
+ {"array", initarray},
+ {"_ast", init_ast},
#ifdef MS_WINDOWS
#ifndef MS_WINI64
- {"audioop", initaudioop},
+ {"audioop", initaudioop},
#endif
#endif
- {"binascii", initbinascii},
- {"cmath", initcmath},
- {"errno", initerrno},
- {"future_builtins", initfuture_builtins},
- {"gc", initgc},
+ {"binascii", initbinascii},
+ {"cmath", initcmath},
+ {"errno", initerrno},
+ {"future_builtins", initfuture_builtins},
+ {"gc", initgc},
#ifndef MS_WINI64
- {"imageop", initimageop},
+ {"imageop", initimageop},
#endif
- {"math", initmath},
- {"_md5", init_md5},
- {"nt", initnt}, /* Use the NT os functions, not posix */
- {"operator", initoperator},
- {"signal", initsignal},
- {"_sha", init_sha},
- {"_sha256", init_sha256},
- {"_sha512", init_sha512},
- {"strop", initstrop},
- {"time", inittime},
+ {"math", initmath},
+ {"_md5", init_md5},
+ {"nt", initnt}, /* Use the NT os functions, not posix */
+ {"operator", initoperator},
+ {"signal", initsignal},
+ {"_sha", init_sha},
+ {"_sha256", init_sha256},
+ {"_sha512", init_sha512},
+ {"strop", initstrop},
+ {"time", inittime},
#ifdef WITH_THREAD
- {"thread", initthread},
+ {"thread", initthread},
#endif
- {"cStringIO", initcStringIO},
- {"cPickle", initcPickle},
+ {"cStringIO", initcStringIO},
+ {"cPickle", initcPickle},
#ifdef WIN32
- {"msvcrt", initmsvcrt},
- {"_locale", init_locale},
+ {"msvcrt", initmsvcrt},
+ {"_locale", init_locale},
#endif
- /* XXX Should _subprocess go in a WIN32 block? not WIN64? */
- {"_subprocess", init_subprocess},
-
- {"_codecs", init_codecs},
- {"_weakref", init_weakref},
- {"_hotshot", init_hotshot},
- {"_random", init_random},
- {"_bisect", init_bisect},
- {"_heapq", init_heapq},
- {"_lsprof", init_lsprof},
- {"itertools", inititertools},
- {"_collections", init_collections},
- {"_symtable", init_symtable},
- {"mmap", initmmap},
- {"_csv", init_csv},
- {"_sre", init_sre},
- {"parser", initparser},
- {"_winreg", init_winreg},
- {"_struct", init_struct},
- {"datetime", initdatetime},
- {"_functools", init_functools},
- {"_json", init_json},
-
- {"xxsubtype", initxxsubtype},
- {"zipimport", initzipimport},
- {"zlib", initzlib},
-
- /* CJK codecs */
- {"_multibytecodec", init_multibytecodec},
- {"_codecs_cn", init_codecs_cn},
- {"_codecs_hk", init_codecs_hk},
- {"_codecs_iso2022", init_codecs_iso2022},
- {"_codecs_jp", init_codecs_jp},
- {"_codecs_kr", init_codecs_kr},
- {"_codecs_tw", init_codecs_tw},
+ /* XXX Should _subprocess go in a WIN32 block? not WIN64? */
+ {"_subprocess", init_subprocess},
+
+ {"_codecs", init_codecs},
+ {"_weakref", init_weakref},
+ {"_hotshot", init_hotshot},
+ {"_random", init_random},
+ {"_bisect", init_bisect},
+ {"_heapq", init_heapq},
+ {"_lsprof", init_lsprof},
+ {"itertools", inititertools},
+ {"_collections", init_collections},
+ {"_symtable", init_symtable},
+ {"mmap", initmmap},
+ {"_csv", init_csv},
+ {"_sre", init_sre},
+ {"parser", initparser},
+ {"_winreg", init_winreg},
+ {"_struct", init_struct},
+ {"datetime", initdatetime},
+ {"_functools", init_functools},
+ {"_json", init_json},
+
+ {"xxsubtype", initxxsubtype},
+ {"zipimport", initzipimport},
+ {"zlib", initzlib},
+
+ /* CJK codecs */
+ {"_multibytecodec", init_multibytecodec},
+ {"_codecs_cn", init_codecs_cn},
+ {"_codecs_hk", init_codecs_hk},
+ {"_codecs_iso2022", init_codecs_iso2022},
+ {"_codecs_jp", init_codecs_jp},
+ {"_codecs_kr", init_codecs_kr},
+ {"_codecs_tw", init_codecs_tw},
/* tools/freeze/makeconfig.py marker for additional "_inittab" entries */
/* -- ADDMODULE MARKER 2 -- */
- /* This module "lives in" with marshal.c */
- {"marshal", PyMarshal_Init},
+ /* This module "lives in" with marshal.c */
+ {"marshal", PyMarshal_Init},
- /* This lives it with import.c */
- {"imp", initimp},
+ /* This lives it with import.c */
+ {"imp", initimp},
- /* These entries are here for sys.builtin_module_names */
- {"__main__", NULL},
- {"__builtin__", NULL},
- {"sys", NULL},
- {"exceptions", NULL},
- {"_warnings", _PyWarnings_Init},
+ /* These entries are here for sys.builtin_module_names */
+ {"__main__", NULL},
+ {"__builtin__", NULL},
+ {"sys", NULL},
+ {"exceptions", NULL},
+ {"_warnings", _PyWarnings_Init},
- {"_io", init_io},
+ {"_io", init_io},
- /* Sentinel */
- {0, 0}
+ /* Sentinel */
+ {0, 0}
};
diff --git a/PC/dl_nt.c b/PC/dl_nt.c
index f8af802..ef1ce09 100644
--- a/PC/dl_nt.c
+++ b/PC/dl_nt.c
@@ -3,7 +3,7 @@
Entry point for the Windows NT DLL.
About the only reason for having this, is so initall() can automatically
-be called, removing that burden (and possible source of frustration if
+be called, removing that burden (and possible source of frustration if
forgotten) from the programmer.
*/
@@ -46,61 +46,61 @@ static PFN_RELEASEACTCTX pfnReleaseActCtx = NULL;
void _LoadActCtxPointers()
{
- HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll");
- if (hKernel32)
- pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx");
- // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest.
- if (pfnGetCurrentActCtx) {
- pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx");
- pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx");
- pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx");
- pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx");
- }
+ HINSTANCE hKernel32 = GetModuleHandleW(L"kernel32.dll");
+ if (hKernel32)
+ pfnGetCurrentActCtx = (PFN_GETCURRENTACTCTX) GetProcAddress(hKernel32, "GetCurrentActCtx");
+ // If we can't load GetCurrentActCtx (ie, pre XP) , don't bother with the rest.
+ if (pfnGetCurrentActCtx) {
+ pfnActivateActCtx = (PFN_ACTIVATEACTCTX) GetProcAddress(hKernel32, "ActivateActCtx");
+ pfnDeactivateActCtx = (PFN_DEACTIVATEACTCTX) GetProcAddress(hKernel32, "DeactivateActCtx");
+ pfnAddRefActCtx = (PFN_ADDREFACTCTX) GetProcAddress(hKernel32, "AddRefActCtx");
+ pfnReleaseActCtx = (PFN_RELEASEACTCTX) GetProcAddress(hKernel32, "ReleaseActCtx");
+ }
}
ULONG_PTR _Py_ActivateActCtx()
{
- ULONG_PTR ret = 0;
- if (PyWin_DLLhActivationContext && pfnActivateActCtx)
- if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) {
- OutputDebugString("Python failed to activate the activation context before loading a DLL\n");
- ret = 0; // no promise the failing function didn't change it!
- }
- return ret;
+ ULONG_PTR ret = 0;
+ if (PyWin_DLLhActivationContext && pfnActivateActCtx)
+ if (!(*pfnActivateActCtx)(PyWin_DLLhActivationContext, &ret)) {
+ OutputDebugString("Python failed to activate the activation context before loading a DLL\n");
+ ret = 0; // no promise the failing function didn't change it!
+ }
+ return ret;
}
void _Py_DeactivateActCtx(ULONG_PTR cookie)
{
- if (cookie && pfnDeactivateActCtx)
- if (!(*pfnDeactivateActCtx)(0, cookie))
- OutputDebugString("Python failed to de-activate the activation context\n");
+ if (cookie && pfnDeactivateActCtx)
+ if (!(*pfnDeactivateActCtx)(0, cookie))
+ OutputDebugString("Python failed to de-activate the activation context\n");
}
-BOOL WINAPI DllMain (HANDLE hInst,
- ULONG ul_reason_for_call,
- LPVOID lpReserved)
+BOOL WINAPI DllMain (HANDLE hInst,
+ ULONG ul_reason_for_call,
+ LPVOID lpReserved)
{
- switch (ul_reason_for_call)
- {
- case DLL_PROCESS_ATTACH:
- PyWin_DLLhModule = hInst;
- // 1000 is a magic number I picked out of the air. Could do with a #define, I spose...
- LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer));
-
- // and capture our activation context for use when loading extensions.
- _LoadActCtxPointers();
- if (pfnGetCurrentActCtx && pfnAddRefActCtx)
- if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext))
- if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext))
- OutputDebugString("Python failed to load the default activation context\n");
- break;
-
- case DLL_PROCESS_DETACH:
- if (pfnReleaseActCtx)
- (*pfnReleaseActCtx)(PyWin_DLLhActivationContext);
- break;
- }
- return TRUE;
+ switch (ul_reason_for_call)
+ {
+ case DLL_PROCESS_ATTACH:
+ PyWin_DLLhModule = hInst;
+ // 1000 is a magic number I picked out of the air. Could do with a #define, I spose...
+ LoadString(hInst, 1000, dllVersionBuffer, sizeof(dllVersionBuffer));
+
+ // and capture our activation context for use when loading extensions.
+ _LoadActCtxPointers();
+ if (pfnGetCurrentActCtx && pfnAddRefActCtx)
+ if ((*pfnGetCurrentActCtx)(&PyWin_DLLhActivationContext))
+ if (!(*pfnAddRefActCtx)(PyWin_DLLhActivationContext))
+ OutputDebugString("Python failed to load the default activation context\n");
+ break;
+
+ case DLL_PROCESS_DETACH:
+ if (pfnReleaseActCtx)
+ (*pfnReleaseActCtx)(PyWin_DLLhActivationContext);
+ break;
+ }
+ return TRUE;
}
#endif /* Py_ENABLE_SHARED */
diff --git a/PC/errmap.h b/PC/errmap.h
index 59aeea1..d225aa4 100644
--- a/PC/errmap.h
+++ b/PC/errmap.h
@@ -1,78 +1,78 @@
/* Generated file. Do not edit. */
int winerror_to_errno(int winerror)
{
- switch(winerror) {
- case 2: return 2;
- case 3: return 2;
- case 4: return 24;
- case 5: return 13;
- case 6: return 9;
- case 7: return 12;
- case 8: return 12;
- case 9: return 12;
- case 10: return 7;
- case 11: return 8;
- case 15: return 2;
- case 16: return 13;
- case 17: return 18;
- case 18: return 2;
- case 19: return 13;
- case 20: return 13;
- case 21: return 13;
- case 22: return 13;
- case 23: return 13;
- case 24: return 13;
- case 25: return 13;
- case 26: return 13;
- case 27: return 13;
- case 28: return 13;
- case 29: return 13;
- case 30: return 13;
- case 31: return 13;
- case 32: return 13;
- case 33: return 13;
- case 34: return 13;
- case 35: return 13;
- case 36: return 13;
- case 53: return 2;
- case 65: return 13;
- case 67: return 2;
- case 80: return 17;
- case 82: return 13;
- case 83: return 13;
- case 89: return 11;
- case 108: return 13;
- case 109: return 32;
- case 112: return 28;
- case 114: return 9;
- case 128: return 10;
- case 129: return 10;
- case 130: return 9;
- case 132: return 13;
- case 145: return 41;
- case 158: return 13;
- case 161: return 2;
- case 164: return 11;
- case 167: return 13;
- case 183: return 17;
- case 188: return 8;
- case 189: return 8;
- case 190: return 8;
- case 191: return 8;
- case 192: return 8;
- case 193: return 8;
- case 194: return 8;
- case 195: return 8;
- case 196: return 8;
- case 197: return 8;
- case 198: return 8;
- case 199: return 8;
- case 200: return 8;
- case 201: return 8;
- case 202: return 8;
- case 206: return 2;
- case 215: return 11;
- case 1816: return 12;
- default: return EINVAL;
- }
+ switch(winerror) {
+ case 2: return 2;
+ case 3: return 2;
+ case 4: return 24;
+ case 5: return 13;
+ case 6: return 9;
+ case 7: return 12;
+ case 8: return 12;
+ case 9: return 12;
+ case 10: return 7;
+ case 11: return 8;
+ case 15: return 2;
+ case 16: return 13;
+ case 17: return 18;
+ case 18: return 2;
+ case 19: return 13;
+ case 20: return 13;
+ case 21: return 13;
+ case 22: return 13;
+ case 23: return 13;
+ case 24: return 13;
+ case 25: return 13;
+ case 26: return 13;
+ case 27: return 13;
+ case 28: return 13;
+ case 29: return 13;
+ case 30: return 13;
+ case 31: return 13;
+ case 32: return 13;
+ case 33: return 13;
+ case 34: return 13;
+ case 35: return 13;
+ case 36: return 13;
+ case 53: return 2;
+ case 65: return 13;
+ case 67: return 2;
+ case 80: return 17;
+ case 82: return 13;
+ case 83: return 13;
+ case 89: return 11;
+ case 108: return 13;
+ case 109: return 32;
+ case 112: return 28;
+ case 114: return 9;
+ case 128: return 10;
+ case 129: return 10;
+ case 130: return 9;
+ case 132: return 13;
+ case 145: return 41;
+ case 158: return 13;
+ case 161: return 2;
+ case 164: return 11;
+ case 167: return 13;
+ case 183: return 17;
+ case 188: return 8;
+ case 189: return 8;
+ case 190: return 8;
+ case 191: return 8;
+ case 192: return 8;
+ case 193: return 8;
+ case 194: return 8;
+ case 195: return 8;
+ case 196: return 8;
+ case 197: return 8;
+ case 198: return 8;
+ case 199: return 8;
+ case 200: return 8;
+ case 201: return 8;
+ case 202: return 8;
+ case 206: return 2;
+ case 215: return 11;
+ case 1816: return 12;
+ default: return EINVAL;
+ }
}
diff --git a/PC/frozen_dllmain.c b/PC/frozen_dllmain.c
index fbb4713..a8cc885 100644
--- a/PC/frozen_dllmain.c
+++ b/PC/frozen_dllmain.c
@@ -9,7 +9,7 @@ a frozen application, this DLLMain symbol exists multiple times.
The solution is:
* Each module checks for a frozen build, and if so, defines its DLLMain
- function as "__declspec(dllexport) DllMain%module%"
+ function as "__declspec(dllexport) DllMain%module%"
(eg, DllMainpythoncom, or DllMainpywintypes)
* The frozen .EXE/.DLL links against this module, which provides
@@ -47,10 +47,10 @@ changed, here is a snippet from the pythoncom extension module.
#include "windows.h"
static char *possibleModules[] = {
- "pywintypes",
- "pythoncom",
- "win32ui",
- NULL,
+ "pywintypes",
+ "pythoncom",
+ "win32ui",
+ NULL,
};
BOOL CallModuleDllMain(char *modName, DWORD dwReason);
@@ -62,73 +62,73 @@ BOOL CallModuleDllMain(char *modName, DWORD dwReason);
*/
void PyWinFreeze_ExeInit(void)
{
- char **modName;
- for (modName = possibleModules;*modName;*modName++) {
-/* printf("Initialising '%s'\n", *modName); */
- CallModuleDllMain(*modName, DLL_PROCESS_ATTACH);
- }
+ char **modName;
+ for (modName = possibleModules;*modName;*modName++) {
+/* printf("Initialising '%s'\n", *modName); */
+ CallModuleDllMain(*modName, DLL_PROCESS_ATTACH);
+ }
}
/*
Called by a frozen .EXE only, so that built-in extension
- modules are cleaned up
+ modules are cleaned up
*/
void PyWinFreeze_ExeTerm(void)
{
- // Must go backwards
- char **modName;
- for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2;
- modName >= possibleModules;
- *modName--) {
-/* printf("Terminating '%s'\n", *modName);*/
- CallModuleDllMain(*modName, DLL_PROCESS_DETACH);
- }
+ // Must go backwards
+ char **modName;
+ for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2;
+ modName >= possibleModules;
+ *modName--) {
+/* printf("Terminating '%s'\n", *modName);*/
+ CallModuleDllMain(*modName, DLL_PROCESS_DETACH);
+ }
}
BOOL WINAPI DllMain(HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved)
{
- BOOL ret = TRUE;
- switch (dwReason) {
- case DLL_PROCESS_ATTACH:
- {
- char **modName;
- for (modName = possibleModules;*modName;*modName++) {
- BOOL ok = CallModuleDllMain(*modName, dwReason);
- if (!ok)
- ret = FALSE;
- }
- break;
- }
- case DLL_PROCESS_DETACH:
- {
- // Must go backwards
- char **modName;
- for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2;
- modName >= possibleModules;
- *modName--)
- CallModuleDllMain(*modName, DLL_PROCESS_DETACH);
- break;
- }
- }
- return ret;
+ BOOL ret = TRUE;
+ switch (dwReason) {
+ case DLL_PROCESS_ATTACH:
+ {
+ char **modName;
+ for (modName = possibleModules;*modName;*modName++) {
+ BOOL ok = CallModuleDllMain(*modName, dwReason);
+ if (!ok)
+ ret = FALSE;
+ }
+ break;
+ }
+ case DLL_PROCESS_DETACH:
+ {
+ // Must go backwards
+ char **modName;
+ for (modName = possibleModules+(sizeof(possibleModules) / sizeof(char *))-2;
+ modName >= possibleModules;
+ *modName--)
+ CallModuleDllMain(*modName, DLL_PROCESS_DETACH);
+ break;
+ }
+ }
+ return ret;
}
BOOL CallModuleDllMain(char *modName, DWORD dwReason)
{
- BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID);
-
- char funcName[255];
- HMODULE hmod = GetModuleHandle(NULL);
- strcpy(funcName, "_DllMain");
- strcat(funcName, modName);
- strcat(funcName, "@12"); // stdcall convention.
- pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName);
- if (pfndllmain==NULL) {
- /* No function by that name exported - then that module does
- not appear in our frozen program - return OK
- */
- return TRUE;
- }
- return (*pfndllmain)(hmod, dwReason, NULL);
+ BOOL (WINAPI * pfndllmain)(HINSTANCE, DWORD, LPVOID);
+
+ char funcName[255];
+ HMODULE hmod = GetModuleHandle(NULL);
+ strcpy(funcName, "_DllMain");
+ strcat(funcName, modName);
+ strcat(funcName, "@12"); // stdcall convention.
+ pfndllmain = (BOOL (WINAPI *)(HINSTANCE, DWORD, LPVOID))GetProcAddress(hmod, funcName);
+ if (pfndllmain==NULL) {
+ /* No function by that name exported - then that module does
+ not appear in our frozen program - return OK
+ */
+ return TRUE;
+ }
+ return (*pfndllmain)(hmod, dwReason, NULL);
}
diff --git a/PC/generrmap.c b/PC/generrmap.c
index 2b25063..bf1081b 100644
--- a/PC/generrmap.c
+++ b/PC/generrmap.c
@@ -5,16 +5,16 @@
int main()
{
- int i;
- printf("/* Generated file. Do not edit. */\n");
- printf("int winerror_to_errno(int winerror)\n");
- printf("{\n\tswitch(winerror) {\n");
- for(i=1; i < 65000; i++) {
- _dosmaperr(i);
- if (errno == EINVAL)
- continue;
- printf("\t\tcase %d: return %d;\n", i, errno);
- }
- printf("\t\tdefault: return EINVAL;\n");
- printf("\t}\n}\n");
+ int i;
+ printf("/* Generated file. Do not edit. */\n");
+ printf("int winerror_to_errno(int winerror)\n");
+ printf("{\n\tswitch(winerror) {\n");
+ for(i=1; i < 65000; i++) {
+ _dosmaperr(i);
+ if (errno == EINVAL)
+ continue;
+ printf("\t\tcase %d: return %d;\n", i, errno);
+ }
+ printf("\t\tdefault: return EINVAL;\n");
+ printf("\t}\n}\n");
}
diff --git a/PC/getpathp.c b/PC/getpathp.c
index 78f4465..461f9fc 100644
--- a/PC/getpathp.c
+++ b/PC/getpathp.c
@@ -4,8 +4,8 @@
/* ----------------------------------------------------------------
PATH RULES FOR WINDOWS:
- This describes how sys.path is formed on Windows. It describes the
- functionality, not the implementation (ie, the order in which these
+ This describes how sys.path is formed on Windows. It describes the
+ functionality, not the implementation (ie, the order in which these
are actually fetched is different)
* Python always adds an empty entry at the start, which corresponds
@@ -24,15 +24,15 @@
* We attempt to locate the "Python Home" - if the PYTHONHOME env var
is set, we believe it. Otherwise, we use the path of our host .EXE's
to try and locate our "landmark" (lib\\os.py) and deduce our home.
- - If we DO have a Python Home: The relevant sub-directories (Lib,
+ - If we DO have a Python Home: The relevant sub-directories (Lib,
plat-win, lib-tk, etc) are based on the Python Home
- If we DO NOT have a Python Home, the core Python Path is
- loaded from the registry. This is the main PythonPath key,
+ loaded from the registry. This is the main PythonPath key,
and both HKLM and HKCU are combined to form the path)
* Iff - we can not locate the Python Home, have not had a PYTHONPATH
specified, and can't locate any Registry entries (ie, we have _nothing_
- we can assume is a good path), a default path with relative entries is
+ we can assume is a good path), a default path with relative entries is
used (eg. .\Lib;.\plat-win, etc)
@@ -42,9 +42,9 @@
the core path is deduced, and the core paths in the registry are
ignored. Other "application paths" in the registry are always read.
- * When Python is hosted in another exe (different directory, embedded via
+ * When Python is hosted in another exe (different directory, embedded via
COM, etc), the Python Home will not be deduced, so the core path from
- the registry is used. Other "application paths" in the registry are
+ the registry is used. Other "application paths" in the registry are
always read.
* If Python can't find its home and there is no registry (eg, frozen
@@ -92,12 +92,12 @@ static char *module_search_path = NULL;
static int
-is_sep(char ch) /* determine if "ch" is a separator character */
+is_sep(char ch) /* determine if "ch" is a separator character */
{
#ifdef ALTSEP
- return ch == SEP || ch == ALTSEP;
+ return ch == SEP || ch == ALTSEP;
#else
- return ch == SEP;
+ return ch == SEP;
#endif
}
@@ -107,36 +107,36 @@ is_sep(char ch) /* determine if "ch" is a separator character */
static void
reduce(char *dir)
{
- size_t i = strlen(dir);
- while (i > 0 && !is_sep(dir[i]))
- --i;
- dir[i] = '\0';
+ size_t i = strlen(dir);
+ while (i > 0 && !is_sep(dir[i]))
+ --i;
+ dir[i] = '\0';
}
-
+
static int
exists(char *filename)
{
- struct stat buf;
- return stat(filename, &buf) == 0;
+ struct stat buf;
+ return stat(filename, &buf) == 0;
}
-/* Assumes 'filename' MAXPATHLEN+1 bytes long -
+/* Assumes 'filename' MAXPATHLEN+1 bytes long -
may extend 'filename' by one character.
*/
static int
-ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */
+ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */
{
- if (exists(filename))
- return 1;
-
- /* Check for the compiled version of prefix. */
- if (strlen(filename) < MAXPATHLEN) {
- strcat(filename, Py_OptimizeFlag ? "o" : "c");
- if (exists(filename))
- return 1;
- }
- return 0;
+ if (exists(filename))
+ return 1;
+
+ /* Check for the compiled version of prefix. */
+ if (strlen(filename) < MAXPATHLEN) {
+ strcat(filename, Py_OptimizeFlag ? "o" : "c");
+ if (exists(filename))
+ return 1;
+ }
+ return 0;
}
/* Add a path component, by appending stuff to buffer.
@@ -151,21 +151,21 @@ ismodule(char *filename) /* Is module -- check for .pyc/.pyo too */
static void
join(char *buffer, char *stuff)
{
- size_t n, k;
- if (is_sep(stuff[0]))
- n = 0;
- else {
- n = strlen(buffer);
- if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
- buffer[n++] = SEP;
- }
- if (n > MAXPATHLEN)
- Py_FatalError("buffer overflow in getpathp.c's joinpath()");
- k = strlen(stuff);
- if (n + k > MAXPATHLEN)
- k = MAXPATHLEN - n;
- strncpy(buffer+n, stuff, k);
- buffer[n+k] = '\0';
+ size_t n, k;
+ if (is_sep(stuff[0]))
+ n = 0;
+ else {
+ n = strlen(buffer);
+ if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
+ buffer[n++] = SEP;
+ }
+ if (n > MAXPATHLEN)
+ Py_FatalError("buffer overflow in getpathp.c's joinpath()");
+ k = strlen(stuff);
+ if (n + k > MAXPATHLEN)
+ k = MAXPATHLEN - n;
+ strncpy(buffer+n, stuff, k);
+ buffer[n+k] = '\0';
}
/* gotlandmark only called by search_for_prefix, which ensures
@@ -175,29 +175,29 @@ join(char *buffer, char *stuff)
static int
gotlandmark(char *landmark)
{
- int ok;
- Py_ssize_t n;
-
- n = strlen(prefix);
- join(prefix, landmark);
- ok = ismodule(prefix);
- prefix[n] = '\0';
- return ok;
+ int ok;
+ Py_ssize_t n;
+
+ n = strlen(prefix);
+ join(prefix, landmark);
+ ok = ismodule(prefix);
+ prefix[n] = '\0';
+ return ok;
}
-/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
+/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
assumption provided by only caller, calculate_path() */
static int
search_for_prefix(char *argv0_path, char *landmark)
{
- /* Search from argv0_path, until landmark is found */
- strcpy(prefix, argv0_path);
- do {
- if (gotlandmark(landmark))
- return 1;
- reduce(prefix);
- } while (prefix[0]);
- return 0;
+ /* Search from argv0_path, until landmark is found */
+ strcpy(prefix, argv0_path);
+ do {
+ if (gotlandmark(landmark))
+ return 1;
+ reduce(prefix);
+ } while (prefix[0]);
+ return 0;
}
#ifdef MS_WINDOWS
@@ -223,146 +223,146 @@ extern const char *PyWin_DLLVersionString;
static char *
getpythonregpath(HKEY keyBase, int skipcore)
{
- HKEY newKey = 0;
- DWORD dataSize = 0;
- DWORD numKeys = 0;
- LONG rc;
- char *retval = NULL;
- TCHAR *dataBuf = NULL;
- static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\");
- static const TCHAR keySuffix[] = _T("\\PythonPath");
- size_t versionLen;
- DWORD index;
- TCHAR *keyBuf = NULL;
- TCHAR *keyBufPtr;
- TCHAR **ppPaths = NULL;
-
- /* Tried to use sysget("winver") but here is too early :-( */
- versionLen = _tcslen(PyWin_DLLVersionString);
- /* Space for all the chars, plus one \0 */
- keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) +
- sizeof(TCHAR)*(versionLen-1) +
- sizeof(keySuffix));
- if (keyBuf==NULL) goto done;
-
- memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR));
- keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1;
- memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR));
- keyBufPtr += versionLen;
- /* NULL comes with this one! */
- memcpy(keyBufPtr, keySuffix, sizeof(keySuffix));
- /* Open the root Python key */
- rc=RegOpenKeyEx(keyBase,
- keyBuf, /* subkey */
- 0, /* reserved */
- KEY_READ,
- &newKey);
- if (rc!=ERROR_SUCCESS) goto done;
- /* Find out how big our core buffer is, and how many subkeys we have */
- rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL,
- NULL, NULL, &dataSize, NULL, NULL);
- if (rc!=ERROR_SUCCESS) goto done;
- if (skipcore) dataSize = 0; /* Only count core ones if we want them! */
- /* Allocate a temp array of char buffers, so we only need to loop
- reading the registry once
- */
- ppPaths = malloc( sizeof(TCHAR *) * numKeys );
- if (ppPaths==NULL) goto done;
- memset(ppPaths, 0, sizeof(TCHAR *) * numKeys);
- /* Loop over all subkeys, allocating a temp sub-buffer. */
- for(index=0;index<numKeys;index++) {
- TCHAR keyBuf[MAX_PATH+1];
- HKEY subKey = 0;
- DWORD reqdSize = MAX_PATH+1;
- /* Get the sub-key name */
- DWORD rc = RegEnumKeyEx(newKey, index, keyBuf, &reqdSize,
- NULL, NULL, NULL, NULL );
- if (rc!=ERROR_SUCCESS) goto done;
- /* Open the sub-key */
- rc=RegOpenKeyEx(newKey,
- keyBuf, /* subkey */
- 0, /* reserved */
- KEY_READ,
- &subKey);
- if (rc!=ERROR_SUCCESS) goto done;
- /* Find the value of the buffer size, malloc, then read it */
- RegQueryValueEx(subKey, NULL, 0, NULL, NULL, &reqdSize);
- if (reqdSize) {
- ppPaths[index] = malloc(reqdSize);
- if (ppPaths[index]) {
- RegQueryValueEx(subKey, NULL, 0, NULL,
- (LPBYTE)ppPaths[index],
- &reqdSize);
- dataSize += reqdSize + 1; /* 1 for the ";" */
- }
- }
- RegCloseKey(subKey);
- }
-
- /* return null if no path to return */
- if (dataSize == 0) goto done;
-
- /* original datasize from RegQueryInfo doesn't include the \0 */
- dataBuf = malloc((dataSize+1) * sizeof(TCHAR));
- if (dataBuf) {
- TCHAR *szCur = dataBuf;
- DWORD reqdSize = dataSize;
- /* Copy our collected strings */
- for (index=0;index<numKeys;index++) {
- if (index > 0) {
- *(szCur++) = _T(';');
- dataSize--;
- }
- if (ppPaths[index]) {
- Py_ssize_t len = _tcslen(ppPaths[index]);
- _tcsncpy(szCur, ppPaths[index], len);
- szCur += len;
- assert(dataSize > (DWORD)len);
- dataSize -= (DWORD)len;
- }
- }
- if (skipcore)
- *szCur = '\0';
- else {
- /* If we have no values, we dont need a ';' */
- if (numKeys) {
- *(szCur++) = _T(';');
- dataSize--;
- }
- /* Now append the core path entries -
- this will include the NULL
- */
- rc = RegQueryValueEx(newKey, NULL, 0, NULL,
- (LPBYTE)szCur, &dataSize);
- }
- /* And set the result - caller must free
- If MBCS, it is fine as is. If Unicode, allocate new
- buffer and convert.
- */
+ HKEY newKey = 0;
+ DWORD dataSize = 0;
+ DWORD numKeys = 0;
+ LONG rc;
+ char *retval = NULL;
+ TCHAR *dataBuf = NULL;
+ static const TCHAR keyPrefix[] = _T("Software\\Python\\PythonCore\\");
+ static const TCHAR keySuffix[] = _T("\\PythonPath");
+ size_t versionLen;
+ DWORD index;
+ TCHAR *keyBuf = NULL;
+ TCHAR *keyBufPtr;
+ TCHAR **ppPaths = NULL;
+
+ /* Tried to use sysget("winver") but here is too early :-( */
+ versionLen = _tcslen(PyWin_DLLVersionString);
+ /* Space for all the chars, plus one \0 */
+ keyBuf = keyBufPtr = malloc(sizeof(keyPrefix) +
+ sizeof(TCHAR)*(versionLen-1) +
+ sizeof(keySuffix));
+ if (keyBuf==NULL) goto done;
+
+ memcpy(keyBufPtr, keyPrefix, sizeof(keyPrefix)-sizeof(TCHAR));
+ keyBufPtr += sizeof(keyPrefix)/sizeof(TCHAR) - 1;
+ memcpy(keyBufPtr, PyWin_DLLVersionString, versionLen * sizeof(TCHAR));
+ keyBufPtr += versionLen;
+ /* NULL comes with this one! */
+ memcpy(keyBufPtr, keySuffix, sizeof(keySuffix));
+ /* Open the root Python key */
+ rc=RegOpenKeyEx(keyBase,
+ keyBuf, /* subkey */
+ 0, /* reserved */
+ KEY_READ,
+ &newKey);
+ if (rc!=ERROR_SUCCESS) goto done;
+ /* Find out how big our core buffer is, and how many subkeys we have */
+ rc = RegQueryInfoKey(newKey, NULL, NULL, NULL, &numKeys, NULL, NULL,
+ NULL, NULL, &dataSize, NULL, NULL);
+ if (rc!=ERROR_SUCCESS) goto done;
+ if (skipcore) dataSize = 0; /* Only count core ones if we want them! */
+ /* Allocate a temp array of char buffers, so we only need to loop
+ reading the registry once
+ */
+ ppPaths = malloc( sizeof(TCHAR *) * numKeys );
+ if (ppPaths==NULL) goto done;
+ memset(ppPaths, 0, sizeof(TCHAR *) * numKeys);
+ /* Loop over all subkeys, allocating a temp sub-buffer. */
+ for(index=0;index<numKeys;index++) {
+ TCHAR keyBuf[MAX_PATH+1];
+ HKEY subKey = 0;
+ DWORD reqdSize = MAX_PATH+1;
+ /* Get the sub-key name */
+ DWORD rc = RegEnumKeyEx(newKey, index, keyBuf, &reqdSize,
+ NULL, NULL, NULL, NULL );
+ if (rc!=ERROR_SUCCESS) goto done;
+ /* Open the sub-key */
+ rc=RegOpenKeyEx(newKey,
+ keyBuf, /* subkey */
+ 0, /* reserved */
+ KEY_READ,
+ &subKey);
+ if (rc!=ERROR_SUCCESS) goto done;
+ /* Find the value of the buffer size, malloc, then read it */
+ RegQueryValueEx(subKey, NULL, 0, NULL, NULL, &reqdSize);
+ if (reqdSize) {
+ ppPaths[index] = malloc(reqdSize);
+ if (ppPaths[index]) {
+ RegQueryValueEx(subKey, NULL, 0, NULL,
+ (LPBYTE)ppPaths[index],
+ &reqdSize);
+ dataSize += reqdSize + 1; /* 1 for the ";" */
+ }
+ }
+ RegCloseKey(subKey);
+ }
+
+ /* return null if no path to return */
+ if (dataSize == 0) goto done;
+
+ /* original datasize from RegQueryInfo doesn't include the \0 */
+ dataBuf = malloc((dataSize+1) * sizeof(TCHAR));
+ if (dataBuf) {
+ TCHAR *szCur = dataBuf;
+ DWORD reqdSize = dataSize;
+ /* Copy our collected strings */
+ for (index=0;index<numKeys;index++) {
+ if (index > 0) {
+ *(szCur++) = _T(';');
+ dataSize--;
+ }
+ if (ppPaths[index]) {
+ Py_ssize_t len = _tcslen(ppPaths[index]);
+ _tcsncpy(szCur, ppPaths[index], len);
+ szCur += len;
+ assert(dataSize > (DWORD)len);
+ dataSize -= (DWORD)len;
+ }
+ }
+ if (skipcore)
+ *szCur = '\0';
+ else {
+ /* If we have no values, we dont need a ';' */
+ if (numKeys) {
+ *(szCur++) = _T(';');
+ dataSize--;
+ }
+ /* Now append the core path entries -
+ this will include the NULL
+ */
+ rc = RegQueryValueEx(newKey, NULL, 0, NULL,
+ (LPBYTE)szCur, &dataSize);
+ }
+ /* And set the result - caller must free
+ If MBCS, it is fine as is. If Unicode, allocate new
+ buffer and convert.
+ */
#ifdef UNICODE
- retval = (char *)malloc(reqdSize+1);
- if (retval)
- WideCharToMultiByte(CP_ACP, 0,
- dataBuf, -1, /* source */
- retval, reqdSize+1, /* dest */
- NULL, NULL);
- free(dataBuf);
+ retval = (char *)malloc(reqdSize+1);
+ if (retval)
+ WideCharToMultiByte(CP_ACP, 0,
+ dataBuf, -1, /* source */
+ retval, reqdSize+1, /* dest */
+ NULL, NULL);
+ free(dataBuf);
#else
- retval = dataBuf;
+ retval = dataBuf;
#endif
- }
+ }
done:
- /* Loop freeing my temp buffers */
- if (ppPaths) {
- for(index=0;index<numKeys;index++)
- if (ppPaths[index]) free(ppPaths[index]);
- free(ppPaths);
- }
- if (newKey)
- RegCloseKey(newKey);
- if (keyBuf)
- free(keyBuf);
- return retval;
+ /* Loop freeing my temp buffers */
+ if (ppPaths) {
+ for(index=0;index<numKeys;index++)
+ if (ppPaths[index]) free(ppPaths[index]);
+ free(ppPaths);
+ }
+ if (newKey)
+ RegCloseKey(newKey);
+ if (keyBuf)
+ free(keyBuf);
+ return retval;
}
#endif /* Py_ENABLE_SHARED */
#endif /* MS_WINDOWS */
@@ -370,314 +370,314 @@ done:
static void
get_progpath(void)
{
- extern char *Py_GetProgramName(void);
- char *path = getenv("PATH");
- char *prog = Py_GetProgramName();
+ extern char *Py_GetProgramName(void);
+ char *path = getenv("PATH");
+ char *prog = Py_GetProgramName();
#ifdef MS_WINDOWS
- extern HANDLE PyWin_DLLhModule;
+ extern HANDLE PyWin_DLLhModule;
#ifdef UNICODE
- WCHAR wprogpath[MAXPATHLEN+1];
- /* Windows documents that GetModuleFileName() will "truncate",
- but makes no mention of the null terminator. Play it safe.
- PLUS Windows itself defines MAX_PATH as the same, but anyway...
- */
+ WCHAR wprogpath[MAXPATHLEN+1];
+ /* Windows documents that GetModuleFileName() will "truncate",
+ but makes no mention of the null terminator. Play it safe.
+ PLUS Windows itself defines MAX_PATH as the same, but anyway...
+ */
#ifdef Py_ENABLE_SHARED
- wprogpath[MAXPATHLEN]=_T('\0');
- if (PyWin_DLLhModule &&
- GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) {
- WideCharToMultiByte(CP_ACP, 0,
- wprogpath, -1,
- dllpath, MAXPATHLEN+1,
- NULL, NULL);
- }
+ wprogpath[MAXPATHLEN]=_T('\0');
+ if (PyWin_DLLhModule &&
+ GetModuleFileName(PyWin_DLLhModule, wprogpath, MAXPATHLEN)) {
+ WideCharToMultiByte(CP_ACP, 0,
+ wprogpath, -1,
+ dllpath, MAXPATHLEN+1,
+ NULL, NULL);
+ }
#else
- dllpath[0] = 0;
+ dllpath[0] = 0;
#endif
- wprogpath[MAXPATHLEN]=_T('\0');
- if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) {
- WideCharToMultiByte(CP_ACP, 0,
- wprogpath, -1,
- progpath, MAXPATHLEN+1,
- NULL, NULL);
- return;
- }
+ wprogpath[MAXPATHLEN]=_T('\0');
+ if (GetModuleFileName(NULL, wprogpath, MAXPATHLEN)) {
+ WideCharToMultiByte(CP_ACP, 0,
+ wprogpath, -1,
+ progpath, MAXPATHLEN+1,
+ NULL, NULL);
+ return;
+ }
#else
- /* static init of progpath ensures final char remains \0 */
+ /* static init of progpath ensures final char remains \0 */
#ifdef Py_ENABLE_SHARED
- if (PyWin_DLLhModule)
- if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN))
- dllpath[0] = 0;
+ if (PyWin_DLLhModule)
+ if (!GetModuleFileName(PyWin_DLLhModule, dllpath, MAXPATHLEN))
+ dllpath[0] = 0;
#else
- dllpath[0] = 0;
+ dllpath[0] = 0;
#endif
- if (GetModuleFileName(NULL, progpath, MAXPATHLEN))
- return;
+ if (GetModuleFileName(NULL, progpath, MAXPATHLEN))
+ return;
#endif
#endif
- if (prog == NULL || *prog == '\0')
- prog = "python";
-
- /* If there is no slash in the argv0 path, then we have to
- * assume python is on the user's $PATH, since there's no
- * other way to find a directory to start the search from. If
- * $PATH isn't exported, you lose.
- */
+ if (prog == NULL || *prog == '\0')
+ prog = "python";
+
+ /* If there is no slash in the argv0 path, then we have to
+ * assume python is on the user's $PATH, since there's no
+ * other way to find a directory to start the search from. If
+ * $PATH isn't exported, you lose.
+ */
#ifdef ALTSEP
- if (strchr(prog, SEP) || strchr(prog, ALTSEP))
+ if (strchr(prog, SEP) || strchr(prog, ALTSEP))
#else
- if (strchr(prog, SEP))
+ if (strchr(prog, SEP))
#endif
- strncpy(progpath, prog, MAXPATHLEN);
- else if (path) {
- while (1) {
- char *delim = strchr(path, DELIM);
-
- if (delim) {
- size_t len = delim - path;
- /* ensure we can't overwrite buffer */
- len = min(MAXPATHLEN,len);
- strncpy(progpath, path, len);
- *(progpath + len) = '\0';
- }
- else
- strncpy(progpath, path, MAXPATHLEN);
-
- /* join() is safe for MAXPATHLEN+1 size buffer */
- join(progpath, prog);
- if (exists(progpath))
- break;
-
- if (!delim) {
- progpath[0] = '\0';
- break;
- }
- path = delim + 1;
- }
- }
- else
- progpath[0] = '\0';
+ strncpy(progpath, prog, MAXPATHLEN);
+ else if (path) {
+ while (1) {
+ char *delim = strchr(path, DELIM);
+
+ if (delim) {
+ size_t len = delim - path;
+ /* ensure we can't overwrite buffer */
+ len = min(MAXPATHLEN,len);
+ strncpy(progpath, path, len);
+ *(progpath + len) = '\0';
+ }
+ else
+ strncpy(progpath, path, MAXPATHLEN);
+
+ /* join() is safe for MAXPATHLEN+1 size buffer */
+ join(progpath, prog);
+ if (exists(progpath))
+ break;
+
+ if (!delim) {
+ progpath[0] = '\0';
+ break;
+ }
+ path = delim + 1;
+ }
+ }
+ else
+ progpath[0] = '\0';
}
static void
calculate_path(void)
{
- char argv0_path[MAXPATHLEN+1];
- char *buf;
- size_t bufsz;
- char *pythonhome = Py_GetPythonHome();
- char *envpath = Py_GETENV("PYTHONPATH");
+ char argv0_path[MAXPATHLEN+1];
+ char *buf;
+ size_t bufsz;
+ char *pythonhome = Py_GetPythonHome();
+ char *envpath = Py_GETENV("PYTHONPATH");
#ifdef MS_WINDOWS
- int skiphome, skipdefault;
- char *machinepath = NULL;
- char *userpath = NULL;
- char zip_path[MAXPATHLEN+1];
- size_t len;
+ int skiphome, skipdefault;
+ char *machinepath = NULL;
+ char *userpath = NULL;
+ char zip_path[MAXPATHLEN+1];
+ size_t len;
#endif
- get_progpath();
- /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
- strcpy(argv0_path, progpath);
- reduce(argv0_path);
- if (pythonhome == NULL || *pythonhome == '\0') {
- if (search_for_prefix(argv0_path, LANDMARK))
- pythonhome = prefix;
- else
- pythonhome = NULL;
- }
- else
- strncpy(prefix, pythonhome, MAXPATHLEN);
+ get_progpath();
+ /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
+ strcpy(argv0_path, progpath);
+ reduce(argv0_path);
+ if (pythonhome == NULL || *pythonhome == '\0') {
+ if (search_for_prefix(argv0_path, LANDMARK))
+ pythonhome = prefix;
+ else
+ pythonhome = NULL;
+ }
+ else
+ strncpy(prefix, pythonhome, MAXPATHLEN);
- if (envpath && *envpath == '\0')
- envpath = NULL;
+ if (envpath && *envpath == '\0')
+ envpath = NULL;
#ifdef MS_WINDOWS
- /* Calculate zip archive path */
- if (dllpath[0]) /* use name of python DLL */
- strncpy(zip_path, dllpath, MAXPATHLEN);
- else /* use name of executable program */
- strncpy(zip_path, progpath, MAXPATHLEN);
- zip_path[MAXPATHLEN] = '\0';
- len = strlen(zip_path);
- if (len > 4) {
- zip_path[len-3] = 'z'; /* change ending to "zip" */
- zip_path[len-2] = 'i';
- zip_path[len-1] = 'p';
- }
- else {
- zip_path[0] = 0;
- }
-
- skiphome = pythonhome==NULL ? 0 : 1;
+ /* Calculate zip archive path */
+ if (dllpath[0]) /* use name of python DLL */
+ strncpy(zip_path, dllpath, MAXPATHLEN);
+ else /* use name of executable program */
+ strncpy(zip_path, progpath, MAXPATHLEN);
+ zip_path[MAXPATHLEN] = '\0';
+ len = strlen(zip_path);
+ if (len > 4) {
+ zip_path[len-3] = 'z'; /* change ending to "zip" */
+ zip_path[len-2] = 'i';
+ zip_path[len-1] = 'p';
+ }
+ else {
+ zip_path[0] = 0;
+ }
+
+ skiphome = pythonhome==NULL ? 0 : 1;
#ifdef Py_ENABLE_SHARED
- machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
- userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
+ machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, skiphome);
+ userpath = getpythonregpath(HKEY_CURRENT_USER, skiphome);
#endif
- /* We only use the default relative PYTHONPATH if we havent
- anything better to use! */
- skipdefault = envpath!=NULL || pythonhome!=NULL || \
- machinepath!=NULL || userpath!=NULL;
+ /* We only use the default relative PYTHONPATH if we havent
+ anything better to use! */
+ skipdefault = envpath!=NULL || pythonhome!=NULL || \
+ machinepath!=NULL || userpath!=NULL;
#endif
- /* We need to construct a path from the following parts.
- (1) the PYTHONPATH environment variable, if set;
- (2) for Win32, the zip archive file path;
- (3) for Win32, the machinepath and userpath, if set;
- (4) the PYTHONPATH config macro, with the leading "."
- of each component replaced with pythonhome, if set;
- (5) the directory containing the executable (argv0_path).
- The length calculation calculates #4 first.
- Extra rules:
- - If PYTHONHOME is set (in any way) item (3) is ignored.
- - If registry values are used, (4) and (5) are ignored.
- */
-
- /* Calculate size of return buffer */
- if (pythonhome != NULL) {
- char *p;
- bufsz = 1;
- for (p = PYTHONPATH; *p; p++) {
- if (*p == DELIM)
- bufsz++; /* number of DELIM plus one */
- }
- bufsz *= strlen(pythonhome);
- }
- else
- bufsz = 0;
- bufsz += strlen(PYTHONPATH) + 1;
- bufsz += strlen(argv0_path) + 1;
+ /* We need to construct a path from the following parts.
+ (1) the PYTHONPATH environment variable, if set;
+ (2) for Win32, the zip archive file path;
+ (3) for Win32, the machinepath and userpath, if set;
+ (4) the PYTHONPATH config macro, with the leading "."
+ of each component replaced with pythonhome, if set;
+ (5) the directory containing the executable (argv0_path).
+ The length calculation calculates #4 first.
+ Extra rules:
+ - If PYTHONHOME is set (in any way) item (3) is ignored.
+ - If registry values are used, (4) and (5) are ignored.
+ */
+
+ /* Calculate size of return buffer */
+ if (pythonhome != NULL) {
+ char *p;
+ bufsz = 1;
+ for (p = PYTHONPATH; *p; p++) {
+ if (*p == DELIM)
+ bufsz++; /* number of DELIM plus one */
+ }
+ bufsz *= strlen(pythonhome);
+ }
+ else
+ bufsz = 0;
+ bufsz += strlen(PYTHONPATH) + 1;
+ bufsz += strlen(argv0_path) + 1;
#ifdef MS_WINDOWS
- if (userpath)
- bufsz += strlen(userpath) + 1;
- if (machinepath)
- bufsz += strlen(machinepath) + 1;
- bufsz += strlen(zip_path) + 1;
+ if (userpath)
+ bufsz += strlen(userpath) + 1;
+ if (machinepath)
+ bufsz += strlen(machinepath) + 1;
+ bufsz += strlen(zip_path) + 1;
#endif
- if (envpath != NULL)
- bufsz += strlen(envpath) + 1;
-
- module_search_path = buf = malloc(bufsz);
- if (buf == NULL) {
- /* We can't exit, so print a warning and limp along */
- fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
- if (envpath) {
- fprintf(stderr, "Using environment $PYTHONPATH.\n");
- module_search_path = envpath;
- }
- else {
- fprintf(stderr, "Using default static path.\n");
- module_search_path = PYTHONPATH;
- }
+ if (envpath != NULL)
+ bufsz += strlen(envpath) + 1;
+
+ module_search_path = buf = malloc(bufsz);
+ if (buf == NULL) {
+ /* We can't exit, so print a warning and limp along */
+ fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
+ if (envpath) {
+ fprintf(stderr, "Using environment $PYTHONPATH.\n");
+ module_search_path = envpath;
+ }
+ else {
+ fprintf(stderr, "Using default static path.\n");
+ module_search_path = PYTHONPATH;
+ }
#ifdef MS_WINDOWS
- if (machinepath)
- free(machinepath);
- if (userpath)
- free(userpath);
+ if (machinepath)
+ free(machinepath);
+ if (userpath)
+ free(userpath);
#endif /* MS_WINDOWS */
- return;
- }
-
- if (envpath) {
- strcpy(buf, envpath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
+ return;
+ }
+
+ if (envpath) {
+ strcpy(buf, envpath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
#ifdef MS_WINDOWS
- if (zip_path[0]) {
- strcpy(buf, zip_path);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
- if (userpath) {
- strcpy(buf, userpath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- free(userpath);
- }
- if (machinepath) {
- strcpy(buf, machinepath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- free(machinepath);
- }
- if (pythonhome == NULL) {
- if (!skipdefault) {
- strcpy(buf, PYTHONPATH);
- buf = strchr(buf, '\0');
- }
- }
+ if (zip_path[0]) {
+ strcpy(buf, zip_path);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
+ if (userpath) {
+ strcpy(buf, userpath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ free(userpath);
+ }
+ if (machinepath) {
+ strcpy(buf, machinepath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ free(machinepath);
+ }
+ if (pythonhome == NULL) {
+ if (!skipdefault) {
+ strcpy(buf, PYTHONPATH);
+ buf = strchr(buf, '\0');
+ }
+ }
#else
- if (pythonhome == NULL) {
- strcpy(buf, PYTHONPATH);
- buf = strchr(buf, '\0');
- }
+ if (pythonhome == NULL) {
+ strcpy(buf, PYTHONPATH);
+ buf = strchr(buf, '\0');
+ }
#endif /* MS_WINDOWS */
- else {
- char *p = PYTHONPATH;
- char *q;
- size_t n;
- for (;;) {
- q = strchr(p, DELIM);
- if (q == NULL)
- n = strlen(p);
- else
- n = q-p;
- if (p[0] == '.' && is_sep(p[1])) {
- strcpy(buf, pythonhome);
- buf = strchr(buf, '\0');
- p++;
- n--;
- }
- strncpy(buf, p, n);
- buf += n;
- if (q == NULL)
- break;
- *buf++ = DELIM;
- p = q+1;
- }
- }
- if (argv0_path) {
- *buf++ = DELIM;
- strcpy(buf, argv0_path);
- buf = strchr(buf, '\0');
- }
- *buf = '\0';
- /* Now to pull one last hack/trick. If sys.prefix is
- empty, then try and find it somewhere on the paths
- we calculated. We scan backwards, as our general policy
- is that Python core directories are at the *end* of
- sys.path. We assume that our "lib" directory is
- on the path, and that our 'prefix' directory is
- the parent of that.
- */
- if (*prefix=='\0') {
- char lookBuf[MAXPATHLEN+1];
- char *look = buf - 1; /* 'buf' is at the end of the buffer */
- while (1) {
- Py_ssize_t nchars;
- char *lookEnd = look;
- /* 'look' will end up one character before the
- start of the path in question - even if this
- is one character before the start of the buffer
- */
- while (look >= module_search_path && *look != DELIM)
- look--;
- nchars = lookEnd-look;
- strncpy(lookBuf, look+1, nchars);
- lookBuf[nchars] = '\0';
- /* Up one level to the parent */
- reduce(lookBuf);
- if (search_for_prefix(lookBuf, LANDMARK)) {
- break;
- }
- /* If we are out of paths to search - give up */
- if (look < module_search_path)
- break;
- look--;
- }
- }
+ else {
+ char *p = PYTHONPATH;
+ char *q;
+ size_t n;
+ for (;;) {
+ q = strchr(p, DELIM);
+ if (q == NULL)
+ n = strlen(p);
+ else
+ n = q-p;
+ if (p[0] == '.' && is_sep(p[1])) {
+ strcpy(buf, pythonhome);
+ buf = strchr(buf, '\0');
+ p++;
+ n--;
+ }
+ strncpy(buf, p, n);
+ buf += n;
+ if (q == NULL)
+ break;
+ *buf++ = DELIM;
+ p = q+1;
+ }
+ }
+ if (argv0_path) {
+ *buf++ = DELIM;
+ strcpy(buf, argv0_path);
+ buf = strchr(buf, '\0');
+ }
+ *buf = '\0';
+ /* Now to pull one last hack/trick. If sys.prefix is
+ empty, then try and find it somewhere on the paths
+ we calculated. We scan backwards, as our general policy
+ is that Python core directories are at the *end* of
+ sys.path. We assume that our "lib" directory is
+ on the path, and that our 'prefix' directory is
+ the parent of that.
+ */
+ if (*prefix=='\0') {
+ char lookBuf[MAXPATHLEN+1];
+ char *look = buf - 1; /* 'buf' is at the end of the buffer */
+ while (1) {
+ Py_ssize_t nchars;
+ char *lookEnd = look;
+ /* 'look' will end up one character before the
+ start of the path in question - even if this
+ is one character before the start of the buffer
+ */
+ while (look >= module_search_path && *look != DELIM)
+ look--;
+ nchars = lookEnd-look;
+ strncpy(lookBuf, look+1, nchars);
+ lookBuf[nchars] = '\0';
+ /* Up one level to the parent */
+ reduce(lookBuf);
+ if (search_for_prefix(lookBuf, LANDMARK)) {
+ break;
+ }
+ /* If we are out of paths to search - give up */
+ if (look < module_search_path)
+ break;
+ look--;
+ }
+ }
}
@@ -686,29 +686,29 @@ calculate_path(void)
char *
Py_GetPath(void)
{
- if (!module_search_path)
- calculate_path();
- return module_search_path;
+ if (!module_search_path)
+ calculate_path();
+ return module_search_path;
}
char *
Py_GetPrefix(void)
{
- if (!module_search_path)
- calculate_path();
- return prefix;
+ if (!module_search_path)
+ calculate_path();
+ return prefix;
}
char *
Py_GetExecPrefix(void)
{
- return Py_GetPrefix();
+ return Py_GetPrefix();
}
char *
Py_GetProgramFullPath(void)
{
- if (!module_search_path)
- calculate_path();
- return progpath;
+ if (!module_search_path)
+ calculate_path();
+ return progpath;
}
diff --git a/PC/import_nt.c b/PC/import_nt.c
index e7d152a..196a774 100644
--- a/PC/import_nt.c
+++ b/PC/import_nt.c
@@ -1,6 +1,6 @@
/********************************************************************
- import_nt.c
+ import_nt.c
Win32 specific import code.
@@ -16,71 +16,71 @@
extern const char *PyWin_DLLVersionString;
FILE *PyWin_FindRegisteredModule(const char *moduleName,
- struct filedescr **ppFileDesc,
- char *pathBuf,
- Py_ssize_t pathLen)
+ struct filedescr **ppFileDesc,
+ char *pathBuf,
+ Py_ssize_t pathLen)
{
- char *moduleKey;
- const char keyPrefix[] = "Software\\Python\\PythonCore\\";
- const char keySuffix[] = "\\Modules\\";
+ char *moduleKey;
+ const char keyPrefix[] = "Software\\Python\\PythonCore\\";
+ const char keySuffix[] = "\\Modules\\";
#ifdef _DEBUG
- /* In debugging builds, we _must_ have the debug version
- * registered.
- */
- const char debugString[] = "\\Debug";
+ /* In debugging builds, we _must_ have the debug version
+ * registered.
+ */
+ const char debugString[] = "\\Debug";
#else
- const char debugString[] = "";
+ const char debugString[] = "";
#endif
- struct filedescr *fdp = NULL;
- FILE *fp;
- HKEY keyBase = HKEY_CURRENT_USER;
- int modNameSize;
- long regStat;
+ struct filedescr *fdp = NULL;
+ FILE *fp;
+ HKEY keyBase = HKEY_CURRENT_USER;
+ int modNameSize;
+ long regStat;
- /* Calculate the size for the sprintf buffer.
- * Get the size of the chars only, plus 1 NULL.
- */
- size_t bufSize = sizeof(keyPrefix)-1 +
- strlen(PyWin_DLLVersionString) +
- sizeof(keySuffix) +
- strlen(moduleName) +
- sizeof(debugString) - 1;
- /* alloca == no free required, but memory only local to fn,
- * also no heap fragmentation!
- */
- moduleKey = alloca(bufSize);
- PyOS_snprintf(moduleKey, bufSize,
- "Software\\Python\\PythonCore\\%s\\Modules\\%s%s",
- PyWin_DLLVersionString, moduleName, debugString);
+ /* Calculate the size for the sprintf buffer.
+ * Get the size of the chars only, plus 1 NULL.
+ */
+ size_t bufSize = sizeof(keyPrefix)-1 +
+ strlen(PyWin_DLLVersionString) +
+ sizeof(keySuffix) +
+ strlen(moduleName) +
+ sizeof(debugString) - 1;
+ /* alloca == no free required, but memory only local to fn,
+ * also no heap fragmentation!
+ */
+ moduleKey = alloca(bufSize);
+ PyOS_snprintf(moduleKey, bufSize,
+ "Software\\Python\\PythonCore\\%s\\Modules\\%s%s",
+ PyWin_DLLVersionString, moduleName, debugString);
- assert(pathLen < INT_MAX);
- modNameSize = (int)pathLen;
- regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize);
- if (regStat != ERROR_SUCCESS) {
- /* No user setting - lookup in machine settings */
- keyBase = HKEY_LOCAL_MACHINE;
- /* be anal - failure may have reset size param */
- modNameSize = (int)pathLen;
- regStat = RegQueryValue(keyBase, moduleKey,
- pathBuf, &modNameSize);
+ assert(pathLen < INT_MAX);
+ modNameSize = (int)pathLen;
+ regStat = RegQueryValue(keyBase, moduleKey, pathBuf, &modNameSize);
+ if (regStat != ERROR_SUCCESS) {
+ /* No user setting - lookup in machine settings */
+ keyBase = HKEY_LOCAL_MACHINE;
+ /* be anal - failure may have reset size param */
+ modNameSize = (int)pathLen;
+ regStat = RegQueryValue(keyBase, moduleKey,
+ pathBuf, &modNameSize);
- if (regStat != ERROR_SUCCESS)
- return NULL;
- }
- /* use the file extension to locate the type entry. */
- for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
- size_t extLen = strlen(fdp->suffix);
- assert(modNameSize >= 0); /* else cast to size_t is wrong */
- if ((size_t)modNameSize > extLen &&
- strnicmp(pathBuf + ((size_t)modNameSize-extLen-1),
- fdp->suffix,
- extLen) == 0)
- break;
- }
- if (fdp->suffix == NULL)
- return NULL;
- fp = fopen(pathBuf, fdp->mode);
- if (fp != NULL)
- *ppFileDesc = fdp;
- return fp;
+ if (regStat != ERROR_SUCCESS)
+ return NULL;
+ }
+ /* use the file extension to locate the type entry. */
+ for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
+ size_t extLen = strlen(fdp->suffix);
+ assert(modNameSize >= 0); /* else cast to size_t is wrong */
+ if ((size_t)modNameSize > extLen &&
+ strnicmp(pathBuf + ((size_t)modNameSize-extLen-1),
+ fdp->suffix,
+ extLen) == 0)
+ break;
+ }
+ if (fdp->suffix == NULL)
+ return NULL;
+ fp = fopen(pathBuf, fdp->mode);
+ if (fp != NULL)
+ *ppFileDesc = fdp;
+ return fp;
}
diff --git a/PC/make_versioninfo.c b/PC/make_versioninfo.c
index b9f9b88..e969671 100644
--- a/PC/make_versioninfo.c
+++ b/PC/make_versioninfo.c
@@ -22,17 +22,17 @@
*/
int main(int argc, char **argv)
{
- printf("/* This file created by make_versioninfo.exe */\n");
- printf("#define FIELD3 %d\n",
- PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL);
- printf("#define MS_DLL_ID \"%d.%d\"\n",
- PY_MAJOR_VERSION, PY_MINOR_VERSION);
- printf("#ifndef _DEBUG\n");
- printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n",
- PY_MAJOR_VERSION, PY_MINOR_VERSION);
- printf("#else\n");
- printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n",
- PY_MAJOR_VERSION, PY_MINOR_VERSION);
- printf("#endif\n");
- return 0;
+ printf("/* This file created by make_versioninfo.exe */\n");
+ printf("#define FIELD3 %d\n",
+ PY_MICRO_VERSION*1000 + PY_RELEASE_LEVEL*10 + PY_RELEASE_SERIAL);
+ printf("#define MS_DLL_ID \"%d.%d\"\n",
+ PY_MAJOR_VERSION, PY_MINOR_VERSION);
+ printf("#ifndef _DEBUG\n");
+ printf("#define PYTHON_DLL_NAME \"python%d%d.dll\"\n",
+ PY_MAJOR_VERSION, PY_MINOR_VERSION);
+ printf("#else\n");
+ printf("#define PYTHON_DLL_NAME \"python%d%d_d.dll\"\n",
+ PY_MAJOR_VERSION, PY_MINOR_VERSION);
+ printf("#endif\n");
+ return 0;
}
diff --git a/PC/msvcrtmodule.c b/PC/msvcrtmodule.c
index 9764a02..68b7d24 100755
--- a/PC/msvcrtmodule.c
+++ b/PC/msvcrtmodule.c
@@ -1,18 +1,18 @@
/*********************************************************
- msvcrtmodule.c
+ msvcrtmodule.c
- A Python interface to the Microsoft Visual C Runtime
- Library, providing access to those non-portable, but
- still useful routines.
+ A Python interface to the Microsoft Visual C Runtime
+ Library, providing access to those non-portable, but
+ still useful routines.
- Only ever compiled with an MS compiler, so no attempt
- has been made to avoid MS language extensions, etc...
+ Only ever compiled with an MS compiler, so no attempt
+ has been made to avoid MS language extensions, etc...
- This may only work on NT or 95...
+ This may only work on NT or 95...
- Author: Mark Hammond and Guido van Rossum.
- Maintenance: Guido van Rossum.
+ Author: Mark Hammond and Guido van Rossum.
+ Maintenance: Guido van Rossum.
***********************************************************/
@@ -33,14 +33,14 @@
static PyObject *
msvcrt_heapmin(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, ":heapmin"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":heapmin"))
+ return NULL;
- if (_heapmin() != 0)
- return PyErr_SetFromErrno(PyExc_IOError);
+ if (_heapmin() != 0)
+ return PyErr_SetFromErrno(PyExc_IOError);
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(heapmin_doc,
@@ -53,22 +53,22 @@ to the operating system. On failure, this raises IOError.");
static PyObject *
msvcrt_locking(PyObject *self, PyObject *args)
{
- int fd;
- int mode;
- long nbytes;
- int err;
-
- if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes))
- return NULL;
-
- Py_BEGIN_ALLOW_THREADS
- err = _locking(fd, mode, nbytes);
- Py_END_ALLOW_THREADS
- if (err != 0)
- return PyErr_SetFromErrno(PyExc_IOError);
-
- Py_INCREF(Py_None);
- return Py_None;
+ int fd;
+ int mode;
+ long nbytes;
+ int err;
+
+ if (!PyArg_ParseTuple(args, "iil:locking", &fd, &mode, &nbytes))
+ return NULL;
+
+ Py_BEGIN_ALLOW_THREADS
+ err = _locking(fd, mode, nbytes);
+ Py_END_ALLOW_THREADS
+ if (err != 0)
+ return PyErr_SetFromErrno(PyExc_IOError);
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(locking_doc,
@@ -86,16 +86,16 @@ individually.");
static PyObject *
msvcrt_setmode(PyObject *self, PyObject *args)
{
- int fd;
- int flags;
- if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags))
- return NULL;
+ int fd;
+ int flags;
+ if (!PyArg_ParseTuple(args,"ii:setmode", &fd, &flags))
+ return NULL;
- flags = _setmode(fd, flags);
- if (flags == -1)
- return PyErr_SetFromErrno(PyExc_IOError);
+ flags = _setmode(fd, flags);
+ if (flags == -1)
+ return PyErr_SetFromErrno(PyExc_IOError);
- return PyInt_FromLong(flags);
+ return PyInt_FromLong(flags);
}
PyDoc_STRVAR(setmode_doc,
@@ -109,18 +109,18 @@ os.O_BINARY.");
static PyObject *
msvcrt_open_osfhandle(PyObject *self, PyObject *args)
{
- long handle;
- int flags;
- int fd;
+ long handle;
+ int flags;
+ int fd;
- if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags))
- return NULL;
+ if (!PyArg_ParseTuple(args, "li:open_osfhandle", &handle, &flags))
+ return NULL;
- fd = _open_osfhandle(handle, flags);
- if (fd == -1)
- return PyErr_SetFromErrno(PyExc_IOError);
+ fd = _open_osfhandle(handle, flags);
+ if (fd == -1)
+ return PyErr_SetFromErrno(PyExc_IOError);
- return PyInt_FromLong(fd);
+ return PyInt_FromLong(fd);
}
PyDoc_STRVAR(open_osfhandle_doc,
@@ -135,20 +135,20 @@ to os.fdopen() to create a file object.");
static PyObject *
msvcrt_get_osfhandle(PyObject *self, PyObject *args)
{
- int fd;
- Py_intptr_t handle;
+ int fd;
+ Py_intptr_t handle;
- if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd))
- return NULL;
+ if (!PyArg_ParseTuple(args,"i:get_osfhandle", &fd))
+ return NULL;
- handle = _get_osfhandle(fd);
- if (handle == -1)
- return PyErr_SetFromErrno(PyExc_IOError);
+ handle = _get_osfhandle(fd);
+ if (handle == -1)
+ return PyErr_SetFromErrno(PyExc_IOError);
- /* technically 'handle' is not a pointer, but a integer as
- large as a pointer, Python's *VoidPtr interface is the
- most appropriate here */
- return PyLong_FromVoidPtr((void*)handle);
+ /* technically 'handle' is not a pointer, but a integer as
+ large as a pointer, Python's *VoidPtr interface is the
+ most appropriate here */
+ return PyLong_FromVoidPtr((void*)handle);
}
PyDoc_STRVAR(get_osfhandle_doc,
@@ -162,13 +162,13 @@ if fd is not recognized.");
static PyObject *
msvcrt_kbhit(PyObject *self, PyObject *args)
{
- int ok;
+ int ok;
- if (!PyArg_ParseTuple(args, ":kbhit"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":kbhit"))
+ return NULL;
- ok = _kbhit();
- return PyInt_FromLong(ok);
+ ok = _kbhit();
+ return PyInt_FromLong(ok);
}
PyDoc_STRVAR(kbhit_doc,
@@ -179,17 +179,17 @@ Return true if a keypress is waiting to be read.");
static PyObject *
msvcrt_getch(PyObject *self, PyObject *args)
{
- int ch;
- char s[1];
+ int ch;
+ char s[1];
- if (!PyArg_ParseTuple(args, ":getch"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":getch"))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- ch = _getch();
- Py_END_ALLOW_THREADS
- s[0] = ch;
- return PyString_FromStringAndSize(s, 1);
+ Py_BEGIN_ALLOW_THREADS
+ ch = _getch();
+ Py_END_ALLOW_THREADS
+ s[0] = ch;
+ return PyString_FromStringAndSize(s, 1);
}
PyDoc_STRVAR(getch_doc,
@@ -206,17 +206,17 @@ this function.");
static PyObject *
msvcrt_getwch(PyObject *self, PyObject *args)
{
- Py_UNICODE ch;
- Py_UNICODE u[1];
+ Py_UNICODE ch;
+ Py_UNICODE u[1];
- if (!PyArg_ParseTuple(args, ":getwch"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":getwch"))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- ch = _getwch();
- Py_END_ALLOW_THREADS
- u[0] = ch;
- return PyUnicode_FromUnicode(u, 1);
+ Py_BEGIN_ALLOW_THREADS
+ ch = _getwch();
+ Py_END_ALLOW_THREADS
+ u[0] = ch;
+ return PyUnicode_FromUnicode(u, 1);
}
PyDoc_STRVAR(getwch_doc,
@@ -228,17 +228,17 @@ Wide char variant of getch(), returning a Unicode value.");
static PyObject *
msvcrt_getche(PyObject *self, PyObject *args)
{
- int ch;
- char s[1];
+ int ch;
+ char s[1];
- if (!PyArg_ParseTuple(args, ":getche"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":getche"))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- ch = _getche();
- Py_END_ALLOW_THREADS
- s[0] = ch;
- return PyString_FromStringAndSize(s, 1);
+ Py_BEGIN_ALLOW_THREADS
+ ch = _getche();
+ Py_END_ALLOW_THREADS
+ s[0] = ch;
+ return PyString_FromStringAndSize(s, 1);
}
PyDoc_STRVAR(getche_doc,
@@ -251,17 +251,17 @@ a printable character.");
static PyObject *
msvcrt_getwche(PyObject *self, PyObject *args)
{
- Py_UNICODE ch;
- Py_UNICODE s[1];
+ Py_UNICODE ch;
+ Py_UNICODE s[1];
- if (!PyArg_ParseTuple(args, ":getwche"))
- return NULL;
+ if (!PyArg_ParseTuple(args, ":getwche"))
+ return NULL;
- Py_BEGIN_ALLOW_THREADS
- ch = _getwche();
- Py_END_ALLOW_THREADS
- s[0] = ch;
- return PyUnicode_FromUnicode(s, 1);
+ Py_BEGIN_ALLOW_THREADS
+ ch = _getwche();
+ Py_END_ALLOW_THREADS
+ s[0] = ch;
+ return PyUnicode_FromUnicode(s, 1);
}
PyDoc_STRVAR(getwche_doc,
@@ -273,14 +273,14 @@ Wide char variant of getche(), returning a Unicode value.");
static PyObject *
msvcrt_putch(PyObject *self, PyObject *args)
{
- char ch;
+ char ch;
- if (!PyArg_ParseTuple(args, "c:putch", &ch))
- return NULL;
+ if (!PyArg_ParseTuple(args, "c:putch", &ch))
+ return NULL;
- _putch(ch);
- Py_INCREF(Py_None);
- return Py_None;
+ _putch(ch);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(putch_doc,
@@ -292,19 +292,19 @@ Print the character char to the console without buffering.");
static PyObject *
msvcrt_putwch(PyObject *self, PyObject *args)
{
- Py_UNICODE *ch;
- int size;
+ Py_UNICODE *ch;
+ int size;
- if (!PyArg_ParseTuple(args, "u#:putwch", &ch, &size))
- return NULL;
+ if (!PyArg_ParseTuple(args, "u#:putwch", &ch, &size))
+ return NULL;
- if (size == 0) {
- PyErr_SetString(PyExc_ValueError,
- "Expected unicode string of length 1");
- return NULL;
- }
- _putwch(*ch);
- Py_RETURN_NONE;
+ if (size == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "Expected unicode string of length 1");
+ return NULL;
+ }
+ _putwch(*ch);
+ Py_RETURN_NONE;
}
@@ -317,15 +317,15 @@ Wide char variant of putch(), accepting a Unicode value.");
static PyObject *
msvcrt_ungetch(PyObject *self, PyObject *args)
{
- char ch;
+ char ch;
- if (!PyArg_ParseTuple(args, "c:ungetch", &ch))
- return NULL;
+ if (!PyArg_ParseTuple(args, "c:ungetch", &ch))
+ return NULL;
- if (_ungetch(ch) == EOF)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_INCREF(Py_None);
- return Py_None;
+ if (_ungetch(ch) == EOF)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(ungetch_doc,
@@ -338,15 +338,15 @@ it will be the next character read by getch() or getche().");
static PyObject *
msvcrt_ungetwch(PyObject *self, PyObject *args)
{
- Py_UNICODE ch;
+ Py_UNICODE ch;
- if (!PyArg_ParseTuple(args, "u:ungetwch", &ch))
- return NULL;
+ if (!PyArg_ParseTuple(args, "u:ungetwch", &ch))
+ return NULL;
- if (_ungetch(ch) == EOF)
- return PyErr_SetFromErrno(PyExc_IOError);
- Py_INCREF(Py_None);
- return Py_None;
+ if (_ungetch(ch) == EOF)
+ return PyErr_SetFromErrno(PyExc_IOError);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(ungetwch_doc,
@@ -358,70 +358,70 @@ Wide char variant of ungetch(), accepting a Unicode value.");
static void
insertint(PyObject *d, char *name, int value)
{
- PyObject *v = PyInt_FromLong((long) value);
- if (v == NULL) {
- /* Don't bother reporting this error */
- PyErr_Clear();
- }
- else {
- PyDict_SetItemString(d, name, v);
- Py_DECREF(v);
- }
+ PyObject *v = PyInt_FromLong((long) value);
+ if (v == NULL) {
+ /* Don't bother reporting this error */
+ PyErr_Clear();
+ }
+ else {
+ PyDict_SetItemString(d, name, v);
+ Py_DECREF(v);
+ }
}
/* List of functions exported by this module */
static struct PyMethodDef msvcrt_functions[] = {
- {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc},
- {"locking", msvcrt_locking, METH_VARARGS, locking_doc},
- {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc},
- {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc},
- {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc},
- {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc},
- {"getch", msvcrt_getch, METH_VARARGS, getch_doc},
- {"getche", msvcrt_getche, METH_VARARGS, getche_doc},
- {"putch", msvcrt_putch, METH_VARARGS, putch_doc},
- {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc},
+ {"heapmin", msvcrt_heapmin, METH_VARARGS, heapmin_doc},
+ {"locking", msvcrt_locking, METH_VARARGS, locking_doc},
+ {"setmode", msvcrt_setmode, METH_VARARGS, setmode_doc},
+ {"open_osfhandle", msvcrt_open_osfhandle, METH_VARARGS, open_osfhandle_doc},
+ {"get_osfhandle", msvcrt_get_osfhandle, METH_VARARGS, get_osfhandle_doc},
+ {"kbhit", msvcrt_kbhit, METH_VARARGS, kbhit_doc},
+ {"getch", msvcrt_getch, METH_VARARGS, getch_doc},
+ {"getche", msvcrt_getche, METH_VARARGS, getche_doc},
+ {"putch", msvcrt_putch, METH_VARARGS, putch_doc},
+ {"ungetch", msvcrt_ungetch, METH_VARARGS, ungetch_doc},
#ifdef _WCONIO_DEFINED
- {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc},
- {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc},
- {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc},
- {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc},
+ {"getwch", msvcrt_getwch, METH_VARARGS, getwch_doc},
+ {"getwche", msvcrt_getwche, METH_VARARGS, getwche_doc},
+ {"putwch", msvcrt_putwch, METH_VARARGS, putwch_doc},
+ {"ungetwch", msvcrt_ungetwch, METH_VARARGS, ungetwch_doc},
#endif
- {NULL, NULL}
+ {NULL, NULL}
};
PyMODINIT_FUNC
initmsvcrt(void)
{
- int st;
- PyObject *d;
- PyObject *m = Py_InitModule("msvcrt", msvcrt_functions);
- if (m == NULL)
- return;
- d = PyModule_GetDict(m);
-
- /* constants for the locking() function's mode argument */
- insertint(d, "LK_LOCK", _LK_LOCK);
- insertint(d, "LK_NBLCK", _LK_NBLCK);
- insertint(d, "LK_NBRLCK", _LK_NBRLCK);
- insertint(d, "LK_RLCK", _LK_RLCK);
- insertint(d, "LK_UNLCK", _LK_UNLCK);
-
- /* constants for the crt versions */
+ int st;
+ PyObject *d;
+ PyObject *m = Py_InitModule("msvcrt", msvcrt_functions);
+ if (m == NULL)
+ return;
+ d = PyModule_GetDict(m);
+
+ /* constants for the locking() function's mode argument */
+ insertint(d, "LK_LOCK", _LK_LOCK);
+ insertint(d, "LK_NBLCK", _LK_NBLCK);
+ insertint(d, "LK_NBRLCK", _LK_NBRLCK);
+ insertint(d, "LK_RLCK", _LK_RLCK);
+ insertint(d, "LK_UNLCK", _LK_UNLCK);
+
+ /* constants for the crt versions */
#ifdef _VC_ASSEMBLY_PUBLICKEYTOKEN
- st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN",
- _VC_ASSEMBLY_PUBLICKEYTOKEN);
- if (st < 0)return;
+ st = PyModule_AddStringConstant(m, "VC_ASSEMBLY_PUBLICKEYTOKEN",
+ _VC_ASSEMBLY_PUBLICKEYTOKEN);
+ if (st < 0)return;
#endif
#ifdef _CRT_ASSEMBLY_VERSION
- st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION",
- _CRT_ASSEMBLY_VERSION);
- if (st < 0)return;
+ st = PyModule_AddStringConstant(m, "CRT_ASSEMBLY_VERSION",
+ _CRT_ASSEMBLY_VERSION);
+ if (st < 0)return;
#endif
#ifdef __LIBRARIES_ASSEMBLY_NAME_PREFIX
- st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX",
- __LIBRARIES_ASSEMBLY_NAME_PREFIX);
- if (st < 0)return;
+ st = PyModule_AddStringConstant(m, "LIBRARIES_ASSEMBLY_NAME_PREFIX",
+ __LIBRARIES_ASSEMBLY_NAME_PREFIX);
+ if (st < 0)return;
#endif
}
diff --git a/PC/os2emx/config.c b/PC/os2emx/config.c
index 408381c..cbab25c 100644
--- a/PC/os2emx/config.c
+++ b/PC/os2emx/config.c
@@ -102,81 +102,81 @@ extern void initgc();
struct _inittab _PyImport_Inittab[] = {
- {"os2", initos2},
- {"signal", initsignal},
+ {"os2", initos2},
+ {"signal", initsignal},
#ifdef WITH_THREAD
- {"thread", initthread},
+ {"thread", initthread},
#endif
- {"_codecs", init_codecs},
- {"_csv", init_csv},
- {"_locale", init_locale},
- {"_random", init_random},
- {"_sre", init_sre},
- {"_symtable", init_symtable},
- {"_weakref", init_weakref},
- {"array", initarray},
- {"binascii", initbinascii},
- {"cPickle", initcPickle},
- {"cStringIO", initcStringIO},
- {"_collections", init_collections},
- {"cmath", initcmath},
- {"datetime", initdatetime},
- {"dl", initdl},
- {"errno", initerrno},
- {"fcntl", initfcntl},
- {"_fileio", init_fileio},
- {"_functools", init_functools},
- {"_heapq", init_heapq},
- {"imageop", initimageop},
- {"itertools", inititertools},
- {"math", initmath},
- {"_md5", init_md5},
- {"operator", initoperator},
- {"_sha", init_sha},
- {"_sha256", init_sha256},
- {"_sha512", init_sha512},
- {"strop", initstrop},
- {"_struct", init_struct},
- {"termios", inittermios},
- {"time", inittime},
- {"timing", inittiming},
- {"xxsubtype", initxxsubtype},
- {"zipimport", initzipimport},
+ {"_codecs", init_codecs},
+ {"_csv", init_csv},
+ {"_locale", init_locale},
+ {"_random", init_random},
+ {"_sre", init_sre},
+ {"_symtable", init_symtable},
+ {"_weakref", init_weakref},
+ {"array", initarray},
+ {"binascii", initbinascii},
+ {"cPickle", initcPickle},
+ {"cStringIO", initcStringIO},
+ {"_collections", init_collections},
+ {"cmath", initcmath},
+ {"datetime", initdatetime},
+ {"dl", initdl},
+ {"errno", initerrno},
+ {"fcntl", initfcntl},
+ {"_fileio", init_fileio},
+ {"_functools", init_functools},
+ {"_heapq", init_heapq},
+ {"imageop", initimageop},
+ {"itertools", inititertools},
+ {"math", initmath},
+ {"_md5", init_md5},
+ {"operator", initoperator},
+ {"_sha", init_sha},
+ {"_sha256", init_sha256},
+ {"_sha512", init_sha512},
+ {"strop", initstrop},
+ {"_struct", init_struct},
+ {"termios", inittermios},
+ {"time", inittime},
+ {"timing", inittiming},
+ {"xxsubtype", initxxsubtype},
+ {"zipimport", initzipimport},
#if !HAVE_DYNAMIC_LOADING
- {"_curses", init_curses},
- {"_curses_panel", init_curses_panel},
- {"_hotshot", init_hotshot},
- {"_testcapi", init_testcapi},
- {"bsddb185", initbsddb185},
- {"bz2", initbz2},
- {"fpectl", initfpectl},
- {"fpetest", initfpetest},
- {"parser", initparser},
- {"pwd", initpwd},
- {"unicodedata", initunicodedata},
- {"zlib", initzlib},
+ {"_curses", init_curses},
+ {"_curses_panel", init_curses_panel},
+ {"_hotshot", init_hotshot},
+ {"_testcapi", init_testcapi},
+ {"bsddb185", initbsddb185},
+ {"bz2", initbz2},
+ {"fpectl", initfpectl},
+ {"fpetest", initfpetest},
+ {"parser", initparser},
+ {"pwd", initpwd},
+ {"unicodedata", initunicodedata},
+ {"zlib", initzlib},
#ifdef USE_SOCKET
- {"_socket", init_socket},
- {"select", initselect},
+ {"_socket", init_socket},
+ {"select", initselect},
#endif
#endif
/* -- ADDMODULE MARKER 2 -- */
- /* This module "lives in" with marshal.c */
- {"marshal", PyMarshal_Init},
+ /* This module "lives in" with marshal.c */
+ {"marshal", PyMarshal_Init},
- /* This lives it with import.c */
- {"imp", initimp},
+ /* This lives it with import.c */
+ {"imp", initimp},
- /* These entries are here for sys.builtin_module_names */
- {"__main__", NULL},
- {"__builtin__", NULL},
- {"sys", NULL},
- {"exceptions", NULL},
+ /* These entries are here for sys.builtin_module_names */
+ {"__main__", NULL},
+ {"__builtin__", NULL},
+ {"sys", NULL},
+ {"exceptions", NULL},
- /* This lives in gcmodule.c */
- {"gc", initgc},
+ /* This lives in gcmodule.c */
+ {"gc", initgc},
- /* Sentinel */
- {0, 0}
+ /* Sentinel */
+ {0, 0}
};
diff --git a/PC/os2emx/dlfcn.c b/PC/os2emx/dlfcn.c
index 9e88d5e..47c046c 100644
--- a/PC/os2emx/dlfcn.c
+++ b/PC/os2emx/dlfcn.c
@@ -46,178 +46,178 @@ PERFORMANCE OF THIS SOFTWARE.
#include <malloc.h>
typedef struct _track_rec {
- char *name;
- HMODULE handle;
- void *id;
- struct _track_rec *next;
+ char *name;
+ HMODULE handle;
+ void *id;
+ struct _track_rec *next;
} tDLLchain, *DLLchain;
-static DLLchain dlload = NULL; /* A simple chained list of DLL names */
-static char dlerr [256]; /* last error text string */
+static DLLchain dlload = NULL; /* A simple chained list of DLL names */
+static char dlerr [256]; /* last error text string */
static void *last_id;
static DLLchain find_id(void *id)
{
- DLLchain tmp;
+ DLLchain tmp;
- for (tmp = dlload; tmp; tmp = tmp->next)
- if (id == tmp->id)
- return tmp;
+ for (tmp = dlload; tmp; tmp = tmp->next)
+ if (id == tmp->id)
+ return tmp;
- return NULL;
+ return NULL;
}
/* load a dynamic-link library and return handle */
void *dlopen(char *filename, int flags)
{
- HMODULE hm;
- DLLchain tmp;
- char err[256];
- char *errtxt;
- int rc = 0, set_chain = 0;
-
- for (tmp = dlload; tmp; tmp = tmp->next)
- if (strnicmp(tmp->name, filename, 999) == 0)
- break;
-
- if (!tmp)
- {
- tmp = (DLLchain) malloc(sizeof(tDLLchain));
- if (!tmp)
- goto nomem;
- tmp->name = strdup(filename);
- tmp->next = dlload;
- set_chain = 1;
- }
-
- switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm))
- {
- case NO_ERROR:
- tmp->handle = hm;
- if (set_chain)
- {
- do
- last_id++;
- while ((last_id == 0) || (find_id(last_id)));
- tmp->id = last_id;
- dlload = tmp;
- }
- return tmp->id;
- case ERROR_FILE_NOT_FOUND:
- case ERROR_PATH_NOT_FOUND:
- errtxt = "module `%s' not found";
- break;
- case ERROR_TOO_MANY_OPEN_FILES:
- case ERROR_NOT_ENOUGH_MEMORY:
- case ERROR_SHARING_BUFFER_EXCEEDED:
+ HMODULE hm;
+ DLLchain tmp;
+ char err[256];
+ char *errtxt;
+ int rc = 0, set_chain = 0;
+
+ for (tmp = dlload; tmp; tmp = tmp->next)
+ if (strnicmp(tmp->name, filename, 999) == 0)
+ break;
+
+ if (!tmp)
+ {
+ tmp = (DLLchain) malloc(sizeof(tDLLchain));
+ if (!tmp)
+ goto nomem;
+ tmp->name = strdup(filename);
+ tmp->next = dlload;
+ set_chain = 1;
+ }
+
+ switch (rc = DosLoadModule((PSZ)&err, sizeof(err), filename, &hm))
+ {
+ case NO_ERROR:
+ tmp->handle = hm;
+ if (set_chain)
+ {
+ do
+ last_id++;
+ while ((last_id == 0) || (find_id(last_id)));
+ tmp->id = last_id;
+ dlload = tmp;
+ }
+ return tmp->id;
+ case ERROR_FILE_NOT_FOUND:
+ case ERROR_PATH_NOT_FOUND:
+ errtxt = "module `%s' not found";
+ break;
+ case ERROR_TOO_MANY_OPEN_FILES:
+ case ERROR_NOT_ENOUGH_MEMORY:
+ case ERROR_SHARING_BUFFER_EXCEEDED:
nomem:
- errtxt = "out of system resources";
- break;
- case ERROR_ACCESS_DENIED:
- errtxt = "access denied";
- break;
- case ERROR_BAD_FORMAT:
- case ERROR_INVALID_SEGMENT_NUMBER:
- case ERROR_INVALID_ORDINAL:
- case ERROR_INVALID_MODULETYPE:
- case ERROR_INVALID_EXE_SIGNATURE:
- case ERROR_EXE_MARKED_INVALID:
- case ERROR_ITERATED_DATA_EXCEEDS_64K:
- case ERROR_INVALID_MINALLOCSIZE:
- case ERROR_INVALID_SEGDPL:
- case ERROR_AUTODATASEG_EXCEEDS_64K:
- case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT:
- errtxt = "invalid module format";
- break;
- case ERROR_INVALID_NAME:
- errtxt = "filename doesn't match module name";
- break;
- case ERROR_SHARING_VIOLATION:
- case ERROR_LOCK_VIOLATION:
- errtxt = "sharing violation";
- break;
- case ERROR_INIT_ROUTINE_FAILED:
- errtxt = "module initialization failed";
- break;
- default:
- errtxt = "cause `%s', error code = %d";
- break;
- }
- snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc);
- if (tmp)
- {
- if (tmp->name)
- free(tmp->name);
- free(tmp);
- }
- return 0;
+ errtxt = "out of system resources";
+ break;
+ case ERROR_ACCESS_DENIED:
+ errtxt = "access denied";
+ break;
+ case ERROR_BAD_FORMAT:
+ case ERROR_INVALID_SEGMENT_NUMBER:
+ case ERROR_INVALID_ORDINAL:
+ case ERROR_INVALID_MODULETYPE:
+ case ERROR_INVALID_EXE_SIGNATURE:
+ case ERROR_EXE_MARKED_INVALID:
+ case ERROR_ITERATED_DATA_EXCEEDS_64K:
+ case ERROR_INVALID_MINALLOCSIZE:
+ case ERROR_INVALID_SEGDPL:
+ case ERROR_AUTODATASEG_EXCEEDS_64K:
+ case ERROR_RELOCSRC_CHAIN_EXCEEDS_SEGLIMIT:
+ errtxt = "invalid module format";
+ break;
+ case ERROR_INVALID_NAME:
+ errtxt = "filename doesn't match module name";
+ break;
+ case ERROR_SHARING_VIOLATION:
+ case ERROR_LOCK_VIOLATION:
+ errtxt = "sharing violation";
+ break;
+ case ERROR_INIT_ROUTINE_FAILED:
+ errtxt = "module initialization failed";
+ break;
+ default:
+ errtxt = "cause `%s', error code = %d";
+ break;
+ }
+ snprintf(dlerr, sizeof(dlerr), errtxt, &err, rc);
+ if (tmp)
+ {
+ if (tmp->name)
+ free(tmp->name);
+ free(tmp);
+ }
+ return 0;
}
/* return a pointer to the `symbol' in DLL */
void *dlsym(void *handle, char *symbol)
{
- int rc = 0;
- PFN addr;
- char *errtxt;
- int symord = 0;
- DLLchain tmp = find_id(handle);
-
- if (!tmp)
- goto inv_handle;
-
- if (*symbol == '#')
- symord = atoi(symbol + 1);
-
- switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr))
- {
- case NO_ERROR:
- return (void *)addr;
- case ERROR_INVALID_HANDLE:
+ int rc = 0;
+ PFN addr;
+ char *errtxt;
+ int symord = 0;
+ DLLchain tmp = find_id(handle);
+
+ if (!tmp)
+ goto inv_handle;
+
+ if (*symbol == '#')
+ symord = atoi(symbol + 1);
+
+ switch (rc = DosQueryProcAddr(tmp->handle, symord, symbol, &addr))
+ {
+ case NO_ERROR:
+ return (void *)addr;
+ case ERROR_INVALID_HANDLE:
inv_handle:
- errtxt = "invalid module handle";
- break;
- case ERROR_PROC_NOT_FOUND:
- case ERROR_INVALID_NAME:
- errtxt = "no symbol `%s' in module";
- break;
- default:
- errtxt = "symbol `%s', error code = %d";
- break;
- }
- snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc);
- return NULL;
+ errtxt = "invalid module handle";
+ break;
+ case ERROR_PROC_NOT_FOUND:
+ case ERROR_INVALID_NAME:
+ errtxt = "no symbol `%s' in module";
+ break;
+ default:
+ errtxt = "symbol `%s', error code = %d";
+ break;
+ }
+ snprintf(dlerr, sizeof(dlerr), errtxt, symbol, rc);
+ return NULL;
}
/* free dynamicaly-linked library */
int dlclose(void *handle)
{
- int rc;
- DLLchain tmp = find_id(handle);
-
- if (!tmp)
- goto inv_handle;
-
- switch (rc = DosFreeModule(tmp->handle))
- {
- case NO_ERROR:
- free(tmp->name);
- dlload = tmp->next;
- free(tmp);
- return 0;
- case ERROR_INVALID_HANDLE:
+ int rc;
+ DLLchain tmp = find_id(handle);
+
+ if (!tmp)
+ goto inv_handle;
+
+ switch (rc = DosFreeModule(tmp->handle))
+ {
+ case NO_ERROR:
+ free(tmp->name);
+ dlload = tmp->next;
+ free(tmp);
+ return 0;
+ case ERROR_INVALID_HANDLE:
inv_handle:
- strcpy(dlerr, "invalid module handle");
- return -1;
- case ERROR_INVALID_ACCESS:
- strcpy(dlerr, "access denied");
- return -1;
- default:
- return -1;
- }
+ strcpy(dlerr, "invalid module handle");
+ return -1;
+ case ERROR_INVALID_ACCESS:
+ strcpy(dlerr, "access denied");
+ return -1;
+ default:
+ return -1;
+ }
}
/* return a string describing last occurred dl error */
char *dlerror()
{
- return dlerr;
+ return dlerr;
}
diff --git a/PC/os2emx/dllentry.c b/PC/os2emx/dllentry.c
index dbf9c98..9ccca1c 100644
--- a/PC/os2emx/dllentry.c
+++ b/PC/os2emx/dllentry.c
@@ -4,7 +4,7 @@
#define NULL 0
-#define REF(s) extern void s(); void *____ref_##s = &s;
+#define REF(s) extern void s(); void *____ref_##s = &s;
/* Make references to imported symbols to pull them from static library */
REF(Py_Main);
@@ -18,25 +18,25 @@ extern void __ctordtorTerm(void);
unsigned long _DLL_InitTerm(unsigned long mod_handle, unsigned long flag)
{
- switch (flag)
- {
- case 0:
- if (_CRT_init())
- return 0;
- __ctordtorInit();
-
- /* Ignore fatal signals */
- signal(SIGSEGV, SIG_IGN);
- signal(SIGFPE, SIG_IGN);
-
- return 1;
-
- case 1:
- __ctordtorTerm();
- _CRT_term();
- return 1;
-
- default:
- return 0;
- }
+ switch (flag)
+ {
+ case 0:
+ if (_CRT_init())
+ return 0;
+ __ctordtorInit();
+
+ /* Ignore fatal signals */
+ signal(SIGSEGV, SIG_IGN);
+ signal(SIGFPE, SIG_IGN);
+
+ return 1;
+
+ case 1:
+ __ctordtorTerm();
+ _CRT_term();
+ return 1;
+
+ default:
+ return 0;
+ }
}
diff --git a/PC/os2emx/getpathp.c b/PC/os2emx/getpathp.c
index 5839eab..4faa505 100644
--- a/PC/os2emx/getpathp.c
+++ b/PC/os2emx/getpathp.c
@@ -4,8 +4,8 @@
/* ----------------------------------------------------------------
PATH RULES FOR OS/2+EMX:
- This describes how sys.path is formed on OS/2+EMX. It describes the
- functionality, not the implementation (ie, the order in which these
+ This describes how sys.path is formed on OS/2+EMX. It describes the
+ functionality, not the implementation (ie, the order in which these
are actually fetched is different)
* Python always adds an empty entry at the start, which corresponds
@@ -16,10 +16,10 @@
* We attempt to locate the "Python Home" - if the PYTHONHOME env var
is set, we believe it. Otherwise, we use the path of our host .EXE's
to try and locate our "landmark" (lib\\os.py) and deduce our home.
- - If we DO have a Python Home: The relevant sub-directories (Lib,
+ - If we DO have a Python Home: The relevant sub-directories (Lib,
plat-win, lib-tk, etc) are based on the Python Home
- If we DO NOT have a Python Home, the core Python Path is
- loaded from the registry. This is the main PythonPath key,
+ loaded from the registry. This is the main PythonPath key,
and both HKLM and HKCU are combined to form the path)
* Iff - we can not locate the Python Home, and have not had a PYTHONPATH
@@ -32,9 +32,9 @@
(either an installed version, or directly from the PCbuild directory),
the core path is deduced.
- * When Python is hosted in another exe (different directory, embedded via
+ * When Python is hosted in another exe (different directory, embedded via
COM, etc), the Python Home will not be deduced, so the core path from
- the registry is used. Other "application paths "in the registry are
+ the registry is used. Other "application paths "in the registry are
always read.
* If Python can't find its home and there is no registry (eg, frozen
@@ -85,12 +85,12 @@ static char *module_search_path = NULL;
static int
-is_sep(char ch) /* determine if "ch" is a separator character */
+is_sep(char ch) /* determine if "ch" is a separator character */
{
#ifdef ALTSEP
- return ch == SEP || ch == ALTSEP;
+ return ch == SEP || ch == ALTSEP;
#else
- return ch == SEP;
+ return ch == SEP;
#endif
}
@@ -100,36 +100,36 @@ is_sep(char ch) /* determine if "ch" is a separator character */
static void
reduce(char *dir)
{
- size_t i = strlen(dir);
- while (i > 0 && !is_sep(dir[i]))
- --i;
- dir[i] = '\0';
+ size_t i = strlen(dir);
+ while (i > 0 && !is_sep(dir[i]))
+ --i;
+ dir[i] = '\0';
}
-
+
static int
exists(char *filename)
{
- struct stat buf;
- return stat(filename, &buf) == 0;
+ struct stat buf;
+ return stat(filename, &buf) == 0;
}
/* Is module (check for .pyc/.pyo too)
- * Assumes 'filename' MAXPATHLEN+1 bytes long -
+ * Assumes 'filename' MAXPATHLEN+1 bytes long -
* may extend 'filename' by one character.
*/
static int
ismodule(char *filename)
{
- if (exists(filename))
- return 1;
-
- /* Check for the compiled version of prefix. */
- if (strlen(filename) < MAXPATHLEN) {
- strcat(filename, Py_OptimizeFlag ? "o" : "c");
- if (exists(filename))
- return 1;
- }
- return 0;
+ if (exists(filename))
+ return 1;
+
+ /* Check for the compiled version of prefix. */
+ if (strlen(filename) < MAXPATHLEN) {
+ strcat(filename, Py_OptimizeFlag ? "o" : "c");
+ if (exists(filename))
+ return 1;
+ }
+ return 0;
}
/* Add a path component, by appending stuff to buffer.
@@ -145,21 +145,21 @@ ismodule(char *filename)
static void
join(char *buffer, char *stuff)
{
- size_t n, k;
- if (is_sep(stuff[0]))
- n = 0;
- else {
- n = strlen(buffer);
- if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
- buffer[n++] = SEP;
- }
- if (n > MAXPATHLEN)
- Py_FatalError("buffer overflow in getpathp.c's joinpath()");
- k = strlen(stuff);
- if (n + k > MAXPATHLEN)
- k = MAXPATHLEN - n;
- strncpy(buffer+n, stuff, k);
- buffer[n+k] = '\0';
+ size_t n, k;
+ if (is_sep(stuff[0]))
+ n = 0;
+ else {
+ n = strlen(buffer);
+ if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
+ buffer[n++] = SEP;
+ }
+ if (n > MAXPATHLEN)
+ Py_FatalError("buffer overflow in getpathp.c's joinpath()");
+ k = strlen(stuff);
+ if (n + k > MAXPATHLEN)
+ k = MAXPATHLEN - n;
+ strncpy(buffer+n, stuff, k);
+ buffer[n+k] = '\0';
}
/* gotlandmark only called by search_for_prefix, which ensures
@@ -169,219 +169,219 @@ join(char *buffer, char *stuff)
static int
gotlandmark(char *landmark)
{
- int n, ok;
+ int n, ok;
- n = strlen(prefix);
- join(prefix, landmark);
- ok = ismodule(prefix);
- prefix[n] = '\0';
- return ok;
+ n = strlen(prefix);
+ join(prefix, landmark);
+ ok = ismodule(prefix);
+ prefix[n] = '\0';
+ return ok;
}
-/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
+/* assumes argv0_path is MAXPATHLEN+1 bytes long, already \0 term'd.
* assumption provided by only caller, calculate_path()
*/
static int
search_for_prefix(char *argv0_path, char *landmark)
{
- /* Search from argv0_path, until landmark is found */
- strcpy(prefix, argv0_path);
- do {
- if (gotlandmark(landmark))
- return 1;
- reduce(prefix);
- } while (prefix[0]);
- return 0;
+ /* Search from argv0_path, until landmark is found */
+ strcpy(prefix, argv0_path);
+ do {
+ if (gotlandmark(landmark))
+ return 1;
+ reduce(prefix);
+ } while (prefix[0]);
+ return 0;
}
static void
get_progpath(void)
{
- extern char *Py_GetProgramName(void);
- char *path = getenv("PATH");
- char *prog = Py_GetProgramName();
-
- PPIB pib;
- if ((DosGetInfoBlocks(NULL, &pib) == 0) &&
- (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0))
- return;
-
- if (prog == NULL || *prog == '\0')
- prog = "python";
-
- /* If there is no slash in the argv0 path, then we have to
- * assume python is on the user's $PATH, since there's no
- * other way to find a directory to start the search from. If
- * $PATH isn't exported, you lose.
- */
+ extern char *Py_GetProgramName(void);
+ char *path = getenv("PATH");
+ char *prog = Py_GetProgramName();
+
+ PPIB pib;
+ if ((DosGetInfoBlocks(NULL, &pib) == 0) &&
+ (DosQueryModuleName(pib->pib_hmte, sizeof(progpath), progpath) == 0))
+ return;
+
+ if (prog == NULL || *prog == '\0')
+ prog = "python";
+
+ /* If there is no slash in the argv0 path, then we have to
+ * assume python is on the user's $PATH, since there's no
+ * other way to find a directory to start the search from. If
+ * $PATH isn't exported, you lose.
+ */
#ifdef ALTSEP
- if (strchr(prog, SEP) || strchr(prog, ALTSEP))
+ if (strchr(prog, SEP) || strchr(prog, ALTSEP))
#else
- if (strchr(prog, SEP))
+ if (strchr(prog, SEP))
#endif
- strncpy(progpath, prog, MAXPATHLEN);
- else if (path) {
- while (1) {
- char *delim = strchr(path, DELIM);
-
- if (delim) {
- size_t len = delim - path;
- /* ensure we can't overwrite buffer */
+ strncpy(progpath, prog, MAXPATHLEN);
+ else if (path) {
+ while (1) {
+ char *delim = strchr(path, DELIM);
+
+ if (delim) {
+ size_t len = delim - path;
+ /* ensure we can't overwrite buffer */
#if !defined(PYCC_GCC)
- len = min(MAXPATHLEN,len);
+ len = min(MAXPATHLEN,len);
#else
- len = MAXPATHLEN < len ? MAXPATHLEN : len;
+ len = MAXPATHLEN < len ? MAXPATHLEN : len;
#endif
- strncpy(progpath, path, len);
- *(progpath + len) = '\0';
- }
- else
- strncpy(progpath, path, MAXPATHLEN);
-
- /* join() is safe for MAXPATHLEN+1 size buffer */
- join(progpath, prog);
- if (exists(progpath))
- break;
-
- if (!delim) {
- progpath[0] = '\0';
- break;
- }
- path = delim + 1;
- }
- }
- else
- progpath[0] = '\0';
+ strncpy(progpath, path, len);
+ *(progpath + len) = '\0';
+ }
+ else
+ strncpy(progpath, path, MAXPATHLEN);
+
+ /* join() is safe for MAXPATHLEN+1 size buffer */
+ join(progpath, prog);
+ if (exists(progpath))
+ break;
+
+ if (!delim) {
+ progpath[0] = '\0';
+ break;
+ }
+ path = delim + 1;
+ }
+ }
+ else
+ progpath[0] = '\0';
}
static void
calculate_path(void)
{
- char argv0_path[MAXPATHLEN+1];
- char *buf;
- size_t bufsz;
- char *pythonhome = Py_GetPythonHome();
- char *envpath = getenv("PYTHONPATH");
- char zip_path[MAXPATHLEN+1];
- size_t len;
-
- get_progpath();
- /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
- strcpy(argv0_path, progpath);
- reduce(argv0_path);
- if (pythonhome == NULL || *pythonhome == '\0') {
- if (search_for_prefix(argv0_path, LANDMARK))
- pythonhome = prefix;
- else
- pythonhome = NULL;
- }
- else
- strncpy(prefix, pythonhome, MAXPATHLEN);
-
- if (envpath && *envpath == '\0')
- envpath = NULL;
-
- /* Calculate zip archive path */
- strncpy(zip_path, progpath, MAXPATHLEN);
- zip_path[MAXPATHLEN] = '\0';
- len = strlen(zip_path);
- if (len > 4) {
- zip_path[len-3] = 'z'; /* change ending to "zip" */
- zip_path[len-2] = 'i';
- zip_path[len-1] = 'p';
- }
- else {
- zip_path[0] = 0;
- }
-
- /* We need to construct a path from the following parts.
- * (1) the PYTHONPATH environment variable, if set;
- * (2) the zip archive file path;
- * (3) the PYTHONPATH config macro, with the leading "."
- * of each component replaced with pythonhome, if set;
- * (4) the directory containing the executable (argv0_path).
- * The length calculation calculates #3 first.
- */
-
- /* Calculate size of return buffer */
- if (pythonhome != NULL) {
- char *p;
- bufsz = 1;
- for (p = PYTHONPATH; *p; p++) {
- if (*p == DELIM)
- bufsz++; /* number of DELIM plus one */
- }
- bufsz *= strlen(pythonhome);
- }
- else
- bufsz = 0;
- bufsz += strlen(PYTHONPATH) + 1;
- bufsz += strlen(argv0_path) + 1;
- bufsz += strlen(zip_path) + 1;
- if (envpath != NULL)
- bufsz += strlen(envpath) + 1;
-
- module_search_path = buf = malloc(bufsz);
- if (buf == NULL) {
- /* We can't exit, so print a warning and limp along */
- fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
- if (envpath) {
- fprintf(stderr, "Using environment $PYTHONPATH.\n");
- module_search_path = envpath;
- }
- else {
- fprintf(stderr, "Using default static path.\n");
- module_search_path = PYTHONPATH;
- }
- return;
- }
-
- if (envpath) {
- strcpy(buf, envpath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
- if (zip_path[0]) {
- strcpy(buf, zip_path);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
-
- if (pythonhome == NULL) {
- strcpy(buf, PYTHONPATH);
- buf = strchr(buf, '\0');
- }
- else {
- char *p = PYTHONPATH;
- char *q;
- size_t n;
- for (;;) {
- q = strchr(p, DELIM);
- if (q == NULL)
- n = strlen(p);
- else
- n = q-p;
- if (p[0] == '.' && is_sep(p[1])) {
- strcpy(buf, pythonhome);
- buf = strchr(buf, '\0');
- p++;
- n--;
- }
- strncpy(buf, p, n);
- buf += n;
- if (q == NULL)
- break;
- *buf++ = DELIM;
- p = q+1;
- }
- }
- if (argv0_path) {
- *buf++ = DELIM;
- strcpy(buf, argv0_path);
- buf = strchr(buf, '\0');
- }
- *buf = '\0';
+ char argv0_path[MAXPATHLEN+1];
+ char *buf;
+ size_t bufsz;
+ char *pythonhome = Py_GetPythonHome();
+ char *envpath = getenv("PYTHONPATH");
+ char zip_path[MAXPATHLEN+1];
+ size_t len;
+
+ get_progpath();
+ /* progpath guaranteed \0 terminated in MAXPATH+1 bytes. */
+ strcpy(argv0_path, progpath);
+ reduce(argv0_path);
+ if (pythonhome == NULL || *pythonhome == '\0') {
+ if (search_for_prefix(argv0_path, LANDMARK))
+ pythonhome = prefix;
+ else
+ pythonhome = NULL;
+ }
+ else
+ strncpy(prefix, pythonhome, MAXPATHLEN);
+
+ if (envpath && *envpath == '\0')
+ envpath = NULL;
+
+ /* Calculate zip archive path */
+ strncpy(zip_path, progpath, MAXPATHLEN);
+ zip_path[MAXPATHLEN] = '\0';
+ len = strlen(zip_path);
+ if (len > 4) {
+ zip_path[len-3] = 'z'; /* change ending to "zip" */
+ zip_path[len-2] = 'i';
+ zip_path[len-1] = 'p';
+ }
+ else {
+ zip_path[0] = 0;
+ }
+
+ /* We need to construct a path from the following parts.
+ * (1) the PYTHONPATH environment variable, if set;
+ * (2) the zip archive file path;
+ * (3) the PYTHONPATH config macro, with the leading "."
+ * of each component replaced with pythonhome, if set;
+ * (4) the directory containing the executable (argv0_path).
+ * The length calculation calculates #3 first.
+ */
+
+ /* Calculate size of return buffer */
+ if (pythonhome != NULL) {
+ char *p;
+ bufsz = 1;
+ for (p = PYTHONPATH; *p; p++) {
+ if (*p == DELIM)
+ bufsz++; /* number of DELIM plus one */
+ }
+ bufsz *= strlen(pythonhome);
+ }
+ else
+ bufsz = 0;
+ bufsz += strlen(PYTHONPATH) + 1;
+ bufsz += strlen(argv0_path) + 1;
+ bufsz += strlen(zip_path) + 1;
+ if (envpath != NULL)
+ bufsz += strlen(envpath) + 1;
+
+ module_search_path = buf = malloc(bufsz);
+ if (buf == NULL) {
+ /* We can't exit, so print a warning and limp along */
+ fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
+ if (envpath) {
+ fprintf(stderr, "Using environment $PYTHONPATH.\n");
+ module_search_path = envpath;
+ }
+ else {
+ fprintf(stderr, "Using default static path.\n");
+ module_search_path = PYTHONPATH;
+ }
+ return;
+ }
+
+ if (envpath) {
+ strcpy(buf, envpath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
+ if (zip_path[0]) {
+ strcpy(buf, zip_path);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
+
+ if (pythonhome == NULL) {
+ strcpy(buf, PYTHONPATH);
+ buf = strchr(buf, '\0');
+ }
+ else {
+ char *p = PYTHONPATH;
+ char *q;
+ size_t n;
+ for (;;) {
+ q = strchr(p, DELIM);
+ if (q == NULL)
+ n = strlen(p);
+ else
+ n = q-p;
+ if (p[0] == '.' && is_sep(p[1])) {
+ strcpy(buf, pythonhome);
+ buf = strchr(buf, '\0');
+ p++;
+ n--;
+ }
+ strncpy(buf, p, n);
+ buf += n;
+ if (q == NULL)
+ break;
+ *buf++ = DELIM;
+ p = q+1;
+ }
+ }
+ if (argv0_path) {
+ *buf++ = DELIM;
+ strcpy(buf, argv0_path);
+ buf = strchr(buf, '\0');
+ }
+ *buf = '\0';
}
@@ -390,29 +390,29 @@ calculate_path(void)
char *
Py_GetPath(void)
{
- if (!module_search_path)
- calculate_path();
- return module_search_path;
+ if (!module_search_path)
+ calculate_path();
+ return module_search_path;
}
char *
Py_GetPrefix(void)
{
- if (!module_search_path)
- calculate_path();
- return prefix;
+ if (!module_search_path)
+ calculate_path();
+ return prefix;
}
char *
Py_GetExecPrefix(void)
{
- return Py_GetPrefix();
+ return Py_GetPrefix();
}
char *
Py_GetProgramFullPath(void)
{
- if (!module_search_path)
- calculate_path();
- return progpath;
+ if (!module_search_path)
+ calculate_path();
+ return progpath;
}
diff --git a/PC/os2emx/pythonpm.c b/PC/os2emx/pythonpm.c
index 5accbbd..ba47f4b 100644
--- a/PC/os2emx/pythonpm.c
+++ b/PC/os2emx/pythonpm.c
@@ -27,10 +27,10 @@
/* use structure to pass command line to Python thread */
typedef struct
{
- int argc;
- char **argv;
- HWND Frame;
- int running;
+ int argc;
+ char **argv;
+ HWND Frame;
+ int running;
} arglist;
/* make this a global to simplify access.
@@ -45,80 +45,80 @@ void PythonThread(void *);
int
main(int argc, char **argv)
{
- ULONG FrameFlags = FCF_TITLEBAR |
- FCF_SYSMENU |
- FCF_SIZEBORDER |
- FCF_HIDEBUTTON |
- FCF_SHELLPOSITION |
- FCF_TASKLIST;
- HAB hab;
- HMQ hmq;
- HWND Client;
- QMSG qmsg;
- arglist args;
- int python_tid;
-
- /* init PM and create message queue */
- hab = WinInitialize(0);
- hmq = WinCreateMsgQueue(hab, 0);
-
- /* create a (hidden) Window to house the window procedure */
- args.Frame = WinCreateStdWindow(HWND_DESKTOP,
- 0,
- &FrameFlags,
- NULL,
- "PythonPM",
- 0L,
- 0,
- 0,
- &Client);
-
- /* run Python interpreter in a thread */
- args.argc = argc;
- args.argv = argv;
- args.running = 0;
- if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args)))
- {
- /* couldn't start thread */
- WinAlarm(HWND_DESKTOP, WA_ERROR);
- PythonRC = 1;
- }
- else
- {
- /* process PM messages, until Python exits */
- while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0))
- WinDispatchMsg(hab, &qmsg);
- if (args.running > 0)
- DosKillThread(python_tid);
- }
-
- /* destroy window, shutdown message queue and PM */
- WinDestroyWindow(args.Frame);
- WinDestroyMsgQueue(hmq);
- WinTerminate(hab);
-
- return PythonRC;
+ ULONG FrameFlags = FCF_TITLEBAR |
+ FCF_SYSMENU |
+ FCF_SIZEBORDER |
+ FCF_HIDEBUTTON |
+ FCF_SHELLPOSITION |
+ FCF_TASKLIST;
+ HAB hab;
+ HMQ hmq;
+ HWND Client;
+ QMSG qmsg;
+ arglist args;
+ int python_tid;
+
+ /* init PM and create message queue */
+ hab = WinInitialize(0);
+ hmq = WinCreateMsgQueue(hab, 0);
+
+ /* create a (hidden) Window to house the window procedure */
+ args.Frame = WinCreateStdWindow(HWND_DESKTOP,
+ 0,
+ &FrameFlags,
+ NULL,
+ "PythonPM",
+ 0L,
+ 0,
+ 0,
+ &Client);
+
+ /* run Python interpreter in a thread */
+ args.argc = argc;
+ args.argv = argv;
+ args.running = 0;
+ if (-1 == (python_tid = _beginthread(PythonThread, NULL, 1024 * 1024, &args)))
+ {
+ /* couldn't start thread */
+ WinAlarm(HWND_DESKTOP, WA_ERROR);
+ PythonRC = 1;
+ }
+ else
+ {
+ /* process PM messages, until Python exits */
+ while (WinGetMsg(hab, &qmsg, NULLHANDLE, 0, 0))
+ WinDispatchMsg(hab, &qmsg);
+ if (args.running > 0)
+ DosKillThread(python_tid);
+ }
+
+ /* destroy window, shutdown message queue and PM */
+ WinDestroyWindow(args.Frame);
+ WinDestroyMsgQueue(hmq);
+ WinTerminate(hab);
+
+ return PythonRC;
}
void PythonThread(void *argl)
{
- HAB hab;
- arglist *args;
+ HAB hab;
+ arglist *args;
- /* PM initialisation */
- hab = WinInitialize(0);
+ /* PM initialisation */
+ hab = WinInitialize(0);
- /* start Python */
- args = (arglist *)argl;
- args->running = 1;
- PythonRC = Py_Main(args->argc, args->argv);
+ /* start Python */
+ args = (arglist *)argl;
+ args->running = 1;
+ PythonRC = Py_Main(args->argc, args->argv);
- /* enter a critical section and send the termination message */
- DosEnterCritSec();
- args->running = 0;
- WinPostMsg(args->Frame, WM_QUIT, NULL, NULL);
+ /* enter a critical section and send the termination message */
+ DosEnterCritSec();
+ args->running = 0;
+ WinPostMsg(args->Frame, WM_QUIT, NULL, NULL);
- /* shutdown PM and terminate thread */
- WinTerminate(hab);
- _endthread();
+ /* shutdown PM and terminate thread */
+ WinTerminate(hab);
+ _endthread();
}
diff --git a/PC/os2vacpp/getpathp.c b/PC/os2vacpp/getpathp.c
index 607f2a1..5bc2827 100644
--- a/PC/os2vacpp/getpathp.c
+++ b/PC/os2vacpp/getpathp.c
@@ -55,12 +55,12 @@ static char *module_search_path = NULL;
static int
-is_sep(char ch) /* determine if "ch" is a separator character */
+is_sep(char ch) /* determine if "ch" is a separator character */
{
#ifdef ALTSEP
- return ch == SEP || ch == ALTSEP;
+ return ch == SEP || ch == ALTSEP;
#else
- return ch == SEP;
+ return ch == SEP;
#endif
}
@@ -68,18 +68,18 @@ is_sep(char ch) /* determine if "ch" is a separator character */
static void
reduce(char *dir)
{
- int i = strlen(dir);
- while (i > 0 && !is_sep(dir[i]))
- --i;
- dir[i] = '\0';
+ int i = strlen(dir);
+ while (i > 0 && !is_sep(dir[i]))
+ --i;
+ dir[i] = '\0';
}
-
+
static int
exists(char *filename)
{
- struct stat buf;
- return stat(filename, &buf) == 0;
+ struct stat buf;
+ return stat(filename, &buf) == 0;
}
@@ -95,42 +95,42 @@ exists(char *filename)
static void
join(char *buffer, char *stuff)
{
- int n, k;
- if (is_sep(stuff[0]))
- n = 0;
- else {
- n = strlen(buffer);
- if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
- buffer[n++] = SEP;
- }
- if (n > MAXPATHLEN)
- Py_FatalError("buffer overflow in getpathp.c's joinpath()");
- k = strlen(stuff);
- if (n + k > MAXPATHLEN)
- k = MAXPATHLEN - n;
- strncpy(buffer+n, stuff, k);
- buffer[n+k] = '\0';
+ int n, k;
+ if (is_sep(stuff[0]))
+ n = 0;
+ else {
+ n = strlen(buffer);
+ if (n > 0 && !is_sep(buffer[n-1]) && n < MAXPATHLEN)
+ buffer[n++] = SEP;
+ }
+ if (n > MAXPATHLEN)
+ Py_FatalError("buffer overflow in getpathp.c's joinpath()");
+ k = strlen(stuff);
+ if (n + k > MAXPATHLEN)
+ k = MAXPATHLEN - n;
+ strncpy(buffer+n, stuff, k);
+ buffer[n+k] = '\0';
}
static int
search_for_prefix(char *argv0_path, char *landmark)
{
- int n;
-
- /* Search from argv0_path, until root is found */
- strcpy(prefix, argv0_path);
- do {
- n = strlen(prefix);
- join(prefix, landmark);
- if (exists(prefix)) {
- prefix[n] = '\0';
- return 1;
- }
- prefix[n] = '\0';
- reduce(prefix);
- } while (prefix[0]);
- return 0;
+ int n;
+
+ /* Search from argv0_path, until root is found */
+ strcpy(prefix, argv0_path);
+ do {
+ n = strlen(prefix);
+ join(prefix, landmark);
+ if (exists(prefix)) {
+ prefix[n] = '\0';
+ return 1;
+ }
+ prefix[n] = '\0';
+ reduce(prefix);
+ } while (prefix[0]);
+ return 0;
}
#ifdef MS_WIN32
@@ -147,299 +147,299 @@ extern const char *PyWin_DLLVersionString; // a string loaded from the DLL at st
static char *
getpythonregpath(HKEY keyBase, BOOL bWin32s)
{
- HKEY newKey = 0;
- DWORD nameSize = 0;
- DWORD dataSize = 0;
- DWORD numEntries = 0;
- LONG rc;
- char *retval = NULL;
- char *dataBuf;
- const char keyPrefix[] = "Software\\Python\\PythonCore\\";
- const char keySuffix[] = "\\PythonPath";
- int versionLen;
- char *keyBuf;
-
- // Tried to use sysget("winver") but here is too early :-(
- versionLen = strlen(PyWin_DLLVersionString);
- // alloca == no free required, but memory only local to fn.
- // also no heap fragmentation! Am I being silly?
- keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL.
- // lots of constants here for the compiler to optimize away :-)
- memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1);
- memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen);
- memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one!
-
- rc=RegOpenKey(keyBase,
- keyBuf,
- &newKey);
- if (rc==ERROR_SUCCESS) {
- RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL,
- &numEntries, &nameSize, &dataSize, NULL, NULL);
- }
- if (bWin32s && numEntries==0 && dataSize==0) {
- /* must hardcode for Win32s */
- numEntries = 1;
- dataSize = 511;
- }
- if (numEntries) {
- /* Loop over all subkeys. */
- /* Win32s doesnt know how many subkeys, so we do
- it twice */
- char keyBuf[MAX_PATH+1];
- int index = 0;
- int off = 0;
- for(index=0;;index++) {
- long reqdSize = 0;
- DWORD rc = RegEnumKey(newKey,
- index, keyBuf, MAX_PATH+1);
- if (rc) break;
- rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize);
- if (rc) break;
- if (bWin32s && reqdSize==0) reqdSize = 512;
- dataSize += reqdSize + 1; /* 1 for the ";" */
- }
- dataBuf = malloc(dataSize+1);
- if (dataBuf==NULL)
- return NULL; /* pretty serious? Raise error? */
- /* Now loop over, grabbing the paths.
- Subkeys before main library */
- for(index=0;;index++) {
- int adjust;
- long reqdSize = dataSize;
- DWORD rc = RegEnumKey(newKey,
- index, keyBuf,MAX_PATH+1);
- if (rc) break;
- rc = RegQueryValue(newKey,
- keyBuf, dataBuf+off, &reqdSize);
- if (rc) break;
- if (reqdSize>1) {
- /* If Nothing, or only '\0' copied. */
- adjust = strlen(dataBuf+off);
- dataSize -= adjust;
- off += adjust;
- dataBuf[off++] = ';';
- dataBuf[off] = '\0';
- dataSize--;
- }
- }
- /* Additionally, win32s doesnt work as expected, so
- the specific strlen() is required for 3.1. */
- rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize);
- if (rc==ERROR_SUCCESS) {
- if (strlen(dataBuf)==0)
- free(dataBuf);
- else
- retval = dataBuf; /* caller will free */
- }
- else
- free(dataBuf);
- }
-
- if (newKey)
- RegCloseKey(newKey);
- return retval;
+ HKEY newKey = 0;
+ DWORD nameSize = 0;
+ DWORD dataSize = 0;
+ DWORD numEntries = 0;
+ LONG rc;
+ char *retval = NULL;
+ char *dataBuf;
+ const char keyPrefix[] = "Software\\Python\\PythonCore\\";
+ const char keySuffix[] = "\\PythonPath";
+ int versionLen;
+ char *keyBuf;
+
+ // Tried to use sysget("winver") but here is too early :-(
+ versionLen = strlen(PyWin_DLLVersionString);
+ // alloca == no free required, but memory only local to fn.
+ // also no heap fragmentation! Am I being silly?
+ keyBuf = alloca(sizeof(keyPrefix)-1 + versionLen + sizeof(keySuffix)); // chars only, plus 1 NULL.
+ // lots of constants here for the compiler to optimize away :-)
+ memcpy(keyBuf, keyPrefix, sizeof(keyPrefix)-1);
+ memcpy(keyBuf+sizeof(keyPrefix)-1, PyWin_DLLVersionString, versionLen);
+ memcpy(keyBuf+sizeof(keyPrefix)-1+versionLen, keySuffix, sizeof(keySuffix)); // NULL comes with this one!
+
+ rc=RegOpenKey(keyBase,
+ keyBuf,
+ &newKey);
+ if (rc==ERROR_SUCCESS) {
+ RegQueryInfoKey(newKey, NULL, NULL, NULL, NULL, NULL, NULL,
+ &numEntries, &nameSize, &dataSize, NULL, NULL);
+ }
+ if (bWin32s && numEntries==0 && dataSize==0) {
+ /* must hardcode for Win32s */
+ numEntries = 1;
+ dataSize = 511;
+ }
+ if (numEntries) {
+ /* Loop over all subkeys. */
+ /* Win32s doesnt know how many subkeys, so we do
+ it twice */
+ char keyBuf[MAX_PATH+1];
+ int index = 0;
+ int off = 0;
+ for(index=0;;index++) {
+ long reqdSize = 0;
+ DWORD rc = RegEnumKey(newKey,
+ index, keyBuf, MAX_PATH+1);
+ if (rc) break;
+ rc = RegQueryValue(newKey, keyBuf, NULL, &reqdSize);
+ if (rc) break;
+ if (bWin32s && reqdSize==0) reqdSize = 512;
+ dataSize += reqdSize + 1; /* 1 for the ";" */
+ }
+ dataBuf = malloc(dataSize+1);
+ if (dataBuf==NULL)
+ return NULL; /* pretty serious? Raise error? */
+ /* Now loop over, grabbing the paths.
+ Subkeys before main library */
+ for(index=0;;index++) {
+ int adjust;
+ long reqdSize = dataSize;
+ DWORD rc = RegEnumKey(newKey,
+ index, keyBuf,MAX_PATH+1);
+ if (rc) break;
+ rc = RegQueryValue(newKey,
+ keyBuf, dataBuf+off, &reqdSize);
+ if (rc) break;
+ if (reqdSize>1) {
+ /* If Nothing, or only '\0' copied. */
+ adjust = strlen(dataBuf+off);
+ dataSize -= adjust;
+ off += adjust;
+ dataBuf[off++] = ';';
+ dataBuf[off] = '\0';
+ dataSize--;
+ }
+ }
+ /* Additionally, win32s doesnt work as expected, so
+ the specific strlen() is required for 3.1. */
+ rc = RegQueryValue(newKey, "", dataBuf+off, &dataSize);
+ if (rc==ERROR_SUCCESS) {
+ if (strlen(dataBuf)==0)
+ free(dataBuf);
+ else
+ retval = dataBuf; /* caller will free */
+ }
+ else
+ free(dataBuf);
+ }
+
+ if (newKey)
+ RegCloseKey(newKey);
+ return retval;
}
#endif /* MS_WIN32 */
static void
get_progpath(void)
{
- extern char *Py_GetProgramName(void);
- char *path = getenv("PATH");
- char *prog = Py_GetProgramName();
+ extern char *Py_GetProgramName(void);
+ char *path = getenv("PATH");
+ char *prog = Py_GetProgramName();
#ifdef MS_WIN32
- if (GetModuleFileName(NULL, progpath, MAXPATHLEN))
- return;
+ if (GetModuleFileName(NULL, progpath, MAXPATHLEN))
+ return;
#endif
- if (prog == NULL || *prog == '\0')
- prog = "python";
-
- /* If there is no slash in the argv0 path, then we have to
- * assume python is on the user's $PATH, since there's no
- * other way to find a directory to start the search from. If
- * $PATH isn't exported, you lose.
- */
+ if (prog == NULL || *prog == '\0')
+ prog = "python";
+
+ /* If there is no slash in the argv0 path, then we have to
+ * assume python is on the user's $PATH, since there's no
+ * other way to find a directory to start the search from. If
+ * $PATH isn't exported, you lose.
+ */
#ifdef ALTSEP
- if (strchr(prog, SEP) || strchr(prog, ALTSEP))
+ if (strchr(prog, SEP) || strchr(prog, ALTSEP))
#else
- if (strchr(prog, SEP))
+ if (strchr(prog, SEP))
#endif
- strcpy(progpath, prog);
- else if (path) {
- while (1) {
- char *delim = strchr(path, DELIM);
-
- if (delim) {
- int len = delim - path;
- strncpy(progpath, path, len);
- *(progpath + len) = '\0';
- }
- else
- strcpy(progpath, path);
-
- join(progpath, prog);
- if (exists(progpath))
- break;
-
- if (!delim) {
- progpath[0] = '\0';
- break;
- }
- path = delim + 1;
- }
- }
- else
- progpath[0] = '\0';
+ strcpy(progpath, prog);
+ else if (path) {
+ while (1) {
+ char *delim = strchr(path, DELIM);
+
+ if (delim) {
+ int len = delim - path;
+ strncpy(progpath, path, len);
+ *(progpath + len) = '\0';
+ }
+ else
+ strcpy(progpath, path);
+
+ join(progpath, prog);
+ if (exists(progpath))
+ break;
+
+ if (!delim) {
+ progpath[0] = '\0';
+ break;
+ }
+ path = delim + 1;
+ }
+ }
+ else
+ progpath[0] = '\0';
}
static void
calculate_path(void)
{
- char argv0_path[MAXPATHLEN+1];
- char *buf;
- int bufsz;
- char *pythonhome = Py_GetPythonHome();
- char *envpath = Py_GETENV("PYTHONPATH");
+ char argv0_path[MAXPATHLEN+1];
+ char *buf;
+ int bufsz;
+ char *pythonhome = Py_GetPythonHome();
+ char *envpath = Py_GETENV("PYTHONPATH");
#ifdef MS_WIN32
- char *machinepath, *userpath;
-
- /* Are we running under Windows 3.1(1) Win32s? */
- if (PyWin_IsWin32s()) {
- /* Only CLASSES_ROOT is supported */
- machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE);
- userpath = NULL;
- } else {
- machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE);
- userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE);
- }
+ char *machinepath, *userpath;
+
+ /* Are we running under Windows 3.1(1) Win32s? */
+ if (PyWin_IsWin32s()) {
+ /* Only CLASSES_ROOT is supported */
+ machinepath = getpythonregpath(HKEY_CLASSES_ROOT, TRUE);
+ userpath = NULL;
+ } else {
+ machinepath = getpythonregpath(HKEY_LOCAL_MACHINE, FALSE);
+ userpath = getpythonregpath(HKEY_CURRENT_USER, FALSE);
+ }
#endif
- get_progpath();
- strcpy(argv0_path, progpath);
- reduce(argv0_path);
- if (pythonhome == NULL || *pythonhome == '\0') {
- if (search_for_prefix(argv0_path, LANDMARK))
- pythonhome = prefix;
- else
- pythonhome = NULL;
- }
- else {
- char *delim;
-
- strcpy(prefix, pythonhome);
-
- /* Extract Any Optional Trailing EXEC_PREFIX */
- /* e.g. PYTHONHOME=<prefix>:<exec_prefix> */
- delim = strchr(prefix, DELIM);
- if (delim) {
- *delim = '\0';
- strcpy(exec_prefix, delim+1);
- } else
- strcpy(exec_prefix, EXEC_PREFIX);
+ get_progpath();
+ strcpy(argv0_path, progpath);
+ reduce(argv0_path);
+ if (pythonhome == NULL || *pythonhome == '\0') {
+ if (search_for_prefix(argv0_path, LANDMARK))
+ pythonhome = prefix;
+ else
+ pythonhome = NULL;
+ }
+ else {
+ char *delim;
+
+ strcpy(prefix, pythonhome);
+
+ /* Extract Any Optional Trailing EXEC_PREFIX */
+ /* e.g. PYTHONHOME=<prefix>:<exec_prefix> */
+ delim = strchr(prefix, DELIM);
+ if (delim) {
+ *delim = '\0';
+ strcpy(exec_prefix, delim+1);
+ } else
+ strcpy(exec_prefix, EXEC_PREFIX);
}
- if (envpath && *envpath == '\0')
- envpath = NULL;
-
- /* We need to construct a path from the following parts:
- (1) the PYTHONPATH environment variable, if set;
- (2) for Win32, the machinepath and userpath, if set;
- (3) the PYTHONPATH config macro, with the leading "."
- of each component replaced with pythonhome, if set;
- (4) the directory containing the executable (argv0_path).
- The length calculation calculates #3 first.
- */
-
- /* Calculate size of return buffer */
- if (pythonhome != NULL) {
- char *p;
- bufsz = 1;
- for (p = PYTHONPATH; *p; p++) {
- if (*p == DELIM)
- bufsz++; /* number of DELIM plus one */
- }
- bufsz *= strlen(pythonhome);
- }
- else
- bufsz = 0;
- bufsz += strlen(PYTHONPATH) + 1;
- if (envpath != NULL)
- bufsz += strlen(envpath) + 1;
- bufsz += strlen(argv0_path) + 1;
+ if (envpath && *envpath == '\0')
+ envpath = NULL;
+
+ /* We need to construct a path from the following parts:
+ (1) the PYTHONPATH environment variable, if set;
+ (2) for Win32, the machinepath and userpath, if set;
+ (3) the PYTHONPATH config macro, with the leading "."
+ of each component replaced with pythonhome, if set;
+ (4) the directory containing the executable (argv0_path).
+ The length calculation calculates #3 first.
+ */
+
+ /* Calculate size of return buffer */
+ if (pythonhome != NULL) {
+ char *p;
+ bufsz = 1;
+ for (p = PYTHONPATH; *p; p++) {
+ if (*p == DELIM)
+ bufsz++; /* number of DELIM plus one */
+ }
+ bufsz *= strlen(pythonhome);
+ }
+ else
+ bufsz = 0;
+ bufsz += strlen(PYTHONPATH) + 1;
+ if (envpath != NULL)
+ bufsz += strlen(envpath) + 1;
+ bufsz += strlen(argv0_path) + 1;
#ifdef MS_WIN32
- if (machinepath)
- bufsz += strlen(machinepath) + 1;
- if (userpath)
- bufsz += strlen(userpath) + 1;
+ if (machinepath)
+ bufsz += strlen(machinepath) + 1;
+ if (userpath)
+ bufsz += strlen(userpath) + 1;
#endif
- module_search_path = buf = malloc(bufsz);
- if (buf == NULL) {
- /* We can't exit, so print a warning and limp along */
- fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
- if (envpath) {
- fprintf(stderr, "Using default static $PYTHONPATH.\n");
- module_search_path = envpath;
- }
- else {
- fprintf(stderr, "Using environment $PYTHONPATH.\n");
- module_search_path = PYTHONPATH;
- }
- return;
- }
-
- if (envpath) {
- strcpy(buf, envpath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
+ module_search_path = buf = malloc(bufsz);
+ if (buf == NULL) {
+ /* We can't exit, so print a warning and limp along */
+ fprintf(stderr, "Can't malloc dynamic PYTHONPATH.\n");
+ if (envpath) {
+ fprintf(stderr, "Using default static $PYTHONPATH.\n");
+ module_search_path = envpath;
+ }
+ else {
+ fprintf(stderr, "Using environment $PYTHONPATH.\n");
+ module_search_path = PYTHONPATH;
+ }
+ return;
+ }
+
+ if (envpath) {
+ strcpy(buf, envpath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
#ifdef MS_WIN32
- if (machinepath) {
- strcpy(buf, machinepath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
- if (userpath) {
- strcpy(buf, userpath);
- buf = strchr(buf, '\0');
- *buf++ = DELIM;
- }
+ if (machinepath) {
+ strcpy(buf, machinepath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
+ if (userpath) {
+ strcpy(buf, userpath);
+ buf = strchr(buf, '\0');
+ *buf++ = DELIM;
+ }
#endif
- if (pythonhome == NULL) {
- strcpy(buf, PYTHONPATH);
- buf = strchr(buf, '\0');
- }
- else {
- char *p = PYTHONPATH;
- char *q;
- int n;
- for (;;) {
- q = strchr(p, DELIM);
- if (q == NULL)
- n = strlen(p);
- else
- n = q-p;
- if (p[0] == '.' && is_sep(p[1])) {
- strcpy(buf, pythonhome);
- buf = strchr(buf, '\0');
- p++;
- n--;
- }
- strncpy(buf, p, n);
- buf += n;
- if (q == NULL)
- break;
- *buf++ = DELIM;
- p = q+1;
- }
- }
- if (argv0_path) {
- *buf++ = DELIM;
- strcpy(buf, argv0_path);
- buf = strchr(buf, '\0');
- }
- *buf = '\0';
+ if (pythonhome == NULL) {
+ strcpy(buf, PYTHONPATH);
+ buf = strchr(buf, '\0');
+ }
+ else {
+ char *p = PYTHONPATH;
+ char *q;
+ int n;
+ for (;;) {
+ q = strchr(p, DELIM);
+ if (q == NULL)
+ n = strlen(p);
+ else
+ n = q-p;
+ if (p[0] == '.' && is_sep(p[1])) {
+ strcpy(buf, pythonhome);
+ buf = strchr(buf, '\0');
+ p++;
+ n--;
+ }
+ strncpy(buf, p, n);
+ buf += n;
+ if (q == NULL)
+ break;
+ *buf++ = DELIM;
+ p = q+1;
+ }
+ }
+ if (argv0_path) {
+ *buf++ = DELIM;
+ strcpy(buf, argv0_path);
+ buf = strchr(buf, '\0');
+ }
+ *buf = '\0';
}
@@ -448,35 +448,35 @@ calculate_path(void)
char *
Py_GetPath(void)
{
- if (!module_search_path)
- calculate_path();
+ if (!module_search_path)
+ calculate_path();
- return module_search_path;
+ return module_search_path;
}
char *
Py_GetPrefix(void)
{
- if (!module_search_path)
- calculate_path();
+ if (!module_search_path)
+ calculate_path();
- return prefix;
+ return prefix;
}
char *
Py_GetExecPrefix(void)
{
- if (!module_search_path)
- calculate_path();
+ if (!module_search_path)
+ calculate_path();
- return exec_prefix;
+ return exec_prefix;
}
char *
Py_GetProgramFullPath(void)
{
- if (!module_search_path)
- calculate_path();
+ if (!module_search_path)
+ calculate_path();
- return progpath;
+ return progpath;
}
diff --git a/PC/winsound.c b/PC/winsound.c
index e6ff226..05305d2 100644
--- a/PC/winsound.c
+++ b/PC/winsound.c
@@ -78,14 +78,14 @@ sound_playsound(PyObject *s, PyObject *args)
int ok;
if(!PyArg_ParseTuple(args,"z#i:PlaySound",&sound,&length,&flags)) {
- return NULL;
+ return NULL;
}
if(flags&SND_ASYNC && flags &SND_MEMORY) {
- /* Sidestep reference counting headache; unfortunately this also
- prevent SND_LOOP from memory. */
- PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory");
- return NULL;
+ /* Sidestep reference counting headache; unfortunately this also
+ prevent SND_LOOP from memory. */
+ PyErr_SetString(PyExc_RuntimeError,"Cannot play asynchronously from memory");
+ return NULL;
}
Py_BEGIN_ALLOW_THREADS
@@ -93,8 +93,8 @@ sound_playsound(PyObject *s, PyObject *args)
Py_END_ALLOW_THREADS
if(!ok)
{
- PyErr_SetString(PyExc_RuntimeError,"Failed to play sound");
- return NULL;
+ PyErr_SetString(PyExc_RuntimeError,"Failed to play sound");
+ return NULL;
}
Py_INCREF(Py_None);
@@ -104,40 +104,40 @@ sound_playsound(PyObject *s, PyObject *args)
static PyObject *
sound_beep(PyObject *self, PyObject *args)
{
- int freq;
- int dur;
- BOOL ok;
-
- if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur))
- return NULL;
-
- if (freq < 37 || freq > 32767) {
- PyErr_SetString(PyExc_ValueError,
- "frequency must be in 37 thru 32767");
- return NULL;
- }
-
- Py_BEGIN_ALLOW_THREADS
- ok = Beep(freq, dur);
- Py_END_ALLOW_THREADS
- if (!ok) {
- PyErr_SetString(PyExc_RuntimeError,"Failed to beep");
- return NULL;
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ int freq;
+ int dur;
+ BOOL ok;
+
+ if (!PyArg_ParseTuple(args, "ii:Beep", &freq, &dur))
+ return NULL;
+
+ if (freq < 37 || freq > 32767) {
+ PyErr_SetString(PyExc_ValueError,
+ "frequency must be in 37 thru 32767");
+ return NULL;
+ }
+
+ Py_BEGIN_ALLOW_THREADS
+ ok = Beep(freq, dur);
+ Py_END_ALLOW_THREADS
+ if (!ok) {
+ PyErr_SetString(PyExc_RuntimeError,"Failed to beep");
+ return NULL;
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
sound_msgbeep(PyObject *self, PyObject *args)
{
- int x = MB_OK;
- if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x))
- return NULL;
- MessageBeep(x);
- Py_INCREF(Py_None);
- return Py_None;
+ int x = MB_OK;
+ if (!PyArg_ParseTuple(args, "|i:MessageBeep", &x))
+ return NULL;
+ MessageBeep(x);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static struct PyMethodDef sound_methods[] =
@@ -155,7 +155,7 @@ add_define(PyObject *dict, const char *key, long value)
PyObject *v=PyLong_FromLong(value);
if(v&&k)
{
- PyDict_SetItem(dict,k,v);
+ PyDict_SetItem(dict,k,v);
}
Py_XDECREF(k);
Py_XDECREF(v);
@@ -166,28 +166,28 @@ add_define(PyObject *dict, const char *key, long value)
PyMODINIT_FUNC
initwinsound(void)
{
- PyObject *dict;
- PyObject *module = Py_InitModule3("winsound",
- sound_methods,
- sound_module_doc);
- if (module == NULL)
- return;
- dict = PyModule_GetDict(module);
-
- ADD_DEFINE(SND_ASYNC);
- ADD_DEFINE(SND_NODEFAULT);
- ADD_DEFINE(SND_NOSTOP);
- ADD_DEFINE(SND_NOWAIT);
- ADD_DEFINE(SND_ALIAS);
- ADD_DEFINE(SND_FILENAME);
- ADD_DEFINE(SND_MEMORY);
- ADD_DEFINE(SND_PURGE);
- ADD_DEFINE(SND_LOOP);
- ADD_DEFINE(SND_APPLICATION);
-
- ADD_DEFINE(MB_OK);
- ADD_DEFINE(MB_ICONASTERISK);
- ADD_DEFINE(MB_ICONEXCLAMATION);
- ADD_DEFINE(MB_ICONHAND);
- ADD_DEFINE(MB_ICONQUESTION);
+ PyObject *dict;
+ PyObject *module = Py_InitModule3("winsound",
+ sound_methods,
+ sound_module_doc);
+ if (module == NULL)
+ return;
+ dict = PyModule_GetDict(module);
+
+ ADD_DEFINE(SND_ASYNC);
+ ADD_DEFINE(SND_NODEFAULT);
+ ADD_DEFINE(SND_NOSTOP);
+ ADD_DEFINE(SND_NOWAIT);
+ ADD_DEFINE(SND_ALIAS);
+ ADD_DEFINE(SND_FILENAME);
+ ADD_DEFINE(SND_MEMORY);
+ ADD_DEFINE(SND_PURGE);
+ ADD_DEFINE(SND_LOOP);
+ ADD_DEFINE(SND_APPLICATION);
+
+ ADD_DEFINE(MB_OK);
+ ADD_DEFINE(MB_ICONASTERISK);
+ ADD_DEFINE(MB_ICONEXCLAMATION);
+ ADD_DEFINE(MB_ICONHAND);
+ ADD_DEFINE(MB_ICONQUESTION);
}
diff --git a/PCbuild/make_buildinfo.c b/PCbuild/make_buildinfo.c
index 22b9882..5a3d385 100644
--- a/PCbuild/make_buildinfo.c
+++ b/PCbuild/make_buildinfo.c
@@ -23,72 +23,72 @@
int make_buildinfo2()
{
- struct _stat st;
- HKEY hTortoise;
- char command[CMD_SIZE+1];
- DWORD type, size;
- if (_stat(".svn", &st) < 0)
- return 0;
- /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
- if (_stat("no_subwcrev", &st) == 0)
- return 0;
- if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
- RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
- /* Tortoise not installed */
- return 0;
- command[0] = '"'; /* quote the path to the executable */
- size = sizeof(command) - 1;
- if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
- type != REG_SZ)
- /* Registry corrupted */
- return 0;
- strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe");
- if (_stat(command+1, &st) < 0)
- /* subwcrev.exe not part of the release */
- return 0;
- strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c");
- puts(command); fflush(stdout);
- if (system(command) < 0)
- return 0;
- return 1;
+ struct _stat st;
+ HKEY hTortoise;
+ char command[CMD_SIZE+1];
+ DWORD type, size;
+ if (_stat(".svn", &st) < 0)
+ return 0;
+ /* Allow suppression of subwcrev.exe invocation if a no_subwcrev file is present. */
+ if (_stat("no_subwcrev", &st) == 0)
+ return 0;
+ if (RegOpenKey(HKEY_LOCAL_MACHINE, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS &&
+ RegOpenKey(HKEY_CURRENT_USER, "Software\\TortoiseSVN", &hTortoise) != ERROR_SUCCESS)
+ /* Tortoise not installed */
+ return 0;
+ command[0] = '"'; /* quote the path to the executable */
+ size = sizeof(command) - 1;
+ if (RegQueryValueEx(hTortoise, "Directory", 0, &type, command+1, &size) != ERROR_SUCCESS ||
+ type != REG_SZ)
+ /* Registry corrupted */
+ return 0;
+ strcat_s(command, CMD_SIZE, "bin\\subwcrev.exe");
+ if (_stat(command+1, &st) < 0)
+ /* subwcrev.exe not part of the release */
+ return 0;
+ strcat_s(command, CMD_SIZE, "\" .. ..\\Modules\\getbuildinfo.c getbuildinfo2.c");
+ puts(command); fflush(stdout);
+ if (system(command) < 0)
+ return 0;
+ return 1;
}
int main(int argc, char*argv[])
{
- char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
- int do_unlink, result;
- if (argc != 2) {
- fprintf(stderr, "make_buildinfo $(ConfigurationName)\n");
- return EXIT_FAILURE;
- }
- if (strcmp(argv[1], "Release") == 0) {
- strcat_s(command, CMD_SIZE, "-MD ");
- }
- else if (strcmp(argv[1], "Debug") == 0) {
- strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd ");
- }
- else if (strcmp(argv[1], "ReleaseItanium") == 0) {
- strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM ");
- }
- else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
- strcat_s(command, CMD_SIZE, "-MD ");
- strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON ");
- }
- else {
- fprintf(stderr, "unsupported configuration %s\n", argv[1]);
- return EXIT_FAILURE;
- }
+ char command[500] = "cl.exe -c -D_WIN32 -DUSE_DL_EXPORT -D_WINDOWS -DWIN32 -D_WINDLL ";
+ int do_unlink, result;
+ if (argc != 2) {
+ fprintf(stderr, "make_buildinfo $(ConfigurationName)\n");
+ return EXIT_FAILURE;
+ }
+ if (strcmp(argv[1], "Release") == 0) {
+ strcat_s(command, CMD_SIZE, "-MD ");
+ }
+ else if (strcmp(argv[1], "Debug") == 0) {
+ strcat_s(command, CMD_SIZE, "-D_DEBUG -MDd ");
+ }
+ else if (strcmp(argv[1], "ReleaseItanium") == 0) {
+ strcat_s(command, CMD_SIZE, "-MD /USECL:MS_ITANIUM ");
+ }
+ else if (strcmp(argv[1], "ReleaseAMD64") == 0) {
+ strcat_s(command, CMD_SIZE, "-MD ");
+ strcat_s(command, CMD_SIZE, "-MD /USECL:MS_OPTERON ");
+ }
+ else {
+ fprintf(stderr, "unsupported configuration %s\n", argv[1]);
+ return EXIT_FAILURE;
+ }
- if ((do_unlink = make_buildinfo2()))
- strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV ");
- else
- strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c");
- strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC");
- puts(command); fflush(stdout);
- result = system(command);
- if (do_unlink)
- _unlink("getbuildinfo2.c");
- if (result < 0)
- return EXIT_FAILURE;
- return 0;
-} \ No newline at end of file
+ if ((do_unlink = make_buildinfo2()))
+ strcat_s(command, CMD_SIZE, "getbuildinfo2.c -DSUBWCREV ");
+ else
+ strcat_s(command, CMD_SIZE, "..\\Modules\\getbuildinfo.c");
+ strcat_s(command, CMD_SIZE, " -Fogetbuildinfo.o -I..\\Include -I..\\PC");
+ puts(command); fflush(stdout);
+ result = system(command);
+ if (do_unlink)
+ _unlink("getbuildinfo2.c");
+ if (result < 0)
+ return EXIT_FAILURE;
+ return 0;
+}
diff --git a/Parser/acceler.c b/Parser/acceler.c
index b41b265..9b14263 100644
--- a/Parser/acceler.c
+++ b/Parser/acceler.c
@@ -23,103 +23,103 @@ static void fixstate(grammar *, state *);
void
PyGrammar_AddAccelerators(grammar *g)
{
- dfa *d;
- int i;
- d = g->g_dfa;
- for (i = g->g_ndfas; --i >= 0; d++)
- fixdfa(g, d);
- g->g_accel = 1;
+ dfa *d;
+ int i;
+ d = g->g_dfa;
+ for (i = g->g_ndfas; --i >= 0; d++)
+ fixdfa(g, d);
+ g->g_accel = 1;
}
void
PyGrammar_RemoveAccelerators(grammar *g)
{
- dfa *d;
- int i;
- g->g_accel = 0;
- d = g->g_dfa;
- for (i = g->g_ndfas; --i >= 0; d++) {
- state *s;
- int j;
- s = d->d_state;
- for (j = 0; j < d->d_nstates; j++, s++) {
- if (s->s_accel)
- PyObject_FREE(s->s_accel);
- s->s_accel = NULL;
- }
- }
+ dfa *d;
+ int i;
+ g->g_accel = 0;
+ d = g->g_dfa;
+ for (i = g->g_ndfas; --i >= 0; d++) {
+ state *s;
+ int j;
+ s = d->d_state;
+ for (j = 0; j < d->d_nstates; j++, s++) {
+ if (s->s_accel)
+ PyObject_FREE(s->s_accel);
+ s->s_accel = NULL;
+ }
+ }
}
static void
fixdfa(grammar *g, dfa *d)
{
- state *s;
- int j;
- s = d->d_state;
- for (j = 0; j < d->d_nstates; j++, s++)
- fixstate(g, s);
+ state *s;
+ int j;
+ s = d->d_state;
+ for (j = 0; j < d->d_nstates; j++, s++)
+ fixstate(g, s);
}
static void
fixstate(grammar *g, state *s)
{
- arc *a;
- int k;
- int *accel;
- int nl = g->g_ll.ll_nlabels;
- s->s_accept = 0;
- accel = (int *) PyObject_MALLOC(nl * sizeof(int));
- if (accel == NULL) {
- fprintf(stderr, "no mem to build parser accelerators\n");
- exit(1);
- }
- for (k = 0; k < nl; k++)
- accel[k] = -1;
- a = s->s_arc;
- for (k = s->s_narcs; --k >= 0; a++) {
- int lbl = a->a_lbl;
- label *l = &g->g_ll.ll_label[lbl];
- int type = l->lb_type;
- if (a->a_arrow >= (1 << 7)) {
- printf("XXX too many states!\n");
- continue;
- }
- if (ISNONTERMINAL(type)) {
- dfa *d1 = PyGrammar_FindDFA(g, type);
- int ibit;
- if (type - NT_OFFSET >= (1 << 7)) {
- printf("XXX too high nonterminal number!\n");
- continue;
- }
- for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) {
- if (testbit(d1->d_first, ibit)) {
- if (accel[ibit] != -1)
- printf("XXX ambiguity!\n");
- accel[ibit] = a->a_arrow | (1 << 7) |
- ((type - NT_OFFSET) << 8);
- }
- }
- }
- else if (lbl == EMPTY)
- s->s_accept = 1;
- else if (lbl >= 0 && lbl < nl)
- accel[lbl] = a->a_arrow;
- }
- while (nl > 0 && accel[nl-1] == -1)
- nl--;
- for (k = 0; k < nl && accel[k] == -1;)
- k++;
- if (k < nl) {
- int i;
- s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int));
- if (s->s_accel == NULL) {
- fprintf(stderr, "no mem to add parser accelerators\n");
- exit(1);
- }
- s->s_lower = k;
- s->s_upper = nl;
- for (i = 0; k < nl; i++, k++)
- s->s_accel[i] = accel[k];
- }
- PyObject_FREE(accel);
+ arc *a;
+ int k;
+ int *accel;
+ int nl = g->g_ll.ll_nlabels;
+ s->s_accept = 0;
+ accel = (int *) PyObject_MALLOC(nl * sizeof(int));
+ if (accel == NULL) {
+ fprintf(stderr, "no mem to build parser accelerators\n");
+ exit(1);
+ }
+ for (k = 0; k < nl; k++)
+ accel[k] = -1;
+ a = s->s_arc;
+ for (k = s->s_narcs; --k >= 0; a++) {
+ int lbl = a->a_lbl;
+ label *l = &g->g_ll.ll_label[lbl];
+ int type = l->lb_type;
+ if (a->a_arrow >= (1 << 7)) {
+ printf("XXX too many states!\n");
+ continue;
+ }
+ if (ISNONTERMINAL(type)) {
+ dfa *d1 = PyGrammar_FindDFA(g, type);
+ int ibit;
+ if (type - NT_OFFSET >= (1 << 7)) {
+ printf("XXX too high nonterminal number!\n");
+ continue;
+ }
+ for (ibit = 0; ibit < g->g_ll.ll_nlabels; ibit++) {
+ if (testbit(d1->d_first, ibit)) {
+ if (accel[ibit] != -1)
+ printf("XXX ambiguity!\n");
+ accel[ibit] = a->a_arrow | (1 << 7) |
+ ((type - NT_OFFSET) << 8);
+ }
+ }
+ }
+ else if (lbl == EMPTY)
+ s->s_accept = 1;
+ else if (lbl >= 0 && lbl < nl)
+ accel[lbl] = a->a_arrow;
+ }
+ while (nl > 0 && accel[nl-1] == -1)
+ nl--;
+ for (k = 0; k < nl && accel[k] == -1;)
+ k++;
+ if (k < nl) {
+ int i;
+ s->s_accel = (int *) PyObject_MALLOC((nl-k) * sizeof(int));
+ if (s->s_accel == NULL) {
+ fprintf(stderr, "no mem to add parser accelerators\n");
+ exit(1);
+ }
+ s->s_lower = k;
+ s->s_upper = nl;
+ for (i = 0; k < nl; i++, k++)
+ s->s_accel[i] = accel[k];
+ }
+ PyObject_FREE(accel);
}
diff --git a/Parser/bitset.c b/Parser/bitset.c
index b5543b8..f5bfd41 100644
--- a/Parser/bitset.c
+++ b/Parser/bitset.c
@@ -7,60 +7,60 @@
bitset
newbitset(int nbits)
{
- int nbytes = NBYTES(nbits);
- bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes);
-
- if (ss == NULL)
- Py_FatalError("no mem for bitset");
-
- ss += nbytes;
- while (--nbytes >= 0)
- *--ss = 0;
- return ss;
+ int nbytes = NBYTES(nbits);
+ bitset ss = (char *)PyObject_MALLOC(sizeof(BYTE) * nbytes);
+
+ if (ss == NULL)
+ Py_FatalError("no mem for bitset");
+
+ ss += nbytes;
+ while (--nbytes >= 0)
+ *--ss = 0;
+ return ss;
}
void
delbitset(bitset ss)
{
- PyObject_FREE(ss);
+ PyObject_FREE(ss);
}
int
addbit(bitset ss, int ibit)
{
- int ibyte = BIT2BYTE(ibit);
- BYTE mask = BIT2MASK(ibit);
-
- if (ss[ibyte] & mask)
- return 0; /* Bit already set */
- ss[ibyte] |= mask;
- return 1;
+ int ibyte = BIT2BYTE(ibit);
+ BYTE mask = BIT2MASK(ibit);
+
+ if (ss[ibyte] & mask)
+ return 0; /* Bit already set */
+ ss[ibyte] |= mask;
+ return 1;
}
#if 0 /* Now a macro */
int
testbit(bitset ss, int ibit)
{
- return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0;
+ return (ss[BIT2BYTE(ibit)] & BIT2MASK(ibit)) != 0;
}
#endif
int
samebitset(bitset ss1, bitset ss2, int nbits)
{
- int i;
-
- for (i = NBYTES(nbits); --i >= 0; )
- if (*ss1++ != *ss2++)
- return 0;
- return 1;
+ int i;
+
+ for (i = NBYTES(nbits); --i >= 0; )
+ if (*ss1++ != *ss2++)
+ return 0;
+ return 1;
}
void
mergebitset(bitset ss1, bitset ss2, int nbits)
{
- int i;
-
- for (i = NBYTES(nbits); --i >= 0; )
- *ss1++ |= *ss2++;
+ int i;
+
+ for (i = NBYTES(nbits); --i >= 0; )
+ *ss1++ |= *ss2++;
}
diff --git a/Parser/firstsets.c b/Parser/firstsets.c
index 00467b3..ee75d1b 100644
--- a/Parser/firstsets.c
+++ b/Parser/firstsets.c
@@ -13,101 +13,101 @@ static void calcfirstset(grammar *, dfa *);
void
addfirstsets(grammar *g)
{
- int i;
- dfa *d;
+ int i;
+ dfa *d;
- if (Py_DebugFlag)
- printf("Adding FIRST sets ...\n");
- for (i = 0; i < g->g_ndfas; i++) {
- d = &g->g_dfa[i];
- if (d->d_first == NULL)
- calcfirstset(g, d);
- }
+ if (Py_DebugFlag)
+ printf("Adding FIRST sets ...\n");
+ for (i = 0; i < g->g_ndfas; i++) {
+ d = &g->g_dfa[i];
+ if (d->d_first == NULL)
+ calcfirstset(g, d);
+ }
}
static void
calcfirstset(grammar *g, dfa *d)
{
- int i, j;
- state *s;
- arc *a;
- int nsyms;
- int *sym;
- int nbits;
- static bitset dummy;
- bitset result;
- int type;
- dfa *d1;
- label *l0;
-
- if (Py_DebugFlag)
- printf("Calculate FIRST set for '%s'\n", d->d_name);
-
- if (dummy == NULL)
- dummy = newbitset(1);
- if (d->d_first == dummy) {
- fprintf(stderr, "Left-recursion for '%s'\n", d->d_name);
- return;
- }
- if (d->d_first != NULL) {
- fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n",
- d->d_name);
- }
- d->d_first = dummy;
-
- l0 = g->g_ll.ll_label;
- nbits = g->g_ll.ll_nlabels;
- result = newbitset(nbits);
-
- sym = (int *)PyObject_MALLOC(sizeof(int));
- if (sym == NULL)
- Py_FatalError("no mem for new sym in calcfirstset");
- nsyms = 1;
- sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL);
-
- s = &d->d_state[d->d_initial];
- for (i = 0; i < s->s_narcs; i++) {
- a = &s->s_arc[i];
- for (j = 0; j < nsyms; j++) {
- if (sym[j] == a->a_lbl)
- break;
- }
- if (j >= nsyms) { /* New label */
- sym = (int *)PyObject_REALLOC(sym,
- sizeof(int) * (nsyms + 1));
- if (sym == NULL)
- Py_FatalError(
- "no mem to resize sym in calcfirstset");
- sym[nsyms++] = a->a_lbl;
- type = l0[a->a_lbl].lb_type;
- if (ISNONTERMINAL(type)) {
- d1 = PyGrammar_FindDFA(g, type);
- if (d1->d_first == dummy) {
- fprintf(stderr,
- "Left-recursion below '%s'\n",
- d->d_name);
- }
- else {
- if (d1->d_first == NULL)
- calcfirstset(g, d1);
- mergebitset(result,
- d1->d_first, nbits);
- }
- }
- else if (ISTERMINAL(type)) {
- addbit(result, a->a_lbl);
- }
- }
- }
- d->d_first = result;
- if (Py_DebugFlag) {
- printf("FIRST set for '%s': {", d->d_name);
- for (i = 0; i < nbits; i++) {
- if (testbit(result, i))
- printf(" %s", PyGrammar_LabelRepr(&l0[i]));
- }
- printf(" }\n");
- }
+ int i, j;
+ state *s;
+ arc *a;
+ int nsyms;
+ int *sym;
+ int nbits;
+ static bitset dummy;
+ bitset result;
+ int type;
+ dfa *d1;
+ label *l0;
- PyObject_FREE(sym);
+ if (Py_DebugFlag)
+ printf("Calculate FIRST set for '%s'\n", d->d_name);
+
+ if (dummy == NULL)
+ dummy = newbitset(1);
+ if (d->d_first == dummy) {
+ fprintf(stderr, "Left-recursion for '%s'\n", d->d_name);
+ return;
+ }
+ if (d->d_first != NULL) {
+ fprintf(stderr, "Re-calculating FIRST set for '%s' ???\n",
+ d->d_name);
+ }
+ d->d_first = dummy;
+
+ l0 = g->g_ll.ll_label;
+ nbits = g->g_ll.ll_nlabels;
+ result = newbitset(nbits);
+
+ sym = (int *)PyObject_MALLOC(sizeof(int));
+ if (sym == NULL)
+ Py_FatalError("no mem for new sym in calcfirstset");
+ nsyms = 1;
+ sym[0] = findlabel(&g->g_ll, d->d_type, (char *)NULL);
+
+ s = &d->d_state[d->d_initial];
+ for (i = 0; i < s->s_narcs; i++) {
+ a = &s->s_arc[i];
+ for (j = 0; j < nsyms; j++) {
+ if (sym[j] == a->a_lbl)
+ break;
+ }
+ if (j >= nsyms) { /* New label */
+ sym = (int *)PyObject_REALLOC(sym,
+ sizeof(int) * (nsyms + 1));
+ if (sym == NULL)
+ Py_FatalError(
+ "no mem to resize sym in calcfirstset");
+ sym[nsyms++] = a->a_lbl;
+ type = l0[a->a_lbl].lb_type;
+ if (ISNONTERMINAL(type)) {
+ d1 = PyGrammar_FindDFA(g, type);
+ if (d1->d_first == dummy) {
+ fprintf(stderr,
+ "Left-recursion below '%s'\n",
+ d->d_name);
+ }
+ else {
+ if (d1->d_first == NULL)
+ calcfirstset(g, d1);
+ mergebitset(result,
+ d1->d_first, nbits);
+ }
+ }
+ else if (ISTERMINAL(type)) {
+ addbit(result, a->a_lbl);
+ }
+ }
+ }
+ d->d_first = result;
+ if (Py_DebugFlag) {
+ printf("FIRST set for '%s': {", d->d_name);
+ for (i = 0; i < nbits; i++) {
+ if (testbit(result, i))
+ printf(" %s", PyGrammar_LabelRepr(&l0[i]));
+ }
+ printf(" }\n");
+ }
+
+ PyObject_FREE(sym);
}
diff --git a/Parser/grammar.c b/Parser/grammar.c
index 9e7c49a..fa1dd7c 100644
--- a/Parser/grammar.c
+++ b/Parser/grammar.c
@@ -18,98 +18,98 @@ extern int Py_DebugFlag;
grammar *
newgrammar(int start)
{
- grammar *g;
-
- g = (grammar *)PyObject_MALLOC(sizeof(grammar));
- if (g == NULL)
- Py_FatalError("no mem for new grammar");
- g->g_ndfas = 0;
- g->g_dfa = NULL;
- g->g_start = start;
- g->g_ll.ll_nlabels = 0;
- g->g_ll.ll_label = NULL;
- g->g_accel = 0;
- return g;
+ grammar *g;
+
+ g = (grammar *)PyObject_MALLOC(sizeof(grammar));
+ if (g == NULL)
+ Py_FatalError("no mem for new grammar");
+ g->g_ndfas = 0;
+ g->g_dfa = NULL;
+ g->g_start = start;
+ g->g_ll.ll_nlabels = 0;
+ g->g_ll.ll_label = NULL;
+ g->g_accel = 0;
+ return g;
}
dfa *
adddfa(grammar *g, int type, char *name)
{
- dfa *d;
-
- g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa,
- sizeof(dfa) * (g->g_ndfas + 1));
- if (g->g_dfa == NULL)
- Py_FatalError("no mem to resize dfa in adddfa");
- d = &g->g_dfa[g->g_ndfas++];
- d->d_type = type;
- d->d_name = strdup(name);
- d->d_nstates = 0;
- d->d_state = NULL;
- d->d_initial = -1;
- d->d_first = NULL;
- return d; /* Only use while fresh! */
+ dfa *d;
+
+ g->g_dfa = (dfa *)PyObject_REALLOC(g->g_dfa,
+ sizeof(dfa) * (g->g_ndfas + 1));
+ if (g->g_dfa == NULL)
+ Py_FatalError("no mem to resize dfa in adddfa");
+ d = &g->g_dfa[g->g_ndfas++];
+ d->d_type = type;
+ d->d_name = strdup(name);
+ d->d_nstates = 0;
+ d->d_state = NULL;
+ d->d_initial = -1;
+ d->d_first = NULL;
+ return d; /* Only use while fresh! */
}
int
addstate(dfa *d)
{
- state *s;
-
- d->d_state = (state *)PyObject_REALLOC(d->d_state,
- sizeof(state) * (d->d_nstates + 1));
- if (d->d_state == NULL)
- Py_FatalError("no mem to resize state in addstate");
- s = &d->d_state[d->d_nstates++];
- s->s_narcs = 0;
- s->s_arc = NULL;
- s->s_lower = 0;
- s->s_upper = 0;
- s->s_accel = NULL;
- s->s_accept = 0;
- return s - d->d_state;
+ state *s;
+
+ d->d_state = (state *)PyObject_REALLOC(d->d_state,
+ sizeof(state) * (d->d_nstates + 1));
+ if (d->d_state == NULL)
+ Py_FatalError("no mem to resize state in addstate");
+ s = &d->d_state[d->d_nstates++];
+ s->s_narcs = 0;
+ s->s_arc = NULL;
+ s->s_lower = 0;
+ s->s_upper = 0;
+ s->s_accel = NULL;
+ s->s_accept = 0;
+ return s - d->d_state;
}
void
addarc(dfa *d, int from, int to, int lbl)
{
- state *s;
- arc *a;
-
- assert(0 <= from && from < d->d_nstates);
- assert(0 <= to && to < d->d_nstates);
-
- s = &d->d_state[from];
- s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1));
- if (s->s_arc == NULL)
- Py_FatalError("no mem to resize arc list in addarc");
- a = &s->s_arc[s->s_narcs++];
- a->a_lbl = lbl;
- a->a_arrow = to;
+ state *s;
+ arc *a;
+
+ assert(0 <= from && from < d->d_nstates);
+ assert(0 <= to && to < d->d_nstates);
+
+ s = &d->d_state[from];
+ s->s_arc = (arc *)PyObject_REALLOC(s->s_arc, sizeof(arc) * (s->s_narcs + 1));
+ if (s->s_arc == NULL)
+ Py_FatalError("no mem to resize arc list in addarc");
+ a = &s->s_arc[s->s_narcs++];
+ a->a_lbl = lbl;
+ a->a_arrow = to;
}
int
addlabel(labellist *ll, int type, char *str)
{
- int i;
- label *lb;
-
- for (i = 0; i < ll->ll_nlabels; i++) {
- if (ll->ll_label[i].lb_type == type &&
- strcmp(ll->ll_label[i].lb_str, str) == 0)
- return i;
- }
- ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label,
- sizeof(label) * (ll->ll_nlabels + 1));
- if (ll->ll_label == NULL)
- Py_FatalError("no mem to resize labellist in addlabel");
- lb = &ll->ll_label[ll->ll_nlabels++];
- lb->lb_type = type;
- lb->lb_str = strdup(str);
- if (Py_DebugFlag)
- printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels,
- PyGrammar_LabelRepr(lb));
- return lb - ll->ll_label;
+ int i;
+ label *lb;
+
+ for (i = 0; i < ll->ll_nlabels; i++) {
+ if (ll->ll_label[i].lb_type == type &&
+ strcmp(ll->ll_label[i].lb_str, str) == 0)
+ return i;
+ }
+ ll->ll_label = (label *)PyObject_REALLOC(ll->ll_label,
+ sizeof(label) * (ll->ll_nlabels + 1));
+ if (ll->ll_label == NULL)
+ Py_FatalError("no mem to resize labellist in addlabel");
+ lb = &ll->ll_label[ll->ll_nlabels++];
+ lb->lb_type = type;
+ lb->lb_str = strdup(str);
+ if (Py_DebugFlag)
+ printf("Label @ %8p, %d: %s\n", ll, ll->ll_nlabels,
+ PyGrammar_LabelRepr(lb));
+ return lb - ll->ll_label;
}
/* Same, but rather dies than adds */
@@ -117,16 +117,16 @@ addlabel(labellist *ll, int type, char *str)
int
findlabel(labellist *ll, int type, char *str)
{
- int i;
-
- for (i = 0; i < ll->ll_nlabels; i++) {
- if (ll->ll_label[i].lb_type == type /*&&
- strcmp(ll->ll_label[i].lb_str, str) == 0*/)
- return i;
- }
- fprintf(stderr, "Label %d/'%s' not found\n", type, str);
- Py_FatalError("grammar.c:findlabel()");
- return 0; /* Make gcc -Wall happy */
+ int i;
+
+ for (i = 0; i < ll->ll_nlabels; i++) {
+ if (ll->ll_label[i].lb_type == type /*&&
+ strcmp(ll->ll_label[i].lb_str, str) == 0*/)
+ return i;
+ }
+ fprintf(stderr, "Label %d/'%s' not found\n", type, str);
+ Py_FatalError("grammar.c:findlabel()");
+ return 0; /* Make gcc -Wall happy */
}
/* Forward */
@@ -135,120 +135,120 @@ static void translabel(grammar *, label *);
void
translatelabels(grammar *g)
{
- int i;
+ int i;
#ifdef Py_DEBUG
- printf("Translating labels ...\n");
+ printf("Translating labels ...\n");
#endif
- /* Don't translate EMPTY */
- for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++)
- translabel(g, &g->g_ll.ll_label[i]);
+ /* Don't translate EMPTY */
+ for (i = EMPTY+1; i < g->g_ll.ll_nlabels; i++)
+ translabel(g, &g->g_ll.ll_label[i]);
}
static void
translabel(grammar *g, label *lb)
{
- int i;
-
- if (Py_DebugFlag)
- printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb));
-
- if (lb->lb_type == NAME) {
- for (i = 0; i < g->g_ndfas; i++) {
- if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) {
- if (Py_DebugFlag)
- printf(
- "Label %s is non-terminal %d.\n",
- lb->lb_str,
- g->g_dfa[i].d_type);
- lb->lb_type = g->g_dfa[i].d_type;
- free(lb->lb_str);
- lb->lb_str = NULL;
- return;
- }
- }
- for (i = 0; i < (int)N_TOKENS; i++) {
- if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) {
- if (Py_DebugFlag)
- printf("Label %s is terminal %d.\n",
- lb->lb_str, i);
- lb->lb_type = i;
- free(lb->lb_str);
- lb->lb_str = NULL;
- return;
- }
- }
- printf("Can't translate NAME label '%s'\n", lb->lb_str);
- return;
- }
-
- if (lb->lb_type == STRING) {
- if (isalpha(Py_CHARMASK(lb->lb_str[1])) ||
- lb->lb_str[1] == '_') {
- char *p;
- char *src;
- char *dest;
- size_t name_len;
- if (Py_DebugFlag)
- printf("Label %s is a keyword\n", lb->lb_str);
- lb->lb_type = NAME;
- src = lb->lb_str + 1;
- p = strchr(src, '\'');
- if (p)
- name_len = p - src;
- else
- name_len = strlen(src);
- dest = (char *)malloc(name_len + 1);
- if (!dest) {
- printf("Can't alloc dest '%s'\n", src);
- return;
- }
- strncpy(dest, src, name_len);
- dest[name_len] = '\0';
- free(lb->lb_str);
- lb->lb_str = dest;
- }
- else if (lb->lb_str[2] == lb->lb_str[0]) {
- int type = (int) PyToken_OneChar(lb->lb_str[1]);
- if (type != OP) {
- lb->lb_type = type;
- free(lb->lb_str);
- lb->lb_str = NULL;
- }
- else
- printf("Unknown OP label %s\n",
- lb->lb_str);
- }
- else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) {
- int type = (int) PyToken_TwoChars(lb->lb_str[1],
- lb->lb_str[2]);
- if (type != OP) {
- lb->lb_type = type;
- free(lb->lb_str);
- lb->lb_str = NULL;
- }
- else
- printf("Unknown OP label %s\n",
- lb->lb_str);
- }
- else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) {
- int type = (int) PyToken_ThreeChars(lb->lb_str[1],
- lb->lb_str[2],
- lb->lb_str[3]);
- if (type != OP) {
- lb->lb_type = type;
- free(lb->lb_str);
- lb->lb_str = NULL;
- }
- else
- printf("Unknown OP label %s\n",
- lb->lb_str);
- }
- else
- printf("Can't translate STRING label %s\n",
- lb->lb_str);
- }
- else
- printf("Can't translate label '%s'\n",
- PyGrammar_LabelRepr(lb));
+ int i;
+
+ if (Py_DebugFlag)
+ printf("Translating label %s ...\n", PyGrammar_LabelRepr(lb));
+
+ if (lb->lb_type == NAME) {
+ for (i = 0; i < g->g_ndfas; i++) {
+ if (strcmp(lb->lb_str, g->g_dfa[i].d_name) == 0) {
+ if (Py_DebugFlag)
+ printf(
+ "Label %s is non-terminal %d.\n",
+ lb->lb_str,
+ g->g_dfa[i].d_type);
+ lb->lb_type = g->g_dfa[i].d_type;
+ free(lb->lb_str);
+ lb->lb_str = NULL;
+ return;
+ }
+ }
+ for (i = 0; i < (int)N_TOKENS; i++) {
+ if (strcmp(lb->lb_str, _PyParser_TokenNames[i]) == 0) {
+ if (Py_DebugFlag)
+ printf("Label %s is terminal %d.\n",
+ lb->lb_str, i);
+ lb->lb_type = i;
+ free(lb->lb_str);
+ lb->lb_str = NULL;
+ return;
+ }
+ }
+ printf("Can't translate NAME label '%s'\n", lb->lb_str);
+ return;
+ }
+
+ if (lb->lb_type == STRING) {
+ if (isalpha(Py_CHARMASK(lb->lb_str[1])) ||
+ lb->lb_str[1] == '_') {
+ char *p;
+ char *src;
+ char *dest;
+ size_t name_len;
+ if (Py_DebugFlag)
+ printf("Label %s is a keyword\n", lb->lb_str);
+ lb->lb_type = NAME;
+ src = lb->lb_str + 1;
+ p = strchr(src, '\'');
+ if (p)
+ name_len = p - src;
+ else
+ name_len = strlen(src);
+ dest = (char *)malloc(name_len + 1);
+ if (!dest) {
+ printf("Can't alloc dest '%s'\n", src);
+ return;
+ }
+ strncpy(dest, src, name_len);
+ dest[name_len] = '\0';
+ free(lb->lb_str);
+ lb->lb_str = dest;
+ }
+ else if (lb->lb_str[2] == lb->lb_str[0]) {
+ int type = (int) PyToken_OneChar(lb->lb_str[1]);
+ if (type != OP) {
+ lb->lb_type = type;
+ free(lb->lb_str);
+ lb->lb_str = NULL;
+ }
+ else
+ printf("Unknown OP label %s\n",
+ lb->lb_str);
+ }
+ else if (lb->lb_str[2] && lb->lb_str[3] == lb->lb_str[0]) {
+ int type = (int) PyToken_TwoChars(lb->lb_str[1],
+ lb->lb_str[2]);
+ if (type != OP) {
+ lb->lb_type = type;
+ free(lb->lb_str);
+ lb->lb_str = NULL;
+ }
+ else
+ printf("Unknown OP label %s\n",
+ lb->lb_str);
+ }
+ else if (lb->lb_str[2] && lb->lb_str[3] && lb->lb_str[4] == lb->lb_str[0]) {
+ int type = (int) PyToken_ThreeChars(lb->lb_str[1],
+ lb->lb_str[2],
+ lb->lb_str[3]);
+ if (type != OP) {
+ lb->lb_type = type;
+ free(lb->lb_str);
+ lb->lb_str = NULL;
+ }
+ else
+ printf("Unknown OP label %s\n",
+ lb->lb_str);
+ }
+ else
+ printf("Can't translate STRING label %s\n",
+ lb->lb_str);
+ }
+ else
+ printf("Can't translate label '%s'\n",
+ PyGrammar_LabelRepr(lb));
}
diff --git a/Parser/grammar1.c b/Parser/grammar1.c
index b76719a..1f7d264 100644
--- a/Parser/grammar1.c
+++ b/Parser/grammar1.c
@@ -11,47 +11,47 @@
dfa *
PyGrammar_FindDFA(grammar *g, register int type)
{
- register dfa *d;
+ register dfa *d;
#if 1
- /* Massive speed-up */
- d = &g->g_dfa[type - NT_OFFSET];
- assert(d->d_type == type);
- return d;
+ /* Massive speed-up */
+ d = &g->g_dfa[type - NT_OFFSET];
+ assert(d->d_type == type);
+ return d;
#else
- /* Old, slow version */
- register int i;
-
- for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) {
- if (d->d_type == type)
- return d;
- }
- assert(0);
- /* NOTREACHED */
+ /* Old, slow version */
+ register int i;
+
+ for (i = g->g_ndfas, d = g->g_dfa; --i >= 0; d++) {
+ if (d->d_type == type)
+ return d;
+ }
+ assert(0);
+ /* NOTREACHED */
#endif
}
char *
PyGrammar_LabelRepr(label *lb)
{
- static char buf[100];
-
- if (lb->lb_type == ENDMARKER)
- return "EMPTY";
- else if (ISNONTERMINAL(lb->lb_type)) {
- if (lb->lb_str == NULL) {
- PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type);
- return buf;
- }
- else
- return lb->lb_str;
- }
- else {
- if (lb->lb_str == NULL)
- return _PyParser_TokenNames[lb->lb_type];
- else {
- PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)",
- _PyParser_TokenNames[lb->lb_type], lb->lb_str);
- return buf;
- }
- }
+ static char buf[100];
+
+ if (lb->lb_type == ENDMARKER)
+ return "EMPTY";
+ else if (ISNONTERMINAL(lb->lb_type)) {
+ if (lb->lb_str == NULL) {
+ PyOS_snprintf(buf, sizeof(buf), "NT%d", lb->lb_type);
+ return buf;
+ }
+ else
+ return lb->lb_str;
+ }
+ else {
+ if (lb->lb_str == NULL)
+ return _PyParser_TokenNames[lb->lb_type];
+ else {
+ PyOS_snprintf(buf, sizeof(buf), "%.32s(%.32s)",
+ _PyParser_TokenNames[lb->lb_type], lb->lb_str);
+ return buf;
+ }
+ }
}
diff --git a/Parser/intrcheck.c b/Parser/intrcheck.c
index 1356191..1c888a5 100644
--- a/Parser/intrcheck.c
+++ b/Parser/intrcheck.c
@@ -21,7 +21,7 @@ PyOS_FiniInterrupts(void)
int
PyOS_InterruptOccurred(void)
{
- _wyield();
+ _wyield();
}
#define OK
@@ -47,7 +47,7 @@ PyOS_InterruptOccurred(void)
void
PyOS_InitInterrupts(void)
{
- _go32_want_ctrl_break(1 /* TRUE */);
+ _go32_want_ctrl_break(1 /* TRUE */);
}
void
@@ -58,7 +58,7 @@ PyOS_FiniInterrupts(void)
int
PyOS_InterruptOccurred(void)
{
- return _go32_was_ctrl_break_hit();
+ return _go32_was_ctrl_break_hit();
}
#else /* !__GNUC__ */
@@ -78,12 +78,12 @@ PyOS_FiniInterrupts(void)
int
PyOS_InterruptOccurred(void)
{
- int interrupted = 0;
- while (kbhit()) {
- if (getch() == '\003')
- interrupted = 1;
- }
- return interrupted;
+ int interrupted = 0;
+ while (kbhit()) {
+ if (getch() == '\003')
+ interrupted = 1;
+ }
+ return interrupted;
}
#endif /* __GNUC__ */
@@ -106,7 +106,7 @@ static int interrupted;
void
PyErr_SetInterrupt(void)
{
- interrupted = 1;
+ interrupted = 1;
}
extern int PyErr_CheckSignals(void);
@@ -114,32 +114,32 @@ extern int PyErr_CheckSignals(void);
static int
checksignals_witharg(void * arg)
{
- return PyErr_CheckSignals();
+ return PyErr_CheckSignals();
}
static void
intcatcher(int sig)
{
- extern void Py_Exit(int);
- static char message[] =
+ extern void Py_Exit(int);
+ static char message[] =
"python: to interrupt a truly hanging Python program, interrupt once more.\n";
- switch (interrupted++) {
- case 0:
- break;
- case 1:
+ switch (interrupted++) {
+ case 0:
+ break;
+ case 1:
#ifdef RISCOS
- fprintf(stderr, message);
+ fprintf(stderr, message);
#else
- write(2, message, strlen(message));
+ write(2, message, strlen(message));
#endif
- break;
- case 2:
- interrupted = 0;
- Py_Exit(1);
- break;
- }
- PyOS_setsig(SIGINT, intcatcher);
- Py_AddPendingCall(checksignals_witharg, NULL);
+ break;
+ case 2:
+ interrupted = 0;
+ Py_Exit(1);
+ break;
+ }
+ PyOS_setsig(SIGINT, intcatcher);
+ Py_AddPendingCall(checksignals_witharg, NULL);
}
static void (*old_siginthandler)(int) = SIG_DFL;
@@ -147,23 +147,23 @@ static void (*old_siginthandler)(int) = SIG_DFL;
void
PyOS_InitInterrupts(void)
{
- if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN)
- PyOS_setsig(SIGINT, intcatcher);
+ if ((old_siginthandler = PyOS_setsig(SIGINT, SIG_IGN)) != SIG_IGN)
+ PyOS_setsig(SIGINT, intcatcher);
}
void
PyOS_FiniInterrupts(void)
{
- PyOS_setsig(SIGINT, old_siginthandler);
+ PyOS_setsig(SIGINT, old_siginthandler);
}
int
PyOS_InterruptOccurred(void)
{
- if (!interrupted)
- return 0;
- interrupted = 0;
- return 1;
+ if (!interrupted)
+ return 0;
+ interrupted = 0;
+ return 1;
}
#endif /* !OK */
@@ -172,7 +172,7 @@ void
PyOS_AfterFork(void)
{
#ifdef WITH_THREAD
- PyEval_ReInitThreads();
- PyThread_ReInitTLS();
+ PyEval_ReInitThreads();
+ PyThread_ReInitTLS();
#endif
}
diff --git a/Parser/listnode.c b/Parser/listnode.c
index c0b3b66..b5f8ad2 100644
--- a/Parser/listnode.c
+++ b/Parser/listnode.c
@@ -12,7 +12,7 @@ static void listnode(FILE *, node *);
void
PyNode_ListTree(node *n)
{
- listnode(stdout, n);
+ listnode(stdout, n);
}
static int level, atbol;
@@ -20,47 +20,47 @@ static int level, atbol;
static void
listnode(FILE *fp, node *n)
{
- level = 0;
- atbol = 1;
- list1node(fp, n);
+ level = 0;
+ atbol = 1;
+ list1node(fp, n);
}
static void
list1node(FILE *fp, node *n)
{
- if (n == 0)
- return;
- if (ISNONTERMINAL(TYPE(n))) {
- int i;
- for (i = 0; i < NCH(n); i++)
- list1node(fp, CHILD(n, i));
- }
- else if (ISTERMINAL(TYPE(n))) {
- switch (TYPE(n)) {
- case INDENT:
- ++level;
- break;
- case DEDENT:
- --level;
- break;
- default:
- if (atbol) {
- int i;
- for (i = 0; i < level; ++i)
- fprintf(fp, "\t");
- atbol = 0;
- }
- if (TYPE(n) == NEWLINE) {
- if (STR(n) != NULL)
- fprintf(fp, "%s", STR(n));
- fprintf(fp, "\n");
- atbol = 1;
- }
- else
- fprintf(fp, "%s ", STR(n));
- break;
- }
- }
- else
- fprintf(fp, "? ");
+ if (n == 0)
+ return;
+ if (ISNONTERMINAL(TYPE(n))) {
+ int i;
+ for (i = 0; i < NCH(n); i++)
+ list1node(fp, CHILD(n, i));
+ }
+ else if (ISTERMINAL(TYPE(n))) {
+ switch (TYPE(n)) {
+ case INDENT:
+ ++level;
+ break;
+ case DEDENT:
+ --level;
+ break;
+ default:
+ if (atbol) {
+ int i;
+ for (i = 0; i < level; ++i)
+ fprintf(fp, "\t");
+ atbol = 0;
+ }
+ if (TYPE(n) == NEWLINE) {
+ if (STR(n) != NULL)
+ fprintf(fp, "%s", STR(n));
+ fprintf(fp, "\n");
+ atbol = 1;
+ }
+ else
+ fprintf(fp, "%s ", STR(n));
+ break;
+ }
+ }
+ else
+ fprintf(fp, "? ");
}
diff --git a/Parser/metagrammar.c b/Parser/metagrammar.c
index b61bc6d..53810b8 100644
--- a/Parser/metagrammar.c
+++ b/Parser/metagrammar.c
@@ -4,152 +4,152 @@
#include "grammar.h"
#include "pgen.h"
static arc arcs_0_0[3] = {
- {2, 0},
- {3, 0},
- {4, 1},
+ {2, 0},
+ {3, 0},
+ {4, 1},
};
static arc arcs_0_1[1] = {
- {0, 1},
+ {0, 1},
};
static state states_0[2] = {
- {3, arcs_0_0},
- {1, arcs_0_1},
+ {3, arcs_0_0},
+ {1, arcs_0_1},
};
static arc arcs_1_0[1] = {
- {5, 1},
+ {5, 1},
};
static arc arcs_1_1[1] = {
- {6, 2},
+ {6, 2},
};
static arc arcs_1_2[1] = {
- {7, 3},
+ {7, 3},
};
static arc arcs_1_3[1] = {
- {3, 4},
+ {3, 4},
};
static arc arcs_1_4[1] = {
- {0, 4},
+ {0, 4},
};
static state states_1[5] = {
- {1, arcs_1_0},
- {1, arcs_1_1},
- {1, arcs_1_2},
- {1, arcs_1_3},
- {1, arcs_1_4},
+ {1, arcs_1_0},
+ {1, arcs_1_1},
+ {1, arcs_1_2},
+ {1, arcs_1_3},
+ {1, arcs_1_4},
};
static arc arcs_2_0[1] = {
- {8, 1},
+ {8, 1},
};
static arc arcs_2_1[2] = {
- {9, 0},
- {0, 1},
+ {9, 0},
+ {0, 1},
};
static state states_2[2] = {
- {1, arcs_2_0},
- {2, arcs_2_1},
+ {1, arcs_2_0},
+ {2, arcs_2_1},
};
static arc arcs_3_0[1] = {
- {10, 1},
+ {10, 1},
};
static arc arcs_3_1[2] = {
- {10, 1},
- {0, 1},
+ {10, 1},
+ {0, 1},
};
static state states_3[2] = {
- {1, arcs_3_0},
- {2, arcs_3_1},
+ {1, arcs_3_0},
+ {2, arcs_3_1},
};
static arc arcs_4_0[2] = {
- {11, 1},
- {13, 2},
+ {11, 1},
+ {13, 2},
};
static arc arcs_4_1[1] = {
- {7, 3},
+ {7, 3},
};
static arc arcs_4_2[3] = {
- {14, 4},
- {15, 4},
- {0, 2},
+ {14, 4},
+ {15, 4},
+ {0, 2},
};
static arc arcs_4_3[1] = {
- {12, 4},
+ {12, 4},
};
static arc arcs_4_4[1] = {
- {0, 4},
+ {0, 4},
};
static state states_4[5] = {
- {2, arcs_4_0},
- {1, arcs_4_1},
- {3, arcs_4_2},
- {1, arcs_4_3},
- {1, arcs_4_4},
+ {2, arcs_4_0},
+ {1, arcs_4_1},
+ {3, arcs_4_2},
+ {1, arcs_4_3},
+ {1, arcs_4_4},
};
static arc arcs_5_0[3] = {
- {5, 1},
- {16, 1},
- {17, 2},
+ {5, 1},
+ {16, 1},
+ {17, 2},
};
static arc arcs_5_1[1] = {
- {0, 1},
+ {0, 1},
};
static arc arcs_5_2[1] = {
- {7, 3},
+ {7, 3},
};
static arc arcs_5_3[1] = {
- {18, 1},
+ {18, 1},
};
static state states_5[4] = {
- {3, arcs_5_0},
- {1, arcs_5_1},
- {1, arcs_5_2},
- {1, arcs_5_3},
+ {3, arcs_5_0},
+ {1, arcs_5_1},
+ {1, arcs_5_2},
+ {1, arcs_5_3},
};
static dfa dfas[6] = {
- {256, "MSTART", 0, 2, states_0,
- "\070\000\000"},
- {257, "RULE", 0, 5, states_1,
- "\040\000\000"},
- {258, "RHS", 0, 2, states_2,
- "\040\010\003"},
- {259, "ALT", 0, 2, states_3,
- "\040\010\003"},
- {260, "ITEM", 0, 5, states_4,
- "\040\010\003"},
- {261, "ATOM", 0, 4, states_5,
- "\040\000\003"},
+ {256, "MSTART", 0, 2, states_0,
+ "\070\000\000"},
+ {257, "RULE", 0, 5, states_1,
+ "\040\000\000"},
+ {258, "RHS", 0, 2, states_2,
+ "\040\010\003"},
+ {259, "ALT", 0, 2, states_3,
+ "\040\010\003"},
+ {260, "ITEM", 0, 5, states_4,
+ "\040\010\003"},
+ {261, "ATOM", 0, 4, states_5,
+ "\040\000\003"},
};
static label labels[19] = {
- {0, "EMPTY"},
- {256, 0},
- {257, 0},
- {4, 0},
- {0, 0},
- {1, 0},
- {11, 0},
- {258, 0},
- {259, 0},
- {18, 0},
- {260, 0},
- {9, 0},
- {10, 0},
- {261, 0},
- {16, 0},
- {14, 0},
- {3, 0},
- {7, 0},
- {8, 0},
+ {0, "EMPTY"},
+ {256, 0},
+ {257, 0},
+ {4, 0},
+ {0, 0},
+ {1, 0},
+ {11, 0},
+ {258, 0},
+ {259, 0},
+ {18, 0},
+ {260, 0},
+ {9, 0},
+ {10, 0},
+ {261, 0},
+ {16, 0},
+ {14, 0},
+ {3, 0},
+ {7, 0},
+ {8, 0},
};
static grammar _PyParser_Grammar = {
- 6,
- dfas,
- {19, labels},
- 256
+ 6,
+ dfas,
+ {19, labels},
+ 256
};
grammar *
meta_grammar(void)
{
- return &_PyParser_Grammar;
+ return &_PyParser_Grammar;
}
grammar *
diff --git a/Parser/myreadline.c b/Parser/myreadline.c
index 433f995..6d90d20 100644
--- a/Parser/myreadline.c
+++ b/Parser/myreadline.c
@@ -39,64 +39,64 @@ int Py_RISCOSWimpFlag;
static int
my_fgets(char *buf, int len, FILE *fp)
{
- char *p;
- if (PyOS_InputHook != NULL)
- (void)(PyOS_InputHook)();
- errno = 0;
- p = fgets(buf, len, fp);
- if (p != NULL)
- return 0; /* No error */
+ char *p;
+ if (PyOS_InputHook != NULL)
+ (void)(PyOS_InputHook)();
+ errno = 0;
+ p = fgets(buf, len, fp);
+ if (p != NULL)
+ return 0; /* No error */
#ifdef MS_WINDOWS
- /* In the case of a Ctrl+C or some other external event
- interrupting the operation:
- Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32
- error code (and feof() returns TRUE).
- Win9x: Ctrl+C seems to have no effect on fgets() returning
- early - the signal handler is called, but the fgets()
- only returns "normally" (ie, when Enter hit or feof())
- */
- if (GetLastError()==ERROR_OPERATION_ABORTED) {
- /* Signals come asynchronously, so we sleep a brief
- moment before checking if the handler has been
- triggered (we cant just return 1 before the
- signal handler has been called, as the later
- signal may be treated as a separate interrupt).
- */
- Sleep(1);
- if (PyOS_InterruptOccurred()) {
- return 1; /* Interrupt */
- }
- /* Either the sleep wasn't long enough (need a
- short loop retrying?) or not interrupted at all
- (in which case we should revisit the whole thing!)
- Logging some warning would be nice. assert is not
- viable as under the debugger, the various dialogs
- mean the condition is not true.
- */
- }
+ /* In the case of a Ctrl+C or some other external event
+ interrupting the operation:
+ Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32
+ error code (and feof() returns TRUE).
+ Win9x: Ctrl+C seems to have no effect on fgets() returning
+ early - the signal handler is called, but the fgets()
+ only returns "normally" (ie, when Enter hit or feof())
+ */
+ if (GetLastError()==ERROR_OPERATION_ABORTED) {
+ /* Signals come asynchronously, so we sleep a brief
+ moment before checking if the handler has been
+ triggered (we cant just return 1 before the
+ signal handler has been called, as the later
+ signal may be treated as a separate interrupt).
+ */
+ Sleep(1);
+ if (PyOS_InterruptOccurred()) {
+ return 1; /* Interrupt */
+ }
+ /* Either the sleep wasn't long enough (need a
+ short loop retrying?) or not interrupted at all
+ (in which case we should revisit the whole thing!)
+ Logging some warning would be nice. assert is not
+ viable as under the debugger, the various dialogs
+ mean the condition is not true.
+ */
+ }
#endif /* MS_WINDOWS */
- if (feof(fp)) {
- return -1; /* EOF */
- }
+ if (feof(fp)) {
+ return -1; /* EOF */
+ }
#ifdef EINTR
- if (errno == EINTR) {
- int s;
+ if (errno == EINTR) {
+ int s;
#ifdef WITH_THREAD
- PyEval_RestoreThread(_PyOS_ReadlineTState);
+ PyEval_RestoreThread(_PyOS_ReadlineTState);
#endif
- s = PyErr_CheckSignals();
+ s = PyErr_CheckSignals();
#ifdef WITH_THREAD
- PyEval_SaveThread();
+ PyEval_SaveThread();
#endif
- if (s < 0) {
- return 1;
- }
- }
+ if (s < 0) {
+ return 1;
+ }
+ }
#endif
- if (PyOS_InterruptOccurred()) {
- return 1; /* Interrupt */
- }
- return -2; /* Error */
+ if (PyOS_InterruptOccurred()) {
+ return 1; /* Interrupt */
+ }
+ return -2; /* Error */
}
@@ -105,50 +105,50 @@ my_fgets(char *buf, int len, FILE *fp)
char *
PyOS_StdioReadline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
- size_t n;
- char *p;
- n = 100;
- if ((p = (char *)PyMem_MALLOC(n)) == NULL)
- return NULL;
- fflush(sys_stdout);
+ size_t n;
+ char *p;
+ n = 100;
+ if ((p = (char *)PyMem_MALLOC(n)) == NULL)
+ return NULL;
+ fflush(sys_stdout);
#ifndef RISCOS
- if (prompt)
- fprintf(stderr, "%s", prompt);
+ if (prompt)
+ fprintf(stderr, "%s", prompt);
#else
- if (prompt) {
- if(Py_RISCOSWimpFlag)
- fprintf(stderr, "\x0cr%s\x0c", prompt);
- else
- fprintf(stderr, "%s", prompt);
- }
+ if (prompt) {
+ if(Py_RISCOSWimpFlag)
+ fprintf(stderr, "\x0cr%s\x0c", prompt);
+ else
+ fprintf(stderr, "%s", prompt);
+ }
#endif
- fflush(stderr);
- switch (my_fgets(p, (int)n, sys_stdin)) {
- case 0: /* Normal case */
- break;
- case 1: /* Interrupt */
- PyMem_FREE(p);
- return NULL;
- case -1: /* EOF */
- case -2: /* Error */
- default: /* Shouldn't happen */
- *p = '\0';
- break;
- }
- n = strlen(p);
- while (n > 0 && p[n-1] != '\n') {
- size_t incr = n+2;
- p = (char *)PyMem_REALLOC(p, n + incr);
- if (p == NULL)
- return NULL;
- if (incr > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError, "input line too long");
- }
- if (my_fgets(p+n, (int)incr, sys_stdin) != 0)
- break;
- n += strlen(p+n);
- }
- return (char *)PyMem_REALLOC(p, n+1);
+ fflush(stderr);
+ switch (my_fgets(p, (int)n, sys_stdin)) {
+ case 0: /* Normal case */
+ break;
+ case 1: /* Interrupt */
+ PyMem_FREE(p);
+ return NULL;
+ case -1: /* EOF */
+ case -2: /* Error */
+ default: /* Shouldn't happen */
+ *p = '\0';
+ break;
+ }
+ n = strlen(p);
+ while (n > 0 && p[n-1] != '\n') {
+ size_t incr = n+2;
+ p = (char *)PyMem_REALLOC(p, n + incr);
+ if (p == NULL)
+ return NULL;
+ if (incr > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError, "input line too long");
+ }
+ if (my_fgets(p+n, (int)incr, sys_stdin) != 0)
+ break;
+ n += strlen(p+n);
+ }
+ return (char *)PyMem_REALLOC(p, n+1);
}
@@ -165,52 +165,52 @@ char *(*PyOS_ReadlineFunctionPointer)(FILE *, FILE *, char *);
char *
PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
- char *rv;
+ char *rv;
+
+ if (_PyOS_ReadlineTState == PyThreadState_GET()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "can't re-enter readline");
+ return NULL;
+ }
- if (_PyOS_ReadlineTState == PyThreadState_GET()) {
- PyErr_SetString(PyExc_RuntimeError,
- "can't re-enter readline");
- return NULL;
- }
-
- if (PyOS_ReadlineFunctionPointer == NULL) {
+ if (PyOS_ReadlineFunctionPointer == NULL) {
#ifdef __VMS
- PyOS_ReadlineFunctionPointer = vms__StdioReadline;
+ PyOS_ReadlineFunctionPointer = vms__StdioReadline;
#else
- PyOS_ReadlineFunctionPointer = PyOS_StdioReadline;
+ PyOS_ReadlineFunctionPointer = PyOS_StdioReadline;
#endif
- }
-
+ }
+
#ifdef WITH_THREAD
- if (_PyOS_ReadlineLock == NULL) {
- _PyOS_ReadlineLock = PyThread_allocate_lock();
- }
+ if (_PyOS_ReadlineLock == NULL) {
+ _PyOS_ReadlineLock = PyThread_allocate_lock();
+ }
#endif
- _PyOS_ReadlineTState = PyThreadState_GET();
- Py_BEGIN_ALLOW_THREADS
+ _PyOS_ReadlineTState = PyThreadState_GET();
+ Py_BEGIN_ALLOW_THREADS
#ifdef WITH_THREAD
- PyThread_acquire_lock(_PyOS_ReadlineLock, 1);
+ PyThread_acquire_lock(_PyOS_ReadlineLock, 1);
#endif
- /* This is needed to handle the unlikely case that the
- * interpreter is in interactive mode *and* stdin/out are not
- * a tty. This can happen, for example if python is run like
- * this: python -i < test1.py
- */
- if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout)))
- rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt);
- else
- rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout,
- prompt);
- Py_END_ALLOW_THREADS
+ /* This is needed to handle the unlikely case that the
+ * interpreter is in interactive mode *and* stdin/out are not
+ * a tty. This can happen, for example if python is run like
+ * this: python -i < test1.py
+ */
+ if (!isatty (fileno (sys_stdin)) || !isatty (fileno (sys_stdout)))
+ rv = PyOS_StdioReadline (sys_stdin, sys_stdout, prompt);
+ else
+ rv = (*PyOS_ReadlineFunctionPointer)(sys_stdin, sys_stdout,
+ prompt);
+ Py_END_ALLOW_THREADS
#ifdef WITH_THREAD
- PyThread_release_lock(_PyOS_ReadlineLock);
+ PyThread_release_lock(_PyOS_ReadlineLock);
#endif
- _PyOS_ReadlineTState = NULL;
+ _PyOS_ReadlineTState = NULL;
- return rv;
+ return rv;
}
diff --git a/Parser/node.c b/Parser/node.c
index f4c86cb..9eba76b 100644
--- a/Parser/node.c
+++ b/Parser/node.c
@@ -7,30 +7,30 @@
node *
PyNode_New(int type)
{
- node *n = (node *) PyObject_MALLOC(1 * sizeof(node));
- if (n == NULL)
- return NULL;
- n->n_type = type;
- n->n_str = NULL;
- n->n_lineno = 0;
- n->n_nchildren = 0;
- n->n_child = NULL;
- return n;
+ node *n = (node *) PyObject_MALLOC(1 * sizeof(node));
+ if (n == NULL)
+ return NULL;
+ n->n_type = type;
+ n->n_str = NULL;
+ n->n_lineno = 0;
+ n->n_nchildren = 0;
+ n->n_child = NULL;
+ return n;
}
/* See comments at XXXROUNDUP below. Returns -1 on overflow. */
static int
fancy_roundup(int n)
{
- /* Round up to the closest power of 2 >= n. */
- int result = 256;
- assert(n > 128);
- while (result < n) {
- result <<= 1;
- if (result <= 0)
- return -1;
- }
- return result;
+ /* Round up to the closest power of 2 >= n. */
+ int result = 256;
+ assert(n > 128);
+ while (result < n) {
+ result <<= 1;
+ if (result <= 0)
+ return -1;
+ }
+ return result;
}
/* A gimmick to make massive numbers of reallocs quicker. The result is
@@ -70,46 +70,46 @@ fancy_roundup(int n)
* Note that this would be straightforward if a node stored its current
* capacity. The code is tricky to avoid that.
*/
-#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \
- (n) <= 128 ? (((n) + 3) & ~3) : \
- fancy_roundup(n))
+#define XXXROUNDUP(n) ((n) <= 1 ? (n) : \
+ (n) <= 128 ? (((n) + 3) & ~3) : \
+ fancy_roundup(n))
int
PyNode_AddChild(register node *n1, int type, char *str, int lineno, int col_offset)
{
- const int nch = n1->n_nchildren;
- int current_capacity;
- int required_capacity;
- node *n;
+ const int nch = n1->n_nchildren;
+ int current_capacity;
+ int required_capacity;
+ node *n;
- if (nch == INT_MAX || nch < 0)
- return E_OVERFLOW;
+ if (nch == INT_MAX || nch < 0)
+ return E_OVERFLOW;
- current_capacity = XXXROUNDUP(nch);
- required_capacity = XXXROUNDUP(nch + 1);
- if (current_capacity < 0 || required_capacity < 0)
- return E_OVERFLOW;
- if (current_capacity < required_capacity) {
- if (required_capacity > PY_SIZE_MAX / sizeof(node)) {
- return E_NOMEM;
- }
- n = n1->n_child;
- n = (node *) PyObject_REALLOC(n,
- required_capacity * sizeof(node));
- if (n == NULL)
- return E_NOMEM;
- n1->n_child = n;
- }
+ current_capacity = XXXROUNDUP(nch);
+ required_capacity = XXXROUNDUP(nch + 1);
+ if (current_capacity < 0 || required_capacity < 0)
+ return E_OVERFLOW;
+ if (current_capacity < required_capacity) {
+ if (required_capacity > PY_SIZE_MAX / sizeof(node)) {
+ return E_NOMEM;
+ }
+ n = n1->n_child;
+ n = (node *) PyObject_REALLOC(n,
+ required_capacity * sizeof(node));
+ if (n == NULL)
+ return E_NOMEM;
+ n1->n_child = n;
+ }
- n = &n1->n_child[n1->n_nchildren++];
- n->n_type = type;
- n->n_str = str;
- n->n_lineno = lineno;
- n->n_col_offset = col_offset;
- n->n_nchildren = 0;
- n->n_child = NULL;
- return 0;
+ n = &n1->n_child[n1->n_nchildren++];
+ n->n_type = type;
+ n->n_str = str;
+ n->n_lineno = lineno;
+ n->n_col_offset = col_offset;
+ n->n_nchildren = 0;
+ n->n_child = NULL;
+ return 0;
}
/* Forward */
@@ -119,20 +119,20 @@ static void freechildren(node *);
void
PyNode_Free(node *n)
{
- if (n != NULL) {
- freechildren(n);
- PyObject_FREE(n);
- }
+ if (n != NULL) {
+ freechildren(n);
+ PyObject_FREE(n);
+ }
}
static void
freechildren(node *n)
{
- int i;
- for (i = NCH(n); --i >= 0; )
- freechildren(CHILD(n, i));
- if (n->n_child != NULL)
- PyObject_FREE(n->n_child);
- if (STR(n) != NULL)
- PyObject_FREE(STR(n));
+ int i;
+ for (i = NCH(n); --i >= 0; )
+ freechildren(CHILD(n, i));
+ if (n->n_child != NULL)
+ PyObject_FREE(n->n_child);
+ if (STR(n) != NULL)
+ PyObject_FREE(STR(n));
}
diff --git a/Parser/parser.c b/Parser/parser.c
index e597ea2..b753a17 100644
--- a/Parser/parser.c
+++ b/Parser/parser.c
@@ -29,7 +29,7 @@ static void s_reset(stack *);
static void
s_reset(stack *s)
{
- s->s_top = &s->s_base[MAXSTACK];
+ s->s_top = &s->s_base[MAXSTACK];
}
#define s_empty(s) ((s)->s_top == &(s)->s_base[MAXSTACK])
@@ -37,16 +37,16 @@ s_reset(stack *s)
static int
s_push(register stack *s, dfa *d, node *parent)
{
- register stackentry *top;
- if (s->s_top == s->s_base) {
- fprintf(stderr, "s_push: parser stack overflow\n");
- return E_NOMEM;
- }
- top = --s->s_top;
- top->s_dfa = d;
- top->s_parent = parent;
- top->s_state = 0;
- return 0;
+ register stackentry *top;
+ if (s->s_top == s->s_base) {
+ fprintf(stderr, "s_push: parser stack overflow\n");
+ return E_NOMEM;
+ }
+ top = --s->s_top;
+ top->s_dfa = d;
+ top->s_parent = parent;
+ top->s_state = 0;
+ return 0;
}
#ifdef Py_DEBUG
@@ -54,9 +54,9 @@ s_push(register stack *s, dfa *d, node *parent)
static void
s_pop(register stack *s)
{
- if (s_empty(s))
- Py_FatalError("s_pop: parser stack underflow -- FATAL");
- s->s_top++;
+ if (s_empty(s))
+ Py_FatalError("s_pop: parser stack underflow -- FATAL");
+ s->s_top++;
}
#else /* !Py_DEBUG */
@@ -71,34 +71,34 @@ s_pop(register stack *s)
parser_state *
PyParser_New(grammar *g, int start)
{
- parser_state *ps;
-
- if (!g->g_accel)
- PyGrammar_AddAccelerators(g);
- ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state));
- if (ps == NULL)
- return NULL;
- ps->p_grammar = g;
+ parser_state *ps;
+
+ if (!g->g_accel)
+ PyGrammar_AddAccelerators(g);
+ ps = (parser_state *)PyMem_MALLOC(sizeof(parser_state));
+ if (ps == NULL)
+ return NULL;
+ ps->p_grammar = g;
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
- ps->p_flags = 0;
+ ps->p_flags = 0;
#endif
- ps->p_tree = PyNode_New(start);
- if (ps->p_tree == NULL) {
- PyMem_FREE(ps);
- return NULL;
- }
- s_reset(&ps->p_stack);
- (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree);
- return ps;
+ ps->p_tree = PyNode_New(start);
+ if (ps->p_tree == NULL) {
+ PyMem_FREE(ps);
+ return NULL;
+ }
+ s_reset(&ps->p_stack);
+ (void) s_push(&ps->p_stack, PyGrammar_FindDFA(g, start), ps->p_tree);
+ return ps;
}
void
PyParser_Delete(parser_state *ps)
{
- /* NB If you want to save the parse tree,
- you must set p_tree to NULL before calling delparser! */
- PyNode_Free(ps->p_tree);
- PyMem_FREE(ps);
+ /* NB If you want to save the parse tree,
+ you must set p_tree to NULL before calling delparser! */
+ PyNode_Free(ps->p_tree);
+ PyMem_FREE(ps);
}
@@ -107,27 +107,27 @@ PyParser_Delete(parser_state *ps)
static int
shift(register stack *s, int type, char *str, int newstate, int lineno, int col_offset)
{
- int err;
- assert(!s_empty(s));
- err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset);
- if (err)
- return err;
- s->s_top->s_state = newstate;
- return 0;
+ int err;
+ assert(!s_empty(s));
+ err = PyNode_AddChild(s->s_top->s_parent, type, str, lineno, col_offset);
+ if (err)
+ return err;
+ s->s_top->s_state = newstate;
+ return 0;
}
static int
push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offset)
{
- int err;
- register node *n;
- n = s->s_top->s_parent;
- assert(!s_empty(s));
- err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset);
- if (err)
- return err;
- s->s_top->s_state = newstate;
- return s_push(s, d, CHILD(n, NCH(n)-1));
+ int err;
+ register node *n;
+ n = s->s_top->s_parent;
+ assert(!s_empty(s));
+ err = PyNode_AddChild(n, type, (char *)NULL, lineno, col_offset);
+ if (err)
+ return err;
+ s->s_top->s_state = newstate;
+ return s_push(s, d, CHILD(n, NCH(n)-1));
}
@@ -136,189 +136,189 @@ push(register stack *s, int type, dfa *d, int newstate, int lineno, int col_offs
static int
classify(parser_state *ps, int type, char *str)
{
- grammar *g = ps->p_grammar;
- register int n = g->g_ll.ll_nlabels;
-
- if (type == NAME) {
- register char *s = str;
- register label *l = g->g_ll.ll_label;
- register int i;
- for (i = n; i > 0; i--, l++) {
- if (l->lb_type != NAME || l->lb_str == NULL ||
- l->lb_str[0] != s[0] ||
- strcmp(l->lb_str, s) != 0)
- continue;
+ grammar *g = ps->p_grammar;
+ register int n = g->g_ll.ll_nlabels;
+
+ if (type == NAME) {
+ register char *s = str;
+ register label *l = g->g_ll.ll_label;
+ register int i;
+ for (i = n; i > 0; i--, l++) {
+ if (l->lb_type != NAME || l->lb_str == NULL ||
+ l->lb_str[0] != s[0] ||
+ strcmp(l->lb_str, s) != 0)
+ continue;
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
- if (ps->p_flags & CO_FUTURE_PRINT_FUNCTION &&
- s[0] == 'p' && strcmp(s, "print") == 0) {
- break; /* no longer a keyword */
- }
+ if (ps->p_flags & CO_FUTURE_PRINT_FUNCTION &&
+ s[0] == 'p' && strcmp(s, "print") == 0) {
+ break; /* no longer a keyword */
+ }
#endif
- D(printf("It's a keyword\n"));
- return n - i;
- }
- }
-
- {
- register label *l = g->g_ll.ll_label;
- register int i;
- for (i = n; i > 0; i--, l++) {
- if (l->lb_type == type && l->lb_str == NULL) {
- D(printf("It's a token we know\n"));
- return n - i;
- }
- }
- }
-
- D(printf("Illegal token\n"));
- return -1;
+ D(printf("It's a keyword\n"));
+ return n - i;
+ }
+ }
+
+ {
+ register label *l = g->g_ll.ll_label;
+ register int i;
+ for (i = n; i > 0; i--, l++) {
+ if (l->lb_type == type && l->lb_str == NULL) {
+ D(printf("It's a token we know\n"));
+ return n - i;
+ }
+ }
+ }
+
+ D(printf("Illegal token\n"));
+ return -1;
}
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
static void
future_hack(parser_state *ps)
{
- node *n = ps->p_stack.s_top->s_parent;
- node *ch, *cch;
- int i;
-
- /* from __future__ import ..., must have at least 4 children */
- n = CHILD(n, 0);
- if (NCH(n) < 4)
- return;
- ch = CHILD(n, 0);
- if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0)
- return;
- ch = CHILD(n, 1);
- if (NCH(ch) == 1 && STR(CHILD(ch, 0)) &&
- strcmp(STR(CHILD(ch, 0)), "__future__") != 0)
- return;
- ch = CHILD(n, 3);
- /* ch can be a star, a parenthesis or import_as_names */
- if (TYPE(ch) == STAR)
- return;
- if (TYPE(ch) == LPAR)
- ch = CHILD(n, 4);
-
- for (i = 0; i < NCH(ch); i += 2) {
- cch = CHILD(ch, i);
- if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) {
- char *str_ch = STR(CHILD(cch, 0));
- if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) {
- ps->p_flags |= CO_FUTURE_WITH_STATEMENT;
- } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) {
- ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
- } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) {
- ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
- }
- }
- }
+ node *n = ps->p_stack.s_top->s_parent;
+ node *ch, *cch;
+ int i;
+
+ /* from __future__ import ..., must have at least 4 children */
+ n = CHILD(n, 0);
+ if (NCH(n) < 4)
+ return;
+ ch = CHILD(n, 0);
+ if (STR(ch) == NULL || strcmp(STR(ch), "from") != 0)
+ return;
+ ch = CHILD(n, 1);
+ if (NCH(ch) == 1 && STR(CHILD(ch, 0)) &&
+ strcmp(STR(CHILD(ch, 0)), "__future__") != 0)
+ return;
+ ch = CHILD(n, 3);
+ /* ch can be a star, a parenthesis or import_as_names */
+ if (TYPE(ch) == STAR)
+ return;
+ if (TYPE(ch) == LPAR)
+ ch = CHILD(n, 4);
+
+ for (i = 0; i < NCH(ch); i += 2) {
+ cch = CHILD(ch, i);
+ if (NCH(cch) >= 1 && TYPE(CHILD(cch, 0)) == NAME) {
+ char *str_ch = STR(CHILD(cch, 0));
+ if (strcmp(str_ch, FUTURE_WITH_STATEMENT) == 0) {
+ ps->p_flags |= CO_FUTURE_WITH_STATEMENT;
+ } else if (strcmp(str_ch, FUTURE_PRINT_FUNCTION) == 0) {
+ ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
+ } else if (strcmp(str_ch, FUTURE_UNICODE_LITERALS) == 0) {
+ ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
+ }
+ }
+ }
}
#endif /* future keyword */
int
PyParser_AddToken(register parser_state *ps, register int type, char *str,
- int lineno, int col_offset, int *expected_ret)
+ int lineno, int col_offset, int *expected_ret)
{
- register int ilabel;
- int err;
-
- D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));
-
- /* Find out which label this token is */
- ilabel = classify(ps, type, str);
- if (ilabel < 0)
- return E_SYNTAX;
-
- /* Loop until the token is shifted or an error occurred */
- for (;;) {
- /* Fetch the current dfa and state */
- register dfa *d = ps->p_stack.s_top->s_dfa;
- register state *s = &d->d_state[ps->p_stack.s_top->s_state];
-
- D(printf(" DFA '%s', state %d:",
- d->d_name, ps->p_stack.s_top->s_state));
-
- /* Check accelerator */
- if (s->s_lower <= ilabel && ilabel < s->s_upper) {
- register int x = s->s_accel[ilabel - s->s_lower];
- if (x != -1) {
- if (x & (1<<7)) {
- /* Push non-terminal */
- int nt = (x >> 8) + NT_OFFSET;
- int arrow = x & ((1<<7)-1);
- dfa *d1 = PyGrammar_FindDFA(
- ps->p_grammar, nt);
- if ((err = push(&ps->p_stack, nt, d1,
- arrow, lineno, col_offset)) > 0) {
- D(printf(" MemError: push\n"));
- return err;
- }
- D(printf(" Push ...\n"));
- continue;
- }
-
- /* Shift the token */
- if ((err = shift(&ps->p_stack, type, str,
- x, lineno, col_offset)) > 0) {
- D(printf(" MemError: shift.\n"));
- return err;
- }
- D(printf(" Shift.\n"));
- /* Pop while we are in an accept-only state */
- while (s = &d->d_state
- [ps->p_stack.s_top->s_state],
- s->s_accept && s->s_narcs == 1) {
- D(printf(" DFA '%s', state %d: "
- "Direct pop.\n",
- d->d_name,
- ps->p_stack.s_top->s_state));
+ register int ilabel;
+ int err;
+
+ D(printf("Token %s/'%s' ... ", _PyParser_TokenNames[type], str));
+
+ /* Find out which label this token is */
+ ilabel = classify(ps, type, str);
+ if (ilabel < 0)
+ return E_SYNTAX;
+
+ /* Loop until the token is shifted or an error occurred */
+ for (;;) {
+ /* Fetch the current dfa and state */
+ register dfa *d = ps->p_stack.s_top->s_dfa;
+ register state *s = &d->d_state[ps->p_stack.s_top->s_state];
+
+ D(printf(" DFA '%s', state %d:",
+ d->d_name, ps->p_stack.s_top->s_state));
+
+ /* Check accelerator */
+ if (s->s_lower <= ilabel && ilabel < s->s_upper) {
+ register int x = s->s_accel[ilabel - s->s_lower];
+ if (x != -1) {
+ if (x & (1<<7)) {
+ /* Push non-terminal */
+ int nt = (x >> 8) + NT_OFFSET;
+ int arrow = x & ((1<<7)-1);
+ dfa *d1 = PyGrammar_FindDFA(
+ ps->p_grammar, nt);
+ if ((err = push(&ps->p_stack, nt, d1,
+ arrow, lineno, col_offset)) > 0) {
+ D(printf(" MemError: push\n"));
+ return err;
+ }
+ D(printf(" Push ...\n"));
+ continue;
+ }
+
+ /* Shift the token */
+ if ((err = shift(&ps->p_stack, type, str,
+ x, lineno, col_offset)) > 0) {
+ D(printf(" MemError: shift.\n"));
+ return err;
+ }
+ D(printf(" Shift.\n"));
+ /* Pop while we are in an accept-only state */
+ while (s = &d->d_state
+ [ps->p_stack.s_top->s_state],
+ s->s_accept && s->s_narcs == 1) {
+ D(printf(" DFA '%s', state %d: "
+ "Direct pop.\n",
+ d->d_name,
+ ps->p_stack.s_top->s_state));
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
- if (d->d_name[0] == 'i' &&
- strcmp(d->d_name,
- "import_stmt") == 0)
- future_hack(ps);
+ if (d->d_name[0] == 'i' &&
+ strcmp(d->d_name,
+ "import_stmt") == 0)
+ future_hack(ps);
#endif
- s_pop(&ps->p_stack);
- if (s_empty(&ps->p_stack)) {
- D(printf(" ACCEPT.\n"));
- return E_DONE;
- }
- d = ps->p_stack.s_top->s_dfa;
- }
- return E_OK;
- }
- }
-
- if (s->s_accept) {
+ s_pop(&ps->p_stack);
+ if (s_empty(&ps->p_stack)) {
+ D(printf(" ACCEPT.\n"));
+ return E_DONE;
+ }
+ d = ps->p_stack.s_top->s_dfa;
+ }
+ return E_OK;
+ }
+ }
+
+ if (s->s_accept) {
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
- if (d->d_name[0] == 'i' &&
- strcmp(d->d_name, "import_stmt") == 0)
- future_hack(ps);
+ if (d->d_name[0] == 'i' &&
+ strcmp(d->d_name, "import_stmt") == 0)
+ future_hack(ps);
#endif
- /* Pop this dfa and try again */
- s_pop(&ps->p_stack);
- D(printf(" Pop ...\n"));
- if (s_empty(&ps->p_stack)) {
- D(printf(" Error: bottom of stack.\n"));
- return E_SYNTAX;
- }
- continue;
- }
-
- /* Stuck, report syntax error */
- D(printf(" Error.\n"));
- if (expected_ret) {
- if (s->s_lower == s->s_upper - 1) {
- /* Only one possible expected token */
- *expected_ret = ps->p_grammar->
- g_ll.ll_label[s->s_lower].lb_type;
- }
- else
- *expected_ret = -1;
- }
- return E_SYNTAX;
- }
+ /* Pop this dfa and try again */
+ s_pop(&ps->p_stack);
+ D(printf(" Pop ...\n"));
+ if (s_empty(&ps->p_stack)) {
+ D(printf(" Error: bottom of stack.\n"));
+ return E_SYNTAX;
+ }
+ continue;
+ }
+
+ /* Stuck, report syntax error */
+ D(printf(" Error.\n"));
+ if (expected_ret) {
+ if (s->s_lower == s->s_upper - 1) {
+ /* Only one possible expected token */
+ *expected_ret = ps->p_grammar->
+ g_ll.ll_label[s->s_lower].lb_type;
+ }
+ else
+ *expected_ret = -1;
+ }
+ return E_SYNTAX;
+ }
}
@@ -329,62 +329,62 @@ PyParser_AddToken(register parser_state *ps, register int type, char *str,
void
dumptree(grammar *g, node *n)
{
- int i;
-
- if (n == NULL)
- printf("NIL");
- else {
- label l;
- l.lb_type = TYPE(n);
- l.lb_str = STR(n);
- printf("%s", PyGrammar_LabelRepr(&l));
- if (ISNONTERMINAL(TYPE(n))) {
- printf("(");
- for (i = 0; i < NCH(n); i++) {
- if (i > 0)
- printf(",");
- dumptree(g, CHILD(n, i));
- }
- printf(")");
- }
- }
+ int i;
+
+ if (n == NULL)
+ printf("NIL");
+ else {
+ label l;
+ l.lb_type = TYPE(n);
+ l.lb_str = STR(n);
+ printf("%s", PyGrammar_LabelRepr(&l));
+ if (ISNONTERMINAL(TYPE(n))) {
+ printf("(");
+ for (i = 0; i < NCH(n); i++) {
+ if (i > 0)
+ printf(",");
+ dumptree(g, CHILD(n, i));
+ }
+ printf(")");
+ }
+ }
}
void
showtree(grammar *g, node *n)
{
- int i;
-
- if (n == NULL)
- return;
- if (ISNONTERMINAL(TYPE(n))) {
- for (i = 0; i < NCH(n); i++)
- showtree(g, CHILD(n, i));
- }
- else if (ISTERMINAL(TYPE(n))) {
- printf("%s", _PyParser_TokenNames[TYPE(n)]);
- if (TYPE(n) == NUMBER || TYPE(n) == NAME)
- printf("(%s)", STR(n));
- printf(" ");
- }
- else
- printf("? ");
+ int i;
+
+ if (n == NULL)
+ return;
+ if (ISNONTERMINAL(TYPE(n))) {
+ for (i = 0; i < NCH(n); i++)
+ showtree(g, CHILD(n, i));
+ }
+ else if (ISTERMINAL(TYPE(n))) {
+ printf("%s", _PyParser_TokenNames[TYPE(n)]);
+ if (TYPE(n) == NUMBER || TYPE(n) == NAME)
+ printf("(%s)", STR(n));
+ printf(" ");
+ }
+ else
+ printf("? ");
}
void
printtree(parser_state *ps)
{
- if (Py_DebugFlag) {
- printf("Parse tree:\n");
- dumptree(ps->p_grammar, ps->p_tree);
- printf("\n");
- printf("Tokens:\n");
- showtree(ps->p_grammar, ps->p_tree);
- printf("\n");
- }
- printf("Listing:\n");
- PyNode_ListTree(ps->p_tree);
- printf("\n");
+ if (Py_DebugFlag) {
+ printf("Parse tree:\n");
+ dumptree(ps->p_grammar, ps->p_tree);
+ printf("\n");
+ printf("Tokens:\n");
+ showtree(ps->p_grammar, ps->p_tree);
+ printf("\n");
+ }
+ printf("Listing:\n");
+ PyNode_ListTree(ps->p_tree);
+ printf("\n");
}
#endif /* Py_DEBUG */
@@ -419,15 +419,15 @@ symbol.
As an example, consider this grammar:
-expr: term (OP term)*
-term: CONSTANT | '(' expr ')'
+expr: term (OP term)*
+term: CONSTANT | '(' expr ')'
The DFA corresponding to the rule for expr is:
------->.---term-->.------->
- ^ |
- | |
- \----OP----/
+ ^ |
+ | |
+ \----OP----/
The parse tree generated for the input a+b is:
diff --git a/Parser/parsetok.c b/Parser/parsetok.c
index 7f2fb36..e8d396a 100644
--- a/Parser/parsetok.c
+++ b/Parser/parsetok.c
@@ -21,89 +21,89 @@ static void initerr(perrdetail *err_ret, const char* filename);
node *
PyParser_ParseString(const char *s, grammar *g, int start, perrdetail *err_ret)
{
- return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0);
+ return PyParser_ParseStringFlagsFilename(s, NULL, g, start, err_ret, 0);
}
node *
PyParser_ParseStringFlags(const char *s, grammar *g, int start,
- perrdetail *err_ret, int flags)
+ perrdetail *err_ret, int flags)
{
- return PyParser_ParseStringFlagsFilename(s, NULL,
- g, start, err_ret, flags);
+ return PyParser_ParseStringFlagsFilename(s, NULL,
+ g, start, err_ret, flags);
}
node *
PyParser_ParseStringFlagsFilename(const char *s, const char *filename,
- grammar *g, int start,
- perrdetail *err_ret, int flags)
+ grammar *g, int start,
+ perrdetail *err_ret, int flags)
{
- int iflags = flags;
- return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start,
- err_ret, &iflags);
+ int iflags = flags;
+ return PyParser_ParseStringFlagsFilenameEx(s, filename, g, start,
+ err_ret, &iflags);
}
node *
PyParser_ParseStringFlagsFilenameEx(const char *s, const char *filename,
- grammar *g, int start,
- perrdetail *err_ret, int *flags)
+ grammar *g, int start,
+ perrdetail *err_ret, int *flags)
{
- struct tok_state *tok;
+ struct tok_state *tok;
- initerr(err_ret, filename);
+ initerr(err_ret, filename);
- if ((tok = PyTokenizer_FromString(s, start == file_input)) == NULL) {
- err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM;
- return NULL;
- }
+ if ((tok = PyTokenizer_FromString(s, start == file_input)) == NULL) {
+ err_ret->error = PyErr_Occurred() ? E_DECODE : E_NOMEM;
+ return NULL;
+ }
- tok->filename = filename ? filename : "<string>";
- if (Py_TabcheckFlag || Py_VerboseFlag) {
- tok->altwarning = (tok->filename != NULL);
- if (Py_TabcheckFlag >= 2)
- tok->alterror++;
- }
+ tok->filename = filename ? filename : "<string>";
+ if (Py_TabcheckFlag || Py_VerboseFlag) {
+ tok->altwarning = (tok->filename != NULL);
+ if (Py_TabcheckFlag >= 2)
+ tok->alterror++;
+ }
- return parsetok(tok, g, start, err_ret, flags);
+ return parsetok(tok, g, start, err_ret, flags);
}
/* Parse input coming from a file. Return error code, print some errors. */
node *
PyParser_ParseFile(FILE *fp, const char *filename, grammar *g, int start,
- char *ps1, char *ps2, perrdetail *err_ret)
+ char *ps1, char *ps2, perrdetail *err_ret)
{
- return PyParser_ParseFileFlags(fp, filename, g, start, ps1, ps2,
- err_ret, 0);
+ return PyParser_ParseFileFlags(fp, filename, g, start, ps1, ps2,
+ err_ret, 0);
}
node *
PyParser_ParseFileFlags(FILE *fp, const char *filename, grammar *g, int start,
- char *ps1, char *ps2, perrdetail *err_ret, int flags)
+ char *ps1, char *ps2, perrdetail *err_ret, int flags)
{
- int iflags = flags;
- return PyParser_ParseFileFlagsEx(fp, filename, g, start, ps1, ps2, err_ret, &iflags);
+ int iflags = flags;
+ return PyParser_ParseFileFlagsEx(fp, filename, g, start, ps1, ps2, err_ret, &iflags);
}
node *
PyParser_ParseFileFlagsEx(FILE *fp, const char *filename, grammar *g, int start,
- char *ps1, char *ps2, perrdetail *err_ret, int *flags)
+ char *ps1, char *ps2, perrdetail *err_ret, int *flags)
{
- struct tok_state *tok;
-
- initerr(err_ret, filename);
-
- if ((tok = PyTokenizer_FromFile(fp, ps1, ps2)) == NULL) {
- err_ret->error = E_NOMEM;
- return NULL;
- }
- tok->filename = filename;
- if (Py_TabcheckFlag || Py_VerboseFlag) {
- tok->altwarning = (filename != NULL);
- if (Py_TabcheckFlag >= 2)
- tok->alterror++;
- }
-
- return parsetok(tok, g, start, err_ret, flags);
+ struct tok_state *tok;
+
+ initerr(err_ret, filename);
+
+ if ((tok = PyTokenizer_FromFile(fp, ps1, ps2)) == NULL) {
+ err_ret->error = E_NOMEM;
+ return NULL;
+ }
+ tok->filename = filename;
+ if (Py_TabcheckFlag || Py_VerboseFlag) {
+ tok->altwarning = (filename != NULL);
+ if (Py_TabcheckFlag >= 2)
+ tok->alterror++;
+ }
+
+ return parsetok(tok, g, start, err_ret, flags);
}
#if 0
@@ -116,9 +116,9 @@ static char as_msg[] =
static void
warn(const char *msg, const char *filename, int lineno)
{
- if (filename == NULL)
- filename = "<string>";
- PySys_WriteStderr(msg, filename, lineno);
+ if (filename == NULL)
+ filename = "<string>";
+ PySys_WriteStderr(msg, filename, lineno);
}
#endif
@@ -127,157 +127,157 @@ warn(const char *msg, const char *filename, int lineno)
static node *
parsetok(struct tok_state *tok, grammar *g, int start, perrdetail *err_ret,
- int *flags)
+ int *flags)
{
- parser_state *ps;
- node *n;
- int started = 0, handling_import = 0, handling_with = 0;
-
- if ((ps = PyParser_New(g, start)) == NULL) {
- fprintf(stderr, "no mem for new parser\n");
- err_ret->error = E_NOMEM;
- PyTokenizer_Free(tok);
- return NULL;
- }
+ parser_state *ps;
+ node *n;
+ int started = 0, handling_import = 0, handling_with = 0;
+
+ if ((ps = PyParser_New(g, start)) == NULL) {
+ fprintf(stderr, "no mem for new parser\n");
+ err_ret->error = E_NOMEM;
+ PyTokenizer_Free(tok);
+ return NULL;
+ }
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
- if (*flags & PyPARSE_PRINT_IS_FUNCTION) {
- ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
- }
- if (*flags & PyPARSE_UNICODE_LITERALS) {
- ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
- }
+ if (*flags & PyPARSE_PRINT_IS_FUNCTION) {
+ ps->p_flags |= CO_FUTURE_PRINT_FUNCTION;
+ }
+ if (*flags & PyPARSE_UNICODE_LITERALS) {
+ ps->p_flags |= CO_FUTURE_UNICODE_LITERALS;
+ }
#endif
- for (;;) {
- char *a, *b;
- int type;
- size_t len;
- char *str;
- int col_offset;
-
- type = PyTokenizer_Get(tok, &a, &b);
- if (type == ERRORTOKEN) {
- err_ret->error = tok->done;
- break;
- }
- if (type == ENDMARKER && started) {
- type = NEWLINE; /* Add an extra newline */
- handling_with = handling_import = 0;
- started = 0;
- /* Add the right number of dedent tokens,
- except if a certain flag is given --
- codeop.py uses this. */
- if (tok->indent &&
- !(*flags & PyPARSE_DONT_IMPLY_DEDENT))
- {
- tok->pendin = -tok->indent;
- tok->indent = 0;
- }
- }
- else
- started = 1;
- len = b - a; /* XXX this may compute NULL - NULL */
- str = (char *) PyObject_MALLOC(len + 1);
- if (str == NULL) {
- fprintf(stderr, "no mem for next token\n");
- err_ret->error = E_NOMEM;
- break;
- }
- if (len > 0)
- strncpy(str, a, len);
- str[len] = '\0';
+ for (;;) {
+ char *a, *b;
+ int type;
+ size_t len;
+ char *str;
+ int col_offset;
+
+ type = PyTokenizer_Get(tok, &a, &b);
+ if (type == ERRORTOKEN) {
+ err_ret->error = tok->done;
+ break;
+ }
+ if (type == ENDMARKER && started) {
+ type = NEWLINE; /* Add an extra newline */
+ handling_with = handling_import = 0;
+ started = 0;
+ /* Add the right number of dedent tokens,
+ except if a certain flag is given --
+ codeop.py uses this. */
+ if (tok->indent &&
+ !(*flags & PyPARSE_DONT_IMPLY_DEDENT))
+ {
+ tok->pendin = -tok->indent;
+ tok->indent = 0;
+ }
+ }
+ else
+ started = 1;
+ len = b - a; /* XXX this may compute NULL - NULL */
+ str = (char *) PyObject_MALLOC(len + 1);
+ if (str == NULL) {
+ fprintf(stderr, "no mem for next token\n");
+ err_ret->error = E_NOMEM;
+ break;
+ }
+ if (len > 0)
+ strncpy(str, a, len);
+ str[len] = '\0';
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
#endif
- if (a >= tok->line_start)
- col_offset = a - tok->line_start;
- else
- col_offset = -1;
-
- if ((err_ret->error =
- PyParser_AddToken(ps, (int)type, str, tok->lineno, col_offset,
- &(err_ret->expected))) != E_OK) {
- if (err_ret->error != E_DONE) {
- PyObject_FREE(str);
- err_ret->token = type;
- }
- break;
- }
- }
-
- if (err_ret->error == E_DONE) {
- n = ps->p_tree;
- ps->p_tree = NULL;
- }
- else
- n = NULL;
+ if (a >= tok->line_start)
+ col_offset = a - tok->line_start;
+ else
+ col_offset = -1;
+
+ if ((err_ret->error =
+ PyParser_AddToken(ps, (int)type, str, tok->lineno, col_offset,
+ &(err_ret->expected))) != E_OK) {
+ if (err_ret->error != E_DONE) {
+ PyObject_FREE(str);
+ err_ret->token = type;
+ }
+ break;
+ }
+ }
+
+ if (err_ret->error == E_DONE) {
+ n = ps->p_tree;
+ ps->p_tree = NULL;
+ }
+ else
+ n = NULL;
#ifdef PY_PARSER_REQUIRES_FUTURE_KEYWORD
- *flags = ps->p_flags;
+ *flags = ps->p_flags;
#endif
- PyParser_Delete(ps);
-
- if (n == NULL) {
- if (tok->lineno <= 1 && tok->done == E_EOF)
- err_ret->error = E_EOF;
- err_ret->lineno = tok->lineno;
- if (tok->buf != NULL) {
- char *text = NULL;
- size_t len;
- assert(tok->cur - tok->buf < INT_MAX);
- err_ret->offset = (int)(tok->cur - tok->buf);
- len = tok->inp - tok->buf;
+ PyParser_Delete(ps);
+
+ if (n == NULL) {
+ if (tok->lineno <= 1 && tok->done == E_EOF)
+ err_ret->error = E_EOF;
+ err_ret->lineno = tok->lineno;
+ if (tok->buf != NULL) {
+ char *text = NULL;
+ size_t len;
+ assert(tok->cur - tok->buf < INT_MAX);
+ err_ret->offset = (int)(tok->cur - tok->buf);
+ len = tok->inp - tok->buf;
#ifdef Py_USING_UNICODE
- text = PyTokenizer_RestoreEncoding(tok, len, &err_ret->offset);
+ text = PyTokenizer_RestoreEncoding(tok, len, &err_ret->offset);
#endif
- if (text == NULL) {
- text = (char *) PyObject_MALLOC(len + 1);
- if (text != NULL) {
- if (len > 0)
- strncpy(text, tok->buf, len);
- text[len] = '\0';
- }
- }
- err_ret->text = text;
- }
- } else if (tok->encoding != NULL) {
- /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was
- * allocated using PyMem_
- */
- node* r = PyNode_New(encoding_decl);
- if (r)
- r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1);
- if (!r || !r->n_str) {
- err_ret->error = E_NOMEM;
- if (r)
- PyObject_FREE(r);
- n = NULL;
- goto done;
- }
- strcpy(r->n_str, tok->encoding);
- PyMem_FREE(tok->encoding);
- tok->encoding = NULL;
- r->n_nchildren = 1;
- r->n_child = n;
- n = r;
- }
+ if (text == NULL) {
+ text = (char *) PyObject_MALLOC(len + 1);
+ if (text != NULL) {
+ if (len > 0)
+ strncpy(text, tok->buf, len);
+ text[len] = '\0';
+ }
+ }
+ err_ret->text = text;
+ }
+ } else if (tok->encoding != NULL) {
+ /* 'nodes->n_str' uses PyObject_*, while 'tok->encoding' was
+ * allocated using PyMem_
+ */
+ node* r = PyNode_New(encoding_decl);
+ if (r)
+ r->n_str = PyObject_MALLOC(strlen(tok->encoding)+1);
+ if (!r || !r->n_str) {
+ err_ret->error = E_NOMEM;
+ if (r)
+ PyObject_FREE(r);
+ n = NULL;
+ goto done;
+ }
+ strcpy(r->n_str, tok->encoding);
+ PyMem_FREE(tok->encoding);
+ tok->encoding = NULL;
+ r->n_nchildren = 1;
+ r->n_child = n;
+ n = r;
+ }
done:
- PyTokenizer_Free(tok);
+ PyTokenizer_Free(tok);
- return n;
+ return n;
}
static void
initerr(perrdetail *err_ret, const char *filename)
{
- err_ret->error = E_OK;
- err_ret->filename = filename;
- err_ret->lineno = 0;
- err_ret->offset = 0;
- err_ret->text = NULL;
- err_ret->token = -1;
- err_ret->expected = -1;
+ err_ret->error = E_OK;
+ err_ret->filename = filename;
+ err_ret->lineno = 0;
+ err_ret->offset = 0;
+ err_ret->text = NULL;
+ err_ret->token = -1;
+ err_ret->expected = -1;
}
diff --git a/Parser/pgen.c b/Parser/pgen.c
index 959a5d3..beaf53b 100644
--- a/Parser/pgen.c
+++ b/Parser/pgen.c
@@ -17,85 +17,85 @@ extern int Py_IgnoreEnvironmentFlag; /* needed by Py_GETENV */
/* PART ONE -- CONSTRUCT NFA -- Cf. Algorithm 3.2 from [Aho&Ullman 77] */
typedef struct _nfaarc {
- int ar_label;
- int ar_arrow;
+ int ar_label;
+ int ar_arrow;
} nfaarc;
typedef struct _nfastate {
- int st_narcs;
- nfaarc *st_arc;
+ int st_narcs;
+ nfaarc *st_arc;
} nfastate;
typedef struct _nfa {
- int nf_type;
- char *nf_name;
- int nf_nstates;
- nfastate *nf_state;
- int nf_start, nf_finish;
+ int nf_type;
+ char *nf_name;
+ int nf_nstates;
+ nfastate *nf_state;
+ int nf_start, nf_finish;
} nfa;
/* Forward */
static void compile_rhs(labellist *ll,
- nfa *nf, node *n, int *pa, int *pb);
+ nfa *nf, node *n, int *pa, int *pb);
static void compile_alt(labellist *ll,
- nfa *nf, node *n, int *pa, int *pb);
+ nfa *nf, node *n, int *pa, int *pb);
static void compile_item(labellist *ll,
- nfa *nf, node *n, int *pa, int *pb);
+ nfa *nf, node *n, int *pa, int *pb);
static void compile_atom(labellist *ll,
- nfa *nf, node *n, int *pa, int *pb);
+ nfa *nf, node *n, int *pa, int *pb);
static int
addnfastate(nfa *nf)
{
- nfastate *st;
-
- nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state,
- sizeof(nfastate) * (nf->nf_nstates + 1));
- if (nf->nf_state == NULL)
- Py_FatalError("out of mem");
- st = &nf->nf_state[nf->nf_nstates++];
- st->st_narcs = 0;
- st->st_arc = NULL;
- return st - nf->nf_state;
+ nfastate *st;
+
+ nf->nf_state = (nfastate *)PyObject_REALLOC(nf->nf_state,
+ sizeof(nfastate) * (nf->nf_nstates + 1));
+ if (nf->nf_state == NULL)
+ Py_FatalError("out of mem");
+ st = &nf->nf_state[nf->nf_nstates++];
+ st->st_narcs = 0;
+ st->st_arc = NULL;
+ return st - nf->nf_state;
}
static void
addnfaarc(nfa *nf, int from, int to, int lbl)
{
- nfastate *st;
- nfaarc *ar;
-
- st = &nf->nf_state[from];
- st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc,
- sizeof(nfaarc) * (st->st_narcs + 1));
- if (st->st_arc == NULL)
- Py_FatalError("out of mem");
- ar = &st->st_arc[st->st_narcs++];
- ar->ar_label = lbl;
- ar->ar_arrow = to;
+ nfastate *st;
+ nfaarc *ar;
+
+ st = &nf->nf_state[from];
+ st->st_arc = (nfaarc *)PyObject_REALLOC(st->st_arc,
+ sizeof(nfaarc) * (st->st_narcs + 1));
+ if (st->st_arc == NULL)
+ Py_FatalError("out of mem");
+ ar = &st->st_arc[st->st_narcs++];
+ ar->ar_label = lbl;
+ ar->ar_arrow = to;
}
static nfa *
newnfa(char *name)
{
- nfa *nf;
- static int type = NT_OFFSET; /* All types will be disjunct */
-
- nf = (nfa *)PyObject_MALLOC(sizeof(nfa));
- if (nf == NULL)
- Py_FatalError("no mem for new nfa");
- nf->nf_type = type++;
- nf->nf_name = name; /* XXX strdup(name) ??? */
- nf->nf_nstates = 0;
- nf->nf_state = NULL;
- nf->nf_start = nf->nf_finish = -1;
- return nf;
+ nfa *nf;
+ static int type = NT_OFFSET; /* All types will be disjunct */
+
+ nf = (nfa *)PyObject_MALLOC(sizeof(nfa));
+ if (nf == NULL)
+ Py_FatalError("no mem for new nfa");
+ nf->nf_type = type++;
+ nf->nf_name = name; /* XXX strdup(name) ??? */
+ nf->nf_nstates = 0;
+ nf->nf_state = NULL;
+ nf->nf_start = nf->nf_finish = -1;
+ return nf;
}
typedef struct _nfagrammar {
- int gr_nnfas;
- nfa **gr_nfa;
- labellist gr_ll;
+ int gr_nnfas;
+ nfa **gr_nfa;
+ labellist gr_ll;
} nfagrammar;
/* Forward */
@@ -104,32 +104,32 @@ static void compile_rule(nfagrammar *gr, node *n);
static nfagrammar *
newnfagrammar(void)
{
- nfagrammar *gr;
-
- gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar));
- if (gr == NULL)
- Py_FatalError("no mem for new nfa grammar");
- gr->gr_nnfas = 0;
- gr->gr_nfa = NULL;
- gr->gr_ll.ll_nlabels = 0;
- gr->gr_ll.ll_label = NULL;
- addlabel(&gr->gr_ll, ENDMARKER, "EMPTY");
- return gr;
+ nfagrammar *gr;
+
+ gr = (nfagrammar *)PyObject_MALLOC(sizeof(nfagrammar));
+ if (gr == NULL)
+ Py_FatalError("no mem for new nfa grammar");
+ gr->gr_nnfas = 0;
+ gr->gr_nfa = NULL;
+ gr->gr_ll.ll_nlabels = 0;
+ gr->gr_ll.ll_label = NULL;
+ addlabel(&gr->gr_ll, ENDMARKER, "EMPTY");
+ return gr;
}
static nfa *
addnfa(nfagrammar *gr, char *name)
{
- nfa *nf;
-
- nf = newnfa(name);
- gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa,
- sizeof(nfa*) * (gr->gr_nnfas + 1));
- if (gr->gr_nfa == NULL)
- Py_FatalError("out of mem");
- gr->gr_nfa[gr->gr_nnfas++] = nf;
- addlabel(&gr->gr_ll, NAME, nf->nf_name);
- return nf;
+ nfa *nf;
+
+ nf = newnfa(name);
+ gr->gr_nfa = (nfa **)PyObject_REALLOC(gr->gr_nfa,
+ sizeof(nfa*) * (gr->gr_nnfas + 1));
+ if (gr->gr_nfa == NULL)
+ Py_FatalError("out of mem");
+ gr->gr_nfa[gr->gr_nnfas++] = nf;
+ addlabel(&gr->gr_ll, NAME, nf->nf_name);
+ return nf;
}
#ifdef Py_DEBUG
@@ -137,203 +137,203 @@ addnfa(nfagrammar *gr, char *name)
static char REQNFMT[] = "metacompile: less than %d children\n";
#define REQN(i, count) \
- if (i < count) { \
- fprintf(stderr, REQNFMT, count); \
- Py_FatalError("REQN"); \
- } else
+ if (i < count) { \
+ fprintf(stderr, REQNFMT, count); \
+ Py_FatalError("REQN"); \
+ } else
#else
-#define REQN(i, count) /* empty */
+#define REQN(i, count) /* empty */
#endif
static nfagrammar *
metacompile(node *n)
{
- nfagrammar *gr;
- int i;
-
- if (Py_DebugFlag)
- printf("Compiling (meta-) parse tree into NFA grammar\n");
- gr = newnfagrammar();
- REQ(n, MSTART);
- i = n->n_nchildren - 1; /* Last child is ENDMARKER */
- n = n->n_child;
- for (; --i >= 0; n++) {
- if (n->n_type != NEWLINE)
- compile_rule(gr, n);
- }
- return gr;
+ nfagrammar *gr;
+ int i;
+
+ if (Py_DebugFlag)
+ printf("Compiling (meta-) parse tree into NFA grammar\n");
+ gr = newnfagrammar();
+ REQ(n, MSTART);
+ i = n->n_nchildren - 1; /* Last child is ENDMARKER */
+ n = n->n_child;
+ for (; --i >= 0; n++) {
+ if (n->n_type != NEWLINE)
+ compile_rule(gr, n);
+ }
+ return gr;
}
static void
compile_rule(nfagrammar *gr, node *n)
{
- nfa *nf;
-
- REQ(n, RULE);
- REQN(n->n_nchildren, 4);
- n = n->n_child;
- REQ(n, NAME);
- nf = addnfa(gr, n->n_str);
- n++;
- REQ(n, COLON);
- n++;
- REQ(n, RHS);
- compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish);
- n++;
- REQ(n, NEWLINE);
+ nfa *nf;
+
+ REQ(n, RULE);
+ REQN(n->n_nchildren, 4);
+ n = n->n_child;
+ REQ(n, NAME);
+ nf = addnfa(gr, n->n_str);
+ n++;
+ REQ(n, COLON);
+ n++;
+ REQ(n, RHS);
+ compile_rhs(&gr->gr_ll, nf, n, &nf->nf_start, &nf->nf_finish);
+ n++;
+ REQ(n, NEWLINE);
}
static void
compile_rhs(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
{
- int i;
- int a, b;
-
- REQ(n, RHS);
- i = n->n_nchildren;
- REQN(i, 1);
- n = n->n_child;
- REQ(n, ALT);
- compile_alt(ll, nf, n, pa, pb);
- if (--i <= 0)
- return;
- n++;
- a = *pa;
- b = *pb;
- *pa = addnfastate(nf);
- *pb = addnfastate(nf);
- addnfaarc(nf, *pa, a, EMPTY);
- addnfaarc(nf, b, *pb, EMPTY);
- for (; --i >= 0; n++) {
- REQ(n, VBAR);
- REQN(i, 1);
- --i;
- n++;
- REQ(n, ALT);
- compile_alt(ll, nf, n, &a, &b);
- addnfaarc(nf, *pa, a, EMPTY);
- addnfaarc(nf, b, *pb, EMPTY);
- }
+ int i;
+ int a, b;
+
+ REQ(n, RHS);
+ i = n->n_nchildren;
+ REQN(i, 1);
+ n = n->n_child;
+ REQ(n, ALT);
+ compile_alt(ll, nf, n, pa, pb);
+ if (--i <= 0)
+ return;
+ n++;
+ a = *pa;
+ b = *pb;
+ *pa = addnfastate(nf);
+ *pb = addnfastate(nf);
+ addnfaarc(nf, *pa, a, EMPTY);
+ addnfaarc(nf, b, *pb, EMPTY);
+ for (; --i >= 0; n++) {
+ REQ(n, VBAR);
+ REQN(i, 1);
+ --i;
+ n++;
+ REQ(n, ALT);
+ compile_alt(ll, nf, n, &a, &b);
+ addnfaarc(nf, *pa, a, EMPTY);
+ addnfaarc(nf, b, *pb, EMPTY);
+ }
}
static void
compile_alt(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
{
- int i;
- int a, b;
-
- REQ(n, ALT);
- i = n->n_nchildren;
- REQN(i, 1);
- n = n->n_child;
- REQ(n, ITEM);
- compile_item(ll, nf, n, pa, pb);
- --i;
- n++;
- for (; --i >= 0; n++) {
- REQ(n, ITEM);
- compile_item(ll, nf, n, &a, &b);
- addnfaarc(nf, *pb, a, EMPTY);
- *pb = b;
- }
+ int i;
+ int a, b;
+
+ REQ(n, ALT);
+ i = n->n_nchildren;
+ REQN(i, 1);
+ n = n->n_child;
+ REQ(n, ITEM);
+ compile_item(ll, nf, n, pa, pb);
+ --i;
+ n++;
+ for (; --i >= 0; n++) {
+ REQ(n, ITEM);
+ compile_item(ll, nf, n, &a, &b);
+ addnfaarc(nf, *pb, a, EMPTY);
+ *pb = b;
+ }
}
static void
compile_item(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
{
- int i;
- int a, b;
-
- REQ(n, ITEM);
- i = n->n_nchildren;
- REQN(i, 1);
- n = n->n_child;
- if (n->n_type == LSQB) {
- REQN(i, 3);
- n++;
- REQ(n, RHS);
- *pa = addnfastate(nf);
- *pb = addnfastate(nf);
- addnfaarc(nf, *pa, *pb, EMPTY);
- compile_rhs(ll, nf, n, &a, &b);
- addnfaarc(nf, *pa, a, EMPTY);
- addnfaarc(nf, b, *pb, EMPTY);
- REQN(i, 1);
- n++;
- REQ(n, RSQB);
- }
- else {
- compile_atom(ll, nf, n, pa, pb);
- if (--i <= 0)
- return;
- n++;
- addnfaarc(nf, *pb, *pa, EMPTY);
- if (n->n_type == STAR)
- *pb = *pa;
- else
- REQ(n, PLUS);
- }
+ int i;
+ int a, b;
+
+ REQ(n, ITEM);
+ i = n->n_nchildren;
+ REQN(i, 1);
+ n = n->n_child;
+ if (n->n_type == LSQB) {
+ REQN(i, 3);
+ n++;
+ REQ(n, RHS);
+ *pa = addnfastate(nf);
+ *pb = addnfastate(nf);
+ addnfaarc(nf, *pa, *pb, EMPTY);
+ compile_rhs(ll, nf, n, &a, &b);
+ addnfaarc(nf, *pa, a, EMPTY);
+ addnfaarc(nf, b, *pb, EMPTY);
+ REQN(i, 1);
+ n++;
+ REQ(n, RSQB);
+ }
+ else {
+ compile_atom(ll, nf, n, pa, pb);
+ if (--i <= 0)
+ return;
+ n++;
+ addnfaarc(nf, *pb, *pa, EMPTY);
+ if (n->n_type == STAR)
+ *pb = *pa;
+ else
+ REQ(n, PLUS);
+ }
}
static void
compile_atom(labellist *ll, nfa *nf, node *n, int *pa, int *pb)
{
- int i;
-
- REQ(n, ATOM);
- i = n->n_nchildren;
- REQN(i, 1);
- n = n->n_child;
- if (n->n_type == LPAR) {
- REQN(i, 3);
- n++;
- REQ(n, RHS);
- compile_rhs(ll, nf, n, pa, pb);
- n++;
- REQ(n, RPAR);
- }
- else if (n->n_type == NAME || n->n_type == STRING) {
- *pa = addnfastate(nf);
- *pb = addnfastate(nf);
- addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str));
- }
- else
- REQ(n, NAME);
+ int i;
+
+ REQ(n, ATOM);
+ i = n->n_nchildren;
+ REQN(i, 1);
+ n = n->n_child;
+ if (n->n_type == LPAR) {
+ REQN(i, 3);
+ n++;
+ REQ(n, RHS);
+ compile_rhs(ll, nf, n, pa, pb);
+ n++;
+ REQ(n, RPAR);
+ }
+ else if (n->n_type == NAME || n->n_type == STRING) {
+ *pa = addnfastate(nf);
+ *pb = addnfastate(nf);
+ addnfaarc(nf, *pa, *pb, addlabel(ll, n->n_type, n->n_str));
+ }
+ else
+ REQ(n, NAME);
}
static void
dumpstate(labellist *ll, nfa *nf, int istate)
{
- nfastate *st;
- int i;
- nfaarc *ar;
-
- printf("%c%2d%c",
- istate == nf->nf_start ? '*' : ' ',
- istate,
- istate == nf->nf_finish ? '.' : ' ');
- st = &nf->nf_state[istate];
- ar = st->st_arc;
- for (i = 0; i < st->st_narcs; i++) {
- if (i > 0)
- printf("\n ");
- printf("-> %2d %s", ar->ar_arrow,
- PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label]));
- ar++;
- }
- printf("\n");
+ nfastate *st;
+ int i;
+ nfaarc *ar;
+
+ printf("%c%2d%c",
+ istate == nf->nf_start ? '*' : ' ',
+ istate,
+ istate == nf->nf_finish ? '.' : ' ');
+ st = &nf->nf_state[istate];
+ ar = st->st_arc;
+ for (i = 0; i < st->st_narcs; i++) {
+ if (i > 0)
+ printf("\n ");
+ printf("-> %2d %s", ar->ar_arrow,
+ PyGrammar_LabelRepr(&ll->ll_label[ar->ar_label]));
+ ar++;
+ }
+ printf("\n");
}
static void
dumpnfa(labellist *ll, nfa *nf)
{
- int i;
-
- printf("NFA '%s' has %d states; start %d, finish %d\n",
- nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish);
- for (i = 0; i < nf->nf_nstates; i++)
- dumpstate(ll, nf, i);
+ int i;
+
+ printf("NFA '%s' has %d states; start %d, finish %d\n",
+ nf->nf_name, nf->nf_nstates, nf->nf_start, nf->nf_finish);
+ for (i = 0; i < nf->nf_nstates; i++)
+ dumpstate(ll, nf, i);
}
@@ -342,184 +342,184 @@ dumpnfa(labellist *ll, nfa *nf)
static void
addclosure(bitset ss, nfa *nf, int istate)
{
- if (addbit(ss, istate)) {
- nfastate *st = &nf->nf_state[istate];
- nfaarc *ar = st->st_arc;
- int i;
-
- for (i = st->st_narcs; --i >= 0; ) {
- if (ar->ar_label == EMPTY)
- addclosure(ss, nf, ar->ar_arrow);
- ar++;
- }
- }
+ if (addbit(ss, istate)) {
+ nfastate *st = &nf->nf_state[istate];
+ nfaarc *ar = st->st_arc;
+ int i;
+
+ for (i = st->st_narcs; --i >= 0; ) {
+ if (ar->ar_label == EMPTY)
+ addclosure(ss, nf, ar->ar_arrow);
+ ar++;
+ }
+ }
}
typedef struct _ss_arc {
- bitset sa_bitset;
- int sa_arrow;
- int sa_label;
+ bitset sa_bitset;
+ int sa_arrow;
+ int sa_label;
} ss_arc;
typedef struct _ss_state {
- bitset ss_ss;
- int ss_narcs;
- struct _ss_arc *ss_arc;
- int ss_deleted;
- int ss_finish;
- int ss_rename;
+ bitset ss_ss;
+ int ss_narcs;
+ struct _ss_arc *ss_arc;
+ int ss_deleted;
+ int ss_finish;
+ int ss_rename;
} ss_state;
typedef struct _ss_dfa {
- int sd_nstates;
- ss_state *sd_state;
+ int sd_nstates;
+ ss_state *sd_state;
} ss_dfa;
/* Forward */
static void printssdfa(int xx_nstates, ss_state *xx_state, int nbits,
- labellist *ll, char *msg);
+ labellist *ll, char *msg);
static void simplify(int xx_nstates, ss_state *xx_state);
static void convert(dfa *d, int xx_nstates, ss_state *xx_state);
static void
makedfa(nfagrammar *gr, nfa *nf, dfa *d)
{
- int nbits = nf->nf_nstates;
- bitset ss;
- int xx_nstates;
- ss_state *xx_state, *yy;
- ss_arc *zz;
- int istate, jstate, iarc, jarc, ibit;
- nfastate *st;
- nfaarc *ar;
-
- ss = newbitset(nbits);
- addclosure(ss, nf, nf->nf_start);
- xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state));
- if (xx_state == NULL)
- Py_FatalError("no mem for xx_state in makedfa");
- xx_nstates = 1;
- yy = &xx_state[0];
- yy->ss_ss = ss;
- yy->ss_narcs = 0;
- yy->ss_arc = NULL;
- yy->ss_deleted = 0;
- yy->ss_finish = testbit(ss, nf->nf_finish);
- if (yy->ss_finish)
- printf("Error: nonterminal '%s' may produce empty.\n",
- nf->nf_name);
-
- /* This algorithm is from a book written before
- the invention of structured programming... */
-
- /* For each unmarked state... */
- for (istate = 0; istate < xx_nstates; ++istate) {
- size_t size;
- yy = &xx_state[istate];
- ss = yy->ss_ss;
- /* For all its states... */
- for (ibit = 0; ibit < nf->nf_nstates; ++ibit) {
- if (!testbit(ss, ibit))
- continue;
- st = &nf->nf_state[ibit];
- /* For all non-empty arcs from this state... */
- for (iarc = 0; iarc < st->st_narcs; iarc++) {
- ar = &st->st_arc[iarc];
- if (ar->ar_label == EMPTY)
- continue;
- /* Look up in list of arcs from this state */
- for (jarc = 0; jarc < yy->ss_narcs; ++jarc) {
- zz = &yy->ss_arc[jarc];
- if (ar->ar_label == zz->sa_label)
- goto found;
- }
- /* Add new arc for this state */
- size = sizeof(ss_arc) * (yy->ss_narcs + 1);
- yy->ss_arc = (ss_arc *)PyObject_REALLOC(
- yy->ss_arc, size);
- if (yy->ss_arc == NULL)
- Py_FatalError("out of mem");
- zz = &yy->ss_arc[yy->ss_narcs++];
- zz->sa_label = ar->ar_label;
- zz->sa_bitset = newbitset(nbits);
- zz->sa_arrow = -1;
- found: ;
- /* Add destination */
- addclosure(zz->sa_bitset, nf, ar->ar_arrow);
- }
- }
- /* Now look up all the arrow states */
- for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) {
- zz = &xx_state[istate].ss_arc[jarc];
- for (jstate = 0; jstate < xx_nstates; jstate++) {
- if (samebitset(zz->sa_bitset,
- xx_state[jstate].ss_ss, nbits)) {
- zz->sa_arrow = jstate;
- goto done;
- }
- }
- size = sizeof(ss_state) * (xx_nstates + 1);
- xx_state = (ss_state *)PyObject_REALLOC(xx_state,
- size);
- if (xx_state == NULL)
- Py_FatalError("out of mem");
- zz->sa_arrow = xx_nstates;
- yy = &xx_state[xx_nstates++];
- yy->ss_ss = zz->sa_bitset;
- yy->ss_narcs = 0;
- yy->ss_arc = NULL;
- yy->ss_deleted = 0;
- yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish);
- done: ;
- }
- }
-
- if (Py_DebugFlag)
- printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll,
- "before minimizing");
-
- simplify(xx_nstates, xx_state);
-
- if (Py_DebugFlag)
- printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll,
- "after minimizing");
-
- convert(d, xx_nstates, xx_state);
-
- /* XXX cleanup */
- PyObject_FREE(xx_state);
+ int nbits = nf->nf_nstates;
+ bitset ss;
+ int xx_nstates;
+ ss_state *xx_state, *yy;
+ ss_arc *zz;
+ int istate, jstate, iarc, jarc, ibit;
+ nfastate *st;
+ nfaarc *ar;
+
+ ss = newbitset(nbits);
+ addclosure(ss, nf, nf->nf_start);
+ xx_state = (ss_state *)PyObject_MALLOC(sizeof(ss_state));
+ if (xx_state == NULL)
+ Py_FatalError("no mem for xx_state in makedfa");
+ xx_nstates = 1;
+ yy = &xx_state[0];
+ yy->ss_ss = ss;
+ yy->ss_narcs = 0;
+ yy->ss_arc = NULL;
+ yy->ss_deleted = 0;
+ yy->ss_finish = testbit(ss, nf->nf_finish);
+ if (yy->ss_finish)
+ printf("Error: nonterminal '%s' may produce empty.\n",
+ nf->nf_name);
+
+ /* This algorithm is from a book written before
+ the invention of structured programming... */
+
+ /* For each unmarked state... */
+ for (istate = 0; istate < xx_nstates; ++istate) {
+ size_t size;
+ yy = &xx_state[istate];
+ ss = yy->ss_ss;
+ /* For all its states... */
+ for (ibit = 0; ibit < nf->nf_nstates; ++ibit) {
+ if (!testbit(ss, ibit))
+ continue;
+ st = &nf->nf_state[ibit];
+ /* For all non-empty arcs from this state... */
+ for (iarc = 0; iarc < st->st_narcs; iarc++) {
+ ar = &st->st_arc[iarc];
+ if (ar->ar_label == EMPTY)
+ continue;
+ /* Look up in list of arcs from this state */
+ for (jarc = 0; jarc < yy->ss_narcs; ++jarc) {
+ zz = &yy->ss_arc[jarc];
+ if (ar->ar_label == zz->sa_label)
+ goto found;
+ }
+ /* Add new arc for this state */
+ size = sizeof(ss_arc) * (yy->ss_narcs + 1);
+ yy->ss_arc = (ss_arc *)PyObject_REALLOC(
+ yy->ss_arc, size);
+ if (yy->ss_arc == NULL)
+ Py_FatalError("out of mem");
+ zz = &yy->ss_arc[yy->ss_narcs++];
+ zz->sa_label = ar->ar_label;
+ zz->sa_bitset = newbitset(nbits);
+ zz->sa_arrow = -1;
+ found: ;
+ /* Add destination */
+ addclosure(zz->sa_bitset, nf, ar->ar_arrow);
+ }
+ }
+ /* Now look up all the arrow states */
+ for (jarc = 0; jarc < xx_state[istate].ss_narcs; jarc++) {
+ zz = &xx_state[istate].ss_arc[jarc];
+ for (jstate = 0; jstate < xx_nstates; jstate++) {
+ if (samebitset(zz->sa_bitset,
+ xx_state[jstate].ss_ss, nbits)) {
+ zz->sa_arrow = jstate;
+ goto done;
+ }
+ }
+ size = sizeof(ss_state) * (xx_nstates + 1);
+ xx_state = (ss_state *)PyObject_REALLOC(xx_state,
+ size);
+ if (xx_state == NULL)
+ Py_FatalError("out of mem");
+ zz->sa_arrow = xx_nstates;
+ yy = &xx_state[xx_nstates++];
+ yy->ss_ss = zz->sa_bitset;
+ yy->ss_narcs = 0;
+ yy->ss_arc = NULL;
+ yy->ss_deleted = 0;
+ yy->ss_finish = testbit(yy->ss_ss, nf->nf_finish);
+ done: ;
+ }
+ }
+
+ if (Py_DebugFlag)
+ printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll,
+ "before minimizing");
+
+ simplify(xx_nstates, xx_state);
+
+ if (Py_DebugFlag)
+ printssdfa(xx_nstates, xx_state, nbits, &gr->gr_ll,
+ "after minimizing");
+
+ convert(d, xx_nstates, xx_state);
+
+ /* XXX cleanup */
+ PyObject_FREE(xx_state);
}
static void
printssdfa(int xx_nstates, ss_state *xx_state, int nbits,
- labellist *ll, char *msg)
+ labellist *ll, char *msg)
{
- int i, ibit, iarc;
- ss_state *yy;
- ss_arc *zz;
-
- printf("Subset DFA %s\n", msg);
- for (i = 0; i < xx_nstates; i++) {
- yy = &xx_state[i];
- if (yy->ss_deleted)
- continue;
- printf(" Subset %d", i);
- if (yy->ss_finish)
- printf(" (finish)");
- printf(" { ");
- for (ibit = 0; ibit < nbits; ibit++) {
- if (testbit(yy->ss_ss, ibit))
- printf("%d ", ibit);
- }
- printf("}\n");
- for (iarc = 0; iarc < yy->ss_narcs; iarc++) {
- zz = &yy->ss_arc[iarc];
- printf(" Arc to state %d, label %s\n",
- zz->sa_arrow,
- PyGrammar_LabelRepr(
- &ll->ll_label[zz->sa_label]));
- }
- }
+ int i, ibit, iarc;
+ ss_state *yy;
+ ss_arc *zz;
+
+ printf("Subset DFA %s\n", msg);
+ for (i = 0; i < xx_nstates; i++) {
+ yy = &xx_state[i];
+ if (yy->ss_deleted)
+ continue;
+ printf(" Subset %d", i);
+ if (yy->ss_finish)
+ printf(" (finish)");
+ printf(" { ");
+ for (ibit = 0; ibit < nbits; ibit++) {
+ if (testbit(yy->ss_ss, ibit))
+ printf("%d ", ibit);
+ }
+ printf("}\n");
+ for (iarc = 0; iarc < yy->ss_narcs; iarc++) {
+ zz = &yy->ss_arc[iarc];
+ printf(" Arc to state %d, label %s\n",
+ zz->sa_arrow,
+ PyGrammar_LabelRepr(
+ &ll->ll_label[zz->sa_label]));
+ }
+ }
}
@@ -535,59 +535,59 @@ printssdfa(int xx_nstates, ss_state *xx_state, int nbits,
static int
samestate(ss_state *s1, ss_state *s2)
{
- int i;
-
- if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish)
- return 0;
- for (i = 0; i < s1->ss_narcs; i++) {
- if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow ||
- s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label)
- return 0;
- }
- return 1;
+ int i;
+
+ if (s1->ss_narcs != s2->ss_narcs || s1->ss_finish != s2->ss_finish)
+ return 0;
+ for (i = 0; i < s1->ss_narcs; i++) {
+ if (s1->ss_arc[i].sa_arrow != s2->ss_arc[i].sa_arrow ||
+ s1->ss_arc[i].sa_label != s2->ss_arc[i].sa_label)
+ return 0;
+ }
+ return 1;
}
static void
renamestates(int xx_nstates, ss_state *xx_state, int from, int to)
{
- int i, j;
-
- if (Py_DebugFlag)
- printf("Rename state %d to %d.\n", from, to);
- for (i = 0; i < xx_nstates; i++) {
- if (xx_state[i].ss_deleted)
- continue;
- for (j = 0; j < xx_state[i].ss_narcs; j++) {
- if (xx_state[i].ss_arc[j].sa_arrow == from)
- xx_state[i].ss_arc[j].sa_arrow = to;
- }
- }
+ int i, j;
+
+ if (Py_DebugFlag)
+ printf("Rename state %d to %d.\n", from, to);
+ for (i = 0; i < xx_nstates; i++) {
+ if (xx_state[i].ss_deleted)
+ continue;
+ for (j = 0; j < xx_state[i].ss_narcs; j++) {
+ if (xx_state[i].ss_arc[j].sa_arrow == from)
+ xx_state[i].ss_arc[j].sa_arrow = to;
+ }
+ }
}
static void
simplify(int xx_nstates, ss_state *xx_state)
{
- int changes;
- int i, j;
-
- do {
- changes = 0;
- for (i = 1; i < xx_nstates; i++) {
- if (xx_state[i].ss_deleted)
- continue;
- for (j = 0; j < i; j++) {
- if (xx_state[j].ss_deleted)
- continue;
- if (samestate(&xx_state[i], &xx_state[j])) {
- xx_state[i].ss_deleted++;
- renamestates(xx_nstates, xx_state,
- i, j);
- changes++;
- break;
- }
- }
- }
- } while (changes);
+ int changes;
+ int i, j;
+
+ do {
+ changes = 0;
+ for (i = 1; i < xx_nstates; i++) {
+ if (xx_state[i].ss_deleted)
+ continue;
+ for (j = 0; j < i; j++) {
+ if (xx_state[j].ss_deleted)
+ continue;
+ if (samestate(&xx_state[i], &xx_state[j])) {
+ xx_state[i].ss_deleted++;
+ renamestates(xx_nstates, xx_state,
+ i, j);
+ changes++;
+ break;
+ }
+ }
+ }
+ } while (changes);
}
@@ -598,32 +598,32 @@ simplify(int xx_nstates, ss_state *xx_state)
static void
convert(dfa *d, int xx_nstates, ss_state *xx_state)
{
- int i, j;
- ss_state *yy;
- ss_arc *zz;
-
- for (i = 0; i < xx_nstates; i++) {
- yy = &xx_state[i];
- if (yy->ss_deleted)
- continue;
- yy->ss_rename = addstate(d);
- }
-
- for (i = 0; i < xx_nstates; i++) {
- yy = &xx_state[i];
- if (yy->ss_deleted)
- continue;
- for (j = 0; j < yy->ss_narcs; j++) {
- zz = &yy->ss_arc[j];
- addarc(d, yy->ss_rename,
- xx_state[zz->sa_arrow].ss_rename,
- zz->sa_label);
- }
- if (yy->ss_finish)
- addarc(d, yy->ss_rename, yy->ss_rename, 0);
- }
-
- d->d_initial = 0;
+ int i, j;
+ ss_state *yy;
+ ss_arc *zz;
+
+ for (i = 0; i < xx_nstates; i++) {
+ yy = &xx_state[i];
+ if (yy->ss_deleted)
+ continue;
+ yy->ss_rename = addstate(d);
+ }
+
+ for (i = 0; i < xx_nstates; i++) {
+ yy = &xx_state[i];
+ if (yy->ss_deleted)
+ continue;
+ for (j = 0; j < yy->ss_narcs; j++) {
+ zz = &yy->ss_arc[j];
+ addarc(d, yy->ss_rename,
+ xx_state[zz->sa_arrow].ss_rename,
+ zz->sa_label);
+ }
+ if (yy->ss_finish)
+ addarc(d, yy->ss_rename, yy->ss_rename, 0);
+ }
+
+ d->d_initial = 0;
}
@@ -632,43 +632,43 @@ convert(dfa *d, int xx_nstates, ss_state *xx_state)
static grammar *
maketables(nfagrammar *gr)
{
- int i;
- nfa *nf;
- dfa *d;
- grammar *g;
-
- if (gr->gr_nnfas == 0)
- return NULL;
- g = newgrammar(gr->gr_nfa[0]->nf_type);
- /* XXX first rule must be start rule */
- g->g_ll = gr->gr_ll;
-
- for (i = 0; i < gr->gr_nnfas; i++) {
- nf = gr->gr_nfa[i];
- if (Py_DebugFlag) {
- printf("Dump of NFA for '%s' ...\n", nf->nf_name);
- dumpnfa(&gr->gr_ll, nf);
- printf("Making DFA for '%s' ...\n", nf->nf_name);
- }
- d = adddfa(g, nf->nf_type, nf->nf_name);
- makedfa(gr, gr->gr_nfa[i], d);
- }
-
- return g;
+ int i;
+ nfa *nf;
+ dfa *d;
+ grammar *g;
+
+ if (gr->gr_nnfas == 0)
+ return NULL;
+ g = newgrammar(gr->gr_nfa[0]->nf_type);
+ /* XXX first rule must be start rule */
+ g->g_ll = gr->gr_ll;
+
+ for (i = 0; i < gr->gr_nnfas; i++) {
+ nf = gr->gr_nfa[i];
+ if (Py_DebugFlag) {
+ printf("Dump of NFA for '%s' ...\n", nf->nf_name);
+ dumpnfa(&gr->gr_ll, nf);
+ printf("Making DFA for '%s' ...\n", nf->nf_name);
+ }
+ d = adddfa(g, nf->nf_type, nf->nf_name);
+ makedfa(gr, gr->gr_nfa[i], d);
+ }
+
+ return g;
}
grammar *
pgen(node *n)
{
- nfagrammar *gr;
- grammar *g;
-
- gr = metacompile(n);
- g = maketables(gr);
- translatelabels(g);
- addfirstsets(g);
- PyObject_FREE(gr);
- return g;
+ nfagrammar *gr;
+ grammar *g;
+
+ gr = metacompile(n);
+ g = maketables(gr);
+ translatelabels(g);
+ addfirstsets(g);
+ PyObject_FREE(gr);
+ return g;
}
grammar *
@@ -702,7 +702,7 @@ Reference
---------
[Aho&Ullman 77]
- Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977
- (first edition)
+ Aho&Ullman, Principles of Compiler Design, Addison-Wesley 1977
+ (first edition)
*/
diff --git a/Parser/pgenmain.c b/Parser/pgenmain.c
index fc27a2c..88fa7f1 100644
--- a/Parser/pgenmain.c
+++ b/Parser/pgenmain.c
@@ -30,104 +30,104 @@ grammar *getgrammar(char *filename);
void
Py_Exit(int sts)
{
- exit(sts);
+ exit(sts);
}
int
main(int argc, char **argv)
{
- grammar *g;
- FILE *fp;
- char *filename, *graminit_h, *graminit_c;
-
- if (argc != 4) {
- fprintf(stderr,
- "usage: %s grammar graminit.h graminit.c\n", argv[0]);
- Py_Exit(2);
- }
- filename = argv[1];
- graminit_h = argv[2];
- graminit_c = argv[3];
- g = getgrammar(filename);
- fp = fopen(graminit_c, "w");
- if (fp == NULL) {
- perror(graminit_c);
- Py_Exit(1);
- }
- if (Py_DebugFlag)
- printf("Writing %s ...\n", graminit_c);
- printgrammar(g, fp);
- fclose(fp);
- fp = fopen(graminit_h, "w");
- if (fp == NULL) {
- perror(graminit_h);
- Py_Exit(1);
- }
- if (Py_DebugFlag)
- printf("Writing %s ...\n", graminit_h);
- printnonterminals(g, fp);
- fclose(fp);
- Py_Exit(0);
- return 0; /* Make gcc -Wall happy */
+ grammar *g;
+ FILE *fp;
+ char *filename, *graminit_h, *graminit_c;
+
+ if (argc != 4) {
+ fprintf(stderr,
+ "usage: %s grammar graminit.h graminit.c\n", argv[0]);
+ Py_Exit(2);
+ }
+ filename = argv[1];
+ graminit_h = argv[2];
+ graminit_c = argv[3];
+ g = getgrammar(filename);
+ fp = fopen(graminit_c, "w");
+ if (fp == NULL) {
+ perror(graminit_c);
+ Py_Exit(1);
+ }
+ if (Py_DebugFlag)
+ printf("Writing %s ...\n", graminit_c);
+ printgrammar(g, fp);
+ fclose(fp);
+ fp = fopen(graminit_h, "w");
+ if (fp == NULL) {
+ perror(graminit_h);
+ Py_Exit(1);
+ }
+ if (Py_DebugFlag)
+ printf("Writing %s ...\n", graminit_h);
+ printnonterminals(g, fp);
+ fclose(fp);
+ Py_Exit(0);
+ return 0; /* Make gcc -Wall happy */
}
grammar *
getgrammar(char *filename)
{
- FILE *fp;
- node *n;
- grammar *g0, *g;
- perrdetail err;
-
- fp = fopen(filename, "r");
- if (fp == NULL) {
- perror(filename);
- Py_Exit(1);
- }
- g0 = meta_grammar();
- n = PyParser_ParseFile(fp, filename, g0, g0->g_start,
- (char *)NULL, (char *)NULL, &err);
- fclose(fp);
- if (n == NULL) {
- fprintf(stderr, "Parsing error %d, line %d.\n",
- err.error, err.lineno);
- if (err.text != NULL) {
- size_t i;
- fprintf(stderr, "%s", err.text);
- i = strlen(err.text);
- if (i == 0 || err.text[i-1] != '\n')
- fprintf(stderr, "\n");
- for (i = 0; i < err.offset; i++) {
- if (err.text[i] == '\t')
- putc('\t', stderr);
- else
- putc(' ', stderr);
- }
- fprintf(stderr, "^\n");
- PyObject_FREE(err.text);
- }
- Py_Exit(1);
- }
- g = pgen(n);
- if (g == NULL) {
- printf("Bad grammar.\n");
- Py_Exit(1);
- }
- return g;
+ FILE *fp;
+ node *n;
+ grammar *g0, *g;
+ perrdetail err;
+
+ fp = fopen(filename, "r");
+ if (fp == NULL) {
+ perror(filename);
+ Py_Exit(1);
+ }
+ g0 = meta_grammar();
+ n = PyParser_ParseFile(fp, filename, g0, g0->g_start,
+ (char *)NULL, (char *)NULL, &err);
+ fclose(fp);
+ if (n == NULL) {
+ fprintf(stderr, "Parsing error %d, line %d.\n",
+ err.error, err.lineno);
+ if (err.text != NULL) {
+ size_t i;
+ fprintf(stderr, "%s", err.text);
+ i = strlen(err.text);
+ if (i == 0 || err.text[i-1] != '\n')
+ fprintf(stderr, "\n");
+ for (i = 0; i < err.offset; i++) {
+ if (err.text[i] == '\t')
+ putc('\t', stderr);
+ else
+ putc(' ', stderr);
+ }
+ fprintf(stderr, "^\n");
+ PyObject_FREE(err.text);
+ }
+ Py_Exit(1);
+ }
+ g = pgen(n);
+ if (g == NULL) {
+ printf("Bad grammar.\n");
+ Py_Exit(1);
+ }
+ return g;
}
/* Can't happen in pgen */
PyObject*
PyErr_Occurred()
{
- return 0;
+ return 0;
}
void
Py_FatalError(const char *msg)
{
- fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg);
- Py_Exit(1);
+ fprintf(stderr, "pgen: FATAL ERROR: %s\n", msg);
+ Py_Exit(1);
}
/* No-nonsense my_readline() for tokenizer.c */
@@ -135,28 +135,28 @@ Py_FatalError(const char *msg)
char *
PyOS_Readline(FILE *sys_stdin, FILE *sys_stdout, char *prompt)
{
- size_t n = 1000;
- char *p = (char *)PyMem_MALLOC(n);
- char *q;
- if (p == NULL)
- return NULL;
- fprintf(stderr, "%s", prompt);
- q = fgets(p, n, sys_stdin);
- if (q == NULL) {
- *p = '\0';
- return p;
- }
- n = strlen(p);
- if (n > 0 && p[n-1] != '\n')
- p[n-1] = '\n';
- return (char *)PyMem_REALLOC(p, n+1);
+ size_t n = 1000;
+ char *p = (char *)PyMem_MALLOC(n);
+ char *q;
+ if (p == NULL)
+ return NULL;
+ fprintf(stderr, "%s", prompt);
+ q = fgets(p, n, sys_stdin);
+ if (q == NULL) {
+ *p = '\0';
+ return p;
+ }
+ n = strlen(p);
+ if (n > 0 && p[n-1] != '\n')
+ p[n-1] = '\n';
+ return (char *)PyMem_REALLOC(p, n+1);
}
/* No-nonsense fgets */
char *
Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
{
- return fgets(buf, n, stream);
+ return fgets(buf, n, stream);
}
@@ -165,9 +165,9 @@ Py_UniversalNewlineFgets(char *buf, int n, FILE *stream, PyObject *fobj)
void
PySys_WriteStderr(const char *format, ...)
{
- va_list va;
+ va_list va;
- va_start(va, format);
- vfprintf(stderr, format, va);
- va_end(va);
+ va_start(va, format);
+ vfprintf(stderr, format, va);
+ va_end(va);
}
diff --git a/Parser/printgrammar.c b/Parser/printgrammar.c
index ae180e1..3b54a05 100644
--- a/Parser/printgrammar.c
+++ b/Parser/printgrammar.c
@@ -13,105 +13,105 @@ static void printlabels(grammar *, FILE *);
void
printgrammar(grammar *g, FILE *fp)
{
- fprintf(fp, "/* Generated by Parser/pgen */\n\n");
- fprintf(fp, "#include \"pgenheaders.h\"\n");
- fprintf(fp, "#include \"grammar.h\"\n");
- fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n");
- printdfas(g, fp);
- printlabels(g, fp);
- fprintf(fp, "grammar _PyParser_Grammar = {\n");
- fprintf(fp, "\t%d,\n", g->g_ndfas);
- fprintf(fp, "\tdfas,\n");
- fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels);
- fprintf(fp, "\t%d\n", g->g_start);
- fprintf(fp, "};\n");
+ fprintf(fp, "/* Generated by Parser/pgen */\n\n");
+ fprintf(fp, "#include \"pgenheaders.h\"\n");
+ fprintf(fp, "#include \"grammar.h\"\n");
+ fprintf(fp, "PyAPI_DATA(grammar) _PyParser_Grammar;\n");
+ printdfas(g, fp);
+ printlabels(g, fp);
+ fprintf(fp, "grammar _PyParser_Grammar = {\n");
+ fprintf(fp, "\t%d,\n", g->g_ndfas);
+ fprintf(fp, "\tdfas,\n");
+ fprintf(fp, "\t{%d, labels},\n", g->g_ll.ll_nlabels);
+ fprintf(fp, "\t%d\n", g->g_start);
+ fprintf(fp, "};\n");
}
void
printnonterminals(grammar *g, FILE *fp)
{
- dfa *d;
- int i;
-
- fprintf(fp, "/* Generated by Parser/pgen */\n\n");
-
- d = g->g_dfa;
- for (i = g->g_ndfas; --i >= 0; d++)
- fprintf(fp, "#define %s %d\n", d->d_name, d->d_type);
+ dfa *d;
+ int i;
+
+ fprintf(fp, "/* Generated by Parser/pgen */\n\n");
+
+ d = g->g_dfa;
+ for (i = g->g_ndfas; --i >= 0; d++)
+ fprintf(fp, "#define %s %d\n", d->d_name, d->d_type);
}
static void
printarcs(int i, dfa *d, FILE *fp)
{
- arc *a;
- state *s;
- int j, k;
-
- s = d->d_state;
- for (j = 0; j < d->d_nstates; j++, s++) {
- fprintf(fp, "static arc arcs_%d_%d[%d] = {\n",
- i, j, s->s_narcs);
- a = s->s_arc;
- for (k = 0; k < s->s_narcs; k++, a++)
- fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow);
- fprintf(fp, "};\n");
- }
+ arc *a;
+ state *s;
+ int j, k;
+
+ s = d->d_state;
+ for (j = 0; j < d->d_nstates; j++, s++) {
+ fprintf(fp, "static arc arcs_%d_%d[%d] = {\n",
+ i, j, s->s_narcs);
+ a = s->s_arc;
+ for (k = 0; k < s->s_narcs; k++, a++)
+ fprintf(fp, "\t{%d, %d},\n", a->a_lbl, a->a_arrow);
+ fprintf(fp, "};\n");
+ }
}
static void
printstates(grammar *g, FILE *fp)
{
- state *s;
- dfa *d;
- int i, j;
-
- d = g->g_dfa;
- for (i = 0; i < g->g_ndfas; i++, d++) {
- printarcs(i, d, fp);
- fprintf(fp, "static state states_%d[%d] = {\n",
- i, d->d_nstates);
- s = d->d_state;
- for (j = 0; j < d->d_nstates; j++, s++)
- fprintf(fp, "\t{%d, arcs_%d_%d},\n",
- s->s_narcs, i, j);
- fprintf(fp, "};\n");
- }
+ state *s;
+ dfa *d;
+ int i, j;
+
+ d = g->g_dfa;
+ for (i = 0; i < g->g_ndfas; i++, d++) {
+ printarcs(i, d, fp);
+ fprintf(fp, "static state states_%d[%d] = {\n",
+ i, d->d_nstates);
+ s = d->d_state;
+ for (j = 0; j < d->d_nstates; j++, s++)
+ fprintf(fp, "\t{%d, arcs_%d_%d},\n",
+ s->s_narcs, i, j);
+ fprintf(fp, "};\n");
+ }
}
static void
printdfas(grammar *g, FILE *fp)
{
- dfa *d;
- int i, j;
-
- printstates(g, fp);
- fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas);
- d = g->g_dfa;
- for (i = 0; i < g->g_ndfas; i++, d++) {
- fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n",
- d->d_type, d->d_name, d->d_initial, d->d_nstates, i);
- fprintf(fp, "\t \"");
- for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++)
- fprintf(fp, "\\%03o", d->d_first[j] & 0xff);
- fprintf(fp, "\"},\n");
- }
- fprintf(fp, "};\n");
+ dfa *d;
+ int i, j;
+
+ printstates(g, fp);
+ fprintf(fp, "static dfa dfas[%d] = {\n", g->g_ndfas);
+ d = g->g_dfa;
+ for (i = 0; i < g->g_ndfas; i++, d++) {
+ fprintf(fp, "\t{%d, \"%s\", %d, %d, states_%d,\n",
+ d->d_type, d->d_name, d->d_initial, d->d_nstates, i);
+ fprintf(fp, "\t \"");
+ for (j = 0; j < NBYTES(g->g_ll.ll_nlabels); j++)
+ fprintf(fp, "\\%03o", d->d_first[j] & 0xff);
+ fprintf(fp, "\"},\n");
+ }
+ fprintf(fp, "};\n");
}
static void
printlabels(grammar *g, FILE *fp)
{
- label *l;
- int i;
-
- fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels);
- l = g->g_ll.ll_label;
- for (i = g->g_ll.ll_nlabels; --i >= 0; l++) {
- if (l->lb_str == NULL)
- fprintf(fp, "\t{%d, 0},\n", l->lb_type);
- else
- fprintf(fp, "\t{%d, \"%s\"},\n",
- l->lb_type, l->lb_str);
- }
- fprintf(fp, "};\n");
+ label *l;
+ int i;
+
+ fprintf(fp, "static label labels[%d] = {\n", g->g_ll.ll_nlabels);
+ l = g->g_ll.ll_label;
+ for (i = g->g_ll.ll_nlabels; --i >= 0; l++) {
+ if (l->lb_str == NULL)
+ fprintf(fp, "\t{%d, 0},\n", l->lb_type);
+ else
+ fprintf(fp, "\t{%d, \"%s\"},\n",
+ l->lb_type, l->lb_str);
+ }
+ fprintf(fp, "};\n");
}
diff --git a/Parser/tokenizer.c b/Parser/tokenizer.c
index 495182f..a647d9c 100644
--- a/Parser/tokenizer.c
+++ b/Parser/tokenizer.c
@@ -35,61 +35,61 @@ static void tok_backup(struct tok_state *tok, int c);
/* Token names */
char *_PyParser_TokenNames[] = {
- "ENDMARKER",
- "NAME",
- "NUMBER",
- "STRING",
- "NEWLINE",
- "INDENT",
- "DEDENT",
- "LPAR",
- "RPAR",
- "LSQB",
- "RSQB",
- "COLON",
- "COMMA",
- "SEMI",
- "PLUS",
- "MINUS",
- "STAR",
- "SLASH",
- "VBAR",
- "AMPER",
- "LESS",
- "GREATER",
- "EQUAL",
- "DOT",
- "PERCENT",
- "BACKQUOTE",
- "LBRACE",
- "RBRACE",
- "EQEQUAL",
- "NOTEQUAL",
- "LESSEQUAL",
- "GREATEREQUAL",
- "TILDE",
- "CIRCUMFLEX",
- "LEFTSHIFT",
- "RIGHTSHIFT",
- "DOUBLESTAR",
- "PLUSEQUAL",
- "MINEQUAL",
- "STAREQUAL",
- "SLASHEQUAL",
- "PERCENTEQUAL",
- "AMPEREQUAL",
- "VBAREQUAL",
- "CIRCUMFLEXEQUAL",
- "LEFTSHIFTEQUAL",
- "RIGHTSHIFTEQUAL",
- "DOUBLESTAREQUAL",
- "DOUBLESLASH",
- "DOUBLESLASHEQUAL",
- "AT",
- /* This table must match the #defines in token.h! */
- "OP",
- "<ERRORTOKEN>",
- "<N_TOKENS>"
+ "ENDMARKER",
+ "NAME",
+ "NUMBER",
+ "STRING",
+ "NEWLINE",
+ "INDENT",
+ "DEDENT",
+ "LPAR",
+ "RPAR",
+ "LSQB",
+ "RSQB",
+ "COLON",
+ "COMMA",
+ "SEMI",
+ "PLUS",
+ "MINUS",
+ "STAR",
+ "SLASH",
+ "VBAR",
+ "AMPER",
+ "LESS",
+ "GREATER",
+ "EQUAL",
+ "DOT",
+ "PERCENT",
+ "BACKQUOTE",
+ "LBRACE",
+ "RBRACE",
+ "EQEQUAL",
+ "NOTEQUAL",
+ "LESSEQUAL",
+ "GREATEREQUAL",
+ "TILDE",
+ "CIRCUMFLEX",
+ "LEFTSHIFT",
+ "RIGHTSHIFT",
+ "DOUBLESTAR",
+ "PLUSEQUAL",
+ "MINEQUAL",
+ "STAREQUAL",
+ "SLASHEQUAL",
+ "PERCENTEQUAL",
+ "AMPEREQUAL",
+ "VBAREQUAL",
+ "CIRCUMFLEXEQUAL",
+ "LEFTSHIFTEQUAL",
+ "RIGHTSHIFTEQUAL",
+ "DOUBLESTAREQUAL",
+ "DOUBLESLASH",
+ "DOUBLESLASHEQUAL",
+ "AT",
+ /* This table must match the #defines in token.h! */
+ "OP",
+ "<ERRORTOKEN>",
+ "<N_TOKENS>"
};
/* Create and initialize a new tok_state structure */
@@ -97,48 +97,48 @@ char *_PyParser_TokenNames[] = {
static struct tok_state *
tok_new(void)
{
- struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(
- sizeof(struct tok_state));
- if (tok == NULL)
- return NULL;
- tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;
- tok->done = E_OK;
- tok->fp = NULL;
- tok->input = NULL;
- tok->tabsize = TABSIZE;
- tok->indent = 0;
- tok->indstack[0] = 0;
- tok->atbol = 1;
- tok->pendin = 0;
- tok->prompt = tok->nextprompt = NULL;
- tok->lineno = 0;
- tok->level = 0;
- tok->filename = NULL;
- tok->altwarning = 0;
- tok->alterror = 0;
- tok->alttabsize = 1;
- tok->altindstack[0] = 0;
- tok->decoding_state = 0;
- tok->decoding_erred = 0;
- tok->read_coding_spec = 0;
- tok->encoding = NULL;
- tok->cont_line = 0;
+ struct tok_state *tok = (struct tok_state *)PyMem_MALLOC(
+ sizeof(struct tok_state));
+ if (tok == NULL)
+ return NULL;
+ tok->buf = tok->cur = tok->end = tok->inp = tok->start = NULL;
+ tok->done = E_OK;
+ tok->fp = NULL;
+ tok->input = NULL;
+ tok->tabsize = TABSIZE;
+ tok->indent = 0;
+ tok->indstack[0] = 0;
+ tok->atbol = 1;
+ tok->pendin = 0;
+ tok->prompt = tok->nextprompt = NULL;
+ tok->lineno = 0;
+ tok->level = 0;
+ tok->filename = NULL;
+ tok->altwarning = 0;
+ tok->alterror = 0;
+ tok->alttabsize = 1;
+ tok->altindstack[0] = 0;
+ tok->decoding_state = 0;
+ tok->decoding_erred = 0;
+ tok->read_coding_spec = 0;
+ tok->encoding = NULL;
+ tok->cont_line = 0;
#ifndef PGEN
- tok->decoding_readline = NULL;
- tok->decoding_buffer = NULL;
+ tok->decoding_readline = NULL;
+ tok->decoding_buffer = NULL;
#endif
- return tok;
+ return tok;
}
static char *
new_string(const char *s, Py_ssize_t len)
{
- char* result = (char *)PyMem_MALLOC(len + 1);
- if (result != NULL) {
- memcpy(result, s, len);
- result[len] = '\0';
- }
- return result;
+ char* result = (char *)PyMem_MALLOC(len + 1);
+ if (result != NULL) {
+ memcpy(result, s, len);
+ result[len] = '\0';
+ }
+ return result;
}
#ifdef PGEN
@@ -146,19 +146,19 @@ new_string(const char *s, Py_ssize_t len)
static char *
decoding_fgets(char *s, int size, struct tok_state *tok)
{
- return fgets(s, size, tok->fp);
+ return fgets(s, size, tok->fp);
}
static int
decoding_feof(struct tok_state *tok)
{
- return feof(tok->fp);
+ return feof(tok->fp);
}
static char *
decode_str(const char *str, int exec_input, struct tok_state *tok)
{
- return new_string(str, strlen(str));
+ return new_string(str, strlen(str));
}
#else /* PGEN */
@@ -166,41 +166,41 @@ decode_str(const char *str, int exec_input, struct tok_state *tok)
static char *
error_ret(struct tok_state *tok) /* XXX */
{
- tok->decoding_erred = 1;
- if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */
- PyMem_FREE(tok->buf);
- tok->buf = NULL;
- return NULL; /* as if it were EOF */
+ tok->decoding_erred = 1;
+ if (tok->fp != NULL && tok->buf != NULL) /* see PyTokenizer_Free */
+ PyMem_FREE(tok->buf);
+ tok->buf = NULL;
+ return NULL; /* as if it were EOF */
}
static char *
-get_normal_name(char *s) /* for utf-8 and latin-1 */
+get_normal_name(char *s) /* for utf-8 and latin-1 */
{
- char buf[13];
- int i;
- for (i = 0; i < 12; i++) {
- int c = s[i];
- if (c == '\0')
- break;
- else if (c == '_')
- buf[i] = '-';
- else
- buf[i] = tolower(c);
- }
- buf[i] = '\0';
- if (strcmp(buf, "utf-8") == 0 ||
- strncmp(buf, "utf-8-", 6) == 0)
- return "utf-8";
- else if (strcmp(buf, "latin-1") == 0 ||
- strcmp(buf, "iso-8859-1") == 0 ||
- strcmp(buf, "iso-latin-1") == 0 ||
- strncmp(buf, "latin-1-", 8) == 0 ||
- strncmp(buf, "iso-8859-1-", 11) == 0 ||
- strncmp(buf, "iso-latin-1-", 12) == 0)
- return "iso-8859-1";
- else
- return s;
+ char buf[13];
+ int i;
+ for (i = 0; i < 12; i++) {
+ int c = s[i];
+ if (c == '\0')
+ break;
+ else if (c == '_')
+ buf[i] = '-';
+ else
+ buf[i] = tolower(c);
+ }
+ buf[i] = '\0';
+ if (strcmp(buf, "utf-8") == 0 ||
+ strncmp(buf, "utf-8-", 6) == 0)
+ return "utf-8";
+ else if (strcmp(buf, "latin-1") == 0 ||
+ strcmp(buf, "iso-8859-1") == 0 ||
+ strcmp(buf, "iso-latin-1") == 0 ||
+ strncmp(buf, "latin-1-", 8) == 0 ||
+ strncmp(buf, "iso-8859-1-", 11) == 0 ||
+ strncmp(buf, "iso-latin-1-", 12) == 0)
+ return "iso-8859-1";
+ else
+ return s;
}
/* Return the coding spec in S, or NULL if none is found. */
@@ -208,43 +208,43 @@ get_normal_name(char *s) /* for utf-8 and latin-1 */
static char *
get_coding_spec(const char *s, Py_ssize_t size)
{
- Py_ssize_t i;
- /* Coding spec must be in a comment, and that comment must be
- * the only statement on the source code line. */
- for (i = 0; i < size - 6; i++) {
- if (s[i] == '#')
- break;
- if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014')
- return NULL;
- }
- for (; i < size - 6; i++) { /* XXX inefficient search */
- const char* t = s + i;
- if (strncmp(t, "coding", 6) == 0) {
- const char* begin = NULL;
- t += 6;
- if (t[0] != ':' && t[0] != '=')
- continue;
- do {
- t++;
- } while (t[0] == '\x20' || t[0] == '\t');
-
- begin = t;
- while (Py_ISALNUM(t[0]) ||
- t[0] == '-' || t[0] == '_' || t[0] == '.')
- t++;
-
- if (begin < t) {
- char* r = new_string(begin, t - begin);
- char* q = get_normal_name(r);
- if (r != q) {
- PyMem_FREE(r);
- r = new_string(q, strlen(q));
- }
- return r;
- }
- }
- }
- return NULL;
+ Py_ssize_t i;
+ /* Coding spec must be in a comment, and that comment must be
+ * the only statement on the source code line. */
+ for (i = 0; i < size - 6; i++) {
+ if (s[i] == '#')
+ break;
+ if (s[i] != ' ' && s[i] != '\t' && s[i] != '\014')
+ return NULL;
+ }
+ for (; i < size - 6; i++) { /* XXX inefficient search */
+ const char* t = s + i;
+ if (strncmp(t, "coding", 6) == 0) {
+ const char* begin = NULL;
+ t += 6;
+ if (t[0] != ':' && t[0] != '=')
+ continue;
+ do {
+ t++;
+ } while (t[0] == '\x20' || t[0] == '\t');
+
+ begin = t;
+ while (Py_ISALNUM(t[0]) ||
+ t[0] == '-' || t[0] == '_' || t[0] == '.')
+ t++;
+
+ if (begin < t) {
+ char* r = new_string(begin, t - begin);
+ char* q = get_normal_name(r);
+ if (r != q) {
+ PyMem_FREE(r);
+ r = new_string(q, strlen(q));
+ }
+ return r;
+ }
+ }
+ }
+ return NULL;
}
/* Check whether the line contains a coding spec. If it does,
@@ -254,51 +254,51 @@ get_coding_spec(const char *s, Py_ssize_t size)
static int
check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok,
- int set_readline(struct tok_state *, const char *))
+ int set_readline(struct tok_state *, const char *))
{
- char * cs;
- int r = 1;
-
- if (tok->cont_line)
- /* It's a continuation line, so it can't be a coding spec. */
- return 1;
- cs = get_coding_spec(line, size);
- if (cs != NULL) {
- tok->read_coding_spec = 1;
- if (tok->encoding == NULL) {
- assert(tok->decoding_state == 1); /* raw */
- if (strcmp(cs, "utf-8") == 0 ||
- strcmp(cs, "iso-8859-1") == 0) {
- tok->encoding = cs;
- } else {
+ char * cs;
+ int r = 1;
+
+ if (tok->cont_line)
+ /* It's a continuation line, so it can't be a coding spec. */
+ return 1;
+ cs = get_coding_spec(line, size);
+ if (cs != NULL) {
+ tok->read_coding_spec = 1;
+ if (tok->encoding == NULL) {
+ assert(tok->decoding_state == 1); /* raw */
+ if (strcmp(cs, "utf-8") == 0 ||
+ strcmp(cs, "iso-8859-1") == 0) {
+ tok->encoding = cs;
+ } else {
#ifdef Py_USING_UNICODE
- r = set_readline(tok, cs);
- if (r) {
- tok->encoding = cs;
- tok->decoding_state = -1;
- }
- else
- PyMem_FREE(cs);
+ r = set_readline(tok, cs);
+ if (r) {
+ tok->encoding = cs;
+ tok->decoding_state = -1;
+ }
+ else
+ PyMem_FREE(cs);
#else
- /* Without Unicode support, we cannot
- process the coding spec. Since there
- won't be any Unicode literals, that
- won't matter. */
- PyMem_FREE(cs);
+ /* Without Unicode support, we cannot
+ process the coding spec. Since there
+ won't be any Unicode literals, that
+ won't matter. */
+ PyMem_FREE(cs);
#endif
- }
- } else { /* then, compare cs with BOM */
- r = (strcmp(tok->encoding, cs) == 0);
- PyMem_FREE(cs);
- }
- }
- if (!r) {
- cs = tok->encoding;
- if (!cs)
- cs = "with BOM";
- PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs);
- }
- return r;
+ }
+ } else { /* then, compare cs with BOM */
+ r = (strcmp(tok->encoding, cs) == 0);
+ PyMem_FREE(cs);
+ }
+ }
+ if (!r) {
+ cs = tok->encoding;
+ if (!cs)
+ cs = "with BOM";
+ PyErr_Format(PyExc_SyntaxError, "encoding problem: %s", cs);
+ }
+ return r;
}
/* See whether the file starts with a BOM. If it does,
@@ -307,61 +307,61 @@ check_coding_spec(const char* line, Py_ssize_t size, struct tok_state *tok,
static int
check_bom(int get_char(struct tok_state *),
- void unget_char(int, struct tok_state *),
- int set_readline(struct tok_state *, const char *),
- struct tok_state *tok)
+ void unget_char(int, struct tok_state *),
+ int set_readline(struct tok_state *, const char *),
+ struct tok_state *tok)
{
- int ch1, ch2, ch3;
- ch1 = get_char(tok);
- tok->decoding_state = 1;
- if (ch1 == EOF) {
- return 1;
- } else if (ch1 == 0xEF) {
- ch2 = get_char(tok);
- if (ch2 != 0xBB) {
- unget_char(ch2, tok);
- unget_char(ch1, tok);
- return 1;
- }
- ch3 = get_char(tok);
- if (ch3 != 0xBF) {
- unget_char(ch3, tok);
- unget_char(ch2, tok);
- unget_char(ch1, tok);
- return 1;
- }
+ int ch1, ch2, ch3;
+ ch1 = get_char(tok);
+ tok->decoding_state = 1;
+ if (ch1 == EOF) {
+ return 1;
+ } else if (ch1 == 0xEF) {
+ ch2 = get_char(tok);
+ if (ch2 != 0xBB) {
+ unget_char(ch2, tok);
+ unget_char(ch1, tok);
+ return 1;
+ }
+ ch3 = get_char(tok);
+ if (ch3 != 0xBF) {
+ unget_char(ch3, tok);
+ unget_char(ch2, tok);
+ unget_char(ch1, tok);
+ return 1;
+ }
#if 0
- /* Disable support for UTF-16 BOMs until a decision
- is made whether this needs to be supported. */
- } else if (ch1 == 0xFE) {
- ch2 = get_char(tok);
- if (ch2 != 0xFF) {
- unget_char(ch2, tok);
- unget_char(ch1, tok);
- return 1;
- }
- if (!set_readline(tok, "utf-16-be"))
- return 0;
- tok->decoding_state = -1;
- } else if (ch1 == 0xFF) {
- ch2 = get_char(tok);
- if (ch2 != 0xFE) {
- unget_char(ch2, tok);
- unget_char(ch1, tok);
- return 1;
- }
- if (!set_readline(tok, "utf-16-le"))
- return 0;
- tok->decoding_state = -1;
+ /* Disable support for UTF-16 BOMs until a decision
+ is made whether this needs to be supported. */
+ } else if (ch1 == 0xFE) {
+ ch2 = get_char(tok);
+ if (ch2 != 0xFF) {
+ unget_char(ch2, tok);
+ unget_char(ch1, tok);
+ return 1;
+ }
+ if (!set_readline(tok, "utf-16-be"))
+ return 0;
+ tok->decoding_state = -1;
+ } else if (ch1 == 0xFF) {
+ ch2 = get_char(tok);
+ if (ch2 != 0xFE) {
+ unget_char(ch2, tok);
+ unget_char(ch1, tok);
+ return 1;
+ }
+ if (!set_readline(tok, "utf-16-le"))
+ return 0;
+ tok->decoding_state = -1;
#endif
- } else {
- unget_char(ch1, tok);
- return 1;
- }
- if (tok->encoding != NULL)
- PyMem_FREE(tok->encoding);
- tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */
- return 1;
+ } else {
+ unget_char(ch1, tok);
+ return 1;
+ }
+ if (tok->encoding != NULL)
+ PyMem_FREE(tok->encoding);
+ tok->encoding = new_string("utf-8", 5); /* resulting is in utf-8 */
+ return 1;
}
/* Read a line of text from TOK into S, using the stream in TOK.
@@ -370,63 +370,63 @@ check_bom(int get_char(struct tok_state *),
On entry, tok->decoding_buffer will be one of:
1) NULL: need to call tok->decoding_readline to get a new line
2) PyUnicodeObject *: decoding_feof has called tok->decoding_readline and
- stored the result in tok->decoding_buffer
+ stored the result in tok->decoding_buffer
3) PyStringObject *: previous call to fp_readl did not have enough room
- (in the s buffer) to copy entire contents of the line read
- by tok->decoding_readline. tok->decoding_buffer has the overflow.
- In this case, fp_readl is called in a loop (with an expanded buffer)
- until the buffer ends with a '\n' (or until the end of the file is
- reached): see tok_nextc and its calls to decoding_fgets.
+ (in the s buffer) to copy entire contents of the line read
+ by tok->decoding_readline. tok->decoding_buffer has the overflow.
+ In this case, fp_readl is called in a loop (with an expanded buffer)
+ until the buffer ends with a '\n' (or until the end of the file is
+ reached): see tok_nextc and its calls to decoding_fgets.
*/
static char *
fp_readl(char *s, int size, struct tok_state *tok)
{
#ifndef Py_USING_UNICODE
- /* In a non-Unicode built, this should never be called. */
- Py_FatalError("fp_readl should not be called in this build.");
- return NULL; /* Keep compiler happy (not reachable) */
+ /* In a non-Unicode built, this should never be called. */
+ Py_FatalError("fp_readl should not be called in this build.");
+ return NULL; /* Keep compiler happy (not reachable) */
#else
- PyObject* utf8 = NULL;
- PyObject* buf = tok->decoding_buffer;
- char *str;
- Py_ssize_t utf8len;
-
- /* Ask for one less byte so we can terminate it */
- assert(size > 0);
- size--;
-
- if (buf == NULL) {
- buf = PyObject_CallObject(tok->decoding_readline, NULL);
- if (buf == NULL)
- return error_ret(tok);
- } else {
- tok->decoding_buffer = NULL;
- if (PyString_CheckExact(buf))
- utf8 = buf;
- }
- if (utf8 == NULL) {
- utf8 = PyUnicode_AsUTF8String(buf);
- Py_DECREF(buf);
- if (utf8 == NULL)
- return error_ret(tok);
- }
- str = PyString_AsString(utf8);
- utf8len = PyString_GET_SIZE(utf8);
- if (utf8len > size) {
- tok->decoding_buffer = PyString_FromStringAndSize(str+size, utf8len-size);
- if (tok->decoding_buffer == NULL) {
- Py_DECREF(utf8);
- return error_ret(tok);
- }
- utf8len = size;
- }
- memcpy(s, str, utf8len);
- s[utf8len] = '\0';
- Py_DECREF(utf8);
- if (utf8len == 0)
- return NULL; /* EOF */
- return s;
+ PyObject* utf8 = NULL;
+ PyObject* buf = tok->decoding_buffer;
+ char *str;
+ Py_ssize_t utf8len;
+
+ /* Ask for one less byte so we can terminate it */
+ assert(size > 0);
+ size--;
+
+ if (buf == NULL) {
+ buf = PyObject_CallObject(tok->decoding_readline, NULL);
+ if (buf == NULL)
+ return error_ret(tok);
+ } else {
+ tok->decoding_buffer = NULL;
+ if (PyString_CheckExact(buf))
+ utf8 = buf;
+ }
+ if (utf8 == NULL) {
+ utf8 = PyUnicode_AsUTF8String(buf);
+ Py_DECREF(buf);
+ if (utf8 == NULL)
+ return error_ret(tok);
+ }
+ str = PyString_AsString(utf8);
+ utf8len = PyString_GET_SIZE(utf8);
+ if (utf8len > size) {
+ tok->decoding_buffer = PyString_FromStringAndSize(str+size, utf8len-size);
+ if (tok->decoding_buffer == NULL) {
+ Py_DECREF(utf8);
+ return error_ret(tok);
+ }
+ utf8len = size;
+ }
+ memcpy(s, str, utf8len);
+ s[utf8len] = '\0';
+ Py_DECREF(utf8);
+ if (utf8len == 0)
+ return NULL; /* EOF */
+ return s;
#endif
}
@@ -443,37 +443,37 @@ fp_readl(char *s, int size, struct tok_state *tok)
static int
fp_setreadl(struct tok_state *tok, const char* enc)
{
- PyObject *reader, *stream, *readline;
+ PyObject *reader, *stream, *readline;
- /* XXX: constify filename argument. */
- stream = PyFile_FromFile(tok->fp, (char*)tok->filename, "rb", NULL);
- if (stream == NULL)
- return 0;
+ /* XXX: constify filename argument. */
+ stream = PyFile_FromFile(tok->fp, (char*)tok->filename, "rb", NULL);
+ if (stream == NULL)
+ return 0;
- reader = PyCodec_StreamReader(enc, stream, NULL);
- Py_DECREF(stream);
- if (reader == NULL)
- return 0;
+ reader = PyCodec_StreamReader(enc, stream, NULL);
+ Py_DECREF(stream);
+ if (reader == NULL)
+ return 0;
- readline = PyObject_GetAttrString(reader, "readline");
- Py_DECREF(reader);
- if (readline == NULL)
- return 0;
+ readline = PyObject_GetAttrString(reader, "readline");
+ Py_DECREF(reader);
+ if (readline == NULL)
+ return 0;
- tok->decoding_readline = readline;
- return 1;
+ tok->decoding_readline = readline;
+ return 1;
}
/* Fetch the next byte from TOK. */
static int fp_getc(struct tok_state *tok) {
- return getc(tok->fp);
+ return getc(tok->fp);
}
/* Unfetch the last byte back into TOK. */
static void fp_ungetc(int c, struct tok_state *tok) {
- ungetc(c, tok->fp);
+ ungetc(c, tok->fp);
}
/* Read a line of input from TOK. Determine encoding
@@ -482,94 +482,94 @@ static void fp_ungetc(int c, struct tok_state *tok) {
static char *
decoding_fgets(char *s, int size, struct tok_state *tok)
{
- char *line = NULL;
- int badchar = 0;
- for (;;) {
- if (tok->decoding_state < 0) {
- /* We already have a codec associated with
- this input. */
- line = fp_readl(s, size, tok);
- break;
- } else if (tok->decoding_state > 0) {
- /* We want a 'raw' read. */
- line = Py_UniversalNewlineFgets(s, size,
- tok->fp, NULL);
- break;
- } else {
- /* We have not yet determined the encoding.
- If an encoding is found, use the file-pointer
- reader functions from now on. */
- if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok))
- return error_ret(tok);
- assert(tok->decoding_state != 0);
- }
- }
- if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) {
- if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) {
- return error_ret(tok);
- }
- }
+ char *line = NULL;
+ int badchar = 0;
+ for (;;) {
+ if (tok->decoding_state < 0) {
+ /* We already have a codec associated with
+ this input. */
+ line = fp_readl(s, size, tok);
+ break;
+ } else if (tok->decoding_state > 0) {
+ /* We want a 'raw' read. */
+ line = Py_UniversalNewlineFgets(s, size,
+ tok->fp, NULL);
+ break;
+ } else {
+ /* We have not yet determined the encoding.
+ If an encoding is found, use the file-pointer
+ reader functions from now on. */
+ if (!check_bom(fp_getc, fp_ungetc, fp_setreadl, tok))
+ return error_ret(tok);
+ assert(tok->decoding_state != 0);
+ }
+ }
+ if (line != NULL && tok->lineno < 2 && !tok->read_coding_spec) {
+ if (!check_coding_spec(line, strlen(line), tok, fp_setreadl)) {
+ return error_ret(tok);
+ }
+ }
#ifndef PGEN
- /* The default encoding is ASCII, so make sure we don't have any
- non-ASCII bytes in it. */
- if (line && !tok->encoding) {
- unsigned char *c;
- for (c = (unsigned char *)line; *c; c++)
- if (*c > 127) {
- badchar = *c;
- break;
- }
- }
- if (badchar) {
- char buf[500];
- /* Need to add 1 to the line number, since this line
- has not been counted, yet. */
- sprintf(buf,
- "Non-ASCII character '\\x%.2x' "
- "in file %.200s on line %i, "
- "but no encoding declared; "
- "see http://www.python.org/peps/pep-0263.html for details",
- badchar, tok->filename, tok->lineno + 1);
- PyErr_SetString(PyExc_SyntaxError, buf);
- return error_ret(tok);
- }
+ /* The default encoding is ASCII, so make sure we don't have any
+ non-ASCII bytes in it. */
+ if (line && !tok->encoding) {
+ unsigned char *c;
+ for (c = (unsigned char *)line; *c; c++)
+ if (*c > 127) {
+ badchar = *c;
+ break;
+ }
+ }
+ if (badchar) {
+ char buf[500];
+ /* Need to add 1 to the line number, since this line
+ has not been counted, yet. */
+ sprintf(buf,
+ "Non-ASCII character '\\x%.2x' "
+ "in file %.200s on line %i, "
+ "but no encoding declared; "
+ "see http://www.python.org/peps/pep-0263.html for details",
+ badchar, tok->filename, tok->lineno + 1);
+ PyErr_SetString(PyExc_SyntaxError, buf);
+ return error_ret(tok);
+ }
#endif
- return line;
+ return line;
}
static int
decoding_feof(struct tok_state *tok)
{
- if (tok->decoding_state >= 0) {
- return feof(tok->fp);
- } else {
- PyObject* buf = tok->decoding_buffer;
- if (buf == NULL) {
- buf = PyObject_CallObject(tok->decoding_readline, NULL);
- if (buf == NULL) {
- error_ret(tok);
- return 1;
- } else {
- tok->decoding_buffer = buf;
- }
- }
- return PyObject_Length(buf) == 0;
- }
+ if (tok->decoding_state >= 0) {
+ return feof(tok->fp);
+ } else {
+ PyObject* buf = tok->decoding_buffer;
+ if (buf == NULL) {
+ buf = PyObject_CallObject(tok->decoding_readline, NULL);
+ if (buf == NULL) {
+ error_ret(tok);
+ return 1;
+ } else {
+ tok->decoding_buffer = buf;
+ }
+ }
+ return PyObject_Length(buf) == 0;
+ }
}
/* Fetch a byte from TOK, using the string buffer. */
static int
buf_getc(struct tok_state *tok) {
- return Py_CHARMASK(*tok->str++);
+ return Py_CHARMASK(*tok->str++);
}
/* Unfetch a byte from TOK, using the string buffer. */
static void
buf_ungetc(int c, struct tok_state *tok) {
- tok->str--;
- assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */
+ tok->str--;
+ assert(Py_CHARMASK(*tok->str) == c); /* tok->cur may point to read-only segment */
}
/* Set the readline function for TOK to ENC. For the string-based
@@ -577,8 +577,8 @@ buf_ungetc(int c, struct tok_state *tok) {
static int
buf_setreadl(struct tok_state *tok, const char* enc) {
- tok->enc = enc;
- return 1;
+ tok->enc = enc;
+ return 1;
}
/* Return a UTF-8 encoding Python string object from the
@@ -587,55 +587,55 @@ buf_setreadl(struct tok_state *tok, const char* enc) {
#ifdef Py_USING_UNICODE
static PyObject *
translate_into_utf8(const char* str, const char* enc) {
- PyObject *utf8;
- PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL);
- if (buf == NULL)
- return NULL;
- utf8 = PyUnicode_AsUTF8String(buf);
- Py_DECREF(buf);
- return utf8;
+ PyObject *utf8;
+ PyObject* buf = PyUnicode_Decode(str, strlen(str), enc, NULL);
+ if (buf == NULL)
+ return NULL;
+ utf8 = PyUnicode_AsUTF8String(buf);
+ Py_DECREF(buf);
+ return utf8;
}
#endif
static char *
translate_newlines(const char *s, int exec_input, struct tok_state *tok) {
- int skip_next_lf = 0, needed_length = strlen(s) + 2, final_length;
- char *buf, *current;
- char c = '\0';
- buf = PyMem_MALLOC(needed_length);
- if (buf == NULL) {
- tok->done = E_NOMEM;
- return NULL;
- }
- for (current = buf; *s; s++, current++) {
- c = *s;
- if (skip_next_lf) {
- skip_next_lf = 0;
- if (c == '\n') {
- c = *++s;
- if (!c)
- break;
- }
- }
- if (c == '\r') {
- skip_next_lf = 1;
- c = '\n';
- }
- *current = c;
- }
- /* If this is exec input, add a newline to the end of the string if
- there isn't one already. */
- if (exec_input && c != '\n') {
- *current = '\n';
- current++;
- }
- *current = '\0';
- final_length = current - buf + 1;
- if (final_length < needed_length && final_length)
- /* should never fail */
- buf = PyMem_REALLOC(buf, final_length);
- return buf;
+ int skip_next_lf = 0, needed_length = strlen(s) + 2, final_length;
+ char *buf, *current;
+ char c = '\0';
+ buf = PyMem_MALLOC(needed_length);
+ if (buf == NULL) {
+ tok->done = E_NOMEM;
+ return NULL;
+ }
+ for (current = buf; *s; s++, current++) {
+ c = *s;
+ if (skip_next_lf) {
+ skip_next_lf = 0;
+ if (c == '\n') {
+ c = *++s;
+ if (!c)
+ break;
+ }
+ }
+ if (c == '\r') {
+ skip_next_lf = 1;
+ c = '\n';
+ }
+ *current = c;
+ }
+ /* If this is exec input, add a newline to the end of the string if
+ there isn't one already. */
+ if (exec_input && c != '\n') {
+ *current = '\n';
+ current++;
+ }
+ *current = '\0';
+ final_length = current - buf + 1;
+ if (final_length < needed_length && final_length)
+ /* should never fail */
+ buf = PyMem_REALLOC(buf, final_length);
+ return buf;
}
/* Decode a byte string STR for use as the buffer of TOK.
@@ -645,61 +645,61 @@ translate_newlines(const char *s, int exec_input, struct tok_state *tok) {
static const char *
decode_str(const char *input, int single, struct tok_state *tok)
{
- PyObject* utf8 = NULL;
- const char *str;
- const char *s;
- const char *newl[2] = {NULL, NULL};
- int lineno = 0;
- tok->input = str = translate_newlines(input, single, tok);
- if (str == NULL)
- return NULL;
- tok->enc = NULL;
- tok->str = str;
- if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok))
- return error_ret(tok);
- str = tok->str; /* string after BOM if any */
- assert(str);
+ PyObject* utf8 = NULL;
+ const char *str;
+ const char *s;
+ const char *newl[2] = {NULL, NULL};
+ int lineno = 0;
+ tok->input = str = translate_newlines(input, single, tok);
+ if (str == NULL)
+ return NULL;
+ tok->enc = NULL;
+ tok->str = str;
+ if (!check_bom(buf_getc, buf_ungetc, buf_setreadl, tok))
+ return error_ret(tok);
+ str = tok->str; /* string after BOM if any */
+ assert(str);
#ifdef Py_USING_UNICODE
- if (tok->enc != NULL) {
- utf8 = translate_into_utf8(str, tok->enc);
- if (utf8 == NULL)
- return error_ret(tok);
- str = PyString_AsString(utf8);
- }
+ if (tok->enc != NULL) {
+ utf8 = translate_into_utf8(str, tok->enc);
+ if (utf8 == NULL)
+ return error_ret(tok);
+ str = PyString_AsString(utf8);
+ }
#endif
- for (s = str;; s++) {
- if (*s == '\0') break;
- else if (*s == '\n') {
- assert(lineno < 2);
- newl[lineno] = s;
- lineno++;
- if (lineno == 2) break;
- }
- }
- tok->enc = NULL;
- /* need to check line 1 and 2 separately since check_coding_spec
- assumes a single line as input */
- if (newl[0]) {
- if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl))
- return error_ret(tok);
- if (tok->enc == NULL && newl[1]) {
- if (!check_coding_spec(newl[0]+1, newl[1] - newl[0],
- tok, buf_setreadl))
- return error_ret(tok);
- }
- }
+ for (s = str;; s++) {
+ if (*s == '\0') break;
+ else if (*s == '\n') {
+ assert(lineno < 2);
+ newl[lineno] = s;
+ lineno++;
+ if (lineno == 2) break;
+ }
+ }
+ tok->enc = NULL;
+ /* need to check line 1 and 2 separately since check_coding_spec
+ assumes a single line as input */
+ if (newl[0]) {
+ if (!check_coding_spec(str, newl[0] - str, tok, buf_setreadl))
+ return error_ret(tok);
+ if (tok->enc == NULL && newl[1]) {
+ if (!check_coding_spec(newl[0]+1, newl[1] - newl[0],
+ tok, buf_setreadl))
+ return error_ret(tok);
+ }
+ }
#ifdef Py_USING_UNICODE
- if (tok->enc != NULL) {
- assert(utf8 == NULL);
- utf8 = translate_into_utf8(str, tok->enc);
- if (utf8 == NULL)
- return error_ret(tok);
- str = PyString_AsString(utf8);
- }
+ if (tok->enc != NULL) {
+ assert(utf8 == NULL);
+ utf8 = translate_into_utf8(str, tok->enc);
+ if (utf8 == NULL)
+ return error_ret(tok);
+ str = PyString_AsString(utf8);
+ }
#endif
- assert(tok->decoding_buffer == NULL);
- tok->decoding_buffer = utf8; /* CAUTION */
- return str;
+ assert(tok->decoding_buffer == NULL);
+ tok->decoding_buffer = utf8; /* CAUTION */
+ return str;
}
#endif /* PGEN */
@@ -709,18 +709,18 @@ decode_str(const char *input, int single, struct tok_state *tok)
struct tok_state *
PyTokenizer_FromString(const char *str, int exec_input)
{
- struct tok_state *tok = tok_new();
- if (tok == NULL)
- return NULL;
- str = (char *)decode_str(str, exec_input, tok);
- if (str == NULL) {
- PyTokenizer_Free(tok);
- return NULL;
- }
-
- /* XXX: constify members. */
- tok->buf = tok->cur = tok->end = tok->inp = (char*)str;
- return tok;
+ struct tok_state *tok = tok_new();
+ if (tok == NULL)
+ return NULL;
+ str = (char *)decode_str(str, exec_input, tok);
+ if (str == NULL) {
+ PyTokenizer_Free(tok);
+ return NULL;
+ }
+
+ /* XXX: constify members. */
+ tok->buf = tok->cur = tok->end = tok->inp = (char*)str;
+ return tok;
}
@@ -729,19 +729,19 @@ PyTokenizer_FromString(const char *str, int exec_input)
struct tok_state *
PyTokenizer_FromFile(FILE *fp, char *ps1, char *ps2)
{
- struct tok_state *tok = tok_new();
- if (tok == NULL)
- return NULL;
- if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) {
- PyTokenizer_Free(tok);
- return NULL;
- }
- tok->cur = tok->inp = tok->buf;
- tok->end = tok->buf + BUFSIZ;
- tok->fp = fp;
- tok->prompt = ps1;
- tok->nextprompt = ps2;
- return tok;
+ struct tok_state *tok = tok_new();
+ if (tok == NULL)
+ return NULL;
+ if ((tok->buf = (char *)PyMem_MALLOC(BUFSIZ)) == NULL) {
+ PyTokenizer_Free(tok);
+ return NULL;
+ }
+ tok->cur = tok->inp = tok->buf;
+ tok->end = tok->buf + BUFSIZ;
+ tok->fp = fp;
+ tok->prompt = ps1;
+ tok->nextprompt = ps2;
+ return tok;
}
@@ -750,80 +750,80 @@ PyTokenizer_FromFile(FILE *fp, char *ps1, char *ps2)
void
PyTokenizer_Free(struct tok_state *tok)
{
- if (tok->encoding != NULL)
- PyMem_FREE(tok->encoding);
+ if (tok->encoding != NULL)
+ PyMem_FREE(tok->encoding);
#ifndef PGEN
- Py_XDECREF(tok->decoding_readline);
- Py_XDECREF(tok->decoding_buffer);
+ Py_XDECREF(tok->decoding_readline);
+ Py_XDECREF(tok->decoding_buffer);
#endif
- if (tok->fp != NULL && tok->buf != NULL)
- PyMem_FREE(tok->buf);
- if (tok->input)
- PyMem_FREE((char *)tok->input);
- PyMem_FREE(tok);
+ if (tok->fp != NULL && tok->buf != NULL)
+ PyMem_FREE(tok->buf);
+ if (tok->input)
+ PyMem_FREE((char *)tok->input);
+ PyMem_FREE(tok);
}
#if !defined(PGEN) && defined(Py_USING_UNICODE)
static int
tok_stdin_decode(struct tok_state *tok, char **inp)
{
- PyObject *enc, *sysstdin, *decoded, *utf8;
- const char *encoding;
- char *converted;
-
- if (PySys_GetFile((char *)"stdin", NULL) != stdin)
- return 0;
- sysstdin = PySys_GetObject("stdin");
- if (sysstdin == NULL || !PyFile_Check(sysstdin))
- return 0;
-
- enc = ((PyFileObject *)sysstdin)->f_encoding;
- if (enc == NULL || !PyString_Check(enc))
- return 0;
- Py_INCREF(enc);
-
- encoding = PyString_AsString(enc);
- decoded = PyUnicode_Decode(*inp, strlen(*inp), encoding, NULL);
- if (decoded == NULL)
- goto error_clear;
-
- utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL);
- Py_DECREF(decoded);
- if (utf8 == NULL)
- goto error_clear;
-
- assert(PyString_Check(utf8));
- converted = new_string(PyString_AS_STRING(utf8),
- PyString_GET_SIZE(utf8));
- Py_DECREF(utf8);
- if (converted == NULL)
- goto error_nomem;
-
- PyMem_FREE(*inp);
- *inp = converted;
- if (tok->encoding != NULL)
- PyMem_FREE(tok->encoding);
- tok->encoding = new_string(encoding, strlen(encoding));
- if (tok->encoding == NULL)
- goto error_nomem;
-
- Py_DECREF(enc);
- return 0;
+ PyObject *enc, *sysstdin, *decoded, *utf8;
+ const char *encoding;
+ char *converted;
+
+ if (PySys_GetFile((char *)"stdin", NULL) != stdin)
+ return 0;
+ sysstdin = PySys_GetObject("stdin");
+ if (sysstdin == NULL || !PyFile_Check(sysstdin))
+ return 0;
+
+ enc = ((PyFileObject *)sysstdin)->f_encoding;
+ if (enc == NULL || !PyString_Check(enc))
+ return 0;
+ Py_INCREF(enc);
+
+ encoding = PyString_AsString(enc);
+ decoded = PyUnicode_Decode(*inp, strlen(*inp), encoding, NULL);
+ if (decoded == NULL)
+ goto error_clear;
+
+ utf8 = PyUnicode_AsEncodedString(decoded, "utf-8", NULL);
+ Py_DECREF(decoded);
+ if (utf8 == NULL)
+ goto error_clear;
+
+ assert(PyString_Check(utf8));
+ converted = new_string(PyString_AS_STRING(utf8),
+ PyString_GET_SIZE(utf8));
+ Py_DECREF(utf8);
+ if (converted == NULL)
+ goto error_nomem;
+
+ PyMem_FREE(*inp);
+ *inp = converted;
+ if (tok->encoding != NULL)
+ PyMem_FREE(tok->encoding);
+ tok->encoding = new_string(encoding, strlen(encoding));
+ if (tok->encoding == NULL)
+ goto error_nomem;
+
+ Py_DECREF(enc);
+ return 0;
error_nomem:
- Py_DECREF(enc);
- tok->done = E_NOMEM;
- return -1;
+ Py_DECREF(enc);
+ tok->done = E_NOMEM;
+ return -1;
error_clear:
- Py_DECREF(enc);
- if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
- tok->done = E_ERROR;
- return -1;
- }
- /* Fallback to iso-8859-1: for backward compatibility */
- PyErr_Clear();
- return 0;
+ Py_DECREF(enc);
+ if (!PyErr_ExceptionMatches(PyExc_UnicodeDecodeError)) {
+ tok->done = E_ERROR;
+ return -1;
+ }
+ /* Fallback to iso-8859-1: for backward compatibility */
+ PyErr_Clear();
+ return 0;
}
#endif
@@ -832,169 +832,169 @@ error_clear:
static int
tok_nextc(register struct tok_state *tok)
{
- for (;;) {
- if (tok->cur != tok->inp) {
- return Py_CHARMASK(*tok->cur++); /* Fast path */
- }
- if (tok->done != E_OK)
- return EOF;
- if (tok->fp == NULL) {
- char *end = strchr(tok->inp, '\n');
- if (end != NULL)
- end++;
- else {
- end = strchr(tok->inp, '\0');
- if (end == tok->inp) {
- tok->done = E_EOF;
- return EOF;
- }
- }
- if (tok->start == NULL)
- tok->buf = tok->cur;
- tok->line_start = tok->cur;
- tok->lineno++;
- tok->inp = end;
- return Py_CHARMASK(*tok->cur++);
- }
- if (tok->prompt != NULL) {
- char *newtok = PyOS_Readline(stdin, stdout, tok->prompt);
- if (tok->nextprompt != NULL)
- tok->prompt = tok->nextprompt;
- if (newtok == NULL)
- tok->done = E_INTR;
- else if (*newtok == '\0') {
- PyMem_FREE(newtok);
- tok->done = E_EOF;
- }
+ for (;;) {
+ if (tok->cur != tok->inp) {
+ return Py_CHARMASK(*tok->cur++); /* Fast path */
+ }
+ if (tok->done != E_OK)
+ return EOF;
+ if (tok->fp == NULL) {
+ char *end = strchr(tok->inp, '\n');
+ if (end != NULL)
+ end++;
+ else {
+ end = strchr(tok->inp, '\0');
+ if (end == tok->inp) {
+ tok->done = E_EOF;
+ return EOF;
+ }
+ }
+ if (tok->start == NULL)
+ tok->buf = tok->cur;
+ tok->line_start = tok->cur;
+ tok->lineno++;
+ tok->inp = end;
+ return Py_CHARMASK(*tok->cur++);
+ }
+ if (tok->prompt != NULL) {
+ char *newtok = PyOS_Readline(stdin, stdout, tok->prompt);
+ if (tok->nextprompt != NULL)
+ tok->prompt = tok->nextprompt;
+ if (newtok == NULL)
+ tok->done = E_INTR;
+ else if (*newtok == '\0') {
+ PyMem_FREE(newtok);
+ tok->done = E_EOF;
+ }
#if !defined(PGEN) && defined(Py_USING_UNICODE)
- else if (tok_stdin_decode(tok, &newtok) != 0)
- PyMem_FREE(newtok);
+ else if (tok_stdin_decode(tok, &newtok) != 0)
+ PyMem_FREE(newtok);
#endif
- else if (tok->start != NULL) {
- size_t start = tok->start - tok->buf;
- size_t oldlen = tok->cur - tok->buf;
- size_t newlen = oldlen + strlen(newtok);
- char *buf = tok->buf;
- buf = (char *)PyMem_REALLOC(buf, newlen+1);
- tok->lineno++;
- if (buf == NULL) {
- PyMem_FREE(tok->buf);
- tok->buf = NULL;
- PyMem_FREE(newtok);
- tok->done = E_NOMEM;
- return EOF;
- }
- tok->buf = buf;
- tok->cur = tok->buf + oldlen;
- tok->line_start = tok->cur;
- strcpy(tok->buf + oldlen, newtok);
- PyMem_FREE(newtok);
- tok->inp = tok->buf + newlen;
- tok->end = tok->inp + 1;
- tok->start = tok->buf + start;
- }
- else {
- tok->lineno++;
- if (tok->buf != NULL)
- PyMem_FREE(tok->buf);
- tok->buf = newtok;
- tok->line_start = tok->buf;
- tok->cur = tok->buf;
- tok->line_start = tok->buf;
- tok->inp = strchr(tok->buf, '\0');
- tok->end = tok->inp + 1;
- }
- }
- else {
- int done = 0;
- Py_ssize_t cur = 0;
- char *pt;
- if (tok->start == NULL) {
- if (tok->buf == NULL) {
- tok->buf = (char *)
- PyMem_MALLOC(BUFSIZ);
- if (tok->buf == NULL) {
- tok->done = E_NOMEM;
- return EOF;
- }
- tok->end = tok->buf + BUFSIZ;
- }
- if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf),
- tok) == NULL) {
- tok->done = E_EOF;
- done = 1;
- }
- else {
- tok->done = E_OK;
- tok->inp = strchr(tok->buf, '\0');
- done = tok->inp[-1] == '\n';
- }
- }
- else {
- cur = tok->cur - tok->buf;
- if (decoding_feof(tok)) {
- tok->done = E_EOF;
- done = 1;
- }
- else
- tok->done = E_OK;
- }
- tok->lineno++;
- /* Read until '\n' or EOF */
- while (!done) {
- Py_ssize_t curstart = tok->start == NULL ? -1 :
- tok->start - tok->buf;
- Py_ssize_t curvalid = tok->inp - tok->buf;
- Py_ssize_t newsize = curvalid + BUFSIZ;
- char *newbuf = tok->buf;
- newbuf = (char *)PyMem_REALLOC(newbuf,
- newsize);
- if (newbuf == NULL) {
- tok->done = E_NOMEM;
- tok->cur = tok->inp;
- return EOF;
- }
- tok->buf = newbuf;
- tok->inp = tok->buf + curvalid;
- tok->end = tok->buf + newsize;
- tok->start = curstart < 0 ? NULL :
- tok->buf + curstart;
- if (decoding_fgets(tok->inp,
- (int)(tok->end - tok->inp),
- tok) == NULL) {
- /* Break out early on decoding
- errors, as tok->buf will be NULL
- */
- if (tok->decoding_erred)
- return EOF;
- /* Last line does not end in \n,
- fake one */
- strcpy(tok->inp, "\n");
- }
- tok->inp = strchr(tok->inp, '\0');
- done = tok->inp[-1] == '\n';
- }
- if (tok->buf != NULL) {
- tok->cur = tok->buf + cur;
- tok->line_start = tok->cur;
- /* replace "\r\n" with "\n" */
- /* For Mac leave the \r, giving a syntax error */
- pt = tok->inp - 2;
- if (pt >= tok->buf && *pt == '\r') {
- *pt++ = '\n';
- *pt = '\0';
- tok->inp = pt;
- }
- }
- }
- if (tok->done != E_OK) {
- if (tok->prompt != NULL)
- PySys_WriteStderr("\n");
- tok->cur = tok->inp;
- return EOF;
- }
- }
- /*NOTREACHED*/
+ else if (tok->start != NULL) {
+ size_t start = tok->start - tok->buf;
+ size_t oldlen = tok->cur - tok->buf;
+ size_t newlen = oldlen + strlen(newtok);
+ char *buf = tok->buf;
+ buf = (char *)PyMem_REALLOC(buf, newlen+1);
+ tok->lineno++;
+ if (buf == NULL) {
+ PyMem_FREE(tok->buf);
+ tok->buf = NULL;
+ PyMem_FREE(newtok);
+ tok->done = E_NOMEM;
+ return EOF;
+ }
+ tok->buf = buf;
+ tok->cur = tok->buf + oldlen;
+ tok->line_start = tok->cur;
+ strcpy(tok->buf + oldlen, newtok);
+ PyMem_FREE(newtok);
+ tok->inp = tok->buf + newlen;
+ tok->end = tok->inp + 1;
+ tok->start = tok->buf + start;
+ }
+ else {
+ tok->lineno++;
+ if (tok->buf != NULL)
+ PyMem_FREE(tok->buf);
+ tok->buf = newtok;
+ tok->line_start = tok->buf;
+ tok->cur = tok->buf;
+ tok->line_start = tok->buf;
+ tok->inp = strchr(tok->buf, '\0');
+ tok->end = tok->inp + 1;
+ }
+ }
+ else {
+ int done = 0;
+ Py_ssize_t cur = 0;
+ char *pt;
+ if (tok->start == NULL) {
+ if (tok->buf == NULL) {
+ tok->buf = (char *)
+ PyMem_MALLOC(BUFSIZ);
+ if (tok->buf == NULL) {
+ tok->done = E_NOMEM;
+ return EOF;
+ }
+ tok->end = tok->buf + BUFSIZ;
+ }
+ if (decoding_fgets(tok->buf, (int)(tok->end - tok->buf),
+ tok) == NULL) {
+ tok->done = E_EOF;
+ done = 1;
+ }
+ else {
+ tok->done = E_OK;
+ tok->inp = strchr(tok->buf, '\0');
+ done = tok->inp[-1] == '\n';
+ }
+ }
+ else {
+ cur = tok->cur - tok->buf;
+ if (decoding_feof(tok)) {
+ tok->done = E_EOF;
+ done = 1;
+ }
+ else
+ tok->done = E_OK;
+ }
+ tok->lineno++;
+ /* Read until '\n' or EOF */
+ while (!done) {
+ Py_ssize_t curstart = tok->start == NULL ? -1 :
+ tok->start - tok->buf;
+ Py_ssize_t curvalid = tok->inp - tok->buf;
+ Py_ssize_t newsize = curvalid + BUFSIZ;
+ char *newbuf = tok->buf;
+ newbuf = (char *)PyMem_REALLOC(newbuf,
+ newsize);
+ if (newbuf == NULL) {
+ tok->done = E_NOMEM;
+ tok->cur = tok->inp;
+ return EOF;
+ }
+ tok->buf = newbuf;
+ tok->inp = tok->buf + curvalid;
+ tok->end = tok->buf + newsize;
+ tok->start = curstart < 0 ? NULL :
+ tok->buf + curstart;
+ if (decoding_fgets(tok->inp,
+ (int)(tok->end - tok->inp),
+ tok) == NULL) {
+ /* Break out early on decoding
+ errors, as tok->buf will be NULL
+ */
+ if (tok->decoding_erred)
+ return EOF;
+ /* Last line does not end in \n,
+ fake one */
+ strcpy(tok->inp, "\n");
+ }
+ tok->inp = strchr(tok->inp, '\0');
+ done = tok->inp[-1] == '\n';
+ }
+ if (tok->buf != NULL) {
+ tok->cur = tok->buf + cur;
+ tok->line_start = tok->cur;
+ /* replace "\r\n" with "\n" */
+ /* For Mac leave the \r, giving a syntax error */
+ pt = tok->inp - 2;
+ if (pt >= tok->buf && *pt == '\r') {
+ *pt++ = '\n';
+ *pt = '\0';
+ tok->inp = pt;
+ }
+ }
+ }
+ if (tok->done != E_OK) {
+ if (tok->prompt != NULL)
+ PySys_WriteStderr("\n");
+ tok->cur = tok->inp;
+ return EOF;
+ }
+ }
+ /*NOTREACHED*/
}
@@ -1003,12 +1003,12 @@ tok_nextc(register struct tok_state *tok)
static void
tok_backup(register struct tok_state *tok, register int c)
{
- if (c != EOF) {
- if (--tok->cur < tok->buf)
- Py_FatalError("tok_backup: beginning of buffer");
- if (*tok->cur != c)
- *tok->cur = c;
- }
+ if (c != EOF) {
+ if (--tok->cur < tok->buf)
+ Py_FatalError("tok_backup: beginning of buffer");
+ if (*tok->cur != c)
+ *tok->cur = c;
+ }
}
@@ -1017,171 +1017,171 @@ tok_backup(register struct tok_state *tok, register int c)
int
PyToken_OneChar(int c)
{
- switch (c) {
- case '(': return LPAR;
- case ')': return RPAR;
- case '[': return LSQB;
- case ']': return RSQB;
- case ':': return COLON;
- case ',': return COMMA;
- case ';': return SEMI;
- case '+': return PLUS;
- case '-': return MINUS;
- case '*': return STAR;
- case '/': return SLASH;
- case '|': return VBAR;
- case '&': return AMPER;
- case '<': return LESS;
- case '>': return GREATER;
- case '=': return EQUAL;
- case '.': return DOT;
- case '%': return PERCENT;
- case '`': return BACKQUOTE;
- case '{': return LBRACE;
- case '}': return RBRACE;
- case '^': return CIRCUMFLEX;
- case '~': return TILDE;
- case '@': return AT;
- default: return OP;
- }
+ switch (c) {
+ case '(': return LPAR;
+ case ')': return RPAR;
+ case '[': return LSQB;
+ case ']': return RSQB;
+ case ':': return COLON;
+ case ',': return COMMA;
+ case ';': return SEMI;
+ case '+': return PLUS;
+ case '-': return MINUS;
+ case '*': return STAR;
+ case '/': return SLASH;
+ case '|': return VBAR;
+ case '&': return AMPER;
+ case '<': return LESS;
+ case '>': return GREATER;
+ case '=': return EQUAL;
+ case '.': return DOT;
+ case '%': return PERCENT;
+ case '`': return BACKQUOTE;
+ case '{': return LBRACE;
+ case '}': return RBRACE;
+ case '^': return CIRCUMFLEX;
+ case '~': return TILDE;
+ case '@': return AT;
+ default: return OP;
+ }
}
int
PyToken_TwoChars(int c1, int c2)
{
- switch (c1) {
- case '=':
- switch (c2) {
- case '=': return EQEQUAL;
- }
- break;
- case '!':
- switch (c2) {
- case '=': return NOTEQUAL;
- }
- break;
- case '<':
- switch (c2) {
- case '>': return NOTEQUAL;
- case '=': return LESSEQUAL;
- case '<': return LEFTSHIFT;
- }
- break;
- case '>':
- switch (c2) {
- case '=': return GREATEREQUAL;
- case '>': return RIGHTSHIFT;
- }
- break;
- case '+':
- switch (c2) {
- case '=': return PLUSEQUAL;
- }
- break;
- case '-':
- switch (c2) {
- case '=': return MINEQUAL;
- }
- break;
- case '*':
- switch (c2) {
- case '*': return DOUBLESTAR;
- case '=': return STAREQUAL;
- }
- break;
- case '/':
- switch (c2) {
- case '/': return DOUBLESLASH;
- case '=': return SLASHEQUAL;
- }
- break;
- case '|':
- switch (c2) {
- case '=': return VBAREQUAL;
- }
- break;
- case '%':
- switch (c2) {
- case '=': return PERCENTEQUAL;
- }
- break;
- case '&':
- switch (c2) {
- case '=': return AMPEREQUAL;
- }
- break;
- case '^':
- switch (c2) {
- case '=': return CIRCUMFLEXEQUAL;
- }
- break;
- }
- return OP;
+ switch (c1) {
+ case '=':
+ switch (c2) {
+ case '=': return EQEQUAL;
+ }
+ break;
+ case '!':
+ switch (c2) {
+ case '=': return NOTEQUAL;
+ }
+ break;
+ case '<':
+ switch (c2) {
+ case '>': return NOTEQUAL;
+ case '=': return LESSEQUAL;
+ case '<': return LEFTSHIFT;
+ }
+ break;
+ case '>':
+ switch (c2) {
+ case '=': return GREATEREQUAL;
+ case '>': return RIGHTSHIFT;
+ }
+ break;
+ case '+':
+ switch (c2) {
+ case '=': return PLUSEQUAL;
+ }
+ break;
+ case '-':
+ switch (c2) {
+ case '=': return MINEQUAL;
+ }
+ break;
+ case '*':
+ switch (c2) {
+ case '*': return DOUBLESTAR;
+ case '=': return STAREQUAL;
+ }
+ break;
+ case '/':
+ switch (c2) {
+ case '/': return DOUBLESLASH;
+ case '=': return SLASHEQUAL;
+ }
+ break;
+ case '|':
+ switch (c2) {
+ case '=': return VBAREQUAL;
+ }
+ break;
+ case '%':
+ switch (c2) {
+ case '=': return PERCENTEQUAL;
+ }
+ break;
+ case '&':
+ switch (c2) {
+ case '=': return AMPEREQUAL;
+ }
+ break;
+ case '^':
+ switch (c2) {
+ case '=': return CIRCUMFLEXEQUAL;
+ }
+ break;
+ }
+ return OP;
}
int
PyToken_ThreeChars(int c1, int c2, int c3)
{
- switch (c1) {
- case '<':
- switch (c2) {
- case '<':
- switch (c3) {
- case '=':
- return LEFTSHIFTEQUAL;
- }
- break;
- }
- break;
- case '>':
- switch (c2) {
- case '>':
- switch (c3) {
- case '=':
- return RIGHTSHIFTEQUAL;
- }
- break;
- }
- break;
- case '*':
- switch (c2) {
- case '*':
- switch (c3) {
- case '=':
- return DOUBLESTAREQUAL;
- }
- break;
- }
- break;
- case '/':
- switch (c2) {
- case '/':
- switch (c3) {
- case '=':
- return DOUBLESLASHEQUAL;
- }
- break;
- }
- break;
- }
- return OP;
+ switch (c1) {
+ case '<':
+ switch (c2) {
+ case '<':
+ switch (c3) {
+ case '=':
+ return LEFTSHIFTEQUAL;
+ }
+ break;
+ }
+ break;
+ case '>':
+ switch (c2) {
+ case '>':
+ switch (c3) {
+ case '=':
+ return RIGHTSHIFTEQUAL;
+ }
+ break;
+ }
+ break;
+ case '*':
+ switch (c2) {
+ case '*':
+ switch (c3) {
+ case '=':
+ return DOUBLESTAREQUAL;
+ }
+ break;
+ }
+ break;
+ case '/':
+ switch (c2) {
+ case '/':
+ switch (c3) {
+ case '=':
+ return DOUBLESLASHEQUAL;
+ }
+ break;
+ }
+ break;
+ }
+ return OP;
}
static int
indenterror(struct tok_state *tok)
{
- if (tok->alterror) {
- tok->done = E_TABSPACE;
- tok->cur = tok->inp;
- return 1;
- }
- if (tok->altwarning) {
- PySys_WriteStderr("%s: inconsistent use of tabs and spaces "
- "in indentation\n", tok->filename);
- tok->altwarning = 0;
- }
- return 0;
+ if (tok->alterror) {
+ tok->done = E_TABSPACE;
+ tok->cur = tok->inp;
+ return 1;
+ }
+ if (tok->altwarning) {
+ PySys_WriteStderr("%s: inconsistent use of tabs and spaces "
+ "in indentation\n", tok->filename);
+ tok->altwarning = 0;
+ }
+ return 0;
}
/* Get next token, after space stripping etc. */
@@ -1189,466 +1189,466 @@ indenterror(struct tok_state *tok)
static int
tok_get(register struct tok_state *tok, char **p_start, char **p_end)
{
- register int c;
- int blankline;
+ register int c;
+ int blankline;
- *p_start = *p_end = NULL;
+ *p_start = *p_end = NULL;
nextline:
- tok->start = NULL;
- blankline = 0;
-
- /* Get indentation level */
- if (tok->atbol) {
- register int col = 0;
- register int altcol = 0;
- tok->atbol = 0;
- for (;;) {
- c = tok_nextc(tok);
- if (c == ' ')
- col++, altcol++;
- else if (c == '\t') {
- col = (col/tok->tabsize + 1) * tok->tabsize;
- altcol = (altcol/tok->alttabsize + 1)
- * tok->alttabsize;
- }
- else if (c == '\014') /* Control-L (formfeed) */
- col = altcol = 0; /* For Emacs users */
- else
- break;
- }
- tok_backup(tok, c);
- if (c == '#' || c == '\n') {
- /* Lines with only whitespace and/or comments
- shouldn't affect the indentation and are
- not passed to the parser as NEWLINE tokens,
- except *totally* empty lines in interactive
- mode, which signal the end of a command group. */
- if (col == 0 && c == '\n' && tok->prompt != NULL)
- blankline = 0; /* Let it through */
- else
- blankline = 1; /* Ignore completely */
- /* We can't jump back right here since we still
- may need to skip to the end of a comment */
- }
- if (!blankline && tok->level == 0) {
- if (col == tok->indstack[tok->indent]) {
- /* No change */
- if (altcol != tok->altindstack[tok->indent]) {
- if (indenterror(tok))
- return ERRORTOKEN;
- }
- }
- else if (col > tok->indstack[tok->indent]) {
- /* Indent -- always one */
- if (tok->indent+1 >= MAXINDENT) {
- tok->done = E_TOODEEP;
- tok->cur = tok->inp;
- return ERRORTOKEN;
- }
- if (altcol <= tok->altindstack[tok->indent]) {
- if (indenterror(tok))
- return ERRORTOKEN;
- }
- tok->pendin++;
- tok->indstack[++tok->indent] = col;
- tok->altindstack[tok->indent] = altcol;
- }
- else /* col < tok->indstack[tok->indent] */ {
- /* Dedent -- any number, must be consistent */
- while (tok->indent > 0 &&
- col < tok->indstack[tok->indent]) {
- tok->pendin--;
- tok->indent--;
- }
- if (col != tok->indstack[tok->indent]) {
- tok->done = E_DEDENT;
- tok->cur = tok->inp;
- return ERRORTOKEN;
- }
- if (altcol != tok->altindstack[tok->indent]) {
- if (indenterror(tok))
- return ERRORTOKEN;
- }
- }
- }
- }
-
- tok->start = tok->cur;
-
- /* Return pending indents/dedents */
- if (tok->pendin != 0) {
- if (tok->pendin < 0) {
- tok->pendin++;
- return DEDENT;
- }
- else {
- tok->pendin--;
- return INDENT;
- }
- }
+ tok->start = NULL;
+ blankline = 0;
+
+ /* Get indentation level */
+ if (tok->atbol) {
+ register int col = 0;
+ register int altcol = 0;
+ tok->atbol = 0;
+ for (;;) {
+ c = tok_nextc(tok);
+ if (c == ' ')
+ col++, altcol++;
+ else if (c == '\t') {
+ col = (col/tok->tabsize + 1) * tok->tabsize;
+ altcol = (altcol/tok->alttabsize + 1)
+ * tok->alttabsize;
+ }
+ else if (c == '\014') /* Control-L (formfeed) */
+ col = altcol = 0; /* For Emacs users */
+ else
+ break;
+ }
+ tok_backup(tok, c);
+ if (c == '#' || c == '\n') {
+ /* Lines with only whitespace and/or comments
+ shouldn't affect the indentation and are
+ not passed to the parser as NEWLINE tokens,
+ except *totally* empty lines in interactive
+ mode, which signal the end of a command group. */
+ if (col == 0 && c == '\n' && tok->prompt != NULL)
+ blankline = 0; /* Let it through */
+ else
+ blankline = 1; /* Ignore completely */
+ /* We can't jump back right here since we still
+ may need to skip to the end of a comment */
+ }
+ if (!blankline && tok->level == 0) {
+ if (col == tok->indstack[tok->indent]) {
+ /* No change */
+ if (altcol != tok->altindstack[tok->indent]) {
+ if (indenterror(tok))
+ return ERRORTOKEN;
+ }
+ }
+ else if (col > tok->indstack[tok->indent]) {
+ /* Indent -- always one */
+ if (tok->indent+1 >= MAXINDENT) {
+ tok->done = E_TOODEEP;
+ tok->cur = tok->inp;
+ return ERRORTOKEN;
+ }
+ if (altcol <= tok->altindstack[tok->indent]) {
+ if (indenterror(tok))
+ return ERRORTOKEN;
+ }
+ tok->pendin++;
+ tok->indstack[++tok->indent] = col;
+ tok->altindstack[tok->indent] = altcol;
+ }
+ else /* col < tok->indstack[tok->indent] */ {
+ /* Dedent -- any number, must be consistent */
+ while (tok->indent > 0 &&
+ col < tok->indstack[tok->indent]) {
+ tok->pendin--;
+ tok->indent--;
+ }
+ if (col != tok->indstack[tok->indent]) {
+ tok->done = E_DEDENT;
+ tok->cur = tok->inp;
+ return ERRORTOKEN;
+ }
+ if (altcol != tok->altindstack[tok->indent]) {
+ if (indenterror(tok))
+ return ERRORTOKEN;
+ }
+ }
+ }
+ }
+
+ tok->start = tok->cur;
+
+ /* Return pending indents/dedents */
+ if (tok->pendin != 0) {
+ if (tok->pendin < 0) {
+ tok->pendin++;
+ return DEDENT;
+ }
+ else {
+ tok->pendin--;
+ return INDENT;
+ }
+ }
again:
- tok->start = NULL;
- /* Skip spaces */
- do {
- c = tok_nextc(tok);
- } while (c == ' ' || c == '\t' || c == '\014');
-
- /* Set start of current token */
- tok->start = tok->cur - 1;
-
- /* Skip comment, while looking for tab-setting magic */
- if (c == '#') {
- static char *tabforms[] = {
- "tab-width:", /* Emacs */
- ":tabstop=", /* vim, full form */
- ":ts=", /* vim, abbreviated form */
- "set tabsize=", /* will vi never die? */
- /* more templates can be added here to support other editors */
- };
- char cbuf[80];
- char *tp, **cp;
- tp = cbuf;
- do {
- *tp++ = c = tok_nextc(tok);
- } while (c != EOF && c != '\n' &&
- (size_t)(tp - cbuf + 1) < sizeof(cbuf));
- *tp = '\0';
- for (cp = tabforms;
- cp < tabforms + sizeof(tabforms)/sizeof(tabforms[0]);
- cp++) {
- if ((tp = strstr(cbuf, *cp))) {
- int newsize = atoi(tp + strlen(*cp));
-
- if (newsize >= 1 && newsize <= 40) {
- tok->tabsize = newsize;
- if (Py_VerboseFlag)
- PySys_WriteStderr(
- "Tab size set to %d\n",
- newsize);
- }
- }
- }
- while (c != EOF && c != '\n')
- c = tok_nextc(tok);
- }
-
- /* Check for EOF and errors now */
- if (c == EOF) {
- return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;
- }
-
- /* Identifier (most frequent token!) */
- if (Py_ISALPHA(c) || c == '_') {
- /* Process r"", u"" and ur"" */
- switch (c) {
- case 'b':
- case 'B':
- c = tok_nextc(tok);
- if (c == 'r' || c == 'R')
- c = tok_nextc(tok);
- if (c == '"' || c == '\'')
- goto letter_quote;
- break;
- case 'r':
- case 'R':
- c = tok_nextc(tok);
- if (c == '"' || c == '\'')
- goto letter_quote;
- break;
- case 'u':
- case 'U':
- c = tok_nextc(tok);
- if (c == 'r' || c == 'R')
- c = tok_nextc(tok);
- if (c == '"' || c == '\'')
- goto letter_quote;
- break;
- }
- while (Py_ISALNUM(c) || c == '_') {
- c = tok_nextc(tok);
- }
- tok_backup(tok, c);
- *p_start = tok->start;
- *p_end = tok->cur;
- return NAME;
- }
-
- /* Newline */
- if (c == '\n') {
- tok->atbol = 1;
- if (blankline || tok->level > 0)
- goto nextline;
- *p_start = tok->start;
- *p_end = tok->cur - 1; /* Leave '\n' out of the string */
- tok->cont_line = 0;
- return NEWLINE;
- }
-
- /* Period or number starting with period? */
- if (c == '.') {
- c = tok_nextc(tok);
- if (isdigit(c)) {
- goto fraction;
- }
- else {
- tok_backup(tok, c);
- *p_start = tok->start;
- *p_end = tok->cur;
- return DOT;
- }
- }
-
- /* Number */
- if (isdigit(c)) {
- if (c == '0') {
- /* Hex, octal or binary -- maybe. */
- c = tok_nextc(tok);
- if (c == '.')
- goto fraction;
+ tok->start = NULL;
+ /* Skip spaces */
+ do {
+ c = tok_nextc(tok);
+ } while (c == ' ' || c == '\t' || c == '\014');
+
+ /* Set start of current token */
+ tok->start = tok->cur - 1;
+
+ /* Skip comment, while looking for tab-setting magic */
+ if (c == '#') {
+ static char *tabforms[] = {
+ "tab-width:", /* Emacs */
+ ":tabstop=", /* vim, full form */
+ ":ts=", /* vim, abbreviated form */
+ "set tabsize=", /* will vi never die? */
+ /* more templates can be added here to support other editors */
+ };
+ char cbuf[80];
+ char *tp, **cp;
+ tp = cbuf;
+ do {
+ *tp++ = c = tok_nextc(tok);
+ } while (c != EOF && c != '\n' &&
+ (size_t)(tp - cbuf + 1) < sizeof(cbuf));
+ *tp = '\0';
+ for (cp = tabforms;
+ cp < tabforms + sizeof(tabforms)/sizeof(tabforms[0]);
+ cp++) {
+ if ((tp = strstr(cbuf, *cp))) {
+ int newsize = atoi(tp + strlen(*cp));
+
+ if (newsize >= 1 && newsize <= 40) {
+ tok->tabsize = newsize;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr(
+ "Tab size set to %d\n",
+ newsize);
+ }
+ }
+ }
+ while (c != EOF && c != '\n')
+ c = tok_nextc(tok);
+ }
+
+ /* Check for EOF and errors now */
+ if (c == EOF) {
+ return tok->done == E_EOF ? ENDMARKER : ERRORTOKEN;
+ }
+
+ /* Identifier (most frequent token!) */
+ if (Py_ISALPHA(c) || c == '_') {
+ /* Process r"", u"" and ur"" */
+ switch (c) {
+ case 'b':
+ case 'B':
+ c = tok_nextc(tok);
+ if (c == 'r' || c == 'R')
+ c = tok_nextc(tok);
+ if (c == '"' || c == '\'')
+ goto letter_quote;
+ break;
+ case 'r':
+ case 'R':
+ c = tok_nextc(tok);
+ if (c == '"' || c == '\'')
+ goto letter_quote;
+ break;
+ case 'u':
+ case 'U':
+ c = tok_nextc(tok);
+ if (c == 'r' || c == 'R')
+ c = tok_nextc(tok);
+ if (c == '"' || c == '\'')
+ goto letter_quote;
+ break;
+ }
+ while (Py_ISALNUM(c) || c == '_') {
+ c = tok_nextc(tok);
+ }
+ tok_backup(tok, c);
+ *p_start = tok->start;
+ *p_end = tok->cur;
+ return NAME;
+ }
+
+ /* Newline */
+ if (c == '\n') {
+ tok->atbol = 1;
+ if (blankline || tok->level > 0)
+ goto nextline;
+ *p_start = tok->start;
+ *p_end = tok->cur - 1; /* Leave '\n' out of the string */
+ tok->cont_line = 0;
+ return NEWLINE;
+ }
+
+ /* Period or number starting with period? */
+ if (c == '.') {
+ c = tok_nextc(tok);
+ if (isdigit(c)) {
+ goto fraction;
+ }
+ else {
+ tok_backup(tok, c);
+ *p_start = tok->start;
+ *p_end = tok->cur;
+ return DOT;
+ }
+ }
+
+ /* Number */
+ if (isdigit(c)) {
+ if (c == '0') {
+ /* Hex, octal or binary -- maybe. */
+ c = tok_nextc(tok);
+ if (c == '.')
+ goto fraction;
#ifndef WITHOUT_COMPLEX
- if (c == 'j' || c == 'J')
- goto imaginary;
+ if (c == 'j' || c == 'J')
+ goto imaginary;
#endif
- if (c == 'x' || c == 'X') {
-
- /* Hex */
- c = tok_nextc(tok);
- if (!isxdigit(c)) {
- tok->done = E_TOKEN;
- tok_backup(tok, c);
- return ERRORTOKEN;
- }
- do {
- c = tok_nextc(tok);
- } while (isxdigit(c));
- }
- else if (c == 'o' || c == 'O') {
- /* Octal */
- c = tok_nextc(tok);
- if (c < '0' || c >= '8') {
- tok->done = E_TOKEN;
- tok_backup(tok, c);
- return ERRORTOKEN;
- }
- do {
- c = tok_nextc(tok);
- } while ('0' <= c && c < '8');
- }
- else if (c == 'b' || c == 'B') {
- /* Binary */
- c = tok_nextc(tok);
- if (c != '0' && c != '1') {
- tok->done = E_TOKEN;
- tok_backup(tok, c);
- return ERRORTOKEN;
- }
- do {
- c = tok_nextc(tok);
- } while (c == '0' || c == '1');
- }
- else {
- int found_decimal = 0;
- /* Octal; c is first char of it */
- /* There's no 'isoctdigit' macro, sigh */
- while ('0' <= c && c < '8') {
- c = tok_nextc(tok);
- }
- if (isdigit(c)) {
- found_decimal = 1;
- do {
- c = tok_nextc(tok);
- } while (isdigit(c));
- }
- if (c == '.')
- goto fraction;
- else if (c == 'e' || c == 'E')
- goto exponent;
+ if (c == 'x' || c == 'X') {
+
+ /* Hex */
+ c = tok_nextc(tok);
+ if (!isxdigit(c)) {
+ tok->done = E_TOKEN;
+ tok_backup(tok, c);
+ return ERRORTOKEN;
+ }
+ do {
+ c = tok_nextc(tok);
+ } while (isxdigit(c));
+ }
+ else if (c == 'o' || c == 'O') {
+ /* Octal */
+ c = tok_nextc(tok);
+ if (c < '0' || c >= '8') {
+ tok->done = E_TOKEN;
+ tok_backup(tok, c);
+ return ERRORTOKEN;
+ }
+ do {
+ c = tok_nextc(tok);
+ } while ('0' <= c && c < '8');
+ }
+ else if (c == 'b' || c == 'B') {
+ /* Binary */
+ c = tok_nextc(tok);
+ if (c != '0' && c != '1') {
+ tok->done = E_TOKEN;
+ tok_backup(tok, c);
+ return ERRORTOKEN;
+ }
+ do {
+ c = tok_nextc(tok);
+ } while (c == '0' || c == '1');
+ }
+ else {
+ int found_decimal = 0;
+ /* Octal; c is first char of it */
+ /* There's no 'isoctdigit' macro, sigh */
+ while ('0' <= c && c < '8') {
+ c = tok_nextc(tok);
+ }
+ if (isdigit(c)) {
+ found_decimal = 1;
+ do {
+ c = tok_nextc(tok);
+ } while (isdigit(c));
+ }
+ if (c == '.')
+ goto fraction;
+ else if (c == 'e' || c == 'E')
+ goto exponent;
#ifndef WITHOUT_COMPLEX
- else if (c == 'j' || c == 'J')
- goto imaginary;
+ else if (c == 'j' || c == 'J')
+ goto imaginary;
#endif
- else if (found_decimal) {
- tok->done = E_TOKEN;
- tok_backup(tok, c);
- return ERRORTOKEN;
- }
- }
- if (c == 'l' || c == 'L')
- c = tok_nextc(tok);
- }
- else {
- /* Decimal */
- do {
- c = tok_nextc(tok);
- } while (isdigit(c));
- if (c == 'l' || c == 'L')
- c = tok_nextc(tok);
- else {
- /* Accept floating point numbers. */
- if (c == '.') {
- fraction:
- /* Fraction */
- do {
- c = tok_nextc(tok);
- } while (isdigit(c));
- }
- if (c == 'e' || c == 'E') {
- exponent:
- /* Exponent part */
- c = tok_nextc(tok);
- if (c == '+' || c == '-')
- c = tok_nextc(tok);
- if (!isdigit(c)) {
- tok->done = E_TOKEN;
- tok_backup(tok, c);
- return ERRORTOKEN;
- }
- do {
- c = tok_nextc(tok);
- } while (isdigit(c));
- }
+ else if (found_decimal) {
+ tok->done = E_TOKEN;
+ tok_backup(tok, c);
+ return ERRORTOKEN;
+ }
+ }
+ if (c == 'l' || c == 'L')
+ c = tok_nextc(tok);
+ }
+ else {
+ /* Decimal */
+ do {
+ c = tok_nextc(tok);
+ } while (isdigit(c));
+ if (c == 'l' || c == 'L')
+ c = tok_nextc(tok);
+ else {
+ /* Accept floating point numbers. */
+ if (c == '.') {
+ fraction:
+ /* Fraction */
+ do {
+ c = tok_nextc(tok);
+ } while (isdigit(c));
+ }
+ if (c == 'e' || c == 'E') {
+ exponent:
+ /* Exponent part */
+ c = tok_nextc(tok);
+ if (c == '+' || c == '-')
+ c = tok_nextc(tok);
+ if (!isdigit(c)) {
+ tok->done = E_TOKEN;
+ tok_backup(tok, c);
+ return ERRORTOKEN;
+ }
+ do {
+ c = tok_nextc(tok);
+ } while (isdigit(c));
+ }
#ifndef WITHOUT_COMPLEX
- if (c == 'j' || c == 'J')
- /* Imaginary part */
- imaginary:
- c = tok_nextc(tok);
+ if (c == 'j' || c == 'J')
+ /* Imaginary part */
+ imaginary:
+ c = tok_nextc(tok);
#endif
- }
- }
- tok_backup(tok, c);
- *p_start = tok->start;
- *p_end = tok->cur;
- return NUMBER;
- }
+ }
+ }
+ tok_backup(tok, c);
+ *p_start = tok->start;
+ *p_end = tok->cur;
+ return NUMBER;
+ }
letter_quote:
- /* String */
- if (c == '\'' || c == '"') {
- Py_ssize_t quote2 = tok->cur - tok->start + 1;
- int quote = c;
- int triple = 0;
- int tripcount = 0;
- for (;;) {
- c = tok_nextc(tok);
- if (c == '\n') {
- if (!triple) {
- tok->done = E_EOLS;
- tok_backup(tok, c);
- return ERRORTOKEN;
- }
- tripcount = 0;
- tok->cont_line = 1; /* multiline string. */
- }
- else if (c == EOF) {
- if (triple)
- tok->done = E_EOFS;
- else
- tok->done = E_EOLS;
- tok->cur = tok->inp;
- return ERRORTOKEN;
- }
- else if (c == quote) {
- tripcount++;
- if (tok->cur - tok->start == quote2) {
- c = tok_nextc(tok);
- if (c == quote) {
- triple = 1;
- tripcount = 0;
- continue;
- }
- tok_backup(tok, c);
- }
- if (!triple || tripcount == 3)
- break;
- }
- else if (c == '\\') {
- tripcount = 0;
- c = tok_nextc(tok);
- if (c == EOF) {
- tok->done = E_EOLS;
- tok->cur = tok->inp;
- return ERRORTOKEN;
- }
- }
- else
- tripcount = 0;
- }
- *p_start = tok->start;
- *p_end = tok->cur;
- return STRING;
- }
-
- /* Line continuation */
- if (c == '\\') {
- c = tok_nextc(tok);
- if (c != '\n') {
- tok->done = E_LINECONT;
- tok->cur = tok->inp;
- return ERRORTOKEN;
- }
- tok->cont_line = 1;
- goto again; /* Read next line */
- }
-
- /* Check for two-character token */
- {
- int c2 = tok_nextc(tok);
- int token = PyToken_TwoChars(c, c2);
+ /* String */
+ if (c == '\'' || c == '"') {
+ Py_ssize_t quote2 = tok->cur - tok->start + 1;
+ int quote = c;
+ int triple = 0;
+ int tripcount = 0;
+ for (;;) {
+ c = tok_nextc(tok);
+ if (c == '\n') {
+ if (!triple) {
+ tok->done = E_EOLS;
+ tok_backup(tok, c);
+ return ERRORTOKEN;
+ }
+ tripcount = 0;
+ tok->cont_line = 1; /* multiline string. */
+ }
+ else if (c == EOF) {
+ if (triple)
+ tok->done = E_EOFS;
+ else
+ tok->done = E_EOLS;
+ tok->cur = tok->inp;
+ return ERRORTOKEN;
+ }
+ else if (c == quote) {
+ tripcount++;
+ if (tok->cur - tok->start == quote2) {
+ c = tok_nextc(tok);
+ if (c == quote) {
+ triple = 1;
+ tripcount = 0;
+ continue;
+ }
+ tok_backup(tok, c);
+ }
+ if (!triple || tripcount == 3)
+ break;
+ }
+ else if (c == '\\') {
+ tripcount = 0;
+ c = tok_nextc(tok);
+ if (c == EOF) {
+ tok->done = E_EOLS;
+ tok->cur = tok->inp;
+ return ERRORTOKEN;
+ }
+ }
+ else
+ tripcount = 0;
+ }
+ *p_start = tok->start;
+ *p_end = tok->cur;
+ return STRING;
+ }
+
+ /* Line continuation */
+ if (c == '\\') {
+ c = tok_nextc(tok);
+ if (c != '\n') {
+ tok->done = E_LINECONT;
+ tok->cur = tok->inp;
+ return ERRORTOKEN;
+ }
+ tok->cont_line = 1;
+ goto again; /* Read next line */
+ }
+
+ /* Check for two-character token */
+ {
+ int c2 = tok_nextc(tok);
+ int token = PyToken_TwoChars(c, c2);
#ifndef PGEN
- if (Py_Py3kWarningFlag && token == NOTEQUAL && c == '<') {
- if (PyErr_WarnExplicit(PyExc_DeprecationWarning,
- "<> not supported in 3.x; use !=",
- tok->filename, tok->lineno,
- NULL, NULL)) {
- return ERRORTOKEN;
- }
- }
+ if (Py_Py3kWarningFlag && token == NOTEQUAL && c == '<') {
+ if (PyErr_WarnExplicit(PyExc_DeprecationWarning,
+ "<> not supported in 3.x; use !=",
+ tok->filename, tok->lineno,
+ NULL, NULL)) {
+ return ERRORTOKEN;
+ }
+ }
#endif
- if (token != OP) {
- int c3 = tok_nextc(tok);
- int token3 = PyToken_ThreeChars(c, c2, c3);
- if (token3 != OP) {
- token = token3;
- } else {
- tok_backup(tok, c3);
- }
- *p_start = tok->start;
- *p_end = tok->cur;
- return token;
- }
- tok_backup(tok, c2);
- }
-
- /* Keep track of parentheses nesting level */
- switch (c) {
- case '(':
- case '[':
- case '{':
- tok->level++;
- break;
- case ')':
- case ']':
- case '}':
- tok->level--;
- break;
- }
-
- /* Punctuation character */
- *p_start = tok->start;
- *p_end = tok->cur;
- return PyToken_OneChar(c);
+ if (token != OP) {
+ int c3 = tok_nextc(tok);
+ int token3 = PyToken_ThreeChars(c, c2, c3);
+ if (token3 != OP) {
+ token = token3;
+ } else {
+ tok_backup(tok, c3);
+ }
+ *p_start = tok->start;
+ *p_end = tok->cur;
+ return token;
+ }
+ tok_backup(tok, c2);
+ }
+
+ /* Keep track of parentheses nesting level */
+ switch (c) {
+ case '(':
+ case '[':
+ case '{':
+ tok->level++;
+ break;
+ case ')':
+ case ']':
+ case '}':
+ tok->level--;
+ break;
+ }
+
+ /* Punctuation character */
+ *p_start = tok->start;
+ *p_end = tok->cur;
+ return PyToken_OneChar(c);
}
int
PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end)
{
- int result = tok_get(tok, p_start, p_end);
- if (tok->decoding_erred) {
- result = ERRORTOKEN;
- tok->done = E_DECODE;
- }
- return result;
+ int result = tok_get(tok, p_start, p_end);
+ if (tok->decoding_erred) {
+ result = ERRORTOKEN;
+ tok->done = E_DECODE;
+ }
+ return result;
}
/* This function is only called from parsetok. However, it cannot live
@@ -1659,54 +1659,54 @@ PyTokenizer_Get(struct tok_state *tok, char **p_start, char **p_end)
char*
PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int* offset)
{
- return NULL;
+ return NULL;
}
#else
#ifdef Py_USING_UNICODE
static PyObject *
dec_utf8(const char *enc, const char *text, size_t len) {
- PyObject *ret = NULL;
- PyObject *unicode_text = PyUnicode_DecodeUTF8(text, len, "replace");
- if (unicode_text) {
- ret = PyUnicode_AsEncodedString(unicode_text, enc, "replace");
- Py_DECREF(unicode_text);
- }
- if (!ret) {
- PyErr_Clear();
- }
- return ret;
+ PyObject *ret = NULL;
+ PyObject *unicode_text = PyUnicode_DecodeUTF8(text, len, "replace");
+ if (unicode_text) {
+ ret = PyUnicode_AsEncodedString(unicode_text, enc, "replace");
+ Py_DECREF(unicode_text);
+ }
+ if (!ret) {
+ PyErr_Clear();
+ }
+ return ret;
}
char *
PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int *offset)
{
- char *text = NULL;
- if (tok->encoding) {
- /* convert source to original encondig */
- PyObject *lineobj = dec_utf8(tok->encoding, tok->buf, len);
- if (lineobj != NULL) {
- int linelen = PyString_Size(lineobj);
- const char *line = PyString_AsString(lineobj);
- text = PyObject_MALLOC(linelen + 1);
- if (text != NULL && line != NULL) {
- if (linelen)
- strncpy(text, line, linelen);
- text[linelen] = '\0';
- }
- Py_DECREF(lineobj);
-
- /* adjust error offset */
- if (*offset > 1) {
- PyObject *offsetobj = dec_utf8(tok->encoding,
- tok->buf, *offset-1);
- if (offsetobj) {
- *offset = PyString_Size(offsetobj) + 1;
- Py_DECREF(offsetobj);
- }
- }
-
- }
- }
- return text;
+ char *text = NULL;
+ if (tok->encoding) {
+ /* convert source to original encondig */
+ PyObject *lineobj = dec_utf8(tok->encoding, tok->buf, len);
+ if (lineobj != NULL) {
+ int linelen = PyString_Size(lineobj);
+ const char *line = PyString_AsString(lineobj);
+ text = PyObject_MALLOC(linelen + 1);
+ if (text != NULL && line != NULL) {
+ if (linelen)
+ strncpy(text, line, linelen);
+ text[linelen] = '\0';
+ }
+ Py_DECREF(lineobj);
+
+ /* adjust error offset */
+ if (*offset > 1) {
+ PyObject *offsetobj = dec_utf8(tok->encoding,
+ tok->buf, *offset-1);
+ if (offsetobj) {
+ *offset = PyString_Size(offsetobj) + 1;
+ Py_DECREF(offsetobj);
+ }
+ }
+
+ }
+ }
+ return text;
}
#endif /* defined(Py_USING_UNICODE) */
@@ -1718,9 +1718,9 @@ PyTokenizer_RestoreEncoding(struct tok_state* tok, int len, int *offset)
void
tok_dump(int type, char *start, char *end)
{
- printf("%s", _PyParser_TokenNames[type]);
- if (type == NAME || type == NUMBER || type == STRING || type == OP)
- printf("(%.*s)", (int)(end - start), start);
+ printf("%s", _PyParser_TokenNames[type]);
+ if (type == NAME || type == NUMBER || type == STRING || type == OP)
+ printf("(%.*s)", (int)(end - start), start);
}
#endif
diff --git a/Parser/tokenizer.h b/Parser/tokenizer.h
index 79c9e28..f15e252 100644
--- a/Parser/tokenizer.h
+++ b/Parser/tokenizer.h
@@ -8,51 +8,51 @@ extern "C" {
/* Tokenizer interface */
-#include "token.h" /* For token types */
+#include "token.h" /* For token types */
-#define MAXINDENT 100 /* Max indentation level */
+#define MAXINDENT 100 /* Max indentation level */
/* Tokenizer state */
struct tok_state {
- /* Input state; buf <= cur <= inp <= end */
- /* NB an entire line is held in the buffer */
- char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */
- char *cur; /* Next character in buffer */
- char *inp; /* End of data in buffer */
- char *end; /* End of input buffer if buf != NULL */
- char *start; /* Start of current token if not NULL */
- int done; /* E_OK normally, E_EOF at EOF, otherwise error code */
- /* NB If done != E_OK, cur must be == inp!!! */
- FILE *fp; /* Rest of input; NULL if tokenizing a string */
- int tabsize; /* Tab spacing */
- int indent; /* Current indentation index */
- int indstack[MAXINDENT]; /* Stack of indents */
- int atbol; /* Nonzero if at begin of new line */
- int pendin; /* Pending indents (if > 0) or dedents (if < 0) */
- char *prompt, *nextprompt; /* For interactive prompting */
- int lineno; /* Current line number */
- int level; /* () [] {} Parentheses nesting level */
- /* Used to allow free continuations inside them */
- /* Stuff for checking on different tab sizes */
- const char *filename; /* For error messages */
- int altwarning; /* Issue warning if alternate tabs don't match */
- int alterror; /* Issue error if alternate tabs don't match */
- int alttabsize; /* Alternate tab spacing */
- int altindstack[MAXINDENT]; /* Stack of alternate indents */
- /* Stuff for PEP 0263 */
- int decoding_state; /* -1:decoding, 0:init, 1:raw */
- int decoding_erred; /* whether erred in decoding */
- int read_coding_spec; /* whether 'coding:...' has been read */
- char *encoding;
- int cont_line; /* whether we are in a continuation line. */
- const char* line_start; /* pointer to start of current line */
+ /* Input state; buf <= cur <= inp <= end */
+ /* NB an entire line is held in the buffer */
+ char *buf; /* Input buffer, or NULL; malloc'ed if fp != NULL */
+ char *cur; /* Next character in buffer */
+ char *inp; /* End of data in buffer */
+ char *end; /* End of input buffer if buf != NULL */
+ char *start; /* Start of current token if not NULL */
+ int done; /* E_OK normally, E_EOF at EOF, otherwise error code */
+ /* NB If done != E_OK, cur must be == inp!!! */
+ FILE *fp; /* Rest of input; NULL if tokenizing a string */
+ int tabsize; /* Tab spacing */
+ int indent; /* Current indentation index */
+ int indstack[MAXINDENT]; /* Stack of indents */
+ int atbol; /* Nonzero if at begin of new line */
+ int pendin; /* Pending indents (if > 0) or dedents (if < 0) */
+ char *prompt, *nextprompt; /* For interactive prompting */
+ int lineno; /* Current line number */
+ int level; /* () [] {} Parentheses nesting level */
+ /* Used to allow free continuations inside them */
+ /* Stuff for checking on different tab sizes */
+ const char *filename; /* For error messages */
+ int altwarning; /* Issue warning if alternate tabs don't match */
+ int alterror; /* Issue error if alternate tabs don't match */
+ int alttabsize; /* Alternate tab spacing */
+ int altindstack[MAXINDENT]; /* Stack of alternate indents */
+ /* Stuff for PEP 0263 */
+ int decoding_state; /* -1:decoding, 0:init, 1:raw */
+ int decoding_erred; /* whether erred in decoding */
+ int read_coding_spec; /* whether 'coding:...' has been read */
+ char *encoding;
+ int cont_line; /* whether we are in a continuation line. */
+ const char* line_start; /* pointer to start of current line */
#ifndef PGEN
- PyObject *decoding_readline; /* codecs.open(...).readline */
- PyObject *decoding_buffer;
+ PyObject *decoding_readline; /* codecs.open(...).readline */
+ PyObject *decoding_buffer;
#endif
- const char* enc;
- const char* str;
- const char* input; /* Tokenizer's newline translated copy of the string. */
+ const char* enc;
+ const char* str;
+ const char* input; /* Tokenizer's newline translated copy of the string. */
};
extern struct tok_state *PyTokenizer_FromString(const char *, int);
@@ -60,8 +60,8 @@ extern struct tok_state *PyTokenizer_FromFile(FILE *, char *, char *);
extern void PyTokenizer_Free(struct tok_state *);
extern int PyTokenizer_Get(struct tok_state *, char **, char **);
#if defined(PGEN) || defined(Py_USING_UNICODE)
-extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok,
- int len, int *offset);
+extern char * PyTokenizer_RestoreEncoding(struct tok_state* tok,
+ int len, int *offset);
#endif
#ifdef __cplusplus
diff --git a/Python/asdl.c b/Python/asdl.c
index 1105d3a..c30d7d20 100644
--- a/Python/asdl.c
+++ b/Python/asdl.c
@@ -4,61 +4,61 @@
asdl_seq *
asdl_seq_new(int size, PyArena *arena)
{
- asdl_seq *seq = NULL;
- size_t n = (size ? (sizeof(void *) * (size - 1)) : 0);
+ asdl_seq *seq = NULL;
+ size_t n = (size ? (sizeof(void *) * (size - 1)) : 0);
- /* check size is sane */
- if (size < 0 || size == INT_MIN ||
- (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) {
- PyErr_NoMemory();
- return NULL;
- }
+ /* check size is sane */
+ if (size < 0 || size == INT_MIN ||
+ (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- /* check if size can be added safely */
- if (n > PY_SIZE_MAX - sizeof(asdl_seq)) {
- PyErr_NoMemory();
- return NULL;
- }
+ /* check if size can be added safely */
+ if (n > PY_SIZE_MAX - sizeof(asdl_seq)) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- n += sizeof(asdl_seq);
+ n += sizeof(asdl_seq);
- seq = (asdl_seq *)PyArena_Malloc(arena, n);
- if (!seq) {
- PyErr_NoMemory();
- return NULL;
- }
- memset(seq, 0, n);
- seq->size = size;
- return seq;
+ seq = (asdl_seq *)PyArena_Malloc(arena, n);
+ if (!seq) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(seq, 0, n);
+ seq->size = size;
+ return seq;
}
asdl_int_seq *
asdl_int_seq_new(int size, PyArena *arena)
{
- asdl_int_seq *seq = NULL;
- size_t n = (size ? (sizeof(void *) * (size - 1)) : 0);
+ asdl_int_seq *seq = NULL;
+ size_t n = (size ? (sizeof(void *) * (size - 1)) : 0);
- /* check size is sane */
- if (size < 0 || size == INT_MIN ||
- (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) {
- PyErr_NoMemory();
- return NULL;
- }
+ /* check size is sane */
+ if (size < 0 || size == INT_MIN ||
+ (size && ((size - 1) > (PY_SIZE_MAX / sizeof(void *))))) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- /* check if size can be added safely */
- if (n > PY_SIZE_MAX - sizeof(asdl_seq)) {
- PyErr_NoMemory();
- return NULL;
- }
+ /* check if size can be added safely */
+ if (n > PY_SIZE_MAX - sizeof(asdl_seq)) {
+ PyErr_NoMemory();
+ return NULL;
+ }
- n += sizeof(asdl_seq);
+ n += sizeof(asdl_seq);
- seq = (asdl_int_seq *)PyArena_Malloc(arena, n);
- if (!seq) {
- PyErr_NoMemory();
- return NULL;
- }
- memset(seq, 0, n);
- seq->size = size;
- return seq;
+ seq = (asdl_int_seq *)PyArena_Malloc(arena, n);
+ if (!seq) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(seq, 0, n);
+ seq->size = size;
+ return seq;
}
diff --git a/Python/atof.c b/Python/atof.c
index 8fbde38..562fcd6 100644
--- a/Python/atof.c
+++ b/Python/atof.c
@@ -10,41 +10,41 @@
double atof(char *s)
{
- double a = 0.0;
- int e = 0;
- int c;
- while ((c = *s++) != '\0' && isdigit(c)) {
- a = a*10.0 + (c - '0');
- }
- if (c == '.') {
- while ((c = *s++) != '\0' && isdigit(c)) {
- a = a*10.0 + (c - '0');
- e = e-1;
- }
- }
- if (c == 'e' || c == 'E') {
- int sign = 1;
- int i = 0;
- c = *s++;
- if (c == '+')
- c = *s++;
- else if (c == '-') {
- c = *s++;
- sign = -1;
- }
- while (isdigit(c)) {
- i = i*10 + (c - '0');
- c = *s++;
- }
- e += i*sign;
- }
- while (e > 0) {
- a *= 10.0;
- e--;
- }
- while (e < 0) {
- a *= 0.1;
- e++;
- }
- return a;
+ double a = 0.0;
+ int e = 0;
+ int c;
+ while ((c = *s++) != '\0' && isdigit(c)) {
+ a = a*10.0 + (c - '0');
+ }
+ if (c == '.') {
+ while ((c = *s++) != '\0' && isdigit(c)) {
+ a = a*10.0 + (c - '0');
+ e = e-1;
+ }
+ }
+ if (c == 'e' || c == 'E') {
+ int sign = 1;
+ int i = 0;
+ c = *s++;
+ if (c == '+')
+ c = *s++;
+ else if (c == '-') {
+ c = *s++;
+ sign = -1;
+ }
+ while (isdigit(c)) {
+ i = i*10 + (c - '0');
+ c = *s++;
+ }
+ e += i*sign;
+ }
+ while (e > 0) {
+ a *= 10.0;
+ e--;
+ }
+ while (e < 0) {
+ a *= 0.1;
+ e++;
+ }
+ return a;
}
diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c
index 40441d2..764ae87 100644
--- a/Python/bltinmodule.c
+++ b/Python/bltinmodule.c
@@ -35,19 +35,19 @@ static PyObject *filtertuple (PyObject *, PyObject *);
static PyObject *
builtin___import__(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"name", "globals", "locals", "fromlist",
- "level", 0};
- char *name;
- PyObject *globals = NULL;
- PyObject *locals = NULL;
- PyObject *fromlist = NULL;
- int level = -1;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
- kwlist, &name, &globals, &locals, &fromlist, &level))
- return NULL;
- return PyImport_ImportModuleLevel(name, globals, locals,
- fromlist, level);
+ static char *kwlist[] = {"name", "globals", "locals", "fromlist",
+ "level", 0};
+ char *name;
+ PyObject *globals = NULL;
+ PyObject *locals = NULL;
+ PyObject *fromlist = NULL;
+ int level = -1;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "s|OOOi:__import__",
+ kwlist, &name, &globals, &locals, &fromlist, &level))
+ return NULL;
+ return PyImport_ImportModuleLevel(name, globals, locals,
+ fromlist, level);
}
PyDoc_STRVAR(import_doc,
@@ -68,7 +68,7 @@ is the number of parent directories to search relative to the current module.");
static PyObject *
builtin_abs(PyObject *self, PyObject *v)
{
- return PyNumber_Absolute(v);
+ return PyNumber_Absolute(v);
}
PyDoc_STRVAR(abs_doc,
@@ -79,38 +79,38 @@ Return the absolute value of the argument.");
static PyObject *
builtin_all(PyObject *self, PyObject *v)
{
- PyObject *it, *item;
- PyObject *(*iternext)(PyObject *);
- int cmp;
-
- it = PyObject_GetIter(v);
- if (it == NULL)
- return NULL;
- iternext = *Py_TYPE(it)->tp_iternext;
-
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- break;
- cmp = PyObject_IsTrue(item);
- Py_DECREF(item);
- if (cmp < 0) {
- Py_DECREF(it);
- return NULL;
- }
- if (cmp == 0) {
- Py_DECREF(it);
- Py_RETURN_FALSE;
- }
- }
- Py_DECREF(it);
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- return NULL;
- }
- Py_RETURN_TRUE;
+ PyObject *it, *item;
+ PyObject *(*iternext)(PyObject *);
+ int cmp;
+
+ it = PyObject_GetIter(v);
+ if (it == NULL)
+ return NULL;
+ iternext = *Py_TYPE(it)->tp_iternext;
+
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ break;
+ cmp = PyObject_IsTrue(item);
+ Py_DECREF(item);
+ if (cmp < 0) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ if (cmp == 0) {
+ Py_DECREF(it);
+ Py_RETURN_FALSE;
+ }
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ Py_RETURN_TRUE;
}
PyDoc_STRVAR(all_doc,
@@ -121,38 +121,38 @@ Return True if bool(x) is True for all values x in the iterable.");
static PyObject *
builtin_any(PyObject *self, PyObject *v)
{
- PyObject *it, *item;
- PyObject *(*iternext)(PyObject *);
- int cmp;
-
- it = PyObject_GetIter(v);
- if (it == NULL)
- return NULL;
- iternext = *Py_TYPE(it)->tp_iternext;
-
- for (;;) {
- item = iternext(it);
- if (item == NULL)
- break;
- cmp = PyObject_IsTrue(item);
- Py_DECREF(item);
- if (cmp < 0) {
- Py_DECREF(it);
- return NULL;
- }
- if (cmp == 1) {
- Py_DECREF(it);
- Py_RETURN_TRUE;
- }
- }
- Py_DECREF(it);
- if (PyErr_Occurred()) {
- if (PyErr_ExceptionMatches(PyExc_StopIteration))
- PyErr_Clear();
- else
- return NULL;
- }
- Py_RETURN_FALSE;
+ PyObject *it, *item;
+ PyObject *(*iternext)(PyObject *);
+ int cmp;
+
+ it = PyObject_GetIter(v);
+ if (it == NULL)
+ return NULL;
+ iternext = *Py_TYPE(it)->tp_iternext;
+
+ for (;;) {
+ item = iternext(it);
+ if (item == NULL)
+ break;
+ cmp = PyObject_IsTrue(item);
+ Py_DECREF(item);
+ if (cmp < 0) {
+ Py_DECREF(it);
+ return NULL;
+ }
+ if (cmp == 1) {
+ Py_DECREF(it);
+ Py_RETURN_TRUE;
+ }
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred()) {
+ if (PyErr_ExceptionMatches(PyExc_StopIteration))
+ PyErr_Clear();
+ else
+ return NULL;
+ }
+ Py_RETURN_FALSE;
}
PyDoc_STRVAR(any_doc,
@@ -163,39 +163,39 @@ Return True if bool(x) is True for any x in the iterable.");
static PyObject *
builtin_apply(PyObject *self, PyObject *args)
{
- PyObject *func, *alist = NULL, *kwdict = NULL;
- PyObject *t = NULL, *retval = NULL;
-
- if (PyErr_WarnPy3k("apply() not supported in 3.x; "
- "use func(*args, **kwargs)", 1) < 0)
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
- return NULL;
- if (alist != NULL) {
- if (!PyTuple_Check(alist)) {
- if (!PySequence_Check(alist)) {
- PyErr_Format(PyExc_TypeError,
- "apply() arg 2 expected sequence, found %s",
- alist->ob_type->tp_name);
- return NULL;
- }
- t = PySequence_Tuple(alist);
- if (t == NULL)
- return NULL;
- alist = t;
- }
- }
- if (kwdict != NULL && !PyDict_Check(kwdict)) {
- PyErr_Format(PyExc_TypeError,
- "apply() arg 3 expected dictionary, found %s",
- kwdict->ob_type->tp_name);
- goto finally;
- }
- retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
+ PyObject *func, *alist = NULL, *kwdict = NULL;
+ PyObject *t = NULL, *retval = NULL;
+
+ if (PyErr_WarnPy3k("apply() not supported in 3.x; "
+ "use func(*args, **kwargs)", 1) < 0)
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "apply", 1, 3, &func, &alist, &kwdict))
+ return NULL;
+ if (alist != NULL) {
+ if (!PyTuple_Check(alist)) {
+ if (!PySequence_Check(alist)) {
+ PyErr_Format(PyExc_TypeError,
+ "apply() arg 2 expected sequence, found %s",
+ alist->ob_type->tp_name);
+ return NULL;
+ }
+ t = PySequence_Tuple(alist);
+ if (t == NULL)
+ return NULL;
+ alist = t;
+ }
+ }
+ if (kwdict != NULL && !PyDict_Check(kwdict)) {
+ PyErr_Format(PyExc_TypeError,
+ "apply() arg 3 expected dictionary, found %s",
+ kwdict->ob_type->tp_name);
+ goto finally;
+ }
+ retval = PyEval_CallObjectWithKeywords(func, alist, kwdict);
finally:
- Py_XDECREF(t);
- return retval;
+ Py_XDECREF(t);
+ return retval;
}
PyDoc_STRVAR(apply_doc,
@@ -212,7 +212,7 @@ Deprecated since release 2.3. Instead, use the extended call syntax:\n\
static PyObject *
builtin_bin(PyObject *self, PyObject *v)
{
- return PyNumber_ToBase(v, 2);
+ return PyNumber_ToBase(v, 2);
}
PyDoc_STRVAR(bin_doc,
@@ -224,10 +224,10 @@ Return the binary representation of an integer or long integer.");
static PyObject *
builtin_callable(PyObject *self, PyObject *v)
{
- if (PyErr_WarnPy3k("callable() not supported in 3.x; "
- "use isinstance(x, collections.Callable)", 1) < 0)
- return NULL;
- return PyBool_FromLong((long)PyCallable_Check(v));
+ if (PyErr_WarnPy3k("callable() not supported in 3.x; "
+ "use isinstance(x, collections.Callable)", 1) < 0)
+ return NULL;
+ return PyBool_FromLong((long)PyCallable_Check(v));
}
PyDoc_STRVAR(callable_doc,
@@ -240,109 +240,109 @@ Note that classes are callable, as are instances with a __call__() method.");
static PyObject *
builtin_filter(PyObject *self, PyObject *args)
{
- PyObject *func, *seq, *result, *it, *arg;
- Py_ssize_t len; /* guess for result list size */
- register Py_ssize_t j;
+ PyObject *func, *seq, *result, *it, *arg;
+ Py_ssize_t len; /* guess for result list size */
+ register Py_ssize_t j;
- if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "filter", 2, 2, &func, &seq))
+ return NULL;
- /* Strings and tuples return a result of the same type. */
- if (PyString_Check(seq))
- return filterstring(func, seq);
+ /* Strings and tuples return a result of the same type. */
+ if (PyString_Check(seq))
+ return filterstring(func, seq);
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(seq))
- return filterunicode(func, seq);
+ if (PyUnicode_Check(seq))
+ return filterunicode(func, seq);
#endif
- if (PyTuple_Check(seq))
- return filtertuple(func, seq);
-
- /* Pre-allocate argument list tuple. */
- arg = PyTuple_New(1);
- if (arg == NULL)
- return NULL;
-
- /* Get iterator. */
- it = PyObject_GetIter(seq);
- if (it == NULL)
- goto Fail_arg;
-
- /* Guess a result list size. */
- len = _PyObject_LengthHint(seq, 8);
- if (len == -1)
- goto Fail_it;
-
- /* Get a result list. */
- if (PyList_Check(seq) && seq->ob_refcnt == 1) {
- /* Eww - can modify the list in-place. */
- Py_INCREF(seq);
- result = seq;
- }
- else {
- result = PyList_New(len);
- if (result == NULL)
- goto Fail_it;
- }
-
- /* Build the result list. */
- j = 0;
- for (;;) {
- PyObject *item;
- int ok;
-
- item = PyIter_Next(it);
- if (item == NULL) {
- if (PyErr_Occurred())
- goto Fail_result_it;
- break;
- }
-
- if (func == (PyObject *)&PyBool_Type || func == Py_None) {
- ok = PyObject_IsTrue(item);
- }
- else {
- PyObject *good;
- PyTuple_SET_ITEM(arg, 0, item);
- good = PyObject_Call(func, arg, NULL);
- PyTuple_SET_ITEM(arg, 0, NULL);
- if (good == NULL) {
- Py_DECREF(item);
- goto Fail_result_it;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- }
- if (ok) {
- if (j < len)
- PyList_SET_ITEM(result, j, item);
- else {
- int status = PyList_Append(result, item);
- Py_DECREF(item);
- if (status < 0)
- goto Fail_result_it;
- }
- ++j;
- }
- else
- Py_DECREF(item);
- }
-
-
- /* Cut back result list if len is too big. */
- if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
- goto Fail_result_it;
-
- Py_DECREF(it);
- Py_DECREF(arg);
- return result;
+ if (PyTuple_Check(seq))
+ return filtertuple(func, seq);
+
+ /* Pre-allocate argument list tuple. */
+ arg = PyTuple_New(1);
+ if (arg == NULL)
+ return NULL;
+
+ /* Get iterator. */
+ it = PyObject_GetIter(seq);
+ if (it == NULL)
+ goto Fail_arg;
+
+ /* Guess a result list size. */
+ len = _PyObject_LengthHint(seq, 8);
+ if (len == -1)
+ goto Fail_it;
+
+ /* Get a result list. */
+ if (PyList_Check(seq) && seq->ob_refcnt == 1) {
+ /* Eww - can modify the list in-place. */
+ Py_INCREF(seq);
+ result = seq;
+ }
+ else {
+ result = PyList_New(len);
+ if (result == NULL)
+ goto Fail_it;
+ }
+
+ /* Build the result list. */
+ j = 0;
+ for (;;) {
+ PyObject *item;
+ int ok;
+
+ item = PyIter_Next(it);
+ if (item == NULL) {
+ if (PyErr_Occurred())
+ goto Fail_result_it;
+ break;
+ }
+
+ if (func == (PyObject *)&PyBool_Type || func == Py_None) {
+ ok = PyObject_IsTrue(item);
+ }
+ else {
+ PyObject *good;
+ PyTuple_SET_ITEM(arg, 0, item);
+ good = PyObject_Call(func, arg, NULL);
+ PyTuple_SET_ITEM(arg, 0, NULL);
+ if (good == NULL) {
+ Py_DECREF(item);
+ goto Fail_result_it;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ }
+ if (ok) {
+ if (j < len)
+ PyList_SET_ITEM(result, j, item);
+ else {
+ int status = PyList_Append(result, item);
+ Py_DECREF(item);
+ if (status < 0)
+ goto Fail_result_it;
+ }
+ ++j;
+ }
+ else
+ Py_DECREF(item);
+ }
+
+
+ /* Cut back result list if len is too big. */
+ if (j < len && PyList_SetSlice(result, j, len, NULL) < 0)
+ goto Fail_result_it;
+
+ Py_DECREF(it);
+ Py_DECREF(arg);
+ return result;
Fail_result_it:
- Py_DECREF(result);
+ Py_DECREF(result);
Fail_it:
- Py_DECREF(it);
+ Py_DECREF(it);
Fail_arg:
- Py_DECREF(arg);
- return NULL;
+ Py_DECREF(arg);
+ return NULL;
}
PyDoc_STRVAR(filter_doc,
@@ -355,13 +355,13 @@ PyDoc_STRVAR(filter_doc,
static PyObject *
builtin_format(PyObject *self, PyObject *args)
{
- PyObject *value;
- PyObject *format_spec = NULL;
+ PyObject *value;
+ PyObject *format_spec = NULL;
- if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
- return NULL;
+ if (!PyArg_ParseTuple(args, "O|O:format", &value, &format_spec))
+ return NULL;
- return PyObject_Format(value, format_spec);
+ return PyObject_Format(value, format_spec);
}
PyDoc_STRVAR(format_doc,
@@ -373,18 +373,18 @@ format_spec defaults to \"\"");
static PyObject *
builtin_chr(PyObject *self, PyObject *args)
{
- long x;
- char s[1];
-
- if (!PyArg_ParseTuple(args, "l:chr", &x))
- return NULL;
- if (x < 0 || x >= 256) {
- PyErr_SetString(PyExc_ValueError,
- "chr() arg not in range(256)");
- return NULL;
- }
- s[0] = (char)x;
- return PyString_FromStringAndSize(s, 1);
+ long x;
+ char s[1];
+
+ if (!PyArg_ParseTuple(args, "l:chr", &x))
+ return NULL;
+ if (x < 0 || x >= 256) {
+ PyErr_SetString(PyExc_ValueError,
+ "chr() arg not in range(256)");
+ return NULL;
+ }
+ s[0] = (char)x;
+ return PyString_FromStringAndSize(s, 1);
}
PyDoc_STRVAR(chr_doc,
@@ -397,12 +397,12 @@ Return a string of one character with ordinal i; 0 <= i < 256.");
static PyObject *
builtin_unichr(PyObject *self, PyObject *args)
{
- int x;
+ int x;
- if (!PyArg_ParseTuple(args, "i:unichr", &x))
- return NULL;
+ if (!PyArg_ParseTuple(args, "i:unichr", &x))
+ return NULL;
- return PyUnicode_FromOrdinal(x);
+ return PyUnicode_FromOrdinal(x);
}
PyDoc_STRVAR(unichr_doc,
@@ -415,14 +415,14 @@ Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff.");
static PyObject *
builtin_cmp(PyObject *self, PyObject *args)
{
- PyObject *a, *b;
- int c;
-
- if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
- return NULL;
- if (PyObject_Cmp(a, b, &c) < 0)
- return NULL;
- return PyInt_FromLong((long)c);
+ PyObject *a, *b;
+ int c;
+
+ if (!PyArg_UnpackTuple(args, "cmp", 2, 2, &a, &b))
+ return NULL;
+ if (PyObject_Cmp(a, b, &c) < 0)
+ return NULL;
+ return PyInt_FromLong((long)c);
}
PyDoc_STRVAR(cmp_doc,
@@ -434,20 +434,20 @@ Return negative if x<y, zero if x==y, positive if x>y.");
static PyObject *
builtin_coerce(PyObject *self, PyObject *args)
{
- PyObject *v, *w;
- PyObject *res;
-
- if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
- return NULL;
- if (PyNumber_Coerce(&v, &w) < 0)
- return NULL;
- res = PyTuple_Pack(2, v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- return res;
+ PyObject *v, *w;
+ PyObject *res;
+
+ if (PyErr_WarnPy3k("coerce() not supported in 3.x", 1) < 0)
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "coerce", 2, 2, &v, &w))
+ return NULL;
+ if (PyNumber_Coerce(&v, &w) < 0)
+ return NULL;
+ res = PyTuple_Pack(2, v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ return res;
}
PyDoc_STRVAR(coerce_doc,
@@ -460,98 +460,98 @@ If coercion is not possible, raise TypeError.");
static PyObject *
builtin_compile(PyObject *self, PyObject *args, PyObject *kwds)
{
- char *str;
- char *filename;
- char *startstr;
- int mode = -1;
- int dont_inherit = 0;
- int supplied_flags = 0;
- int is_ast;
- PyCompilerFlags cf;
- PyObject *result = NULL, *cmd, *tmp = NULL;
- Py_ssize_t length;
- static char *kwlist[] = {"source", "filename", "mode", "flags",
- "dont_inherit", NULL};
- int start[] = {Py_file_input, Py_eval_input, Py_single_input};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
- kwlist, &cmd, &filename, &startstr,
- &supplied_flags, &dont_inherit))
- return NULL;
-
- cf.cf_flags = supplied_flags;
-
- if (supplied_flags &
- ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
- {
- PyErr_SetString(PyExc_ValueError,
- "compile(): unrecognised flags");
- return NULL;
- }
- /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
-
- if (!dont_inherit) {
- PyEval_MergeCompilerFlags(&cf);
- }
-
- if (strcmp(startstr, "exec") == 0)
- mode = 0;
- else if (strcmp(startstr, "eval") == 0)
- mode = 1;
- else if (strcmp(startstr, "single") == 0)
- mode = 2;
- else {
- PyErr_SetString(PyExc_ValueError,
- "compile() arg 3 must be 'exec', 'eval' or 'single'");
- return NULL;
- }
-
- is_ast = PyAST_Check(cmd);
- if (is_ast == -1)
- return NULL;
- if (is_ast) {
- if (supplied_flags & PyCF_ONLY_AST) {
- Py_INCREF(cmd);
- result = cmd;
- }
- else {
- PyArena *arena;
- mod_ty mod;
-
- arena = PyArena_New();
- mod = PyAST_obj2mod(cmd, arena, mode);
- if (mod == NULL) {
- PyArena_Free(arena);
- return NULL;
- }
- result = (PyObject*)PyAST_Compile(mod, filename,
- &cf, arena);
- PyArena_Free(arena);
- }
- return result;
- }
+ char *str;
+ char *filename;
+ char *startstr;
+ int mode = -1;
+ int dont_inherit = 0;
+ int supplied_flags = 0;
+ int is_ast;
+ PyCompilerFlags cf;
+ PyObject *result = NULL, *cmd, *tmp = NULL;
+ Py_ssize_t length;
+ static char *kwlist[] = {"source", "filename", "mode", "flags",
+ "dont_inherit", NULL};
+ int start[] = {Py_file_input, Py_eval_input, Py_single_input};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "Oss|ii:compile",
+ kwlist, &cmd, &filename, &startstr,
+ &supplied_flags, &dont_inherit))
+ return NULL;
+
+ cf.cf_flags = supplied_flags;
+
+ if (supplied_flags &
+ ~(PyCF_MASK | PyCF_MASK_OBSOLETE | PyCF_DONT_IMPLY_DEDENT | PyCF_ONLY_AST))
+ {
+ PyErr_SetString(PyExc_ValueError,
+ "compile(): unrecognised flags");
+ return NULL;
+ }
+ /* XXX Warn if (supplied_flags & PyCF_MASK_OBSOLETE) != 0? */
+
+ if (!dont_inherit) {
+ PyEval_MergeCompilerFlags(&cf);
+ }
+
+ if (strcmp(startstr, "exec") == 0)
+ mode = 0;
+ else if (strcmp(startstr, "eval") == 0)
+ mode = 1;
+ else if (strcmp(startstr, "single") == 0)
+ mode = 2;
+ else {
+ PyErr_SetString(PyExc_ValueError,
+ "compile() arg 3 must be 'exec', 'eval' or 'single'");
+ return NULL;
+ }
+
+ is_ast = PyAST_Check(cmd);
+ if (is_ast == -1)
+ return NULL;
+ if (is_ast) {
+ if (supplied_flags & PyCF_ONLY_AST) {
+ Py_INCREF(cmd);
+ result = cmd;
+ }
+ else {
+ PyArena *arena;
+ mod_ty mod;
+
+ arena = PyArena_New();
+ mod = PyAST_obj2mod(cmd, arena, mode);
+ if (mod == NULL) {
+ PyArena_Free(arena);
+ return NULL;
+ }
+ result = (PyObject*)PyAST_Compile(mod, filename,
+ &cf, arena);
+ PyArena_Free(arena);
+ }
+ return result;
+ }
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(cmd)) {
- tmp = PyUnicode_AsUTF8String(cmd);
- if (tmp == NULL)
- return NULL;
- cmd = tmp;
- cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
- }
+ if (PyUnicode_Check(cmd)) {
+ tmp = PyUnicode_AsUTF8String(cmd);
+ if (tmp == NULL)
+ return NULL;
+ cmd = tmp;
+ cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
+ }
#endif
- if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
- goto cleanup;
- if ((size_t)length != strlen(str)) {
- PyErr_SetString(PyExc_TypeError,
- "compile() expected string without null bytes");
- goto cleanup;
- }
- result = Py_CompileStringFlags(str, filename, start[mode], &cf);
+ if (PyObject_AsReadBuffer(cmd, (const void **)&str, &length))
+ goto cleanup;
+ if ((size_t)length != strlen(str)) {
+ PyErr_SetString(PyExc_TypeError,
+ "compile() expected string without null bytes");
+ goto cleanup;
+ }
+ result = Py_CompileStringFlags(str, filename, start[mode], &cf);
cleanup:
- Py_XDECREF(tmp);
- return result;
+ Py_XDECREF(tmp);
+ return result;
}
PyDoc_STRVAR(compile_doc,
@@ -572,11 +572,11 @@ in addition to any features explicitly specified.");
static PyObject *
builtin_dir(PyObject *self, PyObject *args)
{
- PyObject *arg = NULL;
+ PyObject *arg = NULL;
- if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
- return NULL;
- return PyObject_Dir(arg);
+ if (!PyArg_UnpackTuple(args, "dir", 0, 1, &arg))
+ return NULL;
+ return PyObject_Dir(arg);
}
PyDoc_STRVAR(dir_doc,
@@ -596,11 +596,11 @@ PyDoc_STRVAR(dir_doc,
static PyObject *
builtin_divmod(PyObject *self, PyObject *args)
{
- PyObject *v, *w;
+ PyObject *v, *w;
- if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
- return NULL;
- return PyNumber_Divmod(v, w);
+ if (!PyArg_UnpackTuple(args, "divmod", 2, 2, &v, &w))
+ return NULL;
+ return PyNumber_Divmod(v, w);
}
PyDoc_STRVAR(divmod_doc,
@@ -612,81 +612,81 @@ Return the tuple ((x-x%y)/y, x%y). Invariant: div*y + mod == x.");
static PyObject *
builtin_eval(PyObject *self, PyObject *args)
{
- PyObject *cmd, *result, *tmp = NULL;
- PyObject *globals = Py_None, *locals = Py_None;
- char *str;
- PyCompilerFlags cf;
-
- if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
- return NULL;
- if (locals != Py_None && !PyMapping_Check(locals)) {
- PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
- return NULL;
- }
- if (globals != Py_None && !PyDict_Check(globals)) {
- PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
- "globals must be a real dict; try eval(expr, {}, mapping)"
- : "globals must be a dict");
- return NULL;
- }
- if (globals == Py_None) {
- globals = PyEval_GetGlobals();
- if (locals == Py_None)
- locals = PyEval_GetLocals();
- }
- else if (locals == Py_None)
- locals = globals;
-
- if (globals == NULL || locals == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "eval must be given globals and locals "
- "when called without a frame");
- return NULL;
- }
-
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
- if (PyDict_SetItemString(globals, "__builtins__",
- PyEval_GetBuiltins()) != 0)
- return NULL;
- }
-
- if (PyCode_Check(cmd)) {
- if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
- PyErr_SetString(PyExc_TypeError,
- "code object passed to eval() may not contain free variables");
- return NULL;
- }
- return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
- }
-
- if (!PyString_Check(cmd) &&
- !PyUnicode_Check(cmd)) {
- PyErr_SetString(PyExc_TypeError,
- "eval() arg 1 must be a string or code object");
- return NULL;
- }
- cf.cf_flags = 0;
+ PyObject *cmd, *result, *tmp = NULL;
+ PyObject *globals = Py_None, *locals = Py_None;
+ char *str;
+ PyCompilerFlags cf;
+
+ if (!PyArg_UnpackTuple(args, "eval", 1, 3, &cmd, &globals, &locals))
+ return NULL;
+ if (locals != Py_None && !PyMapping_Check(locals)) {
+ PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
+ return NULL;
+ }
+ if (globals != Py_None && !PyDict_Check(globals)) {
+ PyErr_SetString(PyExc_TypeError, PyMapping_Check(globals) ?
+ "globals must be a real dict; try eval(expr, {}, mapping)"
+ : "globals must be a dict");
+ return NULL;
+ }
+ if (globals == Py_None) {
+ globals = PyEval_GetGlobals();
+ if (locals == Py_None)
+ locals = PyEval_GetLocals();
+ }
+ else if (locals == Py_None)
+ locals = globals;
+
+ if (globals == NULL || locals == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "eval must be given globals and locals "
+ "when called without a frame");
+ return NULL;
+ }
+
+ if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
+ if (PyDict_SetItemString(globals, "__builtins__",
+ PyEval_GetBuiltins()) != 0)
+ return NULL;
+ }
+
+ if (PyCode_Check(cmd)) {
+ if (PyCode_GetNumFree((PyCodeObject *)cmd) > 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "code object passed to eval() may not contain free variables");
+ return NULL;
+ }
+ return PyEval_EvalCode((PyCodeObject *) cmd, globals, locals);
+ }
+
+ if (!PyString_Check(cmd) &&
+ !PyUnicode_Check(cmd)) {
+ PyErr_SetString(PyExc_TypeError,
+ "eval() arg 1 must be a string or code object");
+ return NULL;
+ }
+ cf.cf_flags = 0;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(cmd)) {
- tmp = PyUnicode_AsUTF8String(cmd);
- if (tmp == NULL)
- return NULL;
- cmd = tmp;
- cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
- }
+ if (PyUnicode_Check(cmd)) {
+ tmp = PyUnicode_AsUTF8String(cmd);
+ if (tmp == NULL)
+ return NULL;
+ cmd = tmp;
+ cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
+ }
#endif
- if (PyString_AsStringAndSize(cmd, &str, NULL)) {
- Py_XDECREF(tmp);
- return NULL;
- }
- while (*str == ' ' || *str == '\t')
- str++;
-
- (void)PyEval_MergeCompilerFlags(&cf);
- result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
- Py_XDECREF(tmp);
- return result;
+ if (PyString_AsStringAndSize(cmd, &str, NULL)) {
+ Py_XDECREF(tmp);
+ return NULL;
+ }
+ while (*str == ' ' || *str == '\t')
+ str++;
+
+ (void)PyEval_MergeCompilerFlags(&cf);
+ result = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
+ Py_XDECREF(tmp);
+ return result;
}
PyDoc_STRVAR(eval_doc,
@@ -703,98 +703,98 @@ If only globals is given, locals defaults to it.\n");
static PyObject *
builtin_execfile(PyObject *self, PyObject *args)
{
- char *filename;
- PyObject *globals = Py_None, *locals = Py_None;
- PyObject *res;
- FILE* fp = NULL;
- PyCompilerFlags cf;
- int exists;
-
- if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
- 1) < 0)
- return NULL;
-
- if (!PyArg_ParseTuple(args, "s|O!O:execfile",
- &filename,
- &PyDict_Type, &globals,
- &locals))
- return NULL;
- if (locals != Py_None && !PyMapping_Check(locals)) {
- PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
- return NULL;
- }
- if (globals == Py_None) {
- globals = PyEval_GetGlobals();
- if (locals == Py_None)
- locals = PyEval_GetLocals();
- }
- else if (locals == Py_None)
- locals = globals;
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
- if (PyDict_SetItemString(globals, "__builtins__",
- PyEval_GetBuiltins()) != 0)
- return NULL;
- }
-
- exists = 0;
- /* Test for existence or directory. */
+ char *filename;
+ PyObject *globals = Py_None, *locals = Py_None;
+ PyObject *res;
+ FILE* fp = NULL;
+ PyCompilerFlags cf;
+ int exists;
+
+ if (PyErr_WarnPy3k("execfile() not supported in 3.x; use exec()",
+ 1) < 0)
+ return NULL;
+
+ if (!PyArg_ParseTuple(args, "s|O!O:execfile",
+ &filename,
+ &PyDict_Type, &globals,
+ &locals))
+ return NULL;
+ if (locals != Py_None && !PyMapping_Check(locals)) {
+ PyErr_SetString(PyExc_TypeError, "locals must be a mapping");
+ return NULL;
+ }
+ if (globals == Py_None) {
+ globals = PyEval_GetGlobals();
+ if (locals == Py_None)
+ locals = PyEval_GetLocals();
+ }
+ else if (locals == Py_None)
+ locals = globals;
+ if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
+ if (PyDict_SetItemString(globals, "__builtins__",
+ PyEval_GetBuiltins()) != 0)
+ return NULL;
+ }
+
+ exists = 0;
+ /* Test for existence or directory. */
#if defined(PLAN9)
- {
- Dir *d;
-
- if ((d = dirstat(filename))!=nil) {
- if(d->mode & DMDIR)
- werrstr("is a directory");
- else
- exists = 1;
- free(d);
- }
- }
+ {
+ Dir *d;
+
+ if ((d = dirstat(filename))!=nil) {
+ if(d->mode & DMDIR)
+ werrstr("is a directory");
+ else
+ exists = 1;
+ free(d);
+ }
+ }
#elif defined(RISCOS)
- if (object_exists(filename)) {
- if (isdir(filename))
- errno = EISDIR;
- else
- exists = 1;
- }
-#else /* standard Posix */
- {
- struct stat s;
- if (stat(filename, &s) == 0) {
- if (S_ISDIR(s.st_mode))
-# if defined(PYOS_OS2) && defined(PYCC_VACPP)
- errno = EOS2ERR;
-# else
- errno = EISDIR;
-# endif
- else
- exists = 1;
- }
- }
+ if (object_exists(filename)) {
+ if (isdir(filename))
+ errno = EISDIR;
+ else
+ exists = 1;
+ }
+#else /* standard Posix */
+ {
+ struct stat s;
+ if (stat(filename, &s) == 0) {
+ if (S_ISDIR(s.st_mode))
+# if defined(PYOS_OS2) && defined(PYCC_VACPP)
+ errno = EOS2ERR;
+# else
+ errno = EISDIR;
+# endif
+ else
+ exists = 1;
+ }
+ }
#endif
- if (exists) {
- Py_BEGIN_ALLOW_THREADS
- fp = fopen(filename, "r" PY_STDIOTEXTMODE);
- Py_END_ALLOW_THREADS
-
- if (fp == NULL) {
- exists = 0;
- }
- }
-
- if (!exists) {
- PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
- return NULL;
- }
- cf.cf_flags = 0;
- if (PyEval_MergeCompilerFlags(&cf))
- res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
- locals, 1, &cf);
- else
- res = PyRun_FileEx(fp, filename, Py_file_input, globals,
- locals, 1);
- return res;
+ if (exists) {
+ Py_BEGIN_ALLOW_THREADS
+ fp = fopen(filename, "r" PY_STDIOTEXTMODE);
+ Py_END_ALLOW_THREADS
+
+ if (fp == NULL) {
+ exists = 0;
+ }
+ }
+
+ if (!exists) {
+ PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
+ return NULL;
+ }
+ cf.cf_flags = 0;
+ if (PyEval_MergeCompilerFlags(&cf))
+ res = PyRun_FileExFlags(fp, filename, Py_file_input, globals,
+ locals, 1, &cf);
+ else
+ res = PyRun_FileEx(fp, filename, Py_file_input, globals,
+ locals, 1);
+ return res;
}
PyDoc_STRVAR(execfile_doc,
@@ -808,33 +808,33 @@ globals and locals. If only globals is given, locals defaults to it.");
static PyObject *
builtin_getattr(PyObject *self, PyObject *args)
{
- PyObject *v, *result, *dflt = NULL;
- PyObject *name;
+ PyObject *v, *result, *dflt = NULL;
+ PyObject *name;
- if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "getattr", 2, 3, &v, &name, &dflt))
+ return NULL;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(name)) {
- name = _PyUnicode_AsDefaultEncodedString(name, NULL);
- if (name == NULL)
- return NULL;
- }
+ if (PyUnicode_Check(name)) {
+ name = _PyUnicode_AsDefaultEncodedString(name, NULL);
+ if (name == NULL)
+ return NULL;
+ }
#endif
- if (!PyString_Check(name)) {
- PyErr_SetString(PyExc_TypeError,
- "getattr(): attribute name must be string");
- return NULL;
- }
- result = PyObject_GetAttr(v, name);
- if (result == NULL && dflt != NULL &&
- PyErr_ExceptionMatches(PyExc_AttributeError))
- {
- PyErr_Clear();
- Py_INCREF(dflt);
- result = dflt;
- }
- return result;
+ if (!PyString_Check(name)) {
+ PyErr_SetString(PyExc_TypeError,
+ "getattr(): attribute name must be string");
+ return NULL;
+ }
+ result = PyObject_GetAttr(v, name);
+ if (result == NULL && dflt != NULL &&
+ PyErr_ExceptionMatches(PyExc_AttributeError))
+ {
+ PyErr_Clear();
+ Py_INCREF(dflt);
+ result = dflt;
+ }
+ return result;
}
PyDoc_STRVAR(getattr_doc,
@@ -848,11 +848,11 @@ exist; without it, an exception is raised in that case.");
static PyObject *
builtin_globals(PyObject *self)
{
- PyObject *d;
+ PyObject *d;
- d = PyEval_GetGlobals();
- Py_XINCREF(d);
- return d;
+ d = PyEval_GetGlobals();
+ Py_XINCREF(d);
+ return d;
}
PyDoc_STRVAR(globals_doc,
@@ -864,37 +864,37 @@ Return the dictionary containing the current scope's global variables.");
static PyObject *
builtin_hasattr(PyObject *self, PyObject *args)
{
- PyObject *v;
- PyObject *name;
+ PyObject *v;
+ PyObject *name;
- if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "hasattr", 2, 2, &v, &name))
+ return NULL;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(name)) {
- name = _PyUnicode_AsDefaultEncodedString(name, NULL);
- if (name == NULL)
- return NULL;
- }
+ if (PyUnicode_Check(name)) {
+ name = _PyUnicode_AsDefaultEncodedString(name, NULL);
+ if (name == NULL)
+ return NULL;
+ }
#endif
- if (!PyString_Check(name)) {
- PyErr_SetString(PyExc_TypeError,
- "hasattr(): attribute name must be string");
- return NULL;
- }
- v = PyObject_GetAttr(v, name);
- if (v == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_Exception))
- return NULL;
- else {
- PyErr_Clear();
- Py_INCREF(Py_False);
- return Py_False;
- }
- }
- Py_DECREF(v);
- Py_INCREF(Py_True);
- return Py_True;
+ if (!PyString_Check(name)) {
+ PyErr_SetString(PyExc_TypeError,
+ "hasattr(): attribute name must be string");
+ return NULL;
+ }
+ v = PyObject_GetAttr(v, name);
+ if (v == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_Exception))
+ return NULL;
+ else {
+ PyErr_Clear();
+ Py_INCREF(Py_False);
+ return Py_False;
+ }
+ }
+ Py_DECREF(v);
+ Py_INCREF(Py_True);
+ return Py_True;
}
PyDoc_STRVAR(hasattr_doc,
@@ -907,7 +907,7 @@ Return whether the object has an attribute with the given name.\n\
static PyObject *
builtin_id(PyObject *self, PyObject *v)
{
- return PyLong_FromVoidPtr(v);
+ return PyLong_FromVoidPtr(v);
}
PyDoc_STRVAR(id_doc,
@@ -920,154 +920,154 @@ simultaneously existing objects. (Hint: it's the object's memory address.)");
static PyObject *
builtin_map(PyObject *self, PyObject *args)
{
- typedef struct {
- PyObject *it; /* the iterator object */
- int saw_StopIteration; /* bool: did the iterator end? */
- } sequence;
-
- PyObject *func, *result;
- sequence *seqs = NULL, *sqp;
- Py_ssize_t n, len;
- register int i, j;
-
- n = PyTuple_Size(args);
- if (n < 2) {
- PyErr_SetString(PyExc_TypeError,
- "map() requires at least two args");
- return NULL;
- }
-
- func = PyTuple_GetItem(args, 0);
- n--;
-
- if (func == Py_None) {
- if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
- "use list(...)", 1) < 0)
- return NULL;
- if (n == 1) {
- /* map(None, S) is the same as list(S). */
- return PySequence_List(PyTuple_GetItem(args, 1));
- }
- }
-
- /* Get space for sequence descriptors. Must NULL out the iterator
- * pointers so that jumping to Fail_2 later doesn't see trash.
- */
- if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- for (i = 0; i < n; ++i) {
- seqs[i].it = (PyObject*)NULL;
- seqs[i].saw_StopIteration = 0;
- }
-
- /* Do a first pass to obtain iterators for the arguments, and set len
- * to the largest of their lengths.
- */
- len = 0;
- for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
- PyObject *curseq;
- Py_ssize_t curlen;
-
- /* Get iterator. */
- curseq = PyTuple_GetItem(args, i+1);
- sqp->it = PyObject_GetIter(curseq);
- if (sqp->it == NULL) {
- static char errmsg[] =
- "argument %d to map() must support iteration";
- char errbuf[sizeof(errmsg) + 25];
- PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
- PyErr_SetString(PyExc_TypeError, errbuf);
- goto Fail_2;
- }
-
- /* Update len. */
- curlen = _PyObject_LengthHint(curseq, 8);
- if (curlen > len)
- len = curlen;
- }
-
- /* Get space for the result list. */
- if ((result = (PyObject *) PyList_New(len)) == NULL)
- goto Fail_2;
-
- /* Iterate over the sequences until all have stopped. */
- for (i = 0; ; ++i) {
- PyObject *alist, *item=NULL, *value;
- int numactive = 0;
-
- if (func == Py_None && n == 1)
- alist = NULL;
- else if ((alist = PyTuple_New(n)) == NULL)
- goto Fail_1;
-
- for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
- if (sqp->saw_StopIteration) {
- Py_INCREF(Py_None);
- item = Py_None;
- }
- else {
- item = PyIter_Next(sqp->it);
- if (item)
- ++numactive;
- else {
- if (PyErr_Occurred()) {
- Py_XDECREF(alist);
- goto Fail_1;
- }
- Py_INCREF(Py_None);
- item = Py_None;
- sqp->saw_StopIteration = 1;
- }
- }
- if (alist)
- PyTuple_SET_ITEM(alist, j, item);
- else
- break;
- }
-
- if (!alist)
- alist = item;
-
- if (numactive == 0) {
- Py_DECREF(alist);
- break;
- }
-
- if (func == Py_None)
- value = alist;
- else {
- value = PyEval_CallObject(func, alist);
- Py_DECREF(alist);
- if (value == NULL)
- goto Fail_1;
- }
- if (i >= len) {
- int status = PyList_Append(result, value);
- Py_DECREF(value);
- if (status < 0)
- goto Fail_1;
- }
- else if (PyList_SetItem(result, i, value) < 0)
- goto Fail_1;
- }
-
- if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
- goto Fail_1;
-
- goto Succeed;
+ typedef struct {
+ PyObject *it; /* the iterator object */
+ int saw_StopIteration; /* bool: did the iterator end? */
+ } sequence;
+
+ PyObject *func, *result;
+ sequence *seqs = NULL, *sqp;
+ Py_ssize_t n, len;
+ register int i, j;
+
+ n = PyTuple_Size(args);
+ if (n < 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "map() requires at least two args");
+ return NULL;
+ }
+
+ func = PyTuple_GetItem(args, 0);
+ n--;
+
+ if (func == Py_None) {
+ if (PyErr_WarnPy3k("map(None, ...) not supported in 3.x; "
+ "use list(...)", 1) < 0)
+ return NULL;
+ if (n == 1) {
+ /* map(None, S) is the same as list(S). */
+ return PySequence_List(PyTuple_GetItem(args, 1));
+ }
+ }
+
+ /* Get space for sequence descriptors. Must NULL out the iterator
+ * pointers so that jumping to Fail_2 later doesn't see trash.
+ */
+ if ((seqs = PyMem_NEW(sequence, n)) == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ for (i = 0; i < n; ++i) {
+ seqs[i].it = (PyObject*)NULL;
+ seqs[i].saw_StopIteration = 0;
+ }
+
+ /* Do a first pass to obtain iterators for the arguments, and set len
+ * to the largest of their lengths.
+ */
+ len = 0;
+ for (i = 0, sqp = seqs; i < n; ++i, ++sqp) {
+ PyObject *curseq;
+ Py_ssize_t curlen;
+
+ /* Get iterator. */
+ curseq = PyTuple_GetItem(args, i+1);
+ sqp->it = PyObject_GetIter(curseq);
+ if (sqp->it == NULL) {
+ static char errmsg[] =
+ "argument %d to map() must support iteration";
+ char errbuf[sizeof(errmsg) + 25];
+ PyOS_snprintf(errbuf, sizeof(errbuf), errmsg, i+2);
+ PyErr_SetString(PyExc_TypeError, errbuf);
+ goto Fail_2;
+ }
+
+ /* Update len. */
+ curlen = _PyObject_LengthHint(curseq, 8);
+ if (curlen > len)
+ len = curlen;
+ }
+
+ /* Get space for the result list. */
+ if ((result = (PyObject *) PyList_New(len)) == NULL)
+ goto Fail_2;
+
+ /* Iterate over the sequences until all have stopped. */
+ for (i = 0; ; ++i) {
+ PyObject *alist, *item=NULL, *value;
+ int numactive = 0;
+
+ if (func == Py_None && n == 1)
+ alist = NULL;
+ else if ((alist = PyTuple_New(n)) == NULL)
+ goto Fail_1;
+
+ for (j = 0, sqp = seqs; j < n; ++j, ++sqp) {
+ if (sqp->saw_StopIteration) {
+ Py_INCREF(Py_None);
+ item = Py_None;
+ }
+ else {
+ item = PyIter_Next(sqp->it);
+ if (item)
+ ++numactive;
+ else {
+ if (PyErr_Occurred()) {
+ Py_XDECREF(alist);
+ goto Fail_1;
+ }
+ Py_INCREF(Py_None);
+ item = Py_None;
+ sqp->saw_StopIteration = 1;
+ }
+ }
+ if (alist)
+ PyTuple_SET_ITEM(alist, j, item);
+ else
+ break;
+ }
+
+ if (!alist)
+ alist = item;
+
+ if (numactive == 0) {
+ Py_DECREF(alist);
+ break;
+ }
+
+ if (func == Py_None)
+ value = alist;
+ else {
+ value = PyEval_CallObject(func, alist);
+ Py_DECREF(alist);
+ if (value == NULL)
+ goto Fail_1;
+ }
+ if (i >= len) {
+ int status = PyList_Append(result, value);
+ Py_DECREF(value);
+ if (status < 0)
+ goto Fail_1;
+ }
+ else if (PyList_SetItem(result, i, value) < 0)
+ goto Fail_1;
+ }
+
+ if (i < len && PyList_SetSlice(result, i, len, NULL) < 0)
+ goto Fail_1;
+
+ goto Succeed;
Fail_1:
- Py_DECREF(result);
+ Py_DECREF(result);
Fail_2:
- result = NULL;
+ result = NULL;
Succeed:
- assert(seqs);
- for (i = 0; i < n; ++i)
- Py_XDECREF(seqs[i].it);
- PyMem_DEL(seqs);
- return result;
+ assert(seqs);
+ for (i = 0; i < n; ++i)
+ Py_XDECREF(seqs[i].it);
+ PyMem_DEL(seqs);
+ return result;
}
PyDoc_STRVAR(map_doc,
@@ -1084,35 +1084,35 @@ the items of the sequence (or a list of tuples if more than one sequence).");
static PyObject *
builtin_next(PyObject *self, PyObject *args)
{
- PyObject *it, *res;
- PyObject *def = NULL;
-
- if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
- return NULL;
- if (!PyIter_Check(it)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s object is not an iterator",
- it->ob_type->tp_name);
- return NULL;
- }
-
- res = (*it->ob_type->tp_iternext)(it);
- if (res != NULL) {
- return res;
- } else if (def != NULL) {
- if (PyErr_Occurred()) {
- if (!PyErr_ExceptionMatches(PyExc_StopIteration))
- return NULL;
- PyErr_Clear();
- }
- Py_INCREF(def);
- return def;
- } else if (PyErr_Occurred()) {
- return NULL;
- } else {
- PyErr_SetNone(PyExc_StopIteration);
- return NULL;
- }
+ PyObject *it, *res;
+ PyObject *def = NULL;
+
+ if (!PyArg_UnpackTuple(args, "next", 1, 2, &it, &def))
+ return NULL;
+ if (!PyIter_Check(it)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s object is not an iterator",
+ it->ob_type->tp_name);
+ return NULL;
+ }
+
+ res = (*it->ob_type->tp_iternext)(it);
+ if (res != NULL) {
+ return res;
+ } else if (def != NULL) {
+ if (PyErr_Occurred()) {
+ if (!PyErr_ExceptionMatches(PyExc_StopIteration))
+ return NULL;
+ PyErr_Clear();
+ }
+ Py_INCREF(def);
+ return def;
+ } else if (PyErr_Occurred()) {
+ return NULL;
+ } else {
+ PyErr_SetNone(PyExc_StopIteration);
+ return NULL;
+ }
}
PyDoc_STRVAR(next_doc,
@@ -1125,16 +1125,16 @@ is exhausted, it is returned instead of raising StopIteration.");
static PyObject *
builtin_setattr(PyObject *self, PyObject *args)
{
- PyObject *v;
- PyObject *name;
- PyObject *value;
-
- if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
- return NULL;
- if (PyObject_SetAttr(v, name, value) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v;
+ PyObject *name;
+ PyObject *value;
+
+ if (!PyArg_UnpackTuple(args, "setattr", 3, 3, &v, &name, &value))
+ return NULL;
+ if (PyObject_SetAttr(v, name, value) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setattr_doc,
@@ -1147,15 +1147,15 @@ Set a named attribute on an object; setattr(x, 'y', v) is equivalent to\n\
static PyObject *
builtin_delattr(PyObject *self, PyObject *args)
{
- PyObject *v;
- PyObject *name;
-
- if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
- return NULL;
- if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *v;
+ PyObject *name;
+
+ if (!PyArg_UnpackTuple(args, "delattr", 2, 2, &v, &name))
+ return NULL;
+ if (PyObject_SetAttr(v, name, (PyObject *)NULL) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(delattr_doc,
@@ -1168,12 +1168,12 @@ Delete a named attribute on an object; delattr(x, 'y') is equivalent to\n\
static PyObject *
builtin_hash(PyObject *self, PyObject *v)
{
- long x;
+ long x;
- x = PyObject_Hash(v);
- if (x == -1)
- return NULL;
- return PyInt_FromLong(x);
+ x = PyObject_Hash(v);
+ if (x == -1)
+ return NULL;
+ return PyInt_FromLong(x);
}
PyDoc_STRVAR(hash_doc,
@@ -1186,24 +1186,24 @@ the same hash value. The reverse is not necessarily true, but likely.");
static PyObject *
builtin_hex(PyObject *self, PyObject *v)
{
- PyNumberMethods *nb;
- PyObject *res;
-
- if ((nb = v->ob_type->tp_as_number) == NULL ||
- nb->nb_hex == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "hex() argument can't be converted to hex");
- return NULL;
- }
- res = (*nb->nb_hex)(v);
- if (res && !PyString_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "__hex__ returned non-string (type %.200s)",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
+ PyNumberMethods *nb;
+ PyObject *res;
+
+ if ((nb = v->ob_type->tp_as_number) == NULL ||
+ nb->nb_hex == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "hex() argument can't be converted to hex");
+ return NULL;
+ }
+ res = (*nb->nb_hex)(v);
+ if (res && !PyString_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "__hex__ returned non-string (type %.200s)",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
}
PyDoc_STRVAR(hex_doc,
@@ -1217,31 +1217,31 @@ static PyObject *builtin_raw_input(PyObject *, PyObject *);
static PyObject *
builtin_input(PyObject *self, PyObject *args)
{
- PyObject *line;
- char *str;
- PyObject *res;
- PyObject *globals, *locals;
- PyCompilerFlags cf;
-
- line = builtin_raw_input(self, args);
- if (line == NULL)
- return line;
- if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
- return NULL;
- while (*str == ' ' || *str == '\t')
- str++;
- globals = PyEval_GetGlobals();
- locals = PyEval_GetLocals();
- if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
- if (PyDict_SetItemString(globals, "__builtins__",
- PyEval_GetBuiltins()) != 0)
- return NULL;
- }
- cf.cf_flags = 0;
- PyEval_MergeCompilerFlags(&cf);
- res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
- Py_DECREF(line);
- return res;
+ PyObject *line;
+ char *str;
+ PyObject *res;
+ PyObject *globals, *locals;
+ PyCompilerFlags cf;
+
+ line = builtin_raw_input(self, args);
+ if (line == NULL)
+ return line;
+ if (!PyArg_Parse(line, "s;embedded '\\0' in input line", &str))
+ return NULL;
+ while (*str == ' ' || *str == '\t')
+ str++;
+ globals = PyEval_GetGlobals();
+ locals = PyEval_GetLocals();
+ if (PyDict_GetItemString(globals, "__builtins__") == NULL) {
+ if (PyDict_SetItemString(globals, "__builtins__",
+ PyEval_GetBuiltins()) != 0)
+ return NULL;
+ }
+ cf.cf_flags = 0;
+ PyEval_MergeCompilerFlags(&cf);
+ res = PyRun_StringFlags(str, Py_eval_input, globals, locals, &cf);
+ Py_DECREF(line);
+ return res;
}
PyDoc_STRVAR(input_doc,
@@ -1253,17 +1253,17 @@ Equivalent to eval(raw_input(prompt)).");
static PyObject *
builtin_intern(PyObject *self, PyObject *args)
{
- PyObject *s;
- if (!PyArg_ParseTuple(args, "S:intern", &s))
- return NULL;
- if (!PyString_CheckExact(s)) {
- PyErr_SetString(PyExc_TypeError,
- "can't intern subclass of string");
- return NULL;
- }
- Py_INCREF(s);
- PyString_InternInPlace(&s);
- return s;
+ PyObject *s;
+ if (!PyArg_ParseTuple(args, "S:intern", &s))
+ return NULL;
+ if (!PyString_CheckExact(s)) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't intern subclass of string");
+ return NULL;
+ }
+ Py_INCREF(s);
+ PyString_InternInPlace(&s);
+ return s;
}
PyDoc_STRVAR(intern_doc,
@@ -1278,18 +1278,18 @@ same value.");
static PyObject *
builtin_iter(PyObject *self, PyObject *args)
{
- PyObject *v, *w = NULL;
-
- if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
- return NULL;
- if (w == NULL)
- return PyObject_GetIter(v);
- if (!PyCallable_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "iter(v, w): v must be callable");
- return NULL;
- }
- return PyCallIter_New(v, w);
+ PyObject *v, *w = NULL;
+
+ if (!PyArg_UnpackTuple(args, "iter", 1, 2, &v, &w))
+ return NULL;
+ if (w == NULL)
+ return PyObject_GetIter(v);
+ if (!PyCallable_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "iter(v, w): v must be callable");
+ return NULL;
+ }
+ return PyCallIter_New(v, w);
}
PyDoc_STRVAR(iter_doc,
@@ -1304,12 +1304,12 @@ In the second form, the callable is called until it returns the sentinel.");
static PyObject *
builtin_len(PyObject *self, PyObject *v)
{
- Py_ssize_t res;
+ Py_ssize_t res;
- res = PyObject_Size(v);
- if (res < 0 && PyErr_Occurred())
- return NULL;
- return PyInt_FromSsize_t(res);
+ res = PyObject_Size(v);
+ if (res < 0 && PyErr_Occurred())
+ return NULL;
+ return PyInt_FromSsize_t(res);
}
PyDoc_STRVAR(len_doc,
@@ -1321,11 +1321,11 @@ Return the number of items of a sequence or mapping.");
static PyObject *
builtin_locals(PyObject *self)
{
- PyObject *d;
+ PyObject *d;
- d = PyEval_GetLocals();
- Py_XINCREF(d);
- return d;
+ d = PyEval_GetLocals();
+ Py_XINCREF(d);
+ return d;
}
PyDoc_STRVAR(locals_doc,
@@ -1337,96 +1337,96 @@ Update and return a dictionary containing the current scope's local variables.")
static PyObject *
min_max(PyObject *args, PyObject *kwds, int op)
{
- PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
- const char *name = op == Py_LT ? "min" : "max";
-
- if (PyTuple_Size(args) > 1)
- v = args;
- else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
- return NULL;
-
- if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
- keyfunc = PyDict_GetItemString(kwds, "key");
- if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
- PyErr_Format(PyExc_TypeError,
- "%s() got an unexpected keyword argument", name);
- return NULL;
- }
- Py_INCREF(keyfunc);
- }
-
- it = PyObject_GetIter(v);
- if (it == NULL) {
- Py_XDECREF(keyfunc);
- return NULL;
- }
-
- maxitem = NULL; /* the result */
- maxval = NULL; /* the value associated with the result */
- while (( item = PyIter_Next(it) )) {
- /* get the value from the key function */
- if (keyfunc != NULL) {
- val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
- if (val == NULL)
- goto Fail_it_item;
- }
- /* no key function; the value is the item */
- else {
- val = item;
- Py_INCREF(val);
- }
-
- /* maximum value and item are unset; set them */
- if (maxval == NULL) {
- maxitem = item;
- maxval = val;
- }
- /* maximum value and item are set; update them as necessary */
- else {
- int cmp = PyObject_RichCompareBool(val, maxval, op);
- if (cmp < 0)
- goto Fail_it_item_and_val;
- else if (cmp > 0) {
- Py_DECREF(maxval);
- Py_DECREF(maxitem);
- maxval = val;
- maxitem = item;
- }
- else {
- Py_DECREF(item);
- Py_DECREF(val);
- }
- }
- }
- if (PyErr_Occurred())
- goto Fail_it;
- if (maxval == NULL) {
- PyErr_Format(PyExc_ValueError,
- "%s() arg is an empty sequence", name);
- assert(maxitem == NULL);
- }
- else
- Py_DECREF(maxval);
- Py_DECREF(it);
- Py_XDECREF(keyfunc);
- return maxitem;
+ PyObject *v, *it, *item, *val, *maxitem, *maxval, *keyfunc=NULL;
+ const char *name = op == Py_LT ? "min" : "max";
+
+ if (PyTuple_Size(args) > 1)
+ v = args;
+ else if (!PyArg_UnpackTuple(args, (char *)name, 1, 1, &v))
+ return NULL;
+
+ if (kwds != NULL && PyDict_Check(kwds) && PyDict_Size(kwds)) {
+ keyfunc = PyDict_GetItemString(kwds, "key");
+ if (PyDict_Size(kwds)!=1 || keyfunc == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%s() got an unexpected keyword argument", name);
+ return NULL;
+ }
+ Py_INCREF(keyfunc);
+ }
+
+ it = PyObject_GetIter(v);
+ if (it == NULL) {
+ Py_XDECREF(keyfunc);
+ return NULL;
+ }
+
+ maxitem = NULL; /* the result */
+ maxval = NULL; /* the value associated with the result */
+ while (( item = PyIter_Next(it) )) {
+ /* get the value from the key function */
+ if (keyfunc != NULL) {
+ val = PyObject_CallFunctionObjArgs(keyfunc, item, NULL);
+ if (val == NULL)
+ goto Fail_it_item;
+ }
+ /* no key function; the value is the item */
+ else {
+ val = item;
+ Py_INCREF(val);
+ }
+
+ /* maximum value and item are unset; set them */
+ if (maxval == NULL) {
+ maxitem = item;
+ maxval = val;
+ }
+ /* maximum value and item are set; update them as necessary */
+ else {
+ int cmp = PyObject_RichCompareBool(val, maxval, op);
+ if (cmp < 0)
+ goto Fail_it_item_and_val;
+ else if (cmp > 0) {
+ Py_DECREF(maxval);
+ Py_DECREF(maxitem);
+ maxval = val;
+ maxitem = item;
+ }
+ else {
+ Py_DECREF(item);
+ Py_DECREF(val);
+ }
+ }
+ }
+ if (PyErr_Occurred())
+ goto Fail_it;
+ if (maxval == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "%s() arg is an empty sequence", name);
+ assert(maxitem == NULL);
+ }
+ else
+ Py_DECREF(maxval);
+ Py_DECREF(it);
+ Py_XDECREF(keyfunc);
+ return maxitem;
Fail_it_item_and_val:
- Py_DECREF(val);
+ Py_DECREF(val);
Fail_it_item:
- Py_DECREF(item);
+ Py_DECREF(item);
Fail_it:
- Py_XDECREF(maxval);
- Py_XDECREF(maxitem);
- Py_DECREF(it);
- Py_XDECREF(keyfunc);
- return NULL;
+ Py_XDECREF(maxval);
+ Py_XDECREF(maxitem);
+ Py_DECREF(it);
+ Py_XDECREF(keyfunc);
+ return NULL;
}
static PyObject *
builtin_min(PyObject *self, PyObject *args, PyObject *kwds)
{
- return min_max(args, kwds, Py_LT);
+ return min_max(args, kwds, Py_LT);
}
PyDoc_STRVAR(min_doc,
@@ -1440,7 +1440,7 @@ With two or more arguments, return the smallest argument.");
static PyObject *
builtin_max(PyObject *self, PyObject *args, PyObject *kwds)
{
- return min_max(args, kwds, Py_GT);
+ return min_max(args, kwds, Py_GT);
}
PyDoc_STRVAR(max_doc,
@@ -1454,24 +1454,24 @@ With two or more arguments, return the largest argument.");
static PyObject *
builtin_oct(PyObject *self, PyObject *v)
{
- PyNumberMethods *nb;
- PyObject *res;
-
- if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
- nb->nb_oct == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "oct() argument can't be converted to oct");
- return NULL;
- }
- res = (*nb->nb_oct)(v);
- if (res && !PyString_Check(res)) {
- PyErr_Format(PyExc_TypeError,
- "__oct__ returned non-string (type %.200s)",
- res->ob_type->tp_name);
- Py_DECREF(res);
- return NULL;
- }
- return res;
+ PyNumberMethods *nb;
+ PyObject *res;
+
+ if (v == NULL || (nb = v->ob_type->tp_as_number) == NULL ||
+ nb->nb_oct == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "oct() argument can't be converted to oct");
+ return NULL;
+ }
+ res = (*nb->nb_oct)(v);
+ if (res && !PyString_Check(res)) {
+ PyErr_Format(PyExc_TypeError,
+ "__oct__ returned non-string (type %.200s)",
+ res->ob_type->tp_name);
+ Py_DECREF(res);
+ return NULL;
+ }
+ return res;
}
PyDoc_STRVAR(oct_doc,
@@ -1483,7 +1483,7 @@ Return the octal representation of an integer or long integer.");
static PyObject *
builtin_open(PyObject *self, PyObject *args, PyObject *kwds)
{
- return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
+ return PyObject_Call((PyObject*)&PyFile_Type, args, kwds);
}
PyDoc_STRVAR(open_doc,
@@ -1496,42 +1496,42 @@ preferred way to open a file. See file.__doc__ for further information.");
static PyObject *
builtin_ord(PyObject *self, PyObject* obj)
{
- long ord;
- Py_ssize_t size;
-
- if (PyString_Check(obj)) {
- size = PyString_GET_SIZE(obj);
- if (size == 1) {
- ord = (long)((unsigned char)*PyString_AS_STRING(obj));
- return PyInt_FromLong(ord);
- }
- } else if (PyByteArray_Check(obj)) {
- size = PyByteArray_GET_SIZE(obj);
- if (size == 1) {
- ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
- return PyInt_FromLong(ord);
- }
+ long ord;
+ Py_ssize_t size;
+
+ if (PyString_Check(obj)) {
+ size = PyString_GET_SIZE(obj);
+ if (size == 1) {
+ ord = (long)((unsigned char)*PyString_AS_STRING(obj));
+ return PyInt_FromLong(ord);
+ }
+ } else if (PyByteArray_Check(obj)) {
+ size = PyByteArray_GET_SIZE(obj);
+ if (size == 1) {
+ ord = (long)((unsigned char)*PyByteArray_AS_STRING(obj));
+ return PyInt_FromLong(ord);
+ }
#ifdef Py_USING_UNICODE
- } else if (PyUnicode_Check(obj)) {
- size = PyUnicode_GET_SIZE(obj);
- if (size == 1) {
- ord = (long)*PyUnicode_AS_UNICODE(obj);
- return PyInt_FromLong(ord);
- }
+ } else if (PyUnicode_Check(obj)) {
+ size = PyUnicode_GET_SIZE(obj);
+ if (size == 1) {
+ ord = (long)*PyUnicode_AS_UNICODE(obj);
+ return PyInt_FromLong(ord);
+ }
#endif
- } else {
- PyErr_Format(PyExc_TypeError,
- "ord() expected string of length 1, but " \
- "%.200s found", obj->ob_type->tp_name);
- return NULL;
- }
-
- PyErr_Format(PyExc_TypeError,
- "ord() expected a character, "
- "but string of length %zd found",
- size);
- return NULL;
+ } else {
+ PyErr_Format(PyExc_TypeError,
+ "ord() expected string of length 1, but " \
+ "%.200s found", obj->ob_type->tp_name);
+ return NULL;
+ }
+
+ PyErr_Format(PyExc_TypeError,
+ "ord() expected a character, "
+ "but string of length %zd found",
+ size);
+ return NULL;
}
PyDoc_STRVAR(ord_doc,
@@ -1543,11 +1543,11 @@ Return the integer ordinal of a one-character string.");
static PyObject *
builtin_pow(PyObject *self, PyObject *args)
{
- PyObject *v, *w, *z = Py_None;
+ PyObject *v, *w, *z = Py_None;
- if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
- return NULL;
- return PyNumber_Power(v, w, z);
+ if (!PyArg_UnpackTuple(args, "pow", 2, 3, &v, &w, &z))
+ return NULL;
+ return PyNumber_Power(v, w, z);
}
PyDoc_STRVAR(pow_doc,
@@ -1560,120 +1560,120 @@ equivalent to (x**y) % z, but may be more efficient (e.g. for longs).");
static PyObject *
builtin_print(PyObject *self, PyObject *args, PyObject *kwds)
{
- static char *kwlist[] = {"sep", "end", "file", 0};
- static PyObject *dummy_args = NULL;
- static PyObject *unicode_newline = NULL, *unicode_space = NULL;
- static PyObject *str_newline = NULL, *str_space = NULL;
- PyObject *newline, *space;
- PyObject *sep = NULL, *end = NULL, *file = NULL;
- int i, err, use_unicode = 0;
-
- if (dummy_args == NULL) {
- if (!(dummy_args = PyTuple_New(0)))
- return NULL;
- }
- if (str_newline == NULL) {
- str_newline = PyString_FromString("\n");
- if (str_newline == NULL)
- return NULL;
- str_space = PyString_FromString(" ");
- if (str_space == NULL) {
- Py_CLEAR(str_newline);
- return NULL;
- }
- unicode_newline = PyUnicode_FromString("\n");
- if (unicode_newline == NULL) {
- Py_CLEAR(str_newline);
- Py_CLEAR(str_space);
- return NULL;
- }
- unicode_space = PyUnicode_FromString(" ");
- if (unicode_space == NULL) {
- Py_CLEAR(str_newline);
- Py_CLEAR(str_space);
- Py_CLEAR(unicode_space);
- return NULL;
- }
- }
- if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
- kwlist, &sep, &end, &file))
- return NULL;
- if (file == NULL || file == Py_None) {
- file = PySys_GetObject("stdout");
- /* sys.stdout may be None when FILE* stdout isn't connected */
- if (file == Py_None)
- Py_RETURN_NONE;
- }
- if (sep == Py_None) {
- sep = NULL;
- }
- else if (sep) {
- if (PyUnicode_Check(sep)) {
- use_unicode = 1;
- }
- else if (!PyString_Check(sep)) {
- PyErr_Format(PyExc_TypeError,
- "sep must be None, str or unicode, not %.200s",
- sep->ob_type->tp_name);
- return NULL;
- }
- }
- if (end == Py_None)
- end = NULL;
- else if (end) {
- if (PyUnicode_Check(end)) {
- use_unicode = 1;
- }
- else if (!PyString_Check(end)) {
- PyErr_Format(PyExc_TypeError,
- "end must be None, str or unicode, not %.200s",
- end->ob_type->tp_name);
- return NULL;
- }
- }
-
- if (!use_unicode) {
- for (i = 0; i < PyTuple_Size(args); i++) {
- if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
- use_unicode = 1;
- break;
- }
- }
- }
- if (use_unicode) {
- newline = unicode_newline;
- space = unicode_space;
- }
- else {
- newline = str_newline;
- space = str_space;
- }
-
- for (i = 0; i < PyTuple_Size(args); i++) {
- if (i > 0) {
- if (sep == NULL)
- err = PyFile_WriteObject(space, file,
- Py_PRINT_RAW);
- else
- err = PyFile_WriteObject(sep, file,
- Py_PRINT_RAW);
- if (err)
- return NULL;
- }
- err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
- Py_PRINT_RAW);
- if (err)
- return NULL;
- }
-
- if (end == NULL)
- err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
- else
- err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
- if (err)
- return NULL;
-
- Py_RETURN_NONE;
+ static char *kwlist[] = {"sep", "end", "file", 0};
+ static PyObject *dummy_args = NULL;
+ static PyObject *unicode_newline = NULL, *unicode_space = NULL;
+ static PyObject *str_newline = NULL, *str_space = NULL;
+ PyObject *newline, *space;
+ PyObject *sep = NULL, *end = NULL, *file = NULL;
+ int i, err, use_unicode = 0;
+
+ if (dummy_args == NULL) {
+ if (!(dummy_args = PyTuple_New(0)))
+ return NULL;
+ }
+ if (str_newline == NULL) {
+ str_newline = PyString_FromString("\n");
+ if (str_newline == NULL)
+ return NULL;
+ str_space = PyString_FromString(" ");
+ if (str_space == NULL) {
+ Py_CLEAR(str_newline);
+ return NULL;
+ }
+ unicode_newline = PyUnicode_FromString("\n");
+ if (unicode_newline == NULL) {
+ Py_CLEAR(str_newline);
+ Py_CLEAR(str_space);
+ return NULL;
+ }
+ unicode_space = PyUnicode_FromString(" ");
+ if (unicode_space == NULL) {
+ Py_CLEAR(str_newline);
+ Py_CLEAR(str_space);
+ Py_CLEAR(unicode_space);
+ return NULL;
+ }
+ }
+ if (!PyArg_ParseTupleAndKeywords(dummy_args, kwds, "|OOO:print",
+ kwlist, &sep, &end, &file))
+ return NULL;
+ if (file == NULL || file == Py_None) {
+ file = PySys_GetObject("stdout");
+ /* sys.stdout may be None when FILE* stdout isn't connected */
+ if (file == Py_None)
+ Py_RETURN_NONE;
+ }
+ if (sep == Py_None) {
+ sep = NULL;
+ }
+ else if (sep) {
+ if (PyUnicode_Check(sep)) {
+ use_unicode = 1;
+ }
+ else if (!PyString_Check(sep)) {
+ PyErr_Format(PyExc_TypeError,
+ "sep must be None, str or unicode, not %.200s",
+ sep->ob_type->tp_name);
+ return NULL;
+ }
+ }
+ if (end == Py_None)
+ end = NULL;
+ else if (end) {
+ if (PyUnicode_Check(end)) {
+ use_unicode = 1;
+ }
+ else if (!PyString_Check(end)) {
+ PyErr_Format(PyExc_TypeError,
+ "end must be None, str or unicode, not %.200s",
+ end->ob_type->tp_name);
+ return NULL;
+ }
+ }
+
+ if (!use_unicode) {
+ for (i = 0; i < PyTuple_Size(args); i++) {
+ if (PyUnicode_Check(PyTuple_GET_ITEM(args, i))) {
+ use_unicode = 1;
+ break;
+ }
+ }
+ }
+ if (use_unicode) {
+ newline = unicode_newline;
+ space = unicode_space;
+ }
+ else {
+ newline = str_newline;
+ space = str_space;
+ }
+
+ for (i = 0; i < PyTuple_Size(args); i++) {
+ if (i > 0) {
+ if (sep == NULL)
+ err = PyFile_WriteObject(space, file,
+ Py_PRINT_RAW);
+ else
+ err = PyFile_WriteObject(sep, file,
+ Py_PRINT_RAW);
+ if (err)
+ return NULL;
+ }
+ err = PyFile_WriteObject(PyTuple_GetItem(args, i), file,
+ Py_PRINT_RAW);
+ if (err)
+ return NULL;
+ }
+
+ if (end == NULL)
+ err = PyFile_WriteObject(newline, file, Py_PRINT_RAW);
+ else
+ err = PyFile_WriteObject(end, file, Py_PRINT_RAW);
+ if (err)
+ return NULL;
+
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(print_doc,
@@ -1695,55 +1695,55 @@ end: string appended after the last value, default a newline.");
static long
get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
{
- /* -------------------------------------------------------------
- Algorithm is equal to that of get_len_of_range(), but it operates
- on PyObjects (which are assumed to be PyLong or PyInt objects).
- ---------------------------------------------------------------*/
- long n;
- PyObject *diff = NULL;
- PyObject *one = NULL;
- PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
- /* holds sub-expression evaluations */
-
- /* if (lo >= hi), return length of 0. */
- if (PyObject_Compare(lo, hi) >= 0)
- return 0;
-
- if ((one = PyLong_FromLong(1L)) == NULL)
- goto Fail;
-
- if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
- goto Fail;
-
- if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
- goto Fail;
-
- if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
- goto Fail;
-
- if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
- goto Fail;
-
- n = PyLong_AsLong(tmp3);
- if (PyErr_Occurred()) { /* Check for Overflow */
- PyErr_Clear();
- goto Fail;
- }
-
- Py_DECREF(tmp3);
- Py_DECREF(tmp2);
- Py_DECREF(diff);
- Py_DECREF(tmp1);
- Py_DECREF(one);
- return n;
+ /* -------------------------------------------------------------
+ Algorithm is equal to that of get_len_of_range(), but it operates
+ on PyObjects (which are assumed to be PyLong or PyInt objects).
+ ---------------------------------------------------------------*/
+ long n;
+ PyObject *diff = NULL;
+ PyObject *one = NULL;
+ PyObject *tmp1 = NULL, *tmp2 = NULL, *tmp3 = NULL;
+ /* holds sub-expression evaluations */
+
+ /* if (lo >= hi), return length of 0. */
+ if (PyObject_Compare(lo, hi) >= 0)
+ return 0;
+
+ if ((one = PyLong_FromLong(1L)) == NULL)
+ goto Fail;
+
+ if ((tmp1 = PyNumber_Subtract(hi, lo)) == NULL)
+ goto Fail;
+
+ if ((diff = PyNumber_Subtract(tmp1, one)) == NULL)
+ goto Fail;
+
+ if ((tmp2 = PyNumber_FloorDivide(diff, step)) == NULL)
+ goto Fail;
+
+ if ((tmp3 = PyNumber_Add(tmp2, one)) == NULL)
+ goto Fail;
+
+ n = PyLong_AsLong(tmp3);
+ if (PyErr_Occurred()) { /* Check for Overflow */
+ PyErr_Clear();
+ goto Fail;
+ }
+
+ Py_DECREF(tmp3);
+ Py_DECREF(tmp2);
+ Py_DECREF(diff);
+ Py_DECREF(tmp1);
+ Py_DECREF(one);
+ return n;
Fail:
- Py_XDECREF(tmp3);
- Py_XDECREF(tmp2);
- Py_XDECREF(diff);
- Py_XDECREF(tmp1);
- Py_XDECREF(one);
- return -1;
+ Py_XDECREF(tmp3);
+ Py_XDECREF(tmp2);
+ Py_XDECREF(diff);
+ Py_XDECREF(tmp1);
+ Py_XDECREF(one);
+ return -1;
}
/* Helper function for handle_range_longs. If arg is int or long
@@ -1756,29 +1756,29 @@ get_len_of_range_longs(PyObject *lo, PyObject *hi, PyObject *step)
static PyObject *
get_range_long_argument(PyObject *arg, const char *name)
{
- PyObject *v;
- PyNumberMethods *nb;
- if (PyInt_Check(arg) || PyLong_Check(arg)) {
- Py_INCREF(arg);
- return arg;
- }
- if (PyFloat_Check(arg) ||
- (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
- nb->nb_int == NULL) {
- PyErr_Format(PyExc_TypeError,
- "range() integer %s argument expected, got %s.",
- name, arg->ob_type->tp_name);
- return NULL;
- }
- v = nb->nb_int(arg);
- if (v == NULL)
- return NULL;
- if (PyInt_Check(v) || PyLong_Check(v))
- return v;
- Py_DECREF(v);
- PyErr_SetString(PyExc_TypeError,
- "__int__ should return int object");
- return NULL;
+ PyObject *v;
+ PyNumberMethods *nb;
+ if (PyInt_Check(arg) || PyLong_Check(arg)) {
+ Py_INCREF(arg);
+ return arg;
+ }
+ if (PyFloat_Check(arg) ||
+ (nb = Py_TYPE(arg)->tp_as_number) == NULL ||
+ nb->nb_int == NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "range() integer %s argument expected, got %s.",
+ name, arg->ob_type->tp_name);
+ return NULL;
+ }
+ v = nb->nb_int(arg);
+ if (v == NULL)
+ return NULL;
+ if (PyInt_Check(v) || PyLong_Check(v))
+ return v;
+ Py_DECREF(v);
+ PyErr_SetString(PyExc_TypeError,
+ "__int__ should return int object");
+ return NULL;
}
/* An extension of builtin_range() that handles the case when PyLong
@@ -1786,129 +1786,129 @@ get_range_long_argument(PyObject *arg, const char *name)
static PyObject *
handle_range_longs(PyObject *self, PyObject *args)
{
- PyObject *ilow = NULL;
- PyObject *ihigh = NULL;
- PyObject *istep = NULL;
-
- PyObject *low = NULL;
- PyObject *high = NULL;
- PyObject *step = NULL;
-
- PyObject *curnum = NULL;
- PyObject *v = NULL;
- long bign;
- Py_ssize_t i, n;
- int cmp_result;
-
- PyObject *zero = PyLong_FromLong(0);
-
- if (zero == NULL)
- return NULL;
-
- if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
- Py_DECREF(zero);
- return NULL;
- }
-
- /* Figure out which way we were called, supply defaults, and be
- * sure to incref everything so that the decrefs at the end
- * are correct. NB: ilow, ihigh and istep are borrowed references.
- */
- assert(ilow != NULL);
- if (ihigh == NULL) {
- /* only 1 arg -- it's the upper limit */
- ihigh = ilow;
- ilow = NULL;
- }
-
- /* convert ihigh if necessary */
- assert(ihigh != NULL);
- high = get_range_long_argument(ihigh, "end");
- if (high == NULL)
- goto Fail;
-
- /* ihigh correct now; do ilow */
- if (ilow == NULL) {
- Py_INCREF(zero);
- low = zero;
- }
- else {
- low = get_range_long_argument(ilow, "start");
- if (low == NULL)
- goto Fail;
- }
-
- /* ilow and ihigh correct now; do istep */
- if (istep == NULL)
- step = PyLong_FromLong(1);
- else
- step = get_range_long_argument(istep, "step");
- if (step == NULL)
- goto Fail;
-
- if (PyObject_Cmp(step, zero, &cmp_result) == -1)
- goto Fail;
-
- if (cmp_result == 0) {
- PyErr_SetString(PyExc_ValueError,
- "range() step argument must not be zero");
- goto Fail;
- }
-
- if (cmp_result > 0)
- bign = get_len_of_range_longs(low, high, step);
- else {
- PyObject *neg_step = PyNumber_Negative(step);
- if (neg_step == NULL)
- goto Fail;
- bign = get_len_of_range_longs(high, low, neg_step);
- Py_DECREF(neg_step);
- }
-
- n = (Py_ssize_t)bign;
- if (bign < 0 || (long)n != bign) {
- PyErr_SetString(PyExc_OverflowError,
- "range() result has too many items");
- goto Fail;
- }
-
- v = PyList_New(n);
- if (v == NULL)
- goto Fail;
-
- curnum = low;
- Py_INCREF(curnum);
-
- for (i = 0; i < n; i++) {
- PyObject *w = PyNumber_Long(curnum);
- PyObject *tmp_num;
- if (w == NULL)
- goto Fail;
-
- PyList_SET_ITEM(v, i, w);
-
- tmp_num = PyNumber_Add(curnum, step);
- if (tmp_num == NULL)
- goto Fail;
-
- Py_DECREF(curnum);
- curnum = tmp_num;
- }
- Py_DECREF(low);
- Py_DECREF(high);
- Py_DECREF(step);
- Py_DECREF(zero);
- Py_DECREF(curnum);
- return v;
+ PyObject *ilow = NULL;
+ PyObject *ihigh = NULL;
+ PyObject *istep = NULL;
+
+ PyObject *low = NULL;
+ PyObject *high = NULL;
+ PyObject *step = NULL;
+
+ PyObject *curnum = NULL;
+ PyObject *v = NULL;
+ long bign;
+ Py_ssize_t i, n;
+ int cmp_result;
+
+ PyObject *zero = PyLong_FromLong(0);
+
+ if (zero == NULL)
+ return NULL;
+
+ if (!PyArg_UnpackTuple(args, "range", 1, 3, &ilow, &ihigh, &istep)) {
+ Py_DECREF(zero);
+ return NULL;
+ }
+
+ /* Figure out which way we were called, supply defaults, and be
+ * sure to incref everything so that the decrefs at the end
+ * are correct. NB: ilow, ihigh and istep are borrowed references.
+ */
+ assert(ilow != NULL);
+ if (ihigh == NULL) {
+ /* only 1 arg -- it's the upper limit */
+ ihigh = ilow;
+ ilow = NULL;
+ }
+
+ /* convert ihigh if necessary */
+ assert(ihigh != NULL);
+ high = get_range_long_argument(ihigh, "end");
+ if (high == NULL)
+ goto Fail;
+
+ /* ihigh correct now; do ilow */
+ if (ilow == NULL) {
+ Py_INCREF(zero);
+ low = zero;
+ }
+ else {
+ low = get_range_long_argument(ilow, "start");
+ if (low == NULL)
+ goto Fail;
+ }
+
+ /* ilow and ihigh correct now; do istep */
+ if (istep == NULL)
+ step = PyLong_FromLong(1);
+ else
+ step = get_range_long_argument(istep, "step");
+ if (step == NULL)
+ goto Fail;
+
+ if (PyObject_Cmp(step, zero, &cmp_result) == -1)
+ goto Fail;
+
+ if (cmp_result == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "range() step argument must not be zero");
+ goto Fail;
+ }
+
+ if (cmp_result > 0)
+ bign = get_len_of_range_longs(low, high, step);
+ else {
+ PyObject *neg_step = PyNumber_Negative(step);
+ if (neg_step == NULL)
+ goto Fail;
+ bign = get_len_of_range_longs(high, low, neg_step);
+ Py_DECREF(neg_step);
+ }
+
+ n = (Py_ssize_t)bign;
+ if (bign < 0 || (long)n != bign) {
+ PyErr_SetString(PyExc_OverflowError,
+ "range() result has too many items");
+ goto Fail;
+ }
+
+ v = PyList_New(n);
+ if (v == NULL)
+ goto Fail;
+
+ curnum = low;
+ Py_INCREF(curnum);
+
+ for (i = 0; i < n; i++) {
+ PyObject *w = PyNumber_Long(curnum);
+ PyObject *tmp_num;
+ if (w == NULL)
+ goto Fail;
+
+ PyList_SET_ITEM(v, i, w);
+
+ tmp_num = PyNumber_Add(curnum, step);
+ if (tmp_num == NULL)
+ goto Fail;
+
+ Py_DECREF(curnum);
+ curnum = tmp_num;
+ }
+ Py_DECREF(low);
+ Py_DECREF(high);
+ Py_DECREF(step);
+ Py_DECREF(zero);
+ Py_DECREF(curnum);
+ return v;
Fail:
- Py_XDECREF(low);
- Py_XDECREF(high);
- Py_XDECREF(step);
- Py_DECREF(zero);
- Py_XDECREF(curnum);
- Py_XDECREF(v);
- return NULL;
+ Py_XDECREF(low);
+ Py_XDECREF(high);
+ Py_XDECREF(step);
+ Py_DECREF(zero);
+ Py_XDECREF(curnum);
+ Py_XDECREF(v);
+ return NULL;
}
/* Return number of items in range/xrange (lo, hi, step). step > 0
@@ -1918,81 +1918,81 @@ handle_range_longs(PyObject *self, PyObject *args)
static long
get_len_of_range(long lo, long hi, long step)
{
- /* -------------------------------------------------------------
- If lo >= hi, the range is empty.
- Else if n values are in the range, the last one is
- lo + (n-1)*step, which must be <= hi-1. Rearranging,
- n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
- the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
- the RHS is non-negative and so truncation is the same as the
- floor. Letting M be the largest positive long, the worst case
- for the RHS numerator is hi=M, lo=-M-1, and then
- hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
- precision to compute the RHS exactly.
- ---------------------------------------------------------------*/
- long n = 0;
- if (lo < hi) {
- unsigned long uhi = (unsigned long)hi;
- unsigned long ulo = (unsigned long)lo;
- unsigned long diff = uhi - ulo - 1;
- n = (long)(diff / (unsigned long)step + 1);
- }
- return n;
+ /* -------------------------------------------------------------
+ If lo >= hi, the range is empty.
+ Else if n values are in the range, the last one is
+ lo + (n-1)*step, which must be <= hi-1. Rearranging,
+ n <= (hi - lo - 1)/step + 1, so taking the floor of the RHS gives
+ the proper value. Since lo < hi in this case, hi-lo-1 >= 0, so
+ the RHS is non-negative and so truncation is the same as the
+ floor. Letting M be the largest positive long, the worst case
+ for the RHS numerator is hi=M, lo=-M-1, and then
+ hi-lo-1 = M-(-M-1)-1 = 2*M. Therefore unsigned long has enough
+ precision to compute the RHS exactly.
+ ---------------------------------------------------------------*/
+ long n = 0;
+ if (lo < hi) {
+ unsigned long uhi = (unsigned long)hi;
+ unsigned long ulo = (unsigned long)lo;
+ unsigned long diff = uhi - ulo - 1;
+ n = (long)(diff / (unsigned long)step + 1);
+ }
+ return n;
}
static PyObject *
builtin_range(PyObject *self, PyObject *args)
{
- long ilow = 0, ihigh = 0, istep = 1;
- long bign;
- Py_ssize_t i, n;
-
- PyObject *v;
-
- if (PyTuple_Size(args) <= 1) {
- if (!PyArg_ParseTuple(args,
- "l;range() requires 1-3 int arguments",
- &ihigh)) {
- PyErr_Clear();
- return handle_range_longs(self, args);
- }
- }
- else {
- if (!PyArg_ParseTuple(args,
- "ll|l;range() requires 1-3 int arguments",
- &ilow, &ihigh, &istep)) {
- PyErr_Clear();
- return handle_range_longs(self, args);
- }
- }
- if (istep == 0) {
- PyErr_SetString(PyExc_ValueError,
- "range() step argument must not be zero");
- return NULL;
- }
- if (istep > 0)
- bign = get_len_of_range(ilow, ihigh, istep);
- else
- bign = get_len_of_range(ihigh, ilow, -istep);
- n = (Py_ssize_t)bign;
- if (bign < 0 || (long)n != bign) {
- PyErr_SetString(PyExc_OverflowError,
- "range() result has too many items");
- return NULL;
- }
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- for (i = 0; i < n; i++) {
- PyObject *w = PyInt_FromLong(ilow);
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SET_ITEM(v, i, w);
- ilow += istep;
- }
- return v;
+ long ilow = 0, ihigh = 0, istep = 1;
+ long bign;
+ Py_ssize_t i, n;
+
+ PyObject *v;
+
+ if (PyTuple_Size(args) <= 1) {
+ if (!PyArg_ParseTuple(args,
+ "l;range() requires 1-3 int arguments",
+ &ihigh)) {
+ PyErr_Clear();
+ return handle_range_longs(self, args);
+ }
+ }
+ else {
+ if (!PyArg_ParseTuple(args,
+ "ll|l;range() requires 1-3 int arguments",
+ &ilow, &ihigh, &istep)) {
+ PyErr_Clear();
+ return handle_range_longs(self, args);
+ }
+ }
+ if (istep == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "range() step argument must not be zero");
+ return NULL;
+ }
+ if (istep > 0)
+ bign = get_len_of_range(ilow, ihigh, istep);
+ else
+ bign = get_len_of_range(ihigh, ilow, -istep);
+ n = (Py_ssize_t)bign;
+ if (bign < 0 || (long)n != bign) {
+ PyErr_SetString(PyExc_OverflowError,
+ "range() result has too many items");
+ return NULL;
+ }
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ for (i = 0; i < n; i++) {
+ PyObject *w = PyInt_FromLong(ilow);
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SET_ITEM(v, i, w);
+ ilow += istep;
+ }
+ return v;
}
PyDoc_STRVAR(range_doc,
@@ -2008,75 +2008,75 @@ These are exactly the valid indices for a list of 4 elements.");
static PyObject *
builtin_raw_input(PyObject *self, PyObject *args)
{
- PyObject *v = NULL;
- PyObject *fin = PySys_GetObject("stdin");
- PyObject *fout = PySys_GetObject("stdout");
-
- if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
- return NULL;
-
- if (fin == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
- return NULL;
- }
- if (fout == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
- return NULL;
- }
- if (PyFile_SoftSpace(fout, 0)) {
- if (PyFile_WriteString(" ", fout) != 0)
- return NULL;
- }
- if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
- && isatty(fileno(PyFile_AsFile(fin)))
- && isatty(fileno(PyFile_AsFile(fout)))) {
- PyObject *po;
- char *prompt;
- char *s;
- PyObject *result;
- if (v != NULL) {
- po = PyObject_Str(v);
- if (po == NULL)
- return NULL;
- prompt = PyString_AsString(po);
- if (prompt == NULL)
- return NULL;
- }
- else {
- po = NULL;
- prompt = "";
- }
- s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
- prompt);
- Py_XDECREF(po);
- if (s == NULL) {
- if (!PyErr_Occurred())
- PyErr_SetNone(PyExc_KeyboardInterrupt);
- return NULL;
- }
- if (*s == '\0') {
- PyErr_SetNone(PyExc_EOFError);
- result = NULL;
- }
- else { /* strip trailing '\n' */
- size_t len = strlen(s);
- if (len > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "[raw_]input: input too long");
- result = NULL;
- }
- else {
- result = PyString_FromStringAndSize(s, len-1);
- }
- }
- PyMem_FREE(s);
- return result;
- }
- if (v != NULL) {
- if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
- return NULL;
- }
- return PyFile_GetLine(fin, -1);
+ PyObject *v = NULL;
+ PyObject *fin = PySys_GetObject("stdin");
+ PyObject *fout = PySys_GetObject("stdout");
+
+ if (!PyArg_UnpackTuple(args, "[raw_]input", 0, 1, &v))
+ return NULL;
+
+ if (fin == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdin");
+ return NULL;
+ }
+ if (fout == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "[raw_]input: lost sys.stdout");
+ return NULL;
+ }
+ if (PyFile_SoftSpace(fout, 0)) {
+ if (PyFile_WriteString(" ", fout) != 0)
+ return NULL;
+ }
+ if (PyFile_AsFile(fin) && PyFile_AsFile(fout)
+ && isatty(fileno(PyFile_AsFile(fin)))
+ && isatty(fileno(PyFile_AsFile(fout)))) {
+ PyObject *po;
+ char *prompt;
+ char *s;
+ PyObject *result;
+ if (v != NULL) {
+ po = PyObject_Str(v);
+ if (po == NULL)
+ return NULL;
+ prompt = PyString_AsString(po);
+ if (prompt == NULL)
+ return NULL;
+ }
+ else {
+ po = NULL;
+ prompt = "";
+ }
+ s = PyOS_Readline(PyFile_AsFile(fin), PyFile_AsFile(fout),
+ prompt);
+ Py_XDECREF(po);
+ if (s == NULL) {
+ if (!PyErr_Occurred())
+ PyErr_SetNone(PyExc_KeyboardInterrupt);
+ return NULL;
+ }
+ if (*s == '\0') {
+ PyErr_SetNone(PyExc_EOFError);
+ result = NULL;
+ }
+ else { /* strip trailing '\n' */
+ size_t len = strlen(s);
+ if (len > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "[raw_]input: input too long");
+ result = NULL;
+ }
+ else {
+ result = PyString_FromStringAndSize(s, len-1);
+ }
+ }
+ PyMem_FREE(s);
+ return result;
+ }
+ if (v != NULL) {
+ if (PyFile_WriteObject(v, fout, Py_PRINT_RAW) != 0)
+ return NULL;
+ }
+ return PyFile_GetLine(fin, -1);
}
PyDoc_STRVAR(raw_input_doc,
@@ -2091,22 +2091,22 @@ is printed without a trailing newline before reading.");
static PyObject *
builtin_reduce(PyObject *self, PyObject *args)
{
- static PyObject *functools_reduce = NULL;
-
- if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
- "use functools.reduce()", 1) < 0)
- return NULL;
-
- if (functools_reduce == NULL) {
- PyObject *functools = PyImport_ImportModule("functools");
- if (functools == NULL)
- return NULL;
- functools_reduce = PyObject_GetAttrString(functools, "reduce");
- Py_DECREF(functools);
- if (functools_reduce == NULL)
- return NULL;
- }
- return PyObject_Call(functools_reduce, args, NULL);
+ static PyObject *functools_reduce = NULL;
+
+ if (PyErr_WarnPy3k("reduce() not supported in 3.x; "
+ "use functools.reduce()", 1) < 0)
+ return NULL;
+
+ if (functools_reduce == NULL) {
+ PyObject *functools = PyImport_ImportModule("functools");
+ if (functools == NULL)
+ return NULL;
+ functools_reduce = PyObject_GetAttrString(functools, "reduce");
+ Py_DECREF(functools);
+ if (functools_reduce == NULL)
+ return NULL;
+ }
+ return PyObject_Call(functools_reduce, args, NULL);
}
PyDoc_STRVAR(reduce_doc,
@@ -2123,11 +2123,11 @@ sequence is empty.");
static PyObject *
builtin_reload(PyObject *self, PyObject *v)
{
- if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
- 1) < 0)
- return NULL;
+ if (PyErr_WarnPy3k("In 3.x, reload() is renamed to imp.reload()",
+ 1) < 0)
+ return NULL;
- return PyImport_ReloadModule(v);
+ return PyImport_ReloadModule(v);
}
PyDoc_STRVAR(reload_doc,
@@ -2139,7 +2139,7 @@ Reload the module. The module must have been successfully imported before.");
static PyObject *
builtin_repr(PyObject *self, PyObject *v)
{
- return PyObject_Repr(v);
+ return PyObject_Repr(v);
}
PyDoc_STRVAR(repr_doc,
@@ -2152,45 +2152,45 @@ For most object types, eval(repr(object)) == object.");
static PyObject *
builtin_round(PyObject *self, PyObject *args, PyObject *kwds)
{
- double x;
- PyObject *o_ndigits = NULL;
- Py_ssize_t ndigits;
- static char *kwlist[] = {"number", "ndigits", 0};
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
- kwlist, &x, &o_ndigits))
- return NULL;
-
- if (o_ndigits == NULL) {
- /* second argument defaults to 0 */
- ndigits = 0;
- }
- else {
- /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
- ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
- if (ndigits == -1 && PyErr_Occurred())
- return NULL;
- }
-
- /* nans, infinities and zeros round to themselves */
- if (!Py_IS_FINITE(x) || x == 0.0)
- return PyFloat_FromDouble(x);
-
- /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
- always rounds to itself. For ndigits < NDIGITS_MIN, x always
- rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
+ double x;
+ PyObject *o_ndigits = NULL;
+ Py_ssize_t ndigits;
+ static char *kwlist[] = {"number", "ndigits", 0};
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "d|O:round",
+ kwlist, &x, &o_ndigits))
+ return NULL;
+
+ if (o_ndigits == NULL) {
+ /* second argument defaults to 0 */
+ ndigits = 0;
+ }
+ else {
+ /* interpret 2nd argument as a Py_ssize_t; clip on overflow */
+ ndigits = PyNumber_AsSsize_t(o_ndigits, NULL);
+ if (ndigits == -1 && PyErr_Occurred())
+ return NULL;
+ }
+
+ /* nans, infinities and zeros round to themselves */
+ if (!Py_IS_FINITE(x) || x == 0.0)
+ return PyFloat_FromDouble(x);
+
+ /* Deal with extreme values for ndigits. For ndigits > NDIGITS_MAX, x
+ always rounds to itself. For ndigits < NDIGITS_MIN, x always
+ rounds to +-0.0. Here 0.30103 is an upper bound for log10(2). */
#define NDIGITS_MAX ((int)((DBL_MANT_DIG-DBL_MIN_EXP) * 0.30103))
#define NDIGITS_MIN (-(int)((DBL_MAX_EXP + 1) * 0.30103))
- if (ndigits > NDIGITS_MAX)
- /* return x */
- return PyFloat_FromDouble(x);
- else if (ndigits < NDIGITS_MIN)
- /* return 0.0, but with sign of x */
- return PyFloat_FromDouble(0.0*x);
- else
- /* finite x, and ndigits is not unreasonably large */
- /* _Py_double_round is defined in floatobject.c */
- return _Py_double_round(x, (int)ndigits);
+ if (ndigits > NDIGITS_MAX)
+ /* return x */
+ return PyFloat_FromDouble(x);
+ else if (ndigits < NDIGITS_MIN)
+ /* return 0.0, but with sign of x */
+ return PyFloat_FromDouble(0.0*x);
+ else
+ /* finite x, and ndigits is not unreasonably large */
+ /* _Py_double_round is defined in floatobject.c */
+ return _Py_double_round(x, (int)ndigits);
#undef NDIGITS_MAX
#undef NDIGITS_MIN
}
@@ -2204,42 +2204,42 @@ This always returns a floating point number. Precision may be negative.");
static PyObject *
builtin_sorted(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
- PyObject *callable;
- static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
- int reverse;
-
- /* args 1-4 should match listsort in Objects/listobject.c */
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
- kwlist, &seq, &compare, &keyfunc, &reverse))
- return NULL;
-
- newlist = PySequence_List(seq);
- if (newlist == NULL)
- return NULL;
-
- callable = PyObject_GetAttrString(newlist, "sort");
- if (callable == NULL) {
- Py_DECREF(newlist);
- return NULL;
- }
-
- newargs = PyTuple_GetSlice(args, 1, 4);
- if (newargs == NULL) {
- Py_DECREF(newlist);
- Py_DECREF(callable);
- return NULL;
- }
-
- v = PyObject_Call(callable, newargs, kwds);
- Py_DECREF(newargs);
- Py_DECREF(callable);
- if (v == NULL) {
- Py_DECREF(newlist);
- return NULL;
- }
- Py_DECREF(v);
- return newlist;
+ PyObject *newlist, *v, *seq, *compare=NULL, *keyfunc=NULL, *newargs;
+ PyObject *callable;
+ static char *kwlist[] = {"iterable", "cmp", "key", "reverse", 0};
+ int reverse;
+
+ /* args 1-4 should match listsort in Objects/listobject.c */
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|OOi:sorted",
+ kwlist, &seq, &compare, &keyfunc, &reverse))
+ return NULL;
+
+ newlist = PySequence_List(seq);
+ if (newlist == NULL)
+ return NULL;
+
+ callable = PyObject_GetAttrString(newlist, "sort");
+ if (callable == NULL) {
+ Py_DECREF(newlist);
+ return NULL;
+ }
+
+ newargs = PyTuple_GetSlice(args, 1, 4);
+ if (newargs == NULL) {
+ Py_DECREF(newlist);
+ Py_DECREF(callable);
+ return NULL;
+ }
+
+ v = PyObject_Call(callable, newargs, kwds);
+ Py_DECREF(newargs);
+ Py_DECREF(callable);
+ if (v == NULL) {
+ Py_DECREF(newlist);
+ return NULL;
+ }
+ Py_DECREF(v);
+ return newlist;
}
PyDoc_STRVAR(sorted_doc,
@@ -2248,30 +2248,30 @@ PyDoc_STRVAR(sorted_doc,
static PyObject *
builtin_vars(PyObject *self, PyObject *args)
{
- PyObject *v = NULL;
- PyObject *d;
-
- if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
- return NULL;
- if (v == NULL) {
- d = PyEval_GetLocals();
- if (d == NULL) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_SystemError,
- "vars(): no locals!?");
- }
- else
- Py_INCREF(d);
- }
- else {
- d = PyObject_GetAttrString(v, "__dict__");
- if (d == NULL) {
- PyErr_SetString(PyExc_TypeError,
- "vars() argument must have __dict__ attribute");
- return NULL;
- }
- }
- return d;
+ PyObject *v = NULL;
+ PyObject *d;
+
+ if (!PyArg_UnpackTuple(args, "vars", 0, 1, &v))
+ return NULL;
+ if (v == NULL) {
+ d = PyEval_GetLocals();
+ if (d == NULL) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_SystemError,
+ "vars(): no locals!?");
+ }
+ else
+ Py_INCREF(d);
+ }
+ else {
+ d = PyObject_GetAttrString(v, "__dict__");
+ if (d == NULL) {
+ PyErr_SetString(PyExc_TypeError,
+ "vars() argument must have __dict__ attribute");
+ return NULL;
+ }
+ }
+ return d;
}
PyDoc_STRVAR(vars_doc,
@@ -2284,140 +2284,140 @@ With an argument, equivalent to object.__dict__.");
static PyObject*
builtin_sum(PyObject *self, PyObject *args)
{
- PyObject *seq;
- PyObject *result = NULL;
- PyObject *temp, *item, *iter;
-
- if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
- return NULL;
-
- iter = PyObject_GetIter(seq);
- if (iter == NULL)
- return NULL;
-
- if (result == NULL) {
- result = PyInt_FromLong(0);
- if (result == NULL) {
- Py_DECREF(iter);
- return NULL;
- }
- } else {
- /* reject string values for 'start' parameter */
- if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
- PyErr_SetString(PyExc_TypeError,
- "sum() can't sum strings [use ''.join(seq) instead]");
- Py_DECREF(iter);
- return NULL;
- }
- Py_INCREF(result);
- }
+ PyObject *seq;
+ PyObject *result = NULL;
+ PyObject *temp, *item, *iter;
+
+ if (!PyArg_UnpackTuple(args, "sum", 1, 2, &seq, &result))
+ return NULL;
+
+ iter = PyObject_GetIter(seq);
+ if (iter == NULL)
+ return NULL;
+
+ if (result == NULL) {
+ result = PyInt_FromLong(0);
+ if (result == NULL) {
+ Py_DECREF(iter);
+ return NULL;
+ }
+ } else {
+ /* reject string values for 'start' parameter */
+ if (PyObject_TypeCheck(result, &PyBaseString_Type)) {
+ PyErr_SetString(PyExc_TypeError,
+ "sum() can't sum strings [use ''.join(seq) instead]");
+ Py_DECREF(iter);
+ return NULL;
+ }
+ Py_INCREF(result);
+ }
#ifndef SLOW_SUM
- /* Fast addition by keeping temporary sums in C instead of new Python objects.
- Assumes all inputs are the same type. If the assumption fails, default
- to the more general routine.
- */
- if (PyInt_CheckExact(result)) {
- long i_result = PyInt_AS_LONG(result);
- Py_DECREF(result);
- result = NULL;
- while(result == NULL) {
- item = PyIter_Next(iter);
- if (item == NULL) {
- Py_DECREF(iter);
- if (PyErr_Occurred())
- return NULL;
- return PyInt_FromLong(i_result);
- }
- if (PyInt_CheckExact(item)) {
- long b = PyInt_AS_LONG(item);
- long x = i_result + b;
- if ((x^i_result) >= 0 || (x^b) >= 0) {
- i_result = x;
- Py_DECREF(item);
- continue;
- }
- }
- /* Either overflowed or is not an int. Restore real objects and process normally */
- result = PyInt_FromLong(i_result);
- temp = PyNumber_Add(result, item);
- Py_DECREF(result);
- Py_DECREF(item);
- result = temp;
- if (result == NULL) {
- Py_DECREF(iter);
- return NULL;
- }
- }
- }
-
- if (PyFloat_CheckExact(result)) {
- double f_result = PyFloat_AS_DOUBLE(result);
- Py_DECREF(result);
- result = NULL;
- while(result == NULL) {
- item = PyIter_Next(iter);
- if (item == NULL) {
- Py_DECREF(iter);
- if (PyErr_Occurred())
- return NULL;
- return PyFloat_FromDouble(f_result);
- }
- if (PyFloat_CheckExact(item)) {
- PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
- f_result += PyFloat_AS_DOUBLE(item);
- PyFPE_END_PROTECT(f_result)
- Py_DECREF(item);
- continue;
- }
- if (PyInt_CheckExact(item)) {
- PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
- f_result += (double)PyInt_AS_LONG(item);
- PyFPE_END_PROTECT(f_result)
- Py_DECREF(item);
- continue;
- }
- result = PyFloat_FromDouble(f_result);
- temp = PyNumber_Add(result, item);
- Py_DECREF(result);
- Py_DECREF(item);
- result = temp;
- if (result == NULL) {
- Py_DECREF(iter);
- return NULL;
- }
- }
- }
+ /* Fast addition by keeping temporary sums in C instead of new Python objects.
+ Assumes all inputs are the same type. If the assumption fails, default
+ to the more general routine.
+ */
+ if (PyInt_CheckExact(result)) {
+ long i_result = PyInt_AS_LONG(result);
+ Py_DECREF(result);
+ result = NULL;
+ while(result == NULL) {
+ item = PyIter_Next(iter);
+ if (item == NULL) {
+ Py_DECREF(iter);
+ if (PyErr_Occurred())
+ return NULL;
+ return PyInt_FromLong(i_result);
+ }
+ if (PyInt_CheckExact(item)) {
+ long b = PyInt_AS_LONG(item);
+ long x = i_result + b;
+ if ((x^i_result) >= 0 || (x^b) >= 0) {
+ i_result = x;
+ Py_DECREF(item);
+ continue;
+ }
+ }
+ /* Either overflowed or is not an int. Restore real objects and process normally */
+ result = PyInt_FromLong(i_result);
+ temp = PyNumber_Add(result, item);
+ Py_DECREF(result);
+ Py_DECREF(item);
+ result = temp;
+ if (result == NULL) {
+ Py_DECREF(iter);
+ return NULL;
+ }
+ }
+ }
+
+ if (PyFloat_CheckExact(result)) {
+ double f_result = PyFloat_AS_DOUBLE(result);
+ Py_DECREF(result);
+ result = NULL;
+ while(result == NULL) {
+ item = PyIter_Next(iter);
+ if (item == NULL) {
+ Py_DECREF(iter);
+ if (PyErr_Occurred())
+ return NULL;
+ return PyFloat_FromDouble(f_result);
+ }
+ if (PyFloat_CheckExact(item)) {
+ PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
+ f_result += PyFloat_AS_DOUBLE(item);
+ PyFPE_END_PROTECT(f_result)
+ Py_DECREF(item);
+ continue;
+ }
+ if (PyInt_CheckExact(item)) {
+ PyFPE_START_PROTECT("add", Py_DECREF(item); Py_DECREF(iter); return 0)
+ f_result += (double)PyInt_AS_LONG(item);
+ PyFPE_END_PROTECT(f_result)
+ Py_DECREF(item);
+ continue;
+ }
+ result = PyFloat_FromDouble(f_result);
+ temp = PyNumber_Add(result, item);
+ Py_DECREF(result);
+ Py_DECREF(item);
+ result = temp;
+ if (result == NULL) {
+ Py_DECREF(iter);
+ return NULL;
+ }
+ }
+ }
#endif
- for(;;) {
- item = PyIter_Next(iter);
- if (item == NULL) {
- /* error, or end-of-sequence */
- if (PyErr_Occurred()) {
- Py_DECREF(result);
- result = NULL;
- }
- break;
- }
- /* It's tempting to use PyNumber_InPlaceAdd instead of
- PyNumber_Add here, to avoid quadratic running time
- when doing 'sum(list_of_lists, [])'. However, this
- would produce a change in behaviour: a snippet like
-
- empty = []
- sum([[x] for x in range(10)], empty)
-
- would change the value of empty. */
- temp = PyNumber_Add(result, item);
- Py_DECREF(result);
- Py_DECREF(item);
- result = temp;
- if (result == NULL)
- break;
- }
- Py_DECREF(iter);
- return result;
+ for(;;) {
+ item = PyIter_Next(iter);
+ if (item == NULL) {
+ /* error, or end-of-sequence */
+ if (PyErr_Occurred()) {
+ Py_DECREF(result);
+ result = NULL;
+ }
+ break;
+ }
+ /* It's tempting to use PyNumber_InPlaceAdd instead of
+ PyNumber_Add here, to avoid quadratic running time
+ when doing 'sum(list_of_lists, [])'. However, this
+ would produce a change in behaviour: a snippet like
+
+ empty = []
+ sum([[x] for x in range(10)], empty)
+
+ would change the value of empty. */
+ temp = PyNumber_Add(result, item);
+ Py_DECREF(result);
+ Py_DECREF(item);
+ result = temp;
+ if (result == NULL)
+ break;
+ }
+ Py_DECREF(iter);
+ return result;
}
PyDoc_STRVAR(sum_doc,
@@ -2431,17 +2431,17 @@ empty, returns start.");
static PyObject *
builtin_isinstance(PyObject *self, PyObject *args)
{
- PyObject *inst;
- PyObject *cls;
- int retval;
+ PyObject *inst;
+ PyObject *cls;
+ int retval;
- if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "isinstance", 2, 2, &inst, &cls))
+ return NULL;
- retval = PyObject_IsInstance(inst, cls);
- if (retval < 0)
- return NULL;
- return PyBool_FromLong(retval);
+ retval = PyObject_IsInstance(inst, cls);
+ if (retval < 0)
+ return NULL;
+ return PyBool_FromLong(retval);
}
PyDoc_STRVAR(isinstance_doc,
@@ -2456,17 +2456,17 @@ isinstance(x, A) or isinstance(x, B) or ... (etc.).");
static PyObject *
builtin_issubclass(PyObject *self, PyObject *args)
{
- PyObject *derived;
- PyObject *cls;
- int retval;
+ PyObject *derived;
+ PyObject *cls;
+ int retval;
- if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
- return NULL;
+ if (!PyArg_UnpackTuple(args, "issubclass", 2, 2, &derived, &cls))
+ return NULL;
- retval = PyObject_IsSubclass(derived, cls);
- if (retval < 0)
- return NULL;
- return PyBool_FromLong(retval);
+ retval = PyObject_IsSubclass(derived, cls);
+ if (retval < 0)
+ return NULL;
+ return PyBool_FromLong(retval);
}
PyDoc_STRVAR(issubclass_doc,
@@ -2480,104 +2480,104 @@ is a shortcut for issubclass(X, A) or issubclass(X, B) or ... (etc.).");
static PyObject*
builtin_zip(PyObject *self, PyObject *args)
{
- PyObject *ret;
- const Py_ssize_t itemsize = PySequence_Length(args);
- Py_ssize_t i;
- PyObject *itlist; /* tuple of iterators */
- Py_ssize_t len; /* guess at result length */
-
- if (itemsize == 0)
- return PyList_New(0);
-
- /* args must be a tuple */
- assert(PyTuple_Check(args));
-
- /* Guess at result length: the shortest of the input lengths.
- If some argument refuses to say, we refuse to guess too, lest
- an argument like xrange(sys.maxint) lead us astray.*/
- len = -1; /* unknown */
- for (i = 0; i < itemsize; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
- if (thislen < 0) {
- if (thislen == -1)
- return NULL;
- len = -1;
- break;
- }
- else if (len < 0 || thislen < len)
- len = thislen;
- }
-
- /* allocate result list */
- if (len < 0)
- len = 10; /* arbitrary */
- if ((ret = PyList_New(len)) == NULL)
- return NULL;
-
- /* obtain iterators */
- itlist = PyTuple_New(itemsize);
- if (itlist == NULL)
- goto Fail_ret;
- for (i = 0; i < itemsize; ++i) {
- PyObject *item = PyTuple_GET_ITEM(args, i);
- PyObject *it = PyObject_GetIter(item);
- if (it == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError))
- PyErr_Format(PyExc_TypeError,
- "zip argument #%zd must support iteration",
- i+1);
- goto Fail_ret_itlist;
- }
- PyTuple_SET_ITEM(itlist, i, it);
- }
-
- /* build result into ret list */
- for (i = 0; ; ++i) {
- int j;
- PyObject *next = PyTuple_New(itemsize);
- if (!next)
- goto Fail_ret_itlist;
-
- for (j = 0; j < itemsize; j++) {
- PyObject *it = PyTuple_GET_ITEM(itlist, j);
- PyObject *item = PyIter_Next(it);
- if (!item) {
- if (PyErr_Occurred()) {
- Py_DECREF(ret);
- ret = NULL;
- }
- Py_DECREF(next);
- Py_DECREF(itlist);
- goto Done;
- }
- PyTuple_SET_ITEM(next, j, item);
- }
-
- if (i < len)
- PyList_SET_ITEM(ret, i, next);
- else {
- int status = PyList_Append(ret, next);
- Py_DECREF(next);
- ++len;
- if (status < 0)
- goto Fail_ret_itlist;
- }
- }
+ PyObject *ret;
+ const Py_ssize_t itemsize = PySequence_Length(args);
+ Py_ssize_t i;
+ PyObject *itlist; /* tuple of iterators */
+ Py_ssize_t len; /* guess at result length */
+
+ if (itemsize == 0)
+ return PyList_New(0);
+
+ /* args must be a tuple */
+ assert(PyTuple_Check(args));
+
+ /* Guess at result length: the shortest of the input lengths.
+ If some argument refuses to say, we refuse to guess too, lest
+ an argument like xrange(sys.maxint) lead us astray.*/
+ len = -1; /* unknown */
+ for (i = 0; i < itemsize; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ Py_ssize_t thislen = _PyObject_LengthHint(item, -2);
+ if (thislen < 0) {
+ if (thislen == -1)
+ return NULL;
+ len = -1;
+ break;
+ }
+ else if (len < 0 || thislen < len)
+ len = thislen;
+ }
+
+ /* allocate result list */
+ if (len < 0)
+ len = 10; /* arbitrary */
+ if ((ret = PyList_New(len)) == NULL)
+ return NULL;
+
+ /* obtain iterators */
+ itlist = PyTuple_New(itemsize);
+ if (itlist == NULL)
+ goto Fail_ret;
+ for (i = 0; i < itemsize; ++i) {
+ PyObject *item = PyTuple_GET_ITEM(args, i);
+ PyObject *it = PyObject_GetIter(item);
+ if (it == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError))
+ PyErr_Format(PyExc_TypeError,
+ "zip argument #%zd must support iteration",
+ i+1);
+ goto Fail_ret_itlist;
+ }
+ PyTuple_SET_ITEM(itlist, i, it);
+ }
+
+ /* build result into ret list */
+ for (i = 0; ; ++i) {
+ int j;
+ PyObject *next = PyTuple_New(itemsize);
+ if (!next)
+ goto Fail_ret_itlist;
+
+ for (j = 0; j < itemsize; j++) {
+ PyObject *it = PyTuple_GET_ITEM(itlist, j);
+ PyObject *item = PyIter_Next(it);
+ if (!item) {
+ if (PyErr_Occurred()) {
+ Py_DECREF(ret);
+ ret = NULL;
+ }
+ Py_DECREF(next);
+ Py_DECREF(itlist);
+ goto Done;
+ }
+ PyTuple_SET_ITEM(next, j, item);
+ }
+
+ if (i < len)
+ PyList_SET_ITEM(ret, i, next);
+ else {
+ int status = PyList_Append(ret, next);
+ Py_DECREF(next);
+ ++len;
+ if (status < 0)
+ goto Fail_ret_itlist;
+ }
+ }
Done:
- if (ret != NULL && i < len) {
- /* The list is too big. */
- if (PyList_SetSlice(ret, i, len, NULL) < 0)
- return NULL;
- }
- return ret;
+ if (ret != NULL && i < len) {
+ /* The list is too big. */
+ if (PyList_SetSlice(ret, i, len, NULL) < 0)
+ return NULL;
+ }
+ return ret;
Fail_ret_itlist:
- Py_DECREF(itlist);
+ Py_DECREF(itlist);
Fail_ret:
- Py_DECREF(ret);
- return NULL;
+ Py_DECREF(ret);
+ return NULL;
}
@@ -2590,61 +2590,61 @@ in length to the length of the shortest argument sequence.");
static PyMethodDef builtin_methods[] = {
- {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
- {"abs", builtin_abs, METH_O, abs_doc},
- {"all", builtin_all, METH_O, all_doc},
- {"any", builtin_any, METH_O, any_doc},
- {"apply", builtin_apply, METH_VARARGS, apply_doc},
- {"bin", builtin_bin, METH_O, bin_doc},
- {"callable", builtin_callable, METH_O, callable_doc},
- {"chr", builtin_chr, METH_VARARGS, chr_doc},
- {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
- {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
- {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
- {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
- {"dir", builtin_dir, METH_VARARGS, dir_doc},
- {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
- {"eval", builtin_eval, METH_VARARGS, eval_doc},
- {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
- {"filter", builtin_filter, METH_VARARGS, filter_doc},
- {"format", builtin_format, METH_VARARGS, format_doc},
- {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
- {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
- {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
- {"hash", builtin_hash, METH_O, hash_doc},
- {"hex", builtin_hex, METH_O, hex_doc},
- {"id", builtin_id, METH_O, id_doc},
- {"input", builtin_input, METH_VARARGS, input_doc},
- {"intern", builtin_intern, METH_VARARGS, intern_doc},
- {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
- {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
- {"iter", builtin_iter, METH_VARARGS, iter_doc},
- {"len", builtin_len, METH_O, len_doc},
- {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
- {"map", builtin_map, METH_VARARGS, map_doc},
- {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
- {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
- {"next", builtin_next, METH_VARARGS, next_doc},
- {"oct", builtin_oct, METH_O, oct_doc},
- {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
- {"ord", builtin_ord, METH_O, ord_doc},
- {"pow", builtin_pow, METH_VARARGS, pow_doc},
- {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
- {"range", builtin_range, METH_VARARGS, range_doc},
- {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
- {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
- {"reload", builtin_reload, METH_O, reload_doc},
- {"repr", builtin_repr, METH_O, repr_doc},
- {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
- {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
- {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
- {"sum", builtin_sum, METH_VARARGS, sum_doc},
+ {"__import__", (PyCFunction)builtin___import__, METH_VARARGS | METH_KEYWORDS, import_doc},
+ {"abs", builtin_abs, METH_O, abs_doc},
+ {"all", builtin_all, METH_O, all_doc},
+ {"any", builtin_any, METH_O, any_doc},
+ {"apply", builtin_apply, METH_VARARGS, apply_doc},
+ {"bin", builtin_bin, METH_O, bin_doc},
+ {"callable", builtin_callable, METH_O, callable_doc},
+ {"chr", builtin_chr, METH_VARARGS, chr_doc},
+ {"cmp", builtin_cmp, METH_VARARGS, cmp_doc},
+ {"coerce", builtin_coerce, METH_VARARGS, coerce_doc},
+ {"compile", (PyCFunction)builtin_compile, METH_VARARGS | METH_KEYWORDS, compile_doc},
+ {"delattr", builtin_delattr, METH_VARARGS, delattr_doc},
+ {"dir", builtin_dir, METH_VARARGS, dir_doc},
+ {"divmod", builtin_divmod, METH_VARARGS, divmod_doc},
+ {"eval", builtin_eval, METH_VARARGS, eval_doc},
+ {"execfile", builtin_execfile, METH_VARARGS, execfile_doc},
+ {"filter", builtin_filter, METH_VARARGS, filter_doc},
+ {"format", builtin_format, METH_VARARGS, format_doc},
+ {"getattr", builtin_getattr, METH_VARARGS, getattr_doc},
+ {"globals", (PyCFunction)builtin_globals, METH_NOARGS, globals_doc},
+ {"hasattr", builtin_hasattr, METH_VARARGS, hasattr_doc},
+ {"hash", builtin_hash, METH_O, hash_doc},
+ {"hex", builtin_hex, METH_O, hex_doc},
+ {"id", builtin_id, METH_O, id_doc},
+ {"input", builtin_input, METH_VARARGS, input_doc},
+ {"intern", builtin_intern, METH_VARARGS, intern_doc},
+ {"isinstance", builtin_isinstance, METH_VARARGS, isinstance_doc},
+ {"issubclass", builtin_issubclass, METH_VARARGS, issubclass_doc},
+ {"iter", builtin_iter, METH_VARARGS, iter_doc},
+ {"len", builtin_len, METH_O, len_doc},
+ {"locals", (PyCFunction)builtin_locals, METH_NOARGS, locals_doc},
+ {"map", builtin_map, METH_VARARGS, map_doc},
+ {"max", (PyCFunction)builtin_max, METH_VARARGS | METH_KEYWORDS, max_doc},
+ {"min", (PyCFunction)builtin_min, METH_VARARGS | METH_KEYWORDS, min_doc},
+ {"next", builtin_next, METH_VARARGS, next_doc},
+ {"oct", builtin_oct, METH_O, oct_doc},
+ {"open", (PyCFunction)builtin_open, METH_VARARGS | METH_KEYWORDS, open_doc},
+ {"ord", builtin_ord, METH_O, ord_doc},
+ {"pow", builtin_pow, METH_VARARGS, pow_doc},
+ {"print", (PyCFunction)builtin_print, METH_VARARGS | METH_KEYWORDS, print_doc},
+ {"range", builtin_range, METH_VARARGS, range_doc},
+ {"raw_input", builtin_raw_input, METH_VARARGS, raw_input_doc},
+ {"reduce", builtin_reduce, METH_VARARGS, reduce_doc},
+ {"reload", builtin_reload, METH_O, reload_doc},
+ {"repr", builtin_repr, METH_O, repr_doc},
+ {"round", (PyCFunction)builtin_round, METH_VARARGS | METH_KEYWORDS, round_doc},
+ {"setattr", builtin_setattr, METH_VARARGS, setattr_doc},
+ {"sorted", (PyCFunction)builtin_sorted, METH_VARARGS | METH_KEYWORDS, sorted_doc},
+ {"sum", builtin_sum, METH_VARARGS, sum_doc},
#ifdef Py_USING_UNICODE
- {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
+ {"unichr", builtin_unichr, METH_VARARGS, unichr_doc},
#endif
- {"vars", builtin_vars, METH_VARARGS, vars_doc},
- {"zip", builtin_zip, METH_VARARGS, zip_doc},
- {NULL, NULL},
+ {"vars", builtin_vars, METH_VARARGS, vars_doc},
+ {"zip", builtin_zip, METH_VARARGS, zip_doc},
+ {NULL, NULL},
};
PyDoc_STRVAR(builtin_doc,
@@ -2655,76 +2655,76 @@ Noteworthy: None is the `nil' object; Ellipsis represents `...' in slices.");
PyObject *
_PyBuiltin_Init(void)
{
- PyObject *mod, *dict, *debug;
- mod = Py_InitModule4("__builtin__", builtin_methods,
- builtin_doc, (PyObject *)NULL,
- PYTHON_API_VERSION);
- if (mod == NULL)
- return NULL;
- dict = PyModule_GetDict(mod);
+ PyObject *mod, *dict, *debug;
+ mod = Py_InitModule4("__builtin__", builtin_methods,
+ builtin_doc, (PyObject *)NULL,
+ PYTHON_API_VERSION);
+ if (mod == NULL)
+ return NULL;
+ dict = PyModule_GetDict(mod);
#ifdef Py_TRACE_REFS
- /* __builtin__ exposes a number of statically allocated objects
- * that, before this code was added in 2.3, never showed up in
- * the list of "all objects" maintained by Py_TRACE_REFS. As a
- * result, programs leaking references to None and False (etc)
- * couldn't be diagnosed by examining sys.getobjects(0).
- */
+ /* __builtin__ exposes a number of statically allocated objects
+ * that, before this code was added in 2.3, never showed up in
+ * the list of "all objects" maintained by Py_TRACE_REFS. As a
+ * result, programs leaking references to None and False (etc)
+ * couldn't be diagnosed by examining sys.getobjects(0).
+ */
#define ADD_TO_ALL(OBJECT) _Py_AddToAllObjects((PyObject *)(OBJECT), 0)
#else
#define ADD_TO_ALL(OBJECT) (void)0
#endif
#define SETBUILTIN(NAME, OBJECT) \
- if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
- return NULL; \
- ADD_TO_ALL(OBJECT)
-
- SETBUILTIN("None", Py_None);
- SETBUILTIN("Ellipsis", Py_Ellipsis);
- SETBUILTIN("NotImplemented", Py_NotImplemented);
- SETBUILTIN("False", Py_False);
- SETBUILTIN("True", Py_True);
- SETBUILTIN("basestring", &PyBaseString_Type);
- SETBUILTIN("bool", &PyBool_Type);
- SETBUILTIN("memoryview", &PyMemoryView_Type);
- SETBUILTIN("bytearray", &PyByteArray_Type);
- SETBUILTIN("bytes", &PyString_Type);
- SETBUILTIN("buffer", &PyBuffer_Type);
- SETBUILTIN("classmethod", &PyClassMethod_Type);
+ if (PyDict_SetItemString(dict, NAME, (PyObject *)OBJECT) < 0) \
+ return NULL; \
+ ADD_TO_ALL(OBJECT)
+
+ SETBUILTIN("None", Py_None);
+ SETBUILTIN("Ellipsis", Py_Ellipsis);
+ SETBUILTIN("NotImplemented", Py_NotImplemented);
+ SETBUILTIN("False", Py_False);
+ SETBUILTIN("True", Py_True);
+ SETBUILTIN("basestring", &PyBaseString_Type);
+ SETBUILTIN("bool", &PyBool_Type);
+ SETBUILTIN("memoryview", &PyMemoryView_Type);
+ SETBUILTIN("bytearray", &PyByteArray_Type);
+ SETBUILTIN("bytes", &PyString_Type);
+ SETBUILTIN("buffer", &PyBuffer_Type);
+ SETBUILTIN("classmethod", &PyClassMethod_Type);
#ifndef WITHOUT_COMPLEX
- SETBUILTIN("complex", &PyComplex_Type);
+ SETBUILTIN("complex", &PyComplex_Type);
#endif
- SETBUILTIN("dict", &PyDict_Type);
- SETBUILTIN("enumerate", &PyEnum_Type);
- SETBUILTIN("file", &PyFile_Type);
- SETBUILTIN("float", &PyFloat_Type);
- SETBUILTIN("frozenset", &PyFrozenSet_Type);
- SETBUILTIN("property", &PyProperty_Type);
- SETBUILTIN("int", &PyInt_Type);
- SETBUILTIN("list", &PyList_Type);
- SETBUILTIN("long", &PyLong_Type);
- SETBUILTIN("object", &PyBaseObject_Type);
- SETBUILTIN("reversed", &PyReversed_Type);
- SETBUILTIN("set", &PySet_Type);
- SETBUILTIN("slice", &PySlice_Type);
- SETBUILTIN("staticmethod", &PyStaticMethod_Type);
- SETBUILTIN("str", &PyString_Type);
- SETBUILTIN("super", &PySuper_Type);
- SETBUILTIN("tuple", &PyTuple_Type);
- SETBUILTIN("type", &PyType_Type);
- SETBUILTIN("xrange", &PyRange_Type);
+ SETBUILTIN("dict", &PyDict_Type);
+ SETBUILTIN("enumerate", &PyEnum_Type);
+ SETBUILTIN("file", &PyFile_Type);
+ SETBUILTIN("float", &PyFloat_Type);
+ SETBUILTIN("frozenset", &PyFrozenSet_Type);
+ SETBUILTIN("property", &PyProperty_Type);
+ SETBUILTIN("int", &PyInt_Type);
+ SETBUILTIN("list", &PyList_Type);
+ SETBUILTIN("long", &PyLong_Type);
+ SETBUILTIN("object", &PyBaseObject_Type);
+ SETBUILTIN("reversed", &PyReversed_Type);
+ SETBUILTIN("set", &PySet_Type);
+ SETBUILTIN("slice", &PySlice_Type);
+ SETBUILTIN("staticmethod", &PyStaticMethod_Type);
+ SETBUILTIN("str", &PyString_Type);
+ SETBUILTIN("super", &PySuper_Type);
+ SETBUILTIN("tuple", &PyTuple_Type);
+ SETBUILTIN("type", &PyType_Type);
+ SETBUILTIN("xrange", &PyRange_Type);
#ifdef Py_USING_UNICODE
- SETBUILTIN("unicode", &PyUnicode_Type);
+ SETBUILTIN("unicode", &PyUnicode_Type);
#endif
- debug = PyBool_FromLong(Py_OptimizeFlag == 0);
- if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
- Py_XDECREF(debug);
- return NULL;
- }
- Py_XDECREF(debug);
-
- return mod;
+ debug = PyBool_FromLong(Py_OptimizeFlag == 0);
+ if (PyDict_SetItemString(dict, "__debug__", debug) < 0) {
+ Py_XDECREF(debug);
+ return NULL;
+ }
+ Py_XDECREF(debug);
+
+ return mod;
#undef ADD_TO_ALL
#undef SETBUILTIN
}
@@ -2734,69 +2734,69 @@ _PyBuiltin_Init(void)
static PyObject *
filtertuple(PyObject *func, PyObject *tuple)
{
- PyObject *result;
- Py_ssize_t i, j;
- Py_ssize_t len = PyTuple_Size(tuple);
-
- if (len == 0) {
- if (PyTuple_CheckExact(tuple))
- Py_INCREF(tuple);
- else
- tuple = PyTuple_New(0);
- return tuple;
- }
-
- if ((result = PyTuple_New(len)) == NULL)
- return NULL;
-
- for (i = j = 0; i < len; ++i) {
- PyObject *item, *good;
- int ok;
-
- if (tuple->ob_type->tp_as_sequence &&
- tuple->ob_type->tp_as_sequence->sq_item) {
- item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
- if (item == NULL)
- goto Fail_1;
- } else {
- PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
- goto Fail_1;
- }
- if (func == Py_None) {
- Py_INCREF(item);
- good = item;
- }
- else {
- PyObject *arg = PyTuple_Pack(1, item);
- if (arg == NULL) {
- Py_DECREF(item);
- goto Fail_1;
- }
- good = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
- if (good == NULL) {
- Py_DECREF(item);
- goto Fail_1;
- }
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- if (ok) {
- if (PyTuple_SetItem(result, j++, item) < 0)
- goto Fail_1;
- }
- else
- Py_DECREF(item);
- }
-
- if (_PyTuple_Resize(&result, j) < 0)
- return NULL;
-
- return result;
+ PyObject *result;
+ Py_ssize_t i, j;
+ Py_ssize_t len = PyTuple_Size(tuple);
+
+ if (len == 0) {
+ if (PyTuple_CheckExact(tuple))
+ Py_INCREF(tuple);
+ else
+ tuple = PyTuple_New(0);
+ return tuple;
+ }
+
+ if ((result = PyTuple_New(len)) == NULL)
+ return NULL;
+
+ for (i = j = 0; i < len; ++i) {
+ PyObject *item, *good;
+ int ok;
+
+ if (tuple->ob_type->tp_as_sequence &&
+ tuple->ob_type->tp_as_sequence->sq_item) {
+ item = tuple->ob_type->tp_as_sequence->sq_item(tuple, i);
+ if (item == NULL)
+ goto Fail_1;
+ } else {
+ PyErr_SetString(PyExc_TypeError, "filter(): unsubscriptable tuple");
+ goto Fail_1;
+ }
+ if (func == Py_None) {
+ Py_INCREF(item);
+ good = item;
+ }
+ else {
+ PyObject *arg = PyTuple_Pack(1, item);
+ if (arg == NULL) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ good = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
+ if (good == NULL) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ if (ok) {
+ if (PyTuple_SetItem(result, j++, item) < 0)
+ goto Fail_1;
+ }
+ else
+ Py_DECREF(item);
+ }
+
+ if (_PyTuple_Resize(&result, j) < 0)
+ return NULL;
+
+ return result;
Fail_1:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
@@ -2805,125 +2805,125 @@ Fail_1:
static PyObject *
filterstring(PyObject *func, PyObject *strobj)
{
- PyObject *result;
- Py_ssize_t i, j;
- Py_ssize_t len = PyString_Size(strobj);
- Py_ssize_t outlen = len;
-
- if (func == Py_None) {
- /* If it's a real string we can return the original,
- * as no character is ever false and __getitem__
- * does return this character. If it's a subclass
- * we must go through the __getitem__ loop */
- if (PyString_CheckExact(strobj)) {
- Py_INCREF(strobj);
- return strobj;
- }
- }
- if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
- return NULL;
-
- for (i = j = 0; i < len; ++i) {
- PyObject *item;
- int ok;
-
- item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
- if (item == NULL)
- goto Fail_1;
- if (func==Py_None) {
- ok = 1;
- } else {
- PyObject *arg, *good;
- arg = PyTuple_Pack(1, item);
- if (arg == NULL) {
- Py_DECREF(item);
- goto Fail_1;
- }
- good = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
- if (good == NULL) {
- Py_DECREF(item);
- goto Fail_1;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- }
- if (ok) {
- Py_ssize_t reslen;
- if (!PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
- " __getitem__ returned different type");
- Py_DECREF(item);
- goto Fail_1;
- }
- reslen = PyString_GET_SIZE(item);
- if (reslen == 1) {
- PyString_AS_STRING(result)[j++] =
- PyString_AS_STRING(item)[0];
- } else {
- /* do we need more space? */
- Py_ssize_t need = j;
-
- /* calculate space requirements while checking for overflow */
- if (need > PY_SSIZE_T_MAX - reslen) {
- Py_DECREF(item);
- goto Fail_1;
- }
-
- need += reslen;
-
- if (need > PY_SSIZE_T_MAX - len) {
- Py_DECREF(item);
- goto Fail_1;
- }
-
- need += len;
-
- if (need <= i) {
- Py_DECREF(item);
- goto Fail_1;
- }
-
- need = need - i - 1;
-
- assert(need >= 0);
- assert(outlen >= 0);
-
- if (need > outlen) {
- /* overallocate, to avoid reallocations */
- if (outlen > PY_SSIZE_T_MAX / 2) {
- Py_DECREF(item);
- return NULL;
- }
-
- if (need<2*outlen) {
- need = 2*outlen;
- }
- if (_PyString_Resize(&result, need)) {
- Py_DECREF(item);
- return NULL;
- }
- outlen = need;
- }
- memcpy(
- PyString_AS_STRING(result) + j,
- PyString_AS_STRING(item),
- reslen
- );
- j += reslen;
- }
- }
- Py_DECREF(item);
- }
-
- if (j < outlen)
- _PyString_Resize(&result, j);
-
- return result;
+ PyObject *result;
+ Py_ssize_t i, j;
+ Py_ssize_t len = PyString_Size(strobj);
+ Py_ssize_t outlen = len;
+
+ if (func == Py_None) {
+ /* If it's a real string we can return the original,
+ * as no character is ever false and __getitem__
+ * does return this character. If it's a subclass
+ * we must go through the __getitem__ loop */
+ if (PyString_CheckExact(strobj)) {
+ Py_INCREF(strobj);
+ return strobj;
+ }
+ }
+ if ((result = PyString_FromStringAndSize(NULL, len)) == NULL)
+ return NULL;
+
+ for (i = j = 0; i < len; ++i) {
+ PyObject *item;
+ int ok;
+
+ item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
+ if (item == NULL)
+ goto Fail_1;
+ if (func==Py_None) {
+ ok = 1;
+ } else {
+ PyObject *arg, *good;
+ arg = PyTuple_Pack(1, item);
+ if (arg == NULL) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ good = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
+ if (good == NULL) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ }
+ if (ok) {
+ Py_ssize_t reslen;
+ if (!PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError, "can't filter str to str:"
+ " __getitem__ returned different type");
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ reslen = PyString_GET_SIZE(item);
+ if (reslen == 1) {
+ PyString_AS_STRING(result)[j++] =
+ PyString_AS_STRING(item)[0];
+ } else {
+ /* do we need more space? */
+ Py_ssize_t need = j;
+
+ /* calculate space requirements while checking for overflow */
+ if (need > PY_SSIZE_T_MAX - reslen) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+
+ need += reslen;
+
+ if (need > PY_SSIZE_T_MAX - len) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+
+ need += len;
+
+ if (need <= i) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+
+ need = need - i - 1;
+
+ assert(need >= 0);
+ assert(outlen >= 0);
+
+ if (need > outlen) {
+ /* overallocate, to avoid reallocations */
+ if (outlen > PY_SSIZE_T_MAX / 2) {
+ Py_DECREF(item);
+ return NULL;
+ }
+
+ if (need<2*outlen) {
+ need = 2*outlen;
+ }
+ if (_PyString_Resize(&result, need)) {
+ Py_DECREF(item);
+ return NULL;
+ }
+ outlen = need;
+ }
+ memcpy(
+ PyString_AS_STRING(result) + j,
+ PyString_AS_STRING(item),
+ reslen
+ );
+ j += reslen;
+ }
+ }
+ Py_DECREF(item);
+ }
+
+ if (j < outlen)
+ _PyString_Resize(&result, j);
+
+ return result;
Fail_1:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
#ifdef Py_USING_UNICODE
@@ -2932,112 +2932,112 @@ Fail_1:
static PyObject *
filterunicode(PyObject *func, PyObject *strobj)
{
- PyObject *result;
- register Py_ssize_t i, j;
- Py_ssize_t len = PyUnicode_GetSize(strobj);
- Py_ssize_t outlen = len;
-
- if (func == Py_None) {
- /* If it's a real string we can return the original,
- * as no character is ever false and __getitem__
- * does return this character. If it's a subclass
- * we must go through the __getitem__ loop */
- if (PyUnicode_CheckExact(strobj)) {
- Py_INCREF(strobj);
- return strobj;
- }
- }
- if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
- return NULL;
-
- for (i = j = 0; i < len; ++i) {
- PyObject *item, *arg, *good;
- int ok;
-
- item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
- if (item == NULL)
- goto Fail_1;
- if (func == Py_None) {
- ok = 1;
- } else {
- arg = PyTuple_Pack(1, item);
- if (arg == NULL) {
- Py_DECREF(item);
- goto Fail_1;
- }
- good = PyEval_CallObject(func, arg);
- Py_DECREF(arg);
- if (good == NULL) {
- Py_DECREF(item);
- goto Fail_1;
- }
- ok = PyObject_IsTrue(good);
- Py_DECREF(good);
- }
- if (ok) {
- Py_ssize_t reslen;
- if (!PyUnicode_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "can't filter unicode to unicode:"
- " __getitem__ returned different type");
- Py_DECREF(item);
- goto Fail_1;
- }
- reslen = PyUnicode_GET_SIZE(item);
- if (reslen == 1)
- PyUnicode_AS_UNICODE(result)[j++] =
- PyUnicode_AS_UNICODE(item)[0];
- else {
- /* do we need more space? */
- Py_ssize_t need = j + reslen + len - i - 1;
-
- /* check that didnt overflow */
- if ((j > PY_SSIZE_T_MAX - reslen) ||
- ((j + reslen) > PY_SSIZE_T_MAX - len) ||
- ((j + reslen + len) < i) ||
- ((j + reslen + len - i) <= 0)) {
- Py_DECREF(item);
- return NULL;
- }
-
- assert(need >= 0);
- assert(outlen >= 0);
-
- if (need > outlen) {
- /* overallocate,
- to avoid reallocations */
- if (need < 2 * outlen) {
- if (outlen > PY_SSIZE_T_MAX / 2) {
- Py_DECREF(item);
- return NULL;
- } else {
- need = 2 * outlen;
- }
- }
-
- if (PyUnicode_Resize(
- &result, need) < 0) {
- Py_DECREF(item);
- goto Fail_1;
- }
- outlen = need;
- }
- memcpy(PyUnicode_AS_UNICODE(result) + j,
- PyUnicode_AS_UNICODE(item),
- reslen*sizeof(Py_UNICODE));
- j += reslen;
- }
- }
- Py_DECREF(item);
- }
-
- if (j < outlen)
- PyUnicode_Resize(&result, j);
-
- return result;
+ PyObject *result;
+ register Py_ssize_t i, j;
+ Py_ssize_t len = PyUnicode_GetSize(strobj);
+ Py_ssize_t outlen = len;
+
+ if (func == Py_None) {
+ /* If it's a real string we can return the original,
+ * as no character is ever false and __getitem__
+ * does return this character. If it's a subclass
+ * we must go through the __getitem__ loop */
+ if (PyUnicode_CheckExact(strobj)) {
+ Py_INCREF(strobj);
+ return strobj;
+ }
+ }
+ if ((result = PyUnicode_FromUnicode(NULL, len)) == NULL)
+ return NULL;
+
+ for (i = j = 0; i < len; ++i) {
+ PyObject *item, *arg, *good;
+ int ok;
+
+ item = (*strobj->ob_type->tp_as_sequence->sq_item)(strobj, i);
+ if (item == NULL)
+ goto Fail_1;
+ if (func == Py_None) {
+ ok = 1;
+ } else {
+ arg = PyTuple_Pack(1, item);
+ if (arg == NULL) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ good = PyEval_CallObject(func, arg);
+ Py_DECREF(arg);
+ if (good == NULL) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ ok = PyObject_IsTrue(good);
+ Py_DECREF(good);
+ }
+ if (ok) {
+ Py_ssize_t reslen;
+ if (!PyUnicode_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't filter unicode to unicode:"
+ " __getitem__ returned different type");
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ reslen = PyUnicode_GET_SIZE(item);
+ if (reslen == 1)
+ PyUnicode_AS_UNICODE(result)[j++] =
+ PyUnicode_AS_UNICODE(item)[0];
+ else {
+ /* do we need more space? */
+ Py_ssize_t need = j + reslen + len - i - 1;
+
+ /* check that didnt overflow */
+ if ((j > PY_SSIZE_T_MAX - reslen) ||
+ ((j + reslen) > PY_SSIZE_T_MAX - len) ||
+ ((j + reslen + len) < i) ||
+ ((j + reslen + len - i) <= 0)) {
+ Py_DECREF(item);
+ return NULL;
+ }
+
+ assert(need >= 0);
+ assert(outlen >= 0);
+
+ if (need > outlen) {
+ /* overallocate,
+ to avoid reallocations */
+ if (need < 2 * outlen) {
+ if (outlen > PY_SSIZE_T_MAX / 2) {
+ Py_DECREF(item);
+ return NULL;
+ } else {
+ need = 2 * outlen;
+ }
+ }
+
+ if (PyUnicode_Resize(
+ &result, need) < 0) {
+ Py_DECREF(item);
+ goto Fail_1;
+ }
+ outlen = need;
+ }
+ memcpy(PyUnicode_AS_UNICODE(result) + j,
+ PyUnicode_AS_UNICODE(item),
+ reslen*sizeof(Py_UNICODE));
+ j += reslen;
+ }
+ }
+ Py_DECREF(item);
+ }
+
+ if (j < outlen)
+ PyUnicode_Resize(&result, j);
+
+ return result;
Fail_1:
- Py_DECREF(result);
- return NULL;
+ Py_DECREF(result);
+ return NULL;
}
#endif
diff --git a/Python/ceval.c b/Python/ceval.c
index 2b64cae..a27cfc1 100644
--- a/Python/ceval.c
+++ b/Python/ceval.c
@@ -28,27 +28,27 @@
typedef unsigned long long uint64;
#if defined(__ppc__) /* <- Don't know if this is the correct symbol; this
- section should work for GCC on any PowerPC
- platform, irrespective of OS.
- POWER? Who knows :-) */
+ section should work for GCC on any PowerPC
+ platform, irrespective of OS.
+ POWER? Who knows :-) */
#define READ_TIMESTAMP(var) ppc_getcounter(&var)
static void
ppc_getcounter(uint64 *v)
{
- register unsigned long tbu, tb, tbu2;
+ register unsigned long tbu, tb, tbu2;
loop:
- asm volatile ("mftbu %0" : "=r" (tbu) );
- asm volatile ("mftb %0" : "=r" (tb) );
- asm volatile ("mftbu %0" : "=r" (tbu2));
- if (__builtin_expect(tbu != tbu2, 0)) goto loop;
-
- /* The slightly peculiar way of writing the next lines is
- compiled better by GCC than any other way I tried. */
- ((long*)(v))[0] = tbu;
- ((long*)(v))[1] = tb;
+ asm volatile ("mftbu %0" : "=r" (tbu) );
+ asm volatile ("mftb %0" : "=r" (tb) );
+ asm volatile ("mftbu %0" : "=r" (tbu2));
+ if (__builtin_expect(tbu != tbu2, 0)) goto loop;
+
+ /* The slightly peculiar way of writing the next lines is
+ compiled better by GCC than any other way I tried. */
+ ((long*)(v))[0] = tbu;
+ ((long*)(v))[1] = tb;
}
#elif defined(__i386__)
@@ -77,17 +77,17 @@ ppc_getcounter(uint64 *v)
#endif
void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1,
- uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1)
+ uint64 loop0, uint64 loop1, uint64 intr0, uint64 intr1)
{
- uint64 intr, inst, loop;
- PyThreadState *tstate = PyThreadState_Get();
- if (!tstate->interp->tscdump)
- return;
- intr = intr1 - intr0;
- inst = inst1 - inst0 - intr;
- loop = loop1 - loop0 - intr;
- fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
- opcode, ticked, inst, loop);
+ uint64 intr, inst, loop;
+ PyThreadState *tstate = PyThreadState_Get();
+ if (!tstate->interp->tscdump)
+ return;
+ intr = intr1 - intr0;
+ inst = inst1 - inst0 - intr;
+ loop = loop1 - loop0 - intr;
+ fprintf(stderr, "opcode=%03d t=%d inst=%06lld loop=%06lld\n",
+ opcode, ticked, inst, loop);
}
#endif
@@ -97,8 +97,8 @@ void dump_tsc(int opcode, int ticked, uint64 inst0, uint64 inst1,
#ifdef Py_DEBUG
/* For debugging the interpreter: */
-#define LLTRACE 1 /* Low-level trace feature */
-#define CHECKEXC 1 /* Double-check exception checking */
+#define LLTRACE 1 /* Low-level trace feature */
+#define CHECKEXC 1 /* Double-check exception checking */
#endif
typedef PyObject *(*callproc)(PyObject *, PyObject *, PyObject *);
@@ -113,7 +113,7 @@ static PyObject * fast_function(PyObject *, PyObject ***, int, int, int);
static PyObject * do_call(PyObject *, PyObject ***, int, int);
static PyObject * ext_do_call(PyObject *, PyObject ***, int, int, int);
static PyObject * update_keyword_args(PyObject *, int, PyObject ***,
- PyObject *);
+ PyObject *);
static PyObject * update_star_args(int, int, PyObject *, PyObject ***);
static PyObject * load_args(PyObject ***, int);
#define CALL_FLAG_VAR 1
@@ -124,39 +124,39 @@ static int lltrace;
static int prtrace(PyObject *, char *);
#endif
static int call_trace(Py_tracefunc, PyObject *, PyFrameObject *,
- int, PyObject *);
+ int, PyObject *);
static int call_trace_protected(Py_tracefunc, PyObject *,
- PyFrameObject *, int, PyObject *);
+ PyFrameObject *, int, PyObject *);
static void call_exc_trace(Py_tracefunc, PyObject *, PyFrameObject *);
static int maybe_call_line_trace(Py_tracefunc, PyObject *,
- PyFrameObject *, int *, int *, int *);
+ PyFrameObject *, int *, int *, int *);
static PyObject * apply_slice(PyObject *, PyObject *, PyObject *);
static int assign_slice(PyObject *, PyObject *,
- PyObject *, PyObject *);
+ PyObject *, PyObject *);
static PyObject * cmp_outcome(int, PyObject *, PyObject *);
static PyObject * import_from(PyObject *, PyObject *);
static int import_all_from(PyObject *, PyObject *);
static PyObject * build_class(PyObject *, PyObject *, PyObject *);
static int exec_statement(PyFrameObject *,
- PyObject *, PyObject *, PyObject *);
+ PyObject *, PyObject *, PyObject *);
static void set_exc_info(PyThreadState *, PyObject *, PyObject *, PyObject *);
static void reset_exc_info(PyThreadState *);
static void format_exc_check_arg(PyObject *, char *, PyObject *);
static PyObject * string_concatenate(PyObject *, PyObject *,
- PyFrameObject *, unsigned char *);
+ PyFrameObject *, unsigned char *);
static PyObject * kwd_as_string(PyObject *);
static PyObject * special_lookup(PyObject *, char *, PyObject **);
#define NAME_ERROR_MSG \
- "name '%.200s' is not defined"
+ "name '%.200s' is not defined"
#define GLOBAL_NAME_ERROR_MSG \
- "global name '%.200s' is not defined"
+ "global name '%.200s' is not defined"
#define UNBOUNDLOCAL_ERROR_MSG \
- "local variable '%.200s' referenced before assignment"
+ "local variable '%.200s' referenced before assignment"
#define UNBOUNDFREE_ERROR_MSG \
- "free variable '%.200s' referenced before assignment" \
- " in enclosing scope"
+ "free variable '%.200s' referenced before assignment" \
+ " in enclosing scope"
/* Dynamic execution profile */
#ifdef DYNAMIC_EXECUTION_PROFILE
@@ -208,10 +208,10 @@ static int pcall[PCALL_NUM];
PyObject *
PyEval_GetCallStats(PyObject *self)
{
- return Py_BuildValue("iiiiiiiiiii",
- pcall[0], pcall[1], pcall[2], pcall[3],
- pcall[4], pcall[5], pcall[6], pcall[7],
- pcall[8], pcall[9], pcall[10]);
+ return Py_BuildValue("iiiiiiiiiii",
+ pcall[0], pcall[1], pcall[2], pcall[3],
+ pcall[4], pcall[5], pcall[6], pcall[7],
+ pcall[8], pcall[9], pcall[10]);
}
#else
#define PCALL(O)
@@ -219,8 +219,8 @@ PyEval_GetCallStats(PyObject *self)
PyObject *
PyEval_GetCallStats(PyObject *self)
{
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif
@@ -239,52 +239,52 @@ static long main_thread = 0;
int
PyEval_ThreadsInitialized(void)
{
- return interpreter_lock != 0;
+ return interpreter_lock != 0;
}
void
PyEval_InitThreads(void)
{
- if (interpreter_lock)
- return;
- interpreter_lock = PyThread_allocate_lock();
- PyThread_acquire_lock(interpreter_lock, 1);
- main_thread = PyThread_get_thread_ident();
+ if (interpreter_lock)
+ return;
+ interpreter_lock = PyThread_allocate_lock();
+ PyThread_acquire_lock(interpreter_lock, 1);
+ main_thread = PyThread_get_thread_ident();
}
void
PyEval_AcquireLock(void)
{
- PyThread_acquire_lock(interpreter_lock, 1);
+ PyThread_acquire_lock(interpreter_lock, 1);
}
void
PyEval_ReleaseLock(void)
{
- PyThread_release_lock(interpreter_lock);
+ PyThread_release_lock(interpreter_lock);
}
void
PyEval_AcquireThread(PyThreadState *tstate)
{
- if (tstate == NULL)
- Py_FatalError("PyEval_AcquireThread: NULL new thread state");
- /* Check someone has called PyEval_InitThreads() to create the lock */
- assert(interpreter_lock);
- PyThread_acquire_lock(interpreter_lock, 1);
- if (PyThreadState_Swap(tstate) != NULL)
- Py_FatalError(
- "PyEval_AcquireThread: non-NULL old thread state");
+ if (tstate == NULL)
+ Py_FatalError("PyEval_AcquireThread: NULL new thread state");
+ /* Check someone has called PyEval_InitThreads() to create the lock */
+ assert(interpreter_lock);
+ PyThread_acquire_lock(interpreter_lock, 1);
+ if (PyThreadState_Swap(tstate) != NULL)
+ Py_FatalError(
+ "PyEval_AcquireThread: non-NULL old thread state");
}
void
PyEval_ReleaseThread(PyThreadState *tstate)
{
- if (tstate == NULL)
- Py_FatalError("PyEval_ReleaseThread: NULL thread state");
- if (PyThreadState_Swap(NULL) != tstate)
- Py_FatalError("PyEval_ReleaseThread: wrong thread state");
- PyThread_release_lock(interpreter_lock);
+ if (tstate == NULL)
+ Py_FatalError("PyEval_ReleaseThread: NULL thread state");
+ if (PyThreadState_Swap(NULL) != tstate)
+ Py_FatalError("PyEval_ReleaseThread: wrong thread state");
+ PyThread_release_lock(interpreter_lock);
}
/* This function is called from PyOS_AfterFork to ensure that newly
@@ -295,36 +295,36 @@ PyEval_ReleaseThread(PyThreadState *tstate)
void
PyEval_ReInitThreads(void)
{
- PyObject *threading, *result;
- PyThreadState *tstate;
-
- if (!interpreter_lock)
- return;
- /*XXX Can't use PyThread_free_lock here because it does too
- much error-checking. Doing this cleanly would require
- adding a new function to each thread_*.h. Instead, just
- create a new lock and waste a little bit of memory */
- interpreter_lock = PyThread_allocate_lock();
- pending_lock = PyThread_allocate_lock();
- PyThread_acquire_lock(interpreter_lock, 1);
- main_thread = PyThread_get_thread_ident();
-
- /* Update the threading module with the new state.
- */
- tstate = PyThreadState_GET();
- threading = PyMapping_GetItemString(tstate->interp->modules,
- "threading");
- if (threading == NULL) {
- /* threading not imported */
- PyErr_Clear();
- return;
- }
- result = PyObject_CallMethod(threading, "_after_fork", NULL);
- if (result == NULL)
- PyErr_WriteUnraisable(threading);
- else
- Py_DECREF(result);
- Py_DECREF(threading);
+ PyObject *threading, *result;
+ PyThreadState *tstate;
+
+ if (!interpreter_lock)
+ return;
+ /*XXX Can't use PyThread_free_lock here because it does too
+ much error-checking. Doing this cleanly would require
+ adding a new function to each thread_*.h. Instead, just
+ create a new lock and waste a little bit of memory */
+ interpreter_lock = PyThread_allocate_lock();
+ pending_lock = PyThread_allocate_lock();
+ PyThread_acquire_lock(interpreter_lock, 1);
+ main_thread = PyThread_get_thread_ident();
+
+ /* Update the threading module with the new state.
+ */
+ tstate = PyThreadState_GET();
+ threading = PyMapping_GetItemString(tstate->interp->modules,
+ "threading");
+ if (threading == NULL) {
+ /* threading not imported */
+ PyErr_Clear();
+ return;
+ }
+ result = PyObject_CallMethod(threading, "_after_fork", NULL);
+ if (result == NULL)
+ PyErr_WriteUnraisable(threading);
+ else
+ Py_DECREF(result);
+ Py_DECREF(threading);
}
#endif
@@ -335,29 +335,29 @@ PyEval_ReInitThreads(void)
PyThreadState *
PyEval_SaveThread(void)
{
- PyThreadState *tstate = PyThreadState_Swap(NULL);
- if (tstate == NULL)
- Py_FatalError("PyEval_SaveThread: NULL tstate");
+ PyThreadState *tstate = PyThreadState_Swap(NULL);
+ if (tstate == NULL)
+ Py_FatalError("PyEval_SaveThread: NULL tstate");
#ifdef WITH_THREAD
- if (interpreter_lock)
- PyThread_release_lock(interpreter_lock);
+ if (interpreter_lock)
+ PyThread_release_lock(interpreter_lock);
#endif
- return tstate;
+ return tstate;
}
void
PyEval_RestoreThread(PyThreadState *tstate)
{
- if (tstate == NULL)
- Py_FatalError("PyEval_RestoreThread: NULL tstate");
+ if (tstate == NULL)
+ Py_FatalError("PyEval_RestoreThread: NULL tstate");
#ifdef WITH_THREAD
- if (interpreter_lock) {
- int err = errno;
- PyThread_acquire_lock(interpreter_lock, 1);
- errno = err;
- }
+ if (interpreter_lock) {
+ int err = errno;
+ PyThread_acquire_lock(interpreter_lock, 1);
+ errno = err;
+ }
#endif
- PyThreadState_Swap(tstate);
+ PyThreadState_Swap(tstate);
}
@@ -394,8 +394,8 @@ PyEval_RestoreThread(PyThreadState *tstate)
#define NPENDINGCALLS 32
static struct {
- int (*func)(void *);
- void *arg;
+ int (*func)(void *);
+ void *arg;
} pendingcalls[NPENDINGCALLS];
static int pendingfirst = 0;
static int pendinglast = 0;
@@ -405,93 +405,93 @@ static char pendingbusy = 0;
int
Py_AddPendingCall(int (*func)(void *), void *arg)
{
- int i, j, result=0;
- PyThread_type_lock lock = pending_lock;
-
- /* try a few times for the lock. Since this mechanism is used
- * for signal handling (on the main thread), there is a (slim)
- * chance that a signal is delivered on the same thread while we
- * hold the lock during the Py_MakePendingCalls() function.
- * This avoids a deadlock in that case.
- * Note that signals can be delivered on any thread. In particular,
- * on Windows, a SIGINT is delivered on a system-created worker
- * thread.
- * We also check for lock being NULL, in the unlikely case that
- * this function is called before any bytecode evaluation takes place.
- */
- if (lock != NULL) {
- for (i = 0; i<100; i++) {
- if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
- break;
- }
- if (i == 100)
- return -1;
- }
-
- i = pendinglast;
- j = (i + 1) % NPENDINGCALLS;
- if (j == pendingfirst) {
- result = -1; /* Queue full */
- } else {
- pendingcalls[i].func = func;
- pendingcalls[i].arg = arg;
- pendinglast = j;
- }
- /* signal main loop */
- _Py_Ticker = 0;
- pendingcalls_to_do = 1;
- if (lock != NULL)
- PyThread_release_lock(lock);
- return result;
+ int i, j, result=0;
+ PyThread_type_lock lock = pending_lock;
+
+ /* try a few times for the lock. Since this mechanism is used
+ * for signal handling (on the main thread), there is a (slim)
+ * chance that a signal is delivered on the same thread while we
+ * hold the lock during the Py_MakePendingCalls() function.
+ * This avoids a deadlock in that case.
+ * Note that signals can be delivered on any thread. In particular,
+ * on Windows, a SIGINT is delivered on a system-created worker
+ * thread.
+ * We also check for lock being NULL, in the unlikely case that
+ * this function is called before any bytecode evaluation takes place.
+ */
+ if (lock != NULL) {
+ for (i = 0; i<100; i++) {
+ if (PyThread_acquire_lock(lock, NOWAIT_LOCK))
+ break;
+ }
+ if (i == 100)
+ return -1;
+ }
+
+ i = pendinglast;
+ j = (i + 1) % NPENDINGCALLS;
+ if (j == pendingfirst) {
+ result = -1; /* Queue full */
+ } else {
+ pendingcalls[i].func = func;
+ pendingcalls[i].arg = arg;
+ pendinglast = j;
+ }
+ /* signal main loop */
+ _Py_Ticker = 0;
+ pendingcalls_to_do = 1;
+ if (lock != NULL)
+ PyThread_release_lock(lock);
+ return result;
}
int
Py_MakePendingCalls(void)
{
- int i;
- int r = 0;
-
- if (!pending_lock) {
- /* initial allocation of the lock */
- pending_lock = PyThread_allocate_lock();
- if (pending_lock == NULL)
- return -1;
- }
-
- /* only service pending calls on main thread */
- if (main_thread && PyThread_get_thread_ident() != main_thread)
- return 0;
- /* don't perform recursive pending calls */
- if (pendingbusy)
- return 0;
- pendingbusy = 1;
- /* perform a bounded number of calls, in case of recursion */
- for (i=0; i<NPENDINGCALLS; i++) {
- int j;
- int (*func)(void *);
- void *arg = NULL;
-
- /* pop one item off the queue while holding the lock */
- PyThread_acquire_lock(pending_lock, WAIT_LOCK);
- j = pendingfirst;
- if (j == pendinglast) {
- func = NULL; /* Queue empty */
- } else {
- func = pendingcalls[j].func;
- arg = pendingcalls[j].arg;
- pendingfirst = (j + 1) % NPENDINGCALLS;
- }
- pendingcalls_to_do = pendingfirst != pendinglast;
- PyThread_release_lock(pending_lock);
- /* having released the lock, perform the callback */
- if (func == NULL)
- break;
- r = func(arg);
- if (r)
- break;
- }
- pendingbusy = 0;
- return r;
+ int i;
+ int r = 0;
+
+ if (!pending_lock) {
+ /* initial allocation of the lock */
+ pending_lock = PyThread_allocate_lock();
+ if (pending_lock == NULL)
+ return -1;
+ }
+
+ /* only service pending calls on main thread */
+ if (main_thread && PyThread_get_thread_ident() != main_thread)
+ return 0;
+ /* don't perform recursive pending calls */
+ if (pendingbusy)
+ return 0;
+ pendingbusy = 1;
+ /* perform a bounded number of calls, in case of recursion */
+ for (i=0; i<NPENDINGCALLS; i++) {
+ int j;
+ int (*func)(void *);
+ void *arg = NULL;
+
+ /* pop one item off the queue while holding the lock */
+ PyThread_acquire_lock(pending_lock, WAIT_LOCK);
+ j = pendingfirst;
+ if (j == pendinglast) {
+ func = NULL; /* Queue empty */
+ } else {
+ func = pendingcalls[j].func;
+ arg = pendingcalls[j].arg;
+ pendingfirst = (j + 1) % NPENDINGCALLS;
+ }
+ pendingcalls_to_do = pendingfirst != pendinglast;
+ PyThread_release_lock(pending_lock);
+ /* having released the lock, perform the callback */
+ if (func == NULL)
+ break;
+ r = func(arg);
+ if (r)
+ break;
+ }
+ pendingbusy = 0;
+ return r;
}
#else /* if ! defined WITH_THREAD */
@@ -502,11 +502,11 @@ Py_MakePendingCalls(void)
with WITH_THREAD.
Don't use this implementation when Py_AddPendingCalls() can happen
on a different thread!
-
+
There are two possible race conditions:
(1) nested asynchronous calls to Py_AddPendingCall()
(2) AddPendingCall() calls made while pending calls are being processed.
-
+
(1) is very unlikely because typically signal delivery
is blocked during signal handling. So it should be impossible.
(2) is a real possibility.
@@ -521,8 +521,8 @@ Py_MakePendingCalls(void)
#define NPENDINGCALLS 32
static struct {
- int (*func)(void *);
- void *arg;
+ int (*func)(void *);
+ void *arg;
} pendingcalls[NPENDINGCALLS];
static volatile int pendingfirst = 0;
static volatile int pendinglast = 0;
@@ -531,55 +531,55 @@ static volatile int pendingcalls_to_do = 0;
int
Py_AddPendingCall(int (*func)(void *), void *arg)
{
- static volatile int busy = 0;
- int i, j;
- /* XXX Begin critical section */
- if (busy)
- return -1;
- busy = 1;
- i = pendinglast;
- j = (i + 1) % NPENDINGCALLS;
- if (j == pendingfirst) {
- busy = 0;
- return -1; /* Queue full */
- }
- pendingcalls[i].func = func;
- pendingcalls[i].arg = arg;
- pendinglast = j;
-
- _Py_Ticker = 0;
- pendingcalls_to_do = 1; /* Signal main loop */
- busy = 0;
- /* XXX End critical section */
- return 0;
+ static volatile int busy = 0;
+ int i, j;
+ /* XXX Begin critical section */
+ if (busy)
+ return -1;
+ busy = 1;
+ i = pendinglast;
+ j = (i + 1) % NPENDINGCALLS;
+ if (j == pendingfirst) {
+ busy = 0;
+ return -1; /* Queue full */
+ }
+ pendingcalls[i].func = func;
+ pendingcalls[i].arg = arg;
+ pendinglast = j;
+
+ _Py_Ticker = 0;
+ pendingcalls_to_do = 1; /* Signal main loop */
+ busy = 0;
+ /* XXX End critical section */
+ return 0;
}
int
Py_MakePendingCalls(void)
{
- static int busy = 0;
- if (busy)
- return 0;
- busy = 1;
- pendingcalls_to_do = 0;
- for (;;) {
- int i;
- int (*func)(void *);
- void *arg;
- i = pendingfirst;
- if (i == pendinglast)
- break; /* Queue empty */
- func = pendingcalls[i].func;
- arg = pendingcalls[i].arg;
- pendingfirst = (i + 1) % NPENDINGCALLS;
- if (func(arg) < 0) {
- busy = 0;
- pendingcalls_to_do = 1; /* We're not done yet */
- return -1;
- }
- }
- busy = 0;
- return 0;
+ static int busy = 0;
+ if (busy)
+ return 0;
+ busy = 1;
+ pendingcalls_to_do = 0;
+ for (;;) {
+ int i;
+ int (*func)(void *);
+ void *arg;
+ i = pendingfirst;
+ if (i == pendinglast)
+ break; /* Queue empty */
+ func = pendingcalls[i].func;
+ arg = pendingcalls[i].arg;
+ pendingfirst = (i + 1) % NPENDINGCALLS;
+ if (func(arg) < 0) {
+ busy = 0;
+ pendingcalls_to_do = 1; /* We're not done yet */
+ return -1;
+ }
+ }
+ busy = 0;
+ return 0;
}
#endif /* WITH_THREAD */
@@ -596,14 +596,14 @@ int _Py_CheckRecursionLimit = Py_DEFAULT_RECURSION_LIMIT;
int
Py_GetRecursionLimit(void)
{
- return recursion_limit;
+ return recursion_limit;
}
void
Py_SetRecursionLimit(int new_limit)
{
- recursion_limit = new_limit;
- _Py_CheckRecursionLimit = recursion_limit;
+ recursion_limit = new_limit;
+ _Py_CheckRecursionLimit = recursion_limit;
}
/* the macro Py_EnterRecursiveCall() only calls _Py_CheckRecursiveCall()
@@ -614,35 +614,35 @@ Py_SetRecursionLimit(int new_limit)
int
_Py_CheckRecursiveCall(char *where)
{
- PyThreadState *tstate = PyThreadState_GET();
+ PyThreadState *tstate = PyThreadState_GET();
#ifdef USE_STACKCHECK
- if (PyOS_CheckStack()) {
- --tstate->recursion_depth;
- PyErr_SetString(PyExc_MemoryError, "Stack overflow");
- return -1;
- }
+ if (PyOS_CheckStack()) {
+ --tstate->recursion_depth;
+ PyErr_SetString(PyExc_MemoryError, "Stack overflow");
+ return -1;
+ }
#endif
- if (tstate->recursion_depth > recursion_limit) {
- --tstate->recursion_depth;
- PyErr_Format(PyExc_RuntimeError,
- "maximum recursion depth exceeded%s",
- where);
- return -1;
- }
- _Py_CheckRecursionLimit = recursion_limit;
- return 0;
+ if (tstate->recursion_depth > recursion_limit) {
+ --tstate->recursion_depth;
+ PyErr_Format(PyExc_RuntimeError,
+ "maximum recursion depth exceeded%s",
+ where);
+ return -1;
+ }
+ _Py_CheckRecursionLimit = recursion_limit;
+ return 0;
}
/* Status code for main loop (reason for stack unwind) */
enum why_code {
- WHY_NOT = 0x0001, /* No error */
- WHY_EXCEPTION = 0x0002, /* Exception occurred */
- WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */
- WHY_RETURN = 0x0008, /* 'return' statement */
- WHY_BREAK = 0x0010, /* 'break' statement */
- WHY_CONTINUE = 0x0020, /* 'continue' statement */
- WHY_YIELD = 0x0040 /* 'yield' operator */
+ WHY_NOT = 0x0001, /* No error */
+ WHY_EXCEPTION = 0x0002, /* Exception occurred */
+ WHY_RERAISE = 0x0004, /* Exception re-raised by 'finally' */
+ WHY_RETURN = 0x0008, /* 'return' statement */
+ WHY_BREAK = 0x0010, /* 'break' statement */
+ WHY_CONTINUE = 0x0020, /* 'continue' statement */
+ WHY_YIELD = 0x0040 /* 'yield' operator */
};
static enum why_code do_raise(PyObject *, PyObject *, PyObject *);
@@ -663,12 +663,12 @@ volatile int _Py_Ticker = 0; /* so that we hit a "tick" first thing */
PyObject *
PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
{
- return PyEval_EvalCodeEx(co,
- globals, locals,
- (PyObject **)NULL, 0,
- (PyObject **)NULL, 0,
- (PyObject **)NULL, 0,
- NULL);
+ return PyEval_EvalCodeEx(co,
+ globals, locals,
+ (PyObject **)NULL, 0,
+ (PyObject **)NULL, 0,
+ (PyObject **)NULL, 0,
+ NULL);
}
@@ -676,50 +676,50 @@ PyEval_EvalCode(PyCodeObject *co, PyObject *globals, PyObject *locals)
PyObject *
PyEval_EvalFrame(PyFrameObject *f) {
- /* This is for backward compatibility with extension modules that
- used this API; core interpreter code should call
- PyEval_EvalFrameEx() */
- return PyEval_EvalFrameEx(f, 0);
+ /* This is for backward compatibility with extension modules that
+ used this API; core interpreter code should call
+ PyEval_EvalFrameEx() */
+ return PyEval_EvalFrameEx(f, 0);
}
PyObject *
PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
{
#ifdef DXPAIRS
- int lastopcode = 0;
+ int lastopcode = 0;
#endif
- register PyObject **stack_pointer; /* Next free slot in value stack */
- register unsigned char *next_instr;
- register int opcode; /* Current opcode */
- register int oparg; /* Current opcode argument, if any */
- register enum why_code why; /* Reason for block stack unwind */
- register int err; /* Error status -- nonzero if error */
- register PyObject *x; /* Result object -- NULL if error */
- register PyObject *v; /* Temporary objects popped off stack */
- register PyObject *w;
- register PyObject *u;
- register PyObject *t;
- register PyObject *stream = NULL; /* for PRINT opcodes */
- register PyObject **fastlocals, **freevars;
- PyObject *retval = NULL; /* Return value */
- PyThreadState *tstate = PyThreadState_GET();
- PyCodeObject *co;
-
- /* when tracing we set things up so that
-
- not (instr_lb <= current_bytecode_offset < instr_ub)
-
- is true when the line being executed has changed. The
- initial values are such as to make this false the first
- time it is tested. */
- int instr_ub = -1, instr_lb = 0, instr_prev = -1;
-
- unsigned char *first_instr;
- PyObject *names;
- PyObject *consts;
+ register PyObject **stack_pointer; /* Next free slot in value stack */
+ register unsigned char *next_instr;
+ register int opcode; /* Current opcode */
+ register int oparg; /* Current opcode argument, if any */
+ register enum why_code why; /* Reason for block stack unwind */
+ register int err; /* Error status -- nonzero if error */
+ register PyObject *x; /* Result object -- NULL if error */
+ register PyObject *v; /* Temporary objects popped off stack */
+ register PyObject *w;
+ register PyObject *u;
+ register PyObject *t;
+ register PyObject *stream = NULL; /* for PRINT opcodes */
+ register PyObject **fastlocals, **freevars;
+ PyObject *retval = NULL; /* Return value */
+ PyThreadState *tstate = PyThreadState_GET();
+ PyCodeObject *co;
+
+ /* when tracing we set things up so that
+
+ not (instr_lb <= current_bytecode_offset < instr_ub)
+
+ is true when the line being executed has changed. The
+ initial values are such as to make this false the first
+ time it is tested. */
+ int instr_ub = -1, instr_lb = 0, instr_prev = -1;
+
+ unsigned char *first_instr;
+ PyObject *names;
+ PyObject *consts;
#if defined(Py_DEBUG) || defined(LLTRACE)
- /* Make it easier to find out where we are with a debugger */
- char *filename;
+ /* Make it easier to find out where we are with a debugger */
+ char *filename;
#endif
/* Tuple access macros */
@@ -759,100 +759,100 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
CALL_FUNCTION (and friends)
*/
- uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0;
- int ticked = 0;
+ uint64 inst0, inst1, loop0, loop1, intr0 = 0, intr1 = 0;
+ int ticked = 0;
- READ_TIMESTAMP(inst0);
- READ_TIMESTAMP(inst1);
- READ_TIMESTAMP(loop0);
- READ_TIMESTAMP(loop1);
+ READ_TIMESTAMP(inst0);
+ READ_TIMESTAMP(inst1);
+ READ_TIMESTAMP(loop0);
+ READ_TIMESTAMP(loop1);
- /* shut up the compiler */
- opcode = 0;
+ /* shut up the compiler */
+ opcode = 0;
#endif
/* Code access macros */
-#define INSTR_OFFSET() ((int)(next_instr - first_instr))
-#define NEXTOP() (*next_instr++)
-#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
-#define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
-#define JUMPTO(x) (next_instr = first_instr + (x))
-#define JUMPBY(x) (next_instr += (x))
+#define INSTR_OFFSET() ((int)(next_instr - first_instr))
+#define NEXTOP() (*next_instr++)
+#define NEXTARG() (next_instr += 2, (next_instr[-1]<<8) + next_instr[-2])
+#define PEEKARG() ((next_instr[2]<<8) + next_instr[1])
+#define JUMPTO(x) (next_instr = first_instr + (x))
+#define JUMPBY(x) (next_instr += (x))
/* OpCode prediction macros
- Some opcodes tend to come in pairs thus making it possible to
- predict the second code when the first is run. For example,
- GET_ITER is often followed by FOR_ITER. And FOR_ITER is often
- followed by STORE_FAST or UNPACK_SEQUENCE.
-
- Verifying the prediction costs a single high-speed test of a register
- variable against a constant. If the pairing was good, then the
- processor's own internal branch predication has a high likelihood of
- success, resulting in a nearly zero-overhead transition to the
- next opcode. A successful prediction saves a trip through the eval-loop
- including its two unpredictable branches, the HAS_ARG test and the
- switch-case. Combined with the processor's internal branch prediction,
- a successful PREDICT has the effect of making the two opcodes run as if
- they were a single new opcode with the bodies combined.
+ Some opcodes tend to come in pairs thus making it possible to
+ predict the second code when the first is run. For example,
+ GET_ITER is often followed by FOR_ITER. And FOR_ITER is often
+ followed by STORE_FAST or UNPACK_SEQUENCE.
+
+ Verifying the prediction costs a single high-speed test of a register
+ variable against a constant. If the pairing was good, then the
+ processor's own internal branch predication has a high likelihood of
+ success, resulting in a nearly zero-overhead transition to the
+ next opcode. A successful prediction saves a trip through the eval-loop
+ including its two unpredictable branches, the HAS_ARG test and the
+ switch-case. Combined with the processor's internal branch prediction,
+ a successful PREDICT has the effect of making the two opcodes run as if
+ they were a single new opcode with the bodies combined.
If collecting opcode statistics, your choices are to either keep the
- predictions turned-on and interpret the results as if some opcodes
- had been combined or turn-off predictions so that the opcode frequency
- counter updates for both opcodes.
+ predictions turned-on and interpret the results as if some opcodes
+ had been combined or turn-off predictions so that the opcode frequency
+ counter updates for both opcodes.
*/
#ifdef DYNAMIC_EXECUTION_PROFILE
-#define PREDICT(op) if (0) goto PRED_##op
+#define PREDICT(op) if (0) goto PRED_##op
#else
-#define PREDICT(op) if (*next_instr == op) goto PRED_##op
+#define PREDICT(op) if (*next_instr == op) goto PRED_##op
#endif
-#define PREDICTED(op) PRED_##op: next_instr++
-#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
+#define PREDICTED(op) PRED_##op: next_instr++
+#define PREDICTED_WITH_ARG(op) PRED_##op: oparg = PEEKARG(); next_instr += 3
/* Stack manipulation macros */
/* The stack can grow at most MAXINT deep, as co_nlocals and
co_stacksize are ints. */
-#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
-#define EMPTY() (STACK_LEVEL() == 0)
-#define TOP() (stack_pointer[-1])
-#define SECOND() (stack_pointer[-2])
-#define THIRD() (stack_pointer[-3])
-#define FOURTH() (stack_pointer[-4])
+#define STACK_LEVEL() ((int)(stack_pointer - f->f_valuestack))
+#define EMPTY() (STACK_LEVEL() == 0)
+#define TOP() (stack_pointer[-1])
+#define SECOND() (stack_pointer[-2])
+#define THIRD() (stack_pointer[-3])
+#define FOURTH() (stack_pointer[-4])
#define PEEK(n) (stack_pointer[-(n)])
-#define SET_TOP(v) (stack_pointer[-1] = (v))
-#define SET_SECOND(v) (stack_pointer[-2] = (v))
-#define SET_THIRD(v) (stack_pointer[-3] = (v))
-#define SET_FOURTH(v) (stack_pointer[-4] = (v))
+#define SET_TOP(v) (stack_pointer[-1] = (v))
+#define SET_SECOND(v) (stack_pointer[-2] = (v))
+#define SET_THIRD(v) (stack_pointer[-3] = (v))
+#define SET_FOURTH(v) (stack_pointer[-4] = (v))
#define SET_VALUE(n, v) (stack_pointer[-(n)] = (v))
-#define BASIC_STACKADJ(n) (stack_pointer += n)
-#define BASIC_PUSH(v) (*stack_pointer++ = (v))
-#define BASIC_POP() (*--stack_pointer)
+#define BASIC_STACKADJ(n) (stack_pointer += n)
+#define BASIC_PUSH(v) (*stack_pointer++ = (v))
+#define BASIC_POP() (*--stack_pointer)
#ifdef LLTRACE
-#define PUSH(v) { (void)(BASIC_PUSH(v), \
- lltrace && prtrace(TOP(), "push")); \
- assert(STACK_LEVEL() <= co->co_stacksize); }
-#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
- BASIC_POP())
-#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
- lltrace && prtrace(TOP(), "stackadj")); \
- assert(STACK_LEVEL() <= co->co_stacksize); }
+#define PUSH(v) { (void)(BASIC_PUSH(v), \
+ lltrace && prtrace(TOP(), "push")); \
+ assert(STACK_LEVEL() <= co->co_stacksize); }
+#define POP() ((void)(lltrace && prtrace(TOP(), "pop")), \
+ BASIC_POP())
+#define STACKADJ(n) { (void)(BASIC_STACKADJ(n), \
+ lltrace && prtrace(TOP(), "stackadj")); \
+ assert(STACK_LEVEL() <= co->co_stacksize); }
#define EXT_POP(STACK_POINTER) ((void)(lltrace && \
- prtrace((STACK_POINTER)[-1], "ext_pop")), \
- *--(STACK_POINTER))
+ prtrace((STACK_POINTER)[-1], "ext_pop")), \
+ *--(STACK_POINTER))
#else
-#define PUSH(v) BASIC_PUSH(v)
-#define POP() BASIC_POP()
-#define STACKADJ(n) BASIC_STACKADJ(n)
+#define PUSH(v) BASIC_PUSH(v)
+#define POP() BASIC_POP()
+#define STACKADJ(n) BASIC_STACKADJ(n)
#define EXT_POP(STACK_POINTER) (*--(STACK_POINTER))
#endif
/* Local variable macros */
-#define GETLOCAL(i) (fastlocals[i])
+#define GETLOCAL(i) (fastlocals[i])
/* The SETLOCAL() macro must not DECREF the local variable in-place and
then store the new value; it must copy the old value to a temporary
@@ -860,2150 +860,2150 @@ PyEval_EvalFrameEx(PyFrameObject *f, int throwflag)
This is because it is possible that during the DECREF the frame is
accessed by other code (e.g. a __del__ method or gc.collect()) and the
variable would be pointing to already-freed memory. */
-#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
- GETLOCAL(i) = value; \
- Py_XDECREF(tmp); } while (0)
+#define SETLOCAL(i, value) do { PyObject *tmp = GETLOCAL(i); \
+ GETLOCAL(i) = value; \
+ Py_XDECREF(tmp); } while (0)
/* Start of code */
- if (f == NULL)
- return NULL;
-
- /* push frame */
- if (Py_EnterRecursiveCall(""))
- return NULL;
-
- tstate->frame = f;
-
- if (tstate->use_tracing) {
- if (tstate->c_tracefunc != NULL) {
- /* tstate->c_tracefunc, if defined, is a
- function that will be called on *every* entry
- to a code block. Its return value, if not
- None, is a function that will be called at
- the start of each executed line of code.
- (Actually, the function must return itself
- in order to continue tracing.) The trace
- functions are called with three arguments:
- a pointer to the current frame, a string
- indicating why the function is called, and
- an argument which depends on the situation.
- The global trace function is also called
- whenever an exception is detected. */
- if (call_trace_protected(tstate->c_tracefunc,
- tstate->c_traceobj,
- f, PyTrace_CALL, Py_None)) {
- /* Trace function raised an error */
- goto exit_eval_frame;
- }
- }
- if (tstate->c_profilefunc != NULL) {
- /* Similar for c_profilefunc, except it needn't
- return itself and isn't called for "line" events */
- if (call_trace_protected(tstate->c_profilefunc,
- tstate->c_profileobj,
- f, PyTrace_CALL, Py_None)) {
- /* Profile function raised an error */
- goto exit_eval_frame;
- }
- }
- }
-
- co = f->f_code;
- names = co->co_names;
- consts = co->co_consts;
- fastlocals = f->f_localsplus;
- freevars = f->f_localsplus + co->co_nlocals;
- first_instr = (unsigned char*) PyString_AS_STRING(co->co_code);
- /* An explanation is in order for the next line.
-
- f->f_lasti now refers to the index of the last instruction
- executed. You might think this was obvious from the name, but
- this wasn't always true before 2.3! PyFrame_New now sets
- f->f_lasti to -1 (i.e. the index *before* the first instruction)
- and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
- does work. Promise.
-
- When the PREDICT() macros are enabled, some opcode pairs follow in
- direct succession without updating f->f_lasti. A successful
- prediction effectively links the two codes together as if they
- were a single new opcode; accordingly,f->f_lasti will point to
- the first code in the pair (for instance, GET_ITER followed by
- FOR_ITER is effectively a single opcode and f->f_lasti will point
- at to the beginning of the combined pair.)
- */
- next_instr = first_instr + f->f_lasti + 1;
- stack_pointer = f->f_stacktop;
- assert(stack_pointer != NULL);
- f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
+ if (f == NULL)
+ return NULL;
+
+ /* push frame */
+ if (Py_EnterRecursiveCall(""))
+ return NULL;
+
+ tstate->frame = f;
+
+ if (tstate->use_tracing) {
+ if (tstate->c_tracefunc != NULL) {
+ /* tstate->c_tracefunc, if defined, is a
+ function that will be called on *every* entry
+ to a code block. Its return value, if not
+ None, is a function that will be called at
+ the start of each executed line of code.
+ (Actually, the function must return itself
+ in order to continue tracing.) The trace
+ functions are called with three arguments:
+ a pointer to the current frame, a string
+ indicating why the function is called, and
+ an argument which depends on the situation.
+ The global trace function is also called
+ whenever an exception is detected. */
+ if (call_trace_protected(tstate->c_tracefunc,
+ tstate->c_traceobj,
+ f, PyTrace_CALL, Py_None)) {
+ /* Trace function raised an error */
+ goto exit_eval_frame;
+ }
+ }
+ if (tstate->c_profilefunc != NULL) {
+ /* Similar for c_profilefunc, except it needn't
+ return itself and isn't called for "line" events */
+ if (call_trace_protected(tstate->c_profilefunc,
+ tstate->c_profileobj,
+ f, PyTrace_CALL, Py_None)) {
+ /* Profile function raised an error */
+ goto exit_eval_frame;
+ }
+ }
+ }
+
+ co = f->f_code;
+ names = co->co_names;
+ consts = co->co_consts;
+ fastlocals = f->f_localsplus;
+ freevars = f->f_localsplus + co->co_nlocals;
+ first_instr = (unsigned char*) PyString_AS_STRING(co->co_code);
+ /* An explanation is in order for the next line.
+
+ f->f_lasti now refers to the index of the last instruction
+ executed. You might think this was obvious from the name, but
+ this wasn't always true before 2.3! PyFrame_New now sets
+ f->f_lasti to -1 (i.e. the index *before* the first instruction)
+ and YIELD_VALUE doesn't fiddle with f_lasti any more. So this
+ does work. Promise.
+
+ When the PREDICT() macros are enabled, some opcode pairs follow in
+ direct succession without updating f->f_lasti. A successful
+ prediction effectively links the two codes together as if they
+ were a single new opcode; accordingly,f->f_lasti will point to
+ the first code in the pair (for instance, GET_ITER followed by
+ FOR_ITER is effectively a single opcode and f->f_lasti will point
+ at to the beginning of the combined pair.)
+ */
+ next_instr = first_instr + f->f_lasti + 1;
+ stack_pointer = f->f_stacktop;
+ assert(stack_pointer != NULL);
+ f->f_stacktop = NULL; /* remains NULL unless yield suspends frame */
#ifdef LLTRACE
- lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
+ lltrace = PyDict_GetItemString(f->f_globals, "__lltrace__") != NULL;
#endif
#if defined(Py_DEBUG) || defined(LLTRACE)
- filename = PyString_AsString(co->co_filename);
+ filename = PyString_AsString(co->co_filename);
#endif
- why = WHY_NOT;
- err = 0;
- x = Py_None; /* Not a reference, just anything non-NULL */
- w = NULL;
+ why = WHY_NOT;
+ err = 0;
+ x = Py_None; /* Not a reference, just anything non-NULL */
+ w = NULL;
- if (throwflag) { /* support for generator.throw() */
- why = WHY_EXCEPTION;
- goto on_error;
- }
+ if (throwflag) { /* support for generator.throw() */
+ why = WHY_EXCEPTION;
+ goto on_error;
+ }
- for (;;) {
+ for (;;) {
#ifdef WITH_TSC
- if (inst1 == 0) {
- /* Almost surely, the opcode executed a break
- or a continue, preventing inst1 from being set
- on the way out of the loop.
- */
- READ_TIMESTAMP(inst1);
- loop1 = inst1;
- }
- dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
- intr0, intr1);
- ticked = 0;
- inst1 = 0;
- intr0 = 0;
- intr1 = 0;
- READ_TIMESTAMP(loop0);
+ if (inst1 == 0) {
+ /* Almost surely, the opcode executed a break
+ or a continue, preventing inst1 from being set
+ on the way out of the loop.
+ */
+ READ_TIMESTAMP(inst1);
+ loop1 = inst1;
+ }
+ dump_tsc(opcode, ticked, inst0, inst1, loop0, loop1,
+ intr0, intr1);
+ ticked = 0;
+ inst1 = 0;
+ intr0 = 0;
+ intr1 = 0;
+ READ_TIMESTAMP(loop0);
#endif
- assert(stack_pointer >= f->f_valuestack); /* else underflow */
- assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
-
- /* Do periodic things. Doing this every time through
- the loop would add too much overhead, so we do it
- only every Nth instruction. We also do it if
- ``pendingcalls_to_do'' is set, i.e. when an asynchronous
- event needs attention (e.g. a signal handler or
- async I/O handler); see Py_AddPendingCall() and
- Py_MakePendingCalls() above. */
-
- if (--_Py_Ticker < 0) {
- if (*next_instr == SETUP_FINALLY) {
- /* Make the last opcode before
- a try: finally: block uninterruptable. */
- goto fast_next_opcode;
- }
- _Py_Ticker = _Py_CheckInterval;
- tstate->tick_counter++;
+ assert(stack_pointer >= f->f_valuestack); /* else underflow */
+ assert(STACK_LEVEL() <= co->co_stacksize); /* else overflow */
+
+ /* Do periodic things. Doing this every time through
+ the loop would add too much overhead, so we do it
+ only every Nth instruction. We also do it if
+ ``pendingcalls_to_do'' is set, i.e. when an asynchronous
+ event needs attention (e.g. a signal handler or
+ async I/O handler); see Py_AddPendingCall() and
+ Py_MakePendingCalls() above. */
+
+ if (--_Py_Ticker < 0) {
+ if (*next_instr == SETUP_FINALLY) {
+ /* Make the last opcode before
+ a try: finally: block uninterruptable. */
+ goto fast_next_opcode;
+ }
+ _Py_Ticker = _Py_CheckInterval;
+ tstate->tick_counter++;
#ifdef WITH_TSC
- ticked = 1;
+ ticked = 1;
#endif
- if (pendingcalls_to_do) {
- if (Py_MakePendingCalls() < 0) {
- why = WHY_EXCEPTION;
- goto on_error;
- }
- if (pendingcalls_to_do)
- /* MakePendingCalls() didn't succeed.
- Force early re-execution of this
- "periodic" code, possibly after
- a thread switch */
- _Py_Ticker = 0;
- }
+ if (pendingcalls_to_do) {
+ if (Py_MakePendingCalls() < 0) {
+ why = WHY_EXCEPTION;
+ goto on_error;
+ }
+ if (pendingcalls_to_do)
+ /* MakePendingCalls() didn't succeed.
+ Force early re-execution of this
+ "periodic" code, possibly after
+ a thread switch */
+ _Py_Ticker = 0;
+ }
#ifdef WITH_THREAD
- if (interpreter_lock) {
- /* Give another thread a chance */
-
- if (PyThreadState_Swap(NULL) != tstate)
- Py_FatalError("ceval: tstate mix-up");
- PyThread_release_lock(interpreter_lock);
-
- /* Other threads may run now */
-
- PyThread_acquire_lock(interpreter_lock, 1);
- if (PyThreadState_Swap(tstate) != NULL)
- Py_FatalError("ceval: orphan tstate");
-
- /* Check for thread interrupts */
-
- if (tstate->async_exc != NULL) {
- x = tstate->async_exc;
- tstate->async_exc = NULL;
- PyErr_SetNone(x);
- Py_DECREF(x);
- why = WHY_EXCEPTION;
- goto on_error;
- }
- }
+ if (interpreter_lock) {
+ /* Give another thread a chance */
+
+ if (PyThreadState_Swap(NULL) != tstate)
+ Py_FatalError("ceval: tstate mix-up");
+ PyThread_release_lock(interpreter_lock);
+
+ /* Other threads may run now */
+
+ PyThread_acquire_lock(interpreter_lock, 1);
+ if (PyThreadState_Swap(tstate) != NULL)
+ Py_FatalError("ceval: orphan tstate");
+
+ /* Check for thread interrupts */
+
+ if (tstate->async_exc != NULL) {
+ x = tstate->async_exc;
+ tstate->async_exc = NULL;
+ PyErr_SetNone(x);
+ Py_DECREF(x);
+ why = WHY_EXCEPTION;
+ goto on_error;
+ }
+ }
#endif
- }
-
- fast_next_opcode:
- f->f_lasti = INSTR_OFFSET();
-
- /* line-by-line tracing support */
-
- if (_Py_TracingPossible &&
- tstate->c_tracefunc != NULL && !tstate->tracing) {
- /* see maybe_call_line_trace
- for expository comments */
- f->f_stacktop = stack_pointer;
-
- err = maybe_call_line_trace(tstate->c_tracefunc,
- tstate->c_traceobj,
- f, &instr_lb, &instr_ub,
- &instr_prev);
- /* Reload possibly changed frame fields */
- JUMPTO(f->f_lasti);
- if (f->f_stacktop != NULL) {
- stack_pointer = f->f_stacktop;
- f->f_stacktop = NULL;
- }
- if (err) {
- /* trace function raised an exception */
- goto on_error;
- }
- }
-
- /* Extract opcode and argument */
-
- opcode = NEXTOP();
- oparg = 0; /* allows oparg to be stored in a register because
- it doesn't have to be remembered across a full loop */
- if (HAS_ARG(opcode))
- oparg = NEXTARG();
- dispatch_opcode:
+ }
+
+ fast_next_opcode:
+ f->f_lasti = INSTR_OFFSET();
+
+ /* line-by-line tracing support */
+
+ if (_Py_TracingPossible &&
+ tstate->c_tracefunc != NULL && !tstate->tracing) {
+ /* see maybe_call_line_trace
+ for expository comments */
+ f->f_stacktop = stack_pointer;
+
+ err = maybe_call_line_trace(tstate->c_tracefunc,
+ tstate->c_traceobj,
+ f, &instr_lb, &instr_ub,
+ &instr_prev);
+ /* Reload possibly changed frame fields */
+ JUMPTO(f->f_lasti);
+ if (f->f_stacktop != NULL) {
+ stack_pointer = f->f_stacktop;
+ f->f_stacktop = NULL;
+ }
+ if (err) {
+ /* trace function raised an exception */
+ goto on_error;
+ }
+ }
+
+ /* Extract opcode and argument */
+
+ opcode = NEXTOP();
+ oparg = 0; /* allows oparg to be stored in a register because
+ it doesn't have to be remembered across a full loop */
+ if (HAS_ARG(opcode))
+ oparg = NEXTARG();
+ dispatch_opcode:
#ifdef DYNAMIC_EXECUTION_PROFILE
#ifdef DXPAIRS
- dxpairs[lastopcode][opcode]++;
- lastopcode = opcode;
+ dxpairs[lastopcode][opcode]++;
+ lastopcode = opcode;
#endif
- dxp[opcode]++;
+ dxp[opcode]++;
#endif
#ifdef LLTRACE
- /* Instruction tracing */
-
- if (lltrace) {
- if (HAS_ARG(opcode)) {
- printf("%d: %d, %d\n",
- f->f_lasti, opcode, oparg);
- }
- else {
- printf("%d: %d\n",
- f->f_lasti, opcode);
- }
- }
+ /* Instruction tracing */
+
+ if (lltrace) {
+ if (HAS_ARG(opcode)) {
+ printf("%d: %d, %d\n",
+ f->f_lasti, opcode, oparg);
+ }
+ else {
+ printf("%d: %d\n",
+ f->f_lasti, opcode);
+ }
+ }
#endif
- /* Main switch on opcode */
- READ_TIMESTAMP(inst0);
-
- switch (opcode) {
-
- /* BEWARE!
- It is essential that any operation that fails sets either
- x to NULL, err to nonzero, or why to anything but WHY_NOT,
- and that no operation that succeeds does this! */
-
- /* case STOP_CODE: this is an error! */
-
- case NOP:
- goto fast_next_opcode;
-
- case LOAD_FAST:
- x = GETLOCAL(oparg);
- if (x != NULL) {
- Py_INCREF(x);
- PUSH(x);
- goto fast_next_opcode;
- }
- format_exc_check_arg(PyExc_UnboundLocalError,
- UNBOUNDLOCAL_ERROR_MSG,
- PyTuple_GetItem(co->co_varnames, oparg));
- break;
-
- case LOAD_CONST:
- x = GETITEM(consts, oparg);
- Py_INCREF(x);
- PUSH(x);
- goto fast_next_opcode;
-
- PREDICTED_WITH_ARG(STORE_FAST);
- case STORE_FAST:
- v = POP();
- SETLOCAL(oparg, v);
- goto fast_next_opcode;
-
- case POP_TOP:
- v = POP();
- Py_DECREF(v);
- goto fast_next_opcode;
-
- case ROT_TWO:
- v = TOP();
- w = SECOND();
- SET_TOP(w);
- SET_SECOND(v);
- goto fast_next_opcode;
-
- case ROT_THREE:
- v = TOP();
- w = SECOND();
- x = THIRD();
- SET_TOP(w);
- SET_SECOND(x);
- SET_THIRD(v);
- goto fast_next_opcode;
-
- case ROT_FOUR:
- u = TOP();
- v = SECOND();
- w = THIRD();
- x = FOURTH();
- SET_TOP(v);
- SET_SECOND(w);
- SET_THIRD(x);
- SET_FOURTH(u);
- goto fast_next_opcode;
-
- case DUP_TOP:
- v = TOP();
- Py_INCREF(v);
- PUSH(v);
- goto fast_next_opcode;
-
- case DUP_TOPX:
- if (oparg == 2) {
- x = TOP();
- Py_INCREF(x);
- w = SECOND();
- Py_INCREF(w);
- STACKADJ(2);
- SET_TOP(x);
- SET_SECOND(w);
- goto fast_next_opcode;
- } else if (oparg == 3) {
- x = TOP();
- Py_INCREF(x);
- w = SECOND();
- Py_INCREF(w);
- v = THIRD();
- Py_INCREF(v);
- STACKADJ(3);
- SET_TOP(x);
- SET_SECOND(w);
- SET_THIRD(v);
- goto fast_next_opcode;
- }
- Py_FatalError("invalid argument to DUP_TOPX"
- " (bytecode corruption?)");
- /* Never returns, so don't bother to set why. */
- break;
-
- case UNARY_POSITIVE:
- v = TOP();
- x = PyNumber_Positive(v);
- Py_DECREF(v);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case UNARY_NEGATIVE:
- v = TOP();
- x = PyNumber_Negative(v);
- Py_DECREF(v);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case UNARY_NOT:
- v = TOP();
- err = PyObject_IsTrue(v);
- Py_DECREF(v);
- if (err == 0) {
- Py_INCREF(Py_True);
- SET_TOP(Py_True);
- continue;
- }
- else if (err > 0) {
- Py_INCREF(Py_False);
- SET_TOP(Py_False);
- err = 0;
- continue;
- }
- STACKADJ(-1);
- break;
-
- case UNARY_CONVERT:
- v = TOP();
- x = PyObject_Repr(v);
- Py_DECREF(v);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case UNARY_INVERT:
- v = TOP();
- x = PyNumber_Invert(v);
- Py_DECREF(v);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_POWER:
- w = POP();
- v = TOP();
- x = PyNumber_Power(v, w, Py_None);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_MULTIPLY:
- w = POP();
- v = TOP();
- x = PyNumber_Multiply(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_DIVIDE:
- if (!_Py_QnewFlag) {
- w = POP();
- v = TOP();
- x = PyNumber_Divide(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
- }
- /* -Qnew is in effect: fall through to
- BINARY_TRUE_DIVIDE */
- case BINARY_TRUE_DIVIDE:
- w = POP();
- v = TOP();
- x = PyNumber_TrueDivide(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_FLOOR_DIVIDE:
- w = POP();
- v = TOP();
- x = PyNumber_FloorDivide(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_MODULO:
- w = POP();
- v = TOP();
- if (PyString_CheckExact(v))
- x = PyString_Format(v, w);
- else
- x = PyNumber_Remainder(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_ADD:
- w = POP();
- v = TOP();
- if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
- /* INLINE: int + int */
- register long a, b, i;
- a = PyInt_AS_LONG(v);
- b = PyInt_AS_LONG(w);
- /* cast to avoid undefined behaviour
- on overflow */
- i = (long)((unsigned long)a + b);
- if ((i^a) < 0 && (i^b) < 0)
- goto slow_add;
- x = PyInt_FromLong(i);
- }
- else if (PyString_CheckExact(v) &&
- PyString_CheckExact(w)) {
- x = string_concatenate(v, w, f, next_instr);
- /* string_concatenate consumed the ref to v */
- goto skip_decref_vx;
- }
- else {
- slow_add:
- x = PyNumber_Add(v, w);
- }
- Py_DECREF(v);
- skip_decref_vx:
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_SUBTRACT:
- w = POP();
- v = TOP();
- if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
- /* INLINE: int - int */
- register long a, b, i;
- a = PyInt_AS_LONG(v);
- b = PyInt_AS_LONG(w);
- /* cast to avoid undefined behaviour
- on overflow */
- i = (long)((unsigned long)a - b);
- if ((i^a) < 0 && (i^~b) < 0)
- goto slow_sub;
- x = PyInt_FromLong(i);
- }
- else {
- slow_sub:
- x = PyNumber_Subtract(v, w);
- }
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_SUBSCR:
- w = POP();
- v = TOP();
- if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
- /* INLINE: list[int] */
- Py_ssize_t i = PyInt_AsSsize_t(w);
- if (i < 0)
- i += PyList_GET_SIZE(v);
- if (i >= 0 && i < PyList_GET_SIZE(v)) {
- x = PyList_GET_ITEM(v, i);
- Py_INCREF(x);
- }
- else
- goto slow_get;
- }
- else
- slow_get:
- x = PyObject_GetItem(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_LSHIFT:
- w = POP();
- v = TOP();
- x = PyNumber_Lshift(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_RSHIFT:
- w = POP();
- v = TOP();
- x = PyNumber_Rshift(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_AND:
- w = POP();
- v = TOP();
- x = PyNumber_And(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_XOR:
- w = POP();
- v = TOP();
- x = PyNumber_Xor(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case BINARY_OR:
- w = POP();
- v = TOP();
- x = PyNumber_Or(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case LIST_APPEND:
- w = POP();
- v = PEEK(oparg);
- err = PyList_Append(v, w);
- Py_DECREF(w);
- if (err == 0) {
- PREDICT(JUMP_ABSOLUTE);
- continue;
- }
- break;
-
- case SET_ADD:
- w = POP();
- v = stack_pointer[-oparg];
- err = PySet_Add(v, w);
- Py_DECREF(w);
- if (err == 0) {
- PREDICT(JUMP_ABSOLUTE);
- continue;
- }
- break;
-
- case INPLACE_POWER:
- w = POP();
- v = TOP();
- x = PyNumber_InPlacePower(v, w, Py_None);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_MULTIPLY:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceMultiply(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_DIVIDE:
- if (!_Py_QnewFlag) {
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceDivide(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
- }
- /* -Qnew is in effect: fall through to
- INPLACE_TRUE_DIVIDE */
- case INPLACE_TRUE_DIVIDE:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceTrueDivide(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_FLOOR_DIVIDE:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceFloorDivide(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_MODULO:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceRemainder(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_ADD:
- w = POP();
- v = TOP();
- if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
- /* INLINE: int + int */
- register long a, b, i;
- a = PyInt_AS_LONG(v);
- b = PyInt_AS_LONG(w);
- i = a + b;
- if ((i^a) < 0 && (i^b) < 0)
- goto slow_iadd;
- x = PyInt_FromLong(i);
- }
- else if (PyString_CheckExact(v) &&
- PyString_CheckExact(w)) {
- x = string_concatenate(v, w, f, next_instr);
- /* string_concatenate consumed the ref to v */
- goto skip_decref_v;
- }
- else {
- slow_iadd:
- x = PyNumber_InPlaceAdd(v, w);
- }
- Py_DECREF(v);
- skip_decref_v:
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_SUBTRACT:
- w = POP();
- v = TOP();
- if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
- /* INLINE: int - int */
- register long a, b, i;
- a = PyInt_AS_LONG(v);
- b = PyInt_AS_LONG(w);
- i = a - b;
- if ((i^a) < 0 && (i^~b) < 0)
- goto slow_isub;
- x = PyInt_FromLong(i);
- }
- else {
- slow_isub:
- x = PyNumber_InPlaceSubtract(v, w);
- }
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_LSHIFT:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceLshift(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_RSHIFT:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceRshift(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_AND:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceAnd(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_XOR:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceXor(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case INPLACE_OR:
- w = POP();
- v = TOP();
- x = PyNumber_InPlaceOr(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case SLICE+0:
- case SLICE+1:
- case SLICE+2:
- case SLICE+3:
- if ((opcode-SLICE) & 2)
- w = POP();
- else
- w = NULL;
- if ((opcode-SLICE) & 1)
- v = POP();
- else
- v = NULL;
- u = TOP();
- x = apply_slice(u, v, w);
- Py_DECREF(u);
- Py_XDECREF(v);
- Py_XDECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case STORE_SLICE+0:
- case STORE_SLICE+1:
- case STORE_SLICE+2:
- case STORE_SLICE+3:
- if ((opcode-STORE_SLICE) & 2)
- w = POP();
- else
- w = NULL;
- if ((opcode-STORE_SLICE) & 1)
- v = POP();
- else
- v = NULL;
- u = POP();
- t = POP();
- err = assign_slice(u, v, w, t); /* u[v:w] = t */
- Py_DECREF(t);
- Py_DECREF(u);
- Py_XDECREF(v);
- Py_XDECREF(w);
- if (err == 0) continue;
- break;
-
- case DELETE_SLICE+0:
- case DELETE_SLICE+1:
- case DELETE_SLICE+2:
- case DELETE_SLICE+3:
- if ((opcode-DELETE_SLICE) & 2)
- w = POP();
- else
- w = NULL;
- if ((opcode-DELETE_SLICE) & 1)
- v = POP();
- else
- v = NULL;
- u = POP();
- err = assign_slice(u, v, w, (PyObject *)NULL);
- /* del u[v:w] */
- Py_DECREF(u);
- Py_XDECREF(v);
- Py_XDECREF(w);
- if (err == 0) continue;
- break;
-
- case STORE_SUBSCR:
- w = TOP();
- v = SECOND();
- u = THIRD();
- STACKADJ(-3);
- /* v[w] = u */
- err = PyObject_SetItem(v, w, u);
- Py_DECREF(u);
- Py_DECREF(v);
- Py_DECREF(w);
- if (err == 0) continue;
- break;
-
- case DELETE_SUBSCR:
- w = TOP();
- v = SECOND();
- STACKADJ(-2);
- /* del v[w] */
- err = PyObject_DelItem(v, w);
- Py_DECREF(v);
- Py_DECREF(w);
- if (err == 0) continue;
- break;
-
- case PRINT_EXPR:
- v = POP();
- w = PySys_GetObject("displayhook");
- if (w == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "lost sys.displayhook");
- err = -1;
- x = NULL;
- }
- if (err == 0) {
- x = PyTuple_Pack(1, v);
- if (x == NULL)
- err = -1;
- }
- if (err == 0) {
- w = PyEval_CallObject(w, x);
- Py_XDECREF(w);
- if (w == NULL)
- err = -1;
- }
- Py_DECREF(v);
- Py_XDECREF(x);
- break;
-
- case PRINT_ITEM_TO:
- w = stream = POP();
- /* fall through to PRINT_ITEM */
-
- case PRINT_ITEM:
- v = POP();
- if (stream == NULL || stream == Py_None) {
- w = PySys_GetObject("stdout");
- if (w == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "lost sys.stdout");
- err = -1;
- }
- }
- /* PyFile_SoftSpace() can exececute arbitrary code
- if sys.stdout is an instance with a __getattr__.
- If __getattr__ raises an exception, w will
- be freed, so we need to prevent that temporarily. */
- Py_XINCREF(w);
- if (w != NULL && PyFile_SoftSpace(w, 0))
- err = PyFile_WriteString(" ", w);
- if (err == 0)
- err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
- if (err == 0) {
- /* XXX move into writeobject() ? */
- if (PyString_Check(v)) {
- char *s = PyString_AS_STRING(v);
- Py_ssize_t len = PyString_GET_SIZE(v);
- if (len == 0 ||
- !isspace(Py_CHARMASK(s[len-1])) ||
- s[len-1] == ' ')
- PyFile_SoftSpace(w, 1);
- }
+ /* Main switch on opcode */
+ READ_TIMESTAMP(inst0);
+
+ switch (opcode) {
+
+ /* BEWARE!
+ It is essential that any operation that fails sets either
+ x to NULL, err to nonzero, or why to anything but WHY_NOT,
+ and that no operation that succeeds does this! */
+
+ /* case STOP_CODE: this is an error! */
+
+ case NOP:
+ goto fast_next_opcode;
+
+ case LOAD_FAST:
+ x = GETLOCAL(oparg);
+ if (x != NULL) {
+ Py_INCREF(x);
+ PUSH(x);
+ goto fast_next_opcode;
+ }
+ format_exc_check_arg(PyExc_UnboundLocalError,
+ UNBOUNDLOCAL_ERROR_MSG,
+ PyTuple_GetItem(co->co_varnames, oparg));
+ break;
+
+ case LOAD_CONST:
+ x = GETITEM(consts, oparg);
+ Py_INCREF(x);
+ PUSH(x);
+ goto fast_next_opcode;
+
+ PREDICTED_WITH_ARG(STORE_FAST);
+ case STORE_FAST:
+ v = POP();
+ SETLOCAL(oparg, v);
+ goto fast_next_opcode;
+
+ case POP_TOP:
+ v = POP();
+ Py_DECREF(v);
+ goto fast_next_opcode;
+
+ case ROT_TWO:
+ v = TOP();
+ w = SECOND();
+ SET_TOP(w);
+ SET_SECOND(v);
+ goto fast_next_opcode;
+
+ case ROT_THREE:
+ v = TOP();
+ w = SECOND();
+ x = THIRD();
+ SET_TOP(w);
+ SET_SECOND(x);
+ SET_THIRD(v);
+ goto fast_next_opcode;
+
+ case ROT_FOUR:
+ u = TOP();
+ v = SECOND();
+ w = THIRD();
+ x = FOURTH();
+ SET_TOP(v);
+ SET_SECOND(w);
+ SET_THIRD(x);
+ SET_FOURTH(u);
+ goto fast_next_opcode;
+
+ case DUP_TOP:
+ v = TOP();
+ Py_INCREF(v);
+ PUSH(v);
+ goto fast_next_opcode;
+
+ case DUP_TOPX:
+ if (oparg == 2) {
+ x = TOP();
+ Py_INCREF(x);
+ w = SECOND();
+ Py_INCREF(w);
+ STACKADJ(2);
+ SET_TOP(x);
+ SET_SECOND(w);
+ goto fast_next_opcode;
+ } else if (oparg == 3) {
+ x = TOP();
+ Py_INCREF(x);
+ w = SECOND();
+ Py_INCREF(w);
+ v = THIRD();
+ Py_INCREF(v);
+ STACKADJ(3);
+ SET_TOP(x);
+ SET_SECOND(w);
+ SET_THIRD(v);
+ goto fast_next_opcode;
+ }
+ Py_FatalError("invalid argument to DUP_TOPX"
+ " (bytecode corruption?)");
+ /* Never returns, so don't bother to set why. */
+ break;
+
+ case UNARY_POSITIVE:
+ v = TOP();
+ x = PyNumber_Positive(v);
+ Py_DECREF(v);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case UNARY_NEGATIVE:
+ v = TOP();
+ x = PyNumber_Negative(v);
+ Py_DECREF(v);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case UNARY_NOT:
+ v = TOP();
+ err = PyObject_IsTrue(v);
+ Py_DECREF(v);
+ if (err == 0) {
+ Py_INCREF(Py_True);
+ SET_TOP(Py_True);
+ continue;
+ }
+ else if (err > 0) {
+ Py_INCREF(Py_False);
+ SET_TOP(Py_False);
+ err = 0;
+ continue;
+ }
+ STACKADJ(-1);
+ break;
+
+ case UNARY_CONVERT:
+ v = TOP();
+ x = PyObject_Repr(v);
+ Py_DECREF(v);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case UNARY_INVERT:
+ v = TOP();
+ x = PyNumber_Invert(v);
+ Py_DECREF(v);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_POWER:
+ w = POP();
+ v = TOP();
+ x = PyNumber_Power(v, w, Py_None);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_MULTIPLY:
+ w = POP();
+ v = TOP();
+ x = PyNumber_Multiply(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_DIVIDE:
+ if (!_Py_QnewFlag) {
+ w = POP();
+ v = TOP();
+ x = PyNumber_Divide(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+ }
+ /* -Qnew is in effect: fall through to
+ BINARY_TRUE_DIVIDE */
+ case BINARY_TRUE_DIVIDE:
+ w = POP();
+ v = TOP();
+ x = PyNumber_TrueDivide(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_FLOOR_DIVIDE:
+ w = POP();
+ v = TOP();
+ x = PyNumber_FloorDivide(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_MODULO:
+ w = POP();
+ v = TOP();
+ if (PyString_CheckExact(v))
+ x = PyString_Format(v, w);
+ else
+ x = PyNumber_Remainder(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_ADD:
+ w = POP();
+ v = TOP();
+ if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
+ /* INLINE: int + int */
+ register long a, b, i;
+ a = PyInt_AS_LONG(v);
+ b = PyInt_AS_LONG(w);
+ /* cast to avoid undefined behaviour
+ on overflow */
+ i = (long)((unsigned long)a + b);
+ if ((i^a) < 0 && (i^b) < 0)
+ goto slow_add;
+ x = PyInt_FromLong(i);
+ }
+ else if (PyString_CheckExact(v) &&
+ PyString_CheckExact(w)) {
+ x = string_concatenate(v, w, f, next_instr);
+ /* string_concatenate consumed the ref to v */
+ goto skip_decref_vx;
+ }
+ else {
+ slow_add:
+ x = PyNumber_Add(v, w);
+ }
+ Py_DECREF(v);
+ skip_decref_vx:
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_SUBTRACT:
+ w = POP();
+ v = TOP();
+ if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
+ /* INLINE: int - int */
+ register long a, b, i;
+ a = PyInt_AS_LONG(v);
+ b = PyInt_AS_LONG(w);
+ /* cast to avoid undefined behaviour
+ on overflow */
+ i = (long)((unsigned long)a - b);
+ if ((i^a) < 0 && (i^~b) < 0)
+ goto slow_sub;
+ x = PyInt_FromLong(i);
+ }
+ else {
+ slow_sub:
+ x = PyNumber_Subtract(v, w);
+ }
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_SUBSCR:
+ w = POP();
+ v = TOP();
+ if (PyList_CheckExact(v) && PyInt_CheckExact(w)) {
+ /* INLINE: list[int] */
+ Py_ssize_t i = PyInt_AsSsize_t(w);
+ if (i < 0)
+ i += PyList_GET_SIZE(v);
+ if (i >= 0 && i < PyList_GET_SIZE(v)) {
+ x = PyList_GET_ITEM(v, i);
+ Py_INCREF(x);
+ }
+ else
+ goto slow_get;
+ }
+ else
+ slow_get:
+ x = PyObject_GetItem(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_LSHIFT:
+ w = POP();
+ v = TOP();
+ x = PyNumber_Lshift(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_RSHIFT:
+ w = POP();
+ v = TOP();
+ x = PyNumber_Rshift(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_AND:
+ w = POP();
+ v = TOP();
+ x = PyNumber_And(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_XOR:
+ w = POP();
+ v = TOP();
+ x = PyNumber_Xor(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case BINARY_OR:
+ w = POP();
+ v = TOP();
+ x = PyNumber_Or(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case LIST_APPEND:
+ w = POP();
+ v = PEEK(oparg);
+ err = PyList_Append(v, w);
+ Py_DECREF(w);
+ if (err == 0) {
+ PREDICT(JUMP_ABSOLUTE);
+ continue;
+ }
+ break;
+
+ case SET_ADD:
+ w = POP();
+ v = stack_pointer[-oparg];
+ err = PySet_Add(v, w);
+ Py_DECREF(w);
+ if (err == 0) {
+ PREDICT(JUMP_ABSOLUTE);
+ continue;
+ }
+ break;
+
+ case INPLACE_POWER:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlacePower(v, w, Py_None);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_MULTIPLY:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceMultiply(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_DIVIDE:
+ if (!_Py_QnewFlag) {
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceDivide(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+ }
+ /* -Qnew is in effect: fall through to
+ INPLACE_TRUE_DIVIDE */
+ case INPLACE_TRUE_DIVIDE:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceTrueDivide(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_FLOOR_DIVIDE:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceFloorDivide(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_MODULO:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceRemainder(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_ADD:
+ w = POP();
+ v = TOP();
+ if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
+ /* INLINE: int + int */
+ register long a, b, i;
+ a = PyInt_AS_LONG(v);
+ b = PyInt_AS_LONG(w);
+ i = a + b;
+ if ((i^a) < 0 && (i^b) < 0)
+ goto slow_iadd;
+ x = PyInt_FromLong(i);
+ }
+ else if (PyString_CheckExact(v) &&
+ PyString_CheckExact(w)) {
+ x = string_concatenate(v, w, f, next_instr);
+ /* string_concatenate consumed the ref to v */
+ goto skip_decref_v;
+ }
+ else {
+ slow_iadd:
+ x = PyNumber_InPlaceAdd(v, w);
+ }
+ Py_DECREF(v);
+ skip_decref_v:
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_SUBTRACT:
+ w = POP();
+ v = TOP();
+ if (PyInt_CheckExact(v) && PyInt_CheckExact(w)) {
+ /* INLINE: int - int */
+ register long a, b, i;
+ a = PyInt_AS_LONG(v);
+ b = PyInt_AS_LONG(w);
+ i = a - b;
+ if ((i^a) < 0 && (i^~b) < 0)
+ goto slow_isub;
+ x = PyInt_FromLong(i);
+ }
+ else {
+ slow_isub:
+ x = PyNumber_InPlaceSubtract(v, w);
+ }
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_LSHIFT:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceLshift(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_RSHIFT:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceRshift(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_AND:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceAnd(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_XOR:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceXor(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case INPLACE_OR:
+ w = POP();
+ v = TOP();
+ x = PyNumber_InPlaceOr(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case SLICE+0:
+ case SLICE+1:
+ case SLICE+2:
+ case SLICE+3:
+ if ((opcode-SLICE) & 2)
+ w = POP();
+ else
+ w = NULL;
+ if ((opcode-SLICE) & 1)
+ v = POP();
+ else
+ v = NULL;
+ u = TOP();
+ x = apply_slice(u, v, w);
+ Py_DECREF(u);
+ Py_XDECREF(v);
+ Py_XDECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case STORE_SLICE+0:
+ case STORE_SLICE+1:
+ case STORE_SLICE+2:
+ case STORE_SLICE+3:
+ if ((opcode-STORE_SLICE) & 2)
+ w = POP();
+ else
+ w = NULL;
+ if ((opcode-STORE_SLICE) & 1)
+ v = POP();
+ else
+ v = NULL;
+ u = POP();
+ t = POP();
+ err = assign_slice(u, v, w, t); /* u[v:w] = t */
+ Py_DECREF(t);
+ Py_DECREF(u);
+ Py_XDECREF(v);
+ Py_XDECREF(w);
+ if (err == 0) continue;
+ break;
+
+ case DELETE_SLICE+0:
+ case DELETE_SLICE+1:
+ case DELETE_SLICE+2:
+ case DELETE_SLICE+3:
+ if ((opcode-DELETE_SLICE) & 2)
+ w = POP();
+ else
+ w = NULL;
+ if ((opcode-DELETE_SLICE) & 1)
+ v = POP();
+ else
+ v = NULL;
+ u = POP();
+ err = assign_slice(u, v, w, (PyObject *)NULL);
+ /* del u[v:w] */
+ Py_DECREF(u);
+ Py_XDECREF(v);
+ Py_XDECREF(w);
+ if (err == 0) continue;
+ break;
+
+ case STORE_SUBSCR:
+ w = TOP();
+ v = SECOND();
+ u = THIRD();
+ STACKADJ(-3);
+ /* v[w] = u */
+ err = PyObject_SetItem(v, w, u);
+ Py_DECREF(u);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ if (err == 0) continue;
+ break;
+
+ case DELETE_SUBSCR:
+ w = TOP();
+ v = SECOND();
+ STACKADJ(-2);
+ /* del v[w] */
+ err = PyObject_DelItem(v, w);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ if (err == 0) continue;
+ break;
+
+ case PRINT_EXPR:
+ v = POP();
+ w = PySys_GetObject("displayhook");
+ if (w == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "lost sys.displayhook");
+ err = -1;
+ x = NULL;
+ }
+ if (err == 0) {
+ x = PyTuple_Pack(1, v);
+ if (x == NULL)
+ err = -1;
+ }
+ if (err == 0) {
+ w = PyEval_CallObject(w, x);
+ Py_XDECREF(w);
+ if (w == NULL)
+ err = -1;
+ }
+ Py_DECREF(v);
+ Py_XDECREF(x);
+ break;
+
+ case PRINT_ITEM_TO:
+ w = stream = POP();
+ /* fall through to PRINT_ITEM */
+
+ case PRINT_ITEM:
+ v = POP();
+ if (stream == NULL || stream == Py_None) {
+ w = PySys_GetObject("stdout");
+ if (w == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "lost sys.stdout");
+ err = -1;
+ }
+ }
+ /* PyFile_SoftSpace() can exececute arbitrary code
+ if sys.stdout is an instance with a __getattr__.
+ If __getattr__ raises an exception, w will
+ be freed, so we need to prevent that temporarily. */
+ Py_XINCREF(w);
+ if (w != NULL && PyFile_SoftSpace(w, 0))
+ err = PyFile_WriteString(" ", w);
+ if (err == 0)
+ err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
+ if (err == 0) {
+ /* XXX move into writeobject() ? */
+ if (PyString_Check(v)) {
+ char *s = PyString_AS_STRING(v);
+ Py_ssize_t len = PyString_GET_SIZE(v);
+ if (len == 0 ||
+ !isspace(Py_CHARMASK(s[len-1])) ||
+ s[len-1] == ' ')
+ PyFile_SoftSpace(w, 1);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(v)) {
- Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
- Py_ssize_t len = PyUnicode_GET_SIZE(v);
- if (len == 0 ||
- !Py_UNICODE_ISSPACE(s[len-1]) ||
- s[len-1] == ' ')
- PyFile_SoftSpace(w, 1);
- }
+ else if (PyUnicode_Check(v)) {
+ Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
+ Py_ssize_t len = PyUnicode_GET_SIZE(v);
+ if (len == 0 ||
+ !Py_UNICODE_ISSPACE(s[len-1]) ||
+ s[len-1] == ' ')
+ PyFile_SoftSpace(w, 1);
+ }
#endif
- else
- PyFile_SoftSpace(w, 1);
- }
- Py_XDECREF(w);
- Py_DECREF(v);
- Py_XDECREF(stream);
- stream = NULL;
- if (err == 0)
- continue;
- break;
-
- case PRINT_NEWLINE_TO:
- w = stream = POP();
- /* fall through to PRINT_NEWLINE */
-
- case PRINT_NEWLINE:
- if (stream == NULL || stream == Py_None) {
- w = PySys_GetObject("stdout");
- if (w == NULL) {
- PyErr_SetString(PyExc_RuntimeError,
- "lost sys.stdout");
- why = WHY_EXCEPTION;
- }
- }
- if (w != NULL) {
- /* w.write() may replace sys.stdout, so we
- * have to keep our reference to it */
- Py_INCREF(w);
- err = PyFile_WriteString("\n", w);
- if (err == 0)
- PyFile_SoftSpace(w, 0);
- Py_DECREF(w);
- }
- Py_XDECREF(stream);
- stream = NULL;
- break;
+ else
+ PyFile_SoftSpace(w, 1);
+ }
+ Py_XDECREF(w);
+ Py_DECREF(v);
+ Py_XDECREF(stream);
+ stream = NULL;
+ if (err == 0)
+ continue;
+ break;
+
+ case PRINT_NEWLINE_TO:
+ w = stream = POP();
+ /* fall through to PRINT_NEWLINE */
+
+ case PRINT_NEWLINE:
+ if (stream == NULL || stream == Py_None) {
+ w = PySys_GetObject("stdout");
+ if (w == NULL) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "lost sys.stdout");
+ why = WHY_EXCEPTION;
+ }
+ }
+ if (w != NULL) {
+ /* w.write() may replace sys.stdout, so we
+ * have to keep our reference to it */
+ Py_INCREF(w);
+ err = PyFile_WriteString("\n", w);
+ if (err == 0)
+ PyFile_SoftSpace(w, 0);
+ Py_DECREF(w);
+ }
+ Py_XDECREF(stream);
+ stream = NULL;
+ break;
#ifdef CASE_TOO_BIG
- default: switch (opcode) {
+ default: switch (opcode) {
#endif
- case RAISE_VARARGS:
- u = v = w = NULL;
- switch (oparg) {
- case 3:
- u = POP(); /* traceback */
- /* Fallthrough */
- case 2:
- v = POP(); /* value */
- /* Fallthrough */
- case 1:
- w = POP(); /* exc */
- case 0: /* Fallthrough */
- why = do_raise(w, v, u);
- break;
- default:
- PyErr_SetString(PyExc_SystemError,
- "bad RAISE_VARARGS oparg");
- why = WHY_EXCEPTION;
- break;
- }
- break;
-
- case LOAD_LOCALS:
- if ((x = f->f_locals) != NULL) {
- Py_INCREF(x);
- PUSH(x);
- continue;
- }
- PyErr_SetString(PyExc_SystemError, "no locals");
- break;
-
- case RETURN_VALUE:
- retval = POP();
- why = WHY_RETURN;
- goto fast_block_end;
-
- case YIELD_VALUE:
- retval = POP();
- f->f_stacktop = stack_pointer;
- why = WHY_YIELD;
- goto fast_yield;
-
- case EXEC_STMT:
- w = TOP();
- v = SECOND();
- u = THIRD();
- STACKADJ(-3);
- READ_TIMESTAMP(intr0);
- err = exec_statement(f, u, v, w);
- READ_TIMESTAMP(intr1);
- Py_DECREF(u);
- Py_DECREF(v);
- Py_DECREF(w);
- break;
-
- case POP_BLOCK:
- {
- PyTryBlock *b = PyFrame_BlockPop(f);
- while (STACK_LEVEL() > b->b_level) {
- v = POP();
- Py_DECREF(v);
- }
- }
- continue;
-
- PREDICTED(END_FINALLY);
- case END_FINALLY:
- v = POP();
- if (PyInt_Check(v)) {
- why = (enum why_code) PyInt_AS_LONG(v);
- assert(why != WHY_YIELD);
- if (why == WHY_RETURN ||
- why == WHY_CONTINUE)
- retval = POP();
- }
- else if (PyExceptionClass_Check(v) ||
- PyString_Check(v)) {
- w = POP();
- u = POP();
- PyErr_Restore(v, w, u);
- why = WHY_RERAISE;
- break;
- }
- else if (v != Py_None) {
- PyErr_SetString(PyExc_SystemError,
- "'finally' pops bad exception");
- why = WHY_EXCEPTION;
- }
- Py_DECREF(v);
- break;
-
- case BUILD_CLASS:
- u = TOP();
- v = SECOND();
- w = THIRD();
- STACKADJ(-2);
- x = build_class(u, v, w);
- SET_TOP(x);
- Py_DECREF(u);
- Py_DECREF(v);
- Py_DECREF(w);
- break;
-
- case STORE_NAME:
- w = GETITEM(names, oparg);
- v = POP();
- if ((x = f->f_locals) != NULL) {
- if (PyDict_CheckExact(x))
- err = PyDict_SetItem(x, w, v);
- else
- err = PyObject_SetItem(x, w, v);
- Py_DECREF(v);
- if (err == 0) continue;
- break;
- }
- PyErr_Format(PyExc_SystemError,
- "no locals found when storing %s",
- PyObject_REPR(w));
- break;
-
- case DELETE_NAME:
- w = GETITEM(names, oparg);
- if ((x = f->f_locals) != NULL) {
- if ((err = PyObject_DelItem(x, w)) != 0)
- format_exc_check_arg(PyExc_NameError,
- NAME_ERROR_MSG,
- w);
- break;
- }
- PyErr_Format(PyExc_SystemError,
- "no locals when deleting %s",
- PyObject_REPR(w));
- break;
-
- PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
- case UNPACK_SEQUENCE:
- v = POP();
- if (PyTuple_CheckExact(v) &&
- PyTuple_GET_SIZE(v) == oparg) {
- PyObject **items = \
- ((PyTupleObject *)v)->ob_item;
- while (oparg--) {
- w = items[oparg];
- Py_INCREF(w);
- PUSH(w);
- }
- Py_DECREF(v);
- continue;
- } else if (PyList_CheckExact(v) &&
- PyList_GET_SIZE(v) == oparg) {
- PyObject **items = \
- ((PyListObject *)v)->ob_item;
- while (oparg--) {
- w = items[oparg];
- Py_INCREF(w);
- PUSH(w);
- }
- } else if (unpack_iterable(v, oparg,
- stack_pointer + oparg)) {
- STACKADJ(oparg);
- } else {
- /* unpack_iterable() raised an exception */
- why = WHY_EXCEPTION;
- }
- Py_DECREF(v);
- break;
-
- case STORE_ATTR:
- w = GETITEM(names, oparg);
- v = TOP();
- u = SECOND();
- STACKADJ(-2);
- err = PyObject_SetAttr(v, w, u); /* v.w = u */
- Py_DECREF(v);
- Py_DECREF(u);
- if (err == 0) continue;
- break;
-
- case DELETE_ATTR:
- w = GETITEM(names, oparg);
- v = POP();
- err = PyObject_SetAttr(v, w, (PyObject *)NULL);
- /* del v.w */
- Py_DECREF(v);
- break;
-
- case STORE_GLOBAL:
- w = GETITEM(names, oparg);
- v = POP();
- err = PyDict_SetItem(f->f_globals, w, v);
- Py_DECREF(v);
- if (err == 0) continue;
- break;
-
- case DELETE_GLOBAL:
- w = GETITEM(names, oparg);
- if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
- format_exc_check_arg(
- PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
- break;
-
- case LOAD_NAME:
- w = GETITEM(names, oparg);
- if ((v = f->f_locals) == NULL) {
- PyErr_Format(PyExc_SystemError,
- "no locals when loading %s",
- PyObject_REPR(w));
- why = WHY_EXCEPTION;
- break;
- }
- if (PyDict_CheckExact(v)) {
- x = PyDict_GetItem(v, w);
- Py_XINCREF(x);
- }
- else {
- x = PyObject_GetItem(v, w);
- if (x == NULL && PyErr_Occurred()) {
- if (!PyErr_ExceptionMatches(
- PyExc_KeyError))
- break;
- PyErr_Clear();
- }
- }
- if (x == NULL) {
- x = PyDict_GetItem(f->f_globals, w);
- if (x == NULL) {
- x = PyDict_GetItem(f->f_builtins, w);
- if (x == NULL) {
- format_exc_check_arg(
- PyExc_NameError,
- NAME_ERROR_MSG, w);
- break;
- }
- }
- Py_INCREF(x);
- }
- PUSH(x);
- continue;
-
- case LOAD_GLOBAL:
- w = GETITEM(names, oparg);
- if (PyString_CheckExact(w)) {
- /* Inline the PyDict_GetItem() calls.
- WARNING: this is an extreme speed hack.
- Do not try this at home. */
- long hash = ((PyStringObject *)w)->ob_shash;
- if (hash != -1) {
- PyDictObject *d;
- PyDictEntry *e;
- d = (PyDictObject *)(f->f_globals);
- e = d->ma_lookup(d, w, hash);
- if (e == NULL) {
- x = NULL;
- break;
- }
- x = e->me_value;
- if (x != NULL) {
- Py_INCREF(x);
- PUSH(x);
- continue;
- }
- d = (PyDictObject *)(f->f_builtins);
- e = d->ma_lookup(d, w, hash);
- if (e == NULL) {
- x = NULL;
- break;
- }
- x = e->me_value;
- if (x != NULL) {
- Py_INCREF(x);
- PUSH(x);
- continue;
- }
- goto load_global_error;
- }
- }
- /* This is the un-inlined version of the code above */
- x = PyDict_GetItem(f->f_globals, w);
- if (x == NULL) {
- x = PyDict_GetItem(f->f_builtins, w);
- if (x == NULL) {
- load_global_error:
- format_exc_check_arg(
- PyExc_NameError,
- GLOBAL_NAME_ERROR_MSG, w);
- break;
- }
- }
- Py_INCREF(x);
- PUSH(x);
- continue;
-
- case DELETE_FAST:
- x = GETLOCAL(oparg);
- if (x != NULL) {
- SETLOCAL(oparg, NULL);
- continue;
- }
- format_exc_check_arg(
- PyExc_UnboundLocalError,
- UNBOUNDLOCAL_ERROR_MSG,
- PyTuple_GetItem(co->co_varnames, oparg)
- );
- break;
-
- case LOAD_CLOSURE:
- x = freevars[oparg];
- Py_INCREF(x);
- PUSH(x);
- if (x != NULL) continue;
- break;
-
- case LOAD_DEREF:
- x = freevars[oparg];
- w = PyCell_Get(x);
- if (w != NULL) {
- PUSH(w);
- continue;
- }
- err = -1;
- /* Don't stomp existing exception */
- if (PyErr_Occurred())
- break;
- if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
- v = PyTuple_GET_ITEM(co->co_cellvars,
- oparg);
- format_exc_check_arg(
- PyExc_UnboundLocalError,
- UNBOUNDLOCAL_ERROR_MSG,
- v);
- } else {
- v = PyTuple_GET_ITEM(co->co_freevars, oparg -
- PyTuple_GET_SIZE(co->co_cellvars));
- format_exc_check_arg(PyExc_NameError,
- UNBOUNDFREE_ERROR_MSG, v);
- }
- break;
-
- case STORE_DEREF:
- w = POP();
- x = freevars[oparg];
- PyCell_Set(x, w);
- Py_DECREF(w);
- continue;
-
- case BUILD_TUPLE:
- x = PyTuple_New(oparg);
- if (x != NULL) {
- for (; --oparg >= 0;) {
- w = POP();
- PyTuple_SET_ITEM(x, oparg, w);
- }
- PUSH(x);
- continue;
- }
- break;
-
- case BUILD_LIST:
- x = PyList_New(oparg);
- if (x != NULL) {
- for (; --oparg >= 0;) {
- w = POP();
- PyList_SET_ITEM(x, oparg, w);
- }
- PUSH(x);
- continue;
- }
- break;
-
- case BUILD_SET:
- x = PySet_New(NULL);
- if (x != NULL) {
- for (; --oparg >= 0;) {
- w = POP();
- if (err == 0)
- err = PySet_Add(x, w);
- Py_DECREF(w);
- }
- if (err != 0) {
- Py_DECREF(x);
- break;
- }
- PUSH(x);
- continue;
- }
- break;
-
-
- case BUILD_MAP:
- x = _PyDict_NewPresized((Py_ssize_t)oparg);
- PUSH(x);
- if (x != NULL) continue;
- break;
-
- case STORE_MAP:
- w = TOP(); /* key */
- u = SECOND(); /* value */
- v = THIRD(); /* dict */
- STACKADJ(-2);
- assert (PyDict_CheckExact(v));
- err = PyDict_SetItem(v, w, u); /* v[w] = u */
- Py_DECREF(u);
- Py_DECREF(w);
- if (err == 0) continue;
- break;
-
- case MAP_ADD:
- w = TOP(); /* key */
- u = SECOND(); /* value */
- STACKADJ(-2);
- v = stack_pointer[-oparg]; /* dict */
- assert (PyDict_CheckExact(v));
- err = PyDict_SetItem(v, w, u); /* v[w] = u */
- Py_DECREF(u);
- Py_DECREF(w);
- if (err == 0) {
- PREDICT(JUMP_ABSOLUTE);
- continue;
- }
- break;
-
- case LOAD_ATTR:
- w = GETITEM(names, oparg);
- v = TOP();
- x = PyObject_GetAttr(v, w);
- Py_DECREF(v);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case COMPARE_OP:
- w = POP();
- v = TOP();
- if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) {
- /* INLINE: cmp(int, int) */
- register long a, b;
- register int res;
- a = PyInt_AS_LONG(v);
- b = PyInt_AS_LONG(w);
- switch (oparg) {
- case PyCmp_LT: res = a < b; break;
- case PyCmp_LE: res = a <= b; break;
- case PyCmp_EQ: res = a == b; break;
- case PyCmp_NE: res = a != b; break;
- case PyCmp_GT: res = a > b; break;
- case PyCmp_GE: res = a >= b; break;
- case PyCmp_IS: res = v == w; break;
- case PyCmp_IS_NOT: res = v != w; break;
- default: goto slow_compare;
- }
- x = res ? Py_True : Py_False;
- Py_INCREF(x);
- }
- else {
- slow_compare:
- x = cmp_outcome(oparg, v, w);
- }
- Py_DECREF(v);
- Py_DECREF(w);
- SET_TOP(x);
- if (x == NULL) break;
- PREDICT(POP_JUMP_IF_FALSE);
- PREDICT(POP_JUMP_IF_TRUE);
- continue;
-
- case IMPORT_NAME:
- w = GETITEM(names, oparg);
- x = PyDict_GetItemString(f->f_builtins, "__import__");
- if (x == NULL) {
- PyErr_SetString(PyExc_ImportError,
- "__import__ not found");
- break;
- }
- Py_INCREF(x);
- v = POP();
- u = TOP();
- if (PyInt_AsLong(u) != -1 || PyErr_Occurred())
- w = PyTuple_Pack(5,
- w,
- f->f_globals,
- f->f_locals == NULL ?
- Py_None : f->f_locals,
- v,
- u);
- else
- w = PyTuple_Pack(4,
- w,
- f->f_globals,
- f->f_locals == NULL ?
- Py_None : f->f_locals,
- v);
- Py_DECREF(v);
- Py_DECREF(u);
- if (w == NULL) {
- u = POP();
- Py_DECREF(x);
- x = NULL;
- break;
- }
- READ_TIMESTAMP(intr0);
- v = x;
- x = PyEval_CallObject(v, w);
- Py_DECREF(v);
- READ_TIMESTAMP(intr1);
- Py_DECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case IMPORT_STAR:
- v = POP();
- PyFrame_FastToLocals(f);
- if ((x = f->f_locals) == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "no locals found during 'import *'");
- break;
- }
- READ_TIMESTAMP(intr0);
- err = import_all_from(x, v);
- READ_TIMESTAMP(intr1);
- PyFrame_LocalsToFast(f, 0);
- Py_DECREF(v);
- if (err == 0) continue;
- break;
-
- case IMPORT_FROM:
- w = GETITEM(names, oparg);
- v = TOP();
- READ_TIMESTAMP(intr0);
- x = import_from(v, w);
- READ_TIMESTAMP(intr1);
- PUSH(x);
- if (x != NULL) continue;
- break;
-
- case JUMP_FORWARD:
- JUMPBY(oparg);
- goto fast_next_opcode;
-
- PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
- case POP_JUMP_IF_FALSE:
- w = POP();
- if (w == Py_True) {
- Py_DECREF(w);
- goto fast_next_opcode;
- }
- if (w == Py_False) {
- Py_DECREF(w);
- JUMPTO(oparg);
- goto fast_next_opcode;
- }
- err = PyObject_IsTrue(w);
- Py_DECREF(w);
- if (err > 0)
- err = 0;
- else if (err == 0)
- JUMPTO(oparg);
- else
- break;
- continue;
-
- PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
- case POP_JUMP_IF_TRUE:
- w = POP();
- if (w == Py_False) {
- Py_DECREF(w);
- goto fast_next_opcode;
- }
- if (w == Py_True) {
- Py_DECREF(w);
- JUMPTO(oparg);
- goto fast_next_opcode;
- }
- err = PyObject_IsTrue(w);
- Py_DECREF(w);
- if (err > 0) {
- err = 0;
- JUMPTO(oparg);
- }
- else if (err == 0)
- ;
- else
- break;
- continue;
-
- case JUMP_IF_FALSE_OR_POP:
- w = TOP();
- if (w == Py_True) {
- STACKADJ(-1);
- Py_DECREF(w);
- goto fast_next_opcode;
- }
- if (w == Py_False) {
- JUMPTO(oparg);
- goto fast_next_opcode;
- }
- err = PyObject_IsTrue(w);
- if (err > 0) {
- STACKADJ(-1);
- Py_DECREF(w);
- err = 0;
- }
- else if (err == 0)
- JUMPTO(oparg);
- else
- break;
- continue;
-
- case JUMP_IF_TRUE_OR_POP:
- w = TOP();
- if (w == Py_False) {
- STACKADJ(-1);
- Py_DECREF(w);
- goto fast_next_opcode;
- }
- if (w == Py_True) {
- JUMPTO(oparg);
- goto fast_next_opcode;
- }
- err = PyObject_IsTrue(w);
- if (err > 0) {
- err = 0;
- JUMPTO(oparg);
- }
- else if (err == 0) {
- STACKADJ(-1);
- Py_DECREF(w);
- }
- else
- break;
- continue;
-
- PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
- case JUMP_ABSOLUTE:
- JUMPTO(oparg);
+ case RAISE_VARARGS:
+ u = v = w = NULL;
+ switch (oparg) {
+ case 3:
+ u = POP(); /* traceback */
+ /* Fallthrough */
+ case 2:
+ v = POP(); /* value */
+ /* Fallthrough */
+ case 1:
+ w = POP(); /* exc */
+ case 0: /* Fallthrough */
+ why = do_raise(w, v, u);
+ break;
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "bad RAISE_VARARGS oparg");
+ why = WHY_EXCEPTION;
+ break;
+ }
+ break;
+
+ case LOAD_LOCALS:
+ if ((x = f->f_locals) != NULL) {
+ Py_INCREF(x);
+ PUSH(x);
+ continue;
+ }
+ PyErr_SetString(PyExc_SystemError, "no locals");
+ break;
+
+ case RETURN_VALUE:
+ retval = POP();
+ why = WHY_RETURN;
+ goto fast_block_end;
+
+ case YIELD_VALUE:
+ retval = POP();
+ f->f_stacktop = stack_pointer;
+ why = WHY_YIELD;
+ goto fast_yield;
+
+ case EXEC_STMT:
+ w = TOP();
+ v = SECOND();
+ u = THIRD();
+ STACKADJ(-3);
+ READ_TIMESTAMP(intr0);
+ err = exec_statement(f, u, v, w);
+ READ_TIMESTAMP(intr1);
+ Py_DECREF(u);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ break;
+
+ case POP_BLOCK:
+ {
+ PyTryBlock *b = PyFrame_BlockPop(f);
+ while (STACK_LEVEL() > b->b_level) {
+ v = POP();
+ Py_DECREF(v);
+ }
+ }
+ continue;
+
+ PREDICTED(END_FINALLY);
+ case END_FINALLY:
+ v = POP();
+ if (PyInt_Check(v)) {
+ why = (enum why_code) PyInt_AS_LONG(v);
+ assert(why != WHY_YIELD);
+ if (why == WHY_RETURN ||
+ why == WHY_CONTINUE)
+ retval = POP();
+ }
+ else if (PyExceptionClass_Check(v) ||
+ PyString_Check(v)) {
+ w = POP();
+ u = POP();
+ PyErr_Restore(v, w, u);
+ why = WHY_RERAISE;
+ break;
+ }
+ else if (v != Py_None) {
+ PyErr_SetString(PyExc_SystemError,
+ "'finally' pops bad exception");
+ why = WHY_EXCEPTION;
+ }
+ Py_DECREF(v);
+ break;
+
+ case BUILD_CLASS:
+ u = TOP();
+ v = SECOND();
+ w = THIRD();
+ STACKADJ(-2);
+ x = build_class(u, v, w);
+ SET_TOP(x);
+ Py_DECREF(u);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ break;
+
+ case STORE_NAME:
+ w = GETITEM(names, oparg);
+ v = POP();
+ if ((x = f->f_locals) != NULL) {
+ if (PyDict_CheckExact(x))
+ err = PyDict_SetItem(x, w, v);
+ else
+ err = PyObject_SetItem(x, w, v);
+ Py_DECREF(v);
+ if (err == 0) continue;
+ break;
+ }
+ PyErr_Format(PyExc_SystemError,
+ "no locals found when storing %s",
+ PyObject_REPR(w));
+ break;
+
+ case DELETE_NAME:
+ w = GETITEM(names, oparg);
+ if ((x = f->f_locals) != NULL) {
+ if ((err = PyObject_DelItem(x, w)) != 0)
+ format_exc_check_arg(PyExc_NameError,
+ NAME_ERROR_MSG,
+ w);
+ break;
+ }
+ PyErr_Format(PyExc_SystemError,
+ "no locals when deleting %s",
+ PyObject_REPR(w));
+ break;
+
+ PREDICTED_WITH_ARG(UNPACK_SEQUENCE);
+ case UNPACK_SEQUENCE:
+ v = POP();
+ if (PyTuple_CheckExact(v) &&
+ PyTuple_GET_SIZE(v) == oparg) {
+ PyObject **items = \
+ ((PyTupleObject *)v)->ob_item;
+ while (oparg--) {
+ w = items[oparg];
+ Py_INCREF(w);
+ PUSH(w);
+ }
+ Py_DECREF(v);
+ continue;
+ } else if (PyList_CheckExact(v) &&
+ PyList_GET_SIZE(v) == oparg) {
+ PyObject **items = \
+ ((PyListObject *)v)->ob_item;
+ while (oparg--) {
+ w = items[oparg];
+ Py_INCREF(w);
+ PUSH(w);
+ }
+ } else if (unpack_iterable(v, oparg,
+ stack_pointer + oparg)) {
+ STACKADJ(oparg);
+ } else {
+ /* unpack_iterable() raised an exception */
+ why = WHY_EXCEPTION;
+ }
+ Py_DECREF(v);
+ break;
+
+ case STORE_ATTR:
+ w = GETITEM(names, oparg);
+ v = TOP();
+ u = SECOND();
+ STACKADJ(-2);
+ err = PyObject_SetAttr(v, w, u); /* v.w = u */
+ Py_DECREF(v);
+ Py_DECREF(u);
+ if (err == 0) continue;
+ break;
+
+ case DELETE_ATTR:
+ w = GETITEM(names, oparg);
+ v = POP();
+ err = PyObject_SetAttr(v, w, (PyObject *)NULL);
+ /* del v.w */
+ Py_DECREF(v);
+ break;
+
+ case STORE_GLOBAL:
+ w = GETITEM(names, oparg);
+ v = POP();
+ err = PyDict_SetItem(f->f_globals, w, v);
+ Py_DECREF(v);
+ if (err == 0) continue;
+ break;
+
+ case DELETE_GLOBAL:
+ w = GETITEM(names, oparg);
+ if ((err = PyDict_DelItem(f->f_globals, w)) != 0)
+ format_exc_check_arg(
+ PyExc_NameError, GLOBAL_NAME_ERROR_MSG, w);
+ break;
+
+ case LOAD_NAME:
+ w = GETITEM(names, oparg);
+ if ((v = f->f_locals) == NULL) {
+ PyErr_Format(PyExc_SystemError,
+ "no locals when loading %s",
+ PyObject_REPR(w));
+ why = WHY_EXCEPTION;
+ break;
+ }
+ if (PyDict_CheckExact(v)) {
+ x = PyDict_GetItem(v, w);
+ Py_XINCREF(x);
+ }
+ else {
+ x = PyObject_GetItem(v, w);
+ if (x == NULL && PyErr_Occurred()) {
+ if (!PyErr_ExceptionMatches(
+ PyExc_KeyError))
+ break;
+ PyErr_Clear();
+ }
+ }
+ if (x == NULL) {
+ x = PyDict_GetItem(f->f_globals, w);
+ if (x == NULL) {
+ x = PyDict_GetItem(f->f_builtins, w);
+ if (x == NULL) {
+ format_exc_check_arg(
+ PyExc_NameError,
+ NAME_ERROR_MSG, w);
+ break;
+ }
+ }
+ Py_INCREF(x);
+ }
+ PUSH(x);
+ continue;
+
+ case LOAD_GLOBAL:
+ w = GETITEM(names, oparg);
+ if (PyString_CheckExact(w)) {
+ /* Inline the PyDict_GetItem() calls.
+ WARNING: this is an extreme speed hack.
+ Do not try this at home. */
+ long hash = ((PyStringObject *)w)->ob_shash;
+ if (hash != -1) {
+ PyDictObject *d;
+ PyDictEntry *e;
+ d = (PyDictObject *)(f->f_globals);
+ e = d->ma_lookup(d, w, hash);
+ if (e == NULL) {
+ x = NULL;
+ break;
+ }
+ x = e->me_value;
+ if (x != NULL) {
+ Py_INCREF(x);
+ PUSH(x);
+ continue;
+ }
+ d = (PyDictObject *)(f->f_builtins);
+ e = d->ma_lookup(d, w, hash);
+ if (e == NULL) {
+ x = NULL;
+ break;
+ }
+ x = e->me_value;
+ if (x != NULL) {
+ Py_INCREF(x);
+ PUSH(x);
+ continue;
+ }
+ goto load_global_error;
+ }
+ }
+ /* This is the un-inlined version of the code above */
+ x = PyDict_GetItem(f->f_globals, w);
+ if (x == NULL) {
+ x = PyDict_GetItem(f->f_builtins, w);
+ if (x == NULL) {
+ load_global_error:
+ format_exc_check_arg(
+ PyExc_NameError,
+ GLOBAL_NAME_ERROR_MSG, w);
+ break;
+ }
+ }
+ Py_INCREF(x);
+ PUSH(x);
+ continue;
+
+ case DELETE_FAST:
+ x = GETLOCAL(oparg);
+ if (x != NULL) {
+ SETLOCAL(oparg, NULL);
+ continue;
+ }
+ format_exc_check_arg(
+ PyExc_UnboundLocalError,
+ UNBOUNDLOCAL_ERROR_MSG,
+ PyTuple_GetItem(co->co_varnames, oparg)
+ );
+ break;
+
+ case LOAD_CLOSURE:
+ x = freevars[oparg];
+ Py_INCREF(x);
+ PUSH(x);
+ if (x != NULL) continue;
+ break;
+
+ case LOAD_DEREF:
+ x = freevars[oparg];
+ w = PyCell_Get(x);
+ if (w != NULL) {
+ PUSH(w);
+ continue;
+ }
+ err = -1;
+ /* Don't stomp existing exception */
+ if (PyErr_Occurred())
+ break;
+ if (oparg < PyTuple_GET_SIZE(co->co_cellvars)) {
+ v = PyTuple_GET_ITEM(co->co_cellvars,
+ oparg);
+ format_exc_check_arg(
+ PyExc_UnboundLocalError,
+ UNBOUNDLOCAL_ERROR_MSG,
+ v);
+ } else {
+ v = PyTuple_GET_ITEM(co->co_freevars, oparg -
+ PyTuple_GET_SIZE(co->co_cellvars));
+ format_exc_check_arg(PyExc_NameError,
+ UNBOUNDFREE_ERROR_MSG, v);
+ }
+ break;
+
+ case STORE_DEREF:
+ w = POP();
+ x = freevars[oparg];
+ PyCell_Set(x, w);
+ Py_DECREF(w);
+ continue;
+
+ case BUILD_TUPLE:
+ x = PyTuple_New(oparg);
+ if (x != NULL) {
+ for (; --oparg >= 0;) {
+ w = POP();
+ PyTuple_SET_ITEM(x, oparg, w);
+ }
+ PUSH(x);
+ continue;
+ }
+ break;
+
+ case BUILD_LIST:
+ x = PyList_New(oparg);
+ if (x != NULL) {
+ for (; --oparg >= 0;) {
+ w = POP();
+ PyList_SET_ITEM(x, oparg, w);
+ }
+ PUSH(x);
+ continue;
+ }
+ break;
+
+ case BUILD_SET:
+ x = PySet_New(NULL);
+ if (x != NULL) {
+ for (; --oparg >= 0;) {
+ w = POP();
+ if (err == 0)
+ err = PySet_Add(x, w);
+ Py_DECREF(w);
+ }
+ if (err != 0) {
+ Py_DECREF(x);
+ break;
+ }
+ PUSH(x);
+ continue;
+ }
+ break;
+
+
+ case BUILD_MAP:
+ x = _PyDict_NewPresized((Py_ssize_t)oparg);
+ PUSH(x);
+ if (x != NULL) continue;
+ break;
+
+ case STORE_MAP:
+ w = TOP(); /* key */
+ u = SECOND(); /* value */
+ v = THIRD(); /* dict */
+ STACKADJ(-2);
+ assert (PyDict_CheckExact(v));
+ err = PyDict_SetItem(v, w, u); /* v[w] = u */
+ Py_DECREF(u);
+ Py_DECREF(w);
+ if (err == 0) continue;
+ break;
+
+ case MAP_ADD:
+ w = TOP(); /* key */
+ u = SECOND(); /* value */
+ STACKADJ(-2);
+ v = stack_pointer[-oparg]; /* dict */
+ assert (PyDict_CheckExact(v));
+ err = PyDict_SetItem(v, w, u); /* v[w] = u */
+ Py_DECREF(u);
+ Py_DECREF(w);
+ if (err == 0) {
+ PREDICT(JUMP_ABSOLUTE);
+ continue;
+ }
+ break;
+
+ case LOAD_ATTR:
+ w = GETITEM(names, oparg);
+ v = TOP();
+ x = PyObject_GetAttr(v, w);
+ Py_DECREF(v);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case COMPARE_OP:
+ w = POP();
+ v = TOP();
+ if (PyInt_CheckExact(w) && PyInt_CheckExact(v)) {
+ /* INLINE: cmp(int, int) */
+ register long a, b;
+ register int res;
+ a = PyInt_AS_LONG(v);
+ b = PyInt_AS_LONG(w);
+ switch (oparg) {
+ case PyCmp_LT: res = a < b; break;
+ case PyCmp_LE: res = a <= b; break;
+ case PyCmp_EQ: res = a == b; break;
+ case PyCmp_NE: res = a != b; break;
+ case PyCmp_GT: res = a > b; break;
+ case PyCmp_GE: res = a >= b; break;
+ case PyCmp_IS: res = v == w; break;
+ case PyCmp_IS_NOT: res = v != w; break;
+ default: goto slow_compare;
+ }
+ x = res ? Py_True : Py_False;
+ Py_INCREF(x);
+ }
+ else {
+ slow_compare:
+ x = cmp_outcome(oparg, v, w);
+ }
+ Py_DECREF(v);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x == NULL) break;
+ PREDICT(POP_JUMP_IF_FALSE);
+ PREDICT(POP_JUMP_IF_TRUE);
+ continue;
+
+ case IMPORT_NAME:
+ w = GETITEM(names, oparg);
+ x = PyDict_GetItemString(f->f_builtins, "__import__");
+ if (x == NULL) {
+ PyErr_SetString(PyExc_ImportError,
+ "__import__ not found");
+ break;
+ }
+ Py_INCREF(x);
+ v = POP();
+ u = TOP();
+ if (PyInt_AsLong(u) != -1 || PyErr_Occurred())
+ w = PyTuple_Pack(5,
+ w,
+ f->f_globals,
+ f->f_locals == NULL ?
+ Py_None : f->f_locals,
+ v,
+ u);
+ else
+ w = PyTuple_Pack(4,
+ w,
+ f->f_globals,
+ f->f_locals == NULL ?
+ Py_None : f->f_locals,
+ v);
+ Py_DECREF(v);
+ Py_DECREF(u);
+ if (w == NULL) {
+ u = POP();
+ Py_DECREF(x);
+ x = NULL;
+ break;
+ }
+ READ_TIMESTAMP(intr0);
+ v = x;
+ x = PyEval_CallObject(v, w);
+ Py_DECREF(v);
+ READ_TIMESTAMP(intr1);
+ Py_DECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case IMPORT_STAR:
+ v = POP();
+ PyFrame_FastToLocals(f);
+ if ((x = f->f_locals) == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "no locals found during 'import *'");
+ break;
+ }
+ READ_TIMESTAMP(intr0);
+ err = import_all_from(x, v);
+ READ_TIMESTAMP(intr1);
+ PyFrame_LocalsToFast(f, 0);
+ Py_DECREF(v);
+ if (err == 0) continue;
+ break;
+
+ case IMPORT_FROM:
+ w = GETITEM(names, oparg);
+ v = TOP();
+ READ_TIMESTAMP(intr0);
+ x = import_from(v, w);
+ READ_TIMESTAMP(intr1);
+ PUSH(x);
+ if (x != NULL) continue;
+ break;
+
+ case JUMP_FORWARD:
+ JUMPBY(oparg);
+ goto fast_next_opcode;
+
+ PREDICTED_WITH_ARG(POP_JUMP_IF_FALSE);
+ case POP_JUMP_IF_FALSE:
+ w = POP();
+ if (w == Py_True) {
+ Py_DECREF(w);
+ goto fast_next_opcode;
+ }
+ if (w == Py_False) {
+ Py_DECREF(w);
+ JUMPTO(oparg);
+ goto fast_next_opcode;
+ }
+ err = PyObject_IsTrue(w);
+ Py_DECREF(w);
+ if (err > 0)
+ err = 0;
+ else if (err == 0)
+ JUMPTO(oparg);
+ else
+ break;
+ continue;
+
+ PREDICTED_WITH_ARG(POP_JUMP_IF_TRUE);
+ case POP_JUMP_IF_TRUE:
+ w = POP();
+ if (w == Py_False) {
+ Py_DECREF(w);
+ goto fast_next_opcode;
+ }
+ if (w == Py_True) {
+ Py_DECREF(w);
+ JUMPTO(oparg);
+ goto fast_next_opcode;
+ }
+ err = PyObject_IsTrue(w);
+ Py_DECREF(w);
+ if (err > 0) {
+ err = 0;
+ JUMPTO(oparg);
+ }
+ else if (err == 0)
+ ;
+ else
+ break;
+ continue;
+
+ case JUMP_IF_FALSE_OR_POP:
+ w = TOP();
+ if (w == Py_True) {
+ STACKADJ(-1);
+ Py_DECREF(w);
+ goto fast_next_opcode;
+ }
+ if (w == Py_False) {
+ JUMPTO(oparg);
+ goto fast_next_opcode;
+ }
+ err = PyObject_IsTrue(w);
+ if (err > 0) {
+ STACKADJ(-1);
+ Py_DECREF(w);
+ err = 0;
+ }
+ else if (err == 0)
+ JUMPTO(oparg);
+ else
+ break;
+ continue;
+
+ case JUMP_IF_TRUE_OR_POP:
+ w = TOP();
+ if (w == Py_False) {
+ STACKADJ(-1);
+ Py_DECREF(w);
+ goto fast_next_opcode;
+ }
+ if (w == Py_True) {
+ JUMPTO(oparg);
+ goto fast_next_opcode;
+ }
+ err = PyObject_IsTrue(w);
+ if (err > 0) {
+ err = 0;
+ JUMPTO(oparg);
+ }
+ else if (err == 0) {
+ STACKADJ(-1);
+ Py_DECREF(w);
+ }
+ else
+ break;
+ continue;
+
+ PREDICTED_WITH_ARG(JUMP_ABSOLUTE);
+ case JUMP_ABSOLUTE:
+ JUMPTO(oparg);
#if FAST_LOOPS
- /* Enabling this path speeds-up all while and for-loops by bypassing
- the per-loop checks for signals. By default, this should be turned-off
- because it prevents detection of a control-break in tight loops like
- "while 1: pass". Compile with this option turned-on when you need
- the speed-up and do not need break checking inside tight loops (ones
- that contain only instructions ending with goto fast_next_opcode).
- */
- goto fast_next_opcode;
+ /* Enabling this path speeds-up all while and for-loops by bypassing
+ the per-loop checks for signals. By default, this should be turned-off
+ because it prevents detection of a control-break in tight loops like
+ "while 1: pass". Compile with this option turned-on when you need
+ the speed-up and do not need break checking inside tight loops (ones
+ that contain only instructions ending with goto fast_next_opcode).
+ */
+ goto fast_next_opcode;
#else
- continue;
+ continue;
#endif
- case GET_ITER:
- /* before: [obj]; after [getiter(obj)] */
- v = TOP();
- x = PyObject_GetIter(v);
- Py_DECREF(v);
- if (x != NULL) {
- SET_TOP(x);
- PREDICT(FOR_ITER);
- continue;
- }
- STACKADJ(-1);
- break;
-
- PREDICTED_WITH_ARG(FOR_ITER);
- case FOR_ITER:
- /* before: [iter]; after: [iter, iter()] *or* [] */
- v = TOP();
- x = (*v->ob_type->tp_iternext)(v);
- if (x != NULL) {
- PUSH(x);
- PREDICT(STORE_FAST);
- PREDICT(UNPACK_SEQUENCE);
- continue;
- }
- if (PyErr_Occurred()) {
- if (!PyErr_ExceptionMatches(
- PyExc_StopIteration))
- break;
- PyErr_Clear();
- }
- /* iterator ended normally */
- x = v = POP();
- Py_DECREF(v);
- JUMPBY(oparg);
- continue;
-
- case BREAK_LOOP:
- why = WHY_BREAK;
- goto fast_block_end;
-
- case CONTINUE_LOOP:
- retval = PyInt_FromLong(oparg);
- if (!retval) {
- x = NULL;
- break;
- }
- why = WHY_CONTINUE;
- goto fast_block_end;
-
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- /* NOTE: If you add any new block-setup opcodes that
- are not try/except/finally handlers, you may need
- to update the PyGen_NeedsFinalizing() function.
- */
-
- PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
- STACK_LEVEL());
- continue;
-
- case SETUP_WITH:
- {
- static PyObject *exit, *enter;
- w = TOP();
- x = special_lookup(w, "__exit__", &exit);
- if (!x)
- break;
- SET_TOP(x);
- u = special_lookup(w, "__enter__", &enter);
- Py_DECREF(w);
- if (!u) {
- x = NULL;
- break;
- }
- x = PyObject_CallFunctionObjArgs(u, NULL);
- Py_DECREF(u);
- if (!x)
- break;
- /* Setup a finally block (SETUP_WITH as a block is
- equivalent to SETUP_FINALLY except it normalizes
- the exception) before pushing the result of
- __enter__ on the stack. */
- PyFrame_BlockSetup(f, SETUP_WITH, INSTR_OFFSET() + oparg,
- STACK_LEVEL());
-
- PUSH(x);
- continue;
- }
-
- case WITH_CLEANUP:
- {
- /* At the top of the stack are 1-3 values indicating
- how/why we entered the finally clause:
- - TOP = None
- - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
- - TOP = WHY_*; no retval below it
- - (TOP, SECOND, THIRD) = exc_info()
- Below them is EXIT, the context.__exit__ bound method.
- In the last case, we must call
- EXIT(TOP, SECOND, THIRD)
- otherwise we must call
- EXIT(None, None, None)
-
- In all cases, we remove EXIT from the stack, leaving
- the rest in the same order.
-
- In addition, if the stack represents an exception,
- *and* the function call returns a 'true' value, we
- "zap" this information, to prevent END_FINALLY from
- re-raising the exception. (But non-local gotos
- should still be resumed.)
- */
-
- PyObject *exit_func;
-
- u = POP();
- if (u == Py_None) {
- exit_func = TOP();
- SET_TOP(u);
- v = w = Py_None;
- }
- else if (PyInt_Check(u)) {
- switch(PyInt_AS_LONG(u)) {
- case WHY_RETURN:
- case WHY_CONTINUE:
- /* Retval in TOP. */
- exit_func = SECOND();
- SET_SECOND(TOP());
- SET_TOP(u);
- break;
- default:
- exit_func = TOP();
- SET_TOP(u);
- break;
- }
- u = v = w = Py_None;
- }
- else {
- v = TOP();
- w = SECOND();
- exit_func = THIRD();
- SET_TOP(u);
- SET_SECOND(v);
- SET_THIRD(w);
- }
- /* XXX Not the fastest way to call it... */
- x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
- NULL);
- Py_DECREF(exit_func);
- if (x == NULL)
- break; /* Go to error exit */
-
- if (u != Py_None)
- err = PyObject_IsTrue(x);
- else
- err = 0;
- Py_DECREF(x);
-
- if (err < 0)
- break; /* Go to error exit */
- else if (err > 0) {
- err = 0;
- /* There was an exception and a true return */
- STACKADJ(-2);
- Py_INCREF(Py_None);
- SET_TOP(Py_None);
- Py_DECREF(u);
- Py_DECREF(v);
- Py_DECREF(w);
- } else {
- /* The stack was rearranged to remove EXIT
- above. Let END_FINALLY do its thing */
- }
- PREDICT(END_FINALLY);
- break;
- }
-
- case CALL_FUNCTION:
- {
- PyObject **sp;
- PCALL(PCALL_ALL);
- sp = stack_pointer;
+ case GET_ITER:
+ /* before: [obj]; after [getiter(obj)] */
+ v = TOP();
+ x = PyObject_GetIter(v);
+ Py_DECREF(v);
+ if (x != NULL) {
+ SET_TOP(x);
+ PREDICT(FOR_ITER);
+ continue;
+ }
+ STACKADJ(-1);
+ break;
+
+ PREDICTED_WITH_ARG(FOR_ITER);
+ case FOR_ITER:
+ /* before: [iter]; after: [iter, iter()] *or* [] */
+ v = TOP();
+ x = (*v->ob_type->tp_iternext)(v);
+ if (x != NULL) {
+ PUSH(x);
+ PREDICT(STORE_FAST);
+ PREDICT(UNPACK_SEQUENCE);
+ continue;
+ }
+ if (PyErr_Occurred()) {
+ if (!PyErr_ExceptionMatches(
+ PyExc_StopIteration))
+ break;
+ PyErr_Clear();
+ }
+ /* iterator ended normally */
+ x = v = POP();
+ Py_DECREF(v);
+ JUMPBY(oparg);
+ continue;
+
+ case BREAK_LOOP:
+ why = WHY_BREAK;
+ goto fast_block_end;
+
+ case CONTINUE_LOOP:
+ retval = PyInt_FromLong(oparg);
+ if (!retval) {
+ x = NULL;
+ break;
+ }
+ why = WHY_CONTINUE;
+ goto fast_block_end;
+
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ /* NOTE: If you add any new block-setup opcodes that
+ are not try/except/finally handlers, you may need
+ to update the PyGen_NeedsFinalizing() function.
+ */
+
+ PyFrame_BlockSetup(f, opcode, INSTR_OFFSET() + oparg,
+ STACK_LEVEL());
+ continue;
+
+ case SETUP_WITH:
+ {
+ static PyObject *exit, *enter;
+ w = TOP();
+ x = special_lookup(w, "__exit__", &exit);
+ if (!x)
+ break;
+ SET_TOP(x);
+ u = special_lookup(w, "__enter__", &enter);
+ Py_DECREF(w);
+ if (!u) {
+ x = NULL;
+ break;
+ }
+ x = PyObject_CallFunctionObjArgs(u, NULL);
+ Py_DECREF(u);
+ if (!x)
+ break;
+ /* Setup a finally block (SETUP_WITH as a block is
+ equivalent to SETUP_FINALLY except it normalizes
+ the exception) before pushing the result of
+ __enter__ on the stack. */
+ PyFrame_BlockSetup(f, SETUP_WITH, INSTR_OFFSET() + oparg,
+ STACK_LEVEL());
+
+ PUSH(x);
+ continue;
+ }
+
+ case WITH_CLEANUP:
+ {
+ /* At the top of the stack are 1-3 values indicating
+ how/why we entered the finally clause:
+ - TOP = None
+ - (TOP, SECOND) = (WHY_{RETURN,CONTINUE}), retval
+ - TOP = WHY_*; no retval below it
+ - (TOP, SECOND, THIRD) = exc_info()
+ Below them is EXIT, the context.__exit__ bound method.
+ In the last case, we must call
+ EXIT(TOP, SECOND, THIRD)
+ otherwise we must call
+ EXIT(None, None, None)
+
+ In all cases, we remove EXIT from the stack, leaving
+ the rest in the same order.
+
+ In addition, if the stack represents an exception,
+ *and* the function call returns a 'true' value, we
+ "zap" this information, to prevent END_FINALLY from
+ re-raising the exception. (But non-local gotos
+ should still be resumed.)
+ */
+
+ PyObject *exit_func;
+
+ u = POP();
+ if (u == Py_None) {
+ exit_func = TOP();
+ SET_TOP(u);
+ v = w = Py_None;
+ }
+ else if (PyInt_Check(u)) {
+ switch(PyInt_AS_LONG(u)) {
+ case WHY_RETURN:
+ case WHY_CONTINUE:
+ /* Retval in TOP. */
+ exit_func = SECOND();
+ SET_SECOND(TOP());
+ SET_TOP(u);
+ break;
+ default:
+ exit_func = TOP();
+ SET_TOP(u);
+ break;
+ }
+ u = v = w = Py_None;
+ }
+ else {
+ v = TOP();
+ w = SECOND();
+ exit_func = THIRD();
+ SET_TOP(u);
+ SET_SECOND(v);
+ SET_THIRD(w);
+ }
+ /* XXX Not the fastest way to call it... */
+ x = PyObject_CallFunctionObjArgs(exit_func, u, v, w,
+ NULL);
+ Py_DECREF(exit_func);
+ if (x == NULL)
+ break; /* Go to error exit */
+
+ if (u != Py_None)
+ err = PyObject_IsTrue(x);
+ else
+ err = 0;
+ Py_DECREF(x);
+
+ if (err < 0)
+ break; /* Go to error exit */
+ else if (err > 0) {
+ err = 0;
+ /* There was an exception and a true return */
+ STACKADJ(-2);
+ Py_INCREF(Py_None);
+ SET_TOP(Py_None);
+ Py_DECREF(u);
+ Py_DECREF(v);
+ Py_DECREF(w);
+ } else {
+ /* The stack was rearranged to remove EXIT
+ above. Let END_FINALLY do its thing */
+ }
+ PREDICT(END_FINALLY);
+ break;
+ }
+
+ case CALL_FUNCTION:
+ {
+ PyObject **sp;
+ PCALL(PCALL_ALL);
+ sp = stack_pointer;
#ifdef WITH_TSC
- x = call_function(&sp, oparg, &intr0, &intr1);
+ x = call_function(&sp, oparg, &intr0, &intr1);
#else
- x = call_function(&sp, oparg);
+ x = call_function(&sp, oparg);
#endif
- stack_pointer = sp;
- PUSH(x);
- if (x != NULL)
- continue;
- break;
- }
-
- case CALL_FUNCTION_VAR:
- case CALL_FUNCTION_KW:
- case CALL_FUNCTION_VAR_KW:
- {
- int na = oparg & 0xff;
- int nk = (oparg>>8) & 0xff;
- int flags = (opcode - CALL_FUNCTION) & 3;
- int n = na + 2 * nk;
- PyObject **pfunc, *func, **sp;
- PCALL(PCALL_ALL);
- if (flags & CALL_FLAG_VAR)
- n++;
- if (flags & CALL_FLAG_KW)
- n++;
- pfunc = stack_pointer - n - 1;
- func = *pfunc;
-
- if (PyMethod_Check(func)
- && PyMethod_GET_SELF(func) != NULL) {
- PyObject *self = PyMethod_GET_SELF(func);
- Py_INCREF(self);
- func = PyMethod_GET_FUNCTION(func);
- Py_INCREF(func);
- Py_DECREF(*pfunc);
- *pfunc = self;
- na++;
- } else
- Py_INCREF(func);
- sp = stack_pointer;
- READ_TIMESTAMP(intr0);
- x = ext_do_call(func, &sp, flags, na, nk);
- READ_TIMESTAMP(intr1);
- stack_pointer = sp;
- Py_DECREF(func);
-
- while (stack_pointer > pfunc) {
- w = POP();
- Py_DECREF(w);
- }
- PUSH(x);
- if (x != NULL)
- continue;
- break;
- }
-
- case MAKE_FUNCTION:
- v = POP(); /* code object */
- x = PyFunction_New(v, f->f_globals);
- Py_DECREF(v);
- /* XXX Maybe this should be a separate opcode? */
- if (x != NULL && oparg > 0) {
- v = PyTuple_New(oparg);
- if (v == NULL) {
- Py_DECREF(x);
- x = NULL;
- break;
- }
- while (--oparg >= 0) {
- w = POP();
- PyTuple_SET_ITEM(v, oparg, w);
- }
- err = PyFunction_SetDefaults(x, v);
- Py_DECREF(v);
- }
- PUSH(x);
- break;
-
- case MAKE_CLOSURE:
- {
- v = POP(); /* code object */
- x = PyFunction_New(v, f->f_globals);
- Py_DECREF(v);
- if (x != NULL) {
- v = POP();
- if (PyFunction_SetClosure(x, v) != 0) {
- /* Can't happen unless bytecode is corrupt. */
- why = WHY_EXCEPTION;
- }
- Py_DECREF(v);
- }
- if (x != NULL && oparg > 0) {
- v = PyTuple_New(oparg);
- if (v == NULL) {
- Py_DECREF(x);
- x = NULL;
- break;
- }
- while (--oparg >= 0) {
- w = POP();
- PyTuple_SET_ITEM(v, oparg, w);
- }
- if (PyFunction_SetDefaults(x, v) != 0) {
- /* Can't happen unless
- PyFunction_SetDefaults changes. */
- why = WHY_EXCEPTION;
- }
- Py_DECREF(v);
- }
- PUSH(x);
- break;
- }
-
- case BUILD_SLICE:
- if (oparg == 3)
- w = POP();
- else
- w = NULL;
- v = POP();
- u = TOP();
- x = PySlice_New(u, v, w);
- Py_DECREF(u);
- Py_DECREF(v);
- Py_XDECREF(w);
- SET_TOP(x);
- if (x != NULL) continue;
- break;
-
- case EXTENDED_ARG:
- opcode = NEXTOP();
- oparg = oparg<<16 | NEXTARG();
- goto dispatch_opcode;
-
- default:
- fprintf(stderr,
- "XXX lineno: %d, opcode: %d\n",
- PyFrame_GetLineNumber(f),
- opcode);
- PyErr_SetString(PyExc_SystemError, "unknown opcode");
- why = WHY_EXCEPTION;
- break;
+ stack_pointer = sp;
+ PUSH(x);
+ if (x != NULL)
+ continue;
+ break;
+ }
+
+ case CALL_FUNCTION_VAR:
+ case CALL_FUNCTION_KW:
+ case CALL_FUNCTION_VAR_KW:
+ {
+ int na = oparg & 0xff;
+ int nk = (oparg>>8) & 0xff;
+ int flags = (opcode - CALL_FUNCTION) & 3;
+ int n = na + 2 * nk;
+ PyObject **pfunc, *func, **sp;
+ PCALL(PCALL_ALL);
+ if (flags & CALL_FLAG_VAR)
+ n++;
+ if (flags & CALL_FLAG_KW)
+ n++;
+ pfunc = stack_pointer - n - 1;
+ func = *pfunc;
+
+ if (PyMethod_Check(func)
+ && PyMethod_GET_SELF(func) != NULL) {
+ PyObject *self = PyMethod_GET_SELF(func);
+ Py_INCREF(self);
+ func = PyMethod_GET_FUNCTION(func);
+ Py_INCREF(func);
+ Py_DECREF(*pfunc);
+ *pfunc = self;
+ na++;
+ } else
+ Py_INCREF(func);
+ sp = stack_pointer;
+ READ_TIMESTAMP(intr0);
+ x = ext_do_call(func, &sp, flags, na, nk);
+ READ_TIMESTAMP(intr1);
+ stack_pointer = sp;
+ Py_DECREF(func);
+
+ while (stack_pointer > pfunc) {
+ w = POP();
+ Py_DECREF(w);
+ }
+ PUSH(x);
+ if (x != NULL)
+ continue;
+ break;
+ }
+
+ case MAKE_FUNCTION:
+ v = POP(); /* code object */
+ x = PyFunction_New(v, f->f_globals);
+ Py_DECREF(v);
+ /* XXX Maybe this should be a separate opcode? */
+ if (x != NULL && oparg > 0) {
+ v = PyTuple_New(oparg);
+ if (v == NULL) {
+ Py_DECREF(x);
+ x = NULL;
+ break;
+ }
+ while (--oparg >= 0) {
+ w = POP();
+ PyTuple_SET_ITEM(v, oparg, w);
+ }
+ err = PyFunction_SetDefaults(x, v);
+ Py_DECREF(v);
+ }
+ PUSH(x);
+ break;
+
+ case MAKE_CLOSURE:
+ {
+ v = POP(); /* code object */
+ x = PyFunction_New(v, f->f_globals);
+ Py_DECREF(v);
+ if (x != NULL) {
+ v = POP();
+ if (PyFunction_SetClosure(x, v) != 0) {
+ /* Can't happen unless bytecode is corrupt. */
+ why = WHY_EXCEPTION;
+ }
+ Py_DECREF(v);
+ }
+ if (x != NULL && oparg > 0) {
+ v = PyTuple_New(oparg);
+ if (v == NULL) {
+ Py_DECREF(x);
+ x = NULL;
+ break;
+ }
+ while (--oparg >= 0) {
+ w = POP();
+ PyTuple_SET_ITEM(v, oparg, w);
+ }
+ if (PyFunction_SetDefaults(x, v) != 0) {
+ /* Can't happen unless
+ PyFunction_SetDefaults changes. */
+ why = WHY_EXCEPTION;
+ }
+ Py_DECREF(v);
+ }
+ PUSH(x);
+ break;
+ }
+
+ case BUILD_SLICE:
+ if (oparg == 3)
+ w = POP();
+ else
+ w = NULL;
+ v = POP();
+ u = TOP();
+ x = PySlice_New(u, v, w);
+ Py_DECREF(u);
+ Py_DECREF(v);
+ Py_XDECREF(w);
+ SET_TOP(x);
+ if (x != NULL) continue;
+ break;
+
+ case EXTENDED_ARG:
+ opcode = NEXTOP();
+ oparg = oparg<<16 | NEXTARG();
+ goto dispatch_opcode;
+
+ default:
+ fprintf(stderr,
+ "XXX lineno: %d, opcode: %d\n",
+ PyFrame_GetLineNumber(f),
+ opcode);
+ PyErr_SetString(PyExc_SystemError, "unknown opcode");
+ why = WHY_EXCEPTION;
+ break;
#ifdef CASE_TOO_BIG
- }
+ }
#endif
- } /* switch */
+ } /* switch */
- on_error:
+ on_error:
- READ_TIMESTAMP(inst1);
+ READ_TIMESTAMP(inst1);
- /* Quickly continue if no error occurred */
+ /* Quickly continue if no error occurred */
- if (why == WHY_NOT) {
- if (err == 0 && x != NULL) {
+ if (why == WHY_NOT) {
+ if (err == 0 && x != NULL) {
#ifdef CHECKEXC
- /* This check is expensive! */
- if (PyErr_Occurred())
- fprintf(stderr,
- "XXX undetected error\n");
- else {
+ /* This check is expensive! */
+ if (PyErr_Occurred())
+ fprintf(stderr,
+ "XXX undetected error\n");
+ else {
#endif
- READ_TIMESTAMP(loop1);
- continue; /* Normal, fast path */
+ READ_TIMESTAMP(loop1);
+ continue; /* Normal, fast path */
#ifdef CHECKEXC
- }
+ }
#endif
- }
- why = WHY_EXCEPTION;
- x = Py_None;
- err = 0;
- }
-
- /* Double-check exception status */
-
- if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
- if (!PyErr_Occurred()) {
- PyErr_SetString(PyExc_SystemError,
- "error return without exception set");
- why = WHY_EXCEPTION;
- }
- }
+ }
+ why = WHY_EXCEPTION;
+ x = Py_None;
+ err = 0;
+ }
+
+ /* Double-check exception status */
+
+ if (why == WHY_EXCEPTION || why == WHY_RERAISE) {
+ if (!PyErr_Occurred()) {
+ PyErr_SetString(PyExc_SystemError,
+ "error return without exception set");
+ why = WHY_EXCEPTION;
+ }
+ }
#ifdef CHECKEXC
- else {
- /* This check is expensive! */
- if (PyErr_Occurred()) {
- char buf[128];
- sprintf(buf, "Stack unwind with exception "
- "set and why=%d", why);
- Py_FatalError(buf);
- }
- }
+ else {
+ /* This check is expensive! */
+ if (PyErr_Occurred()) {
+ char buf[128];
+ sprintf(buf, "Stack unwind with exception "
+ "set and why=%d", why);
+ Py_FatalError(buf);
+ }
+ }
#endif
- /* Log traceback info if this is a real exception */
+ /* Log traceback info if this is a real exception */
- if (why == WHY_EXCEPTION) {
- PyTraceBack_Here(f);
+ if (why == WHY_EXCEPTION) {
+ PyTraceBack_Here(f);
- if (tstate->c_tracefunc != NULL)
- call_exc_trace(tstate->c_tracefunc,
- tstate->c_traceobj, f);
- }
+ if (tstate->c_tracefunc != NULL)
+ call_exc_trace(tstate->c_tracefunc,
+ tstate->c_traceobj, f);
+ }
- /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
+ /* For the rest, treat WHY_RERAISE as WHY_EXCEPTION */
- if (why == WHY_RERAISE)
- why = WHY_EXCEPTION;
+ if (why == WHY_RERAISE)
+ why = WHY_EXCEPTION;
- /* Unwind stacks if a (pseudo) exception occurred */
+ /* Unwind stacks if a (pseudo) exception occurred */
fast_block_end:
- while (why != WHY_NOT && f->f_iblock > 0) {
- /* Peek at the current block. */
- PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
-
- assert(why != WHY_YIELD);
- if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
- why = WHY_NOT;
- JUMPTO(PyInt_AS_LONG(retval));
- Py_DECREF(retval);
- break;
- }
-
- /* Now we have to pop the block. */
- f->f_iblock--;
-
- while (STACK_LEVEL() > b->b_level) {
- v = POP();
- Py_XDECREF(v);
- }
- if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
- why = WHY_NOT;
- JUMPTO(b->b_handler);
- break;
- }
- if (b->b_type == SETUP_FINALLY ||
- (b->b_type == SETUP_EXCEPT &&
- why == WHY_EXCEPTION) ||
- b->b_type == SETUP_WITH) {
- if (why == WHY_EXCEPTION) {
- PyObject *exc, *val, *tb;
- PyErr_Fetch(&exc, &val, &tb);
- if (val == NULL) {
- val = Py_None;
- Py_INCREF(val);
- }
- /* Make the raw exception data
- available to the handler,
- so a program can emulate the
- Python main loop. Don't do
- this for 'finally'. */
- if (b->b_type == SETUP_EXCEPT ||
- b->b_type == SETUP_WITH) {
- PyErr_NormalizeException(
- &exc, &val, &tb);
- set_exc_info(tstate,
- exc, val, tb);
- }
- if (tb == NULL) {
- Py_INCREF(Py_None);
- PUSH(Py_None);
- } else
- PUSH(tb);
- PUSH(val);
- PUSH(exc);
- }
- else {
- if (why & (WHY_RETURN | WHY_CONTINUE))
- PUSH(retval);
- v = PyInt_FromLong((long)why);
- PUSH(v);
- }
- why = WHY_NOT;
- JUMPTO(b->b_handler);
- break;
- }
- } /* unwind stack */
-
- /* End the loop if we still have an error (or return) */
-
- if (why != WHY_NOT)
- break;
- READ_TIMESTAMP(loop1);
-
- } /* main loop */
-
- assert(why != WHY_YIELD);
- /* Pop remaining stack entries. */
- while (!EMPTY()) {
- v = POP();
- Py_XDECREF(v);
- }
-
- if (why != WHY_RETURN)
- retval = NULL;
+ while (why != WHY_NOT && f->f_iblock > 0) {
+ /* Peek at the current block. */
+ PyTryBlock *b = &f->f_blockstack[f->f_iblock - 1];
+
+ assert(why != WHY_YIELD);
+ if (b->b_type == SETUP_LOOP && why == WHY_CONTINUE) {
+ why = WHY_NOT;
+ JUMPTO(PyInt_AS_LONG(retval));
+ Py_DECREF(retval);
+ break;
+ }
+
+ /* Now we have to pop the block. */
+ f->f_iblock--;
+
+ while (STACK_LEVEL() > b->b_level) {
+ v = POP();
+ Py_XDECREF(v);
+ }
+ if (b->b_type == SETUP_LOOP && why == WHY_BREAK) {
+ why = WHY_NOT;
+ JUMPTO(b->b_handler);
+ break;
+ }
+ if (b->b_type == SETUP_FINALLY ||
+ (b->b_type == SETUP_EXCEPT &&
+ why == WHY_EXCEPTION) ||
+ b->b_type == SETUP_WITH) {
+ if (why == WHY_EXCEPTION) {
+ PyObject *exc, *val, *tb;
+ PyErr_Fetch(&exc, &val, &tb);
+ if (val == NULL) {
+ val = Py_None;
+ Py_INCREF(val);
+ }
+ /* Make the raw exception data
+ available to the handler,
+ so a program can emulate the
+ Python main loop. Don't do
+ this for 'finally'. */
+ if (b->b_type == SETUP_EXCEPT ||
+ b->b_type == SETUP_WITH) {
+ PyErr_NormalizeException(
+ &exc, &val, &tb);
+ set_exc_info(tstate,
+ exc, val, tb);
+ }
+ if (tb == NULL) {
+ Py_INCREF(Py_None);
+ PUSH(Py_None);
+ } else
+ PUSH(tb);
+ PUSH(val);
+ PUSH(exc);
+ }
+ else {
+ if (why & (WHY_RETURN | WHY_CONTINUE))
+ PUSH(retval);
+ v = PyInt_FromLong((long)why);
+ PUSH(v);
+ }
+ why = WHY_NOT;
+ JUMPTO(b->b_handler);
+ break;
+ }
+ } /* unwind stack */
+
+ /* End the loop if we still have an error (or return) */
+
+ if (why != WHY_NOT)
+ break;
+ READ_TIMESTAMP(loop1);
+
+ } /* main loop */
+
+ assert(why != WHY_YIELD);
+ /* Pop remaining stack entries. */
+ while (!EMPTY()) {
+ v = POP();
+ Py_XDECREF(v);
+ }
+
+ if (why != WHY_RETURN)
+ retval = NULL;
fast_yield:
- if (tstate->use_tracing) {
- if (tstate->c_tracefunc) {
- if (why == WHY_RETURN || why == WHY_YIELD) {
- if (call_trace(tstate->c_tracefunc,
- tstate->c_traceobj, f,
- PyTrace_RETURN, retval)) {
- Py_XDECREF(retval);
- retval = NULL;
- why = WHY_EXCEPTION;
- }
- }
- else if (why == WHY_EXCEPTION) {
- call_trace_protected(tstate->c_tracefunc,
- tstate->c_traceobj, f,
- PyTrace_RETURN, NULL);
- }
- }
- if (tstate->c_profilefunc) {
- if (why == WHY_EXCEPTION)
- call_trace_protected(tstate->c_profilefunc,
- tstate->c_profileobj, f,
- PyTrace_RETURN, NULL);
- else if (call_trace(tstate->c_profilefunc,
- tstate->c_profileobj, f,
- PyTrace_RETURN, retval)) {
- Py_XDECREF(retval);
- retval = NULL;
- why = WHY_EXCEPTION;
- }
- }
- }
-
- if (tstate->frame->f_exc_type != NULL)
- reset_exc_info(tstate);
- else {
- assert(tstate->frame->f_exc_value == NULL);
- assert(tstate->frame->f_exc_traceback == NULL);
- }
-
- /* pop frame */
+ if (tstate->use_tracing) {
+ if (tstate->c_tracefunc) {
+ if (why == WHY_RETURN || why == WHY_YIELD) {
+ if (call_trace(tstate->c_tracefunc,
+ tstate->c_traceobj, f,
+ PyTrace_RETURN, retval)) {
+ Py_XDECREF(retval);
+ retval = NULL;
+ why = WHY_EXCEPTION;
+ }
+ }
+ else if (why == WHY_EXCEPTION) {
+ call_trace_protected(tstate->c_tracefunc,
+ tstate->c_traceobj, f,
+ PyTrace_RETURN, NULL);
+ }
+ }
+ if (tstate->c_profilefunc) {
+ if (why == WHY_EXCEPTION)
+ call_trace_protected(tstate->c_profilefunc,
+ tstate->c_profileobj, f,
+ PyTrace_RETURN, NULL);
+ else if (call_trace(tstate->c_profilefunc,
+ tstate->c_profileobj, f,
+ PyTrace_RETURN, retval)) {
+ Py_XDECREF(retval);
+ retval = NULL;
+ why = WHY_EXCEPTION;
+ }
+ }
+ }
+
+ if (tstate->frame->f_exc_type != NULL)
+ reset_exc_info(tstate);
+ else {
+ assert(tstate->frame->f_exc_value == NULL);
+ assert(tstate->frame->f_exc_traceback == NULL);
+ }
+
+ /* pop frame */
exit_eval_frame:
- Py_LeaveRecursiveCall();
- tstate->frame = f->f_back;
+ Py_LeaveRecursiveCall();
+ tstate->frame = f->f_back;
- return retval;
+ return retval;
}
/* This is gonna seem *real weird*, but if you put some other code between
@@ -3012,291 +3012,291 @@ exit_eval_frame:
PyObject *
PyEval_EvalCodeEx(PyCodeObject *co, PyObject *globals, PyObject *locals,
- PyObject **args, int argcount, PyObject **kws, int kwcount,
- PyObject **defs, int defcount, PyObject *closure)
+ PyObject **args, int argcount, PyObject **kws, int kwcount,
+ PyObject **defs, int defcount, PyObject *closure)
{
- register PyFrameObject *f;
- register PyObject *retval = NULL;
- register PyObject **fastlocals, **freevars;
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *x, *u;
-
- if (globals == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "PyEval_EvalCodeEx: NULL globals");
- return NULL;
- }
-
- assert(tstate != NULL);
- assert(globals != NULL);
- f = PyFrame_New(tstate, co, globals, locals);
- if (f == NULL)
- return NULL;
-
- fastlocals = f->f_localsplus;
- freevars = f->f_localsplus + co->co_nlocals;
-
- if (co->co_argcount > 0 ||
- co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
- int i;
- int n = argcount;
- PyObject *kwdict = NULL;
- if (co->co_flags & CO_VARKEYWORDS) {
- kwdict = PyDict_New();
- if (kwdict == NULL)
- goto fail;
- i = co->co_argcount;
- if (co->co_flags & CO_VARARGS)
- i++;
- SETLOCAL(i, kwdict);
- }
- if (argcount > co->co_argcount) {
- if (!(co->co_flags & CO_VARARGS)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes %s %d "
- "argument%s (%d given)",
- PyString_AsString(co->co_name),
- defcount ? "at most" : "exactly",
- co->co_argcount,
- co->co_argcount == 1 ? "" : "s",
- argcount + kwcount);
- goto fail;
- }
- n = co->co_argcount;
- }
- for (i = 0; i < n; i++) {
- x = args[i];
- Py_INCREF(x);
- SETLOCAL(i, x);
- }
- if (co->co_flags & CO_VARARGS) {
- u = PyTuple_New(argcount - n);
- if (u == NULL)
- goto fail;
- SETLOCAL(co->co_argcount, u);
- for (i = n; i < argcount; i++) {
- x = args[i];
- Py_INCREF(x);
- PyTuple_SET_ITEM(u, i-n, x);
- }
- }
- for (i = 0; i < kwcount; i++) {
- PyObject **co_varnames;
- PyObject *keyword = kws[2*i];
- PyObject *value = kws[2*i + 1];
- int j;
- if (keyword == NULL || !(PyString_Check(keyword)
+ register PyFrameObject *f;
+ register PyObject *retval = NULL;
+ register PyObject **fastlocals, **freevars;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *x, *u;
+
+ if (globals == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "PyEval_EvalCodeEx: NULL globals");
+ return NULL;
+ }
+
+ assert(tstate != NULL);
+ assert(globals != NULL);
+ f = PyFrame_New(tstate, co, globals, locals);
+ if (f == NULL)
+ return NULL;
+
+ fastlocals = f->f_localsplus;
+ freevars = f->f_localsplus + co->co_nlocals;
+
+ if (co->co_argcount > 0 ||
+ co->co_flags & (CO_VARARGS | CO_VARKEYWORDS)) {
+ int i;
+ int n = argcount;
+ PyObject *kwdict = NULL;
+ if (co->co_flags & CO_VARKEYWORDS) {
+ kwdict = PyDict_New();
+ if (kwdict == NULL)
+ goto fail;
+ i = co->co_argcount;
+ if (co->co_flags & CO_VARARGS)
+ i++;
+ SETLOCAL(i, kwdict);
+ }
+ if (argcount > co->co_argcount) {
+ if (!(co->co_flags & CO_VARARGS)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes %s %d "
+ "argument%s (%d given)",
+ PyString_AsString(co->co_name),
+ defcount ? "at most" : "exactly",
+ co->co_argcount,
+ co->co_argcount == 1 ? "" : "s",
+ argcount + kwcount);
+ goto fail;
+ }
+ n = co->co_argcount;
+ }
+ for (i = 0; i < n; i++) {
+ x = args[i];
+ Py_INCREF(x);
+ SETLOCAL(i, x);
+ }
+ if (co->co_flags & CO_VARARGS) {
+ u = PyTuple_New(argcount - n);
+ if (u == NULL)
+ goto fail;
+ SETLOCAL(co->co_argcount, u);
+ for (i = n; i < argcount; i++) {
+ x = args[i];
+ Py_INCREF(x);
+ PyTuple_SET_ITEM(u, i-n, x);
+ }
+ }
+ for (i = 0; i < kwcount; i++) {
+ PyObject **co_varnames;
+ PyObject *keyword = kws[2*i];
+ PyObject *value = kws[2*i + 1];
+ int j;
+ if (keyword == NULL || !(PyString_Check(keyword)
#ifdef Py_USING_UNICODE
- || PyUnicode_Check(keyword)
+ || PyUnicode_Check(keyword)
#endif
- )) {
- PyErr_Format(PyExc_TypeError,
- "%.200s() keywords must be strings",
- PyString_AsString(co->co_name));
- goto fail;
- }
- /* Speed hack: do raw pointer compares. As names are
- normally interned this should almost always hit. */
- co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
- for (j = 0; j < co->co_argcount; j++) {
- PyObject *nm = co_varnames[j];
- if (nm == keyword)
- goto kw_found;
- }
- /* Slow fallback, just in case */
- for (j = 0; j < co->co_argcount; j++) {
- PyObject *nm = co_varnames[j];
- int cmp = PyObject_RichCompareBool(
- keyword, nm, Py_EQ);
- if (cmp > 0)
- goto kw_found;
- else if (cmp < 0)
- goto fail;
- }
- if (kwdict == NULL) {
- PyObject *kwd_str = kwd_as_string(keyword);
- if (kwd_str) {
- PyErr_Format(PyExc_TypeError,
- "%.200s() got an unexpected "
- "keyword argument '%.400s'",
- PyString_AsString(co->co_name),
- PyString_AsString(kwd_str));
- Py_DECREF(kwd_str);
- }
- goto fail;
- }
- PyDict_SetItem(kwdict, keyword, value);
- continue;
- kw_found:
- if (GETLOCAL(j) != NULL) {
- PyObject *kwd_str = kwd_as_string(keyword);
- if (kwd_str) {
- PyErr_Format(PyExc_TypeError,
- "%.200s() got multiple "
- "values for keyword "
- "argument '%.400s'",
- PyString_AsString(co->co_name),
- PyString_AsString(kwd_str));
- Py_DECREF(kwd_str);
- }
- goto fail;
- }
- Py_INCREF(value);
- SETLOCAL(j, value);
- }
- if (argcount < co->co_argcount) {
- int m = co->co_argcount - defcount;
- for (i = argcount; i < m; i++) {
- if (GETLOCAL(i) == NULL) {
- int j, given = 0;
- for (j = 0; j < co->co_argcount; j++)
- if (GETLOCAL(j))
- given++;
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes %s %d "
- "argument%s (%d given)",
- PyString_AsString(co->co_name),
- ((co->co_flags & CO_VARARGS) ||
- defcount) ? "at least"
- : "exactly",
- m, m == 1 ? "" : "s", given);
- goto fail;
- }
- }
- if (n > m)
- i = n - m;
- else
- i = 0;
- for (; i < defcount; i++) {
- if (GETLOCAL(m+i) == NULL) {
- PyObject *def = defs[i];
- Py_INCREF(def);
- SETLOCAL(m+i, def);
- }
- }
- }
- }
- else if (argcount > 0 || kwcount > 0) {
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes no arguments (%d given)",
- PyString_AsString(co->co_name),
- argcount + kwcount);
- goto fail;
- }
- /* Allocate and initialize storage for cell vars, and copy free
- vars into frame. This isn't too efficient right now. */
- if (PyTuple_GET_SIZE(co->co_cellvars)) {
- int i, j, nargs, found;
- char *cellname, *argname;
- PyObject *c;
-
- nargs = co->co_argcount;
- if (co->co_flags & CO_VARARGS)
- nargs++;
- if (co->co_flags & CO_VARKEYWORDS)
- nargs++;
-
- /* Initialize each cell var, taking into account
- cell vars that are initialized from arguments.
-
- Should arrange for the compiler to put cellvars
- that are arguments at the beginning of the cellvars
- list so that we can march over it more efficiently?
- */
- for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
- cellname = PyString_AS_STRING(
- PyTuple_GET_ITEM(co->co_cellvars, i));
- found = 0;
- for (j = 0; j < nargs; j++) {
- argname = PyString_AS_STRING(
- PyTuple_GET_ITEM(co->co_varnames, j));
- if (strcmp(cellname, argname) == 0) {
- c = PyCell_New(GETLOCAL(j));
- if (c == NULL)
- goto fail;
- GETLOCAL(co->co_nlocals + i) = c;
- found = 1;
- break;
- }
- }
- if (found == 0) {
- c = PyCell_New(NULL);
- if (c == NULL)
- goto fail;
- SETLOCAL(co->co_nlocals + i, c);
- }
- }
- }
- if (PyTuple_GET_SIZE(co->co_freevars)) {
- int i;
- for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
- PyObject *o = PyTuple_GET_ITEM(closure, i);
- Py_INCREF(o);
- freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
- }
- }
-
- if (co->co_flags & CO_GENERATOR) {
- /* Don't need to keep the reference to f_back, it will be set
- * when the generator is resumed. */
- Py_XDECREF(f->f_back);
- f->f_back = NULL;
-
- PCALL(PCALL_GENERATOR);
-
- /* Create a new generator that owns the ready to run frame
- * and return that as the value. */
- return PyGen_New(f);
- }
-
- retval = PyEval_EvalFrameEx(f,0);
+ )) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() keywords must be strings",
+ PyString_AsString(co->co_name));
+ goto fail;
+ }
+ /* Speed hack: do raw pointer compares. As names are
+ normally interned this should almost always hit. */
+ co_varnames = ((PyTupleObject *)(co->co_varnames))->ob_item;
+ for (j = 0; j < co->co_argcount; j++) {
+ PyObject *nm = co_varnames[j];
+ if (nm == keyword)
+ goto kw_found;
+ }
+ /* Slow fallback, just in case */
+ for (j = 0; j < co->co_argcount; j++) {
+ PyObject *nm = co_varnames[j];
+ int cmp = PyObject_RichCompareBool(
+ keyword, nm, Py_EQ);
+ if (cmp > 0)
+ goto kw_found;
+ else if (cmp < 0)
+ goto fail;
+ }
+ if (kwdict == NULL) {
+ PyObject *kwd_str = kwd_as_string(keyword);
+ if (kwd_str) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() got an unexpected "
+ "keyword argument '%.400s'",
+ PyString_AsString(co->co_name),
+ PyString_AsString(kwd_str));
+ Py_DECREF(kwd_str);
+ }
+ goto fail;
+ }
+ PyDict_SetItem(kwdict, keyword, value);
+ continue;
+ kw_found:
+ if (GETLOCAL(j) != NULL) {
+ PyObject *kwd_str = kwd_as_string(keyword);
+ if (kwd_str) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() got multiple "
+ "values for keyword "
+ "argument '%.400s'",
+ PyString_AsString(co->co_name),
+ PyString_AsString(kwd_str));
+ Py_DECREF(kwd_str);
+ }
+ goto fail;
+ }
+ Py_INCREF(value);
+ SETLOCAL(j, value);
+ }
+ if (argcount < co->co_argcount) {
+ int m = co->co_argcount - defcount;
+ for (i = argcount; i < m; i++) {
+ if (GETLOCAL(i) == NULL) {
+ int j, given = 0;
+ for (j = 0; j < co->co_argcount; j++)
+ if (GETLOCAL(j))
+ given++;
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes %s %d "
+ "argument%s (%d given)",
+ PyString_AsString(co->co_name),
+ ((co->co_flags & CO_VARARGS) ||
+ defcount) ? "at least"
+ : "exactly",
+ m, m == 1 ? "" : "s", given);
+ goto fail;
+ }
+ }
+ if (n > m)
+ i = n - m;
+ else
+ i = 0;
+ for (; i < defcount; i++) {
+ if (GETLOCAL(m+i) == NULL) {
+ PyObject *def = defs[i];
+ Py_INCREF(def);
+ SETLOCAL(m+i, def);
+ }
+ }
+ }
+ }
+ else if (argcount > 0 || kwcount > 0) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes no arguments (%d given)",
+ PyString_AsString(co->co_name),
+ argcount + kwcount);
+ goto fail;
+ }
+ /* Allocate and initialize storage for cell vars, and copy free
+ vars into frame. This isn't too efficient right now. */
+ if (PyTuple_GET_SIZE(co->co_cellvars)) {
+ int i, j, nargs, found;
+ char *cellname, *argname;
+ PyObject *c;
+
+ nargs = co->co_argcount;
+ if (co->co_flags & CO_VARARGS)
+ nargs++;
+ if (co->co_flags & CO_VARKEYWORDS)
+ nargs++;
+
+ /* Initialize each cell var, taking into account
+ cell vars that are initialized from arguments.
+
+ Should arrange for the compiler to put cellvars
+ that are arguments at the beginning of the cellvars
+ list so that we can march over it more efficiently?
+ */
+ for (i = 0; i < PyTuple_GET_SIZE(co->co_cellvars); ++i) {
+ cellname = PyString_AS_STRING(
+ PyTuple_GET_ITEM(co->co_cellvars, i));
+ found = 0;
+ for (j = 0; j < nargs; j++) {
+ argname = PyString_AS_STRING(
+ PyTuple_GET_ITEM(co->co_varnames, j));
+ if (strcmp(cellname, argname) == 0) {
+ c = PyCell_New(GETLOCAL(j));
+ if (c == NULL)
+ goto fail;
+ GETLOCAL(co->co_nlocals + i) = c;
+ found = 1;
+ break;
+ }
+ }
+ if (found == 0) {
+ c = PyCell_New(NULL);
+ if (c == NULL)
+ goto fail;
+ SETLOCAL(co->co_nlocals + i, c);
+ }
+ }
+ }
+ if (PyTuple_GET_SIZE(co->co_freevars)) {
+ int i;
+ for (i = 0; i < PyTuple_GET_SIZE(co->co_freevars); ++i) {
+ PyObject *o = PyTuple_GET_ITEM(closure, i);
+ Py_INCREF(o);
+ freevars[PyTuple_GET_SIZE(co->co_cellvars) + i] = o;
+ }
+ }
+
+ if (co->co_flags & CO_GENERATOR) {
+ /* Don't need to keep the reference to f_back, it will be set
+ * when the generator is resumed. */
+ Py_XDECREF(f->f_back);
+ f->f_back = NULL;
+
+ PCALL(PCALL_GENERATOR);
+
+ /* Create a new generator that owns the ready to run frame
+ * and return that as the value. */
+ return PyGen_New(f);
+ }
+
+ retval = PyEval_EvalFrameEx(f,0);
fail: /* Jump here from prelude on failure */
- /* decref'ing the frame can cause __del__ methods to get invoked,
- which can call back into Python. While we're done with the
- current Python frame (f), the associated C stack is still in use,
- so recursion_depth must be boosted for the duration.
- */
- assert(tstate != NULL);
- ++tstate->recursion_depth;
- Py_DECREF(f);
- --tstate->recursion_depth;
- return retval;
+ /* decref'ing the frame can cause __del__ methods to get invoked,
+ which can call back into Python. While we're done with the
+ current Python frame (f), the associated C stack is still in use,
+ so recursion_depth must be boosted for the duration.
+ */
+ assert(tstate != NULL);
+ ++tstate->recursion_depth;
+ Py_DECREF(f);
+ --tstate->recursion_depth;
+ return retval;
}
static PyObject *
special_lookup(PyObject *o, char *meth, PyObject **cache)
{
- PyObject *res;
- if (PyInstance_Check(o)) {
- if (!*cache)
- return PyObject_GetAttrString(o, meth);
- else
- return PyObject_GetAttr(o, *cache);
- }
- res = _PyObject_LookupSpecial(o, meth, cache);
- if (res == NULL && !PyErr_Occurred()) {
- PyErr_SetObject(PyExc_AttributeError, *cache);
- return NULL;
- }
- return res;
+ PyObject *res;
+ if (PyInstance_Check(o)) {
+ if (!*cache)
+ return PyObject_GetAttrString(o, meth);
+ else
+ return PyObject_GetAttr(o, *cache);
+ }
+ res = _PyObject_LookupSpecial(o, meth, cache);
+ if (res == NULL && !PyErr_Occurred()) {
+ PyErr_SetObject(PyExc_AttributeError, *cache);
+ return NULL;
+ }
+ return res;
}
static PyObject *
kwd_as_string(PyObject *kwd) {
#ifdef Py_USING_UNICODE
- if (PyString_Check(kwd)) {
+ if (PyString_Check(kwd)) {
#else
- assert(PyString_Check(kwd));
+ assert(PyString_Check(kwd));
#endif
- Py_INCREF(kwd);
- return kwd;
+ Py_INCREF(kwd);
+ return kwd;
#ifdef Py_USING_UNICODE
- }
- return _PyUnicode_AsDefaultEncodedString(kwd, "replace");
+ }
+ return _PyUnicode_AsDefaultEncodedString(kwd, "replace");
#endif
}
@@ -3324,10 +3324,10 @@ kwd_as_string(PyObject *kwd) {
this:
try:
- "something that may fail"
+ "something that may fail"
except "some exception":
- "do something else first"
- "print the exception from sys.exc_ZZZ."
+ "do something else first"
+ "print the exception from sys.exc_ZZZ."
if "do something else first" invoked something that raised and caught
an exception, sys.exc_ZZZ were overwritten. That was a frequent
@@ -3365,92 +3365,92 @@ kwd_as_string(PyObject *kwd) {
static void
set_exc_info(PyThreadState *tstate,
- PyObject *type, PyObject *value, PyObject *tb)
+ PyObject *type, PyObject *value, PyObject *tb)
{
- PyFrameObject *frame = tstate->frame;
- PyObject *tmp_type, *tmp_value, *tmp_tb;
-
- assert(type != NULL);
- assert(frame != NULL);
- if (frame->f_exc_type == NULL) {
- assert(frame->f_exc_value == NULL);
- assert(frame->f_exc_traceback == NULL);
- /* This frame didn't catch an exception before. */
- /* Save previous exception of this thread in this frame. */
- if (tstate->exc_type == NULL) {
- /* XXX Why is this set to Py_None? */
- Py_INCREF(Py_None);
- tstate->exc_type = Py_None;
- }
- Py_INCREF(tstate->exc_type);
- Py_XINCREF(tstate->exc_value);
- Py_XINCREF(tstate->exc_traceback);
- frame->f_exc_type = tstate->exc_type;
- frame->f_exc_value = tstate->exc_value;
- frame->f_exc_traceback = tstate->exc_traceback;
- }
- /* Set new exception for this thread. */
- tmp_type = tstate->exc_type;
- tmp_value = tstate->exc_value;
- tmp_tb = tstate->exc_traceback;
- Py_INCREF(type);
- Py_XINCREF(value);
- Py_XINCREF(tb);
- tstate->exc_type = type;
- tstate->exc_value = value;
- tstate->exc_traceback = tb;
- Py_XDECREF(tmp_type);
- Py_XDECREF(tmp_value);
- Py_XDECREF(tmp_tb);
- /* For b/w compatibility */
- PySys_SetObject("exc_type", type);
- PySys_SetObject("exc_value", value);
- PySys_SetObject("exc_traceback", tb);
+ PyFrameObject *frame = tstate->frame;
+ PyObject *tmp_type, *tmp_value, *tmp_tb;
+
+ assert(type != NULL);
+ assert(frame != NULL);
+ if (frame->f_exc_type == NULL) {
+ assert(frame->f_exc_value == NULL);
+ assert(frame->f_exc_traceback == NULL);
+ /* This frame didn't catch an exception before. */
+ /* Save previous exception of this thread in this frame. */
+ if (tstate->exc_type == NULL) {
+ /* XXX Why is this set to Py_None? */
+ Py_INCREF(Py_None);
+ tstate->exc_type = Py_None;
+ }
+ Py_INCREF(tstate->exc_type);
+ Py_XINCREF(tstate->exc_value);
+ Py_XINCREF(tstate->exc_traceback);
+ frame->f_exc_type = tstate->exc_type;
+ frame->f_exc_value = tstate->exc_value;
+ frame->f_exc_traceback = tstate->exc_traceback;
+ }
+ /* Set new exception for this thread. */
+ tmp_type = tstate->exc_type;
+ tmp_value = tstate->exc_value;
+ tmp_tb = tstate->exc_traceback;
+ Py_INCREF(type);
+ Py_XINCREF(value);
+ Py_XINCREF(tb);
+ tstate->exc_type = type;
+ tstate->exc_value = value;
+ tstate->exc_traceback = tb;
+ Py_XDECREF(tmp_type);
+ Py_XDECREF(tmp_value);
+ Py_XDECREF(tmp_tb);
+ /* For b/w compatibility */
+ PySys_SetObject("exc_type", type);
+ PySys_SetObject("exc_value", value);
+ PySys_SetObject("exc_traceback", tb);
}
static void
reset_exc_info(PyThreadState *tstate)
{
- PyFrameObject *frame;
- PyObject *tmp_type, *tmp_value, *tmp_tb;
-
- /* It's a precondition that the thread state's frame caught an
- * exception -- verify in a debug build.
- */
- assert(tstate != NULL);
- frame = tstate->frame;
- assert(frame != NULL);
- assert(frame->f_exc_type != NULL);
-
- /* Copy the frame's exception info back to the thread state. */
- tmp_type = tstate->exc_type;
- tmp_value = tstate->exc_value;
- tmp_tb = tstate->exc_traceback;
- Py_INCREF(frame->f_exc_type);
- Py_XINCREF(frame->f_exc_value);
- Py_XINCREF(frame->f_exc_traceback);
- tstate->exc_type = frame->f_exc_type;
- tstate->exc_value = frame->f_exc_value;
- tstate->exc_traceback = frame->f_exc_traceback;
- Py_XDECREF(tmp_type);
- Py_XDECREF(tmp_value);
- Py_XDECREF(tmp_tb);
-
- /* For b/w compatibility */
- PySys_SetObject("exc_type", frame->f_exc_type);
- PySys_SetObject("exc_value", frame->f_exc_value);
- PySys_SetObject("exc_traceback", frame->f_exc_traceback);
-
- /* Clear the frame's exception info. */
- tmp_type = frame->f_exc_type;
- tmp_value = frame->f_exc_value;
- tmp_tb = frame->f_exc_traceback;
- frame->f_exc_type = NULL;
- frame->f_exc_value = NULL;
- frame->f_exc_traceback = NULL;
- Py_DECREF(tmp_type);
- Py_XDECREF(tmp_value);
- Py_XDECREF(tmp_tb);
+ PyFrameObject *frame;
+ PyObject *tmp_type, *tmp_value, *tmp_tb;
+
+ /* It's a precondition that the thread state's frame caught an
+ * exception -- verify in a debug build.
+ */
+ assert(tstate != NULL);
+ frame = tstate->frame;
+ assert(frame != NULL);
+ assert(frame->f_exc_type != NULL);
+
+ /* Copy the frame's exception info back to the thread state. */
+ tmp_type = tstate->exc_type;
+ tmp_value = tstate->exc_value;
+ tmp_tb = tstate->exc_traceback;
+ Py_INCREF(frame->f_exc_type);
+ Py_XINCREF(frame->f_exc_value);
+ Py_XINCREF(frame->f_exc_traceback);
+ tstate->exc_type = frame->f_exc_type;
+ tstate->exc_value = frame->f_exc_value;
+ tstate->exc_traceback = frame->f_exc_traceback;
+ Py_XDECREF(tmp_type);
+ Py_XDECREF(tmp_value);
+ Py_XDECREF(tmp_tb);
+
+ /* For b/w compatibility */
+ PySys_SetObject("exc_type", frame->f_exc_type);
+ PySys_SetObject("exc_value", frame->f_exc_value);
+ PySys_SetObject("exc_traceback", frame->f_exc_traceback);
+
+ /* Clear the frame's exception info. */
+ tmp_type = frame->f_exc_type;
+ tmp_value = frame->f_exc_value;
+ tmp_tb = frame->f_exc_traceback;
+ frame->f_exc_type = NULL;
+ frame->f_exc_value = NULL;
+ frame->f_exc_traceback = NULL;
+ Py_DECREF(tmp_type);
+ Py_XDECREF(tmp_value);
+ Py_XDECREF(tmp_tb);
}
/* Logic for the raise statement (too complicated for inlining).
@@ -3458,108 +3458,108 @@ reset_exc_info(PyThreadState *tstate)
static enum why_code
do_raise(PyObject *type, PyObject *value, PyObject *tb)
{
- if (type == NULL) {
- /* Reraise */
- PyThreadState *tstate = PyThreadState_GET();
- type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
- value = tstate->exc_value;
- tb = tstate->exc_traceback;
- Py_XINCREF(type);
- Py_XINCREF(value);
- Py_XINCREF(tb);
- }
-
- /* We support the following forms of raise:
- raise <class>, <classinstance>
- raise <class>, <argument tuple>
- raise <class>, None
- raise <class>, <argument>
- raise <classinstance>, None
- raise <string>, <object>
- raise <string>, None
-
- An omitted second argument is the same as None.
-
- In addition, raise <tuple>, <anything> is the same as
- raising the tuple's first item (and it better have one!);
- this rule is applied recursively.
-
- Finally, an optional third argument can be supplied, which
- gives the traceback to be substituted (useful when
- re-raising an exception after examining it). */
-
- /* First, check the traceback argument, replacing None with
- NULL. */
- if (tb == Py_None) {
- Py_DECREF(tb);
- tb = NULL;
- }
- else if (tb != NULL && !PyTraceBack_Check(tb)) {
- PyErr_SetString(PyExc_TypeError,
- "raise: arg 3 must be a traceback or None");
- goto raise_error;
- }
-
- /* Next, replace a missing value with None */
- if (value == NULL) {
- value = Py_None;
- Py_INCREF(value);
- }
-
- /* Next, repeatedly, replace a tuple exception with its first item */
- while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
- PyObject *tmp = type;
- type = PyTuple_GET_ITEM(type, 0);
- Py_INCREF(type);
- Py_DECREF(tmp);
- }
-
- if (PyExceptionClass_Check(type))
- PyErr_NormalizeException(&type, &value, &tb);
-
- else if (PyExceptionInstance_Check(type)) {
- /* Raising an instance. The value should be a dummy. */
- if (value != Py_None) {
- PyErr_SetString(PyExc_TypeError,
- "instance exception may not have a separate value");
- goto raise_error;
- }
- else {
- /* Normalize to raise <class>, <instance> */
- Py_DECREF(value);
- value = type;
- type = PyExceptionInstance_Class(type);
- Py_INCREF(type);
- }
- }
- else {
- /* Not something you can raise. You get an exception
- anyway, just not what you specified :-) */
- PyErr_Format(PyExc_TypeError,
- "exceptions must be old-style classes or "
- "derived from BaseException, not %s",
- type->ob_type->tp_name);
- goto raise_error;
- }
-
- assert(PyExceptionClass_Check(type));
- if (Py_Py3kWarningFlag && PyClass_Check(type)) {
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "exceptions must derive from BaseException "
- "in 3.x", 1) < 0)
- goto raise_error;
- }
-
- PyErr_Restore(type, value, tb);
- if (tb == NULL)
- return WHY_EXCEPTION;
- else
- return WHY_RERAISE;
+ if (type == NULL) {
+ /* Reraise */
+ PyThreadState *tstate = PyThreadState_GET();
+ type = tstate->exc_type == NULL ? Py_None : tstate->exc_type;
+ value = tstate->exc_value;
+ tb = tstate->exc_traceback;
+ Py_XINCREF(type);
+ Py_XINCREF(value);
+ Py_XINCREF(tb);
+ }
+
+ /* We support the following forms of raise:
+ raise <class>, <classinstance>
+ raise <class>, <argument tuple>
+ raise <class>, None
+ raise <class>, <argument>
+ raise <classinstance>, None
+ raise <string>, <object>
+ raise <string>, None
+
+ An omitted second argument is the same as None.
+
+ In addition, raise <tuple>, <anything> is the same as
+ raising the tuple's first item (and it better have one!);
+ this rule is applied recursively.
+
+ Finally, an optional third argument can be supplied, which
+ gives the traceback to be substituted (useful when
+ re-raising an exception after examining it). */
+
+ /* First, check the traceback argument, replacing None with
+ NULL. */
+ if (tb == Py_None) {
+ Py_DECREF(tb);
+ tb = NULL;
+ }
+ else if (tb != NULL && !PyTraceBack_Check(tb)) {
+ PyErr_SetString(PyExc_TypeError,
+ "raise: arg 3 must be a traceback or None");
+ goto raise_error;
+ }
+
+ /* Next, replace a missing value with None */
+ if (value == NULL) {
+ value = Py_None;
+ Py_INCREF(value);
+ }
+
+ /* Next, repeatedly, replace a tuple exception with its first item */
+ while (PyTuple_Check(type) && PyTuple_Size(type) > 0) {
+ PyObject *tmp = type;
+ type = PyTuple_GET_ITEM(type, 0);
+ Py_INCREF(type);
+ Py_DECREF(tmp);
+ }
+
+ if (PyExceptionClass_Check(type))
+ PyErr_NormalizeException(&type, &value, &tb);
+
+ else if (PyExceptionInstance_Check(type)) {
+ /* Raising an instance. The value should be a dummy. */
+ if (value != Py_None) {
+ PyErr_SetString(PyExc_TypeError,
+ "instance exception may not have a separate value");
+ goto raise_error;
+ }
+ else {
+ /* Normalize to raise <class>, <instance> */
+ Py_DECREF(value);
+ value = type;
+ type = PyExceptionInstance_Class(type);
+ Py_INCREF(type);
+ }
+ }
+ else {
+ /* Not something you can raise. You get an exception
+ anyway, just not what you specified :-) */
+ PyErr_Format(PyExc_TypeError,
+ "exceptions must be old-style classes or "
+ "derived from BaseException, not %s",
+ type->ob_type->tp_name);
+ goto raise_error;
+ }
+
+ assert(PyExceptionClass_Check(type));
+ if (Py_Py3kWarningFlag && PyClass_Check(type)) {
+ if (PyErr_WarnEx(PyExc_DeprecationWarning,
+ "exceptions must derive from BaseException "
+ "in 3.x", 1) < 0)
+ goto raise_error;
+ }
+
+ PyErr_Restore(type, value, tb);
+ if (tb == NULL)
+ return WHY_EXCEPTION;
+ else
+ return WHY_RERAISE;
raise_error:
- Py_XDECREF(value);
- Py_XDECREF(type);
- Py_XDECREF(tb);
- return WHY_EXCEPTION;
+ Py_XDECREF(value);
+ Py_XDECREF(type);
+ Py_XDECREF(tb);
+ return WHY_EXCEPTION;
}
/* Iterate v argcnt times and store the results on the stack (via decreasing
@@ -3568,46 +3568,46 @@ do_raise(PyObject *type, PyObject *value, PyObject *tb)
static int
unpack_iterable(PyObject *v, int argcnt, PyObject **sp)
{
- int i = 0;
- PyObject *it; /* iter(v) */
- PyObject *w;
-
- assert(v != NULL);
-
- it = PyObject_GetIter(v);
- if (it == NULL)
- goto Error;
-
- for (; i < argcnt; i++) {
- w = PyIter_Next(it);
- if (w == NULL) {
- /* Iterator done, via error or exhaustion. */
- if (!PyErr_Occurred()) {
- PyErr_Format(PyExc_ValueError,
- "need more than %d value%s to unpack",
- i, i == 1 ? "" : "s");
- }
- goto Error;
- }
- *--sp = w;
- }
-
- /* We better have exhausted the iterator now. */
- w = PyIter_Next(it);
- if (w == NULL) {
- if (PyErr_Occurred())
- goto Error;
- Py_DECREF(it);
- return 1;
- }
- Py_DECREF(w);
- PyErr_SetString(PyExc_ValueError, "too many values to unpack");
- /* fall through */
+ int i = 0;
+ PyObject *it; /* iter(v) */
+ PyObject *w;
+
+ assert(v != NULL);
+
+ it = PyObject_GetIter(v);
+ if (it == NULL)
+ goto Error;
+
+ for (; i < argcnt; i++) {
+ w = PyIter_Next(it);
+ if (w == NULL) {
+ /* Iterator done, via error or exhaustion. */
+ if (!PyErr_Occurred()) {
+ PyErr_Format(PyExc_ValueError,
+ "need more than %d value%s to unpack",
+ i, i == 1 ? "" : "s");
+ }
+ goto Error;
+ }
+ *--sp = w;
+ }
+
+ /* We better have exhausted the iterator now. */
+ w = PyIter_Next(it);
+ if (w == NULL) {
+ if (PyErr_Occurred())
+ goto Error;
+ Py_DECREF(it);
+ return 1;
+ }
+ Py_DECREF(w);
+ PyErr_SetString(PyExc_ValueError, "too many values to unpack");
+ /* fall through */
Error:
- for (; i > 0; i--, sp++)
- Py_DECREF(*sp);
- Py_XDECREF(it);
- return 0;
+ for (; i > 0; i--, sp++)
+ Py_DECREF(*sp);
+ Py_XDECREF(it);
+ return 0;
}
@@ -3615,238 +3615,238 @@ Error:
static int
prtrace(PyObject *v, char *str)
{
- printf("%s ", str);
- if (PyObject_Print(v, stdout, 0) != 0)
- PyErr_Clear(); /* Don't know what else to do */
- printf("\n");
- return 1;
+ printf("%s ", str);
+ if (PyObject_Print(v, stdout, 0) != 0)
+ PyErr_Clear(); /* Don't know what else to do */
+ printf("\n");
+ return 1;
}
#endif
static void
call_exc_trace(Py_tracefunc func, PyObject *self, PyFrameObject *f)
{
- PyObject *type, *value, *traceback, *arg;
- int err;
- PyErr_Fetch(&type, &value, &traceback);
- if (value == NULL) {
- value = Py_None;
- Py_INCREF(value);
- }
- arg = PyTuple_Pack(3, type, value, traceback);
- if (arg == NULL) {
- PyErr_Restore(type, value, traceback);
- return;
- }
- err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
- Py_DECREF(arg);
- if (err == 0)
- PyErr_Restore(type, value, traceback);
- else {
- Py_XDECREF(type);
- Py_XDECREF(value);
- Py_XDECREF(traceback);
- }
+ PyObject *type, *value, *traceback, *arg;
+ int err;
+ PyErr_Fetch(&type, &value, &traceback);
+ if (value == NULL) {
+ value = Py_None;
+ Py_INCREF(value);
+ }
+ arg = PyTuple_Pack(3, type, value, traceback);
+ if (arg == NULL) {
+ PyErr_Restore(type, value, traceback);
+ return;
+ }
+ err = call_trace(func, self, f, PyTrace_EXCEPTION, arg);
+ Py_DECREF(arg);
+ if (err == 0)
+ PyErr_Restore(type, value, traceback);
+ else {
+ Py_XDECREF(type);
+ Py_XDECREF(value);
+ Py_XDECREF(traceback);
+ }
}
static int
call_trace_protected(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
- int what, PyObject *arg)
+ int what, PyObject *arg)
{
- PyObject *type, *value, *traceback;
- int err;
- PyErr_Fetch(&type, &value, &traceback);
- err = call_trace(func, obj, frame, what, arg);
- if (err == 0)
- {
- PyErr_Restore(type, value, traceback);
- return 0;
- }
- else {
- Py_XDECREF(type);
- Py_XDECREF(value);
- Py_XDECREF(traceback);
- return -1;
- }
+ PyObject *type, *value, *traceback;
+ int err;
+ PyErr_Fetch(&type, &value, &traceback);
+ err = call_trace(func, obj, frame, what, arg);
+ if (err == 0)
+ {
+ PyErr_Restore(type, value, traceback);
+ return 0;
+ }
+ else {
+ Py_XDECREF(type);
+ Py_XDECREF(value);
+ Py_XDECREF(traceback);
+ return -1;
+ }
}
static int
call_trace(Py_tracefunc func, PyObject *obj, PyFrameObject *frame,
- int what, PyObject *arg)
+ int what, PyObject *arg)
{
- register PyThreadState *tstate = frame->f_tstate;
- int result;
- if (tstate->tracing)
- return 0;
- tstate->tracing++;
- tstate->use_tracing = 0;
- result = func(obj, frame, what, arg);
- tstate->use_tracing = ((tstate->c_tracefunc != NULL)
- || (tstate->c_profilefunc != NULL));
- tstate->tracing--;
- return result;
+ register PyThreadState *tstate = frame->f_tstate;
+ int result;
+ if (tstate->tracing)
+ return 0;
+ tstate->tracing++;
+ tstate->use_tracing = 0;
+ result = func(obj, frame, what, arg);
+ tstate->use_tracing = ((tstate->c_tracefunc != NULL)
+ || (tstate->c_profilefunc != NULL));
+ tstate->tracing--;
+ return result;
}
PyObject *
_PyEval_CallTracing(PyObject *func, PyObject *args)
{
- PyFrameObject *frame = PyEval_GetFrame();
- PyThreadState *tstate = frame->f_tstate;
- int save_tracing = tstate->tracing;
- int save_use_tracing = tstate->use_tracing;
- PyObject *result;
-
- tstate->tracing = 0;
- tstate->use_tracing = ((tstate->c_tracefunc != NULL)
- || (tstate->c_profilefunc != NULL));
- result = PyObject_Call(func, args, NULL);
- tstate->tracing = save_tracing;
- tstate->use_tracing = save_use_tracing;
- return result;
+ PyFrameObject *frame = PyEval_GetFrame();
+ PyThreadState *tstate = frame->f_tstate;
+ int save_tracing = tstate->tracing;
+ int save_use_tracing = tstate->use_tracing;
+ PyObject *result;
+
+ tstate->tracing = 0;
+ tstate->use_tracing = ((tstate->c_tracefunc != NULL)
+ || (tstate->c_profilefunc != NULL));
+ result = PyObject_Call(func, args, NULL);
+ tstate->tracing = save_tracing;
+ tstate->use_tracing = save_use_tracing;
+ return result;
}
/* See Objects/lnotab_notes.txt for a description of how tracing works. */
static int
maybe_call_line_trace(Py_tracefunc func, PyObject *obj,
- PyFrameObject *frame, int *instr_lb, int *instr_ub,
- int *instr_prev)
+ PyFrameObject *frame, int *instr_lb, int *instr_ub,
+ int *instr_prev)
{
- int result = 0;
- int line = frame->f_lineno;
-
- /* If the last instruction executed isn't in the current
- instruction window, reset the window.
- */
- if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
- PyAddrPair bounds;
- line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
- &bounds);
- *instr_lb = bounds.ap_lower;
- *instr_ub = bounds.ap_upper;
- }
- /* If the last instruction falls at the start of a line or if
- it represents a jump backwards, update the frame's line
- number and call the trace function. */
- if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
- frame->f_lineno = line;
- result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
- }
- *instr_prev = frame->f_lasti;
- return result;
+ int result = 0;
+ int line = frame->f_lineno;
+
+ /* If the last instruction executed isn't in the current
+ instruction window, reset the window.
+ */
+ if (frame->f_lasti < *instr_lb || frame->f_lasti >= *instr_ub) {
+ PyAddrPair bounds;
+ line = _PyCode_CheckLineNumber(frame->f_code, frame->f_lasti,
+ &bounds);
+ *instr_lb = bounds.ap_lower;
+ *instr_ub = bounds.ap_upper;
+ }
+ /* If the last instruction falls at the start of a line or if
+ it represents a jump backwards, update the frame's line
+ number and call the trace function. */
+ if (frame->f_lasti == *instr_lb || frame->f_lasti < *instr_prev) {
+ frame->f_lineno = line;
+ result = call_trace(func, obj, frame, PyTrace_LINE, Py_None);
+ }
+ *instr_prev = frame->f_lasti;
+ return result;
}
void
PyEval_SetProfile(Py_tracefunc func, PyObject *arg)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *temp = tstate->c_profileobj;
- Py_XINCREF(arg);
- tstate->c_profilefunc = NULL;
- tstate->c_profileobj = NULL;
- /* Must make sure that tracing is not ignored if 'temp' is freed */
- tstate->use_tracing = tstate->c_tracefunc != NULL;
- Py_XDECREF(temp);
- tstate->c_profilefunc = func;
- tstate->c_profileobj = arg;
- /* Flag that tracing or profiling is turned on */
- tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *temp = tstate->c_profileobj;
+ Py_XINCREF(arg);
+ tstate->c_profilefunc = NULL;
+ tstate->c_profileobj = NULL;
+ /* Must make sure that tracing is not ignored if 'temp' is freed */
+ tstate->use_tracing = tstate->c_tracefunc != NULL;
+ Py_XDECREF(temp);
+ tstate->c_profilefunc = func;
+ tstate->c_profileobj = arg;
+ /* Flag that tracing or profiling is turned on */
+ tstate->use_tracing = (func != NULL) || (tstate->c_tracefunc != NULL);
}
void
PyEval_SetTrace(Py_tracefunc func, PyObject *arg)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *temp = tstate->c_traceobj;
- _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
- Py_XINCREF(arg);
- tstate->c_tracefunc = NULL;
- tstate->c_traceobj = NULL;
- /* Must make sure that profiling is not ignored if 'temp' is freed */
- tstate->use_tracing = tstate->c_profilefunc != NULL;
- Py_XDECREF(temp);
- tstate->c_tracefunc = func;
- tstate->c_traceobj = arg;
- /* Flag that tracing or profiling is turned on */
- tstate->use_tracing = ((func != NULL)
- || (tstate->c_profilefunc != NULL));
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *temp = tstate->c_traceobj;
+ _Py_TracingPossible += (func != NULL) - (tstate->c_tracefunc != NULL);
+ Py_XINCREF(arg);
+ tstate->c_tracefunc = NULL;
+ tstate->c_traceobj = NULL;
+ /* Must make sure that profiling is not ignored if 'temp' is freed */
+ tstate->use_tracing = tstate->c_profilefunc != NULL;
+ Py_XDECREF(temp);
+ tstate->c_tracefunc = func;
+ tstate->c_traceobj = arg;
+ /* Flag that tracing or profiling is turned on */
+ tstate->use_tracing = ((func != NULL)
+ || (tstate->c_profilefunc != NULL));
}
PyObject *
PyEval_GetBuiltins(void)
{
- PyFrameObject *current_frame = PyEval_GetFrame();
- if (current_frame == NULL)
- return PyThreadState_GET()->interp->builtins;
- else
- return current_frame->f_builtins;
+ PyFrameObject *current_frame = PyEval_GetFrame();
+ if (current_frame == NULL)
+ return PyThreadState_GET()->interp->builtins;
+ else
+ return current_frame->f_builtins;
}
PyObject *
PyEval_GetLocals(void)
{
- PyFrameObject *current_frame = PyEval_GetFrame();
- if (current_frame == NULL)
- return NULL;
- PyFrame_FastToLocals(current_frame);
- return current_frame->f_locals;
+ PyFrameObject *current_frame = PyEval_GetFrame();
+ if (current_frame == NULL)
+ return NULL;
+ PyFrame_FastToLocals(current_frame);
+ return current_frame->f_locals;
}
PyObject *
PyEval_GetGlobals(void)
{
- PyFrameObject *current_frame = PyEval_GetFrame();
- if (current_frame == NULL)
- return NULL;
- else
- return current_frame->f_globals;
+ PyFrameObject *current_frame = PyEval_GetFrame();
+ if (current_frame == NULL)
+ return NULL;
+ else
+ return current_frame->f_globals;
}
PyFrameObject *
PyEval_GetFrame(void)
{
- PyThreadState *tstate = PyThreadState_GET();
- return _PyThreadState_GetFrame(tstate);
+ PyThreadState *tstate = PyThreadState_GET();
+ return _PyThreadState_GetFrame(tstate);
}
int
PyEval_GetRestricted(void)
{
- PyFrameObject *current_frame = PyEval_GetFrame();
- return current_frame == NULL ? 0 : PyFrame_IsRestricted(current_frame);
+ PyFrameObject *current_frame = PyEval_GetFrame();
+ return current_frame == NULL ? 0 : PyFrame_IsRestricted(current_frame);
}
int
PyEval_MergeCompilerFlags(PyCompilerFlags *cf)
{
- PyFrameObject *current_frame = PyEval_GetFrame();
- int result = cf->cf_flags != 0;
-
- if (current_frame != NULL) {
- const int codeflags = current_frame->f_code->co_flags;
- const int compilerflags = codeflags & PyCF_MASK;
- if (compilerflags) {
- result = 1;
- cf->cf_flags |= compilerflags;
- }
+ PyFrameObject *current_frame = PyEval_GetFrame();
+ int result = cf->cf_flags != 0;
+
+ if (current_frame != NULL) {
+ const int codeflags = current_frame->f_code->co_flags;
+ const int compilerflags = codeflags & PyCF_MASK;
+ if (compilerflags) {
+ result = 1;
+ cf->cf_flags |= compilerflags;
+ }
#if 0 /* future keyword */
- if (codeflags & CO_GENERATOR_ALLOWED) {
- result = 1;
- cf->cf_flags |= CO_GENERATOR_ALLOWED;
- }
+ if (codeflags & CO_GENERATOR_ALLOWED) {
+ result = 1;
+ cf->cf_flags |= CO_GENERATOR_ALLOWED;
+ }
#endif
- }
- return result;
+ }
+ return result;
}
int
Py_FlushLine(void)
{
- PyObject *f = PySys_GetObject("stdout");
- if (f == NULL)
- return 0;
- if (!PyFile_SoftSpace(f, 0))
- return 0;
- return PyFile_WriteString("\n", f);
+ PyObject *f = PySys_GetObject("stdout");
+ if (f == NULL)
+ return 0;
+ if (!PyFile_SoftSpace(f, 0))
+ return 0;
+ return PyFile_WriteString("\n", f);
}
@@ -3856,197 +3856,197 @@ Py_FlushLine(void)
PyObject *
PyEval_CallObjectWithKeywords(PyObject *func, PyObject *arg, PyObject *kw)
{
- PyObject *result;
-
- if (arg == NULL) {
- arg = PyTuple_New(0);
- if (arg == NULL)
- return NULL;
- }
- else if (!PyTuple_Check(arg)) {
- PyErr_SetString(PyExc_TypeError,
- "argument list must be a tuple");
- return NULL;
- }
- else
- Py_INCREF(arg);
-
- if (kw != NULL && !PyDict_Check(kw)) {
- PyErr_SetString(PyExc_TypeError,
- "keyword list must be a dictionary");
- Py_DECREF(arg);
- return NULL;
- }
-
- result = PyObject_Call(func, arg, kw);
- Py_DECREF(arg);
- return result;
+ PyObject *result;
+
+ if (arg == NULL) {
+ arg = PyTuple_New(0);
+ if (arg == NULL)
+ return NULL;
+ }
+ else if (!PyTuple_Check(arg)) {
+ PyErr_SetString(PyExc_TypeError,
+ "argument list must be a tuple");
+ return NULL;
+ }
+ else
+ Py_INCREF(arg);
+
+ if (kw != NULL && !PyDict_Check(kw)) {
+ PyErr_SetString(PyExc_TypeError,
+ "keyword list must be a dictionary");
+ Py_DECREF(arg);
+ return NULL;
+ }
+
+ result = PyObject_Call(func, arg, kw);
+ Py_DECREF(arg);
+ return result;
}
const char *
PyEval_GetFuncName(PyObject *func)
{
- if (PyMethod_Check(func))
- return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
- else if (PyFunction_Check(func))
- return PyString_AsString(((PyFunctionObject*)func)->func_name);
- else if (PyCFunction_Check(func))
- return ((PyCFunctionObject*)func)->m_ml->ml_name;
- else if (PyClass_Check(func))
- return PyString_AsString(((PyClassObject*)func)->cl_name);
- else if (PyInstance_Check(func)) {
- return PyString_AsString(
- ((PyInstanceObject*)func)->in_class->cl_name);
- } else {
- return func->ob_type->tp_name;
- }
+ if (PyMethod_Check(func))
+ return PyEval_GetFuncName(PyMethod_GET_FUNCTION(func));
+ else if (PyFunction_Check(func))
+ return PyString_AsString(((PyFunctionObject*)func)->func_name);
+ else if (PyCFunction_Check(func))
+ return ((PyCFunctionObject*)func)->m_ml->ml_name;
+ else if (PyClass_Check(func))
+ return PyString_AsString(((PyClassObject*)func)->cl_name);
+ else if (PyInstance_Check(func)) {
+ return PyString_AsString(
+ ((PyInstanceObject*)func)->in_class->cl_name);
+ } else {
+ return func->ob_type->tp_name;
+ }
}
const char *
PyEval_GetFuncDesc(PyObject *func)
{
- if (PyMethod_Check(func))
- return "()";
- else if (PyFunction_Check(func))
- return "()";
- else if (PyCFunction_Check(func))
- return "()";
- else if (PyClass_Check(func))
- return " constructor";
- else if (PyInstance_Check(func)) {
- return " instance";
- } else {
- return " object";
- }
+ if (PyMethod_Check(func))
+ return "()";
+ else if (PyFunction_Check(func))
+ return "()";
+ else if (PyCFunction_Check(func))
+ return "()";
+ else if (PyClass_Check(func))
+ return " constructor";
+ else if (PyInstance_Check(func)) {
+ return " instance";
+ } else {
+ return " object";
+ }
}
static void
err_args(PyObject *func, int flags, int nargs)
{
- if (flags & METH_NOARGS)
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes no arguments (%d given)",
- ((PyCFunctionObject *)func)->m_ml->ml_name,
- nargs);
- else
- PyErr_Format(PyExc_TypeError,
- "%.200s() takes exactly one argument (%d given)",
- ((PyCFunctionObject *)func)->m_ml->ml_name,
- nargs);
+ if (flags & METH_NOARGS)
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes no arguments (%d given)",
+ ((PyCFunctionObject *)func)->m_ml->ml_name,
+ nargs);
+ else
+ PyErr_Format(PyExc_TypeError,
+ "%.200s() takes exactly one argument (%d given)",
+ ((PyCFunctionObject *)func)->m_ml->ml_name,
+ nargs);
}
#define C_TRACE(x, call) \
if (tstate->use_tracing && tstate->c_profilefunc) { \
- if (call_trace(tstate->c_profilefunc, \
- tstate->c_profileobj, \
- tstate->frame, PyTrace_C_CALL, \
- func)) { \
- x = NULL; \
- } \
- else { \
- x = call; \
- if (tstate->c_profilefunc != NULL) { \
- if (x == NULL) { \
- call_trace_protected(tstate->c_profilefunc, \
- tstate->c_profileobj, \
- tstate->frame, PyTrace_C_EXCEPTION, \
- func); \
- /* XXX should pass (type, value, tb) */ \
- } else { \
- if (call_trace(tstate->c_profilefunc, \
- tstate->c_profileobj, \
- tstate->frame, PyTrace_C_RETURN, \
- func)) { \
- Py_DECREF(x); \
- x = NULL; \
- } \
- } \
- } \
- } \
+ if (call_trace(tstate->c_profilefunc, \
+ tstate->c_profileobj, \
+ tstate->frame, PyTrace_C_CALL, \
+ func)) { \
+ x = NULL; \
+ } \
+ else { \
+ x = call; \
+ if (tstate->c_profilefunc != NULL) { \
+ if (x == NULL) { \
+ call_trace_protected(tstate->c_profilefunc, \
+ tstate->c_profileobj, \
+ tstate->frame, PyTrace_C_EXCEPTION, \
+ func); \
+ /* XXX should pass (type, value, tb) */ \
+ } else { \
+ if (call_trace(tstate->c_profilefunc, \
+ tstate->c_profileobj, \
+ tstate->frame, PyTrace_C_RETURN, \
+ func)) { \
+ Py_DECREF(x); \
+ x = NULL; \
+ } \
+ } \
+ } \
+ } \
} else { \
- x = call; \
- }
+ x = call; \
+ }
static PyObject *
call_function(PyObject ***pp_stack, int oparg
#ifdef WITH_TSC
- , uint64* pintr0, uint64* pintr1
+ , uint64* pintr0, uint64* pintr1
#endif
- )
+ )
{
- int na = oparg & 0xff;
- int nk = (oparg>>8) & 0xff;
- int n = na + 2 * nk;
- PyObject **pfunc = (*pp_stack) - n - 1;
- PyObject *func = *pfunc;
- PyObject *x, *w;
-
- /* Always dispatch PyCFunction first, because these are
- presumed to be the most frequent callable object.
- */
- if (PyCFunction_Check(func) && nk == 0) {
- int flags = PyCFunction_GET_FLAGS(func);
- PyThreadState *tstate = PyThreadState_GET();
-
- PCALL(PCALL_CFUNCTION);
- if (flags & (METH_NOARGS | METH_O)) {
- PyCFunction meth = PyCFunction_GET_FUNCTION(func);
- PyObject *self = PyCFunction_GET_SELF(func);
- if (flags & METH_NOARGS && na == 0) {
- C_TRACE(x, (*meth)(self,NULL));
- }
- else if (flags & METH_O && na == 1) {
- PyObject *arg = EXT_POP(*pp_stack);
- C_TRACE(x, (*meth)(self,arg));
- Py_DECREF(arg);
- }
- else {
- err_args(func, flags, na);
- x = NULL;
- }
- }
- else {
- PyObject *callargs;
- callargs = load_args(pp_stack, na);
- READ_TIMESTAMP(*pintr0);
- C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
- READ_TIMESTAMP(*pintr1);
- Py_XDECREF(callargs);
- }
- } else {
- if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
- /* optimize access to bound methods */
- PyObject *self = PyMethod_GET_SELF(func);
- PCALL(PCALL_METHOD);
- PCALL(PCALL_BOUND_METHOD);
- Py_INCREF(self);
- func = PyMethod_GET_FUNCTION(func);
- Py_INCREF(func);
- Py_DECREF(*pfunc);
- *pfunc = self;
- na++;
- n++;
- } else
- Py_INCREF(func);
- READ_TIMESTAMP(*pintr0);
- if (PyFunction_Check(func))
- x = fast_function(func, pp_stack, n, na, nk);
- else
- x = do_call(func, pp_stack, na, nk);
- READ_TIMESTAMP(*pintr1);
- Py_DECREF(func);
- }
-
- /* Clear the stack of the function object. Also removes
- the arguments in case they weren't consumed already
- (fast_function() and err_args() leave them on the stack).
- */
- while ((*pp_stack) > pfunc) {
- w = EXT_POP(*pp_stack);
- Py_DECREF(w);
- PCALL(PCALL_POP);
- }
- return x;
+ int na = oparg & 0xff;
+ int nk = (oparg>>8) & 0xff;
+ int n = na + 2 * nk;
+ PyObject **pfunc = (*pp_stack) - n - 1;
+ PyObject *func = *pfunc;
+ PyObject *x, *w;
+
+ /* Always dispatch PyCFunction first, because these are
+ presumed to be the most frequent callable object.
+ */
+ if (PyCFunction_Check(func) && nk == 0) {
+ int flags = PyCFunction_GET_FLAGS(func);
+ PyThreadState *tstate = PyThreadState_GET();
+
+ PCALL(PCALL_CFUNCTION);
+ if (flags & (METH_NOARGS | METH_O)) {
+ PyCFunction meth = PyCFunction_GET_FUNCTION(func);
+ PyObject *self = PyCFunction_GET_SELF(func);
+ if (flags & METH_NOARGS && na == 0) {
+ C_TRACE(x, (*meth)(self,NULL));
+ }
+ else if (flags & METH_O && na == 1) {
+ PyObject *arg = EXT_POP(*pp_stack);
+ C_TRACE(x, (*meth)(self,arg));
+ Py_DECREF(arg);
+ }
+ else {
+ err_args(func, flags, na);
+ x = NULL;
+ }
+ }
+ else {
+ PyObject *callargs;
+ callargs = load_args(pp_stack, na);
+ READ_TIMESTAMP(*pintr0);
+ C_TRACE(x, PyCFunction_Call(func,callargs,NULL));
+ READ_TIMESTAMP(*pintr1);
+ Py_XDECREF(callargs);
+ }
+ } else {
+ if (PyMethod_Check(func) && PyMethod_GET_SELF(func) != NULL) {
+ /* optimize access to bound methods */
+ PyObject *self = PyMethod_GET_SELF(func);
+ PCALL(PCALL_METHOD);
+ PCALL(PCALL_BOUND_METHOD);
+ Py_INCREF(self);
+ func = PyMethod_GET_FUNCTION(func);
+ Py_INCREF(func);
+ Py_DECREF(*pfunc);
+ *pfunc = self;
+ na++;
+ n++;
+ } else
+ Py_INCREF(func);
+ READ_TIMESTAMP(*pintr0);
+ if (PyFunction_Check(func))
+ x = fast_function(func, pp_stack, n, na, nk);
+ else
+ x = do_call(func, pp_stack, na, nk);
+ READ_TIMESTAMP(*pintr1);
+ Py_DECREF(func);
+ }
+
+ /* Clear the stack of the function object. Also removes
+ the arguments in case they weren't consumed already
+ (fast_function() and err_args() leave them on the stack).
+ */
+ while ((*pp_stack) > pfunc) {
+ w = EXT_POP(*pp_stack);
+ Py_DECREF(w);
+ PCALL(PCALL_POP);
+ }
+ return x;
}
/* The fast_function() function optimize calls for which no argument
@@ -4061,273 +4061,273 @@ call_function(PyObject ***pp_stack, int oparg
static PyObject *
fast_function(PyObject *func, PyObject ***pp_stack, int n, int na, int nk)
{
- PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
- PyObject *globals = PyFunction_GET_GLOBALS(func);
- PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
- PyObject **d = NULL;
- int nd = 0;
-
- PCALL(PCALL_FUNCTION);
- PCALL(PCALL_FAST_FUNCTION);
- if (argdefs == NULL && co->co_argcount == n && nk==0 &&
- co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
- PyFrameObject *f;
- PyObject *retval = NULL;
- PyThreadState *tstate = PyThreadState_GET();
- PyObject **fastlocals, **stack;
- int i;
-
- PCALL(PCALL_FASTER_FUNCTION);
- assert(globals != NULL);
- /* XXX Perhaps we should create a specialized
- PyFrame_New() that doesn't take locals, but does
- take builtins without sanity checking them.
- */
- assert(tstate != NULL);
- f = PyFrame_New(tstate, co, globals, NULL);
- if (f == NULL)
- return NULL;
-
- fastlocals = f->f_localsplus;
- stack = (*pp_stack) - n;
-
- for (i = 0; i < n; i++) {
- Py_INCREF(*stack);
- fastlocals[i] = *stack++;
- }
- retval = PyEval_EvalFrameEx(f,0);
- ++tstate->recursion_depth;
- Py_DECREF(f);
- --tstate->recursion_depth;
- return retval;
- }
- if (argdefs != NULL) {
- d = &PyTuple_GET_ITEM(argdefs, 0);
- nd = Py_SIZE(argdefs);
- }
- return PyEval_EvalCodeEx(co, globals,
- (PyObject *)NULL, (*pp_stack)-n, na,
- (*pp_stack)-2*nk, nk, d, nd,
- PyFunction_GET_CLOSURE(func));
+ PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func);
+ PyObject *globals = PyFunction_GET_GLOBALS(func);
+ PyObject *argdefs = PyFunction_GET_DEFAULTS(func);
+ PyObject **d = NULL;
+ int nd = 0;
+
+ PCALL(PCALL_FUNCTION);
+ PCALL(PCALL_FAST_FUNCTION);
+ if (argdefs == NULL && co->co_argcount == n && nk==0 &&
+ co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) {
+ PyFrameObject *f;
+ PyObject *retval = NULL;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject **fastlocals, **stack;
+ int i;
+
+ PCALL(PCALL_FASTER_FUNCTION);
+ assert(globals != NULL);
+ /* XXX Perhaps we should create a specialized
+ PyFrame_New() that doesn't take locals, but does
+ take builtins without sanity checking them.
+ */
+ assert(tstate != NULL);
+ f = PyFrame_New(tstate, co, globals, NULL);
+ if (f == NULL)
+ return NULL;
+
+ fastlocals = f->f_localsplus;
+ stack = (*pp_stack) - n;
+
+ for (i = 0; i < n; i++) {
+ Py_INCREF(*stack);
+ fastlocals[i] = *stack++;
+ }
+ retval = PyEval_EvalFrameEx(f,0);
+ ++tstate->recursion_depth;
+ Py_DECREF(f);
+ --tstate->recursion_depth;
+ return retval;
+ }
+ if (argdefs != NULL) {
+ d = &PyTuple_GET_ITEM(argdefs, 0);
+ nd = Py_SIZE(argdefs);
+ }
+ return PyEval_EvalCodeEx(co, globals,
+ (PyObject *)NULL, (*pp_stack)-n, na,
+ (*pp_stack)-2*nk, nk, d, nd,
+ PyFunction_GET_CLOSURE(func));
}
static PyObject *
update_keyword_args(PyObject *orig_kwdict, int nk, PyObject ***pp_stack,
PyObject *func)
{
- PyObject *kwdict = NULL;
- if (orig_kwdict == NULL)
- kwdict = PyDict_New();
- else {
- kwdict = PyDict_Copy(orig_kwdict);
- Py_DECREF(orig_kwdict);
- }
- if (kwdict == NULL)
- return NULL;
- while (--nk >= 0) {
- int err;
- PyObject *value = EXT_POP(*pp_stack);
- PyObject *key = EXT_POP(*pp_stack);
- if (PyDict_GetItem(kwdict, key) != NULL) {
- PyErr_Format(PyExc_TypeError,
- "%.200s%s got multiple values "
- "for keyword argument '%.200s'",
- PyEval_GetFuncName(func),
- PyEval_GetFuncDesc(func),
- PyString_AsString(key));
- Py_DECREF(key);
- Py_DECREF(value);
- Py_DECREF(kwdict);
- return NULL;
- }
- err = PyDict_SetItem(kwdict, key, value);
- Py_DECREF(key);
- Py_DECREF(value);
- if (err) {
- Py_DECREF(kwdict);
- return NULL;
- }
- }
- return kwdict;
+ PyObject *kwdict = NULL;
+ if (orig_kwdict == NULL)
+ kwdict = PyDict_New();
+ else {
+ kwdict = PyDict_Copy(orig_kwdict);
+ Py_DECREF(orig_kwdict);
+ }
+ if (kwdict == NULL)
+ return NULL;
+ while (--nk >= 0) {
+ int err;
+ PyObject *value = EXT_POP(*pp_stack);
+ PyObject *key = EXT_POP(*pp_stack);
+ if (PyDict_GetItem(kwdict, key) != NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s%s got multiple values "
+ "for keyword argument '%.200s'",
+ PyEval_GetFuncName(func),
+ PyEval_GetFuncDesc(func),
+ PyString_AsString(key));
+ Py_DECREF(key);
+ Py_DECREF(value);
+ Py_DECREF(kwdict);
+ return NULL;
+ }
+ err = PyDict_SetItem(kwdict, key, value);
+ Py_DECREF(key);
+ Py_DECREF(value);
+ if (err) {
+ Py_DECREF(kwdict);
+ return NULL;
+ }
+ }
+ return kwdict;
}
static PyObject *
update_star_args(int nstack, int nstar, PyObject *stararg,
- PyObject ***pp_stack)
+ PyObject ***pp_stack)
{
- PyObject *callargs, *w;
-
- callargs = PyTuple_New(nstack + nstar);
- if (callargs == NULL) {
- return NULL;
- }
- if (nstar) {
- int i;
- for (i = 0; i < nstar; i++) {
- PyObject *a = PyTuple_GET_ITEM(stararg, i);
- Py_INCREF(a);
- PyTuple_SET_ITEM(callargs, nstack + i, a);
- }
- }
- while (--nstack >= 0) {
- w = EXT_POP(*pp_stack);
- PyTuple_SET_ITEM(callargs, nstack, w);
- }
- return callargs;
+ PyObject *callargs, *w;
+
+ callargs = PyTuple_New(nstack + nstar);
+ if (callargs == NULL) {
+ return NULL;
+ }
+ if (nstar) {
+ int i;
+ for (i = 0; i < nstar; i++) {
+ PyObject *a = PyTuple_GET_ITEM(stararg, i);
+ Py_INCREF(a);
+ PyTuple_SET_ITEM(callargs, nstack + i, a);
+ }
+ }
+ while (--nstack >= 0) {
+ w = EXT_POP(*pp_stack);
+ PyTuple_SET_ITEM(callargs, nstack, w);
+ }
+ return callargs;
}
static PyObject *
load_args(PyObject ***pp_stack, int na)
{
- PyObject *args = PyTuple_New(na);
- PyObject *w;
-
- if (args == NULL)
- return NULL;
- while (--na >= 0) {
- w = EXT_POP(*pp_stack);
- PyTuple_SET_ITEM(args, na, w);
- }
- return args;
+ PyObject *args = PyTuple_New(na);
+ PyObject *w;
+
+ if (args == NULL)
+ return NULL;
+ while (--na >= 0) {
+ w = EXT_POP(*pp_stack);
+ PyTuple_SET_ITEM(args, na, w);
+ }
+ return args;
}
static PyObject *
do_call(PyObject *func, PyObject ***pp_stack, int na, int nk)
{
- PyObject *callargs = NULL;
- PyObject *kwdict = NULL;
- PyObject *result = NULL;
-
- if (nk > 0) {
- kwdict = update_keyword_args(NULL, nk, pp_stack, func);
- if (kwdict == NULL)
- goto call_fail;
- }
- callargs = load_args(pp_stack, na);
- if (callargs == NULL)
- goto call_fail;
+ PyObject *callargs = NULL;
+ PyObject *kwdict = NULL;
+ PyObject *result = NULL;
+
+ if (nk > 0) {
+ kwdict = update_keyword_args(NULL, nk, pp_stack, func);
+ if (kwdict == NULL)
+ goto call_fail;
+ }
+ callargs = load_args(pp_stack, na);
+ if (callargs == NULL)
+ goto call_fail;
#ifdef CALL_PROFILE
- /* At this point, we have to look at the type of func to
- update the call stats properly. Do it here so as to avoid
- exposing the call stats machinery outside ceval.c
- */
- if (PyFunction_Check(func))
- PCALL(PCALL_FUNCTION);
- else if (PyMethod_Check(func))
- PCALL(PCALL_METHOD);
- else if (PyType_Check(func))
- PCALL(PCALL_TYPE);
- else if (PyCFunction_Check(func))
- PCALL(PCALL_CFUNCTION);
- else
- PCALL(PCALL_OTHER);
+ /* At this point, we have to look at the type of func to
+ update the call stats properly. Do it here so as to avoid
+ exposing the call stats machinery outside ceval.c
+ */
+ if (PyFunction_Check(func))
+ PCALL(PCALL_FUNCTION);
+ else if (PyMethod_Check(func))
+ PCALL(PCALL_METHOD);
+ else if (PyType_Check(func))
+ PCALL(PCALL_TYPE);
+ else if (PyCFunction_Check(func))
+ PCALL(PCALL_CFUNCTION);
+ else
+ PCALL(PCALL_OTHER);
#endif
- if (PyCFunction_Check(func)) {
- PyThreadState *tstate = PyThreadState_GET();
- C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
- }
- else
- result = PyObject_Call(func, callargs, kwdict);
+ if (PyCFunction_Check(func)) {
+ PyThreadState *tstate = PyThreadState_GET();
+ C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
+ }
+ else
+ result = PyObject_Call(func, callargs, kwdict);
call_fail:
- Py_XDECREF(callargs);
- Py_XDECREF(kwdict);
- return result;
+ Py_XDECREF(callargs);
+ Py_XDECREF(kwdict);
+ return result;
}
static PyObject *
ext_do_call(PyObject *func, PyObject ***pp_stack, int flags, int na, int nk)
{
- int nstar = 0;
- PyObject *callargs = NULL;
- PyObject *stararg = NULL;
- PyObject *kwdict = NULL;
- PyObject *result = NULL;
-
- if (flags & CALL_FLAG_KW) {
- kwdict = EXT_POP(*pp_stack);
- if (!PyDict_Check(kwdict)) {
- PyObject *d;
- d = PyDict_New();
- if (d == NULL)
- goto ext_call_fail;
- if (PyDict_Update(d, kwdict) != 0) {
- Py_DECREF(d);
- /* PyDict_Update raises attribute
- * error (percolated from an attempt
- * to get 'keys' attribute) instead of
- * a type error if its second argument
- * is not a mapping.
- */
- if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s%.200s argument after ** "
- "must be a mapping, not %.200s",
- PyEval_GetFuncName(func),
- PyEval_GetFuncDesc(func),
- kwdict->ob_type->tp_name);
- }
- goto ext_call_fail;
- }
- Py_DECREF(kwdict);
- kwdict = d;
- }
- }
- if (flags & CALL_FLAG_VAR) {
- stararg = EXT_POP(*pp_stack);
- if (!PyTuple_Check(stararg)) {
- PyObject *t = NULL;
- t = PySequence_Tuple(stararg);
- if (t == NULL) {
- if (PyErr_ExceptionMatches(PyExc_TypeError)) {
- PyErr_Format(PyExc_TypeError,
- "%.200s%.200s argument after * "
- "must be a sequence, not %200s",
- PyEval_GetFuncName(func),
- PyEval_GetFuncDesc(func),
- stararg->ob_type->tp_name);
- }
- goto ext_call_fail;
- }
- Py_DECREF(stararg);
- stararg = t;
- }
- nstar = PyTuple_GET_SIZE(stararg);
- }
- if (nk > 0) {
- kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
- if (kwdict == NULL)
- goto ext_call_fail;
- }
- callargs = update_star_args(na, nstar, stararg, pp_stack);
- if (callargs == NULL)
- goto ext_call_fail;
+ int nstar = 0;
+ PyObject *callargs = NULL;
+ PyObject *stararg = NULL;
+ PyObject *kwdict = NULL;
+ PyObject *result = NULL;
+
+ if (flags & CALL_FLAG_KW) {
+ kwdict = EXT_POP(*pp_stack);
+ if (!PyDict_Check(kwdict)) {
+ PyObject *d;
+ d = PyDict_New();
+ if (d == NULL)
+ goto ext_call_fail;
+ if (PyDict_Update(d, kwdict) != 0) {
+ Py_DECREF(d);
+ /* PyDict_Update raises attribute
+ * error (percolated from an attempt
+ * to get 'keys' attribute) instead of
+ * a type error if its second argument
+ * is not a mapping.
+ */
+ if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s%.200s argument after ** "
+ "must be a mapping, not %.200s",
+ PyEval_GetFuncName(func),
+ PyEval_GetFuncDesc(func),
+ kwdict->ob_type->tp_name);
+ }
+ goto ext_call_fail;
+ }
+ Py_DECREF(kwdict);
+ kwdict = d;
+ }
+ }
+ if (flags & CALL_FLAG_VAR) {
+ stararg = EXT_POP(*pp_stack);
+ if (!PyTuple_Check(stararg)) {
+ PyObject *t = NULL;
+ t = PySequence_Tuple(stararg);
+ if (t == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_TypeError)) {
+ PyErr_Format(PyExc_TypeError,
+ "%.200s%.200s argument after * "
+ "must be a sequence, not %200s",
+ PyEval_GetFuncName(func),
+ PyEval_GetFuncDesc(func),
+ stararg->ob_type->tp_name);
+ }
+ goto ext_call_fail;
+ }
+ Py_DECREF(stararg);
+ stararg = t;
+ }
+ nstar = PyTuple_GET_SIZE(stararg);
+ }
+ if (nk > 0) {
+ kwdict = update_keyword_args(kwdict, nk, pp_stack, func);
+ if (kwdict == NULL)
+ goto ext_call_fail;
+ }
+ callargs = update_star_args(na, nstar, stararg, pp_stack);
+ if (callargs == NULL)
+ goto ext_call_fail;
#ifdef CALL_PROFILE
- /* At this point, we have to look at the type of func to
- update the call stats properly. Do it here so as to avoid
- exposing the call stats machinery outside ceval.c
- */
- if (PyFunction_Check(func))
- PCALL(PCALL_FUNCTION);
- else if (PyMethod_Check(func))
- PCALL(PCALL_METHOD);
- else if (PyType_Check(func))
- PCALL(PCALL_TYPE);
- else if (PyCFunction_Check(func))
- PCALL(PCALL_CFUNCTION);
- else
- PCALL(PCALL_OTHER);
+ /* At this point, we have to look at the type of func to
+ update the call stats properly. Do it here so as to avoid
+ exposing the call stats machinery outside ceval.c
+ */
+ if (PyFunction_Check(func))
+ PCALL(PCALL_FUNCTION);
+ else if (PyMethod_Check(func))
+ PCALL(PCALL_METHOD);
+ else if (PyType_Check(func))
+ PCALL(PCALL_TYPE);
+ else if (PyCFunction_Check(func))
+ PCALL(PCALL_CFUNCTION);
+ else
+ PCALL(PCALL_OTHER);
#endif
- if (PyCFunction_Check(func)) {
- PyThreadState *tstate = PyThreadState_GET();
- C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
- }
- else
- result = PyObject_Call(func, callargs, kwdict);
+ if (PyCFunction_Check(func)) {
+ PyThreadState *tstate = PyThreadState_GET();
+ C_TRACE(result, PyCFunction_Call(func, callargs, kwdict));
+ }
+ else
+ result = PyObject_Call(func, callargs, kwdict);
ext_call_fail:
- Py_XDECREF(callargs);
- Py_XDECREF(kwdict);
- Py_XDECREF(stararg);
- return result;
+ Py_XDECREF(callargs);
+ Py_XDECREF(kwdict);
+ Py_XDECREF(stararg);
+ return result;
}
/* Extract a slice index from a PyInt or PyLong or an object with the
@@ -4343,93 +4343,93 @@ ext_call_fail:
int
_PyEval_SliceIndex(PyObject *v, Py_ssize_t *pi)
{
- if (v != NULL) {
- Py_ssize_t x;
- if (PyInt_Check(v)) {
- /* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
- however, it looks like it should be AsSsize_t.
- There should be a comment here explaining why.
- */
- x = PyInt_AS_LONG(v);
- }
- else if (PyIndex_Check(v)) {
- x = PyNumber_AsSsize_t(v, NULL);
- if (x == -1 && PyErr_Occurred())
- return 0;
- }
- else {
- PyErr_SetString(PyExc_TypeError,
- "slice indices must be integers or "
- "None or have an __index__ method");
- return 0;
- }
- *pi = x;
- }
- return 1;
+ if (v != NULL) {
+ Py_ssize_t x;
+ if (PyInt_Check(v)) {
+ /* XXX(nnorwitz): I think PyInt_AS_LONG is correct,
+ however, it looks like it should be AsSsize_t.
+ There should be a comment here explaining why.
+ */
+ x = PyInt_AS_LONG(v);
+ }
+ else if (PyIndex_Check(v)) {
+ x = PyNumber_AsSsize_t(v, NULL);
+ if (x == -1 && PyErr_Occurred())
+ return 0;
+ }
+ else {
+ PyErr_SetString(PyExc_TypeError,
+ "slice indices must be integers or "
+ "None or have an __index__ method");
+ return 0;
+ }
+ *pi = x;
+ }
+ return 1;
}
#undef ISINDEX
#define ISINDEX(x) ((x) == NULL || \
- PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
+ PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
static PyObject *
apply_slice(PyObject *u, PyObject *v, PyObject *w) /* return u[v:w] */
{
- PyTypeObject *tp = u->ob_type;
- PySequenceMethods *sq = tp->tp_as_sequence;
-
- if (sq && sq->sq_slice && ISINDEX(v) && ISINDEX(w)) {
- Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
- if (!_PyEval_SliceIndex(v, &ilow))
- return NULL;
- if (!_PyEval_SliceIndex(w, &ihigh))
- return NULL;
- return PySequence_GetSlice(u, ilow, ihigh);
- }
- else {
- PyObject *slice = PySlice_New(v, w, NULL);
- if (slice != NULL) {
- PyObject *res = PyObject_GetItem(u, slice);
- Py_DECREF(slice);
- return res;
- }
- else
- return NULL;
- }
+ PyTypeObject *tp = u->ob_type;
+ PySequenceMethods *sq = tp->tp_as_sequence;
+
+ if (sq && sq->sq_slice && ISINDEX(v) && ISINDEX(w)) {
+ Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
+ if (!_PyEval_SliceIndex(v, &ilow))
+ return NULL;
+ if (!_PyEval_SliceIndex(w, &ihigh))
+ return NULL;
+ return PySequence_GetSlice(u, ilow, ihigh);
+ }
+ else {
+ PyObject *slice = PySlice_New(v, w, NULL);
+ if (slice != NULL) {
+ PyObject *res = PyObject_GetItem(u, slice);
+ Py_DECREF(slice);
+ return res;
+ }
+ else
+ return NULL;
+ }
}
static int
assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x)
- /* u[v:w] = x */
+ /* u[v:w] = x */
{
- PyTypeObject *tp = u->ob_type;
- PySequenceMethods *sq = tp->tp_as_sequence;
-
- if (sq && sq->sq_ass_slice && ISINDEX(v) && ISINDEX(w)) {
- Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
- if (!_PyEval_SliceIndex(v, &ilow))
- return -1;
- if (!_PyEval_SliceIndex(w, &ihigh))
- return -1;
- if (x == NULL)
- return PySequence_DelSlice(u, ilow, ihigh);
- else
- return PySequence_SetSlice(u, ilow, ihigh, x);
- }
- else {
- PyObject *slice = PySlice_New(v, w, NULL);
- if (slice != NULL) {
- int res;
- if (x != NULL)
- res = PyObject_SetItem(u, slice, x);
- else
- res = PyObject_DelItem(u, slice);
- Py_DECREF(slice);
- return res;
- }
- else
- return -1;
- }
+ PyTypeObject *tp = u->ob_type;
+ PySequenceMethods *sq = tp->tp_as_sequence;
+
+ if (sq && sq->sq_ass_slice && ISINDEX(v) && ISINDEX(w)) {
+ Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
+ if (!_PyEval_SliceIndex(v, &ilow))
+ return -1;
+ if (!_PyEval_SliceIndex(w, &ihigh))
+ return -1;
+ if (x == NULL)
+ return PySequence_DelSlice(u, ilow, ihigh);
+ else
+ return PySequence_SetSlice(u, ilow, ihigh, x);
+ }
+ else {
+ PyObject *slice = PySlice_New(v, w, NULL);
+ if (slice != NULL) {
+ int res;
+ if (x != NULL)
+ res = PyObject_SetItem(u, slice, x);
+ else
+ res = PyObject_DelItem(u, slice);
+ Py_DECREF(slice);
+ return res;
+ }
+ else
+ return -1;
+ }
}
#define Py3kExceptionClass_Check(x) \
@@ -4437,416 +4437,416 @@ assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x)
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
#define CANNOT_CATCH_MSG "catching classes that don't inherit from " \
- "BaseException is not allowed in 3.x"
+ "BaseException is not allowed in 3.x"
static PyObject *
cmp_outcome(int op, register PyObject *v, register PyObject *w)
{
- int res = 0;
- switch (op) {
- case PyCmp_IS:
- res = (v == w);
- break;
- case PyCmp_IS_NOT:
- res = (v != w);
- break;
- case PyCmp_IN:
- res = PySequence_Contains(w, v);
- if (res < 0)
- return NULL;
- break;
- case PyCmp_NOT_IN:
- res = PySequence_Contains(w, v);
- if (res < 0)
- return NULL;
- res = !res;
- break;
- case PyCmp_EXC_MATCH:
- if (PyTuple_Check(w)) {
- Py_ssize_t i, length;
- length = PyTuple_Size(w);
- for (i = 0; i < length; i += 1) {
- PyObject *exc = PyTuple_GET_ITEM(w, i);
- if (PyString_Check(exc)) {
- int ret_val;
- ret_val = PyErr_WarnEx(
- PyExc_DeprecationWarning,
- "catching of string "
- "exceptions is deprecated", 1);
- if (ret_val < 0)
- return NULL;
- }
- else if (Py_Py3kWarningFlag &&
- !PyTuple_Check(exc) &&
- !Py3kExceptionClass_Check(exc))
- {
- int ret_val;
- ret_val = PyErr_WarnEx(
- PyExc_DeprecationWarning,
- CANNOT_CATCH_MSG, 1);
- if (ret_val < 0)
- return NULL;
- }
- }
- }
- else {
- if (PyString_Check(w)) {
- int ret_val;
- ret_val = PyErr_WarnEx(
- PyExc_DeprecationWarning,
- "catching of string "
- "exceptions is deprecated", 1);
- if (ret_val < 0)
- return NULL;
- }
- else if (Py_Py3kWarningFlag &&
- !PyTuple_Check(w) &&
- !Py3kExceptionClass_Check(w))
- {
- int ret_val;
- ret_val = PyErr_WarnEx(
- PyExc_DeprecationWarning,
- CANNOT_CATCH_MSG, 1);
- if (ret_val < 0)
- return NULL;
- }
- }
- res = PyErr_GivenExceptionMatches(v, w);
- break;
- default:
- return PyObject_RichCompare(v, w, op);
- }
- v = res ? Py_True : Py_False;
- Py_INCREF(v);
- return v;
+ int res = 0;
+ switch (op) {
+ case PyCmp_IS:
+ res = (v == w);
+ break;
+ case PyCmp_IS_NOT:
+ res = (v != w);
+ break;
+ case PyCmp_IN:
+ res = PySequence_Contains(w, v);
+ if (res < 0)
+ return NULL;
+ break;
+ case PyCmp_NOT_IN:
+ res = PySequence_Contains(w, v);
+ if (res < 0)
+ return NULL;
+ res = !res;
+ break;
+ case PyCmp_EXC_MATCH:
+ if (PyTuple_Check(w)) {
+ Py_ssize_t i, length;
+ length = PyTuple_Size(w);
+ for (i = 0; i < length; i += 1) {
+ PyObject *exc = PyTuple_GET_ITEM(w, i);
+ if (PyString_Check(exc)) {
+ int ret_val;
+ ret_val = PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ "catching of string "
+ "exceptions is deprecated", 1);
+ if (ret_val < 0)
+ return NULL;
+ }
+ else if (Py_Py3kWarningFlag &&
+ !PyTuple_Check(exc) &&
+ !Py3kExceptionClass_Check(exc))
+ {
+ int ret_val;
+ ret_val = PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ CANNOT_CATCH_MSG, 1);
+ if (ret_val < 0)
+ return NULL;
+ }
+ }
+ }
+ else {
+ if (PyString_Check(w)) {
+ int ret_val;
+ ret_val = PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ "catching of string "
+ "exceptions is deprecated", 1);
+ if (ret_val < 0)
+ return NULL;
+ }
+ else if (Py_Py3kWarningFlag &&
+ !PyTuple_Check(w) &&
+ !Py3kExceptionClass_Check(w))
+ {
+ int ret_val;
+ ret_val = PyErr_WarnEx(
+ PyExc_DeprecationWarning,
+ CANNOT_CATCH_MSG, 1);
+ if (ret_val < 0)
+ return NULL;
+ }
+ }
+ res = PyErr_GivenExceptionMatches(v, w);
+ break;
+ default:
+ return PyObject_RichCompare(v, w, op);
+ }
+ v = res ? Py_True : Py_False;
+ Py_INCREF(v);
+ return v;
}
static PyObject *
import_from(PyObject *v, PyObject *name)
{
- PyObject *x;
-
- x = PyObject_GetAttr(v, name);
- if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
- PyErr_Format(PyExc_ImportError,
- "cannot import name %.230s",
- PyString_AsString(name));
- }
- return x;
+ PyObject *x;
+
+ x = PyObject_GetAttr(v, name);
+ if (x == NULL && PyErr_ExceptionMatches(PyExc_AttributeError)) {
+ PyErr_Format(PyExc_ImportError,
+ "cannot import name %.230s",
+ PyString_AsString(name));
+ }
+ return x;
}
static int
import_all_from(PyObject *locals, PyObject *v)
{
- PyObject *all = PyObject_GetAttrString(v, "__all__");
- PyObject *dict, *name, *value;
- int skip_leading_underscores = 0;
- int pos, err;
-
- if (all == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1; /* Unexpected error */
- PyErr_Clear();
- dict = PyObject_GetAttrString(v, "__dict__");
- if (dict == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_AttributeError))
- return -1;
- PyErr_SetString(PyExc_ImportError,
- "from-import-* object has no __dict__ and no __all__");
- return -1;
- }
- all = PyMapping_Keys(dict);
- Py_DECREF(dict);
- if (all == NULL)
- return -1;
- skip_leading_underscores = 1;
- }
-
- for (pos = 0, err = 0; ; pos++) {
- name = PySequence_GetItem(all, pos);
- if (name == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_IndexError))
- err = -1;
- else
- PyErr_Clear();
- break;
- }
- if (skip_leading_underscores &&
- PyString_Check(name) &&
- PyString_AS_STRING(name)[0] == '_')
- {
- Py_DECREF(name);
- continue;
- }
- value = PyObject_GetAttr(v, name);
- if (value == NULL)
- err = -1;
- else if (PyDict_CheckExact(locals))
- err = PyDict_SetItem(locals, name, value);
- else
- err = PyObject_SetItem(locals, name, value);
- Py_DECREF(name);
- Py_XDECREF(value);
- if (err != 0)
- break;
- }
- Py_DECREF(all);
- return err;
+ PyObject *all = PyObject_GetAttrString(v, "__all__");
+ PyObject *dict, *name, *value;
+ int skip_leading_underscores = 0;
+ int pos, err;
+
+ if (all == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1; /* Unexpected error */
+ PyErr_Clear();
+ dict = PyObject_GetAttrString(v, "__dict__");
+ if (dict == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_AttributeError))
+ return -1;
+ PyErr_SetString(PyExc_ImportError,
+ "from-import-* object has no __dict__ and no __all__");
+ return -1;
+ }
+ all = PyMapping_Keys(dict);
+ Py_DECREF(dict);
+ if (all == NULL)
+ return -1;
+ skip_leading_underscores = 1;
+ }
+
+ for (pos = 0, err = 0; ; pos++) {
+ name = PySequence_GetItem(all, pos);
+ if (name == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_IndexError))
+ err = -1;
+ else
+ PyErr_Clear();
+ break;
+ }
+ if (skip_leading_underscores &&
+ PyString_Check(name) &&
+ PyString_AS_STRING(name)[0] == '_')
+ {
+ Py_DECREF(name);
+ continue;
+ }
+ value = PyObject_GetAttr(v, name);
+ if (value == NULL)
+ err = -1;
+ else if (PyDict_CheckExact(locals))
+ err = PyDict_SetItem(locals, name, value);
+ else
+ err = PyObject_SetItem(locals, name, value);
+ Py_DECREF(name);
+ Py_XDECREF(value);
+ if (err != 0)
+ break;
+ }
+ Py_DECREF(all);
+ return err;
}
static PyObject *
build_class(PyObject *methods, PyObject *bases, PyObject *name)
{
- PyObject *metaclass = NULL, *result, *base;
-
- if (PyDict_Check(methods))
- metaclass = PyDict_GetItemString(methods, "__metaclass__");
- if (metaclass != NULL)
- Py_INCREF(metaclass);
- else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
- base = PyTuple_GET_ITEM(bases, 0);
- metaclass = PyObject_GetAttrString(base, "__class__");
- if (metaclass == NULL) {
- PyErr_Clear();
- metaclass = (PyObject *)base->ob_type;
- Py_INCREF(metaclass);
- }
- }
- else {
- PyObject *g = PyEval_GetGlobals();
- if (g != NULL && PyDict_Check(g))
- metaclass = PyDict_GetItemString(g, "__metaclass__");
- if (metaclass == NULL)
- metaclass = (PyObject *) &PyClass_Type;
- Py_INCREF(metaclass);
- }
- result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods,
- NULL);
- Py_DECREF(metaclass);
- if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
- /* A type error here likely means that the user passed
- in a base that was not a class (such the random module
- instead of the random.random type). Help them out with
- by augmenting the error message with more information.*/
-
- PyObject *ptype, *pvalue, *ptraceback;
-
- PyErr_Fetch(&ptype, &pvalue, &ptraceback);
- if (PyString_Check(pvalue)) {
- PyObject *newmsg;
- newmsg = PyString_FromFormat(
- "Error when calling the metaclass bases\n"
- " %s",
- PyString_AS_STRING(pvalue));
- if (newmsg != NULL) {
- Py_DECREF(pvalue);
- pvalue = newmsg;
- }
- }
- PyErr_Restore(ptype, pvalue, ptraceback);
- }
- return result;
+ PyObject *metaclass = NULL, *result, *base;
+
+ if (PyDict_Check(methods))
+ metaclass = PyDict_GetItemString(methods, "__metaclass__");
+ if (metaclass != NULL)
+ Py_INCREF(metaclass);
+ else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
+ base = PyTuple_GET_ITEM(bases, 0);
+ metaclass = PyObject_GetAttrString(base, "__class__");
+ if (metaclass == NULL) {
+ PyErr_Clear();
+ metaclass = (PyObject *)base->ob_type;
+ Py_INCREF(metaclass);
+ }
+ }
+ else {
+ PyObject *g = PyEval_GetGlobals();
+ if (g != NULL && PyDict_Check(g))
+ metaclass = PyDict_GetItemString(g, "__metaclass__");
+ if (metaclass == NULL)
+ metaclass = (PyObject *) &PyClass_Type;
+ Py_INCREF(metaclass);
+ }
+ result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods,
+ NULL);
+ Py_DECREF(metaclass);
+ if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
+ /* A type error here likely means that the user passed
+ in a base that was not a class (such the random module
+ instead of the random.random type). Help them out with
+ by augmenting the error message with more information.*/
+
+ PyObject *ptype, *pvalue, *ptraceback;
+
+ PyErr_Fetch(&ptype, &pvalue, &ptraceback);
+ if (PyString_Check(pvalue)) {
+ PyObject *newmsg;
+ newmsg = PyString_FromFormat(
+ "Error when calling the metaclass bases\n"
+ " %s",
+ PyString_AS_STRING(pvalue));
+ if (newmsg != NULL) {
+ Py_DECREF(pvalue);
+ pvalue = newmsg;
+ }
+ }
+ PyErr_Restore(ptype, pvalue, ptraceback);
+ }
+ return result;
}
static int
exec_statement(PyFrameObject *f, PyObject *prog, PyObject *globals,
- PyObject *locals)
+ PyObject *locals)
{
- int n;
- PyObject *v;
- int plain = 0;
-
- if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
- ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
- /* Backward compatibility hack */
- globals = PyTuple_GetItem(prog, 1);
- if (n == 3)
- locals = PyTuple_GetItem(prog, 2);
- prog = PyTuple_GetItem(prog, 0);
- }
- if (globals == Py_None) {
- globals = PyEval_GetGlobals();
- if (locals == Py_None) {
- locals = PyEval_GetLocals();
- plain = 1;
- }
- if (!globals || !locals) {
- PyErr_SetString(PyExc_SystemError,
- "globals and locals cannot be NULL");
- return -1;
- }
- }
- else if (locals == Py_None)
- locals = globals;
- if (!PyString_Check(prog) &&
+ int n;
+ PyObject *v;
+ int plain = 0;
+
+ if (PyTuple_Check(prog) && globals == Py_None && locals == Py_None &&
+ ((n = PyTuple_Size(prog)) == 2 || n == 3)) {
+ /* Backward compatibility hack */
+ globals = PyTuple_GetItem(prog, 1);
+ if (n == 3)
+ locals = PyTuple_GetItem(prog, 2);
+ prog = PyTuple_GetItem(prog, 0);
+ }
+ if (globals == Py_None) {
+ globals = PyEval_GetGlobals();
+ if (locals == Py_None) {
+ locals = PyEval_GetLocals();
+ plain = 1;
+ }
+ if (!globals || !locals) {
+ PyErr_SetString(PyExc_SystemError,
+ "globals and locals cannot be NULL");
+ return -1;
+ }
+ }
+ else if (locals == Py_None)
+ locals = globals;
+ if (!PyString_Check(prog) &&
#ifdef Py_USING_UNICODE
- !PyUnicode_Check(prog) &&
+ !PyUnicode_Check(prog) &&
#endif
- !PyCode_Check(prog) &&
- !PyFile_Check(prog)) {
- PyErr_SetString(PyExc_TypeError,
- "exec: arg 1 must be a string, file, or code object");
- return -1;
- }
- if (!PyDict_Check(globals)) {
- PyErr_SetString(PyExc_TypeError,
- "exec: arg 2 must be a dictionary or None");
- return -1;
- }
- if (!PyMapping_Check(locals)) {
- PyErr_SetString(PyExc_TypeError,
- "exec: arg 3 must be a mapping or None");
- return -1;
- }
- if (PyDict_GetItemString(globals, "__builtins__") == NULL)
- PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
- if (PyCode_Check(prog)) {
- if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
- PyErr_SetString(PyExc_TypeError,
- "code object passed to exec may not contain free variables");
- return -1;
- }
- v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
- }
- else if (PyFile_Check(prog)) {
- FILE *fp = PyFile_AsFile(prog);
- char *name = PyString_AsString(PyFile_Name(prog));
- PyCompilerFlags cf;
- if (name == NULL)
- return -1;
- cf.cf_flags = 0;
- if (PyEval_MergeCompilerFlags(&cf))
- v = PyRun_FileFlags(fp, name, Py_file_input, globals,
- locals, &cf);
- else
- v = PyRun_File(fp, name, Py_file_input, globals,
- locals);
- }
- else {
- PyObject *tmp = NULL;
- char *str;
- PyCompilerFlags cf;
- cf.cf_flags = 0;
+ !PyCode_Check(prog) &&
+ !PyFile_Check(prog)) {
+ PyErr_SetString(PyExc_TypeError,
+ "exec: arg 1 must be a string, file, or code object");
+ return -1;
+ }
+ if (!PyDict_Check(globals)) {
+ PyErr_SetString(PyExc_TypeError,
+ "exec: arg 2 must be a dictionary or None");
+ return -1;
+ }
+ if (!PyMapping_Check(locals)) {
+ PyErr_SetString(PyExc_TypeError,
+ "exec: arg 3 must be a mapping or None");
+ return -1;
+ }
+ if (PyDict_GetItemString(globals, "__builtins__") == NULL)
+ PyDict_SetItemString(globals, "__builtins__", f->f_builtins);
+ if (PyCode_Check(prog)) {
+ if (PyCode_GetNumFree((PyCodeObject *)prog) > 0) {
+ PyErr_SetString(PyExc_TypeError,
+ "code object passed to exec may not contain free variables");
+ return -1;
+ }
+ v = PyEval_EvalCode((PyCodeObject *) prog, globals, locals);
+ }
+ else if (PyFile_Check(prog)) {
+ FILE *fp = PyFile_AsFile(prog);
+ char *name = PyString_AsString(PyFile_Name(prog));
+ PyCompilerFlags cf;
+ if (name == NULL)
+ return -1;
+ cf.cf_flags = 0;
+ if (PyEval_MergeCompilerFlags(&cf))
+ v = PyRun_FileFlags(fp, name, Py_file_input, globals,
+ locals, &cf);
+ else
+ v = PyRun_File(fp, name, Py_file_input, globals,
+ locals);
+ }
+ else {
+ PyObject *tmp = NULL;
+ char *str;
+ PyCompilerFlags cf;
+ cf.cf_flags = 0;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(prog)) {
- tmp = PyUnicode_AsUTF8String(prog);
- if (tmp == NULL)
- return -1;
- prog = tmp;
- cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
- }
+ if (PyUnicode_Check(prog)) {
+ tmp = PyUnicode_AsUTF8String(prog);
+ if (tmp == NULL)
+ return -1;
+ prog = tmp;
+ cf.cf_flags |= PyCF_SOURCE_IS_UTF8;
+ }
#endif
- if (PyString_AsStringAndSize(prog, &str, NULL))
- return -1;
- if (PyEval_MergeCompilerFlags(&cf))
- v = PyRun_StringFlags(str, Py_file_input, globals,
- locals, &cf);
- else
- v = PyRun_String(str, Py_file_input, globals, locals);
- Py_XDECREF(tmp);
- }
- if (plain)
- PyFrame_LocalsToFast(f, 0);
- if (v == NULL)
- return -1;
- Py_DECREF(v);
- return 0;
+ if (PyString_AsStringAndSize(prog, &str, NULL))
+ return -1;
+ if (PyEval_MergeCompilerFlags(&cf))
+ v = PyRun_StringFlags(str, Py_file_input, globals,
+ locals, &cf);
+ else
+ v = PyRun_String(str, Py_file_input, globals, locals);
+ Py_XDECREF(tmp);
+ }
+ if (plain)
+ PyFrame_LocalsToFast(f, 0);
+ if (v == NULL)
+ return -1;
+ Py_DECREF(v);
+ return 0;
}
static void
format_exc_check_arg(PyObject *exc, char *format_str, PyObject *obj)
{
- char *obj_str;
+ char *obj_str;
- if (!obj)
- return;
+ if (!obj)
+ return;
- obj_str = PyString_AsString(obj);
- if (!obj_str)
- return;
+ obj_str = PyString_AsString(obj);
+ if (!obj_str)
+ return;
- PyErr_Format(exc, format_str, obj_str);
+ PyErr_Format(exc, format_str, obj_str);
}
static PyObject *
string_concatenate(PyObject *v, PyObject *w,
- PyFrameObject *f, unsigned char *next_instr)
+ PyFrameObject *f, unsigned char *next_instr)
{
- /* This function implements 'variable += expr' when both arguments
- are strings. */
- Py_ssize_t v_len = PyString_GET_SIZE(v);
- Py_ssize_t w_len = PyString_GET_SIZE(w);
- Py_ssize_t new_len = v_len + w_len;
- if (new_len < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "strings are too large to concat");
- return NULL;
- }
-
- if (v->ob_refcnt == 2) {
- /* In the common case, there are 2 references to the value
- * stored in 'variable' when the += is performed: one on the
- * value stack (in 'v') and one still stored in the
- * 'variable'. We try to delete the variable now to reduce
- * the refcnt to 1.
- */
- switch (*next_instr) {
- case STORE_FAST:
- {
- int oparg = PEEKARG();
- PyObject **fastlocals = f->f_localsplus;
- if (GETLOCAL(oparg) == v)
- SETLOCAL(oparg, NULL);
- break;
- }
- case STORE_DEREF:
- {
- PyObject **freevars = (f->f_localsplus +
- f->f_code->co_nlocals);
- PyObject *c = freevars[PEEKARG()];
- if (PyCell_GET(c) == v)
- PyCell_Set(c, NULL);
- break;
- }
- case STORE_NAME:
- {
- PyObject *names = f->f_code->co_names;
- PyObject *name = GETITEM(names, PEEKARG());
- PyObject *locals = f->f_locals;
- if (PyDict_CheckExact(locals) &&
- PyDict_GetItem(locals, name) == v) {
- if (PyDict_DelItem(locals, name) != 0) {
- PyErr_Clear();
- }
- }
- break;
- }
- }
- }
-
- if (v->ob_refcnt == 1 && !PyString_CHECK_INTERNED(v)) {
- /* Now we own the last reference to 'v', so we can resize it
- * in-place.
- */
- if (_PyString_Resize(&v, new_len) != 0) {
- /* XXX if _PyString_Resize() fails, 'v' has been
- * deallocated so it cannot be put back into
- * 'variable'. The MemoryError is raised when there
- * is no value in 'variable', which might (very
- * remotely) be a cause of incompatibilities.
- */
- return NULL;
- }
- /* copy 'w' into the newly allocated area of 'v' */
- memcpy(PyString_AS_STRING(v) + v_len,
- PyString_AS_STRING(w), w_len);
- return v;
- }
- else {
- /* When in-place resizing is not an option. */
- PyString_Concat(&v, w);
- return v;
- }
+ /* This function implements 'variable += expr' when both arguments
+ are strings. */
+ Py_ssize_t v_len = PyString_GET_SIZE(v);
+ Py_ssize_t w_len = PyString_GET_SIZE(w);
+ Py_ssize_t new_len = v_len + w_len;
+ if (new_len < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "strings are too large to concat");
+ return NULL;
+ }
+
+ if (v->ob_refcnt == 2) {
+ /* In the common case, there are 2 references to the value
+ * stored in 'variable' when the += is performed: one on the
+ * value stack (in 'v') and one still stored in the
+ * 'variable'. We try to delete the variable now to reduce
+ * the refcnt to 1.
+ */
+ switch (*next_instr) {
+ case STORE_FAST:
+ {
+ int oparg = PEEKARG();
+ PyObject **fastlocals = f->f_localsplus;
+ if (GETLOCAL(oparg) == v)
+ SETLOCAL(oparg, NULL);
+ break;
+ }
+ case STORE_DEREF:
+ {
+ PyObject **freevars = (f->f_localsplus +
+ f->f_code->co_nlocals);
+ PyObject *c = freevars[PEEKARG()];
+ if (PyCell_GET(c) == v)
+ PyCell_Set(c, NULL);
+ break;
+ }
+ case STORE_NAME:
+ {
+ PyObject *names = f->f_code->co_names;
+ PyObject *name = GETITEM(names, PEEKARG());
+ PyObject *locals = f->f_locals;
+ if (PyDict_CheckExact(locals) &&
+ PyDict_GetItem(locals, name) == v) {
+ if (PyDict_DelItem(locals, name) != 0) {
+ PyErr_Clear();
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ if (v->ob_refcnt == 1 && !PyString_CHECK_INTERNED(v)) {
+ /* Now we own the last reference to 'v', so we can resize it
+ * in-place.
+ */
+ if (_PyString_Resize(&v, new_len) != 0) {
+ /* XXX if _PyString_Resize() fails, 'v' has been
+ * deallocated so it cannot be put back into
+ * 'variable'. The MemoryError is raised when there
+ * is no value in 'variable', which might (very
+ * remotely) be a cause of incompatibilities.
+ */
+ return NULL;
+ }
+ /* copy 'w' into the newly allocated area of 'v' */
+ memcpy(PyString_AS_STRING(v) + v_len,
+ PyString_AS_STRING(w), w_len);
+ return v;
+ }
+ else {
+ /* When in-place resizing is not an option. */
+ PyString_Concat(&v, w);
+ return v;
+ }
}
#ifdef DYNAMIC_EXECUTION_PROFILE
@@ -4854,40 +4854,40 @@ string_concatenate(PyObject *v, PyObject *w,
static PyObject *
getarray(long a[256])
{
- int i;
- PyObject *l = PyList_New(256);
- if (l == NULL) return NULL;
- for (i = 0; i < 256; i++) {
- PyObject *x = PyInt_FromLong(a[i]);
- if (x == NULL) {
- Py_DECREF(l);
- return NULL;
- }
- PyList_SetItem(l, i, x);
- }
- for (i = 0; i < 256; i++)
- a[i] = 0;
- return l;
+ int i;
+ PyObject *l = PyList_New(256);
+ if (l == NULL) return NULL;
+ for (i = 0; i < 256; i++) {
+ PyObject *x = PyInt_FromLong(a[i]);
+ if (x == NULL) {
+ Py_DECREF(l);
+ return NULL;
+ }
+ PyList_SetItem(l, i, x);
+ }
+ for (i = 0; i < 256; i++)
+ a[i] = 0;
+ return l;
}
PyObject *
_Py_GetDXProfile(PyObject *self, PyObject *args)
{
#ifndef DXPAIRS
- return getarray(dxp);
+ return getarray(dxp);
#else
- int i;
- PyObject *l = PyList_New(257);
- if (l == NULL) return NULL;
- for (i = 0; i < 257; i++) {
- PyObject *x = getarray(dxpairs[i]);
- if (x == NULL) {
- Py_DECREF(l);
- return NULL;
- }
- PyList_SetItem(l, i, x);
- }
- return l;
+ int i;
+ PyObject *l = PyList_New(257);
+ if (l == NULL) return NULL;
+ for (i = 0; i < 257; i++) {
+ PyObject *x = getarray(dxpairs[i]);
+ if (x == NULL) {
+ Py_DECREF(l);
+ return NULL;
+ }
+ PyList_SetItem(l, i, x);
+ }
+ return l;
#endif
}
diff --git a/Python/codecs.c b/Python/codecs.c
index 3849cf9..57bd0f4 100644
--- a/Python/codecs.c
+++ b/Python/codecs.c
@@ -14,7 +14,7 @@ Copyright (c) Corporation for National Research Initiatives.
/* --- Codec Registry ----------------------------------------------------- */
/* Import the standard encodings package which will register the first
- codec search function.
+ codec search function.
This is done in a lazy way so that the Unicode implementation does
not downgrade startup time of scripts not needing it.
@@ -30,14 +30,14 @@ int PyCodec_Register(PyObject *search_function)
{
PyInterpreterState *interp = PyThreadState_GET()->interp;
if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
- goto onError;
+ goto onError;
if (search_function == NULL) {
- PyErr_BadArgument();
- goto onError;
+ PyErr_BadArgument();
+ goto onError;
}
if (!PyCallable_Check(search_function)) {
- PyErr_SetString(PyExc_TypeError, "argument must be callable");
- goto onError;
+ PyErr_SetString(PyExc_TypeError, "argument must be callable");
+ goto onError;
}
return PyList_Append(interp->codec_search_path, search_function);
@@ -55,15 +55,15 @@ PyObject *normalizestring(const char *string)
size_t len = strlen(string);
char *p;
PyObject *v;
-
+
if (len > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError, "string is too large");
- return NULL;
+ PyErr_SetString(PyExc_OverflowError, "string is too large");
+ return NULL;
}
-
+
v = PyString_FromStringAndSize(NULL, len);
if (v == NULL)
- return NULL;
+ return NULL;
p = PyString_AS_STRING(v);
for (i = 0; i < len; i++) {
register char ch = string[i];
@@ -71,7 +71,7 @@ PyObject *normalizestring(const char *string)
ch = '-';
else
ch = tolower(Py_CHARMASK(ch));
- p[i] = ch;
+ p[i] = ch;
}
return v;
}
@@ -83,7 +83,7 @@ PyObject *normalizestring(const char *string)
characters. This makes encodings looked up through this mechanism
effectively case-insensitive.
- If no codec is found, a LookupError is set and NULL returned.
+ If no codec is found, a LookupError is set and NULL returned.
As side effect, this tries to load the encodings package, if not
yet done. This is part of the lazy load strategy for the encodings
@@ -98,72 +98,72 @@ PyObject *_PyCodec_Lookup(const char *encoding)
Py_ssize_t i, len;
if (encoding == NULL) {
- PyErr_BadArgument();
- goto onError;
+ PyErr_BadArgument();
+ goto onError;
}
interp = PyThreadState_GET()->interp;
if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
- goto onError;
+ goto onError;
/* Convert the encoding to a normalized Python string: all
characters are converted to lower case, spaces and hyphens are
replaced with underscores. */
v = normalizestring(encoding);
if (v == NULL)
- goto onError;
+ goto onError;
PyString_InternInPlace(&v);
/* First, try to lookup the name in the registry dictionary */
result = PyDict_GetItem(interp->codec_search_cache, v);
if (result != NULL) {
- Py_INCREF(result);
- Py_DECREF(v);
- return result;
+ Py_INCREF(result);
+ Py_DECREF(v);
+ return result;
}
-
+
/* Next, scan the search functions in order of registration */
args = PyTuple_New(1);
if (args == NULL)
- goto onError;
+ goto onError;
PyTuple_SET_ITEM(args,0,v);
len = PyList_Size(interp->codec_search_path);
if (len < 0)
- goto onError;
+ goto onError;
if (len == 0) {
- PyErr_SetString(PyExc_LookupError,
- "no codec search functions registered: "
- "can't find encoding");
- goto onError;
+ PyErr_SetString(PyExc_LookupError,
+ "no codec search functions registered: "
+ "can't find encoding");
+ goto onError;
}
for (i = 0; i < len; i++) {
- PyObject *func;
-
- func = PyList_GetItem(interp->codec_search_path, i);
- if (func == NULL)
- goto onError;
- result = PyEval_CallObject(func, args);
- if (result == NULL)
- goto onError;
- if (result == Py_None) {
- Py_DECREF(result);
- continue;
- }
- if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
- PyErr_SetString(PyExc_TypeError,
- "codec search functions must return 4-tuples");
- Py_DECREF(result);
- goto onError;
- }
- break;
+ PyObject *func;
+
+ func = PyList_GetItem(interp->codec_search_path, i);
+ if (func == NULL)
+ goto onError;
+ result = PyEval_CallObject(func, args);
+ if (result == NULL)
+ goto onError;
+ if (result == Py_None) {
+ Py_DECREF(result);
+ continue;
+ }
+ if (!PyTuple_Check(result) || PyTuple_GET_SIZE(result) != 4) {
+ PyErr_SetString(PyExc_TypeError,
+ "codec search functions must return 4-tuples");
+ Py_DECREF(result);
+ goto onError;
+ }
+ break;
}
if (i == len) {
- /* XXX Perhaps we should cache misses too ? */
- PyErr_Format(PyExc_LookupError,
+ /* XXX Perhaps we should cache misses too ? */
+ PyErr_Format(PyExc_LookupError,
"unknown encoding: %s", encoding);
- goto onError;
+ goto onError;
}
/* Cache and return the result */
@@ -178,24 +178,24 @@ PyObject *_PyCodec_Lookup(const char *encoding)
static
PyObject *args_tuple(PyObject *object,
- const char *errors)
+ const char *errors)
{
PyObject *args;
-
+
args = PyTuple_New(1 + (errors != NULL));
if (args == NULL)
- return NULL;
+ return NULL;
Py_INCREF(object);
PyTuple_SET_ITEM(args,0,object);
if (errors) {
- PyObject *v;
-
- v = PyString_FromString(errors);
- if (v == NULL) {
- Py_DECREF(args);
- return NULL;
- }
- PyTuple_SET_ITEM(args, 1, v);
+ PyObject *v;
+
+ v = PyString_FromString(errors);
+ if (v == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ PyTuple_SET_ITEM(args, 1, v);
}
return args;
}
@@ -210,7 +210,7 @@ PyObject *codec_getitem(const char *encoding, int index)
codecs = _PyCodec_Lookup(encoding);
if (codecs == NULL)
- return NULL;
+ return NULL;
v = PyTuple_GET_ITEM(codecs, index);
Py_DECREF(codecs);
Py_INCREF(v);
@@ -221,22 +221,22 @@ PyObject *codec_getitem(const char *encoding, int index)
static
PyObject *codec_getincrementalcodec(const char *encoding,
- const char *errors,
- const char *attrname)
+ const char *errors,
+ const char *attrname)
{
PyObject *codecs, *ret, *inccodec;
codecs = _PyCodec_Lookup(encoding);
if (codecs == NULL)
- return NULL;
+ return NULL;
inccodec = PyObject_GetAttrString(codecs, attrname);
Py_DECREF(codecs);
if (inccodec == NULL)
- return NULL;
+ return NULL;
if (errors)
- ret = PyObject_CallFunction(inccodec, "s", errors);
+ ret = PyObject_CallFunction(inccodec, "s", errors);
else
- ret = PyObject_CallFunction(inccodec, NULL);
+ ret = PyObject_CallFunction(inccodec, NULL);
Py_DECREF(inccodec);
return ret;
}
@@ -245,29 +245,29 @@ PyObject *codec_getincrementalcodec(const char *encoding,
static
PyObject *codec_getstreamcodec(const char *encoding,
- PyObject *stream,
- const char *errors,
- const int index)
+ PyObject *stream,
+ const char *errors,
+ const int index)
{
PyObject *codecs, *streamcodec, *codeccls;
codecs = _PyCodec_Lookup(encoding);
if (codecs == NULL)
- return NULL;
+ return NULL;
codeccls = PyTuple_GET_ITEM(codecs, index);
if (errors != NULL)
- streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors);
+ streamcodec = PyObject_CallFunction(codeccls, "Os", stream, errors);
else
- streamcodec = PyObject_CallFunction(codeccls, "O", stream);
+ streamcodec = PyObject_CallFunction(codeccls, "O", stream);
Py_DECREF(codecs);
return streamcodec;
}
-/* Convenience APIs to query the Codec registry.
-
+/* Convenience APIs to query the Codec registry.
+
All APIs return a codec object with incremented refcount.
-
+
*/
PyObject *PyCodec_Encoder(const char *encoding)
@@ -281,27 +281,27 @@ PyObject *PyCodec_Decoder(const char *encoding)
}
PyObject *PyCodec_IncrementalEncoder(const char *encoding,
- const char *errors)
+ const char *errors)
{
return codec_getincrementalcodec(encoding, errors, "incrementalencoder");
}
PyObject *PyCodec_IncrementalDecoder(const char *encoding,
- const char *errors)
+ const char *errors)
{
return codec_getincrementalcodec(encoding, errors, "incrementaldecoder");
}
PyObject *PyCodec_StreamReader(const char *encoding,
- PyObject *stream,
- const char *errors)
+ PyObject *stream,
+ const char *errors)
{
return codec_getstreamcodec(encoding, stream, errors, 2);
}
PyObject *PyCodec_StreamWriter(const char *encoding,
- PyObject *stream,
- const char *errors)
+ PyObject *stream,
+ const char *errors)
{
return codec_getstreamcodec(encoding, stream, errors, 3);
}
@@ -312,8 +312,8 @@ PyObject *PyCodec_StreamWriter(const char *encoding,
errors is passed to the encoder factory as argument if non-NULL. */
PyObject *PyCodec_Encode(PyObject *object,
- const char *encoding,
- const char *errors)
+ const char *encoding,
+ const char *errors)
{
PyObject *encoder = NULL;
PyObject *args = NULL, *result = NULL;
@@ -321,21 +321,21 @@ PyObject *PyCodec_Encode(PyObject *object,
encoder = PyCodec_Encoder(encoding);
if (encoder == NULL)
- goto onError;
+ goto onError;
args = args_tuple(object, errors);
if (args == NULL)
- goto onError;
-
+ goto onError;
+
result = PyEval_CallObject(encoder,args);
if (result == NULL)
- goto onError;
+ goto onError;
- if (!PyTuple_Check(result) ||
- PyTuple_GET_SIZE(result) != 2) {
- PyErr_SetString(PyExc_TypeError,
- "encoder must return a tuple (object,integer)");
- goto onError;
+ if (!PyTuple_Check(result) ||
+ PyTuple_GET_SIZE(result) != 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "encoder must return a tuple (object,integer)");
+ goto onError;
}
v = PyTuple_GET_ITEM(result,0);
Py_INCREF(v);
@@ -345,7 +345,7 @@ PyObject *PyCodec_Encode(PyObject *object,
Py_DECREF(encoder);
Py_DECREF(result);
return v;
-
+
onError:
Py_XDECREF(result);
Py_XDECREF(args);
@@ -359,8 +359,8 @@ PyObject *PyCodec_Encode(PyObject *object,
errors is passed to the decoder factory as argument if non-NULL. */
PyObject *PyCodec_Decode(PyObject *object,
- const char *encoding,
- const char *errors)
+ const char *encoding,
+ const char *errors)
{
PyObject *decoder = NULL;
PyObject *args = NULL, *result = NULL;
@@ -368,20 +368,20 @@ PyObject *PyCodec_Decode(PyObject *object,
decoder = PyCodec_Decoder(encoding);
if (decoder == NULL)
- goto onError;
+ goto onError;
args = args_tuple(object, errors);
if (args == NULL)
- goto onError;
-
+ goto onError;
+
result = PyEval_CallObject(decoder,args);
if (result == NULL)
- goto onError;
- if (!PyTuple_Check(result) ||
- PyTuple_GET_SIZE(result) != 2) {
- PyErr_SetString(PyExc_TypeError,
- "decoder must return a tuple (object,integer)");
- goto onError;
+ goto onError;
+ if (!PyTuple_Check(result) ||
+ PyTuple_GET_SIZE(result) != 2) {
+ PyErr_SetString(PyExc_TypeError,
+ "decoder must return a tuple (object,integer)");
+ goto onError;
}
v = PyTuple_GET_ITEM(result,0);
Py_INCREF(v);
@@ -391,7 +391,7 @@ PyObject *PyCodec_Decode(PyObject *object,
Py_DECREF(decoder);
Py_DECREF(result);
return v;
-
+
onError:
Py_XDECREF(args);
Py_XDECREF(decoder);
@@ -409,13 +409,13 @@ int PyCodec_RegisterError(const char *name, PyObject *error)
{
PyInterpreterState *interp = PyThreadState_GET()->interp;
if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
- return -1;
+ return -1;
if (!PyCallable_Check(error)) {
- PyErr_SetString(PyExc_TypeError, "handler must be callable");
- return -1;
+ PyErr_SetString(PyExc_TypeError, "handler must be callable");
+ return -1;
}
return PyDict_SetItemString(interp->codec_error_registry,
- (char *)name, error);
+ (char *)name, error);
}
/* Lookup the error handling callback function registered under the
@@ -427,15 +427,15 @@ PyObject *PyCodec_LookupError(const char *name)
PyInterpreterState *interp = PyThreadState_GET()->interp;
if (interp->codec_search_path == NULL && _PyCodecRegistry_Init())
- return NULL;
+ return NULL;
if (name==NULL)
- name = "strict";
+ name = "strict";
handler = PyDict_GetItemString(interp->codec_error_registry, (char *)name);
if (!handler)
- PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name);
+ PyErr_Format(PyExc_LookupError, "unknown error handler name '%.400s'", name);
else
- Py_INCREF(handler);
+ Py_INCREF(handler);
return handler;
}
@@ -443,18 +443,18 @@ static void wrong_exception_type(PyObject *exc)
{
PyObject *type = PyObject_GetAttrString(exc, "__class__");
if (type != NULL) {
- PyObject *name = PyObject_GetAttrString(type, "__name__");
- Py_DECREF(type);
- if (name != NULL) {
- PyObject *string = PyObject_Str(name);
- Py_DECREF(name);
- if (string != NULL) {
- PyErr_Format(PyExc_TypeError,
- "don't know how to handle %.400s in error callback",
- PyString_AS_STRING(string));
- Py_DECREF(string);
- }
- }
+ PyObject *name = PyObject_GetAttrString(type, "__name__");
+ Py_DECREF(type);
+ if (name != NULL) {
+ PyObject *string = PyObject_Str(name);
+ Py_DECREF(name);
+ if (string != NULL) {
+ PyErr_Format(PyExc_TypeError,
+ "don't know how to handle %.400s in error callback",
+ PyString_AS_STRING(string));
+ Py_DECREF(string);
+ }
+ }
}
}
@@ -463,7 +463,7 @@ PyObject *PyCodec_StrictErrors(PyObject *exc)
if (PyExceptionInstance_Check(exc))
PyErr_SetObject(PyExceptionInstance_Class(exc), exc);
else
- PyErr_SetString(PyExc_TypeError, "codec must pass exception instance");
+ PyErr_SetString(PyExc_TypeError, "codec must pass exception instance");
return NULL;
}
@@ -473,20 +473,20 @@ PyObject *PyCodec_IgnoreErrors(PyObject *exc)
{
Py_ssize_t end;
if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
- if (PyUnicodeEncodeError_GetEnd(exc, &end))
- return NULL;
+ if (PyUnicodeEncodeError_GetEnd(exc, &end))
+ return NULL;
}
else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
- if (PyUnicodeDecodeError_GetEnd(exc, &end))
- return NULL;
+ if (PyUnicodeDecodeError_GetEnd(exc, &end))
+ return NULL;
}
else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
- if (PyUnicodeTranslateError_GetEnd(exc, &end))
- return NULL;
+ if (PyUnicodeTranslateError_GetEnd(exc, &end))
+ return NULL;
}
else {
- wrong_exception_type(exc);
- return NULL;
+ wrong_exception_type(exc);
+ return NULL;
}
/* ouch: passing NULL, 0, pos gives None instead of u'' */
return Py_BuildValue("(u#n)", &end, 0, end);
@@ -501,155 +501,155 @@ PyObject *PyCodec_ReplaceErrors(PyObject *exc)
Py_ssize_t i;
if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
- PyObject *res;
- Py_UNICODE *p;
- if (PyUnicodeEncodeError_GetStart(exc, &start))
- return NULL;
- if (PyUnicodeEncodeError_GetEnd(exc, &end))
- return NULL;
- res = PyUnicode_FromUnicode(NULL, end-start);
- if (res == NULL)
- return NULL;
- for (p = PyUnicode_AS_UNICODE(res), i = start;
- i<end; ++p, ++i)
- *p = '?';
- restuple = Py_BuildValue("(On)", res, end);
- Py_DECREF(res);
- return restuple;
+ PyObject *res;
+ Py_UNICODE *p;
+ if (PyUnicodeEncodeError_GetStart(exc, &start))
+ return NULL;
+ if (PyUnicodeEncodeError_GetEnd(exc, &end))
+ return NULL;
+ res = PyUnicode_FromUnicode(NULL, end-start);
+ if (res == NULL)
+ return NULL;
+ for (p = PyUnicode_AS_UNICODE(res), i = start;
+ i<end; ++p, ++i)
+ *p = '?';
+ restuple = Py_BuildValue("(On)", res, end);
+ Py_DECREF(res);
+ return restuple;
}
else if (PyObject_IsInstance(exc, PyExc_UnicodeDecodeError)) {
- Py_UNICODE res = Py_UNICODE_REPLACEMENT_CHARACTER;
- if (PyUnicodeDecodeError_GetEnd(exc, &end))
- return NULL;
- return Py_BuildValue("(u#n)", &res, 1, end);
+ Py_UNICODE res = Py_UNICODE_REPLACEMENT_CHARACTER;
+ if (PyUnicodeDecodeError_GetEnd(exc, &end))
+ return NULL;
+ return Py_BuildValue("(u#n)", &res, 1, end);
}
else if (PyObject_IsInstance(exc, PyExc_UnicodeTranslateError)) {
- PyObject *res;
- Py_UNICODE *p;
- if (PyUnicodeTranslateError_GetStart(exc, &start))
- return NULL;
- if (PyUnicodeTranslateError_GetEnd(exc, &end))
- return NULL;
- res = PyUnicode_FromUnicode(NULL, end-start);
- if (res == NULL)
- return NULL;
- for (p = PyUnicode_AS_UNICODE(res), i = start;
- i<end; ++p, ++i)
- *p = Py_UNICODE_REPLACEMENT_CHARACTER;
- restuple = Py_BuildValue("(On)", res, end);
- Py_DECREF(res);
- return restuple;
+ PyObject *res;
+ Py_UNICODE *p;
+ if (PyUnicodeTranslateError_GetStart(exc, &start))
+ return NULL;
+ if (PyUnicodeTranslateError_GetEnd(exc, &end))
+ return NULL;
+ res = PyUnicode_FromUnicode(NULL, end-start);
+ if (res == NULL)
+ return NULL;
+ for (p = PyUnicode_AS_UNICODE(res), i = start;
+ i<end; ++p, ++i)
+ *p = Py_UNICODE_REPLACEMENT_CHARACTER;
+ restuple = Py_BuildValue("(On)", res, end);
+ Py_DECREF(res);
+ return restuple;
}
else {
- wrong_exception_type(exc);
- return NULL;
+ wrong_exception_type(exc);
+ return NULL;
}
}
PyObject *PyCodec_XMLCharRefReplaceErrors(PyObject *exc)
{
if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
- PyObject *restuple;
- PyObject *object;
- Py_ssize_t start;
- Py_ssize_t end;
- PyObject *res;
- Py_UNICODE *p;
- Py_UNICODE *startp;
- Py_UNICODE *outp;
- int ressize;
- if (PyUnicodeEncodeError_GetStart(exc, &start))
- return NULL;
- if (PyUnicodeEncodeError_GetEnd(exc, &end))
- return NULL;
- if (!(object = PyUnicodeEncodeError_GetObject(exc)))
- return NULL;
- startp = PyUnicode_AS_UNICODE(object);
- for (p = startp+start, ressize = 0; p < startp+end; ++p) {
- if (*p<10)
- ressize += 2+1+1;
- else if (*p<100)
- ressize += 2+2+1;
- else if (*p<1000)
- ressize += 2+3+1;
- else if (*p<10000)
- ressize += 2+4+1;
+ PyObject *restuple;
+ PyObject *object;
+ Py_ssize_t start;
+ Py_ssize_t end;
+ PyObject *res;
+ Py_UNICODE *p;
+ Py_UNICODE *startp;
+ Py_UNICODE *outp;
+ int ressize;
+ if (PyUnicodeEncodeError_GetStart(exc, &start))
+ return NULL;
+ if (PyUnicodeEncodeError_GetEnd(exc, &end))
+ return NULL;
+ if (!(object = PyUnicodeEncodeError_GetObject(exc)))
+ return NULL;
+ startp = PyUnicode_AS_UNICODE(object);
+ for (p = startp+start, ressize = 0; p < startp+end; ++p) {
+ if (*p<10)
+ ressize += 2+1+1;
+ else if (*p<100)
+ ressize += 2+2+1;
+ else if (*p<1000)
+ ressize += 2+3+1;
+ else if (*p<10000)
+ ressize += 2+4+1;
#ifndef Py_UNICODE_WIDE
- else
- ressize += 2+5+1;
+ else
+ ressize += 2+5+1;
#else
- else if (*p<100000)
- ressize += 2+5+1;
- else if (*p<1000000)
- ressize += 2+6+1;
- else
- ressize += 2+7+1;
+ else if (*p<100000)
+ ressize += 2+5+1;
+ else if (*p<1000000)
+ ressize += 2+6+1;
+ else
+ ressize += 2+7+1;
#endif
- }
- /* allocate replacement */
- res = PyUnicode_FromUnicode(NULL, ressize);
- if (res == NULL) {
- Py_DECREF(object);
- return NULL;
- }
- /* generate replacement */
- for (p = startp+start, outp = PyUnicode_AS_UNICODE(res);
- p < startp+end; ++p) {
- Py_UNICODE c = *p;
- int digits;
- int base;
- *outp++ = '&';
- *outp++ = '#';
- if (*p<10) {
- digits = 1;
- base = 1;
- }
- else if (*p<100) {
- digits = 2;
- base = 10;
- }
- else if (*p<1000) {
- digits = 3;
- base = 100;
- }
- else if (*p<10000) {
- digits = 4;
- base = 1000;
- }
+ }
+ /* allocate replacement */
+ res = PyUnicode_FromUnicode(NULL, ressize);
+ if (res == NULL) {
+ Py_DECREF(object);
+ return NULL;
+ }
+ /* generate replacement */
+ for (p = startp+start, outp = PyUnicode_AS_UNICODE(res);
+ p < startp+end; ++p) {
+ Py_UNICODE c = *p;
+ int digits;
+ int base;
+ *outp++ = '&';
+ *outp++ = '#';
+ if (*p<10) {
+ digits = 1;
+ base = 1;
+ }
+ else if (*p<100) {
+ digits = 2;
+ base = 10;
+ }
+ else if (*p<1000) {
+ digits = 3;
+ base = 100;
+ }
+ else if (*p<10000) {
+ digits = 4;
+ base = 1000;
+ }
#ifndef Py_UNICODE_WIDE
- else {
- digits = 5;
- base = 10000;
- }
+ else {
+ digits = 5;
+ base = 10000;
+ }
#else
- else if (*p<100000) {
- digits = 5;
- base = 10000;
- }
- else if (*p<1000000) {
- digits = 6;
- base = 100000;
- }
- else {
- digits = 7;
- base = 1000000;
- }
+ else if (*p<100000) {
+ digits = 5;
+ base = 10000;
+ }
+ else if (*p<1000000) {
+ digits = 6;
+ base = 100000;
+ }
+ else {
+ digits = 7;
+ base = 1000000;
+ }
#endif
- while (digits-->0) {
- *outp++ = '0' + c/base;
- c %= base;
- base /= 10;
- }
- *outp++ = ';';
- }
- restuple = Py_BuildValue("(On)", res, end);
- Py_DECREF(res);
- Py_DECREF(object);
- return restuple;
+ while (digits-->0) {
+ *outp++ = '0' + c/base;
+ c %= base;
+ base /= 10;
+ }
+ *outp++ = ';';
+ }
+ restuple = Py_BuildValue("(On)", res, end);
+ Py_DECREF(res);
+ Py_DECREF(object);
+ return restuple;
}
else {
- wrong_exception_type(exc);
- return NULL;
+ wrong_exception_type(exc);
+ return NULL;
}
}
@@ -661,72 +661,72 @@ static Py_UNICODE hexdigits[] = {
PyObject *PyCodec_BackslashReplaceErrors(PyObject *exc)
{
if (PyObject_IsInstance(exc, PyExc_UnicodeEncodeError)) {
- PyObject *restuple;
- PyObject *object;
- Py_ssize_t start;
- Py_ssize_t end;
- PyObject *res;
- Py_UNICODE *p;
- Py_UNICODE *startp;
- Py_UNICODE *outp;
- int ressize;
- if (PyUnicodeEncodeError_GetStart(exc, &start))
- return NULL;
- if (PyUnicodeEncodeError_GetEnd(exc, &end))
- return NULL;
- if (!(object = PyUnicodeEncodeError_GetObject(exc)))
- return NULL;
- startp = PyUnicode_AS_UNICODE(object);
- for (p = startp+start, ressize = 0; p < startp+end; ++p) {
+ PyObject *restuple;
+ PyObject *object;
+ Py_ssize_t start;
+ Py_ssize_t end;
+ PyObject *res;
+ Py_UNICODE *p;
+ Py_UNICODE *startp;
+ Py_UNICODE *outp;
+ int ressize;
+ if (PyUnicodeEncodeError_GetStart(exc, &start))
+ return NULL;
+ if (PyUnicodeEncodeError_GetEnd(exc, &end))
+ return NULL;
+ if (!(object = PyUnicodeEncodeError_GetObject(exc)))
+ return NULL;
+ startp = PyUnicode_AS_UNICODE(object);
+ for (p = startp+start, ressize = 0; p < startp+end; ++p) {
#ifdef Py_UNICODE_WIDE
- if (*p >= 0x00010000)
- ressize += 1+1+8;
- else
+ if (*p >= 0x00010000)
+ ressize += 1+1+8;
+ else
#endif
- if (*p >= 0x100) {
- ressize += 1+1+4;
- }
- else
- ressize += 1+1+2;
- }
- res = PyUnicode_FromUnicode(NULL, ressize);
- if (res==NULL)
- return NULL;
- for (p = startp+start, outp = PyUnicode_AS_UNICODE(res);
- p < startp+end; ++p) {
- Py_UNICODE c = *p;
- *outp++ = '\\';
+ if (*p >= 0x100) {
+ ressize += 1+1+4;
+ }
+ else
+ ressize += 1+1+2;
+ }
+ res = PyUnicode_FromUnicode(NULL, ressize);
+ if (res==NULL)
+ return NULL;
+ for (p = startp+start, outp = PyUnicode_AS_UNICODE(res);
+ p < startp+end; ++p) {
+ Py_UNICODE c = *p;
+ *outp++ = '\\';
#ifdef Py_UNICODE_WIDE
- if (c >= 0x00010000) {
- *outp++ = 'U';
- *outp++ = hexdigits[(c>>28)&0xf];
- *outp++ = hexdigits[(c>>24)&0xf];
- *outp++ = hexdigits[(c>>20)&0xf];
- *outp++ = hexdigits[(c>>16)&0xf];
- *outp++ = hexdigits[(c>>12)&0xf];
- *outp++ = hexdigits[(c>>8)&0xf];
- }
- else
+ if (c >= 0x00010000) {
+ *outp++ = 'U';
+ *outp++ = hexdigits[(c>>28)&0xf];
+ *outp++ = hexdigits[(c>>24)&0xf];
+ *outp++ = hexdigits[(c>>20)&0xf];
+ *outp++ = hexdigits[(c>>16)&0xf];
+ *outp++ = hexdigits[(c>>12)&0xf];
+ *outp++ = hexdigits[(c>>8)&0xf];
+ }
+ else
#endif
- if (c >= 0x100) {
- *outp++ = 'u';
- *outp++ = hexdigits[(c>>12)&0xf];
- *outp++ = hexdigits[(c>>8)&0xf];
- }
- else
- *outp++ = 'x';
- *outp++ = hexdigits[(c>>4)&0xf];
- *outp++ = hexdigits[c&0xf];
- }
-
- restuple = Py_BuildValue("(On)", res, end);
- Py_DECREF(res);
- Py_DECREF(object);
- return restuple;
+ if (c >= 0x100) {
+ *outp++ = 'u';
+ *outp++ = hexdigits[(c>>12)&0xf];
+ *outp++ = hexdigits[(c>>8)&0xf];
+ }
+ else
+ *outp++ = 'x';
+ *outp++ = hexdigits[(c>>4)&0xf];
+ *outp++ = hexdigits[c&0xf];
+ }
+
+ restuple = Py_BuildValue("(On)", res, end);
+ Py_DECREF(res);
+ Py_DECREF(object);
+ return restuple;
}
else {
- wrong_exception_type(exc);
- return NULL;
+ wrong_exception_type(exc);
+ return NULL;
}
}
#endif
@@ -765,63 +765,63 @@ static PyObject *backslashreplace_errors(PyObject *self, PyObject *exc)
static int _PyCodecRegistry_Init(void)
{
static struct {
- char *name;
- PyMethodDef def;
+ char *name;
+ PyMethodDef def;
} methods[] =
{
- {
- "strict",
- {
- "strict_errors",
- strict_errors,
- METH_O,
- PyDoc_STR("Implements the 'strict' error handling, which "
- "raises a UnicodeError on coding errors.")
- }
- },
+ {
+ "strict",
+ {
+ "strict_errors",
+ strict_errors,
+ METH_O,
+ PyDoc_STR("Implements the 'strict' error handling, which "
+ "raises a UnicodeError on coding errors.")
+ }
+ },
#ifdef Py_USING_UNICODE
- {
- "ignore",
- {
- "ignore_errors",
- ignore_errors,
- METH_O,
- PyDoc_STR("Implements the 'ignore' error handling, which "
- "ignores malformed data and continues.")
- }
- },
- {
- "replace",
- {
- "replace_errors",
- replace_errors,
- METH_O,
- PyDoc_STR("Implements the 'replace' error handling, which "
- "replaces malformed data with a replacement marker.")
- }
- },
- {
- "xmlcharrefreplace",
- {
- "xmlcharrefreplace_errors",
- xmlcharrefreplace_errors,
- METH_O,
- PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, "
- "which replaces an unencodable character with the "
- "appropriate XML character reference.")
- }
- },
- {
- "backslashreplace",
- {
- "backslashreplace_errors",
- backslashreplace_errors,
- METH_O,
- PyDoc_STR("Implements the 'backslashreplace' error handling, "
- "which replaces an unencodable character with a "
- "backslashed escape sequence.")
- }
- }
+ {
+ "ignore",
+ {
+ "ignore_errors",
+ ignore_errors,
+ METH_O,
+ PyDoc_STR("Implements the 'ignore' error handling, which "
+ "ignores malformed data and continues.")
+ }
+ },
+ {
+ "replace",
+ {
+ "replace_errors",
+ replace_errors,
+ METH_O,
+ PyDoc_STR("Implements the 'replace' error handling, which "
+ "replaces malformed data with a replacement marker.")
+ }
+ },
+ {
+ "xmlcharrefreplace",
+ {
+ "xmlcharrefreplace_errors",
+ xmlcharrefreplace_errors,
+ METH_O,
+ PyDoc_STR("Implements the 'xmlcharrefreplace' error handling, "
+ "which replaces an unencodable character with the "
+ "appropriate XML character reference.")
+ }
+ },
+ {
+ "backslashreplace",
+ {
+ "backslashreplace_errors",
+ backslashreplace_errors,
+ METH_O,
+ PyDoc_STR("Implements the 'backslashreplace' error handling, "
+ "which replaces an unencodable character with a "
+ "backslashed escape sequence.")
+ }
+ }
#endif
};
@@ -830,42 +830,42 @@ static int _PyCodecRegistry_Init(void)
unsigned i;
if (interp->codec_search_path != NULL)
- return 0;
+ return 0;
interp->codec_search_path = PyList_New(0);
interp->codec_search_cache = PyDict_New();
interp->codec_error_registry = PyDict_New();
if (interp->codec_error_registry) {
- for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) {
- PyObject *func = PyCFunction_New(&methods[i].def, NULL);
- int res;
- if (!func)
- Py_FatalError("can't initialize codec error registry");
- res = PyCodec_RegisterError(methods[i].name, func);
- Py_DECREF(func);
- if (res)
- Py_FatalError("can't initialize codec error registry");
- }
+ for (i = 0; i < sizeof(methods)/sizeof(methods[0]); ++i) {
+ PyObject *func = PyCFunction_New(&methods[i].def, NULL);
+ int res;
+ if (!func)
+ Py_FatalError("can't initialize codec error registry");
+ res = PyCodec_RegisterError(methods[i].name, func);
+ Py_DECREF(func);
+ if (res)
+ Py_FatalError("can't initialize codec error registry");
+ }
}
if (interp->codec_search_path == NULL ||
- interp->codec_search_cache == NULL ||
- interp->codec_error_registry == NULL)
- Py_FatalError("can't initialize codec registry");
+ interp->codec_search_cache == NULL ||
+ interp->codec_error_registry == NULL)
+ Py_FatalError("can't initialize codec registry");
mod = PyImport_ImportModuleLevel("encodings", NULL, NULL, NULL, 0);
if (mod == NULL) {
- if (PyErr_ExceptionMatches(PyExc_ImportError)) {
- /* Ignore ImportErrors... this is done so that
- distributions can disable the encodings package. Note
- that other errors are not masked, e.g. SystemErrors
- raised to inform the user of an error in the Python
- configuration are still reported back to the user. */
- PyErr_Clear();
- return 0;
- }
- return -1;
+ if (PyErr_ExceptionMatches(PyExc_ImportError)) {
+ /* Ignore ImportErrors... this is done so that
+ distributions can disable the encodings package. Note
+ that other errors are not masked, e.g. SystemErrors
+ raised to inform the user of an error in the Python
+ configuration are still reported back to the user. */
+ PyErr_Clear();
+ return 0;
+ }
+ return -1;
}
Py_DECREF(mod);
return 0;
diff --git a/Python/compile.c b/Python/compile.c
index 90cf065..a8571d2 100644
--- a/Python/compile.c
+++ b/Python/compile.c
@@ -5,10 +5,10 @@
* PyCodeObject. The compiler makes several passes to build the code
* object:
* 1. Checks for future statements. See future.c
- * 2. Builds a symbol table. See symtable.c.
+ * 2. Builds a symbol table. See symtable.c.
* 3. Generate code for basic blocks. See compiler_mod() in this file.
* 4. Assemble the basic blocks into final code. See assemble() in
- * this file.
+ * this file.
* 5. Optimize the byte code (peephole optimizations). See peephole.c
*
* Note that compiler_mod() suggests module, but the module ast type
@@ -44,37 +44,37 @@ int Py_OptimizeFlag = 0;
#define COMP_DICTCOMP 2
struct instr {
- unsigned i_jabs : 1;
- unsigned i_jrel : 1;
- unsigned i_hasarg : 1;
- unsigned char i_opcode;
- int i_oparg;
- struct basicblock_ *i_target; /* target block (if jump instruction) */
- int i_lineno;
+ unsigned i_jabs : 1;
+ unsigned i_jrel : 1;
+ unsigned i_hasarg : 1;
+ unsigned char i_opcode;
+ int i_oparg;
+ struct basicblock_ *i_target; /* target block (if jump instruction) */
+ int i_lineno;
};
typedef struct basicblock_ {
/* Each basicblock in a compilation unit is linked via b_list in the
reverse order that the block are allocated. b_list points to the next
block, not to be confused with b_next, which is next by control flow. */
- struct basicblock_ *b_list;
- /* number of instructions used */
- int b_iused;
- /* length of instruction array (b_instr) */
- int b_ialloc;
- /* pointer to an array of instructions, initially NULL */
- struct instr *b_instr;
- /* If b_next is non-NULL, it is a pointer to the next
- block reached by normal control flow. */
- struct basicblock_ *b_next;
- /* b_seen is used to perform a DFS of basicblocks. */
- unsigned b_seen : 1;
- /* b_return is true if a RETURN_VALUE opcode is inserted. */
- unsigned b_return : 1;
- /* depth of stack upon entry of block, computed by stackdepth() */
- int b_startdepth;
- /* instruction offset for block, computed by assemble_jump_offsets() */
- int b_offset;
+ struct basicblock_ *b_list;
+ /* number of instructions used */
+ int b_iused;
+ /* length of instruction array (b_instr) */
+ int b_ialloc;
+ /* pointer to an array of instructions, initially NULL */
+ struct instr *b_instr;
+ /* If b_next is non-NULL, it is a pointer to the next
+ block reached by normal control flow. */
+ struct basicblock_ *b_next;
+ /* b_seen is used to perform a DFS of basicblocks. */
+ unsigned b_seen : 1;
+ /* b_return is true if a RETURN_VALUE opcode is inserted. */
+ unsigned b_return : 1;
+ /* depth of stack upon entry of block, computed by stackdepth() */
+ int b_startdepth;
+ /* instruction offset for block, computed by assemble_jump_offsets() */
+ int b_offset;
} basicblock;
/* fblockinfo tracks the current frame block.
@@ -87,63 +87,63 @@ compiler IR.
enum fblocktype { LOOP, EXCEPT, FINALLY_TRY, FINALLY_END };
struct fblockinfo {
- enum fblocktype fb_type;
- basicblock *fb_block;
+ enum fblocktype fb_type;
+ basicblock *fb_block;
};
/* The following items change on entry and exit of code blocks.
They must be saved and restored when returning to a block.
*/
struct compiler_unit {
- PySTEntryObject *u_ste;
-
- PyObject *u_name;
- /* The following fields are dicts that map objects to
- the index of them in co_XXX. The index is used as
- the argument for opcodes that refer to those collections.
- */
- PyObject *u_consts; /* all constants */
- PyObject *u_names; /* all names */
- PyObject *u_varnames; /* local variables */
- PyObject *u_cellvars; /* cell variables */
- PyObject *u_freevars; /* free variables */
-
- PyObject *u_private; /* for private name mangling */
-
- int u_argcount; /* number of arguments for block */
- /* Pointer to the most recently allocated block. By following b_list
- members, you can reach all early allocated blocks. */
- basicblock *u_blocks;
- basicblock *u_curblock; /* pointer to current block */
-
- int u_nfblocks;
- struct fblockinfo u_fblock[CO_MAXBLOCKS];
-
- int u_firstlineno; /* the first lineno of the block */
- int u_lineno; /* the lineno for the current stmt */
- bool u_lineno_set; /* boolean to indicate whether instr
- has been generated with current lineno */
+ PySTEntryObject *u_ste;
+
+ PyObject *u_name;
+ /* The following fields are dicts that map objects to
+ the index of them in co_XXX. The index is used as
+ the argument for opcodes that refer to those collections.
+ */
+ PyObject *u_consts; /* all constants */
+ PyObject *u_names; /* all names */
+ PyObject *u_varnames; /* local variables */
+ PyObject *u_cellvars; /* cell variables */
+ PyObject *u_freevars; /* free variables */
+
+ PyObject *u_private; /* for private name mangling */
+
+ int u_argcount; /* number of arguments for block */
+ /* Pointer to the most recently allocated block. By following b_list
+ members, you can reach all early allocated blocks. */
+ basicblock *u_blocks;
+ basicblock *u_curblock; /* pointer to current block */
+
+ int u_nfblocks;
+ struct fblockinfo u_fblock[CO_MAXBLOCKS];
+
+ int u_firstlineno; /* the first lineno of the block */
+ int u_lineno; /* the lineno for the current stmt */
+ bool u_lineno_set; /* boolean to indicate whether instr
+ has been generated with current lineno */
};
-/* This struct captures the global state of a compilation.
+/* This struct captures the global state of a compilation.
The u pointer points to the current compilation unit, while units
-for enclosing blocks are stored in c_stack. The u and c_stack are
+for enclosing blocks are stored in c_stack. The u and c_stack are
managed by compiler_enter_scope() and compiler_exit_scope().
*/
struct compiler {
- const char *c_filename;
- struct symtable *c_st;
- PyFutureFeatures *c_future; /* pointer to module's __future__ */
- PyCompilerFlags *c_flags;
+ const char *c_filename;
+ struct symtable *c_st;
+ PyFutureFeatures *c_future; /* pointer to module's __future__ */
+ PyCompilerFlags *c_flags;
- int c_interactive; /* true if in interactive mode */
- int c_nestlevel;
+ int c_interactive; /* true if in interactive mode */
+ int c_nestlevel;
- struct compiler_unit *u; /* compiler state for current block */
- PyObject *c_stack; /* Python list holding compiler_unit ptrs */
- PyArena *c_arena; /* pointer to memory allocation arena */
+ struct compiler_unit *u; /* compiler state for current block */
+ PyObject *c_stack; /* Python list holding compiler_unit ptrs */
+ PyArena *c_arena; /* pointer to memory allocation arena */
};
static int compiler_enter_scope(struct compiler *, identifier, void *, int);
@@ -164,12 +164,12 @@ static int compiler_visit_keyword(struct compiler *, keyword_ty);
static int compiler_visit_expr(struct compiler *, expr_ty);
static int compiler_augassign(struct compiler *, stmt_ty);
static int compiler_visit_slice(struct compiler *, slice_ty,
- expr_context_ty);
+ expr_context_ty);
static int compiler_push_fblock(struct compiler *, enum fblocktype,
- basicblock *);
+ basicblock *);
static void compiler_pop_fblock(struct compiler *, enum fblocktype,
- basicblock *);
+ basicblock *);
/* Returns true if there is a loop on the fblock stack. */
static int compiler_in_loop(struct compiler *);
@@ -186,172 +186,172 @@ static PyObject *__doc__;
PyObject *
_Py_Mangle(PyObject *privateobj, PyObject *ident)
{
- /* Name mangling: __private becomes _classname__private.
- This is independent from how the name is used. */
- const char *p, *name = PyString_AsString(ident);
- char *buffer;
- size_t nlen, plen;
- if (privateobj == NULL || !PyString_Check(privateobj) ||
- name == NULL || name[0] != '_' || name[1] != '_') {
- Py_INCREF(ident);
- return ident;
- }
- p = PyString_AsString(privateobj);
- nlen = strlen(name);
- /* Don't mangle __id__ or names with dots.
-
- The only time a name with a dot can occur is when
- we are compiling an import statement that has a
- package name.
-
- TODO(jhylton): Decide whether we want to support
- mangling of the module name, e.g. __M.X.
- */
- if ((name[nlen-1] == '_' && name[nlen-2] == '_')
- || strchr(name, '.')) {
- Py_INCREF(ident);
- return ident; /* Don't mangle __whatever__ */
- }
- /* Strip leading underscores from class name */
- while (*p == '_')
- p++;
- if (*p == '\0') {
- Py_INCREF(ident);
- return ident; /* Don't mangle if class is just underscores */
- }
- plen = strlen(p);
-
- assert(1 <= PY_SSIZE_T_MAX - nlen);
- assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
-
- ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
- if (!ident)
- return 0;
- /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
- buffer = PyString_AS_STRING(ident);
- buffer[0] = '_';
- strncpy(buffer+1, p, plen);
- strcpy(buffer+1+plen, name);
- return ident;
+ /* Name mangling: __private becomes _classname__private.
+ This is independent from how the name is used. */
+ const char *p, *name = PyString_AsString(ident);
+ char *buffer;
+ size_t nlen, plen;
+ if (privateobj == NULL || !PyString_Check(privateobj) ||
+ name == NULL || name[0] != '_' || name[1] != '_') {
+ Py_INCREF(ident);
+ return ident;
+ }
+ p = PyString_AsString(privateobj);
+ nlen = strlen(name);
+ /* Don't mangle __id__ or names with dots.
+
+ The only time a name with a dot can occur is when
+ we are compiling an import statement that has a
+ package name.
+
+ TODO(jhylton): Decide whether we want to support
+ mangling of the module name, e.g. __M.X.
+ */
+ if ((name[nlen-1] == '_' && name[nlen-2] == '_')
+ || strchr(name, '.')) {
+ Py_INCREF(ident);
+ return ident; /* Don't mangle __whatever__ */
+ }
+ /* Strip leading underscores from class name */
+ while (*p == '_')
+ p++;
+ if (*p == '\0') {
+ Py_INCREF(ident);
+ return ident; /* Don't mangle if class is just underscores */
+ }
+ plen = strlen(p);
+
+ assert(1 <= PY_SSIZE_T_MAX - nlen);
+ assert(1 + nlen <= PY_SSIZE_T_MAX - plen);
+
+ ident = PyString_FromStringAndSize(NULL, 1 + nlen + plen);
+ if (!ident)
+ return 0;
+ /* ident = "_" + p[:plen] + name # i.e. 1+plen+nlen bytes */
+ buffer = PyString_AS_STRING(ident);
+ buffer[0] = '_';
+ strncpy(buffer+1, p, plen);
+ strcpy(buffer+1+plen, name);
+ return ident;
}
static int
compiler_init(struct compiler *c)
{
- memset(c, 0, sizeof(struct compiler));
+ memset(c, 0, sizeof(struct compiler));
- c->c_stack = PyList_New(0);
- if (!c->c_stack)
- return 0;
+ c->c_stack = PyList_New(0);
+ if (!c->c_stack)
+ return 0;
- return 1;
+ return 1;
}
PyCodeObject *
PyAST_Compile(mod_ty mod, const char *filename, PyCompilerFlags *flags,
- PyArena *arena)
-{
- struct compiler c;
- PyCodeObject *co = NULL;
- PyCompilerFlags local_flags;
- int merged;
-
- if (!__doc__) {
- __doc__ = PyString_InternFromString("__doc__");
- if (!__doc__)
- return NULL;
- }
-
- if (!compiler_init(&c))
- return NULL;
- c.c_filename = filename;
- c.c_arena = arena;
- c.c_future = PyFuture_FromAST(mod, filename);
- if (c.c_future == NULL)
- goto finally;
- if (!flags) {
- local_flags.cf_flags = 0;
- flags = &local_flags;
- }
- merged = c.c_future->ff_features | flags->cf_flags;
- c.c_future->ff_features = merged;
- flags->cf_flags = merged;
- c.c_flags = flags;
- c.c_nestlevel = 0;
-
- c.c_st = PySymtable_Build(mod, filename, c.c_future);
- if (c.c_st == NULL) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_SystemError, "no symtable");
- goto finally;
- }
-
- co = compiler_mod(&c, mod);
+ PyArena *arena)
+{
+ struct compiler c;
+ PyCodeObject *co = NULL;
+ PyCompilerFlags local_flags;
+ int merged;
+
+ if (!__doc__) {
+ __doc__ = PyString_InternFromString("__doc__");
+ if (!__doc__)
+ return NULL;
+ }
+
+ if (!compiler_init(&c))
+ return NULL;
+ c.c_filename = filename;
+ c.c_arena = arena;
+ c.c_future = PyFuture_FromAST(mod, filename);
+ if (c.c_future == NULL)
+ goto finally;
+ if (!flags) {
+ local_flags.cf_flags = 0;
+ flags = &local_flags;
+ }
+ merged = c.c_future->ff_features | flags->cf_flags;
+ c.c_future->ff_features = merged;
+ flags->cf_flags = merged;
+ c.c_flags = flags;
+ c.c_nestlevel = 0;
+
+ c.c_st = PySymtable_Build(mod, filename, c.c_future);
+ if (c.c_st == NULL) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_SystemError, "no symtable");
+ goto finally;
+ }
+
+ co = compiler_mod(&c, mod);
finally:
- compiler_free(&c);
- assert(co || PyErr_Occurred());
- return co;
+ compiler_free(&c);
+ assert(co || PyErr_Occurred());
+ return co;
}
PyCodeObject *
PyNode_Compile(struct _node *n, const char *filename)
{
- PyCodeObject *co = NULL;
- mod_ty mod;
- PyArena *arena = PyArena_New();
- if (!arena)
- return NULL;
- mod = PyAST_FromNode(n, NULL, filename, arena);
- if (mod)
- co = PyAST_Compile(mod, filename, NULL, arena);
- PyArena_Free(arena);
- return co;
+ PyCodeObject *co = NULL;
+ mod_ty mod;
+ PyArena *arena = PyArena_New();
+ if (!arena)
+ return NULL;
+ mod = PyAST_FromNode(n, NULL, filename, arena);
+ if (mod)
+ co = PyAST_Compile(mod, filename, NULL, arena);
+ PyArena_Free(arena);
+ return co;
}
static void
compiler_free(struct compiler *c)
{
- if (c->c_st)
- PySymtable_Free(c->c_st);
- if (c->c_future)
- PyObject_Free(c->c_future);
- Py_DECREF(c->c_stack);
+ if (c->c_st)
+ PySymtable_Free(c->c_st);
+ if (c->c_future)
+ PyObject_Free(c->c_future);
+ Py_DECREF(c->c_stack);
}
static PyObject *
list2dict(PyObject *list)
{
- Py_ssize_t i, n;
- PyObject *v, *k;
- PyObject *dict = PyDict_New();
- if (!dict) return NULL;
-
- n = PyList_Size(list);
- for (i = 0; i < n; i++) {
- v = PyInt_FromLong(i);
- if (!v) {
- Py_DECREF(dict);
- return NULL;
- }
- k = PyList_GET_ITEM(list, i);
- k = PyTuple_Pack(2, k, k->ob_type);
- if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
- Py_XDECREF(k);
- Py_DECREF(v);
- Py_DECREF(dict);
- return NULL;
- }
- Py_DECREF(k);
- Py_DECREF(v);
- }
- return dict;
+ Py_ssize_t i, n;
+ PyObject *v, *k;
+ PyObject *dict = PyDict_New();
+ if (!dict) return NULL;
+
+ n = PyList_Size(list);
+ for (i = 0; i < n; i++) {
+ v = PyInt_FromLong(i);
+ if (!v) {
+ Py_DECREF(dict);
+ return NULL;
+ }
+ k = PyList_GET_ITEM(list, i);
+ k = PyTuple_Pack(2, k, k->ob_type);
+ if (k == NULL || PyDict_SetItem(dict, k, v) < 0) {
+ Py_XDECREF(k);
+ Py_DECREF(v);
+ Py_DECREF(dict);
+ return NULL;
+ }
+ Py_DECREF(k);
+ Py_DECREF(v);
+ }
+ return dict;
}
/* Return new dict containing names from src that match scope(s).
src is a symbol table dictionary. If the scope of a name matches
-either scope_type or flag is set, insert it into the new dict. The
+either scope_type or flag is set, insert it into the new dict. The
values are integers, starting at offset and increasing by one for
each key.
*/
@@ -359,179 +359,179 @@ each key.
static PyObject *
dictbytype(PyObject *src, int scope_type, int flag, int offset)
{
- Py_ssize_t pos = 0, i = offset, scope;
- PyObject *k, *v, *dest = PyDict_New();
-
- assert(offset >= 0);
- if (dest == NULL)
- return NULL;
-
- while (PyDict_Next(src, &pos, &k, &v)) {
- /* XXX this should probably be a macro in symtable.h */
- assert(PyInt_Check(v));
- scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
-
- if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
- PyObject *tuple, *item = PyInt_FromLong(i);
- if (item == NULL) {
- Py_DECREF(dest);
- return NULL;
- }
- i++;
- tuple = PyTuple_Pack(2, k, k->ob_type);
- if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
- Py_DECREF(item);
- Py_DECREF(dest);
- Py_XDECREF(tuple);
- return NULL;
- }
- Py_DECREF(item);
- Py_DECREF(tuple);
- }
- }
- return dest;
+ Py_ssize_t pos = 0, i = offset, scope;
+ PyObject *k, *v, *dest = PyDict_New();
+
+ assert(offset >= 0);
+ if (dest == NULL)
+ return NULL;
+
+ while (PyDict_Next(src, &pos, &k, &v)) {
+ /* XXX this should probably be a macro in symtable.h */
+ assert(PyInt_Check(v));
+ scope = (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
+
+ if (scope == scope_type || PyInt_AS_LONG(v) & flag) {
+ PyObject *tuple, *item = PyInt_FromLong(i);
+ if (item == NULL) {
+ Py_DECREF(dest);
+ return NULL;
+ }
+ i++;
+ tuple = PyTuple_Pack(2, k, k->ob_type);
+ if (!tuple || PyDict_SetItem(dest, tuple, item) < 0) {
+ Py_DECREF(item);
+ Py_DECREF(dest);
+ Py_XDECREF(tuple);
+ return NULL;
+ }
+ Py_DECREF(item);
+ Py_DECREF(tuple);
+ }
+ }
+ return dest;
}
static void
compiler_unit_check(struct compiler_unit *u)
{
- basicblock *block;
- for (block = u->u_blocks; block != NULL; block = block->b_list) {
- assert((void *)block != (void *)0xcbcbcbcb);
- assert((void *)block != (void *)0xfbfbfbfb);
- assert((void *)block != (void *)0xdbdbdbdb);
- if (block->b_instr != NULL) {
- assert(block->b_ialloc > 0);
- assert(block->b_iused > 0);
- assert(block->b_ialloc >= block->b_iused);
- }
- else {
- assert (block->b_iused == 0);
- assert (block->b_ialloc == 0);
- }
- }
+ basicblock *block;
+ for (block = u->u_blocks; block != NULL; block = block->b_list) {
+ assert((void *)block != (void *)0xcbcbcbcb);
+ assert((void *)block != (void *)0xfbfbfbfb);
+ assert((void *)block != (void *)0xdbdbdbdb);
+ if (block->b_instr != NULL) {
+ assert(block->b_ialloc > 0);
+ assert(block->b_iused > 0);
+ assert(block->b_ialloc >= block->b_iused);
+ }
+ else {
+ assert (block->b_iused == 0);
+ assert (block->b_ialloc == 0);
+ }
+ }
}
static void
compiler_unit_free(struct compiler_unit *u)
{
- basicblock *b, *next;
-
- compiler_unit_check(u);
- b = u->u_blocks;
- while (b != NULL) {
- if (b->b_instr)
- PyObject_Free((void *)b->b_instr);
- next = b->b_list;
- PyObject_Free((void *)b);
- b = next;
- }
- Py_CLEAR(u->u_ste);
- Py_CLEAR(u->u_name);
- Py_CLEAR(u->u_consts);
- Py_CLEAR(u->u_names);
- Py_CLEAR(u->u_varnames);
- Py_CLEAR(u->u_freevars);
- Py_CLEAR(u->u_cellvars);
- Py_CLEAR(u->u_private);
- PyObject_Free(u);
+ basicblock *b, *next;
+
+ compiler_unit_check(u);
+ b = u->u_blocks;
+ while (b != NULL) {
+ if (b->b_instr)
+ PyObject_Free((void *)b->b_instr);
+ next = b->b_list;
+ PyObject_Free((void *)b);
+ b = next;
+ }
+ Py_CLEAR(u->u_ste);
+ Py_CLEAR(u->u_name);
+ Py_CLEAR(u->u_consts);
+ Py_CLEAR(u->u_names);
+ Py_CLEAR(u->u_varnames);
+ Py_CLEAR(u->u_freevars);
+ Py_CLEAR(u->u_cellvars);
+ Py_CLEAR(u->u_private);
+ PyObject_Free(u);
}
static int
compiler_enter_scope(struct compiler *c, identifier name, void *key,
- int lineno)
-{
- struct compiler_unit *u;
-
- u = (struct compiler_unit *)PyObject_Malloc(sizeof(
- struct compiler_unit));
- if (!u) {
- PyErr_NoMemory();
- return 0;
- }
- memset(u, 0, sizeof(struct compiler_unit));
- u->u_argcount = 0;
- u->u_ste = PySymtable_Lookup(c->c_st, key);
- if (!u->u_ste) {
- compiler_unit_free(u);
- return 0;
- }
- Py_INCREF(name);
- u->u_name = name;
- u->u_varnames = list2dict(u->u_ste->ste_varnames);
- u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
- if (!u->u_varnames || !u->u_cellvars) {
- compiler_unit_free(u);
- return 0;
- }
-
- u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
- PyDict_Size(u->u_cellvars));
- if (!u->u_freevars) {
- compiler_unit_free(u);
- return 0;
- }
-
- u->u_blocks = NULL;
- u->u_nfblocks = 0;
- u->u_firstlineno = lineno;
- u->u_lineno = 0;
- u->u_lineno_set = false;
- u->u_consts = PyDict_New();
- if (!u->u_consts) {
- compiler_unit_free(u);
- return 0;
- }
- u->u_names = PyDict_New();
- if (!u->u_names) {
- compiler_unit_free(u);
- return 0;
- }
-
- u->u_private = NULL;
-
- /* Push the old compiler_unit on the stack. */
- if (c->u) {
- PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
- if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
- Py_XDECREF(capsule);
- compiler_unit_free(u);
- return 0;
- }
- Py_DECREF(capsule);
- u->u_private = c->u->u_private;
- Py_XINCREF(u->u_private);
- }
- c->u = u;
-
- c->c_nestlevel++;
- if (compiler_use_new_block(c) == NULL)
- return 0;
-
- return 1;
+ int lineno)
+{
+ struct compiler_unit *u;
+
+ u = (struct compiler_unit *)PyObject_Malloc(sizeof(
+ struct compiler_unit));
+ if (!u) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ memset(u, 0, sizeof(struct compiler_unit));
+ u->u_argcount = 0;
+ u->u_ste = PySymtable_Lookup(c->c_st, key);
+ if (!u->u_ste) {
+ compiler_unit_free(u);
+ return 0;
+ }
+ Py_INCREF(name);
+ u->u_name = name;
+ u->u_varnames = list2dict(u->u_ste->ste_varnames);
+ u->u_cellvars = dictbytype(u->u_ste->ste_symbols, CELL, 0, 0);
+ if (!u->u_varnames || !u->u_cellvars) {
+ compiler_unit_free(u);
+ return 0;
+ }
+
+ u->u_freevars = dictbytype(u->u_ste->ste_symbols, FREE, DEF_FREE_CLASS,
+ PyDict_Size(u->u_cellvars));
+ if (!u->u_freevars) {
+ compiler_unit_free(u);
+ return 0;
+ }
+
+ u->u_blocks = NULL;
+ u->u_nfblocks = 0;
+ u->u_firstlineno = lineno;
+ u->u_lineno = 0;
+ u->u_lineno_set = false;
+ u->u_consts = PyDict_New();
+ if (!u->u_consts) {
+ compiler_unit_free(u);
+ return 0;
+ }
+ u->u_names = PyDict_New();
+ if (!u->u_names) {
+ compiler_unit_free(u);
+ return 0;
+ }
+
+ u->u_private = NULL;
+
+ /* Push the old compiler_unit on the stack. */
+ if (c->u) {
+ PyObject *capsule = PyCapsule_New(c->u, COMPILER_CAPSULE_NAME_COMPILER_UNIT, NULL);
+ if (!capsule || PyList_Append(c->c_stack, capsule) < 0) {
+ Py_XDECREF(capsule);
+ compiler_unit_free(u);
+ return 0;
+ }
+ Py_DECREF(capsule);
+ u->u_private = c->u->u_private;
+ Py_XINCREF(u->u_private);
+ }
+ c->u = u;
+
+ c->c_nestlevel++;
+ if (compiler_use_new_block(c) == NULL)
+ return 0;
+
+ return 1;
}
static void
compiler_exit_scope(struct compiler *c)
{
- int n;
- PyObject *capsule;
-
- c->c_nestlevel--;
- compiler_unit_free(c->u);
- /* Restore c->u to the parent unit. */
- n = PyList_GET_SIZE(c->c_stack) - 1;
- if (n >= 0) {
- capsule = PyList_GET_ITEM(c->c_stack, n);
- c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
- assert(c->u);
- /* we are deleting from a list so this really shouldn't fail */
- if (PySequence_DelItem(c->c_stack, n) < 0)
- Py_FatalError("compiler_exit_scope()");
- compiler_unit_check(c->u);
- }
- else
- c->u = NULL;
+ int n;
+ PyObject *capsule;
+
+ c->c_nestlevel--;
+ compiler_unit_free(c->u);
+ /* Restore c->u to the parent unit. */
+ n = PyList_GET_SIZE(c->c_stack) - 1;
+ if (n >= 0) {
+ capsule = PyList_GET_ITEM(c->c_stack, n);
+ c->u = (struct compiler_unit *)PyCapsule_GetPointer(capsule, COMPILER_CAPSULE_NAME_COMPILER_UNIT);
+ assert(c->u);
+ /* we are deleting from a list so this really shouldn't fail */
+ if (PySequence_DelItem(c->c_stack, n) < 0)
+ Py_FatalError("compiler_exit_scope()");
+ compiler_unit_check(c->u);
+ }
+ else
+ c->u = NULL;
}
@@ -542,50 +542,50 @@ compiler_exit_scope(struct compiler *c)
static basicblock *
compiler_new_block(struct compiler *c)
{
- basicblock *b;
- struct compiler_unit *u;
+ basicblock *b;
+ struct compiler_unit *u;
- u = c->u;
- b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
- if (b == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- memset((void *)b, 0, sizeof(basicblock));
- /* Extend the singly linked list of blocks with new block. */
- b->b_list = u->u_blocks;
- u->u_blocks = b;
- return b;
+ u = c->u;
+ b = (basicblock *)PyObject_Malloc(sizeof(basicblock));
+ if (b == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset((void *)b, 0, sizeof(basicblock));
+ /* Extend the singly linked list of blocks with new block. */
+ b->b_list = u->u_blocks;
+ u->u_blocks = b;
+ return b;
}
static basicblock *
compiler_use_new_block(struct compiler *c)
{
- basicblock *block = compiler_new_block(c);
- if (block == NULL)
- return NULL;
- c->u->u_curblock = block;
- return block;
+ basicblock *block = compiler_new_block(c);
+ if (block == NULL)
+ return NULL;
+ c->u->u_curblock = block;
+ return block;
}
static basicblock *
compiler_next_block(struct compiler *c)
{
- basicblock *block = compiler_new_block(c);
- if (block == NULL)
- return NULL;
- c->u->u_curblock->b_next = block;
- c->u->u_curblock = block;
- return block;
+ basicblock *block = compiler_new_block(c);
+ if (block == NULL)
+ return NULL;
+ c->u->u_curblock->b_next = block;
+ c->u->u_curblock = block;
+ return block;
}
static basicblock *
compiler_use_next_block(struct compiler *c, basicblock *block)
{
- assert(block != NULL);
- c->u->u_curblock->b_next = block;
- c->u->u_curblock = block;
- return block;
+ assert(block != NULL);
+ c->u->u_curblock->b_next = block;
+ c->u->u_curblock = block;
+ return block;
}
/* Returns the offset of the next instruction in the current block's
@@ -596,44 +596,44 @@ compiler_use_next_block(struct compiler *c, basicblock *block)
static int
compiler_next_instr(struct compiler *c, basicblock *b)
{
- assert(b != NULL);
- if (b->b_instr == NULL) {
- b->b_instr = (struct instr *)PyObject_Malloc(
- sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
- if (b->b_instr == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- b->b_ialloc = DEFAULT_BLOCK_SIZE;
- memset((char *)b->b_instr, 0,
- sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
- }
- else if (b->b_iused == b->b_ialloc) {
- struct instr *tmp;
- size_t oldsize, newsize;
- oldsize = b->b_ialloc * sizeof(struct instr);
- newsize = oldsize << 1;
-
- if (oldsize > (PY_SIZE_MAX >> 1)) {
- PyErr_NoMemory();
- return -1;
- }
-
- if (newsize == 0) {
- PyErr_NoMemory();
- return -1;
- }
- b->b_ialloc <<= 1;
- tmp = (struct instr *)PyObject_Realloc(
- (void *)b->b_instr, newsize);
- if (tmp == NULL) {
- PyErr_NoMemory();
- return -1;
- }
- b->b_instr = tmp;
- memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
- }
- return b->b_iused++;
+ assert(b != NULL);
+ if (b->b_instr == NULL) {
+ b->b_instr = (struct instr *)PyObject_Malloc(
+ sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
+ if (b->b_instr == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ b->b_ialloc = DEFAULT_BLOCK_SIZE;
+ memset((char *)b->b_instr, 0,
+ sizeof(struct instr) * DEFAULT_BLOCK_SIZE);
+ }
+ else if (b->b_iused == b->b_ialloc) {
+ struct instr *tmp;
+ size_t oldsize, newsize;
+ oldsize = b->b_ialloc * sizeof(struct instr);
+ newsize = oldsize << 1;
+
+ if (oldsize > (PY_SIZE_MAX >> 1)) {
+ PyErr_NoMemory();
+ return -1;
+ }
+
+ if (newsize == 0) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ b->b_ialloc <<= 1;
+ tmp = (struct instr *)PyObject_Realloc(
+ (void *)b->b_instr, newsize);
+ if (tmp == NULL) {
+ PyErr_NoMemory();
+ return -1;
+ }
+ b->b_instr = tmp;
+ memset((char *)b->b_instr + oldsize, 0, newsize - oldsize);
+ }
+ return b->b_iused++;
}
/* Set the i_lineno member of the instruction at offset off if the
@@ -651,246 +651,246 @@ compiler_next_instr(struct compiler *c, basicblock *b)
static void
compiler_set_lineno(struct compiler *c, int off)
{
- basicblock *b;
- if (c->u->u_lineno_set)
- return;
- c->u->u_lineno_set = true;
- b = c->u->u_curblock;
- b->b_instr[off].i_lineno = c->u->u_lineno;
+ basicblock *b;
+ if (c->u->u_lineno_set)
+ return;
+ c->u->u_lineno_set = true;
+ b = c->u->u_curblock;
+ b->b_instr[off].i_lineno = c->u->u_lineno;
}
static int
opcode_stack_effect(int opcode, int oparg)
{
- switch (opcode) {
- case POP_TOP:
- return -1;
- case ROT_TWO:
- case ROT_THREE:
- return 0;
- case DUP_TOP:
- return 1;
- case ROT_FOUR:
- return 0;
-
- case UNARY_POSITIVE:
- case UNARY_NEGATIVE:
- case UNARY_NOT:
- case UNARY_CONVERT:
- case UNARY_INVERT:
- return 0;
-
- case SET_ADD:
- case LIST_APPEND:
- return -1;
-
- case MAP_ADD:
- return -2;
-
- case BINARY_POWER:
- case BINARY_MULTIPLY:
- case BINARY_DIVIDE:
- case BINARY_MODULO:
- case BINARY_ADD:
- case BINARY_SUBTRACT:
- case BINARY_SUBSCR:
- case BINARY_FLOOR_DIVIDE:
- case BINARY_TRUE_DIVIDE:
- return -1;
- case INPLACE_FLOOR_DIVIDE:
- case INPLACE_TRUE_DIVIDE:
- return -1;
-
- case SLICE+0:
- return 0;
- case SLICE+1:
- return -1;
- case SLICE+2:
- return -1;
- case SLICE+3:
- return -2;
-
- case STORE_SLICE+0:
- return -2;
- case STORE_SLICE+1:
- return -3;
- case STORE_SLICE+2:
- return -3;
- case STORE_SLICE+3:
- return -4;
-
- case DELETE_SLICE+0:
- return -1;
- case DELETE_SLICE+1:
- return -2;
- case DELETE_SLICE+2:
- return -2;
- case DELETE_SLICE+3:
- return -3;
-
- case INPLACE_ADD:
- case INPLACE_SUBTRACT:
- case INPLACE_MULTIPLY:
- case INPLACE_DIVIDE:
- case INPLACE_MODULO:
- return -1;
- case STORE_SUBSCR:
- return -3;
- case STORE_MAP:
- return -2;
- case DELETE_SUBSCR:
- return -2;
-
- case BINARY_LSHIFT:
- case BINARY_RSHIFT:
- case BINARY_AND:
- case BINARY_XOR:
- case BINARY_OR:
- return -1;
- case INPLACE_POWER:
- return -1;
- case GET_ITER:
- return 0;
-
- case PRINT_EXPR:
- return -1;
- case PRINT_ITEM:
- return -1;
- case PRINT_NEWLINE:
- return 0;
- case PRINT_ITEM_TO:
- return -2;
- case PRINT_NEWLINE_TO:
- return -1;
- case INPLACE_LSHIFT:
- case INPLACE_RSHIFT:
- case INPLACE_AND:
- case INPLACE_XOR:
- case INPLACE_OR:
- return -1;
- case BREAK_LOOP:
- return 0;
- case SETUP_WITH:
- return 4;
- case WITH_CLEANUP:
- return -1; /* XXX Sometimes more */
- case LOAD_LOCALS:
- return 1;
- case RETURN_VALUE:
- return -1;
- case IMPORT_STAR:
- return -1;
- case EXEC_STMT:
- return -3;
- case YIELD_VALUE:
- return 0;
-
- case POP_BLOCK:
- return 0;
- case END_FINALLY:
- return -3; /* or -1 or -2 if no exception occurred or
- return/break/continue */
- case BUILD_CLASS:
- return -2;
-
- case STORE_NAME:
- return -1;
- case DELETE_NAME:
- return 0;
- case UNPACK_SEQUENCE:
- return oparg-1;
- case FOR_ITER:
- return 1; /* or -1, at end of iterator */
-
- case STORE_ATTR:
- return -2;
- case DELETE_ATTR:
- return -1;
- case STORE_GLOBAL:
- return -1;
- case DELETE_GLOBAL:
- return 0;
- case DUP_TOPX:
- return oparg;
- case LOAD_CONST:
- return 1;
- case LOAD_NAME:
- return 1;
- case BUILD_TUPLE:
- case BUILD_LIST:
- case BUILD_SET:
- return 1-oparg;
- case BUILD_MAP:
- return 1;
- case LOAD_ATTR:
- return 0;
- case COMPARE_OP:
- return -1;
- case IMPORT_NAME:
- return -1;
- case IMPORT_FROM:
- return 1;
-
- case JUMP_FORWARD:
- case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
- case JUMP_IF_FALSE_OR_POP: /* "" */
- case JUMP_ABSOLUTE:
- return 0;
-
- case POP_JUMP_IF_FALSE:
- case POP_JUMP_IF_TRUE:
- return -1;
-
- case LOAD_GLOBAL:
- return 1;
-
- case CONTINUE_LOOP:
- return 0;
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- return 0;
-
- case LOAD_FAST:
- return 1;
- case STORE_FAST:
- return -1;
- case DELETE_FAST:
- return 0;
-
- case RAISE_VARARGS:
- return -oparg;
+ switch (opcode) {
+ case POP_TOP:
+ return -1;
+ case ROT_TWO:
+ case ROT_THREE:
+ return 0;
+ case DUP_TOP:
+ return 1;
+ case ROT_FOUR:
+ return 0;
+
+ case UNARY_POSITIVE:
+ case UNARY_NEGATIVE:
+ case UNARY_NOT:
+ case UNARY_CONVERT:
+ case UNARY_INVERT:
+ return 0;
+
+ case SET_ADD:
+ case LIST_APPEND:
+ return -1;
+
+ case MAP_ADD:
+ return -2;
+
+ case BINARY_POWER:
+ case BINARY_MULTIPLY:
+ case BINARY_DIVIDE:
+ case BINARY_MODULO:
+ case BINARY_ADD:
+ case BINARY_SUBTRACT:
+ case BINARY_SUBSCR:
+ case BINARY_FLOOR_DIVIDE:
+ case BINARY_TRUE_DIVIDE:
+ return -1;
+ case INPLACE_FLOOR_DIVIDE:
+ case INPLACE_TRUE_DIVIDE:
+ return -1;
+
+ case SLICE+0:
+ return 0;
+ case SLICE+1:
+ return -1;
+ case SLICE+2:
+ return -1;
+ case SLICE+3:
+ return -2;
+
+ case STORE_SLICE+0:
+ return -2;
+ case STORE_SLICE+1:
+ return -3;
+ case STORE_SLICE+2:
+ return -3;
+ case STORE_SLICE+3:
+ return -4;
+
+ case DELETE_SLICE+0:
+ return -1;
+ case DELETE_SLICE+1:
+ return -2;
+ case DELETE_SLICE+2:
+ return -2;
+ case DELETE_SLICE+3:
+ return -3;
+
+ case INPLACE_ADD:
+ case INPLACE_SUBTRACT:
+ case INPLACE_MULTIPLY:
+ case INPLACE_DIVIDE:
+ case INPLACE_MODULO:
+ return -1;
+ case STORE_SUBSCR:
+ return -3;
+ case STORE_MAP:
+ return -2;
+ case DELETE_SUBSCR:
+ return -2;
+
+ case BINARY_LSHIFT:
+ case BINARY_RSHIFT:
+ case BINARY_AND:
+ case BINARY_XOR:
+ case BINARY_OR:
+ return -1;
+ case INPLACE_POWER:
+ return -1;
+ case GET_ITER:
+ return 0;
+
+ case PRINT_EXPR:
+ return -1;
+ case PRINT_ITEM:
+ return -1;
+ case PRINT_NEWLINE:
+ return 0;
+ case PRINT_ITEM_TO:
+ return -2;
+ case PRINT_NEWLINE_TO:
+ return -1;
+ case INPLACE_LSHIFT:
+ case INPLACE_RSHIFT:
+ case INPLACE_AND:
+ case INPLACE_XOR:
+ case INPLACE_OR:
+ return -1;
+ case BREAK_LOOP:
+ return 0;
+ case SETUP_WITH:
+ return 4;
+ case WITH_CLEANUP:
+ return -1; /* XXX Sometimes more */
+ case LOAD_LOCALS:
+ return 1;
+ case RETURN_VALUE:
+ return -1;
+ case IMPORT_STAR:
+ return -1;
+ case EXEC_STMT:
+ return -3;
+ case YIELD_VALUE:
+ return 0;
+
+ case POP_BLOCK:
+ return 0;
+ case END_FINALLY:
+ return -3; /* or -1 or -2 if no exception occurred or
+ return/break/continue */
+ case BUILD_CLASS:
+ return -2;
+
+ case STORE_NAME:
+ return -1;
+ case DELETE_NAME:
+ return 0;
+ case UNPACK_SEQUENCE:
+ return oparg-1;
+ case FOR_ITER:
+ return 1; /* or -1, at end of iterator */
+
+ case STORE_ATTR:
+ return -2;
+ case DELETE_ATTR:
+ return -1;
+ case STORE_GLOBAL:
+ return -1;
+ case DELETE_GLOBAL:
+ return 0;
+ case DUP_TOPX:
+ return oparg;
+ case LOAD_CONST:
+ return 1;
+ case LOAD_NAME:
+ return 1;
+ case BUILD_TUPLE:
+ case BUILD_LIST:
+ case BUILD_SET:
+ return 1-oparg;
+ case BUILD_MAP:
+ return 1;
+ case LOAD_ATTR:
+ return 0;
+ case COMPARE_OP:
+ return -1;
+ case IMPORT_NAME:
+ return -1;
+ case IMPORT_FROM:
+ return 1;
+
+ case JUMP_FORWARD:
+ case JUMP_IF_TRUE_OR_POP: /* -1 if jump not taken */
+ case JUMP_IF_FALSE_OR_POP: /* "" */
+ case JUMP_ABSOLUTE:
+ return 0;
+
+ case POP_JUMP_IF_FALSE:
+ case POP_JUMP_IF_TRUE:
+ return -1;
+
+ case LOAD_GLOBAL:
+ return 1;
+
+ case CONTINUE_LOOP:
+ return 0;
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ return 0;
+
+ case LOAD_FAST:
+ return 1;
+ case STORE_FAST:
+ return -1;
+ case DELETE_FAST:
+ return 0;
+
+ case RAISE_VARARGS:
+ return -oparg;
#define NARGS(o) (((o) % 256) + 2*((o) / 256))
- case CALL_FUNCTION:
- return -NARGS(oparg);
- case CALL_FUNCTION_VAR:
- case CALL_FUNCTION_KW:
- return -NARGS(oparg)-1;
- case CALL_FUNCTION_VAR_KW:
- return -NARGS(oparg)-2;
+ case CALL_FUNCTION:
+ return -NARGS(oparg);
+ case CALL_FUNCTION_VAR:
+ case CALL_FUNCTION_KW:
+ return -NARGS(oparg)-1;
+ case CALL_FUNCTION_VAR_KW:
+ return -NARGS(oparg)-2;
#undef NARGS
- case MAKE_FUNCTION:
- return -oparg;
- case BUILD_SLICE:
- if (oparg == 3)
- return -2;
- else
- return -1;
-
- case MAKE_CLOSURE:
- return -oparg-1;
- case LOAD_CLOSURE:
- return 1;
- case LOAD_DEREF:
- return 1;
- case STORE_DEREF:
- return -1;
- default:
- fprintf(stderr, "opcode = %d\n", opcode);
- Py_FatalError("opcode_stack_effect()");
-
- }
- return 0; /* not reachable */
+ case MAKE_FUNCTION:
+ return -oparg;
+ case BUILD_SLICE:
+ if (oparg == 3)
+ return -2;
+ else
+ return -1;
+
+ case MAKE_CLOSURE:
+ return -oparg-1;
+ case LOAD_CLOSURE:
+ return 1;
+ case LOAD_DEREF:
+ return 1;
+ case STORE_DEREF:
+ return -1;
+ default:
+ fprintf(stderr, "opcode = %d\n", opcode);
+ Py_FatalError("opcode_stack_effect()");
+
+ }
+ return 0; /* not reachable */
}
/* Add an opcode with no argument.
@@ -900,116 +900,116 @@ opcode_stack_effect(int opcode, int oparg)
static int
compiler_addop(struct compiler *c, int opcode)
{
- basicblock *b;
- struct instr *i;
- int off;
- off = compiler_next_instr(c, c->u->u_curblock);
- if (off < 0)
- return 0;
- b = c->u->u_curblock;
- i = &b->b_instr[off];
- i->i_opcode = opcode;
- i->i_hasarg = 0;
- if (opcode == RETURN_VALUE)
- b->b_return = 1;
- compiler_set_lineno(c, off);
- return 1;
+ basicblock *b;
+ struct instr *i;
+ int off;
+ off = compiler_next_instr(c, c->u->u_curblock);
+ if (off < 0)
+ return 0;
+ b = c->u->u_curblock;
+ i = &b->b_instr[off];
+ i->i_opcode = opcode;
+ i->i_hasarg = 0;
+ if (opcode == RETURN_VALUE)
+ b->b_return = 1;
+ compiler_set_lineno(c, off);
+ return 1;
}
static int
compiler_add_o(struct compiler *c, PyObject *dict, PyObject *o)
{
- PyObject *t, *v;
- Py_ssize_t arg;
- double d;
-
- /* necessary to make sure types aren't coerced (e.g., int and long) */
- /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
- if (PyFloat_Check(o)) {
- d = PyFloat_AS_DOUBLE(o);
- /* all we need is to make the tuple different in either the 0.0
- * or -0.0 case from all others, just to avoid the "coercion".
- */
- if (d == 0.0 && copysign(1.0, d) < 0.0)
- t = PyTuple_Pack(3, o, o->ob_type, Py_None);
- else
- t = PyTuple_Pack(2, o, o->ob_type);
- }
+ PyObject *t, *v;
+ Py_ssize_t arg;
+ double d;
+
+ /* necessary to make sure types aren't coerced (e.g., int and long) */
+ /* _and_ to distinguish 0.0 from -0.0 e.g. on IEEE platforms */
+ if (PyFloat_Check(o)) {
+ d = PyFloat_AS_DOUBLE(o);
+ /* all we need is to make the tuple different in either the 0.0
+ * or -0.0 case from all others, just to avoid the "coercion".
+ */
+ if (d == 0.0 && copysign(1.0, d) < 0.0)
+ t = PyTuple_Pack(3, o, o->ob_type, Py_None);
+ else
+ t = PyTuple_Pack(2, o, o->ob_type);
+ }
#ifndef WITHOUT_COMPLEX
- else if (PyComplex_Check(o)) {
- Py_complex z;
- int real_negzero, imag_negzero;
- /* For the complex case we must make complex(x, 0.)
- different from complex(x, -0.) and complex(0., y)
- different from complex(-0., y), for any x and y.
- All four complex zeros must be distinguished.*/
- z = PyComplex_AsCComplex(o);
- real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
- imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
- if (real_negzero && imag_negzero) {
- t = PyTuple_Pack(5, o, o->ob_type,
- Py_None, Py_None, Py_None);
- }
- else if (imag_negzero) {
- t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
- }
- else if (real_negzero) {
- t = PyTuple_Pack(3, o, o->ob_type, Py_None);
- }
- else {
- t = PyTuple_Pack(2, o, o->ob_type);
- }
+ else if (PyComplex_Check(o)) {
+ Py_complex z;
+ int real_negzero, imag_negzero;
+ /* For the complex case we must make complex(x, 0.)
+ different from complex(x, -0.) and complex(0., y)
+ different from complex(-0., y), for any x and y.
+ All four complex zeros must be distinguished.*/
+ z = PyComplex_AsCComplex(o);
+ real_negzero = z.real == 0.0 && copysign(1.0, z.real) < 0.0;
+ imag_negzero = z.imag == 0.0 && copysign(1.0, z.imag) < 0.0;
+ if (real_negzero && imag_negzero) {
+ t = PyTuple_Pack(5, o, o->ob_type,
+ Py_None, Py_None, Py_None);
}
+ else if (imag_negzero) {
+ t = PyTuple_Pack(4, o, o->ob_type, Py_None, Py_None);
+ }
+ else if (real_negzero) {
+ t = PyTuple_Pack(3, o, o->ob_type, Py_None);
+ }
+ else {
+ t = PyTuple_Pack(2, o, o->ob_type);
+ }
+ }
#endif /* WITHOUT_COMPLEX */
- else {
- t = PyTuple_Pack(2, o, o->ob_type);
- }
- if (t == NULL)
- return -1;
-
- v = PyDict_GetItem(dict, t);
- if (!v) {
- arg = PyDict_Size(dict);
- v = PyInt_FromLong(arg);
- if (!v) {
- Py_DECREF(t);
- return -1;
- }
- if (PyDict_SetItem(dict, t, v) < 0) {
- Py_DECREF(t);
- Py_DECREF(v);
- return -1;
- }
- Py_DECREF(v);
- }
- else
- arg = PyInt_AsLong(v);
- Py_DECREF(t);
- return arg;
+ else {
+ t = PyTuple_Pack(2, o, o->ob_type);
+ }
+ if (t == NULL)
+ return -1;
+
+ v = PyDict_GetItem(dict, t);
+ if (!v) {
+ arg = PyDict_Size(dict);
+ v = PyInt_FromLong(arg);
+ if (!v) {
+ Py_DECREF(t);
+ return -1;
+ }
+ if (PyDict_SetItem(dict, t, v) < 0) {
+ Py_DECREF(t);
+ Py_DECREF(v);
+ return -1;
+ }
+ Py_DECREF(v);
+ }
+ else
+ arg = PyInt_AsLong(v);
+ Py_DECREF(t);
+ return arg;
}
static int
compiler_addop_o(struct compiler *c, int opcode, PyObject *dict,
- PyObject *o)
+ PyObject *o)
{
int arg = compiler_add_o(c, dict, o);
if (arg < 0)
- return 0;
+ return 0;
return compiler_addop_i(c, opcode, arg);
}
static int
compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
- PyObject *o)
+ PyObject *o)
{
int arg;
PyObject *mangled = _Py_Mangle(c->u->u_private, o);
if (!mangled)
- return 0;
+ return 0;
arg = compiler_add_o(c, dict, mangled);
Py_DECREF(mangled);
if (arg < 0)
- return 0;
+ return 0;
return compiler_addop_i(c, opcode, arg);
}
@@ -1020,43 +1020,43 @@ compiler_addop_name(struct compiler *c, int opcode, PyObject *dict,
static int
compiler_addop_i(struct compiler *c, int opcode, int oparg)
{
- struct instr *i;
- int off;
- off = compiler_next_instr(c, c->u->u_curblock);
- if (off < 0)
- return 0;
- i = &c->u->u_curblock->b_instr[off];
- i->i_opcode = opcode;
- i->i_oparg = oparg;
- i->i_hasarg = 1;
- compiler_set_lineno(c, off);
- return 1;
+ struct instr *i;
+ int off;
+ off = compiler_next_instr(c, c->u->u_curblock);
+ if (off < 0)
+ return 0;
+ i = &c->u->u_curblock->b_instr[off];
+ i->i_opcode = opcode;
+ i->i_oparg = oparg;
+ i->i_hasarg = 1;
+ compiler_set_lineno(c, off);
+ return 1;
}
static int
compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
{
- struct instr *i;
- int off;
-
- assert(b != NULL);
- off = compiler_next_instr(c, c->u->u_curblock);
- if (off < 0)
- return 0;
- i = &c->u->u_curblock->b_instr[off];
- i->i_opcode = opcode;
- i->i_target = b;
- i->i_hasarg = 1;
- if (absolute)
- i->i_jabs = 1;
- else
- i->i_jrel = 1;
- compiler_set_lineno(c, off);
- return 1;
-}
-
-/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
- like to find better names.) NEW_BLOCK() creates a new block and sets
+ struct instr *i;
+ int off;
+
+ assert(b != NULL);
+ off = compiler_next_instr(c, c->u->u_curblock);
+ if (off < 0)
+ return 0;
+ i = &c->u->u_curblock->b_instr[off];
+ i->i_opcode = opcode;
+ i->i_target = b;
+ i->i_hasarg = 1;
+ if (absolute)
+ i->i_jabs = 1;
+ else
+ i->i_jrel = 1;
+ compiler_set_lineno(c, off);
+ return 1;
+}
+
+/* The distinction between NEW_BLOCK and NEXT_BLOCK is subtle. (I'd
+ like to find better names.) NEW_BLOCK() creates a new block and sets
it as the current block. NEXT_BLOCK() also creates an implicit jump
from the current block to the new block.
*/
@@ -1067,50 +1067,50 @@ compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
#define NEW_BLOCK(C) { \
- if (compiler_use_new_block((C)) == NULL) \
- return 0; \
+ if (compiler_use_new_block((C)) == NULL) \
+ return 0; \
}
#define NEXT_BLOCK(C) { \
- if (compiler_next_block((C)) == NULL) \
- return 0; \
+ if (compiler_next_block((C)) == NULL) \
+ return 0; \
}
#define ADDOP(C, OP) { \
- if (!compiler_addop((C), (OP))) \
- return 0; \
+ if (!compiler_addop((C), (OP))) \
+ return 0; \
}
#define ADDOP_IN_SCOPE(C, OP) { \
- if (!compiler_addop((C), (OP))) { \
- compiler_exit_scope(c); \
- return 0; \
- } \
+ if (!compiler_addop((C), (OP))) { \
+ compiler_exit_scope(c); \
+ return 0; \
+ } \
}
#define ADDOP_O(C, OP, O, TYPE) { \
- if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
- return 0; \
+ if (!compiler_addop_o((C), (OP), (C)->u->u_ ## TYPE, (O))) \
+ return 0; \
}
#define ADDOP_NAME(C, OP, O, TYPE) { \
- if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
- return 0; \
+ if (!compiler_addop_name((C), (OP), (C)->u->u_ ## TYPE, (O))) \
+ return 0; \
}
#define ADDOP_I(C, OP, O) { \
- if (!compiler_addop_i((C), (OP), (O))) \
- return 0; \
+ if (!compiler_addop_i((C), (OP), (O))) \
+ return 0; \
}
#define ADDOP_JABS(C, OP, O) { \
- if (!compiler_addop_j((C), (OP), (O), 1)) \
- return 0; \
+ if (!compiler_addop_j((C), (OP), (O), 1)) \
+ return 0; \
}
#define ADDOP_JREL(C, OP, O) { \
- if (!compiler_addop_j((C), (OP), (O), 0)) \
- return 0; \
+ if (!compiler_addop_j((C), (OP), (O), 0)) \
+ return 0; \
}
/* VISIT and VISIT_SEQ takes an ASDL type as their second argument. They use
@@ -1118,49 +1118,49 @@ compiler_addop_j(struct compiler *c, int opcode, basicblock *b, int absolute)
*/
#define VISIT(C, TYPE, V) {\
- if (!compiler_visit_ ## TYPE((C), (V))) \
- return 0; \
+ if (!compiler_visit_ ## TYPE((C), (V))) \
+ return 0; \
}
#define VISIT_IN_SCOPE(C, TYPE, V) {\
- if (!compiler_visit_ ## TYPE((C), (V))) { \
- compiler_exit_scope(c); \
- return 0; \
- } \
+ if (!compiler_visit_ ## TYPE((C), (V))) { \
+ compiler_exit_scope(c); \
+ return 0; \
+ } \
}
#define VISIT_SLICE(C, V, CTX) {\
- if (!compiler_visit_slice((C), (V), (CTX))) \
- return 0; \
+ if (!compiler_visit_slice((C), (V), (CTX))) \
+ return 0; \
}
#define VISIT_SEQ(C, TYPE, SEQ) { \
- int _i; \
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \
- for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
- if (!compiler_visit_ ## TYPE((C), elt)) \
- return 0; \
- } \
+ int _i; \
+ asdl_seq *seq = (SEQ); /* avoid variable capture */ \
+ for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
+ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
+ if (!compiler_visit_ ## TYPE((C), elt)) \
+ return 0; \
+ } \
}
#define VISIT_SEQ_IN_SCOPE(C, TYPE, SEQ) { \
- int _i; \
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \
- for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
- if (!compiler_visit_ ## TYPE((C), elt)) { \
- compiler_exit_scope(c); \
- return 0; \
- } \
- } \
+ int _i; \
+ asdl_seq *seq = (SEQ); /* avoid variable capture */ \
+ for (_i = 0; _i < asdl_seq_LEN(seq); _i++) { \
+ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, _i); \
+ if (!compiler_visit_ ## TYPE((C), elt)) { \
+ compiler_exit_scope(c); \
+ return 0; \
+ } \
+ } \
}
static int
compiler_isdocstring(stmt_ty s)
{
if (s->kind != Expr_kind)
- return 0;
+ return 0;
return s->v.Expr.value->kind == Str_kind;
}
@@ -1169,67 +1169,67 @@ compiler_isdocstring(stmt_ty s)
static int
compiler_body(struct compiler *c, asdl_seq *stmts)
{
- int i = 0;
- stmt_ty st;
-
- if (!asdl_seq_LEN(stmts))
- return 1;
- st = (stmt_ty)asdl_seq_GET(stmts, 0);
- if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
- /* don't generate docstrings if -OO */
- i = 1;
- VISIT(c, expr, st->v.Expr.value);
- if (!compiler_nameop(c, __doc__, Store))
- return 0;
- }
- for (; i < asdl_seq_LEN(stmts); i++)
- VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
- return 1;
+ int i = 0;
+ stmt_ty st;
+
+ if (!asdl_seq_LEN(stmts))
+ return 1;
+ st = (stmt_ty)asdl_seq_GET(stmts, 0);
+ if (compiler_isdocstring(st) && Py_OptimizeFlag < 2) {
+ /* don't generate docstrings if -OO */
+ i = 1;
+ VISIT(c, expr, st->v.Expr.value);
+ if (!compiler_nameop(c, __doc__, Store))
+ return 0;
+ }
+ for (; i < asdl_seq_LEN(stmts); i++)
+ VISIT(c, stmt, (stmt_ty)asdl_seq_GET(stmts, i));
+ return 1;
}
static PyCodeObject *
compiler_mod(struct compiler *c, mod_ty mod)
{
- PyCodeObject *co;
- int addNone = 1;
- static PyObject *module;
- if (!module) {
- module = PyString_InternFromString("<module>");
- if (!module)
- return NULL;
- }
- /* Use 0 for firstlineno initially, will fixup in assemble(). */
- if (!compiler_enter_scope(c, module, mod, 0))
- return NULL;
- switch (mod->kind) {
- case Module_kind:
- if (!compiler_body(c, mod->v.Module.body)) {
- compiler_exit_scope(c);
- return 0;
- }
- break;
- case Interactive_kind:
- c->c_interactive = 1;
- VISIT_SEQ_IN_SCOPE(c, stmt,
- mod->v.Interactive.body);
- break;
- case Expression_kind:
- VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
- addNone = 0;
- break;
- case Suite_kind:
- PyErr_SetString(PyExc_SystemError,
- "suite should not be possible");
- return 0;
- default:
- PyErr_Format(PyExc_SystemError,
- "module kind %d should not be possible",
- mod->kind);
- return 0;
- }
- co = assemble(c, addNone);
- compiler_exit_scope(c);
- return co;
+ PyCodeObject *co;
+ int addNone = 1;
+ static PyObject *module;
+ if (!module) {
+ module = PyString_InternFromString("<module>");
+ if (!module)
+ return NULL;
+ }
+ /* Use 0 for firstlineno initially, will fixup in assemble(). */
+ if (!compiler_enter_scope(c, module, mod, 0))
+ return NULL;
+ switch (mod->kind) {
+ case Module_kind:
+ if (!compiler_body(c, mod->v.Module.body)) {
+ compiler_exit_scope(c);
+ return 0;
+ }
+ break;
+ case Interactive_kind:
+ c->c_interactive = 1;
+ VISIT_SEQ_IN_SCOPE(c, stmt,
+ mod->v.Interactive.body);
+ break;
+ case Expression_kind:
+ VISIT_IN_SCOPE(c, expr, mod->v.Expression.body);
+ addNone = 0;
+ break;
+ case Suite_kind:
+ PyErr_SetString(PyExc_SystemError,
+ "suite should not be possible");
+ return 0;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "module kind %d should not be possible",
+ mod->kind);
+ return 0;
+ }
+ co = assemble(c, addNone);
+ compiler_exit_scope(c);
+ return co;
}
/* The test for LOCAL must come before the test for FREE in order to
@@ -1240,24 +1240,24 @@ compiler_mod(struct compiler *c, mod_ty mod)
static int
get_ref_type(struct compiler *c, PyObject *name)
{
- int scope = PyST_GetScope(c->u->u_ste, name);
- if (scope == 0) {
- char buf[350];
- PyOS_snprintf(buf, sizeof(buf),
- "unknown scope for %.100s in %.100s(%s) in %s\n"
- "symbols: %s\nlocals: %s\nglobals: %s",
- PyString_AS_STRING(name),
- PyString_AS_STRING(c->u->u_name),
- PyObject_REPR(c->u->u_ste->ste_id),
- c->c_filename,
- PyObject_REPR(c->u->u_ste->ste_symbols),
- PyObject_REPR(c->u->u_varnames),
- PyObject_REPR(c->u->u_names)
- );
- Py_FatalError(buf);
- }
+ int scope = PyST_GetScope(c->u->u_ste, name);
+ if (scope == 0) {
+ char buf[350];
+ PyOS_snprintf(buf, sizeof(buf),
+ "unknown scope for %.100s in %.100s(%s) in %s\n"
+ "symbols: %s\nlocals: %s\nglobals: %s",
+ PyString_AS_STRING(name),
+ PyString_AS_STRING(c->u->u_name),
+ PyObject_REPR(c->u->u_ste->ste_id),
+ c->c_filename,
+ PyObject_REPR(c->u->u_ste->ste_symbols),
+ PyObject_REPR(c->u->u_varnames),
+ PyObject_REPR(c->u->u_names)
+ );
+ Py_FatalError(buf);
+ }
- return scope;
+ return scope;
}
static int
@@ -1266,505 +1266,505 @@ compiler_lookup_arg(PyObject *dict, PyObject *name)
PyObject *k, *v;
k = PyTuple_Pack(2, name, name->ob_type);
if (k == NULL)
- return -1;
+ return -1;
v = PyDict_GetItem(dict, k);
Py_DECREF(k);
if (v == NULL)
- return -1;
+ return -1;
return PyInt_AS_LONG(v);
}
static int
compiler_make_closure(struct compiler *c, PyCodeObject *co, int args)
{
- int i, free = PyCode_GetNumFree(co);
- if (free == 0) {
- ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
- ADDOP_I(c, MAKE_FUNCTION, args);
- return 1;
- }
- for (i = 0; i < free; ++i) {
- /* Bypass com_addop_varname because it will generate
- LOAD_DEREF but LOAD_CLOSURE is needed.
- */
- PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
- int arg, reftype;
-
- /* Special case: If a class contains a method with a
- free variable that has the same name as a method,
- the name will be considered free *and* local in the
- class. It should be handled by the closure, as
- well as by the normal name loookup logic.
- */
- reftype = get_ref_type(c, name);
- if (reftype == CELL)
- arg = compiler_lookup_arg(c->u->u_cellvars, name);
- else /* (reftype == FREE) */
- arg = compiler_lookup_arg(c->u->u_freevars, name);
- if (arg == -1) {
- printf("lookup %s in %s %d %d\n"
- "freevars of %s: %s\n",
- PyObject_REPR(name),
- PyString_AS_STRING(c->u->u_name),
- reftype, arg,
- PyString_AS_STRING(co->co_name),
- PyObject_REPR(co->co_freevars));
- Py_FatalError("compiler_make_closure()");
- }
- ADDOP_I(c, LOAD_CLOSURE, arg);
- }
- ADDOP_I(c, BUILD_TUPLE, free);
- ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
- ADDOP_I(c, MAKE_CLOSURE, args);
- return 1;
+ int i, free = PyCode_GetNumFree(co);
+ if (free == 0) {
+ ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
+ ADDOP_I(c, MAKE_FUNCTION, args);
+ return 1;
+ }
+ for (i = 0; i < free; ++i) {
+ /* Bypass com_addop_varname because it will generate
+ LOAD_DEREF but LOAD_CLOSURE is needed.
+ */
+ PyObject *name = PyTuple_GET_ITEM(co->co_freevars, i);
+ int arg, reftype;
+
+ /* Special case: If a class contains a method with a
+ free variable that has the same name as a method,
+ the name will be considered free *and* local in the
+ class. It should be handled by the closure, as
+ well as by the normal name loookup logic.
+ */
+ reftype = get_ref_type(c, name);
+ if (reftype == CELL)
+ arg = compiler_lookup_arg(c->u->u_cellvars, name);
+ else /* (reftype == FREE) */
+ arg = compiler_lookup_arg(c->u->u_freevars, name);
+ if (arg == -1) {
+ printf("lookup %s in %s %d %d\n"
+ "freevars of %s: %s\n",
+ PyObject_REPR(name),
+ PyString_AS_STRING(c->u->u_name),
+ reftype, arg,
+ PyString_AS_STRING(co->co_name),
+ PyObject_REPR(co->co_freevars));
+ Py_FatalError("compiler_make_closure()");
+ }
+ ADDOP_I(c, LOAD_CLOSURE, arg);
+ }
+ ADDOP_I(c, BUILD_TUPLE, free);
+ ADDOP_O(c, LOAD_CONST, (PyObject*)co, consts);
+ ADDOP_I(c, MAKE_CLOSURE, args);
+ return 1;
}
static int
compiler_decorators(struct compiler *c, asdl_seq* decos)
{
- int i;
+ int i;
- if (!decos)
- return 1;
+ if (!decos)
+ return 1;
- for (i = 0; i < asdl_seq_LEN(decos); i++) {
- VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
- }
- return 1;
+ for (i = 0; i < asdl_seq_LEN(decos); i++) {
+ VISIT(c, expr, (expr_ty)asdl_seq_GET(decos, i));
+ }
+ return 1;
}
static int
compiler_arguments(struct compiler *c, arguments_ty args)
{
- int i;
- int n = asdl_seq_LEN(args->args);
- /* Correctly handle nested argument lists */
- for (i = 0; i < n; i++) {
- expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
- if (arg->kind == Tuple_kind) {
- PyObject *id = PyString_FromFormat(".%d", i);
- if (id == NULL) {
- return 0;
- }
- if (!compiler_nameop(c, id, Load)) {
- Py_DECREF(id);
- return 0;
- }
- Py_DECREF(id);
- VISIT(c, expr, arg);
- }
- }
- return 1;
+ int i;
+ int n = asdl_seq_LEN(args->args);
+ /* Correctly handle nested argument lists */
+ for (i = 0; i < n; i++) {
+ expr_ty arg = (expr_ty)asdl_seq_GET(args->args, i);
+ if (arg->kind == Tuple_kind) {
+ PyObject *id = PyString_FromFormat(".%d", i);
+ if (id == NULL) {
+ return 0;
+ }
+ if (!compiler_nameop(c, id, Load)) {
+ Py_DECREF(id);
+ return 0;
+ }
+ Py_DECREF(id);
+ VISIT(c, expr, arg);
+ }
+ }
+ return 1;
}
static int
compiler_function(struct compiler *c, stmt_ty s)
{
- PyCodeObject *co;
- PyObject *first_const = Py_None;
- arguments_ty args = s->v.FunctionDef.args;
- asdl_seq* decos = s->v.FunctionDef.decorator_list;
- stmt_ty st;
- int i, n, docstring;
-
- assert(s->kind == FunctionDef_kind);
-
- if (!compiler_decorators(c, decos))
- return 0;
- if (args->defaults)
- VISIT_SEQ(c, expr, args->defaults);
- if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
- s->lineno))
- return 0;
-
- st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
- docstring = compiler_isdocstring(st);
- if (docstring && Py_OptimizeFlag < 2)
- first_const = st->v.Expr.value->v.Str.s;
- if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
- compiler_exit_scope(c);
- return 0;
- }
-
- /* unpack nested arguments */
- compiler_arguments(c, args);
-
- c->u->u_argcount = asdl_seq_LEN(args->args);
- n = asdl_seq_LEN(s->v.FunctionDef.body);
- /* if there was a docstring, we need to skip the first statement */
- for (i = docstring; i < n; i++) {
- st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
- VISIT_IN_SCOPE(c, stmt, st);
- }
- co = assemble(c, 1);
- compiler_exit_scope(c);
- if (co == NULL)
- return 0;
-
- compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
- Py_DECREF(co);
-
- for (i = 0; i < asdl_seq_LEN(decos); i++) {
- ADDOP_I(c, CALL_FUNCTION, 1);
- }
-
- return compiler_nameop(c, s->v.FunctionDef.name, Store);
+ PyCodeObject *co;
+ PyObject *first_const = Py_None;
+ arguments_ty args = s->v.FunctionDef.args;
+ asdl_seq* decos = s->v.FunctionDef.decorator_list;
+ stmt_ty st;
+ int i, n, docstring;
+
+ assert(s->kind == FunctionDef_kind);
+
+ if (!compiler_decorators(c, decos))
+ return 0;
+ if (args->defaults)
+ VISIT_SEQ(c, expr, args->defaults);
+ if (!compiler_enter_scope(c, s->v.FunctionDef.name, (void *)s,
+ s->lineno))
+ return 0;
+
+ st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, 0);
+ docstring = compiler_isdocstring(st);
+ if (docstring && Py_OptimizeFlag < 2)
+ first_const = st->v.Expr.value->v.Str.s;
+ if (compiler_add_o(c, c->u->u_consts, first_const) < 0) {
+ compiler_exit_scope(c);
+ return 0;
+ }
+
+ /* unpack nested arguments */
+ compiler_arguments(c, args);
+
+ c->u->u_argcount = asdl_seq_LEN(args->args);
+ n = asdl_seq_LEN(s->v.FunctionDef.body);
+ /* if there was a docstring, we need to skip the first statement */
+ for (i = docstring; i < n; i++) {
+ st = (stmt_ty)asdl_seq_GET(s->v.FunctionDef.body, i);
+ VISIT_IN_SCOPE(c, stmt, st);
+ }
+ co = assemble(c, 1);
+ compiler_exit_scope(c);
+ if (co == NULL)
+ return 0;
+
+ compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
+ Py_DECREF(co);
+
+ for (i = 0; i < asdl_seq_LEN(decos); i++) {
+ ADDOP_I(c, CALL_FUNCTION, 1);
+ }
+
+ return compiler_nameop(c, s->v.FunctionDef.name, Store);
}
static int
compiler_class(struct compiler *c, stmt_ty s)
{
- int n, i;
- PyCodeObject *co;
- PyObject *str;
- asdl_seq* decos = s->v.ClassDef.decorator_list;
-
- if (!compiler_decorators(c, decos))
- return 0;
-
- /* push class name on stack, needed by BUILD_CLASS */
- ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
- /* push the tuple of base classes on the stack */
- n = asdl_seq_LEN(s->v.ClassDef.bases);
- if (n > 0)
- VISIT_SEQ(c, expr, s->v.ClassDef.bases);
- ADDOP_I(c, BUILD_TUPLE, n);
- if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
- s->lineno))
- return 0;
- Py_XDECREF(c->u->u_private);
- c->u->u_private = s->v.ClassDef.name;
- Py_INCREF(c->u->u_private);
- str = PyString_InternFromString("__name__");
- if (!str || !compiler_nameop(c, str, Load)) {
- Py_XDECREF(str);
- compiler_exit_scope(c);
- return 0;
- }
-
- Py_DECREF(str);
- str = PyString_InternFromString("__module__");
- if (!str || !compiler_nameop(c, str, Store)) {
- Py_XDECREF(str);
- compiler_exit_scope(c);
- return 0;
- }
- Py_DECREF(str);
-
- if (!compiler_body(c, s->v.ClassDef.body)) {
- compiler_exit_scope(c);
- return 0;
- }
-
- ADDOP_IN_SCOPE(c, LOAD_LOCALS);
- ADDOP_IN_SCOPE(c, RETURN_VALUE);
- co = assemble(c, 1);
- compiler_exit_scope(c);
- if (co == NULL)
- return 0;
-
- compiler_make_closure(c, co, 0);
- Py_DECREF(co);
-
- ADDOP_I(c, CALL_FUNCTION, 0);
- ADDOP(c, BUILD_CLASS);
- /* apply decorators */
- for (i = 0; i < asdl_seq_LEN(decos); i++) {
- ADDOP_I(c, CALL_FUNCTION, 1);
- }
- if (!compiler_nameop(c, s->v.ClassDef.name, Store))
- return 0;
- return 1;
+ int n, i;
+ PyCodeObject *co;
+ PyObject *str;
+ asdl_seq* decos = s->v.ClassDef.decorator_list;
+
+ if (!compiler_decorators(c, decos))
+ return 0;
+
+ /* push class name on stack, needed by BUILD_CLASS */
+ ADDOP_O(c, LOAD_CONST, s->v.ClassDef.name, consts);
+ /* push the tuple of base classes on the stack */
+ n = asdl_seq_LEN(s->v.ClassDef.bases);
+ if (n > 0)
+ VISIT_SEQ(c, expr, s->v.ClassDef.bases);
+ ADDOP_I(c, BUILD_TUPLE, n);
+ if (!compiler_enter_scope(c, s->v.ClassDef.name, (void *)s,
+ s->lineno))
+ return 0;
+ Py_XDECREF(c->u->u_private);
+ c->u->u_private = s->v.ClassDef.name;
+ Py_INCREF(c->u->u_private);
+ str = PyString_InternFromString("__name__");
+ if (!str || !compiler_nameop(c, str, Load)) {
+ Py_XDECREF(str);
+ compiler_exit_scope(c);
+ return 0;
+ }
+
+ Py_DECREF(str);
+ str = PyString_InternFromString("__module__");
+ if (!str || !compiler_nameop(c, str, Store)) {
+ Py_XDECREF(str);
+ compiler_exit_scope(c);
+ return 0;
+ }
+ Py_DECREF(str);
+
+ if (!compiler_body(c, s->v.ClassDef.body)) {
+ compiler_exit_scope(c);
+ return 0;
+ }
+
+ ADDOP_IN_SCOPE(c, LOAD_LOCALS);
+ ADDOP_IN_SCOPE(c, RETURN_VALUE);
+ co = assemble(c, 1);
+ compiler_exit_scope(c);
+ if (co == NULL)
+ return 0;
+
+ compiler_make_closure(c, co, 0);
+ Py_DECREF(co);
+
+ ADDOP_I(c, CALL_FUNCTION, 0);
+ ADDOP(c, BUILD_CLASS);
+ /* apply decorators */
+ for (i = 0; i < asdl_seq_LEN(decos); i++) {
+ ADDOP_I(c, CALL_FUNCTION, 1);
+ }
+ if (!compiler_nameop(c, s->v.ClassDef.name, Store))
+ return 0;
+ return 1;
}
static int
compiler_ifexp(struct compiler *c, expr_ty e)
{
- basicblock *end, *next;
-
- assert(e->kind == IfExp_kind);
- end = compiler_new_block(c);
- if (end == NULL)
- return 0;
- next = compiler_new_block(c);
- if (next == NULL)
- return 0;
- VISIT(c, expr, e->v.IfExp.test);
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
- VISIT(c, expr, e->v.IfExp.body);
- ADDOP_JREL(c, JUMP_FORWARD, end);
- compiler_use_next_block(c, next);
- VISIT(c, expr, e->v.IfExp.orelse);
- compiler_use_next_block(c, end);
- return 1;
+ basicblock *end, *next;
+
+ assert(e->kind == IfExp_kind);
+ end = compiler_new_block(c);
+ if (end == NULL)
+ return 0;
+ next = compiler_new_block(c);
+ if (next == NULL)
+ return 0;
+ VISIT(c, expr, e->v.IfExp.test);
+ ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
+ VISIT(c, expr, e->v.IfExp.body);
+ ADDOP_JREL(c, JUMP_FORWARD, end);
+ compiler_use_next_block(c, next);
+ VISIT(c, expr, e->v.IfExp.orelse);
+ compiler_use_next_block(c, end);
+ return 1;
}
static int
compiler_lambda(struct compiler *c, expr_ty e)
{
- PyCodeObject *co;
- static identifier name;
- arguments_ty args = e->v.Lambda.args;
- assert(e->kind == Lambda_kind);
-
- if (!name) {
- name = PyString_InternFromString("<lambda>");
- if (!name)
- return 0;
- }
-
- if (args->defaults)
- VISIT_SEQ(c, expr, args->defaults);
- if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
- return 0;
-
- /* unpack nested arguments */
- compiler_arguments(c, args);
-
- /* Make None the first constant, so the lambda can't have a
- docstring. */
- if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
- return 0;
-
- c->u->u_argcount = asdl_seq_LEN(args->args);
- VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
- if (c->u->u_ste->ste_generator) {
- ADDOP_IN_SCOPE(c, POP_TOP);
- }
- else {
- ADDOP_IN_SCOPE(c, RETURN_VALUE);
- }
- co = assemble(c, 1);
- compiler_exit_scope(c);
- if (co == NULL)
- return 0;
-
- compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
- Py_DECREF(co);
-
- return 1;
+ PyCodeObject *co;
+ static identifier name;
+ arguments_ty args = e->v.Lambda.args;
+ assert(e->kind == Lambda_kind);
+
+ if (!name) {
+ name = PyString_InternFromString("<lambda>");
+ if (!name)
+ return 0;
+ }
+
+ if (args->defaults)
+ VISIT_SEQ(c, expr, args->defaults);
+ if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
+ return 0;
+
+ /* unpack nested arguments */
+ compiler_arguments(c, args);
+
+ /* Make None the first constant, so the lambda can't have a
+ docstring. */
+ if (compiler_add_o(c, c->u->u_consts, Py_None) < 0)
+ return 0;
+
+ c->u->u_argcount = asdl_seq_LEN(args->args);
+ VISIT_IN_SCOPE(c, expr, e->v.Lambda.body);
+ if (c->u->u_ste->ste_generator) {
+ ADDOP_IN_SCOPE(c, POP_TOP);
+ }
+ else {
+ ADDOP_IN_SCOPE(c, RETURN_VALUE);
+ }
+ co = assemble(c, 1);
+ compiler_exit_scope(c);
+ if (co == NULL)
+ return 0;
+
+ compiler_make_closure(c, co, asdl_seq_LEN(args->defaults));
+ Py_DECREF(co);
+
+ return 1;
}
static int
compiler_print(struct compiler *c, stmt_ty s)
{
- int i, n;
- bool dest;
-
- assert(s->kind == Print_kind);
- n = asdl_seq_LEN(s->v.Print.values);
- dest = false;
- if (s->v.Print.dest) {
- VISIT(c, expr, s->v.Print.dest);
- dest = true;
- }
- for (i = 0; i < n; i++) {
- expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
- if (dest) {
- ADDOP(c, DUP_TOP);
- VISIT(c, expr, e);
- ADDOP(c, ROT_TWO);
- ADDOP(c, PRINT_ITEM_TO);
- }
- else {
- VISIT(c, expr, e);
- ADDOP(c, PRINT_ITEM);
- }
- }
- if (s->v.Print.nl) {
- if (dest)
- ADDOP(c, PRINT_NEWLINE_TO)
- else
- ADDOP(c, PRINT_NEWLINE)
- }
- else if (dest)
- ADDOP(c, POP_TOP);
- return 1;
+ int i, n;
+ bool dest;
+
+ assert(s->kind == Print_kind);
+ n = asdl_seq_LEN(s->v.Print.values);
+ dest = false;
+ if (s->v.Print.dest) {
+ VISIT(c, expr, s->v.Print.dest);
+ dest = true;
+ }
+ for (i = 0; i < n; i++) {
+ expr_ty e = (expr_ty)asdl_seq_GET(s->v.Print.values, i);
+ if (dest) {
+ ADDOP(c, DUP_TOP);
+ VISIT(c, expr, e);
+ ADDOP(c, ROT_TWO);
+ ADDOP(c, PRINT_ITEM_TO);
+ }
+ else {
+ VISIT(c, expr, e);
+ ADDOP(c, PRINT_ITEM);
+ }
+ }
+ if (s->v.Print.nl) {
+ if (dest)
+ ADDOP(c, PRINT_NEWLINE_TO)
+ else
+ ADDOP(c, PRINT_NEWLINE)
+ }
+ else if (dest)
+ ADDOP(c, POP_TOP);
+ return 1;
}
static int
compiler_if(struct compiler *c, stmt_ty s)
{
- basicblock *end, *next;
- int constant;
- assert(s->kind == If_kind);
- end = compiler_new_block(c);
- if (end == NULL)
- return 0;
-
- constant = expr_constant(s->v.If.test);
- /* constant = 0: "if 0"
- * constant = 1: "if 1", "if 2", ...
- * constant = -1: rest */
- if (constant == 0) {
- if (s->v.If.orelse)
- VISIT_SEQ(c, stmt, s->v.If.orelse);
- } else if (constant == 1) {
- VISIT_SEQ(c, stmt, s->v.If.body);
- } else {
- if (s->v.If.orelse) {
- next = compiler_new_block(c);
- if (next == NULL)
- return 0;
- }
- else
- next = end;
- VISIT(c, expr, s->v.If.test);
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
- VISIT_SEQ(c, stmt, s->v.If.body);
- ADDOP_JREL(c, JUMP_FORWARD, end);
- if (s->v.If.orelse) {
- compiler_use_next_block(c, next);
- VISIT_SEQ(c, stmt, s->v.If.orelse);
- }
- }
- compiler_use_next_block(c, end);
- return 1;
+ basicblock *end, *next;
+ int constant;
+ assert(s->kind == If_kind);
+ end = compiler_new_block(c);
+ if (end == NULL)
+ return 0;
+
+ constant = expr_constant(s->v.If.test);
+ /* constant = 0: "if 0"
+ * constant = 1: "if 1", "if 2", ...
+ * constant = -1: rest */
+ if (constant == 0) {
+ if (s->v.If.orelse)
+ VISIT_SEQ(c, stmt, s->v.If.orelse);
+ } else if (constant == 1) {
+ VISIT_SEQ(c, stmt, s->v.If.body);
+ } else {
+ if (s->v.If.orelse) {
+ next = compiler_new_block(c);
+ if (next == NULL)
+ return 0;
+ }
+ else
+ next = end;
+ VISIT(c, expr, s->v.If.test);
+ ADDOP_JABS(c, POP_JUMP_IF_FALSE, next);
+ VISIT_SEQ(c, stmt, s->v.If.body);
+ ADDOP_JREL(c, JUMP_FORWARD, end);
+ if (s->v.If.orelse) {
+ compiler_use_next_block(c, next);
+ VISIT_SEQ(c, stmt, s->v.If.orelse);
+ }
+ }
+ compiler_use_next_block(c, end);
+ return 1;
}
static int
compiler_for(struct compiler *c, stmt_ty s)
{
- basicblock *start, *cleanup, *end;
-
- start = compiler_new_block(c);
- cleanup = compiler_new_block(c);
- end = compiler_new_block(c);
- if (start == NULL || end == NULL || cleanup == NULL)
- return 0;
- ADDOP_JREL(c, SETUP_LOOP, end);
- if (!compiler_push_fblock(c, LOOP, start))
- return 0;
- VISIT(c, expr, s->v.For.iter);
- ADDOP(c, GET_ITER);
- compiler_use_next_block(c, start);
- ADDOP_JREL(c, FOR_ITER, cleanup);
- VISIT(c, expr, s->v.For.target);
- VISIT_SEQ(c, stmt, s->v.For.body);
- ADDOP_JABS(c, JUMP_ABSOLUTE, start);
- compiler_use_next_block(c, cleanup);
- ADDOP(c, POP_BLOCK);
- compiler_pop_fblock(c, LOOP, start);
- VISIT_SEQ(c, stmt, s->v.For.orelse);
- compiler_use_next_block(c, end);
- return 1;
+ basicblock *start, *cleanup, *end;
+
+ start = compiler_new_block(c);
+ cleanup = compiler_new_block(c);
+ end = compiler_new_block(c);
+ if (start == NULL || end == NULL || cleanup == NULL)
+ return 0;
+ ADDOP_JREL(c, SETUP_LOOP, end);
+ if (!compiler_push_fblock(c, LOOP, start))
+ return 0;
+ VISIT(c, expr, s->v.For.iter);
+ ADDOP(c, GET_ITER);
+ compiler_use_next_block(c, start);
+ ADDOP_JREL(c, FOR_ITER, cleanup);
+ VISIT(c, expr, s->v.For.target);
+ VISIT_SEQ(c, stmt, s->v.For.body);
+ ADDOP_JABS(c, JUMP_ABSOLUTE, start);
+ compiler_use_next_block(c, cleanup);
+ ADDOP(c, POP_BLOCK);
+ compiler_pop_fblock(c, LOOP, start);
+ VISIT_SEQ(c, stmt, s->v.For.orelse);
+ compiler_use_next_block(c, end);
+ return 1;
}
static int
compiler_while(struct compiler *c, stmt_ty s)
{
- basicblock *loop, *orelse, *end, *anchor = NULL;
- int constant = expr_constant(s->v.While.test);
-
- if (constant == 0) {
- if (s->v.While.orelse)
- VISIT_SEQ(c, stmt, s->v.While.orelse);
- return 1;
- }
- loop = compiler_new_block(c);
- end = compiler_new_block(c);
- if (constant == -1) {
- anchor = compiler_new_block(c);
- if (anchor == NULL)
- return 0;
- }
- if (loop == NULL || end == NULL)
- return 0;
- if (s->v.While.orelse) {
- orelse = compiler_new_block(c);
- if (orelse == NULL)
- return 0;
- }
- else
- orelse = NULL;
-
- ADDOP_JREL(c, SETUP_LOOP, end);
- compiler_use_next_block(c, loop);
- if (!compiler_push_fblock(c, LOOP, loop))
- return 0;
- if (constant == -1) {
- VISIT(c, expr, s->v.While.test);
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
- }
- VISIT_SEQ(c, stmt, s->v.While.body);
- ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
-
- /* XXX should the two POP instructions be in a separate block
- if there is no else clause ?
- */
-
- if (constant == -1) {
- compiler_use_next_block(c, anchor);
- ADDOP(c, POP_BLOCK);
- }
- compiler_pop_fblock(c, LOOP, loop);
- if (orelse != NULL) /* what if orelse is just pass? */
- VISIT_SEQ(c, stmt, s->v.While.orelse);
- compiler_use_next_block(c, end);
-
- return 1;
+ basicblock *loop, *orelse, *end, *anchor = NULL;
+ int constant = expr_constant(s->v.While.test);
+
+ if (constant == 0) {
+ if (s->v.While.orelse)
+ VISIT_SEQ(c, stmt, s->v.While.orelse);
+ return 1;
+ }
+ loop = compiler_new_block(c);
+ end = compiler_new_block(c);
+ if (constant == -1) {
+ anchor = compiler_new_block(c);
+ if (anchor == NULL)
+ return 0;
+ }
+ if (loop == NULL || end == NULL)
+ return 0;
+ if (s->v.While.orelse) {
+ orelse = compiler_new_block(c);
+ if (orelse == NULL)
+ return 0;
+ }
+ else
+ orelse = NULL;
+
+ ADDOP_JREL(c, SETUP_LOOP, end);
+ compiler_use_next_block(c, loop);
+ if (!compiler_push_fblock(c, LOOP, loop))
+ return 0;
+ if (constant == -1) {
+ VISIT(c, expr, s->v.While.test);
+ ADDOP_JABS(c, POP_JUMP_IF_FALSE, anchor);
+ }
+ VISIT_SEQ(c, stmt, s->v.While.body);
+ ADDOP_JABS(c, JUMP_ABSOLUTE, loop);
+
+ /* XXX should the two POP instructions be in a separate block
+ if there is no else clause ?
+ */
+
+ if (constant == -1) {
+ compiler_use_next_block(c, anchor);
+ ADDOP(c, POP_BLOCK);
+ }
+ compiler_pop_fblock(c, LOOP, loop);
+ if (orelse != NULL) /* what if orelse is just pass? */
+ VISIT_SEQ(c, stmt, s->v.While.orelse);
+ compiler_use_next_block(c, end);
+
+ return 1;
}
static int
compiler_continue(struct compiler *c)
{
- static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
- static const char IN_FINALLY_ERROR_MSG[] =
- "'continue' not supported inside 'finally' clause";
- int i;
-
- if (!c->u->u_nfblocks)
- return compiler_error(c, LOOP_ERROR_MSG);
- i = c->u->u_nfblocks - 1;
- switch (c->u->u_fblock[i].fb_type) {
- case LOOP:
- ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
- break;
- case EXCEPT:
- case FINALLY_TRY:
- while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
- /* Prevent continue anywhere under a finally
- even if hidden in a sub-try or except. */
- if (c->u->u_fblock[i].fb_type == FINALLY_END)
- return compiler_error(c, IN_FINALLY_ERROR_MSG);
- }
- if (i == -1)
- return compiler_error(c, LOOP_ERROR_MSG);
- ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
- break;
- case FINALLY_END:
- return compiler_error(c, IN_FINALLY_ERROR_MSG);
- }
-
- return 1;
+ static const char LOOP_ERROR_MSG[] = "'continue' not properly in loop";
+ static const char IN_FINALLY_ERROR_MSG[] =
+ "'continue' not supported inside 'finally' clause";
+ int i;
+
+ if (!c->u->u_nfblocks)
+ return compiler_error(c, LOOP_ERROR_MSG);
+ i = c->u->u_nfblocks - 1;
+ switch (c->u->u_fblock[i].fb_type) {
+ case LOOP:
+ ADDOP_JABS(c, JUMP_ABSOLUTE, c->u->u_fblock[i].fb_block);
+ break;
+ case EXCEPT:
+ case FINALLY_TRY:
+ while (--i >= 0 && c->u->u_fblock[i].fb_type != LOOP) {
+ /* Prevent continue anywhere under a finally
+ even if hidden in a sub-try or except. */
+ if (c->u->u_fblock[i].fb_type == FINALLY_END)
+ return compiler_error(c, IN_FINALLY_ERROR_MSG);
+ }
+ if (i == -1)
+ return compiler_error(c, LOOP_ERROR_MSG);
+ ADDOP_JABS(c, CONTINUE_LOOP, c->u->u_fblock[i].fb_block);
+ break;
+ case FINALLY_END:
+ return compiler_error(c, IN_FINALLY_ERROR_MSG);
+ }
+
+ return 1;
}
/* Code generated for "try: <body> finally: <finalbody>" is as follows:
-
- SETUP_FINALLY L
- <code for body>
- POP_BLOCK
- LOAD_CONST <None>
- L: <code for finalbody>
- END_FINALLY
-
+
+ SETUP_FINALLY L
+ <code for body>
+ POP_BLOCK
+ LOAD_CONST <None>
+ L: <code for finalbody>
+ END_FINALLY
+
The special instructions use the block stack. Each block
stack entry contains the instruction that created it (here
SETUP_FINALLY), the level of the value stack at the time the
block stack entry was created, and a label (here L).
-
+
SETUP_FINALLY:
- Pushes the current value stack level and the label
- onto the block stack.
+ Pushes the current value stack level and the label
+ onto the block stack.
POP_BLOCK:
- Pops en entry from the block stack, and pops the value
- stack until its level is the same as indicated on the
- block stack. (The label is ignored.)
+ Pops en entry from the block stack, and pops the value
+ stack until its level is the same as indicated on the
+ block stack. (The label is ignored.)
END_FINALLY:
- Pops a variable number of entries from the *value* stack
- and re-raises the exception they specify. The number of
- entries popped depends on the (pseudo) exception type.
-
+ Pops a variable number of entries from the *value* stack
+ and re-raises the exception they specify. The number of
+ entries popped depends on the (pseudo) exception type.
+
The block stack is unwound when an exception is raised:
when a SETUP_FINALLY entry is found, the exception is pushed
onto the value stack (and the exception condition is cleared),
@@ -1775,29 +1775,29 @@ compiler_continue(struct compiler *c)
static int
compiler_try_finally(struct compiler *c, stmt_ty s)
{
- basicblock *body, *end;
- body = compiler_new_block(c);
- end = compiler_new_block(c);
- if (body == NULL || end == NULL)
- return 0;
-
- ADDOP_JREL(c, SETUP_FINALLY, end);
- compiler_use_next_block(c, body);
- if (!compiler_push_fblock(c, FINALLY_TRY, body))
- return 0;
- VISIT_SEQ(c, stmt, s->v.TryFinally.body);
- ADDOP(c, POP_BLOCK);
- compiler_pop_fblock(c, FINALLY_TRY, body);
+ basicblock *body, *end;
+ body = compiler_new_block(c);
+ end = compiler_new_block(c);
+ if (body == NULL || end == NULL)
+ return 0;
+
+ ADDOP_JREL(c, SETUP_FINALLY, end);
+ compiler_use_next_block(c, body);
+ if (!compiler_push_fblock(c, FINALLY_TRY, body))
+ return 0;
+ VISIT_SEQ(c, stmt, s->v.TryFinally.body);
+ ADDOP(c, POP_BLOCK);
+ compiler_pop_fblock(c, FINALLY_TRY, body);
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- compiler_use_next_block(c, end);
- if (!compiler_push_fblock(c, FINALLY_END, end))
- return 0;
- VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
- ADDOP(c, END_FINALLY);
- compiler_pop_fblock(c, FINALLY_END, end);
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ compiler_use_next_block(c, end);
+ if (!compiler_push_fblock(c, FINALLY_END, end))
+ return 0;
+ VISIT_SEQ(c, stmt, s->v.TryFinally.finalbody);
+ ADDOP(c, END_FINALLY);
+ compiler_pop_fblock(c, FINALLY_END, end);
- return 1;
+ return 1;
}
/*
@@ -1805,853 +1805,853 @@ compiler_try_finally(struct compiler *c, stmt_ty s)
(The contents of the value stack is shown in [], with the top
at the right; 'tb' is trace-back info, 'val' the exception's
associated value, and 'exc' the exception.)
-
- Value stack Label Instruction Argument
- [] SETUP_EXCEPT L1
- [] <code for S>
- [] POP_BLOCK
- [] JUMP_FORWARD L0
-
- [tb, val, exc] L1: DUP )
- [tb, val, exc, exc] <evaluate E1> )
- [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
- [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
- [tb, val, exc] POP
- [tb, val] <assign to V1> (or POP if no V1)
- [tb] POP
- [] <code for S1>
- JUMP_FORWARD L0
-
- [tb, val, exc] L2: DUP
+
+ Value stack Label Instruction Argument
+ [] SETUP_EXCEPT L1
+ [] <code for S>
+ [] POP_BLOCK
+ [] JUMP_FORWARD L0
+
+ [tb, val, exc] L1: DUP )
+ [tb, val, exc, exc] <evaluate E1> )
+ [tb, val, exc, exc, E1] COMPARE_OP EXC_MATCH ) only if E1
+ [tb, val, exc, 1-or-0] POP_JUMP_IF_FALSE L2 )
+ [tb, val, exc] POP
+ [tb, val] <assign to V1> (or POP if no V1)
+ [tb] POP
+ [] <code for S1>
+ JUMP_FORWARD L0
+
+ [tb, val, exc] L2: DUP
.............................etc.......................
- [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
-
- [] L0: <next statement>
-
+ [tb, val, exc] Ln+1: END_FINALLY # re-raise exception
+
+ [] L0: <next statement>
+
Of course, parts are not generated if Vi or Ei is not present.
*/
static int
compiler_try_except(struct compiler *c, stmt_ty s)
{
- basicblock *body, *orelse, *except, *end;
- int i, n;
-
- body = compiler_new_block(c);
- except = compiler_new_block(c);
- orelse = compiler_new_block(c);
- end = compiler_new_block(c);
- if (body == NULL || except == NULL || orelse == NULL || end == NULL)
- return 0;
- ADDOP_JREL(c, SETUP_EXCEPT, except);
- compiler_use_next_block(c, body);
- if (!compiler_push_fblock(c, EXCEPT, body))
- return 0;
- VISIT_SEQ(c, stmt, s->v.TryExcept.body);
- ADDOP(c, POP_BLOCK);
- compiler_pop_fblock(c, EXCEPT, body);
- ADDOP_JREL(c, JUMP_FORWARD, orelse);
- n = asdl_seq_LEN(s->v.TryExcept.handlers);
- compiler_use_next_block(c, except);
- for (i = 0; i < n; i++) {
- excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
- s->v.TryExcept.handlers, i);
- if (!handler->v.ExceptHandler.type && i < n-1)
- return compiler_error(c, "default 'except:' must be last");
- c->u->u_lineno_set = false;
- c->u->u_lineno = handler->lineno;
- except = compiler_new_block(c);
- if (except == NULL)
- return 0;
- if (handler->v.ExceptHandler.type) {
- ADDOP(c, DUP_TOP);
- VISIT(c, expr, handler->v.ExceptHandler.type);
- ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
- }
- ADDOP(c, POP_TOP);
- if (handler->v.ExceptHandler.name) {
- VISIT(c, expr, handler->v.ExceptHandler.name);
- }
- else {
- ADDOP(c, POP_TOP);
- }
- ADDOP(c, POP_TOP);
- VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
- ADDOP_JREL(c, JUMP_FORWARD, end);
- compiler_use_next_block(c, except);
- }
- ADDOP(c, END_FINALLY);
- compiler_use_next_block(c, orelse);
- VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
- compiler_use_next_block(c, end);
- return 1;
+ basicblock *body, *orelse, *except, *end;
+ int i, n;
+
+ body = compiler_new_block(c);
+ except = compiler_new_block(c);
+ orelse = compiler_new_block(c);
+ end = compiler_new_block(c);
+ if (body == NULL || except == NULL || orelse == NULL || end == NULL)
+ return 0;
+ ADDOP_JREL(c, SETUP_EXCEPT, except);
+ compiler_use_next_block(c, body);
+ if (!compiler_push_fblock(c, EXCEPT, body))
+ return 0;
+ VISIT_SEQ(c, stmt, s->v.TryExcept.body);
+ ADDOP(c, POP_BLOCK);
+ compiler_pop_fblock(c, EXCEPT, body);
+ ADDOP_JREL(c, JUMP_FORWARD, orelse);
+ n = asdl_seq_LEN(s->v.TryExcept.handlers);
+ compiler_use_next_block(c, except);
+ for (i = 0; i < n; i++) {
+ excepthandler_ty handler = (excepthandler_ty)asdl_seq_GET(
+ s->v.TryExcept.handlers, i);
+ if (!handler->v.ExceptHandler.type && i < n-1)
+ return compiler_error(c, "default 'except:' must be last");
+ c->u->u_lineno_set = false;
+ c->u->u_lineno = handler->lineno;
+ except = compiler_new_block(c);
+ if (except == NULL)
+ return 0;
+ if (handler->v.ExceptHandler.type) {
+ ADDOP(c, DUP_TOP);
+ VISIT(c, expr, handler->v.ExceptHandler.type);
+ ADDOP_I(c, COMPARE_OP, PyCmp_EXC_MATCH);
+ ADDOP_JABS(c, POP_JUMP_IF_FALSE, except);
+ }
+ ADDOP(c, POP_TOP);
+ if (handler->v.ExceptHandler.name) {
+ VISIT(c, expr, handler->v.ExceptHandler.name);
+ }
+ else {
+ ADDOP(c, POP_TOP);
+ }
+ ADDOP(c, POP_TOP);
+ VISIT_SEQ(c, stmt, handler->v.ExceptHandler.body);
+ ADDOP_JREL(c, JUMP_FORWARD, end);
+ compiler_use_next_block(c, except);
+ }
+ ADDOP(c, END_FINALLY);
+ compiler_use_next_block(c, orelse);
+ VISIT_SEQ(c, stmt, s->v.TryExcept.orelse);
+ compiler_use_next_block(c, end);
+ return 1;
}
static int
compiler_import_as(struct compiler *c, identifier name, identifier asname)
{
- /* The IMPORT_NAME opcode was already generated. This function
- merely needs to bind the result to a name.
-
- If there is a dot in name, we need to split it and emit a
- LOAD_ATTR for each name.
- */
- const char *src = PyString_AS_STRING(name);
- const char *dot = strchr(src, '.');
- if (dot) {
- /* Consume the base module name to get the first attribute */
- src = dot + 1;
- while (dot) {
- /* NB src is only defined when dot != NULL */
- PyObject *attr;
- dot = strchr(src, '.');
- attr = PyString_FromStringAndSize(src,
- dot ? dot - src : strlen(src));
- if (!attr)
- return -1;
- ADDOP_O(c, LOAD_ATTR, attr, names);
- Py_DECREF(attr);
- src = dot + 1;
- }
- }
- return compiler_nameop(c, asname, Store);
+ /* The IMPORT_NAME opcode was already generated. This function
+ merely needs to bind the result to a name.
+
+ If there is a dot in name, we need to split it and emit a
+ LOAD_ATTR for each name.
+ */
+ const char *src = PyString_AS_STRING(name);
+ const char *dot = strchr(src, '.');
+ if (dot) {
+ /* Consume the base module name to get the first attribute */
+ src = dot + 1;
+ while (dot) {
+ /* NB src is only defined when dot != NULL */
+ PyObject *attr;
+ dot = strchr(src, '.');
+ attr = PyString_FromStringAndSize(src,
+ dot ? dot - src : strlen(src));
+ if (!attr)
+ return -1;
+ ADDOP_O(c, LOAD_ATTR, attr, names);
+ Py_DECREF(attr);
+ src = dot + 1;
+ }
+ }
+ return compiler_nameop(c, asname, Store);
}
static int
compiler_import(struct compiler *c, stmt_ty s)
{
- /* The Import node stores a module name like a.b.c as a single
- string. This is convenient for all cases except
- import a.b.c as d
- where we need to parse that string to extract the individual
- module names.
- XXX Perhaps change the representation to make this case simpler?
- */
- int i, n = asdl_seq_LEN(s->v.Import.names);
-
- for (i = 0; i < n; i++) {
- alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
- int r;
- PyObject *level;
-
- if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
- level = PyInt_FromLong(0);
- else
- level = PyInt_FromLong(-1);
-
- if (level == NULL)
- return 0;
-
- ADDOP_O(c, LOAD_CONST, level, consts);
- Py_DECREF(level);
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
-
- if (alias->asname) {
- r = compiler_import_as(c, alias->name, alias->asname);
- if (!r)
- return r;
- }
- else {
- identifier tmp = alias->name;
- const char *base = PyString_AS_STRING(alias->name);
- char *dot = strchr(base, '.');
- if (dot)
- tmp = PyString_FromStringAndSize(base,
- dot - base);
- r = compiler_nameop(c, tmp, Store);
- if (dot) {
- Py_DECREF(tmp);
- }
- if (!r)
- return r;
- }
- }
- return 1;
+ /* The Import node stores a module name like a.b.c as a single
+ string. This is convenient for all cases except
+ import a.b.c as d
+ where we need to parse that string to extract the individual
+ module names.
+ XXX Perhaps change the representation to make this case simpler?
+ */
+ int i, n = asdl_seq_LEN(s->v.Import.names);
+
+ for (i = 0; i < n; i++) {
+ alias_ty alias = (alias_ty)asdl_seq_GET(s->v.Import.names, i);
+ int r;
+ PyObject *level;
+
+ if (c->c_flags && (c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
+ level = PyInt_FromLong(0);
+ else
+ level = PyInt_FromLong(-1);
+
+ if (level == NULL)
+ return 0;
+
+ ADDOP_O(c, LOAD_CONST, level, consts);
+ Py_DECREF(level);
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ ADDOP_NAME(c, IMPORT_NAME, alias->name, names);
+
+ if (alias->asname) {
+ r = compiler_import_as(c, alias->name, alias->asname);
+ if (!r)
+ return r;
+ }
+ else {
+ identifier tmp = alias->name;
+ const char *base = PyString_AS_STRING(alias->name);
+ char *dot = strchr(base, '.');
+ if (dot)
+ tmp = PyString_FromStringAndSize(base,
+ dot - base);
+ r = compiler_nameop(c, tmp, Store);
+ if (dot) {
+ Py_DECREF(tmp);
+ }
+ if (!r)
+ return r;
+ }
+ }
+ return 1;
}
static int
compiler_from_import(struct compiler *c, stmt_ty s)
{
- int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
-
- PyObject *names = PyTuple_New(n);
- PyObject *level;
- static PyObject *empty_string;
-
- if (!empty_string) {
- empty_string = PyString_FromString("");
- if (!empty_string)
- return 0;
- }
-
- if (!names)
- return 0;
-
- if (s->v.ImportFrom.level == 0 && c->c_flags &&
- !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
- level = PyInt_FromLong(-1);
- else
- level = PyInt_FromLong(s->v.ImportFrom.level);
-
- if (!level) {
- Py_DECREF(names);
- return 0;
- }
-
- /* build up the names */
- for (i = 0; i < n; i++) {
- alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
- Py_INCREF(alias->name);
- PyTuple_SET_ITEM(names, i, alias->name);
- }
-
- if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
- !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
- Py_DECREF(level);
- Py_DECREF(names);
- return compiler_error(c, "from __future__ imports must occur "
- "at the beginning of the file");
- }
-
- ADDOP_O(c, LOAD_CONST, level, consts);
- Py_DECREF(level);
- ADDOP_O(c, LOAD_CONST, names, consts);
- Py_DECREF(names);
- if (s->v.ImportFrom.module) {
- ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
- }
- else {
- ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
- }
- for (i = 0; i < n; i++) {
- alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
- identifier store_name;
-
- if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
- assert(n == 1);
- ADDOP(c, IMPORT_STAR);
- return 1;
- }
-
- ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
- store_name = alias->name;
- if (alias->asname)
- store_name = alias->asname;
-
- if (!compiler_nameop(c, store_name, Store)) {
- Py_DECREF(names);
- return 0;
- }
- }
- /* remove imported module */
- ADDOP(c, POP_TOP);
- return 1;
+ int i, n = asdl_seq_LEN(s->v.ImportFrom.names);
+
+ PyObject *names = PyTuple_New(n);
+ PyObject *level;
+ static PyObject *empty_string;
+
+ if (!empty_string) {
+ empty_string = PyString_FromString("");
+ if (!empty_string)
+ return 0;
+ }
+
+ if (!names)
+ return 0;
+
+ if (s->v.ImportFrom.level == 0 && c->c_flags &&
+ !(c->c_flags->cf_flags & CO_FUTURE_ABSOLUTE_IMPORT))
+ level = PyInt_FromLong(-1);
+ else
+ level = PyInt_FromLong(s->v.ImportFrom.level);
+
+ if (!level) {
+ Py_DECREF(names);
+ return 0;
+ }
+
+ /* build up the names */
+ for (i = 0; i < n; i++) {
+ alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
+ Py_INCREF(alias->name);
+ PyTuple_SET_ITEM(names, i, alias->name);
+ }
+
+ if (s->lineno > c->c_future->ff_lineno && s->v.ImportFrom.module &&
+ !strcmp(PyString_AS_STRING(s->v.ImportFrom.module), "__future__")) {
+ Py_DECREF(level);
+ Py_DECREF(names);
+ return compiler_error(c, "from __future__ imports must occur "
+ "at the beginning of the file");
+ }
+
+ ADDOP_O(c, LOAD_CONST, level, consts);
+ Py_DECREF(level);
+ ADDOP_O(c, LOAD_CONST, names, consts);
+ Py_DECREF(names);
+ if (s->v.ImportFrom.module) {
+ ADDOP_NAME(c, IMPORT_NAME, s->v.ImportFrom.module, names);
+ }
+ else {
+ ADDOP_NAME(c, IMPORT_NAME, empty_string, names);
+ }
+ for (i = 0; i < n; i++) {
+ alias_ty alias = (alias_ty)asdl_seq_GET(s->v.ImportFrom.names, i);
+ identifier store_name;
+
+ if (i == 0 && *PyString_AS_STRING(alias->name) == '*') {
+ assert(n == 1);
+ ADDOP(c, IMPORT_STAR);
+ return 1;
+ }
+
+ ADDOP_NAME(c, IMPORT_FROM, alias->name, names);
+ store_name = alias->name;
+ if (alias->asname)
+ store_name = alias->asname;
+
+ if (!compiler_nameop(c, store_name, Store)) {
+ Py_DECREF(names);
+ return 0;
+ }
+ }
+ /* remove imported module */
+ ADDOP(c, POP_TOP);
+ return 1;
}
static int
compiler_assert(struct compiler *c, stmt_ty s)
{
- static PyObject *assertion_error = NULL;
- basicblock *end;
-
- if (Py_OptimizeFlag)
- return 1;
- if (assertion_error == NULL) {
- assertion_error = PyString_InternFromString("AssertionError");
- if (assertion_error == NULL)
- return 0;
- }
- if (s->v.Assert.test->kind == Tuple_kind &&
- asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
- const char* msg =
- "assertion is always true, perhaps remove parentheses?";
- if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
- c->u->u_lineno, NULL, NULL) == -1)
- return 0;
- }
- VISIT(c, expr, s->v.Assert.test);
- end = compiler_new_block(c);
- if (end == NULL)
- return 0;
- ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
- ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
- if (s->v.Assert.msg) {
- VISIT(c, expr, s->v.Assert.msg);
- ADDOP_I(c, RAISE_VARARGS, 2);
- }
- else {
- ADDOP_I(c, RAISE_VARARGS, 1);
- }
- compiler_use_next_block(c, end);
- return 1;
+ static PyObject *assertion_error = NULL;
+ basicblock *end;
+
+ if (Py_OptimizeFlag)
+ return 1;
+ if (assertion_error == NULL) {
+ assertion_error = PyString_InternFromString("AssertionError");
+ if (assertion_error == NULL)
+ return 0;
+ }
+ if (s->v.Assert.test->kind == Tuple_kind &&
+ asdl_seq_LEN(s->v.Assert.test->v.Tuple.elts) > 0) {
+ const char* msg =
+ "assertion is always true, perhaps remove parentheses?";
+ if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, c->c_filename,
+ c->u->u_lineno, NULL, NULL) == -1)
+ return 0;
+ }
+ VISIT(c, expr, s->v.Assert.test);
+ end = compiler_new_block(c);
+ if (end == NULL)
+ return 0;
+ ADDOP_JABS(c, POP_JUMP_IF_TRUE, end);
+ ADDOP_O(c, LOAD_GLOBAL, assertion_error, names);
+ if (s->v.Assert.msg) {
+ VISIT(c, expr, s->v.Assert.msg);
+ ADDOP_I(c, RAISE_VARARGS, 2);
+ }
+ else {
+ ADDOP_I(c, RAISE_VARARGS, 1);
+ }
+ compiler_use_next_block(c, end);
+ return 1;
}
static int
compiler_visit_stmt(struct compiler *c, stmt_ty s)
{
- int i, n;
-
- /* Always assign a lineno to the next instruction for a stmt. */
- c->u->u_lineno = s->lineno;
- c->u->u_lineno_set = false;
-
- switch (s->kind) {
- case FunctionDef_kind:
- return compiler_function(c, s);
- case ClassDef_kind:
- return compiler_class(c, s);
- case Return_kind:
- if (c->u->u_ste->ste_type != FunctionBlock)
- return compiler_error(c, "'return' outside function");
- if (s->v.Return.value) {
- VISIT(c, expr, s->v.Return.value);
- }
- else
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- ADDOP(c, RETURN_VALUE);
- break;
- case Delete_kind:
- VISIT_SEQ(c, expr, s->v.Delete.targets)
- break;
- case Assign_kind:
- n = asdl_seq_LEN(s->v.Assign.targets);
- VISIT(c, expr, s->v.Assign.value);
- for (i = 0; i < n; i++) {
- if (i < n - 1)
- ADDOP(c, DUP_TOP);
- VISIT(c, expr,
- (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
- }
- break;
- case AugAssign_kind:
- return compiler_augassign(c, s);
- case Print_kind:
- return compiler_print(c, s);
- case For_kind:
- return compiler_for(c, s);
- case While_kind:
- return compiler_while(c, s);
- case If_kind:
- return compiler_if(c, s);
- case Raise_kind:
- n = 0;
- if (s->v.Raise.type) {
- VISIT(c, expr, s->v.Raise.type);
- n++;
- if (s->v.Raise.inst) {
- VISIT(c, expr, s->v.Raise.inst);
- n++;
- if (s->v.Raise.tback) {
- VISIT(c, expr, s->v.Raise.tback);
- n++;
- }
- }
- }
- ADDOP_I(c, RAISE_VARARGS, n);
- break;
- case TryExcept_kind:
- return compiler_try_except(c, s);
- case TryFinally_kind:
- return compiler_try_finally(c, s);
- case Assert_kind:
- return compiler_assert(c, s);
- case Import_kind:
- return compiler_import(c, s);
- case ImportFrom_kind:
- return compiler_from_import(c, s);
- case Exec_kind:
- VISIT(c, expr, s->v.Exec.body);
- if (s->v.Exec.globals) {
- VISIT(c, expr, s->v.Exec.globals);
- if (s->v.Exec.locals) {
- VISIT(c, expr, s->v.Exec.locals);
- } else {
- ADDOP(c, DUP_TOP);
- }
- } else {
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- ADDOP(c, DUP_TOP);
- }
- ADDOP(c, EXEC_STMT);
- break;
- case Global_kind:
- break;
- case Expr_kind:
- if (c->c_interactive && c->c_nestlevel <= 1) {
- VISIT(c, expr, s->v.Expr.value);
- ADDOP(c, PRINT_EXPR);
- }
- else if (s->v.Expr.value->kind != Str_kind &&
- s->v.Expr.value->kind != Num_kind) {
- VISIT(c, expr, s->v.Expr.value);
- ADDOP(c, POP_TOP);
- }
- break;
- case Pass_kind:
- break;
- case Break_kind:
- if (!compiler_in_loop(c))
- return compiler_error(c, "'break' outside loop");
- ADDOP(c, BREAK_LOOP);
- break;
- case Continue_kind:
- return compiler_continue(c);
- case With_kind:
- return compiler_with(c, s);
- }
- return 1;
+ int i, n;
+
+ /* Always assign a lineno to the next instruction for a stmt. */
+ c->u->u_lineno = s->lineno;
+ c->u->u_lineno_set = false;
+
+ switch (s->kind) {
+ case FunctionDef_kind:
+ return compiler_function(c, s);
+ case ClassDef_kind:
+ return compiler_class(c, s);
+ case Return_kind:
+ if (c->u->u_ste->ste_type != FunctionBlock)
+ return compiler_error(c, "'return' outside function");
+ if (s->v.Return.value) {
+ VISIT(c, expr, s->v.Return.value);
+ }
+ else
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ ADDOP(c, RETURN_VALUE);
+ break;
+ case Delete_kind:
+ VISIT_SEQ(c, expr, s->v.Delete.targets)
+ break;
+ case Assign_kind:
+ n = asdl_seq_LEN(s->v.Assign.targets);
+ VISIT(c, expr, s->v.Assign.value);
+ for (i = 0; i < n; i++) {
+ if (i < n - 1)
+ ADDOP(c, DUP_TOP);
+ VISIT(c, expr,
+ (expr_ty)asdl_seq_GET(s->v.Assign.targets, i));
+ }
+ break;
+ case AugAssign_kind:
+ return compiler_augassign(c, s);
+ case Print_kind:
+ return compiler_print(c, s);
+ case For_kind:
+ return compiler_for(c, s);
+ case While_kind:
+ return compiler_while(c, s);
+ case If_kind:
+ return compiler_if(c, s);
+ case Raise_kind:
+ n = 0;
+ if (s->v.Raise.type) {
+ VISIT(c, expr, s->v.Raise.type);
+ n++;
+ if (s->v.Raise.inst) {
+ VISIT(c, expr, s->v.Raise.inst);
+ n++;
+ if (s->v.Raise.tback) {
+ VISIT(c, expr, s->v.Raise.tback);
+ n++;
+ }
+ }
+ }
+ ADDOP_I(c, RAISE_VARARGS, n);
+ break;
+ case TryExcept_kind:
+ return compiler_try_except(c, s);
+ case TryFinally_kind:
+ return compiler_try_finally(c, s);
+ case Assert_kind:
+ return compiler_assert(c, s);
+ case Import_kind:
+ return compiler_import(c, s);
+ case ImportFrom_kind:
+ return compiler_from_import(c, s);
+ case Exec_kind:
+ VISIT(c, expr, s->v.Exec.body);
+ if (s->v.Exec.globals) {
+ VISIT(c, expr, s->v.Exec.globals);
+ if (s->v.Exec.locals) {
+ VISIT(c, expr, s->v.Exec.locals);
+ } else {
+ ADDOP(c, DUP_TOP);
+ }
+ } else {
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ ADDOP(c, DUP_TOP);
+ }
+ ADDOP(c, EXEC_STMT);
+ break;
+ case Global_kind:
+ break;
+ case Expr_kind:
+ if (c->c_interactive && c->c_nestlevel <= 1) {
+ VISIT(c, expr, s->v.Expr.value);
+ ADDOP(c, PRINT_EXPR);
+ }
+ else if (s->v.Expr.value->kind != Str_kind &&
+ s->v.Expr.value->kind != Num_kind) {
+ VISIT(c, expr, s->v.Expr.value);
+ ADDOP(c, POP_TOP);
+ }
+ break;
+ case Pass_kind:
+ break;
+ case Break_kind:
+ if (!compiler_in_loop(c))
+ return compiler_error(c, "'break' outside loop");
+ ADDOP(c, BREAK_LOOP);
+ break;
+ case Continue_kind:
+ return compiler_continue(c);
+ case With_kind:
+ return compiler_with(c, s);
+ }
+ return 1;
}
static int
unaryop(unaryop_ty op)
{
- switch (op) {
- case Invert:
- return UNARY_INVERT;
- case Not:
- return UNARY_NOT;
- case UAdd:
- return UNARY_POSITIVE;
- case USub:
- return UNARY_NEGATIVE;
- default:
- PyErr_Format(PyExc_SystemError,
- "unary op %d should not be possible", op);
- return 0;
- }
+ switch (op) {
+ case Invert:
+ return UNARY_INVERT;
+ case Not:
+ return UNARY_NOT;
+ case UAdd:
+ return UNARY_POSITIVE;
+ case USub:
+ return UNARY_NEGATIVE;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "unary op %d should not be possible", op);
+ return 0;
+ }
}
static int
binop(struct compiler *c, operator_ty op)
{
- switch (op) {
- case Add:
- return BINARY_ADD;
- case Sub:
- return BINARY_SUBTRACT;
- case Mult:
- return BINARY_MULTIPLY;
- case Div:
- if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
- return BINARY_TRUE_DIVIDE;
- else
- return BINARY_DIVIDE;
- case Mod:
- return BINARY_MODULO;
- case Pow:
- return BINARY_POWER;
- case LShift:
- return BINARY_LSHIFT;
- case RShift:
- return BINARY_RSHIFT;
- case BitOr:
- return BINARY_OR;
- case BitXor:
- return BINARY_XOR;
- case BitAnd:
- return BINARY_AND;
- case FloorDiv:
- return BINARY_FLOOR_DIVIDE;
- default:
- PyErr_Format(PyExc_SystemError,
- "binary op %d should not be possible", op);
- return 0;
- }
+ switch (op) {
+ case Add:
+ return BINARY_ADD;
+ case Sub:
+ return BINARY_SUBTRACT;
+ case Mult:
+ return BINARY_MULTIPLY;
+ case Div:
+ if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
+ return BINARY_TRUE_DIVIDE;
+ else
+ return BINARY_DIVIDE;
+ case Mod:
+ return BINARY_MODULO;
+ case Pow:
+ return BINARY_POWER;
+ case LShift:
+ return BINARY_LSHIFT;
+ case RShift:
+ return BINARY_RSHIFT;
+ case BitOr:
+ return BINARY_OR;
+ case BitXor:
+ return BINARY_XOR;
+ case BitAnd:
+ return BINARY_AND;
+ case FloorDiv:
+ return BINARY_FLOOR_DIVIDE;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "binary op %d should not be possible", op);
+ return 0;
+ }
}
static int
cmpop(cmpop_ty op)
{
- switch (op) {
- case Eq:
- return PyCmp_EQ;
- case NotEq:
- return PyCmp_NE;
- case Lt:
- return PyCmp_LT;
- case LtE:
- return PyCmp_LE;
- case Gt:
- return PyCmp_GT;
- case GtE:
- return PyCmp_GE;
- case Is:
- return PyCmp_IS;
- case IsNot:
- return PyCmp_IS_NOT;
- case In:
- return PyCmp_IN;
- case NotIn:
- return PyCmp_NOT_IN;
- default:
- return PyCmp_BAD;
- }
+ switch (op) {
+ case Eq:
+ return PyCmp_EQ;
+ case NotEq:
+ return PyCmp_NE;
+ case Lt:
+ return PyCmp_LT;
+ case LtE:
+ return PyCmp_LE;
+ case Gt:
+ return PyCmp_GT;
+ case GtE:
+ return PyCmp_GE;
+ case Is:
+ return PyCmp_IS;
+ case IsNot:
+ return PyCmp_IS_NOT;
+ case In:
+ return PyCmp_IN;
+ case NotIn:
+ return PyCmp_NOT_IN;
+ default:
+ return PyCmp_BAD;
+ }
}
static int
inplace_binop(struct compiler *c, operator_ty op)
{
- switch (op) {
- case Add:
- return INPLACE_ADD;
- case Sub:
- return INPLACE_SUBTRACT;
- case Mult:
- return INPLACE_MULTIPLY;
- case Div:
- if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
- return INPLACE_TRUE_DIVIDE;
- else
- return INPLACE_DIVIDE;
- case Mod:
- return INPLACE_MODULO;
- case Pow:
- return INPLACE_POWER;
- case LShift:
- return INPLACE_LSHIFT;
- case RShift:
- return INPLACE_RSHIFT;
- case BitOr:
- return INPLACE_OR;
- case BitXor:
- return INPLACE_XOR;
- case BitAnd:
- return INPLACE_AND;
- case FloorDiv:
- return INPLACE_FLOOR_DIVIDE;
- default:
- PyErr_Format(PyExc_SystemError,
- "inplace binary op %d should not be possible", op);
- return 0;
- }
+ switch (op) {
+ case Add:
+ return INPLACE_ADD;
+ case Sub:
+ return INPLACE_SUBTRACT;
+ case Mult:
+ return INPLACE_MULTIPLY;
+ case Div:
+ if (c->c_flags && c->c_flags->cf_flags & CO_FUTURE_DIVISION)
+ return INPLACE_TRUE_DIVIDE;
+ else
+ return INPLACE_DIVIDE;
+ case Mod:
+ return INPLACE_MODULO;
+ case Pow:
+ return INPLACE_POWER;
+ case LShift:
+ return INPLACE_LSHIFT;
+ case RShift:
+ return INPLACE_RSHIFT;
+ case BitOr:
+ return INPLACE_OR;
+ case BitXor:
+ return INPLACE_XOR;
+ case BitAnd:
+ return INPLACE_AND;
+ case FloorDiv:
+ return INPLACE_FLOOR_DIVIDE;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "inplace binary op %d should not be possible", op);
+ return 0;
+ }
}
static int
compiler_nameop(struct compiler *c, identifier name, expr_context_ty ctx)
{
- int op, scope, arg;
- enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
-
- PyObject *dict = c->u->u_names;
- PyObject *mangled;
- /* XXX AugStore isn't used anywhere! */
-
- mangled = _Py_Mangle(c->u->u_private, name);
- if (!mangled)
- return 0;
-
- op = 0;
- optype = OP_NAME;
- scope = PyST_GetScope(c->u->u_ste, mangled);
- switch (scope) {
- case FREE:
- dict = c->u->u_freevars;
- optype = OP_DEREF;
- break;
- case CELL:
- dict = c->u->u_cellvars;
- optype = OP_DEREF;
- break;
- case LOCAL:
- if (c->u->u_ste->ste_type == FunctionBlock)
- optype = OP_FAST;
- break;
- case GLOBAL_IMPLICIT:
- if (c->u->u_ste->ste_type == FunctionBlock &&
- !c->u->u_ste->ste_unoptimized)
- optype = OP_GLOBAL;
- break;
- case GLOBAL_EXPLICIT:
- optype = OP_GLOBAL;
- break;
- default:
- /* scope can be 0 */
- break;
- }
-
- /* XXX Leave assert here, but handle __doc__ and the like better */
- assert(scope || PyString_AS_STRING(name)[0] == '_');
-
- switch (optype) {
- case OP_DEREF:
- switch (ctx) {
- case Load: op = LOAD_DEREF; break;
- case Store: op = STORE_DEREF; break;
- case AugLoad:
- case AugStore:
- break;
- case Del:
- PyErr_Format(PyExc_SyntaxError,
- "can not delete variable '%s' referenced "
- "in nested scope",
- PyString_AS_STRING(name));
- Py_DECREF(mangled);
- return 0;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid for deref variable");
- return 0;
- }
- break;
- case OP_FAST:
- switch (ctx) {
- case Load: op = LOAD_FAST; break;
- case Store: op = STORE_FAST; break;
- case Del: op = DELETE_FAST; break;
- case AugLoad:
- case AugStore:
- break;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid for local variable");
- return 0;
- }
- ADDOP_O(c, op, mangled, varnames);
- Py_DECREF(mangled);
- return 1;
- case OP_GLOBAL:
- switch (ctx) {
- case Load: op = LOAD_GLOBAL; break;
- case Store: op = STORE_GLOBAL; break;
- case Del: op = DELETE_GLOBAL; break;
- case AugLoad:
- case AugStore:
- break;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid for global variable");
- return 0;
- }
- break;
- case OP_NAME:
- switch (ctx) {
- case Load: op = LOAD_NAME; break;
- case Store: op = STORE_NAME; break;
- case Del: op = DELETE_NAME; break;
- case AugLoad:
- case AugStore:
- break;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid for name variable");
- return 0;
- }
- break;
- }
-
- assert(op);
- arg = compiler_add_o(c, dict, mangled);
- Py_DECREF(mangled);
- if (arg < 0)
- return 0;
- return compiler_addop_i(c, op, arg);
+ int op, scope, arg;
+ enum { OP_FAST, OP_GLOBAL, OP_DEREF, OP_NAME } optype;
+
+ PyObject *dict = c->u->u_names;
+ PyObject *mangled;
+ /* XXX AugStore isn't used anywhere! */
+
+ mangled = _Py_Mangle(c->u->u_private, name);
+ if (!mangled)
+ return 0;
+
+ op = 0;
+ optype = OP_NAME;
+ scope = PyST_GetScope(c->u->u_ste, mangled);
+ switch (scope) {
+ case FREE:
+ dict = c->u->u_freevars;
+ optype = OP_DEREF;
+ break;
+ case CELL:
+ dict = c->u->u_cellvars;
+ optype = OP_DEREF;
+ break;
+ case LOCAL:
+ if (c->u->u_ste->ste_type == FunctionBlock)
+ optype = OP_FAST;
+ break;
+ case GLOBAL_IMPLICIT:
+ if (c->u->u_ste->ste_type == FunctionBlock &&
+ !c->u->u_ste->ste_unoptimized)
+ optype = OP_GLOBAL;
+ break;
+ case GLOBAL_EXPLICIT:
+ optype = OP_GLOBAL;
+ break;
+ default:
+ /* scope can be 0 */
+ break;
+ }
+
+ /* XXX Leave assert here, but handle __doc__ and the like better */
+ assert(scope || PyString_AS_STRING(name)[0] == '_');
+
+ switch (optype) {
+ case OP_DEREF:
+ switch (ctx) {
+ case Load: op = LOAD_DEREF; break;
+ case Store: op = STORE_DEREF; break;
+ case AugLoad:
+ case AugStore:
+ break;
+ case Del:
+ PyErr_Format(PyExc_SyntaxError,
+ "can not delete variable '%s' referenced "
+ "in nested scope",
+ PyString_AS_STRING(name));
+ Py_DECREF(mangled);
+ return 0;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid for deref variable");
+ return 0;
+ }
+ break;
+ case OP_FAST:
+ switch (ctx) {
+ case Load: op = LOAD_FAST; break;
+ case Store: op = STORE_FAST; break;
+ case Del: op = DELETE_FAST; break;
+ case AugLoad:
+ case AugStore:
+ break;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid for local variable");
+ return 0;
+ }
+ ADDOP_O(c, op, mangled, varnames);
+ Py_DECREF(mangled);
+ return 1;
+ case OP_GLOBAL:
+ switch (ctx) {
+ case Load: op = LOAD_GLOBAL; break;
+ case Store: op = STORE_GLOBAL; break;
+ case Del: op = DELETE_GLOBAL; break;
+ case AugLoad:
+ case AugStore:
+ break;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid for global variable");
+ return 0;
+ }
+ break;
+ case OP_NAME:
+ switch (ctx) {
+ case Load: op = LOAD_NAME; break;
+ case Store: op = STORE_NAME; break;
+ case Del: op = DELETE_NAME; break;
+ case AugLoad:
+ case AugStore:
+ break;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid for name variable");
+ return 0;
+ }
+ break;
+ }
+
+ assert(op);
+ arg = compiler_add_o(c, dict, mangled);
+ Py_DECREF(mangled);
+ if (arg < 0)
+ return 0;
+ return compiler_addop_i(c, op, arg);
}
static int
compiler_boolop(struct compiler *c, expr_ty e)
{
- basicblock *end;
- int jumpi, i, n;
- asdl_seq *s;
-
- assert(e->kind == BoolOp_kind);
- if (e->v.BoolOp.op == And)
- jumpi = JUMP_IF_FALSE_OR_POP;
- else
- jumpi = JUMP_IF_TRUE_OR_POP;
- end = compiler_new_block(c);
- if (end == NULL)
- return 0;
- s = e->v.BoolOp.values;
- n = asdl_seq_LEN(s) - 1;
- assert(n >= 0);
- for (i = 0; i < n; ++i) {
- VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
- ADDOP_JABS(c, jumpi, end);
- }
- VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
- compiler_use_next_block(c, end);
- return 1;
+ basicblock *end;
+ int jumpi, i, n;
+ asdl_seq *s;
+
+ assert(e->kind == BoolOp_kind);
+ if (e->v.BoolOp.op == And)
+ jumpi = JUMP_IF_FALSE_OR_POP;
+ else
+ jumpi = JUMP_IF_TRUE_OR_POP;
+ end = compiler_new_block(c);
+ if (end == NULL)
+ return 0;
+ s = e->v.BoolOp.values;
+ n = asdl_seq_LEN(s) - 1;
+ assert(n >= 0);
+ for (i = 0; i < n; ++i) {
+ VISIT(c, expr, (expr_ty)asdl_seq_GET(s, i));
+ ADDOP_JABS(c, jumpi, end);
+ }
+ VISIT(c, expr, (expr_ty)asdl_seq_GET(s, n));
+ compiler_use_next_block(c, end);
+ return 1;
}
static int
compiler_list(struct compiler *c, expr_ty e)
{
- int n = asdl_seq_LEN(e->v.List.elts);
- if (e->v.List.ctx == Store) {
- ADDOP_I(c, UNPACK_SEQUENCE, n);
- }
- VISIT_SEQ(c, expr, e->v.List.elts);
- if (e->v.List.ctx == Load) {
- ADDOP_I(c, BUILD_LIST, n);
- }
- return 1;
+ int n = asdl_seq_LEN(e->v.List.elts);
+ if (e->v.List.ctx == Store) {
+ ADDOP_I(c, UNPACK_SEQUENCE, n);
+ }
+ VISIT_SEQ(c, expr, e->v.List.elts);
+ if (e->v.List.ctx == Load) {
+ ADDOP_I(c, BUILD_LIST, n);
+ }
+ return 1;
}
static int
compiler_tuple(struct compiler *c, expr_ty e)
{
- int n = asdl_seq_LEN(e->v.Tuple.elts);
- if (e->v.Tuple.ctx == Store) {
- ADDOP_I(c, UNPACK_SEQUENCE, n);
- }
- VISIT_SEQ(c, expr, e->v.Tuple.elts);
- if (e->v.Tuple.ctx == Load) {
- ADDOP_I(c, BUILD_TUPLE, n);
- }
- return 1;
+ int n = asdl_seq_LEN(e->v.Tuple.elts);
+ if (e->v.Tuple.ctx == Store) {
+ ADDOP_I(c, UNPACK_SEQUENCE, n);
+ }
+ VISIT_SEQ(c, expr, e->v.Tuple.elts);
+ if (e->v.Tuple.ctx == Load) {
+ ADDOP_I(c, BUILD_TUPLE, n);
+ }
+ return 1;
}
static int
compiler_compare(struct compiler *c, expr_ty e)
{
- int i, n;
- basicblock *cleanup = NULL;
-
- /* XXX the logic can be cleaned up for 1 or multiple comparisons */
- VISIT(c, expr, e->v.Compare.left);
- n = asdl_seq_LEN(e->v.Compare.ops);
- assert(n > 0);
- if (n > 1) {
- cleanup = compiler_new_block(c);
- if (cleanup == NULL)
- return 0;
- VISIT(c, expr,
- (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
- }
- for (i = 1; i < n; i++) {
- ADDOP(c, DUP_TOP);
- ADDOP(c, ROT_THREE);
- ADDOP_I(c, COMPARE_OP,
- cmpop((cmpop_ty)(asdl_seq_GET(
- e->v.Compare.ops, i - 1))));
- ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
- NEXT_BLOCK(c);
- if (i < (n - 1))
- VISIT(c, expr,
- (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
- }
- VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
- ADDOP_I(c, COMPARE_OP,
- cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
- if (n > 1) {
- basicblock *end = compiler_new_block(c);
- if (end == NULL)
- return 0;
- ADDOP_JREL(c, JUMP_FORWARD, end);
- compiler_use_next_block(c, cleanup);
- ADDOP(c, ROT_TWO);
- ADDOP(c, POP_TOP);
- compiler_use_next_block(c, end);
- }
- return 1;
+ int i, n;
+ basicblock *cleanup = NULL;
+
+ /* XXX the logic can be cleaned up for 1 or multiple comparisons */
+ VISIT(c, expr, e->v.Compare.left);
+ n = asdl_seq_LEN(e->v.Compare.ops);
+ assert(n > 0);
+ if (n > 1) {
+ cleanup = compiler_new_block(c);
+ if (cleanup == NULL)
+ return 0;
+ VISIT(c, expr,
+ (expr_ty)asdl_seq_GET(e->v.Compare.comparators, 0));
+ }
+ for (i = 1; i < n; i++) {
+ ADDOP(c, DUP_TOP);
+ ADDOP(c, ROT_THREE);
+ ADDOP_I(c, COMPARE_OP,
+ cmpop((cmpop_ty)(asdl_seq_GET(
+ e->v.Compare.ops, i - 1))));
+ ADDOP_JABS(c, JUMP_IF_FALSE_OR_POP, cleanup);
+ NEXT_BLOCK(c);
+ if (i < (n - 1))
+ VISIT(c, expr,
+ (expr_ty)asdl_seq_GET(e->v.Compare.comparators, i));
+ }
+ VISIT(c, expr, (expr_ty)asdl_seq_GET(e->v.Compare.comparators, n - 1));
+ ADDOP_I(c, COMPARE_OP,
+ cmpop((cmpop_ty)(asdl_seq_GET(e->v.Compare.ops, n - 1))));
+ if (n > 1) {
+ basicblock *end = compiler_new_block(c);
+ if (end == NULL)
+ return 0;
+ ADDOP_JREL(c, JUMP_FORWARD, end);
+ compiler_use_next_block(c, cleanup);
+ ADDOP(c, ROT_TWO);
+ ADDOP(c, POP_TOP);
+ compiler_use_next_block(c, end);
+ }
+ return 1;
}
static int
compiler_call(struct compiler *c, expr_ty e)
{
- int n, code = 0;
-
- VISIT(c, expr, e->v.Call.func);
- n = asdl_seq_LEN(e->v.Call.args);
- VISIT_SEQ(c, expr, e->v.Call.args);
- if (e->v.Call.keywords) {
- VISIT_SEQ(c, keyword, e->v.Call.keywords);
- n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
- }
- if (e->v.Call.starargs) {
- VISIT(c, expr, e->v.Call.starargs);
- code |= 1;
- }
- if (e->v.Call.kwargs) {
- VISIT(c, expr, e->v.Call.kwargs);
- code |= 2;
- }
- switch (code) {
- case 0:
- ADDOP_I(c, CALL_FUNCTION, n);
- break;
- case 1:
- ADDOP_I(c, CALL_FUNCTION_VAR, n);
- break;
- case 2:
- ADDOP_I(c, CALL_FUNCTION_KW, n);
- break;
- case 3:
- ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
- break;
- }
- return 1;
+ int n, code = 0;
+
+ VISIT(c, expr, e->v.Call.func);
+ n = asdl_seq_LEN(e->v.Call.args);
+ VISIT_SEQ(c, expr, e->v.Call.args);
+ if (e->v.Call.keywords) {
+ VISIT_SEQ(c, keyword, e->v.Call.keywords);
+ n |= asdl_seq_LEN(e->v.Call.keywords) << 8;
+ }
+ if (e->v.Call.starargs) {
+ VISIT(c, expr, e->v.Call.starargs);
+ code |= 1;
+ }
+ if (e->v.Call.kwargs) {
+ VISIT(c, expr, e->v.Call.kwargs);
+ code |= 2;
+ }
+ switch (code) {
+ case 0:
+ ADDOP_I(c, CALL_FUNCTION, n);
+ break;
+ case 1:
+ ADDOP_I(c, CALL_FUNCTION_VAR, n);
+ break;
+ case 2:
+ ADDOP_I(c, CALL_FUNCTION_KW, n);
+ break;
+ case 3:
+ ADDOP_I(c, CALL_FUNCTION_VAR_KW, n);
+ break;
+ }
+ return 1;
}
static int
compiler_listcomp_generator(struct compiler *c, asdl_seq *generators,
- int gen_index, expr_ty elt)
-{
- /* generate code for the iterator, then each of the ifs,
- and then write to the element */
-
- comprehension_ty l;
- basicblock *start, *anchor, *skip, *if_cleanup;
- int i, n;
-
- start = compiler_new_block(c);
- skip = compiler_new_block(c);
- if_cleanup = compiler_new_block(c);
- anchor = compiler_new_block(c);
-
- if (start == NULL || skip == NULL || if_cleanup == NULL ||
- anchor == NULL)
- return 0;
-
- l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
- VISIT(c, expr, l->iter);
- ADDOP(c, GET_ITER);
- compiler_use_next_block(c, start);
- ADDOP_JREL(c, FOR_ITER, anchor);
- NEXT_BLOCK(c);
- VISIT(c, expr, l->target);
-
- /* XXX this needs to be cleaned up...a lot! */
- n = asdl_seq_LEN(l->ifs);
- for (i = 0; i < n; i++) {
- expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
- VISIT(c, expr, e);
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
- NEXT_BLOCK(c);
- }
-
- if (++gen_index < asdl_seq_LEN(generators))
- if (!compiler_listcomp_generator(c, generators, gen_index, elt))
- return 0;
-
- /* only append after the last for generator */
- if (gen_index >= asdl_seq_LEN(generators)) {
- VISIT(c, expr, elt);
- ADDOP_I(c, LIST_APPEND, gen_index+1);
-
- compiler_use_next_block(c, skip);
- }
- compiler_use_next_block(c, if_cleanup);
- ADDOP_JABS(c, JUMP_ABSOLUTE, start);
- compiler_use_next_block(c, anchor);
-
- return 1;
+ int gen_index, expr_ty elt)
+{
+ /* generate code for the iterator, then each of the ifs,
+ and then write to the element */
+
+ comprehension_ty l;
+ basicblock *start, *anchor, *skip, *if_cleanup;
+ int i, n;
+
+ start = compiler_new_block(c);
+ skip = compiler_new_block(c);
+ if_cleanup = compiler_new_block(c);
+ anchor = compiler_new_block(c);
+
+ if (start == NULL || skip == NULL || if_cleanup == NULL ||
+ anchor == NULL)
+ return 0;
+
+ l = (comprehension_ty)asdl_seq_GET(generators, gen_index);
+ VISIT(c, expr, l->iter);
+ ADDOP(c, GET_ITER);
+ compiler_use_next_block(c, start);
+ ADDOP_JREL(c, FOR_ITER, anchor);
+ NEXT_BLOCK(c);
+ VISIT(c, expr, l->target);
+
+ /* XXX this needs to be cleaned up...a lot! */
+ n = asdl_seq_LEN(l->ifs);
+ for (i = 0; i < n; i++) {
+ expr_ty e = (expr_ty)asdl_seq_GET(l->ifs, i);
+ VISIT(c, expr, e);
+ ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
+ NEXT_BLOCK(c);
+ }
+
+ if (++gen_index < asdl_seq_LEN(generators))
+ if (!compiler_listcomp_generator(c, generators, gen_index, elt))
+ return 0;
+
+ /* only append after the last for generator */
+ if (gen_index >= asdl_seq_LEN(generators)) {
+ VISIT(c, expr, elt);
+ ADDOP_I(c, LIST_APPEND, gen_index+1);
+
+ compiler_use_next_block(c, skip);
+ }
+ compiler_use_next_block(c, if_cleanup);
+ ADDOP_JABS(c, JUMP_ABSOLUTE, start);
+ compiler_use_next_block(c, anchor);
+
+ return 1;
}
static int
compiler_listcomp(struct compiler *c, expr_ty e)
{
- assert(e->kind == ListComp_kind);
- ADDOP_I(c, BUILD_LIST, 0);
- return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
- e->v.ListComp.elt);
+ assert(e->kind == ListComp_kind);
+ ADDOP_I(c, BUILD_LIST, 0);
+ return compiler_listcomp_generator(c, e->v.ListComp.generators, 0,
+ e->v.ListComp.elt);
}
/* Dict and set comprehensions and generator expressions work by creating a
@@ -2670,204 +2670,204 @@ compiler_listcomp(struct compiler *c, expr_ty e)
*/
static int
-compiler_comprehension_generator(struct compiler *c,
- asdl_seq *generators, int gen_index,
- expr_ty elt, expr_ty val, int type)
-{
- /* generate code for the iterator, then each of the ifs,
- and then write to the element */
-
- comprehension_ty gen;
- basicblock *start, *anchor, *skip, *if_cleanup;
- int i, n;
-
- start = compiler_new_block(c);
- skip = compiler_new_block(c);
- if_cleanup = compiler_new_block(c);
- anchor = compiler_new_block(c);
-
- if (start == NULL || skip == NULL || if_cleanup == NULL ||
- anchor == NULL)
- return 0;
-
- gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
-
- if (gen_index == 0) {
- /* Receive outermost iter as an implicit argument */
- c->u->u_argcount = 1;
- ADDOP_I(c, LOAD_FAST, 0);
- }
- else {
- /* Sub-iter - calculate on the fly */
- VISIT(c, expr, gen->iter);
- ADDOP(c, GET_ITER);
- }
- compiler_use_next_block(c, start);
- ADDOP_JREL(c, FOR_ITER, anchor);
- NEXT_BLOCK(c);
- VISIT(c, expr, gen->target);
-
- /* XXX this needs to be cleaned up...a lot! */
- n = asdl_seq_LEN(gen->ifs);
- for (i = 0; i < n; i++) {
- expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
- VISIT(c, expr, e);
- ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
- NEXT_BLOCK(c);
- }
-
- if (++gen_index < asdl_seq_LEN(generators))
- if (!compiler_comprehension_generator(c,
- generators, gen_index,
- elt, val, type))
- return 0;
-
- /* only append after the last for generator */
- if (gen_index >= asdl_seq_LEN(generators)) {
- /* comprehension specific code */
- switch (type) {
- case COMP_GENEXP:
- VISIT(c, expr, elt);
- ADDOP(c, YIELD_VALUE);
- ADDOP(c, POP_TOP);
- break;
- case COMP_SETCOMP:
- VISIT(c, expr, elt);
- ADDOP_I(c, SET_ADD, gen_index + 1);
- break;
- case COMP_DICTCOMP:
- /* With 'd[k] = v', v is evaluated before k, so we do
- the same. */
- VISIT(c, expr, val);
- VISIT(c, expr, elt);
- ADDOP_I(c, MAP_ADD, gen_index + 1);
- break;
- default:
- return 0;
- }
-
- compiler_use_next_block(c, skip);
- }
- compiler_use_next_block(c, if_cleanup);
- ADDOP_JABS(c, JUMP_ABSOLUTE, start);
- compiler_use_next_block(c, anchor);
-
- return 1;
+compiler_comprehension_generator(struct compiler *c,
+ asdl_seq *generators, int gen_index,
+ expr_ty elt, expr_ty val, int type)
+{
+ /* generate code for the iterator, then each of the ifs,
+ and then write to the element */
+
+ comprehension_ty gen;
+ basicblock *start, *anchor, *skip, *if_cleanup;
+ int i, n;
+
+ start = compiler_new_block(c);
+ skip = compiler_new_block(c);
+ if_cleanup = compiler_new_block(c);
+ anchor = compiler_new_block(c);
+
+ if (start == NULL || skip == NULL || if_cleanup == NULL ||
+ anchor == NULL)
+ return 0;
+
+ gen = (comprehension_ty)asdl_seq_GET(generators, gen_index);
+
+ if (gen_index == 0) {
+ /* Receive outermost iter as an implicit argument */
+ c->u->u_argcount = 1;
+ ADDOP_I(c, LOAD_FAST, 0);
+ }
+ else {
+ /* Sub-iter - calculate on the fly */
+ VISIT(c, expr, gen->iter);
+ ADDOP(c, GET_ITER);
+ }
+ compiler_use_next_block(c, start);
+ ADDOP_JREL(c, FOR_ITER, anchor);
+ NEXT_BLOCK(c);
+ VISIT(c, expr, gen->target);
+
+ /* XXX this needs to be cleaned up...a lot! */
+ n = asdl_seq_LEN(gen->ifs);
+ for (i = 0; i < n; i++) {
+ expr_ty e = (expr_ty)asdl_seq_GET(gen->ifs, i);
+ VISIT(c, expr, e);
+ ADDOP_JABS(c, POP_JUMP_IF_FALSE, if_cleanup);
+ NEXT_BLOCK(c);
+ }
+
+ if (++gen_index < asdl_seq_LEN(generators))
+ if (!compiler_comprehension_generator(c,
+ generators, gen_index,
+ elt, val, type))
+ return 0;
+
+ /* only append after the last for generator */
+ if (gen_index >= asdl_seq_LEN(generators)) {
+ /* comprehension specific code */
+ switch (type) {
+ case COMP_GENEXP:
+ VISIT(c, expr, elt);
+ ADDOP(c, YIELD_VALUE);
+ ADDOP(c, POP_TOP);
+ break;
+ case COMP_SETCOMP:
+ VISIT(c, expr, elt);
+ ADDOP_I(c, SET_ADD, gen_index + 1);
+ break;
+ case COMP_DICTCOMP:
+ /* With 'd[k] = v', v is evaluated before k, so we do
+ the same. */
+ VISIT(c, expr, val);
+ VISIT(c, expr, elt);
+ ADDOP_I(c, MAP_ADD, gen_index + 1);
+ break;
+ default:
+ return 0;
+ }
+
+ compiler_use_next_block(c, skip);
+ }
+ compiler_use_next_block(c, if_cleanup);
+ ADDOP_JABS(c, JUMP_ABSOLUTE, start);
+ compiler_use_next_block(c, anchor);
+
+ return 1;
}
static int
compiler_comprehension(struct compiler *c, expr_ty e, int type, identifier name,
- asdl_seq *generators, expr_ty elt, expr_ty val)
-{
- PyCodeObject *co = NULL;
- expr_ty outermost_iter;
-
- outermost_iter = ((comprehension_ty)
- asdl_seq_GET(generators, 0))->iter;
-
- if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
- goto error;
-
- if (type != COMP_GENEXP) {
- int op;
- switch (type) {
- case COMP_SETCOMP:
- op = BUILD_SET;
- break;
- case COMP_DICTCOMP:
- op = BUILD_MAP;
- break;
- default:
- PyErr_Format(PyExc_SystemError,
- "unknown comprehension type %d", type);
- goto error_in_scope;
- }
-
- ADDOP_I(c, op, 0);
- }
-
- if (!compiler_comprehension_generator(c, generators, 0, elt,
- val, type))
- goto error_in_scope;
-
- if (type != COMP_GENEXP) {
- ADDOP(c, RETURN_VALUE);
- }
-
- co = assemble(c, 1);
- compiler_exit_scope(c);
- if (co == NULL)
- goto error;
-
- if (!compiler_make_closure(c, co, 0))
- goto error;
- Py_DECREF(co);
-
- VISIT(c, expr, outermost_iter);
- ADDOP(c, GET_ITER);
- ADDOP_I(c, CALL_FUNCTION, 1);
- return 1;
+ asdl_seq *generators, expr_ty elt, expr_ty val)
+{
+ PyCodeObject *co = NULL;
+ expr_ty outermost_iter;
+
+ outermost_iter = ((comprehension_ty)
+ asdl_seq_GET(generators, 0))->iter;
+
+ if (!compiler_enter_scope(c, name, (void *)e, e->lineno))
+ goto error;
+
+ if (type != COMP_GENEXP) {
+ int op;
+ switch (type) {
+ case COMP_SETCOMP:
+ op = BUILD_SET;
+ break;
+ case COMP_DICTCOMP:
+ op = BUILD_MAP;
+ break;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "unknown comprehension type %d", type);
+ goto error_in_scope;
+ }
+
+ ADDOP_I(c, op, 0);
+ }
+
+ if (!compiler_comprehension_generator(c, generators, 0, elt,
+ val, type))
+ goto error_in_scope;
+
+ if (type != COMP_GENEXP) {
+ ADDOP(c, RETURN_VALUE);
+ }
+
+ co = assemble(c, 1);
+ compiler_exit_scope(c);
+ if (co == NULL)
+ goto error;
+
+ if (!compiler_make_closure(c, co, 0))
+ goto error;
+ Py_DECREF(co);
+
+ VISIT(c, expr, outermost_iter);
+ ADDOP(c, GET_ITER);
+ ADDOP_I(c, CALL_FUNCTION, 1);
+ return 1;
error_in_scope:
- compiler_exit_scope(c);
+ compiler_exit_scope(c);
error:
- Py_XDECREF(co);
- return 0;
+ Py_XDECREF(co);
+ return 0;
}
static int
compiler_genexp(struct compiler *c, expr_ty e)
{
- static identifier name;
- if (!name) {
- name = PyString_FromString("<genexpr>");
- if (!name)
- return 0;
- }
- assert(e->kind == GeneratorExp_kind);
- return compiler_comprehension(c, e, COMP_GENEXP, name,
- e->v.GeneratorExp.generators,
- e->v.GeneratorExp.elt, NULL);
+ static identifier name;
+ if (!name) {
+ name = PyString_FromString("<genexpr>");
+ if (!name)
+ return 0;
+ }
+ assert(e->kind == GeneratorExp_kind);
+ return compiler_comprehension(c, e, COMP_GENEXP, name,
+ e->v.GeneratorExp.generators,
+ e->v.GeneratorExp.elt, NULL);
}
static int
compiler_setcomp(struct compiler *c, expr_ty e)
{
- static identifier name;
- if (!name) {
- name = PyString_FromString("<setcomp>");
- if (!name)
- return 0;
- }
- assert(e->kind == SetComp_kind);
- return compiler_comprehension(c, e, COMP_SETCOMP, name,
- e->v.SetComp.generators,
- e->v.SetComp.elt, NULL);
+ static identifier name;
+ if (!name) {
+ name = PyString_FromString("<setcomp>");
+ if (!name)
+ return 0;
+ }
+ assert(e->kind == SetComp_kind);
+ return compiler_comprehension(c, e, COMP_SETCOMP, name,
+ e->v.SetComp.generators,
+ e->v.SetComp.elt, NULL);
}
static int
compiler_dictcomp(struct compiler *c, expr_ty e)
{
- static identifier name;
- if (!name) {
- name = PyString_FromString("<dictcomp>");
- if (!name)
- return 0;
- }
- assert(e->kind == DictComp_kind);
- return compiler_comprehension(c, e, COMP_DICTCOMP, name,
- e->v.DictComp.generators,
- e->v.DictComp.key, e->v.DictComp.value);
+ static identifier name;
+ if (!name) {
+ name = PyString_FromString("<dictcomp>");
+ if (!name)
+ return 0;
+ }
+ assert(e->kind == DictComp_kind);
+ return compiler_comprehension(c, e, COMP_DICTCOMP, name,
+ e->v.DictComp.generators,
+ e->v.DictComp.key, e->v.DictComp.value);
}
static int
compiler_visit_keyword(struct compiler *c, keyword_ty k)
{
- ADDOP_O(c, LOAD_CONST, k->arg, consts);
- VISIT(c, expr, k->value);
- return 1;
+ ADDOP_O(c, LOAD_CONST, k->arg, consts);
+ VISIT(c, expr, k->value);
+ return 1;
}
-/* Test whether expression is constant. For constants, report
+/* Test whether expression is constant. For constants, report
whether they are true or false.
Return values: 1 for true, 0 for false, -1 for non-constant.
@@ -2876,33 +2876,33 @@ compiler_visit_keyword(struct compiler *c, keyword_ty k)
static int
expr_constant(expr_ty e)
{
- switch (e->kind) {
- case Num_kind:
- return PyObject_IsTrue(e->v.Num.n);
- case Str_kind:
- return PyObject_IsTrue(e->v.Str.s);
- case Name_kind:
- /* __debug__ is not assignable, so we can optimize
- * it away in if and while statements */
- if (strcmp(PyString_AS_STRING(e->v.Name.id),
- "__debug__") == 0)
- return ! Py_OptimizeFlag;
- /* fall through */
- default:
- return -1;
- }
+ switch (e->kind) {
+ case Num_kind:
+ return PyObject_IsTrue(e->v.Num.n);
+ case Str_kind:
+ return PyObject_IsTrue(e->v.Str.s);
+ case Name_kind:
+ /* __debug__ is not assignable, so we can optimize
+ * it away in if and while statements */
+ if (strcmp(PyString_AS_STRING(e->v.Name.id),
+ "__debug__") == 0)
+ return ! Py_OptimizeFlag;
+ /* fall through */
+ default:
+ return -1;
+ }
}
/*
Implements the with statement from PEP 343.
- The semantics outlined in that PEP are as follows:
+ The semantics outlined in that PEP are as follows:
with EXPR as VAR:
BLOCK
-
+
It is implemented roughly as:
-
+
context = EXPR
exit = context.__exit__ # not calling it
value = context.__enter__()
@@ -2911,9 +2911,9 @@ expr_constant(expr_ty e)
BLOCK
finally:
if an exception was raised:
- exc = copy of (exception, instance, traceback)
+ exc = copy of (exception, instance, traceback)
else:
- exc = (None, None, None)
+ exc = (None, None, None)
exit(*exc)
*/
static int
@@ -2926,7 +2926,7 @@ compiler_with(struct compiler *c, stmt_ty s)
block = compiler_new_block(c);
finally = compiler_new_block(c);
if (!block || !finally)
- return 0;
+ return 0;
/* Evaluate EXPR */
VISIT(c, expr, s->v.With.context_expr);
@@ -2938,15 +2938,15 @@ compiler_with(struct compiler *c, stmt_ty s)
functions the same as SETUP_FINALLY except that exceptions are
normalized. */
if (!compiler_push_fblock(c, FINALLY_TRY, block)) {
- return 0;
+ return 0;
}
if (s->v.With.optional_vars) {
- VISIT(c, expr, s->v.With.optional_vars);
+ VISIT(c, expr, s->v.With.optional_vars);
}
else {
- /* Discard result from context.__enter__() */
- ADDOP(c, POP_TOP);
+ /* Discard result from context.__enter__() */
+ ADDOP(c, POP_TOP);
}
/* BLOCK code */
@@ -2959,7 +2959,7 @@ compiler_with(struct compiler *c, stmt_ty s)
ADDOP_O(c, LOAD_CONST, Py_None, consts);
compiler_use_next_block(c, finally);
if (!compiler_push_fblock(c, FINALLY_END, finally))
- return 0;
+ return 0;
/* Finally block starts; context.__exit__ is on the stack under
the exception or return information. Just issue our magic
@@ -2975,226 +2975,226 @@ compiler_with(struct compiler *c, stmt_ty s)
static int
compiler_visit_expr(struct compiler *c, expr_ty e)
{
- int i, n;
-
- /* If expr e has a different line number than the last expr/stmt,
- set a new line number for the next instruction.
- */
- if (e->lineno > c->u->u_lineno) {
- c->u->u_lineno = e->lineno;
- c->u->u_lineno_set = false;
- }
- switch (e->kind) {
- case BoolOp_kind:
- return compiler_boolop(c, e);
- case BinOp_kind:
- VISIT(c, expr, e->v.BinOp.left);
- VISIT(c, expr, e->v.BinOp.right);
- ADDOP(c, binop(c, e->v.BinOp.op));
- break;
- case UnaryOp_kind:
- VISIT(c, expr, e->v.UnaryOp.operand);
- ADDOP(c, unaryop(e->v.UnaryOp.op));
- break;
- case Lambda_kind:
- return compiler_lambda(c, e);
- case IfExp_kind:
- return compiler_ifexp(c, e);
- case Dict_kind:
- n = asdl_seq_LEN(e->v.Dict.values);
- ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
- for (i = 0; i < n; i++) {
- VISIT(c, expr,
- (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
- VISIT(c, expr,
- (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
- ADDOP(c, STORE_MAP);
- }
- break;
- case Set_kind:
- n = asdl_seq_LEN(e->v.Set.elts);
- VISIT_SEQ(c, expr, e->v.Set.elts);
- ADDOP_I(c, BUILD_SET, n);
- break;
- case ListComp_kind:
- return compiler_listcomp(c, e);
- case SetComp_kind:
- return compiler_setcomp(c, e);
- case DictComp_kind:
- return compiler_dictcomp(c, e);
- case GeneratorExp_kind:
- return compiler_genexp(c, e);
- case Yield_kind:
- if (c->u->u_ste->ste_type != FunctionBlock)
- return compiler_error(c, "'yield' outside function");
- if (e->v.Yield.value) {
- VISIT(c, expr, e->v.Yield.value);
- }
- else {
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- }
- ADDOP(c, YIELD_VALUE);
- break;
- case Compare_kind:
- return compiler_compare(c, e);
- case Call_kind:
- return compiler_call(c, e);
- case Repr_kind:
- VISIT(c, expr, e->v.Repr.value);
- ADDOP(c, UNARY_CONVERT);
- break;
- case Num_kind:
- ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
- break;
- case Str_kind:
- ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
- break;
- /* The following exprs can be assignment targets. */
- case Attribute_kind:
- if (e->v.Attribute.ctx != AugStore)
- VISIT(c, expr, e->v.Attribute.value);
- switch (e->v.Attribute.ctx) {
- case AugLoad:
- ADDOP(c, DUP_TOP);
- /* Fall through to load */
- case Load:
- ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
- break;
- case AugStore:
- ADDOP(c, ROT_TWO);
- /* Fall through to save */
- case Store:
- ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
- break;
- case Del:
- ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
- break;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid in attribute expression");
- return 0;
- }
- break;
- case Subscript_kind:
- switch (e->v.Subscript.ctx) {
- case AugLoad:
- VISIT(c, expr, e->v.Subscript.value);
- VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
- break;
- case Load:
- VISIT(c, expr, e->v.Subscript.value);
- VISIT_SLICE(c, e->v.Subscript.slice, Load);
- break;
- case AugStore:
- VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
- break;
- case Store:
- VISIT(c, expr, e->v.Subscript.value);
- VISIT_SLICE(c, e->v.Subscript.slice, Store);
- break;
- case Del:
- VISIT(c, expr, e->v.Subscript.value);
- VISIT_SLICE(c, e->v.Subscript.slice, Del);
- break;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid in subscript expression");
- return 0;
- }
- break;
- case Name_kind:
- return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
- /* child nodes of List and Tuple will have expr_context set */
- case List_kind:
- return compiler_list(c, e);
- case Tuple_kind:
- return compiler_tuple(c, e);
- }
- return 1;
+ int i, n;
+
+ /* If expr e has a different line number than the last expr/stmt,
+ set a new line number for the next instruction.
+ */
+ if (e->lineno > c->u->u_lineno) {
+ c->u->u_lineno = e->lineno;
+ c->u->u_lineno_set = false;
+ }
+ switch (e->kind) {
+ case BoolOp_kind:
+ return compiler_boolop(c, e);
+ case BinOp_kind:
+ VISIT(c, expr, e->v.BinOp.left);
+ VISIT(c, expr, e->v.BinOp.right);
+ ADDOP(c, binop(c, e->v.BinOp.op));
+ break;
+ case UnaryOp_kind:
+ VISIT(c, expr, e->v.UnaryOp.operand);
+ ADDOP(c, unaryop(e->v.UnaryOp.op));
+ break;
+ case Lambda_kind:
+ return compiler_lambda(c, e);
+ case IfExp_kind:
+ return compiler_ifexp(c, e);
+ case Dict_kind:
+ n = asdl_seq_LEN(e->v.Dict.values);
+ ADDOP_I(c, BUILD_MAP, (n>0xFFFF ? 0xFFFF : n));
+ for (i = 0; i < n; i++) {
+ VISIT(c, expr,
+ (expr_ty)asdl_seq_GET(e->v.Dict.values, i));
+ VISIT(c, expr,
+ (expr_ty)asdl_seq_GET(e->v.Dict.keys, i));
+ ADDOP(c, STORE_MAP);
+ }
+ break;
+ case Set_kind:
+ n = asdl_seq_LEN(e->v.Set.elts);
+ VISIT_SEQ(c, expr, e->v.Set.elts);
+ ADDOP_I(c, BUILD_SET, n);
+ break;
+ case ListComp_kind:
+ return compiler_listcomp(c, e);
+ case SetComp_kind:
+ return compiler_setcomp(c, e);
+ case DictComp_kind:
+ return compiler_dictcomp(c, e);
+ case GeneratorExp_kind:
+ return compiler_genexp(c, e);
+ case Yield_kind:
+ if (c->u->u_ste->ste_type != FunctionBlock)
+ return compiler_error(c, "'yield' outside function");
+ if (e->v.Yield.value) {
+ VISIT(c, expr, e->v.Yield.value);
+ }
+ else {
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ }
+ ADDOP(c, YIELD_VALUE);
+ break;
+ case Compare_kind:
+ return compiler_compare(c, e);
+ case Call_kind:
+ return compiler_call(c, e);
+ case Repr_kind:
+ VISIT(c, expr, e->v.Repr.value);
+ ADDOP(c, UNARY_CONVERT);
+ break;
+ case Num_kind:
+ ADDOP_O(c, LOAD_CONST, e->v.Num.n, consts);
+ break;
+ case Str_kind:
+ ADDOP_O(c, LOAD_CONST, e->v.Str.s, consts);
+ break;
+ /* The following exprs can be assignment targets. */
+ case Attribute_kind:
+ if (e->v.Attribute.ctx != AugStore)
+ VISIT(c, expr, e->v.Attribute.value);
+ switch (e->v.Attribute.ctx) {
+ case AugLoad:
+ ADDOP(c, DUP_TOP);
+ /* Fall through to load */
+ case Load:
+ ADDOP_NAME(c, LOAD_ATTR, e->v.Attribute.attr, names);
+ break;
+ case AugStore:
+ ADDOP(c, ROT_TWO);
+ /* Fall through to save */
+ case Store:
+ ADDOP_NAME(c, STORE_ATTR, e->v.Attribute.attr, names);
+ break;
+ case Del:
+ ADDOP_NAME(c, DELETE_ATTR, e->v.Attribute.attr, names);
+ break;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid in attribute expression");
+ return 0;
+ }
+ break;
+ case Subscript_kind:
+ switch (e->v.Subscript.ctx) {
+ case AugLoad:
+ VISIT(c, expr, e->v.Subscript.value);
+ VISIT_SLICE(c, e->v.Subscript.slice, AugLoad);
+ break;
+ case Load:
+ VISIT(c, expr, e->v.Subscript.value);
+ VISIT_SLICE(c, e->v.Subscript.slice, Load);
+ break;
+ case AugStore:
+ VISIT_SLICE(c, e->v.Subscript.slice, AugStore);
+ break;
+ case Store:
+ VISIT(c, expr, e->v.Subscript.value);
+ VISIT_SLICE(c, e->v.Subscript.slice, Store);
+ break;
+ case Del:
+ VISIT(c, expr, e->v.Subscript.value);
+ VISIT_SLICE(c, e->v.Subscript.slice, Del);
+ break;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid in subscript expression");
+ return 0;
+ }
+ break;
+ case Name_kind:
+ return compiler_nameop(c, e->v.Name.id, e->v.Name.ctx);
+ /* child nodes of List and Tuple will have expr_context set */
+ case List_kind:
+ return compiler_list(c, e);
+ case Tuple_kind:
+ return compiler_tuple(c, e);
+ }
+ return 1;
}
static int
compiler_augassign(struct compiler *c, stmt_ty s)
{
- expr_ty e = s->v.AugAssign.target;
- expr_ty auge;
-
- assert(s->kind == AugAssign_kind);
-
- switch (e->kind) {
- case Attribute_kind:
- auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
- AugLoad, e->lineno, e->col_offset, c->c_arena);
- if (auge == NULL)
- return 0;
- VISIT(c, expr, auge);
- VISIT(c, expr, s->v.AugAssign.value);
- ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
- auge->v.Attribute.ctx = AugStore;
- VISIT(c, expr, auge);
- break;
- case Subscript_kind:
- auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
- AugLoad, e->lineno, e->col_offset, c->c_arena);
- if (auge == NULL)
- return 0;
- VISIT(c, expr, auge);
- VISIT(c, expr, s->v.AugAssign.value);
- ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
- auge->v.Subscript.ctx = AugStore;
- VISIT(c, expr, auge);
- break;
- case Name_kind:
- if (!compiler_nameop(c, e->v.Name.id, Load))
- return 0;
- VISIT(c, expr, s->v.AugAssign.value);
- ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
- return compiler_nameop(c, e->v.Name.id, Store);
- default:
- PyErr_Format(PyExc_SystemError,
- "invalid node type (%d) for augmented assignment",
- e->kind);
- return 0;
- }
- return 1;
+ expr_ty e = s->v.AugAssign.target;
+ expr_ty auge;
+
+ assert(s->kind == AugAssign_kind);
+
+ switch (e->kind) {
+ case Attribute_kind:
+ auge = Attribute(e->v.Attribute.value, e->v.Attribute.attr,
+ AugLoad, e->lineno, e->col_offset, c->c_arena);
+ if (auge == NULL)
+ return 0;
+ VISIT(c, expr, auge);
+ VISIT(c, expr, s->v.AugAssign.value);
+ ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
+ auge->v.Attribute.ctx = AugStore;
+ VISIT(c, expr, auge);
+ break;
+ case Subscript_kind:
+ auge = Subscript(e->v.Subscript.value, e->v.Subscript.slice,
+ AugLoad, e->lineno, e->col_offset, c->c_arena);
+ if (auge == NULL)
+ return 0;
+ VISIT(c, expr, auge);
+ VISIT(c, expr, s->v.AugAssign.value);
+ ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
+ auge->v.Subscript.ctx = AugStore;
+ VISIT(c, expr, auge);
+ break;
+ case Name_kind:
+ if (!compiler_nameop(c, e->v.Name.id, Load))
+ return 0;
+ VISIT(c, expr, s->v.AugAssign.value);
+ ADDOP(c, inplace_binop(c, s->v.AugAssign.op));
+ return compiler_nameop(c, e->v.Name.id, Store);
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "invalid node type (%d) for augmented assignment",
+ e->kind);
+ return 0;
+ }
+ return 1;
}
static int
compiler_push_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
{
- struct fblockinfo *f;
- if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
- PyErr_SetString(PyExc_SystemError,
- "too many statically nested blocks");
- return 0;
- }
- f = &c->u->u_fblock[c->u->u_nfblocks++];
- f->fb_type = t;
- f->fb_block = b;
- return 1;
+ struct fblockinfo *f;
+ if (c->u->u_nfblocks >= CO_MAXBLOCKS) {
+ PyErr_SetString(PyExc_SystemError,
+ "too many statically nested blocks");
+ return 0;
+ }
+ f = &c->u->u_fblock[c->u->u_nfblocks++];
+ f->fb_type = t;
+ f->fb_block = b;
+ return 1;
}
static void
compiler_pop_fblock(struct compiler *c, enum fblocktype t, basicblock *b)
{
- struct compiler_unit *u = c->u;
- assert(u->u_nfblocks > 0);
- u->u_nfblocks--;
- assert(u->u_fblock[u->u_nfblocks].fb_type == t);
- assert(u->u_fblock[u->u_nfblocks].fb_block == b);
+ struct compiler_unit *u = c->u;
+ assert(u->u_nfblocks > 0);
+ u->u_nfblocks--;
+ assert(u->u_fblock[u->u_nfblocks].fb_type == t);
+ assert(u->u_fblock[u->u_nfblocks].fb_block == b);
}
static int
compiler_in_loop(struct compiler *c) {
- int i;
- struct compiler_unit *u = c->u;
- for (i = 0; i < u->u_nfblocks; ++i) {
- if (u->u_fblock[i].fb_type == LOOP)
- return 1;
- }
- return 0;
+ int i;
+ struct compiler_unit *u = c->u;
+ for (i = 0; i < u->u_nfblocks; ++i) {
+ if (u->u_fblock[i].fb_type == LOOP)
+ return 1;
+ }
+ return 0;
}
/* Raises a SyntaxError and returns 0.
If something goes wrong, a different exception may be raised.
@@ -3203,205 +3203,205 @@ compiler_in_loop(struct compiler *c) {
static int
compiler_error(struct compiler *c, const char *errstr)
{
- PyObject *loc;
- PyObject *u = NULL, *v = NULL;
-
- loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
- if (!loc) {
- Py_INCREF(Py_None);
- loc = Py_None;
- }
- u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
- Py_None, loc);
- if (!u)
- goto exit;
- v = Py_BuildValue("(zO)", errstr, u);
- if (!v)
- goto exit;
- PyErr_SetObject(PyExc_SyntaxError, v);
+ PyObject *loc;
+ PyObject *u = NULL, *v = NULL;
+
+ loc = PyErr_ProgramText(c->c_filename, c->u->u_lineno);
+ if (!loc) {
+ Py_INCREF(Py_None);
+ loc = Py_None;
+ }
+ u = Py_BuildValue("(ziOO)", c->c_filename, c->u->u_lineno,
+ Py_None, loc);
+ if (!u)
+ goto exit;
+ v = Py_BuildValue("(zO)", errstr, u);
+ if (!v)
+ goto exit;
+ PyErr_SetObject(PyExc_SyntaxError, v);
exit:
- Py_DECREF(loc);
- Py_XDECREF(u);
- Py_XDECREF(v);
- return 0;
-}
-
-static int
-compiler_handle_subscr(struct compiler *c, const char *kind,
- expr_context_ty ctx)
-{
- int op = 0;
-
- /* XXX this code is duplicated */
- switch (ctx) {
- case AugLoad: /* fall through to Load */
- case Load: op = BINARY_SUBSCR; break;
- case AugStore:/* fall through to Store */
- case Store: op = STORE_SUBSCR; break;
- case Del: op = DELETE_SUBSCR; break;
- case Param:
- PyErr_Format(PyExc_SystemError,
- "invalid %s kind %d in subscript\n",
- kind, ctx);
- return 0;
- }
- if (ctx == AugLoad) {
- ADDOP_I(c, DUP_TOPX, 2);
- }
- else if (ctx == AugStore) {
- ADDOP(c, ROT_THREE);
- }
- ADDOP(c, op);
- return 1;
+ Py_DECREF(loc);
+ Py_XDECREF(u);
+ Py_XDECREF(v);
+ return 0;
+}
+
+static int
+compiler_handle_subscr(struct compiler *c, const char *kind,
+ expr_context_ty ctx)
+{
+ int op = 0;
+
+ /* XXX this code is duplicated */
+ switch (ctx) {
+ case AugLoad: /* fall through to Load */
+ case Load: op = BINARY_SUBSCR; break;
+ case AugStore:/* fall through to Store */
+ case Store: op = STORE_SUBSCR; break;
+ case Del: op = DELETE_SUBSCR; break;
+ case Param:
+ PyErr_Format(PyExc_SystemError,
+ "invalid %s kind %d in subscript\n",
+ kind, ctx);
+ return 0;
+ }
+ if (ctx == AugLoad) {
+ ADDOP_I(c, DUP_TOPX, 2);
+ }
+ else if (ctx == AugStore) {
+ ADDOP(c, ROT_THREE);
+ }
+ ADDOP(c, op);
+ return 1;
}
static int
compiler_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
{
- int n = 2;
- assert(s->kind == Slice_kind);
-
- /* only handles the cases where BUILD_SLICE is emitted */
- if (s->v.Slice.lower) {
- VISIT(c, expr, s->v.Slice.lower);
- }
- else {
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- }
-
- if (s->v.Slice.upper) {
- VISIT(c, expr, s->v.Slice.upper);
- }
- else {
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- }
-
- if (s->v.Slice.step) {
- n++;
- VISIT(c, expr, s->v.Slice.step);
- }
- ADDOP_I(c, BUILD_SLICE, n);
- return 1;
+ int n = 2;
+ assert(s->kind == Slice_kind);
+
+ /* only handles the cases where BUILD_SLICE is emitted */
+ if (s->v.Slice.lower) {
+ VISIT(c, expr, s->v.Slice.lower);
+ }
+ else {
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ }
+
+ if (s->v.Slice.upper) {
+ VISIT(c, expr, s->v.Slice.upper);
+ }
+ else {
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ }
+
+ if (s->v.Slice.step) {
+ n++;
+ VISIT(c, expr, s->v.Slice.step);
+ }
+ ADDOP_I(c, BUILD_SLICE, n);
+ return 1;
}
static int
compiler_simple_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
{
- int op = 0, slice_offset = 0, stack_count = 0;
-
- assert(s->v.Slice.step == NULL);
- if (s->v.Slice.lower) {
- slice_offset++;
- stack_count++;
- if (ctx != AugStore)
- VISIT(c, expr, s->v.Slice.lower);
- }
- if (s->v.Slice.upper) {
- slice_offset += 2;
- stack_count++;
- if (ctx != AugStore)
- VISIT(c, expr, s->v.Slice.upper);
- }
-
- if (ctx == AugLoad) {
- switch (stack_count) {
- case 0: ADDOP(c, DUP_TOP); break;
- case 1: ADDOP_I(c, DUP_TOPX, 2); break;
- case 2: ADDOP_I(c, DUP_TOPX, 3); break;
- }
- }
- else if (ctx == AugStore) {
- switch (stack_count) {
- case 0: ADDOP(c, ROT_TWO); break;
- case 1: ADDOP(c, ROT_THREE); break;
- case 2: ADDOP(c, ROT_FOUR); break;
- }
- }
-
- switch (ctx) {
- case AugLoad: /* fall through to Load */
- case Load: op = SLICE; break;
- case AugStore:/* fall through to Store */
- case Store: op = STORE_SLICE; break;
- case Del: op = DELETE_SLICE; break;
- case Param:
- default:
- PyErr_SetString(PyExc_SystemError,
- "param invalid in simple slice");
- return 0;
- }
-
- ADDOP(c, op + slice_offset);
- return 1;
-}
-
-static int
-compiler_visit_nested_slice(struct compiler *c, slice_ty s,
- expr_context_ty ctx)
-{
- switch (s->kind) {
- case Ellipsis_kind:
- ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
- break;
- case Slice_kind:
- return compiler_slice(c, s, ctx);
- case Index_kind:
- VISIT(c, expr, s->v.Index.value);
- break;
- case ExtSlice_kind:
- default:
- PyErr_SetString(PyExc_SystemError,
- "extended slice invalid in nested slice");
- return 0;
- }
- return 1;
+ int op = 0, slice_offset = 0, stack_count = 0;
+
+ assert(s->v.Slice.step == NULL);
+ if (s->v.Slice.lower) {
+ slice_offset++;
+ stack_count++;
+ if (ctx != AugStore)
+ VISIT(c, expr, s->v.Slice.lower);
+ }
+ if (s->v.Slice.upper) {
+ slice_offset += 2;
+ stack_count++;
+ if (ctx != AugStore)
+ VISIT(c, expr, s->v.Slice.upper);
+ }
+
+ if (ctx == AugLoad) {
+ switch (stack_count) {
+ case 0: ADDOP(c, DUP_TOP); break;
+ case 1: ADDOP_I(c, DUP_TOPX, 2); break;
+ case 2: ADDOP_I(c, DUP_TOPX, 3); break;
+ }
+ }
+ else if (ctx == AugStore) {
+ switch (stack_count) {
+ case 0: ADDOP(c, ROT_TWO); break;
+ case 1: ADDOP(c, ROT_THREE); break;
+ case 2: ADDOP(c, ROT_FOUR); break;
+ }
+ }
+
+ switch (ctx) {
+ case AugLoad: /* fall through to Load */
+ case Load: op = SLICE; break;
+ case AugStore:/* fall through to Store */
+ case Store: op = STORE_SLICE; break;
+ case Del: op = DELETE_SLICE; break;
+ case Param:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "param invalid in simple slice");
+ return 0;
+ }
+
+ ADDOP(c, op + slice_offset);
+ return 1;
+}
+
+static int
+compiler_visit_nested_slice(struct compiler *c, slice_ty s,
+ expr_context_ty ctx)
+{
+ switch (s->kind) {
+ case Ellipsis_kind:
+ ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
+ break;
+ case Slice_kind:
+ return compiler_slice(c, s, ctx);
+ case Index_kind:
+ VISIT(c, expr, s->v.Index.value);
+ break;
+ case ExtSlice_kind:
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "extended slice invalid in nested slice");
+ return 0;
+ }
+ return 1;
}
static int
compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
{
- char * kindname = NULL;
- switch (s->kind) {
- case Index_kind:
- kindname = "index";
- if (ctx != AugStore) {
- VISIT(c, expr, s->v.Index.value);
- }
- break;
- case Ellipsis_kind:
- kindname = "ellipsis";
- if (ctx != AugStore) {
- ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
- }
- break;
- case Slice_kind:
- kindname = "slice";
- if (!s->v.Slice.step)
- return compiler_simple_slice(c, s, ctx);
- if (ctx != AugStore) {
- if (!compiler_slice(c, s, ctx))
- return 0;
- }
- break;
- case ExtSlice_kind:
- kindname = "extended slice";
- if (ctx != AugStore) {
- int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
- for (i = 0; i < n; i++) {
- slice_ty sub = (slice_ty)asdl_seq_GET(
- s->v.ExtSlice.dims, i);
- if (!compiler_visit_nested_slice(c, sub, ctx))
- return 0;
- }
- ADDOP_I(c, BUILD_TUPLE, n);
- }
- break;
- default:
- PyErr_Format(PyExc_SystemError,
- "invalid subscript kind %d", s->kind);
- return 0;
- }
- return compiler_handle_subscr(c, kindname, ctx);
+ char * kindname = NULL;
+ switch (s->kind) {
+ case Index_kind:
+ kindname = "index";
+ if (ctx != AugStore) {
+ VISIT(c, expr, s->v.Index.value);
+ }
+ break;
+ case Ellipsis_kind:
+ kindname = "ellipsis";
+ if (ctx != AugStore) {
+ ADDOP_O(c, LOAD_CONST, Py_Ellipsis, consts);
+ }
+ break;
+ case Slice_kind:
+ kindname = "slice";
+ if (!s->v.Slice.step)
+ return compiler_simple_slice(c, s, ctx);
+ if (ctx != AugStore) {
+ if (!compiler_slice(c, s, ctx))
+ return 0;
+ }
+ break;
+ case ExtSlice_kind:
+ kindname = "extended slice";
+ if (ctx != AugStore) {
+ int i, n = asdl_seq_LEN(s->v.ExtSlice.dims);
+ for (i = 0; i < n; i++) {
+ slice_ty sub = (slice_ty)asdl_seq_GET(
+ s->v.ExtSlice.dims, i);
+ if (!compiler_visit_nested_slice(c, sub, ctx))
+ return 0;
+ }
+ ADDOP_I(c, BUILD_TUPLE, n);
+ }
+ break;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "invalid subscript kind %d", s->kind);
+ return 0;
+ }
+ return compiler_handle_subscr(c, kindname, ctx);
}
@@ -3414,73 +3414,73 @@ compiler_visit_slice(struct compiler *c, slice_ty s, expr_context_ty ctx)
*/
struct assembler {
- PyObject *a_bytecode; /* string containing bytecode */
- int a_offset; /* offset into bytecode */
- int a_nblocks; /* number of reachable blocks */
- basicblock **a_postorder; /* list of blocks in dfs postorder */
- PyObject *a_lnotab; /* string containing lnotab */
- int a_lnotab_off; /* offset into lnotab */
- int a_lineno; /* last lineno of emitted instruction */
- int a_lineno_off; /* bytecode offset of last lineno */
+ PyObject *a_bytecode; /* string containing bytecode */
+ int a_offset; /* offset into bytecode */
+ int a_nblocks; /* number of reachable blocks */
+ basicblock **a_postorder; /* list of blocks in dfs postorder */
+ PyObject *a_lnotab; /* string containing lnotab */
+ int a_lnotab_off; /* offset into lnotab */
+ int a_lineno; /* last lineno of emitted instruction */
+ int a_lineno_off; /* bytecode offset of last lineno */
};
static void
dfs(struct compiler *c, basicblock *b, struct assembler *a)
{
- int i;
- struct instr *instr = NULL;
-
- if (b->b_seen)
- return;
- b->b_seen = 1;
- if (b->b_next != NULL)
- dfs(c, b->b_next, a);
- for (i = 0; i < b->b_iused; i++) {
- instr = &b->b_instr[i];
- if (instr->i_jrel || instr->i_jabs)
- dfs(c, instr->i_target, a);
- }
- a->a_postorder[a->a_nblocks++] = b;
+ int i;
+ struct instr *instr = NULL;
+
+ if (b->b_seen)
+ return;
+ b->b_seen = 1;
+ if (b->b_next != NULL)
+ dfs(c, b->b_next, a);
+ for (i = 0; i < b->b_iused; i++) {
+ instr = &b->b_instr[i];
+ if (instr->i_jrel || instr->i_jabs)
+ dfs(c, instr->i_target, a);
+ }
+ a->a_postorder[a->a_nblocks++] = b;
}
static int
stackdepth_walk(struct compiler *c, basicblock *b, int depth, int maxdepth)
{
- int i, target_depth;
- struct instr *instr;
- if (b->b_seen || b->b_startdepth >= depth)
- return maxdepth;
- b->b_seen = 1;
- b->b_startdepth = depth;
- for (i = 0; i < b->b_iused; i++) {
- instr = &b->b_instr[i];
- depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
- if (depth > maxdepth)
- maxdepth = depth;
- assert(depth >= 0); /* invalid code or bug in stackdepth() */
- if (instr->i_jrel || instr->i_jabs) {
- target_depth = depth;
- if (instr->i_opcode == FOR_ITER) {
- target_depth = depth-2;
- } else if (instr->i_opcode == SETUP_FINALLY ||
- instr->i_opcode == SETUP_EXCEPT) {
- target_depth = depth+3;
- if (target_depth > maxdepth)
- maxdepth = target_depth;
- }
- maxdepth = stackdepth_walk(c, instr->i_target,
- target_depth, maxdepth);
- if (instr->i_opcode == JUMP_ABSOLUTE ||
- instr->i_opcode == JUMP_FORWARD) {
- goto out; /* remaining code is dead */
- }
- }
- }
- if (b->b_next)
- maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
+ int i, target_depth;
+ struct instr *instr;
+ if (b->b_seen || b->b_startdepth >= depth)
+ return maxdepth;
+ b->b_seen = 1;
+ b->b_startdepth = depth;
+ for (i = 0; i < b->b_iused; i++) {
+ instr = &b->b_instr[i];
+ depth += opcode_stack_effect(instr->i_opcode, instr->i_oparg);
+ if (depth > maxdepth)
+ maxdepth = depth;
+ assert(depth >= 0); /* invalid code or bug in stackdepth() */
+ if (instr->i_jrel || instr->i_jabs) {
+ target_depth = depth;
+ if (instr->i_opcode == FOR_ITER) {
+ target_depth = depth-2;
+ } else if (instr->i_opcode == SETUP_FINALLY ||
+ instr->i_opcode == SETUP_EXCEPT) {
+ target_depth = depth+3;
+ if (target_depth > maxdepth)
+ maxdepth = target_depth;
+ }
+ maxdepth = stackdepth_walk(c, instr->i_target,
+ target_depth, maxdepth);
+ if (instr->i_opcode == JUMP_ABSOLUTE ||
+ instr->i_opcode == JUMP_FORWARD) {
+ goto out; /* remaining code is dead */
+ }
+ }
+ }
+ if (b->b_next)
+ maxdepth = stackdepth_walk(c, b->b_next, depth, maxdepth);
out:
- b->b_seen = 0;
- return maxdepth;
+ b->b_seen = 0;
+ return maxdepth;
}
/* Find the flow path that needs the largest stack. We assume that
@@ -3489,49 +3489,49 @@ out:
static int
stackdepth(struct compiler *c)
{
- basicblock *b, *entryblock;
- entryblock = NULL;
- for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
- b->b_seen = 0;
- b->b_startdepth = INT_MIN;
- entryblock = b;
- }
- if (!entryblock)
- return 0;
- return stackdepth_walk(c, entryblock, 0, 0);
+ basicblock *b, *entryblock;
+ entryblock = NULL;
+ for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
+ b->b_seen = 0;
+ b->b_startdepth = INT_MIN;
+ entryblock = b;
+ }
+ if (!entryblock)
+ return 0;
+ return stackdepth_walk(c, entryblock, 0, 0);
}
static int
assemble_init(struct assembler *a, int nblocks, int firstlineno)
{
- memset(a, 0, sizeof(struct assembler));
- a->a_lineno = firstlineno;
- a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
- if (!a->a_bytecode)
- return 0;
- a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
- if (!a->a_lnotab)
- return 0;
- if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
- PyErr_NoMemory();
- return 0;
- }
- a->a_postorder = (basicblock **)PyObject_Malloc(
- sizeof(basicblock *) * nblocks);
- if (!a->a_postorder) {
- PyErr_NoMemory();
- return 0;
- }
- return 1;
+ memset(a, 0, sizeof(struct assembler));
+ a->a_lineno = firstlineno;
+ a->a_bytecode = PyString_FromStringAndSize(NULL, DEFAULT_CODE_SIZE);
+ if (!a->a_bytecode)
+ return 0;
+ a->a_lnotab = PyString_FromStringAndSize(NULL, DEFAULT_LNOTAB_SIZE);
+ if (!a->a_lnotab)
+ return 0;
+ if (nblocks > PY_SIZE_MAX / sizeof(basicblock *)) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ a->a_postorder = (basicblock **)PyObject_Malloc(
+ sizeof(basicblock *) * nblocks);
+ if (!a->a_postorder) {
+ PyErr_NoMemory();
+ return 0;
+ }
+ return 1;
}
static void
assemble_free(struct assembler *a)
{
- Py_XDECREF(a->a_bytecode);
- Py_XDECREF(a->a_lnotab);
- if (a->a_postorder)
- PyObject_Free(a->a_postorder);
+ Py_XDECREF(a->a_bytecode);
+ Py_XDECREF(a->a_lnotab);
+ if (a->a_postorder)
+ PyObject_Free(a->a_postorder);
}
/* Return the size of a basic block in bytes. */
@@ -3539,22 +3539,22 @@ assemble_free(struct assembler *a)
static int
instrsize(struct instr *instr)
{
- if (!instr->i_hasarg)
- return 1; /* 1 byte for the opcode*/
- if (instr->i_oparg > 0xffff)
- return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
- return 3; /* 1 (opcode) + 2 (oparg) */
+ if (!instr->i_hasarg)
+ return 1; /* 1 byte for the opcode*/
+ if (instr->i_oparg > 0xffff)
+ return 6; /* 1 (opcode) + 1 (EXTENDED_ARG opcode) + 2 (oparg) + 2(oparg extended) */
+ return 3; /* 1 (opcode) + 2 (oparg) */
}
static int
blocksize(basicblock *b)
{
- int i;
- int size = 0;
+ int i;
+ int size = 0;
- for (i = 0; i < b->b_iused; i++)
- size += instrsize(&b->b_instr[i]);
- return size;
+ for (i = 0; i < b->b_iused; i++)
+ size += instrsize(&b->b_instr[i]);
+ return size;
}
/* Appends a pair to the end of the line number table, a_lnotab, representing
@@ -3564,94 +3564,94 @@ blocksize(basicblock *b)
static int
assemble_lnotab(struct assembler *a, struct instr *i)
{
- int d_bytecode, d_lineno;
- int len;
- unsigned char *lnotab;
-
- d_bytecode = a->a_offset - a->a_lineno_off;
- d_lineno = i->i_lineno - a->a_lineno;
-
- assert(d_bytecode >= 0);
- assert(d_lineno >= 0);
-
- if(d_bytecode == 0 && d_lineno == 0)
- return 1;
-
- if (d_bytecode > 255) {
- int j, nbytes, ncodes = d_bytecode / 255;
- nbytes = a->a_lnotab_off + 2 * ncodes;
- len = PyString_GET_SIZE(a->a_lnotab);
- if (nbytes >= len) {
- if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
- len = nbytes;
- else if (len <= INT_MAX / 2)
- len *= 2;
- else {
- PyErr_NoMemory();
- return 0;
- }
- if (_PyString_Resize(&a->a_lnotab, len) < 0)
- return 0;
- }
- lnotab = (unsigned char *)
- PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
- for (j = 0; j < ncodes; j++) {
- *lnotab++ = 255;
- *lnotab++ = 0;
- }
- d_bytecode -= ncodes * 255;
- a->a_lnotab_off += ncodes * 2;
- }
- assert(d_bytecode <= 255);
- if (d_lineno > 255) {
- int j, nbytes, ncodes = d_lineno / 255;
- nbytes = a->a_lnotab_off + 2 * ncodes;
- len = PyString_GET_SIZE(a->a_lnotab);
- if (nbytes >= len) {
- if ((len <= INT_MAX / 2) && len * 2 < nbytes)
- len = nbytes;
- else if (len <= INT_MAX / 2)
- len *= 2;
- else {
- PyErr_NoMemory();
- return 0;
- }
- if (_PyString_Resize(&a->a_lnotab, len) < 0)
- return 0;
- }
- lnotab = (unsigned char *)
- PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
- *lnotab++ = d_bytecode;
- *lnotab++ = 255;
- d_bytecode = 0;
- for (j = 1; j < ncodes; j++) {
- *lnotab++ = 0;
- *lnotab++ = 255;
- }
- d_lineno -= ncodes * 255;
- a->a_lnotab_off += ncodes * 2;
- }
-
- len = PyString_GET_SIZE(a->a_lnotab);
- if (a->a_lnotab_off + 2 >= len) {
- if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
- return 0;
- }
- lnotab = (unsigned char *)
- PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
-
- a->a_lnotab_off += 2;
- if (d_bytecode) {
- *lnotab++ = d_bytecode;
- *lnotab++ = d_lineno;
- }
- else { /* First line of a block; def stmt, etc. */
- *lnotab++ = 0;
- *lnotab++ = d_lineno;
- }
- a->a_lineno = i->i_lineno;
- a->a_lineno_off = a->a_offset;
- return 1;
+ int d_bytecode, d_lineno;
+ int len;
+ unsigned char *lnotab;
+
+ d_bytecode = a->a_offset - a->a_lineno_off;
+ d_lineno = i->i_lineno - a->a_lineno;
+
+ assert(d_bytecode >= 0);
+ assert(d_lineno >= 0);
+
+ if(d_bytecode == 0 && d_lineno == 0)
+ return 1;
+
+ if (d_bytecode > 255) {
+ int j, nbytes, ncodes = d_bytecode / 255;
+ nbytes = a->a_lnotab_off + 2 * ncodes;
+ len = PyString_GET_SIZE(a->a_lnotab);
+ if (nbytes >= len) {
+ if ((len <= INT_MAX / 2) && (len * 2 < nbytes))
+ len = nbytes;
+ else if (len <= INT_MAX / 2)
+ len *= 2;
+ else {
+ PyErr_NoMemory();
+ return 0;
+ }
+ if (_PyString_Resize(&a->a_lnotab, len) < 0)
+ return 0;
+ }
+ lnotab = (unsigned char *)
+ PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
+ for (j = 0; j < ncodes; j++) {
+ *lnotab++ = 255;
+ *lnotab++ = 0;
+ }
+ d_bytecode -= ncodes * 255;
+ a->a_lnotab_off += ncodes * 2;
+ }
+ assert(d_bytecode <= 255);
+ if (d_lineno > 255) {
+ int j, nbytes, ncodes = d_lineno / 255;
+ nbytes = a->a_lnotab_off + 2 * ncodes;
+ len = PyString_GET_SIZE(a->a_lnotab);
+ if (nbytes >= len) {
+ if ((len <= INT_MAX / 2) && len * 2 < nbytes)
+ len = nbytes;
+ else if (len <= INT_MAX / 2)
+ len *= 2;
+ else {
+ PyErr_NoMemory();
+ return 0;
+ }
+ if (_PyString_Resize(&a->a_lnotab, len) < 0)
+ return 0;
+ }
+ lnotab = (unsigned char *)
+ PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
+ *lnotab++ = d_bytecode;
+ *lnotab++ = 255;
+ d_bytecode = 0;
+ for (j = 1; j < ncodes; j++) {
+ *lnotab++ = 0;
+ *lnotab++ = 255;
+ }
+ d_lineno -= ncodes * 255;
+ a->a_lnotab_off += ncodes * 2;
+ }
+
+ len = PyString_GET_SIZE(a->a_lnotab);
+ if (a->a_lnotab_off + 2 >= len) {
+ if (_PyString_Resize(&a->a_lnotab, len * 2) < 0)
+ return 0;
+ }
+ lnotab = (unsigned char *)
+ PyString_AS_STRING(a->a_lnotab) + a->a_lnotab_off;
+
+ a->a_lnotab_off += 2;
+ if (d_bytecode) {
+ *lnotab++ = d_bytecode;
+ *lnotab++ = d_lineno;
+ }
+ else { /* First line of a block; def stmt, etc. */
+ *lnotab++ = 0;
+ *lnotab++ = d_lineno;
+ }
+ a->a_lineno = i->i_lineno;
+ a->a_lineno_off = a->a_offset;
+ return 1;
}
/* assemble_emit()
@@ -3662,226 +3662,226 @@ assemble_lnotab(struct assembler *a, struct instr *i)
static int
assemble_emit(struct assembler *a, struct instr *i)
{
- int size, arg = 0, ext = 0;
- Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
- char *code;
-
- size = instrsize(i);
- if (i->i_hasarg) {
- arg = i->i_oparg;
- ext = arg >> 16;
- }
- if (i->i_lineno && !assemble_lnotab(a, i))
- return 0;
- if (a->a_offset + size >= len) {
- if (len > PY_SSIZE_T_MAX / 2)
- return 0;
- if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
- return 0;
- }
- code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
- a->a_offset += size;
- if (size == 6) {
- assert(i->i_hasarg);
- *code++ = (char)EXTENDED_ARG;
- *code++ = ext & 0xff;
- *code++ = ext >> 8;
- arg &= 0xffff;
- }
- *code++ = i->i_opcode;
- if (i->i_hasarg) {
- assert(size == 3 || size == 6);
- *code++ = arg & 0xff;
- *code++ = arg >> 8;
- }
- return 1;
+ int size, arg = 0, ext = 0;
+ Py_ssize_t len = PyString_GET_SIZE(a->a_bytecode);
+ char *code;
+
+ size = instrsize(i);
+ if (i->i_hasarg) {
+ arg = i->i_oparg;
+ ext = arg >> 16;
+ }
+ if (i->i_lineno && !assemble_lnotab(a, i))
+ return 0;
+ if (a->a_offset + size >= len) {
+ if (len > PY_SSIZE_T_MAX / 2)
+ return 0;
+ if (_PyString_Resize(&a->a_bytecode, len * 2) < 0)
+ return 0;
+ }
+ code = PyString_AS_STRING(a->a_bytecode) + a->a_offset;
+ a->a_offset += size;
+ if (size == 6) {
+ assert(i->i_hasarg);
+ *code++ = (char)EXTENDED_ARG;
+ *code++ = ext & 0xff;
+ *code++ = ext >> 8;
+ arg &= 0xffff;
+ }
+ *code++ = i->i_opcode;
+ if (i->i_hasarg) {
+ assert(size == 3 || size == 6);
+ *code++ = arg & 0xff;
+ *code++ = arg >> 8;
+ }
+ return 1;
}
static void
assemble_jump_offsets(struct assembler *a, struct compiler *c)
{
- basicblock *b;
- int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
- int i;
-
- /* Compute the size of each block and fixup jump args.
- Replace block pointer with position in bytecode. */
- do {
- totsize = 0;
- for (i = a->a_nblocks - 1; i >= 0; i--) {
- b = a->a_postorder[i];
- bsize = blocksize(b);
- b->b_offset = totsize;
- totsize += bsize;
- }
- last_extended_arg_count = extended_arg_count;
- extended_arg_count = 0;
- for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
- bsize = b->b_offset;
- for (i = 0; i < b->b_iused; i++) {
- struct instr *instr = &b->b_instr[i];
- /* Relative jumps are computed relative to
- the instruction pointer after fetching
- the jump instruction.
- */
- bsize += instrsize(instr);
- if (instr->i_jabs)
- instr->i_oparg = instr->i_target->b_offset;
- else if (instr->i_jrel) {
- int delta = instr->i_target->b_offset - bsize;
- instr->i_oparg = delta;
- }
- else
- continue;
- if (instr->i_oparg > 0xffff)
- extended_arg_count++;
- }
- }
-
- /* XXX: This is an awful hack that could hurt performance, but
- on the bright side it should work until we come up
- with a better solution.
-
- The issue is that in the first loop blocksize() is called
- which calls instrsize() which requires i_oparg be set
- appropriately. There is a bootstrap problem because
- i_oparg is calculated in the second loop above.
-
- So we loop until we stop seeing new EXTENDED_ARGs.
- The only EXTENDED_ARGs that could be popping up are
- ones in jump instructions. So this should converge
- fairly quickly.
- */
- } while (last_extended_arg_count != extended_arg_count);
+ basicblock *b;
+ int bsize, totsize, extended_arg_count = 0, last_extended_arg_count;
+ int i;
+
+ /* Compute the size of each block and fixup jump args.
+ Replace block pointer with position in bytecode. */
+ do {
+ totsize = 0;
+ for (i = a->a_nblocks - 1; i >= 0; i--) {
+ b = a->a_postorder[i];
+ bsize = blocksize(b);
+ b->b_offset = totsize;
+ totsize += bsize;
+ }
+ last_extended_arg_count = extended_arg_count;
+ extended_arg_count = 0;
+ for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
+ bsize = b->b_offset;
+ for (i = 0; i < b->b_iused; i++) {
+ struct instr *instr = &b->b_instr[i];
+ /* Relative jumps are computed relative to
+ the instruction pointer after fetching
+ the jump instruction.
+ */
+ bsize += instrsize(instr);
+ if (instr->i_jabs)
+ instr->i_oparg = instr->i_target->b_offset;
+ else if (instr->i_jrel) {
+ int delta = instr->i_target->b_offset - bsize;
+ instr->i_oparg = delta;
+ }
+ else
+ continue;
+ if (instr->i_oparg > 0xffff)
+ extended_arg_count++;
+ }
+ }
+
+ /* XXX: This is an awful hack that could hurt performance, but
+ on the bright side it should work until we come up
+ with a better solution.
+
+ The issue is that in the first loop blocksize() is called
+ which calls instrsize() which requires i_oparg be set
+ appropriately. There is a bootstrap problem because
+ i_oparg is calculated in the second loop above.
+
+ So we loop until we stop seeing new EXTENDED_ARGs.
+ The only EXTENDED_ARGs that could be popping up are
+ ones in jump instructions. So this should converge
+ fairly quickly.
+ */
+ } while (last_extended_arg_count != extended_arg_count);
}
static PyObject *
dict_keys_inorder(PyObject *dict, int offset)
{
- PyObject *tuple, *k, *v;
- Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
-
- tuple = PyTuple_New(size);
- if (tuple == NULL)
- return NULL;
- while (PyDict_Next(dict, &pos, &k, &v)) {
- i = PyInt_AS_LONG(v);
- /* The keys of the dictionary are tuples. (see compiler_add_o)
- The object we want is always first, though. */
- k = PyTuple_GET_ITEM(k, 0);
- Py_INCREF(k);
- assert((i - offset) < size);
- assert((i - offset) >= 0);
- PyTuple_SET_ITEM(tuple, i - offset, k);
- }
- return tuple;
+ PyObject *tuple, *k, *v;
+ Py_ssize_t i, pos = 0, size = PyDict_Size(dict);
+
+ tuple = PyTuple_New(size);
+ if (tuple == NULL)
+ return NULL;
+ while (PyDict_Next(dict, &pos, &k, &v)) {
+ i = PyInt_AS_LONG(v);
+ /* The keys of the dictionary are tuples. (see compiler_add_o)
+ The object we want is always first, though. */
+ k = PyTuple_GET_ITEM(k, 0);
+ Py_INCREF(k);
+ assert((i - offset) < size);
+ assert((i - offset) >= 0);
+ PyTuple_SET_ITEM(tuple, i - offset, k);
+ }
+ return tuple;
}
static int
compute_code_flags(struct compiler *c)
{
- PySTEntryObject *ste = c->u->u_ste;
- int flags = 0, n;
- if (ste->ste_type != ModuleBlock)
- flags |= CO_NEWLOCALS;
- if (ste->ste_type == FunctionBlock) {
- if (!ste->ste_unoptimized)
- flags |= CO_OPTIMIZED;
- if (ste->ste_nested)
- flags |= CO_NESTED;
- if (ste->ste_generator)
- flags |= CO_GENERATOR;
- if (ste->ste_varargs)
- flags |= CO_VARARGS;
- if (ste->ste_varkeywords)
- flags |= CO_VARKEYWORDS;
- }
-
- /* (Only) inherit compilerflags in PyCF_MASK */
- flags |= (c->c_flags->cf_flags & PyCF_MASK);
-
- n = PyDict_Size(c->u->u_freevars);
- if (n < 0)
- return -1;
- if (n == 0) {
- n = PyDict_Size(c->u->u_cellvars);
- if (n < 0)
- return -1;
- if (n == 0) {
- flags |= CO_NOFREE;
- }
- }
-
- return flags;
+ PySTEntryObject *ste = c->u->u_ste;
+ int flags = 0, n;
+ if (ste->ste_type != ModuleBlock)
+ flags |= CO_NEWLOCALS;
+ if (ste->ste_type == FunctionBlock) {
+ if (!ste->ste_unoptimized)
+ flags |= CO_OPTIMIZED;
+ if (ste->ste_nested)
+ flags |= CO_NESTED;
+ if (ste->ste_generator)
+ flags |= CO_GENERATOR;
+ if (ste->ste_varargs)
+ flags |= CO_VARARGS;
+ if (ste->ste_varkeywords)
+ flags |= CO_VARKEYWORDS;
+ }
+
+ /* (Only) inherit compilerflags in PyCF_MASK */
+ flags |= (c->c_flags->cf_flags & PyCF_MASK);
+
+ n = PyDict_Size(c->u->u_freevars);
+ if (n < 0)
+ return -1;
+ if (n == 0) {
+ n = PyDict_Size(c->u->u_cellvars);
+ if (n < 0)
+ return -1;
+ if (n == 0) {
+ flags |= CO_NOFREE;
+ }
+ }
+
+ return flags;
}
static PyCodeObject *
makecode(struct compiler *c, struct assembler *a)
{
- PyObject *tmp;
- PyCodeObject *co = NULL;
- PyObject *consts = NULL;
- PyObject *names = NULL;
- PyObject *varnames = NULL;
- PyObject *filename = NULL;
- PyObject *name = NULL;
- PyObject *freevars = NULL;
- PyObject *cellvars = NULL;
- PyObject *bytecode = NULL;
- int nlocals, flags;
-
- tmp = dict_keys_inorder(c->u->u_consts, 0);
- if (!tmp)
- goto error;
- consts = PySequence_List(tmp); /* optimize_code requires a list */
- Py_DECREF(tmp);
-
- names = dict_keys_inorder(c->u->u_names, 0);
- varnames = dict_keys_inorder(c->u->u_varnames, 0);
- if (!consts || !names || !varnames)
- goto error;
-
- cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
- if (!cellvars)
- goto error;
- freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
- if (!freevars)
- goto error;
- filename = PyString_FromString(c->c_filename);
- if (!filename)
- goto error;
-
- nlocals = PyDict_Size(c->u->u_varnames);
- flags = compute_code_flags(c);
- if (flags < 0)
- goto error;
-
- bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
- if (!bytecode)
- goto error;
-
- tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
- if (!tmp)
- goto error;
- Py_DECREF(consts);
- consts = tmp;
-
- co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
- bytecode, consts, names, varnames,
- freevars, cellvars,
- filename, c->u->u_name,
- c->u->u_firstlineno,
- a->a_lnotab);
+ PyObject *tmp;
+ PyCodeObject *co = NULL;
+ PyObject *consts = NULL;
+ PyObject *names = NULL;
+ PyObject *varnames = NULL;
+ PyObject *filename = NULL;
+ PyObject *name = NULL;
+ PyObject *freevars = NULL;
+ PyObject *cellvars = NULL;
+ PyObject *bytecode = NULL;
+ int nlocals, flags;
+
+ tmp = dict_keys_inorder(c->u->u_consts, 0);
+ if (!tmp)
+ goto error;
+ consts = PySequence_List(tmp); /* optimize_code requires a list */
+ Py_DECREF(tmp);
+
+ names = dict_keys_inorder(c->u->u_names, 0);
+ varnames = dict_keys_inorder(c->u->u_varnames, 0);
+ if (!consts || !names || !varnames)
+ goto error;
+
+ cellvars = dict_keys_inorder(c->u->u_cellvars, 0);
+ if (!cellvars)
+ goto error;
+ freevars = dict_keys_inorder(c->u->u_freevars, PyTuple_Size(cellvars));
+ if (!freevars)
+ goto error;
+ filename = PyString_FromString(c->c_filename);
+ if (!filename)
+ goto error;
+
+ nlocals = PyDict_Size(c->u->u_varnames);
+ flags = compute_code_flags(c);
+ if (flags < 0)
+ goto error;
+
+ bytecode = PyCode_Optimize(a->a_bytecode, consts, names, a->a_lnotab);
+ if (!bytecode)
+ goto error;
+
+ tmp = PyList_AsTuple(consts); /* PyCode_New requires a tuple */
+ if (!tmp)
+ goto error;
+ Py_DECREF(consts);
+ consts = tmp;
+
+ co = PyCode_New(c->u->u_argcount, nlocals, stackdepth(c), flags,
+ bytecode, consts, names, varnames,
+ freevars, cellvars,
+ filename, c->u->u_name,
+ c->u->u_firstlineno,
+ a->a_lnotab);
error:
- Py_XDECREF(consts);
- Py_XDECREF(names);
- Py_XDECREF(varnames);
- Py_XDECREF(filename);
- Py_XDECREF(name);
- Py_XDECREF(freevars);
- Py_XDECREF(cellvars);
- Py_XDECREF(bytecode);
- return co;
+ Py_XDECREF(consts);
+ Py_XDECREF(names);
+ Py_XDECREF(varnames);
+ Py_XDECREF(filename);
+ Py_XDECREF(name);
+ Py_XDECREF(freevars);
+ Py_XDECREF(cellvars);
+ Py_XDECREF(bytecode);
+ return co;
}
@@ -3890,90 +3890,90 @@ makecode(struct compiler *c, struct assembler *a)
static void
dump_instr(const struct instr *i)
{
- const char *jrel = i->i_jrel ? "jrel " : "";
- const char *jabs = i->i_jabs ? "jabs " : "";
- char arg[128];
+ const char *jrel = i->i_jrel ? "jrel " : "";
+ const char *jabs = i->i_jabs ? "jabs " : "";
+ char arg[128];
- *arg = '\0';
- if (i->i_hasarg)
- sprintf(arg, "arg: %d ", i->i_oparg);
+ *arg = '\0';
+ if (i->i_hasarg)
+ sprintf(arg, "arg: %d ", i->i_oparg);
- fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
- i->i_lineno, i->i_opcode, arg, jabs, jrel);
+ fprintf(stderr, "line: %d, opcode: %d %s%s%s\n",
+ i->i_lineno, i->i_opcode, arg, jabs, jrel);
}
static void
dump_basicblock(const basicblock *b)
{
- const char *seen = b->b_seen ? "seen " : "";
- const char *b_return = b->b_return ? "return " : "";
- fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
- b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
- if (b->b_instr) {
- int i;
- for (i = 0; i < b->b_iused; i++) {
- fprintf(stderr, " [%02d] ", i);
- dump_instr(b->b_instr + i);
- }
- }
+ const char *seen = b->b_seen ? "seen " : "";
+ const char *b_return = b->b_return ? "return " : "";
+ fprintf(stderr, "used: %d, depth: %d, offset: %d %s%s\n",
+ b->b_iused, b->b_startdepth, b->b_offset, seen, b_return);
+ if (b->b_instr) {
+ int i;
+ for (i = 0; i < b->b_iused; i++) {
+ fprintf(stderr, " [%02d] ", i);
+ dump_instr(b->b_instr + i);
+ }
+ }
}
#endif
static PyCodeObject *
assemble(struct compiler *c, int addNone)
{
- basicblock *b, *entryblock;
- struct assembler a;
- int i, j, nblocks;
- PyCodeObject *co = NULL;
-
- /* Make sure every block that falls off the end returns None.
- XXX NEXT_BLOCK() isn't quite right, because if the last
- block ends with a jump or return b_next shouldn't set.
- */
- if (!c->u->u_curblock->b_return) {
- NEXT_BLOCK(c);
- if (addNone)
- ADDOP_O(c, LOAD_CONST, Py_None, consts);
- ADDOP(c, RETURN_VALUE);
- }
-
- nblocks = 0;
- entryblock = NULL;
- for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
- nblocks++;
- entryblock = b;
- }
-
- /* Set firstlineno if it wasn't explicitly set. */
- if (!c->u->u_firstlineno) {
- if (entryblock && entryblock->b_instr)
- c->u->u_firstlineno = entryblock->b_instr->i_lineno;
- else
- c->u->u_firstlineno = 1;
- }
- if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
- goto error;
- dfs(c, entryblock, &a);
-
- /* Can't modify the bytecode after computing jump offsets. */
- assemble_jump_offsets(&a, c);
-
- /* Emit code in reverse postorder from dfs. */
- for (i = a.a_nblocks - 1; i >= 0; i--) {
- b = a.a_postorder[i];
- for (j = 0; j < b->b_iused; j++)
- if (!assemble_emit(&a, &b->b_instr[j]))
- goto error;
- }
-
- if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
- goto error;
- if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
- goto error;
-
- co = makecode(c, &a);
+ basicblock *b, *entryblock;
+ struct assembler a;
+ int i, j, nblocks;
+ PyCodeObject *co = NULL;
+
+ /* Make sure every block that falls off the end returns None.
+ XXX NEXT_BLOCK() isn't quite right, because if the last
+ block ends with a jump or return b_next shouldn't set.
+ */
+ if (!c->u->u_curblock->b_return) {
+ NEXT_BLOCK(c);
+ if (addNone)
+ ADDOP_O(c, LOAD_CONST, Py_None, consts);
+ ADDOP(c, RETURN_VALUE);
+ }
+
+ nblocks = 0;
+ entryblock = NULL;
+ for (b = c->u->u_blocks; b != NULL; b = b->b_list) {
+ nblocks++;
+ entryblock = b;
+ }
+
+ /* Set firstlineno if it wasn't explicitly set. */
+ if (!c->u->u_firstlineno) {
+ if (entryblock && entryblock->b_instr)
+ c->u->u_firstlineno = entryblock->b_instr->i_lineno;
+ else
+ c->u->u_firstlineno = 1;
+ }
+ if (!assemble_init(&a, nblocks, c->u->u_firstlineno))
+ goto error;
+ dfs(c, entryblock, &a);
+
+ /* Can't modify the bytecode after computing jump offsets. */
+ assemble_jump_offsets(&a, c);
+
+ /* Emit code in reverse postorder from dfs. */
+ for (i = a.a_nblocks - 1; i >= 0; i--) {
+ b = a.a_postorder[i];
+ for (j = 0; j < b->b_iused; j++)
+ if (!assemble_emit(&a, &b->b_instr[j]))
+ goto error;
+ }
+
+ if (_PyString_Resize(&a.a_lnotab, a.a_lnotab_off) < 0)
+ goto error;
+ if (_PyString_Resize(&a.a_bytecode, a.a_offset) < 0)
+ goto error;
+
+ co = makecode(c, &a);
error:
- assemble_free(&a);
- return co;
+ assemble_free(&a);
+ return co;
}
diff --git a/Python/dynload_aix.c b/Python/dynload_aix.c
index 7a604f2..8d56d7d 100644
--- a/Python/dynload_aix.c
+++ b/Python/dynload_aix.c
@@ -4,10 +4,10 @@
#include "Python.h"
#include "importdl.h"
-#include <ctype.h> /* for isdigit() */
-#include <errno.h> /* for global errno */
-#include <string.h> /* for strerror() */
-#include <stdlib.h> /* for malloc(), free() */
+#include <ctype.h> /* for isdigit() */
+#include <errno.h> /* for global errno */
+#include <string.h> /* for strerror() */
+#include <stdlib.h> /* for malloc(), free() */
#include <sys/ldr.h>
@@ -22,85 +22,85 @@
extern char *Py_GetProgramName(void);
typedef struct Module {
- struct Module *next;
- void *entry;
+ struct Module *next;
+ void *entry;
} Module, *ModulePtr;
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {".so", "rb", C_EXTENSION},
- {"module.so", "rb", C_EXTENSION},
- {0, 0}
+ {".so", "rb", C_EXTENSION},
+ {"module.so", "rb", C_EXTENSION},
+ {0, 0}
};
static int
aix_getoldmodules(void **modlistptr)
{
- register ModulePtr modptr, prevmodptr;
- register struct ld_info *ldiptr;
- register char *ldibuf;
- register int errflag, bufsize = 1024;
- register unsigned int offset;
- char *progname = Py_GetProgramName();
-
- /*
- -- Get the list of loaded modules into ld_info structures.
- */
- if ((ldibuf = malloc(bufsize)) == NULL) {
- PyErr_SetString(PyExc_ImportError, strerror(errno));
- return -1;
- }
- while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1
- && errno == ENOMEM) {
- free(ldibuf);
- bufsize += 1024;
- if ((ldibuf = malloc(bufsize)) == NULL) {
- PyErr_SetString(PyExc_ImportError, strerror(errno));
- return -1;
- }
- }
- if (errflag == -1) {
- PyErr_SetString(PyExc_ImportError, strerror(errno));
- return -1;
- }
- /*
- -- Make the modules list from the ld_info structures.
- */
- ldiptr = (struct ld_info *)ldibuf;
- prevmodptr = NULL;
- do {
- if (strstr(progname, ldiptr->ldinfo_filename) == NULL &&
- strstr(ldiptr->ldinfo_filename, "python") == NULL) {
- /*
- -- Extract only the modules belonging to the main
- -- executable + those containing "python" as a
- -- substring (like the "python[version]" binary or
- -- "libpython[version].a" in case it's a shared lib).
- */
- offset = (unsigned int)ldiptr->ldinfo_next;
- ldiptr = (struct ld_info *)((char*)ldiptr + offset);
- continue;
- }
- if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) {
- PyErr_SetString(PyExc_ImportError, strerror(errno));
- while (*modlistptr) {
- modptr = (ModulePtr)*modlistptr;
- *modlistptr = (void *)modptr->next;
- free(modptr);
- }
- return -1;
- }
- modptr->entry = ldiptr->ldinfo_dataorg;
- modptr->next = NULL;
- if (prevmodptr == NULL)
- *modlistptr = (void *)modptr;
- else
- prevmodptr->next = modptr;
- prevmodptr = modptr;
- offset = (unsigned int)ldiptr->ldinfo_next;
- ldiptr = (struct ld_info *)((char*)ldiptr + offset);
- } while (offset);
- free(ldibuf);
- return 0;
+ register ModulePtr modptr, prevmodptr;
+ register struct ld_info *ldiptr;
+ register char *ldibuf;
+ register int errflag, bufsize = 1024;
+ register unsigned int offset;
+ char *progname = Py_GetProgramName();
+
+ /*
+ -- Get the list of loaded modules into ld_info structures.
+ */
+ if ((ldibuf = malloc(bufsize)) == NULL) {
+ PyErr_SetString(PyExc_ImportError, strerror(errno));
+ return -1;
+ }
+ while ((errflag = loadquery(L_GETINFO, ldibuf, bufsize)) == -1
+ && errno == ENOMEM) {
+ free(ldibuf);
+ bufsize += 1024;
+ if ((ldibuf = malloc(bufsize)) == NULL) {
+ PyErr_SetString(PyExc_ImportError, strerror(errno));
+ return -1;
+ }
+ }
+ if (errflag == -1) {
+ PyErr_SetString(PyExc_ImportError, strerror(errno));
+ return -1;
+ }
+ /*
+ -- Make the modules list from the ld_info structures.
+ */
+ ldiptr = (struct ld_info *)ldibuf;
+ prevmodptr = NULL;
+ do {
+ if (strstr(progname, ldiptr->ldinfo_filename) == NULL &&
+ strstr(ldiptr->ldinfo_filename, "python") == NULL) {
+ /*
+ -- Extract only the modules belonging to the main
+ -- executable + those containing "python" as a
+ -- substring (like the "python[version]" binary or
+ -- "libpython[version].a" in case it's a shared lib).
+ */
+ offset = (unsigned int)ldiptr->ldinfo_next;
+ ldiptr = (struct ld_info *)((char*)ldiptr + offset);
+ continue;
+ }
+ if ((modptr = (ModulePtr)malloc(sizeof(Module))) == NULL) {
+ PyErr_SetString(PyExc_ImportError, strerror(errno));
+ while (*modlistptr) {
+ modptr = (ModulePtr)*modlistptr;
+ *modlistptr = (void *)modptr->next;
+ free(modptr);
+ }
+ return -1;
+ }
+ modptr->entry = ldiptr->ldinfo_dataorg;
+ modptr->next = NULL;
+ if (prevmodptr == NULL)
+ *modlistptr = (void *)modptr;
+ else
+ prevmodptr->next = modptr;
+ prevmodptr = modptr;
+ offset = (unsigned int)ldiptr->ldinfo_next;
+ ldiptr = (struct ld_info *)((char*)ldiptr + offset);
+ } while (offset);
+ free(ldibuf);
+ return 0;
}
@@ -108,76 +108,76 @@ static void
aix_loaderror(const char *pathname)
{
- char *message[1024], errbuf[1024];
- register int i,j;
-
- struct errtab {
- int errNo;
- char *errstr;
- } load_errtab[] = {
- {L_ERROR_TOOMANY, "too many errors, rest skipped."},
- {L_ERROR_NOLIB, "can't load library:"},
- {L_ERROR_UNDEF, "can't find symbol in library:"},
- {L_ERROR_RLDBAD,
- "RLD index out of range or bad relocation type:"},
- {L_ERROR_FORMAT, "not a valid, executable xcoff file:"},
- {L_ERROR_MEMBER,
- "file not an archive or does not contain requested member:"},
- {L_ERROR_TYPE, "symbol table mismatch:"},
- {L_ERROR_ALIGN, "text alignment in file is wrong."},
- {L_ERROR_SYSTEM, "System error:"},
- {L_ERROR_ERRNO, NULL}
- };
-
-#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0]))
+ char *message[1024], errbuf[1024];
+ register int i,j;
+
+ struct errtab {
+ int errNo;
+ char *errstr;
+ } load_errtab[] = {
+ {L_ERROR_TOOMANY, "too many errors, rest skipped."},
+ {L_ERROR_NOLIB, "can't load library:"},
+ {L_ERROR_UNDEF, "can't find symbol in library:"},
+ {L_ERROR_RLDBAD,
+ "RLD index out of range or bad relocation type:"},
+ {L_ERROR_FORMAT, "not a valid, executable xcoff file:"},
+ {L_ERROR_MEMBER,
+ "file not an archive or does not contain requested member:"},
+ {L_ERROR_TYPE, "symbol table mismatch:"},
+ {L_ERROR_ALIGN, "text alignment in file is wrong."},
+ {L_ERROR_SYSTEM, "System error:"},
+ {L_ERROR_ERRNO, NULL}
+ };
+
+#define LOAD_ERRTAB_LEN (sizeof(load_errtab)/sizeof(load_errtab[0]))
#define ERRBUF_APPEND(s) strncat(errbuf, s, sizeof(errbuf)-strlen(errbuf)-1)
- PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname);
-
- if (!loadquery(L_GETMESSAGES, &message[0], sizeof(message))) {
- ERRBUF_APPEND(strerror(errno));
- ERRBUF_APPEND("\n");
- }
- for(i = 0; message[i] && *message[i]; i++) {
- int nerr = atoi(message[i]);
- for (j=0; j<LOAD_ERRTAB_LEN ; j++) {
- if (nerr == load_errtab[j].errNo && load_errtab[j].errstr)
- ERRBUF_APPEND(load_errtab[j].errstr);
- }
- while (isdigit(Py_CHARMASK(*message[i]))) message[i]++ ;
- ERRBUF_APPEND(message[i]);
- ERRBUF_APPEND("\n");
- }
- errbuf[strlen(errbuf)-1] = '\0'; /* trim off last newline */
- PyErr_SetString(PyExc_ImportError, errbuf);
- return;
+ PyOS_snprintf(errbuf, sizeof(errbuf), "from module %.200s ", pathname);
+
+ if (!loadquery(L_GETMESSAGES, &message[0], sizeof(message))) {
+ ERRBUF_APPEND(strerror(errno));
+ ERRBUF_APPEND("\n");
+ }
+ for(i = 0; message[i] && *message[i]; i++) {
+ int nerr = atoi(message[i]);
+ for (j=0; j<LOAD_ERRTAB_LEN ; j++) {
+ if (nerr == load_errtab[j].errNo && load_errtab[j].errstr)
+ ERRBUF_APPEND(load_errtab[j].errstr);
+ }
+ while (isdigit(Py_CHARMASK(*message[i]))) message[i]++ ;
+ ERRBUF_APPEND(message[i]);
+ ERRBUF_APPEND("\n");
+ }
+ errbuf[strlen(errbuf)-1] = '\0'; /* trim off last newline */
+ PyErr_SetString(PyExc_ImportError, errbuf);
+ return;
}
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p;
-
- /*
- -- Invoke load() with L_NOAUTODEFER leaving the imported symbols
- -- of the shared module unresolved. Thus we have to resolve them
- -- explicitly with loadbind. The new module is loaded, then we
- -- resolve its symbols using the list of already loaded modules
- -- (only those that belong to the python executable). Get these
- -- with loadquery(L_GETINFO).
- */
-
- static void *staticmodlistptr = NULL;
-
- if (!staticmodlistptr)
- if (aix_getoldmodules(&staticmodlistptr) == -1)
- return NULL;
- p = (dl_funcptr) aix_load((char *)pathname, L_NOAUTODEFER, 0);
- if (p == NULL) {
- aix_loaderror(pathname);
- return NULL;
- }
-
- return p;
+ dl_funcptr p;
+
+ /*
+ -- Invoke load() with L_NOAUTODEFER leaving the imported symbols
+ -- of the shared module unresolved. Thus we have to resolve them
+ -- explicitly with loadbind. The new module is loaded, then we
+ -- resolve its symbols using the list of already loaded modules
+ -- (only those that belong to the python executable). Get these
+ -- with loadquery(L_GETINFO).
+ */
+
+ static void *staticmodlistptr = NULL;
+
+ if (!staticmodlistptr)
+ if (aix_getoldmodules(&staticmodlistptr) == -1)
+ return NULL;
+ p = (dl_funcptr) aix_load((char *)pathname, L_NOAUTODEFER, 0);
+ if (p == NULL) {
+ aix_loaderror(pathname);
+ return NULL;
+ }
+
+ return p;
}
diff --git a/Python/dynload_atheos.c b/Python/dynload_atheos.c
index 6f4df73..65e4136 100644
--- a/Python/dynload_atheos.c
+++ b/Python/dynload_atheos.c
@@ -9,39 +9,39 @@
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {".so", "rb", C_EXTENSION},
- {"module.so", "rb", C_EXTENSION},
- {0, 0}
+ {".so", "rb", C_EXTENSION},
+ {"module.so", "rb", C_EXTENSION},
+ {0, 0}
};
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- void *p;
- int lib;
- char funcname[258];
-
- if (Py_VerboseFlag)
- printf("load_library %s\n", pathname);
-
- lib = load_library(pathname, 0);
- if (lib < 0) {
- char buf[512];
- if (Py_VerboseFlag)
- perror(pathname);
- PyOS_snprintf(buf, sizeof(buf), "Failed to load %.200s: %.200s",
- pathname, strerror(errno));
- PyErr_SetString(PyExc_ImportError, buf);
- return NULL;
- }
- PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
- if (Py_VerboseFlag)
- printf("get_symbol_address %s\n", funcname);
- if (get_symbol_address(lib, funcname, -1, &p) < 0) {
- p = NULL;
- if (Py_VerboseFlag)
- perror(funcname);
- }
-
- return (dl_funcptr) p;
+ void *p;
+ int lib;
+ char funcname[258];
+
+ if (Py_VerboseFlag)
+ printf("load_library %s\n", pathname);
+
+ lib = load_library(pathname, 0);
+ if (lib < 0) {
+ char buf[512];
+ if (Py_VerboseFlag)
+ perror(pathname);
+ PyOS_snprintf(buf, sizeof(buf), "Failed to load %.200s: %.200s",
+ pathname, strerror(errno));
+ PyErr_SetString(PyExc_ImportError, buf);
+ return NULL;
+ }
+ PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
+ if (Py_VerboseFlag)
+ printf("get_symbol_address %s\n", funcname);
+ if (get_symbol_address(lib, funcname, -1, &p) < 0) {
+ p = NULL;
+ if (Py_VerboseFlag)
+ perror(funcname);
+ }
+
+ return (dl_funcptr) p;
}
diff --git a/Python/dynload_beos.c b/Python/dynload_beos.c
index 5b05d6b..f5ca1ec 100644
--- a/Python/dynload_beos.c
+++ b/Python/dynload_beos.c
@@ -9,9 +9,9 @@
#include "importdl.h"
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {".so", "rb", C_EXTENSION},
- {"module.so", "rb", C_EXTENSION},
- {0, 0}
+ {".so", "rb", C_EXTENSION},
+ {"module.so", "rb", C_EXTENSION},
+ {0, 0}
};
#if defined(MAXPATHLEN) && !defined(_SYS_PARAM_H)
@@ -52,13 +52,13 @@ static PyObject *beos_dyn_images = NULL;
*/
static void beos_nuke_dyn( PyObject *item )
{
- status_t retval;
+ status_t retval;
- if( item ) {
- image_id id = (image_id)PyInt_AsLong( item );
-
- retval = unload_add_on( id );
- }
+ if( item ) {
+ image_id id = (image_id)PyInt_AsLong( item );
+
+ retval = unload_add_on( id );
+ }
}
/* atexit() handler that'll call unload_add_on() for every item in the
@@ -66,31 +66,31 @@ static void beos_nuke_dyn( PyObject *item )
*/
static void beos_cleanup_dyn( void )
{
- if( beos_dyn_images ) {
- int idx;
- int list_size;
- PyObject *id_list;
+ if( beos_dyn_images ) {
+ int idx;
+ int list_size;
+ PyObject *id_list;
#ifdef WITH_THREAD
- PyThread_acquire_lock( beos_dyn_lock, 1 );
+ PyThread_acquire_lock( beos_dyn_lock, 1 );
#endif
- id_list = PyDict_Values( beos_dyn_images );
+ id_list = PyDict_Values( beos_dyn_images );
+
+ list_size = PyList_Size( id_list );
+ for( idx = 0; idx < list_size; idx++ ) {
+ PyObject *the_item;
- list_size = PyList_Size( id_list );
- for( idx = 0; idx < list_size; idx++ ) {
- PyObject *the_item;
-
- the_item = PyList_GetItem( id_list, idx );
- beos_nuke_dyn( the_item );
- }
+ the_item = PyList_GetItem( id_list, idx );
+ beos_nuke_dyn( the_item );
+ }
- PyDict_Clear( beos_dyn_images );
+ PyDict_Clear( beos_dyn_images );
#ifdef WITH_THREAD
- PyThread_free_lock( beos_dyn_lock );
+ PyThread_free_lock( beos_dyn_lock );
#endif
- }
+ }
}
/*
@@ -98,20 +98,20 @@ static void beos_cleanup_dyn( void )
*/
static void beos_init_dyn( void )
{
- /* We're protected from a race condition here by the atomic init_count
- * variable.
- */
- static int32 init_count = 0;
- int32 val;
-
- val = atomic_add( &init_count, 1 );
- if( beos_dyn_images == NULL && val == 0 ) {
- beos_dyn_images = PyDict_New();
+ /* We're protected from a race condition here by the atomic init_count
+ * variable.
+ */
+ static int32 init_count = 0;
+ int32 val;
+
+ val = atomic_add( &init_count, 1 );
+ if( beos_dyn_images == NULL && val == 0 ) {
+ beos_dyn_images = PyDict_New();
#ifdef WITH_THREAD
- beos_dyn_lock = PyThread_allocate_lock();
+ beos_dyn_lock = PyThread_allocate_lock();
#endif
- atexit( beos_cleanup_dyn );
- }
+ atexit( beos_cleanup_dyn );
+ }
}
/*
@@ -122,133 +122,133 @@ static void beos_init_dyn( void )
*/
static void beos_add_dyn( char *name, image_id id )
{
- int retval;
- PyObject *py_id;
+ int retval;
+ PyObject *py_id;
- if( beos_dyn_images == NULL ) {
- beos_init_dyn();
- }
+ if( beos_dyn_images == NULL ) {
+ beos_init_dyn();
+ }
#ifdef WITH_THREAD
- retval = PyThread_acquire_lock( beos_dyn_lock, 1 );
+ retval = PyThread_acquire_lock( beos_dyn_lock, 1 );
#endif
- /* If there's already an object with this key in the dictionary,
- * we're doing a reload(), so let's nuke it.
- */
- py_id = PyDict_GetItemString( beos_dyn_images, name );
- if( py_id ) {
- beos_nuke_dyn( py_id );
- retval = PyDict_DelItemString( beos_dyn_images, name );
- }
+ /* If there's already an object with this key in the dictionary,
+ * we're doing a reload(), so let's nuke it.
+ */
+ py_id = PyDict_GetItemString( beos_dyn_images, name );
+ if( py_id ) {
+ beos_nuke_dyn( py_id );
+ retval = PyDict_DelItemString( beos_dyn_images, name );
+ }
- py_id = PyInt_FromLong( (long)id );
- if( py_id ) {
- retval = PyDict_SetItemString( beos_dyn_images, name, py_id );
- }
+ py_id = PyInt_FromLong( (long)id );
+ if( py_id ) {
+ retval = PyDict_SetItemString( beos_dyn_images, name, py_id );
+ }
#ifdef WITH_THREAD
- PyThread_release_lock( beos_dyn_lock );
+ PyThread_release_lock( beos_dyn_lock );
#endif
}
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p;
- image_id the_id;
- status_t retval;
- char fullpath[PATH_MAX];
- char funcname[258];
-
- if( Py_VerboseFlag ) {
- printf( "load_add_on( %s )\n", pathname );
- }
-
- /* Hmm, this old bug appears to have regenerated itself; if the
- * path isn't absolute, load_add_on() will fail. Reported to Be
- * April 21, 1998.
- */
- if( pathname[0] != '/' ) {
- (void)getcwd( fullpath, PATH_MAX );
- (void)strncat( fullpath, "/", PATH_MAX );
- (void)strncat( fullpath, pathname, PATH_MAX );
-
- if( Py_VerboseFlag ) {
- printf( "load_add_on( %s )\n", fullpath );
- }
- } else {
- (void)strcpy( fullpath, pathname );
- }
-
- the_id = load_add_on( fullpath );
- if( the_id < B_NO_ERROR ) {
- /* It's too bad load_add_on() doesn't set errno or something...
- */
- char buff[256]; /* hate hard-coded string sizes... */
-
- if( Py_VerboseFlag ) {
- printf( "load_add_on( %s ) failed", fullpath );
- }
-
- if( the_id == B_ERROR )
- PyOS_snprintf( buff, sizeof(buff),
- "BeOS: Failed to load %.200s",
- fullpath );
- else
- PyOS_snprintf( buff, sizeof(buff),
- "Unknown error loading %.200s",
- fullpath );
-
- PyErr_SetString( PyExc_ImportError, buff );
- return NULL;
- }
-
- PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
- if( Py_VerboseFlag ) {
- printf( "get_image_symbol( %s )\n", funcname );
- }
-
- retval = get_image_symbol( the_id, funcname, B_SYMBOL_TYPE_TEXT, &p );
- if( retval != B_NO_ERROR || p == NULL ) {
- /* That's bad, we can't find that symbol in the module...
- */
- char buff[256]; /* hate hard-coded string sizes... */
-
- if( Py_VerboseFlag ) {
- printf( "get_image_symbol( %s ) failed", funcname );
- }
-
- switch( retval ) {
- case B_BAD_IMAGE_ID:
- PyOS_snprintf( buff, sizeof(buff),
- "can't load init function for dynamic module: "
- "Invalid image ID for %.180s", fullpath );
- break;
- case B_BAD_INDEX:
- PyOS_snprintf( buff, sizeof(buff),
- "can't load init function for dynamic module: "
- "Bad index for %.180s", funcname );
- break;
- default:
- PyOS_snprintf( buff, sizeof(buff),
- "can't load init function for dynamic module: "
- "Unknown error looking up %.180s", funcname );
- break;
- }
-
- retval = unload_add_on( the_id );
-
- PyErr_SetString( PyExc_ImportError, buff );
- return NULL;
- }
-
- /* Save the module name and image ID for later so we can clean up
- * gracefully.
- */
- beos_add_dyn( fqname, the_id );
-
- return p;
+ dl_funcptr p;
+ image_id the_id;
+ status_t retval;
+ char fullpath[PATH_MAX];
+ char funcname[258];
+
+ if( Py_VerboseFlag ) {
+ printf( "load_add_on( %s )\n", pathname );
+ }
+
+ /* Hmm, this old bug appears to have regenerated itself; if the
+ * path isn't absolute, load_add_on() will fail. Reported to Be
+ * April 21, 1998.
+ */
+ if( pathname[0] != '/' ) {
+ (void)getcwd( fullpath, PATH_MAX );
+ (void)strncat( fullpath, "/", PATH_MAX );
+ (void)strncat( fullpath, pathname, PATH_MAX );
+
+ if( Py_VerboseFlag ) {
+ printf( "load_add_on( %s )\n", fullpath );
+ }
+ } else {
+ (void)strcpy( fullpath, pathname );
+ }
+
+ the_id = load_add_on( fullpath );
+ if( the_id < B_NO_ERROR ) {
+ /* It's too bad load_add_on() doesn't set errno or something...
+ */
+ char buff[256]; /* hate hard-coded string sizes... */
+
+ if( Py_VerboseFlag ) {
+ printf( "load_add_on( %s ) failed", fullpath );
+ }
+
+ if( the_id == B_ERROR )
+ PyOS_snprintf( buff, sizeof(buff),
+ "BeOS: Failed to load %.200s",
+ fullpath );
+ else
+ PyOS_snprintf( buff, sizeof(buff),
+ "Unknown error loading %.200s",
+ fullpath );
+
+ PyErr_SetString( PyExc_ImportError, buff );
+ return NULL;
+ }
+
+ PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
+ if( Py_VerboseFlag ) {
+ printf( "get_image_symbol( %s )\n", funcname );
+ }
+
+ retval = get_image_symbol( the_id, funcname, B_SYMBOL_TYPE_TEXT, &p );
+ if( retval != B_NO_ERROR || p == NULL ) {
+ /* That's bad, we can't find that symbol in the module...
+ */
+ char buff[256]; /* hate hard-coded string sizes... */
+
+ if( Py_VerboseFlag ) {
+ printf( "get_image_symbol( %s ) failed", funcname );
+ }
+
+ switch( retval ) {
+ case B_BAD_IMAGE_ID:
+ PyOS_snprintf( buff, sizeof(buff),
+ "can't load init function for dynamic module: "
+ "Invalid image ID for %.180s", fullpath );
+ break;
+ case B_BAD_INDEX:
+ PyOS_snprintf( buff, sizeof(buff),
+ "can't load init function for dynamic module: "
+ "Bad index for %.180s", funcname );
+ break;
+ default:
+ PyOS_snprintf( buff, sizeof(buff),
+ "can't load init function for dynamic module: "
+ "Unknown error looking up %.180s", funcname );
+ break;
+ }
+
+ retval = unload_add_on( the_id );
+
+ PyErr_SetString( PyExc_ImportError, buff );
+ return NULL;
+ }
+
+ /* Save the module name and image ID for later so we can clean up
+ * gracefully.
+ */
+ beos_add_dyn( fqname, the_id );
+
+ return p;
}
diff --git a/Python/dynload_hpux.c b/Python/dynload_hpux.c
index fec0826..c6ce16e 100644
--- a/Python/dynload_hpux.c
+++ b/Python/dynload_hpux.c
@@ -14,45 +14,45 @@
#endif
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {SHLIB_EXT, "rb", C_EXTENSION},
- {"module"SHLIB_EXT, "rb", C_EXTENSION},
- {0, 0}
+ {SHLIB_EXT, "rb", C_EXTENSION},
+ {"module"SHLIB_EXT, "rb", C_EXTENSION},
+ {0, 0}
};
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p;
- shl_t lib;
- int flags;
- char funcname[258];
-
- flags = BIND_FIRST | BIND_DEFERRED;
- if (Py_VerboseFlag) {
- flags = BIND_FIRST | BIND_IMMEDIATE |
- BIND_NONFATAL | BIND_VERBOSE;
- printf("shl_load %s\n",pathname);
- }
- lib = shl_load(pathname, flags, 0);
- /* XXX Chuck Blake once wrote that 0 should be BIND_NOSTART? */
- if (lib == NULL) {
- char buf[256];
- if (Py_VerboseFlag)
- perror(pathname);
- PyOS_snprintf(buf, sizeof(buf), "Failed to load %.200s",
- pathname);
- PyErr_SetString(PyExc_ImportError, buf);
- return NULL;
- }
- PyOS_snprintf(funcname, sizeof(funcname), FUNCNAME_PATTERN, shortname);
- if (Py_VerboseFlag)
- printf("shl_findsym %s\n", funcname);
- if (shl_findsym(&lib, funcname, TYPE_UNDEFINED, (void *) &p) == -1) {
- shl_unload(lib);
- p = NULL;
- }
- if (p == NULL && Py_VerboseFlag)
- perror(funcname);
-
- return p;
+ dl_funcptr p;
+ shl_t lib;
+ int flags;
+ char funcname[258];
+
+ flags = BIND_FIRST | BIND_DEFERRED;
+ if (Py_VerboseFlag) {
+ flags = BIND_FIRST | BIND_IMMEDIATE |
+ BIND_NONFATAL | BIND_VERBOSE;
+ printf("shl_load %s\n",pathname);
+ }
+ lib = shl_load(pathname, flags, 0);
+ /* XXX Chuck Blake once wrote that 0 should be BIND_NOSTART? */
+ if (lib == NULL) {
+ char buf[256];
+ if (Py_VerboseFlag)
+ perror(pathname);
+ PyOS_snprintf(buf, sizeof(buf), "Failed to load %.200s",
+ pathname);
+ PyErr_SetString(PyExc_ImportError, buf);
+ return NULL;
+ }
+ PyOS_snprintf(funcname, sizeof(funcname), FUNCNAME_PATTERN, shortname);
+ if (Py_VerboseFlag)
+ printf("shl_findsym %s\n", funcname);
+ if (shl_findsym(&lib, funcname, TYPE_UNDEFINED, (void *) &p) == -1) {
+ shl_unload(lib);
+ p = NULL;
+ }
+ if (p == NULL && Py_VerboseFlag)
+ perror(funcname);
+
+ return p;
}
diff --git a/Python/dynload_next.c b/Python/dynload_next.c
index 27df356..7e61b5d 100644
--- a/Python/dynload_next.c
+++ b/Python/dynload_next.c
@@ -9,9 +9,9 @@
#include <mach-o/dyld.h>
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {".so", "rb", C_EXTENSION},
- {"module.so", "rb", C_EXTENSION},
- {0, 0}
+ {".so", "rb", C_EXTENSION},
+ {"module.so", "rb", C_EXTENSION},
+ {0, 0}
};
/*
@@ -29,86 +29,86 @@ const struct filedescr _PyImport_DynLoadFiletab[] = {
#define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR
#else
#define LINKOPTIONS NSLINKMODULE_OPTION_BINDNOW| \
- NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE
+ NSLINKMODULE_OPTION_RETURN_ON_ERROR|NSLINKMODULE_OPTION_PRIVATE
#endif
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p = NULL;
- char funcname[258];
- NSObjectFileImageReturnCode rc;
- NSObjectFileImage image;
- NSModule newModule;
- NSSymbol theSym;
- const char *errString;
- char errBuf[512];
+ dl_funcptr p = NULL;
+ char funcname[258];
+ NSObjectFileImageReturnCode rc;
+ NSObjectFileImage image;
+ NSModule newModule;
+ NSSymbol theSym;
+ const char *errString;
+ char errBuf[512];
- PyOS_snprintf(funcname, sizeof(funcname), "_init%.200s", shortname);
+ PyOS_snprintf(funcname, sizeof(funcname), "_init%.200s", shortname);
#ifdef USE_DYLD_GLOBAL_NAMESPACE
- if (NSIsSymbolNameDefined(funcname)) {
- theSym = NSLookupAndBindSymbol(funcname);
- p = (dl_funcptr)NSAddressOfSymbol(theSym);
- return p;
- }
+ if (NSIsSymbolNameDefined(funcname)) {
+ theSym = NSLookupAndBindSymbol(funcname);
+ p = (dl_funcptr)NSAddressOfSymbol(theSym);
+ return p;
+ }
#endif
- rc = NSCreateObjectFileImageFromFile(pathname, &image);
- switch(rc) {
- default:
- case NSObjectFileImageFailure:
- case NSObjectFileImageFormat:
- /* for these a message is printed on stderr by dyld */
- errString = "Can't create object file image";
- break;
- case NSObjectFileImageSuccess:
- errString = NULL;
- break;
- case NSObjectFileImageInappropriateFile:
- errString = "Inappropriate file type for dynamic loading";
- break;
- case NSObjectFileImageArch:
- errString = "Wrong CPU type in object file";
- break;
- case NSObjectFileImageAccess:
- errString = "Can't read object file (no access)";
- break;
- }
- if (errString == NULL) {
- newModule = NSLinkModule(image, pathname, LINKOPTIONS);
- if (newModule == NULL) {
- int errNo;
- const char *fileName, *moreErrorStr;
- NSLinkEditErrors c;
- NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr );
- PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s",
- fileName, moreErrorStr);
- errString = errBuf;
- }
- }
- if (errString != NULL) {
- PyErr_SetString(PyExc_ImportError, errString);
- return NULL;
- }
+ rc = NSCreateObjectFileImageFromFile(pathname, &image);
+ switch(rc) {
+ default:
+ case NSObjectFileImageFailure:
+ case NSObjectFileImageFormat:
+ /* for these a message is printed on stderr by dyld */
+ errString = "Can't create object file image";
+ break;
+ case NSObjectFileImageSuccess:
+ errString = NULL;
+ break;
+ case NSObjectFileImageInappropriateFile:
+ errString = "Inappropriate file type for dynamic loading";
+ break;
+ case NSObjectFileImageArch:
+ errString = "Wrong CPU type in object file";
+ break;
+ case NSObjectFileImageAccess:
+ errString = "Can't read object file (no access)";
+ break;
+ }
+ if (errString == NULL) {
+ newModule = NSLinkModule(image, pathname, LINKOPTIONS);
+ if (newModule == NULL) {
+ int errNo;
+ const char *fileName, *moreErrorStr;
+ NSLinkEditErrors c;
+ NSLinkEditError( &c, &errNo, &fileName, &moreErrorStr );
+ PyOS_snprintf(errBuf, 512, "Failure linking new module: %s: %s",
+ fileName, moreErrorStr);
+ errString = errBuf;
+ }
+ }
+ if (errString != NULL) {
+ PyErr_SetString(PyExc_ImportError, errString);
+ return NULL;
+ }
#ifdef USE_DYLD_GLOBAL_NAMESPACE
- if (!NSIsSymbolNameDefined(funcname)) {
- /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */
- /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */
- PyErr_Format(PyExc_ImportError,
- "Loaded module does not contain symbol %.200s",
- funcname);
- return NULL;
- }
- theSym = NSLookupAndBindSymbol(funcname);
+ if (!NSIsSymbolNameDefined(funcname)) {
+ /* UnlinkModule() isn't implemented in current versions, but calling it does no harm */
+ /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */
+ PyErr_Format(PyExc_ImportError,
+ "Loaded module does not contain symbol %.200s",
+ funcname);
+ return NULL;
+ }
+ theSym = NSLookupAndBindSymbol(funcname);
#else
- theSym = NSLookupSymbolInModule(newModule, funcname);
- if ( theSym == NULL ) {
- /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */
- PyErr_Format(PyExc_ImportError,
- "Loaded module does not contain symbol %.200s",
- funcname);
- return NULL;
- }
+ theSym = NSLookupSymbolInModule(newModule, funcname);
+ if ( theSym == NULL ) {
+ /* NSUnLinkModule(newModule, FALSE); removed: causes problems for ObjC code */
+ PyErr_Format(PyExc_ImportError,
+ "Loaded module does not contain symbol %.200s",
+ funcname);
+ return NULL;
+ }
#endif
- p = (dl_funcptr)NSAddressOfSymbol(theSym);
- return p;
+ p = (dl_funcptr)NSAddressOfSymbol(theSym);
+ return p;
}
diff --git a/Python/dynload_os2.c b/Python/dynload_os2.c
index d660e27..e3fdb70 100644
--- a/Python/dynload_os2.c
+++ b/Python/dynload_os2.c
@@ -10,37 +10,37 @@
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {".pyd", "rb", C_EXTENSION},
- {".dll", "rb", C_EXTENSION},
- {0, 0}
+ {".pyd", "rb", C_EXTENSION},
+ {".dll", "rb", C_EXTENSION},
+ {0, 0}
};
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p;
- APIRET rc;
- HMODULE hDLL;
- char failreason[256];
- char funcname[258];
-
- rc = DosLoadModule(failreason,
- sizeof(failreason),
- pathname,
- &hDLL);
-
- if (rc != NO_ERROR) {
- char errBuf[256];
- PyOS_snprintf(errBuf, sizeof(errBuf),
- "DLL load failed, rc = %d: %.200s",
- rc, failreason);
- PyErr_SetString(PyExc_ImportError, errBuf);
- return NULL;
- }
-
- PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
- rc = DosQueryProcAddr(hDLL, 0L, funcname, &p);
- if (rc != NO_ERROR)
- p = NULL; /* Signify Failure to Acquire Entrypoint */
- return p;
+ dl_funcptr p;
+ APIRET rc;
+ HMODULE hDLL;
+ char failreason[256];
+ char funcname[258];
+
+ rc = DosLoadModule(failreason,
+ sizeof(failreason),
+ pathname,
+ &hDLL);
+
+ if (rc != NO_ERROR) {
+ char errBuf[256];
+ PyOS_snprintf(errBuf, sizeof(errBuf),
+ "DLL load failed, rc = %d: %.200s",
+ rc, failreason);
+ PyErr_SetString(PyExc_ImportError, errBuf);
+ return NULL;
+ }
+
+ PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
+ rc = DosQueryProcAddr(hDLL, 0L, funcname, &p);
+ if (rc != NO_ERROR)
+ p = NULL; /* Signify Failure to Acquire Entrypoint */
+ return p;
}
diff --git a/Python/dynload_shlib.c b/Python/dynload_shlib.c
index f12a93c..17ebab1 100644
--- a/Python/dynload_shlib.c
+++ b/Python/dynload_shlib.c
@@ -33,111 +33,111 @@
const struct filedescr _PyImport_DynLoadFiletab[] = {
#ifdef __CYGWIN__
- {".dll", "rb", C_EXTENSION},
- {"module.dll", "rb", C_EXTENSION},
+ {".dll", "rb", C_EXTENSION},
+ {"module.dll", "rb", C_EXTENSION},
#else
#if defined(PYOS_OS2) && defined(PYCC_GCC)
- {".pyd", "rb", C_EXTENSION},
- {".dll", "rb", C_EXTENSION},
+ {".pyd", "rb", C_EXTENSION},
+ {".dll", "rb", C_EXTENSION},
#else
#ifdef __VMS
- {".exe", "rb", C_EXTENSION},
- {".EXE", "rb", C_EXTENSION},
- {"module.exe", "rb", C_EXTENSION},
- {"MODULE.EXE", "rb", C_EXTENSION},
+ {".exe", "rb", C_EXTENSION},
+ {".EXE", "rb", C_EXTENSION},
+ {"module.exe", "rb", C_EXTENSION},
+ {"MODULE.EXE", "rb", C_EXTENSION},
#else
- {".so", "rb", C_EXTENSION},
- {"module.so", "rb", C_EXTENSION},
+ {".so", "rb", C_EXTENSION},
+ {"module.so", "rb", C_EXTENSION},
#endif
#endif
#endif
- {0, 0}
+ {0, 0}
};
static struct {
- dev_t dev;
+ dev_t dev;
#ifdef __VMS
- ino_t ino[3];
+ ino_t ino[3];
#else
- ino_t ino;
+ ino_t ino;
#endif
- void *handle;
+ void *handle;
} handles[128];
static int nhandles = 0;
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p;
- void *handle;
- char funcname[258];
- char pathbuf[260];
- int dlopenflags=0;
-
- if (strchr(pathname, '/') == NULL) {
- /* Prefix bare filename with "./" */
- PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname);
- pathname = pathbuf;
- }
-
- PyOS_snprintf(funcname, sizeof(funcname),
- LEAD_UNDERSCORE "init%.200s", shortname);
-
- if (fp != NULL) {
- int i;
- struct stat statb;
- fstat(fileno(fp), &statb);
- for (i = 0; i < nhandles; i++) {
- if (statb.st_dev == handles[i].dev &&
- statb.st_ino == handles[i].ino) {
- p = (dl_funcptr) dlsym(handles[i].handle,
- funcname);
- return p;
- }
- }
- if (nhandles < 128) {
- handles[nhandles].dev = statb.st_dev;
+ dl_funcptr p;
+ void *handle;
+ char funcname[258];
+ char pathbuf[260];
+ int dlopenflags=0;
+
+ if (strchr(pathname, '/') == NULL) {
+ /* Prefix bare filename with "./" */
+ PyOS_snprintf(pathbuf, sizeof(pathbuf), "./%-.255s", pathname);
+ pathname = pathbuf;
+ }
+
+ PyOS_snprintf(funcname, sizeof(funcname),
+ LEAD_UNDERSCORE "init%.200s", shortname);
+
+ if (fp != NULL) {
+ int i;
+ struct stat statb;
+ fstat(fileno(fp), &statb);
+ for (i = 0; i < nhandles; i++) {
+ if (statb.st_dev == handles[i].dev &&
+ statb.st_ino == handles[i].ino) {
+ p = (dl_funcptr) dlsym(handles[i].handle,
+ funcname);
+ return p;
+ }
+ }
+ if (nhandles < 128) {
+ handles[nhandles].dev = statb.st_dev;
#ifdef __VMS
- handles[nhandles].ino[0] = statb.st_ino[0];
- handles[nhandles].ino[1] = statb.st_ino[1];
- handles[nhandles].ino[2] = statb.st_ino[2];
+ handles[nhandles].ino[0] = statb.st_ino[0];
+ handles[nhandles].ino[1] = statb.st_ino[1];
+ handles[nhandles].ino[2] = statb.st_ino[2];
#else
- handles[nhandles].ino = statb.st_ino;
+ handles[nhandles].ino = statb.st_ino;
#endif
- }
- }
+ }
+ }
#if !(defined(PYOS_OS2) && defined(PYCC_GCC))
- dlopenflags = PyThreadState_GET()->interp->dlopenflags;
+ dlopenflags = PyThreadState_GET()->interp->dlopenflags;
#endif
- if (Py_VerboseFlag)
- PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname,
- dlopenflags);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("dlopen(\"%s\", %x);\n", pathname,
+ dlopenflags);
#ifdef __VMS
- /* VMS currently don't allow a pathname, use a logical name instead */
- /* Concatenate 'python_module_' and shortname */
- /* so "import vms.bar" will use the logical python_module_bar */
- /* As C module use only one name space this is probably not a */
- /* important limitation */
- PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s",
- shortname);
- pathname = pathbuf;
+ /* VMS currently don't allow a pathname, use a logical name instead */
+ /* Concatenate 'python_module_' and shortname */
+ /* so "import vms.bar" will use the logical python_module_bar */
+ /* As C module use only one name space this is probably not a */
+ /* important limitation */
+ PyOS_snprintf(pathbuf, sizeof(pathbuf), "python_module_%-.200s",
+ shortname);
+ pathname = pathbuf;
#endif
- handle = dlopen(pathname, dlopenflags);
-
- if (handle == NULL) {
- const char *error = dlerror();
- if (error == NULL)
- error = "unknown dlopen() error";
- PyErr_SetString(PyExc_ImportError, error);
- return NULL;
- }
- if (fp != NULL && nhandles < 128)
- handles[nhandles++].handle = handle;
- p = (dl_funcptr) dlsym(handle, funcname);
- return p;
+ handle = dlopen(pathname, dlopenflags);
+
+ if (handle == NULL) {
+ const char *error = dlerror();
+ if (error == NULL)
+ error = "unknown dlopen() error";
+ PyErr_SetString(PyExc_ImportError, error);
+ return NULL;
+ }
+ if (fp != NULL && nhandles < 128)
+ handles[nhandles++].handle = handle;
+ p = (dl_funcptr) dlsym(handle, funcname);
+ return p;
}
diff --git a/Python/dynload_win.c b/Python/dynload_win.c
index 907a5a3..4e5555e 100644
--- a/Python/dynload_win.c
+++ b/Python/dynload_win.c
@@ -17,11 +17,11 @@ void _Py_DeactivateActCtx(ULONG_PTR cookie);
const struct filedescr _PyImport_DynLoadFiletab[] = {
#ifdef _DEBUG
- {"_d.pyd", "rb", C_EXTENSION},
+ {"_d.pyd", "rb", C_EXTENSION},
#else
- {".pyd", "rb", C_EXTENSION},
+ {".pyd", "rb", C_EXTENSION},
#endif
- {0, 0}
+ {0, 0}
};
@@ -29,18 +29,18 @@ const struct filedescr _PyImport_DynLoadFiletab[] = {
C RTL implementations */
static int strcasecmp (char *string1, char *string2)
-{
- int first, second;
+{
+ int first, second;
- do {
- first = tolower(*string1);
- second = tolower(*string2);
- string1++;
- string2++;
- } while (first && first == second);
+ do {
+ first = tolower(*string1);
+ second = tolower(*string2);
+ string1++;
+ string2++;
+ } while (first && first == second);
- return (first - second);
-}
+ return (first - second);
+}
/* Function to return the name of the "python" DLL that the supplied module
@@ -66,209 +66,209 @@ static int strcasecmp (char *string1, char *string2)
static char *GetPythonImport (HINSTANCE hModule)
{
- unsigned char *dllbase, *import_data, *import_name;
- DWORD pe_offset, opt_offset;
- WORD opt_magic;
- int num_dict_off, import_off;
-
- /* Safety check input */
- if (hModule == NULL) {
- return NULL;
- }
-
- /* Module instance is also the base load address. First portion of
- memory is the MS-DOS loader, which holds the offset to the PE
- header (from the load base) at 0x3C */
- dllbase = (unsigned char *)hModule;
- pe_offset = DWORD_AT(dllbase + 0x3C);
-
- /* The PE signature must be "PE\0\0" */
- if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
- return NULL;
- }
-
- /* Following the PE signature is the standard COFF header (20
- bytes) and then the optional header. The optional header starts
- with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
- uses 64-bits for some fields). It might also be 0x107 for a ROM
- image, but we don't process that here.
-
- The optional header ends with a data dictionary that directly
- points to certain types of data, among them the import entries
- (in the second table entry). Based on the header type, we
- determine offsets for the data dictionary count and the entry
- within the dictionary pointing to the imports. */
-
- opt_offset = pe_offset + 4 + 20;
- opt_magic = WORD_AT(dllbase+opt_offset);
- if (opt_magic == 0x10B) {
- /* PE32 */
- num_dict_off = 92;
- import_off = 104;
- } else if (opt_magic == 0x20B) {
- /* PE32+ */
- num_dict_off = 108;
- import_off = 120;
- } else {
- /* Unsupported */
- return NULL;
- }
-
- /* Now if an import table exists, offset to it and walk the list of
- imports. The import table is an array (ending when an entry has
- empty values) of structures (20 bytes each), which contains (at
- offset 12) a relative address (to the module base) at which a
- string constant holding the import name is located. */
-
- if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
- /* We have at least 2 tables - the import table is the second
- one. But still it may be that the table size is zero */
- if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD)))
- return NULL;
- import_data = dllbase + DWORD_AT(dllbase +
- opt_offset +
- import_off);
- while (DWORD_AT(import_data)) {
- import_name = dllbase + DWORD_AT(import_data+12);
- if (strlen(import_name) >= 6 &&
- !strncmp(import_name,"python",6)) {
- char *pch;
-
- /* Ensure python prefix is followed only
- by numbers to the end of the basename */
- pch = import_name + 6;
+ unsigned char *dllbase, *import_data, *import_name;
+ DWORD pe_offset, opt_offset;
+ WORD opt_magic;
+ int num_dict_off, import_off;
+
+ /* Safety check input */
+ if (hModule == NULL) {
+ return NULL;
+ }
+
+ /* Module instance is also the base load address. First portion of
+ memory is the MS-DOS loader, which holds the offset to the PE
+ header (from the load base) at 0x3C */
+ dllbase = (unsigned char *)hModule;
+ pe_offset = DWORD_AT(dllbase + 0x3C);
+
+ /* The PE signature must be "PE\0\0" */
+ if (memcmp(dllbase+pe_offset,"PE\0\0",4)) {
+ return NULL;
+ }
+
+ /* Following the PE signature is the standard COFF header (20
+ bytes) and then the optional header. The optional header starts
+ with a magic value of 0x10B for PE32 or 0x20B for PE32+ (PE32+
+ uses 64-bits for some fields). It might also be 0x107 for a ROM
+ image, but we don't process that here.
+
+ The optional header ends with a data dictionary that directly
+ points to certain types of data, among them the import entries
+ (in the second table entry). Based on the header type, we
+ determine offsets for the data dictionary count and the entry
+ within the dictionary pointing to the imports. */
+
+ opt_offset = pe_offset + 4 + 20;
+ opt_magic = WORD_AT(dllbase+opt_offset);
+ if (opt_magic == 0x10B) {
+ /* PE32 */
+ num_dict_off = 92;
+ import_off = 104;
+ } else if (opt_magic == 0x20B) {
+ /* PE32+ */
+ num_dict_off = 108;
+ import_off = 120;
+ } else {
+ /* Unsupported */
+ return NULL;
+ }
+
+ /* Now if an import table exists, offset to it and walk the list of
+ imports. The import table is an array (ending when an entry has
+ empty values) of structures (20 bytes each), which contains (at
+ offset 12) a relative address (to the module base) at which a
+ string constant holding the import name is located. */
+
+ if (DWORD_AT(dllbase + opt_offset + num_dict_off) >= 2) {
+ /* We have at least 2 tables - the import table is the second
+ one. But still it may be that the table size is zero */
+ if (0 == DWORD_AT(dllbase + opt_offset + import_off + sizeof(DWORD)))
+ return NULL;
+ import_data = dllbase + DWORD_AT(dllbase +
+ opt_offset +
+ import_off);
+ while (DWORD_AT(import_data)) {
+ import_name = dllbase + DWORD_AT(import_data+12);
+ if (strlen(import_name) >= 6 &&
+ !strncmp(import_name,"python",6)) {
+ char *pch;
+
+ /* Ensure python prefix is followed only
+ by numbers to the end of the basename */
+ pch = import_name + 6;
#ifdef _DEBUG
- while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
+ while (*pch && pch[0] != '_' && pch[1] != 'd' && pch[2] != '.') {
#else
- while (*pch && *pch != '.') {
+ while (*pch && *pch != '.') {
#endif
- if (*pch >= '0' && *pch <= '9') {
- pch++;
- } else {
- pch = NULL;
- break;
- }
- }
-
- if (pch) {
- /* Found it - return the name */
- return import_name;
- }
- }
- import_data += 20;
- }
- }
-
- return NULL;
+ if (*pch >= '0' && *pch <= '9') {
+ pch++;
+ } else {
+ pch = NULL;
+ break;
+ }
+ }
+
+ if (pch) {
+ /* Found it - return the name */
+ return import_name;
+ }
+ }
+ import_data += 20;
+ }
+ }
+
+ return NULL;
}
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- const char *pathname, FILE *fp)
+ const char *pathname, FILE *fp)
{
- dl_funcptr p;
- char funcname[258], *import_python;
-
- PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
-
- {
- HINSTANCE hDLL = NULL;
- char pathbuf[260];
- LPTSTR dummy;
- unsigned int old_mode;
- ULONG_PTR cookie = 0;
- /* We use LoadLibraryEx so Windows looks for dependent DLLs
- in directory of pathname first. However, Windows95
- can sometimes not work correctly unless the absolute
- path is used. If GetFullPathName() fails, the LoadLibrary
- will certainly fail too, so use its error code */
-
- /* Don't display a message box when Python can't load a DLL */
- old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
-
- if (GetFullPathName(pathname,
- sizeof(pathbuf),
- pathbuf,
- &dummy)) {
- ULONG_PTR cookie = _Py_ActivateActCtx();
- /* XXX This call doesn't exist in Windows CE */
- hDLL = LoadLibraryEx(pathname, NULL,
- LOAD_WITH_ALTERED_SEARCH_PATH);
- _Py_DeactivateActCtx(cookie);
- }
-
- /* restore old error mode settings */
- SetErrorMode(old_mode);
-
- if (hDLL==NULL){
- char errBuf[256];
- unsigned int errorCode;
-
- /* Get an error string from Win32 error code */
- char theInfo[256]; /* Pointer to error text
- from system */
- int theLength; /* Length of error text */
-
- errorCode = GetLastError();
-
- theLength = FormatMessage(
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
- NULL, /* message source */
- errorCode, /* the message (error) ID */
- 0, /* default language environment */
- (LPTSTR) theInfo, /* the buffer */
- sizeof(theInfo), /* the buffer size */
- NULL); /* no additional format args. */
-
- /* Problem: could not get the error message.
- This should not happen if called correctly. */
- if (theLength == 0) {
- PyOS_snprintf(errBuf, sizeof(errBuf),
- "DLL load failed with error code %d",
- errorCode);
- } else {
- size_t len;
- /* For some reason a \r\n
- is appended to the text */
- if (theLength >= 2 &&
- theInfo[theLength-2] == '\r' &&
- theInfo[theLength-1] == '\n') {
- theLength -= 2;
- theInfo[theLength] = '\0';
- }
- strcpy(errBuf, "DLL load failed: ");
- len = strlen(errBuf);
- strncpy(errBuf+len, theInfo,
- sizeof(errBuf)-len);
- errBuf[sizeof(errBuf)-1] = '\0';
- }
- PyErr_SetString(PyExc_ImportError, errBuf);
- return NULL;
- } else {
- char buffer[256];
+ dl_funcptr p;
+ char funcname[258], *import_python;
+
+ PyOS_snprintf(funcname, sizeof(funcname), "init%.200s", shortname);
+
+ {
+ HINSTANCE hDLL = NULL;
+ char pathbuf[260];
+ LPTSTR dummy;
+ unsigned int old_mode;
+ ULONG_PTR cookie = 0;
+ /* We use LoadLibraryEx so Windows looks for dependent DLLs
+ in directory of pathname first. However, Windows95
+ can sometimes not work correctly unless the absolute
+ path is used. If GetFullPathName() fails, the LoadLibrary
+ will certainly fail too, so use its error code */
+
+ /* Don't display a message box when Python can't load a DLL */
+ old_mode = SetErrorMode(SEM_FAILCRITICALERRORS);
+
+ if (GetFullPathName(pathname,
+ sizeof(pathbuf),
+ pathbuf,
+ &dummy)) {
+ ULONG_PTR cookie = _Py_ActivateActCtx();
+ /* XXX This call doesn't exist in Windows CE */
+ hDLL = LoadLibraryEx(pathname, NULL,
+ LOAD_WITH_ALTERED_SEARCH_PATH);
+ _Py_DeactivateActCtx(cookie);
+ }
+
+ /* restore old error mode settings */
+ SetErrorMode(old_mode);
+
+ if (hDLL==NULL){
+ char errBuf[256];
+ unsigned int errorCode;
+
+ /* Get an error string from Win32 error code */
+ char theInfo[256]; /* Pointer to error text
+ from system */
+ int theLength; /* Length of error text */
+
+ errorCode = GetLastError();
+
+ theLength = FormatMessage(
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS, /* flags */
+ NULL, /* message source */
+ errorCode, /* the message (error) ID */
+ 0, /* default language environment */
+ (LPTSTR) theInfo, /* the buffer */
+ sizeof(theInfo), /* the buffer size */
+ NULL); /* no additional format args. */
+
+ /* Problem: could not get the error message.
+ This should not happen if called correctly. */
+ if (theLength == 0) {
+ PyOS_snprintf(errBuf, sizeof(errBuf),
+ "DLL load failed with error code %d",
+ errorCode);
+ } else {
+ size_t len;
+ /* For some reason a \r\n
+ is appended to the text */
+ if (theLength >= 2 &&
+ theInfo[theLength-2] == '\r' &&
+ theInfo[theLength-1] == '\n') {
+ theLength -= 2;
+ theInfo[theLength] = '\0';
+ }
+ strcpy(errBuf, "DLL load failed: ");
+ len = strlen(errBuf);
+ strncpy(errBuf+len, theInfo,
+ sizeof(errBuf)-len);
+ errBuf[sizeof(errBuf)-1] = '\0';
+ }
+ PyErr_SetString(PyExc_ImportError, errBuf);
+ return NULL;
+ } else {
+ char buffer[256];
#ifdef _DEBUG
- PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll",
+ PyOS_snprintf(buffer, sizeof(buffer), "python%d%d_d.dll",
#else
- PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll",
+ PyOS_snprintf(buffer, sizeof(buffer), "python%d%d.dll",
#endif
- PY_MAJOR_VERSION,PY_MINOR_VERSION);
- import_python = GetPythonImport(hDLL);
-
- if (import_python &&
- strcasecmp(buffer,import_python)) {
- PyOS_snprintf(buffer, sizeof(buffer),
- "Module use of %.150s conflicts "
- "with this version of Python.",
- import_python);
- PyErr_SetString(PyExc_ImportError,buffer);
- FreeLibrary(hDLL);
- return NULL;
- }
- }
- p = GetProcAddress(hDLL, funcname);
- }
-
- return p;
+ PY_MAJOR_VERSION,PY_MINOR_VERSION);
+ import_python = GetPythonImport(hDLL);
+
+ if (import_python &&
+ strcasecmp(buffer,import_python)) {
+ PyOS_snprintf(buffer, sizeof(buffer),
+ "Module use of %.150s conflicts "
+ "with this version of Python.",
+ import_python);
+ PyErr_SetString(PyExc_ImportError,buffer);
+ FreeLibrary(hDLL);
+ return NULL;
+ }
+ }
+ p = GetProcAddress(hDLL, funcname);
+ }
+
+ return p;
}
diff --git a/Python/errors.c b/Python/errors.c
index 2d47779..4294f2f 100644
--- a/Python/errors.c
+++ b/Python/errors.c
@@ -24,115 +24,115 @@ extern "C" {
void
PyErr_Restore(PyObject *type, PyObject *value, PyObject *traceback)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *oldtype, *oldvalue, *oldtraceback;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *oldtype, *oldvalue, *oldtraceback;
- if (traceback != NULL && !PyTraceBack_Check(traceback)) {
- /* XXX Should never happen -- fatal error instead? */
- /* Well, it could be None. */
- Py_DECREF(traceback);
- traceback = NULL;
- }
+ if (traceback != NULL && !PyTraceBack_Check(traceback)) {
+ /* XXX Should never happen -- fatal error instead? */
+ /* Well, it could be None. */
+ Py_DECREF(traceback);
+ traceback = NULL;
+ }
- /* Save these in locals to safeguard against recursive
- invocation through Py_XDECREF */
- oldtype = tstate->curexc_type;
- oldvalue = tstate->curexc_value;
- oldtraceback = tstate->curexc_traceback;
+ /* Save these in locals to safeguard against recursive
+ invocation through Py_XDECREF */
+ oldtype = tstate->curexc_type;
+ oldvalue = tstate->curexc_value;
+ oldtraceback = tstate->curexc_traceback;
- tstate->curexc_type = type;
- tstate->curexc_value = value;
- tstate->curexc_traceback = traceback;
+ tstate->curexc_type = type;
+ tstate->curexc_value = value;
+ tstate->curexc_traceback = traceback;
- Py_XDECREF(oldtype);
- Py_XDECREF(oldvalue);
- Py_XDECREF(oldtraceback);
+ Py_XDECREF(oldtype);
+ Py_XDECREF(oldvalue);
+ Py_XDECREF(oldtraceback);
}
void
PyErr_SetObject(PyObject *exception, PyObject *value)
{
- Py_XINCREF(exception);
- Py_XINCREF(value);
- PyErr_Restore(exception, value, (PyObject *)NULL);
+ Py_XINCREF(exception);
+ Py_XINCREF(value);
+ PyErr_Restore(exception, value, (PyObject *)NULL);
}
void
PyErr_SetNone(PyObject *exception)
{
- PyErr_SetObject(exception, (PyObject *)NULL);
+ PyErr_SetObject(exception, (PyObject *)NULL);
}
void
PyErr_SetString(PyObject *exception, const char *string)
{
- PyObject *value = PyString_FromString(string);
- PyErr_SetObject(exception, value);
- Py_XDECREF(value);
+ PyObject *value = PyString_FromString(string);
+ PyErr_SetObject(exception, value);
+ Py_XDECREF(value);
}
PyObject *
PyErr_Occurred(void)
{
- PyThreadState *tstate = PyThreadState_GET();
+ PyThreadState *tstate = PyThreadState_GET();
- return tstate->curexc_type;
+ return tstate->curexc_type;
}
int
PyErr_GivenExceptionMatches(PyObject *err, PyObject *exc)
{
- if (err == NULL || exc == NULL) {
- /* maybe caused by "import exceptions" that failed early on */
- return 0;
- }
- if (PyTuple_Check(exc)) {
- Py_ssize_t i, n;
- n = PyTuple_Size(exc);
- for (i = 0; i < n; i++) {
- /* Test recursively */
- if (PyErr_GivenExceptionMatches(
- err, PyTuple_GET_ITEM(exc, i)))
- {
- return 1;
- }
- }
- return 0;
- }
- /* err might be an instance, so check its class. */
- if (PyExceptionInstance_Check(err))
- err = PyExceptionInstance_Class(err);
-
- if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
- int res = 0, reclimit;
- PyObject *exception, *value, *tb;
- PyErr_Fetch(&exception, &value, &tb);
- /* Temporarily bump the recursion limit, so that in the most
- common case PyObject_IsSubclass will not raise a recursion
- error we have to ignore anyway. */
- reclimit = Py_GetRecursionLimit();
- Py_SetRecursionLimit(reclimit + 5);
- res = PyObject_IsSubclass(err, exc);
- Py_SetRecursionLimit(reclimit);
- /* This function must not fail, so print the error here */
- if (res == -1) {
- PyErr_WriteUnraisable(err);
- res = 0;
- }
- PyErr_Restore(exception, value, tb);
- return res;
- }
-
- return err == exc;
+ if (err == NULL || exc == NULL) {
+ /* maybe caused by "import exceptions" that failed early on */
+ return 0;
+ }
+ if (PyTuple_Check(exc)) {
+ Py_ssize_t i, n;
+ n = PyTuple_Size(exc);
+ for (i = 0; i < n; i++) {
+ /* Test recursively */
+ if (PyErr_GivenExceptionMatches(
+ err, PyTuple_GET_ITEM(exc, i)))
+ {
+ return 1;
+ }
+ }
+ return 0;
+ }
+ /* err might be an instance, so check its class. */
+ if (PyExceptionInstance_Check(err))
+ err = PyExceptionInstance_Class(err);
+
+ if (PyExceptionClass_Check(err) && PyExceptionClass_Check(exc)) {
+ int res = 0, reclimit;
+ PyObject *exception, *value, *tb;
+ PyErr_Fetch(&exception, &value, &tb);
+ /* Temporarily bump the recursion limit, so that in the most
+ common case PyObject_IsSubclass will not raise a recursion
+ error we have to ignore anyway. */
+ reclimit = Py_GetRecursionLimit();
+ Py_SetRecursionLimit(reclimit + 5);
+ res = PyObject_IsSubclass(err, exc);
+ Py_SetRecursionLimit(reclimit);
+ /* This function must not fail, so print the error here */
+ if (res == -1) {
+ PyErr_WriteUnraisable(err);
+ res = 0;
+ }
+ PyErr_Restore(exception, value, tb);
+ return res;
+ }
+
+ return err == exc;
}
int
PyErr_ExceptionMatches(PyObject *exc)
{
- return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
+ return PyErr_GivenExceptionMatches(PyErr_Occurred(), exc);
}
@@ -142,123 +142,123 @@ PyErr_ExceptionMatches(PyObject *exc)
void
PyErr_NormalizeException(PyObject **exc, PyObject **val, PyObject **tb)
{
- PyObject *type = *exc;
- PyObject *value = *val;
- PyObject *inclass = NULL;
- PyObject *initial_tb = NULL;
- PyThreadState *tstate = NULL;
-
- if (type == NULL) {
- /* There was no exception, so nothing to do. */
- return;
- }
-
- /* If PyErr_SetNone() was used, the value will have been actually
- set to NULL.
- */
- if (!value) {
- value = Py_None;
- Py_INCREF(value);
- }
-
- if (PyExceptionInstance_Check(value))
- inclass = PyExceptionInstance_Class(value);
-
- /* Normalize the exception so that if the type is a class, the
- value will be an instance.
- */
- if (PyExceptionClass_Check(type)) {
- /* if the value was not an instance, or is not an instance
- whose class is (or is derived from) type, then use the
- value as an argument to instantiation of the type
- class.
- */
- if (!inclass || !PyObject_IsSubclass(inclass, type)) {
- PyObject *args, *res;
-
- if (value == Py_None)
- args = PyTuple_New(0);
- else if (PyTuple_Check(value)) {
- Py_INCREF(value);
- args = value;
- }
- else
- args = PyTuple_Pack(1, value);
-
- if (args == NULL)
- goto finally;
- res = PyEval_CallObject(type, args);
- Py_DECREF(args);
- if (res == NULL)
- goto finally;
- Py_DECREF(value);
- value = res;
- }
- /* if the class of the instance doesn't exactly match the
- class of the type, believe the instance
- */
- else if (inclass != type) {
- Py_DECREF(type);
- type = inclass;
- Py_INCREF(type);
- }
- }
- *exc = type;
- *val = value;
- return;
+ PyObject *type = *exc;
+ PyObject *value = *val;
+ PyObject *inclass = NULL;
+ PyObject *initial_tb = NULL;
+ PyThreadState *tstate = NULL;
+
+ if (type == NULL) {
+ /* There was no exception, so nothing to do. */
+ return;
+ }
+
+ /* If PyErr_SetNone() was used, the value will have been actually
+ set to NULL.
+ */
+ if (!value) {
+ value = Py_None;
+ Py_INCREF(value);
+ }
+
+ if (PyExceptionInstance_Check(value))
+ inclass = PyExceptionInstance_Class(value);
+
+ /* Normalize the exception so that if the type is a class, the
+ value will be an instance.
+ */
+ if (PyExceptionClass_Check(type)) {
+ /* if the value was not an instance, or is not an instance
+ whose class is (or is derived from) type, then use the
+ value as an argument to instantiation of the type
+ class.
+ */
+ if (!inclass || !PyObject_IsSubclass(inclass, type)) {
+ PyObject *args, *res;
+
+ if (value == Py_None)
+ args = PyTuple_New(0);
+ else if (PyTuple_Check(value)) {
+ Py_INCREF(value);
+ args = value;
+ }
+ else
+ args = PyTuple_Pack(1, value);
+
+ if (args == NULL)
+ goto finally;
+ res = PyEval_CallObject(type, args);
+ Py_DECREF(args);
+ if (res == NULL)
+ goto finally;
+ Py_DECREF(value);
+ value = res;
+ }
+ /* if the class of the instance doesn't exactly match the
+ class of the type, believe the instance
+ */
+ else if (inclass != type) {
+ Py_DECREF(type);
+ type = inclass;
+ Py_INCREF(type);
+ }
+ }
+ *exc = type;
+ *val = value;
+ return;
finally:
- Py_DECREF(type);
- Py_DECREF(value);
- /* If the new exception doesn't set a traceback and the old
- exception had a traceback, use the old traceback for the
- new exception. It's better than nothing.
- */
- initial_tb = *tb;
- PyErr_Fetch(exc, val, tb);
- if (initial_tb != NULL) {
- if (*tb == NULL)
- *tb = initial_tb;
- else
- Py_DECREF(initial_tb);
- }
- /* normalize recursively */
- tstate = PyThreadState_GET();
- if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
- --tstate->recursion_depth;
- /* throw away the old exception... */
- Py_DECREF(*exc);
- Py_DECREF(*val);
- /* ... and use the recursion error instead */
- *exc = PyExc_RuntimeError;
- *val = PyExc_RecursionErrorInst;
- Py_INCREF(*exc);
- Py_INCREF(*val);
- /* just keeping the old traceback */
- return;
- }
- PyErr_NormalizeException(exc, val, tb);
- --tstate->recursion_depth;
+ Py_DECREF(type);
+ Py_DECREF(value);
+ /* If the new exception doesn't set a traceback and the old
+ exception had a traceback, use the old traceback for the
+ new exception. It's better than nothing.
+ */
+ initial_tb = *tb;
+ PyErr_Fetch(exc, val, tb);
+ if (initial_tb != NULL) {
+ if (*tb == NULL)
+ *tb = initial_tb;
+ else
+ Py_DECREF(initial_tb);
+ }
+ /* normalize recursively */
+ tstate = PyThreadState_GET();
+ if (++tstate->recursion_depth > Py_GetRecursionLimit()) {
+ --tstate->recursion_depth;
+ /* throw away the old exception... */
+ Py_DECREF(*exc);
+ Py_DECREF(*val);
+ /* ... and use the recursion error instead */
+ *exc = PyExc_RuntimeError;
+ *val = PyExc_RecursionErrorInst;
+ Py_INCREF(*exc);
+ Py_INCREF(*val);
+ /* just keeping the old traceback */
+ return;
+ }
+ PyErr_NormalizeException(exc, val, tb);
+ --tstate->recursion_depth;
}
void
PyErr_Fetch(PyObject **p_type, PyObject **p_value, PyObject **p_traceback)
{
- PyThreadState *tstate = PyThreadState_GET();
+ PyThreadState *tstate = PyThreadState_GET();
- *p_type = tstate->curexc_type;
- *p_value = tstate->curexc_value;
- *p_traceback = tstate->curexc_traceback;
+ *p_type = tstate->curexc_type;
+ *p_value = tstate->curexc_value;
+ *p_traceback = tstate->curexc_traceback;
- tstate->curexc_type = NULL;
- tstate->curexc_value = NULL;
- tstate->curexc_traceback = NULL;
+ tstate->curexc_type = NULL;
+ tstate->curexc_value = NULL;
+ tstate->curexc_traceback = NULL;
}
void
PyErr_Clear(void)
{
- PyErr_Restore(NULL, NULL, NULL);
+ PyErr_Restore(NULL, NULL, NULL);
}
/* Convenience functions to set a type error exception and return 0 */
@@ -266,258 +266,258 @@ PyErr_Clear(void)
int
PyErr_BadArgument(void)
{
- PyErr_SetString(PyExc_TypeError,
- "bad argument type for built-in operation");
- return 0;
+ PyErr_SetString(PyExc_TypeError,
+ "bad argument type for built-in operation");
+ return 0;
}
PyObject *
PyErr_NoMemory(void)
{
- if (PyErr_ExceptionMatches(PyExc_MemoryError))
- /* already current */
- return NULL;
+ if (PyErr_ExceptionMatches(PyExc_MemoryError))
+ /* already current */
+ return NULL;
- /* raise the pre-allocated instance if it still exists */
- if (PyExc_MemoryErrorInst)
- PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
- else
- /* this will probably fail since there's no memory and hee,
- hee, we have to instantiate this class
- */
- PyErr_SetNone(PyExc_MemoryError);
+ /* raise the pre-allocated instance if it still exists */
+ if (PyExc_MemoryErrorInst)
+ PyErr_SetObject(PyExc_MemoryError, PyExc_MemoryErrorInst);
+ else
+ /* this will probably fail since there's no memory and hee,
+ hee, we have to instantiate this class
+ */
+ PyErr_SetNone(PyExc_MemoryError);
- return NULL;
+ return NULL;
}
PyObject *
PyErr_SetFromErrnoWithFilenameObject(PyObject *exc, PyObject *filenameObject)
{
- PyObject *v;
- char *s;
- int i = errno;
+ PyObject *v;
+ char *s;
+ int i = errno;
#ifdef PLAN9
- char errbuf[ERRMAX];
+ char errbuf[ERRMAX];
#endif
#ifdef MS_WINDOWS
- char *s_buf = NULL;
- char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
+ char *s_buf = NULL;
+ char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
#endif
#ifdef EINTR
- if (i == EINTR && PyErr_CheckSignals())
- return NULL;
+ if (i == EINTR && PyErr_CheckSignals())
+ return NULL;
#endif
#ifdef PLAN9
- rerrstr(errbuf, sizeof errbuf);
- s = errbuf;
+ rerrstr(errbuf, sizeof errbuf);
+ s = errbuf;
#else
- if (i == 0)
- s = "Error"; /* Sometimes errno didn't get set */
- else
+ if (i == 0)
+ s = "Error"; /* Sometimes errno didn't get set */
+ else
#ifndef MS_WINDOWS
- s = strerror(i);
+ s = strerror(i);
#else
- {
- /* Note that the Win32 errors do not lineup with the
- errno error. So if the error is in the MSVC error
- table, we use it, otherwise we assume it really _is_
- a Win32 error code
- */
- if (i > 0 && i < _sys_nerr) {
- s = _sys_errlist[i];
- }
- else {
- int len = FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, /* no message source */
- i,
- MAKELANGID(LANG_NEUTRAL,
- SUBLANG_DEFAULT),
- /* Default language */
- (LPTSTR) &s_buf,
- 0, /* size not used */
- NULL); /* no args */
- if (len==0) {
- /* Only ever seen this in out-of-mem
- situations */
- sprintf(s_small_buf, "Windows Error 0x%X", i);
- s = s_small_buf;
- s_buf = NULL;
- } else {
- s = s_buf;
- /* remove trailing cr/lf and dots */
- while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
- s[--len] = '\0';
- }
- }
- }
+ {
+ /* Note that the Win32 errors do not lineup with the
+ errno error. So if the error is in the MSVC error
+ table, we use it, otherwise we assume it really _is_
+ a Win32 error code
+ */
+ if (i > 0 && i < _sys_nerr) {
+ s = _sys_errlist[i];
+ }
+ else {
+ int len = FormatMessage(
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, /* no message source */
+ i,
+ MAKELANGID(LANG_NEUTRAL,
+ SUBLANG_DEFAULT),
+ /* Default language */
+ (LPTSTR) &s_buf,
+ 0, /* size not used */
+ NULL); /* no args */
+ if (len==0) {
+ /* Only ever seen this in out-of-mem
+ situations */
+ sprintf(s_small_buf, "Windows Error 0x%X", i);
+ s = s_small_buf;
+ s_buf = NULL;
+ } else {
+ s = s_buf;
+ /* remove trailing cr/lf and dots */
+ while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
+ s[--len] = '\0';
+ }
+ }
+ }
#endif /* Unix/Windows */
#endif /* PLAN 9*/
- if (filenameObject != NULL)
- v = Py_BuildValue("(isO)", i, s, filenameObject);
- else
- v = Py_BuildValue("(is)", i, s);
- if (v != NULL) {
- PyErr_SetObject(exc, v);
- Py_DECREF(v);
- }
+ if (filenameObject != NULL)
+ v = Py_BuildValue("(isO)", i, s, filenameObject);
+ else
+ v = Py_BuildValue("(is)", i, s);
+ if (v != NULL) {
+ PyErr_SetObject(exc, v);
+ Py_DECREF(v);
+ }
#ifdef MS_WINDOWS
- LocalFree(s_buf);
+ LocalFree(s_buf);
#endif
- return NULL;
+ return NULL;
}
PyObject *
PyErr_SetFromErrnoWithFilename(PyObject *exc, const char *filename)
{
- PyObject *name = filename ? PyString_FromString(filename) : NULL;
- PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
- Py_XDECREF(name);
- return result;
+ PyObject *name = filename ? PyString_FromString(filename) : NULL;
+ PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
+ Py_XDECREF(name);
+ return result;
}
#ifdef MS_WINDOWS
PyObject *
PyErr_SetFromErrnoWithUnicodeFilename(PyObject *exc, const Py_UNICODE *filename)
{
- PyObject *name = filename ?
- PyUnicode_FromUnicode(filename, wcslen(filename)) :
- NULL;
- PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
- Py_XDECREF(name);
- return result;
+ PyObject *name = filename ?
+ PyUnicode_FromUnicode(filename, wcslen(filename)) :
+ NULL;
+ PyObject *result = PyErr_SetFromErrnoWithFilenameObject(exc, name);
+ Py_XDECREF(name);
+ return result;
}
#endif /* MS_WINDOWS */
PyObject *
PyErr_SetFromErrno(PyObject *exc)
{
- return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
+ return PyErr_SetFromErrnoWithFilenameObject(exc, NULL);
}
#ifdef MS_WINDOWS
/* Windows specific error code handling */
PyObject *PyErr_SetExcFromWindowsErrWithFilenameObject(
- PyObject *exc,
- int ierr,
- PyObject *filenameObject)
+ PyObject *exc,
+ int ierr,
+ PyObject *filenameObject)
{
- int len;
- char *s;
- char *s_buf = NULL; /* Free via LocalFree */
- char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
- PyObject *v;
- DWORD err = (DWORD)ierr;
- if (err==0) err = GetLastError();
- len = FormatMessage(
- /* Error API error */
- FORMAT_MESSAGE_ALLOCATE_BUFFER |
- FORMAT_MESSAGE_FROM_SYSTEM |
- FORMAT_MESSAGE_IGNORE_INSERTS,
- NULL, /* no message source */
- err,
- MAKELANGID(LANG_NEUTRAL,
- SUBLANG_DEFAULT), /* Default language */
- (LPTSTR) &s_buf,
- 0, /* size not used */
- NULL); /* no args */
- if (len==0) {
- /* Only seen this in out of mem situations */
- sprintf(s_small_buf, "Windows Error 0x%X", err);
- s = s_small_buf;
- s_buf = NULL;
- } else {
- s = s_buf;
- /* remove trailing cr/lf and dots */
- while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
- s[--len] = '\0';
- }
- if (filenameObject != NULL)
- v = Py_BuildValue("(isO)", err, s, filenameObject);
- else
- v = Py_BuildValue("(is)", err, s);
- if (v != NULL) {
- PyErr_SetObject(exc, v);
- Py_DECREF(v);
- }
- LocalFree(s_buf);
- return NULL;
+ int len;
+ char *s;
+ char *s_buf = NULL; /* Free via LocalFree */
+ char s_small_buf[28]; /* Room for "Windows Error 0xFFFFFFFF" */
+ PyObject *v;
+ DWORD err = (DWORD)ierr;
+ if (err==0) err = GetLastError();
+ len = FormatMessage(
+ /* Error API error */
+ FORMAT_MESSAGE_ALLOCATE_BUFFER |
+ FORMAT_MESSAGE_FROM_SYSTEM |
+ FORMAT_MESSAGE_IGNORE_INSERTS,
+ NULL, /* no message source */
+ err,
+ MAKELANGID(LANG_NEUTRAL,
+ SUBLANG_DEFAULT), /* Default language */
+ (LPTSTR) &s_buf,
+ 0, /* size not used */
+ NULL); /* no args */
+ if (len==0) {
+ /* Only seen this in out of mem situations */
+ sprintf(s_small_buf, "Windows Error 0x%X", err);
+ s = s_small_buf;
+ s_buf = NULL;
+ } else {
+ s = s_buf;
+ /* remove trailing cr/lf and dots */
+ while (len > 0 && (s[len-1] <= ' ' || s[len-1] == '.'))
+ s[--len] = '\0';
+ }
+ if (filenameObject != NULL)
+ v = Py_BuildValue("(isO)", err, s, filenameObject);
+ else
+ v = Py_BuildValue("(is)", err, s);
+ if (v != NULL) {
+ PyErr_SetObject(exc, v);
+ Py_DECREF(v);
+ }
+ LocalFree(s_buf);
+ return NULL;
}
PyObject *PyErr_SetExcFromWindowsErrWithFilename(
- PyObject *exc,
- int ierr,
- const char *filename)
+ PyObject *exc,
+ int ierr,
+ const char *filename)
{
- PyObject *name = filename ? PyString_FromString(filename) : NULL;
- PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
- ierr,
- name);
- Py_XDECREF(name);
- return ret;
+ PyObject *name = filename ? PyString_FromString(filename) : NULL;
+ PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
+ ierr,
+ name);
+ Py_XDECREF(name);
+ return ret;
}
PyObject *PyErr_SetExcFromWindowsErrWithUnicodeFilename(
- PyObject *exc,
- int ierr,
- const Py_UNICODE *filename)
+ PyObject *exc,
+ int ierr,
+ const Py_UNICODE *filename)
{
- PyObject *name = filename ?
- PyUnicode_FromUnicode(filename, wcslen(filename)) :
- NULL;
- PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
- ierr,
- name);
- Py_XDECREF(name);
- return ret;
+ PyObject *name = filename ?
+ PyUnicode_FromUnicode(filename, wcslen(filename)) :
+ NULL;
+ PyObject *ret = PyErr_SetExcFromWindowsErrWithFilenameObject(exc,
+ ierr,
+ name);
+ Py_XDECREF(name);
+ return ret;
}
PyObject *PyErr_SetExcFromWindowsErr(PyObject *exc, int ierr)
{
- return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
+ return PyErr_SetExcFromWindowsErrWithFilename(exc, ierr, NULL);
}
PyObject *PyErr_SetFromWindowsErr(int ierr)
{
- return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
- ierr, NULL);
+ return PyErr_SetExcFromWindowsErrWithFilename(PyExc_WindowsError,
+ ierr, NULL);
}
PyObject *PyErr_SetFromWindowsErrWithFilename(
- int ierr,
- const char *filename)
+ int ierr,
+ const char *filename)
{
- PyObject *name = filename ? PyString_FromString(filename) : NULL;
- PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
- PyExc_WindowsError,
- ierr, name);
- Py_XDECREF(name);
- return result;
+ PyObject *name = filename ? PyString_FromString(filename) : NULL;
+ PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
+ PyExc_WindowsError,
+ ierr, name);
+ Py_XDECREF(name);
+ return result;
}
PyObject *PyErr_SetFromWindowsErrWithUnicodeFilename(
- int ierr,
- const Py_UNICODE *filename)
+ int ierr,
+ const Py_UNICODE *filename)
{
- PyObject *name = filename ?
- PyUnicode_FromUnicode(filename, wcslen(filename)) :
- NULL;
- PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
- PyExc_WindowsError,
- ierr, name);
- Py_XDECREF(name);
- return result;
+ PyObject *name = filename ?
+ PyUnicode_FromUnicode(filename, wcslen(filename)) :
+ NULL;
+ PyObject *result = PyErr_SetExcFromWindowsErrWithFilenameObject(
+ PyExc_WindowsError,
+ ierr, name);
+ Py_XDECREF(name);
+ return result;
}
#endif /* MS_WINDOWS */
void
_PyErr_BadInternalCall(char *filename, int lineno)
{
- PyErr_Format(PyExc_SystemError,
- "%s:%d: bad argument to internal function",
- filename, lineno);
+ PyErr_Format(PyExc_SystemError,
+ "%s:%d: bad argument to internal function",
+ filename, lineno);
}
/* Remove the preprocessor macro for PyErr_BadInternalCall() so that we can
@@ -526,8 +526,8 @@ _PyErr_BadInternalCall(char *filename, int lineno)
void
PyErr_BadInternalCall(void)
{
- PyErr_Format(PyExc_SystemError,
- "bad argument to internal function");
+ PyErr_Format(PyExc_SystemError,
+ "bad argument to internal function");
}
#define PyErr_BadInternalCall() _PyErr_BadInternalCall(__FILE__, __LINE__)
@@ -536,20 +536,20 @@ PyErr_BadInternalCall(void)
PyObject *
PyErr_Format(PyObject *exception, const char *format, ...)
{
- va_list vargs;
- PyObject* string;
+ va_list vargs;
+ PyObject* string;
#ifdef HAVE_STDARG_PROTOTYPES
- va_start(vargs, format);
+ va_start(vargs, format);
#else
- va_start(vargs);
+ va_start(vargs);
#endif
- string = PyString_FromFormatV(format, vargs);
- PyErr_SetObject(exception, string);
- Py_XDECREF(string);
- va_end(vargs);
- return NULL;
+ string = PyString_FromFormatV(format, vargs);
+ PyErr_SetObject(exception, string);
+ Py_XDECREF(string);
+ va_end(vargs);
+ return NULL;
}
@@ -557,51 +557,51 @@ PyErr_Format(PyObject *exception, const char *format, ...)
PyObject *
PyErr_NewException(char *name, PyObject *base, PyObject *dict)
{
- char *dot;
- PyObject *modulename = NULL;
- PyObject *classname = NULL;
- PyObject *mydict = NULL;
- PyObject *bases = NULL;
- PyObject *result = NULL;
- dot = strrchr(name, '.');
- if (dot == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "PyErr_NewException: name must be module.class");
- return NULL;
- }
- if (base == NULL)
- base = PyExc_Exception;
- if (dict == NULL) {
- dict = mydict = PyDict_New();
- if (dict == NULL)
- goto failure;
- }
- if (PyDict_GetItemString(dict, "__module__") == NULL) {
- modulename = PyString_FromStringAndSize(name,
- (Py_ssize_t)(dot-name));
- if (modulename == NULL)
- goto failure;
- if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
- goto failure;
- }
- if (PyTuple_Check(base)) {
- bases = base;
- /* INCREF as we create a new ref in the else branch */
- Py_INCREF(bases);
- } else {
- bases = PyTuple_Pack(1, base);
- if (bases == NULL)
- goto failure;
- }
- /* Create a real new-style class. */
- result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
- dot+1, bases, dict);
+ char *dot;
+ PyObject *modulename = NULL;
+ PyObject *classname = NULL;
+ PyObject *mydict = NULL;
+ PyObject *bases = NULL;
+ PyObject *result = NULL;
+ dot = strrchr(name, '.');
+ if (dot == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "PyErr_NewException: name must be module.class");
+ return NULL;
+ }
+ if (base == NULL)
+ base = PyExc_Exception;
+ if (dict == NULL) {
+ dict = mydict = PyDict_New();
+ if (dict == NULL)
+ goto failure;
+ }
+ if (PyDict_GetItemString(dict, "__module__") == NULL) {
+ modulename = PyString_FromStringAndSize(name,
+ (Py_ssize_t)(dot-name));
+ if (modulename == NULL)
+ goto failure;
+ if (PyDict_SetItemString(dict, "__module__", modulename) != 0)
+ goto failure;
+ }
+ if (PyTuple_Check(base)) {
+ bases = base;
+ /* INCREF as we create a new ref in the else branch */
+ Py_INCREF(bases);
+ } else {
+ bases = PyTuple_Pack(1, base);
+ if (bases == NULL)
+ goto failure;
+ }
+ /* Create a real new-style class. */
+ result = PyObject_CallFunction((PyObject *)&PyType_Type, "sOO",
+ dot+1, bases, dict);
failure:
- Py_XDECREF(bases);
- Py_XDECREF(mydict);
- Py_XDECREF(classname);
- Py_XDECREF(modulename);
- return result;
+ Py_XDECREF(bases);
+ Py_XDECREF(mydict);
+ Py_XDECREF(classname);
+ Py_XDECREF(modulename);
+ return result;
}
@@ -609,32 +609,32 @@ PyErr_NewException(char *name, PyObject *base, PyObject *dict)
PyObject *
PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
{
- int result;
- PyObject *ret = NULL;
- PyObject *mydict = NULL; /* points to the dict only if we create it */
- PyObject *docobj;
-
- if (dict == NULL) {
- dict = mydict = PyDict_New();
- if (dict == NULL) {
- return NULL;
- }
- }
-
- if (doc != NULL) {
- docobj = PyString_FromString(doc);
- if (docobj == NULL)
- goto failure;
- result = PyDict_SetItemString(dict, "__doc__", docobj);
- Py_DECREF(docobj);
- if (result < 0)
- goto failure;
- }
-
- ret = PyErr_NewException(name, base, dict);
+ int result;
+ PyObject *ret = NULL;
+ PyObject *mydict = NULL; /* points to the dict only if we create it */
+ PyObject *docobj;
+
+ if (dict == NULL) {
+ dict = mydict = PyDict_New();
+ if (dict == NULL) {
+ return NULL;
+ }
+ }
+
+ if (doc != NULL) {
+ docobj = PyString_FromString(doc);
+ if (docobj == NULL)
+ goto failure;
+ result = PyDict_SetItemString(dict, "__doc__", docobj);
+ Py_DECREF(docobj);
+ if (result < 0)
+ goto failure;
+ }
+
+ ret = PyErr_NewException(name, base, dict);
failure:
- Py_XDECREF(mydict);
- return ret;
+ Py_XDECREF(mydict);
+ return ret;
}
@@ -643,52 +643,52 @@ PyErr_NewExceptionWithDoc(char *name, char *doc, PyObject *base, PyObject *dict)
void
PyErr_WriteUnraisable(PyObject *obj)
{
- PyObject *f, *t, *v, *tb;
- PyErr_Fetch(&t, &v, &tb);
- f = PySys_GetObject("stderr");
- if (f != NULL) {
- PyFile_WriteString("Exception ", f);
- if (t) {
- PyObject* moduleName;
- char* className;
- assert(PyExceptionClass_Check(t));
- className = PyExceptionClass_Name(t);
- if (className != NULL) {
- char *dot = strrchr(className, '.');
- if (dot != NULL)
- className = dot+1;
- }
-
- moduleName = PyObject_GetAttrString(t, "__module__");
- if (moduleName == NULL)
- PyFile_WriteString("<unknown>", f);
- else {
- char* modstr = PyString_AsString(moduleName);
- if (modstr &&
- strcmp(modstr, "exceptions") != 0)
- {
- PyFile_WriteString(modstr, f);
- PyFile_WriteString(".", f);
- }
- }
- if (className == NULL)
- PyFile_WriteString("<unknown>", f);
- else
- PyFile_WriteString(className, f);
- if (v && v != Py_None) {
- PyFile_WriteString(": ", f);
- PyFile_WriteObject(v, f, 0);
- }
- Py_XDECREF(moduleName);
- }
- PyFile_WriteString(" in ", f);
- PyFile_WriteObject(obj, f, 0);
- PyFile_WriteString(" ignored\n", f);
- PyErr_Clear(); /* Just in case */
- }
- Py_XDECREF(t);
- Py_XDECREF(v);
- Py_XDECREF(tb);
+ PyObject *f, *t, *v, *tb;
+ PyErr_Fetch(&t, &v, &tb);
+ f = PySys_GetObject("stderr");
+ if (f != NULL) {
+ PyFile_WriteString("Exception ", f);
+ if (t) {
+ PyObject* moduleName;
+ char* className;
+ assert(PyExceptionClass_Check(t));
+ className = PyExceptionClass_Name(t);
+ if (className != NULL) {
+ char *dot = strrchr(className, '.');
+ if (dot != NULL)
+ className = dot+1;
+ }
+
+ moduleName = PyObject_GetAttrString(t, "__module__");
+ if (moduleName == NULL)
+ PyFile_WriteString("<unknown>", f);
+ else {
+ char* modstr = PyString_AsString(moduleName);
+ if (modstr &&
+ strcmp(modstr, "exceptions") != 0)
+ {
+ PyFile_WriteString(modstr, f);
+ PyFile_WriteString(".", f);
+ }
+ }
+ if (className == NULL)
+ PyFile_WriteString("<unknown>", f);
+ else
+ PyFile_WriteString(className, f);
+ if (v && v != Py_None) {
+ PyFile_WriteString(": ", f);
+ PyFile_WriteObject(v, f, 0);
+ }
+ Py_XDECREF(moduleName);
+ }
+ PyFile_WriteString(" in ", f);
+ PyFile_WriteObject(obj, f, 0);
+ PyFile_WriteString(" ignored\n", f);
+ PyErr_Clear(); /* Just in case */
+ }
+ Py_XDECREF(t);
+ Py_XDECREF(v);
+ Py_XDECREF(tb);
}
extern PyObject *PyModule_GetWarningsModule(void);
@@ -701,59 +701,59 @@ extern PyObject *PyModule_GetWarningsModule(void);
void
PyErr_SyntaxLocation(const char *filename, int lineno)
{
- PyObject *exc, *v, *tb, *tmp;
-
- /* add attributes for the line number and filename for the error */
- PyErr_Fetch(&exc, &v, &tb);
- PyErr_NormalizeException(&exc, &v, &tb);
- /* XXX check that it is, indeed, a syntax error. It might not
- * be, though. */
- tmp = PyInt_FromLong(lineno);
- if (tmp == NULL)
- PyErr_Clear();
- else {
- if (PyObject_SetAttrString(v, "lineno", tmp))
- PyErr_Clear();
- Py_DECREF(tmp);
- }
- if (filename != NULL) {
- tmp = PyString_FromString(filename);
- if (tmp == NULL)
- PyErr_Clear();
- else {
- if (PyObject_SetAttrString(v, "filename", tmp))
- PyErr_Clear();
- Py_DECREF(tmp);
- }
-
- tmp = PyErr_ProgramText(filename, lineno);
- if (tmp) {
- if (PyObject_SetAttrString(v, "text", tmp))
- PyErr_Clear();
- Py_DECREF(tmp);
- }
- }
- if (PyObject_SetAttrString(v, "offset", Py_None)) {
- PyErr_Clear();
- }
- if (exc != PyExc_SyntaxError) {
- if (!PyObject_HasAttrString(v, "msg")) {
- tmp = PyObject_Str(v);
- if (tmp) {
- if (PyObject_SetAttrString(v, "msg", tmp))
- PyErr_Clear();
- Py_DECREF(tmp);
- } else {
- PyErr_Clear();
- }
- }
- if (!PyObject_HasAttrString(v, "print_file_and_line")) {
- if (PyObject_SetAttrString(v, "print_file_and_line",
- Py_None))
- PyErr_Clear();
- }
- }
- PyErr_Restore(exc, v, tb);
+ PyObject *exc, *v, *tb, *tmp;
+
+ /* add attributes for the line number and filename for the error */
+ PyErr_Fetch(&exc, &v, &tb);
+ PyErr_NormalizeException(&exc, &v, &tb);
+ /* XXX check that it is, indeed, a syntax error. It might not
+ * be, though. */
+ tmp = PyInt_FromLong(lineno);
+ if (tmp == NULL)
+ PyErr_Clear();
+ else {
+ if (PyObject_SetAttrString(v, "lineno", tmp))
+ PyErr_Clear();
+ Py_DECREF(tmp);
+ }
+ if (filename != NULL) {
+ tmp = PyString_FromString(filename);
+ if (tmp == NULL)
+ PyErr_Clear();
+ else {
+ if (PyObject_SetAttrString(v, "filename", tmp))
+ PyErr_Clear();
+ Py_DECREF(tmp);
+ }
+
+ tmp = PyErr_ProgramText(filename, lineno);
+ if (tmp) {
+ if (PyObject_SetAttrString(v, "text", tmp))
+ PyErr_Clear();
+ Py_DECREF(tmp);
+ }
+ }
+ if (PyObject_SetAttrString(v, "offset", Py_None)) {
+ PyErr_Clear();
+ }
+ if (exc != PyExc_SyntaxError) {
+ if (!PyObject_HasAttrString(v, "msg")) {
+ tmp = PyObject_Str(v);
+ if (tmp) {
+ if (PyObject_SetAttrString(v, "msg", tmp))
+ PyErr_Clear();
+ Py_DECREF(tmp);
+ } else {
+ PyErr_Clear();
+ }
+ }
+ if (!PyObject_HasAttrString(v, "print_file_and_line")) {
+ if (PyObject_SetAttrString(v, "print_file_and_line",
+ Py_None))
+ PyErr_Clear();
+ }
+ }
+ PyErr_Restore(exc, v, tb);
}
/* com_fetch_program_text will attempt to load the line of text that
@@ -767,36 +767,36 @@ PyErr_SyntaxLocation(const char *filename, int lineno)
PyObject *
PyErr_ProgramText(const char *filename, int lineno)
{
- FILE *fp;
- int i;
- char linebuf[1000];
-
- if (filename == NULL || *filename == '\0' || lineno <= 0)
- return NULL;
- fp = fopen(filename, "r" PY_STDIOTEXTMODE);
- if (fp == NULL)
- return NULL;
- for (i = 0; i < lineno; i++) {
- char *pLastChar = &linebuf[sizeof(linebuf) - 2];
- do {
- *pLastChar = '\0';
- if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
- break;
- /* fgets read *something*; if it didn't get as
- far as pLastChar, it must have found a newline
- or hit the end of the file; if pLastChar is \n,
- it obviously found a newline; else we haven't
- yet seen a newline, so must continue */
- } while (*pLastChar != '\0' && *pLastChar != '\n');
- }
- fclose(fp);
- if (i == lineno) {
- char *p = linebuf;
- while (*p == ' ' || *p == '\t' || *p == '\014')
- p++;
- return PyString_FromString(p);
- }
- return NULL;
+ FILE *fp;
+ int i;
+ char linebuf[1000];
+
+ if (filename == NULL || *filename == '\0' || lineno <= 0)
+ return NULL;
+ fp = fopen(filename, "r" PY_STDIOTEXTMODE);
+ if (fp == NULL)
+ return NULL;
+ for (i = 0; i < lineno; i++) {
+ char *pLastChar = &linebuf[sizeof(linebuf) - 2];
+ do {
+ *pLastChar = '\0';
+ if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, fp, NULL) == NULL)
+ break;
+ /* fgets read *something*; if it didn't get as
+ far as pLastChar, it must have found a newline
+ or hit the end of the file; if pLastChar is \n,
+ it obviously found a newline; else we haven't
+ yet seen a newline, so must continue */
+ } while (*pLastChar != '\0' && *pLastChar != '\n');
+ }
+ fclose(fp);
+ if (i == lineno) {
+ char *p = linebuf;
+ while (*p == ' ' || *p == '\t' || *p == '\014')
+ p++;
+ return PyString_FromString(p);
+ }
+ return NULL;
}
#ifdef __cplusplus
diff --git a/Python/frozen.c b/Python/frozen.c
index 946d626..ae7e9a4 100644
--- a/Python/frozen.c
+++ b/Python/frozen.c
@@ -12,24 +12,24 @@
the appropriate bytes from M___main__.c. */
static unsigned char M___hello__[] = {
- 99,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
- 0,115,9,0,0,0,100,0,0,71,72,100,1,0,83,40,
- 2,0,0,0,115,14,0,0,0,72,101,108,108,111,32,119,
- 111,114,108,100,46,46,46,78,40,0,0,0,0,40,0,0,
- 0,0,40,0,0,0,0,40,0,0,0,0,115,8,0,0,
- 0,104,101,108,108,111,46,112,121,115,1,0,0,0,63,1,
- 0,0,0,115,0,0,0,0,
+ 99,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,
+ 0,115,9,0,0,0,100,0,0,71,72,100,1,0,83,40,
+ 2,0,0,0,115,14,0,0,0,72,101,108,108,111,32,119,
+ 111,114,108,100,46,46,46,78,40,0,0,0,0,40,0,0,
+ 0,0,40,0,0,0,0,40,0,0,0,0,115,8,0,0,
+ 0,104,101,108,108,111,46,112,121,115,1,0,0,0,63,1,
+ 0,0,0,115,0,0,0,0,
};
#define SIZE (int)sizeof(M___hello__)
static struct _frozen _PyImport_FrozenModules[] = {
- /* Test module */
- {"__hello__", M___hello__, SIZE},
- /* Test package (negative size indicates package-ness) */
- {"__phello__", M___hello__, -SIZE},
- {"__phello__.spam", M___hello__, SIZE},
- {0, 0, 0} /* sentinel */
+ /* Test module */
+ {"__hello__", M___hello__, SIZE},
+ /* Test package (negative size indicates package-ness) */
+ {"__phello__", M___hello__, -SIZE},
+ {"__phello__.spam", M___hello__, SIZE},
+ {0, 0, 0} /* sentinel */
};
/* Embedding apps may change this pointer to point to their favorite
diff --git a/Python/frozenmain.c b/Python/frozenmain.c
index 397f046..d31da07 100644
--- a/Python/frozenmain.c
+++ b/Python/frozenmain.c
@@ -14,55 +14,55 @@ extern int PyInitFrozenExtensions(void);
int
Py_FrozenMain(int argc, char **argv)
{
- char *p;
- int n, sts;
- int inspect = 0;
- int unbuffered = 0;
+ char *p;
+ int n, sts;
+ int inspect = 0;
+ int unbuffered = 0;
- Py_FrozenFlag = 1; /* Suppress errors from getpath.c */
+ Py_FrozenFlag = 1; /* Suppress errors from getpath.c */
- if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
- inspect = 1;
- if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
- unbuffered = 1;
+ if ((p = Py_GETENV("PYTHONINSPECT")) && *p != '\0')
+ inspect = 1;
+ if ((p = Py_GETENV("PYTHONUNBUFFERED")) && *p != '\0')
+ unbuffered = 1;
- if (unbuffered) {
- setbuf(stdin, (char *)NULL);
- setbuf(stdout, (char *)NULL);
- setbuf(stderr, (char *)NULL);
- }
+ if (unbuffered) {
+ setbuf(stdin, (char *)NULL);
+ setbuf(stdout, (char *)NULL);
+ setbuf(stderr, (char *)NULL);
+ }
#ifdef MS_WINDOWS
- PyInitFrozenExtensions();
+ PyInitFrozenExtensions();
#endif /* MS_WINDOWS */
- Py_SetProgramName(argv[0]);
- Py_Initialize();
+ Py_SetProgramName(argv[0]);
+ Py_Initialize();
#ifdef MS_WINDOWS
- PyWinFreeze_ExeInit();
+ PyWinFreeze_ExeInit();
#endif
- if (Py_VerboseFlag)
- fprintf(stderr, "Python %s\n%s\n",
- Py_GetVersion(), Py_GetCopyright());
+ if (Py_VerboseFlag)
+ fprintf(stderr, "Python %s\n%s\n",
+ Py_GetVersion(), Py_GetCopyright());
- PySys_SetArgv(argc, argv);
+ PySys_SetArgv(argc, argv);
- n = PyImport_ImportFrozenModule("__main__");
- if (n == 0)
- Py_FatalError("__main__ not frozen");
- if (n < 0) {
- PyErr_Print();
- sts = 1;
- }
- else
- sts = 0;
+ n = PyImport_ImportFrozenModule("__main__");
+ if (n == 0)
+ Py_FatalError("__main__ not frozen");
+ if (n < 0) {
+ PyErr_Print();
+ sts = 1;
+ }
+ else
+ sts = 0;
- if (inspect && isatty((int)fileno(stdin)))
- sts = PyRun_AnyFile(stdin, "<stdin>") != 0;
+ if (inspect && isatty((int)fileno(stdin)))
+ sts = PyRun_AnyFile(stdin, "<stdin>") != 0;
#ifdef MS_WINDOWS
- PyWinFreeze_ExeTerm();
+ PyWinFreeze_ExeTerm();
#endif
- Py_Finalize();
- return sts;
+ Py_Finalize();
+ return sts;
}
diff --git a/Python/future.c b/Python/future.c
index 532a7fd..96be757 100644
--- a/Python/future.c
+++ b/Python/future.c
@@ -14,129 +14,129 @@
static int
future_check_features(PyFutureFeatures *ff, stmt_ty s, const char *filename)
{
- int i;
- asdl_seq *names;
-
- assert(s->kind == ImportFrom_kind);
-
- names = s->v.ImportFrom.names;
- for (i = 0; i < asdl_seq_LEN(names); i++) {
- alias_ty name = (alias_ty)asdl_seq_GET(names, i);
- const char *feature = PyString_AsString(name->name);
- if (!feature)
- return 0;
- if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) {
- continue;
- } else if (strcmp(feature, FUTURE_GENERATORS) == 0) {
- continue;
- } else if (strcmp(feature, FUTURE_DIVISION) == 0) {
- ff->ff_features |= CO_FUTURE_DIVISION;
- } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) {
- ff->ff_features |= CO_FUTURE_ABSOLUTE_IMPORT;
- } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) {
- ff->ff_features |= CO_FUTURE_WITH_STATEMENT;
- } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) {
- ff->ff_features |= CO_FUTURE_PRINT_FUNCTION;
- } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) {
- ff->ff_features |= CO_FUTURE_UNICODE_LITERALS;
- } else if (strcmp(feature, "braces") == 0) {
- PyErr_SetString(PyExc_SyntaxError,
- "not a chance");
- PyErr_SyntaxLocation(filename, s->lineno);
- return 0;
- } else {
- PyErr_Format(PyExc_SyntaxError,
- UNDEFINED_FUTURE_FEATURE, feature);
- PyErr_SyntaxLocation(filename, s->lineno);
- return 0;
- }
- }
- return 1;
+ int i;
+ asdl_seq *names;
+
+ assert(s->kind == ImportFrom_kind);
+
+ names = s->v.ImportFrom.names;
+ for (i = 0; i < asdl_seq_LEN(names); i++) {
+ alias_ty name = (alias_ty)asdl_seq_GET(names, i);
+ const char *feature = PyString_AsString(name->name);
+ if (!feature)
+ return 0;
+ if (strcmp(feature, FUTURE_NESTED_SCOPES) == 0) {
+ continue;
+ } else if (strcmp(feature, FUTURE_GENERATORS) == 0) {
+ continue;
+ } else if (strcmp(feature, FUTURE_DIVISION) == 0) {
+ ff->ff_features |= CO_FUTURE_DIVISION;
+ } else if (strcmp(feature, FUTURE_ABSOLUTE_IMPORT) == 0) {
+ ff->ff_features |= CO_FUTURE_ABSOLUTE_IMPORT;
+ } else if (strcmp(feature, FUTURE_WITH_STATEMENT) == 0) {
+ ff->ff_features |= CO_FUTURE_WITH_STATEMENT;
+ } else if (strcmp(feature, FUTURE_PRINT_FUNCTION) == 0) {
+ ff->ff_features |= CO_FUTURE_PRINT_FUNCTION;
+ } else if (strcmp(feature, FUTURE_UNICODE_LITERALS) == 0) {
+ ff->ff_features |= CO_FUTURE_UNICODE_LITERALS;
+ } else if (strcmp(feature, "braces") == 0) {
+ PyErr_SetString(PyExc_SyntaxError,
+ "not a chance");
+ PyErr_SyntaxLocation(filename, s->lineno);
+ return 0;
+ } else {
+ PyErr_Format(PyExc_SyntaxError,
+ UNDEFINED_FUTURE_FEATURE, feature);
+ PyErr_SyntaxLocation(filename, s->lineno);
+ return 0;
+ }
+ }
+ return 1;
}
static int
future_parse(PyFutureFeatures *ff, mod_ty mod, const char *filename)
{
- int i, found_docstring = 0, done = 0, prev_line = 0;
-
- static PyObject *future;
- if (!future) {
- future = PyString_InternFromString("__future__");
- if (!future)
- return 0;
- }
-
- if (!(mod->kind == Module_kind || mod->kind == Interactive_kind))
- return 1;
-
- /* A subsequent pass will detect future imports that don't
- appear at the beginning of the file. There's one case,
- however, that is easier to handle here: A series of imports
- joined by semi-colons, where the first import is a future
- statement but some subsequent import has the future form
- but is preceded by a regular import.
- */
-
-
- for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) {
- stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i);
-
- if (done && s->lineno > prev_line)
- return 1;
- prev_line = s->lineno;
-
- /* The tests below will return from this function unless it is
- still possible to find a future statement. The only things
- that can precede a future statement are another future
- statement and a doc string.
- */
-
- if (s->kind == ImportFrom_kind) {
- if (s->v.ImportFrom.module == future) {
- if (done) {
- PyErr_SetString(PyExc_SyntaxError,
- ERR_LATE_FUTURE);
- PyErr_SyntaxLocation(filename,
- s->lineno);
- return 0;
- }
- if (!future_check_features(ff, s, filename))
- return 0;
- ff->ff_lineno = s->lineno;
- }
- else
- done = 1;
- }
- else if (s->kind == Expr_kind && !found_docstring) {
- expr_ty e = s->v.Expr.value;
- if (e->kind != Str_kind)
- done = 1;
- else
- found_docstring = 1;
- }
- else
- done = 1;
- }
- return 1;
+ int i, found_docstring = 0, done = 0, prev_line = 0;
+
+ static PyObject *future;
+ if (!future) {
+ future = PyString_InternFromString("__future__");
+ if (!future)
+ return 0;
+ }
+
+ if (!(mod->kind == Module_kind || mod->kind == Interactive_kind))
+ return 1;
+
+ /* A subsequent pass will detect future imports that don't
+ appear at the beginning of the file. There's one case,
+ however, that is easier to handle here: A series of imports
+ joined by semi-colons, where the first import is a future
+ statement but some subsequent import has the future form
+ but is preceded by a regular import.
+ */
+
+
+ for (i = 0; i < asdl_seq_LEN(mod->v.Module.body); i++) {
+ stmt_ty s = (stmt_ty)asdl_seq_GET(mod->v.Module.body, i);
+
+ if (done && s->lineno > prev_line)
+ return 1;
+ prev_line = s->lineno;
+
+ /* The tests below will return from this function unless it is
+ still possible to find a future statement. The only things
+ that can precede a future statement are another future
+ statement and a doc string.
+ */
+
+ if (s->kind == ImportFrom_kind) {
+ if (s->v.ImportFrom.module == future) {
+ if (done) {
+ PyErr_SetString(PyExc_SyntaxError,
+ ERR_LATE_FUTURE);
+ PyErr_SyntaxLocation(filename,
+ s->lineno);
+ return 0;
+ }
+ if (!future_check_features(ff, s, filename))
+ return 0;
+ ff->ff_lineno = s->lineno;
+ }
+ else
+ done = 1;
+ }
+ else if (s->kind == Expr_kind && !found_docstring) {
+ expr_ty e = s->v.Expr.value;
+ if (e->kind != Str_kind)
+ done = 1;
+ else
+ found_docstring = 1;
+ }
+ else
+ done = 1;
+ }
+ return 1;
}
PyFutureFeatures *
PyFuture_FromAST(mod_ty mod, const char *filename)
{
- PyFutureFeatures *ff;
-
- ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures));
- if (ff == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- ff->ff_features = 0;
- ff->ff_lineno = -1;
-
- if (!future_parse(ff, mod, filename)) {
- PyObject_Free(ff);
- return NULL;
- }
- return ff;
+ PyFutureFeatures *ff;
+
+ ff = (PyFutureFeatures *)PyObject_Malloc(sizeof(PyFutureFeatures));
+ if (ff == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ ff->ff_features = 0;
+ ff->ff_lineno = -1;
+
+ if (!future_parse(ff, mod, filename)) {
+ PyObject_Free(ff);
+ return NULL;
+ }
+ return ff;
}
diff --git a/Python/getargs.c b/Python/getargs.c
index 502e9cd..7c3e9fa 100644
--- a/Python/getargs.c
+++ b/Python/getargs.c
@@ -7,16 +7,16 @@
#ifdef __cplusplus
-extern "C" {
+extern "C" {
#endif
int PyArg_Parse(PyObject *, const char *, ...);
int PyArg_ParseTuple(PyObject *, const char *, ...);
int PyArg_VaParse(PyObject *, const char *, va_list);
int PyArg_ParseTupleAndKeywords(PyObject *, PyObject *,
- const char *, char **, ...);
+ const char *, char **, ...);
int PyArg_VaParseTupleAndKeywords(PyObject *, PyObject *,
- const char *, char **, va_list);
+ const char *, char **, va_list);
#ifdef HAVE_DECLSPEC_DLL
/* Export functions */
@@ -37,103 +37,103 @@ PyAPI_FUNC(int) _PyArg_VaParseTupleAndKeywords_SizeT(PyObject *, PyObject *,
/* Forward */
static int vgetargs1(PyObject *, const char *, va_list *, int);
static void seterror(int, const char *, int *, const char *, const char *);
-static char *convertitem(PyObject *, const char **, va_list *, int, int *,
+static char *convertitem(PyObject *, const char **, va_list *, int, int *,
char *, size_t, PyObject **);
static char *converttuple(PyObject *, const char **, va_list *, int,
- int *, char *, size_t, int, PyObject **);
+ int *, char *, size_t, int, PyObject **);
static char *convertsimple(PyObject *, const char **, va_list *, int, char *,
- size_t, PyObject **);
+ size_t, PyObject **);
static Py_ssize_t convertbuffer(PyObject *, void **p, char **);
static int getbuffer(PyObject *, Py_buffer *, char**);
static int vgetargskeywords(PyObject *, PyObject *,
- const char *, char **, va_list *, int);
+ const char *, char **, va_list *, int);
static char *skipitem(const char **, va_list *, int);
int
PyArg_Parse(PyObject *args, const char *format, ...)
{
- int retval;
- va_list va;
-
- va_start(va, format);
- retval = vgetargs1(args, format, &va, FLAG_COMPAT);
- va_end(va);
- return retval;
+ int retval;
+ va_list va;
+
+ va_start(va, format);
+ retval = vgetargs1(args, format, &va, FLAG_COMPAT);
+ va_end(va);
+ return retval;
}
int
_PyArg_Parse_SizeT(PyObject *args, char *format, ...)
{
- int retval;
- va_list va;
-
- va_start(va, format);
- retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T);
- va_end(va);
- return retval;
+ int retval;
+ va_list va;
+
+ va_start(va, format);
+ retval = vgetargs1(args, format, &va, FLAG_COMPAT|FLAG_SIZE_T);
+ va_end(va);
+ return retval;
}
int
PyArg_ParseTuple(PyObject *args, const char *format, ...)
{
- int retval;
- va_list va;
-
- va_start(va, format);
- retval = vgetargs1(args, format, &va, 0);
- va_end(va);
- return retval;
+ int retval;
+ va_list va;
+
+ va_start(va, format);
+ retval = vgetargs1(args, format, &va, 0);
+ va_end(va);
+ return retval;
}
int
_PyArg_ParseTuple_SizeT(PyObject *args, char *format, ...)
{
- int retval;
- va_list va;
-
- va_start(va, format);
- retval = vgetargs1(args, format, &va, FLAG_SIZE_T);
- va_end(va);
- return retval;
+ int retval;
+ va_list va;
+
+ va_start(va, format);
+ retval = vgetargs1(args, format, &va, FLAG_SIZE_T);
+ va_end(va);
+ return retval;
}
int
PyArg_VaParse(PyObject *args, const char *format, va_list va)
{
- va_list lva;
+ va_list lva;
#ifdef VA_LIST_IS_ARRAY
- memcpy(lva, va, sizeof(va_list));
+ memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(lva, va);
+ __va_copy(lva, va);
#else
- lva = va;
+ lva = va;
#endif
#endif
- return vgetargs1(args, format, &lva, 0);
+ return vgetargs1(args, format, &lva, 0);
}
int
_PyArg_VaParse_SizeT(PyObject *args, char *format, va_list va)
{
- va_list lva;
+ va_list lva;
#ifdef VA_LIST_IS_ARRAY
- memcpy(lva, va, sizeof(va_list));
+ memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(lva, va);
+ __va_copy(lva, va);
#else
- lva = va;
+ lva = va;
#endif
#endif
- return vgetargs1(args, format, &lva, FLAG_SIZE_T);
+ return vgetargs1(args, format, &lva, FLAG_SIZE_T);
}
@@ -145,221 +145,221 @@ _PyArg_VaParse_SizeT(PyObject *args, char *format, va_list va)
static void
cleanup_ptr(PyObject *self)
{
- void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR);
- if (ptr) {
- PyMem_FREE(ptr);
- }
+ void *ptr = PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_PTR);
+ if (ptr) {
+ PyMem_FREE(ptr);
+ }
}
static void
cleanup_buffer(PyObject *self)
{
- Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER);
- if (ptr) {
- PyBuffer_Release(ptr);
- }
+ Py_buffer *ptr = (Py_buffer *)PyCapsule_GetPointer(self, GETARGS_CAPSULE_NAME_CLEANUP_BUFFER);
+ if (ptr) {
+ PyBuffer_Release(ptr);
+ }
}
static int
addcleanup(void *ptr, PyObject **freelist, PyCapsule_Destructor destr)
{
- PyObject *cobj;
- const char *name;
-
- if (!*freelist) {
- *freelist = PyList_New(0);
- if (!*freelist) {
- destr(ptr);
- return -1;
- }
- }
-
- if (destr == cleanup_ptr) {
- name = GETARGS_CAPSULE_NAME_CLEANUP_PTR;
- } else if (destr == cleanup_buffer) {
- name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER;
- } else {
- return -1;
- }
- cobj = PyCapsule_New(ptr, name, destr);
- if (!cobj) {
- destr(ptr);
- return -1;
- }
- if (PyList_Append(*freelist, cobj)) {
- Py_DECREF(cobj);
- return -1;
- }
+ PyObject *cobj;
+ const char *name;
+
+ if (!*freelist) {
+ *freelist = PyList_New(0);
+ if (!*freelist) {
+ destr(ptr);
+ return -1;
+ }
+ }
+
+ if (destr == cleanup_ptr) {
+ name = GETARGS_CAPSULE_NAME_CLEANUP_PTR;
+ } else if (destr == cleanup_buffer) {
+ name = GETARGS_CAPSULE_NAME_CLEANUP_BUFFER;
+ } else {
+ return -1;
+ }
+ cobj = PyCapsule_New(ptr, name, destr);
+ if (!cobj) {
+ destr(ptr);
+ return -1;
+ }
+ if (PyList_Append(*freelist, cobj)) {
Py_DECREF(cobj);
- return 0;
+ return -1;
+ }
+ Py_DECREF(cobj);
+ return 0;
}
static int
cleanreturn(int retval, PyObject *freelist)
{
- if (freelist && retval != 0) {
- /* We were successful, reset the destructors so that they
- don't get called. */
- Py_ssize_t len = PyList_GET_SIZE(freelist), i;
- for (i = 0; i < len; i++)
- PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL);
- }
- Py_XDECREF(freelist);
- return retval;
+ if (freelist && retval != 0) {
+ /* We were successful, reset the destructors so that they
+ don't get called. */
+ Py_ssize_t len = PyList_GET_SIZE(freelist), i;
+ for (i = 0; i < len; i++)
+ PyCapsule_SetDestructor(PyList_GET_ITEM(freelist, i), NULL);
+ }
+ Py_XDECREF(freelist);
+ return retval;
}
static int
vgetargs1(PyObject *args, const char *format, va_list *p_va, int flags)
{
- char msgbuf[256];
- int levels[32];
- const char *fname = NULL;
- const char *message = NULL;
- int min = -1;
- int max = 0;
- int level = 0;
- int endfmt = 0;
- const char *formatsave = format;
- Py_ssize_t i, len;
- char *msg;
- PyObject *freelist = NULL;
- int compat = flags & FLAG_COMPAT;
-
- assert(compat || (args != (PyObject*)NULL));
- flags = flags & ~FLAG_COMPAT;
-
- while (endfmt == 0) {
- int c = *format++;
- switch (c) {
- case '(':
- if (level == 0)
- max++;
- level++;
- if (level >= 30)
- Py_FatalError("too many tuple nesting levels "
- "in argument format string");
- break;
- case ')':
- if (level == 0)
- Py_FatalError("excess ')' in getargs format");
- else
- level--;
- break;
- case '\0':
- endfmt = 1;
- break;
- case ':':
- fname = format;
- endfmt = 1;
- break;
- case ';':
- message = format;
- endfmt = 1;
- break;
- default:
- if (level == 0) {
- if (c == 'O')
- max++;
- else if (isalpha(Py_CHARMASK(c))) {
- if (c != 'e') /* skip encoded */
- max++;
- } else if (c == '|')
- min = max;
- }
- break;
- }
- }
-
- if (level != 0)
- Py_FatalError(/* '(' */ "missing ')' in getargs format");
-
- if (min < 0)
- min = max;
-
- format = formatsave;
-
- if (compat) {
- if (max == 0) {
- if (args == NULL)
- return 1;
- PyOS_snprintf(msgbuf, sizeof(msgbuf),
- "%.200s%s takes no arguments",
- fname==NULL ? "function" : fname,
- fname==NULL ? "" : "()");
- PyErr_SetString(PyExc_TypeError, msgbuf);
- return 0;
- }
- else if (min == 1 && max == 1) {
- if (args == NULL) {
- PyOS_snprintf(msgbuf, sizeof(msgbuf),
- "%.200s%s takes at least one argument",
- fname==NULL ? "function" : fname,
- fname==NULL ? "" : "()");
- PyErr_SetString(PyExc_TypeError, msgbuf);
- return 0;
- }
- msg = convertitem(args, &format, p_va, flags, levels,
- msgbuf, sizeof(msgbuf), &freelist);
- if (msg == NULL)
- return cleanreturn(1, freelist);
- seterror(levels[0], msg, levels+1, fname, message);
- return cleanreturn(0, freelist);
- }
- else {
- PyErr_SetString(PyExc_SystemError,
- "old style getargs format uses new features");
- return 0;
- }
- }
-
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_SystemError,
- "new style getargs format but argument is not a tuple");
- return 0;
- }
-
- len = PyTuple_GET_SIZE(args);
-
- if (len < min || max < len) {
- if (message == NULL) {
- PyOS_snprintf(msgbuf, sizeof(msgbuf),
- "%.150s%s takes %s %d argument%s "
- "(%ld given)",
- fname==NULL ? "function" : fname,
- fname==NULL ? "" : "()",
- min==max ? "exactly"
- : len < min ? "at least" : "at most",
- len < min ? min : max,
- (len < min ? min : max) == 1 ? "" : "s",
- Py_SAFE_DOWNCAST(len, Py_ssize_t, long));
- message = msgbuf;
- }
- PyErr_SetString(PyExc_TypeError, message);
- return 0;
- }
-
- for (i = 0; i < len; i++) {
- if (*format == '|')
- format++;
- msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va,
- flags, levels, msgbuf,
- sizeof(msgbuf), &freelist);
- if (msg) {
- seterror(i+1, msg, levels, fname, msg);
- return cleanreturn(0, freelist);
- }
- }
-
- if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) &&
- *format != '(' &&
- *format != '|' && *format != ':' && *format != ';') {
- PyErr_Format(PyExc_SystemError,
- "bad format string: %.200s", formatsave);
- return cleanreturn(0, freelist);
- }
-
- return cleanreturn(1, freelist);
+ char msgbuf[256];
+ int levels[32];
+ const char *fname = NULL;
+ const char *message = NULL;
+ int min = -1;
+ int max = 0;
+ int level = 0;
+ int endfmt = 0;
+ const char *formatsave = format;
+ Py_ssize_t i, len;
+ char *msg;
+ PyObject *freelist = NULL;
+ int compat = flags & FLAG_COMPAT;
+
+ assert(compat || (args != (PyObject*)NULL));
+ flags = flags & ~FLAG_COMPAT;
+
+ while (endfmt == 0) {
+ int c = *format++;
+ switch (c) {
+ case '(':
+ if (level == 0)
+ max++;
+ level++;
+ if (level >= 30)
+ Py_FatalError("too many tuple nesting levels "
+ "in argument format string");
+ break;
+ case ')':
+ if (level == 0)
+ Py_FatalError("excess ')' in getargs format");
+ else
+ level--;
+ break;
+ case '\0':
+ endfmt = 1;
+ break;
+ case ':':
+ fname = format;
+ endfmt = 1;
+ break;
+ case ';':
+ message = format;
+ endfmt = 1;
+ break;
+ default:
+ if (level == 0) {
+ if (c == 'O')
+ max++;
+ else if (isalpha(Py_CHARMASK(c))) {
+ if (c != 'e') /* skip encoded */
+ max++;
+ } else if (c == '|')
+ min = max;
+ }
+ break;
+ }
+ }
+
+ if (level != 0)
+ Py_FatalError(/* '(' */ "missing ')' in getargs format");
+
+ if (min < 0)
+ min = max;
+
+ format = formatsave;
+
+ if (compat) {
+ if (max == 0) {
+ if (args == NULL)
+ return 1;
+ PyOS_snprintf(msgbuf, sizeof(msgbuf),
+ "%.200s%s takes no arguments",
+ fname==NULL ? "function" : fname,
+ fname==NULL ? "" : "()");
+ PyErr_SetString(PyExc_TypeError, msgbuf);
+ return 0;
+ }
+ else if (min == 1 && max == 1) {
+ if (args == NULL) {
+ PyOS_snprintf(msgbuf, sizeof(msgbuf),
+ "%.200s%s takes at least one argument",
+ fname==NULL ? "function" : fname,
+ fname==NULL ? "" : "()");
+ PyErr_SetString(PyExc_TypeError, msgbuf);
+ return 0;
+ }
+ msg = convertitem(args, &format, p_va, flags, levels,
+ msgbuf, sizeof(msgbuf), &freelist);
+ if (msg == NULL)
+ return cleanreturn(1, freelist);
+ seterror(levels[0], msg, levels+1, fname, message);
+ return cleanreturn(0, freelist);
+ }
+ else {
+ PyErr_SetString(PyExc_SystemError,
+ "old style getargs format uses new features");
+ return 0;
+ }
+ }
+
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_SystemError,
+ "new style getargs format but argument is not a tuple");
+ return 0;
+ }
+
+ len = PyTuple_GET_SIZE(args);
+
+ if (len < min || max < len) {
+ if (message == NULL) {
+ PyOS_snprintf(msgbuf, sizeof(msgbuf),
+ "%.150s%s takes %s %d argument%s "
+ "(%ld given)",
+ fname==NULL ? "function" : fname,
+ fname==NULL ? "" : "()",
+ min==max ? "exactly"
+ : len < min ? "at least" : "at most",
+ len < min ? min : max,
+ (len < min ? min : max) == 1 ? "" : "s",
+ Py_SAFE_DOWNCAST(len, Py_ssize_t, long));
+ message = msgbuf;
+ }
+ PyErr_SetString(PyExc_TypeError, message);
+ return 0;
+ }
+
+ for (i = 0; i < len; i++) {
+ if (*format == '|')
+ format++;
+ msg = convertitem(PyTuple_GET_ITEM(args, i), &format, p_va,
+ flags, levels, msgbuf,
+ sizeof(msgbuf), &freelist);
+ if (msg) {
+ seterror(i+1, msg, levels, fname, msg);
+ return cleanreturn(0, freelist);
+ }
+ }
+
+ if (*format != '\0' && !isalpha(Py_CHARMASK(*format)) &&
+ *format != '(' &&
+ *format != '|' && *format != ':' && *format != ';') {
+ PyErr_Format(PyExc_SystemError,
+ "bad format string: %.200s", formatsave);
+ return cleanreturn(0, freelist);
+ }
+
+ return cleanreturn(1, freelist);
}
@@ -368,37 +368,37 @@ static void
seterror(int iarg, const char *msg, int *levels, const char *fname,
const char *message)
{
- char buf[512];
- int i;
- char *p = buf;
-
- if (PyErr_Occurred())
- return;
- else if (message == NULL) {
- if (fname != NULL) {
- PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
- p += strlen(p);
- }
- if (iarg != 0) {
- PyOS_snprintf(p, sizeof(buf) - (p - buf),
- "argument %d", iarg);
- i = 0;
- p += strlen(p);
- while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) {
- PyOS_snprintf(p, sizeof(buf) - (p - buf),
- ", item %d", levels[i]-1);
- p += strlen(p);
- i++;
- }
- }
- else {
- PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
- p += strlen(p);
- }
- PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
- message = buf;
- }
- PyErr_SetString(PyExc_TypeError, message);
+ char buf[512];
+ int i;
+ char *p = buf;
+
+ if (PyErr_Occurred())
+ return;
+ else if (message == NULL) {
+ if (fname != NULL) {
+ PyOS_snprintf(p, sizeof(buf), "%.200s() ", fname);
+ p += strlen(p);
+ }
+ if (iarg != 0) {
+ PyOS_snprintf(p, sizeof(buf) - (p - buf),
+ "argument %d", iarg);
+ i = 0;
+ p += strlen(p);
+ while (levels[i] > 0 && i < 32 && (int)(p-buf) < 220) {
+ PyOS_snprintf(p, sizeof(buf) - (p - buf),
+ ", item %d", levels[i]-1);
+ p += strlen(p);
+ i++;
+ }
+ }
+ else {
+ PyOS_snprintf(p, sizeof(buf) - (p - buf), "argument");
+ p += strlen(p);
+ }
+ PyOS_snprintf(p, sizeof(buf) - (p - buf), " %.256s", msg);
+ message = buf;
+ }
+ PyErr_SetString(PyExc_TypeError, message);
}
@@ -414,83 +414,83 @@ seterror(int iarg, const char *msg, int *levels, const char *fname,
*p_va is undefined,
*levels is a 0-terminated list of item numbers,
*msgbuf contains an error message, whose format is:
- "must be <typename1>, not <typename2>", where:
- <typename1> is the name of the expected type, and
- <typename2> is the name of the actual type,
+ "must be <typename1>, not <typename2>", where:
+ <typename1> is the name of the expected type, and
+ <typename2> is the name of the actual type,
and msgbuf is returned.
*/
static char *
converttuple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
- int *levels, char *msgbuf, size_t bufsize, int toplevel,
+ int *levels, char *msgbuf, size_t bufsize, int toplevel,
PyObject **freelist)
{
- int level = 0;
- int n = 0;
- const char *format = *p_format;
- int i;
-
- for (;;) {
- int c = *format++;
- if (c == '(') {
- if (level == 0)
- n++;
- level++;
- }
- else if (c == ')') {
- if (level == 0)
- break;
- level--;
- }
- else if (c == ':' || c == ';' || c == '\0')
- break;
- else if (level == 0 && isalpha(Py_CHARMASK(c)))
- n++;
- }
-
- if (!PySequence_Check(arg) || PyString_Check(arg)) {
- levels[0] = 0;
- PyOS_snprintf(msgbuf, bufsize,
- toplevel ? "expected %d arguments, not %.50s" :
- "must be %d-item sequence, not %.50s",
- n,
- arg == Py_None ? "None" : arg->ob_type->tp_name);
- return msgbuf;
- }
-
- if ((i = PySequence_Size(arg)) != n) {
- levels[0] = 0;
- PyOS_snprintf(msgbuf, bufsize,
- toplevel ? "expected %d arguments, not %d" :
- "must be sequence of length %d, not %d",
- n, i);
- return msgbuf;
- }
-
- format = *p_format;
- for (i = 0; i < n; i++) {
- char *msg;
- PyObject *item;
- item = PySequence_GetItem(arg, i);
- if (item == NULL) {
- PyErr_Clear();
- levels[0] = i+1;
- levels[1] = 0;
- strncpy(msgbuf, "is not retrievable", bufsize);
- return msgbuf;
- }
- msg = convertitem(item, &format, p_va, flags, levels+1,
- msgbuf, bufsize, freelist);
- /* PySequence_GetItem calls tp->sq_item, which INCREFs */
- Py_XDECREF(item);
- if (msg != NULL) {
- levels[0] = i+1;
- return msg;
- }
- }
-
- *p_format = format;
- return NULL;
+ int level = 0;
+ int n = 0;
+ const char *format = *p_format;
+ int i;
+
+ for (;;) {
+ int c = *format++;
+ if (c == '(') {
+ if (level == 0)
+ n++;
+ level++;
+ }
+ else if (c == ')') {
+ if (level == 0)
+ break;
+ level--;
+ }
+ else if (c == ':' || c == ';' || c == '\0')
+ break;
+ else if (level == 0 && isalpha(Py_CHARMASK(c)))
+ n++;
+ }
+
+ if (!PySequence_Check(arg) || PyString_Check(arg)) {
+ levels[0] = 0;
+ PyOS_snprintf(msgbuf, bufsize,
+ toplevel ? "expected %d arguments, not %.50s" :
+ "must be %d-item sequence, not %.50s",
+ n,
+ arg == Py_None ? "None" : arg->ob_type->tp_name);
+ return msgbuf;
+ }
+
+ if ((i = PySequence_Size(arg)) != n) {
+ levels[0] = 0;
+ PyOS_snprintf(msgbuf, bufsize,
+ toplevel ? "expected %d arguments, not %d" :
+ "must be sequence of length %d, not %d",
+ n, i);
+ return msgbuf;
+ }
+
+ format = *p_format;
+ for (i = 0; i < n; i++) {
+ char *msg;
+ PyObject *item;
+ item = PySequence_GetItem(arg, i);
+ if (item == NULL) {
+ PyErr_Clear();
+ levels[0] = i+1;
+ levels[1] = 0;
+ strncpy(msgbuf, "is not retrievable", bufsize);
+ return msgbuf;
+ }
+ msg = convertitem(item, &format, p_va, flags, levels+1,
+ msgbuf, bufsize, freelist);
+ /* PySequence_GetItem calls tp->sq_item, which INCREFs */
+ Py_XDECREF(item);
+ if (msg != NULL) {
+ levels[0] = i+1;
+ return msg;
+ }
+ }
+
+ *p_format = format;
+ return NULL;
}
@@ -500,43 +500,43 @@ static char *
convertitem(PyObject *arg, const char **p_format, va_list *p_va, int flags,
int *levels, char *msgbuf, size_t bufsize, PyObject **freelist)
{
- char *msg;
- const char *format = *p_format;
-
- if (*format == '(' /* ')' */) {
- format++;
- msg = converttuple(arg, &format, p_va, flags, levels, msgbuf,
- bufsize, 0, freelist);
- if (msg == NULL)
- format++;
- }
- else {
- msg = convertsimple(arg, &format, p_va, flags,
- msgbuf, bufsize, freelist);
- if (msg != NULL)
- levels[0] = 0;
- }
- if (msg == NULL)
- *p_format = format;
- return msg;
+ char *msg;
+ const char *format = *p_format;
+
+ if (*format == '(' /* ')' */) {
+ format++;
+ msg = converttuple(arg, &format, p_va, flags, levels, msgbuf,
+ bufsize, 0, freelist);
+ if (msg == NULL)
+ format++;
+ }
+ else {
+ msg = convertsimple(arg, &format, p_va, flags,
+ msgbuf, bufsize, freelist);
+ if (msg != NULL)
+ levels[0] = 0;
+ }
+ if (msg == NULL)
+ *p_format = format;
+ return msg;
}
#define UNICODE_DEFAULT_ENCODING(arg) \
- _PyUnicode_AsDefaultEncodedString(arg, NULL)
+ _PyUnicode_AsDefaultEncodedString(arg, NULL)
/* Format an error message generated by convertsimple(). */
static char *
converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize)
{
- assert(expected != NULL);
- assert(arg != NULL);
- PyOS_snprintf(msgbuf, bufsize,
- "must be %.50s, not %.50s", expected,
- arg == Py_None ? "None" : arg->ob_type->tp_name);
- return msgbuf;
+ assert(expected != NULL);
+ assert(arg != NULL);
+ PyOS_snprintf(msgbuf, bufsize,
+ "must be %.50s, not %.50s", expected,
+ arg == Py_None ? "None" : arg->ob_type->tp_name);
+ return msgbuf;
}
#define CONV_UNICODE "(unicode conversion error)"
@@ -546,12 +546,12 @@ converterr(const char *expected, PyObject *arg, char *msgbuf, size_t bufsize)
static int
float_argument_warning(PyObject *arg)
{
- if (PyFloat_Check(arg) &&
- PyErr_Warn(PyExc_DeprecationWarning,
- "integer argument expected, got float" ))
- return 1;
- else
- return 0;
+ if (PyFloat_Check(arg) &&
+ PyErr_Warn(PyExc_DeprecationWarning,
+ "integer argument expected, got float" ))
+ return 1;
+ else
+ return 0;
}
/* explicitly check for float arguments when integers are expected. Raises
@@ -559,13 +559,13 @@ float_argument_warning(PyObject *arg)
static int
float_argument_error(PyObject *arg)
{
- if (PyFloat_Check(arg)) {
- PyErr_SetString(PyExc_TypeError,
- "integer argument expected, got float");
- return 1;
- }
- else
- return 0;
+ if (PyFloat_Check(arg)) {
+ PyErr_SetString(PyExc_TypeError,
+ "integer argument expected, got float");
+ return 1;
+ }
+ else
+ return 0;
}
/* Convert a non-tuple argument. Return NULL if conversion went OK,
@@ -581,826 +581,826 @@ static char *
convertsimple(PyObject *arg, const char **p_format, va_list *p_va, int flags,
char *msgbuf, size_t bufsize, PyObject **freelist)
{
- /* For # codes */
-#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\
- if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \
- else q=va_arg(*p_va, int*);
+ /* For # codes */
+#define FETCH_SIZE int *q=NULL;Py_ssize_t *q2=NULL;\
+ if (flags & FLAG_SIZE_T) q2=va_arg(*p_va, Py_ssize_t*); \
+ else q=va_arg(*p_va, int*);
#define STORE_SIZE(s) if (flags & FLAG_SIZE_T) *q2=s; else *q=s;
#define BUFFER_LEN ((flags & FLAG_SIZE_T) ? *q2:*q)
- const char *format = *p_format;
- char c = *format++;
+ const char *format = *p_format;
+ char c = *format++;
#ifdef Py_USING_UNICODE
- PyObject *uarg;
+ PyObject *uarg;
#endif
-
- switch (c) {
-
- case 'b': { /* unsigned byte -- very short int */
- char *p = va_arg(*p_va, char *);
- long ival;
- if (float_argument_error(arg))
- return converterr("integer<b>", arg, msgbuf, bufsize);
- ival = PyInt_AsLong(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<b>", arg, msgbuf, bufsize);
- else if (ival < 0) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned byte integer is less than minimum");
- return converterr("integer<b>", arg, msgbuf, bufsize);
- }
- else if (ival > UCHAR_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "unsigned byte integer is greater than maximum");
- return converterr("integer<b>", arg, msgbuf, bufsize);
- }
- else
- *p = (unsigned char) ival;
- break;
- }
-
- case 'B': {/* byte sized bitfield - both signed and unsigned
- values allowed */
- char *p = va_arg(*p_va, char *);
- long ival;
- if (float_argument_error(arg))
- return converterr("integer<B>", arg, msgbuf, bufsize);
- ival = PyInt_AsUnsignedLongMask(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<B>", arg, msgbuf, bufsize);
- else
- *p = (unsigned char) ival;
- break;
- }
-
- case 'h': {/* signed short int */
- short *p = va_arg(*p_va, short *);
- long ival;
- if (float_argument_error(arg))
- return converterr("integer<h>", arg, msgbuf, bufsize);
- ival = PyInt_AsLong(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<h>", arg, msgbuf, bufsize);
- else if (ival < SHRT_MIN) {
- PyErr_SetString(PyExc_OverflowError,
- "signed short integer is less than minimum");
- return converterr("integer<h>", arg, msgbuf, bufsize);
- }
- else if (ival > SHRT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "signed short integer is greater than maximum");
- return converterr("integer<h>", arg, msgbuf, bufsize);
- }
- else
- *p = (short) ival;
- break;
- }
-
- case 'H': { /* short int sized bitfield, both signed and
- unsigned allowed */
- unsigned short *p = va_arg(*p_va, unsigned short *);
- long ival;
- if (float_argument_error(arg))
- return converterr("integer<H>", arg, msgbuf, bufsize);
- ival = PyInt_AsUnsignedLongMask(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<H>", arg, msgbuf, bufsize);
- else
- *p = (unsigned short) ival;
- break;
- }
-
- case 'i': {/* signed int */
- int *p = va_arg(*p_va, int *);
- long ival;
- if (float_argument_error(arg))
- return converterr("integer<i>", arg, msgbuf, bufsize);
- ival = PyInt_AsLong(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<i>", arg, msgbuf, bufsize);
- else if (ival > INT_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "signed integer is greater than maximum");
- return converterr("integer<i>", arg, msgbuf, bufsize);
- }
- else if (ival < INT_MIN) {
- PyErr_SetString(PyExc_OverflowError,
- "signed integer is less than minimum");
- return converterr("integer<i>", arg, msgbuf, bufsize);
- }
- else
- *p = ival;
- break;
- }
-
- case 'I': { /* int sized bitfield, both signed and
- unsigned allowed */
- unsigned int *p = va_arg(*p_va, unsigned int *);
- unsigned int ival;
- if (float_argument_error(arg))
- return converterr("integer<I>", arg, msgbuf, bufsize);
- ival = (unsigned int)PyInt_AsUnsignedLongMask(arg);
- if (ival == (unsigned int)-1 && PyErr_Occurred())
- return converterr("integer<I>", arg, msgbuf, bufsize);
- else
- *p = ival;
- break;
- }
-
- case 'n': /* Py_ssize_t */
+
+ switch (c) {
+
+ case 'b': { /* unsigned byte -- very short int */
+ char *p = va_arg(*p_va, char *);
+ long ival;
+ if (float_argument_error(arg))
+ return converterr("integer<b>", arg, msgbuf, bufsize);
+ ival = PyInt_AsLong(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<b>", arg, msgbuf, bufsize);
+ else if (ival < 0) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned byte integer is less than minimum");
+ return converterr("integer<b>", arg, msgbuf, bufsize);
+ }
+ else if (ival > UCHAR_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "unsigned byte integer is greater than maximum");
+ return converterr("integer<b>", arg, msgbuf, bufsize);
+ }
+ else
+ *p = (unsigned char) ival;
+ break;
+ }
+
+ case 'B': {/* byte sized bitfield - both signed and unsigned
+ values allowed */
+ char *p = va_arg(*p_va, char *);
+ long ival;
+ if (float_argument_error(arg))
+ return converterr("integer<B>", arg, msgbuf, bufsize);
+ ival = PyInt_AsUnsignedLongMask(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<B>", arg, msgbuf, bufsize);
+ else
+ *p = (unsigned char) ival;
+ break;
+ }
+
+ case 'h': {/* signed short int */
+ short *p = va_arg(*p_va, short *);
+ long ival;
+ if (float_argument_error(arg))
+ return converterr("integer<h>", arg, msgbuf, bufsize);
+ ival = PyInt_AsLong(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<h>", arg, msgbuf, bufsize);
+ else if (ival < SHRT_MIN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed short integer is less than minimum");
+ return converterr("integer<h>", arg, msgbuf, bufsize);
+ }
+ else if (ival > SHRT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed short integer is greater than maximum");
+ return converterr("integer<h>", arg, msgbuf, bufsize);
+ }
+ else
+ *p = (short) ival;
+ break;
+ }
+
+ case 'H': { /* short int sized bitfield, both signed and
+ unsigned allowed */
+ unsigned short *p = va_arg(*p_va, unsigned short *);
+ long ival;
+ if (float_argument_error(arg))
+ return converterr("integer<H>", arg, msgbuf, bufsize);
+ ival = PyInt_AsUnsignedLongMask(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<H>", arg, msgbuf, bufsize);
+ else
+ *p = (unsigned short) ival;
+ break;
+ }
+
+ case 'i': {/* signed int */
+ int *p = va_arg(*p_va, int *);
+ long ival;
+ if (float_argument_error(arg))
+ return converterr("integer<i>", arg, msgbuf, bufsize);
+ ival = PyInt_AsLong(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<i>", arg, msgbuf, bufsize);
+ else if (ival > INT_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed integer is greater than maximum");
+ return converterr("integer<i>", arg, msgbuf, bufsize);
+ }
+ else if (ival < INT_MIN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "signed integer is less than minimum");
+ return converterr("integer<i>", arg, msgbuf, bufsize);
+ }
+ else
+ *p = ival;
+ break;
+ }
+
+ case 'I': { /* int sized bitfield, both signed and
+ unsigned allowed */
+ unsigned int *p = va_arg(*p_va, unsigned int *);
+ unsigned int ival;
+ if (float_argument_error(arg))
+ return converterr("integer<I>", arg, msgbuf, bufsize);
+ ival = (unsigned int)PyInt_AsUnsignedLongMask(arg);
+ if (ival == (unsigned int)-1 && PyErr_Occurred())
+ return converterr("integer<I>", arg, msgbuf, bufsize);
+ else
+ *p = ival;
+ break;
+ }
+
+ case 'n': /* Py_ssize_t */
#if SIZEOF_SIZE_T != SIZEOF_LONG
- {
- Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *);
- Py_ssize_t ival;
- if (float_argument_error(arg))
- return converterr("integer<n>", arg, msgbuf, bufsize);
- ival = PyInt_AsSsize_t(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<n>", arg, msgbuf, bufsize);
- *p = ival;
- break;
- }
+ {
+ Py_ssize_t *p = va_arg(*p_va, Py_ssize_t *);
+ Py_ssize_t ival;
+ if (float_argument_error(arg))
+ return converterr("integer<n>", arg, msgbuf, bufsize);
+ ival = PyInt_AsSsize_t(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<n>", arg, msgbuf, bufsize);
+ *p = ival;
+ break;
+ }
#endif
- /* Fall through from 'n' to 'l' if Py_ssize_t is int */
- case 'l': {/* long int */
- long *p = va_arg(*p_va, long *);
- long ival;
- if (float_argument_error(arg))
- return converterr("integer<l>", arg, msgbuf, bufsize);
- ival = PyInt_AsLong(arg);
- if (ival == -1 && PyErr_Occurred())
- return converterr("integer<l>", arg, msgbuf, bufsize);
- else
- *p = ival;
- break;
- }
-
- case 'k': { /* long sized bitfield */
- unsigned long *p = va_arg(*p_va, unsigned long *);
- unsigned long ival;
- if (PyInt_Check(arg))
- ival = PyInt_AsUnsignedLongMask(arg);
- else if (PyLong_Check(arg))
- ival = PyLong_AsUnsignedLongMask(arg);
- else
- return converterr("integer<k>", arg, msgbuf, bufsize);
- *p = ival;
- break;
- }
-
+ /* Fall through from 'n' to 'l' if Py_ssize_t is int */
+ case 'l': {/* long int */
+ long *p = va_arg(*p_va, long *);
+ long ival;
+ if (float_argument_error(arg))
+ return converterr("integer<l>", arg, msgbuf, bufsize);
+ ival = PyInt_AsLong(arg);
+ if (ival == -1 && PyErr_Occurred())
+ return converterr("integer<l>", arg, msgbuf, bufsize);
+ else
+ *p = ival;
+ break;
+ }
+
+ case 'k': { /* long sized bitfield */
+ unsigned long *p = va_arg(*p_va, unsigned long *);
+ unsigned long ival;
+ if (PyInt_Check(arg))
+ ival = PyInt_AsUnsignedLongMask(arg);
+ else if (PyLong_Check(arg))
+ ival = PyLong_AsUnsignedLongMask(arg);
+ else
+ return converterr("integer<k>", arg, msgbuf, bufsize);
+ *p = ival;
+ break;
+ }
+
#ifdef HAVE_LONG_LONG
- case 'L': {/* PY_LONG_LONG */
- PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * );
- PY_LONG_LONG ival;
- if (float_argument_warning(arg))
- return converterr("long<L>", arg, msgbuf, bufsize);
- ival = PyLong_AsLongLong(arg);
- if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) {
- return converterr("long<L>", arg, msgbuf, bufsize);
- } else {
- *p = ival;
- }
- break;
- }
-
- case 'K': { /* long long sized bitfield */
- unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *);
- unsigned PY_LONG_LONG ival;
- if (PyInt_Check(arg))
- ival = PyInt_AsUnsignedLongMask(arg);
- else if (PyLong_Check(arg))
- ival = PyLong_AsUnsignedLongLongMask(arg);
- else
- return converterr("integer<K>", arg, msgbuf, bufsize);
- *p = ival;
- break;
- }
+ case 'L': {/* PY_LONG_LONG */
+ PY_LONG_LONG *p = va_arg( *p_va, PY_LONG_LONG * );
+ PY_LONG_LONG ival;
+ if (float_argument_warning(arg))
+ return converterr("long<L>", arg, msgbuf, bufsize);
+ ival = PyLong_AsLongLong(arg);
+ if (ival == (PY_LONG_LONG)-1 && PyErr_Occurred() ) {
+ return converterr("long<L>", arg, msgbuf, bufsize);
+ } else {
+ *p = ival;
+ }
+ break;
+ }
+
+ case 'K': { /* long long sized bitfield */
+ unsigned PY_LONG_LONG *p = va_arg(*p_va, unsigned PY_LONG_LONG *);
+ unsigned PY_LONG_LONG ival;
+ if (PyInt_Check(arg))
+ ival = PyInt_AsUnsignedLongMask(arg);
+ else if (PyLong_Check(arg))
+ ival = PyLong_AsUnsignedLongLongMask(arg);
+ else
+ return converterr("integer<K>", arg, msgbuf, bufsize);
+ *p = ival;
+ break;
+ }
#endif
-
- case 'f': {/* float */
- float *p = va_arg(*p_va, float *);
- double dval = PyFloat_AsDouble(arg);
- if (PyErr_Occurred())
- return converterr("float<f>", arg, msgbuf, bufsize);
- else
- *p = (float) dval;
- break;
- }
-
- case 'd': {/* double */
- double *p = va_arg(*p_va, double *);
- double dval = PyFloat_AsDouble(arg);
- if (PyErr_Occurred())
- return converterr("float<d>", arg, msgbuf, bufsize);
- else
- *p = dval;
- break;
- }
-
+
+ case 'f': {/* float */
+ float *p = va_arg(*p_va, float *);
+ double dval = PyFloat_AsDouble(arg);
+ if (PyErr_Occurred())
+ return converterr("float<f>", arg, msgbuf, bufsize);
+ else
+ *p = (float) dval;
+ break;
+ }
+
+ case 'd': {/* double */
+ double *p = va_arg(*p_va, double *);
+ double dval = PyFloat_AsDouble(arg);
+ if (PyErr_Occurred())
+ return converterr("float<d>", arg, msgbuf, bufsize);
+ else
+ *p = dval;
+ break;
+ }
+
#ifndef WITHOUT_COMPLEX
- case 'D': {/* complex double */
- Py_complex *p = va_arg(*p_va, Py_complex *);
- Py_complex cval;
- cval = PyComplex_AsCComplex(arg);
- if (PyErr_Occurred())
- return converterr("complex<D>", arg, msgbuf, bufsize);
- else
- *p = cval;
- break;
- }
+ case 'D': {/* complex double */
+ Py_complex *p = va_arg(*p_va, Py_complex *);
+ Py_complex cval;
+ cval = PyComplex_AsCComplex(arg);
+ if (PyErr_Occurred())
+ return converterr("complex<D>", arg, msgbuf, bufsize);
+ else
+ *p = cval;
+ break;
+ }
#endif /* WITHOUT_COMPLEX */
-
- case 'c': {/* char */
- char *p = va_arg(*p_va, char *);
- if (PyString_Check(arg) && PyString_Size(arg) == 1)
- *p = PyString_AS_STRING(arg)[0];
- else
- return converterr("char", arg, msgbuf, bufsize);
- break;
- }
-
- case 's': {/* string */
- if (*format == '*') {
- Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
-
- if (PyString_Check(arg)) {
- PyBuffer_FillInfo(p, arg,
- PyString_AS_STRING(arg), PyString_GET_SIZE(arg),
- 1, 0);
- }
+
+ case 'c': {/* char */
+ char *p = va_arg(*p_va, char *);
+ if (PyString_Check(arg) && PyString_Size(arg) == 1)
+ *p = PyString_AS_STRING(arg)[0];
+ else
+ return converterr("char", arg, msgbuf, bufsize);
+ break;
+ }
+
+ case 's': {/* string */
+ if (*format == '*') {
+ Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
+
+ if (PyString_Check(arg)) {
+ PyBuffer_FillInfo(p, arg,
+ PyString_AS_STRING(arg), PyString_GET_SIZE(arg),
+ 1, 0);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(arg)) {
- uarg = UNICODE_DEFAULT_ENCODING(arg);
- if (uarg == NULL)
- return converterr(CONV_UNICODE,
- arg, msgbuf, bufsize);
- PyBuffer_FillInfo(p, arg,
- PyString_AS_STRING(uarg), PyString_GET_SIZE(uarg),
- 1, 0);
- }
+ else if (PyUnicode_Check(arg)) {
+ uarg = UNICODE_DEFAULT_ENCODING(arg);
+ if (uarg == NULL)
+ return converterr(CONV_UNICODE,
+ arg, msgbuf, bufsize);
+ PyBuffer_FillInfo(p, arg,
+ PyString_AS_STRING(uarg), PyString_GET_SIZE(uarg),
+ 1, 0);
+ }
#endif
- else { /* any buffer-like object */
- char *buf;
- if (getbuffer(arg, p, &buf) < 0)
- return converterr(buf, arg, msgbuf, bufsize);
- }
- if (addcleanup(p, freelist, cleanup_buffer)) {
- return converterr(
- "(cleanup problem)",
- arg, msgbuf, bufsize);
- }
- format++;
- } else if (*format == '#') {
- void **p = (void **)va_arg(*p_va, char **);
- FETCH_SIZE;
-
- if (PyString_Check(arg)) {
- *p = PyString_AS_STRING(arg);
- STORE_SIZE(PyString_GET_SIZE(arg));
- }
+ else { /* any buffer-like object */
+ char *buf;
+ if (getbuffer(arg, p, &buf) < 0)
+ return converterr(buf, arg, msgbuf, bufsize);
+ }
+ if (addcleanup(p, freelist, cleanup_buffer)) {
+ return converterr(
+ "(cleanup problem)",
+ arg, msgbuf, bufsize);
+ }
+ format++;
+ } else if (*format == '#') {
+ void **p = (void **)va_arg(*p_va, char **);
+ FETCH_SIZE;
+
+ if (PyString_Check(arg)) {
+ *p = PyString_AS_STRING(arg);
+ STORE_SIZE(PyString_GET_SIZE(arg));
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(arg)) {
- uarg = UNICODE_DEFAULT_ENCODING(arg);
- if (uarg == NULL)
- return converterr(CONV_UNICODE,
- arg, msgbuf, bufsize);
- *p = PyString_AS_STRING(uarg);
- STORE_SIZE(PyString_GET_SIZE(uarg));
- }
+ else if (PyUnicode_Check(arg)) {
+ uarg = UNICODE_DEFAULT_ENCODING(arg);
+ if (uarg == NULL)
+ return converterr(CONV_UNICODE,
+ arg, msgbuf, bufsize);
+ *p = PyString_AS_STRING(uarg);
+ STORE_SIZE(PyString_GET_SIZE(uarg));
+ }
#endif
- else { /* any buffer-like object */
- char *buf;
- Py_ssize_t count = convertbuffer(arg, p, &buf);
- if (count < 0)
- return converterr(buf, arg, msgbuf, bufsize);
- STORE_SIZE(count);
- }
- format++;
- } else {
- char **p = va_arg(*p_va, char **);
-
- if (PyString_Check(arg))
- *p = PyString_AS_STRING(arg);
+ else { /* any buffer-like object */
+ char *buf;
+ Py_ssize_t count = convertbuffer(arg, p, &buf);
+ if (count < 0)
+ return converterr(buf, arg, msgbuf, bufsize);
+ STORE_SIZE(count);
+ }
+ format++;
+ } else {
+ char **p = va_arg(*p_va, char **);
+
+ if (PyString_Check(arg))
+ *p = PyString_AS_STRING(arg);
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(arg)) {
- uarg = UNICODE_DEFAULT_ENCODING(arg);
- if (uarg == NULL)
- return converterr(CONV_UNICODE,
- arg, msgbuf, bufsize);
- *p = PyString_AS_STRING(uarg);
- }
+ else if (PyUnicode_Check(arg)) {
+ uarg = UNICODE_DEFAULT_ENCODING(arg);
+ if (uarg == NULL)
+ return converterr(CONV_UNICODE,
+ arg, msgbuf, bufsize);
+ *p = PyString_AS_STRING(uarg);
+ }
#endif
- else
- return converterr("string", arg, msgbuf, bufsize);
- if ((Py_ssize_t)strlen(*p) != PyString_Size(arg))
- return converterr("string without null bytes",
- arg, msgbuf, bufsize);
- }
- break;
- }
-
- case 'z': {/* string, may be NULL (None) */
- if (*format == '*') {
- Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
-
- if (arg == Py_None)
- PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0);
- else if (PyString_Check(arg)) {
- PyBuffer_FillInfo(p, arg,
- PyString_AS_STRING(arg), PyString_GET_SIZE(arg),
- 1, 0);
- }
+ else
+ return converterr("string", arg, msgbuf, bufsize);
+ if ((Py_ssize_t)strlen(*p) != PyString_Size(arg))
+ return converterr("string without null bytes",
+ arg, msgbuf, bufsize);
+ }
+ break;
+ }
+
+ case 'z': {/* string, may be NULL (None) */
+ if (*format == '*') {
+ Py_buffer *p = (Py_buffer *)va_arg(*p_va, Py_buffer *);
+
+ if (arg == Py_None)
+ PyBuffer_FillInfo(p, NULL, NULL, 0, 1, 0);
+ else if (PyString_Check(arg)) {
+ PyBuffer_FillInfo(p, arg,
+ PyString_AS_STRING(arg), PyString_GET_SIZE(arg),
+ 1, 0);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(arg)) {
- uarg = UNICODE_DEFAULT_ENCODING(arg);
- if (uarg == NULL)
- return converterr(CONV_UNICODE,
- arg, msgbuf, bufsize);
- PyBuffer_FillInfo(p, arg,
- PyString_AS_STRING(uarg), PyString_GET_SIZE(uarg),
- 1, 0);
- }
+ else if (PyUnicode_Check(arg)) {
+ uarg = UNICODE_DEFAULT_ENCODING(arg);
+ if (uarg == NULL)
+ return converterr(CONV_UNICODE,
+ arg, msgbuf, bufsize);
+ PyBuffer_FillInfo(p, arg,
+ PyString_AS_STRING(uarg), PyString_GET_SIZE(uarg),
+ 1, 0);
+ }
#endif
- else { /* any buffer-like object */
- char *buf;
- if (getbuffer(arg, p, &buf) < 0)
- return converterr(buf, arg, msgbuf, bufsize);
- }
- if (addcleanup(p, freelist, cleanup_buffer)) {
- return converterr(
- "(cleanup problem)",
- arg, msgbuf, bufsize);
- }
- format++;
- } else if (*format == '#') { /* any buffer-like object */
- void **p = (void **)va_arg(*p_va, char **);
- FETCH_SIZE;
-
- if (arg == Py_None) {
- *p = 0;
- STORE_SIZE(0);
- }
- else if (PyString_Check(arg)) {
- *p = PyString_AS_STRING(arg);
- STORE_SIZE(PyString_GET_SIZE(arg));
- }
+ else { /* any buffer-like object */
+ char *buf;
+ if (getbuffer(arg, p, &buf) < 0)
+ return converterr(buf, arg, msgbuf, bufsize);
+ }
+ if (addcleanup(p, freelist, cleanup_buffer)) {
+ return converterr(
+ "(cleanup problem)",
+ arg, msgbuf, bufsize);
+ }
+ format++;
+ } else if (*format == '#') { /* any buffer-like object */
+ void **p = (void **)va_arg(*p_va, char **);
+ FETCH_SIZE;
+
+ if (arg == Py_None) {
+ *p = 0;
+ STORE_SIZE(0);
+ }
+ else if (PyString_Check(arg)) {
+ *p = PyString_AS_STRING(arg);
+ STORE_SIZE(PyString_GET_SIZE(arg));
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(arg)) {
- uarg = UNICODE_DEFAULT_ENCODING(arg);
- if (uarg == NULL)
- return converterr(CONV_UNICODE,
- arg, msgbuf, bufsize);
- *p = PyString_AS_STRING(uarg);
- STORE_SIZE(PyString_GET_SIZE(uarg));
- }
+ else if (PyUnicode_Check(arg)) {
+ uarg = UNICODE_DEFAULT_ENCODING(arg);
+ if (uarg == NULL)
+ return converterr(CONV_UNICODE,
+ arg, msgbuf, bufsize);
+ *p = PyString_AS_STRING(uarg);
+ STORE_SIZE(PyString_GET_SIZE(uarg));
+ }
#endif
- else { /* any buffer-like object */
- char *buf;
- Py_ssize_t count = convertbuffer(arg, p, &buf);
- if (count < 0)
- return converterr(buf, arg, msgbuf, bufsize);
- STORE_SIZE(count);
- }
- format++;
- } else {
- char **p = va_arg(*p_va, char **);
-
- if (arg == Py_None)
- *p = 0;
- else if (PyString_Check(arg))
- *p = PyString_AS_STRING(arg);
+ else { /* any buffer-like object */
+ char *buf;
+ Py_ssize_t count = convertbuffer(arg, p, &buf);
+ if (count < 0)
+ return converterr(buf, arg, msgbuf, bufsize);
+ STORE_SIZE(count);
+ }
+ format++;
+ } else {
+ char **p = va_arg(*p_va, char **);
+
+ if (arg == Py_None)
+ *p = 0;
+ else if (PyString_Check(arg))
+ *p = PyString_AS_STRING(arg);
#ifdef Py_USING_UNICODE
- else if (PyUnicode_Check(arg)) {
- uarg = UNICODE_DEFAULT_ENCODING(arg);
- if (uarg == NULL)
- return converterr(CONV_UNICODE,
- arg, msgbuf, bufsize);
- *p = PyString_AS_STRING(uarg);
- }
+ else if (PyUnicode_Check(arg)) {
+ uarg = UNICODE_DEFAULT_ENCODING(arg);
+ if (uarg == NULL)
+ return converterr(CONV_UNICODE,
+ arg, msgbuf, bufsize);
+ *p = PyString_AS_STRING(uarg);
+ }
#endif
- else
- return converterr("string or None",
- arg, msgbuf, bufsize);
- if (*format == '#') {
- FETCH_SIZE;
- assert(0); /* XXX redundant with if-case */
- if (arg == Py_None)
- *q = 0;
- else
- *q = PyString_Size(arg);
- format++;
- }
- else if (*p != NULL &&
- (Py_ssize_t)strlen(*p) != PyString_Size(arg))
- return converterr(
- "string without null bytes or None",
- arg, msgbuf, bufsize);
- }
- break;
- }
-
- case 'e': {/* encoded string */
- char **buffer;
- const char *encoding;
- PyObject *s;
- Py_ssize_t size;
- int recode_strings;
-
- /* Get 'e' parameter: the encoding name */
- encoding = (const char *)va_arg(*p_va, const char *);
+ else
+ return converterr("string or None",
+ arg, msgbuf, bufsize);
+ if (*format == '#') {
+ FETCH_SIZE;
+ assert(0); /* XXX redundant with if-case */
+ if (arg == Py_None)
+ *q = 0;
+ else
+ *q = PyString_Size(arg);
+ format++;
+ }
+ else if (*p != NULL &&
+ (Py_ssize_t)strlen(*p) != PyString_Size(arg))
+ return converterr(
+ "string without null bytes or None",
+ arg, msgbuf, bufsize);
+ }
+ break;
+ }
+
+ case 'e': {/* encoded string */
+ char **buffer;
+ const char *encoding;
+ PyObject *s;
+ Py_ssize_t size;
+ int recode_strings;
+
+ /* Get 'e' parameter: the encoding name */
+ encoding = (const char *)va_arg(*p_va, const char *);
#ifdef Py_USING_UNICODE
- if (encoding == NULL)
- encoding = PyUnicode_GetDefaultEncoding();
+ if (encoding == NULL)
+ encoding = PyUnicode_GetDefaultEncoding();
#endif
-
- /* Get output buffer parameter:
- 's' (recode all objects via Unicode) or
- 't' (only recode non-string objects)
- */
- if (*format == 's')
- recode_strings = 1;
- else if (*format == 't')
- recode_strings = 0;
- else
- return converterr(
- "(unknown parser marker combination)",
- arg, msgbuf, bufsize);
- buffer = (char **)va_arg(*p_va, char **);
- format++;
- if (buffer == NULL)
- return converterr("(buffer is NULL)",
- arg, msgbuf, bufsize);
-
- /* Encode object */
- if (!recode_strings && PyString_Check(arg)) {
- s = arg;
- Py_INCREF(s);
- }
- else {
+
+ /* Get output buffer parameter:
+ 's' (recode all objects via Unicode) or
+ 't' (only recode non-string objects)
+ */
+ if (*format == 's')
+ recode_strings = 1;
+ else if (*format == 't')
+ recode_strings = 0;
+ else
+ return converterr(
+ "(unknown parser marker combination)",
+ arg, msgbuf, bufsize);
+ buffer = (char **)va_arg(*p_va, char **);
+ format++;
+ if (buffer == NULL)
+ return converterr("(buffer is NULL)",
+ arg, msgbuf, bufsize);
+
+ /* Encode object */
+ if (!recode_strings && PyString_Check(arg)) {
+ s = arg;
+ Py_INCREF(s);
+ }
+ else {
#ifdef Py_USING_UNICODE
- PyObject *u;
-
- /* Convert object to Unicode */
- u = PyUnicode_FromObject(arg);
- if (u == NULL)
- return converterr(
- "string or unicode or text buffer",
- arg, msgbuf, bufsize);
-
- /* Encode object; use default error handling */
- s = PyUnicode_AsEncodedString(u,
- encoding,
- NULL);
- Py_DECREF(u);
- if (s == NULL)
- return converterr("(encoding failed)",
- arg, msgbuf, bufsize);
- if (!PyString_Check(s)) {
- Py_DECREF(s);
- return converterr(
- "(encoder failed to return a string)",
- arg, msgbuf, bufsize);
- }
+ PyObject *u;
+
+ /* Convert object to Unicode */
+ u = PyUnicode_FromObject(arg);
+ if (u == NULL)
+ return converterr(
+ "string or unicode or text buffer",
+ arg, msgbuf, bufsize);
+
+ /* Encode object; use default error handling */
+ s = PyUnicode_AsEncodedString(u,
+ encoding,
+ NULL);
+ Py_DECREF(u);
+ if (s == NULL)
+ return converterr("(encoding failed)",
+ arg, msgbuf, bufsize);
+ if (!PyString_Check(s)) {
+ Py_DECREF(s);
+ return converterr(
+ "(encoder failed to return a string)",
+ arg, msgbuf, bufsize);
+ }
#else
- return converterr("string<e>", arg, msgbuf, bufsize);
+ return converterr("string<e>", arg, msgbuf, bufsize);
#endif
- }
- size = PyString_GET_SIZE(s);
-
- /* Write output; output is guaranteed to be 0-terminated */
- if (*format == '#') {
- /* Using buffer length parameter '#':
-
- - if *buffer is NULL, a new buffer of the
- needed size is allocated and the data
- copied into it; *buffer is updated to point
- to the new buffer; the caller is
- responsible for PyMem_Free()ing it after
- usage
-
- - if *buffer is not NULL, the data is
- copied to *buffer; *buffer_len has to be
- set to the size of the buffer on input;
- buffer overflow is signalled with an error;
- buffer has to provide enough room for the
- encoded string plus the trailing 0-byte
-
- - in both cases, *buffer_len is updated to
- the size of the buffer /excluding/ the
- trailing 0-byte
-
- */
- FETCH_SIZE;
-
- format++;
- if (q == NULL && q2 == NULL) {
- Py_DECREF(s);
- return converterr(
- "(buffer_len is NULL)",
- arg, msgbuf, bufsize);
- }
- if (*buffer == NULL) {
- *buffer = PyMem_NEW(char, size + 1);
- if (*buffer == NULL) {
- Py_DECREF(s);
- return converterr(
- "(memory error)",
- arg, msgbuf, bufsize);
- }
- if (addcleanup(*buffer, freelist, cleanup_ptr)) {
- Py_DECREF(s);
- return converterr(
- "(cleanup problem)",
- arg, msgbuf, bufsize);
- }
- } else {
- if (size + 1 > BUFFER_LEN) {
- Py_DECREF(s);
- return converterr(
- "(buffer overflow)",
- arg, msgbuf, bufsize);
- }
- }
- memcpy(*buffer,
- PyString_AS_STRING(s),
- size + 1);
- STORE_SIZE(size);
- } else {
- /* Using a 0-terminated buffer:
-
- - the encoded string has to be 0-terminated
- for this variant to work; if it is not, an
- error raised
-
- - a new buffer of the needed size is
- allocated and the data copied into it;
- *buffer is updated to point to the new
- buffer; the caller is responsible for
- PyMem_Free()ing it after usage
-
- */
- if ((Py_ssize_t)strlen(PyString_AS_STRING(s))
- != size) {
- Py_DECREF(s);
- return converterr(
- "encoded string without NULL bytes",
- arg, msgbuf, bufsize);
- }
- *buffer = PyMem_NEW(char, size + 1);
- if (*buffer == NULL) {
- Py_DECREF(s);
- return converterr("(memory error)",
- arg, msgbuf, bufsize);
- }
- if (addcleanup(*buffer, freelist, cleanup_ptr)) {
- Py_DECREF(s);
- return converterr("(cleanup problem)",
- arg, msgbuf, bufsize);
- }
- memcpy(*buffer,
- PyString_AS_STRING(s),
- size + 1);
- }
- Py_DECREF(s);
- break;
- }
+ }
+ size = PyString_GET_SIZE(s);
+
+ /* Write output; output is guaranteed to be 0-terminated */
+ if (*format == '#') {
+ /* Using buffer length parameter '#':
+
+ - if *buffer is NULL, a new buffer of the
+ needed size is allocated and the data
+ copied into it; *buffer is updated to point
+ to the new buffer; the caller is
+ responsible for PyMem_Free()ing it after
+ usage
+
+ - if *buffer is not NULL, the data is
+ copied to *buffer; *buffer_len has to be
+ set to the size of the buffer on input;
+ buffer overflow is signalled with an error;
+ buffer has to provide enough room for the
+ encoded string plus the trailing 0-byte
+
+ - in both cases, *buffer_len is updated to
+ the size of the buffer /excluding/ the
+ trailing 0-byte
+
+ */
+ FETCH_SIZE;
+
+ format++;
+ if (q == NULL && q2 == NULL) {
+ Py_DECREF(s);
+ return converterr(
+ "(buffer_len is NULL)",
+ arg, msgbuf, bufsize);
+ }
+ if (*buffer == NULL) {
+ *buffer = PyMem_NEW(char, size + 1);
+ if (*buffer == NULL) {
+ Py_DECREF(s);
+ return converterr(
+ "(memory error)",
+ arg, msgbuf, bufsize);
+ }
+ if (addcleanup(*buffer, freelist, cleanup_ptr)) {
+ Py_DECREF(s);
+ return converterr(
+ "(cleanup problem)",
+ arg, msgbuf, bufsize);
+ }
+ } else {
+ if (size + 1 > BUFFER_LEN) {
+ Py_DECREF(s);
+ return converterr(
+ "(buffer overflow)",
+ arg, msgbuf, bufsize);
+ }
+ }
+ memcpy(*buffer,
+ PyString_AS_STRING(s),
+ size + 1);
+ STORE_SIZE(size);
+ } else {
+ /* Using a 0-terminated buffer:
+
+ - the encoded string has to be 0-terminated
+ for this variant to work; if it is not, an
+ error raised
+
+ - a new buffer of the needed size is
+ allocated and the data copied into it;
+ *buffer is updated to point to the new
+ buffer; the caller is responsible for
+ PyMem_Free()ing it after usage
+
+ */
+ if ((Py_ssize_t)strlen(PyString_AS_STRING(s))
+ != size) {
+ Py_DECREF(s);
+ return converterr(
+ "encoded string without NULL bytes",
+ arg, msgbuf, bufsize);
+ }
+ *buffer = PyMem_NEW(char, size + 1);
+ if (*buffer == NULL) {
+ Py_DECREF(s);
+ return converterr("(memory error)",
+ arg, msgbuf, bufsize);
+ }
+ if (addcleanup(*buffer, freelist, cleanup_ptr)) {
+ Py_DECREF(s);
+ return converterr("(cleanup problem)",
+ arg, msgbuf, bufsize);
+ }
+ memcpy(*buffer,
+ PyString_AS_STRING(s),
+ size + 1);
+ }
+ Py_DECREF(s);
+ break;
+ }
#ifdef Py_USING_UNICODE
- case 'u': {/* raw unicode buffer (Py_UNICODE *) */
- if (*format == '#') { /* any buffer-like object */
- void **p = (void **)va_arg(*p_va, char **);
- FETCH_SIZE;
- if (PyUnicode_Check(arg)) {
- *p = PyUnicode_AS_UNICODE(arg);
- STORE_SIZE(PyUnicode_GET_SIZE(arg));
- }
- else {
- return converterr("cannot convert raw buffers",
- arg, msgbuf, bufsize);
- }
- format++;
- } else {
- Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
- if (PyUnicode_Check(arg))
- *p = PyUnicode_AS_UNICODE(arg);
- else
- return converterr("unicode", arg, msgbuf, bufsize);
- }
- break;
- }
+ case 'u': {/* raw unicode buffer (Py_UNICODE *) */
+ if (*format == '#') { /* any buffer-like object */
+ void **p = (void **)va_arg(*p_va, char **);
+ FETCH_SIZE;
+ if (PyUnicode_Check(arg)) {
+ *p = PyUnicode_AS_UNICODE(arg);
+ STORE_SIZE(PyUnicode_GET_SIZE(arg));
+ }
+ else {
+ return converterr("cannot convert raw buffers",
+ arg, msgbuf, bufsize);
+ }
+ format++;
+ } else {
+ Py_UNICODE **p = va_arg(*p_va, Py_UNICODE **);
+ if (PyUnicode_Check(arg))
+ *p = PyUnicode_AS_UNICODE(arg);
+ else
+ return converterr("unicode", arg, msgbuf, bufsize);
+ }
+ break;
+ }
#endif
- case 'S': { /* string object */
- PyObject **p = va_arg(*p_va, PyObject **);
- if (PyString_Check(arg))
- *p = arg;
- else
- return converterr("string", arg, msgbuf, bufsize);
- break;
- }
-
+ case 'S': { /* string object */
+ PyObject **p = va_arg(*p_va, PyObject **);
+ if (PyString_Check(arg))
+ *p = arg;
+ else
+ return converterr("string", arg, msgbuf, bufsize);
+ break;
+ }
+
#ifdef Py_USING_UNICODE
- case 'U': { /* Unicode object */
- PyObject **p = va_arg(*p_va, PyObject **);
- if (PyUnicode_Check(arg))
- *p = arg;
- else
- return converterr("unicode", arg, msgbuf, bufsize);
- break;
- }
+ case 'U': { /* Unicode object */
+ PyObject **p = va_arg(*p_va, PyObject **);
+ if (PyUnicode_Check(arg))
+ *p = arg;
+ else
+ return converterr("unicode", arg, msgbuf, bufsize);
+ break;
+ }
#endif
-
- case 'O': { /* object */
- PyTypeObject *type;
- PyObject **p;
- if (*format == '!') {
- type = va_arg(*p_va, PyTypeObject*);
- p = va_arg(*p_va, PyObject **);
- format++;
- if (PyType_IsSubtype(arg->ob_type, type))
- *p = arg;
- else
- return converterr(type->tp_name, arg, msgbuf, bufsize);
-
- }
- else if (*format == '?') {
- inquiry pred = va_arg(*p_va, inquiry);
- p = va_arg(*p_va, PyObject **);
- format++;
- if ((*pred)(arg))
- *p = arg;
- else
- return converterr("(unspecified)",
- arg, msgbuf, bufsize);
-
- }
- else if (*format == '&') {
- typedef int (*converter)(PyObject *, void *);
- converter convert = va_arg(*p_va, converter);
- void *addr = va_arg(*p_va, void *);
- format++;
- if (! (*convert)(arg, addr))
- return converterr("(unspecified)",
- arg, msgbuf, bufsize);
- }
- else {
- p = va_arg(*p_va, PyObject **);
- *p = arg;
- }
- break;
- }
-
-
- case 'w': { /* memory buffer, read-write access */
- void **p = va_arg(*p_va, void **);
- void *res;
- PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
- Py_ssize_t count;
-
- if (pb && pb->bf_releasebuffer && *format != '*')
- /* Buffer must be released, yet caller does not use
- the Py_buffer protocol. */
- return converterr("pinned buffer", arg, msgbuf, bufsize);
-
- if (pb && pb->bf_getbuffer && *format == '*') {
- /* Caller is interested in Py_buffer, and the object
- supports it directly. */
- format++;
- if (pb->bf_getbuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
- PyErr_Clear();
- return converterr("read-write buffer", arg, msgbuf, bufsize);
- }
- if (addcleanup(p, freelist, cleanup_buffer)) {
- return converterr(
- "(cleanup problem)",
- arg, msgbuf, bufsize);
- }
- if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C'))
- return converterr("contiguous buffer", arg, msgbuf, bufsize);
- break;
- }
-
- if (pb == NULL ||
- pb->bf_getwritebuffer == NULL ||
- pb->bf_getsegcount == NULL)
- return converterr("read-write buffer", arg, msgbuf, bufsize);
- if ((*pb->bf_getsegcount)(arg, NULL) != 1)
- return converterr("single-segment read-write buffer",
- arg, msgbuf, bufsize);
- if ((count = pb->bf_getwritebuffer(arg, 0, &res)) < 0)
- return converterr("(unspecified)", arg, msgbuf, bufsize);
- if (*format == '*') {
- PyBuffer_FillInfo((Py_buffer*)p, arg, res, count, 1, 0);
- format++;
- }
- else {
- *p = res;
- if (*format == '#') {
- FETCH_SIZE;
- STORE_SIZE(count);
- format++;
- }
- }
- break;
- }
-
- case 't': { /* 8-bit character buffer, read-only access */
- char **p = va_arg(*p_va, char **);
- PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
- Py_ssize_t count;
-
- if (*format++ != '#')
- return converterr(
- "invalid use of 't' format character",
- arg, msgbuf, bufsize);
- if (!PyType_HasFeature(arg->ob_type,
- Py_TPFLAGS_HAVE_GETCHARBUFFER) ||
- pb == NULL || pb->bf_getcharbuffer == NULL ||
- pb->bf_getsegcount == NULL)
- return converterr(
- "string or read-only character buffer",
- arg, msgbuf, bufsize);
-
- if (pb->bf_getsegcount(arg, NULL) != 1)
- return converterr(
- "string or single-segment read-only buffer",
- arg, msgbuf, bufsize);
-
- if (pb->bf_releasebuffer)
- return converterr(
- "string or pinned buffer",
- arg, msgbuf, bufsize);
-
- count = pb->bf_getcharbuffer(arg, 0, p);
- if (count < 0)
- return converterr("(unspecified)", arg, msgbuf, bufsize);
- {
- FETCH_SIZE;
- STORE_SIZE(count);
- }
- break;
- }
-
- default:
- return converterr("impossible<bad format char>", arg, msgbuf, bufsize);
-
- }
-
- *p_format = format;
- return NULL;
+
+ case 'O': { /* object */
+ PyTypeObject *type;
+ PyObject **p;
+ if (*format == '!') {
+ type = va_arg(*p_va, PyTypeObject*);
+ p = va_arg(*p_va, PyObject **);
+ format++;
+ if (PyType_IsSubtype(arg->ob_type, type))
+ *p = arg;
+ else
+ return converterr(type->tp_name, arg, msgbuf, bufsize);
+
+ }
+ else if (*format == '?') {
+ inquiry pred = va_arg(*p_va, inquiry);
+ p = va_arg(*p_va, PyObject **);
+ format++;
+ if ((*pred)(arg))
+ *p = arg;
+ else
+ return converterr("(unspecified)",
+ arg, msgbuf, bufsize);
+
+ }
+ else if (*format == '&') {
+ typedef int (*converter)(PyObject *, void *);
+ converter convert = va_arg(*p_va, converter);
+ void *addr = va_arg(*p_va, void *);
+ format++;
+ if (! (*convert)(arg, addr))
+ return converterr("(unspecified)",
+ arg, msgbuf, bufsize);
+ }
+ else {
+ p = va_arg(*p_va, PyObject **);
+ *p = arg;
+ }
+ break;
+ }
+
+
+ case 'w': { /* memory buffer, read-write access */
+ void **p = va_arg(*p_va, void **);
+ void *res;
+ PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
+ Py_ssize_t count;
+
+ if (pb && pb->bf_releasebuffer && *format != '*')
+ /* Buffer must be released, yet caller does not use
+ the Py_buffer protocol. */
+ return converterr("pinned buffer", arg, msgbuf, bufsize);
+
+ if (pb && pb->bf_getbuffer && *format == '*') {
+ /* Caller is interested in Py_buffer, and the object
+ supports it directly. */
+ format++;
+ if (pb->bf_getbuffer(arg, (Py_buffer*)p, PyBUF_WRITABLE) < 0) {
+ PyErr_Clear();
+ return converterr("read-write buffer", arg, msgbuf, bufsize);
+ }
+ if (addcleanup(p, freelist, cleanup_buffer)) {
+ return converterr(
+ "(cleanup problem)",
+ arg, msgbuf, bufsize);
+ }
+ if (!PyBuffer_IsContiguous((Py_buffer*)p, 'C'))
+ return converterr("contiguous buffer", arg, msgbuf, bufsize);
+ break;
+ }
+
+ if (pb == NULL ||
+ pb->bf_getwritebuffer == NULL ||
+ pb->bf_getsegcount == NULL)
+ return converterr("read-write buffer", arg, msgbuf, bufsize);
+ if ((*pb->bf_getsegcount)(arg, NULL) != 1)
+ return converterr("single-segment read-write buffer",
+ arg, msgbuf, bufsize);
+ if ((count = pb->bf_getwritebuffer(arg, 0, &res)) < 0)
+ return converterr("(unspecified)", arg, msgbuf, bufsize);
+ if (*format == '*') {
+ PyBuffer_FillInfo((Py_buffer*)p, arg, res, count, 1, 0);
+ format++;
+ }
+ else {
+ *p = res;
+ if (*format == '#') {
+ FETCH_SIZE;
+ STORE_SIZE(count);
+ format++;
+ }
+ }
+ break;
+ }
+
+ case 't': { /* 8-bit character buffer, read-only access */
+ char **p = va_arg(*p_va, char **);
+ PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
+ Py_ssize_t count;
+
+ if (*format++ != '#')
+ return converterr(
+ "invalid use of 't' format character",
+ arg, msgbuf, bufsize);
+ if (!PyType_HasFeature(arg->ob_type,
+ Py_TPFLAGS_HAVE_GETCHARBUFFER) ||
+ pb == NULL || pb->bf_getcharbuffer == NULL ||
+ pb->bf_getsegcount == NULL)
+ return converterr(
+ "string or read-only character buffer",
+ arg, msgbuf, bufsize);
+
+ if (pb->bf_getsegcount(arg, NULL) != 1)
+ return converterr(
+ "string or single-segment read-only buffer",
+ arg, msgbuf, bufsize);
+
+ if (pb->bf_releasebuffer)
+ return converterr(
+ "string or pinned buffer",
+ arg, msgbuf, bufsize);
+
+ count = pb->bf_getcharbuffer(arg, 0, p);
+ if (count < 0)
+ return converterr("(unspecified)", arg, msgbuf, bufsize);
+ {
+ FETCH_SIZE;
+ STORE_SIZE(count);
+ }
+ break;
+ }
+
+ default:
+ return converterr("impossible<bad format char>", arg, msgbuf, bufsize);
+
+ }
+
+ *p_format = format;
+ return NULL;
}
static Py_ssize_t
convertbuffer(PyObject *arg, void **p, char **errmsg)
{
- PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
- Py_ssize_t count;
- if (pb == NULL ||
- pb->bf_getreadbuffer == NULL ||
- pb->bf_getsegcount == NULL ||
- pb->bf_releasebuffer != NULL) {
- *errmsg = "string or read-only buffer";
- return -1;
- }
- if ((*pb->bf_getsegcount)(arg, NULL) != 1) {
- *errmsg = "string or single-segment read-only buffer";
- return -1;
- }
- if ((count = (*pb->bf_getreadbuffer)(arg, 0, p)) < 0) {
- *errmsg = "(unspecified)";
- }
- return count;
+ PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
+ Py_ssize_t count;
+ if (pb == NULL ||
+ pb->bf_getreadbuffer == NULL ||
+ pb->bf_getsegcount == NULL ||
+ pb->bf_releasebuffer != NULL) {
+ *errmsg = "string or read-only buffer";
+ return -1;
+ }
+ if ((*pb->bf_getsegcount)(arg, NULL) != 1) {
+ *errmsg = "string or single-segment read-only buffer";
+ return -1;
+ }
+ if ((count = (*pb->bf_getreadbuffer)(arg, 0, p)) < 0) {
+ *errmsg = "(unspecified)";
+ }
+ return count;
}
static int
getbuffer(PyObject *arg, Py_buffer *view, char **errmsg)
{
- void *buf;
- Py_ssize_t count;
- PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
- if (pb == NULL) {
- *errmsg = "string or buffer";
- return -1;
- }
- if (pb->bf_getbuffer) {
- if (pb->bf_getbuffer(arg, view, 0) < 0) {
- *errmsg = "convertible to a buffer";
- return -1;
- }
- if (!PyBuffer_IsContiguous(view, 'C')) {
- *errmsg = "contiguous buffer";
- return -1;
- }
- return 0;
- }
-
- count = convertbuffer(arg, &buf, errmsg);
- if (count < 0) {
- *errmsg = "convertible to a buffer";
- return count;
- }
- PyBuffer_FillInfo(view, NULL, buf, count, 1, 0);
- return 0;
+ void *buf;
+ Py_ssize_t count;
+ PyBufferProcs *pb = arg->ob_type->tp_as_buffer;
+ if (pb == NULL) {
+ *errmsg = "string or buffer";
+ return -1;
+ }
+ if (pb->bf_getbuffer) {
+ if (pb->bf_getbuffer(arg, view, 0) < 0) {
+ *errmsg = "convertible to a buffer";
+ return -1;
+ }
+ if (!PyBuffer_IsContiguous(view, 'C')) {
+ *errmsg = "contiguous buffer";
+ return -1;
+ }
+ return 0;
+ }
+
+ count = convertbuffer(arg, &buf, errmsg);
+ if (count < 0) {
+ *errmsg = "convertible to a buffer";
+ return count;
+ }
+ PyBuffer_FillInfo(view, NULL, buf, count, 1, 0);
+ return 0;
}
/* Support for keyword arguments donated by
@@ -1409,487 +1409,487 @@ getbuffer(PyObject *arg, Py_buffer *view, char **errmsg)
/* Return false (0) for error, else true. */
int
PyArg_ParseTupleAndKeywords(PyObject *args,
- PyObject *keywords,
- const char *format,
- char **kwlist, ...)
+ PyObject *keywords,
+ const char *format,
+ char **kwlist, ...)
{
- int retval;
- va_list va;
-
- if ((args == NULL || !PyTuple_Check(args)) ||
- (keywords != NULL && !PyDict_Check(keywords)) ||
- format == NULL ||
- kwlist == NULL)
- {
- PyErr_BadInternalCall();
- return 0;
- }
-
- va_start(va, kwlist);
- retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0);
- va_end(va);
- return retval;
+ int retval;
+ va_list va;
+
+ if ((args == NULL || !PyTuple_Check(args)) ||
+ (keywords != NULL && !PyDict_Check(keywords)) ||
+ format == NULL ||
+ kwlist == NULL)
+ {
+ PyErr_BadInternalCall();
+ return 0;
+ }
+
+ va_start(va, kwlist);
+ retval = vgetargskeywords(args, keywords, format, kwlist, &va, 0);
+ va_end(va);
+ return retval;
}
int
_PyArg_ParseTupleAndKeywords_SizeT(PyObject *args,
- PyObject *keywords,
- const char *format,
- char **kwlist, ...)
+ PyObject *keywords,
+ const char *format,
+ char **kwlist, ...)
{
- int retval;
- va_list va;
-
- if ((args == NULL || !PyTuple_Check(args)) ||
- (keywords != NULL && !PyDict_Check(keywords)) ||
- format == NULL ||
- kwlist == NULL)
- {
- PyErr_BadInternalCall();
- return 0;
- }
-
- va_start(va, kwlist);
- retval = vgetargskeywords(args, keywords, format,
- kwlist, &va, FLAG_SIZE_T);
- va_end(va);
- return retval;
+ int retval;
+ va_list va;
+
+ if ((args == NULL || !PyTuple_Check(args)) ||
+ (keywords != NULL && !PyDict_Check(keywords)) ||
+ format == NULL ||
+ kwlist == NULL)
+ {
+ PyErr_BadInternalCall();
+ return 0;
+ }
+
+ va_start(va, kwlist);
+ retval = vgetargskeywords(args, keywords, format,
+ kwlist, &va, FLAG_SIZE_T);
+ va_end(va);
+ return retval;
}
int
PyArg_VaParseTupleAndKeywords(PyObject *args,
PyObject *keywords,
- const char *format,
+ const char *format,
char **kwlist, va_list va)
{
- int retval;
- va_list lva;
-
- if ((args == NULL || !PyTuple_Check(args)) ||
- (keywords != NULL && !PyDict_Check(keywords)) ||
- format == NULL ||
- kwlist == NULL)
- {
- PyErr_BadInternalCall();
- return 0;
- }
+ int retval;
+ va_list lva;
+
+ if ((args == NULL || !PyTuple_Check(args)) ||
+ (keywords != NULL && !PyDict_Check(keywords)) ||
+ format == NULL ||
+ kwlist == NULL)
+ {
+ PyErr_BadInternalCall();
+ return 0;
+ }
#ifdef VA_LIST_IS_ARRAY
- memcpy(lva, va, sizeof(va_list));
+ memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(lva, va);
+ __va_copy(lva, va);
#else
- lva = va;
+ lva = va;
#endif
#endif
- retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0);
- return retval;
+ retval = vgetargskeywords(args, keywords, format, kwlist, &lva, 0);
+ return retval;
}
int
_PyArg_VaParseTupleAndKeywords_SizeT(PyObject *args,
- PyObject *keywords,
- const char *format,
- char **kwlist, va_list va)
+ PyObject *keywords,
+ const char *format,
+ char **kwlist, va_list va)
{
- int retval;
- va_list lva;
-
- if ((args == NULL || !PyTuple_Check(args)) ||
- (keywords != NULL && !PyDict_Check(keywords)) ||
- format == NULL ||
- kwlist == NULL)
- {
- PyErr_BadInternalCall();
- return 0;
- }
+ int retval;
+ va_list lva;
+
+ if ((args == NULL || !PyTuple_Check(args)) ||
+ (keywords != NULL && !PyDict_Check(keywords)) ||
+ format == NULL ||
+ kwlist == NULL)
+ {
+ PyErr_BadInternalCall();
+ return 0;
+ }
#ifdef VA_LIST_IS_ARRAY
- memcpy(lva, va, sizeof(va_list));
+ memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(lva, va);
+ __va_copy(lva, va);
#else
- lva = va;
+ lva = va;
#endif
#endif
- retval = vgetargskeywords(args, keywords, format,
- kwlist, &lva, FLAG_SIZE_T);
- return retval;
+ retval = vgetargskeywords(args, keywords, format,
+ kwlist, &lva, FLAG_SIZE_T);
+ return retval;
}
#define IS_END_OF_FORMAT(c) (c == '\0' || c == ';' || c == ':')
static int
vgetargskeywords(PyObject *args, PyObject *keywords, const char *format,
- char **kwlist, va_list *p_va, int flags)
+ char **kwlist, va_list *p_va, int flags)
{
- char msgbuf[512];
- int levels[32];
- const char *fname, *msg, *custom_msg, *keyword;
- int min = INT_MAX;
- int i, len, nargs, nkeywords;
- PyObject *freelist = NULL, *current_arg;
-
- assert(args != NULL && PyTuple_Check(args));
- assert(keywords == NULL || PyDict_Check(keywords));
- assert(format != NULL);
- assert(kwlist != NULL);
- assert(p_va != NULL);
-
- /* grab the function name or custom error msg first (mutually exclusive) */
- fname = strchr(format, ':');
- if (fname) {
- fname++;
- custom_msg = NULL;
- }
- else {
- custom_msg = strchr(format,';');
- if (custom_msg)
- custom_msg++;
- }
-
- /* scan kwlist and get greatest possible nbr of args */
- for (len=0; kwlist[len]; len++)
- continue;
-
- nargs = PyTuple_GET_SIZE(args);
- nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords);
- if (nargs + nkeywords > len) {
- PyErr_Format(PyExc_TypeError, "%s%s takes at most %d "
- "argument%s (%d given)",
- (fname == NULL) ? "function" : fname,
- (fname == NULL) ? "" : "()",
- len,
- (len == 1) ? "" : "s",
- nargs + nkeywords);
- return 0;
- }
-
- /* convert tuple args and keyword args in same loop, using kwlist to drive process */
- for (i = 0; i < len; i++) {
- keyword = kwlist[i];
- if (*format == '|') {
- min = i;
- format++;
- }
- if (IS_END_OF_FORMAT(*format)) {
- PyErr_Format(PyExc_RuntimeError,
- "More keyword list entries (%d) than "
- "format specifiers (%d)", len, i);
- return cleanreturn(0, freelist);
- }
- current_arg = NULL;
- if (nkeywords) {
- current_arg = PyDict_GetItemString(keywords, keyword);
- }
- if (current_arg) {
- --nkeywords;
- if (i < nargs) {
- /* arg present in tuple and in dict */
- PyErr_Format(PyExc_TypeError,
- "Argument given by name ('%s') "
- "and position (%d)",
- keyword, i+1);
- return cleanreturn(0, freelist);
- }
- }
- else if (nkeywords && PyErr_Occurred())
- return cleanreturn(0, freelist);
- else if (i < nargs)
- current_arg = PyTuple_GET_ITEM(args, i);
-
- if (current_arg) {
- msg = convertitem(current_arg, &format, p_va, flags,
- levels, msgbuf, sizeof(msgbuf), &freelist);
- if (msg) {
- seterror(i+1, msg, levels, fname, custom_msg);
- return cleanreturn(0, freelist);
- }
- continue;
- }
-
- if (i < min) {
- PyErr_Format(PyExc_TypeError, "Required argument "
- "'%s' (pos %d) not found",
- keyword, i+1);
- return cleanreturn(0, freelist);
- }
- /* current code reports success when all required args
- * fulfilled and no keyword args left, with no further
- * validation. XXX Maybe skip this in debug build ?
- */
- if (!nkeywords)
- return cleanreturn(1, freelist);
-
- /* We are into optional args, skip thru to any remaining
- * keyword args */
- msg = skipitem(&format, p_va, flags);
- if (msg) {
- PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg,
- format);
- return cleanreturn(0, freelist);
- }
- }
-
- if (!IS_END_OF_FORMAT(*format) && *format != '|') {
- PyErr_Format(PyExc_RuntimeError,
- "more argument specifiers than keyword list entries "
- "(remaining format:'%s')", format);
- return cleanreturn(0, freelist);
- }
-
- /* make sure there are no extraneous keyword arguments */
- if (nkeywords > 0) {
- PyObject *key, *value;
- Py_ssize_t pos = 0;
- while (PyDict_Next(keywords, &pos, &key, &value)) {
- int match = 0;
- char *ks;
- if (!PyString_Check(key)) {
- PyErr_SetString(PyExc_TypeError,
- "keywords must be strings");
- return cleanreturn(0, freelist);
- }
- ks = PyString_AsString(key);
- for (i = 0; i < len; i++) {
- if (!strcmp(ks, kwlist[i])) {
- match = 1;
- break;
- }
- }
- if (!match) {
- PyErr_Format(PyExc_TypeError,
- "'%s' is an invalid keyword "
- "argument for this function",
- ks);
- return cleanreturn(0, freelist);
- }
- }
- }
-
- return cleanreturn(1, freelist);
+ char msgbuf[512];
+ int levels[32];
+ const char *fname, *msg, *custom_msg, *keyword;
+ int min = INT_MAX;
+ int i, len, nargs, nkeywords;
+ PyObject *freelist = NULL, *current_arg;
+
+ assert(args != NULL && PyTuple_Check(args));
+ assert(keywords == NULL || PyDict_Check(keywords));
+ assert(format != NULL);
+ assert(kwlist != NULL);
+ assert(p_va != NULL);
+
+ /* grab the function name or custom error msg first (mutually exclusive) */
+ fname = strchr(format, ':');
+ if (fname) {
+ fname++;
+ custom_msg = NULL;
+ }
+ else {
+ custom_msg = strchr(format,';');
+ if (custom_msg)
+ custom_msg++;
+ }
+
+ /* scan kwlist and get greatest possible nbr of args */
+ for (len=0; kwlist[len]; len++)
+ continue;
+
+ nargs = PyTuple_GET_SIZE(args);
+ nkeywords = (keywords == NULL) ? 0 : PyDict_Size(keywords);
+ if (nargs + nkeywords > len) {
+ PyErr_Format(PyExc_TypeError, "%s%s takes at most %d "
+ "argument%s (%d given)",
+ (fname == NULL) ? "function" : fname,
+ (fname == NULL) ? "" : "()",
+ len,
+ (len == 1) ? "" : "s",
+ nargs + nkeywords);
+ return 0;
+ }
+
+ /* convert tuple args and keyword args in same loop, using kwlist to drive process */
+ for (i = 0; i < len; i++) {
+ keyword = kwlist[i];
+ if (*format == '|') {
+ min = i;
+ format++;
+ }
+ if (IS_END_OF_FORMAT(*format)) {
+ PyErr_Format(PyExc_RuntimeError,
+ "More keyword list entries (%d) than "
+ "format specifiers (%d)", len, i);
+ return cleanreturn(0, freelist);
+ }
+ current_arg = NULL;
+ if (nkeywords) {
+ current_arg = PyDict_GetItemString(keywords, keyword);
+ }
+ if (current_arg) {
+ --nkeywords;
+ if (i < nargs) {
+ /* arg present in tuple and in dict */
+ PyErr_Format(PyExc_TypeError,
+ "Argument given by name ('%s') "
+ "and position (%d)",
+ keyword, i+1);
+ return cleanreturn(0, freelist);
+ }
+ }
+ else if (nkeywords && PyErr_Occurred())
+ return cleanreturn(0, freelist);
+ else if (i < nargs)
+ current_arg = PyTuple_GET_ITEM(args, i);
+
+ if (current_arg) {
+ msg = convertitem(current_arg, &format, p_va, flags,
+ levels, msgbuf, sizeof(msgbuf), &freelist);
+ if (msg) {
+ seterror(i+1, msg, levels, fname, custom_msg);
+ return cleanreturn(0, freelist);
+ }
+ continue;
+ }
+
+ if (i < min) {
+ PyErr_Format(PyExc_TypeError, "Required argument "
+ "'%s' (pos %d) not found",
+ keyword, i+1);
+ return cleanreturn(0, freelist);
+ }
+ /* current code reports success when all required args
+ * fulfilled and no keyword args left, with no further
+ * validation. XXX Maybe skip this in debug build ?
+ */
+ if (!nkeywords)
+ return cleanreturn(1, freelist);
+
+ /* We are into optional args, skip thru to any remaining
+ * keyword args */
+ msg = skipitem(&format, p_va, flags);
+ if (msg) {
+ PyErr_Format(PyExc_RuntimeError, "%s: '%s'", msg,
+ format);
+ return cleanreturn(0, freelist);
+ }
+ }
+
+ if (!IS_END_OF_FORMAT(*format) && *format != '|') {
+ PyErr_Format(PyExc_RuntimeError,
+ "more argument specifiers than keyword list entries "
+ "(remaining format:'%s')", format);
+ return cleanreturn(0, freelist);
+ }
+
+ /* make sure there are no extraneous keyword arguments */
+ if (nkeywords > 0) {
+ PyObject *key, *value;
+ Py_ssize_t pos = 0;
+ while (PyDict_Next(keywords, &pos, &key, &value)) {
+ int match = 0;
+ char *ks;
+ if (!PyString_Check(key)) {
+ PyErr_SetString(PyExc_TypeError,
+ "keywords must be strings");
+ return cleanreturn(0, freelist);
+ }
+ ks = PyString_AsString(key);
+ for (i = 0; i < len; i++) {
+ if (!strcmp(ks, kwlist[i])) {
+ match = 1;
+ break;
+ }
+ }
+ if (!match) {
+ PyErr_Format(PyExc_TypeError,
+ "'%s' is an invalid keyword "
+ "argument for this function",
+ ks);
+ return cleanreturn(0, freelist);
+ }
+ }
+ }
+
+ return cleanreturn(1, freelist);
}
static char *
skipitem(const char **p_format, va_list *p_va, int flags)
{
- const char *format = *p_format;
- char c = *format++;
-
- switch (c) {
-
- /* simple codes
- * The individual types (second arg of va_arg) are irrelevant */
-
- case 'b': /* byte -- very short int */
- case 'B': /* byte as bitfield */
- case 'h': /* short int */
- case 'H': /* short int as bitfield */
- case 'i': /* int */
- case 'I': /* int sized bitfield */
- case 'l': /* long int */
- case 'k': /* long int sized bitfield */
+ const char *format = *p_format;
+ char c = *format++;
+
+ switch (c) {
+
+ /* simple codes
+ * The individual types (second arg of va_arg) are irrelevant */
+
+ case 'b': /* byte -- very short int */
+ case 'B': /* byte as bitfield */
+ case 'h': /* short int */
+ case 'H': /* short int as bitfield */
+ case 'i': /* int */
+ case 'I': /* int sized bitfield */
+ case 'l': /* long int */
+ case 'k': /* long int sized bitfield */
#ifdef HAVE_LONG_LONG
- case 'L': /* PY_LONG_LONG */
- case 'K': /* PY_LONG_LONG sized bitfield */
+ case 'L': /* PY_LONG_LONG */
+ case 'K': /* PY_LONG_LONG sized bitfield */
#endif
- case 'f': /* float */
- case 'd': /* double */
+ case 'f': /* float */
+ case 'd': /* double */
#ifndef WITHOUT_COMPLEX
- case 'D': /* complex double */
+ case 'D': /* complex double */
#endif
- case 'c': /* char */
- {
- (void) va_arg(*p_va, void *);
- break;
- }
-
- case 'n': /* Py_ssize_t */
- {
- (void) va_arg(*p_va, Py_ssize_t *);
- break;
- }
-
- /* string codes */
-
- case 'e': /* string with encoding */
- {
- (void) va_arg(*p_va, const char *);
- if (!(*format == 's' || *format == 't'))
- /* after 'e', only 's' and 't' is allowed */
- goto err;
- format++;
- /* explicit fallthrough to string cases */
- }
-
- case 's': /* string */
- case 'z': /* string or None */
+ case 'c': /* char */
+ {
+ (void) va_arg(*p_va, void *);
+ break;
+ }
+
+ case 'n': /* Py_ssize_t */
+ {
+ (void) va_arg(*p_va, Py_ssize_t *);
+ break;
+ }
+
+ /* string codes */
+
+ case 'e': /* string with encoding */
+ {
+ (void) va_arg(*p_va, const char *);
+ if (!(*format == 's' || *format == 't'))
+ /* after 'e', only 's' and 't' is allowed */
+ goto err;
+ format++;
+ /* explicit fallthrough to string cases */
+ }
+
+ case 's': /* string */
+ case 'z': /* string or None */
#ifdef Py_USING_UNICODE
- case 'u': /* unicode string */
+ case 'u': /* unicode string */
#endif
- case 't': /* buffer, read-only */
- case 'w': /* buffer, read-write */
- {
- (void) va_arg(*p_va, char **);
- if (*format == '#') {
- if (flags & FLAG_SIZE_T)
- (void) va_arg(*p_va, Py_ssize_t *);
- else
- (void) va_arg(*p_va, int *);
- format++;
- } else if ((c == 's' || c == 'z') && *format == '*') {
- format++;
- }
- break;
- }
-
- /* object codes */
-
- case 'S': /* string object */
+ case 't': /* buffer, read-only */
+ case 'w': /* buffer, read-write */
+ {
+ (void) va_arg(*p_va, char **);
+ if (*format == '#') {
+ if (flags & FLAG_SIZE_T)
+ (void) va_arg(*p_va, Py_ssize_t *);
+ else
+ (void) va_arg(*p_va, int *);
+ format++;
+ } else if ((c == 's' || c == 'z') && *format == '*') {
+ format++;
+ }
+ break;
+ }
+
+ /* object codes */
+
+ case 'S': /* string object */
#ifdef Py_USING_UNICODE
- case 'U': /* unicode string object */
+ case 'U': /* unicode string object */
#endif
- {
- (void) va_arg(*p_va, PyObject **);
- break;
- }
-
- case 'O': /* object */
- {
- if (*format == '!') {
- format++;
- (void) va_arg(*p_va, PyTypeObject*);
- (void) va_arg(*p_va, PyObject **);
- }
- else if (*format == '&') {
- typedef int (*converter)(PyObject *, void *);
- (void) va_arg(*p_va, converter);
- (void) va_arg(*p_va, void *);
- format++;
- }
- else {
- (void) va_arg(*p_va, PyObject **);
- }
- break;
- }
-
- case '(': /* bypass tuple, not handled at all previously */
- {
- char *msg;
- for (;;) {
- if (*format==')')
- break;
- if (IS_END_OF_FORMAT(*format))
- return "Unmatched left paren in format "
- "string";
- msg = skipitem(&format, p_va, flags);
- if (msg)
- return msg;
- }
- format++;
- break;
- }
-
- case ')':
- return "Unmatched right paren in format string";
-
- default:
+ {
+ (void) va_arg(*p_va, PyObject **);
+ break;
+ }
+
+ case 'O': /* object */
+ {
+ if (*format == '!') {
+ format++;
+ (void) va_arg(*p_va, PyTypeObject*);
+ (void) va_arg(*p_va, PyObject **);
+ }
+ else if (*format == '&') {
+ typedef int (*converter)(PyObject *, void *);
+ (void) va_arg(*p_va, converter);
+ (void) va_arg(*p_va, void *);
+ format++;
+ }
+ else {
+ (void) va_arg(*p_va, PyObject **);
+ }
+ break;
+ }
+
+ case '(': /* bypass tuple, not handled at all previously */
+ {
+ char *msg;
+ for (;;) {
+ if (*format==')')
+ break;
+ if (IS_END_OF_FORMAT(*format))
+ return "Unmatched left paren in format "
+ "string";
+ msg = skipitem(&format, p_va, flags);
+ if (msg)
+ return msg;
+ }
+ format++;
+ break;
+ }
+
+ case ')':
+ return "Unmatched right paren in format string";
+
+ default:
err:
- return "impossible<bad format char>";
-
- }
+ return "impossible<bad format char>";
+
+ }
- *p_format = format;
- return NULL;
+ *p_format = format;
+ return NULL;
}
int
PyArg_UnpackTuple(PyObject *args, const char *name, Py_ssize_t min, Py_ssize_t max, ...)
{
- Py_ssize_t i, l;
- PyObject **o;
- va_list vargs;
+ Py_ssize_t i, l;
+ PyObject **o;
+ va_list vargs;
#ifdef HAVE_STDARG_PROTOTYPES
- va_start(vargs, max);
+ va_start(vargs, max);
#else
- va_start(vargs);
+ va_start(vargs);
#endif
- assert(min >= 0);
- assert(min <= max);
- if (!PyTuple_Check(args)) {
- PyErr_SetString(PyExc_SystemError,
- "PyArg_UnpackTuple() argument list is not a tuple");
- return 0;
- }
- l = PyTuple_GET_SIZE(args);
- if (l < min) {
- if (name != NULL)
- PyErr_Format(
- PyExc_TypeError,
- "%s expected %s%zd arguments, got %zd",
- name, (min == max ? "" : "at least "), min, l);
- else
- PyErr_Format(
- PyExc_TypeError,
- "unpacked tuple should have %s%zd elements,"
- " but has %zd",
- (min == max ? "" : "at least "), min, l);
- va_end(vargs);
- return 0;
- }
- if (l > max) {
- if (name != NULL)
- PyErr_Format(
- PyExc_TypeError,
- "%s expected %s%zd arguments, got %zd",
- name, (min == max ? "" : "at most "), max, l);
- else
- PyErr_Format(
- PyExc_TypeError,
- "unpacked tuple should have %s%zd elements,"
- " but has %zd",
- (min == max ? "" : "at most "), max, l);
- va_end(vargs);
- return 0;
- }
- for (i = 0; i < l; i++) {
- o = va_arg(vargs, PyObject **);
- *o = PyTuple_GET_ITEM(args, i);
- }
- va_end(vargs);
- return 1;
+ assert(min >= 0);
+ assert(min <= max);
+ if (!PyTuple_Check(args)) {
+ PyErr_SetString(PyExc_SystemError,
+ "PyArg_UnpackTuple() argument list is not a tuple");
+ return 0;
+ }
+ l = PyTuple_GET_SIZE(args);
+ if (l < min) {
+ if (name != NULL)
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s expected %s%zd arguments, got %zd",
+ name, (min == max ? "" : "at least "), min, l);
+ else
+ PyErr_Format(
+ PyExc_TypeError,
+ "unpacked tuple should have %s%zd elements,"
+ " but has %zd",
+ (min == max ? "" : "at least "), min, l);
+ va_end(vargs);
+ return 0;
+ }
+ if (l > max) {
+ if (name != NULL)
+ PyErr_Format(
+ PyExc_TypeError,
+ "%s expected %s%zd arguments, got %zd",
+ name, (min == max ? "" : "at most "), max, l);
+ else
+ PyErr_Format(
+ PyExc_TypeError,
+ "unpacked tuple should have %s%zd elements,"
+ " but has %zd",
+ (min == max ? "" : "at most "), max, l);
+ va_end(vargs);
+ return 0;
+ }
+ for (i = 0; i < l; i++) {
+ o = va_arg(vargs, PyObject **);
+ *o = PyTuple_GET_ITEM(args, i);
+ }
+ va_end(vargs);
+ return 1;
}
/* For type constructors that don't take keyword args
*
- * Sets a TypeError and returns 0 if the kwds dict is
+ * Sets a TypeError and returns 0 if the kwds dict is
* not empty, returns 1 otherwise
*/
int
_PyArg_NoKeywords(const char *funcname, PyObject *kw)
{
- if (kw == NULL)
- return 1;
- if (!PyDict_CheckExact(kw)) {
- PyErr_BadInternalCall();
- return 0;
- }
- if (PyDict_Size(kw) == 0)
- return 1;
-
- PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments",
- funcname);
- return 0;
+ if (kw == NULL)
+ return 1;
+ if (!PyDict_CheckExact(kw)) {
+ PyErr_BadInternalCall();
+ return 0;
+ }
+ if (PyDict_Size(kw) == 0)
+ return 1;
+
+ PyErr_Format(PyExc_TypeError, "%s does not take keyword arguments",
+ funcname);
+ return 0;
}
#ifdef __cplusplus
};
diff --git a/Python/getcwd.c b/Python/getcwd.c
index 36fcd5c..44dc9e6 100644
--- a/Python/getcwd.c
+++ b/Python/getcwd.c
@@ -26,24 +26,24 @@ extern char *getwd(char *);
char *
getcwd(char *buf, int size)
{
- char localbuf[MAXPATHLEN+1];
- char *ret;
+ char localbuf[MAXPATHLEN+1];
+ char *ret;
- if (size <= 0) {
- errno = EINVAL;
- return NULL;
- }
- ret = getwd(localbuf);
- if (ret != NULL && strlen(localbuf) >= (size_t)size) {
- errno = ERANGE;
- return NULL;
- }
- if (ret == NULL) {
- errno = EACCES; /* Most likely error */
- return NULL;
- }
- strncpy(buf, localbuf, size);
- return buf;
+ if (size <= 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+ ret = getwd(localbuf);
+ if (ret != NULL && strlen(localbuf) >= (size_t)size) {
+ errno = ERANGE;
+ return NULL;
+ }
+ if (ret == NULL) {
+ errno = EACCES; /* Most likely error */
+ return NULL;
+ }
+ strncpy(buf, localbuf, size);
+ return buf;
}
#else /* !HAVE_GETWD */
@@ -57,26 +57,26 @@ getcwd(char *buf, int size)
char *
getcwd(char *buf, int size)
{
- FILE *fp;
- char *p;
- if (size <= 0) {
- errno = EINVAL;
- return NULL;
- }
- if ((fp = popen(PWD_CMD, "r")) == NULL)
- return NULL;
- if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) {
- errno = EACCES; /* Most likely error */
- return NULL;
- }
- for (p = buf; *p != '\n'; p++) {
- if (*p == '\0') {
- errno = ERANGE;
- return NULL;
- }
- }
- *p = '\0';
- return buf;
+ FILE *fp;
+ char *p;
+ if (size <= 0) {
+ errno = EINVAL;
+ return NULL;
+ }
+ if ((fp = popen(PWD_CMD, "r")) == NULL)
+ return NULL;
+ if (fgets(buf, size, fp) == NULL || pclose(fp) != 0) {
+ errno = EACCES; /* Most likely error */
+ return NULL;
+ }
+ for (p = buf; *p != '\n'; p++) {
+ if (*p == '\0') {
+ errno = ERANGE;
+ return NULL;
+ }
+ }
+ *p = '\0';
+ return buf;
}
#endif /* !HAVE_GETWD */
diff --git a/Python/getopt.c b/Python/getopt.c
index 247600b..093c3da 100644
--- a/Python/getopt.c
+++ b/Python/getopt.c
@@ -7,8 +7,8 @@
*
* 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, this permission notice and
* the following disclaimer notice appear unmodified in all copies.
*
@@ -40,84 +40,84 @@ char *_PyOS_optarg = NULL; /* optional argument */
int _PyOS_GetOpt(int argc, char **argv, char *optstring)
{
- static char *opt_ptr = "";
- char *ptr;
- int option;
+ static char *opt_ptr = "";
+ char *ptr;
+ int option;
- if (*opt_ptr == '\0') {
+ if (*opt_ptr == '\0') {
- if (_PyOS_optind >= argc)
- return -1;
+ if (_PyOS_optind >= argc)
+ return -1;
#ifdef MS_WINDOWS
- else if (strcmp(argv[_PyOS_optind], "/?") == 0) {
- ++_PyOS_optind;
- return 'h';
- }
+ else if (strcmp(argv[_PyOS_optind], "/?") == 0) {
+ ++_PyOS_optind;
+ return 'h';
+ }
#endif
- else if (argv[_PyOS_optind][0] != '-' ||
- argv[_PyOS_optind][1] == '\0' /* lone dash */ )
- return -1;
-
- else if (strcmp(argv[_PyOS_optind], "--") == 0) {
- ++_PyOS_optind;
- return -1;
- }
-
- else if (strcmp(argv[_PyOS_optind], "--help") == 0) {
- ++_PyOS_optind;
- return 'h';
- }
-
- else if (strcmp(argv[_PyOS_optind], "--version") == 0) {
- ++_PyOS_optind;
- return 'V';
- }
-
-
- opt_ptr = &argv[_PyOS_optind++][1];
- }
-
- if ( (option = *opt_ptr++) == '\0')
- return -1;
-
- if (option == 'J') {
- fprintf(stderr, "-J is reserved for Jython\n");
- return '_';
- }
-
- if (option == 'X') {
- fprintf(stderr,
- "-X is reserved for implementation-specific arguments\n");
- return '_';
- }
-
- if ((ptr = strchr(optstring, option)) == NULL) {
- if (_PyOS_opterr)
- fprintf(stderr, "Unknown option: -%c\n", option);
-
- return '_';
- }
-
- if (*(ptr + 1) == ':') {
- if (*opt_ptr != '\0') {
- _PyOS_optarg = opt_ptr;
- opt_ptr = "";
- }
-
- else {
- if (_PyOS_optind >= argc) {
- if (_PyOS_opterr)
- fprintf(stderr,
- "Argument expected for the -%c option\n", option);
- return '_';
- }
-
- _PyOS_optarg = argv[_PyOS_optind++];
- }
- }
-
- return option;
+ else if (argv[_PyOS_optind][0] != '-' ||
+ argv[_PyOS_optind][1] == '\0' /* lone dash */ )
+ return -1;
+
+ else if (strcmp(argv[_PyOS_optind], "--") == 0) {
+ ++_PyOS_optind;
+ return -1;
+ }
+
+ else if (strcmp(argv[_PyOS_optind], "--help") == 0) {
+ ++_PyOS_optind;
+ return 'h';
+ }
+
+ else if (strcmp(argv[_PyOS_optind], "--version") == 0) {
+ ++_PyOS_optind;
+ return 'V';
+ }
+
+
+ opt_ptr = &argv[_PyOS_optind++][1];
+ }
+
+ if ( (option = *opt_ptr++) == '\0')
+ return -1;
+
+ if (option == 'J') {
+ fprintf(stderr, "-J is reserved for Jython\n");
+ return '_';
+ }
+
+ if (option == 'X') {
+ fprintf(stderr,
+ "-X is reserved for implementation-specific arguments\n");
+ return '_';
+ }
+
+ if ((ptr = strchr(optstring, option)) == NULL) {
+ if (_PyOS_opterr)
+ fprintf(stderr, "Unknown option: -%c\n", option);
+
+ return '_';
+ }
+
+ if (*(ptr + 1) == ':') {
+ if (*opt_ptr != '\0') {
+ _PyOS_optarg = opt_ptr;
+ opt_ptr = "";
+ }
+
+ else {
+ if (_PyOS_optind >= argc) {
+ if (_PyOS_opterr)
+ fprintf(stderr,
+ "Argument expected for the -%c option\n", option);
+ return '_';
+ }
+
+ _PyOS_optarg = argv[_PyOS_optind++];
+ }
+ }
+
+ return option;
}
#ifdef __cplusplus
diff --git a/Python/import.c b/Python/import.c
index a5e23e8..7abe679 100644
--- a/Python/import.c
+++ b/Python/import.c
@@ -67,13 +67,13 @@ typedef unsigned short mode_t;
Python 2.5b3: 62101 (fix wrong code: for x, in ...)
Python 2.5b3: 62111 (fix wrong code: x += yield)
Python 2.5c1: 62121 (fix wrong lnotab with for loops and
- storing constants that should have been removed)
+ storing constants that should have been removed)
Python 2.5c2: 62131 (fix wrong code: for x, in ... in listcomp/genexp)
Python 2.6a0: 62151 (peephole optimizations and STORE_MAP opcode)
Python 2.6a1: 62161 (WITH_CLEANUP optimization)
Python 2.7a0: 62171 (optimize list comprehensions/change LIST_APPEND)
Python 2.7a0: 62181 (optimize conditional branches:
- introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
+ introduce POP_JUMP_IF_FALSE and POP_JUMP_IF_TRUE)
Python 2.7a0 62191 (introduce SETUP_WITH)
Python 2.7a0 62201 (introduce BUILD_SET)
Python 2.7a0 62211 (introduce MAP_ADD and SET_ADD)
@@ -99,18 +99,18 @@ struct filedescr * _PyImport_Filetab = NULL;
#ifdef RISCOS
static const struct filedescr _PyImport_StandardFiletab[] = {
- {"/py", "U", PY_SOURCE},
- {"/pyc", "rb", PY_COMPILED},
- {0, 0}
+ {"/py", "U", PY_SOURCE},
+ {"/pyc", "rb", PY_COMPILED},
+ {0, 0}
};
#else
static const struct filedescr _PyImport_StandardFiletab[] = {
- {".py", "U", PY_SOURCE},
+ {".py", "U", PY_SOURCE},
#ifdef MS_WINDOWS
- {".pyw", "U", PY_SOURCE},
+ {".pyw", "U", PY_SOURCE},
#endif
- {".pyc", "rb", PY_COMPILED},
- {0, 0}
+ {".pyc", "rb", PY_COMPILED},
+ {0, 0}
};
#endif
@@ -120,131 +120,131 @@ static const struct filedescr _PyImport_StandardFiletab[] = {
void
_PyImport_Init(void)
{
- const struct filedescr *scan;
- struct filedescr *filetab;
- int countD = 0;
- int countS = 0;
+ const struct filedescr *scan;
+ struct filedescr *filetab;
+ int countD = 0;
+ int countS = 0;
- /* prepare _PyImport_Filetab: copy entries from
- _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
- */
+ /* prepare _PyImport_Filetab: copy entries from
+ _PyImport_DynLoadFiletab and _PyImport_StandardFiletab.
+ */
#ifdef HAVE_DYNAMIC_LOADING
- for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
- ++countD;
+ for (scan = _PyImport_DynLoadFiletab; scan->suffix != NULL; ++scan)
+ ++countD;
#endif
- for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
- ++countS;
- filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
- if (filetab == NULL)
- Py_FatalError("Can't initialize import file table.");
+ for (scan = _PyImport_StandardFiletab; scan->suffix != NULL; ++scan)
+ ++countS;
+ filetab = PyMem_NEW(struct filedescr, countD + countS + 1);
+ if (filetab == NULL)
+ Py_FatalError("Can't initialize import file table.");
#ifdef HAVE_DYNAMIC_LOADING
- memcpy(filetab, _PyImport_DynLoadFiletab,
- countD * sizeof(struct filedescr));
+ memcpy(filetab, _PyImport_DynLoadFiletab,
+ countD * sizeof(struct filedescr));
#endif
- memcpy(filetab + countD, _PyImport_StandardFiletab,
- countS * sizeof(struct filedescr));
- filetab[countD + countS].suffix = NULL;
+ memcpy(filetab + countD, _PyImport_StandardFiletab,
+ countS * sizeof(struct filedescr));
+ filetab[countD + countS].suffix = NULL;
- _PyImport_Filetab = filetab;
+ _PyImport_Filetab = filetab;
- if (Py_OptimizeFlag) {
- /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
- for (; filetab->suffix != NULL; filetab++) {
+ if (Py_OptimizeFlag) {
+ /* Replace ".pyc" with ".pyo" in _PyImport_Filetab */
+ for (; filetab->suffix != NULL; filetab++) {
#ifndef RISCOS
- if (strcmp(filetab->suffix, ".pyc") == 0)
- filetab->suffix = ".pyo";
+ if (strcmp(filetab->suffix, ".pyc") == 0)
+ filetab->suffix = ".pyo";
#else
- if (strcmp(filetab->suffix, "/pyc") == 0)
- filetab->suffix = "/pyo";
+ if (strcmp(filetab->suffix, "/pyc") == 0)
+ filetab->suffix = "/pyo";
#endif
- }
- }
+ }
+ }
- if (Py_UnicodeFlag) {
- /* Fix the pyc_magic so that byte compiled code created
- using the all-Unicode method doesn't interfere with
- code created in normal operation mode. */
- pyc_magic = MAGIC + 1;
- }
+ if (Py_UnicodeFlag) {
+ /* Fix the pyc_magic so that byte compiled code created
+ using the all-Unicode method doesn't interfere with
+ code created in normal operation mode. */
+ pyc_magic = MAGIC + 1;
+ }
}
void
_PyImportHooks_Init(void)
{
- PyObject *v, *path_hooks = NULL, *zimpimport;
- int err = 0;
-
- /* adding sys.path_hooks and sys.path_importer_cache, setting up
- zipimport */
- if (PyType_Ready(&PyNullImporter_Type) < 0)
- goto error;
-
- if (Py_VerboseFlag)
- PySys_WriteStderr("# installing zipimport hook\n");
-
- v = PyList_New(0);
- if (v == NULL)
- goto error;
- err = PySys_SetObject("meta_path", v);
- Py_DECREF(v);
- if (err)
- goto error;
- v = PyDict_New();
- if (v == NULL)
- goto error;
- err = PySys_SetObject("path_importer_cache", v);
- Py_DECREF(v);
- if (err)
- goto error;
- path_hooks = PyList_New(0);
- if (path_hooks == NULL)
- goto error;
- err = PySys_SetObject("path_hooks", path_hooks);
- if (err) {
+ PyObject *v, *path_hooks = NULL, *zimpimport;
+ int err = 0;
+
+ /* adding sys.path_hooks and sys.path_importer_cache, setting up
+ zipimport */
+ if (PyType_Ready(&PyNullImporter_Type) < 0)
+ goto error;
+
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# installing zipimport hook\n");
+
+ v = PyList_New(0);
+ if (v == NULL)
+ goto error;
+ err = PySys_SetObject("meta_path", v);
+ Py_DECREF(v);
+ if (err)
+ goto error;
+ v = PyDict_New();
+ if (v == NULL)
+ goto error;
+ err = PySys_SetObject("path_importer_cache", v);
+ Py_DECREF(v);
+ if (err)
+ goto error;
+ path_hooks = PyList_New(0);
+ if (path_hooks == NULL)
+ goto error;
+ err = PySys_SetObject("path_hooks", path_hooks);
+ if (err) {
error:
- PyErr_Print();
- Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
- "path_importer_cache, or NullImporter failed"
- );
- }
-
- zimpimport = PyImport_ImportModule("zipimport");
- if (zimpimport == NULL) {
- PyErr_Clear(); /* No zip import module -- okay */
- if (Py_VerboseFlag)
- PySys_WriteStderr("# can't import zipimport\n");
- }
- else {
- PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
- "zipimporter");
- Py_DECREF(zimpimport);
- if (zipimporter == NULL) {
- PyErr_Clear(); /* No zipimporter object -- okay */
- if (Py_VerboseFlag)
- PySys_WriteStderr(
- "# can't import zipimport.zipimporter\n");
- }
- else {
- /* sys.path_hooks.append(zipimporter) */
- err = PyList_Append(path_hooks, zipimporter);
- Py_DECREF(zipimporter);
- if (err)
- goto error;
- if (Py_VerboseFlag)
- PySys_WriteStderr(
- "# installed zipimport hook\n");
- }
- }
- Py_DECREF(path_hooks);
+ PyErr_Print();
+ Py_FatalError("initializing sys.meta_path, sys.path_hooks, "
+ "path_importer_cache, or NullImporter failed"
+ );
+ }
+
+ zimpimport = PyImport_ImportModule("zipimport");
+ if (zimpimport == NULL) {
+ PyErr_Clear(); /* No zip import module -- okay */
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# can't import zipimport\n");
+ }
+ else {
+ PyObject *zipimporter = PyObject_GetAttrString(zimpimport,
+ "zipimporter");
+ Py_DECREF(zimpimport);
+ if (zipimporter == NULL) {
+ PyErr_Clear(); /* No zipimporter object -- okay */
+ if (Py_VerboseFlag)
+ PySys_WriteStderr(
+ "# can't import zipimport.zipimporter\n");
+ }
+ else {
+ /* sys.path_hooks.append(zipimporter) */
+ err = PyList_Append(path_hooks, zipimporter);
+ Py_DECREF(zipimporter);
+ if (err)
+ goto error;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr(
+ "# installed zipimport hook\n");
+ }
+ }
+ Py_DECREF(path_hooks);
}
void
_PyImport_Fini(void)
{
- Py_XDECREF(extensions);
- extensions = NULL;
- PyMem_DEL(_PyImport_Filetab);
- _PyImport_Filetab = NULL;
+ Py_XDECREF(extensions);
+ extensions = NULL;
+ PyMem_DEL(_PyImport_Filetab);
+ _PyImport_Filetab = NULL;
}
@@ -263,42 +263,42 @@ static int import_lock_level = 0;
void
_PyImport_AcquireLock(void)
{
- long me = PyThread_get_thread_ident();
- if (me == -1)
- return; /* Too bad */
- if (import_lock == NULL) {
- import_lock = PyThread_allocate_lock();
- if (import_lock == NULL)
- return; /* Nothing much we can do. */
- }
- if (import_lock_thread == me) {
- import_lock_level++;
- return;
- }
- if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
- {
- PyThreadState *tstate = PyEval_SaveThread();
- PyThread_acquire_lock(import_lock, 1);
- PyEval_RestoreThread(tstate);
- }
- import_lock_thread = me;
- import_lock_level = 1;
+ long me = PyThread_get_thread_ident();
+ if (me == -1)
+ return; /* Too bad */
+ if (import_lock == NULL) {
+ import_lock = PyThread_allocate_lock();
+ if (import_lock == NULL)
+ return; /* Nothing much we can do. */
+ }
+ if (import_lock_thread == me) {
+ import_lock_level++;
+ return;
+ }
+ if (import_lock_thread != -1 || !PyThread_acquire_lock(import_lock, 0))
+ {
+ PyThreadState *tstate = PyEval_SaveThread();
+ PyThread_acquire_lock(import_lock, 1);
+ PyEval_RestoreThread(tstate);
+ }
+ import_lock_thread = me;
+ import_lock_level = 1;
}
int
_PyImport_ReleaseLock(void)
{
- long me = PyThread_get_thread_ident();
- if (me == -1 || import_lock == NULL)
- return 0; /* Too bad */
- if (import_lock_thread != me)
- return -1;
- import_lock_level--;
- if (import_lock_level == 0) {
- import_lock_thread = -1;
- PyThread_release_lock(import_lock);
- }
- return 1;
+ long me = PyThread_get_thread_ident();
+ if (me == -1 || import_lock == NULL)
+ return 0; /* Too bad */
+ if (import_lock_thread != me)
+ return -1;
+ import_lock_level--;
+ if (import_lock_level == 0) {
+ import_lock_thread = -1;
+ PyThread_release_lock(import_lock);
+ }
+ return 1;
}
/* This function is called from PyOS_AfterFork to ensure that newly
@@ -309,10 +309,10 @@ _PyImport_ReleaseLock(void)
void
_PyImport_ReInitLock(void)
{
- if (import_lock != NULL)
- import_lock = PyThread_allocate_lock();
- import_lock_thread = -1;
- import_lock_level = 0;
+ if (import_lock != NULL)
+ import_lock = PyThread_allocate_lock();
+ import_lock_thread = -1;
+ import_lock_level = 0;
}
#endif
@@ -321,9 +321,9 @@ static PyObject *
imp_lock_held(PyObject *self, PyObject *noargs)
{
#ifdef WITH_THREAD
- return PyBool_FromLong(import_lock_thread != -1);
+ return PyBool_FromLong(import_lock_thread != -1);
#else
- return PyBool_FromLong(0);
+ return PyBool_FromLong(0);
#endif
}
@@ -331,32 +331,32 @@ static PyObject *
imp_acquire_lock(PyObject *self, PyObject *noargs)
{
#ifdef WITH_THREAD
- _PyImport_AcquireLock();
+ _PyImport_AcquireLock();
#endif
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
imp_release_lock(PyObject *self, PyObject *noargs)
{
#ifdef WITH_THREAD
- if (_PyImport_ReleaseLock() < 0) {
- PyErr_SetString(PyExc_RuntimeError,
- "not holding the import lock");
- return NULL;
- }
+ if (_PyImport_ReleaseLock() < 0) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "not holding the import lock");
+ return NULL;
+ }
#endif
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static void
imp_modules_reloading_clear(void)
{
- PyInterpreterState *interp = PyThreadState_Get()->interp;
- if (interp->modules_reloading != NULL)
- PyDict_Clear(interp->modules_reloading);
+ PyInterpreterState *interp = PyThreadState_Get()->interp;
+ if (interp->modules_reloading != NULL)
+ PyDict_Clear(interp->modules_reloading);
}
/* Helper for sys */
@@ -364,29 +364,29 @@ imp_modules_reloading_clear(void)
PyObject *
PyImport_GetModuleDict(void)
{
- PyInterpreterState *interp = PyThreadState_GET()->interp;
- if (interp->modules == NULL)
- Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
- return interp->modules;
+ PyInterpreterState *interp = PyThreadState_GET()->interp;
+ if (interp->modules == NULL)
+ Py_FatalError("PyImport_GetModuleDict: no module dictionary!");
+ return interp->modules;
}
/* List of names to clear in sys */
static char* sys_deletes[] = {
- "path", "argv", "ps1", "ps2", "exitfunc",
- "exc_type", "exc_value", "exc_traceback",
- "last_type", "last_value", "last_traceback",
- "path_hooks", "path_importer_cache", "meta_path",
- /* misc stuff */
- "flags", "float_info",
- NULL
+ "path", "argv", "ps1", "ps2", "exitfunc",
+ "exc_type", "exc_value", "exc_traceback",
+ "last_type", "last_value", "last_traceback",
+ "path_hooks", "path_importer_cache", "meta_path",
+ /* misc stuff */
+ "flags", "float_info",
+ NULL
};
static char* sys_files[] = {
- "stdin", "__stdin__",
- "stdout", "__stdout__",
- "stderr", "__stderr__",
- NULL
+ "stdin", "__stdin__",
+ "stdout", "__stdout__",
+ "stderr", "__stderr__",
+ NULL
};
@@ -395,132 +395,132 @@ static char* sys_files[] = {
void
PyImport_Cleanup(void)
{
- Py_ssize_t pos, ndone;
- char *name;
- PyObject *key, *value, *dict;
- PyInterpreterState *interp = PyThreadState_GET()->interp;
- PyObject *modules = interp->modules;
-
- if (modules == NULL)
- return; /* Already done */
-
- /* Delete some special variables first. These are common
- places where user values hide and people complain when their
- destructors fail. Since the modules containing them are
- deleted *last* of all, they would come too late in the normal
- destruction order. Sigh. */
-
- value = PyDict_GetItemString(modules, "__builtin__");
- if (value != NULL && PyModule_Check(value)) {
- dict = PyModule_GetDict(value);
- if (Py_VerboseFlag)
- PySys_WriteStderr("# clear __builtin__._\n");
- PyDict_SetItemString(dict, "_", Py_None);
- }
- value = PyDict_GetItemString(modules, "sys");
- if (value != NULL && PyModule_Check(value)) {
- char **p;
- PyObject *v;
- dict = PyModule_GetDict(value);
- for (p = sys_deletes; *p != NULL; p++) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# clear sys.%s\n", *p);
- PyDict_SetItemString(dict, *p, Py_None);
- }
- for (p = sys_files; *p != NULL; p+=2) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# restore sys.%s\n", *p);
- v = PyDict_GetItemString(dict, *(p+1));
- if (v == NULL)
- v = Py_None;
- PyDict_SetItemString(dict, *p, v);
- }
- }
-
- /* First, delete __main__ */
- value = PyDict_GetItemString(modules, "__main__");
- if (value != NULL && PyModule_Check(value)) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# cleanup __main__\n");
- _PyModule_Clear(value);
- PyDict_SetItemString(modules, "__main__", Py_None);
- }
-
- /* The special treatment of __builtin__ here is because even
- when it's not referenced as a module, its dictionary is
- referenced by almost every module's __builtins__. Since
- deleting a module clears its dictionary (even if there are
- references left to it), we need to delete the __builtin__
- module last. Likewise, we don't delete sys until the very
- end because it is implicitly referenced (e.g. by print).
-
- Also note that we 'delete' modules by replacing their entry
- in the modules dict with None, rather than really deleting
- them; this avoids a rehash of the modules dictionary and
- also marks them as "non existent" so they won't be
- re-imported. */
-
- /* Next, repeatedly delete modules with a reference count of
- one (skipping __builtin__ and sys) and delete them */
- do {
- ndone = 0;
- pos = 0;
- while (PyDict_Next(modules, &pos, &key, &value)) {
- if (value->ob_refcnt != 1)
- continue;
- if (PyString_Check(key) && PyModule_Check(value)) {
- name = PyString_AS_STRING(key);
- if (strcmp(name, "__builtin__") == 0)
- continue;
- if (strcmp(name, "sys") == 0)
- continue;
- if (Py_VerboseFlag)
- PySys_WriteStderr(
- "# cleanup[1] %s\n", name);
- _PyModule_Clear(value);
- PyDict_SetItem(modules, key, Py_None);
- ndone++;
- }
- }
- } while (ndone > 0);
-
- /* Next, delete all modules (still skipping __builtin__ and sys) */
- pos = 0;
- while (PyDict_Next(modules, &pos, &key, &value)) {
- if (PyString_Check(key) && PyModule_Check(value)) {
- name = PyString_AS_STRING(key);
- if (strcmp(name, "__builtin__") == 0)
- continue;
- if (strcmp(name, "sys") == 0)
- continue;
- if (Py_VerboseFlag)
- PySys_WriteStderr("# cleanup[2] %s\n", name);
- _PyModule_Clear(value);
- PyDict_SetItem(modules, key, Py_None);
- }
- }
-
- /* Next, delete sys and __builtin__ (in that order) */
- value = PyDict_GetItemString(modules, "sys");
- if (value != NULL && PyModule_Check(value)) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# cleanup sys\n");
- _PyModule_Clear(value);
- PyDict_SetItemString(modules, "sys", Py_None);
- }
- value = PyDict_GetItemString(modules, "__builtin__");
- if (value != NULL && PyModule_Check(value)) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# cleanup __builtin__\n");
- _PyModule_Clear(value);
- PyDict_SetItemString(modules, "__builtin__", Py_None);
- }
-
- /* Finally, clear and delete the modules directory */
- PyDict_Clear(modules);
- interp->modules = NULL;
- Py_DECREF(modules);
- Py_CLEAR(interp->modules_reloading);
+ Py_ssize_t pos, ndone;
+ char *name;
+ PyObject *key, *value, *dict;
+ PyInterpreterState *interp = PyThreadState_GET()->interp;
+ PyObject *modules = interp->modules;
+
+ if (modules == NULL)
+ return; /* Already done */
+
+ /* Delete some special variables first. These are common
+ places where user values hide and people complain when their
+ destructors fail. Since the modules containing them are
+ deleted *last* of all, they would come too late in the normal
+ destruction order. Sigh. */
+
+ value = PyDict_GetItemString(modules, "__builtin__");
+ if (value != NULL && PyModule_Check(value)) {
+ dict = PyModule_GetDict(value);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# clear __builtin__._\n");
+ PyDict_SetItemString(dict, "_", Py_None);
+ }
+ value = PyDict_GetItemString(modules, "sys");
+ if (value != NULL && PyModule_Check(value)) {
+ char **p;
+ PyObject *v;
+ dict = PyModule_GetDict(value);
+ for (p = sys_deletes; *p != NULL; p++) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# clear sys.%s\n", *p);
+ PyDict_SetItemString(dict, *p, Py_None);
+ }
+ for (p = sys_files; *p != NULL; p+=2) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# restore sys.%s\n", *p);
+ v = PyDict_GetItemString(dict, *(p+1));
+ if (v == NULL)
+ v = Py_None;
+ PyDict_SetItemString(dict, *p, v);
+ }
+ }
+
+ /* First, delete __main__ */
+ value = PyDict_GetItemString(modules, "__main__");
+ if (value != NULL && PyModule_Check(value)) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# cleanup __main__\n");
+ _PyModule_Clear(value);
+ PyDict_SetItemString(modules, "__main__", Py_None);
+ }
+
+ /* The special treatment of __builtin__ here is because even
+ when it's not referenced as a module, its dictionary is
+ referenced by almost every module's __builtins__. Since
+ deleting a module clears its dictionary (even if there are
+ references left to it), we need to delete the __builtin__
+ module last. Likewise, we don't delete sys until the very
+ end because it is implicitly referenced (e.g. by print).
+
+ Also note that we 'delete' modules by replacing their entry
+ in the modules dict with None, rather than really deleting
+ them; this avoids a rehash of the modules dictionary and
+ also marks them as "non existent" so they won't be
+ re-imported. */
+
+ /* Next, repeatedly delete modules with a reference count of
+ one (skipping __builtin__ and sys) and delete them */
+ do {
+ ndone = 0;
+ pos = 0;
+ while (PyDict_Next(modules, &pos, &key, &value)) {
+ if (value->ob_refcnt != 1)
+ continue;
+ if (PyString_Check(key) && PyModule_Check(value)) {
+ name = PyString_AS_STRING(key);
+ if (strcmp(name, "__builtin__") == 0)
+ continue;
+ if (strcmp(name, "sys") == 0)
+ continue;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr(
+ "# cleanup[1] %s\n", name);
+ _PyModule_Clear(value);
+ PyDict_SetItem(modules, key, Py_None);
+ ndone++;
+ }
+ }
+ } while (ndone > 0);
+
+ /* Next, delete all modules (still skipping __builtin__ and sys) */
+ pos = 0;
+ while (PyDict_Next(modules, &pos, &key, &value)) {
+ if (PyString_Check(key) && PyModule_Check(value)) {
+ name = PyString_AS_STRING(key);
+ if (strcmp(name, "__builtin__") == 0)
+ continue;
+ if (strcmp(name, "sys") == 0)
+ continue;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# cleanup[2] %s\n", name);
+ _PyModule_Clear(value);
+ PyDict_SetItem(modules, key, Py_None);
+ }
+ }
+
+ /* Next, delete sys and __builtin__ (in that order) */
+ value = PyDict_GetItemString(modules, "sys");
+ if (value != NULL && PyModule_Check(value)) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# cleanup sys\n");
+ _PyModule_Clear(value);
+ PyDict_SetItemString(modules, "sys", Py_None);
+ }
+ value = PyDict_GetItemString(modules, "__builtin__");
+ if (value != NULL && PyModule_Check(value)) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# cleanup __builtin__\n");
+ _PyModule_Clear(value);
+ PyDict_SetItemString(modules, "__builtin__", Py_None);
+ }
+
+ /* Finally, clear and delete the modules directory */
+ PyDict_Clear(modules);
+ interp->modules = NULL;
+ Py_DECREF(modules);
+ Py_CLEAR(interp->modules_reloading);
}
@@ -529,7 +529,7 @@ PyImport_Cleanup(void)
long
PyImport_GetMagicNumber(void)
{
- return pyc_magic;
+ return pyc_magic;
}
@@ -546,51 +546,51 @@ PyImport_GetMagicNumber(void)
PyObject *
_PyImport_FixupExtension(char *name, char *filename)
{
- PyObject *modules, *mod, *dict, *copy;
- if (extensions == NULL) {
- extensions = PyDict_New();
- if (extensions == NULL)
- return NULL;
- }
- modules = PyImport_GetModuleDict();
- mod = PyDict_GetItemString(modules, name);
- if (mod == NULL || !PyModule_Check(mod)) {
- PyErr_Format(PyExc_SystemError,
- "_PyImport_FixupExtension: module %.200s not loaded", name);
- return NULL;
- }
- dict = PyModule_GetDict(mod);
- if (dict == NULL)
- return NULL;
- copy = PyDict_Copy(dict);
- if (copy == NULL)
- return NULL;
- PyDict_SetItemString(extensions, filename, copy);
- Py_DECREF(copy);
- return copy;
+ PyObject *modules, *mod, *dict, *copy;
+ if (extensions == NULL) {
+ extensions = PyDict_New();
+ if (extensions == NULL)
+ return NULL;
+ }
+ modules = PyImport_GetModuleDict();
+ mod = PyDict_GetItemString(modules, name);
+ if (mod == NULL || !PyModule_Check(mod)) {
+ PyErr_Format(PyExc_SystemError,
+ "_PyImport_FixupExtension: module %.200s not loaded", name);
+ return NULL;
+ }
+ dict = PyModule_GetDict(mod);
+ if (dict == NULL)
+ return NULL;
+ copy = PyDict_Copy(dict);
+ if (copy == NULL)
+ return NULL;
+ PyDict_SetItemString(extensions, filename, copy);
+ Py_DECREF(copy);
+ return copy;
}
PyObject *
_PyImport_FindExtension(char *name, char *filename)
{
- PyObject *dict, *mod, *mdict;
- if (extensions == NULL)
- return NULL;
- dict = PyDict_GetItemString(extensions, filename);
- if (dict == NULL)
- return NULL;
- mod = PyImport_AddModule(name);
- if (mod == NULL)
- return NULL;
- mdict = PyModule_GetDict(mod);
- if (mdict == NULL)
- return NULL;
- if (PyDict_Update(mdict, dict))
- return NULL;
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # previously loaded (%s)\n",
- name, filename);
- return mod;
+ PyObject *dict, *mod, *mdict;
+ if (extensions == NULL)
+ return NULL;
+ dict = PyDict_GetItemString(extensions, filename);
+ if (dict == NULL)
+ return NULL;
+ mod = PyImport_AddModule(name);
+ if (mod == NULL)
+ return NULL;
+ mdict = PyModule_GetDict(mod);
+ if (mdict == NULL)
+ return NULL;
+ if (PyDict_Update(mdict, dict))
+ return NULL;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # previously loaded (%s)\n",
+ name, filename);
+ return mod;
}
@@ -603,34 +603,34 @@ _PyImport_FindExtension(char *name, char *filename)
PyObject *
PyImport_AddModule(const char *name)
{
- PyObject *modules = PyImport_GetModuleDict();
- PyObject *m;
+ PyObject *modules = PyImport_GetModuleDict();
+ PyObject *m;
- if ((m = PyDict_GetItemString(modules, name)) != NULL &&
- PyModule_Check(m))
- return m;
- m = PyModule_New(name);
- if (m == NULL)
- return NULL;
- if (PyDict_SetItemString(modules, name, m) != 0) {
- Py_DECREF(m);
- return NULL;
- }
- Py_DECREF(m); /* Yes, it still exists, in modules! */
+ if ((m = PyDict_GetItemString(modules, name)) != NULL &&
+ PyModule_Check(m))
+ return m;
+ m = PyModule_New(name);
+ if (m == NULL)
+ return NULL;
+ if (PyDict_SetItemString(modules, name, m) != 0) {
+ Py_DECREF(m);
+ return NULL;
+ }
+ Py_DECREF(m); /* Yes, it still exists, in modules! */
- return m;
+ return m;
}
/* Remove name from sys.modules, if it's there. */
static void
remove_module(const char *name)
{
- PyObject *modules = PyImport_GetModuleDict();
- if (PyDict_GetItemString(modules, name) == NULL)
- return;
- if (PyDict_DelItemString(modules, name) < 0)
- Py_FatalError("import: deleting existing key in"
- "sys.modules failed");
+ PyObject *modules = PyImport_GetModuleDict();
+ if (PyDict_GetItemString(modules, name) == NULL)
+ return;
+ if (PyDict_DelItemString(modules, name) < 0)
+ Py_FatalError("import: deleting existing key in"
+ "sys.modules failed");
}
/* Execute a code object in a module and return the module object
@@ -643,60 +643,60 @@ remove_module(const char *name)
PyObject *
PyImport_ExecCodeModule(char *name, PyObject *co)
{
- return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
+ return PyImport_ExecCodeModuleEx(name, co, (char *)NULL);
}
PyObject *
PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
{
- PyObject *modules = PyImport_GetModuleDict();
- PyObject *m, *d, *v;
-
- m = PyImport_AddModule(name);
- if (m == NULL)
- return NULL;
- /* If the module is being reloaded, we get the old module back
- and re-use its dict to exec the new code. */
- d = PyModule_GetDict(m);
- if (PyDict_GetItemString(d, "__builtins__") == NULL) {
- if (PyDict_SetItemString(d, "__builtins__",
- PyEval_GetBuiltins()) != 0)
- goto error;
- }
- /* Remember the filename as the __file__ attribute */
- v = NULL;
- if (pathname != NULL) {
- v = PyString_FromString(pathname);
- if (v == NULL)
- PyErr_Clear();
- }
- if (v == NULL) {
- v = ((PyCodeObject *)co)->co_filename;
- Py_INCREF(v);
- }
- if (PyDict_SetItemString(d, "__file__", v) != 0)
- PyErr_Clear(); /* Not important enough to report */
- Py_DECREF(v);
-
- v = PyEval_EvalCode((PyCodeObject *)co, d, d);
- if (v == NULL)
- goto error;
- Py_DECREF(v);
-
- if ((m = PyDict_GetItemString(modules, name)) == NULL) {
- PyErr_Format(PyExc_ImportError,
- "Loaded module %.200s not found in sys.modules",
- name);
- return NULL;
- }
-
- Py_INCREF(m);
-
- return m;
+ PyObject *modules = PyImport_GetModuleDict();
+ PyObject *m, *d, *v;
+
+ m = PyImport_AddModule(name);
+ if (m == NULL)
+ return NULL;
+ /* If the module is being reloaded, we get the old module back
+ and re-use its dict to exec the new code. */
+ d = PyModule_GetDict(m);
+ if (PyDict_GetItemString(d, "__builtins__") == NULL) {
+ if (PyDict_SetItemString(d, "__builtins__",
+ PyEval_GetBuiltins()) != 0)
+ goto error;
+ }
+ /* Remember the filename as the __file__ attribute */
+ v = NULL;
+ if (pathname != NULL) {
+ v = PyString_FromString(pathname);
+ if (v == NULL)
+ PyErr_Clear();
+ }
+ if (v == NULL) {
+ v = ((PyCodeObject *)co)->co_filename;
+ Py_INCREF(v);
+ }
+ if (PyDict_SetItemString(d, "__file__", v) != 0)
+ PyErr_Clear(); /* Not important enough to report */
+ Py_DECREF(v);
+
+ v = PyEval_EvalCode((PyCodeObject *)co, d, d);
+ if (v == NULL)
+ goto error;
+ Py_DECREF(v);
+
+ if ((m = PyDict_GetItemString(modules, name)) == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "Loaded module %.200s not found in sys.modules",
+ name);
+ return NULL;
+ }
+
+ Py_INCREF(m);
+
+ return m;
error:
- remove_module(name);
- return NULL;
+ remove_module(name);
+ return NULL;
}
@@ -708,21 +708,21 @@ PyImport_ExecCodeModuleEx(char *name, PyObject *co, char *pathname)
static char *
make_compiled_pathname(char *pathname, char *buf, size_t buflen)
{
- size_t len = strlen(pathname);
- if (len+2 > buflen)
- return NULL;
+ size_t len = strlen(pathname);
+ if (len+2 > buflen)
+ return NULL;
#ifdef MS_WINDOWS
- /* Treat .pyw as if it were .py. The case of ".pyw" must match
- that used in _PyImport_StandardFiletab. */
- if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
- --len; /* pretend 'w' isn't there */
+ /* Treat .pyw as if it were .py. The case of ".pyw" must match
+ that used in _PyImport_StandardFiletab. */
+ if (len >= 4 && strcmp(&pathname[len-4], ".pyw") == 0)
+ --len; /* pretend 'w' isn't there */
#endif
- memcpy(buf, pathname, len);
- buf[len] = Py_OptimizeFlag ? 'o' : 'c';
- buf[len+1] = '\0';
+ memcpy(buf, pathname, len);
+ buf[len] = Py_OptimizeFlag ? 'o' : 'c';
+ buf[len+1] = '\0';
- return buf;
+ return buf;
}
@@ -736,30 +736,30 @@ make_compiled_pathname(char *pathname, char *buf, size_t buflen)
static FILE *
check_compiled_module(char *pathname, time_t mtime, char *cpathname)
{
- FILE *fp;
- long magic;
- long pyc_mtime;
-
- fp = fopen(cpathname, "rb");
- if (fp == NULL)
- return NULL;
- magic = PyMarshal_ReadLongFromFile(fp);
- if (magic != pyc_magic) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s has bad magic\n", cpathname);
- fclose(fp);
- return NULL;
- }
- pyc_mtime = PyMarshal_ReadLongFromFile(fp);
- if (pyc_mtime != mtime) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s has bad mtime\n", cpathname);
- fclose(fp);
- return NULL;
- }
- if (Py_VerboseFlag)
- PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
- return fp;
+ FILE *fp;
+ long magic;
+ long pyc_mtime;
+
+ fp = fopen(cpathname, "rb");
+ if (fp == NULL)
+ return NULL;
+ magic = PyMarshal_ReadLongFromFile(fp);
+ if (magic != pyc_magic) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s has bad magic\n", cpathname);
+ fclose(fp);
+ return NULL;
+ }
+ pyc_mtime = PyMarshal_ReadLongFromFile(fp);
+ if (pyc_mtime != mtime) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s has bad mtime\n", cpathname);
+ fclose(fp);
+ return NULL;
+ }
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# %s matches %s\n", cpathname, pathname);
+ return fp;
}
@@ -768,18 +768,18 @@ check_compiled_module(char *pathname, time_t mtime, char *cpathname)
static PyCodeObject *
read_compiled_module(char *cpathname, FILE *fp)
{
- PyObject *co;
+ PyObject *co;
- co = PyMarshal_ReadLastObjectFromFile(fp);
- if (co == NULL)
- return NULL;
- if (!PyCode_Check(co)) {
- PyErr_Format(PyExc_ImportError,
- "Non-code object in %.200s", cpathname);
- Py_DECREF(co);
- return NULL;
- }
- return (PyCodeObject *)co;
+ co = PyMarshal_ReadLastObjectFromFile(fp);
+ if (co == NULL)
+ return NULL;
+ if (!PyCode_Check(co)) {
+ PyErr_Format(PyExc_ImportError,
+ "Non-code object in %.200s", cpathname);
+ Py_DECREF(co);
+ return NULL;
+ }
+ return (PyCodeObject *)co;
}
@@ -789,27 +789,27 @@ read_compiled_module(char *cpathname, FILE *fp)
static PyObject *
load_compiled_module(char *name, char *cpathname, FILE *fp)
{
- long magic;
- PyCodeObject *co;
- PyObject *m;
-
- magic = PyMarshal_ReadLongFromFile(fp);
- if (magic != pyc_magic) {
- PyErr_Format(PyExc_ImportError,
- "Bad magic number in %.200s", cpathname);
- return NULL;
- }
- (void) PyMarshal_ReadLongFromFile(fp);
- co = read_compiled_module(cpathname, fp);
- if (co == NULL)
- return NULL;
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # precompiled from %s\n",
- name, cpathname);
- m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
- Py_DECREF(co);
-
- return m;
+ long magic;
+ PyCodeObject *co;
+ PyObject *m;
+
+ magic = PyMarshal_ReadLongFromFile(fp);
+ if (magic != pyc_magic) {
+ PyErr_Format(PyExc_ImportError,
+ "Bad magic number in %.200s", cpathname);
+ return NULL;
+ }
+ (void) PyMarshal_ReadLongFromFile(fp);
+ co = read_compiled_module(cpathname, fp);
+ if (co == NULL)
+ return NULL;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # precompiled from %s\n",
+ name, cpathname);
+ m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, cpathname);
+ Py_DECREF(co);
+
+ return m;
}
/* Parse a source file and return the corresponding code object */
@@ -817,22 +817,22 @@ load_compiled_module(char *name, char *cpathname, FILE *fp)
static PyCodeObject *
parse_source_module(const char *pathname, FILE *fp)
{
- PyCodeObject *co = NULL;
- mod_ty mod;
- PyCompilerFlags flags;
- PyArena *arena = PyArena_New();
- if (arena == NULL)
- return NULL;
+ PyCodeObject *co = NULL;
+ mod_ty mod;
+ PyCompilerFlags flags;
+ PyArena *arena = PyArena_New();
+ if (arena == NULL)
+ return NULL;
- flags.cf_flags = 0;
+ flags.cf_flags = 0;
- mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,
- NULL, arena);
- if (mod) {
- co = PyAST_Compile(mod, pathname, NULL, arena);
- }
- PyArena_Free(arena);
- return co;
+ mod = PyParser_ASTFromFile(fp, pathname, Py_file_input, 0, 0, &flags,
+ NULL, arena);
+ if (mod) {
+ co = PyAST_Compile(mod, pathname, NULL, arena);
+ }
+ PyArena_Free(arena);
+ return co;
}
@@ -842,30 +842,30 @@ static FILE *
open_exclusive(char *filename, mode_t mode)
{
#if defined(O_EXCL)&&defined(O_CREAT)&&defined(O_WRONLY)&&defined(O_TRUNC)
- /* Use O_EXCL to avoid a race condition when another process tries to
- write the same file. When that happens, our open() call fails,
- which is just fine (since it's only a cache).
- XXX If the file exists and is writable but the directory is not
- writable, the file will never be written. Oh well.
- */
- int fd;
- (void) unlink(filename);
- fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
+ /* Use O_EXCL to avoid a race condition when another process tries to
+ write the same file. When that happens, our open() call fails,
+ which is just fine (since it's only a cache).
+ XXX If the file exists and is writable but the directory is not
+ writable, the file will never be written. Oh well.
+ */
+ int fd;
+ (void) unlink(filename);
+ fd = open(filename, O_EXCL|O_CREAT|O_WRONLY|O_TRUNC
#ifdef O_BINARY
- |O_BINARY /* necessary for Windows */
+ |O_BINARY /* necessary for Windows */
#endif
#ifdef __VMS
- , mode, "ctxt=bin", "shr=nil"
+ , mode, "ctxt=bin", "shr=nil"
#else
- , mode
+ , mode
#endif
- );
- if (fd < 0)
- return NULL;
- return fdopen(fd, "wb");
+ );
+ if (fd < 0)
+ return NULL;
+ return fdopen(fd, "wb");
#else
- /* Best we can do -- on Windows this can't happen anyway */
- return fopen(filename, "wb");
+ /* Best we can do -- on Windows this can't happen anyway */
+ return fopen(filename, "wb");
#endif
}
@@ -878,85 +878,85 @@ open_exclusive(char *filename, mode_t mode)
static void
write_compiled_module(PyCodeObject *co, char *cpathname, struct stat *srcstat)
{
- FILE *fp;
- time_t mtime = srcstat->st_mtime;
+ FILE *fp;
+ time_t mtime = srcstat->st_mtime;
#ifdef MS_WINDOWS /* since Windows uses different permissions */
- mode_t mode = srcstat->st_mode & ~S_IEXEC;
+ mode_t mode = srcstat->st_mode & ~S_IEXEC;
#else
- mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
+ mode_t mode = srcstat->st_mode & ~S_IXUSR & ~S_IXGRP & ~S_IXOTH;
#endif
- fp = open_exclusive(cpathname, mode);
- if (fp == NULL) {
- if (Py_VerboseFlag)
- PySys_WriteStderr(
- "# can't create %s\n", cpathname);
- return;
- }
- PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
- /* First write a 0 for mtime */
- PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
- PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
- if (fflush(fp) != 0 || ferror(fp)) {
- if (Py_VerboseFlag)
- PySys_WriteStderr("# can't write %s\n", cpathname);
- /* Don't keep partial file */
- fclose(fp);
- (void) unlink(cpathname);
- return;
- }
- /* Now write the true mtime */
- fseek(fp, 4L, 0);
- assert(mtime < LONG_MAX);
- PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
- fflush(fp);
- fclose(fp);
- if (Py_VerboseFlag)
- PySys_WriteStderr("# wrote %s\n", cpathname);
+ fp = open_exclusive(cpathname, mode);
+ if (fp == NULL) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr(
+ "# can't create %s\n", cpathname);
+ return;
+ }
+ PyMarshal_WriteLongToFile(pyc_magic, fp, Py_MARSHAL_VERSION);
+ /* First write a 0 for mtime */
+ PyMarshal_WriteLongToFile(0L, fp, Py_MARSHAL_VERSION);
+ PyMarshal_WriteObjectToFile((PyObject *)co, fp, Py_MARSHAL_VERSION);
+ if (fflush(fp) != 0 || ferror(fp)) {
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# can't write %s\n", cpathname);
+ /* Don't keep partial file */
+ fclose(fp);
+ (void) unlink(cpathname);
+ return;
+ }
+ /* Now write the true mtime */
+ fseek(fp, 4L, 0);
+ assert(mtime < LONG_MAX);
+ PyMarshal_WriteLongToFile((long)mtime, fp, Py_MARSHAL_VERSION);
+ fflush(fp);
+ fclose(fp);
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("# wrote %s\n", cpathname);
}
static void
update_code_filenames(PyCodeObject *co, PyObject *oldname, PyObject *newname)
{
- PyObject *constants, *tmp;
- Py_ssize_t i, n;
+ PyObject *constants, *tmp;
+ Py_ssize_t i, n;
- if (!_PyString_Eq(co->co_filename, oldname))
- return;
+ if (!_PyString_Eq(co->co_filename, oldname))
+ return;
- tmp = co->co_filename;
- co->co_filename = newname;
- Py_INCREF(co->co_filename);
- Py_DECREF(tmp);
+ tmp = co->co_filename;
+ co->co_filename = newname;
+ Py_INCREF(co->co_filename);
+ Py_DECREF(tmp);
- constants = co->co_consts;
- n = PyTuple_GET_SIZE(constants);
- for (i = 0; i < n; i++) {
- tmp = PyTuple_GET_ITEM(constants, i);
- if (PyCode_Check(tmp))
- update_code_filenames((PyCodeObject *)tmp,
- oldname, newname);
- }
+ constants = co->co_consts;
+ n = PyTuple_GET_SIZE(constants);
+ for (i = 0; i < n; i++) {
+ tmp = PyTuple_GET_ITEM(constants, i);
+ if (PyCode_Check(tmp))
+ update_code_filenames((PyCodeObject *)tmp,
+ oldname, newname);
+ }
}
static int
update_compiled_module(PyCodeObject *co, char *pathname)
{
- PyObject *oldname, *newname;
+ PyObject *oldname, *newname;
- if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)
- return 0;
+ if (strcmp(PyString_AsString(co->co_filename), pathname) == 0)
+ return 0;
- newname = PyString_FromString(pathname);
- if (newname == NULL)
- return -1;
+ newname = PyString_FromString(pathname);
+ if (newname == NULL)
+ return -1;
- oldname = co->co_filename;
- Py_INCREF(oldname);
- update_code_filenames(co, oldname, newname);
- Py_DECREF(oldname);
- Py_DECREF(newname);
- return 1;
+ oldname = co->co_filename;
+ Py_INCREF(oldname);
+ update_code_filenames(co, oldname, newname);
+ Py_DECREF(oldname);
+ Py_DECREF(newname);
+ return 1;
}
/* Load a source module from a given file and return its module
@@ -966,69 +966,69 @@ update_compiled_module(PyCodeObject *co, char *pathname)
static PyObject *
load_source_module(char *name, char *pathname, FILE *fp)
{
- struct stat st;
- FILE *fpc;
- char buf[MAXPATHLEN+1];
- char *cpathname;
- PyCodeObject *co;
- PyObject *m;
-
- if (fstat(fileno(fp), &st) != 0) {
- PyErr_Format(PyExc_RuntimeError,
- "unable to get file status from '%s'",
- pathname);
- return NULL;
- }
+ struct stat st;
+ FILE *fpc;
+ char buf[MAXPATHLEN+1];
+ char *cpathname;
+ PyCodeObject *co;
+ PyObject *m;
+
+ if (fstat(fileno(fp), &st) != 0) {
+ PyErr_Format(PyExc_RuntimeError,
+ "unable to get file status from '%s'",
+ pathname);
+ return NULL;
+ }
#if SIZEOF_TIME_T > 4
- /* Python's .pyc timestamp handling presumes that the timestamp fits
- in 4 bytes. This will be fine until sometime in the year 2038,
- when a 4-byte signed time_t will overflow.
- */
- if (st.st_mtime >> 32) {
- PyErr_SetString(PyExc_OverflowError,
- "modification time overflows a 4 byte field");
- return NULL;
- }
+ /* Python's .pyc timestamp handling presumes that the timestamp fits
+ in 4 bytes. This will be fine until sometime in the year 2038,
+ when a 4-byte signed time_t will overflow.
+ */
+ if (st.st_mtime >> 32) {
+ PyErr_SetString(PyExc_OverflowError,
+ "modification time overflows a 4 byte field");
+ return NULL;
+ }
#endif
- cpathname = make_compiled_pathname(pathname, buf,
- (size_t)MAXPATHLEN + 1);
- if (cpathname != NULL &&
- (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
- co = read_compiled_module(cpathname, fpc);
- fclose(fpc);
- if (co == NULL)
- return NULL;
- if (update_compiled_module(co, pathname) < 0)
- return NULL;
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # precompiled from %s\n",
- name, cpathname);
- pathname = cpathname;
- }
- else {
- co = parse_source_module(pathname, fp);
- if (co == NULL)
- return NULL;
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # from %s\n",
- name, pathname);
- if (cpathname) {
- PyObject *ro = PySys_GetObject("dont_write_bytecode");
- if (ro == NULL || !PyObject_IsTrue(ro))
- write_compiled_module(co, cpathname, &st);
- }
- }
- m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
- Py_DECREF(co);
-
- return m;
+ cpathname = make_compiled_pathname(pathname, buf,
+ (size_t)MAXPATHLEN + 1);
+ if (cpathname != NULL &&
+ (fpc = check_compiled_module(pathname, st.st_mtime, cpathname))) {
+ co = read_compiled_module(cpathname, fpc);
+ fclose(fpc);
+ if (co == NULL)
+ return NULL;
+ if (update_compiled_module(co, pathname) < 0)
+ return NULL;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # precompiled from %s\n",
+ name, cpathname);
+ pathname = cpathname;
+ }
+ else {
+ co = parse_source_module(pathname, fp);
+ if (co == NULL)
+ return NULL;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # from %s\n",
+ name, pathname);
+ if (cpathname) {
+ PyObject *ro = PySys_GetObject("dont_write_bytecode");
+ if (ro == NULL || !PyObject_IsTrue(ro))
+ write_compiled_module(co, cpathname, &st);
+ }
+ }
+ m = PyImport_ExecCodeModuleEx(name, (PyObject *)co, pathname);
+ Py_DECREF(co);
+
+ return m;
}
/* Forward */
static PyObject *load_module(char *, FILE *, char *, int, PyObject *);
static struct filedescr *find_module(char *, char *, PyObject *,
- char *, size_t, FILE **, PyObject **);
+ char *, size_t, FILE **, PyObject **);
static struct _frozen *find_frozen(char *name);
/* Load a package and return its module object WITH INCREMENTED
@@ -1037,54 +1037,54 @@ static struct _frozen *find_frozen(char *name);
static PyObject *
load_package(char *name, char *pathname)
{
- PyObject *m, *d;
- PyObject *file = NULL;
- PyObject *path = NULL;
- int err;
- char buf[MAXPATHLEN+1];
- FILE *fp = NULL;
- struct filedescr *fdp;
-
- m = PyImport_AddModule(name);
- if (m == NULL)
- return NULL;
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # directory %s\n",
- name, pathname);
- d = PyModule_GetDict(m);
- file = PyString_FromString(pathname);
- if (file == NULL)
- goto error;
- path = Py_BuildValue("[O]", file);
- if (path == NULL)
- goto error;
- err = PyDict_SetItemString(d, "__file__", file);
- if (err == 0)
- err = PyDict_SetItemString(d, "__path__", path);
- if (err != 0)
- goto error;
- buf[0] = '\0';
- fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
- if (fdp == NULL) {
- if (PyErr_ExceptionMatches(PyExc_ImportError)) {
- PyErr_Clear();
- Py_INCREF(m);
- }
- else
- m = NULL;
- goto cleanup;
- }
- m = load_module(name, fp, buf, fdp->type, NULL);
- if (fp != NULL)
- fclose(fp);
- goto cleanup;
+ PyObject *m, *d;
+ PyObject *file = NULL;
+ PyObject *path = NULL;
+ int err;
+ char buf[MAXPATHLEN+1];
+ FILE *fp = NULL;
+ struct filedescr *fdp;
+
+ m = PyImport_AddModule(name);
+ if (m == NULL)
+ return NULL;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # directory %s\n",
+ name, pathname);
+ d = PyModule_GetDict(m);
+ file = PyString_FromString(pathname);
+ if (file == NULL)
+ goto error;
+ path = Py_BuildValue("[O]", file);
+ if (path == NULL)
+ goto error;
+ err = PyDict_SetItemString(d, "__file__", file);
+ if (err == 0)
+ err = PyDict_SetItemString(d, "__path__", path);
+ if (err != 0)
+ goto error;
+ buf[0] = '\0';
+ fdp = find_module(name, "__init__", path, buf, sizeof(buf), &fp, NULL);
+ if (fdp == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_ImportError)) {
+ PyErr_Clear();
+ Py_INCREF(m);
+ }
+ else
+ m = NULL;
+ goto cleanup;
+ }
+ m = load_module(name, fp, buf, fdp->type, NULL);
+ if (fp != NULL)
+ fclose(fp);
+ goto cleanup;
error:
- m = NULL;
+ m = NULL;
cleanup:
- Py_XDECREF(path);
- Py_XDECREF(file);
- return m;
+ Py_XDECREF(path);
+ Py_XDECREF(file);
+ return m;
}
@@ -1093,16 +1093,16 @@ load_package(char *name, char *pathname)
static int
is_builtin(char *name)
{
- int i;
- for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
- if (strcmp(name, PyImport_Inittab[i].name) == 0) {
- if (PyImport_Inittab[i].initfunc == NULL)
- return -1;
- else
- return 1;
- }
- }
- return 0;
+ int i;
+ for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
+ if (strcmp(name, PyImport_Inittab[i].name) == 0) {
+ if (PyImport_Inittab[i].initfunc == NULL)
+ return -1;
+ else
+ return 1;
+ }
+ }
+ return 0;
}
@@ -1116,72 +1116,72 @@ is_builtin(char *name)
static PyObject *
get_path_importer(PyObject *path_importer_cache, PyObject *path_hooks,
- PyObject *p)
-{
- PyObject *importer;
- Py_ssize_t j, nhooks;
-
- /* These conditions are the caller's responsibility: */
- assert(PyList_Check(path_hooks));
- assert(PyDict_Check(path_importer_cache));
-
- nhooks = PyList_Size(path_hooks);
- if (nhooks < 0)
- return NULL; /* Shouldn't happen */
-
- importer = PyDict_GetItem(path_importer_cache, p);
- if (importer != NULL)
- return importer;
-
- /* set path_importer_cache[p] to None to avoid recursion */
- if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
- return NULL;
-
- for (j = 0; j < nhooks; j++) {
- PyObject *hook = PyList_GetItem(path_hooks, j);
- if (hook == NULL)
- return NULL;
- importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
- if (importer != NULL)
- break;
-
- if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
- return NULL;
- }
- PyErr_Clear();
- }
- if (importer == NULL) {
- importer = PyObject_CallFunctionObjArgs(
- (PyObject *)&PyNullImporter_Type, p, NULL
- );
- if (importer == NULL) {
- if (PyErr_ExceptionMatches(PyExc_ImportError)) {
- PyErr_Clear();
- return Py_None;
- }
- }
- }
- if (importer != NULL) {
- int err = PyDict_SetItem(path_importer_cache, p, importer);
- Py_DECREF(importer);
- if (err != 0)
- return NULL;
- }
- return importer;
+ PyObject *p)
+{
+ PyObject *importer;
+ Py_ssize_t j, nhooks;
+
+ /* These conditions are the caller's responsibility: */
+ assert(PyList_Check(path_hooks));
+ assert(PyDict_Check(path_importer_cache));
+
+ nhooks = PyList_Size(path_hooks);
+ if (nhooks < 0)
+ return NULL; /* Shouldn't happen */
+
+ importer = PyDict_GetItem(path_importer_cache, p);
+ if (importer != NULL)
+ return importer;
+
+ /* set path_importer_cache[p] to None to avoid recursion */
+ if (PyDict_SetItem(path_importer_cache, p, Py_None) != 0)
+ return NULL;
+
+ for (j = 0; j < nhooks; j++) {
+ PyObject *hook = PyList_GetItem(path_hooks, j);
+ if (hook == NULL)
+ return NULL;
+ importer = PyObject_CallFunctionObjArgs(hook, p, NULL);
+ if (importer != NULL)
+ break;
+
+ if (!PyErr_ExceptionMatches(PyExc_ImportError)) {
+ return NULL;
+ }
+ PyErr_Clear();
+ }
+ if (importer == NULL) {
+ importer = PyObject_CallFunctionObjArgs(
+ (PyObject *)&PyNullImporter_Type, p, NULL
+ );
+ if (importer == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_ImportError)) {
+ PyErr_Clear();
+ return Py_None;
+ }
+ }
+ }
+ if (importer != NULL) {
+ int err = PyDict_SetItem(path_importer_cache, p, importer);
+ Py_DECREF(importer);
+ if (err != 0)
+ return NULL;
+ }
+ return importer;
}
PyAPI_FUNC(PyObject *)
PyImport_GetImporter(PyObject *path) {
- PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
+ PyObject *importer=NULL, *path_importer_cache=NULL, *path_hooks=NULL;
- if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
- if ((path_hooks = PySys_GetObject("path_hooks"))) {
- importer = get_path_importer(path_importer_cache,
- path_hooks, path);
- }
- }
- Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
- return importer;
+ if ((path_importer_cache = PySys_GetObject("path_importer_cache"))) {
+ if ((path_hooks = PySys_GetObject("path_hooks"))) {
+ importer = get_path_importer(path_importer_cache,
+ path_hooks, path);
+ }
+ }
+ Py_XINCREF(importer); /* get_path_importer returns a borrowed reference */
+ return importer;
}
/* Search the path (default sys.path) for a module. Return the
@@ -1190,7 +1190,7 @@ PyImport_GetImporter(PyObject *path) {
#ifdef MS_COREDLL
extern FILE *PyWin_FindRegisteredModule(const char *, struct filedescr **,
- char *, Py_ssize_t);
+ char *, Py_ssize_t);
#endif
static int case_ok(char *, Py_ssize_t, Py_ssize_t, char *);
@@ -1199,319 +1199,319 @@ static struct filedescr importhookdescr = {"", "", IMP_HOOK};
static struct filedescr *
find_module(char *fullname, char *subname, PyObject *path, char *buf,
- size_t buflen, FILE **p_fp, PyObject **p_loader)
-{
- Py_ssize_t i, npath;
- size_t len, namelen;
- struct filedescr *fdp = NULL;
- char *filemode;
- FILE *fp = NULL;
- PyObject *path_hooks, *path_importer_cache;
+ size_t buflen, FILE **p_fp, PyObject **p_loader)
+{
+ Py_ssize_t i, npath;
+ size_t len, namelen;
+ struct filedescr *fdp = NULL;
+ char *filemode;
+ FILE *fp = NULL;
+ PyObject *path_hooks, *path_importer_cache;
#ifndef RISCOS
- struct stat statbuf;
+ struct stat statbuf;
#endif
- static struct filedescr fd_frozen = {"", "", PY_FROZEN};
- static struct filedescr fd_builtin = {"", "", C_BUILTIN};
- static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
- char name[MAXPATHLEN+1];
+ static struct filedescr fd_frozen = {"", "", PY_FROZEN};
+ static struct filedescr fd_builtin = {"", "", C_BUILTIN};
+ static struct filedescr fd_package = {"", "", PKG_DIRECTORY};
+ char name[MAXPATHLEN+1];
#if defined(PYOS_OS2)
- size_t saved_len;
- size_t saved_namelen;
- char *saved_buf = NULL;
+ size_t saved_len;
+ size_t saved_namelen;
+ char *saved_buf = NULL;
#endif
- if (p_loader != NULL)
- *p_loader = NULL;
-
- if (strlen(subname) > MAXPATHLEN) {
- PyErr_SetString(PyExc_OverflowError,
- "module name is too long");
- return NULL;
- }
- strcpy(name, subname);
-
- /* sys.meta_path import hook */
- if (p_loader != NULL) {
- PyObject *meta_path;
-
- meta_path = PySys_GetObject("meta_path");
- if (meta_path == NULL || !PyList_Check(meta_path)) {
- PyErr_SetString(PyExc_ImportError,
- "sys.meta_path must be a list of "
- "import hooks");
- return NULL;
- }
- Py_INCREF(meta_path); /* zap guard */
- npath = PyList_Size(meta_path);
- for (i = 0; i < npath; i++) {
- PyObject *loader;
- PyObject *hook = PyList_GetItem(meta_path, i);
- loader = PyObject_CallMethod(hook, "find_module",
- "sO", fullname,
- path != NULL ?
- path : Py_None);
- if (loader == NULL) {
- Py_DECREF(meta_path);
- return NULL; /* true error */
- }
- if (loader != Py_None) {
- /* a loader was found */
- *p_loader = loader;
- Py_DECREF(meta_path);
- return &importhookdescr;
- }
- Py_DECREF(loader);
- }
- Py_DECREF(meta_path);
- }
-
- if (path != NULL && PyString_Check(path)) {
- /* The only type of submodule allowed inside a "frozen"
- package are other frozen modules or packages. */
- if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
- PyErr_SetString(PyExc_ImportError,
- "full frozen module name too long");
- return NULL;
- }
- strcpy(buf, PyString_AsString(path));
- strcat(buf, ".");
- strcat(buf, name);
- strcpy(name, buf);
- if (find_frozen(name) != NULL) {
- strcpy(buf, name);
- return &fd_frozen;
- }
- PyErr_Format(PyExc_ImportError,
- "No frozen submodule named %.200s", name);
- return NULL;
- }
- if (path == NULL) {
- if (is_builtin(name)) {
- strcpy(buf, name);
- return &fd_builtin;
- }
- if ((find_frozen(name)) != NULL) {
- strcpy(buf, name);
- return &fd_frozen;
- }
+ if (p_loader != NULL)
+ *p_loader = NULL;
+
+ if (strlen(subname) > MAXPATHLEN) {
+ PyErr_SetString(PyExc_OverflowError,
+ "module name is too long");
+ return NULL;
+ }
+ strcpy(name, subname);
+
+ /* sys.meta_path import hook */
+ if (p_loader != NULL) {
+ PyObject *meta_path;
+
+ meta_path = PySys_GetObject("meta_path");
+ if (meta_path == NULL || !PyList_Check(meta_path)) {
+ PyErr_SetString(PyExc_ImportError,
+ "sys.meta_path must be a list of "
+ "import hooks");
+ return NULL;
+ }
+ Py_INCREF(meta_path); /* zap guard */
+ npath = PyList_Size(meta_path);
+ for (i = 0; i < npath; i++) {
+ PyObject *loader;
+ PyObject *hook = PyList_GetItem(meta_path, i);
+ loader = PyObject_CallMethod(hook, "find_module",
+ "sO", fullname,
+ path != NULL ?
+ path : Py_None);
+ if (loader == NULL) {
+ Py_DECREF(meta_path);
+ return NULL; /* true error */
+ }
+ if (loader != Py_None) {
+ /* a loader was found */
+ *p_loader = loader;
+ Py_DECREF(meta_path);
+ return &importhookdescr;
+ }
+ Py_DECREF(loader);
+ }
+ Py_DECREF(meta_path);
+ }
+
+ if (path != NULL && PyString_Check(path)) {
+ /* The only type of submodule allowed inside a "frozen"
+ package are other frozen modules or packages. */
+ if (PyString_Size(path) + 1 + strlen(name) >= (size_t)buflen) {
+ PyErr_SetString(PyExc_ImportError,
+ "full frozen module name too long");
+ return NULL;
+ }
+ strcpy(buf, PyString_AsString(path));
+ strcat(buf, ".");
+ strcat(buf, name);
+ strcpy(name, buf);
+ if (find_frozen(name) != NULL) {
+ strcpy(buf, name);
+ return &fd_frozen;
+ }
+ PyErr_Format(PyExc_ImportError,
+ "No frozen submodule named %.200s", name);
+ return NULL;
+ }
+ if (path == NULL) {
+ if (is_builtin(name)) {
+ strcpy(buf, name);
+ return &fd_builtin;
+ }
+ if ((find_frozen(name)) != NULL) {
+ strcpy(buf, name);
+ return &fd_frozen;
+ }
#ifdef MS_COREDLL
- fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
- if (fp != NULL) {
- *p_fp = fp;
- return fdp;
- }
+ fp = PyWin_FindRegisteredModule(name, &fdp, buf, buflen);
+ if (fp != NULL) {
+ *p_fp = fp;
+ return fdp;
+ }
#endif
- path = PySys_GetObject("path");
- }
- if (path == NULL || !PyList_Check(path)) {
- PyErr_SetString(PyExc_ImportError,
- "sys.path must be a list of directory names");
- return NULL;
- }
-
- path_hooks = PySys_GetObject("path_hooks");
- if (path_hooks == NULL || !PyList_Check(path_hooks)) {
- PyErr_SetString(PyExc_ImportError,
- "sys.path_hooks must be a list of "
- "import hooks");
- return NULL;
- }
- path_importer_cache = PySys_GetObject("path_importer_cache");
- if (path_importer_cache == NULL ||
- !PyDict_Check(path_importer_cache)) {
- PyErr_SetString(PyExc_ImportError,
- "sys.path_importer_cache must be a dict");
- return NULL;
- }
-
- npath = PyList_Size(path);
- namelen = strlen(name);
- for (i = 0; i < npath; i++) {
- PyObject *copy = NULL;
- PyObject *v = PyList_GetItem(path, i);
- if (!v)
- return NULL;
+ path = PySys_GetObject("path");
+ }
+ if (path == NULL || !PyList_Check(path)) {
+ PyErr_SetString(PyExc_ImportError,
+ "sys.path must be a list of directory names");
+ return NULL;
+ }
+
+ path_hooks = PySys_GetObject("path_hooks");
+ if (path_hooks == NULL || !PyList_Check(path_hooks)) {
+ PyErr_SetString(PyExc_ImportError,
+ "sys.path_hooks must be a list of "
+ "import hooks");
+ return NULL;
+ }
+ path_importer_cache = PySys_GetObject("path_importer_cache");
+ if (path_importer_cache == NULL ||
+ !PyDict_Check(path_importer_cache)) {
+ PyErr_SetString(PyExc_ImportError,
+ "sys.path_importer_cache must be a dict");
+ return NULL;
+ }
+
+ npath = PyList_Size(path);
+ namelen = strlen(name);
+ for (i = 0; i < npath; i++) {
+ PyObject *copy = NULL;
+ PyObject *v = PyList_GetItem(path, i);
+ if (!v)
+ return NULL;
#ifdef Py_USING_UNICODE
- if (PyUnicode_Check(v)) {
- copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
- PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
- if (copy == NULL)
- return NULL;
- v = copy;
- }
- else
+ if (PyUnicode_Check(v)) {
+ copy = PyUnicode_Encode(PyUnicode_AS_UNICODE(v),
+ PyUnicode_GET_SIZE(v), Py_FileSystemDefaultEncoding, NULL);
+ if (copy == NULL)
+ return NULL;
+ v = copy;
+ }
+ else
#endif
- if (!PyString_Check(v))
- continue;
- len = PyString_GET_SIZE(v);
- if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
- Py_XDECREF(copy);
- continue; /* Too long */
- }
- strcpy(buf, PyString_AS_STRING(v));
- if (strlen(buf) != len) {
- Py_XDECREF(copy);
- continue; /* v contains '\0' */
- }
-
- /* sys.path_hooks import hook */
- if (p_loader != NULL) {
- PyObject *importer;
-
- importer = get_path_importer(path_importer_cache,
- path_hooks, v);
- if (importer == NULL) {
- Py_XDECREF(copy);
- return NULL;
- }
- /* Note: importer is a borrowed reference */
- if (importer != Py_None) {
- PyObject *loader;
- loader = PyObject_CallMethod(importer,
- "find_module",
- "s", fullname);
- Py_XDECREF(copy);
- if (loader == NULL)
- return NULL; /* error */
- if (loader != Py_None) {
- /* a loader was found */
- *p_loader = loader;
- return &importhookdescr;
- }
- Py_DECREF(loader);
- continue;
- }
- }
- /* no hook was found, use builtin import */
-
- if (len > 0 && buf[len-1] != SEP
+ if (!PyString_Check(v))
+ continue;
+ len = PyString_GET_SIZE(v);
+ if (len + 2 + namelen + MAXSUFFIXSIZE >= buflen) {
+ Py_XDECREF(copy);
+ continue; /* Too long */
+ }
+ strcpy(buf, PyString_AS_STRING(v));
+ if (strlen(buf) != len) {
+ Py_XDECREF(copy);
+ continue; /* v contains '\0' */
+ }
+
+ /* sys.path_hooks import hook */
+ if (p_loader != NULL) {
+ PyObject *importer;
+
+ importer = get_path_importer(path_importer_cache,
+ path_hooks, v);
+ if (importer == NULL) {
+ Py_XDECREF(copy);
+ return NULL;
+ }
+ /* Note: importer is a borrowed reference */
+ if (importer != Py_None) {
+ PyObject *loader;
+ loader = PyObject_CallMethod(importer,
+ "find_module",
+ "s", fullname);
+ Py_XDECREF(copy);
+ if (loader == NULL)
+ return NULL; /* error */
+ if (loader != Py_None) {
+ /* a loader was found */
+ *p_loader = loader;
+ return &importhookdescr;
+ }
+ Py_DECREF(loader);
+ continue;
+ }
+ }
+ /* no hook was found, use builtin import */
+
+ if (len > 0 && buf[len-1] != SEP
#ifdef ALTSEP
- && buf[len-1] != ALTSEP
+ && buf[len-1] != ALTSEP
#endif
- )
- buf[len++] = SEP;
- strcpy(buf+len, name);
- len += namelen;
+ )
+ buf[len++] = SEP;
+ strcpy(buf+len, name);
+ len += namelen;
- /* Check for package import (buf holds a directory name,
- and there's an __init__ module in that directory */
+ /* Check for package import (buf holds a directory name,
+ and there's an __init__ module in that directory */
#ifdef HAVE_STAT
- if (stat(buf, &statbuf) == 0 && /* it exists */
- S_ISDIR(statbuf.st_mode) && /* it's a directory */
- case_ok(buf, len, namelen, name)) { /* case matches */
- if (find_init_module(buf)) { /* and has __init__.py */
- Py_XDECREF(copy);
- return &fd_package;
- }
- else {
- char warnstr[MAXPATHLEN+80];
- sprintf(warnstr, "Not importing directory "
- "'%.*s': missing __init__.py",
- MAXPATHLEN, buf);
- if (PyErr_Warn(PyExc_ImportWarning,
- warnstr)) {
- Py_XDECREF(copy);
- return NULL;
- }
- }
- }
+ if (stat(buf, &statbuf) == 0 && /* it exists */
+ S_ISDIR(statbuf.st_mode) && /* it's a directory */
+ case_ok(buf, len, namelen, name)) { /* case matches */
+ if (find_init_module(buf)) { /* and has __init__.py */
+ Py_XDECREF(copy);
+ return &fd_package;
+ }
+ else {
+ char warnstr[MAXPATHLEN+80];
+ sprintf(warnstr, "Not importing directory "
+ "'%.*s': missing __init__.py",
+ MAXPATHLEN, buf);
+ if (PyErr_Warn(PyExc_ImportWarning,
+ warnstr)) {
+ Py_XDECREF(copy);
+ return NULL;
+ }
+ }
+ }
#else
- /* XXX How are you going to test for directories? */
+ /* XXX How are you going to test for directories? */
#ifdef RISCOS
- if (isdir(buf) &&
- case_ok(buf, len, namelen, name)) {
- if (find_init_module(buf)) {
- Py_XDECREF(copy);
- return &fd_package;
- }
- else {
- char warnstr[MAXPATHLEN+80];
- sprintf(warnstr, "Not importing directory "
- "'%.*s': missing __init__.py",
- MAXPATHLEN, buf);
- if (PyErr_Warn(PyExc_ImportWarning,
- warnstr)) {
- Py_XDECREF(copy);
- return NULL;
- }
- }
+ if (isdir(buf) &&
+ case_ok(buf, len, namelen, name)) {
+ if (find_init_module(buf)) {
+ Py_XDECREF(copy);
+ return &fd_package;
+ }
+ else {
+ char warnstr[MAXPATHLEN+80];
+ sprintf(warnstr, "Not importing directory "
+ "'%.*s': missing __init__.py",
+ MAXPATHLEN, buf);
+ if (PyErr_Warn(PyExc_ImportWarning,
+ warnstr)) {
+ Py_XDECREF(copy);
+ return NULL;
+ }
+ }
#endif
#endif
#if defined(PYOS_OS2)
- /* take a snapshot of the module spec for restoration
- * after the 8 character DLL hackery
- */
- saved_buf = strdup(buf);
- saved_len = len;
- saved_namelen = namelen;
+ /* take a snapshot of the module spec for restoration
+ * after the 8 character DLL hackery
+ */
+ saved_buf = strdup(buf);
+ saved_len = len;
+ saved_namelen = namelen;
#endif /* PYOS_OS2 */
- for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
+ for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
#if defined(PYOS_OS2) && defined(HAVE_DYNAMIC_LOADING)
- /* OS/2 limits DLLs to 8 character names (w/o
- extension)
- * so if the name is longer than that and its a
- * dynamically loaded module we're going to try,
- * truncate the name before trying
- */
- if (strlen(subname) > 8) {
- /* is this an attempt to load a C extension? */
- const struct filedescr *scan;
- scan = _PyImport_DynLoadFiletab;
- while (scan->suffix != NULL) {
- if (!strcmp(scan->suffix, fdp->suffix))
- break;
- else
- scan++;
- }
- if (scan->suffix != NULL) {
- /* yes, so truncate the name */
- namelen = 8;
- len -= strlen(subname) - namelen;
- buf[len] = '\0';
- }
- }
+ /* OS/2 limits DLLs to 8 character names (w/o
+ extension)
+ * so if the name is longer than that and its a
+ * dynamically loaded module we're going to try,
+ * truncate the name before trying
+ */
+ if (strlen(subname) > 8) {
+ /* is this an attempt to load a C extension? */
+ const struct filedescr *scan;
+ scan = _PyImport_DynLoadFiletab;
+ while (scan->suffix != NULL) {
+ if (!strcmp(scan->suffix, fdp->suffix))
+ break;
+ else
+ scan++;
+ }
+ if (scan->suffix != NULL) {
+ /* yes, so truncate the name */
+ namelen = 8;
+ len -= strlen(subname) - namelen;
+ buf[len] = '\0';
+ }
+ }
#endif /* PYOS_OS2 */
- strcpy(buf+len, fdp->suffix);
- if (Py_VerboseFlag > 1)
- PySys_WriteStderr("# trying %s\n", buf);
- filemode = fdp->mode;
- if (filemode[0] == 'U')
- filemode = "r" PY_STDIOTEXTMODE;
- fp = fopen(buf, filemode);
- if (fp != NULL) {
- if (case_ok(buf, len, namelen, name))
- break;
- else { /* continue search */
- fclose(fp);
- fp = NULL;
- }
- }
+ strcpy(buf+len, fdp->suffix);
+ if (Py_VerboseFlag > 1)
+ PySys_WriteStderr("# trying %s\n", buf);
+ filemode = fdp->mode;
+ if (filemode[0] == 'U')
+ filemode = "r" PY_STDIOTEXTMODE;
+ fp = fopen(buf, filemode);
+ if (fp != NULL) {
+ if (case_ok(buf, len, namelen, name))
+ break;
+ else { /* continue search */
+ fclose(fp);
+ fp = NULL;
+ }
+ }
#if defined(PYOS_OS2)
- /* restore the saved snapshot */
- strcpy(buf, saved_buf);
- len = saved_len;
- namelen = saved_namelen;
+ /* restore the saved snapshot */
+ strcpy(buf, saved_buf);
+ len = saved_len;
+ namelen = saved_namelen;
#endif
- }
+ }
#if defined(PYOS_OS2)
- /* don't need/want the module name snapshot anymore */
- if (saved_buf)
- {
- free(saved_buf);
- saved_buf = NULL;
- }
+ /* don't need/want the module name snapshot anymore */
+ if (saved_buf)
+ {
+ free(saved_buf);
+ saved_buf = NULL;
+ }
#endif
- Py_XDECREF(copy);
- if (fp != NULL)
- break;
- }
- if (fp == NULL) {
- PyErr_Format(PyExc_ImportError,
- "No module named %.200s", name);
- return NULL;
- }
- *p_fp = fp;
- return fdp;
+ Py_XDECREF(copy);
+ if (fp != NULL)
+ break;
+ }
+ if (fp == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "No module named %.200s", name);
+ return NULL;
+ }
+ *p_fp = fp;
+ return fdp;
}
/* Helpers for main.c
@@ -1519,15 +1519,15 @@ find_module(char *fullname, char *subname, PyObject *path, char *buf,
*/
struct filedescr *
_PyImport_FindModule(const char *name, PyObject *path, char *buf,
- size_t buflen, FILE **p_fp, PyObject **p_loader)
+ size_t buflen, FILE **p_fp, PyObject **p_loader)
{
- return find_module((char *) name, (char *) name, path,
- buf, buflen, p_fp, p_loader);
+ return find_module((char *) name, (char *) name, path,
+ buf, buflen, p_fp, p_loader);
}
PyAPI_FUNC(int) _PyImport_IsScript(struct filedescr * fd)
{
- return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
+ return fd->type == PY_SOURCE || fd->type == PY_COMPILED;
}
/* case_ok(char* buf, Py_ssize_t len, Py_ssize_t namelen, char* name)
@@ -1586,128 +1586,128 @@ case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
/* MS_WINDOWS */
#if defined(MS_WINDOWS)
- WIN32_FIND_DATA data;
- HANDLE h;
-
- if (Py_GETENV("PYTHONCASEOK") != NULL)
- return 1;
-
- h = FindFirstFile(buf, &data);
- if (h == INVALID_HANDLE_VALUE) {
- PyErr_Format(PyExc_NameError,
- "Can't find file for module %.100s\n(filename %.300s)",
- name, buf);
- return 0;
- }
- FindClose(h);
- return strncmp(data.cFileName, name, namelen) == 0;
+ WIN32_FIND_DATA data;
+ HANDLE h;
+
+ if (Py_GETENV("PYTHONCASEOK") != NULL)
+ return 1;
+
+ h = FindFirstFile(buf, &data);
+ if (h == INVALID_HANDLE_VALUE) {
+ PyErr_Format(PyExc_NameError,
+ "Can't find file for module %.100s\n(filename %.300s)",
+ name, buf);
+ return 0;
+ }
+ FindClose(h);
+ return strncmp(data.cFileName, name, namelen) == 0;
/* DJGPP */
#elif defined(DJGPP)
- struct ffblk ffblk;
- int done;
+ struct ffblk ffblk;
+ int done;
- if (Py_GETENV("PYTHONCASEOK") != NULL)
- return 1;
+ if (Py_GETENV("PYTHONCASEOK") != NULL)
+ return 1;
- done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
- if (done) {
- PyErr_Format(PyExc_NameError,
- "Can't find file for module %.100s\n(filename %.300s)",
- name, buf);
- return 0;
- }
- return strncmp(ffblk.ff_name, name, namelen) == 0;
+ done = findfirst(buf, &ffblk, FA_ARCH|FA_RDONLY|FA_HIDDEN|FA_DIREC);
+ if (done) {
+ PyErr_Format(PyExc_NameError,
+ "Can't find file for module %.100s\n(filename %.300s)",
+ name, buf);
+ return 0;
+ }
+ return strncmp(ffblk.ff_name, name, namelen) == 0;
/* new-fangled macintosh (macosx) or Cygwin */
#elif (defined(__MACH__) && defined(__APPLE__) || defined(__CYGWIN__)) && defined(HAVE_DIRENT_H)
- DIR *dirp;
- struct dirent *dp;
- char dirname[MAXPATHLEN + 1];
- const int dirlen = len - namelen - 1; /* don't want trailing SEP */
-
- if (Py_GETENV("PYTHONCASEOK") != NULL)
- return 1;
-
- /* Copy the dir component into dirname; substitute "." if empty */
- if (dirlen <= 0) {
- dirname[0] = '.';
- dirname[1] = '\0';
- }
- else {
- assert(dirlen <= MAXPATHLEN);
- memcpy(dirname, buf, dirlen);
- dirname[dirlen] = '\0';
- }
- /* Open the directory and search the entries for an exact match. */
- dirp = opendir(dirname);
- if (dirp) {
- char *nameWithExt = buf + len - namelen;
- while ((dp = readdir(dirp)) != NULL) {
- const int thislen =
+ DIR *dirp;
+ struct dirent *dp;
+ char dirname[MAXPATHLEN + 1];
+ const int dirlen = len - namelen - 1; /* don't want trailing SEP */
+
+ if (Py_GETENV("PYTHONCASEOK") != NULL)
+ return 1;
+
+ /* Copy the dir component into dirname; substitute "." if empty */
+ if (dirlen <= 0) {
+ dirname[0] = '.';
+ dirname[1] = '\0';
+ }
+ else {
+ assert(dirlen <= MAXPATHLEN);
+ memcpy(dirname, buf, dirlen);
+ dirname[dirlen] = '\0';
+ }
+ /* Open the directory and search the entries for an exact match. */
+ dirp = opendir(dirname);
+ if (dirp) {
+ char *nameWithExt = buf + len - namelen;
+ while ((dp = readdir(dirp)) != NULL) {
+ const int thislen =
#ifdef _DIRENT_HAVE_D_NAMELEN
- dp->d_namlen;
+ dp->d_namlen;
#else
- strlen(dp->d_name);
+ strlen(dp->d_name);
#endif
- if (thislen >= namelen &&
- strcmp(dp->d_name, nameWithExt) == 0) {
- (void)closedir(dirp);
- return 1; /* Found */
- }
- }
- (void)closedir(dirp);
- }
- return 0 ; /* Not found */
+ if (thislen >= namelen &&
+ strcmp(dp->d_name, nameWithExt) == 0) {
+ (void)closedir(dirp);
+ return 1; /* Found */
+ }
+ }
+ (void)closedir(dirp);
+ }
+ return 0 ; /* Not found */
/* RISC OS */
#elif defined(RISCOS)
- char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
- char buf2[MAXPATHLEN+2];
- char *nameWithExt = buf+len-namelen;
- int canonlen;
- os_error *e;
+ char canon[MAXPATHLEN+1]; /* buffer for the canonical form of the path */
+ char buf2[MAXPATHLEN+2];
+ char *nameWithExt = buf+len-namelen;
+ int canonlen;
+ os_error *e;
- if (Py_GETENV("PYTHONCASEOK") != NULL)
- return 1;
+ if (Py_GETENV("PYTHONCASEOK") != NULL)
+ return 1;
- /* workaround:
- append wildcard, otherwise case of filename wouldn't be touched */
- strcpy(buf2, buf);
- strcat(buf2, "*");
+ /* workaround:
+ append wildcard, otherwise case of filename wouldn't be touched */
+ strcpy(buf2, buf);
+ strcat(buf2, "*");
- e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
- canonlen = MAXPATHLEN+1-canonlen;
- if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
- return 0;
- if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
- return 1; /* match */
+ e = xosfscontrol_canonicalise_path(buf2,canon,0,0,MAXPATHLEN+1,&canonlen);
+ canonlen = MAXPATHLEN+1-canonlen;
+ if (e || canonlen<=0 || canonlen>(MAXPATHLEN+1) )
+ return 0;
+ if (strcmp(nameWithExt, canon+canonlen-strlen(nameWithExt))==0)
+ return 1; /* match */
- return 0;
+ return 0;
/* OS/2 */
#elif defined(PYOS_OS2)
- HDIR hdir = 1;
- ULONG srchcnt = 1;
- FILEFINDBUF3 ffbuf;
- APIRET rc;
-
- if (Py_GETENV("PYTHONCASEOK") != NULL)
- return 1;
-
- rc = DosFindFirst(buf,
- &hdir,
- FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
- &ffbuf, sizeof(ffbuf),
- &srchcnt,
- FIL_STANDARD);
- if (rc != NO_ERROR)
- return 0;
- return strncmp(ffbuf.achName, name, namelen) == 0;
+ HDIR hdir = 1;
+ ULONG srchcnt = 1;
+ FILEFINDBUF3 ffbuf;
+ APIRET rc;
+
+ if (Py_GETENV("PYTHONCASEOK") != NULL)
+ return 1;
+
+ rc = DosFindFirst(buf,
+ &hdir,
+ FILE_READONLY | FILE_HIDDEN | FILE_SYSTEM | FILE_DIRECTORY,
+ &ffbuf, sizeof(ffbuf),
+ &srchcnt,
+ FIL_STANDARD);
+ if (rc != NO_ERROR)
+ return 0;
+ return strncmp(ffbuf.achName, name, namelen) == 0;
/* assuming it's a case-sensitive filesystem, so there's nothing to do! */
#else
- return 1;
+ return 1;
#endif
}
@@ -1718,46 +1718,46 @@ case_ok(char *buf, Py_ssize_t len, Py_ssize_t namelen, char *name)
static int
find_init_module(char *buf)
{
- const size_t save_len = strlen(buf);
- size_t i = save_len;
- char *pname; /* pointer to start of __init__ */
- struct stat statbuf;
-
-/* For calling case_ok(buf, len, namelen, name):
- * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
- * ^ ^ ^ ^
- * |--------------------- buf ---------------------|
- * |------------------- len ------------------|
- * |------ name -------|
- * |----- namelen -----|
+ const size_t save_len = strlen(buf);
+ size_t i = save_len;
+ char *pname; /* pointer to start of __init__ */
+ struct stat statbuf;
+
+/* For calling case_ok(buf, len, namelen, name):
+ * /a/b/c/d/e/f/g/h/i/j/k/some_long_module_name.py\0
+ * ^ ^ ^ ^
+ * |--------------------- buf ---------------------|
+ * |------------------- len ------------------|
+ * |------ name -------|
+ * |----- namelen -----|
*/
- if (save_len + 13 >= MAXPATHLEN)
- return 0;
- buf[i++] = SEP;
- pname = buf + i;
- strcpy(pname, "__init__.py");
- if (stat(buf, &statbuf) == 0) {
- if (case_ok(buf,
- save_len + 9, /* len("/__init__") */
- 8, /* len("__init__") */
- pname)) {
- buf[save_len] = '\0';
- return 1;
- }
- }
- i += strlen(pname);
- strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
- if (stat(buf, &statbuf) == 0) {
- if (case_ok(buf,
- save_len + 9, /* len("/__init__") */
- 8, /* len("__init__") */
- pname)) {
- buf[save_len] = '\0';
- return 1;
- }
- }
- buf[save_len] = '\0';
- return 0;
+ if (save_len + 13 >= MAXPATHLEN)
+ return 0;
+ buf[i++] = SEP;
+ pname = buf + i;
+ strcpy(pname, "__init__.py");
+ if (stat(buf, &statbuf) == 0) {
+ if (case_ok(buf,
+ save_len + 9, /* len("/__init__") */
+ 8, /* len("__init__") */
+ pname)) {
+ buf[save_len] = '\0';
+ return 1;
+ }
+ }
+ i += strlen(pname);
+ strcpy(buf+i, Py_OptimizeFlag ? "o" : "c");
+ if (stat(buf, &statbuf) == 0) {
+ if (case_ok(buf,
+ save_len + 9, /* len("/__init__") */
+ 8, /* len("__init__") */
+ pname)) {
+ buf[save_len] = '\0';
+ return 1;
+ }
+ }
+ buf[save_len] = '\0';
+ return 0;
}
#else
@@ -1765,30 +1765,30 @@ find_init_module(char *buf)
#ifdef RISCOS
static int
find_init_module(buf)
- char *buf;
-{
- int save_len = strlen(buf);
- int i = save_len;
-
- if (save_len + 13 >= MAXPATHLEN)
- return 0;
- buf[i++] = SEP;
- strcpy(buf+i, "__init__/py");
- if (isfile(buf)) {
- buf[save_len] = '\0';
- return 1;
- }
-
- if (Py_OptimizeFlag)
- strcpy(buf+i, "o");
- else
- strcpy(buf+i, "c");
- if (isfile(buf)) {
- buf[save_len] = '\0';
- return 1;
- }
- buf[save_len] = '\0';
- return 0;
+ char *buf;
+{
+ int save_len = strlen(buf);
+ int i = save_len;
+
+ if (save_len + 13 >= MAXPATHLEN)
+ return 0;
+ buf[i++] = SEP;
+ strcpy(buf+i, "__init__/py");
+ if (isfile(buf)) {
+ buf[save_len] = '\0';
+ return 1;
+ }
+
+ if (Py_OptimizeFlag)
+ strcpy(buf+i, "o");
+ else
+ strcpy(buf+i, "c");
+ if (isfile(buf)) {
+ buf[save_len] = '\0';
+ return 1;
+ }
+ buf[save_len] = '\0';
+ return 0;
}
#endif /*RISCOS*/
@@ -1803,93 +1803,93 @@ static int init_builtin(char *); /* Forward */
static PyObject *
load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
{
- PyObject *modules;
- PyObject *m;
- int err;
+ PyObject *modules;
+ PyObject *m;
+ int err;
- /* First check that there's an open file (if we need one) */
- switch (type) {
- case PY_SOURCE:
- case PY_COMPILED:
- if (fp == NULL) {
- PyErr_Format(PyExc_ValueError,
- "file object required for import (type code %d)",
- type);
- return NULL;
- }
- }
+ /* First check that there's an open file (if we need one) */
+ switch (type) {
+ case PY_SOURCE:
+ case PY_COMPILED:
+ if (fp == NULL) {
+ PyErr_Format(PyExc_ValueError,
+ "file object required for import (type code %d)",
+ type);
+ return NULL;
+ }
+ }
- switch (type) {
+ switch (type) {
- case PY_SOURCE:
- m = load_source_module(name, pathname, fp);
- break;
+ case PY_SOURCE:
+ m = load_source_module(name, pathname, fp);
+ break;
- case PY_COMPILED:
- m = load_compiled_module(name, pathname, fp);
- break;
+ case PY_COMPILED:
+ m = load_compiled_module(name, pathname, fp);
+ break;
#ifdef HAVE_DYNAMIC_LOADING
- case C_EXTENSION:
- m = _PyImport_LoadDynamicModule(name, pathname, fp);
- break;
+ case C_EXTENSION:
+ m = _PyImport_LoadDynamicModule(name, pathname, fp);
+ break;
#endif
- case PKG_DIRECTORY:
- m = load_package(name, pathname);
- break;
-
- case C_BUILTIN:
- case PY_FROZEN:
- if (pathname != NULL && pathname[0] != '\0')
- name = pathname;
- if (type == C_BUILTIN)
- err = init_builtin(name);
- else
- err = PyImport_ImportFrozenModule(name);
- if (err < 0)
- return NULL;
- if (err == 0) {
- PyErr_Format(PyExc_ImportError,
- "Purported %s module %.200s not found",
- type == C_BUILTIN ?
- "builtin" : "frozen",
- name);
- return NULL;
- }
- modules = PyImport_GetModuleDict();
- m = PyDict_GetItemString(modules, name);
- if (m == NULL) {
- PyErr_Format(
- PyExc_ImportError,
- "%s module %.200s not properly initialized",
- type == C_BUILTIN ?
- "builtin" : "frozen",
- name);
- return NULL;
- }
- Py_INCREF(m);
- break;
-
- case IMP_HOOK: {
- if (loader == NULL) {
- PyErr_SetString(PyExc_ImportError,
- "import hook without loader");
- return NULL;
- }
- m = PyObject_CallMethod(loader, "load_module", "s", name);
- break;
- }
-
- default:
- PyErr_Format(PyExc_ImportError,
- "Don't know how to import %.200s (type code %d)",
- name, type);
- m = NULL;
-
- }
-
- return m;
+ case PKG_DIRECTORY:
+ m = load_package(name, pathname);
+ break;
+
+ case C_BUILTIN:
+ case PY_FROZEN:
+ if (pathname != NULL && pathname[0] != '\0')
+ name = pathname;
+ if (type == C_BUILTIN)
+ err = init_builtin(name);
+ else
+ err = PyImport_ImportFrozenModule(name);
+ if (err < 0)
+ return NULL;
+ if (err == 0) {
+ PyErr_Format(PyExc_ImportError,
+ "Purported %s module %.200s not found",
+ type == C_BUILTIN ?
+ "builtin" : "frozen",
+ name);
+ return NULL;
+ }
+ modules = PyImport_GetModuleDict();
+ m = PyDict_GetItemString(modules, name);
+ if (m == NULL) {
+ PyErr_Format(
+ PyExc_ImportError,
+ "%s module %.200s not properly initialized",
+ type == C_BUILTIN ?
+ "builtin" : "frozen",
+ name);
+ return NULL;
+ }
+ Py_INCREF(m);
+ break;
+
+ case IMP_HOOK: {
+ if (loader == NULL) {
+ PyErr_SetString(PyExc_ImportError,
+ "import hook without loader");
+ return NULL;
+ }
+ m = PyObject_CallMethod(loader, "load_module", "s", name);
+ break;
+ }
+
+ default:
+ PyErr_Format(PyExc_ImportError,
+ "Don't know how to import %.200s (type code %d)",
+ name, type);
+ m = NULL;
+
+ }
+
+ return m;
}
@@ -1900,30 +1900,30 @@ load_module(char *name, FILE *fp, char *pathname, int type, PyObject *loader)
static int
init_builtin(char *name)
{
- struct _inittab *p;
-
- if (_PyImport_FindExtension(name, name) != NULL)
- return 1;
-
- for (p = PyImport_Inittab; p->name != NULL; p++) {
- if (strcmp(name, p->name) == 0) {
- if (p->initfunc == NULL) {
- PyErr_Format(PyExc_ImportError,
- "Cannot re-init internal module %.200s",
- name);
- return -1;
- }
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # builtin\n", name);
- (*p->initfunc)();
- if (PyErr_Occurred())
- return -1;
- if (_PyImport_FixupExtension(name, name) == NULL)
- return -1;
- return 1;
- }
- }
- return 0;
+ struct _inittab *p;
+
+ if (_PyImport_FindExtension(name, name) != NULL)
+ return 1;
+
+ for (p = PyImport_Inittab; p->name != NULL; p++) {
+ if (strcmp(name, p->name) == 0) {
+ if (p->initfunc == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "Cannot re-init internal module %.200s",
+ name);
+ return -1;
+ }
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # builtin\n", name);
+ (*p->initfunc)();
+ if (PyErr_Occurred())
+ return -1;
+ if (_PyImport_FixupExtension(name, name) == NULL)
+ return -1;
+ return 1;
+ }
+ }
+ return 0;
}
@@ -1932,39 +1932,39 @@ init_builtin(char *name)
static struct _frozen *
find_frozen(char *name)
{
- struct _frozen *p;
+ struct _frozen *p;
- for (p = PyImport_FrozenModules; ; p++) {
- if (p->name == NULL)
- return NULL;
- if (strcmp(p->name, name) == 0)
- break;
- }
- return p;
+ for (p = PyImport_FrozenModules; ; p++) {
+ if (p->name == NULL)
+ return NULL;
+ if (strcmp(p->name, name) == 0)
+ break;
+ }
+ return p;
}
static PyObject *
get_frozen_object(char *name)
{
- struct _frozen *p = find_frozen(name);
- int size;
-
- if (p == NULL) {
- PyErr_Format(PyExc_ImportError,
- "No such frozen object named %.200s",
- name);
- return NULL;
- }
- if (p->code == NULL) {
- PyErr_Format(PyExc_ImportError,
- "Excluded frozen object named %.200s",
- name);
- return NULL;
- }
- size = p->size;
- if (size < 0)
- size = -size;
- return PyMarshal_ReadObjectFromString((char *)p->code, size);
+ struct _frozen *p = find_frozen(name);
+ int size;
+
+ if (p == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "No such frozen object named %.200s",
+ name);
+ return NULL;
+ }
+ if (p->code == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "Excluded frozen object named %.200s",
+ name);
+ return NULL;
+ }
+ size = p->size;
+ if (size < 0)
+ size = -size;
+ return PyMarshal_ReadObjectFromString((char *)p->code, size);
}
/* Initialize a frozen module.
@@ -1975,61 +1975,61 @@ get_frozen_object(char *name)
int
PyImport_ImportFrozenModule(char *name)
{
- struct _frozen *p = find_frozen(name);
- PyObject *co;
- PyObject *m;
- int ispackage;
- int size;
-
- if (p == NULL)
- return 0;
- if (p->code == NULL) {
- PyErr_Format(PyExc_ImportError,
- "Excluded frozen object named %.200s",
- name);
- return -1;
- }
- size = p->size;
- ispackage = (size < 0);
- if (ispackage)
- size = -size;
- if (Py_VerboseFlag)
- PySys_WriteStderr("import %s # frozen%s\n",
- name, ispackage ? " package" : "");
- co = PyMarshal_ReadObjectFromString((char *)p->code, size);
- if (co == NULL)
- return -1;
- if (!PyCode_Check(co)) {
- PyErr_Format(PyExc_TypeError,
- "frozen object %.200s is not a code object",
- name);
- goto err_return;
- }
- if (ispackage) {
- /* Set __path__ to the package name */
- PyObject *d, *s;
- int err;
- m = PyImport_AddModule(name);
- if (m == NULL)
- goto err_return;
- d = PyModule_GetDict(m);
- s = PyString_InternFromString(name);
- if (s == NULL)
- goto err_return;
- err = PyDict_SetItemString(d, "__path__", s);
- Py_DECREF(s);
- if (err != 0)
- goto err_return;
- }
- m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
- if (m == NULL)
- goto err_return;
- Py_DECREF(co);
- Py_DECREF(m);
- return 1;
+ struct _frozen *p = find_frozen(name);
+ PyObject *co;
+ PyObject *m;
+ int ispackage;
+ int size;
+
+ if (p == NULL)
+ return 0;
+ if (p->code == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "Excluded frozen object named %.200s",
+ name);
+ return -1;
+ }
+ size = p->size;
+ ispackage = (size < 0);
+ if (ispackage)
+ size = -size;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr("import %s # frozen%s\n",
+ name, ispackage ? " package" : "");
+ co = PyMarshal_ReadObjectFromString((char *)p->code, size);
+ if (co == NULL)
+ return -1;
+ if (!PyCode_Check(co)) {
+ PyErr_Format(PyExc_TypeError,
+ "frozen object %.200s is not a code object",
+ name);
+ goto err_return;
+ }
+ if (ispackage) {
+ /* Set __path__ to the package name */
+ PyObject *d, *s;
+ int err;
+ m = PyImport_AddModule(name);
+ if (m == NULL)
+ goto err_return;
+ d = PyModule_GetDict(m);
+ s = PyString_InternFromString(name);
+ if (s == NULL)
+ goto err_return;
+ err = PyDict_SetItemString(d, "__path__", s);
+ Py_DECREF(s);
+ if (err != 0)
+ goto err_return;
+ }
+ m = PyImport_ExecCodeModuleEx(name, co, "<frozen>");
+ if (m == NULL)
+ goto err_return;
+ Py_DECREF(co);
+ Py_DECREF(m);
+ return 1;
err_return:
- Py_DECREF(co);
- return -1;
+ Py_DECREF(co);
+ return -1;
}
@@ -2039,15 +2039,15 @@ err_return:
PyObject *
PyImport_ImportModule(const char *name)
{
- PyObject *pname;
- PyObject *result;
+ PyObject *pname;
+ PyObject *result;
- pname = PyString_FromString(name);
- if (pname == NULL)
- return NULL;
- result = PyImport_Import(pname);
- Py_DECREF(pname);
- return result;
+ pname = PyString_FromString(name);
+ if (pname == NULL)
+ return NULL;
+ result = PyImport_Import(pname);
+ Py_DECREF(pname);
+ return result;
}
/* Import a module without blocking
@@ -2062,137 +2062,137 @@ PyImport_ImportModule(const char *name)
PyObject *
PyImport_ImportModuleNoBlock(const char *name)
{
- PyObject *result;
- PyObject *modules;
- long me;
-
- /* Try to get the module from sys.modules[name] */
- modules = PyImport_GetModuleDict();
- if (modules == NULL)
- return NULL;
-
- result = PyDict_GetItemString(modules, name);
- if (result != NULL) {
- Py_INCREF(result);
- return result;
- }
- else {
- PyErr_Clear();
- }
+ PyObject *result;
+ PyObject *modules;
+ long me;
+
+ /* Try to get the module from sys.modules[name] */
+ modules = PyImport_GetModuleDict();
+ if (modules == NULL)
+ return NULL;
+
+ result = PyDict_GetItemString(modules, name);
+ if (result != NULL) {
+ Py_INCREF(result);
+ return result;
+ }
+ else {
+ PyErr_Clear();
+ }
#ifdef WITH_THREAD
- /* check the import lock
- * me might be -1 but I ignore the error here, the lock function
- * takes care of the problem */
- me = PyThread_get_thread_ident();
- if (import_lock_thread == -1 || import_lock_thread == me) {
- /* no thread or me is holding the lock */
- return PyImport_ImportModule(name);
- }
- else {
- PyErr_Format(PyExc_ImportError,
- "Failed to import %.200s because the import lock"
- "is held by another thread.",
- name);
- return NULL;
- }
+ /* check the import lock
+ * me might be -1 but I ignore the error here, the lock function
+ * takes care of the problem */
+ me = PyThread_get_thread_ident();
+ if (import_lock_thread == -1 || import_lock_thread == me) {
+ /* no thread or me is holding the lock */
+ return PyImport_ImportModule(name);
+ }
+ else {
+ PyErr_Format(PyExc_ImportError,
+ "Failed to import %.200s because the import lock"
+ "is held by another thread.",
+ name);
+ return NULL;
+ }
#else
- return PyImport_ImportModule(name);
+ return PyImport_ImportModule(name);
#endif
}
/* Forward declarations for helper routines */
static PyObject *get_parent(PyObject *globals, char *buf,
- Py_ssize_t *p_buflen, int level);
+ Py_ssize_t *p_buflen, int level);
static PyObject *load_next(PyObject *mod, PyObject *altmod,
- char **p_name, char *buf, Py_ssize_t *p_buflen);
+ char **p_name, char *buf, Py_ssize_t *p_buflen);
static int mark_miss(char *name);
static int ensure_fromlist(PyObject *mod, PyObject *fromlist,
- char *buf, Py_ssize_t buflen, int recursive);
+ char *buf, Py_ssize_t buflen, int recursive);
static PyObject * import_submodule(PyObject *mod, char *name, char *fullname);
/* The Magnum Opus of dotted-name import :-) */
static PyObject *
import_module_level(char *name, PyObject *globals, PyObject *locals,
- PyObject *fromlist, int level)
+ PyObject *fromlist, int level)
{
- char buf[MAXPATHLEN+1];
- Py_ssize_t buflen = 0;
- PyObject *parent, *head, *next, *tail;
+ char buf[MAXPATHLEN+1];
+ Py_ssize_t buflen = 0;
+ PyObject *parent, *head, *next, *tail;
- if (strchr(name, '/') != NULL
+ if (strchr(name, '/') != NULL
#ifdef MS_WINDOWS
- || strchr(name, '\\') != NULL
+ || strchr(name, '\\') != NULL
#endif
- ) {
- PyErr_SetString(PyExc_ImportError,
- "Import by filename is not supported.");
- return NULL;
- }
-
- parent = get_parent(globals, buf, &buflen, level);
- if (parent == NULL)
- return NULL;
-
- head = load_next(parent, Py_None, &name, buf, &buflen);
- if (head == NULL)
- return NULL;
-
- tail = head;
- Py_INCREF(tail);
- while (name) {
- next = load_next(tail, tail, &name, buf, &buflen);
- Py_DECREF(tail);
- if (next == NULL) {
- Py_DECREF(head);
- return NULL;
- }
- tail = next;
- }
- if (tail == Py_None) {
- /* If tail is Py_None, both get_parent and load_next found
- an empty module name: someone called __import__("") or
- doctored faulty bytecode */
- Py_DECREF(tail);
- Py_DECREF(head);
- PyErr_SetString(PyExc_ValueError,
- "Empty module name");
- return NULL;
- }
-
- if (fromlist != NULL) {
- if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
- fromlist = NULL;
- }
-
- if (fromlist == NULL) {
- Py_DECREF(tail);
- return head;
- }
-
- Py_DECREF(head);
- if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
- Py_DECREF(tail);
- return NULL;
- }
-
- return tail;
+ ) {
+ PyErr_SetString(PyExc_ImportError,
+ "Import by filename is not supported.");
+ return NULL;
+ }
+
+ parent = get_parent(globals, buf, &buflen, level);
+ if (parent == NULL)
+ return NULL;
+
+ head = load_next(parent, Py_None, &name, buf, &buflen);
+ if (head == NULL)
+ return NULL;
+
+ tail = head;
+ Py_INCREF(tail);
+ while (name) {
+ next = load_next(tail, tail, &name, buf, &buflen);
+ Py_DECREF(tail);
+ if (next == NULL) {
+ Py_DECREF(head);
+ return NULL;
+ }
+ tail = next;
+ }
+ if (tail == Py_None) {
+ /* If tail is Py_None, both get_parent and load_next found
+ an empty module name: someone called __import__("") or
+ doctored faulty bytecode */
+ Py_DECREF(tail);
+ Py_DECREF(head);
+ PyErr_SetString(PyExc_ValueError,
+ "Empty module name");
+ return NULL;
+ }
+
+ if (fromlist != NULL) {
+ if (fromlist == Py_None || !PyObject_IsTrue(fromlist))
+ fromlist = NULL;
+ }
+
+ if (fromlist == NULL) {
+ Py_DECREF(tail);
+ return head;
+ }
+
+ Py_DECREF(head);
+ if (!ensure_fromlist(tail, fromlist, buf, buflen, 0)) {
+ Py_DECREF(tail);
+ return NULL;
+ }
+
+ return tail;
}
PyObject *
PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
- PyObject *fromlist, int level)
+ PyObject *fromlist, int level)
{
- PyObject *result;
- _PyImport_AcquireLock();
- result = import_module_level(name, globals, locals, fromlist, level);
- if (_PyImport_ReleaseLock() < 0) {
- Py_XDECREF(result);
- PyErr_SetString(PyExc_RuntimeError,
- "not holding the import lock");
- return NULL;
- }
- return result;
+ PyObject *result;
+ _PyImport_AcquireLock();
+ result = import_module_level(name, globals, locals, fromlist, level);
+ if (_PyImport_ReleaseLock() < 0) {
+ Py_XDECREF(result);
+ PyErr_SetString(PyExc_RuntimeError,
+ "not holding the import lock");
+ return NULL;
+ }
+ return result;
}
/* Return the package that an import is being performed in. If globals comes
@@ -2209,400 +2209,400 @@ PyImport_ImportModuleLevel(char *name, PyObject *globals, PyObject *locals,
static PyObject *
get_parent(PyObject *globals, char *buf, Py_ssize_t *p_buflen, int level)
{
- static PyObject *namestr = NULL;
- static PyObject *pathstr = NULL;
- static PyObject *pkgstr = NULL;
- PyObject *pkgname, *modname, *modpath, *modules, *parent;
- int orig_level = level;
-
- if (globals == NULL || !PyDict_Check(globals) || !level)
- return Py_None;
-
- if (namestr == NULL) {
- namestr = PyString_InternFromString("__name__");
- if (namestr == NULL)
- return NULL;
- }
- if (pathstr == NULL) {
- pathstr = PyString_InternFromString("__path__");
- if (pathstr == NULL)
- return NULL;
- }
- if (pkgstr == NULL) {
- pkgstr = PyString_InternFromString("__package__");
- if (pkgstr == NULL)
- return NULL;
- }
-
- *buf = '\0';
- *p_buflen = 0;
- pkgname = PyDict_GetItem(globals, pkgstr);
-
- if ((pkgname != NULL) && (pkgname != Py_None)) {
- /* __package__ is set, so use it */
- Py_ssize_t len;
- if (!PyString_Check(pkgname)) {
- PyErr_SetString(PyExc_ValueError,
- "__package__ set to non-string");
- return NULL;
- }
- len = PyString_GET_SIZE(pkgname);
- if (len == 0) {
- if (level > 0) {
- PyErr_SetString(PyExc_ValueError,
- "Attempted relative import in non-package");
- return NULL;
- }
- return Py_None;
- }
- if (len > MAXPATHLEN) {
- PyErr_SetString(PyExc_ValueError,
- "Package name too long");
- return NULL;
- }
- strcpy(buf, PyString_AS_STRING(pkgname));
- } else {
- /* __package__ not set, so figure it out and set it */
- modname = PyDict_GetItem(globals, namestr);
- if (modname == NULL || !PyString_Check(modname))
- return Py_None;
-
- modpath = PyDict_GetItem(globals, pathstr);
- if (modpath != NULL) {
- /* __path__ is set, so modname is already the package name */
- Py_ssize_t len = PyString_GET_SIZE(modname);
- int error;
- if (len > MAXPATHLEN) {
- PyErr_SetString(PyExc_ValueError,
- "Module name too long");
- return NULL;
- }
- strcpy(buf, PyString_AS_STRING(modname));
- error = PyDict_SetItem(globals, pkgstr, modname);
- if (error) {
- PyErr_SetString(PyExc_ValueError,
- "Could not set __package__");
- return NULL;
- }
- } else {
- /* Normal module, so work out the package name if any */
- char *start = PyString_AS_STRING(modname);
- char *lastdot = strrchr(start, '.');
- size_t len;
- int error;
- if (lastdot == NULL && level > 0) {
- PyErr_SetString(PyExc_ValueError,
- "Attempted relative import in non-package");
- return NULL;
- }
- if (lastdot == NULL) {
- error = PyDict_SetItem(globals, pkgstr, Py_None);
- if (error) {
- PyErr_SetString(PyExc_ValueError,
- "Could not set __package__");
- return NULL;
- }
- return Py_None;
- }
- len = lastdot - start;
- if (len >= MAXPATHLEN) {
- PyErr_SetString(PyExc_ValueError,
- "Module name too long");
- return NULL;
- }
- strncpy(buf, start, len);
- buf[len] = '\0';
- pkgname = PyString_FromString(buf);
- if (pkgname == NULL) {
- return NULL;
- }
- error = PyDict_SetItem(globals, pkgstr, pkgname);
- Py_DECREF(pkgname);
- if (error) {
- PyErr_SetString(PyExc_ValueError,
- "Could not set __package__");
- return NULL;
- }
- }
- }
- while (--level > 0) {
- char *dot = strrchr(buf, '.');
- if (dot == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "Attempted relative import beyond "
- "toplevel package");
- return NULL;
- }
- *dot = '\0';
- }
- *p_buflen = strlen(buf);
-
- modules = PyImport_GetModuleDict();
- parent = PyDict_GetItemString(modules, buf);
- if (parent == NULL) {
- if (orig_level < 1) {
- PyObject *err_msg = PyString_FromFormat(
- "Parent module '%.200s' not found "
- "while handling absolute import", buf);
- if (err_msg == NULL) {
- return NULL;
- }
- if (!PyErr_WarnEx(PyExc_RuntimeWarning,
- PyString_AsString(err_msg), 1)) {
- *buf = '\0';
- *p_buflen = 0;
- parent = Py_None;
- }
- Py_DECREF(err_msg);
- } else {
- PyErr_Format(PyExc_SystemError,
- "Parent module '%.200s' not loaded, "
- "cannot perform relative import", buf);
- }
- }
- return parent;
- /* We expect, but can't guarantee, if parent != None, that:
- - parent.__name__ == buf
- - parent.__dict__ is globals
- If this is violated... Who cares? */
+ static PyObject *namestr = NULL;
+ static PyObject *pathstr = NULL;
+ static PyObject *pkgstr = NULL;
+ PyObject *pkgname, *modname, *modpath, *modules, *parent;
+ int orig_level = level;
+
+ if (globals == NULL || !PyDict_Check(globals) || !level)
+ return Py_None;
+
+ if (namestr == NULL) {
+ namestr = PyString_InternFromString("__name__");
+ if (namestr == NULL)
+ return NULL;
+ }
+ if (pathstr == NULL) {
+ pathstr = PyString_InternFromString("__path__");
+ if (pathstr == NULL)
+ return NULL;
+ }
+ if (pkgstr == NULL) {
+ pkgstr = PyString_InternFromString("__package__");
+ if (pkgstr == NULL)
+ return NULL;
+ }
+
+ *buf = '\0';
+ *p_buflen = 0;
+ pkgname = PyDict_GetItem(globals, pkgstr);
+
+ if ((pkgname != NULL) && (pkgname != Py_None)) {
+ /* __package__ is set, so use it */
+ Py_ssize_t len;
+ if (!PyString_Check(pkgname)) {
+ PyErr_SetString(PyExc_ValueError,
+ "__package__ set to non-string");
+ return NULL;
+ }
+ len = PyString_GET_SIZE(pkgname);
+ if (len == 0) {
+ if (level > 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "Attempted relative import in non-package");
+ return NULL;
+ }
+ return Py_None;
+ }
+ if (len > MAXPATHLEN) {
+ PyErr_SetString(PyExc_ValueError,
+ "Package name too long");
+ return NULL;
+ }
+ strcpy(buf, PyString_AS_STRING(pkgname));
+ } else {
+ /* __package__ not set, so figure it out and set it */
+ modname = PyDict_GetItem(globals, namestr);
+ if (modname == NULL || !PyString_Check(modname))
+ return Py_None;
+
+ modpath = PyDict_GetItem(globals, pathstr);
+ if (modpath != NULL) {
+ /* __path__ is set, so modname is already the package name */
+ Py_ssize_t len = PyString_GET_SIZE(modname);
+ int error;
+ if (len > MAXPATHLEN) {
+ PyErr_SetString(PyExc_ValueError,
+ "Module name too long");
+ return NULL;
+ }
+ strcpy(buf, PyString_AS_STRING(modname));
+ error = PyDict_SetItem(globals, pkgstr, modname);
+ if (error) {
+ PyErr_SetString(PyExc_ValueError,
+ "Could not set __package__");
+ return NULL;
+ }
+ } else {
+ /* Normal module, so work out the package name if any */
+ char *start = PyString_AS_STRING(modname);
+ char *lastdot = strrchr(start, '.');
+ size_t len;
+ int error;
+ if (lastdot == NULL && level > 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "Attempted relative import in non-package");
+ return NULL;
+ }
+ if (lastdot == NULL) {
+ error = PyDict_SetItem(globals, pkgstr, Py_None);
+ if (error) {
+ PyErr_SetString(PyExc_ValueError,
+ "Could not set __package__");
+ return NULL;
+ }
+ return Py_None;
+ }
+ len = lastdot - start;
+ if (len >= MAXPATHLEN) {
+ PyErr_SetString(PyExc_ValueError,
+ "Module name too long");
+ return NULL;
+ }
+ strncpy(buf, start, len);
+ buf[len] = '\0';
+ pkgname = PyString_FromString(buf);
+ if (pkgname == NULL) {
+ return NULL;
+ }
+ error = PyDict_SetItem(globals, pkgstr, pkgname);
+ Py_DECREF(pkgname);
+ if (error) {
+ PyErr_SetString(PyExc_ValueError,
+ "Could not set __package__");
+ return NULL;
+ }
+ }
+ }
+ while (--level > 0) {
+ char *dot = strrchr(buf, '.');
+ if (dot == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "Attempted relative import beyond "
+ "toplevel package");
+ return NULL;
+ }
+ *dot = '\0';
+ }
+ *p_buflen = strlen(buf);
+
+ modules = PyImport_GetModuleDict();
+ parent = PyDict_GetItemString(modules, buf);
+ if (parent == NULL) {
+ if (orig_level < 1) {
+ PyObject *err_msg = PyString_FromFormat(
+ "Parent module '%.200s' not found "
+ "while handling absolute import", buf);
+ if (err_msg == NULL) {
+ return NULL;
+ }
+ if (!PyErr_WarnEx(PyExc_RuntimeWarning,
+ PyString_AsString(err_msg), 1)) {
+ *buf = '\0';
+ *p_buflen = 0;
+ parent = Py_None;
+ }
+ Py_DECREF(err_msg);
+ } else {
+ PyErr_Format(PyExc_SystemError,
+ "Parent module '%.200s' not loaded, "
+ "cannot perform relative import", buf);
+ }
+ }
+ return parent;
+ /* We expect, but can't guarantee, if parent != None, that:
+ - parent.__name__ == buf
+ - parent.__dict__ is globals
+ If this is violated... Who cares? */
}
/* altmod is either None or same as mod */
static PyObject *
load_next(PyObject *mod, PyObject *altmod, char **p_name, char *buf,
- Py_ssize_t *p_buflen)
-{
- char *name = *p_name;
- char *dot = strchr(name, '.');
- size_t len;
- char *p;
- PyObject *result;
-
- if (strlen(name) == 0) {
- /* completely empty module name should only happen in
- 'from . import' (or '__import__("")')*/
- Py_INCREF(mod);
- *p_name = NULL;
- return mod;
- }
-
- if (dot == NULL) {
- *p_name = NULL;
- len = strlen(name);
- }
- else {
- *p_name = dot+1;
- len = dot-name;
- }
- if (len == 0) {
- PyErr_SetString(PyExc_ValueError,
- "Empty module name");
- return NULL;
- }
-
- p = buf + *p_buflen;
- if (p != buf)
- *p++ = '.';
- if (p+len-buf >= MAXPATHLEN) {
- PyErr_SetString(PyExc_ValueError,
- "Module name too long");
- return NULL;
- }
- strncpy(p, name, len);
- p[len] = '\0';
- *p_buflen = p+len-buf;
-
- result = import_submodule(mod, p, buf);
- if (result == Py_None && altmod != mod) {
- Py_DECREF(result);
- /* Here, altmod must be None and mod must not be None */
- result = import_submodule(altmod, p, p);
- if (result != NULL && result != Py_None) {
- if (mark_miss(buf) != 0) {
- Py_DECREF(result);
- return NULL;
- }
- strncpy(buf, name, len);
- buf[len] = '\0';
- *p_buflen = len;
- }
- }
- if (result == NULL)
- return NULL;
-
- if (result == Py_None) {
- Py_DECREF(result);
- PyErr_Format(PyExc_ImportError,
- "No module named %.200s", name);
- return NULL;
- }
-
- return result;
+ Py_ssize_t *p_buflen)
+{
+ char *name = *p_name;
+ char *dot = strchr(name, '.');
+ size_t len;
+ char *p;
+ PyObject *result;
+
+ if (strlen(name) == 0) {
+ /* completely empty module name should only happen in
+ 'from . import' (or '__import__("")')*/
+ Py_INCREF(mod);
+ *p_name = NULL;
+ return mod;
+ }
+
+ if (dot == NULL) {
+ *p_name = NULL;
+ len = strlen(name);
+ }
+ else {
+ *p_name = dot+1;
+ len = dot-name;
+ }
+ if (len == 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "Empty module name");
+ return NULL;
+ }
+
+ p = buf + *p_buflen;
+ if (p != buf)
+ *p++ = '.';
+ if (p+len-buf >= MAXPATHLEN) {
+ PyErr_SetString(PyExc_ValueError,
+ "Module name too long");
+ return NULL;
+ }
+ strncpy(p, name, len);
+ p[len] = '\0';
+ *p_buflen = p+len-buf;
+
+ result = import_submodule(mod, p, buf);
+ if (result == Py_None && altmod != mod) {
+ Py_DECREF(result);
+ /* Here, altmod must be None and mod must not be None */
+ result = import_submodule(altmod, p, p);
+ if (result != NULL && result != Py_None) {
+ if (mark_miss(buf) != 0) {
+ Py_DECREF(result);
+ return NULL;
+ }
+ strncpy(buf, name, len);
+ buf[len] = '\0';
+ *p_buflen = len;
+ }
+ }
+ if (result == NULL)
+ return NULL;
+
+ if (result == Py_None) {
+ Py_DECREF(result);
+ PyErr_Format(PyExc_ImportError,
+ "No module named %.200s", name);
+ return NULL;
+ }
+
+ return result;
}
static int
mark_miss(char *name)
{
- PyObject *modules = PyImport_GetModuleDict();
- return PyDict_SetItemString(modules, name, Py_None);
+ PyObject *modules = PyImport_GetModuleDict();
+ return PyDict_SetItemString(modules, name, Py_None);
}
static int
ensure_fromlist(PyObject *mod, PyObject *fromlist, char *buf, Py_ssize_t buflen,
- int recursive)
-{
- int i;
-
- if (!PyObject_HasAttrString(mod, "__path__"))
- return 1;
-
- for (i = 0; ; i++) {
- PyObject *item = PySequence_GetItem(fromlist, i);
- int hasit;
- if (item == NULL) {
- if (PyErr_ExceptionMatches(PyExc_IndexError)) {
- PyErr_Clear();
- return 1;
- }
- return 0;
- }
- if (!PyString_Check(item)) {
- PyErr_SetString(PyExc_TypeError,
- "Item in ``from list'' not a string");
- Py_DECREF(item);
- return 0;
- }
- if (PyString_AS_STRING(item)[0] == '*') {
- PyObject *all;
- Py_DECREF(item);
- /* See if the package defines __all__ */
- if (recursive)
- continue; /* Avoid endless recursion */
- all = PyObject_GetAttrString(mod, "__all__");
- if (all == NULL)
- PyErr_Clear();
- else {
- int ret = ensure_fromlist(mod, all, buf, buflen, 1);
- Py_DECREF(all);
- if (!ret)
- return 0;
- }
- continue;
- }
- hasit = PyObject_HasAttr(mod, item);
- if (!hasit) {
- char *subname = PyString_AS_STRING(item);
- PyObject *submod;
- char *p;
- if (buflen + strlen(subname) >= MAXPATHLEN) {
- PyErr_SetString(PyExc_ValueError,
- "Module name too long");
- Py_DECREF(item);
- return 0;
- }
- p = buf + buflen;
- *p++ = '.';
- strcpy(p, subname);
- submod = import_submodule(mod, subname, buf);
- Py_XDECREF(submod);
- if (submod == NULL) {
- Py_DECREF(item);
- return 0;
- }
- }
- Py_DECREF(item);
- }
-
- /* NOTREACHED */
+ int recursive)
+{
+ int i;
+
+ if (!PyObject_HasAttrString(mod, "__path__"))
+ return 1;
+
+ for (i = 0; ; i++) {
+ PyObject *item = PySequence_GetItem(fromlist, i);
+ int hasit;
+ if (item == NULL) {
+ if (PyErr_ExceptionMatches(PyExc_IndexError)) {
+ PyErr_Clear();
+ return 1;
+ }
+ return 0;
+ }
+ if (!PyString_Check(item)) {
+ PyErr_SetString(PyExc_TypeError,
+ "Item in ``from list'' not a string");
+ Py_DECREF(item);
+ return 0;
+ }
+ if (PyString_AS_STRING(item)[0] == '*') {
+ PyObject *all;
+ Py_DECREF(item);
+ /* See if the package defines __all__ */
+ if (recursive)
+ continue; /* Avoid endless recursion */
+ all = PyObject_GetAttrString(mod, "__all__");
+ if (all == NULL)
+ PyErr_Clear();
+ else {
+ int ret = ensure_fromlist(mod, all, buf, buflen, 1);
+ Py_DECREF(all);
+ if (!ret)
+ return 0;
+ }
+ continue;
+ }
+ hasit = PyObject_HasAttr(mod, item);
+ if (!hasit) {
+ char *subname = PyString_AS_STRING(item);
+ PyObject *submod;
+ char *p;
+ if (buflen + strlen(subname) >= MAXPATHLEN) {
+ PyErr_SetString(PyExc_ValueError,
+ "Module name too long");
+ Py_DECREF(item);
+ return 0;
+ }
+ p = buf + buflen;
+ *p++ = '.';
+ strcpy(p, subname);
+ submod = import_submodule(mod, subname, buf);
+ Py_XDECREF(submod);
+ if (submod == NULL) {
+ Py_DECREF(item);
+ return 0;
+ }
+ }
+ Py_DECREF(item);
+ }
+
+ /* NOTREACHED */
}
static int
add_submodule(PyObject *mod, PyObject *submod, char *fullname, char *subname,
- PyObject *modules)
-{
- if (mod == Py_None)
- return 1;
- /* Irrespective of the success of this load, make a
- reference to it in the parent package module. A copy gets
- saved in the modules dictionary under the full name, so get a
- reference from there, if need be. (The exception is when the
- load failed with a SyntaxError -- then there's no trace in
- sys.modules. In that case, of course, do nothing extra.) */
- if (submod == NULL) {
- submod = PyDict_GetItemString(modules, fullname);
- if (submod == NULL)
- return 1;
- }
- if (PyModule_Check(mod)) {
- /* We can't use setattr here since it can give a
- * spurious warning if the submodule name shadows a
- * builtin name */
- PyObject *dict = PyModule_GetDict(mod);
- if (!dict)
- return 0;
- if (PyDict_SetItemString(dict, subname, submod) < 0)
- return 0;
- }
- else {
- if (PyObject_SetAttrString(mod, subname, submod) < 0)
- return 0;
- }
- return 1;
+ PyObject *modules)
+{
+ if (mod == Py_None)
+ return 1;
+ /* Irrespective of the success of this load, make a
+ reference to it in the parent package module. A copy gets
+ saved in the modules dictionary under the full name, so get a
+ reference from there, if need be. (The exception is when the
+ load failed with a SyntaxError -- then there's no trace in
+ sys.modules. In that case, of course, do nothing extra.) */
+ if (submod == NULL) {
+ submod = PyDict_GetItemString(modules, fullname);
+ if (submod == NULL)
+ return 1;
+ }
+ if (PyModule_Check(mod)) {
+ /* We can't use setattr here since it can give a
+ * spurious warning if the submodule name shadows a
+ * builtin name */
+ PyObject *dict = PyModule_GetDict(mod);
+ if (!dict)
+ return 0;
+ if (PyDict_SetItemString(dict, subname, submod) < 0)
+ return 0;
+ }
+ else {
+ if (PyObject_SetAttrString(mod, subname, submod) < 0)
+ return 0;
+ }
+ return 1;
}
static PyObject *
import_submodule(PyObject *mod, char *subname, char *fullname)
{
- PyObject *modules = PyImport_GetModuleDict();
- PyObject *m = NULL;
-
- /* Require:
- if mod == None: subname == fullname
- else: mod.__name__ + "." + subname == fullname
- */
-
- if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
- Py_INCREF(m);
- }
- else {
- PyObject *path, *loader = NULL;
- char buf[MAXPATHLEN+1];
- struct filedescr *fdp;
- FILE *fp = NULL;
-
- if (mod == Py_None)
- path = NULL;
- else {
- path = PyObject_GetAttrString(mod, "__path__");
- if (path == NULL) {
- PyErr_Clear();
- Py_INCREF(Py_None);
- return Py_None;
- }
- }
-
- buf[0] = '\0';
- fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
- &fp, &loader);
- Py_XDECREF(path);
- if (fdp == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_ImportError))
- return NULL;
- PyErr_Clear();
- Py_INCREF(Py_None);
- return Py_None;
- }
- m = load_module(fullname, fp, buf, fdp->type, loader);
- Py_XDECREF(loader);
- if (fp)
- fclose(fp);
- if (!add_submodule(mod, m, fullname, subname, modules)) {
- Py_XDECREF(m);
- m = NULL;
- }
- }
-
- return m;
+ PyObject *modules = PyImport_GetModuleDict();
+ PyObject *m = NULL;
+
+ /* Require:
+ if mod == None: subname == fullname
+ else: mod.__name__ + "." + subname == fullname
+ */
+
+ if ((m = PyDict_GetItemString(modules, fullname)) != NULL) {
+ Py_INCREF(m);
+ }
+ else {
+ PyObject *path, *loader = NULL;
+ char buf[MAXPATHLEN+1];
+ struct filedescr *fdp;
+ FILE *fp = NULL;
+
+ if (mod == Py_None)
+ path = NULL;
+ else {
+ path = PyObject_GetAttrString(mod, "__path__");
+ if (path == NULL) {
+ PyErr_Clear();
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ }
+
+ buf[0] = '\0';
+ fdp = find_module(fullname, subname, path, buf, MAXPATHLEN+1,
+ &fp, &loader);
+ Py_XDECREF(path);
+ if (fdp == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_ImportError))
+ return NULL;
+ PyErr_Clear();
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ m = load_module(fullname, fp, buf, fdp->type, loader);
+ Py_XDECREF(loader);
+ if (fp)
+ fclose(fp);
+ if (!add_submodule(mod, m, fullname, subname, modules)) {
+ Py_XDECREF(m);
+ m = NULL;
+ }
+ }
+
+ return m;
}
@@ -2612,96 +2612,96 @@ import_submodule(PyObject *mod, char *subname, char *fullname)
PyObject *
PyImport_ReloadModule(PyObject *m)
{
- PyInterpreterState *interp = PyThreadState_Get()->interp;
- PyObject *modules_reloading = interp->modules_reloading;
- PyObject *modules = PyImport_GetModuleDict();
- PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
- char *name, *subname;
- char buf[MAXPATHLEN+1];
- struct filedescr *fdp;
- FILE *fp = NULL;
- PyObject *newm;
-
- if (modules_reloading == NULL) {
- Py_FatalError("PyImport_ReloadModule: "
- "no modules_reloading dictionary!");
- return NULL;
- }
-
- if (m == NULL || !PyModule_Check(m)) {
- PyErr_SetString(PyExc_TypeError,
- "reload() argument must be module");
- return NULL;
- }
- name = PyModule_GetName(m);
- if (name == NULL)
- return NULL;
- if (m != PyDict_GetItemString(modules, name)) {
- PyErr_Format(PyExc_ImportError,
- "reload(): module %.200s not in sys.modules",
- name);
- return NULL;
- }
- existing_m = PyDict_GetItemString(modules_reloading, name);
- if (existing_m != NULL) {
- /* Due to a recursive reload, this module is already
- being reloaded. */
- Py_INCREF(existing_m);
- return existing_m;
- }
- if (PyDict_SetItemString(modules_reloading, name, m) < 0)
- return NULL;
-
- subname = strrchr(name, '.');
- if (subname == NULL)
- subname = name;
- else {
- PyObject *parentname, *parent;
- parentname = PyString_FromStringAndSize(name, (subname-name));
- if (parentname == NULL) {
- imp_modules_reloading_clear();
- return NULL;
- }
- parent = PyDict_GetItem(modules, parentname);
- if (parent == NULL) {
- PyErr_Format(PyExc_ImportError,
- "reload(): parent %.200s not in sys.modules",
- PyString_AS_STRING(parentname));
- Py_DECREF(parentname);
- imp_modules_reloading_clear();
- return NULL;
- }
- Py_DECREF(parentname);
- subname++;
- path = PyObject_GetAttrString(parent, "__path__");
- if (path == NULL)
- PyErr_Clear();
- }
- buf[0] = '\0';
- fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
- Py_XDECREF(path);
-
- if (fdp == NULL) {
- Py_XDECREF(loader);
- imp_modules_reloading_clear();
- return NULL;
- }
-
- newm = load_module(name, fp, buf, fdp->type, loader);
- Py_XDECREF(loader);
-
- if (fp)
- fclose(fp);
- if (newm == NULL) {
- /* load_module probably removed name from modules because of
- * the error. Put back the original module object. We're
- * going to return NULL in this case regardless of whether
- * replacing name succeeds, so the return value is ignored.
- */
- PyDict_SetItemString(modules, name, m);
- }
- imp_modules_reloading_clear();
- return newm;
+ PyInterpreterState *interp = PyThreadState_Get()->interp;
+ PyObject *modules_reloading = interp->modules_reloading;
+ PyObject *modules = PyImport_GetModuleDict();
+ PyObject *path = NULL, *loader = NULL, *existing_m = NULL;
+ char *name, *subname;
+ char buf[MAXPATHLEN+1];
+ struct filedescr *fdp;
+ FILE *fp = NULL;
+ PyObject *newm;
+
+ if (modules_reloading == NULL) {
+ Py_FatalError("PyImport_ReloadModule: "
+ "no modules_reloading dictionary!");
+ return NULL;
+ }
+
+ if (m == NULL || !PyModule_Check(m)) {
+ PyErr_SetString(PyExc_TypeError,
+ "reload() argument must be module");
+ return NULL;
+ }
+ name = PyModule_GetName(m);
+ if (name == NULL)
+ return NULL;
+ if (m != PyDict_GetItemString(modules, name)) {
+ PyErr_Format(PyExc_ImportError,
+ "reload(): module %.200s not in sys.modules",
+ name);
+ return NULL;
+ }
+ existing_m = PyDict_GetItemString(modules_reloading, name);
+ if (existing_m != NULL) {
+ /* Due to a recursive reload, this module is already
+ being reloaded. */
+ Py_INCREF(existing_m);
+ return existing_m;
+ }
+ if (PyDict_SetItemString(modules_reloading, name, m) < 0)
+ return NULL;
+
+ subname = strrchr(name, '.');
+ if (subname == NULL)
+ subname = name;
+ else {
+ PyObject *parentname, *parent;
+ parentname = PyString_FromStringAndSize(name, (subname-name));
+ if (parentname == NULL) {
+ imp_modules_reloading_clear();
+ return NULL;
+ }
+ parent = PyDict_GetItem(modules, parentname);
+ if (parent == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "reload(): parent %.200s not in sys.modules",
+ PyString_AS_STRING(parentname));
+ Py_DECREF(parentname);
+ imp_modules_reloading_clear();
+ return NULL;
+ }
+ Py_DECREF(parentname);
+ subname++;
+ path = PyObject_GetAttrString(parent, "__path__");
+ if (path == NULL)
+ PyErr_Clear();
+ }
+ buf[0] = '\0';
+ fdp = find_module(name, subname, path, buf, MAXPATHLEN+1, &fp, &loader);
+ Py_XDECREF(path);
+
+ if (fdp == NULL) {
+ Py_XDECREF(loader);
+ imp_modules_reloading_clear();
+ return NULL;
+ }
+
+ newm = load_module(name, fp, buf, fdp->type, loader);
+ Py_XDECREF(loader);
+
+ if (fp)
+ fclose(fp);
+ if (newm == NULL) {
+ /* load_module probably removed name from modules because of
+ * the error. Put back the original module object. We're
+ * going to return NULL in this case regardless of whether
+ * replacing name succeeds, so the return value is ignored.
+ */
+ PyDict_SetItemString(modules, name, m);
+ }
+ imp_modules_reloading_clear();
+ return newm;
}
@@ -2717,68 +2717,68 @@ PyImport_ReloadModule(PyObject *m)
PyObject *
PyImport_Import(PyObject *module_name)
{
- static PyObject *silly_list = NULL;
- static PyObject *builtins_str = NULL;
- static PyObject *import_str = NULL;
- PyObject *globals = NULL;
- PyObject *import = NULL;
- PyObject *builtins = NULL;
- PyObject *r = NULL;
-
- /* Initialize constant string objects */
- if (silly_list == NULL) {
- import_str = PyString_InternFromString("__import__");
- if (import_str == NULL)
- return NULL;
- builtins_str = PyString_InternFromString("__builtins__");
- if (builtins_str == NULL)
- return NULL;
- silly_list = Py_BuildValue("[s]", "__doc__");
- if (silly_list == NULL)
- return NULL;
- }
-
- /* Get the builtins from current globals */
- globals = PyEval_GetGlobals();
- if (globals != NULL) {
- Py_INCREF(globals);
- builtins = PyObject_GetItem(globals, builtins_str);
- if (builtins == NULL)
- goto err;
- }
- else {
- /* No globals -- use standard builtins, and fake globals */
- builtins = PyImport_ImportModuleLevel("__builtin__",
- NULL, NULL, NULL, 0);
- if (builtins == NULL)
- return NULL;
- globals = Py_BuildValue("{OO}", builtins_str, builtins);
- if (globals == NULL)
- goto err;
- }
-
- /* Get the __import__ function from the builtins */
- if (PyDict_Check(builtins)) {
- import = PyObject_GetItem(builtins, import_str);
- if (import == NULL)
- PyErr_SetObject(PyExc_KeyError, import_str);
- }
- else
- import = PyObject_GetAttr(builtins, import_str);
- if (import == NULL)
- goto err;
-
- /* Call the __import__ function with the proper argument list
- * Always use absolute import here. */
- r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
- globals, silly_list, 0, NULL);
+ static PyObject *silly_list = NULL;
+ static PyObject *builtins_str = NULL;
+ static PyObject *import_str = NULL;
+ PyObject *globals = NULL;
+ PyObject *import = NULL;
+ PyObject *builtins = NULL;
+ PyObject *r = NULL;
+
+ /* Initialize constant string objects */
+ if (silly_list == NULL) {
+ import_str = PyString_InternFromString("__import__");
+ if (import_str == NULL)
+ return NULL;
+ builtins_str = PyString_InternFromString("__builtins__");
+ if (builtins_str == NULL)
+ return NULL;
+ silly_list = Py_BuildValue("[s]", "__doc__");
+ if (silly_list == NULL)
+ return NULL;
+ }
+
+ /* Get the builtins from current globals */
+ globals = PyEval_GetGlobals();
+ if (globals != NULL) {
+ Py_INCREF(globals);
+ builtins = PyObject_GetItem(globals, builtins_str);
+ if (builtins == NULL)
+ goto err;
+ }
+ else {
+ /* No globals -- use standard builtins, and fake globals */
+ builtins = PyImport_ImportModuleLevel("__builtin__",
+ NULL, NULL, NULL, 0);
+ if (builtins == NULL)
+ return NULL;
+ globals = Py_BuildValue("{OO}", builtins_str, builtins);
+ if (globals == NULL)
+ goto err;
+ }
+
+ /* Get the __import__ function from the builtins */
+ if (PyDict_Check(builtins)) {
+ import = PyObject_GetItem(builtins, import_str);
+ if (import == NULL)
+ PyErr_SetObject(PyExc_KeyError, import_str);
+ }
+ else
+ import = PyObject_GetAttr(builtins, import_str);
+ if (import == NULL)
+ goto err;
+
+ /* Call the __import__ function with the proper argument list
+ * Always use absolute import here. */
+ r = PyObject_CallFunction(import, "OOOOi", module_name, globals,
+ globals, silly_list, 0, NULL);
err:
- Py_XDECREF(globals);
- Py_XDECREF(builtins);
- Py_XDECREF(import);
+ Py_XDECREF(globals);
+ Py_XDECREF(builtins);
+ Py_XDECREF(import);
- return r;
+ return r;
}
@@ -2789,192 +2789,192 @@ PyImport_Import(PyObject *module_name)
static PyObject *
imp_get_magic(PyObject *self, PyObject *noargs)
{
- char buf[4];
+ char buf[4];
- buf[0] = (char) ((pyc_magic >> 0) & 0xff);
- buf[1] = (char) ((pyc_magic >> 8) & 0xff);
- buf[2] = (char) ((pyc_magic >> 16) & 0xff);
- buf[3] = (char) ((pyc_magic >> 24) & 0xff);
+ buf[0] = (char) ((pyc_magic >> 0) & 0xff);
+ buf[1] = (char) ((pyc_magic >> 8) & 0xff);
+ buf[2] = (char) ((pyc_magic >> 16) & 0xff);
+ buf[3] = (char) ((pyc_magic >> 24) & 0xff);
- return PyString_FromStringAndSize(buf, 4);
+ return PyString_FromStringAndSize(buf, 4);
}
static PyObject *
imp_get_suffixes(PyObject *self, PyObject *noargs)
{
- PyObject *list;
- struct filedescr *fdp;
-
- list = PyList_New(0);
- if (list == NULL)
- return NULL;
- for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
- PyObject *item = Py_BuildValue("ssi",
- fdp->suffix, fdp->mode, fdp->type);
- if (item == NULL) {
- Py_DECREF(list);
- return NULL;
- }
- if (PyList_Append(list, item) < 0) {
- Py_DECREF(list);
- Py_DECREF(item);
- return NULL;
- }
- Py_DECREF(item);
- }
- return list;
+ PyObject *list;
+ struct filedescr *fdp;
+
+ list = PyList_New(0);
+ if (list == NULL)
+ return NULL;
+ for (fdp = _PyImport_Filetab; fdp->suffix != NULL; fdp++) {
+ PyObject *item = Py_BuildValue("ssi",
+ fdp->suffix, fdp->mode, fdp->type);
+ if (item == NULL) {
+ Py_DECREF(list);
+ return NULL;
+ }
+ if (PyList_Append(list, item) < 0) {
+ Py_DECREF(list);
+ Py_DECREF(item);
+ return NULL;
+ }
+ Py_DECREF(item);
+ }
+ return list;
}
static PyObject *
call_find_module(char *name, PyObject *path)
{
- extern int fclose(FILE *);
- PyObject *fob, *ret;
- struct filedescr *fdp;
- char pathname[MAXPATHLEN+1];
- FILE *fp = NULL;
-
- pathname[0] = '\0';
- if (path == Py_None)
- path = NULL;
- fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
- if (fdp == NULL)
- return NULL;
- if (fp != NULL) {
- fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
- if (fob == NULL) {
- fclose(fp);
- return NULL;
- }
- }
- else {
- fob = Py_None;
- Py_INCREF(fob);
- }
- ret = Py_BuildValue("Os(ssi)",
- fob, pathname, fdp->suffix, fdp->mode, fdp->type);
- Py_DECREF(fob);
- return ret;
+ extern int fclose(FILE *);
+ PyObject *fob, *ret;
+ struct filedescr *fdp;
+ char pathname[MAXPATHLEN+1];
+ FILE *fp = NULL;
+
+ pathname[0] = '\0';
+ if (path == Py_None)
+ path = NULL;
+ fdp = find_module(NULL, name, path, pathname, MAXPATHLEN+1, &fp, NULL);
+ if (fdp == NULL)
+ return NULL;
+ if (fp != NULL) {
+ fob = PyFile_FromFile(fp, pathname, fdp->mode, fclose);
+ if (fob == NULL) {
+ fclose(fp);
+ return NULL;
+ }
+ }
+ else {
+ fob = Py_None;
+ Py_INCREF(fob);
+ }
+ ret = Py_BuildValue("Os(ssi)",
+ fob, pathname, fdp->suffix, fdp->mode, fdp->type);
+ Py_DECREF(fob);
+ return ret;
}
static PyObject *
imp_find_module(PyObject *self, PyObject *args)
{
- char *name;
- PyObject *path = NULL;
- if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
- return NULL;
- return call_find_module(name, path);
+ char *name;
+ PyObject *path = NULL;
+ if (!PyArg_ParseTuple(args, "s|O:find_module", &name, &path))
+ return NULL;
+ return call_find_module(name, path);
}
static PyObject *
imp_init_builtin(PyObject *self, PyObject *args)
{
- char *name;
- int ret;
- PyObject *m;
- if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
- return NULL;
- ret = init_builtin(name);
- if (ret < 0)
- return NULL;
- if (ret == 0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- m = PyImport_AddModule(name);
- Py_XINCREF(m);
- return m;
+ char *name;
+ int ret;
+ PyObject *m;
+ if (!PyArg_ParseTuple(args, "s:init_builtin", &name))
+ return NULL;
+ ret = init_builtin(name);
+ if (ret < 0)
+ return NULL;
+ if (ret == 0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ m = PyImport_AddModule(name);
+ Py_XINCREF(m);
+ return m;
}
static PyObject *
imp_init_frozen(PyObject *self, PyObject *args)
{
- char *name;
- int ret;
- PyObject *m;
- if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
- return NULL;
- ret = PyImport_ImportFrozenModule(name);
- if (ret < 0)
- return NULL;
- if (ret == 0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- m = PyImport_AddModule(name);
- Py_XINCREF(m);
- return m;
+ char *name;
+ int ret;
+ PyObject *m;
+ if (!PyArg_ParseTuple(args, "s:init_frozen", &name))
+ return NULL;
+ ret = PyImport_ImportFrozenModule(name);
+ if (ret < 0)
+ return NULL;
+ if (ret == 0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ m = PyImport_AddModule(name);
+ Py_XINCREF(m);
+ return m;
}
static PyObject *
imp_get_frozen_object(PyObject *self, PyObject *args)
{
- char *name;
+ char *name;
- if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
- return NULL;
- return get_frozen_object(name);
+ if (!PyArg_ParseTuple(args, "s:get_frozen_object", &name))
+ return NULL;
+ return get_frozen_object(name);
}
static PyObject *
imp_is_builtin(PyObject *self, PyObject *args)
{
- char *name;
- if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
- return NULL;
- return PyInt_FromLong(is_builtin(name));
+ char *name;
+ if (!PyArg_ParseTuple(args, "s:is_builtin", &name))
+ return NULL;
+ return PyInt_FromLong(is_builtin(name));
}
static PyObject *
imp_is_frozen(PyObject *self, PyObject *args)
{
- char *name;
- struct _frozen *p;
- if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
- return NULL;
- p = find_frozen(name);
- return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
+ char *name;
+ struct _frozen *p;
+ if (!PyArg_ParseTuple(args, "s:is_frozen", &name))
+ return NULL;
+ p = find_frozen(name);
+ return PyBool_FromLong((long) (p == NULL ? 0 : p->size));
}
static FILE *
get_file(char *pathname, PyObject *fob, char *mode)
{
- FILE *fp;
- if (fob == NULL) {
- if (mode[0] == 'U')
- mode = "r" PY_STDIOTEXTMODE;
- fp = fopen(pathname, mode);
- if (fp == NULL)
- PyErr_SetFromErrno(PyExc_IOError);
- }
- else {
- fp = PyFile_AsFile(fob);
- if (fp == NULL)
- PyErr_SetString(PyExc_ValueError,
- "bad/closed file object");
- }
- return fp;
+ FILE *fp;
+ if (fob == NULL) {
+ if (mode[0] == 'U')
+ mode = "r" PY_STDIOTEXTMODE;
+ fp = fopen(pathname, mode);
+ if (fp == NULL)
+ PyErr_SetFromErrno(PyExc_IOError);
+ }
+ else {
+ fp = PyFile_AsFile(fob);
+ if (fp == NULL)
+ PyErr_SetString(PyExc_ValueError,
+ "bad/closed file object");
+ }
+ return fp;
}
static PyObject *
imp_load_compiled(PyObject *self, PyObject *args)
{
- char *name;
- char *pathname;
- PyObject *fob = NULL;
- PyObject *m;
- FILE *fp;
- if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
- &PyFile_Type, &fob))
- return NULL;
- fp = get_file(pathname, fob, "rb");
- if (fp == NULL)
- return NULL;
- m = load_compiled_module(name, pathname, fp);
- if (fob == NULL)
- fclose(fp);
- return m;
+ char *name;
+ char *pathname;
+ PyObject *fob = NULL;
+ PyObject *m;
+ FILE *fp;
+ if (!PyArg_ParseTuple(args, "ss|O!:load_compiled", &name, &pathname,
+ &PyFile_Type, &fob))
+ return NULL;
+ fp = get_file(pathname, fob, "rb");
+ if (fp == NULL)
+ return NULL;
+ m = load_compiled_module(name, pathname, fp);
+ if (fob == NULL)
+ fclose(fp);
+ return m;
}
#ifdef HAVE_DYNAMIC_LOADING
@@ -2982,21 +2982,21 @@ imp_load_compiled(PyObject *self, PyObject *args)
static PyObject *
imp_load_dynamic(PyObject *self, PyObject *args)
{
- char *name;
- char *pathname;
- PyObject *fob = NULL;
- PyObject *m;
- FILE *fp = NULL;
- if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
- &PyFile_Type, &fob))
- return NULL;
- if (fob) {
- fp = get_file(pathname, fob, "r");
- if (fp == NULL)
- return NULL;
- }
- m = _PyImport_LoadDynamicModule(name, pathname, fp);
- return m;
+ char *name;
+ char *pathname;
+ PyObject *fob = NULL;
+ PyObject *m;
+ FILE *fp = NULL;
+ if (!PyArg_ParseTuple(args, "ss|O!:load_dynamic", &name, &pathname,
+ &PyFile_Type, &fob))
+ return NULL;
+ if (fob) {
+ fp = get_file(pathname, fob, "r");
+ if (fp == NULL)
+ return NULL;
+ }
+ m = _PyImport_LoadDynamicModule(name, pathname, fp);
+ return m;
}
#endif /* HAVE_DYNAMIC_LOADING */
@@ -3004,87 +3004,87 @@ imp_load_dynamic(PyObject *self, PyObject *args)
static PyObject *
imp_load_source(PyObject *self, PyObject *args)
{
- char *name;
- char *pathname;
- PyObject *fob = NULL;
- PyObject *m;
- FILE *fp;
- if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
- &PyFile_Type, &fob))
- return NULL;
- fp = get_file(pathname, fob, "r");
- if (fp == NULL)
- return NULL;
- m = load_source_module(name, pathname, fp);
- if (fob == NULL)
- fclose(fp);
- return m;
+ char *name;
+ char *pathname;
+ PyObject *fob = NULL;
+ PyObject *m;
+ FILE *fp;
+ if (!PyArg_ParseTuple(args, "ss|O!:load_source", &name, &pathname,
+ &PyFile_Type, &fob))
+ return NULL;
+ fp = get_file(pathname, fob, "r");
+ if (fp == NULL)
+ return NULL;
+ m = load_source_module(name, pathname, fp);
+ if (fob == NULL)
+ fclose(fp);
+ return m;
}
static PyObject *
imp_load_module(PyObject *self, PyObject *args)
{
- char *name;
- PyObject *fob;
- char *pathname;
- char *suffix; /* Unused */
- char *mode;
- int type;
- FILE *fp;
-
- if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
- &name, &fob, &pathname,
- &suffix, &mode, &type))
- return NULL;
- if (*mode) {
- /* Mode must start with 'r' or 'U' and must not contain '+'.
- Implicit in this test is the assumption that the mode
- may contain other modifiers like 'b' or 't'. */
-
- if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
- PyErr_Format(PyExc_ValueError,
- "invalid file open mode %.200s", mode);
- return NULL;
- }
- }
- if (fob == Py_None)
- fp = NULL;
- else {
- if (!PyFile_Check(fob)) {
- PyErr_SetString(PyExc_ValueError,
- "load_module arg#2 should be a file or None");
- return NULL;
- }
- fp = get_file(pathname, fob, mode);
- if (fp == NULL)
- return NULL;
- }
- return load_module(name, fp, pathname, type, NULL);
+ char *name;
+ PyObject *fob;
+ char *pathname;
+ char *suffix; /* Unused */
+ char *mode;
+ int type;
+ FILE *fp;
+
+ if (!PyArg_ParseTuple(args, "sOs(ssi):load_module",
+ &name, &fob, &pathname,
+ &suffix, &mode, &type))
+ return NULL;
+ if (*mode) {
+ /* Mode must start with 'r' or 'U' and must not contain '+'.
+ Implicit in this test is the assumption that the mode
+ may contain other modifiers like 'b' or 't'. */
+
+ if (!(*mode == 'r' || *mode == 'U') || strchr(mode, '+')) {
+ PyErr_Format(PyExc_ValueError,
+ "invalid file open mode %.200s", mode);
+ return NULL;
+ }
+ }
+ if (fob == Py_None)
+ fp = NULL;
+ else {
+ if (!PyFile_Check(fob)) {
+ PyErr_SetString(PyExc_ValueError,
+ "load_module arg#2 should be a file or None");
+ return NULL;
+ }
+ fp = get_file(pathname, fob, mode);
+ if (fp == NULL)
+ return NULL;
+ }
+ return load_module(name, fp, pathname, type, NULL);
}
static PyObject *
imp_load_package(PyObject *self, PyObject *args)
{
- char *name;
- char *pathname;
- if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
- return NULL;
- return load_package(name, pathname);
+ char *name;
+ char *pathname;
+ if (!PyArg_ParseTuple(args, "ss:load_package", &name, &pathname))
+ return NULL;
+ return load_package(name, pathname);
}
static PyObject *
imp_new_module(PyObject *self, PyObject *args)
{
- char *name;
- if (!PyArg_ParseTuple(args, "s:new_module", &name))
- return NULL;
- return PyModule_New(name);
+ char *name;
+ if (!PyArg_ParseTuple(args, "s:new_module", &name))
+ return NULL;
+ return PyModule_New(name);
}
static PyObject *
imp_reload(PyObject *self, PyObject *v)
{
- return PyImport_ReloadModule(v);
+ return PyImport_ReloadModule(v);
}
@@ -3143,40 +3143,40 @@ Release the interpreter's import lock.\n\
On platforms without threads, this function does nothing.");
static PyMethodDef imp_methods[] = {
- {"reload", imp_reload, METH_O, doc_reload},
- {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
- {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
- {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
- {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
- {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
- {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
- {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
- {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
- /* The rest are obsolete */
- {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
- {"init_builtin", imp_init_builtin, METH_VARARGS},
- {"init_frozen", imp_init_frozen, METH_VARARGS},
- {"is_builtin", imp_is_builtin, METH_VARARGS},
- {"is_frozen", imp_is_frozen, METH_VARARGS},
- {"load_compiled", imp_load_compiled, METH_VARARGS},
+ {"reload", imp_reload, METH_O, doc_reload},
+ {"find_module", imp_find_module, METH_VARARGS, doc_find_module},
+ {"get_magic", imp_get_magic, METH_NOARGS, doc_get_magic},
+ {"get_suffixes", imp_get_suffixes, METH_NOARGS, doc_get_suffixes},
+ {"load_module", imp_load_module, METH_VARARGS, doc_load_module},
+ {"new_module", imp_new_module, METH_VARARGS, doc_new_module},
+ {"lock_held", imp_lock_held, METH_NOARGS, doc_lock_held},
+ {"acquire_lock", imp_acquire_lock, METH_NOARGS, doc_acquire_lock},
+ {"release_lock", imp_release_lock, METH_NOARGS, doc_release_lock},
+ /* The rest are obsolete */
+ {"get_frozen_object", imp_get_frozen_object, METH_VARARGS},
+ {"init_builtin", imp_init_builtin, METH_VARARGS},
+ {"init_frozen", imp_init_frozen, METH_VARARGS},
+ {"is_builtin", imp_is_builtin, METH_VARARGS},
+ {"is_frozen", imp_is_frozen, METH_VARARGS},
+ {"load_compiled", imp_load_compiled, METH_VARARGS},
#ifdef HAVE_DYNAMIC_LOADING
- {"load_dynamic", imp_load_dynamic, METH_VARARGS},
+ {"load_dynamic", imp_load_dynamic, METH_VARARGS},
#endif
- {"load_package", imp_load_package, METH_VARARGS},
- {"load_source", imp_load_source, METH_VARARGS},
- {NULL, NULL} /* sentinel */
+ {"load_package", imp_load_package, METH_VARARGS},
+ {"load_source", imp_load_source, METH_VARARGS},
+ {NULL, NULL} /* sentinel */
};
static int
setint(PyObject *d, char *name, int value)
{
- PyObject *v;
- int err;
+ PyObject *v;
+ int err;
- v = PyInt_FromLong((long)value);
- err = PyDict_SetItemString(d, name, v);
- Py_XDECREF(v);
- return err;
+ v = PyInt_FromLong((long)value);
+ err = PyDict_SetItemString(d, name, v);
+ Py_XDECREF(v);
+ return err;
}
typedef struct {
@@ -3186,155 +3186,155 @@ typedef struct {
static int
NullImporter_init(NullImporter *self, PyObject *args, PyObject *kwds)
{
- char *path;
- Py_ssize_t pathlen;
+ char *path;
+ Py_ssize_t pathlen;
- if (!_PyArg_NoKeywords("NullImporter()", kwds))
- return -1;
+ if (!_PyArg_NoKeywords("NullImporter()", kwds))
+ return -1;
- if (!PyArg_ParseTuple(args, "s:NullImporter",
- &path))
- return -1;
+ if (!PyArg_ParseTuple(args, "s:NullImporter",
+ &path))
+ return -1;
- pathlen = strlen(path);
- if (pathlen == 0) {
- PyErr_SetString(PyExc_ImportError, "empty pathname");
- return -1;
- } else {
+ pathlen = strlen(path);
+ if (pathlen == 0) {
+ PyErr_SetString(PyExc_ImportError, "empty pathname");
+ return -1;
+ } else {
#ifndef RISCOS
#ifndef MS_WINDOWS
- struct stat statbuf;
- int rv;
-
- rv = stat(path, &statbuf);
- if (rv == 0) {
- /* it exists */
- if (S_ISDIR(statbuf.st_mode)) {
- /* it's a directory */
- PyErr_SetString(PyExc_ImportError,
- "existing directory");
- return -1;
- }
- }
+ struct stat statbuf;
+ int rv;
+
+ rv = stat(path, &statbuf);
+ if (rv == 0) {
+ /* it exists */
+ if (S_ISDIR(statbuf.st_mode)) {
+ /* it's a directory */
+ PyErr_SetString(PyExc_ImportError,
+ "existing directory");
+ return -1;
+ }
+ }
#else /* MS_WINDOWS */
- DWORD rv;
- /* see issue1293 and issue3677:
- * stat() on Windows doesn't recognise paths like
- * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
- */
- rv = GetFileAttributesA(path);
- if (rv != INVALID_FILE_ATTRIBUTES) {
- /* it exists */
- if (rv & FILE_ATTRIBUTE_DIRECTORY) {
- /* it's a directory */
- PyErr_SetString(PyExc_ImportError,
- "existing directory");
- return -1;
- }
- }
+ DWORD rv;
+ /* see issue1293 and issue3677:
+ * stat() on Windows doesn't recognise paths like
+ * "e:\\shared\\" and "\\\\whiterab-c2znlh\\shared" as dirs.
+ */
+ rv = GetFileAttributesA(path);
+ if (rv != INVALID_FILE_ATTRIBUTES) {
+ /* it exists */
+ if (rv & FILE_ATTRIBUTE_DIRECTORY) {
+ /* it's a directory */
+ PyErr_SetString(PyExc_ImportError,
+ "existing directory");
+ return -1;
+ }
+ }
#endif
#else /* RISCOS */
- if (object_exists(path)) {
- /* it exists */
- if (isdir(path)) {
- /* it's a directory */
- PyErr_SetString(PyExc_ImportError,
- "existing directory");
- return -1;
- }
- }
+ if (object_exists(path)) {
+ /* it exists */
+ if (isdir(path)) {
+ /* it's a directory */
+ PyErr_SetString(PyExc_ImportError,
+ "existing directory");
+ return -1;
+ }
+ }
#endif
- }
- return 0;
+ }
+ return 0;
}
static PyObject *
NullImporter_find_module(NullImporter *self, PyObject *args)
{
- Py_RETURN_NONE;
+ Py_RETURN_NONE;
}
static PyMethodDef NullImporter_methods[] = {
- {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
- "Always return None"
- },
- {NULL} /* Sentinel */
+ {"find_module", (PyCFunction)NullImporter_find_module, METH_VARARGS,
+ "Always return None"
+ },
+ {NULL} /* Sentinel */
};
PyTypeObject PyNullImporter_Type = {
- PyVarObject_HEAD_INIT(NULL, 0)
- "imp.NullImporter", /*tp_name*/
- sizeof(NullImporter), /*tp_basicsize*/
- 0, /*tp_itemsize*/
- 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*/
- 0, /*tp_getattro*/
- 0, /*tp_setattro*/
- 0, /*tp_as_buffer*/
- Py_TPFLAGS_DEFAULT, /*tp_flags*/
- "Null importer object", /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- NullImporter_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 */
- (initproc)NullImporter_init, /* tp_init */
- 0, /* tp_alloc */
- PyType_GenericNew /* tp_new */
+ PyVarObject_HEAD_INIT(NULL, 0)
+ "imp.NullImporter", /*tp_name*/
+ sizeof(NullImporter), /*tp_basicsize*/
+ 0, /*tp_itemsize*/
+ 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*/
+ 0, /*tp_getattro*/
+ 0, /*tp_setattro*/
+ 0, /*tp_as_buffer*/
+ Py_TPFLAGS_DEFAULT, /*tp_flags*/
+ "Null importer object", /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ NullImporter_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 */
+ (initproc)NullImporter_init, /* tp_init */
+ 0, /* tp_alloc */
+ PyType_GenericNew /* tp_new */
};
PyMODINIT_FUNC
initimp(void)
{
- PyObject *m, *d;
-
- if (PyType_Ready(&PyNullImporter_Type) < 0)
- goto failure;
-
- m = Py_InitModule4("imp", imp_methods, doc_imp,
- NULL, PYTHON_API_VERSION);
- if (m == NULL)
- goto failure;
- d = PyModule_GetDict(m);
- if (d == NULL)
- goto failure;
-
- if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
- if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
- if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
- if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
- if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
- if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
- if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
- if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
- if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
- if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
-
- Py_INCREF(&PyNullImporter_Type);
- PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
+ PyObject *m, *d;
+
+ if (PyType_Ready(&PyNullImporter_Type) < 0)
+ goto failure;
+
+ m = Py_InitModule4("imp", imp_methods, doc_imp,
+ NULL, PYTHON_API_VERSION);
+ if (m == NULL)
+ goto failure;
+ d = PyModule_GetDict(m);
+ if (d == NULL)
+ goto failure;
+
+ if (setint(d, "SEARCH_ERROR", SEARCH_ERROR) < 0) goto failure;
+ if (setint(d, "PY_SOURCE", PY_SOURCE) < 0) goto failure;
+ if (setint(d, "PY_COMPILED", PY_COMPILED) < 0) goto failure;
+ if (setint(d, "C_EXTENSION", C_EXTENSION) < 0) goto failure;
+ if (setint(d, "PY_RESOURCE", PY_RESOURCE) < 0) goto failure;
+ if (setint(d, "PKG_DIRECTORY", PKG_DIRECTORY) < 0) goto failure;
+ if (setint(d, "C_BUILTIN", C_BUILTIN) < 0) goto failure;
+ if (setint(d, "PY_FROZEN", PY_FROZEN) < 0) goto failure;
+ if (setint(d, "PY_CODERESOURCE", PY_CODERESOURCE) < 0) goto failure;
+ if (setint(d, "IMP_HOOK", IMP_HOOK) < 0) goto failure;
+
+ Py_INCREF(&PyNullImporter_Type);
+ PyModule_AddObject(m, "NullImporter", (PyObject *)&PyNullImporter_Type);
failure:
- ;
+ ;
}
@@ -3348,31 +3348,31 @@ initimp(void)
int
PyImport_ExtendInittab(struct _inittab *newtab)
{
- static struct _inittab *our_copy = NULL;
- struct _inittab *p;
- int i, n;
+ static struct _inittab *our_copy = NULL;
+ struct _inittab *p;
+ int i, n;
- /* Count the number of entries in both tables */
- for (n = 0; newtab[n].name != NULL; n++)
- ;
- if (n == 0)
- return 0; /* Nothing to do */
- for (i = 0; PyImport_Inittab[i].name != NULL; i++)
- ;
+ /* Count the number of entries in both tables */
+ for (n = 0; newtab[n].name != NULL; n++)
+ ;
+ if (n == 0)
+ return 0; /* Nothing to do */
+ for (i = 0; PyImport_Inittab[i].name != NULL; i++)
+ ;
- /* Allocate new memory for the combined table */
- p = our_copy;
- PyMem_RESIZE(p, struct _inittab, i+n+1);
- if (p == NULL)
- return -1;
+ /* Allocate new memory for the combined table */
+ p = our_copy;
+ PyMem_RESIZE(p, struct _inittab, i+n+1);
+ if (p == NULL)
+ return -1;
- /* Copy the tables into the new memory */
- if (our_copy != PyImport_Inittab)
- memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
- PyImport_Inittab = our_copy = p;
- memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
+ /* Copy the tables into the new memory */
+ if (our_copy != PyImport_Inittab)
+ memcpy(p, PyImport_Inittab, (i+1) * sizeof(struct _inittab));
+ PyImport_Inittab = our_copy = p;
+ memcpy(p+i, newtab, (n+1) * sizeof(struct _inittab));
- return 0;
+ return 0;
}
/* Shorthand to add a single entry given a name and a function */
@@ -3380,14 +3380,14 @@ PyImport_ExtendInittab(struct _inittab *newtab)
int
PyImport_AppendInittab(const char *name, void (*initfunc)(void))
{
- struct _inittab newtab[2];
+ struct _inittab newtab[2];
- memset(newtab, '\0', sizeof newtab);
+ memset(newtab, '\0', sizeof newtab);
- newtab[0].name = (char *)name;
- newtab[0].initfunc = initfunc;
+ newtab[0].name = (char *)name;
+ newtab[0].initfunc = initfunc;
- return PyImport_ExtendInittab(newtab);
+ return PyImport_ExtendInittab(newtab);
}
#ifdef __cplusplus
diff --git a/Python/importdl.c b/Python/importdl.c
index 9c325e4..14c9be8 100644
--- a/Python/importdl.c
+++ b/Python/importdl.c
@@ -13,66 +13,66 @@
#include "importdl.h"
extern dl_funcptr _PyImport_GetDynLoadFunc(const char *name,
- const char *shortname,
- const char *pathname, FILE *fp);
+ const char *shortname,
+ const char *pathname, FILE *fp);
PyObject *
_PyImport_LoadDynamicModule(char *name, char *pathname, FILE *fp)
{
- PyObject *m;
- char *lastdot, *shortname, *packagecontext, *oldcontext;
- dl_funcptr p;
+ PyObject *m;
+ char *lastdot, *shortname, *packagecontext, *oldcontext;
+ dl_funcptr p;
- if ((m = _PyImport_FindExtension(name, pathname)) != NULL) {
- Py_INCREF(m);
- return m;
- }
- lastdot = strrchr(name, '.');
- if (lastdot == NULL) {
- packagecontext = NULL;
- shortname = name;
- }
- else {
- packagecontext = name;
- shortname = lastdot+1;
- }
+ if ((m = _PyImport_FindExtension(name, pathname)) != NULL) {
+ Py_INCREF(m);
+ return m;
+ }
+ lastdot = strrchr(name, '.');
+ if (lastdot == NULL) {
+ packagecontext = NULL;
+ shortname = name;
+ }
+ else {
+ packagecontext = name;
+ shortname = lastdot+1;
+ }
- p = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp);
- if (PyErr_Occurred())
- return NULL;
- if (p == NULL) {
- PyErr_Format(PyExc_ImportError,
- "dynamic module does not define init function (init%.200s)",
- shortname);
- return NULL;
- }
- oldcontext = _Py_PackageContext;
- _Py_PackageContext = packagecontext;
- (*p)();
- _Py_PackageContext = oldcontext;
- if (PyErr_Occurred())
- return NULL;
+ p = _PyImport_GetDynLoadFunc(name, shortname, pathname, fp);
+ if (PyErr_Occurred())
+ return NULL;
+ if (p == NULL) {
+ PyErr_Format(PyExc_ImportError,
+ "dynamic module does not define init function (init%.200s)",
+ shortname);
+ return NULL;
+ }
+ oldcontext = _Py_PackageContext;
+ _Py_PackageContext = packagecontext;
+ (*p)();
+ _Py_PackageContext = oldcontext;
+ if (PyErr_Occurred())
+ return NULL;
- m = PyDict_GetItemString(PyImport_GetModuleDict(), name);
- if (m == NULL) {
- PyErr_SetString(PyExc_SystemError,
- "dynamic module not initialized properly");
- return NULL;
- }
- /* Remember the filename as the __file__ attribute */
- if (PyModule_AddStringConstant(m, "__file__", pathname) < 0)
- PyErr_Clear(); /* Not important enough to report */
+ m = PyDict_GetItemString(PyImport_GetModuleDict(), name);
+ if (m == NULL) {
+ PyErr_SetString(PyExc_SystemError,
+ "dynamic module not initialized properly");
+ return NULL;
+ }
+ /* Remember the filename as the __file__ attribute */
+ if (PyModule_AddStringConstant(m, "__file__", pathname) < 0)
+ PyErr_Clear(); /* Not important enough to report */
- if (_PyImport_FixupExtension(name, pathname) == NULL)
- return NULL;
- if (Py_VerboseFlag)
- PySys_WriteStderr(
- "import %s # dynamically loaded from %s\n",
- name, pathname);
- Py_INCREF(m);
- return m;
+ if (_PyImport_FixupExtension(name, pathname) == NULL)
+ return NULL;
+ if (Py_VerboseFlag)
+ PySys_WriteStderr(
+ "import %s # dynamically loaded from %s\n",
+ name, pathname);
+ Py_INCREF(m);
+ return m;
}
#endif /* HAVE_DYNAMIC_LOADING */
diff --git a/Python/importdl.h b/Python/importdl.h
index 5a2d45c..b4d21be 100644
--- a/Python/importdl.h
+++ b/Python/importdl.h
@@ -8,28 +8,28 @@ extern "C" {
/* Definitions for dynamic loading of extension modules */
enum filetype {
- SEARCH_ERROR,
- PY_SOURCE,
- PY_COMPILED,
- C_EXTENSION,
- PY_RESOURCE, /* Mac only */
- PKG_DIRECTORY,
- C_BUILTIN,
- PY_FROZEN,
- PY_CODERESOURCE, /* Mac only */
- IMP_HOOK
+ SEARCH_ERROR,
+ PY_SOURCE,
+ PY_COMPILED,
+ C_EXTENSION,
+ PY_RESOURCE, /* Mac only */
+ PKG_DIRECTORY,
+ C_BUILTIN,
+ PY_FROZEN,
+ PY_CODERESOURCE, /* Mac only */
+ IMP_HOOK
};
struct filedescr {
- char *suffix;
- char *mode;
- enum filetype type;
+ char *suffix;
+ char *mode;
+ enum filetype type;
};
extern struct filedescr * _PyImport_Filetab;
extern const struct filedescr _PyImport_DynLoadFiletab[];
extern PyObject *_PyImport_LoadDynamicModule(char *name, char *pathname,
- FILE *);
+ FILE *);
/* Max length of module suffix searched for -- accommodates "module.slb" */
#define MAXSUFFIXSIZE 12
diff --git a/Python/mactoolboxglue.c b/Python/mactoolboxglue.c
index 4037d47..92bf3e8 100644
--- a/Python/mactoolboxglue.c
+++ b/Python/mactoolboxglue.c
@@ -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.
@@ -25,45 +25,45 @@ OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#include "Python.h"
#include "pymactoolbox.h"
-#include <arpa/inet.h> /* for ntohl, htonl */
+#include <arpa/inet.h> /* for ntohl, htonl */
/* Like strerror() but for Mac OS error numbers */
char *
PyMac_StrError(int err)
{
- static char buf[256];
- PyObject *m;
- PyObject *rv;
-
- m = PyImport_ImportModuleNoBlock("MacOS");
- if (!m) {
- if (Py_VerboseFlag)
- PyErr_Print();
- PyErr_Clear();
- rv = NULL;
- }
- else {
- rv = PyObject_CallMethod(m, "GetErrorString", "i", err);
- if (!rv)
- PyErr_Clear();
- }
- if (!rv) {
- buf[0] = '\0';
- }
- else {
- char *input = PyString_AsString(rv);
- if (!input) {
- PyErr_Clear();
- buf[0] = '\0';
- } else {
- strncpy(buf, input, sizeof(buf) - 1);
- buf[sizeof(buf) - 1] = '\0';
- }
- Py_DECREF(rv);
- }
- Py_XDECREF(m);
- return buf;
+ static char buf[256];
+ PyObject *m;
+ PyObject *rv;
+
+ m = PyImport_ImportModuleNoBlock("MacOS");
+ if (!m) {
+ if (Py_VerboseFlag)
+ PyErr_Print();
+ PyErr_Clear();
+ rv = NULL;
+ }
+ else {
+ rv = PyObject_CallMethod(m, "GetErrorString", "i", err);
+ if (!rv)
+ PyErr_Clear();
+ }
+ if (!rv) {
+ buf[0] = '\0';
+ }
+ else {
+ char *input = PyString_AsString(rv);
+ if (!input) {
+ PyErr_Clear();
+ buf[0] = '\0';
+ } else {
+ strncpy(buf, input, sizeof(buf) - 1);
+ buf[sizeof(buf) - 1] = '\0';
+ }
+ Py_DECREF(rv);
+ }
+ Py_XDECREF(m);
+ return buf;
}
/* Exception object shared by all Mac specific modules for Mac OS errors */
@@ -73,36 +73,36 @@ PyObject *PyMac_OSErrException;
PyObject *
PyMac_GetOSErrException(void)
{
- if (PyMac_OSErrException == NULL)
- PyMac_OSErrException = PyErr_NewException("MacOS.Error", NULL, NULL);
- return PyMac_OSErrException;
+ if (PyMac_OSErrException == NULL)
+ PyMac_OSErrException = PyErr_NewException("MacOS.Error", NULL, NULL);
+ return PyMac_OSErrException;
}
/* Set a MAC-specific error from errno, and return NULL; return None if no error */
-PyObject *
+PyObject *
PyErr_Mac(PyObject *eobj, int err)
{
- char *msg;
- PyObject *v;
-
- if (err == 0 && !PyErr_Occurred()) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (err == -1 && PyErr_Occurred())
- return NULL;
- msg = PyMac_StrError(err);
- v = Py_BuildValue("(is)", err, msg);
- PyErr_SetObject(eobj, v);
- Py_DECREF(v);
- return NULL;
+ char *msg;
+ PyObject *v;
+
+ if (err == 0 && !PyErr_Occurred()) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (err == -1 && PyErr_Occurred())
+ return NULL;
+ msg = PyMac_StrError(err);
+ v = Py_BuildValue("(is)", err, msg);
+ PyErr_SetObject(eobj, v);
+ Py_DECREF(v);
+ return NULL;
}
/* Call PyErr_Mac with PyMac_OSErrException */
PyObject *
PyMac_Error(OSErr err)
{
- return PyErr_Mac(PyMac_GetOSErrException(), err);
+ return PyErr_Mac(PyMac_GetOSErrException(), err);
}
@@ -110,49 +110,49 @@ PyMac_Error(OSErr err)
OSErr
PyMac_GetFullPathname(FSSpec *fss, char *path, int len)
{
- PyObject *fs, *exc;
- PyObject *rv = NULL;
- char *input;
- OSErr err = noErr;
+ PyObject *fs, *exc;
+ PyObject *rv = NULL;
+ char *input;
+ OSErr err = noErr;
- *path = '\0';
+ *path = '\0';
- fs = PyMac_BuildFSSpec(fss);
- if (!fs)
- goto error;
+ fs = PyMac_BuildFSSpec(fss);
+ if (!fs)
+ goto error;
- rv = PyObject_CallMethod(fs, "as_pathname", "");
- if (!rv)
- goto error;
+ rv = PyObject_CallMethod(fs, "as_pathname", "");
+ if (!rv)
+ goto error;
- input = PyString_AsString(rv);
- if (!input)
- goto error;
+ input = PyString_AsString(rv);
+ if (!input)
+ goto error;
- strncpy(path, input, len - 1);
- path[len - 1] = '\0';
+ strncpy(path, input, len - 1);
+ path[len - 1] = '\0';
- Py_XDECREF(rv);
- Py_XDECREF(fs);
- return err;
+ Py_XDECREF(rv);
+ Py_XDECREF(fs);
+ return err;
error:
- exc = PyErr_Occurred();
- if (exc && PyErr_GivenExceptionMatches(exc,
- PyMac_GetOSErrException())) {
- PyObject *args = PyObject_GetAttrString(exc, "args");
- if (args) {
- char *ignore;
- PyArg_ParseTuple(args, "is", &err, &ignore);
- Py_XDECREF(args);
- }
- }
- if (err == noErr)
- err = -1;
- PyErr_Clear();
- Py_XDECREF(rv);
- Py_XDECREF(fs);
- return err;
+ exc = PyErr_Occurred();
+ if (exc && PyErr_GivenExceptionMatches(exc,
+ PyMac_GetOSErrException())) {
+ PyObject *args = PyObject_GetAttrString(exc, "args");
+ if (args) {
+ char *ignore;
+ PyArg_ParseTuple(args, "is", &err, &ignore);
+ Py_XDECREF(args);
+ }
+ }
+ if (err == noErr)
+ err = -1;
+ PyErr_Clear();
+ Py_XDECREF(rv);
+ Py_XDECREF(fs);
+ return err;
}
#endif /* !__LP64__ */
@@ -160,30 +160,30 @@ PyMac_GetFullPathname(FSSpec *fss, char *path, int len)
int
PyMac_GetOSType(PyObject *v, OSType *pr)
{
- uint32_t tmp;
- if (!PyString_Check(v) || PyString_Size(v) != 4) {
- PyErr_SetString(PyExc_TypeError,
- "OSType arg must be string of 4 chars");
- return 0;
- }
- memcpy((char *)&tmp, PyString_AsString(v), 4);
- *pr = (OSType)ntohl(tmp);
- return 1;
+ uint32_t tmp;
+ if (!PyString_Check(v) || PyString_Size(v) != 4) {
+ PyErr_SetString(PyExc_TypeError,
+ "OSType arg must be string of 4 chars");
+ return 0;
+ }
+ memcpy((char *)&tmp, PyString_AsString(v), 4);
+ *pr = (OSType)ntohl(tmp);
+ return 1;
}
/* Convert an OSType value to a 4-char string object */
PyObject *
PyMac_BuildOSType(OSType t)
{
- uint32_t tmp = htonl((uint32_t)t);
- return PyString_FromStringAndSize((char *)&tmp, 4);
+ uint32_t tmp = htonl((uint32_t)t);
+ return PyString_FromStringAndSize((char *)&tmp, 4);
}
/* Convert an NumVersion value to a 4-element tuple */
PyObject *
PyMac_BuildNumVersion(NumVersion t)
{
- return Py_BuildValue("(hhhh)", t.majorRev, t.minorAndBugRev, t.stage, t.nonRelRev);
+ return Py_BuildValue("(hhhh)", t.majorRev, t.minorAndBugRev, t.stage, t.nonRelRev);
}
@@ -191,36 +191,36 @@ PyMac_BuildNumVersion(NumVersion t)
int
PyMac_GetStr255(PyObject *v, Str255 pbuf)
{
- int len;
- if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
- PyErr_SetString(PyExc_TypeError,
- "Str255 arg must be string of at most 255 chars");
- return 0;
- }
- pbuf[0] = len;
- memcpy((char *)(pbuf+1), PyString_AsString(v), len);
- return 1;
+ int len;
+ if (!PyString_Check(v) || (len = PyString_Size(v)) > 255) {
+ PyErr_SetString(PyExc_TypeError,
+ "Str255 arg must be string of at most 255 chars");
+ return 0;
+ }
+ pbuf[0] = len;
+ memcpy((char *)(pbuf+1), PyString_AsString(v), len);
+ return 1;
}
/* Convert a Str255 to a Python string object */
PyObject *
PyMac_BuildStr255(Str255 s)
{
- if ( s == NULL ) {
- PyErr_SetString(PyExc_SystemError, "Str255 pointer is NULL");
- return NULL;
- }
- return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
+ if ( s == NULL ) {
+ PyErr_SetString(PyExc_SystemError, "Str255 pointer is NULL");
+ return NULL;
+ }
+ return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
}
PyObject *
PyMac_BuildOptStr255(Str255 s)
{
- if ( s == NULL ) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
+ if ( s == NULL ) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ return PyString_FromStringAndSize((char *)&s[1], (int)s[0]);
}
@@ -232,14 +232,14 @@ PyMac_BuildOptStr255(Str255 s)
int
PyMac_GetRect(PyObject *v, Rect *r)
{
- return PyArg_Parse(v, "(hhhh)", &r->left, &r->top, &r->right, &r->bottom);
+ return PyArg_Parse(v, "(hhhh)", &r->left, &r->top, &r->right, &r->bottom);
}
/* Convert a Rect to a Python object */
PyObject *
PyMac_BuildRect(Rect *r)
{
- return Py_BuildValue("(hhhh)", r->left, r->top, r->right, r->bottom);
+ return Py_BuildValue("(hhhh)", r->left, r->top, r->right, r->bottom);
}
@@ -250,14 +250,14 @@ PyMac_BuildRect(Rect *r)
int
PyMac_GetPoint(PyObject *v, Point *p)
{
- return PyArg_Parse(v, "(hh)", &p->h, &p->v);
+ return PyArg_Parse(v, "(hh)", &p->h, &p->v);
}
/* Convert a Point to a Python object */
PyObject *
PyMac_BuildPoint(Point p)
{
- return Py_BuildValue("(hh)", p.h, p.v);
+ return Py_BuildValue("(hh)", p.h, p.v);
}
@@ -266,73 +266,73 @@ PyMac_BuildPoint(Point p)
int
PyMac_GetEventRecord(PyObject *v, EventRecord *e)
{
- return PyArg_Parse(v, "(Hkk(hh)H)",
- &e->what,
- &e->message,
- &e->when,
- &e->where.h,
- &e->where.v,
- &e->modifiers);
+ return PyArg_Parse(v, "(Hkk(hh)H)",
+ &e->what,
+ &e->message,
+ &e->when,
+ &e->where.h,
+ &e->where.v,
+ &e->modifiers);
}
/* Convert a Rect to an EventRecord object */
PyObject *
PyMac_BuildEventRecord(EventRecord *e)
{
- return Py_BuildValue("(hll(hh)h)",
- e->what,
- e->message,
- e->when,
- e->where.h,
- e->where.v,
- e->modifiers);
+ return Py_BuildValue("(hll(hh)h)",
+ e->what,
+ e->message,
+ e->when,
+ e->where.h,
+ e->where.v,
+ e->modifiers);
}
/* Convert Python object to Fixed */
int
PyMac_GetFixed(PyObject *v, Fixed *f)
{
- double d;
-
- if( !PyArg_Parse(v, "d", &d))
- return 0;
- *f = (Fixed)(d * 0x10000);
- return 1;
+ double d;
+
+ if( !PyArg_Parse(v, "d", &d))
+ return 0;
+ *f = (Fixed)(d * 0x10000);
+ return 1;
}
/* Convert a Fixed to a Python object */
PyObject *
PyMac_BuildFixed(Fixed f)
{
- double d;
-
- d = f;
- d = d / 0x10000;
- return Py_BuildValue("d", d);
+ double d;
+
+ d = f;
+ d = d / 0x10000;
+ return Py_BuildValue("d", d);
}
/* Convert wide to/from Python int or (hi, lo) tuple. XXXX Should use Python longs */
int
PyMac_Getwide(PyObject *v, wide *rv)
{
- if (PyInt_Check(v)) {
- rv->hi = 0;
- rv->lo = PyInt_AsLong(v);
- if( rv->lo & 0x80000000 )
- rv->hi = -1;
- return 1;
- }
- return PyArg_Parse(v, "(kk)", &rv->hi, &rv->lo);
+ if (PyInt_Check(v)) {
+ rv->hi = 0;
+ rv->lo = PyInt_AsLong(v);
+ if( rv->lo & 0x80000000 )
+ rv->hi = -1;
+ return 1;
+ }
+ return PyArg_Parse(v, "(kk)", &rv->hi, &rv->lo);
}
PyObject *
PyMac_Buildwide(wide *w)
{
- if ( (w->hi == 0 && (w->lo & 0x80000000) == 0) ||
- (w->hi == -1 && (w->lo & 0x80000000) ) )
- return PyInt_FromLong(w->lo);
- return Py_BuildValue("(ll)", w->hi, w->lo);
+ if ( (w->hi == 0 && (w->lo & 0x80000000) == 0) ||
+ (w->hi == -1 && (w->lo & 0x80000000) ) )
+ return PyInt_FromLong(w->lo);
+ return Py_BuildValue("(ll)", w->hi, w->lo);
}
#ifdef USE_TOOLBOX_OBJECT_GLUE
@@ -358,8 +358,8 @@ PyObject *routinename(object cobj) { \
if (!PyMacGluePtr_##routinename) { \
if (!PyImport_ImportModule(module)) return NULL; \
if (!PyMacGluePtr_##routinename) { \
- PyErr_SetString(PyExc_ImportError, "Module did not provide routine: " module ": " #routinename); \
- return NULL; \
+ PyErr_SetString(PyExc_ImportError, "Module did not provide routine: " module ": " #routinename); \
+ return NULL; \
} \
} \
return (*PyMacGluePtr_##routinename)(cobj); \
@@ -372,8 +372,8 @@ int routinename(PyObject *pyobj, object *cobj) { \
if (!PyMacGluePtr_##routinename) { \
if (!PyImport_ImportModule(module)) return 0; \
if (!PyMacGluePtr_##routinename) { \
- PyErr_SetString(PyExc_ImportError, "Module did not provide routine: " module ": " #routinename); \
- return 0; \
+ PyErr_SetString(PyExc_ImportError, "Module did not provide routine: " module ": " #routinename); \
+ return 0; \
} \
} \
return (*PyMacGluePtr_##routinename)(pyobj, cobj); \
diff --git a/Python/marshal.c b/Python/marshal.c
index 14f7134..faca027 100644
--- a/Python/marshal.c
+++ b/Python/marshal.c
@@ -19,30 +19,30 @@
*/
#define MAX_MARSHAL_STACK_DEPTH 2000
-#define TYPE_NULL '0'
-#define TYPE_NONE 'N'
-#define TYPE_FALSE 'F'
-#define TYPE_TRUE 'T'
-#define TYPE_STOPITER 'S'
-#define TYPE_ELLIPSIS '.'
-#define TYPE_INT 'i'
-#define TYPE_INT64 'I'
-#define TYPE_FLOAT 'f'
-#define TYPE_BINARY_FLOAT 'g'
-#define TYPE_COMPLEX 'x'
-#define TYPE_BINARY_COMPLEX 'y'
-#define TYPE_LONG 'l'
-#define TYPE_STRING 's'
-#define TYPE_INTERNED 't'
-#define TYPE_STRINGREF 'R'
-#define TYPE_TUPLE '('
-#define TYPE_LIST '['
-#define TYPE_DICT '{'
-#define TYPE_CODE 'c'
-#define TYPE_UNICODE 'u'
-#define TYPE_UNKNOWN '?'
-#define TYPE_SET '<'
-#define TYPE_FROZENSET '>'
+#define TYPE_NULL '0'
+#define TYPE_NONE 'N'
+#define TYPE_FALSE 'F'
+#define TYPE_TRUE 'T'
+#define TYPE_STOPITER 'S'
+#define TYPE_ELLIPSIS '.'
+#define TYPE_INT 'i'
+#define TYPE_INT64 'I'
+#define TYPE_FLOAT 'f'
+#define TYPE_BINARY_FLOAT 'g'
+#define TYPE_COMPLEX 'x'
+#define TYPE_BINARY_COMPLEX 'y'
+#define TYPE_LONG 'l'
+#define TYPE_STRING 's'
+#define TYPE_INTERNED 't'
+#define TYPE_STRINGREF 'R'
+#define TYPE_TUPLE '('
+#define TYPE_LIST '['
+#define TYPE_DICT '{'
+#define TYPE_CODE 'c'
+#define TYPE_UNICODE 'u'
+#define TYPE_UNKNOWN '?'
+#define TYPE_SET '<'
+#define TYPE_FROZENSET '>'
#define WFERR_OK 0
#define WFERR_UNMARSHALLABLE 1
@@ -50,79 +50,79 @@
#define WFERR_NOMEMORY 3
typedef struct {
- FILE *fp;
- int error; /* see WFERR_* values */
- int depth;
- /* If fp == NULL, the following are valid: */
- PyObject *str;
- char *ptr;
- char *end;
- PyObject *strings; /* dict on marshal, list on unmarshal */
- int version;
+ FILE *fp;
+ int error; /* see WFERR_* values */
+ int depth;
+ /* If fp == NULL, the following are valid: */
+ PyObject *str;
+ char *ptr;
+ char *end;
+ PyObject *strings; /* dict on marshal, list on unmarshal */
+ int version;
} WFILE;
#define w_byte(c, p) if (((p)->fp)) putc((c), (p)->fp); \
- else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \
- else w_more(c, p)
+ else if ((p)->ptr != (p)->end) *(p)->ptr++ = (c); \
+ else w_more(c, p)
static void
w_more(int c, WFILE *p)
{
- Py_ssize_t size, newsize;
- if (p->str == NULL)
- return; /* An error already occurred */
- size = PyString_Size(p->str);
- newsize = size + size + 1024;
- if (newsize > 32*1024*1024) {
- newsize = size + (size >> 3); /* 12.5% overallocation */
- }
- if (_PyString_Resize(&p->str, newsize) != 0) {
- p->ptr = p->end = NULL;
- }
- else {
- p->ptr = PyString_AS_STRING((PyStringObject *)p->str) + size;
- p->end =
- PyString_AS_STRING((PyStringObject *)p->str) + newsize;
- *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char);
- }
+ Py_ssize_t size, newsize;
+ if (p->str == NULL)
+ return; /* An error already occurred */
+ size = PyString_Size(p->str);
+ newsize = size + size + 1024;
+ if (newsize > 32*1024*1024) {
+ newsize = size + (size >> 3); /* 12.5% overallocation */
+ }
+ if (_PyString_Resize(&p->str, newsize) != 0) {
+ p->ptr = p->end = NULL;
+ }
+ else {
+ p->ptr = PyString_AS_STRING((PyStringObject *)p->str) + size;
+ p->end =
+ PyString_AS_STRING((PyStringObject *)p->str) + newsize;
+ *p->ptr++ = Py_SAFE_DOWNCAST(c, int, char);
+ }
}
static void
w_string(char *s, int n, WFILE *p)
{
- if (p->fp != NULL) {
- fwrite(s, 1, n, p->fp);
- }
- else {
- while (--n >= 0) {
- w_byte(*s, p);
- s++;
- }
- }
+ if (p->fp != NULL) {
+ fwrite(s, 1, n, p->fp);
+ }
+ else {
+ while (--n >= 0) {
+ w_byte(*s, p);
+ s++;
+ }
+ }
}
static void
w_short(int x, WFILE *p)
{
- w_byte((char)( x & 0xff), p);
- w_byte((char)((x>> 8) & 0xff), p);
+ w_byte((char)( x & 0xff), p);
+ w_byte((char)((x>> 8) & 0xff), p);
}
static void
w_long(long x, WFILE *p)
{
- w_byte((char)( x & 0xff), p);
- w_byte((char)((x>> 8) & 0xff), p);
- w_byte((char)((x>>16) & 0xff), p);
- w_byte((char)((x>>24) & 0xff), p);
+ w_byte((char)( x & 0xff), p);
+ w_byte((char)((x>> 8) & 0xff), p);
+ w_byte((char)((x>>16) & 0xff), p);
+ w_byte((char)((x>>24) & 0xff), p);
}
#if SIZEOF_LONG > 4
static void
w_long64(long x, WFILE *p)
{
- w_long(x, p);
- w_long(x>>32, p);
+ w_long(x, p);
+ w_long(x>>32, p);
}
#endif
@@ -141,337 +141,337 @@ w_long64(long x, WFILE *p)
static void
w_PyLong(const PyLongObject *ob, WFILE *p)
{
- Py_ssize_t i, j, n, l;
- digit d;
-
- w_byte(TYPE_LONG, p);
- if (Py_SIZE(ob) == 0) {
- w_long((long)0, p);
- return;
- }
-
- /* set l to number of base PyLong_MARSHAL_BASE digits */
- n = ABS(Py_SIZE(ob));
- l = (n-1) * PyLong_MARSHAL_RATIO;
- d = ob->ob_digit[n-1];
- assert(d != 0); /* a PyLong is always normalized */
- do {
- d >>= PyLong_MARSHAL_SHIFT;
- l++;
- } while (d != 0);
- w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p);
-
- for (i=0; i < n-1; i++) {
- d = ob->ob_digit[i];
- for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
- w_short(d & PyLong_MARSHAL_MASK, p);
- d >>= PyLong_MARSHAL_SHIFT;
- }
- assert (d == 0);
- }
- d = ob->ob_digit[n-1];
- do {
- w_short(d & PyLong_MARSHAL_MASK, p);
- d >>= PyLong_MARSHAL_SHIFT;
- } while (d != 0);
+ Py_ssize_t i, j, n, l;
+ digit d;
+
+ w_byte(TYPE_LONG, p);
+ if (Py_SIZE(ob) == 0) {
+ w_long((long)0, p);
+ return;
+ }
+
+ /* set l to number of base PyLong_MARSHAL_BASE digits */
+ n = ABS(Py_SIZE(ob));
+ l = (n-1) * PyLong_MARSHAL_RATIO;
+ d = ob->ob_digit[n-1];
+ assert(d != 0); /* a PyLong is always normalized */
+ do {
+ d >>= PyLong_MARSHAL_SHIFT;
+ l++;
+ } while (d != 0);
+ w_long((long)(Py_SIZE(ob) > 0 ? l : -l), p);
+
+ for (i=0; i < n-1; i++) {
+ d = ob->ob_digit[i];
+ for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
+ w_short(d & PyLong_MARSHAL_MASK, p);
+ d >>= PyLong_MARSHAL_SHIFT;
+ }
+ assert (d == 0);
+ }
+ d = ob->ob_digit[n-1];
+ do {
+ w_short(d & PyLong_MARSHAL_MASK, p);
+ d >>= PyLong_MARSHAL_SHIFT;
+ } while (d != 0);
}
static void
w_object(PyObject *v, WFILE *p)
{
- Py_ssize_t i, n;
-
- p->depth++;
-
- if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
- p->error = WFERR_NESTEDTOODEEP;
- }
- else if (v == NULL) {
- w_byte(TYPE_NULL, p);
- }
- else if (v == Py_None) {
- w_byte(TYPE_NONE, p);
- }
- else if (v == PyExc_StopIteration) {
- w_byte(TYPE_STOPITER, p);
- }
- else if (v == Py_Ellipsis) {
- w_byte(TYPE_ELLIPSIS, p);
- }
- else if (v == Py_False) {
- w_byte(TYPE_FALSE, p);
- }
- else if (v == Py_True) {
- w_byte(TYPE_TRUE, p);
- }
- else if (PyInt_CheckExact(v)) {
- long x = PyInt_AS_LONG((PyIntObject *)v);
+ Py_ssize_t i, n;
+
+ p->depth++;
+
+ if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
+ p->error = WFERR_NESTEDTOODEEP;
+ }
+ else if (v == NULL) {
+ w_byte(TYPE_NULL, p);
+ }
+ else if (v == Py_None) {
+ w_byte(TYPE_NONE, p);
+ }
+ else if (v == PyExc_StopIteration) {
+ w_byte(TYPE_STOPITER, p);
+ }
+ else if (v == Py_Ellipsis) {
+ w_byte(TYPE_ELLIPSIS, p);
+ }
+ else if (v == Py_False) {
+ w_byte(TYPE_FALSE, p);
+ }
+ else if (v == Py_True) {
+ w_byte(TYPE_TRUE, p);
+ }
+ else if (PyInt_CheckExact(v)) {
+ long x = PyInt_AS_LONG((PyIntObject *)v);
#if SIZEOF_LONG > 4
- long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
- if (y && y != -1) {
- w_byte(TYPE_INT64, p);
- w_long64(x, p);
- }
- else
+ long y = Py_ARITHMETIC_RIGHT_SHIFT(long, x, 31);
+ if (y && y != -1) {
+ w_byte(TYPE_INT64, p);
+ w_long64(x, p);
+ }
+ else
#endif
- {
- w_byte(TYPE_INT, p);
- w_long(x, p);
- }
- }
- else if (PyLong_CheckExact(v)) {
- PyLongObject *ob = (PyLongObject *)v;
- w_PyLong(ob, p);
- }
- else if (PyFloat_CheckExact(v)) {
- if (p->version > 1) {
- unsigned char buf[8];
- if (_PyFloat_Pack8(PyFloat_AsDouble(v),
- buf, 1) < 0) {
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_byte(TYPE_BINARY_FLOAT, p);
- w_string((char*)buf, 8, p);
- }
- else {
- char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
- 'g', 17, 0, NULL);
- if (!buf) {
- p->error = WFERR_NOMEMORY;
- return;
- }
- n = strlen(buf);
- w_byte(TYPE_FLOAT, p);
- w_byte((int)n, p);
- w_string(buf, (int)n, p);
- PyMem_Free(buf);
- }
- }
+ {
+ w_byte(TYPE_INT, p);
+ w_long(x, p);
+ }
+ }
+ else if (PyLong_CheckExact(v)) {
+ PyLongObject *ob = (PyLongObject *)v;
+ w_PyLong(ob, p);
+ }
+ else if (PyFloat_CheckExact(v)) {
+ if (p->version > 1) {
+ unsigned char buf[8];
+ if (_PyFloat_Pack8(PyFloat_AsDouble(v),
+ buf, 1) < 0) {
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_byte(TYPE_BINARY_FLOAT, p);
+ w_string((char*)buf, 8, p);
+ }
+ else {
+ char *buf = PyOS_double_to_string(PyFloat_AS_DOUBLE(v),
+ 'g', 17, 0, NULL);
+ if (!buf) {
+ p->error = WFERR_NOMEMORY;
+ return;
+ }
+ n = strlen(buf);
+ w_byte(TYPE_FLOAT, p);
+ w_byte((int)n, p);
+ w_string(buf, (int)n, p);
+ PyMem_Free(buf);
+ }
+ }
#ifndef WITHOUT_COMPLEX
- else if (PyComplex_CheckExact(v)) {
- if (p->version > 1) {
- unsigned char buf[8];
- if (_PyFloat_Pack8(PyComplex_RealAsDouble(v),
- buf, 1) < 0) {
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_byte(TYPE_BINARY_COMPLEX, p);
- w_string((char*)buf, 8, p);
- if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v),
- buf, 1) < 0) {
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_string((char*)buf, 8, p);
- }
- else {
- char *buf;
- w_byte(TYPE_COMPLEX, p);
- buf = PyOS_double_to_string(PyComplex_RealAsDouble(v),
- 'g', 17, 0, NULL);
- if (!buf) {
- p->error = WFERR_NOMEMORY;
- return;
- }
- n = strlen(buf);
- w_byte((int)n, p);
- w_string(buf, (int)n, p);
- PyMem_Free(buf);
- buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v),
- 'g', 17, 0, NULL);
- if (!buf) {
- p->error = WFERR_NOMEMORY;
- return;
- }
- n = strlen(buf);
- w_byte((int)n, p);
- w_string(buf, (int)n, p);
- PyMem_Free(buf);
- }
- }
+ else if (PyComplex_CheckExact(v)) {
+ if (p->version > 1) {
+ unsigned char buf[8];
+ if (_PyFloat_Pack8(PyComplex_RealAsDouble(v),
+ buf, 1) < 0) {
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_byte(TYPE_BINARY_COMPLEX, p);
+ w_string((char*)buf, 8, p);
+ if (_PyFloat_Pack8(PyComplex_ImagAsDouble(v),
+ buf, 1) < 0) {
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_string((char*)buf, 8, p);
+ }
+ else {
+ char *buf;
+ w_byte(TYPE_COMPLEX, p);
+ buf = PyOS_double_to_string(PyComplex_RealAsDouble(v),
+ 'g', 17, 0, NULL);
+ if (!buf) {
+ p->error = WFERR_NOMEMORY;
+ return;
+ }
+ n = strlen(buf);
+ w_byte((int)n, p);
+ w_string(buf, (int)n, p);
+ PyMem_Free(buf);
+ buf = PyOS_double_to_string(PyComplex_ImagAsDouble(v),
+ 'g', 17, 0, NULL);
+ if (!buf) {
+ p->error = WFERR_NOMEMORY;
+ return;
+ }
+ n = strlen(buf);
+ w_byte((int)n, p);
+ w_string(buf, (int)n, p);
+ PyMem_Free(buf);
+ }
+ }
#endif
- else if (PyString_CheckExact(v)) {
- if (p->strings && PyString_CHECK_INTERNED(v)) {
- PyObject *o = PyDict_GetItem(p->strings, v);
- if (o) {
- long w = PyInt_AsLong(o);
- w_byte(TYPE_STRINGREF, p);
- w_long(w, p);
- goto exit;
- }
- else {
- int ok;
- o = PyInt_FromSsize_t(PyDict_Size(p->strings));
- ok = o &&
- PyDict_SetItem(p->strings, v, o) >= 0;
- Py_XDECREF(o);
- if (!ok) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_byte(TYPE_INTERNED, p);
- }
- }
- else {
- w_byte(TYPE_STRING, p);
- }
- n = PyString_GET_SIZE(v);
- if (n > INT_MAX) {
- /* huge strings are not supported */
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_long((long)n, p);
- w_string(PyString_AS_STRING(v), (int)n, p);
- }
+ else if (PyString_CheckExact(v)) {
+ if (p->strings && PyString_CHECK_INTERNED(v)) {
+ PyObject *o = PyDict_GetItem(p->strings, v);
+ if (o) {
+ long w = PyInt_AsLong(o);
+ w_byte(TYPE_STRINGREF, p);
+ w_long(w, p);
+ goto exit;
+ }
+ else {
+ int ok;
+ o = PyInt_FromSsize_t(PyDict_Size(p->strings));
+ ok = o &&
+ PyDict_SetItem(p->strings, v, o) >= 0;
+ Py_XDECREF(o);
+ if (!ok) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_byte(TYPE_INTERNED, p);
+ }
+ }
+ else {
+ w_byte(TYPE_STRING, p);
+ }
+ n = PyString_GET_SIZE(v);
+ if (n > INT_MAX) {
+ /* huge strings are not supported */
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_long((long)n, p);
+ w_string(PyString_AS_STRING(v), (int)n, p);
+ }
#ifdef Py_USING_UNICODE
- else if (PyUnicode_CheckExact(v)) {
- PyObject *utf8;
- utf8 = PyUnicode_AsUTF8String(v);
- if (utf8 == NULL) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_byte(TYPE_UNICODE, p);
- n = PyString_GET_SIZE(utf8);
- if (n > INT_MAX) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_long((long)n, p);
- w_string(PyString_AS_STRING(utf8), (int)n, p);
- Py_DECREF(utf8);
- }
+ else if (PyUnicode_CheckExact(v)) {
+ PyObject *utf8;
+ utf8 = PyUnicode_AsUTF8String(v);
+ if (utf8 == NULL) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_byte(TYPE_UNICODE, p);
+ n = PyString_GET_SIZE(utf8);
+ if (n > INT_MAX) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_long((long)n, p);
+ w_string(PyString_AS_STRING(utf8), (int)n, p);
+ Py_DECREF(utf8);
+ }
#endif
- else if (PyTuple_CheckExact(v)) {
- w_byte(TYPE_TUPLE, p);
- n = PyTuple_Size(v);
- w_long((long)n, p);
- for (i = 0; i < n; i++) {
- w_object(PyTuple_GET_ITEM(v, i), p);
- }
- }
- else if (PyList_CheckExact(v)) {
- w_byte(TYPE_LIST, p);
- n = PyList_GET_SIZE(v);
- w_long((long)n, p);
- for (i = 0; i < n; i++) {
- w_object(PyList_GET_ITEM(v, i), p);
- }
- }
- else if (PyDict_CheckExact(v)) {
- Py_ssize_t pos;
- PyObject *key, *value;
- w_byte(TYPE_DICT, p);
- /* This one is NULL object terminated! */
- pos = 0;
- while (PyDict_Next(v, &pos, &key, &value)) {
- w_object(key, p);
- w_object(value, p);
- }
- w_object((PyObject *)NULL, p);
- }
- else if (PyAnySet_CheckExact(v)) {
- PyObject *value, *it;
-
- if (PyObject_TypeCheck(v, &PySet_Type))
- w_byte(TYPE_SET, p);
- else
- w_byte(TYPE_FROZENSET, p);
- n = PyObject_Size(v);
- if (n == -1) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_long((long)n, p);
- it = PyObject_GetIter(v);
- if (it == NULL) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- while ((value = PyIter_Next(it)) != NULL) {
- w_object(value, p);
- Py_DECREF(value);
- }
- Py_DECREF(it);
- if (PyErr_Occurred()) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- }
- else if (PyCode_Check(v)) {
- PyCodeObject *co = (PyCodeObject *)v;
- w_byte(TYPE_CODE, p);
- w_long(co->co_argcount, p);
- w_long(co->co_nlocals, p);
- w_long(co->co_stacksize, p);
- w_long(co->co_flags, p);
- w_object(co->co_code, p);
- w_object(co->co_consts, p);
- w_object(co->co_names, p);
- w_object(co->co_varnames, p);
- w_object(co->co_freevars, p);
- w_object(co->co_cellvars, p);
- w_object(co->co_filename, p);
- w_object(co->co_name, p);
- w_long(co->co_firstlineno, p);
- w_object(co->co_lnotab, p);
- }
- else if (PyObject_CheckReadBuffer(v)) {
- /* Write unknown buffer-style objects as a string */
- char *s;
- PyBufferProcs *pb = v->ob_type->tp_as_buffer;
- w_byte(TYPE_STRING, p);
- n = (*pb->bf_getreadbuffer)(v, 0, (void **)&s);
- if (n > INT_MAX) {
- p->depth--;
- p->error = WFERR_UNMARSHALLABLE;
- return;
- }
- w_long((long)n, p);
- w_string(s, (int)n, p);
- }
- else {
- w_byte(TYPE_UNKNOWN, p);
- p->error = WFERR_UNMARSHALLABLE;
- }
+ else if (PyTuple_CheckExact(v)) {
+ w_byte(TYPE_TUPLE, p);
+ n = PyTuple_Size(v);
+ w_long((long)n, p);
+ for (i = 0; i < n; i++) {
+ w_object(PyTuple_GET_ITEM(v, i), p);
+ }
+ }
+ else if (PyList_CheckExact(v)) {
+ w_byte(TYPE_LIST, p);
+ n = PyList_GET_SIZE(v);
+ w_long((long)n, p);
+ for (i = 0; i < n; i++) {
+ w_object(PyList_GET_ITEM(v, i), p);
+ }
+ }
+ else if (PyDict_CheckExact(v)) {
+ Py_ssize_t pos;
+ PyObject *key, *value;
+ w_byte(TYPE_DICT, p);
+ /* This one is NULL object terminated! */
+ pos = 0;
+ while (PyDict_Next(v, &pos, &key, &value)) {
+ w_object(key, p);
+ w_object(value, p);
+ }
+ w_object((PyObject *)NULL, p);
+ }
+ else if (PyAnySet_CheckExact(v)) {
+ PyObject *value, *it;
+
+ if (PyObject_TypeCheck(v, &PySet_Type))
+ w_byte(TYPE_SET, p);
+ else
+ w_byte(TYPE_FROZENSET, p);
+ n = PyObject_Size(v);
+ if (n == -1) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_long((long)n, p);
+ it = PyObject_GetIter(v);
+ if (it == NULL) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ while ((value = PyIter_Next(it)) != NULL) {
+ w_object(value, p);
+ Py_DECREF(value);
+ }
+ Py_DECREF(it);
+ if (PyErr_Occurred()) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ }
+ else if (PyCode_Check(v)) {
+ PyCodeObject *co = (PyCodeObject *)v;
+ w_byte(TYPE_CODE, p);
+ w_long(co->co_argcount, p);
+ w_long(co->co_nlocals, p);
+ w_long(co->co_stacksize, p);
+ w_long(co->co_flags, p);
+ w_object(co->co_code, p);
+ w_object(co->co_consts, p);
+ w_object(co->co_names, p);
+ w_object(co->co_varnames, p);
+ w_object(co->co_freevars, p);
+ w_object(co->co_cellvars, p);
+ w_object(co->co_filename, p);
+ w_object(co->co_name, p);
+ w_long(co->co_firstlineno, p);
+ w_object(co->co_lnotab, p);
+ }
+ else if (PyObject_CheckReadBuffer(v)) {
+ /* Write unknown buffer-style objects as a string */
+ char *s;
+ PyBufferProcs *pb = v->ob_type->tp_as_buffer;
+ w_byte(TYPE_STRING, p);
+ n = (*pb->bf_getreadbuffer)(v, 0, (void **)&s);
+ if (n > INT_MAX) {
+ p->depth--;
+ p->error = WFERR_UNMARSHALLABLE;
+ return;
+ }
+ w_long((long)n, p);
+ w_string(s, (int)n, p);
+ }
+ else {
+ w_byte(TYPE_UNKNOWN, p);
+ p->error = WFERR_UNMARSHALLABLE;
+ }
exit:
- p->depth--;
+ p->depth--;
}
/* version currently has no effect for writing longs. */
void
PyMarshal_WriteLongToFile(long x, FILE *fp, int version)
{
- WFILE wf;
- wf.fp = fp;
- wf.error = WFERR_OK;
- wf.depth = 0;
- wf.strings = NULL;
- wf.version = version;
- w_long(x, &wf);
+ WFILE wf;
+ wf.fp = fp;
+ wf.error = WFERR_OK;
+ wf.depth = 0;
+ wf.strings = NULL;
+ wf.version = version;
+ w_long(x, &wf);
}
void
PyMarshal_WriteObjectToFile(PyObject *x, FILE *fp, int version)
{
- WFILE wf;
- wf.fp = fp;
- wf.error = WFERR_OK;
- wf.depth = 0;
- wf.strings = (version > 0) ? PyDict_New() : NULL;
- wf.version = version;
- w_object(x, &wf);
- Py_XDECREF(wf.strings);
+ WFILE wf;
+ wf.fp = fp;
+ wf.error = WFERR_OK;
+ wf.depth = 0;
+ wf.strings = (version > 0) ? PyDict_New() : NULL;
+ wf.version = version;
+ w_object(x, &wf);
+ Py_XDECREF(wf.strings);
}
typedef WFILE RFILE; /* Same struct with different invariants */
@@ -483,49 +483,49 @@ typedef WFILE RFILE; /* Same struct with different invariants */
static int
r_string(char *s, int n, RFILE *p)
{
- if (p->fp != NULL)
- /* The result fits into int because it must be <=n. */
- return (int)fread(s, 1, n, p->fp);
- if (p->end - p->ptr < n)
- n = (int)(p->end - p->ptr);
- memcpy(s, p->ptr, n);
- p->ptr += n;
- return n;
+ if (p->fp != NULL)
+ /* The result fits into int because it must be <=n. */
+ return (int)fread(s, 1, n, p->fp);
+ if (p->end - p->ptr < n)
+ n = (int)(p->end - p->ptr);
+ memcpy(s, p->ptr, n);
+ p->ptr += n;
+ return n;
}
static int
r_short(RFILE *p)
{
- register short x;
- x = r_byte(p);
- x |= r_byte(p) << 8;
- /* Sign-extension, in case short greater than 16 bits */
- x |= -(x & 0x8000);
- return x;
+ register short x;
+ x = r_byte(p);
+ x |= r_byte(p) << 8;
+ /* Sign-extension, in case short greater than 16 bits */
+ x |= -(x & 0x8000);
+ return x;
}
static long
r_long(RFILE *p)
{
- register long x;
- register FILE *fp = p->fp;
- if (fp) {
- x = getc(fp);
- x |= (long)getc(fp) << 8;
- x |= (long)getc(fp) << 16;
- x |= (long)getc(fp) << 24;
- }
- else {
- x = rs_byte(p);
- x |= (long)rs_byte(p) << 8;
- x |= (long)rs_byte(p) << 16;
- x |= (long)rs_byte(p) << 24;
- }
+ register long x;
+ register FILE *fp = p->fp;
+ if (fp) {
+ x = getc(fp);
+ x |= (long)getc(fp) << 8;
+ x |= (long)getc(fp) << 16;
+ x |= (long)getc(fp) << 24;
+ }
+ else {
+ x = rs_byte(p);
+ x |= (long)rs_byte(p) << 8;
+ x |= (long)rs_byte(p) << 16;
+ x |= (long)rs_byte(p) << 24;
+ }
#if SIZEOF_LONG > 4
- /* Sign extension for 64-bit machines */
- x |= -(x & 0x80000000L);
+ /* Sign extension for 64-bit machines */
+ x |= -(x & 0x80000000L);
#endif
- return x;
+ return x;
}
/* r_long64 deals with the TYPE_INT64 code. On a machine with
@@ -538,570 +538,570 @@ r_long(RFILE *p)
static PyObject *
r_long64(RFILE *p)
{
- long lo4 = r_long(p);
- long hi4 = r_long(p);
+ long lo4 = r_long(p);
+ long hi4 = r_long(p);
#if SIZEOF_LONG > 4
- long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL);
- return PyInt_FromLong(x);
+ long x = (hi4 << 32) | (lo4 & 0xFFFFFFFFL);
+ return PyInt_FromLong(x);
#else
- unsigned char buf[8];
- int one = 1;
- int is_little_endian = (int)*(char*)&one;
- if (is_little_endian) {
- memcpy(buf, &lo4, 4);
- memcpy(buf+4, &hi4, 4);
- }
- else {
- memcpy(buf, &hi4, 4);
- memcpy(buf+4, &lo4, 4);
- }
- return _PyLong_FromByteArray(buf, 8, is_little_endian, 1);
+ unsigned char buf[8];
+ int one = 1;
+ int is_little_endian = (int)*(char*)&one;
+ if (is_little_endian) {
+ memcpy(buf, &lo4, 4);
+ memcpy(buf+4, &hi4, 4);
+ }
+ else {
+ memcpy(buf, &hi4, 4);
+ memcpy(buf+4, &lo4, 4);
+ }
+ return _PyLong_FromByteArray(buf, 8, is_little_endian, 1);
#endif
}
static PyObject *
r_PyLong(RFILE *p)
{
- PyLongObject *ob;
- int size, i, j, md, shorts_in_top_digit;
- long n;
- digit d;
-
- n = r_long(p);
- if (n == 0)
- return (PyObject *)_PyLong_New(0);
- if (n < -INT_MAX || n > INT_MAX) {
- PyErr_SetString(PyExc_ValueError,
- "bad marshal data (long size out of range)");
- return NULL;
- }
-
- size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO;
- shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO;
- ob = _PyLong_New(size);
- if (ob == NULL)
- return NULL;
- Py_SIZE(ob) = n > 0 ? size : -size;
-
- for (i = 0; i < size-1; i++) {
- d = 0;
- for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
- md = r_short(p);
- if (md < 0 || md > PyLong_MARSHAL_BASE)
- goto bad_digit;
- d += (digit)md << j*PyLong_MARSHAL_SHIFT;
- }
- ob->ob_digit[i] = d;
- }
- d = 0;
- for (j=0; j < shorts_in_top_digit; j++) {
- md = r_short(p);
- if (md < 0 || md > PyLong_MARSHAL_BASE)
- goto bad_digit;
- /* topmost marshal digit should be nonzero */
- if (md == 0 && j == shorts_in_top_digit - 1) {
- Py_DECREF(ob);
- PyErr_SetString(PyExc_ValueError,
- "bad marshal data (unnormalized long data)");
- return NULL;
- }
- d += (digit)md << j*PyLong_MARSHAL_SHIFT;
- }
- /* top digit should be nonzero, else the resulting PyLong won't be
- normalized */
- ob->ob_digit[size-1] = d;
- return (PyObject *)ob;
+ PyLongObject *ob;
+ int size, i, j, md, shorts_in_top_digit;
+ long n;
+ digit d;
+
+ n = r_long(p);
+ if (n == 0)
+ return (PyObject *)_PyLong_New(0);
+ if (n < -INT_MAX || n > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError,
+ "bad marshal data (long size out of range)");
+ return NULL;
+ }
+
+ size = 1 + (ABS(n) - 1) / PyLong_MARSHAL_RATIO;
+ shorts_in_top_digit = 1 + (ABS(n) - 1) % PyLong_MARSHAL_RATIO;
+ ob = _PyLong_New(size);
+ if (ob == NULL)
+ return NULL;
+ Py_SIZE(ob) = n > 0 ? size : -size;
+
+ for (i = 0; i < size-1; i++) {
+ d = 0;
+ for (j=0; j < PyLong_MARSHAL_RATIO; j++) {
+ md = r_short(p);
+ if (md < 0 || md > PyLong_MARSHAL_BASE)
+ goto bad_digit;
+ d += (digit)md << j*PyLong_MARSHAL_SHIFT;
+ }
+ ob->ob_digit[i] = d;
+ }
+ d = 0;
+ for (j=0; j < shorts_in_top_digit; j++) {
+ md = r_short(p);
+ if (md < 0 || md > PyLong_MARSHAL_BASE)
+ goto bad_digit;
+ /* topmost marshal digit should be nonzero */
+ if (md == 0 && j == shorts_in_top_digit - 1) {
+ Py_DECREF(ob);
+ PyErr_SetString(PyExc_ValueError,
+ "bad marshal data (unnormalized long data)");
+ return NULL;
+ }
+ d += (digit)md << j*PyLong_MARSHAL_SHIFT;
+ }
+ /* top digit should be nonzero, else the resulting PyLong won't be
+ normalized */
+ ob->ob_digit[size-1] = d;
+ return (PyObject *)ob;
bad_digit:
- Py_DECREF(ob);
- PyErr_SetString(PyExc_ValueError,
- "bad marshal data (digit out of range in long)");
- return NULL;
+ Py_DECREF(ob);
+ PyErr_SetString(PyExc_ValueError,
+ "bad marshal data (digit out of range in long)");
+ return NULL;
}
static PyObject *
r_object(RFILE *p)
{
- /* NULL is a valid return value, it does not necessarily means that
- an exception is set. */
- PyObject *v, *v2;
- long i, n;
- int type = r_byte(p);
- PyObject *retval;
-
- p->depth++;
-
- if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
- p->depth--;
- PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
- return NULL;
- }
-
- switch (type) {
-
- case EOF:
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
-
- case TYPE_NULL:
- retval = NULL;
- break;
-
- case TYPE_NONE:
- Py_INCREF(Py_None);
- retval = Py_None;
- break;
-
- case TYPE_STOPITER:
- Py_INCREF(PyExc_StopIteration);
- retval = PyExc_StopIteration;
- break;
-
- case TYPE_ELLIPSIS:
- Py_INCREF(Py_Ellipsis);
- retval = Py_Ellipsis;
- break;
-
- case TYPE_FALSE:
- Py_INCREF(Py_False);
- retval = Py_False;
- break;
-
- case TYPE_TRUE:
- Py_INCREF(Py_True);
- retval = Py_True;
- break;
-
- case TYPE_INT:
- retval = PyInt_FromLong(r_long(p));
- break;
-
- case TYPE_INT64:
- retval = r_long64(p);
- break;
-
- case TYPE_LONG:
- retval = r_PyLong(p);
- break;
-
- case TYPE_FLOAT:
- {
- char buf[256];
- double dx;
- n = r_byte(p);
- if (n == EOF || r_string(buf, (int)n, p) != n) {
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- buf[n] = '\0';
- dx = PyOS_string_to_double(buf, NULL, NULL);
- if (dx == -1.0 && PyErr_Occurred()) {
- retval = NULL;
- break;
- }
- retval = PyFloat_FromDouble(dx);
- break;
- }
-
- case TYPE_BINARY_FLOAT:
- {
- unsigned char buf[8];
- double x;
- if (r_string((char*)buf, 8, p) != 8) {
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- x = _PyFloat_Unpack8(buf, 1);
- if (x == -1.0 && PyErr_Occurred()) {
- retval = NULL;
- break;
- }
- retval = PyFloat_FromDouble(x);
- break;
- }
+ /* NULL is a valid return value, it does not necessarily means that
+ an exception is set. */
+ PyObject *v, *v2;
+ long i, n;
+ int type = r_byte(p);
+ PyObject *retval;
+
+ p->depth++;
+
+ if (p->depth > MAX_MARSHAL_STACK_DEPTH) {
+ p->depth--;
+ PyErr_SetString(PyExc_ValueError, "recursion limit exceeded");
+ return NULL;
+ }
+
+ switch (type) {
+
+ case EOF:
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+
+ case TYPE_NULL:
+ retval = NULL;
+ break;
+
+ case TYPE_NONE:
+ Py_INCREF(Py_None);
+ retval = Py_None;
+ break;
+
+ case TYPE_STOPITER:
+ Py_INCREF(PyExc_StopIteration);
+ retval = PyExc_StopIteration;
+ break;
+
+ case TYPE_ELLIPSIS:
+ Py_INCREF(Py_Ellipsis);
+ retval = Py_Ellipsis;
+ break;
+
+ case TYPE_FALSE:
+ Py_INCREF(Py_False);
+ retval = Py_False;
+ break;
+
+ case TYPE_TRUE:
+ Py_INCREF(Py_True);
+ retval = Py_True;
+ break;
+
+ case TYPE_INT:
+ retval = PyInt_FromLong(r_long(p));
+ break;
+
+ case TYPE_INT64:
+ retval = r_long64(p);
+ break;
+
+ case TYPE_LONG:
+ retval = r_PyLong(p);
+ break;
+
+ case TYPE_FLOAT:
+ {
+ char buf[256];
+ double dx;
+ n = r_byte(p);
+ if (n == EOF || r_string(buf, (int)n, p) != n) {
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ buf[n] = '\0';
+ dx = PyOS_string_to_double(buf, NULL, NULL);
+ if (dx == -1.0 && PyErr_Occurred()) {
+ retval = NULL;
+ break;
+ }
+ retval = PyFloat_FromDouble(dx);
+ break;
+ }
+
+ case TYPE_BINARY_FLOAT:
+ {
+ unsigned char buf[8];
+ double x;
+ if (r_string((char*)buf, 8, p) != 8) {
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ x = _PyFloat_Unpack8(buf, 1);
+ if (x == -1.0 && PyErr_Occurred()) {
+ retval = NULL;
+ break;
+ }
+ retval = PyFloat_FromDouble(x);
+ break;
+ }
#ifndef WITHOUT_COMPLEX
- case TYPE_COMPLEX:
- {
- char buf[256];
- Py_complex c;
- n = r_byte(p);
- if (n == EOF || r_string(buf, (int)n, p) != n) {
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- buf[n] = '\0';
- c.real = PyOS_string_to_double(buf, NULL, NULL);
- if (c.real == -1.0 && PyErr_Occurred()) {
- retval = NULL;
- break;
- }
- n = r_byte(p);
- if (n == EOF || r_string(buf, (int)n, p) != n) {
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- buf[n] = '\0';
- c.imag = PyOS_string_to_double(buf, NULL, NULL);
- if (c.imag == -1.0 && PyErr_Occurred()) {
- retval = NULL;
- break;
- }
- retval = PyComplex_FromCComplex(c);
- break;
- }
-
- case TYPE_BINARY_COMPLEX:
- {
- unsigned char buf[8];
- Py_complex c;
- if (r_string((char*)buf, 8, p) != 8) {
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- c.real = _PyFloat_Unpack8(buf, 1);
- if (c.real == -1.0 && PyErr_Occurred()) {
- retval = NULL;
- break;
- }
- if (r_string((char*)buf, 8, p) != 8) {
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- c.imag = _PyFloat_Unpack8(buf, 1);
- if (c.imag == -1.0 && PyErr_Occurred()) {
- retval = NULL;
- break;
- }
- retval = PyComplex_FromCComplex(c);
- break;
- }
+ case TYPE_COMPLEX:
+ {
+ char buf[256];
+ Py_complex c;
+ n = r_byte(p);
+ if (n == EOF || r_string(buf, (int)n, p) != n) {
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ buf[n] = '\0';
+ c.real = PyOS_string_to_double(buf, NULL, NULL);
+ if (c.real == -1.0 && PyErr_Occurred()) {
+ retval = NULL;
+ break;
+ }
+ n = r_byte(p);
+ if (n == EOF || r_string(buf, (int)n, p) != n) {
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ buf[n] = '\0';
+ c.imag = PyOS_string_to_double(buf, NULL, NULL);
+ if (c.imag == -1.0 && PyErr_Occurred()) {
+ retval = NULL;
+ break;
+ }
+ retval = PyComplex_FromCComplex(c);
+ break;
+ }
+
+ case TYPE_BINARY_COMPLEX:
+ {
+ unsigned char buf[8];
+ Py_complex c;
+ if (r_string((char*)buf, 8, p) != 8) {
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ c.real = _PyFloat_Unpack8(buf, 1);
+ if (c.real == -1.0 && PyErr_Occurred()) {
+ retval = NULL;
+ break;
+ }
+ if (r_string((char*)buf, 8, p) != 8) {
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ c.imag = _PyFloat_Unpack8(buf, 1);
+ if (c.imag == -1.0 && PyErr_Occurred()) {
+ retval = NULL;
+ break;
+ }
+ retval = PyComplex_FromCComplex(c);
+ break;
+ }
#endif
- case TYPE_INTERNED:
- case TYPE_STRING:
- n = r_long(p);
- if (n < 0 || n > INT_MAX) {
- PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)");
- retval = NULL;
- break;
- }
- v = PyString_FromStringAndSize((char *)NULL, n);
- if (v == NULL) {
- retval = NULL;
- break;
- }
- if (r_string(PyString_AS_STRING(v), (int)n, p) != n) {
- Py_DECREF(v);
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- if (type == TYPE_INTERNED) {
- PyString_InternInPlace(&v);
- if (PyList_Append(p->strings, v) < 0) {
- retval = NULL;
- break;
- }
- }
- retval = v;
- break;
-
- case TYPE_STRINGREF:
- n = r_long(p);
- if (n < 0 || n >= PyList_GET_SIZE(p->strings)) {
- PyErr_SetString(PyExc_ValueError, "bad marshal data (string ref out of range)");
- retval = NULL;
- break;
- }
- v = PyList_GET_ITEM(p->strings, n);
- Py_INCREF(v);
- retval = v;
- break;
+ case TYPE_INTERNED:
+ case TYPE_STRING:
+ n = r_long(p);
+ if (n < 0 || n > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (string size out of range)");
+ retval = NULL;
+ break;
+ }
+ v = PyString_FromStringAndSize((char *)NULL, n);
+ if (v == NULL) {
+ retval = NULL;
+ break;
+ }
+ if (r_string(PyString_AS_STRING(v), (int)n, p) != n) {
+ Py_DECREF(v);
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ if (type == TYPE_INTERNED) {
+ PyString_InternInPlace(&v);
+ if (PyList_Append(p->strings, v) < 0) {
+ retval = NULL;
+ break;
+ }
+ }
+ retval = v;
+ break;
+
+ case TYPE_STRINGREF:
+ n = r_long(p);
+ if (n < 0 || n >= PyList_GET_SIZE(p->strings)) {
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (string ref out of range)");
+ retval = NULL;
+ break;
+ }
+ v = PyList_GET_ITEM(p->strings, n);
+ Py_INCREF(v);
+ retval = v;
+ break;
#ifdef Py_USING_UNICODE
- case TYPE_UNICODE:
- {
- char *buffer;
-
- n = r_long(p);
- if (n < 0 || n > INT_MAX) {
- PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)");
- retval = NULL;
- break;
- }
- buffer = PyMem_NEW(char, n);
- if (buffer == NULL) {
- retval = PyErr_NoMemory();
- break;
- }
- if (r_string(buffer, (int)n, p) != n) {
- PyMem_DEL(buffer);
- PyErr_SetString(PyExc_EOFError,
- "EOF read where object expected");
- retval = NULL;
- break;
- }
- v = PyUnicode_DecodeUTF8(buffer, n, NULL);
- PyMem_DEL(buffer);
- retval = v;
- break;
- }
+ case TYPE_UNICODE:
+ {
+ char *buffer;
+
+ n = r_long(p);
+ if (n < 0 || n > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (unicode size out of range)");
+ retval = NULL;
+ break;
+ }
+ buffer = PyMem_NEW(char, n);
+ if (buffer == NULL) {
+ retval = PyErr_NoMemory();
+ break;
+ }
+ if (r_string(buffer, (int)n, p) != n) {
+ PyMem_DEL(buffer);
+ PyErr_SetString(PyExc_EOFError,
+ "EOF read where object expected");
+ retval = NULL;
+ break;
+ }
+ v = PyUnicode_DecodeUTF8(buffer, n, NULL);
+ PyMem_DEL(buffer);
+ retval = v;
+ break;
+ }
#endif
- case TYPE_TUPLE:
- n = r_long(p);
- if (n < 0 || n > INT_MAX) {
- PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)");
- retval = NULL;
- break;
- }
- v = PyTuple_New((int)n);
- if (v == NULL) {
- retval = NULL;
- break;
- }
- for (i = 0; i < n; i++) {
- v2 = r_object(p);
- if ( v2 == NULL ) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_TypeError,
- "NULL object in marshal data for tuple");
- Py_DECREF(v);
- v = NULL;
- break;
- }
- PyTuple_SET_ITEM(v, (int)i, v2);
- }
- retval = v;
- break;
-
- case TYPE_LIST:
- n = r_long(p);
- if (n < 0 || n > INT_MAX) {
- PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)");
- retval = NULL;
- break;
- }
- v = PyList_New((int)n);
- if (v == NULL) {
- retval = NULL;
- break;
- }
- for (i = 0; i < n; i++) {
- v2 = r_object(p);
- if ( v2 == NULL ) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_TypeError,
- "NULL object in marshal data for list");
- Py_DECREF(v);
- v = NULL;
- break;
- }
- PyList_SET_ITEM(v, (int)i, v2);
- }
- retval = v;
- break;
-
- case TYPE_DICT:
- v = PyDict_New();
- if (v == NULL) {
- retval = NULL;
- break;
- }
- for (;;) {
- PyObject *key, *val;
- key = r_object(p);
- if (key == NULL)
- break;
- val = r_object(p);
- if (val != NULL)
- PyDict_SetItem(v, key, val);
- Py_DECREF(key);
- Py_XDECREF(val);
- }
- if (PyErr_Occurred()) {
- Py_DECREF(v);
- v = NULL;
- }
- retval = v;
- break;
-
- case TYPE_SET:
- case TYPE_FROZENSET:
- n = r_long(p);
- if (n < 0 || n > INT_MAX) {
- PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)");
- retval = NULL;
- break;
- }
- v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
- if (v == NULL) {
- retval = NULL;
- break;
- }
- for (i = 0; i < n; i++) {
- v2 = r_object(p);
- if ( v2 == NULL ) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_TypeError,
- "NULL object in marshal data for set");
- Py_DECREF(v);
- v = NULL;
- break;
- }
- if (PySet_Add(v, v2) == -1) {
- Py_DECREF(v);
- Py_DECREF(v2);
- v = NULL;
- break;
- }
- Py_DECREF(v2);
- }
- retval = v;
- break;
-
- case TYPE_CODE:
- if (PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError,
- "cannot unmarshal code objects in "
- "restricted execution mode");
- retval = NULL;
- break;
- }
- else {
- int argcount;
- int nlocals;
- int stacksize;
- int flags;
- PyObject *code = NULL;
- PyObject *consts = NULL;
- PyObject *names = NULL;
- PyObject *varnames = NULL;
- PyObject *freevars = NULL;
- PyObject *cellvars = NULL;
- PyObject *filename = NULL;
- PyObject *name = NULL;
- int firstlineno;
- PyObject *lnotab = NULL;
-
- v = NULL;
-
- /* XXX ignore long->int overflows for now */
- argcount = (int)r_long(p);
- nlocals = (int)r_long(p);
- stacksize = (int)r_long(p);
- flags = (int)r_long(p);
- code = r_object(p);
- if (code == NULL)
- goto code_error;
- consts = r_object(p);
- if (consts == NULL)
- goto code_error;
- names = r_object(p);
- if (names == NULL)
- goto code_error;
- varnames = r_object(p);
- if (varnames == NULL)
- goto code_error;
- freevars = r_object(p);
- if (freevars == NULL)
- goto code_error;
- cellvars = r_object(p);
- if (cellvars == NULL)
- goto code_error;
- filename = r_object(p);
- if (filename == NULL)
- goto code_error;
- name = r_object(p);
- if (name == NULL)
- goto code_error;
- firstlineno = (int)r_long(p);
- lnotab = r_object(p);
- if (lnotab == NULL)
- goto code_error;
-
- v = (PyObject *) PyCode_New(
- argcount, nlocals, stacksize, flags,
- code, consts, names, varnames,
- freevars, cellvars, filename, name,
- firstlineno, lnotab);
-
- code_error:
- Py_XDECREF(code);
- Py_XDECREF(consts);
- Py_XDECREF(names);
- Py_XDECREF(varnames);
- Py_XDECREF(freevars);
- Py_XDECREF(cellvars);
- Py_XDECREF(filename);
- Py_XDECREF(name);
- Py_XDECREF(lnotab);
-
- }
- retval = v;
- break;
-
- default:
- /* Bogus data got written, which isn't ideal.
- This will let you keep working and recover. */
- PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)");
- retval = NULL;
- break;
-
- }
- p->depth--;
- return retval;
+ case TYPE_TUPLE:
+ n = r_long(p);
+ if (n < 0 || n > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (tuple size out of range)");
+ retval = NULL;
+ break;
+ }
+ v = PyTuple_New((int)n);
+ if (v == NULL) {
+ retval = NULL;
+ break;
+ }
+ for (i = 0; i < n; i++) {
+ v2 = r_object(p);
+ if ( v2 == NULL ) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_TypeError,
+ "NULL object in marshal data for tuple");
+ Py_DECREF(v);
+ v = NULL;
+ break;
+ }
+ PyTuple_SET_ITEM(v, (int)i, v2);
+ }
+ retval = v;
+ break;
+
+ case TYPE_LIST:
+ n = r_long(p);
+ if (n < 0 || n > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (list size out of range)");
+ retval = NULL;
+ break;
+ }
+ v = PyList_New((int)n);
+ if (v == NULL) {
+ retval = NULL;
+ break;
+ }
+ for (i = 0; i < n; i++) {
+ v2 = r_object(p);
+ if ( v2 == NULL ) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_TypeError,
+ "NULL object in marshal data for list");
+ Py_DECREF(v);
+ v = NULL;
+ break;
+ }
+ PyList_SET_ITEM(v, (int)i, v2);
+ }
+ retval = v;
+ break;
+
+ case TYPE_DICT:
+ v = PyDict_New();
+ if (v == NULL) {
+ retval = NULL;
+ break;
+ }
+ for (;;) {
+ PyObject *key, *val;
+ key = r_object(p);
+ if (key == NULL)
+ break;
+ val = r_object(p);
+ if (val != NULL)
+ PyDict_SetItem(v, key, val);
+ Py_DECREF(key);
+ Py_XDECREF(val);
+ }
+ if (PyErr_Occurred()) {
+ Py_DECREF(v);
+ v = NULL;
+ }
+ retval = v;
+ break;
+
+ case TYPE_SET:
+ case TYPE_FROZENSET:
+ n = r_long(p);
+ if (n < 0 || n > INT_MAX) {
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (set size out of range)");
+ retval = NULL;
+ break;
+ }
+ v = (type == TYPE_SET) ? PySet_New(NULL) : PyFrozenSet_New(NULL);
+ if (v == NULL) {
+ retval = NULL;
+ break;
+ }
+ for (i = 0; i < n; i++) {
+ v2 = r_object(p);
+ if ( v2 == NULL ) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_TypeError,
+ "NULL object in marshal data for set");
+ Py_DECREF(v);
+ v = NULL;
+ break;
+ }
+ if (PySet_Add(v, v2) == -1) {
+ Py_DECREF(v);
+ Py_DECREF(v2);
+ v = NULL;
+ break;
+ }
+ Py_DECREF(v2);
+ }
+ retval = v;
+ break;
+
+ case TYPE_CODE:
+ if (PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "cannot unmarshal code objects in "
+ "restricted execution mode");
+ retval = NULL;
+ break;
+ }
+ else {
+ int argcount;
+ int nlocals;
+ int stacksize;
+ int flags;
+ PyObject *code = NULL;
+ PyObject *consts = NULL;
+ PyObject *names = NULL;
+ PyObject *varnames = NULL;
+ PyObject *freevars = NULL;
+ PyObject *cellvars = NULL;
+ PyObject *filename = NULL;
+ PyObject *name = NULL;
+ int firstlineno;
+ PyObject *lnotab = NULL;
+
+ v = NULL;
+
+ /* XXX ignore long->int overflows for now */
+ argcount = (int)r_long(p);
+ nlocals = (int)r_long(p);
+ stacksize = (int)r_long(p);
+ flags = (int)r_long(p);
+ code = r_object(p);
+ if (code == NULL)
+ goto code_error;
+ consts = r_object(p);
+ if (consts == NULL)
+ goto code_error;
+ names = r_object(p);
+ if (names == NULL)
+ goto code_error;
+ varnames = r_object(p);
+ if (varnames == NULL)
+ goto code_error;
+ freevars = r_object(p);
+ if (freevars == NULL)
+ goto code_error;
+ cellvars = r_object(p);
+ if (cellvars == NULL)
+ goto code_error;
+ filename = r_object(p);
+ if (filename == NULL)
+ goto code_error;
+ name = r_object(p);
+ if (name == NULL)
+ goto code_error;
+ firstlineno = (int)r_long(p);
+ lnotab = r_object(p);
+ if (lnotab == NULL)
+ goto code_error;
+
+ v = (PyObject *) PyCode_New(
+ argcount, nlocals, stacksize, flags,
+ code, consts, names, varnames,
+ freevars, cellvars, filename, name,
+ firstlineno, lnotab);
+
+ code_error:
+ Py_XDECREF(code);
+ Py_XDECREF(consts);
+ Py_XDECREF(names);
+ Py_XDECREF(varnames);
+ Py_XDECREF(freevars);
+ Py_XDECREF(cellvars);
+ Py_XDECREF(filename);
+ Py_XDECREF(name);
+ Py_XDECREF(lnotab);
+
+ }
+ retval = v;
+ break;
+
+ default:
+ /* Bogus data got written, which isn't ideal.
+ This will let you keep working and recover. */
+ PyErr_SetString(PyExc_ValueError, "bad marshal data (unknown type code)");
+ retval = NULL;
+ break;
+
+ }
+ p->depth--;
+ return retval;
}
static PyObject *
read_object(RFILE *p)
{
- PyObject *v;
- if (PyErr_Occurred()) {
- fprintf(stderr, "XXX readobject called with exception set\n");
- return NULL;
- }
- v = r_object(p);
- if (v == NULL && !PyErr_Occurred())
- PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");
- return v;
+ PyObject *v;
+ if (PyErr_Occurred()) {
+ fprintf(stderr, "XXX readobject called with exception set\n");
+ return NULL;
+ }
+ v = r_object(p);
+ if (v == NULL && !PyErr_Occurred())
+ PyErr_SetString(PyExc_TypeError, "NULL object in marshal data for object");
+ return v;
}
int
PyMarshal_ReadShortFromFile(FILE *fp)
{
- RFILE rf;
- assert(fp);
- rf.fp = fp;
- rf.strings = NULL;
- rf.end = rf.ptr = NULL;
- return r_short(&rf);
+ RFILE rf;
+ assert(fp);
+ rf.fp = fp;
+ rf.strings = NULL;
+ rf.end = rf.ptr = NULL;
+ return r_short(&rf);
}
long
PyMarshal_ReadLongFromFile(FILE *fp)
{
- RFILE rf;
- rf.fp = fp;
- rf.strings = NULL;
- rf.ptr = rf.end = NULL;
- return r_long(&rf);
+ RFILE rf;
+ rf.fp = fp;
+ rf.strings = NULL;
+ rf.ptr = rf.end = NULL;
+ return r_long(&rf);
}
#ifdef HAVE_FSTAT
@@ -1109,11 +1109,11 @@ PyMarshal_ReadLongFromFile(FILE *fp)
static off_t
getfilesize(FILE *fp)
{
- struct stat st;
- if (fstat(fileno(fp), &st) != 0)
- return -1;
- else
- return st.st_size;
+ struct stat st;
+ if (fstat(fileno(fp), &st) != 0)
+ return -1;
+ else
+ return st.st_size;
}
#endif
@@ -1129,27 +1129,27 @@ PyMarshal_ReadLastObjectFromFile(FILE *fp)
/* REASONABLE_FILE_LIMIT is by defn something big enough for Tkinter.pyc. */
#define REASONABLE_FILE_LIMIT (1L << 18)
#ifdef HAVE_FSTAT
- off_t filesize;
- filesize = getfilesize(fp);
- if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) {
- char* pBuf = (char *)PyMem_MALLOC(filesize);
- if (pBuf != NULL) {
- PyObject* v;
- size_t n;
- /* filesize must fit into an int, because it
- is smaller than REASONABLE_FILE_LIMIT */
- n = fread(pBuf, 1, (int)filesize, fp);
- v = PyMarshal_ReadObjectFromString(pBuf, n);
- PyMem_FREE(pBuf);
- return v;
- }
-
- }
+ off_t filesize;
+ filesize = getfilesize(fp);
+ if (filesize > 0 && filesize <= REASONABLE_FILE_LIMIT) {
+ char* pBuf = (char *)PyMem_MALLOC(filesize);
+ if (pBuf != NULL) {
+ PyObject* v;
+ size_t n;
+ /* filesize must fit into an int, because it
+ is smaller than REASONABLE_FILE_LIMIT */
+ n = fread(pBuf, 1, (int)filesize, fp);
+ v = PyMarshal_ReadObjectFromString(pBuf, n);
+ PyMem_FREE(pBuf);
+ return v;
+ }
+
+ }
#endif
- /* We don't have fstat, or we do but the file is larger than
- * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time.
- */
- return PyMarshal_ReadObjectFromFile(fp);
+ /* We don't have fstat, or we do but the file is larger than
+ * REASONABLE_FILE_LIMIT or malloc failed -- read a byte at a time.
+ */
+ return PyMarshal_ReadObjectFromFile(fp);
#undef REASONABLE_FILE_LIMIT
}
@@ -1157,83 +1157,83 @@ PyMarshal_ReadLastObjectFromFile(FILE *fp)
PyObject *
PyMarshal_ReadObjectFromFile(FILE *fp)
{
- RFILE rf;
- PyObject *result;
- rf.fp = fp;
- rf.strings = PyList_New(0);
- rf.depth = 0;
- rf.ptr = rf.end = NULL;
- result = r_object(&rf);
- Py_DECREF(rf.strings);
- return result;
+ RFILE rf;
+ PyObject *result;
+ rf.fp = fp;
+ rf.strings = PyList_New(0);
+ rf.depth = 0;
+ rf.ptr = rf.end = NULL;
+ result = r_object(&rf);
+ Py_DECREF(rf.strings);
+ return result;
}
PyObject *
PyMarshal_ReadObjectFromString(char *str, Py_ssize_t len)
{
- RFILE rf;
- PyObject *result;
- rf.fp = NULL;
- rf.ptr = str;
- rf.end = str + len;
- rf.strings = PyList_New(0);
- rf.depth = 0;
- result = r_object(&rf);
- Py_DECREF(rf.strings);
- return result;
+ RFILE rf;
+ PyObject *result;
+ rf.fp = NULL;
+ rf.ptr = str;
+ rf.end = str + len;
+ rf.strings = PyList_New(0);
+ rf.depth = 0;
+ result = r_object(&rf);
+ Py_DECREF(rf.strings);
+ return result;
}
static void
set_error(int error)
{
- switch (error) {
- case WFERR_NOMEMORY:
- PyErr_NoMemory();
- break;
- case WFERR_UNMARSHALLABLE:
- PyErr_SetString(PyExc_ValueError, "unmarshallable object");
- break;
- case WFERR_NESTEDTOODEEP:
- default:
- PyErr_SetString(PyExc_ValueError,
- "object too deeply nested to marshal");
- break;
- }
+ switch (error) {
+ case WFERR_NOMEMORY:
+ PyErr_NoMemory();
+ break;
+ case WFERR_UNMARSHALLABLE:
+ PyErr_SetString(PyExc_ValueError, "unmarshallable object");
+ break;
+ case WFERR_NESTEDTOODEEP:
+ default:
+ PyErr_SetString(PyExc_ValueError,
+ "object too deeply nested to marshal");
+ break;
+ }
}
PyObject *
PyMarshal_WriteObjectToString(PyObject *x, int version)
{
- WFILE wf;
- wf.fp = NULL;
- wf.str = PyString_FromStringAndSize((char *)NULL, 50);
- if (wf.str == NULL)
- return NULL;
- wf.ptr = PyString_AS_STRING((PyStringObject *)wf.str);
- wf.end = wf.ptr + PyString_Size(wf.str);
- wf.error = WFERR_OK;
- wf.depth = 0;
- wf.version = version;
- wf.strings = (version > 0) ? PyDict_New() : NULL;
- w_object(x, &wf);
- Py_XDECREF(wf.strings);
- if (wf.str != NULL) {
- char *base = PyString_AS_STRING((PyStringObject *)wf.str);
- if (wf.ptr - base > PY_SSIZE_T_MAX) {
- Py_DECREF(wf.str);
- PyErr_SetString(PyExc_OverflowError,
- "too much marshall data for a string");
- return NULL;
- }
- if (_PyString_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)))
- return NULL;
- }
- if (wf.error != WFERR_OK) {
- Py_XDECREF(wf.str);
- set_error(wf.error);
- return NULL;
- }
- return wf.str;
+ WFILE wf;
+ wf.fp = NULL;
+ wf.str = PyString_FromStringAndSize((char *)NULL, 50);
+ if (wf.str == NULL)
+ return NULL;
+ wf.ptr = PyString_AS_STRING((PyStringObject *)wf.str);
+ wf.end = wf.ptr + PyString_Size(wf.str);
+ wf.error = WFERR_OK;
+ wf.depth = 0;
+ wf.version = version;
+ wf.strings = (version > 0) ? PyDict_New() : NULL;
+ w_object(x, &wf);
+ Py_XDECREF(wf.strings);
+ if (wf.str != NULL) {
+ char *base = PyString_AS_STRING((PyStringObject *)wf.str);
+ if (wf.ptr - base > PY_SSIZE_T_MAX) {
+ Py_DECREF(wf.str);
+ PyErr_SetString(PyExc_OverflowError,
+ "too much marshall data for a string");
+ return NULL;
+ }
+ if (_PyString_Resize(&wf.str, (Py_ssize_t)(wf.ptr - base)))
+ return NULL;
+ }
+ if (wf.error != WFERR_OK) {
+ Py_XDECREF(wf.str);
+ set_error(wf.error);
+ return NULL;
+ }
+ return wf.str;
}
/* And an interface for Python programs... */
@@ -1241,32 +1241,32 @@ PyMarshal_WriteObjectToString(PyObject *x, int version)
static PyObject *
marshal_dump(PyObject *self, PyObject *args)
{
- WFILE wf;
- PyObject *x;
- PyObject *f;
- int version = Py_MARSHAL_VERSION;
- if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version))
- return NULL;
- if (!PyFile_Check(f)) {
- PyErr_SetString(PyExc_TypeError,
- "marshal.dump() 2nd arg must be file");
- return NULL;
- }
- wf.fp = PyFile_AsFile(f);
- wf.str = NULL;
- wf.ptr = wf.end = NULL;
- wf.error = WFERR_OK;
- wf.depth = 0;
- wf.strings = (version > 0) ? PyDict_New() : 0;
- wf.version = version;
- w_object(x, &wf);
- Py_XDECREF(wf.strings);
- if (wf.error != WFERR_OK) {
- set_error(wf.error);
- return NULL;
- }
- Py_INCREF(Py_None);
- return Py_None;
+ WFILE wf;
+ PyObject *x;
+ PyObject *f;
+ int version = Py_MARSHAL_VERSION;
+ if (!PyArg_ParseTuple(args, "OO|i:dump", &x, &f, &version))
+ return NULL;
+ if (!PyFile_Check(f)) {
+ PyErr_SetString(PyExc_TypeError,
+ "marshal.dump() 2nd arg must be file");
+ return NULL;
+ }
+ wf.fp = PyFile_AsFile(f);
+ wf.str = NULL;
+ wf.ptr = wf.end = NULL;
+ wf.error = WFERR_OK;
+ wf.depth = 0;
+ wf.strings = (version > 0) ? PyDict_New() : 0;
+ wf.version = version;
+ w_object(x, &wf);
+ Py_XDECREF(wf.strings);
+ if (wf.error != WFERR_OK) {
+ set_error(wf.error);
+ return NULL;
+ }
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(dump_doc,
@@ -1286,19 +1286,19 @@ dump should use.");
static PyObject *
marshal_load(PyObject *self, PyObject *f)
{
- RFILE rf;
- PyObject *result;
- if (!PyFile_Check(f)) {
- PyErr_SetString(PyExc_TypeError,
- "marshal.load() arg must be file");
- return NULL;
- }
- rf.fp = PyFile_AsFile(f);
- rf.strings = PyList_New(0);
- rf.depth = 0;
- result = read_object(&rf);
- Py_DECREF(rf.strings);
- return result;
+ RFILE rf;
+ PyObject *result;
+ if (!PyFile_Check(f)) {
+ PyErr_SetString(PyExc_TypeError,
+ "marshal.load() arg must be file");
+ return NULL;
+ }
+ rf.fp = PyFile_AsFile(f);
+ rf.strings = PyList_New(0);
+ rf.depth = 0;
+ result = read_object(&rf);
+ Py_DECREF(rf.strings);
+ return result;
}
PyDoc_STRVAR(load_doc,
@@ -1317,11 +1317,11 @@ dump(), load() will substitute None for the unmarshallable type.");
static PyObject *
marshal_dumps(PyObject *self, PyObject *args)
{
- PyObject *x;
- int version = Py_MARSHAL_VERSION;
- if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version))
- return NULL;
- return PyMarshal_WriteObjectToString(x, version);
+ PyObject *x;
+ int version = Py_MARSHAL_VERSION;
+ if (!PyArg_ParseTuple(args, "O|i:dumps", &x, &version))
+ return NULL;
+ return PyMarshal_WriteObjectToString(x, version);
}
PyDoc_STRVAR(dumps_doc,
@@ -1338,20 +1338,20 @@ dumps should use.");
static PyObject *
marshal_loads(PyObject *self, PyObject *args)
{
- RFILE rf;
- char *s;
- Py_ssize_t n;
- PyObject* result;
- if (!PyArg_ParseTuple(args, "s#:loads", &s, &n))
- return NULL;
- rf.fp = NULL;
- rf.ptr = s;
- rf.end = s + n;
- rf.strings = PyList_New(0);
- rf.depth = 0;
- result = read_object(&rf);
- Py_DECREF(rf.strings);
- return result;
+ RFILE rf;
+ char *s;
+ Py_ssize_t n;
+ PyObject* result;
+ if (!PyArg_ParseTuple(args, "s#:loads", &s, &n))
+ return NULL;
+ rf.fp = NULL;
+ rf.ptr = s;
+ rf.end = s + n;
+ rf.strings = PyList_New(0);
+ rf.depth = 0;
+ result = read_object(&rf);
+ Py_DECREF(rf.strings);
+ return result;
}
PyDoc_STRVAR(loads_doc,
@@ -1362,11 +1362,11 @@ EOFError, ValueError or TypeError. Extra characters in the string are\n\
ignored.");
static PyMethodDef marshal_methods[] = {
- {"dump", marshal_dump, METH_VARARGS, dump_doc},
- {"load", marshal_load, METH_O, load_doc},
- {"dumps", marshal_dumps, METH_VARARGS, dumps_doc},
- {"loads", marshal_loads, METH_VARARGS, loads_doc},
- {NULL, NULL} /* sentinel */
+ {"dump", marshal_dump, METH_VARARGS, dump_doc},
+ {"load", marshal_load, METH_O, load_doc},
+ {"dumps", marshal_dumps, METH_VARARGS, dumps_doc},
+ {"loads", marshal_loads, METH_VARARGS, loads_doc},
+ {NULL, NULL} /* sentinel */
};
PyDoc_STRVAR(marshal_doc,
@@ -1402,9 +1402,9 @@ loads() -- read value from a string");
PyMODINIT_FUNC
PyMarshal_Init(void)
{
- PyObject *mod = Py_InitModule3("marshal", marshal_methods,
- marshal_doc);
- if (mod == NULL)
- return;
- PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION);
+ PyObject *mod = Py_InitModule3("marshal", marshal_methods,
+ marshal_doc);
+ if (mod == NULL)
+ return;
+ PyModule_AddIntConstant(mod, "version", Py_MARSHAL_VERSION);
}
diff --git a/Python/modsupport.c b/Python/modsupport.c
index d54158f..6ee48f3 100644
--- a/Python/modsupport.c
+++ b/Python/modsupport.c
@@ -30,76 +30,76 @@ static char api_version_warning[] =
PyObject *
Py_InitModule4(const char *name, PyMethodDef *methods, const char *doc,
- PyObject *passthrough, int module_api_version)
+ PyObject *passthrough, int module_api_version)
{
- PyObject *m, *d, *v, *n;
- PyMethodDef *ml;
- if (!Py_IsInitialized())
- Py_FatalError("Interpreter not initialized (version mismatch?)");
- if (module_api_version != PYTHON_API_VERSION) {
- char message[512];
- PyOS_snprintf(message, sizeof(message),
- api_version_warning, name,
- PYTHON_API_VERSION, name,
- module_api_version);
- if (PyErr_Warn(PyExc_RuntimeWarning, message))
- return NULL;
- }
- /* Make sure name is fully qualified.
-
- This is a bit of a hack: when the shared library is loaded,
- the module name is "package.module", but the module calls
- Py_InitModule*() with just "module" for the name. The shared
- library loader squirrels away the true name of the module in
- _Py_PackageContext, and Py_InitModule*() will substitute this
- (if the name actually matches).
- */
- if (_Py_PackageContext != NULL) {
- char *p = strrchr(_Py_PackageContext, '.');
- if (p != NULL && strcmp(name, p+1) == 0) {
- name = _Py_PackageContext;
- _Py_PackageContext = NULL;
- }
- }
- if ((m = PyImport_AddModule(name)) == NULL)
- return NULL;
- d = PyModule_GetDict(m);
- if (methods != NULL) {
- n = PyString_FromString(name);
- if (n == NULL)
- return NULL;
- for (ml = methods; ml->ml_name != NULL; ml++) {
- if ((ml->ml_flags & METH_CLASS) ||
- (ml->ml_flags & METH_STATIC)) {
- PyErr_SetString(PyExc_ValueError,
- "module functions cannot set"
- " METH_CLASS or METH_STATIC");
- Py_DECREF(n);
- return NULL;
- }
- v = PyCFunction_NewEx(ml, passthrough, n);
- if (v == NULL) {
- Py_DECREF(n);
- return NULL;
- }
- if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
- Py_DECREF(v);
- Py_DECREF(n);
- return NULL;
- }
- Py_DECREF(v);
- }
- Py_DECREF(n);
- }
- if (doc != NULL) {
- v = PyString_FromString(doc);
- if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
- Py_XDECREF(v);
- return NULL;
- }
- Py_DECREF(v);
- }
- return m;
+ PyObject *m, *d, *v, *n;
+ PyMethodDef *ml;
+ if (!Py_IsInitialized())
+ Py_FatalError("Interpreter not initialized (version mismatch?)");
+ if (module_api_version != PYTHON_API_VERSION) {
+ char message[512];
+ PyOS_snprintf(message, sizeof(message),
+ api_version_warning, name,
+ PYTHON_API_VERSION, name,
+ module_api_version);
+ if (PyErr_Warn(PyExc_RuntimeWarning, message))
+ return NULL;
+ }
+ /* Make sure name is fully qualified.
+
+ This is a bit of a hack: when the shared library is loaded,
+ the module name is "package.module", but the module calls
+ Py_InitModule*() with just "module" for the name. The shared
+ library loader squirrels away the true name of the module in
+ _Py_PackageContext, and Py_InitModule*() will substitute this
+ (if the name actually matches).
+ */
+ if (_Py_PackageContext != NULL) {
+ char *p = strrchr(_Py_PackageContext, '.');
+ if (p != NULL && strcmp(name, p+1) == 0) {
+ name = _Py_PackageContext;
+ _Py_PackageContext = NULL;
+ }
+ }
+ if ((m = PyImport_AddModule(name)) == NULL)
+ return NULL;
+ d = PyModule_GetDict(m);
+ if (methods != NULL) {
+ n = PyString_FromString(name);
+ if (n == NULL)
+ return NULL;
+ for (ml = methods; ml->ml_name != NULL; ml++) {
+ if ((ml->ml_flags & METH_CLASS) ||
+ (ml->ml_flags & METH_STATIC)) {
+ PyErr_SetString(PyExc_ValueError,
+ "module functions cannot set"
+ " METH_CLASS or METH_STATIC");
+ Py_DECREF(n);
+ return NULL;
+ }
+ v = PyCFunction_NewEx(ml, passthrough, n);
+ if (v == NULL) {
+ Py_DECREF(n);
+ return NULL;
+ }
+ if (PyDict_SetItemString(d, ml->ml_name, v) != 0) {
+ Py_DECREF(v);
+ Py_DECREF(n);
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ Py_DECREF(n);
+ }
+ if (doc != NULL) {
+ v = PyString_FromString(doc);
+ if (v == NULL || PyDict_SetItemString(d, "__doc__", v) != 0) {
+ Py_XDECREF(v);
+ return NULL;
+ }
+ Py_DECREF(v);
+ }
+ return m;
}
@@ -108,41 +108,41 @@ Py_InitModule4(const char *name, PyMethodDef *methods, const char *doc,
static int
countformat(const char *format, int endchar)
{
- int count = 0;
- int level = 0;
- while (level > 0 || *format != endchar) {
- switch (*format) {
- case '\0':
- /* Premature end */
- PyErr_SetString(PyExc_SystemError,
- "unmatched paren in format");
- return -1;
- case '(':
- case '[':
- case '{':
- if (level == 0)
- count++;
- level++;
- break;
- case ')':
- case ']':
- case '}':
- level--;
- break;
- case '#':
- case '&':
- case ',':
- case ':':
- case ' ':
- case '\t':
- break;
- default:
- if (level == 0)
- count++;
- }
- format++;
- }
- return count;
+ int count = 0;
+ int level = 0;
+ while (level > 0 || *format != endchar) {
+ switch (*format) {
+ case '\0':
+ /* Premature end */
+ PyErr_SetString(PyExc_SystemError,
+ "unmatched paren in format");
+ return -1;
+ case '(':
+ case '[':
+ case '{':
+ if (level == 0)
+ count++;
+ level++;
+ break;
+ case ')':
+ case ']':
+ case '}':
+ level--;
+ break;
+ case '#':
+ case '&':
+ case ',':
+ case ':':
+ case ' ':
+ case '\t':
+ break;
+ default:
+ if (level == 0)
+ count++;
+ }
+ format++;
+ }
+ return count;
}
@@ -158,486 +158,486 @@ static PyObject *do_mkvalue(const char**, va_list *, int);
static PyObject *
do_mkdict(const char **p_format, va_list *p_va, int endchar, int n, int flags)
{
- PyObject *d;
- int i;
- int itemfailed = 0;
- if (n < 0)
- return NULL;
- if ((d = PyDict_New()) == NULL)
- return NULL;
- /* Note that we can't bail immediately on error as this will leak
- refcounts on any 'N' arguments. */
- for (i = 0; i < n; i+= 2) {
- PyObject *k, *v;
- int err;
- k = do_mkvalue(p_format, p_va, flags);
- if (k == NULL) {
- itemfailed = 1;
- Py_INCREF(Py_None);
- k = Py_None;
- }
- v = do_mkvalue(p_format, p_va, flags);
- if (v == NULL) {
- itemfailed = 1;
- Py_INCREF(Py_None);
- v = Py_None;
- }
- err = PyDict_SetItem(d, k, v);
- Py_DECREF(k);
- Py_DECREF(v);
- if (err < 0 || itemfailed) {
- Py_DECREF(d);
- return NULL;
- }
- }
- if (d != NULL && **p_format != endchar) {
- Py_DECREF(d);
- d = NULL;
- PyErr_SetString(PyExc_SystemError,
- "Unmatched paren in format");
- }
- else if (endchar)
- ++*p_format;
- return d;
+ PyObject *d;
+ int i;
+ int itemfailed = 0;
+ if (n < 0)
+ return NULL;
+ if ((d = PyDict_New()) == NULL)
+ return NULL;
+ /* Note that we can't bail immediately on error as this will leak
+ refcounts on any 'N' arguments. */
+ for (i = 0; i < n; i+= 2) {
+ PyObject *k, *v;
+ int err;
+ k = do_mkvalue(p_format, p_va, flags);
+ if (k == NULL) {
+ itemfailed = 1;
+ Py_INCREF(Py_None);
+ k = Py_None;
+ }
+ v = do_mkvalue(p_format, p_va, flags);
+ if (v == NULL) {
+ itemfailed = 1;
+ Py_INCREF(Py_None);
+ v = Py_None;
+ }
+ err = PyDict_SetItem(d, k, v);
+ Py_DECREF(k);
+ Py_DECREF(v);
+ if (err < 0 || itemfailed) {
+ Py_DECREF(d);
+ return NULL;
+ }
+ }
+ if (d != NULL && **p_format != endchar) {
+ Py_DECREF(d);
+ d = NULL;
+ PyErr_SetString(PyExc_SystemError,
+ "Unmatched paren in format");
+ }
+ else if (endchar)
+ ++*p_format;
+ return d;
}
static PyObject *
do_mklist(const char **p_format, va_list *p_va, int endchar, int n, int flags)
{
- PyObject *v;
- int i;
- int itemfailed = 0;
- if (n < 0)
- return NULL;
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- /* Note that we can't bail immediately on error as this will leak
- refcounts on any 'N' arguments. */
- for (i = 0; i < n; i++) {
- PyObject *w = do_mkvalue(p_format, p_va, flags);
- if (w == NULL) {
- itemfailed = 1;
- Py_INCREF(Py_None);
- w = Py_None;
- }
- PyList_SET_ITEM(v, i, w);
- }
-
- if (itemfailed) {
- /* do_mkvalue() should have already set an error */
- Py_DECREF(v);
- return NULL;
- }
- if (**p_format != endchar) {
- Py_DECREF(v);
- PyErr_SetString(PyExc_SystemError,
- "Unmatched paren in format");
- return NULL;
- }
- if (endchar)
- ++*p_format;
- return v;
+ PyObject *v;
+ int i;
+ int itemfailed = 0;
+ if (n < 0)
+ return NULL;
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ /* Note that we can't bail immediately on error as this will leak
+ refcounts on any 'N' arguments. */
+ for (i = 0; i < n; i++) {
+ PyObject *w = do_mkvalue(p_format, p_va, flags);
+ if (w == NULL) {
+ itemfailed = 1;
+ Py_INCREF(Py_None);
+ w = Py_None;
+ }
+ PyList_SET_ITEM(v, i, w);
+ }
+
+ if (itemfailed) {
+ /* do_mkvalue() should have already set an error */
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (**p_format != endchar) {
+ Py_DECREF(v);
+ PyErr_SetString(PyExc_SystemError,
+ "Unmatched paren in format");
+ return NULL;
+ }
+ if (endchar)
+ ++*p_format;
+ return v;
}
#ifdef Py_USING_UNICODE
static int
_ustrlen(Py_UNICODE *u)
{
- int i = 0;
- Py_UNICODE *v = u;
- while (*v != 0) { i++; v++; }
- return i;
+ int i = 0;
+ Py_UNICODE *v = u;
+ while (*v != 0) { i++; v++; }
+ return i;
}
#endif
static PyObject *
do_mktuple(const char **p_format, va_list *p_va, int endchar, int n, int flags)
{
- PyObject *v;
- int i;
- int itemfailed = 0;
- if (n < 0)
- return NULL;
- if ((v = PyTuple_New(n)) == NULL)
- return NULL;
- /* Note that we can't bail immediately on error as this will leak
- refcounts on any 'N' arguments. */
- for (i = 0; i < n; i++) {
- PyObject *w = do_mkvalue(p_format, p_va, flags);
- if (w == NULL) {
- itemfailed = 1;
- Py_INCREF(Py_None);
- w = Py_None;
- }
- PyTuple_SET_ITEM(v, i, w);
- }
- if (itemfailed) {
- /* do_mkvalue() should have already set an error */
- Py_DECREF(v);
- return NULL;
- }
- if (**p_format != endchar) {
- Py_DECREF(v);
- PyErr_SetString(PyExc_SystemError,
- "Unmatched paren in format");
- return NULL;
- }
- if (endchar)
- ++*p_format;
- return v;
+ PyObject *v;
+ int i;
+ int itemfailed = 0;
+ if (n < 0)
+ return NULL;
+ if ((v = PyTuple_New(n)) == NULL)
+ return NULL;
+ /* Note that we can't bail immediately on error as this will leak
+ refcounts on any 'N' arguments. */
+ for (i = 0; i < n; i++) {
+ PyObject *w = do_mkvalue(p_format, p_va, flags);
+ if (w == NULL) {
+ itemfailed = 1;
+ Py_INCREF(Py_None);
+ w = Py_None;
+ }
+ PyTuple_SET_ITEM(v, i, w);
+ }
+ if (itemfailed) {
+ /* do_mkvalue() should have already set an error */
+ Py_DECREF(v);
+ return NULL;
+ }
+ if (**p_format != endchar) {
+ Py_DECREF(v);
+ PyErr_SetString(PyExc_SystemError,
+ "Unmatched paren in format");
+ return NULL;
+ }
+ if (endchar)
+ ++*p_format;
+ return v;
}
static PyObject *
do_mkvalue(const char **p_format, va_list *p_va, int flags)
{
- for (;;) {
- switch (*(*p_format)++) {
- case '(':
- return do_mktuple(p_format, p_va, ')',
- countformat(*p_format, ')'), flags);
-
- case '[':
- return do_mklist(p_format, p_va, ']',
- countformat(*p_format, ']'), flags);
-
- case '{':
- return do_mkdict(p_format, p_va, '}',
- countformat(*p_format, '}'), flags);
-
- case 'b':
- case 'B':
- case 'h':
- case 'i':
- return PyInt_FromLong((long)va_arg(*p_va, int));
-
- case 'H':
- return PyInt_FromLong((long)va_arg(*p_va, unsigned int));
-
- case 'I':
- {
- unsigned int n;
- n = va_arg(*p_va, unsigned int);
- if (n > (unsigned long)PyInt_GetMax())
- return PyLong_FromUnsignedLong((unsigned long)n);
- else
- return PyInt_FromLong(n);
- }
-
- case 'n':
+ for (;;) {
+ switch (*(*p_format)++) {
+ case '(':
+ return do_mktuple(p_format, p_va, ')',
+ countformat(*p_format, ')'), flags);
+
+ case '[':
+ return do_mklist(p_format, p_va, ']',
+ countformat(*p_format, ']'), flags);
+
+ case '{':
+ return do_mkdict(p_format, p_va, '}',
+ countformat(*p_format, '}'), flags);
+
+ case 'b':
+ case 'B':
+ case 'h':
+ case 'i':
+ return PyInt_FromLong((long)va_arg(*p_va, int));
+
+ case 'H':
+ return PyInt_FromLong((long)va_arg(*p_va, unsigned int));
+
+ case 'I':
+ {
+ unsigned int n;
+ n = va_arg(*p_va, unsigned int);
+ if (n > (unsigned long)PyInt_GetMax())
+ return PyLong_FromUnsignedLong((unsigned long)n);
+ else
+ return PyInt_FromLong(n);
+ }
+
+ case 'n':
#if SIZEOF_SIZE_T!=SIZEOF_LONG
- return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t));
+ return PyInt_FromSsize_t(va_arg(*p_va, Py_ssize_t));
#endif
- /* Fall through from 'n' to 'l' if Py_ssize_t is long */
- case 'l':
- return PyInt_FromLong(va_arg(*p_va, long));
-
- case 'k':
- {
- unsigned long n;
- n = va_arg(*p_va, unsigned long);
- if (n > (unsigned long)PyInt_GetMax())
- return PyLong_FromUnsignedLong(n);
- else
- return PyInt_FromLong(n);
- }
+ /* Fall through from 'n' to 'l' if Py_ssize_t is long */
+ case 'l':
+ return PyInt_FromLong(va_arg(*p_va, long));
+
+ case 'k':
+ {
+ unsigned long n;
+ n = va_arg(*p_va, unsigned long);
+ if (n > (unsigned long)PyInt_GetMax())
+ return PyLong_FromUnsignedLong(n);
+ else
+ return PyInt_FromLong(n);
+ }
#ifdef HAVE_LONG_LONG
- case 'L':
- return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG));
+ case 'L':
+ return PyLong_FromLongLong((PY_LONG_LONG)va_arg(*p_va, PY_LONG_LONG));
- case 'K':
- return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG));
+ case 'K':
+ return PyLong_FromUnsignedLongLong((PY_LONG_LONG)va_arg(*p_va, unsigned PY_LONG_LONG));
#endif
#ifdef Py_USING_UNICODE
- case 'u':
- {
- PyObject *v;
- Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *);
- Py_ssize_t n;
- if (**p_format == '#') {
- ++*p_format;
- if (flags & FLAG_SIZE_T)
- n = va_arg(*p_va, Py_ssize_t);
- else
- n = va_arg(*p_va, int);
- }
- else
- n = -1;
- if (u == NULL) {
- v = Py_None;
- Py_INCREF(v);
- }
- else {
- if (n < 0)
- n = _ustrlen(u);
- v = PyUnicode_FromUnicode(u, n);
- }
- return v;
- }
+ case 'u':
+ {
+ PyObject *v;
+ Py_UNICODE *u = va_arg(*p_va, Py_UNICODE *);
+ Py_ssize_t n;
+ if (**p_format == '#') {
+ ++*p_format;
+ if (flags & FLAG_SIZE_T)
+ n = va_arg(*p_va, Py_ssize_t);
+ else
+ n = va_arg(*p_va, int);
+ }
+ else
+ n = -1;
+ if (u == NULL) {
+ v = Py_None;
+ Py_INCREF(v);
+ }
+ else {
+ if (n < 0)
+ n = _ustrlen(u);
+ v = PyUnicode_FromUnicode(u, n);
+ }
+ return v;
+ }
#endif
- case 'f':
- case 'd':
- return PyFloat_FromDouble(
- (double)va_arg(*p_va, va_double));
+ case 'f':
+ case 'd':
+ return PyFloat_FromDouble(
+ (double)va_arg(*p_va, va_double));
#ifndef WITHOUT_COMPLEX
- case 'D':
- return PyComplex_FromCComplex(
- *((Py_complex *)va_arg(*p_va, Py_complex *)));
+ case 'D':
+ return PyComplex_FromCComplex(
+ *((Py_complex *)va_arg(*p_va, Py_complex *)));
#endif /* WITHOUT_COMPLEX */
- case 'c':
- {
- char p[1];
- p[0] = (char)va_arg(*p_va, int);
- return PyString_FromStringAndSize(p, 1);
- }
-
- case 's':
- case 'z':
- {
- PyObject *v;
- char *str = va_arg(*p_va, char *);
- Py_ssize_t n;
- if (**p_format == '#') {
- ++*p_format;
- if (flags & FLAG_SIZE_T)
- n = va_arg(*p_va, Py_ssize_t);
- else
- n = va_arg(*p_va, int);
- }
- else
- n = -1;
- if (str == NULL) {
- v = Py_None;
- Py_INCREF(v);
- }
- else {
- if (n < 0) {
- size_t m = strlen(str);
- if (m > PY_SSIZE_T_MAX) {
- PyErr_SetString(PyExc_OverflowError,
- "string too long for Python string");
- return NULL;
- }
- n = (Py_ssize_t)m;
- }
- v = PyString_FromStringAndSize(str, n);
- }
- return v;
- }
-
- case 'N':
- case 'S':
- case 'O':
- if (**p_format == '&') {
- typedef PyObject *(*converter)(void *);
- converter func = va_arg(*p_va, converter);
- void *arg = va_arg(*p_va, void *);
- ++*p_format;
- return (*func)(arg);
- }
- else {
- PyObject *v;
- v = va_arg(*p_va, PyObject *);
- if (v != NULL) {
- if (*(*p_format - 1) != 'N')
- Py_INCREF(v);
- }
- else if (!PyErr_Occurred())
- /* If a NULL was passed
- * because a call that should
- * have constructed a value
- * failed, that's OK, and we
- * pass the error on; but if
- * no error occurred it's not
- * clear that the caller knew
- * what she was doing. */
- PyErr_SetString(PyExc_SystemError,
- "NULL object passed to Py_BuildValue");
- return v;
- }
-
- case ':':
- case ',':
- case ' ':
- case '\t':
- break;
-
- default:
- PyErr_SetString(PyExc_SystemError,
- "bad format char passed to Py_BuildValue");
- return NULL;
-
- }
- }
+ case 'c':
+ {
+ char p[1];
+ p[0] = (char)va_arg(*p_va, int);
+ return PyString_FromStringAndSize(p, 1);
+ }
+
+ case 's':
+ case 'z':
+ {
+ PyObject *v;
+ char *str = va_arg(*p_va, char *);
+ Py_ssize_t n;
+ if (**p_format == '#') {
+ ++*p_format;
+ if (flags & FLAG_SIZE_T)
+ n = va_arg(*p_va, Py_ssize_t);
+ else
+ n = va_arg(*p_va, int);
+ }
+ else
+ n = -1;
+ if (str == NULL) {
+ v = Py_None;
+ Py_INCREF(v);
+ }
+ else {
+ if (n < 0) {
+ size_t m = strlen(str);
+ if (m > PY_SSIZE_T_MAX) {
+ PyErr_SetString(PyExc_OverflowError,
+ "string too long for Python string");
+ return NULL;
+ }
+ n = (Py_ssize_t)m;
+ }
+ v = PyString_FromStringAndSize(str, n);
+ }
+ return v;
+ }
+
+ case 'N':
+ case 'S':
+ case 'O':
+ if (**p_format == '&') {
+ typedef PyObject *(*converter)(void *);
+ converter func = va_arg(*p_va, converter);
+ void *arg = va_arg(*p_va, void *);
+ ++*p_format;
+ return (*func)(arg);
+ }
+ else {
+ PyObject *v;
+ v = va_arg(*p_va, PyObject *);
+ if (v != NULL) {
+ if (*(*p_format - 1) != 'N')
+ Py_INCREF(v);
+ }
+ else if (!PyErr_Occurred())
+ /* If a NULL was passed
+ * because a call that should
+ * have constructed a value
+ * failed, that's OK, and we
+ * pass the error on; but if
+ * no error occurred it's not
+ * clear that the caller knew
+ * what she was doing. */
+ PyErr_SetString(PyExc_SystemError,
+ "NULL object passed to Py_BuildValue");
+ return v;
+ }
+
+ case ':':
+ case ',':
+ case ' ':
+ case '\t':
+ break;
+
+ default:
+ PyErr_SetString(PyExc_SystemError,
+ "bad format char passed to Py_BuildValue");
+ return NULL;
+
+ }
+ }
}
PyObject *
Py_BuildValue(const char *format, ...)
{
- va_list va;
- PyObject* retval;
- va_start(va, format);
- retval = va_build_value(format, va, 0);
- va_end(va);
- return retval;
+ va_list va;
+ PyObject* retval;
+ va_start(va, format);
+ retval = va_build_value(format, va, 0);
+ va_end(va);
+ return retval;
}
PyObject *
_Py_BuildValue_SizeT(const char *format, ...)
{
- va_list va;
- PyObject* retval;
- va_start(va, format);
- retval = va_build_value(format, va, FLAG_SIZE_T);
- va_end(va);
- return retval;
+ va_list va;
+ PyObject* retval;
+ va_start(va, format);
+ retval = va_build_value(format, va, FLAG_SIZE_T);
+ va_end(va);
+ return retval;
}
PyObject *
Py_VaBuildValue(const char *format, va_list va)
{
- return va_build_value(format, va, 0);
+ return va_build_value(format, va, 0);
}
PyObject *
_Py_VaBuildValue_SizeT(const char *format, va_list va)
{
- return va_build_value(format, va, FLAG_SIZE_T);
+ return va_build_value(format, va, FLAG_SIZE_T);
}
static PyObject *
va_build_value(const char *format, va_list va, int flags)
{
- const char *f = format;
- int n = countformat(f, '\0');
- va_list lva;
+ const char *f = format;
+ int n = countformat(f, '\0');
+ va_list lva;
#ifdef VA_LIST_IS_ARRAY
- memcpy(lva, va, sizeof(va_list));
+ memcpy(lva, va, sizeof(va_list));
#else
#ifdef __va_copy
- __va_copy(lva, va);
+ __va_copy(lva, va);
#else
- lva = va;
+ lva = va;
#endif
#endif
- if (n < 0)
- return NULL;
- if (n == 0) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (n == 1)
- return do_mkvalue(&f, &lva, flags);
- return do_mktuple(&f, &lva, '\0', n, flags);
+ if (n < 0)
+ return NULL;
+ if (n == 0) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (n == 1)
+ return do_mkvalue(&f, &lva, flags);
+ return do_mktuple(&f, &lva, '\0', n, flags);
}
PyObject *
PyEval_CallFunction(PyObject *obj, const char *format, ...)
{
- va_list vargs;
- PyObject *args;
- PyObject *res;
+ va_list vargs;
+ PyObject *args;
+ PyObject *res;
- va_start(vargs, format);
+ va_start(vargs, format);
- args = Py_VaBuildValue(format, vargs);
- va_end(vargs);
+ args = Py_VaBuildValue(format, vargs);
+ va_end(vargs);
- if (args == NULL)
- return NULL;
+ if (args == NULL)
+ return NULL;
- res = PyEval_CallObject(obj, args);
- Py_DECREF(args);
+ res = PyEval_CallObject(obj, args);
+ Py_DECREF(args);
- return res;
+ return res;
}
PyObject *
PyEval_CallMethod(PyObject *obj, const char *methodname, const char *format, ...)
{
- va_list vargs;
- PyObject *meth;
- PyObject *args;
- PyObject *res;
+ va_list vargs;
+ PyObject *meth;
+ PyObject *args;
+ PyObject *res;
- meth = PyObject_GetAttrString(obj, methodname);
- if (meth == NULL)
- return NULL;
+ meth = PyObject_GetAttrString(obj, methodname);
+ if (meth == NULL)
+ return NULL;
- va_start(vargs, format);
+ va_start(vargs, format);
- args = Py_VaBuildValue(format, vargs);
- va_end(vargs);
+ args = Py_VaBuildValue(format, vargs);
+ va_end(vargs);
- if (args == NULL) {
- Py_DECREF(meth);
- return NULL;
- }
+ if (args == NULL) {
+ Py_DECREF(meth);
+ return NULL;
+ }
- res = PyEval_CallObject(meth, args);
- Py_DECREF(meth);
- Py_DECREF(args);
+ res = PyEval_CallObject(meth, args);
+ Py_DECREF(meth);
+ Py_DECREF(args);
- return res;
+ return res;
}
int
PyModule_AddObject(PyObject *m, const char *name, PyObject *o)
{
- PyObject *dict;
- if (!PyModule_Check(m)) {
- PyErr_SetString(PyExc_TypeError,
- "PyModule_AddObject() needs module as first arg");
- return -1;
- }
- if (!o) {
- if (!PyErr_Occurred())
- PyErr_SetString(PyExc_TypeError,
- "PyModule_AddObject() needs non-NULL value");
- return -1;
- }
-
- dict = PyModule_GetDict(m);
- if (dict == NULL) {
- /* Internal error -- modules must have a dict! */
- PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
- PyModule_GetName(m));
- return -1;
- }
- if (PyDict_SetItemString(dict, name, o))
- return -1;
- Py_DECREF(o);
- return 0;
+ PyObject *dict;
+ if (!PyModule_Check(m)) {
+ PyErr_SetString(PyExc_TypeError,
+ "PyModule_AddObject() needs module as first arg");
+ return -1;
+ }
+ if (!o) {
+ if (!PyErr_Occurred())
+ PyErr_SetString(PyExc_TypeError,
+ "PyModule_AddObject() needs non-NULL value");
+ return -1;
+ }
+
+ dict = PyModule_GetDict(m);
+ if (dict == NULL) {
+ /* Internal error -- modules must have a dict! */
+ PyErr_Format(PyExc_SystemError, "module '%s' has no __dict__",
+ PyModule_GetName(m));
+ return -1;
+ }
+ if (PyDict_SetItemString(dict, name, o))
+ return -1;
+ Py_DECREF(o);
+ return 0;
}
-int
+int
PyModule_AddIntConstant(PyObject *m, const char *name, long value)
{
- PyObject *o = PyInt_FromLong(value);
- if (!o)
- return -1;
- if (PyModule_AddObject(m, name, o) == 0)
- return 0;
- Py_DECREF(o);
- return -1;
+ PyObject *o = PyInt_FromLong(value);
+ if (!o)
+ return -1;
+ if (PyModule_AddObject(m, name, o) == 0)
+ return 0;
+ Py_DECREF(o);
+ return -1;
}
-int
+int
PyModule_AddStringConstant(PyObject *m, const char *name, const char *value)
{
- PyObject *o = PyString_FromString(value);
- if (!o)
- return -1;
- if (PyModule_AddObject(m, name, o) == 0)
- return 0;
- Py_DECREF(o);
- return -1;
+ PyObject *o = PyString_FromString(value);
+ if (!o)
+ return -1;
+ if (PyModule_AddObject(m, name, o) == 0)
+ return 0;
+ Py_DECREF(o);
+ return -1;
}
diff --git a/Python/mysnprintf.c b/Python/mysnprintf.c
index 3173863..39e3ff1 100644
--- a/Python/mysnprintf.c
+++ b/Python/mysnprintf.c
@@ -20,20 +20,20 @@
Return value (rv):
- When 0 <= rv < size, the output conversion was unexceptional, and
- rv characters were written to str (excluding a trailing \0 byte at
- str[rv]).
+ When 0 <= rv < size, the output conversion was unexceptional, and
+ rv characters were written to str (excluding a trailing \0 byte at
+ str[rv]).
- When rv >= size, output conversion was truncated, and a buffer of
- size rv+1 would have been needed to avoid truncation. str[size-1]
- is \0 in this case.
+ When rv >= size, output conversion was truncated, and a buffer of
+ size rv+1 would have been needed to avoid truncation. str[size-1]
+ is \0 in this case.
- When rv < 0, "something bad happened". str[size-1] is \0 in this
- case too, but the rest of str is unreliable. It could be that
- an error in format codes was detected by libc, or on platforms
- with a non-C99 vsnprintf simply that the buffer wasn't big enough
- to avoid truncation, or on platforms without any vsnprintf that
- PyMem_Malloc couldn't obtain space for a temp buffer.
+ When rv < 0, "something bad happened". str[size-1] is \0 in this
+ case too, but the rest of str is unreliable. It could be that
+ an error in format codes was detected by libc, or on platforms
+ with a non-C99 vsnprintf simply that the buffer wasn't big enough
+ to avoid truncation, or on platforms without any vsnprintf that
+ PyMem_Malloc couldn't obtain space for a temp buffer.
CAUTION: Unlike C99, str != NULL and size > 0 are required.
*/
@@ -41,65 +41,65 @@
int
PyOS_snprintf(char *str, size_t size, const char *format, ...)
{
- int rc;
- va_list va;
+ int rc;
+ va_list va;
- va_start(va, format);
- rc = PyOS_vsnprintf(str, size, format, va);
- va_end(va);
- return rc;
+ va_start(va, format);
+ rc = PyOS_vsnprintf(str, size, format, va);
+ va_end(va);
+ return rc;
}
int
PyOS_vsnprintf(char *str, size_t size, const char *format, va_list va)
{
- int len; /* # bytes written, excluding \0 */
+ int len; /* # bytes written, excluding \0 */
#ifdef HAVE_SNPRINTF
#define _PyOS_vsnprintf_EXTRA_SPACE 1
#else
#define _PyOS_vsnprintf_EXTRA_SPACE 512
- char *buffer;
+ char *buffer;
#endif
- assert(str != NULL);
- assert(size > 0);
- assert(format != NULL);
- /* We take a size_t as input but return an int. Sanity check
- * our input so that it won't cause an overflow in the
- * vsnprintf return value or the buffer malloc size. */
- if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) {
- len = -666;
- goto Done;
- }
+ assert(str != NULL);
+ assert(size > 0);
+ assert(format != NULL);
+ /* We take a size_t as input but return an int. Sanity check
+ * our input so that it won't cause an overflow in the
+ * vsnprintf return value or the buffer malloc size. */
+ if (size > INT_MAX - _PyOS_vsnprintf_EXTRA_SPACE) {
+ len = -666;
+ goto Done;
+ }
#ifdef HAVE_SNPRINTF
- len = vsnprintf(str, size, format, va);
+ len = vsnprintf(str, size, format, va);
#else
- /* Emulate it. */
- buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE);
- if (buffer == NULL) {
- len = -666;
- goto Done;
- }
-
- len = vsprintf(buffer, format, va);
- if (len < 0)
- /* ignore the error */;
-
- else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE)
- Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
-
- else {
- const size_t to_copy = (size_t)len < size ?
- (size_t)len : size - 1;
- assert(to_copy < size);
- memcpy(str, buffer, to_copy);
- str[to_copy] = '\0';
- }
- PyMem_FREE(buffer);
+ /* Emulate it. */
+ buffer = PyMem_MALLOC(size + _PyOS_vsnprintf_EXTRA_SPACE);
+ if (buffer == NULL) {
+ len = -666;
+ goto Done;
+ }
+
+ len = vsprintf(buffer, format, va);
+ if (len < 0)
+ /* ignore the error */;
+
+ else if ((size_t)len >= size + _PyOS_vsnprintf_EXTRA_SPACE)
+ Py_FatalError("Buffer overflow in PyOS_snprintf/PyOS_vsnprintf");
+
+ else {
+ const size_t to_copy = (size_t)len < size ?
+ (size_t)len : size - 1;
+ assert(to_copy < size);
+ memcpy(str, buffer, to_copy);
+ str[to_copy] = '\0';
+ }
+ PyMem_FREE(buffer);
#endif
Done:
- if (size > 0)
- str[size-1] = '\0';
- return len;
+ if (size > 0)
+ str[size-1] = '\0';
+ return len;
#undef _PyOS_vsnprintf_EXTRA_SPACE
}
diff --git a/Python/mystrtoul.c b/Python/mystrtoul.c
index ebd468c..c35be81 100644
--- a/Python/mystrtoul.c
+++ b/Python/mystrtoul.c
@@ -18,43 +18,43 @@
* i * base doesn't overflow unsigned long.
*/
static unsigned long smallmax[] = {
- 0, /* bases 0 and 1 are invalid */
- 0,
- ULONG_MAX / 2,
- ULONG_MAX / 3,
- ULONG_MAX / 4,
- ULONG_MAX / 5,
- ULONG_MAX / 6,
- ULONG_MAX / 7,
- ULONG_MAX / 8,
- ULONG_MAX / 9,
- ULONG_MAX / 10,
- ULONG_MAX / 11,
- ULONG_MAX / 12,
- ULONG_MAX / 13,
- ULONG_MAX / 14,
- ULONG_MAX / 15,
- ULONG_MAX / 16,
- ULONG_MAX / 17,
- ULONG_MAX / 18,
- ULONG_MAX / 19,
- ULONG_MAX / 20,
- ULONG_MAX / 21,
- ULONG_MAX / 22,
- ULONG_MAX / 23,
- ULONG_MAX / 24,
- ULONG_MAX / 25,
- ULONG_MAX / 26,
- ULONG_MAX / 27,
- ULONG_MAX / 28,
- ULONG_MAX / 29,
- ULONG_MAX / 30,
- ULONG_MAX / 31,
- ULONG_MAX / 32,
- ULONG_MAX / 33,
- ULONG_MAX / 34,
- ULONG_MAX / 35,
- ULONG_MAX / 36,
+ 0, /* bases 0 and 1 are invalid */
+ 0,
+ ULONG_MAX / 2,
+ ULONG_MAX / 3,
+ ULONG_MAX / 4,
+ ULONG_MAX / 5,
+ ULONG_MAX / 6,
+ ULONG_MAX / 7,
+ ULONG_MAX / 8,
+ ULONG_MAX / 9,
+ ULONG_MAX / 10,
+ ULONG_MAX / 11,
+ ULONG_MAX / 12,
+ ULONG_MAX / 13,
+ ULONG_MAX / 14,
+ ULONG_MAX / 15,
+ ULONG_MAX / 16,
+ ULONG_MAX / 17,
+ ULONG_MAX / 18,
+ ULONG_MAX / 19,
+ ULONG_MAX / 20,
+ ULONG_MAX / 21,
+ ULONG_MAX / 22,
+ ULONG_MAX / 23,
+ ULONG_MAX / 24,
+ ULONG_MAX / 25,
+ ULONG_MAX / 26,
+ ULONG_MAX / 27,
+ ULONG_MAX / 28,
+ ULONG_MAX / 29,
+ ULONG_MAX / 30,
+ ULONG_MAX / 31,
+ ULONG_MAX / 32,
+ ULONG_MAX / 33,
+ ULONG_MAX / 34,
+ ULONG_MAX / 35,
+ ULONG_MAX / 36,
};
/* maximum digits that can't ever overflow for bases 2 through 36,
@@ -63,223 +63,223 @@ static unsigned long smallmax[] = {
*/
#if SIZEOF_LONG == 4
static int digitlimit[] = {
- 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */
- 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */
- 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */
- 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */
+ 0, 0, 32, 20, 16, 13, 12, 11, 10, 10, /* 0 - 9 */
+ 9, 9, 8, 8, 8, 8, 8, 7, 7, 7, /* 10 - 19 */
+ 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, /* 20 - 29 */
+ 6, 6, 6, 6, 6, 6, 6}; /* 30 - 36 */
#elif SIZEOF_LONG == 8
/* [int(math.floor(math.log(2**64, i))) for i in range(2, 37)] */
static int digitlimit[] = {
- 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */
- 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */
- 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */
- 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */
+ 0, 0, 64, 40, 32, 27, 24, 22, 21, 20, /* 0 - 9 */
+ 19, 18, 17, 17, 16, 16, 16, 15, 15, 15, /* 10 - 19 */
+ 14, 14, 14, 14, 13, 13, 13, 13, 13, 13, /* 20 - 29 */
+ 13, 12, 12, 12, 12, 12, 12}; /* 30 - 36 */
#else
#error "Need table for SIZEOF_LONG"
#endif
/*
-** strtoul
-** This is a general purpose routine for converting
-** an ascii string to an integer in an arbitrary base.
-** Leading white space is ignored. If 'base' is zero
-** it looks for a leading 0, 0b, 0B, 0o, 0O, 0x or 0X
-** to tell which base. If these are absent it defaults
-** to 10. Base must be 0 or between 2 and 36 (inclusive).
-** If 'ptr' is non-NULL it will contain a pointer to
-** the end of the scan.
-** Errors due to bad pointers will probably result in
-** exceptions - we don't check for them.
+** strtoul
+** This is a general purpose routine for converting
+** an ascii string to an integer in an arbitrary base.
+** Leading white space is ignored. If 'base' is zero
+** it looks for a leading 0, 0b, 0B, 0o, 0O, 0x or 0X
+** to tell which base. If these are absent it defaults
+** to 10. Base must be 0 or between 2 and 36 (inclusive).
+** If 'ptr' is non-NULL it will contain a pointer to
+** the end of the scan.
+** Errors due to bad pointers will probably result in
+** exceptions - we don't check for them.
*/
unsigned long
PyOS_strtoul(register char *str, char **ptr, int base)
{
- register unsigned long result = 0; /* return value of the function */
- register int c; /* current input character */
- register int ovlimit; /* required digits to overflow */
-
- /* skip leading white space */
- while (*str && isspace(Py_CHARMASK(*str)))
- ++str;
-
- /* check for leading 0 or 0x for auto-base or base 16 */
- switch (base) {
- case 0: /* look for leading 0, 0b, 0o or 0x */
- if (*str == '0') {
- ++str;
- if (*str == 'x' || *str == 'X') {
- /* there must be at least one digit after 0x */
- if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) {
- if (ptr)
- *ptr = str;
- return 0;
- }
- ++str;
- base = 16;
- } else if (*str == 'o' || *str == 'O') {
- /* there must be at least one digit after 0o */
- if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) {
- if (ptr)
- *ptr = str;
- return 0;
- }
- ++str;
- base = 8;
- } else if (*str == 'b' || *str == 'B') {
- /* there must be at least one digit after 0b */
- if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) {
- if (ptr)
- *ptr = str;
- return 0;
- }
- ++str;
- base = 2;
- } else {
- base = 8;
- }
- }
- else
- base = 10;
- break;
-
- case 2: /* skip leading 0b or 0B */
- if (*str == '0') {
- ++str;
- if (*str == 'b' || *str == 'B') {
- /* there must be at least one digit after 0b */
- if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) {
- if (ptr)
- *ptr = str;
- return 0;
- }
- ++str;
- }
- }
- break;
-
- case 8: /* skip leading 0o or 0O */
- if (*str == '0') {
- ++str;
- if (*str == 'o' || *str == 'O') {
- /* there must be at least one digit after 0o */
- if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) {
- if (ptr)
- *ptr = str;
- return 0;
- }
- ++str;
- }
- }
- break;
-
- case 16: /* skip leading 0x or 0X */
- if (*str == '0') {
- ++str;
- if (*str == 'x' || *str == 'X') {
- /* there must be at least one digit after 0x */
- if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) {
- if (ptr)
- *ptr = str;
- return 0;
- }
- ++str;
- }
- }
- break;
- }
-
- /* catch silly bases */
- if (base < 2 || base > 36) {
- if (ptr)
- *ptr = str;
- return 0;
- }
-
- /* skip leading zeroes */
- while (*str == '0')
- ++str;
-
- /* base is guaranteed to be in [2, 36] at this point */
- ovlimit = digitlimit[base];
-
- /* do the conversion until non-digit character encountered */
- while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) {
- if (ovlimit > 0) /* no overflow check required */
- result = result * base + c;
- else { /* requires overflow check */
- register unsigned long temp_result;
-
- if (ovlimit < 0) /* guaranteed overflow */
- goto overflowed;
-
- /* there could be an overflow */
- /* check overflow just from shifting */
- if (result > smallmax[base])
- goto overflowed;
-
- result *= base;
-
- /* check overflow from the digit's value */
- temp_result = result + c;
- if (temp_result < result)
- goto overflowed;
-
- result = temp_result;
- }
-
- ++str;
- --ovlimit;
- }
-
- /* set pointer to point to the last character scanned */
- if (ptr)
- *ptr = str;
-
- return result;
+ register unsigned long result = 0; /* return value of the function */
+ register int c; /* current input character */
+ register int ovlimit; /* required digits to overflow */
+
+ /* skip leading white space */
+ while (*str && isspace(Py_CHARMASK(*str)))
+ ++str;
+
+ /* check for leading 0 or 0x for auto-base or base 16 */
+ switch (base) {
+ case 0: /* look for leading 0, 0b, 0o or 0x */
+ if (*str == '0') {
+ ++str;
+ if (*str == 'x' || *str == 'X') {
+ /* there must be at least one digit after 0x */
+ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+ ++str;
+ base = 16;
+ } else if (*str == 'o' || *str == 'O') {
+ /* there must be at least one digit after 0o */
+ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+ ++str;
+ base = 8;
+ } else if (*str == 'b' || *str == 'B') {
+ /* there must be at least one digit after 0b */
+ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+ ++str;
+ base = 2;
+ } else {
+ base = 8;
+ }
+ }
+ else
+ base = 10;
+ break;
+
+ case 2: /* skip leading 0b or 0B */
+ if (*str == '0') {
+ ++str;
+ if (*str == 'b' || *str == 'B') {
+ /* there must be at least one digit after 0b */
+ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 2) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+ ++str;
+ }
+ }
+ break;
+
+ case 8: /* skip leading 0o or 0O */
+ if (*str == '0') {
+ ++str;
+ if (*str == 'o' || *str == 'O') {
+ /* there must be at least one digit after 0o */
+ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 8) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+ ++str;
+ }
+ }
+ break;
+
+ case 16: /* skip leading 0x or 0X */
+ if (*str == '0') {
+ ++str;
+ if (*str == 'x' || *str == 'X') {
+ /* there must be at least one digit after 0x */
+ if (_PyLong_DigitValue[Py_CHARMASK(str[1])] >= 16) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+ ++str;
+ }
+ }
+ break;
+ }
+
+ /* catch silly bases */
+ if (base < 2 || base > 36) {
+ if (ptr)
+ *ptr = str;
+ return 0;
+ }
+
+ /* skip leading zeroes */
+ while (*str == '0')
+ ++str;
+
+ /* base is guaranteed to be in [2, 36] at this point */
+ ovlimit = digitlimit[base];
+
+ /* do the conversion until non-digit character encountered */
+ while ((c = _PyLong_DigitValue[Py_CHARMASK(*str)]) < base) {
+ if (ovlimit > 0) /* no overflow check required */
+ result = result * base + c;
+ else { /* requires overflow check */
+ register unsigned long temp_result;
+
+ if (ovlimit < 0) /* guaranteed overflow */
+ goto overflowed;
+
+ /* there could be an overflow */
+ /* check overflow just from shifting */
+ if (result > smallmax[base])
+ goto overflowed;
+
+ result *= base;
+
+ /* check overflow from the digit's value */
+ temp_result = result + c;
+ if (temp_result < result)
+ goto overflowed;
+
+ result = temp_result;
+ }
+
+ ++str;
+ --ovlimit;
+ }
+
+ /* set pointer to point to the last character scanned */
+ if (ptr)
+ *ptr = str;
+
+ return result;
overflowed:
- if (ptr) {
- /* spool through remaining digit characters */
- while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base)
- ++str;
- *ptr = str;
- }
- errno = ERANGE;
- return (unsigned long)-1;
+ if (ptr) {
+ /* spool through remaining digit characters */
+ while (_PyLong_DigitValue[Py_CHARMASK(*str)] < base)
+ ++str;
+ *ptr = str;
+ }
+ errno = ERANGE;
+ return (unsigned long)-1;
}
/* Checking for overflow in PyOS_strtol is a PITA; see comments
* about PY_ABS_LONG_MIN in longobject.c.
*/
-#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
+#define PY_ABS_LONG_MIN (0-(unsigned long)LONG_MIN)
long
PyOS_strtol(char *str, char **ptr, int base)
{
- long result;
- unsigned long uresult;
- char sign;
-
- while (*str && isspace(Py_CHARMASK(*str)))
- str++;
-
- sign = *str;
- if (sign == '+' || sign == '-')
- str++;
-
- uresult = PyOS_strtoul(str, ptr, base);
-
- if (uresult <= (unsigned long)LONG_MAX) {
- result = (long)uresult;
- if (sign == '-')
- result = -result;
- }
- else if (sign == '-' && uresult == PY_ABS_LONG_MIN) {
- result = LONG_MIN;
- }
- else {
- errno = ERANGE;
- result = LONG_MAX;
- }
- return result;
+ long result;
+ unsigned long uresult;
+ char sign;
+
+ while (*str && isspace(Py_CHARMASK(*str)))
+ str++;
+
+ sign = *str;
+ if (sign == '+' || sign == '-')
+ str++;
+
+ uresult = PyOS_strtoul(str, ptr, base);
+
+ if (uresult <= (unsigned long)LONG_MAX) {
+ result = (long)uresult;
+ if (sign == '-')
+ result = -result;
+ }
+ else if (sign == '-' && uresult == PY_ABS_LONG_MIN) {
+ result = LONG_MIN;
+ }
+ else {
+ errno = ERANGE;
+ result = LONG_MAX;
+ }
+ return result;
}
diff --git a/Python/peephole.c b/Python/peephole.c
index fbc81ff..313eb43 100644
--- a/Python/peephole.c
+++ b/Python/peephole.c
@@ -12,651 +12,651 @@
#include "opcode.h"
#define GETARG(arr, i) ((int)((arr[i+2]<<8) + arr[i+1]))
-#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
+#define UNCONDITIONAL_JUMP(op) (op==JUMP_ABSOLUTE || op==JUMP_FORWARD)
#define CONDITIONAL_JUMP(op) (op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
- || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
+ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
#define ABSOLUTE_JUMP(op) (op==JUMP_ABSOLUTE || op==CONTINUE_LOOP \
- || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
- || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
+ || op==POP_JUMP_IF_FALSE || op==POP_JUMP_IF_TRUE \
+ || op==JUMP_IF_FALSE_OR_POP || op==JUMP_IF_TRUE_OR_POP)
#define JUMPS_ON_TRUE(op) (op==POP_JUMP_IF_TRUE || op==JUMP_IF_TRUE_OR_POP)
#define GETJUMPTGT(arr, i) (GETARG(arr,i) + (ABSOLUTE_JUMP(arr[i]) ? 0 : i+3))
#define SETARG(arr, i, val) arr[i+2] = val>>8; arr[i+1] = val & 255
#define CODESIZE(op) (HAS_ARG(op) ? 3 : 1)
#define ISBASICBLOCK(blocks, start, bytes) \
- (blocks[start]==blocks[start+bytes-1])
+ (blocks[start]==blocks[start+bytes-1])
/* Replace LOAD_CONST c1. LOAD_CONST c2 ... LOAD_CONST cn BUILD_TUPLE n
- with LOAD_CONST (c1, c2, ... cn).
+ with LOAD_CONST (c1, c2, ... cn).
The consts table must still be in list form so that the
new constant (c1, c2, ... cn) can be appended.
Called with codestr pointing to the first LOAD_CONST.
- Bails out with no change if one or more of the LOAD_CONSTs is missing.
+ Bails out with no change if one or more of the LOAD_CONSTs is missing.
Also works for BUILD_LIST when followed by an "in" or "not in" test.
*/
static int
tuple_of_constants(unsigned char *codestr, Py_ssize_t n, PyObject *consts)
{
- PyObject *newconst, *constant;
- Py_ssize_t i, arg, len_consts;
-
- /* Pre-conditions */
- assert(PyList_CheckExact(consts));
- assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
- assert(GETARG(codestr, (n*3)) == n);
- for (i=0 ; i<n ; i++)
- assert(codestr[i*3] == LOAD_CONST);
-
- /* Buildup new tuple of constants */
- newconst = PyTuple_New(n);
- if (newconst == NULL)
- return 0;
- len_consts = PyList_GET_SIZE(consts);
- for (i=0 ; i<n ; i++) {
- arg = GETARG(codestr, (i*3));
- assert(arg < len_consts);
- constant = PyList_GET_ITEM(consts, arg);
- Py_INCREF(constant);
- PyTuple_SET_ITEM(newconst, i, constant);
- }
-
- /* Append folded constant onto consts */
- if (PyList_Append(consts, newconst)) {
- Py_DECREF(newconst);
- return 0;
- }
- Py_DECREF(newconst);
-
- /* Write NOPs over old LOAD_CONSTS and
- add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
- memset(codestr, NOP, n*3);
- codestr[n*3] = LOAD_CONST;
- SETARG(codestr, (n*3), len_consts);
- return 1;
+ PyObject *newconst, *constant;
+ Py_ssize_t i, arg, len_consts;
+
+ /* Pre-conditions */
+ assert(PyList_CheckExact(consts));
+ assert(codestr[n*3] == BUILD_TUPLE || codestr[n*3] == BUILD_LIST);
+ assert(GETARG(codestr, (n*3)) == n);
+ for (i=0 ; i<n ; i++)
+ assert(codestr[i*3] == LOAD_CONST);
+
+ /* Buildup new tuple of constants */
+ newconst = PyTuple_New(n);
+ if (newconst == NULL)
+ return 0;
+ len_consts = PyList_GET_SIZE(consts);
+ for (i=0 ; i<n ; i++) {
+ arg = GETARG(codestr, (i*3));
+ assert(arg < len_consts);
+ constant = PyList_GET_ITEM(consts, arg);
+ Py_INCREF(constant);
+ PyTuple_SET_ITEM(newconst, i, constant);
+ }
+
+ /* Append folded constant onto consts */
+ if (PyList_Append(consts, newconst)) {
+ Py_DECREF(newconst);
+ return 0;
+ }
+ Py_DECREF(newconst);
+
+ /* Write NOPs over old LOAD_CONSTS and
+ add a new LOAD_CONST newconst on top of the BUILD_TUPLE n */
+ memset(codestr, NOP, n*3);
+ codestr[n*3] = LOAD_CONST;
+ SETARG(codestr, (n*3), len_consts);
+ return 1;
}
/* Replace LOAD_CONST c1. LOAD_CONST c2 BINOP
- with LOAD_CONST binop(c1,c2)
+ with LOAD_CONST binop(c1,c2)
The consts table must still be in list form so that the
new constant can be appended.
- Called with codestr pointing to the first LOAD_CONST.
- Abandons the transformation if the folding fails (i.e. 1+'a').
+ Called with codestr pointing to the first LOAD_CONST.
+ Abandons the transformation if the folding fails (i.e. 1+'a').
If the new constant is a sequence, only folds when the size
- is below a threshold value. That keeps pyc files from
- becoming large in the presence of code like: (None,)*1000.
+ is below a threshold value. That keeps pyc files from
+ becoming large in the presence of code like: (None,)*1000.
*/
static int
fold_binops_on_constants(unsigned char *codestr, PyObject *consts)
{
- PyObject *newconst, *v, *w;
- Py_ssize_t len_consts, size;
- int opcode;
-
- /* Pre-conditions */
- assert(PyList_CheckExact(consts));
- assert(codestr[0] == LOAD_CONST);
- assert(codestr[3] == LOAD_CONST);
-
- /* Create new constant */
- v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
- w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
- opcode = codestr[6];
- switch (opcode) {
- case BINARY_POWER:
- newconst = PyNumber_Power(v, w, Py_None);
- break;
- case BINARY_MULTIPLY:
- newconst = PyNumber_Multiply(v, w);
- break;
- case BINARY_DIVIDE:
- /* Cannot fold this operation statically since
- the result can depend on the run-time presence
- of the -Qnew flag */
- return 0;
- case BINARY_TRUE_DIVIDE:
- newconst = PyNumber_TrueDivide(v, w);
- break;
- case BINARY_FLOOR_DIVIDE:
- newconst = PyNumber_FloorDivide(v, w);
- break;
- case BINARY_MODULO:
- newconst = PyNumber_Remainder(v, w);
- break;
- case BINARY_ADD:
- newconst = PyNumber_Add(v, w);
- break;
- case BINARY_SUBTRACT:
- newconst = PyNumber_Subtract(v, w);
- break;
- case BINARY_SUBSCR:
- newconst = PyObject_GetItem(v, w);
- break;
- case BINARY_LSHIFT:
- newconst = PyNumber_Lshift(v, w);
- break;
- case BINARY_RSHIFT:
- newconst = PyNumber_Rshift(v, w);
- break;
- case BINARY_AND:
- newconst = PyNumber_And(v, w);
- break;
- case BINARY_XOR:
- newconst = PyNumber_Xor(v, w);
- break;
- case BINARY_OR:
- newconst = PyNumber_Or(v, w);
- break;
- default:
- /* Called with an unknown opcode */
- PyErr_Format(PyExc_SystemError,
- "unexpected binary operation %d on a constant",
- opcode);
- return 0;
- }
- if (newconst == NULL) {
- PyErr_Clear();
- return 0;
- }
- size = PyObject_Size(newconst);
- if (size == -1)
- PyErr_Clear();
- else if (size > 20) {
- Py_DECREF(newconst);
- return 0;
- }
-
- /* Append folded constant into consts table */
- len_consts = PyList_GET_SIZE(consts);
- if (PyList_Append(consts, newconst)) {
- Py_DECREF(newconst);
- return 0;
- }
- Py_DECREF(newconst);
-
- /* Write NOP NOP NOP NOP LOAD_CONST newconst */
- memset(codestr, NOP, 4);
- codestr[4] = LOAD_CONST;
- SETARG(codestr, 4, len_consts);
- return 1;
+ PyObject *newconst, *v, *w;
+ Py_ssize_t len_consts, size;
+ int opcode;
+
+ /* Pre-conditions */
+ assert(PyList_CheckExact(consts));
+ assert(codestr[0] == LOAD_CONST);
+ assert(codestr[3] == LOAD_CONST);
+
+ /* Create new constant */
+ v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
+ w = PyList_GET_ITEM(consts, GETARG(codestr, 3));
+ opcode = codestr[6];
+ switch (opcode) {
+ case BINARY_POWER:
+ newconst = PyNumber_Power(v, w, Py_None);
+ break;
+ case BINARY_MULTIPLY:
+ newconst = PyNumber_Multiply(v, w);
+ break;
+ case BINARY_DIVIDE:
+ /* Cannot fold this operation statically since
+ the result can depend on the run-time presence
+ of the -Qnew flag */
+ return 0;
+ case BINARY_TRUE_DIVIDE:
+ newconst = PyNumber_TrueDivide(v, w);
+ break;
+ case BINARY_FLOOR_DIVIDE:
+ newconst = PyNumber_FloorDivide(v, w);
+ break;
+ case BINARY_MODULO:
+ newconst = PyNumber_Remainder(v, w);
+ break;
+ case BINARY_ADD:
+ newconst = PyNumber_Add(v, w);
+ break;
+ case BINARY_SUBTRACT:
+ newconst = PyNumber_Subtract(v, w);
+ break;
+ case BINARY_SUBSCR:
+ newconst = PyObject_GetItem(v, w);
+ break;
+ case BINARY_LSHIFT:
+ newconst = PyNumber_Lshift(v, w);
+ break;
+ case BINARY_RSHIFT:
+ newconst = PyNumber_Rshift(v, w);
+ break;
+ case BINARY_AND:
+ newconst = PyNumber_And(v, w);
+ break;
+ case BINARY_XOR:
+ newconst = PyNumber_Xor(v, w);
+ break;
+ case BINARY_OR:
+ newconst = PyNumber_Or(v, w);
+ break;
+ default:
+ /* Called with an unknown opcode */
+ PyErr_Format(PyExc_SystemError,
+ "unexpected binary operation %d on a constant",
+ opcode);
+ return 0;
+ }
+ if (newconst == NULL) {
+ PyErr_Clear();
+ return 0;
+ }
+ size = PyObject_Size(newconst);
+ if (size == -1)
+ PyErr_Clear();
+ else if (size > 20) {
+ Py_DECREF(newconst);
+ return 0;
+ }
+
+ /* Append folded constant into consts table */
+ len_consts = PyList_GET_SIZE(consts);
+ if (PyList_Append(consts, newconst)) {
+ Py_DECREF(newconst);
+ return 0;
+ }
+ Py_DECREF(newconst);
+
+ /* Write NOP NOP NOP NOP LOAD_CONST newconst */
+ memset(codestr, NOP, 4);
+ codestr[4] = LOAD_CONST;
+ SETARG(codestr, 4, len_consts);
+ return 1;
}
static int
fold_unaryops_on_constants(unsigned char *codestr, PyObject *consts)
{
- PyObject *newconst=NULL, *v;
- Py_ssize_t len_consts;
- int opcode;
-
- /* Pre-conditions */
- assert(PyList_CheckExact(consts));
- assert(codestr[0] == LOAD_CONST);
-
- /* Create new constant */
- v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
- opcode = codestr[3];
- switch (opcode) {
- case UNARY_NEGATIVE:
- /* Preserve the sign of -0.0 */
- if (PyObject_IsTrue(v) == 1)
- newconst = PyNumber_Negative(v);
- break;
- case UNARY_CONVERT:
- newconst = PyObject_Repr(v);
- break;
- case UNARY_INVERT:
- newconst = PyNumber_Invert(v);
- break;
- default:
- /* Called with an unknown opcode */
- PyErr_Format(PyExc_SystemError,
- "unexpected unary operation %d on a constant",
- opcode);
- return 0;
- }
- if (newconst == NULL) {
- PyErr_Clear();
- return 0;
- }
-
- /* Append folded constant into consts table */
- len_consts = PyList_GET_SIZE(consts);
- if (PyList_Append(consts, newconst)) {
- Py_DECREF(newconst);
- return 0;
- }
- Py_DECREF(newconst);
-
- /* Write NOP LOAD_CONST newconst */
- codestr[0] = NOP;
- codestr[1] = LOAD_CONST;
- SETARG(codestr, 1, len_consts);
- return 1;
+ PyObject *newconst=NULL, *v;
+ Py_ssize_t len_consts;
+ int opcode;
+
+ /* Pre-conditions */
+ assert(PyList_CheckExact(consts));
+ assert(codestr[0] == LOAD_CONST);
+
+ /* Create new constant */
+ v = PyList_GET_ITEM(consts, GETARG(codestr, 0));
+ opcode = codestr[3];
+ switch (opcode) {
+ case UNARY_NEGATIVE:
+ /* Preserve the sign of -0.0 */
+ if (PyObject_IsTrue(v) == 1)
+ newconst = PyNumber_Negative(v);
+ break;
+ case UNARY_CONVERT:
+ newconst = PyObject_Repr(v);
+ break;
+ case UNARY_INVERT:
+ newconst = PyNumber_Invert(v);
+ break;
+ default:
+ /* Called with an unknown opcode */
+ PyErr_Format(PyExc_SystemError,
+ "unexpected unary operation %d on a constant",
+ opcode);
+ return 0;
+ }
+ if (newconst == NULL) {
+ PyErr_Clear();
+ return 0;
+ }
+
+ /* Append folded constant into consts table */
+ len_consts = PyList_GET_SIZE(consts);
+ if (PyList_Append(consts, newconst)) {
+ Py_DECREF(newconst);
+ return 0;
+ }
+ Py_DECREF(newconst);
+
+ /* Write NOP LOAD_CONST newconst */
+ codestr[0] = NOP;
+ codestr[1] = LOAD_CONST;
+ SETARG(codestr, 1, len_consts);
+ return 1;
}
static unsigned int *
markblocks(unsigned char *code, Py_ssize_t len)
{
- unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
- int i,j, opcode, blockcnt = 0;
-
- if (blocks == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
- memset(blocks, 0, len*sizeof(int));
-
- /* Mark labels in the first pass */
- for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
- opcode = code[i];
- switch (opcode) {
- case FOR_ITER:
- case JUMP_FORWARD:
- case JUMP_IF_FALSE_OR_POP:
- case JUMP_IF_TRUE_OR_POP:
- case POP_JUMP_IF_FALSE:
- case POP_JUMP_IF_TRUE:
- case JUMP_ABSOLUTE:
- case CONTINUE_LOOP:
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- case SETUP_WITH:
- j = GETJUMPTGT(code, i);
- blocks[j] = 1;
- break;
- }
- }
- /* Build block numbers in the second pass */
- for (i=0 ; i<len ; i++) {
- blockcnt += blocks[i]; /* increment blockcnt over labels */
- blocks[i] = blockcnt;
- }
- return blocks;
+ unsigned int *blocks = (unsigned int *)PyMem_Malloc(len*sizeof(int));
+ int i,j, opcode, blockcnt = 0;
+
+ if (blocks == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+ memset(blocks, 0, len*sizeof(int));
+
+ /* Mark labels in the first pass */
+ for (i=0 ; i<len ; i+=CODESIZE(opcode)) {
+ opcode = code[i];
+ switch (opcode) {
+ case FOR_ITER:
+ case JUMP_FORWARD:
+ case JUMP_IF_FALSE_OR_POP:
+ case JUMP_IF_TRUE_OR_POP:
+ case POP_JUMP_IF_FALSE:
+ case POP_JUMP_IF_TRUE:
+ case JUMP_ABSOLUTE:
+ case CONTINUE_LOOP:
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ case SETUP_WITH:
+ j = GETJUMPTGT(code, i);
+ blocks[j] = 1;
+ break;
+ }
+ }
+ /* Build block numbers in the second pass */
+ for (i=0 ; i<len ; i++) {
+ blockcnt += blocks[i]; /* increment blockcnt over labels */
+ blocks[i] = blockcnt;
+ }
+ return blocks;
}
/* Perform basic peephole optimizations to components of a code object.
- The consts object should still be in list form to allow new constants
+ The consts object should still be in list form to allow new constants
to be appended.
To keep the optimizer simple, it bails out (does nothing) for code
- containing extended arguments or that has a length over 32,700. That
- allows us to avoid overflow and sign issues. Likewise, it bails when
+ containing extended arguments or that has a length over 32,700. That
+ allows us to avoid overflow and sign issues. Likewise, it bails when
the lineno table has complex encoding for gaps >= 255.
Optimizations are restricted to simple transformations occuring within a
- single basic block. All transformations keep the code size the same or
- smaller. For those that reduce size, the gaps are initially filled with
- NOPs. Later those NOPs are removed and the jump addresses retargeted in
+ single basic block. All transformations keep the code size the same or
+ smaller. For those that reduce size, the gaps are initially filled with
+ NOPs. Later those NOPs are removed and the jump addresses retargeted in
a single pass. Line numbering is adjusted accordingly. */
PyObject *
PyCode_Optimize(PyObject *code, PyObject* consts, PyObject *names,
PyObject *lineno_obj)
{
- Py_ssize_t i, j, codelen;
- int nops, h, adj;
- int tgt, tgttgt, opcode;
- unsigned char *codestr = NULL;
- unsigned char *lineno;
- int *addrmap = NULL;
- int new_line, cum_orig_line, last_line, tabsiz;
- int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
- unsigned int *blocks = NULL;
- char *name;
-
- /* Bail out if an exception is set */
- if (PyErr_Occurred())
- goto exitError;
-
- /* Bypass optimization when the lineno table is too complex */
- assert(PyString_Check(lineno_obj));
- lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
- tabsiz = PyString_GET_SIZE(lineno_obj);
- if (memchr(lineno, 255, tabsiz) != NULL)
- goto exitUnchanged;
-
- /* Avoid situations where jump retargeting could overflow */
- assert(PyString_Check(code));
- codelen = PyString_GET_SIZE(code);
- if (codelen > 32700)
- goto exitUnchanged;
-
- /* Make a modifiable copy of the code string */
- codestr = (unsigned char *)PyMem_Malloc(codelen);
- if (codestr == NULL)
- goto exitError;
- codestr = (unsigned char *)memcpy(codestr,
- PyString_AS_STRING(code), codelen);
-
- /* Verify that RETURN_VALUE terminates the codestring. This allows
- the various transformation patterns to look ahead several
- instructions without additional checks to make sure they are not
- looking beyond the end of the code string.
- */
- if (codestr[codelen-1] != RETURN_VALUE)
- goto exitUnchanged;
-
- /* Mapping to new jump targets after NOPs are removed */
- addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
- if (addrmap == NULL)
- goto exitError;
-
- blocks = markblocks(codestr, codelen);
- if (blocks == NULL)
- goto exitError;
- assert(PyList_Check(consts));
-
- for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
- reoptimize_current:
- opcode = codestr[i];
-
- lastlc = cumlc;
- cumlc = 0;
-
- switch (opcode) {
- /* Replace UNARY_NOT POP_JUMP_IF_FALSE
- with POP_JUMP_IF_TRUE */
- case UNARY_NOT:
- if (codestr[i+1] != POP_JUMP_IF_FALSE
- || !ISBASICBLOCK(blocks,i,4))
- continue;
- j = GETARG(codestr, i+1);
- codestr[i] = POP_JUMP_IF_TRUE;
- SETARG(codestr, i, j);
- codestr[i+3] = NOP;
- goto reoptimize_current;
-
- /* not a is b --> a is not b
- not a in b --> a not in b
- not a is not b --> a is b
- not a not in b --> a in b
- */
- case COMPARE_OP:
- j = GETARG(codestr, i);
- if (j < 6 || j > 9 ||
- codestr[i+3] != UNARY_NOT ||
- !ISBASICBLOCK(blocks,i,4))
- continue;
- SETARG(codestr, i, (j^1));
- codestr[i+3] = NOP;
- break;
-
- /* Replace LOAD_GLOBAL/LOAD_NAME None
- with LOAD_CONST None */
- case LOAD_NAME:
- case LOAD_GLOBAL:
- j = GETARG(codestr, i);
- name = PyString_AsString(PyTuple_GET_ITEM(names, j));
- if (name == NULL || strcmp(name, "None") != 0)
- continue;
- for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
- if (PyList_GET_ITEM(consts, j) == Py_None)
- break;
- }
- if (j == PyList_GET_SIZE(consts)) {
- if (PyList_Append(consts, Py_None) == -1)
- goto exitError;
- }
- assert(PyList_GET_ITEM(consts, j) == Py_None);
- codestr[i] = LOAD_CONST;
- SETARG(codestr, i, j);
- cumlc = lastlc + 1;
- break;
-
- /* Skip over LOAD_CONST trueconst
- POP_JUMP_IF_FALSE xx. This improves
- "while 1" performance. */
- case LOAD_CONST:
- cumlc = lastlc + 1;
- j = GETARG(codestr, i);
- if (codestr[i+3] != POP_JUMP_IF_FALSE ||
- !ISBASICBLOCK(blocks,i,6) ||
- !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
- continue;
- memset(codestr+i, NOP, 6);
- cumlc = 0;
- break;
-
- /* Try to fold tuples of constants (includes a case for lists
- which are only used for "in" and "not in" tests).
- Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
- Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
- Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
- case BUILD_TUPLE:
- case BUILD_LIST:
- j = GETARG(codestr, i);
- h = i - 3 * j;
- if (h >= 0 &&
- j <= lastlc &&
- ((opcode == BUILD_TUPLE &&
- ISBASICBLOCK(blocks, h, 3*(j+1))) ||
- (opcode == BUILD_LIST &&
- codestr[i+3]==COMPARE_OP &&
- ISBASICBLOCK(blocks, h, 3*(j+2)) &&
- (GETARG(codestr,i+3)==6 ||
- GETARG(codestr,i+3)==7))) &&
- tuple_of_constants(&codestr[h], j, consts)) {
- assert(codestr[i] == LOAD_CONST);
- cumlc = 1;
- break;
- }
- if (codestr[i+3] != UNPACK_SEQUENCE ||
- !ISBASICBLOCK(blocks,i,6) ||
- j != GETARG(codestr, i+3))
- continue;
- if (j == 1) {
- memset(codestr+i, NOP, 6);
- } else if (j == 2) {
- codestr[i] = ROT_TWO;
- memset(codestr+i+1, NOP, 5);
- } else if (j == 3) {
- codestr[i] = ROT_THREE;
- codestr[i+1] = ROT_TWO;
- memset(codestr+i+2, NOP, 4);
- }
- break;
-
- /* Fold binary ops on constants.
- LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
- case BINARY_POWER:
- case BINARY_MULTIPLY:
- case BINARY_TRUE_DIVIDE:
- case BINARY_FLOOR_DIVIDE:
- case BINARY_MODULO:
- case BINARY_ADD:
- case BINARY_SUBTRACT:
- case BINARY_SUBSCR:
- case BINARY_LSHIFT:
- case BINARY_RSHIFT:
- case BINARY_AND:
- case BINARY_XOR:
- case BINARY_OR:
- if (lastlc >= 2 &&
- ISBASICBLOCK(blocks, i-6, 7) &&
- fold_binops_on_constants(&codestr[i-6], consts)) {
- i -= 2;
- assert(codestr[i] == LOAD_CONST);
- cumlc = 1;
- }
- break;
-
- /* Fold unary ops on constants.
- LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
- case UNARY_NEGATIVE:
- case UNARY_CONVERT:
- case UNARY_INVERT:
- if (lastlc >= 1 &&
- ISBASICBLOCK(blocks, i-3, 4) &&
- fold_unaryops_on_constants(&codestr[i-3], consts)) {
- i -= 2;
- assert(codestr[i] == LOAD_CONST);
- cumlc = 1;
- }
- break;
-
- /* Simplify conditional jump to conditional jump where the
- result of the first test implies the success of a similar
- test or the failure of the opposite test.
- Arises in code like:
- "if a and b:"
- "if a or b:"
- "a and b or c"
- "(a and b) and c"
- x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
- --> x:JUMP_IF_FALSE_OR_POP z
- x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
- --> x:POP_JUMP_IF_FALSE y+3
- where y+3 is the instruction following the second test.
- */
- case JUMP_IF_FALSE_OR_POP:
- case JUMP_IF_TRUE_OR_POP:
- tgt = GETJUMPTGT(codestr, i);
- j = codestr[tgt];
- if (CONDITIONAL_JUMP(j)) {
- /* NOTE: all possible jumps here are
- absolute! */
- if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
- /* The second jump will be
- taken iff the first is. */
- tgttgt = GETJUMPTGT(codestr, tgt);
- /* The current opcode inherits
- its target's stack behaviour */
- codestr[i] = j;
- SETARG(codestr, i, tgttgt);
- goto reoptimize_current;
- } else {
- /* The second jump is not taken
- if the first is (so jump past
- it), and all conditional
- jumps pop their argument when
- they're not taken (so change
- the first jump to pop its
- argument when it's taken). */
- if (JUMPS_ON_TRUE(opcode))
- codestr[i] = POP_JUMP_IF_TRUE;
- else
- codestr[i] = POP_JUMP_IF_FALSE;
- SETARG(codestr, i, (tgt + 3));
- goto reoptimize_current;
- }
- }
- /* Intentional fallthrough */
-
- /* Replace jumps to unconditional jumps */
- case POP_JUMP_IF_FALSE:
- case POP_JUMP_IF_TRUE:
- case FOR_ITER:
- case JUMP_FORWARD:
- case JUMP_ABSOLUTE:
- case CONTINUE_LOOP:
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- case SETUP_WITH:
- tgt = GETJUMPTGT(codestr, i);
- /* Replace JUMP_* to a RETURN into just a RETURN */
- if (UNCONDITIONAL_JUMP(opcode) &&
- codestr[tgt] == RETURN_VALUE) {
- codestr[i] = RETURN_VALUE;
- memset(codestr+i+1, NOP, 2);
- continue;
- }
- if (!UNCONDITIONAL_JUMP(codestr[tgt]))
- continue;
- tgttgt = GETJUMPTGT(codestr, tgt);
- if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
- opcode = JUMP_ABSOLUTE;
- if (!ABSOLUTE_JUMP(opcode))
- tgttgt -= i + 3; /* Calc relative jump addr */
- if (tgttgt < 0) /* No backward relative jumps */
- continue;
- codestr[i] = opcode;
- SETARG(codestr, i, tgttgt);
- break;
-
- case EXTENDED_ARG:
- goto exitUnchanged;
-
- /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
- /* Remove unreachable JUMPs after RETURN */
- case RETURN_VALUE:
- if (i+4 >= codelen)
- continue;
- if (codestr[i+4] == RETURN_VALUE &&
- ISBASICBLOCK(blocks,i,5))
- memset(codestr+i+1, NOP, 4);
- else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
- ISBASICBLOCK(blocks,i,4))
- memset(codestr+i+1, NOP, 3);
- break;
- }
- }
-
- /* Fixup linenotab */
- for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
- addrmap[i] = i - nops;
- if (codestr[i] == NOP)
- nops++;
- }
- cum_orig_line = 0;
- last_line = 0;
- for (i=0 ; i < tabsiz ; i+=2) {
- cum_orig_line += lineno[i];
- new_line = addrmap[cum_orig_line];
- assert (new_line - last_line < 255);
- lineno[i] =((unsigned char)(new_line - last_line));
- last_line = new_line;
- }
-
- /* Remove NOPs and fixup jump targets */
- for (i=0, h=0 ; i<codelen ; ) {
- opcode = codestr[i];
- switch (opcode) {
- case NOP:
- i++;
- continue;
-
- case JUMP_ABSOLUTE:
- case CONTINUE_LOOP:
- case POP_JUMP_IF_FALSE:
- case POP_JUMP_IF_TRUE:
- case JUMP_IF_FALSE_OR_POP:
- case JUMP_IF_TRUE_OR_POP:
- j = addrmap[GETARG(codestr, i)];
- SETARG(codestr, i, j);
- break;
-
- case FOR_ITER:
- case JUMP_FORWARD:
- case SETUP_LOOP:
- case SETUP_EXCEPT:
- case SETUP_FINALLY:
- case SETUP_WITH:
- j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
- SETARG(codestr, i, j);
- break;
- }
- adj = CODESIZE(opcode);
- while (adj--)
- codestr[h++] = codestr[i++];
- }
- assert(h + nops == codelen);
-
- code = PyString_FromStringAndSize((char *)codestr, h);
- PyMem_Free(addrmap);
- PyMem_Free(codestr);
- PyMem_Free(blocks);
- return code;
+ Py_ssize_t i, j, codelen;
+ int nops, h, adj;
+ int tgt, tgttgt, opcode;
+ unsigned char *codestr = NULL;
+ unsigned char *lineno;
+ int *addrmap = NULL;
+ int new_line, cum_orig_line, last_line, tabsiz;
+ int cumlc=0, lastlc=0; /* Count runs of consecutive LOAD_CONSTs */
+ unsigned int *blocks = NULL;
+ char *name;
+
+ /* Bail out if an exception is set */
+ if (PyErr_Occurred())
+ goto exitError;
+
+ /* Bypass optimization when the lineno table is too complex */
+ assert(PyString_Check(lineno_obj));
+ lineno = (unsigned char*)PyString_AS_STRING(lineno_obj);
+ tabsiz = PyString_GET_SIZE(lineno_obj);
+ if (memchr(lineno, 255, tabsiz) != NULL)
+ goto exitUnchanged;
+
+ /* Avoid situations where jump retargeting could overflow */
+ assert(PyString_Check(code));
+ codelen = PyString_GET_SIZE(code);
+ if (codelen > 32700)
+ goto exitUnchanged;
+
+ /* Make a modifiable copy of the code string */
+ codestr = (unsigned char *)PyMem_Malloc(codelen);
+ if (codestr == NULL)
+ goto exitError;
+ codestr = (unsigned char *)memcpy(codestr,
+ PyString_AS_STRING(code), codelen);
+
+ /* Verify that RETURN_VALUE terminates the codestring. This allows
+ the various transformation patterns to look ahead several
+ instructions without additional checks to make sure they are not
+ looking beyond the end of the code string.
+ */
+ if (codestr[codelen-1] != RETURN_VALUE)
+ goto exitUnchanged;
+
+ /* Mapping to new jump targets after NOPs are removed */
+ addrmap = (int *)PyMem_Malloc(codelen * sizeof(int));
+ if (addrmap == NULL)
+ goto exitError;
+
+ blocks = markblocks(codestr, codelen);
+ if (blocks == NULL)
+ goto exitError;
+ assert(PyList_Check(consts));
+
+ for (i=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
+ reoptimize_current:
+ opcode = codestr[i];
+
+ lastlc = cumlc;
+ cumlc = 0;
+
+ switch (opcode) {
+ /* Replace UNARY_NOT POP_JUMP_IF_FALSE
+ with POP_JUMP_IF_TRUE */
+ case UNARY_NOT:
+ if (codestr[i+1] != POP_JUMP_IF_FALSE
+ || !ISBASICBLOCK(blocks,i,4))
+ continue;
+ j = GETARG(codestr, i+1);
+ codestr[i] = POP_JUMP_IF_TRUE;
+ SETARG(codestr, i, j);
+ codestr[i+3] = NOP;
+ goto reoptimize_current;
+
+ /* not a is b --> a is not b
+ not a in b --> a not in b
+ not a is not b --> a is b
+ not a not in b --> a in b
+ */
+ case COMPARE_OP:
+ j = GETARG(codestr, i);
+ if (j < 6 || j > 9 ||
+ codestr[i+3] != UNARY_NOT ||
+ !ISBASICBLOCK(blocks,i,4))
+ continue;
+ SETARG(codestr, i, (j^1));
+ codestr[i+3] = NOP;
+ break;
+
+ /* Replace LOAD_GLOBAL/LOAD_NAME None
+ with LOAD_CONST None */
+ case LOAD_NAME:
+ case LOAD_GLOBAL:
+ j = GETARG(codestr, i);
+ name = PyString_AsString(PyTuple_GET_ITEM(names, j));
+ if (name == NULL || strcmp(name, "None") != 0)
+ continue;
+ for (j=0 ; j < PyList_GET_SIZE(consts) ; j++) {
+ if (PyList_GET_ITEM(consts, j) == Py_None)
+ break;
+ }
+ if (j == PyList_GET_SIZE(consts)) {
+ if (PyList_Append(consts, Py_None) == -1)
+ goto exitError;
+ }
+ assert(PyList_GET_ITEM(consts, j) == Py_None);
+ codestr[i] = LOAD_CONST;
+ SETARG(codestr, i, j);
+ cumlc = lastlc + 1;
+ break;
+
+ /* Skip over LOAD_CONST trueconst
+ POP_JUMP_IF_FALSE xx. This improves
+ "while 1" performance. */
+ case LOAD_CONST:
+ cumlc = lastlc + 1;
+ j = GETARG(codestr, i);
+ if (codestr[i+3] != POP_JUMP_IF_FALSE ||
+ !ISBASICBLOCK(blocks,i,6) ||
+ !PyObject_IsTrue(PyList_GET_ITEM(consts, j)))
+ continue;
+ memset(codestr+i, NOP, 6);
+ cumlc = 0;
+ break;
+
+ /* Try to fold tuples of constants (includes a case for lists
+ which are only used for "in" and "not in" tests).
+ Skip over BUILD_SEQN 1 UNPACK_SEQN 1.
+ Replace BUILD_SEQN 2 UNPACK_SEQN 2 with ROT2.
+ Replace BUILD_SEQN 3 UNPACK_SEQN 3 with ROT3 ROT2. */
+ case BUILD_TUPLE:
+ case BUILD_LIST:
+ j = GETARG(codestr, i);
+ h = i - 3 * j;
+ if (h >= 0 &&
+ j <= lastlc &&
+ ((opcode == BUILD_TUPLE &&
+ ISBASICBLOCK(blocks, h, 3*(j+1))) ||
+ (opcode == BUILD_LIST &&
+ codestr[i+3]==COMPARE_OP &&
+ ISBASICBLOCK(blocks, h, 3*(j+2)) &&
+ (GETARG(codestr,i+3)==6 ||
+ GETARG(codestr,i+3)==7))) &&
+ tuple_of_constants(&codestr[h], j, consts)) {
+ assert(codestr[i] == LOAD_CONST);
+ cumlc = 1;
+ break;
+ }
+ if (codestr[i+3] != UNPACK_SEQUENCE ||
+ !ISBASICBLOCK(blocks,i,6) ||
+ j != GETARG(codestr, i+3))
+ continue;
+ if (j == 1) {
+ memset(codestr+i, NOP, 6);
+ } else if (j == 2) {
+ codestr[i] = ROT_TWO;
+ memset(codestr+i+1, NOP, 5);
+ } else if (j == 3) {
+ codestr[i] = ROT_THREE;
+ codestr[i+1] = ROT_TWO;
+ memset(codestr+i+2, NOP, 4);
+ }
+ break;
+
+ /* Fold binary ops on constants.
+ LOAD_CONST c1 LOAD_CONST c2 BINOP --> LOAD_CONST binop(c1,c2) */
+ case BINARY_POWER:
+ case BINARY_MULTIPLY:
+ case BINARY_TRUE_DIVIDE:
+ case BINARY_FLOOR_DIVIDE:
+ case BINARY_MODULO:
+ case BINARY_ADD:
+ case BINARY_SUBTRACT:
+ case BINARY_SUBSCR:
+ case BINARY_LSHIFT:
+ case BINARY_RSHIFT:
+ case BINARY_AND:
+ case BINARY_XOR:
+ case BINARY_OR:
+ if (lastlc >= 2 &&
+ ISBASICBLOCK(blocks, i-6, 7) &&
+ fold_binops_on_constants(&codestr[i-6], consts)) {
+ i -= 2;
+ assert(codestr[i] == LOAD_CONST);
+ cumlc = 1;
+ }
+ break;
+
+ /* Fold unary ops on constants.
+ LOAD_CONST c1 UNARY_OP --> LOAD_CONST unary_op(c) */
+ case UNARY_NEGATIVE:
+ case UNARY_CONVERT:
+ case UNARY_INVERT:
+ if (lastlc >= 1 &&
+ ISBASICBLOCK(blocks, i-3, 4) &&
+ fold_unaryops_on_constants(&codestr[i-3], consts)) {
+ i -= 2;
+ assert(codestr[i] == LOAD_CONST);
+ cumlc = 1;
+ }
+ break;
+
+ /* Simplify conditional jump to conditional jump where the
+ result of the first test implies the success of a similar
+ test or the failure of the opposite test.
+ Arises in code like:
+ "if a and b:"
+ "if a or b:"
+ "a and b or c"
+ "(a and b) and c"
+ x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_FALSE_OR_POP z
+ --> x:JUMP_IF_FALSE_OR_POP z
+ x:JUMP_IF_FALSE_OR_POP y y:JUMP_IF_TRUE_OR_POP z
+ --> x:POP_JUMP_IF_FALSE y+3
+ where y+3 is the instruction following the second test.
+ */
+ case JUMP_IF_FALSE_OR_POP:
+ case JUMP_IF_TRUE_OR_POP:
+ tgt = GETJUMPTGT(codestr, i);
+ j = codestr[tgt];
+ if (CONDITIONAL_JUMP(j)) {
+ /* NOTE: all possible jumps here are
+ absolute! */
+ if (JUMPS_ON_TRUE(j) == JUMPS_ON_TRUE(opcode)) {
+ /* The second jump will be
+ taken iff the first is. */
+ tgttgt = GETJUMPTGT(codestr, tgt);
+ /* The current opcode inherits
+ its target's stack behaviour */
+ codestr[i] = j;
+ SETARG(codestr, i, tgttgt);
+ goto reoptimize_current;
+ } else {
+ /* The second jump is not taken
+ if the first is (so jump past
+ it), and all conditional
+ jumps pop their argument when
+ they're not taken (so change
+ the first jump to pop its
+ argument when it's taken). */
+ if (JUMPS_ON_TRUE(opcode))
+ codestr[i] = POP_JUMP_IF_TRUE;
+ else
+ codestr[i] = POP_JUMP_IF_FALSE;
+ SETARG(codestr, i, (tgt + 3));
+ goto reoptimize_current;
+ }
+ }
+ /* Intentional fallthrough */
+
+ /* Replace jumps to unconditional jumps */
+ case POP_JUMP_IF_FALSE:
+ case POP_JUMP_IF_TRUE:
+ case FOR_ITER:
+ case JUMP_FORWARD:
+ case JUMP_ABSOLUTE:
+ case CONTINUE_LOOP:
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ case SETUP_WITH:
+ tgt = GETJUMPTGT(codestr, i);
+ /* Replace JUMP_* to a RETURN into just a RETURN */
+ if (UNCONDITIONAL_JUMP(opcode) &&
+ codestr[tgt] == RETURN_VALUE) {
+ codestr[i] = RETURN_VALUE;
+ memset(codestr+i+1, NOP, 2);
+ continue;
+ }
+ if (!UNCONDITIONAL_JUMP(codestr[tgt]))
+ continue;
+ tgttgt = GETJUMPTGT(codestr, tgt);
+ if (opcode == JUMP_FORWARD) /* JMP_ABS can go backwards */
+ opcode = JUMP_ABSOLUTE;
+ if (!ABSOLUTE_JUMP(opcode))
+ tgttgt -= i + 3; /* Calc relative jump addr */
+ if (tgttgt < 0) /* No backward relative jumps */
+ continue;
+ codestr[i] = opcode;
+ SETARG(codestr, i, tgttgt);
+ break;
+
+ case EXTENDED_ARG:
+ goto exitUnchanged;
+
+ /* Replace RETURN LOAD_CONST None RETURN with just RETURN */
+ /* Remove unreachable JUMPs after RETURN */
+ case RETURN_VALUE:
+ if (i+4 >= codelen)
+ continue;
+ if (codestr[i+4] == RETURN_VALUE &&
+ ISBASICBLOCK(blocks,i,5))
+ memset(codestr+i+1, NOP, 4);
+ else if (UNCONDITIONAL_JUMP(codestr[i+1]) &&
+ ISBASICBLOCK(blocks,i,4))
+ memset(codestr+i+1, NOP, 3);
+ break;
+ }
+ }
+
+ /* Fixup linenotab */
+ for (i=0, nops=0 ; i<codelen ; i += CODESIZE(codestr[i])) {
+ addrmap[i] = i - nops;
+ if (codestr[i] == NOP)
+ nops++;
+ }
+ cum_orig_line = 0;
+ last_line = 0;
+ for (i=0 ; i < tabsiz ; i+=2) {
+ cum_orig_line += lineno[i];
+ new_line = addrmap[cum_orig_line];
+ assert (new_line - last_line < 255);
+ lineno[i] =((unsigned char)(new_line - last_line));
+ last_line = new_line;
+ }
+
+ /* Remove NOPs and fixup jump targets */
+ for (i=0, h=0 ; i<codelen ; ) {
+ opcode = codestr[i];
+ switch (opcode) {
+ case NOP:
+ i++;
+ continue;
+
+ case JUMP_ABSOLUTE:
+ case CONTINUE_LOOP:
+ case POP_JUMP_IF_FALSE:
+ case POP_JUMP_IF_TRUE:
+ case JUMP_IF_FALSE_OR_POP:
+ case JUMP_IF_TRUE_OR_POP:
+ j = addrmap[GETARG(codestr, i)];
+ SETARG(codestr, i, j);
+ break;
+
+ case FOR_ITER:
+ case JUMP_FORWARD:
+ case SETUP_LOOP:
+ case SETUP_EXCEPT:
+ case SETUP_FINALLY:
+ case SETUP_WITH:
+ j = addrmap[GETARG(codestr, i) + i + 3] - addrmap[i] - 3;
+ SETARG(codestr, i, j);
+ break;
+ }
+ adj = CODESIZE(opcode);
+ while (adj--)
+ codestr[h++] = codestr[i++];
+ }
+ assert(h + nops == codelen);
+
+ code = PyString_FromStringAndSize((char *)codestr, h);
+ PyMem_Free(addrmap);
+ PyMem_Free(codestr);
+ PyMem_Free(blocks);
+ return code;
exitError:
- code = NULL;
+ code = NULL;
exitUnchanged:
- if (blocks != NULL)
- PyMem_Free(blocks);
- if (addrmap != NULL)
- PyMem_Free(addrmap);
- if (codestr != NULL)
- PyMem_Free(codestr);
- Py_XINCREF(code);
- return code;
+ if (blocks != NULL)
+ PyMem_Free(blocks);
+ if (addrmap != NULL)
+ PyMem_Free(addrmap);
+ if (codestr != NULL)
+ PyMem_Free(codestr);
+ Py_XINCREF(code);
+ return code;
}
diff --git a/Python/pyarena.c b/Python/pyarena.c
index f4cc474..2d63638 100644
--- a/Python/pyarena.c
+++ b/Python/pyarena.c
@@ -12,32 +12,32 @@
*/
#define DEFAULT_BLOCK_SIZE 8192
-#define ALIGNMENT 8
-#define ALIGNMENT_MASK (ALIGNMENT - 1)
-#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
+#define ALIGNMENT 8
+#define ALIGNMENT_MASK (ALIGNMENT - 1)
+#define ROUNDUP(x) (((x) + ALIGNMENT_MASK) & ~ALIGNMENT_MASK)
typedef struct _block {
- /* Total number of bytes owned by this block available to pass out.
- * Read-only after initialization. The first such byte starts at
- * ab_mem.
- */
- size_t ab_size;
-
- /* Total number of bytes already passed out. The next byte available
- * to pass out starts at ab_mem + ab_offset.
- */
- size_t ab_offset;
-
- /* An arena maintains a singly-linked, NULL-terminated list of
- * all blocks owned by the arena. These are linked via the
- * ab_next member.
- */
- struct _block *ab_next;
-
- /* Pointer to the first allocatable byte owned by this block. Read-
- * only after initialization.
- */
- void *ab_mem;
+ /* Total number of bytes owned by this block available to pass out.
+ * Read-only after initialization. The first such byte starts at
+ * ab_mem.
+ */
+ size_t ab_size;
+
+ /* Total number of bytes already passed out. The next byte available
+ * to pass out starts at ab_mem + ab_offset.
+ */
+ size_t ab_offset;
+
+ /* An arena maintains a singly-linked, NULL-terminated list of
+ * all blocks owned by the arena. These are linked via the
+ * ab_next member.
+ */
+ struct _block *ab_next;
+
+ /* Pointer to the first allocatable byte owned by this block. Read-
+ * only after initialization.
+ */
+ void *ab_mem;
} block;
/* The arena manages two kinds of memory, blocks of raw memory
@@ -46,175 +46,175 @@ typedef struct _block {
*/
struct _arena {
- /* Pointer to the first block allocated for the arena, never NULL.
- It is used only to find the first block when the arena is
- being freed.
- */
- block *a_head;
-
- /* Pointer to the block currently used for allocation. It's
- ab_next field should be NULL. If it is not-null after a
- call to block_alloc(), it means a new block has been allocated
- and a_cur should be reset to point it.
- */
- block *a_cur;
-
- /* A Python list object containing references to all the PyObject
- pointers associated with this area. They will be DECREFed
- when the arena is freed.
- */
- PyObject *a_objects;
+ /* Pointer to the first block allocated for the arena, never NULL.
+ It is used only to find the first block when the arena is
+ being freed.
+ */
+ block *a_head;
+
+ /* Pointer to the block currently used for allocation. It's
+ ab_next field should be NULL. If it is not-null after a
+ call to block_alloc(), it means a new block has been allocated
+ and a_cur should be reset to point it.
+ */
+ block *a_cur;
+
+ /* A Python list object containing references to all the PyObject
+ pointers associated with this area. They will be DECREFed
+ when the arena is freed.
+ */
+ PyObject *a_objects;
#if defined(Py_DEBUG)
- /* Debug output */
- size_t total_allocs;
- size_t total_size;
- size_t total_blocks;
- size_t total_block_size;
- size_t total_big_blocks;
+ /* Debug output */
+ size_t total_allocs;
+ size_t total_size;
+ size_t total_blocks;
+ size_t total_block_size;
+ size_t total_big_blocks;
#endif
};
static block *
block_new(size_t size)
{
- /* Allocate header and block as one unit.
- ab_mem points just past header. */
- block *b = (block *)malloc(sizeof(block) + size);
- if (!b)
- return NULL;
- b->ab_size = size;
- b->ab_mem = (void *)(b + 1);
- b->ab_next = NULL;
- b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) -
- (Py_uintptr_t)(b->ab_mem);
- return b;
+ /* Allocate header and block as one unit.
+ ab_mem points just past header. */
+ block *b = (block *)malloc(sizeof(block) + size);
+ if (!b)
+ return NULL;
+ b->ab_size = size;
+ b->ab_mem = (void *)(b + 1);
+ b->ab_next = NULL;
+ b->ab_offset = ROUNDUP((Py_uintptr_t)(b->ab_mem)) -
+ (Py_uintptr_t)(b->ab_mem);
+ return b;
}
static void
block_free(block *b) {
- while (b) {
- block *next = b->ab_next;
- free(b);
- b = next;
- }
+ while (b) {
+ block *next = b->ab_next;
+ free(b);
+ b = next;
+ }
}
static void *
block_alloc(block *b, size_t size)
{
- void *p;
- assert(b);
- size = ROUNDUP(size);
- if (b->ab_offset + size > b->ab_size) {
- /* If we need to allocate more memory than will fit in
- the default block, allocate a one-off block that is
- exactly the right size. */
- /* TODO(jhylton): Think about space waste at end of block */
- block *newbl = block_new(
- size < DEFAULT_BLOCK_SIZE ?
- DEFAULT_BLOCK_SIZE : size);
- if (!newbl)
- return NULL;
- assert(!b->ab_next);
- b->ab_next = newbl;
- b = newbl;
- }
-
- assert(b->ab_offset + size <= b->ab_size);
- p = (void *)(((char *)b->ab_mem) + b->ab_offset);
- b->ab_offset += size;
- return p;
+ void *p;
+ assert(b);
+ size = ROUNDUP(size);
+ if (b->ab_offset + size > b->ab_size) {
+ /* If we need to allocate more memory than will fit in
+ the default block, allocate a one-off block that is
+ exactly the right size. */
+ /* TODO(jhylton): Think about space waste at end of block */
+ block *newbl = block_new(
+ size < DEFAULT_BLOCK_SIZE ?
+ DEFAULT_BLOCK_SIZE : size);
+ if (!newbl)
+ return NULL;
+ assert(!b->ab_next);
+ b->ab_next = newbl;
+ b = newbl;
+ }
+
+ assert(b->ab_offset + size <= b->ab_size);
+ p = (void *)(((char *)b->ab_mem) + b->ab_offset);
+ b->ab_offset += size;
+ return p;
}
PyArena *
PyArena_New()
{
- PyArena* arena = (PyArena *)malloc(sizeof(PyArena));
- if (!arena)
- return (PyArena*)PyErr_NoMemory();
-
- arena->a_head = block_new(DEFAULT_BLOCK_SIZE);
- arena->a_cur = arena->a_head;
- if (!arena->a_head) {
- free((void *)arena);
- return (PyArena*)PyErr_NoMemory();
- }
- arena->a_objects = PyList_New(0);
- if (!arena->a_objects) {
- block_free(arena->a_head);
- free((void *)arena);
- return (PyArena*)PyErr_NoMemory();
- }
+ PyArena* arena = (PyArena *)malloc(sizeof(PyArena));
+ if (!arena)
+ return (PyArena*)PyErr_NoMemory();
+
+ arena->a_head = block_new(DEFAULT_BLOCK_SIZE);
+ arena->a_cur = arena->a_head;
+ if (!arena->a_head) {
+ free((void *)arena);
+ return (PyArena*)PyErr_NoMemory();
+ }
+ arena->a_objects = PyList_New(0);
+ if (!arena->a_objects) {
+ block_free(arena->a_head);
+ free((void *)arena);
+ return (PyArena*)PyErr_NoMemory();
+ }
#if defined(Py_DEBUG)
- arena->total_allocs = 0;
- arena->total_size = 0;
- arena->total_blocks = 1;
- arena->total_block_size = DEFAULT_BLOCK_SIZE;
- arena->total_big_blocks = 0;
+ arena->total_allocs = 0;
+ arena->total_size = 0;
+ arena->total_blocks = 1;
+ arena->total_block_size = DEFAULT_BLOCK_SIZE;
+ arena->total_big_blocks = 0;
#endif
- return arena;
+ return arena;
}
void
PyArena_Free(PyArena *arena)
{
- int r;
- assert(arena);
+ int r;
+ assert(arena);
#if defined(Py_DEBUG)
- /*
- fprintf(stderr,
- "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n",
- arena->total_allocs, arena->total_size, arena->total_blocks,
- arena->total_block_size, arena->total_big_blocks,
- PyList_Size(arena->a_objects));
- */
+ /*
+ fprintf(stderr,
+ "alloc=%d size=%d blocks=%d block_size=%d big=%d objects=%d\n",
+ arena->total_allocs, arena->total_size, arena->total_blocks,
+ arena->total_block_size, arena->total_big_blocks,
+ PyList_Size(arena->a_objects));
+ */
#endif
- block_free(arena->a_head);
- /* This property normally holds, except when the code being compiled
- is sys.getobjects(0), in which case there will be two references.
- assert(arena->a_objects->ob_refcnt == 1);
- */
-
- /* Clear all the elements from the list. This is necessary
- to guarantee that they will be DECREFed. */
- r = PyList_SetSlice(arena->a_objects,
- 0, PyList_GET_SIZE(arena->a_objects), NULL);
- assert(r == 0);
- assert(PyList_GET_SIZE(arena->a_objects) == 0);
- Py_DECREF(arena->a_objects);
- free(arena);
+ block_free(arena->a_head);
+ /* This property normally holds, except when the code being compiled
+ is sys.getobjects(0), in which case there will be two references.
+ assert(arena->a_objects->ob_refcnt == 1);
+ */
+
+ /* Clear all the elements from the list. This is necessary
+ to guarantee that they will be DECREFed. */
+ r = PyList_SetSlice(arena->a_objects,
+ 0, PyList_GET_SIZE(arena->a_objects), NULL);
+ assert(r == 0);
+ assert(PyList_GET_SIZE(arena->a_objects) == 0);
+ Py_DECREF(arena->a_objects);
+ free(arena);
}
void *
PyArena_Malloc(PyArena *arena, size_t size)
{
- void *p = block_alloc(arena->a_cur, size);
- if (!p)
- return PyErr_NoMemory();
+ void *p = block_alloc(arena->a_cur, size);
+ if (!p)
+ return PyErr_NoMemory();
#if defined(Py_DEBUG)
- arena->total_allocs++;
- arena->total_size += size;
+ arena->total_allocs++;
+ arena->total_size += size;
#endif
- /* Reset cur if we allocated a new block. */
- if (arena->a_cur->ab_next) {
- arena->a_cur = arena->a_cur->ab_next;
+ /* Reset cur if we allocated a new block. */
+ if (arena->a_cur->ab_next) {
+ arena->a_cur = arena->a_cur->ab_next;
#if defined(Py_DEBUG)
- arena->total_blocks++;
- arena->total_block_size += arena->a_cur->ab_size;
- if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE)
- ++arena->total_big_blocks;
+ arena->total_blocks++;
+ arena->total_block_size += arena->a_cur->ab_size;
+ if (arena->a_cur->ab_size > DEFAULT_BLOCK_SIZE)
+ ++arena->total_big_blocks;
#endif
- }
- return p;
+ }
+ return p;
}
int
PyArena_AddPyObject(PyArena *arena, PyObject *obj)
{
- int r = PyList_Append(arena->a_objects, obj);
- if (r >= 0) {
- Py_DECREF(obj);
- }
- return r;
+ int r = PyList_Append(arena->a_objects, obj);
+ if (r >= 0) {
+ Py_DECREF(obj);
+ }
+ return r;
}
diff --git a/Python/pymath.c b/Python/pymath.c
index 83105f2..827a773 100644
--- a/Python/pymath.c
+++ b/Python/pymath.c
@@ -7,9 +7,9 @@
thus rounding from extended precision to double precision. */
double _Py_force_double(double x)
{
- volatile double y;
- y = x;
- return y;
+ volatile double y;
+ y = x;
+ return y;
}
#endif
@@ -34,21 +34,21 @@ void _Py_set_387controlword(unsigned short cw) {
#ifndef HAVE_HYPOT
double hypot(double x, double y)
{
- double yx;
+ double yx;
- x = fabs(x);
- y = fabs(y);
- if (x < y) {
- double temp = x;
- x = y;
- y = temp;
- }
- if (x == 0.)
- return 0.;
- else {
- yx = y/x;
- return x*sqrt(1.+yx*yx);
- }
+ x = fabs(x);
+ y = fabs(y);
+ if (x < y) {
+ double temp = x;
+ x = y;
+ y = temp;
+ }
+ if (x == 0.)
+ return 0.;
+ else {
+ yx = y/x;
+ return x*sqrt(1.+yx*yx);
+ }
}
#endif /* HAVE_HYPOT */
@@ -56,12 +56,12 @@ double hypot(double x, double y)
double
copysign(double x, double y)
{
- /* use atan2 to distinguish -0. from 0. */
- if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) {
- return fabs(x);
- } else {
- return -fabs(x);
- }
+ /* use atan2 to distinguish -0. from 0. */
+ if (y > 0. || (y == 0. && atan2(y, -1.) > 0.)) {
+ return fabs(x);
+ } else {
+ return -fabs(x);
+ }
}
#endif /* HAVE_COPYSIGN */
@@ -73,7 +73,7 @@ round(double x)
absx = fabs(x);
y = floor(absx);
if (absx - y >= 0.5)
- y += 1.0;
+ y += 1.0;
return copysign(y, x);
}
#endif /* HAVE_ROUND */
diff --git a/Python/pystate.c b/Python/pystate.c
index 343a97b..5afc01a 100644
--- a/Python/pystate.c
+++ b/Python/pystate.c
@@ -58,92 +58,92 @@ static void _PyGILState_NoteThreadState(PyThreadState* tstate);
PyInterpreterState *
PyInterpreterState_New(void)
{
- PyInterpreterState *interp = (PyInterpreterState *)
- malloc(sizeof(PyInterpreterState));
+ PyInterpreterState *interp = (PyInterpreterState *)
+ malloc(sizeof(PyInterpreterState));
- if (interp != NULL) {
- HEAD_INIT();
+ if (interp != NULL) {
+ HEAD_INIT();
#ifdef WITH_THREAD
- if (head_mutex == NULL)
- Py_FatalError("Can't initialize threads for interpreter");
+ if (head_mutex == NULL)
+ Py_FatalError("Can't initialize threads for interpreter");
#endif
- interp->modules = NULL;
- interp->modules_reloading = NULL;
- interp->sysdict = NULL;
- interp->builtins = NULL;
- interp->tstate_head = NULL;
- interp->codec_search_path = NULL;
- interp->codec_search_cache = NULL;
- interp->codec_error_registry = NULL;
+ interp->modules = NULL;
+ interp->modules_reloading = NULL;
+ interp->sysdict = NULL;
+ interp->builtins = NULL;
+ interp->tstate_head = NULL;
+ interp->codec_search_path = NULL;
+ interp->codec_search_cache = NULL;
+ interp->codec_error_registry = NULL;
#ifdef HAVE_DLOPEN
#ifdef RTLD_NOW
- interp->dlopenflags = RTLD_NOW;
+ interp->dlopenflags = RTLD_NOW;
#else
- interp->dlopenflags = RTLD_LAZY;
+ interp->dlopenflags = RTLD_LAZY;
#endif
#endif
#ifdef WITH_TSC
- interp->tscdump = 0;
+ interp->tscdump = 0;
#endif
- HEAD_LOCK();
- interp->next = interp_head;
- interp_head = interp;
- HEAD_UNLOCK();
- }
+ HEAD_LOCK();
+ interp->next = interp_head;
+ interp_head = interp;
+ HEAD_UNLOCK();
+ }
- return interp;
+ return interp;
}
void
PyInterpreterState_Clear(PyInterpreterState *interp)
{
- PyThreadState *p;
- HEAD_LOCK();
- for (p = interp->tstate_head; p != NULL; p = p->next)
- PyThreadState_Clear(p);
- HEAD_UNLOCK();
- Py_CLEAR(interp->codec_search_path);
- Py_CLEAR(interp->codec_search_cache);
- Py_CLEAR(interp->codec_error_registry);
- Py_CLEAR(interp->modules);
- Py_CLEAR(interp->modules_reloading);
- Py_CLEAR(interp->sysdict);
- Py_CLEAR(interp->builtins);
+ PyThreadState *p;
+ HEAD_LOCK();
+ for (p = interp->tstate_head; p != NULL; p = p->next)
+ PyThreadState_Clear(p);
+ HEAD_UNLOCK();
+ Py_CLEAR(interp->codec_search_path);
+ Py_CLEAR(interp->codec_search_cache);
+ Py_CLEAR(interp->codec_error_registry);
+ Py_CLEAR(interp->modules);
+ Py_CLEAR(interp->modules_reloading);
+ Py_CLEAR(interp->sysdict);
+ Py_CLEAR(interp->builtins);
}
static void
zapthreads(PyInterpreterState *interp)
{
- PyThreadState *p;
- /* No need to lock the mutex here because this should only happen
- when the threads are all really dead (XXX famous last words). */
- while ((p = interp->tstate_head) != NULL) {
- PyThreadState_Delete(p);
- }
+ PyThreadState *p;
+ /* No need to lock the mutex here because this should only happen
+ when the threads are all really dead (XXX famous last words). */
+ while ((p = interp->tstate_head) != NULL) {
+ PyThreadState_Delete(p);
+ }
}
void
PyInterpreterState_Delete(PyInterpreterState *interp)
{
- PyInterpreterState **p;
- zapthreads(interp);
- HEAD_LOCK();
- for (p = &interp_head; ; p = &(*p)->next) {
- if (*p == NULL)
- Py_FatalError(
- "PyInterpreterState_Delete: invalid interp");
- if (*p == interp)
- break;
- }
- if (interp->tstate_head != NULL)
- Py_FatalError("PyInterpreterState_Delete: remaining threads");
- *p = interp->next;
- HEAD_UNLOCK();
- free(interp);
+ PyInterpreterState **p;
+ zapthreads(interp);
+ HEAD_LOCK();
+ for (p = &interp_head; ; p = &(*p)->next) {
+ if (*p == NULL)
+ Py_FatalError(
+ "PyInterpreterState_Delete: invalid interp");
+ if (*p == interp)
+ break;
+ }
+ if (interp->tstate_head != NULL)
+ Py_FatalError("PyInterpreterState_Delete: remaining threads");
+ *p = interp->next;
+ HEAD_UNLOCK();
+ free(interp);
}
@@ -151,104 +151,104 @@ PyInterpreterState_Delete(PyInterpreterState *interp)
static struct _frame *
threadstate_getframe(PyThreadState *self)
{
- return self->frame;
+ return self->frame;
}
static PyThreadState *
new_threadstate(PyInterpreterState *interp, int init)
{
- PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState));
+ PyThreadState *tstate = (PyThreadState *)malloc(sizeof(PyThreadState));
- if (_PyThreadState_GetFrame == NULL)
- _PyThreadState_GetFrame = threadstate_getframe;
+ if (_PyThreadState_GetFrame == NULL)
+ _PyThreadState_GetFrame = threadstate_getframe;
- if (tstate != NULL) {
- tstate->interp = interp;
+ if (tstate != NULL) {
+ tstate->interp = interp;
- tstate->frame = NULL;
- tstate->recursion_depth = 0;
- tstate->tracing = 0;
- tstate->use_tracing = 0;
- tstate->tick_counter = 0;
- tstate->gilstate_counter = 0;
- tstate->async_exc = NULL;
+ tstate->frame = NULL;
+ tstate->recursion_depth = 0;
+ tstate->tracing = 0;
+ tstate->use_tracing = 0;
+ tstate->tick_counter = 0;
+ tstate->gilstate_counter = 0;
+ tstate->async_exc = NULL;
#ifdef WITH_THREAD
- tstate->thread_id = PyThread_get_thread_ident();
+ tstate->thread_id = PyThread_get_thread_ident();
#else
- tstate->thread_id = 0;
+ tstate->thread_id = 0;
#endif
- tstate->dict = NULL;
+ tstate->dict = NULL;
- tstate->curexc_type = NULL;
- tstate->curexc_value = NULL;
- tstate->curexc_traceback = NULL;
+ tstate->curexc_type = NULL;
+ tstate->curexc_value = NULL;
+ tstate->curexc_traceback = NULL;
- tstate->exc_type = NULL;
- tstate->exc_value = NULL;
- tstate->exc_traceback = NULL;
+ tstate->exc_type = NULL;
+ tstate->exc_value = NULL;
+ tstate->exc_traceback = NULL;
- tstate->c_profilefunc = NULL;
- tstate->c_tracefunc = NULL;
- tstate->c_profileobj = NULL;
- tstate->c_traceobj = NULL;
+ tstate->c_profilefunc = NULL;
+ tstate->c_tracefunc = NULL;
+ tstate->c_profileobj = NULL;
+ tstate->c_traceobj = NULL;
- if (init)
- _PyThreadState_Init(tstate);
+ if (init)
+ _PyThreadState_Init(tstate);
- HEAD_LOCK();
- tstate->next = interp->tstate_head;
- interp->tstate_head = tstate;
- HEAD_UNLOCK();
- }
+ HEAD_LOCK();
+ tstate->next = interp->tstate_head;
+ interp->tstate_head = tstate;
+ HEAD_UNLOCK();
+ }
- return tstate;
+ return tstate;
}
PyThreadState *
PyThreadState_New(PyInterpreterState *interp)
{
- return new_threadstate(interp, 1);
+ return new_threadstate(interp, 1);
}
PyThreadState *
_PyThreadState_Prealloc(PyInterpreterState *interp)
{
- return new_threadstate(interp, 0);
+ return new_threadstate(interp, 0);
}
void
_PyThreadState_Init(PyThreadState *tstate)
{
#ifdef WITH_THREAD
- _PyGILState_NoteThreadState(tstate);
+ _PyGILState_NoteThreadState(tstate);
#endif
}
void
PyThreadState_Clear(PyThreadState *tstate)
{
- if (Py_VerboseFlag && tstate->frame != NULL)
- fprintf(stderr,
- "PyThreadState_Clear: warning: thread still has a frame\n");
+ if (Py_VerboseFlag && tstate->frame != NULL)
+ fprintf(stderr,
+ "PyThreadState_Clear: warning: thread still has a frame\n");
- Py_CLEAR(tstate->frame);
+ Py_CLEAR(tstate->frame);
- Py_CLEAR(tstate->dict);
- Py_CLEAR(tstate->async_exc);
+ Py_CLEAR(tstate->dict);
+ Py_CLEAR(tstate->async_exc);
- Py_CLEAR(tstate->curexc_type);
- Py_CLEAR(tstate->curexc_value);
- Py_CLEAR(tstate->curexc_traceback);
+ Py_CLEAR(tstate->curexc_type);
+ Py_CLEAR(tstate->curexc_value);
+ Py_CLEAR(tstate->curexc_traceback);
- Py_CLEAR(tstate->exc_type);
- Py_CLEAR(tstate->exc_value);
- Py_CLEAR(tstate->exc_traceback);
+ Py_CLEAR(tstate->exc_type);
+ Py_CLEAR(tstate->exc_value);
+ Py_CLEAR(tstate->exc_traceback);
- tstate->c_profilefunc = NULL;
- tstate->c_tracefunc = NULL;
- Py_CLEAR(tstate->c_profileobj);
- Py_CLEAR(tstate->c_traceobj);
+ tstate->c_profilefunc = NULL;
+ tstate->c_tracefunc = NULL;
+ Py_CLEAR(tstate->c_profileobj);
+ Py_CLEAR(tstate->c_traceobj);
}
@@ -256,50 +256,50 @@ PyThreadState_Clear(PyThreadState *tstate)
static void
tstate_delete_common(PyThreadState *tstate)
{
- PyInterpreterState *interp;
- PyThreadState **p;
- PyThreadState *prev_p = NULL;
- if (tstate == NULL)
- Py_FatalError("PyThreadState_Delete: NULL tstate");
- interp = tstate->interp;
- if (interp == NULL)
- Py_FatalError("PyThreadState_Delete: NULL interp");
- HEAD_LOCK();
- for (p = &interp->tstate_head; ; p = &(*p)->next) {
- if (*p == NULL)
- Py_FatalError(
- "PyThreadState_Delete: invalid tstate");
- if (*p == tstate)
- break;
- /* Sanity check. These states should never happen but if
- * they do we must abort. Otherwise we'll end up spinning in
- * in a tight loop with the lock held. A similar check is done
- * in thread.c find_key(). */
- if (*p == prev_p)
- Py_FatalError(
- "PyThreadState_Delete: small circular list(!)"
- " and tstate not found.");
- prev_p = *p;
- if ((*p)->next == interp->tstate_head)
- Py_FatalError(
- "PyThreadState_Delete: circular list(!) and"
- " tstate not found.");
- }
- *p = tstate->next;
- HEAD_UNLOCK();
- free(tstate);
+ PyInterpreterState *interp;
+ PyThreadState **p;
+ PyThreadState *prev_p = NULL;
+ if (tstate == NULL)
+ Py_FatalError("PyThreadState_Delete: NULL tstate");
+ interp = tstate->interp;
+ if (interp == NULL)
+ Py_FatalError("PyThreadState_Delete: NULL interp");
+ HEAD_LOCK();
+ for (p = &interp->tstate_head; ; p = &(*p)->next) {
+ if (*p == NULL)
+ Py_FatalError(
+ "PyThreadState_Delete: invalid tstate");
+ if (*p == tstate)
+ break;
+ /* Sanity check. These states should never happen but if
+ * they do we must abort. Otherwise we'll end up spinning in
+ * in a tight loop with the lock held. A similar check is done
+ * in thread.c find_key(). */
+ if (*p == prev_p)
+ Py_FatalError(
+ "PyThreadState_Delete: small circular list(!)"
+ " and tstate not found.");
+ prev_p = *p;
+ if ((*p)->next == interp->tstate_head)
+ Py_FatalError(
+ "PyThreadState_Delete: circular list(!) and"
+ " tstate not found.");
+ }
+ *p = tstate->next;
+ HEAD_UNLOCK();
+ free(tstate);
}
void
PyThreadState_Delete(PyThreadState *tstate)
{
- if (tstate == _PyThreadState_Current)
- Py_FatalError("PyThreadState_Delete: tstate is still current");
- tstate_delete_common(tstate);
+ if (tstate == _PyThreadState_Current)
+ Py_FatalError("PyThreadState_Delete: tstate is still current");
+ tstate_delete_common(tstate);
#ifdef WITH_THREAD
- if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
- PyThread_delete_key_value(autoTLSkey);
+ if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
+ PyThread_delete_key_value(autoTLSkey);
#endif /* WITH_THREAD */
}
@@ -308,15 +308,15 @@ PyThreadState_Delete(PyThreadState *tstate)
void
PyThreadState_DeleteCurrent()
{
- PyThreadState *tstate = _PyThreadState_Current;
- if (tstate == NULL)
- Py_FatalError(
- "PyThreadState_DeleteCurrent: no current tstate");
- _PyThreadState_Current = NULL;
- tstate_delete_common(tstate);
- if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
- PyThread_delete_key_value(autoTLSkey);
- PyEval_ReleaseLock();
+ PyThreadState *tstate = _PyThreadState_Current;
+ if (tstate == NULL)
+ Py_FatalError(
+ "PyThreadState_DeleteCurrent: no current tstate");
+ _PyThreadState_Current = NULL;
+ tstate_delete_common(tstate);
+ if (autoTLSkey && PyThread_get_key_value(autoTLSkey) == tstate)
+ PyThread_delete_key_value(autoTLSkey);
+ PyEval_ReleaseLock();
}
#endif /* WITH_THREAD */
@@ -324,36 +324,36 @@ PyThreadState_DeleteCurrent()
PyThreadState *
PyThreadState_Get(void)
{
- if (_PyThreadState_Current == NULL)
- Py_FatalError("PyThreadState_Get: no current thread");
+ if (_PyThreadState_Current == NULL)
+ Py_FatalError("PyThreadState_Get: no current thread");
- return _PyThreadState_Current;
+ return _PyThreadState_Current;
}
PyThreadState *
PyThreadState_Swap(PyThreadState *newts)
{
- PyThreadState *oldts = _PyThreadState_Current;
+ PyThreadState *oldts = _PyThreadState_Current;
- _PyThreadState_Current = newts;
- /* It should not be possible for more than one thread state
- to be used for a thread. Check this the best we can in debug
- builds.
- */
+ _PyThreadState_Current = newts;
+ /* It should not be possible for more than one thread state
+ to be used for a thread. Check this the best we can in debug
+ builds.
+ */
#if defined(Py_DEBUG) && defined(WITH_THREAD)
- if (newts) {
- /* This can be called from PyEval_RestoreThread(). Similar
- to it, we need to ensure errno doesn't change.
- */
- int err = errno;
- PyThreadState *check = PyGILState_GetThisThreadState();
- if (check && check->interp == newts->interp && check != newts)
- Py_FatalError("Invalid thread state for this thread");
- errno = err;
- }
+ if (newts) {
+ /* This can be called from PyEval_RestoreThread(). Similar
+ to it, we need to ensure errno doesn't change.
+ */
+ int err = errno;
+ PyThreadState *check = PyGILState_GetThisThreadState();
+ if (check && check->interp == newts->interp && check != newts)
+ Py_FatalError("Invalid thread state for this thread");
+ errno = err;
+ }
#endif
- return oldts;
+ return oldts;
}
/* An extension mechanism to store arbitrary additional per-thread state.
@@ -365,16 +365,16 @@ PyThreadState_Swap(PyThreadState *newts)
PyObject *
PyThreadState_GetDict(void)
{
- if (_PyThreadState_Current == NULL)
- return NULL;
-
- if (_PyThreadState_Current->dict == NULL) {
- PyObject *d;
- _PyThreadState_Current->dict = d = PyDict_New();
- if (d == NULL)
- PyErr_Clear();
- }
- return _PyThreadState_Current->dict;
+ if (_PyThreadState_Current == NULL)
+ return NULL;
+
+ if (_PyThreadState_Current->dict == NULL) {
+ PyObject *d;
+ _PyThreadState_Current->dict = d = PyDict_New();
+ if (d == NULL)
+ PyErr_Clear();
+ }
+ return _PyThreadState_Current->dict;
}
@@ -388,36 +388,36 @@ PyThreadState_GetDict(void)
int
PyThreadState_SetAsyncExc(long id, PyObject *exc) {
- PyThreadState *tstate = PyThreadState_GET();
- PyInterpreterState *interp = tstate->interp;
- PyThreadState *p;
-
- /* Although the GIL is held, a few C API functions can be called
- * without the GIL held, and in particular some that create and
- * destroy thread and interpreter states. Those can mutate the
- * list of thread states we're traversing, so to prevent that we lock
- * head_mutex for the duration.
- */
- HEAD_LOCK();
- for (p = interp->tstate_head; p != NULL; p = p->next) {
- if (p->thread_id == id) {
- /* Tricky: we need to decref the current value
- * (if any) in p->async_exc, but that can in turn
- * allow arbitrary Python code to run, including
- * perhaps calls to this function. To prevent
- * deadlock, we need to release head_mutex before
- * the decref.
- */
- PyObject *old_exc = p->async_exc;
- Py_XINCREF(exc);
- p->async_exc = exc;
- HEAD_UNLOCK();
- Py_XDECREF(old_exc);
- return 1;
- }
- }
- HEAD_UNLOCK();
- return 0;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyInterpreterState *interp = tstate->interp;
+ PyThreadState *p;
+
+ /* Although the GIL is held, a few C API functions can be called
+ * without the GIL held, and in particular some that create and
+ * destroy thread and interpreter states. Those can mutate the
+ * list of thread states we're traversing, so to prevent that we lock
+ * head_mutex for the duration.
+ */
+ HEAD_LOCK();
+ for (p = interp->tstate_head; p != NULL; p = p->next) {
+ if (p->thread_id == id) {
+ /* Tricky: we need to decref the current value
+ * (if any) in p->async_exc, but that can in turn
+ * allow arbitrary Python code to run, including
+ * perhaps calls to this function. To prevent
+ * deadlock, we need to release head_mutex before
+ * the decref.
+ */
+ PyObject *old_exc = p->async_exc;
+ Py_XINCREF(exc);
+ p->async_exc = exc;
+ HEAD_UNLOCK();
+ Py_XDECREF(old_exc);
+ return 1;
+ }
+ }
+ HEAD_UNLOCK();
+ return 0;
}
@@ -427,22 +427,22 @@ PyThreadState_SetAsyncExc(long id, PyObject *exc) {
PyInterpreterState *
PyInterpreterState_Head(void)
{
- return interp_head;
+ return interp_head;
}
PyInterpreterState *
PyInterpreterState_Next(PyInterpreterState *interp) {
- return interp->next;
+ return interp->next;
}
PyThreadState *
PyInterpreterState_ThreadHead(PyInterpreterState *interp) {
- return interp->tstate_head;
+ return interp->tstate_head;
}
PyThreadState *
PyThreadState_Next(PyThreadState *tstate) {
- return tstate->next;
+ return tstate->next;
}
/* The implementation of sys._current_frames(). This is intended to be
@@ -453,44 +453,44 @@ PyThreadState_Next(PyThreadState *tstate) {
PyObject *
_PyThread_CurrentFrames(void)
{
- PyObject *result;
- PyInterpreterState *i;
-
- result = PyDict_New();
- if (result == NULL)
- return NULL;
-
- /* for i in all interpreters:
- * for t in all of i's thread states:
- * if t's frame isn't NULL, map t's id to its frame
- * Because these lists can mutute even when the GIL is held, we
- * need to grab head_mutex for the duration.
- */
- HEAD_LOCK();
- for (i = interp_head; i != NULL; i = i->next) {
- PyThreadState *t;
- for (t = i->tstate_head; t != NULL; t = t->next) {
- PyObject *id;
- int stat;
- struct _frame *frame = t->frame;
- if (frame == NULL)
- continue;
- id = PyInt_FromLong(t->thread_id);
- if (id == NULL)
- goto Fail;
- stat = PyDict_SetItem(result, id, (PyObject *)frame);
- Py_DECREF(id);
- if (stat < 0)
- goto Fail;
- }
- }
- HEAD_UNLOCK();
- return result;
+ PyObject *result;
+ PyInterpreterState *i;
+
+ result = PyDict_New();
+ if (result == NULL)
+ return NULL;
+
+ /* for i in all interpreters:
+ * for t in all of i's thread states:
+ * if t's frame isn't NULL, map t's id to its frame
+ * Because these lists can mutute even when the GIL is held, we
+ * need to grab head_mutex for the duration.
+ */
+ HEAD_LOCK();
+ for (i = interp_head; i != NULL; i = i->next) {
+ PyThreadState *t;
+ for (t = i->tstate_head; t != NULL; t = t->next) {
+ PyObject *id;
+ int stat;
+ struct _frame *frame = t->frame;
+ if (frame == NULL)
+ continue;
+ id = PyInt_FromLong(t->thread_id);
+ if (id == NULL)
+ goto Fail;
+ stat = PyDict_SetItem(result, id, (PyObject *)frame);
+ Py_DECREF(id);
+ if (stat < 0)
+ goto Fail;
+ }
+ }
+ HEAD_UNLOCK();
+ return result;
Fail:
- HEAD_UNLOCK();
- Py_DECREF(result);
- return NULL;
+ HEAD_UNLOCK();
+ Py_DECREF(result);
+ return NULL;
}
/* Python "auto thread state" API. */
@@ -507,12 +507,12 @@ _PyThread_CurrentFrames(void)
static int
PyThreadState_IsCurrent(PyThreadState *tstate)
{
- /* Must be the tstate for this thread */
- assert(PyGILState_GetThisThreadState()==tstate);
- /* On Windows at least, simple reads and writes to 32 bit values
- are atomic.
- */
- return tstate == _PyThreadState_Current;
+ /* Must be the tstate for this thread */
+ assert(PyGILState_GetThisThreadState()==tstate);
+ /* On Windows at least, simple reads and writes to 32 bit values
+ are atomic.
+ */
+ return tstate == _PyThreadState_Current;
}
/* Internal initialization/finalization functions called by
@@ -521,21 +521,21 @@ PyThreadState_IsCurrent(PyThreadState *tstate)
void
_PyGILState_Init(PyInterpreterState *i, PyThreadState *t)
{
- assert(i && t); /* must init with valid states */
- autoTLSkey = PyThread_create_key();
- autoInterpreterState = i;
- assert(PyThread_get_key_value(autoTLSkey) == NULL);
- assert(t->gilstate_counter == 0);
+ assert(i && t); /* must init with valid states */
+ autoTLSkey = PyThread_create_key();
+ autoInterpreterState = i;
+ assert(PyThread_get_key_value(autoTLSkey) == NULL);
+ assert(t->gilstate_counter == 0);
- _PyGILState_NoteThreadState(t);
+ _PyGILState_NoteThreadState(t);
}
void
_PyGILState_Fini(void)
{
- PyThread_delete_key(autoTLSkey);
- autoTLSkey = 0;
- autoInterpreterState = NULL;
+ PyThread_delete_key(autoTLSkey);
+ autoTLSkey = 0;
+ autoInterpreterState = NULL;
}
/* When a thread state is created for a thread by some mechanism other than
@@ -546,113 +546,113 @@ _PyGILState_Fini(void)
static void
_PyGILState_NoteThreadState(PyThreadState* tstate)
{
- /* If autoTLSkey is 0, this must be the very first threadstate created
- in Py_Initialize(). Don't do anything for now (we'll be back here
- when _PyGILState_Init is called). */
- if (!autoTLSkey)
- return;
-
- /* Stick the thread state for this thread in thread local storage.
-
- The only situation where you can legitimately have more than one
- thread state for an OS level thread is when there are multiple
- interpreters, when:
-
- a) You shouldn't really be using the PyGILState_ APIs anyway,
- and:
-
- b) The slightly odd way PyThread_set_key_value works (see
- comments by its implementation) means that the first thread
- state created for that given OS level thread will "win",
- which seems reasonable behaviour.
- */
- if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
- Py_FatalError("Couldn't create autoTLSkey mapping");
-
- /* PyGILState_Release must not try to delete this thread state. */
- tstate->gilstate_counter = 1;
+ /* If autoTLSkey is 0, this must be the very first threadstate created
+ in Py_Initialize(). Don't do anything for now (we'll be back here
+ when _PyGILState_Init is called). */
+ if (!autoTLSkey)
+ return;
+
+ /* Stick the thread state for this thread in thread local storage.
+
+ The only situation where you can legitimately have more than one
+ thread state for an OS level thread is when there are multiple
+ interpreters, when:
+
+ a) You shouldn't really be using the PyGILState_ APIs anyway,
+ and:
+
+ b) The slightly odd way PyThread_set_key_value works (see
+ comments by its implementation) means that the first thread
+ state created for that given OS level thread will "win",
+ which seems reasonable behaviour.
+ */
+ if (PyThread_set_key_value(autoTLSkey, (void *)tstate) < 0)
+ Py_FatalError("Couldn't create autoTLSkey mapping");
+
+ /* PyGILState_Release must not try to delete this thread state. */
+ tstate->gilstate_counter = 1;
}
/* The public functions */
PyThreadState *
PyGILState_GetThisThreadState(void)
{
- if (autoInterpreterState == NULL || autoTLSkey == 0)
- return NULL;
- return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
+ if (autoInterpreterState == NULL || autoTLSkey == 0)
+ return NULL;
+ return (PyThreadState *)PyThread_get_key_value(autoTLSkey);
}
PyGILState_STATE
PyGILState_Ensure(void)
{
- int current;
- PyThreadState *tcur;
- /* Note that we do not auto-init Python here - apart from
- potential races with 2 threads auto-initializing, pep-311
- spells out other issues. Embedders are expected to have
- called Py_Initialize() and usually PyEval_InitThreads().
- */
- assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
- tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
- if (tcur == NULL) {
- /* Create a new thread state for this thread */
- tcur = PyThreadState_New(autoInterpreterState);
- if (tcur == NULL)
- Py_FatalError("Couldn't create thread-state for new thread");
- /* This is our thread state! We'll need to delete it in the
- matching call to PyGILState_Release(). */
- tcur->gilstate_counter = 0;
- current = 0; /* new thread state is never current */
- }
- else
- current = PyThreadState_IsCurrent(tcur);
- if (current == 0)
- PyEval_RestoreThread(tcur);
- /* Update our counter in the thread-state - no need for locks:
- - tcur will remain valid as we hold the GIL.
- - the counter is safe as we are the only thread "allowed"
- to modify this value
- */
- ++tcur->gilstate_counter;
- return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
+ int current;
+ PyThreadState *tcur;
+ /* Note that we do not auto-init Python here - apart from
+ potential races with 2 threads auto-initializing, pep-311
+ spells out other issues. Embedders are expected to have
+ called Py_Initialize() and usually PyEval_InitThreads().
+ */
+ assert(autoInterpreterState); /* Py_Initialize() hasn't been called! */
+ tcur = (PyThreadState *)PyThread_get_key_value(autoTLSkey);
+ if (tcur == NULL) {
+ /* Create a new thread state for this thread */
+ tcur = PyThreadState_New(autoInterpreterState);
+ if (tcur == NULL)
+ Py_FatalError("Couldn't create thread-state for new thread");
+ /* This is our thread state! We'll need to delete it in the
+ matching call to PyGILState_Release(). */
+ tcur->gilstate_counter = 0;
+ current = 0; /* new thread state is never current */
+ }
+ else
+ current = PyThreadState_IsCurrent(tcur);
+ if (current == 0)
+ PyEval_RestoreThread(tcur);
+ /* Update our counter in the thread-state - no need for locks:
+ - tcur will remain valid as we hold the GIL.
+ - the counter is safe as we are the only thread "allowed"
+ to modify this value
+ */
+ ++tcur->gilstate_counter;
+ return current ? PyGILState_LOCKED : PyGILState_UNLOCKED;
}
void
PyGILState_Release(PyGILState_STATE oldstate)
{
- PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
- autoTLSkey);
- if (tcur == NULL)
- Py_FatalError("auto-releasing thread-state, "
- "but no thread-state for this thread");
- /* We must hold the GIL and have our thread state current */
- /* XXX - remove the check - the assert should be fine,
- but while this is very new (April 2003), the extra check
- by release-only users can't hurt.
- */
- if (! PyThreadState_IsCurrent(tcur))
- Py_FatalError("This thread state must be current when releasing");
- assert(PyThreadState_IsCurrent(tcur));
- --tcur->gilstate_counter;
- assert(tcur->gilstate_counter >= 0); /* illegal counter value */
-
- /* If we're going to destroy this thread-state, we must
- * clear it while the GIL is held, as destructors may run.
- */
- if (tcur->gilstate_counter == 0) {
- /* can't have been locked when we created it */
- assert(oldstate == PyGILState_UNLOCKED);
- PyThreadState_Clear(tcur);
- /* Delete the thread-state. Note this releases the GIL too!
- * It's vital that the GIL be held here, to avoid shutdown
- * races; see bugs 225673 and 1061968 (that nasty bug has a
- * habit of coming back).
- */
- PyThreadState_DeleteCurrent();
- }
- /* Release the lock if necessary */
- else if (oldstate == PyGILState_UNLOCKED)
- PyEval_SaveThread();
+ PyThreadState *tcur = (PyThreadState *)PyThread_get_key_value(
+ autoTLSkey);
+ if (tcur == NULL)
+ Py_FatalError("auto-releasing thread-state, "
+ "but no thread-state for this thread");
+ /* We must hold the GIL and have our thread state current */
+ /* XXX - remove the check - the assert should be fine,
+ but while this is very new (April 2003), the extra check
+ by release-only users can't hurt.
+ */
+ if (! PyThreadState_IsCurrent(tcur))
+ Py_FatalError("This thread state must be current when releasing");
+ assert(PyThreadState_IsCurrent(tcur));
+ --tcur->gilstate_counter;
+ assert(tcur->gilstate_counter >= 0); /* illegal counter value */
+
+ /* If we're going to destroy this thread-state, we must
+ * clear it while the GIL is held, as destructors may run.
+ */
+ if (tcur->gilstate_counter == 0) {
+ /* can't have been locked when we created it */
+ assert(oldstate == PyGILState_UNLOCKED);
+ PyThreadState_Clear(tcur);
+ /* Delete the thread-state. Note this releases the GIL too!
+ * It's vital that the GIL be held here, to avoid shutdown
+ * races; see bugs 225673 and 1061968 (that nasty bug has a
+ * habit of coming back).
+ */
+ PyThreadState_DeleteCurrent();
+ }
+ /* Release the lock if necessary */
+ else if (oldstate == PyGILState_UNLOCKED)
+ PyEval_SaveThread();
}
#ifdef __cplusplus
diff --git a/Python/pystrcmp.c b/Python/pystrcmp.c
index 84295e7..f9c2277 100644
--- a/Python/pystrcmp.c
+++ b/Python/pystrcmp.c
@@ -6,21 +6,21 @@
int
PyOS_mystrnicmp(const char *s1, const char *s2, Py_ssize_t size)
{
- if (size == 0)
- return 0;
- while ((--size > 0) &&
- (tolower((unsigned)*s1) == tolower((unsigned)*s2))) {
- if (!*s1++ || !*s2++)
- break;
- }
- return tolower((unsigned)*s1) - tolower((unsigned)*s2);
+ if (size == 0)
+ return 0;
+ while ((--size > 0) &&
+ (tolower((unsigned)*s1) == tolower((unsigned)*s2))) {
+ if (!*s1++ || !*s2++)
+ break;
+ }
+ return tolower((unsigned)*s1) - tolower((unsigned)*s2);
}
int
PyOS_mystricmp(const char *s1, const char *s2)
{
- while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) {
- ;
- }
- return (tolower((unsigned)*s1) - tolower((unsigned)*s2));
+ while (*s1 && (tolower((unsigned)*s1++) == tolower((unsigned)*s2++))) {
+ ;
+ }
+ return (tolower((unsigned)*s1) - tolower((unsigned)*s2));
}
diff --git a/Python/pystrtod.c b/Python/pystrtod.c
index 909e021..859af43 100644
--- a/Python/pystrtod.c
+++ b/Python/pystrtod.c
@@ -9,11 +9,11 @@
static int
case_insensitive_match(const char *s, const char *t)
{
- while(*t && Py_TOLOWER(*s) == *t) {
- s++;
- t++;
- }
- return *t ? 0 : 1;
+ while(*t && Py_TOLOWER(*s) == *t) {
+ s++;
+ t++;
+ }
+ return *t ? 0 : 1;
}
/* _Py_parse_inf_or_nan: Attempt to parse a string of the form "nan", "inf" or
@@ -25,36 +25,36 @@ case_insensitive_match(const char *s, const char *t)
double
_Py_parse_inf_or_nan(const char *p, char **endptr)
{
- double retval;
- const char *s;
- int negate = 0;
-
- s = p;
- if (*s == '-') {
- negate = 1;
- s++;
- }
- else if (*s == '+') {
- s++;
- }
- if (case_insensitive_match(s, "inf")) {
- s += 3;
- if (case_insensitive_match(s, "inity"))
- s += 5;
- retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL;
- }
+ double retval;
+ const char *s;
+ int negate = 0;
+
+ s = p;
+ if (*s == '-') {
+ negate = 1;
+ s++;
+ }
+ else if (*s == '+') {
+ s++;
+ }
+ if (case_insensitive_match(s, "inf")) {
+ s += 3;
+ if (case_insensitive_match(s, "inity"))
+ s += 5;
+ retval = negate ? -Py_HUGE_VAL : Py_HUGE_VAL;
+ }
#ifdef Py_NAN
- else if (case_insensitive_match(s, "nan")) {
- s += 3;
- retval = negate ? -Py_NAN : Py_NAN;
- }
+ else if (case_insensitive_match(s, "nan")) {
+ s += 3;
+ retval = negate ? -Py_NAN : Py_NAN;
+ }
#endif
- else {
- s = p;
- retval = -1.0;
- }
- *endptr = (char *)s;
- return retval;
+ else {
+ s = p;
+ retval = -1.0;
+ }
+ *endptr = (char *)s;
+ return retval;
}
/**
@@ -62,7 +62,7 @@ _Py_parse_inf_or_nan(const char *p, char **endptr)
* @nptr: the string to convert to a numeric value.
* @endptr: if non-%NULL, it returns the character after
* the last character used in the conversion.
- *
+ *
* Converts a string to a #gdouble value.
* This function behaves like the standard strtod() function
* does in the C locale. It does this without actually
@@ -79,7 +79,7 @@ _Py_parse_inf_or_nan(const char *p, char **endptr)
* stored in %errno. If the correct value would cause underflow,
* zero is returned and %ERANGE is stored in %errno.
* If memory allocation fails, %ENOMEM is stored in %errno.
- *
+ *
* This function resets %errno before calling strtod() so that
* you can reliably detect overflow and underflow.
*
@@ -91,23 +91,23 @@ _Py_parse_inf_or_nan(const char *p, char **endptr)
double
_PyOS_ascii_strtod(const char *nptr, char **endptr)
{
- double result;
- _Py_SET_53BIT_PRECISION_HEADER;
+ double result;
+ _Py_SET_53BIT_PRECISION_HEADER;
- assert(nptr != NULL);
- /* Set errno to zero, so that we can distinguish zero results
- and underflows */
- errno = 0;
+ assert(nptr != NULL);
+ /* Set errno to zero, so that we can distinguish zero results
+ and underflows */
+ errno = 0;
- _Py_SET_53BIT_PRECISION_START;
- result = _Py_dg_strtod(nptr, endptr);
- _Py_SET_53BIT_PRECISION_END;
+ _Py_SET_53BIT_PRECISION_START;
+ result = _Py_dg_strtod(nptr, endptr);
+ _Py_SET_53BIT_PRECISION_END;
- if (*endptr == nptr)
- /* string might represent an inf or nan */
- result = _Py_parse_inf_or_nan(nptr, endptr);
+ if (*endptr == nptr)
+ /* string might represent an inf or nan */
+ result = _Py_parse_inf_or_nan(nptr, endptr);
- return result;
+ return result;
}
@@ -124,148 +124,148 @@ _PyOS_ascii_strtod(const char *nptr, char **endptr)
double
_PyOS_ascii_strtod(const char *nptr, char **endptr)
{
- char *fail_pos;
- double val = -1.0;
- struct lconv *locale_data;
- const char *decimal_point;
- size_t decimal_point_len;
- const char *p, *decimal_point_pos;
- const char *end = NULL; /* Silence gcc */
- const char *digits_pos = NULL;
- int negate = 0;
-
- assert(nptr != NULL);
-
- fail_pos = NULL;
-
- locale_data = localeconv();
- decimal_point = locale_data->decimal_point;
- decimal_point_len = strlen(decimal_point);
-
- assert(decimal_point_len != 0);
-
- decimal_point_pos = NULL;
-
- /* Parse infinities and nans */
- val = _Py_parse_inf_or_nan(nptr, endptr);
- if (*endptr != nptr)
- return val;
-
- /* Set errno to zero, so that we can distinguish zero results
- and underflows */
- errno = 0;
-
- /* We process the optional sign manually, then pass the remainder to
- the system strtod. This ensures that the result of an underflow
- has the correct sign. (bug #1725) */
- p = nptr;
- /* Process leading sign, if present */
- if (*p == '-') {
- negate = 1;
- p++;
- }
- else if (*p == '+') {
- p++;
- }
-
- /* Some platform strtods accept hex floats; Python shouldn't (at the
- moment), so we check explicitly for strings starting with '0x'. */
- if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X'))
- goto invalid_string;
-
- /* Check that what's left begins with a digit or decimal point */
- if (!Py_ISDIGIT(*p) && *p != '.')
- goto invalid_string;
-
- digits_pos = p;
- if (decimal_point[0] != '.' ||
- decimal_point[1] != 0)
- {
- /* Look for a '.' in the input; if present, it'll need to be
- swapped for the current locale's decimal point before we
- call strtod. On the other hand, if we find the current
- locale's decimal point then the input is invalid. */
- while (Py_ISDIGIT(*p))
- p++;
-
- if (*p == '.')
- {
- decimal_point_pos = p++;
-
- /* locate end of number */
- while (Py_ISDIGIT(*p))
- p++;
-
- if (*p == 'e' || *p == 'E')
- p++;
- if (*p == '+' || *p == '-')
- p++;
- while (Py_ISDIGIT(*p))
- p++;
- end = p;
- }
- else if (strncmp(p, decimal_point, decimal_point_len) == 0)
- /* Python bug #1417699 */
- goto invalid_string;
- /* For the other cases, we need not convert the decimal
- point */
- }
-
- if (decimal_point_pos) {
- char *copy, *c;
- /* Create a copy of the input, with the '.' converted to the
- locale-specific decimal point */
- copy = (char *)PyMem_MALLOC(end - digits_pos +
- 1 + decimal_point_len);
- if (copy == NULL) {
- *endptr = (char *)nptr;
- errno = ENOMEM;
- return val;
- }
-
- c = copy;
- memcpy(c, digits_pos, decimal_point_pos - digits_pos);
- c += decimal_point_pos - digits_pos;
- memcpy(c, decimal_point, decimal_point_len);
- c += decimal_point_len;
- memcpy(c, decimal_point_pos + 1,
- end - (decimal_point_pos + 1));
- c += end - (decimal_point_pos + 1);
- *c = 0;
-
- val = strtod(copy, &fail_pos);
-
- if (fail_pos)
- {
- if (fail_pos > decimal_point_pos)
- fail_pos = (char *)digits_pos +
- (fail_pos - copy) -
- (decimal_point_len - 1);
- else
- fail_pos = (char *)digits_pos +
- (fail_pos - copy);
- }
-
- PyMem_FREE(copy);
-
- }
- else {
- val = strtod(digits_pos, &fail_pos);
- }
-
- if (fail_pos == digits_pos)
- goto invalid_string;
-
- if (negate && fail_pos != nptr)
- val = -val;
- *endptr = fail_pos;
-
- return val;
+ char *fail_pos;
+ double val = -1.0;
+ struct lconv *locale_data;
+ const char *decimal_point;
+ size_t decimal_point_len;
+ const char *p, *decimal_point_pos;
+ const char *end = NULL; /* Silence gcc */
+ const char *digits_pos = NULL;
+ int negate = 0;
+
+ assert(nptr != NULL);
+
+ fail_pos = NULL;
+
+ locale_data = localeconv();
+ decimal_point = locale_data->decimal_point;
+ decimal_point_len = strlen(decimal_point);
+
+ assert(decimal_point_len != 0);
+
+ decimal_point_pos = NULL;
+
+ /* Parse infinities and nans */
+ val = _Py_parse_inf_or_nan(nptr, endptr);
+ if (*endptr != nptr)
+ return val;
+
+ /* Set errno to zero, so that we can distinguish zero results
+ and underflows */
+ errno = 0;
+
+ /* We process the optional sign manually, then pass the remainder to
+ the system strtod. This ensures that the result of an underflow
+ has the correct sign. (bug #1725) */
+ p = nptr;
+ /* Process leading sign, if present */
+ if (*p == '-') {
+ negate = 1;
+ p++;
+ }
+ else if (*p == '+') {
+ p++;
+ }
+
+ /* Some platform strtods accept hex floats; Python shouldn't (at the
+ moment), so we check explicitly for strings starting with '0x'. */
+ if (*p == '0' && (*(p+1) == 'x' || *(p+1) == 'X'))
+ goto invalid_string;
+
+ /* Check that what's left begins with a digit or decimal point */
+ if (!Py_ISDIGIT(*p) && *p != '.')
+ goto invalid_string;
+
+ digits_pos = p;
+ if (decimal_point[0] != '.' ||
+ decimal_point[1] != 0)
+ {
+ /* Look for a '.' in the input; if present, it'll need to be
+ swapped for the current locale's decimal point before we
+ call strtod. On the other hand, if we find the current
+ locale's decimal point then the input is invalid. */
+ while (Py_ISDIGIT(*p))
+ p++;
+
+ if (*p == '.')
+ {
+ decimal_point_pos = p++;
+
+ /* locate end of number */
+ while (Py_ISDIGIT(*p))
+ p++;
+
+ if (*p == 'e' || *p == 'E')
+ p++;
+ if (*p == '+' || *p == '-')
+ p++;
+ while (Py_ISDIGIT(*p))
+ p++;
+ end = p;
+ }
+ else if (strncmp(p, decimal_point, decimal_point_len) == 0)
+ /* Python bug #1417699 */
+ goto invalid_string;
+ /* For the other cases, we need not convert the decimal
+ point */
+ }
+
+ if (decimal_point_pos) {
+ char *copy, *c;
+ /* Create a copy of the input, with the '.' converted to the
+ locale-specific decimal point */
+ copy = (char *)PyMem_MALLOC(end - digits_pos +
+ 1 + decimal_point_len);
+ if (copy == NULL) {
+ *endptr = (char *)nptr;
+ errno = ENOMEM;
+ return val;
+ }
+
+ c = copy;
+ memcpy(c, digits_pos, decimal_point_pos - digits_pos);
+ c += decimal_point_pos - digits_pos;
+ memcpy(c, decimal_point, decimal_point_len);
+ c += decimal_point_len;
+ memcpy(c, decimal_point_pos + 1,
+ end - (decimal_point_pos + 1));
+ c += end - (decimal_point_pos + 1);
+ *c = 0;
+
+ val = strtod(copy, &fail_pos);
+
+ if (fail_pos)
+ {
+ if (fail_pos > decimal_point_pos)
+ fail_pos = (char *)digits_pos +
+ (fail_pos - copy) -
+ (decimal_point_len - 1);
+ else
+ fail_pos = (char *)digits_pos +
+ (fail_pos - copy);
+ }
+
+ PyMem_FREE(copy);
+
+ }
+ else {
+ val = strtod(digits_pos, &fail_pos);
+ }
+
+ if (fail_pos == digits_pos)
+ goto invalid_string;
+
+ if (negate && fail_pos != nptr)
+ val = -val;
+ *endptr = fail_pos;
+
+ return val;
invalid_string:
- *endptr = (char*)nptr;
- errno = EINVAL;
- return -1.0;
+ *endptr = (char*)nptr;
+ errno = EINVAL;
+ return -1.0;
}
#endif
@@ -275,27 +275,27 @@ _PyOS_ascii_strtod(const char *nptr, char **endptr)
double
PyOS_ascii_strtod(const char *nptr, char **endptr)
{
- char *fail_pos;
- const char *p;
- double x;
-
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "PyOS_ascii_strtod and PyOS_ascii_atof are "
- "deprecated. Use PyOS_string_to_double "
- "instead.", 1) < 0)
- return -1.0;
-
- /* _PyOS_ascii_strtod already does everything that we want,
- except that it doesn't parse leading whitespace */
- p = nptr;
- while (Py_ISSPACE(*p))
- p++;
- x = _PyOS_ascii_strtod(p, &fail_pos);
- if (fail_pos == p)
- fail_pos = (char *)nptr;
- if (endptr)
- *endptr = (char *)fail_pos;
- return x;
+ char *fail_pos;
+ const char *p;
+ double x;
+
+ if (PyErr_WarnEx(PyExc_DeprecationWarning,
+ "PyOS_ascii_strtod and PyOS_ascii_atof are "
+ "deprecated. Use PyOS_string_to_double "
+ "instead.", 1) < 0)
+ return -1.0;
+
+ /* _PyOS_ascii_strtod already does everything that we want,
+ except that it doesn't parse leading whitespace */
+ p = nptr;
+ while (Py_ISSPACE(*p))
+ p++;
+ x = _PyOS_ascii_strtod(p, &fail_pos);
+ if (fail_pos == p)
+ fail_pos = (char *)nptr;
+ if (endptr)
+ *endptr = (char *)fail_pos;
+ return x;
}
/* PyOS_ascii_strtod is DEPRECATED in Python 2.7 and 3.1 */
@@ -303,7 +303,7 @@ PyOS_ascii_strtod(const char *nptr, char **endptr)
double
PyOS_ascii_atof(const char *nptr)
{
- return PyOS_ascii_strtod(nptr, NULL);
+ return PyOS_ascii_strtod(nptr, NULL);
}
/* PyOS_string_to_double is the recommended replacement for the deprecated
@@ -334,39 +334,39 @@ PyOS_ascii_atof(const char *nptr)
double
PyOS_string_to_double(const char *s,
- char **endptr,
- PyObject *overflow_exception)
+ char **endptr,
+ PyObject *overflow_exception)
{
- double x, result=-1.0;
- char *fail_pos;
-
- errno = 0;
- PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0)
- x = _PyOS_ascii_strtod(s, &fail_pos);
- PyFPE_END_PROTECT(x)
-
- if (errno == ENOMEM) {
- PyErr_NoMemory();
- fail_pos = (char *)s;
- }
- else if (!endptr && (fail_pos == s || *fail_pos != '\0'))
- PyErr_Format(PyExc_ValueError,
- "could not convert string to float: "
- "%.200s", s);
- else if (fail_pos == s)
- PyErr_Format(PyExc_ValueError,
- "could not convert string to float: "
- "%.200s", s);
- else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception)
- PyErr_Format(overflow_exception,
- "value too large to convert to float: "
- "%.200s", s);
- else
- result = x;
-
- if (endptr != NULL)
- *endptr = fail_pos;
- return result;
+ double x, result=-1.0;
+ char *fail_pos;
+
+ errno = 0;
+ PyFPE_START_PROTECT("PyOS_string_to_double", return -1.0)
+ x = _PyOS_ascii_strtod(s, &fail_pos);
+ PyFPE_END_PROTECT(x)
+
+ if (errno == ENOMEM) {
+ PyErr_NoMemory();
+ fail_pos = (char *)s;
+ }
+ else if (!endptr && (fail_pos == s || *fail_pos != '\0'))
+ PyErr_Format(PyExc_ValueError,
+ "could not convert string to float: "
+ "%.200s", s);
+ else if (fail_pos == s)
+ PyErr_Format(PyExc_ValueError,
+ "could not convert string to float: "
+ "%.200s", s);
+ else if (errno == ERANGE && fabs(x) >= 1.0 && overflow_exception)
+ PyErr_Format(overflow_exception,
+ "value too large to convert to float: "
+ "%.200s", s);
+ else
+ result = x;
+
+ if (endptr != NULL)
+ *endptr = fail_pos;
+ return result;
}
/* Given a string that may have a decimal point in the current
@@ -375,30 +375,30 @@ PyOS_string_to_double(const char *s,
Py_LOCAL_INLINE(void)
change_decimal_from_locale_to_dot(char* buffer)
{
- struct lconv *locale_data = localeconv();
- const char *decimal_point = locale_data->decimal_point;
-
- if (decimal_point[0] != '.' || decimal_point[1] != 0) {
- size_t decimal_point_len = strlen(decimal_point);
-
- if (*buffer == '+' || *buffer == '-')
- buffer++;
- while (Py_ISDIGIT(*buffer))
- buffer++;
- if (strncmp(buffer, decimal_point, decimal_point_len) == 0) {
- *buffer = '.';
- buffer++;
- if (decimal_point_len > 1) {
- /* buffer needs to get smaller */
- size_t rest_len = strlen(buffer +
- (decimal_point_len - 1));
- memmove(buffer,
- buffer + (decimal_point_len - 1),
- rest_len);
- buffer[rest_len] = 0;
- }
- }
- }
+ struct lconv *locale_data = localeconv();
+ const char *decimal_point = locale_data->decimal_point;
+
+ if (decimal_point[0] != '.' || decimal_point[1] != 0) {
+ size_t decimal_point_len = strlen(decimal_point);
+
+ if (*buffer == '+' || *buffer == '-')
+ buffer++;
+ while (Py_ISDIGIT(*buffer))
+ buffer++;
+ if (strncmp(buffer, decimal_point, decimal_point_len) == 0) {
+ *buffer = '.';
+ buffer++;
+ if (decimal_point_len > 1) {
+ /* buffer needs to get smaller */
+ size_t rest_len = strlen(buffer +
+ (decimal_point_len - 1));
+ memmove(buffer,
+ buffer + (decimal_point_len - 1),
+ rest_len);
+ buffer[rest_len] = 0;
+ }
+ }
+ }
}
@@ -413,65 +413,65 @@ as necessary to represent the exponent.
Py_LOCAL_INLINE(void)
ensure_minimum_exponent_length(char* buffer, size_t buf_size)
{
- char *p = strpbrk(buffer, "eE");
- if (p && (*(p + 1) == '-' || *(p + 1) == '+')) {
- char *start = p + 2;
- int exponent_digit_cnt = 0;
- int leading_zero_cnt = 0;
- int in_leading_zeros = 1;
- int significant_digit_cnt;
-
- /* Skip over the exponent and the sign. */
- p += 2;
-
- /* Find the end of the exponent, keeping track of leading
- zeros. */
- while (*p && Py_ISDIGIT(*p)) {
- if (in_leading_zeros && *p == '0')
- ++leading_zero_cnt;
- if (*p != '0')
- in_leading_zeros = 0;
- ++p;
- ++exponent_digit_cnt;
- }
-
- significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt;
- if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) {
- /* If there are 2 exactly digits, we're done,
- regardless of what they contain */
- }
- else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) {
- int extra_zeros_cnt;
-
- /* There are more than 2 digits in the exponent. See
- if we can delete some of the leading zeros */
- if (significant_digit_cnt < MIN_EXPONENT_DIGITS)
- significant_digit_cnt = MIN_EXPONENT_DIGITS;
- extra_zeros_cnt = exponent_digit_cnt -
- significant_digit_cnt;
-
- /* Delete extra_zeros_cnt worth of characters from the
- front of the exponent */
- assert(extra_zeros_cnt >= 0);
-
- /* Add one to significant_digit_cnt to copy the
- trailing 0 byte, thus setting the length */
- memmove(start,
- start + extra_zeros_cnt,
- significant_digit_cnt + 1);
- }
- else {
- /* If there are fewer than 2 digits, add zeros
- until there are 2, if there's enough room */
- int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt;
- if (start + zeros + exponent_digit_cnt + 1
- < buffer + buf_size) {
- memmove(start + zeros, start,
- exponent_digit_cnt + 1);
- memset(start, '0', zeros);
- }
- }
- }
+ char *p = strpbrk(buffer, "eE");
+ if (p && (*(p + 1) == '-' || *(p + 1) == '+')) {
+ char *start = p + 2;
+ int exponent_digit_cnt = 0;
+ int leading_zero_cnt = 0;
+ int in_leading_zeros = 1;
+ int significant_digit_cnt;
+
+ /* Skip over the exponent and the sign. */
+ p += 2;
+
+ /* Find the end of the exponent, keeping track of leading
+ zeros. */
+ while (*p && Py_ISDIGIT(*p)) {
+ if (in_leading_zeros && *p == '0')
+ ++leading_zero_cnt;
+ if (*p != '0')
+ in_leading_zeros = 0;
+ ++p;
+ ++exponent_digit_cnt;
+ }
+
+ significant_digit_cnt = exponent_digit_cnt - leading_zero_cnt;
+ if (exponent_digit_cnt == MIN_EXPONENT_DIGITS) {
+ /* If there are 2 exactly digits, we're done,
+ regardless of what they contain */
+ }
+ else if (exponent_digit_cnt > MIN_EXPONENT_DIGITS) {
+ int extra_zeros_cnt;
+
+ /* There are more than 2 digits in the exponent. See
+ if we can delete some of the leading zeros */
+ if (significant_digit_cnt < MIN_EXPONENT_DIGITS)
+ significant_digit_cnt = MIN_EXPONENT_DIGITS;
+ extra_zeros_cnt = exponent_digit_cnt -
+ significant_digit_cnt;
+
+ /* Delete extra_zeros_cnt worth of characters from the
+ front of the exponent */
+ assert(extra_zeros_cnt >= 0);
+
+ /* Add one to significant_digit_cnt to copy the
+ trailing 0 byte, thus setting the length */
+ memmove(start,
+ start + extra_zeros_cnt,
+ significant_digit_cnt + 1);
+ }
+ else {
+ /* If there are fewer than 2 digits, add zeros
+ until there are 2, if there's enough room */
+ int zeros = MIN_EXPONENT_DIGITS - exponent_digit_cnt;
+ if (start + zeros + exponent_digit_cnt + 1
+ < buffer + buf_size) {
+ memmove(start + zeros, start,
+ exponent_digit_cnt + 1);
+ memset(start, '0', zeros);
+ }
+ }
+ }
}
/* Remove trailing zeros after the decimal point from a numeric string; also
@@ -481,40 +481,40 @@ ensure_minimum_exponent_length(char* buffer, size_t buf_size)
Py_LOCAL_INLINE(void)
remove_trailing_zeros(char *buffer)
{
- char *old_fraction_end, *new_fraction_end, *end, *p;
-
- p = buffer;
- if (*p == '-' || *p == '+')
- /* Skip leading sign, if present */
- ++p;
- while (Py_ISDIGIT(*p))
- ++p;
-
- /* if there's no decimal point there's nothing to do */
- if (*p++ != '.')
- return;
-
- /* scan any digits after the point */
- while (Py_ISDIGIT(*p))
- ++p;
- old_fraction_end = p;
-
- /* scan up to ending '\0' */
- while (*p != '\0')
- p++;
- /* +1 to make sure that we move the null byte as well */
- end = p+1;
-
- /* scan back from fraction_end, looking for removable zeros */
- p = old_fraction_end;
- while (*(p-1) == '0')
- --p;
- /* and remove point if we've got that far */
- if (*(p-1) == '.')
- --p;
- new_fraction_end = p;
-
- memmove(new_fraction_end, old_fraction_end, end-old_fraction_end);
+ char *old_fraction_end, *new_fraction_end, *end, *p;
+
+ p = buffer;
+ if (*p == '-' || *p == '+')
+ /* Skip leading sign, if present */
+ ++p;
+ while (Py_ISDIGIT(*p))
+ ++p;
+
+ /* if there's no decimal point there's nothing to do */
+ if (*p++ != '.')
+ return;
+
+ /* scan any digits after the point */
+ while (Py_ISDIGIT(*p))
+ ++p;
+ old_fraction_end = p;
+
+ /* scan up to ending '\0' */
+ while (*p != '\0')
+ p++;
+ /* +1 to make sure that we move the null byte as well */
+ end = p+1;
+
+ /* scan back from fraction_end, looking for removable zeros */
+ p = old_fraction_end;
+ while (*(p-1) == '0')
+ --p;
+ /* and remove point if we've got that far */
+ if (*(p-1) == '.')
+ --p;
+ new_fraction_end = p;
+
+ memmove(new_fraction_end, old_fraction_end, end-old_fraction_end);
}
/* Ensure that buffer has a decimal point in it. The decimal point will not
@@ -527,91 +527,91 @@ remove_trailing_zeros(char *buffer)
Py_LOCAL_INLINE(char *)
ensure_decimal_point(char* buffer, size_t buf_size, int precision)
{
- int digit_count, insert_count = 0, convert_to_exp = 0;
- char *chars_to_insert, *digits_start;
-
- /* search for the first non-digit character */
- char *p = buffer;
- if (*p == '-' || *p == '+')
- /* Skip leading sign, if present. I think this could only
- ever be '-', but it can't hurt to check for both. */
- ++p;
- digits_start = p;
- while (*p && Py_ISDIGIT(*p))
- ++p;
- digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int);
-
- if (*p == '.') {
- if (Py_ISDIGIT(*(p+1))) {
- /* Nothing to do, we already have a decimal
- point and a digit after it */
- }
- else {
- /* We have a decimal point, but no following
- digit. Insert a zero after the decimal. */
- /* can't ever get here via PyOS_double_to_string */
- assert(precision == -1);
- ++p;
- chars_to_insert = "0";
- insert_count = 1;
- }
- }
- else if (!(*p == 'e' || *p == 'E')) {
- /* Don't add ".0" if we have an exponent. */
- if (digit_count == precision) {
- /* issue 5864: don't add a trailing .0 in the case
- where the '%g'-formatted result already has as many
- significant digits as were requested. Switch to
- exponential notation instead. */
- convert_to_exp = 1;
- /* no exponent, no point, and we shouldn't land here
- for infs and nans, so we must be at the end of the
- string. */
- assert(*p == '\0');
- }
- else {
- assert(precision == -1 || digit_count < precision);
- chars_to_insert = ".0";
- insert_count = 2;
- }
- }
- if (insert_count) {
- size_t buf_len = strlen(buffer);
- if (buf_len + insert_count + 1 >= buf_size) {
- /* If there is not enough room in the buffer
- for the additional text, just skip it. It's
- not worth generating an error over. */
- }
- else {
- memmove(p + insert_count, p,
- buffer + strlen(buffer) - p + 1);
- memcpy(p, chars_to_insert, insert_count);
- }
- }
- if (convert_to_exp) {
- int written;
- size_t buf_avail;
- p = digits_start;
- /* insert decimal point */
- assert(digit_count >= 1);
- memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */
- p[1] = '.';
- p += digit_count+1;
- assert(p <= buf_size+buffer);
- buf_avail = buf_size+buffer-p;
- if (buf_avail == 0)
- return NULL;
- /* Add exponent. It's okay to use lower case 'e': we only
- arrive here as a result of using the empty format code or
- repr/str builtins and those never want an upper case 'E' */
- written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1);
- if (!(0 <= written &&
- written < Py_SAFE_DOWNCAST(buf_avail, size_t, int)))
- /* output truncated, or something else bad happened */
- return NULL;
- remove_trailing_zeros(buffer);
- }
- return buffer;
+ int digit_count, insert_count = 0, convert_to_exp = 0;
+ char *chars_to_insert, *digits_start;
+
+ /* search for the first non-digit character */
+ char *p = buffer;
+ if (*p == '-' || *p == '+')
+ /* Skip leading sign, if present. I think this could only
+ ever be '-', but it can't hurt to check for both. */
+ ++p;
+ digits_start = p;
+ while (*p && Py_ISDIGIT(*p))
+ ++p;
+ digit_count = Py_SAFE_DOWNCAST(p - digits_start, Py_ssize_t, int);
+
+ if (*p == '.') {
+ if (Py_ISDIGIT(*(p+1))) {
+ /* Nothing to do, we already have a decimal
+ point and a digit after it */
+ }
+ else {
+ /* We have a decimal point, but no following
+ digit. Insert a zero after the decimal. */
+ /* can't ever get here via PyOS_double_to_string */
+ assert(precision == -1);
+ ++p;
+ chars_to_insert = "0";
+ insert_count = 1;
+ }
+ }
+ else if (!(*p == 'e' || *p == 'E')) {
+ /* Don't add ".0" if we have an exponent. */
+ if (digit_count == precision) {
+ /* issue 5864: don't add a trailing .0 in the case
+ where the '%g'-formatted result already has as many
+ significant digits as were requested. Switch to
+ exponential notation instead. */
+ convert_to_exp = 1;
+ /* no exponent, no point, and we shouldn't land here
+ for infs and nans, so we must be at the end of the
+ string. */
+ assert(*p == '\0');
+ }
+ else {
+ assert(precision == -1 || digit_count < precision);
+ chars_to_insert = ".0";
+ insert_count = 2;
+ }
+ }
+ if (insert_count) {
+ size_t buf_len = strlen(buffer);
+ if (buf_len + insert_count + 1 >= buf_size) {
+ /* If there is not enough room in the buffer
+ for the additional text, just skip it. It's
+ not worth generating an error over. */
+ }
+ else {
+ memmove(p + insert_count, p,
+ buffer + strlen(buffer) - p + 1);
+ memcpy(p, chars_to_insert, insert_count);
+ }
+ }
+ if (convert_to_exp) {
+ int written;
+ size_t buf_avail;
+ p = digits_start;
+ /* insert decimal point */
+ assert(digit_count >= 1);
+ memmove(p+2, p+1, digit_count); /* safe, but overwrites nul */
+ p[1] = '.';
+ p += digit_count+1;
+ assert(p <= buf_size+buffer);
+ buf_avail = buf_size+buffer-p;
+ if (buf_avail == 0)
+ return NULL;
+ /* Add exponent. It's okay to use lower case 'e': we only
+ arrive here as a result of using the empty format code or
+ repr/str builtins and those never want an upper case 'E' */
+ written = PyOS_snprintf(p, buf_avail, "e%+.02d", digit_count-1);
+ if (!(0 <= written &&
+ written < Py_SAFE_DOWNCAST(buf_avail, size_t, int)))
+ /* output truncated, or something else bad happened */
+ return NULL;
+ remove_trailing_zeros(buffer);
+ }
+ return buffer;
}
/* see FORMATBUFLEN in unicodeobject.c */
@@ -622,14 +622,14 @@ ensure_decimal_point(char* buffer, size_t buf_size, int precision)
* @buffer: A buffer to place the resulting string in
* @buf_size: The length of the buffer.
* @format: The printf()-style format to use for the
- * code to use for converting.
+ * code to use for converting.
* @d: The #gdouble to convert
*
* Converts a #gdouble to a string, using the '.' as
* decimal point. To format the number you pass in
* a printf()-style format string. Allowed conversion
* specifiers are 'e', 'E', 'f', 'F', 'g', 'G', and 'Z'.
- *
+ *
* 'Z' is the same as 'g', except it always has a decimal and
* at least one digit after the decimal.
*
@@ -637,97 +637,97 @@ ensure_decimal_point(char* buffer, size_t buf_size, int precision)
* On failure returns NULL but does not set any Python exception.
**/
char *
-_PyOS_ascii_formatd(char *buffer,
- size_t buf_size,
- const char *format,
- double d,
- int precision)
+_PyOS_ascii_formatd(char *buffer,
+ size_t buf_size,
+ const char *format,
+ double d,
+ int precision)
{
- char format_char;
- size_t format_len = strlen(format);
-
- /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but
- also with at least one character past the decimal. */
- char tmp_format[FLOAT_FORMATBUFLEN];
-
- /* The last character in the format string must be the format char */
- format_char = format[format_len - 1];
-
- if (format[0] != '%')
- return NULL;
-
- /* I'm not sure why this test is here. It's ensuring that the format
- string after the first character doesn't have a single quote, a
- lowercase l, or a percent. This is the reverse of the commented-out
- test about 10 lines ago. */
- if (strpbrk(format + 1, "'l%"))
- return NULL;
-
- /* Also curious about this function is that it accepts format strings
- like "%xg", which are invalid for floats. In general, the
- interface to this function is not very good, but changing it is
- difficult because it's a public API. */
-
- if (!(format_char == 'e' || format_char == 'E' ||
- format_char == 'f' || format_char == 'F' ||
- format_char == 'g' || format_char == 'G' ||
- format_char == 'Z'))
- return NULL;
-
- /* Map 'Z' format_char to 'g', by copying the format string and
- replacing the final char with a 'g' */
- if (format_char == 'Z') {
- if (format_len + 1 >= sizeof(tmp_format)) {
- /* The format won't fit in our copy. Error out. In
- practice, this will never happen and will be
- detected by returning NULL */
- return NULL;
- }
- strcpy(tmp_format, format);
- tmp_format[format_len - 1] = 'g';
- format = tmp_format;
- }
-
-
- /* Have PyOS_snprintf do the hard work */
- PyOS_snprintf(buffer, buf_size, format, d);
-
- /* Do various fixups on the return string */
-
- /* Get the current locale, and find the decimal point string.
- Convert that string back to a dot. */
- change_decimal_from_locale_to_dot(buffer);
-
- /* If an exponent exists, ensure that the exponent is at least
- MIN_EXPONENT_DIGITS digits, providing the buffer is large enough
- for the extra zeros. Also, if there are more than
- MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get
- back to MIN_EXPONENT_DIGITS */
- ensure_minimum_exponent_length(buffer, buf_size);
-
- /* If format_char is 'Z', make sure we have at least one character
- after the decimal point (and make sure we have a decimal point);
- also switch to exponential notation in some edge cases where the
- extra character would produce more significant digits that we
- really want. */
- if (format_char == 'Z')
- buffer = ensure_decimal_point(buffer, buf_size, precision);
-
- return buffer;
+ char format_char;
+ size_t format_len = strlen(format);
+
+ /* Issue 2264: code 'Z' requires copying the format. 'Z' is 'g', but
+ also with at least one character past the decimal. */
+ char tmp_format[FLOAT_FORMATBUFLEN];
+
+ /* The last character in the format string must be the format char */
+ format_char = format[format_len - 1];
+
+ if (format[0] != '%')
+ return NULL;
+
+ /* I'm not sure why this test is here. It's ensuring that the format
+ string after the first character doesn't have a single quote, a
+ lowercase l, or a percent. This is the reverse of the commented-out
+ test about 10 lines ago. */
+ if (strpbrk(format + 1, "'l%"))
+ return NULL;
+
+ /* Also curious about this function is that it accepts format strings
+ like "%xg", which are invalid for floats. In general, the
+ interface to this function is not very good, but changing it is
+ difficult because it's a public API. */
+
+ if (!(format_char == 'e' || format_char == 'E' ||
+ format_char == 'f' || format_char == 'F' ||
+ format_char == 'g' || format_char == 'G' ||
+ format_char == 'Z'))
+ return NULL;
+
+ /* Map 'Z' format_char to 'g', by copying the format string and
+ replacing the final char with a 'g' */
+ if (format_char == 'Z') {
+ if (format_len + 1 >= sizeof(tmp_format)) {
+ /* The format won't fit in our copy. Error out. In
+ practice, this will never happen and will be
+ detected by returning NULL */
+ return NULL;
+ }
+ strcpy(tmp_format, format);
+ tmp_format[format_len - 1] = 'g';
+ format = tmp_format;
+ }
+
+
+ /* Have PyOS_snprintf do the hard work */
+ PyOS_snprintf(buffer, buf_size, format, d);
+
+ /* Do various fixups on the return string */
+
+ /* Get the current locale, and find the decimal point string.
+ Convert that string back to a dot. */
+ change_decimal_from_locale_to_dot(buffer);
+
+ /* If an exponent exists, ensure that the exponent is at least
+ MIN_EXPONENT_DIGITS digits, providing the buffer is large enough
+ for the extra zeros. Also, if there are more than
+ MIN_EXPONENT_DIGITS, remove as many zeros as possible until we get
+ back to MIN_EXPONENT_DIGITS */
+ ensure_minimum_exponent_length(buffer, buf_size);
+
+ /* If format_char is 'Z', make sure we have at least one character
+ after the decimal point (and make sure we have a decimal point);
+ also switch to exponential notation in some edge cases where the
+ extra character would produce more significant digits that we
+ really want. */
+ if (format_char == 'Z')
+ buffer = ensure_decimal_point(buffer, buf_size, precision);
+
+ return buffer;
}
char *
-PyOS_ascii_formatd(char *buffer,
- size_t buf_size,
- const char *format,
- double d)
+PyOS_ascii_formatd(char *buffer,
+ size_t buf_size,
+ const char *format,
+ double d)
{
- if (PyErr_WarnEx(PyExc_DeprecationWarning,
- "PyOS_ascii_formatd is deprecated, "
- "use PyOS_double_to_string instead", 1) < 0)
- return NULL;
+ if (PyErr_WarnEx(PyExc_DeprecationWarning,
+ "PyOS_ascii_formatd is deprecated, "
+ "use PyOS_double_to_string instead", 1) < 0)
+ return NULL;
- return _PyOS_ascii_formatd(buffer, buf_size, format, d, -1);
+ return _PyOS_ascii_formatd(buffer, buf_size, format, d, -1);
}
#ifdef PY_NO_SHORT_FLOAT_REPR
@@ -740,146 +740,146 @@ PyAPI_FUNC(char *) PyOS_double_to_string(double val,
int flags,
int *type)
{
- char format[32];
- Py_ssize_t bufsize;
- char *buf;
- int t, exp;
- int upper = 0;
-
- /* Validate format_code, and map upper and lower case */
- switch (format_code) {
- case 'e': /* exponent */
- case 'f': /* fixed */
- case 'g': /* general */
- break;
- case 'E':
- upper = 1;
- format_code = 'e';
- break;
- case 'F':
- upper = 1;
- format_code = 'f';
- break;
- case 'G':
- upper = 1;
- format_code = 'g';
- break;
- case 'r': /* repr format */
- /* Supplied precision is unused, must be 0. */
- if (precision != 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
- /* The repr() precision (17 significant decimal digits) is the
- minimal number that is guaranteed to have enough precision
- so that if the number is read back in the exact same binary
- value is recreated. This is true for IEEE floating point
- by design, and also happens to work for all other modern
- hardware. */
- precision = 17;
- format_code = 'g';
- break;
- default:
- PyErr_BadInternalCall();
- return NULL;
- }
-
- /* Here's a quick-and-dirty calculation to figure out how big a buffer
- we need. In general, for a finite float we need:
-
- 1 byte for each digit of the decimal significand, and
-
- 1 for a possible sign
- 1 for a possible decimal point
- 2 for a possible [eE][+-]
- 1 for each digit of the exponent; if we allow 19 digits
- total then we're safe up to exponents of 2**63.
- 1 for the trailing nul byte
-
- This gives a total of 24 + the number of digits in the significand,
- and the number of digits in the significand is:
-
- for 'g' format: at most precision, except possibly
- when precision == 0, when it's 1.
- for 'e' format: precision+1
- for 'f' format: precision digits after the point, at least 1
- before. To figure out how many digits appear before the point
- we have to examine the size of the number. If fabs(val) < 1.0
- then there will be only one digit before the point. If
- fabs(val) >= 1.0, then there are at most
-
- 1+floor(log10(ceiling(fabs(val))))
-
- digits before the point (where the 'ceiling' allows for the
- possibility that the rounding rounds the integer part of val
- up). A safe upper bound for the above quantity is
- 1+floor(exp/3), where exp is the unique integer such that 0.5
- <= fabs(val)/2**exp < 1.0. This exp can be obtained from
- frexp.
-
- So we allow room for precision+1 digits for all formats, plus an
- extra floor(exp/3) digits for 'f' format.
-
- */
-
- if (Py_IS_NAN(val) || Py_IS_INFINITY(val))
- /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */
- bufsize = 5;
- else {
- bufsize = 25 + precision;
- if (format_code == 'f' && fabs(val) >= 1.0) {
- frexp(val, &exp);
- bufsize += exp/3;
- }
- }
-
- buf = PyMem_Malloc(bufsize);
- if (buf == NULL) {
- PyErr_NoMemory();
- return NULL;
- }
-
- /* Handle nan and inf. */
- if (Py_IS_NAN(val)) {
- strcpy(buf, "nan");
- t = Py_DTST_NAN;
- } else if (Py_IS_INFINITY(val)) {
- if (copysign(1., val) == 1.)
- strcpy(buf, "inf");
- else
- strcpy(buf, "-inf");
- t = Py_DTST_INFINITE;
- } else {
- t = Py_DTST_FINITE;
- if (flags & Py_DTSF_ADD_DOT_0)
- format_code = 'Z';
-
- PyOS_snprintf(format, sizeof(format), "%%%s.%i%c",
- (flags & Py_DTSF_ALT ? "#" : ""), precision,
- format_code);
- _PyOS_ascii_formatd(buf, bufsize, format, val, precision);
- }
-
- /* Add sign when requested. It's convenient (esp. when formatting
- complex numbers) to include a sign even for inf and nan. */
- if (flags & Py_DTSF_SIGN && buf[0] != '-') {
- size_t len = strlen(buf);
- /* the bufsize calculations above should ensure that we've got
- space to add a sign */
- assert((size_t)bufsize >= len+2);
- memmove(buf+1, buf, len+1);
- buf[0] = '+';
- }
- if (upper) {
- /* Convert to upper case. */
- char *p1;
- for (p1 = buf; *p1; p1++)
- *p1 = Py_TOUPPER(*p1);
- }
-
- if (type)
- *type = t;
- return buf;
+ char format[32];
+ Py_ssize_t bufsize;
+ char *buf;
+ int t, exp;
+ int upper = 0;
+
+ /* Validate format_code, and map upper and lower case */
+ switch (format_code) {
+ case 'e': /* exponent */
+ case 'f': /* fixed */
+ case 'g': /* general */
+ break;
+ case 'E':
+ upper = 1;
+ format_code = 'e';
+ break;
+ case 'F':
+ upper = 1;
+ format_code = 'f';
+ break;
+ case 'G':
+ upper = 1;
+ format_code = 'g';
+ break;
+ case 'r': /* repr format */
+ /* Supplied precision is unused, must be 0. */
+ if (precision != 0) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ /* The repr() precision (17 significant decimal digits) is the
+ minimal number that is guaranteed to have enough precision
+ so that if the number is read back in the exact same binary
+ value is recreated. This is true for IEEE floating point
+ by design, and also happens to work for all other modern
+ hardware. */
+ precision = 17;
+ format_code = 'g';
+ break;
+ default:
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ /* Here's a quick-and-dirty calculation to figure out how big a buffer
+ we need. In general, for a finite float we need:
+
+ 1 byte for each digit of the decimal significand, and
+
+ 1 for a possible sign
+ 1 for a possible decimal point
+ 2 for a possible [eE][+-]
+ 1 for each digit of the exponent; if we allow 19 digits
+ total then we're safe up to exponents of 2**63.
+ 1 for the trailing nul byte
+
+ This gives a total of 24 + the number of digits in the significand,
+ and the number of digits in the significand is:
+
+ for 'g' format: at most precision, except possibly
+ when precision == 0, when it's 1.
+ for 'e' format: precision+1
+ for 'f' format: precision digits after the point, at least 1
+ before. To figure out how many digits appear before the point
+ we have to examine the size of the number. If fabs(val) < 1.0
+ then there will be only one digit before the point. If
+ fabs(val) >= 1.0, then there are at most
+
+ 1+floor(log10(ceiling(fabs(val))))
+
+ digits before the point (where the 'ceiling' allows for the
+ possibility that the rounding rounds the integer part of val
+ up). A safe upper bound for the above quantity is
+ 1+floor(exp/3), where exp is the unique integer such that 0.5
+ <= fabs(val)/2**exp < 1.0. This exp can be obtained from
+ frexp.
+
+ So we allow room for precision+1 digits for all formats, plus an
+ extra floor(exp/3) digits for 'f' format.
+
+ */
+
+ if (Py_IS_NAN(val) || Py_IS_INFINITY(val))
+ /* 3 for 'inf'/'nan', 1 for sign, 1 for '\0' */
+ bufsize = 5;
+ else {
+ bufsize = 25 + precision;
+ if (format_code == 'f' && fabs(val) >= 1.0) {
+ frexp(val, &exp);
+ bufsize += exp/3;
+ }
+ }
+
+ buf = PyMem_Malloc(bufsize);
+ if (buf == NULL) {
+ PyErr_NoMemory();
+ return NULL;
+ }
+
+ /* Handle nan and inf. */
+ if (Py_IS_NAN(val)) {
+ strcpy(buf, "nan");
+ t = Py_DTST_NAN;
+ } else if (Py_IS_INFINITY(val)) {
+ if (copysign(1., val) == 1.)
+ strcpy(buf, "inf");
+ else
+ strcpy(buf, "-inf");
+ t = Py_DTST_INFINITE;
+ } else {
+ t = Py_DTST_FINITE;
+ if (flags & Py_DTSF_ADD_DOT_0)
+ format_code = 'Z';
+
+ PyOS_snprintf(format, sizeof(format), "%%%s.%i%c",
+ (flags & Py_DTSF_ALT ? "#" : ""), precision,
+ format_code);
+ _PyOS_ascii_formatd(buf, bufsize, format, val, precision);
+ }
+
+ /* Add sign when requested. It's convenient (esp. when formatting
+ complex numbers) to include a sign even for inf and nan. */
+ if (flags & Py_DTSF_SIGN && buf[0] != '-') {
+ size_t len = strlen(buf);
+ /* the bufsize calculations above should ensure that we've got
+ space to add a sign */
+ assert((size_t)bufsize >= len+2);
+ memmove(buf+1, buf, len+1);
+ buf[0] = '+';
+ }
+ if (upper) {
+ /* Convert to upper case. */
+ char *p1;
+ for (p1 = buf; *p1; p1++)
+ *p1 = Py_TOUPPER(*p1);
+ }
+
+ if (type)
+ *type = t;
+ return buf;
}
#else
@@ -894,14 +894,14 @@ PyAPI_FUNC(char *) PyOS_double_to_string(double val,
/* The lengths of these are known to the code below, so don't change them */
static char *lc_float_strings[] = {
- "inf",
- "nan",
- "e",
+ "inf",
+ "nan",
+ "e",
};
static char *uc_float_strings[] = {
- "INF",
- "NAN",
- "E",
+ "INF",
+ "NAN",
+ "E",
};
@@ -925,9 +925,9 @@ static char *uc_float_strings[] = {
be nonzero.
type, if non-NULL, will be set to one of these constants to identify
the type of the 'd' argument:
- Py_DTST_FINITE
- Py_DTST_INFINITE
- Py_DTST_NAN
+ Py_DTST_FINITE
+ Py_DTST_INFINITE
+ Py_DTST_NAN
Returns a PyMem_Malloc'd block of memory containing the resulting string,
or NULL on error. If NULL is returned, the Python error has been set.
@@ -935,315 +935,315 @@ static char *uc_float_strings[] = {
static char *
format_float_short(double d, char format_code,
- int mode, Py_ssize_t precision,
- int always_add_sign, int add_dot_0_if_integer,
- int use_alt_formatting, char **float_strings, int *type)
+ int mode, Py_ssize_t precision,
+ int always_add_sign, int add_dot_0_if_integer,
+ int use_alt_formatting, char **float_strings, int *type)
{
- char *buf = NULL;
- char *p = NULL;
- Py_ssize_t bufsize = 0;
- char *digits, *digits_end;
- int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0;
- Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end;
- _Py_SET_53BIT_PRECISION_HEADER;
-
- /* _Py_dg_dtoa returns a digit string (no decimal point or exponent).
- Must be matched by a call to _Py_dg_freedtoa. */
- _Py_SET_53BIT_PRECISION_START;
- digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign,
- &digits_end);
- _Py_SET_53BIT_PRECISION_END;
-
- decpt = (Py_ssize_t)decpt_as_int;
- if (digits == NULL) {
- /* The only failure mode is no memory. */
- PyErr_NoMemory();
- goto exit;
- }
- assert(digits_end != NULL && digits_end >= digits);
- digits_len = digits_end - digits;
-
- if (digits_len && !Py_ISDIGIT(digits[0])) {
- /* Infinities and nans here; adapt Gay's output,
- so convert Infinity to inf and NaN to nan, and
- ignore sign of nan. Then return. */
-
- /* ignore the actual sign of a nan */
- if (digits[0] == 'n' || digits[0] == 'N')
- sign = 0;
-
- /* We only need 5 bytes to hold the result "+inf\0" . */
- bufsize = 5; /* Used later in an assert. */
- buf = (char *)PyMem_Malloc(bufsize);
- if (buf == NULL) {
- PyErr_NoMemory();
- goto exit;
- }
- p = buf;
-
- if (sign == 1) {
- *p++ = '-';
- }
- else if (always_add_sign) {
- *p++ = '+';
- }
- if (digits[0] == 'i' || digits[0] == 'I') {
- strncpy(p, float_strings[OFS_INF], 3);
- p += 3;
-
- if (type)
- *type = Py_DTST_INFINITE;
- }
- else if (digits[0] == 'n' || digits[0] == 'N') {
- strncpy(p, float_strings[OFS_NAN], 3);
- p += 3;
-
- if (type)
- *type = Py_DTST_NAN;
- }
- else {
- /* shouldn't get here: Gay's code should always return
- something starting with a digit, an 'I', or 'N' */
- strncpy(p, "ERR", 3);
- p += 3;
- assert(0);
- }
- goto exit;
- }
-
- /* The result must be finite (not inf or nan). */
- if (type)
- *type = Py_DTST_FINITE;
-
-
- /* We got digits back, format them. We may need to pad 'digits'
- either on the left or right (or both) with extra zeros, so in
- general the resulting string has the form
-
- [<sign>]<zeros><digits><zeros>[<exponent>]
-
- where either of the <zeros> pieces could be empty, and there's a
- decimal point that could appear either in <digits> or in the
- leading or trailing <zeros>.
-
- Imagine an infinite 'virtual' string vdigits, consisting of the
- string 'digits' (starting at index 0) padded on both the left and
- right with infinite strings of zeros. We want to output a slice
-
- vdigits[vdigits_start : vdigits_end]
-
- of this virtual string. Thus if vdigits_start < 0 then we'll end
- up producing some leading zeros; if vdigits_end > digits_len there
- will be trailing zeros in the output. The next section of code
- determines whether to use an exponent or not, figures out the
- position 'decpt' of the decimal point, and computes 'vdigits_start'
- and 'vdigits_end'. */
- vdigits_end = digits_len;
- switch (format_code) {
- case 'e':
- use_exp = 1;
- vdigits_end = precision;
- break;
- case 'f':
- vdigits_end = decpt + precision;
- break;
- case 'g':
- if (decpt <= -4 || decpt >
- (add_dot_0_if_integer ? precision-1 : precision))
- use_exp = 1;
- if (use_alt_formatting)
- vdigits_end = precision;
- break;
- case 'r':
- /* convert to exponential format at 1e16. We used to convert
- at 1e17, but that gives odd-looking results for some values
- when a 16-digit 'shortest' repr is padded with bogus zeros.
- For example, repr(2e16+8) would give 20000000000000010.0;
- the true value is 20000000000000008.0. */
- if (decpt <= -4 || decpt > 16)
- use_exp = 1;
- break;
- default:
- PyErr_BadInternalCall();
- goto exit;
- }
-
- /* if using an exponent, reset decimal point position to 1 and adjust
- exponent accordingly.*/
- if (use_exp) {
- exp = decpt - 1;
- decpt = 1;
- }
- /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start <
- decpt < vdigits_end if add_dot_0_if_integer and no exponent */
- vdigits_start = decpt <= 0 ? decpt-1 : 0;
- if (!use_exp && add_dot_0_if_integer)
- vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1;
- else
- vdigits_end = vdigits_end > decpt ? vdigits_end : decpt;
-
- /* double check inequalities */
- assert(vdigits_start <= 0 &&
- 0 <= digits_len &&
- digits_len <= vdigits_end);
- /* decimal point should be in (vdigits_start, vdigits_end] */
- assert(vdigits_start < decpt && decpt <= vdigits_end);
-
- /* Compute an upper bound how much memory we need. This might be a few
- chars too long, but no big deal. */
- bufsize =
- /* sign, decimal point and trailing 0 byte */
- 3 +
-
- /* total digit count (including zero padding on both sides) */
- (vdigits_end - vdigits_start) +
-
- /* exponent "e+100", max 3 numerical digits */
- (use_exp ? 5 : 0);
-
- /* Now allocate the memory and initialize p to point to the start of
- it. */
- buf = (char *)PyMem_Malloc(bufsize);
- if (buf == NULL) {
- PyErr_NoMemory();
- goto exit;
- }
- p = buf;
-
- /* Add a negative sign if negative, and a plus sign if non-negative
- and always_add_sign is true. */
- if (sign == 1)
- *p++ = '-';
- else if (always_add_sign)
- *p++ = '+';
-
- /* note that exactly one of the three 'if' conditions is true,
- so we include exactly one decimal point */
- /* Zero padding on left of digit string */
- if (decpt <= 0) {
- memset(p, '0', decpt-vdigits_start);
- p += decpt - vdigits_start;
- *p++ = '.';
- memset(p, '0', 0-decpt);
- p += 0-decpt;
- }
- else {
- memset(p, '0', 0-vdigits_start);
- p += 0 - vdigits_start;
- }
-
- /* Digits, with included decimal point */
- if (0 < decpt && decpt <= digits_len) {
- strncpy(p, digits, decpt-0);
- p += decpt-0;
- *p++ = '.';
- strncpy(p, digits+decpt, digits_len-decpt);
- p += digits_len-decpt;
- }
- else {
- strncpy(p, digits, digits_len);
- p += digits_len;
- }
-
- /* And zeros on the right */
- if (digits_len < decpt) {
- memset(p, '0', decpt-digits_len);
- p += decpt-digits_len;
- *p++ = '.';
- memset(p, '0', vdigits_end-decpt);
- p += vdigits_end-decpt;
- }
- else {
- memset(p, '0', vdigits_end-digits_len);
- p += vdigits_end-digits_len;
- }
-
- /* Delete a trailing decimal pt unless using alternative formatting. */
- if (p[-1] == '.' && !use_alt_formatting)
- p--;
-
- /* Now that we've done zero padding, add an exponent if needed. */
- if (use_exp) {
- *p++ = float_strings[OFS_E][0];
- exp_len = sprintf(p, "%+.02d", exp);
- p += exp_len;
- }
+ char *buf = NULL;
+ char *p = NULL;
+ Py_ssize_t bufsize = 0;
+ char *digits, *digits_end;
+ int decpt_as_int, sign, exp_len, exp = 0, use_exp = 0;
+ Py_ssize_t decpt, digits_len, vdigits_start, vdigits_end;
+ _Py_SET_53BIT_PRECISION_HEADER;
+
+ /* _Py_dg_dtoa returns a digit string (no decimal point or exponent).
+ Must be matched by a call to _Py_dg_freedtoa. */
+ _Py_SET_53BIT_PRECISION_START;
+ digits = _Py_dg_dtoa(d, mode, precision, &decpt_as_int, &sign,
+ &digits_end);
+ _Py_SET_53BIT_PRECISION_END;
+
+ decpt = (Py_ssize_t)decpt_as_int;
+ if (digits == NULL) {
+ /* The only failure mode is no memory. */
+ PyErr_NoMemory();
+ goto exit;
+ }
+ assert(digits_end != NULL && digits_end >= digits);
+ digits_len = digits_end - digits;
+
+ if (digits_len && !Py_ISDIGIT(digits[0])) {
+ /* Infinities and nans here; adapt Gay's output,
+ so convert Infinity to inf and NaN to nan, and
+ ignore sign of nan. Then return. */
+
+ /* ignore the actual sign of a nan */
+ if (digits[0] == 'n' || digits[0] == 'N')
+ sign = 0;
+
+ /* We only need 5 bytes to hold the result "+inf\0" . */
+ bufsize = 5; /* Used later in an assert. */
+ buf = (char *)PyMem_Malloc(bufsize);
+ if (buf == NULL) {
+ PyErr_NoMemory();
+ goto exit;
+ }
+ p = buf;
+
+ if (sign == 1) {
+ *p++ = '-';
+ }
+ else if (always_add_sign) {
+ *p++ = '+';
+ }
+ if (digits[0] == 'i' || digits[0] == 'I') {
+ strncpy(p, float_strings[OFS_INF], 3);
+ p += 3;
+
+ if (type)
+ *type = Py_DTST_INFINITE;
+ }
+ else if (digits[0] == 'n' || digits[0] == 'N') {
+ strncpy(p, float_strings[OFS_NAN], 3);
+ p += 3;
+
+ if (type)
+ *type = Py_DTST_NAN;
+ }
+ else {
+ /* shouldn't get here: Gay's code should always return
+ something starting with a digit, an 'I', or 'N' */
+ strncpy(p, "ERR", 3);
+ p += 3;
+ assert(0);
+ }
+ goto exit;
+ }
+
+ /* The result must be finite (not inf or nan). */
+ if (type)
+ *type = Py_DTST_FINITE;
+
+
+ /* We got digits back, format them. We may need to pad 'digits'
+ either on the left or right (or both) with extra zeros, so in
+ general the resulting string has the form
+
+ [<sign>]<zeros><digits><zeros>[<exponent>]
+
+ where either of the <zeros> pieces could be empty, and there's a
+ decimal point that could appear either in <digits> or in the
+ leading or trailing <zeros>.
+
+ Imagine an infinite 'virtual' string vdigits, consisting of the
+ string 'digits' (starting at index 0) padded on both the left and
+ right with infinite strings of zeros. We want to output a slice
+
+ vdigits[vdigits_start : vdigits_end]
+
+ of this virtual string. Thus if vdigits_start < 0 then we'll end
+ up producing some leading zeros; if vdigits_end > digits_len there
+ will be trailing zeros in the output. The next section of code
+ determines whether to use an exponent or not, figures out the
+ position 'decpt' of the decimal point, and computes 'vdigits_start'
+ and 'vdigits_end'. */
+ vdigits_end = digits_len;
+ switch (format_code) {
+ case 'e':
+ use_exp = 1;
+ vdigits_end = precision;
+ break;
+ case 'f':
+ vdigits_end = decpt + precision;
+ break;
+ case 'g':
+ if (decpt <= -4 || decpt >
+ (add_dot_0_if_integer ? precision-1 : precision))
+ use_exp = 1;
+ if (use_alt_formatting)
+ vdigits_end = precision;
+ break;
+ case 'r':
+ /* convert to exponential format at 1e16. We used to convert
+ at 1e17, but that gives odd-looking results for some values
+ when a 16-digit 'shortest' repr is padded with bogus zeros.
+ For example, repr(2e16+8) would give 20000000000000010.0;
+ the true value is 20000000000000008.0. */
+ if (decpt <= -4 || decpt > 16)
+ use_exp = 1;
+ break;
+ default:
+ PyErr_BadInternalCall();
+ goto exit;
+ }
+
+ /* if using an exponent, reset decimal point position to 1 and adjust
+ exponent accordingly.*/
+ if (use_exp) {
+ exp = decpt - 1;
+ decpt = 1;
+ }
+ /* ensure vdigits_start < decpt <= vdigits_end, or vdigits_start <
+ decpt < vdigits_end if add_dot_0_if_integer and no exponent */
+ vdigits_start = decpt <= 0 ? decpt-1 : 0;
+ if (!use_exp && add_dot_0_if_integer)
+ vdigits_end = vdigits_end > decpt ? vdigits_end : decpt + 1;
+ else
+ vdigits_end = vdigits_end > decpt ? vdigits_end : decpt;
+
+ /* double check inequalities */
+ assert(vdigits_start <= 0 &&
+ 0 <= digits_len &&
+ digits_len <= vdigits_end);
+ /* decimal point should be in (vdigits_start, vdigits_end] */
+ assert(vdigits_start < decpt && decpt <= vdigits_end);
+
+ /* Compute an upper bound how much memory we need. This might be a few
+ chars too long, but no big deal. */
+ bufsize =
+ /* sign, decimal point and trailing 0 byte */
+ 3 +
+
+ /* total digit count (including zero padding on both sides) */
+ (vdigits_end - vdigits_start) +
+
+ /* exponent "e+100", max 3 numerical digits */
+ (use_exp ? 5 : 0);
+
+ /* Now allocate the memory and initialize p to point to the start of
+ it. */
+ buf = (char *)PyMem_Malloc(bufsize);
+ if (buf == NULL) {
+ PyErr_NoMemory();
+ goto exit;
+ }
+ p = buf;
+
+ /* Add a negative sign if negative, and a plus sign if non-negative
+ and always_add_sign is true. */
+ if (sign == 1)
+ *p++ = '-';
+ else if (always_add_sign)
+ *p++ = '+';
+
+ /* note that exactly one of the three 'if' conditions is true,
+ so we include exactly one decimal point */
+ /* Zero padding on left of digit string */
+ if (decpt <= 0) {
+ memset(p, '0', decpt-vdigits_start);
+ p += decpt - vdigits_start;
+ *p++ = '.';
+ memset(p, '0', 0-decpt);
+ p += 0-decpt;
+ }
+ else {
+ memset(p, '0', 0-vdigits_start);
+ p += 0 - vdigits_start;
+ }
+
+ /* Digits, with included decimal point */
+ if (0 < decpt && decpt <= digits_len) {
+ strncpy(p, digits, decpt-0);
+ p += decpt-0;
+ *p++ = '.';
+ strncpy(p, digits+decpt, digits_len-decpt);
+ p += digits_len-decpt;
+ }
+ else {
+ strncpy(p, digits, digits_len);
+ p += digits_len;
+ }
+
+ /* And zeros on the right */
+ if (digits_len < decpt) {
+ memset(p, '0', decpt-digits_len);
+ p += decpt-digits_len;
+ *p++ = '.';
+ memset(p, '0', vdigits_end-decpt);
+ p += vdigits_end-decpt;
+ }
+ else {
+ memset(p, '0', vdigits_end-digits_len);
+ p += vdigits_end-digits_len;
+ }
+
+ /* Delete a trailing decimal pt unless using alternative formatting. */
+ if (p[-1] == '.' && !use_alt_formatting)
+ p--;
+
+ /* Now that we've done zero padding, add an exponent if needed. */
+ if (use_exp) {
+ *p++ = float_strings[OFS_E][0];
+ exp_len = sprintf(p, "%+.02d", exp);
+ p += exp_len;
+ }
exit:
- if (buf) {
- *p = '\0';
- /* It's too late if this fails, as we've already stepped on
- memory that isn't ours. But it's an okay debugging test. */
- assert(p-buf < bufsize);
- }
- if (digits)
- _Py_dg_freedtoa(digits);
-
- return buf;
+ if (buf) {
+ *p = '\0';
+ /* It's too late if this fails, as we've already stepped on
+ memory that isn't ours. But it's an okay debugging test. */
+ assert(p-buf < bufsize);
+ }
+ if (digits)
+ _Py_dg_freedtoa(digits);
+
+ return buf;
}
PyAPI_FUNC(char *) PyOS_double_to_string(double val,
- char format_code,
- int precision,
- int flags,
- int *type)
+ char format_code,
+ int precision,
+ int flags,
+ int *type)
{
- char **float_strings = lc_float_strings;
- int mode;
-
- /* Validate format_code, and map upper and lower case. Compute the
- mode and make any adjustments as needed. */
- switch (format_code) {
- /* exponent */
- case 'E':
- float_strings = uc_float_strings;
- format_code = 'e';
- /* Fall through. */
- case 'e':
- mode = 2;
- precision++;
- break;
-
- /* fixed */
- case 'F':
- float_strings = uc_float_strings;
- format_code = 'f';
- /* Fall through. */
- case 'f':
- mode = 3;
- break;
-
- /* general */
- case 'G':
- float_strings = uc_float_strings;
- format_code = 'g';
- /* Fall through. */
- case 'g':
- mode = 2;
- /* precision 0 makes no sense for 'g' format; interpret as 1 */
- if (precision == 0)
- precision = 1;
- break;
-
- /* repr format */
- case 'r':
- mode = 0;
- /* Supplied precision is unused, must be 0. */
- if (precision != 0) {
- PyErr_BadInternalCall();
- return NULL;
- }
- break;
-
- default:
- PyErr_BadInternalCall();
- return NULL;
- }
-
- return format_float_short(val, format_code, mode, precision,
- flags & Py_DTSF_SIGN,
- flags & Py_DTSF_ADD_DOT_0,
- flags & Py_DTSF_ALT,
- float_strings, type);
+ char **float_strings = lc_float_strings;
+ int mode;
+
+ /* Validate format_code, and map upper and lower case. Compute the
+ mode and make any adjustments as needed. */
+ switch (format_code) {
+ /* exponent */
+ case 'E':
+ float_strings = uc_float_strings;
+ format_code = 'e';
+ /* Fall through. */
+ case 'e':
+ mode = 2;
+ precision++;
+ break;
+
+ /* fixed */
+ case 'F':
+ float_strings = uc_float_strings;
+ format_code = 'f';
+ /* Fall through. */
+ case 'f':
+ mode = 3;
+ break;
+
+ /* general */
+ case 'G':
+ float_strings = uc_float_strings;
+ format_code = 'g';
+ /* Fall through. */
+ case 'g':
+ mode = 2;
+ /* precision 0 makes no sense for 'g' format; interpret as 1 */
+ if (precision == 0)
+ precision = 1;
+ break;
+
+ /* repr format */
+ case 'r':
+ mode = 0;
+ /* Supplied precision is unused, must be 0. */
+ if (precision != 0) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ break;
+
+ default:
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+
+ return format_float_short(val, format_code, mode, precision,
+ flags & Py_DTSF_SIGN,
+ flags & Py_DTSF_ADD_DOT_0,
+ flags & Py_DTSF_ALT,
+ float_strings, type);
}
#endif /* ifdef PY_NO_SHORT_FLOAT_REPR */
diff --git a/Python/pythonrun.c b/Python/pythonrun.c
index 71a53ea..f203618 100644
--- a/Python/pythonrun.c
+++ b/Python/pythonrun.c
@@ -40,9 +40,9 @@
#ifndef Py_REF_DEBUG
#define PRINT_TOTAL_REFS()
#else /* Py_REF_DEBUG */
-#define PRINT_TOTAL_REFS() fprintf(stderr, \
- "[%" PY_FORMAT_SIZE_T "d refs]\n", \
- _Py_GetRefTotal())
+#define PRINT_TOTAL_REFS() fprintf(stderr, \
+ "[%" PY_FORMAT_SIZE_T "d refs]\n", \
+ _Py_GetRefTotal())
#endif
#ifdef __cplusplus
@@ -57,9 +57,9 @@ extern grammar _PyParser_Grammar; /* From graminit.c */
static void initmain(void);
static void initsite(void);
static PyObject *run_mod(mod_ty, const char *, PyObject *, PyObject *,
- PyCompilerFlags *, PyArena *);
+ PyCompilerFlags *, PyArena *);
static PyObject *run_pyc_file(FILE *, const char *, PyObject *, PyObject *,
- PyCompilerFlags *);
+ PyCompilerFlags *);
static void err_input(perrdetail *);
static void initsigs(void);
static void wait_for_thread_shutdown(void);
@@ -95,7 +95,7 @@ since _warnings is builtin. This API should not be used. */
PyObject *
PyModule_GetWarningsModule(void)
{
- return PyImport_ImportModule("warnings");
+ return PyImport_ImportModule("warnings");
}
static int initialized = 0;
@@ -105,7 +105,7 @@ static int initialized = 0;
int
Py_IsInitialized(void)
{
- return initialized;
+ return initialized;
}
/* Global initializations. Can be undone by Py_Finalize(). Don't
@@ -123,251 +123,251 @@ Py_IsInitialized(void)
static int
add_flag(int flag, const char *envs)
{
- int env = atoi(envs);
- if (flag < env)
- flag = env;
- if (flag < 1)
- flag = 1;
- return flag;
+ int env = atoi(envs);
+ if (flag < env)
+ flag = env;
+ if (flag < 1)
+ flag = 1;
+ return flag;
}
void
Py_InitializeEx(int install_sigs)
{
- PyInterpreterState *interp;
- PyThreadState *tstate;
- PyObject *bimod, *sysmod;
- char *p;
- char *icodeset = NULL; /* On Windows, input codeset may theoretically
- differ from output codeset. */
- char *codeset = NULL;
- char *errors = NULL;
- int free_codeset = 0;
- int overridden = 0;
- PyObject *sys_stream, *sys_isatty;
+ PyInterpreterState *interp;
+ PyThreadState *tstate;
+ PyObject *bimod, *sysmod;
+ char *p;
+ char *icodeset = NULL; /* On Windows, input codeset may theoretically
+ differ from output codeset. */
+ char *codeset = NULL;
+ char *errors = NULL;
+ int free_codeset = 0;
+ int overridden = 0;
+ PyObject *sys_stream, *sys_isatty;
#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
- char *saved_locale, *loc_codeset;
+ char *saved_locale, *loc_codeset;
#endif
#ifdef MS_WINDOWS
- char ibuf[128];
- char buf[128];
+ char ibuf[128];
+ char buf[128];
#endif
- extern void _Py_ReadyTypes(void);
+ extern void _Py_ReadyTypes(void);
- if (initialized)
- return;
- initialized = 1;
+ if (initialized)
+ return;
+ initialized = 1;
- if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
- Py_DebugFlag = add_flag(Py_DebugFlag, p);
- if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
- Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
- if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
- Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
- if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
- Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
+ if ((p = Py_GETENV("PYTHONDEBUG")) && *p != '\0')
+ Py_DebugFlag = add_flag(Py_DebugFlag, p);
+ if ((p = Py_GETENV("PYTHONVERBOSE")) && *p != '\0')
+ Py_VerboseFlag = add_flag(Py_VerboseFlag, p);
+ if ((p = Py_GETENV("PYTHONOPTIMIZE")) && *p != '\0')
+ Py_OptimizeFlag = add_flag(Py_OptimizeFlag, p);
+ if ((p = Py_GETENV("PYTHONDONTWRITEBYTECODE")) && *p != '\0')
+ Py_DontWriteBytecodeFlag = add_flag(Py_DontWriteBytecodeFlag, p);
- interp = PyInterpreterState_New();
- if (interp == NULL)
- Py_FatalError("Py_Initialize: can't make first interpreter");
+ interp = PyInterpreterState_New();
+ if (interp == NULL)
+ Py_FatalError("Py_Initialize: can't make first interpreter");
- tstate = PyThreadState_New(interp);
- if (tstate == NULL)
- Py_FatalError("Py_Initialize: can't make first thread");
- (void) PyThreadState_Swap(tstate);
+ tstate = PyThreadState_New(interp);
+ if (tstate == NULL)
+ Py_FatalError("Py_Initialize: can't make first thread");
+ (void) PyThreadState_Swap(tstate);
- _Py_ReadyTypes();
+ _Py_ReadyTypes();
- if (!_PyFrame_Init())
- Py_FatalError("Py_Initialize: can't init frames");
+ if (!_PyFrame_Init())
+ Py_FatalError("Py_Initialize: can't init frames");
- if (!_PyInt_Init())
- Py_FatalError("Py_Initialize: can't init ints");
+ if (!_PyInt_Init())
+ Py_FatalError("Py_Initialize: can't init ints");
- if (!_PyLong_Init())
- Py_FatalError("Py_Initialize: can't init longs");
+ if (!_PyLong_Init())
+ Py_FatalError("Py_Initialize: can't init longs");
- if (!PyByteArray_Init())
- Py_FatalError("Py_Initialize: can't init bytearray");
+ if (!PyByteArray_Init())
+ Py_FatalError("Py_Initialize: can't init bytearray");
- _PyFloat_Init();
+ _PyFloat_Init();
- interp->modules = PyDict_New();
- if (interp->modules == NULL)
- Py_FatalError("Py_Initialize: can't make modules dictionary");
- interp->modules_reloading = PyDict_New();
- if (interp->modules_reloading == NULL)
- Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
+ interp->modules = PyDict_New();
+ if (interp->modules == NULL)
+ Py_FatalError("Py_Initialize: can't make modules dictionary");
+ interp->modules_reloading = PyDict_New();
+ if (interp->modules_reloading == NULL)
+ Py_FatalError("Py_Initialize: can't make modules_reloading dictionary");
#ifdef Py_USING_UNICODE
- /* Init Unicode implementation; relies on the codec registry */
- _PyUnicode_Init();
+ /* Init Unicode implementation; relies on the codec registry */
+ _PyUnicode_Init();
#endif
- bimod = _PyBuiltin_Init();
- if (bimod == NULL)
- Py_FatalError("Py_Initialize: can't initialize __builtin__");
- interp->builtins = PyModule_GetDict(bimod);
- if (interp->builtins == NULL)
- Py_FatalError("Py_Initialize: can't initialize builtins dict");
- Py_INCREF(interp->builtins);
-
- sysmod = _PySys_Init();
- if (sysmod == NULL)
- Py_FatalError("Py_Initialize: can't initialize sys");
- interp->sysdict = PyModule_GetDict(sysmod);
- if (interp->sysdict == NULL)
- Py_FatalError("Py_Initialize: can't initialize sys dict");
- Py_INCREF(interp->sysdict);
- _PyImport_FixupExtension("sys", "sys");
- PySys_SetPath(Py_GetPath());
- PyDict_SetItemString(interp->sysdict, "modules",
- interp->modules);
-
- _PyImport_Init();
-
- /* initialize builtin exceptions */
- _PyExc_Init();
- _PyImport_FixupExtension("exceptions", "exceptions");
-
- /* phase 2 of builtins */
- _PyImport_FixupExtension("__builtin__", "__builtin__");
-
- _PyImportHooks_Init();
-
- if (install_sigs)
- initsigs(); /* Signal handling stuff, including initintr() */
-
- /* Initialize warnings. */
- _PyWarnings_Init();
- if (PySys_HasWarnOptions()) {
- PyObject *warnings_module = PyImport_ImportModule("warnings");
- if (!warnings_module)
- PyErr_Clear();
- Py_XDECREF(warnings_module);
- }
-
- initmain(); /* Module __main__ */
-
- /* auto-thread-state API, if available */
+ bimod = _PyBuiltin_Init();
+ if (bimod == NULL)
+ Py_FatalError("Py_Initialize: can't initialize __builtin__");
+ interp->builtins = PyModule_GetDict(bimod);
+ if (interp->builtins == NULL)
+ Py_FatalError("Py_Initialize: can't initialize builtins dict");
+ Py_INCREF(interp->builtins);
+
+ sysmod = _PySys_Init();
+ if (sysmod == NULL)
+ Py_FatalError("Py_Initialize: can't initialize sys");
+ interp->sysdict = PyModule_GetDict(sysmod);
+ if (interp->sysdict == NULL)
+ Py_FatalError("Py_Initialize: can't initialize sys dict");
+ Py_INCREF(interp->sysdict);
+ _PyImport_FixupExtension("sys", "sys");
+ PySys_SetPath(Py_GetPath());
+ PyDict_SetItemString(interp->sysdict, "modules",
+ interp->modules);
+
+ _PyImport_Init();
+
+ /* initialize builtin exceptions */
+ _PyExc_Init();
+ _PyImport_FixupExtension("exceptions", "exceptions");
+
+ /* phase 2 of builtins */
+ _PyImport_FixupExtension("__builtin__", "__builtin__");
+
+ _PyImportHooks_Init();
+
+ if (install_sigs)
+ initsigs(); /* Signal handling stuff, including initintr() */
+
+ /* Initialize warnings. */
+ _PyWarnings_Init();
+ if (PySys_HasWarnOptions()) {
+ PyObject *warnings_module = PyImport_ImportModule("warnings");
+ if (!warnings_module)
+ PyErr_Clear();
+ Py_XDECREF(warnings_module);
+ }
+
+ initmain(); /* Module __main__ */
+
+ /* auto-thread-state API, if available */
#ifdef WITH_THREAD
- _PyGILState_Init(interp, tstate);
+ _PyGILState_Init(interp, tstate);
#endif /* WITH_THREAD */
- if (!Py_NoSiteFlag)
- initsite(); /* Module site */
+ if (!Py_NoSiteFlag)
+ initsite(); /* Module site */
- if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
- p = icodeset = codeset = strdup(p);
- free_codeset = 1;
- errors = strchr(p, ':');
- if (errors) {
- *errors = '\0';
- errors++;
- }
- overridden = 1;
- }
+ if ((p = Py_GETENV("PYTHONIOENCODING")) && *p != '\0') {
+ p = icodeset = codeset = strdup(p);
+ free_codeset = 1;
+ errors = strchr(p, ':');
+ if (errors) {
+ *errors = '\0';
+ errors++;
+ }
+ overridden = 1;
+ }
#if defined(Py_USING_UNICODE) && defined(HAVE_LANGINFO_H) && defined(CODESET)
- /* On Unix, set the file system encoding according to the
- user's preference, if the CODESET names a well-known
- Python codec, and Py_FileSystemDefaultEncoding isn't
- initialized by other means. Also set the encoding of
- stdin and stdout if these are terminals, unless overridden. */
-
- if (!overridden || !Py_FileSystemDefaultEncoding) {
- saved_locale = strdup(setlocale(LC_CTYPE, NULL));
- setlocale(LC_CTYPE, "");
- loc_codeset = nl_langinfo(CODESET);
- if (loc_codeset && *loc_codeset) {
- PyObject *enc = PyCodec_Encoder(loc_codeset);
- if (enc) {
- loc_codeset = strdup(loc_codeset);
- Py_DECREF(enc);
- } else {
- if (PyErr_ExceptionMatches(PyExc_LookupError)) {
- PyErr_Clear();
- loc_codeset = NULL;
- } else {
- PyErr_Print();
- exit(1);
- }
- }
- } else
- loc_codeset = NULL;
- setlocale(LC_CTYPE, saved_locale);
- free(saved_locale);
-
- if (!overridden) {
- codeset = icodeset = loc_codeset;
- free_codeset = 1;
- }
-
- /* Initialize Py_FileSystemDefaultEncoding from
- locale even if PYTHONIOENCODING is set. */
- if (!Py_FileSystemDefaultEncoding) {
- Py_FileSystemDefaultEncoding = loc_codeset;
- if (!overridden)
- free_codeset = 0;
- }
- }
+ /* On Unix, set the file system encoding according to the
+ user's preference, if the CODESET names a well-known
+ Python codec, and Py_FileSystemDefaultEncoding isn't
+ initialized by other means. Also set the encoding of
+ stdin and stdout if these are terminals, unless overridden. */
+
+ if (!overridden || !Py_FileSystemDefaultEncoding) {
+ saved_locale = strdup(setlocale(LC_CTYPE, NULL));
+ setlocale(LC_CTYPE, "");
+ loc_codeset = nl_langinfo(CODESET);
+ if (loc_codeset && *loc_codeset) {
+ PyObject *enc = PyCodec_Encoder(loc_codeset);
+ if (enc) {
+ loc_codeset = strdup(loc_codeset);
+ Py_DECREF(enc);
+ } else {
+ if (PyErr_ExceptionMatches(PyExc_LookupError)) {
+ PyErr_Clear();
+ loc_codeset = NULL;
+ } else {
+ PyErr_Print();
+ exit(1);
+ }
+ }
+ } else
+ loc_codeset = NULL;
+ setlocale(LC_CTYPE, saved_locale);
+ free(saved_locale);
+
+ if (!overridden) {
+ codeset = icodeset = loc_codeset;
+ free_codeset = 1;
+ }
+
+ /* Initialize Py_FileSystemDefaultEncoding from
+ locale even if PYTHONIOENCODING is set. */
+ if (!Py_FileSystemDefaultEncoding) {
+ Py_FileSystemDefaultEncoding = loc_codeset;
+ if (!overridden)
+ free_codeset = 0;
+ }
+ }
#endif
#ifdef MS_WINDOWS
- if (!overridden) {
- icodeset = ibuf;
- codeset = buf;
- sprintf(ibuf, "cp%d", GetConsoleCP());
- sprintf(buf, "cp%d", GetConsoleOutputCP());
- }
+ if (!overridden) {
+ icodeset = ibuf;
+ codeset = buf;
+ sprintf(ibuf, "cp%d", GetConsoleCP());
+ sprintf(buf, "cp%d", GetConsoleOutputCP());
+ }
#endif
- if (codeset) {
- sys_stream = PySys_GetObject("stdin");
- sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
- if (!sys_isatty)
- PyErr_Clear();
- if ((overridden ||
- (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
- PyFile_Check(sys_stream)) {
- if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
- Py_FatalError("Cannot set codeset of stdin");
- }
- Py_XDECREF(sys_isatty);
-
- sys_stream = PySys_GetObject("stdout");
- sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
- if (!sys_isatty)
- PyErr_Clear();
- if ((overridden ||
- (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
- PyFile_Check(sys_stream)) {
- if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
- Py_FatalError("Cannot set codeset of stdout");
- }
- Py_XDECREF(sys_isatty);
-
- sys_stream = PySys_GetObject("stderr");
- sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
- if (!sys_isatty)
- PyErr_Clear();
- if((overridden ||
- (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
- PyFile_Check(sys_stream)) {
- if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
- Py_FatalError("Cannot set codeset of stderr");
- }
- Py_XDECREF(sys_isatty);
-
- if (free_codeset)
- free(codeset);
- }
+ if (codeset) {
+ sys_stream = PySys_GetObject("stdin");
+ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
+ if (!sys_isatty)
+ PyErr_Clear();
+ if ((overridden ||
+ (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
+ PyFile_Check(sys_stream)) {
+ if (!PyFile_SetEncodingAndErrors(sys_stream, icodeset, errors))
+ Py_FatalError("Cannot set codeset of stdin");
+ }
+ Py_XDECREF(sys_isatty);
+
+ sys_stream = PySys_GetObject("stdout");
+ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
+ if (!sys_isatty)
+ PyErr_Clear();
+ if ((overridden ||
+ (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
+ PyFile_Check(sys_stream)) {
+ if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
+ Py_FatalError("Cannot set codeset of stdout");
+ }
+ Py_XDECREF(sys_isatty);
+
+ sys_stream = PySys_GetObject("stderr");
+ sys_isatty = PyObject_CallMethod(sys_stream, "isatty", "");
+ if (!sys_isatty)
+ PyErr_Clear();
+ if((overridden ||
+ (sys_isatty && PyObject_IsTrue(sys_isatty))) &&
+ PyFile_Check(sys_stream)) {
+ if (!PyFile_SetEncodingAndErrors(sys_stream, codeset, errors))
+ Py_FatalError("Cannot set codeset of stderr");
+ }
+ Py_XDECREF(sys_isatty);
+
+ if (free_codeset)
+ free(codeset);
+ }
}
void
Py_Initialize(void)
{
- Py_InitializeEx(1);
+ Py_InitializeEx(1);
}
@@ -392,159 +392,159 @@ extern void dump_counts(FILE*);
void
Py_Finalize(void)
{
- PyInterpreterState *interp;
- PyThreadState *tstate;
-
- if (!initialized)
- return;
-
- wait_for_thread_shutdown();
-
- /* The interpreter is still entirely intact at this point, and the
- * exit funcs may be relying on that. In particular, if some thread
- * or exit func is still waiting to do an import, the import machinery
- * expects Py_IsInitialized() to return true. So don't say the
- * interpreter is uninitialized until after the exit funcs have run.
- * Note that Threading.py uses an exit func to do a join on all the
- * threads created thru it, so this also protects pending imports in
- * the threads created via Threading.
- */
- call_sys_exitfunc();
- initialized = 0;
-
- /* Get current thread state and interpreter pointer */
- tstate = PyThreadState_GET();
- interp = tstate->interp;
-
- /* Disable signal handling */
- PyOS_FiniInterrupts();
-
- /* Clear type lookup cache */
- PyType_ClearCache();
-
- /* Collect garbage. This may call finalizers; it's nice to call these
- * before all modules are destroyed.
- * XXX If a __del__ or weakref callback is triggered here, and tries to
- * XXX import a module, bad things can happen, because Python no
- * XXX longer believes it's initialized.
- * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
- * XXX is easy to provoke that way. I've also seen, e.g.,
- * XXX Exception exceptions.ImportError: 'No module named sha'
- * XXX in <function callback at 0x008F5718> ignored
- * XXX but I'm unclear on exactly how that one happens. In any case,
- * XXX I haven't seen a real-life report of either of these.
- */
- PyGC_Collect();
+ PyInterpreterState *interp;
+ PyThreadState *tstate;
+
+ if (!initialized)
+ return;
+
+ wait_for_thread_shutdown();
+
+ /* The interpreter is still entirely intact at this point, and the
+ * exit funcs may be relying on that. In particular, if some thread
+ * or exit func is still waiting to do an import, the import machinery
+ * expects Py_IsInitialized() to return true. So don't say the
+ * interpreter is uninitialized until after the exit funcs have run.
+ * Note that Threading.py uses an exit func to do a join on all the
+ * threads created thru it, so this also protects pending imports in
+ * the threads created via Threading.
+ */
+ call_sys_exitfunc();
+ initialized = 0;
+
+ /* Get current thread state and interpreter pointer */
+ tstate = PyThreadState_GET();
+ interp = tstate->interp;
+
+ /* Disable signal handling */
+ PyOS_FiniInterrupts();
+
+ /* Clear type lookup cache */
+ PyType_ClearCache();
+
+ /* Collect garbage. This may call finalizers; it's nice to call these
+ * before all modules are destroyed.
+ * XXX If a __del__ or weakref callback is triggered here, and tries to
+ * XXX import a module, bad things can happen, because Python no
+ * XXX longer believes it's initialized.
+ * XXX Fatal Python error: Interpreter not initialized (version mismatch?)
+ * XXX is easy to provoke that way. I've also seen, e.g.,
+ * XXX Exception exceptions.ImportError: 'No module named sha'
+ * XXX in <function callback at 0x008F5718> ignored
+ * XXX but I'm unclear on exactly how that one happens. In any case,
+ * XXX I haven't seen a real-life report of either of these.
+ */
+ PyGC_Collect();
#ifdef COUNT_ALLOCS
- /* With COUNT_ALLOCS, it helps to run GC multiple times:
- each collection might release some types from the type
- list, so they become garbage. */
- while (PyGC_Collect() > 0)
- /* nothing */;
+ /* With COUNT_ALLOCS, it helps to run GC multiple times:
+ each collection might release some types from the type
+ list, so they become garbage. */
+ while (PyGC_Collect() > 0)
+ /* nothing */;
#endif
- /* Destroy all modules */
- PyImport_Cleanup();
-
- /* Collect final garbage. This disposes of cycles created by
- * new-style class definitions, for example.
- * XXX This is disabled because it caused too many problems. If
- * XXX a __del__ or weakref callback triggers here, Python code has
- * XXX a hard time running, because even the sys module has been
- * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
- * XXX One symptom is a sequence of information-free messages
- * XXX coming from threads (if a __del__ or callback is invoked,
- * XXX other threads can execute too, and any exception they encounter
- * XXX triggers a comedy of errors as subsystem after subsystem
- * XXX fails to find what it *expects* to find in sys to help report
- * XXX the exception and consequent unexpected failures). I've also
- * XXX seen segfaults then, after adding print statements to the
- * XXX Python code getting called.
- */
+ /* Destroy all modules */
+ PyImport_Cleanup();
+
+ /* Collect final garbage. This disposes of cycles created by
+ * new-style class definitions, for example.
+ * XXX This is disabled because it caused too many problems. If
+ * XXX a __del__ or weakref callback triggers here, Python code has
+ * XXX a hard time running, because even the sys module has been
+ * XXX cleared out (sys.stdout is gone, sys.excepthook is gone, etc).
+ * XXX One symptom is a sequence of information-free messages
+ * XXX coming from threads (if a __del__ or callback is invoked,
+ * XXX other threads can execute too, and any exception they encounter
+ * XXX triggers a comedy of errors as subsystem after subsystem
+ * XXX fails to find what it *expects* to find in sys to help report
+ * XXX the exception and consequent unexpected failures). I've also
+ * XXX seen segfaults then, after adding print statements to the
+ * XXX Python code getting called.
+ */
#if 0
- PyGC_Collect();
+ PyGC_Collect();
#endif
- /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
- _PyImport_Fini();
+ /* Destroy the database used by _PyImport_{Fixup,Find}Extension */
+ _PyImport_Fini();
- /* Debugging stuff */
+ /* Debugging stuff */
#ifdef COUNT_ALLOCS
- dump_counts(stdout);
+ dump_counts(stdout);
#endif
- PRINT_TOTAL_REFS();
+ PRINT_TOTAL_REFS();
#ifdef Py_TRACE_REFS
- /* Display all objects still alive -- this can invoke arbitrary
- * __repr__ overrides, so requires a mostly-intact interpreter.
- * Alas, a lot of stuff may still be alive now that will be cleaned
- * up later.
- */
- if (Py_GETENV("PYTHONDUMPREFS"))
- _Py_PrintReferences(stderr);
+ /* Display all objects still alive -- this can invoke arbitrary
+ * __repr__ overrides, so requires a mostly-intact interpreter.
+ * Alas, a lot of stuff may still be alive now that will be cleaned
+ * up later.
+ */
+ if (Py_GETENV("PYTHONDUMPREFS"))
+ _Py_PrintReferences(stderr);
#endif /* Py_TRACE_REFS */
- /* Clear interpreter state */
- PyInterpreterState_Clear(interp);
+ /* Clear interpreter state */
+ PyInterpreterState_Clear(interp);
- /* Now we decref the exception classes. After this point nothing
- can raise an exception. That's okay, because each Fini() method
- below has been checked to make sure no exceptions are ever
- raised.
- */
+ /* Now we decref the exception classes. After this point nothing
+ can raise an exception. That's okay, because each Fini() method
+ below has been checked to make sure no exceptions are ever
+ raised.
+ */
- _PyExc_Fini();
+ _PyExc_Fini();
- /* Cleanup auto-thread-state */
+ /* Cleanup auto-thread-state */
#ifdef WITH_THREAD
- _PyGILState_Fini();
+ _PyGILState_Fini();
#endif /* WITH_THREAD */
- /* Delete current thread */
- PyThreadState_Swap(NULL);
- PyInterpreterState_Delete(interp);
-
- /* Sundry finalizers */
- PyMethod_Fini();
- PyFrame_Fini();
- PyCFunction_Fini();
- PyTuple_Fini();
- PyList_Fini();
- PySet_Fini();
- PyString_Fini();
- PyByteArray_Fini();
- PyInt_Fini();
- PyFloat_Fini();
- PyDict_Fini();
+ /* Delete current thread */
+ PyThreadState_Swap(NULL);
+ PyInterpreterState_Delete(interp);
+
+ /* Sundry finalizers */
+ PyMethod_Fini();
+ PyFrame_Fini();
+ PyCFunction_Fini();
+ PyTuple_Fini();
+ PyList_Fini();
+ PySet_Fini();
+ PyString_Fini();
+ PyByteArray_Fini();
+ PyInt_Fini();
+ PyFloat_Fini();
+ PyDict_Fini();
#ifdef Py_USING_UNICODE
- /* Cleanup Unicode implementation */
- _PyUnicode_Fini();
+ /* Cleanup Unicode implementation */
+ _PyUnicode_Fini();
#endif
- /* XXX Still allocated:
- - various static ad-hoc pointers to interned strings
- - int and float free list blocks
- - whatever various modules and libraries allocate
- */
+ /* XXX Still allocated:
+ - various static ad-hoc pointers to interned strings
+ - int and float free list blocks
+ - whatever various modules and libraries allocate
+ */
- PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
+ PyGrammar_RemoveAccelerators(&_PyParser_Grammar);
#ifdef Py_TRACE_REFS
- /* Display addresses (& refcnts) of all objects still alive.
- * An address can be used to find the repr of the object, printed
- * above by _Py_PrintReferences.
- */
- if (Py_GETENV("PYTHONDUMPREFS"))
- _Py_PrintReferenceAddresses(stderr);
+ /* Display addresses (& refcnts) of all objects still alive.
+ * An address can be used to find the repr of the object, printed
+ * above by _Py_PrintReferences.
+ */
+ if (Py_GETENV("PYTHONDUMPREFS"))
+ _Py_PrintReferenceAddresses(stderr);
#endif /* Py_TRACE_REFS */
#ifdef PYMALLOC_DEBUG
- if (Py_GETENV("PYTHONMALLOCSTATS"))
- _PyObject_DebugMallocStats();
+ if (Py_GETENV("PYTHONMALLOCSTATS"))
+ _PyObject_DebugMallocStats();
#endif
- call_ll_exitfuncs();
+ call_ll_exitfuncs();
}
/* Create and initialize a new interpreter and thread, and return the
@@ -563,65 +563,65 @@ Py_Finalize(void)
PyThreadState *
Py_NewInterpreter(void)
{
- PyInterpreterState *interp;
- PyThreadState *tstate, *save_tstate;
- PyObject *bimod, *sysmod;
-
- if (!initialized)
- Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
-
- interp = PyInterpreterState_New();
- if (interp == NULL)
- return NULL;
-
- tstate = PyThreadState_New(interp);
- if (tstate == NULL) {
- PyInterpreterState_Delete(interp);
- return NULL;
- }
-
- save_tstate = PyThreadState_Swap(tstate);
-
- /* XXX The following is lax in error checking */
-
- interp->modules = PyDict_New();
- interp->modules_reloading = PyDict_New();
-
- bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
- if (bimod != NULL) {
- interp->builtins = PyModule_GetDict(bimod);
- if (interp->builtins == NULL)
- goto handle_error;
- Py_INCREF(interp->builtins);
- }
- sysmod = _PyImport_FindExtension("sys", "sys");
- if (bimod != NULL && sysmod != NULL) {
- interp->sysdict = PyModule_GetDict(sysmod);
- if (interp->sysdict == NULL)
- goto handle_error;
- Py_INCREF(interp->sysdict);
- PySys_SetPath(Py_GetPath());
- PyDict_SetItemString(interp->sysdict, "modules",
- interp->modules);
- _PyImportHooks_Init();
- initmain();
- if (!Py_NoSiteFlag)
- initsite();
- }
-
- if (!PyErr_Occurred())
- return tstate;
+ PyInterpreterState *interp;
+ PyThreadState *tstate, *save_tstate;
+ PyObject *bimod, *sysmod;
+
+ if (!initialized)
+ Py_FatalError("Py_NewInterpreter: call Py_Initialize first");
+
+ interp = PyInterpreterState_New();
+ if (interp == NULL)
+ return NULL;
+
+ tstate = PyThreadState_New(interp);
+ if (tstate == NULL) {
+ PyInterpreterState_Delete(interp);
+ return NULL;
+ }
+
+ save_tstate = PyThreadState_Swap(tstate);
+
+ /* XXX The following is lax in error checking */
+
+ interp->modules = PyDict_New();
+ interp->modules_reloading = PyDict_New();
+
+ bimod = _PyImport_FindExtension("__builtin__", "__builtin__");
+ if (bimod != NULL) {
+ interp->builtins = PyModule_GetDict(bimod);
+ if (interp->builtins == NULL)
+ goto handle_error;
+ Py_INCREF(interp->builtins);
+ }
+ sysmod = _PyImport_FindExtension("sys", "sys");
+ if (bimod != NULL && sysmod != NULL) {
+ interp->sysdict = PyModule_GetDict(sysmod);
+ if (interp->sysdict == NULL)
+ goto handle_error;
+ Py_INCREF(interp->sysdict);
+ PySys_SetPath(Py_GetPath());
+ PyDict_SetItemString(interp->sysdict, "modules",
+ interp->modules);
+ _PyImportHooks_Init();
+ initmain();
+ if (!Py_NoSiteFlag)
+ initsite();
+ }
+
+ if (!PyErr_Occurred())
+ return tstate;
handle_error:
- /* Oops, it didn't work. Undo it all. */
+ /* Oops, it didn't work. Undo it all. */
- PyErr_Print();
- PyThreadState_Clear(tstate);
- PyThreadState_Swap(save_tstate);
- PyThreadState_Delete(tstate);
- PyInterpreterState_Delete(interp);
+ PyErr_Print();
+ PyThreadState_Clear(tstate);
+ PyThreadState_Swap(save_tstate);
+ PyThreadState_Delete(tstate);
+ PyInterpreterState_Delete(interp);
- return NULL;
+ return NULL;
}
/* Delete an interpreter and its last thread. This requires that the
@@ -639,19 +639,19 @@ handle_error:
void
Py_EndInterpreter(PyThreadState *tstate)
{
- PyInterpreterState *interp = tstate->interp;
+ PyInterpreterState *interp = tstate->interp;
- if (tstate != PyThreadState_GET())
- Py_FatalError("Py_EndInterpreter: thread is not current");
- if (tstate->frame != NULL)
- Py_FatalError("Py_EndInterpreter: thread still has a frame");
- if (tstate != interp->tstate_head || tstate->next != NULL)
- Py_FatalError("Py_EndInterpreter: not the last thread");
+ if (tstate != PyThreadState_GET())
+ Py_FatalError("Py_EndInterpreter: thread is not current");
+ if (tstate->frame != NULL)
+ Py_FatalError("Py_EndInterpreter: thread still has a frame");
+ if (tstate != interp->tstate_head || tstate->next != NULL)
+ Py_FatalError("Py_EndInterpreter: not the last thread");
- PyImport_Cleanup();
- PyInterpreterState_Clear(interp);
- PyThreadState_Swap(NULL);
- PyInterpreterState_Delete(interp);
+ PyImport_Cleanup();
+ PyInterpreterState_Clear(interp);
+ PyThreadState_Swap(NULL);
+ PyInterpreterState_Delete(interp);
}
static char *progname = "python";
@@ -659,14 +659,14 @@ static char *progname = "python";
void
Py_SetProgramName(char *pn)
{
- if (pn && *pn)
- progname = pn;
+ if (pn && *pn)
+ progname = pn;
}
char *
Py_GetProgramName(void)
{
- return progname;
+ return progname;
}
static char *default_home = NULL;
@@ -674,16 +674,16 @@ static char *default_home = NULL;
void
Py_SetPythonHome(char *home)
{
- default_home = home;
+ default_home = home;
}
char *
Py_GetPythonHome(void)
{
- char *home = default_home;
- if (home == NULL && !Py_IgnoreEnvironmentFlag)
- home = Py_GETENV("PYTHONHOME");
- return home;
+ char *home = default_home;
+ if (home == NULL && !Py_IgnoreEnvironmentFlag)
+ home = Py_GETENV("PYTHONHOME");
+ return home;
}
/* Create __main__ module */
@@ -691,18 +691,18 @@ Py_GetPythonHome(void)
static void
initmain(void)
{
- PyObject *m, *d;
- m = PyImport_AddModule("__main__");
- if (m == NULL)
- Py_FatalError("can't create __main__ module");
- d = PyModule_GetDict(m);
- if (PyDict_GetItemString(d, "__builtins__") == NULL) {
- PyObject *bimod = PyImport_ImportModule("__builtin__");
- if (bimod == NULL ||
- PyDict_SetItemString(d, "__builtins__", bimod) != 0)
- Py_FatalError("can't add __builtins__ to __main__");
- Py_XDECREF(bimod);
- }
+ PyObject *m, *d;
+ m = PyImport_AddModule("__main__");
+ if (m == NULL)
+ Py_FatalError("can't create __main__ module");
+ d = PyModule_GetDict(m);
+ if (PyDict_GetItemString(d, "__builtins__") == NULL) {
+ PyObject *bimod = PyImport_ImportModule("__builtin__");
+ if (bimod == NULL ||
+ PyDict_SetItemString(d, "__builtins__", bimod) != 0)
+ Py_FatalError("can't add __builtins__ to __main__");
+ Py_XDECREF(bimod);
+ }
}
/* Import the site module (not into __main__ though) */
@@ -710,148 +710,148 @@ initmain(void)
static void
initsite(void)
{
- PyObject *m;
- m = PyImport_ImportModule("site");
- if (m == NULL) {
- PyErr_Print();
- Py_Finalize();
- exit(1);
- }
- else {
- Py_DECREF(m);
- }
+ PyObject *m;
+ m = PyImport_ImportModule("site");
+ if (m == NULL) {
+ PyErr_Print();
+ Py_Finalize();
+ exit(1);
+ }
+ else {
+ Py_DECREF(m);
+ }
}
/* Parse input from a file and execute it */
int
PyRun_AnyFileExFlags(FILE *fp, const char *filename, int closeit,
- PyCompilerFlags *flags)
+ PyCompilerFlags *flags)
{
- if (filename == NULL)
- filename = "???";
- if (Py_FdIsInteractive(fp, filename)) {
- int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
- if (closeit)
- fclose(fp);
- return err;
- }
- else
- return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
+ if (filename == NULL)
+ filename = "???";
+ if (Py_FdIsInteractive(fp, filename)) {
+ int err = PyRun_InteractiveLoopFlags(fp, filename, flags);
+ if (closeit)
+ fclose(fp);
+ return err;
+ }
+ else
+ return PyRun_SimpleFileExFlags(fp, filename, closeit, flags);
}
int
PyRun_InteractiveLoopFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
{
- PyObject *v;
- int ret;
- PyCompilerFlags local_flags;
-
- if (flags == NULL) {
- flags = &local_flags;
- local_flags.cf_flags = 0;
- }
- v = PySys_GetObject("ps1");
- if (v == NULL) {
- PySys_SetObject("ps1", v = PyString_FromString(">>> "));
- Py_XDECREF(v);
- }
- v = PySys_GetObject("ps2");
- if (v == NULL) {
- PySys_SetObject("ps2", v = PyString_FromString("... "));
- Py_XDECREF(v);
- }
- for (;;) {
- ret = PyRun_InteractiveOneFlags(fp, filename, flags);
- PRINT_TOTAL_REFS();
- if (ret == E_EOF)
- return 0;
- /*
- if (ret == E_NOMEM)
- return -1;
- */
- }
+ PyObject *v;
+ int ret;
+ PyCompilerFlags local_flags;
+
+ if (flags == NULL) {
+ flags = &local_flags;
+ local_flags.cf_flags = 0;
+ }
+ v = PySys_GetObject("ps1");
+ if (v == NULL) {
+ PySys_SetObject("ps1", v = PyString_FromString(">>> "));
+ Py_XDECREF(v);
+ }
+ v = PySys_GetObject("ps2");
+ if (v == NULL) {
+ PySys_SetObject("ps2", v = PyString_FromString("... "));
+ Py_XDECREF(v);
+ }
+ for (;;) {
+ ret = PyRun_InteractiveOneFlags(fp, filename, flags);
+ PRINT_TOTAL_REFS();
+ if (ret == E_EOF)
+ return 0;
+ /*
+ if (ret == E_NOMEM)
+ return -1;
+ */
+ }
}
#if 0
/* compute parser flags based on compiler flags */
#define PARSER_FLAGS(flags) \
- ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
- PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
+ ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
+ PyPARSE_DONT_IMPLY_DEDENT : 0)) : 0)
#endif
#if 1
/* Keep an example of flags with future keyword support. */
#define PARSER_FLAGS(flags) \
- ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
- PyPARSE_DONT_IMPLY_DEDENT : 0) \
- | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
- PyPARSE_PRINT_IS_FUNCTION : 0) \
- | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
- PyPARSE_UNICODE_LITERALS : 0) \
- ) : 0)
+ ((flags) ? ((((flags)->cf_flags & PyCF_DONT_IMPLY_DEDENT) ? \
+ PyPARSE_DONT_IMPLY_DEDENT : 0) \
+ | (((flags)->cf_flags & CO_FUTURE_PRINT_FUNCTION) ? \
+ PyPARSE_PRINT_IS_FUNCTION : 0) \
+ | (((flags)->cf_flags & CO_FUTURE_UNICODE_LITERALS) ? \
+ PyPARSE_UNICODE_LITERALS : 0) \
+ ) : 0)
#endif
int
PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags)
{
- PyObject *m, *d, *v, *w;
- mod_ty mod;
- PyArena *arena;
- char *ps1 = "", *ps2 = "";
- int errcode = 0;
-
- v = PySys_GetObject("ps1");
- if (v != NULL) {
- v = PyObject_Str(v);
- if (v == NULL)
- PyErr_Clear();
- else if (PyString_Check(v))
- ps1 = PyString_AsString(v);
- }
- w = PySys_GetObject("ps2");
- if (w != NULL) {
- w = PyObject_Str(w);
- if (w == NULL)
- PyErr_Clear();
- else if (PyString_Check(w))
- ps2 = PyString_AsString(w);
- }
- arena = PyArena_New();
- if (arena == NULL) {
- Py_XDECREF(v);
- Py_XDECREF(w);
- return -1;
- }
- mod = PyParser_ASTFromFile(fp, filename,
- Py_single_input, ps1, ps2,
- flags, &errcode, arena);
- Py_XDECREF(v);
- Py_XDECREF(w);
- if (mod == NULL) {
- PyArena_Free(arena);
- if (errcode == E_EOF) {
- PyErr_Clear();
- return E_EOF;
- }
- PyErr_Print();
- return -1;
- }
- m = PyImport_AddModule("__main__");
- if (m == NULL) {
- PyArena_Free(arena);
- return -1;
- }
- d = PyModule_GetDict(m);
- v = run_mod(mod, filename, d, d, flags, arena);
- PyArena_Free(arena);
- if (v == NULL) {
- PyErr_Print();
- return -1;
- }
- Py_DECREF(v);
- if (Py_FlushLine())
- PyErr_Clear();
- return 0;
+ PyObject *m, *d, *v, *w;
+ mod_ty mod;
+ PyArena *arena;
+ char *ps1 = "", *ps2 = "";
+ int errcode = 0;
+
+ v = PySys_GetObject("ps1");
+ if (v != NULL) {
+ v = PyObject_Str(v);
+ if (v == NULL)
+ PyErr_Clear();
+ else if (PyString_Check(v))
+ ps1 = PyString_AsString(v);
+ }
+ w = PySys_GetObject("ps2");
+ if (w != NULL) {
+ w = PyObject_Str(w);
+ if (w == NULL)
+ PyErr_Clear();
+ else if (PyString_Check(w))
+ ps2 = PyString_AsString(w);
+ }
+ arena = PyArena_New();
+ if (arena == NULL) {
+ Py_XDECREF(v);
+ Py_XDECREF(w);
+ return -1;
+ }
+ mod = PyParser_ASTFromFile(fp, filename,
+ Py_single_input, ps1, ps2,
+ flags, &errcode, arena);
+ Py_XDECREF(v);
+ Py_XDECREF(w);
+ if (mod == NULL) {
+ PyArena_Free(arena);
+ if (errcode == E_EOF) {
+ PyErr_Clear();
+ return E_EOF;
+ }
+ PyErr_Print();
+ return -1;
+ }
+ m = PyImport_AddModule("__main__");
+ if (m == NULL) {
+ PyArena_Free(arena);
+ return -1;
+ }
+ d = PyModule_GetDict(m);
+ v = run_mod(mod, filename, d, d, flags, arena);
+ PyArena_Free(arena);
+ if (v == NULL) {
+ PyErr_Print();
+ return -1;
+ }
+ Py_DECREF(v);
+ if (Py_FlushLine())
+ PyErr_Clear();
+ return 0;
}
/* Check whether a file maybe a pyc file: Look at the extension,
@@ -860,624 +860,624 @@ PyRun_InteractiveOneFlags(FILE *fp, const char *filename, PyCompilerFlags *flags
static int
maybe_pyc_file(FILE *fp, const char* filename, const char* ext, int closeit)
{
- if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
- return 1;
-
- /* Only look into the file if we are allowed to close it, since
- it then should also be seekable. */
- if (closeit) {
- /* Read only two bytes of the magic. If the file was opened in
- text mode, the bytes 3 and 4 of the magic (\r\n) might not
- be read as they are on disk. */
- unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
- unsigned char buf[2];
- /* Mess: In case of -x, the stream is NOT at its start now,
- and ungetc() was used to push back the first newline,
- which makes the current stream position formally undefined,
- and a x-platform nightmare.
- Unfortunately, we have no direct way to know whether -x
- was specified. So we use a terrible hack: if the current
- stream position is not 0, we assume -x was specified, and
- give up. Bug 132850 on SourceForge spells out the
- hopelessness of trying anything else (fseek and ftell
- don't work predictably x-platform for text-mode files).
- */
- int ispyc = 0;
- if (ftell(fp) == 0) {
- if (fread(buf, 1, 2, fp) == 2 &&
- ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
- ispyc = 1;
- rewind(fp);
- }
- return ispyc;
- }
- return 0;
+ if (strcmp(ext, ".pyc") == 0 || strcmp(ext, ".pyo") == 0)
+ return 1;
+
+ /* Only look into the file if we are allowed to close it, since
+ it then should also be seekable. */
+ if (closeit) {
+ /* Read only two bytes of the magic. If the file was opened in
+ text mode, the bytes 3 and 4 of the magic (\r\n) might not
+ be read as they are on disk. */
+ unsigned int halfmagic = PyImport_GetMagicNumber() & 0xFFFF;
+ unsigned char buf[2];
+ /* Mess: In case of -x, the stream is NOT at its start now,
+ and ungetc() was used to push back the first newline,
+ which makes the current stream position formally undefined,
+ and a x-platform nightmare.
+ Unfortunately, we have no direct way to know whether -x
+ was specified. So we use a terrible hack: if the current
+ stream position is not 0, we assume -x was specified, and
+ give up. Bug 132850 on SourceForge spells out the
+ hopelessness of trying anything else (fseek and ftell
+ don't work predictably x-platform for text-mode files).
+ */
+ int ispyc = 0;
+ if (ftell(fp) == 0) {
+ if (fread(buf, 1, 2, fp) == 2 &&
+ ((unsigned int)buf[1]<<8 | buf[0]) == halfmagic)
+ ispyc = 1;
+ rewind(fp);
+ }
+ return ispyc;
+ }
+ return 0;
}
int
PyRun_SimpleFileExFlags(FILE *fp, const char *filename, int closeit,
- PyCompilerFlags *flags)
-{
- PyObject *m, *d, *v;
- const char *ext;
- int set_file_name = 0, ret, len;
-
- m = PyImport_AddModule("__main__");
- if (m == NULL)
- return -1;
- d = PyModule_GetDict(m);
- if (PyDict_GetItemString(d, "__file__") == NULL) {
- PyObject *f = PyString_FromString(filename);
- if (f == NULL)
- return -1;
- if (PyDict_SetItemString(d, "__file__", f) < 0) {
- Py_DECREF(f);
- return -1;
- }
- set_file_name = 1;
- Py_DECREF(f);
- }
- len = strlen(filename);
- ext = filename + len - (len > 4 ? 4 : 0);
- if (maybe_pyc_file(fp, filename, ext, closeit)) {
- /* Try to run a pyc file. First, re-open in binary */
- if (closeit)
- fclose(fp);
- if ((fp = fopen(filename, "rb")) == NULL) {
- fprintf(stderr, "python: Can't reopen .pyc file\n");
- ret = -1;
- goto done;
- }
- /* Turn on optimization if a .pyo file is given */
- if (strcmp(ext, ".pyo") == 0)
- Py_OptimizeFlag = 1;
- v = run_pyc_file(fp, filename, d, d, flags);
- } else {
- v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
- closeit, flags);
- }
- if (v == NULL) {
- PyErr_Print();
- ret = -1;
- goto done;
- }
- Py_DECREF(v);
- if (Py_FlushLine())
- PyErr_Clear();
- ret = 0;
+ PyCompilerFlags *flags)
+{
+ PyObject *m, *d, *v;
+ const char *ext;
+ int set_file_name = 0, ret, len;
+
+ m = PyImport_AddModule("__main__");
+ if (m == NULL)
+ return -1;
+ d = PyModule_GetDict(m);
+ if (PyDict_GetItemString(d, "__file__") == NULL) {
+ PyObject *f = PyString_FromString(filename);
+ if (f == NULL)
+ return -1;
+ if (PyDict_SetItemString(d, "__file__", f) < 0) {
+ Py_DECREF(f);
+ return -1;
+ }
+ set_file_name = 1;
+ Py_DECREF(f);
+ }
+ len = strlen(filename);
+ ext = filename + len - (len > 4 ? 4 : 0);
+ if (maybe_pyc_file(fp, filename, ext, closeit)) {
+ /* Try to run a pyc file. First, re-open in binary */
+ if (closeit)
+ fclose(fp);
+ if ((fp = fopen(filename, "rb")) == NULL) {
+ fprintf(stderr, "python: Can't reopen .pyc file\n");
+ ret = -1;
+ goto done;
+ }
+ /* Turn on optimization if a .pyo file is given */
+ if (strcmp(ext, ".pyo") == 0)
+ Py_OptimizeFlag = 1;
+ v = run_pyc_file(fp, filename, d, d, flags);
+ } else {
+ v = PyRun_FileExFlags(fp, filename, Py_file_input, d, d,
+ closeit, flags);
+ }
+ if (v == NULL) {
+ PyErr_Print();
+ ret = -1;
+ goto done;
+ }
+ Py_DECREF(v);
+ if (Py_FlushLine())
+ PyErr_Clear();
+ ret = 0;
done:
- if (set_file_name && PyDict_DelItemString(d, "__file__"))
- PyErr_Clear();
- return ret;
+ if (set_file_name && PyDict_DelItemString(d, "__file__"))
+ PyErr_Clear();
+ return ret;
}
int
PyRun_SimpleStringFlags(const char *command, PyCompilerFlags *flags)
{
- PyObject *m, *d, *v;
- m = PyImport_AddModule("__main__");
- if (m == NULL)
- return -1;
- d = PyModule_GetDict(m);
- v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
- if (v == NULL) {
- PyErr_Print();
- return -1;
- }
- Py_DECREF(v);
- if (Py_FlushLine())
- PyErr_Clear();
- return 0;
+ PyObject *m, *d, *v;
+ m = PyImport_AddModule("__main__");
+ if (m == NULL)
+ return -1;
+ d = PyModule_GetDict(m);
+ v = PyRun_StringFlags(command, Py_file_input, d, d, flags);
+ if (v == NULL) {
+ PyErr_Print();
+ return -1;
+ }
+ Py_DECREF(v);
+ if (Py_FlushLine())
+ PyErr_Clear();
+ return 0;
}
static int
parse_syntax_error(PyObject *err, PyObject **message, const char **filename,
- int *lineno, int *offset, const char **text)
-{
- long hold;
- PyObject *v;
-
- /* old style errors */
- if (PyTuple_Check(err))
- return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
- lineno, offset, text);
-
- /* new style errors. `err' is an instance */
-
- if (! (v = PyObject_GetAttrString(err, "msg")))
- goto finally;
- *message = v;
-
- if (!(v = PyObject_GetAttrString(err, "filename")))
- goto finally;
- if (v == Py_None)
- *filename = NULL;
- else if (! (*filename = PyString_AsString(v)))
- goto finally;
-
- Py_DECREF(v);
- if (!(v = PyObject_GetAttrString(err, "lineno")))
- goto finally;
- hold = PyInt_AsLong(v);
- Py_DECREF(v);
- v = NULL;
- if (hold < 0 && PyErr_Occurred())
- goto finally;
- *lineno = (int)hold;
-
- if (!(v = PyObject_GetAttrString(err, "offset")))
- goto finally;
- if (v == Py_None) {
- *offset = -1;
- Py_DECREF(v);
- v = NULL;
- } else {
- hold = PyInt_AsLong(v);
- Py_DECREF(v);
- v = NULL;
- if (hold < 0 && PyErr_Occurred())
- goto finally;
- *offset = (int)hold;
- }
-
- if (!(v = PyObject_GetAttrString(err, "text")))
- goto finally;
- if (v == Py_None)
- *text = NULL;
- else if (! (*text = PyString_AsString(v)))
- goto finally;
- Py_DECREF(v);
- return 1;
+ int *lineno, int *offset, const char **text)
+{
+ long hold;
+ PyObject *v;
+
+ /* old style errors */
+ if (PyTuple_Check(err))
+ return PyArg_ParseTuple(err, "O(ziiz)", message, filename,
+ lineno, offset, text);
+
+ /* new style errors. `err' is an instance */
+
+ if (! (v = PyObject_GetAttrString(err, "msg")))
+ goto finally;
+ *message = v;
+
+ if (!(v = PyObject_GetAttrString(err, "filename")))
+ goto finally;
+ if (v == Py_None)
+ *filename = NULL;
+ else if (! (*filename = PyString_AsString(v)))
+ goto finally;
+
+ Py_DECREF(v);
+ if (!(v = PyObject_GetAttrString(err, "lineno")))
+ goto finally;
+ hold = PyInt_AsLong(v);
+ Py_DECREF(v);
+ v = NULL;
+ if (hold < 0 && PyErr_Occurred())
+ goto finally;
+ *lineno = (int)hold;
+
+ if (!(v = PyObject_GetAttrString(err, "offset")))
+ goto finally;
+ if (v == Py_None) {
+ *offset = -1;
+ Py_DECREF(v);
+ v = NULL;
+ } else {
+ hold = PyInt_AsLong(v);
+ Py_DECREF(v);
+ v = NULL;
+ if (hold < 0 && PyErr_Occurred())
+ goto finally;
+ *offset = (int)hold;
+ }
+
+ if (!(v = PyObject_GetAttrString(err, "text")))
+ goto finally;
+ if (v == Py_None)
+ *text = NULL;
+ else if (! (*text = PyString_AsString(v)))
+ goto finally;
+ Py_DECREF(v);
+ return 1;
finally:
- Py_XDECREF(v);
- return 0;
+ Py_XDECREF(v);
+ return 0;
}
void
PyErr_Print(void)
{
- PyErr_PrintEx(1);
+ PyErr_PrintEx(1);
}
static void
print_error_text(PyObject *f, int offset, const char *text)
{
- char *nl;
- if (offset >= 0) {
- if (offset > 0 && offset == (int)strlen(text))
- offset--;
- for (;;) {
- nl = strchr(text, '\n');
- if (nl == NULL || nl-text >= offset)
- break;
- offset -= (int)(nl+1-text);
- text = nl+1;
- }
- while (*text == ' ' || *text == '\t') {
- text++;
- offset--;
- }
- }
- PyFile_WriteString(" ", f);
- PyFile_WriteString(text, f);
- if (*text == '\0' || text[strlen(text)-1] != '\n')
- PyFile_WriteString("\n", f);
- if (offset == -1)
- return;
- PyFile_WriteString(" ", f);
- offset--;
- while (offset > 0) {
- PyFile_WriteString(" ", f);
- offset--;
- }
- PyFile_WriteString("^\n", f);
+ char *nl;
+ if (offset >= 0) {
+ if (offset > 0 && offset == (int)strlen(text))
+ offset--;
+ for (;;) {
+ nl = strchr(text, '\n');
+ if (nl == NULL || nl-text >= offset)
+ break;
+ offset -= (int)(nl+1-text);
+ text = nl+1;
+ }
+ while (*text == ' ' || *text == '\t') {
+ text++;
+ offset--;
+ }
+ }
+ PyFile_WriteString(" ", f);
+ PyFile_WriteString(text, f);
+ if (*text == '\0' || text[strlen(text)-1] != '\n')
+ PyFile_WriteString("\n", f);
+ if (offset == -1)
+ return;
+ PyFile_WriteString(" ", f);
+ offset--;
+ while (offset > 0) {
+ PyFile_WriteString(" ", f);
+ offset--;
+ }
+ PyFile_WriteString("^\n", f);
}
static void
handle_system_exit(void)
{
- PyObject *exception, *value, *tb;
- int exitcode = 0;
-
- if (Py_InspectFlag)
- /* Don't exit if -i flag was given. This flag is set to 0
- * when entering interactive mode for inspecting. */
- return;
-
- PyErr_Fetch(&exception, &value, &tb);
- if (Py_FlushLine())
- PyErr_Clear();
- fflush(stdout);
- if (value == NULL || value == Py_None)
- goto done;
- if (PyExceptionInstance_Check(value)) {
- /* The error code should be in the `code' attribute. */
- PyObject *code = PyObject_GetAttrString(value, "code");
- if (code) {
- Py_DECREF(value);
- value = code;
- if (value == Py_None)
- goto done;
- }
- /* If we failed to dig out the 'code' attribute,
- just let the else clause below print the error. */
- }
- if (PyInt_Check(value))
- exitcode = (int)PyInt_AsLong(value);
- else {
- PyObject_Print(value, stderr, Py_PRINT_RAW);
- PySys_WriteStderr("\n");
- exitcode = 1;
- }
+ PyObject *exception, *value, *tb;
+ int exitcode = 0;
+
+ if (Py_InspectFlag)
+ /* Don't exit if -i flag was given. This flag is set to 0
+ * when entering interactive mode for inspecting. */
+ return;
+
+ PyErr_Fetch(&exception, &value, &tb);
+ if (Py_FlushLine())
+ PyErr_Clear();
+ fflush(stdout);
+ if (value == NULL || value == Py_None)
+ goto done;
+ if (PyExceptionInstance_Check(value)) {
+ /* The error code should be in the `code' attribute. */
+ PyObject *code = PyObject_GetAttrString(value, "code");
+ if (code) {
+ Py_DECREF(value);
+ value = code;
+ if (value == Py_None)
+ goto done;
+ }
+ /* If we failed to dig out the 'code' attribute,
+ just let the else clause below print the error. */
+ }
+ if (PyInt_Check(value))
+ exitcode = (int)PyInt_AsLong(value);
+ else {
+ PyObject_Print(value, stderr, Py_PRINT_RAW);
+ PySys_WriteStderr("\n");
+ exitcode = 1;
+ }
done:
- /* Restore and clear the exception info, in order to properly decref
- * the exception, value, and traceback. If we just exit instead,
- * these leak, which confuses PYTHONDUMPREFS output, and may prevent
- * some finalizers from running.
- */
- PyErr_Restore(exception, value, tb);
- PyErr_Clear();
- Py_Exit(exitcode);
- /* NOTREACHED */
+ /* Restore and clear the exception info, in order to properly decref
+ * the exception, value, and traceback. If we just exit instead,
+ * these leak, which confuses PYTHONDUMPREFS output, and may prevent
+ * some finalizers from running.
+ */
+ PyErr_Restore(exception, value, tb);
+ PyErr_Clear();
+ Py_Exit(exitcode);
+ /* NOTREACHED */
}
void
PyErr_PrintEx(int set_sys_last_vars)
{
- PyObject *exception, *v, *tb, *hook;
-
- if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
- handle_system_exit();
- }
- PyErr_Fetch(&exception, &v, &tb);
- if (exception == NULL)
- return;
- PyErr_NormalizeException(&exception, &v, &tb);
- if (exception == NULL)
- return;
- /* Now we know v != NULL too */
- if (set_sys_last_vars) {
- PySys_SetObject("last_type", exception);
- PySys_SetObject("last_value", v);
- PySys_SetObject("last_traceback", tb);
- }
- hook = PySys_GetObject("excepthook");
- if (hook) {
- PyObject *args = PyTuple_Pack(3,
- exception, v, tb ? tb : Py_None);
- PyObject *result = PyEval_CallObject(hook, args);
- if (result == NULL) {
- PyObject *exception2, *v2, *tb2;
- if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
- handle_system_exit();
- }
- PyErr_Fetch(&exception2, &v2, &tb2);
- PyErr_NormalizeException(&exception2, &v2, &tb2);
- /* It should not be possible for exception2 or v2
- to be NULL. However PyErr_Display() can't
- tolerate NULLs, so just be safe. */
- if (exception2 == NULL) {
- exception2 = Py_None;
- Py_INCREF(exception2);
- }
- if (v2 == NULL) {
- v2 = Py_None;
- Py_INCREF(v2);
- }
- if (Py_FlushLine())
- PyErr_Clear();
- fflush(stdout);
- PySys_WriteStderr("Error in sys.excepthook:\n");
- PyErr_Display(exception2, v2, tb2);
- PySys_WriteStderr("\nOriginal exception was:\n");
- PyErr_Display(exception, v, tb);
- Py_DECREF(exception2);
- Py_DECREF(v2);
- Py_XDECREF(tb2);
- }
- Py_XDECREF(result);
- Py_XDECREF(args);
- } else {
- PySys_WriteStderr("sys.excepthook is missing\n");
- PyErr_Display(exception, v, tb);
- }
- Py_XDECREF(exception);
- Py_XDECREF(v);
- Py_XDECREF(tb);
+ PyObject *exception, *v, *tb, *hook;
+
+ if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
+ handle_system_exit();
+ }
+ PyErr_Fetch(&exception, &v, &tb);
+ if (exception == NULL)
+ return;
+ PyErr_NormalizeException(&exception, &v, &tb);
+ if (exception == NULL)
+ return;
+ /* Now we know v != NULL too */
+ if (set_sys_last_vars) {
+ PySys_SetObject("last_type", exception);
+ PySys_SetObject("last_value", v);
+ PySys_SetObject("last_traceback", tb);
+ }
+ hook = PySys_GetObject("excepthook");
+ if (hook) {
+ PyObject *args = PyTuple_Pack(3,
+ exception, v, tb ? tb : Py_None);
+ PyObject *result = PyEval_CallObject(hook, args);
+ if (result == NULL) {
+ PyObject *exception2, *v2, *tb2;
+ if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
+ handle_system_exit();
+ }
+ PyErr_Fetch(&exception2, &v2, &tb2);
+ PyErr_NormalizeException(&exception2, &v2, &tb2);
+ /* It should not be possible for exception2 or v2
+ to be NULL. However PyErr_Display() can't
+ tolerate NULLs, so just be safe. */
+ if (exception2 == NULL) {
+ exception2 = Py_None;
+ Py_INCREF(exception2);
+ }
+ if (v2 == NULL) {
+ v2 = Py_None;
+ Py_INCREF(v2);
+ }
+ if (Py_FlushLine())
+ PyErr_Clear();
+ fflush(stdout);
+ PySys_WriteStderr("Error in sys.excepthook:\n");
+ PyErr_Display(exception2, v2, tb2);
+ PySys_WriteStderr("\nOriginal exception was:\n");
+ PyErr_Display(exception, v, tb);
+ Py_DECREF(exception2);
+ Py_DECREF(v2);
+ Py_XDECREF(tb2);
+ }
+ Py_XDECREF(result);
+ Py_XDECREF(args);
+ } else {
+ PySys_WriteStderr("sys.excepthook is missing\n");
+ PyErr_Display(exception, v, tb);
+ }
+ Py_XDECREF(exception);
+ Py_XDECREF(v);
+ Py_XDECREF(tb);
}
void
PyErr_Display(PyObject *exception, PyObject *value, PyObject *tb)
{
- int err = 0;
- PyObject *f = PySys_GetObject("stderr");
- Py_INCREF(value);
- if (f == NULL)
- fprintf(stderr, "lost sys.stderr\n");
- else {
- if (Py_FlushLine())
- PyErr_Clear();
- fflush(stdout);
- if (tb && tb != Py_None)
- err = PyTraceBack_Print(tb, f);
- if (err == 0 &&
- PyObject_HasAttrString(value, "print_file_and_line"))
- {
- PyObject *message;
- const char *filename, *text;
- int lineno, offset;
- if (!parse_syntax_error(value, &message, &filename,
- &lineno, &offset, &text))
- PyErr_Clear();
- else {
- char buf[10];
- PyFile_WriteString(" File \"", f);
- if (filename == NULL)
- PyFile_WriteString("<string>", f);
- else
- PyFile_WriteString(filename, f);
- PyFile_WriteString("\", line ", f);
- PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
- PyFile_WriteString(buf, f);
- PyFile_WriteString("\n", f);
- if (text != NULL)
- print_error_text(f, offset, text);
- Py_DECREF(value);
- value = message;
- /* Can't be bothered to check all those
- PyFile_WriteString() calls */
- if (PyErr_Occurred())
- err = -1;
- }
- }
- if (err) {
- /* Don't do anything else */
- }
- else if (PyExceptionClass_Check(exception)) {
- PyObject* moduleName;
- char* className = PyExceptionClass_Name(exception);
- if (className != NULL) {
- char *dot = strrchr(className, '.');
- if (dot != NULL)
- className = dot+1;
- }
-
- moduleName = PyObject_GetAttrString(exception, "__module__");
- if (moduleName == NULL)
- err = PyFile_WriteString("<unknown>", f);
- else {
- char* modstr = PyString_AsString(moduleName);
- if (modstr && strcmp(modstr, "exceptions"))
- {
- err = PyFile_WriteString(modstr, f);
- err += PyFile_WriteString(".", f);
- }
- Py_DECREF(moduleName);
- }
- if (err == 0) {
- if (className == NULL)
- err = PyFile_WriteString("<unknown>", f);
- else
- err = PyFile_WriteString(className, f);
- }
- }
- else
- err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
- if (err == 0 && (value != Py_None)) {
- PyObject *s = PyObject_Str(value);
- /* only print colon if the str() of the
- object is not the empty string
- */
- if (s == NULL)
- err = -1;
- else if (!PyString_Check(s) ||
- PyString_GET_SIZE(s) != 0)
- err = PyFile_WriteString(": ", f);
- if (err == 0)
- err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
- Py_XDECREF(s);
- }
- /* try to write a newline in any case */
- err += PyFile_WriteString("\n", f);
- }
- Py_DECREF(value);
- /* If an error happened here, don't show it.
- XXX This is wrong, but too many callers rely on this behavior. */
- if (err != 0)
- PyErr_Clear();
+ int err = 0;
+ PyObject *f = PySys_GetObject("stderr");
+ Py_INCREF(value);
+ if (f == NULL)
+ fprintf(stderr, "lost sys.stderr\n");
+ else {
+ if (Py_FlushLine())
+ PyErr_Clear();
+ fflush(stdout);
+ if (tb && tb != Py_None)
+ err = PyTraceBack_Print(tb, f);
+ if (err == 0 &&
+ PyObject_HasAttrString(value, "print_file_and_line"))
+ {
+ PyObject *message;
+ const char *filename, *text;
+ int lineno, offset;
+ if (!parse_syntax_error(value, &message, &filename,
+ &lineno, &offset, &text))
+ PyErr_Clear();
+ else {
+ char buf[10];
+ PyFile_WriteString(" File \"", f);
+ if (filename == NULL)
+ PyFile_WriteString("<string>", f);
+ else
+ PyFile_WriteString(filename, f);
+ PyFile_WriteString("\", line ", f);
+ PyOS_snprintf(buf, sizeof(buf), "%d", lineno);
+ PyFile_WriteString(buf, f);
+ PyFile_WriteString("\n", f);
+ if (text != NULL)
+ print_error_text(f, offset, text);
+ Py_DECREF(value);
+ value = message;
+ /* Can't be bothered to check all those
+ PyFile_WriteString() calls */
+ if (PyErr_Occurred())
+ err = -1;
+ }
+ }
+ if (err) {
+ /* Don't do anything else */
+ }
+ else if (PyExceptionClass_Check(exception)) {
+ PyObject* moduleName;
+ char* className = PyExceptionClass_Name(exception);
+ if (className != NULL) {
+ char *dot = strrchr(className, '.');
+ if (dot != NULL)
+ className = dot+1;
+ }
+
+ moduleName = PyObject_GetAttrString(exception, "__module__");
+ if (moduleName == NULL)
+ err = PyFile_WriteString("<unknown>", f);
+ else {
+ char* modstr = PyString_AsString(moduleName);
+ if (modstr && strcmp(modstr, "exceptions"))
+ {
+ err = PyFile_WriteString(modstr, f);
+ err += PyFile_WriteString(".", f);
+ }
+ Py_DECREF(moduleName);
+ }
+ if (err == 0) {
+ if (className == NULL)
+ err = PyFile_WriteString("<unknown>", f);
+ else
+ err = PyFile_WriteString(className, f);
+ }
+ }
+ else
+ err = PyFile_WriteObject(exception, f, Py_PRINT_RAW);
+ if (err == 0 && (value != Py_None)) {
+ PyObject *s = PyObject_Str(value);
+ /* only print colon if the str() of the
+ object is not the empty string
+ */
+ if (s == NULL)
+ err = -1;
+ else if (!PyString_Check(s) ||
+ PyString_GET_SIZE(s) != 0)
+ err = PyFile_WriteString(": ", f);
+ if (err == 0)
+ err = PyFile_WriteObject(s, f, Py_PRINT_RAW);
+ Py_XDECREF(s);
+ }
+ /* try to write a newline in any case */
+ err += PyFile_WriteString("\n", f);
+ }
+ Py_DECREF(value);
+ /* If an error happened here, don't show it.
+ XXX This is wrong, but too many callers rely on this behavior. */
+ if (err != 0)
+ PyErr_Clear();
}
PyObject *
PyRun_StringFlags(const char *str, int start, PyObject *globals,
- PyObject *locals, PyCompilerFlags *flags)
+ PyObject *locals, PyCompilerFlags *flags)
{
- PyObject *ret = NULL;
- mod_ty mod;
- PyArena *arena = PyArena_New();
- if (arena == NULL)
- return NULL;
+ PyObject *ret = NULL;
+ mod_ty mod;
+ PyArena *arena = PyArena_New();
+ if (arena == NULL)
+ return NULL;
- mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
- if (mod != NULL)
- ret = run_mod(mod, "<string>", globals, locals, flags, arena);
- PyArena_Free(arena);
- return ret;
+ mod = PyParser_ASTFromString(str, "<string>", start, flags, arena);
+ if (mod != NULL)
+ ret = run_mod(mod, "<string>", globals, locals, flags, arena);
+ PyArena_Free(arena);
+ return ret;
}
PyObject *
PyRun_FileExFlags(FILE *fp, const char *filename, int start, PyObject *globals,
- PyObject *locals, int closeit, PyCompilerFlags *flags)
-{
- PyObject *ret;
- mod_ty mod;
- PyArena *arena = PyArena_New();
- if (arena == NULL)
- return NULL;
-
- mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
- flags, NULL, arena);
- if (closeit)
- fclose(fp);
- if (mod == NULL) {
- PyArena_Free(arena);
- return NULL;
- }
- ret = run_mod(mod, filename, globals, locals, flags, arena);
- PyArena_Free(arena);
- return ret;
+ PyObject *locals, int closeit, PyCompilerFlags *flags)
+{
+ PyObject *ret;
+ mod_ty mod;
+ PyArena *arena = PyArena_New();
+ if (arena == NULL)
+ return NULL;
+
+ mod = PyParser_ASTFromFile(fp, filename, start, 0, 0,
+ flags, NULL, arena);
+ if (closeit)
+ fclose(fp);
+ if (mod == NULL) {
+ PyArena_Free(arena);
+ return NULL;
+ }
+ ret = run_mod(mod, filename, globals, locals, flags, arena);
+ PyArena_Free(arena);
+ return ret;
}
static PyObject *
run_mod(mod_ty mod, const char *filename, PyObject *globals, PyObject *locals,
- PyCompilerFlags *flags, PyArena *arena)
+ PyCompilerFlags *flags, PyArena *arena)
{
- PyCodeObject *co;
- PyObject *v;
- co = PyAST_Compile(mod, filename, flags, arena);
- if (co == NULL)
- return NULL;
- v = PyEval_EvalCode(co, globals, locals);
- Py_DECREF(co);
- return v;
+ PyCodeObject *co;
+ PyObject *v;
+ co = PyAST_Compile(mod, filename, flags, arena);
+ if (co == NULL)
+ return NULL;
+ v = PyEval_EvalCode(co, globals, locals);
+ Py_DECREF(co);
+ return v;
}
static PyObject *
run_pyc_file(FILE *fp, const char *filename, PyObject *globals,
- PyObject *locals, PyCompilerFlags *flags)
-{
- PyCodeObject *co;
- PyObject *v;
- long magic;
- long PyImport_GetMagicNumber(void);
-
- magic = PyMarshal_ReadLongFromFile(fp);
- if (magic != PyImport_GetMagicNumber()) {
- PyErr_SetString(PyExc_RuntimeError,
- "Bad magic number in .pyc file");
- return NULL;
- }
- (void) PyMarshal_ReadLongFromFile(fp);
- v = PyMarshal_ReadLastObjectFromFile(fp);
- fclose(fp);
- if (v == NULL || !PyCode_Check(v)) {
- Py_XDECREF(v);
- PyErr_SetString(PyExc_RuntimeError,
- "Bad code object in .pyc file");
- return NULL;
- }
- co = (PyCodeObject *)v;
- v = PyEval_EvalCode(co, globals, locals);
- if (v && flags)
- flags->cf_flags |= (co->co_flags & PyCF_MASK);
- Py_DECREF(co);
- return v;
+ PyObject *locals, PyCompilerFlags *flags)
+{
+ PyCodeObject *co;
+ PyObject *v;
+ long magic;
+ long PyImport_GetMagicNumber(void);
+
+ magic = PyMarshal_ReadLongFromFile(fp);
+ if (magic != PyImport_GetMagicNumber()) {
+ PyErr_SetString(PyExc_RuntimeError,
+ "Bad magic number in .pyc file");
+ return NULL;
+ }
+ (void) PyMarshal_ReadLongFromFile(fp);
+ v = PyMarshal_ReadLastObjectFromFile(fp);
+ fclose(fp);
+ if (v == NULL || !PyCode_Check(v)) {
+ Py_XDECREF(v);
+ PyErr_SetString(PyExc_RuntimeError,
+ "Bad code object in .pyc file");
+ return NULL;
+ }
+ co = (PyCodeObject *)v;
+ v = PyEval_EvalCode(co, globals, locals);
+ if (v && flags)
+ flags->cf_flags |= (co->co_flags & PyCF_MASK);
+ Py_DECREF(co);
+ return v;
}
PyObject *
Py_CompileStringFlags(const char *str, const char *filename, int start,
- PyCompilerFlags *flags)
-{
- PyCodeObject *co;
- mod_ty mod;
- PyArena *arena = PyArena_New();
- if (arena == NULL)
- return NULL;
-
- mod = PyParser_ASTFromString(str, filename, start, flags, arena);
- if (mod == NULL) {
- PyArena_Free(arena);
- return NULL;
- }
- if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
- PyObject *result = PyAST_mod2obj(mod);
- PyArena_Free(arena);
- return result;
- }
- co = PyAST_Compile(mod, filename, flags, arena);
- PyArena_Free(arena);
- return (PyObject *)co;
+ PyCompilerFlags *flags)
+{
+ PyCodeObject *co;
+ mod_ty mod;
+ PyArena *arena = PyArena_New();
+ if (arena == NULL)
+ return NULL;
+
+ mod = PyParser_ASTFromString(str, filename, start, flags, arena);
+ if (mod == NULL) {
+ PyArena_Free(arena);
+ return NULL;
+ }
+ if (flags && (flags->cf_flags & PyCF_ONLY_AST)) {
+ PyObject *result = PyAST_mod2obj(mod);
+ PyArena_Free(arena);
+ return result;
+ }
+ co = PyAST_Compile(mod, filename, flags, arena);
+ PyArena_Free(arena);
+ return (PyObject *)co;
}
struct symtable *
Py_SymtableString(const char *str, const char *filename, int start)
{
- struct symtable *st;
- mod_ty mod;
- PyCompilerFlags flags;
- PyArena *arena = PyArena_New();
- if (arena == NULL)
- return NULL;
+ struct symtable *st;
+ mod_ty mod;
+ PyCompilerFlags flags;
+ PyArena *arena = PyArena_New();
+ if (arena == NULL)
+ return NULL;
- flags.cf_flags = 0;
+ flags.cf_flags = 0;
- mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
- if (mod == NULL) {
- PyArena_Free(arena);
- return NULL;
- }
- st = PySymtable_Build(mod, filename, 0);
- PyArena_Free(arena);
- return st;
+ mod = PyParser_ASTFromString(str, filename, start, &flags, arena);
+ if (mod == NULL) {
+ PyArena_Free(arena);
+ return NULL;
+ }
+ st = PySymtable_Build(mod, filename, 0);
+ PyArena_Free(arena);
+ return st;
}
/* Preferred access to parser is through AST. */
mod_ty
PyParser_ASTFromString(const char *s, const char *filename, int start,
- PyCompilerFlags *flags, PyArena *arena)
-{
- mod_ty mod;
- PyCompilerFlags localflags;
- perrdetail err;
- int iflags = PARSER_FLAGS(flags);
-
- node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
- &_PyParser_Grammar, start, &err,
- &iflags);
- if (flags == NULL) {
- localflags.cf_flags = 0;
- flags = &localflags;
- }
- if (n) {
- flags->cf_flags |= iflags & PyCF_MASK;
- mod = PyAST_FromNode(n, flags, filename, arena);
- PyNode_Free(n);
- return mod;
- }
- else {
- err_input(&err);
- return NULL;
- }
+ PyCompilerFlags *flags, PyArena *arena)
+{
+ mod_ty mod;
+ PyCompilerFlags localflags;
+ perrdetail err;
+ int iflags = PARSER_FLAGS(flags);
+
+ node *n = PyParser_ParseStringFlagsFilenameEx(s, filename,
+ &_PyParser_Grammar, start, &err,
+ &iflags);
+ if (flags == NULL) {
+ localflags.cf_flags = 0;
+ flags = &localflags;
+ }
+ if (n) {
+ flags->cf_flags |= iflags & PyCF_MASK;
+ mod = PyAST_FromNode(n, flags, filename, arena);
+ PyNode_Free(n);
+ return mod;
+ }
+ else {
+ err_input(&err);
+ return NULL;
+ }
}
mod_ty
PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
- char *ps2, PyCompilerFlags *flags, int *errcode,
- PyArena *arena)
-{
- mod_ty mod;
- PyCompilerFlags localflags;
- perrdetail err;
- int iflags = PARSER_FLAGS(flags);
-
- node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
- start, ps1, ps2, &err, &iflags);
- if (flags == NULL) {
- localflags.cf_flags = 0;
- flags = &localflags;
- }
- if (n) {
- flags->cf_flags |= iflags & PyCF_MASK;
- mod = PyAST_FromNode(n, flags, filename, arena);
- PyNode_Free(n);
- return mod;
- }
- else {
- err_input(&err);
- if (errcode)
- *errcode = err.error;
- return NULL;
- }
+ char *ps2, PyCompilerFlags *flags, int *errcode,
+ PyArena *arena)
+{
+ mod_ty mod;
+ PyCompilerFlags localflags;
+ perrdetail err;
+ int iflags = PARSER_FLAGS(flags);
+
+ node *n = PyParser_ParseFileFlagsEx(fp, filename, &_PyParser_Grammar,
+ start, ps1, ps2, &err, &iflags);
+ if (flags == NULL) {
+ localflags.cf_flags = 0;
+ flags = &localflags;
+ }
+ if (n) {
+ flags->cf_flags |= iflags & PyCF_MASK;
+ mod = PyAST_FromNode(n, flags, filename, arena);
+ PyNode_Free(n);
+ return mod;
+ }
+ else {
+ err_input(&err);
+ if (errcode)
+ *errcode = err.error;
+ return NULL;
+ }
}
/* Simplified interface to parsefile -- return node or set exception */
@@ -1485,13 +1485,13 @@ PyParser_ASTFromFile(FILE *fp, const char *filename, int start, char *ps1,
node *
PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int flags)
{
- perrdetail err;
- node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
- start, NULL, NULL, &err, flags);
- if (n == NULL)
- err_input(&err);
+ perrdetail err;
+ node *n = PyParser_ParseFileFlags(fp, filename, &_PyParser_Grammar,
+ start, NULL, NULL, &err, flags);
+ if (n == NULL)
+ err_input(&err);
- return n;
+ return n;
}
/* Simplified interface to parsestring -- return node or set exception */
@@ -1499,30 +1499,30 @@ PyParser_SimpleParseFileFlags(FILE *fp, const char *filename, int start, int fla
node *
PyParser_SimpleParseStringFlags(const char *str, int start, int flags)
{
- perrdetail err;
- node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
- start, &err, flags);
- if (n == NULL)
- err_input(&err);
- return n;
+ perrdetail err;
+ node *n = PyParser_ParseStringFlags(str, &_PyParser_Grammar,
+ start, &err, flags);
+ if (n == NULL)
+ err_input(&err);
+ return n;
}
node *
PyParser_SimpleParseStringFlagsFilename(const char *str, const char *filename,
- int start, int flags)
+ int start, int flags)
{
- perrdetail err;
- node *n = PyParser_ParseStringFlagsFilename(str, filename,
- &_PyParser_Grammar, start, &err, flags);
- if (n == NULL)
- err_input(&err);
- return n;
+ perrdetail err;
+ node *n = PyParser_ParseStringFlagsFilename(str, filename,
+ &_PyParser_Grammar, start, &err, flags);
+ if (n == NULL)
+ err_input(&err);
+ return n;
}
node *
PyParser_SimpleParseStringFilename(const char *str, const char *filename, int start)
{
- return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
+ return PyParser_SimpleParseStringFlagsFilename(str, filename, start, 0);
}
/* May want to move a more generalized form of this to parsetok.c or
@@ -1531,7 +1531,7 @@ PyParser_SimpleParseStringFilename(const char *str, const char *filename, int st
void
PyParser_SetError(perrdetail *err)
{
- err_input(err);
+ err_input(err);
}
/* Set the error appropriate to the given input error code (see errcode.h) */
@@ -1539,98 +1539,98 @@ PyParser_SetError(perrdetail *err)
static void
err_input(perrdetail *err)
{
- PyObject *v, *w, *errtype;
- PyObject* u = NULL;
- char *msg = NULL;
- errtype = PyExc_SyntaxError;
- switch (err->error) {
- case E_ERROR:
- return;
- case E_SYNTAX:
- errtype = PyExc_IndentationError;
- if (err->expected == INDENT)
- msg = "expected an indented block";
- else if (err->token == INDENT)
- msg = "unexpected indent";
- else if (err->token == DEDENT)
- msg = "unexpected unindent";
- else {
- errtype = PyExc_SyntaxError;
- msg = "invalid syntax";
- }
- break;
- case E_TOKEN:
- msg = "invalid token";
- break;
- case E_EOFS:
- msg = "EOF while scanning triple-quoted string literal";
- break;
- case E_EOLS:
- msg = "EOL while scanning string literal";
- break;
- case E_INTR:
- if (!PyErr_Occurred())
- PyErr_SetNone(PyExc_KeyboardInterrupt);
- goto cleanup;
- case E_NOMEM:
- PyErr_NoMemory();
- goto cleanup;
- case E_EOF:
- msg = "unexpected EOF while parsing";
- break;
- case E_TABSPACE:
- errtype = PyExc_TabError;
- msg = "inconsistent use of tabs and spaces in indentation";
- break;
- case E_OVERFLOW:
- msg = "expression too long";
- break;
- case E_DEDENT:
- errtype = PyExc_IndentationError;
- msg = "unindent does not match any outer indentation level";
- break;
- case E_TOODEEP:
- errtype = PyExc_IndentationError;
- msg = "too many levels of indentation";
- break;
- case E_DECODE: {
- PyObject *type, *value, *tb;
- PyErr_Fetch(&type, &value, &tb);
- if (value != NULL) {
- u = PyObject_Str(value);
- if (u != NULL) {
- msg = PyString_AsString(u);
- }
- }
- if (msg == NULL)
- msg = "unknown decode error";
- Py_XDECREF(type);
- Py_XDECREF(value);
- Py_XDECREF(tb);
- break;
- }
- case E_LINECONT:
- msg = "unexpected character after line continuation character";
- break;
- default:
- fprintf(stderr, "error=%d\n", err->error);
- msg = "unknown parsing error";
- break;
- }
- v = Py_BuildValue("(ziiz)", err->filename,
- err->lineno, err->offset, err->text);
- w = NULL;
- if (v != NULL)
- w = Py_BuildValue("(sO)", msg, v);
- Py_XDECREF(u);
- Py_XDECREF(v);
- PyErr_SetObject(errtype, w);
- Py_XDECREF(w);
+ PyObject *v, *w, *errtype;
+ PyObject* u = NULL;
+ char *msg = NULL;
+ errtype = PyExc_SyntaxError;
+ switch (err->error) {
+ case E_ERROR:
+ return;
+ case E_SYNTAX:
+ errtype = PyExc_IndentationError;
+ if (err->expected == INDENT)
+ msg = "expected an indented block";
+ else if (err->token == INDENT)
+ msg = "unexpected indent";
+ else if (err->token == DEDENT)
+ msg = "unexpected unindent";
+ else {
+ errtype = PyExc_SyntaxError;
+ msg = "invalid syntax";
+ }
+ break;
+ case E_TOKEN:
+ msg = "invalid token";
+ break;
+ case E_EOFS:
+ msg = "EOF while scanning triple-quoted string literal";
+ break;
+ case E_EOLS:
+ msg = "EOL while scanning string literal";
+ break;
+ case E_INTR:
+ if (!PyErr_Occurred())
+ PyErr_SetNone(PyExc_KeyboardInterrupt);
+ goto cleanup;
+ case E_NOMEM:
+ PyErr_NoMemory();
+ goto cleanup;
+ case E_EOF:
+ msg = "unexpected EOF while parsing";
+ break;
+ case E_TABSPACE:
+ errtype = PyExc_TabError;
+ msg = "inconsistent use of tabs and spaces in indentation";
+ break;
+ case E_OVERFLOW:
+ msg = "expression too long";
+ break;
+ case E_DEDENT:
+ errtype = PyExc_IndentationError;
+ msg = "unindent does not match any outer indentation level";
+ break;
+ case E_TOODEEP:
+ errtype = PyExc_IndentationError;
+ msg = "too many levels of indentation";
+ break;
+ case E_DECODE: {
+ PyObject *type, *value, *tb;
+ PyErr_Fetch(&type, &value, &tb);
+ if (value != NULL) {
+ u = PyObject_Str(value);
+ if (u != NULL) {
+ msg = PyString_AsString(u);
+ }
+ }
+ if (msg == NULL)
+ msg = "unknown decode error";
+ Py_XDECREF(type);
+ Py_XDECREF(value);
+ Py_XDECREF(tb);
+ break;
+ }
+ case E_LINECONT:
+ msg = "unexpected character after line continuation character";
+ break;
+ default:
+ fprintf(stderr, "error=%d\n", err->error);
+ msg = "unknown parsing error";
+ break;
+ }
+ v = Py_BuildValue("(ziiz)", err->filename,
+ err->lineno, err->offset, err->text);
+ w = NULL;
+ if (v != NULL)
+ w = Py_BuildValue("(sO)", msg, v);
+ Py_XDECREF(u);
+ Py_XDECREF(v);
+ PyErr_SetObject(errtype, w);
+ Py_XDECREF(w);
cleanup:
- if (err->text != NULL) {
- PyObject_FREE(err->text);
- err->text = NULL;
- }
+ if (err->text != NULL) {
+ PyObject_FREE(err->text);
+ err->text = NULL;
+ }
}
/* Print fatal error message and abort */
@@ -1638,30 +1638,30 @@ cleanup:
void
Py_FatalError(const char *msg)
{
- fprintf(stderr, "Fatal Python error: %s\n", msg);
- fflush(stderr); /* it helps in Windows debug build */
+ fprintf(stderr, "Fatal Python error: %s\n", msg);
+ fflush(stderr); /* it helps in Windows debug build */
#ifdef MS_WINDOWS
- {
- size_t len = strlen(msg);
- WCHAR* buffer;
- size_t i;
-
- /* Convert the message to wchar_t. This uses a simple one-to-one
- conversion, assuming that the this error message actually uses ASCII
- only. If this ceases to be true, we will have to convert. */
- buffer = alloca( (len+1) * (sizeof *buffer));
- for( i=0; i<=len; ++i)
- buffer[i] = msg[i];
- OutputDebugStringW(L"Fatal Python error: ");
- OutputDebugStringW(buffer);
- OutputDebugStringW(L"\n");
- }
+ {
+ size_t len = strlen(msg);
+ WCHAR* buffer;
+ size_t i;
+
+ /* Convert the message to wchar_t. This uses a simple one-to-one
+ conversion, assuming that the this error message actually uses ASCII
+ only. If this ceases to be true, we will have to convert. */
+ buffer = alloca( (len+1) * (sizeof *buffer));
+ for( i=0; i<=len; ++i)
+ buffer[i] = msg[i];
+ OutputDebugStringW(L"Fatal Python error: ");
+ OutputDebugStringW(buffer);
+ OutputDebugStringW(L"\n");
+ }
#ifdef _DEBUG
- DebugBreak();
+ DebugBreak();
#endif
#endif /* MS_WINDOWS */
- abort();
+ abort();
}
/* Clean up and exit */
@@ -1678,21 +1678,21 @@ static void
wait_for_thread_shutdown(void)
{
#ifdef WITH_THREAD
- PyObject *result;
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
- "threading");
- if (threading == NULL) {
- /* threading not imported */
- PyErr_Clear();
- return;
- }
- result = PyObject_CallMethod(threading, "_shutdown", "");
- if (result == NULL)
- PyErr_WriteUnraisable(threading);
- else
- Py_DECREF(result);
- Py_DECREF(threading);
+ PyObject *result;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *threading = PyMapping_GetItemString(tstate->interp->modules,
+ "threading");
+ if (threading == NULL) {
+ /* threading not imported */
+ PyErr_Clear();
+ return;
+ }
+ result = PyObject_CallMethod(threading, "_shutdown", "");
+ if (result == NULL)
+ PyErr_WriteUnraisable(threading);
+ else
+ Py_DECREF(result);
+ Py_DECREF(threading);
#endif
}
@@ -1702,66 +1702,66 @@ static int nexitfuncs = 0;
int Py_AtExit(void (*func)(void))
{
- if (nexitfuncs >= NEXITFUNCS)
- return -1;
- exitfuncs[nexitfuncs++] = func;
- return 0;
+ if (nexitfuncs >= NEXITFUNCS)
+ return -1;
+ exitfuncs[nexitfuncs++] = func;
+ return 0;
}
static void
call_sys_exitfunc(void)
{
- PyObject *exitfunc = PySys_GetObject("exitfunc");
+ PyObject *exitfunc = PySys_GetObject("exitfunc");
- if (exitfunc) {
- PyObject *res;
- Py_INCREF(exitfunc);
- PySys_SetObject("exitfunc", (PyObject *)NULL);
- res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
- if (res == NULL) {
- if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
- PySys_WriteStderr("Error in sys.exitfunc:\n");
- }
- PyErr_Print();
- }
- Py_DECREF(exitfunc);
- }
+ if (exitfunc) {
+ PyObject *res;
+ Py_INCREF(exitfunc);
+ PySys_SetObject("exitfunc", (PyObject *)NULL);
+ res = PyEval_CallObject(exitfunc, (PyObject *)NULL);
+ if (res == NULL) {
+ if (!PyErr_ExceptionMatches(PyExc_SystemExit)) {
+ PySys_WriteStderr("Error in sys.exitfunc:\n");
+ }
+ PyErr_Print();
+ }
+ Py_DECREF(exitfunc);
+ }
- if (Py_FlushLine())
- PyErr_Clear();
+ if (Py_FlushLine())
+ PyErr_Clear();
}
static void
call_ll_exitfuncs(void)
{
- while (nexitfuncs > 0)
- (*exitfuncs[--nexitfuncs])();
+ while (nexitfuncs > 0)
+ (*exitfuncs[--nexitfuncs])();
- fflush(stdout);
- fflush(stderr);
+ fflush(stdout);
+ fflush(stderr);
}
void
Py_Exit(int sts)
{
- Py_Finalize();
+ Py_Finalize();
- exit(sts);
+ exit(sts);
}
static void
initsigs(void)
{
#ifdef SIGPIPE
- PyOS_setsig(SIGPIPE, SIG_IGN);
+ PyOS_setsig(SIGPIPE, SIG_IGN);
#endif
#ifdef SIGXFZ
- PyOS_setsig(SIGXFZ, SIG_IGN);
+ PyOS_setsig(SIGXFZ, SIG_IGN);
#endif
#ifdef SIGXFSZ
- PyOS_setsig(SIGXFSZ, SIG_IGN);
+ PyOS_setsig(SIGXFSZ, SIG_IGN);
#endif
- PyOS_InitInterrupts(); /* May imply initsignal() */
+ PyOS_InitInterrupts(); /* May imply initsignal() */
}
@@ -1774,13 +1774,13 @@ initsigs(void)
int
Py_FdIsInteractive(FILE *fp, const char *filename)
{
- if (isatty((int)fileno(fp)))
- return 1;
- if (!Py_InteractiveFlag)
- return 0;
- return (filename == NULL) ||
- (strcmp(filename, "<stdin>") == 0) ||
- (strcmp(filename, "???") == 0);
+ if (isatty((int)fileno(fp)))
+ return 1;
+ if (!Py_InteractiveFlag)
+ return 0;
+ return (filename == NULL) ||
+ (strcmp(filename, "<stdin>") == 0) ||
+ (strcmp(filename, "???") == 0);
}
@@ -1798,21 +1798,21 @@ Py_FdIsInteractive(FILE *fp, const char *filename)
int
PyOS_CheckStack(void)
{
- __try {
- /* alloca throws a stack overflow exception if there's
- not enough space left on the stack */
- alloca(PYOS_STACK_MARGIN * sizeof(void*));
- return 0;
- } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
- EXCEPTION_EXECUTE_HANDLER :
- EXCEPTION_CONTINUE_SEARCH) {
- int errcode = _resetstkoflw();
- if (errcode == 0)
- {
- Py_FatalError("Could not reset the stack!");
- }
- }
- return 1;
+ __try {
+ /* alloca throws a stack overflow exception if there's
+ not enough space left on the stack */
+ alloca(PYOS_STACK_MARGIN * sizeof(void*));
+ return 0;
+ } __except (GetExceptionCode() == STATUS_STACK_OVERFLOW ?
+ EXCEPTION_EXECUTE_HANDLER :
+ EXCEPTION_CONTINUE_SEARCH) {
+ int errcode = _resetstkoflw();
+ if (errcode == 0)
+ {
+ Py_FatalError("Could not reset the stack!");
+ }
+ }
+ return 1;
}
#endif /* WIN32 && _MSC_VER */
@@ -1828,33 +1828,33 @@ PyOS_sighandler_t
PyOS_getsig(int sig)
{
#ifdef HAVE_SIGACTION
- struct sigaction context;
- if (sigaction(sig, NULL, &context) == -1)
- return SIG_ERR;
- return context.sa_handler;
+ struct sigaction context;
+ if (sigaction(sig, NULL, &context) == -1)
+ return SIG_ERR;
+ return context.sa_handler;
#else
- PyOS_sighandler_t handler;
+ PyOS_sighandler_t handler;
/* Special signal handling for the secure CRT in Visual Studio 2005 */
#if defined(_MSC_VER) && _MSC_VER >= 1400
- switch (sig) {
- /* Only these signals are valid */
- case SIGINT:
- case SIGILL:
- case SIGFPE:
- case SIGSEGV:
- case SIGTERM:
- case SIGBREAK:
- case SIGABRT:
- break;
- /* Don't call signal() with other values or it will assert */
- default:
- return SIG_ERR;
- }
+ switch (sig) {
+ /* Only these signals are valid */
+ case SIGINT:
+ case SIGILL:
+ case SIGFPE:
+ case SIGSEGV:
+ case SIGTERM:
+ case SIGBREAK:
+ case SIGABRT:
+ break;
+ /* Don't call signal() with other values or it will assert */
+ default:
+ return SIG_ERR;
+ }
#endif /* _MSC_VER && _MSC_VER >= 1400 */
- handler = signal(sig, SIG_IGN);
- if (handler != SIG_ERR)
- signal(sig, handler);
- return handler;
+ handler = signal(sig, SIG_IGN);
+ if (handler != SIG_ERR)
+ signal(sig, handler);
+ return handler;
#endif
}
@@ -1862,24 +1862,24 @@ PyOS_sighandler_t
PyOS_setsig(int sig, PyOS_sighandler_t handler)
{
#ifdef HAVE_SIGACTION
- /* Some code in Modules/signalmodule.c depends on sigaction() being
- * used here if HAVE_SIGACTION is defined. Fix that if this code
- * changes to invalidate that assumption.
- */
- struct sigaction context, ocontext;
- context.sa_handler = handler;
- sigemptyset(&context.sa_mask);
- context.sa_flags = 0;
- if (sigaction(sig, &context, &ocontext) == -1)
- return SIG_ERR;
- return ocontext.sa_handler;
+ /* Some code in Modules/signalmodule.c depends on sigaction() being
+ * used here if HAVE_SIGACTION is defined. Fix that if this code
+ * changes to invalidate that assumption.
+ */
+ struct sigaction context, ocontext;
+ context.sa_handler = handler;
+ sigemptyset(&context.sa_mask);
+ context.sa_flags = 0;
+ if (sigaction(sig, &context, &ocontext) == -1)
+ return SIG_ERR;
+ return ocontext.sa_handler;
#else
- PyOS_sighandler_t oldhandler;
- oldhandler = signal(sig, handler);
+ PyOS_sighandler_t oldhandler;
+ oldhandler = signal(sig, handler);
#ifdef HAVE_SIGINTERRUPT
- siginterrupt(sig, 1);
+ siginterrupt(sig, 1);
#endif
- return oldhandler;
+ return oldhandler;
#endif
}
@@ -1889,71 +1889,71 @@ PyOS_setsig(int sig, PyOS_sighandler_t handler)
PyAPI_FUNC(node *)
PyParser_SimpleParseFile(FILE *fp, const char *filename, int start)
{
- return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
+ return PyParser_SimpleParseFileFlags(fp, filename, start, 0);
}
#undef PyParser_SimpleParseString
PyAPI_FUNC(node *)
PyParser_SimpleParseString(const char *str, int start)
{
- return PyParser_SimpleParseStringFlags(str, start, 0);
+ return PyParser_SimpleParseStringFlags(str, start, 0);
}
#undef PyRun_AnyFile
PyAPI_FUNC(int)
PyRun_AnyFile(FILE *fp, const char *name)
{
- return PyRun_AnyFileExFlags(fp, name, 0, NULL);
+ return PyRun_AnyFileExFlags(fp, name, 0, NULL);
}
#undef PyRun_AnyFileEx
PyAPI_FUNC(int)
PyRun_AnyFileEx(FILE *fp, const char *name, int closeit)
{
- return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
+ return PyRun_AnyFileExFlags(fp, name, closeit, NULL);
}
#undef PyRun_AnyFileFlags
PyAPI_FUNC(int)
PyRun_AnyFileFlags(FILE *fp, const char *name, PyCompilerFlags *flags)
{
- return PyRun_AnyFileExFlags(fp, name, 0, flags);
+ return PyRun_AnyFileExFlags(fp, name, 0, flags);
}
#undef PyRun_File
PyAPI_FUNC(PyObject *)
PyRun_File(FILE *fp, const char *p, int s, PyObject *g, PyObject *l)
{
- return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
+ return PyRun_FileExFlags(fp, p, s, g, l, 0, NULL);
}
#undef PyRun_FileEx
PyAPI_FUNC(PyObject *)
PyRun_FileEx(FILE *fp, const char *p, int s, PyObject *g, PyObject *l, int c)
{
- return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
+ return PyRun_FileExFlags(fp, p, s, g, l, c, NULL);
}
#undef PyRun_FileFlags
PyAPI_FUNC(PyObject *)
PyRun_FileFlags(FILE *fp, const char *p, int s, PyObject *g, PyObject *l,
- PyCompilerFlags *flags)
+ PyCompilerFlags *flags)
{
- return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
+ return PyRun_FileExFlags(fp, p, s, g, l, 0, flags);
}
#undef PyRun_SimpleFile
PyAPI_FUNC(int)
PyRun_SimpleFile(FILE *f, const char *p)
{
- return PyRun_SimpleFileExFlags(f, p, 0, NULL);
+ return PyRun_SimpleFileExFlags(f, p, 0, NULL);
}
#undef PyRun_SimpleFileEx
PyAPI_FUNC(int)
PyRun_SimpleFileEx(FILE *f, const char *p, int c)
{
- return PyRun_SimpleFileExFlags(f, p, c, NULL);
+ return PyRun_SimpleFileExFlags(f, p, c, NULL);
}
@@ -1961,35 +1961,35 @@ PyRun_SimpleFileEx(FILE *f, const char *p, int c)
PyAPI_FUNC(PyObject *)
PyRun_String(const char *str, int s, PyObject *g, PyObject *l)
{
- return PyRun_StringFlags(str, s, g, l, NULL);
+ return PyRun_StringFlags(str, s, g, l, NULL);
}
#undef PyRun_SimpleString
PyAPI_FUNC(int)
PyRun_SimpleString(const char *s)
{
- return PyRun_SimpleStringFlags(s, NULL);
+ return PyRun_SimpleStringFlags(s, NULL);
}
#undef Py_CompileString
PyAPI_FUNC(PyObject *)
Py_CompileString(const char *str, const char *p, int s)
{
- return Py_CompileStringFlags(str, p, s, NULL);
+ return Py_CompileStringFlags(str, p, s, NULL);
}
#undef PyRun_InteractiveOne
PyAPI_FUNC(int)
PyRun_InteractiveOne(FILE *f, const char *p)
{
- return PyRun_InteractiveOneFlags(f, p, NULL);
+ return PyRun_InteractiveOneFlags(f, p, NULL);
}
#undef PyRun_InteractiveLoop
PyAPI_FUNC(int)
PyRun_InteractiveLoop(FILE *f, const char *p)
{
- return PyRun_InteractiveLoopFlags(f, p, NULL);
+ return PyRun_InteractiveLoopFlags(f, p, NULL);
}
#ifdef __cplusplus
diff --git a/Python/strtod.c b/Python/strtod.c
index 748f37b..ee55898 100644
--- a/Python/strtod.c
+++ b/Python/strtod.c
@@ -25,9 +25,9 @@
There are two reasons why this should be provided to the net:
(a) some UNIX systems do not yet have strtod(), or do not have it
- available in the BSD "universe" (but they do have atof()).
+ available in the BSD "universe" (but they do have atof()).
(b) some of the UNIX systems that *do* have it get it wrong.
- (some crash with large arguments, some assign the wrong *ptr value).
+ (some crash with large arguments, some assign the wrong *ptr value).
There is a reason why *we* are providing it: we need a correct version
of strtod(), and if we give this one away maybe someone will look for
mistakes in it and fix them for us (:-).
@@ -35,8 +35,8 @@
/* The following constants are machine-specific. MD{MIN,MAX}EXPT are
integers and MD{MIN,MAX}FRAC are strings such that
- 0.${MDMAXFRAC}e${MDMAXEXPT} is the largest representable double,
- 0.${MDMINFRAC}e${MDMINEXPT} is the smallest representable +ve double
+ 0.${MDMAXFRAC}e${MDMAXEXPT} is the largest representable double,
+ 0.${MDMINFRAC}e${MDMINEXPT} is the smallest representable +ve double
MD{MIN,MAX}FRAC must not have any trailing zeros.
The values here are for IEEE-754 64-bit floats.
It is not perfectly clear to me whether an IEEE infinity should be
@@ -47,113 +47,113 @@
I do know about <values.h>, but the whole point of this file is that
we can't always trust that stuff to be there or to be correct.
*/
-static int MDMINEXPT = -323;
-static char MDMINFRAC[] = "494065645841246544";
-static double ZERO = 0.0;
+static int MDMINEXPT = -323;
+static char MDMINFRAC[] = "494065645841246544";
+static double ZERO = 0.0;
-static int MDMAXEXPT = 309;
-static char MDMAXFRAC[] = "17976931348623157";
-static double HUGE = 1.7976931348623157e308;
+static int MDMAXEXPT = 309;
+static char MDMAXFRAC[] = "17976931348623157";
+static double HUGE = 1.7976931348623157e308;
-extern double atof(const char *); /* Only called when result known to be ok */
+extern double atof(const char *); /* Only called when result known to be ok */
#ifdef HAVE_ERRNO_H
#include <errno.h>
#endif
-extern int errno;
+extern int errno;
double strtod(char *str, char **ptr)
{
- int sign, scale, dotseen;
- int esign, expt;
- char *save;
- register char *sp, *dp;
- register int c;
- char *buforg, *buflim;
- char buffer[64]; /* 45-digit significant + */
- /* 13-digit exponent */
- sp = str;
- while (*sp == ' ') sp++;
- sign = 1;
- if (*sp == '-') sign -= 2, sp++;
- dotseen = 0, scale = 0;
- dp = buffer;
- *dp++ = '0'; *dp++ = '.';
- buforg = dp, buflim = buffer+48;
- for (save = sp; (c = *sp); sp++)
- if (c == '.') {
- if (dotseen) break;
- dotseen++;
- } else
- if ((unsigned)(c-'0') > (unsigned)('9'-'0')) {
- break;
- } else
- if (c == '0') {
- if (dp != buforg) {
- /* This is not the first digit, so we want to keep it */
- if (dp < buflim) *dp++ = c;
- if (!dotseen) scale++;
- } else {
- /* No non-zero digits seen yet */
- /* If a . has been seen, scale must be adjusted */
- if (dotseen) scale--;
- }
- } else {
- /* This is a nonzero digit, so we want to keep it */
- if (dp < buflim) *dp++ = c;
- /* If it precedes a ., scale must be adjusted */
- if (!dotseen) scale++;
- }
- if (sp == save) {
- if (ptr) *ptr = str;
- errno = EDOM; /* what should this be? */
- return ZERO;
- }
+ int sign, scale, dotseen;
+ int esign, expt;
+ char *save;
+ register char *sp, *dp;
+ register int c;
+ char *buforg, *buflim;
+ char buffer[64]; /* 45-digit significant + */
+ /* 13-digit exponent */
+ sp = str;
+ while (*sp == ' ') sp++;
+ sign = 1;
+ if (*sp == '-') sign -= 2, sp++;
+ dotseen = 0, scale = 0;
+ dp = buffer;
+ *dp++ = '0'; *dp++ = '.';
+ buforg = dp, buflim = buffer+48;
+ for (save = sp; (c = *sp); sp++)
+ if (c == '.') {
+ if (dotseen) break;
+ dotseen++;
+ } else
+ if ((unsigned)(c-'0') > (unsigned)('9'-'0')) {
+ break;
+ } else
+ if (c == '0') {
+ if (dp != buforg) {
+ /* This is not the first digit, so we want to keep it */
+ if (dp < buflim) *dp++ = c;
+ if (!dotseen) scale++;
+ } else {
+ /* No non-zero digits seen yet */
+ /* If a . has been seen, scale must be adjusted */
+ if (dotseen) scale--;
+ }
+ } else {
+ /* This is a nonzero digit, so we want to keep it */
+ if (dp < buflim) *dp++ = c;
+ /* If it precedes a ., scale must be adjusted */
+ if (!dotseen) scale++;
+ }
+ if (sp == save) {
+ if (ptr) *ptr = str;
+ errno = EDOM; /* what should this be? */
+ return ZERO;
+ }
- while (dp > buforg && dp[-1] == '0') --dp;
- if (dp == buforg) *dp++ = '0';
- *dp = '\0';
- /* Now the contents of buffer are
- +--+--------+-+--------+
- |0.|fraction|\|leftover|
- +--+--------+-+--------+
- ^dp points here
- where fraction begins with 0 iff it is "0", and has at most
- 45 digits in it, and leftover is at least 16 characters.
- */
- save = sp, expt = 0, esign = 1;
- do {
- c = *sp++;
- if (c != 'e' && c != 'E') break;
- c = *sp++;
- if (c == '-') esign -= 2, c = *sp++; else
- if (c == '+' /* || c == ' ' */ ) c = *sp++;
- if ((unsigned)(c-'0') > (unsigned)('9'-'0')) break;
- while (c == '0') c = *sp++;
- for (; (unsigned)(c-'0') <= (unsigned)('9'-'0'); c = *sp++)
- expt = expt*10 + c-'0';
- if (esign < 0) expt = -expt;
- save = sp-1;
- } while (0);
- if (ptr) *ptr = save;
- expt += scale;
- /* Now the number is sign*0.fraction*10**expt */
- errno = ERANGE;
- if (expt > MDMAXEXPT) {
- return HUGE*sign;
- } else
- if (expt == MDMAXEXPT) {
- if (strcmp(buforg, MDMAXFRAC) > 0) return HUGE*sign;
- } else
- if (expt < MDMINEXPT) {
- return ZERO*sign;
- } else
- if (expt == MDMINEXPT) {
- if (strcmp(buforg, MDMINFRAC) < 0) return ZERO*sign;
- }
- /* We have now established that the number can be */
- /* represented without overflow or underflow */
- (void) sprintf(dp, "E%d", expt);
- errno = 0;
- return atof(buffer)*sign;
+ while (dp > buforg && dp[-1] == '0') --dp;
+ if (dp == buforg) *dp++ = '0';
+ *dp = '\0';
+ /* Now the contents of buffer are
+ +--+--------+-+--------+
+ |0.|fraction|\|leftover|
+ +--+--------+-+--------+
+ ^dp points here
+ where fraction begins with 0 iff it is "0", and has at most
+ 45 digits in it, and leftover is at least 16 characters.
+ */
+ save = sp, expt = 0, esign = 1;
+ do {
+ c = *sp++;
+ if (c != 'e' && c != 'E') break;
+ c = *sp++;
+ if (c == '-') esign -= 2, c = *sp++; else
+ if (c == '+' /* || c == ' ' */ ) c = *sp++;
+ if ((unsigned)(c-'0') > (unsigned)('9'-'0')) break;
+ while (c == '0') c = *sp++;
+ for (; (unsigned)(c-'0') <= (unsigned)('9'-'0'); c = *sp++)
+ expt = expt*10 + c-'0';
+ if (esign < 0) expt = -expt;
+ save = sp-1;
+ } while (0);
+ if (ptr) *ptr = save;
+ expt += scale;
+ /* Now the number is sign*0.fraction*10**expt */
+ errno = ERANGE;
+ if (expt > MDMAXEXPT) {
+ return HUGE*sign;
+ } else
+ if (expt == MDMAXEXPT) {
+ if (strcmp(buforg, MDMAXFRAC) > 0) return HUGE*sign;
+ } else
+ if (expt < MDMINEXPT) {
+ return ZERO*sign;
+ } else
+ if (expt == MDMINEXPT) {
+ if (strcmp(buforg, MDMINFRAC) < 0) return ZERO*sign;
+ }
+ /* We have now established that the number can be */
+ /* represented without overflow or underflow */
+ (void) sprintf(dp, "E%d", expt);
+ errno = 0;
+ return atof(buffer)*sign;
}
diff --git a/Python/structmember.c b/Python/structmember.c
index ac75bf0..e347b51 100644
--- a/Python/structmember.c
+++ b/Python/structmember.c
@@ -8,356 +8,356 @@
static PyObject *
listmembers(struct memberlist *mlist)
{
- int i, n;
- PyObject *v;
- for (n = 0; mlist[n].name != NULL; n++)
- ;
- v = PyList_New(n);
- if (v != NULL) {
- for (i = 0; i < n; i++)
- PyList_SetItem(v, i,
- PyString_FromString(mlist[i].name));
- if (PyErr_Occurred()) {
- Py_DECREF(v);
- v = NULL;
- }
- else {
- PyList_Sort(v);
- }
- }
- return v;
+ int i, n;
+ PyObject *v;
+ for (n = 0; mlist[n].name != NULL; n++)
+ ;
+ v = PyList_New(n);
+ if (v != NULL) {
+ for (i = 0; i < n; i++)
+ PyList_SetItem(v, i,
+ PyString_FromString(mlist[i].name));
+ if (PyErr_Occurred()) {
+ Py_DECREF(v);
+ v = NULL;
+ }
+ else {
+ PyList_Sort(v);
+ }
+ }
+ return v;
}
PyObject *
PyMember_Get(const char *addr, struct memberlist *mlist, const char *name)
{
- struct memberlist *l;
+ struct memberlist *l;
- if (strcmp(name, "__members__") == 0)
- return listmembers(mlist);
- for (l = mlist; l->name != NULL; l++) {
- if (strcmp(l->name, name) == 0) {
- PyMemberDef copy;
- copy.name = l->name;
- copy.type = l->type;
- copy.offset = l->offset;
- copy.flags = l->flags;
- copy.doc = NULL;
- return PyMember_GetOne(addr, &copy);
- }
- }
- PyErr_SetString(PyExc_AttributeError, name);
- return NULL;
+ if (strcmp(name, "__members__") == 0)
+ return listmembers(mlist);
+ for (l = mlist; l->name != NULL; l++) {
+ if (strcmp(l->name, name) == 0) {
+ PyMemberDef copy;
+ copy.name = l->name;
+ copy.type = l->type;
+ copy.offset = l->offset;
+ copy.flags = l->flags;
+ copy.doc = NULL;
+ return PyMember_GetOne(addr, &copy);
+ }
+ }
+ PyErr_SetString(PyExc_AttributeError, name);
+ return NULL;
}
PyObject *
PyMember_GetOne(const char *addr, PyMemberDef *l)
{
- PyObject *v;
- if ((l->flags & READ_RESTRICTED) &&
- PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
- return NULL;
- }
- addr += l->offset;
- switch (l->type) {
- case T_BOOL:
- v = PyBool_FromLong(*(char*)addr);
- break;
- case T_BYTE:
- v = PyInt_FromLong(*(char*)addr);
- break;
- case T_UBYTE:
- v = PyLong_FromUnsignedLong(*(unsigned char*)addr);
- break;
- case T_SHORT:
- v = PyInt_FromLong(*(short*)addr);
- break;
- case T_USHORT:
- v = PyLong_FromUnsignedLong(*(unsigned short*)addr);
- break;
- case T_INT:
- v = PyInt_FromLong(*(int*)addr);
- break;
- case T_UINT:
- v = PyLong_FromUnsignedLong(*(unsigned int*)addr);
- break;
- case T_LONG:
- v = PyInt_FromLong(*(long*)addr);
- break;
- case T_ULONG:
- v = PyLong_FromUnsignedLong(*(unsigned long*)addr);
- break;
- case T_PYSSIZET:
- v = PyInt_FromSsize_t(*(Py_ssize_t*)addr);
- break;
- case T_FLOAT:
- v = PyFloat_FromDouble((double)*(float*)addr);
- break;
- case T_DOUBLE:
- v = PyFloat_FromDouble(*(double*)addr);
- break;
- case T_STRING:
- if (*(char**)addr == NULL) {
- Py_INCREF(Py_None);
- v = Py_None;
- }
- else
- v = PyString_FromString(*(char**)addr);
- break;
- case T_STRING_INPLACE:
- v = PyString_FromString((char*)addr);
- break;
- case T_CHAR:
- v = PyString_FromStringAndSize((char*)addr, 1);
- break;
- case T_OBJECT:
- v = *(PyObject **)addr;
- if (v == NULL)
- v = Py_None;
- Py_INCREF(v);
- break;
- case T_OBJECT_EX:
- v = *(PyObject **)addr;
- if (v == NULL)
- PyErr_SetString(PyExc_AttributeError, l->name);
- Py_XINCREF(v);
- break;
+ PyObject *v;
+ if ((l->flags & READ_RESTRICTED) &&
+ PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
+ return NULL;
+ }
+ addr += l->offset;
+ switch (l->type) {
+ case T_BOOL:
+ v = PyBool_FromLong(*(char*)addr);
+ break;
+ case T_BYTE:
+ v = PyInt_FromLong(*(char*)addr);
+ break;
+ case T_UBYTE:
+ v = PyLong_FromUnsignedLong(*(unsigned char*)addr);
+ break;
+ case T_SHORT:
+ v = PyInt_FromLong(*(short*)addr);
+ break;
+ case T_USHORT:
+ v = PyLong_FromUnsignedLong(*(unsigned short*)addr);
+ break;
+ case T_INT:
+ v = PyInt_FromLong(*(int*)addr);
+ break;
+ case T_UINT:
+ v = PyLong_FromUnsignedLong(*(unsigned int*)addr);
+ break;
+ case T_LONG:
+ v = PyInt_FromLong(*(long*)addr);
+ break;
+ case T_ULONG:
+ v = PyLong_FromUnsignedLong(*(unsigned long*)addr);
+ break;
+ case T_PYSSIZET:
+ v = PyInt_FromSsize_t(*(Py_ssize_t*)addr);
+ break;
+ case T_FLOAT:
+ v = PyFloat_FromDouble((double)*(float*)addr);
+ break;
+ case T_DOUBLE:
+ v = PyFloat_FromDouble(*(double*)addr);
+ break;
+ case T_STRING:
+ if (*(char**)addr == NULL) {
+ Py_INCREF(Py_None);
+ v = Py_None;
+ }
+ else
+ v = PyString_FromString(*(char**)addr);
+ break;
+ case T_STRING_INPLACE:
+ v = PyString_FromString((char*)addr);
+ break;
+ case T_CHAR:
+ v = PyString_FromStringAndSize((char*)addr, 1);
+ break;
+ case T_OBJECT:
+ v = *(PyObject **)addr;
+ if (v == NULL)
+ v = Py_None;
+ Py_INCREF(v);
+ break;
+ case T_OBJECT_EX:
+ v = *(PyObject **)addr;
+ if (v == NULL)
+ PyErr_SetString(PyExc_AttributeError, l->name);
+ Py_XINCREF(v);
+ break;
#ifdef HAVE_LONG_LONG
- case T_LONGLONG:
- v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr);
- break;
- case T_ULONGLONG:
- v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr);
- break;
+ case T_LONGLONG:
+ v = PyLong_FromLongLong(*(PY_LONG_LONG *)addr);
+ break;
+ case T_ULONGLONG:
+ v = PyLong_FromUnsignedLongLong(*(unsigned PY_LONG_LONG *)addr);
+ break;
#endif /* HAVE_LONG_LONG */
- default:
- PyErr_SetString(PyExc_SystemError, "bad memberdescr type");
- v = NULL;
- }
- return v;
+ default:
+ PyErr_SetString(PyExc_SystemError, "bad memberdescr type");
+ v = NULL;
+ }
+ return v;
}
int
PyMember_Set(char *addr, struct memberlist *mlist, const char *name, PyObject *v)
{
- struct memberlist *l;
+ struct memberlist *l;
- for (l = mlist; l->name != NULL; l++) {
- if (strcmp(l->name, name) == 0) {
- PyMemberDef copy;
- copy.name = l->name;
- copy.type = l->type;
- copy.offset = l->offset;
- copy.flags = l->flags;
- copy.doc = NULL;
- return PyMember_SetOne(addr, &copy, v);
- }
- }
+ for (l = mlist; l->name != NULL; l++) {
+ if (strcmp(l->name, name) == 0) {
+ PyMemberDef copy;
+ copy.name = l->name;
+ copy.type = l->type;
+ copy.offset = l->offset;
+ copy.flags = l->flags;
+ copy.doc = NULL;
+ return PyMember_SetOne(addr, &copy, v);
+ }
+ }
- PyErr_SetString(PyExc_AttributeError, name);
- return -1;
+ PyErr_SetString(PyExc_AttributeError, name);
+ return -1;
}
-#define WARN(msg) \
- do { \
- if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) \
- return -1; \
+#define WARN(msg) \
+ do { \
+ if (PyErr_Warn(PyExc_RuntimeWarning, msg) < 0) \
+ return -1; \
} while (0)
int
PyMember_SetOne(char *addr, PyMemberDef *l, PyObject *v)
{
- PyObject *oldv;
+ PyObject *oldv;
- addr += l->offset;
+ addr += l->offset;
- if ((l->flags & READONLY))
- {
- PyErr_SetString(PyExc_TypeError, "readonly attribute");
- return -1;
- }
- if ((l->flags & PY_WRITE_RESTRICTED) && PyEval_GetRestricted()) {
- PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
- return -1;
- }
- if (v == NULL) {
- if (l->type == T_OBJECT_EX) {
- /* Check if the attribute is set. */
- if (*(PyObject **)addr == NULL) {
- PyErr_SetString(PyExc_AttributeError, l->name);
- return -1;
- }
- }
- else if (l->type != T_OBJECT) {
- PyErr_SetString(PyExc_TypeError,
- "can't delete numeric/char attribute");
- return -1;
- }
- }
- switch (l->type) {
- case T_BOOL:{
- if (!PyBool_Check(v)) {
- PyErr_SetString(PyExc_TypeError,
- "attribute value type must be bool");
- return -1;
- }
- if (v == Py_True)
- *(char*)addr = (char) 1;
- else
- *(char*)addr = (char) 0;
- break;
- }
- case T_BYTE:{
- long long_val = PyInt_AsLong(v);
- if ((long_val == -1) && PyErr_Occurred())
- return -1;
- *(char*)addr = (char)long_val;
- /* XXX: For compatibility, only warn about truncations
- for now. */
- if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN))
- WARN("Truncation of value to char");
- break;
- }
- case T_UBYTE:{
- long long_val = PyInt_AsLong(v);
- if ((long_val == -1) && PyErr_Occurred())
- return -1;
- *(unsigned char*)addr = (unsigned char)long_val;
- if ((long_val > UCHAR_MAX) || (long_val < 0))
- WARN("Truncation of value to unsigned char");
- break;
- }
- case T_SHORT:{
- long long_val = PyInt_AsLong(v);
- if ((long_val == -1) && PyErr_Occurred())
- return -1;
- *(short*)addr = (short)long_val;
- if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN))
- WARN("Truncation of value to short");
- break;
- }
- case T_USHORT:{
- long long_val = PyInt_AsLong(v);
- if ((long_val == -1) && PyErr_Occurred())
- return -1;
- *(unsigned short*)addr = (unsigned short)long_val;
- if ((long_val > USHRT_MAX) || (long_val < 0))
- WARN("Truncation of value to unsigned short");
- break;
- }
- case T_INT:{
- long long_val = PyInt_AsLong(v);
- if ((long_val == -1) && PyErr_Occurred())
- return -1;
- *(int *)addr = (int)long_val;
- if ((long_val > INT_MAX) || (long_val < INT_MIN))
- WARN("Truncation of value to int");
- break;
- }
- case T_UINT:{
- unsigned long ulong_val = PyLong_AsUnsignedLong(v);
- if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) {
- /* XXX: For compatibility, accept negative int values
- as well. */
- PyErr_Clear();
- ulong_val = PyLong_AsLong(v);
- if ((ulong_val == (unsigned long)-1) &&
- PyErr_Occurred())
- return -1;
- *(unsigned int *)addr = (unsigned int)ulong_val;
- WARN("Writing negative value into unsigned field");
- } else
- *(unsigned int *)addr = (unsigned int)ulong_val;
- if (ulong_val > UINT_MAX)
- WARN("Truncation of value to unsigned int");
- break;
- }
- case T_LONG:{
- *(long*)addr = PyLong_AsLong(v);
- if ((*(long*)addr == -1) && PyErr_Occurred())
- return -1;
- break;
- }
- case T_ULONG:{
- *(unsigned long*)addr = PyLong_AsUnsignedLong(v);
- if ((*(unsigned long*)addr == (unsigned long)-1)
- && PyErr_Occurred()) {
- /* XXX: For compatibility, accept negative int values
- as well. */
- PyErr_Clear();
- *(unsigned long*)addr = PyLong_AsLong(v);
- if ((*(unsigned long*)addr == (unsigned long)-1)
- && PyErr_Occurred())
- return -1;
- WARN("Writing negative value into unsigned field");
- }
- break;
- }
- case T_PYSSIZET:{
- *(Py_ssize_t*)addr = PyInt_AsSsize_t(v);
- if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1)
- && PyErr_Occurred())
- return -1;
- break;
- }
- case T_FLOAT:{
- double double_val = PyFloat_AsDouble(v);
- if ((double_val == -1) && PyErr_Occurred())
- return -1;
- *(float*)addr = (float)double_val;
- break;
- }
- case T_DOUBLE:
- *(double*)addr = PyFloat_AsDouble(v);
- if ((*(double*)addr == -1) && PyErr_Occurred())
- return -1;
- break;
- case T_OBJECT:
- case T_OBJECT_EX:
- Py_XINCREF(v);
- oldv = *(PyObject **)addr;
- *(PyObject **)addr = v;
- Py_XDECREF(oldv);
- break;
- case T_CHAR:
- if (PyString_Check(v) && PyString_Size(v) == 1) {
- *(char*)addr = PyString_AsString(v)[0];
- }
- else {
- PyErr_BadArgument();
- return -1;
- }
- break;
- case T_STRING:
- case T_STRING_INPLACE:
- PyErr_SetString(PyExc_TypeError, "readonly attribute");
- return -1;
+ if ((l->flags & READONLY))
+ {
+ PyErr_SetString(PyExc_TypeError, "readonly attribute");
+ return -1;
+ }
+ if ((l->flags & PY_WRITE_RESTRICTED) && PyEval_GetRestricted()) {
+ PyErr_SetString(PyExc_RuntimeError, "restricted attribute");
+ return -1;
+ }
+ if (v == NULL) {
+ if (l->type == T_OBJECT_EX) {
+ /* Check if the attribute is set. */
+ if (*(PyObject **)addr == NULL) {
+ PyErr_SetString(PyExc_AttributeError, l->name);
+ return -1;
+ }
+ }
+ else if (l->type != T_OBJECT) {
+ PyErr_SetString(PyExc_TypeError,
+ "can't delete numeric/char attribute");
+ return -1;
+ }
+ }
+ switch (l->type) {
+ case T_BOOL:{
+ if (!PyBool_Check(v)) {
+ PyErr_SetString(PyExc_TypeError,
+ "attribute value type must be bool");
+ return -1;
+ }
+ if (v == Py_True)
+ *(char*)addr = (char) 1;
+ else
+ *(char*)addr = (char) 0;
+ break;
+ }
+ case T_BYTE:{
+ long long_val = PyInt_AsLong(v);
+ if ((long_val == -1) && PyErr_Occurred())
+ return -1;
+ *(char*)addr = (char)long_val;
+ /* XXX: For compatibility, only warn about truncations
+ for now. */
+ if ((long_val > CHAR_MAX) || (long_val < CHAR_MIN))
+ WARN("Truncation of value to char");
+ break;
+ }
+ case T_UBYTE:{
+ long long_val = PyInt_AsLong(v);
+ if ((long_val == -1) && PyErr_Occurred())
+ return -1;
+ *(unsigned char*)addr = (unsigned char)long_val;
+ if ((long_val > UCHAR_MAX) || (long_val < 0))
+ WARN("Truncation of value to unsigned char");
+ break;
+ }
+ case T_SHORT:{
+ long long_val = PyInt_AsLong(v);
+ if ((long_val == -1) && PyErr_Occurred())
+ return -1;
+ *(short*)addr = (short)long_val;
+ if ((long_val > SHRT_MAX) || (long_val < SHRT_MIN))
+ WARN("Truncation of value to short");
+ break;
+ }
+ case T_USHORT:{
+ long long_val = PyInt_AsLong(v);
+ if ((long_val == -1) && PyErr_Occurred())
+ return -1;
+ *(unsigned short*)addr = (unsigned short)long_val;
+ if ((long_val > USHRT_MAX) || (long_val < 0))
+ WARN("Truncation of value to unsigned short");
+ break;
+ }
+ case T_INT:{
+ long long_val = PyInt_AsLong(v);
+ if ((long_val == -1) && PyErr_Occurred())
+ return -1;
+ *(int *)addr = (int)long_val;
+ if ((long_val > INT_MAX) || (long_val < INT_MIN))
+ WARN("Truncation of value to int");
+ break;
+ }
+ case T_UINT:{
+ unsigned long ulong_val = PyLong_AsUnsignedLong(v);
+ if ((ulong_val == (unsigned long)-1) && PyErr_Occurred()) {
+ /* XXX: For compatibility, accept negative int values
+ as well. */
+ PyErr_Clear();
+ ulong_val = PyLong_AsLong(v);
+ if ((ulong_val == (unsigned long)-1) &&
+ PyErr_Occurred())
+ return -1;
+ *(unsigned int *)addr = (unsigned int)ulong_val;
+ WARN("Writing negative value into unsigned field");
+ } else
+ *(unsigned int *)addr = (unsigned int)ulong_val;
+ if (ulong_val > UINT_MAX)
+ WARN("Truncation of value to unsigned int");
+ break;
+ }
+ case T_LONG:{
+ *(long*)addr = PyLong_AsLong(v);
+ if ((*(long*)addr == -1) && PyErr_Occurred())
+ return -1;
+ break;
+ }
+ case T_ULONG:{
+ *(unsigned long*)addr = PyLong_AsUnsignedLong(v);
+ if ((*(unsigned long*)addr == (unsigned long)-1)
+ && PyErr_Occurred()) {
+ /* XXX: For compatibility, accept negative int values
+ as well. */
+ PyErr_Clear();
+ *(unsigned long*)addr = PyLong_AsLong(v);
+ if ((*(unsigned long*)addr == (unsigned long)-1)
+ && PyErr_Occurred())
+ return -1;
+ WARN("Writing negative value into unsigned field");
+ }
+ break;
+ }
+ case T_PYSSIZET:{
+ *(Py_ssize_t*)addr = PyInt_AsSsize_t(v);
+ if ((*(Py_ssize_t*)addr == (Py_ssize_t)-1)
+ && PyErr_Occurred())
+ return -1;
+ break;
+ }
+ case T_FLOAT:{
+ double double_val = PyFloat_AsDouble(v);
+ if ((double_val == -1) && PyErr_Occurred())
+ return -1;
+ *(float*)addr = (float)double_val;
+ break;
+ }
+ case T_DOUBLE:
+ *(double*)addr = PyFloat_AsDouble(v);
+ if ((*(double*)addr == -1) && PyErr_Occurred())
+ return -1;
+ break;
+ case T_OBJECT:
+ case T_OBJECT_EX:
+ Py_XINCREF(v);
+ oldv = *(PyObject **)addr;
+ *(PyObject **)addr = v;
+ Py_XDECREF(oldv);
+ break;
+ case T_CHAR:
+ if (PyString_Check(v) && PyString_Size(v) == 1) {
+ *(char*)addr = PyString_AsString(v)[0];
+ }
+ else {
+ PyErr_BadArgument();
+ return -1;
+ }
+ break;
+ case T_STRING:
+ case T_STRING_INPLACE:
+ PyErr_SetString(PyExc_TypeError, "readonly attribute");
+ return -1;
#ifdef HAVE_LONG_LONG
- case T_LONGLONG:{
- PY_LONG_LONG value;
- *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v);
- if ((value == -1) && PyErr_Occurred())
- return -1;
- break;
- }
- case T_ULONGLONG:{
- unsigned PY_LONG_LONG value;
- /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong
- doesn't ??? */
- if (PyLong_Check(v))
- *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v);
- else
- *(unsigned PY_LONG_LONG*)addr = value = PyInt_AsLong(v);
- if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred())
- return -1;
- break;
- }
+ case T_LONGLONG:{
+ PY_LONG_LONG value;
+ *(PY_LONG_LONG*)addr = value = PyLong_AsLongLong(v);
+ if ((value == -1) && PyErr_Occurred())
+ return -1;
+ break;
+ }
+ case T_ULONGLONG:{
+ unsigned PY_LONG_LONG value;
+ /* ??? PyLong_AsLongLong accepts an int, but PyLong_AsUnsignedLongLong
+ doesn't ??? */
+ if (PyLong_Check(v))
+ *(unsigned PY_LONG_LONG*)addr = value = PyLong_AsUnsignedLongLong(v);
+ else
+ *(unsigned PY_LONG_LONG*)addr = value = PyInt_AsLong(v);
+ if ((value == (unsigned PY_LONG_LONG)-1) && PyErr_Occurred())
+ return -1;
+ break;
+ }
#endif /* HAVE_LONG_LONG */
- default:
- PyErr_Format(PyExc_SystemError,
- "bad memberdescr type for %s", l->name);
- return -1;
- }
- return 0;
+ default:
+ PyErr_Format(PyExc_SystemError,
+ "bad memberdescr type for %s", l->name);
+ return -1;
+ }
+ return 0;
}
diff --git a/Python/symtable.c b/Python/symtable.c
index 0c463a2..0da2faf 100644
--- a/Python/symtable.c
+++ b/Python/symtable.c
@@ -19,149 +19,149 @@
static PySTEntryObject *
ste_new(struct symtable *st, identifier name, _Py_block_ty block,
- void *key, int lineno)
+ void *key, int lineno)
{
- PySTEntryObject *ste = NULL;
- PyObject *k;
-
- k = PyLong_FromVoidPtr(key);
- if (k == NULL)
- goto fail;
- ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
- if (ste == NULL)
- goto fail;
- ste->ste_table = st;
- ste->ste_id = k;
-
- ste->ste_name = name;
- Py_INCREF(name);
-
- ste->ste_symbols = NULL;
- ste->ste_varnames = NULL;
- ste->ste_children = NULL;
-
- ste->ste_symbols = PyDict_New();
- if (ste->ste_symbols == NULL)
- goto fail;
-
- ste->ste_varnames = PyList_New(0);
- if (ste->ste_varnames == NULL)
- goto fail;
-
- ste->ste_children = PyList_New(0);
- if (ste->ste_children == NULL)
- goto fail;
-
- ste->ste_type = block;
- ste->ste_unoptimized = 0;
- ste->ste_nested = 0;
- ste->ste_free = 0;
- ste->ste_varargs = 0;
- ste->ste_varkeywords = 0;
- ste->ste_opt_lineno = 0;
- ste->ste_lineno = lineno;
-
- if (st->st_cur != NULL &&
- (st->st_cur->ste_nested ||
- st->st_cur->ste_type == FunctionBlock))
- ste->ste_nested = 1;
- ste->ste_child_free = 0;
- ste->ste_generator = 0;
- ste->ste_returns_value = 0;
-
- if (PyDict_SetItem(st->st_symbols, ste->ste_id, (PyObject *)ste) < 0)
- goto fail;
-
- return ste;
+ PySTEntryObject *ste = NULL;
+ PyObject *k;
+
+ k = PyLong_FromVoidPtr(key);
+ if (k == NULL)
+ goto fail;
+ ste = PyObject_New(PySTEntryObject, &PySTEntry_Type);
+ if (ste == NULL)
+ goto fail;
+ ste->ste_table = st;
+ ste->ste_id = k;
+
+ ste->ste_name = name;
+ Py_INCREF(name);
+
+ ste->ste_symbols = NULL;
+ ste->ste_varnames = NULL;
+ ste->ste_children = NULL;
+
+ ste->ste_symbols = PyDict_New();
+ if (ste->ste_symbols == NULL)
+ goto fail;
+
+ ste->ste_varnames = PyList_New(0);
+ if (ste->ste_varnames == NULL)
+ goto fail;
+
+ ste->ste_children = PyList_New(0);
+ if (ste->ste_children == NULL)
+ goto fail;
+
+ ste->ste_type = block;
+ ste->ste_unoptimized = 0;
+ ste->ste_nested = 0;
+ ste->ste_free = 0;
+ ste->ste_varargs = 0;
+ ste->ste_varkeywords = 0;
+ ste->ste_opt_lineno = 0;
+ ste->ste_lineno = lineno;
+
+ if (st->st_cur != NULL &&
+ (st->st_cur->ste_nested ||
+ st->st_cur->ste_type == FunctionBlock))
+ ste->ste_nested = 1;
+ ste->ste_child_free = 0;
+ ste->ste_generator = 0;
+ ste->ste_returns_value = 0;
+
+ if (PyDict_SetItem(st->st_symbols, ste->ste_id, (PyObject *)ste) < 0)
+ goto fail;
+
+ return ste;
fail:
- Py_XDECREF(ste);
- return NULL;
+ Py_XDECREF(ste);
+ return NULL;
}
static PyObject *
ste_repr(PySTEntryObject *ste)
{
- char buf[256];
+ char buf[256];
- PyOS_snprintf(buf, sizeof(buf),
- "<symtable entry %.100s(%ld), line %d>",
- PyString_AS_STRING(ste->ste_name),
- PyInt_AS_LONG(ste->ste_id), ste->ste_lineno);
- return PyString_FromString(buf);
+ PyOS_snprintf(buf, sizeof(buf),
+ "<symtable entry %.100s(%ld), line %d>",
+ PyString_AS_STRING(ste->ste_name),
+ PyInt_AS_LONG(ste->ste_id), ste->ste_lineno);
+ return PyString_FromString(buf);
}
static void
ste_dealloc(PySTEntryObject *ste)
{
- ste->ste_table = NULL;
- Py_XDECREF(ste->ste_id);
- Py_XDECREF(ste->ste_name);
- Py_XDECREF(ste->ste_symbols);
- Py_XDECREF(ste->ste_varnames);
- Py_XDECREF(ste->ste_children);
- PyObject_Del(ste);
+ ste->ste_table = NULL;
+ Py_XDECREF(ste->ste_id);
+ Py_XDECREF(ste->ste_name);
+ Py_XDECREF(ste->ste_symbols);
+ Py_XDECREF(ste->ste_varnames);
+ Py_XDECREF(ste->ste_children);
+ PyObject_Del(ste);
}
#define OFF(x) offsetof(PySTEntryObject, x)
static PyMemberDef ste_memberlist[] = {
- {"id", T_OBJECT, OFF(ste_id), READONLY},
- {"name", T_OBJECT, OFF(ste_name), READONLY},
- {"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
- {"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
- {"children", T_OBJECT, OFF(ste_children), READONLY},
- {"optimized",T_INT, OFF(ste_unoptimized), READONLY},
- {"nested", T_INT, OFF(ste_nested), READONLY},
- {"type", T_INT, OFF(ste_type), READONLY},
- {"lineno", T_INT, OFF(ste_lineno), READONLY},
- {NULL}
+ {"id", T_OBJECT, OFF(ste_id), READONLY},
+ {"name", T_OBJECT, OFF(ste_name), READONLY},
+ {"symbols", T_OBJECT, OFF(ste_symbols), READONLY},
+ {"varnames", T_OBJECT, OFF(ste_varnames), READONLY},
+ {"children", T_OBJECT, OFF(ste_children), READONLY},
+ {"optimized",T_INT, OFF(ste_unoptimized), READONLY},
+ {"nested", T_INT, OFF(ste_nested), READONLY},
+ {"type", T_INT, OFF(ste_type), READONLY},
+ {"lineno", T_INT, OFF(ste_lineno), READONLY},
+ {NULL}
};
PyTypeObject PySTEntry_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "symtable entry",
- sizeof(PySTEntryObject),
- 0,
- (destructor)ste_dealloc, /* tp_dealloc */
- 0, /* tp_print */
- 0, /* tp_getattr */
- 0, /* tp_setattr */
- 0, /* tp_compare */
- (reprfunc)ste_repr, /* 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 */
- 0, /* tp_doc */
- 0, /* tp_traverse */
- 0, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- ste_memberlist, /* 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 */
- 0, /* tp_new */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "symtable entry",
+ sizeof(PySTEntryObject),
+ 0,
+ (destructor)ste_dealloc, /* tp_dealloc */
+ 0, /* tp_print */
+ 0, /* tp_getattr */
+ 0, /* tp_setattr */
+ 0, /* tp_compare */
+ (reprfunc)ste_repr, /* 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 */
+ 0, /* tp_doc */
+ 0, /* tp_traverse */
+ 0, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ ste_memberlist, /* 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 */
+ 0, /* tp_new */
};
static int symtable_analyze(struct symtable *st);
static int symtable_warn(struct symtable *st, char *msg, int lineno);
-static int symtable_enter_block(struct symtable *st, identifier name,
- _Py_block_ty block, void *ast, int lineno);
+static int symtable_enter_block(struct symtable *st, identifier name,
+ _Py_block_ty block, void *ast, int lineno);
static int symtable_exit_block(struct symtable *st, void *ast);
static int symtable_visit_stmt(struct symtable *st, stmt_ty s);
static int symtable_visit_expr(struct symtable *st, expr_ty s);
@@ -180,10 +180,10 @@ static int symtable_implicit_arg(struct symtable *st, int pos);
static identifier top = NULL, lambda = NULL, genexpr = NULL, setcomp = NULL,
- dictcomp = NULL;
+ dictcomp = NULL;
#define GET_IDENTIFIER(VAR) \
- ((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
+ ((VAR) ? (VAR) : ((VAR) = PyString_InternFromString(# VAR)))
#define DUPLICATE_ARGUMENT \
"duplicate argument '%s' in function definition"
@@ -191,134 +191,134 @@ static identifier top = NULL, lambda = NULL, genexpr = NULL, setcomp = NULL,
static struct symtable *
symtable_new(void)
{
- struct symtable *st;
-
- st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
- if (st == NULL)
- return NULL;
-
- st->st_filename = NULL;
- st->st_symbols = NULL;
-
- if ((st->st_stack = PyList_New(0)) == NULL)
- goto fail;
- if ((st->st_symbols = PyDict_New()) == NULL)
- goto fail;
- st->st_cur = NULL;
- st->st_private = NULL;
- return st;
+ struct symtable *st;
+
+ st = (struct symtable *)PyMem_Malloc(sizeof(struct symtable));
+ if (st == NULL)
+ return NULL;
+
+ st->st_filename = NULL;
+ st->st_symbols = NULL;
+
+ if ((st->st_stack = PyList_New(0)) == NULL)
+ goto fail;
+ if ((st->st_symbols = PyDict_New()) == NULL)
+ goto fail;
+ st->st_cur = NULL;
+ st->st_private = NULL;
+ return st;
fail:
- PySymtable_Free(st);
- return NULL;
+ PySymtable_Free(st);
+ return NULL;
}
struct symtable *
PySymtable_Build(mod_ty mod, const char *filename, PyFutureFeatures *future)
{
- struct symtable *st = symtable_new();
- asdl_seq *seq;
- int i;
-
- if (st == NULL)
- return st;
- st->st_filename = filename;
- st->st_future = future;
- if (!GET_IDENTIFIER(top) ||
- !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) {
- PySymtable_Free(st);
- return NULL;
- }
-
- st->st_top = st->st_cur;
- st->st_cur->ste_unoptimized = OPT_TOPLEVEL;
- /* Any other top-level initialization? */
- switch (mod->kind) {
- case Module_kind:
- seq = mod->v.Module.body;
- for (i = 0; i < asdl_seq_LEN(seq); i++)
- if (!symtable_visit_stmt(st,
- (stmt_ty)asdl_seq_GET(seq, i)))
- goto error;
- break;
- case Expression_kind:
- if (!symtable_visit_expr(st, mod->v.Expression.body))
- goto error;
- break;
- case Interactive_kind:
- seq = mod->v.Interactive.body;
- for (i = 0; i < asdl_seq_LEN(seq); i++)
- if (!symtable_visit_stmt(st,
- (stmt_ty)asdl_seq_GET(seq, i)))
- goto error;
- break;
- case Suite_kind:
- PyErr_SetString(PyExc_RuntimeError,
- "this compiler does not handle Suites");
- goto error;
- }
- if (!symtable_exit_block(st, (void *)mod)) {
- PySymtable_Free(st);
- return NULL;
- }
- if (symtable_analyze(st))
- return st;
- PySymtable_Free(st);
- return NULL;
+ struct symtable *st = symtable_new();
+ asdl_seq *seq;
+ int i;
+
+ if (st == NULL)
+ return st;
+ st->st_filename = filename;
+ st->st_future = future;
+ if (!GET_IDENTIFIER(top) ||
+ !symtable_enter_block(st, top, ModuleBlock, (void *)mod, 0)) {
+ PySymtable_Free(st);
+ return NULL;
+ }
+
+ st->st_top = st->st_cur;
+ st->st_cur->ste_unoptimized = OPT_TOPLEVEL;
+ /* Any other top-level initialization? */
+ switch (mod->kind) {
+ case Module_kind:
+ seq = mod->v.Module.body;
+ for (i = 0; i < asdl_seq_LEN(seq); i++)
+ if (!symtable_visit_stmt(st,
+ (stmt_ty)asdl_seq_GET(seq, i)))
+ goto error;
+ break;
+ case Expression_kind:
+ if (!symtable_visit_expr(st, mod->v.Expression.body))
+ goto error;
+ break;
+ case Interactive_kind:
+ seq = mod->v.Interactive.body;
+ for (i = 0; i < asdl_seq_LEN(seq); i++)
+ if (!symtable_visit_stmt(st,
+ (stmt_ty)asdl_seq_GET(seq, i)))
+ goto error;
+ break;
+ case Suite_kind:
+ PyErr_SetString(PyExc_RuntimeError,
+ "this compiler does not handle Suites");
+ goto error;
+ }
+ if (!symtable_exit_block(st, (void *)mod)) {
+ PySymtable_Free(st);
+ return NULL;
+ }
+ if (symtable_analyze(st))
+ return st;
+ PySymtable_Free(st);
+ return NULL;
error:
- (void) symtable_exit_block(st, (void *)mod);
- PySymtable_Free(st);
- return NULL;
+ (void) symtable_exit_block(st, (void *)mod);
+ PySymtable_Free(st);
+ return NULL;
}
void
PySymtable_Free(struct symtable *st)
{
- Py_XDECREF(st->st_symbols);
- Py_XDECREF(st->st_stack);
- PyMem_Free((void *)st);
+ Py_XDECREF(st->st_symbols);
+ Py_XDECREF(st->st_stack);
+ PyMem_Free((void *)st);
}
PySTEntryObject *
PySymtable_Lookup(struct symtable *st, void *key)
{
- PyObject *k, *v;
-
- k = PyLong_FromVoidPtr(key);
- if (k == NULL)
- return NULL;
- v = PyDict_GetItem(st->st_symbols, k);
- if (v) {
- assert(PySTEntry_Check(v));
- Py_INCREF(v);
- }
- else {
- PyErr_SetString(PyExc_KeyError,
- "unknown symbol table entry");
- }
-
- Py_DECREF(k);
- return (PySTEntryObject *)v;
+ PyObject *k, *v;
+
+ k = PyLong_FromVoidPtr(key);
+ if (k == NULL)
+ return NULL;
+ v = PyDict_GetItem(st->st_symbols, k);
+ if (v) {
+ assert(PySTEntry_Check(v));
+ Py_INCREF(v);
+ }
+ else {
+ PyErr_SetString(PyExc_KeyError,
+ "unknown symbol table entry");
+ }
+
+ Py_DECREF(k);
+ return (PySTEntryObject *)v;
}
-int
+int
PyST_GetScope(PySTEntryObject *ste, PyObject *name)
{
- PyObject *v = PyDict_GetItem(ste->ste_symbols, name);
- if (!v)
- return 0;
- assert(PyInt_Check(v));
- return (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
+ PyObject *v = PyDict_GetItem(ste->ste_symbols, name);
+ if (!v)
+ return 0;
+ assert(PyInt_Check(v));
+ return (PyInt_AS_LONG(v) >> SCOPE_OFF) & SCOPE_MASK;
}
/* Analyze raw symbol information to determine scope of each name.
The next several functions are helpers for PySymtable_Analyze(),
- which determines whether a name is local, global, or free. In addition,
+ which determines whether a name is local, global, or free. In addition,
it determines which local variables are cell variables; they provide
- bindings that are used for free variables in enclosed blocks.
+ bindings that are used for free variables in enclosed blocks.
- There are also two kinds of free variables, implicit and explicit. An
+ There are also two kinds of free variables, implicit and explicit. An
explicit global is declared with the global statement. An implicit
global is a free variable for which the compiler has found no binding
in an enclosing function scope. The implicit global is either a global
@@ -328,35 +328,35 @@ PyST_GetScope(PySTEntryObject *ste, PyObject *name)
is treated as a local.
The symbol table requires two passes to determine the scope of each name.
- The first pass collects raw facts from the AST: the name is a parameter
+ The first pass collects raw facts from the AST: the name is a parameter
here, the name is used by not defined here, etc. The second pass analyzes
these facts during a pass over the PySTEntryObjects created during pass 1.
When a function is entered during the second pass, the parent passes
- the set of all name bindings visible to its children. These bindings
+ the set of all name bindings visible to its children. These bindings
are used to determine if the variable is free or an implicit global.
After doing the local analysis, it analyzes each of its child blocks
- using an updated set of name bindings.
+ using an updated set of name bindings.
- The children update the free variable set. If a local variable is free
- in a child, the variable is marked as a cell. The current function must
- provide runtime storage for the variable that may outlive the function's
+ The children update the free variable set. If a local variable is free
+ in a child, the variable is marked as a cell. The current function must
+ provide runtime storage for the variable that may outlive the function's
frame. Cell variables are removed from the free set before the analyze
function returns to its parent.
-
+
The sets of bound and free variables are implemented as dictionaries
mapping strings to None.
*/
#define SET_SCOPE(DICT, NAME, I) { \
- PyObject *o = PyInt_FromLong(I); \
- if (!o) \
- return 0; \
- if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
- Py_DECREF(o); \
- return 0; \
- } \
- Py_DECREF(o); \
+ PyObject *o = PyInt_FromLong(I); \
+ if (!o) \
+ return 0; \
+ if (PyDict_SetItem((DICT), (NAME), o) < 0) { \
+ Py_DECREF(o); \
+ return 0; \
+ } \
+ Py_DECREF(o); \
}
/* Decide on scope of name, given flags.
@@ -366,69 +366,69 @@ PyST_GetScope(PySTEntryObject *ste, PyObject *name)
global. A name that was global can be changed to local.
*/
-static int
+static int
analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, long flags,
- PyObject *bound, PyObject *local, PyObject *free,
- PyObject *global)
+ PyObject *bound, PyObject *local, PyObject *free,
+ PyObject *global)
{
- if (flags & DEF_GLOBAL) {
- if (flags & DEF_PARAM) {
- PyErr_Format(PyExc_SyntaxError,
- "name '%s' is local and global",
- PyString_AS_STRING(name));
- PyErr_SyntaxLocation(ste->ste_table->st_filename,
- ste->ste_lineno);
-
- return 0;
- }
- SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
- if (PyDict_SetItem(global, name, Py_None) < 0)
- return 0;
- if (bound && PyDict_GetItem(bound, name)) {
- if (PyDict_DelItem(bound, name) < 0)
- return 0;
- }
- return 1;
- }
- if (flags & DEF_BOUND) {
- SET_SCOPE(dict, name, LOCAL);
- if (PyDict_SetItem(local, name, Py_None) < 0)
- return 0;
- if (PyDict_GetItem(global, name)) {
- if (PyDict_DelItem(global, name) < 0)
- return 0;
- }
- return 1;
- }
- /* If an enclosing block has a binding for this name, it
- is a free variable rather than a global variable.
- Note that having a non-NULL bound implies that the block
- is nested.
- */
- if (bound && PyDict_GetItem(bound, name)) {
- SET_SCOPE(dict, name, FREE);
- ste->ste_free = 1;
- if (PyDict_SetItem(free, name, Py_None) < 0)
- return 0;
- return 1;
- }
- /* If a parent has a global statement, then call it global
- explicit? It could also be global implicit.
- */
- else if (global && PyDict_GetItem(global, name)) {
- SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
- return 1;
- }
- else {
- if (ste->ste_nested)
- ste->ste_free = 1;
- SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
- return 1;
- }
- /* Should never get here. */
- PyErr_Format(PyExc_SystemError, "failed to set scope for %s",
- PyString_AS_STRING(name));
- return 0;
+ if (flags & DEF_GLOBAL) {
+ if (flags & DEF_PARAM) {
+ PyErr_Format(PyExc_SyntaxError,
+ "name '%s' is local and global",
+ PyString_AS_STRING(name));
+ PyErr_SyntaxLocation(ste->ste_table->st_filename,
+ ste->ste_lineno);
+
+ return 0;
+ }
+ SET_SCOPE(dict, name, GLOBAL_EXPLICIT);
+ if (PyDict_SetItem(global, name, Py_None) < 0)
+ return 0;
+ if (bound && PyDict_GetItem(bound, name)) {
+ if (PyDict_DelItem(bound, name) < 0)
+ return 0;
+ }
+ return 1;
+ }
+ if (flags & DEF_BOUND) {
+ SET_SCOPE(dict, name, LOCAL);
+ if (PyDict_SetItem(local, name, Py_None) < 0)
+ return 0;
+ if (PyDict_GetItem(global, name)) {
+ if (PyDict_DelItem(global, name) < 0)
+ return 0;
+ }
+ return 1;
+ }
+ /* If an enclosing block has a binding for this name, it
+ is a free variable rather than a global variable.
+ Note that having a non-NULL bound implies that the block
+ is nested.
+ */
+ if (bound && PyDict_GetItem(bound, name)) {
+ SET_SCOPE(dict, name, FREE);
+ ste->ste_free = 1;
+ if (PyDict_SetItem(free, name, Py_None) < 0)
+ return 0;
+ return 1;
+ }
+ /* If a parent has a global statement, then call it global
+ explicit? It could also be global implicit.
+ */
+ else if (global && PyDict_GetItem(global, name)) {
+ SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
+ return 1;
+ }
+ else {
+ if (ste->ste_nested)
+ ste->ste_free = 1;
+ SET_SCOPE(dict, name, GLOBAL_IMPLICIT);
+ return 1;
+ }
+ /* Should never get here. */
+ PyErr_Format(PyExc_SystemError, "failed to set scope for %s",
+ PyString_AS_STRING(name));
+ return 0;
}
#undef SET_SCOPE
@@ -444,152 +444,152 @@ analyze_name(PySTEntryObject *ste, PyObject *dict, PyObject *name, long flags,
static int
analyze_cells(PyObject *scope, PyObject *free)
{
- PyObject *name, *v, *w;
- int success = 0;
- Py_ssize_t pos = 0;
-
- w = PyInt_FromLong(CELL);
- if (!w)
- return 0;
- while (PyDict_Next(scope, &pos, &name, &v)) {
- long flags;
- assert(PyInt_Check(v));
- flags = PyInt_AS_LONG(v);
- if (flags != LOCAL)
- continue;
- if (!PyDict_GetItem(free, name))
- continue;
- /* Replace LOCAL with CELL for this name, and remove
- from free. It is safe to replace the value of name
- in the dict, because it will not cause a resize.
- */
- if (PyDict_SetItem(scope, name, w) < 0)
- goto error;
- if (!PyDict_DelItem(free, name) < 0)
- goto error;
- }
- success = 1;
+ PyObject *name, *v, *w;
+ int success = 0;
+ Py_ssize_t pos = 0;
+
+ w = PyInt_FromLong(CELL);
+ if (!w)
+ return 0;
+ while (PyDict_Next(scope, &pos, &name, &v)) {
+ long flags;
+ assert(PyInt_Check(v));
+ flags = PyInt_AS_LONG(v);
+ if (flags != LOCAL)
+ continue;
+ if (!PyDict_GetItem(free, name))
+ continue;
+ /* Replace LOCAL with CELL for this name, and remove
+ from free. It is safe to replace the value of name
+ in the dict, because it will not cause a resize.
+ */
+ if (PyDict_SetItem(scope, name, w) < 0)
+ goto error;
+ if (!PyDict_DelItem(free, name) < 0)
+ goto error;
+ }
+ success = 1;
error:
- Py_DECREF(w);
- return success;
+ Py_DECREF(w);
+ return success;
}
/* Check for illegal statements in unoptimized namespaces */
static int
check_unoptimized(const PySTEntryObject* ste) {
- char buf[300];
- const char* trailer;
-
- if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized
- || !(ste->ste_free || ste->ste_child_free))
- return 1;
-
- trailer = (ste->ste_child_free ?
- "contains a nested function with free variables" :
- "is a nested function");
-
- switch (ste->ste_unoptimized) {
- case OPT_TOPLEVEL: /* exec / import * at top-level is fine */
- case OPT_EXEC: /* qualified exec is fine */
- return 1;
- case OPT_IMPORT_STAR:
- PyOS_snprintf(buf, sizeof(buf),
- "import * is not allowed in function '%.100s' "
- "because it %s",
- PyString_AS_STRING(ste->ste_name), trailer);
- break;
- case OPT_BARE_EXEC:
- PyOS_snprintf(buf, sizeof(buf),
- "unqualified exec is not allowed in function "
- "'%.100s' it %s",
- PyString_AS_STRING(ste->ste_name), trailer);
- break;
- default:
- PyOS_snprintf(buf, sizeof(buf),
- "function '%.100s' uses import * and bare exec, "
- "which are illegal because it %s",
- PyString_AS_STRING(ste->ste_name), trailer);
- break;
- }
-
- PyErr_SetString(PyExc_SyntaxError, buf);
- PyErr_SyntaxLocation(ste->ste_table->st_filename,
- ste->ste_opt_lineno);
- return 0;
+ char buf[300];
+ const char* trailer;
+
+ if (ste->ste_type != FunctionBlock || !ste->ste_unoptimized
+ || !(ste->ste_free || ste->ste_child_free))
+ return 1;
+
+ trailer = (ste->ste_child_free ?
+ "contains a nested function with free variables" :
+ "is a nested function");
+
+ switch (ste->ste_unoptimized) {
+ case OPT_TOPLEVEL: /* exec / import * at top-level is fine */
+ case OPT_EXEC: /* qualified exec is fine */
+ return 1;
+ case OPT_IMPORT_STAR:
+ PyOS_snprintf(buf, sizeof(buf),
+ "import * is not allowed in function '%.100s' "
+ "because it %s",
+ PyString_AS_STRING(ste->ste_name), trailer);
+ break;
+ case OPT_BARE_EXEC:
+ PyOS_snprintf(buf, sizeof(buf),
+ "unqualified exec is not allowed in function "
+ "'%.100s' it %s",
+ PyString_AS_STRING(ste->ste_name), trailer);
+ break;
+ default:
+ PyOS_snprintf(buf, sizeof(buf),
+ "function '%.100s' uses import * and bare exec, "
+ "which are illegal because it %s",
+ PyString_AS_STRING(ste->ste_name), trailer);
+ break;
+ }
+
+ PyErr_SetString(PyExc_SyntaxError, buf);
+ PyErr_SyntaxLocation(ste->ste_table->st_filename,
+ ste->ste_opt_lineno);
+ return 0;
}
-/* Enter the final scope information into the st_symbols dict.
- *
+/* Enter the final scope information into the st_symbols dict.
+ *
* All arguments are dicts. Modifies symbols, others are read-only.
*/
static int
-update_symbols(PyObject *symbols, PyObject *scope,
+update_symbols(PyObject *symbols, PyObject *scope,
PyObject *bound, PyObject *free, int classflag)
{
- PyObject *name, *v, *u, *w, *free_value = NULL;
- Py_ssize_t pos = 0;
-
- while (PyDict_Next(symbols, &pos, &name, &v)) {
- long i, flags;
- assert(PyInt_Check(v));
- flags = PyInt_AS_LONG(v);
- w = PyDict_GetItem(scope, name);
- assert(w && PyInt_Check(w));
- i = PyInt_AS_LONG(w);
- flags |= (i << SCOPE_OFF);
- u = PyInt_FromLong(flags);
- if (!u)
- return 0;
- if (PyDict_SetItem(symbols, name, u) < 0) {
- Py_DECREF(u);
- return 0;
- }
- Py_DECREF(u);
- }
-
- free_value = PyInt_FromLong(FREE << SCOPE_OFF);
- if (!free_value)
- return 0;
-
- /* add a free variable when it's only use is for creating a closure */
- pos = 0;
- while (PyDict_Next(free, &pos, &name, &v)) {
- PyObject *o = PyDict_GetItem(symbols, name);
-
- if (o) {
- /* It could be a free variable in a method of
- the class that has the same name as a local
- or global in the class scope.
- */
- if (classflag &&
- PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
- long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
- o = PyInt_FromLong(i);
- if (!o) {
- Py_DECREF(free_value);
- return 0;
- }
- if (PyDict_SetItem(symbols, name, o) < 0) {
- Py_DECREF(o);
- Py_DECREF(free_value);
- return 0;
- }
- Py_DECREF(o);
- }
- /* else it's not free, probably a cell */
- continue;
- }
- if (!PyDict_GetItem(bound, name))
- continue; /* it's a global */
-
- if (PyDict_SetItem(symbols, name, free_value) < 0) {
- Py_DECREF(free_value);
- return 0;
- }
+ PyObject *name, *v, *u, *w, *free_value = NULL;
+ Py_ssize_t pos = 0;
+
+ while (PyDict_Next(symbols, &pos, &name, &v)) {
+ long i, flags;
+ assert(PyInt_Check(v));
+ flags = PyInt_AS_LONG(v);
+ w = PyDict_GetItem(scope, name);
+ assert(w && PyInt_Check(w));
+ i = PyInt_AS_LONG(w);
+ flags |= (i << SCOPE_OFF);
+ u = PyInt_FromLong(flags);
+ if (!u)
+ return 0;
+ if (PyDict_SetItem(symbols, name, u) < 0) {
+ Py_DECREF(u);
+ return 0;
+ }
+ Py_DECREF(u);
+ }
+
+ free_value = PyInt_FromLong(FREE << SCOPE_OFF);
+ if (!free_value)
+ return 0;
+
+ /* add a free variable when it's only use is for creating a closure */
+ pos = 0;
+ while (PyDict_Next(free, &pos, &name, &v)) {
+ PyObject *o = PyDict_GetItem(symbols, name);
+
+ if (o) {
+ /* It could be a free variable in a method of
+ the class that has the same name as a local
+ or global in the class scope.
+ */
+ if (classflag &&
+ PyInt_AS_LONG(o) & (DEF_BOUND | DEF_GLOBAL)) {
+ long i = PyInt_AS_LONG(o) | DEF_FREE_CLASS;
+ o = PyInt_FromLong(i);
+ if (!o) {
+ Py_DECREF(free_value);
+ return 0;
+ }
+ if (PyDict_SetItem(symbols, name, o) < 0) {
+ Py_DECREF(o);
+ Py_DECREF(free_value);
+ return 0;
+ }
+ Py_DECREF(o);
+ }
+ /* else it's not free, probably a cell */
+ continue;
}
- Py_DECREF(free_value);
- return 1;
-}
+ if (!PyDict_GetItem(bound, name))
+ continue; /* it's a global */
+
+ if (PyDict_SetItem(symbols, name, free_value) < 0) {
+ Py_DECREF(free_value);
+ return 0;
+ }
+ }
+ Py_DECREF(free_value);
+ return 1;
+}
/* Make final symbol table decisions for block of ste.
@@ -612,199 +612,199 @@ update_symbols(PyObject *symbols, PyObject *scope,
*/
static int
-analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
- PyObject *global, PyObject* child_free);
+analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
+ PyObject *global, PyObject* child_free);
static int
-analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
- PyObject *global)
+analyze_block(PySTEntryObject *ste, PyObject *bound, PyObject *free,
+ PyObject *global)
{
- PyObject *name, *v, *local = NULL, *scope = NULL;
- PyObject *newbound = NULL, *newglobal = NULL;
- PyObject *newfree = NULL, *allfree = NULL;
- int i, success = 0;
- Py_ssize_t pos = 0;
-
- local = PyDict_New(); /* collect new names bound in block */
- if (!local)
- goto error;
- scope = PyDict_New(); /* collect scopes defined for each name */
- if (!scope)
- goto error;
-
- /* Allocate new global and bound variable dictionaries. These
- dictionaries hold the names visible in nested blocks. For
- ClassBlocks, the bound and global names are initialized
- before analyzing names, because class bindings aren't
- visible in methods. For other blocks, they are initialized
- after names are analyzed.
- */
-
- /* TODO(jhylton): Package these dicts in a struct so that we
- can write reasonable helper functions?
- */
- newglobal = PyDict_New();
- if (!newglobal)
- goto error;
- newbound = PyDict_New();
- if (!newbound)
- goto error;
- newfree = PyDict_New();
- if (!newfree)
- goto error;
-
- if (ste->ste_type == ClassBlock) {
- if (PyDict_Update(newglobal, global) < 0)
- goto error;
- if (bound)
- if (PyDict_Update(newbound, bound) < 0)
- goto error;
- }
-
- while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
- long flags = PyInt_AS_LONG(v);
- if (!analyze_name(ste, scope, name, flags,
- bound, local, free, global))
- goto error;
- }
-
- if (ste->ste_type != ClassBlock) {
- if (ste->ste_type == FunctionBlock) {
- if (PyDict_Update(newbound, local) < 0)
- goto error;
- }
- if (bound) {
- if (PyDict_Update(newbound, bound) < 0)
- goto error;
- }
- if (PyDict_Update(newglobal, global) < 0)
- goto error;
- }
-
- /* Recursively call analyze_block() on each child block.
-
- newbound, newglobal now contain the names visible in
- nested blocks. The free variables in the children will
- be collected in allfree.
- */
- allfree = PyDict_New();
- if (!allfree)
- goto error;
- for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
- PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
- PySTEntryObject* entry;
- assert(c && PySTEntry_Check(c));
- entry = (PySTEntryObject*)c;
- if (!analyze_child_block(entry, newbound, newfree, newglobal,
- allfree))
- goto error;
- if (entry->ste_free || entry->ste_child_free)
- ste->ste_child_free = 1;
- }
-
- if (PyDict_Update(newfree, allfree) < 0)
- goto error;
- if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
- goto error;
- if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
- ste->ste_type == ClassBlock))
- goto error;
- if (!check_unoptimized(ste))
- goto error;
-
- if (PyDict_Update(free, newfree) < 0)
- goto error;
- success = 1;
+ PyObject *name, *v, *local = NULL, *scope = NULL;
+ PyObject *newbound = NULL, *newglobal = NULL;
+ PyObject *newfree = NULL, *allfree = NULL;
+ int i, success = 0;
+ Py_ssize_t pos = 0;
+
+ local = PyDict_New(); /* collect new names bound in block */
+ if (!local)
+ goto error;
+ scope = PyDict_New(); /* collect scopes defined for each name */
+ if (!scope)
+ goto error;
+
+ /* Allocate new global and bound variable dictionaries. These
+ dictionaries hold the names visible in nested blocks. For
+ ClassBlocks, the bound and global names are initialized
+ before analyzing names, because class bindings aren't
+ visible in methods. For other blocks, they are initialized
+ after names are analyzed.
+ */
+
+ /* TODO(jhylton): Package these dicts in a struct so that we
+ can write reasonable helper functions?
+ */
+ newglobal = PyDict_New();
+ if (!newglobal)
+ goto error;
+ newbound = PyDict_New();
+ if (!newbound)
+ goto error;
+ newfree = PyDict_New();
+ if (!newfree)
+ goto error;
+
+ if (ste->ste_type == ClassBlock) {
+ if (PyDict_Update(newglobal, global) < 0)
+ goto error;
+ if (bound)
+ if (PyDict_Update(newbound, bound) < 0)
+ goto error;
+ }
+
+ while (PyDict_Next(ste->ste_symbols, &pos, &name, &v)) {
+ long flags = PyInt_AS_LONG(v);
+ if (!analyze_name(ste, scope, name, flags,
+ bound, local, free, global))
+ goto error;
+ }
+
+ if (ste->ste_type != ClassBlock) {
+ if (ste->ste_type == FunctionBlock) {
+ if (PyDict_Update(newbound, local) < 0)
+ goto error;
+ }
+ if (bound) {
+ if (PyDict_Update(newbound, bound) < 0)
+ goto error;
+ }
+ if (PyDict_Update(newglobal, global) < 0)
+ goto error;
+ }
+
+ /* Recursively call analyze_block() on each child block.
+
+ newbound, newglobal now contain the names visible in
+ nested blocks. The free variables in the children will
+ be collected in allfree.
+ */
+ allfree = PyDict_New();
+ if (!allfree)
+ goto error;
+ for (i = 0; i < PyList_GET_SIZE(ste->ste_children); ++i) {
+ PyObject *c = PyList_GET_ITEM(ste->ste_children, i);
+ PySTEntryObject* entry;
+ assert(c && PySTEntry_Check(c));
+ entry = (PySTEntryObject*)c;
+ if (!analyze_child_block(entry, newbound, newfree, newglobal,
+ allfree))
+ goto error;
+ if (entry->ste_free || entry->ste_child_free)
+ ste->ste_child_free = 1;
+ }
+
+ if (PyDict_Update(newfree, allfree) < 0)
+ goto error;
+ if (ste->ste_type == FunctionBlock && !analyze_cells(scope, newfree))
+ goto error;
+ if (!update_symbols(ste->ste_symbols, scope, bound, newfree,
+ ste->ste_type == ClassBlock))
+ goto error;
+ if (!check_unoptimized(ste))
+ goto error;
+
+ if (PyDict_Update(free, newfree) < 0)
+ goto error;
+ success = 1;
error:
- Py_XDECREF(local);
- Py_XDECREF(scope);
- Py_XDECREF(newbound);
- Py_XDECREF(newglobal);
- Py_XDECREF(newfree);
- Py_XDECREF(allfree);
- if (!success)
- assert(PyErr_Occurred());
- return success;
+ Py_XDECREF(local);
+ Py_XDECREF(scope);
+ Py_XDECREF(newbound);
+ Py_XDECREF(newglobal);
+ Py_XDECREF(newfree);
+ Py_XDECREF(allfree);
+ if (!success)
+ assert(PyErr_Occurred());
+ return success;
}
static int
-analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
- PyObject *global, PyObject* child_free)
+analyze_child_block(PySTEntryObject *entry, PyObject *bound, PyObject *free,
+ PyObject *global, PyObject* child_free)
{
- PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
-
- /* Copy the bound and global dictionaries.
-
- These dictionary are used by all blocks enclosed by the
- current block. The analyze_block() call modifies these
- dictionaries.
-
- */
- temp_bound = PyDict_New();
- if (!temp_bound)
- goto error;
- if (PyDict_Update(temp_bound, bound) < 0)
- goto error;
- temp_free = PyDict_New();
- if (!temp_free)
- goto error;
- if (PyDict_Update(temp_free, free) < 0)
- goto error;
- temp_global = PyDict_New();
- if (!temp_global)
- goto error;
- if (PyDict_Update(temp_global, global) < 0)
- goto error;
-
- if (!analyze_block(entry, temp_bound, temp_free, temp_global))
- goto error;
- if (PyDict_Update(child_free, temp_free) < 0)
- goto error;
- Py_DECREF(temp_bound);
- Py_DECREF(temp_free);
- Py_DECREF(temp_global);
- return 1;
+ PyObject *temp_bound = NULL, *temp_global = NULL, *temp_free = NULL;
+
+ /* Copy the bound and global dictionaries.
+
+ These dictionary are used by all blocks enclosed by the
+ current block. The analyze_block() call modifies these
+ dictionaries.
+
+ */
+ temp_bound = PyDict_New();
+ if (!temp_bound)
+ goto error;
+ if (PyDict_Update(temp_bound, bound) < 0)
+ goto error;
+ temp_free = PyDict_New();
+ if (!temp_free)
+ goto error;
+ if (PyDict_Update(temp_free, free) < 0)
+ goto error;
+ temp_global = PyDict_New();
+ if (!temp_global)
+ goto error;
+ if (PyDict_Update(temp_global, global) < 0)
+ goto error;
+
+ if (!analyze_block(entry, temp_bound, temp_free, temp_global))
+ goto error;
+ if (PyDict_Update(child_free, temp_free) < 0)
+ goto error;
+ Py_DECREF(temp_bound);
+ Py_DECREF(temp_free);
+ Py_DECREF(temp_global);
+ return 1;
error:
- Py_XDECREF(temp_bound);
- Py_XDECREF(temp_free);
- Py_XDECREF(temp_global);
- return 0;
+ Py_XDECREF(temp_bound);
+ Py_XDECREF(temp_free);
+ Py_XDECREF(temp_global);
+ return 0;
}
static int
symtable_analyze(struct symtable *st)
{
- PyObject *free, *global;
- int r;
-
- free = PyDict_New();
- if (!free)
- return 0;
- global = PyDict_New();
- if (!global) {
- Py_DECREF(free);
- return 0;
- }
- r = analyze_block(st->st_top, NULL, free, global);
- Py_DECREF(free);
- Py_DECREF(global);
- return r;
+ PyObject *free, *global;
+ int r;
+
+ free = PyDict_New();
+ if (!free)
+ return 0;
+ global = PyDict_New();
+ if (!global) {
+ Py_DECREF(free);
+ return 0;
+ }
+ r = analyze_block(st->st_top, NULL, free, global);
+ Py_DECREF(free);
+ Py_DECREF(global);
+ return r;
}
static int
symtable_warn(struct symtable *st, char *msg, int lineno)
{
- if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename,
- lineno, NULL, NULL) < 0) {
- if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
- PyErr_SetString(PyExc_SyntaxError, msg);
- PyErr_SyntaxLocation(st->st_filename,
- st->st_cur->ste_lineno);
- }
- return 0;
- }
- return 1;
+ if (PyErr_WarnExplicit(PyExc_SyntaxWarning, msg, st->st_filename,
+ lineno, NULL, NULL) < 0) {
+ if (PyErr_ExceptionMatches(PyExc_SyntaxWarning)) {
+ PyErr_SetString(PyExc_SyntaxError, msg);
+ PyErr_SyntaxLocation(st->st_filename,
+ st->st_cur->ste_lineno);
+ }
+ return 0;
+ }
+ return 1;
}
/* symtable_enter_block() gets a reference via ste_new.
@@ -815,739 +815,739 @@ symtable_warn(struct symtable *st, char *msg, int lineno)
static int
symtable_exit_block(struct symtable *st, void *ast)
{
- Py_ssize_t end;
-
- Py_CLEAR(st->st_cur);
- end = PyList_GET_SIZE(st->st_stack) - 1;
- if (end >= 0) {
- st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
- end);
- if (st->st_cur == NULL)
- return 0;
- Py_INCREF(st->st_cur);
- if (PySequence_DelItem(st->st_stack, end) < 0)
- return 0;
- }
- return 1;
+ Py_ssize_t end;
+
+ Py_CLEAR(st->st_cur);
+ end = PyList_GET_SIZE(st->st_stack) - 1;
+ if (end >= 0) {
+ st->st_cur = (PySTEntryObject *)PyList_GET_ITEM(st->st_stack,
+ end);
+ if (st->st_cur == NULL)
+ return 0;
+ Py_INCREF(st->st_cur);
+ if (PySequence_DelItem(st->st_stack, end) < 0)
+ return 0;
+ }
+ return 1;
}
static int
-symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
- void *ast, int lineno)
+symtable_enter_block(struct symtable *st, identifier name, _Py_block_ty block,
+ void *ast, int lineno)
{
- PySTEntryObject *prev = NULL;
-
- if (st->st_cur) {
- prev = st->st_cur;
- if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) {
- return 0;
- }
- Py_DECREF(st->st_cur);
- }
- st->st_cur = ste_new(st, name, block, ast, lineno);
- if (st->st_cur == NULL)
- return 0;
- if (name == GET_IDENTIFIER(top))
- st->st_global = st->st_cur->ste_symbols;
- if (prev) {
- if (PyList_Append(prev->ste_children,
- (PyObject *)st->st_cur) < 0) {
- return 0;
- }
- }
- return 1;
+ PySTEntryObject *prev = NULL;
+
+ if (st->st_cur) {
+ prev = st->st_cur;
+ if (PyList_Append(st->st_stack, (PyObject *)st->st_cur) < 0) {
+ return 0;
+ }
+ Py_DECREF(st->st_cur);
+ }
+ st->st_cur = ste_new(st, name, block, ast, lineno);
+ if (st->st_cur == NULL)
+ return 0;
+ if (name == GET_IDENTIFIER(top))
+ st->st_global = st->st_cur->ste_symbols;
+ if (prev) {
+ if (PyList_Append(prev->ste_children,
+ (PyObject *)st->st_cur) < 0) {
+ return 0;
+ }
+ }
+ return 1;
}
static long
symtable_lookup(struct symtable *st, PyObject *name)
{
- PyObject *o;
- PyObject *mangled = _Py_Mangle(st->st_private, name);
- if (!mangled)
- return 0;
- o = PyDict_GetItem(st->st_cur->ste_symbols, mangled);
- Py_DECREF(mangled);
- if (!o)
- return 0;
- return PyInt_AsLong(o);
+ PyObject *o;
+ PyObject *mangled = _Py_Mangle(st->st_private, name);
+ if (!mangled)
+ return 0;
+ o = PyDict_GetItem(st->st_cur->ste_symbols, mangled);
+ Py_DECREF(mangled);
+ if (!o)
+ return 0;
+ return PyInt_AsLong(o);
}
static int
-symtable_add_def(struct symtable *st, PyObject *name, int flag)
+symtable_add_def(struct symtable *st, PyObject *name, int flag)
{
- PyObject *o;
- PyObject *dict;
- long val;
- PyObject *mangled = _Py_Mangle(st->st_private, name);
-
- if (!mangled)
- return 0;
- dict = st->st_cur->ste_symbols;
- if ((o = PyDict_GetItem(dict, mangled))) {
- val = PyInt_AS_LONG(o);
- if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
- /* Is it better to use 'mangled' or 'name' here? */
- PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
- PyString_AsString(name));
- PyErr_SyntaxLocation(st->st_filename,
- st->st_cur->ste_lineno);
- goto error;
- }
- val |= flag;
- } else
- val = flag;
- o = PyInt_FromLong(val);
+ PyObject *o;
+ PyObject *dict;
+ long val;
+ PyObject *mangled = _Py_Mangle(st->st_private, name);
+
+ if (!mangled)
+ return 0;
+ dict = st->st_cur->ste_symbols;
+ if ((o = PyDict_GetItem(dict, mangled))) {
+ val = PyInt_AS_LONG(o);
+ if ((flag & DEF_PARAM) && (val & DEF_PARAM)) {
+ /* Is it better to use 'mangled' or 'name' here? */
+ PyErr_Format(PyExc_SyntaxError, DUPLICATE_ARGUMENT,
+ PyString_AsString(name));
+ PyErr_SyntaxLocation(st->st_filename,
+ st->st_cur->ste_lineno);
+ goto error;
+ }
+ val |= flag;
+ } else
+ val = flag;
+ o = PyInt_FromLong(val);
+ if (o == NULL)
+ goto error;
+ if (PyDict_SetItem(dict, mangled, o) < 0) {
+ Py_DECREF(o);
+ goto error;
+ }
+ Py_DECREF(o);
+
+ if (flag & DEF_PARAM) {
+ if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0)
+ goto error;
+ } else if (flag & DEF_GLOBAL) {
+ /* XXX need to update DEF_GLOBAL for other flags too;
+ perhaps only DEF_FREE_GLOBAL */
+ val = flag;
+ if ((o = PyDict_GetItem(st->st_global, mangled))) {
+ val |= PyInt_AS_LONG(o);
+ }
+ o = PyInt_FromLong(val);
if (o == NULL)
- goto error;
- if (PyDict_SetItem(dict, mangled, o) < 0) {
- Py_DECREF(o);
- goto error;
- }
- Py_DECREF(o);
-
- if (flag & DEF_PARAM) {
- if (PyList_Append(st->st_cur->ste_varnames, mangled) < 0)
- goto error;
- } else if (flag & DEF_GLOBAL) {
- /* XXX need to update DEF_GLOBAL for other flags too;
- perhaps only DEF_FREE_GLOBAL */
- val = flag;
- if ((o = PyDict_GetItem(st->st_global, mangled))) {
- val |= PyInt_AS_LONG(o);
- }
- o = PyInt_FromLong(val);
- if (o == NULL)
- goto error;
- if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
- Py_DECREF(o);
- goto error;
- }
- Py_DECREF(o);
- }
- Py_DECREF(mangled);
- return 1;
+ goto error;
+ if (PyDict_SetItem(st->st_global, mangled, o) < 0) {
+ Py_DECREF(o);
+ goto error;
+ }
+ Py_DECREF(o);
+ }
+ Py_DECREF(mangled);
+ return 1;
error:
- Py_DECREF(mangled);
- return 0;
+ Py_DECREF(mangled);
+ return 0;
}
/* VISIT, VISIT_SEQ and VIST_SEQ_TAIL take an ASDL type as their second argument.
They use the ASDL name to synthesize the name of the C type and the visit
- function.
-
+ function.
+
VISIT_SEQ_TAIL permits the start of an ASDL sequence to be skipped, which is
useful if the first node in the sequence requires special treatment.
*/
#define VISIT(ST, TYPE, V) \
- if (!symtable_visit_ ## TYPE((ST), (V))) \
- return 0;
+ if (!symtable_visit_ ## TYPE((ST), (V))) \
+ return 0;
#define VISIT_IN_BLOCK(ST, TYPE, V, S) \
- if (!symtable_visit_ ## TYPE((ST), (V))) { \
- symtable_exit_block((ST), (S)); \
- return 0; \
- }
+ if (!symtable_visit_ ## TYPE((ST), (V))) { \
+ symtable_exit_block((ST), (S)); \
+ return 0; \
+ }
#define VISIT_SEQ(ST, TYPE, SEQ) { \
- int i; \
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \
- for (i = 0; i < asdl_seq_LEN(seq); i++) { \
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
- if (!symtable_visit_ ## TYPE((ST), elt)) \
- return 0; \
- } \
+ int i; \
+ asdl_seq *seq = (SEQ); /* avoid variable capture */ \
+ for (i = 0; i < asdl_seq_LEN(seq); i++) { \
+ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
+ if (!symtable_visit_ ## TYPE((ST), elt)) \
+ return 0; \
+ } \
}
#define VISIT_SEQ_IN_BLOCK(ST, TYPE, SEQ, S) { \
- int i; \
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \
- for (i = 0; i < asdl_seq_LEN(seq); i++) { \
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
- if (!symtable_visit_ ## TYPE((ST), elt)) { \
- symtable_exit_block((ST), (S)); \
- return 0; \
- } \
- } \
+ int i; \
+ asdl_seq *seq = (SEQ); /* avoid variable capture */ \
+ for (i = 0; i < asdl_seq_LEN(seq); i++) { \
+ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
+ if (!symtable_visit_ ## TYPE((ST), elt)) { \
+ symtable_exit_block((ST), (S)); \
+ return 0; \
+ } \
+ } \
}
#define VISIT_SEQ_TAIL(ST, TYPE, SEQ, START) { \
- int i; \
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \
- for (i = (START); i < asdl_seq_LEN(seq); i++) { \
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
- if (!symtable_visit_ ## TYPE((ST), elt)) \
- return 0; \
- } \
+ int i; \
+ asdl_seq *seq = (SEQ); /* avoid variable capture */ \
+ for (i = (START); i < asdl_seq_LEN(seq); i++) { \
+ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
+ if (!symtable_visit_ ## TYPE((ST), elt)) \
+ return 0; \
+ } \
}
#define VISIT_SEQ_TAIL_IN_BLOCK(ST, TYPE, SEQ, START, S) { \
- int i; \
- asdl_seq *seq = (SEQ); /* avoid variable capture */ \
- for (i = (START); i < asdl_seq_LEN(seq); i++) { \
- TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
- if (!symtable_visit_ ## TYPE((ST), elt)) { \
- symtable_exit_block((ST), (S)); \
- return 0; \
- } \
- } \
+ int i; \
+ asdl_seq *seq = (SEQ); /* avoid variable capture */ \
+ for (i = (START); i < asdl_seq_LEN(seq); i++) { \
+ TYPE ## _ty elt = (TYPE ## _ty)asdl_seq_GET(seq, i); \
+ if (!symtable_visit_ ## TYPE((ST), elt)) { \
+ symtable_exit_block((ST), (S)); \
+ return 0; \
+ } \
+ } \
}
static int
symtable_visit_stmt(struct symtable *st, stmt_ty s)
{
- switch (s->kind) {
- case FunctionDef_kind:
- if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL))
- return 0;
- if (s->v.FunctionDef.args->defaults)
- VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
- if (s->v.FunctionDef.decorator_list)
- VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
- if (!symtable_enter_block(st, s->v.FunctionDef.name,
- FunctionBlock, (void *)s, s->lineno))
- return 0;
- VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s);
- VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s);
- if (!symtable_exit_block(st, s))
- return 0;
- break;
- case ClassDef_kind: {
- PyObject *tmp;
- if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL))
- return 0;
- VISIT_SEQ(st, expr, s->v.ClassDef.bases);
- if (s->v.ClassDef.decorator_list)
- VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
- if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
- (void *)s, s->lineno))
- return 0;
- tmp = st->st_private;
- st->st_private = s->v.ClassDef.name;
- VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s);
- st->st_private = tmp;
- if (!symtable_exit_block(st, s))
- return 0;
- break;
- }
- case Return_kind:
- if (s->v.Return.value) {
- VISIT(st, expr, s->v.Return.value);
- st->st_cur->ste_returns_value = 1;
- if (st->st_cur->ste_generator) {
- PyErr_SetString(PyExc_SyntaxError,
- RETURN_VAL_IN_GENERATOR);
- PyErr_SyntaxLocation(st->st_filename,
- s->lineno);
- return 0;
- }
- }
- break;
- case Delete_kind:
- VISIT_SEQ(st, expr, s->v.Delete.targets);
- break;
- case Assign_kind:
- VISIT_SEQ(st, expr, s->v.Assign.targets);
- VISIT(st, expr, s->v.Assign.value);
- break;
- case AugAssign_kind:
- VISIT(st, expr, s->v.AugAssign.target);
- VISIT(st, expr, s->v.AugAssign.value);
- break;
- case Print_kind:
- if (s->v.Print.dest)
- VISIT(st, expr, s->v.Print.dest);
- VISIT_SEQ(st, expr, s->v.Print.values);
- break;
- case For_kind:
- VISIT(st, expr, s->v.For.target);
- VISIT(st, expr, s->v.For.iter);
- VISIT_SEQ(st, stmt, s->v.For.body);
- if (s->v.For.orelse)
- VISIT_SEQ(st, stmt, s->v.For.orelse);
- break;
- case While_kind:
- VISIT(st, expr, s->v.While.test);
- VISIT_SEQ(st, stmt, s->v.While.body);
- if (s->v.While.orelse)
- VISIT_SEQ(st, stmt, s->v.While.orelse);
- break;
- case If_kind:
- /* XXX if 0: and lookup_yield() hacks */
- VISIT(st, expr, s->v.If.test);
- VISIT_SEQ(st, stmt, s->v.If.body);
- if (s->v.If.orelse)
- VISIT_SEQ(st, stmt, s->v.If.orelse);
- break;
- case Raise_kind:
- if (s->v.Raise.type) {
- VISIT(st, expr, s->v.Raise.type);
- if (s->v.Raise.inst) {
- VISIT(st, expr, s->v.Raise.inst);
- if (s->v.Raise.tback)
- VISIT(st, expr, s->v.Raise.tback);
- }
- }
- break;
- case TryExcept_kind:
- VISIT_SEQ(st, stmt, s->v.TryExcept.body);
- VISIT_SEQ(st, stmt, s->v.TryExcept.orelse);
- VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers);
- break;
- case TryFinally_kind:
- VISIT_SEQ(st, stmt, s->v.TryFinally.body);
- VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody);
- break;
- case Assert_kind:
- VISIT(st, expr, s->v.Assert.test);
- if (s->v.Assert.msg)
- VISIT(st, expr, s->v.Assert.msg);
- break;
- case Import_kind:
- VISIT_SEQ(st, alias, s->v.Import.names);
- /* XXX Don't have the lineno available inside
- visit_alias */
- if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
- st->st_cur->ste_opt_lineno = s->lineno;
- break;
- case ImportFrom_kind:
- VISIT_SEQ(st, alias, s->v.ImportFrom.names);
- /* XXX Don't have the lineno available inside
- visit_alias */
- if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
- st->st_cur->ste_opt_lineno = s->lineno;
- break;
- case Exec_kind:
- VISIT(st, expr, s->v.Exec.body);
- if (!st->st_cur->ste_opt_lineno)
- st->st_cur->ste_opt_lineno = s->lineno;
- if (s->v.Exec.globals) {
- st->st_cur->ste_unoptimized |= OPT_EXEC;
- VISIT(st, expr, s->v.Exec.globals);
- if (s->v.Exec.locals)
- VISIT(st, expr, s->v.Exec.locals);
- } else {
- st->st_cur->ste_unoptimized |= OPT_BARE_EXEC;
- }
- break;
- case Global_kind: {
- int i;
- asdl_seq *seq = s->v.Global.names;
- for (i = 0; i < asdl_seq_LEN(seq); i++) {
- identifier name = (identifier)asdl_seq_GET(seq, i);
- char *c_name = PyString_AS_STRING(name);
- long cur = symtable_lookup(st, name);
- if (cur < 0)
- return 0;
- if (cur & (DEF_LOCAL | USE)) {
- char buf[256];
- if (cur & DEF_LOCAL)
- PyOS_snprintf(buf, sizeof(buf),
- GLOBAL_AFTER_ASSIGN,
- c_name);
- else
- PyOS_snprintf(buf, sizeof(buf),
- GLOBAL_AFTER_USE,
- c_name);
- if (!symtable_warn(st, buf, s->lineno))
- return 0;
- }
- if (!symtable_add_def(st, name, DEF_GLOBAL))
- return 0;
- }
- break;
- }
- case Expr_kind:
- VISIT(st, expr, s->v.Expr.value);
- break;
- case Pass_kind:
- case Break_kind:
- case Continue_kind:
- /* nothing to do here */
- break;
- case With_kind:
- VISIT(st, expr, s->v.With.context_expr);
- if (s->v.With.optional_vars) {
- VISIT(st, expr, s->v.With.optional_vars);
- }
- VISIT_SEQ(st, stmt, s->v.With.body);
- break;
- }
- return 1;
+ switch (s->kind) {
+ case FunctionDef_kind:
+ if (!symtable_add_def(st, s->v.FunctionDef.name, DEF_LOCAL))
+ return 0;
+ if (s->v.FunctionDef.args->defaults)
+ VISIT_SEQ(st, expr, s->v.FunctionDef.args->defaults);
+ if (s->v.FunctionDef.decorator_list)
+ VISIT_SEQ(st, expr, s->v.FunctionDef.decorator_list);
+ if (!symtable_enter_block(st, s->v.FunctionDef.name,
+ FunctionBlock, (void *)s, s->lineno))
+ return 0;
+ VISIT_IN_BLOCK(st, arguments, s->v.FunctionDef.args, s);
+ VISIT_SEQ_IN_BLOCK(st, stmt, s->v.FunctionDef.body, s);
+ if (!symtable_exit_block(st, s))
+ return 0;
+ break;
+ case ClassDef_kind: {
+ PyObject *tmp;
+ if (!symtable_add_def(st, s->v.ClassDef.name, DEF_LOCAL))
+ return 0;
+ VISIT_SEQ(st, expr, s->v.ClassDef.bases);
+ if (s->v.ClassDef.decorator_list)
+ VISIT_SEQ(st, expr, s->v.ClassDef.decorator_list);
+ if (!symtable_enter_block(st, s->v.ClassDef.name, ClassBlock,
+ (void *)s, s->lineno))
+ return 0;
+ tmp = st->st_private;
+ st->st_private = s->v.ClassDef.name;
+ VISIT_SEQ_IN_BLOCK(st, stmt, s->v.ClassDef.body, s);
+ st->st_private = tmp;
+ if (!symtable_exit_block(st, s))
+ return 0;
+ break;
+ }
+ case Return_kind:
+ if (s->v.Return.value) {
+ VISIT(st, expr, s->v.Return.value);
+ st->st_cur->ste_returns_value = 1;
+ if (st->st_cur->ste_generator) {
+ PyErr_SetString(PyExc_SyntaxError,
+ RETURN_VAL_IN_GENERATOR);
+ PyErr_SyntaxLocation(st->st_filename,
+ s->lineno);
+ return 0;
+ }
+ }
+ break;
+ case Delete_kind:
+ VISIT_SEQ(st, expr, s->v.Delete.targets);
+ break;
+ case Assign_kind:
+ VISIT_SEQ(st, expr, s->v.Assign.targets);
+ VISIT(st, expr, s->v.Assign.value);
+ break;
+ case AugAssign_kind:
+ VISIT(st, expr, s->v.AugAssign.target);
+ VISIT(st, expr, s->v.AugAssign.value);
+ break;
+ case Print_kind:
+ if (s->v.Print.dest)
+ VISIT(st, expr, s->v.Print.dest);
+ VISIT_SEQ(st, expr, s->v.Print.values);
+ break;
+ case For_kind:
+ VISIT(st, expr, s->v.For.target);
+ VISIT(st, expr, s->v.For.iter);
+ VISIT_SEQ(st, stmt, s->v.For.body);
+ if (s->v.For.orelse)
+ VISIT_SEQ(st, stmt, s->v.For.orelse);
+ break;
+ case While_kind:
+ VISIT(st, expr, s->v.While.test);
+ VISIT_SEQ(st, stmt, s->v.While.body);
+ if (s->v.While.orelse)
+ VISIT_SEQ(st, stmt, s->v.While.orelse);
+ break;
+ case If_kind:
+ /* XXX if 0: and lookup_yield() hacks */
+ VISIT(st, expr, s->v.If.test);
+ VISIT_SEQ(st, stmt, s->v.If.body);
+ if (s->v.If.orelse)
+ VISIT_SEQ(st, stmt, s->v.If.orelse);
+ break;
+ case Raise_kind:
+ if (s->v.Raise.type) {
+ VISIT(st, expr, s->v.Raise.type);
+ if (s->v.Raise.inst) {
+ VISIT(st, expr, s->v.Raise.inst);
+ if (s->v.Raise.tback)
+ VISIT(st, expr, s->v.Raise.tback);
+ }
+ }
+ break;
+ case TryExcept_kind:
+ VISIT_SEQ(st, stmt, s->v.TryExcept.body);
+ VISIT_SEQ(st, stmt, s->v.TryExcept.orelse);
+ VISIT_SEQ(st, excepthandler, s->v.TryExcept.handlers);
+ break;
+ case TryFinally_kind:
+ VISIT_SEQ(st, stmt, s->v.TryFinally.body);
+ VISIT_SEQ(st, stmt, s->v.TryFinally.finalbody);
+ break;
+ case Assert_kind:
+ VISIT(st, expr, s->v.Assert.test);
+ if (s->v.Assert.msg)
+ VISIT(st, expr, s->v.Assert.msg);
+ break;
+ case Import_kind:
+ VISIT_SEQ(st, alias, s->v.Import.names);
+ /* XXX Don't have the lineno available inside
+ visit_alias */
+ if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
+ st->st_cur->ste_opt_lineno = s->lineno;
+ break;
+ case ImportFrom_kind:
+ VISIT_SEQ(st, alias, s->v.ImportFrom.names);
+ /* XXX Don't have the lineno available inside
+ visit_alias */
+ if (st->st_cur->ste_unoptimized && !st->st_cur->ste_opt_lineno)
+ st->st_cur->ste_opt_lineno = s->lineno;
+ break;
+ case Exec_kind:
+ VISIT(st, expr, s->v.Exec.body);
+ if (!st->st_cur->ste_opt_lineno)
+ st->st_cur->ste_opt_lineno = s->lineno;
+ if (s->v.Exec.globals) {
+ st->st_cur->ste_unoptimized |= OPT_EXEC;
+ VISIT(st, expr, s->v.Exec.globals);
+ if (s->v.Exec.locals)
+ VISIT(st, expr, s->v.Exec.locals);
+ } else {
+ st->st_cur->ste_unoptimized |= OPT_BARE_EXEC;
+ }
+ break;
+ case Global_kind: {
+ int i;
+ asdl_seq *seq = s->v.Global.names;
+ for (i = 0; i < asdl_seq_LEN(seq); i++) {
+ identifier name = (identifier)asdl_seq_GET(seq, i);
+ char *c_name = PyString_AS_STRING(name);
+ long cur = symtable_lookup(st, name);
+ if (cur < 0)
+ return 0;
+ if (cur & (DEF_LOCAL | USE)) {
+ char buf[256];
+ if (cur & DEF_LOCAL)
+ PyOS_snprintf(buf, sizeof(buf),
+ GLOBAL_AFTER_ASSIGN,
+ c_name);
+ else
+ PyOS_snprintf(buf, sizeof(buf),
+ GLOBAL_AFTER_USE,
+ c_name);
+ if (!symtable_warn(st, buf, s->lineno))
+ return 0;
+ }
+ if (!symtable_add_def(st, name, DEF_GLOBAL))
+ return 0;
+ }
+ break;
+ }
+ case Expr_kind:
+ VISIT(st, expr, s->v.Expr.value);
+ break;
+ case Pass_kind:
+ case Break_kind:
+ case Continue_kind:
+ /* nothing to do here */
+ break;
+ case With_kind:
+ VISIT(st, expr, s->v.With.context_expr);
+ if (s->v.With.optional_vars) {
+ VISIT(st, expr, s->v.With.optional_vars);
+ }
+ VISIT_SEQ(st, stmt, s->v.With.body);
+ break;
+ }
+ return 1;
}
-static int
+static int
symtable_visit_expr(struct symtable *st, expr_ty e)
{
- switch (e->kind) {
- case BoolOp_kind:
- VISIT_SEQ(st, expr, e->v.BoolOp.values);
- break;
- case BinOp_kind:
- VISIT(st, expr, e->v.BinOp.left);
- VISIT(st, expr, e->v.BinOp.right);
- break;
- case UnaryOp_kind:
- VISIT(st, expr, e->v.UnaryOp.operand);
- break;
- case Lambda_kind: {
- if (!GET_IDENTIFIER(lambda))
- return 0;
- if (e->v.Lambda.args->defaults)
- VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
- if (!symtable_enter_block(st, lambda,
- FunctionBlock, (void *)e, e->lineno))
- return 0;
- VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e);
- VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e);
- if (!symtable_exit_block(st, (void *)e))
- return 0;
- break;
- }
- case IfExp_kind:
- VISIT(st, expr, e->v.IfExp.test);
- VISIT(st, expr, e->v.IfExp.body);
- VISIT(st, expr, e->v.IfExp.orelse);
- break;
- case Dict_kind:
- VISIT_SEQ(st, expr, e->v.Dict.keys);
- VISIT_SEQ(st, expr, e->v.Dict.values);
- break;
- case Set_kind:
- VISIT_SEQ(st, expr, e->v.Set.elts);
- break;
- case ListComp_kind:
- VISIT(st, expr, e->v.ListComp.elt);
- VISIT_SEQ(st, comprehension, e->v.ListComp.generators);
- break;
- case GeneratorExp_kind:
- if (!symtable_visit_genexp(st, e))
- return 0;
- break;
- case SetComp_kind:
- if (!symtable_visit_setcomp(st, e))
- return 0;
- break;
- case DictComp_kind:
- if (!symtable_visit_dictcomp(st, e))
- return 0;
- break;
- case Yield_kind:
- if (e->v.Yield.value)
- VISIT(st, expr, e->v.Yield.value);
- st->st_cur->ste_generator = 1;
- if (st->st_cur->ste_returns_value) {
- PyErr_SetString(PyExc_SyntaxError,
- RETURN_VAL_IN_GENERATOR);
- PyErr_SyntaxLocation(st->st_filename,
- e->lineno);
- return 0;
- }
- break;
- case Compare_kind:
- VISIT(st, expr, e->v.Compare.left);
- VISIT_SEQ(st, expr, e->v.Compare.comparators);
- break;
- case Call_kind:
- VISIT(st, expr, e->v.Call.func);
- VISIT_SEQ(st, expr, e->v.Call.args);
- VISIT_SEQ(st, keyword, e->v.Call.keywords);
- if (e->v.Call.starargs)
- VISIT(st, expr, e->v.Call.starargs);
- if (e->v.Call.kwargs)
- VISIT(st, expr, e->v.Call.kwargs);
- break;
- case Repr_kind:
- VISIT(st, expr, e->v.Repr.value);
- break;
- case Num_kind:
- case Str_kind:
- /* Nothing to do here. */
- break;
- /* The following exprs can be assignment targets. */
- case Attribute_kind:
- VISIT(st, expr, e->v.Attribute.value);
- break;
- case Subscript_kind:
- VISIT(st, expr, e->v.Subscript.value);
- VISIT(st, slice, e->v.Subscript.slice);
- break;
- case Name_kind:
- if (!symtable_add_def(st, e->v.Name.id,
- e->v.Name.ctx == Load ? USE : DEF_LOCAL))
- return 0;
- break;
- /* child nodes of List and Tuple will have expr_context set */
- case List_kind:
- VISIT_SEQ(st, expr, e->v.List.elts);
- break;
- case Tuple_kind:
- VISIT_SEQ(st, expr, e->v.Tuple.elts);
- break;
- }
- return 1;
+ switch (e->kind) {
+ case BoolOp_kind:
+ VISIT_SEQ(st, expr, e->v.BoolOp.values);
+ break;
+ case BinOp_kind:
+ VISIT(st, expr, e->v.BinOp.left);
+ VISIT(st, expr, e->v.BinOp.right);
+ break;
+ case UnaryOp_kind:
+ VISIT(st, expr, e->v.UnaryOp.operand);
+ break;
+ case Lambda_kind: {
+ if (!GET_IDENTIFIER(lambda))
+ return 0;
+ if (e->v.Lambda.args->defaults)
+ VISIT_SEQ(st, expr, e->v.Lambda.args->defaults);
+ if (!symtable_enter_block(st, lambda,
+ FunctionBlock, (void *)e, e->lineno))
+ return 0;
+ VISIT_IN_BLOCK(st, arguments, e->v.Lambda.args, (void*)e);
+ VISIT_IN_BLOCK(st, expr, e->v.Lambda.body, (void*)e);
+ if (!symtable_exit_block(st, (void *)e))
+ return 0;
+ break;
+ }
+ case IfExp_kind:
+ VISIT(st, expr, e->v.IfExp.test);
+ VISIT(st, expr, e->v.IfExp.body);
+ VISIT(st, expr, e->v.IfExp.orelse);
+ break;
+ case Dict_kind:
+ VISIT_SEQ(st, expr, e->v.Dict.keys);
+ VISIT_SEQ(st, expr, e->v.Dict.values);
+ break;
+ case Set_kind:
+ VISIT_SEQ(st, expr, e->v.Set.elts);
+ break;
+ case ListComp_kind:
+ VISIT(st, expr, e->v.ListComp.elt);
+ VISIT_SEQ(st, comprehension, e->v.ListComp.generators);
+ break;
+ case GeneratorExp_kind:
+ if (!symtable_visit_genexp(st, e))
+ return 0;
+ break;
+ case SetComp_kind:
+ if (!symtable_visit_setcomp(st, e))
+ return 0;
+ break;
+ case DictComp_kind:
+ if (!symtable_visit_dictcomp(st, e))
+ return 0;
+ break;
+ case Yield_kind:
+ if (e->v.Yield.value)
+ VISIT(st, expr, e->v.Yield.value);
+ st->st_cur->ste_generator = 1;
+ if (st->st_cur->ste_returns_value) {
+ PyErr_SetString(PyExc_SyntaxError,
+ RETURN_VAL_IN_GENERATOR);
+ PyErr_SyntaxLocation(st->st_filename,
+ e->lineno);
+ return 0;
+ }
+ break;
+ case Compare_kind:
+ VISIT(st, expr, e->v.Compare.left);
+ VISIT_SEQ(st, expr, e->v.Compare.comparators);
+ break;
+ case Call_kind:
+ VISIT(st, expr, e->v.Call.func);
+ VISIT_SEQ(st, expr, e->v.Call.args);
+ VISIT_SEQ(st, keyword, e->v.Call.keywords);
+ if (e->v.Call.starargs)
+ VISIT(st, expr, e->v.Call.starargs);
+ if (e->v.Call.kwargs)
+ VISIT(st, expr, e->v.Call.kwargs);
+ break;
+ case Repr_kind:
+ VISIT(st, expr, e->v.Repr.value);
+ break;
+ case Num_kind:
+ case Str_kind:
+ /* Nothing to do here. */
+ break;
+ /* The following exprs can be assignment targets. */
+ case Attribute_kind:
+ VISIT(st, expr, e->v.Attribute.value);
+ break;
+ case Subscript_kind:
+ VISIT(st, expr, e->v.Subscript.value);
+ VISIT(st, slice, e->v.Subscript.slice);
+ break;
+ case Name_kind:
+ if (!symtable_add_def(st, e->v.Name.id,
+ e->v.Name.ctx == Load ? USE : DEF_LOCAL))
+ return 0;
+ break;
+ /* child nodes of List and Tuple will have expr_context set */
+ case List_kind:
+ VISIT_SEQ(st, expr, e->v.List.elts);
+ break;
+ case Tuple_kind:
+ VISIT_SEQ(st, expr, e->v.Tuple.elts);
+ break;
+ }
+ return 1;
}
static int
symtable_implicit_arg(struct symtable *st, int pos)
{
- PyObject *id = PyString_FromFormat(".%d", pos);
- if (id == NULL)
- return 0;
- if (!symtable_add_def(st, id, DEF_PARAM)) {
- Py_DECREF(id);
- return 0;
- }
- Py_DECREF(id);
- return 1;
+ PyObject *id = PyString_FromFormat(".%d", pos);
+ if (id == NULL)
+ return 0;
+ if (!symtable_add_def(st, id, DEF_PARAM)) {
+ Py_DECREF(id);
+ return 0;
+ }
+ Py_DECREF(id);
+ return 1;
}
-static int
+static int
symtable_visit_params(struct symtable *st, asdl_seq *args, int toplevel)
{
- int i;
-
- /* go through all the toplevel arguments first */
- for (i = 0; i < asdl_seq_LEN(args); i++) {
- expr_ty arg = (expr_ty)asdl_seq_GET(args, i);
- if (arg->kind == Name_kind) {
- assert(arg->v.Name.ctx == Param ||
- (arg->v.Name.ctx == Store && !toplevel));
- if (!symtable_add_def(st, arg->v.Name.id, DEF_PARAM))
- return 0;
- }
- else if (arg->kind == Tuple_kind) {
- assert(arg->v.Tuple.ctx == Store);
- if (toplevel) {
- if (!symtable_implicit_arg(st, i))
- return 0;
- }
- }
- else {
- PyErr_SetString(PyExc_SyntaxError,
- "invalid expression in parameter list");
- PyErr_SyntaxLocation(st->st_filename,
- st->st_cur->ste_lineno);
- return 0;
- }
- }
-
- if (!toplevel) {
- if (!symtable_visit_params_nested(st, args))
- return 0;
- }
-
- return 1;
+ int i;
+
+ /* go through all the toplevel arguments first */
+ for (i = 0; i < asdl_seq_LEN(args); i++) {
+ expr_ty arg = (expr_ty)asdl_seq_GET(args, i);
+ if (arg->kind == Name_kind) {
+ assert(arg->v.Name.ctx == Param ||
+ (arg->v.Name.ctx == Store && !toplevel));
+ if (!symtable_add_def(st, arg->v.Name.id, DEF_PARAM))
+ return 0;
+ }
+ else if (arg->kind == Tuple_kind) {
+ assert(arg->v.Tuple.ctx == Store);
+ if (toplevel) {
+ if (!symtable_implicit_arg(st, i))
+ return 0;
+ }
+ }
+ else {
+ PyErr_SetString(PyExc_SyntaxError,
+ "invalid expression in parameter list");
+ PyErr_SyntaxLocation(st->st_filename,
+ st->st_cur->ste_lineno);
+ return 0;
+ }
+ }
+
+ if (!toplevel) {
+ if (!symtable_visit_params_nested(st, args))
+ return 0;
+ }
+
+ return 1;
}
static int
symtable_visit_params_nested(struct symtable *st, asdl_seq *args)
{
- int i;
- for (i = 0; i < asdl_seq_LEN(args); i++) {
- expr_ty arg = (expr_ty)asdl_seq_GET(args, i);
- if (arg->kind == Tuple_kind &&
- !symtable_visit_params(st, arg->v.Tuple.elts, 0))
- return 0;
- }
-
- return 1;
+ int i;
+ for (i = 0; i < asdl_seq_LEN(args); i++) {
+ expr_ty arg = (expr_ty)asdl_seq_GET(args, i);
+ if (arg->kind == Tuple_kind &&
+ !symtable_visit_params(st, arg->v.Tuple.elts, 0))
+ return 0;
+ }
+
+ return 1;
}
-static int
+static int
symtable_visit_arguments(struct symtable *st, arguments_ty a)
{
- /* skip default arguments inside function block
- XXX should ast be different?
- */
- if (a->args && !symtable_visit_params(st, a->args, 1))
- return 0;
- if (a->vararg) {
- if (!symtable_add_def(st, a->vararg, DEF_PARAM))
- return 0;
- st->st_cur->ste_varargs = 1;
- }
- if (a->kwarg) {
- if (!symtable_add_def(st, a->kwarg, DEF_PARAM))
- return 0;
- st->st_cur->ste_varkeywords = 1;
- }
- if (a->args && !symtable_visit_params_nested(st, a->args))
- return 0;
- return 1;
+ /* skip default arguments inside function block
+ XXX should ast be different?
+ */
+ if (a->args && !symtable_visit_params(st, a->args, 1))
+ return 0;
+ if (a->vararg) {
+ if (!symtable_add_def(st, a->vararg, DEF_PARAM))
+ return 0;
+ st->st_cur->ste_varargs = 1;
+ }
+ if (a->kwarg) {
+ if (!symtable_add_def(st, a->kwarg, DEF_PARAM))
+ return 0;
+ st->st_cur->ste_varkeywords = 1;
+ }
+ if (a->args && !symtable_visit_params_nested(st, a->args))
+ return 0;
+ return 1;
}
-static int
+static int
symtable_visit_excepthandler(struct symtable *st, excepthandler_ty eh)
{
- if (eh->v.ExceptHandler.type)
- VISIT(st, expr, eh->v.ExceptHandler.type);
- if (eh->v.ExceptHandler.name)
- VISIT(st, expr, eh->v.ExceptHandler.name);
- VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
- return 1;
+ if (eh->v.ExceptHandler.type)
+ VISIT(st, expr, eh->v.ExceptHandler.type);
+ if (eh->v.ExceptHandler.name)
+ VISIT(st, expr, eh->v.ExceptHandler.name);
+ VISIT_SEQ(st, stmt, eh->v.ExceptHandler.body);
+ return 1;
}
-static int
+static int
symtable_visit_alias(struct symtable *st, alias_ty a)
{
- /* Compute store_name, the name actually bound by the import
- operation. It is diferent than a->name when a->name is a
- dotted package name (e.g. spam.eggs)
- */
- PyObject *store_name;
- PyObject *name = (a->asname == NULL) ? a->name : a->asname;
- const char *base = PyString_AS_STRING(name);
- char *dot = strchr(base, '.');
- if (dot) {
- store_name = PyString_FromStringAndSize(base, dot - base);
- if (!store_name)
- return 0;
- }
- else {
- store_name = name;
- Py_INCREF(store_name);
- }
- if (strcmp(PyString_AS_STRING(name), "*")) {
- int r = symtable_add_def(st, store_name, DEF_IMPORT);
- Py_DECREF(store_name);
- return r;
- }
- else {
- if (st->st_cur->ste_type != ModuleBlock) {
- int lineno = st->st_cur->ste_lineno;
- if (!symtable_warn(st, IMPORT_STAR_WARNING, lineno)) {
- Py_DECREF(store_name);
- return 0;
- }
- }
- st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR;
- Py_DECREF(store_name);
- return 1;
- }
+ /* Compute store_name, the name actually bound by the import
+ operation. It is diferent than a->name when a->name is a
+ dotted package name (e.g. spam.eggs)
+ */
+ PyObject *store_name;
+ PyObject *name = (a->asname == NULL) ? a->name : a->asname;
+ const char *base = PyString_AS_STRING(name);
+ char *dot = strchr(base, '.');
+ if (dot) {
+ store_name = PyString_FromStringAndSize(base, dot - base);
+ if (!store_name)
+ return 0;
+ }
+ else {
+ store_name = name;
+ Py_INCREF(store_name);
+ }
+ if (strcmp(PyString_AS_STRING(name), "*")) {
+ int r = symtable_add_def(st, store_name, DEF_IMPORT);
+ Py_DECREF(store_name);
+ return r;
+ }
+ else {
+ if (st->st_cur->ste_type != ModuleBlock) {
+ int lineno = st->st_cur->ste_lineno;
+ if (!symtable_warn(st, IMPORT_STAR_WARNING, lineno)) {
+ Py_DECREF(store_name);
+ return 0;
+ }
+ }
+ st->st_cur->ste_unoptimized |= OPT_IMPORT_STAR;
+ Py_DECREF(store_name);
+ return 1;
+ }
}
-static int
+static int
symtable_visit_comprehension(struct symtable *st, comprehension_ty lc)
{
- VISIT(st, expr, lc->target);
- VISIT(st, expr, lc->iter);
- VISIT_SEQ(st, expr, lc->ifs);
- return 1;
+ VISIT(st, expr, lc->target);
+ VISIT(st, expr, lc->iter);
+ VISIT_SEQ(st, expr, lc->ifs);
+ return 1;
}
-static int
+static int
symtable_visit_keyword(struct symtable *st, keyword_ty k)
{
- VISIT(st, expr, k->value);
- return 1;
+ VISIT(st, expr, k->value);
+ return 1;
}
-static int
+static int
symtable_visit_slice(struct symtable *st, slice_ty s)
{
- switch (s->kind) {
- case Slice_kind:
- if (s->v.Slice.lower)
- VISIT(st, expr, s->v.Slice.lower)
- if (s->v.Slice.upper)
- VISIT(st, expr, s->v.Slice.upper)
- if (s->v.Slice.step)
- VISIT(st, expr, s->v.Slice.step)
- break;
- case ExtSlice_kind:
- VISIT_SEQ(st, slice, s->v.ExtSlice.dims)
- break;
- case Index_kind:
- VISIT(st, expr, s->v.Index.value)
- break;
- case Ellipsis_kind:
- break;
- }
- return 1;
+ switch (s->kind) {
+ case Slice_kind:
+ if (s->v.Slice.lower)
+ VISIT(st, expr, s->v.Slice.lower)
+ if (s->v.Slice.upper)
+ VISIT(st, expr, s->v.Slice.upper)
+ if (s->v.Slice.step)
+ VISIT(st, expr, s->v.Slice.step)
+ break;
+ case ExtSlice_kind:
+ VISIT_SEQ(st, slice, s->v.ExtSlice.dims)
+ break;
+ case Index_kind:
+ VISIT(st, expr, s->v.Index.value)
+ break;
+ case Ellipsis_kind:
+ break;
+ }
+ return 1;
}
static int
symtable_new_tmpname(struct symtable *st)
{
- char tmpname[256];
- identifier tmp;
-
- PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
- ++st->st_cur->ste_tmpname);
- tmp = PyString_InternFromString(tmpname);
- if (!tmp)
- return 0;
- if (!symtable_add_def(st, tmp, DEF_LOCAL))
- return 0;
- Py_DECREF(tmp);
- return 1;
+ char tmpname[256];
+ identifier tmp;
+
+ PyOS_snprintf(tmpname, sizeof(tmpname), "_[%d]",
+ ++st->st_cur->ste_tmpname);
+ tmp = PyString_InternFromString(tmpname);
+ if (!tmp)
+ return 0;
+ if (!symtable_add_def(st, tmp, DEF_LOCAL))
+ return 0;
+ Py_DECREF(tmp);
+ return 1;
}
-static int
+static int
symtable_handle_comprehension(struct symtable *st, expr_ty e,
identifier scope_name, asdl_seq *generators,
expr_ty elt, expr_ty value)
{
- int is_generator = (e->kind == GeneratorExp_kind);
- int needs_tmp = !is_generator;
- comprehension_ty outermost = ((comprehension_ty)
- asdl_seq_GET(generators, 0));
- /* Outermost iterator is evaluated in current scope */
- VISIT(st, expr, outermost->iter);
- /* Create comprehension scope for the rest */
- if (!scope_name ||
- !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, 0)) {
- return 0;
- }
- st->st_cur->ste_generator = is_generator;
- /* Outermost iter is received as an argument */
- if (!symtable_implicit_arg(st, 0)) {
- symtable_exit_block(st, (void *)e);
- return 0;
- }
- /* Allocate temporary name if needed */
- if (needs_tmp && !symtable_new_tmpname(st)) {
- symtable_exit_block(st, (void *)e);
- return 0;
- }
- VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e);
- VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e);
- VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension,
- generators, 1, (void*)e);
- if (value)
- VISIT_IN_BLOCK(st, expr, value, (void*)e);
- VISIT_IN_BLOCK(st, expr, elt, (void*)e);
- return symtable_exit_block(st, (void *)e);
+ int is_generator = (e->kind == GeneratorExp_kind);
+ int needs_tmp = !is_generator;
+ comprehension_ty outermost = ((comprehension_ty)
+ asdl_seq_GET(generators, 0));
+ /* Outermost iterator is evaluated in current scope */
+ VISIT(st, expr, outermost->iter);
+ /* Create comprehension scope for the rest */
+ if (!scope_name ||
+ !symtable_enter_block(st, scope_name, FunctionBlock, (void *)e, 0)) {
+ return 0;
+ }
+ st->st_cur->ste_generator = is_generator;
+ /* Outermost iter is received as an argument */
+ if (!symtable_implicit_arg(st, 0)) {
+ symtable_exit_block(st, (void *)e);
+ return 0;
+ }
+ /* Allocate temporary name if needed */
+ if (needs_tmp && !symtable_new_tmpname(st)) {
+ symtable_exit_block(st, (void *)e);
+ return 0;
+ }
+ VISIT_IN_BLOCK(st, expr, outermost->target, (void*)e);
+ VISIT_SEQ_IN_BLOCK(st, expr, outermost->ifs, (void*)e);
+ VISIT_SEQ_TAIL_IN_BLOCK(st, comprehension,
+ generators, 1, (void*)e);
+ if (value)
+ VISIT_IN_BLOCK(st, expr, value, (void*)e);
+ VISIT_IN_BLOCK(st, expr, elt, (void*)e);
+ return symtable_exit_block(st, (void *)e);
}
-static int
+static int
symtable_visit_genexp(struct symtable *st, expr_ty e)
{
- return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr),
- e->v.GeneratorExp.generators,
- e->v.GeneratorExp.elt, NULL);
+ return symtable_handle_comprehension(st, e, GET_IDENTIFIER(genexpr),
+ e->v.GeneratorExp.generators,
+ e->v.GeneratorExp.elt, NULL);
}
static int
symtable_visit_setcomp(struct symtable *st, expr_ty e)
{
- return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp),
- e->v.SetComp.generators,
- e->v.SetComp.elt, NULL);
+ return symtable_handle_comprehension(st, e, GET_IDENTIFIER(setcomp),
+ e->v.SetComp.generators,
+ e->v.SetComp.elt, NULL);
}
static int
symtable_visit_dictcomp(struct symtable *st, expr_ty e)
{
- return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp),
- e->v.DictComp.generators,
- e->v.DictComp.key,
- e->v.DictComp.value);
+ return symtable_handle_comprehension(st, e, GET_IDENTIFIER(dictcomp),
+ e->v.DictComp.generators,
+ e->v.DictComp.key,
+ e->v.DictComp.value);
}
diff --git a/Python/sysmodule.c b/Python/sysmodule.c
index 27eaad1..7cfa15d 100644
--- a/Python/sysmodule.c
+++ b/Python/sysmodule.c
@@ -49,78 +49,78 @@ extern const char *PyWin_DLLVersionString;
PyObject *
PySys_GetObject(char *name)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *sd = tstate->interp->sysdict;
- if (sd == NULL)
- return NULL;
- return PyDict_GetItemString(sd, name);
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *sd = tstate->interp->sysdict;
+ if (sd == NULL)
+ return NULL;
+ return PyDict_GetItemString(sd, name);
}
FILE *
PySys_GetFile(char *name, FILE *def)
{
- FILE *fp = NULL;
- PyObject *v = PySys_GetObject(name);
- if (v != NULL && PyFile_Check(v))
- fp = PyFile_AsFile(v);
- if (fp == NULL)
- fp = def;
- return fp;
+ FILE *fp = NULL;
+ PyObject *v = PySys_GetObject(name);
+ if (v != NULL && PyFile_Check(v))
+ fp = PyFile_AsFile(v);
+ if (fp == NULL)
+ fp = def;
+ return fp;
}
int
PySys_SetObject(char *name, PyObject *v)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *sd = tstate->interp->sysdict;
- if (v == NULL) {
- if (PyDict_GetItemString(sd, name) == NULL)
- return 0;
- else
- return PyDict_DelItemString(sd, name);
- }
- else
- return PyDict_SetItemString(sd, name, v);
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *sd = tstate->interp->sysdict;
+ if (v == NULL) {
+ if (PyDict_GetItemString(sd, name) == NULL)
+ return 0;
+ else
+ return PyDict_DelItemString(sd, name);
+ }
+ else
+ return PyDict_SetItemString(sd, name, v);
}
static PyObject *
sys_displayhook(PyObject *self, PyObject *o)
{
- PyObject *outf;
- PyInterpreterState *interp = PyThreadState_GET()->interp;
- PyObject *modules = interp->modules;
- PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
-
- if (builtins == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
- return NULL;
- }
-
- /* Print value except if None */
- /* After printing, also assign to '_' */
- /* Before, set '_' to None to avoid recursion */
- if (o == Py_None) {
- Py_INCREF(Py_None);
- return Py_None;
- }
- if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
- return NULL;
- if (Py_FlushLine() != 0)
- return NULL;
- outf = PySys_GetObject("stdout");
- if (outf == NULL) {
- PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
- return NULL;
- }
- if (PyFile_WriteObject(o, outf, 0) != 0)
- return NULL;
- PyFile_SoftSpace(outf, 1);
- if (Py_FlushLine() != 0)
- return NULL;
- if (PyObject_SetAttrString(builtins, "_", o) != 0)
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *outf;
+ PyInterpreterState *interp = PyThreadState_GET()->interp;
+ PyObject *modules = interp->modules;
+ PyObject *builtins = PyDict_GetItemString(modules, "__builtin__");
+
+ if (builtins == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "lost __builtin__");
+ return NULL;
+ }
+
+ /* Print value except if None */
+ /* After printing, also assign to '_' */
+ /* Before, set '_' to None to avoid recursion */
+ if (o == Py_None) {
+ Py_INCREF(Py_None);
+ return Py_None;
+ }
+ if (PyObject_SetAttrString(builtins, "_", Py_None) != 0)
+ return NULL;
+ if (Py_FlushLine() != 0)
+ return NULL;
+ outf = PySys_GetObject("stdout");
+ if (outf == NULL) {
+ PyErr_SetString(PyExc_RuntimeError, "lost sys.stdout");
+ return NULL;
+ }
+ if (PyFile_WriteObject(o, outf, 0) != 0)
+ return NULL;
+ PyFile_SoftSpace(outf, 1);
+ if (Py_FlushLine() != 0)
+ return NULL;
+ if (PyObject_SetAttrString(builtins, "_", o) != 0)
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(displayhook_doc,
@@ -132,12 +132,12 @@ PyDoc_STRVAR(displayhook_doc,
static PyObject *
sys_excepthook(PyObject* self, PyObject* args)
{
- PyObject *exc, *value, *tb;
- if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
- return NULL;
- PyErr_Display(exc, value, tb);
- Py_INCREF(Py_None);
- return Py_None;
+ PyObject *exc, *value, *tb;
+ if (!PyArg_UnpackTuple(args, "excepthook", 3, 3, &exc, &value, &tb))
+ return NULL;
+ PyErr_Display(exc, value, tb);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(excepthook_doc,
@@ -149,14 +149,14 @@ PyDoc_STRVAR(excepthook_doc,
static PyObject *
sys_exc_info(PyObject *self, PyObject *noargs)
{
- PyThreadState *tstate;
- tstate = PyThreadState_GET();
- return Py_BuildValue(
- "(OOO)",
- tstate->exc_type != NULL ? tstate->exc_type : Py_None,
- tstate->exc_value != NULL ? tstate->exc_value : Py_None,
- tstate->exc_traceback != NULL ?
- tstate->exc_traceback : Py_None);
+ PyThreadState *tstate;
+ tstate = PyThreadState_GET();
+ return Py_BuildValue(
+ "(OOO)",
+ tstate->exc_type != NULL ? tstate->exc_type : Py_None,
+ tstate->exc_value != NULL ? tstate->exc_value : Py_None,
+ tstate->exc_traceback != NULL ?
+ tstate->exc_traceback : Py_None);
}
PyDoc_STRVAR(exc_info_doc,
@@ -169,29 +169,29 @@ clause in the current stack frame or in an older stack frame."
static PyObject *
sys_exc_clear(PyObject *self, PyObject *noargs)
{
- PyThreadState *tstate;
- PyObject *tmp_type, *tmp_value, *tmp_tb;
-
- if (PyErr_WarnPy3k("sys.exc_clear() not supported in 3.x; "
- "use except clauses", 1) < 0)
- return NULL;
-
- tstate = PyThreadState_GET();
- tmp_type = tstate->exc_type;
- tmp_value = tstate->exc_value;
- tmp_tb = tstate->exc_traceback;
- tstate->exc_type = NULL;
- tstate->exc_value = NULL;
- tstate->exc_traceback = NULL;
- Py_XDECREF(tmp_type);
- Py_XDECREF(tmp_value);
- Py_XDECREF(tmp_tb);
- /* For b/w compatibility */
- PySys_SetObject("exc_type", Py_None);
- PySys_SetObject("exc_value", Py_None);
- PySys_SetObject("exc_traceback", Py_None);
- Py_INCREF(Py_None);
- return Py_None;
+ PyThreadState *tstate;
+ PyObject *tmp_type, *tmp_value, *tmp_tb;
+
+ if (PyErr_WarnPy3k("sys.exc_clear() not supported in 3.x; "
+ "use except clauses", 1) < 0)
+ return NULL;
+
+ tstate = PyThreadState_GET();
+ tmp_type = tstate->exc_type;
+ tmp_value = tstate->exc_value;
+ tmp_tb = tstate->exc_traceback;
+ tstate->exc_type = NULL;
+ tstate->exc_value = NULL;
+ tstate->exc_traceback = NULL;
+ Py_XDECREF(tmp_type);
+ Py_XDECREF(tmp_value);
+ Py_XDECREF(tmp_tb);
+ /* For b/w compatibility */
+ PySys_SetObject("exc_type", Py_None);
+ PySys_SetObject("exc_value", Py_None);
+ PySys_SetObject("exc_traceback", Py_None);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(exc_clear_doc,
@@ -206,12 +206,12 @@ another exception is being handled."
static PyObject *
sys_exit(PyObject *self, PyObject *args)
{
- PyObject *exit_code = 0;
- if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
- return NULL;
- /* Raise SystemExit so callers may catch it or clean up. */
- PyErr_SetObject(PyExc_SystemExit, exit_code);
- return NULL;
+ PyObject *exit_code = 0;
+ if (!PyArg_UnpackTuple(args, "exit", 0, 1, &exit_code))
+ return NULL;
+ /* Raise SystemExit so callers may catch it or clean up. */
+ PyErr_SetObject(PyExc_SystemExit, exit_code);
+ return NULL;
}
PyDoc_STRVAR(exit_doc,
@@ -229,7 +229,7 @@ exit status will be one (i.e., failure)."
static PyObject *
sys_getdefaultencoding(PyObject *self)
{
- return PyString_FromString(PyUnicode_GetDefaultEncoding());
+ return PyString_FromString(PyUnicode_GetDefaultEncoding());
}
PyDoc_STRVAR(getdefaultencoding_doc,
@@ -242,13 +242,13 @@ implementation."
static PyObject *
sys_setdefaultencoding(PyObject *self, PyObject *args)
{
- char *encoding;
- if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
- return NULL;
- if (PyUnicode_SetDefaultEncoding(encoding))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ char *encoding;
+ if (!PyArg_ParseTuple(args, "s:setdefaultencoding", &encoding))
+ return NULL;
+ if (PyUnicode_SetDefaultEncoding(encoding))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setdefaultencoding_doc,
@@ -260,10 +260,10 @@ Set the current default string encoding used by the Unicode implementation."
static PyObject *
sys_getfilesystemencoding(PyObject *self)
{
- if (Py_FileSystemDefaultEncoding)
- return PyString_FromString(Py_FileSystemDefaultEncoding);
- Py_INCREF(Py_None);
- return Py_None;
+ if (Py_FileSystemDefaultEncoding)
+ return PyString_FromString(Py_FileSystemDefaultEncoding);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(getfilesystemencoding_doc,
@@ -284,116 +284,116 @@ static PyObject *whatstrings[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL};
static int
trace_init(void)
{
- static char *whatnames[7] = {"call", "exception", "line", "return",
- "c_call", "c_exception", "c_return"};
- PyObject *name;
- int i;
- for (i = 0; i < 7; ++i) {
- if (whatstrings[i] == NULL) {
- name = PyString_InternFromString(whatnames[i]);
- if (name == NULL)
- return -1;
- whatstrings[i] = name;
- }
- }
- return 0;
+ static char *whatnames[7] = {"call", "exception", "line", "return",
+ "c_call", "c_exception", "c_return"};
+ PyObject *name;
+ int i;
+ for (i = 0; i < 7; ++i) {
+ if (whatstrings[i] == NULL) {
+ name = PyString_InternFromString(whatnames[i]);
+ if (name == NULL)
+ return -1;
+ whatstrings[i] = name;
+ }
+ }
+ return 0;
}
static PyObject *
call_trampoline(PyThreadState *tstate, PyObject* callback,
- PyFrameObject *frame, int what, PyObject *arg)
+ PyFrameObject *frame, int what, PyObject *arg)
{
- PyObject *args = PyTuple_New(3);
- PyObject *whatstr;
- PyObject *result;
-
- if (args == NULL)
- return NULL;
- Py_INCREF(frame);
- whatstr = whatstrings[what];
- Py_INCREF(whatstr);
- if (arg == NULL)
- arg = Py_None;
- Py_INCREF(arg);
- PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
- PyTuple_SET_ITEM(args, 1, whatstr);
- PyTuple_SET_ITEM(args, 2, arg);
-
- /* call the Python-level function */
- PyFrame_FastToLocals(frame);
- result = PyEval_CallObject(callback, args);
- PyFrame_LocalsToFast(frame, 1);
- if (result == NULL)
- PyTraceBack_Here(frame);
-
- /* cleanup */
- Py_DECREF(args);
- return result;
+ PyObject *args = PyTuple_New(3);
+ PyObject *whatstr;
+ PyObject *result;
+
+ if (args == NULL)
+ return NULL;
+ Py_INCREF(frame);
+ whatstr = whatstrings[what];
+ Py_INCREF(whatstr);
+ if (arg == NULL)
+ arg = Py_None;
+ Py_INCREF(arg);
+ PyTuple_SET_ITEM(args, 0, (PyObject *)frame);
+ PyTuple_SET_ITEM(args, 1, whatstr);
+ PyTuple_SET_ITEM(args, 2, arg);
+
+ /* call the Python-level function */
+ PyFrame_FastToLocals(frame);
+ result = PyEval_CallObject(callback, args);
+ PyFrame_LocalsToFast(frame, 1);
+ if (result == NULL)
+ PyTraceBack_Here(frame);
+
+ /* cleanup */
+ Py_DECREF(args);
+ return result;
}
static int
profile_trampoline(PyObject *self, PyFrameObject *frame,
- int what, PyObject *arg)
+ int what, PyObject *arg)
{
- PyThreadState *tstate = frame->f_tstate;
- PyObject *result;
-
- if (arg == NULL)
- arg = Py_None;
- result = call_trampoline(tstate, self, frame, what, arg);
- if (result == NULL) {
- PyEval_SetProfile(NULL, NULL);
- return -1;
- }
- Py_DECREF(result);
- return 0;
+ PyThreadState *tstate = frame->f_tstate;
+ PyObject *result;
+
+ if (arg == NULL)
+ arg = Py_None;
+ result = call_trampoline(tstate, self, frame, what, arg);
+ if (result == NULL) {
+ PyEval_SetProfile(NULL, NULL);
+ return -1;
+ }
+ Py_DECREF(result);
+ return 0;
}
static int
trace_trampoline(PyObject *self, PyFrameObject *frame,
- int what, PyObject *arg)
+ int what, PyObject *arg)
{
- PyThreadState *tstate = frame->f_tstate;
- PyObject *callback;
- PyObject *result;
-
- if (what == PyTrace_CALL)
- callback = self;
- else
- callback = frame->f_trace;
- if (callback == NULL)
- return 0;
- result = call_trampoline(tstate, callback, frame, what, arg);
- if (result == NULL) {
- PyEval_SetTrace(NULL, NULL);
- Py_XDECREF(frame->f_trace);
- frame->f_trace = NULL;
- return -1;
- }
- if (result != Py_None) {
- PyObject *temp = frame->f_trace;
- frame->f_trace = NULL;
- Py_XDECREF(temp);
- frame->f_trace = result;
- }
- else {
- Py_DECREF(result);
- }
- return 0;
+ PyThreadState *tstate = frame->f_tstate;
+ PyObject *callback;
+ PyObject *result;
+
+ if (what == PyTrace_CALL)
+ callback = self;
+ else
+ callback = frame->f_trace;
+ if (callback == NULL)
+ return 0;
+ result = call_trampoline(tstate, callback, frame, what, arg);
+ if (result == NULL) {
+ PyEval_SetTrace(NULL, NULL);
+ Py_XDECREF(frame->f_trace);
+ frame->f_trace = NULL;
+ return -1;
+ }
+ if (result != Py_None) {
+ PyObject *temp = frame->f_trace;
+ frame->f_trace = NULL;
+ Py_XDECREF(temp);
+ frame->f_trace = result;
+ }
+ else {
+ Py_DECREF(result);
+ }
+ return 0;
}
static PyObject *
sys_settrace(PyObject *self, PyObject *args)
{
- if (trace_init() == -1)
- return NULL;
- if (args == Py_None)
- PyEval_SetTrace(NULL, NULL);
- else
- PyEval_SetTrace(trace_trampoline, args);
- Py_INCREF(Py_None);
- return Py_None;
+ if (trace_init() == -1)
+ return NULL;
+ if (args == Py_None)
+ PyEval_SetTrace(NULL, NULL);
+ else
+ PyEval_SetTrace(trace_trampoline, args);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(settrace_doc,
@@ -406,13 +406,13 @@ function call. See the debugger chapter in the library manual."
static PyObject *
sys_gettrace(PyObject *self, PyObject *args)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *temp = tstate->c_traceobj;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *temp = tstate->c_traceobj;
- if (temp == NULL)
- temp = Py_None;
- Py_INCREF(temp);
- return temp;
+ if (temp == NULL)
+ temp = Py_None;
+ Py_INCREF(temp);
+ return temp;
}
PyDoc_STRVAR(gettrace_doc,
@@ -425,14 +425,14 @@ See the debugger chapter in the library manual."
static PyObject *
sys_setprofile(PyObject *self, PyObject *args)
{
- if (trace_init() == -1)
- return NULL;
- if (args == Py_None)
- PyEval_SetProfile(NULL, NULL);
- else
- PyEval_SetProfile(profile_trampoline, args);
- Py_INCREF(Py_None);
- return Py_None;
+ if (trace_init() == -1)
+ return NULL;
+ if (args == Py_None)
+ PyEval_SetProfile(NULL, NULL);
+ else
+ PyEval_SetProfile(profile_trampoline, args);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setprofile_doc,
@@ -445,13 +445,13 @@ and return. See the profiler chapter in the library manual."
static PyObject *
sys_getprofile(PyObject *self, PyObject *args)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyObject *temp = tstate->c_profileobj;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyObject *temp = tstate->c_profileobj;
- if (temp == NULL)
- temp = Py_None;
- Py_INCREF(temp);
- return temp;
+ if (temp == NULL)
+ temp = Py_None;
+ Py_INCREF(temp);
+ return temp;
}
PyDoc_STRVAR(getprofile_doc,
@@ -464,10 +464,10 @@ See the profiler chapter in the library manual."
static PyObject *
sys_setcheckinterval(PyObject *self, PyObject *args)
{
- if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
- return NULL;
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "i:setcheckinterval", &_Py_CheckInterval))
+ return NULL;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setcheckinterval_doc,
@@ -480,7 +480,7 @@ n instructions. This also affects how often thread switches occur."
static PyObject *
sys_getcheckinterval(PyObject *self, PyObject *args)
{
- return PyInt_FromLong(_Py_CheckInterval);
+ return PyInt_FromLong(_Py_CheckInterval);
}
PyDoc_STRVAR(getcheckinterval_doc,
@@ -491,17 +491,17 @@ PyDoc_STRVAR(getcheckinterval_doc,
static PyObject *
sys_settscdump(PyObject *self, PyObject *args)
{
- int bool;
- PyThreadState *tstate = PyThreadState_Get();
-
- if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
- return NULL;
- if (bool)
- tstate->interp->tscdump = 1;
- else
- tstate->interp->tscdump = 0;
- Py_INCREF(Py_None);
- return Py_None;
+ int bool;
+ PyThreadState *tstate = PyThreadState_Get();
+
+ if (!PyArg_ParseTuple(args, "i:settscdump", &bool))
+ return NULL;
+ if (bool)
+ tstate->interp->tscdump = 1;
+ else
+ tstate->interp->tscdump = 0;
+ Py_INCREF(Py_None);
+ return Py_None;
}
@@ -517,17 +517,17 @@ processor's time-stamp counter."
static PyObject *
sys_setrecursionlimit(PyObject *self, PyObject *args)
{
- int new_limit;
- if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
- return NULL;
- if (new_limit <= 0) {
- PyErr_SetString(PyExc_ValueError,
- "recursion limit must be positive");
- return NULL;
- }
- Py_SetRecursionLimit(new_limit);
- Py_INCREF(Py_None);
- return Py_None;
+ int new_limit;
+ if (!PyArg_ParseTuple(args, "i:setrecursionlimit", &new_limit))
+ return NULL;
+ if (new_limit <= 0) {
+ PyErr_SetString(PyExc_ValueError,
+ "recursion limit must be positive");
+ return NULL;
+ }
+ Py_SetRecursionLimit(new_limit);
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setrecursionlimit_doc,
@@ -542,7 +542,7 @@ dependent."
static PyObject *
sys_getrecursionlimit(PyObject *self)
{
- return PyInt_FromLong(Py_GetRecursionLimit());
+ return PyInt_FromLong(Py_GetRecursionLimit());
}
PyDoc_STRVAR(getrecursionlimit_doc,
@@ -570,52 +570,52 @@ controller, 3 for a server."
static PyTypeObject WindowsVersionType = {0, 0, 0, 0, 0, 0};
static PyStructSequence_Field windows_version_fields[] = {
- {"major", "Major version number"},
- {"minor", "Minor version number"},
- {"build", "Build number"},
- {"platform", "Operating system platform"},
- {"service_pack", "Latest Service Pack installed on the system"},
- {"service_pack_major", "Service Pack major version number"},
- {"service_pack_minor", "Service Pack minor version number"},
- {"suite_mask", "Bit mask identifying available product suites"},
- {"product_type", "System product type"},
- {0}
+ {"major", "Major version number"},
+ {"minor", "Minor version number"},
+ {"build", "Build number"},
+ {"platform", "Operating system platform"},
+ {"service_pack", "Latest Service Pack installed on the system"},
+ {"service_pack_major", "Service Pack major version number"},
+ {"service_pack_minor", "Service Pack minor version number"},
+ {"suite_mask", "Bit mask identifying available product suites"},
+ {"product_type", "System product type"},
+ {0}
};
static PyStructSequence_Desc windows_version_desc = {
- "sys.getwindowsversion", /* name */
- getwindowsversion_doc, /* doc */
- windows_version_fields, /* fields */
- 5 /* For backward compatibility,
- only the first 5 items are accessible
- via indexing, the rest are name only */
+ "sys.getwindowsversion", /* name */
+ getwindowsversion_doc, /* doc */
+ windows_version_fields, /* fields */
+ 5 /* For backward compatibility,
+ only the first 5 items are accessible
+ via indexing, the rest are name only */
};
static PyObject *
sys_getwindowsversion(PyObject *self)
{
- PyObject *version;
- int pos = 0;
- OSVERSIONINFOEX ver;
- ver.dwOSVersionInfoSize = sizeof(ver);
- if (!GetVersionEx((OSVERSIONINFO*) &ver))
- return PyErr_SetFromWindowsErr(0);
-
- version = PyStructSequence_New(&WindowsVersionType);
- if (version == NULL)
- return NULL;
-
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMajorVersion));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMinorVersion));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwBuildNumber));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwPlatformId));
- PyStructSequence_SET_ITEM(version, pos++, PyString_FromString(ver.szCSDVersion));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMajor));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMinor));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wSuiteMask));
- PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wProductType));
-
- return version;
+ PyObject *version;
+ int pos = 0;
+ OSVERSIONINFOEX ver;
+ ver.dwOSVersionInfoSize = sizeof(ver);
+ if (!GetVersionEx((OSVERSIONINFO*) &ver))
+ return PyErr_SetFromWindowsErr(0);
+
+ version = PyStructSequence_New(&WindowsVersionType);
+ if (version == NULL)
+ return NULL;
+
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMajorVersion));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwMinorVersion));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwBuildNumber));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.dwPlatformId));
+ PyStructSequence_SET_ITEM(version, pos++, PyString_FromString(ver.szCSDVersion));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMajor));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wServicePackMinor));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wSuiteMask));
+ PyStructSequence_SET_ITEM(version, pos++, PyInt_FromLong(ver.wProductType));
+
+ return version;
}
#endif /* MS_WINDOWS */
@@ -624,15 +624,15 @@ sys_getwindowsversion(PyObject *self)
static PyObject *
sys_setdlopenflags(PyObject *self, PyObject *args)
{
- int new_val;
- PyThreadState *tstate = PyThreadState_GET();
- if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
- return NULL;
- if (!tstate)
- return NULL;
- tstate->interp->dlopenflags = new_val;
- Py_INCREF(Py_None);
- return Py_None;
+ int new_val;
+ PyThreadState *tstate = PyThreadState_GET();
+ if (!PyArg_ParseTuple(args, "i:setdlopenflags", &new_val))
+ return NULL;
+ if (!tstate)
+ return NULL;
+ tstate->interp->dlopenflags = new_val;
+ Py_INCREF(Py_None);
+ return Py_None;
}
PyDoc_STRVAR(setdlopenflags_doc,
@@ -650,10 +650,10 @@ h2py script.");
static PyObject *
sys_getdlopenflags(PyObject *self, PyObject *args)
{
- PyThreadState *tstate = PyThreadState_GET();
- if (!tstate)
- return NULL;
- return PyInt_FromLong(tstate->interp->dlopenflags);
+ PyThreadState *tstate = PyThreadState_GET();
+ if (!tstate)
+ return NULL;
+ return PyInt_FromLong(tstate->interp->dlopenflags);
}
PyDoc_STRVAR(getdlopenflags_doc,
@@ -662,7 +662,7 @@ PyDoc_STRVAR(getdlopenflags_doc,
Return the current value of the flags that are used for dlopen calls.\n\
The flag constants are defined in the ctypes and DLFCN modules.");
-#endif /* HAVE_DLOPEN */
+#endif /* HAVE_DLOPEN */
#ifdef USE_MALLOPT
/* Link with -lmalloc (or -lmpc) on an SGI */
@@ -671,75 +671,75 @@ The flag constants are defined in the ctypes and DLFCN modules.");
static PyObject *
sys_mdebug(PyObject *self, PyObject *args)
{
- int flag;
- if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
- return NULL;
- mallopt(M_DEBUG, flag);
- Py_INCREF(Py_None);
- return Py_None;
+ int flag;
+ if (!PyArg_ParseTuple(args, "i:mdebug", &flag))
+ return NULL;
+ mallopt(M_DEBUG, flag);
+ Py_INCREF(Py_None);
+ return Py_None;
}
#endif /* USE_MALLOPT */
static PyObject *
sys_getsizeof(PyObject *self, PyObject *args, PyObject *kwds)
{
- PyObject *res = NULL;
- static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
- static char *kwlist[] = {"object", "default", 0};
- PyObject *o, *dflt = NULL;
-
- if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
- kwlist, &o, &dflt))
- return NULL;
-
- /* Initialize static variable for GC head size */
- if (gc_head_size == NULL) {
- gc_head_size = PyInt_FromSsize_t(sizeof(PyGC_Head));
- if (gc_head_size == NULL)
- return NULL;
- }
-
- /* Make sure the type is initialized. float gets initialized late */
- if (PyType_Ready(Py_TYPE(o)) < 0)
- return NULL;
-
- /* Instance of old-style class */
- if (PyInstance_Check(o))
- res = PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);
- /* all other objects */
- else {
- PyObject *method = _PyObject_LookupSpecial(o, "__sizeof__",
- &str__sizeof__);
- if (method == NULL) {
- if (!PyErr_Occurred())
- PyErr_Format(PyExc_TypeError,
- "Type %.100s doesn't define __sizeof__",
- Py_TYPE(o)->tp_name);
- }
- else {
- res = PyObject_CallFunctionObjArgs(method, NULL);
- Py_DECREF(method);
- }
- }
-
- /* Has a default value been given? */
- if ((res == NULL) && (dflt != NULL) &&
- PyErr_ExceptionMatches(PyExc_TypeError))
- {
- PyErr_Clear();
- Py_INCREF(dflt);
- return dflt;
- }
- else if (res == NULL)
- return res;
-
- /* add gc_head size */
- if (PyObject_IS_GC(o)) {
- PyObject *tmp = res;
- res = PyNumber_Add(tmp, gc_head_size);
- Py_DECREF(tmp);
- }
- return res;
+ PyObject *res = NULL;
+ static PyObject *str__sizeof__ = NULL, *gc_head_size = NULL;
+ static char *kwlist[] = {"object", "default", 0};
+ PyObject *o, *dflt = NULL;
+
+ if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|O:getsizeof",
+ kwlist, &o, &dflt))
+ return NULL;
+
+ /* Initialize static variable for GC head size */
+ if (gc_head_size == NULL) {
+ gc_head_size = PyInt_FromSsize_t(sizeof(PyGC_Head));
+ if (gc_head_size == NULL)
+ return NULL;
+ }
+
+ /* Make sure the type is initialized. float gets initialized late */
+ if (PyType_Ready(Py_TYPE(o)) < 0)
+ return NULL;
+
+ /* Instance of old-style class */
+ if (PyInstance_Check(o))
+ res = PyInt_FromSsize_t(PyInstance_Type.tp_basicsize);
+ /* all other objects */
+ else {
+ PyObject *method = _PyObject_LookupSpecial(o, "__sizeof__",
+ &str__sizeof__);
+ if (method == NULL) {
+ if (!PyErr_Occurred())
+ PyErr_Format(PyExc_TypeError,
+ "Type %.100s doesn't define __sizeof__",
+ Py_TYPE(o)->tp_name);
+ }
+ else {
+ res = PyObject_CallFunctionObjArgs(method, NULL);
+ Py_DECREF(method);
+ }
+ }
+
+ /* Has a default value been given? */
+ if ((res == NULL) && (dflt != NULL) &&
+ PyErr_ExceptionMatches(PyExc_TypeError))
+ {
+ PyErr_Clear();
+ Py_INCREF(dflt);
+ return dflt;
+ }
+ else if (res == NULL)
+ return res;
+
+ /* add gc_head size */
+ if (PyObject_IS_GC(o)) {
+ PyObject *tmp = res;
+ res = PyNumber_Add(tmp, gc_head_size);
+ Py_DECREF(tmp);
+ }
+ return res;
}
PyDoc_STRVAR(getsizeof_doc,
@@ -750,14 +750,14 @@ Return the size of object in bytes.");
static PyObject *
sys_getrefcount(PyObject *self, PyObject *arg)
{
- return PyInt_FromSsize_t(arg->ob_refcnt);
+ return PyInt_FromSsize_t(arg->ob_refcnt);
}
#ifdef Py_REF_DEBUG
static PyObject *
sys_gettotalrefcount(PyObject *self)
{
- return PyInt_FromSsize_t(_Py_GetRefTotal());
+ return PyInt_FromSsize_t(_Py_GetRefTotal());
}
#endif /* Py_REF_DEBUG */
@@ -773,9 +773,9 @@ reference as an argument to getrefcount()."
static PyObject *
sys_getcounts(PyObject *self)
{
- extern PyObject *get_counts(void);
+ extern PyObject *get_counts(void);
- return get_counts();
+ return get_counts();
}
#endif
@@ -794,23 +794,23 @@ purposes only."
static PyObject *
sys_getframe(PyObject *self, PyObject *args)
{
- PyFrameObject *f = PyThreadState_GET()->frame;
- int depth = -1;
-
- if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
- return NULL;
-
- while (depth > 0 && f != NULL) {
- f = f->f_back;
- --depth;
- }
- if (f == NULL) {
- PyErr_SetString(PyExc_ValueError,
- "call stack is not deep enough");
- return NULL;
- }
- Py_INCREF(f);
- return (PyObject*)f;
+ PyFrameObject *f = PyThreadState_GET()->frame;
+ int depth = -1;
+
+ if (!PyArg_ParseTuple(args, "|i:_getframe", &depth))
+ return NULL;
+
+ while (depth > 0 && f != NULL) {
+ f = f->f_back;
+ --depth;
+ }
+ if (f == NULL) {
+ PyErr_SetString(PyExc_ValueError,
+ "call stack is not deep enough");
+ return NULL;
+ }
+ Py_INCREF(f);
+ return (PyObject*)f;
}
PyDoc_STRVAR(current_frames_doc,
@@ -825,7 +825,7 @@ This function should be used for specialized purposes only."
static PyObject *
sys_current_frames(PyObject *self, PyObject *noargs)
{
- return _PyThread_CurrentFrames();
+ return _PyThread_CurrentFrames();
}
PyDoc_STRVAR(call_tracing_doc,
@@ -839,10 +839,10 @@ a debugger from a checkpoint, to recursively debug some other code."
static PyObject *
sys_call_tracing(PyObject *self, PyObject *args)
{
- PyObject *func, *funcargs;
- if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
- return NULL;
- return _PyEval_CallTracing(func, funcargs);
+ PyObject *func, *funcargs;
+ if (!PyArg_ParseTuple(args, "OO!:call_tracing", &func, &PyTuple_Type, &funcargs))
+ return NULL;
+ return _PyEval_CallTracing(func, funcargs);
}
PyDoc_STRVAR(callstats_doc,
@@ -889,8 +889,8 @@ extern PyObject *_Py_GetDXProfile(PyObject *, PyObject *);
static PyObject *
sys_clear_type_cache(PyObject* self, PyObject* args)
{
- PyType_ClearCache();
- Py_RETURN_NONE;
+ PyType_ClearCache();
+ Py_RETURN_NONE;
}
PyDoc_STRVAR(sys_clear_type_cache__doc__,
@@ -899,105 +899,105 @@ Clear the internal type lookup cache.");
static PyMethodDef sys_methods[] = {
- /* Might as well keep this in alphabetic order */
- {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
- callstats_doc},
- {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
- sys_clear_type_cache__doc__},
- {"_current_frames", sys_current_frames, METH_NOARGS,
- current_frames_doc},
- {"displayhook", sys_displayhook, METH_O, displayhook_doc},
- {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
- {"exc_clear", sys_exc_clear, METH_NOARGS, exc_clear_doc},
- {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
- {"exit", sys_exit, METH_VARARGS, exit_doc},
+ /* Might as well keep this in alphabetic order */
+ {"callstats", (PyCFunction)PyEval_GetCallStats, METH_NOARGS,
+ callstats_doc},
+ {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS,
+ sys_clear_type_cache__doc__},
+ {"_current_frames", sys_current_frames, METH_NOARGS,
+ current_frames_doc},
+ {"displayhook", sys_displayhook, METH_O, displayhook_doc},
+ {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc},
+ {"exc_clear", sys_exc_clear, METH_NOARGS, exc_clear_doc},
+ {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc},
+ {"exit", sys_exit, METH_VARARGS, exit_doc},
#ifdef Py_USING_UNICODE
- {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
- METH_NOARGS, getdefaultencoding_doc},
+ {"getdefaultencoding", (PyCFunction)sys_getdefaultencoding,
+ METH_NOARGS, getdefaultencoding_doc},
#endif
#ifdef HAVE_DLOPEN
- {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
- getdlopenflags_doc},
+ {"getdlopenflags", (PyCFunction)sys_getdlopenflags, METH_NOARGS,
+ getdlopenflags_doc},
#endif
#ifdef COUNT_ALLOCS
- {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
+ {"getcounts", (PyCFunction)sys_getcounts, METH_NOARGS},
#endif
#ifdef DYNAMIC_EXECUTION_PROFILE
- {"getdxp", _Py_GetDXProfile, METH_VARARGS},
+ {"getdxp", _Py_GetDXProfile, METH_VARARGS},
#endif
#ifdef Py_USING_UNICODE
- {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
- METH_NOARGS, getfilesystemencoding_doc},
+ {"getfilesystemencoding", (PyCFunction)sys_getfilesystemencoding,
+ METH_NOARGS, getfilesystemencoding_doc},
#endif
#ifdef Py_TRACE_REFS
- {"getobjects", _Py_GetObjects, METH_VARARGS},
+ {"getobjects", _Py_GetObjects, METH_VARARGS},
#endif
#ifdef Py_REF_DEBUG
- {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
+ {"gettotalrefcount", (PyCFunction)sys_gettotalrefcount, METH_NOARGS},
#endif
- {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
- {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
- getrecursionlimit_doc},
- {"getsizeof", (PyCFunction)sys_getsizeof,
- METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
- {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
+ {"getrefcount", (PyCFunction)sys_getrefcount, METH_O, getrefcount_doc},
+ {"getrecursionlimit", (PyCFunction)sys_getrecursionlimit, METH_NOARGS,
+ getrecursionlimit_doc},
+ {"getsizeof", (PyCFunction)sys_getsizeof,
+ METH_VARARGS | METH_KEYWORDS, getsizeof_doc},
+ {"_getframe", sys_getframe, METH_VARARGS, getframe_doc},
#ifdef MS_WINDOWS
- {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
- getwindowsversion_doc},
+ {"getwindowsversion", (PyCFunction)sys_getwindowsversion, METH_NOARGS,
+ getwindowsversion_doc},
#endif /* MS_WINDOWS */
#ifdef USE_MALLOPT
- {"mdebug", sys_mdebug, METH_VARARGS},
+ {"mdebug", sys_mdebug, METH_VARARGS},
#endif
#ifdef Py_USING_UNICODE
- {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
- setdefaultencoding_doc},
+ {"setdefaultencoding", sys_setdefaultencoding, METH_VARARGS,
+ setdefaultencoding_doc},
#endif
- {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
- setcheckinterval_doc},
- {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
- getcheckinterval_doc},
+ {"setcheckinterval", sys_setcheckinterval, METH_VARARGS,
+ setcheckinterval_doc},
+ {"getcheckinterval", sys_getcheckinterval, METH_NOARGS,
+ getcheckinterval_doc},
#ifdef HAVE_DLOPEN
- {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
- setdlopenflags_doc},
+ {"setdlopenflags", sys_setdlopenflags, METH_VARARGS,
+ setdlopenflags_doc},
#endif
- {"setprofile", sys_setprofile, METH_O, setprofile_doc},
- {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
- {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
- setrecursionlimit_doc},
+ {"setprofile", sys_setprofile, METH_O, setprofile_doc},
+ {"getprofile", sys_getprofile, METH_NOARGS, getprofile_doc},
+ {"setrecursionlimit", sys_setrecursionlimit, METH_VARARGS,
+ setrecursionlimit_doc},
#ifdef WITH_TSC
- {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
+ {"settscdump", sys_settscdump, METH_VARARGS, settscdump_doc},
#endif
- {"settrace", sys_settrace, METH_O, settrace_doc},
- {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
- {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
- {NULL, NULL} /* sentinel */
+ {"settrace", sys_settrace, METH_O, settrace_doc},
+ {"gettrace", sys_gettrace, METH_NOARGS, gettrace_doc},
+ {"call_tracing", sys_call_tracing, METH_VARARGS, call_tracing_doc},
+ {NULL, NULL} /* sentinel */
};
static PyObject *
list_builtin_module_names(void)
{
- PyObject *list = PyList_New(0);
- int i;
- if (list == NULL)
- return NULL;
- for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
- PyObject *name = PyString_FromString(
- PyImport_Inittab[i].name);
- if (name == NULL)
- break;
- PyList_Append(list, name);
- Py_DECREF(name);
- }
- if (PyList_Sort(list) != 0) {
- Py_DECREF(list);
- list = NULL;
- }
- if (list) {
- PyObject *v = PyList_AsTuple(list);
- Py_DECREF(list);
- list = v;
- }
- return list;
+ PyObject *list = PyList_New(0);
+ int i;
+ if (list == NULL)
+ return NULL;
+ for (i = 0; PyImport_Inittab[i].name != NULL; i++) {
+ PyObject *name = PyString_FromString(
+ PyImport_Inittab[i].name);
+ if (name == NULL)
+ break;
+ PyList_Append(list, name);
+ Py_DECREF(name);
+ }
+ if (PyList_Sort(list) != 0) {
+ Py_DECREF(list);
+ list = NULL;
+ }
+ if (list) {
+ PyObject *v = PyList_AsTuple(list);
+ Py_DECREF(list);
+ list = v;
+ }
+ return list;
}
static PyObject *warnoptions = NULL;
@@ -1005,27 +1005,27 @@ static PyObject *warnoptions = NULL;
void
PySys_ResetWarnOptions(void)
{
- if (warnoptions == NULL || !PyList_Check(warnoptions))
- return;
- PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
+ if (warnoptions == NULL || !PyList_Check(warnoptions))
+ return;
+ PyList_SetSlice(warnoptions, 0, PyList_GET_SIZE(warnoptions), NULL);
}
void
PySys_AddWarnOption(char *s)
{
- PyObject *str;
-
- if (warnoptions == NULL || !PyList_Check(warnoptions)) {
- Py_XDECREF(warnoptions);
- warnoptions = PyList_New(0);
- if (warnoptions == NULL)
- return;
- }
- str = PyString_FromString(s);
- if (str != NULL) {
- PyList_Append(warnoptions, str);
- Py_DECREF(str);
- }
+ PyObject *str;
+
+ if (warnoptions == NULL || !PyList_Check(warnoptions)) {
+ Py_XDECREF(warnoptions);
+ warnoptions = PyList_New(0);
+ if (warnoptions == NULL)
+ return;
+ }
+ str = PyString_FromString(s);
+ if (str != NULL) {
+ PyList_Append(warnoptions, str);
+ Py_DECREF(str);
+ }
}
int
@@ -1154,69 +1154,69 @@ static const char *svn_revision;
static void
svnversion_init(void)
{
- const char *python, *br_start, *br_end, *br_end2, *svnversion;
- Py_ssize_t len;
- int istag;
-
- if (svn_initialized)
- return;
-
- python = strstr(headurl, "/python/");
- if (!python) {
- /* XXX quick hack to get bzr working */
- *patchlevel_revision = '\0';
- strcpy(branch, "");
- strcpy(shortbranch, "unknown");
- svn_revision = "";
- return;
- /* Py_FatalError("subversion keywords missing"); */
- }
-
- br_start = python + 8;
- br_end = strchr(br_start, '/');
- assert(br_end);
-
- /* Works even for trunk,
- as we are in trunk/Python/sysmodule.c */
- br_end2 = strchr(br_end+1, '/');
-
- istag = strncmp(br_start, "tags", 4) == 0;
- if (strncmp(br_start, "trunk", 5) == 0) {
- strcpy(branch, "trunk");
- strcpy(shortbranch, "trunk");
-
- }
- else if (istag || strncmp(br_start, "branches", 8) == 0) {
- len = br_end2 - br_start;
- strncpy(branch, br_start, len);
- branch[len] = '\0';
-
- len = br_end2 - (br_end + 1);
- strncpy(shortbranch, br_end + 1, len);
- shortbranch[len] = '\0';
- }
- else {
- Py_FatalError("bad HeadURL");
- return;
- }
-
-
- svnversion = _Py_svnversion();
- if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0)
- svn_revision = svnversion;
- else if (istag) {
- len = strlen(_patchlevel_revision);
- assert(len >= 13);
- assert(len < (sizeof(patchlevel_revision) + 13));
- strncpy(patchlevel_revision, _patchlevel_revision + 11,
- len - 13);
- patchlevel_revision[len - 13] = '\0';
- svn_revision = patchlevel_revision;
- }
- else
- svn_revision = "";
-
- svn_initialized = 1;
+ const char *python, *br_start, *br_end, *br_end2, *svnversion;
+ Py_ssize_t len;
+ int istag;
+
+ if (svn_initialized)
+ return;
+
+ python = strstr(headurl, "/python/");
+ if (!python) {
+ /* XXX quick hack to get bzr working */
+ *patchlevel_revision = '\0';
+ strcpy(branch, "");
+ strcpy(shortbranch, "unknown");
+ svn_revision = "";
+ return;
+ /* Py_FatalError("subversion keywords missing"); */
+ }
+
+ br_start = python + 8;
+ br_end = strchr(br_start, '/');
+ assert(br_end);
+
+ /* Works even for trunk,
+ as we are in trunk/Python/sysmodule.c */
+ br_end2 = strchr(br_end+1, '/');
+
+ istag = strncmp(br_start, "tags", 4) == 0;
+ if (strncmp(br_start, "trunk", 5) == 0) {
+ strcpy(branch, "trunk");
+ strcpy(shortbranch, "trunk");
+
+ }
+ else if (istag || strncmp(br_start, "branches", 8) == 0) {
+ len = br_end2 - br_start;
+ strncpy(branch, br_start, len);
+ branch[len] = '\0';
+
+ len = br_end2 - (br_end + 1);
+ strncpy(shortbranch, br_end + 1, len);
+ shortbranch[len] = '\0';
+ }
+ else {
+ Py_FatalError("bad HeadURL");
+ return;
+ }
+
+
+ svnversion = _Py_svnversion();
+ if (strcmp(svnversion, "Unversioned directory") != 0 && strcmp(svnversion, "exported") != 0)
+ svn_revision = svnversion;
+ else if (istag) {
+ len = strlen(_patchlevel_revision);
+ assert(len >= 13);
+ assert(len < (sizeof(patchlevel_revision) + 13));
+ strncpy(patchlevel_revision, _patchlevel_revision + 11,
+ len - 13);
+ patchlevel_revision[len - 13] = '\0';
+ svn_revision = patchlevel_revision;
+ }
+ else
+ svn_revision = "";
+
+ svn_initialized = 1;
}
/* Return svnversion output if available.
@@ -1225,15 +1225,15 @@ svnversion_init(void)
const char*
Py_SubversionRevision()
{
- svnversion_init();
- return svn_revision;
+ svnversion_init();
+ return svn_revision;
}
const char*
Py_SubversionShortBranch()
{
- svnversion_init();
- return shortbranch;
+ svnversion_init();
+ return shortbranch;
}
@@ -1245,79 +1245,79 @@ Flags provided through command line arguments or environment vars.");
static PyTypeObject FlagsType = {0, 0, 0, 0, 0, 0};
static PyStructSequence_Field flags_fields[] = {
- {"debug", "-d"},
- {"py3k_warning", "-3"},
- {"division_warning", "-Q"},
- {"division_new", "-Qnew"},
- {"inspect", "-i"},
- {"interactive", "-i"},
- {"optimize", "-O or -OO"},
- {"dont_write_bytecode", "-B"},
- {"no_user_site", "-s"},
- {"no_site", "-S"},
- {"ignore_environment", "-E"},
- {"tabcheck", "-t or -tt"},
- {"verbose", "-v"},
+ {"debug", "-d"},
+ {"py3k_warning", "-3"},
+ {"division_warning", "-Q"},
+ {"division_new", "-Qnew"},
+ {"inspect", "-i"},
+ {"interactive", "-i"},
+ {"optimize", "-O or -OO"},
+ {"dont_write_bytecode", "-B"},
+ {"no_user_site", "-s"},
+ {"no_site", "-S"},
+ {"ignore_environment", "-E"},
+ {"tabcheck", "-t or -tt"},
+ {"verbose", "-v"},
#ifdef RISCOS
- {"riscos_wimp", "???"},
+ {"riscos_wimp", "???"},
#endif
- /* {"unbuffered", "-u"}, */
- {"unicode", "-U"},
- /* {"skip_first", "-x"}, */
- {"bytes_warning", "-b"},
- {0}
+ /* {"unbuffered", "-u"}, */
+ {"unicode", "-U"},
+ /* {"skip_first", "-x"}, */
+ {"bytes_warning", "-b"},
+ {0}
};
static PyStructSequence_Desc flags_desc = {
- "sys.flags", /* name */
- flags__doc__, /* doc */
- flags_fields, /* fields */
+ "sys.flags", /* name */
+ flags__doc__, /* doc */
+ flags_fields, /* fields */
#ifdef RISCOS
- 16
+ 16
#else
- 15
+ 15
#endif
};
static PyObject*
make_flags(void)
{
- int pos = 0;
- PyObject *seq;
+ int pos = 0;
+ PyObject *seq;
- seq = PyStructSequence_New(&FlagsType);
- if (seq == NULL)
- return NULL;
+ seq = PyStructSequence_New(&FlagsType);
+ if (seq == NULL)
+ return NULL;
#define SetFlag(flag) \
- PyStructSequence_SET_ITEM(seq, pos++, PyInt_FromLong(flag))
-
- SetFlag(Py_DebugFlag);
- SetFlag(Py_Py3kWarningFlag);
- SetFlag(Py_DivisionWarningFlag);
- SetFlag(_Py_QnewFlag);
- SetFlag(Py_InspectFlag);
- SetFlag(Py_InteractiveFlag);
- SetFlag(Py_OptimizeFlag);
- SetFlag(Py_DontWriteBytecodeFlag);
- SetFlag(Py_NoUserSiteDirectory);
- SetFlag(Py_NoSiteFlag);
- SetFlag(Py_IgnoreEnvironmentFlag);
- SetFlag(Py_TabcheckFlag);
- SetFlag(Py_VerboseFlag);
+ PyStructSequence_SET_ITEM(seq, pos++, PyInt_FromLong(flag))
+
+ SetFlag(Py_DebugFlag);
+ SetFlag(Py_Py3kWarningFlag);
+ SetFlag(Py_DivisionWarningFlag);
+ SetFlag(_Py_QnewFlag);
+ SetFlag(Py_InspectFlag);
+ SetFlag(Py_InteractiveFlag);
+ SetFlag(Py_OptimizeFlag);
+ SetFlag(Py_DontWriteBytecodeFlag);
+ SetFlag(Py_NoUserSiteDirectory);
+ SetFlag(Py_NoSiteFlag);
+ SetFlag(Py_IgnoreEnvironmentFlag);
+ SetFlag(Py_TabcheckFlag);
+ SetFlag(Py_VerboseFlag);
#ifdef RISCOS
- SetFlag(Py_RISCOSWimpFlag);
+ SetFlag(Py_RISCOSWimpFlag);
#endif
- /* SetFlag(saw_unbuffered_flag); */
- SetFlag(Py_UnicodeFlag);
- /* SetFlag(skipfirstline); */
+ /* SetFlag(saw_unbuffered_flag); */
+ SetFlag(Py_UnicodeFlag);
+ /* SetFlag(skipfirstline); */
SetFlag(Py_BytesWarningFlag);
#undef SetFlag
- if (PyErr_Occurred()) {
- return NULL;
- }
- return seq;
+ if (PyErr_Occurred()) {
+ return NULL;
+ }
+ return seq;
}
PyDoc_STRVAR(version_info__doc__,
@@ -1328,428 +1328,428 @@ Version information as a named tuple.");
static PyTypeObject VersionInfoType = {0, 0, 0, 0, 0, 0};
static PyStructSequence_Field version_info_fields[] = {
- {"major", "Major release number"},
- {"minor", "Minor release number"},
- {"micro", "Patch release number"},
- {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
- {"serial", "Serial release number"},
- {0}
+ {"major", "Major release number"},
+ {"minor", "Minor release number"},
+ {"micro", "Patch release number"},
+ {"releaselevel", "'alpha', 'beta', 'candidate', or 'release'"},
+ {"serial", "Serial release number"},
+ {0}
};
static PyStructSequence_Desc version_info_desc = {
- "sys.version_info", /* name */
- version_info__doc__, /* doc */
- version_info_fields, /* fields */
- 5
+ "sys.version_info", /* name */
+ version_info__doc__, /* doc */
+ version_info_fields, /* fields */
+ 5
};
static PyObject *
make_version_info(void)
{
- PyObject *version_info;
- char *s;
- int pos = 0;
-
- version_info = PyStructSequence_New(&VersionInfoType);
- if (version_info == NULL) {
- return NULL;
- }
-
- /*
- * These release level checks are mutually exclusive and cover
- * the field, so don't get too fancy with the pre-processor!
- */
+ PyObject *version_info;
+ char *s;
+ int pos = 0;
+
+ version_info = PyStructSequence_New(&VersionInfoType);
+ if (version_info == NULL) {
+ return NULL;
+ }
+
+ /*
+ * These release level checks are mutually exclusive and cover
+ * the field, so don't get too fancy with the pre-processor!
+ */
#if PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_ALPHA
- s = "alpha";
+ s = "alpha";
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_BETA
- s = "beta";
+ s = "beta";
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_GAMMA
- s = "candidate";
+ s = "candidate";
#elif PY_RELEASE_LEVEL == PY_RELEASE_LEVEL_FINAL
- s = "final";
+ s = "final";
#endif
#define SetIntItem(flag) \
- PyStructSequence_SET_ITEM(version_info, pos++, PyInt_FromLong(flag))
+ PyStructSequence_SET_ITEM(version_info, pos++, PyInt_FromLong(flag))
#define SetStrItem(flag) \
- PyStructSequence_SET_ITEM(version_info, pos++, PyString_FromString(flag))
+ PyStructSequence_SET_ITEM(version_info, pos++, PyString_FromString(flag))
- SetIntItem(PY_MAJOR_VERSION);
- SetIntItem(PY_MINOR_VERSION);
- SetIntItem(PY_MICRO_VERSION);
- SetStrItem(s);
- SetIntItem(PY_RELEASE_SERIAL);
+ SetIntItem(PY_MAJOR_VERSION);
+ SetIntItem(PY_MINOR_VERSION);
+ SetIntItem(PY_MICRO_VERSION);
+ SetStrItem(s);
+ SetIntItem(PY_RELEASE_SERIAL);
#undef SetIntItem
#undef SetStrItem
- if (PyErr_Occurred()) {
- Py_CLEAR(version_info);
- return NULL;
- }
- return version_info;
+ if (PyErr_Occurred()) {
+ Py_CLEAR(version_info);
+ return NULL;
+ }
+ return version_info;
}
PyObject *
_PySys_Init(void)
{
- PyObject *m, *v, *sysdict;
- PyObject *sysin, *sysout, *syserr;
- char *s;
-
- m = Py_InitModule3("sys", sys_methods, sys_doc);
- if (m == NULL)
- return NULL;
- sysdict = PyModule_GetDict(m);
-#define SET_SYS_FROM_STRING(key, value) \
- v = value; \
- if (v != NULL) \
- PyDict_SetItemString(sysdict, key, v); \
- Py_XDECREF(v)
-
- /* Check that stdin is not a directory
- Using shell redirection, you can redirect stdin to a directory,
- crashing the Python interpreter. Catch this common mistake here
- and output a useful error message. Note that under MS Windows,
- the shell already prevents that. */
+ PyObject *m, *v, *sysdict;
+ PyObject *sysin, *sysout, *syserr;
+ char *s;
+
+ m = Py_InitModule3("sys", sys_methods, sys_doc);
+ if (m == NULL)
+ return NULL;
+ sysdict = PyModule_GetDict(m);
+#define SET_SYS_FROM_STRING(key, value) \
+ v = value; \
+ if (v != NULL) \
+ PyDict_SetItemString(sysdict, key, v); \
+ Py_XDECREF(v)
+
+ /* Check that stdin is not a directory
+ Using shell redirection, you can redirect stdin to a directory,
+ crashing the Python interpreter. Catch this common mistake here
+ and output a useful error message. Note that under MS Windows,
+ the shell already prevents that. */
#if !defined(MS_WINDOWS)
- {
- struct stat sb;
- if (fstat(fileno(stdin), &sb) == 0 &&
- S_ISDIR(sb.st_mode)) {
- /* There's nothing more we can do. */
- /* Py_FatalError() will core dump, so just exit. */
- PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
- exit(EXIT_FAILURE);
- }
- }
+ {
+ struct stat sb;
+ if (fstat(fileno(stdin), &sb) == 0 &&
+ S_ISDIR(sb.st_mode)) {
+ /* There's nothing more we can do. */
+ /* Py_FatalError() will core dump, so just exit. */
+ PySys_WriteStderr("Python error: <stdin> is a directory, cannot continue\n");
+ exit(EXIT_FAILURE);
+ }
+ }
#endif
- /* Closing the standard FILE* if sys.std* goes aways causes problems
- * for embedded Python usages. Closing them when somebody explicitly
- * invokes .close() might be possible, but the FAQ promises they get
- * never closed. However, we still need to get write errors when
- * writing fails (e.g. because stdout is redirected), so we flush the
- * streams and check for errors before the file objects are deleted.
- * On OS X, fflush()ing stdin causes an error, so we exempt stdin
- * from that procedure.
- */
- sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
- sysout = PyFile_FromFile(stdout, "<stdout>", "w", _check_and_flush);
- syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);
- if (PyErr_Occurred())
- return NULL;
-
- PyDict_SetItemString(sysdict, "stdin", sysin);
- PyDict_SetItemString(sysdict, "stdout", sysout);
- PyDict_SetItemString(sysdict, "stderr", syserr);
- /* Make backup copies for cleanup */
- PyDict_SetItemString(sysdict, "__stdin__", sysin);
- PyDict_SetItemString(sysdict, "__stdout__", sysout);
- PyDict_SetItemString(sysdict, "__stderr__", syserr);
- PyDict_SetItemString(sysdict, "__displayhook__",
- PyDict_GetItemString(sysdict, "displayhook"));
- PyDict_SetItemString(sysdict, "__excepthook__",
- PyDict_GetItemString(sysdict, "excepthook"));
- Py_XDECREF(sysin);
- Py_XDECREF(sysout);
- Py_XDECREF(syserr);
-
- SET_SYS_FROM_STRING("version",
- PyString_FromString(Py_GetVersion()));
- SET_SYS_FROM_STRING("hexversion",
- PyInt_FromLong(PY_VERSION_HEX));
- svnversion_init();
- SET_SYS_FROM_STRING("subversion",
- Py_BuildValue("(ssz)", "CPython", branch,
- svn_revision));
- SET_SYS_FROM_STRING("dont_write_bytecode",
- PyBool_FromLong(Py_DontWriteBytecodeFlag));
- SET_SYS_FROM_STRING("api_version",
- PyInt_FromLong(PYTHON_API_VERSION));
- SET_SYS_FROM_STRING("copyright",
- PyString_FromString(Py_GetCopyright()));
- SET_SYS_FROM_STRING("platform",
- PyString_FromString(Py_GetPlatform()));
- SET_SYS_FROM_STRING("executable",
- PyString_FromString(Py_GetProgramFullPath()));
- SET_SYS_FROM_STRING("prefix",
- PyString_FromString(Py_GetPrefix()));
- SET_SYS_FROM_STRING("exec_prefix",
- PyString_FromString(Py_GetExecPrefix()));
- SET_SYS_FROM_STRING("maxsize",
- PyInt_FromSsize_t(PY_SSIZE_T_MAX));
- SET_SYS_FROM_STRING("maxint",
- PyInt_FromLong(PyInt_GetMax()));
- SET_SYS_FROM_STRING("py3kwarning",
- PyBool_FromLong(Py_Py3kWarningFlag));
- SET_SYS_FROM_STRING("float_info",
- PyFloat_GetInfo());
- SET_SYS_FROM_STRING("long_info",
- PyLong_GetInfo());
+ /* Closing the standard FILE* if sys.std* goes aways causes problems
+ * for embedded Python usages. Closing them when somebody explicitly
+ * invokes .close() might be possible, but the FAQ promises they get
+ * never closed. However, we still need to get write errors when
+ * writing fails (e.g. because stdout is redirected), so we flush the
+ * streams and check for errors before the file objects are deleted.
+ * On OS X, fflush()ing stdin causes an error, so we exempt stdin
+ * from that procedure.
+ */
+ sysin = PyFile_FromFile(stdin, "<stdin>", "r", NULL);
+ sysout = PyFile_FromFile(stdout, "<stdout>", "w", _check_and_flush);
+ syserr = PyFile_FromFile(stderr, "<stderr>", "w", _check_and_flush);
+ if (PyErr_Occurred())
+ return NULL;
+
+ PyDict_SetItemString(sysdict, "stdin", sysin);
+ PyDict_SetItemString(sysdict, "stdout", sysout);
+ PyDict_SetItemString(sysdict, "stderr", syserr);
+ /* Make backup copies for cleanup */
+ PyDict_SetItemString(sysdict, "__stdin__", sysin);
+ PyDict_SetItemString(sysdict, "__stdout__", sysout);
+ PyDict_SetItemString(sysdict, "__stderr__", syserr);
+ PyDict_SetItemString(sysdict, "__displayhook__",
+ PyDict_GetItemString(sysdict, "displayhook"));
+ PyDict_SetItemString(sysdict, "__excepthook__",
+ PyDict_GetItemString(sysdict, "excepthook"));
+ Py_XDECREF(sysin);
+ Py_XDECREF(sysout);
+ Py_XDECREF(syserr);
+
+ SET_SYS_FROM_STRING("version",
+ PyString_FromString(Py_GetVersion()));
+ SET_SYS_FROM_STRING("hexversion",
+ PyInt_FromLong(PY_VERSION_HEX));
+ svnversion_init();
+ SET_SYS_FROM_STRING("subversion",
+ Py_BuildValue("(ssz)", "CPython", branch,
+ svn_revision));
+ SET_SYS_FROM_STRING("dont_write_bytecode",
+ PyBool_FromLong(Py_DontWriteBytecodeFlag));
+ SET_SYS_FROM_STRING("api_version",
+ PyInt_FromLong(PYTHON_API_VERSION));
+ SET_SYS_FROM_STRING("copyright",
+ PyString_FromString(Py_GetCopyright()));
+ SET_SYS_FROM_STRING("platform",
+ PyString_FromString(Py_GetPlatform()));
+ SET_SYS_FROM_STRING("executable",
+ PyString_FromString(Py_GetProgramFullPath()));
+ SET_SYS_FROM_STRING("prefix",
+ PyString_FromString(Py_GetPrefix()));
+ SET_SYS_FROM_STRING("exec_prefix",
+ PyString_FromString(Py_GetExecPrefix()));
+ SET_SYS_FROM_STRING("maxsize",
+ PyInt_FromSsize_t(PY_SSIZE_T_MAX));
+ SET_SYS_FROM_STRING("maxint",
+ PyInt_FromLong(PyInt_GetMax()));
+ SET_SYS_FROM_STRING("py3kwarning",
+ PyBool_FromLong(Py_Py3kWarningFlag));
+ SET_SYS_FROM_STRING("float_info",
+ PyFloat_GetInfo());
+ SET_SYS_FROM_STRING("long_info",
+ PyLong_GetInfo());
#ifdef Py_USING_UNICODE
- SET_SYS_FROM_STRING("maxunicode",
- PyInt_FromLong(PyUnicode_GetMax()));
+ SET_SYS_FROM_STRING("maxunicode",
+ PyInt_FromLong(PyUnicode_GetMax()));
#endif
- SET_SYS_FROM_STRING("builtin_module_names",
- list_builtin_module_names());
- {
- /* Assumes that longs are at least 2 bytes long.
- Should be safe! */
- unsigned long number = 1;
- char *value;
-
- s = (char *) &number;
- if (s[0] == 0)
- value = "big";
- else
- value = "little";
- SET_SYS_FROM_STRING("byteorder",
- PyString_FromString(value));
- }
+ SET_SYS_FROM_STRING("builtin_module_names",
+ list_builtin_module_names());
+ {
+ /* Assumes that longs are at least 2 bytes long.
+ Should be safe! */
+ unsigned long number = 1;
+ char *value;
+
+ s = (char *) &number;
+ if (s[0] == 0)
+ value = "big";
+ else
+ value = "little";
+ SET_SYS_FROM_STRING("byteorder",
+ PyString_FromString(value));
+ }
#ifdef MS_COREDLL
- SET_SYS_FROM_STRING("dllhandle",
- PyLong_FromVoidPtr(PyWin_DLLhModule));
- SET_SYS_FROM_STRING("winver",
- PyString_FromString(PyWin_DLLVersionString));
+ SET_SYS_FROM_STRING("dllhandle",
+ PyLong_FromVoidPtr(PyWin_DLLhModule));
+ SET_SYS_FROM_STRING("winver",
+ PyString_FromString(PyWin_DLLVersionString));
#endif
- if (warnoptions == NULL) {
- warnoptions = PyList_New(0);
- }
- else {
- Py_INCREF(warnoptions);
- }
- if (warnoptions != NULL) {
- PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
- }
-
- /* version_info */
- if (VersionInfoType.tp_name == 0)
- PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
- SET_SYS_FROM_STRING("version_info", make_version_info());
- /* prevent user from creating new instances */
- VersionInfoType.tp_init = NULL;
- VersionInfoType.tp_new = NULL;
-
- /* flags */
- if (FlagsType.tp_name == 0)
- PyStructSequence_InitType(&FlagsType, &flags_desc);
- SET_SYS_FROM_STRING("flags", make_flags());
- /* prevent user from creating new instances */
- FlagsType.tp_init = NULL;
- FlagsType.tp_new = NULL;
+ if (warnoptions == NULL) {
+ warnoptions = PyList_New(0);
+ }
+ else {
+ Py_INCREF(warnoptions);
+ }
+ if (warnoptions != NULL) {
+ PyDict_SetItemString(sysdict, "warnoptions", warnoptions);
+ }
+
+ /* version_info */
+ if (VersionInfoType.tp_name == 0)
+ PyStructSequence_InitType(&VersionInfoType, &version_info_desc);
+ SET_SYS_FROM_STRING("version_info", make_version_info());
+ /* prevent user from creating new instances */
+ VersionInfoType.tp_init = NULL;
+ VersionInfoType.tp_new = NULL;
+
+ /* flags */
+ if (FlagsType.tp_name == 0)
+ PyStructSequence_InitType(&FlagsType, &flags_desc);
+ SET_SYS_FROM_STRING("flags", make_flags());
+ /* prevent user from creating new instances */
+ FlagsType.tp_init = NULL;
+ FlagsType.tp_new = NULL;
#if defined(MS_WINDOWS)
- /* getwindowsversion */
- if (WindowsVersionType.tp_name == 0)
- PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
- /* prevent user from creating new instances */
- WindowsVersionType.tp_init = NULL;
- WindowsVersionType.tp_new = NULL;
+ /* getwindowsversion */
+ if (WindowsVersionType.tp_name == 0)
+ PyStructSequence_InitType(&WindowsVersionType, &windows_version_desc);
+ /* prevent user from creating new instances */
+ WindowsVersionType.tp_init = NULL;
+ WindowsVersionType.tp_new = NULL;
#endif
- /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
+ /* float repr style: 0.03 (short) vs 0.029999999999999999 (legacy) */
#ifndef PY_NO_SHORT_FLOAT_REPR
- SET_SYS_FROM_STRING("float_repr_style",
- PyString_FromString("short"));
+ SET_SYS_FROM_STRING("float_repr_style",
+ PyString_FromString("short"));
#else
- SET_SYS_FROM_STRING("float_repr_style",
- PyString_FromString("legacy"));
+ SET_SYS_FROM_STRING("float_repr_style",
+ PyString_FromString("legacy"));
#endif
#undef SET_SYS_FROM_STRING
- if (PyErr_Occurred())
- return NULL;
- return m;
+ if (PyErr_Occurred())
+ return NULL;
+ return m;
}
static PyObject *
makepathobject(char *path, int delim)
{
- int i, n;
- char *p;
- PyObject *v, *w;
-
- n = 1;
- p = path;
- while ((p = strchr(p, delim)) != NULL) {
- n++;
- p++;
- }
- v = PyList_New(n);
- if (v == NULL)
- return NULL;
- for (i = 0; ; i++) {
- p = strchr(path, delim);
- if (p == NULL)
- p = strchr(path, '\0'); /* End of string */
- w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));
- if (w == NULL) {
- Py_DECREF(v);
- return NULL;
- }
- PyList_SetItem(v, i, w);
- if (*p == '\0')
- break;
- path = p+1;
- }
- return v;
+ int i, n;
+ char *p;
+ PyObject *v, *w;
+
+ n = 1;
+ p = path;
+ while ((p = strchr(p, delim)) != NULL) {
+ n++;
+ p++;
+ }
+ v = PyList_New(n);
+ if (v == NULL)
+ return NULL;
+ for (i = 0; ; i++) {
+ p = strchr(path, delim);
+ if (p == NULL)
+ p = strchr(path, '\0'); /* End of string */
+ w = PyString_FromStringAndSize(path, (Py_ssize_t) (p - path));
+ if (w == NULL) {
+ Py_DECREF(v);
+ return NULL;
+ }
+ PyList_SetItem(v, i, w);
+ if (*p == '\0')
+ break;
+ path = p+1;
+ }
+ return v;
}
void
PySys_SetPath(char *path)
{
- PyObject *v;
- if ((v = makepathobject(path, DELIM)) == NULL)
- Py_FatalError("can't create sys.path");
- if (PySys_SetObject("path", v) != 0)
- Py_FatalError("can't assign sys.path");
- Py_DECREF(v);
+ PyObject *v;
+ if ((v = makepathobject(path, DELIM)) == NULL)
+ Py_FatalError("can't create sys.path");
+ if (PySys_SetObject("path", v) != 0)
+ Py_FatalError("can't assign sys.path");
+ Py_DECREF(v);
}
static PyObject *
makeargvobject(int argc, char **argv)
{
- PyObject *av;
- if (argc <= 0 || argv == NULL) {
- /* Ensure at least one (empty) argument is seen */
- static char *empty_argv[1] = {""};
- argv = empty_argv;
- argc = 1;
- }
- av = PyList_New(argc);
- if (av != NULL) {
- int i;
- for (i = 0; i < argc; i++) {
+ PyObject *av;
+ if (argc <= 0 || argv == NULL) {
+ /* Ensure at least one (empty) argument is seen */
+ static char *empty_argv[1] = {""};
+ argv = empty_argv;
+ argc = 1;
+ }
+ av = PyList_New(argc);
+ if (av != NULL) {
+ int i;
+ for (i = 0; i < argc; i++) {
#ifdef __VMS
- PyObject *v;
-
- /* argv[0] is the script pathname if known */
- if (i == 0) {
- char* fn = decc$translate_vms(argv[0]);
- if ((fn == (char *)0) || fn == (char *)-1)
- v = PyString_FromString(argv[0]);
- else
- v = PyString_FromString(
- decc$translate_vms(argv[0]));
- } else
- v = PyString_FromString(argv[i]);
+ PyObject *v;
+
+ /* argv[0] is the script pathname if known */
+ if (i == 0) {
+ char* fn = decc$translate_vms(argv[0]);
+ if ((fn == (char *)0) || fn == (char *)-1)
+ v = PyString_FromString(argv[0]);
+ else
+ v = PyString_FromString(
+ decc$translate_vms(argv[0]));
+ } else
+ v = PyString_FromString(argv[i]);
#else
- PyObject *v = PyString_FromString(argv[i]);
+ PyObject *v = PyString_FromString(argv[i]);
#endif
- if (v == NULL) {
- Py_DECREF(av);
- av = NULL;
- break;
- }
- PyList_SetItem(av, i, v);
- }
- }
- return av;
+ if (v == NULL) {
+ Py_DECREF(av);
+ av = NULL;
+ break;
+ }
+ PyList_SetItem(av, i, v);
+ }
+ }
+ return av;
}
void
PySys_SetArgv(int argc, char **argv)
{
#if defined(HAVE_REALPATH)
- char fullpath[MAXPATHLEN];
+ char fullpath[MAXPATHLEN];
#elif defined(MS_WINDOWS) && !defined(MS_WINCE)
- char fullpath[MAX_PATH];
+ char fullpath[MAX_PATH];
#endif
- PyObject *av = makeargvobject(argc, argv);
- PyObject *path = PySys_GetObject("path");
- if (av == NULL)
- Py_FatalError("no mem for sys.argv");
- if (PySys_SetObject("argv", av) != 0)
- Py_FatalError("can't assign sys.argv");
- if (path != NULL) {
- char *argv0 = argv[0];
- char *p = NULL;
- Py_ssize_t n = 0;
- PyObject *a;
+ PyObject *av = makeargvobject(argc, argv);
+ PyObject *path = PySys_GetObject("path");
+ if (av == NULL)
+ Py_FatalError("no mem for sys.argv");
+ if (PySys_SetObject("argv", av) != 0)
+ Py_FatalError("can't assign sys.argv");
+ if (path != NULL) {
+ char *argv0 = argv[0];
+ char *p = NULL;
+ Py_ssize_t n = 0;
+ PyObject *a;
#ifdef HAVE_READLINK
- char link[MAXPATHLEN+1];
- char argv0copy[2*MAXPATHLEN+1];
- int nr = 0;
- if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)
- nr = readlink(argv0, link, MAXPATHLEN);
- if (nr > 0) {
- /* It's a symlink */
- link[nr] = '\0';
- if (link[0] == SEP)
- argv0 = link; /* Link to absolute path */
- else if (strchr(link, SEP) == NULL)
- ; /* Link without path */
- else {
- /* Must join(dirname(argv0), link) */
- char *q = strrchr(argv0, SEP);
- if (q == NULL)
- argv0 = link; /* argv0 without path */
- else {
- /* Must make a copy */
- strcpy(argv0copy, argv0);
- q = strrchr(argv0copy, SEP);
- strcpy(q+1, link);
- argv0 = argv0copy;
- }
- }
- }
+ char link[MAXPATHLEN+1];
+ char argv0copy[2*MAXPATHLEN+1];
+ int nr = 0;
+ if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0)
+ nr = readlink(argv0, link, MAXPATHLEN);
+ if (nr > 0) {
+ /* It's a symlink */
+ link[nr] = '\0';
+ if (link[0] == SEP)
+ argv0 = link; /* Link to absolute path */
+ else if (strchr(link, SEP) == NULL)
+ ; /* Link without path */
+ else {
+ /* Must join(dirname(argv0), link) */
+ char *q = strrchr(argv0, SEP);
+ if (q == NULL)
+ argv0 = link; /* argv0 without path */
+ else {
+ /* Must make a copy */
+ strcpy(argv0copy, argv0);
+ q = strrchr(argv0copy, SEP);
+ strcpy(q+1, link);
+ argv0 = argv0copy;
+ }
+ }
+ }
#endif /* HAVE_READLINK */
#if SEP == '\\' /* Special case for MS filename syntax */
- if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
- char *q;
+ if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
+ char *q;
#if defined(MS_WINDOWS) && !defined(MS_WINCE)
- /* This code here replaces the first element in argv with the full
- path that it represents. Under CE, there are no relative paths so
- the argument must be the full path anyway. */
- char *ptemp;
- if (GetFullPathName(argv0,
- sizeof(fullpath),
- fullpath,
- &ptemp)) {
- argv0 = fullpath;
- }
+ /* This code here replaces the first element in argv with the full
+ path that it represents. Under CE, there are no relative paths so
+ the argument must be the full path anyway. */
+ char *ptemp;
+ if (GetFullPathName(argv0,
+ sizeof(fullpath),
+ fullpath,
+ &ptemp)) {
+ argv0 = fullpath;
+ }
#endif
- p = strrchr(argv0, SEP);
- /* Test for alternate separator */
- q = strrchr(p ? p : argv0, '/');
- if (q != NULL)
- p = q;
- if (p != NULL) {
- n = p + 1 - argv0;
- if (n > 1 && p[-1] != ':')
- n--; /* Drop trailing separator */
- }
- }
+ p = strrchr(argv0, SEP);
+ /* Test for alternate separator */
+ q = strrchr(p ? p : argv0, '/');
+ if (q != NULL)
+ p = q;
+ if (p != NULL) {
+ n = p + 1 - argv0;
+ if (n > 1 && p[-1] != ':')
+ n--; /* Drop trailing separator */
+ }
+ }
#else /* All other filename syntaxes */
- if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
+ if (argc > 0 && argv0 != NULL && strcmp(argv0, "-c") != 0) {
#if defined(HAVE_REALPATH)
- if (realpath(argv0, fullpath)) {
- argv0 = fullpath;
- }
+ if (realpath(argv0, fullpath)) {
+ argv0 = fullpath;
+ }
#endif
- p = strrchr(argv0, SEP);
- }
- if (p != NULL) {
+ p = strrchr(argv0, SEP);
+ }
+ if (p != NULL) {
#ifndef RISCOS
- n = p + 1 - argv0;
+ n = p + 1 - argv0;
#else /* don't include trailing separator */
- n = p - argv0;
+ n = p - argv0;
#endif /* RISCOS */
#if SEP == '/' /* Special case for Unix filename syntax */
- if (n > 1)
- n--; /* Drop trailing separator */
+ if (n > 1)
+ n--; /* Drop trailing separator */
#endif /* Unix */
- }
+ }
#endif /* All others */
- a = PyString_FromStringAndSize(argv0, n);
- if (a == NULL)
- Py_FatalError("no mem for sys.path insertion");
- if (PyList_Insert(path, 0, a) < 0)
- Py_FatalError("sys.path.insert(0) failed");
- Py_DECREF(a);
- }
- Py_DECREF(av);
+ a = PyString_FromStringAndSize(argv0, n);
+ if (a == NULL)
+ Py_FatalError("no mem for sys.path insertion");
+ if (PyList_Insert(path, 0, a) < 0)
+ Py_FatalError("sys.path.insert(0) failed");
+ Py_DECREF(a);
+ }
+ Py_DECREF(av);
}
@@ -1780,48 +1780,48 @@ PySys_SetArgv(int argc, char **argv)
static void
mywrite(char *name, FILE *fp, const char *format, va_list va)
{
- PyObject *file;
- PyObject *error_type, *error_value, *error_traceback;
-
- PyErr_Fetch(&error_type, &error_value, &error_traceback);
- file = PySys_GetObject(name);
- if (file == NULL || PyFile_AsFile(file) == fp)
- vfprintf(fp, format, va);
- else {
- char buffer[1001];
- const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
- format, va);
- if (PyFile_WriteString(buffer, file) != 0) {
- PyErr_Clear();
- fputs(buffer, fp);
- }
- if (written < 0 || (size_t)written >= sizeof(buffer)) {
- const char *truncated = "... truncated";
- if (PyFile_WriteString(truncated, file) != 0) {
- PyErr_Clear();
- fputs(truncated, fp);
- }
- }
- }
- PyErr_Restore(error_type, error_value, error_traceback);
+ PyObject *file;
+ PyObject *error_type, *error_value, *error_traceback;
+
+ PyErr_Fetch(&error_type, &error_value, &error_traceback);
+ file = PySys_GetObject(name);
+ if (file == NULL || PyFile_AsFile(file) == fp)
+ vfprintf(fp, format, va);
+ else {
+ char buffer[1001];
+ const int written = PyOS_vsnprintf(buffer, sizeof(buffer),
+ format, va);
+ if (PyFile_WriteString(buffer, file) != 0) {
+ PyErr_Clear();
+ fputs(buffer, fp);
+ }
+ if (written < 0 || (size_t)written >= sizeof(buffer)) {
+ const char *truncated = "... truncated";
+ if (PyFile_WriteString(truncated, file) != 0) {
+ PyErr_Clear();
+ fputs(truncated, fp);
+ }
+ }
+ }
+ PyErr_Restore(error_type, error_value, error_traceback);
}
void
PySys_WriteStdout(const char *format, ...)
{
- va_list va;
+ va_list va;
- va_start(va, format);
- mywrite("stdout", stdout, format, va);
- va_end(va);
+ va_start(va, format);
+ mywrite("stdout", stdout, format, va);
+ va_end(va);
}
void
PySys_WriteStderr(const char *format, ...)
{
- va_list va;
+ va_list va;
- va_start(va, format);
- mywrite("stderr", stderr, format, va);
- va_end(va);
+ va_start(va, format);
+ mywrite("stderr", stderr, format, va);
+ va_end(va);
}
diff --git a/Python/thread.c b/Python/thread.c
index ff571d8..1578f82 100644
--- a/Python/thread.c
+++ b/Python/thread.c
@@ -46,7 +46,7 @@
#endif
/* Check if we're running on HP-UX and _SC_THREADS is defined. If so, then
- enough of the Posix threads package is implimented to support python
+ enough of the Posix threads package is implimented to support python
threads.
This is valid for HP-UX 11.23 running on an ia64 system. If needed, add
@@ -64,8 +64,8 @@
#ifdef Py_DEBUG
static int thread_debug = 0;
-#define dprintf(args) (void)((thread_debug & 1) && printf args)
-#define d2printf(args) ((thread_debug & 8) && printf args)
+#define dprintf(args) (void)((thread_debug & 1) && printf args)
+#define d2printf(args) ((thread_debug & 8) && printf args)
#else
#define dprintf(args)
#define d2printf(args)
@@ -79,20 +79,20 @@ void
PyThread_init_thread(void)
{
#ifdef Py_DEBUG
- char *p = Py_GETENV("PYTHONTHREADDEBUG");
-
- if (p) {
- if (*p)
- thread_debug = atoi(p);
- else
- thread_debug = 1;
- }
+ char *p = Py_GETENV("PYTHONTHREADDEBUG");
+
+ if (p) {
+ if (*p)
+ thread_debug = atoi(p);
+ else
+ thread_debug = 1;
+ }
#endif /* Py_DEBUG */
- if (initialized)
- return;
- initialized = 1;
- dprintf(("PyThread_init_thread called\n"));
- PyThread__init_thread();
+ if (initialized)
+ return;
+ initialized = 1;
+ dprintf(("PyThread_init_thread called\n"));
+ PyThread__init_thread();
}
/* Support for runtime thread stack size tuning.
@@ -155,21 +155,21 @@ static size_t _pythread_stacksize = 0;
size_t
PyThread_get_stacksize(void)
{
- return _pythread_stacksize;
+ return _pythread_stacksize;
}
/* Only platforms defining a THREAD_SET_STACKSIZE() macro
in thread_<platform>.h support changing the stack size.
Return 0 if stack size is valid,
- -1 if stack size value is invalid,
- -2 if setting stack size is not supported. */
+ -1 if stack size value is invalid,
+ -2 if setting stack size is not supported. */
int
PyThread_set_stacksize(size_t size)
{
#if defined(THREAD_SET_STACKSIZE)
- return THREAD_SET_STACKSIZE(size);
+ return THREAD_SET_STACKSIZE(size);
#else
- return -2;
+ return -2;
#endif
}
@@ -221,15 +221,15 @@ that calls to PyThread_create_key() are serialized externally.
* to enforce exclusion internally.
*/
struct key {
- /* Next record in the list, or NULL if this is the last record. */
- struct key *next;
+ /* Next record in the list, or NULL if this is the last record. */
+ struct key *next;
- /* The thread id, according to PyThread_get_thread_ident(). */
- long id;
+ /* The thread id, according to PyThread_get_thread_ident(). */
+ long id;
- /* The key and its associated value. */
- int key;
- void *value;
+ /* The key and its associated value. */
+ int key;
+ void *value;
};
static struct key *keyhead = NULL;
@@ -260,41 +260,41 @@ static int nkeys = 0; /* PyThread_create_key() hands out nkeys+1 next */
static struct key *
find_key(int key, void *value)
{
- struct key *p, *prev_p;
- long id = PyThread_get_thread_ident();
-
- if (!keymutex)
- return NULL;
- PyThread_acquire_lock(keymutex, 1);
- prev_p = NULL;
- for (p = keyhead; p != NULL; p = p->next) {
- if (p->id == id && p->key == key)
- goto Done;
- /* Sanity check. These states should never happen but if
- * they do we must abort. Otherwise we'll end up spinning in
- * in a tight loop with the lock held. A similar check is done
- * in pystate.c tstate_delete_common(). */
- if (p == prev_p)
- Py_FatalError("tls find_key: small circular list(!)");
- prev_p = p;
- if (p->next == keyhead)
- Py_FatalError("tls find_key: circular list(!)");
- }
- if (value == NULL) {
- assert(p == NULL);
- goto Done;
- }
- p = (struct key *)malloc(sizeof(struct key));
- if (p != NULL) {
- p->id = id;
- p->key = key;
- p->value = value;
- p->next = keyhead;
- keyhead = p;
- }
+ struct key *p, *prev_p;
+ long id = PyThread_get_thread_ident();
+
+ if (!keymutex)
+ return NULL;
+ PyThread_acquire_lock(keymutex, 1);
+ prev_p = NULL;
+ for (p = keyhead; p != NULL; p = p->next) {
+ if (p->id == id && p->key == key)
+ goto Done;
+ /* Sanity check. These states should never happen but if
+ * they do we must abort. Otherwise we'll end up spinning in
+ * in a tight loop with the lock held. A similar check is done
+ * in pystate.c tstate_delete_common(). */
+ if (p == prev_p)
+ Py_FatalError("tls find_key: small circular list(!)");
+ prev_p = p;
+ if (p->next == keyhead)
+ Py_FatalError("tls find_key: circular list(!)");
+ }
+ if (value == NULL) {
+ assert(p == NULL);
+ goto Done;
+ }
+ p = (struct key *)malloc(sizeof(struct key));
+ if (p != NULL) {
+ p->id = id;
+ p->key = key;
+ p->value = value;
+ p->next = keyhead;
+ keyhead = p;
+ }
Done:
- PyThread_release_lock(keymutex);
- return p;
+ PyThread_release_lock(keymutex);
+ return p;
}
/* Return a new key. This must be called before any other functions in
@@ -304,32 +304,32 @@ find_key(int key, void *value)
int
PyThread_create_key(void)
{
- /* All parts of this function are wrong if it's called by multiple
- * threads simultaneously.
- */
- if (keymutex == NULL)
- keymutex = PyThread_allocate_lock();
- return ++nkeys;
+ /* All parts of this function are wrong if it's called by multiple
+ * threads simultaneously.
+ */
+ if (keymutex == NULL)
+ keymutex = PyThread_allocate_lock();
+ return ++nkeys;
}
/* Forget the associations for key across *all* threads. */
void
PyThread_delete_key(int key)
{
- struct key *p, **q;
-
- PyThread_acquire_lock(keymutex, 1);
- q = &keyhead;
- while ((p = *q) != NULL) {
- if (p->key == key) {
- *q = p->next;
- free((void *)p);
- /* NB This does *not* free p->value! */
- }
- else
- q = &p->next;
- }
- PyThread_release_lock(keymutex);
+ struct key *p, **q;
+
+ PyThread_acquire_lock(keymutex, 1);
+ q = &keyhead;
+ while ((p = *q) != NULL) {
+ if (p->key == key) {
+ *q = p->next;
+ free((void *)p);
+ /* NB This does *not* free p->value! */
+ }
+ else
+ q = &p->next;
+ }
+ PyThread_release_lock(keymutex);
}
/* Confusing: If the current thread has an association for key,
@@ -341,14 +341,14 @@ PyThread_delete_key(int key)
int
PyThread_set_key_value(int key, void *value)
{
- struct key *p;
-
- assert(value != NULL);
- p = find_key(key, value);
- if (p == NULL)
- return -1;
- else
- return 0;
+ struct key *p;
+
+ assert(value != NULL);
+ p = find_key(key, value);
+ if (p == NULL)
+ return -1;
+ else
+ return 0;
}
/* Retrieve the value associated with key in the current thread, or NULL
@@ -357,34 +357,34 @@ PyThread_set_key_value(int key, void *value)
void *
PyThread_get_key_value(int key)
{
- struct key *p = find_key(key, NULL);
+ struct key *p = find_key(key, NULL);
- if (p == NULL)
- return NULL;
- else
- return p->value;
+ if (p == NULL)
+ return NULL;
+ else
+ return p->value;
}
/* Forget the current thread's association for key, if any. */
void
PyThread_delete_key_value(int key)
{
- long id = PyThread_get_thread_ident();
- struct key *p, **q;
-
- PyThread_acquire_lock(keymutex, 1);
- q = &keyhead;
- while ((p = *q) != NULL) {
- if (p->key == key && p->id == id) {
- *q = p->next;
- free((void *)p);
- /* NB This does *not* free p->value! */
- break;
- }
- else
- q = &p->next;
- }
- PyThread_release_lock(keymutex);
+ long id = PyThread_get_thread_ident();
+ struct key *p, **q;
+
+ PyThread_acquire_lock(keymutex, 1);
+ q = &keyhead;
+ while ((p = *q) != NULL) {
+ if (p->key == key && p->id == id) {
+ *q = p->next;
+ free((void *)p);
+ /* NB This does *not* free p->value! */
+ break;
+ }
+ else
+ q = &p->next;
+ }
+ PyThread_release_lock(keymutex);
}
/* Forget everything not associated with the current thread id.
@@ -395,27 +395,27 @@ PyThread_delete_key_value(int key)
void
PyThread_ReInitTLS(void)
{
- long id = PyThread_get_thread_ident();
- struct key *p, **q;
-
- if (!keymutex)
- return;
-
- /* As with interpreter_lock in PyEval_ReInitThreads()
- we just create a new lock without freeing the old one */
- keymutex = PyThread_allocate_lock();
-
- /* Delete all keys which do not match the current thread id */
- q = &keyhead;
- while ((p = *q) != NULL) {
- if (p->id != id) {
- *q = p->next;
- free((void *)p);
- /* NB This does *not* free p->value! */
- }
- else
- q = &p->next;
- }
+ long id = PyThread_get_thread_ident();
+ struct key *p, **q;
+
+ if (!keymutex)
+ return;
+
+ /* As with interpreter_lock in PyEval_ReInitThreads()
+ we just create a new lock without freeing the old one */
+ keymutex = PyThread_allocate_lock();
+
+ /* Delete all keys which do not match the current thread id */
+ q = &keyhead;
+ while ((p = *q) != NULL) {
+ if (p->id != id) {
+ *q = p->next;
+ free((void *)p);
+ /* NB This does *not* free p->value! */
+ }
+ else
+ q = &p->next;
+ }
}
#endif /* Py_HAVE_NATIVE_TLS */
diff --git a/Python/thread_atheos.h b/Python/thread_atheos.h
index 747a6a2..230594f 100644
--- a/Python/thread_atheos.h
+++ b/Python/thread_atheos.h
@@ -19,8 +19,8 @@ extern int exit_thread(int);
/* Use an atomic counter and a semaphore for maximum speed. */
typedef struct fastmutex {
- sem_id sem;
- atomic_t count;
+ sem_id sem;
+ atomic_t count;
} fastmutex_t;
@@ -33,49 +33,49 @@ static int fastmutex_unlock(fastmutex_t * mutex);
static int fastmutex_create(const char *name, fastmutex_t * mutex)
{
- mutex->count = 0;
- mutex->sem = create_semaphore(name, 0, 0);
- return (mutex->sem < 0) ? -1 : 0;
+ mutex->count = 0;
+ mutex->sem = create_semaphore(name, 0, 0);
+ return (mutex->sem < 0) ? -1 : 0;
}
static int fastmutex_destroy(fastmutex_t * mutex)
{
- if (fastmutex_timedlock(mutex, 0) == 0 || errno == EWOULDBLOCK) {
- return delete_semaphore(mutex->sem);
- }
- return 0;
+ if (fastmutex_timedlock(mutex, 0) == 0 || errno == EWOULDBLOCK) {
+ return delete_semaphore(mutex->sem);
+ }
+ return 0;
}
static int fastmutex_lock(fastmutex_t * mutex)
{
- atomic_t prev = atomic_add(&mutex->count, 1);
- if (prev > 0)
- return lock_semaphore(mutex->sem);
- return 0;
+ atomic_t prev = atomic_add(&mutex->count, 1);
+ if (prev > 0)
+ return lock_semaphore(mutex->sem);
+ return 0;
}
static int fastmutex_timedlock(fastmutex_t * mutex, bigtime_t timeout)
{
- atomic_t prev = atomic_add(&mutex->count, 1);
- if (prev > 0)
- return lock_semaphore_x(mutex->sem, 1, 0, timeout);
- return 0;
+ atomic_t prev = atomic_add(&mutex->count, 1);
+ if (prev > 0)
+ return lock_semaphore_x(mutex->sem, 1, 0, timeout);
+ return 0;
}
static int fastmutex_unlock(fastmutex_t * mutex)
{
- atomic_t prev = atomic_add(&mutex->count, -1);
- if (prev > 1)
- return unlock_semaphore(mutex->sem);
- return 0;
+ atomic_t prev = atomic_add(&mutex->count, -1);
+ if (prev > 1)
+ return unlock_semaphore(mutex->sem);
+ return 0;
}
-#endif /* FASTLOCK */
+#endif /* FASTLOCK */
/*
@@ -84,8 +84,8 @@ static int fastmutex_unlock(fastmutex_t * mutex)
*/
static void PyThread__init_thread(void)
{
- /* Do nothing. */
- return;
+ /* Do nothing. */
+ return;
}
@@ -98,48 +98,48 @@ static atomic_t thread_count = 0;
long PyThread_start_new_thread(void (*func) (void *), void *arg)
{
- status_t success = -1;
- thread_id tid;
- char name[OS_NAME_LENGTH];
- atomic_t this_thread;
-
- dprintf(("PyThread_start_new_thread called\n"));
-
- this_thread = atomic_add(&thread_count, 1);
- PyOS_snprintf(name, sizeof(name), "python thread (%d)", this_thread);
-
- tid = spawn_thread(name, func, NORMAL_PRIORITY, 0, arg);
- if (tid < 0) {
- dprintf(("PyThread_start_new_thread spawn_thread failed: %s\n", strerror(errno)));
- } else {
- success = resume_thread(tid);
- if (success < 0) {
- dprintf(("PyThread_start_new_thread resume_thread failed: %s\n", strerror(errno)));
- }
- }
-
- return (success < 0 ? -1 : tid);
+ status_t success = -1;
+ thread_id tid;
+ char name[OS_NAME_LENGTH];
+ atomic_t this_thread;
+
+ dprintf(("PyThread_start_new_thread called\n"));
+
+ this_thread = atomic_add(&thread_count, 1);
+ PyOS_snprintf(name, sizeof(name), "python thread (%d)", this_thread);
+
+ tid = spawn_thread(name, func, NORMAL_PRIORITY, 0, arg);
+ if (tid < 0) {
+ dprintf(("PyThread_start_new_thread spawn_thread failed: %s\n", strerror(errno)));
+ } else {
+ success = resume_thread(tid);
+ if (success < 0) {
+ dprintf(("PyThread_start_new_thread resume_thread failed: %s\n", strerror(errno)));
+ }
+ }
+
+ return (success < 0 ? -1 : tid);
}
long PyThread_get_thread_ident(void)
{
- return get_thread_id(NULL);
+ return get_thread_id(NULL);
}
void PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
-
- /* Thread-safe way to read a variable without a mutex: */
- if (atomic_add(&thread_count, 0) == 0) {
- /* No threads around, so exit main(). */
- exit(0);
- } else {
- /* We're a thread */
- exit_thread(0);
- }
+ dprintf(("PyThread_exit_thread called\n"));
+
+ /* Thread-safe way to read a variable without a mutex: */
+ if (atomic_add(&thread_count, 0) == 0) {
+ /* No threads around, so exit main(). */
+ exit(0);
+ } else {
+ /* We're a thread */
+ exit_thread(0);
+ }
}
@@ -153,107 +153,107 @@ static atomic_t lock_count = 0;
PyThread_type_lock PyThread_allocate_lock(void)
{
#ifdef FASTLOCK
- fastmutex_t *lock;
+ fastmutex_t *lock;
#else
- sem_id sema;
+ sem_id sema;
#endif
- char name[OS_NAME_LENGTH];
- atomic_t this_lock;
+ char name[OS_NAME_LENGTH];
+ atomic_t this_lock;
- dprintf(("PyThread_allocate_lock called\n"));
+ dprintf(("PyThread_allocate_lock called\n"));
#ifdef FASTLOCK
- lock = (fastmutex_t *) malloc(sizeof(fastmutex_t));
- if (lock == NULL) {
- dprintf(("PyThread_allocate_lock failed: out of memory\n"));
- return (PyThread_type_lock) NULL;
- }
+ lock = (fastmutex_t *) malloc(sizeof(fastmutex_t));
+ if (lock == NULL) {
+ dprintf(("PyThread_allocate_lock failed: out of memory\n"));
+ return (PyThread_type_lock) NULL;
+ }
#endif
- this_lock = atomic_add(&lock_count, 1);
- PyOS_snprintf(name, sizeof(name), "python lock (%d)", this_lock);
+ this_lock = atomic_add(&lock_count, 1);
+ PyOS_snprintf(name, sizeof(name), "python lock (%d)", this_lock);
#ifdef FASTLOCK
- if (fastmutex_create(name, lock) < 0) {
- dprintf(("PyThread_allocate_lock failed: %s\n",
- strerror(errno)));
- free(lock);
- lock = NULL;
- }
- dprintf(("PyThread_allocate_lock()-> %p\n", lock));
- return (PyThread_type_lock) lock;
+ if (fastmutex_create(name, lock) < 0) {
+ dprintf(("PyThread_allocate_lock failed: %s\n",
+ strerror(errno)));
+ free(lock);
+ lock = NULL;
+ }
+ dprintf(("PyThread_allocate_lock()-> %p\n", lock));
+ return (PyThread_type_lock) lock;
#else
- sema = create_semaphore(name, 1, 0);
- if (sema < 0) {
- dprintf(("PyThread_allocate_lock failed: %s\n",
- strerror(errno)));
- sema = 0;
- }
- dprintf(("PyThread_allocate_lock()-> %p\n", sema));
- return (PyThread_type_lock) sema;
+ sema = create_semaphore(name, 1, 0);
+ if (sema < 0) {
+ dprintf(("PyThread_allocate_lock failed: %s\n",
+ strerror(errno)));
+ sema = 0;
+ }
+ dprintf(("PyThread_allocate_lock()-> %p\n", sema));
+ return (PyThread_type_lock) sema;
#endif
}
void PyThread_free_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_free_lock(%p) called\n", lock));
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
#ifdef FASTLOCK
- if (fastmutex_destroy((fastmutex_t *) lock) < 0) {
- dprintf(("PyThread_free_lock(%p) failed: %s\n", lock,
- strerror(errno)));
- }
- free(lock);
+ if (fastmutex_destroy((fastmutex_t *) lock) < 0) {
+ dprintf(("PyThread_free_lock(%p) failed: %s\n", lock,
+ strerror(errno)));
+ }
+ free(lock);
#else
- if (delete_semaphore((sem_id) lock) < 0) {
- dprintf(("PyThread_free_lock(%p) failed: %s\n", lock,
- strerror(errno)));
- }
+ if (delete_semaphore((sem_id) lock) < 0) {
+ dprintf(("PyThread_free_lock(%p) failed: %s\n", lock,
+ strerror(errno)));
+ }
#endif
}
int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int retval;
+ int retval;
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock,
- waitflag));
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock,
+ waitflag));
#ifdef FASTLOCK
- if (waitflag)
- retval = fastmutex_lock((fastmutex_t *) lock);
- else
- retval = fastmutex_timedlock((fastmutex_t *) lock, 0);
+ if (waitflag)
+ retval = fastmutex_lock((fastmutex_t *) lock);
+ else
+ retval = fastmutex_timedlock((fastmutex_t *) lock, 0);
#else
- if (waitflag)
- retval = lock_semaphore((sem_id) lock);
- else
- retval = lock_semaphore_x((sem_id) lock, 1, 0, 0);
+ if (waitflag)
+ retval = lock_semaphore((sem_id) lock);
+ else
+ retval = lock_semaphore_x((sem_id) lock, 1, 0, 0);
#endif
- if (retval < 0) {
- dprintf(("PyThread_acquire_lock(%p, %d) failed: %s\n",
- lock, waitflag, strerror(errno)));
- }
- dprintf(("PyThread_acquire_lock(%p, %d)-> %d\n", lock, waitflag,
- retval));
- return retval < 0 ? 0 : 1;
+ if (retval < 0) {
+ dprintf(("PyThread_acquire_lock(%p, %d) failed: %s\n",
+ lock, waitflag, strerror(errno)));
+ }
+ dprintf(("PyThread_acquire_lock(%p, %d)-> %d\n", lock, waitflag,
+ retval));
+ return retval < 0 ? 0 : 1;
}
void PyThread_release_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_release_lock(%p) called\n", lock));
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
#ifdef FASTLOCK
- if (fastmutex_unlock((fastmutex_t *) lock) < 0) {
- dprintf(("PyThread_release_lock(%p) failed: %s\n", lock,
- strerror(errno)));
- }
+ if (fastmutex_unlock((fastmutex_t *) lock) < 0) {
+ dprintf(("PyThread_release_lock(%p) failed: %s\n", lock,
+ strerror(errno)));
+ }
#else
- if (unlock_semaphore((sem_id) lock) < 0) {
- dprintf(("PyThread_release_lock(%p) failed: %s\n", lock,
- strerror(errno)));
- }
+ if (unlock_semaphore((sem_id) lock) < 0) {
+ dprintf(("PyThread_release_lock(%p) failed: %s\n", lock,
+ strerror(errno)));
+ }
#endif
}
diff --git a/Python/thread_beos.h b/Python/thread_beos.h
index d12d562..65dc470 100644
--- a/Python/thread_beos.h
+++ b/Python/thread_beos.h
@@ -7,8 +7,8 @@
* in the Be Developer's Newsletter, Issue #26 (http://www.be.com/).
*/
typedef struct benaphore {
- sem_id _sem;
- int32 _atom;
+ sem_id _sem;
+ int32 _atom;
} benaphore_t;
static status_t benaphore_create( const char *name, benaphore_t *ben );
@@ -19,79 +19,79 @@ static status_t benaphore_unlock( benaphore_t *ben );
static status_t benaphore_create( const char *name, benaphore_t *ben )
{
- if( ben != NULL ) {
- ben->_atom = 0;
- ben->_sem = create_sem( 0, name );
-
- if( ben->_sem < B_NO_ERROR ) {
- return B_BAD_SEM_ID;
- }
- } else {
- return EFAULT;
- }
-
- return EOK;
+ if( ben != NULL ) {
+ ben->_atom = 0;
+ ben->_sem = create_sem( 0, name );
+
+ if( ben->_sem < B_NO_ERROR ) {
+ return B_BAD_SEM_ID;
+ }
+ } else {
+ return EFAULT;
+ }
+
+ return EOK;
}
static status_t benaphore_destroy( benaphore_t *ben )
{
- if( ben->_sem >= B_NO_ERROR ) {
- status_t retval = benaphore_timedlock( ben, 0 );
-
- if( retval == EOK || retval == EWOULDBLOCK ) {
- status_t del_retval = delete_sem( ben->_sem );
-
- return del_retval;
- }
- }
-
- return B_BAD_SEM_ID;
+ if( ben->_sem >= B_NO_ERROR ) {
+ status_t retval = benaphore_timedlock( ben, 0 );
+
+ if( retval == EOK || retval == EWOULDBLOCK ) {
+ status_t del_retval = delete_sem( ben->_sem );
+
+ return del_retval;
+ }
+ }
+
+ return B_BAD_SEM_ID;
}
static status_t benaphore_lock( benaphore_t *ben )
{
- int32 prev = atomic_add( &(ben->_atom), 1 );
-
- if( prev > 0 ) {
- return acquire_sem( ben->_sem );
- }
-
- return EOK;
+ int32 prev = atomic_add( &(ben->_atom), 1 );
+
+ if( prev > 0 ) {
+ return acquire_sem( ben->_sem );
+ }
+
+ return EOK;
}
static status_t benaphore_timedlock( benaphore_t *ben, bigtime_t micros )
{
- int32 prev = atomic_add( &(ben->_atom), 1 );
-
- if( prev > 0 ) {
- status_t retval = acquire_sem_etc( ben->_sem, 1, B_TIMEOUT, micros );
-
- switch( retval ) {
- case B_WOULD_BLOCK: /* Fall through... */
- case B_TIMED_OUT:
- return EWOULDBLOCK;
- break;
- case B_OK:
- return EOK;
- break;
- default:
- return retval;
- break;
- }
- }
-
- return EOK;
+ int32 prev = atomic_add( &(ben->_atom), 1 );
+
+ if( prev > 0 ) {
+ status_t retval = acquire_sem_etc( ben->_sem, 1, B_TIMEOUT, micros );
+
+ switch( retval ) {
+ case B_WOULD_BLOCK: /* Fall through... */
+ case B_TIMED_OUT:
+ return EWOULDBLOCK;
+ break;
+ case B_OK:
+ return EOK;
+ break;
+ default:
+ return retval;
+ break;
+ }
+ }
+
+ return EOK;
}
static status_t benaphore_unlock( benaphore_t *ben )
{
- int32 prev = atomic_add( &(ben->_atom), -1 );
-
- if( prev > 1 ) {
- return release_sem( ben->_sem );
- }
-
- return EOK;
+ int32 prev = atomic_add( &(ben->_atom), -1 );
+
+ if( prev > 1 ) {
+ return release_sem( ben->_sem );
+ }
+
+ return EOK;
}
/* ----------------------------------------------------------------------
@@ -99,8 +99,8 @@ static status_t benaphore_unlock( benaphore_t *ben )
*/
static void PyThread__init_thread( void )
{
- /* Do nothing. */
- return;
+ /* Do nothing. */
+ return;
}
/* ----------------------------------------------------------------------
@@ -114,52 +114,52 @@ static int32 thread_count = 0;
long PyThread_start_new_thread( void (*func)(void *), void *arg )
{
- status_t success = 0;
- thread_id tid;
- char name[B_OS_NAME_LENGTH];
- int32 this_thread;
+ status_t success = 0;
+ thread_id tid;
+ char name[B_OS_NAME_LENGTH];
+ int32 this_thread;
- dprintf(("PyThread_start_new_thread called\n"));
+ dprintf(("PyThread_start_new_thread called\n"));
- /* We are so very thread-safe... */
- this_thread = atomic_add( &thread_count, 1 );
- PyOS_snprintf(name, sizeof(name),
- "python thread (%d)", this_thread );
+ /* We are so very thread-safe... */
+ this_thread = atomic_add( &thread_count, 1 );
+ PyOS_snprintf(name, sizeof(name),
+ "python thread (%d)", this_thread );
- tid = spawn_thread( (thread_func)func, name,
- B_NORMAL_PRIORITY, arg );
- if( tid > B_NO_ERROR ) {
- success = resume_thread( tid );
- }
+ tid = spawn_thread( (thread_func)func, name,
+ B_NORMAL_PRIORITY, arg );
+ if( tid > B_NO_ERROR ) {
+ success = resume_thread( tid );
+ }
- return ( success == B_NO_ERROR ? tid : -1 );
+ return ( success == B_NO_ERROR ? tid : -1 );
}
long PyThread_get_thread_ident( void )
{
- /* Presumed to return the current thread's ID... */
- thread_id tid;
- tid = find_thread( NULL );
-
- return ( tid != B_NAME_NOT_FOUND ? tid : -1 );
+ /* Presumed to return the current thread's ID... */
+ thread_id tid;
+ tid = find_thread( NULL );
+
+ return ( tid != B_NAME_NOT_FOUND ? tid : -1 );
}
void PyThread_exit_thread( void )
{
- int32 threads;
+ int32 threads;
- dprintf(("PyThread_exit_thread called\n"));
+ dprintf(("PyThread_exit_thread called\n"));
- /* Thread-safe way to read a variable without a mutex: */
- threads = atomic_add( &thread_count, 0 );
+ /* Thread-safe way to read a variable without a mutex: */
+ threads = atomic_add( &thread_count, 0 );
- if( threads == 0 ) {
- /* No threads around, so exit main(). */
- exit(0);
- } else {
- /* Oh, we're a thread, let's try to exit gracefully... */
- exit_thread( B_NO_ERROR );
- }
+ if( threads == 0 ) {
+ /* No threads around, so exit main(). */
+ exit(0);
+ } else {
+ /* Oh, we're a thread, let's try to exit gracefully... */
+ exit_thread( B_NO_ERROR );
+ }
}
/* ----------------------------------------------------------------------
@@ -170,79 +170,79 @@ static int32 lock_count = 0;
PyThread_type_lock PyThread_allocate_lock( void )
{
- benaphore_t *lock;
- status_t retval;
- char name[B_OS_NAME_LENGTH];
- int32 this_lock;
-
- dprintf(("PyThread_allocate_lock called\n"));
-
- lock = (benaphore_t *)malloc( sizeof( benaphore_t ) );
- if( lock == NULL ) {
- /* TODO: that's bad, raise MemoryError */
- return (PyThread_type_lock)NULL;
- }
-
- this_lock = atomic_add( &lock_count, 1 );
- PyOS_snprintf(name, sizeof(name), "python lock (%d)", this_lock);
-
- retval = benaphore_create( name, lock );
- if( retval != EOK ) {
- /* TODO: that's bad, raise an exception */
- return (PyThread_type_lock)NULL;
- }
-
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ benaphore_t *lock;
+ status_t retval;
+ char name[B_OS_NAME_LENGTH];
+ int32 this_lock;
+
+ dprintf(("PyThread_allocate_lock called\n"));
+
+ lock = (benaphore_t *)malloc( sizeof( benaphore_t ) );
+ if( lock == NULL ) {
+ /* TODO: that's bad, raise MemoryError */
+ return (PyThread_type_lock)NULL;
+ }
+
+ this_lock = atomic_add( &lock_count, 1 );
+ PyOS_snprintf(name, sizeof(name), "python lock (%d)", this_lock);
+
+ retval = benaphore_create( name, lock );
+ if( retval != EOK ) {
+ /* TODO: that's bad, raise an exception */
+ return (PyThread_type_lock)NULL;
+ }
+
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
void PyThread_free_lock( PyThread_type_lock lock )
{
- status_t retval;
-
- dprintf(("PyThread_free_lock(%p) called\n", lock));
-
- retval = benaphore_destroy( (benaphore_t *)lock );
- if( retval != EOK ) {
- /* TODO: that's bad, raise an exception */
- return;
- }
+ status_t retval;
+
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
+
+ retval = benaphore_destroy( (benaphore_t *)lock );
+ if( retval != EOK ) {
+ /* TODO: that's bad, raise an exception */
+ return;
+ }
}
int PyThread_acquire_lock( PyThread_type_lock lock, int waitflag )
{
- int success;
- status_t retval;
-
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
-
- if( waitflag ) {
- retval = benaphore_lock( (benaphore_t *)lock );
- } else {
- retval = benaphore_timedlock( (benaphore_t *)lock, 0 );
- }
-
- if( retval == EOK ) {
- success = 1;
- } else {
- success = 0;
-
- /* TODO: that's bad, raise an exception */
- }
-
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ int success;
+ status_t retval;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+
+ if( waitflag ) {
+ retval = benaphore_lock( (benaphore_t *)lock );
+ } else {
+ retval = benaphore_timedlock( (benaphore_t *)lock, 0 );
+ }
+
+ if( retval == EOK ) {
+ success = 1;
+ } else {
+ success = 0;
+
+ /* TODO: that's bad, raise an exception */
+ }
+
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
void PyThread_release_lock( PyThread_type_lock lock )
{
- status_t retval;
-
- dprintf(("PyThread_release_lock(%p) called\n", lock));
-
- retval = benaphore_unlock( (benaphore_t *)lock );
- if( retval != EOK ) {
- /* TODO: that's bad, raise an exception */
- return;
- }
+ status_t retval;
+
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
+
+ retval = benaphore_unlock( (benaphore_t *)lock );
+ if( retval != EOK ) {
+ /* TODO: that's bad, raise an exception */
+ return;
+ }
}
diff --git a/Python/thread_cthread.h b/Python/thread_cthread.h
index 7163412..1b3e390 100644
--- a/Python/thread_cthread.h
+++ b/Python/thread_cthread.h
@@ -14,12 +14,12 @@ static void
PyThread__init_thread(void)
{
#ifndef HURD_C_THREADS
- /* Roland McGrath said this should not be used since this is
- done while linking to threads */
- cthread_init();
+ /* Roland McGrath said this should not be used since this is
+ done while linking to threads */
+ cthread_init();
#else
/* do nothing */
- ;
+ ;
#endif
}
@@ -29,34 +29,34 @@ PyThread__init_thread(void)
long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- int success = 0; /* init not needed when SOLARIS_THREADS and */
- /* C_THREADS implemented properly */
+ int success = 0; /* init not needed when SOLARIS_THREADS and */
+ /* C_THREADS implemented properly */
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
- /* looks like solaris detaches the thread to never rejoin
- * so well do it here
- */
- cthread_detach(cthread_fork((cthread_fn_t) func, arg));
- return success < 0 ? -1 : 0;
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+ /* looks like solaris detaches the thread to never rejoin
+ * so well do it here
+ */
+ cthread_detach(cthread_fork((cthread_fn_t) func, arg));
+ return success < 0 ? -1 : 0;
}
long
PyThread_get_thread_ident(void)
{
- if (!initialized)
- PyThread_init_thread();
- return (long) cthread_self();
+ if (!initialized)
+ PyThread_init_thread();
+ return (long) cthread_self();
}
void
PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized)
- exit(0);
- cthread_exit(0);
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized)
+ exit(0);
+ cthread_exit(0);
}
/*
@@ -65,48 +65,48 @@ PyThread_exit_thread(void)
PyThread_type_lock
PyThread_allocate_lock(void)
{
- mutex_t lock;
+ mutex_t lock;
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- lock = mutex_alloc();
- if (mutex_init(lock)) {
- perror("mutex_init");
- free((void *) lock);
- lock = 0;
- }
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ lock = mutex_alloc();
+ if (mutex_init(lock)) {
+ perror("mutex_init");
+ free((void *) lock);
+ lock = 0;
+ }
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
void
PyThread_free_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_free_lock(%p) called\n", lock));
- mutex_free(lock);
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
+ mutex_free(lock);
}
int
PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success = FALSE;
+ int success = FALSE;
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
- if (waitflag) { /* blocking */
- mutex_lock((mutex_t)lock);
- success = TRUE;
- } else { /* non blocking */
- success = mutex_try_lock((mutex_t)lock);
- }
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+ if (waitflag) { /* blocking */
+ mutex_lock((mutex_t)lock);
+ success = TRUE;
+ } else { /* non blocking */
+ success = mutex_try_lock((mutex_t)lock);
+ }
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
void
PyThread_release_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_release_lock(%p) called\n", lock));
- mutex_unlock((mutex_t )lock);
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
+ mutex_unlock((mutex_t )lock);
}
diff --git a/Python/thread_foobar.h b/Python/thread_foobar.h
index 1b993d1..d2b78c5 100644
--- a/Python/thread_foobar.h
+++ b/Python/thread_foobar.h
@@ -13,28 +13,28 @@ PyThread__init_thread(void)
long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- int success = 0; /* init not needed when SOLARIS_THREADS and */
- /* C_THREADS implemented properly */
+ int success = 0; /* init not needed when SOLARIS_THREADS and */
+ /* C_THREADS implemented properly */
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
- return success < 0 ? -1 : 0;
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+ return success < 0 ? -1 : 0;
}
long
PyThread_get_thread_ident(void)
{
- if (!initialized)
- PyThread_init_thread();
+ if (!initialized)
+ PyThread_init_thread();
}
void
PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized)
- exit(0);
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized)
+ exit(0);
}
/*
@@ -44,32 +44,32 @@ PyThread_type_lock
PyThread_allocate_lock(void)
{
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
void
PyThread_free_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_free_lock(%p) called\n", lock));
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
}
int
PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
+ int success;
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
void
PyThread_release_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_release_lock(%p) called\n", lock));
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
}
diff --git a/Python/thread_lwp.h b/Python/thread_lwp.h
index 93d8295..ba7b37a 100644
--- a/Python/thread_lwp.h
+++ b/Python/thread_lwp.h
@@ -3,13 +3,13 @@
#include <lwp/lwp.h>
#include <lwp/stackdep.h>
-#define STACKSIZE 1000 /* stacksize for a thread */
-#define NSTACKS 2 /* # stacks to be put in cache initially */
+#define STACKSIZE 1000 /* stacksize for a thread */
+#define NSTACKS 2 /* # stacks to be put in cache initially */
struct lock {
- int lock_locked;
- cv_t lock_condvar;
- mon_t lock_monitor;
+ int lock_locked;
+ cv_t lock_condvar;
+ mon_t lock_monitor;
};
@@ -18,7 +18,7 @@ struct lock {
*/
static void PyThread__init_thread(void)
{
- lwp_setstkcache(STACKSIZE, NSTACKS);
+ lwp_setstkcache(STACKSIZE, NSTACKS);
}
/*
@@ -28,31 +28,31 @@ static void PyThread__init_thread(void)
long PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- thread_t tid;
- int success;
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
- success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg);
- return success < 0 ? -1 : 0;
+ thread_t tid;
+ int success;
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+ success = lwp_create(&tid, func, MINPRIO, 0, lwp_newstk(), 1, arg);
+ return success < 0 ? -1 : 0;
}
long PyThread_get_thread_ident(void)
{
- thread_t tid;
- if (!initialized)
- PyThread_init_thread();
- if (lwp_self(&tid) < 0)
- return -1;
- return tid.thread_id;
+ thread_t tid;
+ if (!initialized)
+ PyThread_init_thread();
+ if (lwp_self(&tid) < 0)
+ return -1;
+ return tid.thread_id;
}
void PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized)
- exit(0);
- lwp_destroy(SELF);
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized)
+ exit(0);
+ lwp_destroy(SELF);
}
/*
@@ -60,54 +60,54 @@ void PyThread_exit_thread(void)
*/
PyThread_type_lock PyThread_allocate_lock(void)
{
- struct lock *lock;
- extern char *malloc(size_t);
-
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
-
- lock = (struct lock *) malloc(sizeof(struct lock));
- lock->lock_locked = 0;
- (void) mon_create(&lock->lock_monitor);
- (void) cv_create(&lock->lock_condvar, lock->lock_monitor);
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ struct lock *lock;
+ extern char *malloc(size_t);
+
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+
+ lock = (struct lock *) malloc(sizeof(struct lock));
+ lock->lock_locked = 0;
+ (void) mon_create(&lock->lock_monitor);
+ (void) cv_create(&lock->lock_condvar, lock->lock_monitor);
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
void PyThread_free_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_free_lock(%p) called\n", lock));
- mon_destroy(((struct lock *) lock)->lock_monitor);
- free((char *) lock);
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
+ mon_destroy(((struct lock *) lock)->lock_monitor);
+ free((char *) lock);
}
int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
-
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
- success = 0;
-
- (void) mon_enter(((struct lock *) lock)->lock_monitor);
- if (waitflag)
- while (((struct lock *) lock)->lock_locked)
- cv_wait(((struct lock *) lock)->lock_condvar);
- if (!((struct lock *) lock)->lock_locked) {
- success = 1;
- ((struct lock *) lock)->lock_locked = 1;
- }
- cv_broadcast(((struct lock *) lock)->lock_condvar);
- mon_exit(((struct lock *) lock)->lock_monitor);
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ int success;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+ success = 0;
+
+ (void) mon_enter(((struct lock *) lock)->lock_monitor);
+ if (waitflag)
+ while (((struct lock *) lock)->lock_locked)
+ cv_wait(((struct lock *) lock)->lock_condvar);
+ if (!((struct lock *) lock)->lock_locked) {
+ success = 1;
+ ((struct lock *) lock)->lock_locked = 1;
+ }
+ cv_broadcast(((struct lock *) lock)->lock_condvar);
+ mon_exit(((struct lock *) lock)->lock_monitor);
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
void PyThread_release_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_release_lock(%p) called\n", lock));
- (void) mon_enter(((struct lock *) lock)->lock_monitor);
- ((struct lock *) lock)->lock_locked = 0;
- cv_broadcast(((struct lock *) lock)->lock_condvar);
- mon_exit(((struct lock *) lock)->lock_monitor);
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
+ (void) mon_enter(((struct lock *) lock)->lock_monitor);
+ ((struct lock *) lock)->lock_locked = 0;
+ cv_broadcast(((struct lock *) lock)->lock_condvar);
+ mon_exit(((struct lock *) lock)->lock_monitor);
}
diff --git a/Python/thread_nt.h b/Python/thread_nt.h
index 0c5d192..9796a34 100644
--- a/Python/thread_nt.h
+++ b/Python/thread_nt.h
@@ -10,81 +10,81 @@
#endif
typedef struct NRMUTEX {
- LONG owned ;
- DWORD thread_id ;
- HANDLE hevent ;
+ LONG owned ;
+ DWORD thread_id ;
+ HANDLE hevent ;
} NRMUTEX, *PNRMUTEX ;
BOOL
InitializeNonRecursiveMutex(PNRMUTEX mutex)
{
- mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */
- mutex->thread_id = 0 ;
- mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ;
- return mutex->hevent != NULL ; /* TRUE if the mutex is created */
+ mutex->owned = -1 ; /* No threads have entered NonRecursiveMutex */
+ mutex->thread_id = 0 ;
+ mutex->hevent = CreateEvent(NULL, FALSE, FALSE, NULL) ;
+ return mutex->hevent != NULL ; /* TRUE if the mutex is created */
}
VOID
DeleteNonRecursiveMutex(PNRMUTEX mutex)
{
- /* No in-use check */
- CloseHandle(mutex->hevent) ;
- mutex->hevent = NULL ; /* Just in case */
+ /* No in-use check */
+ CloseHandle(mutex->hevent) ;
+ mutex->hevent = NULL ; /* Just in case */
}
DWORD
EnterNonRecursiveMutex(PNRMUTEX mutex, BOOL wait)
{
- /* Assume that the thread waits successfully */
- DWORD ret ;
-
- /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */
- if (!wait)
- {
- if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1)
- return WAIT_TIMEOUT ;
- ret = WAIT_OBJECT_0 ;
- }
- else
- ret = InterlockedIncrement(&mutex->owned) ?
- /* Some thread owns the mutex, let's wait... */
- WaitForSingleObject(mutex->hevent, INFINITE) : WAIT_OBJECT_0 ;
-
- mutex->thread_id = GetCurrentThreadId() ; /* We own it */
- return ret ;
+ /* Assume that the thread waits successfully */
+ DWORD ret ;
+
+ /* InterlockedIncrement(&mutex->owned) == 0 means that no thread currently owns the mutex */
+ if (!wait)
+ {
+ if (InterlockedCompareExchange(&mutex->owned, 0, -1) != -1)
+ return WAIT_TIMEOUT ;
+ ret = WAIT_OBJECT_0 ;
+ }
+ else
+ ret = InterlockedIncrement(&mutex->owned) ?
+ /* Some thread owns the mutex, let's wait... */
+ WaitForSingleObject(mutex->hevent, INFINITE) : WAIT_OBJECT_0 ;
+
+ mutex->thread_id = GetCurrentThreadId() ; /* We own it */
+ return ret ;
}
BOOL
LeaveNonRecursiveMutex(PNRMUTEX mutex)
{
- /* We don't own the mutex */
- mutex->thread_id = 0 ;
- return
- InterlockedDecrement(&mutex->owned) < 0 ||
- SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */
+ /* We don't own the mutex */
+ mutex->thread_id = 0 ;
+ return
+ InterlockedDecrement(&mutex->owned) < 0 ||
+ SetEvent(mutex->hevent) ; /* Other threads are waiting, wake one on them up */
}
PNRMUTEX
AllocNonRecursiveMutex(void)
{
- PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ;
- if (mutex && !InitializeNonRecursiveMutex(mutex))
- {
- free(mutex) ;
- mutex = NULL ;
- }
- return mutex ;
+ PNRMUTEX mutex = (PNRMUTEX)malloc(sizeof(NRMUTEX)) ;
+ if (mutex && !InitializeNonRecursiveMutex(mutex))
+ {
+ free(mutex) ;
+ mutex = NULL ;
+ }
+ return mutex ;
}
void
FreeNonRecursiveMutex(PNRMUTEX mutex)
{
- if (mutex)
- {
- DeleteNonRecursiveMutex(mutex) ;
- free(mutex) ;
- }
+ if (mutex)
+ {
+ DeleteNonRecursiveMutex(mutex) ;
+ free(mutex) ;
+ }
}
long PyThread_get_thread_ident(void);
@@ -102,8 +102,8 @@ PyThread__init_thread(void)
*/
typedef struct {
- void (*func)(void*);
- void *arg;
+ void (*func)(void*);
+ void *arg;
} callobj;
/* thunker to call adapt between the function type used by the system's
@@ -115,66 +115,66 @@ static unsigned __stdcall
#endif
bootstrap(void *call)
{
- callobj *obj = (callobj*)call;
- void (*func)(void*) = obj->func;
- void *arg = obj->arg;
- HeapFree(GetProcessHeap(), 0, obj);
- func(arg);
- return 0;
+ callobj *obj = (callobj*)call;
+ void (*func)(void*) = obj->func;
+ void *arg = obj->arg;
+ HeapFree(GetProcessHeap(), 0, obj);
+ func(arg);
+ return 0;
}
long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- HANDLE hThread;
- unsigned threadID;
- callobj *obj;
-
- dprintf(("%ld: PyThread_start_new_thread called\n",
- PyThread_get_thread_ident()));
- if (!initialized)
- PyThread_init_thread();
-
- obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj));
- if (!obj)
- return -1;
- obj->func = func;
- obj->arg = arg;
+ HANDLE hThread;
+ unsigned threadID;
+ callobj *obj;
+
+ dprintf(("%ld: PyThread_start_new_thread called\n",
+ PyThread_get_thread_ident()));
+ if (!initialized)
+ PyThread_init_thread();
+
+ obj = (callobj*)HeapAlloc(GetProcessHeap(), 0, sizeof(*obj));
+ if (!obj)
+ return -1;
+ obj->func = func;
+ obj->arg = arg;
#if defined(MS_WINCE)
- hThread = CreateThread(NULL,
- Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T),
- bootstrap, obj, 0, &threadID);
+ hThread = CreateThread(NULL,
+ Py_SAFE_DOWNCAST(_pythread_stacksize, Py_ssize_t, SIZE_T),
+ bootstrap, obj, 0, &threadID);
#else
- hThread = (HANDLE)_beginthreadex(0,
- Py_SAFE_DOWNCAST(_pythread_stacksize,
- Py_ssize_t, unsigned int),
- bootstrap, obj,
- 0, &threadID);
+ hThread = (HANDLE)_beginthreadex(0,
+ Py_SAFE_DOWNCAST(_pythread_stacksize,
+ Py_ssize_t, unsigned int),
+ bootstrap, obj,
+ 0, &threadID);
#endif
- if (hThread == 0) {
+ if (hThread == 0) {
#if defined(MS_WINCE)
- /* Save error in variable, to prevent PyThread_get_thread_ident
- from clobbering it. */
- unsigned e = GetLastError();
- dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n",
- PyThread_get_thread_ident(), e));
+ /* Save error in variable, to prevent PyThread_get_thread_ident
+ from clobbering it. */
+ unsigned e = GetLastError();
+ dprintf(("%ld: PyThread_start_new_thread failed, win32 error code %u\n",
+ PyThread_get_thread_ident(), e));
#else
- /* I've seen errno == EAGAIN here, which means "there are
- * too many threads".
- */
- int e = errno;
- dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n",
- PyThread_get_thread_ident(), e));
+ /* I've seen errno == EAGAIN here, which means "there are
+ * too many threads".
+ */
+ int e = errno;
+ dprintf(("%ld: PyThread_start_new_thread failed, errno %d\n",
+ PyThread_get_thread_ident(), e));
#endif
- threadID = (unsigned)-1;
- HeapFree(GetProcessHeap(), 0, obj);
- }
- else {
- dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n",
- PyThread_get_thread_ident(), (void*)hThread));
- CloseHandle(hThread);
- }
- return (long) threadID;
+ threadID = (unsigned)-1;
+ HeapFree(GetProcessHeap(), 0, obj);
+ }
+ else {
+ dprintf(("%ld: PyThread_start_new_thread succeeded: %p\n",
+ PyThread_get_thread_ident(), (void*)hThread));
+ CloseHandle(hThread);
+ }
+ return (long) threadID;
}
/*
@@ -184,22 +184,22 @@ PyThread_start_new_thread(void (*func)(void *), void *arg)
long
PyThread_get_thread_ident(void)
{
- if (!initialized)
- PyThread_init_thread();
+ if (!initialized)
+ PyThread_init_thread();
- return GetCurrentThreadId();
+ return GetCurrentThreadId();
}
void
PyThread_exit_thread(void)
{
- dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
- if (!initialized)
- exit(0);
+ dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
+ if (!initialized)
+ exit(0);
#if defined(MS_WINCE)
- ExitThread(0);
+ ExitThread(0);
#else
- _endthreadex(0);
+ _endthreadex(0);
#endif
}
@@ -211,25 +211,25 @@ PyThread_exit_thread(void)
PyThread_type_lock
PyThread_allocate_lock(void)
{
- PNRMUTEX aLock;
+ PNRMUTEX aLock;
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- aLock = AllocNonRecursiveMutex() ;
+ aLock = AllocNonRecursiveMutex() ;
- dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock));
+ dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock));
- return (PyThread_type_lock) aLock;
+ return (PyThread_type_lock) aLock;
}
void
PyThread_free_lock(PyThread_type_lock aLock)
{
- dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
+ dprintf(("%ld: PyThread_free_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
- FreeNonRecursiveMutex(aLock) ;
+ FreeNonRecursiveMutex(aLock) ;
}
/*
@@ -241,29 +241,29 @@ PyThread_free_lock(PyThread_type_lock aLock)
int
PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag)
{
- int success ;
+ int success ;
- dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", PyThread_get_thread_ident(),aLock, waitflag));
+ dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n", PyThread_get_thread_ident(),aLock, waitflag));
- success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (waitflag ? INFINITE : 0)) == WAIT_OBJECT_0 ;
+ success = aLock && EnterNonRecursiveMutex((PNRMUTEX) aLock, (waitflag ? INFINITE : 0)) == WAIT_OBJECT_0 ;
- dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success));
+ dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success));
- return success;
+ return success;
}
void
PyThread_release_lock(PyThread_type_lock aLock)
{
- dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
+ dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
- if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock)))
- dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError()));
+ if (!(aLock && LeaveNonRecursiveMutex((PNRMUTEX) aLock)))
+ dprintf(("%ld: Could not PyThread_release_lock(%p) error: %ld\n", PyThread_get_thread_ident(), aLock, GetLastError()));
}
/* minimum/maximum thread stack sizes supported */
-#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */
-#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */
+#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */
+#define THREAD_MAX_STACKSIZE 0x10000000 /* 256MB */
/* set the thread stack size.
* Return 0 if size is valid, -1 otherwise.
@@ -271,22 +271,22 @@ PyThread_release_lock(PyThread_type_lock aLock)
static int
_pythread_nt_set_stacksize(size_t size)
{
- /* set to default */
- if (size == 0) {
- _pythread_stacksize = 0;
- return 0;
- }
-
- /* valid range? */
- if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) {
- _pythread_stacksize = size;
- return 0;
- }
-
- return -1;
+ /* set to default */
+ if (size == 0) {
+ _pythread_stacksize = 0;
+ return 0;
+ }
+
+ /* valid range? */
+ if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) {
+ _pythread_stacksize = size;
+ return 0;
+ }
+
+ return -1;
}
-#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x)
+#define THREAD_SET_STACKSIZE(x) _pythread_nt_set_stacksize(x)
/* use native Windows TLS functions */
@@ -296,13 +296,13 @@ _pythread_nt_set_stacksize(size_t size)
int
PyThread_create_key(void)
{
- return (int) TlsAlloc();
+ return (int) TlsAlloc();
}
void
PyThread_delete_key(int key)
{
- TlsFree(key);
+ TlsFree(key);
}
/* We must be careful to emulate the strange semantics implemented in thread.c,
@@ -311,42 +311,42 @@ PyThread_delete_key(int key)
int
PyThread_set_key_value(int key, void *value)
{
- BOOL ok;
- void *oldvalue;
-
- assert(value != NULL);
- oldvalue = TlsGetValue(key);
- if (oldvalue != NULL)
- /* ignore value if already set */
- return 0;
- ok = TlsSetValue(key, value);
- if (!ok)
- return -1;
- return 0;
+ BOOL ok;
+ void *oldvalue;
+
+ assert(value != NULL);
+ oldvalue = TlsGetValue(key);
+ if (oldvalue != NULL)
+ /* ignore value if already set */
+ return 0;
+ ok = TlsSetValue(key, value);
+ if (!ok)
+ return -1;
+ return 0;
}
void *
PyThread_get_key_value(int key)
{
- /* because TLS is used in the Py_END_ALLOW_THREAD macro,
- * it is necessary to preserve the windows error state, because
- * it is assumed to be preserved across the call to the macro.
- * Ideally, the macro should be fixed, but it is simpler to
- * do it here.
- */
- DWORD error = GetLastError();
- void *result = TlsGetValue(key);
- SetLastError(error);
- return result;
+ /* because TLS is used in the Py_END_ALLOW_THREAD macro,
+ * it is necessary to preserve the windows error state, because
+ * it is assumed to be preserved across the call to the macro.
+ * Ideally, the macro should be fixed, but it is simpler to
+ * do it here.
+ */
+ DWORD error = GetLastError();
+ void *result = TlsGetValue(key);
+ SetLastError(error);
+ return result;
}
void
PyThread_delete_key_value(int key)
{
- /* NULL is used as "key missing", and it is also the default
- * given by TlsGetValue() if nothing has been set yet.
- */
- TlsSetValue(key, NULL);
+ /* NULL is used as "key missing", and it is also the default
+ * given by TlsGetValue() if nothing has been set yet.
+ */
+ TlsSetValue(key, NULL);
}
/* reinitialization of TLS is not necessary after fork when using
diff --git a/Python/thread_os2.h b/Python/thread_os2.h
index eee8de6..1b264b5 100644
--- a/Python/thread_os2.h
+++ b/Python/thread_os2.h
@@ -16,10 +16,10 @@ long PyThread_get_thread_ident(void);
/* default thread stack size of 64kB */
#if !defined(THREAD_STACK_SIZE)
-#define THREAD_STACK_SIZE 0x10000
+#define THREAD_STACK_SIZE 0x10000
#endif
-#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE)
+#define OS2_STACKSIZE(x) (x ? x : THREAD_STACK_SIZE)
/*
* Initialization of the C package, should not be needed.
@@ -35,113 +35,113 @@ PyThread__init_thread(void)
long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- int thread_id;
+ int thread_id;
- thread_id = _beginthread(func,
- NULL,
- OS2_STACKSIZE(_pythread_stacksize),
- arg);
+ thread_id = _beginthread(func,
+ NULL,
+ OS2_STACKSIZE(_pythread_stacksize),
+ arg);
- if (thread_id == -1) {
- dprintf(("_beginthread failed. return %ld\n", errno));
- }
+ if (thread_id == -1) {
+ dprintf(("_beginthread failed. return %ld\n", errno));
+ }
- return thread_id;
+ return thread_id;
}
long
PyThread_get_thread_ident(void)
{
#if !defined(PYCC_GCC)
- PPIB pib;
- PTIB tib;
+ PPIB pib;
+ PTIB tib;
#endif
- if (!initialized)
- PyThread_init_thread();
+ if (!initialized)
+ PyThread_init_thread();
#if defined(PYCC_GCC)
- return _gettid();
+ return _gettid();
#else
- DosGetInfoBlocks(&tib, &pib);
- return tib->tib_ptib2->tib2_ultid;
+ DosGetInfoBlocks(&tib, &pib);
+ return tib->tib_ptib2->tib2_ultid;
#endif
}
void
PyThread_exit_thread(void)
{
- dprintf(("%ld: PyThread_exit_thread called\n",
- PyThread_get_thread_ident()));
- if (!initialized)
- exit(0);
- _endthread();
+ dprintf(("%ld: PyThread_exit_thread called\n",
+ PyThread_get_thread_ident()));
+ if (!initialized)
+ exit(0);
+ _endthread();
}
/*
* Lock support. This is implemented with an event semaphore and critical
- * sections to make it behave more like a posix mutex than its OS/2
+ * sections to make it behave more like a posix mutex than its OS/2
* counterparts.
*/
typedef struct os2_lock_t {
- int is_set;
- HEV changed;
+ int is_set;
+ HEV changed;
} *type_os2_lock;
-PyThread_type_lock
+PyThread_type_lock
PyThread_allocate_lock(void)
{
#if defined(PYCC_GCC)
- _fmutex *sem = malloc(sizeof(_fmutex));
- if (!initialized)
- PyThread_init_thread();
- dprintf(("%ld: PyThread_allocate_lock() -> %lx\n",
- PyThread_get_thread_ident(),
- (long)sem));
- if (_fmutex_create(sem, 0)) {
- free(sem);
- sem = NULL;
- }
- return (PyThread_type_lock)sem;
+ _fmutex *sem = malloc(sizeof(_fmutex));
+ if (!initialized)
+ PyThread_init_thread();
+ dprintf(("%ld: PyThread_allocate_lock() -> %lx\n",
+ PyThread_get_thread_ident(),
+ (long)sem));
+ if (_fmutex_create(sem, 0)) {
+ free(sem);
+ sem = NULL;
+ }
+ return (PyThread_type_lock)sem;
#else
- APIRET rc;
- type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t));
+ APIRET rc;
+ type_os2_lock lock = (type_os2_lock)malloc(sizeof(struct os2_lock_t));
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- lock->is_set = 0;
+ lock->is_set = 0;
- DosCreateEventSem(NULL, &lock->changed, 0, 0);
+ DosCreateEventSem(NULL, &lock->changed, 0, 0);
- dprintf(("%ld: PyThread_allocate_lock() -> %p\n",
- PyThread_get_thread_ident(),
- lock->changed));
+ dprintf(("%ld: PyThread_allocate_lock() -> %p\n",
+ PyThread_get_thread_ident(),
+ lock->changed));
- return (PyThread_type_lock)lock;
+ return (PyThread_type_lock)lock;
#endif
}
-void
+void
PyThread_free_lock(PyThread_type_lock aLock)
{
#if !defined(PYCC_GCC)
- type_os2_lock lock = (type_os2_lock)aLock;
+ type_os2_lock lock = (type_os2_lock)aLock;
#endif
- dprintf(("%ld: PyThread_free_lock(%p) called\n",
- PyThread_get_thread_ident(),aLock));
+ dprintf(("%ld: PyThread_free_lock(%p) called\n",
+ PyThread_get_thread_ident(),aLock));
#if defined(PYCC_GCC)
- if (aLock) {
- _fmutex_close((_fmutex *)aLock);
- free((_fmutex *)aLock);
- }
+ if (aLock) {
+ _fmutex_close((_fmutex *)aLock);
+ free((_fmutex *)aLock);
+ }
#else
- DosCloseEventSem(lock->changed);
- free(aLock);
+ DosCloseEventSem(lock->changed);
+ free(aLock);
#endif
}
@@ -150,98 +150,98 @@ PyThread_free_lock(PyThread_type_lock aLock)
*
* and 0 if the lock was not acquired.
*/
-int
+int
PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag)
{
#if !defined(PYCC_GCC)
- int done = 0;
- ULONG count;
- PID pid = 0;
- TID tid = 0;
- type_os2_lock lock = (type_os2_lock)aLock;
+ int done = 0;
+ ULONG count;
+ PID pid = 0;
+ TID tid = 0;
+ type_os2_lock lock = (type_os2_lock)aLock;
#endif
- dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n",
- PyThread_get_thread_ident(),
- aLock,
- waitflag));
+ dprintf(("%ld: PyThread_acquire_lock(%p, %d) called\n",
+ PyThread_get_thread_ident(),
+ aLock,
+ waitflag));
#if defined(PYCC_GCC)
- /* always successful if the lock doesn't exist */
- if (aLock &&
- _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT))
- return 0;
+ /* always successful if the lock doesn't exist */
+ if (aLock &&
+ _fmutex_request((_fmutex *)aLock, waitflag ? 0 : _FMR_NOWAIT))
+ return 0;
#else
- while (!done) {
- /* if the lock is currently set, we have to wait for
- * the state to change
- */
- if (lock->is_set) {
- if (!waitflag)
- return 0;
- DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT);
- }
-
- /* enter a critical section and try to get the semaphore. If
- * it is still locked, we will try again.
- */
- if (DosEnterCritSec())
- return 0;
-
- if (!lock->is_set) {
- lock->is_set = 1;
- DosResetEventSem(lock->changed, &count);
- done = 1;
- }
-
- DosExitCritSec();
- }
+ while (!done) {
+ /* if the lock is currently set, we have to wait for
+ * the state to change
+ */
+ if (lock->is_set) {
+ if (!waitflag)
+ return 0;
+ DosWaitEventSem(lock->changed, SEM_INDEFINITE_WAIT);
+ }
+
+ /* enter a critical section and try to get the semaphore. If
+ * it is still locked, we will try again.
+ */
+ if (DosEnterCritSec())
+ return 0;
+
+ if (!lock->is_set) {
+ lock->is_set = 1;
+ DosResetEventSem(lock->changed, &count);
+ done = 1;
+ }
+
+ DosExitCritSec();
+ }
#endif
- return 1;
+ return 1;
}
void
PyThread_release_lock(PyThread_type_lock aLock)
{
#if !defined(PYCC_GCC)
- type_os2_lock lock = (type_os2_lock)aLock;
+ type_os2_lock lock = (type_os2_lock)aLock;
#endif
- dprintf(("%ld: PyThread_release_lock(%p) called\n",
- PyThread_get_thread_ident(),
- aLock));
+ dprintf(("%ld: PyThread_release_lock(%p) called\n",
+ PyThread_get_thread_ident(),
+ aLock));
#if defined(PYCC_GCC)
- if (aLock)
- _fmutex_release((_fmutex *)aLock);
+ if (aLock)
+ _fmutex_release((_fmutex *)aLock);
#else
- if (!lock->is_set) {
- dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n",
- PyThread_get_thread_ident(),
- aLock,
- GetLastError()));
- return;
- }
-
- if (DosEnterCritSec()) {
- dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n",
- PyThread_get_thread_ident(),
- aLock,
- GetLastError()));
- return;
- }
-
- lock->is_set = 0;
- DosPostEventSem(lock->changed);
-
- DosExitCritSec();
+ if (!lock->is_set) {
+ dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n",
+ PyThread_get_thread_ident(),
+ aLock,
+ GetLastError()));
+ return;
+ }
+
+ if (DosEnterCritSec()) {
+ dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n",
+ PyThread_get_thread_ident(),
+ aLock,
+ GetLastError()));
+ return;
+ }
+
+ lock->is_set = 0;
+ DosPostEventSem(lock->changed);
+
+ DosExitCritSec();
#endif
}
/* minimum/maximum thread stack sizes supported */
-#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */
-#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */
+#define THREAD_MIN_STACKSIZE 0x8000 /* 32kB */
+#define THREAD_MAX_STACKSIZE 0x2000000 /* 32MB */
/* set the thread stack size.
* Return 0 if size is valid, -1 otherwise.
@@ -249,19 +249,19 @@ PyThread_release_lock(PyThread_type_lock aLock)
static int
_pythread_os2_set_stacksize(size_t size)
{
- /* set to default */
- if (size == 0) {
- _pythread_stacksize = 0;
- return 0;
- }
-
- /* valid range? */
- if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) {
- _pythread_stacksize = size;
- return 0;
- }
-
- return -1;
+ /* set to default */
+ if (size == 0) {
+ _pythread_stacksize = 0;
+ return 0;
+ }
+
+ /* valid range? */
+ if (size >= THREAD_MIN_STACKSIZE && size < THREAD_MAX_STACKSIZE) {
+ _pythread_stacksize = size;
+ return 0;
+ }
+
+ return -1;
}
-#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x)
+#define THREAD_SET_STACKSIZE(x) _pythread_os2_set_stacksize(x)
diff --git a/Python/thread_pth.h b/Python/thread_pth.h
index f11e484..82a00e7 100644
--- a/Python/thread_pth.h
+++ b/Python/thread_pth.h
@@ -3,7 +3,7 @@
http://www.gnu.org/software/pth
2000-05-03 Andy Dustman <andy@dustman.net>
- Adapted from Posix threads interface
+ Adapted from Posix threads interface
12 May 1997 -- david arnold <davida@pobox.com>
*/
@@ -22,10 +22,10 @@
*/
typedef struct {
- char locked; /* 0=unlocked, 1=locked */
- /* a <cond, mutex> pair to handle an acquire of a locked lock */
- pth_cond_t lock_released;
- pth_mutex_t mut;
+ char locked; /* 0=unlocked, 1=locked */
+ /* a <cond, mutex> pair to handle an acquire of a locked lock */
+ pth_cond_t lock_released;
+ pth_mutex_t mut;
} pth_lock;
#define CHECK_STATUS(name) if (status == -1) { printf("%d ", status); perror(name); error = 1; }
@@ -38,10 +38,10 @@ pth_attr_t PyThread_attr;
static void PyThread__init_thread(void)
{
- pth_init();
- PyThread_attr = pth_attr_new();
- pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18);
- pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE);
+ pth_init();
+ PyThread_attr = pth_attr_new();
+ pth_attr_set(PyThread_attr, PTH_ATTR_STACK_SIZE, 1<<18);
+ pth_attr_set(PyThread_attr, PTH_ATTR_JOINABLE, FALSE);
}
/*
@@ -51,35 +51,35 @@ static void PyThread__init_thread(void)
long PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- pth_t th;
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
+ pth_t th;
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- th = pth_spawn(PyThread_attr,
- (void* (*)(void *))func,
- (void *)arg
- );
+ th = pth_spawn(PyThread_attr,
+ (void* (*)(void *))func,
+ (void *)arg
+ );
- return th;
+ return th;
}
long PyThread_get_thread_ident(void)
{
- volatile pth_t threadid;
- if (!initialized)
- PyThread_init_thread();
- /* Jump through some hoops for Alpha OSF/1 */
- threadid = pth_self();
- return (long) *(long *) &threadid;
+ volatile pth_t threadid;
+ if (!initialized)
+ PyThread_init_thread();
+ /* Jump through some hoops for Alpha OSF/1 */
+ threadid = pth_self();
+ return (long) *(long *) &threadid;
}
void PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized) {
- exit(0);
- }
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized) {
+ exit(0);
+ }
}
/*
@@ -87,92 +87,92 @@ void PyThread_exit_thread(void)
*/
PyThread_type_lock PyThread_allocate_lock(void)
{
- pth_lock *lock;
- int status, error = 0;
-
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
-
- lock = (pth_lock *) malloc(sizeof(pth_lock));
- memset((void *)lock, '\0', sizeof(pth_lock));
- if (lock) {
- lock->locked = 0;
- status = pth_mutex_init(&lock->mut);
- CHECK_STATUS("pth_mutex_init");
- status = pth_cond_init(&lock->lock_released);
- CHECK_STATUS("pth_cond_init");
- if (error) {
- free((void *)lock);
- lock = NULL;
- }
- }
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ pth_lock *lock;
+ int status, error = 0;
+
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+
+ lock = (pth_lock *) malloc(sizeof(pth_lock));
+ memset((void *)lock, '\0', sizeof(pth_lock));
+ if (lock) {
+ lock->locked = 0;
+ status = pth_mutex_init(&lock->mut);
+ CHECK_STATUS("pth_mutex_init");
+ status = pth_cond_init(&lock->lock_released);
+ CHECK_STATUS("pth_cond_init");
+ if (error) {
+ free((void *)lock);
+ lock = NULL;
+ }
+ }
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
void PyThread_free_lock(PyThread_type_lock lock)
{
- pth_lock *thelock = (pth_lock *)lock;
+ pth_lock *thelock = (pth_lock *)lock;
- dprintf(("PyThread_free_lock(%p) called\n", lock));
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
- free((void *)thelock);
+ free((void *)thelock);
}
int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
- pth_lock *thelock = (pth_lock *)lock;
- int status, error = 0;
-
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
-
- status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL);
- CHECK_STATUS("pth_mutex_acquire[1]");
- success = thelock->locked == 0;
- if (success) thelock->locked = 1;
- status = pth_mutex_release( &thelock->mut );
- CHECK_STATUS("pth_mutex_release[1]");
-
- if ( !success && waitflag ) {
- /* continue trying until we get the lock */
-
- /* mut must be locked by me -- part of the condition
- * protocol */
- status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL );
- CHECK_STATUS("pth_mutex_acquire[2]");
- while ( thelock->locked ) {
- status = pth_cond_await(&thelock->lock_released,
- &thelock->mut, NULL);
- CHECK_STATUS("pth_cond_await");
- }
- thelock->locked = 1;
- status = pth_mutex_release( &thelock->mut );
- CHECK_STATUS("pth_mutex_release[2]");
- success = 1;
+ int success;
+ pth_lock *thelock = (pth_lock *)lock;
+ int status, error = 0;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+
+ status = pth_mutex_acquire(&thelock->mut, !waitflag, NULL);
+ CHECK_STATUS("pth_mutex_acquire[1]");
+ success = thelock->locked == 0;
+ if (success) thelock->locked = 1;
+ status = pth_mutex_release( &thelock->mut );
+ CHECK_STATUS("pth_mutex_release[1]");
+
+ if ( !success && waitflag ) {
+ /* continue trying until we get the lock */
+
+ /* mut must be locked by me -- part of the condition
+ * protocol */
+ status = pth_mutex_acquire( &thelock->mut, !waitflag, NULL );
+ CHECK_STATUS("pth_mutex_acquire[2]");
+ while ( thelock->locked ) {
+ status = pth_cond_await(&thelock->lock_released,
+ &thelock->mut, NULL);
+ CHECK_STATUS("pth_cond_await");
}
- if (error) success = 0;
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ thelock->locked = 1;
+ status = pth_mutex_release( &thelock->mut );
+ CHECK_STATUS("pth_mutex_release[2]");
+ success = 1;
+ }
+ if (error) success = 0;
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
void PyThread_release_lock(PyThread_type_lock lock)
{
- pth_lock *thelock = (pth_lock *)lock;
- int status, error = 0;
+ pth_lock *thelock = (pth_lock *)lock;
+ int status, error = 0;
- dprintf(("PyThread_release_lock(%p) called\n", lock));
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
- status = pth_mutex_acquire( &thelock->mut, 0, NULL );
- CHECK_STATUS("pth_mutex_acquire[3]");
+ status = pth_mutex_acquire( &thelock->mut, 0, NULL );
+ CHECK_STATUS("pth_mutex_acquire[3]");
- thelock->locked = 0;
+ thelock->locked = 0;
- status = pth_mutex_release( &thelock->mut );
- CHECK_STATUS("pth_mutex_release[3]");
+ status = pth_mutex_release( &thelock->mut );
+ CHECK_STATUS("pth_mutex_release[3]");
- /* wake up someone (anyone, if any) waiting on the lock */
- status = pth_cond_notify( &thelock->lock_released, 0 );
- CHECK_STATUS("pth_cond_notify");
+ /* wake up someone (anyone, if any) waiting on the lock */
+ status = pth_cond_notify( &thelock->lock_released, 0 );
+ CHECK_STATUS("pth_cond_notify");
}
diff --git a/Python/thread_pthread.h b/Python/thread_pthread.h
index 4305a19..ef49a30 100644
--- a/Python/thread_pthread.h
+++ b/Python/thread_pthread.h
@@ -16,10 +16,10 @@
be conditional on _POSIX_THREAD_ATTR_STACKSIZE being defined. */
#ifdef _POSIX_THREAD_ATTR_STACKSIZE
#ifndef THREAD_STACK_SIZE
-#define THREAD_STACK_SIZE 0 /* use default stack size */
+#define THREAD_STACK_SIZE 0 /* use default stack size */
#endif
/* for safety, ensure a viable minimum stacksize */
-#define THREAD_STACK_MIN 0x8000 /* 32kB */
+#define THREAD_STACK_MIN 0x8000 /* 32kB */
#else /* !_POSIX_THREAD_ATTR_STACKSIZE */
#ifdef THREAD_STACK_SIZE
#error "THREAD_STACK_SIZE defined but _POSIX_THREAD_ATTR_STACKSIZE undefined"
@@ -28,9 +28,9 @@
/* The POSIX spec says that implementations supporting the sem_*
family of functions must indicate this by defining
- _POSIX_SEMAPHORES. */
+ _POSIX_SEMAPHORES. */
#ifdef _POSIX_SEMAPHORES
-/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so
+/* On FreeBSD 4.x, _POSIX_SEMAPHORES is defined empty, so
we need to add 0 to make it work there as well. */
#if (_POSIX_SEMAPHORES+0) == -1
#define HAVE_BROKEN_POSIX_SEMAPHORES
@@ -99,10 +99,10 @@
*/
typedef struct {
- char locked; /* 0=unlocked, 1=locked */
- /* a <cond, mutex> pair to handle an acquire of a locked lock */
- pthread_cond_t lock_released;
- pthread_mutex_t mut;
+ char locked; /* 0=unlocked, 1=locked */
+ /* a <cond, mutex> pair to handle an acquire of a locked lock */
+ pthread_cond_t lock_released;
+ pthread_mutex_t mut;
} pthread_lock;
#define CHECK_STATUS(name) if (status != 0) { perror(name); error = 1; }
@@ -120,11 +120,11 @@ void _noop(void)
static void
PyThread__init_thread(void)
{
- /* DO AN INIT BY STARTING THE THREAD */
- static int dummy = 0;
- pthread_t thread1;
- pthread_create(&thread1, NULL, (void *) _noop, &dummy);
- pthread_join(thread1, NULL);
+ /* DO AN INIT BY STARTING THE THREAD */
+ static int dummy = 0;
+ pthread_t thread1;
+ pthread_create(&thread1, NULL, (void *) _noop, &dummy);
+ pthread_join(thread1, NULL);
}
#else /* !_HAVE_BSDI */
@@ -133,7 +133,7 @@ static void
PyThread__init_thread(void)
{
#if defined(_AIX) && defined(__GNUC__)
- pthread_init();
+ pthread_init();
#endif
}
@@ -147,59 +147,59 @@ PyThread__init_thread(void)
long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- pthread_t th;
- int status;
+ pthread_t th;
+ int status;
#if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
- pthread_attr_t attrs;
+ pthread_attr_t attrs;
#endif
#if defined(THREAD_STACK_SIZE)
- size_t tss;
+ size_t tss;
#endif
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
#if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
- if (pthread_attr_init(&attrs) != 0)
- return -1;
+ if (pthread_attr_init(&attrs) != 0)
+ return -1;
#endif
#if defined(THREAD_STACK_SIZE)
- tss = (_pythread_stacksize != 0) ? _pythread_stacksize
- : THREAD_STACK_SIZE;
- if (tss != 0) {
- if (pthread_attr_setstacksize(&attrs, tss) != 0) {
- pthread_attr_destroy(&attrs);
- return -1;
- }
- }
+ tss = (_pythread_stacksize != 0) ? _pythread_stacksize
+ : THREAD_STACK_SIZE;
+ if (tss != 0) {
+ if (pthread_attr_setstacksize(&attrs, tss) != 0) {
+ pthread_attr_destroy(&attrs);
+ return -1;
+ }
+ }
#endif
#if defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
- pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM);
+ pthread_attr_setscope(&attrs, PTHREAD_SCOPE_SYSTEM);
#endif
- status = pthread_create(&th,
+ status = pthread_create(&th,
#if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
- &attrs,
+ &attrs,
#else
- (pthread_attr_t*)NULL,
+ (pthread_attr_t*)NULL,
#endif
- (void* (*)(void *))func,
- (void *)arg
- );
+ (void* (*)(void *))func,
+ (void *)arg
+ );
#if defined(THREAD_STACK_SIZE) || defined(PTHREAD_SYSTEM_SCHED_SUPPORTED)
- pthread_attr_destroy(&attrs);
+ pthread_attr_destroy(&attrs);
#endif
- if (status != 0)
- return -1;
+ if (status != 0)
+ return -1;
- pthread_detach(th);
+ pthread_detach(th);
#if SIZEOF_PTHREAD_T <= SIZEOF_LONG
- return (long) th;
+ return (long) th;
#else
- return (long) *(long *) &th;
+ return (long) *(long *) &th;
#endif
}
@@ -210,28 +210,28 @@ PyThread_start_new_thread(void (*func)(void *), void *arg)
- It is not clear that the 'volatile' (for AIX?) and ugly casting in the
latter return statement (for Alpha OSF/1) are any longer necessary.
*/
-long
+long
PyThread_get_thread_ident(void)
{
- volatile pthread_t threadid;
- if (!initialized)
- PyThread_init_thread();
- /* Jump through some hoops for Alpha OSF/1 */
- threadid = pthread_self();
+ volatile pthread_t threadid;
+ if (!initialized)
+ PyThread_init_thread();
+ /* Jump through some hoops for Alpha OSF/1 */
+ threadid = pthread_self();
#if SIZEOF_PTHREAD_T <= SIZEOF_LONG
- return (long) threadid;
+ return (long) threadid;
#else
- return (long) *(long *) &threadid;
+ return (long) *(long *) &threadid;
#endif
}
-void
+void
PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized) {
- exit(0);
- }
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized) {
+ exit(0);
+ }
}
#ifdef USE_SEMAPHORES
@@ -240,47 +240,47 @@ PyThread_exit_thread(void)
* Lock support.
*/
-PyThread_type_lock
+PyThread_type_lock
PyThread_allocate_lock(void)
{
- sem_t *lock;
- int status, error = 0;
+ sem_t *lock;
+ int status, error = 0;
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- lock = (sem_t *)malloc(sizeof(sem_t));
+ lock = (sem_t *)malloc(sizeof(sem_t));
- if (lock) {
- status = sem_init(lock,0,1);
- CHECK_STATUS("sem_init");
+ if (lock) {
+ status = sem_init(lock,0,1);
+ CHECK_STATUS("sem_init");
- if (error) {
- free((void *)lock);
- lock = NULL;
- }
- }
+ if (error) {
+ free((void *)lock);
+ lock = NULL;
+ }
+ }
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock)lock;
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock)lock;
}
-void
+void
PyThread_free_lock(PyThread_type_lock lock)
{
- sem_t *thelock = (sem_t *)lock;
- int status, error = 0;
+ sem_t *thelock = (sem_t *)lock;
+ int status, error = 0;
- dprintf(("PyThread_free_lock(%p) called\n", lock));
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
- if (!thelock)
- return;
+ if (!thelock)
+ return;
- status = sem_destroy(thelock);
- CHECK_STATUS("sem_destroy");
+ status = sem_destroy(thelock);
+ CHECK_STATUS("sem_destroy");
- free((void *)thelock);
+ free((void *)thelock);
}
/*
@@ -292,47 +292,47 @@ PyThread_free_lock(PyThread_type_lock lock)
static int
fix_status(int status)
{
- return (status == -1) ? errno : status;
+ return (status == -1) ? errno : status;
}
-int
+int
PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
- sem_t *thelock = (sem_t *)lock;
- int status, error = 0;
-
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
-
- do {
- if (waitflag)
- status = fix_status(sem_wait(thelock));
- else
- status = fix_status(sem_trywait(thelock));
- } while (status == EINTR); /* Retry if interrupted by a signal */
-
- if (waitflag) {
- CHECK_STATUS("sem_wait");
- } else if (status != EAGAIN) {
- CHECK_STATUS("sem_trywait");
- }
-
- success = (status == 0) ? 1 : 0;
-
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ int success;
+ sem_t *thelock = (sem_t *)lock;
+ int status, error = 0;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+
+ do {
+ if (waitflag)
+ status = fix_status(sem_wait(thelock));
+ else
+ status = fix_status(sem_trywait(thelock));
+ } while (status == EINTR); /* Retry if interrupted by a signal */
+
+ if (waitflag) {
+ CHECK_STATUS("sem_wait");
+ } else if (status != EAGAIN) {
+ CHECK_STATUS("sem_trywait");
+ }
+
+ success = (status == 0) ? 1 : 0;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
-void
+void
PyThread_release_lock(PyThread_type_lock lock)
{
- sem_t *thelock = (sem_t *)lock;
- int status, error = 0;
+ sem_t *thelock = (sem_t *)lock;
+ int status, error = 0;
- dprintf(("PyThread_release_lock(%p) called\n", lock));
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
- status = sem_post(thelock);
- CHECK_STATUS("sem_post");
+ status = sem_post(thelock);
+ CHECK_STATUS("sem_post");
}
#else /* USE_SEMAPHORES */
@@ -340,109 +340,109 @@ PyThread_release_lock(PyThread_type_lock lock)
/*
* Lock support.
*/
-PyThread_type_lock
+PyThread_type_lock
PyThread_allocate_lock(void)
{
- pthread_lock *lock;
- int status, error = 0;
-
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
-
- lock = (pthread_lock *) malloc(sizeof(pthread_lock));
- if (lock) {
- memset((void *)lock, '\0', sizeof(pthread_lock));
- lock->locked = 0;
-
- status = pthread_mutex_init(&lock->mut,
- pthread_mutexattr_default);
- CHECK_STATUS("pthread_mutex_init");
-
- status = pthread_cond_init(&lock->lock_released,
- pthread_condattr_default);
- CHECK_STATUS("pthread_cond_init");
-
- if (error) {
- free((void *)lock);
- lock = 0;
- }
- }
-
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ pthread_lock *lock;
+ int status, error = 0;
+
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+
+ lock = (pthread_lock *) malloc(sizeof(pthread_lock));
+ if (lock) {
+ memset((void *)lock, '\0', sizeof(pthread_lock));
+ lock->locked = 0;
+
+ status = pthread_mutex_init(&lock->mut,
+ pthread_mutexattr_default);
+ CHECK_STATUS("pthread_mutex_init");
+
+ status = pthread_cond_init(&lock->lock_released,
+ pthread_condattr_default);
+ CHECK_STATUS("pthread_cond_init");
+
+ if (error) {
+ free((void *)lock);
+ lock = 0;
+ }
+ }
+
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
-void
+void
PyThread_free_lock(PyThread_type_lock lock)
{
- pthread_lock *thelock = (pthread_lock *)lock;
- int status, error = 0;
+ pthread_lock *thelock = (pthread_lock *)lock;
+ int status, error = 0;
- dprintf(("PyThread_free_lock(%p) called\n", lock));
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
- status = pthread_mutex_destroy( &thelock->mut );
- CHECK_STATUS("pthread_mutex_destroy");
+ status = pthread_mutex_destroy( &thelock->mut );
+ CHECK_STATUS("pthread_mutex_destroy");
- status = pthread_cond_destroy( &thelock->lock_released );
- CHECK_STATUS("pthread_cond_destroy");
+ status = pthread_cond_destroy( &thelock->lock_released );
+ CHECK_STATUS("pthread_cond_destroy");
- free((void *)thelock);
+ free((void *)thelock);
}
-int
+int
PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
- pthread_lock *thelock = (pthread_lock *)lock;
- int status, error = 0;
-
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
-
- status = pthread_mutex_lock( &thelock->mut );
- CHECK_STATUS("pthread_mutex_lock[1]");
- success = thelock->locked == 0;
-
- if ( !success && waitflag ) {
- /* continue trying until we get the lock */
-
- /* mut must be locked by me -- part of the condition
- * protocol */
- while ( thelock->locked ) {
- status = pthread_cond_wait(&thelock->lock_released,
- &thelock->mut);
- CHECK_STATUS("pthread_cond_wait");
- }
- success = 1;
- }
- if (success) thelock->locked = 1;
- status = pthread_mutex_unlock( &thelock->mut );
- CHECK_STATUS("pthread_mutex_unlock[1]");
-
- if (error) success = 0;
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ int success;
+ pthread_lock *thelock = (pthread_lock *)lock;
+ int status, error = 0;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+
+ status = pthread_mutex_lock( &thelock->mut );
+ CHECK_STATUS("pthread_mutex_lock[1]");
+ success = thelock->locked == 0;
+
+ if ( !success && waitflag ) {
+ /* continue trying until we get the lock */
+
+ /* mut must be locked by me -- part of the condition
+ * protocol */
+ while ( thelock->locked ) {
+ status = pthread_cond_wait(&thelock->lock_released,
+ &thelock->mut);
+ CHECK_STATUS("pthread_cond_wait");
+ }
+ success = 1;
+ }
+ if (success) thelock->locked = 1;
+ status = pthread_mutex_unlock( &thelock->mut );
+ CHECK_STATUS("pthread_mutex_unlock[1]");
+
+ if (error) success = 0;
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
-void
+void
PyThread_release_lock(PyThread_type_lock lock)
{
- pthread_lock *thelock = (pthread_lock *)lock;
- int status, error = 0;
+ pthread_lock *thelock = (pthread_lock *)lock;
+ int status, error = 0;
- dprintf(("PyThread_release_lock(%p) called\n", lock));
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
- status = pthread_mutex_lock( &thelock->mut );
- CHECK_STATUS("pthread_mutex_lock[3]");
+ status = pthread_mutex_lock( &thelock->mut );
+ CHECK_STATUS("pthread_mutex_lock[3]");
- thelock->locked = 0;
+ thelock->locked = 0;
- status = pthread_mutex_unlock( &thelock->mut );
- CHECK_STATUS("pthread_mutex_unlock[3]");
+ status = pthread_mutex_unlock( &thelock->mut );
+ CHECK_STATUS("pthread_mutex_unlock[3]");
- /* wake up someone (anyone, if any) waiting on the lock */
- status = pthread_cond_signal( &thelock->lock_released );
- CHECK_STATUS("pthread_cond_signal");
+ /* wake up someone (anyone, if any) waiting on the lock */
+ status = pthread_cond_signal( &thelock->lock_released );
+ CHECK_STATUS("pthread_cond_signal");
}
#endif /* USE_SEMAPHORES */
@@ -455,39 +455,39 @@ static int
_pythread_pthread_set_stacksize(size_t size)
{
#if defined(THREAD_STACK_SIZE)
- pthread_attr_t attrs;
- size_t tss_min;
- int rc = 0;
+ pthread_attr_t attrs;
+ size_t tss_min;
+ int rc = 0;
#endif
- /* set to default */
- if (size == 0) {
- _pythread_stacksize = 0;
- return 0;
- }
+ /* set to default */
+ if (size == 0) {
+ _pythread_stacksize = 0;
+ return 0;
+ }
#if defined(THREAD_STACK_SIZE)
#if defined(PTHREAD_STACK_MIN)
- tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN
- : THREAD_STACK_MIN;
+ tss_min = PTHREAD_STACK_MIN > THREAD_STACK_MIN ? PTHREAD_STACK_MIN
+ : THREAD_STACK_MIN;
#else
- tss_min = THREAD_STACK_MIN;
+ tss_min = THREAD_STACK_MIN;
#endif
- if (size >= tss_min) {
- /* validate stack size by setting thread attribute */
- if (pthread_attr_init(&attrs) == 0) {
- rc = pthread_attr_setstacksize(&attrs, size);
- pthread_attr_destroy(&attrs);
- if (rc == 0) {
- _pythread_stacksize = size;
- return 0;
- }
- }
- }
- return -1;
+ if (size >= tss_min) {
+ /* validate stack size by setting thread attribute */
+ if (pthread_attr_init(&attrs) == 0) {
+ rc = pthread_attr_setstacksize(&attrs, size);
+ pthread_attr_destroy(&attrs);
+ if (rc == 0) {
+ _pythread_stacksize = size;
+ return 0;
+ }
+ }
+ }
+ return -1;
#else
- return -2;
+ return -2;
#endif
}
-#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x)
+#define THREAD_SET_STACKSIZE(x) _pythread_pthread_set_stacksize(x)
diff --git a/Python/thread_sgi.h b/Python/thread_sgi.h
index 4f4b210..771ab2c 100644
--- a/Python/thread_sgi.h
+++ b/Python/thread_sgi.h
@@ -8,67 +8,67 @@
#include <ulocks.h>
#include <errno.h>
-#define HDR_SIZE 2680 /* sizeof(ushdr_t) */
-#define MAXPROC 100 /* max # of threads that can be started */
+#define HDR_SIZE 2680 /* sizeof(ushdr_t) */
+#define MAXPROC 100 /* max # of threads that can be started */
static usptr_t *shared_arena;
-static ulock_t count_lock; /* protection for some variables */
-static ulock_t wait_lock; /* lock used to wait for other threads */
-static int waiting_for_threads; /* protected by count_lock */
-static int nthreads; /* protected by count_lock */
+static ulock_t count_lock; /* protection for some variables */
+static ulock_t wait_lock; /* lock used to wait for other threads */
+static int waiting_for_threads; /* protected by count_lock */
+static int nthreads; /* protected by count_lock */
static int exit_status;
-static int exiting; /* we're already exiting (for maybe_exit) */
-static pid_t my_pid; /* PID of main thread */
+static int exiting; /* we're already exiting (for maybe_exit) */
+static pid_t my_pid; /* PID of main thread */
static struct pidlist {
- pid_t parent;
- pid_t child;
-} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */
-static int maxpidindex; /* # of PIDs in pidlist */
+ pid_t parent;
+ pid_t child;
+} pidlist[MAXPROC]; /* PIDs of other threads; protected by count_lock */
+static int maxpidindex; /* # of PIDs in pidlist */
/*
* Initialization.
*/
static void PyThread__init_thread(void)
{
#ifdef USE_DL
- long addr, size;
+ long addr, size;
#endif /* USE_DL */
#ifdef USE_DL
- if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0)
- perror("usconfig - CONF_INITSIZE (check)");
- if (usconfig(CONF_INITSIZE, size) < 0)
- perror("usconfig - CONF_INITSIZE (reset)");
- addr = (long) dl_getrange(size + HDR_SIZE);
- dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size));
- errno = 0;
- if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0)
- perror("usconfig - CONF_ATTACHADDR (set)");
+ if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0)
+ perror("usconfig - CONF_INITSIZE (check)");
+ if (usconfig(CONF_INITSIZE, size) < 0)
+ perror("usconfig - CONF_INITSIZE (reset)");
+ addr = (long) dl_getrange(size + HDR_SIZE);
+ dprintf(("trying to use addr %p-%p for shared arena\n", addr, addr+size));
+ errno = 0;
+ if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 && errno != 0)
+ perror("usconfig - CONF_ATTACHADDR (set)");
#endif /* USE_DL */
- if (usconfig(CONF_INITUSERS, 16) < 0)
- perror("usconfig - CONF_INITUSERS");
- my_pid = getpid(); /* so that we know which is the main thread */
- if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0)
- perror("usconfig - CONF_ARENATYPE");
- usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */
+ if (usconfig(CONF_INITUSERS, 16) < 0)
+ perror("usconfig - CONF_INITUSERS");
+ my_pid = getpid(); /* so that we know which is the main thread */
+ if (usconfig(CONF_ARENATYPE, US_SHAREDONLY) < 0)
+ perror("usconfig - CONF_ARENATYPE");
+ usconfig(CONF_LOCKTYPE, US_DEBUG); /* XXX */
#ifdef Py_DEBUG
- if (thread_debug & 4)
- usconfig(CONF_LOCKTYPE, US_DEBUGPLUS);
- else if (thread_debug & 2)
- usconfig(CONF_LOCKTYPE, US_DEBUG);
+ if (thread_debug & 4)
+ usconfig(CONF_LOCKTYPE, US_DEBUGPLUS);
+ else if (thread_debug & 2)
+ usconfig(CONF_LOCKTYPE, US_DEBUG);
#endif /* Py_DEBUG */
- if ((shared_arena = usinit(tmpnam(0))) == 0)
- perror("usinit");
+ if ((shared_arena = usinit(tmpnam(0))) == 0)
+ perror("usinit");
#ifdef USE_DL
- if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */
- perror("usconfig - CONF_ATTACHADDR (reset)");
+ if (usconfig(CONF_ATTACHADDR, addr) < 0) /* reset address */
+ perror("usconfig - CONF_ATTACHADDR (reset)");
#endif /* USE_DL */
- if ((count_lock = usnewlock(shared_arena)) == NULL)
- perror("usnewlock (count_lock)");
- (void) usinitlock(count_lock);
- if ((wait_lock = usnewlock(shared_arena)) == NULL)
- perror("usnewlock (wait_lock)");
- dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena)));
+ if ((count_lock = usnewlock(shared_arena)) == NULL)
+ perror("usnewlock (count_lock)");
+ (void) usinitlock(count_lock);
+ if ((wait_lock = usnewlock(shared_arena)) == NULL)
+ perror("usnewlock (wait_lock)");
+ dprintf(("arena start: %p, arena size: %ld\n", shared_arena, (long) usconfig(CONF_GETSIZE, shared_arena)));
}
/*
@@ -77,138 +77,138 @@ static void PyThread__init_thread(void)
static void clean_threads(void)
{
- int i, j;
- pid_t mypid, pid;
+ int i, j;
+ pid_t mypid, pid;
- /* clean up any exited threads */
- mypid = getpid();
- i = 0;
- while (i < maxpidindex) {
- if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) {
- pid = waitpid(pid, 0, WNOHANG);
- if (pid > 0) {
- /* a thread has exited */
- pidlist[i] = pidlist[--maxpidindex];
- /* remove references to children of dead proc */
- for (j = 0; j < maxpidindex; j++)
- if (pidlist[j].parent == pid)
- pidlist[j].child = -1;
- continue; /* don't increment i */
- }
- }
- i++;
- }
- /* clean up the list */
- i = 0;
- while (i < maxpidindex) {
- if (pidlist[i].child == -1) {
- pidlist[i] = pidlist[--maxpidindex];
- continue; /* don't increment i */
- }
- i++;
- }
+ /* clean up any exited threads */
+ mypid = getpid();
+ i = 0;
+ while (i < maxpidindex) {
+ if (pidlist[i].parent == mypid && (pid = pidlist[i].child) > 0) {
+ pid = waitpid(pid, 0, WNOHANG);
+ if (pid > 0) {
+ /* a thread has exited */
+ pidlist[i] = pidlist[--maxpidindex];
+ /* remove references to children of dead proc */
+ for (j = 0; j < maxpidindex; j++)
+ if (pidlist[j].parent == pid)
+ pidlist[j].child = -1;
+ continue; /* don't increment i */
+ }
+ }
+ i++;
+ }
+ /* clean up the list */
+ i = 0;
+ while (i < maxpidindex) {
+ if (pidlist[i].child == -1) {
+ pidlist[i] = pidlist[--maxpidindex];
+ continue; /* don't increment i */
+ }
+ i++;
+ }
}
long PyThread_start_new_thread(void (*func)(void *), void *arg)
{
#ifdef USE_DL
- long addr, size;
- static int local_initialized = 0;
+ long addr, size;
+ static int local_initialized = 0;
#endif /* USE_DL */
- int success = 0; /* init not needed when SOLARIS_THREADS and */
- /* C_THREADS implemented properly */
+ int success = 0; /* init not needed when SOLARIS_THREADS and */
+ /* C_THREADS implemented properly */
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
- switch (ussetlock(count_lock)) {
- case 0: return 0;
- case -1: perror("ussetlock (count_lock)");
- }
- if (maxpidindex >= MAXPROC)
- success = -1;
- else {
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+ switch (ussetlock(count_lock)) {
+ case 0: return 0;
+ case -1: perror("ussetlock (count_lock)");
+ }
+ if (maxpidindex >= MAXPROC)
+ success = -1;
+ else {
#ifdef USE_DL
- if (!local_initialized) {
- if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0)
- perror("usconfig - CONF_INITSIZE (check)");
- if (usconfig(CONF_INITSIZE, size) < 0)
- perror("usconfig - CONF_INITSIZE (reset)");
- addr = (long) dl_getrange(size + HDR_SIZE);
- dprintf(("trying to use addr %p-%p for sproc\n",
- addr, addr+size));
- errno = 0;
- if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 &&
- errno != 0)
- perror("usconfig - CONF_ATTACHADDR (set)");
- }
+ if (!local_initialized) {
+ if ((size = usconfig(CONF_INITSIZE, 64*1024)) < 0)
+ perror("usconfig - CONF_INITSIZE (check)");
+ if (usconfig(CONF_INITSIZE, size) < 0)
+ perror("usconfig - CONF_INITSIZE (reset)");
+ addr = (long) dl_getrange(size + HDR_SIZE);
+ dprintf(("trying to use addr %p-%p for sproc\n",
+ addr, addr+size));
+ errno = 0;
+ if ((addr = usconfig(CONF_ATTACHADDR, addr)) < 0 &&
+ errno != 0)
+ perror("usconfig - CONF_ATTACHADDR (set)");
+ }
#endif /* USE_DL */
- clean_threads();
- if ((success = sproc(func, PR_SALL, arg)) < 0)
- perror("sproc");
+ clean_threads();
+ if ((success = sproc(func, PR_SALL, arg)) < 0)
+ perror("sproc");
#ifdef USE_DL
- if (!local_initialized) {
- if (usconfig(CONF_ATTACHADDR, addr) < 0)
- /* reset address */
- perror("usconfig - CONF_ATTACHADDR (reset)");
- local_initialized = 1;
- }
+ if (!local_initialized) {
+ if (usconfig(CONF_ATTACHADDR, addr) < 0)
+ /* reset address */
+ perror("usconfig - CONF_ATTACHADDR (reset)");
+ local_initialized = 1;
+ }
#endif /* USE_DL */
- if (success >= 0) {
- nthreads++;
- pidlist[maxpidindex].parent = getpid();
- pidlist[maxpidindex++].child = success;
- dprintf(("pidlist[%d] = %d\n",
- maxpidindex-1, success));
- }
- }
- if (usunsetlock(count_lock) < 0)
- perror("usunsetlock (count_lock)");
- return success;
+ if (success >= 0) {
+ nthreads++;
+ pidlist[maxpidindex].parent = getpid();
+ pidlist[maxpidindex++].child = success;
+ dprintf(("pidlist[%d] = %d\n",
+ maxpidindex-1, success));
+ }
+ }
+ if (usunsetlock(count_lock) < 0)
+ perror("usunsetlock (count_lock)");
+ return success;
}
long PyThread_get_thread_ident(void)
{
- return getpid();
+ return getpid();
}
void PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized)
- exit(0);
- if (ussetlock(count_lock) < 0)
- perror("ussetlock (count_lock)");
- nthreads--;
- if (getpid() == my_pid) {
- /* main thread; wait for other threads to exit */
- exiting = 1;
- waiting_for_threads = 1;
- if (ussetlock(wait_lock) < 0)
- perror("ussetlock (wait_lock)");
- for (;;) {
- if (nthreads < 0) {
- dprintf(("really exit (%d)\n", exit_status));
- exit(exit_status);
- }
- if (usunsetlock(count_lock) < 0)
- perror("usunsetlock (count_lock)");
- dprintf(("waiting for other threads (%d)\n", nthreads));
- if (ussetlock(wait_lock) < 0)
- perror("ussetlock (wait_lock)");
- if (ussetlock(count_lock) < 0)
- perror("ussetlock (count_lock)");
- }
- }
- /* not the main thread */
- if (waiting_for_threads) {
- dprintf(("main thread is waiting\n"));
- if (usunsetlock(wait_lock) < 0)
- perror("usunsetlock (wait_lock)");
- }
- if (usunsetlock(count_lock) < 0)
- perror("usunsetlock (count_lock)");
- _exit(0);
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized)
+ exit(0);
+ if (ussetlock(count_lock) < 0)
+ perror("ussetlock (count_lock)");
+ nthreads--;
+ if (getpid() == my_pid) {
+ /* main thread; wait for other threads to exit */
+ exiting = 1;
+ waiting_for_threads = 1;
+ if (ussetlock(wait_lock) < 0)
+ perror("ussetlock (wait_lock)");
+ for (;;) {
+ if (nthreads < 0) {
+ dprintf(("really exit (%d)\n", exit_status));
+ exit(exit_status);
+ }
+ if (usunsetlock(count_lock) < 0)
+ perror("usunsetlock (count_lock)");
+ dprintf(("waiting for other threads (%d)\n", nthreads));
+ if (ussetlock(wait_lock) < 0)
+ perror("ussetlock (wait_lock)");
+ if (ussetlock(count_lock) < 0)
+ perror("ussetlock (count_lock)");
+ }
+ }
+ /* not the main thread */
+ if (waiting_for_threads) {
+ dprintf(("main thread is waiting\n"));
+ if (usunsetlock(wait_lock) < 0)
+ perror("usunsetlock (wait_lock)");
+ }
+ if (usunsetlock(count_lock) < 0)
+ perror("usunsetlock (count_lock)");
+ _exit(0);
}
/*
@@ -216,44 +216,44 @@ void PyThread_exit_thread(void)
*/
PyThread_type_lock PyThread_allocate_lock(void)
{
- ulock_t lock;
+ ulock_t lock;
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
- if ((lock = usnewlock(shared_arena)) == NULL)
- perror("usnewlock");
- (void) usinitlock(lock);
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ if ((lock = usnewlock(shared_arena)) == NULL)
+ perror("usnewlock");
+ (void) usinitlock(lock);
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
void PyThread_free_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_free_lock(%p) called\n", lock));
- usfreelock((ulock_t) lock, shared_arena);
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
+ usfreelock((ulock_t) lock, shared_arena);
}
int PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
+ int success;
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
- errno = 0; /* clear it just in case */
- if (waitflag)
- success = ussetlock((ulock_t) lock);
- else
- success = uscsetlock((ulock_t) lock, 1); /* Try it once */
- if (success < 0)
- perror(waitflag ? "ussetlock" : "uscsetlock");
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+ errno = 0; /* clear it just in case */
+ if (waitflag)
+ success = ussetlock((ulock_t) lock);
+ else
+ success = uscsetlock((ulock_t) lock, 1); /* Try it once */
+ if (success < 0)
+ perror(waitflag ? "ussetlock" : "uscsetlock");
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
void PyThread_release_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_release_lock(%p) called\n", lock));
- if (usunsetlock((ulock_t) lock) < 0)
- perror("usunsetlock");
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
+ if (usunsetlock((ulock_t) lock) < 0)
+ perror("usunsetlock");
}
diff --git a/Python/thread_solaris.h b/Python/thread_solaris.h
index 59ca002..1ce1cfc 100644
--- a/Python/thread_solaris.h
+++ b/Python/thread_solaris.h
@@ -17,114 +17,114 @@ static void PyThread__init_thread(void)
* Thread support.
*/
struct func_arg {
- void (*func)(void *);
- void *arg;
+ void (*func)(void *);
+ void *arg;
};
static void *
new_func(void *funcarg)
{
- void (*func)(void *);
- void *arg;
-
- func = ((struct func_arg *) funcarg)->func;
- arg = ((struct func_arg *) funcarg)->arg;
- free(funcarg);
- (*func)(arg);
- return 0;
+ void (*func)(void *);
+ void *arg;
+
+ func = ((struct func_arg *) funcarg)->func;
+ arg = ((struct func_arg *) funcarg)->arg;
+ free(funcarg);
+ (*func)(arg);
+ return 0;
}
long
PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- thread_t tid;
- struct func_arg *funcarg;
-
- dprintf(("PyThread_start_new_thread called\n"));
- if (!initialized)
- PyThread_init_thread();
- funcarg = (struct func_arg *) malloc(sizeof(struct func_arg));
- funcarg->func = func;
- funcarg->arg = arg;
- if (thr_create(0, 0, new_func, funcarg,
- THR_DETACHED | THR_NEW_LWP, &tid)) {
- perror("thr_create");
- free((void *) funcarg);
- return -1;
- }
- return tid;
+ thread_t tid;
+ struct func_arg *funcarg;
+
+ dprintf(("PyThread_start_new_thread called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+ funcarg = (struct func_arg *) malloc(sizeof(struct func_arg));
+ funcarg->func = func;
+ funcarg->arg = arg;
+ if (thr_create(0, 0, new_func, funcarg,
+ THR_DETACHED | THR_NEW_LWP, &tid)) {
+ perror("thr_create");
+ free((void *) funcarg);
+ return -1;
+ }
+ return tid;
}
long
PyThread_get_thread_ident(void)
{
- if (!initialized)
- PyThread_init_thread();
- return thr_self();
+ if (!initialized)
+ PyThread_init_thread();
+ return thr_self();
}
-void
+void
PyThread_exit_thread(void)
{
- dprintf(("PyThread_exit_thread called\n"));
- if (!initialized)
- exit(0);
- thr_exit(0);
+ dprintf(("PyThread_exit_thread called\n"));
+ if (!initialized)
+ exit(0);
+ thr_exit(0);
}
/*
* Lock support.
*/
-PyThread_type_lock
+PyThread_type_lock
PyThread_allocate_lock(void)
{
- mutex_t *lock;
-
- dprintf(("PyThread_allocate_lock called\n"));
- if (!initialized)
- PyThread_init_thread();
-
- lock = (mutex_t *) malloc(sizeof(mutex_t));
- if (mutex_init(lock, USYNC_THREAD, 0)) {
- perror("mutex_init");
- free((void *) lock);
- lock = 0;
- }
- dprintf(("PyThread_allocate_lock() -> %p\n", lock));
- return (PyThread_type_lock) lock;
+ mutex_t *lock;
+
+ dprintf(("PyThread_allocate_lock called\n"));
+ if (!initialized)
+ PyThread_init_thread();
+
+ lock = (mutex_t *) malloc(sizeof(mutex_t));
+ if (mutex_init(lock, USYNC_THREAD, 0)) {
+ perror("mutex_init");
+ free((void *) lock);
+ lock = 0;
+ }
+ dprintf(("PyThread_allocate_lock() -> %p\n", lock));
+ return (PyThread_type_lock) lock;
}
-void
+void
PyThread_free_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_free_lock(%p) called\n", lock));
- mutex_destroy((mutex_t *) lock);
- free((void *) lock);
+ dprintf(("PyThread_free_lock(%p) called\n", lock));
+ mutex_destroy((mutex_t *) lock);
+ free((void *) lock);
}
-int
+int
PyThread_acquire_lock(PyThread_type_lock lock, int waitflag)
{
- int success;
-
- dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
- if (waitflag)
- success = mutex_lock((mutex_t *) lock);
- else
- success = mutex_trylock((mutex_t *) lock);
- if (success < 0)
- perror(waitflag ? "mutex_lock" : "mutex_trylock");
- else
- success = !success; /* solaris does it the other way round */
- dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
- return success;
+ int success;
+
+ dprintf(("PyThread_acquire_lock(%p, %d) called\n", lock, waitflag));
+ if (waitflag)
+ success = mutex_lock((mutex_t *) lock);
+ else
+ success = mutex_trylock((mutex_t *) lock);
+ if (success < 0)
+ perror(waitflag ? "mutex_lock" : "mutex_trylock");
+ else
+ success = !success; /* solaris does it the other way round */
+ dprintf(("PyThread_acquire_lock(%p, %d) -> %d\n", lock, waitflag, success));
+ return success;
}
-void
+void
PyThread_release_lock(PyThread_type_lock lock)
{
- dprintf(("PyThread_release_lock(%p) called\n", lock));
- if (mutex_unlock((mutex_t *) lock))
- perror("mutex_unlock");
+ dprintf(("PyThread_release_lock(%p) called\n", lock));
+ if (mutex_unlock((mutex_t *) lock))
+ perror("mutex_unlock");
}
diff --git a/Python/thread_wince.h b/Python/thread_wince.h
index f8cf2cf..51ddc02 100644
--- a/Python/thread_wince.h
+++ b/Python/thread_wince.h
@@ -24,21 +24,21 @@ static void PyThread__init_thread(void)
*/
long PyThread_start_new_thread(void (*func)(void *), void *arg)
{
- long rv;
- int success = -1;
+ long rv;
+ int success = -1;
- dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident()));
- if (!initialized)
- PyThread_init_thread();
+ dprintf(("%ld: PyThread_start_new_thread called\n", PyThread_get_thread_ident()));
+ if (!initialized)
+ PyThread_init_thread();
- rv = _beginthread(func, 0, arg); /* use default stack size */
-
- if (rv != -1) {
- success = 0;
- dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident()));
- }
+ rv = _beginthread(func, 0, arg); /* use default stack size */
- return success;
+ if (rv != -1) {
+ success = 0;
+ dprintf(("%ld: PyThread_start_new_thread succeeded:\n", PyThread_get_thread_ident()));
+ }
+
+ return success;
}
/*
@@ -47,18 +47,18 @@ long PyThread_start_new_thread(void (*func)(void *), void *arg)
*/
long PyThread_get_thread_ident(void)
{
- if (!initialized)
- PyThread_init_thread();
-
- return GetCurrentThreadId();
+ if (!initialized)
+ PyThread_init_thread();
+
+ return GetCurrentThreadId();
}
void PyThread_exit_thread(void)
{
- dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
- if (!initialized)
- exit(0);
- _endthread();
+ dprintf(("%ld: PyThread_exit_thread called\n", PyThread_get_thread_ident()));
+ if (!initialized)
+ exit(0);
+ _endthread();
}
/*
@@ -72,12 +72,12 @@ PyThread_type_lock PyThread_allocate_lock(void)
dprintf(("PyThread_allocate_lock called\n"));
if (!initialized)
- PyThread_init_thread();
+ PyThread_init_thread();
aLock = CreateEvent(NULL, /* Security attributes */
- 0, /* Manual-Reset */
- 1, /* Is initially signalled */
- NULL); /* Name of event */
+ 0, /* Manual-Reset */
+ 1, /* Is initially signalled */
+ NULL); /* Name of event */
dprintf(("%ld: PyThread_allocate_lock() -> %p\n", PyThread_get_thread_ident(), aLock));
@@ -107,22 +107,22 @@ int PyThread_acquire_lock(PyThread_type_lock aLock, int waitflag)
#ifndef DEBUG
waitResult = WaitForSingleObject(aLock, (waitflag ? INFINITE : 0));
#else
- /* To aid in debugging, we regularly wake up. This allows us to
- break into the debugger */
- while (TRUE) {
- waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0);
- if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0))
- break;
- }
+ /* To aid in debugging, we regularly wake up. This allows us to
+ break into the debugger */
+ while (TRUE) {
+ waitResult = WaitForSingleObject(aLock, waitflag ? 3000 : 0);
+ if (waitflag==0 || (waitflag && waitResult == WAIT_OBJECT_0))
+ break;
+ }
#endif
if (waitResult != WAIT_OBJECT_0) {
- success = 0; /* We failed */
+ success = 0; /* We failed */
}
- dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success));
+ dprintf(("%ld: PyThread_acquire_lock(%p, %d) -> %d\n", PyThread_get_thread_ident(),aLock, waitflag, success));
- return success;
+ return success;
}
void PyThread_release_lock(PyThread_type_lock aLock)
@@ -130,7 +130,7 @@ void PyThread_release_lock(PyThread_type_lock aLock)
dprintf(("%ld: PyThread_release_lock(%p) called\n", PyThread_get_thread_ident(),aLock));
if (!SetEvent(aLock))
- dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError()));
+ dprintf(("%ld: Could not PyThread_release_lock(%p) error: %l\n", PyThread_get_thread_ident(), aLock, GetLastError()));
}
diff --git a/Python/traceback.c b/Python/traceback.c
index 53491ee..adfd66c 100644
--- a/Python/traceback.c
+++ b/Python/traceback.c
@@ -12,272 +12,272 @@
#define OFF(x) offsetof(PyTracebackObject, x)
static PyMemberDef tb_memberlist[] = {
- {"tb_next", T_OBJECT, OFF(tb_next), READONLY},
- {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY},
- {"tb_lasti", T_INT, OFF(tb_lasti), READONLY},
- {"tb_lineno", T_INT, OFF(tb_lineno), READONLY},
- {NULL} /* Sentinel */
+ {"tb_next", T_OBJECT, OFF(tb_next), READONLY},
+ {"tb_frame", T_OBJECT, OFF(tb_frame), READONLY},
+ {"tb_lasti", T_INT, OFF(tb_lasti), READONLY},
+ {"tb_lineno", T_INT, OFF(tb_lineno), READONLY},
+ {NULL} /* Sentinel */
};
static void
tb_dealloc(PyTracebackObject *tb)
{
- PyObject_GC_UnTrack(tb);
- Py_TRASHCAN_SAFE_BEGIN(tb)
- Py_XDECREF(tb->tb_next);
- Py_XDECREF(tb->tb_frame);
- PyObject_GC_Del(tb);
- Py_TRASHCAN_SAFE_END(tb)
+ PyObject_GC_UnTrack(tb);
+ Py_TRASHCAN_SAFE_BEGIN(tb)
+ Py_XDECREF(tb->tb_next);
+ Py_XDECREF(tb->tb_frame);
+ PyObject_GC_Del(tb);
+ Py_TRASHCAN_SAFE_END(tb)
}
static int
tb_traverse(PyTracebackObject *tb, visitproc visit, void *arg)
{
- Py_VISIT(tb->tb_next);
- Py_VISIT(tb->tb_frame);
- return 0;
+ Py_VISIT(tb->tb_next);
+ Py_VISIT(tb->tb_frame);
+ return 0;
}
static void
tb_clear(PyTracebackObject *tb)
{
- Py_CLEAR(tb->tb_next);
- Py_CLEAR(tb->tb_frame);
+ Py_CLEAR(tb->tb_next);
+ Py_CLEAR(tb->tb_frame);
}
PyTypeObject PyTraceBack_Type = {
- PyVarObject_HEAD_INIT(&PyType_Type, 0)
- "traceback",
- sizeof(PyTracebackObject),
- 0,
- (destructor)tb_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_HAVE_GC,/* tp_flags */
- 0, /* tp_doc */
- (traverseproc)tb_traverse, /* tp_traverse */
- (inquiry)tb_clear, /* tp_clear */
- 0, /* tp_richcompare */
- 0, /* tp_weaklistoffset */
- 0, /* tp_iter */
- 0, /* tp_iternext */
- 0, /* tp_methods */
- tb_memberlist, /* tp_members */
- 0, /* tp_getset */
- 0, /* tp_base */
- 0, /* tp_dict */
+ PyVarObject_HEAD_INIT(&PyType_Type, 0)
+ "traceback",
+ sizeof(PyTracebackObject),
+ 0,
+ (destructor)tb_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_HAVE_GC,/* tp_flags */
+ 0, /* tp_doc */
+ (traverseproc)tb_traverse, /* tp_traverse */
+ (inquiry)tb_clear, /* tp_clear */
+ 0, /* tp_richcompare */
+ 0, /* tp_weaklistoffset */
+ 0, /* tp_iter */
+ 0, /* tp_iternext */
+ 0, /* tp_methods */
+ tb_memberlist, /* tp_members */
+ 0, /* tp_getset */
+ 0, /* tp_base */
+ 0, /* tp_dict */
};
static PyTracebackObject *
newtracebackobject(PyTracebackObject *next, PyFrameObject *frame)
{
- PyTracebackObject *tb;
- if ((next != NULL && !PyTraceBack_Check(next)) ||
- frame == NULL || !PyFrame_Check(frame)) {
- PyErr_BadInternalCall();
- return NULL;
- }
- tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type);
- if (tb != NULL) {
- Py_XINCREF(next);
- tb->tb_next = next;
- Py_XINCREF(frame);
- tb->tb_frame = frame;
- tb->tb_lasti = frame->f_lasti;
- tb->tb_lineno = PyFrame_GetLineNumber(frame);
- PyObject_GC_Track(tb);
- }
- return tb;
+ PyTracebackObject *tb;
+ if ((next != NULL && !PyTraceBack_Check(next)) ||
+ frame == NULL || !PyFrame_Check(frame)) {
+ PyErr_BadInternalCall();
+ return NULL;
+ }
+ tb = PyObject_GC_New(PyTracebackObject, &PyTraceBack_Type);
+ if (tb != NULL) {
+ Py_XINCREF(next);
+ tb->tb_next = next;
+ Py_XINCREF(frame);
+ tb->tb_frame = frame;
+ tb->tb_lasti = frame->f_lasti;
+ tb->tb_lineno = PyFrame_GetLineNumber(frame);
+ PyObject_GC_Track(tb);
+ }
+ return tb;
}
int
PyTraceBack_Here(PyFrameObject *frame)
{
- PyThreadState *tstate = PyThreadState_GET();
- PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback;
- PyTracebackObject *tb = newtracebackobject(oldtb, frame);
- if (tb == NULL)
- return -1;
- tstate->curexc_traceback = (PyObject *)tb;
- Py_XDECREF(oldtb);
- return 0;
+ PyThreadState *tstate = PyThreadState_GET();
+ PyTracebackObject *oldtb = (PyTracebackObject *) tstate->curexc_traceback;
+ PyTracebackObject *tb = newtracebackobject(oldtb, frame);
+ if (tb == NULL)
+ return -1;
+ tstate->curexc_traceback = (PyObject *)tb;
+ Py_XDECREF(oldtb);
+ return 0;
}
int
_Py_DisplaySourceLine(PyObject *f, const char *filename, int lineno, int indent)
{
- int err = 0;
- FILE *xfp = NULL;
- char linebuf[2000];
- int i;
- char namebuf[MAXPATHLEN+1];
+ int err = 0;
+ FILE *xfp = NULL;
+ char linebuf[2000];
+ int i;
+ char namebuf[MAXPATHLEN+1];
- if (filename == NULL)
- return -1;
- /* This is needed by Emacs' compile command */
+ if (filename == NULL)
+ return -1;
+ /* This is needed by Emacs' compile command */
#define FMT " File \"%.500s\", line %d, in %.500s\n"
- xfp = fopen(filename, "r" PY_STDIOTEXTMODE);
- if (xfp == NULL) {
- /* Search tail of filename in sys.path before giving up */
- PyObject *path;
- const char *tail = strrchr(filename, SEP);
- if (tail == NULL)
- tail = filename;
- else
- tail++;
- path = PySys_GetObject("path");
- if (path != NULL && PyList_Check(path)) {
- Py_ssize_t _npath = PyList_Size(path);
- int npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int);
- size_t taillen = strlen(tail);
- for (i = 0; i < npath; i++) {
- PyObject *v = PyList_GetItem(path, i);
- if (v == NULL) {
- PyErr_Clear();
- break;
- }
- if (PyString_Check(v)) {
- size_t len;
- len = PyString_GET_SIZE(v);
- if (len + 1 + taillen >= MAXPATHLEN)
- continue; /* Too long */
- strcpy(namebuf, PyString_AsString(v));
- if (strlen(namebuf) != len)
- continue; /* v contains '\0' */
- if (len > 0 && namebuf[len-1] != SEP)
- namebuf[len++] = SEP;
- strcpy(namebuf+len, tail);
- xfp = fopen(namebuf, "r" PY_STDIOTEXTMODE);
- if (xfp != NULL) {
- break;
- }
- }
- }
- }
- }
-
- if (xfp == NULL)
- return err;
- if (err != 0) {
- fclose(xfp);
- return err;
+ xfp = fopen(filename, "r" PY_STDIOTEXTMODE);
+ if (xfp == NULL) {
+ /* Search tail of filename in sys.path before giving up */
+ PyObject *path;
+ const char *tail = strrchr(filename, SEP);
+ if (tail == NULL)
+ tail = filename;
+ else
+ tail++;
+ path = PySys_GetObject("path");
+ if (path != NULL && PyList_Check(path)) {
+ Py_ssize_t _npath = PyList_Size(path);
+ int npath = Py_SAFE_DOWNCAST(_npath, Py_ssize_t, int);
+ size_t taillen = strlen(tail);
+ for (i = 0; i < npath; i++) {
+ PyObject *v = PyList_GetItem(path, i);
+ if (v == NULL) {
+ PyErr_Clear();
+ break;
+ }
+ if (PyString_Check(v)) {
+ size_t len;
+ len = PyString_GET_SIZE(v);
+ if (len + 1 + taillen >= MAXPATHLEN)
+ continue; /* Too long */
+ strcpy(namebuf, PyString_AsString(v));
+ if (strlen(namebuf) != len)
+ continue; /* v contains '\0' */
+ if (len > 0 && namebuf[len-1] != SEP)
+ namebuf[len++] = SEP;
+ strcpy(namebuf+len, tail);
+ xfp = fopen(namebuf, "r" PY_STDIOTEXTMODE);
+ if (xfp != NULL) {
+ break;
+ }
+ }
+ }
}
+ }
+
+ if (xfp == NULL)
+ return err;
+ if (err != 0) {
+ fclose(xfp);
+ return err;
+ }
- for (i = 0; i < lineno; i++) {
- char* pLastChar = &linebuf[sizeof(linebuf)-2];
- do {
- *pLastChar = '\0';
- if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, xfp, NULL) == NULL)
- break;
- /* fgets read *something*; if it didn't get as
- far as pLastChar, it must have found a newline
- or hit the end of the file; if pLastChar is \n,
- it obviously found a newline; else we haven't
- yet seen a newline, so must continue */
- } while (*pLastChar != '\0' && *pLastChar != '\n');
- }
- if (i == lineno) {
- char buf[11];
- char *p = linebuf;
- while (*p == ' ' || *p == '\t' || *p == '\014')
- p++;
+ for (i = 0; i < lineno; i++) {
+ char* pLastChar = &linebuf[sizeof(linebuf)-2];
+ do {
+ *pLastChar = '\0';
+ if (Py_UniversalNewlineFgets(linebuf, sizeof linebuf, xfp, NULL) == NULL)
+ break;
+ /* fgets read *something*; if it didn't get as
+ far as pLastChar, it must have found a newline
+ or hit the end of the file; if pLastChar is \n,
+ it obviously found a newline; else we haven't
+ yet seen a newline, so must continue */
+ } while (*pLastChar != '\0' && *pLastChar != '\n');
+ }
+ if (i == lineno) {
+ char buf[11];
+ char *p = linebuf;
+ while (*p == ' ' || *p == '\t' || *p == '\014')
+ p++;
- /* Write some spaces before the line */
- strcpy(buf, " ");
- assert (strlen(buf) == 10);
- while (indent > 0) {
- if(indent < 10)
- buf[indent] = '\0';
- err = PyFile_WriteString(buf, f);
- if (err != 0)
- break;
- indent -= 10;
- }
+ /* Write some spaces before the line */
+ strcpy(buf, " ");
+ assert (strlen(buf) == 10);
+ while (indent > 0) {
+ if(indent < 10)
+ buf[indent] = '\0';
+ err = PyFile_WriteString(buf, f);
+ if (err != 0)
+ break;
+ indent -= 10;
+ }
- if (err == 0)
- err = PyFile_WriteString(p, f);
- if (err == 0 && strchr(p, '\n') == NULL)
- err = PyFile_WriteString("\n", f);
- }
- fclose(xfp);
- return err;
+ if (err == 0)
+ err = PyFile_WriteString(p, f);
+ if (err == 0 && strchr(p, '\n') == NULL)
+ err = PyFile_WriteString("\n", f);
+ }
+ fclose(xfp);
+ return err;
}
static int
tb_displayline(PyObject *f, const char *filename, int lineno, const char *name)
{
- int err = 0;
- char linebuf[2000];
+ int err = 0;
+ char linebuf[2000];
- if (filename == NULL || name == NULL)
- return -1;
- /* This is needed by Emacs' compile command */
+ if (filename == NULL || name == NULL)
+ return -1;
+ /* This is needed by Emacs' compile command */
#define FMT " File \"%.500s\", line %d, in %.500s\n"
- PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name);
- err = PyFile_WriteString(linebuf, f);
- if (err != 0)
- return err;
- return _Py_DisplaySourceLine(f, filename, lineno, 4);
+ PyOS_snprintf(linebuf, sizeof(linebuf), FMT, filename, lineno, name);
+ err = PyFile_WriteString(linebuf, f);
+ if (err != 0)
+ return err;
+ return _Py_DisplaySourceLine(f, filename, lineno, 4);
}
static int
tb_printinternal(PyTracebackObject *tb, PyObject *f, long limit)
{
- int err = 0;
- long depth = 0;
- PyTracebackObject *tb1 = tb;
- while (tb1 != NULL) {
- depth++;
- tb1 = tb1->tb_next;
- }
- while (tb != NULL && err == 0) {
- if (depth <= limit) {
- err = tb_displayline(f,
- PyString_AsString(
- tb->tb_frame->f_code->co_filename),
- tb->tb_lineno,
- PyString_AsString(tb->tb_frame->f_code->co_name));
- }
- depth--;
- tb = tb->tb_next;
- if (err == 0)
- err = PyErr_CheckSignals();
- }
- return err;
+ int err = 0;
+ long depth = 0;
+ PyTracebackObject *tb1 = tb;
+ while (tb1 != NULL) {
+ depth++;
+ tb1 = tb1->tb_next;
+ }
+ while (tb != NULL && err == 0) {
+ if (depth <= limit) {
+ err = tb_displayline(f,
+ PyString_AsString(
+ tb->tb_frame->f_code->co_filename),
+ tb->tb_lineno,
+ PyString_AsString(tb->tb_frame->f_code->co_name));
+ }
+ depth--;
+ tb = tb->tb_next;
+ if (err == 0)
+ err = PyErr_CheckSignals();
+ }
+ return err;
}
int
PyTraceBack_Print(PyObject *v, PyObject *f)
{
- int err;
- PyObject *limitv;
- long limit = 1000;
- if (v == NULL)
- return 0;
- if (!PyTraceBack_Check(v)) {
- PyErr_BadInternalCall();
- return -1;
- }
- limitv = PySys_GetObject("tracebacklimit");
- if (limitv && PyInt_Check(limitv)) {
- limit = PyInt_AsLong(limitv);
- if (limit <= 0)
- return 0;
- }
- err = PyFile_WriteString("Traceback (most recent call last):\n", f);
- if (!err)
- err = tb_printinternal((PyTracebackObject *)v, f, limit);
- return err;
+ int err;
+ PyObject *limitv;
+ long limit = 1000;
+ if (v == NULL)
+ return 0;
+ if (!PyTraceBack_Check(v)) {
+ PyErr_BadInternalCall();
+ return -1;
+ }
+ limitv = PySys_GetObject("tracebacklimit");
+ if (limitv && PyInt_Check(limitv)) {
+ limit = PyInt_AsLong(limitv);
+ if (limit <= 0)
+ return 0;
+ }
+ err = PyFile_WriteString("Traceback (most recent call last):\n", f);
+ if (!err)
+ err = tb_printinternal((PyTracebackObject *)v, f, limit);
+ return err;
}
diff --git a/RISCOS/Modules/config.c b/RISCOS/Modules/config.c
index 54fbc79..c498e98 100644
--- a/RISCOS/Modules/config.c
+++ b/RISCOS/Modules/config.c
@@ -49,25 +49,25 @@ extern void initswi(void);
struct _inittab _PyImport_Inittab[] = {
- {"riscos", initriscos},
+ {"riscos", initriscos},
/* -- ADDMODULE MARKER 2 -- */
- /* This module "lives in" with marshal.c */
- {"marshal", PyMarshal_Init},
+ /* This module "lives in" with marshal.c */
+ {"marshal", PyMarshal_Init},
- /* This lives it with import.c */
- {"imp", initimp},
+ /* This lives it with import.c */
+ {"imp", initimp},
- /* These entries are here for sys.builtin_module_names */
- {"__main__", NULL},
- {"__builtin__", NULL},
- {"sys", NULL},
- {"exceptions", NULL},
+ /* These entries are here for sys.builtin_module_names */
+ {"__main__", NULL},
+ {"__builtin__", NULL},
+ {"sys", NULL},
+ {"exceptions", NULL},
- /* This lives in gcmodule.c */
- {"gc", initgc},
+ /* This lives in gcmodule.c */
+ {"gc", initgc},
- /* Sentinel */
- {0, 0}
+ /* Sentinel */
+ {0, 0}
};
diff --git a/RISCOS/Modules/getpath_riscos.c b/RISCOS/Modules/getpath_riscos.c
index ce978c6..11e92c1 100644
--- a/RISCOS/Modules/getpath_riscos.c
+++ b/RISCOS/Modules/getpath_riscos.c
@@ -5,24 +5,24 @@ static char *prefix, *exec_prefix, *progpath, *module_search_path=NULL;
static void
calculate_path()
-{
- char *pypath = getenv("Python$Path");
- if (pypath) {
- int pathlen = strlen(pypath);
- module_search_path = malloc(pathlen + 1);
- if (module_search_path)
- strncpy(module_search_path, pypath, pathlen + 1);
- else {
- fprintf(stderr,
- "Not enough memory for dynamic PYTHONPATH.\n"
- "Using default static PYTHONPATH.\n");
- }
- }
- if (!module_search_path)
- module_search_path = "<Python$Dir>.Lib";
- prefix = "<Python$Dir>";
- exec_prefix = prefix;
- progpath = Py_GetProgramName();
+{
+ char *pypath = getenv("Python$Path");
+ if (pypath) {
+ int pathlen = strlen(pypath);
+ module_search_path = malloc(pathlen + 1);
+ if (module_search_path)
+ strncpy(module_search_path, pypath, pathlen + 1);
+ else {
+ fprintf(stderr,
+ "Not enough memory for dynamic PYTHONPATH.\n"
+ "Using default static PYTHONPATH.\n");
+ }
+ }
+ if (!module_search_path)
+ module_search_path = "<Python$Dir>.Lib";
+ prefix = "<Python$Dir>";
+ exec_prefix = prefix;
+ progpath = Py_GetProgramName();
}
/* External interface */
@@ -30,31 +30,31 @@ calculate_path()
char *
Py_GetPath()
{
- if (!module_search_path)
- calculate_path();
- return module_search_path;
+ if (!module_search_path)
+ calculate_path();
+ return module_search_path;
}
char *
Py_GetPrefix()
{
- if (!module_search_path)
- calculate_path();
- return prefix;
+ if (!module_search_path)
+ calculate_path();
+ return prefix;
}
char *
Py_GetExecPrefix()
{
- if (!module_search_path)
- calculate_path();
- return exec_prefix;
+ if (!module_search_path)
+ calculate_path();
+ return exec_prefix;
}
char *
Py_GetProgramFullPath()
{
- if (!module_search_path)
- calculate_path();
- return progpath;
+ if (!module_search_path)
+ calculate_path();
+ return progpath;
}
diff --git a/RISCOS/Modules/riscosmodule.c b/RISCOS/Modules/riscosmodule.c
index 3dabb4d..4387383 100644
--- a/RISCOS/Modules/riscosmodule.c
+++ b/RISCOS/Modules/riscosmodule.c
@@ -19,13 +19,13 @@ static os_error *e;
static PyObject *riscos_error(char *s)
{
- PyErr_SetString(PyExc_OSError, s);
- return NULL;
+ PyErr_SetString(PyExc_OSError, s);
+ return NULL;
}
static PyObject *riscos_oserror(void)
{
- return riscos_error(e->errmess);
+ return riscos_error(e->errmess);
}
@@ -35,40 +35,40 @@ static PyObject *
riscos_remove(PyObject *self, PyObject *args)
{
char *path1;
- if (!PyArg_ParseTuple(args, "s:remove", &path1)) return NULL;
- if (remove(path1)) return PyErr_SetFromErrno(PyExc_OSError);
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "s:remove", &path1)) return NULL;
+ if (remove(path1)) return PyErr_SetFromErrno(PyExc_OSError);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
riscos_rename(PyObject *self, PyObject *args)
{
- char *path1, *path2;
- if (!PyArg_ParseTuple(args, "ss:rename", &path1, &path2))
- return NULL;
- if (rename(path1,path2)) return PyErr_SetFromErrno(PyExc_OSError);
- Py_INCREF(Py_None);
- return Py_None;
+ char *path1, *path2;
+ if (!PyArg_ParseTuple(args, "ss:rename", &path1, &path2))
+ return NULL;
+ if (rename(path1,path2)) return PyErr_SetFromErrno(PyExc_OSError);
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
riscos_system(PyObject *self, PyObject *args)
{
- char *command;
- if (!PyArg_ParseTuple(args, "s:system", &command)) return NULL;
- return PyInt_FromLong(system(command));
+ char *command;
+ if (!PyArg_ParseTuple(args, "s:system", &command)) return NULL;
+ return PyInt_FromLong(system(command));
}
static PyObject *
riscos_chdir(PyObject *self, PyObject *args)
{
- char *path;
- if (!PyArg_ParseTuple(args, "s:chdir", &path)) return NULL;
- e=xosfscontrol_dir(path);
- if(e) return riscos_oserror();
- Py_INCREF(Py_None);
- return Py_None;
+ char *path;
+ if (!PyArg_ParseTuple(args, "s:chdir", &path)) return NULL;
+ e=xosfscontrol_dir(path);
+ if(e) return riscos_oserror();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
@@ -98,46 +98,46 @@ riscos_getcwd(PyObject *self, PyObject *unused)
static PyObject *
riscos_expand(PyObject *self, PyObject *args)
{
- char *path;
- if (!PyArg_ParseTuple(args, "s:expand", &path)) return NULL;
- return canon(path);
+ char *path;
+ if (!PyArg_ParseTuple(args, "s:expand", &path)) return NULL;
+ return canon(path);
}
static PyObject *
riscos_mkdir(PyObject *self, PyObject *args)
{
- char *path;
+ char *path;
int mode;
if (!PyArg_ParseTuple(args, "s|i:mkdir", &path, &mode)) return NULL;
e=xosfile_create_dir(path,0);
if(e) return riscos_oserror();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
riscos_listdir(PyObject *self, PyObject *args)
{
- char *path,buf[256];
+ char *path,buf[256];
PyObject *d, *v;
int c=0,count;
- if (!PyArg_ParseTuple(args, "s:listdir", &path)) return NULL;
- d=PyList_New(0);
- if(!d) return NULL;
- for(;;)
- { e=xosgbpb_dir_entries(path,(osgbpb_string_list*)buf,
- 1,c,256,0,&count,&c);
- if(e)
- { Py_DECREF(d);return riscos_oserror();
- }
- if(count)
- { v=PyString_FromString(buf);
- if(!v) { Py_DECREF(d);return 0;}
- if(PyList_Append(d,v)) {Py_DECREF(d);Py_DECREF(v);return 0;}
- }
- if(c==-1) break;
- }
- return d;
+ if (!PyArg_ParseTuple(args, "s:listdir", &path)) return NULL;
+ d=PyList_New(0);
+ if(!d) return NULL;
+ for(;;)
+ { e=xosgbpb_dir_entries(path,(osgbpb_string_list*)buf,
+ 1,c,256,0,&count,&c);
+ if(e)
+ { Py_DECREF(d);return riscos_oserror();
+ }
+ if(count)
+ { v=PyString_FromString(buf);
+ if(!v) { Py_DECREF(d);return 0;}
+ if(PyList_Append(d,v)) {Py_DECREF(d);Py_DECREF(v);return 0;}
+ }
+ if(c==-1) break;
+ }
+ return d;
}
PyDoc_STRVAR(stat_result__doc__,
@@ -151,167 +151,167 @@ RiscOS: The fields st_ftype, st_attrs, and st_obtype are also available.\n\
See os.stat for more information.");
static PyStructSequence_Field stat_result_fields[] = {
- { "st_mode", "protection bits" },
- { "st_ino", "inode" },
- { "st_dev", "device" },
- { "st_nlink", "number of hard links" },
- { "st_uid", "user ID of owner" },
- { "st_gid", "group ID of owner" },
- { "st_size", "total size, in bytes" },
- { "st_atime", "time of last access" },
- { "st_mtime", "time of last modification" },
- { "st_ctime", "time of last change" },
- { "st_ftype", "file type" },
- { "st_attrs", "attributes" },
- { "st_obtype", "object type" },
- { 0 }
+ { "st_mode", "protection bits" },
+ { "st_ino", "inode" },
+ { "st_dev", "device" },
+ { "st_nlink", "number of hard links" },
+ { "st_uid", "user ID of owner" },
+ { "st_gid", "group ID of owner" },
+ { "st_size", "total size, in bytes" },
+ { "st_atime", "time of last access" },
+ { "st_mtime", "time of last modification" },
+ { "st_ctime", "time of last change" },
+ { "st_ftype", "file type" },
+ { "st_attrs", "attributes" },
+ { "st_obtype", "object type" },
+ { 0 }
};
static PyStructSequence_Desc stat_result_desc = {
- "riscos.stat_result",
- stat_result__doc__,
- stat_result_fields,
- 13
+ "riscos.stat_result",
+ stat_result__doc__,
+ stat_result_fields,
+ 13
};
static PyTypeObject StatResultType;
static PyObject *
riscos_stat(PyObject *self, PyObject *args)
-{
- PyObject *v;
- char *path;
- int ob,len;
- bits t=0;
- bits ld,ex,at,ft,mode;
- if (!PyArg_ParseTuple(args, "s:stat", &path)) return NULL;
- e=xosfile_read_stamped_no_path(path,&ob,&ld,&ex,&len,&at,&ft);
- if(e) return riscos_oserror();
- switch (ob)
- { case osfile_IS_FILE:mode=0100000;break; /* OCTAL */
- case osfile_IS_DIR:mode=040000;break;
- case osfile_IS_IMAGE:mode=0140000;break;
- default:return riscos_error("Not found");
- }
- if(ft!=-1) t=unixtime(ld,ex);
- mode|=(at&7)<<6;
- mode|=((at&112)*9)>>4;
-
- v = PyStructSequence_New(&StatResultType);
-
- PyStructSequence_SET_ITEM(v, 0,
- PyInt_FromLong((long) mode)); /*st_mode*/
- PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) 0)); /*st_ino*/
- PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) 0)); /*st_dev*/
- PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) 0)); /*st_nlink*/
- PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) 0)); /*st_uid*/
- PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) 0)); /*st_gid*/
- PyStructSequence_SET_ITEM(v, 6,
- PyInt_FromLong((long) len)); /*st_size*/
- PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) t)); /*st_atime*/
- PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) t)); /*st_mtime*/
- PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) t)); /*st_ctime*/
- PyStructSequence_SET_ITEM(v, 10,
- PyInt_FromLong((long) ft)); /*file type*/
- PyStructSequence_SET_ITEM(v, 11,
- PyInt_FromLong((long) at)); /*attributes*/
- PyStructSequence_SET_ITEM(v, 12,
- PyInt_FromLong((long) ob)); /*object type*/
-
- if (PyErr_Occurred()) {
- Py_DECREF(v);
- return NULL;
- }
-
- return v;
+{
+ PyObject *v;
+ char *path;
+ int ob,len;
+ bits t=0;
+ bits ld,ex,at,ft,mode;
+ if (!PyArg_ParseTuple(args, "s:stat", &path)) return NULL;
+ e=xosfile_read_stamped_no_path(path,&ob,&ld,&ex,&len,&at,&ft);
+ if(e) return riscos_oserror();
+ switch (ob)
+ { case osfile_IS_FILE:mode=0100000;break; /* OCTAL */
+ case osfile_IS_DIR:mode=040000;break;
+ case osfile_IS_IMAGE:mode=0140000;break;
+ default:return riscos_error("Not found");
+ }
+ if(ft!=-1) t=unixtime(ld,ex);
+ mode|=(at&7)<<6;
+ mode|=((at&112)*9)>>4;
+
+ v = PyStructSequence_New(&StatResultType);
+
+ PyStructSequence_SET_ITEM(v, 0,
+ PyInt_FromLong((long) mode)); /*st_mode*/
+ PyStructSequence_SET_ITEM(v, 1, PyInt_FromLong((long) 0)); /*st_ino*/
+ PyStructSequence_SET_ITEM(v, 2, PyInt_FromLong((long) 0)); /*st_dev*/
+ PyStructSequence_SET_ITEM(v, 3, PyInt_FromLong((long) 0)); /*st_nlink*/
+ PyStructSequence_SET_ITEM(v, 4, PyInt_FromLong((long) 0)); /*st_uid*/
+ PyStructSequence_SET_ITEM(v, 5, PyInt_FromLong((long) 0)); /*st_gid*/
+ PyStructSequence_SET_ITEM(v, 6,
+ PyInt_FromLong((long) len)); /*st_size*/
+ PyStructSequence_SET_ITEM(v, 7, PyInt_FromLong((long) t)); /*st_atime*/
+ PyStructSequence_SET_ITEM(v, 8, PyInt_FromLong((long) t)); /*st_mtime*/
+ PyStructSequence_SET_ITEM(v, 9, PyInt_FromLong((long) t)); /*st_ctime*/
+ PyStructSequence_SET_ITEM(v, 10,
+ PyInt_FromLong((long) ft)); /*file type*/
+ PyStructSequence_SET_ITEM(v, 11,
+ PyInt_FromLong((long) at)); /*attributes*/
+ PyStructSequence_SET_ITEM(v, 12,
+ PyInt_FromLong((long) ob)); /*object type*/
+
+ if (PyErr_Occurred()) {
+ Py_DECREF(v);
+ return NULL;
+ }
+
+ return v;
}
static PyObject *
riscos_chmod(PyObject *self,PyObject *args)
{
- char *path;
+ char *path;
bits mode;
bits attr;
attr=(mode&0x700)>>8;
attr|=(mode&7)<<4;
- if (!PyArg_ParseTuple(args, "si:chmod", &path,(int*)&mode)) return NULL;
- e=xosfile_write_attr(path,attr);
- if(e) return riscos_oserror();
- Py_INCREF(Py_None);
- return Py_None;
+ if (!PyArg_ParseTuple(args, "si:chmod", &path,(int*)&mode)) return NULL;
+ e=xosfile_write_attr(path,attr);
+ if(e) return riscos_oserror();
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
riscos_utime(PyObject *self, PyObject *args)
{
- char *path;
- long atime, mtime;
- PyObject* arg;
-
- if (!PyArg_ParseTuple(args, "sO:utime", &path, &arg))
- return NULL;
-
- if (arg == Py_None) {
- /* optional time values not given */
- Py_BEGIN_ALLOW_THREADS
- e=xosfile_stamp(path);
- Py_END_ALLOW_THREADS
- if(e) return riscos_oserror();
- }
- else if (!PyArg_Parse(arg, "(ll)", &atime, &mtime)) {
- PyErr_SetString(PyExc_TypeError,
- "utime() arg 2 must be a tuple (atime, mtime)");
- return NULL;
- }
- else {
- /* catalogue info*/
- fileswitch_object_type obj_type;
- bits load_addr, exec_addr;
- int size;
- fileswitch_attr attr;
-
- /* read old catalogue info */
- Py_BEGIN_ALLOW_THREADS
- e=xosfile_read_no_path(path, &obj_type, &load_addr, &exec_addr, &size, &attr);
- Py_END_ALLOW_THREADS
- if(e) return riscos_oserror();
-
- /* check if load and exec address really contain filetype and date */
- if ( (load_addr & 0xFFF00000U) != 0xFFF00000U)
- return riscos_error("can't set date for object with load and exec addresses");
-
- /* convert argument mtime to RISC OS load and exec address */
- if(acorntime(&exec_addr, &load_addr, (time_t) mtime))
- return riscos_oserror();
-
- /* write new load and exec address */
- Py_BEGIN_ALLOW_THREADS
- e = xosfile_write(path, load_addr, exec_addr, attr);
- Py_END_ALLOW_THREADS
- if(e) return riscos_oserror();
- }
-
- Py_INCREF(Py_None);
- return Py_None;
+ char *path;
+ long atime, mtime;
+ PyObject* arg;
+
+ if (!PyArg_ParseTuple(args, "sO:utime", &path, &arg))
+ return NULL;
+
+ if (arg == Py_None) {
+ /* optional time values not given */
+ Py_BEGIN_ALLOW_THREADS
+ e=xosfile_stamp(path);
+ Py_END_ALLOW_THREADS
+ if(e) return riscos_oserror();
+ }
+ else if (!PyArg_Parse(arg, "(ll)", &atime, &mtime)) {
+ PyErr_SetString(PyExc_TypeError,
+ "utime() arg 2 must be a tuple (atime, mtime)");
+ return NULL;
+ }
+ else {
+ /* catalogue info*/
+ fileswitch_object_type obj_type;
+ bits load_addr, exec_addr;
+ int size;
+ fileswitch_attr attr;
+
+ /* read old catalogue info */
+ Py_BEGIN_ALLOW_THREADS
+ e=xosfile_read_no_path(path, &obj_type, &load_addr, &exec_addr, &size, &attr);
+ Py_END_ALLOW_THREADS
+ if(e) return riscos_oserror();
+
+ /* check if load and exec address really contain filetype and date */
+ if ( (load_addr & 0xFFF00000U) != 0xFFF00000U)
+ return riscos_error("can't set date for object with load and exec addresses");
+
+ /* convert argument mtime to RISC OS load and exec address */
+ if(acorntime(&exec_addr, &load_addr, (time_t) mtime))
+ return riscos_oserror();
+
+ /* write new load and exec address */
+ Py_BEGIN_ALLOW_THREADS
+ e = xosfile_write(path, load_addr, exec_addr, attr);
+ Py_END_ALLOW_THREADS
+ if(e) return riscos_oserror();
+ }
+
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
riscos_settype(PyObject *self, PyObject *args)
{
- char *path,*name;
+ char *path,*name;
int type;
- if (!PyArg_ParseTuple(args, "si:settype", &path,&type))
- {
+ if (!PyArg_ParseTuple(args, "si:settype", &path,&type))
+ {
PyErr_Clear();
- if (!PyArg_ParseTuple(args, "ss:settype", &path,&name)) return NULL;
- e=xosfscontrol_file_type_from_string(name,(bits*)&type);
- if(e) return riscos_oserror();
- }
+ if (!PyArg_ParseTuple(args, "ss:settype", &path,&name)) return NULL;
+ e=xosfscontrol_file_type_from_string(name,(bits*)&type);
+ if(e) return riscos_oserror();
+ }
e=xosfile_set_type(path,type);
if(e) return riscos_oserror();
- Py_INCREF(Py_None);
- return Py_None;
+ Py_INCREF(Py_None);
+ return Py_None;
}
static PyObject *
@@ -368,7 +368,7 @@ riscos_getenvdict(PyObject *self, PyObject *args)
if (!dict) return NULL;
/* XXX This part ignores errors */
while(!xos_read_var_val(which,value,sizeof(value)-1,(int)context,
- os_VARTYPE_EXPANDED,&size,(int *)&context,0))
+ os_VARTYPE_EXPANDED,&size,(int *)&context,0))
{ PyObject *v;
value[size]='\0';
v = PyString_FromString(value);
@@ -381,32 +381,32 @@ riscos_getenvdict(PyObject *self, PyObject *args)
static PyMethodDef riscos_methods[] = {
- {"unlink", riscos_remove, METH_VARARGS},
+ {"unlink", riscos_remove, METH_VARARGS},
{"remove", riscos_remove, METH_VARARGS},
- {"rename", riscos_rename, METH_VARARGS},
- {"system", riscos_system, METH_VARARGS},
- {"rmdir", riscos_remove, METH_VARARGS},
- {"chdir", riscos_chdir, METH_VARARGS},
- {"getcwd", riscos_getcwd, METH_NOARGS},
- {"expand", riscos_expand, METH_VARARGS},
- {"mkdir", riscos_mkdir, METH_VARARGS},
- {"listdir", riscos_listdir, METH_VARARGS},
- {"stat", riscos_stat, METH_VARARGS},
- {"lstat", riscos_stat, METH_VARARGS},
- {"chmod", riscos_chmod, METH_VARARGS},
- {"utime", riscos_utime, METH_VARARGS},
- {"settype", riscos_settype, METH_VARARGS},
- {"getenv", riscos_getenv, METH_VARARGS},
- {"putenv", riscos_putenv, METH_VARARGS},
- {"delenv", riscos_delenv, METH_VARARGS},
- {"getenvdict", riscos_getenvdict, METH_VARARGS},
- {NULL, NULL} /* Sentinel */
+ {"rename", riscos_rename, METH_VARARGS},
+ {"system", riscos_system, METH_VARARGS},
+ {"rmdir", riscos_remove, METH_VARARGS},
+ {"chdir", riscos_chdir, METH_VARARGS},
+ {"getcwd", riscos_getcwd, METH_NOARGS},
+ {"expand", riscos_expand, METH_VARARGS},
+ {"mkdir", riscos_mkdir, METH_VARARGS},
+ {"listdir", riscos_listdir, METH_VARARGS},
+ {"stat", riscos_stat, METH_VARARGS},
+ {"lstat", riscos_stat, METH_VARARGS},
+ {"chmod", riscos_chmod, METH_VARARGS},
+ {"utime", riscos_utime, METH_VARARGS},
+ {"settype", riscos_settype, METH_VARARGS},
+ {"getenv", riscos_getenv, METH_VARARGS},
+ {"putenv", riscos_putenv, METH_VARARGS},
+ {"delenv", riscos_delenv, METH_VARARGS},
+ {"getenvdict", riscos_getenvdict, METH_VARARGS},
+ {NULL, NULL} /* Sentinel */
};
static int
ins(PyObject *module, char *symbol, long value)
{
- return PyModule_AddIntConstant(module, symbol, value);
+ return PyModule_AddIntConstant(module, symbol, value);
}
@@ -414,190 +414,190 @@ static int
all_ins(PyObject *d)
{
#ifdef F_OK
- if (ins(d, "F_OK", (long)F_OK)) return -1;
+ if (ins(d, "F_OK", (long)F_OK)) return -1;
#endif
#ifdef R_OK
- if (ins(d, "R_OK", (long)R_OK)) return -1;
+ if (ins(d, "R_OK", (long)R_OK)) return -1;
#endif
#ifdef W_OK
- if (ins(d, "W_OK", (long)W_OK)) return -1;
+ if (ins(d, "W_OK", (long)W_OK)) return -1;
#endif
#ifdef X_OK
- if (ins(d, "X_OK", (long)X_OK)) return -1;
+ if (ins(d, "X_OK", (long)X_OK)) return -1;
#endif
#ifdef NGROUPS_MAX
- if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;
+ if (ins(d, "NGROUPS_MAX", (long)NGROUPS_MAX)) return -1;
#endif
#ifdef TMP_MAX
- if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;
+ if (ins(d, "TMP_MAX", (long)TMP_MAX)) return -1;
#endif
#ifdef WCONTINUED
- if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;
+ if (ins(d, "WCONTINUED", (long)WCONTINUED)) return -1;
#endif
#ifdef WNOHANG
- if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;
+ if (ins(d, "WNOHANG", (long)WNOHANG)) return -1;
#endif
#ifdef WUNTRACED
- if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;
+ if (ins(d, "WUNTRACED", (long)WUNTRACED)) return -1;
#endif
#ifdef O_RDONLY
- if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;
+ if (ins(d, "O_RDONLY", (long)O_RDONLY)) return -1;
#endif
#ifdef O_WRONLY
- if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;
+ if (ins(d, "O_WRONLY", (long)O_WRONLY)) return -1;
#endif
#ifdef O_RDWR
- if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;
+ if (ins(d, "O_RDWR", (long)O_RDWR)) return -1;
#endif
#ifdef O_NDELAY
- if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;
+ if (ins(d, "O_NDELAY", (long)O_NDELAY)) return -1;
#endif
#ifdef O_NONBLOCK
- if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;
+ if (ins(d, "O_NONBLOCK", (long)O_NONBLOCK)) return -1;
#endif
#ifdef O_APPEND
- if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;
+ if (ins(d, "O_APPEND", (long)O_APPEND)) return -1;
#endif
#ifdef O_DSYNC
- if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;
+ if (ins(d, "O_DSYNC", (long)O_DSYNC)) return -1;
#endif
#ifdef O_RSYNC
- if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;
+ if (ins(d, "O_RSYNC", (long)O_RSYNC)) return -1;
#endif
#ifdef O_SYNC
- if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;
+ if (ins(d, "O_SYNC", (long)O_SYNC)) return -1;
#endif
#ifdef O_NOCTTY
- if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;
+ if (ins(d, "O_NOCTTY", (long)O_NOCTTY)) return -1;
#endif
#ifdef O_CREAT
- if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;
+ if (ins(d, "O_CREAT", (long)O_CREAT)) return -1;
#endif
#ifdef O_EXCL
- if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;
+ if (ins(d, "O_EXCL", (long)O_EXCL)) return -1;
#endif
#ifdef O_TRUNC
- if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;
+ if (ins(d, "O_TRUNC", (long)O_TRUNC)) return -1;
#endif
#ifdef O_BINARY
- if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;
+ if (ins(d, "O_BINARY", (long)O_BINARY)) return -1;
#endif
#ifdef O_TEXT
- if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;
+ if (ins(d, "O_TEXT", (long)O_TEXT)) return -1;
#endif
#ifdef O_LARGEFILE
- if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;
+ if (ins(d, "O_LARGEFILE", (long)O_LARGEFILE)) return -1;
#endif
/* MS Windows */
#ifdef O_NOINHERIT
- /* Don't inherit in child processes. */
- if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;
+ /* Don't inherit in child processes. */
+ if (ins(d, "O_NOINHERIT", (long)O_NOINHERIT)) return -1;
#endif
#ifdef _O_SHORT_LIVED
- /* Optimize for short life (keep in memory). */
- /* MS forgot to define this one with a non-underscore form too. */
- if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;
+ /* Optimize for short life (keep in memory). */
+ /* MS forgot to define this one with a non-underscore form too. */
+ if (ins(d, "O_SHORT_LIVED", (long)_O_SHORT_LIVED)) return -1;
#endif
#ifdef O_TEMPORARY
- /* Automatically delete when last handle is closed. */
- if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;
+ /* Automatically delete when last handle is closed. */
+ if (ins(d, "O_TEMPORARY", (long)O_TEMPORARY)) return -1;
#endif
#ifdef O_RANDOM
- /* Optimize for random access. */
- if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;
+ /* Optimize for random access. */
+ if (ins(d, "O_RANDOM", (long)O_RANDOM)) return -1;
#endif
#ifdef O_SEQUENTIAL
- /* Optimize for sequential access. */
- if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;
+ /* Optimize for sequential access. */
+ if (ins(d, "O_SEQUENTIAL", (long)O_SEQUENTIAL)) return -1;
#endif
/* GNU extensions. */
#ifdef O_DIRECT
- /* Direct disk access. */
- if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;
+ /* Direct disk access. */
+ if (ins(d, "O_DIRECT", (long)O_DIRECT)) return -1;
#endif
#ifdef O_DIRECTORY
- /* Must be a directory. */
- if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;
+ /* Must be a directory. */
+ if (ins(d, "O_DIRECTORY", (long)O_DIRECTORY)) return -1;
#endif
#ifdef O_NOFOLLOW
- /* Do not follow links. */
- if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;
+ /* Do not follow links. */
+ if (ins(d, "O_NOFOLLOW", (long)O_NOFOLLOW)) return -1;
#endif
- /* These come from sysexits.h */
+ /* These come from sysexits.h */
#ifdef EX_OK
- if (ins(d, "EX_OK", (long)EX_OK)) return -1;
+ if (ins(d, "EX_OK", (long)EX_OK)) return -1;
#endif /* EX_OK */
#ifdef EX_USAGE
- if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;
+ if (ins(d, "EX_USAGE", (long)EX_USAGE)) return -1;
#endif /* EX_USAGE */
#ifdef EX_DATAERR
- if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;
+ if (ins(d, "EX_DATAERR", (long)EX_DATAERR)) return -1;
#endif /* EX_DATAERR */
#ifdef EX_NOINPUT
- if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;
+ if (ins(d, "EX_NOINPUT", (long)EX_NOINPUT)) return -1;
#endif /* EX_NOINPUT */
#ifdef EX_NOUSER
- if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;
+ if (ins(d, "EX_NOUSER", (long)EX_NOUSER)) return -1;
#endif /* EX_NOUSER */
#ifdef EX_NOHOST
- if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;
+ if (ins(d, "EX_NOHOST", (long)EX_NOHOST)) return -1;
#endif /* EX_NOHOST */
#ifdef EX_UNAVAILABLE
- if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;
+ if (ins(d, "EX_UNAVAILABLE", (long)EX_UNAVAILABLE)) return -1;
#endif /* EX_UNAVAILABLE */
#ifdef EX_SOFTWARE
- if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;
+ if (ins(d, "EX_SOFTWARE", (long)EX_SOFTWARE)) return -1;
#endif /* EX_SOFTWARE */
#ifdef EX_OSERR
- if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;
+ if (ins(d, "EX_OSERR", (long)EX_OSERR)) return -1;
#endif /* EX_OSERR */
#ifdef EX_OSFILE
- if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;
+ if (ins(d, "EX_OSFILE", (long)EX_OSFILE)) return -1;
#endif /* EX_OSFILE */
#ifdef EX_CANTCREAT
- if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;
+ if (ins(d, "EX_CANTCREAT", (long)EX_CANTCREAT)) return -1;
#endif /* EX_CANTCREAT */
#ifdef EX_IOERR
- if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;
+ if (ins(d, "EX_IOERR", (long)EX_IOERR)) return -1;
#endif /* EX_IOERR */
#ifdef EX_TEMPFAIL
- if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;
+ if (ins(d, "EX_TEMPFAIL", (long)EX_TEMPFAIL)) return -1;
#endif /* EX_TEMPFAIL */
#ifdef EX_PROTOCOL
- if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;
+ if (ins(d, "EX_PROTOCOL", (long)EX_PROTOCOL)) return -1;
#endif /* EX_PROTOCOL */
#ifdef EX_NOPERM
- if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;
+ if (ins(d, "EX_NOPERM", (long)EX_NOPERM)) return -1;
#endif /* EX_NOPERM */
#ifdef EX_CONFIG
- if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;
+ if (ins(d, "EX_CONFIG", (long)EX_CONFIG)) return -1;
#endif /* EX_CONFIG */
#ifdef EX_NOTFOUND
- if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
+ if (ins(d, "EX_NOTFOUND", (long)EX_NOTFOUND)) return -1;
#endif /* EX_NOTFOUND */
- return 0;
+ return 0;
}
void
initriscos()
{
- PyObject *m, *d, *stat_m;
+ PyObject *m, *d, *stat_m;
- m = Py_InitModule("riscos", riscos_methods);
+ m = Py_InitModule("riscos", riscos_methods);
- if (all_ins(m))
- return;
+ if (all_ins(m))
+ return;
- d = PyModule_GetDict(m);
+ d = PyModule_GetDict(m);
- Py_INCREF(PyExc_OSError);
- PyModule_AddObject(m, "error", PyExc_OSError);
+ Py_INCREF(PyExc_OSError);
+ PyModule_AddObject(m, "error", PyExc_OSError);
- PyStructSequence_InitType(&StatResultType, &stat_result_desc);
- PyDict_SetItemString(d, "stat_result", (PyObject*) &StatResultType);
+ PyStructSequence_InitType(&StatResultType, &stat_result_desc);
+ PyDict_SetItemString(d, "stat_result", (PyObject*) &StatResultType);
}
diff --git a/RISCOS/Python/dynload_riscos.c b/RISCOS/Python/dynload_riscos.c
index 6b87f2d..8ecb29d 100644
--- a/RISCOS/Python/dynload_riscos.c
+++ b/RISCOS/Python/dynload_riscos.c
@@ -39,8 +39,8 @@ PERFORMANCE OF THIS SOFTWARE.
const struct filedescr _PyImport_DynLoadFiletab[] = {
- {"/pyd", "rb", C_EXTENSION},
- {0, 0}
+ {"/pyd", "rb", C_EXTENSION},
+ {0, 0}
};
void dynload_init_dummy()
@@ -48,16 +48,16 @@ void dynload_init_dummy()
}
dl_funcptr _PyImport_GetDynLoadFunc(const char *fqname, const char *shortname,
- char *pathname, FILE *fp)
+ char *pathname, FILE *fp)
{
- int err;
- char errstr[256];
- void (*init_function)(void);
-
- err = dlk_load_no_init(pathname, &init_function);
- if (err) {
- PyOS_snprintf(errstr, sizeof(errstr), "dlk failure %d", err);
- PyErr_SetString(PyExc_ImportError, errstr);
- }
- return init_function;
+ int err;
+ char errstr[256];
+ void (*init_function)(void);
+
+ err = dlk_load_no_init(pathname, &init_function);
+ if (err) {
+ PyOS_snprintf(errstr, sizeof(errstr), "dlk failure %d", err);
+ PyErr_SetString(PyExc_ImportError, errstr);
+ }
+ return init_function;
}
diff --git a/RISCOS/sleep.c b/RISCOS/sleep.c
index c85eb86..ffdff81 100644
--- a/RISCOS/sleep.c
+++ b/RISCOS/sleep.c
@@ -9,33 +9,33 @@
int riscos_sleep(double delay)
{
- os_t starttime, endtime, time; /* monotonic times (centiseconds) */
- int *pollword, ret;
- osbool claimed;
+ os_t starttime, endtime, time; /* monotonic times (centiseconds) */
+ int *pollword, ret;
+ osbool claimed;
- /* calculate end time */
- starttime = os_read_monotonic_time();
- if (starttime + 100.0*delay >INT_MAX)
- endtime = INT_MAX;
- else
- endtime = (os_t)(starttime + 100.0*delay);
+ /* calculate end time */
+ starttime = os_read_monotonic_time();
+ if (starttime + 100.0*delay >INT_MAX)
+ endtime = INT_MAX;
+ else
+ endtime = (os_t)(starttime + 100.0*delay);
- /* allocate (in RMA) and set pollword for xupcall_sleep */
- pollword = osmodule_alloc(4);
- *pollword = 1;
+ /* allocate (in RMA) and set pollword for xupcall_sleep */
+ pollword = osmodule_alloc(4);
+ *pollword = 1;
- time = starttime;
- ret = 0;
- while ( time<endtime && time>=starttime ) {
- xupcall_sleep (pollword, &claimed);
- if (PyErr_CheckSignals()) {
- ret = 1;
- break;
- }
- time = os_read_monotonic_time();
- }
+ time = starttime;
+ ret = 0;
+ while ( time<endtime && time>=starttime ) {
+ xupcall_sleep (pollword, &claimed);
+ if (PyErr_CheckSignals()) {
+ ret = 1;
+ break;
+ }
+ time = os_read_monotonic_time();
+ }
- /* deallocate pollword */
- osmodule_free(pollword);
- return ret;
+ /* deallocate pollword */
+ osmodule_free(pollword);
+ return ret;
}
diff --git a/Tools/msi/msisupport.c b/Tools/msi/msisupport.c
index f60a356..1fd2ee4 100644
--- a/Tools/msi/msisupport.c
+++ b/Tools/msi/msisupport.c
@@ -7,13 +7,13 @@
*/
static UINT debug(MSIHANDLE hInstall, LPCSTR msg)
{
- MSIHANDLE hRec = MsiCreateRecord(1);
- if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) {
- return ERROR_INSTALL_FAILURE;
- }
- MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec);
- MsiCloseHandle(hRec);
- return ERROR_SUCCESS;
+ MSIHANDLE hRec = MsiCreateRecord(1);
+ if (!hRec || MsiRecordSetStringA(hRec, 1, msg) != ERROR_SUCCESS) {
+ return ERROR_INSTALL_FAILURE;
+ }
+ MsiProcessMessage(hInstall, INSTALLMESSAGE_INFO, hRec);
+ MsiCloseHandle(hRec);
+ return ERROR_SUCCESS;
}
/* Check whether the TARGETDIR exists and is a directory.
@@ -22,27 +22,27 @@ static UINT debug(MSIHANDLE hInstall, LPCSTR msg)
UINT __declspec(dllexport) __stdcall CheckDir(MSIHANDLE hInstall)
{
#define PSIZE 1024
- WCHAR wpath[PSIZE];
- char path[PSIZE];
- UINT result;
- DWORD size = PSIZE;
- DWORD attributes;
+ WCHAR wpath[PSIZE];
+ char path[PSIZE];
+ UINT result;
+ DWORD size = PSIZE;
+ DWORD attributes;
-
- result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size);
- if (result != ERROR_SUCCESS)
- return result;
- wpath[size] = L'\0';
- path[size] = L'\0';
- attributes = GetFileAttributesW(wpath);
- if (attributes == INVALID_FILE_ATTRIBUTES ||
- !(attributes & FILE_ATTRIBUTE_DIRECTORY))
- {
- return MsiSetPropertyA(hInstall, "TargetExists", "0");
- } else {
- return MsiSetPropertyA(hInstall, "TargetExists", "1");
- }
+ result = MsiGetPropertyW(hInstall, L"TARGETDIR", wpath, &size);
+ if (result != ERROR_SUCCESS)
+ return result;
+ wpath[size] = L'\0';
+ path[size] = L'\0';
+
+ attributes = GetFileAttributesW(wpath);
+ if (attributes == INVALID_FILE_ATTRIBUTES ||
+ !(attributes & FILE_ATTRIBUTE_DIRECTORY))
+ {
+ return MsiSetPropertyA(hInstall, "TargetExists", "0");
+ } else {
+ return MsiSetPropertyA(hInstall, "TargetExists", "1");
+ }
}
/* Update the state of the REGISTRY.tcl component according to the
@@ -51,41 +51,41 @@ UINT __declspec(dllexport) __stdcall CheckDir(MSIHANDLE hInstall)
*/
UINT __declspec(dllexport) __stdcall UpdateEditIDLE(MSIHANDLE hInstall)
{
- INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new;
- UINT result;
+ INSTALLSTATE ext_old, ext_new, tcl_old, tcl_new, reg_new;
+ UINT result;
- result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new);
- if (result != ERROR_SUCCESS)
- return result;
- result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new);
- if (result != ERROR_SUCCESS)
- return result;
+ result = MsiGetFeatureStateA(hInstall, "Extensions", &ext_old, &ext_new);
+ if (result != ERROR_SUCCESS)
+ return result;
+ result = MsiGetFeatureStateA(hInstall, "TclTk", &tcl_old, &tcl_new);
+ if (result != ERROR_SUCCESS)
+ return result;
- /* If the current state is Absent, and the user did not select
- the feature in the UI, Installer apparently sets the "selected"
- state to unknown. Update it to the current value, then. */
- if (ext_new == INSTALLSTATE_UNKNOWN)
- ext_new = ext_old;
- if (tcl_new == INSTALLSTATE_UNKNOWN)
- tcl_new = tcl_old;
+ /* If the current state is Absent, and the user did not select
+ the feature in the UI, Installer apparently sets the "selected"
+ state to unknown. Update it to the current value, then. */
+ if (ext_new == INSTALLSTATE_UNKNOWN)
+ ext_new = ext_old;
+ if (tcl_new == INSTALLSTATE_UNKNOWN)
+ tcl_new = tcl_old;
- // XXX consider current state of REGISTRY.tcl?
- if (((tcl_new == INSTALLSTATE_LOCAL) ||
- (tcl_new == INSTALLSTATE_SOURCE) ||
- (tcl_new == INSTALLSTATE_DEFAULT)) &&
- ((ext_new == INSTALLSTATE_LOCAL) ||
- (ext_new == INSTALLSTATE_SOURCE) ||
- (ext_new == INSTALLSTATE_DEFAULT))) {
- reg_new = INSTALLSTATE_SOURCE;
- } else {
- reg_new = INSTALLSTATE_ABSENT;
- }
- result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new);
- return result;
+ // XXX consider current state of REGISTRY.tcl?
+ if (((tcl_new == INSTALLSTATE_LOCAL) ||
+ (tcl_new == INSTALLSTATE_SOURCE) ||
+ (tcl_new == INSTALLSTATE_DEFAULT)) &&
+ ((ext_new == INSTALLSTATE_LOCAL) ||
+ (ext_new == INSTALLSTATE_SOURCE) ||
+ (ext_new == INSTALLSTATE_DEFAULT))) {
+ reg_new = INSTALLSTATE_SOURCE;
+ } else {
+ reg_new = INSTALLSTATE_ABSENT;
+ }
+ result = MsiSetComponentStateA(hInstall, "REGISTRY.tcl", reg_new);
+ return result;
}
-BOOL APIENTRY DllMain(HANDLE hModule,
- DWORD ul_reason_for_call,
+BOOL APIENTRY DllMain(HANDLE hModule,
+ DWORD ul_reason_for_call,
LPVOID lpReserved)
{
return TRUE;